14.7 Policy Gradient
In Section 14.5 a policy learned from an expert, taking one ascent step on the log-probability of each demonstrated action with every action weighted by one. In Section 14.6 a planner differentiated known transition equations to compute backward Riccati gains. Now suppose there is neither an expert nor a known differentiable model of the environment—only the agent's own attempts and the reward each attempt earned. An obvious guess keeps the cloning update and changes the weights: push up the log-probability of every action the agent took, weighted by the return of the episode it belongs to, so that actions from episodes that paid off become more likely. Is this guess principled? How does the expected return change when the parameters of the policy move?
Ronald Williams answered this question in 1992 (Williams, 1992). The average of the guessed update is the gradient of the expected return, so the guess is stochastic gradient ascent, and he called the algorithm REINFORCE. The return of an episode depends on the environment's transition probabilities, which the agent does not know, yet the estimate needs only sampled episodes and the policy's own log-probabilities. Writing the policy down as a function also lifts a limit of the value tables of Section 14.3. Acting greedily on a table needs a maximum over a finite list of actions, whereas a parameterized policy can output a torque, or a distribution over a vocabulary of tokens. The same identity, applied to the next-token distribution of a language model, trains reasoning models from a single reward given to the finished answer.
We derive the estimator from the smallest problem with a policy gradient and run it on the verifier task of Section 14.1, where every gradient can be computed exactly, and on the lake. It is right on average, but it needs fresh episodes after every update, and a small batch leaves much noise.
import gymnasium as gym14.7.1 Parameterizing the Policy#
Gradient ascent needs a policy that changes smoothly with its parameters. A deterministic policy is an argmax, which is piecewise constant: a small change of the parameters either changes nothing or switches the action. The probabilities of a stochastic policy can move by any small amount.
14.7.1.1 Softmax Preferences#
Policy.tabular from Section 14.5 stores one parameter , called a preference, for each state-action pair. A softmax over the actions turns the preferences at state into probabilities:
This is the softmax regression of Section 3.1 with a state index as its input, the same policy that behavior cloning fitted. The zero table gives the uniform policy. Unlike , a preference is not an estimate of return; adding the same constant to every preference at a state leaves the policy unchanged.
14.7.1.2 The Score Function#
The softmax is easy to differentiate. Since , the derivative with respect to the preference of any action at the same state is
and the derivative with respect to the preferences at every other state is zero. The vector is called the score function. In words, increasing the log-probability of means raising its own preference and lowering every preference at in proportion to its probability. Writing for the indicator vector of action , the row of the score at is . Its components sum to zero, so the score has no component along the one direction that leaves the policy unchanged, adding a constant to every preference at . We check the formula against automatic differentiation of Policy.log_prob at a random table:
rng = np.random.default_rng(0)
check = d2l.Policy.tabular(16, 4)
with torch.no_grad(): # move to a generic table, off the uniform start
check.policy.weight.copy_(torch.as_tensor(rng.standard_normal((16, 4))))
check.log_prob(torch.tensor([6]), torch.tensor([2])).backward()
probs = np.exp(check.log_prob_np(np.repeat(6, 4), np.arange(4)))
hand = np.zeros((16, 4), dtype=np.float32)
hand[6], hand[6, 2] = -probs, 1 - probs[2]
print(bool(torch.allclose(check.policy.weight.grad, torch.as_tensor(hand),
atol=1e-6)))True
The gradient of the library's log_prob at state 6 and action 2 matches (14.7.2), and it is zero in every other row of the table.
14.7.2 The Policy Gradient#
What is the gradient of the expected return, and can it be estimated from the agent's own episodes? The answer is cleanest with one state, and it keeps its form for trajectories.
14.7.2.1 The Smallest Case#
Take one state and two actions with preferences and . Action 1 earns reward and action 2 earns . Write . The expected reward is , and by (14.7.2) its derivative with respect to is . Suppose that we could not compute but could only try actions. The derivative can still be written as an average over the policy's own actions. Multiply and divide each term by :
So one sampled action, its reward multiplied by its score, is an estimate of the derivative. With probability the sample is action 1, whose reward is and whose score is ; with probability the reward is zero and so is the estimate. The mean is , the derivative itself. The second moment is , so the standard deviation is , which is
times the mean. When the paying action is rare, the estimate is right on average and useless in almost every single draw: it is usually zero, and occasionally about times too large. Averaging independent draws divides the ratio by .
The lake has the same structure at the start of learning. The uniform policy reaches the goal in about of episodes (Section 14.2), on calm and slippery ice alike, because a uniformly random command is a uniformly random move. An episode that misses earns nothing. At the ratio is , and a batch of 16 episodes contains no success at all with probability . Four batches in five then give an estimate of zero. The rest of this section carries out the same computation with trajectories in place of the two actions.
14.7.2.2 An Optimization Problem over Trajectories#
On the lake an episode is a trajectory that ends at the first terminal state , so its length is random. The agent chooses each action and the environment chooses each next state, so the probability of a trajectory is a product of the policy's factors, the transition kernel's factors, and the start distribution of Section 14.1:
Only the policy's factors depend on . The objective is the expected return over these trajectories, with :
The lake has a fixed start state, so in the notation of Section 14.2. On the verifier task is the uniform distribution over the four prompts.
14.7.2.3 The Log-Derivative Trick#
The step of the smallest case applies unchanged. The return of a fixed trajectory does not depend on ; only its probability does. Moving the gradient inside the sum and multiplying and dividing by gives
that is,
The identity is called the log-derivative trick. It turns the gradient back into an average over the trajectories that the current policy produces, which we can sample. The sum over trajectories is infinite, because an episode can last any number of steps. Moving the gradient inside is still allowed: under a softmax policy every state has a positive probability of reaching a terminal state within a few steps, so long episodes are exponentially rare, and each step adds a score of bounded length.
14.7.2.4 Cancellation of the Transition Probabilities#
The gradient still contains , and contains the transition kernel, which the agent does not know. The logarithm of the product (14.7.4) is a sum, and only the policy's terms survive differentiation:
Figure 14.7.1 shows the chain of factors. The start distribution and the kernel do not depend on , so their logarithms have zero gradient. The kernel still decides which trajectories we sample, but the estimator never evaluates it. This is what makes the method model-free, and it names the assumption the derivation needs: the dynamics must not depend on the policy's parameters (exercise 1 drops it).
The probability of a trajectory as a chain of factors, . Only the policy factors (blue, above the chain) depend on . The start distribution and the transition kernel (gray, below) do not, so their logarithms have zero gradient, and the score of a trajectory is the sum of the policy's scores, which can be computed without knowing .
14.7.2.5 The REINFORCE Estimator#
Substituting the sum of scores into (14.7.6) and replacing the expectation by an average over trajectories sampled from the current policy gives
Each trajectory pushes up the log-probability of every action it took, by an amount proportional to its return. This is the guess of the opening, and each term has expectation , so is an unbiased estimate of the gradient. REINFORCE (Williams, 1992) takes the ascent step with a step size , then samples a new batch from the updated policy. On the lake every return is nonnegative, so every sampled action is pushed up. Actions that were not sampled lose probability through the part of the score, and an episode with return zero changes nothing.
Figure 14.7.2 draws one step for a one-step problem with a continuous action, which a softmax over four actions cannot show as a curve. The policy is a Gaussian , whose score with respect to the mean is . An episode is a single action , so its return is that action's reward, and the step reads : the mean moves toward the sampled actions that paid most. Twelve samples move it to , where the exact gradient would give .
One REINFORCE step on a one-step problem. The policy is with , and the reward is , so the expected reward is and the exact gradient is . (a) Twelve sampled actions each push up their own log-probability, weighted by their rewards; all rewards are positive, so every arrow points up. (b) The step with moves the mean from to , toward the actions with higher reward; the exact gradient would have moved it to .
14.7.3 REINFORCE on the Running Examples#
The verifier task has one step per episode and no transitions, so every quantity can be computed exactly. The lake has episodes of several steps and a transition kernel that the update never reads.
14.7.3.1 The Verifier Task#
The verifier task of Section 14.1 has four arithmetic prompts and nine candidate responses shared by all of them. The policy is a table with one row of preferences per prompt, is the softmax of row , and the verifier pays for the correct answer and otherwise. A trajectory is a single response to a prompt, with probability and no kernel at all. Row of affects only the expected score of prompt , , and by (14.7.2) with the prompt in place of the state, its exact gradient is a sum of nine terms:
REINFORCE replaces this sum by an average over sampled responses. verifier_step samples responses for every prompt, turns their rewards into weights with the function weighting, and moves the row of by lr times the weighted average of the scores. With weighting = lambda r: r the weights are the rewards and the step is (14.7.7); Section 14.8 passes other weightings. The checker is the argument reward, so the same step can train against a different verifier.
def verifier_step(task, theta, K, reward, rng, weighting, lr=2.0):
"""One REINFORCE step on a VerifierTask: K responses per prompt, each
score e_y - pi(.|x) (eq_softmax_score) weighted by weighting(rewards of
the prompt's K responses), averaged over the K, one ascent step."""
pi, g = task.policy(theta), np.zeros_like(theta)
eye = np.eye(len(task.resp))
for x in range(len(task.prompts)): # one group of K per prompt
ys = rng.choice(len(task.resp), K, p=pi[x])
w = weighting(np.array([reward(x, y) for y in ys]))
g[x] = (eye[ys] - pi[x]).T @ w / K
return theta + lr * gThe exact-match verifier pays only the correct response , so the estimate for prompt is , where counts the correct responses among the . The count is binomial with success probability , so the estimate has mean , the exact gradient, and relative standard deviation : the ratio of the smallest case divided by . At the reference table on the two answerable prompts, so a group of should be off by about of the gradient's length.
The next cell checks this prediction. It draws 10,000 estimates at the reference table (with lr=1.0 the step minus is the estimate) and takes one step with :
task = d2l.VerifierTask()
theta0, pi0, R = task.theta_ref, task.policy(task.theta_ref), task.R
exact = pi0 * R - pi0 * (pi0 * R).sum(axis=1, keepdims=True) # nine terms
rng = np.random.default_rng(0)
U = np.stack([verifier_step(task, theta0, 16, task.verify, rng, lambda r: r,
lr=1.0) - theta0 for _ in range(10_000)])
err = lambda u: np.linalg.norm(u - exact) / np.linalg.norm(exact)
print(f'one K=16 estimate is off by '
f'{np.sqrt(np.mean([err(u) ** 2 for u in U])):.2f} of the gradient (RMS)')
print('the mean of M of them: ' + ', '.join(
f'M={M}: {err(U[:M].mean(axis=0)):.3f}' for M in (10, 100, 1000, 10_000)))
print(f'groups without a success, per prompt: '
f'{np.round((U == 0).all(axis=-1).mean(axis=0), 2)}')
after = [task.success(task.policy(theta0 + 2.0 * u)) for u in U]
print(f'success {task.success(pi0):.3f}; one step with lr = 2 gives '
f'{task.success(task.policy(theta0 + 2.0 * exact)):.3f} (exact gradient),'
f' median {np.median(after):.3f} (sampled)')one K=16 estimate is off by 0.66 of the gradient (RMS)
the mean of M of them: M=10: 0.126, M=100: 0.061, M=1000: 0.047, M=10000: 0.009
groups without a success, per prompt: [0.12 0.12 1. 1. ]
success 0.062; one step with lr = 2 gives 0.077 (exact gradient), median 0.077 (sampled)
One estimate is off by of the gradient's length, as predicted. The error of the mean of estimates keeps falling as grows, on average like , and shows no floor: the estimator is unbiased. Each estimate amounts to one binomial count per answerable prompt, so a single average can land well below that rate or up to about twice above it. On each answerable prompt about of the groups contain no correct response, , and contribute nothing. On 8*8 and 9*9, where no candidate passes the verifier, every group is empty: no amount of sampling produces a gradient for a prompt that no response solves. One exact step with raises the success from to , and a sampled step does about as well in the median. A sampled step never lowers the success on this task, because the only weighted score is that of the correct response.
14.7.3.2 The Lake#
On the lake an episode has several steps and the kernel enters. We use the calm lake, where every command moves the agent as intended, rather than the slippery ice of the earlier sections. The reason is how much one episode says about one action. At the uniform start both maps give the same walk and the same success probability of about . But on slippery ice a command moves the agent in its own direction or in either perpendicular direction with probability each, so the one thing it controls is that the agent does not move the opposite way. At the uniform start this makes the exact gradient on slippery ice one third as long as on calm ice, while the noise of a one-episode estimate is about the same, so a batch must be nine times larger for the same precision (exercise 3 derives the factor).
As the policy improves the gap widens: successful episodes on slippery ice last tens of steps instead of six, so each success is shared among many more actions and discounted by . REINFORCE still learns on slippery ice, slowly (exercise 6).
We remove Gymnasium's default limit of 100 steps for this map. The objective (14.7.5) is defined over complete episodes, and the sum of rewards of a cut episode is not its return (Section 14.1). A softmax policy gives every action positive probability, so on this map every episode ends with probability one, and the cap of 10,000 steps is only a safeguard far above any episode these runs produce:
gamma = 0.95
env = gym.make('FrozenLake-v1', is_slippery=False, max_episode_steps=10_000)Batch stores the transitions of several episodes in flat arrays, with the index one past the last step of each episode. episode_returns computes for each episode, and per_step repeats one value per episode over that episode's steps, which turns a return into the weight of each of its actions. The container also records the next state and a flag term that marks terminated, never truncated: by the rule of Section 14.1, a cut episode has not reached a terminal state. Every lake episode here terminates, so the flag matters only once episodes are cut.
class Batch:
"""A flat batch of transitions, plus the episode boundaries."""
def __init__(self, obs, act, rew, next_obs, term, ep_ends):
self.obs, self.act, self.rew = obs, act, rew
self.next_obs, self.term = next_obs, term
self.ep_ends = ep_ends # one past the last step of each episode
def __len__(self):
return len(self.rew)
def episodes(self):
"""Yield one slice per episode."""
start = 0
for end in self.ep_ends:
yield slice(start, end)
start = end
def episode_returns(self, gamma=1.0):
"""R(tau), the discounted return, one number per episode."""
return np.array([(gamma ** np.arange(ep.stop - ep.start)
* self.rew[ep]).sum() for ep in self.episodes()])
def per_step(self, values):
"""Repeat one value per episode over that episode's steps."""
return np.repeat(values, np.diff(self.ep_ends, prepend=0))rollout fills a batch. It plays complete episodes with any policy written as a function policy(obs, rng) -> action, the acting protocol of evaluate in Section 14.2, and appends each step's state, action, reward, next state and termination flag. All randomness of the agent comes from the NumPy generator rng, so the seed fixes every sampled episode.
def rollout(env, policy, num_episodes, rng):
"""Collect complete episodes from `policy(obs, rng) -> action` as a
Batch. `term` records `terminated`, never `truncated`: a time-limit cut
is not a terminal state. All sampling runs through the numpy `rng`."""
cols, ep_ends = [[] for _ in range(5)], []
for _ in range(num_episodes):
obs, done = env.reset()[0], False
while not done:
act = policy(obs, rng)
next_obs, reward, terminated, truncated, _ = env.step(act)
done = terminated or truncated
for col, val in zip(cols, (obs, act, reward, next_obs,
float(terminated))):
col.append(val)
obs = next_obs
ep_ends.append(len(cols[0]))
obs, act, rew, next_obs, term = (np.asarray(c) for c in cols)
return Batch(obs, act, rew.astype(np.float32), next_obs,
term.astype(np.float32), np.asarray(ep_ends))The training loop reuses policy_step from Section 14.5, which takes one optimizer step on over the steps of a batch. Behavior cloning passed ; REINFORCE passes the return of the episode that contains step . Internally policy_step minimizes the negative of this sum, a surrogate loss, whose value says nothing about how well the policy performs; only its gradient at the current , the estimate, matters.
Two details differ from (14.7.7). First, policy_step divides by the number of steps rather than the number of episodes , which divides the estimate by the mean episode length of the batch, a factor that varies from batch to batch. Second, the optimizer is Adam with the learning rate of Policy.tabular, not the plain step . Plain ascent crawls wherever an action has small probability, because by (14.7.2) the gradient of its preference carries that probability as a factor, while Adam moves each coordinate by about its learning rate (exercise 6 compares the two). The loop collects a fresh batch, weights each step by its episode's return, takes one step, and yields the batch's mean return and its number of steps:
def train_reinforce_tabular(ac, env, gamma, seed, num_updates=256,
batch_episodes=16):
"""REINFORCE: a fresh batch from the current policy, every step of a
trajectory weighted by that trajectory's return, one ascent step.
Yields the batch's mean return and its number of steps."""
rng = np.random.default_rng(seed) # one stream for all sampling
env.reset(seed=seed)
for _ in range(num_updates):
batch = rollout(env, ac.act, batch_episodes, rng)
R = batch.episode_returns(gamma)
d2l.policy_step(ac, batch.obs, batch.act, batch.per_step(R))
yield float(R.mean()), len(batch)We train twelve agents from the uniform policy, each with its own seed, and plot the mean return of each training batch, an estimate of , against the ceiling of a six-step path:
agents = [d2l.Policy.tabular(16, 4) for _ in range(12)] # uniform policies
runs = np.array([list(train_reinforce_tabular(ac, env, gamma, seed))
for seed, ac in enumerate(agents)]) # (seed, update, 2)
curves, steps = runs[..., 0], runs[..., 1].astype(int)
d2l.plot_curves({'REINFORCE': curves}, xlabel='update',
ylabel='mean return of the batch', reference=gamma ** 5)The plot shows the median of the twelve runs, with a band from the slowest to the fastest. The median starts flat because, as the smallest case predicted, most early batches contain no success and give a zero estimate. Once a batch succeeds, its actions become more likely, successes become more frequent, and the mean return rises quickly. Every run approaches the dashed ceiling within a few dozen updates and stays a little below it, because the policy is still stochastic and sometimes leaves the shortest path. The next cell shows the learned policy of the first agent, with the most probable action and its probability at each cell:
probs = agents[0].probs(16, 4)
d2l.show_grid(env.unwrapped.desc, probs.max(axis=1), probs.argmax(axis=1))The policy concentrates on one of the three shortest paths to the goal, chosen by the episodes that happened to succeed first. The holes and the goal stay uniform, because no action is ever taken there. Cells off the chosen path keep most of the preferences they picked up from early successful episodes that passed through them. They change only when an episode strays through them, which becomes rare as the path firms up; between visits Adam's momentum carries the last change on for a few dozen updates, then they stay put. Nothing in this loop evaluated the transition kernel: rollout recorded the next states that the simulator sampled, and the update read only states, actions and returns. This is the cancellation of Section 14.7.2.4 at work, which the verifier task, having no kernel, could not show.
14.7.4 The Policy Gradient Theorem#
REINFORCE weights the score of every action by the return of the whole trajectory, including rewards that arrived before the action was taken. An action cannot affect rewards that are already collected, so those rewards should contribute nothing on average. The policy gradient theorem (Sutton et al., 2000) makes this precise, and it rewrites the gradient as an average over the states the policy visits rather than over whole trajectories. To state it, let the chain stay in its terminal state after the episode ends, with zero reward, so that is defined for every . Write for the distribution of under , and
for its discounted average over time, the discounted state-occupancy distribution. The factor makes the weights sum to one, so is a probability distribution over states.
14.7.4.1 Statement and Proof#
Proposition (policy gradient theorem). For the objective ,
Proof. By (14.7.6) and the cancellation, . At each , split the return into the rewards before and those from on. The rewards before are fixed once the agent stands at , while is still to be drawn, and the score of has mean zero given : . So the earlier rewards contribute zero. For the rewards from on, condition on : by the Markov property their expected discounted sum is . This gives the first form. For the second, group the sum over by the state visited: for any function , , and substitute the definition of . At terminal states , so the steps after the end of an episode contribute nothing.
14.7.4.2 Consequences#
The theorem has three consequences. First, the score at time needs only the rewards from on, because the proof removed the earlier ones as zero-mean noise, so an estimator that drops them has the same mean and usually less noise. Second, the gradient is an average over the states the policy visits, weighted by how often and how early it visits them, so a state the policy rarely reaches receives little gradient, and a batch that never visits it gives its row an estimate of exactly zero; this is why the cells off the learned path above barely change. Third, many implementations drop the factor from the first form. This replaces by the undiscounted visitation of states, changes the relative weight of states visited late, and in general yields an update that is not the gradient of any objective (Nota and Thomas, 2020). Exercise 7 examines the difference.
14.7.5 Costs and Limitations#
14.7.5.1 The On-Policy Data Requirement#
The estimator (14.7.7) averages trajectories drawn from the current policy. After one update the parameters have changed, and the trajectories already collected no longer follow . Methods with this requirement are called on-policy, and they collect a new batch for every update. Q-learning is off-policy: its update learns about the greedy policy from transitions that any behavior policy generated (Section 14.3). We count the data that REINFORCE uses in environment steps:
hit = (curves >= 0.7).argmax(axis=1) + 1 # batches until the mean is 0.7
to_hit = np.array([s[:k].sum() for s, k in zip(steps, hit)])
for name, x in [('batches until a batch mean reaches 0.7', hit),
('environment steps until then', to_hit),
('environment steps of the full run', steps.sum(axis=1))]:
print(f'{name:>38}: median {np.median(x):>6,.0f}, '
f'range {x.min():,} to {x.max():,}')batches until a batch mean reaches 0.7: median 32, range 25 to 49
environment steps until then: median 4,313, range 3,210 to 6,191
environment steps of the full run: median 27,049, range 26,058 to 28,383
A batch mean first reaches , about of the ceiling, after 25 to 50 updates, which is 3,000 to 7,000 environment steps. The full run of 256 updates uses about 27,000 steps, because each update keeps collecting a new batch long after the policy has stopped improving. On the same map, tabular Q-learning with found, in almost every run, a greedy table that reaches the goal, and the whole run took about 3,500 steps (Section 14.3). Reusing a batch for several updates is the obvious remedy, and it is unsound without a correction (exercise 4).
14.7.5.2 Unbiasedness and Variance#
The lake, like the verifier task, permits a check against the exact gradient, because its model is known. In Section 14.2 the value of a policy solved the linear system , where and . The objective is therefore
Every entry of and is a smooth function of , so automatic differentiation through the linear solve gives the exact . Holes and the goal are absorbing states with zero reward in TabularMDP.from_gym, so the solve accounts for termination. We freeze a policy probe after 16 updates of the run with seed 3, which has started to climb by then:
probe = d2l.Policy.tabular(16, 4)
list(train_reinforce_tabular(probe, env, gamma, 3, num_updates=16)) # train
mdp = d2l.TabularMDP.from_gym(env, gamma)policy_objective computes by (14.7.11) from a preference table, a kernel P[s, a, s'] and rewards r[s, a], and the framework's grad differentiates it through the solve. We compute and its exact gradient at the probe:
def policy_objective(theta, P, r, gamma):
"""J(theta) = V(s0) of the softmax policy, a differentiable linear solve."""
pi = torch.softmax(theta, -1)
P_pi = torch.einsum('sa,sat->st', pi, P)
return torch.linalg.solve(torch.eye(len(P)) - gamma * P_pi,
(pi * r).sum(-1))[0]
P, r = torch.as_tensor(mdp.P).float(), torch.as_tensor(mdp.r).float()
theta = probe.policy.weight.detach()
g_exact = torch.func.grad(policy_objective)(theta, P, r, gamma).numpy()
print(f'J(theta) after 16 updates = '
f'{float(policy_objective(theta, P, r, gamma)):.3f}, '
f'against the ceiling gamma^5 = {gamma ** 5:.3f}')J(theta) after 16 updates = 0.313, against the ceiling gamma^5 = 0.774
The probe lies partway between the uniform policy and the ceiling. Now hold fixed and draw the estimator many times. tabular_score sums the weighted scores of a batch, each into the row of its state, by (14.7.2). reinforce_estimate computes one draw of (14.7.7) with it, as verifier_step does: each step is weighted by its episode's return, and the sum is divided by . For each batch size we draw fifty estimates and print three numbers relative to : the root-mean-square error of one draw, the error of the mean of the fifty, and the error that an unbiased estimator would leave in that mean, the first number divided by :
def tabular_score(obs, act, w, pi):
"""sum_t w_t (e_{a_t} - pi(.|s_t)), each term added into row s_t: the
weighted softmax score (eq_softmax_score) of a batch, the shape of pi."""
u = np.zeros(pi.shape)
np.add.at(u, obs, w[:, None] * (np.eye(pi.shape[1])[act] - pi[obs]))
return u
def reinforce_estimate(env, probe, gamma, n, rng):
"""One draw of eq_reinforce at the frozen tabular policy `probe`: each
step adds its trajectory's return times its score to row s; the sum is
divided by n."""
pi = probe.probs(env.observation_space.n, env.action_space.n)
batch = rollout(env, probe.act, n, rng)
w = batch.per_step(batch.episode_returns(gamma))
return tabular_score(batch.obs, batch.act, w, pi).ravel() / n
rng, g = np.random.default_rng(4), g_exact.ravel()
for n in [4, 16, 64]:
U = np.stack([reinforce_estimate(env, probe, gamma, n, rng)
for _ in range(50)])
zero = int((U == 0).all(axis=1).sum())
one = np.sqrt(((U - g) ** 2).sum(axis=1).mean()) / np.linalg.norm(g)
mean = np.linalg.norm(U.mean(axis=0) - g) / np.linalg.norm(g)
print(f'n={n:>2}: {zero:>2}/50 zero; one draw off by {one:.2f}, the mean '
f'of 50 by {mean:.2f} (if unbiased: {one / np.sqrt(50):.2f})')n= 4: 3/50 zero; one draw off by 3.85, the mean of 50 by 0.48 (if unbiased: 0.54)
n=16: 0/50 zero; one draw off by 1.78, the mean of 50 by 0.24 (if unbiased: 0.25)
n=64: 0/50 zero; one draw off by 0.96, the mean of 50 by 0.10 (if unbiased: 0.14)
At a single draw is off by more than three times the length of the gradient it estimates, and some draws can be zero because no episode in the batch reached the goal. The error halves each time quadruples, the law of the smallest case. At every the mean of fifty draws is off by about as much as an unbiased estimator would be, so the test finds no bias; exercise 5 pushes it to many more draws, where a small bias would show.
14.7.5.3 Plateaus and Convergence#
The objective is not concave in . Already in the smallest case is a logistic function of , flat on both sides. Gradient ascent on a nonconcave function can in general stop at a poor stationary point. For the tabular softmax policy it cannot: there is no suboptimal stationary point, and exact gradient ascent with a small enough step converges to an optimal policy when the start distribution gives every state positive probability (Agarwal et al., 2021; Mei et al., 2020). Convergence can still be slow. Where the better action at a state has small probability, the gradient of its preference carries that probability as a factor, so ascent creeps across a plateau, and there are MDPs in which exact softmax ascent needs a number of steps exponential in the number of states (Li et al., 2021).
Sampled updates with a fixed step size add a second risk. A few lucky batches can make the policy at some state nearly deterministic on a worse action, after which the gradient that would undo the choice is tiny, and the run stays committed for a long time (Mei et al., 2021). On the calm lake all twelve runs ended within a few hundredths of the ceiling; on slippery ice the same recipe settles at different levels from seed to seed, some well below the optimum, and exercise 6 finds out why.
We can now improve a policy from its own episodes and their rewards alone, without a model, an expert, or a table of values, and on the verifier task the same update already has the shape of post-training a language model: a response is a trajectory, and its reward arrives at the end. The estimate is right on average, but at the probe policy, with four episodes per batch, a single draw is off by more than three times the gradient's length, and every failed episode contributes nothing. Section 14.8 asks how much of that noise can be removed without moving the mean.
14.7.6 Summary#
Policy gradient methods improve a parameterized policy directly by gradient ascent on its expected return . The log-derivative trick writes as an average over the policy's own trajectories of the return times the trajectory's score, and the transition kernel drops out of the score, so the gradient can be estimated from sampled episodes without a model. REINFORCE weights the score of every action by the return of its episode, which is behavior cloning's update with returns in place of unit weights. On the verifier task and the calm lake the estimate matches the exact gradient on average, but on the lake a small batch is off by several times the gradient's length, and the error shrinks only as . The policy gradient theorem shows that rewards collected before an action contribute only noise; every update needs a fresh batch from the current policy.
14.7.7 Exercises#
- Parameter-dependent dynamics. The derivation of
Section 14.7.2.4 assumes that the transition
probabilities do not depend on . A recommender violates this
assumption when users who see an item more often click it less.
- Suppose the dynamics are . Repeat the derivation of and state the term that no longer vanishes. What would the agent need to know to compute it?
- In a one-step model, the recommender shows item 1 with probability and item 0 otherwise, where is the logistic function. A shown item 1 is clicked with probability , item 0 is never clicked, and a click earns reward . Compute and . Compare the derivative with the expectation of the REINFORCE estimate (14.7.7), which drops that term. Where does plain gradient ascent converge with each of the two?
- [code] Sparse rewards. The smallest case of the text has one state,
two actions, reward for action 1 and for action 2, and
; a single-sample estimate has standard deviation
times its mean. On the lake the analogous quantity is the
probability that an episode of the uniform policy
reaches the goal, which Section 14.2.4 computes by
policy evaluation at .
- A batch with no success gives the estimate zero, and
policy_stepthen leaves the zero table unchanged, so the policy stays uniform until the first success. What distribution does the number of updates up to and including the first nonzero estimate follow, and what is its mean for batches of 16 episodes? Record that number for each of the twelve training runs and compare it with the prediction and with the flat start of the training curve. - Show that the mean of independent single-sample estimates has standard deviation times its mean. How many episodes per batch would make the standard deviation equal to the mean at ? How does the answer change as training raises the success probability?
- A batch with no success gives the estimate zero, and
- [code] The theorem in a table. ● For the tabular softmax policy, write for the discounted number of visits to , so that in (14.7.10).
- By problem 1b of
Section 14.2, is the row of
that belongs to . Compute
, and at the parameters
of
probeby linear solves withmdp.Pandmdp.r, assemble the formula, and compare the result withg_exact. - On slippery ice a command moves the agent in direction or in
either perpendicular direction with probability each. Show
that at the uniform policy both maps induce the same chain, hence
the same and , and that the slippery
satisfies , where
is the command opposite to . Conclude that the exact
gradient at is one third as long on slippery ice, and
check it with
policy_objectiveon both transition tables.
- [code] Reusing a batch. ● Modify
train_reinforce_tabularto callpolicy_steptimes on each batch without any correction, for . Write for the parameters that collected the batch.- On the calm lake, log the batch mean return and, after the
-th step, the mean and the maximum over the batch of the ratio
;
log_prob_npevaluates both policies. How many environment steps does each need before the batch mean return reaches , and how large does the ratio grow? - As grows, the steps approach a maximizer of the surrogate on the fixed batch, where is the return of the episode that contains step . Find the maximizing tabular policy in closed form, and use it to explain the result of part a.
- Compare with on the slippery map
(
is_slippery=True) by the final , computed with (14.7.11) from the slippery transition table. Each run takes seconds. Explain the difference from the calm lake with the closed form of part b.
- On the calm lake, log the batch mean return and, after the
-th step, the mean and the maximum over the batch of the ratio
;
- [code] Testing unbiasedness. ● The fifty-draw test of the text
cannot reveal a bias smaller than the noise of fifty draws. A sharper
test averages estimates: for an unbiased estimator, the error of the
average keeps shrinking as grows, whereas for a biased one it levels
off at the bias.
- At the parameters of
probe, draw estimates withreinforce_estimateat . Plot the error of the running average relative tog_exactagainst on logarithmic axes. Explain the slope of the curve. - Repeat the measurement with an environment rebuilt with
max_episode_stepslowered to and to , passed toreinforce_estimate, so thatrolloutends some episodes by truncation. At what level does each curve settle? Of which objective are the truncated estimates unbiased estimates of the gradient?
- At the parameters of
- Softmax plateaus. ● Consider a single state with two actions,
rewards and , and initial preferences with
, so that the better action starts with probability
. This is the plateau of Section 14.7.5.3
in its smallest form.
- Show that depends on only through , as with the logistic function . Conclude that is not concave.
- Show that one step of plain gradient ascent with step size increases by . Treat this as a differential equation, and show that reaching from takes about steps when is large.
- Adam, fed the same exact gradients, moves each coordinate by about
its learning rate per step while the sign of the gradient
stays fixed. Estimate the number of steps it needs, and compare it
with the answer of part b at and . What does
the comparison suggest about the use of Adam in
Policy.tabular? - [code] Run
train_reinforce_tabularfor 1,024 updates on the slippery map with several seeds and compute the final with (14.7.11). At which states is the final policy of a run that ends well below nearly deterministic, and on which actions? Compute there and at the uniform start. Is the final a stationary point? Run exact gradient ascent from it and from , and relate what you see to parts b and c.
- [code] The dropped discount. ●● Many implementations omit the factor from the trajectory form of (14.7.10), which gives the update field
Nota and Thomas (2020) prove that need not be the gradient of any function, and they construct an MDP in which exact updates along drive the policy toward the worst possible policy. The parts below check the first finding on FrozenLake and then construct a small MDP in which a step along lowers , the starting point of the second.
- Following problem 3a, show that
where is the expected number of visits to before the episode ends. Compute by a linear solve in which the rows of the policy's transition matrix that belong to terminal states are set to zero.
- The Jacobian of a continuously differentiable gradient field is a
Hessian and therefore symmetric. Compute the Jacobian at the
zero table and at the parameters of
probeby automatic differentiation, and report in the Frobenius norm. Run the same check on as a control. - Measure the cosine between and at the same two points. Give a practical reason why implementations accept anyway.
- Show that for the tabular softmax policy at every , so that a small step along never lowers on FrozenLake. Then construct a small episodic MDP in which a single parameter controls the policy at two states visited in sequence, together with a at which .