Track VIII · Inference & Optimisation · 09/09

RL을 위한 추론Inference for RL

RL 학습 루프 안의 추론 엔진을 해부한다. rollout 길이의 긴 꼬리가 동기 배치의 활용률을 어떻게 깎는지 유도하고 over-sampling·partial rollout의 대가(길이 편향, staleness)를 비교한다. 같은 가중치에서도 엔진과 trainer의 logprob이 왜 다른지(배치에 따른 reduction 순서, 커널·정밀도 차이, MoE routing)를 bf16 NumPy 실험으로 보이고, batch-invariant 커널과 결정적 샘플링, weight sync 전략을 계산한다.An anatomy of the inference engine inside the RL loop. Derive how the long tail of rollout lengths eats the utilisation of a synchronous batch, and compare the price of over-sampling and partial rollouts (length bias, staleness). Show with bf16 NumPy experiments why engine and trainer logprobs differ even at identical weights (batch-dependent reduction order, kernel and precision differences, MoE routing), then work through batch-invariant kernels, deterministic sampling and weight-sync strategies.

50 분min RL · rollout · vLLM · SGLang · batch invariance · determinism · weight sync · partial rollout · training-inference mismatch 먼저 볼 것:Before this: 추론 최적화Inference optimisation, 배칭과 스케줄링Batching and scheduling, Speculative decoding 심화Speculative decoding in depth, 학습–추론 불일치와 importance samplingTraining–inference mismatch and importance sampling

In online RL the inference engine is not a service next to training; it is inside the training loop. Every iteration generates a batch of rollouts, scores them, computes gradients, and pushes new weights back to the engine. How much of the bill is generation? MiMo-V2.6 Pro, for example, reports that rollout is 43.8% of its RL cost, training 43.5% and the grader 12.7% (MiMo-V2 review). Everything in this track applies, but RL changes three requirements that ordinary serving never has:

  1. The batch has to finish. Serving optimises tokens per second and per-request latency; an RL iteration waits for the batch it trains on. Rollout lengths have a long tail, so the tail decides the iteration time.
  2. The probabilities must agree with the trainer. The policy-gradient estimator uses the sampler’s tokens and the trainer’s log-probs. If the two engines disagree for the same weights, “on-policy” RL is off-policy (training–inference mismatch).
  3. The weights change every step. Hundreds of GB to a TB must move from the trainer’s layout into the engine’s, often while requests are in flight.

This lesson takes them in turn, ending with what to log and what to fix.

Anatomy of a rollout engine

The rollout workers are ordinary serving engines (vLLM, SGLang, TensorRT-LLM) driven by the RL framework. What the framework needs from them goes beyond the OpenAI-style API:

  • Token in, token out. The trainer must score exactly the token ids the engine generated. Re-tokenising returned text can produce a different token sequence and silently corrupts the log-probs; verl’s agent loop exposes a token-in-token-out generate for this reason, and GLM-5’s agentic RL records token ids end to end (GLM-5 review).
  • The right log-probs. By default vLLM V1 returns log-probs of the raw model output, before temperature, penalties and top-k/top-p; a logprobs-mode setting returns the processed ones. Which you need depends on whether your behaviour policy is the raw model or the truncated sampling distribution. DeepSeek-V3.2’s “Keep Sampling Mask” exists because top-p truncation changes the distribution the trainer must assume (V3.2 review).
  • Routing information. For MoE, routing replay (R3, Keep Routing) needs the engine to return which experts each token used (mismatch engineering).
  • Prefix reuse. A GRPO group samples GG responses from one prompt, and an agent trajectory re-sends a growing prefix every turn. Prefix caching (KV-cache lesson) turns those into cache hits, but only if later turns land on the replica that holds the prefix: verl’s agent loop binds a request id to a server (sticky sessions) and picks the least-loaded server for a new one, and SGLang’s router is cache-aware.
  • A weight-update path and a way to get out of the way. Covered below.

Placement: colocated or disaggregated. In a colocated design the trainer and the engine time-share the same GPUs. HybridFlow (verl) reshards the actor between its training layout and its generation layout with its 3D-HybridEngine (“zero memory redundancy”), and Kimi k1.5 ran Megatron and vLLM as sidecars in one pod (k1.5 review). The engine must release memory while the trainer runs: vLLM’s sleep mode level 1 offloads weights to CPU and discards the KV cache; level 2 discards both, for when the weights are about to be replaced anyway, and wake_up(tags=["weights"]) then wake_up(tags=["kv_cache"]) re-allocates in stages so the KV cache does not compete with the weight update for memory. In a disaggregated design rollout and training own separate GPUs and run concurrently, which is what asynchronous RL needs. slime, used for GLM-4.5, runs reasoning RL synchronously colocated and agentic RL asynchronously disaggregated, because agent rollouts are long and wait on environments (GLM-4.5 review).

The long tail

Suppose response lengths are log-normal, ℓ=m eσZ\ell = m\,e^{\sigma Z}. A synchronous iteration runs until the longest of its NN responses is done, and decoding is memory-bound, so a step costs about the same whether 64 or 3 sequences are active. The fraction of slot-steps doing useful work is

Usync=∑iℓiNmax⁡iℓi≈E[ℓ]E[max⁡iℓi]≈eσ2/2eσzN,U_{\text{sync}} = \frac{\sum_i \ell_i}{N \max_i \ell_i} \approx \frac{\mathbb E[\ell]}{\mathbb E[\max_i \ell_i]} \approx \frac{e^{\sigma^2/2}}{e^{\sigma z_N}},

with zNz_N the typical largest of NN standard normals (≈2.2\approx 2.2 for N=64N = 64). For σ=0.9\sigma = 0.9 that is 1.5/7.2≈0.21.5/7.2 \approx 0.2: four-fifths of the iteration is spent decoding a nearly empty batch. The fix is to stop letting the slowest response set the pace, and every option has a price.

온라인 RL에서 추론 엔진은 학습 옆의 서비스가 아니라 학습 루프 안에 있다. 매 iteration이 rollout 배치를 생성하고, 채점하고, gradient를 계산하고, 새 가중치를 엔진으로 밀어 넣는다. 비용 중 생성은 얼마나 되나? 예를 들어 MiMo-V2.6 Pro는 RL 비용의 43.8%가 rollout, 43.5%가 학습, 12.7%가 grader라고 보고한다(MiMo-V2 리뷰). 이 트랙의 모든 내용이 적용되지만, RL은 일반 서빙에는 없는 요구 셋을 바꿔 놓는다.

  1. 배치가 끝나야 한다. 서빙은 초당 토큰과 요청별 지연을 최적화하지만, RL iteration은 학습할 배치를 기다린다. rollout 길이에는 긴 꼬리가 있어 꼬리가 iteration 시간을 정한다.
  2. 확률이 trainer와 일치해야 한다. policy gradient 추정량은 샘플러의 토큰과 trainer의 log-prob을 쓴다. 같은 가중치에서 두 엔진이 다르면 “on-policy” RL은 off-policy다(학습–추론 불일치).
  3. 가중치가 매 step 바뀐다. 수백 GB에서 1 TB가 trainer의 배치(layout)에서 엔진의 배치로 옮겨져야 하고, 요청이 처리되는 도중일 때가 많다.

이 레슨은 이 셋을 차례로 다루고, 무엇을 기록하고 무엇을 고칠지로 끝난다.

rollout 엔진의 해부

rollout worker는 RL 프레임워크가 구동하는 평범한 서빙 엔진(vLLM, SGLang, TensorRT-LLM)이다. 프레임워크가 엔진에 요구하는 것은 OpenAI식 API를 넘어선다.

  • token in, token out. trainer는 엔진이 생성한 토큰 id를 정확히 그대로 채점해야 한다. 돌려받은 텍스트를 다시 토큰화하면 다른 토큰 시퀀스가 나올 수 있고 log-prob이 조용히 망가진다. verl의 agent loop가 token-in-token-out generate를 제공하는 이유이고, GLM-5의 agentic RL은 토큰 id를 처음부터 끝까지 기록한다(GLM-5 리뷰).
  • 올바른 log-prob. vLLM V1은 기본으로 temperature, penalty, top-k/top-p를 적용하기 전의 원시 모델 출력의 log-prob을 돌려주고, logprobs-mode 설정으로 처리된 값을 받을 수 있다. 어느 쪽이 필요한지는 행동 정책을 원시 모델로 보느냐 잘린 샘플링 분포로 보느냐에 달렸다. DeepSeek-V3.2의 “Keep Sampling Mask”는 top-p 절단이 trainer가 가정해야 할 분포를 바꾸기 때문에 있다(V3.2 리뷰).
  • routing 정보. MoE에서 routing replay(R3, Keep Routing)를 하려면 엔진이 각 토큰이 쓴 expert를 돌려줘야 한다(mismatch engineering).
  • prefix 재사용. GRPO 그룹은 한 prompt에서 응답 GG개를 뽑고, agent trajectory는 턴마다 자라는 prefix를 다시 보낸다. prefix caching(KV cache 레슨)이 이를 cache hit로 바꾸지만, 뒤 턴이 그 prefix를 가진 replica에 도착할 때만 그렇다. verl의 agent loop는 요청 id를 서버에 묶고(sticky session) 새 요청에는 부하가 가장 적은 서버를 고르며, SGLang의 router는 cache-aware다.
  • 가중치 갱신 경로와 비켜 주는 방법. 아래에서 다룬다.

