Track X · Agent RL Frameworks · 05/07

verl rollout correction — 세 정책과 각 옵션의 수식verl rollout correction — three policies and the equation behind every option

verl의 algorithm.rollout_correction이 하는 일을 코드 그대로 수식으로 옮긴다. π_rollout·π_old·π_θ 세 정책, decoupled와 bypass 모드(ppo_clip·reinforce), 토큰·시퀀스 IS와 TIS·IcePop, 11가지 rejection 규칙(k1/k2/k3 × token/seq_sum/seq_mean/seq_max, Geo-RS 포함)을 하나씩 유도하고, length trap과 bias–variance를 그림과 NumPy로 확인한다.What verl's algorithm.rollout_correction actually computes, translated from the code into equations. The three policies π_rollout, π_old and π_θ; decoupled vs bypass mode (ppo_clip and reinforce); token- and sequence-level IS with TIS or an IcePop band; and all eleven rejection rules (k1/k2/k3 × token/seq_sum/seq_mean/seq_max, including Geo-RS). We check the length trap and the bias–variance trade-off with figures and NumPy.

The mismatch lesson derived why “on-policy” LLM RL is off-policy and what importance sampling can and cannot do about it; clipping and IS compares the published correction rules. This lesson is narrower and more literal: it takes verl’s algorithm.rollout_correction block and writes down, for every option, the exact quantity the code multiplies into the loss or removes from the mask. Everything below was checked against verl main at commit 4525109 (2026-12-02, version string 0.10.0.dev; latest release v0.9.1): the usage guide docs/algo/rollout_corr.md (last updated 2026-10-11), docs/algo/rollout_corr_math.md, verl/trainer/ppo/rollout_corr_helper.py, verl/trainer/config/algorithm.py and verl/trainer/ppo/core_algos.py. Where the docs and the code disagree, the code wins and the disagreement is pointed out.

Three policies, two drifts

A verl PPO step touches three distributions over the same sampled tokens yty_t in context hth_t:

  • πrollout\pi_{\text{rollout}} — the behaviour policy. Its log-probs come back from vLLM/SGLang with each sampled token when actor_rollout_ref.rollout.calculate_log_probs: true and are stored as rollout_log_probs. With partial rollouts (see async systems) one response can be sampled by several weight versions; the recorded per-token log-prob is still the right πrollout\pi_{\text{rollout}} for that token.
  • πold\pi_{\text{old}} — the proximal (anchor) policy: the trainer’s own forward pass over the batch, once, before the mini-batch updates (actor.compute_log_prob(), stored as old_log_probs).
  • πθ\pi_\theta — the policy being updated, recomputed in every micro-batch.

The ratio we would need for an unbiased token-level correction factorises:

πθ(yt∣ht)πrollout(yt∣ht)=πθπold⏟rt(θ): drift 2, update  ⋅  πoldπrollout⏟ρt: drift 1, engine + staleness\frac{\pi_\theta(y_t\mid h_t)}{\pi_{\text{rollout}}(y_t\mid h_t)} =\underbrace{\frac{\pi_\theta}{\pi_{\text{old}}}}_{r_t(\theta):\ \text{drift 2, update}}\;\cdot\;\underbrace{\frac{\pi_{\text{old}}}{\pi_{\text{rollout}}}}_{\rho_t:\ \text{drift 1, engine + staleness}}

Drift 1 is everything that separates the sampler from the trainer at the same step: kernels, precision, MoE routing, sampling transforms, plus staleness when rollouts come from older weights. Drift 2 is what PPO was invented for. The verl docs call the classic bug “PPO that assumes πold=πrollout\pi_{\text{old}}=\pi_{\text{rollout}}”: computing rtr_t against the trainer’s recomputed πold\pi_{\text{old}} and silently ignoring ρt\rho_t. All the options below are ways of not ignoring it.

Decoupled mode: three policies

With bypass_mode: false (the default), verl implements decoupled PPO (Hilton et al. 2021): πold\pi_{\text{old}} controls the step size and a separate weight corrects for the behaviour policy. The per-token loss in compute_policy_loss_vanilla is

ℓt(θ)  =  wt⋅max⁡ ⁣(−At rt(θ),  −At clip⁡(rt(θ),1−εlow,1+εhigh)),rt=πθπold\ell_t(\theta) \;=\; w_t\cdot \max\!\Big(-A_t\,r_t(\theta),\; -A_t\,\operatorname{clip}\big(r_t(\theta),1-\varepsilon_{\text{low}},1+\varepsilon_{\text{high}}\big)\Big),\qquad r_t=\frac{\pi_\theta}{\pi_{\text{old}}}

(plus the dual-clip branch for At<0A_t<0), where wtw_t is a constant built from ρt\rho_t — no stop-gradient is needed because πold\pi_{\text{old}} and πrollout\pi_{\text{rollout}} are both frozen. The weight and the rejection mask are computed once per batch by compute_rollout_correction_and_add_to_batch in the trainer, before advantages are computed: the mask overwrites response_mask, the weights are stored as rollout_is_weights and multiplied into pg_losses. The cost of this mode is one extra forward pass over the batch to get πold\pi_{\text{old}}.

Bypass mode: two policies

With bypass_mode: true the trainer skips that forward pass and copies rollout_log_probs into old_log_probs, i.e. it defines πold:=πrollout\pi_{\text{old}}:=\pi_{\text{rollout}}. Then rt=πθ/πrolloutr_t=\pi_\theta/\pi_{\text{rollout}} and drift 1 and drift 2 are no longer separated. loss_type picks what to do with that single ratio:

loss_type: ppo_clip (default). The ordinary clipped surrogate with rt=πθ/πrolloutr_t=\pi_\theta/\pi_{\text{rollout}}. The ratio is the importance weight, so verl deliberately passes rollout_is_weights=None (multiplying by wtw_t again would count the correction twice). Two consequences that are easy to miss: on the very first mini-batch rt≠1r_t\ne1 (it equals ρt\rho_t, the engine mismatch), so tokens can already sit outside the clip range before any update; and the clip now bounds the total distance from the sampler, which is what you want for stale data.

loss_type: reinforce. No clipping; the loss is

ℓt(θ)=−At  sg⁡ ⁣[wˉt] log⁡πθ(yt∣ht),wˉt=min⁡ ⁣(πθπrollout,C) (token or sequence form)\ell_t(\theta) = -A_t\;\operatorname{sg}\!\big[\bar w_t\big]\,\log\pi_\theta(y_t\mid h_t),\qquad \bar w_t=\min\!\Big(\frac{\pi_\theta}{\pi_{\text{rollout}}},C\Big)\ \text{(token or sequence form)}

The stop-gradient matters. Since ∇θπθπrollout=πθπrollout∇θlog⁡πθ\nabla_\theta\frac{\pi_\theta}{\pi_{\text{rollout}}}=\frac{\pi_\theta}{\pi_{\text{rollout}}}\nabla_\theta\log\pi_\theta, the gradient of −A sg⁡[w]log⁡πθ-A\,\operatorname{sg}[w]\log\pi_\theta equals the gradient of the IS surrogate −A w-A\,w whenever ww is not truncated; differentiating through ww would add a spurious log⁡πθ ∇w\log\pi_\theta\,\nabla w term. With truncation this is a CISPO-style objective (clip the weight, keep every token’s gradient) — compare clipping and IS.

In both bypass variants, the IS weights and rejection statistics are computed inside the loss, per micro-batch, against the current πθ\pi_\theta (under torch.no_grad). So a rejection rule in bypass mode measures engine mismatch + staleness + the updates already applied in this step: it acts as a hard trust region around the sampler, which is exactly the framing of Trust Region Masking (Li et al.). Switching it on requires actor_rollout_ref.actor.use_rollout_log_probs: true, actor_rollout_ref.actor.policy_loss.loss_mode: bypass_mode, and mirroring the rollout_correction block into actor_rollout_ref.actor.policy_loss.rollout_correction.

Weights: rollout_is and rollout_is_threshold

Let δt=log⁡πtrain(yt)−log⁡πrollout(yt)\delta_t=\log\pi_{\text{train}}(y_t)-\log\pi_{\text{rollout}}(y_t), with πtrain=πold\pi_{\text{train}}=\pi_{\text{old}} (decoupled) or πθ\pi_\theta (bypass). The helper first clamps to a safety range [−20,20][-20,20], then:

rollout_israw weight w~t\tilde w_tthen, with rollout_is_threshold
null— (metrics only)—
tokeneδte^{\delta_t}float CC: TIS wt=min⁡(w~t,C)w_t=\min(\tilde w_t,C)
sequenceexp⁡(clamp⁡(∑sδs,±20))\exp\big(\operatorname{clamp}(\sum_{s}\delta_s,\pm20)\big), broadcast to every tokenstring "lo_hi": IcePop wt=w~t 1[lo≤w~t≤hi]w_t=\tilde w_t\,\mathbb 1[\text{lo}\le\tilde w_t\le\text{hi}]

