Chapter 15

Applications and Case Studies

Every case study in this chapter is assembled from parts we already own. The previous chapter (Chapter 14) found the TD error at work in animals; here it is at work in machines built to play, wager, schedule and fly. TD-Gammon is semi-gradient TD(λ\lambda) with a neural network; DQN is semi-gradient Q-learning; AlphaGo Zero is policy iteration in which Monte Carlo tree search performs the improvement step; Watson’s wagering is the identity “an action value is the expected value of the next state”. None of the algorithms is new. What is new is the engineering around them: how the state is presented to the learner, what the reward actually rewards, where the experience comes from (self-play, a simulator, a log of past interactions), and how learned values are combined with search at decision time. Sutton and Barto put it plainly: applications “typically require as much art as science”.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 We read each case study with the same five questions in mind: what is the problem, how are states, actions and rewards defined, which algorithm of the earlier chapters is being run, what made it work, and what it taught the field. The chapter closes with a survey of the case studies that came after the book was published.

SystemStateRewardCore algorithmSource of experience
Samuel’s checkers (1959)hand-made featuresnone (piece advantage, fixed)minimax search + TD-like backupself-play
TD-Gammon (1992–95)198 board units+1+1 on a winsemi-gradient TD(λ\lambda), afterstatesself-play
Watson DD wagering (2011)scores, clues left+1+1 on a winTD(λ\lambda) + one-step lookaheadsimulated opponents
DRAM controller (2008)6 queue features+1+1 per read/writeSarsa, tile codingonline, on chip
DQN (2015)4 stacked framessign of score changesemi-gradient Q-learning + replayemulator
AlphaGo Zero (2017)17 board planes±1\pm 1 at game endMCTS-driven policy iterationself-play
Web services (2010–15)user featuresclickcontextual bandits, fitted Q iterationlogged data
Thermal soaring (2016)2 wind cues, 3 bins eachwind velocity and accelerationSarsa, state aggregationsimulator

15.1TD-Gammon

Backgammon is a race of fifteen pieces per player around 24 points, driven by two dice and complicated by the possibility of hitting a lone opposing piece and sending it back to the start. The number of positions is astronomically large, and because each move depends on a dice roll the effective branching factor of the game tree is around 400, which rules out the deep search that works in chess. On the other hand the state is fully observed, every game ends, and the outcome is a natural target for prediction. Gerald Tesauro’s TD-Gammon learned to play at the level of the best human players by doing nothing more than predicting that outcome.Gerald Tesauro. TD-Gammon, a Self-Teaching Backgammon Program, Achieves Master-Level Play. Neural Computation, 6(2):215–219, 1994. doi: 10.1162/neco.1994.6.2.215; and Gerald Tesauro. Temporal Difference Learning and TD-Gammon. Communications of the ACM, 38(3):58–68, 1995. doi: 10.1145/203330.203343

Value and reward. The reward is 00 on every step except a win, where it is 11, and γ=1\gamma = 1. Then the value of a position under the current policy is exactly the probability of winning from it, vπ(s)=Pr⁡π{win∣St=s}v_\pi(s) = \Pr_\pi\{\text{win} \mid S_t = s\}, and the TD error reduces to v^(St+1,𝐰)−v^(St,𝐰)\hat v(S_{t+1}, \mathbf{w}) - \hat v(S_t, \mathbf{w}) before the end of the game.

Representation. The network had 198 input units: for each of the 24 points and each color, four units coding “one piece” (a vulnerable blot), “at least two” (a made point), “exactly three” (one spare) and (n−3)/2(n-3)/2 for further spares; then units for the pieces on the bar and borne off, and two for the side to move. This is a nearly raw description of the board, but one designed by someone who knew that a network learns faster from inputs of comparable scale that switch on at qualitatively meaningful thresholds. A hidden layer of 40–160 sigmoid units fed one sigmoid output,

v^(s,𝐰)=σ(∑juj hj),hj=σ(∑iwij xi(s)), \hat v(s, \mathbf{w}) = \sigma\Bigl(\sum_j u_j\, h_j\Bigr), \qquad h_j = \sigma\Bigl(\sum_i w_{ij}\, x_i(s)\Bigr), (15.1)

with the logistic function σ(z)=1/(1+e−z)\sigma(z) = 1/(1 + e^{-z}), so that the output lies in (0,1)(0, 1), as a probability should.

Algorithm. Learning was the semi-gradient TD(λ\lambda) of Algorithm 12.2 with the gradient ∇v^\nabla \hat v computed by backpropagation, applied after every move. Moves were chosen greedily by one-step lookahead over afterstates: for each of the roughly twenty legal ways of playing the dice, evaluate the resulting position and pick the best.

Algorithm 15.1 (Self-Play TD(λ\lambda) over Afterstates (TD-Gammon)). Parameters: step size α>0\alpha > 0, trace decay λ∈[0,1]\lambda \in [0, 1]; network (15.1) with small random weights 𝐰\mathbf{w}.

  1. Loop for each game:
    1. Set S0S_0 to the initial position (from the point of view of the player to move) and 𝐳←𝟎\mathbf{z} \leftarrow \mathbf{0}.
    2. Loop for t=0,1,2,…t = 0, 1, 2, \dots until the game ends:
      1. Roll the dice; for each legal move compute the afterstate s′s' and v^(s′,𝐰)\hat v(s', \mathbf{w}); play the move with the largest value. Let St+1S_{t+1} be the resulting position and Rt+1R_{t+1} the reward (11 if it wins the game, else 00).
      2. 𝐳←λ 𝐳+∇v^(St,𝐰)\mathbf{z} \leftarrow \lambda\,\mathbf{z} + \nabla \hat v(S_t, \mathbf{w}).
      3. δ←Rt+1+v^(St+1,𝐰)−v^(St,𝐰)\delta \leftarrow R_{t+1} + \hat v(S_{t+1}, \mathbf{w}) - \hat v(S_t, \mathbf{w}), with v^(terminal)≐0\hat v(\text{terminal}) \doteq 0.
      4. 𝐰←𝐰+α δ 𝐳\mathbf{w} \leftarrow \mathbf{w} + \alpha\,\delta\,\mathbf{z}.

Both sides are played by the same network, so the opponent improves with the learner: this is self-play. The early games, played by a random network, lasted thousands of moves; after a few dozen they became sensible, and after about 300,000 games TD-Gammon 0.0, which knew essentially nothing about backgammon, played as well as Neurogammon, Tesauro’s own champion program trained by supervised learning on expert moves with hand-crafted features. Adding those features as extra inputs (TD-Gammon 1.0), larger hidden layers and selective two- and three-ply search at decision time (versions 2.0 to 3.1) produced a program that played on equal terms with world-class grandmasters and changed how humans play several openings.Gerald Tesauro. Programming Backgammon Using Self-Teaching Neural Nets. Artificial Intelligence, 134(1–2):181–199, 2002. doi: 10.1016/S0004-3702(01)00110-2

15.1.1In Wolfram Language

The only nontrivial computation in Algorithm 15.1 is the gradient of (15.1). Backpropagation is the chain rule organized around the identity σ′=σ(1−σ)\sigma' = \sigma(1-\sigma); we check both on a network with two inputs and two hidden units.

The logistic sigmoid’s derivative is a function of its own output, which is why a backward pass needs only the activations stored during the forward pass.
await show`D[LogisticSigmoid[z], z]`
σ′(z)=(1−σ(z))σ(z) \sigma'(z) = (1-\sigma (z)) \sigma (z) Differentiate the whole network symbolically and subtract the backpropagation formulas ∂v^/∂u1=v^(1−v^)h1\partial\hat v/\partial u_1 = \hat v(1-\hat v)h_1 and ∂v^/∂w11=v^(1−v^) u1 h1(1−h1) x1\partial\hat v/\partial w_{11} = \hat v(1-\hat v)\,u_1\,h_1(1-h_1)\,x_1: both differences vanish.
const tdgNet = await wl`Function[{x1, x2}, LogisticSigmoid[Subscript[u, 1] LogisticSigmoid[Subscript[w, 11] x1 + Subscript[w, 21] x2] + Subscript[u, 2] LogisticSigmoid[Subscript[w, 12] x1 + Subscript[w, 22] x2]]]`
const tdgV = await wl`${tdgNet}[Subscript[x, 1], Subscript[x, 2]]`
const tdgH1 = await wl`LogisticSigmoid[Subscript[w, 11] Subscript[x, 1] + Subscript[w, 21] Subscript[x, 2]]`
await show`Simplify[{D[${tdgV}, Subscript[u, 1]] - ${tdgV} (1 - ${tdgV}) ${tdgH1}, D[${tdgV}, Subscript[w, 11]] - ${tdgV} (1 - ${tdgV}) Subscript[u, 1] ${tdgH1} (1 - ${tdgH1}) Subscript[x, 1]}]`
(∂v^∂u1−backprop,  ∂v^∂w11−backprop)={0,0} \Bigl(\tfrac{\partial \hat v}{\partial u_1} - \text{backprop},\; \tfrac{\partial \hat v}{\partial w_{11}} - \text{backprop}\Bigr) = \{0,0\}

