Course contents 07 / 27

07 / 27 · Reinforcement Learning

Policy gradients and actor-critic

Optimizing a stochastic policy directly: the policy gradient theorem derived with the log-derivative trick, REINFORCE and why baselines keep it unbiased, advantages, actor-critic and GAE, trust regions, TRPO and PPO's clipped objective, and the entropy bonus.

On this page 11

A scheduler has three slots. Each slot runs either a routine job or a priority job. A batch earns one point if it contains exactly two priority jobs; every other allocation earns zero. Suppose the scheduler uses one shared probability pp for all three decisions, independently of the slot and previous choices. Always choosing either job type fails. How should we adjust pp from completed batches?

A policy gradient changes action probabilities directly to increase expected reward. The allocation task is deliberately small enough to enumerate every possible trajectory. It lets us check an estimator before trusting the same calculation inside a neural policy.

Baseline: acting greedily on learned values#

A value method estimates Q(s,a)Q(s,a) and selects an action with a large value. A policy method represents πθ(a∣s)\pi_\theta(a\mid s) itself. This is useful when actions are continuous, when differentiable sampling distributions are convenient, or when the chosen policy class is intentionally stochastic. It does not imply that value methods cannot handle continuous actions or that every MDP needs randomness.

For the scheduler, define a state by the slot number and the priority jobs already selected. A state-aware deterministic policy can choose priority, priority, routine and receive reward one. Our restricted policy ignores that state and uses the same pp each time. We are comparing policies within that restricted class.

There are three successful schedules. Each has probability p2(1−p)p^2(1-p), so

J(p)=3p2(1−p),dJdp=6p−9p2.\begin{aligned} J(p)&=3p^2(1-p),\\ \frac{dJ}{dp}&=6p-9p^2. \end{aligned}

On [0,1][0,1], the maximum is at p=2/3p=2/3, with expected reward 4/94/9. The endpoints give zero. This is an optimum of the shared-probability class, not the maximum reward attainable with full state information. Distinguishing the environment from the representation prevents us from attributing a policy limitation to the task.

Figure

Three slots, one probability

Three slots, one probabilityExpected reward J(p) = 3p²(1 − p). At p = 0.4 it is 0.288; the maximum 4/9 occurs at p = 2/3. At p = 0 and p = 1 reward is zero.J(p)0.00.20.40.00.20.40.60.81.0p0.288p = 2/3, J = 4/9
Each of three slots independently selects a priority job with the same probability p. Three schedules succeed: 110, 101 and 011. The curve uses their exact probabilities. The shared-probability restriction matters: a policy that observes the slot and previous choices can obtain reward 1.

The policy gradient theorem#

Let a finite episode be τ=(s0,a0,r1,…,sT)\tau=(s_0,a_0,r_1,\ldots,s_T), with policy πθ\pi_\theta. For discount γ∈[0,1]\gamma\in[0,1], define

R(τ)=∑t=0T−1γtrt+1,J(θ)=Epθ(τ)R(τ).\begin{aligned} R(\tau)&=\sum_{t=0}^{T-1}\gamma^t r_{t+1},\\ J(\theta)&=\mathbb E_{p_\theta(\tau)}R(\tau). \end{aligned}

Assume the initial distribution, environment transitions and reward rule do not depend on θ\theta. Use a differentiable policy with fixed support; for continuous variables we also need conditions allowing differentiation under the integral. A finite state/action model with a finite horizon avoids that analytic complication.

The product of policy and environment factors defines a trajectory probability. Taking its logarithm and differentiating removes the environment factors:

∇θ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 identity ∇p=p∇log⁡p\nabla p=p\nabla\log p then gives

∇J=∑τpθ(τ)R(τ)∇log⁡pθ(τ)=E[R(τ)∑t∇log⁡πθ(at∣st)].\nabla J=\sum_\tau p_\theta(\tau)R(\tau)\nabla\log p_\theta(\tau) =\mathbb E\left[R(\tau)\sum_t\nabla\log\pi_\theta(a_t\mid s_t)\right].

This differentiates the sampling distribution; treating the sampled rewards as constants without their score factors would lose this effect. We need action log-probabilities and observed rewards, without an explicit transition model.

Earlier rewards can be removed from each action’s multiplier. Conditional on the history before that action, they are fixed, while

Ea∼πθ(⋅∣s)∇log⁡πθ(a∣s)=∑a∇πθ(a∣s)=0.\mathbb E_{a\sim\pi_\theta(\cdot\mid s)}\nabla\log\pi_\theta(a\mid s) =\sum_a\nabla\pi_\theta(a\mid s)=0.

