Track X · Agent RL Frameworks · 02/07

학습 step 해부 — rollout, mini-batch, micro-batchAnatomy of a training step — rollout, mini-batch, micro-batch

train_batch_size, rollout.n, ppo_mini_batch_size, ppo_epochs, micro-batch 크기, use_dynamic_bsz와 ppo_max_token_len_per_gpu가 어떻게 맞물려 rollout 하나를 optimizer step 여러 개와 forward/backward 여러 번으로 바꾸는지 유도한다. rollout당 갱신 횟수가 만드는 정책 지연, 기울기 누적에서 token-mean을 정확히 지키는 정규화, 고정 micro-batch와 토큰 예산 동적 배치의 차이를 그림과 NumPy로 확인한다.Derives how train_batch_size, rollout.n, ppo_mini_batch_size, ppo_epochs, the micro-batch size, use_dynamic_bsz and ppo_max_token_len_per_gpu fit together to turn one rollout into several optimizer steps and many forward/backward passes. Checks, with figures and NumPy, the policy lag created by several updates per rollout, the normalisation that keeps token-mean exact under gradient accumulation, and fixed micro-batches versus token-budget dynamic batching.

40 분min batch size · mini-batch · micro-batch · gradient accumulation · dynamic batching · sequence packing · verl · PPO epochs 먼저 볼 것:Before this: Trust region에서 PPO까지From trust regions to PPO, RLVR과 추론 — GRPO, RLOO, Dr. GRPO, DAPO, GSPORLVR and reasoning — GRPO, RLOO, Dr. GRPO, DAPO, GSPO, Agent RL 프레임워크 지형도The landscape of agent RL frameworks

Every RL framework turns one rollout into parameter updates through the same three nested loops, but each names the knobs differently, and the defaults change between versions. This lesson pins the hierarchy down with formulas, using the names of current verl (main at commit 4525109, 2026-12-02, version 0.10.0.dev; latest release v0.9.1) as the running example. The equivalents in other frameworks are in a table at the end. If you have ever wondered “how many optimizer steps does one step in my wandb chart contain?” or “why did raising ppo_max_token_len_per_gpu speed things up without changing the loss?”, this lesson answers both.

Five numbers define a step

symbolverl nameunitscope
BBdata.train_batch_sizepromptsglobal
nnactor_rollout_ref.rollout.nsamples per prompt (the GRPO group)global
bbactor_rollout_ref.actor.ppo_mini_batch_sizepromptsglobal
EEactor_rollout_ref.actor.ppo_epochspasses over the rolloutglobal
μ\mu or TTppo_micro_batch_size_per_gpu, or ppo_max_token_len_per_gpu with use_dynamic_bsz=Truesequences, or tokensper GPU

The data-parallel size DD of the actor completes the set. With Megatron it is D=NGPU/(TP⋅PP⋅CP)D = N_\text{GPU}/(\text{TP}\cdot\text{PP}\cdot\text{CP}); with FSDP it is the number of FSDP ranks divided by the Ulysses sequence-parallel size.

Two details that surprise people. First, ppo_mini_batch_size counts prompts: the trainer multiplies it by rollout.n before handing it to the workers (_update_actor in verl/trainer/ppo/v1/trainer_base.py), and the worker then divides it by the data-parallel size (train_mini_batch in verl/workers/engine_workers.py asserts mini_batch_size % dp_size == 0). Second, the docs state the rule behind the scopes: algorithmic sizes (train batch, PPO mini-batch) are global, from the single controller’s point of view, while performance sizes (micro-batch, token budget) are local to one GPU. Changing DD therefore never changes the algorithm; changing μ\mu or TT never changes the gradient (up to floating-point summation order).

From these definitions:

B n⏟trajectories per step,K=E⋅Bb⏟optimizer steps per rollout,b nD⏟trajectories per GPU per update,M=b nD μ⏟accumulated passes per update\underbrace{B\,n}_{\text{trajectories per step}}, \qquad \underbrace{K = E\cdot\frac{B}{b}}_{\text{optimizer steps per rollout}}, \qquad \underbrace{\frac{b\,n}{D}}_{\text{trajectories per GPU per update}}, \qquad \underbrace{M = \frac{b\,n}{D\,\mu}}_{\text{accumulated passes per update}}

A verl global step (the x-axis of the logged metrics and the unit of trainer.total_training_steps) is one rollout batch of BB prompts, so one point on the chart hides KK optimizer steps and K⋅MK\cdot M backward passes per GPU.

모든 RL 프레임워크는 같은 세 겹의 루프로 rollout 하나를 매개변수 갱신으로 바꾼다. 다만 손잡이 이름이 프레임워크마다 다르고, 기본값은 버전마다 바뀐다. 이 레슨은 그 계층을 식으로 고정한다. 예시는 현재 verl(main, 커밋 4525109, 2026-12-02, 버전 0.10.0.dev, 최신 릴리스 v0.9.1)의 이름을 쓰고, 다른 프레임워크의 대응 이름은 끝의 표에 모았다. “wandb 그래프의 step 하나에 optimizer step이 몇 번 들어 있나?”, “ppo_max_token_len_per_gpu를 키웠더니 손실은 그대로인데 왜 빨라졌나?” 같은 질문에 대한 답이 여기 있다.

step을 정하는 다섯 개의 수

기호verl 이름단위범위
BBdata.train_batch_size프롬프트전역
nnactor_rollout_ref.rollout.n프롬프트당 샘플 수(GRPO 그룹)전역
bbactor_rollout_ref.actor.ppo_mini_batch_size프롬프트전역
EEactor_rollout_ref.actor.ppo_epochsrollout을 도는 횟수전역
μ\mu 또는 TTppo_micro_batch_size_per_gpu, 또는 use_dynamic_bsz=True일 때 ppo_max_token_len_per_gpu시퀀스 수 또는 토큰 수GPU당

여기에 actor의 data-parallel 크기 DD가 더해진다. Megatron이면 D=NGPU/(TP⋅PP⋅CP)D = N_\text{GPU}/(\text{TP}\cdot\text{PP}\cdot\text{CP}), FSDP면 FSDP rank 수를 Ulysses sequence-parallel 크기로 나눈 값이다.

자주 헷갈리는 점이 둘 있다. 첫째, ppo_mini_batch_size는 프롬프트 수다. trainer가 worker에 넘기기 전에 rollout.n을 곱하고(verl/trainer/ppo/v1/trainer_base.py의 _update_actor), worker가 다시 data-parallel 크기로 나눈다(verl/workers/engine_workers.py의 train_mini_batch는 mini_batch_size % dp_size == 0을 assert한다). 둘째, 문서가 범위의 원칙을 밝혀 두었다. 알고리즘 크기(train batch, PPO mini-batch)는 single controller 관점의 전역 값이고, 성능 크기(micro-batch, 토큰 예산)는 GPU 하나에 대한 지역 값이다. 그래서 DD를 바꿔도 알고리즘은 바뀌지 않고, μ\mu나 TT를 바꿔도 기울기는 바뀌지 않는다(부동소수점 합산 순서 차이 정도만 생긴다).

정의에서 바로 나오는 양들:

