Overview
Suppose you walk a maze and find the exit after hundreds of steps. Plain Q-learning learns one thing from that: the last step was good. It needs to walk the maze again and again for that news to travel back to the start. Dyna keeps a record of every move it has made and what happened. After each real step it replays some remembered moves in its head and updates their values as if they had just happened. The news of the exit spreads backward through the table within one or two episodes. Planning and learning are the same update, one fed by the world and the other by the record.
A short history
Richard Sutton introduced the Dyna architecture in papers from 1990 and 1991. At the time, learning from trial and error and planning with a model were treated as separate fields. Dyna showed they could share one value function: every real step both updates the values and improves a model, and the model then supplies extra simulated steps. Dyna is a name, not an acronym. The idea of training on model-generated experience returns in modern methods such as MBPO and World Models.
How it works
actpicks an action for the current state: random with probabilityepsilon, otherwise the one with the highest Q value, with ties broken at random.- The environment returns a reward and a next state.
observeapplies one Q-learning update from this real transition (direct learning). observethen stores the outcome in the model: the table entry for this state and action now holds the reward, next state and done flag just seen (model learning).plandrawsplanning_stepsremembered pairs uniformly at random, looks up what the model says happened, and applies the same Q-learning update to each (planning).- With
kappaabove zero (Dyna-Q+), planning adds a bonus to the reward that grows with the time since the pair was last tried in the real world. learnrepeats this for a number of episodes and returns how many real steps each one took.
Watch out for
- The model stores only the last outcome of each pair. In an environment with random outcomes it remembers one sample as if it were certain, and planning repeats that mistake many times.
- If the world changes, the model stays wrong until the agent happens to retry the affected pair. Plain Dyna-Q can miss a newly opened shortcut for a very long time.
- Planning multiplies computing cost: each real step triggers
planning_stepsextra updates. The gain is in real steps saved, not in total computation. - Uniform sampling spends most planning updates on pairs whose values would not change. This is why few steps help little right after the first reward is found.
- This is the tabular method with an exact table model. It does not scale to large or continuous state spaces, where the model must be learned and will have errors.
Use cases
When to use it
Use it when real steps are costly and the state space is small enough for a table, or to see clearly that planning and learning are one update applied to simulated and real experience.
In industry
- Research and teaching
- Maze examples where a few planning updates per real step cut the number of real episodes needed many times over.
- Robotics
- Small navigation tasks where each real move costs time or wear, so replaying remembered transitions is far cheaper than moving again.
- Operations
- Tabular decision problems with slow real feedback, where a remembered model lets the agent keep learning between observations.
Choosing it: what must hold
- A small number of discrete states and actions, since both the values and the model are tables.
- An environment that is deterministic or nearly so, or a model that stores outcome counts.
- Real steps that cost much more than computation, which is what makes planning updates worth it.
When to choose something else
| If | Use instead |
|---|---|
| States are continuous or high-dimensional | MBPO, which uses the same idea with neural network models |
| Real steps are cheap | Tabular Q-learning without a model |
| The environment changes over time, so the remembered model goes stale | A variant with an exploration bonus such as Dyna-Q+, or plain Q-learning |
Math foundations
The Q-learning update
Move the estimate a fraction toward the target: the reward plus the discounted value of the best action in the next state. When ends the episode the target is just .
Model learning
After every real step the table remembers what that action did in that state. For a deterministic environment one visit is enough for the entry to be exact.
A planning update
Pick a remembered pair, read the model's answer, and apply the Q-learning update above to it. Nothing here touches the real environment.
Updates per real step
One update from the real transition plus planned ones. With this is plain Q-learning. Larger extracts more from each real step.
Dyna-Q+ exploration bonus
In planning only, a pair that has not been tried for real steps looks more rewarding than the model says. The agent is drawn back to recheck old knowledge, which is how it notices that the world has changed.
Symbols
- estimated value of taking action a in state s
- state, action, reward and next state of one transition
- step size of the Q-learning update
- discount factor
- the remembered outcome of action a in state s
- planning updates per real step (planning_steps)
- weight of the Dyna-Q+ bonus
- real steps since the pair was last tried
- reward used in a Dyna-Q+ planning update
Worked by hand
All Q values start at zero, and . The agent moved from state to state with reward 0, then from to the goal with reward 1. Planning then happens to draw the remembered step from .
State now has a positive value without the agent visiting it again. Plain Q-learning would have left it at zero until the next real pass through .
Visual example
Loading the example.
Try this
- Drag n to 0: after the same 700 real steps, only the cell beside the goal has learned anything.
- Drag n to 50 and see the values reach the start from the same real experience.
- Press Start over, then Finish the episode twice: the first episode takes 468 real steps for any n, the second depends on n.
- Click the boxes of the loop to read what the model remembers and which memories were just replayed.
Code sample
from impl import DynaQ, MazeEnv
from config import DynaConfig
env = MazeEnv() # Sutton and Barto's Dyna maze
agent = DynaQ(DynaConfig(planning_steps=20), env.n_states, env.n_actions)
steps = agent.learn(env, n_episodes=30) # real steps taken in each episode
print(steps[0], steps[-1], len(agent.greedy_path(env)) - 1) # long first episode, then about 14 stepsRead the implementation (168 lines)
"""Dyna-Q: tabular Q-learning plus planning updates replayed from a learned table model. Includes Dyna-Q+.
NumPy only. `MazeEnv` is a small grid maze so the folder runs on its own.
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import DynaConfig
except ImportError: # run from the template's own folder
from config import DynaConfig
# S start, G goal, # wall, . free
DYNA_MAZE = (
".......#G",
"..#....#.",
"S.#....#.",
"..#......",
".....#...",
".........",
)
SHORTCUT_MAZE_BEFORE = (
"........G",
".........",
".........",
".########",
".........",
"...S.....",
)
SHORTCUT_MAZE_AFTER = (
"........G",
".........",
".........",
".#######.",
".........",
"...S.....",
)
class MazeEnv:
"""Deterministic grid maze. Actions: 0 up, 1 down, 2 left, 3 right. Reward 1 on reaching G, else 0.
A move into a wall or off the grid leaves the agent where it is. States are integers row * n_cols + col.
"""
n_actions = 4
_moves = ((-1, 0), (1, 0), (0, -1), (0, 1))
def __init__(self, layout: tuple = DYNA_MAZE) -> None:
self.set_layout(layout)
self.state = self.start
def set_layout(self, layout: tuple) -> None:
"""Swap the maze (walls, start and goal); used to change the world in the middle of learning."""
self.layout = tuple(layout)
self.n_rows, self.n_cols = len(layout), len(layout[0])
self.n_states = self.n_rows * self.n_cols
cells = {ch: (r, c) for r, row in enumerate(layout) for c, ch in enumerate(row) if ch in "SG"}
self.start = cells["S"][0] * self.n_cols + cells["S"][1]
self.goal = cells["G"][0] * self.n_cols + cells["G"][1]
def reset(self) -> int:
self.state = self.start
return self.state
def peek(self, state: int, action: int) -> tuple[int, float, bool]:
"""What `action` does in `state`, without moving the agent: (next_state, reward, done)."""
r, c = divmod(state, self.n_cols)
dr, dc = self._moves[action]
nr, nc = r + dr, c + dc
if 0 <= nr < self.n_rows and 0 <= nc < self.n_cols and self.layout[nr][nc] != "#":
r, c = nr, nc
nxt = r * self.n_cols + c
return nxt, float(nxt == self.goal), nxt == self.goal
def step(self, action: int) -> tuple[int, float, bool]:
"""Move the agent. Returns (next_state, reward, done)."""
self.state, reward, done = self.peek(self.state, int(action))
return self.state, reward, done
class DynaQ:
"""Tabular Dyna-Q agent (Dyna-Q+ when `kappa > 0`)."""
def __init__(self, config: DynaConfig | None, n_states: int, n_actions: int) -> None:
self.config = config or DynaConfig()
self.n_states, self.n_actions = n_states, n_actions
self.q = np.zeros((n_states, n_actions))
self.model: dict[tuple[int, int], tuple[float, int, bool]] = {} # (s, a) -> (reward, next_state, done)
self._keys: list[tuple[int, int]] = [] # model keys in insertion order, for O(1) random draws
self.last_tried: dict[tuple[int, int], int] = {} # (s, a) -> real time step it was last taken
self.time = 0 # real steps taken so far
self.n_updates = 0 # Q updates applied so far, real and planned
self.rng = np.random.default_rng(self.config.seed)
def act(self, state: int, greedy: bool = False) -> int:
"""Epsilon-greedy action for `state`; ties between best actions are broken at random."""
if not greedy and self.rng.random() < self.config.epsilon:
return int(self.rng.integers(self.n_actions))
row = self.q[state]
best = np.flatnonzero(row == row.max())
return int(best[0]) if greedy else int(self.rng.choice(best))
def _q_update(self, s: int, a: int, r: float, s2: int, done: bool) -> None:
target = r + (0.0 if done else self.config.gamma * self.q[s2].max())
self.q[s, a] += self.config.alpha * (target - self.q[s, a])
self.n_updates += 1
def _remember(self, key: tuple[int, int], outcome: tuple[float, int, bool]) -> None:
if key not in self.model:
self._keys.append(key)
self.model[key] = outcome
def observe(self, s: int, a: int, r: float, s2: int, done: bool) -> None:
"""Learn from one real transition: direct RL update, model update, then planning."""
self.time += 1
self._q_update(s, a, r, s2, done)
if self.config.kappa > 0:
# Dyna-Q+: actions never tried in a visited state are modelled as "stay here, reward 0" so that
# planning can consider them too
for b in range(self.n_actions):
if (s, b) not in self.model:
self._remember((s, b), (0.0, s, False))
self.last_tried[(s, b)] = 0
self._remember((s, a), (r, s2, done))
self.last_tried[(s, a)] = self.time
self.plan(self.config.planning_steps)
def plan(self, n: int) -> None:
"""Apply `n` Q-learning updates to transitions drawn uniformly from the model."""
for _ in range(n):
s, a = self._keys[int(self.rng.integers(len(self._keys)))]
r, s2, done = self.model[(s, a)]
if self.config.kappa > 0:
r += self.config.kappa * math.sqrt(self.time - self.last_tried[(s, a)])
self._q_update(s, a, r, s2, done)
def run_episode(self, env, max_steps: int | None = None) -> tuple[int, float]:
"""Run and learn from one episode. Returns (real steps taken, sum of rewards)."""
limit = max_steps or self.config.max_episode_steps
s, total = env.reset(), 0.0
for t in range(1, limit + 1):
a = self.act(s)
s2, r, done = env.step(a)
self.observe(s, a, r, s2, done)
total += r
s = s2
if done:
break
return t, total
def learn(self, env, n_episodes: int) -> list[int]:
"""Run `n_episodes` learning episodes and return the number of real steps each one took."""
return [self.run_episode(env)[0] for _ in range(n_episodes)]
def greedy_path(self, env, max_steps: int = 500) -> list[int]:
"""States visited when following the greedy policy from the start, without learning."""
s = env.reset()
path = [s]
for _ in range(max_steps):
s, _, done = env.step(self.act(s, greedy=True))
path.append(s)
if done:
break
return path- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 9, run with
python3 -m unittest -v
Practice
Create MazeEnv() and train three agents, DynaQ(DynaConfig(planning_steps=n), env.n_states, env.n_actions) with of 0, 5 and 50, calling learn(env, n_episodes=30) on each. Plot the steps per episode for all three and compare len(agent.greedy_path(env)) - 1 with the shortest route of 14 steps. Compare agent.n_updates too.
Check on learning
- During the very first episode, before the goal has been found, planning has almost no effect. Why, and when exactly does it start to matter?
A way to think about it
All rewards seen so far are zero and all Q values are zero. Work out the result of a planning update in that situation.
- An agent with 50 planning steps solves the maze in far fewer real steps than one with none. Is it a better algorithm, or only a different way of paying the cost?
A way to think about it
Compare real steps and total Q updates for both. Then decide which of the two is expensive in the problem you care about.
- A wall is removed, opening a shorter path. Dyna-Q with a small epsilon keeps using the old route. Why does its model not show the new path, and how does the Dyna-Q+ bonus fix this?
A way to think about it
The model changes only for pairs the agent actually tries. Ask which moves the greedy policy stopped trying long ago.
- What would happen to the learned values if the environment gave a reward of 1 at the goal only half of the time, at random?
A way to think about it
The model keeps the most recent outcome. Consider what the planning updates see during a stretch when the last stored outcome was 0.
- Uniform sampling of remembered pairs is wasteful just after the first reward is found. Which pairs would you update first, and why?
A way to think about it
Only pairs that lead into a state whose value just changed can change themselves. Think about working backward from the goal.