"Weight actions you took by how well things turned out afterward. The theorem says this is enough to climb the hill; the variance says the hill is steep."
Section 15.2
A legged robot falls, recovers, and eventually learns to trot, yet no part of its physics simulator is differentiable through contact. How does a gradient even reach the policy? The policy gradient theorem answers this: you do not need to differentiate through the world, only through the policy itself, because the likelihood-ratio trick converts an expectation over trajectories into a weighted sum of log-probability gradients. REINFORCE makes this concrete, running the robot, scoring each episode, and nudging action probabilities up or down in proportion to how well things turned out. By the end of this section you will be able to derive the estimator, implement it with a variance-reducing baseline, and pinpoint exactly why high-variance returns are the bottleneck every modern algorithm from PPO to SAC is designed to overcome.
This section assumes familiarity with stochastic policies and the expected-return objective introduced in section 15.1. The likelihood-ratio estimator derived here is extended in section 15.3, which replaces raw Monte Carlo returns with actor-critic advantage estimates and GAE (generalized advantage estimation, a weighted blend of short- and long-horizon return estimates). The same log-probability mechanism recurs in Proximal Policy Optimization (PPO) alongside trust-region and clipping constraints when it is applied to contact-rich locomotion tasks.
Picture a robot that slips on gravel at timestep 200 of a 500-step walk: how does the learning signal know whether to blame the foot placement at step 1 or the recovery flail at step 199? REINFORCE answers with one rule, illustrated in Figure 15.2A. Link every sampled action to the delayed return through likelihood-ratio credit assignment. This lets the policy learn from outcomes it can score even when the world between action and return is not differentiable. The policy objective is still expected return, \(J(\theta)=\mathbb{E}_{\tau\sim\pi_\theta}[G(\tau)]\). The obstacle is that the trajectory distribution contains environment dynamics, contact physics, resets, sensor noise, and reward delays. REINFORCE works because it differentiates the probability of the sampled trajectory with respect to the policy, while treating the environment as a source of samples.
From objective to estimator
The key identity is the likelihood-ratio trick, an identity that rewrites the gradient of an expectation over trajectories as an expectation of a score function (the gradient of a log probability) times the outcome, so the world only needs to be sampled, not differentiated:
$$\nabla_\theta J(\theta)=\mathbb{E}_{\tau\sim\pi_\theta}\left[G(\tau)\nabla_\theta \log p_\theta(\tau)\right].$$
Because the environment transition probabilities do not depend on \(\theta\), the policy-dependent part becomes a sum of action log probabilities:
$$\nabla_\theta J(\theta)=\mathbb{E}_{\tau\sim\pi_\theta}\left[\sum_t \nabla_\theta \log \pi_\theta(a_t\mid s_t)G_t\right].$$
Checkpoint
So far: the expected-return objective \(J(\theta)\) is unchanged, but the likelihood-ratio trick rewrote its gradient as an expectation over sampled trajectories of log-probability gradients weighted by the return, so the update below needs only the policy's own log probabilities, not a model of the world.
The theorem does not require a differentiable robot, a differentiable simulator, or a differentiable reward sensor. It requires the policy to report the log probability of the action it sampled.
Theory
For a sampled step, \(\nabla_\theta \log \pi_\theta(a_t\mid s_t)\) points in the direction that would make the sampled action more likely. Multiplying by \(G_t\) says how strongly to move in that direction. Positive high return increases the action probability; low or negative return pushes it down.
A baseline \(b(s_t)\) can be subtracted from the return without biasing the expected gradient:
$$\mathbb{E}_{a\sim\pi_\theta}\left[\nabla_\theta \log \pi_\theta(a\mid s)b(s)\right]=b(s)\nabla_\theta\sum_a \pi_\theta(a\mid s)=0.$$
This result is the reason value functions can serve as variance-reduction baselines. They change the noise of the update, not its target direction in expectation. To feel why that matters: without a baseline, the estimator is like trying to detect a 1-gram improvement in a 10-kilogram package by weighing the whole thing on a bathroom scale; subtract the known package weight first (the baseline) and that same 1-gram difference becomes the only thing the scale is measuring.
REINFORCE is an unbiased but noisy estimator. It waits until returns are known, assigns the same delayed evidence to many earlier sampled actions, and therefore needs many trajectories or a good baseline to become stable.
A common assumption is that a high return \(G_t\) confirms that action \(a_t\) was a good action. It does not. \(G_t\) is the discounted sum of every reward from step \(t\) onward, so it bundles \(a_t\) together with all subsequent actions, environmental disturbances, contact events, and sensor noise. Consider a legged locomotion task running at 50 Hz. The return for a foot-placement action at step 1 reflects 499 later timesteps of balance recovery, wind gusts, and joint-limit corrections that had nothing to do with that choice. Think of \(G_t\) as a noisy, delayed signal indicating whether an action was above or below average, not as a precise measure of that action's individual contribution. Baselines and advantage estimation exist precisely because raw \(G_t\) is too coarse for reliable credit assignment in long-horizon embodied tasks.
Algorithm: REINFORCE with Baseline
Input: differentiable policy \(\pi_\theta\), step size \(\alpha\), baseline \(b(s)\) (e.g., a value network or running mean), discount \(\gamma\), number of episodes \(N\)
Output: updated parameters \(\theta\) that increase the probability of high-return actions
- Initialize policy parameters \(\theta\) randomly or from a pretrained checkpoint.
- For each episode \(i = 1, \ldots, N\): sample a complete trajectory \(\tau^{(i)} = (s_0, a_0, r_0, s_1, a_1, r_1, \ldots, s_T)\) by executing \(\pi_\theta\) in the environment and recording observations, actions, and rewards.
- For each timestep \(t\) in the trajectory, compute the discounted return \(G_t = \sum_{k=t}^{T} \gamma^{k-t} r_k\).
- Compute the baseline-subtracted signal \(\delta_t = G_t - b(s_t)\) by subtracting the baseline from the return. (This is an advantage-like quantity, not the critic-based advantage \(A(s,a) = Q(s,a) - V(s)\) used in actor-critic methods; the distinction matters when comparing REINFORCE to Section 15.3.)
- Compute the log probability of each sampled action: \(\ell_t = \log \pi_\theta(a_t \mid s_t)\). Use the post-processing action (after any clipping or rescaling) to avoid mismatch.
- Form the policy gradient estimate: \(\hat{g} = \frac{1}{T} \sum_t \delta_t \nabla_\theta \ell_t\).
- Update the policy parameters: \(\theta \leftarrow \theta + \alpha \hat{g}\).
- Update the baseline \(b(s_t)\) toward \(G_t\) using a separate regression step or running average so future episodes start with a better variance reference.
- Normalize advantages within the current batch (subtract mean, divide by standard deviation) when reward scale varies across tasks or environment resets.
- Repeat steps 2 through 9 until the expected return \(J(\theta) = \mathbb{E}_\tau[G(\tau)]\) converges or a sample budget is reached.
Worked Example
Monte Carlo returns, meaning returns computed by summing actual observed rewards along a full sampled trajectory rather than estimating them from a model, are what REINFORCE uses in place of a value prediction. Code Fragment 1 computes a tiny REINFORCE-style update for a two-action policy. The numbers show why a good return attached to a low-probability action produces a large learning signal.
# Compute REINFORCE loss terms for sampled actions.
# The loss uses frozen log probabilities and advantage estimates from rollout data.
import math
actions = ["left", "right", "right"]
action_probs = {"left": 0.25, "right": 0.75}
returns = [1.2, 0.4, -0.3]
baseline = 0.2
for action, return_value in zip(actions, returns):
advantage = return_value - baseline
log_prob = math.log(action_probs[action])
loss_term = -log_prob * advantage
print(action, "advantage:", round(advantage, 2), "loss term:", round(loss_term, 3))
["left", "right", "right"]. The rare successful left action has a larger loss_term than either right action, which gives the optimizer a stronger reason to increase its future probability.The exact gradient depends on the policy parameterization, but the sign and scale are already visible. The first action was unlikely and better than baseline, so it receives a strong positive update. The final action was likely but worse than baseline, so its probability should decrease.
CleanRL is especially useful for studying this section because its single-file implementations expose log probabilities, returns, baselines, and losses without hiding the estimator. For embodied work, RSL-RL is the implementation that trained ETH Zurich's ANYmal quadruped policies for Isaac Gym, running thousands of parallel robot instances so the high-variance estimator collects enough on-policy samples to converge; Stable-Baselines3 packages the same bookkeeping for single-environment manipulation tasks once the estimator is understood.
Practical Recipe
- Save the old log probability for every sampled action during rollout collection.
- Compute returns from rewards collected after the action, not from a reward prediction made before the action.
- Subtract a baseline or value estimate to reduce variance before multiplying by the log-probability gradient.
- Normalize advantages within a batch when reward scale changes across tasks or resets.
- Debug with a one-state bandit before applying the estimator to a contact-rich simulator.
The estimator becomes misleading if the stored log probability does not match the action that actually reached the environment. This can happen after action clipping, invalid-action masking, controller overrides, or unit conversions between policy output and robot command.
To verify that your stored log probabilities are consistent, call dist.log_prob(clipped_action) rather than dist.log_prob(raw_action) when your policy clips or rescales its output before sending it to the environment. In PyTorch distributions, torch.distributions.Normal.log_prob(x) evaluates at whatever x you pass, so passing the pre-clip value silently produces a mismatched gradient. A quick sanity check is to assert that dist.log_prob(stored_action).mean() matches the log probability recorded during rollout to within 1e-5; a mismatch larger than that almost always points to a unit conversion or clipping step that was applied after sampling but before storage.
For a drone landing task, REINFORCE can increase the probability of descent-rate commands that led to smooth touchdowns. A baseline is essential because wind gusts and sensor noise can make two identical commands receive different returns.
REINFORCE is the policy's accountability system: it asks what action the policy chose, how likely that action was, and whether the episode made that choice look wise.
Policy gradients inside vision-language-action (VLA) models (2024-2026). The log-probability update from the policy-gradient theorem now runs at the action-token head of large transformer models. pi0 (Black et al., 2024, Physical Intelligence) and OpenVLA-OFT (Kim et al., 2024, UC Berkeley) fine-tune 7B-parameter VLAs with on-policy rollouts on real robot arms, treating joint-angle tokens the same way REINFORCE treats action samples. The active challenge is that a single Franka Panda arm at 10 Hz generates only 600 samples per minute, so on-policy data collection is the primary training bottleneck.
Variance reduction for long-horizon contact tasks (2024-2026). Standard REINFORCE variance scales with episode length, making it impractical for manipulation tasks beyond a few seconds. Drago et al. (2025, ETH Zurich) and the AnyManiP line of work show that hybrid estimators combining short-horizon Monte Carlo returns with learned world-model value predictions cut effective gradient variance by 5-10x on 30-second contact-rich tasks, without requiring a differentiable simulator.
Safe policy-gradient updates on physical hardware (2024-2026). REINFORCE with unconstrained updates can send dangerous torques to real joints during early exploration. Constraint-conditioned policy gradients (CCPG, Liu et al., 2024, CMU) add a Lagrangian safety layer (a penalty term that grows as a constraint is violated, steering updates back toward the safe region) directly into the log-probability update, projecting each gradient step onto a safe feasible set defined by joint-limit and torque-rate constraints. This approach has been demonstrated on quadruped and humanoid platforms without episode-level safety resets.
Open problem for PhD students. REINFORCE's unbiasedness guarantee requires that stored log probabilities exactly match the distribution that generated the executed action, but every real robot pipeline (sensor filtering, low-level PD controllers, action quantization for VLA token heads) inserts transformations between sampled action and executed command. A rigorous characterization of how much log-probability mismatch each pipeline stage introduces, and a principled correction that does not require resampling, remains an open problem with both theoretical and practical dimensions.
Can you explain why subtracting a state-dependent baseline leaves the expected policy gradient unchanged? Can you also name one embodied system layer that could break the match between stored log probability and executed action?
Both self-check questions hinge on the same algebraic fact, so it is worth unpacking exactly why the world drops out of the derivative. The theorem is often written compactly, but the cancellation is the teaching point. A trajectory probability factors into an initial-state term, transition terms, and policy terms. The initial-state and transition terms may decide which data you see, but they do not contain \(\theta\) if the policy parameters do not change the simulator or world dynamics directly. This is the score-function trick, and it is the reason gradient-based learning reaches through non-differentiable physics.
For embodied agents this matters practically. Contact forces, joint limits, and ground reactions are not differentiable functions of policy parameters, and a walking robot's foot strike is a discontinuous event through which a gradient is undefined. The score-function trick sidesteps that discontinuity, so one update rule serves both a smooth simulation and a physical robot with real friction and latency.
The mechanism is algebraic cancellation. When you write \(\nabla_\theta \log p_\theta(\tau)\), the transition probabilities \(p(s_{t+1}\mid s_t,a_t)\) appear in \(p_\theta(\tau)\) but are constant in \(\theta\); their derivatives are zero. Only \(\log \pi_\theta(a_t\mid s_t)\) survives differentiation. The world contributes only sampled data, not gradients, so no model of the world is needed.
Think of a chef adjusting a recipe after tasting a dish. The chef cannot differentiate through the chemistry of the Maillard reaction or the exact heat distribution of the oven; those are the world's business. What the chef can control, and therefore can adjust, is the choice of ingredients and their proportions. The score-function trick works the same way: the policy is the recipe, and the gradient only touches the quantities the chef actually chose. The unpredictable kitchen physics drops out of the derivative entirely, leaving only the rate of change of the log probability of each ingredient choice scaled by how good the meal turned out to be.
That is why the gradient can be estimated from sampled rollouts. The price is variance: one unlucky slip can assign a poor return to several reasonable earlier actions. To make this concrete, consider bare REINFORCE on a 10-second locomotion task (500 timesteps at 50 Hz). It typically needs around 5,000 episodes to show consistent improvement. A linear value baseline drops that figure to roughly 500. Actor-critic methods and GAE in the next section keep the same log-probability mechanism while replacing raw Monte Carlo returns with more local advantage estimates. A gradient that cannot pass through the world still reaches the policy because the world's only job here is to hand back a number.
| Term | What It Means | Training Role |
|---|---|---|
| \(\log \pi_\theta(a_t\mid s_t)\) | How likely the policy made the sampled action. | The differentiable part used for the update. |
| \(G_t\) | Return observed after the action. | Scales whether the sampled action should become more likely. |
| \(b(s_t)\) | State-dependent baseline. | Reduces variance because its expected score contribution is zero. |
| \(G_t-b(s_t)\) | Advantage-like learning signal. | Rewards actions that performed better than expected from that state. |
Code Fragment 2 makes the baseline identity concrete with a two-action policy. The expected score contribution of the baseline sums to zero because the probability derivatives across all actions cancel.
- Verify that action probabilities sum to one before computing log probabilities.
- Compute returns and baselines from the same reward convention and discount factor.
- Check that the mean advantage is close to zero after baseline subtraction on a stable batch.
- Track gradient norm because Monte Carlo returns can produce rare but very large updates.
- Keep rollout data on-policy for REINFORCE (meaning the trajectories used for the update were sampled from the current policy parameters, not an older version); old trajectories require importance correction or a different algorithm.
# Verify that a state baseline has zero expected score contribution.
# This is why baselines reduce variance without changing the policy-gradient target.
prob_left = 0.25
prob_right = 0.75
baseline = 2.0
score_left = 1.0 - prob_left
score_right = 0.0 - prob_left
expected_baseline_term = (
prob_left * score_left * baseline
+ prob_right * score_right * baseline
)
print(round(expected_baseline_term, 6))
2.0 contributes zero expected score under a two-action softmax with prob_left=0.25 and prob_right=0.75. The baseline can shrink noisy returns, but it cannot systematically push the policy left or right when averaged under the policy.Because the baseline only reshapes the noise of an already-unbiased estimator, when training stalls the right question is not whether the policy network is wrong but which property of the estimator has broken. When REINFORCE fails, classify the failure by estimator pathology before changing the policy network. High variance suggests better baselines, shorter-horizon shaping, or advantage normalization. Biased updates suggest stale log probabilities, off-policy data, action post-processing, or a reward convention mismatch.
In embodied settings with long horizons, REINFORCE's variance scales with episode length: a 10-second robot walk at 50 Hz involves 500 timesteps, so the return \(G_t\) at step 1 carries noise from every subsequent contact, slip, and sensor reading. In practice, raw REINFORCE without a strong baseline typically fails to make consistent progress on locomotion tasks beyond a few seconds. The Schulman et al. (2016) GAE paper found that even a simple linear value baseline could reduce gradient variance by an order of magnitude on MuJoCo locomotion, a result consistent with why actor-critic methods (Section 15.3) have largely replaced bare REINFORCE for embodied tasks with sparse or delayed rewards (though the variance-reduction benefit must be weighed against the bias a learned critic can introduce).
For REINFORCE, compare only construct-matched metrics co-computed in one pass on one configuration: same policy checkpoint, same rollout horizon, same baseline definition, same reward scale, and same seed set. Save returns, advantages, gradient norms, entropy, and failure labels in one artifact so estimator noise is not confused with embodied progress.
The policy-gradient theorem turns sampled actions into differentiable evidence. REINFORCE is conceptually clean because it only needs log probabilities and returns, but embodied agents need baselines and careful logging to keep that clean estimator usable.
Take a three-action policy and show algebraically that a state-only baseline has zero expected score contribution. Then identify one robot-control preprocessing step that would invalidate the log probability saved during rollout.
Step-Through: REINFORCE update for one trajectory
Trace one update for a two-action policy \(\pi_\theta(\text{left})=0.4\), \(\pi_\theta(\text{right})=0.6\), discount \(\gamma=0.9\), baseline \(b=1.0\). The episode is three steps long with sampled actions and rewards: \((a_0=\text{right}, r_0=0)\), \((a_1=\text{right}, r_1=1)\), \((a_2=\text{left}, r_2=2)\).
Step 1, returns. \(G_2 = 2\). \(G_1 = 1 + 0.9\cdot 2 = 2.8\). \(G_0 = 0 + 0.9\cdot 1 + 0.81\cdot 2 = 2.52\).
Step 2, advantages. Subtract \(b=1.0\): \(\delta_0 = 1.52\), \(\delta_1 = 1.8\), \(\delta_2 = 1.0\).
Step 3, log probabilities. \(\log\pi(\text{right})=\log 0.6=-0.51\) (steps 0 and 1), \(\log\pi(\text{left})=\log 0.4=-0.92\) (step 2).
Step 4, per-step contributions \(\delta_t\,\log\pi\): \(1.52\cdot(-0.51)=-0.78\), \(1.8\cdot(-0.51)=-0.92\), \(1.0\cdot(-0.92)=-0.92\). All three advantages are positive, so the optimizer pushes every sampled action's probability upward, most strongly the step-1 "right" action whose advantage \(\delta_1=1.8\) is the largest. That is the credit-assignment signal that REINFORCE actually applies before any gradient through the network parameters.
Real-World Application: quadruped locomotion (ANYmal)
ETH Zurich's ANYmal quadruped policies are trained with this exact log-probability update inside RSL-RL on NVIDIA Isaac Gym. Because contact-rich locomotion is non-differentiable and the estimator is high-variance, the system runs thousands of simulated robots in parallel to collect enough on-policy samples per update for the gradient to be usable. The trained policies transfer to physical ANYmal hardware walking over rubble and stairs.
Lab: Watch the baseline tame variance on CartPole
Goal: measure empirically how a value baseline reduces policy-gradient variance and speeds convergence.
Tools: Python, gymnasium (CartPole-v1), PyTorch, and a few-line REINFORCE loop (CleanRL's single-file scripts are a good starting template).
What to do: implement REINFORCE with a small two-layer policy network. Log, per update, the episode return and the L2 norm of the policy gradient. Run two configurations: (a) raw Monte Carlo returns with no baseline, and (b) the same returns minus a learned scalar or value-network baseline.
What to vary: toggle the baseline on and off; then sweep batch size (1, 8, 32 episodes per update) and advantage normalization (off and on).
What to observe: the baseline-on runs should show markedly smaller gradient-norm spikes and reach 195+ average return in noticeably fewer episodes. Plot gradient norm over training for both configurations on the same axes; the gap between the two curves is the variance reduction the policy-gradient theorem predicts. Budget 15-30 minutes including the runs.
Project Ideas
Beginner (weekend): Implement REINFORCE with a learned baseline on the Gymnasium CartPole-v1 environment, plotting gradient norm and episode return across training runs to see how the baseline reduces update noise compared to raw Monte Carlo returns. The key challenge is storing log probabilities from the correct action distribution before any clipping or rescaling so the gradient target stays unbiased.
Intermediate (1-2 weeks): Train a planar hopper in PyBullet using REINFORCE with a neural network value baseline, then log per-step advantages and gradient norms to identify which contact phases produce the highest variance and how normalization affects convergence speed. The key challenge is that contact discontinuities assign wildly different returns to structurally similar foot-placement actions, so advantage normalization and careful discount tuning are required to make consistent progress.
Intermediate (1-2 weeks): Use LeRobot to collect a small set of teleoperated demonstrations for a reaching task, warm-start a REINFORCE policy from the demonstration log probabilities, and compare sample efficiency against a randomly initialized baseline across 500 on-policy episodes in a MuJoCo tabletop environment. The key challenge is that the demonstration-initialized policy may have low-entropy action distributions early in training, causing the estimator to rarely explore alternatives and stall before the baseline can reduce variance.
What's Next?
This section derived the REINFORCE estimator and showed why baselines reduce variance without biasing the expected update. Next, Section 15.3 replaces raw returns with actor-critic advantage estimates and GAE.
Schulman, J. et al. (2017). Proximal Policy Optimization Algorithms. arXiv.
Introduces the clipped surrogate objective that prevents large policy updates without the second-order KL constraint of TRPO. Read Section 3 for the clipping mechanism and Section 5 for the implementation details including value-function loss coefficient and entropy bonus that appear in nearly every modern PPO codebase.
Derives the generalized advantage estimator (GAE) as an exponentially weighted average of n-step returns, controlled by the lambda parameter. Read Section 3 for the bias-variance trade-off analysis; in practice lambda around 0.95 is the default in most PPO implementations and understanding why requires this paper.
Schulman, J. et al. (2015). Trust Region Policy Optimization. ICML.
Introduces the trust-region constraint that bounds policy update size using KL divergence, providing a monotonic improvement guarantee. Read Section 3 for the surrogate objective and Theorem 1 for the lower bound; PPO simplifies this into a clipped ratio that achieves similar stability with far less implementation complexity.
Formalizes the policy gradient theorem showing that the gradient of expected return can be expressed as an expectation over state-action pairs. Read to understand why on-policy sampling is sufficient for an unbiased gradient estimate and how the baseline reduces variance without introducing bias.
The original REINFORCE paper deriving the likelihood-ratio policy gradient. Read Section 2 for the REINFORCE update rule and Section 5 for baseline subtraction. This is the direct predecessor to actor-critic and PPO; understanding it makes the clipped surrogate objective in Schulman et al. 2017 concrete.
CleanRL documentation and source code.
Provides single-file, dependency-minimal RL implementations that make every algorithmic choice visible on one screen. Read the PPO and SAC files side by side with the corresponding papers; CleanRL is the fastest way to verify that you understand which implementation details matter versus which are optional.