Writing Gt=∑k=tT−1γk−trk+1G_t=\sum_{k=t}^{T-1}\gamma^{k-t}r_{k+1} for reward-to-go yields

∇J=E[∑tγtGt∇log⁡πθ(at∣st)].\nabla J=\mathbb E\left[\sum_t\gamma^tG_t\nabla\log\pi_\theta(a_t\mid s_t)\right].

Replacing GtG_t by its conditional expectation Qπ(st,at)Q^\pi(s_t,a_t) preserves the mean. Grouping terms by state gives the policy-gradient theorem with discounted visitation weights dπ(s)=∑tγtPr⁡(st=s)d^\pi(s)=\sum_t\gamma^t\Pr(s_t=s), as in Sutton et al., Theorem 1. In a finite-horizon task, include time in the state. Uniformly averaging all visited steps while omitting γt\gamma^t generally changes this start-state discounted objective; it is not an algebraic simplification of the displayed formula.

REINFORCE#

REINFORCE estimates this expectation from complete episodes (Williams, 1992). Collect trajectories under the current policy, compute their rewards-to-go, average the score-weighted returns, and take an ascent step. Freeze the sampled targets when differentiating the policy loss. Collect new data after updating; repeatedly treating old trajectories as fresh on-policy samples changes the estimator.

For the allocation task, set p=σ(h)p=\sigma(h) with a scalar logit hh. If a trajectory contains kk priority choices, its log-probability derivative is

S(τ)=k−3p.S(\tau)=k-3p.

With γ=1\gamma=1 and reward only at termination, its gradient estimate is RSR S. At p=2/5p=2/5, each successful trajectory has probability 12/12512/125, reward one and score 4/54/5. The other five trajectories contribute zero. Hence

E[RS]=31212545=144625=0.2304.\mathbb E[RS]=3\frac{12}{125}\frac45=\frac{144}{625}=0.2304.

Direct differentiation agrees: (6p−9p2)p(1−p)=0.2304(6p-9p^2)p(1-p)=0.2304. The positive sign increases the priority probability from 0.4 toward the optimum. Enumerating eight paths gives an exact check; it is not an estimate from a large training run.

How a baseline changes variance#

A baseline may depend on the state or earlier history, provided it does not depend on the current sampled action conditional on that information. With the baseline fixed for the score calculation, its expected contribution is zero:

E[b(st)∇log⁡πθ(at∣st)∣st]=0.\mathbb E[b(s_t)\nabla\log\pi_\theta(a_t\mid s_t)\mid s_t]=0.

Thus Gt−b(st)G_t-b(s_t) can replace GtG_t. This is a control variate. An arbitrary baseline need not reduce variance. Fitting one on the same outcomes can also introduce dependence; action independence must hold for the actual estimator, not just its function signature.

Our trajectory-level example uses a constant bb and estimator (R−b)S(R-b)S. Its mean remains 0.2304. Exact enumeration gives:

BaselineValueGradient variance
None00.13123584
Expected reward0.2880.08478720
Best constant for this estimator0.2560.08404992

Why is the best constant different from the value? Differentiating the second moment E[(R−b)2S2]\mathbb E[(R-b)^2S^2] with respect to bb gives

b∗=E[RS2]E[S2],b^*=\frac{\mathbb E[RS^2]}{\mathbb E[S^2]},

when the denominator is nonzero. Large score magnitudes receive more weight. This formula concerns one scalar trajectory estimator, not every actor-critic baseline.

Add seven points to the terminal reward of every schedule. The objective changes by a constant and its gradient stays the same, but the variance without a baseline becomes 37.99171584. Increasing the baseline by seven exactly restores the original estimator, path by path. Conversely, setting b=Rb=R makes every estimate zero and is biased here: this baseline uses the current actions’ outcome. At p=2/3p=2/3, the unbaselined estimator already has zero variance in this special task; variance reduction is not a universal property of subtracting a value.

Advantages, actors and critics#

Define Vπ(s)=E[Gt∣st=s]V^\pi(s)=\mathbb E[G_t\mid s_t=s] and Aπ(s,a)=Qπ(s,a)−Vπ(s)A^\pi(s,a)=Q^\pi(s,a)-V^\pi(s). Subtracting the value leaves the policy gradient unchanged and measures how an action compares with the policy’s average at that state.

A critic estimates the value, while an actor changes the policy. For a true value function and a terminal value of zero,