B n⏟step당 trajectory,K=E⋅Bb⏟rollout당 optimizer step,b nD⏟갱신당 GPU당 trajectory,M=b nD μ⏟갱신당 누적 pass 수\underbrace{B\,n}_{\text{step당 trajectory}}, \qquad \underbrace{K = E\cdot\frac{B}{b}}_{\text{rollout당 optimizer step}}, \qquad \underbrace{\frac{b\,n}{D}}_{\text{갱신당 GPU당 trajectory}}, \qquad \underbrace{M = \frac{b\,n}{D\,\mu}}_{\text{갱신당 누적 pass 수}}

verl의 global step(로그 그래프의 가로축이자 trainer.total_training_steps의 단위)은 프롬프트 BB개짜리 rollout 하나다. 그래프의 점 하나에 optimizer step KK번과 GPU당 backward K⋅MK\cdot M번이 들어 있다.

Top: the rollout of one global step, B prompts × n samples, cut into mini-batches of b·n trajectories (colours). Middle: every mini-batch is one optimizer step; with E epochs the cuts repeat. The staircase is the policy lag — how many updates the parameters have moved since the data were sampled. Bottom: click a step to see how its b·n trajectories spread over D data-parallel GPUs and, on each GPU, into micro-batches of μ (forward/backward passes whose gradients are accumulated before the one optimizer step). Shrink b and you get more updates per rollout but a longer staircase; raise D and each GPU holds fewer trajectories, so fewer micro-batches. 위: global step 하나의 rollout, 즉 프롬프트 B개 × 샘플 n개를 b·n개 trajectory씩 mini-batch(색)로 자른다. 가운데: mini-batch 하나가 optimizer step 하나이고, epoch E가 2 이상이면 같은 자르기가 반복된다. 계단은 정책 지연(policy lag), 즉 데이터를 샘플한 뒤 매개변수가 몇 번 갱신됐는지다. 아래: step을 클릭하면 그 step의 b·n개 trajectory가 data-parallel GPU D개로 나뉘고, 각 GPU 안에서 μ개씩 micro-batch(기울기를 누적하는 forward/backward 한 번)로 쪼개지는 모습이 보인다. b를 줄이면 rollout당 갱신 횟수가 늘지만 계단이 길어지고, D를 키우면 GPU당 trajectory가 줄어 micro-batch 수가 준다.

Try the configurations from verl’s own material. The Qwen3-235B-A22B GRPO launcher in examples/grpo_trainer/ sets TRAIN_BATCH_SIZE=128 and PPO_MINI_BATCH_SIZE=128 with n=16: K=1K=1, one update per rollout. The V1 async-trainer benchmark in docs/advance/v1_async_trainer.md uses train_batch_size=64, ppo_mini_batch_size=16: K=4K=4. Both are common; the next section is about what separates them.

Several updates per rollout means stale data inside a step

The rollout is sampled once, by the parameters θ0\theta_0 at the start of the step. Before the update loop verl computes old_log_prob once for the whole batch (step 4 of _step_once), so every mini-batch uses the same πold=πθ0\pi_\text{old}=\pi_{\theta_0} in the ratio. Mini-batch jj is trained at θj\theta_j, after jj optimizer steps:

ρt(j)=πθj(yt∣x,y<t)πθ0(yt∣x,y<t),j=0,1,…,K−1.\rho_t^{(j)} = \frac{\pi_{\theta_j}(y_t\mid x, y_{<t})}{\pi_{\theta_0}(y_t\mid x, y_{<t})}, \qquad j = 0, 1, \dots, K-1.

At j=0j=0 the ratio is exactly 1 (if trainer and sampler agree numerically — they do not quite, see training–inference mismatch), the clip is inactive, and the PPO gradient reduces to the plain policy gradient ∇ρ A=∇log⁡π A\nabla\rho\,A = \nabla\log\pi\,A. Every later mini-batch is off-policy by jj updates. The lag averages (K−1)/2(K-1)/2 and peaks at K−1K-1; with E>1E>1 each sample is also reused EE times.

How fast does the drift grow? If each optimizer step moves the parameters by roughly the same displacement δ\delta (Adam’s step size is nearly constant), then θj−θ0≈j δ\theta_j - \theta_0 \approx j\,\delta and a second-order expansion of the KL gives

KL(πθ0 ∥ πθj)≈12(jδ)⊤F(θ0) (jδ)=j2⋅12 δ⊤F δ,\mathrm{KL}(\pi_{\theta_0}\,\|\,\pi_{\theta_j}) \approx \tfrac12 (j\delta)^\top F(\theta_0)\,(j\delta) = j^2 \cdot \tfrac12\,\delta^\top F\,\delta ,

with FF the Fisher information. The KL to the sampling policy grows quadratically in the lag, so the last mini-batch of a K=16K=16 step sees roughly (15/3)2=25(15/3)^2 = 25 times the drift of the last mini-batch of a K=4K=4 step. When enough tokens leave [1−ϵ,1+ϵ][1-\epsilon, 1+\epsilon], PPO’s clip zeroes their gradient: the late mini-batches carry less and less signal. That is the trade-off: rollouts are expensive, so more updates per rollout improve sample efficiency, but each extra update trains on staler data. The same reasoning reappears, across steps instead of inside one, in asynchronous training.

NumPy Lag inside one step: KL and clip fraction per mini-batch (toy policy)
import numpy as np
rng = np.random.default_rng(2)

V = 200                                   # toy "vocabulary": one-step policy over V actions
reward = rng.normal(size=V)
theta0 = rng.normal(size=V) * 0.5
softmax = lambda z: np.exp(z - z.max()) / np.exp(z - z.max()).sum()

def run(K, total=4096, lr=0.03, eps=0.2):
    """one rollout of `total` samples from pi_old, split into K mini-batches = K optimizer steps"""
    p_old = softmax(theta0)
    a = rng.choice(V, size=total, p=p_old)
    adv = reward[a] - reward[a].mean()
    theta, m, v = theta0.copy(), np.zeros(V), np.zeros(V)
    rows = []
    for j, idx in enumerate(np.array_split(np.arange(total), K)):
        p = softmax(theta)
        ratio = p[a[idx]] / p_old[a[idx]]
        kl = np.sum(p_old * np.log(p_old / p))
        clipped = np.mean((ratio < 1 - eps) | (ratio > 1 + eps))
        rows.append((j, kl, clipped))
        # PPO-clip surrogate: clipped samples contribute no gradient
        live = ~(((ratio > 1 + eps) & (adv[idx] > 0)) | ((ratio < 1 - eps) & (adv[idx] < 0)))
        c = ratio * adv[idx] * live
        # gradient of mean_i c_i * log p(a_i) wrt logits = onehot(a_i) - p
        g = (np.bincount(a[idx].astype(np.intp), weights=c, minlength=V) - c.sum() * p) / len(idx)
        m = 0.9 * m + 0.1 * g; v = 0.999 * v + 0.001 * g * g          # Adam (bias-corrected)
        mh, vh = m / (1 - 0.9 ** (j + 1)), v / (1 - 0.999 ** (j + 1))
        theta += lr * mh / (np.sqrt(vh) + 1e-8)
    return rows

