Track V · RL for LLMs & Agents · 09/10

학습–추론 불일치와 importance samplingTraining–inference mismatch and importance sampling

"on-policy" LLM RL의 샘플이 실제로는 다른 정책에서 나오는 세 가지 이유(여러 epoch, 비동기 staleness, 추론·학습 엔진의 수치 차이)를 정리하고, importance sampling의 분산과 ESS, truncated·self-normalized IS, 토큰 단위와 시퀀스 단위 보정의 trade-off를 유도한다. TIS, IcePop, CISPO, GSPO가 이 그림의 어디에 있는지와 진단 지표를 다룬다.Three reasons why the samples of "on-policy" LLM RL actually come from a different policy (multiple epochs, asynchronous staleness, numerical differences between inference and training engines). We derive the variance of importance sampling and the ESS, truncated and self-normalised IS, and the trade-off between token-level and sequence-level correction, then place TIS, IcePop, CISPO and GSPO on that picture and cover diagnostic metrics.

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.

  • μ\mu: the distribution that actually sampled the tokens. The probabilities computed by the inference engine (vLLM, SGLang) with the weights at sampling time.
  • πold\pi_{\text{old}}: the probabilities recomputed by the training engine (FSDP, Megatron) with the same weights. The denominator of the PPO ratio.
  • πθ\pi_\theta: the policy currently being updated.

The gradient we want is an expectation under πθ\pi_\theta, but the samples came from μ\mu. Their ratio splits into two pieces.

πθ(yt∣ht)μ(yt∣ht)=πθ(yt∣ht)πold(yt∣ht)⏟ρt: PPO ratio⋅πold(yt∣ht)μ(yt∣ht)⏟engine mismatch (+ staleness)\frac{\pi_\theta(y_t\mid h_t)}{\mu(y_t\mid h_t)}=\underbrace{\frac{\pi_\theta(y_t\mid h_t)}{\pi_{\text{old}}(y_t\mid h_t)}}_{\rho_t:\ \text{PPO ratio}}\cdot\underbrace{\frac{\pi_{\text{old}}(y_t\mid h_t)}{\mu(y_t\mid h_t)}}_{\text{engine mismatch (+ staleness)}}

There are three causes of the difference.

  1. Multiple updates. If one batch is split into several minibatches and run for several epochs, then from the second update on πθ≠πold\pi_\theta\ne\pi_{\text{old}}. This is the difference PPO’s clip handles.
  2. 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 πold\pi_{\text{old}} with its current weights, staleness mixes into the second piece.
  3. 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.)

SourceLands inShapeGrows withFirst remedy
Several mini-batches or PPO epochs per rollout batchρt=πθ/πold\rho_t=\pi_\theta/\pi_{\text{old}}moves with the policy; depends on the gradients in between, so it differs per sequenceupdates since samplingPPO clip, fewer epochs, per-sequence masks (clipping and IS)
One-step-off and fully asynchronous rolloutstaleness (inside πold/μ\pi_{\text{old}}/\mu unless πold\pi_{\text{old}} is recomputed at the rollout weights)systematic, self-amplifyingversion gapdecoupled PPO, ESS-triggered resync (async RL)
Partial rollouts (weights swapped mid-trajectory)both, piecewise within one sequencemixednumber of swapsper-token version tags, token-level correction
Reduction order that depends on batch shapeengine mismatchdense noiselength (T\sqrt T)batch-invariant kernels (mismatch engineering)
Different tensor-parallel degree in engine and trainerengine mismatchdense noisedepth, lengthTP-invariant reductions such as TBIK (inference for RL)
Precision (bf16 rounding, a bf16 LM head)engine mismatchdense, larger on unlikely tokenslogit magnitudeFP32 LM head; fp16 on both sides (Qi et al. 2025)
Quantised rollout (FP8/INT8 weights, low-bit KV cache)engine mismatchdense plus systematicaggressiveness of the formatthe same quantisation on both sides; score centering
MoE routing; any discrete top-k inside the network (sparse-attention indexers)engine mismatchsparse heavy taillayers, near-tied scoresrouting 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 mismatchsystematic offset; with hard truncation also support violation (qv=0<pvq_v=0<p_v, which no IS weight can correct)length, linearlythe same transform on both sides; keep the sampling mask
Re-tokenised text, chat-template driftnot a ratio — a different sequencebug—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 μ\mu.

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 πold\pi_{\text{old}} 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 π\pi using samples from μ\mu.