E[rt+1+γVπ(st+1)−Vπ(st)∣st,at]=Aπ(st,at).\mathbb E[r_{t+1}+\gamma V^\pi(s_{t+1})-V^\pi(s_t)\mid s_t,a_t]=A^\pi(s_t,a_t).

A learned critic VwV_w supplies the temporal-difference residual δt=rt+1+γVw(st+1)−Vw(st)\delta_t=r_{t+1}+\gamma V_w(s_{t+1})-V_w(s_t). Bootstrapping uses a shorter reward window, often reducing variance, while critic error can bias the actor’s direction. This is the actor-critic trade-off; it is not a guarantee that every critic improves every update. The value estimate and advantage are held fixed during the actor-gradient calculation. Shared network parameters require separating that actor term from the critic’s own regression loss.

Generalized advantage estimation#

Generalized advantage estimation combines TD residuals:

A^t=∑l=0T−t−1(γλ)lδt+l,A^t=δt+γλA^t+1.\begin{aligned} \hat A_t&=\sum_{l=0}^{T-t-1}(\gamma\lambda)^l\delta_{t+l},\\ \hat A_t&=\delta_t+\gamma\lambda\hat A_{t+1}. \end{aligned}

Use the backward recursion with A^T=0\hat A_T=0. At λ=0\lambda=0, only one TD residual remains. At λ=1\lambda=1, a genuinely terminated episode with Vw(sT)=0V_w(s_T)=0 telescopes to Gt−Vw(st)G_t-V_w(s_t), so the critic acts only as an action-independent baseline. For intermediate values, the balance depends on critic error and reward variability; no fixed λ\lambda is uniformly best.

A separate original four-step trace has rewards (1,−0.5,0,2)(1,-0.5,0,2) and value estimates (0.8,0.6,0.9,1.4,0)(0.8,0.6,0.9,1.4,0). With γ=0.8\gamma=0.8, its TD residuals are (0.68,−0.38,0.22,0.6)(0.68,-0.38,0.22,0.6). For λ=0.6\lambda=0.6, multiply each next advantage by 0.48:

StepTD residualGAE advantage
00.680.6146432
1−0.38−0.13616
20.220.508
30.600.600

For example, A^1=−0.38+0.48⋅0.508=−0.13616\hat A_1=-0.38+0.48\cdot0.508=-0.13616. The negative sign discourages the sampled action at step one in the actor term. The critic can regress toward fixed targets A^t+Vw(st)\hat A_t+V_w(s_t); these are bootstrapped estimates, not observed full returns for every λ\lambda.

A collection cutoff is different from termination. If the process continues after step four, retaining a bootstrap value 0.7 adds 0.84⋅0.7=0.286720.8^4\cdot0.7=0.28672 to the start’s λ=1\lambda=1 target. Setting it to zero discards that continuation estimate. The unbiased full-return statement does not apply to an arbitrary finite cutoff with an imperfect bootstrap.

Trust regions: how far one step may go#

After a policy update, the next trajectories come from a different distribution. A good local gradient can still produce a harmful large step. Define the action-probability ratio rt(θ)=πθ(at∣st)/πold(at∣st)r_t(\theta)=\pi_\theta(a_t\mid s_t)/\pi_{\mathrm{old}}(a_t\mid s_t) on old-policy data. A surrogate averages rtA^tr_t\hat A_t using the old visitation weights. With exact advantages and matching discounted weights, its derivative at the old parameters agrees with the policy gradient, up to a fixed normalization.

Away from those parameters, the ratio corrects action probabilities but does not replace old state visitation by new state visitation. TRPO bounds the resulting error using a maximum policy divergence over states, then implements a practical average-KL constraint. The average is an approximation to that worst-state condition; it does not give the same pointwise guarantee.

Locally, KL is approximately 12Δθ⊤FΔθ\tfrac12\Delta\theta^\top F\Delta\theta, where FF is the policy Fisher matrix. Maximizing a linearized improvement under this quadratic constraint gives a direction proportional to F−1gF^{-1}g, subject to invertibility or suitable regularization. Practical TRPO uses Fisher-vector products, conjugate gradients and a line search. These approximations should not be described as guaranteed improvement on every sampled batch.

PPO: a clipped objective#

PPO replaces the hard constraint with a samplewise clipped surrogate (Schulman et al., 2017, Section 3):

LCLIP=Et[min⁡(rtA^t,clip⁡(rt,1−ε,1+ε)A^t)].L^{\mathrm{CLIP}}=\mathbb E_t\left[\min\left(r_t\hat A_t,\operatorname{clip}(r_t,1-\varepsilon,1+\varepsilon)\hat A_t\right)\right].