for K in (1, 4, 16):
    print(f"K={K:2d} optimizer steps per rollout")
    for j, kl, cf in run(K):
        if j in (0, 1, 3, 7, 15):
            print(f"   mini-batch {j:2d} (lag {j:2d}): KL(pi_old||pi_j)={kl:.5f}  clip fraction={cf:5.1%}")
 

The KL at lag 15 is about 16 times the KL at lag 3, close to the predicted 52=255^2=25 (Adam’s effective step shrinks a little as the moments settle). And the clip fraction jumps from a few percent to nearly everything between lag 7 and lag 15: in this toy the last mini-batches of a K=16K=16 step contribute almost no gradient. Real LLM runs move far less per step (learning rates around 10−610^{-6}), but the shape — quadratic KL, then a cliff in the clip fraction — is the same, and it is what actor/pg_clipfrac and actor/ppo_kl in verl’s metrics show.

verl 자료에 나온 설정을 넣어 보자. examples/grpo_trainer/의 Qwen3-235B-A22B GRPO 실행 스크립트는 TRAIN_BATCH_SIZE=128, PPO_MINI_BATCH_SIZE=128, n=16이다. K=1K=1, rollout당 갱신 한 번이다. docs/advance/v1_async_trainer.md의 V1 async trainer 벤치마크는 train_batch_size=64, ppo_mini_batch_size=16, 즉 K=4K=4다. 둘 다 흔한 선택이고, 둘을 가르는 것이 다음 절의 내용이다.

rollout당 여러 번 갱신하면 step 안에서 데이터가 낡는다

rollout은 step 시작 시점의 매개변수 θ0\theta_0로 한 번 샘플된다. verl은 갱신 루프 전에 배치 전체의 old_log_prob을 한 번 계산하므로(_step_once의 4단계), 모든 mini-batch가 ratio에서 같은 πold=πθ0\pi_\text{old}=\pi_{\theta_0}를 쓴다. mini-batch jj는 optimizer step jj번 뒤의 θj\theta_j에서 학습된다.

ρt(j)=πθj(yt∣x,y<t)πθ0(yt∣x,y<t),j=0,1,…,K−1.\rho_t^{(j)} = \frac{\pi_{\theta_j}(y_t\mid x, y_{<t})}{\pi_{\theta_0}(y_t\mid x, y_{<t})}, \qquad j = 0, 1, \dots, K-1.

j=0j=0이면 ratio는 정확히 1이고(trainer와 sampler가 수치적으로 같다면. 실제로는 조금 다르다. 학습–추론 불일치 참고), clip은 작동하지 않으며 PPO 기울기는 평범한 정책 경사 ∇ρ A=∇log⁡π A\nabla\rho\,A = \nabla\log\pi\,A가 된다. 그 뒤의 mini-batch는 모두 jj번의 갱신만큼 off-policy다. 지연의 평균은 (K−1)/2(K-1)/2, 최대는 K−1K-1이다. E>1E>1이면 샘플 하나를 EE번 재사용하기도 한다.

drift는 얼마나 빨리 커질까. optimizer step마다 매개변수가 거의 같은 크기 δ\delta만큼 움직인다고 하자(Adam의 step 크기는 거의 일정하다). 그러면 θj−θ0≈j δ\theta_j - \theta_0 \approx j\,\delta이고, KL을 2차까지 전개하면

KL(πθ0 ∥ πθj)≈12(jδ)⊤F(θ0) (jδ)=j2⋅12 δ⊤F δ\mathrm{KL}(\pi_{\theta_0}\,\|\,\pi_{\theta_j}) \approx \tfrac12 (j\delta)^\top F(\theta_0)\,(j\delta) = j^2 \cdot \tfrac12\,\delta^\top F\,\delta

이다(FF는 Fisher information). 샘플링 정책과의 KL은 지연의 제곱으로 자란다. K=16K=16 step의 마지막 mini-batch는 K=4K=4 step의 마지막 mini-batch보다 대략 (15/3)2=25(15/3)^2 = 25배의 drift를 본다. [1−ϵ,1+ϵ][1-\epsilon, 1+\epsilon] 밖으로 나간 토큰이 많아지면 PPO의 clip이 그 기울기를 0으로 만든다. 뒤쪽 mini-batch일수록 신호가 줄어든다. 이것이 trade-off다. rollout은 비싸므로 rollout당 갱신을 늘리면 샘플 효율이 좋아지지만, 갱신이 하나 늘 때마다 더 낡은 데이터로 학습한다. 같은 논리가 step 안이 아니라 step 사이에서 다시 나오는 것이 비동기 학습이다.

NumPy step 안의 지연: mini-batch별 KL과 clip 비율 (장난감 정책)
import numpy as np
rng = np.random.default_rng(2)

V = 200                                   # 장난감 "어휘": V개 행동에 대한 한 단계 정책
reward = rng.normal(size=V)
theta0 = rng.normal(size=V) * 0.5
softmax = lambda z: np.exp(z - z.max()) / np.exp(z - z.max()).sum()

def run(K, total=4096, lr=0.03, eps=0.2):
    """pi_old에서 뽑은 샘플 total개의 rollout 하나를 mini-batch K개(= optimizer step K번)로 나눈다"""
    p_old = softmax(theta0)
    a = rng.choice(V, size=total, p=p_old)
    adv = reward[a] - reward[a].mean()
    theta, m, v = theta0.copy(), np.zeros(V), np.zeros(V)
    rows = []
    for j, idx in enumerate(np.array_split(np.arange(total), K)):
        p = softmax(theta)
        ratio = p[a[idx]] / p_old[a[idx]]
        kl = np.sum(p_old * np.log(p_old / p))
        clipped = np.mean((ratio < 1 - eps) | (ratio > 1 + eps))
        rows.append((j, kl, clipped))
        # PPO-clip surrogate: clip된 샘플은 기울기를 내지 않는다
        live = ~(((ratio > 1 + eps) & (adv[idx] > 0)) | ((ratio < 1 - eps) & (adv[idx] < 0)))
        c = ratio * adv[idx] * live
        # mean_i c_i * log p(a_i)의 logit 기울기 = onehot(a_i) - p
        g = (np.bincount(a[idx].astype(np.intp), weights=c, minlength=V) - c.sum() * p) / len(idx)
        m = 0.9 * m + 0.1 * g; v = 0.999 * v + 0.001 * g * g          # Adam (bias 보정)
        mh, vh = m / (1 - 0.9 ** (j + 1)), v / (1 - 0.999 ** (j + 1))
        theta += lr * mh / (np.sqrt(vh) + 1e-8)
    return rows

for K in (1, 4, 16):
    print(f"K={K:2d} optimizer steps per rollout")
    for j, kl, cf in run(K):
        if j in (0, 1, 3, 7, 15):
            print(f"   mini-batch {j:2d} (lag {j:2d}): KL(pi_old||pi_j)={kl:.5f}  clip fraction={cf:5.1%}")
 