배치: colocated인가 disaggregated인가. colocated 설계에서는 trainer와 엔진이 같은 GPU를 시분할한다. HybridFlow(verl)는 3D-HybridEngine으로 actor를 학습용 배치와 생성용 배치 사이에서 재샤딩하고(“메모리 중복 없음”), Kimi k1.5는 Megatron과 vLLM을 한 pod의 sidecar로 돌렸다(k1.5 리뷰). trainer가 도는 동안 엔진은 메모리를 비워 줘야 한다. vLLM의 sleep mode level 1은 가중치를 CPU로 내리고 KV cache를 버린다. level 2는 둘 다 버리며, 어차피 가중치를 바꿀 때 쓴다. 이후 wake_up(tags=["weights"]), 그다음 wake_up(tags=["kv_cache"])로 단계적으로 다시 할당해 KV cache가 가중치 갱신과 메모리를 다투지 않게 한다. disaggregated 설계에서는 rollout과 학습이 각자 GPU를 갖고 동시에 돈다. 비동기 RL에 필요한 형태다. GLM-4.5에 쓰인 slime은 추론 RL은 동기 colocated로, agentic RL은 비동기 disaggregated로 돌린다. agent rollout은 길고 환경을 기다리기 때문이다(GLM-4.5 리뷰).

긴 꼬리

응답 길이가 log-normal ℓ=m eσZ\ell = m\,e^{\sigma Z}라고 하자. 동기 iteration은 NN개 응답 중 가장 긴 것이 끝날 때까지 돌고, decode는 memory-bound라서 활성 시퀀스가 64개든 3개든 step 비용이 거의 같다. 쓸모 있는 일을 하는 slot-step의 비율은

Usync=∑iℓiNmax⁡iℓi≈E[ℓ]E[max⁡iℓi]≈eσ2/2eσzN,U_{\text{sync}} = \frac{\sum_i \ell_i}{N \max_i \ell_i} \approx \frac{\mathbb E[\ell]}{\mathbb E[\max_i \ell_i]} \approx \frac{e^{\sigma^2/2}}{e^{\sigma z_N}},

zNz_N은 표준정규 NN개 중 최댓값의 전형적 크기다(N=64N = 64이면 ≈2.2\approx 2.2). σ=0.9\sigma = 0.9이면 1.5/7.2≈0.21.5/7.2 \approx 0.2다. iteration의 5분의 4를 거의 빈 배치를 decode하며 보낸다. 해법은 가장 느린 응답이 속도를 정하지 못하게 하는 것이고, 어떤 선택지든 대가가 있다.

N = 64 trajectories per training batch. Left: how many sequences are decoding during one iteration (the dashed line is N). Right: the N trajectories that go to the trainer, sorted by length and coloured by how many weight updates old each token is: ■ current policy ■ 1 version old ■ 2 ■ 3+; grey bars are aborted work. Synchronous: the batch waits for its longest member, so most of the iteration runs a nearly empty batch. Over-sample + abort launches N(1+r) and stops at the N-th completion: the tail disappears, but the kept set is the N shortest, a length bias. Partial rollout keeps every slot busy and carries unfinished trajectories into the next iteration: no tail and no length bias, but long trajectories are stitched from several policy versions. Raise σ to make the tail worse. 학습 배치당 trajectory N = 64. 왼쪽: 한 iteration 동안 decode 중인 시퀀스 수(점선이 N). 오른쪽: trainer로 가는 N개 trajectory를 길이순으로 놓고, 각 토큰이 몇 번의 가중치 갱신 전에 생성됐는지로 색칠했다. ■ 현재 정책 ■ 1버전 전 ■ 2 ■ 3+. 회색 막대는 중단된 작업이다. 동기 배치: 배치가 가장 긴 응답을 기다리므로 iteration 대부분이 거의 빈 배치로 돈다. over-sample + abort는 N(1+r)개를 띄우고 N번째 완료에서 멈춘다. 꼬리는 사라지지만 남는 것은 가장 짧은 N개라 길이 편향이 생긴다. partial rollout은 모든 슬롯을 계속 채우고 끝나지 않은 trajectory를 다음 iteration으로 넘긴다. 꼬리도 길이 편향도 없지만 긴 trajectory가 여러 정책 버전으로 이어 붙여진다. σ를 올리면 꼬리가 나빠진다.

Things to check in the figure:

  1. Synchronous, σ = 0.9: the left panel is a cliff followed by a long, thin tail; training tokens per step is a small fraction of 64. Raise σ to 1.4 and it gets much worse, exactly as eσ2/2−σzNe^{\sigma^2/2 - \sigma z_N} predicts.
  2. Over-sample + abort with r = 0.25: launch 80, stop at the 64th completion. The iteration is several times shorter, but the right panel shows the price twice: grey aborted work, and a kept set whose mean length is well below the population’s. The trainer now sees a length-biased sample, exactly the responses that finished fast. On hard prompts the long responses are often the ones still reasoning, so this bias can push the policy towards short answers.
  3. Partial rollout: no idle slots and no length bias, but long trajectories are now coloured amber and red: they were generated partly by older weights.

The published systems are points in this space.

  • Over-sampling with abort. verl added an over-sample strategy to its SGLang multi-turn rollout that aborts the remaining requests once the target count is reached; aborted requests come back as padding and are excluded from the reward average. MiMo-7B’s rollout engine terminates ongoing tasks only once the valid-sample count meets the batch requirement, with FIFO selection (MiMo-7B).
  • Partial rollout (carry the unfinished forward). Kimi k1.5 fixes an output-token budget per iteration and saves unfinished trajectories to continue in the next one; K3 pauses generation once a fraction λ of responses is done (K3); APRIL over-provisions requests, stops at the target and continues the unfinished ones later (up to 44% higher rollout throughput in its experiments). AReaL goes fully asynchronous: rollout workers never wait, and when new weights arrive they are interrupted, discard the KV cache computed with the old weights, recompute it with the new ones and continue, so a trajectory is a concatenation of segments from several policy versions. A staleness bound η\eta throttles new requests so a training batch is never more than η\eta versions behind (up to 2.77× over synchronous systems).
  • Resume, never restart. DeepSeek-V4’s rollout service resumes interrupted requests from a token-level write-ahead log and the saved KV cache, and notes that regenerating them from scratch would bias towards short responses, the same bias as abort (V4).

The off-policy tokens that partial rollouts create are handled on the algorithm side, with staleness-aware importance weights and masks (async and staleness). Two systems tricks also shorten the tail itself: speculative decoding is at its best when the batch has shrunk to a few stragglers (speculative decoding), and prefill–decode disaggregation stops long multi-turn prefills from stalling decodes.

The trainer side of the same problem. Long-tailed lengths also waste the trainer’s FLOPs when sequences are padded to the longest. Two standard fixes are sequence packing (remove padding and concatenate variable-length samples, with attention masks or variable-length kernels keeping them separate; use_remove_padding in verl) and token-budget dynamic batching (form micro-batches by a maximum number of tokens rather than a number of samples; use_dynamic_bsz with ppo_max_token_len_per_gpu, which verl recommends setting to at least 2×2\times(max prompt + max response length)).

Why the engine’s log-probs differ from the trainer’s

Take the same weights and the same token sequence. The engine reported log⁡μ(yt)\log \mu(y_t) when it sampled; the trainer recomputes log⁡π(yt)\log \pi(y_t). They are rarely bit-identical. The sources, roughly from most to least universal:

  1. Floating-point addition is not associative. (0.1+1020)−1020=0(0.1 + 10^{20}) - 10^{20} = 0 but 0.1+(1020−1020)=0.10.1 + (10^{20} - 10^{20}) = 0.1. Every matmul, norm and softmax is a reduction, and its result depends on the order of additions.
  2. The order depends on the batch. A kernel is deterministic run to run for a fixed shape, but serving kernels pick their strategy from the shape: split-K for small batches (to occupy all SMs), different tensor-core instructions or tiles, split-KV in decode attention with a fixed number of splits, chunked-prefill boundaries. The batch a request lands in depends on server load, so the same request gets different bits depending on who else is in the batch. This, not GPU thread races, is the main cause of nondeterminism in LLM inference (Thinking Machines; a typical forward pass contains no atomic adds).
  3. The trainer and the engine use different kernels. Fused versus unfused ops, different attention backends, different TP sizes (all-reduce order changes with the number of ranks; TBIK targets exactly this), and precision choices such as a bf16 LM-head output. MiniMax-M1 found its training/inference token-probability correlation stuck around 0.9x and traced it to the LM head; computing it in FP32 brought it to 0.99x (MiniMax).
  4. Discrete decisions amplify tiny differences. MoE top-kk routing is discontinuous: a 10−310^{-3} change in a router logit near the kk-th/(k+1)(k{+}1)-th boundary swaps an expert. R3 measured about 10% of routers choosing a different expert between engine and trainer on Qwen3-30B-A3B, with 94% of tokens differing in at least one layer, and a sampler–trainer KL of 1.5e-3 versus 6.4e-4 for a dense 8B model. GLM-5 hit the same with DSA’s top-kk token selection and switched the trainer to a deterministic torch.topk.
  5. Sampling-side mismatch. Raw versus processed log-probs, and top-p/top-k truncation (above). Speculative decoding verifies on a different token layout, so it inherits (2).