Ey∼π[f(y)]=∑yπ(y)f(y)=∑yμ(y)π(y)μ(y)f(y)=Ey∼μ[w(y) f(y)],w=πμ\mathbb{E}_{y\sim\pi}[f(y)]=\sum_y\pi(y)f(y)=\sum_y\mu(y)\frac{\pi(y)}{\mu(y)}f(y)=\mathbb{E}_{y\sim\mu}\big[w(y)\,f(y)\big],\qquad w=\frac{\pi}{\mu}

It is exact as long as μ(y)>0\mu(y)>0 wherever π(y)>0\pi(y)>0. The estimator I^=1n∑iwifi\hat I=\frac1n\sum_i w_if_i is unbiased. The problem is the variance.

Var⁡μ[wf]=Eμ[w2f2]−(Eπf)2,Eμ[w2]=∑yπ(y)2μ(y)=1+χ2(π ∥ μ)\operatorname{Var}_\mu[w f]=\mathbb{E}_\mu[w^2f^2]-\big(\mathbb{E}_\pi f\big)^2,\qquad \mathbb{E}_\mu[w^2]=\sum_y\frac{\pi(y)^2}{\mu(y)}=1+\chi^2(\pi\,\|\,\mu)

If there are places where μ\mu gives much smaller probability than π\pi, π2/μ\pi^2/\mu explodes. The effective sample size (ESS), which summarises the spread of the weights, is

ESS=(∑iwi)2∑iwi2 ≈ n1+χ2(π∥μ)\text{ESS}=\frac{\big(\sum_i w_i\big)^2}{\sum_i w_i^2}\ \approx\ \frac{n}{1+\chi^2(\pi\|\mu)}

Even if you drew nn 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 ww to min⁡(w,C)\min(w, C). The variance is bounded by C2 E[f2]/nC^2\,\mathbb{E}[f^2]/n, but a bias equal to the truncated mass Eμ[(w−C)+f]\mathbb{E}_\mu[(w-C)_+f] appears. If f≥0f\ge0, it always skews downward.
  • Self-normalised IS (SNIS). I^=∑iwifi/∑iwi\hat I=\sum_iw_if_i/\sum_iw_i. It has O(1/n)O(1/n) bias but is consistent, and since the estimate always stays within the range of ff it is less swayed by extreme values.

PPO와 GRPO는 on-policy 알고리즘으로 소개된다. 지금 정책으로 샘플을 뽑고, 그 샘플로 지금 정책을 고친다. 그런데 실제 LLM RL 시스템에서 샘플을 만든 분포와 gradient를 계산하는 분포가 정확히 같은 경우는 거의 없다. 둘이 다르면 gradient가 편향되고, 그 편향이 학습 내내 쌓이면 어느 순간 보상이 무너진다. 이 레슨은 그 차이가 어디서 오는지, 통계학의 importance sampling이 그것을 어떻게 다루는지, 그리고 왜 LLM에서는 교과서 그대로의 보정이 통하지 않는지를 본다.

샘플은 어디서 오는가

세 개의 분포를 구분하자.

  • μ\mu: 실제로 토큰을 샘플한 분포. 추론 엔진(vLLM, SGLang)이 샘플 시점의 가중치로 계산한 확률이다.
  • πold\pi_{\text{old}}: 학습 엔진(FSDP, Megatron)이 같은 가중치로 다시 계산한 확률. PPO ratio의 분모다.
  • πθ\pi_\theta: 지금 업데이트 중인 정책.

우리가 원하는 gradient는 πθ\pi_\theta에 대한 기대값이지만 샘플은 μ\mu에서 왔다. 둘의 비는 두 조각으로 나뉜다.

πθ(yt∣ht)μ(yt∣ht)=πθ(yt∣ht)πold(yt∣ht)⏟ρt: PPO ratio⋅πold(yt∣ht)μ(yt∣ht)⏟엔진 불일치 (+ staleness)\frac{\pi_\theta(y_t\mid h_t)}{\mu(y_t\mid h_t)}=\underbrace{\frac{\pi_\theta(y_t\mid h_t)}{\pi_{\text{old}}(y_t\mid h_t)}}_{\rho_t:\ \text{PPO ratio}}\cdot\underbrace{\frac{\pi_{\text{old}}(y_t\mid h_t)}{\mu(y_t\mid h_t)}}_{\text{엔진 불일치 (+ staleness)}}