지연 15의 KL은 지연 3의 약 16배로, 예측한 52=255^2=25에 가깝다(모멘트가 안정되면서 Adam의 실효 step이 조금 줄어든다). clip 비율은 지연 7과 15 사이에서 몇 %에서 거의 전부로 뛴다. 이 장난감에서는 K=16K=16 step의 마지막 mini-batch들이 기울기를 거의 내지 못한다. 실제 LLM 학습은 step당 훨씬 적게 움직이지만(학습률 10−610^{-6} 안팎), 모양 — KL은 제곱으로, clip 비율은 절벽처럼 — 은 같고, verl 지표의 actor/pg_clipfrac, actor/ppo_kl이 보여 주는 것이 이것이다.

Gradient accumulation must not change the loss

Inside one optimizer step each GPU runs MM forward/backward passes and the optimizer steps once. For this to be the same update as one giant batch, the per-pass losses must add up to the mini-batch loss exactly. Take the default aggregation loss_agg_mode=token-mean over a mini-batch whose response tokens are T\mathcal{T} (all GPUs, all micro-batches), N=∣T∣N = |\mathcal{T}|:

L=1N∑t∈Tℓt.\mathcal{L} = \frac{1}{N}\sum_{t\in\mathcal{T}} \ell_t .

Rank dd holds micro-batches m=1..Mm = 1..M with token sets Td,m\mathcal{T}_{d,m}. verl’s agg_loss computes each micro-batch loss as

Ld,m=DN∑t∈Td,mℓt,\mathcal{L}_{d,m} = \frac{D}{N}\sum_{t\in\mathcal{T}_{d,m}} \ell_t ,

where NN is the global token count of the mini-batch (each rank all-gathers the per-sequence lengths, global_token_num, before the loop). Backward on each Ld,m\mathcal{L}_{d,m} accumulates gradients on rank dd; the data-parallel reduction then averages over the DD ranks:

1D∑d=1D∑m=1M∇Ld,m=1D⋅DN∑d,m∑t∈Td,m∇ℓt=∇L.  ✓\frac{1}{D}\sum_{d=1}^{D}\sum_{m=1}^{M} \nabla\mathcal{L}_{d,m} = \frac{1}{D}\cdot\frac{D}{N}\sum_{d,m}\sum_{t\in\mathcal{T}_{d,m}}\nabla\ell_t = \nabla\mathcal{L}. \;\checkmark

The tempting alternative — take the mean inside each micro-batch and average the means — weights a token by 1/(M ∣Td,m∣)1/(M\,|\mathcal{T}_{d,m}|), so tokens in micro-batches with few tokens count more. With dynamic batching the token counts per micro-batch are deliberately uneven across sequences of different length, so this bias is not hypothetical. The same care applies to the sequence-level modes (seq-mean-token-mean, seq-mean-token-sum, seq-mean-token-sum-norm), which divide by the global number of sequences instead; sequence vs token explains what these modes do to length bias.

NumPy Token-mean under micro-batching and data parallelism
import numpy as np
rng = np.random.default_rng(0)

# 64 sequences with long-tailed lengths (response tokens that carry loss)
lens = np.clip(rng.lognormal(mean=6.0, sigma=0.9, size=64).astype(int), 8, 4096)
d = 16
X = [rng.normal(size=(L, d)) for L in lens]          # per-token features
Y = [rng.normal(size=L) for L in lens]               # per-token targets
w = rng.normal(size=d) * 0.1

def tok_grad_sum(idx, w):
    """sum over tokens of grad of 0.5*(x.w - y)^2 for sequences idx, and their token count"""
    g = np.zeros(d); n = 0
    for i in idx:
        r = X[i] @ w - Y[i]
        g += X[i].T @ r
        n += len(r)
    return g, n

g_all, N = tok_grad_sum(range(64), w)
g_ref = g_all / N                                    # reference: one big batch, token-mean

D, M = 4, 4                                          # 4 DP ranks, 4 micro-batches each
ranks = np.array_split(rng.permutation(64), D)

def verl_style(w):
    per_rank = []
    for r in ranks:
        acc = np.zeros(d)
        for mb in np.array_split(r, M):
            g, _ = tok_grad_sum(mb, w)
            acc += g / N * D                          # sum / N_global * dp_size
        per_rank.append(acc)
    return np.mean(per_rank, axis=0)                 # DP all-reduce = average

def naive(w):
    per_rank = []
    for r in ranks:
        acc = np.zeros(d)
        for mb in np.array_split(r, M):
            g, n = tok_grad_sum(mb, w)
            acc += (g / n) / M                       # mean inside each micro-batch, then average
        per_rank.append(acc)
    return np.mean(per_rank, axis=0)

rel = lambda a: np.linalg.norm(a - g_ref) / np.linalg.norm(g_ref)
print(f"tokens in mini-batch N = {N},  shortest seq {lens.min()}, longest {lens.max()}")
print(f"global token-mean (sum/N_global*D, then DP mean): rel. error = {rel(verl_style(w)):.2e}")
print(f"per-micro-batch mean, then average:                rel. error = {rel(naive(w)):.2e}")
 

The first error is at machine precision; the second is a few percent — a systematically different gradient, not noise.

기울기 누적이 손실을 바꾸면 안 된다

optimizer step 하나 안에서 GPU마다 forward/backward를 MM번 하고 optimizer는 한 번 움직인다. 이것이 거대한 배치 하나로 한 갱신과 같으려면, pass별 손실을 더한 것이 mini-batch 손실과 정확히 같아야 한다. 기본 집계 loss_agg_mode=token-mean을 보자. mini-batch의 응답 토큰 전체(모든 GPU, 모든 micro-batch)를 T\mathcal{T}, N=∣T∣N = |\mathcal{T}|라 하면

L=1N∑t∈Tℓt.\mathcal{L} = \frac{1}{N}\sum_{t\in\mathcal{T}} \ell_t .

rank dd는 토큰 집합이 Td,m\mathcal{T}_{d,m}인 micro-batch m=1..Mm = 1..M을 갖는다. verl의 agg_loss는 micro-batch 손실을 이렇게 계산한다.

Ld,m=DN∑t∈Td,mℓt\mathcal{L}_{d,m} = \frac{D}{N}\sum_{t\in\mathcal{T}_{d,m}} \ell_t

여기서 NN은 mini-batch의 전역 토큰 수다(각 rank가 루프 전에 시퀀스별 길이 global_token_num을 all-gather한다). 각 Ld,m\mathcal{L}_{d,m}의 backward가 rank dd에 기울기를 누적하고, data-parallel reduction이 DD개 rank에 대해 평균을 낸다.

1D∑d=1D∑m=1M∇Ld,m=1D⋅DN∑d,m∑t∈Td,m∇ℓt=∇L.  ✓\frac{1}{D}\sum_{d=1}^{D}\sum_{m=1}^{M} \nabla\mathcal{L}_{d,m} = \frac{1}{D}\cdot\frac{D}{N}\sum_{d,m}\sum_{t\in\mathcal{T}_{d,m}}\nabla\ell_t = \nabla\mathcal{L}. \;\checkmark

