Track IX · Frontier RL: Algorithms & Stability · 07/10

학습–추론 불일치 엔지니어링Engineering away the training–inference mismatch

같은 weight인데 rollout 엔진과 trainer의 log-prob가 다른 원인을 통계적 모양(조밀한 잡음, 드문 큰 점프, 체계적 오프셋)으로 나누고, 각 모양이 긴 시퀀스에서 어떻게 쌓이는지 유도한다. FP32 LM head, batch-invariant kernel과 bit-exact rollout, routing replay(R2/R3·Keep Routing), Keep Sampling Mask와 processed log-prob, 같은 양자화, score centering과 IS 보정이 각각 무엇을 없애고 무엇을 남기는지, 비용과 함께 본다.Sort the reasons why the rollout engine and the trainer disagree on log-probs at identical weights by their statistical shape — dense noise, rare large jumps, systematic offsets — and derive how each shape accumulates over long sequences. Then see what each fix removes and what it leaves, with its cost — FP32 LM head, batch-invariant kernels and bit-exact rollout, routing replay (R2/R3, Keep Routing), Keep Sampling Mask and processed log-probs, matched quantisation, score centering and IS corrections.

The training–inference mismatch lesson set up the statistics: the sampled tokens come from the inference engine’s μ\mu, the gradient is taken through the trainer’s π\pi, and importance sampling with its ESS tells you how much a gap costs. The previous lesson handled the part of the gap that comes from stale weights. This lesson is about the part that remains at identical weights — and about engineering it away rather than correcting for it.

Write the per-token gap of a sampled token as

δt=log⁡πtrain(yt∣ht)−log⁡πinfer(yt∣ht).\delta_t=\log\pi_{\text{train}}(y_t\mid h_t)-\log\pi_{\text{infer}}(y_t\mid h_t).

Every source in this lesson produces some distribution of δt\delta_t. What matters for training is not its average size but its shape, because the shape decides how it accumulates over a 30,000-token trajectory and which correction can possibly work. The kernel-level mechanics (how a batch-invariant matmul or a split-KV attention kernel is built) live in inference for RL; the objectives that clip or mask ratios live in clipping and IS.

Three shapes, three growth laws

Dense zero-mean noise. Floating-point rounding in a different order, a different attention kernel, a bf16 head: almost every token gets a small δt\delta_t of random sign. Over a sequence of length TT the sum ST=∑tδtS_T=\sum_t\delta_t has mean ≈0\approx0 and standard deviation σT\sigma\sqrt T. Token-level ratios stay near 1; any per-token correction works.

Sparse heavy tail. An MoE token whose expert set flips, a top-kk indexer that picks a different token: a small fraction qq of tokens gets a large δt\delta_t, the rest nothing. The probability that a sequence contains at least one such token is 1−(1−q)T≈1−e−qT1-(1-q)^T\approx1-e^{-qT} — with q=2%q=2\%, 41% of 256-token sequences and essentially every 2,048-token sequence. A per-token mask removes a few tokens; a sequence-level rule that reacts to any outlier removes almost every long sequence.

Systematic offset. The trainer and the sampler compute different distributions — a top-p nucleus versus the full vocabulary, a temperature applied on one side only. Then E[δt]=−c≠0\mathbb{E}[\delta_t]=-c\neq0 and E[ST]=−cT\mathbb{E}[S_T]=-cT grows linearly. A per-token offset of 0.035 nats is invisible token by token and is e−72e^{-72} in the sequence ratio at T=2,048T=2{,}048.

There is a further trap in the third shape. The usual monitor k3=Eμ[eδ−1−δ]k_3=\mathbb{E}_\mu[e^{\delta}-1-\delta] is an unbiased estimate of KL(μ∥π)\mathrm{KL}(\mu\|\pi) only if Eμ[eδ]=Eμ[π/μ]=1\mathbb{E}_\mu[e^\delta]=\mathbb{E}_\mu[\pi/\mu]=1, i.e. only if π\pi puts no mass where μ\mu puts none. Top-p breaks exactly that: if the sampler keeps a nucleus SS with mass Z=∑v∈Sπ(v)Z=\sum_{v\in S}\pi(v), then μ(y)=π(y)/Z\mu(y)=\pi(y)/Z on SS and

δt=log⁡Zt≤0,k1=−E[δ]=E[−log⁡Z]≈1−Zˉ,k3=E[Z−1−log⁡Z]≈12E[(1−Z)2]≈12k12.\delta_t=\log Z_t\le0,\qquad k_1=-\mathbb{E}[\delta]=\mathbb{E}[-\log Z]\approx1-\bar Z,\qquad k_3=\mathbb{E}[Z-1-\log Z]\approx\tfrac12\mathbb{E}[(1-Z)^2]\approx\tfrac12k_1^2 .

With 1−Z≈0.0351-Z\approx0.035 the honest k1k_1 is 0.035 and k3k_3 reports about 6×10−46\times10^{-4} — a fifty-fold under-report, from the monitor most dashboards plot. (The NumPy block below measures k1=3.5×10−2k_1=3.5\times10^{-2}, k3=7×10−4k_3=7\times10^{-4}.)

학습–추론 불일치 레슨은 통계의 틀을 세웠다. 샘플된 토큰은 추론 엔진의 μ\mu에서 오고, gradient는 trainer의 π\pi를 통과하며, importance sampling과 ESS가 차이의 비용을 알려 준다. 이전 레슨은 그 차이 중 낡은 weight에서 오는 부분을 다뤘다. 이 레슨은 weight가 똑같을 때 남는 부분에 관한 것이고, 그것을 보정하기보다 엔지니어링으로 없애는 이야기다.

샘플된 토큰의 토큰별 차이를

δt=log⁡πtrain(yt∣ht)−log⁡πinfer(yt∣ht)\delta_t=\log\pi_{\text{train}}(y_t\mid h_t)-\log\pi_{\text{infer}}(y_t\mid h_t)

로 쓰자. 이 레슨의 모든 원인은 δt\delta_t의 어떤 분포를 만든다. 학습에 중요한 것은 평균 크기가 아니라 모양이다. 모양이 30,000 토큰 trajectory에서 어떻게 쌓이는지, 어떤 보정이 통할 수 있는지를 정하기 때문이다. kernel 수준의 메커니즘(batch-invariant matmul이나 split-KV attention kernel을 어떻게 만드는지)은 RL을 위한 추론에, ratio를 clip하거나 mask하는 목적함수는 clipping과 IS에 있다.

세 가지 모양, 세 가지 성장 법칙

조밀한 평균 0 잡음. 다른 순서의 부동소수점 반올림, 다른 attention kernel, bf16 head. 거의 모든 토큰이 부호가 무작위인 작은 δt\delta_t를 받는다. 길이 TT 시퀀스의 합 ST=∑tδtS_T=\sum_t\delta_t는 평균 ≈0\approx0, 표준편차 σT\sigma\sqrt T다. 토큰 ratio는 1 근처에 머물고, 토큰 단위 보정은 무엇이든 통한다.

드문 두꺼운 꼬리. expert 집합이 뒤집힌 MoE 토큰, 다른 토큰을 고른 top-kk indexer. 토큰의 작은 비율 qq가 큰 δt\delta_t를 받고 나머지는 아무것도 받지 않는다. 시퀀스에 그런 토큰이 하나라도 있을 확률은 1−(1−q)T≈1−e−qT1-(1-q)^T\approx1-e^{-qT}다. q=2%q=2\%면 256 토큰 시퀀스의 41%, 2,048 토큰 시퀀스는 사실상 전부다. 토큰 단위 mask는 토큰 몇 개를 지우지만, 이상치 하나에 반응하는 시퀀스 단위 규칙은 긴 시퀀스를 거의 다 지운다.

체계적 오프셋. trainer와 sampler가 다른 분포를 계산한다. top-p nucleus 대 전체 vocabulary, 한쪽에만 적용된 temperature. 그러면 E[δt]=−c≠0\mathbb{E}[\delta_t]=-c\neq0이고 E[ST]=−cT\mathbb{E}[S_T]=-cT가 선형으로 자란다. 토큰당 0.035 nats의 오프셋은 토큰 하나씩 보면 보이지 않지만 T=2,048T=2{,}048에서 시퀀스 ratio로는 e−72e^{-72}다.

세 번째 모양에는 함정이 하나 더 있다. 흔한 모니터 k3=Eμ[eδ−1−δ]k_3=\mathbb{E}_\mu[e^{\delta}-1-\delta]는 Eμ[eδ]=Eμ[π/μ]=1\mathbb{E}_\mu[e^\delta]=\mathbb{E}_\mu[\pi/\mu]=1일 때만, 즉 μ\mu가 질량을 두지 않는 곳에 π\pi도 질량을 두지 않을 때만 KL(μ∥π)\mathrm{KL}(\mu\|\pi)의 불편 추정량이다. top-p가 바로 그것을 깬다. sampler가 질량 Z=∑v∈Sπ(v)Z=\sum_{v\in S}\pi(v)인 nucleus SS를 남기면 SS 위에서 μ(y)=π(y)/Z\mu(y)=\pi(y)/Z이고

δt=log⁡Zt≤0,k1=−E[δ]=E[−log⁡Z]≈1−Zˉ,k3=E[Z−1−log⁡Z]≈12E[(1−Z)2]≈12k12\delta_t=\log Z_t\le0,\qquad k_1=-\mathbb{E}[\delta]=\mathbb{E}[-\log Z]\approx1-\bar Z,\qquad k_3=\mathbb{E}[Z-1-\log Z]\approx\tfrac12\mathbb{E}[(1-Z)^2]\approx\tfrac12k_1^2

이다. 1−Z≈0.0351-Z\approx0.035면 정직한 k1k_1은 0.035인데 k3k_3는 약 6×10−46\times10^{-4}를 보고한다. 대부분의 대시보드가 그리는 모니터가 50배 작게 말하는 것이다. (아래 NumPy 블록은 k1=3.5×10−2k_1=3.5\times10^{-2}, k3=7×10−4k_3=7\times10^{-4}를 잰다.)

