In the landscape we saw that most disagreements between labs are about which tokens get zero weight. This lesson is about that question. A token’s ratio in a modern RL stack hides three gaps, and it helps to name the three distributions involved:
is the behaviour policy that actually sampled the token (the inference engine, possibly several versions old); is the proximal policy against which the trust region is measured (classically the trainer’s recompute ); is the policy being updated. Clip rules act on , importance corrections act on , and some methods act on the product. The mismatch lesson derived the statistics of ; here we look at what each rule does to the gradient.
One function per rule: w(ρ, sign Â)
Every rule in this lesson can be written as a multiplier on (the regulariser and aggregation are set aside). For the PPO clipped surrogate, differentiating gives
Read the second one carefully: for a negative advantage, PPO switches the gradient off only when the ratio has fallen too low. If a bad token’s probability has risen — , which happens with stale data or when another update pushed it up — the multiplier is itself and grows without bound. The clip’s “pessimistic minimum” chooses the unclipped branch there, because it is the more negative one. Dual-clip PPO (Ye et al. 2020) adds a floor with for (they used , ), which turns the weight off above . MAI-Thinking-1’s outer clip on every branch plays the same role; its report added it after stale rollouts produced ratios in the tens and the , large- branch caused gradient-norm spikes (from the MAI review).
The other rules, in the same notation:
| Rule | Gradient ever exactly 0? | ||
|---|---|---|---|
| PPO | yes, unbounded for | ||
| Clip-higher (DAPO) | , | as PPO | yes |
| Dual-clip | as PPO | yes, bounded | |
| CISPO (MiniMax-M1) | never | ||
| SAPO (Qwen) | same with | never (smooth decay) | |
| DPPO-TV | unless and | unless and | yes, depends on |
| Log-ratio mask (Kimi K2.5) | same | yes, regardless of sign |
지도 레슨에서 랩 사이 이견의 대부분이 어떤 토큰의 가중치를 0으로 만드느냐에 관한 것임을 봤다. 이 레슨이 그 질문을 다룬다. 요즘 RL 스택에서 토큰의 ratio에는 세 가지 차이가 숨어 있고, 관련된 세 분포에 이름을 붙이면 도움이 된다.
는 토큰을 실제로 샘플한 행동(behaviour) 정책(추론 엔진, 몇 버전 전일 수도 있다), 는 trust region을 재는 기준인 근접(proximal) 정책(고전적으로는 학습기가 다시 계산한 ), 는 업데이트 중인 정책이다. Clip 규칙은 에, importance 보정은 에 작용하고, 둘의 곱에 작용하는 방법도 있다. 불일치 레슨이 의 통계를 유도했다. 여기서는 각 규칙이 gradient에 무엇을 하는지 본다.
규칙마다 함수 하나: w(ρ, sign Â)
이 레슨의 모든 규칙은 에 곱하는 인자 로 쓸 수 있다(정규화 항과 집계는 제쳐 둔다). PPO clipped surrogate 를 미분하면
두 번째 식을 주의해서 읽자. 음의 advantage에서 PPO는 ratio가 너무 낮아졌을 때만 gradient를 끈다. 나쁜 토큰의 확률이 올라갔다면 — 오래된 데이터나 다른 업데이트가 그것을 밀어 올린 경우, — 인자는 자신이고 끝없이 커진다. Clip의 “비관적 최솟값”이 거기서는 clip되지 않은 가지를 고르기 때문이다(더 음수이므로). Dual-clip PPO(Ye et al. 2020)는 에 바닥 ()를 더해 위에서 가중치를 끈다(그들은 , 를 썼다). MAI-Thinking-1이 모든 가지에 건 바깥 clip 이 같은 역할이다. 오래된 rollout에서 ratio가 수십에 이르고 ·큰 가지가 gradient-norm 급등을 일으킨 뒤에 추가했다고 보고서는 적는다(MAI 리뷰에서).
같은 표기로 쓴 다른 규칙들:
| 규칙 | gradient가 정확히 0이 되나? | ||
|---|---|---|---|
| PPO | 예, 쪽은 무한히 큼 | ||
| Clip-higher (DAPO) | , | PPO와 같음 | 예 |
| Dual-clip | PPO와 같음 | 예, 유계 | |
| CISPO (MiniMax-M1) | 결코 아님 | ||
| SAPO (Qwen) | 로 같은 꼴 | 아님(부드럽게 감소) | |
| DPPO-TV | 이고 가 아니면 | 이고 가 아니면 | 예, 에 달림 |
| Log-ratio mask (Kimi K2.5) | 같음 | 예, 부호와 무관 |
- Uncheck everything except PPO. On the right () the curve keeps rising: the most stale, most wrong tokens get the largest push. Turn on dual-clip and move c.
- Raise policy drift. The readout “Â<0 w>3” counts the tokens whose multiplier exceeds 3. Under PPO it grows; dual-clip and DPPO keep it near 0; CISPO caps it at by construction.
- Compare PPO and clip-higher on the left: raising moves the cut-off right and recovers the positive-advantage tokens that moved most. Those are mostly low-probability tokens, because a logit shift of the same size changes a small probability by a much larger factor. That is why clip-higher counters entropy collapse (the regularisation lesson derives the covariance argument).
- DPPO with cuts off at (TV ); drag to 0.01 and the cut-off moves to . The ratio is a poor distance for rare tokens: the DPPO paper’s example is a token going from to , and clipped by PPO although only 0.01 of probability mass moved, while gives , passes the clip, and moves 0.19 of mass.
CISPO and the rare-token problem
MiniMax motivated CISPO with an observation about reasoning traces: tokens such as “However”, “Wait” or “Recheck” are rare under the policy, so after the first update their ratio rises fastest, they hit the clip, and they stop contributing for the remaining off-policy updates on the same batch (M1 ran 16 such updates per generation batch). CISPO keeps the PPO-style cap on the weight — — but never removes the token. The cost is that the trust region is gone: nothing stops the update except the weight cap and the learning rate. The DPPO paper reports that CISPO-style unclipped training collapsed on an MoE base model without routing replay, and that the main source of instability was a small fraction (at most about 0.5%) of updates that cut a token’s probability by more than half on negative samples — exactly the , large-movement corner of the plot.
The block below isolates the effect: one context, twenty tokens, the only rewarded one starting at probability 0.01, eight passes over each sampled batch.
import numpy as np
rng = np.random.default_rng(0)
K = 20
softmax = lambda z: np.exp(z - z.max(-1, keepdims=True)) / np.exp(z - z.max(-1, keepdims=True)).sum(-1, keepdims=True)
reward = np.zeros(K); reward[0] = 1.0 # token 0 is the rare good token
def weight(rule, rho, A, p_old, eps_low=0.2, eps_high=0.28):
"""multiplier on A·∇log π for each sampled token (the per-token weight / A)."""
if rule == "PPO 0.2/0.2": return np.where(A >= 0, rho <= 1.2, rho >= 0.8) * rho
if rule == "clip-higher": return np.where(A >= 0, rho <= 1 + eps_high, rho >= 1 - eps_low) * rho
if rule == "CISPO (cap 2)": return np.minimum(rho, 2.0)
if rule == "DPPO-TV δ=0.2": # mask only when the move goes further out and |Δπ| > δ
tv = p_old * np.abs(rho - 1)
out = np.where(A >= 0, rho > 1, rho < 1) & (tv > 0.2)
return (~out) * rho
if rule == "no clip": return rho
def run(rule, iters=12, B=1024, epochs=8, lr=4.0):
z = np.zeros(K); z[0] = -1.65 # π(good) ≈ 0.01
hist = []
for it in range(iters):
pi_old = softmax(z)
y = rng.choice(K, size=B, p=pi_old).astype(np.intp)
A = reward[y] - reward[y].mean()
for _ in range(epochs): # several minibatch passes on one batch
pi = softmax(z)
rho = pi[y] / pi_old[y]
w = weight(rule, rho, A, pi_old[y]) * A
g = (w[:, None] * (np.eye(K)[y] - pi)).mean(0)
z = z + lr * g
pi = softmax(z)
kl = np.sum(pi_old * np.log(pi_old / pi))
hist.append((softmax(z)[0], kl))
return hist
print("π(good token) after iterations 1, 3, 6, 12 (8 passes per batch) | max KL(π_old‖π) per iteration")
for rule in ["PPO 0.2/0.2", "clip-higher", "CISPO (cap 2)", "DPPO-TV δ=0.2", "no clip"]:
h = run(rule)
print(f" {rule:14s}", " ".join(f"{h[i][0]:.3f}" for i in [0, 2, 5, 11]), f"| {max(k for _, k in h):.3f}")PPO and clip-higher take the good token from 0.01 to only 0.04–0.06 in six iterations; CISPO and DPPO reach 0.97 or more. The last column is the price: the largest per-iteration is about 0.12 for the clipped rules and 0.8–1.5 for the others. Clip-higher buys a little speed at no KL cost; CISPO and DPPO buy a lot by letting the step grow. Which side of this trade you want depends on whether your instability comes from moving too slowly on rare useful tokens or too fast on rare harmful ones.
Three policies: decoupled PPO and the bypass mode
Return to the three distributions at the top. Hilton, Cobbe and Schulman (2021) pointed out that PPO conflates two roles of : the behaviour policy that importance sampling must correct for, and the proximal policy that the trust region should be measured against. Decoupling them gives
with the first factor held constant. This is the structure behind most of the table: Olmo 3 truncates the behaviour factor to (TIS) with the trainer’s recompute; Nemotron’s asynchronous distillation stage writes it with ; AReaL uses it to absorb staleness. The async lesson covers the staleness side.
The bypass mode sets : skip the recompute, use the rollout engine’s log-probs as the denominator, and clip or mask the single ratio . GLM-5’s asynchronous agentic stage (a double-sided band on ) and MiMo-V2.6 do this, and DPPO argues for it on principle: its experiments found that a trust region measured against the recomputed distribution still collapsed, the anchor must be the rollout distribution, and skipping the recompute saves about a quarter of the step’s cost. The price is that one ratio now carries the update, staleness and engine noise together, so its band must be tight enough for the sum of all three — GLM-5’s report says so explicitly.
Correcting the engine gap: TIS, MIS, IcePop, CIS
The behaviour factor is where engine mismatch enters. Four rules dominate:
- TIS (Yao, Liu et al. 2025): multiply by . Every token is kept; large weights are truncated, which biases the estimate downward on the tokens with . Olmo 3 uses .
- Token MIS (Liu, Li et al. 2025): — drop instead of truncate.
- IcePop (Ling Team 2025): , two-sided, in the paper, where the masked tokens were 1–2‰ of training tokens and had higher entropy than average. GLM-5 uses in its reasoning RL; the IcePop paper itself reports as unstable in its own sensitivity study, so the right band is setup-dependent.
- CIS (Yu et al. 2026): starting from with the trainer probability and the logit gap between engines, it caps at (, ), a cap that tightens as the token gets more confident. Its ablation found that a two-sided band raising small weights collapsed training.
The identity tells you where to look before choosing: the mismatch lives on low-probability tokens.
- PPO만 남기고 모두 끄자. 오른쪽() 곡선이 계속 오른다. 가장 오래되고 가장 틀린 토큰이 가장 세게 밀린다. dual-clip을 켜고 c를 움직여 보라.
- 정책 이동을 올려라. “Â<0 w>3” 값은 인자가 3을 넘는 토큰을 센다. PPO에서는 늘어나고, dual-clip과 DPPO는 0 근처에 두며, CISPO는 구조상 에서 막는다.
- 왼쪽에서 PPO와 clip-higher를 비교하라. 를 올리면 차단점이 오른쪽으로 가서 가장 많이 움직인 양의 advantage 토큰을 되찾는다. 이들은 대부분 확률이 낮은 토큰이다. 같은 크기의 logit 이동이 작은 확률을 훨씬 큰 배수로 바꾸기 때문이다. 그래서 clip-higher가 엔트로피 붕괴에 맞선다(공분산 논증은 정규화 레슨에서 유도한다).
- 에서 DPPO는 에서 끊는다(TV ). 를 0.01로 끌면 차단점이 로 간다. 드문 토큰에게 ratio는 나쁜 거리다. DPPO 논문의 예에서 에서 로 간 토큰은 으로 PPO에 clip되지만 확률 질량은 0.01만 움직였고, 은 로 clip을 통과하지만 질량 0.19를 옮긴다.
CISPO와 드문 토큰 문제
MiniMax는 추론 궤적에 대한 관찰로 CISPO를 동기화했다. “However”, “Wait”, “Recheck” 같은 토큰은 정책 아래 드물어서 첫 업데이트 뒤 ratio가 가장 빨리 오르고, clip에 걸려 같은 배치의 남은 off-policy 업데이트에서 기여를 멈춘다(M1은 생성 배치마다 그런 업데이트를 16번 했다). CISPO는 PPO식 상한을 가중치에 남기되 — — 토큰을 결코 지우지 않는다. 대가는 trust region이 사라진다는 것이다. 가중치 상한과 학습률 말고는 업데이트를 막는 것이 없다. DPPO 논문은 routing replay 없는 MoE base 모델에서 CISPO식 clip 없는 학습이 붕괴했고, 불안정의 주원인이 음의 샘플에서 토큰 확률을 절반 넘게 깎은 소수(많아야 약 0.5%)의 업데이트였다고 보고한다. 그림의 ·큰 이동 구석이다.
아래 블록이 그 효과를 떼어 본다. 문맥 하나, 토큰 스무 개, 보상받는 토큰 하나는 확률 0.01에서 시작하고, 샘플한 배치마다 여덟 번 지나간다.
import numpy as np
rng = np.random.default_rng(0)
K = 20
softmax = lambda z: np.exp(z - z.max(-1, keepdims=True)) / np.exp(z - z.max(-1, keepdims=True)).sum(-1, keepdims=True)
reward = np.zeros(K); reward[0] = 1.0 # 토큰 0이 드문 좋은 토큰
def weight(rule, rho, A, p_old, eps_low=0.2, eps_high=0.28):
"""샘플 토큰마다 A·∇log π에 곱하는 인자(토큰당 가중치 / A)."""
if rule == "PPO 0.2/0.2": return np.where(A >= 0, rho <= 1.2, rho >= 0.8) * rho
if rule == "clip-higher": return np.where(A >= 0, rho <= 1 + eps_high, rho >= 1 - eps_low) * rho
if rule == "CISPO (cap 2)": return np.minimum(rho, 2.0)
if rule == "DPPO-TV δ=0.2": # 바깥으로 더 나가는 이동이고 |Δπ| > δ일 때만 mask
tv = p_old * np.abs(rho - 1)
out = np.where(A >= 0, rho > 1, rho < 1) & (tv > 0.2)
return (~out) * rho
if rule == "no clip": return rho
def run(rule, iters=12, B=1024, epochs=8, lr=4.0):
z = np.zeros(K); z[0] = -1.65 # π(good) ≈ 0.01
hist = []
for it in range(iters):
pi_old = softmax(z)
y = rng.choice(K, size=B, p=pi_old).astype(np.intp)
A = reward[y] - reward[y].mean()
for _ in range(epochs): # 한 배치에 여러 번의 minibatch 패스
pi = softmax(z)
rho = pi[y] / pi_old[y]
w = weight(rule, rho, A, pi_old[y]) * A
g = (w[:, None] * (np.eye(K)[y] - pi)).mean(0)
z = z + lr * g
pi = softmax(z)
kl = np.sum(pi_old * np.log(pi_old / pi))
hist.append((softmax(z)[0], kl))
return hist
print("π(good token) after iterations 1, 3, 6, 12 (8 passes per batch) | max KL(π_old‖π) per iteration")
for rule in ["PPO 0.2/0.2", "clip-higher", "CISPO (cap 2)", "DPPO-TV δ=0.2", "no clip"]:
h = run(rule)
print(f" {rule:14s}", " ".join(f"{h[i][0]:.3f}" for i in [0, 2, 5, 11]), f"| {max(k for _, k in h):.3f}")PPO와 clip-higher는 여섯 iteration 동안 좋은 토큰을 0.01에서 0.04–0.06으로밖에 올리지 못한다. CISPO와 DPPO는 0.97 이상에 이른다. 마지막 열이 대가다. iteration당 최대 가 clip 규칙에서는 약 0.12, 나머지에서는 0.8–1.5다. Clip-higher는 KL 비용 없이 속도를 조금 사고, CISPO와 DPPO는 step이 커지도록 두어 속도를 많이 산다. 이 교환의 어느 쪽을 원하는지는 불안정이 드물고 유용한 토큰에서 너무 느리게 움직여서 오는지, 드물고 해로운 토큰에서 너무 빨리 움직여서 오는지에 달렸다.
세 정책: decoupled PPO와 bypass 방식
맨 위의 세 분포로 돌아가자. Hilton, Cobbe, Schulman(2021)은 PPO가 의 두 역할을 섞는다고 지적했다. importance sampling이 보정해야 할 행동 정책, 그리고 trust region을 재는 기준인 근접 정책이다. 둘을 나누면
첫 인자는 상수로 둔다. 표의 대부분이 이 구조다. Olmo 3는 학습기 재계산으로 두고 행동 인자를 (TIS)로 자른다. Nemotron의 비동기 증류 단계는 그것을 로 쓴다. AReaL은 staleness를 흡수하는 데 쓴다. staleness 쪽은 비동기 레슨이 다룬다.
Bypass 방식은 로 둔다. 재계산을 건너뛰고 rollout 엔진의 log-prob을 분모로 써서 ratio 하나 를 clip하거나 mask한다. GLM-5의 비동기 agentic 단계(에 양방향 band)와 MiMo-V2.6이 그렇게 하고, DPPO는 원리적으로 이를 지지한다. 재계산한 분포를 기준으로 잰 trust region도 붕괴했으며, 기준은 rollout 분포여야 하고, 재계산을 건너뛰면 step 비용의 약 4분의 1을 아낀다는 실험이다. 대가는 ratio 하나가 업데이트, staleness, 엔진 잡음을 함께 싣는다는 것이다. 그래서 band는 셋의 합에 맞을 만큼 좁아야 한다. GLM-5 보고서가 이를 명시한다.
엔진 차이 보정: TIS, MIS, IcePop, CIS
행동 인자 가 엔진 불일치가 들어오는 곳이다. 네 규칙이 주류다.
- TIS(Yao, Liu et al. 2025): 를 곱한다. 모든 토큰을 남기고 큰 가중치를 자르므로 인 토큰에서 추정이 아래로 편향된다. Olmo 3는 .
- 토큰 MIS(Liu, Li et al. 2025): . 자르는 대신 버린다.
- IcePop(Ling Team 2025): , 양방향, 논문에서는 . mask된 토큰은 학습 토큰의 1–2‰였고 평균보다 엔트로피가 높았다. GLM-5는 추론 RL에서 를 쓴다. IcePop 논문 자신은 민감도 실험에서 가 불안정했다고 보고하니, 맞는 band는 설정에 달렸다.
- CIS(Yu et al. 2026): 를 학습기 확률, 를 엔진 사이 logit 차이로 할 때 에서 출발해, 상한 (, )를 쓴다. 토큰이 확신할수록 좁아지는 상한이다. 그 ablation에서 작은 가중치를 끌어올리는 양방향 band는 학습을 무너뜨렸다.
항등식 이 고르기 전에 어디를 봐야 하는지 알려 준다. 불일치는 확률 낮은 토큰에 산다.
Under TIS nothing is dropped, and every truncated token sits at low . Switch to the band mask at β = 2: the lower edge removes tokens the sampler over-weighted (), again almost all low-probability. CIS spends its truncation budget more evenly — high-confidence tokens face a tight cap because for them even a moderate means a large logit gap. The ESS readout shows the variance side: dropping and truncating both raise it.
The block below measures these rules as estimators of the policy gradient (not just of an expectation, as in the mismatch lesson): a 60-token next-token distribution, rewards per token, samples from a sampler whose logits differ from the trainer’s.
V = 60
logits = rng.normal(0, 2.0, V); logits[0] += 4 # a peaked trainer distribution
pi = softmax(logits) # π_train(·|h) at θ_old
r_tok = rng.random(V) # reward of each next token
g_true = pi * (r_tok - pi @ r_tok) # E_π[(r − b) ∇_z log π], b = E_π r
def estimators(sig, tail, n=128, reps=400):
gap = sig * rng.normal(size=V) * np.where(rng.random(V) < tail, 4, 1)
mu = softmax(logits - gap) # sampler logits differ by ε = gap
k = pi / mu # = p + (1−p) e^ε for the sampled token
cis_cap = 1 + 2.3 * np.maximum(1 - pi, 5e-3)
W = {"none": np.ones(V), "TIS C=2": np.minimum(k, 2), "band [0.5,2]": k * ((k >= 0.5) & (k <= 2)),
"band [0.5,5]": k * ((k >= 0.5) & (k <= 5)), "CIS": np.minimum(k, cis_cap), "exact IS": k}
out = {}
for name, w in W.items():
est = []
for _ in range(reps):
y = rng.choice(V, size=n, p=mu).astype(np.intp)
adv = r_tok[y] - pi @ r_tok
est.append(((w[y] * adv)[:, None] * (np.eye(V)[y] - pi)).mean(0))
est = np.array(est)
out[name] = (np.linalg.norm(est.mean(0) - g_true) / np.linalg.norm(g_true),
np.sqrt(((est - est.mean(0)) ** 2).sum(1).mean()) / np.linalg.norm(g_true))
dropped = {"band [0.5,2]": mu[(k < 0.5) | (k > 2)].sum(), "band [0.5,5]": mu[(k < 0.5) | (k > 5)].sum()}
return out, dropped, np.sum(mu * np.log(mu / pi))
for sig, tail in [(0.2, 0.0), (0.4, 0.05), (0.7, 0.1)]:
out, dropped, kl = estimators(sig, tail)
print(f"\nlogit gap σ={sig}, tail={tail}: KL(μ‖π)={kl:.3f}; sampler mass dropped: "
+ ", ".join(f"{k} {v:.1%}" for k, v in dropped.items()))
for name, (b, s) in out.items():
print(f" {name:13s} rel.bias {b:6.3f} rel.std {s:6.3f} rel.RMSE {np.hypot(b, s):6.3f}")At a mild gap (KL 0.014) every correction removes the bias of doing nothing (0.16 → about 0.01–0.02) and nothing is dropped. At a moderate gap with a tail (KL 0.06), the narrow band [0.5, 2] drops about 5% of the sampler’s mass and its bias jumps to 0.28 — as large as doing nothing — while TIS, the wide band and CIS stay at 0.01–0.03. At a severe gap (KL 0.31) both bands drop a quarter of the mass; TIS and CIS trade a bias of 0.06–0.10 for a spread about 25% below that of exact IS. The pattern to keep: masks are cheap insurance when the tail is rare, and a bias machine when it is not. If your logged out-of-band fraction climbs past a few percent, the correction has stopped being a correction; fix the system.
Sequence-level masks
Token rules never look at the response as a whole. Four rules do:
- DeepSeek-V3.2 masks a response only if its advantage is negative and its mean log-ratio exceeds — learning from one’s own mistakes is useful, learning from far-off-policy mistakes is not.
- Sequence MIS drops a response when its product ratio leaves a band.
- Geo-RS (geometric-mean rejection) keeps a response only if — GSPO’s length normalisation used as a mask.
- Trust Region Masking (Li et al. 2025) keeps a response only if , estimated per token with k2 (for the max) or k3 (for a mean variant). The motivation is theoretical: classical surrogate-error bounds grow like and are vacuous at ; bounds driven by the maximum token divergence are not. The paper itself notes the catch: if each token independently exceeds with probability , acceptance is , and it proposes a length-neutral variant.
def accept_rates(T, n=300, sig=0.03, tail=0.001):
d = rng.normal(-sig**2 / 2, sig, (n, T))
d += np.where(rng.random((n, T)) < tail, rng.normal(0, 0.7, (n, T)), 0) # rare large token gaps
seq = d.sum(1)
k2 = 0.5 * d**2; k3 = np.expm1(d) - d
return {
"seq-MIS Πρ∈[0.5,2]": np.mean(np.abs(seq) <= np.log(2)),
"Geo-RS ρ^(1/T)∈[e^±.01]": np.mean(np.abs(seq / T) <= 0.01),
"TRM-max max k2≤0.05": np.mean(k2.max(1) <= 0.05),
"TRM-avg mean k3≤1e-3": np.mean(k3.mean(1) <= 1e-3),
}
print("acceptance rate of sequence-level masks vs response length")
rows = {T: accept_rates(T) for T in [100, 1000, 5000]}
for name in rows[100]:
print(f" {name:25s}", " ".join(f"T={T}: {rows[T][name]:5.1%}" for T in rows))With identical per-token behaviour (σ = 0.03 plus a 0.1% tail), the product-ratio mask keeps 95% of 100-token responses and about 15% of 5,000-token ones; the max-based TRM falls to about 3%. The geometric-mean and mean-based criteria do the opposite: averaging makes them more certain as grows, so acceptance becomes a property of the policy gap instead of the length. A mask whose acceptance depends on length is a length penalty again — the same lesson as aggregation. For long reasoning and agent trajectories, prefer length-normalised criteria, or per-turn masks.
Implementing it
import torch
def pg_loss(logp, prox_logp, behav_logp, adv, mask, *, rule="ppo",
eps_low=0.2, eps_high=0.28, dual_c=3.0, tv_delta=0.2,
is_corr="tis", tis_cap=2.0, band=(0.5, 5.0), geo_band=None, bypass=False):
"""logp: (B,T) π_θ with grad; prox_logp: (B,T) proximal π (trainer recompute);
behav_logp: (B,T) behaviour μ (rollout engine); adv: (B,T); mask: (B,T) model tokens.
bypass=True sets π_prox := μ (no recompute) and skips the behaviour correction."""
m = mask.float()
if bypass:
prox_logp = behav_logp
ratio = torch.exp(logp - prox_logp) # ρ_t = π_θ/π_prox
if rule in ("ppo", "dual"):
surr = torch.minimum(ratio * adv, ratio.clamp(1 - eps_low, 1 + eps_high) * adv)
if rule == "dual": # Ye et al.: floor at c·A for A<0
surr = torch.where(adv < 0, torch.maximum(surr, dual_c * adv), surr)
elif rule == "cispo": # weight capped, never zeroed
surr = ratio.detach().clamp(max=1 + eps_high) * adv * logp
elif rule == "dppo_tv": # DPPO binary-TV mask
tv = torch.exp(prox_logp) * (ratio.detach() - 1).abs()
going_out = torch.where(adv > 0, ratio.detach() > 1, ratio.detach() < 1)
keep = (~(going_out & (tv > tv_delta))).float()
surr = keep * ratio * adv
else:
raise ValueError(rule)
if not bypass: # behaviour correction k = π_prox/μ
k = torch.exp(prox_logp - behav_logp).detach()
if is_corr == "tis":
surr = k.clamp(max=tis_cap) * surr
elif is_corr == "icepop":
surr = torch.where((k >= band[0]) & (k <= band[1]), k, torch.zeros_like(k)) * surr
if geo_band is not None: # Geo-RS: whole-sequence rejection
log_geo = ((prox_logp - behav_logp) * m).sum(1) / m.sum(1).clamp(min=1)
ok = ((log_geo >= torch.log(torch.tensor(geo_band[0]))) &
(log_geo <= torch.log(torch.tensor(geo_band[1])))).float()
m = m * ok[:, None]
return -(surr * m).sum() / mask.float().sum().clamp(min=1) # token mean over the global batchNote the last line divides by the original token count even when Geo-RS rejects responses, so a batch with many rejections takes a smaller step instead of re-weighting the survivors (dividing by the surviving count is the other defensible choice; log which one you use). In bypass mode geo_band is a no-op by construction, since ; a bypass implementation should apply the sequence test to at the start of the step instead.
A PPO run with stale rollouts shows rare gradient-norm spikes. Logging shows that the spikes come from tokens with negative advantage and ratios of 10–40. Which change targets exactly these tokens?
For , PPO’s multiplier is : it is never switched off on the high side, so a bad token whose probability rose 10–40× contributes 10–40 times its advantage. Dual-clip’s floor (with in the original paper) or MAI’s outer cap remove exactly that branch. Clip-higher changes the side; CISPO caps the weight at but keeps the gradient; lowering widens the low side.
Your IcePop-style band [0.5, 2] masks 6% of tokens on long agent trajectories, up from 0.2% a week ago. What does the gradient-estimator experiment suggest?
In the experiment, a band that dropped about 5% of the sampler mass already had a relative bias of about 0.28 — as large as applying no correction at all, and an order of magnitude above TIS or a wide band. A growing out-of-band fraction is a symptom that and are drifting apart (precision, kernels, routing). Tightening the band drops more; exact sequence IS has exploding variance on long trajectories.
Summary
- Every clip rule is a multiplier on . PPO never switches off large ratios for negative advantages; dual-clip () and outer ratio caps (MAI, ) do.
- Clip-higher widens the positive side and recovers the low-probability tokens that move most. CISPO caps the weight but never removes a token; DPPO measures the trust region in probability mass, so rare tokens may move far and confident tokens may not.
- Decoupled PPO separates the behaviour policy (importance correction) from the proximal policy (trust region); the bypass mode merges them into one ratio against the rollout engine and must then keep a tight band.
- TIS truncates, MIS and IcePop drop, CIS truncates with a confidence-dependent cap. Masks are nearly free when out-of-band tokens are rare and become heavily biased when they are not.
- Sequence-level masks differ sharply in length dependence: product-ratio and max-token (TRM) tests reject long responses, geometric-mean (Geo-RS) and mean tests do not. A length-dependent mask is an implicit length penalty.
TIS에서는 아무것도 버려지지 않고, 잘린 토큰은 모두 낮은 에 있다. β = 2의 band mask로 바꾸면 아래 경계가 샘플러가 과대 가중한 토큰()을 지우는데, 역시 거의 모두 확률이 낮다. CIS는 자르는 예산을 더 고르게 쓴다. 확신이 높은 토큰은 중간 크기의 도 큰 logit 차이를 뜻하므로 좁은 상한을 만난다. ESS 값이 분산 쪽을 보여 준다. 버리기와 자르기 모두 ESS를 올린다.
아래 블록은 이 규칙들을 (불일치 레슨처럼 기댓값이 아니라) policy gradient의 추정량으로 잰다. 다음 토큰 분포 60개, 토큰마다 보상, 학습기와 logit이 다른 샘플러에서 뽑은 샘플이다.
V = 60
logits = rng.normal(0, 2.0, V); logits[0] += 4 # 뾰족한 학습기 분포
pi = softmax(logits) # θ_old에서 π_train(·|h)
r_tok = rng.random(V) # 다음 토큰마다의 보상
g_true = pi * (r_tok - pi @ r_tok) # E_π[(r − b) ∇_z log π], b = E_π r
def estimators(sig, tail, n=128, reps=400):
gap = sig * rng.normal(size=V) * np.where(rng.random(V) < tail, 4, 1)
mu = softmax(logits - gap) # 샘플러 logit이 ε = gap만큼 다름
k = pi / mu # 샘플 토큰에서 = p + (1−p) e^ε
cis_cap = 1 + 2.3 * np.maximum(1 - pi, 5e-3)
W = {"none": np.ones(V), "TIS C=2": np.minimum(k, 2), "band [0.5,2]": k * ((k >= 0.5) & (k <= 2)),
"band [0.5,5]": k * ((k >= 0.5) & (k <= 5)), "CIS": np.minimum(k, cis_cap), "exact IS": k}
out = {}
for name, w in W.items():
est = []
for _ in range(reps):
y = rng.choice(V, size=n, p=mu).astype(np.intp)
adv = r_tok[y] - pi @ r_tok
est.append(((w[y] * adv)[:, None] * (np.eye(V)[y] - pi)).mean(0))
est = np.array(est)
out[name] = (np.linalg.norm(est.mean(0) - g_true) / np.linalg.norm(g_true),
np.sqrt(((est - est.mean(0)) ** 2).sum(1).mean()) / np.linalg.norm(g_true))
dropped = {"band [0.5,2]": mu[(k < 0.5) | (k > 2)].sum(), "band [0.5,5]": mu[(k < 0.5) | (k > 5)].sum()}
return out, dropped, np.sum(mu * np.log(mu / pi))
for sig, tail in [(0.2, 0.0), (0.4, 0.05), (0.7, 0.1)]:
out, dropped, kl = estimators(sig, tail)
print(f"\nlogit gap σ={sig}, tail={tail}: KL(μ‖π)={kl:.3f}; sampler mass dropped: "
+ ", ".join(f"{k} {v:.1%}" for k, v in dropped.items()))
for name, (b, s) in out.items():
print(f" {name:13s} rel.bias {b:6.3f} rel.std {s:6.3f} rel.RMSE {np.hypot(b, s):6.3f}")차이가 작을 때(KL 0.014)는 모든 보정이 아무것도 안 할 때의 편향(0.16)을 약 0.01–0.02로 없애고 버리는 것도 없다. 꼬리가 있는 중간 차이(KL 0.06)에서 좁은 band [0.5, 2]는 샘플러 질량의 약 5%를 버리고 편향이 0.28로 뛰어 아무것도 안 한 것만큼 커지는데, TIS·넓은 band·CIS는 0.01–0.03에 머문다. 심한 차이(KL 0.31)에서는 두 band 모두 질량의 4분의 1을 버린다. TIS와 CIS는 0.06–0.10의 편향을 내주고 정확한 IS보다 약 25% 작은 퍼짐을 얻는다. 기억할 패턴: mask는 꼬리가 드물 때는 값싼 보험이고, 드물지 않으면 편향 기계다. 기록한 band 밖 비율이 몇 %를 넘어 오르면 보정은 더 이상 보정이 아니다. 시스템을 고쳐라.
시퀀스 단위 mask
토큰 규칙은 응답 전체를 보지 않는다. 네 규칙이 본다.
- DeepSeek-V3.2는 advantage가 음수이고 평균 log-ratio 가 를 넘을 때만 응답을 mask한다. 자기 실수에서 배우는 것은 유용하지만 멀리 off-policy인 실수에서 배우는 것은 아니다.
- 시퀀스 MIS는 곱 ratio 가 band를 벗어나면 응답을 버린다.
- Geo-RS(기하평균 거부)는 일 때만 응답을 남긴다. GSPO의 길이 정규화를 mask로 쓴 것이다.
- Trust Region Masking(Li et al. 2025)은 일 때만 응답을 남긴다. 토큰마다 k2(최댓값용)나 k3(평균 변형용)로 추정한다. 동기는 이론이다. 고전적 surrogate 오차 한계는 처럼 커져 에서 무의미한데, 최대 토큰 divergence가 좌우하는 한계는 그렇지 않다. 논문 스스로 함정을 짚는다. 각 토큰이 독립적으로 확률 로 를 넘으면 수용률은 이고, 그래서 길이 중립적인 변형을 제안한다.
def accept_rates(T, n=300, sig=0.03, tail=0.001):
d = rng.normal(-sig**2 / 2, sig, (n, T))
d += np.where(rng.random((n, T)) < tail, rng.normal(0, 0.7, (n, T)), 0) # 드문 큰 토큰 차이
seq = d.sum(1)
k2 = 0.5 * d**2; k3 = np.expm1(d) - d
return {
"seq-MIS Πρ∈[0.5,2]": np.mean(np.abs(seq) <= np.log(2)),
"Geo-RS ρ^(1/T)∈[e^±.01]": np.mean(np.abs(seq / T) <= 0.01),
"TRM-max max k2≤0.05": np.mean(k2.max(1) <= 0.05),
"TRM-avg mean k3≤1e-3": np.mean(k3.mean(1) <= 1e-3),
}
print("acceptance rate of sequence-level masks vs response length")
rows = {T: accept_rates(T) for T in [100, 1000, 5000]}
for name in rows[100]:
print(f" {name:25s}", " ".join(f"T={T}: {rows[T][name]:5.1%}" for T in rows))토큰당 행동이 똑같아도(σ = 0.03에 0.1% 꼬리) 곱 ratio mask는 100토큰 응답의 95%, 5,000토큰 응답의 약 15%를 남긴다. 최댓값 기반 TRM은 약 3%로 떨어진다. 기하평균과 평균 기반 기준은 반대다. 평균이 가 커질수록 확실해지므로 수용률이 길이가 아니라 정책 차이의 성질이 된다. 수용률이 길이에 달린 mask는 다시 길이 패널티다. 집계와 같은 교훈이다. 긴 추론과 agent 궤적에는 길이 정규화된 기준이나 턴별 mask를 택하라.
구현
import torch
def pg_loss(logp, prox_logp, behav_logp, adv, mask, *, rule="ppo",
eps_low=0.2, eps_high=0.28, dual_c=3.0, tv_delta=0.2,
is_corr="tis", tis_cap=2.0, band=(0.5, 5.0), geo_band=None, bypass=False):
"""logp: (B,T) gradient가 흐르는 π_θ; prox_logp: (B,T) 근접 π (학습기 재계산);
behav_logp: (B,T) 행동 μ (rollout 엔진); adv: (B,T); mask: (B,T) 모델 토큰.
bypass=True이면 π_prox := μ (재계산 없음)이고 행동 보정을 건너뛴다."""
m = mask.float()
if bypass:
prox_logp = behav_logp
ratio = torch.exp(logp - prox_logp) # ρ_t = π_θ/π_prox
if rule in ("ppo", "dual"):
surr = torch.minimum(ratio * adv, ratio.clamp(1 - eps_low, 1 + eps_high) * adv)
if rule == "dual": # Ye et al.: A<0이면 c·A에서 바닥
surr = torch.where(adv < 0, torch.maximum(surr, dual_c * adv), surr)
elif rule == "cispo": # 가중치 상한, 결코 0이 아님
surr = ratio.detach().clamp(max=1 + eps_high) * adv * logp
elif rule == "dppo_tv": # DPPO binary-TV mask
tv = torch.exp(prox_logp) * (ratio.detach() - 1).abs()
going_out = torch.where(adv > 0, ratio.detach() > 1, ratio.detach() < 1)
keep = (~(going_out & (tv > tv_delta))).float()
surr = keep * ratio * adv
else:
raise ValueError(rule)
if not bypass: # 행동 보정 k = π_prox/μ
k = torch.exp(prox_logp - behav_logp).detach()
if is_corr == "tis":
surr = k.clamp(max=tis_cap) * surr
elif is_corr == "icepop":
surr = torch.where((k >= band[0]) & (k <= band[1]), k, torch.zeros_like(k)) * surr
if geo_band is not None: # Geo-RS: 시퀀스 전체 거부
log_geo = ((prox_logp - behav_logp) * m).sum(1) / m.sum(1).clamp(min=1)
ok = ((log_geo >= torch.log(torch.tensor(geo_band[0]))) &
(log_geo <= torch.log(torch.tensor(geo_band[1])))).float()
m = m * ok[:, None]
return -(surr * m).sum() / mask.float().sum().clamp(min=1) # 전역 배치 위의 token mean마지막 줄은 Geo-RS가 응답을 거부해도 원래 토큰 수로 나눈다. 그래서 거부가 많은 배치는 살아남은 응답을 재가중하는 대신 작은 step을 밟는다(살아남은 수로 나누는 것도 변호할 만한 다른 선택이다. 어느 쪽을 쓰는지 기록하라). bypass 방식에서는 이므로 geo_band가 구조상 아무 일도 하지 않는다. bypass 구현은 step 시작에서 에 시퀀스 검정을 적용해야 한다.
오래된 rollout을 쓰는 PPO 실험에서 드물게 gradient-norm 급등이 보인다. 기록을 보니 급등은 음의 advantage에 ratio 10–40인 토큰에서 온다. 정확히 이 토큰을 겨냥하는 변경은?
에서 PPO의 인자는 이라 높은 쪽에서는 결코 꺼지지 않는다. 확률이 10–40배 오른 나쁜 토큰은 advantage의 10–40배를 기여한다. Dual-clip의 바닥 (원 논문 )나 MAI의 바깥 상한 이 바로 그 가지를 없앤다. Clip-higher는 쪽을 바꾸고, CISPO는 가중치를 에서 막지만 gradient는 유지하며, 을 낮추면 낮은 쪽이 넓어진다.
IcePop식 band [0.5, 2]가 긴 agent 궤적에서 토큰의 6%를 mask한다. 일주일 전에는 0.2%였다. gradient 추정량 실험은 무엇을 시사하나?
실험에서 샘플러 질량의 약 5%를 버린 band는 이미 상대 편향이 약 0.28로, 아무 보정도 안 한 것만큼 크고 TIS나 넓은 band보다 한 자릿수 컸다. band 밖 비율이 자란다는 것은 와 가 멀어지고 있다는 증상이다(정밀도, 커널, routing). band를 좁히면 더 많이 버린다. 정확한 시퀀스 IS는 긴 궤적에서 분산이 폭발한다.
정리
- 모든 clip 규칙은 에 곱하는 인자 다. PPO는 음의 advantage에서 큰 ratio를 결코 끄지 않는다. dual-clip()과 바깥 ratio 상한(MAI, )은 끈다.
- Clip-higher는 양의 쪽을 넓혀 가장 많이 움직이는 확률 낮은 토큰을 되찾는다. CISPO는 가중치를 누르되 토큰을 결코 지우지 않는다. DPPO는 trust region을 확률 질량으로 재므로 드문 토큰은 멀리 움직이고 확신하는 토큰은 그러지 못한다.
- Decoupled PPO는 행동 정책(importance 보정)과 근접 정책(trust region)을 나눈다. bypass 방식은 둘을 rollout 엔진 기준 ratio 하나로 합치고, 그러면 좁은 band를 유지해야 한다.
- TIS는 자르고, MIS와 IcePop은 버리며, CIS는 확신에 따라 달라지는 상한으로 자른다. Mask는 band 밖 토큰이 드물 때는 거의 공짜이고, 그렇지 않으면 크게 편향된다.
- 시퀀스 단위 mask는 길이 의존성이 크게 다르다. 곱 ratio와 최대 토큰(TRM) 검정은 긴 응답을 거부하고, 기하평균(Geo-RS)과 평균 검정은 그렇지 않다. 길이에 의존하는 mask는 숨은 길이 패널티다.
더 읽을거리Further reading
- Ye et al., Mastering Complex Control in MOBA Games with Deep Reinforcement Learning (AAAI 2020) — dual-clip PPO. 음의 advantage에서 손실을 c·A로 막는다(c=3, ε=0.2).Dual-clip PPO: bounds the loss at c·A for negative advantages (c = 3, ε = 0.2).
- Yu et al., DAPO: An Open-Source LLM Reinforcement Learning System at Scale (2025) — clip-higher (ε_low 0.2, ε_high 0.28).Clip-higher (ε_low 0.2, ε_high 0.28).
- MiniMax, MiniMax-M1: Scaling Test-Time Compute Efficiently with Lightning Attention (2025), §3.1 — CISPO. 업데이트 대신 IS 가중치를 clip한다.CISPO: clip the IS weight, not the update.
- Qi et al., Rethinking the Trust Region in LLM Reinforcement Learning (DPPO, 2026) — ratio 대신 total variation·KL로 정하는 trust-region mask. rollout 분포를 기준으로 삼는다.A trust-region mask set by total variation or KL instead of the ratio, anchored at the rollout distribution.
- Hilton, Cobbe, Schulman, Batch size-invariance for policy optimization (2021) — 근접 정책(업데이트 크기 조절)과 행동 정책(off-policy 보정)을 분리한 decoupled PPO.Decoupled PPO: separates the proximal policy (controls update size) from the behaviour policy (off-policy correction).
- Ling Team, Every Step Evolves: Scaling Reinforcement Learning for Trillion-Scale Thinking Model (2025), §2.3.2 — IcePop. 엔진 ratio가 [0.5, 5] 밖인 토큰의 gradient를 버린다.IcePop: drops the gradient of tokens whose engine ratio is outside [0.5, 5].
- Yao, Liu et al., Your Efficient RL Framework Secretly Brings You Off-Policy RL Training (2025, blog) — truncated importance sampling(TIS)으로 vLLM·FSDP 차이를 보정.Truncated importance sampling (TIS) for the vLLM/FSDP gap.
- Li et al., Trust Region Masking for Long-Horizon LLM Reinforcement Learning (2025) — 토큰 divergence의 최댓값으로 시퀀스 전체를 mask. 긴 horizon에서도 의미 있는 개선 한계.Masks whole sequences by their maximum token divergence, restoring non-vacuous bounds at long horizons.
- Liu, Li et al., When Speed Kills Stability: Demystifying RL Collapse from the Training-Inference Mismatch (2025, blog) — 토큰·시퀀스 단위 masked IS와 기하평균 시퀀스 거부(Geo-RS).Token- and sequence-level masked IS and geometric-mean sequence rejection (Geo-RS).