The figure lets you watch 2–4 happen in a small bf16 network whose arithmetic is emulated bit for bit.

그림에서 확인할 것:

  1. 동기 배치, σ = 0.9: 왼쪽은 절벽 뒤에 길고 가는 꼬리가 이어진다. step당 학습 토큰은 64의 작은 부분이다. σ를 1.4로 올리면 eσ2/2−σzNe^{\sigma^2/2 - \sigma z_N}이 예측하는 대로 훨씬 나빠진다.
  2. over-sample + abort, r = 0.25: 80개를 띄우고 64번째 완료에서 멈춘다. iteration은 몇 배 짧아지지만 오른쪽이 대가를 두 번 보여 준다. 회색의 중단된 작업, 그리고 평균 길이가 모집단보다 한참 짧은 학습 집합. trainer는 빨리 끝난 응답, 즉 길이로 편향된 표본을 보게 된다. 어려운 prompt에서는 긴 응답이 아직 추론 중인 응답인 경우가 많으므로 이 편향은 정책을 짧은 답 쪽으로 밀 수 있다.
  3. partial rollout: 노는 슬롯도 길이 편향도 없지만, 긴 trajectory가 주황과 빨강으로 칠해진다. 일부가 이전 가중치로 생성되었다.

공개된 시스템들은 이 공간의 한 점들이다.

  • over-sampling + abort. verl은 SGLang 멀티턴 rollout에 목표 수에 도달하면 남은 요청을 중단하는 over-sample 전략을 넣었다. 중단된 요청은 padding으로 돌아오고 보상 평균에서 빠진다. MiMo-7B의 rollout 엔진은 유효 샘플 수가 배치 요구를 채웠을 때만 진행 중인 작업을 끝내고 FIFO로 고른다(MiMo-7B).
  • partial rollout(끝나지 않은 것을 넘긴다). Kimi k1.5는 iteration마다 출력 토큰 예산을 정하고 끝나지 않은 trajectory를 저장해 다음 iteration에 잇는다. K3는 응답의 λ 비율이 끝나면 생성을 멈춘다(K3). APRIL은 요청을 넉넉히 띄우고 목표 수에서 멈춘 뒤 끝나지 않은 것을 나중에 잇는다(실험에서 rollout 처리량 최대 44% 향상). AReaL은 완전 비동기다. rollout worker는 기다리지 않고, 새 가중치가 오면 중단되어 이전 가중치로 계산한 KV cache를 버리고 새 가중치로 다시 계산한 뒤 이어 간다. 그래서 trajectory는 여러 정책 버전의 조각을 이어 붙인 것이 된다. staleness 상한 η\eta가 새 요청을 조절해 학습 배치가 η\eta 버전보다 뒤처지지 않게 한다(동기 시스템 대비 최대 2.77×).
  • 다시 시작하지 말고 이어 간다. DeepSeek-V4의 rollout 서비스는 중단된 요청을 토큰 단위 write-ahead log와 저장된 KV cache로 재개하며, 처음부터 다시 생성하면 짧은 응답 쪽으로 편향된다고 지적한다. abort와 같은 편향이다(V4).

partial rollout이 만드는 off-policy 토큰은 알고리즘 쪽에서 staleness를 고려한 importance weight와 mask로 다룬다(비동기와 staleness). 꼬리 자체를 줄이는 시스템 요령도 둘 있다. 배치가 소수의 낙오자로 줄었을 때가 speculative decoding이 가장 빛나는 때이고(speculative decoding), prefill–decode 분리는 긴 멀티턴 prefill이 decode를 멈추지 못하게 한다.

같은 문제의 trainer 쪽. 길이의 긴 꼬리는 시퀀스를 가장 긴 것에 맞춰 padding할 때 trainer의 FLOP도 낭비한다. 표준 해법은 둘이다. sequence packing(padding을 없애고 가변 길이 샘플을 이어 붙이며, attention mask나 가변 길이 커널로 서로를 분리한다. verl의 use_remove_padding)과 토큰 예산 dynamic batching(micro-batch를 샘플 수가 아니라 최대 토큰 수로 구성한다. use_dynamic_bsz와 ppo_max_token_len_per_gpu, verl은 이를 최소 2×2\times(최대 prompt + 최대 응답 길이)로 두라고 권한다).

엔진의 log-prob은 왜 trainer와 다른가

같은 가중치, 같은 토큰 시퀀스를 놓자. 엔진은 샘플링할 때 log⁡μ(yt)\log \mu(y_t)를 보고했고, trainer는 log⁡π(yt)\log \pi(y_t)를 다시 계산한다. 비트까지 같은 경우는 드물다. 원인을 대략 보편적인 것부터 늘어놓으면 이렇다.

  1. 부동소수점 덧셈은 결합법칙이 성립하지 않는다. (0.1+1020)−1020=0(0.1 + 10^{20}) - 10^{20} = 0이지만 0.1+(1020−1020)=0.10.1 + (10^{20} - 10^{20}) = 0.1이다. 모든 matmul, norm, softmax는 reduction이고 그 결과는 덧셈 순서에 달렸다.
  2. 그 순서가 배치에 달렸다. 커널은 고정된 shape에서는 실행마다 결정적이지만, 서빙 커널은 shape를 보고 전략을 고른다. 작은 배치에서는 (모든 SM을 쓰려고) split-K, 다른 tensor core 명령이나 tile, decode attention에서 split 개수를 고정한 split-KV, chunked prefill의 경계. 요청이 어느 배치에 들어가는지는 서버 부하에 달렸으므로 같은 요청이 함께 배치된 다른 요청에 따라 다른 비트를 얻는다. GPU 스레드 경쟁이 아니라 이것이 LLM 추론 비결정성의 주원인이다(Thinking Machines. 전형적인 forward에는 atomic add가 없다).
  3. trainer와 엔진이 다른 커널을 쓴다. fused와 unfused 연산, 다른 attention 백엔드, 다른 TP 크기(all-reduce 순서는 rank 수에 따라 바뀐다. TBIK가 정확히 이것을 겨냥한다), bf16 LM head 출력 같은 정밀도 선택. MiniMax-M1은 학습/추론 토큰 확률의 상관이 0.9x에서 멈춘 원인을 LM head로 추적했고, 이를 FP32로 계산하자 0.99x가 되었다(MiniMax).
  4. 이산적 결정이 작은 차이를 증폭한다. MoE의 top-kk routing은 불연속이다. kk번째/(k+1)(k{+}1)번째 경계 근처에서 router logit이 10−310^{-3}만 바뀌어도 expert가 바뀐다. R3는 Qwen3-30B-A3B에서 엔진과 trainer 사이에 router의 약 10%가 다른 expert를 고르고, 토큰의 94%가 적어도 한 layer에서 다르며, 샘플러–trainer KL이 dense 8B 모델의 6.4e-4 대비 1.5e-3임을 측정했다. GLM-5는 DSA의 top-kk 토큰 선택에서 같은 문제를 만나 trainer를 결정적 torch.topk로 바꿨다.
  5. 샘플링 쪽 불일치. 원시 대 처리된 log-prob, top-p/top-k 절단(위 참고). speculative decoding은 다른 토큰 배치로 검증하므로 (2)를 물려받는다.

아래 그림에서 산술을 비트 단위로 흉내 낸 작은 bf16 네트워크로 2–4가 일어나는 것을 볼 수 있다.