원인sources 처방fixes
k1 – k3 – max |δ| – [0.5, 2] 밖outside [0.5, 2] – corr(πtrain, πinfer) – Σδ @ T=16K –
Toy magnitudes, real shapes. Each sampled token gets δ = log πtrain − log πinfer as a sum of the ticked sources: dense zero-mean noise that is larger on unlikely tokens (precision, kernels, FP8), sparse large jumps on the ~2% of tokens whose expert set flips, and a systematic offset log Z ≤ 0 from top-p when the trainer normalises over the full vocabulary. Tokens are drawn from toy softmax distributions; with top-p on, from the kept set renormalised, so πinfer = p/Z ≤ 1 and every readout uses the same two probabilities. Left: histogram of δ on a log-count axis (grey = all sources, no fixes); dashed lines are an IcePop-style band [0.5, 2]. Right, top: the sequence sum Σδ — its std grows as √T, its mean as T. Right, bottom: probability that a sequence contains at least one out-of-band token, and that a V3.2-style sequence mask (mean log(πinfer/πtrain) > 0.01) fires. Tick top-p: k3 barely moves while the sequence mean explodes — then tick its fix. 크기는 장난감, 모양은 실제를 따른다. 샘플된 토큰마다 δ = log πtrain − log πinfer를 체크한 원인들의 합으로 만든다. 조밀한 평균 0 잡음(정밀도·kernel·FP8, 확률 낮은 토큰에서 더 크다), expert 집합이 뒤집힌 약 2% 토큰에만 생기는 드문 큰 점프, 그리고 trainer가 전체 vocabulary로 정규화할 때 top-p가 만드는 체계적 오프셋 log Z ≤ 0이다. 토큰은 장난감 softmax 분포에서 뽑고, top-p를 켜면 남긴 집합을 다시 정규화한 분포에서 뽑으므로 πinfer = p/Z ≤ 1이며 모든 수치가 같은 두 확률을 쓴다. 왼쪽: log 빈도 축의 δ 히스토그램(회색 = 모든 원인, 처방 없음). 점선은 IcePop식 밴드 [0.5, 2]. 오른쪽 위: 시퀀스 합 Σδ — 표준편차는 √T로, 평균은 T로 자란다. 오른쪽 아래: 시퀀스에 밴드 밖 토큰이 하나라도 있을 확률과 V3.2식 sequence mask(mean log(πinfer/πtrain) > 0.01)가 켜질 확률. top-p를 체크해 보면 k3는 거의 그대로인데 시퀀스 평균은 폭발한다. 그다음 그 처방을 체크해 보자.
  1. Default (precision + kernels + routing flips): the black histogram is a narrow spike with thin wings out to ±1 — the wings are the routing flips. Right-top: std grows as √T, the mean stays tiny. Right-bottom: the red curve (≥ 1 out-of-band token) is already near 1 by a few thousand tokens.
  2. Tick routing replay (R3): the wings shrink tenfold, the red curve moves right by an order of magnitude in T. Tick FP32 LM head: the core of the histogram narrows; k3 drops.
  3. Tick top-p 0.95: the histogram shifts slightly left, k3 barely changes, but |mean Σδ| (amber) overtakes the std and grows linearly, and the sequence mask (violet) fires on every sequence at every length. Now tick sampling-mask replay: the offset is gone exactly.
  4. Watch the correlation readout. Dense noise barely moves it; it is a coarse monitor. Count-based metrics (fraction out of band) and the mean of δ are more informative.

Source by source

Precision and the LM head

Round each logit zvz_v with an error ϵv\epsilon_v. The log-softmax of the sampled token changes by

δy=ϵy−∑vπvϵv,Var⁡(δy)=σy2(1−πy)2+∑v≠yπv2σv2.\delta_y=\epsilon_y-\sum_v\pi_v\epsilon_v,\qquad \operatorname{Var}(\delta_y)=\sigma_y^2(1-\pi_y)^2+\sum_{v\ne y}\pi_v^2\sigma_v^2 .

Two consequences. A confident token (πy→1\pi_y\to1) is almost immune; an unlikely token absorbs its own rounding error in full. That is why measured mismatch concentrates on low-probability tokens (Liu, Li et al.), which are also the exploratory tokens RL most wants to adjust. And the rounding error of a float is proportional to its magnitude (ulp(z)∝∣z∣\text{ulp}(z)\propto|z|), so large logits mean large errors even though softmax is shift-invariant. MiniMax-M1 traced its mismatch — a training/inference probability correlation stuck around 0.9x and a reward that would not rise — to high-magnitude activations in the LM head; computing the head in FP32 raised the correlation to 0.99x. ScaleRL adopted the same fix in both generator and trainer and reports the fitted asymptotic performance rising from 0.52 to 0.61; it is in its final recipe. Not every stack is dominated by the head: in Liu, Li et al.’s vLLM setup an FP32 lm_head made no visible difference, and MAI-Base-2 reports that keeping both sides in bf16 gave a much smaller and more stable gap than lower precision. Measure which source dominates before paying for a fix.

NumPy LM-head precision: bf16 rounding, logit magnitude, and who absorbs the error
import numpy as np
rng = np.random.default_rng(0)

def bf16(x):
    """Round float32 to bfloat16 (8-bit mantissa), round-to-nearest-even, returned as float32."""
    b = np.ascontiguousarray(x, dtype=np.float32).view(np.uint32)
    b = (b + np.uint32(0x7FFF) + ((b >> np.uint32(16)) & np.uint32(1))) & np.uint32(0xFFFF0000)
    return b.view(np.float32)

def log_softmax(z):
    z = z - z.max(-1, keepdims=True)
    return z - np.log(np.exp(z).sum(-1, keepdims=True))

V, N = 2048, 1200
z = rng.normal(0, 2.0, (N, V))                         # logits of N positions
z[np.arange(N), 0] += rng.uniform(0, 16, N)            # token 0 is the favourite with varying confidence
lp_exact = log_softmax(z.astype(np.float64))
p = np.exp(lp_exact)
y = np.argmax(z - np.log(-np.log(rng.random((N, V)))), axis=1)   # Gumbel-max sampling from softmax(z)
rows = np.arange(N)

def delta(offset, head):
    """log-prob gap of the sampled token: exact (fp64) vs an LM head that outputs `head` precision.
    `offset` is added to every logit: mathematically a no-op for softmax."""
    zz = (z + offset).astype(np.float32)
    zz = bf16(zz) if head == 'bf16' else zz
    return log_softmax(zz.astype(np.float64))[rows, y] - lp_exact[rows, y]

py = p[rows, y]
bins = [(0, 1e-3), (1e-3, 0.05), (0.05, 0.5), (0.5, 0.95), (0.95, 1.01)]
print("std of delta = log pi_head - log pi_exact, by probability of the sampled token")
print("p(y) bin        n   | bf16 off=0   bf16 off=+30   fp32 off=+30 | predicted bf16 off=0")
d0, d30, f30 = delta(0, 'bf16'), delta(30, 'bf16'), delta(30, 'fp32')
# prediction: rounding error of logit v ~ U(-h/2, h/2) with h = ulp(z_v); delta = e_y - sum_v p_v e_v
ulp = lambda x: 2.0 ** (np.floor(np.log2(np.abs(x) + 1e-30)) - 7)
s2 = ulp(z) ** 2 / 12
pred = np.sqrt(s2[rows, y] * (1 - py) ** 2 + (p ** 2 * s2).sum(1) - p[rows, y] ** 2 * s2[rows, y])
for lo, hi in bins:
    m = (py >= lo) & (py < hi)
    print(f"[{lo:<5g},{hi:<5g})  {m.sum():5d}  | {d0[m].std():10.4f}   {d30[m].std():12.4f}   {f30[m].std():12.2e} | {pred[m].mean():10.4f}")
 

The bf16 column matches the variance formula to within its approximations, and it shows the pattern: tokens above 0.95 probability get a std of 3×10−43\times10^{-4}, tokens below 0.5 get 30 times more. Adding a constant 30 to every logit — no change to the distribution at all — multiplies the error by about 7, because the ulp of 30 is larger than the ulp of 2. An FP32 head brings it down by five orders of magnitude. This is one side’s error against exact arithmetic; two engines with independent rounding add their variances.

Reductions whose order depends on the batch

Floating-point addition is not associative. A kernel that is deterministic for a fixed input can still produce different bits when the server batches the request with different neighbours, because the reduction strategy (split sizes, tile shapes) depends on the batch shape. He et al. sent the same prompt to Qwen3-235B-A22B-Instruct at temperature 0 a thousand times and got 80 distinct completions, the first divergence at token 103; with batch-invariant RMSNorm, matmul and attention (the KV split size fixed rather than the number of splits), all 1,000 were identical. The cost on their 8B test was 26 s → 55 s, and 42 s after improving the attention kernel. The serving engines now expose this: vLLM has a beta batch-invariant mode (VLLM_BATCH_INVARIANT=1), documented as possibly slower than the default; SGLang’s deterministic-inference mode builds on the same kernels, adds a seeded Gumbel sampler for non-greedy sampling, reports an average slowdown of 34.35% with its FlashInfer and FA3 backends, and was used in slime’s GRPO recipe to get identical rollouts across runs.

Batch invariance makes the inference engine reproducible. It does not by itself make the inference engine agree with the trainer, which runs different kernels on different shapes. The kernel choice can dominate everything else: Liu, Li et al. measured the vLLM–FSDP KL at 5e-4–1e-3 on H20, 1e-3–1e-2 on L20 and 1e-2–1 on A100, and on A100 disabling cascade attention alone brought it from 5e-2–1e-1 to about 1e-3.

Zero-mismatch rollout as a reference

Push the idea all the way and the rollout engine shares the trainer’s model code and kernels, so log-probs agree bit for bit. VeXact (open-source repository) does this (shared transformer definitions, batch-invariant operators, a fused MoE kernel), and uses it as a reference to isolate the effect of numerics. On Qwen3-30B-A3B with plain REINFORCE, the vLLM run’s train/validation reward fell after step 280 from 0.574/0.293 to 0.255/0.067, while the bit-exact run rose to 0.753/0.534. The worrying part is the monitor: with the trainer recomputing old log-probs, k1 and k3 stayed almost identical to the bit-exact run for the first 700 steps and missed the early degradation (note on these readings). The verl determinism guide makes the same point in engineering terms: compare per-token log-prob mismatch counts between rollout and trainer, because a mean such as the PPO KL can be zero while individual tokens differ — and to target exact agreement it requires the rollout to sample without top-k/top-p truncation, for the reason in the sampling-mask section below.

MoE routing

Top-kk routing is a step function of the router scores. Let mm be the margin between the kk-th and (k+1)(k{+}1)-th expert’s score for a token in one layer, and let each engine perturb the scores by independent noise of size ε\varepsilon. The selection flips when the noise difference, with standard deviation 2ε\sqrt2\varepsilon, exceeds mm. If margins are roughly exponential with mean m0m_0,

pflip=Em[Φ(−m2 ε)] ≈ 1m0∫0∞Φ(−m2 ε)dm=επ m0(ε≪m0),p_{\text{flip}}=\mathbb{E}_m\Big[\Phi\big(-\tfrac{m}{\sqrt2\,\varepsilon}\big)\Big]\ \approx\ \frac{1}{m_0}\int_0^\infty\Phi\big(-\tfrac{m}{\sqrt2\,\varepsilon}\big)dm=\frac{\varepsilon}{\sqrt\pi\,m_0}\qquad(\varepsilon\ll m_0),