Padding positions are zeroed, and rollout_is_batch_normalize: true divides by the batch mean (over tokens, or over one weight per sequence) after truncation. Note the asymmetry between the two threshold forms: TIS has no lower cut (small weights are kept as they are), while IcePop zeroes both tails. And IcePop changes the weight, not response_mask — under loss_agg_mode: token-mean an IcePop-zeroed token still counts in the denominator, whereas a token removed by a rejection rule does not.

Masks: rollout_rs and rollout_rs_threshold

Rejection rules are built from three per-token divergence statistics (the same k1/k2/k3 estimators used for the KL penalty):

k1=−δt=log⁡πrolloutπtrain,k2=12δt2,k3=eδt−1−δt.k_1=-\delta_t=\log\frac{\pi_{\text{rollout}}}{\pi_{\text{train}}},\qquad k_2=\tfrac12\delta_t^2,\qquad k_3=e^{\delta_t}-1-\delta_t .

Because the tokens were sampled from πrollout\pi_{\text{rollout}}, E[k1]=E[k3]=KL(πrollout ∥ πtrain)\mathbb E[k_1]=\mathbb E[k_3]=\mathrm{KL}(\pi_{\text{rollout}}\,\|\,\pi_{\text{train}}) per token; k3≥0k_3\ge0 always, k1k_1 can be negative. Each option aggregates one statistic and compares it with a threshold; a comma-separated list applies several rules with logical AND:

optionstatistic (per token or per response)kept iff
token_k1k1k_1log⁡lo≤k1≤log⁡hi\log\text{lo}\le k_1\le\log\text{hi}
token_k2, token_k3k2k_2 or k3k_3≤c\le c
seq_sum_k1∑tk1=log⁡∏tπrolloutπtrain\sum_t k_1=\log\prod_t\frac{\pi_{\text{rollout}}}{\pi_{\text{train}}}in [log⁡lo,log⁡hi][\log\text{lo},\log\text{hi}]
seq_sum_k2, seq_sum_k3∑tk2,3\sum_t k_{2,3}≤c\le c
seq_mean_k1 (Geo-RS)1T∑tk1\frac1T\sum_t k_1 = log of the geometric-mean ratioin [log⁡lo,log⁡hi][\log\text{lo},\log\text{hi}]
seq_mean_k2, seq_mean_k3 (K3-RS)1T∑tk2,3\frac1T\sum_t k_{2,3}≤c\le c
seq_max_k2, seq_max_k3max⁡tk2,3\max_t k_{2,3} (worst token)≤c\le c

A k1 threshold given as a single float uu means [1/u,u][1/u,u]. A rejected sequence loses all its tokens from response_mask.

The presets in RolloutCorrectionConfig are just combinations of these pieces. The defaults matter more than the names:

presetmode / lossrollout_is (threshold)rollout_rs (threshold)
decoupled_token_is()decoupledtoken (2.0)—
decoupled_seq_is()decoupledsequence (2.0)—
decoupled_token_icepop()decoupledtoken ("0.5_5.0")—
decoupled_seq_is_rs() (“Seq-MIS”)decoupledsequence (2.0)seq_sum_k1 ("0.5_2.0")
decoupled_geo_rs()decoupled—seq_mean_k1 ("0.999_1.001")
decoupled_geo_rs_token_tis()decoupledtoken (2.0)seq_mean_k1 ("0.999_1.001")
decoupled_k3_rs()decoupled—seq_mean_k3 (0.01)
bypass_ppo_clip()bypass / ppo_clip——
bypass_ppo_clip_geo_rs()bypass / ppo_clip—seq_mean_k1 ("0.999_1.001")
bypass_pg_is()bypass / reinforcesequence (2.0)—
bypass_pg_geo_rs_token_tis()bypass / reinforcetoken (2.0)seq_mean_k1 ("0.999_1.001")

Read the Geo-RS default literally: ∣1T∑tk1∣≤log⁡1.001≈10−3|\frac1T\sum_t k_1|\le\log1.001\approx10^{-3}, i.e. reject a response whose per-token k1 estimate of KL(πrollout∥πtrain)\mathrm{KL}(\pi_{\text{rollout}}\|\pi_{\text{train}}) exceeds about 0.001 nats (or is below −0.001). K3-RS with 0.01 is the same test with the non-negative k3k_3 estimator and a ten times looser budget. Both are KL budgets per token, not “ratio near 1” checks.

The figure below runs these rules on a toy batch. Try the presets, then raise the spike probability and the length multiplier.

불일치 레슨은 “on-policy” LLM RL이 왜 off-policy인지, importance sampling이 무엇을 할 수 있고 없는지를 유도했다. clipping과 IS는 발표된 보정 규칙들을 비교한다. 이 레슨은 더 좁고 더 문자 그대로다. verl의 algorithm.rollout_correction 블록을 가져와, 옵션마다 코드가 손실에 곱하는 양 또는 mask에서 빼는 양을 정확히 적는다. 아래 내용은 모두 verl main 커밋 4525109(2026-12-02, 버전 문자열 0.10.0.dev, 최신 릴리스 v0.9.1)의 사용 가이드 docs/algo/rollout_corr.md(2026-10-11 갱신), docs/algo/rollout_corr_math.md, verl/trainer/ppo/rollout_corr_helper.py, verl/trainer/config/algorithm.py, verl/trainer/ppo/core_algos.py와 대조했다. 문서와 코드가 다르면 코드를 따르고, 차이는 따로 짚는다.

세 정책, 두 drift

verl PPO 한 스텝은 같은 샘플 토큰 yty_t(문맥 hth_t)에 대해 세 분포를 다룬다.

  • πrollout\pi_{\text{rollout}} — behaviour policy. actor_rollout_ref.rollout.calculate_log_probs: true이면 vLLM/SGLang이 샘플한 토큰마다 log-prob을 돌려주고, 이것이 rollout_log_probs로 저장된다. partial rollout(비동기 시스템 참고)에서는 응답 하나를 여러 가중치 버전이 나눠 샘플할 수 있는데, 기록된 토큰별 log-prob은 그 토큰에 대해서는 여전히 올바른 πrollout\pi_{\text{rollout}}이다.
  • πold\pi_{\text{old}} — proximal(anchor) policy. mini-batch 업데이트 전에 학습기가 배치 전체를 한 번 forward한 값이다(actor.compute_log_prob(), old_log_probs).
  • πθ\pi_\theta — 업데이트 중인 정책. micro-batch마다 다시 계산된다.

토큰 단위로 정확히 보정하려면 필요한 ratio는 다음처럼 쪼개진다.

πθ(yt∣ht)πrollout(yt∣ht)=πθπold⏟rt(θ): drift 2, 업데이트  ⋅  πoldπrollout⏟ρt: drift 1, 엔진 + staleness\frac{\pi_\theta(y_t\mid h_t)}{\pi_{\text{rollout}}(y_t\mid h_t)} =\underbrace{\frac{\pi_\theta}{\pi_{\text{old}}}}_{r_t(\theta):\ \text{drift 2, 업데이트}}\;\cdot\;\underbrace{\frac{\pi_{\text{old}}}{\pi_{\text{rollout}}}}_{\rho_t:\ \text{drift 1, 엔진 + staleness}}

drift 1은 같은 스텝에서 sampler와 학습기를 갈라놓는 모든 것이다. 커널, 정밀도, MoE routing, 샘플링 변환, 그리고 rollout이 옛 가중치에서 나왔다면 staleness까지. drift 2는 PPO가 원래 다루려던 것이다. verl 문서가 말하는 고전적 버그는 “πold=πrollout\pi_{\text{old}}=\pi_{\text{rollout}}이라고 가정한 PPO”, 즉 학습기가 다시 계산한 πold\pi_{\text{old}}로 rtr_t를 만들고 ρt\rho_t는 조용히 무시하는 것이다. 아래 옵션들은 모두 이것을 무시하지 않는 방법이다.

Decoupled 모드: 정책 셋

bypass_mode: false(기본값)이면 verl은 decoupled PPO(Hilton et al. 2021)를 구현한다. πold\pi_{\text{old}}가 스텝 크기를 통제하고, 별도의 가중치가 behaviour policy를 보정한다. compute_policy_loss_vanilla의 토큰별 손실은

