14.1 Markov Decision Processes

Picture a robot crossing a frozen lake, a program playing a board game, or a language model writing an answer one token at a time. Each choice changes what happens next: the robot slips into a different cell, the game reaches a different position, the answer takes a different turn. The reward may come only at the end, and the same command may have several outcomes. Before we can ask how to act well, we need a way to write such a problem down: what the decision maker knows at each step, what it can do, what follows, and what it is trying to achieve.

Bellman gave this description its form in a 1957 paper on Markovian decision processes (Bellman, 1957). His idea was to put everything about the past that matters for the future into a state, so that the consequences of an action depend only on the state in which it is taken. That one assumption makes the problem tractable. Once the future depends on the present state alone, a single number per state can say how good it is to be there. The resulting model, the Markov decision process (MDP), became a standard tool of operations research (Puterman, 1994). Every method in this chapter and the next works on it, from dynamic programming to the training of language models with a reward.

We work on a sixteen-cell frozen lake, small enough that every quantity can be checked by hand. It still has the feature that makes acting over time hard: on slippery ice the agent often slides somewhere other than where it meant to go. We read the lake's transition table out of a simulator and name its parts, then define the return an agent maximizes and the discount that keeps it finite. We ask what a state must contain, and we examine a bonus that looks helpful but pays the agent for going in circles. A second, even smaller example closes the section: a language model answering arithmetic questions, scored by a checker.

The chapter uses the symbols of Table 14.1.1. Those of this section are defined below; the others belong to later sections, which define each where it is first used.

