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
| symbol | verl name | unit | scope |
|---|---|---|---|
data.train_batch_size | prompts | global | |
actor_rollout_ref.rollout.n | samples per prompt (the GRPO group) | global | |
actor_rollout_ref.actor.ppo_mini_batch_size | prompts | global | |
actor_rollout_ref.actor.ppo_epochs | passes over the rollout | global | |
| or | ppo_micro_batch_size_per_gpu, or ppo_max_token_len_per_gpu with use_dynamic_bsz=True | sequences, or tokens | per GPU |
The data-parallel size of the actor completes the set. With Megatron it is ; 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 therefore never changes the algorithm; changing or never changes the gradient (up to floating-point summation order).
From these definitions:
A verl global step (the x-axis of the logged metrics and the unit of trainer.total_training_steps) is one rollout batch of prompts, so one point on the chart hides optimizer steps and 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 이름 | 단위 | 범위 |
|---|---|---|---|
data.train_batch_size | 프롬프트 | 전역 | |
actor_rollout_ref.rollout.n | 프롬프트당 샘플 수(GRPO 그룹) | 전역 | |
actor_rollout_ref.actor.ppo_mini_batch_size | 프롬프트 | 전역 | |
actor_rollout_ref.actor.ppo_epochs | rollout을 도는 횟수 | 전역 | |
| 또는 | ppo_micro_batch_size_per_gpu, 또는 use_dynamic_bsz=True일 때 ppo_max_token_len_per_gpu | 시퀀스 수 또는 토큰 수 | GPU당 |
여기에 actor의 data-parallel 크기 가 더해진다. Megatron이면 , 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 하나에 대한 지역 값이다. 그래서 를 바꿔도 알고리즘은 바뀌지 않고, 나 를 바꿔도 기울기는 바뀌지 않는다(부동소수점 합산 순서 차이 정도만 생긴다).
정의에서 바로 나오는 양들:
verl의 global step(로그 그래프의 가로축이자 trainer.total_training_steps의 단위)은 프롬프트 개짜리 rollout 하나다. 그래프의 점 하나에 optimizer step 번과 GPU당 backward 번이 들어 있다.
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: , 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: . 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 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 in the ratio. Mini-batch is trained at , after optimizer steps:
At 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 . Every later mini-batch is off-policy by updates. The lag averages and peaks at ; with each sample is also reused times.
How fast does the drift grow? If each optimizer step moves the parameters by roughly the same displacement (Adam’s step size is nearly constant), then and a second-order expansion of the KL gives
with the Fisher information. The KL to the sampling policy grows quadratically in the lag, so the last mini-batch of a step sees roughly times the drift of the last mini-batch of a step. When enough tokens leave , 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.
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 (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 step contribute almost no gradient. Real LLM runs move far less per step (learning rates around ), 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이다. , rollout당 갱신 한 번이다. docs/advance/v1_async_trainer.md의 V1 async trainer 벤치마크는 train_batch_size=64, ppo_mini_batch_size=16, 즉 다. 둘 다 흔한 선택이고, 둘을 가르는 것이 다음 절의 내용이다.
rollout당 여러 번 갱신하면 step 안에서 데이터가 낡는다
rollout은 step 시작 시점의 매개변수 로 한 번 샘플된다. verl은 갱신 루프 전에 배치 전체의 old_log_prob을 한 번 계산하므로(_step_once의 4단계), 모든 mini-batch가 ratio에서 같은 를 쓴다. mini-batch 는 optimizer step 번 뒤의 에서 학습된다.
이면 ratio는 정확히 1이고(trainer와 sampler가 수치적으로 같다면. 실제로는 조금 다르다. 학습–추론 불일치 참고), clip은 작동하지 않으며 PPO 기울기는 평범한 정책 경사 가 된다. 그 뒤의 mini-batch는 모두 번의 갱신만큼 off-policy다. 지연의 평균은 , 최대는 이다. 이면 샘플 하나를 번 재사용하기도 한다.
drift는 얼마나 빨리 커질까. optimizer step마다 매개변수가 거의 같은 크기 만큼 움직인다고 하자(Adam의 step 크기는 거의 일정하다). 그러면 이고, KL을 2차까지 전개하면
이다(는 Fisher information). 샘플링 정책과의 KL은 지연의 제곱으로 자란다. step의 마지막 mini-batch는 step의 마지막 mini-batch보다 대략 배의 drift를 본다. 밖으로 나간 토큰이 많아지면 PPO의 clip이 그 기울기를 0으로 만든다. 뒤쪽 mini-batch일수록 신호가 줄어든다. 이것이 trade-off다. rollout은 비싸므로 rollout당 갱신을 늘리면 샘플 효율이 좋아지지만, 갱신이 하나 늘 때마다 더 낡은 데이터로 학습한다. 같은 논리가 step 안이 아니라 step 사이에서 다시 나오는 것이 비동기 학습이다.
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배로, 예측한 에 가깝다(모멘트가 안정되면서 Adam의 실효 step이 조금 줄어든다). clip 비율은 지연 7과 15 사이에서 몇 %에서 거의 전부로 뛴다. 이 장난감에서는 step의 마지막 mini-batch들이 기울기를 거의 내지 못한다. 실제 LLM 학습은 step당 훨씬 적게 움직이지만(학습률 안팎), 모양 — KL은 제곱으로, clip 비율은 절벽처럼 — 은 같고, verl 지표의 actor/pg_clipfrac, actor/ppo_kl이 보여 주는 것이 이것이다.
Gradient accumulation must not change the loss
Inside one optimizer step each GPU runs 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 (all GPUs, all micro-batches), :
Rank holds micro-batches with token sets . verl’s agg_loss computes each micro-batch loss as
where 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 accumulates gradients on rank ; the data-parallel reduction then averages over the ranks:
The tempting alternative — take the mean inside each micro-batch and average the means — weights a token by , 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.
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를 번 하고 optimizer는 한 번 움직인다. 이것이 거대한 배치 하나로 한 갱신과 같으려면, pass별 손실을 더한 것이 mini-batch 손실과 정확히 같아야 한다. 기본 집계 loss_agg_mode=token-mean을 보자. mini-batch의 응답 토큰 전체(모든 GPU, 모든 micro-batch)를 , 라 하면
rank 는 토큰 집합이 인 micro-batch 을 갖는다. verl의 agg_loss는 micro-batch 손실을 이렇게 계산한다.
여기서 은 mini-batch의 전역 토큰 수다(각 rank가 루프 전에 시퀀스별 길이 global_token_num을 all-gather한다). 각 의 backward가 rank 에 기울기를 누적하고, data-parallel reduction이 개 rank에 대해 평균을 낸다.
솔깃한 대안 — micro-batch마다 평균을 내고 그 평균들을 다시 평균 — 은 토큰 하나에 의 가중치를 준다. 토큰이 적은 micro-batch의 토큰이 더 크게 반영된다. 동적 배치에서는 길이가 다른 시퀀스 때문에 micro-batch별 토큰 수가 일부러 고르지 않게 되므로, 이 편향은 가상의 문제가 아니다. 시퀀스 단위 모드(seq-mean-token-mean, seq-mean-token-sum, seq-mean-token-sum-norm)도 같은 이유로 전역 시퀀스 수로 나눈다. 이 모드들이 길이 편향에 무엇을 하는지는 sequence vs token에서 다룬다.
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 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 therefore gives passes whose memory varies with whatever lengths happened to land together, and 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 = ppo_max_token_len_per_gpu (default 16384). The algorithm in rearrange_micro_batches is short enough to state completely:
- Start with micro-batches (a lower bound, since sequences are indivisible).
- Synchronise 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 up to a multiple of their count.
- Partition the sequences into groups balancing an attention-aware workload (Karmarkar–Karp differencing).
- If some group exceeds tokens, set and repartition.
- Order the groups so the lighter ones sit at both ends (smaller pipeline warm-up and cool-down bubbles).
The hard constraint is 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 max_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 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은 짜리 attention score를 만들지 않으므로 Korthikanti 등의 층당 activation 식이 토큰 수에 선형이 되고, logit은 토큰 수 × 어휘 크기만큼 더해진다. 그래서 고정 를 쓰면 어떤 길이들이 함께 묶였는지에 따라 pass마다 메모리가 달라지고, 를 최악의 경우에 맞춰야 한다. 이를 고치는 장치가 둘이다.
Packing(actor_rollout_ref.model.use_remove_padding=True, 기본값 켜짐)은 micro-batch의 시퀀스들을 한 줄로 이어 붙이고, 누적 시퀀스 길이를 가변 길이 attention kernel에 넘긴다. padding은 아예 계산하지 않는다.
동적 배치 크기(use_dynamic_bsz=True, 현재 ppo_trainer.yaml에서 역시 기본값 켜짐)는 토큰 예산 = ppo_max_token_len_per_gpu(기본 16384)로 micro-batch를 만든다. rearrange_micro_batches의 알고리즘은 짧아서 전부 적을 수 있다.
- 개의 micro-batch로 시작한다(시퀀스는 쪼갤 수 없으니 하한이다).
- data-parallel rank 사이에서 all-reduce MAX로 를 맞춘다. 모든 rank가 같은 횟수의 forward/backward를 해야 하기 때문이다(FSDP와 Megatron의 collective가 pass마다 일어난다). virtual pipeline stage가 있으면 를 그 수의 배수로 올린다.
- attention을 고려한 작업량 의 균형을 맞추도록 시퀀스를 개 그룹으로 나눈다(Karmarkar–Karp differencing).
- 어느 그룹이 토큰을 넘으면 로 다시 나눈다.
- 가벼운 그룹을 양 끝에 오도록 순서를 정한다(pipeline warm-up·cool-down bubble이 작아진다).
절대 조건은 가장 긴 시퀀스(프롬프트 + 응답, 멀티턴이면 trajectory 전체)이고, Ulysses sequence parallel을 쓰면 그 크기를 곱한다. 코드가 assert한다. 설정 파일 주석은 max_prompt_length + max_response_length를, 튜닝 가이드는 “적어도 2 × (max_prompt_length + max_response_length)“를 권한다. 하한 위에서는 가 클수록 pass가 더 적고 커져 kernel 효율이 좋아지며, 메모리가 허락하는 데까지 키우면 된다. 이와 별개로 앞 단계의 균형기(trainer.balance_batch=True)가 배치 전체를 재배열해 data-parallel rank마다 총 토큰 수가 비슷해지게 한다.
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 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.
| quantity | verl | TRL GRPOTrainer | slime | OpenRLHF |
|---|---|---|---|---|
| prompts per rollout | data.train_batch_size | see note | --rollout-batch-size | --rollout.batch_size |
| samples per prompt | rollout.n | num_generations | --n-samples-per-prompt | --rollout.n_samples_per_prompt |
| per optimizer step | ppo_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 rollout | ppo_epochs | num_iterations | --num-steps-per-rollout (steps, not epochs) | --train.max_epochs |
| per-GPU pass | ppo_micro_batch_size_per_gpu / ppo_max_token_len_per_gpu | per_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, 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 directly (it is , 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 cost like verl’s.
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))행을 짝지어 읽자. 고정 와 동적 예산 16384는 pass당 최대 토큰(≈ 최대 메모리)이 거의 같지만, 고정 쪽은 크기가 2.4배까지 들쭉날쭉한 pass 16번, 동적 쪽은 거의 같은 크기의 pass 10번이다. 마지막 열이 함정이다. packing이 없으면, 긴 시퀀스 하나와 짧은 시퀀스 여럿을 섞는 균형기의 습성 때문에 padding이 고정 배치보다 더 나빠진다. 동적 배치는 packing을 위한 기능이다.
다른 프레임워크에서 같은 해부도
시스템으로서의 비교는 landscape 레슨에서 했다. 여기서는 배치 용어만 맞춰 본다.
| 양 | verl | TRL GRPOTrainer | slime | OpenRLHF |
|---|---|---|---|---|
| rollout당 프롬프트 | data.train_batch_size | 아래 설명 | --rollout-batch-size | --rollout.batch_size |
| 프롬프트당 샘플 | rollout.n | num_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_epochs | num_iterations | --num-steps-per-rollout(epoch가 아니라 step 수) | --train.max_epochs |
| GPU당 pass | ppo_micro_batch_size_per_gpu / ppo_max_token_len_per_gpu | per_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라 하면 기본값에서 이다. 문서는 steps_per_generation > gradient_accumulation_steps이거나 num_iterations > 1이면 off-policy가 된다고 적어 두었다. slime의 --num-steps-per-rollout은 를 직접 정하고(epoch 수가 아니라 다), 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처럼 비용에 Karmarkar–Karp 분할을 쓴다.
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 reductions and does not change the result.)
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?
optimizer steps. Each mini-batch holds trajectories, i.e. per GPU, which with is accumulated passes. The last update trains on data 7 updates old (mean lag 3.5), and every trajectory is used twice.
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 = trajectories; it becomes optimizer steps, each split into trajectories per GPU and accumulated passes. In verl
ppo_mini_batch_sizecounts prompts and is multiplied byrollout.ninternally. - Mini-batch is trained at against ; only the first update is on-policy, and the KL to the sampler grows roughly as , 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 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.
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을 번 아끼고 결과는 같다.)
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를 몇 번 하나?
번이다. mini-batch 하나에 trajectory 개, GPU당 개이고, 이면 누적 pass 번이다. 마지막 갱신은 7번 갱신만큼 낡은 데이터로 학습하고(평균 지연 3.5), 모든 trajectory가 두 번씩 쓰인다.
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 개이고, 이것이 optimizer step 번이 되며, 각 step은 GPU당 개, 누적 pass 번으로 쪼개진다. verl의
ppo_mini_batch_size는 프롬프트 수이고 내부에서rollout.n이 곱해진다. - mini-batch 는 에서 에 대해 학습된다. 첫 갱신만 on-policy이고, sampler와의 KL은 대략 로 자라다가 clip이 뒤쪽 mini-batch를 침묵시킨다.
- token-mean이 micro-batch와 data parallel 아래에서 유지되려면 모든 pass가 전역 토큰 수로 나눠야 한다(rank 평균을 낸다면 를 곱한다). micro-batch 평균의 평균은 편향된다.
- 메모리는 pass당 토큰 수를 따른다. packing은 padding을 없애고, 동적 배치(
use_dynamic_bsz,ppo_max_token_len_per_gpu)는 토큰 예산으로 묶되 micro-batch 수를 균형 있게, DP 사이에 맞춰 정한다. 예산은 가장 긴 시퀀스보다 커야 한다. - 성능 손잡이는 학습 곡선을 바꾸면 안 된다. 바뀐다면 먼저 손실 정규화를 보라.
더 읽을거리Further reading
- verl docs — Performance tuning guide (batch size tuning, dynamic batch size) — '알고리즘 크기는 전역, 성능 크기는 GPU당'이라는 원칙과 동적 배치 튜닝 팁의 출처.Source of the "algorithmic sizes are global, performance sizes are per GPU" rule and of the dynamic-batching tuning tips.
- verl source @ 4525109 (2026-12-02) — verl/workers/engine_workers.py (train_mini_batch), verl/utils/seqlen_balancing.py (rearrange_micro_batches) — mini-batch를 DP로 나누는 코드와 토큰 예산 micro-batch 분할 알고리즘. 이 레슨의 수식은 이 커밋 기준이다.The code that divides a mini-batch over DP ranks and the token-budget micro-batch splitter. The formulas in this lesson are checked against this commit.
- verl source @ 4525109 — verl/trainer/ppo/core_algos.py (agg_loss) — token-mean·seq-mean 집계가 전역 토큰 수와 dp_size로 정규화되는 방식.How token-mean and seq-mean aggregation are normalised by the global token count and dp_size.
- Schulman et al., Proximal Policy Optimization Algorithms (2017) — 같은 배치로 여러 epoch·mini-batch를 도는 PPO 루프의 원형.The original PPO loop that runs several epochs of mini-batches over one batch.
- Krell et al., Efficient Sequence Packing without Cross-contamination (2021) — 가변 길이 시퀀스를 padding 없이 묶는 packing의 분석.An analysis of packing variable-length sequences without padding.
- Korthikanti et al., Reducing Activation Recomputation in Large Transformer Models (2022) — 층당 activation 메모리 식. 토큰 수가 메모리를 정한다는 근거.The per-layer activation-memory formula — why the token count sets memory.