Skip to content

5.3 Constraint Mechanisms for Policy Updates

Section Overview

Section 7.2 derived PPO's clipped surrogate objective:

This objective contains a policy ratio , a clipping operation, and an outer min. This section answers two questions: what does this formula protect, and why can we not simply use the vanilla policy gradient?

The line of reasoning is: the update risk of vanilla policy gradient → importance sampling for data reuse → TRPO's KL-divergence constraint → PPO's clipped approximation. The entire formula is driven by a single motive: constrain the magnitude of each update so that a single step cannot ruin the policy.

To keep the derivation concrete, this section uses a single running example throughout: a state with two actions , where the initial policy assigns and . The central question is: what happens if one update pushes to ?

Prerequisites for This Section

The Update Risk of Vanilla Policy Gradient

Recall the policy-gradient update from Chapter 5 (REINFORCE):

When the advantage (better than average), the parameters are updated in the direction that increases . The problem: there is no upper bound on the magnitude of this update.

Apply this to the running example. Suppose we sample with advantage and learning rate . A single update yields:

BeforeAfter
0.60.99
0.40.01

In one step, the probability of rises from 0.6 to 0.99. Yet this is the result of a single sample — if the high advantage was partly due to sampling variance, the policy has already compressed the alternative action's probability to 0.01. Policy updates are irreversible; there is no undo mechanism.

The next round is worse. Training data was collected under the old policy , but when we attempt to reuse the same batch, is already 0.99, far from the 0.6 at which it was sampled. The old data is stale.

The core dilemma of vanilla policy gradient is: single-step updates have high variance, yet policy updates are irreversible. One bad step renders the entire batch unusable.

If a single update can damage the policy, then before asking "how much to update," should we not first ensure that the operation of "training a new policy on old data" is itself safe?

Importance Sampling and Data Reuse

The first problem is data reuse. The sample was collected under . Can it be used to update a new policy where ?

Mathematically yes, via importance sampling. An expectation under one distribution can be rewritten in terms of another using a likelihood ratio:

This ratio is called the policy ratio — it measures the change in probability that the new policy assigns to the same relative to the old.

In the running example:

Policy
Old policy 0.6
New policy 0.99
1.65

The new policy makes 1.65× more likely. Incorporating this ratio into the policy gradient yields the importance-sampled objective:

In form, old data can now evaluate the new policy. But the value 1.65 also exposes a problem: the gradient is amplified 1.65×. If the policy pushes more aggressively to 0.999, then ; at 0.9999, . The larger becomes, the larger the next update, which in turn drives even higher — a positive feedback loop.

Importance sampling solves the data-reuse problem but provides no guarantee of safe usage.

Vanilla policy gradient exhibits update risk in a single step, and importance sampling allows to grow without bound. Can the requirement that "each update be bounded in magnitude" be formulated mathematically?

TRPO and a KL-Divergence Constraint

In 2015, Schulman et al. proposed TRPO (Trust Region Policy Optimization). Its core idea: constrain the distance between the old and new policies directly. The standard tool for measuring the difference between two probability distributions is KL divergence (Kullback-Leibler divergence), written here as a hard constraint:

This optimization problem has two parts: the left side is the objective to be maximized — the importance-sampled objective, pursuing higher cumulative advantage; the right side is the constraint that must be satisfied. "s.t." reads "subject to."

KL divergence measures the difference between two probability distributions, defined as:

When the two distributions are identical, ; the greater the difference, the larger (always non-negative). Here is the policy before the update and is the policy after, so measures how much a single update changes the policy distribution. The constraint requires this change to not exceed .

Returning to the running example. With and :

The result is approximately 1.18, far exceeding . TRPO would reject this update outright and pull the policy back inside the trust region.

is typically 0.01, meaning the policy's behavior distribution may change by at most 1% per update. This defines a trust region: the policy may move freely within it, but any update that crosses the boundary is rejected.

Elegant in theory, but difficult in practice. Solving this constrained optimization requires the Hessian matrix (second derivatives of the parameters). For a network with millions of parameters, the Hessian's dimension is the square of the parameter count and cannot fit in memory. In the LLM setting, the policy itself is a 70B-parameter language model; computing its Hessian is entirely infeasible. TRPO approximates the solution via conjugate gradient, but it remains slow and complex to implement. The cost of strict constraints is computational expense.