ℓt(θ)  =  wt⋅max⁡ ⁣(−At rt(θ),  −At clip⁡(rt(θ),1−εlow,1+εhigh)),rt=πθπold\ell_t(\theta) \;=\; w_t\cdot \max\!\Big(-A_t\,r_t(\theta),\; -A_t\,\operatorname{clip}\big(r_t(\theta),1-\varepsilon_{\text{low}},1+\varepsilon_{\text{high}}\big)\Big),\qquad r_t=\frac{\pi_\theta}{\pi_{\text{old}}}

이다(At<0A_t<0일 때의 dual-clip 분기가 더 있다). wtw_t는 ρt\rho_t로 만든 상수다. πold\pi_{\text{old}}와 πrollout\pi_{\text{rollout}}이 둘 다 고정이므로 stop-gradient가 필요 없다. 가중치와 rejection mask는 학습기의 compute_rollout_correction_and_add_to_batch가 배치당 한 번, advantage 계산 전에 만든다. mask는 response_mask를 덮어쓰고, 가중치는 rollout_is_weights로 저장돼 pg_losses에 곱해진다. 이 모드의 비용은 πold\pi_{\text{old}}를 얻기 위한 배치 전체 forward 한 번이다.

Bypass 모드: 정책 둘

bypass_mode: true이면 학습기는 그 forward를 건너뛰고 rollout_log_probs를 old_log_probs로 복사한다. 즉 πold:=πrollout\pi_{\text{old}}:=\pi_{\text{rollout}}으로 정의한다. 그러면 rt=πθ/πrolloutr_t=\pi_\theta/\pi_{\text{rollout}}이 되고 drift 1과 drift 2는 더 이상 분리되지 않는다. 이 하나의 ratio로 무엇을 할지는 loss_type이 정한다.

loss_type: ppo_clip(기본값). rt=πθ/πrolloutr_t=\pi_\theta/\pi_{\text{rollout}}로 계산한 보통의 clipped surrogate다. ratio 자체가 importance weight이므로 verl은 일부러 rollout_is_weights=None을 넘긴다(wtw_t를 또 곱하면 보정을 두 번 하는 셈이다). 놓치기 쉬운 결과가 두 가지 있다. 첫 mini-batch에서 이미 rt≠1r_t\ne1이다(ρt\rho_t, 즉 엔진 불일치와 같다). 그래서 업데이트 전부터 clip 범위 밖에 있는 토큰이 생긴다. 그리고 clip이 이제 sampler로부터의 전체 거리를 묶는다. stale 데이터에는 이쪽이 바라는 동작이다.

loss_type: reinforce. clipping이 없고 손실은

ℓt(θ)=−At  sg⁡ ⁣[wˉt] log⁡πθ(yt∣ht),wˉt=min⁡ ⁣(πθπrollout,C) (토큰 또는 시퀀스 형태)\ell_t(\theta) = -A_t\;\operatorname{sg}\!\big[\bar w_t\big]\,\log\pi_\theta(y_t\mid h_t),\qquad \bar w_t=\min\!\Big(\frac{\pi_\theta}{\pi_{\text{rollout}}},C\Big)\ \text{(토큰 또는 시퀀스 형태)}

이다. stop-gradient가 중요하다. ∇θπθπrollout=πθπrollout∇θlog⁡πθ\nabla_\theta\frac{\pi_\theta}{\pi_{\text{rollout}}}=\frac{\pi_\theta}{\pi_{\text{rollout}}}\nabla_\theta\log\pi_\theta이므로, ww가 잘리지 않는 한 −A sg⁡[w]log⁡πθ-A\,\operatorname{sg}[w]\log\pi_\theta의 gradient는 IS surrogate −A w-A\,w의 gradient와 같다. ww를 통해 미분하면 엉뚱한 log⁡πθ ∇w\log\pi_\theta\,\nabla w 항이 더해진다. truncation이 있으면 이것은 CISPO식 목적함수(가중치를 자르고 모든 토큰의 gradient는 살림)다. clipping과 IS와 비교해 보자.

두 bypass 변형 모두 IS 가중치와 rejection 통계량을 손실 안에서, micro-batch마다, 현재 πθ\pi_\theta를 기준으로(torch.no_grad 아래) 계산한다. 그래서 bypass 모드의 rejection 규칙은 엔진 불일치 + staleness + 이번 스텝에서 이미 적용된 업데이트를 함께 잰다. sampler 주변의 hard trust region으로 작동하는 셈이고, 이는 Trust Region Masking(Li et al.)의 관점과 정확히 같다. 켜려면 actor_rollout_ref.actor.use_rollout_log_probs: true, actor_rollout_ref.actor.policy_loss.loss_mode: bypass_mode를 설정하고 rollout_correction 블록을 actor_rollout_ref.actor.policy_loss.rollout_correction에도 똑같이 적어야 한다.

가중치: rollout_is와 rollout_is_threshold

δt=log⁡πtrain(yt)−log⁡πrollout(yt)\delta_t=\log\pi_{\text{train}}(y_t)-\log\pi_{\text{rollout}}(y_t)라 하자. πtrain\pi_{\text{train}}은 decoupled에서 πold\pi_{\text{old}}, bypass에서 πθ\pi_\theta다. helper는 먼저 안전 범위 [−20,20][-20,20]으로 clamp한 뒤 다음을 한다.

rollout_is원 가중치 w~t\tilde w_t그 다음 rollout_is_threshold에 따라
null— (지표만)—
tokeneδte^{\delta_t}float CC: TIS wt=min⁡(w~t,C)w_t=\min(\tilde w_t,C)
sequenceexp⁡(clamp⁡(∑sδs,±20))\exp\big(\operatorname{clamp}(\sum_{s}\delta_s,\pm20)\big), 모든 토큰에 broadcast문자열 "lo_hi": IcePop wt=w~t 1[lo≤w~t≤hi]w_t=\tilde w_t\,\mathbb 1[\text{lo}\le\tilde w_t\le\text{hi}]

padding 위치는 0이 되고, rollout_is_batch_normalize: true이면 truncation 뒤에 배치 평균(토큰 단위, 또는 시퀀스당 가중치 하나)으로 나눈다. 두 threshold 형식의 비대칭에 주의하자. TIS에는 아래쪽 자르기가 없다(작은 가중치는 그대로 둔다). IcePop은 양쪽 꼬리를 모두 0으로 만든다. 또 IcePop은 response_mask가 아니라 가중치를 바꾼다. loss_agg_mode: token-mean에서 IcePop으로 0이 된 토큰은 여전히 분모에 들어가지만, rejection 규칙으로 빠진 토큰은 분모에서도 빠진다.

Mask: rollout_rs와 rollout_rs_threshold

rejection 규칙은 토큰별 divergence 통계량 세 개로 만든다(KL penalty에 쓰는 k1/k2/k3 추정량과 같다).

k1=−δt=log⁡πrolloutπtrain,k2=12δt2,k3=eδt−1−δt.k_1=-\delta_t=\log\frac{\pi_{\text{rollout}}}{\pi_{\text{train}}},\qquad k_2=\tfrac12\delta_t^2,\qquad k_3=e^{\delta_t}-1-\delta_t .

토큰이 πrollout\pi_{\text{rollout}}에서 샘플됐으므로 토큰당 E[k1]=E[k3]=KL(πrollout ∥ πtrain)\mathbb E[k_1]=\mathbb E[k_3]=\mathrm{KL}(\pi_{\text{rollout}}\,\|\,\pi_{\text{train}})이다. k3≥0k_3\ge0은 항상 성립하고 k1k_1은 음수가 될 수 있다. 옵션마다 통계량 하나를 모아 threshold와 비교하며, 쉼표로 여러 규칙을 주면 논리곱(AND)으로 적용한다.

옵션통계량(토큰별 또는 응답별)유지 조건
token_k1k1k_1log⁡lo≤k1≤log⁡hi\log\text{lo}\le k_1\le\log\text{hi}
token_k2, token_k3k2k_2 또는 k3k_3≤c\le c
seq_sum_k1∑tk1=log⁡∏tπrolloutπtrain\sum_t k_1=\log\prod_t\frac{\pi_{\text{rollout}}}{\pi_{\text{train}}}[log⁡lo,log⁡hi][\log\text{lo},\log\text{hi}] 안
seq_sum_k2, seq_sum_k3∑tk2,3\sum_t k_{2,3}≤c\le c
seq_mean_k1 (Geo-RS)1T∑tk1\frac1T\sum_t k_1 = 기하평균 ratio의 log[log⁡lo,log⁡hi][\log\text{lo},\log\text{hi}] 안
seq_mean_k2, seq_mean_k3 (K3-RS)1T∑tk2,3\frac1T\sum_t k_{2,3}≤c\le c
seq_max_k2, seq_max_k3max⁡tk2,3\max_t k_{2,3} (최악 토큰)≤c\le c

k1 threshold를 float 하나 uu로 주면 [1/u,u][1/u,u]를 뜻한다. 거부된 시퀀스는 모든 토큰이 response_mask에서 빠진다.

