RLS RL, Read as Statistics

Chapter 08 · Part 3: Learning policies

Policy gradients are score-function estimators

The policy gradient is the likelihood-ratio estimator of the derivative of an expectation; baselines are control variates, reward-to-go drops zero-mean terms, and GAE is a bias-variance dial.

Chapter 7 learned values and then acted greedily on them. That route has a limit: a max⁡\max over estimated values is awkward when actions are continuous, and a greedy policy cannot be stochastic. The alternative is to parametrise the policy directly, πθ(a∣s)\pi_\theta(a \mid s), and ascend the objective J(θ)=Eπθ[G0]J(\theta) = \mathbb{E}_{\pi_\theta}[G_0] by gradient steps. The obstacle is that JJ is an expectation over trajectories whose distribution depends on θ\theta, and we need its derivative from samples. A statistician would say: this is the problem of differentiating an expectation with respect to a parameter of the distribution. There are two standard tools, the pathwise (reparametrisation) derivative and the score-function derivative. RL almost always uses the second, because the environment is a black box we cannot differentiate through.

To keep the algebra light, this chapter takes episodes of fixed length TT and no discounting, so R(τ)=∑t=0T−1Rt+1R(\tau) = \sum_{t=0}^{T-1} R_{t+1}. With discounting, replace Rt+1R_{t+1} by γtRt+1\gamma^t R_{t+1} in the return; nothing else in the derivations changes. Practitioners usually also drop the leading γt\gamma^t weight on each term of the gradient; that changes the quantity being estimated, and is a separate topic.

Where does the policy gradient come from?

Write pθ(τ)p_\theta(\tau) for the probability (density) of a trajectory τ=(S0,A0,R1,S1,… )\tau = (S_0, A_0, R_1, S_1, \dots) under πθ\pi_\theta. Then J(θ)=∫pθ(τ)R(τ) dτJ(\theta) = \int p_\theta(\tau) R(\tau)\,d\tau. Differentiate under the integral (this needs pθp_\theta smooth in θ\theta and, for the interchange, a dominating integrable bound; for a softmax policy on a finite problem it is automatic, and the support of τ\tau does not depend on θ\theta), and use ∇p=p ∇log⁡p\nabla p = p\,\nabla\log p:

∇θJ(θ)=∫∇θpθ(τ) R(τ) dτ=∫pθ(τ) ∇θlog⁡pθ(τ) R(τ) dτ=Eπθ[R(τ) ∇θlog⁡pθ(τ)].\nabla_\theta J(\theta) = \int \nabla_\theta p_\theta(\tau)\,R(\tau)\,d\tau = \int p_\theta(\tau)\,\nabla_\theta\log p_\theta(\tau)\,R(\tau)\,d\tau = \mathbb{E}_{\pi_\theta}\big[R(\tau)\,\nabla_\theta\log p_\theta(\tau)\big].

This is the likelihood-ratio method of Glynn (1990) and, in RL, the REINFORCE estimator of Williams (1992). ∇θlog⁡pθ(τ)\nabla_\theta\log p_\theta(\tau) is the score of the trajectory, familiar from maximum likelihood: the gradient of the log-likelihood. It has mean zero, and the estimator multiplies it by the observed return.

The dynamics drop out

The trajectory probability factorises:

pθ(τ)=p(S0)∏t=0T−1πθ(At∣St) p(St+1,Rt+1∣St,At).p_\theta(\tau) = p(S_0)\prod_{t=0}^{T-1}\pi_\theta(A_t \mid S_t)\,p(S_{t+1}, R_{t+1}\mid S_t, A_t).

Take logs and differentiate. Only the policy factors depend on θ\theta:

∇θlog⁡pθ(τ)=∑t=0T−1∇θlog⁡πθ(At∣St).\nabla_\theta\log p_\theta(\tau) = \sum_{t=0}^{T-1}\nabla_\theta\log\pi_\theta(A_t\mid S_t).