Table 14.1.1. Symbols of the reinforcement-learning chapters. The rows from VπV^\pi on belong to later sections, and those from λ\lambda on to Chapter 15. The exploration rate ϵ\epsilon and the per-step disagreement ε\varepsilon are different symbols, and so are a response yy and a value target yty_t. A μ\mu with a subscript or argument other than 0 is a mean (an arm's, a Gaussian's).
SymbolMeaningIntroduced in
S\mathcal{S}, A\mathcal{A}the sets of states and actionsSection 14.1
sts_t, ata_t, rtr_tthe state, action and reward at step ttSection 14.1
P(s′∣s,a)P(s' \mid s, a)transition kernel: the probability of reaching s′s' from ss under action aaSection 14.1
r(s,a)r(s, a)expected reward of action aa at state ssSection 14.1
μ0\mu_0start-state distribution (for language models, the distribution of prompts)Section 14.1
τ\tautrajectory (s0,a0,r0,s1,…)(s_0, a_0, r_0, s_1, \ldots)Section 14.1
γ\gammadiscount factorSection 14.1
R(τ)R(\tau)return of a trajectory, ∑tγtrt\sum_t \gamma^t r_tSection 14.1
TTnumber of steps of an episode, or a time limitSection 14.1
π(a∣s)\pi(a \mid s), π(s)\pi(s)policy: probability of action aa at state ss; the action of a deterministic policySection 14.1, Section 14.2
ℓ(s)\ell(s)Manhattan distance from cell ss to the goalSection 14.1
Φ(s)\Phi(s)potential of a shaping bonusSection 14.1
xx, yy, r(x,y)r(x, y)prompt, response, and the verifier's score of the responseSection 14.1
yty_ttarget of a value update: an estimate of the return from step ttSection 14.1, Section 14.9
VπV^\pi, QπQ^\piexpected return under π\pi from a state, from a state-action pairSection 14.2
V∗V^*, Q∗Q^*the same under an optimal policySection 14.2
T\mathcal{T}Bellman operator: one step of lookahead applied to a vector of valuesSection 14.2
δ\delta, δt\delta_ttemporal-difference error of one transition, of the transition at step ttSection 14.3
α\alphastep size of temporal-difference updatesSection 14.3
ϵ\epsilonexploration rate of ϵ\epsilon-greedy action selectionSection 14.3
πe\pi_ebehavior policy, the one that chooses the actions while a method learnsSection 14.3
κ\kappaweight of the uncertainty bonusSection 14.4
KKnumber of responses sampled per promptSection 14.4
πθ\pi_\theta, θ\thetapolicy with parameters θ\thetaSection 14.1 (the verifier's preference table), Section 14.5
dtπd^\pi_t, dγπd^\pi_\gammadistribution of sts_t under π\pi; its discounted average over ttSection 14.5, Section 14.7
ε\varepsilonper-step probability that a cloned policy disagrees with the expertSection 14.5
xt\mathbf{x}_t, ut\mathbf{u}_t, A\mathbf{A}, B\mathbf{B}, Q\mathbf{Q}, R\mathbf{R}continuous state and control; linear dynamics and quadratic cost matricesSection 14.6
Pt\mathbf{P}_t, Kt\mathbf{K}_tRiccati cost-to-go matrix and linear state-feedback gain matrixSection 14.6
J(θ)J(\theta)expected return of πθ\pi_\thetaSection 14.7
η\etastep size of a policy updateSection 14.7
G^t\hat{G}_treward-to-go: the discounted sum of the rewards from step tt onSection 14.8
bbbaseline subtracted from a returnSection 14.8
ηV\eta_Vstep size of a value-baseline updateSection 14.8
AπA^\piadvantage Qπ−VπQ^\pi - V^\piSection 14.8
λ\lambdaweight of the λ\lambda-returnSection 15.1
ww, w−w^-parameters of a value network; of its frozen or Polyak-averaged copySection 15.1, Section 15.4
nndepth of an nn-step target, or of a planSection 15.1, Section 15.6
ρt\rho_timportance ratio πθ(at∣st)/πθold(at∣st)\pi_\theta(a_t \mid s_t) / \pi_{\theta_{\textrm{old}}}(a_t \mid s_t) at step ttSection 15.2
ϵclip\epsilon_{\textrm{clip}}half-width of the clip band of the ratioSection 15.2
ΔKL\Delta_{\textrm{KL}}a KL budget per updateSection 15.2
πref\pi_{\textrm{ref}}, β\betareference policy; weight of the KL penalty, and soft actor-critic's temperatureSection 15.3, Section 15.5
r^\hat{r}a fitted rewardSection 15.3, Section 15.6
ν\nuPolyak rate of a target networkSection 15.5
f^ϕ\hat{f}_\phia learned transition modelSection 15.6
import gymnasium as gym

14.1.1 The Model#

Figure 14.1.1 shows the lake: FrozenLake from the Gymnasium suite (Towers et al., 2024), which the tabular sections of this chapter share. The agent starts in the top-left cell and tries to reach the goal at the bottom right, which pays a reward of one. Four cells are holes, and entering a hole or the goal ends the attempt. On slippery ice a command moves the agent in the intended direction with probability 1/31/3 and in each of the two perpendicular directions with probability 1/31/3. A move off the edge of the grid leaves the agent where it is.

Figure 14.1.1:

The lake. (a) S marks the start, G the goal, and the gray cells marked H are holes; each cell carries its state index. On calm ice the shortest path takes six moves. (b) One command on slippery ice: from state s=9s = 9 the action down lands in cell 13, 8 or 10 with probability 1/31/3 each. The intended move is one of three equally likely outcomes, and the probabilities sum to one.

Consider the agent in cell 9, three moves from the goal. Three of its four commands can slide it into the hole at cell 5, one time in three each. Only down cannot, but down also slides it sideways two times in three, into cell 8 or 10. Is the safety of down worth the steps it loses sliding sideways? To compare commands we need to know where each can lead, what the agent can do from there, and what it receives at the end.

14.1.1.1 States, Actions and the Transition Kernel#

The state of the lake is the agent's cell. The set of states S={0,1,…,15}\mathcal{S} = \{0, 1, \ldots, 15\} numbers the cells row by row. The actions are the four commands left, down, right and up, encoded as 0 to 3; they form the set A\mathcal{A}. On slippery ice an action determines a distribution over next states, and Gymnasium stores this distribution as a table that we can read directly:

env = gym.make('FrozenLake-v1', is_slippery=True)
LEFT, DOWN, RIGHT, UP = 0, 1, 2, 3
ARROWS = '<v>^'                        # one glyph per action, for printing
env.unwrapped.P[9][DOWN]
[(0.33333333333333337, 8, 0, False),
 (0.3333333333333333, 13, 0, False),
 (0.33333333333333337, 10, 0, False)]

The output lists three outcomes, each of the form (probability, next state, reward, terminated). Commanded down from cell 9, the agent reaches 8, 13 or 10 with probability 1/31/3 each, as in Figure 14.1.1. In symbols, this table is the transition kernel P(s′∣s,a)P(s' \mid s, a), the probability of reaching state s′s' from state ss under action aa. For each pair (s,a)(s, a) the numbers P(⋅∣s,a)P(\cdot \mid s, a) form a distribution, so ∑s′∈SP(s′∣s,a)=1\sum_{s' \in \mathcal{S}} P(s' \mid s, a) = 1.

The fourth ingredient is the reward. The simulator pays one for the step that enters the goal and zero for every other step, so the reward of a step depends on where the step lands. We work with its average over the landing cell, the expected reward r(s,a)r(s, a) of action aa at state ss; exercise 3 shows that the averaging changes no expected return. Together, the four objects form the MDP:

MDP:(S,A,P,r).(14.1.1)\textrm{MDP}: \quad (\mathcal{S}, \mathcal{A}, P, r). \tag{14.1.1}

The first three describe the environment. The reward describes the task, and whoever sets the task chooses it, a difference that the section on reward design turns on. Some treatments add the discount factor defined below to this tuple, or let the reward be random or depend on the next state. Our r(s,a)r(s, a) then plays the role of the expected reward, and nothing in this chapter loses generality from the simpler form.

14.1.2 Return, Discount and Horizon#

The agent starts at a state s0s_0 drawn from a start-state distribution μ0\mu_0, which for the lake puts all its mass on cell 0. At each step tt the agent is at state sts_t, takes action ata_t, receives reward rtr_t, and moves to a next state st+1∼P(⋅∣st,at)s_{t+1} \sim P(\cdot \mid s_t, a_t). The sequence of these quantities is a trajectory,

τ=(s0,a0,r0,s1,a1,r1,s2,a2,r2,…).\tau = (s_0, a_0, r_0, s_1, a_1, r_1, s_2, a_2, r_2, \ldots).

The reward rtr_t in a trajectory is the realized one that the simulator pays; the expected reward r(st,at)r(s_t, a_t) is its average given sts_t and ata_t.

A rule for choosing actions is called a policy; we write π(a∣s)\pi(a \mid s) for the probability that it picks action aa in state ss. The simplest one picks each of the four commands with probability 1/41/4, whatever the state. We run it once from cell 0 and print every step:

rng = np.random.default_rng(8)
s, _ = env.reset(seed=8)
terminated = truncated = False
total, t = 0.0, 0
while not (terminated or truncated):
    a = int(rng.integers(4))
    s_next, r, terminated, truncated, _ = env.step(a)
    print(f"t={t:>2}  s={s:>2}  a={ARROWS[a]}  s'={s_next:>2}  r={r:.0f}")
    total, s, t = total + r, s_next, t + 1
print(f'terminated={terminated}, truncated={truncated}, total reward={total:.0f}')
t= 0  s= 0  a=>  s'= 0  r=0
t= 1  s= 0  a=v  s'= 0  r=0
t= 2  s= 0  a=<  s'= 4  r=0
t= 3  s= 4  a=^  s'= 4  r=0
t= 4  s= 4  a=<  s'= 4  r=0
t= 5  s= 4  a=v  s'= 8  r=0
t= 6  s= 8  a=>  s'= 9  r=0
t= 7  s= 9  a=^  s'=10  r=0
t= 8  s=10  a=>  s'=11  r=0
terminated=True, truncated=False, total reward=0

The transcript shows the kernel at work. At t=0t=0 the agent commands right and stays in cell 0, because the ice slid it into the wall above. At t=2t=2 it commands left and slides down to cell 4. At t=8t=8 it commands right from cell 10 and enters the hole at cell 11, which ends the attempt with terminated=True. No step entered the goal, so every reward is zero. To score a trajectory that does reach the goal, we must first decide how much a late reward counts.

14.1.2.1 Discounting and the Effective Horizon#

Why not simply add the rewards? A trajectory can be infinitely long. The policy that always commands up never leaves the top row of the lake: up runs into the wall, and its two slips move along the row. With a positive reward on every step, the sum along such a trajectory grows without bound. A reward now is also usually worth more than the same reward later. Both concerns lead to a discount factor 0≤γ<10 \leq \gamma \lt 1, which weights the reward of step tt by γt\gamma^t. The return of a trajectory is the discounted sum

R(τ)=r0+γr1+γ2r2+⋯=∑t=0∞γtrt.(14.1.2)R(\tau) = r_0 + \gamma r_1 + \gamma^2 r_2 + \cdots = \sum_{t=0}^\infty \gamma^t r_t. \tag{14.1.2}

With γ=0.95\gamma = 0.95 a reward one step away counts 0.950.95, and a reward twenty steps away counts about 0.360.36. The goal is to act so that the return is as large as possible on average, over the draws of the kernel, the start state and the agent's own choices. We maximize this expected return because it is what many independent attempts collect on average. For a finite MDP with γ<1\gamma \lt 1 the problem has a definite answer (Puterman, 1994). There is one policy that is best from every start state at once, and it can be chosen deterministic and independent of time: one command per cell. So the best policy does not depend on where the agent starts, and a start-state distribution concentrated on one cell loses nothing.

The discount also controls how far ahead the agent looks. If every reward satisfies ∣rt∣≤rmax⁡|r_t| \leq r_{\max}, discounting keeps the return finite and bounds the part of it that lies beyond step kk:

∣R(τ)∣≤rmax⁡1−γ,∣∑t≥kγtrt∣≤γk rmax⁡1−γ.\begin{aligned} |R(\tau)| &\leq \frac{r_{\max}}{1 - \gamma}, \\ \Big| \sum_{t \geq k} \gamma^t r_t \Big| &\leq \frac{\gamma^k \, r_{\max}}{1 - \gamma}. \end{aligned}

The first bound makes the objective finite. The second says that rewards beyond step kk can move the return by at most a fraction γk\gamma^k of its largest possible size. This suggests measuring the reach of the discount in steps, by the effective horizon 1/(1−γ)1/(1-\gamma). For γ\gamma near one, γ1/(1−γ)≈e−1\gamma^{1/(1-\gamma)} \approx e^{-1}, so the weights fall by a factor of about ee per horizon. For a constant reward stream, 95 percent of the discounted weight then lies within log⁡(0.05)/log⁡(γ)\log(0.05)/\log(\gamma) steps, about three horizons. The table below lists both step counts for four discounts, together with the weight γ5\gamma^5 that the goal's reward receives at the end of the six-move shortest path on calm ice:

print(f'{"gamma":>6} {"horizon 1/(1-gamma)":>20} {"t: gamma^t < 0.05":>18} '
      f'{"gamma^5":>8}')
for g in [0.5, 0.9, 0.95, 0.99]:
    t95 = int(np.ceil(np.log(0.05) / np.log(g)))
    print(f'{g:>6} {1 / (1 - g):>20.0f} {t95:>18} {g**5:>8.3f}')
 gamma  horizon 1/(1-gamma)  t: gamma^t < 0.05  gamma^5
   0.5                    2                  5    0.031
   0.9                   10                 29    0.590
  0.95                   20                 59    0.774
  0.99                  100                299    0.951

At γ=0.95\gamma = 0.95, the discount used throughout this chapter, the horizon is 20 steps, 95 percent of the weight lies within 59 steps, and a goal reached in six moves is worth γ5≈0.774\gamma^5 \approx 0.774. At γ=0.5\gamma = 0.5 the same goal is worth about 0.030.03. Figure 14.1.2 shows these quantities. The discount is part of the task, chosen by its designer: a small γ\gamma makes the agent short-sighted, but exercise 8 shows that it can make planning with an inaccurate model more reliable.

Figure 14.1.2:

Discounting defines an effective horizon. (a) The weight γt\gamma^t of a reward tt steps away falls below 0.050.05 at t=5t = 5 for γ=0.5\gamma = 0.5, at t=29t = 29 for γ=0.9\gamma = 0.9, at t=59t = 59 for γ=0.95\gamma = 0.95, and only at t=299t = 299 for γ=0.99\gamma = 0.99. (b) The horizon 1/(1−γ)1/(1-\gamma) on a logarithmic axis: two steps at γ=0.5\gamma = 0.5, twenty at γ=0.95\gamma = 0.95 and a hundred at γ=0.99\gamma = 0.99.

14.1.2.2 The Model as Arrays#

Dynamic programming reads the kernel, the reward and the discount many times over, and every later tabular section checks its learner against those exact computations. The dictionary of tuples that Gymnasium exposes is awkward for that. We want PP as one array indexed by (s,a,s′)(s, a, s') and rr as one array indexed by (s,a)(s, a), so that an average over next states becomes one matrix product. TabularMDP holds the three objects. Its from_gym method builds the arrays from the simulator's table: it adds up outcomes that lead to the same next state, and it averages the reward over the outcomes, which gives the expected reward r(s,a)r(s, a). We save the class to the d2l library, since every tabular section of the chapter uses it:

class TabularMDP:
    """A finite MDP as dense arrays: P[s, a, s'] and r[s, a]."""
    def __init__(self, P, r, gamma):
        self.P, self.r, self.gamma = P, r, gamma
        self.num_states, self.num_actions = r.shape

    @classmethod
    def from_gym(cls, env, gamma):
        """Read the transition table Gymnasium exposes as env.unwrapped.P."""
        n_s, n_a = env.observation_space.n, env.action_space.n
        P, r = np.zeros((n_s, n_a, n_s)), np.zeros((n_s, n_a))
        for s, actions in env.unwrapped.P.items():
            for a, outcomes in actions.items():
                for p, s_next, reward, _ in outcomes:
                    P[s, a, s_next] += p      # several outcomes may share s'
                    r[s, a] += p * reward     # r(s,a) is the expected reward
        return cls(P, r, gamma)

We build the lake's model with γ=0.95\gamma = 0.95 and print the row of the command we read from the simulator above:

gamma = 0.95
mdp = TabularMDP.from_gym(env, gamma)
print(mdp.P[9, DOWN])
[0.         0.         0.         0.         0.         0.
 0.         0.         0.33333333 0.         0.33333333 0.
 0.         0.33333333 0.         0.        ]

The list of tuples has become a dense row of sixteen numbers: 1/31/3 in columns 8, 10 and 13, zero elsewhere. Two checks, one per array, confirm the construction. Every row of PP must sum to one, and the reward must be nonzero only where the goal can be entered:

print(f'largest |row sum - 1|: {np.abs(mdp.P.sum(axis=-1) - 1).max():.1e}')
for s, a in np.argwhere(mdp.r > 0):
    print(f'r(s={s}, a={ARROWS[a]}) = {mdp.r[s, a]:.3f}')
largest |row sum - 1|: 0.0e+00
r(s=14, a=v) = 0.333
r(s=14, a=>) = 0.333
r(s=14, a=^) = 0.333

Every row of PP sums to one. The reward array is zero except in cell 14, the only frozen cell next to the goal. There down, right and up each reach the goal with probability 1/31/3 and so have expected reward 1/31/3, while none of the three outcomes of left is the goal. The lake pays its reward only on the step that enters the goal.

14.1.2.3 Episodes, Termination and Truncation#

A state that ends the process is terminal; on the lake, the holes and the goal are terminal. A run from the start to a terminal state is an episode. The simulator stops an episode there and must be reset. Gymnasium's table, and so TabularMDP, stores each terminal state as an absorbing state whose actions lead back to itself with zero reward, so that every row of PP is a distribution. The two descriptions give the same returns, since the absorbing state collects nothing more.

When every episode ends after finitely many steps, discounting is not needed to keep the return finite, and γ=1\gamma = 1 is allowed: the return is then the plain sum of the rewards of an episode with TT steps. On the lake not every episode ends, since the always-up policy circles the top row forever, but γ=1\gamma = 1 is still safe there: rewards are nonnegative and a trajectory collects at most one. It is not safe in general. With a reward of +0.05+0.05 per step, the same always-up policy would have an infinite undiscounted return. Tasks that never end, such as controlling the heating of a building, therefore use γ<1\gamma \lt 1. Maximizing the long-run reward per step is the other common choice for such tasks; this chapter does not treat it.

Gymnasium separates two ways in which an episode can stop. terminated=True means that the process entered a terminal state: nothing more can happen, and the value of continuing is zero. truncated=True means that recording stopped, usually because of a time limit, while the agent stands in a state from which the process would go on. gym.make gives FrozenLake such a limit: after 100 steps the episode ends with truncated=True, even if the agent stands on frozen ice from where the goal can still be reached. Figure 14.1.3 shows both cases. The sum of rewards of a truncated episode is therefore not its return, since it misses everything after the cut. A method that estimates the value of continuing from the last state must treat them differently: the value is zero after termination, and after truncation it is whatever the last state is worth, its value V(s)V(s), the expected return from ss on, which Section 14.2 defines precisely. Every method in this chapter that estimates the value of continuing sets it to zero on terminated alone.

Figure 14.1.3:

Two ways an episode stops. (a) Terminated: the episode enters the hole s8s_8, a terminal state. Nothing follows, so the value of continuing from it, V(s8)V(s_8), is zero, and the target for the last step, y7y_7, the return counted from that step, is the last reward r7r_7 alone. (b) Truncated: the 100-step time limit cuts the recording while the agent stands on frozen ice, from where the process would go on. The unrecorded future is worth V(s100)V(s_{100}), the value of continuing from the last recorded state, which is not zero, so an estimate of the return from the last step, y99=r99+γV(s100)y_{99} = r_{99} + \gamma V(s_{100}), must include it.

14.1.3 The Choice of State#

The kernel P(s′∣s,a)P(s' \mid s,a) conditions on the current state and action, and on nothing else. This is the Markov property: once the present state is known, the earlier history says nothing more about the next state. It is what keeps the model small. Because the future depends on the present state alone, how good it is to be in a state can be summarized by one number per state, whatever path led there. On the lake the property holds by construction. The simulator samples the next cell from the row P[s][a] that we read above and draws each slip afresh. Whether the property holds in general depends on what we call the state.

14.1.3.1 State Augmentation#

Suppose the recorded state sts_t is a vehicle's location and the action ata_t is its acceleration. The next location also depends on the current velocity, which the current location alone does not reveal. Velocity can be inferred from two successive locations, so the next location depends on two past ones,

st+1=f(st,at,st−1),(14.1.3)s_{t+1} = f(s_t, a_t, s_{t-1}), \tag{14.1.3}

and the location by itself is not Markov. Defining the state as the pair (location, velocity) resolves the problem: Newtonian dynamics determine the next location and velocity from the current pair and the applied acceleration. The Markov property is therefore a property of how we represent the state, not only of the physical system.

This construction is called state augmentation: the state is enlarged until it contains what is needed to predict the future. The enlarged state can be large, and the information it needs can be unknown, too large to store, or impossible to observe. A time limit that is part of the task is a simple case: with 100 steps allowed, the best command in a cell can depend on how many steps remain, and adding that count to the state restores the property (exercise 5).

14.1.3.2 Partial Observability#

Augmentation requires the added variables to be observable. A poker player cannot see the opponents' cards. When the agent receives an observation oto_t that reveals only part of the state, the problem is a partially observable MDP. An exact solution tracks the agent's belief, the posterior distribution of the hidden state given everything observed so far (exercise 7). In practice agents approximate it with memory. Early Atari agents stacked the last few frames, since one frame shows positions but not velocities. Current agents carry a recurrent state or attend over their whole history, as a language model does over its context. The rest of this chapter assumes that the agent observes a Markov state.

14.1.4 Reward Design#

The states, actions and kernel describe the environment; the reward describes the task, and the designer chooses it. An optimizer maximizes whatever reward is written down, including any difference between that reward and what the designer meant (Krakovna et al., 2020). The lake shows how this happens in a few lines of arithmetic.

FrozenLake's reward is sparse: it is zero on every step except the one that enters the goal. An agent that has never reached the goal has seen nothing but zeros, so it is tempting to help it along. Let ℓ(s)\ell(s) be the Manhattan distance from cell ss to the goal, the number of moves it would take if no hole were in the way, and pay a bonus of 0.30.3 for every move that gets closer:

r~(s,a,s′)=r(s,a)+0.3 1(ℓ(s′)<ℓ(s)).(14.1.4)\tilde r(s, a, s') = r(s, a) + 0.3\, \mathbf{1}\big(\ell(s') \lt \ell(s)\big). \tag{14.1.4}

The bonus seems to point the agent toward the goal, but it can be collected without ever finishing. Take the two cells next to the goal on the bottom row, 13 and 14, with ℓ=2\ell = 2 and ℓ=1\ell = 1, and suppose for the moment that the ice is calm. The move from 14 to 13 earns nothing and costs nothing, and the move back earns 0.30.3. From cell 14, entering the goal collects 1.31.3, the reward and the bonus, and ends the episode. Shuttling to 13 and back instead collects 0.30.3 on every second step, forever, which at γ=0.95\gamma = 0.95 is worth 0.3γ/(1−γ2)≈2.90.3\gamma/(1 - \gamma^2) \approx 2.9. The flaw is that the bonus pays for moving closer but charges nothing for moving away, so it adds up to a positive amount around any loop. Randløv and Alstrøm (1998) met the same flaw in a simulated bicycle that was rewarded for progress toward a goal and learned to ride in circles.

A bonus that cannot be collected around a loop must charge for each move away what it pays for the move back. Bonuses of the form

r~(s,a,s′)=r(s,a)+γΦ(s′)−Φ(s),(14.1.5)\tilde r(s, a, s') = r(s, a) + \gamma \Phi(s') - \Phi(s), \tag{14.1.5}

for some function Φ:S→R\Phi: \mathcal{S} \to \mathbb{R} called a potential, have this property. Around a loop that returns to its start, the differences Φ(s′)−Φ(s)\Phi(s') - \Phi(s) cancel, so apart from the effect of discounting a loop earns nothing. This construction is called potential-based shaping. With Φ(s)=−0.3 ℓ(s)\Phi(s) = -0.3\,\ell(s) it pays 0.3150.315 for the move from 13 to 14 and charges 0.270.27 for the move back. Shuttling forever from cell 14 now collects 0.30.3 in total, while entering the goal still collects 1.31.3: the shaped reward keeps the goal ahead of the loop by exactly the one that the original reward pays. Figure 14.1.4 puts the two bonuses side by side on this loop. Such a bonus is still useful: a potential spreads the goal's reward over the route, which gives a learner a signal long before it first reaches the goal.

Figure 14.1.4:

Two bonuses on the cells 13 and 14 beside the goal G, on calm ice. Each arrow carries the shaped reward of its move. (a) The approach bonus pays 0.30.3 for the move toward the goal and nothing for the move back, so shuttling forever from cell 14 is worth 2.92.9, more than the 1.31.3 for entering the goal. (b) The potential Φ=−0.3 ℓ\Phi = -0.3\,\ell pays 0.3150.315 for the move toward the goal and charges 0.270.27 for the move back. Shuttling is now worth only 0.30.3, and entering the goal is the better choice.

One condition remains: the potential must be zero at the terminal states. The simulator stops at a terminal state, so a nonzero potential there would leave a final term that depends on which terminal state the episode ends in, and when. Such a term can change which behavior is best. Our Φ=−0.3 ℓ\Phi = -0.3\,\ell is zero at the goal but not at the holes, so it must be set to zero there. What the approach bonus does to the best policy on slippery ice is computed in Section 14.2, which also proves that the potential form leaves the best policy unchanged.

14.1.5 Two Special Cases#

Two kinds of MDP recur in this chapter, because each removes one difficulty of the lake. When there is only one state, each round consists of choosing an action and observing a reward, and no action affects the future. This is the multi-armed bandit, named after a row of slot machines whose payout rates a player must discover by playing; it isolates the question of which actions to try, which Section 14.4 studies. The second case keeps the future but removes the randomness of the transitions, and it describes a language model writing a response.

14.1.5.1 Text Generation as an MDP#

A language model that writes a response one token at a time fits the MDP with simple dynamics. The state is the prompt together with the tokens written so far, the action is the next token, and the transition appends that token to the state with probability one. The reward arrives once, when the response is complete: a checker called a verifier compares the response with a known answer, or a learned model scores it. Two properties set this MDP apart from the lake. The transitions are deterministic, so all randomness comes from the policy. And the state is the whole prefix, so no state is ever visited twice, and the states form a tree rooted at the prompt.

With deterministic transitions, a single reward at the end, and no revisits, the expected return depends only on the probability that the policy gives to each complete response. Nothing is lost by treating the whole response as one action chosen at the prompt. The MDP then collapses to one step: the prompt xx, drawn from a distribution μ0\mu_0 over prompts, is the state; a complete response yy is the action; and the verifier's score r(x,y)r(x, y) is the reward. This is why methods for language models can score and update whole responses. Section 15.8 returns to the token-level view.

14.1.5.2 The Verifier Task#

We make the one-step view concrete with an instance small enough to compute exactly, the second running example of this chapter. It has four arithmetic prompts and nine candidate responses shared by all of them. The verifier pays one when a response equals the prompt's answer exactly, and zero otherwise. Two of the prompts, 8*8 and 9*9, have no correct candidate, so no policy can score more than 0.50.5 on average over the prompts. The ninth candidate, "one of 4, 12, 64 or 81", lists every answer at once. The exact-match verifier rejects this hedge, but a lenient checker that accepts any response containing the answer would pay it on every prompt, the problem of reward design in another form.

The policy stands in for a pretrained language model. It is a table θ\theta of preferences with one row per prompt and one column per response, turned into probabilities by a softmax over each row, π(y∣x)∝exp⁡θxy\pi(y \mid x) \propto \exp \theta_{xy}, as in softmax regression. The reference table θref\theta_{\textrm{ref}} is zero except for the hedge column, which is −4-4. A reference response is therefore one of the eight ordinary candidates with probability about 1/81/8 each, and the hedge with probability about 0.20.2 percent. The class VerifierTask collects these pieces. Its method verify(x, y) is the checker, and its attribute R holds the checker's rewards as a table, one row per prompt and one column per response. Its method policy(theta) applies the softmax to each row of a preference table. Its method success(pi) is the expected score of one sampled response, averaged over the four prompts: the expected return of this one-step MDP, with μ0\mu_0 uniform over the prompts. An optional reward argument scores the policy under another checker instead. Training changes the table; here we only score the reference:

class VerifierTask:
    """Four prompts, nine candidate responses shared by all of them, an
    exact-match verifier, and a reference policy that rarely hedges."""
    prompts = ['2+2', '3*4', '8*8', '9*9']
    answers = ['4', '12', '64', '81']
    resp = ['1', '3', '4', '7', '12', '19', '23', '35',
            'one of 4, 12, 64 or 81']          # the last one is the hedge

    def __init__(self):
        self.theta_ref = np.zeros((len(self.prompts), len(self.resp)))
        self.theta_ref[:, -1] = -4.0           # the reference rarely hedges
        self.pi_ref = self.policy(self.theta_ref)
        self.R = self.reward_table(self.verify)   # R[x, y] = r(x, y)

    def verify(self, x, y):
        """The verifier: reward 1 iff response y is prompt x's answer."""
        return float(self.resp[y] == self.answers[x])

    def reward_table(self, reward):
        """reward(x, y) for every prompt x (rows) and response y (columns)."""
        return np.array([[reward(x, y) for y in range(len(self.resp))]
                         for x in range(len(self.prompts))])

    @staticmethod
    def policy(theta):
        """pi(y | x): a softmax over each prompt's row of preferences."""
        z = np.exp(theta - theta.max(1, keepdims=True))
        return z / z.sum(1, keepdims=True)

    def success(self, pi, reward=None):
        """E r(x, y), y ~ pi(. | x), averaged over the prompts; r = verify
        unless another reward function is given."""
        R = self.R if reward is None else self.reward_table(reward)
        return (pi * R).sum(1).mean()

task = VerifierTask()
print(f'success of a response sampled from the reference: '
      f'{task.success(task.pi_ref):.3f}')
success of a response sampled from the reference: 0.062

A response sampled from the reference passes the verifier with probability 0.0620.062. On each of the two answerable prompts the correct candidate has probability about 1/81/8, and the other two prompts contribute nothing, so the average is about 1/161/16. Training on this task has to close the gap between 0.0620.062 and the ceiling of 0.50.5.

We can now write a decision problem down: the lake as two arrays and a discount, the verifier task as a table of scores, and for each the return that a trajectory earns. A model of this kind can be queried at any state and action, which is what model-based methods use; model-free methods see only the transitions that the agent's own experience produces. The question posed at cell 9 is still open. Comparing down with right requires the return that each command can lead to, and that depends on what the agent does in every cell it may reach next. Section 14.2 computes these values for all cells at once.

14.1.6 Summary#

A Markov decision process writes a problem of acting over time as states, actions, a transition kernel and a reward, (S,A,P,r)(\mathcal{S}, \mathcal{A}, P, r), under the assumption that the present state carries everything about the past that matters for the future. The agent maximizes the expected discounted return; the discount γ\gamma keeps the return finite and sets an effective horizon of 1/(1−γ)1/(1-\gamma) steps, with weights that fall by a factor of about ee per horizon when γ\gamma is near one. Terminal states end the process, while truncation only stops the recording, so the value of continuing is zero only after termination. When the obvious state is not Markov, augmenting it restores the property if the missing information can be observed. The reward is a design choice: a bonus that can be collected around a loop changes what the agent does, while a potential-based bonus cannot be collected that way. FrozenLake and the four-prompt verifier task, a token MDP collapsed to one step, are the running examples of the chapter.

14.1.7 Exercises#

  1. What the state must contain. In each system below the obvious state is not Markov. Name the smallest addition that restores the Markov property, and say whether the agent can observe it.

    1. A delivery robot whose state is its location, when every move drains its battery by an amount that depends on the terrain and on the load it carries, and the robot stops once the battery is empty.
    2. A recommender whose state is the user's profile, when the user's interest in a topic falls with the number of recent recommendations of that topic.
    3. A chess program whose state is the arrangement of the pieces on the board, when the game ends in a draw as soon as a position occurs for the third time, or as soon as fifty moves by each player pass without a capture or a pawn move.

    In which of the three systems can the addition grow with the length of the episode, and what keeps it bounded there?

  2. [code] Episodes from the kernel. The example trajectory τ\tau of this section draws every action uniformly at random with rng.integers(4). Under this policy π\pi the next state has the distribution

Pπ(s′∣s)=14∑a∈AP(s′∣s,a),(14.1.6)P_\pi(s' \mid s) = \frac{1}{4} \sum_{a \in \mathcal{A}} P(s' \mid s, a), \tag{14.1.6}

which is mdp.P.mean(axis=1).

  1. from_gym accumulates probabilities with += because several of Gymnasium's outcomes for one state-action pair can lead to the same next state. Find every pair at which this happens, and explain from Figure 14.1.1 why these pairs and no others. If the line that fills P assigned with = instead, which rows of mdp.P would no longer sum to one, and what would they sum to?
  2. Let dtπd^\pi_t be the distribution of sts_t, starting from d0π=μ0d^\pi_0 = \mu_0, the point mass on state 0, so that dt+1π(s′)=∑sdtπ(s)Pπ(s′∣s)d^\pi_{t+1}(s') = \sum_{s} d^\pi_t(s) P_\pi(s' \mid s). Plot, for t≤30t \leq 30, the probability that the agent has reached the goal, the probability that it has fallen into a hole, and the probability that its episode is still running. What are the limits as t→∞t \to \infty?
  3. Ignoring the time limit of env, show that the mean episode length equals ∑t≥0Pr⁡(st is not terminal)\sum_{t \geq 0} \Pr(s_t \textrm{ is not terminal}). Run 10,000 episodes of env with the random policy, and compare the fraction of episodes that reach the goal and the mean episode length with the values that dtπd^\pi_t predicts. The 100-step limit of env ends a random episode with probability below 10−810^{-8}, so it does not affect the comparison.
  1. Expected rewards. Gymnasium attaches its reward to the transition: entering the goal pays one. from_gym replaces this reward ρ(s,a,s′)\rho(s, a, s') by its expectation r(s,a)=∑s′P(s′∣s,a) ρ(s,a,s′)r(s, a) = \sum_{s'} P(s' \mid s, a)\, \rho(s, a, s').

    1. Show that for every policy and every start state the expected discounted return is the same whether step tt pays ρ(st,at,st+1)\rho(s_t, a_t, s_{t+1}) or r(st,at)r(s_t, a_t). Extend the argument to a reward that is drawn at each visit of (s,a)(s, a), independently of everything else, from a distribution with mean r(s,a)r(s, a).
    2. Under the convention r(s,a)r(s, a), which FrozenLake episodes have a positive return? For the uniformly random policy of this section, estimate from 10,000 episodes the probability of a positive return under each of the two conventions. Which properties of the return does the model (14.1.1) therefore determine, and which does it not?
  2. Discount as termination. The discounted return (14.1.2) weights the reward of step tt by γt\gamma^t.

    1. This section locates 95 percent of the discounted weight within log⁡(0.05)/log⁡(γ)\log(0.05) / \log(\gamma) steps and calls this about three effective horizons. Show that for every fraction p∈(0,1)p \in (0, 1)
ln⁡(1/p)ln⁡(1/γ)≤ln⁡(1/p)1−γ,(14.1.7)\frac{\ln(1/p)}{\ln(1/\gamma)} \leq \frac{\ln(1/p)}{1 - \gamma}, \tag{14.1.7}

and that the ratio of the two sides tends to one as γ→1\gamma \to 1. Use the inequality to explain the step counts of Figure 14.1.2 at γ=0.5\gamma = 0.5, 0.90.9 and 0.990.99.

  1. Modify an MDP so that after every reward the process moves, with probability 1−γ1 - \gamma, to an absorbing state with zero reward, and otherwise moves according to PP. Show that the expected undiscounted return of every policy in the modified process equals its expected discounted return in the original, and that the expected number of rewards collected is 1/(1−γ)1 / (1 - \gamma). Read the arrays of TabularMDP in these terms: what do the row sums of γP\gamma P mean?
  1. Time limits. gym.make wraps FrozenLake in a time limit: after 100 steps the episode ends with truncated=True (Section 14.1.2.3). Suppose that the limit is part of the task: the objective is the probability of entering the goal within 100 steps. Model the end of the limit as a move to an absorbing state. Show that the distribution of the next state then depends on the number hh of steps that remain, so that the location alone is not a Markov state, whereas the pair (s,h)(s, h) is (Pardo et al., 2018). Why can the best action at a location depend on hh?

  2. Actions without consequences. A multi-armed bandit has a single state, so no action can influence the future.

    1. Suppose more generally that the kernel does not depend on the action, P(s′∣s,a)=P(s′∣s)P(s' \mid s, a) = P(s' \mid s) for all aa. Show that for every γ\gamma the policy that picks an action in arg⁡max⁡ar(s,a)\arg\max_a r(s, a) at every state maximizes the expected discounted return from every start state.
    2. Construct an MDP with two states and two actions in which this greedy policy is optimal for small γ\gamma and not for large γ\gamma, and find the value of γ\gamma at which the optimal action changes.
  3. Belief states. ● In a partially observable MDP the agent receives an observation oto_t, drawn with probability O(ot∣st)O(o_t \mid s_t), instead of the state sts_t. Its belief βt(s)=Pr⁡(st=s∣o0,a0,…,at−1,ot)\beta_t(s) = \Pr(s_t = s \mid o_0, a_0, \ldots, a_{t-1}, o_t) is the posterior over the hidden state given everything observed so far (Kaelbling et al., 1998).

    1. Using the Markov property of the hidden states, derive the update
βt+1(s′)∝O(ot+1∣s′)∑s∈SP(s′∣s,at) βt(s).(14.1.8)\beta_{t+1}(s') \propto O(o_{t+1} \mid s') \sum_{s \in \mathcal{S}} P(s' \mid s, a_t)\, \beta_t(s). \tag{14.1.8}
  1. Show that the belief is a Markov state: given βt\beta_t and ata_t, the distribution of βt+1\beta_{t+1} and the expected reward do not depend on earlier observations. What are the state space and the kernel of the resulting MDP over beliefs?
  2. In a T-maze adapted from Bakker (2001), the agent observes a cue at the start, left or right with probability 1/21/2 each, then moves one cell per step through NN corridor cells that all produce the same observation, and then reaches a junction. Turning toward the cue there gives reward one, and turning away gives zero. Show that a policy that acts on the kk most recent observations succeeds with probability at most 1/21/2 unless k≥N+2k \geq N + 2. What is the belief at the junction, and how much memory suffices to act optimally? Why does stacking a few frames work for Pong but not here?
  1. [extended] Planning horizon and model error. ●● The discount γ\gamma of the objective is fixed by the task, but a planner may compute its policy with a smaller planning discount γ′\gamma'. Jiang et al. (2015) found that when the model is estimated from data, γ′<γ\gamma' \lt \gamma can yield a better policy than γ′=γ\gamma' = \gamma. Let Vγπ(s)V^\pi_\gamma(s) be the expected discounted return from ss under policy π\pi and discount γ\gamma. Part (b) uses the value iteration and exact policy evaluation of Section 14.2 (d2l.value_iteration and TabularMDP.policy_value).
    1. Let rewards lie in [0,rmax⁡][0, r_{\max}] and let γ′≤γ\gamma' \leq \gamma. Show that for every policy π\pi and state ss
0≤Vγπ(s)−Vγ′π(s)≤(γ−γ′) rmax⁡(1−γ)(1−γ′),(14.1.9)0 \leq V^\pi_\gamma(s) - V^\pi_{\gamma'}(s) \leq \frac{(\gamma - \gamma')\, r_{\max}}{(1 - \gamma)(1 - \gamma')}, \tag{14.1.9}

and conclude that on the true model the policy that is optimal for γ′\gamma' loses at most this amount under γ\gamma.

  1. Reproduce their experiment at small scale with TabularMDP. Draw 100 random MDPs with 10 states and 2 actions: for each state-action pair, choose 5 next states uniformly without replacement, give them weights drawn uniformly from [0,1][0, 1], and normalize; draw each r(s,a)r(s, a) uniformly from [0,1][0, 1]. For each MDP and each n∈{2,5,10,20}n \in \{2, 5, 10, 20\}, build 20 estimated kernels P^\hat P from nn next states sampled per pair, keeping the true rr. Compute the optimal policy of each estimated model for γ′∈{0,0.1,…,0.9,0.99}\gamma' \in \{0, 0.1, \ldots, 0.9, 0.99\}, evaluate it on the true model at γ=0.99\gamma = 0.99, and average the loss Vγ∗(s)−Vγπ(s)V^*_\gamma(s) - V^\pi_\gamma(s) over states, kernels and MDPs, where Vγ∗V^*_\gamma is the value of the optimal policy of the true model. Value iteration needs about log⁡(10−8)/log⁡γ′\log(10^{-8})/\log\gamma' sweeps, about 2,000 at γ′=0.99\gamma' = 0.99 and far fewer below; with that schedule the experiment takes a few minutes of CPU time. Plot the loss against γ′\gamma' for each nn.
  2. Which γ′\gamma' minimizes the loss for each nn, and how does it move with nn? Explain the shape of the curves with two sources of loss, the horizon bias bounded in this problem and the error of P^\hat P, and say which of the two grows with γ′\gamma'.

Discussions