Policy Gradient

Dive into Deep Learning · §14.7

Policy Gradient and REINFORCE
softmax preferences & score function · log-derivative trick · kernel cancellation · REINFORCE · policy gradient theorem · on-policy variance

Learning a Policy Directly from Episode Returns

Motivation & Mental Model

  • From cloning weights to return weights: Behavior cloning ascended \frac{1}{N}\sum_t w_t \log \pi_\theta(a_t \mid s_t) with w_t = 1 on expert data; REINFORCE rolls out \pi_\theta itself and sets w_t = R(\tau).
  • Williams’ insight (1992): Weighting each sampled action’s score \nabla_\theta \log \pi_\theta(a_t \mid s_t) by R(\tau) gives an unbiased stochastic gradient of J(\theta) = \mathbb{E}[R(\tau)].

Softmax Preferences and the Score Function

Differentiating a Stochastic Policy

Because a deterministic \mathrm{argmax} policy has zero gradient almost everywhere and jumps discontinuously, policy gradient methods parameterize a smooth stochastic policy \pi_\theta(a \mid s):

\pi_\theta(a \mid s) = \frac{e^{\theta_{s,a}}}{\sum_{a''} e^{\theta_{s,a''}}}, \qquad \frac{\partial \log \pi_\theta(a \mid s)}{\partial \theta_{s,a'}} = \mathbf{1}(a' = a) - \pi_\theta(a' \mid s)

  • The score vector \nabla_\theta \log \pi_\theta(a \mid s): At state s, the gradient is \mathbf{e}_a - \pi_\theta(\cdot \mid s)—raising the chosen action’s preference by 1 - \pi_\theta(a \mid s) and lowering every other action’s preference in proportion to its current probability.
  • Zero row sum: Because \sum_{a'} (\mathbf{1}(a' = a) - \pi_\theta(a' \mid s)) = 0, the score is orthogonal to constant row shifts.
True

The Smallest Case: Rare Rewards Mean High Variance

Bias and Variance of a Single-State Estimator

\frac{\partial J}{\partial \theta_1} = \mathbb{E}_{a \sim \pi_\theta}\Big[r(a)\,\frac{\partial \log \pi_\theta(a)}{\partial \theta_1}\Big] = p(1 - p)

  • Unbiased but spiky: With probability p, action 1 returns estimator 1 - p; with probability 1 - p, action 2 returns 0.
  • Relative std \sqrt{(1 - p)/p}: At p \approx 0.014 on FrozenLake, single-episode noise is 8.4\times the true gradient.

Trajectory Probabilities and the Log-Derivative Trick

Differentiating Through an Expectation

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)

  • The log-derivative trick (\nabla_\theta P = P\,\nabla_\theta \log P): Multiplying and dividing by P(\tau; \theta) turns \nabla_\theta \sum_\tau P(\tau; \theta)R(\tau) back into a sampleable expectation \mathbb{E}_{\tau \sim P}[R(\tau)\,\nabla_\theta \log P(\tau; \theta)].

Why the Unknown Transition Kernel Drops Out

Model-Free Cancellation

Taking the logarithm of the trajectory product P(\tau; \theta) turns it into a sum in which only the policy terms depend on \theta:

\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)

  • Model-free gradient estimation: The environment dynamics P(s_{t+1} \mid s_t, a_t) govern which trajectories are sampled, but their derivatives with respect to \theta are identically zero.

The REINFORCE Estimator and Geometric Intuition

Monte Carlo Policy Gradient

Averaging R(\tau)\sum_t \nabla_\theta \log \pi_\theta(a_t \mid s_t) over n sampled trajectories \tau_1, \ldots, \tau_n gives Williams’ REINFORCE estimator:

\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)

  • Gaussian 1-step illustration: For \pi_\theta(a) = \mathcal{N}(a; \mu, 1), the score is \partial_\mu \log \pi_\theta(a) = a - \mu.
  • Reward-weighted pull: Each sampled action a_i pulls \mu toward a_i in proportion to R(a_i), moving \mu from 0 to 0.32 in 12 samples (exact gradient 0.52).

REINFORCE on the Verifier Task

One-Step Language Model Post-Training