차이가 생기는 원인은 세 가지다.

  1. 여러 번의 업데이트. 한 배치로 minibatch 여러 개, epoch 여러 번을 돌면 두 번째 업데이트부터 πθ≠πold\pi_\theta\ne\pi_{\text{old}}다. PPO의 clip이 다루는 것이 이 차이다.
  2. 비동기 rollout과 staleness. 앞 레슨의 비동기 시스템에서는 샘플러의 가중치가 학습기보다 몇 버전 뒤처져 있다. 학습기가 πold\pi_{\text{old}}를 현재 가중치로 다시 계산하면 두 번째 조각에 staleness가 섞인다.
  3. 엔진 간 수치 차이. 가중치가 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 여러 번ρt=πθ/πold\rho_t=\pi_\theta/\pi_{\text{old}}정책과 함께 움직인다. 사이의 gradient에 달려 있어 시퀀스마다 다르다샘플 이후의 업데이트 수PPO clip, epoch 줄이기, 시퀀스별 mask(clipping과 IS)
one-step-off와 완전 비동기 rolloutstaleness(πold\pi_{\text{old}}를 rollout weight에서 다시 계산하지 않으면 πold/μ\pi_{\text{old}}/\mu 안에 섞인다)체계적, 스스로 증폭버전 차이decoupled PPO, ESS로 촉발하는 재동기화(비동기 RL)
partial rollout(trajectory 중간에 weight 교체)둘 다, 한 시퀀스 안에서 구간별로섞임교체 횟수토큰별 버전 태그, 토큰 단위 보정
batch 모양에 따라 바뀌는 reduction 순서엔진 불일치조밀한 잡음길이(T\sqrt T)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 위반도(qv=0<pvq_v=0<p_v, 어떤 IS 가중치로도 보정 불가)길이, 선형으로양쪽에 같은 변환, sampling mask 유지
다시 tokenize한 텍스트, chat template 차이ratio가 아니라 다른 시퀀스버그—token-in-token-out(Agent RL)

speculative decoding은 흔한 오해의 대상이다. 정확한(lossless) 검증을 쓰면 수락된 토큰은 target 모델의 분포를 따르므로, 정책보다 뒤처진 draft 모델은 정확성이 아니라 수락률을 깎는다(speculative decoding). 완화된 수락 규칙만 μ\mu를 바꾼다.

여기서 습관 셋이 나온다. 원인들은 한 ratio 안에서 겹친다. TP-4 엔진의 FP8 rollout을 TP-1 trainer와 PPO 4 epoch로 학습하면 정밀도, 병렬화, staleness 항을 한꺼번에 낸다. 따로 재자. trainer로 rollout weight에서 πold\pi_{\text{old}}를 다시 계산해(verl의 decoupled 모드, DLC의 추가 forward) 엔진 인자와 staleness 인자를 가르고, 알고리즘을 탓하기 전에 같은 checkpoint 배치로 엔진 인자만 시험하자. 크기가 전부는 아니다. 지속적이고 weight와 함께 갱신되는 작은 차이가, 평균으로 사라지는 더 큰 차이보다 긴 실행에서 더 큰 해를 끼칠 수 있다. score centering의 주제다.

Importance sampling

π\pi에 대한 기대값을 μ\mu의 샘플로 구하는 항등식에서 출발한다.

Ey∼π[f(y)]=∑yπ(y)f(y)=∑yμ(y)π(y)μ(y)f(y)=Ey∼μ[w(y) f(y)],w=πμ\mathbb{E}_{y\sim\pi}[f(y)]=\sum_y\pi(y)f(y)=\sum_y\mu(y)\frac{\pi(y)}{\mu(y)}f(y)=\mathbb{E}_{y\sim\mu}\big[w(y)\,f(y)\big],\qquad w=\frac{\pi}{\mu}

μ(y)>0\mu(y)>0인 곳에서 π(y)>0\pi(y)>0이기만 하면 정확하다. 추정량 I^=1n∑iwifi\hat I=\frac1n\sum_i w_if_i는 불편이다. 문제는 분산이다.

Var⁡μ[wf]=Eμ[w2f2]−(Eπf)2,Eμ[w2]=∑yπ(y)2μ(y)=1+χ2(π ∥ μ)\operatorname{Var}_\mu[w f]=\mathbb{E}_\mu[w^2f^2]-\big(\mathbb{E}_\pi f\big)^2,\qquad \mathbb{E}_\mu[w^2]=\sum_y\frac{\pi(y)^2}{\mu(y)}=1+\chi^2(\pi\,\|\,\mu)