솔깃한 대안 — micro-batch마다 평균을 내고 그 평균들을 다시 평균 — 은 토큰 하나에 1/(M ∣Td,m∣)1/(M\,|\mathcal{T}_{d,m}|)의 가중치를 준다. 토큰이 적은 micro-batch의 토큰이 더 크게 반영된다. 동적 배치에서는 길이가 다른 시퀀스 때문에 micro-batch별 토큰 수가 일부러 고르지 않게 되므로, 이 편향은 가상의 문제가 아니다. 시퀀스 단위 모드(seq-mean-token-mean, seq-mean-token-sum, seq-mean-token-sum-norm)도 같은 이유로 전역 시퀀스 수로 나눈다. 이 모드들이 길이 편향에 무엇을 하는지는 sequence vs token에서 다룬다.

NumPy micro-batch와 data parallel 아래의 token-mean
import numpy as np
rng = np.random.default_rng(0)

# 길이 분포의 꼬리가 긴 시퀀스 64개 (손실이 걸리는 응답 토큰)
lens = np.clip(rng.lognormal(mean=6.0, sigma=0.9, size=64).astype(int), 8, 4096)
d = 16
X = [rng.normal(size=(L, d)) for L in lens]          # 토큰별 특징
Y = [rng.normal(size=L) for L in lens]               # 토큰별 목표값
w = rng.normal(size=d) * 0.1

def tok_grad_sum(idx, w):
    """시퀀스 idx의 토큰별 0.5*(x.w - y)^2 기울기 합과 토큰 수"""
    g = np.zeros(d); n = 0
    for i in idx:
        r = X[i] @ w - Y[i]
        g += X[i].T @ r
        n += len(r)
    return g, n

g_all, N = tok_grad_sum(range(64), w)
g_ref = g_all / N                                    # 기준: 큰 배치 하나, token-mean

D, M = 4, 4                                          # DP rank 4개, rank마다 micro-batch 4개
ranks = np.array_split(rng.permutation(64), D)

def verl_style(w):
    per_rank = []
    for r in ranks:
        acc = np.zeros(d)
        for mb in np.array_split(r, M):
            g, _ = tok_grad_sum(mb, w)
            acc += g / N * D                          # 합 / 전역 N * dp_size
        per_rank.append(acc)
    return np.mean(per_rank, axis=0)                 # DP all-reduce = 평균

def naive(w):
    per_rank = []
    for r in ranks:
        acc = np.zeros(d)
        for mb in np.array_split(r, M):
            g, n = tok_grad_sum(mb, w)
            acc += (g / n) / M                       # micro-batch 안에서 평균, 그다음 평균
        per_rank.append(acc)
    return np.mean(per_rank, axis=0)

rel = lambda a: np.linalg.norm(a - g_ref) / np.linalg.norm(g_ref)
print(f"tokens in mini-batch N = {N},  shortest seq {lens.min()}, longest {lens.max()}")
print(f"global token-mean (sum/N_global*D, then DP mean): rel. error = {rel(verl_style(w)):.2e}")
print(f"per-micro-batch mean, then average:                rel. error = {rel(naive(w)):.2e}")
 

첫 번째 오차는 기계 정밀도 수준이고, 두 번째는 몇 % — 잡음이 아니라 체계적으로 다른 기울기다.

Micro-batches: count sequences or count tokens

Activation memory is proportional to the number of tokens in a pass, not the number of sequences: with FlashAttention the s2s^2 attention-score term is never materialised, so the per-layer activations of the Korthikanti et al. formula become linear in tokens, and the logits add tokens × vocabulary. A fixed μ\mu therefore gives passes whose memory varies with whatever lengths happened to land together, and μ\mu has to be set for the worst case. Two mechanisms fix this.

Packing (actor_rollout_ref.model.use_remove_padding=True, on by default) concatenates the sequences of a micro-batch into one row and passes cumulative sequence lengths to a variable-length attention kernel, so padding is never computed.

Dynamic batch size (use_dynamic_bsz=True, also on by default in current ppo_trainer.yaml) forms micro-batches by a token budget TT = ppo_max_token_len_per_gpu (default 16384). The algorithm in rearrange_micro_batches is short enough to state completely:

  1. Start with k=⌈∑iℓi/T⌉k = \lceil \sum_i \ell_i / T\rceil micro-batches (a lower bound, since sequences are indivisible).
  2. Synchronise kk across data-parallel ranks with an all-reduce MAX, because every rank must run the same number of forward/backward passes (FSDP and Megatron collectives happen inside each pass); with virtual pipeline stages, round kk up to a multiple of their count.
  3. Partition the sequences into kk groups balancing an attention-aware workload w(ℓ)=24576 ℓ+ℓ2w(\ell)=24576\,\ell+\ell^2 (Karmarkar–Karp differencing).
  4. If some group exceeds TT tokens, set k←k+1k \leftarrow k+1 and repartition.
  5. Order the groups so the lighter ones sit at both ends (smaller pipeline warm-up and cool-down bubbles).

The hard constraint is T≥T \ge the longest sequence (prompt + response, or the whole multi-turn trajectory), times the Ulysses sequence-parallel size if used — the code asserts it. The config comment suggests T≈n⋅T \approx n\cdotmax_prompt_length + max_response_length and the tuning guide says “at least 2 × (max_prompt_length + max_response_length)”; above the hard floor, a larger TT means fewer, larger passes and better kernel efficiency, until memory runs out. A separate, earlier balancer (trainer.balance_batch=True) reorders the whole batch so that every data-parallel rank receives a similar total token count.

micro-batch: 시퀀스를 셀까, 토큰을 셀까

activation 메모리는 pass 안의 시퀀스 수가 아니라 토큰 수에 비례한다. FlashAttention은 s2s^2짜리 attention score를 만들지 않으므로 Korthikanti 등의 층당 activation 식이 토큰 수에 선형이 되고, logit은 토큰 수 × 어휘 크기만큼 더해진다. 그래서 고정 μ\mu를 쓰면 어떤 길이들이 함께 묶였는지에 따라 pass마다 메모리가 달라지고, μ\mu를 최악의 경우에 맞춰야 한다. 이를 고치는 장치가 둘이다.

Packing(actor_rollout_ref.model.use_remove_padding=True, 기본값 켜짐)은 micro-batch의 시퀀스들을 한 줄로 이어 붙이고, 누적 시퀀스 길이를 가변 길이 attention kernel에 넘긴다. padding은 아예 계산하지 않는다.

동적 배치 크기(use_dynamic_bsz=True, 현재 ppo_trainer.yaml에서 역시 기본값 켜짐)는 토큰 예산 TT = ppo_max_token_len_per_gpu(기본 16384)로 micro-batch를 만든다. rearrange_micro_batches의 알고리즘은 짧아서 전부 적을 수 있다.

  1. k=⌈∑iℓi/T⌉k = \lceil \sum_i \ell_i / T\rceil개의 micro-batch로 시작한다(시퀀스는 쪼갤 수 없으니 하한이다).
  2. data-parallel rank 사이에서 all-reduce MAX로 kk를 맞춘다. 모든 rank가 같은 횟수의 forward/backward를 해야 하기 때문이다(FSDP와 Megatron의 collective가 pass마다 일어난다). virtual pipeline stage가 있으면 kk를 그 수의 배수로 올린다.
  3. attention을 고려한 작업량 w(ℓ)=24576 ℓ+ℓ2w(\ell)=24576\,\ell+\ell^2의 균형을 맞추도록 시퀀스를 kk개 그룹으로 나눈다(Karmarkar–Karp differencing).
  4. 어느 그룹이 TT 토큰을 넘으면 k←k+1k \leftarrow k+1로 다시 나눈다.
  5. 가벼운 그룹을 양 끝에 오도록 순서를 정한다(pipeline warm-up·cool-down bubble이 작아진다).