linear in the noise: there is no threshold below which routing is safe, because some margins are always near zero. Across LL layers a token is affected somewhere with probability up to 1−(1−p)L1-(1-p)^L. And when it flips, the token’s hidden state goes through a different expert — not a rounding-sized change but a different function — which is why routing produces the sparse heavy tail. R3 (Ma et al.) measured this on Qwen3-30B-A3B (SGLang rollout, Megatron recompute, about 20M tokens): about 10% of routers chose a different expert and 94% of tokens disagreed in at least one layer; the MoE’s train/inference KL was 1.535e-3 against 6.4e-4 for the dense Qwen3-8B.

  1. 기본값(정밀도 + kernel + routing 뒤집힘): 검은 히스토그램은 ±1까지 얇은 날개가 달린 좁은 뾰족이다. 날개가 routing 뒤집힘이다. 오른쪽 위: 표준편차는 √T로 자라고 평균은 작게 머문다. 오른쪽 아래: 빨간 곡선(밴드 밖 토큰 ≥ 1개)은 몇천 토큰이면 이미 1 근처다.
  2. **routing replay (R3)**를 체크하면 날개가 10분의 1로 줄고 빨간 곡선이 T 축에서 한 자릿수 오른쪽으로 간다. FP32 LM head를 체크하면 히스토그램 몸통이 좁아지고 k3가 내려간다.
  3. top-p 0.95를 체크하자. 히스토그램은 왼쪽으로 조금 이동하고 k3는 거의 그대로인데, |mean Σδ|(주황)가 표준편차를 추월해 선형으로 자라고 sequence mask(보라)가 모든 길이에서 모든 시퀀스에 켜진다. 이제 sampling mask 재사용을 체크하면 오프셋이 정확히 사라진다.
  4. 상관 계수 readout을 보자. 조밀한 잡음은 그것을 거의 움직이지 않는다. 거친 모니터다. 개수 기반 지표(밴드 밖 비율)와 δ의 평균이 더 많은 것을 알려 준다.

원인별로

정밀도와 LM head

각 logit zvz_v를 오차 ϵv\epsilon_v로 반올림하자. 샘플된 토큰의 log-softmax는

δy=ϵy−∑vπvϵv,Var⁡(δy)=σy2(1−πy)2+∑v≠yπv2σv2\delta_y=\epsilon_y-\sum_v\pi_v\epsilon_v,\qquad \operatorname{Var}(\delta_y)=\sigma_y^2(1-\pi_y)^2+\sum_{v\ne y}\pi_v^2\sigma_v^2

만큼 바뀐다. 결과는 둘이다. 확신하는 토큰(πy→1\pi_y\to1)은 거의 면역이고, 확률 낮은 토큰은 자기 반올림 오차를 고스란히 떠안는다. 측정된 불일치가 확률 낮은 토큰에 몰리는 이유이고(Liu, Li et al.), 그 토큰들은 RL이 가장 조정하고 싶은 탐색 토큰이기도 하다. 그리고 float의 반올림 오차는 크기에 비례하므로(ulp(z)∝∣z∣\text{ulp}(z)\propto|z|), softmax가 shift 불변인데도 logit이 크면 오차가 크다. MiniMax-M1은 학습·추론 확률 상관이 0.9x에 머물고 보상이 오르지 않던 불일치를 LM head의 큰 activation으로 추적했고, head를 FP32로 계산하자 상관이 0.99x로 올랐다. ScaleRL은 generator와 trainer 모두에 같은 처방을 쓰고 맞춘 점근 성능이 0.52에서 0.61로 올랐다고 보고하며, 이것을 최종 레시피에 넣었다. 모든 스택이 head에 지배되지는 않는다. Liu, Li et al.의 vLLM 설정에서는 FP32 lm_head가 눈에 띄는 차이를 만들지 않았고, MAI-Base-2는 양쪽을 bf16으로 맞추는 것이 더 낮은 정밀도보다 훨씬 작고 안정적인 차이를 줬다고 보고한다. 처방에 돈을 쓰기 전에 어느 원인이 지배하는지 재자.

NumPy LM head 정밀도: bf16 반올림, logit 크기, 누가 오차를 떠안나
import numpy as np
rng = np.random.default_rng(0)

def bf16(x):
    """float32를 bfloat16(가수 8비트, round-to-nearest-even)으로 반올림해 float32로 돌려준다."""
    b = np.ascontiguousarray(x, dtype=np.float32).view(np.uint32)
    b = (b + np.uint32(0x7FFF) + ((b >> np.uint32(16)) & np.uint32(1))) & np.uint32(0xFFFF0000)
    return b.view(np.float32)

def log_softmax(z):
    z = z - z.max(-1, keepdims=True)
    return z - np.log(np.exp(z).sum(-1, keepdims=True))

V, N = 2048, 1200
z = rng.normal(0, 2.0, (N, V))                         # 위치 N개의 logit
z[np.arange(N), 0] += rng.uniform(0, 16, N)            # 토큰 0이 확신 정도가 제각각인 최빈 토큰
lp_exact = log_softmax(z.astype(np.float64))
p = np.exp(lp_exact)
y = np.argmax(z - np.log(-np.log(rng.random((N, V)))), axis=1)   # softmax(z)에서 Gumbel-max 샘플링
rows = np.arange(N)

def delta(offset, head):
    """샘플된 토큰의 log-prob 차이: 정확한 값(fp64) vs `head` 정밀도로 출력하는 LM head.
    `offset`은 모든 logit에 더한다. softmax에는 수학적으로 아무 영향이 없다."""
    zz = (z + offset).astype(np.float32)
    zz = bf16(zz) if head == 'bf16' else zz
    return log_softmax(zz.astype(np.float64))[rows, y] - lp_exact[rows, y]

py = p[rows, y]
bins = [(0, 1e-3), (1e-3, 0.05), (0.05, 0.5), (0.5, 0.95), (0.95, 1.01)]
print("std of delta = log pi_head - log pi_exact, by probability of the sampled token")
print("p(y) bin        n   | bf16 off=0   bf16 off=+30   fp32 off=+30 | predicted bf16 off=0")
d0, d30, f30 = delta(0, 'bf16'), delta(30, 'bf16'), delta(30, 'fp32')
# 예측: logit v의 반올림 오차 ~ U(-h/2, h/2), h = ulp(z_v). delta = e_y - sum_v p_v e_v
ulp = lambda x: 2.0 ** (np.floor(np.log2(np.abs(x) + 1e-30)) - 7)
s2 = ulp(z) ** 2 / 12
pred = np.sqrt(s2[rows, y] * (1 - py) ** 2 + (p ** 2 * s2).sum(1) - p[rows, y] ** 2 * s2[rows, y])
for lo, hi in bins:
    m = (py >= lo) & (py < hi)
    print(f"[{lo:<5g},{hi:<5g})  {m.sum():5d}  | {d0[m].std():10.4f}   {d30[m].std():12.4f}   {f30[m].std():12.2e} | {pred[m].mean():10.4f}")
 

bf16 열은 근사 범위 안에서 분산 공식과 맞고, 패턴을 보여 준다. 확률 0.95 위의 토큰은 표준편차 3×10−43\times10^{-4}, 0.5 아래 토큰은 30배를 받는다. 모든 logit에 상수 30을 더하면 — 분포는 전혀 바뀌지 않는데 — 30의 ulp가 2의 ulp보다 크기 때문에 오차가 약 7배가 된다. FP32 head는 이를 다섯 자릿수 줄인다. 이것은 정확한 산술 대비 한쪽의 오차이고, 반올림이 독립인 두 엔진이면 분산이 더해진다.

batch에 따라 순서가 바뀌는 reduction

부동소수점 덧셈은 결합법칙을 따르지 않는다. 고정된 입력에 대해 결정적인 kernel도 서버가 요청을 다른 이웃과 batch로 묶으면 다른 비트를 낼 수 있다. reduction 전략(split 크기, tile 모양)이 batch 모양에 따라 바뀌기 때문이다. He et al.은 같은 프롬프트를 temperature 0으로 Qwen3-235B-A22B-Instruct에 천 번 보내 서로 다른 완성 80개를 얻었고, 첫 분기는 토큰 103이었다. batch-invariant RMSNorm, matmul, attention(split 개수가 아니라 KV split 크기를 고정)을 쓰자 1,000개 모두 같았다. 8B 시험의 비용은 26초 → 55초, attention kernel 개선 후 42초였다. serving 엔진들도 이제 이것을 제공한다. vLLM에는 beta batch-invariant 모드(VLLM_BATCH_INVARIANT=1)가 있고 기본 모드보다 느릴 수 있다고 문서화되어 있다. SGLang의 deterministic inference 모드는 같은 kernel 위에 non-greedy 샘플링용 seed 고정 Gumbel sampler를 더하고, FlashInfer·FA3 backend에서 평균 34.35% 느려진다고 보고하며, slime의 GRPO 레시피에서 실행마다 같은 rollout을 얻는 데 쓰였다.

batch invariance는 추론 엔진을 재현 가능하게 만든다. 그것만으로 추론 엔진이 다른 모양에서 다른 kernel을 돌리는 trainer와 일치하지는 않는다. kernel 선택이 다른 모든 것을 압도할 수도 있다. Liu, Li et al.은 vLLM–FSDP KL을 H20에서 5e-4–1e-3, L20에서 1e-3–1e-2, A100에서 1e-2–1로 쟀고, A100에서는 cascade attention을 끄는 것만으로 5e-2–1e-1에서 약 1e-3으로 내려갔다.

기준선으로서의 zero-mismatch rollout

이 생각을 끝까지 밀면 rollout 엔진이 trainer의 모델 코드와 kernel을 공유해 log-prob가 비트 단위로 일치한다. VeXact(오픈소스 저장소)가 그렇게 하고(공유 transformer 정의, batch-invariant 연산자, fused MoE kernel), 수치의 효과를 떼어 내는 기준선으로 쓴다. 평범한 REINFORCE의 Qwen3-30B-A3B에서 vLLM 실행의 학습·검증 보상은 step 280 이후 0.574/0.293에서 0.255/0.067로 떨어졌고, bit-exact 실행은 0.753/0.534로 올랐다. 걱정스러운 부분은 모니터다. trainer가 old log-prob를 다시 계산하는 설정에서 k1과 k3는 처음 700 step 동안 bit-exact 실행과 거의 같아서 초기 악화를 놓쳤다(이 자료들의 정리 노트). verl의 determinism 가이드도 엔지니어링 언어로 같은 말을 한다. rollout과 trainer 사이의 토큰별 log-prob 불일치 개수를 비교하라, PPO KL 같은 평균은 개별 토큰이 달라도 0일 수 있다. 그리고 정확한 일치를 목표로 할 때는 아래 sampling mask 절의 이유로 rollout이 top-k/top-p 절단 없이 샘플하도록 요구한다.

MoE routing

top-kk routing은 router 점수의 계단 함수다. 한 층에서 어떤 토큰의 kk번째와 (k+1)(k{+}1)번째 expert 점수 차를 margin mm이라 하고, 각 엔진이 점수에 크기 ε\varepsilon의 독립 잡음을 얹는다고 하자. 표준편차 2ε\sqrt2\varepsilon인 잡음 차가 mm을 넘으면 선택이 뒤집힌다. margin이 평균 m0m_0의 대략 지수분포라면

pflip=Em[Φ(−m2 ε)] ≈ 1m0∫0∞Φ(−m2 ε)dm=επ m0(ε≪m0)p_{\text{flip}}=\mathbb{E}_m\Big[\Phi\big(-\tfrac{m}{\sqrt2\,\varepsilon}\big)\Big]\ \approx\ \frac{1}{m_0}\int_0^\infty\Phi\big(-\tfrac{m}{\sqrt2\,\varepsilon}\big)dm=\frac{\varepsilon}{\sqrt\pi\,m_0}\qquad(\varepsilon\ll m_0)

