PPO and GRPO are introduced as on-policy algorithms: sample with the current policy, and use those samples to improve the current policy. Yet in real LLM RL systems the distribution that produced the samples and the distribution under which the gradient is computed are almost never exactly the same. When they differ, the gradient is biased, and if that bias accumulates over training, at some point the reward collapses. This lesson looks at where the difference comes from, how importance sampling from statistics deals with it, and why the textbook correction does not work as-is for LLMs.
Where do samples come from?
Let us distinguish three distributions.
- : the distribution that actually sampled the tokens. The probabilities computed by the inference engine (vLLM, SGLang) with the weights at sampling time.
- : the probabilities recomputed by the training engine (FSDP, Megatron) with the same weights. The denominator of the PPO ratio.
- : the policy currently being updated.
The gradient we want is an expectation under , but the samples came from . Their ratio splits into two pieces.
There are three causes of the difference.
- Multiple updates. If one batch is split into several minibatches and run for several epochs, then from the second update on . This is the difference PPO’s clip handles.
- Asynchronous rollout and staleness. In the asynchronous systems of the previous lesson, the sampler’s weights lag the trainer’s by a few versions. If the trainer recomputes with its current weights, staleness mixes into the second piece.
- Numerical differences between engines. Even with bit-identical weights, the two engines use different kernels. Floating-point addition is not associative, so changing the reduction order changes the result. The inference engine’s batch size varies with server load, and many kernels change their operation order with batch size (the lack of batch invariance). On top of that come bf16/FP8 precision, different attention kernels, rollout-only quantisation, and, for MoE, routing differences where a different expert is picked when router scores are nearly tied.
Yao et al. (2025) showed that vLLM and FSDP with the same weights can assign very different probabilities to some tokens, and He et al. (2025) at Thinking Machines showed that sending the same prompt several times at temperature 0 produces different outputs because of how batches are composed. These differences are small on average; the problem is the rare large differences. There are also reports that the mismatch is especially large on very low-probability tokens (Liu, Li et al. 2025).
→ Go deeper: the same problem seen from the rollout engine’s side in inference for RL; staleness (cause 2) in asynchronous RL and staleness.
A fuller map: everywhere “on-policy” leaks
The three causes above are the textbook split. A production pipeline has more of them, and for each it helps to know which factor of the ratio it lands in, what shape it has, and where it is fixed. (The list follows Chris Liu’s survey of off-policy drift and §2.1 of the score-centering paper; the details live in the linked lessons.)
| Source | Lands in | Shape | Grows with | First remedy |
|---|---|---|---|---|
| Several mini-batches or PPO epochs per rollout batch | moves with the policy; depends on the gradients in between, so it differs per sequence | updates since sampling | PPO clip, fewer epochs, per-sequence masks (clipping and IS) | |
| One-step-off and fully asynchronous rollout | staleness (inside unless is recomputed at the rollout weights) | systematic, self-amplifying | version gap | decoupled PPO, ESS-triggered resync (async RL) |
| Partial rollouts (weights swapped mid-trajectory) | both, piecewise within one sequence | mixed | number of swaps | per-token version tags, token-level correction |
| Reduction order that depends on batch shape | engine mismatch | dense noise | length () | batch-invariant kernels (mismatch engineering) |
| Different tensor-parallel degree in engine and trainer | engine mismatch | dense noise | depth, length | TP-invariant reductions such as TBIK (inference for RL) |
| Precision (bf16 rounding, a bf16 LM head) | engine mismatch | dense, larger on unlikely tokens | logit magnitude | FP32 LM head; fp16 on both sides (Qi et al. 2025) |
| Quantised rollout (FP8/INT8 weights, low-bit KV cache) | engine mismatch | dense plus systematic | aggressiveness of the format | the same quantisation on both sides; score centering |
| MoE routing; any discrete top-k inside the network (sparse-attention indexers) | engine mismatch | sparse heavy tail | layers, near-tied scores | routing replay; deterministic top-k |
| A sampling transform applied on one side only: a finite positive temperature or finite penalties (change probabilities, keep the support); hard top-k / top-p / masks (can cut the support) | engine mismatch | systematic offset; with hard truncation also support violation (, which no IS weight can correct) | length, linearly | the same transform on both sides; keep the sampling mask |
| Re-tokenised text, chat-template drift | not a ratio — a different sequence | bug | — | token-in-token-out (agent RL) |
Speculative decoding is a common false suspect: with exact (lossless) verification the accepted tokens follow the target model’s distribution, so a draft model that lags behind the policy costs acceptance rate, not correctness (speculative decoding); only relaxed acceptance rules change .
Three habits follow. The sources compound in one ratio: FP8 rollouts on a TP-4 engine against a TP-1 trainer with four PPO epochs pay the precision, parallelism and staleness terms at once. Measure them separately: recompute with the trainer at the rollout weights (verl’s decoupled mode, DLC’s extra forward pass) to split the engine factor from the staleness factor, and test the engine factor alone on a same-checkpoint batch before blaming the algorithm. Size is not the whole story: a small gap that is persistent and refreshed with the weights can do more damage over a long run than a larger one that averages out — the subject of score centering.
Importance sampling
Start from the identity that computes an expectation under using samples from .
It is exact as long as wherever . The estimator is unbiased. The problem is the variance.
If there are places where gives much smaller probability than , explodes. The effective sample size (ESS), which summarises the spread of the weights, is
Even if you drew samples, if the weight concentrates on a few of them, you really have only that few samples’ worth of information.
There are two classic ways to reduce the variance.
- Truncated IS (TIS). Clip to . The variance is bounded by , but a bias equal to the truncated mass appears. If , it always skews downward.
- Self-normalised IS (SNIS). . It has bias but is consistent, and since the estimate always stays within the range of it is less swayed by extreme values.
PPO와 GRPO는 on-policy 알고리즘으로 소개된다. 지금 정책으로 샘플을 뽑고, 그 샘플로 지금 정책을 고친다. 그런데 실제 LLM RL 시스템에서 샘플을 만든 분포와 gradient를 계산하는 분포가 정확히 같은 경우는 거의 없다. 둘이 다르면 gradient가 편향되고, 그 편향이 학습 내내 쌓이면 어느 순간 보상이 무너진다. 이 레슨은 그 차이가 어디서 오는지, 통계학의 importance sampling이 그것을 어떻게 다루는지, 그리고 왜 LLM에서는 교과서 그대로의 보정이 통하지 않는지를 본다.
샘플은 어디서 오는가
세 개의 분포를 구분하자.
- : 실제로 토큰을 샘플한 분포. 추론 엔진(vLLM, SGLang)이 샘플 시점의 가중치로 계산한 확률이다.
- : 학습 엔진(FSDP, Megatron)이 같은 가중치로 다시 계산한 확률. PPO ratio의 분모다.
- : 지금 업데이트 중인 정책.
우리가 원하는 gradient는 에 대한 기대값이지만 샘플은 에서 왔다. 둘의 비는 두 조각으로 나뉜다.
차이가 생기는 원인은 세 가지다.
- 여러 번의 업데이트. 한 배치로 minibatch 여러 개, epoch 여러 번을 돌면 두 번째 업데이트부터 다. PPO의 clip이 다루는 것이 이 차이다.
- 비동기 rollout과 staleness. 앞 레슨의 비동기 시스템에서는 샘플러의 가중치가 학습기보다 몇 버전 뒤처져 있다. 학습기가 를 현재 가중치로 다시 계산하면 두 번째 조각에 staleness가 섞인다.
- 엔진 간 수치 차이. 가중치가 bit 단위로 같아도 두 엔진은 다른 커널을 쓴다. 부동소수점 덧셈은 결합법칙이 성립하지 않아 reduction 순서가 바뀌면 결과가 바뀐다. 추론 엔진은 서버 부하에 따라 batch 크기가 달라지고 많은 커널이 batch 크기에 따라 연산 순서를 바꾼다(batch invariance의 부재). 여기에 bf16·FP8 정밀도, 다른 attention 커널, rollout 전용 양자화, MoE의 경우 거의 동점인 router 점수에서 다른 expert가 뽑히는 routing 차이가 더해진다.
Yao et al.(2025)은 같은 가중치의 vLLM과 FSDP가 일부 토큰에서 확률이 매우 크게 다를 수 있음을 보였고, Thinking Machines의 He et al.(2025)은 temperature 0에서 같은 프롬프트를 여러 번 보내도 batch 구성 때문에 서로 다른 출력이 나오는 것을 보였다. 이런 차이는 평균으로는 작지만 드문 큰 차이가 문제다. 불일치는 확률이 아주 낮은 토큰에서 특히 크다는 보고도 있다(Liu, Li et al. 2025).
→ 더 깊이: rollout 엔진 쪽에서 본 같은 문제는 RL을 위한 추론, staleness(원인 2)는 비동기 RL과 staleness.
더 넓은 지도: “on-policy”가 새는 모든 곳
위의 세 원인은 교과서식 분류다. 실제 파이프라인에는 더 많고, 각각이 ratio의 어느 인자에 들어가는지, 어떤 모양인지, 어디서 고치는지를 알아 두면 좋다. (목록은 Chris Liu의 off-policy drift 정리와 score centering 논문의 §2.1을 따르고, 자세한 내용은 링크한 레슨에 있다.)
| 원인 | 들어가는 곳 | 모양 | 무엇과 함께 자라나 | 첫 처방 |
|---|---|---|---|---|
| rollout 배치 하나에 mini-batch나 PPO epoch 여러 번 | 정책과 함께 움직인다. 사이의 gradient에 달려 있어 시퀀스마다 다르다 | 샘플 이후의 업데이트 수 | PPO clip, epoch 줄이기, 시퀀스별 mask(clipping과 IS) | |
| one-step-off와 완전 비동기 rollout | staleness(를 rollout weight에서 다시 계산하지 않으면 안에 섞인다) | 체계적, 스스로 증폭 | 버전 차이 | decoupled PPO, ESS로 촉발하는 재동기화(비동기 RL) |
| partial rollout(trajectory 중간에 weight 교체) | 둘 다, 한 시퀀스 안에서 구간별로 | 섞임 | 교체 횟수 | 토큰별 버전 태그, 토큰 단위 보정 |
| batch 모양에 따라 바뀌는 reduction 순서 | 엔진 불일치 | 조밀한 잡음 | 길이() | batch-invariant kernel(불일치 엔지니어링) |
| 엔진과 trainer의 tensor-parallel 크기 차이 | 엔진 불일치 | 조밀한 잡음 | 깊이, 길이 | TBIK 같은 TP 불변 reduction(RL을 위한 추론) |
| 정밀도(bf16 반올림, bf16 LM head) | 엔진 불일치 | 조밀함, 확률 낮은 토큰에서 더 큼 | logit 크기 | FP32 LM head, 양쪽 fp16(Qi et al. 2025) |
| 양자화된 rollout(FP8/INT8 weight, 저비트 KV cache) | 엔진 불일치 | 조밀함 + 체계적 | 형식이 얼마나 공격적인지 | 양쪽에 같은 양자화, score centering |
| MoE routing, 네트워크 안의 모든 이산 top-k(sparse attention indexer) | 엔진 불일치 | 드문 두꺼운 꼬리 | 층 수, 거의 동점인 점수 | routing replay, 결정적 top-k |
| 한쪽에만 적용된 샘플링 변환: 유한한 양의 temperature나 유한한 penalty(확률은 바꾸되 support는 유지), hard top-k·top-p·mask(support를 자를 수 있음) | 엔진 불일치 | 체계적 오프셋. hard truncation이면 support 위반도(, 어떤 IS 가중치로도 보정 불가) | 길이, 선형으로 | 양쪽에 같은 변환, sampling mask 유지 |
| 다시 tokenize한 텍스트, chat template 차이 | ratio가 아니라 다른 시퀀스 | 버그 | — | token-in-token-out(Agent RL) |
speculative decoding은 흔한 오해의 대상이다. 정확한(lossless) 검증을 쓰면 수락된 토큰은 target 모델의 분포를 따르므로, 정책보다 뒤처진 draft 모델은 정확성이 아니라 수락률을 깎는다(speculative decoding). 완화된 수락 규칙만 를 바꾼다.
여기서 습관 셋이 나온다. 원인들은 한 ratio 안에서 겹친다. TP-4 엔진의 FP8 rollout을 TP-1 trainer와 PPO 4 epoch로 학습하면 정밀도, 병렬화, staleness 항을 한꺼번에 낸다. 따로 재자. trainer로 rollout weight에서 를 다시 계산해(verl의 decoupled 모드, DLC의 추가 forward) 엔진 인자와 staleness 인자를 가르고, 알고리즘을 탓하기 전에 같은 checkpoint 배치로 엔진 인자만 시험하자. 크기가 전부는 아니다. 지속적이고 weight와 함께 갱신되는 작은 차이가, 평균으로 사라지는 더 큰 차이보다 긴 실행에서 더 큰 해를 끼칠 수 있다. score centering의 주제다.
Importance sampling
에 대한 기대값을 의 샘플로 구하는 항등식에서 출발한다.
인 곳에서 이기만 하면 정확하다. 추정량 는 불편이다. 문제는 분산이다.
가 보다 훨씬 작은 확률을 주는 곳이 있으면 가 폭발한다. 가중치의 퍼짐을 요약하는 유효 표본 수(effective sample size) 는
이다. 표본 개를 뽑았어도 가중치가 몇 개에 몰리면 실제로는 그 몇 개만큼의 정보다.
분산을 줄이는 두 가지 고전적 방법이 있다.
- Truncated IS (TIS). 를 로 자른다. 분산은 이하로 묶이지만, 잘린 질량 만큼 편향이 생긴다. 이면 항상 아래로 치우친다.
- Self-normalized IS (SNIS). . 의 편향이 있지만 일치 추정량이고, 추정값이 항상 의 범위 안에 있어 극단값에 덜 휘둘린다.
- With the mismatch at 0 the three estimators coincide (). Raise it to about 1 and exceeds 1; the plain IS dots begin to spread.
- Lower C to 1 and the TIS dots tighten, but their centre is pushed left of the true value (black line). Raise C to 20 and it becomes plain IS. Somewhere in between the RMSE is minimal.
- Raise the mismatch to 2 or more and reduce n. In the weight distribution at the top right, the red part (weights above C) has small probability but large values. That is why a few plain-IS estimates fly far away.
Tokens and sequences: the product blows up
In an LLM a “sample” is a token sequence. The probability ratio of a whole sequence is the product of token ratios.
Suppose the are independent and normal with mean and variance (with this mean, , so a single token is unbiased). Then , and from the moments of the log-normal distribution
Even with a per-token log-prob difference as small as , at the ESS is — about 2 out of 1000 samples. Responses from reasoning models run from thousands to tens of thousands of tokens. Exact sequence-level IS is practically unusable for LLMs.
- 불일치를 0으로 두면 세 추정량이 같다(). 1 정도로 올리면 가 1을 넘고 plain IS의 점들이 퍼지기 시작한다.
- C를 1까지 내리면 TIS의 점들은 촘촘해지지만 중심이 참값(검은 선)에서 왼쪽으로 밀려난다. C를 20까지 올리면 plain IS와 같아진다. 중간 어딘가에서 RMSE가 최소다.
- 불일치를 2 이상으로 올리고 n을 줄여 보자. 오른쪽 위 가중치 분포의 빨간 부분(C를 넘는 가중치)이 확률은 작지만 값이 크다. plain IS의 추정값 몇 개가 멀리 튀는 이유다.
토큰과 시퀀스: 곱이 터진다
LLM에서 “샘플”은 토큰 시퀀스다. 시퀀스 전체의 확률비는 토큰 ratio의 곱이다.
가 서로 독립이고 평균 , 분산 인 정규분포라고 하자(평균을 이렇게 잡으면 로 토큰 하나는 불편이다). 그러면 이고 로그정규분포의 모멘트에서
이다. 토큰당 log-prob 차이가 정도로 작아도 이면 ESS가 , 표본 1000개 중 2개 꼴이다. 추론 모델의 응답은 수천에서 수만 토큰이다. 시퀀스 단위의 정확한 IS는 LLM에서 사실상 쓸 수 없다.
- Drag T from 10 to 1000. The red line (sequence ratio) spreads as and mostly leaves the dashed band [½, 2]. The green line (geometric mean) does the opposite and gathers at 1 (log 0).
- On the right, the sequence-level ESS (red) goes to 0 exponentially as T grows, while the token-level one (blue) does not depend on length.
- Turn on “heavy tail”: most tokens nearly match and only 3% differ a lot. The average noise is actually smaller, yet the token-level ESS also gets worse. Real mismatch looks like this.
So most practical corrections are token-level. The gradient term of token , , is multiplied by that token’s ratio only. This corrects only the difference in the distribution of “which token was chosen in state ” and ignores the difference in “the probability of reaching state ” (the product of earlier tokens’ ratios), so it is biased. In exchange, its variance does not depend on length. This is exactly what PPO was already doing. PPO’s surrogate keeps the state distribution of and justifies the bias with the trust-region argument (TRPO’s bound) that the difference is small when the two policies are close. The same argument applies to engine mismatch: token-level correction is right only when the two distributions are close enough.
GSPO’s geometric-mean ratio sits in between. The variance of is , so it does not explode for long responses, but it is not an exact IS weight. It is best seen as a length-normalised distance measuring how far the whole response has moved, used for clipping.
Corrections in practice
Placing recent methods on this picture gives the following.
| Method | What it does | Unit |
|---|---|---|
| PPO clip | turns off the gradient in that direction when is outside | token |
| TIS (Yao et al.) | multiplies the loss by to correct the engine mismatch | token |
| Masked IS / IcePop | discards the gradient of tokens whose engine ratio is outside a band (IcePop uses ) | token |
| Sequence-level TIS/MIS | truncates by the sequence ratio (or its geometric mean), or drops whole sequences above a threshold | sequence |
| CISPO (MiniMax-M1) | instead of clipping the update, clips the IS weight and multiplies it as a stop-gradient. Every token receives gradient | token |
| GSPO | clips with a length-normalised sequence ratio | sequence |
TIS plays a different role from PPO’s clip. The clip is a trust region that keeps from moving too far from ; TIS is a correction factor between and . So the two are multiplied and used together.
CISPO came from a different concern. The MiniMax-M1 report points out that reflection tokens such as “However” and “Wait” have low probability, so after the first update their ratio grows, hits the clip, and loses gradient in later updates. So it uses the REINFORCE form and clips only the weight .
Which correction is better is not settled yet. Liu, Li et al. (2025) reported that in a multi-turn tool-use setting, token-level correction eventually collapsed while sequence-level correction held up. Sequence-level correction, on the other hand, has the length problem seen above, so long trajectories need length normalisation such as the geometric mean. Rather than numerical correction, there are also systems-side fixes that reduce the cause.
- Same kernels, same precision. Matching sampler and trainer bit for bit with batch-invariant kernels brings the engine mismatch to 0 (He et al. 2025). In exchange, inference gets slower. MiniMax-M1 reported that computing the LM head in FP32 greatly raised the correlation between the two engines’ probabilities.
- MoE routing replay. Record the experts chosen at inference and reuse them in the training forward pass (R3, Ma et al. 2025). GSPO reports stabilising without routing replay by using a sequence-level ratio.
- Use the rollout’s log-probs and token ids as they are. First remove things that are “bugs, not mismatch”, such as re-tokenisation and different sampling parameters.
→ Go deeper: how these corrections become real framework options in verl rollout correction and verl today; systems-side fixes in engineering away the training–inference mismatch; the clip and IS variants compared in clipping and IS; reading failures from metrics in the stability playbook.
Suppose responses average 2,000 tokens and the per-token cross-engine log-prob difference has a standard deviation of 0.05 (independent, normal). Roughly what is ESS/n for exact sequence-level IS?
. That the weights have mean 1 (unbiasedness) and that their variance is small are entirely different statements. Only about 7 out of 1000 samples are effectively used. That is why practice uses token-level correction (accepting bias) or a length-normalised sequence ratio.
Try it yourself
In the same discrete space as the figure, repeat plain IS, TIS and SNIS 2000 times each and measure bias, std and RMSE. Then vary the cap C to see the bias–variance trade-off.
import numpy as np
rng = np.random.default_rng(0)
K = 24
k = np.arange(K)
logit_pi = 2.2 * np.exp(-(k - 6)**2 / 8) + 1.6 * np.exp(-(k - 17)**2 / 6)
direction = rng.standard_normal(K) - 1.2 * np.exp(-(k - 17)**2 / 10) # direction in which μ departs from π
f = 0.5 + 0.45 * np.sin(k / 2.6) # function to estimate (e.g. reward)
softmax = lambda z: np.exp(z - z.max()) / np.exp(z - z.max()).sum()
pi = softmax(logit_pi)
truth = pi @ f
def estimators(mu, n, C, trials=2000):
x = rng.choice(K, size=(trials, n), p=mu) # sample from μ (behaviour policy = inference engine)
w = pi[x] / mu[x] # importance weight
is_ = (w * f[x]).mean(1) # unbiased, high variance
tis = (np.minimum(w, C) * f[x]).mean(1) # truncated: lower variance, biased downward
snis = (w * f[x]).sum(1) / w.sum(1) # self-normalized: O(1/n) bias
return is_, tis, snis
print(f"true value E_π[f] = {truth:.4f}\n")
print("mismatch χ² ESS/n | estimator bias std RMSE")
for m in [0.0, 0.5, 1.0, 1.5, 2.0]:
mu = softmax(logit_pi + m * direction)
chi2 = (pi**2 / mu).sum() - 1 # E_μ[w²] − 1
for name, e in zip(["IS", "TIS(C=2)", "SNIS"], estimators(mu, n=60, C=2.0)):
b, s = e.mean() - truth, e.std()
head = f" {m:3.1f} {chi2:6.2f} {1/(1+chi2):5.2f}" if name == "IS" else " " * 21
print(f"{head} | {name:9s} {b:+8.4f} {s:7.4f} {np.sqrt(b*b + s*s):7.4f}")
print("\nbias–variance vs cap C at mismatch 1.5")
mu = softmax(logit_pi + 1.5 * direction)
for C in [1.0, 2.0, 5.0, 10.0, 50.0, np.inf]:
e = estimators(mu, n=60, C=C)[1]
b, s = e.mean() - truth, e.std()
print(f" C={C:<5} bias {b:+.4f} std {s:.4f} RMSE {np.sqrt(b*b + s*s):.4f}")As the mismatch grows, plain IS stays unbiased while its std grows, and TIS (C=2) has small std but a growing bias, so its RMSE can actually get worse. Setting C to around 5–10 gives a balance between the two. The optimal C of this toy does not carry over to real LLMs. The point is that C is a dial that trades bias against variance.
Next, how the product of sequence ratios breaks down with length.
sigma = 0.08 # std of the per-token log-ratio noise
print(f"per-token δ_t ~ N(−σ²/2, σ²), σ={sigma} (E[e^δ] = 1: unbiased for a single token)")
print(" T std(log w) σ√T ESS/n(MC) e^(−Tσ²) w∈[½,2] max w mean w(true 1)")
for T in [10, 100, 300, 1000, 3000]:
d = rng.normal(-sigma**2 / 2, sigma, size=(2000, T))
logw = d.sum(1) # sequence ratio = Π_t ρ_t
w = np.exp(logw)
ess = w.sum()**2 / (w**2).sum() / len(w)
inside = np.mean(np.abs(logw) <= np.log(2))
print(f"{T:6d} {logw.std():9.2f} {sigma*np.sqrt(T):5.2f} {ess:9.4f} {np.exp(-T*sigma**2):8.4f}"
f" {inside:7.2f} {w.max():8.1f} {w.mean():8.3f}")
# used per token, each individual weight stays small regardless of length
d = rng.normal(-sigma**2 / 2, sigma, size=(200, 3000))
rho = np.exp(d)
print(f"\ntoken ratio ρ_t: mean {rho.mean():.4f}, max {rho.max():.3f}, min(ρ,2) is ≤ 2 by definition")
geo = np.exp(d.mean(1)) # GSPO-style geometric-mean ratio
print(f"geometric-mean ratio (T=3000): mean {geo.mean():.4f}, std {geo.std():.4f} ← gathers near 1")Look at the T=3000 row. The theoretical ESS is practically 0, yet the Monte Carlo ESS comes out non-zero, and the sample mean of the weights is far below the true value 1. That is because most of the mass sits in an extreme tail that 2000 samples never hit once. Sample-based ESS lies when the weights are very bad. Worth remembering when you read diagnostic metrics.
Finally, the PyTorch form of a PPO loss with engine-mismatch correction and diagnostics attached.
import torch
def ppo_loss_with_mismatch(logp, old_logp, rollout_logp, adv, mask,
eps_low=0.2, eps_high=0.28, tis_cap=2.0, mis_band=None):
"""All (N, T), for the sampled tokens.
logp: current policy π_θ (with grad)
old_logp: π_old recomputed by the training engine (no grad)
rollout_logp: μ returned by the inference engine at sampling time (no grad)
adv: per-token advantage, mask: response (model) tokens = 1"""
ratio = torch.exp(logp - old_logp) # PPO ratio ρ_t
surr = torch.minimum(ratio * adv, ratio.clamp(1 - eps_low, 1 + eps_high) * adv)
eng = torch.exp((old_logp - rollout_logp).clamp(-20.0, 20.0)) # π_old / μ
weight = eng.clamp(max=tis_cap) # TIS
m = mask.float()
if mis_band is not None: # IcePop-style masking
lo, hi = mis_band
m = m * ((eng >= lo) & (eng <= hi)).float()
per_tok = -weight.detach() * surr
return (per_tok * m).sum() / mask.float().sum().clamp(min=1)
def cispo_loss(logp, old_logp, adv, mask, eps_high=2.0):
"""CISPO: clip the IS weight, not the update. Every token receives gradient."""
w = torch.exp(logp - old_logp).clamp(max=1 + eps_high).detach()
m = mask.float()
return -(w * adv * logp * m).sum() / m.sum().clamp(min=1)
@torch.no_grad()
def mismatch_stats(old_logp, rollout_logp, mask):
d = (old_logp - rollout_logp)[mask.bool()] # δ = log π_old − log μ
r = torch.exp(d)
return {
"kl_k1": (-d).mean().item(), # estimate of KL(μ‖π_old) (samples are from μ)
"kl_k3": (r - 1 - d).mean().item(), # always ≥ 0, lower variance
"max_abs_logp_diff": d.abs().max().item(),
"frac_ratio_out_0.5_2": ((r < 0.5) | (r > 2.0)).float().mean().item(),
"token_ess_frac": (r.sum() ** 2 / (r ** 2).sum() / r.numel()).item(),
}The eps_high value in cispo_loss is a placeholder. The MiniMax-M1 report says it tunes only the upper bound, but this lesson does not recommend a specific value.
In PPO you build the ratio by recomputing π_old with the training engine. Which difference does this ratio alone not correct?
The PPO ratio measures only how far the policy has moved within the training engine. Since the samples came from , the true correction factor is , and PPO does not see the second piece. Methods like TIS and masked IS are the factors that multiply this piece. Conversely, if the trainer does not recompute and uses directly as the denominator, it ends up clipping with a single ratio in which both pieces are mixed.
Summary
- Samples in LLM RL come from (the inference engine), while the gradient is taken with respect to (the training engine). The ratio splits into the PPO ratio × (engine mismatch + staleness).
- IS is unbiased but its variance is proportional to , summarised as ESS . TIS bounds the variance with a cap at the cost of bias; SNIS gains stability with a small bias.
- A sequence ratio is a product of token ratios, so its ESS collapses as . Practical corrections are therefore token-level (accepting bias) or use a length-normalised sequence ratio.
- TIS, IcePop, CISPO and GSPO are choices of whether to clip weights or drop tokens, and of which unit to use. Batch-invariant kernels, LM-head precision and routing replay reduce the cause.
- Log the distribution of , k1 and k3 KL, the out-of-band fraction and the ESS, broken down by position, turn and probability bin. Sample ESS is optimistic when the tail is bad.
- T를 10에서 1000으로 끌어 보자. 빨간 선(시퀀스 ratio)은 로 퍼져 점선 [½, 2] 밖으로 대부분 나간다. 초록 선(기하평균)은 반대로 1(로그 0)로 모인다.
- 오른쪽에서 시퀀스 단위 ESS(빨강)는 T가 커지면 지수적으로 0이 되고, 토큰 단위(파랑)는 길이와 무관하다.
- “두꺼운 꼬리”를 켜면 대부분 토큰은 거의 일치하고 3%만 크게 다르다. 평균 잡음은 오히려 작은데 토큰 단위 ESS도 나빠진다. 실제 불일치가 이런 모양이다.
그래서 실전의 보정은 대부분 토큰 단위다. 토큰 의 gradient 항 에 그 토큰의 ratio만 곱한다. 이것은 “상태 에서 어떤 토큰을 골랐는가”의 분포 차이만 보정하고 “그 상태 에 도달할 확률”의 차이(앞쪽 토큰들의 ratio 곱)는 무시하므로 편향이 있다. 대신 분산이 길이와 무관하다. PPO가 원래 하던 일이 정확히 이것이다. PPO의 surrogate 는 상태 분포를 의 것으로 두고, 두 정책이 가까우면 그 차이가 작다는 trust region 논리(TRPO의 bound)로 이 편향을 정당화한다. 같은 논리가 엔진 불일치에도 적용된다. 두 분포가 충분히 가까울 때만 토큰 단위 보정이 맞다.
GSPO의 기하평균 ratio 는 그 중간이다. 의 분산이 라 길어도 폭발하지 않지만, 정확한 IS 가중치는 아니다. 응답 전체가 얼마나 움직였는지를 재는 길이 정규화된 거리로 보고 clip에 쓰는 것이다.
실전의 보정들
이 그림 위에 최근 방법들을 놓으면 이렇다.
| 방법 | 무엇을 하나 | 단위 |
|---|---|---|
| PPO clip | 가 밖이면 그 방향 gradient를 끈다 | 토큰 |
| TIS (Yao et al.) | 손실에 를 곱해 엔진 불일치를 보정 | 토큰 |
| Masked IS / IcePop | 엔진 ratio가 밴드 밖인 토큰은 gradient를 버린다 (IcePop은 ) | 토큰 |
| 시퀀스 단위 TIS/MIS | 시퀀스 ratio(또는 그 기하평균)로 자르거나, 기준을 넘는 시퀀스를 통째로 버린다 | 시퀀스 |
| CISPO (MiniMax-M1) | 업데이트를 clip하지 않고 IS 가중치를 clip해 stop-gradient로 곱한다. 모든 토큰이 gradient를 받는다 | 토큰 |
| GSPO | 길이 정규화된 시퀀스 ratio로 clip | 시퀀스 |
TIS는 PPO의 clip과 역할이 다르다. clip은 가 에서 너무 멀어지지 않게 하는 trust region이고, TIS는 와 사이의 보정 계수다. 그래서 둘을 곱해 함께 쓴다.
CISPO는 다른 문제의식에서 나왔다. MiniMax-M1 보고서는 “However”, “Wait” 같은 반성 토큰이 저확률이라 첫 업데이트 뒤 ratio가 커져 clip에 걸리고, 이후 업데이트에서 gradient를 잃는다고 지적한다. 그래서 REINFORCE 형태 를 쓰고 가중치 만 자른다.
어느 보정이 나은지는 아직 정리되지 않았다. Liu, Li et al.(2025)은 멀티턴 tool 사용 설정에서 토큰 단위 보정이 결국 무너지고 시퀀스 단위 보정이 버텼다고 보고했다. 반면 시퀀스 단위는 위에서 본 길이 문제가 있어 긴 trajectory에서는 기하평균 같은 길이 정규화가 필요하다. 수치 보정보다 원인을 줄이는 시스템 쪽 해법도 있다.
- 같은 커널, 같은 정밀도. batch-invariant 커널로 샘플러와 학습기를 bit 단위로 맞추면 엔진 불일치가 0이 된다(He et al. 2025). 대신 추론이 느려진다. MiniMax-M1은 LM head를 FP32로 계산해 두 엔진의 확률 상관을 크게 높였다고 보고했다.
- MoE routing replay. 추론 때 고른 expert를 기록했다가 학습 forward에서 그대로 쓴다(R3, Ma et al. 2025). GSPO는 시퀀스 단위 ratio로 routing replay 없이 안정화했다고 보고한다.
- rollout의 log-prob과 토큰 id를 그대로 쓰기. 재토큰화, 다른 샘플링 파라미터 같은 “불일치가 아니라 버그”인 것부터 없앤다.
→ 더 깊이: 이 보정들이 실제 프레임워크 옵션으로 어떻게 구현되는지는 verl rollout correction과 verl 오늘, 원인을 줄이는 시스템 쪽 처방은 학습–추론 불일치 엔지니어링, clip·IS 변형 비교는 clipping과 IS, 지표로 실패를 읽는 법은 안정화 플레이북.
응답 길이가 평균 2,000 토큰이고 토큰당 엔진 간 log-prob 차이의 표준편차가 0.05라고 하자(독립, 정규 가정). 시퀀스 단위 정확한 IS의 ESS/n은 대략 얼마인가?
. 가중치의 평균이 1이라는 것(불편성)과 분산이 작다는 것은 전혀 다른 이야기다. 표본 1000개 중 7개 정도만 실질적으로 쓰이는 셈이다. 그래서 실전에서는 토큰 단위 보정(편향을 감수)이나 길이 정규화된 시퀀스 ratio를 쓴다.
직접 해 보기
그림과 같은 이산 공간에서 plain IS, TIS, SNIS를 2000번씩 반복해 bias, std, RMSE를 잰다. 그다음 cap C를 바꿔 가며 bias–variance trade-off를 본다.
import numpy as np
rng = np.random.default_rng(0)
K = 24
k = np.arange(K)
logit_pi = 2.2 * np.exp(-(k - 6)**2 / 8) + 1.6 * np.exp(-(k - 17)**2 / 6)
direction = rng.standard_normal(K) - 1.2 * np.exp(-(k - 17)**2 / 10) # μ가 π에서 벗어나는 방향
f = 0.5 + 0.45 * np.sin(k / 2.6) # 추정할 함수 (예: 보상)
softmax = lambda z: np.exp(z - z.max()) / np.exp(z - z.max()).sum()
pi = softmax(logit_pi)
truth = pi @ f
def estimators(mu, n, C, trials=2000):
x = rng.choice(K, size=(trials, n), p=mu) # μ(행동 정책 = 추론 엔진)에서 샘플
w = pi[x] / mu[x] # importance weight
is_ = (w * f[x]).mean(1) # 불편, 분산 큼
tis = (np.minimum(w, C) * f[x]).mean(1) # truncated: 분산 ↓, 편향 ↓방향
snis = (w * f[x]).sum(1) / w.sum(1) # self-normalized: 편향 O(1/n)
return is_, tis, snis
print(f"참값 E_π[f] = {truth:.4f}\n")
print(" 불일치 χ² ESS/n | estimator bias std RMSE")
for m in [0.0, 0.5, 1.0, 1.5, 2.0]:
mu = softmax(logit_pi + m * direction)
chi2 = (pi**2 / mu).sum() - 1 # E_μ[w²] − 1
for name, e in zip(["IS", "TIS(C=2)", "SNIS"], estimators(mu, n=60, C=2.0)):
b, s = e.mean() - truth, e.std()
head = f" {m:3.1f} {chi2:6.2f} {1/(1+chi2):5.2f}" if name == "IS" else " " * 21
print(f"{head} | {name:9s} {b:+8.4f} {s:7.4f} {np.sqrt(b*b + s*s):7.4f}")
print("\n불일치 1.5에서 cap C에 따른 bias–variance")
mu = softmax(logit_pi + 1.5 * direction)
for C in [1.0, 2.0, 5.0, 10.0, 50.0, np.inf]:
e = estimators(mu, n=60, C=C)[1]
b, s = e.mean() - truth, e.std()
print(f" C={C:<5} bias {b:+.4f} std {s:.4f} RMSE {np.sqrt(b*b + s*s):.4f}")불일치가 커질수록 plain IS는 편향 없이 std만 커지고, TIS(C=2)는 std는 작지만 편향이 커져 RMSE가 오히려 나빠지기도 한다. C를 5–10 정도로 두면 둘 사이의 균형점이 나온다. 이 장난감의 최적 C가 실제 LLM에도 맞는 것은 아니다. 핵심은 C가 bias와 variance를 맞바꾸는 다이얼이라는 것이다.
다음은 시퀀스 ratio의 곱이 길이에 따라 어떻게 무너지는지다.
sigma = 0.08 # 토큰당 log-ratio 잡음의 표준편차
print(f"토큰당 δ_t ~ N(−σ²/2, σ²), σ={sigma} (E[e^δ] = 1: 토큰 하나로는 불편)")
print(" T std(log w) σ√T ESS/n(MC) e^(−Tσ²) w∈[½,2] max w mean w(참값 1)")
for T in [10, 100, 300, 1000, 3000]:
d = rng.normal(-sigma**2 / 2, sigma, size=(2000, T))
logw = d.sum(1) # 시퀀스 ratio = Π_t ρ_t
w = np.exp(logw)
ess = w.sum()**2 / (w**2).sum() / len(w)
inside = np.mean(np.abs(logw) <= np.log(2))
print(f"{T:6d} {logw.std():9.2f} {sigma*np.sqrt(T):5.2f} {ess:9.4f} {np.exp(-T*sigma**2):8.4f}"
f" {inside:7.2f} {w.max():8.1f} {w.mean():8.3f}")
# 토큰 단위로 쓰면 가중치 하나하나는 길이와 무관하게 작다
d = rng.normal(-sigma**2 / 2, sigma, size=(200, 3000))
rho = np.exp(d)
print(f"\n토큰 ratio ρ_t: 평균 {rho.mean():.4f}, 최대 {rho.max():.3f}, min(ρ,2)는 정의상 ≤ 2")
geo = np.exp(d.mean(1)) # GSPO식 기하평균 ratio
print(f"기하평균 ratio (T=3000): 평균 {geo.mean():.4f}, std {geo.std():.4f} ← 1 근처로 모인다")T=3000 줄을 보자. 이론 ESS는 사실상 0인데 Monte Carlo ESS는 0이 아닌 값이 나오고, 가중치의 표본 평균은 참값 1보다 훨씬 작다. 질량 대부분이 2000개 표본으로는 한 번도 뽑히지 않는 극단적 꼬리에 있기 때문이다. 표본으로 잰 ESS는 가중치가 아주 나쁠 때 거짓말을 한다. 진단 지표를 볼 때 기억해 둘 점이다.
마지막으로 PPO 손실에 엔진 불일치 보정과 진단을 붙인 PyTorch 형태다.
import torch
def ppo_loss_with_mismatch(logp, old_logp, rollout_logp, adv, mask,
eps_low=0.2, eps_high=0.28, tis_cap=2.0, mis_band=None):
"""모두 (N, T), 샘플된 토큰 기준.
logp: 현재 정책 π_θ (grad 있음)
old_logp: 학습 엔진이 다시 계산한 π_old (no grad)
rollout_logp: 추론 엔진이 샘플할 때 돌려준 μ (no grad)
adv: 토큰별 advantage, mask: 응답(모델) 토큰 = 1"""
ratio = torch.exp(logp - old_logp) # PPO ratio ρ_t
surr = torch.minimum(ratio * adv, ratio.clamp(1 - eps_low, 1 + eps_high) * adv)
eng = torch.exp((old_logp - rollout_logp).clamp(-20.0, 20.0)) # π_old / μ
weight = eng.clamp(max=tis_cap) # TIS
m = mask.float()
if mis_band is not None: # IcePop식 masking
lo, hi = mis_band
m = m * ((eng >= lo) & (eng <= hi)).float()
per_tok = -weight.detach() * surr
return (per_tok * m).sum() / mask.float().sum().clamp(min=1)
def cispo_loss(logp, old_logp, adv, mask, eps_high=2.0):
"""CISPO: 업데이트가 아니라 IS 가중치를 자른다. 모든 토큰이 gradient를 받는다."""
w = torch.exp(logp - old_logp).clamp(max=1 + eps_high).detach()
m = mask.float()
return -(w * adv * logp * m).sum() / m.sum().clamp(min=1)
@torch.no_grad()
def mismatch_stats(old_logp, rollout_logp, mask):
d = (old_logp - rollout_logp)[mask.bool()] # δ = log π_old − log μ
r = torch.exp(d)
return {
"kl_k1": (-d).mean().item(), # KL(μ‖π_old) 추정 (샘플은 μ에서)
"kl_k3": (r - 1 - d).mean().item(), # 항상 ≥ 0, 분산이 작다
"max_abs_logp_diff": d.abs().max().item(),
"frac_ratio_out_0.5_2": ((r < 0.5) | (r > 2.0)).float().mean().item(),
"token_ess_frac": (r.sum() ** 2 / (r ** 2).sum() / r.numel()).item(),
}cispo_loss의 eps_high 값은 자리표시자다. MiniMax-M1 보고서는 상한만 조정한다고 밝혔지만 이 레슨에서 특정 값을 권하지는 않는다.
PPO에서 π_old를 학습 엔진으로 다시 계산해 ratio를 만들고 있다. 이 ratio만으로 보정되지 않는 차이는?
PPO ratio 는 학습 엔진 안에서 정책이 움직인 만큼만 잰다. 샘플은 에서 왔으므로 진짜 보정 계수는 이고, 두 번째 조각은 PPO가 보지 못한다. TIS, masked IS 같은 방법이 이 조각에 곱하는 계수다. 반대로 학습기가 를 다시 계산하지 않고 를 그대로 분모로 쓰면 두 조각이 섞인 ratio 하나로 clip하게 된다.
정리
- LLM RL의 샘플은 (추론 엔진)에서 오고 gradient는 (학습 엔진)에 대해 구한다. 비는 PPO ratio × (엔진 불일치 + staleness)로 나뉜다.
- IS는 불편이지만 분산이 에 비례하고, ESS 로 요약된다. TIS는 cap으로 분산을 묶는 대신 편향을, SNIS는 작은 편향으로 안정성을 얻는다.
- 시퀀스 ratio는 토큰 ratio의 곱이라 ESS가 로 무너진다. 그래서 실전 보정은 토큰 단위(편향 감수)이거나 길이 정규화된 시퀀스 ratio다.
- TIS, IcePop, CISPO, GSPO는 가중치를 자를지, 토큰을 버릴지, 단위를 무엇으로 할지의 선택이다. batch-invariant 커널, LM head 정밀도, routing replay는 원인을 줄인다.
- 의 분포, k1·k3 KL, 밴드 밖 비율, ESS를 위치·turn·확률 구간별로 기록한다. 표본 ESS는 꼬리가 나쁠 때 낙관적이다.
더 읽을거리Further reading
- Yao et al., Your Efficient RL Framework Secretly Brings You Off-Policy RL Training (2025, blog) — vLLM 샘플러와 FSDP 학습기의 확률 차이를 보이고 truncated importance sampling(TIS)으로 보정.Shows probability differences between the vLLM sampler and the FSDP trainer and corrects them with truncated importance sampling (TIS).
- He et al. (Thinking Machines Lab), Defeating Nondeterminism in LLM Inference (2025, blog) — 추론 비결정성의 주원인이 batch-invariance 부재임을 보이고, 샘플러와 학습기를 bit 단위로 맞춘 "진짜 on-policy" RL을 시연.Shows that the main cause of inference nondeterminism is the lack of batch invariance, and demonstrates "truly on-policy" RL with sampler and trainer matched bit for bit.
- Liu, Li et al., When Speed Kills Stability: Demystifying RL Collapse from the Training-Inference Mismatch (2025, blog) — 멀티턴 tool 사용에서 불일치가 커지는 양상과 토큰 단위·시퀀스 단위 보정 비교.How the mismatch grows in multi-turn tool use, and a comparison of token-level and sequence-level correction.
- Ma et al., Stabilizing MoE Reinforcement Learning by Aligning Training and Inference Routers (2025) — MoE의 router 불일치를 추론 때의 routing을 학습에서 재사용(R3)해 줄인다.Reduces MoE router mismatch by reusing the inference-time routing during training (R3).
- Ling Team, Every Step Evolves: Scaling Reinforcement Learning for Trillion-Scale Thinking Model (2025) — IcePop. 엔진 간 ratio가 밴드 밖인 토큰의 gradient를 버리는 양방향 masking.IcePop. Two-sided masking that discards the gradient of tokens whose cross-engine ratio falls outside a band.
- MiniMax, MiniMax-M1: Scaling Test-Time Compute Efficiently with Lightning Attention (2025) — CISPO(업데이트 대신 IS 가중치를 clip)와 LM head 정밀도로 학습·추론 확률을 맞춘 경험.CISPO (clip the IS weight instead of the update) and experience matching training and inference probabilities through LM-head precision.
- Zheng et al., Group Sequence Policy Optimization (2025) — 길이 정규화된 시퀀스 ratio. 토큰 ratio의 잡음과 MoE 불안정에 대한 논의.A length-normalised sequence ratio. Discusses the noise in token ratios and MoE instability.
- Qi et al., Defeating the Training-Inference Mismatch via FP16 (2025) — 학습·추론 엔진을 모두 bf16에서 fp16으로 바꾸면 불일치가 크게 준다(없어지지는 않는다).Switching both training and inference engines from bf16 to fp16 greatly reduces the mismatch (without eliminating it).
- Chris Liu, Off-Policy Drift in LLM RL (2026, blog, WIP) — off-policy가 되는 원인의 분류(정밀도, kernel, TP, MoE routing, 비동기, 양자화), verl 기준 진단 지표와 결정 트리.A taxonomy of the sources of off-policyness (precision, kernels, TP, MoE routing, asynchrony, quantisation), with verl-based diagnostics and a decision tree.
- Owen, Monte Carlo Theory, Methods and Examples, Ch. 9 Importance Sampling — IS의 분산, ESS, self-normalized IS를 다룬 교과서.A textbook treatment of IS variance, ESS and self-normalised IS.
- Ionides, Truncated Importance Sampling (J. Computational and Graphical Statistics, 2008) — 가중치를 자르는 IS의 bias–variance 분석.Bias–variance analysis of IS with truncated weights.