절대 조건은 T≥T \ge 가장 긴 시퀀스(프롬프트 + 응답, 멀티턴이면 trajectory 전체)이고, Ulysses sequence parallel을 쓰면 그 크기를 곱한다. 코드가 assert한다. 설정 파일 주석은 T≈n⋅T \approx n\cdotmax_prompt_length + max_response_length를, 튜닝 가이드는 “적어도 2 × (max_prompt_length + max_response_length)“를 권한다. 하한 위에서는 TT가 클수록 pass가 더 적고 커져 kernel 효율이 좋아지며, 메모리가 허락하는 데까지 키우면 된다. 이와 별개로 앞 단계의 균형기(trainer.balance_batch=True)가 배치 전체를 재배열해 data-parallel rank마다 총 토큰 수가 비슷해지게 한다.

Each row is one forward/backward pass (a micro-batch) on one GPU; its length is the number of tokens it computes. Coloured segments are real tokens of individual sequences (prompt darker, response lighter); hatched red is padding that is computed for nothing. With fixed μ, rows have very different lengths: the longest row sets peak activation memory, so μ must be chosen for the worst case. With the dynamic budget T (in units of the longest sequence), rows are filled up to the dashed line, so there are fewer passes of almost equal size. Untick use_remove_padding to see why dynamic batching assumes packing: the balancer mixes long and short sequences, which is the worst case for padding. 각 행은 한 GPU의 forward/backward 한 번(micro-batch)이고, 길이는 그 pass가 계산하는 토큰 수다. 색 구간은 각 시퀀스의 실제 토큰(진한 쪽 프롬프트, 옅은 쪽 응답), 빗금 빨강은 헛계산하는 padding이다. 고정 μ에서는 행 길이가 들쭉날쭉하다. 가장 긴 행이 activation 메모리 최대치를 정하므로 μ를 최악의 경우에 맞춰야 한다. 동적 예산 T(가장 긴 시퀀스 길이의 배수)에서는 행이 점선까지 채워져, 크기가 고른 pass가 더 적게 나온다. use_remove_padding을 끄면 동적 배치가 왜 packing을 전제하는지 보인다. 균형을 맞추느라 긴 시퀀스와 짧은 시퀀스를 섞는데, 그게 padding에는 최악이다.
NumPy Fixed micro-batches vs token-budget packing on one GPU
import numpy as np
rng = np.random.default_rng(1)

P, R = 1024, 8192                                    # max prompt / response length
S = 64                                               # sequences on one GPU for one optimizer step
prompt = rng.integers(200, P, size=S)
resp = np.minimum(rng.lognormal(np.log(1500), 1.0, size=S).astype(int) + 1, R)
L = prompt + resp                                    # tokens per sequence

def workload(s):                                     # verl's attention-aware cost proxy
    return 24576 * s + s.astype(np.int64) ** 2

def partition(items_w, k):
    """greedy LPT: heaviest item to the lightest bin (a simple stand-in for Karmarkar-Karp)"""
    bins = [[] for _ in range(k)]; load = np.zeros(k)
    for i in np.argsort(-items_w):
        j = int(np.argmin(load)); bins[j].append(i); load[j] += items_w[i]
    return bins

def dynamic(L, T):
    assert T >= L.max(), "token budget must hold the longest sequence"
    k = int(np.ceil(L.sum() / T))                    # lower bound on #micro-batches
    while True:
        bins = partition(workload(L), k)
        if all(L[b].sum() <= T for b in bins):
            return bins
        k += 1                                       # balanced split overflowed: one more micro-batch

def fixed(L, mu):
    return [list(range(i, i + mu)) for i in range(0, len(L), mu)]

def report(name, bins):
    tok = np.array([L[b].sum() for b in bins])
    padded = np.array([len(b) * L[b].max() for b in bins])       # cost if every micro-batch is padded
    print(f"{name:<28} passes={len(bins):3d}  max tokens/pass={tok.max():6d}  "
          f"min={tok.min():6d}  padding if not packed={1 - L.sum() / padded.sum():5.1%}")

print(f"{S} sequences, {L.sum()} real tokens, longest {L.max()}")
for mu in (1, 2, 4):
    report(f"fixed micro_bsz={mu}", fixed(L, mu))
for T in (L.max(), 16384, 32768):
    report(f"dynamic max_token_len={T}", dynamic(L, T))
 

Read the rows in pairs. Fixed μ=4\mu=4 and the dynamic budget 16384 reach almost the same peak tokens per pass (≈ the same peak memory), but the fixed version needs 16 passes whose sizes vary 2.4× while the dynamic one needs 10 nearly equal passes. And the last column is the trap: without packing, the balancer’s habit of mixing one long sequence with several short ones makes padding worse than fixed batching. Dynamic batching is a packing feature.

The same anatomy in other frameworks

The landscape lesson compares the frameworks as systems; here only the batch vocabulary.

quantityverlTRL GRPOTrainerslimeOpenRLHF
prompts per rolloutdata.train_batch_sizesee note--rollout-batch-size--rollout.batch_size
samples per promptrollout.nnum_generations--n-samples-per-prompt--rollout.n_samples_per_prompt
per optimizer stepppo_mini_batch_size (prompts)per_device_train_batch_size × gradient_accumulation_steps × world size (completions)--global-batch-size (samples)--train.batch_size (samples)
reuse of a rolloutppo_epochsnum_iterations--num-steps-per-rollout (steps, not epochs)--train.max_epochs
per-GPU passppo_micro_batch_size_per_gpu / ppo_max_token_len_per_gpuper_device_train_batch_size--micro-batch-size / --max-tokens-per-gpu--train.micro_batch_size / --train.max_tokens_per_gpu

Versions read on 2026-12-03: TRL v1.19.0 (trl/trainer/grpo_config.py), slime v0.4.0 (slime/utils/arguments.py), OpenRLHF v0.12.0 (openrlhf/cli/train_ppo_ray.py, whose flags are now namespaced as --train.*, --rollout.*). Two differences matter. TRL counts completions per device, not prompts, and its generation_batch_size defaults to per_device_train_batch_size × num_processes × steps_per_generation with steps_per_generation defaulting to gradient_accumulation_steps — “one generation batch processed per optimization step”, so with spg = steps_per_generation and gas = gradient_accumulation_steps, K=(spg/gas)⋅num_iterations=1K = (\text{spg}/\text{gas})\cdot\text{num\_iterations} = 1 by default; its docs note that training becomes off-policy when steps_per_generation > gradient_accumulation_steps or num_iterations > 1. slime’s --num-steps-per-rollout sets KK directly (it is B/bB/b, not an epoch count), and its help text warns that --global-batch-size counts samples, so one step per rollout means rollout_batch_size × n_samples_per_prompt. Its --use-dynamic-batch-size / --max-tokens-per-gpu is the same token-budget idea, and --balance-by-flops uses a Karmarkar–Karp partition on a c L+L2c\,L + L^2 cost like verl’s.

