Dyna: Learning, Planning & Acting
One loop for real and simulated experience.
Sutton's Dyna architecture makes planning look like learning: transitions drawn from a learned model go through exactly the same update rule as real ones. That single idea turns each real step into dozens of useful updates. This lesson builds Dyna-Q, measures what planning buys, breaks it with a world that changes, and asks which simulated transitions are worth the computation.
What you’ll learn
- Write Dyna-Q and name the four processes of the Dyna architecture: acting, direct RL, model learning and planning with search control.
- Show that one-step learning moves reward information back one state per episode, and compute how uniform and prioritized planning change that.
- Explain why an environment that gets worse corrects the model by itself while one that gets better does not, and motivate the Dyna-Q+ bonus .
- Compare search-control strategies: uniform replay, prioritized sweeping, expected versus sample updates, and trajectory sampling.
- Relate Dyna to experience replay and to deep model-based methods, and say when a parametric model can hurt.
One loop for real and simulated experience
In the Dyna architecture (Sutton, 1990) real experience is used twice. Direct RL improves the value function or policy from each real transition, as any model-free method would. Model learning improves a model of the environment from the same transition. The model then produces simulated experience, and planning applies the same learning rule to it. A fourth process, search control, decides which states and actions to simulate from.
Models come in two kinds. A distribution model returns the probabilities and expected reward ; a sample model returns one draw of . Dyna-Q uses the simplest sample model there is: a table that remembers, for every pair tried, the last reward and next state observed. It is exact in a deterministic world and wrong in a stochastic one, where counting outcomes and sampling from the maximum-likelihood estimate is the natural upgrade.
import random
from collections import defaultdict
def dyna_q(env, n_planning, episodes, alpha=0.1, gamma=0.95, eps=0.1):
Q = defaultdict(float) # Q[(s, a)], all zero at the start
model = {} # model[(s, a)] = (r, s2, terminal), last outcome seen
A = range(env.action_space.n)
greedy = lambda s: max(A, key=lambda a: (Q[(s, a)], random.random())) # random tie-breaks
def update(s, a, r, s2, terminal): # one rule for real and simulated steps
target = r if terminal else r + gamma * max(Q[(s2, b)] for b in A)
Q[(s, a)] += alpha * (target - Q[(s, a)])
for _ in range(episodes):
s, _ = env.reset()
done = False
while not done:
a = env.action_space.sample() if random.random() < eps else greedy(s)
s2, r, terminated, truncated, _ = env.step(a)
update(s, a, r, s2, terminated) # direct RL
model[(s, a)] = (r, s2, terminated) # model learning
keys = list(model)
for _ in range(n_planning): # planning, with uniform search control
ps, pa = random.choice(keys)
update(ps, pa, *model[(ps, pa)])
s, done = s2, terminated or truncated
return QTabular Dyna-Q for a Gymnasium environment with discrete states. With n_planning = 0 it is Q-learning. Bootstrapping stops only at true termination, not at a time-limit truncation. Each real step now costs updates of cost each.
What does unlimited planning converge to? With a maximum-likelihood model and enough planning updates, Dyna's values approach the optimal values of the estimated MDP, the certainty-equivalence answer, which batch TD also reaches for prediction (TD vs Monte Carlo: Certainty Equivalence). Planning cannot extract more than the model contains; it removes the computational bottleneck, not the statistical one.
What planning buys
Why does planning help so much in a maze? Because one-step learning moves information slowly. The cleanest case is a corridor, where everything can be computed exactly.
A corridor of states with one action that moves right; entering the goal from state pays 1 and every other reward is 0. Start from and use , which is safe in a deterministic world. Q-learning updates the pairs in the order it visits them, so when it updates state in episode , the value of state is still the one from episode :
Unroll the recursion from . After episodes exactly the last states know anything, so the start state learns only in episode : the reward travels one state per episode.
Now plan. After one episode the model holds all transitions. With uniform search control the "frontier" of correct values moves back one state only when the planner happens to pick the transition right behind it, probability per update. Each of the advances therefore takes updates on average:
Updating in backward order, which is what prioritized sweeping produces, needs one update per state. Same model, same update rule, a factor of less computation: which transitions are simulated matters as much as how many.
A corridor of states has been walked once, so the model holds all 20 transitions and only the last state's value is nonzero. With uniform random planning updates (), how many planning updates are expected before the start state's value becomes nonzero?
Show the answer
380
Nineteen advances of the frontier, each waiting on average updates for the one useful transition: . Backward-ordered updates would need 19. With 50 planning updates per real step, 380 updates take fewer than 8 real steps. A maze model holds many more transitions than one path, so planning needs more updates there, but the same arithmetic explains why Dyna with spreads the goal's value far back during its second episode.
When the world changes
A model learned yesterday describes yesterday's world. Two of Sutton & Barto's mazes change partway through a run. In the blocking maze the short route is walled off and a longer one opens. In the shortcut maze the long route stays open and a shorter one appears.
The two cases are not symmetric. When the world gets worse, the model is optimistic: it still predicts the blocked route, the greedy policy walks into the wall, and the real transition corrects the model. Errors of this kind are self-correcting because acting on them produces exactly the experience that refutes them. When the world gets better, the model is pessimistic: it has no record of the opening, the greedy policy never goes near it, and nothing ever contradicts the model. Finding the shortcut by -greedy exploration needs a whole sequence of exploratory moves in a row, the deep exploration problem.
A Dyna-Q agent has learned a maze well. Which change can it fail to adapt to indefinitely, even while it keeps exploring with ?
- Its best route is blocked by a new wall
- A reward it relied on is removed
- A new, shorter route opens far from its current path
- The goal pays more than before
Show the answer
C. A new, shorter route opens far from its current path
Changes along the current route show up in real experience at once and correct the model. A new opening off the route is invisible to the greedy policy, and reaching it by -greedy exploration needs a long run of lucky exploratory moves. Dyna-Q+ makes the model itself say "go and check".
Which transitions to simulate
The corridor showed that uniform search control wastes most updates: once the model is learned, most simulated transitions lead to states whose values have not changed, so updating them changes nothing. Prioritized sweeping (Moore & Atkeson, 1993; Peng & Williams, 1993) works backward from change instead. It keeps a priority queue of pairs whose values would move a lot, updates the most urgent one, and then queues the predecessors of its state, since their targets just changed.
PRIORITIZED-SWEEPING(n, θ): # deterministic model, as in Dyna-Q
after each real transition (S, A, R, S′):
Model(S, A) ← (R, S′); record (S, A) as a predecessor of S′
p ← |R + γ · max_a Q(S′, a) − Q(S, A)|
if p > θ: insert (S, A) into PQueue with priority p
repeat at most n times while PQueue is not empty:
(s, a) ← pop the pair with the highest priority
(r, s′) ← Model(s, a)
Q(s, a) ← Q(s, a) + α · (r + γ · max_b Q(s′, b) − Q(s, a))
for each predecessor (s̄, ā) of s, with modeled reward r̄:
p ← |r̄ + γ · max_b Q(s, b) − Q(s̄, ā)|
if p > θ: insert (s̄, ā) with priority p (keep the larger if already queued)In the corridor this is exactly the backward sweep: updates instead of about . In stochastic problems the priorities use the model's expected next value, and the threshold stops the queue from filling with negligible changes.
Take one pair with equally likely successors whose values are fixed. An expected update computes their mean exactly, at the cost of evaluations:
A sample update with step size holds the running average of sampled successors. It is unbiased at every budget, and its error falls like one over the square root of the computation spent:
Compare at equal cost. With and a budget of 100 evaluations the expected update cannot even finish, while 100 samples already cut the error to . Sampling wins when branching is large and computation scarce, all the more because in planning the successor values are themselves still improving, so many cheap updates spread improvements sooner than a few exact ones (Sutton & Barto, §8.5). When is small, an expected update costs little and removes the sampling noise entirely.
Search control can also follow the agent's own policy: simulate whole trajectories in the model from start states and update the pairs met along the way. In Sutton & Barto's experiments on randomly generated tasks (§8.6), sampling from this on-policy distribution sped up planning early on, most clearly in large problems with small branching factors, because it ignores states the policy never reaches; but it slowed the final convergence, since rarely visited states are rarely updated. Real-time dynamic programming takes this to the extreme: asynchronous value iteration on the states of simulated greedy trajectories (Asynchronous & Prioritized Dynamic Programming).
| Search control | What it simulates | Strength | Weakness |
|---|---|---|---|
| Uniform (Dyna-Q) | Random remembered pairs | Simple; touches everything eventually | Wastes most updates once few values are changing |
| Prioritized sweeping | Pairs whose values would change most, then their predecessors | Moves changes backward fast | Needs predecessor lists; priorities are heuristic under noise |
| Trajectory sampling | Pairs along simulated trajectories of the current policy | Focuses on states that matter now | Neglects rarely visited states |
| Expected vs sample | The whole successor distribution, or one draw | Exact, or cheap | Cost per update, or noise |
Dyna at scale: replay, linear models and deep models
Tables do not scale, but the Dyna loop does. Sutton, Szepesvári, Geramifard and Bowling (2008) made the model linear in the features: it predicts the expected next feature vector and the expected reward as linear functions of the current features, and planning applies TD updates to these imagined feature transitions. They proved that, under natural conditions, linear Dyna-style planning converges to a unique solution independent of the distribution the planning features are drawn from (for policy evaluation, the least-squares TD solution), and extended prioritized sweeping to the linear case.
Experience replay is Dyna with a non-parametric model: it stores real transitions and replays them, so it can only reproduce what actually happened. van Hasselt, Hessel and Aslanides (2019) argued that replay therefore already captures much of the benefit of a model, and backed it up on Atari with 100,000 interactions: a data-efficient variant of Rainbow that simply replayed more matched the model-based SimPLe after 70,000 interactions, was roughly 25% better at 100,000, and came out ahead on 17 of 26 games.
Deep model-based RL keeps Dyna's shape. MBPO (Janner et al., 2019) trains an ensemble of neural network models and generates short rollouts branched from states in the replay buffer, which a model-free learner (soft actor–critic) trains on. Dreamer learns its model in a latent space and trains an actor–critic entirely on imagined rollouts (World Models: Learning in Imagination). In every case the questions of this lesson return: how far to roll out, from where, and how much to trust what the model says.
Key takeaways
- Dyna uses real experience twice, for direct RL and for model learning, and plans by applying the same update to simulated transitions; with zero planning steps Dyna-Q is Q-learning.
- One-step learning moves reward back one state per episode along a path; planning moves it without new experience, about uniform updates or well-ordered ones in a corridor of length .
- A world that gets worse corrects an optimistic model through action, but one that gets better leaves a pessimistic model unchallenged; Dyna-Q+ adds to stale transitions in planning so the agent retests them.
- Search control matters as much as the amount of planning: prioritized sweeping works backward from changes, sample updates beat expected ones when branching is large, and trajectory sampling focuses on states the policy reaches.
- Experience replay is Dyna with a non-parametric model and captures much of the benefit; a parametric model can generalize, but planning forward from real states with it can corrupt their values.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A state–action pair has 1,000 equally likely successor states. Your planner can afford only 100 successor evaluations for it right now. What should it do?
- Start an expected update and stop after the first 100 of its 1,000 terms
- Skip the pair until it can afford the full expected update
- Make 100 sample updates, leaving an error of about , where is the spread of the successor values
- Make a single sample update and save the rest of the budget
Show the answer
C. Make 100 sample updates, leaving an error of about , where is the spread of the successor values
An expected update is exact only when complete. Sample averages are unbiased at every budget, with error , so 100 samples give . With large branching factors and limited computation, sample updates win.
Dyna-Q runs planning updates after every real step. Compared with Q-learning, what does it spend and what does it save?
- It spends real experience to save computation
- It spends about 51 times the computation per real step to save real experience
- It spends nothing extra: planning updates are free
- It spends memory but needs exactly as many real episodes
Show the answer
B. It spends about 51 times the computation per real step to save real experience
Each real step triggers one real and 50 simulated updates. The payoff is in real experience: reward information spreads through the model's remembered transitions without new episodes, so far fewer real steps are needed.
What does Dyna-Q+'s bonus change?
- Planning makes long-untried transitions look attractive, so the greedy policy goes back to test them
- The real rewards the agent receives
- The step size of the updates
- The model's predictions of next states
Show the answer
A. Planning makes long-untried transitions look attractive, so the greedy policy goes back to test them
The bonus is added only in planning updates. Planning propagates it, so states leading toward stale transitions look valuable and the agent travels there on purpose. That is how it discovers the shortcut that plain Dyna-Q never sees.
In the corridor analysis, why does backward-ordered planning need only updates while uniform planning needs about ?
- Backward updates use a larger step size
- Uniform planning computes the wrong values
- Uniform planning ignores the model
- Only the update just behind the frontier of known values makes progress, and backward order always picks it
Show the answer
D. Only the update just behind the frontier of known values makes progress, and backward order always picks it
An update helps only if its next state already has a nonzero value. Uniform selection finds that one useful transition with probability per update, so most updates are wasted; backward order never wastes one. Prioritized sweeping generalizes this ordering to any MDP.
Dyna-Q's model stores only the last observed for each pair. What goes wrong in a stochastic environment?
- Nothing: the last outcome is an unbiased estimate of the expected next value
- Planning keeps replaying one arbitrary outcome as if it were certain, so values chase whichever outcome happened last
- The algorithm stops converging even in deterministic environments
- The step size must be set to 1
Show the answer
B. Planning keeps replaying one arbitrary outcome as if it were certain, so values chase whichever outcome happened last
One stored outcome is a sample, but planning replays that same sample over and over between visits, which is very different from averaging fresh samples. Counting outcomes and sampling from , or doing expected updates with , fixes it.
Go deeper
- Model Errors & Value-Equivalent Models · Compounding errors, the simulation lemma, and models that only need to get values right.
- When to Trust a Model: MBPO · Short branched rollouts and a bound on model-based policy improvement.
- Uncertainty-Aware Models: PILCO & PETS · Gaussian processes, probabilistic ensembles and planning under model uncertainty.
Further reading
- R. S. Sutton, "Integrated architectures for learning, planning, and reacting based on approximating dynamic programming," Proceedings of the 7th International Conference on Machine Learning (1990).
- R. S. Sutton & A. G. Barto, Reinforcement Learning: An Introduction, ch. 8 (MIT Press, 2nd ed., 2018).
- A. W. Moore & C. G. Atkeson, "Prioritized sweeping: reinforcement learning with less data and less time," Machine Learning 13 (1993).
- H. van Hasselt, M. Hessel & J. Aslanides, "When to use parametric models in reinforcement learning?," NeurIPS (2019).