15.1.2What Made It Work

Three features of backgammon conspired in TD-Gammon’s favor, and each is a lesson. First, the dice supply exploration for free: a purely greedy self-play policy still visits a broad and changing set of positions, whereas in a deterministic game it could lock into a narrow repertoire. Second, the value function is smooth in the board description, because a single dice roll rarely turns a won position into a lost one, so a network with a few dozen hidden units generalizes well. Third, afterstate values are learned directly, and the move generator is known exactly, so no model of the dynamics has to be learned. The theory of Chapter 9 says nothing about nonlinear TD with a moving self-play target; TD-Gammon showed that the combination could nonetheless be stable and strong, and it remained the reference point for the next two decades.

15.2Samuel’s Checkers Player

Arthur Samuel’s checkers programs of 1952–1967 contain, in embryo, most of the ideas of Sutton and Barto’s book.Arthur L. Samuel. Some Studies in Machine Learning Using the Game of Checkers. IBM Journal of Research and Development, 3(3):210–229, 1959. doi: 10.1147/rd.33.0210 They played by minimax lookahead, scoring the leaves of the search tree with a scoring polynomial, a linear function of hand-designed features. Samuel’s rote learning cached the backed-up minimax value of every position encountered, which effectively extended the search depth whenever a cached position reappeared as a leaf. To make the program prefer the shortest win, he reduced a value slightly each time it was backed up one ply: in effect a discount factor.

His second method, learning by generalization, is the direct ancestor of TD-Gammon. After each move, the value of the previous on-move position was adjusted towards the minimax value of a search launched from the current one: a backup over one real move followed by a search over hypothetical ones, which is exactly the combination of sampling and search that Section 8.9 develops. The program reached “better-than-average” amateur play.

What it lacked is instructive. Samuel used no reward and gave the terminal positions no special value; instead he fixed the weight of the piece-advantage feature and let the others learn.

Proposition 15.2 (Consistency Without an Anchor). In an episodic task with no rewards, if terminal positions receive the same estimated value as any other position, every constant value function satisfies the TD consistency condition v^(s)=𝔼[v^(St+1)∣St=s]\hat v(s) = \mathbb{E}[\hat v(S_{t+1}) \mid S_t = s], whatever the policy.

Proof. If v^≡c\hat v \equiv c then 𝔼[v^(St+1)∣St=s]=c=v^(s)\mathbb{E}[\hat v(S_{t+1}) \mid S_t = s] = c = \hat v(s) for every ss, so every TD error is zero. A reward on termination, or the convention v^(terminal)=0\hat v(\text{terminal}) = 0 used throughout this companion, breaks the symmetry: the Bellman equation (3.9) then has a unique solution. □

A fixed weight on one feature does not prevent such degenerate solutions: the learned weights can cancel it (Exercise 15.5). Samuel did observe his program getting worse during long self-play sessions, and he repaired it by resetting the largest weight to zero. Sutton and Barto suggest that the program may have been drifting towards evaluations that were self-consistent but unrelated to winning. TD learning makes a value function agree with itself; only rewards and terminal values tie it to the task.

15.3Watson’s Daily-Double Wagering

IBM’s Watson won a televised Jeopardy! exhibition match against two human champions in 2011. Its question answering is not reinforcement learning, but its wagering strategy is, and it was built by Tesauro and colleagues with the TD-Gammon recipe.G. Tesauro, D. C. Gondek, J. Lenchner, J. Fan, and J. M. Prager. Analysis of Watson’s Strategies for Playing Jeopardy! Journal of Artificial Intelligence Research, 47:205–251, 2013. doi: 10.1613/jair.3834 When a contestant finds a Daily Double square, they must bet any amount up to their current score before seeing the clue; a correct answer adds the bet, a wrong one subtracts it.

A network v^(⋅,𝐰)\hat v(\cdot, \mathbf{w}), trained by nonlinear TD(λ\lambda) over millions of simulated games, estimated Watson’s probability of winning from a game state described by the three scores, the number of remaining Daily Doubles, the value of the remaining clues and similar quantities. A second estimate pDDp_{\mathrm{DD}}, the probability of answering the hidden clue correctly, was conditioned on Watson’s right and wrong answers so far in that category. The action values were then computed at decision time, for every legal bet, as

q^(s,bet)=pDD v^(SW+bet,… )+(1−pDD) v^(SW−bet,… ), \hat q(s, \text{bet}) = p_{\mathrm{DD}}\,\hat v(S_W + \text{bet}, \dots) + (1 - p_{\mathrm{DD}})\,\hat v(S_W - \text{bet}, \dots), (15.2)

where SWS_W is Watson’s score: an action value as the expected value of the afterstate, one step of the Bellman equation (3.10) evaluated with a learned v^\hat v.

Two departures from TD-Gammon are worth noting. Self-play would have been useless, because Watson’s abilities were so unlike a human’s that games against itself would have explored the wrong part of the state space; the team instead built stochastic models of average, champion and grand-champion contestants from an archive of about 300,000 clues, and trained against those. And maximizing (15.2) turned out to take “a frightening amount of risk”, so the final bet subtracted a small multiple of the standard deviation of the two afterstate values and forbade bets whose wrong-answer value fell below a threshold: a risk-sensitive modification that gave up a little expected value for a large reduction of the downside. Near the end of a game, where the network’s errors matter most and the remaining game is short, Monte Carlo rollouts to the end replaced v^\hat v. In simulation, learned wagering raised Watson’s win rate from 61% to 67%, from a decision taken fewer than twice per game.

15.4Optimizing Memory Control

A DRAM memory controller decides, at every memory clock cycle, which command to issue to the memory chips: activate a row (copy it into the row buffer), read or write a word of the open row, precharge (write the row back), or do nothing. Reads and writes to an already open row are fast; switching rows costs time; and hundreds of timing constraints restrict which commands are legal at any moment. The best hand-designed policy of the time, FR-FCFS, served ready column commands first and otherwise the oldest request.

İpek, Mutlu, Martínez and Caruana cast scheduling as a continuing MDP.Engin Ipek, Onur Mutlu, José F. Martínez, and Rich Caruana. Self-Optimizing Memory Controllers: A Reinforcement Learning Approach. In Proceedings of the 35th International Symposium on Computer Architecture (ISCA), pages 39–50. IEEE, 2008. doi: 10.1109/ISCA.2008.21 The state was described by six integer features of the transaction queue (numbers of pending reads and writes, how many are waiting for their row to be opened, and so on), the actions were the five commands, and the reward was 11 for a read or a write, 00 otherwise: only these move data across the bus, so maximizing reward maximizes throughput. Activate and precharge earn nothing themselves but are required before reads and writes can follow, so the controller must learn delayed consequences. Learning used Sarsa (Algorithm 6.6) with ε=0.05\varepsilon = 0.05 and a linear action-value function on hashed tile coding with 32 tilings, small enough to be laid out in hardware with two five-stage pipelines evaluating two actions per processor cycle.

The design detail with the widest relevance is how safety was obtained: the sets 𝒜(s)\mathcal{A}(s) of legal actions were computed from timing and resource constraints that were not part of the learner’s state features. Exploration could therefore never violate a hardware constraint; the learner only chose among safe commands. In simulation on nine parallel workloads the learned controller improved execution speed over FR-FCFS by 7% to 33%, 19% on average, and learning online added 8% over a policy trained in advance and then frozen. Since throughput per unit time is the real objective, this is naturally an average-reward problem (Section 10.3), approximated here with discounting.

15.5Human-Level Video Game Play

Before 2013 every strong reinforcement learning application had been built on hand-crafted features; even TD-Gammon gained most of its strength from them. The deep Q-network (DQN) of Mnih and colleagues at DeepMind showed that a single agent, with one network architecture and one set of hyperparameters, could learn to play 49 different Atari 2600 games from the screen pixels and the score alone.Volodymyr Mnih, Koray Kavukcuoglu, David Silver, Andrei A. Rusu, Joel Veness, Marc G. Bellemare, Alex Graves, Martin Riedmiller, Andreas K. Fidjeland, Georg Ostrovski, Stig Petersen, Charles Beattie, Amir Sadik, Ioannis Antonoglou, Helen King, Dharshan Kumaran, Daan Wierstra, Shane Legg, and Demis Hassabis. Human-Level Control through Deep Reinforcement Learning. Nature, 518(7540):529–533, 2015. doi: 10.1038/nature14236 The games differ in nearly everything: the meaning of the actions, the dynamics, the time scale, the kind of skill required. A convolutional network learned, separately for each game, the features its action values needed.

