The previous chapters optimized policies through Q-functions, soft Bellman relations, or path-consistency equations. Can expected return itself supply the policy objective without differentiating the environment dynamics? The score function estimator applies directly to trajectories because the policy terms are the only factors in their probability law that depend on the policy parameters.
The estimator requires only the ability to evaluate and differentiate , so it also works with discrete actions where reparameterization is unavailable.
Let be the sum of undiscounted rewards in a trajectory . The stochastic optimization problem we face is to maximize:
where is a trajectory and is the total return. Applying the score function estimator, we get:
We have eliminated the need to know the transition probabilities in this estimator since the probability of a trajectory factorizes as:
Therefore, only the policy depends on . When taking the logarithm of this product, we get a sum where all the -independent terms vanish. The final estimator samples trajectories under the distribution and computes:
This is a direct application of the score function estimator. However, we rarely use this form in practice and instead make several improvements to further reduce the variance.
Leveraging Conditional Independence¶
Given the Markov property of the MDP, rewards for are conditionally independent of action given the history . This allows us to only need to consider future rewards when computing policy gradients.
The conditional independence assumption means that the term vanishes. To see this, factor the trajectory distribution as:
We can now re-write a single term of this summation as:
The inner expectation is zero because
The Monte Carlo estimator becomes:
This gives us the REINFORCE algorithm:
The benefit of this estimator compared to the naive one (which would weight each score function by the full trajectory return ) is that it generally has less variance. This variance reduction arises from the conditional independence structure we exploited: past rewards do not depend on future actions. More formally, this estimator is an instance of a variance reduction technique known as the Extended Conditional Monte Carlo Method.
The Surrogate Loss Perspective¶
The algorithm above computes a gradient estimate explicitly. In practice, implementations using automatic differentiation frameworks take a different approach: they define a surrogate loss whose gradient matches the REINFORCE estimator. For a single trajectory, consider:
where the returns and actions are treated as fixed constants (detached from the computation graph). Taking the gradient with respect to :
Minimizing this surrogate loss via gradient descent yields the same update as maximizing expected return via REINFORCE. The negative sign converts our maximization problem into a minimization suitable for standard optimizers.
This surrogate loss is not the expected return we are trying to maximize. It is a computational device that produces the correct gradient at the current parameter values. Several properties distinguish it from a true loss function:
It changes each iteration. The returns come from trajectories sampled under the current policy. After updating , we must collect new trajectories and construct a new surrogate loss.
Its value is not meaningful. Unlike supervised learning where the loss measures prediction error, the numerical value of has no direct interpretation. Only its gradient matters.
It is valid only locally. The surrogate loss provides the correct gradient only at the parameters used to collect the data. Moving far from those parameters invalidates the gradient estimate.
This perspective explains why policy gradient code often looks different from the pseudocode above. Instead of computing explicitly, implementations define the surrogate loss and call loss.backward():
# Surrogate loss implementation (single trajectory)
log_probs = [policy.log_prob(a_t, s_t) for s_t, a_t in trajectory]
returns = compute_returns(rewards)
surrogate_loss = -sum(lp * G for lp, G in zip(log_probs, returns))
surrogate_loss.backward() # computes REINFORCE gradient
optimizer.step()Variance Reduction via Control Variates¶
Recall that the REINFORCE gradient estimator, after leveraging conditional independence, takes the form:
This is a sum over trajectories and timesteps. The gradient contribution at timestep of trajectory is:
While unbiased, this estimator suffers from high variance because the return can vary significantly across trajectories even for the same state-action pair. The control variate method provides a principled way to reduce this variance.
General Control Variate Theory¶
For a general estimator of some quantity , and a control variate with known expectation , we can construct:
This remains unbiased since . The variance is:
The term is what enables variance reduction. If and are positively correlated, we can choose to make this term negative and large in magnitude, reducing the overall variance. However, the term grows quadratically with , so if we make too large, this quadratic term will eventually dominate and the variance will increase rather than decrease. The variance as a function of is a parabola opening upward, with a unique minimum. Setting gives:
This is the coefficient from ordinary least squares regression: we predict the estimator using the control variate as the predictor. Since , the linear model is , where is the OLS slope coefficient. The control variate estimator computes the residual: the part of that cannot be explained by .
Substituting into the variance formula yields:
where is the coefficient of determination from regressing on . The variance reduction is : the better predicts , the more variance we eliminate.
Application to REINFORCE¶
In the reinforcement learning setting, our REINFORCE gradient estimator is a sum over timesteps: where each represents the gradient contribution at timestep . We apply control variates separately to each term. Since , reducing the variance of each reduces the total variance, though we do not explicitly address the cross-timestep covariance terms.
For a given trajectory at state , the gradient contribution at time is:
This is the product of the score function and the return-to-go . We can subtract any state-dependent function from the return without introducing bias, as long as does not depend on . This is because:
where the last equality follows from the score function identity (8).
We can now define our control variate as:
where is a baseline function that depends only on the state. This satisfies . Our control variate estimator becomes:
The optimal baseline minimizes the variance. To find it, consider the scalar parameter case for simplicity. Write and . We want to minimize:
Since the mean does not depend on , minimizing the variance is equivalent to minimizing the second moment . Expanding and taking the derivative with respect to gives:
For vector-valued parameters , we minimize a scalar proxy such as the trace of the covariance matrix, which yields the same formula with in place of :
This is the exact optimal baseline: a weighted average of returns where the weights are the squared norms of the score function. In practice, we treat the squared norm as roughly constant across actions at a given state, which leads to the simpler and widely used choice:
With this approximation, the variance-reduced gradient contribution at timestep becomes:
The term in parentheses is exactly the advantage function: , where the Q-function is approximated by the Monte Carlo return . The full gradient estimate for a trajectory is then the sum over all timesteps:
In practice, we do not have access to the true value function and must learn it. Unlike the methods in the amortization chapter, where we learned value functions to approximate the optimal Q-function, here our goal is policy evaluation: estimating the value of the current policy . The same function approximation techniques apply, but we target rather than . The simplest approach is to regress from states to Monte Carlo returns, learning what Williams (1992) called a “baseline”:
When implementing this algorithm nowadays, we always use mini-batching to make full use of our GPUs. Therefore, a more representative variant for this algorithm would be:
The value function is trained by regressing states directly to their sampled Monte Carlo returns . Advantage normalization (step 2.5) is not part of the optimal baseline derivation but improves optimization in practice and is standard in modern implementations.
Generalized Advantage Estimation¶
The baseline construction gave us a gradient estimator of the form:
where is the Monte Carlo return from time . For each visited state-action pair , the term in parentheses
is a Monte Carlo estimate of the advantage . If the baseline equals the true value function, , then , so this estimator is unbiased.
However, as an estimator it has two limitations. First, it has high variance because depends on all future rewards. Second, it uses the value function only as a baseline, not as a predictor of long-term returns. We essentially discard the information in
GAE addresses these issues by constructing a family of estimators that interpolate between pure Monte Carlo and pure bootstrapping. A parameter controls the bias-variance tradeoff.
Decomposing the Monte Carlo Advantage¶
Fix a value function (not necessarily equal to ) and define the one-step residual:
Start from the Monte Carlo advantage and add and subtract :
Applying this decomposition recursively yields:
The Monte Carlo advantage is exactly the discounted sum of future residuals. This is an algebraic identity, not an approximation.
The sequence provides incremental corrections to the value function as we move forward in time. The term depends only on ; depends on , and so on. As increases, the corrections become more noisy (they depend on more random outcomes) and more sensitive to errors in the value function at later states. Although the full sum is unbiased when , it can have high variance and can be badly affected by approximation error in .
GAE as a Shrinkage Estimator¶
The decomposition above suggests a family of estimators that downweight residuals farther in the future. Let and define:
This is the generalized advantage estimator .
Two special cases illustrate the extremes. When , we recover the Monte Carlo advantage:
When , we keep only the immediate residual:
Intermediate values interpolate between these extremes. The influence of decays geometrically as . The parameter acts as a shrinkage parameter: small shrinks the estimator toward the one-step residual; large allows the estimator to behave more like the Monte Carlo advantage.
If is the true value function, then and for . In this case:
for all . When the value function is exact, GAE is unbiased regardless of ; changing only affects variance.
In practice, we approximate with a function approximator, and the residuals inherit approximation error. Distant residuals involve multiple applications of the approximate value function and are more contaminated by modeling error. Downweighting them (choosing ) introduces bias but can reduce variance and limit the impact of those errors.
Mixture of Multi-Step Estimators¶
Another perspective on GAE comes from multi-step returns. Define the -step return from time :
and the corresponding -step advantage estimator . Each uses rewards before bootstrapping; larger means more variance but less bootstrapping error.
The GAE estimator can be written as a geometric mixture:
GAE is a weighted average of the -step advantage estimators, with shorter horizons weighted more heavily when is small.
Using GAE in the Policy Gradient¶
Once we choose , we plug in place of in the policy gradient estimator:
We still use a control variate to reduce variance (the baseline ), but now we construct the advantage target by smoothing the sequence of residuals with a geometrically decaying kernel.
For the value function, it is convenient to define the -return:
When , reduces to the Monte Carlo return; when , it becomes the one-step bootstrapped target .
When , this reduces (up to advantage normalization) to the Monte Carlo baseline algorithm earlier in the chapter. When , advantages become the one-step residuals , and the -returns reduce to standard one-step bootstrapped targets.
Actor-Critic as the Limit¶
The case is particularly simple. The advantage becomes:
and the policy update reduces to:
while the value update becomes a standard one-step regression toward . This gives the online actor-critic algorithm:
This algorithm was derived by Sutton in his 1984 thesis as an “adaptive heuristic” for temporal credit assignment. In the language of this chapter, it is the member of the GAE family: it uses the most local residual as both the target for the value function and the advantage estimate for the policy gradient.
Likelihood Ratio Methods in Reinforcement Learning¶
How do importance ratios and constrained or clipped surrogates reuse trajectories collected under an earlier policy?
The score function estimator from the previous section is a special case of the likelihood ratio method where the proposal distribution equals the target distribution. We now consider the general case where they differ.
Recall the likelihood ratio gradient estimator from the beginning of this chapter. For objective and any proposal distribution :
where is the likelihood ratio. The partial derivative holds because is treated as fixed, having been sampled from , which does not depend on .
In reinforcement learning, let be a trajectory, the return, the trajectory distribution under policy , and the trajectory distribution under some other policy . The gradient becomes:
where the trajectory likelihood ratio simplifies because transition probabilities cancel:
This product of ratios can become extremely large or small as grows, leading to high variance. The temporal structure provides some relief: since , future ratios for that do not affect the reward can be marginalized out. However, past ratios are still needed to correctly weight the probability of reaching state .
In practice, algorithms like PPO and TRPO make an additional approximation: they use only the per-step ratio rather than the cumulative product . This ignores the mismatch between the state distributions induced by the two policies. Combined with a baseline , the approximate estimator is:
This approximation corresponds to maximizing the importance-weighted surrogate objective:
where . Taking the gradient with respect to , only depends on (since trajectories are sampled from ):
The gradient of the ratio is:
Substituting back:
This matches equation (46). When , the ratios and we recover the score function estimator. The approximation error grows as the policies diverge, which motivates the trust region and clipping mechanisms discussed below.
Variance and the Dominance Condition¶
The ratio is well-behaved only when the two policies are similar. If assigns high probability to an action where assigns low probability, the ratio explodes. For example, if and , then , amplifying any noise in the advantage estimate.
Importance sampling also requires the dominance condition: the support of must be contained in the support of . If but , the ratio is undefined. Stochastic policies typically have full support, but the ratio can still become arbitrarily large as .
A common use case is to set , a previous version of the policy. This allows reusing data across multiple gradient steps: collect trajectories once, then update several times. But each update moves further from , making the ratios more extreme. Eventually, the gradient signal is dominated by a few samples with large weights.
Proximal Policy Optimization¶
The variance issues suggest a natural solution: keep the ratio close to 1 by ensuring the new policy stays close to the behavior policy. This keeps the importance-weighted surrogate from (47) well-behaved.
Trust Region Policy Optimization (TRPO) formalizes this by adding a constraint on the KL divergence between the old and new policies:
The KL constraint ensures that the two distributions remain similar, which bounds how extreme the importance weights can become. This is a constrained optimization problem, and one could in principle apply standard methods such as projected gradient descent or augmented Lagrangian approaches (as discussed in the trajectory optimization chapter). TRPO takes a different approach: it uses a second-order Taylor approximation of the KL constraint around the current parameters and solves the resulting trust region subproblem using conjugate gradient methods. This involves computing the Fisher information matrix (the Hessian of the KL divergence), which adds computational overhead.
Proximal Policy Optimization (PPO) achieves similar behavior through a simpler mechanism: rather than constraining the distributions to be similar, it directly clips the ratio to prevent it from moving too far from 1. This is a construction-level guarantee rather than an optimization-level constraint.
From Trajectory Expectations to State-Action Averages¶
Before defining the PPO objective, we need to clarify the relationship between the trajectory-level surrogate (47) and the state-action level objective that PPO actually optimizes. The importance-weighted surrogate is defined as an expectation over trajectories:
We can rewrite this as an expectation over state-action pairs by introducing a sampling distribution. For a finite horizon , define the averaged time-marginal distribution:
where is the probability of being in state at time when following policy from the initial distribution. This is the uniform mixture over the time-indexed state-action distributions: we pick a timestep uniformly at random from , then sample from the joint distribution at that timestep.
With this definition, the trajectory expectation becomes:
The factor is just a constant that does not affect the optimization. This reformulation shows that the importance-weighted surrogate is equivalent to an expectation over state-action pairs drawn from the averaged time-marginal distribution. This is not a stationary distribution or a discounted visitation distribution, but the empirical mixture induced by the finite-horizon rollout procedure.
The Clipped Surrogate Objective¶
PPO replaces the linear importance-weighted term with a clipped version. For a state-action pair with advantage and importance ratio , define the per-sample clipped objective:
where is a hyperparameter (typically 0.1 or 0.2) and restricts to the interval .
The population-level PPO objective is then:
where the expectation is taken over the averaged time-marginal distribution (53) induced by .
In practice, we never compute this expectation exactly. Instead, we collect a batch of transitions by running and approximate the expectation with an empirical average:
This is the same plug-in approximation used in fitted Q-iteration: replace the unknown population distribution with the empirical distribution induced by the collected batch, then compute the sample average. The empirical surrogate is simply an expectation under . No assumptions about stationarity or discounted visitation are needed. We just average over the transitions we collected.
Intuition for the Clipping Mechanism¶
The operator in (55) selects the more pessimistic estimate. Consider the two cases:
Positive advantage (): The action is better than average, so we want to increase . The unclipped term increases with . The clipped term stops increasing once . Taking the minimum means we get the benefit of increasing only up to .
Negative advantage (): The action is worse than average, so we want to decrease . The unclipped term becomes less negative (improves) as decreases. The clipped term stops improving once . Taking the minimum means we get the benefit of decreasing only down to .
In both cases, the clipping removes the incentive to move the probability ratio beyond the interval . This keeps the new policy close to the old policy without explicitly computing or constraining the KL divergence.
The algorithm collects a batch of trajectories, then performs epochs of mini-batch updates on the same data. The empirical surrogate approximates the population objective (56) using samples from the averaged time-marginal distribution. The ratio is computed in log-space for numerical stability. Clipping removes the local incentive to move a sampled probability ratio beyond the chosen interval. It does not guarantee that the sampled updates will find a successful policy, and it says nothing about physical constraints absent from the reward or environment.
Experiment: PPO on the SwingRL Plant¶
The SwingRL model from the modeling chapter provides a matched comparison between supplied structure and sampled policy optimization. Both controllers act on the same articulated standing rider, use the same two bounded commands, receive the same observations, and count one full unwrapped rotation as success. The structured controller receives a phase-locked pumping rule whose phases were selected by a model sweep. PPO receives trajectories and the environment reward.
The experiment asks whether the clipped policy-gradient update discovers a full rotation under one fixed, reproducible protocol. The protocol was chosen before inspecting the five final runs.
| quantity | value |
|---|---|
| policy and value networks | separate tanh networks |
| requested interactions | 1,000,000 per seed |
| rollout batch | 8 environments 256 steps |
| PPO epochs and minibatch | 4 epochs, 256 samples |
| optimizer | Adam, learning rate with linear decay |
| discount and GAE | , |
| clipping and entropy coefficients | 0.2 and 0.001 |
| seeds | 0, 1, 2, 3, 4 |
| evaluation | 100 fixed initial states every 50,000 requested interactions |
Each complete rollout batch contains 2,048 transitions, so the last update is recorded at 1,001,472 interactions. A checkpoint is the first complete update at or beyond its nominal 50,000-interaction target. Evaluation angles are uniform between and , angular velocities are uniform between -0.1 and 0.1 rad/s, and the deterministic policy uses the tanh of the Gaussian mean. The environment and the structured baseline use the same 100 states.
Figure 1:Recorded training replay for seed 0. Checkpoints occur every 50,000 requested interactions, with complete rollout batches producing the recorded counts shown by the slider. Each checkpoint uses the saved deterministic policy from the same initial angle. The curve shows raw completed-episode returns and an eight-point trailing mean. The 21 saved policies are compressed into 63 seconds; the overlay reports the original elapsed training time.
The replay is an illustration from one prespecified run, not the evidential comparison. Future observations remain hidden until the movie reaches their checkpoint. The five-seed result below carries the comparison across runs.
Download the recorded seed-0 replay