64 tokens scored by a sampler (inference engine) and a trainer with the same bf16 weights (an 8-layer bf16 toy, precomputed with the NumPy code below). Left: per token, ■ engine − trainer log-prob, and ● engine at batch B − the same engine at batch 1. Right: mean |Δ log p| against the trainer as the server batch changes. Move B: the engine's split-K choice changes with load, so the same request gets different bits at different batch sizes. Batch-invariant kernels make the grey dots vanish (one reduction order for every batch) but the gap to the trainer stays. Set the trainer to the same kernels as well and the gap is exactly zero: truly on-policy. An fp32 LM head shrinks the gap but does not close it, because bf16 rounding flips in the hidden states have already propagated. 같은 bf16 가중치로 샘플러(추론 엔진)와 trainer가 토큰 64개를 채점한다(8-layer bf16 장난감, 아래 NumPy 코드로 미리 계산). 왼쪽: 토큰마다 ■ 엔진 − trainer log-prob, ● 배치 B의 엔진 − 배치 1의 같은 엔진. 오른쪽: 서버 배치에 따른 trainer 대비 평균 |Δ log p|. B를 움직이면 엔진의 split-K 선택이 부하에 따라 바뀌어 같은 요청이 배치 크기마다 다른 비트를 얻는다. batch-invariant 커널은 회색 점을 없애지만(모든 배치에 같은 reduction 순서) trainer와의 차이는 남는다. trainer도 같은 커널로 바꾸면 차이가 정확히 0이 된다. 진짜 on-policy다. fp32 LM head는 차이를 줄이지만 없애지는 못한다. hidden state의 bf16 반올림 뒤집힘이 이미 전파되었기 때문이다.

Things to check:

  1. At the default (batch 1, default kernels) most tokens are bit-identical to the trainer, and a few differ by up to ~1e-2 in log-prob. Slide B: the grey dots appear, meaning the same engine gives the same request different log-probs at different load. The right panel steps as the kernel’s split-K choice changes.
  2. Switch the engine to batch-invariant: the grey dots vanish and the right curve goes flat. The gap to the trainer is still there: invariance makes the engine consistent with itself.
  3. Also set the trainer to the same kernels: every bar is exactly zero. This is what Thinking Machines calls truly on-policy RL.
  4. Switch the LM head to fp32 with default kernels: the gap shrinks but does not vanish. The head is one source among many; earlier bf16 rounding flips in the hidden state have already propagated.
  5. Read the last statistic: per-token differences of 10−410^{-4} look harmless, but the sequence log-ratio is a sum over tokens, and its spread grows as T\sqrt{T}. For a 32K-token agent trajectory, sequence-level importance weights built from these log-probs carry visible noise from numerics alone.

The NumPy version runs the same experiment at a larger scale, then shows greedy decoding diverging under load and MoE routing flipping.

NumPy Batch-dependent split-K changes log-probs (bf16 network, fp32 accumulation)
import numpy as np

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

print("non-associativity:", (0.1 + 1e20) - 1e20, "vs", 0.1 + (1e20 - 1e20))

def matmul(X, W, splits=1, tree=False):
    """Y = X @ W.T with the reduction dim K cut into chunks, fp32 inside a chunk.
    splits=s: s chunks added left to right (a split-K kernel); tree=True: 64-wide tiles added pairwise.
    Same mathematics, different association of the sums."""
    K = X.shape[1]
    edges = np.arange(0, K + 1, 64) if tree else np.linspace(0, K, splits + 1).astype(int)
    parts = [X[:, a:b] @ W[:, a:b].T for a, b in zip(edges[:-1], edges[1:])]
    if tree:
        while len(parts) > 1:
            parts = [(parts[i] + parts[i + 1]).astype(np.float32) for i in range(0, len(parts) - 1, 2)] + \
                    ([parts[-1]] if len(parts) % 2 else [])
        return parts[0]
    Y = parts[0]
    for p in parts[1:]:
        Y = (Y + p).astype(np.float32)
    return Y

def engine_splits(batch):
    """Illustrative heuristic: a small batch leaves SMs idle, so the kernel splits K more."""
    return 8 if batch <= 8 else 4 if batch <= 32 else 3 if batch <= 128 else 1

rs = np.random.default_rng(0)
d, V, L, T = 512, 1024, 8, 128
Ws = [bf16(rs.normal(0, 1 / np.sqrt(d), (d, d)).astype(np.float32)) for _ in range(L)]
Wout = bf16(rs.normal(0, 3 / np.sqrt(d), (V, d)).astype(np.float32))
X = bf16(rs.normal(0, 1, (T, d)).astype(np.float32))          # hidden states of T tokens

def logprobs(splits=1, tree=False, head_fp32=False):
    h = X
    for W in Ws:                                                # residual stack with bf16 activations
        h = bf16(h + bf16(np.tanh(bf16(matmul(h, W, splits, tree)))))
    z = matmul(h, Wout, splits, tree)
    z = (z if head_fp32 else bf16(z)).astype(np.float64)        # bf16 vs fp32 LM-head output
    m = z.max(1, keepdims=True)
    return z - m - np.log(np.exp(z - m).sum(1, keepdims=True))

idx = np.arange(T)
trainer = logprobs(tree=True)                                   # the trainer's kernels: a different library
tok = trainer.argmax(1)                                         # score these tokens
alone = logprobs(engine_splits(1))                              # the same requests served at batch 1
print(f"\n{T} tokens through {L} layers (bf16 activations); logprob of the same token:")
print(" server batch | split-K | bit-identical to batch 1 | mean |dlogp| vs batch 1 | mean |dlogp| vs trainer")
for B in [1, 16, 64, 256]:
    lp = logprobs(engine_splits(B))
    d1, dt = lp[idx, tok] - alone[idx, tok], lp[idx, tok] - trainer[idx, tok]
    print(f" {B:12d} |   {engine_splits(B)}     |        {np.mean(d1 == 0):6.1%}           |      {np.abs(d1).mean():.1e}"
          f"          |     {np.abs(dt).mean():.1e}")

inv = logprobs(4)                                               # batch-invariant: ONE config for every batch
print(f"\nbatch-invariant engine: identical at every batch by construction; vs trainer still "
      f"{np.abs(inv[idx, tok] - trainer[idx, tok]).mean():.1e}")
same = logprobs(tree=True)                                      # trainer and sampler share kernels
print(f"sampler uses the trainer's kernels: max |dlogp| = {np.abs(same - trainer).max():.1e}  -> truly on-policy")
h32 = logprobs(8, head_fp32=True)[idx, tok] - logprobs(tree=True, head_fp32=True)[idx, tok]
print(f"fp32 LM head only (batch 1 vs trainer): mean |dlogp| = {np.abs(h32).mean():.1e}  (hidden-state flips remain)")
 

About 10% of tokens change bits when the server batch changes, and every engine configuration differs from the trainer’s by 1e-5 to 1e-4 on average. Only sharing kernels gives exact zeros. The split-K heuristic here is illustrative; real libraries choose among many more configurations, which is why Thinking Machines fixed a single kernel configuration for all shapes.

Next: what that does to greedy decoding when the batch changes with load at every step, and how sensitive top-kk routing is.

NumPy Greedy decoding under load, and MoE routing flips
# (a) greedy decoding under varying server load: same prompt, many runs
rs = np.random.default_rng(2)
dg, Vg, steps, runs = 128, 256, 100, 120
A = bf16(rs.normal(0, 2.0 / np.sqrt(dg), (dg, dg)).astype(np.float32))
Emb = bf16(rs.normal(0, 1.0, (Vg, dg)).astype(np.float32))
Wo = bf16(rs.normal(0, 1.0 / np.sqrt(dg), (Vg, dg)).astype(np.float32))

def decode(load_rng=None):
    """Greedy decode for all runs at once; each run sees a random server batch (load) at every step."""
    h = np.tile(Emb[0] * 0.5, (runs, 1))
    toks = np.zeros((runs, steps), dtype=np.intp)
    for t in range(steps):
        s = np.full(runs, 1) if load_rng is None else \
            np.array([8, 4, 3, 1])[np.searchsorted([8, 32, 128], load_rng.integers(1, 257, runs))]  # engine_splits
        z = np.empty((runs, Vg), np.float32)
        hn = np.empty_like(h)
        for sp in np.unique(s):                                  # group runs by the kernel config they got
            g = s == sp
            hn[g] = bf16(np.tanh(bf16(matmul(h[g], A, int(sp)) + 0.5 * Emb[toks[g, t - 1] if t else 0])))
            z[g] = bf16(matmul(hn[g], Wo, int(sp)))
        h = hn
        toks[:, t] = z.argmax(1)
    return toks

fixed = decode()                                                 # one kernel config for every request
loaded = decode(np.random.default_rng(7))
uniq = lambda tk: len({tuple(r) for r in tk})
first_div = next((t for t in range(steps) if len(set(loaded[:, t])) > 1), None)
print(f"{runs} greedy runs of the same prompt, {steps} tokens each")
print(f"  batch-invariant serving : {uniq(fixed)} distinct completion(s)")
counts = sorted(np.unique([hash(tuple(r)) for r in loaded], return_counts=True)[1], reverse=True)
print(f"  load-dependent kernels  : {uniq(loaded)} distinct completions {[int(c) for c in counts]}, first divergence at token {first_div}")

