Adjust the policy itself, uphill in expected reward. Noisy REINFORCE estimates and the baseline that tames them, a pole balanced by a network trained in your browser, and trust regions.
Instead of learning values and acting greedily on them, describe the policy itself with parameters and push those parameters uphill in expected reward. The gradient can be estimated from nothing but sampled episodes — noisily — and taming that noise is most of the craft.
Press Sample a few times and watch REINFORCE estimates scatter around the true gradient, then compare the tighter cloud with a baseline. Push the reward offset to +10 and watch the no-baseline cloud explode.
The policy picks action A, B or C with probabilities softmax(θ₁, θ₂, 0), and each episode is one choice with a fixed reward. The heatmap is the exact J(θ) (green high, rose low) with contours; the white arrow is the exact gradient. Thin lines are batch estimates, the rings their means and the dashed ellipses one standard deviation. Blue uses no baseline and purple subtracts b, computed from the same samples. Drag on the landscape to move θ, and drag the green bars to change the rewards.
Write the expected return as J(θ) = Σₐ π(a | θ) G(a), the average return when actions are drawn from the policy. Differentiating, and using ∇π = π ∇log π, gives the score-function or likelihood-ratio identity ∇J(θ) = E[G ∇log π(a | θ)]. The right-hand side is an expectation under the policy, so it can be estimated by sampling: run episodes, and for each one multiply its return by the gradient of the log-probability of what was done. Nothing about how the rewards are produced needs to be known or differentiable. Ronald Williams named this family of estimators REINFORCE in 1992.
For multi-step problems, the policy gradient theorem (Sutton, McAllester, Singh and Mansour, 2000) says ∇J(θ) = E[Σₜ qπ(sₜ, aₜ) ∇log π(aₜ | sₜ; θ)]: each action is credited with the value of taking it, and — remarkably — the gradient does not involve the derivative of the state distribution, even though changing the policy changes which states are visited.
Any baseline b that does not depend on the action leaves the estimator unbiased, because E[∇log π] = Σₐ ∇π(a | θ) = ∇Σₐ π(a | θ) = ∇1 = 0. So E[(G − b) ∇log π] = E[G ∇log π] for every b, but the variance changes a lot. A constant added to every reward moves the no-baseline estimate by that constant times ∇log π — pure noise, which is exactly what the offset slider shows. The demo’s optimal constant b* = E[G ‖∇log π‖²] / E[‖∇log π‖²] minimises the total variance; the running mean of returns is the usual practical choice.
Making the baseline depend on the state, b(s) ≈ vπ(s), is better still, and learning it as you go gives actor–critic methods: an actor (the policy) and a critic (a value function) trained side by side, with the advantage G − v(s) telling the actor whether an action was better or worse than usual.
Press Train and watch a small network learn to balance the pole, live, while the learning curve climbs to the 500-step cap. Then nudge the pole, or take control and try it yourself.
Gym-standard CartPole: ±10 N pushes every 0.02 s, failure past ±2.4 m or 12°, capped at 500 steps. The policy network (4 → 32 → 2, tanh, softmax) is trained by REINFORCE with reward-to-go (γ = 0.99) and Adam, one update per 2 episodes; the optional baseline is a second network (4 → 32 → 1) that predicts the return from each state. Training runs at up to 1,500 environment steps per second on Normal, while the cart above replays the current policy in real time. Purple curves use the baseline, blue curves do not; network edges are green for positive weights and rose for negative ones.
Cart-pole balancing is one of the oldest benchmarks in the field. Barto, Sutton and Anderson (1983) solved it with two neuron-like elements: an associative search element that chose pushes and an adaptive critic element that learned to predict failure and turned that prediction into a reward signal for the first — an early actor–critic. The dynamics and limits used here are theirs, with the constants of the widely used Gym implementation.
The policy here is a network with 226 parameters (4 inputs → 32 tanh units → 2 action logits). After every pair of episodes, each step t gets the reward-to-go Gₜ = rₜ + γ rₜ₊₁ + γ² rₜ₊₂ + …, the discounted reward that came after it (γ = 0.99), and the update is θ ← θ + α · (1/N) Σₜ (Gₜ − v(sₜ)) ∇log π(aₜ | sₜ; θ), taken by Adam. Using reward-to-go rather than the whole episode’s return is still unbiased — an action cannot affect rewards that came before it — and it removes noise. In an episode that ran long, early actions have large Gₜ and become more likely; in an episode that ended in a fall, the actions just before it have small Gₜ and, once the baseline expects more, become less likely.
With the baseline switched off the update uses Gₜ alone: every action in every episode is pushed up, and only the differences in how much tell the policy anything. In our tests, the default settings reach an average of 400 steps over 20 episodes after a median of about 14,000 environment steps (around 9 seconds at Normal speed); without the baseline it takes about twice as long and often falls back from the cap. These are measurements on this small problem, not general laws.
A human at the controls has a hard time, even in slow motion: you see the pole lean before you react, while the network reads the angular velocity directly and decides 50 times a second.
Press Play and watch the KL bars as three update rules climb the same reward curve. The vanilla rule overshoots once its policy narrows; drag the reward points or the start to try other landscapes.
The policy samples an action a ~ N(μ, σ²) and earns r(a). All three rules use exact expectations computed by quadrature (no sampling noise), with parameters (μ, log σ). Vanilla: θ ← θ + α ∇J. Natural: θ ← θ + η F⁻¹∇J, with F = diag(1/σ², 2) the Fisher information and η chosen so each step has KL ≈ δ. PPO: 10 Adam steps (step size 0.01) on the clipped surrogate with normalised advantages. In panel A, solid is the clipped objective and dashed the unclipped r · Â; grey bands are where the gradient vanishes. σ is floored at 0.02.
A gradient step is a step of fixed length in parameter space, but what matters is how much the policy’s behaviour changes. For a Gaussian policy, moving the mean by 0.1 hardly matters when σ = 1 and changes everything when σ = 0.02: the KL divergence of a mean shift Δμ is Δμ² / (2σ²). The natural gradient(Kakade, 2001) measures steps with the Fisher information F = E[∇log π ∇log πᵀ] instead, stepping along F⁻¹∇J. Because ½ ΔθᵀFΔθ approximates the KL divergence of a small step, the step is the same size in behaviour wherever it starts, and to first order it does not depend on how the policy happens to be parameterised.
Trust Region Policy Optimization (TRPO; Schulman et al., 2015) turns this into a constraint: maximise the surrogate E[r(θ) Â] with r(θ) = πθ(a | s) / πold(a | s), subject to an average KL divergence from the old policy of at most δ, solved with conjugate gradients and a line search. In the demo the natural gradient is scaled so that every step has KL δ, which is the same idea in its simplest form.
Proximal Policy Optimization (PPO; Schulman et al., 2017) replaces the constraint with clipping: maximise E[min(r Â, clip(r, 1 − ε, 1 + ε) Â)] by several epochs of ordinary first-order optimisation on the same batch. Once r has moved more than ε in the direction the advantage favours, the objective goes flat and the gradient vanishes, so there is no incentive to go further. This is not a hard bound — the policy can still drift — but it is simple, works with any network, and PPO became a default workhorse, including for fine-tuning language models from human feedback (see also the Rewards and Preferences lesson).
The demo is a simplification: all three rules use exact expectations rather than samples, so the only thing that differs is how each turns the same gradient information into a step.
Spot a mistake or have an idea?