RolloutCorrectionConfig의 preset들은 이 부품들의 조합일 뿐이다. 이름보다 기본값이 중요하다.

preset모드 / 손실rollout_is (threshold)rollout_rs (threshold)
decoupled_token_is()decoupledtoken (2.0)—
decoupled_seq_is()decoupledsequence (2.0)—
decoupled_token_icepop()decoupledtoken ("0.5_5.0")—
decoupled_seq_is_rs() (“Seq-MIS”)decoupledsequence (2.0)seq_sum_k1 ("0.5_2.0")
decoupled_geo_rs()decoupled—seq_mean_k1 ("0.999_1.001")
decoupled_geo_rs_token_tis()decoupledtoken (2.0)seq_mean_k1 ("0.999_1.001")
decoupled_k3_rs()decoupled—seq_mean_k3 (0.01)
bypass_ppo_clip()bypass / ppo_clip——
bypass_ppo_clip_geo_rs()bypass / ppo_clip—seq_mean_k1 ("0.999_1.001")
bypass_pg_is()bypass / reinforcesequence (2.0)—
bypass_pg_geo_rs_token_tis()bypass / reinforcetoken (2.0)seq_mean_k1 ("0.999_1.001")

Geo-RS 기본값을 글자 그대로 읽으면 ∣1T∑tk1∣≤log⁡1.001≈10−3|\frac1T\sum_t k_1|\le\log1.001\approx10^{-3}, 즉 토큰당 KL(πrollout∥πtrain)\mathrm{KL}(\pi_{\text{rollout}}\|\pi_{\text{train}})의 k1 추정치가 약 0.001 nat를 넘는(또는 −0.001 아래인) 응답을 거부한다는 뜻이다. 0.01짜리 K3-RS는 음이 아닌 k3k_3 추정량으로 하는 같은 검사이고, 예산이 열 배 느슨하다. 둘 다 “ratio가 1 근처인가”가 아니라 토큰당 KL 예산이다.

아래 그림은 이 규칙들을 장난감 배치에 적용한다. preset을 바꿔 본 뒤 스파이크 확률과 길이 배율을 올려 보자.

유지 토큰tokens kept – 건드려진 시퀀스sequences touched – mean w – ESS – kl – · k3_kl – · chi2_token –
 
Ten responses of different lengths; each cell is one token, coloured by the multiplier the loss finally applies (blue < 1 < red). Dark cells are rejected by rollout_rs (removed from response_mask); amber cells got weight 0 from an IcePop band but stay in the mask. The right column prints each sequence's rejection statistic. Pick a preset, then raise the spike probability: token rules drop single tokens, seq_* rules drop whole responses, and seq_sum_k1 drops the long ones first. In bypass mode the ratio is πθ/πrollout, so the statistics move with the mini-batch index k. 길이가 다른 응답 10개. 칸 하나가 토큰 하나이고, 색은 손실이 최종적으로 곱하는 배수다(파랑 < 1 < 빨강). 검은 칸은 rollout_rs가 거부한 토큰(response_mask에서 빠짐), 주황 칸은 IcePop 밴드 때문에 가중치가 0이 됐지만 mask에는 남은 토큰이다. 오른쪽 열은 시퀀스별 거부 통계량. preset을 고른 뒤 스파이크 확률을 올려 보면 토큰 규칙은 토큰 하나씩, seq_* 규칙은 응답 전체를 버리고, seq_sum_k1은 긴 응답부터 버린다. bypass 모드에서는 ratio가 πθ/πrollout이라 통계량이 mini-batch 번호 k에 따라 움직인다.

What to notice:

  1. decoupled_token_is() with a 1% spike rate: the spikes become dark-red cells capped at 2, the rest is near-white. Switch to decoupled_seq_is(): whole rows turn one colour, because a single spike multiplies the entire response; long rows are mostly at the cap or near zero.
  2. decoupled_seq_is_rs(): the band [0.5,2][0.5,2] on the product rejects responses with even one spike, and, as the length multiplier grows, rejects long clean responses too — the sum of TT noisy terms has standard deviation σT\sigma\sqrt T.
  3. decoupled_geo_rs() with the default ±0.001\pm0.001: with σ = 0.08 the per-token KL is about σ2/2=0.0032\sigma^2/2=0.0032, above the budget, so almost everything is rejected. Lower σ to 0.03 (KL ≈ 0.00045) and the long responses come back first — the mean over more tokens is less noisy.
  4. Bypass modes: the statistics include the update drift and grow with the mini-batch index kk; under bypass_ppo_clip the mean weight shows “1 (—)” because the IS weight is only logged, not applied.

The length trap, quantitatively

Model the per-token log-ratio as i.i.d. δt∼N(m−σ2/2, σ2)\delta_t\sim\mathcal N(m-\sigma^2/2,\ \sigma^2): pure noise has m=0m=0, which makes E[eδt]=1\mathbb E[e^{\delta_t}]=1 (a single token is unbiased); m≠0m\ne0 is a systematic shift such as staleness. Then the acceptance probability of each rule is available in closed form:

Pseq_sum_k1(T)=Φ ⁣(log⁡2+TδˉσT)−Φ ⁣(−log⁡2+TδˉσT),PGeo(T)=Φ ⁣(u+δˉσ/T)−Φ ⁣(−u+δˉσ/T)P_{\text{seq\_sum\_k1}}(T)=\Phi\!\Big(\tfrac{\log2+T\bar\delta}{\sigma\sqrt T}\Big)-\Phi\!\Big(\tfrac{-\log2+T\bar\delta}{\sigma\sqrt T}\Big),\qquad P_{\text{Geo}}(T)=\Phi\!\Big(\tfrac{u+\bar\delta}{\sigma/\sqrt T}\Big)-\Phi\!\Big(\tfrac{-u+\bar\delta}{\sigma/\sqrt T}\Big)

with δˉ=m−σ2/2\bar\delta=m-\sigma^2/2, and Ptoken_k1(T)=pTP_{\text{token\_k1}}(T)=p^T, Pseq_max_k2(T)=qTP_{\text{seq\_max\_k2}}(T)=q^T for the per-token pass probabilities p,qp,q. For K3-RS the mean of k3k_3 has expectation eδˉ+σ2/2−1−δˉe^{\bar\delta+\sigma^2/2}-1-\bar\delta and, by the CLT, variance Var⁡(k3)/T\operatorname{Var}(k_3)/T, with Var⁡(k3)=Var⁡(eδ)+σ2−2σ2eδˉ+σ2/2\operatorname{Var}(k_3)=\operatorname{Var}(e^\delta)+\sigma^2-2\sigma^2e^{\bar\delta+\sigma^2/2} (Stein’s lemma for the covariance).

The limits tell the whole story. As T→∞T\to\infty: the product rule’s statistic drifts as T∣δˉ∣T|\bar\delta| with spread σT\sigma\sqrt T, so P→0P\to0 — the length trap: long chains of thought are rejected for being long. Every per-token rule (pTp^T, qTq^T) also goes to 0. The two mean rules go to a step function: PGeo→1[ ∣δˉ∣<u ]P_{\text{Geo}}\to\mathbb 1[\,|\bar\delta|<u\,] and PK3→1[ Ek3<c ]P_{\text{K3}}\to\mathbb 1[\,\mathbb E k_3<c\,]. They are length-invariant in expectation but noisier for short responses, so at a fixed threshold they reject short responses more often than long ones.

볼 것:

  1. 스파이크 1%로 decoupled_token_is(): 스파이크가 2에서 잘린 진한 빨간 칸이 되고 나머지는 거의 흰색이다. decoupled_seq_is()로 바꾸면 줄 전체가 한 색이 된다. 스파이크 하나가 응답 전체에 곱해지기 때문이다. 긴 줄은 대부분 상한에 붙거나 0 근처다.
  2. decoupled_seq_is_rs(): 곱에 대한 밴드 [0.5,2][0.5,2]가 스파이크 하나만 있어도 응답을 거부하고, 길이 배율을 키우면 깨끗한 긴 응답까지 거부한다. 잡음 TT개의 합은 표준편차가 σT\sigma\sqrt T다.
  3. 기본값 ±0.001\pm0.001의 decoupled_geo_rs(): σ = 0.08이면 토큰당 KL이 약 σ2/2=0.0032\sigma^2/2=0.0032로 예산을 넘어 거의 전부 거부된다. σ를 0.03(KL ≈ 0.00045)으로 내리면 긴 응답부터 돌아온다. 더 많은 토큰에 대한 평균이 덜 시끄럽기 때문이다.
  4. bypass 모드: 통계량에 업데이트 drift가 들어가 mini-batch 번호 kk와 함께 커진다. bypass_ppo_clip에서는 IS 가중치를 기록만 하고 적용하지 않으므로 mean w가 “1 (—)“로 나온다.