# (b) MoE routing is a discontinuous function of tiny numerical differences
E, k, n = 128, 8, 4096
Wr = rs.normal(0, 1 / np.sqrt(dg), (E, dg)).astype(np.float32)
H = rs.normal(0, 1, (n, dg)).astype(np.float32)
top = lambda S: np.sort(np.argsort(-S, 1)[:, :k], 1)
base = top(H @ Wr.T)
print(f"\nrouter: {E} experts, top-{k}; perturb the router input by a relative eps (bf16 ulp ~ 4e-3)")
for eps in [1e-4, 1e-3, 4e-3]:
    Hp = H * (1 + eps * rs.standard_normal(H.shape).astype(np.float32))
    f = np.mean((top(Hp @ Wr.T) != base).any(1))
    print(f"  eps={eps:.0e}: tokens with a different expert set in ONE layer = {f:6.2%};"
          f"  in at least one of 48 layers (if independent) = {1 - (1 - f) ** 48:5.1%}")
 

Greedy decoding is supposed to be deterministic. With load-dependent kernels the same prompt splits into two completions (74 and 46 of 120 runs) after 63 identical tokens: a rounding flip near an argmax tie. Thinking Machines saw the same thing at scale: 1,000 temperature-0 completions of one prompt on Qwen3-235B-A22B gave 80 distinct outputs, identical for the first 102 tokens; with batch-invariant kernels all 1,000 were identical. For routing, perturbations at bf16 rounding scale change a token’s expert set in ~1–3% of layers, which over 48 layers touches most tokens; that compounding is why R3 measures most tokens differing somewhere.

Batch-invariant kernels and deterministic sampling

Batch invariance means: the reduction order for every output element is fixed, whatever the batch size. Thinking Machines’ recipe, kernel by kernel:

  • RMSNorm: one batch element per core, so each row’s reduction stays inside one core. At small batch this leaves cores idle; a split reduction would fix that but changes the order, so you accept the slowdown.
  • Matmul: no split-K that depends on the shape, and one tile/instruction configuration for every shape. Their batch-invariant matmul is about 20% slower than cuBLAS.
  • Attention: update the KV cache and page table before the attention kernel so cached and new keys are reduced in one consistent layout (a token’s reduction must not depend on how many of its sequence’s tokens are processed in the same step, which chunked prefill and prefix caching otherwise break). For split-KV decoding, fix the split size, not the number of splits: a 1,000-token KV is cut into 256 + 256 + 256 + 232 regardless of the batch.

On Qwen3-8B (1,000 sequences, one GPU) default vLLM took 26 s, the unoptimised deterministic version 55 s, and 42 s with an improved attention kernel. SGLang integrated these kernels with CUDA graphs (2.8× over deterministic mode without graphs), radix cache and chunked prefill (aligning chunk boundaries to multiples of the split-KV size), measuring an average 34.35% slowdown against 61.5% in the original blog; at the time it supported TP1/TP2 and dense models only. vLLM exposes the same idea as VLLM_BATCH_INVARIANT=1. TP size is a separate axis: an all-reduce over 4 ranks associates sums differently from one over 8, and TBIK aligns intra- and inter-GPU reductions in one binary tree to make results bit-identical across TP sizes, including between vLLM and FSDP.

Sampling. A shared random generator consumed in batch order makes the token sampled for a request depend on the batch too. The fix is to derive the noise from (request seed, position) only and sample by Gumbel-max, arg⁡max⁡x(zx/T+Gx)\arg\max_x (z_x/T + G_x), which has exactly the softmax distribution. SGLang’s deterministic mode does this with a seeded hash (multinomial_with_seed).

NumPy Seeded Gumbel-max sampling is independent of the batch
# (c) sampling that does not depend on who else is in the batch
def softmax(z):
    e = np.exp(z - z.max()); return e / e.sum()

def sample_seeded(logits, seed, pos, temp=1.0):
    """Gumbel-max with noise derived from (request seed, position) only: argmax(z/T + G) ~ softmax(z/T)."""
    g = -np.log(-np.log(np.random.default_rng([seed, pos]).random(logits.shape[-1])))
    return int(np.argmax(logits / temp + g))

zt = np.array([2.0, 1.0, 0.5, 0.0, -1.0])
draws = np.array([sample_seeded(zt, s, 0) for s in range(5000)])
freq = np.bincount(draws, minlength=len(zt)) / len(draws)
print(f"Gumbel-max frequencies {np.round(freq, 3)} vs softmax {np.round(softmax(zt), 3)}")

reqs = {101: rs.normal(0, 1, 50), 202: rs.normal(0, 1, 50), 303: rs.normal(0, 1, 50)}   # request id -> logits
def serve(order, pos=7, global_seed=0):
    shared = np.random.default_rng(global_seed)            # one generator consumed in batch order
    out_shared, out_seeded = {}, {}
    for rid in order:
        out_shared[rid] = int(shared.choice(50, p=softmax(reqs[rid])))
        out_seeded[rid] = sample_seeded(reqs[rid], rid, pos)
    return out_shared, out_seeded
a_sh, a_se = serve([101, 202, 303])
b_sh, b_se = serve([303, 101])                              # different batch: 202 finished, order changed
print("shared RNG stream, request 101:", a_sh[101], "->", b_sh[101], "| 303:", a_sh[303], "->", b_sh[303])
print("per-request seed,  request 101:", a_se[101], "->", b_se[101], "| 303:", a_se[303], "->", b_se[303])
 

Is bit-exactness worth it? In Thinking Machines’ RL experiment, training without importance weighting on a mismatched sampler made the reward collapse partway through, importance weighting kept the sampler–trainer KL around 1e-3 with spikes, and the bitwise-matched setup kept it flat at exactly 0. SGLang with slime reproduced identical training curves across two runs of Qwen3-8B, which also required deterministic settings on the training side (FA2 for deterministic backward, Megatron’s deterministic mode, NCCL_ALGO=Ring, torch.use_deterministic_algorithms). The cost is 20–60% of inference throughput and engineering work for every new kernel, so most large-scale recipes instead measure and correct the mismatch: token-level truncated or masked importance weights (TIS, MIS, IcePop), sequence-level rejection masks on the length-normalised (geometric-mean) ratio exp⁡(1∣y∣∑tlog⁡ρt)\exp(\frac1{|y|}\sum_t \log \rho_t), routing replay for MoE, an FP32 LM head. Whether the trainer recomputes πold\pi_{\text{old}} (a “decoupled”, three-policy setup with μ≠πold≠πθ\mu \ne \pi_{\text{old}} \ne \pi_\theta) or simply uses the rollout log-probs as πold\pi_{\text{old}} (“bypass”) changes where those corrections enter the loss; see clipping and IS, mismatch engineering and the framework view in verl rollout correction. Determinism remains the best debugging tool: if two runs with the same seed diverge, you know it is not noise.

Weight sync

After each update (or every KK updates in asynchronous RL) the engine needs the new weights. The raw cost is simple, bytes over bandwidth,

tsync≈Nparams⋅bBWeff+treshard+treload,t_{\text{sync}} \approx \frac{N_{\text{params}} \cdot b}{\text{BW}_{\text{eff}}} + t_{\text{reshard}} + t_{\text{reload}},

but every term has a trap. bb is the engine’s precision (FP8 rollouts mean re-quantising every sync); the trainer’s layout (FSDP shards, or TP×PP×EP) differs from the engine’s (TP with DP-attention and wide EP), so tensors must be gathered and re-sliced (parallelism for serving); and the engine must not run out of memory while old and new copies coexist (hence staged wake-up).

The strategies, roughly in order of sophistication:

StrategyHowNotes from public sources
Colocated, in-placeTrainer and engine share GPUs; hand over CUDA IPC handles or reshard in placeHybridFlow’s 3D-HybridEngine; sleep/wake to release memory
NCCL broadcastTrainer ranks broadcast bucketed tensors to engine ranks over a shared process groupOverlap bucket n+1’s copy with bucket n’s broadcast
checkpoint-enginePipeline H2D → broadcast among workers into a CUDA-IPC buffer → the engine reloads the slice it needs; P2P mode for instances that join mid-runKimi-K2 (1T) across thousands of GPUs in about 20 s; e.g. Kimi-K2-Instruct (FP8) on 256×H20 TP16: 16.0 s broadcast
Delta syncByte-diff each shard against a CPU snapshot; send only changed (position, value) pairs; checksum on receiptAbout 1–3% of parameter bytes change per step for dense models, 0.02–0.05% for a 235B MoE early on; Qwen3-235B-A22B sync 11–15 s vs 246–266 s full broadcast (~21×)

Delta sync works because RL updates are sparse at bf16 resolution: most parameters move by less than half a bf16 ulp and their bits do not change at all, consistent with the finding that RL fine-tunes a subnetwork of 5–30% of parameters (Mukherjee et al.). What happens to in-flight requests during a sync is a policy decision, not a detail: AReaL interrupts them and recomputes the KV cache under the new weights; NVIDIA’s Nemotron 3 Super keeps the old KV cache and lets generation continue, then masks tokens whose engine/trainer ratio diverges too far (Nemotron 3 Ultra). Either way the trajectory mixes policy versions, which the trainer must know about.

→ See also: Asynchronous RL systems compared for weight-sync arithmetic and admission rules across real frameworks; distillation and synthetic data for the teacher-side counterpart — shipping top-k teacher log-probs through a one-/two-step-off asynchronous pipeline.