NumPy 한 GPU에서 고정 micro-batch와 토큰 예산 packing 비교
import numpy as np
rng = np.random.default_rng(1)

P, R = 1024, 8192                                    # 최대 프롬프트 / 응답 길이
S = 64                                               # optimizer step 하나에서 GPU 하나가 맡는 시퀀스
prompt = rng.integers(200, P, size=S)
resp = np.minimum(rng.lognormal(np.log(1500), 1.0, size=S).astype(int) + 1, R)
L = prompt + resp                                    # 시퀀스별 토큰 수

def workload(s):                                     # verl의 attention 고려 비용 근사
    return 24576 * s + s.astype(np.int64) ** 2

def partition(items_w, k):
    """greedy LPT: 가장 무거운 것을 가장 가벼운 bin에 (Karmarkar-Karp의 간단한 대용)"""
    bins = [[] for _ in range(k)]; load = np.zeros(k)
    for i in np.argsort(-items_w):
        j = int(np.argmin(load)); bins[j].append(i); load[j] += items_w[i]
    return bins

def dynamic(L, T):
    assert T >= L.max(), "토큰 예산은 가장 긴 시퀀스를 담아야 한다"
    k = int(np.ceil(L.sum() / T))                    # micro-batch 수의 하한
    while True:
        bins = partition(workload(L), k)
        if all(L[b].sum() <= T for b in bins):
            return bins
        k += 1                                       # 균형 분할이 넘쳤다: micro-batch 하나 추가

def fixed(L, mu):
    return [list(range(i, i + mu)) for i in range(0, len(L), mu)]

def report(name, bins):
    tok = np.array([L[b].sum() for b in bins])
    padded = np.array([len(b) * L[b].max() for b in bins])       # micro-batch마다 padding할 때의 비용
    print(f"{name:<28} passes={len(bins):3d}  max tokens/pass={tok.max():6d}  "
          f"min={tok.min():6d}  padding if not packed={1 - L.sum() / padded.sum():5.1%}")

print(f"{S} sequences, {L.sum()} real tokens, longest {L.max()}")
for mu in (1, 2, 4):
    report(f"fixed micro_bsz={mu}", fixed(L, mu))
for T in (L.max(), 16384, 32768):
    report(f"dynamic max_token_len={T}", dynamic(L, T))
 

행을 짝지어 읽자. 고정 μ=4\mu=4와 동적 예산 16384는 pass당 최대 토큰(≈ 최대 메모리)이 거의 같지만, 고정 쪽은 크기가 2.4배까지 들쭉날쭉한 pass 16번, 동적 쪽은 거의 같은 크기의 pass 10번이다. 마지막 열이 함정이다. packing이 없으면, 긴 시퀀스 하나와 짧은 시퀀스 여럿을 섞는 균형기의 습성 때문에 padding이 고정 배치보다 더 나빠진다. 동적 배치는 packing을 위한 기능이다.

다른 프레임워크에서 같은 해부도

시스템으로서의 비교는 landscape 레슨에서 했다. 여기서는 배치 용어만 맞춰 본다.

양verlTRL GRPOTrainerslimeOpenRLHF
rollout당 프롬프트data.train_batch_size아래 설명--rollout-batch-size--rollout.batch_size
프롬프트당 샘플rollout.nnum_generations--n-samples-per-prompt--rollout.n_samples_per_prompt
optimizer step당ppo_mini_batch_size(프롬프트)per_device_train_batch_size × gradient_accumulation_steps × world size(completion)--global-batch-size(샘플)--train.batch_size(샘플)
rollout 재사용ppo_epochsnum_iterations--num-steps-per-rollout(epoch가 아니라 step 수)--train.max_epochs
GPU당 passppo_micro_batch_size_per_gpu / ppo_max_token_len_per_gpuper_device_train_batch_size--micro-batch-size / --max-tokens-per-gpu--train.micro_batch_size / --train.max_tokens_per_gpu

2026-12-03에 읽은 버전: TRL v1.19.0(trl/trainer/grpo_config.py), slime v0.4.0(slime/utils/arguments.py), OpenRLHF v0.12.0(openrlhf/cli/train_ppo_ray.py. 플래그가 이제 --train.*, --rollout.*처럼 이름공간으로 묶였다). 중요한 차이가 둘이다. TRL은 프롬프트가 아니라 device당 completion 수를 세고, generation_batch_size의 기본값이 per_device_train_batch_size × num_processes × steps_per_generation, steps_per_generation의 기본값이 gradient_accumulation_steps다. 문서 표현대로 “optimization step마다 generation batch 하나”이니 spg = steps_per_generation, gas = gradient_accumulation_steps라 하면 기본값에서 K=(spg/gas)⋅num_iterations=1K = (\text{spg}/\text{gas})\cdot\text{num\_iterations} = 1이다. 문서는 steps_per_generation > gradient_accumulation_steps이거나 num_iterations > 1이면 off-policy가 된다고 적어 두었다. slime의 --num-steps-per-rollout은 KK를 직접 정하고(epoch 수가 아니라 B/bB/b다), help 문구가 --global-batch-size는 샘플 수이므로 rollout당 한 step이려면 rollout_batch_size × n_samples_per_prompt로 두라고 경고한다. --use-dynamic-batch-size / --max-tokens-per-gpu는 같은 토큰 예산 아이디어이고, --balance-by-flops는 verl처럼 c L+L2c\,L + L^2 비용에 Karmarkar–Karp 분할을 쓴다.

PyTorch PyTorch: gradient accumulation with global token-mean (data parallel) 로컬에서 실행run locally (pip install torch)
import torch
import torch.distributed as dist

def train_one_mini_batch(model, optimizer, micro_batches, eps=0.2):
    """micro_batches: this rank's share of one mini-batch, each a dict with
    input_ids, response_mask, old_logprob, advantages (packed or padded the same way)."""
    world = dist.get_world_size()
    # 1. global token count of the whole mini-batch (all ranks, all micro-batches)
    local = sum(int(mb["response_mask"].sum()) for mb in micro_batches)
    n_global = torch.tensor([local], device="cuda")
    dist.all_reduce(n_global, op=dist.ReduceOp.SUM)

    optimizer.zero_grad(set_to_none=True)
    for mb in micro_batches:
        logp = model.token_logprobs(mb["input_ids"])            # (B, T) log pi_theta(y_t | ...)
        ratio = torch.exp(logp - mb["old_logprob"])
        A = mb["advantages"]
        pg = -torch.minimum(ratio * A, ratio.clamp(1 - eps, 1 + eps) * A)
        # sum / N_global * world: DDP/FSDP averages grads over ranks, which divides by world again
        loss = (pg * mb["response_mask"]).sum() / n_global * world
        loss.backward()                                         # grads accumulate across micro-batches
    torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
    optimizer.step()                                            # one optimizer step per mini-batch
 

(With FSDP or DDP you would also skip the gradient reduction on all but the last micro-batch — no_sync() or FSDP2’s set_requires_gradient_sync(False) — which verl’s FSDP engine does by default; it saves M−1M-1 reductions and does not change the result.)