로 잡음에 선형이다. 언제나 0 근처의 margin이 있으므로 routing이 안전해지는 문턱은 없다. LL개 층에 걸쳐 토큰이 어딘가에서 영향받을 확률은 최대 1−(1−p)L1-(1-p)^L이다. 그리고 뒤집히면 토큰의 hidden state는 다른 expert를 지난다. 반올림 크기의 변화가 아니라 다른 함수다. routing이 드문 두꺼운 꼬리를 만드는 이유다. R3(Ma et al.)는 Qwen3-30B-A3B(SGLang rollout, Megatron 재계산, 약 2천만 토큰)에서 이를 쟀다. router의 약 10%가 다른 expert를 골랐고 토큰의 94%가 적어도 한 층에서 어긋났다. MoE의 학습·추론 KL은 1.535e-3으로 dense Qwen3-8B의 6.4e-4보다 컸다.

층별 뒤집힘 비율per-layer flip rate – ≥1층 뒤집힌 토큰tokens with ≥1 flipped layer – 독립 가정 예측independence predicts – 근사approx. ε/(√π m₀) –
Top: 64 tokens (columns) × L MoE layers (rows); a red cell means the rollout engine and the trainer chose a different expert set in that layer. Bottom left: distribution of the router margin (gap between the k-th and (k+1)-th expert score) and, in red, the probability that noise of size ε reverses it. Bottom right: share of tokens with at least one flipped layer as depth grows. R3 measured about 10% of routing decisions and 94% of tokens differing in at least one layer for Qwen3-30B-A3B (48 layers) — raise κ and see how flips concentrating on ambiguous tokens bring the "≥1 layer" share below the independence prediction. Tick replay: the trainer reuses the rollout's expert indices, so no cell can disagree. 위: 토큰 64개(열) × MoE 층 L개(행). 빨간 칸은 그 층에서 rollout 엔진과 trainer가 다른 expert 집합을 골랐다는 뜻이다. 왼쪽 아래: router margin(k번째와 k+1번째 expert 점수 차)의 분포와, 빨강으로 크기 ε의 잡음이 그것을 뒤집을 확률. 오른쪽 아래: 깊이에 따라 한 층이라도 뒤집힌 토큰의 비율. R3는 Qwen3-30B-A3B(48층)에서 routing 결정의 약 10%, 토큰의 94%가 적어도 한 층에서 다르다고 측정했다. κ를 올려 보면 뒤집힘이 애매한 토큰에 몰리면서 "≥1층" 비율이 독립 가정 예측보다 낮아진다. replay를 체크하면 trainer가 rollout의 expert index를 그대로 쓰므로 어떤 칸도 어긋나지 않는다.

With the defaults the toy matches both R3 numbers at once: about 10% per layer and about 94% of tokens with at least one flipped layer over 48 layers. Set κ = 0 and the per-layer rate drops but the ”≥ 1 layer” share stays high: with independent layers, 10% per layer would give 99.4%, not 94%. The measured 94% is a hint that flips cluster on ambiguous tokens — the same tokens are near a routing boundary in many layers — which also means a token-level mask removes them more cheaply than the per-layer rate suggests.

Fixes. Keep Routing (DeepSeek-V3.2, used since V3-0324 and called “crucial” for MoE RL stability) and Rollout Routing Replay (R3) record the experts chosen at sampling time and force them in the training forward and backward pass, while the gating weights are still computed from the trainer’s own router logits so that the router keeps receiving gradient. R3 reduced the KL from 1.5e-3 to 7.5e-4 and the frequency of large-mismatch tokens to about a tenth; in its Table 1 (Qwen3-30B-A3B-SFT, one mini-step) GRPO collapsed at step 60, GRPO+TIS at step 105, while GRPO+R3 (71.83) and GRPO+TIS+R3 (70.14) did not collapse; on SWE-bench Verified GRPO went from 31.80 (collapsing around step 90) to 38.60 with R3. The cost was 3.45% more step time (4,820 s → 4,967 s per 10 steps) and 2.5 GB/1.5 GB more CPU memory per inference/training node. The routing masks are cached with the prefix KV, so multi-turn rollouts need no re-prefill. MiMo-V2 and MAI-Base-2 use routing replay in production.

R2 vs R3 — which mismatch, which bias. Zheng et al. (Qwen Team) separate two replays. Vanilla routing replay (R2) replays, during the gradient updates, the experts the rollout policy selected in the training engine; it targets policy staleness across mini-batches, leaves the target policy unchanged on the first mini-batch and alters it on later ones (the replayed experts are no longer the current policy’s natural routing). R3 replays the routes from the inference engine; it targets both the engine discrepancy and staleness, but alters the target policy on every mini-batch, including the first, because the inference routes can differ from the trainer’s natural ones. Their recommendations, from a 30B MoE with FP8 inference and BF16 training: fully on-policy, the plain IS-corrected policy gradient was best and adding R3 gave no gain (R3 without IS correction still collapsed); off-policy, both replay and clipping were needed. With small off-policiness (global batch = 2× mini-batch) R2 beat R3; at 4× and 8×, R2 could not sustain training and R3 was better. GSPO reached stability without replay at the sequence level, noting that about 10% of activated experts change after each update in a 48-layer Qwen3-30B-A3B — that part is policy drift, not numerics, and router freezing (MiMo-V2.6) or anticipatory routing (DeepSeek-V4) attack it directly (stability playbook).

The same problem, without MoE. Any discrete top-kk inside the network behaves this way. GLM-5’s DSA indexer picks 2,048 tokens per query; replaying those indices is too much to store and send, so GLM-5 uses the deterministic torch.topk in the trainer instead of the non-deterministic top-k in SGLang’s indexer — with the non-deterministic one RL “degraded drastically after only a few steps, accompanied by a sharp drop in entropy” — and freezes the indexer during RL (GLM-5 review).

Sampling masks, temperature and processed log-probs

The derivation in the first section is the whole story of top-p: if the sampler draws from the nucleus StS_t renormalised by ZtZ_t and the trainer computes πθ\pi_\theta over the full vocabulary, every sampled token has δt=log⁡Zt∈[log⁡p,0]\delta_t=\log Z_t\in[\log p,0], a systematic bias. Two more consequences:

  • Support violation. πθ\pi_\theta has mass 1−Zt1-Z_t on tokens μ\mu can never produce. The IS identity Eμ[πμf]=Eπ[f]\mathbb{E}_\mu[\tfrac{\pi}{\mu}f]=\mathbb{E}_\pi[f] requires μ>0\mu>0 wherever π>0\pi>0; it fails here, so no importance weight can repair it — the estimator is not even consistent.
  • Gradient leak. ∂(−log⁡πθ(y))/∂zv=πθ(v)\partial(-\log\pi_\theta(y))/\partial z_v=\pi_\theta(v) for every v≠yv\ne y, so each update pushes down tokens outside the nucleus — tokens the sampler never shows — with total weight 1−Zt1-Z_t per position. MAI-Base-2 samples with top-p 0.97 and reports that when gradients flowed through the out-of-nucleus logits, the “catastrophic off-policy mismatch” made training diverge within a few steps (MAI-Base-2 review).

The fix is to compute πθ\pi_\theta on the same support: record StS_t at sampling time and renormalise the trainer’s distribution over it, πθS(y)=πθ(y)/∑v∈Stπθ(v)\pi^{S}_\theta(y)=\pi_\theta(y)/\sum_{v\in S_t}\pi_\theta(v). DeepSeek-V3.2 calls it Keep Sampling Mask and reports that top-p with it helped preserve language consistency during RL; MAI-Base-2 replays the top-p mask by setting the masked logits to −∞-\infty in training; MiMo-V2.6 replays the top-p candidate sets. The alternative is to sample without truncation (top-p = 1), which the verl determinism guide requires for exact agreement. Liu, Li et al. found top-p 0.98–0.999 reduced mismatch spikes but slowed reward growth.

Temperature is the same issue in a different form: the trainer must apply the identical transform. And the engine’s returned log-probs may not be the probabilities it sampled from: vLLM V1 by default returns raw log-probs (V1 guide, “Semantic Changes to Logprobs”), computed from the model output before any logit processing (temperature, penalties, top-k/top-p), and offers processed_logprobs for values after processing; its documentation states that the returned log-probs do not reflect the final adjusted probabilities used during sampling. Using raw log-probs as μ\mu while sampling with temperature 0.7 and top-p, or processed ones while the trainer computes a full-vocabulary temperature-1 softmax, creates exactly the systematic shape above. Decide which distribution μ\mu is, and make both sides compute that one.

Quantised rollouts and matched quantisation

Rollout is most of the cost (Yao et al. report about 70% of training time for DAPO-32B), so low-precision rollouts are tempting. slime (GLM-4.5) quantises the BF16 trainer weights block-wise to FP8 online at every update for its rollout engines; Yao et al.’s FlashRL reports INT8/FP8 rollouts with TIS matching BF16 with TIS. How far you can go depends on the format: in the score-centering experiments on Qwen3-30B-A3B, an FP8 sampler was stable even without correction, an FP4 KV cache made plain policy gradient collapse within 200 steps (score centering 52%, TIS 51%), and INT8 weights with an INT4 KV cache left score centering at 30% and TIS at 12%. DLC measured an FP8-weight-plus-KV sampler at a roughly constant 0.02 nats per token. The structural fix is to quantise both sides the same way: K3 trains with MXFP4 weights and MXFP8 activations (QAT) from SFT on and uses the same quantisation in rollout and training (K3 review); DeepSeek-V4 applies FP4 QAT to expert weights and the indexer path and rolls out with the real FP4 weights rather than a simulation.

Tokens and templates

Two “mismatches” are plain bugs and should be removed first: re-tokenising decoded text (the same string can be a different token sequence, agent RL), and chat-template drift between rollout and training. GLM-5’s token-in-token-out gateway records the exact token ids the engine produced for exactly this reason.

Algorithmic corrections, matched to the shape

When the source cannot be removed, the shape tells you which correction fits. The equations are in clipping and IS; here is what each one is for.

CorrectionWhat it doesFitsFails on
Token TIS (Yao et al.)multiply by sg⁡[min⁡(πtrain/πinfer,C)]\operatorname{sg}[\min(\pi_{\text{train}}/\pi_{\text{infer}},C)]; OLMo 3 uses C=2C=2dense noisesystematic offsets (biased, not removed)
IcePop / token masked ISzero tokens whose ratio leaves [α,β][\alpha,\beta] (Ring-1T: [0.5, 5]; GLM-5 reasoning: [0.5, 2])sparse tail (removes 1–2‰ of tokens in Ring’s runs)offsets; a too-tight band (Ring: [0.5, 2] was unstable for them)
Sequence MIS / TISreject or truncate by the sequence ratiocatastrophic sequenceslong sequences: the product drifts with length
Geo-RS, Trust Region Maskingkeep a response if Clow≤ρ1/T≤ChighC_{\text{low}}\le\rho^{1/T}\le C_{\text{high}}; TRM masks a sequence if any token’s divergence leaves the trust regionlength-invariant sequence filteringTRM’s acceptance ≈e−pT\approx e^{-pT} rejects long sequences unless made length-neutral
V3.2 off-policy sequence maskingmask a sequence only if A^<0\hat A<0 and its mean log-ratio exceeds δ\deltastale and mismatched negativesnothing for positives by design
Decoupled PPOclip against πprox\pi_{\text{prox}}, weight by πprox/πbehav\pi_{\text{prox}}/\pi_{\text{behav}} (async lesson)separating trust region from correctionvariance of the weight
Score centeringsubtract the sampler-expected score sˉ=∑vqv∇log⁡πv\bar s=\sum_v q_v\nabla\log\pi_v (top-128 head)the drift that any persistent gap — and IS clipping — leavesheavy staleness alone (its signal is measured under the sampler: compose with TIS/MIS)