확인 문제Check yourself

Rollout lengths are log-normal with σ = 1.2 and N = 64 per batch. Roughly what fraction of slot-steps does a synchronous iteration spend on useful decoding?

U≈eσ2/2−σzNU \approx e^{\sigma^2/2 - \sigma z_N} with z64≈2.2z_{64} \approx 2.2: e0.72−2.64=e−1.92≈0.15e^{0.72 - 2.64} = e^{-1.92} \approx 0.15, so on the order of 10–15%. The longest of 64 responses is about e1.2⋅2.2≈14×e^{1.2 \cdot 2.2} \approx 14\times the median, while the mean is only e0.72≈2×e^{0.72} \approx 2\times the median.

확인 문제Check yourself

Your rollout engine uses batch-invariant kernels and per-request seeded sampling. The trainer uses its own fused kernels. What is true?

Batch invariance makes the engine consistent with itself: the same request gives the same bits at any batch size, and seeded Gumbel-max makes sampling independent of batch order too. But the trainer associates its sums differently, so log⁡π−log⁡μ≠0\log\pi - \log\mu \ne 0. Bit-identical log-probs need the trainer to run the same kernels (and the same TP reduction order), as in the “truly on-policy” setup.

Summary

  • In RL the engine sits inside the loop: the batch must finish, its log-probs must match the trainer’s, and its weights change every step. It must return token ids, the right log-probs and (for MoE) routing, and route multi-turn requests to the replica holding their prefix.
  • Synchronous rollouts waste most of an iteration on the tail: utilisation ≈eσ2/2−σzN\approx e^{\sigma^2/2-\sigma z_N}. Over-sampling with abort removes the tail but keeps a length-biased (short) sample; partial rollouts keep slots full and avoid the bias but stitch trajectories from several policy versions.
  • Engine and trainer log-probs differ because reductions are non-associative and their order depends on the batch (split-K, split-KV, chunked prefill), on kernels and TP size, and on precision (LM head); discrete routing amplifies the differences.
  • Batch-invariant kernels (fixed reduction order, fixed split size) and seeded Gumbel sampling make inference reproducible at a 20–60% throughput cost; bit-identical sampler and trainer need shared kernels. Most recipes measure and correct the mismatch instead.
  • Weight sync is bytes ÷ bandwidth plus resharding, re-quantisation and memory juggling; checkpoint-engine pipelines it, and delta sync exploits the bit-level sparsity of RL updates.

확인할 것:

  1. 기본값(배치 1, 기본 커널)에서 대부분의 토큰은 trainer와 비트까지 같고, 몇몇은 log-prob이 최대 ~1e-2까지 다르다. B를 움직이면 회색 점이 나타난다. 같은 엔진이 같은 요청에 부하에 따라 다른 log-prob을 준다는 뜻이다. 오른쪽은 커널의 split-K 선택이 바뀔 때마다 계단을 그린다.
  2. 엔진을 batch-invariant로 바꾸면 회색 점이 사라지고 오른쪽 곡선이 평평해진다. trainer와의 차이는 그대로다. invariance는 엔진을 자기 자신과 일치시킨다.
  3. trainer도 같은 커널로 바꾸면 모든 막대가 정확히 0이다. Thinking Machines가 진짜 on-policy RL이라 부르는 상태다.
  4. 기본 커널에서 LM head를 fp32로 바꾸면 차이가 줄지만 사라지지 않는다. head는 여러 원인 중 하나이고, 앞선 hidden state의 bf16 반올림 뒤집힘은 이미 전파되었다.
  5. 마지막 통계를 보자. 토큰당 10−410^{-4}의 차이는 무해해 보이지만 시퀀스 log-ratio는 토큰에 대한 합이고 퍼짐은 T\sqrt{T}로 자란다. 32K 토큰짜리 agent trajectory라면 이 log-prob으로 만든 시퀀스 단위 importance weight는 수치 문제만으로도 눈에 띄는 잡음을 갖는다.

NumPy 판은 같은 실험을 더 큰 규모로 하고, 이어서 부하 아래에서 greedy decoding이 갈라지는 것과 MoE routing이 뒤집히는 것을 보인다.

NumPy 배치에 따른 split-K가 log-prob을 바꾼다 (bf16 네트워크, fp32 누산)
import numpy as np

def bf16(x):
    """float32를 bfloat16으로 반올림(round-to-nearest-even)하고 float32로 돌려준다."""
    b = np.asarray(x, np.float32).view(np.uint32)
    b = (b + np.uint32(0x7FFF) + ((b >> 16) & np.uint32(1))) & np.uint32(0xFFFF0000)
    return b.view(np.float32)

print("결합법칙 불성립:", (0.1 + 1e20) - 1e20, "vs", 0.1 + (1e20 - 1e20))

def matmul(X, W, splits=1, tree=False):
    """Y = X @ W.T. reduction 차원 K를 조각으로 나누고 조각 안은 fp32.
    splits=s: 조각 s개를 왼쪽부터 더함(split-K 커널); tree=True: 64폭 tile을 쌍으로 더함.
    수학은 같고 덧셈의 결합 순서만 다르다."""
    K = X.shape[1]
    edges = np.arange(0, K + 1, 64) if tree else np.linspace(0, K, splits + 1).astype(int)
    parts = [X[:, a:b] @ W[:, a:b].T for a, b in zip(edges[:-1], edges[1:])]
    if tree:
        while len(parts) > 1:
            parts = [(parts[i] + parts[i + 1]).astype(np.float32) for i in range(0, len(parts) - 1, 2)] + \
                    ([parts[-1]] if len(parts) % 2 else [])
        return parts[0]
    Y = parts[0]
    for p in parts[1:]:
        Y = (Y + p).astype(np.float32)
    return Y

def engine_splits(batch):
    """설명용 휴리스틱: 배치가 작으면 SM이 놀아서 커널이 K를 더 쪼갠다."""
    return 8 if batch <= 8 else 4 if batch <= 32 else 3 if batch <= 128 else 1

rs = np.random.default_rng(0)
d, V, L, T = 512, 1024, 8, 128
Ws = [bf16(rs.normal(0, 1 / np.sqrt(d), (d, d)).astype(np.float32)) for _ in range(L)]
Wout = bf16(rs.normal(0, 3 / np.sqrt(d), (V, d)).astype(np.float32))
X = bf16(rs.normal(0, 1, (T, d)).astype(np.float32))          # 토큰 T개의 hidden state

def logprobs(splits=1, tree=False, head_fp32=False):
    h = X
    for W in Ws:                                                # bf16 activation의 residual 스택
        h = bf16(h + bf16(np.tanh(bf16(matmul(h, W, splits, tree)))))
    z = matmul(h, Wout, splits, tree)
    z = (z if head_fp32 else bf16(z)).astype(np.float64)        # bf16 대 fp32 LM head 출력
    m = z.max(1, keepdims=True)
    return z - m - np.log(np.exp(z - m).sum(1, keepdims=True))

idx = np.arange(T)
trainer = logprobs(tree=True)                                   # trainer의 커널: 다른 라이브러리
tok = trainer.argmax(1)                                         # 이 토큰들을 채점한다
alone = logprobs(engine_splits(1))                              # 같은 요청을 배치 1로 서빙
print(f"\n토큰 {T}개, layer {L}개(bf16 activation); 같은 토큰의 logprob:")
print(" 서버 배치 | split-K | 배치 1과 비트 동일 | 배치 1 대비 평균 |dlogp| | trainer 대비 평균 |dlogp|")
for B in [1, 16, 64, 256]:
    lp = logprobs(engine_splits(B))
    d1, dt = lp[idx, tok] - alone[idx, tok], lp[idx, tok] - trainer[idx, tok]
    print(f" {B:9d} |   {engine_splits(B)}     |      {np.mean(d1 == 0):6.1%}        |      {np.abs(d1).mean():.1e}"
          f"           |     {np.abs(dt).mean():.1e}")

inv = logprobs(4)                                               # batch-invariant: 모든 배치에 설정 하나
print(f"\nbatch-invariant 엔진: 구성상 모든 배치에서 동일; trainer 대비는 여전히 "
      f"{np.abs(inv[idx, tok] - trainer[idx, tok]).mean():.1e}")
same = logprobs(tree=True)                                      # 샘플러가 trainer의 커널을 공유
print(f"샘플러가 trainer 커널 사용: 최대 |dlogp| = {np.abs(same - trainer).max():.1e}  -> 진짜 on-policy")
h32 = logprobs(8, head_fp32=True)[idx, tok] - logprobs(tree=True, head_fp32=True)[idx, tok]
print(f"fp32 LM head만 (배치 1 대 trainer): 평균 |dlogp| = {np.abs(h32).mean():.1e}  (hidden state 뒤집힘은 남음)")
 