On VerifierTask (4 prompts, 9 responses), a trajectory is a single response y \sim \pi_\theta(\cdot \mid x), and verifier_step averages K reward-weighted scores \mathbf{e}_y - \pi_\theta(\cdot \mid x) per prompt:

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
  • Flexible weighting hook: Passing weighting = lambda r: r executes vanilla REINFORCE; in §14.8, passing group-standardized rewards turns this exact same function into GRPO.

Verifying Unbiasedness on the Verifier Task

Sampled Estimates vs. the Exact Nine-Term Gradient

Comparing 10{,}000 independent K = 16 group estimates against the exact 9-term gradient \nabla_{\theta_x} J_x = \sum_y \pi_\theta(y \mid x)r(x, y)(\mathbf{e}_y - \pi_\theta(\cdot \mid x)) confirms our theoretical variance formula:

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)
  • Exact match with \sqrt{(1-p)/(Kp)}: At p \approx 1/8 and K = 16, one group estimate has RMS relative error \sqrt{7 / 16} = 0.66, and averaging M groups shrinks the error at the exact 0.66/\sqrt{M} rate with zero bias floor.
  • Unsolvable prompts receive zero gradient: On 8*8 and 9*9 (r = 0 for all candidates), 100\% of groups produce \hat{u} = \mathbf{0}.

Implementing Episodic REINFORCE on FrozenLake

Rollout Batching and Surrogate Loss Ascent

train_reinforce_tabular collects n = 16 complete episodes into a flat Batch, repeats each episode’s return R(\tau_i) across its steps via batch.per_step(R), and calls d2l.policy_step:

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)
  • Why calm ice first: At the uniform start, slippery ice attenuates each action’s directional control by 1/3, shrinking \|\nabla_\theta J\| three-fold and requiring 9\times larger batches for equal signal-to-noise ratio.

Training Trajectories and the Learned Policy Grid

From Flat Exploration to a Deterministic Shortest Path

Training 12 seeds of Policy.tabular(16, 4) over 256 updates on calm FrozenLake shows the characteristic S-curve of policy gradient learning:

  • Escape from the initial plateau: Early batches mostly fail (\hat{u} = \mathbf{0}); once a batch hits the goal, Adam boosts those 6 actions and locks onto one of the 6-move shortest paths (\gamma^5 \approx 0.774).

The Policy Gradient Theorem

Causality and Discounted State Occupancy

\nabla_\theta J(\theta) = \mathbb{E}_\tau\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]

  • Causality cancellation: Past rewards r_{<t} are fixed at s_t while \mathbb{E}_{a_t}[\nabla_\theta \log \pi_\theta(a_t \mid s_t)] = \mathbf{0}.
  • State-occupancy weighting: Scales updates at s by d_\gamma^{\pi_\theta}(s) = (1-\gamma)\sum_{t \geq 0} \gamma^t \Pr(s_t = s).

Sample Cost of On-Policy Data Collection

Why REINFORCE Needs Fresh Episodes Every Step

Because the expectation \mathbb{E}_{\tau \sim P(\cdot; \theta)} is taken under the current parameters \theta, old trajectories become stale after a single parameter update:

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
  • On-policy sample tax: Reaching 0.70 batch return takes a median of 32 updates (4{,}313 steps), and 256 updates consume \approx 27{,}000 steps—compared with \approx 3{,}500 steps for off-policy Q-learning on the same calm lake.

Exact Policy Gradient via Differentiable Linear Solve

Ground-Truth Reference on FrozenLake

Because J(\theta) = V^{\pi_\theta}(s_0) = [(I - \gamma P_{\pi_\theta})^{-1}r_{\pi_\theta}]_{s_0} is a smooth rational function of \theta, we can differentiate through linalg.solve to obtain the exact gradient \nabla_\theta J(\theta):

J(theta) after 16 updates = 0.313, against the ceiling gamma^5 = 0.774
  • Frozen probe policy: After 16 updates of seed 3, the probe achieves J(\theta) = 0.313 (roughly halfway between the uniform policy’s 0.008 and the 0.774 ceiling), providing a reference point to measure estimator noise.

Measuring REINFORCE Variance Against Exact Grad J

The 1/sqrt(n) Scaling Law