length trap을 정량적으로

토큰별 log-ratio를 i.i.d. δt∼N(m−σ2/2, σ2)\delta_t\sim\mathcal N(m-\sigma^2/2,\ \sigma^2)로 모델링하자. 순수한 잡음은 m=0m=0이고, 이때 E[eδt]=1\mathbb E[e^{\delta_t}]=1(토큰 하나는 불편)이다. m≠0m\ne0은 staleness 같은 체계적 이동이다. 그러면 각 규칙의 통과 확률이 닫힌 형태로 나온다.

Pseq_sum_k1(T)=Φ ⁣(log⁡2+TδˉσT)−Φ ⁣(−log⁡2+TδˉσT),PGeo(T)=Φ ⁣(u+δˉσ/T)−Φ ⁣(−u+δˉσ/T)P_{\text{seq\_sum\_k1}}(T)=\Phi\!\Big(\tfrac{\log2+T\bar\delta}{\sigma\sqrt T}\Big)-\Phi\!\Big(\tfrac{-\log2+T\bar\delta}{\sigma\sqrt T}\Big),\qquad P_{\text{Geo}}(T)=\Phi\!\Big(\tfrac{u+\bar\delta}{\sigma/\sqrt T}\Big)-\Phi\!\Big(\tfrac{-u+\bar\delta}{\sigma/\sqrt T}\Big)

여기서 δˉ=m−σ2/2\bar\delta=m-\sigma^2/2이고, 토큰별 통과 확률 p,qp,q에 대해 Ptoken_k1(T)=pTP_{\text{token\_k1}}(T)=p^T, Pseq_max_k2(T)=qTP_{\text{seq\_max\_k2}}(T)=q^T다. K3-RS에서 k3k_3 평균의 기댓값은 eδˉ+σ2/2−1−δˉe^{\bar\delta+\sigma^2/2}-1-\bar\delta이고 CLT로 분산은 Var⁡(k3)/T\operatorname{Var}(k_3)/T, Var⁡(k3)=Var⁡(eδ)+σ2−2σ2eδˉ+σ2/2\operatorname{Var}(k_3)=\operatorname{Var}(e^\delta)+\sigma^2-2\sigma^2e^{\bar\delta+\sigma^2/2}이다(공분산은 Stein의 보조정리).

극한이 모든 것을 말해 준다. T→∞T\to\infty이면 곱 규칙의 통계량은 T∣δˉ∣T|\bar\delta|로 이동하고 퍼짐은 σT\sigma\sqrt T이므로 P→0P\to0이다. 이것이 length trap이다. 긴 chain of thought가 길다는 이유로 거부된다. 토큰 단위 규칙(pTp^T, qTq^T)도 모두 0으로 간다. 두 평균 규칙은 계단 함수로 간다. PGeo→1[ ∣δˉ∣<u ]P_{\text{Geo}}\to\mathbb 1[\,|\bar\delta|<u\,], PK3→1[ Ek3<c ]P_{\text{K3}}\to\mathbb 1[\,\mathbb E k_3<c\,]. 기댓값에서는 길이에 무관하지만 짧은 응답에서 더 시끄럽다. 그래서 고정된 threshold에서는 짧은 응답을 긴 응답보다 더 자주 거부한다.

토큰당per token KL(πrollout‖πold) = σ²/2 − m = – E[k3] = –
Probability that a response of length T survives each rejection rule (thresholds: seq_sum_k1 and token_k1 at [0.5, 2]; seq_mean_k1 at [e−u, eu]; seq_mean_k3 ≤ c; seq_max_k2 ≤ 2.5). Drag σ up: the product rule (red) and every per-token rule (amber, violet) reject long responses first — the length trap. The length-normalised rules (Geo, K3) do the opposite: their statistic averages over T, so they converge to a hard verdict on the per-token KL, accepting everything if it is under the threshold and nothing if it is over. Drag m to see a systematic shift (e.g. staleness) push Geo-RS over its edge. 길이 T인 응답이 각 거부 규칙을 통과할 확률(임계값: seq_sum_k1·token_k1은 [0.5, 2], seq_mean_k1은 [e−u, eu], seq_mean_k3 ≤ c, seq_max_k2 ≤ 2.5). σ를 올려 보면 곱 규칙(빨강)과 토큰 단위 규칙들(주황, 보라)은 긴 응답부터 거부한다 — length trap. 길이 정규화 규칙(Geo, K3)은 반대다. 통계량이 T에 걸쳐 평균되므로, 토큰당 KL이 임계값보다 작으면 전부 통과, 크면 전부 거부라는 단단한 판정으로 수렴한다. m을 끌면 체계적인 이동(예: staleness)이 Geo-RS를 경계 밖으로 밀어내는 것을 볼 수 있다.

Bias and variance, measured

Which estimator to use is a bias–variance question, and it is easy to measure on a model small enough to have an exact gradient. Below, a 4-token Markov “language model” generates TT tokens; the reward is whether the last token is token 0; the rollout engine’s logits are perturbed by fixed noise (scale 0.3, a per-token KL of about 0.02 — much larger than a healthy engine gap, closer to a few steps of staleness). For each rule we form the RLOO policy gradient from 16 rollouts, repeat 1,500 times, and compare the mean with the exact gradient (computed by forward–backward, no sampling).

NumPy Bias and variance of verl-style corrections on a toy Markov LM
import numpy as np

K = 4                                    # tokens = states of a tiny Markov "language model"
softmax = lambda z: np.exp(z - z.max(-1, keepdims=True)) / np.exp(z - z.max(-1, keepdims=True)).sum(-1, keepdims=True)
theta = np.random.default_rng(0).normal(0, 1.0, (K, K))
pi = softmax(theta)                      # trainer policy  pi_old(a | s)
eps = np.random.default_rng(7).normal(0, 1.0, (K, K))
TARGET = 0                               # reward R = 1[last token == 0]

def exact_grad(T):
    """d/dtheta P_pi(y_T = TARGET), y_0 = 0, by forward-backward (no sampling)."""
    d = np.eye(K)[0]; g = np.zeros((K, K))
    P = [np.eye(K)]
    for _ in range(T): P.append(P[-1] @ pi)
    for t in range(1, T + 1):
        Q = P[T - t][:, TARGET]                                  # P(y_T = TARGET | y_t = a)
        g += d[:, None] * (pi * Q - pi * (pi @ Q)[:, None])     # sum_a pi(a|s)(e_a - pi_s) Q[a]
        d = d @ pi
    return g

def sample(mu, n, T, rng):
    y = np.zeros((n, T + 1), dtype=np.intp); cdf = np.cumsum(mu, 1)
    for t in range(1, T + 1):
        y[:, t] = np.minimum((rng.random(n)[:, None] > cdf[y[:, t - 1]]).sum(1), K - 1)
    return y

def run(scale, T, trials=1500, n=16, seed=1):
    rng = np.random.default_rng(seed)
    mu = softmax(theta + scale * eps)                            # rollout engine: perturbed logits
    gt = exact_grad(T); norm = np.linalg.norm(gt)
    y = sample(mu, trials * n, T, rng); s, a = y[:, :-1], y[:, 1:]
    lr = np.log(pi[s, a]) - np.log(mu[s, a])                     # log rho_t = log pi_old/pi_rollout
    R = (y[:, -1] == TARGET).astype(float).reshape(trials, n)
    A = (R - (R.sum(1, keepdims=True) - R) / (n - 1)).reshape(-1)   # RLOO advantage
    seq, geo = lr.sum(1), -lr.mean(1)                            # seq_sum_k1 / seq_mean_k1 stats
    k3 = (np.exp(lr) - 1 - lr).mean(1)                           # seq_mean_k3 stat
    tis = np.minimum(np.exp(lr), 2.0)
    rules = {
        'no correction':    np.ones_like(lr),
        'token-TIS (C=2)':  tis,
        'seq-IS (exact)':   np.repeat(np.exp(seq)[:, None], T, 1),
        'seq-TIS (C=2)':    np.repeat(np.minimum(np.exp(seq), 2.0)[:, None], T, 1),
        'Geo-RS+token-TIS': tis * (np.abs(geo) <= np.log(1.05))[:, None],
        'K3-RS+token-TIS':  tis * (k3 <= 0.02)[:, None],
    }
    idx = (np.repeat(np.arange(trials), n)[:, None] * K * K + s * K + a).ravel().astype(np.intp)
    print(f"T={T:3d}  per-token KL(rollout||old) ~ {(-lr).mean():.3f}")
    for name, w in rules.items():
        C = np.bincount(idx, weights=(w * A[:, None]).ravel(), minlength=trials * K * K).reshape(trials, K, K) / n
        g = C - C.sum(2, keepdims=True) * pi[None]               # sum_t w_t A (e_{y_t} - pi(.|s_t))
        m = g.mean(0)
        bias = np.linalg.norm(m - gt) / norm
        std = np.sqrt(((g - m) ** 2).sum((1, 2)).mean()) / norm
        kept = (w[:, 0] > 0).mean()
        print(f"   {name:17s} bias {bias:5.2f}  std/batch {std:7.2f}  kept {kept:4.0%}")

