Chapter 6 · Post-training and Alignment 6.4
Reinforcement Learning Basics: Policy Gradients, Advantages and PPO
Policy gradients, baselines, GAE, PPO clipping and the KL penalty are the toolkit behind RLHF and reasoning RL. This page measures each on a toy task small enough to enumerate exactly: how baselines cut variance, why clipping is not a trust region, and where the KL belongs.
After this page you will be able to
- Write down the policy gradient, explain why the reward does not need to be differentiable, and why for a softmax policy the gradient of log π is a one-hot vector minus the probabilities.
- Prove that a baseline depending only on the state leaves the expected gradient unchanged, say what the advantage means, and read the bias and noise of the no-baseline, constant-baseline and value-baseline estimators.
- Write down GAE, explain how λ trades bias against variance, and why the bias comes from the critic's error rather than from λ itself.
- Say in which cases the PPO clipped objective has zero gradient, and why clipping limits the size of an update without being a strict trust region.
- Tell apart putting the KL penalty in the reward and in the loss (the k1, k2, k3 estimators), and explain why GRPO's mean-only group baseline shrinks the expected gradient by (G−1)/G while RLOO stays unbiased.
On this page
- Writing a response as a reinforcement learning problem
- The policy gradient: push up what scored well
- Experiment 1: is the formula right?
- Baselines and advantages: subtract what does not depend on the action
- Experiment 2: bias and noise of three baselines
- Experiment 3: how noise becomes training behavior
- GAE: trading critic error for variance
- Experiment 4: λ and the critic’s error
- When the data gets stale: importance ratios and PPO’s clipping
- Experiment 5: several epochs on the same batch
- KL: keeping the policy near a reference model
- Experiment 6: where does the KL penalty go?
- Dropping the value model: group baselines in GRPO and RLOO
- Experiment 7: expected gradient of group baselines
- Practical checklist
- Common misconceptions
- Summary and exercises
- Quick self-test
- Exercises
- Further reading
- FAQ
Reinforcement learning (RL) is learning without an answer key: the model generates first, is scored afterwards, and adjusts. RLHF and reasoning RL for large language models use the same four tools. The policy gradient gives the direction of the update (push up the probability of high-scoring responses). Baselines and advantage estimates cut the noise in that direction. Importance ratios and clipping let one batch of samples be reused for several updates without the policy running away (PPO). A KL penalty keeps the policy near a reference model.
The pages on preference optimization and reasoning RL use these words directly: PPO, advantage, GAE, KL. This page supplies the background and checks each piece. The test bed is a toy task small enough to be enumerated exactly: the probability and reward of all 4,096 sequences can be computed one by one, so “does this gradient estimator have bias, and how noisy is it” has an exact answer rather than a sampled estimate. A toy is not a large model. Magnitudes (how many times noisier, how large the KL gets) do not carry over to real training; the structural relations among bias, variance and KL do.
The seven experiments run one after another in a single script; the code blocks on this page, concatenated in order, are the complete script. Environment: Apple M2 Max (64 GB), CPU only; Python 3.14.3 and NumPy 2.4.2, no deep-learning framework. Every random number is seeded, so a rerun gives bit-identical numbers; on another machine the last digit of a few values may differ. A complete run takes about 1 minute.
Writing a response as a reinforcement learning problem
Generating a response is a sequence of decisions, and the vocabulary maps over one to one:
| RL term | In a language model |
|---|---|
| State | the prompt plus the first tokens written so far |
| Action | the next token (one pick from the vocabulary) |
| Policy | the language model itself: a distribution over the next token |
| Trajectory | one complete response |
| Reward | usually a single scalar at the end (a reward model’s score, or a verifier’s right or wrong); zero at every intermediate step |
| Objective |
Three features differ from textbook RL and shape the tricks that follow:
- Transitions are deterministic. The action is writing the next token and the next state is that token appended to the text, so all randomness sits in the policy and the probability of a trajectory is the product of its step probabilities.
- Rewards are sparse and arrive at the end. A reward model scores the whole response, or a verifier says right or wrong; nothing says which token deserves the credit. Credit assignment has to be estimated with baselines and value functions.
- The action space is huge and trajectories are long. Vocabularies have around a hundred thousand entries and responses run from hundreds to tens of thousands of tokens, so the variance of a gradient estimate can easily drown the signal.
The toy keeps the first two and shrinks the size until it can be enumerated: sequence length , a vocabulary of symbols, sequences in all. The reward is the fraction of adjacent pairs with : five pairs, so the values are 0, 0.2, …, 1. The uniform policy earns 0.25 on average (each pair satisfies the rule with probability ) and the best policy earns 1. The policy is a table of logits with one row per (position, previous symbol): parameters.
The policy gradient: push up what scored well
The objective is . When differentiating, the reward does not depend on the parameters; only the probability of the trajectory does. Then the log-derivative trick turns the derivative of a distribution back into an expectation under it:
Transitions are deterministic, so and the gradient is a sum over steps as well:
This is REINFORCE (Williams, 1992), and it reads naturally: sample a response, push up the log-probability of each of its tokens, and let the score of the whole response decide how hard; a high score pushes more, a low (or negative) score pushes down. The reward sits in the position of a weight and is never differentiated, so it can be a human rating, a reward model, or something that is not differentiable at all, such as “did the unit tests pass”. That is why RL can be used for RLHF and for verifiable rewards.
For a softmax policy the gradient of with respect to the logits is simple: a one-hot vector minus the probability vector, . The code below builds the toy task and checks the formula.
Experiment 1: is the formula right?
import itertools
import math
import numpy as np
# Toy task: sequences of length T=6 over a vocabulary of V=4. The reward
# is the fraction of adjacent pairs with a_t = a_(t-1)+1 (mod V), from 0
# to 1. The policy is a logits table theta[t, previous, next]: 120 numbers.
T, V = 6, 4
START = V # index of the start symbol
seqs = np.array(list(itertools.product(range(V), repeat=T))) # 4096
N = len(seqs)
prev = np.concatenate([np.full((N, 1), START), seqs[:, :-1]], axis=1)
R = (seqs[:, 1:] == (seqs[:, :-1] + 1) % V).mean(axis=1)
def log_policy(theta): # per-step log-softmax
z = theta - theta.max(-1, keepdims=True)
return z - np.log(np.exp(z).sum(-1, keepdims=True))
def policy(theta):
return np.exp(log_policy(theta))
def seq_logp(theta):
# log-probability of every sequence; seq_prob is its exponential
lp = log_policy(theta)
return sum(lp[t, prev[:, t], seqs[:, t]] for t in range(T))
def seq_prob(theta):
return np.exp(seq_logp(theta))
def score(theta):
# per-step ∇logπ(a_t|s_t), shape (N, T, 120)
pi = policy(theta)
phi = np.zeros((N, T) + theta.shape)
for t in range(T):
g = -pi[t, prev[:, t], :]
g[np.arange(N), seqs[:, t]] += 1.0
phi[np.arange(N), t, t, prev[:, t], :] = g
return phi.reshape(N, T, -1)
def exact_grad(theta):
# ∇J = Σ p(τ) R(τ) Σ_t ∇logπ(a_t|s_t), summed exactly over 4096 sequences
p = seq_prob(theta)
return ((p * R)[:, None] * score(theta).sum(1)).sum(0)
theta0 = np.zeros((T, V + 1, V)) # uniform policy
p0 = seq_prob(theta0)
g0 = exact_grad(theta0)
fd = np.zeros_like(g0)
for k in range(g0.size): # central differences for all 120 components
e = np.zeros(g0.size)
e[k] = 1e-5
up = seq_prob(theta0 + e.reshape(theta0.shape)) @ R
dn = seq_prob(theta0 - e.reshape(theta0.shape)) @ R
fd[k] = (up - dn) / 2e-5
print(f"sequences {N}, probabilities sum to {p0.sum():.6f}, "
f"J(uniform) = {p0 @ R:.4f}")
print(f"gradient norm {np.linalg.norm(g0):.5f}; max abs error between the "
f"formula and differences {np.abs(g0 - fd).max():.1e}")
sequences 4096, probabilities sum to 1.000000, J(uniform) = 0.2500
gradient norm 0.04841; max abs error between the formula and differences 1.4e-11
The gradient obtained by summing the formula exactly over 4,096 sequences and the central differences taken one by one over the 120 parameters agree to a maximum absolute error of 1.4e-11: the derivation is right and the code is right. Under the uniform policy the gradient norm is 0.04841. That number is small; remember it, because the next section compares it with the estimate a single sequence gives.
In real training we do not enumerate all sequences. We sample of them and estimate the expectation with the sample mean:
It is unbiased: its expectation is exactly the true gradient. The trouble is variance.
Baselines and advantages: subtract what does not depend on the action
Rewards are often non-negative, so even an average response has every one of its tokens pushed up a little. The signal hides in “pushed up more or less”, and since every batch contains different samples, the size of the push jumps around. The fix is to subtract a baseline from the reward:
As long as depends only on the state and not on the action taken there, this leaves the expectation unchanged:
So a baseline is a free noise reduction: no bias, and a good choice cuts the variance a lot. The most common baseline is the value function , “how much do we get on average from this state”. The reward minus it is the advantage:
Read the advantage as “how much better is this response than the average from this state”: better than average gets pushed up, worse gets pushed down. (The strict advantage is ; the sampled is an unbiased sample of , so the two agree in expectation.)
On the toy, can be computed exactly (enumerate all completions of each prefix), so bias and noise of three choices can be computed exactly: no baseline (), a constant baseline (, the equivalent of a batch mean) and a value baseline (, with an exact critic). Bias is the norm of the difference between the expected estimate and the true gradient; noise is the standard deviation of the estimate a single sequence gives; both are divided by the norm of the true gradient. The number of sequences needed to bring the noise down to half the gradient norm is .
Experiment 2: bias and noise of three baselines
def train_exact(theta, steps, lr):
# gradient ascent with the exact gradient: a policy that is trained
for _ in range(steps):
theta = theta + lr * exact_grad(theta).reshape(theta.shape)
return theta
theta_late = train_exact(theta0, 200, 3.0)
def prefix_values(theta):
# V_t(prefix): expected final reward after the first t symbols
P = seq_prob(theta).reshape((V,) * T)
Rt = R.reshape((V,) * T)
out = []
for t in range(T + 1):
axes = tuple(range(t, T))
num = (P * Rt).sum(axis=axes) if axes else P * Rt
den = P.sum(axis=axes) if axes else P
out.append(num / den)
return out
def value_at(vals, t, toks=seqs):
# value of each sequence's state (prefix) at step t, shape (count,)
return np.broadcast_to(vals[t][tuple(toks[:, :t].T)], (len(toks),))
def adv_none(theta): # no baseline: A_t = R
return np.repeat(R[:, None], T, axis=1)
def adv_mean(theta): # constant baseline: A_t = R - J
return np.repeat((R - seq_prob(theta) @ R)[:, None], T, axis=1)
def adv_critic(theta):
# state-value baseline (exact critic): A_t = R - V_t(s_t)
vals = prefix_values(theta)
return np.stack([R - value_at(vals, t) for t in range(T)], axis=1)
def grad_stats(theta, A):
# bias and noise of a gradient estimator, relative to ‖true gradient‖
p, phi, g = seq_prob(theta), score(theta), exact_grad(theta)
gi = (A[:, :, None] * phi).sum(1) # one estimate per sequence
mean = p @ gi
gn = np.linalg.norm(g)
bias = np.linalg.norm(mean - g) / gn
noise = math.sqrt((p * ((gi - mean) ** 2).sum(1)).sum()) / gn
return bias, noise
ESTIMATORS = [
("no baseline", adv_none),
("constant baseline", adv_mean),
("value baseline", adv_critic),
]
print("noise: std of a one-sequence estimate, in units of the gradient norm")
print("sequences needed: to bring the noise down to half the gradient norm")
for tag, theta in (("early", theta0), ("late", theta_late)):
print(f"{tag}: J = {seq_prob(theta) @ R:.3f}")
for name, fn in ESTIMATORS:
bias, noise = grad_stats(theta, fn(theta))
print(f" {name}: bias {bias:.4f}, noise {noise:.2f}, "
f"sequences needed {math.ceil(4 * noise**2)}")
noise: std of a one-sequence estimate, in units of the gradient norm
sequences needed: to bring the noise down to half the gradient norm
early: J = 0.250
no baseline: bias 0.0000, noise 13.82, sequences needed 765
constant baseline: bias 0.0000, noise 8.43, sequences needed 285
value baseline: bias 0.0000, noise 6.86, sequences needed 189
late: J = 0.966
no baseline: bias 0.0000, noise 113.10, sequences needed 51164
constant baseline: bias 0.0000, noise 16.19, sequences needed 1050
value baseline: bias 0.0000, noise 15.81, sequences needed 1001
All three have a bias of 0.0000, as the proof says: a baseline does not change the expectation. The whole difference is noise:
- Early in training (uniform policy, expected reward 0.250), the no-baseline noise is 13.82 times the gradient norm, the constant baseline 8.43, the value baseline 6.86. To bring the noise down to half the gradient, no baseline needs 765 sequences and the value baseline only 189.
- Late in training (expected reward 0.966), the gap widens a lot: no baseline has noise 113.10 and needs 51,164 sequences; a constant baseline has only 16.19 and needs 1,050, a ratio of about 48.8 in sequences (Exercise 2). Late in training most sequences have rewards near 1, so the true gradient signal is small, while the no-baseline estimate still carries the large term, which is almost pure noise.
- The value baseline is only somewhat better than the constant one (late: 15.81 against 16.19). The critic here is exact; a real value model has errors, and when Experiment 4 adds noise with to the critic, the noise of the value baseline () goes from 6.86 back to 8.17, almost the level of the constant baseline (8.43). So do not extrapolate this gap to the real benefit of a value model.
How does the noise turn into training behavior? The experiment below trains by sampling: every step draws sequences, estimates the gradient and takes one gradient-ascent step; each setting uses 40 random seeds, and the expected reward is computed exactly over 4,096 sequences at every step. Besides the three baselines two more things vary: the learning rate (1, 3, 10), and adding 5 to every reward (a reward model’s scores have no fixed zero point; the reward models page explains that only differences within the same prompt are meaningful).
Experiment 3: how noise becomes training behavior
def prev_of(toks):
return np.concatenate([np.full((len(toks), 1), START), toks[:, :-1]], 1)
def sample(theta, B, rng):
# sample B sequences from the policy, one symbol at a time
pi = policy(theta)
toks = np.zeros((B, T), dtype=int)
state = np.full(B, START)
for t in range(T):
u = rng.random((B, 1))
state = (pi[t, state].cumsum(1) < u).sum(1).clip(max=V - 1)
toks[:, t] = state
return toks
def reward_of(toks):
return (toks[:, 1:] == (toks[:, :-1] + 1) % V).mean(axis=1)
def batch_grad(theta, toks, adv):
# (1/B) Σ_i Σ_t A[i,t] ∇logπ(a_t|s_t), added up on sampled symbols
pi, prv = policy(theta), prev_of(toks)
B = len(toks)
g = np.zeros_like(theta)
for t in range(T):
d = -pi[t, prv[:, t]]
d[np.arange(B), toks[:, t]] += 1.0
np.add.at(g[t], prv[:, t], adv[:, t, None] * d)
return g / B
def advantage(kind, theta, toks, r, shift):
# r is the reward the learner sees (true reward + shift); exact critic
if kind == "none":
return np.repeat(r[:, None], T, axis=1)
if kind == "mean":
return np.repeat((r - r.mean())[:, None], T, axis=1)
vals = prefix_values(theta)
v = [value_at(vals, t, toks) + shift for t in range(T)]
return r[:, None] - np.stack(v, axis=1)
def entropy(theta):
# mean entropy of the policy on the states it actually visits (nats)
H = -(policy(theta) * log_policy(theta)).sum(-1) # (T, V+1)
p = seq_prob(theta)
return sum((p * H[t, prev[:, t]]).sum() for t in range(T)) / T
def run(kind, seed, lr, shift=0.0, steps=400, B=16):
rng = np.random.default_rng(seed)
theta = np.zeros((T, V + 1, V))
curve = [seq_prob(theta) @ R]
for _ in range(steps):
toks = sample(theta, B, rng)
r = reward_of(toks) + shift
A = advantage(kind, theta, toks, r, shift)
theta = theta + lr * batch_grad(theta, toks, A)
curve.append(seq_prob(theta) @ R)
return np.array(curve), entropy(theta)
KINDS = [
("none", "no baseline"),
("mean", "constant baseline"),
("critic", "value baseline"),
]
CURVES = {}
print("40 seeds, B=16 per batch. Each row: J at step 40, J at step 400 (std),")
print("worst seed's J, seeds with J<0.9, mean policy entropy")
for lr, shift in ((1.0, 0.0), (3.0, 0.0), (10.0, 0.0), (1.0, 5.0)):
print(f"learning rate {lr:g}, reward shifted by {shift:g}")
for kind, name in KINDS:
results = [run(kind, s, lr, shift) for s in range(40)]
cs = np.stack([c for c, _ in results])
ent = np.mean([h for _, h in results])
CURVES[(lr, shift, kind)] = cs.mean(axis=0)
low = int((cs[:, 400] < 0.9).sum())
print(f" {name}: {cs[:, 40].mean():.3f} {cs[:, 400].mean():.3f} "
f"({cs[:, 400].std():.3f}) {cs[:, 400].min():.3f} "
f"{low}/40 {ent:.3f}")
40 seeds, B=16 per batch. Each row: J at step 40, J at step 400 (std),
worst seed's J, seeds with J<0.9, mean policy entropy
learning rate 1, reward shifted by 0
no baseline: 0.373 0.981 (0.004) 0.969 0/40 0.097
constant baseline: 0.359 0.975 (0.006) 0.958 0/40 0.144
value baseline: 0.368 0.978 (0.005) 0.957 0/40 0.127
learning rate 3, reward shifted by 0
no baseline: 0.750 0.986 (0.043) 0.796 2/40 0.026
constant baseline: 0.700 0.995 (0.001) 0.993 0/40 0.032
value baseline: 0.731 0.996 (0.000) 0.995 0/40 0.029
learning rate 10, reward shifted by 0
no baseline: 0.875 0.919 (0.098) 0.798 16/40 0.008
constant baseline: 0.980 0.999 (0.000) 0.998 0/40 0.008
value baseline: 0.981 0.999 (0.000) 0.998 0/40 0.008
learning rate 1, reward shifted by 5
no baseline: 0.327 0.481 (0.189) 0.010 40/40 0.048
constant baseline: 0.359 0.975 (0.006) 0.958 0/40 0.144
value baseline: 0.368 0.978 (0.005) 0.957 0/40 0.127
- At a small learning rate the three are close. At learning rate 1 the values after 400 steps are 0.981, 0.975 and 0.978, and no baseline is even slightly ahead (0.373 against 0.359 and 0.368 at step 40): the noise is not yet big enough to overwhelm the signal. The difference is small and we do not interpret it.
- Low noise is what permits a large learning rate. At learning rate 3, 2 of the 40 no-baseline seeds fail to reach 0.9 (the worst ends at only 0.796), while the two baselines average 0.995 and 0.996 after 400 steps with a worst case of 0.993. At learning rate 10, 16 of the 40 no-baseline seeds stop below 0.9 and the mean is only 0.919, while the two baselines are already at 0.980 and 0.981 by step 40 and end at 0.999. The practical value of noise reduction is that the learning rate can be raised for faster convergence.
- A baseline makes the update independent of where the reward’s zero is. With 5 added to every reward, no baseline ends at 0.481, all 40 seeds are below 0.9 and the worst is only 0.010. The two baselines give bit-identical results to the unshifted run, because they subtract the shift away.
- Failure looks like “very sure, and wrong”. With the shift of 5, the no-baseline policy has an average entropy of 0.048, lower than the 0.144 of the constant baseline under the same setting, yet its expected reward is only 0.481: noise pushes up whichever responses happened to be sampled, they become more likely to be sampled again, the policy quickly becomes almost deterministic, and it never explores its way to better responses. At learning rate 10 all three average an entropy of 0.008, so the 16 failed no-baseline seeds are also nearly deterministic policies stuck on a wrong choice. The “entropy collapse” that recurs in reasoning RL (the DAPO paper tackles it directly) is a similar phenomenon in large models; this toy does not separate causes, it only shows that the symptoms match.
A baseline reduces noise; it cannot create signal. If every response to a prompt gets the same reward (all right or all wrong), the advantage is zero everywhere and that batch teaches nothing about that prompt.
The widget below turns experiment 3 into a version with your own parameters: pick a baseline, tune the learning rate and the reward shift, and rerun sampled training on the same toy task (J is computed exactly over all 4,096 sequences at every step). Try “add 5 to every reward” and larger learning rates to watch noise crush the no-baseline policy.
GAE: trading critic error for variance
The value baseline uses : the final reward of the whole response minus a baseline. It is unbiased, but carries the luck of all the tokens that follow, so the noise is high. The other extreme looks only one step ahead: the value estimate of the next state replaces all later rewards, giving the temporal-difference error
It has low noise, but it is biased whenever is inaccurate. Generalized Advantage Estimation (GAE; Schulman et al., 2015) connects the two ends with a single parameter :
At only is left; at and the terms telescope into , the value baseline above. Responses have finite length and is common for language models; the hyperparameter tables of the PPO paper use and .
On the toy the critic gets noise: , an independent Gaussian per prefix (real critic errors are correlated between similar states; this is the simplest assumption), and the end uses the true reward. The result depends strongly on the draw of the critic noise, so each setting averages 10 draws; the first version of the script drew only one and got a bias about half of the current value, which is why it was changed. Besides noise and bias, the table gives the root-mean-square error of the gradient estimate at batch size , : the larger the batch, the smaller the noise term and the more the bias matters.
Experiment 4: λ and the critic’s error
def adv_gae(theta, lam, sigma, seed=0):
# δ_t = V̂_(t+1) - V̂_t, A_t = Σ_l λ^l δ_(t+l); V̂ = V + σ·noise with
# one independent Gaussian per prefix; the end uses the true reward
rng = np.random.default_rng(seed)
vals = prefix_values(theta)
noisy = [v + sigma * rng.standard_normal(np.shape(v)) for v in vals]
vhat = np.stack([value_at(noisy, t) for t in range(T)] + [R], axis=1)
delta = vhat[:, 1:] - vhat[:, :-1]
return np.stack([sum(lam**l * delta[:, t + l] for l in range(T - t))
for t in range(T)], axis=1)
for sigma in (0.0, 0.1):
print(f"critic noise σ={sigma} (early policy; mean of 10 noise draws, "
"std in brackets)")
for lam in (0.0, 0.5, 0.9, 0.95, 1.0):
st = np.array([grad_stats(theta0, adv_gae(theta0, lam, sigma, s))
for s in range(10)])
bias, noise = st[:, 0], st[:, 1]
rms = [np.sqrt(bias**2 + noise**2 / B).mean() for B in (16, 256)]
print(f" λ={lam:<4}: bias {bias.mean():.4f} ({bias.std():.4f}), "
f"noise {noise.mean():.2f}, "
f"RMS error B=16: {rms[0]:.2f}, B=256: {rms[1]:.2f}")
critic noise σ=0.0 (early policy; mean of 10 noise draws, std in brackets)
λ=0.0 : bias 0.0000 (0.0000), noise 3.32, RMS error B=16: 0.83, B=256: 0.21
λ=0.5 : bias 0.0000 (0.0000), noise 3.84, RMS error B=16: 0.96, B=256: 0.24
λ=0.9 : bias 0.0000 (0.0000), noise 5.81, RMS error B=16: 1.45, B=256: 0.36
λ=0.95: bias 0.0000 (0.0000), noise 6.29, RMS error B=16: 1.57, B=256: 0.39
λ=1.0 : bias 0.0000 (0.0000), noise 6.86, RMS error B=16: 1.71, B=256: 0.43
critic noise σ=0.1 (early policy; mean of 10 noise draws, std in brackets)
λ=0.0 : bias 1.1319 (0.3695), noise 6.69, RMS error B=16: 2.04, B=256: 1.21
λ=0.5 : bias 0.6024 (0.2098), noise 6.21, RMS error B=16: 1.68, B=256: 0.72
λ=0.9 : bias 0.1298 (0.0418), noise 7.33, RMS error B=16: 1.84, B=256: 0.48
λ=0.95: bias 0.0656 (0.0208), noise 7.71, RMS error B=16: 1.93, B=256: 0.49
λ=1.0 : bias 0.0000 (0.0000), noise 8.17, RMS error B=16: 2.04, B=256: 0.51
- With an exact critic () every is unbiased (all biases are 0.0000), and noise falls as falls: 3.32 at , 6.86 at . So the source of bias is not but the critic’s error.
- With a noisy critic () the bias grows as falls: 1.1319 at (larger than the true gradient itself), 0.6024 at , 0.1298 at , 0 at . A small means trusting the critic’s value of the following states more, and all of its error turns into bias.
- The best depends on the batch size. At the smallest RMS error is at (1.68), and both ends, and , are at 2.04. At the smallest is at (0.48), with and close behind (0.49 and 0.51), while has reached 1.21. With a large batch the noise averages out, what remains is mostly bias, and so the unbiased end deserves more trust.
So a smaller is not automatically safer: it picks a proportion between “trust the critic” and “trust the samples”. With a good critic and a small batch, go lower; with an unreliable critic and a large batch, go higher. Common values lie between 0.9 and 0.97.
A value model has extra costs in large language models: it has to be as large as the policy (doubling memory and compute), and since the reward arrives only once, at the last token, getting it right at every token is hard (the DeepSeekMath paper gives these two points as its motivation for removing the value model in GRPO).
The widget below moves this experiment into the browser, on the same toy task and the same uniform policy. Drag lambda: with an exact critic the noise climbs from 3.32 to 6.86; with a critic that carries error, smaller lambda means more bias while the noise dips and then rises, so the best lambda depends on the batch size. The lower half lays out one sequence: position by position, the exact value, the noisy critic’s value and the TD errors, and how lambda’s powers weight them into an advantage. The circles on the chart are the page’s ten printed cells.
When the data gets stale: importance ratios and PPO’s clipping
The expectation in the policy gradient is taken under the current policy . Every update of makes the samples in hand a little more out of date, yet generating responses is the most expensive step of the whole training, and throwing samples away after one use is wasteful. Can one batch be used for several rounds?
The tool is importance sampling: take samples drawn from the old policy and correct them with the probability ratio :
The surrogate objective has exactly the policy gradient as its gradient at (there and ). But it approximates the true objective well only while stays near : the advantages were estimated under the old policy, and optimizing over and over on the same samples optimizes the noise in those samples. Implementations use the per-token ratio rather than the ratio of the whole response (the latter is a product of ratios whose variance grows quickly with length), which is an approximation; GSPO argues for the opposite, a length-normalized sequence-level ratio (see the paper walkthrough).
TRPO (Schulman et al., 2015) adds a constraint , which needs an approximate second-order method (conjugate gradient). PPO (Schulman et al., 2017) swaps it for an objective that first-order methods can optimize, one that takes away the incentive to go further once a token is out of range:
The figure below plots the objective value of a single token as a function of . The makes it a pessimistic estimate: it cuts only when the update has gone too far in the favorable direction, never in the direction that makes things worse.
Four cases. When the advantage is positive and (already pushed up enough), or negative and (already pushed down enough), the objective is constant and the gradient is zero. In the other cases the gradient is kept, including the two that need to be pulled back: “positive advantage but pushed down” and “negative advantage but pushed up” (Exercise 4 checks each case). The PPO paper compares settings on 7 MuJoCo tasks with 3 seeds each: no clipping scores −0.39 normalized (one task ends worse than the random policy), and , 0.2, 0.3 score 0.76, 0.82 and 0.70 (Table 1 of the paper).
One PPO iteration: sample a batch of responses with and score them; estimate advantages (GAE, which needs a value model); split the batch into minibatches and run gradient ascent on the clipped objective for several epochs (the value model is trained by regression at the same time); then set and start over.
Experiment 5: several epochs on the same batch
Start from a half-trained policy (expected reward 0.568), draw only sequences each time (so the advantages are very noisy), run epochs of gradient ascent on that batch, and compare two versions: unclipped (the importance-ratio surrogate, keep going) and clipped (). Advantages use the batch-mean baseline. Repeat for 100 batches; ΔJ and the KL to the old policy are computed exactly over the 4,096 sequences.
def token_logp(theta, toks):
lp, prv = log_policy(theta), prev_of(toks)
return np.stack([lp[t, prv[:, t], toks[:, t]] for t in range(T)], axis=1)
def kl_seq(old, new):
# KL(π_old ‖ π_new), summed exactly over the 4096 sequences, in nats
lo = seq_logp(old)
return float(np.exp(lo) @ (lo - seq_logp(new)))
def ppo_epochs(theta_old, toks, A, K, lr, clip, eps=0.2):
# K epochs of ascent on one batch; returns the policy after each epoch
# and the share of tokens whose ratio left [1-eps, 1+eps]
theta, lp_old, out = theta_old.copy(), token_logp(theta_old, toks), []
for _ in range(K):
rho = np.exp(token_logp(theta, toks) - lp_old) # importance ratio
coef = A * rho # ∇(ρA) = A·ρ·∇logπ
if clip:
# the clipped objective is constant in these two cases
dead = ((A > 0) & (rho > 1 + eps)) | ((A < 0) & (rho < 1 - eps))
coef = np.where(dead, 0.0, coef)
theta = theta + lr * batch_grad(theta, toks, coef)
rho = np.exp(token_logp(theta, toks) - lp_old)
out.append((theta, ((rho > 1 + eps) | (rho < 1 - eps)).mean()))
return out
EPS, B, LR, K_MAX, BATCHES = 0.2, 8, 3.0, 64, 100
theta_mid = train_exact(theta0, 30, 3.0)
J_mid = seq_prob(theta_mid) @ R
KL_CURVE = {c: np.zeros((BATCHES, K_MAX)) for c in (False, True)}
DJ = {c: np.zeros((BATCHES, K_MAX)) for c in (False, True)}
OUT = {c: np.zeros((BATCHES, K_MAX)) for c in (False, True)}
for seed in range(BATCHES):
toks = sample(theta_mid, B, np.random.default_rng(seed))
A = advantage("mean", theta_mid, toks, reward_of(toks), 0.0)
for clip in (False, True):
for k, (th, share) in enumerate(
ppo_epochs(theta_mid, toks, A, K_MAX, LR, clip, EPS)):
KL_CURVE[clip][seed, k] = kl_seq(theta_mid, th)
DJ[clip][seed, k] = seq_prob(th) @ R - J_mid
OUT[clip][seed, k] = share
print(f"start J = {J_mid:.3f}; {BATCHES} batches of {B} sequences, "
f"learning rate {LR:g}, ε = {EPS}")
print("Each row: median ΔJ, batches with ΔJ<0, median KL (max), share of")
print("tokens out of range")
for clip in (False, True):
print("clipped" if clip else "unclipped")
for k in (1, 4, 16, 64):
dj, kl = DJ[clip][:, k - 1], KL_CURVE[clip][:, k - 1]
print(f" {k:>2} epochs: {np.median(dj):.3f} "
f"{int((dj < 0).sum())}/{BATCHES} "
f"{np.median(kl):.3f} ({kl.max():.3f}) "
f"{OUT[clip][:, k - 1].mean():.0%}")
start J = 0.568; 100 batches of 8 sequences, learning rate 3, ε = 0.2
Each row: median ΔJ, batches with ΔJ<0, median KL (max), share of
tokens out of range
unclipped
1 epochs: 0.009 0/100 0.007 (0.031) 3%
4 epochs: 0.032 0/100 0.114 (0.417) 41%
16 epochs: 0.081 7/100 1.346 (2.604) 81%
64 epochs: 0.171 16/100 4.872 (6.830) 94%
clipped
1 epochs: 0.009 0/100 0.007 (0.031) 3%
4 epochs: 0.028 0/100 0.054 (0.112) 34%
16 epochs: 0.042 0/100 0.113 (0.197) 65%
64 epochs: 0.042 0/100 0.147 (0.269) 77%
- After the first epoch the two are identical (the ratios are 1, clipping has not acted yet).
- Without clipping the KL has no ceiling: the median is 0.114 (4 epochs), 1.346 (16 epochs), 4.872 (64 epochs), with a maximum of 6.830. The median ΔJ is indeed larger (0.171), but 16 of 100 batches end worse than they started: walking along the noise in 8 samples, the farther it goes the more it overfits.
- With clipping the KL flattens: 0.113 (16 epochs), 0.147 (64 epochs), maximum 0.269, and no batch got worse. The price is smaller progress per batch: the median ΔJ stays at 0.042. PPO is not designed to learn more from each batch but to keep the size of each update under control; progress accumulates through fresh samples.
- Clipping is not a hard constraint. After 64 epochs 77% of tokens still have ratios outside (94% without clipping): tokens already out of range in the favorable direction stop contributing gradient, but updates from other tokens, and from tokens sharing the same row of logits, keep carrying them further. Engstrom et al. (2020) measured the same thing on MuJoCo: PPO trained with ratio clipping still lets the ratios leave the interval, and they found that most of PPO’s gain over TRPO comes from code-level optimizations such as reward scaling and value clipping, not from clipping itself. A common remedy in implementations is KL early stopping. The OpenAI Spinning Up documentation of PPO says that clipping helps keep updates reasonable but the new policy can still end up too far from the old one, so its implementation stops taking gradient steps once the average KL of the new policy from the old one exceeds a threshold (the
target_klparameter, default 0.01 in the function signature).
The experiment is small (100 batches, 8 sequences each, one fixed starting point), so do not read the number of batches that got worse as a general rule. What it shows is the mechanism: without clipping the size of the update grows without bound as epochs accumulate, and clipping levels it off.
The widget below makes that figure draggable: set the ratio rho, the advantage and eps to see which stretch is flat, which keeps its slope, and where each of the page’s situations falls. The one-state panel in the middle shrinks “many epochs on one batch” to one state with four actions, with exact gradients at every step. When only action 0 has an advantage, all gradients become 0 once it leaves the band and the update stops exactly; with advantages of both signs, the clipped token contributes nothing of its own, yet its rho is carried further out by the other actions, so clipping is not a hard constraint. The page’s experiment 5 closes the widget.
KL: keeping the policy near a reference model
RLHF trades off the score against “how far from the reference model”. The reference policy is usually the SFT model:
By the chain rule, the sequence-level KL is the expectation of the sum of per-token log-ratios:
So each token’s log-ratio is an unbiased sample of the KL. Write ; Schulman (2020) gives three estimators:
| Estimator | Formula | Properties |
|---|---|---|
| unbiased; a single sample can be negative; high variance | ||
| biased but only slightly; low variance; non-negative | ||
| unbiased; non-negative; low variance when the KL is small |
Their expectations on a vocabulary of 8 tokens and their standard deviations over 200,000 samples are checked in the DeepSeek-R1 walkthrough, so we do not repeat that. The question here is a different one: in training, does the KL go into the reward or into the loss?
- In the reward (InstructGPT, and Ziegler et al.): subtract from each token’s reward and take a policy gradient with advantage estimates. The current token affects the KL of later steps, and the return accumulated to the end of the response counts this automatically.
- In the loss (GRPO): add to the loss and differentiate it. It is simpler and takes no space in the reward channel.
Tang and Munos (2025) point out two common implementation pitfalls: differentiating a sample-based KL estimator used as a loss usually does not give the KL gradient you wanted, and a per-token loss does not account for the fact that the current token changes the KL of later steps, so it is at best a partial gradient. The experiment below measures both on the toy.
Experiment 6: where does the KL penalty go?
The reference and the current policy both get asymmetric random logits: the toy task has a cyclic symmetry, and symmetric policies would make some variants coincide by accident. The exact gradient comes from central differences; the expected gradient of each variant is summed exactly over the 4,096 sequences and compared with it.
# Reference and current policy get asymmetric random logits, so that the
# toy task's cyclic symmetry does not make the variants agree by accident
rng = np.random.default_rng(5)
theta_ref = 0.7 * rng.standard_normal(theta0.shape)
theta_pol = train_exact(theta_ref, 30, 3.0)
theta_pol = theta_pol + 0.4 * rng.standard_normal(theta0.shape)
def token_logp_all(theta):
lp = log_policy(theta)
return np.stack([lp[t, prev[:, t], seqs[:, t]] for t in range(T)], axis=1)
def fd_grad(f, theta, h=1e-5):
g = np.zeros(theta.size)
for k in range(theta.size):
e = np.zeros(theta.size)
e[k] = h
g[k] = (f(theta + e.reshape(theta.shape))
- f(theta - e.reshape(theta.shape))) / (2 * h)
return g
def seq_kl(theta): # KL(π_θ ‖ π_ref)
lp = seq_logp(theta)
return float(np.exp(lp) @ (lp - seq_logp(theta_ref)))
g_kl = fd_grad(seq_kl, theta_pol) # exact gradient (central differences)
log_ratio = token_logp_all(theta_pol) - token_logp_all(theta_ref) # (N, T)
p, phi = seq_prob(theta_pol), score(theta_pol)
to_go = np.cumsum(log_ratio[:, ::-1], axis=1)[:, ::-1] # return-to-go
VARIANTS = [
("k1 in the reward (to-go sum)", to_go),
("k1 as a loss", np.ones_like(log_ratio)),
("k2 as a loss", log_ratio),
("k3 as a loss", 1 - np.exp(-log_ratio)),
]
print(f"KL(π‖π_ref) = {seq_kl(theta_pol):.3f} nats; norm of the exact "
f"gradient {np.linalg.norm(g_kl):.3f}")
print("Rows below, against the exact gradient: norm ratio, cosine, largest")
print("component difference")
grads = []
for name, coef in VARIANTS:
# expected gradient = Σ_i p_i Σ_t coef[i,t] ∇logπ(a_t|s_t)
g = ((p[:, None] * coef)[:, :, None] * phi).sum((0, 1))
grads.append(g)
ratio = np.linalg.norm(g) / np.linalg.norm(g_kl)
cos = g @ g_kl / (np.linalg.norm(g) * np.linalg.norm(g_kl))
err = np.abs(g - g_kl).max()
cos = f"{cos:.4f}" if ratio > 1e-6 else "—"
print(f" {name}: norm ratio {ratio:.4f}, cosine {cos}, "
f"max diff {err:.1e}")
# With the state distribution frozen at π_θ, the per-state KL gradients:
# what do k2 and k3 as losses actually optimize?
visit = np.zeros((T, V + 1))
for t in range(T):
np.add.at(visit[t], prev[:, t], p)
def frozen_kl(theta, forward):
lp, lr_ = log_policy(theta), log_policy(theta_ref)
if forward: # KL(π_ref ‖ π_θ)
row = (np.exp(lr_) * (lr_ - lp)).sum(-1)
else: # KL(π_θ ‖ π_ref)
row = (np.exp(lp) * (lp - lr_)).sum(-1)
return float((visit * row).sum())
g_rev = fd_grad(lambda th: frozen_kl(th, False), theta_pol)
g_fwd = fd_grad(lambda th: frozen_kl(th, True), theta_pol)
print("Per-state KL gradients with the state distribution frozen, against")
print("the expected gradients of the losses:")
print(f" KL(π‖π_ref) vs k2: max difference "
f"{np.abs(grads[2] - g_rev).max():.1e}")
print(f" KL(π_ref‖π) vs k3: max difference "
f"{np.abs(grads[3] - g_fwd).max():.1e}")
KL(π‖π_ref) = 2.420 nats; norm of the exact gradient 0.746
Rows below, against the exact gradient: norm ratio, cosine, largest
component difference
k1 in the reward (to-go sum): norm ratio 1.0000, cosine 1.0000, max diff 7.9e-11
k1 as a loss: norm ratio 0.0000, cosine —, max diff 4.3e-01
k2 as a loss: norm ratio 0.8592, cosine 0.9832, max diff 1.3e-01
k3 as a loss: norm ratio 1.3638, cosine 0.9543, max diff 2.0e-01
Per-state KL gradients with the state distribution frozen, against
the expected gradients of the losses:
KL(π‖π_ref) vs k2: max difference 3.2e-11
KL(π_ref‖π) vs k3: max difference 2.5e-11
- k1 in the reward (accumulated to the end): agrees with the exact gradient component by component, maximum difference 7.9e-11. The accumulation is the key: the current token’s choice changes the KL of every later step.
- k1 as a loss: the expected gradient is exactly zero (norm ratio 0.0000; the cosine is meaningless). The reason is : such a “KL penalty” does nothing on average and only adds noise.
- k2 and k3 as losses: close in direction, but not the gradient of the sequence-level KL. The cosines with the exact gradient are 0.9832 and 0.9543, the norm ratios 0.8592 and 1.3638. The last two lines of the output show what each one optimizes. With the state distribution frozen at the states visits, the expected gradient of k2 as a loss is the gradient of the per-state (maximum difference 3.2e-11), while that of k3 as a loss is the gradient of the per-state (maximum difference 2.5e-11), the KL with its arguments swapped. Both are also only “partial gradients”: they miss the effect of the current token on the KL of later steps. The DeepSeek-R1 walkthrough checked the direction of k3 for a single step on a small vocabulary (see above), and the DeepSeek-V3.2 walkthrough discusses the same issue.
These numbers come from one specific pair of policies, so the size of the cosines does not generalize. What does generalize is the conclusion: a per-token estimator used as a loss is only an approximation, and to optimize “reward minus KL” exactly, put the log-ratio in the reward and accumulate it to the end. GRPO chose the loss, trading exactness for simplicity, which is why needs tuning and the KL curve needs watching.
Dropping the value model: group baselines in GRPO and RLOO
A value model is expensive (see above). GRPO (DeepSeekMath, 2024) draws responses to the same prompt and uses statistics of the rewards within the group instead of a value baseline:
| Variant | Advantage |
|---|---|
| Subtract the mean (as in Dr. GRPO) | |
| Original GRPO | |
| RLOO (leave-one-out) |
RLOO comes from Kool et al. (2019) and was applied to RLHF by Ahmadian et al. (2024). The catch is that the baseline contains response ‘s own reward: the baseline depends on that action, which breaks the condition above for “a baseline does not change the expectation”. Expand the mean baseline:
The bracket on the right is exactly the RLOO advantage. Its baseline uses only the other responses and is independent of response , so it is unbiased; hence the expected gradient of the mean-subtracted version is exactly of the true gradient. Dividing by the standard deviation adds another layer: the scale factor changes with the difficulty of the prompt. The experiment below takes binary rewards (probability of being right), enumerates all right/wrong patterns of responses exactly, and computes the ratio of the expected gradient to the true one.
Experiment 7: expected gradient of group baselines
def expected_ratio(p, G, kind):
# enumerate all 2^G right/wrong patterns of G responses; returns
# E[gradient estimate] / true gradient. For one response ∇logπ w.r.t.
# the logit is 1-p if right and -p if wrong; the true gradient is p(1-p)
total = 0.0
for pattern in itertools.product((0.0, 1.0), repeat=G):
r = np.array(pattern)
prob = p ** r.sum() * (1 - p) ** (G - r.sum())
phi = np.where(r == 1, 1 - p, -p)
if kind == "mean":
A = r - r.mean()
elif kind == "std":
A = (r - r.mean()) / (r.std() + 1e-4)
else:
A = r - (r.sum() - r) / (G - 1)
total += prob * (A * phi).mean()
return total / (p * (1 - p))
PS = (0.05, 0.25, 0.5)
for G in (2, 4, 8, 12):
mean = [expected_ratio(p, G, "mean") for p in PS]
rloo = [expected_ratio(p, G, "rloo") for p in PS]
std = [expected_ratio(p, G, "std") for p in PS]
assert max(mean) - min(mean) < 1e-9 and max(rloo) - min(rloo) < 1e-9
print(f"G={G:<2} mean-only {mean[0]:.4f}, RLOO {rloo[0]:.4f}")
print(" divided by std, p=" + "/".join(map(str, PS)) + ": "
+ " ".join(f"{v:.4f}" for v in std))
G=2 mean-only 0.5000, RLOO 1.0000
divided by std, p=0.05/0.25/0.5: 0.9998 0.9998 0.9998
G=4 mean-only 0.7500, RLOO 1.0000
divided by std, p=0.05/0.25/0.5: 1.7096 1.6447 1.6157
G=8 mean-only 0.8750, RLOO 1.0000
divided by std, p=0.05/0.25/0.5: 2.4724 2.0256 1.8553
G=12 mean-only 0.9167, RLOO 1.0000
divided by std, p=0.05/0.25/0.5: 2.9402 2.1463 1.9097
- Mean subtraction: exactly , independent of (0.5000 at , 0.8750 at , 0.9167 at ). The direction is unchanged, only the whole gradient shrinks, and the smaller the group the more it shrinks; a learning rate can compensate.
- RLOO: 1.0000 throughout. It is unbiased, at the cost of every advantage using the information of other responses and no extra model.
- Dividing by the standard deviation: the scale factor varies with . At the factor is 2.4724 at and 1.8553 at : very hard or very easy prompts (probability of being right near 0 or 1) are relatively amplified. This is the “question-level difficulty bias” pointed out by Dr. GRPO (Liu et al., 2025). At the advantage can only be ±1 and the factor is about 1.
The experiment covers a single prompt with binary rewards and does not include the per-response length normalization in the GRPO loss (which Dr. GRPO identifies as a source of length bias). If you do want standard-deviation normalization, you can apply it to the advantages of the whole batch together: all prompts share one scale, so the relative weights of prompts do not change.
Practical checklist
- Always subtract a baseline, and make it depend only on the state or on the other samples. In Experiment 3, adding 5 to every reward leaves all 40 no-baseline seeds below 0.9 while the two baselines give bit-identical results to the unshifted run.
- Spend the noise reduction on a larger learning rate or a smaller batch instead of leaving it unused, and check every change on several seeds: at learning rate 3 only 2 of 40 no-baseline seeds fail, and a single seed would never show it.
- Monitor the size of updates: the approximate KL (new against old) per iteration and the share of tokens whose ratio is out of range. In Experiment 5 the out-of-range share is still 77% after 64 epochs; a clipped ratio is not a bounded ratio. Stop the updates on the batch once a threshold is exceeded.
- Monitor the policy entropy. In Experiment 3, with 5 added to the rewards, the no-baseline entropy falls to 0.048, below the 0.144 of the healthy run, while the reward is only 0.481: the policy is nearly deterministic yet stuck on a wrong choice, and it will not explore its way to better responses afterwards.
- Plot reward and KL together. A reward that rises while the KL grows without bound is often over-optimization of the proxy; see reward models.
- Decide whether the KL goes into the reward or the loss, and write it down. To optimize “reward minus KL” exactly, put it in the reward and accumulate it to the end; in the loss it is only an approximation and has to be tuned by experiment.
- With group baselines, watch the group size and the normalization. In a small group ( of 2 to 4) the mean baseline shrinks the step by 25% to 50%; standard-deviation normalization changes the weights of different prompts, so do it over the whole batch if you can.
- A prompt whose responses are all right or all wrong carries no learning signal (all advantages are zero); when they make up too large a share, change the prompts or sample more responses.
Common misconceptions
| Misconception | What actually happens |
|---|---|
| ”A baseline adds bias, so it is better not to use one” | A baseline that depends only on the state is unbiased: in Experiment 2 all three estimators have a bias of 0.0000 while the noise differs by a factor of 7 (late: 113.10 against 16.19) |
| “PPO’s clipping guarantees the new policy stays close to the old one” | It only stops out-of-range favorable tokens from contributing gradient; in Experiment 5, 77% of tokens are still out of range after 64 epochs and the KL merely flattens |
| ”A smaller GAE λ is always more stable” | The bias comes from the critic’s error: when the critic is inaccurate a small λ only turns its error into bias (Experiment 4) |
| “A KL penalty in the loss is the same as one in the reward” | Experiment 6: k1 in the loss has zero expected gradient; only the reward version, accumulated to the end, gives the exact gradient |
| ”GRPO’s mean-only group baseline is unbiased” | The baseline contains the response’s own reward, so the expected gradient is smaller by (G−1)/G; RLOO is the unbiased one |
| ”Making all rewards larger makes the policy better” | Without a baseline, shifting every reward can make training fail (Experiment 3); only differences within a prompt matter |
Summary and exercises
- The policy gradient is unbiased and the reward need not be differentiable; the noise of a single sample can still be ten to a hundred times the true gradient.
- A baseline that depends only on the state leaves the expectation unchanged and cuts the noise to a fraction (a factor of 7 late in training) and the required number of sequences by a factor of tens; the practical payoff is a larger usable learning rate and updates that no longer depend on where the reward’s zero is.
- The bias of GAE comes from the critic’s error: with an accurate critic every is unbiased; with an inaccurate one chooses a proportion between bias and variance, and the larger the batch the closer to 1 it should be.
- PPO’s clipping stops out-of-range favorable tokens from contributing gradient and keeps the KL low, but it is not a hard constraint; monitor the approximate KL and the out-of-range share, and stop early if needed.
- A KL penalty in the reward (accumulated to the end) gives the exact gradient; a per-token estimator in the loss only approximates it. A mean-only group baseline shrinks the expected gradient by , RLOO is unbiased, and standard-deviation normalization introduces a difficulty bias.
Quick self-test
1. Which of these can NOT serve as a baseline for the policy gradient (keeping the estimate unbiased)?
- A constant, such as the average reward in the batch
- The value function
- The average reward of the other responses to the same prompt
- This response’s own final reward
A baseline must not depend on the current action for to hold. depends on every action in this response, and subtracting it wipes out the gradient estimate entirely. The other three do not depend on the current response, so they are legitimate (RLOO’s baseline is exactly the third).
2. In Experiment 2 the no-baseline noise late in training is 113.10 times the gradient norm and the constant baseline’s is 16.19. Which statements are true?
- Both estimators have a bias of 0.0000; the whole difference is noise
- Late in training most sequences have rewards near 1 and the true gradient is small, while the no-baseline estimate still contains a large term
- The constant baseline introduces a small bias and buys lower noise in exchange
- To bring the noise down to half the gradient, no baseline needs 51,164 sequences and the constant baseline only 1,050
A baseline is a free noise reduction, not a bias-variance trade: both biases are 0.0000. The noise ratio is 113.10/16.19 ≈ 6.98, and the ratio of required sequences is its square, about 48.8 (Exercise 2).
3. In Experiment 4, how does GAE’s bias change with when the critic is exact ()? And when the critic is noisy ()?
- In both cases the bias grows as falls
- At every has a bias of 0.0000; at the bias grows as falls
- At the bias is largest at
- The bias depends only on , not on the critic
The bias comes from the critic’s error. With an exact critic the conditional expectation of is the true advantage and every is unbiased; with a noisy critic, the smaller the the more it relies on the critic and the more of its error turns into bias (1.1319 at , 0 at ).
4. In PPO’s clipped objective (), which tokens have zero gradient?
- ,
- ,
- ,
- ,
The zero-gradient cases are the two that “have already gone far in the favorable direction”: positive advantage with , negative advantage with . The other two (negative advantage but pushed up to 1.3, positive advantage but pushed down to 0.7) are moving in the bad direction; after the their gradient is kept so they get a chance to be pulled back.
5. About Experiment 5 (64 epochs on one batch), which statements are true?
- Without clipping the median KL is 4.872 nats; with clipping it is 0.147 nats
- With clipping 77% of tokens still have ratios outside , so clipping is not a strict trust region
- Clipping gives a larger median ΔJ per batch (0.042 against 0.171)
- With clipping 16 of the 100 batches still get worse
The median ΔJ with clipping is 0.042, below the 0.171 without it; what clipping buys is a controlled update size. The number of batches that got worse is 0 with clipping and 16 without.
6. In Experiment 7, at , what multiple of the true gradient is the expected gradient with only the group mean subtracted? And with RLOO?
- Mean baseline 1.0000, RLOO 0.8750
- Mean baseline 0.8750, RLOO 1.0000
- Both 0.8750
- Both 1.0000
The mean baseline contains the response’s own reward, so the expected gradient is of the true one; RLOO’s baseline uses only the other responses and is unbiased.
Exercises
- By hand. A one-step softmax policy with where only action 0 pays 1 and the others pay 0. Find , and explain why subtracting a baseline of 0.4 leaves the expected gradient unchanged.
- Read the table (Experiment 2). Late in training, what is the ratio of the no-baseline noise to the constant-baseline noise, and the ratio of the required numbers of sequences? What does this imply for tasks where the rewards are all positive?
- GAE by hand. A three-step sequence, critic estimates , true final reward 1, . Find for , 0.9 and 1.
- Clipping. With , which of these five tokens still carry gradient in the clipped objective: , , , , ?
- Group baselines. With group sizes and , what fraction of the true gradient does the mean-only baseline give in expectation? How should the learning rate be adjusted if you train with it?
- Design. You train a math model with GRPO, sampling responses per prompt with a right-or-wrong reward. List the metrics you would monitor and your first reaction to each one going wrong.
Reference answers
Continue the script above (it uses grad_stats, adv_none and so on):
# Exercise 1: a one-step softmax policy, π=(0.5, 0.3, 0.2); only action 0
# pays 1
pi, r = np.array([0.5, 0.3, 0.2]), np.array([1.0, 0.0, 0.0])
eye = np.eye(3)
grad = sum(pi[a] * r[a] * (eye[a] - pi) for a in range(3))
grad_b = sum(pi[a] * (r[a] - 0.4) * (eye[a] - pi) for a in range(3))
print("∇J =", grad.round(3).tolist())
print("expected gradient with baseline 0.4 =", grad_b.round(3).tolist())
# Exercise 2: late in training, noise and required sequences, no baseline
# versus constant baseline
n_none = grad_stats(theta_late, adv_none(theta_late))[1]
n_mean = grad_stats(theta_late, adv_mean(theta_late))[1]
print(f"noise ratio {n_none / n_mean:.2f}, ratio of required sequences "
f"{(n_none / n_mean) ** 2:.1f}")
# Exercise 3: GAE by hand. V̂ = (0.3, 0.5, 0.8), final reward 1, γ=1
vhat = np.array([0.3, 0.5, 0.8, 1.0])
delta = vhat[1:] - vhat[:-1]
for lam in (0.0, 0.9, 1.0):
adv = [sum(lam**l * delta[t + l] for l in range(3 - t)) for t in range(3)]
print(f"λ={lam}: δ = {delta.round(3).tolist()}, "
f"A = {np.round(adv, 3).tolist()}")
# Exercise 4: which tokens still carry gradient in the clipped objective
# (ε=0.2)
for rho, A in ((1.3, 1.0), (1.3, -1.0), (0.7, 1.0), (0.7, -1.0), (1.1, 1.0)):
dead = (A > 0 and rho > 1.2) or (A < 0 and rho < 0.8)
print(f"ρ={rho}, A={A:+.0f}: {'zero gradient' if dead else 'kept'}")
# Exercise 5: the mean-only baseline gives (G-1)/G of the true gradient
for G in (2, 4, 8, 12):
print(f"G={G}: (G-1)/G = {(G - 1) / G:.4f}")
∇J = [0.25, -0.15, -0.1]
expected gradient with baseline 0.4 = [0.25, -0.15, -0.1]
noise ratio 6.98, ratio of required sequences 48.8
λ=0.0: δ = [0.2, 0.3, 0.2], A = [0.2, 0.3, 0.2]
λ=0.9: δ = [0.2, 0.3, 0.2], A = [0.632, 0.48, 0.2]
λ=1.0: δ = [0.2, 0.3, 0.2], A = [0.7, 0.5, 0.2]
ρ=1.3, A=+1: zero gradient
ρ=1.3, A=-1: kept
ρ=0.7, A=+1: kept
ρ=0.7, A=-1: zero gradient
ρ=1.1, A=+1: kept
G=2: (G-1)/G = 0.5000
G=4: (G-1)/G = 0.7500
G=8: (G-1)/G = 0.8750
G=12: (G-1)/G = 0.9167
1. The gradient is : the logit of action 0 goes up, the other two go down, and the three components sum to 0 (adding a constant to all logits of a softmax does not change the policy). With a baseline of 0.4 the extra term is , so the expected gradient is still (the second line of the output).
2. The noise ratio is 6.98 and the ratio of required sequences is its square, about 48.8. When rewards are all positive every response gets pushed up and the signal hides in “pushed more or less”; the closer the reward is to its ceiling, the smaller the true gradient and the more purely noise that term of the no-baseline estimate becomes. So for tasks with always-positive rewards that end up near full marks (most verifiable-reward settings), a baseline is close to mandatory.
3. . At , : each step sees only its own error. At , , , . At , , which is exactly .
4. The gradient is zero for and ; the other three keep it: and move in the bad direction and clipping does not cut them, and lies inside .
5. At it is 0.7500 and at it is (the output gives 0.5000, 0.7500, 0.8750, 0.9167 for ; the rule is ). The direction is unchanged and the whole gradient just shrinks, so the learning rate can be multiplied by to compensate; but this holds only for a single prompt with the same group size, and with standard-deviation normalization it is no longer a constant factor: different prompts get different weights.
6. A reference list: the within-group mean reward per prompt and the share of prompts whose responses are all right or all wrong (a high share means no learning signal, so change the prompts or sample more); the curve of the average KL (new against reference) over steps, read together with the reward, since a rising reward with an unbounded KL signals over-optimization; the approximate KL (new against old) per iteration and the share of out-of-range tokens (if too large, use fewer epochs, lower the learning rate, or add KL early stopping); the policy entropy (near zero means entropy collapse; consider a higher upper clipping bound or an entropy term, see DAPO’s Clip-Higher); the distribution of response length and format (length bias, reward hacking); and accuracy on a held-out set, independent of the training reward. At the mean baseline shrinks the step by , which is not the main problem; if you use standard-deviation normalization, watch for very hard or very easy prompts being amplified.
Further reading
The links below were checked in November 2026.
- Williams, Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement Learning, Machine Learning, 1992: REINFORCE
- Sutton, McAllester, Singh, Mansour, Policy Gradient Methods for Reinforcement Learning with Function Approximation, NeurIPS 1999: the policy gradient theorem
- Sutton, Barto, Reinforcement Learning: An Introduction (2nd edition, 2018): chapter 13 covers policy gradients
- Schulman et al., High-Dimensional Continuous Control Using Generalized Advantage Estimation, 2015: GAE
- Schulman et al., Trust Region Policy Optimization, 2015
- Schulman et al., Proximal Policy Optimization Algorithms, 2017 (paper walkthrough)
- Engstrom et al., Implementation Matters in Deep Policy Gradients: A Case Study on PPO and TRPO, 2020
- Huang et al., The 37 Implementation Details of Proximal Policy Optimization, ICLR Blog Track, 2022
- Ziegler et al., Fine-Tuning Language Models from Human Preferences, 2019: RLHF with the KL penalty in the reward
- Ouyang et al., Training Language Models to Follow Instructions with Human Feedback, 2022 (paper walkthrough)
- Schulman, Approximating KL Divergence, 2020:
- Tang, Munos, On a Few Pitfalls in KL Divergence Gradient Estimation for RL, 2025
- Shao et al., DeepSeekMath, 2024: GRPO (paper walkthrough)
- Kool, van Hoof, Welling, Buy 4 REINFORCE Samples, Get a Baseline for Free!, DeepRLStructPred@ICLR, 2019: the source of RLOO (cited through the paper of Ahmadian et al.; no link given here)
- Ahmadian et al., Back to Basics: Revisiting REINFORCE Style Optimization for Learning from Human Feedback in LLMs, 2024: RLOO
- Liu et al., Understanding R1-Zero-Like Training: A Critical Perspective, 2025: length bias and difficulty bias in GRPO
- Yu et al., DAPO, 2025: Clip-Higher and entropy collapse (paper walkthrough)
- The walkthroughs of GSPO and GDPO: sequence-level importance ratios, and per-reward group normalization for multiple rewards
FAQ
- What is the policy gradient, and why does the formula contain the gradient of a log-probability?
- The policy gradient is the direct derivative of the expected reward J(θ)=E[R(τ)] with respect to the policy parameters. The key step is the log-derivative trick ∇p = p·∇log p, which turns a derivative of a distribution into an expectation over samples: ∇J = E[R(τ)·Σ_t ∇log π(a_t|s_t)]. Sample a response; if it scored high, push up the probability of each of its tokens, and if it scored low, push them down. The reward only appears as a weight and is never differentiated, so it can be a human rating, a reward model, or whether unit tests pass. Experiment 1 on this page enumerates all 4,096 sequences exactly, and the formula agrees with numerical gradients to a maximum absolute error of 1.4e-11.
- Why does subtracting a baseline add no bias but reduce variance?
- If the baseline depends only on the state and not on the current action, its expected contribution is zero: E_{a~π}[b(s)∇log π(a|s)] = b(s)·∇Σ_a π(a|s) = b(s)·∇1 = 0, so the expected gradient is unchanged. Variance drops sharply because, without a baseline, the largest term in the estimator is the average level of the reward, which contributes only noise. Experiment 2 computes this exactly on the toy: late in training (expected reward 0.966) the no-baseline estimator has noise equal to 113.10 times the gradient norm, a constant baseline brings it to 16.19, and the number of sequences needed to bring the noise down to half the gradient falls from 51,164 to 1,050. All three estimators have a bias of 0.0000.
- What does PPO's clipping actually do, and does it keep the new policy close to the old one?
- The clipped objective min(ρA, clip(ρ, 1−ε, 1+ε)A) cuts the gradient only when an update has already gone far in the favorable direction: tokens with positive advantage and ρ>1+ε, or negative advantage and ρ<1−ε, get zero gradient, while tokens moving in the bad direction keep theirs. It removes the incentive to keep going, but it is not a hard constraint: in Experiment 5, after 64 epochs on one batch 77% of tokens still have ratios outside [0.8, 1.2]. Without clipping the median KL to the old policy is 4.872 nats, with clipping 0.147 nats, and the number of batches that got worse drops from 16 out of 100 to 0. That is why implementations often add KL-based early stopping.
- How should λ in GAE be chosen, and why is it a bias-variance trade-off?
- GAE sums the one-step temporal-difference errors δ_t = r_t + γV(s_{t+1}) − V(s_t) with geometric weights (γλ)^l. With λ=0 only one step is used (it leans on the critic, low noise); with λ=1 it equals return minus a value baseline (unbiased, high noise). The bias comes from the critic's error, not from λ itself: in Experiment 4 every λ is unbiased when the critic is exact, while with critic noise σ=0.1 the bias grows as λ shrinks (means over 10 noise draws: 1.1319 at λ=0, 0.1298 at λ=0.9, 0 at λ=1), and the best λ moves toward 1 as the batch grows (0.5 at B=16, 0.9 at B=256). Typical values are 0.9 to 0.97; the PPO paper uses 0.95.
- Should the KL penalty in RLHF go into the reward or into the loss?
- They do not optimize the same thing. Treating the per-token log-ratio log(π/π_ref) as a penalty in the reward and accumulating it to the end of the response before taking a policy gradient gives the exact gradient of the sequence-level KL: in Experiment 6 it differs from finite differences by only 7.9e-11. Differentiating a per-token estimator used as a loss does not: the expected gradient of k1 is exactly zero, and k2 and k3 give only approximate directions (cosines with the exact gradient 0.9832 and 0.9543, norm ratios 0.8592 and 1.3638). Tang and Munos (2025) list these two points among common implementation pitfalls. The loss is simpler, but be clear about what it optimizes.