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.
Q-learning and temporal-difference learning · Deep Q-networks · Gradient descent
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 for all three decisions, independently of the slot and previous choices. Always choosing either job type fails. How should we adjust 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 and selects an action with a large value. A policy method represents 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 each time. We are comparing policies within that restricted class.
There are three successful schedules. Each has probability , so
On , the maximum is at , with expected reward . 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.
Three slots, one probability
The policy gradient theorem#
Let a finite episode be , with policy . For discount , define
Assume the initial distribution, environment transitions and reward rule do not depend on . 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:
The identity then gives
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
Writing for reward-to-go yields
Replacing by its conditional expectation preserves the mean. Grouping terms by state gives the policy-gradient theorem with discounted visitation weights , as in Sutton et al., Theorem 1. In a finite-horizon task, include time in the state. Uniformly averaging all visited steps while omitting 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 with a scalar logit . If a trajectory contains priority choices, its log-probability derivative is
With and reward only at termination, its gradient estimate is . At , each successful trajectory has probability , reward one and score . The other five trajectories contribute zero. Hence
Direct differentiation agrees: . 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:
Thus can replace . 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 and estimator . Its mean remains 0.2304. Exact enumeration gives:
| Baseline | Value | Gradient variance |
|---|---|---|
| None | 0 | 0.13123584 |
| Expected reward | 0.288 | 0.08478720 |
| Best constant for this estimator | 0.256 | 0.08404992 |
Why is the best constant different from the value? Differentiating the second moment with respect to gives
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 makes every estimate zero and is biased here: this baseline uses the current actions’ outcome. At , 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 and . 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,
A learned critic supplies the temporal-difference residual . 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:
Use the backward recursion with . At , only one TD residual remains. At , a genuinely terminated episode with telescopes to , so the critic acts only as an action-independent baseline. For intermediate values, the balance depends on critic error and reward variability; no fixed is uniformly best.
A separate original four-step trace has rewards and value estimates . With , its TD residuals are . For , multiply each next advantage by 0.48:
| Step | TD residual | GAE advantage |
|---|---|---|
| 0 | 0.68 | 0.6146432 |
| 1 | −0.38 | −0.13616 |
| 2 | 0.22 | 0.508 |
| 3 | 0.60 | 0.600 |
For example, . The negative sign discourages the sampled action at step one in the actor term. The critic can regress toward fixed targets ; these are bootstrapped estimates, not observed full returns for every .
A collection cutoff is different from termination. If the process continues after step four, retaining a bootstrap value 0.7 adds to the start’s 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 on old-policy data. A surrogate averages 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 , where is the policy Fisher matrix. Maximizing a linearized improvement under this quadratic constraint gives a direction proportional to , 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):
For our illustrative choice , the interval is :
| Ratio | Advantage +3 | Advantage −2 |
|---|---|---|
| 0.7 | 2.10 | −1.70 |
| 1.0 | 3.00 | −2.00 |
| 1.3 | 3.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 . With ,
At , 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 , 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#
- Richard S. Sutton, David McAllester, Satinder Singh, Yishay Mansour. Policy Gradient Methods for Reinforcement Learning with Function Approximation. NeurIPS 12, 1999. Section 1 and Theorem 1; discounted visitation formulation. Scientific reference, no source task or figure reproduced.
- Ronald J. Williams. Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement Learning. Machine Learning 8, 229–256, 1992. Historical REINFORCE attribution; the finite score calculation above is derived directly.
- John Schulman, Philipp Moritz, Sergey Levine, Michael I. Jordan, Pieter Abbeel. High-Dimensional Continuous Control Using Generalized Advantage Estimation. ICLR 2016; version 6, 2018. Section 3, residual sums and the value-error/variance trade-off.
- John Schulman, Sergey Levine, Philipp Moritz, Michael I. Jordan, Pieter Abbeel. Trust Region Policy Optimization. ICML 2015; version 5, 2017. Sections 3–6, maximum versus average KL and practical optimization.
- John Schulman, Filip Wolski, Prafulla Dhariwal, Alec Radford, Oleg Klimov. Proximal Policy Optimization Algorithms. 2017. Sections 3 and 5, clipped surrogate and actor-critic optimization. No source benchmark results or implementation copied.