for T in [4, 16, 64]:
    run(0.3, T)
 

Bias and std are relative to the norm of the true gradient. How to read it:

  • No correction vs token-TIS. Token-level weights fix the per-token conditional mismatch and roughly halve the bias, but they cannot fix the different state distribution the rollout engine visits, so a residual bias remains and grows slowly with TT.
  • Exact sequence IS is unbiased in theory; at T=4T=4 its measured bias is at the Monte-Carlo floor. At T=64T=64 the per-batch std is about 18× the gradient, and the “bias” it prints (≈0.5) is itself noise: the standard error of a 1,500-batch mean is 18.5/1500≈0.4818.5/\sqrt{1500}\approx0.48. That is the ESS collapse from the mismatch lesson in a form you can see.
  • Sequence TIS keeps the variance bounded, but the truncated mass grows with TT, so its bias grows from 0.04 to about 0.5: most long-sequence weights are either capped or tiny.
  • The rejection rules trade bias for variance in a different way: they drop whole samples whose statistic is out of budget, which is not random with respect to the gradient (bias), and fewer samples with extreme weights means lower variance. Note the Geo-RS “kept” column rising with TT (43% → 89%) — the noisy-short-response effect from the figure.
  • All stds grow with TT for a reason unrelated to IS: one terminal reward is broadcast to TT score terms (the credit-assignment variance of agent RL).

Now the threshold semantics. This reproduces the core of compute_rollout_rejection_mask for token_k1 and checks the asymmetric-band behaviour from the callout:

NumPy verl's k1 band bounds π_rollout/π_train
import numpy as np

def token_k1_keep(log_ratio, spec):
    """log_ratio = log pi_train - log pi_rollout; spec = 'lo_hi' as in rollout_rs_threshold."""
    lo, hi = map(float, spec.split('_'))
    k1 = -np.clip(log_ratio, -20, 20)                 # = log(pi_rollout / pi_train)
    return (k1 >= np.log(lo)) & (k1 <= np.log(hi))

ratios = np.array([0.4, 0.6, 0.9, 1.0, 1.8, 2.2])     # pi_train / pi_rollout (the IS weight)
for spec in ['0.5_2.0', '0.5_1.5']:
    keep = token_k1_keep(np.log(ratios), spec)
    print(spec, {float(r): bool(k) for r, k in zip(ratios, keep)})
print("symmetric band: keeps IS weights in [0.5, 2];  '0.5_1.5' keeps IS weights in [1/1.5, 2] = [0.667, 2]")
 

For local use, here is the same logic in PyTorch, written to match the helper’s semantics (log-space, safety clamp, IcePop as a string threshold, AND over rules omitted for brevity), together with the two loss forms:

PyTorch PyTorch: verl-style weights, masks and the two losses 로컬에서 실행run locally (pip install torch)
import math
import torch

def rollout_correction(train_lp, rollout_lp, mask, rollout_is="token", is_threshold=2.0,
                       rollout_rs=None, rs_threshold=None):
    """train_lp, rollout_lp, mask: (B, T). Returns (weights or None, new_mask)."""
    log_ratio = (train_lp - rollout_lp).clamp(-20.0, 20.0)       # log pi_train / pi_rollout
    mask = mask.to(log_ratio.dtype)
    w = None
    if rollout_is is not None:
        if rollout_is == "token":
            raw = log_ratio.exp()
        else:                                                      # "sequence": product, broadcast
            raw = (log_ratio * mask).sum(-1, keepdim=True).clamp(-20.0, 20.0).exp().expand_as(log_ratio)
        if isinstance(is_threshold, str):                          # "lo_hi" -> IcePop band
            lo, hi = map(float, is_threshold.split("_"))
            w = torch.where((raw >= lo) & (raw <= hi), raw, torch.zeros_like(raw))
        else:                                                      # float -> TIS
            w = raw.clamp(max=float(is_threshold))
        w = (w * mask).detach()
    keep = torch.ones_like(mask)
    if rollout_rs is not None:
        stat = {"k1": -log_ratio, "k2": 0.5 * log_ratio**2, "k3": log_ratio.exp() - 1.0 - log_ratio}[rollout_rs[-2:]]
        if rollout_rs.startswith("token"):
            s = stat
        elif rollout_rs.startswith("seq_sum"):
            s = (stat * mask).sum(-1, keepdim=True)
        elif rollout_rs.startswith("seq_mean"):
            s = (stat * mask).sum(-1, keepdim=True) / mask.sum(-1, keepdim=True).clamp(min=1.0)
        else:                                                      # seq_max_k2 / seq_max_k3
            s = stat.masked_fill(mask == 0, float("-inf")).amax(-1, keepdim=True)
        if rollout_rs.endswith("k1"):
            lo, hi = map(float, str(rs_threshold).split("_"))
            ok = (s >= math.log(lo)) & (s <= math.log(hi))
        else:
            ok = s <= float(rs_threshold)
        keep = ok.expand_as(mask).to(mask.dtype)
    return w, mask * keep

def decoupled_ppo_loss(logp, old_lp, adv, w, mask, eps_low=0.2, eps_high=0.2):
    ratio = (logp - old_lp).clamp(-20.0, 20.0).exp()             # pi_theta / pi_old
    pg = torch.maximum(-adv * ratio, -adv * ratio.clamp(1 - eps_low, 1 + eps_high))
    if w is not None:
        pg = pg * w                                                # constant: pi_old / pi_rollout
    return (pg * mask).sum() / mask.sum().clamp(min=1.0)           # token-mean

def bypass_reinforce_loss(logp, rollout_lp, adv, mask, C=2.0):
    w = (logp - rollout_lp).clamp(-20.0, 20.0).exp().clamp(max=C).detach()   # sg[min(pi_theta/pi_rollout, C)]
    return (-adv * w * logp * mask).sum() / mask.sum().clamp(min=1.0)
 

Score centering, the newest option

score_centering: true (bypass + reinforce only, rollout_is null or token, needs rollout.topk_log_probs, vLLM only) implements Marek & Ryabinin (2026). Their argument: when the sampler qq differs from the trainer pp, the per-token score has non-zero mean under the sampler, Ey∼q[∇log⁡p(y∣h)]=∑vq(v∣h)∇log⁡p(v∣h)≠0\mathbb E_{y\sim q}[\nabla\log p(y\mid h)]=\sum_v q(v\mid h)\nabla\log p(v\mid h)\neq0, and the estimator picks up a drift term proportional to it that accumulates step after step. The fix is additive: replace the score of the sampled token by ∇log⁡p(yt)−∑vq(v)∇log⁡p(v)\nabla\log p(y_t)-\sum_v q(v)\nabla\log p(v), with the sum approximated over the sampler’s recorded top-kk head (k=128k=128 in the paper) plus a modelled tail. It is a no-op when q=pq=p and composes with token TIS/IcePop. verl currently restricts it to single-turn agent loops. The derivation (why group centering leaves drift, what clipped IS leaves, how the top-kk tail is modelled) and the paper’s measurements are in score centering.

확인 문제Check yourself

You run verl in bypass mode with loss_type=ppo_clip and rollout_is=token. Which statement is true?

In bypass mode πold:=πrollout\pi_{\text{old}}:=\pi_{\text{rollout}}, so the PPO ratio rt=πθ/πrolloutr_t=\pi_\theta/\pi_{\text{rollout}} already carries the importance correction. compute_policy_loss_bypass_mode calls the vanilla PPO loss with rollout_is_weights=None and only merges the IS metrics; a rejection rule, if configured, still edits the mask. Explicit weights are applied only with loss_type: reinforce.

확인 문제Check yourself

Your measured per-token KL(π_rollout‖π_old) is about 0.003 nats with no systematic trend. What will decoupled_geo_rs() with its default threshold do to long responses?

seq_mean_k1 with "0.999_1.001" keeps a response only if ∣1T∑tk1∣≤log⁡1.001≈0.001|\frac1T\sum_t k_1|\le\log1.001\approx0.001. Its expectation is the per-token KL (0.003), and its standard deviation shrinks like 1/T1/\sqrt T, so long responses are rejected with probability → 1. Short responses survive more often, purely through noise. Either loosen the band to your measured budget or remove the cause of the gap.