Score centering deserves a sentence of its own because it targets something the others miss. Under mismatch, Eq[R ∇log⁡πy]=Eq[R] sˉ+Cov⁡q(R,∇log⁡πy)\mathbb{E}_q[R\,\nabla\log\pi_y]=\mathbb{E}_q[R]\,\bar s+\operatorname{Cov}_q(R,\nabla\log\pi_y): the first term is a drift that is zero only when q=πq=\pi, distils the trainer toward the sampler, and accumulates every step because the sampler is refreshed from the trainer; group centering does not remove it because the expected advantage per prefix is not zero. Subtracting sˉ\bar s removes it and composes with IS. The derivation, the top-kk approximation and the measurements are in the next lesson.

Implementing it

The same three sources as the figure, now with the growth laws measured. Token statistics come from 200,000 sampled tokens; the sequence columns use the i.i.d. formulas (mean TmTm, std Ts\sqrt T s, 1−(1−f)T1-(1-f)^T), checked by a Monte Carlo line at the end. The top-p nucleus masses are computed exactly from Zipf-like distributions.

NumPy How each source accumulates over length, and what each fix changes
import numpy as np
rng = np.random.default_rng(1)

# A pool of token positions: probability of the sampled token, and the nucleus mass Z of top-p sampling there.
P = 4000
conf = rng.random(P) < 0.7                                     # 70% confident positions, 30% high-entropy
p_tok = np.where(conf, 1 - 10 ** rng.uniform(-4, -1, P), 10 ** rng.uniform(-3, -0.05, P))
def nucleus_mass(top_p, n=P):
    """Exact top-p on a Zipf-like distribution per position: Z = mass kept by the nucleus."""
    a = np.where(conf, rng.uniform(3, 6, n), rng.uniform(0.6, 1.4, n))   # sharp vs flat positions
    ranks = np.arange(1, 1001)
    probs = ranks[None, :] ** (-a[:, None]); probs /= probs.sum(1, keepdims=True)
    cum = np.cumsum(probs, 1)
    k = (cum < top_p).sum(1)                                  # index of the last token needed to reach top_p
    return cum[np.arange(n), k]
Z = nucleus_mass(0.95)

def token_delta(n, src, fix):
    """delta = log pi_train - log pi_infer for n sampled tokens, by source (toy magnitudes)."""
    i = rng.integers(0, P, n); p = p_tok[i]
    d = np.zeros(n)
    if 'precision' in src:                                    # dense, zero-mean, larger on unlikely tokens
        s = 0.03 * (0.25 if 'fp32_head' in fix else 1.0)
        d += rng.normal(0, s * (1 - p) + 0.002, n)
    if 'routing' in src:                                      # sparse: a flipped expert changes the token's logit
        q = 0.02 * (0.1 if 'replay' in fix else 1.0)          # R3: large-mismatch tokens fall to ~1/10
        flip = rng.random(n) < q
        d += flip * rng.normal(0, 0.8 * (1 - p) + 0.05, n)
    if 'top_p' in src and 'mask_replay' not in fix:           # systematic: trainer renormalises over full vocab
        d += np.log(Z[i])                                     # pi_full(y) = Z * mu(y)  ->  delta = log Z <= 0
    return d

from math import erf, sqrt
Phi = lambda x: 0.5 * (1 + erf(x / sqrt(2)))

def report(name, src, fix, Ts=(256, 2048, 16384), thr=0.01):
    d = token_delta(200000, src, fix)
    m, s = d.mean(), d.std()
    k3 = np.mean(np.exp(d) - 1 - d)                           # KL(mu || pi_train), samples from mu
    out = np.mean((d < np.log(0.5)) | (d > np.log(2)))        # tokens an IcePop-style band would drop
    cells = []
    for T in Ts:                                              # i.i.d. tokens: sum has mean T*m, std sqrt(T)*s
        any_out = 1 - (1 - out) ** T
        seqmask = 1 - Phi((thr + m) / (s / np.sqrt(T) + 1e-12))   # P(mean of -delta > thr)
        cells.append(f"{T * m:+8.2f} {np.sqrt(T) * s:6.2f} {any_out:5.2f} {seqmask:5.2f}")
    print(f"{name:26s} k1={-m:+.1e} k3={k3:.1e} out={out:.1e} | " + " | ".join(cells))

print("per T: mean(sum delta)  std(sum delta)  P(>=1 token outside [0.5,2])  P(seq-mask fires, thr=0.01)")
print(" " * 63 + " | ".join(f"{'T=' + str(T):^26s}" for T in (256, 2048, 16384)))
report("precision (bf16 head)", {'precision'}, set())
report("  + FP32 LM head", {'precision'}, {'fp32_head'})
report("routing flips (MoE)", {'routing'}, set())
report("  + routing replay (R3)", {'routing'}, {'replay'})
report("top-p 0.95, no mask replay", {'top_p'}, set())
report("  + sampling-mask replay", {'top_p'}, {'mask_replay'})
report("all three", {'precision', 'routing', 'top_p'}, set())
report("all three + all fixes", {'precision', 'routing', 'top_p'}, {'fp32_head', 'replay', 'mask_replay'})
print(f"\nmean log Z over positions (top-p 0.95): {np.log(Z).mean():+.4f} nats/token -> x{np.exp(16384*np.log(Z).mean()):.1e} at T=16384")
d = token_delta(200 * 2048, {"precision", "routing", "top_p"}, set()).reshape(200, 2048)
print("Monte Carlo check, all three at T=2048: mean %+.2f std %.2f P(any out) %.2f" % (d.sum(1).mean(), d.sum(1).std(), ((d < np.log(0.5)) | (d > np.log(2))).any(1).mean()))
 

Each row is one of the three growth laws. Precision: the sequence std grows from 0.25 to 2.0 nats between 256 and 16K tokens and no token leaves the band; the FP32 head divides it by about three. Routing: k3 is ten times larger than precision’s, only 0.2% of tokens leave the band, yet 41% of 256-token sequences and essentially every 2K-token sequence contain one — a sequence-level rule keyed on outliers would discard everything long; replay moves that curve by an order of magnitude but at 16K tokens 97% of sequences still contain a flip, so a token-level mask stays useful. Top-p: the honest k1 is 3.5×10−23.5\times10^{-2}, k3 reports 7×10−47\times10^{-4}, no token leaves the band, and the sequence log-ratio is −71 at 2K tokens — the sequence mask fires on every sequence. Only mask replay removes it, and it removes it exactly.

Now the routing formula against simulation, and the effect of flips clustering on ambiguous tokens.

NumPy Routing flips: ε/(√π m₀), depth, and clustering
import numpy as np
from math import erf, sqrt, pi

rng = np.random.default_rng(2)
# Router margins m ~ Exp(mean m0) per (token, layer); each engine adds N(0, eps^2) noise to the two competing scores.
# A flip happens when the noise difference (std sqrt(2)*eps) overturns the margin.
NT, L, m0 = 4000, 48, 0.1
e = rng.exponential(1.0, (NT, L)); z = rng.standard_normal((NT, L)); g0 = rng.standard_normal(NT)
print("   eps    | per-layer p (MC)  approx eps/(sqrt(pi) m0) | >=1 of 48 layers: MC (kappa=0)  independent")
for eps in [1e-4, 1e-3, 3e-3, 1e-2]:
    flip = z * sqrt(2) * eps > m0 * e
    p = flip.mean()
    print(f"  {eps:7.0e} |   {p:8.4f}          {eps / (sqrt(pi) * m0):8.4f}            |  {flip.any(1).mean():8.3f}          {1 - (1 - p) ** L:8.3f}")
# heterogeneous tokens: some tokens are ambiguous in every layer (smaller margins), so flips cluster
eps = 10 ** -1.9
for kappa in [0.0, 0.8]:
    gscale = np.exp(kappa * g0 - kappa**2 / 2)[:, None]
    flip = z * sqrt(2) * eps > m0 * gscale * e
    p = flip.mean()
    print(f"eps={eps:.4f} kappa={kappa}: per-layer {p:.3f}, tokens with >=1 flip {flip.any(1).mean():.3f}"
          f" (independence would give {1 - (1 - p) ** L:.3f}); mean flipped layers per token {flip.sum(1).mean():.2f}")
 

The approximation ε/(πm0)\varepsilon/(\sqrt\pi m_0) tracks the simulation over two orders of magnitude, and the per-layer rate is linear in the noise: halving numerical noise halves routing flips, it never removes them. With heterogeneous tokens (κ = 0.8) the per-layer rate is 10% but only 94% of tokens are affected over 48 layers, against 99.3% under independence; the flipped tokens have 4.8 flipped layers on average.

Finally, the trainer side in PyTorch: log-probs on the recorded sampling support, MoE routing with replay, and a diagnostics report.

PyTorch PyTorch: Keep Sampling Mask, routing replay, mismatch report 로컬에서 실행run locally (pip install torch)
import torch

def logprobs_on_support(logits, tokens, keep_mask=None, temperature=1.0):
    """Trainer-side log-probs of the sampled tokens under the SAME transform the sampler used.
    logits: (N, T, V) from the training forward; tokens: (N, T) sampled ids;
    keep_mask: (N, T, V) bool, the top-p/top-k support recorded at sampling time (None = full vocabulary).
    In practice store the support compactly (e.g. sorted-index cut-offs) and rebuild the mask per micro-batch."""
    z = logits.float() / temperature                      # FP32 head output and softmax
    if keep_mask is not None:
        z = z.masked_fill(~keep_mask, float("-inf"))      # Keep Sampling Mask: renormalise over the same subset
    return torch.log_softmax(z, dim=-1).gather(-1, tokens.unsqueeze(-1)).squeeze(-1)

def moe_route(router_logits, k, replay_idx=None):
    """router_logits: (n_tokens, E). replay_idx: (n_tokens, k) experts recorded by the rollout engine (R3 /
    Keep Routing). The selection is replayed; the gates still come from the trainer's logits, so the router
    keeps receiving gradient."""
    idx = router_logits.topk(k, dim=-1).indices if replay_idx is None else replay_idx
    gates = torch.softmax(router_logits.float().gather(-1, idx), dim=-1)
    return idx, gates.to(router_logits.dtype)

@torch.no_grad()
def mismatch_report(train_logp, infer_logp, mask, edges=(0.0, 1e-3, 0.05, 0.5, 0.95, 1.01)):
    """train_logp, infer_logp, mask: (N, T). Returns the per-step numbers worth logging."""
    m = mask.bool()
    d = (train_logp - infer_logp)[m].double()             # delta = log pi_train - log pi_infer
    p = infer_logp[m].double().exp()
    r = d.exp()
    out = {
        "mean_delta": d.mean().item(),                    # systematic offsets live here (and in k1)
        "k1": (-d).mean().item(),
        "k3": (r - 1 - d).mean().item(),                  # under-reports when supports differ
        "max_abs_delta": d.abs().max().item(),
        "n_tokens_differ": int((d != 0).sum()),           # counts catch what means hide
        "frac_out_0.5_2": ((r < 0.5) | (r > 2.0)).double().mean().item(),
    }
    e = torch.tensor(edges, dtype=torch.float64)
    b = torch.bucketize(p, e) - 1
    for i in range(len(edges) - 1):
        sel = b == i
        if sel.sum() > 1:
            out[f"std_delta_p[{edges[i]:g},{edges[i + 1]:g})"] = d[sel].std().item()
    seq = ((train_logp - infer_logp) * mask).sum(-1).double()   # per-sequence sum: offset ~ T, noise ~ sqrt(T)
    out["seq_sum_mean"], out["seq_sum_std"] = seq.mean().item(), seq.std().item()
    return out
 