확인 문제Check yourself

B=256 prompts, rollout.n=8, ppo_mini_batch_size=64, ppo_epochs=2, actor data-parallel size 16, micro_batch_size_per_gpu=4. How many optimizer steps happen per rollout, and how many forward/backward passes does each GPU run per optimizer step?

K=E⋅B/b=2⋅256/64=8K = E\cdot B/b = 2\cdot 256/64 = 8 optimizer steps. Each mini-batch holds b n=64⋅8=512b\,n = 64\cdot 8 = 512 trajectories, i.e. 512/16=32512/16 = 32 per GPU, which with μ=4\mu=4 is M=8M = 8 accumulated passes. The last update trains on data 7 updates old (mean lag 3.5), and every trajectory is used twice.

확인 문제Check yourself

With use_dynamic_bsz=True you set ppo_max_token_len_per_gpu=8192, but max_prompt_length=2048 and max_response_length=8192. What happens?

A sequence is indivisible for the micro-batch splitter, so rearrange_micro_batches asserts max_token_len >= max_seq_len. The budget must cover the longest possible prompt + response (times the Ulysses size if sequence parallelism is on). In multi-turn agent RL the “sequence” is the whole trajectory with all tool outputs, which is why agent runs need much larger budgets — or context parallelism.

Summary

  • One rollout = B nB\,n trajectories; it becomes K=E B/bK = E\,B/b optimizer steps, each split into b n/Db\,n/D trajectories per GPU and MM accumulated passes. In verl ppo_mini_batch_size counts prompts and is multiplied by rollout.n internally.
  • Mini-batch jj is trained at θj\theta_j against πold=πθ0\pi_\text{old}=\pi_{\theta_0}; only the first update is on-policy, and the KL to the sampler grows roughly as j2j^2, until clipping silences the late mini-batches.
  • Token-mean survives micro-batching and data parallelism only if every pass divides by the global token count (and multiplies by DD when ranks are averaged); averaging per-micro-batch means is biased.
  • Memory follows tokens per pass. Packing removes padding; dynamic batching (use_dynamic_bsz, ppo_max_token_len_per_gpu) packs to a token budget with balanced, DP-synchronised micro-batch counts. The budget must exceed the longest sequence.
  • Performance knobs must never change the learning curve; if they do, look at the loss normalisation first.
PyTorch PyTorch: 전역 token-mean으로 하는 기울기 누적 (data parallel) 로컬에서 실행run locally (pip install torch)
import torch
import torch.distributed as dist

def train_one_mini_batch(model, optimizer, micro_batches, eps=0.2):
    """micro_batches: 이 rank가 맡은 mini-batch 몫. 각각 input_ids, response_mask,
    old_logprob, advantages를 담은 dict (packing 또는 padding 방식은 같게)."""
    world = dist.get_world_size()
    # 1. mini-batch 전체(모든 rank, 모든 micro-batch)의 전역 토큰 수
    local = sum(int(mb["response_mask"].sum()) for mb in micro_batches)
    n_global = torch.tensor([local], device="cuda")
    dist.all_reduce(n_global, op=dist.ReduceOp.SUM)

    optimizer.zero_grad(set_to_none=True)
    for mb in micro_batches:
        logp = model.token_logprobs(mb["input_ids"])            # (B, T) log pi_theta(y_t | ...)
        ratio = torch.exp(logp - mb["old_logprob"])
        A = mb["advantages"]
        pg = -torch.minimum(ratio * A, ratio.clamp(1 - eps, 1 + eps) * A)
        # 합 / 전역 N * world: DDP/FSDP가 rank 평균을 내며 world로 다시 나눈다
        loss = (pg * mb["response_mask"]).sum() / n_global * world
        loss.backward()                                         # micro-batch마다 기울기가 누적된다
    torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
    optimizer.step()                                            # mini-batch당 optimizer step 한 번
 

(FSDP나 DDP라면 마지막 micro-batch를 뺀 나머지에서는 기울기 reduction을 건너뛸 수도 있다. no_sync() 또는 FSDP2의 set_requires_gradient_sync(False)이고, verl의 FSDP engine은 기본으로 그렇게 한다. reduction을 M−1M-1번 아끼고 결과는 같다.)

확인 문제Check yourself

B=256 프롬프트, rollout.n=8, ppo_mini_batch_size=64, ppo_epochs=2, actor의 data-parallel 크기 16, micro_batch_size_per_gpu=4. rollout당 optimizer step은 몇 번이고, optimizer step마다 GPU 하나가 forward/backward를 몇 번 하나?

K=E⋅B/b=2⋅256/64=8K = E\cdot B/b = 2\cdot 256/64 = 8번이다. mini-batch 하나에 trajectory b n=64⋅8=512b\,n = 64\cdot 8 = 512개, GPU당 512/16=32512/16 = 32개이고, μ=4\mu=4이면 누적 pass M=8M = 8번이다. 마지막 갱신은 7번 갱신만큼 낡은 데이터로 학습하고(평균 지연 3.5), 모든 trajectory가 두 번씩 쓰인다.

확인 문제Check yourself

use_dynamic_bsz=True에서 ppo_max_token_len_per_gpu=8192로 두었는데 max_prompt_length=2048, max_response_length=8192다. 어떻게 되나?

micro-batch 분할기에게 시퀀스는 쪼갤 수 없는 단위라서 rearrange_micro_batches가 max_token_len >= max_seq_len을 assert한다. 예산은 가능한 가장 긴 프롬프트 + 응답(sequence parallel을 쓰면 Ulysses 크기를 곱한 값)을 덮어야 한다. 멀티턴 agent RL에서 “시퀀스”는 tool 출력까지 포함한 trajectory 전체이므로 agent 학습은 훨씬 큰 예산이나 context parallelism이 필요하다.

정리

  • rollout 하나 = trajectory B nB\,n개이고, 이것이 optimizer step K=E B/bK = E\,B/b번이 되며, 각 step은 GPU당 b n/Db\,n/D개, 누적 pass MM번으로 쪼개진다. verl의 ppo_mini_batch_size는 프롬프트 수이고 내부에서 rollout.n이 곱해진다.
  • mini-batch jj는 θj\theta_j에서 πold=πθ0\pi_\text{old}=\pi_{\theta_0}에 대해 학습된다. 첫 갱신만 on-policy이고, sampler와의 KL은 대략 j2j^2로 자라다가 clip이 뒤쪽 mini-batch를 침묵시킨다.
  • token-mean이 micro-batch와 data parallel 아래에서 유지되려면 모든 pass가 전역 토큰 수로 나눠야 한다(rank 평균을 낸다면 DD를 곱한다). micro-batch 평균의 평균은 편향된다.
  • 메모리는 pass당 토큰 수를 따른다. packing은 padding을 없애고, 동적 배치(use_dynamic_bsz, ppo_max_token_len_per_gpu)는 토큰 예산으로 묶되 micro-batch 수를 균형 있게, DP 사이에 맞춰 정한다. 예산은 가장 긴 시퀀스보다 커야 한다.
  • 성능 손잡이는 학습 곡선을 바꾸면 안 된다. 바뀐다면 먼저 손실 정규화를 보라.

더 읽을거리Further reading