PPO: clip a surrogate, not the policy itself
PPO
Differentiate clipping branches and inspect frozen old probabilities, advantages and KL stopping with sampled updates.
ppoWhy can probabilities escape a flattened objective?
An old policy gives an action probability 0.5. With PPO-Clip epsilon=0.2, must the next probability lie between 0.4 and 0.6? No. Clipping occurs inside the optimized surrogate; it does not project the new probability back into an interval. A sufficiently large gradient step can overshoot. With shared parameters, other samples can also keep moving this action’s probability. PPO clipping objective
PPO collects data under an old policy and uses that batch for multiple optimization steps. It retains probability ratios while flattening contributions that have already moved too far in a favorable direction. Advantage signs matter: this is not simply replacing every ratio with its clipped value.
The minimum determines which direction stops earning credit
For an old-policy record, a is the sampled action and s the state. Theta0, its old log probability and advantage A stay fixed during this round of optimization. The ratio is:
Old probability must be positive on the sampled action. Let clip restrict a number to[1−epsilon,1+epsilon]. PPO-Clip maximizes the batch-average surrogate:
The minimum makes each contribution no greater than its unclipped rA. This lower-bound relation concerns the unclipped surrogate, not arbitrary true return. Multi-step objectives also require explicit state-sampling, discount and advantage conventions; the program uses a one-step task to keep those approximations out of its loop. Original Eq. 7
Writing one contribution as ell and resolving the sign of A gives:
Positive advantage favors higher action probability, so exceeding the upper ratio flattens the contribution; decreasing probability still hurts. Negative advantage favors lower probability, so going below the lower ratio flattens the contribution; increasing that probability remains penalized. For A=−2, ratio 1.3 and epsilon 0.2, the contribution is min(−2.6,−2.4)=−2.6, not−2.4.
Away from a kink, the unflattened branch differentiates through the ratio; the flattened branch contributes zero sample gradient:
At a kink the function need not be differentiable. The program chooses the slope from the unclipped side and checks finite differences away from kinks. Zero advantage always contributes zero. Entropy bonuses, value losses and shared networks can be added separately; they are not automatically part of this clipping term. The referenced Spinning Up policy loss does not add entropy, although entropy is logged. Implementation check
Take a Bernoulli logit theta with old theta0=0 and a batch containing just action 1 with advantage 1. Its score is 0.5. One step with learning rate 10 gives:
The gradient was computed at the old point before entering the flat region. The update does not automatically stop at the boundary. A subsequently zero sample gradient also does not restore the overshot parameters.
KL stopping is an additional check. We can calculate exact old||new KL here; a common sample estimate averages old-data log-probability differences:
True KL is nonnegative, but a finite-sample estimate can be negative. Checking before each gradient step and stopping when over the limit preserves any overshoot from the preceding step. Restoring parameters requires a separate rollback or line search; stopping alone is not a hard guarantee.
Keep one denominator throughout a batch
The standard-library program uses a one-step Bernoulli bandit whose reward equals its action. Each cycle samples 64 records, stores old log probabilities and advantages, and performs at most 10 updates. It runs 30 cycles for seeds 0–7. To isolate policy optimization, the baseline is the known old value p_old rather than a trained critic. There is no advantage normalization, entropy bonus or value loss.
"""PPO-Clip on a sampled Bernoulli bandit with a fixed old-policy batch.
Known value p_old supplies the baseline, isolating the policy update mechanics.
Exact KL stopping is a teaching convenience; an overshoot is not rolled back.
"""
import json
import math
import random
def sigmoid(x):
if not math.isfinite(x):
raise ValueError('finite logit required')
return 1/(1+math.exp(-x)) if x >= 0 else math.exp(x)/(1+math.exp(x))
def softplus(x):
return max(x, 0.)+math.log1p(math.exp(-abs(x)))
def log_probability(theta, action):
if action not in (0, 1):
raise ValueError('binary action required')
sigmoid(theta)
return -softplus(-theta) if action else -softplus(theta)
def clipped_term(ratio, advantage, epsilon=0.2):
if not math.isfinite(ratio) or ratio < 0 or not math.isfinite(advantage) or not 0 < epsilon < 1:
raise ValueError('finite nonnegative ratio, finite advantage and epsilon in (0,1) required')
clipped = max(1-epsilon, min(1+epsilon, ratio))
return min(ratio*advantage, clipped*advantage)
def objective_gradient(theta, rows, epsilon=0.2):
"""Rows are (action, old log-probability, fixed advantage).
At the clipping kink this chooses the slope from the unclipped side.
It does not differentiate through the old policy or the advantage.
"""
if not rows:
raise ValueError('nonempty on-policy batch required')
p, total, grad = sigmoid(theta), 0., 0.
for action, old_logp, advantage in rows:
if not math.isfinite(old_logp) or old_logp > 0:
raise ValueError('finite nonpositive old log-probability required')
ratio = math.exp(log_probability(theta, action)-old_logp)
total += clipped_term(ratio, advantage, epsilon)
flat = (advantage > 0 and ratio > 1+epsilon) or (advantage < 0 and ratio < 1-epsilon)
if not flat:
grad += advantage*ratio*(action-p)
return total/len(rows), grad/len(rows)
def collect(theta, rng, size=64):
if size < 1:
raise ValueError('positive batch size required')
p = sigmoid(theta)
return tuple((action, log_probability(theta, action), action-p)
for action in (int(rng.random() < p) for _ in range(size)))
def old_new_kl(old, new):
p = sigmoid(old)
sigmoid(new)
return softplus(new)-softplus(old)-p*(new-old)
def update(old, rows, epochs=10, lr=1., epsilon=0.2, target_kl=0.02):
if epochs < 0 or not math.isfinite(lr) or lr <= 0 or not math.isfinite(target_kl) or target_kl <= 0:
raise ValueError('nonnegative epochs, positive finite learning rate and KL target required')
if any(abs(log_probability(old, a)-lp) > 1e-12 for a, lp, _ in rows):
raise ValueError('batch old probabilities do not match the old policy')
theta, steps = old, 0
for _ in range(epochs):
if old_new_kl(old, theta) > target_kl:
break
_, grad = objective_gradient(theta, rows, epsilon)
theta += lr*grad
steps += 1
ratios = [math.exp(log_probability(theta, a)-lp) for a, lp, _ in rows]
return theta, {'steps': steps, 'kl': old_new_kl(old, theta),
'min_ratio': min(ratios), 'max_ratio': max(ratios)}
def train(seed=0, cycles=30):
if cycles < 0:
raise ValueError('nonnegative cycles required')
rng, theta, history = random.Random(seed), 0., []
for _ in range(cycles):
old = theta
rows = collect(old, rng)
theta, report = update(old, rows)
history.append(report)
return {'seed': seed, 'return': sigmoid(theta), 'logit': theta,
'overshoot_cycles': sum(row['kl'] > 0.02 for row in history),
'last_batch': history[-1] if history else None}
def main():
runs = [train(seed) for seed in range(8)]
theta, overshoot = update(0., ((1, -math.log(2.), 1.),), lr=10., epochs=10)
print(json.dumps({'initial_return': 0.5, 'runs': runs,
'failures_below_0_9': [r['seed'] for r in runs if r['return'] < 0.9],
'one_step_overshoot': dict(overshoot, logit=theta),
'sign_cases': {str(a): [clipped_term(r, a) for r in (0.7, 1., 1.3)]
for a in (-2., 0., 2.)}}, indent=2))
if __name__ == '__main__':
main()
Inspect the complete recorded output
{
"initial_return": 0.5,
"runs": [
{
"seed": 0,
"return": 0.9964716411358783,
"logit": 5.6433878289522355,
"overshoot_cycles": 3,
"last_batch": {
"steps": 10,
"kl": 2.7258552186271157e-11,
"min_ratio": 1.000000439368481,
"max_ratio": 1.000000439368481
}
},
{
"seed": 1,
"return": 0.9956734693608243,
"logit": 5.438653379039499,
"overshoot_cycles": 3,
"last_batch": {
"steps": 10,
"kl": 4.994611281772254e-05,
"min_ratio": 0.8655111287152788,
"max_ratio": 1.0006756625972426
}
},
{
"seed": 2,
"return": 0.9936943811025546,
"logit": 5.059988571315741,
"overshoot_cycles": 3,
"last_batch": {
"steps": 10,
"kl": 4.960305140808488e-10,
"min_ratio": 1.0000025092051383,
"max_ratio": 1.0000025092051383
}
},
{
"seed": 3,
"return": 0.9957363864207287,
"logit": 5.453365491525722,
"overshoot_cycles": 3,
"last_batch": {
"steps": 10,
"kl": 7.0194525701988e-11,
"min_ratio": 1.0000007753450673,
"max_ratio": 1.0000007753450673
}
},
{
"seed": 4,
"return": 0.995073253087848,
"logit": 5.308137440935634,
"overshoot_cycles": 3,
"last_batch": {
"steps": 10,
"kl": 1.4455078166343213e-10,
"min_ratio": 1.0000011964550048,
"max_ratio": 1.0000011964550048
}
},
{
"seed": 5,
"return": 0.9932530560948812,
"logit": 4.9918958239908475,
"overshoot_cycles": 3,
"last_batch": {
"steps": 10,
"kl": 6.955139691716856e-10,
"min_ratio": 1.0000030741523886,
"max_ratio": 1.0000030741523886
}
},
{
"seed": 6,
"return": 0.996168766307803,
"logit": 5.56072982314422,
"overshoot_cycles": 3,
"last_batch": {
"steps": 10,
"kl": 4.113652365793363e-11,
"min_ratio": 1.000000562530886,
"max_ratio": 1.000000562530886
}
},
{
"seed": 7,
"return": 0.9941583395906533,
"logit": 5.136881416234481,
"overshoot_cycles": 3,
"last_batch": {
"steps": 10,
"kl": 3.3858083909243594e-10,
"min_ratio": 1.0000019948578016,
"max_ratio": 1.0000019948578016
}
}
],
"failures_below_0_9": [],
"one_step_overshoot": {
"steps": 1,
"kl": 1.8135681679291729,
"min_ratio": 1.9866142981514303,
"max_ratio": 1.9866142981514303,
"logit": 5.0
},
"sign_cases": {
"-2.0": [
-1.6,
-2.0,
-2.6
],
"0.0": [
0.0,
0.0,
0.0
],
"2.0": [
1.4,
2.0,
2.4
]
}
}Normal training uses learning rate 1 and exact-KL stopping threshold 0.02. Checks happen before the next update, without rollback. Eight final expected returns are approximately 0.9933–0.9965, all above the preset 0.9 check threshold. Output retains each seed’s number of overshoot cycles. The separate rate 10 counterexample stops after one update yet keeps theta=5, ratio about 1.9866 and KL about 1.8136.
Only new data collection refreshes the old policy. Recomputing the old denominator every optimization epoch would keep resetting ratios toward 1 while the data still came from the original policy. With one scalar parameter, B samples and K updates cost O(KB) time and O(B) batch space. Multi-parameter networks add forward, backward and optimizer-state costs. Minibatching, epoch counts and KL-estimation choices should be recorded.
Clipping leaves several policy-optimization problems open
Clipping alters part of a sample surrogate’s gradient. It does not guarantee ratio, KL or true-return bounds. Uncovered state-action pairs have no corresponding sample constraint, wrong advantages can label harmful actions as favorable, and shared parameters allow other samples to move an action even when its own contribution is flat.
The true baseline is easy to obtain in this one-step task. Multi-step PPO commonly uses a value network and GAE, requiring separate treatment of critic error, fragment boundaries and training objectives. The PPO paper also proposes adaptive KL penalties, distinct from PPO-Clip. Implementations named PPO need not share the same loss and update procedure. Two variants
Calculate the contribution before judging its gradient
- With advantage 2, ratio 1.3 and epsilon 0.2, what are the contribution and local gradient? Answer: The contribution is 2.4 and the sample gradient is zero away from the kink: its favorable-direction threshold has been exceeded. Other samples can still update shared parameters.
- With advantage−2 and ratios 0.7,1,1.3, what are the contributions? Answer: −1.6,−2,−2.6. A favorable decrease below the lower threshold is flattened; increasing the harmful action’s probability remains penalized.
- What changes if old log probabilities are replaced after every epoch? Answer: The denominator’s reference moves and ratios keep returning toward 1, although the data came from the original policy. The fixed-batch surrogate and clipping interpretation no longer apply.
- Does a negative approximate KL in a training log prove an implementation error? Answer: Not alone. True KL is nonnegative, but a finite old-sample mean of log differences can be negative. Inspect sampling distribution, direction, sample size and frozen old probabilities. When exact summation is available, compare against true KL.
Check version identity and formula indices
PPO first appeared 2017-07-20. This reading uses arXiv v2 dated 2017-08-28, PDF 1–5, with 3/5 viewed. On PDF 5, the last reward/residual exponents in Eqs. 10/11 are printed as T−t+1. Expanding through indexT−1 gives T−t−1; the bootstrap exponent T−t remains correct. Our GAE example independently checks finite sums against recurrence rather than copying that typo. Later performance tables and benchmarks were not reproduced. Original method
Spinning Up commit 038665d, PPO documentation 1–139 and PyTorch code 1–86,224–289,302–328 support the buffer, frozen-probability and stopping discussion. Its sampled approximate KL differs from our exactly enumerable KL. No upstream code was executed or copied. Implementation reference
Make a prediction, then check
With epsilon=0.2, advantage=-2 and ratio=1.3, what is the clipped contribution?
Learning objectives
- Compute the clipped surrogate and gradient for either advantage sign, separating favorable and harmful directions.
- Freeze old probabilities and advantages within a batch and explain why stopping does not undo an earlier overshoot.
Prerequisites & connections
Explore related knowledge →References
- Proximal Policy Optimization Algorithms — arXiv v2 methods
John Schulman; Filip Wolski; Prafulla Dhariwal; Alec Radford; Oleg Klimov · 2017 - Spinning Up — scoped PPO documentation and PyTorch buffer/update
OpenAI; Joshua Achiam and contributors · 2020
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-23 · Single AI author. Scoped reading: First2017-07-20, v2 dated2017-08-28. Read PDF1–5, viewed3/5. Clipping bounds the surrogate, not ratios. Printed last-term exponents in PDF5 Eqs10/11 corrected to T-t-1 by finite expansion; no benchmark replication. Read docs1–139; PyTorch ppo.py1–86,224–289,302–328. GAE, fixed old logp and early stopping; sample KL may be negative, stopping does not roll back, normalization lacks a zero-variance guard. MIT reference, no upstream execution or copying. 6 paired equations and four explained exercises. Both advantage-sign branches checked by finite differences away from kinks; frozen old log probabilities/advantages, sampled bandit cycles and all eight seeds retained. One large update overshoots ratio and KL despite stopping; finite-sample approximate KL can be negative. Exact known baseline and no entropy/value loss clearly scoped.
- Both advantage-sign branches checked by finite differences away from kinks; frozen old log probabilities/advantages, sampled bandit cycles and all eight seeds retained. One large update overshoots ratio and KL despite stopping; finite-sample approximate KL can be negative. Exact known baseline and no entropy/value loss clearly scoped.
- Four computed SVG variants per topic;16 numeric/geometry tests and36 current responsive cases passed. All twelve selected current captures directly viewed. Three groups retain initial captures; three use their actually viewed revised captures. Actual assets and manuscripts are SHA bound. Full article acceptance recorded separately.
Source locations checked:
- Proximal Policy Optimization Algorithms — arXiv v2 methods · First2017-07-20, v2 dated2017-08-28. Read PDF1–5, viewed3/5. Clipping bounds the surrogate, not ratios. Printed last-term exponents in PDF5 Eqs10/11 corrected to T-t-1 by finite expansion; no benchmark replication.
- Spinning Up — scoped PPO documentation and PyTorch buffer/update · Read docs1–139; PyTorch ppo.py1–86,224–289,302–328. GAE, fixed old logp and early stopping; sample KL may be negative, stopping does not roll back, normalization lacks a zero-variance guard. MIT reference, no upstream execution or copying.
Related topics