Part I · Foundations of Sequential Decision-Making
7.Unifying Learning & Planning: n-step, Traces, Dyna & MCTS
“Planning and learning are deeply related. Both involve estimating value functions by backing up updates; the difference is only whether the experience is real or simulated.”
Chapter 6 left a false dichotomy: Monte Carlo waits for the whole return, TD(0) uses one step. This chapter puts a continuous dial between them — the λ-return blends every n-step return at once, and eligibility traces make that blend computable online with one update per step. Then a second unification: if a robot can learn a model from experience, it can plan with it exactly as in Chapter 5 while still learning as in Chapter 6. Dyna is that architecture, and it is the intellectual ancestor of every model-based method in Chapter 12.
Foundation
n-step returns and the error-reduction property, the λ-return, forward/backward equivalence proved, accumulating traces, Dyna-Q and Dyna-Q+, prioritized sweeping, and UCT.
Conceptual
The λ dial: drag it from 0 to 1 and watch weight slide from the one-step return onto the full return, with the trace decaying along Rusty's corridor beside it.
Practical
Sarsa(λ) with traces, Dyna-Q(+) composed from Chapter 6's learner, and prioritized sweeping on a binary heap.
After this chapter you can
- Write the n-step return and state the error-reduction property that justifies intermediate n
- Define the λ-return and prove the forward and backward views are equivalent offline
- Implement eligibility traces and explain what the trace vector physically represents
- Build Dyna-Q and explain why planning steps buy sample efficiency at the cost of model bias
- Explain how Dyna-Q+ detects a world that has changed underneath a stale model
- Describe MCTS as decision-time planning, and name the two substitutions AlphaZero makes
7.1 The space between one step and all of them
Rusty delivers a package and receives . Which of the forty decisions that got him there deserves credit?
TD(0) credits exactly one: the state immediately before the reward. The state two steps back learns nothing this episode — it must wait until its successor's value improves, then inherit a little. Monte Carlo credits all forty at once, but every one of them absorbs the noise of the entire trajectory.
The -step return interpolates by looking ahead steps before bootstrapping:
At this is the TD target; at (or the episode end) it is the Monte Carlo return. The update is the usual one, .
Intermediate is not a compromise — it is usually strictly better than either extreme, and there is a theorem saying why.
Theorem 7.1— Error-reduction property of n-step returns
For any value function ,
The expected -step return is a better estimate of than itself, by a factor . Larger contracts the bias faster — while adding the variance of extra sampled rewards. That is the whole trade, and it has no universal optimum.
7.2 The λ-return: averaging all of them
Rather than choosing one , average them all, with geometrically decaying weights:
The factor normalizes the weights to sum to one. At only the term survives — TD(0). At all the weight slides onto the full return — Monte Carlo. In between, a smooth blend.
The λ dial: from TD(0) to Monte Carlo
ch07-lambda-dialGλ = (1−λ) Σₙ λⁿ⁻¹ Gₜ:ₜ₊ₙ — a geometric blend of every n-step return at once.
Eligibility along Rusty's corridor
One TD error updates every shaded cell in proportion to its trace — the backward view.
Effective lookahead
3.3 steps
mean n under the λ-weighting
Trace half-life
1.7 steps
how far back credit reaches
Drag the dial and watch both panels. On the left, the weight distribution over -step returns; on the right, the eligibility trace decaying backwards along the corridor Rusty just drove. Those are two views of the same number.
7.3 Forward and backward views
The definition above is the forward view: to update you look ahead over future returns. It is conceptually clean and computationally useless online — you would have to wait for the episode to finish.
The backward view achieves the same thing causally. Maintain an eligibility trace for every state, decaying by each step and incremented when the state is visited:
Then at every step, compute the one-step TD error and apply it to every state in proportion to its trace:
The trace is a short-term memory of who is responsible for what happens now. A cell visited recently has a large trace and receives most of the credit; a cell visited long ago has a small one.
Theorem 7.2— Forward–backward equivalence (offline)
If updates are accumulated and applied at the end of an episode, the total update made by the backward view with accumulating traces equals the total update prescribed by the forward view using -returns.
▸Proof
Unroll the trace at time for a state first visited at time : . The total backward update to over the episode is therefore
Now take the forward view. Chapter 6's exercise established that the MC error decomposes as a discounted sum of TD errors; the same telescoping applied to the -return gives
The two expressions are identical, so the accumulated updates agree.
The equivalence is exact only offline, because online updates change mid-episode and the two views then diverge slightly. True online TD(λ) repairs this at modest extra cost.
7.4 Dyna: planning with a learned model
Now the second unification. Chapter 5 planned with a given model; Chapter 6 learned with no model. Dyna does both: learn a model from real experience, then use it to generate simulated experience and learn from that too.
The architecture is small enough to state completely. After each real transition :
- Direct RL — apply a Q-learning update from the real transition.
- Model learning — store .
- Planning — repeat times: sample a previously-seen , look up the model's prediction, and apply the same Q-learning update to that imagined transition.
The planning updates are indistinguishable from real ones as far as the learner is concerned. That is the insight in the epigraph: planning and learning differ only in where the experience comes from.
The payoff is sample efficiency, which for a robot is the currency that matters. With planning steps per real step, Dyna-Q typically reaches good policies in an order of magnitude fewer real interactions than Q-learning — because each expensive real transition is mined fifty times.
Prioritized sweeping improves on uniform sampling of imagined transitions. Instead of picking at random, maintain a priority queue ordered by the magnitude of the change a backup would produce, and always work on the largest. When a state's value changes, all its predecessors are enqueued with priority proportional to the change. Computation flows to where it matters, and the speedup over uniform Dyna is often an order of magnitude.
use std::collections::HashMap;
use rl_core::Transition;
use crate::td::QLearning;
pub struct DynaQPlus {
learner: QLearning,
model: HashMap<(usize, usize), (f64, usize)>,
/// Steps since each (s, a) was tried for real — drives the bonus.
last_tried: HashMap<(usize, usize), u64>,
planning_steps: usize,
kappa: f64,
step: u64,
}
impl DynaQPlus {
pub fn observe<R: rand::Rng>(&mut self, s: usize, a: usize, t: &Transition<usize>, rng: &mut R) {
self.step += 1;
// 1. Direct RL from real experience.
self.learner.update(s, a, t);
// 2. Model learning.
self.model.insert((s, a), (t.reward, t.next_state));
self.last_tried.insert((s, a), self.step);
// 3. Planning — the same update, on remembered transitions.
let keys: Vec<_> = self.model.keys().copied().collect();
for _ in 0..self.planning_steps {
let &(ps, pa) = &keys[rng.gen_range(0..keys.len())];
let (reward, next) = self.model[&(ps, pa)];
// Dyna-Q+ bonus: reward staleness, so the agent re-checks old beliefs.
let tau = (self.step - self.last_tried[&(ps, pa)]) as f64;
let imagined = Transition {
next_state: next,
reward: reward + self.kappa * tau.sqrt(),
done: false,
};
self.learner.update(ps, pa, &imagined);
}
}
}7.5 Decision-time planning and MCTS
Everything so far uses planning to improve a stored policy — Sutton and Barto call this background planning. There is another use: plan at the moment of decision, for the state you are actually in, then throw the computation away.
Monte Carlo tree search is the canonical method. From the current state, repeat four steps:
- Selection — descend the tree using a rule that balances exploitation and exploration. The standard is UCT, which is Chapter 3's UCB applied at each node: .
- Expansion — add a child node for an untried action.
- Simulation — roll out to a terminal state with a cheap default policy.
- Backpropagation — propagate the outcome up the path, updating and .
Given enough iterations, UCT converges to the optimal action at the root. The tree grows asymmetrically, concentrating depth along promising lines — which is exactly how you would want a finite computation budget spent.
For robots, decision-time planning is most familiar as model predictive control: at each control step, optimize a short action sequence against a model, execute the first action, discard the rest, and re-plan. Chapter 12 derives it properly and Chapter 13 gives it its classical-control context.
7.6 Chapter bridge
Part I is complete, and it is worth naming what has been assembled.
We have a formalism (Chapter 4), an exact planning method for when the model is known (Chapter 5), sampling methods for when it is not (Chapter 6), a continuous dial between one-step and full-return credit assignment (this chapter), and an architecture that learns a model and plans with it while continuing to learn (also this chapter). All of it is unified by generalized policy iteration and underwritten by the contraction mathematics of Chapter 2.
All of it also assumes tables. Every method here stores one number per state or per state–action pair, and Chapter 5's arithmetic already showed that a modest robot arm has more states than a sweep can touch before the sun burns out.
Part II abandons tables. We will represent value functions and policies as parameterized functions — linear in features, then deep networks — and discover that the guarantees do not survive the transition intact. Chapter 8 begins with what breaks, because knowing precisely how approximation can diverge is what makes the engineering of Chapters 9 through 12 comprehensible rather than superstitious.
- 01Foundation●●●Prove the error-reduction property
Prove Theorem 7.1. Then explain why it does NOT imply that larger n is always better in practice — what does the theorem measure, and what does it ignore?
- 02Foundation●●●λ-weights sum to one
Verify that (1−λ)Σ_{n≥1} λ^{n−1} = 1, and work out what the weights become when an episode terminates at step T. Why must the remaining weight go onto the full return?
- 03Foundation●●●The equivalence, in full
Reproduce the proof of Theorem 7.2, justifying the telescoping step explicitly. Then construct a small example where online updating makes the forward and backward views differ, and quantify the discrepancy.
- 04Foundation●●●Effective lookahead
Show that the mean n under the λ-weighting is 1/(1−λ), and interpret this as an effective lookahead horizon. Compare with the effective horizon 1/(1−γ) from Chapter 4 — what does the product γλ mean?
- 05Conceptual●●●The two extremes
In the λ dial, set λ = 0 and λ = 1 and describe precisely what each does to the trace along the corridor. Then find the λ at which the trace half-life is about five steps, at γ = 0.95.
- 06Practical●●●Sarsa(λ) with traces
Implement Sarsa(λ) with accumulating traces and sweep λ ∈ {0, 0.5, 0.9, 0.95, 0.99} on Rusty’s warehouse. Plot episodes-to-threshold against λ. The curve should be U-shaped — explain both arms.
- 07Practical●●●The blocking maze
Build a maze whose optimal corridor is blocked halfway through training. Run Dyna-Q and Dyna-Q+ across the change. Measure how many episodes each needs to recover, and tune κ to trade recovery speed against steady-state performance.
- 08Practical●●●Prioritized sweeping
Implement prioritized sweeping with a binary heap and compare total backups to convergence against uniform Dyna-Q at equal planning budgets. Report the speedup, and identify what problem structure makes the advantage largest.
References
Baseline references
- Sutton, R. S. & Barto, A. G. (2018). Reinforcement Learning: An Introduction. MIT Press, 2nd editionChapter 7 (n-step bootstrapping), Chapter 12 (eligibility traces, forward and backward views, true online TD(λ)), and Chapter 8 (Dyna, prioritized sweeping, MCTS).
- Kober, J., Bagnell, J. A. & Peters, J. (2013). Reinforcement Learning in Robotics: A Survey. International Journal of Robotics Research 32(11)§6 mental rehearsal — the robotics case for planning with learned models, developed fully in Chapter 12.
Further reading & modern sources
- Sutton, R. S. (1990). Integrated architectures for learning, planning, and reacting based on approximating dynamic programming. ICML 1990The Dyna architecture, in the original.
- Moore, A. W. & Atkeson, C. G. (1993). Prioritized sweeping: Reinforcement learning with less data and less time. Machine Learning 13The priority-queue idea of §7.4.
- van Seijen, H. & Sutton, R. S. (2014). True Online TD(λ). ICML 2014Repairs the online gap in the forward–backward equivalence exactly, rather than approximately.
- Kocsis, L. & Szepesvári, C. (2006). Bandit based Monte-Carlo Planning. ECML 2006UCT — Chapter 3’s UCB applied inside a search tree, with the consistency proof.
- Silver, D. et al. (2018). A general reinforcement learning algorithm that masters chess, shogi, and Go through self-play. Science 362(6419)AlphaZero — the two substitutions described in §7.5, and search as a policy improvement operator.