Summary

  • verl separates drift 1 (πold/πrollout\pi_{\text{old}}/\pi_{\text{rollout}}: engine + staleness) from drift 2 (πθ/πold\pi_\theta/\pi_{\text{old}}: updates). Decoupled mode corrects the first with a constant weight wtw_t on the clipped loss; bypass mode sets πold:=πrollout\pi_{\text{old}}:=\pi_{\text{rollout}} and lets one ratio do both jobs (ppo_clip) or uses sg⁡[w]log⁡πθ\operatorname{sg}[w]\log\pi_\theta (reinforce).
  • rollout_is builds token or sequence weights; a float threshold is TIS (upper clamp), a "lo_hi" string is IcePop (zero outside the band, mask untouched).
  • rollout_rs builds masks from k1,k2,k3k_1,k_2,k_3 aggregated per token, sum, mean or max; Geo-RS (seq_mean_k1) and K3-RS (seq_mean_k3) are per-token KL budgets of about 0.001 and 0.01 nats by default. The k1 band bounds πrollout/πtrain\pi_{\text{rollout}}/\pi_{\text{train}}.
  • Product rules and per-token rules reject long responses (the length trap); mean rules converge to an all-or-nothing verdict on the per-token KL and are noisier for short responses.
  • In bypass mode the statistics are computed per micro-batch against the current πθ\pi_\theta, so a rejection rule is a hard trust region around the sampler.

bias와 variance를 재 보기

어떤 추정량을 쓸지는 bias–variance 문제이고, 정확한 gradient를 계산할 수 있을 만큼 작은 모델에서는 쉽게 잴 수 있다. 아래에서는 토큰 4개짜리 Markov “언어 모델”이 TT개 토큰을 생성하고, 보상은 마지막 토큰이 0번인지 여부다. rollout 엔진의 logit에는 고정된 잡음(scale 0.3, 토큰당 KL 약 0.02 — 건강한 엔진 차이보다 훨씬 크고, 몇 스텝의 staleness에 가깝다)을 더했다. 규칙마다 rollout 16개로 RLOO policy gradient를 만들고 1,500번 반복해, 평균을 정확한 gradient(forward–backward로 계산, 샘플링 없음)와 비교한다.

NumPy toy Markov LM에서 verl식 보정의 bias와 variance
import numpy as np

K = 4                                    # tokens = states of a tiny Markov "language model"
softmax = lambda z: np.exp(z - z.max(-1, keepdims=True)) / np.exp(z - z.max(-1, keepdims=True)).sum(-1, keepdims=True)
theta = np.random.default_rng(0).normal(0, 1.0, (K, K))
pi = softmax(theta)                      # trainer policy  pi_old(a | s)
eps = np.random.default_rng(7).normal(0, 1.0, (K, K))
TARGET = 0                               # reward R = 1[last token == 0]

def exact_grad(T):
    """d/dtheta P_pi(y_T = TARGET), y_0 = 0, by forward-backward (no sampling)."""
    d = np.eye(K)[0]; g = np.zeros((K, K))
    P = [np.eye(K)]
    for _ in range(T): P.append(P[-1] @ pi)
    for t in range(1, T + 1):
        Q = P[T - t][:, TARGET]                                  # P(y_T = TARGET | y_t = a)
        g += d[:, None] * (pi * Q - pi * (pi @ Q)[:, None])     # sum_a pi(a|s)(e_a - pi_s) Q[a]
        d = d @ pi
    return g

def sample(mu, n, T, rng):
    y = np.zeros((n, T + 1), dtype=np.intp); cdf = np.cumsum(mu, 1)
    for t in range(1, T + 1):
        y[:, t] = np.minimum((rng.random(n)[:, None] > cdf[y[:, t - 1]]).sum(1), K - 1)
    return y

def run(scale, T, trials=1500, n=16, seed=1):
    rng = np.random.default_rng(seed)
    mu = softmax(theta + scale * eps)                            # rollout engine: perturbed logits
    gt = exact_grad(T); norm = np.linalg.norm(gt)
    y = sample(mu, trials * n, T, rng); s, a = y[:, :-1], y[:, 1:]
    lr = np.log(pi[s, a]) - np.log(mu[s, a])                     # log rho_t = log pi_old/pi_rollout
    R = (y[:, -1] == TARGET).astype(float).reshape(trials, n)
    A = (R - (R.sum(1, keepdims=True) - R) / (n - 1)).reshape(-1)   # RLOO advantage
    seq, geo = lr.sum(1), -lr.mean(1)                            # seq_sum_k1 / seq_mean_k1 stats
    k3 = (np.exp(lr) - 1 - lr).mean(1)                           # seq_mean_k3 stat
    tis = np.minimum(np.exp(lr), 2.0)
    rules = {
        'no correction':    np.ones_like(lr),
        'token-TIS (C=2)':  tis,
        'seq-IS (exact)':   np.repeat(np.exp(seq)[:, None], T, 1),
        'seq-TIS (C=2)':    np.repeat(np.minimum(np.exp(seq), 2.0)[:, None], T, 1),
        'Geo-RS+token-TIS': tis * (np.abs(geo) <= np.log(1.05))[:, None],
        'K3-RS+token-TIS':  tis * (k3 <= 0.02)[:, None],
    }
    idx = (np.repeat(np.arange(trials), n)[:, None] * K * K + s * K + a).ravel().astype(np.intp)
    print(f"T={T:3d}  per-token KL(rollout||old) ~ {(-lr).mean():.3f}")
    for name, w in rules.items():
        C = np.bincount(idx, weights=(w * A[:, None]).ravel(), minlength=trials * K * K).reshape(trials, K, K) / n
        g = C - C.sum(2, keepdims=True) * pi[None]               # sum_t w_t A (e_{y_t} - pi(.|s_t))
        m = g.mean(0)
        bias = np.linalg.norm(m - gt) / norm
        std = np.sqrt(((g - m) ** 2).sum((1, 2)).mean()) / norm
        kept = (w[:, 0] > 0).mean()
        print(f"   {name:17s} bias {bias:5.2f}  std/batch {std:7.2f}  kept {kept:4.0%}")

for T in [4, 16, 64]:
    run(0.3, T)
 

bias와 std는 참 gradient의 norm 대비 값이다. 읽는 법:

  • 보정 없음 vs token-TIS. 토큰 가중치는 토큰별 조건부 불일치를 고쳐 bias를 대략 절반으로 줄인다. 하지만 rollout 엔진이 방문하는 상태 분포의 차이는 고치지 못하므로 잔여 bias가 남고 TT와 함께 천천히 커진다.
  • 정확한 시퀀스 IS는 이론상 불편이다. T=4T=4에서는 측정된 bias가 Monte-Carlo 바닥 수준이다. T=64T=64에서는 배치당 std가 gradient의 약 18배이고, 출력된 “bias”(≈0.5) 자체가 잡음이다. 1,500 배치 평균의 표준오차가 18.5/1500≈0.4818.5/\sqrt{1500}\approx0.48이다. 불일치 레슨의 ESS 붕괴를 눈으로 보는 셈이다.
  • 시퀀스 TIS는 variance를 묶어 두지만 잘려 나가는 질량이 TT와 함께 커져 bias가 0.04에서 약 0.5로 커진다. 긴 시퀀스의 가중치는 대부분 상한에 붙거나 아주 작다.
  • rejection 규칙은 다른 방식으로 bias와 variance를 맞바꾼다. 통계량이 예산을 넘는 샘플을 통째로 버리는데, 이는 gradient에 대해 무작위가 아니므로 bias가 생기고, 극단적 가중치를 가진 샘플이 줄어 variance는 낮아진다. Geo-RS의 “kept”가 TT와 함께 올라가는 것(43% → 89%)에 주목하자. 그림에서 본 “짧은 응답이 더 시끄럽다” 효과다.
  • 모든 std가 TT와 함께 커지는 데는 IS와 무관한 이유도 있다. 마지막 보상 하나가 score 항 TT개에 broadcast되기 때문이다(agent RL의 credit assignment variance).

이제 threshold의 의미. 아래는 compute_rollout_rejection_mask의 token_k1 핵심을 재현해 callout의 비대칭 밴드 동작을 확인한다.

NumPy verl의 k1 밴드는 π_rollout/π_train을 묶는다
import numpy as np

def token_k1_keep(log_ratio, spec):
    """log_ratio = log pi_train - log pi_rollout; spec = 'lo_hi' as in rollout_rs_threshold."""
    lo, hi = map(float, spec.split('_'))
    k1 = -np.clip(log_ratio, -20, 20)                 # = log(pi_rollout / pi_train)
    return (k1 >= np.log(lo)) & (k1 <= np.log(hi))