μ\mu가 π\pi보다 훨씬 작은 확률을 주는 곳이 있으면 π2/μ\pi^2/\mu가 폭발한다. 가중치의 퍼짐을 요약하는 유효 표본 수(effective sample size) 는

ESS=(∑iwi)2∑iwi2 ≈ n1+χ2(π∥μ)\text{ESS}=\frac{\big(\sum_i w_i\big)^2}{\sum_i w_i^2}\ \approx\ \frac{n}{1+\chi^2(\pi\|\mu)}

이다. 표본 nn개를 뽑았어도 가중치가 몇 개에 몰리면 실제로는 그 몇 개만큼의 정보다.

분산을 줄이는 두 가지 고전적 방법이 있다.

  • Truncated IS (TIS). ww를 min⁡(w,C)\min(w, C)로 자른다. 분산은 C2 E[f2]/nC^2\,\mathbb{E}[f^2]/n 이하로 묶이지만, 잘린 질량 Eμ[(w−C)+f]\mathbb{E}_\mu[(w-C)_+f]만큼 편향이 생긴다. f≥0f\ge0이면 항상 아래로 치우친다.
  • Self-normalized IS (SNIS). I^=∑iwifi/∑iwi\hat I=\sum_iw_if_i/\sum_iw_i. O(1/n)O(1/n)의 편향이 있지만 일치 추정량이고, 추정값이 항상 ff의 범위 안에 있어 극단값에 덜 휘둘린다.
χ²(π‖μ) – ESS/n ≈ 1/(1+χ²) – max w –
Top left: the target policy π (blue bars) and the behaviour policy μ that produced the samples (orange line); the dots are the function f to be estimated. Top right: the distribution of weights w = π/μ for samples drawn from μ (log axis, vertical line = cap C). Bottom: estimates from repeating the same experiment 300 times. The black vertical line is the true value Eπ[f]. Increase the mismatch and the weight tail lengthens while the plain-IS dots spread widely. Decrease C and the variance of TIS shrinks, but the centre of its dots is pushed away from the true value (bias). SNIS has small bias and stable variance, but its bias becomes visible when n is small. 왼쪽 위: 목표 정책 π(파랑 막대)와 샘플을 만든 행동 정책 μ(주황 선), 점은 추정할 함수 f. 오른쪽 위: μ에서 뽑은 표본의 가중치 w = π/μ 분포(로그 축, 세로선 = cap C). 아래: 같은 실험을 300번 반복해 얻은 추정값들. 검은 세로선이 참값 Eπ[f]다. 불일치를 키우면 가중치 꼬리가 길어지고 plain IS의 점들이 넓게 퍼진다. C를 줄이면 TIS의 분산은 줄지만 점들의 중심이 참값에서 밀려난다(편향). SNIS는 편향이 작고 분산도 안정적이지만 n이 작을 때 편향이 보인다.
  1. With the mismatch at 0 the three estimators coincide (w≡1w\equiv1). Raise it to about 1 and χ2\chi^2 exceeds 1; the plain IS dots begin to spread.
  2. 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.
  3. 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.

W(y)=π(y∣x)μ(y∣x)=∏t=1Tρt,log⁡W=∑t=1Tδt,δt=log⁡π(yt∣ht)μ(yt∣ht)W(y)=\frac{\pi(y\mid x)}{\mu(y\mid x)}=\prod_{t=1}^{T}\rho_t,\qquad \log W=\sum_{t=1}^{T}\delta_t,\quad \delta_t=\log\frac{\pi(y_t\mid h_t)}{\mu(y_t\mid h_t)}

Suppose the δt\delta_t are independent and normal with mean −σ2/2-\sigma^2/2 and variance σ2\sigma^2 (with this mean, E[eδt]=1\mathbb{E}[e^{\delta_t}]=1, so a single token is unbiased). Then log⁡W∼N(−Tσ2/2, Tσ2)\log W\sim\mathcal{N}(-T\sigma^2/2,\ T\sigma^2), and from the moments of the log-normal distribution

E[W]=1,E[W2]=eTσ2,ESSn=e−Tσ2\mathbb{E}[W]=1,\qquad \mathbb{E}[W^2]=e^{T\sigma^2},\qquad \frac{\text{ESS}}{n}=e^{-T\sigma^2}