TRPO's constraint is so precise that the computational cost becomes prohibitive. Is there a method that is less strict than TRPO yet still effectively bounds the magnitude of each update?

PPO's Clipping Mechanism

In 2017, Schulman proposed PPO (Proximal Policy Optimization). The previous section noted that TRPO's difficulty is the cost of precisely computing KL divergence, which requires the Hessian matrix. PPO's key insight: since the goal is simply to keep the old and new policies "not too far apart," there is no need to measure the distance precisely — just bound the policy ratio directly.

Recall the definition of : . When , the new and old policies agree exactly on that action; the more deviates from 1, the larger the policy change. Therefore, constraining within is equivalent to limiting the probability change of each action — a local, inexpensive approximation of the goal "policy distance must not be too large," requiring neither KL computation nor the Hessian.

PPO's objective:

Using the 1.65 example from above (, ). With , compute each term:

Unclipped term: .

Clipped term: since , it exceeds the upper bound, so the clipping operation truncates to . The clipped term is then .

Take the minimum: .

TermComputationValue
Unclipped
Clipped
picks

Clipping compresses the larger objective value (3.30) down to 2.40. The objective becomes constant in this interval — its dependence on vanishes, and the policy is no longer encouraged to increase further.

The formula consists of three terms, each with a distinct role:

  • Unclipped term : the standard policy-gradient objective after importance sampling — the product of the policy ratio and the advantage.
  • Clipped term : constrains within . is typically 0.1 or 0.2, corresponding to a maximum change of 10% or 20% in policy probability.
  • Minimum : selects the more conservative of the two values.

Directionality of the Clipping Mechanism

The effect of clipping depends on the sign of the advantage , with the upper and lower bounds activating under different conditions:

When (a good action): the update direction should increase . Clipping imposes an upper bound of on — any value exceeding it is truncated. Even if a good action carries a high advantage, the policy probability cannot grow without bound in that direction.

When (a bad action): the update direction should decrease . Clipping imposes a lower bound of on , preventing the policy probability from being reduced excessively.

Mermaid diagram

As shown, is constrained by clipping only in the "advantage-consistent direction": the upper bound activates when , and the lower bound activates when . Once crosses the corresponding boundary, the gradient becomes zero and the update stops.

A question remains, however: what if crosses the boundary in the opposite direction — for instance, calls for increasing , yet has fallen below ? Can the clipping term handle this case on its own? This is precisely the reason the outer exists.

The Role of the Minimum

The clipping term has zero gradient at both ends. How can the outer guarantee that the overall objective has a non-zero gradient? More pointedly: picks one of two candidates — could it ever pick the zero-gradient clipped term and stall the policy?

No. always picks the numerically smaller of the two candidates, and the arithmetic structure of clip happens to make "smaller" equivalent to "gradient direction is correct". Verify case by case.

Fix (so should increase) and examine the two out-of-bounds cases.

Same-direction overshoot (). Clip truncates to :

TermExpressionValue (, , )
Unclipped (larger)
Clipped (smaller)

Since implies , picks the clipped term — gradient zero. As intended: a good action has already overshot the tolerance; the update stops.

Opposite-direction overshoot (). Clip truncates to :

TermExpressionValue (, , )
Unclipped (smaller)
Clipped (larger)

Since implies , picks the unclipped term. This term contains the true , so the chain rule gives a non-zero gradient pointing toward larger :

This is precisely the corrective signal that pulls the policy back into .

The two cases for (a bad action, so should decrease) are symmetric to the above — both values are negative, and "smaller" means larger in magnitude (heavier penalty).

Same-direction overshoot (). Clip truncates to :

TermExpressionValue (, , )
Unclipped (smaller magnitude)
Clipped (larger magnitude)

Multiplying both sides by the negative flips the inequality: implies , i.e. , so picks the clipped term — gradient zero. As intended: the bad action's probability has been reduced enough; the update stops.