ratios = np.array([0.4, 0.6, 0.9, 1.0, 1.8, 2.2])     # pi_train / pi_rollout (the IS weight)
for spec in ['0.5_2.0', '0.5_1.5']:
    keep = token_k1_keep(np.log(ratios), spec)
    print(spec, {float(r): bool(k) for r, k in zip(ratios, keep)})
print("symmetric band: keeps IS weights in [0.5, 2];  '0.5_1.5' keeps IS weights in [1/1.5, 2] = [0.667, 2]")
 

로컬에서 쓸 수 있도록 같은 로직을 PyTorch로 옮겼다. helper의 의미(log 공간, 안전 clamp, 문자열 threshold로 IcePop, 여러 규칙의 AND는 생략)에 맞췄고, 두 손실 형태도 함께 적었다.

PyTorch PyTorch: verl식 가중치·mask와 두 손실 로컬에서 실행run locally (pip install torch)
import math
import torch

def rollout_correction(train_lp, rollout_lp, mask, rollout_is="token", is_threshold=2.0,
                       rollout_rs=None, rs_threshold=None):
    """train_lp, rollout_lp, mask: (B, T). Returns (weights or None, new_mask)."""
    log_ratio = (train_lp - rollout_lp).clamp(-20.0, 20.0)       # log pi_train / pi_rollout
    mask = mask.to(log_ratio.dtype)
    w = None
    if rollout_is is not None:
        if rollout_is == "token":
            raw = log_ratio.exp()
        else:                                                      # "sequence": product, broadcast
            raw = (log_ratio * mask).sum(-1, keepdim=True).clamp(-20.0, 20.0).exp().expand_as(log_ratio)
        if isinstance(is_threshold, str):                          # "lo_hi" -> IcePop band
            lo, hi = map(float, is_threshold.split("_"))
            w = torch.where((raw >= lo) & (raw <= hi), raw, torch.zeros_like(raw))
        else:                                                      # float -> TIS
            w = raw.clamp(max=float(is_threshold))
        w = (w * mask).detach()
    keep = torch.ones_like(mask)
    if rollout_rs is not None:
        stat = {"k1": -log_ratio, "k2": 0.5 * log_ratio**2, "k3": log_ratio.exp() - 1.0 - log_ratio}[rollout_rs[-2:]]
        if rollout_rs.startswith("token"):
            s = stat
        elif rollout_rs.startswith("seq_sum"):
            s = (stat * mask).sum(-1, keepdim=True)
        elif rollout_rs.startswith("seq_mean"):
            s = (stat * mask).sum(-1, keepdim=True) / mask.sum(-1, keepdim=True).clamp(min=1.0)
        else:                                                      # seq_max_k2 / seq_max_k3
            s = stat.masked_fill(mask == 0, float("-inf")).amax(-1, keepdim=True)
        if rollout_rs.endswith("k1"):
            lo, hi = map(float, str(rs_threshold).split("_"))
            ok = (s >= math.log(lo)) & (s <= math.log(hi))
        else:
            ok = s <= float(rs_threshold)
        keep = ok.expand_as(mask).to(mask.dtype)
    return w, mask * keep

def decoupled_ppo_loss(logp, old_lp, adv, w, mask, eps_low=0.2, eps_high=0.2):
    ratio = (logp - old_lp).clamp(-20.0, 20.0).exp()             # pi_theta / pi_old
    pg = torch.maximum(-adv * ratio, -adv * ratio.clamp(1 - eps_low, 1 + eps_high))
    if w is not None:
        pg = pg * w                                                # constant: pi_old / pi_rollout
    return (pg * mask).sum() / mask.sum().clamp(min=1.0)           # token-mean

def bypass_reinforce_loss(logp, rollout_lp, adv, mask, C=2.0):
    w = (logp - rollout_lp).clamp(-20.0, 20.0).exp().clamp(max=C).detach()   # sg[min(pi_theta/pi_rollout, C)]
    return (-adv * w * logp * mask).sum() / mask.sum().clamp(min=1.0)
 

가장 새로운 옵션, score centering

score_centering: true(bypass + reinforce 전용, rollout_is는 null 또는 token, rollout.topk_log_probs 필요, vLLM 전용)는 Marek & Ryabinin(2026)을 구현한다. 그들의 논지는 이렇다. sampler qq가 학습기 pp와 다르면 토큰별 score가 sampler 아래에서 평균이 0이 아니다. Ey∼q[∇log⁡p(y∣h)]=∑vq(v∣h)∇log⁡p(v∣h)≠0\mathbb E_{y\sim q}[\nabla\log p(y\mid h)]=\sum_v q(v\mid h)\nabla\log p(v\mid h)\neq0이고, 추정량에 이것에 비례하는 drift 항이 생겨 스텝마다 쌓인다. 해법은 가산적이다. 샘플된 토큰의 score를 ∇log⁡p(yt)−∑vq(v)∇log⁡p(v)\nabla\log p(y_t)-\sum_v q(v)\nabla\log p(v)로 바꾸고, 합은 sampler가 기록한 top-kk head(논문은 k=128k=128)와 모델링한 꼬리로 근사한다. q=pq=p이면 아무 일도 하지 않고, token TIS/IcePop과 함께 쓸 수 있다. 현재 verl은 single-turn agent loop에서만 허용한다. 유도(group centering이 왜 drift를 남기는지, clip한 IS가 무엇을 남기는지, top-kk 꼬리를 어떻게 모델링하는지)와 논문의 측정 결과는 score centering에 있다.

확인 문제Check yourself

verl을 bypass 모드, loss_type=ppo_clip, rollout_is=token으로 돌린다. 맞는 설명은?

bypass 모드에서는 πold:=πrollout\pi_{\text{old}}:=\pi_{\text{rollout}}이므로 PPO ratio rt=πθ/πrolloutr_t=\pi_\theta/\pi_{\text{rollout}}이 이미 importance 보정을 담고 있다. compute_policy_loss_bypass_mode는 rollout_is_weights=None으로 vanilla PPO 손실을 부르고 IS 지표만 합친다. rejection 규칙을 설정했다면 그것은 여전히 mask를 바꾼다. 명시적 가중치는 loss_type: reinforce에서만 적용된다.

확인 문제Check yourself

측정한 토큰당 KL(π_rollout‖π_old)이 약 0.003 nat이고 체계적 추세는 없다. 기본 threshold의 decoupled_geo_rs()는 긴 응답을 어떻게 하나?

"0.999_1.001"의 seq_mean_k1은 ∣1T∑tk1∣≤log⁡1.001≈0.001|\frac1T\sum_t k_1|\le\log1.001\approx0.001일 때만 응답을 남긴다. 그 기댓값은 토큰당 KL(0.003)이고 표준편차는 1/T1/\sqrt T로 줄어드므로, 긴 응답은 확률 → 1로 거부된다. 짧은 응답은 순전히 잡음 덕에 더 자주 살아남는다. 밴드를 측정한 예산에 맞춰 넓히거나 차이의 원인을 없애야 한다.

정리

  • verl은 drift 1(πold/πrollout\pi_{\text{old}}/\pi_{\text{rollout}}: 엔진 + staleness)과 drift 2(πθ/πold\pi_\theta/\pi_{\text{old}}: 업데이트)를 나눈다. decoupled 모드는 clipped 손실에 상수 가중치 wtw_t를 곱해 앞의 것을 보정하고, bypass 모드는 πold:=πrollout\pi_{\text{old}}:=\pi_{\text{rollout}}으로 두어 ratio 하나가 두 일을 다 하게 하거나(ppo_clip) sg⁡[w]log⁡πθ\operatorname{sg}[w]\log\pi_\theta를 쓴다(reinforce).
  • rollout_is는 토큰 또는 시퀀스 가중치를 만든다. float threshold는 TIS(위쪽 clamp), "lo_hi" 문자열은 IcePop(밴드 밖은 0, mask는 그대로)이다.
  • rollout_rs는 k1,k2,k3k_1,k_2,k_3를 토큰·합·평균·최댓값으로 모아 mask를 만든다. Geo-RS(seq_mean_k1)와 K3-RS(seq_mean_k3)는 기본값이 각각 약 0.001, 0.01 nat인 토큰당 KL 예산이다. k1 밴드는 πrollout/πtrain\pi_{\text{rollout}}/\pi_{\text{train}}을 묶는다.
  • 곱 규칙과 토큰 단위 규칙은 긴 응답을 거부한다(length trap). 평균 규칙은 토큰당 KL에 대한 전부-아니면-전무 판정으로 수렴하고 짧은 응답에서 더 시끄럽다.
  • bypass 모드에서는 통계량을 micro-batch마다 현재 πθ\pi_\theta 기준으로 계산하므로, rejection 규칙이 sampler 주변의 hard trust region이 된다.

더 읽을거리Further reading