Even with a per-token log-prob difference as small as σ=0.08\sigma=0.08, at T=1000T=1000 the ESS is e−6.4≈0.002e^{-6.4}\approx0.002 — 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.

  1. 불일치를 0으로 두면 세 추정량이 같다(w≡1w\equiv1). 1 정도로 올리면 χ2\chi^2가 1을 넘고 plain IS의 점들이 퍼지기 시작한다.
  2. C를 1까지 내리면 TIS의 점들은 촘촘해지지만 중심이 참값(검은 선)에서 왼쪽으로 밀려난다. C를 20까지 올리면 plain IS와 같아진다. 중간 어딘가에서 RMSE가 최소다.
  3. 불일치를 2 이상으로 올리고 n을 줄여 보자. 오른쪽 위 가중치 분포의 빨간 부분(C를 넘는 가중치)이 확률은 작지만 값이 크다. plain IS의 추정값 몇 개가 멀리 튀는 이유다.

토큰과 시퀀스: 곱이 터진다

LLM에서 “샘플”은 토큰 시퀀스다. 시퀀스 전체의 확률비는 토큰 ratio의 곱이다.

W(y)=π(y∣x)μ(y∣x)=∏t=1Tρt,log⁡W=∑t=1Tδt,δt=log⁡π(yt∣ht)μ(yt∣ht)W(y)=\frac{\pi(y\mid x)}{\mu(y\mid x)}=\prod_{t=1}^{T}\rho_t,\qquad \log W=\sum_{t=1}^{T}\delta_t,\quad \delta_t=\log\frac{\pi(y_t\mid h_t)}{\mu(y_t\mid h_t)}

δt\delta_t가 서로 독립이고 평균 −σ2/2-\sigma^2/2, 분산 σ2\sigma^2인 정규분포라고 하자(평균을 이렇게 잡으면 E[eδt]=1\mathbb{E}[e^{\delta_t}]=1로 토큰 하나는 불편이다). 그러면 log⁡W∼N(−Tσ2/2, Tσ2)\log W\sim\mathcal{N}(-T\sigma^2/2,\ T\sigma^2)이고 로그정규분포의 모멘트에서

E[W]=1,E[W2]=eTσ2,ESSn=e−Tσ2\mathbb{E}[W]=1,\qquad \mathbb{E}[W^2]=e^{T\sigma^2},\qquad \frac{\text{ESS}}{n}=e^{-T\sigma^2}

이다. 토큰당 log-prob 차이가 σ=0.08\sigma=0.08 정도로 작아도 T=1000T=1000이면 ESS가 e−6.4≈0.002e^{-6.4}\approx0.002, 표본 1000개 중 2개 꼴이다. 추론 모델의 응답은 수천에서 수만 토큰이다. 시퀀스 단위의 정확한 IS는 LLM에서 사실상 쓸 수 없다.

