Simple Algorithm
Reinforcement Learning · Bootstrapping · 22 min

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 κτ\kappa\sqrt\tau.
  • 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 P^(s′∣s,a)\hat P(s'\mid s,a) and expected reward r^(s,a)\hat r(s,a); a sample model returns one draw of (r,s′)(r,s'). 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 P^(s′∣s,a)=N(s,a,s′)/N(s,a)\hat P(s'\mid s,a)=N(s,a,s')/N(s,a) is the natural upgrade.

Q(s,a) ← Q(s,a)+α[ r+γmax⁡a′Q(s′,a′)−Q(s,a) ]Q(s,a)\ \leftarrow\ Q(s,a)+\alpha\Big[\,r+\gamma\max_{a'}Q(s',a')-Q(s,a)\,\Big]
The one update of Dyna-Q, applied to real transitions (St,At,Rt+1,St+1)(S_t,A_t,R_{t+1},S_{t+1}) and to simulated ones (s,a,r^,s^′)(s,a,\hat r,\hat s') alike. Planning is learning from imagined data.
python
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 Q

Tabular 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 1+n1+n updates of cost O(∣A∣)\order{|\mathcal A|} 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.

DerivationHow fast reward travels: learning versus planning
  1. Qk(L)=1,Qk(j)=γ Qk−1(j+1)(j<L)Q_k(L)=1,\qquad Q_k(j)=\gamma\,Q_{k-1}(j+1)\quad(j<L)

    A corridor of states 1,…,L1,\dots,L with one action that moves right; entering the goal from state LL pays 1 and every other reward is 0. Start from Q≡0Q\equiv0 and use α=1\alpha=1, which is safe in a deterministic world. Q-learning updates the pairs in the order it visits them, so when it updates state jj in episode kk, the value of state j+1j+1 is still the one from episode k−1k-1:

  2. Qk(j)={γ L−jj≥L−k+10otherwiseQ_k(j)=\begin{cases}\gamma^{\,L-j} & j\ge L-k+1\\ 0 & \text{otherwise}\end{cases}

    Unroll the recursion from Q0≡0Q_0\equiv0. After kk episodes exactly the last kk states know anything, so the start state learns only in episode LL: the reward travels one state per episode.

  3. E[#planning updates until the start state learns]=(L−1) L\E\big[\#\text{planning updates until the start state learns}\big]=(L-1)\,L

    Now plan. After one episode the model holds all LL 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 1/L1/L per update. Each of the L−1L-1 advances therefore takes LL updates on average:

  4. L−1updates (backward order)vsL(L−1)(uniform)L-1\quad\text{updates (backward order)}\qquad\text{vs}\qquad L(L-1)\quad\text{(uniform)}

    Updating in backward order, which is what prioritized sweeping produces, needs one update per state. Same model, same update rule, a factor of LL less computation: which transitions are simulated matters as much as how many.

Predict before you look

A corridor of L=20L=20 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 (α=1\alpha=1), 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 L=20L=20 updates for the one useful transition: 19×20=38019\times20=380. 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 n=50n=50 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 ε\varepsilon-greedy exploration needs a whole sequence of exploratory moves in a row, the deep exploration problem.

r~(s,a)=r^(s,a)+κτ(s,a)\tilde r(s,a)=\hat r(s,a)+\kappa\sqrt{\tau(s,a)}
Dyna-Q+. In planning updates, a pair last tried τ\tau real steps ago is credited with a bonus that grows with τ\tau. Planning then carries the bonus back to the current state, so the greedy policy itself sets out to retest stale transitions. Actions never tried from a visited state are also allowed in planning, modeled as leading back to the same state with reward 0.
Check your understanding

A Dyna-Q agent has learned a maze well. Which change can it fail to adapt to indefinitely, even while it keeps exploring with ε=0.1\varepsilon=0.1?

  1. Its best route is blocked by a new wall
  2. A reward it relied on is removed
  3. A new, shorter route opens far from its current path
  4. 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 ε\varepsilon-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.

text
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: L−1L-1 updates instead of about L2L^2. In stochastic problems the priorities use the model's expected next value, and the threshold θ\theta stops the queue from filling with negligible changes.

DerivationExpected versus sample updates
  1. vˉ=1b∑i=1bV(si′),cost b,error 0\bar v=\frac1b\sum_{i=1}^{b}V(s'_i),\qquad\text{cost }b,\quad\text{error }0

    Take one pair (s,a)(s,a) with bb equally likely successors whose values V(s1′),…,V(sb′)V(s'_1),\dots,V(s'_b) are fixed. An expected update computes their mean exactly, at the cost of bb evaluations:

  2. v^t=1t∑j=1tV(Sj′),E[(v^t−vˉ)2]=σt,σ2=1b∑i=1b(V(si′)−vˉ)2\hat v_t=\frac1t\sum_{j=1}^{t}V(S'_j),\qquad\sqrt{\E\big[(\hat v_t-\bar v)^2\big]}=\frac{\sigma}{\sqrt t},\qquad\sigma^2=\frac1b\sum_{i=1}^{b}\big(V(s'_i)-\bar v\big)^2

    A sample update with step size 1/t1/t holds the running average of tt sampled successors. It is unbiased at every budget, and its error falls like one over the square root of the computation spent:

  3. Compare at equal cost. With b=1000b=1000 and a budget of 100 evaluations the expected update cannot even finish, while 100 samples already cut the error to σ/10\sigma/10. 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 bb 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 controlWhat it simulatesStrengthWeakness
Uniform (Dyna-Q)Random remembered pairsSimple; touches everything eventuallyWastes most updates once few values are changing
Prioritized sweepingPairs whose values would change most, then their predecessorsMoves changes backward fastNeeds predecessor lists; priorities are heuristic under noise
Trajectory samplingPairs along simulated trajectories of the current policyFocuses on states that matter nowNeglects rarely visited states
Expected vs sampleThe whole successor distribution, or one drawExact, or cheapCost bb per update, or noise σ/t\sigma/\sqrt t

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 L(L−1)L(L-1) uniform updates or L−1L-1 well-ordered ones in a corridor of length LL.
  • A world that gets worse corrects an optimistic model through action, but one that gets better leaves a pessimistic model unchallenged; Dyna-Q+ adds κτ\kappa\sqrt\tau 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.

Question 1

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?

  1. Start an expected update and stop after the first 100 of its 1,000 terms
  2. Skip the pair until it can afford the full expected update
  3. Make 100 sample updates, leaving an error of about σ/10\sigma/10, where σ\sigma is the spread of the successor values
  4. 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 σ/10\sigma/10, where σ\sigma is the spread of the successor values

An expected update is exact only when complete. Sample averages are unbiased at every budget, with error σ/t\sigma/\sqrt t, so 100 samples give σ/10\sigma/10. With large branching factors and limited computation, sample updates win.

Question 2

Dyna-Q runs n=50n=50 planning updates after every real step. Compared with Q-learning, what does it spend and what does it save?

  1. It spends real experience to save computation
  2. It spends about 51 times the computation per real step to save real experience
  3. It spends nothing extra: planning updates are free
  4. 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.

Question 3

What does Dyna-Q+'s bonus κτ(s,a)\kappa\sqrt{\tau(s,a)} change?

  1. Planning makes long-untried transitions look attractive, so the greedy policy goes back to test them
  2. The real rewards the agent receives
  3. The step size of the updates
  4. 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.

Question 4

In the corridor analysis, why does backward-ordered planning need only L−1L-1 updates while uniform planning needs about L(L−1)L(L-1)?

  1. Backward updates use a larger step size
  2. Uniform planning computes the wrong values
  3. Uniform planning ignores the model
  4. 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 1/L1/L per update, so most updates are wasted; backward order never wastes one. Prioritized sweeping generalizes this ordering to any MDP.

Question 5

Dyna-Q's model stores only the last observed (r,s′)(r,s') for each pair. What goes wrong in a stochastic environment?

  1. Nothing: the last outcome is an unbiased estimate of the expected next value
  2. Planning keeps replaying one arbitrary outcome as if it were certain, so values chase whichever outcome happened last
  3. The algorithm stops converging even in deterministic environments
  4. 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 P^(s′∣s,a)=N(s,a,s′)/N(s,a)\hat P(s'\mid s,a)=N(s,a,s')/N(s,a), or doing expected updates with P^\hat P, fixes it.

Go deeper

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).