Figure 2:Five prespecified PPO seeds evaluated on the same 100 fixed initial states. Thin blue traces show individual seeds; the solid trace and band show the mean and a two-sided 95% interval with seed as the statistical unit. PPO improves its return early but never completes a rotation. The structured controller succeeds from every state and obtains mean return 191.8; this value is annotated off scale in the return panel so that the smaller PPO change remains visible.
The final policies settle on low-motion behavior. Across the five showcase rollouts, the largest angle lies between and . Return improves because the policy changes the rider while keeping effort and time penalties modest, but the behavior never approaches the success condition.
| controller | training transitions | held-out success | mean return | worst suspension tension |
|---|---|---|---|---|
| structured phase controller | 0 | 100% | 191.79 | -637 N |
| PPO, mean over five final policies | 1,001,472 per seed | 0% | -5.11 | +387 N |
The comparison does not establish a general ranking between control and RL. The structured controller receives the oscillation phase and a controller family adapted to the mechanism, while PPO must infer useful coordination from sampled returns. Conversely, the structured controller’s nominal success requires negative suspension tension during 7.37 percent of its active steps. A rigid rod can supply that outward force; a playground chain cannot. PPO avoids the violation by barely moving, which is feasible but does not solve the task.
The two failures answer different audit questions. Optimization has not found a successful sampled policy under this protocol. The successful structured policy exposes an inadequate rigid-link model. More interactions or a revised learning objective might address the first failure. A unilateral chain model or an explicit tension constraint is required for the second.
The complete Python implementation includes policy sampling, tanh-corrected log probabilities, GAE, PPO updates, batched SwingRL evaluation, checkpoint serialization, and replay rendering. The experiment record specifies the artifact layout and reproduction command. Policy training is deliberately absent from the MyST build; the page reads the recorded checkpoints, tables, figures, and movie.
The Policy Gradient Theorem¶
How can the trajectory-level score estimator be rewritten as an expectation over discounted state visitation and action values?
The algorithms developed so far (REINFORCE, actor-critic, GAE, and PPO) all estimate policy gradients from sampled trajectories. We now establish the theoretical foundation for these estimators by deriving the policy gradient theorem in the discounted infinite-horizon setting.
Sutton et al. (1999) provided the original derivation. Here we present an alternative approach using the Implicit Function Theorem, which frames policy optimization as a bilevel problem:
subject to:
The Implicit Function Theorem states that if there is a solution to the problem , then we can “reparameterize” our problem as where is an implicit function of . If the Jacobian is invertible, then:
Here we made it clear in our notation that the derivative must be evaluated at root of . For the remaining of this derivation, we will drop this dependence to make notation more compact.
Applying this to our case with :
Then:
where we have defined the discounted state visitation distribution:
Recall the vector notation for MDPs from the infinite-horizon MDP chapter:
Taking derivatives with respect to gives:
Substituting back:
This is the policy gradient theorem, where is the discounted state visitation distribution and the term in parentheses is the state-action value function .
Normalized Discounted State Visitation Distribution¶
The discounted state visitation is not normalized. Therefore the expression we obtained above is not an expectation. However, we can transform it into one by normalizing by . Note that for any initial distribution :
Therefore, defining the normalized state distribution , we can write:
Now we have expressed the policy gradient theorem in terms of expectations under the normalized discounted state visitation distribution. But what does sampling from mean? Recall that . Using the Neumann series expansion (valid when , which holds for since is a stochastic matrix) we have:
We can then factor out the first term from this summation to obtain:
The balance equation:
shows that is a mixture distribution: with probability you draw a state from the initial distribution (reset), and with probability you follow the policy dynamics from the current state (continue). This interpretation directly connects to the geometric process: at each step you either terminate and resample from (with probability ) or continue following the policy (with probability ).
import numpy as np
def sample_from_discounted_visitation(
alpha,
policy,
transition_model,
gamma,
n_samples=1000
):
"""Sample states from the discounted visitation distribution.
Args:
alpha: Initial state distribution (vector of probabilities)
policy: Function (state -> action probabilities)
transition_model: Function (state, action -> next state probabilities)
gamma: Discount factor
n_samples: Number of states to sample
Returns:
Array of sampled states
"""
samples = []
n_states = len(alpha)
rng = np.random.default_rng(2026)
# Initialize state from alpha
current_state = rng.choice(n_states, p=alpha)
for _ in range(n_samples):
samples.append(current_state)
# With probability (1-gamma): reset
if rng.random() > gamma:
current_state = rng.choice(n_states, p=alpha)
# With probability gamma: continue
else:
# Sample action from policy
action_probs = policy(current_state)
action = rng.choice(len(action_probs), p=action_probs)
# Sample next state from transition model
next_state_probs = transition_model(current_state, action)
current_state = rng.choice(n_states, p=next_state_probs)
return np.array(samples)
# Example usage for a simple 2-state MDP
alpha = np.array([0.7, 0.3]) # Initial distribution
policy = lambda s: np.array([0.8, 0.2]) # Dummy policy
transition_model = lambda s, a: np.array([0.9, 0.1]) # Dummy transitions
gamma = 0.9
samples = sample_from_discounted_visitation(alpha, policy, transition_model, gamma)
# Check empirical distribution
print("Empirical state distribution:")
print(np.bincount(samples) / len(samples))Empirical state distribution:
[0.867 0.133]
While the math shows that sampling from the discounted visitation distribution would give us unbiased policy gradient estimates, Thomas (2014) demonstrated that this implementation can be detrimental to performance in practice. The issue arises because terminating trajectories early (with probability ) reduces the effective amount of data we collect from each trajectory. This early termination weakens the learning signal, as many trajectories don’t reach meaningful terminal states or rewards.
Therefore, in practice, we typically sample complete trajectories from the undiscounted process (running the policy until natural termination or a fixed horizon) while still using in the advantage estimation. This approach preserves the full learning signal from each trajectory and has been empirically shown to lead to better performance.
This is one of several cases in RL where the theoretically optimal procedure differs from the best practical implementation.
The Actor-Critic Architecture¶
The policy gradient theorem shows that the gradient depends on the action-value function . In practice, we do not have access to the true -function and must estimate it. This leads to the actor-critic architecture: the actor maintains the policy , while the critic maintains an estimate of the value function.
This architecture traces back to Sutton’s 1984 thesis, where he proposed the Adaptive Heuristic Critic. The actor uses the critic’s value estimates to compute advantage estimates for the policy gradient, while the critic learns from the same trajectories generated by the actor. The algorithms we developed earlier (REINFORCE with baseline, GAE, and the one-step actor-critic) are all instances of this architecture.
We are simultaneously learning two functions that depend on each other, which creates a stability challenge. The actor’s gradient uses the critic’s estimates, but the critic is trained on data generated by the actor’s policy. If both change too quickly, the learning process can become unstable.
Konda (2002) analyzed this coupled learning problem and established convergence guarantees under a two-timescale condition: the critic must update faster than the actor. Intuitively, the critic needs to “track” the current policy’s value function before the actor uses those estimates to update. If the actor moves too fast, it uses stale or inaccurate value estimates, leading to poor gradient estimates.
In practice, this is implemented by using different learning rates: a larger learning rate for the critic and a smaller learning rate for the actor, with . Alternatively, one can perform multiple critic updates per actor update. The soft actor-critic algorithm discussed earlier in the amortization chapter follows this same principle, inheriting the actor-critic structure while incorporating entropy regularization and learning Q-functions directly.
The actor-critic architecture also connects to the bilevel optimization perspective of the policy gradient theorem: the outer problem optimizes the policy, while the inner problem solves for the value function given that policy. The two-timescale condition ensures that the inner problem is approximately solved before taking a step on the outer problem.
Reparameterization Methods in Reinforcement Learning¶
When actions and dynamics admit differentiable sampling paths, how does pathwise differentiation change the variance and model requirements of policy optimization?
When dynamics are known or can be learned, reparameterization provides an alternative to score function methods. By expressing actions and state transitions as deterministic functions of noise, we can backpropagate through trajectories to compute policy gradients with lower variance than score function estimators.
Stochastic Value Gradients¶
The reparameterization trick requires that we can express our random variable as a deterministic function of noise. In reinforcement learning, this applies naturally when we have a learned model of the dynamics. Consider a stochastic policy that we can reparameterize as where , and a dynamics model where represents environment stochasticity. Both transformations are deterministic given the noise variables.
With these reparameterizations, we can write an -step return as a differentiable function of the noise:
where and for . The objective becomes:
We can now apply the reparameterization gradient estimator:
This gradient can be computed by automatic differentiation through the sequence of policy and model evaluations. The computation requires backpropagating through steps of model rollouts, which becomes expensive for large but avoids the high variance of score function estimators.
The Stochastic Value Gradients (SVG) framework Heess et al., 2015 uses this approach while introducing a hybrid objective that combines model rollouts with value function bootstrapping:
The terminal value function approximates the value beyond horizon , allowing shorter rollouts while still capturing long-term value. This creates a spectrum of algorithms parameterized by .
SVG(0): Model-Free Reparameterization¶
When , the objective collapses to:
No model is required. We simply differentiate the critic with respect to actions sampled from the reparameterized policy. This is the approach used in DDPG Lillicrap et al., 2015 (with a deterministic policy where is absent) and SAC Haarnoja et al., 2018 (where produces the stochastic component). The gradient is:
This requires only that the critic be differentiable with respect to actions, not a learned dynamics model. All bias comes from errors in the value function approximation.
SVG(1) to SVG(): Model-Based Rollouts¶
For , we unroll a learned dynamics model for steps before bootstrapping with the critic. Consider SVG(1):
where is the next state predicted by the model. The gradient now flows through both the reward and the model transition. Increasing propagates reward information more directly through the model rollout, reducing reliance on the critic. However, model errors compound over the horizon. If the model is inaccurate, longer rollouts can degrade performance.
SVG(): Pure Model-Based Optimization¶
As , we eliminate the critic entirely:
This is pure model-based policy optimization, differentiating through the entire trajectory. Approaches like PILCO Deisenroth & Rasmussen, 2011 and Dreamer Hafner et al., 2019 operate in this regime. With an accurate model, this provides the most direct gradient signal. The tradeoff is computational: backpropagating through hundreds of time steps is expensive, and gradient magnitudes can explode or vanish over long horizons.
The choice of reflects a fundamental bias-variance tradeoff. Small relies on the critic for long-term value estimation, inheriting its approximation errors. Large relies on the model, accumulating its prediction errors. In practice, intermediate values like or often work well when combined with a reasonably accurate learned model.
Noise Inference for Off-Policy Learning¶
A subtle issue arises when combining reparameterization with experience replay. SVG naturally supports off-policy learning: states can be sampled from a replay buffer rather than the current policy. However, reparameterization requires the noise variables that generated each action.
For on-policy data, we can simply store alongside each transition . For off-policy data collected under a different policy, the noise is unknown. To apply reparameterization gradients to such data, we must infer the noise that would have produced the observed action under the current policy.
For invertible policies, this is straightforward. If with , and the policy takes the form (as in a Gaussian policy), we can recover the noise exactly:
This recovered can then be used for gradient computation. However, this introduces a subtle dependence: the inferred depends on the current policy parameters , not just the data. As the policy changes during training, the same action corresponds to different noise values.
For dynamics noise , the situation is more complex. If we have a probabilistic model and observe the actual next state , we could in principle infer . In practice, environment stochasticity is often treated as irreducible: we cannot replay the exact same noise realization. SVG handles this by either: (1) using deterministic models and ignoring environment stochasticity, (2) re-simulating from the model rather than using observed next states, or (3) using importance weighting to correct for the distribution mismatch.
The noise inference perspective connects reparameterization gradients to the broader question of credit assignment in RL. By explicitly tracking which noise realizations led to which outcomes, we can more precisely attribute value to policy parameters rather than to lucky or unlucky samples.
When dynamics are deterministic or can be accurately reparameterized, SVG-style methods offer an efficient alternative to the score function methods developed in the previous section. However, many reinforcement learning problems involve unknown dynamics or dynamics that resist accurate modeling. In those settings, score function methods remain the primary tool since they require only the ability to sample trajectories under the policy.
Summary¶
The trajectory score supplies a model-free policy gradient because the transition terms do not depend on the policy parameters. Conditional returns, state-dependent baselines, generalized advantage estimates, and learned critics reduce its variance. Importance ratios then compare data from an older policy with the current one, while PPO clips those ratios to limit the update.
The SwingRL experiment separated a correct PPO implementation from a successful control result. Five million total training interactions improved the shaped return but produced no full rotations. The structured controller solved the nominal rigid-link problem without policy training, then failed a different test because the resulting trajectory required a chain to push. Algorithm diagnostics, task success, and model validity therefore remain separate parts of the evaluation.
The policy-gradient theorem expresses the same derivative through discounted state visitation and action values. Approximating those values produces the actor-critic architecture, with a faster critic update supplying the signal used by the actor.
When dynamics models are available, reparameterization through stochastic value gradients supplies a lower-variance alternative. SVG(0) recovers actor-critic methods such as DDPG and SAC, while SVG() differentiates through a complete simulated trajectory. The resulting choice is now explicit: score methods trade variance for minimal model assumptions; pathwise methods trade stronger differentiability assumptions for lower-variance credit assignment.
Self-checks¶
Solution to Exercise 1
No. It differentiates the log probability of sampled actions under the policy and weights that score by sampled returns or advantages; the environment need only generate trajectories.
Solution to Exercise 2
Conditioned on a state, the expected policy score is zero: . Multiplying a state-only baseline by that score therefore has zero expectation.
- Williams, R. J. (1992). Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement Learning. Machine Learning, 8(3), 229–256. 10.1007/BF00992696
- Sutton, R. S., McAllester, D., Singh, S., & Mansour, Y. (1999). Policy Gradient Methods for Reinforcement Learning with Function Approximation. Advances in Neural Information Processing Systems, 12, 1057–1063.
- Konda, V. R. (2002). Actor-Critic Algorithms [Phdthesis]. Massachusetts Institute of Technology.
- Heess, N., Wayne, G., Silver, D., Lillicrap, T., Erez, T., & Tassa, Y. (2015). Learning Continuous Control Policies by Stochastic Value Gradients. Advances in Neural Information Processing Systems, 28, 2944–2952.
- Lillicrap, T. P., Hunt, J. J., Pritzel, A., Heess, N., Erez, T., Tassa, Y., Silver, D., & Wierstra, D. (2015). Continuous Control with Deep Reinforcement Learning. arXiv Preprint arXiv:1509.02971.
- Haarnoja, T., Zhou, A., Abbeel, P., & Levine, S. (2018). Soft actor-critic: Off-policy maximum entropy deep reinforcement learning with a stochastic actor. Proceedings of the 35th International Conference on Machine Learning (ICML), 1861–1870.
- Deisenroth, M. P., & Rasmussen, C. E. (2011). PILCO: A Model-Based and Data-Efficient Approach to Policy Search. Proceedings of the 28th International Conference on Machine Learning (ICML), 465–472.
- Hafner, D., Lillicrap, T., Ba, J., & Norouzi, M. (2019). Dream to Control: Learning Behaviors by Latent Imagination. arXiv Preprint arXiv:1912.01603.