std(log wseq) – wseq ∈ [½, 2] 비율fraction – ESS/n: 시퀀스sequence – · 토큰token – · 기하평균geometric mean –
Suppose that at every token the log-prob difference δt between the training engine and the inference engine arises as small noise. Left: the cumulative log10 Πtρt of 24 sequences (red) and the geometric-mean ratio (green, GSPO-style). The dotted lines are ratios 2 and ½. Drag T and the red lines spread as √T, so the sequence ratio becomes tens or hundreds of times off. Right: the effective sample fraction ESS/n as a function of length. Sequence-level collapses as e−Tσ², token-level does not depend on length, and the geometric mean actually goes to 1 (but it is not an exact IS correction). 토큰마다 학습 엔진과 추론 엔진의 log-prob 차이 δt가 작은 잡음으로 생긴다고 하자. 왼쪽: 시퀀스 24개의 누적 log10 Πtρt(빨강)와 기하평균 ratio(초록, GSPO식). 점선은 ratio 2와 ½. T를 끌어 보면 빨간 선들이 √T로 퍼져 시퀀스 ratio가 수십·수백 배가 된다. 오른쪽: 길이에 따른 유효 표본 비율 ESS/n. 시퀀스 단위는 e−Tσ²로 무너지고, 토큰 단위는 길이와 무관하며, 기하평균은 오히려 1로 간다(대신 정확한 IS 보정이 아니다).
  1. Drag T from 10 to 1000. The red line (sequence ratio) spreads as T\sqrt T and mostly leaves the dashed band [½, 2]. The green line (geometric mean) does the opposite and gathers at 1 (log 0).
  2. 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.
  3. 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 tt, ∇log⁡πθ(yt∣ht)\nabla\log\pi_\theta(y_t\mid h_t), is multiplied by that token’s ratio only. This corrects only the difference in the distribution of “which token was chosen in state hth_t” and ignores the difference in “the probability of reaching state hth_t” (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 Eh∼dπold[ρtA^t]\mathbb{E}_{h\sim d^{\pi_{\text{old}}}}[\rho_t\hat A_t] keeps the state distribution of πold\pi_{\text{old}} 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 s=W1/Ts=W^{1/T} sits in between. The variance of log⁡s\log s is σ2/T\sigma^2/T, 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.

MethodWhat it doesUnit
PPO clipturns off the gradient in that direction when ρt=πθ/πold\rho_t=\pi_\theta/\pi_{\text{old}} is outside [1−ε,1+ε][1-\varepsilon,1+\varepsilon]token
TIS (Yao et al.)multiplies the loss by sg⁡[min⁡(πold/μ, C)]\operatorname{sg}\big[\min(\pi_{\text{old}}/\mu,\ C)\big] to correct the engine mismatchtoken
Masked IS / IcePopdiscards the gradient of tokens whose engine ratio is outside a band [α,β][\alpha,\beta] (IcePop uses [0.5,5][0.5, 5])token
Sequence-level TIS/MIStruncates by the sequence ratio (or its geometric mean), or drops whole sequences above a thresholdsequence
CISPO (MiniMax-M1)instead of clipping the update, clips the IS weight and multiplies it as a stop-gradient. Every token receives gradienttoken
GSPOclips with a length-normalised sequence ratiosequence

TIS plays a different role from PPO’s clip. The clip is a trust region that keeps πθ\pi_\theta from moving too far from πold\pi_{\text{old}}; TIS is a correction factor between πold\pi_{\text{old}} and μ\mu. So the two are multiplied and used together.

Lt=−sg⁡[min⁡(πold(yt)μ(yt), C)]⋅min⁡(ρtA^t, clip⁡(ρt,1−ε,1+ε)A^t)\mathcal{L}_t=-\operatorname{sg}\Big[\min\Big(\frac{\pi_{\text{old}}(y_t)}{\mu(y_t)},\,C\Big)\Big]\cdot\min\big(\rho_t\hat A_t,\ \operatorname{clip}(\rho_t,1-\varepsilon,1+\varepsilon)\hat A_t\big)

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 sg⁡[r^t] A^tlog⁡πθ(yt)\operatorname{sg}[\hat r_t]\,\hat A_t\log\pi_\theta(y_t) and clips only the weight r^t\hat r_t.

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.

확인 문제Check yourself

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?

ESS/n=e−Tσ2=e−2000×0.0025=e−5≈0.0067\text{ESS}/n=e^{-T\sigma^2}=e^{-2000\times0.0025}=e^{-5}\approx0.0067. 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.

NumPy Bias and variance of IS / TIS / SNIS
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.

NumPy Product of token ratios: collapse 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.

PyTorch PyTorch: PPO loss with TIS / masked IS, and mismatch diagnostics 로컬에서 실행run locally (pip install torch)
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.

확인 문제Check yourself

In PPO you build the ratio by recomputing π_old with the training engine. Which difference does this ratio alone not correct?

The PPO ratio ρt=πθ/πold\rho_t=\pi_\theta/\pi_{\text{old}} measures only how far the policy has moved within the training engine. Since the samples came from μ\mu, the true correction factor is πθ/μ=ρt⋅(πold/μ)\pi_\theta/\mu=\rho_t\cdot(\pi_{\text{old}}/\mu), 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 πold\pi_{\text{old}} and uses μ\mu 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 μ\mu (the inference engine), while the gradient is taken with respect to πθ\pi_\theta (the training engine). The ratio splits into the PPO ratio × (engine mismatch + staleness).
  • IS is unbiased but its variance is proportional to 1+χ21+\chi^2, summarised as ESS ≈n/(1+χ2)\approx n/(1+\chi^2). 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 e−Tσ2e^{-T\sigma^2}. 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 log⁡πold−log⁡μ\log\pi_{\text{old}}-\log\mu, 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.
  1. T를 10에서 1000으로 끌어 보자. 빨간 선(시퀀스 ratio)은 T\sqrt T로 퍼져 점선 [½, 2] 밖으로 대부분 나간다. 초록 선(기하평균)은 반대로 1(로그 0)로 모인다.
  2. 오른쪽에서 시퀀스 단위 ESS(빨강)는 T가 커지면 지수적으로 0이 되고, 토큰 단위(파랑)는 길이와 무관하다.
  3. “두꺼운 꼬리”를 켜면 대부분 토큰은 거의 일치하고 3%만 크게 다르다. 평균 잡음은 오히려 작은데 토큰 단위 ESS도 나빠진다. 실제 불일치가 이런 모양이다.

그래서 실전의 보정은 대부분 토큰 단위다. 토큰 tt의 gradient 항 ∇log⁡πθ(yt∣ht)\nabla\log\pi_\theta(y_t\mid h_t)에 그 토큰의 ratio만 곱한다. 이것은 “상태 hth_t에서 어떤 토큰을 골랐는가”의 분포 차이만 보정하고 “그 상태 hth_t에 도달할 확률”의 차이(앞쪽 토큰들의 ratio 곱)는 무시하므로 편향이 있다. 대신 분산이 길이와 무관하다. PPO가 원래 하던 일이 정확히 이것이다. PPO의 surrogate Eh∼dπold[ρtA^t]\mathbb{E}_{h\sim d^{\pi_{\text{old}}}}[\rho_t\hat A_t]는 상태 분포를 πold\pi_{\text{old}}의 것으로 두고, 두 정책이 가까우면 그 차이가 작다는 trust region 논리(TRPO의 bound)로 이 편향을 정당화한다. 같은 논리가 엔진 불일치에도 적용된다. 두 분포가 충분히 가까울 때만 토큰 단위 보정이 맞다.

GSPO의 기하평균 ratio s=W1/Ts=W^{1/T}는 그 중간이다. log⁡s\log s의 분산이 σ2/T\sigma^2/T라 길어도 폭발하지 않지만, 정확한 IS 가중치는 아니다. 응답 전체가 얼마나 움직였는지를 재는 길이 정규화된 거리로 보고 clip에 쓰는 것이다.

실전의 보정들

이 그림 위에 최근 방법들을 놓으면 이렇다.

방법무엇을 하나단위
PPO clipρt=πθ/πold\rho_t=\pi_\theta/\pi_{\text{old}}가 [1−ε,1+ε][1-\varepsilon,1+\varepsilon] 밖이면 그 방향 gradient를 끈다토큰
TIS (Yao et al.)손실에 sg⁡[min⁡(πold/μ, C)]\operatorname{sg}\big[\min(\pi_{\text{old}}/\mu,\ C)\big]를 곱해 엔진 불일치를 보정토큰
Masked IS / IcePop엔진 ratio가 밴드 [α,β][\alpha,\beta] 밖인 토큰은 gradient를 버린다 (IcePop은 [0.5,5][0.5, 5])토큰
시퀀스 단위 TIS/MIS시퀀스 ratio(또는 그 기하평균)로 자르거나, 기준을 넘는 시퀀스를 통째로 버린다시퀀스
CISPO (MiniMax-M1)업데이트를 clip하지 않고 IS 가중치를 clip해 stop-gradient로 곱한다. 모든 토큰이 gradient를 받는다토큰
GSPO길이 정규화된 시퀀스 ratio로 clip시퀀스

TIS는 PPO의 clip과 역할이 다르다. clip은 πθ\pi_\theta가 πold\pi_{\text{old}}에서 너무 멀어지지 않게 하는 trust region이고, TIS는 πold\pi_{\text{old}}와 μ\mu 사이의 보정 계수다. 그래서 둘을 곱해 함께 쓴다.

Lt=−sg⁡[min⁡(πold(yt)μ(yt), C)]⋅min⁡(ρtA^t, clip⁡(ρt,1−ε,1+ε)A^t)\mathcal{L}_t=-\operatorname{sg}\Big[\min\Big(\frac{\pi_{\text{old}}(y_t)}{\mu(y_t)},\,C\Big)\Big]\cdot\min\big(\rho_t\hat A_t,\ \operatorname{clip}(\rho_t,1-\varepsilon,1+\varepsilon)\hat A_t\big)

CISPO는 다른 문제의식에서 나왔다. MiniMax-M1 보고서는 “However”, “Wait” 같은 반성 토큰이 저확률이라 첫 업데이트 뒤 ratio가 커져 clip에 걸리고, 이후 업데이트에서 gradient를 잃는다고 지적한다. 그래서 REINFORCE 형태 sg⁡[r^t] A^tlog⁡πθ(yt)\operatorname{sg}[\hat r_t]\,\hat A_t\log\pi_\theta(y_t)를 쓰고 가중치 r^t\hat r_t만 자른다.

어느 보정이 나은지는 아직 정리되지 않았다. 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, 지표로 실패를 읽는 법은 안정화 플레이북.

확인 문제Check yourself

응답 길이가 평균 2,000 토큰이고 토큰당 엔진 간 log-prob 차이의 표준편차가 0.05라고 하자(독립, 정규 가정). 시퀀스 단위 정확한 IS의 ESS/n은 대략 얼마인가?

ESS/n=e−Tσ2=e−2000×0.0025=e−5≈0.0067\text{ESS}/n=e^{-T\sigma^2}=e^{-2000\times0.0025}=e^{-5}\approx0.0067. 가중치의 평균이 1이라는 것(불편성)과 분산이 작다는 것은 전혀 다른 이야기다. 표본 1000개 중 7개 정도만 실질적으로 쓰이는 셈이다. 그래서 실전에서는 토큰 단위 보정(편향을 감수)이나 길이 정규화된 시퀀스 ratio를 쓴다.

직접 해 보기

그림과 같은 이산 공간에서 plain IS, TIS, SNIS를 2000번씩 반복해 bias, std, RMSE를 잰다. 그다음 cap C를 바꿔 가며 bias–variance trade-off를 본다.

NumPy IS / TIS / SNIS의 bias와 분산
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의 곱이 길이에 따라 어떻게 무너지는지다.

NumPy 토큰 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 형태다.

PyTorch PyTorch: TIS / masked IS가 들어간 PPO 손실과 불일치 진단 로컬에서 실행run locally (pip install torch)
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 보고서는 상한만 조정한다고 밝혔지만 이 레슨에서 특정 값을 권하지는 않는다.

확인 문제Check yourself

PPO에서 π_old를 학습 엔진으로 다시 계산해 ratio를 만들고 있다. 이 ratio만으로 보정되지 않는 차이는?

PPO ratio ρt=πθ/πold\rho_t=\pi_\theta/\pi_{\text{old}}는 학습 엔진 안에서 정책이 움직인 만큼만 잰다. 샘플은 μ\mu에서 왔으므로 진짜 보정 계수는 πθ/μ=ρt⋅(πold/μ)\pi_\theta/\mu=\rho_t\cdot(\pi_{\text{old}}/\mu)이고, 두 번째 조각은 PPO가 보지 못한다. TIS, masked IS 같은 방법이 이 조각에 곱하는 계수다. 반대로 학습기가 πold\pi_{\text{old}}를 다시 계산하지 않고 μ\mu를 그대로 분모로 쓰면 두 조각이 섞인 ratio 하나로 clip하게 된다.

정리

  • LLM RL의 샘플은 μ\mu(추론 엔진)에서 오고 gradient는 πθ\pi_\theta(학습 엔진)에 대해 구한다. 비는 PPO ratio × (엔진 불일치 + staleness)로 나뉜다.
  • IS는 불편이지만 분산이 1+χ21+\chi^2에 비례하고, ESS ≈n/(1+χ2)\approx n/(1+\chi^2)로 요약된다. TIS는 cap으로 분산을 묶는 대신 편향을, SNIS는 작은 편향으로 안정성을 얻는다.
  • 시퀀스 ratio는 토큰 ratio의 곱이라 ESS가 e−Tσ2e^{-T\sigma^2}로 무너진다. 그래서 실전 보정은 토큰 단위(편향 감수)이거나 길이 정규화된 시퀀스 ratio다.
  • TIS, IcePop, CISPO, GSPO는 가중치를 자를지, 토큰을 버릴지, 단위를 무엇으로 할지의 선택이다. batch-invariant 커널, LM head 정밀도, routing replay는 원인을 줄인다.
  • log⁡πold−log⁡μ\log\pi_{\text{old}}-\log\mu의 분포, k1·k3 KL, 밴드 밖 비율, ESS를 위치·turn·확률 구간별로 기록한다. 표본 ESS는 꼬리가 나쁠 때 낙관적이다.

더 읽을거리Further reading