States. Each 210×160210 \times 160 color frame was reduced to an 84×8484 \times 84 luminance image, and the four most recent images were stacked into an 84×84×484 \times 84 \times 4 input. A single frame is not a Markov state (it does not show which way a ball is moving); four frames are much closer to one. Frame stacking is the simplest of the approximate state-update functions of Section 16.3. Actions were up to 18 joystick commands, each repeated for four frames. Rewards were clipped to sign⁡\operatorname{sign} of the score change, {−1,0,+1}\{-1, 0, +1\}, so that one step size suited every game, at the price of making the agent indifferent to the size of a reward. The network had three convolutional layers and one fully connected layer of 512 rectified units, with one output per action: q^(s,a,𝐰)\hat q(s, a, \mathbf{w}) for all aa in a single forward pass.

The starting point is semi-gradient Q-learning (Algorithm 6.7 with the update of (9.3)):

δt=Rt+1+γmax⁡aq^(St+1,a,𝐰)−q^(St,At,𝐰),𝐰←𝐰+α δt ∇q^(St,At,𝐰). \begin{aligned} \delta_t &= R_{t+1} + \gamma \max_a \hat q(S_{t+1}, a, \mathbf{w}) - \hat q(S_t, A_t, \mathbf{w}), \\ \mathbf{w} &\leftarrow \mathbf{w} + \alpha\,\delta_t\,\nabla \hat q(S_t, A_t, \mathbf{w}). \end{aligned} (15.3)

On its own this was unstable. Three modifications made it work.

Algorithm 15.3 (Deep Q-Network (DQN)). Parameters: replay capacity NN (one million transitions), minibatch size 3232, target period CC (ten thousand updates), discount γ=0.99\gamma = 0.99, step size α\alpha (RMSProp), exploration ε\varepsilon annealed linearly from 11 to 0.10.1 over the first million frames.