서버 배치가 바뀌면 토큰의 약 10%가 비트가 바뀌고, 어떤 엔진 설정이든 trainer와 평균 1e-5에서 1e-4 정도 차이가 난다. 커널을 공유해야만 정확히 0이다. 여기의 split-K 휴리스틱은 설명용이다. 실제 라이브러리는 훨씬 많은 설정 중에서 고르며, 그래서 Thinking Machines는 모든 shape에 커널 설정 하나를 고정했다.

다음은 배치가 step마다 부하에 따라 바뀔 때 greedy decoding에 어떤 일이 생기는지, 그리고 top-kk routing이 얼마나 민감한지다.

NumPy 부하 아래의 greedy decoding과 MoE routing 뒤집힘
# (a) 서버 부하가 바뀌는 greedy decoding: 같은 prompt, 여러 번 실행
rs = np.random.default_rng(2)
dg, Vg, steps, runs = 128, 256, 100, 120
A = bf16(rs.normal(0, 2.0 / np.sqrt(dg), (dg, dg)).astype(np.float32))
Emb = bf16(rs.normal(0, 1.0, (Vg, dg)).astype(np.float32))
Wo = bf16(rs.normal(0, 1.0 / np.sqrt(dg), (Vg, dg)).astype(np.float32))

def decode(load_rng=None):
    """모든 실행을 한꺼번에 greedy decode; 각 실행은 step마다 무작위 서버 배치(부하)를 만난다."""
    h = np.tile(Emb[0] * 0.5, (runs, 1))
    toks = np.zeros((runs, steps), dtype=np.intp)
    for t in range(steps):
        s = np.full(runs, 1) if load_rng is None else \
            np.array([8, 4, 3, 1])[np.searchsorted([8, 32, 128], load_rng.integers(1, 257, runs))]  # engine_splits
        z = np.empty((runs, Vg), np.float32)
        hn = np.empty_like(h)
        for sp in np.unique(s):                                  # 받은 커널 설정별로 실행을 묶는다
            g = s == sp
            hn[g] = bf16(np.tanh(bf16(matmul(h[g], A, int(sp)) + 0.5 * Emb[toks[g, t - 1] if t else 0])))
            z[g] = bf16(matmul(hn[g], Wo, int(sp)))
        h = hn
        toks[:, t] = z.argmax(1)
    return toks

fixed = decode()                                                 # 모든 요청에 커널 설정 하나
loaded = decode(np.random.default_rng(7))
uniq = lambda tk: len({tuple(r) for r in tk})
first_div = next((t for t in range(steps) if len(set(loaded[:, t])) > 1), None)
print(f"같은 prompt의 greedy 실행 {runs}번, 각 {steps}토큰")
print(f"  batch-invariant 서빙  : 서로 다른 완성 {uniq(fixed)}개")
counts = sorted(np.unique([hash(tuple(r)) for r in loaded], return_counts=True)[1], reverse=True)
print(f"  부하 의존 커널        : 서로 다른 완성 {uniq(loaded)}개 {[int(c) for c in counts]}, 처음 갈라진 토큰 {first_div}")

# (b) MoE routing은 작은 수치 차이에 대한 불연속 함수다
E, k, n = 128, 8, 4096
Wr = rs.normal(0, 1 / np.sqrt(dg), (E, dg)).astype(np.float32)
H = rs.normal(0, 1, (n, dg)).astype(np.float32)
top = lambda S: np.sort(np.argsort(-S, 1)[:, :k], 1)
base = top(H @ Wr.T)
print(f"\nrouter: expert {E}개, top-{k}; router 입력에 상대 크기 eps의 교란(bf16 ulp ~ 4e-3)")
for eps in [1e-4, 1e-3, 4e-3]:
    Hp = H * (1 + eps * rs.standard_normal(H.shape).astype(np.float32))
    f = np.mean((top(Hp @ Wr.T) != base).any(1))
    print(f"  eps={eps:.0e}: layer 하나에서 expert 집합이 바뀐 토큰 = {f:6.2%};"
          f"  48개 layer 중 하나 이상(독립 가정) = {1 - (1 - f) ** 48:5.1%}")
 

greedy decoding은 결정적이어야 한다. 부하 의존 커널에서는 같은 prompt가 63개 토큰까지 같다가 두 완성(120번 중 74번과 46번)으로 갈라진다. argmax 동률 근처의 반올림 뒤집힘이다. Thinking Machines도 큰 규모에서 같은 것을 보았다. Qwen3-235B-A22B에서 한 prompt의 temperature 0 완성 1,000개가 서로 다른 80개 출력이었고 처음 102개 토큰은 같았다. batch-invariant 커널에서는 1,000개가 모두 같았다. routing에서는 bf16 반올림 크기의 교란이 layer 하나에서 토큰의 expert 집합을 ~1–3% 바꾸고, 48개 layer에 걸치면 대부분의 토큰이 영향을 받는다. R3가 대부분의 토큰이 어딘가에서 다르다고 측정한 이유가 이 누적이다.

batch-invariant 커널과 결정적 샘플링

batch invariance란 배치 크기와 상관없이 모든 출력 원소의 reduction 순서가 고정되어 있다는 뜻이다. Thinking Machines의 방법을 커널별로 보자.

  • RMSNorm: 코어 하나에 배치 원소 하나를 맡겨 각 행의 reduction이 코어 하나 안에 머물게 한다. 작은 배치에서는 코어가 놀지만, split reduction은 순서를 바꾸므로 느려짐을 받아들인다.
  • Matmul: shape에 따라 바뀌는 split-K를 쓰지 않고, 모든 shape에 tile/명령 설정 하나를 쓴다. batch-invariant matmul은 cuBLAS보다 약 20% 느리다.
  • Attention: attention 커널 전에 KV cache와 page table을 갱신해 캐시된 key와 새 key가 하나의 일관된 배치로 reduction되게 한다(한 토큰의 reduction이 같은 시퀀스의 토큰이 이번 step에 몇 개 처리되는지에 달려서는 안 되는데, chunked prefill과 prefix caching이 이를 깬다). split-KV decoding에서는 split 개수가 아니라 split 크기를 고정한다. KV 1,000토큰은 배치와 무관하게 256 + 256 + 256 + 232로 자른다.

Qwen3-8B(시퀀스 1,000개, GPU 하나)에서 기본 vLLM은 26초, 최적화 안 한 결정적 버전은 55초, attention 커널을 개선하자 42초였다. SGLang은 이 커널들을 CUDA graph(graph 없는 결정적 모드 대비 2.8×), radix cache, chunked prefill(조각 경계를 split-KV 크기의 배수에 맞춤)과 통합해 평균 34.35%의 느려짐을 측정했다(원 블로그는 61.5%). 당시에는 TP1/TP2와 dense 모델만 지원했다. vLLM은 같은 생각을 VLLM_BATCH_INVARIANT=1로 제공한다. TP 크기는 별개의 축이다. rank 4개에 걸친 all-reduce는 8개에 걸친 것과 덧셈 결합이 다르며, TBIK는 GPU 내부와 GPU 사이의 reduction을 하나의 이진 트리로 맞춰 TP 크기가 달라도(vLLM과 FSDP 사이에서도) 비트 동일한 결과를 낸다.

샘플링. 배치 순서대로 소비되는 공유 난수 생성기는 요청에 뽑히는 토큰까지 배치에 의존하게 만든다. 해법은 잡음을 (요청 seed, 위치)에서만 만들고 Gumbel-max arg⁡max⁡x(zx/T+Gx)\arg\max_x (z_x/T + G_x)로 뽑는 것이다. 이는 정확히 softmax 분포를 따른다. SGLang의 결정적 모드는 seed 기반 hash로 이를 한다(multinomial_with_seed).

NumPy seed 기반 Gumbel-max 샘플링은 배치와 무관하다
# (c) 배치에 누가 있든 상관없는 샘플링
def softmax(z):
    e = np.exp(z - z.max()); return e / e.sum()

def sample_seeded(logits, seed, pos, temp=1.0):
    """(요청 seed, 위치)에서만 만든 잡음의 Gumbel-max: argmax(z/T + G) ~ softmax(z/T)."""
    g = -np.log(-np.log(np.random.default_rng([seed, pos]).random(logits.shape[-1])))
    return int(np.argmax(logits / temp + g))

zt = np.array([2.0, 1.0, 0.5, 0.0, -1.0])
draws = np.array([sample_seeded(zt, s, 0) for s in range(5000)])
freq = np.bincount(draws, minlength=len(zt)) / len(draws)
print(f"Gumbel-max 빈도 {np.round(freq, 3)} vs softmax {np.round(softmax(zt), 3)}")

reqs = {101: rs.normal(0, 1, 50), 202: rs.normal(0, 1, 50), 303: rs.normal(0, 1, 50)}   # 요청 id -> logits
def serve(order, pos=7, global_seed=0):
    shared = np.random.default_rng(global_seed)            # 배치 순서대로 소비되는 생성기 하나
    out_shared, out_seeded = {}, {}
    for rid in order:
        out_shared[rid] = int(shared.choice(50, p=softmax(reqs[rid])))
        out_seeded[rid] = sample_seeded(reqs[rid], rid, pos)
    return out_shared, out_seeded