For our illustrative choice ε=0.15\varepsilon=0.15, the interval is [0.85,1.15][0.85,1.15]:

RatioAdvantage +3Advantage −2
0.72.10−1.70
1.03.00−2.00
1.33.45−2.60

A positive-advantage term stops rewarding increases beyond 1.15. A negative-advantage term stops rewarding decreases below 0.85. The opposite direction stays active. The minimum makes this term a lower bound on the unclipped surrogate term. It is not a lower bound on actual policy performance.

Clipping also does not constrain the policy ratio to remain inside the interval. Let an old binary policy select an action with probability 0.4 and give that observed action advantage +3. New probabilities 0.5, 0.9, 0.99 and 0.999 all give the same clipped term, 3.45. Yet the old-to-new Bernoulli KL grows from about 0.0201 to 3.4720 nats and diverges as the new probability approaches one. The clipped term is flat, not a barrier. Other samples, shared parameters and optimizer steps can still move the policy.

PPO alternates collecting data and several optimization passes over the recorded batch, keeping old log-probabilities and targets fixed. A critic loss and an entropy term may accompany the actor term. Monitor actual KL, reward and value quality; a clipping parameter alone supplies no global update-size or performance guarantee.

The entropy bonus#

For a binary policy, entropy is H(p)=−plog⁡p−(1−p)log⁡(1−p)H(p)=-p\log p-(1-p)\log(1-p). With p=σ(h)p=\sigma(h),

dHdh=p(1−p)log⁡1−pp.\frac{dH}{dh}=p(1-p)\log\frac{1-p}{p}.

At p=0.4p=0.4, entropy is 0.67301167 nats and this derivative is 0.09731163. Adding a positive entropy coefficient pushes that probability toward 0.5. At the allocation optimum p=2/3p=2/3, the entropy derivative is negative, so the regularized optimum generally changes. Encouraging diversity is an intentional objective change, not free exploration without a reward trade-off. Entropy also cannot reveal actions excluded from the policy’s support.

The same objective trains language models#

A response can be viewed as an episode: the state contains the prompt and generated prefix, an action is the next token, and a score evaluates the completed response. The score-function derivation still applies when the policy is a token distribution. Practical estimators must respect response termination, padding, sampling probabilities and the chosen reward and discount convention.

PPO is one way to update such a policy, often alongside a separate reference-policy KL penalty. That penalty and PPO’s clipped ratio have different roles. Reward-model mistakes, sampling costs and response-level credit assignment remain. The language-model RL note develops that setting; no language-model experiment is inferred from the scheduler’s eight trajectories.

What changed#

Value learning represents action quality and extracts a decision rule. Policy gradients optimize the decision distribution directly. A baseline controls score-estimator variance, an actor-critic trades complete returns for bootstrapping, GAE selects a residual horizon, and TRPO/PPO address how policy updates use data collected earlier. These choices solve different parts of the problem and have separate assumptions.

Limitations#

A gradient is local and depends on the policy representation and reward. Our shared scheduler cannot reach the state-aware policy’s reward one even with exact optimization. Sampled gradients introduce variance; an inaccurate critic adds bias to bootstrapped updates. Repeated batch reuse needs its own correction or surrogate. Ratio clipping does not guarantee bounded KL, and entropy regularization changes the objective. Check these mechanisms separately before interpreting a learning curve.

What you should remember#

  • Differentiate trajectory probabilities with score factors; retain the discount convention.
  • A valid baseline preserves the mean; variance reduction depends on its choice.
  • Critic bootstrapping and finite-cutoff handling change the estimator.
  • PPO clips incentives, while actual probability changes still need measurement.
  • A small exact environment checks arithmetic and assumptions, not benchmark performance.

Code#

Run python3 scripts/notes/policy-gradient-allocation.py from the repository. The standard-library implementation enumerates all eight schedules with exact fractions, checks the logit gradient against differentiation, compares baseline variances, computes GAE and the clipped/KL examples, and verifies the saved results.

These fixtures and calculations were newly authored for this project with Codex assistance. They use no external dataset, simulator, model or training code. The experiment is exhaustive arithmetic, not a sampled comparison of learning algorithms.

Next#

The scheduler’s transition rule was available for exact checking, but the score estimator did not use it. A learned or supplied transition model can also predict consequences before collecting another real trajectory. Model-based reinforcement learning examines when that planning helps and how model error changes the result.

References#