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 f(xt,ut)f(\mathbf{x}_t, \mathbf{u}_t) 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 θ\theta 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 πθ(a∣s)\pi_\theta(a \mid s) 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 gym

14.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 θs,a\theta_{s,a}, called a preference, for each state-action pair. A softmax over the actions turns the preferences at state ss into probabilities:

πθ(a∣s)=eθs,a∑a′eθs,a′.(14.7.1)\pi_\theta(a \mid s) = \frac{e^{\theta_{s,a}}}{\sum_{a'} e^{\theta_{s,a'}}}. \tag{14.7.1}

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 Q(s,a)Q(s,a), 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 log⁡πθ(a∣s)=θs,a−log⁡∑a′′eθs,a′′\log \pi_\theta(a \mid s) = \theta_{s,a} - \log \sum_{a''} e^{\theta_{s,a''}}, the derivative with respect to the preference θs,a′\theta_{s,a'} of any action a′a' at the same state is

∂log⁡πθ(a∣s)∂θs,a′=1(a′=a)−πθ(a′∣s),(14.7.2)\frac{\partial \log \pi_\theta(a \mid s)}{\partial \theta_{s,a'}} = \mathbf{1}(a' = a) - \pi_\theta(a' \mid s), \tag{14.7.2}

and the derivative with respect to the preferences at every other state is zero. The vector ∇θlog⁡πθ(a∣s)\nabla_\theta\log\pi_\theta(a\mid s) is called the score function. In words, increasing the log-probability of aa means raising its own preference and lowering every preference at ss in proportion to its probability. Writing eae_a for the indicator vector of action aa, the row of the score at ss is ea−πθ(⋅∣s)e_a - \pi_\theta(\cdot \mid s). 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 ss. 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 θ1\theta_1 and θ2\theta_2. Action 1 earns reward 11 and action 2 earns 00. Write p=πθ(1)p = \pi_\theta(1). The expected reward is J(θ)=pJ(\theta) = p, and by (14.7.2) its derivative with respect to θ1\theta_1 is p(1−p)p(1 - p). Suppose that we could not compute pp 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 πθ(a)\pi_\theta(a):

∂J∂θ1=∑ar(a) ∂πθ(a)∂θ1=∑aπθ(a) r(a) ∂log⁡πθ(a)∂θ1=Ea∼πθ[r(a) ∂log⁡πθ(a)∂θ1].\begin{aligned} \frac{\partial J}{\partial \theta_1} &= \sum_a r(a)\, \frac{\partial \pi_\theta(a)}{\partial \theta_1} = \sum_a \pi_\theta(a)\, r(a)\, \frac{\partial \log \pi_\theta(a)}{\partial \theta_1} \\ &= \mathbb{E}_{a \sim \pi_\theta}\Big[ r(a)\, \frac{\partial \log \pi_\theta(a)}{\partial \theta_1} \Big]. \end{aligned}

So one sampled action, its reward multiplied by its score, is an estimate of the derivative. With probability pp the sample is action 1, whose reward is 11 and whose score is 1−p1 - p; with probability 1−p1 - p the reward is zero and so is the estimate. The mean is p(1−p)p(1 - p), the derivative itself. The second moment is p(1−p)2p(1-p)^2, so the standard deviation is (1−p)p(1−p)(1-p)\sqrt{p(1-p)}, which is

1−pp(14.7.3)\sqrt{\frac{1 - p}{p}} \tag{14.7.3}

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 1/p1/p times too large. Averaging nn independent draws divides the ratio by n\sqrt n.

The lake has the same structure at the start of learning. The uniform policy reaches the goal in about 1.4%1.4\% 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 p=0.014p = 0.014 the ratio is 8.48.4, and a batch of 16 episodes contains no success at all with probability (1−0.014)16≈0.80(1 - 0.014)^{16} \approx 0.80. 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 τ=(s0,a0,r0,s1,a1,r1,…,sT)\tau = (s_0, a_0, r_0, s_1, a_1, r_1, \ldots, s_T) that ends at the first terminal state sTs_T, so its length TT 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 μ0\mu_0 of Section 14.1:

P(τ;θ)=μ0(s0)∏t=0T−1πθ(at∣st) P(st+1∣st,at).(14.7.4)P(\tau; \theta) = \mu_0(s_0) \prod_{t=0}^{T-1} \pi_\theta(a_t \mid s_t)\ P(s_{t+1} \mid s_t, a_t). \tag{14.7.4}

Only the policy's factors depend on θ\theta. The objective is the expected return over these trajectories, with R(τ)=∑t=0T−1γtrtR(\tau) = \sum_{t=0}^{T-1} \gamma^t r_t:

J(θ)=Eτ∼P(⋅; θ)[R(τ)]=∑τR(τ) P(τ;θ).(14.7.5)J(\theta) = \mathbb{E}_{\tau \sim P(\cdot;\, \theta)} \big[ R(\tau) \big] = \sum_{\tau} R(\tau)\ P(\tau; \theta). \tag{14.7.5}

The lake has a fixed start state, so J(θ)=Vπθ(s0)J(\theta) = V^{\pi_\theta}(s_0) in the notation of Section 14.2. On the verifier task μ0\mu_0 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 R(τ)R(\tau) of a fixed trajectory does not depend on θ\theta; only its probability does. Moving the gradient inside the sum and multiplying and dividing by P(τ;θ)P(\tau;\theta) gives

∇θJ(θ)=∑τR(τ) ∇θP(τ;θ)=∑τP(τ;θ) R(τ) ∇θP(τ;θ)P(τ;θ)=∑τP(τ;θ) R(τ) ∇θlog⁡P(τ;θ),\begin{aligned} \nabla_\theta J(\theta) &= \sum_\tau R(\tau)\ \nabla_\theta P(\tau; \theta) = \sum_\tau P(\tau; \theta)\ R(\tau)\ \frac{\nabla_\theta P(\tau; \theta)}{P(\tau; \theta)} \\ &= \sum_\tau P(\tau; \theta)\ R(\tau)\ \nabla_\theta \log P(\tau; \theta), \end{aligned}

that is,

∇θJ(θ)=Eτ∼P(⋅; θ)[R(τ) ∇θlog⁡P(τ;θ)].(14.7.6)\nabla_\theta J(\theta) = \mathbb{E}_{\tau \sim P(\cdot;\, \theta)} \Big[ R(\tau)\ \nabla_\theta \log P(\tau; \theta) \Big]. \tag{14.7.6}

The identity ∇log⁡P=∇P/P\nabla \log P = \nabla P / P 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 log⁡P(τ;θ)\log P(\tau;\theta), and P(τ;θ)P(\tau;\theta) 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:

∇θlog⁡P(τ;θ)=∇θ[log⁡μ0(s0)+∑t=0T−1log⁡πθ(at∣st)+∑t=0T−1log⁡P(st+1∣st,at)]=∑t=0T−1∇θlog⁡πθ(at∣st).\begin{aligned} \nabla_\theta \log P(\tau; \theta) &= \nabla_\theta \Big[ \log \mu_0(s_0) + \sum_{t=0}^{T-1} \log \pi_\theta(a_t \mid s_t) + \sum_{t=0}^{T-1} \log P(s_{t+1} \mid s_t, a_t) \Big] \\ &= \sum_{t=0}^{T-1} \nabla_\theta \log \pi_\theta(a_t \mid s_t). \end{aligned}

Figure 14.7.1 shows the chain of factors. The start distribution and the kernel do not depend on θ\theta, 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).

Figure 14.7.1:

The probability of a trajectory as a chain of factors, P(τ;θ)=μ0(s0)∏tπθ(at∣st) P(st+1∣st,at)P(\tau;\theta) = \mu_0(s_0)\prod_t \pi_\theta(a_t \mid s_t)\,P(s_{t+1} \mid s_t, a_t). Only the policy factors (blue, above the chain) depend on θ\theta. 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 PP.

14.7.2.5 The REINFORCE Estimator#

Substituting the sum of scores into (14.7.6) and replacing the expectation by an average over nn trajectories τ1,…,τn\tau_1, \ldots, \tau_n sampled from the current policy gives

u^=1n∑i=1nR(τi)∑t=0Ti−1∇θlog⁡πθ(ati∣sti).(14.7.7)\hat{u} = \frac{1}{n} \sum_{i=1}^n R(\tau_i) \sum_{t=0}^{T_i-1} \nabla_\theta \log \pi_\theta(a_t^i \mid s_t^i). \tag{14.7.7}

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 ∇θJ(θ)\nabla_\theta J(\theta), so u^\hat u is an unbiased estimate of the gradient. REINFORCE (Williams, 1992) takes the ascent step θ←θ+η u^\theta \leftarrow \theta + \eta\, \hat u with a step size η\eta, 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 −πθ(⋅∣s)-\pi_\theta(\cdot\mid s) 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 N(a;μ,1)\mathcal{N}(a; \mu, 1), whose score with respect to the mean is a−μa - \mu. An episode is a single action aa, so its return R(a)R(a) is that action's reward, and the step reads μ←μ+η 1n∑iR(ai)(ai−μ)\mu \leftarrow \mu + \eta\, \frac{1}{n}\sum_i R(a_i)(a_i - \mu): the mean moves toward the sampled actions that paid most. Twelve samples move it to 0.320.32, where the exact gradient would give 0.520.52.

Figure 14.7.2:

One REINFORCE step on a one-step problem. The policy is πθ(a)=N(a;μ,1)\pi_\theta(a) = \mathcal{N}(a; \mu, 1) with μ=0\mu = 0, and the reward is R(a)=0.4+2e−(a−2)2/2R(a) = 0.4 + 2e^{-(a-2)^2/2}, so the expected reward is J=0.92J = 0.92 and the exact gradient is dJ/dμ=0.52\mathrm{d}J/\mathrm{d}\mu = 0.52. (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 μ←μ+η 112∑iR(ai)(ai−μ)\mu \leftarrow \mu + \eta\,\frac{1}{12}\sum_i R(a_i)(a_i - \mu) with η=1\eta = 1 moves the mean from 00 to 0.320.32, toward the actions with higher reward; the exact gradient would have moved it to 0.520.52.

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 xx and nine candidate responses yy shared by all of them. The policy is a table θ\theta with one row of preferences per prompt, πθ(y∣x)\pi_\theta(y \mid x) is the softmax of row xx, and the verifier pays r(x,y)=1r(x, y) = 1 for the correct answer and 00 otherwise. A trajectory is a single response to a prompt, with probability μ0(x) πθ(y∣x)\mu_0(x)\,\pi_\theta(y \mid x) and no kernel at all. Row xx of θ\theta affects only the expected score of prompt xx, Jx(θ)=∑yπθ(y∣x) r(x,y)J_x(\theta) = \sum_y \pi_\theta(y \mid x)\, r(x, y), and by (14.7.2) with the prompt in place of the state, its exact gradient is a sum of nine terms:

∇θxJx(θ)=∑yπθ(y∣x) r(x,y) (ey−πθ(⋅∣x)).(14.7.8)\nabla_{\theta_x} J_x(\theta) = \sum_{y} \pi_\theta(y \mid x)\, r(x, y)\, \big( e_y - \pi_\theta(\cdot \mid x) \big). \tag{14.7.8}

REINFORCE replaces this sum by an average over KK sampled responses. verifier_step samples KK responses for every prompt, turns their rewards into weights with the function weighting, and moves the row of θ\theta by lr =η= \eta times the weighted average of the KK 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 * g

The exact-match verifier pays only the correct response y∗y^*, so the estimate for prompt xx is cK(ey∗−πθ(⋅∣x))\frac{c}{K}\big(e_{y^*} - \pi_\theta(\cdot \mid x)\big), where cc counts the correct responses among the KK. The count cc is binomial with success probability p=πθ(y∗∣x)p = \pi_\theta(y^* \mid x), so the estimate has mean p (ey∗−πθ(⋅∣x))p\,(e_{y^*} - \pi_\theta(\cdot\mid x)), the exact gradient, and relative standard deviation (1−p)/(Kp)\sqrt{(1-p)/(Kp)}: the ratio of the smallest case divided by K\sqrt K. At the reference table p≈1/8p \approx 1/8 on the two answerable prompts, so a group of K=16K = 16 should be off by about 0.660.66 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 θ\theta is the estimate) and takes one step with η=2\eta = 2:

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 0.660.66 of the gradient's length, as predicted. The error of the mean of MM estimates keeps falling as MM grows, on average like 0.66/M0.66/\sqrt M, 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 12%12\% of the groups contain no correct response, (7/8)16≈0.12(7/8)^{16} \approx 0.12, 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 η=2\eta = 2 raises the success from 0.0620.062 to 0.0770.077, 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 1.4%1.4\%. But on slippery ice a command moves the agent in its own direction or in either perpendicular direction with probability 1/31/3 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 γT−1\gamma^{T-1}. 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 R(τ)R(\tau) 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 1N∑twtlog⁡πθ(at∣st)\frac{1}{N}\sum_t w_t \log \pi_\theta(a_t \mid s_t) over the NN steps of a batch. Behavior cloning passed wt=1w_t = 1; REINFORCE passes the return of the episode that contains step tt. 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 θ\theta, the estimate, matters.

Two details differ from (14.7.7). First, policy_step divides by the number of steps NN rather than the number of episodes nn, 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 0.10.1 of Policy.tabular, not the plain step θ←θ+ηu^\theta \leftarrow \theta + \eta\hat u. 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 J(θ)J(\theta), against the ceiling γ5≈0.774\gamma^5 \approx 0.774 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 sts_t is defined for every tt. Write dtπθ(s)=Pr⁡(st=s)d^{\pi_\theta}_t(s) = \Pr(s_t = s) for the distribution of sts_t under πθ\pi_\theta, and

dγπθ(s)=(1−γ)∑t≥0γt dtπθ(s)(14.7.9)d^{\pi_\theta}_\gamma(s) = (1 - \gamma) \sum_{t \geq 0} \gamma^t\, d^{\pi_\theta}_t(s) \tag{14.7.9}

for its discounted average over time, the discounted state-occupancy distribution. The factor 1−γ1-\gamma makes the weights γt\gamma^t sum to one, so dγπθd^{\pi_\theta}_\gamma is a probability distribution over states.

14.7.4.1 Statement and Proof#

Proposition (policy gradient theorem). For the objective J(θ)=Es0∼μ0[Vπθ(s0)]J(\theta) = \mathbb{E}_{s_0 \sim \mu_0} [V^{\pi_\theta}(s_0)],

∇θJ(θ)=Eτ∼P(⋅; θ)[∑t≥0γt ∇θlog⁡πθ(at∣st) Qπθ(st,at)]=11−γ Es∼dγπθ, a∼πθ(⋅∣s)[∇θlog⁡πθ(a∣s) Qπθ(s,a)](14.7.10)\begin{aligned} \nabla_\theta J(\theta) &= \mathbb{E}_{\tau \sim P(\cdot;\, \theta)} \Big[ \sum_{t \geq 0} \gamma^t\, \nabla_\theta \log \pi_\theta(a_t \mid s_t)\ Q^{\pi_\theta}(s_t, a_t) \Big] \\ &= \frac{1}{1 - \gamma}\, \mathbb{E}_{s \sim d^{\pi_\theta}_\gamma,\ a \sim \pi_\theta(\cdot \mid s)} \Big[ \nabla_\theta \log \pi_\theta(a \mid s)\ Q^{\pi_\theta}(s, a) \Big] \end{aligned} \tag{14.7.10}

Proof. By (14.7.6) and the cancellation, ∇θJ=E[∑t∇θlog⁡πθ(at∣st) R(τ)]\nabla_\theta J = \mathbb{E}\big[\sum_t \nabla_\theta \log \pi_\theta(a_t \mid s_t)\, R(\tau)\big]. At each tt, split the return into the rewards before tt and those from tt on. The rewards before tt are fixed once the agent stands at sts_t, while ata_t is still to be drawn, and the score of ata_t has mean zero given sts_t: ∑aπθ(a∣s)∇θlog⁡πθ(a∣s)=∑a∇θπθ(a∣s)=∇θ1=0\sum_a \pi_\theta(a \mid s)\nabla_\theta \log\pi_\theta(a\mid s) = \sum_a \nabla_\theta \pi_\theta(a\mid s) = \nabla_\theta 1 = 0. So the earlier rewards contribute zero. For the rewards from tt on, condition on (st,at)(s_t, a_t): by the Markov property their expected discounted sum is γtQπθ(st,at)\gamma^t Q^{\pi_\theta}(s_t, a_t). This gives the first form. For the second, group the sum over tt by the state visited: for any function ff, E[∑tγtf(st,at)]=∑s∑tγtdtπθ(s) Ea∼πθ(⋅∣s)f(s,a)\mathbb{E}\big[\sum_t \gamma^t f(s_t, a_t)\big] = \sum_s \sum_t \gamma^t d^{\pi_\theta}_t(s)\ \mathbb{E}_{a \sim \pi_\theta(\cdot\mid s)} f(s, a), and substitute the definition of dγπθd^{\pi_\theta}_\gamma. At terminal states Qπθ=0Q^{\pi_\theta} = 0, so the steps after the end of an episode contribute nothing. ■\blacksquare

14.7.4.2 Consequences#

The theorem has three consequences. First, the score at time tt needs only the rewards from tt 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 γt\gamma^t from the first form. This replaces dγπθd^{\pi_\theta}_\gamma 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 P(τ;θ)P(\tau;\theta). 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 0.70.7, about 90%90\% 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 α=0.9\alpha = 0.9 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 Vπ=rπ+γPπVπV^\pi = r_\pi + \gamma P_\pi V^\pi, where Pπ(s′∣s)=∑aπ(a∣s)P(s′∣s,a)P_\pi(s' \mid s) = \sum_a \pi(a \mid s) P(s' \mid s, a) and rπ(s)=∑aπ(a∣s) r(s,a)r_\pi(s) = \sum_a \pi(a \mid s)\, r(s, a). The objective is therefore

J(θ)=Vπθ(s0)=[(I−γPπθ)−1rπθ]s0.(14.7.11)J(\theta) = V^{\pi_\theta}(s_0) = \Big[ \big(I - \gamma P_{\pi_\theta}\big)^{-1} r_{\pi_\theta} \Big]_{s_0}. \tag{14.7.11}

Every entry of PπθP_{\pi_\theta} and rπθr_{\pi_\theta} is a smooth function of θ\theta, so automatic differentiation through the linear solve gives the exact ∇θJ\nabla_\theta J. 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 J(θ)J(\theta) 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 JJ 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 θ\theta fixed and draw the estimator many times. tabular_score sums the weighted scores wt (eat−πθ(⋅∣st))w_t\,(e_{a_t} - \pi_\theta(\cdot \mid s_t)) 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 nn. For each batch size nn we draw fifty estimates and print three numbers relative to ∥∇θJ∥\|\nabla_\theta J\|: 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 50\sqrt{50}:

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 n=4n = 4 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 nn quadruples, the 1/n1/\sqrt n law of the smallest case. At every nn 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 θ\theta. Already in the smallest case J=pJ = p is a logistic function of θ1−θ2\theta_1 - \theta_2, 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 πθ\pi_\theta directly by gradient ascent on its expected return J(θ)J(\theta). The log-derivative trick writes ∇θJ\nabla_\theta J 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 1/n1/\sqrt n. 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#

  1. Parameter-dependent dynamics. The derivation of Section 14.7.2.4 assumes that the transition probabilities do not depend on θ\theta. A recommender violates this assumption when users who see an item more often click it less.
    1. Suppose the dynamics are Pθ(st+1∣st,at)P_\theta(s_{t+1} \mid s_t, a_t). Repeat the derivation of ∇θlog⁡P(τ;θ)\nabla_\theta \log P(\tau; \theta) and state the term that no longer vanishes. What would the agent need to know to compute it?
    2. In a one-step model, the recommender shows item 1 with probability πθ(1)=σ(θ)\pi_\theta(1) = \sigma(\theta) and item 0 otherwise, where σ\sigma is the logistic function. A shown item 1 is clicked with probability 1−σ(θ)1 - \sigma(\theta), item 0 is never clicked, and a click earns reward 11. Compute J(θ)J(\theta) and dJ/dθ\mathrm{d}J/\mathrm{d}\theta. 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?
  2. [code] Sparse rewards. The smallest case of the text has one state, two actions, reward 11 for action 1 and 00 for action 2, and p=πθ(1)p = \pi_\theta(1); a single-sample estimate has standard deviation (1−p)/p\sqrt{(1-p)/p} times its mean. On the lake the analogous quantity is the probability p0≈0.014p_0 \approx 0.014 that an episode of the uniform policy reaches the goal, which Section 14.2.4 computes by policy evaluation at γ=1\gamma = 1.
    1. A batch with no success gives the estimate zero, and policy_step then 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.
    2. Show that the mean of nn independent single-sample estimates has standard deviation (1−p)/(np)\sqrt{(1-p)/(np)} times its mean. How many episodes per batch would make the standard deviation equal to the mean at p=p0p = p_0? How does the answer change as training raises the success probability?
  3. [code] The theorem in a table. ● For the tabular softmax policy, write ργ(s)=∑t≥0γtdtπθ(s)\rho_\gamma(s) = \sum_{t \geq 0} \gamma^t d^{\pi_\theta}_t(s) for the discounted number of visits to ss, so that dγπθ=(1−γ)ργd^{\pi_\theta}_\gamma = (1 - \gamma)\rho_\gamma in (14.7.10).
    1. Combine the occupancy form of (14.7.10) with (14.7.2) to show that
∂J∂θs,a′=ργ(s) πθ(a′∣s)(Qπθ(s,a′)−Vπθ(s)).\frac{\partial J}{\partial \theta_{s,a'}} = \rho_\gamma(s)\, \pi_\theta(a' \mid s) \big( Q^{\pi_\theta}(s,a') - V^{\pi_\theta}(s) \big).
  1. By problem 1b of Section 14.2, ργ⊤\rho_\gamma^\top is the row of (I−γPπθ)−1(I - \gamma P_{\pi_\theta})^{-1} that belongs to s0s_0. Compute ργ\rho_\gamma, VπθV^{\pi_\theta} and QπθQ^{\pi_\theta} at the parameters of probe by linear solves with mdp.P and mdp.r, assemble the formula, and compare the result with g_exact.
  2. On slippery ice a command aa moves the agent in direction aa or in either perpendicular direction with probability 1/31/3 each. Show that at the uniform policy both maps induce the same chain, hence the same ργ\rho_\gamma and VV, and that the slippery Q(s,a)Q(s, a) satisfies Qslip(s,a)−V(s)=−13(Qcalm(s,aˉ)−V(s))Q_\textrm{slip}(s,a) - V(s) = -\tfrac{1}{3}\big(Q_\textrm{calm}(s, \bar a) - V(s)\big), where aˉ\bar a is the command opposite to aa. Conclude that the exact gradient at θ=0\theta = 0 is one third as long on slippery ice, and check it with policy_objective on both transition tables.
  1. [code] Reusing a batch. ● Modify train_reinforce_tabular to call policy_step kk times on each batch without any correction, for k∈{1,2,5,20}k \in \{1, 2, 5, 20\}. Write θold\theta_\textrm{old} for the parameters that collected the batch.
    1. On the calm lake, log the batch mean return and, after the kk-th step, the mean and the maximum over the batch of the ratio πθ(at∣st)/πθold(at∣st)\pi_\theta(a_t \mid s_t) / \pi_{\theta_\textrm{old}}(a_t \mid s_t); log_prob_np evaluates both policies. How many environment steps does each kk need before the batch mean return reaches 0.70.7, and how large does the ratio grow?
    2. As kk grows, the steps approach a maximizer of the surrogate ∑twtlog⁡πθ(at∣st)\sum_t w_t \log \pi_\theta(a_t \mid s_t) on the fixed batch, where wtw_t is the return of the episode that contains step tt. Find the maximizing tabular policy in closed form, and use it to explain the result of part a.
    3. Compare k=1k = 1 with k=20k = 20 on the slippery map (is_slippery=True) by the final J(θ)J(\theta), 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.
  2. [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 MM estimates: for an unbiased estimator, the error of the average keeps shrinking as MM grows, whereas for a biased one it levels off at the bias.
    1. At the parameters of probe, draw M=25,600M = 25{,}600 estimates with reinforce_estimate at n=1n = 1. Plot the error of the running average relative to ∥\|g_exact∥\| against MM on logarithmic axes. Explain the slope of the curve.
    2. Repeat the measurement with an environment rebuilt with max_episode_steps lowered to 2020 and to 1010, passed to reinforce_estimate, so that rollout ends some episodes by truncation. At what level does each curve settle? Of which objective are the truncated estimates unbiased estimates of the gradient?
  3. Softmax plateaus. ● Consider a single state with two actions, rewards 11 and 00, and initial preferences θ=(0,L)\theta = (0, L) with L>0L > 0, so that the better action starts with probability 1/(1+eL)1/(1 + e^L). This is the plateau of Section 14.7.5.3 in its smallest form.
    1. Show that JJ depends on θ\theta only through x=θ1−θ2x = \theta_1 - \theta_2, as J=σ(x)J = \sigma(x) with the logistic function σ\sigma. Conclude that JJ is not concave.
    2. Show that one step of plain gradient ascent with step size η\eta increases xx by 2η σ(x)(1−σ(x))2\eta\, \sigma(x)(1 - \sigma(x)). Treat this as a differential equation, and show that reaching πθ(1)=1/2\pi_\theta(1) = 1/2 from x=−Lx = -L takes about eL/(2η)e^L / (2\eta) steps when LL is large.
    3. Adam, fed the same exact gradients, moves each coordinate by about its learning rate η\eta 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 L=10L = 10 and η=0.1\eta = 0.1. What does the comparison suggest about the use of Adam in Policy.tabular?
    4. [code] Run train_reinforce_tabular for 1,024 updates on the slippery map with several seeds and compute the final J(θ)J(\theta) with (14.7.11). At which states is the final policy of a run that ends well below V∗(s0)V^*(s_0) nearly deterministic, and on which actions? Compute ∥∇θJ∥\|\nabla_\theta J\| there and at the uniform start. Is the final θ\theta a stationary point? Run exact gradient ascent from it and from θ=0\theta = 0, and relate what you see to parts b and c.
  4. [code] The dropped discount. ●● Many implementations omit the factor γt\gamma^t from the trajectory form of (14.7.10), which gives the update field
F(θ)=Eτ∼P(⋅; θ)[∑t≥0∇θlog⁡πθ(at∣st) Qπθ(st,at)].(14.7.12)F(\theta) = \mathbb{E}_{\tau \sim P(\cdot;\, \theta)} \Big[ \sum_{t \geq 0} \nabla_\theta \log \pi_\theta(a_t \mid s_t)\ Q^{\pi_\theta}(s_t, a_t) \Big]. \tag{14.7.12}

Nota and Thomas (2020) prove that FF need not be the gradient of any function, and they construct an MDP in which exact updates along FF 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 FF lowers JJ, the starting point of the second.

  1. Following problem 3a, show that
Fs,a′(θ)=ρ1(s) πθ(a′∣s)(Qπθ(s,a′)−Vπθ(s)),(14.7.13)F_{s,a'}(\theta) = \rho_1(s)\, \pi_\theta(a' \mid s) \big( Q^{\pi_\theta}(s,a') - V^{\pi_\theta}(s) \big), \tag{14.7.13}

where ρ1(s)=∑t≥0Pr⁡(st=s, t<T)\rho_1(s) = \sum_{t \geq 0} \Pr(s_t = s,\ t \lt T) is the expected number of visits to ss before the episode ends. Compute ρ1\rho_1 by a linear solve in which the rows of the policy's transition matrix that belong to terminal states are set to zero.

  1. The Jacobian of a continuously differentiable gradient field is a Hessian and therefore symmetric. Compute the Jacobian DFDF at the zero table and at the parameters of probe by automatic differentiation, and report ∥DF−DF⊤∥/∥DF∥\|DF - DF^\top\| / \|DF\| in the Frobenius norm. Run the same check on ∇θJ\nabla_\theta J as a control.
  2. Measure the cosine between FF and ∇θJ\nabla_\theta J at the same two points. Give a practical reason why implementations accept FF anyway.
  3. Show that F(θ)⊤∇θJ(θ)≥0F(\theta)^\top \nabla_\theta J(\theta) \geq 0 for the tabular softmax policy at every θ\theta, so that a small step along FF never lowers JJ 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 θ\theta at which F(θ) dJ/dθ<0F(\theta)\, \mathrm{d}J/\mathrm{d}\theta \lt 0.

Discussions