a_sh, a_se = serve([101, 202, 303])
b_sh, b_se = serve([303, 101])                              # 다른 배치: 202는 끝났고 순서도 바뀜
print("공유 난수열,     요청 101:", a_sh[101], "->", b_sh[101], "| 303:", a_sh[303], "->", b_sh[303])
print("요청별 seed,     요청 101:", a_se[101], "->", b_se[101], "| 303:", a_se[303], "->", b_se[303])
 

비트 일치는 그만한 가치가 있나? Thinking Machines의 RL 실험에서 불일치한 샘플러로 importance weighting 없이 학습하면 보상이 중간에 무너졌고, importance weighting은 샘플러–trainer KL을 1e-3 근처에 스파이크와 함께 유지했으며, 비트 일치 설정은 정확히 0에서 평평했다. SGLang과 slime은 Qwen3-8B 두 번의 실행에서 같은 학습 곡선을 재현했는데, 학습 쪽에도 결정적 설정이 필요했다(결정적 backward를 위한 FA2, Megatron의 deterministic mode, NCCL_ALGO=Ring, torch.use_deterministic_algorithms). 대가는 추론 처리량의 20–60%와 새 커널마다의 공학 작업이라, 대부분의 대규모 레시피는 대신 불일치를 측정하고 보정한다. 토큰 단위 truncated/masked importance weight(TIS, MIS, IcePop), 길이로 정규화한(기하평균) ratio exp⁡(1∣y∣∑tlog⁡ρt)\exp(\frac1{|y|}\sum_t \log \rho_t)에 대한 시퀀스 단위 rejection mask, MoE의 routing replay, FP32 LM head. trainer가 πold\pi_{\text{old}}를 다시 계산하느냐(“decoupled”, μ≠πold≠πθ\mu \ne \pi_{\text{old}} \ne \pi_\theta인 세 정책 구성) 아니면 rollout log-prob을 그대로 πold\pi_{\text{old}}로 쓰느냐(“bypass”)에 따라 이 보정이 loss의 어디에 들어가는지가 달라진다. clipping과 IS, mismatch engineering, 프레임워크 관점은 verl rollout correction을 보라. 결정성은 여전히 최고의 디버깅 도구다. 같은 seed의 두 실행이 갈라지면 그것은 잡음이 아니다.

weight sync

업데이트마다(비동기 RL에서는 KK번마다) 엔진은 새 가중치가 필요하다. 원가는 단순히 바이트 나누기 대역폭이다.

tsync≈Nparams⋅bBWeff+treshard+treload,t_{\text{sync}} \approx \frac{N_{\text{params}} \cdot b}{\text{BW}_{\text{eff}}} + t_{\text{reshard}} + t_{\text{reload}},

하지만 항마다 함정이 있다. bb는 엔진의 정밀도다(FP8 rollout이면 sync마다 다시 양자화한다). trainer의 배치(FSDP shard, 또는 TP×PP×EP)는 엔진의 배치(DP-attention을 곁들인 TP와 wide EP)와 달라서 텐서를 모으고 다시 잘라야 한다(서빙의 병렬화). 그리고 옛 사본과 새 사본이 공존하는 동안 엔진이 메모리 부족에 빠지면 안 된다(그래서 단계적 wake-up).

전략을 대략 정교한 순서로 놓으면:

전략방법공개 자료의 메모
colocated, 제자리trainer와 엔진이 GPU를 공유. CUDA IPC handle을 넘기거나 제자리에서 재샤딩HybridFlow의 3D-HybridEngine. sleep/wake로 메모리 해제
NCCL broadcasttrainer rank가 공유 process group으로 버킷 단위 텐서를 엔진 rank에 broadcast버킷 n+1의 복사와 버킷 n의 broadcast를 겹친다
checkpoint-engineH2D → worker 사이 broadcast로 CUDA-IPC 버퍼 → 엔진이 필요한 조각을 reload. 도중에 합류한 인스턴스는 P2P 모드Kimi-K2(1T)를 수천 GPU에 약 20초. 예: Kimi-K2-Instruct(FP8), 256×H20 TP16에서 broadcast 16.0초
delta sync각 shard를 CPU snapshot과 바이트 비교해 바뀐 (위치, 값)만 보내고 수신 측에서 checksum 확인dense 모델은 step당 파라미터 바이트의 약 1–3%, 235B MoE 초기에는 0.02–0.05%가 바뀜. Qwen3-235B-A22B sync 11–15초 대 전체 broadcast 246–266초(~21×)

delta sync가 통하는 것은 RL 업데이트가 bf16 해상도에서 희소하기 때문이다. 대부분의 파라미터는 bf16 ulp의 절반보다 덜 움직여 비트가 전혀 바뀌지 않는다. RL이 파라미터의 5–30%인 부분망만 미세조정한다는 관찰(Mukherjee et al.)과도 맞는다. sync 중 처리 중인 요청을 어떻게 할지는 세부가 아니라 정책 결정이다. AReaL은 요청을 중단하고 새 가중치로 KV cache를 다시 계산한다. NVIDIA의 Nemotron 3 Super는 옛 KV cache를 유지한 채 생성을 이어 가고, 엔진/trainer ratio가 너무 벌어진 토큰을 mask한다(Nemotron 3 Ultra). 어느 쪽이든 trajectory는 정책 버전을 섞으며, trainer는 그것을 알아야 한다.

→ 함께 보기: 실제 프레임워크들의 가중치 동기화 산수와 입장 규칙은 비동기 RL 시스템 비교, 교사 쪽의 같은 문제(top-k 교사 log-prob을 one/two-step-off 비동기 파이프라인으로 보내기)는 증류와 합성 데이터.

확인 문제Check yourself

rollout 길이가 σ = 1.2인 log-normal이고 배치당 N = 64다. 동기 iteration에서 쓸모 있는 decode에 쓰이는 slot-step 비율은 대략?

z64≈2.2z_{64} \approx 2.2로 U≈eσ2/2−σzN=e0.72−2.64=e−1.92≈0.15U \approx e^{\sigma^2/2 - \sigma z_N} = e^{0.72 - 2.64} = e^{-1.92} \approx 0.15, 즉 10–15% 수준이다. 64개 중 가장 긴 응답은 중앙값의 약 e1.2⋅2.2≈14e^{1.2 \cdot 2.2} \approx 14배인데, 평균은 중앙값의 e0.72≈2e^{0.72} \approx 2배밖에 안 된다.

확인 문제Check yourself

rollout 엔진이 batch-invariant 커널과 요청별 seed 샘플링을 쓴다. trainer는 자체 fused 커널을 쓴다. 맞는 것은?

batch invariance는 엔진을 자기 자신과 일치시킨다. 같은 요청은 어떤 배치 크기에서도 같은 비트를 얻고, seed 기반 Gumbel-max는 샘플링도 배치 순서와 무관하게 만든다. 하지만 trainer는 덧셈을 다르게 결합하므로 log⁡π−log⁡μ≠0\log\pi - \log\mu \ne 0이다. 비트 동일한 log-prob에는 trainer도 같은 커널(과 같은 TP reduction 순서)을 써야 한다. “진짜 on-policy” 설정이 그렇다.

정리

  • RL에서 엔진은 루프 안에 있다. 배치가 끝나야 하고, log-prob이 trainer와 맞아야 하며, 가중치가 매 step 바뀐다. 엔진은 토큰 id, 올바른 log-prob, (MoE면) routing을 돌려주고, 멀티턴 요청을 prefix를 가진 replica로 보내야 한다.
  • 동기 rollout은 iteration 대부분을 꼬리에 낭비한다. 활용률 ≈eσ2/2−σzN\approx e^{\sigma^2/2-\sigma z_N}. over-sampling + abort는 꼬리를 없애지만 길이로 편향된(짧은) 표본을 남기고, partial rollout은 슬롯을 채우고 편향을 피하지만 trajectory를 여러 정책 버전으로 이어 붙인다.
  • 엔진과 trainer의 log-prob이 다른 것은 reduction이 결합법칙을 따르지 않고 그 순서가 배치(split-K, split-KV, chunked prefill), 커널과 TP 크기, 정밀도(LM head)에 달렸기 때문이다. 이산적 routing이 차이를 증폭한다.
  • batch-invariant 커널(고정 reduction 순서, 고정 split 크기)과 seed 기반 Gumbel 샘플링은 처리량 20–60%를 내고 추론을 재현 가능하게 만든다. 샘플러와 trainer의 비트 일치에는 커널 공유가 필요하다. 대부분의 레시피는 대신 불일치를 측정하고 보정한다.
  • weight sync는 바이트 ÷ 대역폭에 재샤딩, 재양자화, 메모리 곡예가 더해진다. checkpoint-engine은 이를 파이프라인으로 만들고, delta sync는 RL 업데이트의 비트 수준 희소성을 이용한다.

더 읽을거리Further reading