확인 문제Check yourself

Your rollouts use top-p 0.95 and the trainer computes a full-vocabulary softmax. The token-level k3 between engines is 7e-4 and looks fine, yet a sequence-level mask on the mean log-ratio fires on almost every response. Which fix addresses the cause?

Top-p makes the sampler’s distribution μ=π/Z\mu=\pi/Z on the nucleus, so every sampled token has δ=log⁡Z<0\delta=\log Z<0: a systematic offset that adds up linearly over the sequence. k3 under-reports it because the trainer’s distribution has mass where the sampler has none (Eμ[π/μ]=Z<1\mathbb{E}_\mu[\pi/\mu]=Z<1), and no importance weight can fix a support mismatch. The cure is to make both sides compute the same distribution: replay the truncation mask in training (DeepSeek-V3.2, MAI-Base-2, MiMo-V2.6) or turn truncation off. Also check whether your engine returns raw or processed log-probs.

확인 문제Check yourself

In a 30B MoE trained fully on-policy with an importance-sampling correction against the rollout log-probs, adding rollout routing replay (R3) gives no gain. In the same setup with 8 mini-batches per global batch, R3 helps a lot. Why the difference?

This is Zheng et al.’s finding. R3 changes the function being trained — the trainer uses the inference engine’s experts, not its own — so it biases the target on every mini-batch. When training is on-policy and corrected by IS, that bias buys nothing. With more off-policiness, routing shifts between the policy that sampled and the one being updated make the ratio itself unreliable, and fixing the routes (R2 for small off-policiness, R3 for larger) together with clipping was needed to avoid collapse.

Summary

  • At identical weights the rollout engine and the trainer still disagree. What matters is the shape of δt\delta_t: dense noise grows as T\sqrt T, a sparse tail makes “at least one outlier” certain for long sequences, a systematic offset grows as TT and is under-reported by k3.
  • Precision error is absorbed by unlikely tokens and grows with logit magnitude; an FP32 LM head fixed it for MiniMax-M1 and ScaleRL but not in every stack. Batch-invariant kernels make inference reproducible (at a cost of tens of percent); a bit-exact rollout engine is the reference that shows how much numerics alone costs.
  • MoE routing flips are linear in noise (≈ε/πm0\approx\varepsilon/\sqrt\pi m_0 per layer) and turn into a heavy tail. Keep Routing / R3 replay inference routes (+3.45% time in R3’s setup); R2 replays training-engine routes for staleness. Each biases the target differently; on-policy with IS, replay was unnecessary in Zheng et al.’s study, while off-policy it was essential.
  • Top-p or temperature applied on one side only creates a systematic offset and a support violation that IS cannot fix. Keep the sampling mask (or do not truncate), apply the same temperature, and know whether your engine returns raw or processed log-probs.
  • Quantised rollouts are fine to a point (FP8) and harmful beyond (FP4 KV); matched quantisation (K3, V4) removes the gap structurally. Residual mismatch is then corrected by the tool that fits its shape: TIS for noise, token masks for tails, length-normalised sequence filters for catastrophic sequences, score centering for drift.

기본값에서 장난감은 R3의 두 숫자를 동시에 맞춘다. 층당 약 10%, 48층에 걸쳐 한 층이라도 뒤집힌 토큰 약 94%다. κ = 0으로 두면 층당 비율은 내려가지만 ”≥ 1층” 비율은 높게 남는다. 층이 독립이라면 층당 10%는 94%가 아니라 99.4%를 준다. 측정된 94%는 뒤집힘이 애매한 토큰에 몰린다는 단서다. 같은 토큰이 여러 층에서 routing 경계 근처에 있다. 이는 토큰 단위 mask가 층당 비율이 시사하는 것보다 싸게 그것들을 지운다는 뜻이기도 하다.

처방. Keep Routing(DeepSeek-V3.2. V3-0324부터 썼고 MoE RL 안정성에 “결정적”이라 했다)과 Rollout Routing Replay(R3)는 샘플할 때 고른 expert를 기록해 학습의 forward와 backward에 강제하되, gating weight는 trainer 자신의 router logit으로 계산해 router가 계속 gradient를 받게 한다. R3는 KL을 1.5e-3에서 7.5e-4로, 큰 불일치 토큰의 빈도를 약 10분의 1로 줄였다. Table 1(Qwen3-30B-A3B-SFT, mini-step 1)에서 GRPO는 step 60에, GRPO+TIS는 step 105에 붕괴했고 GRPO+R3(71.83)와 GRPO+TIS+R3(70.14)는 붕괴하지 않았다. SWE-bench Verified에서 GRPO는 31.80(약 step 90에 붕괴)에서 R3로 38.60이 됐다. 비용은 step 시간 3.45% 증가(10 step당 4,820초 → 4,967초)와 추론·학습 노드당 CPU 메모리 2.5 GB/1.5 GB 증가였다. routing mask는 prefix KV와 함께 cache되므로 멀티턴 rollout에 re-prefill이 필요 없다. MiMo-V2와 MAI-Base-2가 실전에서 routing replay를 쓴다.

R2 대 R3 — 어떤 불일치를, 어떤 bias로. Zheng et al.(Qwen Team)은 두 replay를 구분한다. Vanilla routing replay(R2)는 gradient 업데이트 동안 rollout 정책이 학습 엔진에서 고른 expert를 재사용한다. mini-batch 사이의 정책 staleness를 겨냥하고, 첫 mini-batch에서는 목표 정책을 바꾸지 않지만 이후 mini-batch에서는 바꾼다(재사용한 expert가 더 이상 현재 정책의 자연스러운 routing이 아니다). R3는 추론 엔진의 routing을 재사용한다. 엔진 discrepancy와 staleness를 둘 다 겨냥하지만, 추론 routing이 trainer의 자연스러운 routing과 다를 수 있으므로 첫 mini-batch를 포함한 모든 mini-batch에서 목표 정책을 바꾼다. FP8 추론·BF16 학습의 30B MoE에서 나온 권고는 이렇다. 완전 on-policy에서는 IS로 보정한 평범한 정책 경사가 가장 좋았고 R3를 더해도 이득이 없었다(IS 보정 없는 R3는 여전히 붕괴). off-policy에서는 replay와 clipping이 모두 필요했다. off-policy가 작을 때(global batch = mini-batch의 2배)는 R2가 R3보다 나았고, 4배와 8배에서는 R2가 학습을 유지하지 못하고 R3가 나았다. GSPO는 시퀀스 단위로 replay 없이 안정성에 닿았고, 48층 Qwen3-30B-A3B에서 업데이트마다 활성 expert의 약 10%가 바뀐다고 적는다. 그 부분은 수치가 아니라 정책 drift이고, router freezing(MiMo-V2.6)이나 anticipatory routing(DeepSeek-V4)이 직접 다룬다(안정화 플레이북).

MoE가 아니어도 같은 문제. 네트워크 안의 이산 top-kk는 모두 이렇게 행동한다. GLM-5의 DSA indexer는 query마다 2,048 토큰을 고른다. 그 index를 재사용하기에는 저장·전송량이 너무 커서, GLM-5는 SGLang indexer의 비결정적 top-k 대신 trainer에서 결정적 torch.topk를 쓴다. 비결정적인 것을 쓰면 RL이 “몇 step 만에 급격히 나빠지고 entropy가 급락”했다. 그리고 RL 중에는 indexer를 고정한다(GLM-5 리뷰).

sampling mask, temperature, processed log-prob

첫 절의 유도가 top-p 이야기의 전부다. sampler가 ZtZ_t로 재정규화한 nucleus StS_t에서 뽑고 trainer가 전체 vocabulary로 πθ\pi_\theta를 계산하면, 샘플된 모든 토큰이 δt=log⁡Zt∈[log⁡p,0]\delta_t=\log Z_t\in[\log p,0], 체계적 bias를 갖는다. 결과가 둘 더 있다.

  • support 위반. πθ\pi_\theta는 μ\mu가 절대 만들 수 없는 토큰에 질량 1−Zt1-Z_t를 둔다. IS 항등식 Eμ[πμf]=Eπ[f]\mathbb{E}_\mu[\tfrac{\pi}{\mu}f]=\mathbb{E}_\pi[f]는 π>0\pi>0인 곳마다 μ>0\mu>0을 요구한다. 여기서는 깨지므로 어떤 importance weight도 고칠 수 없다. 추정량이 일치성조차 없다.
  • gradient 누수. 모든 v≠yv\ne y에 대해 ∂(−log⁡πθ(y))/∂zv=πθ(v)\partial(-\log\pi_\theta(y))/\partial z_v=\pi_\theta(v)이므로, 업데이트마다 nucleus 밖 토큰 — sampler가 절대 보여 주지 않는 토큰 — 을 위치당 총 가중 1−Zt1-Z_t로 누른다. MAI-Base-2는 top-p 0.97로 샘플하고, nucleus 밖 logit으로 gradient가 흐르자 “파국적 off-policy 불일치”로 몇 step 만에 학습이 발산했다고 보고한다(MAI-Base-2 리뷰).

처방은 같은 support에서 πθ\pi_\theta를 계산하는 것이다. 샘플할 때 StS_t를 기록하고 trainer의 분포를 그 위에서 재정규화한다. πθS(y)=πθ(y)/∑v∈Stπθ(v)\pi^{S}_\theta(y)=\pi_\theta(y)/\sum_{v\in S_t}\pi_\theta(v). DeepSeek-V3.2는 이것을 Keep Sampling Mask라 부르고, top-p와 함께 쓰면 RL 중 언어 일관성 유지에 도움이 됐다고 보고한다. MAI-Base-2는 학습에서 mask된 logit을 −∞-\infty로 두어 top-p mask를 재사용하고, MiMo-V2.6은 top-p 후보 집합을 재사용한다. 다른 길은 절단 없이(top-p = 1) 샘플하는 것으로, verl determinism 가이드가 정확한 일치를 위해 요구한다. Liu, Li et al.은 top-p 0.98–0.999가 불일치 spike를 줄이지만 보상 상승을 늦춘다고 봤다.

temperature는 같은 문제의 다른 모양이다. trainer가 똑같은 변환을 적용해야 한다. 그리고 엔진이 돌려주는 log-prob가 실제로 샘플한 확률이 아닐 수 있다. vLLM V1은(V1 가이드의 “Semantic Changes to Logprobs”) 기본적으로 logit 처리(temperature, penalty, top-k/top-p) 전의 모델 출력에서 계산한 raw log-prob를 돌려주고, 처리 후 값을 위한 processed_logprobs를 제공한다. 문서는 돌려준 log-prob가 샘플링에 쓰인 최종 조정 확률을 반영하지 않는다고 적는다. temperature 0.7과 top-p로 샘플하면서 raw log-prob를 μ\mu로 쓰거나, trainer가 temperature 1의 전체 vocabulary softmax를 계산하는데 processed를 쓰면 위의 체계적 모양이 정확히 생긴다. μ\mu가 어떤 분포인지 정하고 양쪽이 그것을 계산하게 하자.

