Chapter 8
Planning and Learning with Tabular Methods
Dynamic programming needs a model of the environment, and Monte Carlo and TD learning do not. Up to now this has been presented as the line that separates two families: model-based methods, which plan, and model-free methods, which learn. This chapter argues that the line is thin. Both kinds of method compute value functions, and both do it by backing values up along possible trajectories. They differ in where the trajectories come from: a model or the world. Once this is seen, a learning rule can be used as a planner just by feeding it simulated experience, and planning, acting and learning can run together in one agent. The previous chapters joined Monte Carlo and TD learning through the -step methods of Chapter 7; this one joins both to dynamic programming. The second half of the chapter is about where to spend computation: which states to update, in which order, with which kind of update, and whether to plan in the background or at the moment of decision. That last question leads to Monte Carlo Tree Search and, beyond the book, to the learned-model search of AlphaZero and MuZero.
8.1Models and Planning#
A model is anything the agent can use to predict how the environment will respond to an action. There are two kinds. A distribution model returns all possible next states and rewards with their probabilities, . This is what dynamic programming (Chapter 4) assumes. A sample model returns one outcome, drawn with those probabilities. A distribution model can always produce samples, but the converse is often far easier to build. Think of the time a delivery takes through a city. A simulator that draws traffic at every junction and adds up the delays takes an afternoon to write. The exact distribution of the total time is a convolution over every route and every traffic state, and nobody would want to write it down.
Either kind of model can generate simulated experience: single transitions, whole episodes, or, for a distribution model, all episodes with their probabilities. Planning is any computation that takes a model as input and produces or improves a policy. Here, as in Sutton and Barto, planning means state-space planning: a search through states, with values attached to states or state–action pairs.The alternative, plan-space planning, searches the space of plans themselves, as partial-order planners in classical AI do. It does not fit stochastic sequential decision problems well, and Sutton and Barto set it aside. The unifying view of this chapter rests on two observations. First, state-space planning methods compute value functions as an intermediate step toward a better policy. Second, they compute them with backups applied to simulated experience, so the pipeline is: model, simulated experience, backups, values, policy.
Dynamic programming fits this pipeline. It sweeps the states, asks the distribution model for all transitions out of each state, and uses them in an expected backup. Learning fits it as well, with real experience in place of simulated experience. So a learning rule becomes a planning rule as soon as it is fed with the output of a model.
Algorithm 8.1 (Random-sample One-step Tabular Q-planning). Input: a sample model. Parameters: step size . Initialization: arbitrary.
Repeat forever:
- Select a state and an action at random.
- Ask the sample model for a next reward and next state .
- Apply one-step Q-learning to the simulated transition: .
Q-planning converges to the optimal action values of the model under the same conditions that make Q-learning converge in the world: every pair chosen infinitely often in step 1, and step sizes decreasing appropriately (Theorem A.7). The convergence proof of Q-learning never asks whether a transition is real.
8.2Dyna: Planning, Acting and Learning Together#
An agent that plans while it interacts with the world can use real experience in two ways. It can improve the model so that it matches the world better (model learning). It can also improve the value function and policy directly, with the learning methods of the previous chapters (direct reinforcement learning). Improving the policy through the model is called indirect reinforcement learning. The indirect route squeezes more out of each real transition. The direct route is simpler and does not inherit the model’s mistakes. Sutton and Barto refuse to choose between them.Richard S. Sutton and Andrew G. Barto. Reinforcement Learning: An Introduction. Adaptive Computation and Machine Learning. MIT Press, Cambridge, MA, second edition, 2018. ISBN 978-0-262-03924-6. URL http://incompleteideas.net/book/the-book-2nd.html Their Dyna architecture runs both at once, together with acting and model learning, and uses the same update rule for real and simulated experience.Richard S. Sutton. Integrated Architectures for Learning, Planning, and Reacting Based on Approximating Dynamic Programming. In Machine Learning Proceedings 1990: Proceedings of the Seventh International Conference on Machine Learning, pages 216–224. Morgan Kaufmann, San Francisco, CA, 1990. ISBN 978-1-55860-141-3. doi: 10.1016/B978-1-55860-141-3.50030-4 The learning rule is the “final common path” of learning and planning. What remains is search control, the process that decides which states and actions the simulated experiences start from.
Algorithm 8.2 (Tabular Dyna-Q). Parameters: step size , small , number of planning updates per real step. Initialization: arbitrary and empty for all .
Repeat forever:
- current nonterminal state.
- -greedy.
- Take action ; observe reward and next state .
- Direct RL: .
- Model learning: (the environment is assumed deterministic).
- Planning: repeat times:
- a random previously observed state; a random action previously taken in ;
- ;
- .
Without steps 5 and 6 this is Q-learning (Algorithm 6.7). Planning only queries pairs that have actually been tried, so the model never has to answer a question it knows nothing about. Sutton and Barto’s test is a -state maze with and reward only on reaching the goal. The non-planning agent () needs about episodes to settle on a near-optimal path, the agent with about , and with only . The reason is clear from the backups. After the first episode, Q-learning knows the value of one transition only, the one into the goal, and each later episode pushes this knowledge back by one more step. With planning, the model already contains every transition seen in the first episode. During the second episode, planning updates replay those transitions and spread the goal’s value backwards, while the agent is still wandering near the start. Planning is incremental and can stop at any time, so the agent is always ready to act and always planning in the background.
8.3When the Model Is Wrong#
A model can be wrong because the environment is stochastic and has been sampled too little, because function approximation has generalized badly, or because the world has changed. Errors in the two directions behave very differently. An optimistic model promises more reward than the world gives. The planned policy goes to collect it, finds that it is not there, and the model is corrected: the error is self-revealing. Sutton and Barto’s blocking maze, in which the short path is closed after steps and a long one opened, shows a Dyna-Q agent recovering in this way after a flat period. A pessimistic error, where the world has become better than the model thinks, may never be discovered. In the shortcut maze a shorter path opens after steps. Dyna-Q’s model says that there is no shortcut. The more it plans, the more firmly its policy avoids the region, and -greedy exploration is far too weak to stumble on a path that needs several exploratory steps in a row.
This is the exploration–exploitation conflict of Chapter 2 again. Here exploring means trying actions that would improve the model. **Dyna-Q+** uses a simple heuristic. For each pair it records how many real steps have passed since the pair was last tried. In planning updates it pretends that the modeled reward comes with a bonus that grows with that time:
(8.1)Because the bonus enters the planning updates rather than only the choice of action, it propagates. States from which a long-untested pair can be reached also gain value, so the agent will carry out multi-step excursions to test the model. Sutton and Barto’s Dyna-Q+ also lets planning consider actions never tried in a state, modeled as leading back to the same state with reward . How long must a pair go untested before the bonus outweighs a known alternative? Take an untested self-loop whose planned value is that of collecting the bonus forever, , competing with an action of value .
Solve , squared to , for . The waiting time grows quadratically with the value at stake and shrinks quadratically with .const retestTime = await show`Factor[\[Tau] /. First[Solve[\[Kappa]^2 \[Tau] == (1 - \[Gamma])^2 v^2, \[Tau]]]]`Better paths are therefore tested at a rate that depends on how much is at stake. The tests cost real reward, but in a world that changes that cost is often well spent (Exercise 8.10).
8.4Prioritized Sweeping#
Dyna-Q chooses the pairs for its planning updates uniformly at random. In the maze, early in the second episode, that is almost always wasted: all values but one are zero, and a backup from a zero-valued state to a zero-valued state changes nothing. The useful updates are those into states whose values have just changed. After each of them, the predecessors of the updated state become useful in turn. Working backward from changes in this way is backward focusing. The order of the updates matters a great deal. On a chain of four states ending in a reward of , a single sweep of exact backups () in backward order computes every value, while the same sweep in forward order learns only the last one.
One sweep of one-step backups (and ) on a four-state chain, starting from zeros: first in the order , then in the order .const chainSweep = await wl`Function[{order}, Fold[Function[{v, s}, ReplacePart[v, s -> If[s == 4, 1, \[Gamma] v[[s + 1]]]]], {0, 0, 0, 0}, order]]`
const sweepOrders = await show`{${chainSweep}[{4, 3, 2, 1}], ${chainSweep}[{1, 2, 3, 4}]}`Uniform random selection among pairs needs on average draws for each useful update along a chain of length , that is updates in all, against in the right order. Prioritized sweeping finds a good order automatically.Andrew W. Moore and Christopher G. Atkeson. Prioritized Sweeping: Reinforcement Learning with Less Data and Less Time. Machine Learning, 13(1):103–130, 1993. doi: 10.1007/BF00993104; and Jing Peng and Ronald J. Williams. Efficient Learning and Planning Within the Dyna Framework. Adaptive Behavior, 1(4):437–454, 1993. doi: 10.1177/105971239300100403 It keeps a priority queue of pairs whose value would change by more than a threshold if updated, ranked by the size of that change. It always updates the top pair and then re-examines that pair’s predecessors.
Algorithm 8.3 (Prioritized Sweeping, Deterministic Environment). Parameters: , threshold , planning updates per step. Initialization: and for all ; empty.
Repeat forever:
- current nonterminal state; policy; take , observe .
- .
- ; if , insert into with priority .
- Repeat times while is not empty:
- the pair of highest priority, removed from the queue; ;
- ;
- for every predicted to lead to , with predicted reward : ; if , insert with priority (keeping only the higher priority if it is already queued).
On mazes like the one above, prioritized sweeping finds optimal solutions with 5 to 10 times fewer updates than Dyna-Q, and the advantage grows with the size of the grid.Jing Peng and Ronald J. Williams. Efficient Learning and Planning Within the Dyna Framework. Adaptive Behavior, 1(4):437–454, 1993. doi: 10.1177/105971239300100403 Moore and Atkeson used it to steer a rod through obstacles in a space of states, a problem too large for unfocused planning.Andrew W. Moore and Christopher G. Atkeson. Prioritized Sweeping: Reinforcement Learning with Less Data and Less Time. Machine Learning, 13(1):103–130, 1993. doi: 10.1007/BF00993104 In stochastic environments the model keeps transition counts, and the natural update becomes an expected update over all successors. This exposes a weakness. An expected update spends as much computation on rare successors as on likely ones. The next section shows that sample updates can be the better buy. Small backups take the idea to its limit: an update along a single transition that uses its probability instead of sampling it.Harm van Seijen and Richard S. Sutton. Planning by Prioritized Sweeping with Small Backups. In Sanjoy Dasgupta and David McAllester, editors, Proceedings of the 30th International Conference on Machine Learning (ICML 2013), volume 28 of Proceedings of Machine Learning Research, pages 361–369, Atlanta, Georgia, USA, 2013. PMLR. URL https://proceedings.mlr.press/v28/vanseijen13.html
8.5Expected versus Sample Updates#
The one-step updates of Part I vary along three binary dimensions. They estimate state values or action values. They estimate the values of a given policy or optimal values. And they are expected updates, which average over all possible next events, or sample updates, which use one sampled event. Seven of the eight combinations are familiar algorithms:
| expected (needs a distribution model) | sample (one transition) | |
|---|---|---|
| policy evaluation | TD(0) | |
| value iteration | — | |
| -policy evaluation | Sarsa | |
| -value iteration | Q-learning |
(The sample version of would need the maximum over actions inside the expectation over next states, and a single sample cannot provide it.) For and an estimated model , the two updates of a pair are
(8.2)where in the sample update .
With a deterministic environment they coincide (for ). Otherwise the expected update is exact up to the errors of the successors’ values, and the sample update adds sampling error. But the expected update costs about times as much, where the branching factor is the number of successors with . The fair question is therefore not which update is better, but what a fixed amount of computation buys.
Consider the idealized case analyzed by Sutton and Barto. The successors are equally likely, their values are correct, and the target is their mean . Sample updates with make the estimate after updates equal to the average of sampled values. Normalize the spread of the successor values so that .
Proposition 8.4 (Error of Sample Updates). Let be the variance of a single sampled successor value. After sample updates with , the root-mean-square error of the estimate is
(8.3)Proof. The estimate is the average of the sampled values. It is unbiased, because each is uniform over the , so its mean squared error is its variance. With independent draws, the variance is . Without replacement, still holds, but distinct draws are negatively correlated. Writing and ,
so . This is the finite-population correction. Substituting gives . □
8.5.1In Wolfram Language#
In terms of the power sums : the covariance of two draws without replacement divided by , and the variance of the -sample mean divided by . The second is times the finite-population correction .const popVar = await wl`Subscript[S, 2]/b - (Subscript[S, 1]/b)^2`
const covWo = await wl`(Subscript[S, 1]^2 - Subscript[S, 2])/(b (b - 1)) - (Subscript[S, 1]/b)^2`
const fpc = await show`Simplify[{${covWo}/${popVar}, (t ${popVar} + t (t - 1) ${covWo})/t^2/${popVar}}]`const succVals = await wl`Array[Subscript[x, #] &, 4]`
const sampleVar = await wl`Total[(${succVals} - Mean[${succVals}])^2]/3`
const sqErr = await wl`Function[{idx}, (Mean[${succVals}[[idx]]] - Mean[${succVals}])^2]`
const enumCheck = await show`Simplify[{Mean[${sqErr} /@ Tuples[Range[4], 2]] - ${sampleVar} (4 - 1)/(4*2), Mean[${sqErr} /@ Permutations[Range[4], {2}]] - ${sampleVar} (4 - 2)/(4*2)}]`Figure 8.1 draws (8.3) against computation, measured in units of one expected update, so that sample updates cost . The expected update does nothing useful until it has finished, and then it is exact. The sample updates are useful at once. For large , a small fraction of the cost of one expected update already removes most of the error. For , ten samples () leave an RMS error of about . The without-replacement curve makes the comparison fair at the end as well: it reaches zero exactly when it has seen every successor, at the cost of one expected update.
In a real problem the advantage of sampling is probably larger. The successor values are themselves estimates being improved, and cheap sample updates make them accurate sooner, so everything backed up from them improves too. For large stochastic branching factors and more states than can be solved exactly, sample updates are likely to win (Exercise 8.9 looks at non-uniform successors).
8.6Trajectory Sampling#
Which states should planning update? Dynamic programming sweeps the whole state space, giving every state equal time. In a large problem most states are irrelevant, reached only under bad policies or with negligible probability, and a single sweep may not even be affordable. The alternative is to sample states from a distribution. Uniform sampling has the same defect as a sweep. The on-policy distribution , the distribution of states visited while following the current policy, focuses on the states that matter now, and it is easy to sample from: simulate trajectories with the model and the current policy, and update the states along the way. This is trajectory sampling. It is hard to think of another efficient way to sample from , which is rarely known explicitly and changes with every change of policy.
Is it a good distribution? Sutton and Barto test it on random tasks with expected updates in both conditions: two actions per state, equally likely successors, and a chance of terminating on every transition. On-policy focusing makes planning much faster at first and somewhat slower in the long run. The early gain is larger and lasts longer when is small and the state space is large. For states and the advantage is large and long-lasting. The explanation is natural. Early on, the states near the start matter most, and on-policy sampling concentrates on them. Later those states are already correct, and updating them again is wasted, while a sweep still does useful work elsewhere. For large problems in which the policy visits a small part of the space, on-policy focusing is a large win. In Part II it gains a further, decisive advantage: with function approximation, it is the distribution under which semi-gradient methods are stable (Chapter 9).
8.7Real-time Dynamic Programming#
Real-time dynamic programming (RTDP) is value iteration with on-policy trajectory sampling. It follows real or simulated trajectories, always acting greedily with respect to the current values, and applies the expected value-iteration update to the states it visits:
(8.4)It is an asynchronous DP algorithm (Section 4.7): states are updated in the order in which trajectories visit them, using whatever values their successors happen to have. For prediction, a fixed policy never reaches some states from the start states, and those states can be ignored. For control, we need an optimal partial policy, optimal on the relevant states, those reachable from some start state under some optimal policy. In general, finding one still requires visiting every state–action pair infinitely often, for example with exploring starts. RTDP’s interesting property is that in a natural class of problems it does not.
Theorem 8.5 (Barto, Bradtke and Singh, 1995). Consider an undiscounted episodic task with absorbing goal states that yield zero reward. Suppose that (1) every goal state has initial value ; (2) there is a policy that reaches a goal with probability one from every start state; (3) every reward on transitions from non-goal states is strictly negative; and (4) every initial value is at least its optimal value, (for instance ). If each episode starts in a random start state and RTDP acts greedily (breaking ties randomly), then with probability one it converges to a policy that is optimal on all relevant states, without necessarily visiting the other states infinitely often, or even at all.
Proof. We sketch the argument of Barto, Bradtke and Singh, who combine asynchronous DP with Korf’s analysis of learning real-time A*.Andrew G. Barto, Steven J. Bradtke, and Satinder P. Singh. Learning to Act Using Real-Time Dynamic Programming. Artificial Intelligence, 72(1–2):81–138, 1995. doi: 10.1016/0004-3702(94)00011-O; and Richard E. Korf. Real-Time Heuristic Search. Artificial Intelligence, 42(2–3):189–211, 1990. doi: 10.1016/0004-3702(90)90054-4 The Bellman optimality operator is monotone, so implies that the updated value is at least . Optimism is therefore preserved forever. An optimistic greedy agent is drawn toward states it overvalues, and each visit lowers the overvalued estimate toward the truth. Strictly negative rewards rule out trajectories that never reach a goal, because an endless one would drive the values on it to , below . Hence the states visited infinitely often form a set closed under the greedy policy, on which the values converge to a fixed point of the optimality equation. With optimism, these values must be , and the greedy actions are optimal there. States outside this set may keep their optimistic initial values. They are never worth visiting, because the true values reachable through them are no better. □
Sutton and Barto illustrate this on a racetrack with reachable states, only of them relevant. Sweep-based value iteration needed about updates to converge, while RTDP reached equally good policies with about half as many. It updated about of the states at most ten times and about of them never. A second advantage is that RTDP’s policy is greedy with respect to the current values at all times. It improves while values are still converging, whereas value iteration gives no sign that its greedy policy became optimal long before the values settled.
8.8Planning at Decision Time#
So far planning has been background planning: it improves a table (or later a function) that is consulted when an action is needed, and it is not focused on the current state. The alternative is decision-time planning. After each new state , planning starts from , ends with the choice of , and its results are usually discarded. The pipeline from simulated experience to values to policy is the same, but the values are specific to the present state and its choices. Decision-time planning suits problems with time to think, such as a board game with seconds or minutes per move, and visits to the same state are rare. When actions must be chosen with low latency, background planning is better. The two combine naturally: plan around the current state, and keep what was learned in case the state returns.
8.8.1Heuristic Search#
Classical AI planning is heuristic search. From the current state, build a tree of possible continuations, evaluate the leaves with an approximate value function, and back the values up to the root with max-backups, the expected updates for and . Then choose the best action at the root and throw the tree away. A greedy policy is the depth-one case: comparing over actions is a one-step search. Searching deeper helps when the model is good and the value function is not. The error-reduction property of Theorem 7.3 has a control analog: steps of max-backups shrink the error of the leaf values by , and a search to the end of the episode needs no value function at all. How much does an error in the leaf values cost?
Theorem 8.6 (Loss of a Greedy Policy). If and is greedy with respect to (using the true model), then for all .
Proof. Write for the Bellman optimality operator and for the Bellman operator of . Both are -contractions in the max norm, and greediness means . Then
and solving for gives the bound. □
This is Singh and Yee’s bound.Satinder P. Singh and Richard C. Yee. An Upper Bound on the Loss from Approximate Optimal-Value Functions. Machine Learning, 16(3):227–233, 1994. doi: 10.1007/BF00993308 Exercise 8.11 shows that depth- lookahead multiplies it by . In practice, much of heuristic search’s power has another source: focus. The search tree concentrates computation and memory on the states that can follow the current one, where accuracy matters most. TD-Gammon’s selective search a few moves ahead made its play markedly better, at the price of slower moves.Searching deeper does not always help: Pearl’s 1984 book on heuristics discusses on game trees “pathological” games in which deeper minimax search gives worse decisions. Such cases are rare in practice. A tree search can even be run as a sequence of one-step backups ordered from the leaves to the root. The improvement then comes from where the updates are focused, not from any multi-step update.
8.8.2Rollout Algorithms#
A rollout algorithm is decision-time Monte Carlo control.Gerald Tesauro and Gregory R. Galperin. On-line Policy Improvement using Monte-Carlo Search. In Advances in Neural Information Processing Systems 9 (NIPS 1996), volume 9, pages 1068–1074. MIT Press, 1997. URL https://proceedings.neurips.cc/paper/1996/hash/996009f2374006606f4c0b0fda878af1-Abstract.html From the current state , for each action , simulate many trajectories that start with and then follow a fixed rollout policy , and average their returns to estimate . Take the action with the highest estimate, and repeat from the next state. The name comes from backgammon, where a position is evaluated by “rolling out” the dice many times to the end of the game.
Algorithm 8.7 (Rollout Algorithm). Input: a sample model, a rollout policy , a simulation budget. At each real state :
- For each : run simulated episodes from that take first and then follow , possibly truncated and completed with a stored value estimate. Let be the average return.
- Take , and discard the estimates.
What does this achieve? By the policy improvement theorem (Theorem 4.6), the policy that plays at the current state and afterwards is at least as good as . The rollout policy, which does this at every state it meets, is therefore an improvement on , one step of policy iteration carried out only where it is needed. The aim of a rollout algorithm is to beat its rollout policy, not to be optimal. A matrix identity makes the improvement quantitative. For any two deterministic policies,
(8.5)and has nonnegative entries. If the advantages are nonnegative, so is the gain in value. We check the identity on a general two-state, two-action MDP, in which plays action everywhere and switches state to action .
Rewards and probabilities of moving to state are free symbols. The display is minus the right-hand side of (8.5), whose advantage vector is .const mdpP = await wl`Function[{s, a}, {Subscript[p, s, a], 1 - Subscript[p, s, a]}]`
const mdpR = await wl`Function[{s, a}, Subscript[r, s, a]]`
const vOfPol = await wl`Function[{pol}, Inverse[IdentityMatrix[2] - \[Gamma] Table[${mdpP}[s, pol[[s]]], {s, 2}]] . Table[${mdpR}[s, pol[[s]]], {s, 2}]]`
const vRollBase = await wl`${vOfPol}[{1, 1}]`
const qRollBase = await wl`Function[{s, a}, ${mdpR}[s, a] + \[Gamma] ${mdpP}[s, a] . ${vRollBase}]`
const perfDiff = await show`Simplify[${vOfPol}[{2, 1}] - ${vRollBase} - Inverse[IdentityMatrix[2] - \[Gamma] Table[${mdpP}[s, {2, 1}[[s]]], {s, 2}]] . {${qRollBase}[1, 2] - ${vRollBase}[[1]], 0}]`Better rollout policies and more simulations give better decisions but cost more time, and decisions are usually on a deadline. The trials are independent, so they parallelize trivially. Trajectories can be truncated and completed with a stored evaluation, which brings back the -step returns of Chapter 7. And candidate actions that are clearly worse can be pruned early.
8.9Monte Carlo Tree Search#
Monte Carlo Tree Search (MCTS) is a rollout algorithm with a memory.Rémi Coulom. Efficient Selectivity and Backup Operators in Monte-Carlo Tree Search. In H. Jaap van den Herik, Paolo Ciancarini, and H. H. L. M. Donkers, editors, Computers and Games: 5th International Conference, CG 2006, Turin, Italy, May 29–31, 2006, volume 4630 of Lecture Notes in Computer Science, pages 72–83, Berlin, Heidelberg, 2007. Springer. doi: 10.1007/978-3-540-75538-8_7; and Levente Kocsis and Csaba Szepesvári. Bandit Based Monte-Carlo Planning. In Johannes Fürnkranz, Tobias Scheffer, and Myra Spiliopoulou, editors, Machine Learning: ECML 2006. 17th European Conference on Machine Learning, volume 4212 of Lecture Notes in Computer Science, pages 282–293, Berlin, Heidelberg, 2006. Springer. doi: 10.1007/11871842_29 It keeps value estimates for a tree of state–action pairs rooted at the current state and grows the tree toward the trajectories that have done well, so that later simulations go where earlier ones found reward. MCTS raised computer Go from weak amateur level in 2005 to strong amateur level (6 dan or more) by 2015. Inside the tree, actions are chosen by a tree policy that balances exploration and exploitation using the stored statistics. Beyond the tree, a cheap rollout policy finishes the simulation. Each iteration has four steps:
- Selection. From the root, follow the tree policy down to a leaf of the tree.
- Expansion. On some iterations, add one or more children of that leaf, reached by untried actions.
- Simulation. From the leaf (or a new child), simulate to the end of the episode with the rollout policy.
- Backup. Use the return to update the statistics of the edges traversed in the tree. Nothing is stored for the part of the trajectory beyond the tree.
When time runs out, the agent acts, usually with the most visited root action, which is more robust than the one with the highest mean. The subtree below the chosen action can be kept for the next search. The classic tree policy is UCT (Upper Confidence bounds applied to Trees), which runs the UCB rule of Chapter 2 at every node.Levente Kocsis and Csaba Szepesvári. Bandit Based Monte-Carlo Planning. In Johannes Fürnkranz, Tobias Scheffer, and Myra Spiliopoulou, editors, Machine Learning: ECML 2006. 17th European Conference on Machine Learning, volume 4212 of Lecture Notes in Computer Science, pages 282–293, Berlin, Heidelberg, 2006. Springer. doi: 10.1007/11871842_29; and Peter Auer, Nicolò Cesa-Bianchi, and Paul Fischer. Finite-time Analysis of the Multiarmed Bandit Problem. Machine Learning, 47(2–3):235–256, 2002. doi: 10.1023/A:1013689704352 With visits of node , of edge , and the mean return through that edge,
(8.6)with untried actions chosen first. With returns in , the constant gives the UCB1 index of Auer, Cesa-Bianchi and Fischer.
Algorithm 8.8 (Monte Carlo Tree Search with UCT). Input: the current state , a sample model, a rollout policy, exploration constant , a time budget. Initialization: a tree with root ; for every edge, and , and .
While time remains:
- Selection: ; while is in the tree, nonterminal and has no untried action, choose by (8.6), sample from the model, record the edge and reward, and set .
- Expansion: if is nonterminal and has an untried action , add the edge , sample , record them, and add to the tree.
- Simulation: from the last state, follow the rollout policy to termination, collecting rewards.
- Backup: for each recorded edge , from the deepest up, let be the return from that edge onward; set , , .
Act with .
Why the logarithm and the square root? Hoeffding’s inequality bounds the chance that a mean of returns in overshoots its expectation by by .Wassily Hoeffding. Probability Inequalities for Sums of Bounded Random Variables. Journal of the American Statistical Association, 58(301):13–30, 1963. doi: 10.1080/01621459.1963.10500830 With equal to the exploration bonus, this failure probability is a power of the visit count of the node. And an edge whose value is below the best stops being selected once its bonus falls below , which happens after logarithmically many visits.
With bonus , Hoeffding’s bound becomes , which is for UCB1’s . Solving gives the number of visits after which a -suboptimal edge stops being chosen.const uctFacts = await show`{Simplify[Exp[-2 Subscript[n, a] (c Sqrt[Log[n]/Subscript[n, a]])^2], Subscript[n, a] > 0], Subscript[n, a] /. First[Solve[\[CapitalDelta]^2 Subscript[n, a] == c^2 Log[n], Subscript[n, a]]]}`Suboptimal edges thus receive of the simulations, and the most visited root action is, in the long run, the best one. Kocsis and Szepesvári proved that UCT’s probability of choosing a wrong action at the root goes to zero at a polynomial rate.Levente Kocsis and Csaba Szepesvári. Bandit Based Monte-Carlo Planning. In Johannes Fürnkranz, Tobias Scheffer, and Myra Spiliopoulou, editors, Machine Learning: ECML 2006. 17th European Conference on Machine Learning, volume 4212 of Lecture Notes in Computer Science, pages 282–293, Berlin, Heidelberg, 2006. Springer. doi: 10.1007/11871842_29 Their analysis has to cope with a difficulty that plain bandits do not have: the returns seen by a node drift as the subtree below it improves.
Seen this way, MCTS combines most of Part I’s ideas. It is Monte Carlo control on simulated trajectories from the root, so it is a rollout algorithm and inherits policy improvement. It stores the action values of the first part of the trajectories in a lookup table that grows where returns have been high, so it never needs a global value function. It updates those values with sample updates, chooses actions in the tree with a bandit rule, and focuses all its computation on the current decision.
8.10Part I in Retrospect: Dimensions of Methods#
Every method in Part I estimates value functions, backs values up along actual or possible trajectories, and follows generalized policy iteration (Section 4.7). They differ along a few dimensions. The two most important concern the update itself. Its width ranges from sample updates (one trajectory) to expected updates (all branches). Its depth ranges from one-step bootstrapping to full returns. TD learning (narrow, shallow), dynamic programming (wide, shallow) and Monte Carlo (narrow, deep) occupy three corners of this square. Exhaustive search (wide, deep) occupies the fourth. -step methods fill the narrow edge, heuristic search the wide one, and tree backup and the interior. Further dimensions are: on- or off-policy; episodic or continuing, discounted or not; state, action or afterstate values; how actions are chosen and how exploration is ensured; synchronous or asynchronous updates; real or simulated experience; which states to update, when to update them (in the background or at decision time), and how long to keep the results. The most important dimension missing from Part I is function approximation, which Part II adds.
8.11Beyond the Book: Learned Models and Search#
Sutton and Barto end with MCTS and with AlphaGo, which combined MCTS with learned value and policy networks (Section 15.6). The years after the book went to press closed the loop of this chapter: search was used to train the networks that guide it, the model itself became learned, and search learned to work with tiny budgets.
8.11.1AlphaGo Zero and AlphaZero: Search as Policy Improvement#
AlphaGo Zero learned Go from self-play alone, without human games.David Silver, Julian Schrittwieser, Karen Simonyan, Ioannis Antonoglou, Aja Huang, Arthur Guez, Thomas Hubert, Lucas Baker, Matthew Lai, Adrian Bolton, Yutian Chen, Timothy Lillicrap, Fan Hui, Laurent Sifre, George van den Driessche, Thore Graepel, and Demis Hassabis. Mastering the Game of Go without Human Knowledge. Nature, 550(7676):354–359, 2017. doi: 10.1038/nature24270Beyond Sutton and Barto (2018). AlphaGo Zero (Silver et al., Nature, 2017) and AlphaZero (Silver et al., Science, 2018; preprint 2017), which applied the same algorithm to chess and shogi, appeared too late for the book’s main text. The selection rule is a variant of Rosin’s PUCB (2011). A single network outputs move probabilities and a value. MCTS uses no rollouts. A leaf is evaluated by , and the tree policy is the PUCT rule
(8.7)where the prior from the network replaces UCT’s uniform optimism. The visit counts at the root define an improved policy , and the network is trained to match it and to predict the game outcome :
This is generalized policy iteration in which MCTS is the policy-improvement operator: the search policy is better than the raw network policy, and the network is regressed onto it. Search makes the network better, and the network makes the next search better.David Silver, Thomas Hubert, Julian Schrittwieser, Ioannis Antonoglou, Matthew Lai, Arthur Guez, Marc Lanctot, Laurent Sifre, Dharshan Kumaran, Thore Graepel, Timothy Lillicrap, Karen Simonyan, and Demis Hassabis. A General Reinforcement Learning Algorithm that Masters Chess, Shogi, and Go through Self-Play. Science, 362(6419):1140–1144, 2018. doi: 10.1126/science.aar6404; and Christopher D. Rosin. Multi-Armed Bandits with Episode Context. Annals of Mathematics and Artificial Intelligence, 61(3):203–230, 2011. doi: 10.1007/s10472-011-9258-6
8.11.2MuZero: Planning with a Learned Model#
AlphaZero needs the rules of the game as its model. MuZero learns one, but not a model of observations.Julian Schrittwieser, Ioannis Antonoglou, Thomas Hubert, Karen Simonyan, Laurent Sifre, Simon Schmitt, Arthur Guez, Edward Lockhart, Demis Hassabis, Thore Graepel, Timothy Lillicrap, and David Silver. Mastering Atari, Go, Chess and Shogi by Planning with a Learned Model. Nature, 588(7839):604–609, 2020. doi: 10.1038/s41586-020-03051-4Beyond Sutton and Barto (2018). MuZero (Schrittwieser et al., Nature, 2020; arXiv 2019) matched AlphaZero in Go, chess and shogi without being given the rules, and set a new state of the art on Atari. It has three functions: a representation , a deterministic dynamics function , and a prediction function . Unrolled for steps along the actions actually taken, the model is trained to predict only what planning needs: rewards, values (-step bootstrapped targets, as in (7.1)) and the search policies. The hidden state need not resemble the environment’s state at all. It is a model in exactly the sense of Section 8.1, something that predicts the consequences of actions, but a value-equivalent one. MCTS runs inside the learned model, with the pUCT rule (, ) and values normalized to over the tree.
8.11.3Gumbel AlphaZero and MuZero: Policy Improvement with Few Simulations#
Visit-count targets are a poor policy improvement when the budget is small: with simulations at the root, most actions are never visited, and AlphaZero’s targets need not improve on the prior. Danihelka, Guez, Schrittwieser and Silver replaced the root of the search by a procedure with a guarantee.Ivo Danihelka, Arthur Guez, Julian Schrittwieser, and David Silver. Policy Improvement by Planning with Gumbel. In International Conference on Learning Representations (ICLR 2022), 2022. URL https://openreview.net/forum?id=bERaNdoegnOBeyond Sutton and Barto (2018). Gumbel AlphaZero and Gumbel MuZero (Danihelka et al., ICLR 2022) learn reliably with as few as simulations on Go, a budget at which the original MuZero fails to learn. It rests on the Gumbel-max trick: if are independent standard Gumbel variables, is distributed as . Taking the top actions of samples actions without replacement. Sequential Halving then shares the simulations among them, and the action played is with an increasing transformation . Because the same is used, the expected of the chosen action is at least that of the prior policy when the estimates are correct. The training target becomes , where unvisited actions are given a value estimate, and . The trick itself is a one-line check for two actions.
With independent standard Gumbel (maximum) variables, in Wolfram’sExtremeValueDistribution[0, 1], the probability that beats is the softmax probability of the first logit.const gumbelMax = await show`Probability[x + a > y + b, {x \[Distributed] ExtremeValueDistribution[0, 1], y \[Distributed] ExtremeValueDistribution[0, 1]}]`8.11.4Dyna Revisited: Dreamer and MBPO#
Background planning with a learned model, which is the Dyna idea, has also grown up. Two questions matter: what to model, and how far to trust it. Dreamer learns a latent world model from pixels and trains an actor and a critic purely on trajectories imagined in latent space, steps long, starting from states of replayed real sequences.Danijar Hafner, Timothy Lillicrap, Jimmy Ba, and Mohammad Norouzi. Dream to Control: Learning Behaviors by Latent Imagination. In International Conference on Learning Representations (ICLR 2020), 2020 The critic regresses on -returns (Chapter 12) computed from imagined rewards and values. The first Dreamer trained the actor by backpropagating value gradients through the learned dynamics. DreamerV3 uses a single fixed set of hyperparameters for more than tasks, made possible by robustness devices such as the squashing of targets. It was the first algorithm to collect diamonds in Minecraft from scratch, without human data or curricula.Danijar Hafner, Jurgis Pasukonis, Jimmy Ba, and Timothy Lillicrap. Mastering Diverse Domains through World Models. arXiv preprint arXiv:2301.04104, 2023. Journal version: Nature 640, 647–653 (2025), doi:10.1038/s41586-025-08744-2; and Danijar Hafner, Jurgis Pasukonis, Jimmy Ba, and Timothy Lillicrap. Mastering Diverse Control Tasks through World Models. Nature, 640(8059):647–653, 2025. doi: 10.1038/s41586-025-08744-2Beyond Sutton and Barto (2018). Dreamer (Hafner, Lillicrap, Ba and Norouzi, ICLR 2020) and DreamerV3 (Hafner, Pasukonis, Ba and Lillicrap, arXiv 2023; Nature 2025, under the title “Mastering diverse control tasks through world models”) are Dyna-style agents whose model is a learned latent dynamics network.
Model-based policy optimization (MBPO) answers the trust question.Michael Janner, Justin Fu, Marvin Zhang, and Sergey Levine. When to Trust Your Model: Model-Based Policy Optimization. In Advances in Neural Information Processing Systems 32 (NeurIPS 2019), volume 32, pages 12519–12530. Curran Associates, Inc., 2019. URL https://proceedings.neurips.cc/paper/2019/hash/5faf461eff3099671ad63c6f3f094f7f-Abstract.htmlBeyond Sutton and Barto (2018). MBPO (Janner, Fu, Zhang and Levine, NeurIPS 2019) bounds the true return of a policy trained in a model by its model return minus terms that grow with the model error, the policy shift, and the rollout length. Model errors compound along long simulated trajectories, so MBPO generates only short branched rollouts of steps from states sampled from real experience, and trains a model-free learner on the mixture. Its analysis bounds the true return by the model return minus a penalty that grows linearly with times the model error. Dyna-Q’s planning updates are the case . MBPO shows that a few more steps pay when the model is accurate, and that long imagined trajectories rarely do.
All of these agents replace tables by neural networks. That is the step Part II takes, starting with the prediction problem in Chapter 9.
8.12Exercises#
Exercise 8.9. The analysis of Proposition 8.4 assumed that the successors were equally likely. Suppose instead that they have probabilities , and that their values are independent draws with mean and variance . Show that the expected variance of one sampled successor value, , equals . Does a skewed distribution strengthen or weaken the case for sample updates?
Solution
Expanding the square, with , gives . For with normal values:
The expectation computed exactly for three normal successor values, with : first its factored form, then its difference from .const skewVar = await wl`Expectation[Sum[Subscript[p, i] (Subscript[x, i] - Sum[Subscript[p, j] Subscript[x, j], {j, 3}])^2, {i, 3}] /. Subscript[p, 3] -> 1 - Subscript[p, 1] - Subscript[p, 2], {Subscript[x, 1] \[Distributed] NormalDistribution[\[Mu], \[Sigma]], Subscript[x, 2] \[Distributed] NormalDistribution[\[Mu], \[Sigma]], Subscript[x, 3] \[Distributed] NormalDistribution[\[Mu], \[Sigma]]}]`
const skewCheck = await show`{Factor[${skewVar}], Simplify[${skewVar} - \[Sigma]^2 (1 - Subscript[p, 1]^2 - Subscript[p, 2]^2 - (1 - Subscript[p, 1] - Subscript[p, 2])^2)]}`The uniform case gives , the largest possible value. If one successor carries probability , the variance is about . Sampling naturally spends its effort on the likely successors, while the expected update still pays for all of them. Skew therefore strengthens the case for sample updates. The error after samples is and does not depend on , whereas the cost of the expected update grows with .
Exercise 8.10. Dyna-Q+ adds the bonus to rewards in planning updates. An alternative adds it only when choosing actions, selecting . Consider a state whose only action leads deterministically to with reward . In , a long-untried action is modeled as a self-loop with reward , and the other action ends the episode with reward . Find the planned values of and in each variant, with the bonus held fixed at . What does the comparison say about the strengths and weaknesses of each variant?
Solution
With the bonus in the updates, the planning fixed point satisfies for the untried action and .
Fixed point of the planning updates with the bonus in the reward: the untried self-loop is worth , and one step upstream inherits .const bonusFixed = await show`Solve[{Subscript[q, 1] == \[Beta] + \[Gamma] Subscript[q, 1], Subscript[v, 0] == \[Gamma] Subscript[q, 1]}, {Subscript[q, 1], Subscript[v, 0]}]`In the action-selection variant all planned values stay . The bonus acts only when the agent is already in , so nothing draws it toward from or from farther away. Bonuses in updates therefore produce directed, multi-step exploration toward untested parts of the world. The price is that the values themselves are distorted, by an amount that grows over time and must be relearned after each test. Bonuses in action selection leave the values honest but explore only locally, one step at a time. This is the same distinction as between optimistic initial values and UCB in Chapter 2, in a sequential setting.
Exercise 8.11. Extend Theorem 8.6 to search. Let choose, in each state, the root action of a depth- max-backup search with exact model and leaf values , . Show that . What does this say about how search depth trades against the accuracy of the value function?
Solution
A depth- search with leaf values is the same as acting greedily with respect to , the values after levels of max-backups below the root. Since is a -contraction with fixed point , . Applying Theorem 8.6 to gives the bound . Each extra level of search is worth a factor in value accuracy. To halve the loss, one can either halve (learning) or search levels deeper (planning). With branching factor , the search costs evaluations, so for close to deeper search is an expensive substitute for a better value function. This is why AlphaZero couples a moderate search with a learned evaluation.
Exercise 8.12. The non-planning agent of the Dyna maze is one-step Q-learning. Could an -step method from Chapter 7 do as well as Dyna-Q with planning steps? Consider the second episode of the maze.
Solution
Partly. After the first episode, an -step method has propagated the goal reward steps back along the path of that episode, against one step for Q-learning. That helps a great deal if the second episode follows the same route. But -step methods only learn along trajectories as they are experienced, and only once. Dyna’s model lets it replay every transition ever seen, as often as it likes and in any order. In particular, it can combine pieces of different episodes: a state visited early in episode , from which a transition led into a region whose value became known only later, receives that value through planning without being visited again. With many planning steps per real step, Dyna effectively runs value iteration on the part of the maze explored so far, which no method limited to the current trajectory can match. The two ideas combine, too: multi-step returns can be computed on simulated trajectories, as MuZero and Dreamer do.