The initial-state distribution and the transition and reward model p(s′,r∣s,a)p(s', r\mid s, a) vanish. This is why the method is "model-free": we never need pp, only the ability to sample from it and to evaluate the gradient of our own policy's log-probability. Write gt=∇θlog⁡πθ(At∣St)g_t = \nabla_\theta\log\pi_\theta(A_t\mid S_t) and g=∑tgtg = \sum_t g_t. The single-trajectory estimator is

∇^J=R(τ)∑t=0T−1gt.\hat\nabla J = R(\tau)\sum_{t=0}^{T-1} g_t .

It is unbiased for ∇θJ\nabla_\theta J by the derivation above, and an average of nn independent trajectories has variance 1/n1/n times that of one. The only issue is that variance, which is large.

The score has mean zero

For any state ss,

EA∼πθ(⋅∣s)[∇θlog⁡πθ(A∣s)]=∑a∇θπθ(a∣s)=∇θ∑aπθ(a∣s)=∇θ1=0.\mathbb{E}_{A\sim\pi_\theta(\cdot\mid s)}\big[\nabla_\theta\log\pi_\theta(A\mid s)\big] = \sum_a \nabla_\theta\pi_\theta(a\mid s) = \nabla_\theta\sum_a\pi_\theta(a\mid s) = \nabla_\theta 1 = 0 .

(An integral for continuous actions.) This one fact generates every variance-reduction trick in the chapter. The first consequence is the policy gradient theorem in the form of Sutton, McAllester, Singh and Mansour (2000): in a finite-horizon problem

∇θJ(θ)=∑t=0T−1Eπθ[gt  qtπ(St,At)],\nabla_\theta J(\theta) = \sum_{t=0}^{T-1}\mathbb{E}_{\pi_\theta}\big[g_t\; q_t^{\pi}(S_t,A_t)\big],

with qtπq^\pi_t the action value at time tt. Their paper states the infinite-horizon version with the discounted state-visitation weighting and shows that a compatible function approximator for qq preserves unbiasedness.

Why can we replace the full return by reward-to-go?

Expand the estimator into terms gtRk+1g_t R_{k+1} for all pairs tt, kk. Consider k<tk < t: a reward received before action AtA_t. Condition on everything up to and including StS_t, which determines Rk+1R_{k+1} (it is already realised). Then

E[gt Rk+1]=E[Rk+1  E[gt∣S0,A0,…,St]]=E[Rk+1⋅0]=0.\mathbb{E}\big[g_t\,R_{k+1}\big] = \mathbb{E}\Big[R_{k+1}\;\mathbb{E}\big[g_t \mid S_0,A_0,\dots,S_t\big]\Big] = \mathbb{E}\big[R_{k+1}\cdot 0\big] = 0 .

Past rewards cannot depend on a future action, and the score of the future action is mean zero given the past. Dropping those terms leaves the reward-to-go estimator

∇^JRTG=∑t=0T−1gt Gt,Gt=∑k=tT−1Rk+1.\hat\nabla J_{\mathrm{RTG}} = \sum_{t=0}^{T-1} g_t\,G_t, \qquad G_t = \sum_{k=t}^{T-1} R_{k+1}.

Same expectation, fewer terms. This is "causality" in the policy-gradient literature. In statistical terms we deleted summands that have mean zero but non-zero variance. That typically reduces the variance, because we remove noise; it need not do so in every problem, since the deleted terms can be correlated with the retained ones. (This is why I call it a Rao–Blackwell-flavoured step, not a Rao–Blackwellisation: we are not conditioning on a sufficient statistic.)

Why is a baseline a control variate?

Take any bb that does not depend on the action AtA_t at the time it multiplies gtg_t. Then E[gt b]=E[b E[gt∣past]]=0\mathbb{E}[g_t\,b] = \mathbb{E}[b\,\mathbb{E}[g_t \mid \text{past}]] = 0 and

E[g (R(τ)−b)]=∇θJ(b constant),\mathbb{E}\big[g\,(R(\tau)-b)\big] = \nabla_\theta J \qquad (b \text{ constant}),

so subtracting b gb\,g from the estimator does not change its mean. In control-variate language: Y=R gY = R\,g is the estimator, C=gC = g is a variable with known mean 00, and we use Y−b CY - b\,C. The textbook coefficient is β∗=Cov⁡(Y,C)/Var⁡(C)\beta^* = \operatorname{Cov}(Y,C)/\operatorname{Var}(C). Work it out for component ii of the gradient, using E[gi]=0\mathbb{E}[g_i] = 0:

Cov⁡(Rgi,gi)=E[R gi2]−E[R gi] E[gi]=E[R gi2],Var⁡(gi)=E[gi2].\operatorname{Cov}(R g_i, g_i) = \mathbb{E}[R\,g_i^2] - \mathbb{E}[R\,g_i]\,\mathbb{E}[g_i] = \mathbb{E}[R\,g_i^2], \qquad \operatorname{Var}(g_i) = \mathbb{E}[g_i^2].

Equivalently, minimise the variance directly. The ii-th component of g (R−b)g\,(R-b) has mean ∇iJ\nabla_iJ (free of bb) and second moment E[gi2(R−b)2]\mathbb{E}[g_i^2(R-b)^2], so we minimise f(b)=E[gi2(R−b)2]f(b) = \mathbb{E}[g_i^2(R-b)^2]:

f′(b)=−2 E[gi2(R−b)]=0⟹bi∗=E[gi2 R]E[gi2],f'(b) = -2\,\mathbb{E}[g_i^2 (R-b)] = 0 \quad\Longrightarrow\quad b_i^* = \frac{\mathbb{E}[g_i^2\,R]}{\mathbb{E}[g_i^2]},

and f′′=2 E[gi2]>0f'' = 2\,\mathbb{E}[g_i^2] > 0, so this is the minimum. The optimal constant baseline is the mean return weighted by the squared score: trajectories whose score is large in component ii count more, because they are the ones that make the estimator swing. It coincides with E[R]\mathbb{E}[R] only if gi2g_i^2 and RR are uncorrelated. Greensmith, Bartlett and Baxter (2004) treat baselines and critics as additive control variates, derive the optimal baseline, and show that the average reward is in general suboptimal, consistent with this calculation.

A state-dependent baseline and the advantage

The baseline is allowed to depend on the state at time tt (and on anything else that precedes AtA_t), because the argument above only used that it does not depend on AtA_t. Use bt(St)b_t(S_t) in the tt-th term:

∇^J=∑t=0T−1gt (Gt−bt(St)).\hat\nabla J = \sum_{t=0}^{T-1} g_t\,\big(G_t - b_t(S_t)\big).

The natural choice is bt(s)=vtπ(s)b_t(s) = v_t^\pi(s), the state value. Since E[Gt∣St=s,At=a]=qtπ(s,a)\mathbb{E}[G_t\mid S_t=s,A_t=a] = q_t^\pi(s,a), the weight Gt−vtπ(St)G_t - v_t^\pi(S_t) is an unbiased noisy version of the advantage Atπ(s,a)=qtπ(s,a)−vtπ(s)A^\pi_t(s,a) = q_t^\pi(s,a) - v_t^\pi(s). The advantage has a clear interpretation: how much better than average is this action in this state. Making the weight a function of the state and action rather than of the whole future trajectory gives actor–critic methods: replace GtG_t by an estimate q^\hat q or A^\hat A from a learned critic. That lowers variance more but can introduce bias if the critic is wrong, the same trade-off as chapters 4 and 5.

The state value is not the variance-minimising baseline either (Greensmith et al. show this); it is a good, cheap, learnable one, and it is what the learned baseline in the experiment uses.

Generalised advantage estimation as a dial

Let VV be a learned value function and δt=Rt+1+γV(St+1)−V(St)\delta_t = R_{t+1} + \gamma V(S_{t+1}) - V(S_t) the TD error from chapter 5. Using a kk-step return to form an advantage estimate gives

A^t(k)=∑l=0k−1γl δt+l=Gt(k)−V(St),\hat A_t^{(k)} = \sum_{l=0}^{k-1}\gamma^l\,\delta_{t+l} = G_t^{(k)} - V(S_t),

where Gt(k)G_t^{(k)} is the kk-step return. At k=1k = 1 this is δt\delta_t: low variance, biased unless V=vπV = v_\pi. At k=∞k = \infty it is Gt−V(St)G_t - V(S_t), a Monte Carlo advantage: unbiased for any VV (the baseline only shifts the variance), high variance. Generalised advantage estimation (GAE; Schulman, Moritz, Levine, Jordan and Abbeel, 2016) averages these with geometric weights (1−λ)λk−1(1-\lambda)\lambda^{k-1}:

A^tGAE(γ,λ)=∑l=0∞(γλ)l δt+l=Gtλ−V(St),\hat A_t^{\mathrm{GAE}(\gamma,\lambda)} = \sum_{l=0}^{\infty}(\gamma\lambda)^l\,\delta_{t+l} = G_t^{\lambda} - V(S_t),

where GtλG_t^\lambda is exactly the λ\lambda-return from chapter 5 for the fixed function VV. The weight λ∈[0,1]\lambda\in[0,1] moves the estimator from the one-step TD advantage (λ=0\lambda=0) to the Monte Carlo advantage (λ=1\lambda=1). The bias at intermediate λ\lambda comes from the error of VV, damped by powers of γλ\gamma\lambda the further it enters; the variance comes from summing more random δ\delta's. Nothing new is needed to understand this: it is the bias-variance dial of chapter 5, applied to an advantage instead of a value. (Schulman et al. also use γ\gamma itself as a variance-reduction parameter; the discussion above fixes γ\gamma as part of the problem.)

Where this is used

The policy-optimisation methods you will meet in practice are built from these pieces. PPO (Schulman et al., 2017) takes an advantage estimate, typically GAE, and uses it in a clipped surrogate objective that lets one batch be reused for several gradient steps. GRPO, introduced for language-model post-training in DeepSeekMath (Shao et al., 2024), samples a group of outputs per prompt and uses the group-standardised reward as the advantage, dropping the learned critic: the group mean is the baseline. A statistical remark on that choice, which chapter 10 returns to: if the baseline for sample ii is the mean of a group of mm rewards including sample ii, it is no longer independent of that sample's action, and the expectation of the estimator is scaled by 1−1/m1-1/m. A leave-one-out mean is exactly unbiased. Dividing by the group's standard deviation rescales the gradient prompt by prompt and is a different estimator again.

A worked example by hand: a two-armed bandit

One state, one step (T=1T=1), two arms, softmax policy with parameters θ=(θ1,θ2)\theta = (\theta_1,\theta_2):

πθ(a)=eθaeθ1+eθ2.\pi_\theta(a) = \frac{e^{\theta_a}}{e^{\theta_1}+e^{\theta_2}}.

Score. log⁡π(a)=θa−log⁡∑ceθc\log\pi(a) = \theta_a - \log\sum_c e^{\theta_c}, so ∂log⁡π(a)/∂θj=1{j=a}−π(j)\partial\log\pi(a)/\partial\theta_j = \mathbf 1\{j=a\} - \pi(j). The score is g=ea−πg = e_a - \pi, with eae_a the indicator vector of the chosen arm. Check mean zero: ∑aπ(a)(ea−π)=π−π=0\sum_a \pi(a)(e_a-\pi) = \pi - \pi = 0.

Let θ=(0,0)\theta = (0,0), so π=(12,12)\pi = (\tfrac12,\tfrac12), and let the rewards be deterministic, r=(3,1)r = (3, 1). Then J=12⋅3+12⋅1=2J = \tfrac12\cdot3+\tfrac12\cdot1 = 2.

True gradient. ∇J=∑aπ(a) ra (ea−π)\nabla J = \sum_a \pi(a)\,r_a\,(e_a-\pi). For component 1:

∂θ1J=12⋅3⋅12+12⋅1⋅(−12)=34−14=12.\partial_{\theta_1}J = \tfrac12\cdot 3\cdot\tfrac12 + \tfrac12\cdot 1\cdot\big(-\tfrac12\big) = \tfrac34-\tfrac14 = \tfrac12 .

By symmetry (the two components of the softmax score sum to zero), ∂θ2J=−12\partial_{\theta_2}J = -\tfrac12.

The estimator. Draw AA; the estimate of component 1 is rA g1r_A\,g_1.

  • A=1A=1 (probability 12\tfrac12): 3×12=1.53\times\tfrac12 = 1.5.
  • A=2A=2 (probability 12\tfrac12): 1×(−12)=−0.51\times(-\tfrac12) = -0.5.

Mean: 12(1.5)+12(−0.5)=0.5\tfrac12(1.5)+\tfrac12(-0.5) = 0.5. Unbiased. Variance: 12(1.5−0.5)2+12(−0.5−0.5)2=1\tfrac12(1.5-0.5)^2+\tfrac12(-0.5-0.5)^2 = 1.

With a baseline bb. The estimate is (rA−b) g1(r_A-b)\,g_1. For A=1A=1, g1=12g_1=\tfrac12 and the value is 12(3−b)\tfrac12(3-b). For A=2A=2, g1=−12g_1 = -\tfrac12 and the value is −12(1−b)-\tfrac12(1-b). Subtract the mean 0.50.5 from each: 12(3−b)−12=1−b2\tfrac12(3-b)-\tfrac12 = 1-\tfrac b2 and −12(1−b)−12=−1+b2-\tfrac12(1-b)-\tfrac12 = -1+\tfrac b2. Both have magnitude ∣1−b/2∣\lvert 1-b/2\rvert, so

Var⁡[(rA−b) g1]=(1−b2)2.\operatorname{Var}\big[(r_A-b)\,g_1\big] = \Big(1-\frac b2\Big)^2 .

At b=0b=0 the variance is 11; at b=1b=1 it is 14\tfrac14; at b=2b=2 it is 00. With b=2b=2 the estimator returns 0.50.5 on every draw: every sample reports the exact gradient. Check against the formula: here g12=14g_1^2 = \tfrac14 for both arms, a constant, so b1∗=E[g12R]/E[g12]=E[R]=2b^*_1 = \mathbb{E}[g_1^2R]/\mathbb{E}[g_1^2] = \mathbb{E}[R] = 2. This is the special case where the optimal baseline equals the mean, because g12g_1^2 does not vary. With π=(0.8,0.2)\pi = (0.8, 0.2) it does vary, and the two baselines separate (exercise 1).

Experiment

ch08_policy_gradient.py builds a small episodic problem: 3 states, 2 actions, horizon T=4T=4, stochastic transitions, mean rewards between 3.53.5 and 77 plus Gaussian noise of standard deviation 11, a tabular softmax policy (6 parameters). The mean rewards are deliberately shifted upward so that raw returns are large (about 19) and a baseline has something to remove. The true gradient is computed exactly by backward induction on qt(s,a)q_t(s,a) and forward propagation of state probabilities, and the script checks it against finite differences first.

For a fixed policy we draw 400,000 independent single-trajectory estimates under each of five estimators:

  1. no baseline: R(τ) gR(\tau)\,g;
  2. constant baseline equal to JJ (fitted from a pilot sample of 200,000 trajectories);
  3. optimal constant baseline bi∗=E[gi2R]/E[gi2]b^*_i = \mathbb{E}[g_i^2R]/\mathbb{E}[g_i^2], estimated from the same pilot;
  4. reward-to-go;
  5. reward-to-go minus a learned time-and-state value V(t,St)V(t,S_t), the mean of GtG_t in each cell of the pilot sample.

Baselines are fitted on a separate sample from the estimates, so they are fixed constants as far as the estimation sample is concerned, and unbiasedness holds. "max z-score" is the largest, over the six components, of ∣mean−truth∣\lvert\text{mean}-\text{truth}\rvert divided by its standard error.

Output
check: max |exact grad - finite difference| = 2.97e-10

True J = 19.3015; ||true gradient|| = 1.3546; 6 parameters; 400000 single-trajectory estimates per row.
Baselines fitted on a separate pilot of 200000 trajectories; mean pilot return 19.306.

estimator                      | ||mean - truth|| | max z-score | total variance | rel. to none
no baseline                    |           0.0512 |        1.84 |         737.03 |      1.0000
constant mean baseline         |           0.0040 |        0.90 |          16.98 |      0.0230
optimal constant baseline      |           0.0043 |        1.08 |          14.40 |      0.0195
reward-to-go                   |           0.0336 |        1.46 |         339.50 |      0.4606
reward-to-go, learned V(t,s)   |           0.0040 |        1.31 |           9.75 |      0.0132

component 0..5 of the gradient: truth and empirical means
truth                          |  -0.540   0.540   0.331  -0.331  -0.718   0.718
no baseline                    |  -0.576   0.576   0.325  -0.325  -0.712   0.712
constant mean baseline         |  -0.539   0.539   0.333  -0.333  -0.719   0.719
optimal constant baseline      |  -0.541   0.541   0.334  -0.334  -0.720   0.720
reward-to-go                   |  -0.564   0.564   0.327  -0.327  -0.719   0.719
reward-to-go, learned V(t,s)   |  -0.541   0.541   0.334  -0.334  -0.720   0.720

Learning: 150 SGD steps, batch 32, step 0.05, 40 seeds. J(uniform) = 19.161, J(optimal) = 22.720
variant                        | final J mean | final J sd
no baseline                    |       22.127 |      0.206
reward-to-go                   |       22.124 |      0.182
reward-to-go + learned V       |       22.110 |      0.082

What the numbers show.

  • All five are unbiased. The largest z-score is 1.841.84; no estimator is distinguishable from the exact gradient at that sample size. The estimators with large variance have visibly larger discrepancies in the mean (norm 0.0510.051 for no baseline, 0.0340.034 for reward-to-go against 0.0040.004 for the baselined ones), which is what a Monte Carlo error proportional to the standard deviation looks like, not bias. The gradient components come in ±\pm pairs because softmax scores within a state sum to zero.
  • A constant baseline removes 98% of the variance. The raw return has mean 19.319.3 and a much smaller standard deviation, so multiplying the score by RR mostly multiplies it by a constant. Subtracting the mean cuts total variance from 737737 to 1717, a factor of 4343. The optimal constant baseline improves on it modestly (to 14.414.4): in this problem gi2g_i^2 and RR are only weakly related, so the score-weighted mean is close to the plain mean, as the theory predicts.
  • Reward-to-go helps without any baseline, halving the variance (0.460.46 of the no-baseline value), by deleting the mean-zero terms that pair each action with earlier rewards.
  • Combining causality and a state baseline is best: 9.759.75, or 1.3%1.3\% of the no-baseline variance, a factor of about 7575. The state baseline removes more than a constant baseline because later returns depend strongly on which state the chain is in.
  • In learning, the means are similar and the spread is not. After 150 steps with 32 trajectories per step, all three variants reach about 22.122.1 of the optimal 22.7222.72 from 19.1619.16 for the uniform policy. The learned-baseline variant has less than half the seed-to-seed standard deviation (0.0820.082 against 0.2060.206). The variance of the gradient estimate shows up as run-to-run variability of the learned policy. Here the problem is small and the step is moderate, so baselines do not change where learning ends up; with a larger step size, a smaller batch, or a longer horizon, that variance would also slow or derail learning.

Exercises

  1. Pen and paper. In the bandit example, set π=(0.8,0.2)\pi = (0.8,0.2) and r=(3,1)r = (3,1). Compute E[R]\mathbb{E}[R] and the optimal baseline b1∗b_1^*. Then compute the variance of the estimator of component 1 at each of the two baselines.
  2. Pen and paper. Show that the weights A^t(k)=Gt(k)−V(St)\hat A^{(k)}_t = G_t^{(k)} - V(S_t) and ∑l<kγlδt+l\sum_{l<k}\gamma^l\delta_{t+l} are the same thing. (Telescope the sum.)
  3. Pen and paper. Suppose bb is the batch mean of mm returns including the sample it multiplies. Show that E[g (R−b)]=(1−1m)∇J\mathbb{E}[g\,(R-b)] = (1-\tfrac1m)\nabla J.
  4. Change the code and predict. Lower REWARD_SD to 0 and rerun the variance experiment. Which row's variance falls most? Then raise HH to 8 and predict how the no-baseline and reward-to-go variances scale.
  5. Change the code and predict. In learn, set batch=4 and lr=0.05. Predict whether the ordering of final-JJ standard deviations persists, then run.

Sources