양자화된 rollout과 맞춘 양자화

rollout이 비용의 대부분이므로(Yao et al.은 DAPO-32B에서 학습 시간의 약 70%라 보고) 낮은 정밀도 rollout은 유혹적이다. slime(GLM-4.5)은 업데이트마다 BF16 trainer weight를 block 단위로 온라인 FP8 양자화해 rollout 엔진에 보낸다. Yao et al.의 FlashRL은 INT8/FP8 rollout + TIS가 BF16 + TIS와 맞먹는다고 보고한다. 어디까지 갈 수 있는지는 형식에 달렸다. Qwen3-30B-A3B의 score centering 실험에서 FP8 sampler는 보정 없이도 안정적이었고, FP4 KV cache는 평범한 정책 경사를 200 step 안에 붕괴시켰으며(score centering 52%, TIS 51%), INT8 weight + INT4 KV cache는 score centering을 30%, TIS를 12%에 남겼다. DLC는 FP8 weight + KV sampler를 토큰당 대략 일정한 0.02 nats로 쟀다. 구조적 처방은 양쪽을 같은 방식으로 양자화하는 것이다. K3는 SFT부터 MXFP4 weight와 MXFP8 activation으로 학습하고(QAT) rollout과 학습에 같은 양자화를 쓴다(K3 리뷰). DeepSeek-V4는 expert weight와 indexer 경로에 FP4 QAT를 걸고 시뮬레이션이 아닌 실제 FP4 weight로 rollout한다.

토큰과 template

두 “불일치”는 그냥 버그이므로 먼저 없애야 한다. decode한 텍스트를 다시 tokenize하는 것(같은 문자열이 다른 토큰 시퀀스일 수 있다, Agent RL), 그리고 rollout과 학습 사이의 chat template 차이다. GLM-5의 token-in-token-out gateway는 바로 이 이유로 엔진이 만든 정확한 token id를 기록한다.

모양에 맞춘 알고리즘 보정

원인을 없앨 수 없을 때는 모양이 어떤 보정이 맞는지 알려 준다. 식은 clipping과 IS에 있고, 여기서는 각각이 무엇을 위한 것인지만 본다.

보정하는 일맞는 모양실패하는 곳
토큰 TIS (Yao et al.)sg⁡[min⁡(πtrain/πinfer,C)]\operatorname{sg}[\min(\pi_{\text{train}}/\pi_{\text{infer}},C)]를 곱한다. OLMo 3는 C=2C=2조밀한 잡음체계적 오프셋(없애지 못하고 bias를 남긴다)
IcePop / 토큰 masked ISratio가 [α,β][\alpha,\beta]를 벗어난 토큰을 0으로(Ring-1T: [0.5, 5], GLM-5 reasoning: [0.5, 2])드문 꼬리(Ring 실행에서 토큰의 1–2‰ 제거)오프셋, 너무 좁은 밴드(Ring에서는 [0.5, 2]가 불안정)
시퀀스 MIS / TIS시퀀스 ratio로 거부하거나 자른다파국적인 시퀀스긴 시퀀스: 곱이 길이와 함께 떠내려간다
Geo-RS, Trust Region MaskingClow≤ρ1/T≤ChighC_{\text{low}}\le\rho^{1/T}\le C_{\text{high}}면 응답을 남긴다. TRM은 어느 토큰이라도 divergence가 trust region을 벗어나면 시퀀스를 mask길이 불변 시퀀스 필터TRM의 수락 확률 ≈e−pT\approx e^{-pT}는 길이 중립으로 만들지 않으면 긴 시퀀스를 거부
V3.2 off-policy sequence maskingA^<0\hat A<0이고 평균 log-ratio가 δ\delta를 넘을 때만 시퀀스를 mask낡았고 또 불일치한 음의 샘플설계상 양의 샘플에는 아무것도 안 함
Decoupled PPOπprox\pi_{\text{prox}} 기준으로 clip하고 πprox/πbehav\pi_{\text{prox}}/\pi_{\text{behav}}로 가중(비동기 레슨)trust region과 보정의 분리weight의 분산
Score centeringsampler 기대 score sˉ=∑vqv∇log⁡πv\bar s=\sum_v q_v\nabla\log\pi_v를 뺀다(top-128 head)지속적인 차이가, 그리고 IS clipping이 남기는 drift심한 staleness 단독(signal을 sampler 아래에서 잰다: TIS/MIS와 결합)

score centering은 다른 것들이 놓치는 것을 겨냥하므로 한 문장 더 쓸 만하다. 불일치가 있으면 Eq[R ∇log⁡πy]=Eq[R] sˉ+Cov⁡q(R,∇log⁡πy)\mathbb{E}_q[R\,\nabla\log\pi_y]=\mathbb{E}_q[R]\,\bar s+\operatorname{Cov}_q(R,\nabla\log\pi_y)이고, 첫 항은 q=πq=\pi일 때만 0인 drift다. trainer를 sampler 쪽으로 증류하고, sampler가 trainer에서 갱신되므로 매 step 쌓인다. prefix별 기대 advantage가 0이 아니므로 group centering도 이것을 지우지 못한다. sˉ\bar s를 빼면 사라지고, IS와 함께 쓸 수 있다. 유도, top-kk 근사, 측정 결과는 다음 레슨에 있다.

구현해 보기

그림과 같은 세 원인에 성장 법칙을 재 본다. 토큰 통계는 샘플 토큰 200,000개에서, 시퀀스 열은 i.i.d. 공식(평균 TmTm, 표준편차 Ts\sqrt T s, 1−(1−f)T1-(1-f)^T)에서 나오고, 끝의 Monte Carlo 한 줄로 확인한다. top-p nucleus 질량은 Zipf 꼴 분포에서 정확히 계산한다.

NumPy 원인마다 길이에 따라 어떻게 쌓이나, 처방마다 무엇이 바뀌나
import numpy as np
rng = np.random.default_rng(1)

# 토큰 위치 풀: 샘플된 토큰의 확률과, 그 위치에서 top-p가 남기는 nucleus 질량 Z.
P = 4000
conf = rng.random(P) < 0.7                                     # 70%는 확신하는 위치, 30%는 entropy 높은 위치
p_tok = np.where(conf, 1 - 10 ** rng.uniform(-4, -1, P), 10 ** rng.uniform(-3, -0.05, P))
def nucleus_mass(top_p, n=P):
    """위치마다 Zipf 꼴 분포에서 정확한 top-p: Z = nucleus가 남기는 질량."""
    a = np.where(conf, rng.uniform(3, 6, n), rng.uniform(0.6, 1.4, n))   # 날카로운 위치 vs 평평한 위치
    ranks = np.arange(1, 1001)
    probs = ranks[None, :] ** (-a[:, None]); probs /= probs.sum(1, keepdims=True)
    cum = np.cumsum(probs, 1)
    k = (cum < top_p).sum(1)                                  # top_p에 닿는 데 필요한 마지막 토큰의 index
    return cum[np.arange(n), k]
Z = nucleus_mass(0.95)

def token_delta(n, src, fix):
    """샘플된 토큰 n개의 delta = log pi_train - log pi_infer, 원인별 (장난감 크기)."""
    i = rng.integers(0, P, n); p = p_tok[i]
    d = np.zeros(n)
    if 'precision' in src:                                    # 조밀, 평균 0, 확률 낮은 토큰에서 더 크다
        s = 0.03 * (0.25 if 'fp32_head' in fix else 1.0)
        d += rng.normal(0, s * (1 - p) + 0.002, n)
    if 'routing' in src:                                      # 드묾: 뒤집힌 expert가 토큰의 logit을 바꾼다
        q = 0.02 * (0.1 if 'replay' in fix else 1.0)          # R3: 큰 불일치 토큰이 약 1/10로 준다
        flip = rng.random(n) < q
        d += flip * rng.normal(0, 0.8 * (1 - p) + 0.05, n)
    if 'top_p' in src and 'mask_replay' not in fix:           # 체계적: trainer가 전체 vocab으로 재정규화
        d += np.log(Z[i])                                     # pi_full(y) = Z * mu(y)  ->  delta = log Z <= 0
    return d

from math import erf, sqrt
Phi = lambda x: 0.5 * (1 + erf(x / sqrt(2)))

def report(name, src, fix, Ts=(256, 2048, 16384), thr=0.01):
    d = token_delta(200000, src, fix)
    m, s = d.mean(), d.std()
    k3 = np.mean(np.exp(d) - 1 - d)                           # KL(mu || pi_train), mu에서 온 샘플
    out = np.mean((d < np.log(0.5)) | (d > np.log(2)))        # IcePop식 밴드가 버릴 토큰
    cells = []
    for T in Ts:                                              # i.i.d. 토큰: 합의 평균 T*m, 표준편차 sqrt(T)*s
        any_out = 1 - (1 - out) ** T
        seqmask = 1 - Phi((thr + m) / (s / np.sqrt(T) + 1e-12))   # P(-delta의 평균 > thr)
        cells.append(f"{T * m:+8.2f} {np.sqrt(T) * s:6.2f} {any_out:5.2f} {seqmask:5.2f}")
    print(f"{name:26s} k1={-m:+.1e} k3={k3:.1e} out={out:.1e} | " + " | ".join(cells))

print("per T: mean(sum delta)  std(sum delta)  P(>=1 token outside [0.5,2])  P(seq-mask fires, thr=0.01)")
print(" " * 63 + " | ".join(f"{'T=' + str(T):^26s}" for T in (256, 2048, 16384)))
report("precision (bf16 head)", {'precision'}, set())
report("  + FP32 LM head", {'precision'}, {'fp32_head'})
report("routing flips (MoE)", {'routing'}, set())
report("  + routing replay (R3)", {'routing'}, {'replay'})
report("top-p 0.95, no mask replay", {'top_p'}, set())
report("  + sampling-mask replay", {'top_p'}, {'mask_replay'})
report("all three", {'precision', 'routing', 'top_p'}, set())
report("all three + all fixes", {'precision', 'routing', 'top_p'}, {'fp32_head', 'replay', 'mask_replay'})
print(f"\nmean log Z over positions (top-p 0.95): {np.log(Z).mean():+.4f} nats/token -> x{np.exp(16384*np.log(Z).mean()):.1e} at T=16384")
d = token_delta(200 * 2048, {"precision", "routing", "top_p"}, set()).reshape(200, 2048)
print("Monte Carlo check, all three at T=2048: mean %+.2f std %.2f P(any out) %.2f" % (d.sum(1).mean(), d.sum(1).std(), ((d < np.log(0.5)) | (d > np.log(2))).any(1).mean()))
 