Opposite-direction overshoot (). Clip truncates to :

TermExpressionValue (, , )
Unclipped (larger magnitude)
Clipped (smaller magnitude)

implies , i.e. , so picks the unclipped term — gradient non-zero, pointing toward smaller , pulling the policy back into the safe interval.

The four out-of-bounds cases:

positionMagnitude relation picksGradientDesign intent
unclipped clippedclipped valuezero (flat region)same-direction stop
unclipped clippedunclipped valuenonzero, increase opposite-direction correction
unclipped clippedclipped valuezero (flat region)same-direction stop
unclipped clippedunclipped valuenonzero, decrease opposite-direction correction
Formal proof that the gradient never reverses (optional)

The table above verifies the min's choice across four cases. Can we give a unified mathematical guarantee that does not depend on case analysis? Yes — and the proof is remarkably short.

Proposition: For any and , the PPO objective (where ) satisfies the following with respect to the partial derivative in :

Corollary: . That is, the gradient component is either zero or has the same sign as it never reverses.

Proof: By the derivative rule of min — pick the smaller of two terms, and its derivative equals that term's derivative. As a function of , has only three forms:

position

Determine which term equals, case by case:

  • : , the two terms are equal, , so .
  • : is constant.
    • : , min picks the clipped term (constant), so .
    • : multiplying by a negative flips the inequality, , min picks the unclipped term, so .
  • : is constant.
    • : , min picks the unclipped term, so .
    • : after the flip , min picks the clipped term (constant), so .

The five reachable cases (one inside the interval, two on each side) give . QED.

Geometric interpretation: As a function of , is a piecewise polyline whose slope takes only two values — or . Segments with slope (containing the true ) supply the corrective gradient; segments with slope (clip's flat regions) halt the update. The slope of the entire curve never takes the value this is precisely the geometric portrait of "the gradient never reverses".

By the chain rule , combined with ( is a positive constant):

  • When , points in the direction that increases — good actions are reinforced.
  • When , points in the direction that decreases — bad actions are suppressed.
  • When , the gradient is zero and the update stops — and this only occurs when the policy has overshot in the correct direction, where stopping is the design intent.

Every PPO update either stops, or moves in the direction indicated by the advantage — it never reverses, and it never stalls when correction is needed.

Across all four cases, consistently picks the more pessimistic (numerically smaller) candidate: same-direction overshoot makes clip cut the inflated reward, so the clipped value is more pessimistic; opposite-direction overshoot makes the unclipped value honestly expose that the reward really is low, so the unclipped value is more pessimistic. "More pessimistic" coincides exactly with "gradient direction is correct" — this is the intuition behind the formal proof above.

Replacing with flips the rule to "pick the more optimistic": same-direction overshoot would no longer be cut (encouraging further excursions), and opposite-direction overshoot would have its reward inflated (rewarding the wrong direction). Both cases fail. cannot be replaced by .

Visualizing the Clipping Mechanism

The following code illustrates the behavior of the clipped objective:

python
import numpy as np
import matplotlib.pyplot as plt

# ==========================================
# Visualize the PPO Clip objective
# ==========================================
epsilon = 0.2
r = np.linspace(0.0, 2.0, 500)  # policy ratio r_t(θ)

def ppo_clip_objective(r, A, eps=0.2):
    """PPO clipped objective: L = min(r * A, clip(r, 1-eps, 1+eps) * A)"""
    r_clipped = np.clip(r, 1 - eps, 1 + eps)
    return np.minimum(r * A, r_clipped * A)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))

# Case: A > 0
A_pos = 1.0
obj_pos = ppo_clip_objective(r, A_pos)
ax1.plot(r, r * A_pos, 'b--', alpha=0.5, label='Unclipped: r × A')
ax1.plot(r, obj_pos, 'r-', linewidth=2, label='PPO: min(r×A, clip(r)×A)')
ax1.axvline(x=1+epsilon, color='gray', linestyle=':', label=f'1+ε={1+epsilon}')
ax1.axvline(x=1-epsilon, color='gray', linestyle=':', label=f'1-ε={1-epsilon}')
ax1.set_title('A > 0 (good action)')
ax1.set_xlabel('Policy ratio r_t(θ)')
ax1.set_ylabel('Objective value')
ax1.legend()

