verl is the open-source implementation of HybridFlow (EuroSys 2025), started by ByteDance Seed and now maintained under the verl-project organisation. It changed more in 2026 than in its first year, so this lesson is pinned: main at commit 4525109 (2026-12-02, version 0.10.0.dev), latest release v0.9.1 (2026-09-20). The single most important fact for anyone with older notes: per the README news of November 2026, “Mainline PPO training now uses V1 exclusively; the V0 trainer has been removed. Fully async and one-step-off trainers have moved to verl-recipe, pinned to verl v0.9.1.” Knobs such as async_training.trigger_parameter_sync_step and staleness_threshold therefore belong to the recipe on v0.9.1; mainline asynchrony is configured under trainer.v1.*. Both are covered below.
Architecture: a single controller over SPMD worker groups
HybridFlow’s programming model has two levels. The controller is one Python process (the Ray driver running PPOTrainer) that writes the RL dataflow as ordinary sequential code: generate, compute rewards, compute log-probs, compute advantages, update. Each call goes to a WorkerGroup — a set of Ray actors on a ResourcePool of GPUs that run the call SPMD-style (multi-controller inside: FSDP, Megatron, an inference engine). The @register(dispatch_mode=...) decorator on a worker method says how the controller’s batch is split across ranks and how results are gathered. The design doc gives the motivation: plain SPMD launchers make it hard to express several models’ DAGs and to inspect intermediate tensors, while one RPC per method on one actor cannot drive a multi-process model.
The V1 trainer adds a data plane: batches live in TransferQueue (transfer_queue@transfer_queue in the config), and the controller passes KVBatchMeta — keys, tags and a partition id — rather than tensors. Agent-loop outputs are written there per trajectory with tags (status, seq_len, the global step at which the prompt was submitted, and the min/max weight versions that generated it), which is what the async modes’ replay buffer reads to sample, drop and refill.
Roles and engines in the current config:
- actor / ref / critic run on a model engine chosen by
model_engine(dp= FSDP/FSDP2,megatron,veomni,torchtitan); the same worker class also hosts the rollout in the hybrid engine. - rollout runs as LLM server replicas (
actor_rollout_ref.rollout.name=vllm,sglang,trtllm, alsovllm_pdfor prefill/decode disaggregation), always in server mode (rollout.mode: async). Each replica spanstensor_model_parallel_size × data_parallel_size × pipeline_model_parallel_sizeGPUs, so replicas = ⌊rollout GPUs / that product⌋:LLMServerManagerfloors the division and does not check the remainder, so leftover GPUs simply sit idle. - AgentLoop workers (
rollout.agent.num_workers, default 8) run user agent loops as asyncio coroutines and talk to the replicas through anLLMServerClientthat picks the least-loaded replica on a trajectory’s first turn and keeps later turns on the same replica (sticky sessions, so the prefix KV cache is reused). - reward loop computes rule or model rewards, as a separate pool or colocated.
The hybrid engine and weight sync
In the default colocated setup the actor and the rollout replicas share GPUs. Between phases the replicas sleep (free_cache_engine: True drops the KV cache; weights are released) and wake up for generation, and checkpoint_manager.update_weights reshards the trained weights from the training layout (FSDP shards or Megatron TP/PP/EP) into the serving layout (vLLM/SGLang TP). The rollout engine’s share of memory is rollout.gpu_memory_utilization (default 0.5). When rollout runs on separate GPUs, weights travel through a checkpoint engine (rollout.checkpoint_engine.backend: naive by default, nccl, nixl, mooncake, and since v0.9.0 delta_sharded, which sends only the bytes that changed and reported 1.9–3.1× faster steady-state updates for 7B–72B models in the release notes).
The AgentLoop
An agent loop subclasses AgentLoopBase and implements one coroutine, run(sampling_params, **kwargs) -> AgentLoopOutput, returning prompt_ids, response_ids and a response_mask (1 for model tokens, 0 for tool tokens — the mask of the agent RL lesson). verl’s docs explain why the interface is token-in-token-out rather than chat messages: re-applying the chat template to the final message list does not reproduce the generated token ids (tool parsers rewrite content; decode–encode is not invertible), and training on the re-tokenised sequence “make[s] PPO training not even converged in single-turn”. Built-ins are single_turn_agent (rollout.agent.default_agent_loop) and a tool agent loop driven by rollout.multi_turn.*; v0.9.0 added the uni-agent gateway for bringing external harnesses that speak an OpenAI/Anthropic-compatible API.
verl은 HybridFlow(EuroSys 2025)의 오픈소스 구현으로, ByteDance Seed가 시작했고 지금은 verl-project 조직 아래에서 관리된다. 첫해보다 2026년에 더 많이 바뀌었으니 이 레슨은 기준을 박아 둔다. main 커밋 4525109(2026-12-02, 버전 0.10.0.dev), 최신 릴리스 v0.9.1(2026-09-20). 예전 노트를 가진 사람에게 가장 중요한 사실은 2026년 11월 README 공지다. “Mainline PPO 학습은 이제 V1만 쓴다. V0 trainer는 제거됐다. fully async와 one-step-off trainer는 verl v0.9.1에 고정된 verl-recipe로 옮겼다.” 그러니 async_training.trigger_parameter_sync_step이나 staleness_threshold 같은 손잡이는 v0.9.1 위의 recipe에 속하고, mainline의 비동기는 trainer.v1.* 아래에서 설정한다. 아래에서 둘 다 다룬다.
구조: SPMD worker group 위의 single controller
HybridFlow의 프로그래밍 모델은 두 층이다. controller는 Python 프로세스 하나(PPOTrainer를 돌리는 Ray driver)이고, RL 데이터 흐름을 평범한 순차 코드로 쓴다. 생성, 보상 계산, log-prob 계산, advantage 계산, 갱신. 호출 하나하나는 WorkerGroup으로 간다. GPU의 ResourcePool 위에 놓인 Ray actor 묶음이고, 호출을 SPMD 방식으로 실행한다(안쪽은 FSDP, Megatron, 추론 엔진 같은 multi-controller다). worker 메서드의 @register(dispatch_mode=...) decorator가 controller의 배치를 rank에 어떻게 나누고 결과를 어떻게 모을지 정한다. 설계 문서가 동기를 적어 두었다. 평범한 SPMD launcher로는 여러 모델의 DAG를 표현하기도 중간 tensor를 들여다보기도 어렵고, actor 하나에 메서드당 RPC 하나로는 다중 프로세스 모델을 움직일 수 없다.
V1 trainer는 데이터 평면을 더했다. 배치는 TransferQueue(설정의 transfer_queue@transfer_queue)에 살고, controller는 tensor가 아니라 KVBatchMeta — key, tag, partition id — 를 넘긴다. agent loop 출력은 trajectory마다 tag와 함께 거기에 기록되며(status, seq_len, 프롬프트가 제출된 global step, 그것을 생성한 가중치 버전의 최소·최대), 비동기 모드의 replay buffer가 sample·drop·refill에 읽는 것이 이것이다.
현재 설정의 역할과 엔진:
- actor / ref / critic은
model_engine으로 고른 model engine 위에서 돈다(dp= FSDP/FSDP2,megatron,veomni,torchtitan). hybrid engine에서는 같은 worker 클래스가 rollout도 맡는다. - rollout은 LLM server replica로 돈다(
actor_rollout_ref.rollout.name=vllm,sglang,trtllm, prefill/decode 분리용vllm_pd). 늘 server 모드(rollout.mode: async)다. replica 하나는tensor_model_parallel_size × data_parallel_size × pipeline_model_parallel_size개 GPU에 걸치므로 replica 수 = ⌊rollout GPU 수 / 그 곱⌋이다.LLMServerManager는 나눗셈을 내림하고 나머지를 검사하지 않으므로, 남는 GPU는 그냥 논다. - AgentLoop worker(
rollout.agent.num_workers, 기본 8)는 사용자 agent loop를 asyncio coroutine으로 돌리고,LLMServerClient를 통해 replica와 대화한다. trajectory의 첫 turn은 요청이 가장 적은 replica로 보내고 이후 turn은 같은 replica에 붙인다(sticky session. prefix KV cache를 재사용한다). - reward loop는 규칙 보상이나 모델 보상을 별도 pool이나 colocated로 계산한다.
hybrid engine과 가중치 동기화
기본 colocated 구성에서는 actor와 rollout replica가 GPU를 공유한다. 단계 사이에 replica가 sleep하고(free_cache_engine: True가 KV cache를 버리고 가중치를 내린다) 생성 때 wake up하며, checkpoint_manager.update_weights가 학습된 가중치를 학습 배치(FSDP shard 또는 Megatron TP/PP/EP)에서 서빙 배치(vLLM/SGLang TP)로 다시 나눠 넣는다. rollout 엔진의 메모리 몫은 rollout.gpu_memory_utilization(기본 0.5)이다. rollout이 별도 GPU에서 돌면 가중치는 checkpoint engine으로 간다(rollout.checkpoint_engine.backend: 기본 naive, nccl, nixl, mooncake, 그리고 v0.9.0부터 delta_sharded. 바뀐 바이트만 보내며, 릴리스 노트는 7B–72B 모델에서 정상 상태 갱신이 1.9–3.1배 빨라졌다고 보고한다).
AgentLoop
agent loop는 AgentLoopBase를 상속해 coroutine 하나, run(sampling_params, **kwargs) -> AgentLoopOutput을 구현하고, prompt_ids, response_ids, response_mask(모델 토큰 1, tool 토큰 0 — agent RL 레슨의 그 mask)를 돌려준다. verl 문서는 인터페이스가 chat 메시지가 아니라 token-in-token-out인 이유를 설명한다. 최종 메시지 목록에 chat template을 다시 적용하면 생성된 토큰 id가 재현되지 않고(tool parser가 내용을 고치고, decode–encode가 역함수가 아니다), 다시 토큰화한 시퀀스로 학습하면 “single-turn에서조차 PPO 학습이 수렴하지 않았다”. 기본 제공은 single_turn_agent(rollout.agent.default_agent_loop)와 rollout.multi_turn.*로 움직이는 tool agent loop이고, v0.9.0은 OpenAI/Anthropic 호환 API를 말하는 외부 harness를 들여오는 uni-agent gateway를 더했다.
verl/trainer/ppo/v1/ that runs it. The controller is one Python process that calls worker groups; data travels through TransferQueue, so the controller handles only metadata. Switch the mode to see what changes: in colocate_async unfinished trajectories are aborted, kept and resumed; in separate_async the standalone rollout pool never stops and the trainer works mini-batch by mini-batch. verl V1 PPO trainer의 global step 하나를 단계별로 따라간다. 강조된 상자가 현재 단계에서 일하는 구성 요소이고, 글은 그 단계를 실행하는 verl/trainer/ppo/v1/의 메서드 이름을 댄다. controller는 worker group을 호출하는 Python 프로세스 하나이고, 데이터는 TransferQueue로 다니므로 controller는 메타데이터만 다룬다. 모드를 바꿔 무엇이 달라지는지 보자. colocate_async에서는 끝나지 않은 trajectory를 중단했다가 보관하고 이어 가며, separate_async에서는 standalone rollout pool이 멈추지 않고 trainer가 mini-batch 단위로 일한다. The knobs that define a run
Names below are the full Hydra paths in verl/trainer/config/ppo_trainer.yaml and its defaults (actor/actor.yaml, rollout/rollout.yaml, data/legacy_data.yaml) at the pinned commit.
| setting | default | meaning |
|---|---|---|
data.train_batch_size | 1024 | prompts per global step () |
data.gen_batch_size | null (= train_batch_size) | prompts fetched per dataloader call; async warmup/refill are submitted in whole chunks of it |
actor_rollout_ref.rollout.n | 1 | samples per prompt; each sample is one agent-loop coroutine |
actor_rollout_ref.actor.ppo_mini_batch_size | 256 | prompts per optimizer step (multiplied by n internally, then divided by DP) |
actor_rollout_ref.actor.ppo_epochs | 1 | passes over each batch |
actor_rollout_ref.actor.use_dynamic_bsz | true | token-budget micro-batches |
actor_rollout_ref.actor.ppo_max_token_len_per_gpu | 16384 | token budget per micro-batch per GPU; must exceed the longest sequence |
actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu | null | fixed micro-batch size, used only when dynamic batching is off |
actor_rollout_ref.actor.loss_agg_mode | token-mean | also token-sum, seq-mean-token-sum, seq-mean-token-mean, seq-mean-token-sum-norm |
actor_rollout_ref.rollout.tensor_model_parallel_size | 2 | GPUs per replica (with data_parallel_size, pipeline_model_parallel_size) |
actor_rollout_ref.rollout.gpu_memory_utilization | 0.5 | engine memory fraction; standalone_gpu_memory_utilization overrides it on dedicated rollout GPUs |
actor_rollout_ref.rollout.max_num_seqs | 256 | sequences an engine replica decodes at once; the rest queue |
actor_rollout_ref.rollout.over_sample_rate | 0 | abort the remaining requests once (1 − rate) of them have completed |
actor_rollout_ref.rollout.agent.num_workers | 8 | AgentLoop worker actors |
trainer.v1.trainer_mode | sync | sync, colocate_async, separate_async |
trainer.v1.colocate_async.num_warmup_batches, …separate_async.num_warmup_batches | 1 | extra train batches of prompts submitted before step 1 (fractions allowed) |
trainer.v1.separate_async.parameter_sync_step | 4 | mini-batch updates between weight pushes; must equal train_batch_size / ppo_mini_batch_size |
trainer.v1.sampler.max_off_policy_threshold | 8 | max model versions between a prompt’s submission and its training; null disables |
trainer.v1.sampler.max_off_policy_strategy | drop | drop evicts and refills stale groups; wait blocks until in-flight ones finish |
trainer.v1.separate_async.hybrid_rollout.enable_switch | false | lend the trainer GPUs to rollout while the trainer waits |
The batch arithmetic ( optimizer steps, trajectories per GPU, token-budget micro-batches) is derived in the step-anatomy lesson; the parallel layout of the actor engine in training parallelism.
The three V1 modes
All three run the same loop (_step_once: sample → reward → balance → old log-prob → ref → values → advantage → critic → actor) and process train_batch_size / ppo_mini_batch_size mini-batches per global step. They differ in where generation runs and when it stops.
sync— hybrid replicas on the trainer GPUs; each step submits prompts, waits until every group has finished, puts the replicas to sleep, trains, and syncs weights. Strictly on-policy (up to engine numerics).colocate_async— same GPUs, plusnum_warmup_batchesof prompts submitted ahead. A step samples as soon as finished groups exist; in-flight requests are aborted but kept (tokens and log-probs retained) and resumed after the weight update, with the KV cache rebuilt from the kept prefix. A trajectory can span several versions.separate_async— standalone rollout replicas on their own GPUs (actor_rollout_ref.rollout.nnodes,n_gpus_per_node) generate continuously; the trainer samples one mini-batch at a time and pushes weights everyparameter_sync_stepmini-batches, which is why verl assertstrain_batch_size == parameter_sync_step × ppo_mini_batch_sizeand requires a non-naivecheckpoint engine. Withenable_switch=True, hybrid replicas are also created on the trainer GPUs and join rollout while the trainer waits for samples.
Staleness is measured in model versions. A group is evicted (and replaced by exactly one fresh prompt) when its age exceeds max_off_policy_threshold under drop; under wait, sampling blocks while an in-flight group is at the threshold. The metrics training/off_policy/trajectory_spans/* (versions used within one trajectory) and trajectory_staleness/* show what actually happened. If you recompute old log-probs in separate_async (decoupled PPO), must stay fixed across the parameter_sync_step mini-batches although the trainer’s weights change after each: the docs count save_model_to_cpu and restore_model_from_cpu calls for mini-batches, all skipped with algorithm.rollout_correction.bypass_mode=True (use the rollout’s log-probs as ; the corrections themselves are the topic of the next lesson).
The V1 benchmark in the docs (Qwen3.5-35B-A3B, Megatron TP2 PP2 CP2 EP4, vLLM TP4, train_batch_size=64, ppo_mini_batch_size=16, parameter_sync_step=4, DAPO-Math-17k, responses up to 32,768 tokens, four nodes):
| mode | resources | 150-step time | tokens/s |
|---|---|---|---|
sync | 4 hybrid nodes | 22.79 h | 12,053 |
colocate_async | 4 hybrid nodes | 14.72 h (−35.4%) | 18,852 |
separate_async | 2 hybrid + 2 standalone | 14.10 h (−38.1%) | 18,829 |
A separate 100-step run on 3 × 8 H100 (2 trainer + 1 rollout node) measured step switching at 13.15 h → 11.79 h.
The fully-async recipe and how its knobs map to V1
The recipe verl-recipe/fully_async_policy (by the meituan-search team; pinned to v0.9.1 and its V0 trainer) is what most existing fully-async launch scripts use. Its Rollouter generates sample by sample into a MessageQueue; the Trainer fetches require_batches × ppo_mini_batch_size samples per local update and triggers a parameter sync every trigger_parameter_sync_step local updates. Its knobs (from the recipe’s config/fully_async_ppo_trainer.yaml):
| recipe (v0.9.1) | default | V1 counterpart |
|---|---|---|
async_training.require_batches | 1 | none — V1 trains one mini-batch per _step_once |
async_training.trigger_parameter_sync_step | 4 | trainer.v1.separate_async.parameter_sync_step |
async_training.staleness_threshold | 0.1 | trainer.v1.sampler.max_off_policy_threshold (different unit: versions, not a sample fraction) |
async_training.partial_rollout | True | always on in V1 async modes |
async_training.concurrent_samples_per_replica | 16 | none — V1 launches all submitted groups; the engine’s max_num_seqs queues them |
async_training.use_dynamic_resource_scheduling | False | trainer.v1.separate_async.hybrid_rollout.enable_switch |
data.train_batch_size=0, data.gen_batch_size=1, rollout.total_rollout_steps | — | V1 keeps train_batch_size and gen_batch_size meaningful |
In the recipe, staleness_threshold caps how many samples the Rollouter may produce per sync window: at most minus the stale samples left over, and is a synchronous stream. Its concurrency cap is max_concurrent_samples = min(replicas × concurrent_samples_per_replica, max_required_samples), and each sample runs rollout.n agent loops. The recipe README lists four modes: on-policy pipeline (trigger 1, η 0), stream off-policy (trigger > 1, η 0), async with stale samples (η > 0, partial off), and async with partial rollout (η > 0, partial on); its 128-GPU Qwen2.5-Math-7B experiments report about 1.6× from streaming alone and 2.35× with staleness and partial rollout.
→ Go deeper: the IS and rejection options that pair with these async modes, equation by equation, in verl rollout correction; verl’s choices set side by side with other asynchronous systems in asynchronous RL systems compared.
실행을 정하는 손잡이
아래 이름은 고정한 커밋의 verl/trainer/config/ppo_trainer.yaml과 그 기본 설정(actor/actor.yaml, rollout/rollout.yaml, data/legacy_data.yaml)의 Hydra 전체 경로와 기본값이다.
| 설정 | 기본값 | 의미 |
|---|---|---|
data.train_batch_size | 1024 | global step당 프롬프트() |
data.gen_batch_size | null (= train_batch_size) | dataloader 호출당 가져오는 프롬프트. 비동기 warmup/refill은 이것의 온전한 묶음 단위로 제출된다 |
actor_rollout_ref.rollout.n | 1 | 프롬프트당 샘플. 샘플 하나가 agent-loop coroutine 하나 |
actor_rollout_ref.actor.ppo_mini_batch_size | 256 | optimizer step당 프롬프트(내부에서 n을 곱하고 DP로 나눈다) |
actor_rollout_ref.actor.ppo_epochs | 1 | 배치마다 도는 횟수 |
actor_rollout_ref.actor.use_dynamic_bsz | true | 토큰 예산 micro-batch |
actor_rollout_ref.actor.ppo_max_token_len_per_gpu | 16384 | GPU당 micro-batch 토큰 예산. 가장 긴 시퀀스보다 커야 한다 |
actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu | null | 고정 micro-batch 크기. 동적 배치가 꺼졌을 때만 쓴다 |
actor_rollout_ref.actor.loss_agg_mode | token-mean | token-sum, seq-mean-token-sum, seq-mean-token-mean, seq-mean-token-sum-norm도 있다 |
actor_rollout_ref.rollout.tensor_model_parallel_size | 2 | replica당 GPU(data_parallel_size, pipeline_model_parallel_size와 함께) |
actor_rollout_ref.rollout.gpu_memory_utilization | 0.5 | 엔진 메모리 비율. 전용 rollout GPU에서는 standalone_gpu_memory_utilization이 덮어쓴다 |
actor_rollout_ref.rollout.max_num_seqs | 256 | 엔진 replica가 동시에 decode하는 시퀀스. 나머지는 queue에서 기다린다 |
actor_rollout_ref.rollout.over_sample_rate | 0 | 요청의 (1 − rate)가 끝나면 남은 요청을 중단한다 |
actor_rollout_ref.rollout.agent.num_workers | 8 | AgentLoop worker actor 수 |
trainer.v1.trainer_mode | sync | sync, colocate_async, separate_async |
trainer.v1.colocate_async.num_warmup_batches, …separate_async.num_warmup_batches | 1 | step 1 전에 미리 제출하는 train batch 분량의 프롬프트(분수 가능) |
trainer.v1.separate_async.parameter_sync_step | 4 | 가중치를 밀어 넣는 사이의 mini-batch 갱신 수. train_batch_size / ppo_mini_batch_size와 같아야 한다 |
trainer.v1.sampler.max_off_policy_threshold | 8 | 프롬프트 제출부터 학습까지 허용하는 최대 모델 버전 수. null이면 끈다 |
trainer.v1.sampler.max_off_policy_strategy | drop | drop은 낡은 그룹을 버리고 다시 채우고, wait은 진행 중인 그룹이 끝날 때까지 막는다 |
trainer.v1.separate_async.hybrid_rollout.enable_switch | false | trainer가 기다리는 동안 trainer GPU를 rollout에 빌려준다 |
배치 산수( optimizer step, GPU당 trajectory , 토큰 예산 micro-batch)는 step 해부 레슨에서, actor engine의 병렬 배치는 학습 병렬화에서 유도했다.
V1의 세 모드
셋 다 같은 루프(_step_once: sample → 보상 → balance → old log-prob → ref → value → advantage → critic → actor)를 돌고, global step마다 mini-batch train_batch_size / ppo_mini_batch_size개를 처리한다. 다른 점은 생성이 어디서 돌고 언제 멈추는지다.
sync— trainer GPU 위의 hybrid replica. step마다 프롬프트 개를 제출하고, 모든 그룹이 끝날 때까지 기다린 뒤 replica를 재우고, 학습하고, 가중치를 동기화한다. 엄밀한 on-policy다(엔진 수치 차이를 빼면).colocate_async— 같은 GPU에num_warmup_batches만큼의 프롬프트를 미리 제출한다. 끝난 그룹이 개 생기는 즉시 sample하고, 진행 중인 요청은 중단하되 보관한다(토큰과 log-prob 유지). 가중치 갱신 뒤 이어 가며, KV cache는 보관한 prefix에서 다시 만든다. trajectory 하나가 여러 버전에 걸칠 수 있다.separate_async— 전용 GPU(actor_rollout_ref.rollout.nnodes,n_gpus_per_node)의 standalone rollout replica가 쉬지 않고 생성한다. trainer는 mini-batch 하나씩 sample하고parameter_sync_step개 mini-batch마다 가중치를 밀어 넣는다. 그래서 verl은train_batch_size == parameter_sync_step × ppo_mini_batch_size를 assert하고naive가 아닌 checkpoint engine을 요구한다.enable_switch=True면 trainer GPU에도 hybrid replica를 만들어 trainer가 샘플을 기다리는 동안 rollout에 합류시킨다.
staleness는 모델 버전 단위로 잰다. drop에서는 그룹의 나이 이 max_off_policy_threshold를 넘으면 그 그룹을 내보내고(정확히 새 프롬프트 하나로 대체), wait에서는 진행 중인 그룹이 한도에 닿으면 sampling을 막는다. 실제로 무슨 일이 있었는지는 training/off_policy/trajectory_spans/*(trajectory 하나에 쓰인 버전 수)와 trajectory_staleness/* 지표가 보여 준다. separate_async에서 old log-prob을 다시 계산하면(decoupled PPO), trainer 가중치가 mini-batch마다 바뀌어도 는 parameter_sync_step개 mini-batch 동안 고정돼야 한다. 문서는 mini-batch 개에 save_model_to_cpu 번과 restore_model_from_cpu 번을 센다. algorithm.rollout_correction.bypass_mode=True(rollout의 log-prob을 로 씀)면 모두 생략된다. 보정 자체는 다음 레슨의 주제다.
문서의 V1 벤치마크(Qwen3.5-35B-A3B, Megatron TP2 PP2 CP2 EP4, vLLM TP4, train_batch_size=64, ppo_mini_batch_size=16, parameter_sync_step=4, DAPO-Math-17k, 응답 최대 32,768 토큰, 노드 4개):
| 모드 | 자원 | 150 step 시간 | 토큰/초 |
|---|---|---|---|
sync | hybrid 노드 4 | 22.79 h | 12,053 |
colocate_async | hybrid 노드 4 | 14.72 h (−35.4%) | 18,852 |
separate_async | hybrid 2 + standalone 2 | 14.10 h (−38.1%) | 18,829 |
H100 3 × 8장(trainer 2 + rollout 1 노드)에서 따로 잰 100 step 실험에서는 step switching이 13.15 h → 11.79 h였다.
fully-async recipe와 V1 손잡이 짝짓기
verl-recipe/fully_async_policy recipe(meituan-search 팀 작성. v0.9.1과 그 V0 trainer에 고정)는 기존 fully-async 실행 스크립트 대부분이 쓰는 것이다. Rollouter가 샘플 단위로 MessageQueue에 생성해 넣고, Trainer는 local update마다 require_batches × ppo_mini_batch_size개 샘플을 가져오며, local update trigger_parameter_sync_step번마다 매개변수 동기화를 일으킨다. 손잡이(recipe의 config/fully_async_ppo_trainer.yaml 기준):
| recipe (v0.9.1) | 기본값 | V1 대응 |
|---|---|---|
async_training.require_batches | 1 | 없음 — V1은 _step_once마다 mini-batch 하나를 학습한다 |
async_training.trigger_parameter_sync_step | 4 | trainer.v1.separate_async.parameter_sync_step |
async_training.staleness_threshold | 0.1 | trainer.v1.sampler.max_off_policy_threshold (단위가 다르다: 샘플 비율이 아니라 버전) |
async_training.partial_rollout | True | V1 비동기 모드에서는 항상 켜짐 |
async_training.concurrent_samples_per_replica | 16 | 없음 — V1은 제출된 그룹을 모두 띄우고, 엔진의 max_num_seqs가 queue에 줄 세운다 |
async_training.use_dynamic_resource_scheduling | False | trainer.v1.separate_async.hybrid_rollout.enable_switch |
data.train_batch_size=0, data.gen_batch_size=1, rollout.total_rollout_steps | — | V1은 train_batch_size와 gen_batch_size가 의미를 유지한다 |
recipe에서 staleness_threshold는 동기화 구간당 Rollouter가 만들 수 있는 샘플 수를 묶는다. 최대 에서 지난 구간에 남은 낡은 샘플을 뺀 수이고, 이면 동기 stream이다. 동시성 상한은 max_concurrent_samples = min(replica 수 × concurrent_samples_per_replica, max_required_samples)이고, 샘플 하나가 rollout.n개의 agent loop를 돌린다. recipe README는 네 모드를 든다. on-policy pipeline(trigger 1, η 0), stream off-policy(trigger > 1, η 0), 낡은 샘플을 쓰는 async(η > 0, partial 끔), partial rollout을 쓰는 async(η > 0, partial 켬). GPU 128장 Qwen2.5-Math-7B 실험에서 streaming만으로 약 1.6배, staleness와 partial rollout까지 더해 2.35배를 보고한다.
→ 더 깊이: 이 비동기 모드와 짝을 이루는 IS·rejection 옵션의 수식은 verl rollout correction, verl의 선택을 다른 비동기 시스템들과 나란히 놓고 보려면 비동기 RL 시스템 비교.
How many agent loops run at once?
For agent RL the number of trajectories alive at the same time decides more than throughput: each one may hold a sandbox, a browser or a container, and each is a request competing for KV cache on some replica. Reading the V1 code gives exact rules. _submit_batch_to_rollout registers prompts in TransferQueue and the AgentLoop worker starts, for every prompt, rollout.n agent-loop coroutines immediately (“fire-and-forget”); nothing else limits them except the engines’ own scheduling.
sync: every step submits prompts and waits for all of them, so the peak is live agent loops, all started at once, all done before training.colocate_async/separate_async: =num_warmup_batchesextra batches are submitted before step 1 and one batch per step after, while each step consumes one batch. At most prompt groups — agent loops — are submitted and not yet consumed, plus one refill per dropped group. Incolocate_asyncthe unfinished ones are paused during training but remain alive, as do their environments.- recipe
fully_async_policy: with replicas, =concurrent_samples_per_replica, =require_batches, =trigger_parameter_sync_step.
Divide by the number of replicas and compare with max_num_seqs: requests beyond it wait in the engine’s queue (and the KV cache may bind earlier). For the V1 benchmark configuration the async bound is agent loops on 4 standalone replicas, 512 per replica — above the default max_num_seqs=256, so half of them would be queued inside the engines unless that setting is raised.
→ Go deeper: Agent loops and environments — where many concurrent agent loops bottleneck: sandboxes, environment servers, KV cache.
agent loop는 동시에 몇 개 도나?
agent RL에서 동시에 살아 있는 trajectory 수는 처리량 이상을 정한다. 하나하나가 sandbox, 브라우저, 컨테이너를 붙들 수 있고, 하나하나가 어떤 replica의 KV cache를 두고 다투는 요청이다. V1 코드를 읽으면 정확한 규칙이 나온다. _submit_batch_to_rollout이 프롬프트를 TransferQueue에 등록하면 AgentLoop worker가 프롬프트마다 rollout.n개의 agent-loop coroutine을 즉시 띄운다(“fire-and-forget”). 엔진 자체의 스케줄링 말고는 이를 막는 것이 없다.
sync: step마다 프롬프트 개를 제출하고 전부를 기다리므로, 최대치는 살아 있는 agent loop 개다. 모두 한꺼번에 시작하고 학습 전에 모두 끝난다.colocate_async/separate_async: step 1 전에 =num_warmup_batches배치를 더 제출하고, 이후 step마다 한 배치를 제출하며, step마다 한 배치를 소비한다. 제출됐지만 아직 소비되지 않은 프롬프트 그룹은 많아야 개 — agent loop 개 — 이고, drop된 그룹마다 refill이 하나 더해진다.colocate_async에서는 끝나지 않은 것들이 학습 중 멈춰 있지만 살아 있고, 그 환경도 마찬가지다.- recipe
fully_async_policy: replica 개, =concurrent_samples_per_replica, =require_batches, =trigger_parameter_sync_step일 때 .
replica 수로 나눠 max_num_seqs와 비교하자. 그보다 많은 요청은 엔진 queue에서 기다린다(KV cache가 더 먼저 한도가 될 수도 있다). V1 벤치마크 설정에서 비동기 상한은 개 agent loop가 standalone replica 4개에, replica당 512개다. 기본 max_num_seqs=256보다 크므로, 그 설정을 올리지 않으면 절반은 엔진 안에서 줄을 선다.
→ 더 깊이: Agent loop과 환경 — 동시에 도는 agent loop이 sandbox, 환경 서버, KV cache에서 어디서 막히는지.
rollout.n agent-loop coroutines the moment it is submitted, and in async modes they stay alive (paused, holding their sandbox) across weight updates. Red lines are assertions verl raises at start-up or at the first long batch. Defaults reproduce the V1 benchmark in verl's docs (64 prompts, mini-batch 16, parameter_sync_step 4, 2 + 2 nodes, vLLM TP 4). 설정을 입력하면 verl이 그것으로 무엇을 할지 표가 보여 준다. global step당 optimizer step, GPU당 trajectory, rollout replica 수, 그리고 동시에 살아 있는 agent loop 수의 상한이다. 프롬프트 그룹은 제출되는 순간 rollout.n개의 agent-loop coroutine을 띄우고, 비동기 모드에서는 가중치 갱신 동안에도 (멈춘 채 sandbox를 붙들고) 살아 있다. 빨간 줄은 verl이 시작할 때나 첫 긴 배치에서 내는 assertion이다. 기본값은 verl 문서의 V1 벤치마크(프롬프트 64, mini-batch 16, parameter_sync_step 4, 2 + 2 노드, vLLM TP 4)를 재현한다. import heapq
import numpy as np
def plan(B, n, b, E, D, mode="sync", w=1.0, pss=None, replicas=8, max_num_seqs=256,
rb=1, tps=4, st=0.5, csr=16):
"""What verl does with a config (V1 modes) or the fully_async_policy recipe ('recipe')."""
out = {}
assert (b * n) % D == 0, "ppo_mini_batch_size * n must divide by the actor DP size"
if mode == "recipe":
req = b * rb
max_req = int(req * (1 + st) * tps)
out["opt_steps_per_sync"] = rb * E * tps
out["concurrent_samples"] = min(replicas * csr, max_req)
out["agent_loops"] = out["concurrent_samples"] * n
else:
assert B % b == 0
if mode == "separate_async":
assert B == pss * b, "train_batch_size must equal parameter_sync_step * ppo_mini_batch_size"
out["opt_steps_per_step"] = E * B // b
out["agent_loops"] = B * n if mode == "sync" else int((1 + w) * B * n)
out["per_gpu_per_update"] = b * n // D
out["requests_per_replica"] = out["agent_loops"] / replicas
out["engine_queues"] = out["requests_per_replica"] > max_num_seqs
return out
# the V1 benchmark in verl's docs: 64 prompts, n=16, mini-batch 16, 2 trainer nodes (DP 2), 2 rollout nodes (TP 4 -> 4 replicas)
print("separate_async :", plan(64, 16, 16, 1, D=2, mode="separate_async", pss=4, replicas=4))
print("sync (4 nodes) :", plan(64, 16, 16, 1, D=4, mode="sync", replicas=8))
print("recipe :", plan(0, 16, 32, 1, D=8, mode="recipe", replicas=8, rb=4, tps=4, st=0.5))
# ---- how often does max_off_policy_threshold drop groups? (toy replay buffer, V1 semantics)
def run(thr, sigma, steps=150, B=64, n=16, w=1.0, t_train=1.0, seed=0):
rng = np.random.default_rng(seed)
dur = lambda k: np.exp(sigma * rng.normal(size=(k, n))).max(1) * 0.6 # a group ends with its longest sample
t, pending = 0.0, [] # pending: (finish_time, submit_step)
def submit(k, step):
for f in t + dur(k):
heapq.heappush(pending, (f, step))
submit(int(w * B), 1)
dropped = used = 0; ages = []
for step in range(1, steps + 1):
submit(B, step) # prepare_step: one train batch per step
batch = []
while len(batch) < B:
fin, s0 = heapq.heappop(pending)
t = max(t, fin) # wait for the next finished group
if step - s0 + 1 > thr: # prompt age beyond the threshold -> drop and refill
dropped += 1; submit(1, step)
else:
batch.append(s0)
ages += [step - s0 for s0 in batch]; used += B
t += t_train # rollout keeps running meanwhile (separate pool)
return dropped / (dropped + used), np.mean(ages), t / steps
print("\nthreshold sigma dropped mean lag time/step")
for sigma in (0.6, 1.2):
for thr in (1, 2, 4, 8):
d, a, ts = run(thr, sigma)
print(f" {thr:2d} {sigma:.1f} {d:6.1%} {a:5.2f} {ts:5.2f}")The toy replay buffer reproduces the trade-off the threshold controls. A threshold of 1 accepts only groups submitted in the current step, so it behaves like a synchronous trainer that throws away the rest — around half the generated groups are wasted and steps are slowest. From 2 upward, drops vanish quickly when the length tail is moderate, but with a heavy tail (σ = 1.2, typical of agent episodes) a threshold of 2 still discards 15% of the groups, and those are the long trajectories — a selection bias toward short episodes that drop introduces and wait avoids at the cost of blocking.
separate_async with data.train_batch_size=128, ppo_mini_batch_size=32, parameter_sync_step=8. What happens?
PPOTrainerSeparateAsync.__init__ asserts train_batch_size == parameter_sync_step * ppo_mini_batch_size. In separate_async one _step_once samples one mini-batch of train_batch_size / parameter_sync_step prompts, so the invariant makes the number of mini-batches per global step the same as in the other modes. Here set parameter_sync_step=4, or ppo_mini_batch_size=16 if you want 8 updates per weight push.
With V1 colocate_async, train_batch_size=128, rollout.n=8, num_warmup_batches=1, each trajectory holds one sandbox pod for its whole life. What is the peak number of pods alive, ignoring refills?
. Agent loops are coroutines launched when their prompt is submitted; max_num_seqs limits how many requests an engine decodes at once, not how many agent loops (and their pods) exist. In colocate_async, unfinished trajectories stay alive through the training phase, so the pods do too — size the sandbox cluster for this number, not for .
Summary
- verl main (
4525109, 2026-12-02) runs only the V1 trainer:trainer.v1.trainer_mode=sync,colocate_asyncorseparate_async; the V0 fully-async and one-step-off trainers live inverl-recipe, pinned to v0.9.1. - Architecture: a single controller (Ray driver) calls SPMD worker groups on resource pools; TransferQueue carries the data; rollout runs as vLLM/SGLang/TRT-LLM server replicas driven by AgentLoop coroutines with least-request + sticky routing; weights reach the engines by sleep/wake + reshard (colocated) or a checkpoint engine (separate).
- Key semantics:
ppo_mini_batch_sizecounts prompts;use_dynamic_bszis on by default with a 16,384-token budget;separate_asyncrequirestrain_batch_size = parameter_sync_step × ppo_mini_batch_size; staleness is bounded in versions bymax_off_policy_thresholdwithdroporwait. - Recipe ↔ V1:
trigger_parameter_sync_step↔parameter_sync_step;staleness_threshold(sample fraction) ↔max_off_policy_threshold(versions); partial rollout is always on in V1 async;require_batchesandconcurrent_samples_per_replicahave no V1 counterpart. - Live agent loops: in sync, up to in V1 async, in the recipe. Compare per-replica load with
max_num_seqs, and size sandboxes for the same number.
import heapq
import numpy as np
def plan(B, n, b, E, D, mode="sync", w=1.0, pss=None, replicas=8, max_num_seqs=256,
rb=1, tps=4, st=0.5, csr=16):
"""설정 하나로 verl이 하는 일 (V1 모드) 또는 fully_async_policy recipe ('recipe')."""
out = {}
assert (b * n) % D == 0, "ppo_mini_batch_size * n은 actor DP 크기로 나누어떨어져야 한다"
if mode == "recipe":
req = b * rb
max_req = int(req * (1 + st) * tps)
out["opt_steps_per_sync"] = rb * E * tps
out["concurrent_samples"] = min(replicas * csr, max_req)
out["agent_loops"] = out["concurrent_samples"] * n
else:
assert B % b == 0
if mode == "separate_async":
assert B == pss * b, "train_batch_size는 parameter_sync_step * ppo_mini_batch_size와 같아야 한다"
out["opt_steps_per_step"] = E * B // b
out["agent_loops"] = B * n if mode == "sync" else int((1 + w) * B * n)
out["per_gpu_per_update"] = b * n // D
out["requests_per_replica"] = out["agent_loops"] / replicas
out["engine_queues"] = out["requests_per_replica"] > max_num_seqs
return out
# verl 문서의 V1 벤치마크: 프롬프트 64, n=16, mini-batch 16, trainer 2노드(DP 2), rollout 2노드(TP 4 -> replica 4)
print("separate_async :", plan(64, 16, 16, 1, D=2, mode="separate_async", pss=4, replicas=4))
print("sync (4 nodes) :", plan(64, 16, 16, 1, D=4, mode="sync", replicas=8))
print("recipe :", plan(0, 16, 32, 1, D=8, mode="recipe", replicas=8, rb=4, tps=4, st=0.5))
# ---- max_off_policy_threshold는 그룹을 얼마나 버리나? (장난감 replay buffer, V1 의미)
def run(thr, sigma, steps=150, B=64, n=16, w=1.0, t_train=1.0, seed=0):
rng = np.random.default_rng(seed)
dur = lambda k: np.exp(sigma * rng.normal(size=(k, n))).max(1) * 0.6 # 그룹은 가장 긴 샘플과 함께 끝난다
t, pending = 0.0, [] # pending: (끝나는 시각, 제출 step)
def submit(k, step):
for f in t + dur(k):
heapq.heappush(pending, (f, step))
submit(int(w * B), 1)
dropped = used = 0; ages = []
for step in range(1, steps + 1):
submit(B, step) # prepare_step: step마다 train batch 하나
batch = []
while len(batch) < B:
fin, s0 = heapq.heappop(pending)
t = max(t, fin) # 다음으로 끝나는 그룹을 기다린다
if step - s0 + 1 > thr: # 프롬프트 나이가 한도를 넘으면 drop하고 refill
dropped += 1; submit(1, step)
else:
batch.append(s0)
ages += [step - s0 for s0 in batch]; used += B
t += t_train # 그동안 rollout은 계속 돈다 (분리 pool)
return dropped / (dropped + used), np.mean(ages), t / steps
print("\nthreshold sigma dropped mean lag time/step")
for sigma in (0.6, 1.2):
for thr in (1, 2, 4, 8):
d, a, ts = run(thr, sigma)
print(f" {thr:2d} {sigma:.1f} {d:6.1%} {a:5.2f} {ts:5.2f}")장난감 replay buffer가 한도가 조절하는 trade-off를 재현한다. 한도 1은 현재 step에 제출된 그룹만 받으므로 나머지를 버리는 동기 trainer처럼 군다. 생성한 그룹의 절반쯤이 버려지고 step이 가장 느리다. 2 이상에서는 길이 꼬리가 적당하면 drop이 금세 사라지지만, 꼬리가 무거우면(σ = 1.2, agent 에피소드에 흔하다) 한도 2에서도 그룹의 15%를 버리고, 그것이 바로 긴 trajectory다. drop이 들여오는 짧은 에피소드 쪽 선택 편향이고, wait은 막힘을 대가로 이를 피한다.
separate_async에서 data.train_batch_size=128, ppo_mini_batch_size=32, parameter_sync_step=8이다. 어떻게 되나?
PPOTrainerSeparateAsync.__init__이 train_batch_size == parameter_sync_step * ppo_mini_batch_size를 assert한다. separate_async에서 _step_once 한 번은 프롬프트 train_batch_size / parameter_sync_step개짜리 mini-batch 하나를 sample하므로, 이 불변식이 global step당 mini-batch 수를 다른 모드와 같게 만든다. 여기서는 parameter_sync_step=4로 두거나, 가중치 밀어 넣기마다 갱신 8번을 원하면 ppo_mini_batch_size=16으로 둔다.
V1 colocate_async, train_batch_size=128, rollout.n=8, num_warmup_batches=1이고, trajectory 하나가 살아 있는 내내 sandbox pod 하나를 붙든다. refill을 무시하면 동시에 살아 있는 pod는 최대 몇 개인가?
이다. agent loop는 프롬프트가 제출될 때 띄워지는 coroutine이다. max_num_seqs는 엔진이 한 번에 decode하는 요청 수를 묶을 뿐, agent loop(와 그 pod)가 몇 개 존재하는지는 묶지 않는다. colocate_async에서는 끝나지 않은 trajectory가 학습 단계 내내 살아 있으므로 pod도 그렇다. sandbox 클러스터는 이 아니라 이 수에 맞춰야 한다.
정리
- verl main(
4525109, 2026-12-02)은 V1 trainer만 돌린다.trainer.v1.trainer_mode=sync,colocate_async,separate_async. V0의 fully-async·one-step-off trainer는 v0.9.1에 고정된verl-recipe에 있다. - 구조: single controller(Ray driver)가 resource pool 위의 SPMD worker group을 부른다. TransferQueue가 데이터를 나르고, rollout은 AgentLoop coroutine이 least-request + sticky routing으로 부리는 vLLM/SGLang/TRT-LLM server replica로 돈다. 가중치는 sleep/wake + reshard(colocated)나 checkpoint engine(분리)으로 엔진에 닿는다.
- 핵심 의미:
ppo_mini_batch_size는 프롬프트 수이고,use_dynamic_bsz가 기본으로 켜져 있으며 예산은 16,384 토큰이다.separate_async는train_batch_size = parameter_sync_step × ppo_mini_batch_size를 요구하고, staleness는max_off_policy_threshold가 버전 단위로drop이나wait으로 묶는다. - recipe ↔ V1:
trigger_parameter_sync_step↔parameter_sync_step,staleness_threshold(샘플 비율) ↔max_off_policy_threshold(버전). V1 비동기에서는 partial rollout이 늘 켜져 있고,require_batches와concurrent_samples_per_replica는 V1 대응이 없다. - 살아 있는 agent loop: sync는 , V1 비동기는 최대 , recipe는 . replica당 부하를
max_num_seqs와 비교하고, sandbox도 같은 수에 맞춰라.
더 읽을거리Further reading
- verl repository, main @ 4525109 (2026-12-02), README and News — 이 레슨이 기준으로 삼은 커밋. 2026/11에 V0 trainer 제거와 recipe 이전이 공지됐다.The commit this lesson is checked against; the November 2026 news announces the removal of the V0 trainer and the move of the async recipes.
- verl docs — V1 Async Trainer (docs/advance/v1_async_trainer.md, updated 2026-11-07) — 세 모드, parameter_sync_step 불변식, max_off_policy_threshold, step switching, 벤치마크.The three modes, the parameter_sync_step invariant, max_off_policy_threshold, step switching and the benchmarks.
- verl-recipe — fully_async_policy README (pinned to verl v0.9.1) — require_batches, trigger_parameter_sync_step, staleness_threshold, partial_rollout의 원래 정의와 네 가지 모드.The original definitions of require_batches, trigger_parameter_sync_step, staleness_threshold, partial_rollout and the four modes.
- verl docs — Agent Loop (docs/advance/agent_loop.rst) — AgentLoopBase, AgentLoopOutput, token-in-token-out을 고른 이유, least-request + sticky session.AgentLoopBase, AgentLoopOutput, why token-in-token-out, least-request plus sticky-session routing.
- verl v0.9.0 release notes (2026-08-14) — 통합 V1 trainer 기본화, drop/wait staleness 제어, delta_sharded checkpoint engine, dynamic CP.Unified V1 trainer on by default, drop/wait staleness control, the delta_sharded checkpoint engine, dynamic CP.
- Sheng et al., HybridFlow: A Flexible and Efficient RLHF Framework (EuroSys 2025) — single controller + multi-controller 프로그래밍 모델과 3D-HybridEngine.The single-controller + multi-controller programming model and the 3D-HybridEngine.
- verl docs — The Design of verl.single_controller — WorkerGroup, ResourcePool, dispatch mode가 왜 생겼는지.Why WorkerGroup, ResourcePool and dispatch modes exist.