행마다 세 성장 법칙 중 하나다. 정밀도: 256에서 16K 토큰 사이에 시퀀스 표준편차가 0.25에서 2.0 nats로 자라고 밴드를 벗어나는 토큰은 없다. FP32 head가 이를 약 3분의 1로 줄인다. Routing: k3는 정밀도의 10배이고 밴드를 벗어나는 토큰은 0.2%뿐인데, 256 토큰 시퀀스의 41%와 2K 토큰 시퀀스는 사실상 전부가 그런 토큰을 품는다. 이상치에 반응하는 시퀀스 단위 규칙은 긴 것을 모두 버릴 것이다. replay는 그 곡선을 한 자릿수 옮기지만 16K 토큰에서는 여전히 시퀀스의 97%가 뒤집힘을 품으므로 토큰 단위 mask가 계속 쓸모 있다. Top-p: 정직한 k1은 3.5×10−23.5\times10^{-2}인데 k3는 7×10−47\times10^{-4}를 보고하고, 밴드를 벗어나는 토큰은 없으며, 시퀀스 log-ratio는 2K 토큰에서 −71이다. sequence mask가 모든 시퀀스에 켜진다. mask 재사용만이 이를 없애고, 정확히 없앤다.

다음은 routing 공식과 시뮬레이션의 비교, 그리고 뒤집힘이 애매한 토큰에 몰릴 때의 효과다.

NumPy Routing 뒤집힘: ε/(√π m₀), 깊이, 몰림
import numpy as np
from math import erf, sqrt, pi

rng = np.random.default_rng(2)
# (토큰, 층)마다 router margin m ~ Exp(평균 m0). 각 엔진이 경쟁하는 두 점수에 N(0, eps^2) 잡음을 얹는다.
# 잡음 차(표준편차 sqrt(2)*eps)가 margin을 넘으면 뒤집힌다.
NT, L, m0 = 4000, 48, 0.1
e = rng.exponential(1.0, (NT, L)); z = rng.standard_normal((NT, L)); g0 = rng.standard_normal(NT)
print("   eps    | per-layer p (MC)  approx eps/(sqrt(pi) m0) | >=1 of 48 layers: MC (kappa=0)  independent")
for eps in [1e-4, 1e-3, 3e-3, 1e-2]:
    flip = z * sqrt(2) * eps > m0 * e
    p = flip.mean()
    print(f"  {eps:7.0e} |   {p:8.4f}          {eps / (sqrt(pi) * m0):8.4f}            |  {flip.any(1).mean():8.3f}          {1 - (1 - p) ** L:8.3f}")
# 이질적인 토큰: 어떤 토큰은 모든 층에서 애매하다(margin이 작다). 그래서 뒤집힘이 몰린다
eps = 10 ** -1.9
for kappa in [0.0, 0.8]:
    gscale = np.exp(kappa * g0 - kappa**2 / 2)[:, None]
    flip = z * sqrt(2) * eps > m0 * gscale * e
    p = flip.mean()
    print(f"eps={eps:.4f} kappa={kappa}: per-layer {p:.3f}, tokens with >=1 flip {flip.any(1).mean():.3f}"
          f" (independence would give {1 - (1 - p) ** L:.3f}); mean flipped layers per token {flip.sum(1).mean():.2f}")
 

근사 ε/(πm0)\varepsilon/(\sqrt\pi m_0)는 두 자릿수에 걸쳐 시뮬레이션을 따라가고, 층당 비율은 잡음에 선형이다. 수치 잡음을 반으로 줄이면 routing 뒤집힘이 반이 될 뿐 사라지지 않는다. 이질적인 토큰(κ = 0.8)에서는 층당 비율이 10%인데 48층에 걸쳐 영향받는 토큰은 94%뿐으로, 독립 가정의 99.3%보다 낮다. 뒤집힌 토큰은 평균 4.8개 층에서 뒤집힌다.

마지막으로 PyTorch로 trainer 쪽을 보자. 기록한 sampling support 위의 log-prob, replay가 있는 MoE routing, 진단 보고서다.

PyTorch PyTorch: Keep Sampling Mask, routing replay, 불일치 보고서 로컬에서 실행run locally (pip install torch)
import torch

def logprobs_on_support(logits, tokens, keep_mask=None, temperature=1.0):
    """sampler가 쓴 것과 똑같은 변환 아래에서 샘플된 토큰의 trainer 쪽 log-prob.
    logits: 학습 forward의 (N, T, V). tokens: 샘플된 id (N, T).
    keep_mask: 샘플할 때 기록한 top-p/top-k support (N, T, V) bool (None = 전체 vocabulary).
    실제로는 support를 압축해 저장하고(예: 정렬 index의 cut-off) micro-batch마다 mask를 다시 만든다."""
    z = logits.float() / temperature                      # head 출력과 softmax는 FP32
    if keep_mask is not None:
        z = z.masked_fill(~keep_mask, float("-inf"))      # Keep Sampling Mask: 같은 부분집합에서 재정규화
    return torch.log_softmax(z, dim=-1).gather(-1, tokens.unsqueeze(-1)).squeeze(-1)

def moe_route(router_logits, k, replay_idx=None):
    """router_logits: (n_tokens, E). replay_idx: rollout 엔진이 기록한 expert (n_tokens, k) (R3 /
    Keep Routing). 선택은 재사용하고 gate는 trainer의 logit에서 계산하므로 router가 계속 gradient를 받는다."""
    idx = router_logits.topk(k, dim=-1).indices if replay_idx is None else replay_idx
    gates = torch.softmax(router_logits.float().gather(-1, idx), dim=-1)
    return idx, gates.to(router_logits.dtype)

@torch.no_grad()
def mismatch_report(train_logp, infer_logp, mask, edges=(0.0, 1e-3, 0.05, 0.5, 0.95, 1.01)):
    """train_logp, infer_logp, mask: (N, T). step마다 기록할 만한 숫자들을 돌려준다."""
    m = mask.bool()
    d = (train_logp - infer_logp)[m].double()             # delta = log pi_train - log pi_infer
    p = infer_logp[m].double().exp()
    r = d.exp()
    out = {
        "mean_delta": d.mean().item(),                    # 체계적 오프셋은 여기(와 k1)에 있다
        "k1": (-d).mean().item(),
        "k3": (r - 1 - d).mean().item(),                  # support가 다르면 작게 말한다
        "max_abs_delta": d.abs().max().item(),
        "n_tokens_differ": int((d != 0).sum()),           # 개수는 평균이 숨기는 것을 잡는다
        "frac_out_0.5_2": ((r < 0.5) | (r > 2.0)).double().mean().item(),
    }
    e = torch.tensor(edges, dtype=torch.float64)
    b = torch.bucketize(p, e) - 1
    for i in range(len(edges) - 1):
        sel = b == i
        if sel.sum() > 1:
            out[f"std_delta_p[{edges[i]:g},{edges[i + 1]:g})"] = d[sel].std().item()
    seq = ((train_logp - infer_logp) * mask).sum(-1).double()   # 시퀀스별 합: 오프셋 ~ T, 잡음 ~ sqrt(T)
    out["seq_sum_mean"], out["seq_sum_std"] = seq.mean().item(), seq.std().item()
    return out
 
확인 문제Check yourself

rollout은 top-p 0.95를 쓰고 trainer는 전체 vocabulary softmax를 계산한다. 엔진 사이 토큰 단위 k3는 7e-4로 괜찮아 보이는데, 평균 log-ratio에 건 sequence mask가 거의 모든 응답에 켜진다. 원인을 고치는 처방은?

top-p는 sampler의 분포를 nucleus 위의 μ=π/Z\mu=\pi/Z로 만들어, 샘플된 모든 토큰이 δ=log⁡Z<0\delta=\log Z<0을 갖는다. 시퀀스에 걸쳐 선형으로 더해지는 체계적 오프셋이다. trainer의 분포가 sampler가 질량을 두지 않는 곳에 질량을 두므로(Eμ[π/μ]=Z<1\mathbb{E}_\mu[\pi/\mu]=Z<1) k3는 이를 작게 말하고, support 불일치는 어떤 importance weight로도 고칠 수 없다. 처방은 양쪽이 같은 분포를 계산하게 하는 것이다. 학습에서 절단 mask를 재사용하거나(DeepSeek-V3.2, MAI-Base-2, MiMo-V2.6) 절단을 끈다. 엔진이 raw log-prob를 돌려주는지 processed를 돌려주는지도 확인하자.

확인 문제Check yourself

rollout log-prob 기준 importance sampling 보정으로 완전 on-policy 학습하는 30B MoE에서 rollout routing replay(R3)를 더해도 이득이 없다. global batch당 mini-batch 8개인 같은 설정에서는 R3가 크게 돕는다. 왜 다른가?

Zheng et al.의 발견이다. R3는 학습하는 함수 자체를 바꾼다. trainer가 자기 expert가 아니라 추론 엔진의 expert를 쓰므로 모든 mini-batch에서 목표를 bias시킨다. on-policy이고 IS로 보정할 때는 그 bias로 얻는 것이 없다. off-policy가 커지면 샘플한 정책과 업데이트되는 정책 사이의 routing 변화가 ratio 자체를 못 믿게 만들고, 붕괴를 피하려면 routing 고정(작은 off-policy에는 R2, 큰 것에는 R3)과 clipping이 함께 필요했다.

정리

  • weight가 같아도 rollout 엔진과 trainer는 어긋난다. 중요한 것은 δt\delta_t의 모양이다. 조밀한 잡음은 T\sqrt T로 자라고, 드문 꼬리는 긴 시퀀스에서 “이상치 하나 이상”을 확실하게 만들며, 체계적 오프셋은 TT로 자라고 k3에는 작게 보고된다.
  • 정밀도 오차는 확률 낮은 토큰이 떠안고 logit 크기와 함께 커진다. FP32 LM head는 MiniMax-M1과 ScaleRL에서 이를 고쳤지만 모든 스택에서는 아니다. batch-invariant kernel은 추론을 재현 가능하게 만들고(수십 % 비용), bit-exact rollout 엔진은 수치만의 비용이 얼마인지 보여 주는 기준선이다.
  • MoE routing 뒤집힘은 잡음에 선형이고(층당 ≈ε/πm0\approx\varepsilon/\sqrt\pi m_0) 두꺼운 꼬리가 된다. Keep Routing / R3는 추론 routing을 재사용하고(R3 설정에서 시간 +3.45%), R2는 staleness를 위해 학습 엔진 routing을 재사용한다. 각각 목표를 다르게 bias시킨다. Zheng et al.의 연구에서 IS를 쓰는 on-policy에서는 replay가 불필요했고 off-policy에서는 필수였다.
  • 한쪽에만 적용된 top-p나 temperature는 체계적 오프셋과 IS가 고칠 수 없는 support 위반을 만든다. sampling mask를 유지하고(또는 절단하지 말고), 같은 temperature를 쓰고, 엔진이 raw와 processed 중 어떤 log-prob를 돌려주는지 알자.
  • 양자화된 rollout은 어느 선까지는(FP8) 괜찮고 그 너머는(FP4 KV) 해롭다. 맞춘 양자화(K3, V4)는 차이를 구조적으로 없앤다. 남은 불일치는 모양에 맞는 도구로 보정한다. 잡음엔 TIS, 꼬리엔 토큰 mask, 파국적 시퀀스엔 길이 정규화한 시퀀스 필터, drift엔 score centering이다.

더 읽을거리Further reading