# Case: A < 0
A_neg = -1.0
obj_neg = ppo_clip_objective(r, A_neg)
ax2.plot(r, r * A_neg, 'b--', alpha=0.5, label='Unclipped: r × A')
ax2.plot(r, obj_neg, 'r-', linewidth=2, label='PPO: min(r×A, clip(r)×A)')
ax2.axvline(x=1+epsilon, color='gray', linestyle=':', label=f'1+ε={1+epsilon}')
ax2.axvline(x=1-epsilon, color='gray', linestyle=':', label=f'1-ε={1-epsilon}')
ax2.set_title('A < 0 (bad action)')
ax2.set_xlabel('Policy ratio r_t(θ)')
ax2.legend()

plt.suptitle('Behavior of the PPO Clip objective (ε=0.2)', fontsize=14)
plt.tight_layout()
plt.savefig("ppo_clip_visualization.png", dpi=150)
print("Saved visualization of the clipped objective")

Running this code shows: when , the objective becomes flat once (the gradient goes to zero and the update stops); when , the objective becomes flat once . This is the core effect of PPO clipping — once the policy ratio leaves the safe interval, the gradient automatically vanishes.

Sensitivity to

The choice of directly affects training dynamics. The table below summarizes practical experience:

ε valueUpdate sizeTraining speedStabilityTypical use case
0.05very smallvery slowextremely stablefine-tuning an already trained policy
0.1smallslowerstableLLM alignment (large models are fragile)
0.2mediummoderatemoderategames/control tasks (a common default)
0.3largerfasterunstablequick experiments/simple tasks
0.5very largefast but often collapsesvery unstablenot recommended

In LLM alignment, a smaller (around 0.1 or less) is commonly used, because the policy space of a language model is larger and more brittle: a single poorly controlled update can degrade the model's general language ability (for instance, losing an already acquired language).

Question: If PPO clipping makes training "too conservative," can we speed it up without sacrificing stability?

Several common strategies are used in practice:

  1. Adaptive ε: PPO-PPG (Phasic Policy Gradient) suggests using a larger ε early in training and gradually shrinking it later, like “take big steps to explore first, then take small steps to refine.”
  2. More update epochs per batch: PPO commonly performs multiple epochs (often 10) over the same batch of data. If clipping makes each step small, increasing the number of epochs can accumulate a meaningful overall update.
  3. Early stopping based on KL divergence: monitor the KL divergence during optimization, and stop early if KL exceeds a threshold within an epoch. This effectively combines the TRPO idea (a KL constraint) with PPO’s clipping.

In practice, the second approach is the most common. PPO’s default n_epochs=10 is already motivated by the idea that clipping limits per-step movement, so multiple passes are used to accumulate sufficient progress.

Question: TRPO is more theoretically principled. Why does industry almost always choose PPO?

Because in engineering practice, “simple and reliable” usually beats “theoretically perfect.”

TRPO requires second-order machinery (Hessian-vector products). On large models this is slow, complex to implement, and easy to get wrong. PPO, in contrast, can be implemented with a simple torch.clamp and a min, often in under ten lines of code.

The PPO paper (2017) also shows empirically that PPO matches TRPO and often performs as well or better across many tasks. One reason is that TRPO’s own second-order approximations introduce error; solving the constrained problem precisely does not necessarily outperform PPO’s simple heuristic clipping.

This tradeoff becomes even clearer in the LLM era. For a 70B-parameter policy, second-order optimization is simply not practical. OpenAI’s alignment training in InstructGPT and GPT-4 uses PPO rather than TRPO for exactly these reasons.

This completes the derivation of PPO's clipping mechanism: from the update risk of vanilla policy gradient, to data reuse via importance sampling, to TRPO's KL constraint, and finally to PPO's clipped approximation. But PPO has another key component not covered here: GAE (Generalized Advantage Estimation), and the major burden it introduces in LLM alignment — the reward model. See Advantage Estimation and Reward Modeling.

现代强化学习实战课程