Initialize: replay memory 𝒟←∅\mathcal{D} \leftarrow \emptyset; network weights 𝐰\mathbf{w} at random; target weights 𝐰−←𝐰\mathbf{w}^- \leftarrow \mathbf{w}.

  1. Loop for each episode:
    1. Observe the first frames and form the stacked state S0S_0.
    2. Loop for each step tt until the episode ends:
      1. With probability ε\varepsilon choose AtA_t uniformly at random, otherwise At←arg⁡max⁡aq^(St,a,𝐰)A_t \leftarrow \arg\max_a \hat q(S_t, a, \mathbf{w}).
      2. Repeat AtA_t for four frames; observe the clipped reward Rt+1∈{−1,0,1}R_{t+1} \in \{-1, 0, 1\} and the next frame, and form St+1S_{t+1} by pushing it onto the stack.
      3. Store (St,At,Rt+1,St+1)(S_t, A_t, R_{t+1}, S_{t+1}) in 𝒟\mathcal{D}, discarding the oldest transition if ∣𝒟∣>N\lvert \mathcal{D} \rvert > N.
      4. Sample a minibatch {(sj,aj,rj,sj′)}j=132\{(s_j, a_j, r_j, s'_j)\}_{j=1}^{32} uniformly from 𝒟\mathcal{D} and form the targets yj=rjy_j = r_j if sj′s'_j is terminal, else yj=rj+γmax⁡a′q^(sj′,a′,𝐰−)y_j = r_j + \gamma \max_{a'} \hat q(s'_j, a', \mathbf{w}^-).
      5. Take one RMSProp step on ∑jLH(yj−q^(sj,aj,𝐰))\sum_j L_H\bigl(y_j - \hat q(s_j, a_j, \mathbf{w})\bigr), where LHL_H is the Huber loss (15.4); the targets yjy_j are treated as constants.
      6. Every CC updates, set 𝐰−←𝐰\mathbf{w}^- \leftarrow \mathbf{w}.

**Experience replay.** Transitions are stored and later sampled at random, an idea of Lin’s.Long-Ji Lin. Self-Improving Reactive Agents Based on Reinforcement Learning, Planning and Teaching. Machine Learning, 8(3–4):293–321, 1992. doi: 10.1007/BF00992699 Each transition is used many times, so learning is more data-efficient; consecutive updates are no longer strongly correlated, so their average has lower variance; and the data distribution is a slowly moving average over many past policies rather than the output of the current one, which removes one feedback loop between the weights and the data. Replay is possible only because Q-learning is off-policy: the stored action was chosen by an old policy, but the update target max⁡aq^\max_a \hat q is the value of the greedy policy whatever generated the data.

**Target network.** The targets yjy_j are computed with a copy 𝐰−\mathbf{w}^- of the weights that is refreshed only every CC updates. Between refreshes, learning is ordinary regression onto fixed targets; across refreshes, it is an approximate value iteration 𝐰−↦arg⁡min⁡𝐰𝔼[(r+γmax⁡a′q^(s′,a′,𝐰−)−q^(s,a,𝐰))2]\mathbf{w}^- \mapsto \arg\min_{\mathbf{w}} \mathbb{E}\bigl[(r + \gamma \max_{a'} \hat q(s', a', \mathbf{w}^-) - \hat q(s, a, \mathbf{w}))^2\bigr], which is fitted Q iteration with CC gradient steps per iteration.

Error clipping. The TD error was clipped to [−1,1][-1, 1] in the gradient. This is exactly the gradient of the Huber loss

LH(δ)={12δ2,∣δ∣≤1,∣δ∣−12,∣δ∣>1, L_H(\delta) = \begin{cases} \tfrac{1}{2}\delta^2, & \lvert \delta \rvert \le 1, \\ \lvert \delta \rvert - \tfrac{1}{2}, & \lvert \delta \rvert > 1, \end{cases} (15.4)

quadratic near zero and linear beyond, so that a single surprising transition cannot produce a huge step.

15.5.1DQN and the Deadly Triad

DQN contains all three elements of the deadly triad of Section 11.3: nonlinear function approximation, bootstrapping, and off-policy data. Do its modifications remove the danger? The symbolic checks below say: they reduce it, but they do not remove it. We first verify the clipping identity, then compare the two gradients one could follow for a linear q^(s,a,𝐰)=𝐰⊤𝐱(s,a)\hat q(s, a, \mathbf{w}) = \mathbf{w}^\top \mathbf{x}(s, a), and finally run the target network on the two-state counterexample of Chapter 11.

Differentiate the Huber loss (15.4) piece by piece.
const huber = await wl`Function[d, Piecewise[{{d^2/2, -1 <= d <= 1}, {d - 1/2, d > 1}}, -d - 1/2]]`
const dHuber = await wl`D[${huber}[\[Delta]], \[Delta]]`
await show`${dHuber}`
LH′(δ)={−1δ<−1∨δ=−1δ−1<δ<11True L_H'(\delta) = \begin{cases} -1 & \delta <-1\lor \delta =-1 \\ \delta & -1<\delta <1 \\ 1 & \text{True} \end{cases} The derivative coincides with clip⁡(δ,−1,1)\operatorname{clip}(\delta, -1, 1) for every real δ\delta: “clipping the error” and “using the Huber loss” are the same update.
await show`Simplify[PiecewiseExpand[${dHuber} - Clip[\[Delta], {-1, 1}]], Element[\[Delta], Reals]]`
LH′(δ)−clip⁡(δ,−1,1)=0 L_H'(\delta) - \operatorname{clip}(\delta, -1, 1) = 0

Write 𝐱=𝐱(St,At)\mathbf{x} = \mathbf{x}(S_t, A_t) and 𝐲=𝐱(St+1,a∗)\mathbf{y} = \mathbf{x}(S_{t+1}, a^*) for the feature vector of the maximizing next action. With a frozen target the loss is 12(r+γ𝐰−⊤𝐲−𝐰⊤𝐱)2\frac{1}{2}(r + \gamma \mathbf{w}^{-\top}\mathbf{y} - \mathbf{w}^\top\mathbf{x})^2; if instead the target is differentiated too, we obtain the residual-gradient loss of Chapter 11.

Negative gradients of the frozen-target loss (first row) and of the full residual loss (second row), evaluated at 𝐰−=𝐰\mathbf{w}^- = \mathbf{w} and divided by the common TD error δ\delta.
const dqnW = await wl`{Subscript[w, 1], Subscript[w, 2]}`
const dqnX = await wl`{Subscript[x, 1], Subscript[x, 2]}`
const dqnY = await wl`{Subscript[y, 1], Subscript[y, 2]}`
const dqnWm = await wl`{Subscript[v, 1], Subscript[v, 2]}`
const dqnDelta = await wl`r + \[Gamma] ${dqnW} . ${dqnY} - ${dqnW} . ${dqnX}`
await show`Simplify[({-D[(r + \[Gamma] ${dqnWm} . ${dqnY} - ${dqnW} . ${dqnX})^2/2, {${dqnW}}], -D[${dqnDelta}^2/2, {${dqnW}}]} /. Thread[${dqnWm} -> ${dqnW}])/${dqnDelta}]`
1δ(−∇𝐰12δfrozen2−∇𝐰12δ2)=(x1x2x1−γy1x2−γy2) \frac{1}{\delta}\begin{pmatrix} -\nabla_{\mathbf{w}} \tfrac12\delta_{\text{frozen}}^2 \\ -\nabla_{\mathbf{w}} \tfrac12\delta^2 \end{pmatrix} = \left( \begin{array}{cc} x_1 & x_2 \\ x_1-\gamma y_1 & x_2-\gamma y_2 \\ \end{array} \right)

The target network turns the update into the semi-gradient δ 𝐱\delta\,\mathbf{x} of (15.3), not into a true gradient: the missing term −γδ 𝐲-\gamma\delta\,\mathbf{y} is precisely what the residual-gradient method keeps. So DQN is still a semi-gradient method, and the divergence examples of Chapter 11 still apply to it. To see this, take the two states whose estimated values are ww and 2w2w, with a zero reward on the transition between them, and update only on that transition, as an off-policy distribution may do. Plain semi-gradient TD multiplies ww by 1+α(2γ−1)1 + \alpha(2\gamma - 1) at every step. With a target network, the CC inner steps regress ww onto the fixed target 2γw−2\gamma w^-:

Solve the inner recursion wk+1=wk+α(2γw−−wk)w_{k+1} = w_k + \alpha(2\gamma w^- - w_k) from w0=w−w_0 = w^- for mm steps, and give the multiplier wm/w−w_m / w^- applied at each target refresh, collected in γ\gamma.
const wInner = await wl`RSolveValue[{y[k + 1] == y[k] + \[Alpha] (2 \[Gamma] Subscript[w, "-"] - y[k]), y[0] == Subscript[w, "-"]}, y[k], k] /. k -> m`
const wMult = await show`Collect[Simplify[${wInner}/Subscript[w, "-"]], \[Gamma]]`
wmw−=(1−α)m−2(−1+(1−α)m)γ \frac{w_m}{w^-} = (1-\alpha )^m-2 \left(-1+(1-\alpha )^m\right) \gamma The multiplier minus one, factored: −((1−α)m−1)-\bigl((1-\alpha)^m - 1\bigr) is positive for 0<α<10 < \alpha < 1 and m≥1m \ge 1, so the sign is that of 2γ−12\gamma - 1.
const wGrowth = await show`Factor[${wMult} - 1]`
wmw−−1=−((−1+(1−α)m)(−1+2γ)) \frac{w_m}{w^-} - 1 = -\left(\left(-1+(1-\alpha )^m\right) (-1+2 \gamma )\right)

The multiplier per refresh is (1−α)C+2γ(1−(1−α)C)(1-\alpha)^C + 2\gamma\bigl(1 - (1-\alpha)^C\bigr), and it exceeds 11 exactly when γ>12\gamma > \frac{1}{2}, for every step size 0<α<10 < \alpha < 1 and every period CC; as C→∞C \to \infty it tends to 2γ2\gamma, the factor by which the projected Bellman operator stretches this one-dimensional subspace. A target network slows divergence down and makes each inner problem a well-posed regression, but the outer iteration diverges whenever the projected operator is not a contraction (compare Theorem A.3). What saves DQN in practice is mostly the data distribution: a large replay memory filled by a slowly changing ε\varepsilon-greedy policy is close enough to on-policy that the bad cases rarely occur.

15.5.2Results and Limits

DQN learned each game from 50 million frames (about 38 days of play), and was tested over 30 episodes of up to five minutes. It beat the best earlier learning system on 43 of the 49 games and reached at least 75% of a professional human tester’s score on 29 of them. Ablations on five games showed that replay and the target network each helped substantially and that together they helped enormously, and that a linear network on the same input was far worse. The failures were as informative as the successes: on Montezuma’s Revenge, where reward requires a long sequence of precise actions, DQN scored like a random player. ε\varepsilon-greedy exploration cannot find a reward that is hundreds of steps away; this is the problem that intrinsic motivation (Section 16.4) and the agents of Section 15.10 address.Beyond Sutton and Barto (2018). The max⁡\max in the DQN target overestimates action values, because the maximum of noisy estimates is biased upward (Exercise 15.6). Double DQN (van Hasselt, Guez and Silver, AAAI 2016) selects the maximizing action with the online weights and evaluates it with the target weights; it is treated with the other heirs of Double Q-learning in Section 6.9.3.Hado van Hasselt, Arthur Guez, and David Silver. Deep Reinforcement Learning with Double Q-Learning. In Proceedings of the Thirtieth AAAI Conference on Artificial Intelligence, volume 30, pages 2094–2100. AAAI Press, 2016. doi: 10.1609/aaai.v30i1.10295

15.6Mastering the Game of Go

Go is played on a 19×1919 \times 19 grid; about 250 legal moves per position and games of about 150 moves put exhaustive search out of reach, but the real obstacle was that nobody could write a decent evaluation function. Monte Carlo tree search (Section 8.9) had lifted programs to strong amateur level by evaluating positions with random rollouts instead. DeepMind’s AlphaGo (2016) and AlphaGo Zero (2017) added learned policies and values to MCTS and surpassed the best human players.David Silver, Aja Huang, Chris J. Maddison, Arthur Guez, Laurent Sifre, George van den Driessche, Julian Schrittwieser, Ioannis Antonoglou, Veda Panneershelvam, Marc Lanctot, Sander Dieleman, Dominik Grewe, John Nham, Nal Kalchbrenner, Ilya Sutskever, Timothy Lillicrap, Madeleine Leach, Koray Kavukcuoglu, Thore Graepel, and Demis Hassabis. Mastering the Game of Go with Deep Neural Networks and Tree Search. Nature, 529(7587):484–489, 2016. doi: 10.1038/nature16961; and 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/nature24270

15.6.1AlphaGo

AlphaGo was trained in a pipeline of four networks before it ever played a match.

  1. A 13-layer convolutional SL policy network pσp_\sigma was trained by supervised learning to predict expert moves (30 million positions), reaching 57% accuracy.
  2. An RL policy network pρp_\rho, initialized to pσp_\sigma, was improved by the REINFORCE policy gradient (Algorithm 13.4) with reward ±1\pm 1 at the end of games against randomly chosen earlier versions of itself (a pool of opponents prevents overfitting to the current one). It won 80% of its games against pσp_\sigma.
  3. A value network vθv_\theta was trained by Monte Carlo policy evaluation (Chapter 5): regression of the outcome of self-play games of pρp_\rho on the position, using one position per game (30 million games) to avoid the strong correlations within a game.
  4. A small linear rollout policy, also trained on expert moves, was about a thousand times faster than pσp_\sigma.

At play time, AlphaGo’s MCTS used pσp_\sigma as the prior for expanding the tree, and evaluated a new leaf ss by mixing the value network with the return GG of a fast rollout,

V(s)=(1−η) vθ(s)+η G. V(s) = (1 - \eta)\,v_\theta(s) + \eta\,G. (15.5)

The value network alone (η=0\eta = 0) already beat every other Go program; the best play came from η=12\eta = \frac{1}{2}, which combines an accurate but biased evaluation of a strong policy with an unbiased but noisy evaluation of a weak one. Curiously, the SL policy was a better search prior than the stronger RL policy, presumably because it spread its probability over the variety of moves humans consider. AlphaGo beat the European champion Fan Hui 5–0 and, in March 2016, the world champion Lee Sedol 4–1.

15.6.2AlphaGo Zero

AlphaGo Zero discarded human data, hand-crafted features, rollouts and the separate networks. Its input was 17 binary 19×1919 \times 19 planes: the stones of each player in the current and the seven previous positions (the history is needed because the repetition rule makes the board alone non-Markov), and the color to play. One residual network f𝜽(s)=(𝐩,v)f_{\boldsymbol\theta}(s) = (\mathbf{p}, v) had a policy head 𝐩\mathbf{p} over the 362 moves and a value head v∈[−1,1]v \in [-1, 1] predicting the outcome for the player to move. Training was a loop of self-play and fitting.

Algorithm 15.4 (AlphaGo Zero: Self-Play Policy Iteration with MCTS). Parameters: simulations per move nn (16001600), exploration constant cpuctc_{\mathrm{puct}}, root noise Dir⁡(0.03)\operatorname{Dir}(0.03) with weight 0.250.25, temperature τ\tau, regularization cc.

  1. Initialize 𝜽\boldsymbol\theta at random. Repeat:
    1. Self-play. Play games with the current network. At each position sts_t:
      1. Run nn simulations of MCTS from sts_t. Each edge stores a visit count N(s,a)N(s,a), a mean value Q(s,a)Q(s,a) and a prior P(s,a)P(s,a). A simulation descends from the root choosing aa by the PUCT rule (8.7), until it reaches a leaf sLs_L; it expands sLs_L, setting P(sL,⋅)=𝐩P(s_L, \cdot) = \mathbf{p} from (𝐩,v)=f𝜽(sL)(\mathbf{p}, v) = f_{\boldsymbol\theta}(s_L), and backs vv up along the path (with alternating sign), incrementing NN and updating QQ as a running mean. At the root, the prior is mixed with Dirichlet noise.
      2. Let 𝝅t(a)∝N(st,a)1/τ\boldsymbol\pi_t(a) \propto N(s_t, a)^{1/\tau} and play at∼𝝅ta_t \sim \boldsymbol\pi_t.
    2. When the game ends with winner known, set zt=±1z_t = \pm 1 from the point of view of the player to move at tt, and store every (st,𝝅t,zt)(s_t, \boldsymbol\pi_t, z_t).
    3. Fitting. On minibatches sampled from the recent games, take SGD steps on ℓ(𝜽)=(z−v)2−𝝅⊤log⁡𝐩+c ∥𝜽∥2. \ell(\boldsymbol\theta) = (z - v)^2 - \boldsymbol\pi^\top \log \mathbf{p} + c\,\lVert\boldsymbol\theta\rVert^2. (15.6)
    4. (AlphaGo Zero only) Let the new network play the current best; it becomes the self-play network if it wins at least 55% of 400 games.

The selection rule is the PUCT rule (8.7) of Section 8.11.1: UCB (Chapter 2) with the network’s prior in the exploration bonus U(s,a)=cpuct P(s,a)∑bN(s,b) / (1+N(s,a))U(s, a) = c_{\mathrm{puct}}\,P(s, a)\sqrt{\textstyle\sum_b N(s, b)}\,/\,\bigl(1 + N(s, a)\bigr). The bonus is large for moves the network considers likely and that have been visited little, and it decays like 1/N1/\sqrt{N} once a move’s visits grow in proportion to the total, after which QQ dominates.

Why it is policy iteration. The same section explains why the loop is generalized policy iteration (Section 4.7) with search as the improvement operator. In the terms of Algorithm 15.4: the search policy 𝝅\boldsymbol\pi, which Silver and colleagues call the output of “a powerful policy improvement operator”, is (empirically) better than 𝐩\mathbf{p}; the cross-entropy term of (15.6) projects this improvement onto the network, and the squared error moves vv toward the Monte Carlo returns zz of games played by 𝝅\boldsymbol\pi, which is policy evaluation of the improved policy. Unlike AlphaGo, AlphaGo Zero uses MCTS during training, not only at play time.

15.6.3In Wolfram Language

How does PUCT allocate visits? If all moves at a node look equally good, so that their QQ values tie, the search keeps the bonus terms UU equal. For two moves with priors P1,P2P_1, P_2 and nn visits in total, we solve for the visit counts that equalize the bonus.

Equalize P1/(1+n1)=P2/(1+n2)P_1/(1+n_1) = P_2/(1+n_2) subject to n1+n2=nn_1 + n_2 = n; the common factor cpuctnc_{\mathrm{puct}}\sqrt{n} cancels.
const puctSol = await wl`Solve[Subscript[P, 1]/(1 + Subscript[n, 1]) == Subscript[P, 2]/(1 + Subscript[n, 2]) && Subscript[n, 1] + Subscript[n, 2] == n, {Subscript[n, 1], Subscript[n, 2]}]`
await show`${puctSol}`
{{n1→−−P1−nP1+P2P1+P2,n2→−P1−P2−nP2P1+P2}} \left\{\left\{n_1\to -\frac{-P_1-n P_1+P_2}{P_1+P_2},n_2\to -\frac{P_1-P_2-n P_2}{P_1+P_2}\right\}\right\} The fraction of visits given to the first move tends to its share of the prior.
await show`Limit[(Subscript[n, 1] /. First[${puctSol}])/n, n -> Infinity]`
lim⁡n→∞n1n=P1P1+P2 \lim_{n \to \infty} \frac{n_1}{n} = \frac{P_1}{P_1+P_2}

So in the absence of value information the visit distribution reproduces the network’s prior; it departs from the prior exactly where the backed-up values disagree with it. The visit-count policy 𝝅\boldsymbol\pi is therefore the prior corrected by search, and training 𝐩\mathbf{p} on it is what makes the loop improve.

15.6.4Results

After three days and 4.9 million self-play games, AlphaGo Zero beat the version of AlphaGo that had defeated Lee Sedol in 100 games out of 100. A larger version trained for 40 days reached an Elo rating of 5,185 and beat AlphaGo Master, which had used human data and had won 60–0 against top professionals online, by 89 games to 11. A network of the same architecture trained by supervised learning predicted human moves better but played worse: the self-play program had found its own way of playing, including new variations of classical sequences. The lesson is the one TD-Gammon taught at smaller scale, now without the help of dice: a learned value function and a learned policy, combined with decision-time search and improved by self-play, can exceed human knowledge in a domain where that knowledge had been accumulated for millennia.

15.7Personalized Web Services

Choosing which news story, offer or advertisement to show a visitor is a decision under uncertainty with immediate, noisy feedback: a click. A/B testing is a two-armed bandit without context. Adding a feature vector 𝐱\mathbf{x} describing the user and the candidate items gives a contextual bandit (the associative search of Chapter 2). Li, Chu, Langford and Schapire applied one to the Yahoo! front page; their LinUCB algorithm models the click-through probability of item aa as linear, 𝐱⊤𝜽a\mathbf{x}^\top\boldsymbol\theta_a, and chooses arg⁡max⁡a[𝐱⊤𝜽^a+c𝐱⊤𝐀a−1𝐱]\arg\max_a \bigl[\mathbf{x}^\top\hat{\boldsymbol\theta}_a + c\sqrt{\mathbf{x}^\top \mathbf{A}_a^{-1}\mathbf{x}}\bigr], where 𝐀a\mathbf{A}_a is the regularized Gram matrix of the contexts in which aa was shown: UCB with the confidence width of ridge regression. It improved the click-through rate by 12.5% over a context-free bandit.Lihong Li, Wei Chu, John Langford, and Robert E. Schapire. A Contextual-Bandit Approach to Personalized News Article Recommendation. In Proceedings of the 19th International Conference on World Wide Web (WWW 2010), pages 661–670. ACM, 2010. doi: 10.1145/1772690.1772758

A bandit treats each visit as if made by a new user. Theocharous, Thomas and Ghavamzadeh argued that, since many users come back, recommendation is an MDP whose return is the number of clicks a user makes over all visits, the life-time value: a policy that leads a customer “down a sales funnel” (first financing terms, then service, then the discount) can beat one that offers the discount at once.Georgios Theocharous, Philip S. Thomas, and Mohammad Ghavamzadeh. Personalized Ad Recommendation Systems for Life-Time Value Optimization with Guarantees. In Proceedings of the Twenty-Fourth International Joint Conference on Artificial Intelligence (IJCAI), pages 1806–1812, 2015. URL https://www.ijcai.org/Proceedings/15/Papers/257.pdf On banking data with up to four million interactions they trained a greedy click predictor (a random forest) and a policy by fitted Q iteration, the batch analogue of Q-learning in which each iteration fits a regressor to the targets r+γmax⁡a′q^(s′,a′)r + \gamma\max_{a'}\hat q(s', a') computed from the previous fit. As expected, the greedy policy won on click-through rate (clicks per visit), the MDP policy on life-time value (clicks per visitor).

The decisive ingredient was not the learning algorithm but off-policy evaluation. A company cannot deploy a policy to find out whether it is bad. Data logged under a behavior policy bb (here, uniformly random offers) can however estimate the value of a target policy π\pi by importance sampling ((5.2)), and Thomas and colleagues turned such estimates into high-confidence lower bounds by applying concentration inequalities to the importance-weighted returns, so that a new policy is deployed only if, with probability at least 1−δ1 - \delta, it beats the current one.Philip S. Thomas, Georgios Theocharous, and Mohammad Ghavamzadeh. High-Confidence Off-Policy Evaluation. In Proceedings of the Twenty-Ninth AAAI Conference on Artificial Intelligence, volume 29. AAAI Press, 2015. doi: 10.1609/aaai.v29i1.9541 Adobe adopted the method in its marketing products in 2016. The basic fact underneath is unbiasedness, which we check for a one-step problem with two contexts and two offers.

The inverse-propensity estimate π(A∣X)b(A∣X)R\frac{\pi(A \mid X)}{b(A \mid X)}R averaged under the logging policy bb, minus the value of π\pi; contexts xx have probabilities ρx\rho_x and r(x,a)r(x, a) is the expected click.
await show`Simplify[Sum[Subscript[\[Rho], x] Sum[b[a, x] (\[Pi][a, x]/b[a, x]) r[x, a], {a, 1, 2}], {x, 1, 2}] - Sum[Subscript[\[Rho], x] Sum[\[Pi][a, x] r[x, a], {a, 1, 2}], {x, 1, 2}]]`
𝔼b ⁣[π(A∣X)b(A∣X) R]−𝔼π[R]=0 \mathbb{E}_b\!\left[\frac{\pi(A \mid X)}{b(A \mid X)}\,R\right] - \mathbb{E}_\pi[R] = 0

Unbiasedness is cheap; variance is the problem. With sparse clicks and many possible offers, the importance ratios are large and rare (Exercise 15.8), which is why the confidence bounds, and not the point estimates, determined what could be deployed.

15.8Thermal Soaring

Birds and gliders climb in thermals, columns of rising warm air, without flapping or engines. Reddy, Celani, Sejnowski and Vergassola asked which sensory cues are sufficient to soar in the strong turbulence that surrounds a thermal, both to understand birds and to build autonomous gliders.Gautam Reddy, Antonio Celani, Terrence J. Sejnowski, and Massimo Vergassola. Learning to Soar in Turbulent Environments. Proceedings of the National Academy of Sciences, 113(33):E4877–E4884, 2016. doi: 10.1073/pnas.1606075113 The environment was a cubic kilometer of air simulated by the fluid equations, with turbulent thermals arising from small perturbations, and a glider whose aerodynamics depend on its angle of attack and bank angle.

The case is a model of careful problem formulation. Actions: increase, decrease or keep the bank angle (by 5∘5^\circ, within ±15∘\pm 15^\circ) and the angle of attack (by 2.5∘2.5^\circ): 3×3=93 \times 3 = 9 actions. States: state aggregation (Chapter 9) of candidate cues (vertical wind velocity, vertical wind acceleration, the torque produced by the difference of vertical wind between the two wing tips, temperature), each cut into three bins. Reward: the obvious choice, altitude gained at the end of an episode with a large penalty for touching the ground, did not lead to learning in episodes of realistic length, and eligibility traces did not help; what worked was a per-step reward combining the vertical wind velocity and acceleration just experienced, a dense signal correlated with climbing. Algorithm: one-step Sarsa (Algorithm 6.6) with α=0.1\alpha = 0.1, γ=0.98\gamma = 0.98, and a soft-max policy on action values normalized to [0,1][0, 1] and divided by a temperature annealed from 22 to 0.20.2.

After a few hundred 2.5-minute episodes the glider spiralled upward inside thermals and almost never hit the ground. The scientific output was the comparison of cue sets: vertical wind acceleration and torque together were enough, because they measure the gradient of the updraft in the two directions the glider can act on (turning or not), while vertical velocity itself, temperature and control of the angle of attack added little for staying in a thermal. Policies learned in strong turbulence banked more conservatively than those learned in weak turbulence, and the altitude gained grew with γ\gamma up to about 0.990.99: soaring requires planning over tens of seconds.Beyond Sutton and Barto (2018). The same group later flew the approach on a real glider, learning in the field from measured vertical accelerations and wing-tip torques, and confirmed that these two cues suffice to climb in atmospheric thermals (Reddy et al., Nature, 2018).Gautam Reddy, Jerome Wong-Ng, Antonio Celani, Terrence J. Sejnowski, and Massimo Vergassola. Glider Soaring via Reinforcement Learning in the Field. Nature, 562(7726):236–239, 2018. doi: 10.1038/s41586-018-0533-0

15.9Lessons from the Case Studies

Read side by side, the case studies say more than any one of them.

  • The reward is a design decision. Samuel’s program drifted without one; DQN clipped rewards to make one step size fit all games; the soaring agent learned only from a dense proxy of the real objective; Watson’s designers added risk terms. Section 16.4 takes this up in general.
  • Representation decides what is learnable. TD-Gammon’s thresholds, the six queue features of the DRAM controller and the two wind cues of the glider were hand-chosen; DQN and AlphaGo Zero learned theirs, but only with very large amounts of experience and an architecture suited to images or boards.
  • Experience must come from somewhere cheap. Self-play, emulators and simulators supply the millions of episodes that deep networks need; where they cannot (web services), off-policy evaluation of logged data replaces experimentation.
  • Learning and search are complementary. Samuel, TD-Gammon 2.0–3.1, Watson’s endgame and AlphaGo all search at decision time using learned values; AlphaGo Zero also learns from search.
  • Safety can be built into the action sets. The DRAM controller explored only among legal commands; risk-sensitive wagering limited Watson’s losses.

15.10Beyond the Book: Case Studies after 2018

The years after the second edition turned these lessons into a series of landmark systems.Beyond Sutton and Barto (2018). Every system in this section appeared after the book went to press, between 2018 and 2025. Each paragraph names the paper that introduced it.

Rainbow (2018). Hessel and colleagues combined six independent improvements of DQN in one agent: double Q-learning (Section 6.9.3), prioritized replay (sampling transitions in proportion to their TD error), the dueling architecture (q^=v^+\hat q = \hat v + a centered advantage), nn-step returns ((7.1)), distributional value learning (Section 16.7.1) and noisy networks for exploration.Matteo Hessel, Joseph Modayil, Hado van Hasselt, Tom Schaul, Georg Ostrovski, Will Dabney, Dan Horgan, Bilal Piot, Mohammad Azar, and David Silver. Rainbow: Combining Improvements in Deep Reinforcement Learning. In Proceedings of the AAAI Conference on Artificial Intelligence, volume 32, pages 3215–3222. AAAI Press, 2018. doi: 10.1609/aaai.v32i1.11796 The combination beat every component on the 57-game Atari benchmark by a wide margin, and the ablations showed that prioritized replay and multi-step targets mattered most. In the terms of this companion, half of the gains come from better targets (multi-step, double, distributional) and half from better use of data.

AlphaZero and MuZero (2018, 2020). AlphaZero is Algorithm 15.4 without Go-specific details (no board symmetries, no evaluation gate, continuous updating of a single network); the same algorithm and hyperparameters reached superhuman strength in chess, shogi and Go.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 MuZero removed the last piece of given knowledge, the rules, by running the search inside a learned, value-equivalent model, and set a new state of the art on Atari, a first for a model-based agent.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-4 Both are described as planning methods in Section 8.11.1 and Section 8.11.2.

AlphaStar and OpenAI Five (2019). Real-time strategy games add partial observability, long horizons (tens of thousands of steps), huge structured action spaces and multiple agents. AlphaStar reached the Grandmaster level of StarCraft II, above 99.8% of ranked human players, by starting from imitation of human games and then training a league of agents, including “exploiters” whose only job is to find the weaknesses of the main agents, with an off-policy actor-critic (Algorithm 13.7).Oriol Vinyals, Igor Babuschkin, Wojciech M. Czarnecki, Michaël Mathieu, Andrew Dudzik, Junyoung Chung, David H. Choi, Richard Powell, Timo Ewalds, Petko Georgiev, Junhyuk Oh, Dan Horgan, Manuel Kroiss, Ivo Danihelka, Aja Huang, Laurent Sifre, Trevor Cai, John P. Agapiou, Max Jaderberg, Alexander S. Vezhnevets, Rémi Leblond, Tobias Pohlen, Valentin Dalibard, David Budden, Yury Sulsky, James Molloy, Tom L. Paine, Caglar Gulcehre, Ziyu Wang, Tobias Pfaff, Yuhuai Wu, Roman Ring, Dani Yogatama, Dario Wünsch, Katrina McKinney, Oliver Smith, Tom Schaul, Timothy Lillicrap, Koray Kavukcuoglu, Demis Hassabis, Chris Apps, and David Silver. Grandmaster Level in StarCraft II Using Multi-Agent Reinforcement Learning. Nature, 575(7782):350–354, 2019. doi: 10.1038/s41586-019-1724-z OpenAI Five beat the Dota 2 world champions with PPO, a clipped policy-gradient method, run continuously for about ten months at very large scale, with “surgery” to carry weights across architecture changes.Christopher Berner, Greg Brockman, Brooke Chan, Vicki Cheung, Przemysław Dębiak, Christy Dennison, David Farhi, Quirin Fischer, Shariq Hashme, Chris Hesse, Rafal Józefowicz, Scott Gray, Catherine Olsson, Jakub Pachocki, Michael Petrov, Henrique P. d. O. Pinto, Jonathan Raiman, Tim Salimans, Jeremy Schlatter, Jonas Schneider, Szymon Sidor, Ilya Sutskever, Jie Tang, Filip Wolski, and Susan Zhang. Dota 2 with Large Scale Deep Reinforcement Learning, 2019. OpenAI Both show that the self-play recipe of TD-Gammon extends to imperfect-information team games when the opponent population is managed explicitly.

Agent57 (2020). Badia and colleagues built the first agent to exceed the human baseline on all 57 Atari games, including Montezuma’s Revenge and Pitfall.Adrià Puigdomènech Badia, Bilal Piot, Steven Kapturowski, Pablo Sprechmann, Alex Vitvitskyi, Zhaohan Daniel Guo, and Charles Blundell. Agent57: Outperforming the Atari Human Benchmark. In Proceedings of the 37th International Conference on Machine Learning, volume 119 of Proceedings of Machine Learning Research, pages 507–517. PMLR, 2020. URL https://proceedings.mlr.press/v119/badia20a.html It learns a family of policies indexed by an exploration weight β\beta (on an intrinsic novelty reward combining episodic and lifelong novelty) and a discount γ\gamma, with separate value heads for extrinsic and intrinsic reward, and a bandit meta-controller that chooses which member of the family to run. It is DQN’s descendant equipped with the intrinsic motivation and the GVF-like multiple predictions of Chapter 16.

Control of real physical systems (2022–2023). Three Nature papers moved deep RL from games to hardware, all following the same pattern: train an actor-critic in a high-fidelity simulator, then deploy the frozen policy. Degrave and colleagues controlled the plasma of the TCV tokamak in Lausanne, commanding all 19 magnetic coils directly from sensor measurements to hold several plasma shapes, including two droplets at once.Jonas Degrave, Federico Felici, Jonas Buchli, Michael Neunert, Brendan Tracey, Francesco Carpanese, Timo Ewalds, Roland Hafner, Abbas Abdolmaleki, Diego de las Casas, Craig Donner, Leslie Fritz, Cristian Galperti, Andrea Huber, James Keeling, Maria Tsimpoukelli, Jackie Kay, Antoine Merle, Jean-Marc Moret, Seb Noury, Federico Pesamosca, David Pfau, Olivier Sauter, Cristian Sommariva, Stefano Coda, Basil Duval, Ambrogio Fasoli, Pushmeet Kohli, Koray Kavukcuoglu, Demis Hassabis, and Martin Riedmiller. Magnetic Control of Tokamak Plasmas through Deep Reinforcement Learning. Nature, 602(7897):414–419, 2022. doi: 10.1038/s41586-021-04301-9 Gran Turismo Sophy beat the world’s best drivers of the Gran Turismo racing simulator, with a reward that had to encode racing etiquette as well as speed.Peter R. Wurman, Samuel Barrett, Kenta Kawamoto, James MacGlashan, Kaushik Subramanian, Thomas J. Walsh, Roberto Capobianco, Alisa Devlic, Franziska Eckert, Florian Fuchs, Leilani Gilpin, Piyush Khandelwal, Varun Kompella, HaoChih Lin, Patrick MacAlpine, Declan Oller, Takuma Seno, Craig Sherstan, Michael D. Thomure, Houmehr Aghabozorgi, Leon Barrett, Rory Douglas, Dion Whitehead, Peter Dürr, Peter Stone, Michael Spranger, and Hiroaki Kitano. Outracing Champion Gran Turismo Drivers with Deep Reinforcement Learning. Nature, 602(7896):223–228, 2022. doi: 10.1038/s41586-021-04357-7 Swift beat three human champions at first-person-view drone racing on a physical track, using a policy trained in simulation and corrected with residual models of perception and dynamics estimated from real flights.Elia Kaufmann, Leonard Bauersfeld, Antonio Loquercio, Matthias Müller, Vladlen Koltun, and Davide Scaramuzza. Champion-Level Drone Racing Using Deep Reinforcement Learning. Nature, 620(7976):982–987, 2023. doi: 10.1038/s41586-023-06419-4 The lesson echoes the DRAM controller: the decisive engineering lies in the simulator, the reward and the sim-to-real gap, not in the update rule.

Algorithm discovery (2022–2023). AlphaTensor cast the search for a matrix multiplication algorithm as a single-player game whose moves subtract rank-one tensors from the multiplication tensor; an AlphaZero-style agent found, for instance, a 4×44 \times 4 algorithm in modular arithmetic with 47 multiplications, against 49 for Strassen’s method applied twice.Alhussein Fawzi, Matej Balog, Aja Huang, Thomas Hubert, Bernardino Romera-Paredes, Mohammadamin Barekatain, Alexander Novikov, Francisco J. R. Ruiz, Julian Schrittwieser, Grzegorz Swirszcz, David Silver, Demis Hassabis, and Pushmeet Kohli. Discovering Faster Matrix Multiplication Algorithms with Reinforcement Learning. Nature, 610(7930):47–53, 2022. doi: 10.1038/s41586-022-05172-4 AlphaDev played a game of writing assembly instructions and discovered sorting routines for short sequences that were faster than the human benchmarks and were merged into the LLVM C++ standard library.Daniel J. Mankowitz, Andrea Michi, Anton Zhernov, Marco Gelmi, Marco Selvi, Cosmin Paduraru, Edouard Leurent, Shariq Iqbal, Jean-Baptiste Lespiau, Alex Ahern, Thomas Köppe, Kevin Millikin, Stephen Gaffney, Sophie Elster, Jackson Broshear, Chris Gamble, Kieran Milan, Robert Tung, Minjae Hwang, Taylan Cemgil, Mohammadamin Barekatain, Yujia Li, Amol Mandhane, Thomas Hubert, Julian Schrittwieser, Demis Hassabis, Pushmeet Kohli, Martin Riedmiller, Oriol Vinyals, and David Silver. Faster Sorting Algorithms Discovered Using Deep Reinforcement Learning. Nature, 618(7964):257–263, 2023. doi: 10.1038/s41586-023-06004-9 Here MCTS with learned values is a tool for combinatorial search in mathematics and software.

Language models (2022–2025). The largest deployment of reinforcement learning since the book is the fine-tuning of language models; its algorithms (RLHF with a learned reward model and PPO, DPO, GRPO) are derived in Section 13.8.7, and here we note only what the case studies taught. When the goal is “be helpful” there is no score to read off, so the reward itself was learned from human comparisons; a 1.3-billion-parameter InstructGPT model tuned this way was preferred by labelers to the 175-billion-parameter GPT-3, and the KL penalty to the supervised model acts as a defense against exploiting the learned reward’s errors.Paul F. Christiano, Jan Leike, Tom B. Brown, Miljan Martic, Shane Legg, and Dario Amodei. Deep Reinforcement Learning from Human Preferences. In Isabelle Guyon, Ulrike von Luxburg, Samy Bengio, Hanna Wallach, Rob Fergus, S. V. N. Vishwanathan, and Roman Garnett, editors, Advances in Neural Information Processing Systems 30 (NIPS 2017), volume 30, pages 4299–4307. Curran Associates, Inc., 2017; and Long Ouyang, Jeff Wu, Xu Jiang, Diogo Almeida, Carroll L. Wainwright, Pamela Mishkin, Chong Zhang, Sandhini Agarwal, Katarina Slama, Alex Ray, John Schulman, Jacob Hilton, Fraser Kelton, Luke Miller, Maddie Simens, Amanda Askell, Peter Welinder, Paul F. Christiano, Jan Leike, and Ryan Lowe. Training Language Models to Follow Instructions with Human Feedback. In S. Koyejo, S. Mohamed, A. Agarwal, D. Belgrave, K. Cho, and A. Oh, editors, Advances in Neural Information Processing Systems 35 (NeurIPS 2022), volume 35, pages 27730–27744. Curran Associates, Inc., 2022. doi: 10.52202/068431-2011 DeepSeek-R1 went the other way, training on problems whose answers can be checked automatically (mathematics with known results, code with tests) with rule-based rewards for correctness and format; starting from a pre-trained model without supervised reasoning examples, long chains of reasoning with self-verification emerged from reward alone.Daya Guo, Dejian Yang, Haowei Zhang, Junxiao Song, Peiyi Wang, Qihao Zhu, Runxin Xu, Ruoyu Zhang, Shirong Ma, Xiao Bi, et al. DeepSeek-R1 Incentivizes Reasoning in LLMs through Reinforcement Learning. Nature, 645(8081):633–638, Springer Nature, 2025. doi: 10.1038/s41586-025-09422-z. Preprint: DeepSeek-AI, “DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning”, arXiv:2501.12948 (2025) This is the most visible instance of Sutton and Barto’s thesis that a scalar reward can drive the acquisition of complex behavior, and of their warning that what is optimized is what is rewarded.

These systems also show where the methods of Parts I and II run out. Agent57 needed intrinsic rewards and many simultaneous predictions, MuZero a learned model, AlphaStar a memory of past observations in place of a Markov state, and the language models a reward that had to be learned or verified. Each of these is one of the frontiers that Sutton and Barto survey in their last chapter, and the subject of Chapter 16.

15.11Exercises

Exercise 15.5. Let v^(s,𝐰)=βf(s)+𝐰⊤𝐱(s)\hat v(s, \mathbf{w}) = \beta f(s) + \mathbf{w}^\top \mathbf{x}(s), where ff is Samuel’s piece-advantage feature with fixed weight β≠0\beta \neq 0 and 𝐰\mathbf{w} is learned by TD without rewards and without terminal values. Show that if ff lies in the span of the learnable features plus a constant (for instance f=x1−x2f = x_1 - x_2 for two learnable features), there is a 𝐰\mathbf{w} for which v^\hat v is constant, and hence a fixed point of TD learning by Proposition 15.2. What change to the problem removes all such fixed points?

Solution

If f=𝐜⊤𝐱+kf = \mathbf{c}^\top\mathbf{x} + k for some vector 𝐜\mathbf{c} and constant kk, choose 𝐰=−β𝐜\mathbf{w} = -\beta\mathbf{c}. Then v^(s,𝐰)=β(𝐜⊤𝐱(s)+k)−β𝐜⊤𝐱(s)=βk\hat v(s, \mathbf{w}) = \beta(\mathbf{c}^\top\mathbf{x}(s) + k) - \beta\mathbf{c}^\top\mathbf{x}(s) = \beta k for every ss, a constant, so every TD error v^(St+1)−v^(St)\hat v(S_{t+1}) - \hat v(S_t) is zero and the expected update vanishes. The fixed weight constrains the direction of v^\hat v in weight space but not its values. Giving terminal positions their true values (+1+1 for a win, 00 or −1-1 otherwise), or equivalently a reward at the end of the game, makes the TD target at the last step independent of 𝐰\mathbf{w}; the Bellman equation then has the win probability as its unique solution, and a constant v^\hat v produces nonzero TD errors at the end of every game.

Exercise 15.6. Two actions have the same true value μ\mu, and their estimates X1,X2X_1, X_2 are independent 𝒩(μ,σ2)\mathcal{N}(\mu, \sigma^2). Compute 𝔼[max⁡(X1,X2)]\mathbb{E}[\max(X_1, X_2)] and explain why the target of (15.3) is biased upward. How does Double DQN remove the bias in this example?

Solution

Write max⁡(X1,X2)=12(X1+X2)+12∣X1−X2∣\max(X_1, X_2) = \frac{1}{2}(X_1 + X_2) + \frac{1}{2}\lvert X_1 - X_2 \rvert. The first term has mean μ\mu; the difference X1−X2X_1 - X_2 is 𝒩(0,2σ2)\mathcal{N}(0, 2\sigma^2).

The mean absolute value of the difference of two independent estimates.
await show`Expectation[Abs[d], d \[Distributed] NormalDistribution[0, Sqrt[2] \[Sigma]], Assumptions -> \[Sigma] > 0]`
𝔼∣X1−X2∣=2σπ \mathbb{E}\lvert X_1 - X_2 \rvert = \frac{2 \sigma }{\sqrt{\pi }}

Hence 𝔼[max⁡(X1,X2)]=μ+σ/π>max⁡(𝔼X1,𝔼X2)=μ\mathbb{E}[\max(X_1, X_2)] = \mu + \sigma/\sqrt{\pi} > \max(\mathbb{E}X_1, \mathbb{E}X_2) = \mu. The target max⁡aq^(s′,a)\max_a \hat q(s', a) inherits this bias at every state, and bootstrapping propagates it backward. Double DQN uses one estimate to choose the action and an independent one to evaluate it: 𝔼[Xarg⁡max⁡iXi′]=μ\mathbb{E}[X'_{\arg\max_i X_i}] = \mu when X′X' is independent of XX, because the choice carries no information about the noise of the evaluating estimate. With the online and target networks the two estimates are only partly independent, so the bias is reduced rather than removed.

Exercise 15.7. In AlphaGo Zero the policy head is 𝐩=softmax⁡(𝐡)\mathbf{p} = \operatorname{softmax}(\mathbf{h}) for logits 𝐡\mathbf{h}. Show that the gradient of the cross-entropy term −𝝅⊤log⁡𝐩-\boldsymbol\pi^\top\log\mathbf{p} of (15.6) with respect to 𝐡\mathbf{h} is 𝐩−𝝅\mathbf{p} - \boldsymbol\pi. Compare with the REINFORCE update for a soft-max policy in Chapter 13: which target replaces the one-hot vector of the sampled action?

SolutionGradient of the cross-entropy for three moves, with π3=1−π1−π2\pi_3 = 1 - \pi_1 - \pi_2, minus 𝐩−𝝅\mathbf{p} - \boldsymbol\pi.
const smH = await wl`{Subscript[h, 1], Subscript[h, 2], Subscript[h, 3]}`
const smPi = await wl`{Subscript[\[Pi], 1], Subscript[\[Pi], 2], 1 - Subscript[\[Pi], 1] - Subscript[\[Pi], 2]}`
await show`Simplify[D[-${smPi} . Log[Exp[${smH}]/Total[Exp[${smH}]]], {${smH}}] - (Exp[${smH}]/Total[Exp[${smH}]] - ${smPi})]`
∇𝐡(−𝝅⊤log⁡softmax⁡(𝐡))−(𝐩−𝝅)={0,0,0} \nabla_{\mathbf{h}}\bigl(-\boldsymbol\pi^\top \log \operatorname{softmax}(\mathbf{h})\bigr) - (\mathbf{p} - \boldsymbol\pi) = \{0,0,0\}

In general −∑bπblog⁡pb=−∑bπbhb+log⁡∑cehc-\sum_b \pi_b \log p_b = -\sum_b \pi_b h_b + \log\sum_c e^{h_c} (using ∑bπb=1\sum_b \pi_b = 1), whose derivative in hah_a is −πa+pa-\pi_a + p_a. A gradient step therefore moves the logits by α(𝝅−𝐩)\alpha(\boldsymbol\pi - \mathbf{p}). For a soft-max policy, REINFORCE moves them by α G (𝐞A−𝐩)\alpha\,G\,(\mathbf{e}_{A} - \mathbf{p}), where 𝐞A\mathbf{e}_A is the one-hot vector of the sampled action, weighted by the return. AlphaGo Zero replaces the single sampled action, weighted by its return, with the whole search distribution 𝝅\boldsymbol\pi, unweighted: the search has already done the credit assignment, which is why the policy update has much lower variance than a policy gradient.

Exercise 15.8. A website shows one of KK offers uniformly at random (b(a)=1/Kb(a) = 1/K) and logs clicks R∈{0,1}R \in \{0, 1\}. The target policy π\pi always shows offer 11, whose click probability is p1p_1. Compute the mean and variance of the importance-sampling estimate X=π(A)b(A)RX = \frac{\pi(A)}{b(A)}R. How many logged visits are needed for a standard error of p1/10p_1/10 when p1=0.01p_1 = 0.01 and K=12K = 12?

Solution

X=KX = K if the logged offer was 11 and it was clicked, and X=0X = 0 otherwise, so X=K BX = K\,B with BB Bernoulli with success probability p1/Kp_1/K.

Mean and variance of X=K Bernoulli(p1/K)X = K\,\mathrm{Bernoulli}(p_1/K).
await show`With[{d = TransformedDistribution[K x, x \[Distributed] BernoulliDistribution[Subscript[p, 1]/K]]}, Simplify[{Mean[d], Variance[d]}]]`
(𝔼X,  Var⁡X)={p1,(K−p1)p1} \bigl(\mathbb{E}X,\; \operatorname{Var}X\bigr) = \left\{p_1,\left(K-p_1\right) p_1\right\}

The estimate is unbiased, but its variance p1(K−p1)≈Kp1p_1(K - p_1) \approx K p_1 grows linearly with the number of offers. With nn visits the standard error is p1(K−p1)/n\sqrt{p_1(K - p_1)/n}; setting it to p1/10p_1/10 gives n=100 (K−p1)/p1=100×11.99/0.01≈120,000n = 100\,(K - p_1)/p_1 = 100 \times 11.99/0.01 \approx 120{,}000 visits to estimate a one-step policy to 10% relative accuracy. For multi-step policies the ratios multiply along the trajectory, which is why high-confidence off-policy evaluation needs millions of interactions, and why the bounds, not the estimates, govern deployment.