Drawing 50 independent REINFORCE batch estimates at the frozen probe for batch sizes n \in \{4, 16, 64\} quantifies the severe noise of raw return weighting:

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)
  • Nearly four gradient lengths of noise at n = 4: A single 4-episode draw misses \nabla_\theta J by 3.85\times the gradient’s norm (and 3/50 batches are identically zero); quadrupling n roughly halves the error (3.85 \to 1.78 \to 0.96), while the 50-draw mean matches \textrm{one}/\sqrt{50}, confirming zero bias.

Non-Concavity, Softmax Plateaus, and Locking

Optimization Landscape of Policy Gradients

Although J(\theta) is non-concave in \theta (even for 1 state and 2 actions, J(\theta) = \sigma(\theta_1 - \theta_2) has flat sigmoid tails), tabular softmax policy gradient has benign global geometry with practical caveats:

  • No suboptimal stationary points (Agarwal et al., 2021; Mei et al., 2020): When \mu_0(s) > 0 everywhere, exact tabular softmax gradient ascent converges globally to \pi^*.
  • Vanishing gradient on rare optimal actions (Li et al., 2021): Because \partial_{\theta_{s,a}} J \propto \pi_\theta(a \mid s), if the optimal action a^* currently has tiny probability \pi_\theta(a^* \mid s) \ll 1, plain SGD crawls across an exponential plateau (which Adam’s second-moment normalization mitigates).
  • Premature commitment under noise (Mei et al., 2021): Large noisy steps can push \pi_\theta(\cdot \mid s) nearly deterministic on a suboptimal action before enough samples arrive to reverse it.

Concept Check: Policy Gradients and REINFORCE

Check Your Understanding

Verify your mastery of the score function, log-derivative cancellation, and variance scaling:

  1. One lucky trajectory: At the uniform policy (\pi_\theta(a \mid s) = 1/4) with batch size n = 16, suppose 15 episodes hit holes (R = 0) and 1 episode reaches the goal in 6 steps (R = \gamma^5 \approx 0.774). What is the REINFORCE update vector \hat{u} at each of the 6 visited states?
  2. Model-free property: Where do the transition probabilities P(s_{t+1} \mid s_t, a_t) enter \nabla_\theta J(\theta) if they disappear from \nabla_\theta \log P(\tau; \theta)?
  3. Batch size scaling: At the frozen probe, a batch of n = 4 episodes has relative RMS error 3.85. Approximately how many episodes per batch are needed to reduce the single-batch relative error below 0.50?

Answers:

  1. Only the single successful episode contributes: at each of its 6 visited states, \hat{u}_s = \frac{\gamma^5}{16}(\mathbf{e}_{a_t} - \frac{1}{4}\mathbf{1}), which is +0.0363 on the taken action and -0.0121 on the other three actions.
  2. P(s_{t+1} \mid s_t, a_t) determines the sampling distribution P(\tau; \theta) over which the expectation \mathbb{E}_{\tau \sim P(\cdot; \theta)}[\cdots] is taken, which the environment simulator executes for us.
  3. Because RMS error scales as 1/\sqrt{n}, we need n \approx 4 \times (3.85 / 0.50)^2 \approx 4 \times 59.3 \approx 237 episodes per batch, motivating variance reduction via baselines in §14.8.

Summary: Policy Gradient Foundations

Key Takeaways

Concept Mathematical Formula Role & Practical Takeaway
Softmax score function \nabla_{\theta_s} \log \pi_\theta(a \mid s) = \mathbf{e}_a - \pi_\theta(\cdot \mid s) Zero-sum vector that boosts chosen action a and suppresses others
Log-derivative trick \nabla_\theta P(\tau; \theta) = P(\tau; \theta)\,\nabla_\theta \log P(\tau; \theta) Converts gradient of an expectation into an expectation of a score
Kernel cancellation \nabla_\theta \log P(\tau; \theta) = \sum_{t=0}^{T-1} \nabla_\theta \log \pi_\theta(a_t \mid s_t) Eliminates unknown dynamics P(s' \mid s, a) from the gradient estimator
REINFORCE estimator \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) Unbiased on-policy Monte Carlo gradient; high variance (O(1/\sqrt{n}))
Policy gradient theorem \nabla_\theta J = \mathbb{E}_\tau[\sum_{t \geq 0} \gamma^t \nabla_\theta \log \pi_\theta(a_t \mid s_t) Q^{\pi_\theta}(s_t, a_t)] Proves past rewards r_{<t} have zero expected product with step-t score