Agent RL derived why only model-sampled tokens get a policy gradient and why multi-turn credit assignment is hard; long-horizon RL and rewards and environments cover the algorithms and the reward side. This lesson is about the machinery and its arithmetic: how one agent trajectory is executed in verl, and how many of them — with their sandboxes — are alive at once for a given configuration. Code references are to verl main at 4525109 (2026-12-02) unless marked as the v0.9.1-pinned verl-recipe.
One trajectory, step by step
Dispatch. AgentLoopManager starts actor_rollout_ref.rollout.agent.num_workers Ray actors (default 8) of type AgentLoopWorker and splits each batch of prompts across them. In the V1 trainers the worker spawns, for every prompt, rollout.n coroutines at once (_run_prompt → asyncio.create_task per session) and does not wait for them: each finished trajectory is written to the TransferQueue on its own. There is no semaphore on agent loops inside a worker — a coroutine is cheap, so every dispatched trajectory is alive immediately, whether or not the LLM server has room for it.
The loop. Each coroutine instantiates the registered agent loop (default single_turn_agent; with tools, ToolAgentLoop) and calls its run(). ToolAgentLoop is a small state machine:
PENDING (render the chat template with tool schemas → prompt ids) → GENERATING (one LLM call) → if the output contains tool calls, PROCESSING_TOOLS → back to GENERATING … → TERMINATED.
It stops on the response budget (rollout.response_length), on multi_turn.max_assistant_turns / max_user_turns, or when the model answers without a tool call. At most multi_turn.max_parallel_calls tool calls (default 1) run per turn, concurrently via asyncio.gather; each tool response is truncated to max_tool_response_length characters (default 256, tool_response_truncate_side: middle). A stateful tool (BaseTool) goes through create → execute → release per call; a stateless @function_tool is just called. Long-lived environments (a SWE repository in a container) are therefore usually written as a custom agent loop that owns its sandbox for the whole trajectory.
Talking to the LLM. The loop never calls vLLM/SGLang directly; it calls LLMServerClient.generate(request_id, prompt_ids=…). The client picks the server replica with the fewest in-flight requests for a new request_id and keeps later turns of the same trajectory on the same replica (sticky session), so the prefix KV cache built in turn is reused in turn . The interface is token in, token out: the verl docs explain that re-applying the chat template to the final message list does not reproduce the token ids the model actually generated (tool parsers rewrite content; decode–encode is not an identity), and that training on the re-tokenised version broke convergence even in single-turn runs. With multi-turn enabled, each worker replays fixed conversations through its “continuous token builder” before the first rollout and compares every turn boundary with a single-pass template render (multi_turn check mode strict by default).
What comes back. AgentLoopOutput holds prompt_ids, response_ids (model tokens and tool/observation tokens interleaved), response_mask (1 for model-generated tokens, 0 for tool/observation tokens), the rollout log-probs aligned with them, and, for MoE, the routed experts for routing replay. The mask is the identity from the agent-RL lesson made concrete; rollout correction then runs on the same masked tokens. The reward is computed per trajectory when it finishes (reward loop); code verifiers commonly go through SandboxFusion, whose verl config (sandbox_fusion.max_concurrent, default 64; memory_limit_mb, 1024) is a reward-side cap, separate from any sandboxes the agent itself uses.
The figure below runs a few dozen such loops against one LLM replica. Each loop alternates between decoding on the server and waiting for a tool.
Agent RL은 왜 모델이 샘플한 토큰만 policy gradient를 받는지, 왜 멀티턴 credit assignment가 어려운지를 유도했다. 장기 horizon RL과 보상과 환경은 알고리즘과 보상 쪽을 다룬다. 이 레슨은 기계 장치와 그 산수에 관한 것이다. agent trajectory 하나가 verl에서 어떻게 실행되는지, 그리고 주어진 설정에서 그런 trajectory가 — 그 sandbox와 함께 — 동시에 몇 개 살아 있는지. 코드 참조는 따로 표시하지 않으면 verl main 커밋 4525109(2026-12-02)이고, 표시한 것은 v0.9.1에 고정된 verl-recipe다.
trajectory 하나를 단계별로
분배. AgentLoopManager는 actor_rollout_ref.rollout.agent.num_workers개(기본 8)의 AgentLoopWorker Ray actor를 띄우고 prompt 배치를 그들에게 나눈다. V1 trainer에서 worker는 prompt마다 rollout.n개의 coroutine을 한꺼번에 띄우고(_run_prompt → 세션마다 asyncio.create_task) 기다리지 않는다. 끝난 trajectory는 각자 TransferQueue에 쓰인다. worker 안에서 agent loop에 대한 semaphore는 없다 — coroutine은 싸므로, LLM 서버에 자리가 있든 없든 분배된 trajectory는 모두 즉시 살아 있다.
루프. 각 coroutine은 등록된 agent loop(기본 single_turn_agent, tool이 있으면 ToolAgentLoop)을 만들고 run()을 부른다. ToolAgentLoop은 작은 상태 기계다.
PENDING(tool schema와 함께 chat template 렌더 → prompt id) → GENERATING(LLM 호출 한 번) → 출력에 tool 호출이 있으면 PROCESSING_TOOLS → 다시 GENERATING … → TERMINATED.
응답 예산(rollout.response_length), multi_turn.max_assistant_turns / max_user_turns, 또는 모델이 tool 호출 없이 답하면 멈춘다. turn당 최대 multi_turn.max_parallel_calls개(기본 1)의 tool 호출이 asyncio.gather로 동시에 돌고, 각 tool 응답은 max_tool_response_length자(기본 256, tool_response_truncate_side: middle)로 잘린다. 상태가 있는 tool(BaseTool)은 호출마다 create → execute → release를 거치고, 상태 없는 @function_tool은 그냥 호출된다. 그래서 오래 사는 환경(컨테이너 안의 SWE 저장소)은 보통 trajectory 전체 동안 sandbox를 소유하는 custom agent loop으로 쓴다.
LLM과의 대화. 루프는 vLLM/SGLang을 직접 부르지 않고 LLMServerClient.generate(request_id, prompt_ids=…)를 부른다. 클라이언트는 새 request_id에 대해 진행 중 요청이 가장 적은 서버 replica를 고르고, 같은 trajectory의 이후 turn은 같은 replica에 붙여 둔다(sticky session). 그래서 turn 에서 만든 prefix KV cache가 turn 에서 재사용된다. 인터페이스는 token in, token out이다. verl 문서는 최종 메시지 목록에 chat template을 다시 적용해도 모델이 실제로 생성한 토큰 id가 재현되지 않으며(tool parser가 내용을 고치고, decode–encode는 항등이 아니다), 다시 토큰화한 버전으로 학습하면 single-turn에서도 수렴이 깨졌다고 설명한다. 멀티턴을 켜면 각 worker는 첫 rollout 전에 고정된 대화들을 “continuous token builder”로 재생해 모든 turn 경계를 한 번에 렌더한 template과 비교한다(multi_turn 검사 모드 기본값 strict).
돌아오는 것. AgentLoopOutput은 prompt_ids, response_ids(모델 토큰과 tool/관측 토큰이 번갈아), response_mask(모델이 생성한 토큰은 1, tool/관측 토큰은 0), 그에 맞춰 정렬된 rollout log-prob, 그리고 MoE라면 routing replay용 routed expert를 담는다. mask는 agent-RL 레슨의 항등식을 구체화한 것이고, rollout correction은 같은 mask된 토큰 위에서 돈다. 보상은 trajectory가 끝날 때 trajectory마다 계산된다(reward loop). 코드 검증기는 흔히 SandboxFusion을 거치는데, 그 verl 설정(sandbox_fusion.max_concurrent 기본 64, memory_limit_mb 1024)은 reward 쪽 상한으로, agent 자신이 쓰는 sandbox와는 별개다.
아래 그림은 이런 loop 수십 개를 LLM replica 하나에 대고 돌린다. 각 loop는 서버에서 decode하는 시간과 tool을 기다리는 시간을 오간다.
max_num_seqs. The bottom band is the number of sequences decoding at once. Raise the tool latency: the server batch thins out and tokens/s collapses although every loop is "busy" — the run is environment-bound. Raise the loop count to refill the batch. Lower max_num_seqs to see grey queues — then the LLM side is the bottleneck. All loops start together, as in a synchronous step, so the last loops finish alone (the tail). 한 줄이 agent loop 하나(trajectory 하나)다. 파랑 = LLM 서버에서 생성 중, 주황 = tool/sandbox를 기다리는 중, 회색 = 서버가 max_num_seqs에 차서 대기 중. 아래 띠는 동시에 decode 중인 시퀀스 수다. tool 지연을 올리면 모든 loop가 "바쁜데도" 서버 배치가 얇아지고 토큰/s가 무너진다 — 환경이 병목이다. loop 수를 올려 배치를 다시 채워 보자. max_num_seqs를 낮추면 회색 대기열이 생긴다 — 이때는 LLM 쪽이 병목이다. 동기 스텝처럼 모든 loop가 함께 시작하므로 마지막 loop들은 혼자 끝난다(꼬리). How many loops are alive?
Write for the number of LLM server replicas, (llm_server.py: num_replicas = world_size // rollout_world_size). The number of live agent loops follows from how prompts are dispatched:
| trainer | live agent loops | where it comes from |
|---|---|---|
V1 sync | at the start of each step, then decaying through the tail | the whole train_batch_size is dispatched; every prompt spawns sessions |
V1 colocate_async / separate_async | at most | num_warmup_batches batches dispatched up front plus one batch per step; evicted or failed groups are refilled one for one |
fully_async_policy recipe (v0.9.1) | max_concurrent_samples caps in-flight samples (one sample = one prompt = loops); = async_training.concurrent_samples_per_replica (default 16; earlier versions hard-coded 16); = require_batches, = staleness_threshold, = trigger_parameter_sync_step |
Two consequences engineers trip over. First, in the V1 async trainers nothing caps per replica: if exceeds vLLM’s max_num_seqs (256 in verl’s rollout config), the surplus requests simply queue inside the engine while their loops — and their sandboxes — stay alive. Second, in colocate_async the replicas sleep during training while the in-flight loops wait to resume: sandboxes are held through the training phase too.
Little’s law: where the time goes
In steady state a loop alternates a generation phase of length and a tool phase of mean length . Little’s law () splits the loops of one replica into
The server decodes sequences; with a decode step time (memory-bound at small , compute-bound at large ; see the roofline), per-sequence speed is , replica throughput , and for tokens per turn (the last factor is queueing when exceeds the cap). These equations define a fixed point that is easy to solve by bisection — the NumPy block checks it against a direct simulation. From it:
- Tokens/s per replica rises linearly in while (every extra loop adds one more sequence to the batch only a fraction of the time), then saturates. The knee is where the server is just full: . With long tool latencies the knee moves far to the right — an environment-bound run needs many more loops than the server’s batch size to keep the GPUs busy.
- Sandboxes. If each trajectory owns a sandbox for its lifetime (SWE-style containers), pods . If sandboxes are acquired per call (
BaseTool.create/release), pods , with the cluster-wide tool-call rate. - Bottleneck. If is pinned at
max_num_seqsor is near , the run is LLM-bound: add replicas, not sandboxes. If most of a loop’s time is and the server is far from saturation, it is environment-bound: add concurrency (loops and their sandboxes) or make the environment faster; more GPUs would idle.
The calculator puts the verl formulas and this model together. The default reproduces a typical question: 4 rollout nodes, TP 4 → ; for the recipe with , , , , : loops, the per-replica cap binding.
살아 있는 loop는 몇 개인가
LLM 서버 replica 수를 라 쓰자(llm_server.py: num_replicas = world_size // rollout_world_size). 살아 있는 agent loop 수 은 prompt를 분배하는 방식에서 나온다.
| trainer | 살아 있는 agent loop | 출처 |
|---|---|---|
V1 sync | 스텝 시작에 , 이후 꼬리를 따라 줄어듦 | train_batch_size 전체가 분배되고 prompt마다 세션 개 |
V1 colocate_async / separate_async | 최대 | 처음에 num_warmup_batches 개 배치 + 스텝마다 한 배치; 버려지거나 실패한 group은 하나씩 보충 |
fully_async_policy 레시피(v0.9.1) | max_concurrent_samples가 진행 중 샘플을 제한(샘플 하나 = prompt 하나 = loop 개); = async_training.concurrent_samples_per_replica(기본 16; 예전 버전은 16을 하드코딩); = require_batches, = staleness_threshold, = trigger_parameter_sync_step |
엔지니어가 자주 걸려 넘어지는 결과가 둘 있다. 첫째, V1 비동기 trainer에서는 replica당 을 제한하는 것이 없다. 가 vLLM의 max_num_seqs(verl rollout 설정에서 256)를 넘으면 남는 요청은 엔진 안에서 줄을 서고, 그동안 loop — 그리고 그 sandbox — 는 살아 있다. 둘째, colocate_async에서는 학습 동안 replica가 잠들고 진행 중 loop는 재개를 기다린다. sandbox는 학습 단계 내내 붙잡혀 있다.
Little’s law: 시간은 어디로 가나
정상상태에서 loop는 길이 의 생성 단계와 평균 길이 의 tool 단계를 오간다. Little’s law(단계 안의 수 = 비율 × 단계 체류 시간)는 replica 하나의 loop 개를 다음처럼 나눈다.
서버는 개 시퀀스를 decode한다. decode 스텝 시간을 (작은 에서 memory-bound, 큰 에서 compute-bound; roofline 참고)로 두면 시퀀스당 속도는 , replica 처리량은 이고, turn당 토큰에 대해 다(마지막 인자는 이 상한을 넘을 때의 대기). 이 식들은 이분법으로 쉽게 푸는 고정점을 정의한다 — NumPy 블록이 이것을 직접 시뮬레이션과 대조한다. 여기서 나오는 것:
- replica당 토큰/s는 인 동안 에 선형으로 오른다(loop 하나를 더하면 시간의 만큼만 배치에 시퀀스 하나가 더해진다). 그 뒤 포화한다. knee는 서버가 막 가득 차는 곳, 다. tool 지연이 길면 knee는 한참 오른쪽으로 간다 — 환경이 병목인 run은 GPU를 바쁘게 두려면 서버 배치 크기보다 훨씬 많은 loop가 필요하다.
- sandbox. trajectory마다 sandbox를 평생 소유하면(SWE식 컨테이너) pod 수 . 호출마다 sandbox를 얻으면(
BaseTool.create/release) pod 수 , 는 클러스터 전체의 tool 호출 비율이다. - 병목. 가
max_num_seqs에 붙어 있거나 가 근처면 LLM 병목이다. sandbox가 아니라 replica를 늘린다. loop 시간 대부분이 이고 서버가 포화와 거리가 멀면 환경 병목이다. 동시성(loop와 그 sandbox)을 늘리거나 환경을 빠르게 한다. GPU를 더해도 놀 뿐이다.
계산기는 verl 식과 이 모델을 합친다. 기본값은 전형적인 질문을 재현한다. rollout 노드 4개, TP 4 → . 레시피에서 , , , , 이면 개 loop이고, replica당 상한이 묶는 쪽이다.
max_num_seqs; the dot is your configuration and the dashed line the knee L* where the server just saturates. Single-stream decode is fixed at 60 tokens/s. The split into generate / queue / tool time is a steady-state estimate (processor sharing + Little's law), not a measurement. 왼쪽: 이 설정에서 verl이 동시에 살려 두는 agent loop 수(코드에서 나온 식), 그것이 LLM replica에 어떻게 나뉘는지, 그로부터 필요한 sandbox/pod 수, 그리고 병목. 오른쪽: replica당 loop 수에 따른 replica당 토큰/s(파랑). loop가 대부분 tool을 기다리는 동안은 선형으로 오르다가 replica 최대치나 max_num_seqs에서 포화한다. 점은 현재 설정, 점선은 서버가 막 포화하는 knee L*. 단일 stream decode는 60 토큰/s로 고정. 생성/대기/tool 시간 분할은 정상상태 추정(processor sharing + Little's law)이지 측정이 아니다. Things to try: switch to the recipe mode with the defaults and set rollout nodes 12 — and both caps equal 384 ( loops); lower trigger_parameter_sync_step to 2 and the training-side cap binds instead (1536). In V1 separate_async, raise the tool latency to 30 s with 30 turns: the dot slides onto the linear part of the curve — environment-bound, the GPUs idle — and the remedy is a larger train_batch_size or more warmup batches (more loops), not more rollout nodes.
How other frameworks cap concurrency
| system | knob that bounds live trajectories | default |
|---|---|---|
| AReaL | rollout.max_concurrent_rollouts (split over DP ranks), plus the staleness admission rule | = consumer_batch_size |
| slime | --sglang-server-concurrency per engine → global semaphore; fully-async group pool = that × engines / n_samples_per_prompt × prefetch factor | 512 |
| prime-rl | [orchestrator.concurrency] adaptive controller (max_inflight “to bound external resources the episodes hold, e.g. sandboxes”), dispatch_per_minute | unbounded / none |
| SkyRL | fully_async.num_parallel_generation_workers; per-engine request semaphore; skyrl_gym.max_env_workers thread pool; Harbor rate limits | 768; 512; 32 |
| ROLL (agentic) | env managers: num_env_groups × group_size environments, max_env_num_per_worker; max_running_requests per inference DP rank | 128 groups; 128 |
| OpenRLHF | none: a whole generate batch is dispatched; backpressure only via async_queue_size | — |
The newest pattern decouples the agent from the trainer entirely: the unmodified agent harness calls an OpenAI-compatible endpoint, and the trainer records the token-level trace behind it (Agent Lightning; SkyRL’s Harbor integration runs agents in Docker/Daytona/Modal sandboxes that call vLLM through LiteLLM with an X-Session-ID header for sticky routing). The concurrency arithmetic above is unchanged — only the place where is set moves to the harness.
import numpy as np
# ---- 1. How many agent loops does verl keep alive? (formulas from the code) ----
def loops_alive(mode, n, B=None, warmup=1.0, H=None, c=16, B_mini=None, R=None, S=None, T=None):
if mode == 'sync': # every trajectory of the batch is a coroutine at once
return B * n
if mode in ('colocate_async', 'separate_async'): # prompts dispatched ahead: warmup + 1 batch
return int((1 + warmup) * B * n) # upper bound (refills replace evicted groups 1:1)
if mode == 'recipe': # verl-recipe fully_async_policy (pinned to verl v0.9.1)
return min(H * c, int(B_mini * R * (1 + S) * T)) * n
H = 32 // 4 # 4 rollout nodes x 8 GPUs, TP=4 -> 8 vLLM replicas
print('sync :', loops_alive('sync', n=8, B=64))
print('separate_async:', loops_alive('separate_async', n=8, B=64, warmup=1))
print('recipe :', loops_alive('recipe', n=8, H=H, B_mini=32, R=2, S=0.5, T=4),
' (H*16 =', H * 16, ' vs B_mini*R*(1+S)*T =', int(32 * 2 * 1.5 * 4), ')')
# ---- 2. Steady state on one replica: fixed point vs a direct simulation ----
V1, VMAX = 60.0, 4000.0 # single-stream and saturated tokens/s (assumed)
t0, t1 = 1 / V1, 1 / VMAX # per-sequence step time t0 + t1*b
def fixed_point(x, g, tau, cap):
lo, hi = 0.0, float(x)
for _ in range(60): # solve w = x * Tg(w) / (Tg(w) + tau)
w = (lo + hi) / 2; b = min(w, cap)
Tg = g * (t0 + t1 * max(b, 1)) * (w / max(b, 1e-9))
lo, hi = (w, hi) if x * Tg / (Tg + tau) > w else (lo, w)
b = min(w, cap)
return b / (t0 + t1 * max(b, 1)), x - w # tokens/s, loops inside a tool call
def simulate(x, g, tau, cap, T=150.0, dt=0.025, seed=0):
rng = np.random.default_rng(seed)
left = rng.uniform(0.5, 1.5, x) * g # all loops start generating
tool = np.zeros(x)
gen = np.ones(x, bool)
tokens, in_tool = 0.0, []
for step in range(int(T / dt)):
idx = np.flatnonzero(gen)[:cap] # at most cap sequences decode (FIFO by index)
v = 1 / (t0 + t1 * max(len(idx), 1))
left[idx] -= v * dt; tokens += v * dt * len(idx)
done = idx[left[idx] <= 0]
gen[done] = False; tool[done] = rng.exponential(tau, len(done))
tool[~gen] -= dt
back = (~gen) & (tool <= 0)
gen[back] = True; left[back] = rng.uniform(0.5, 1.5, back.sum()) * g
if step * dt > T / 3: in_tool.append((~gen).sum())
return tokens / T, np.mean(in_tool)
print('\nloops/replica tool(s) | tokens/s fixed-pt sim | loops in tool fixed-pt sim')
for x, tau in [(16, 5.0), (64, 5.0), (256, 5.0), (64, 30.0)]:
f_tps, f_tool = fixed_point(x, g=300, tau=tau, cap=256)
s_tps, s_tool = simulate(x, g=300, tau=tau, cap=256)
print(f'{x:13d} {tau:7.0f} | {f_tps:17.0f} {s_tps:5.0f} | {f_tool:22.1f} {s_tool:5.1f}')The first three lines reproduce the table. The second block compares the fixed-point estimate with a direct simulation of loops on one replica (processor-sharing decode, exponential tool times): tokens/s and loops-in-tool agree within about 10% (the simulation includes its warm-up). At 16 loops with 5 s tools the replica runs at ~11% of its 4,000 tokens/s peak with half the loops in a tool; at 256 loops it reaches ~75%; with 30 s tools, 64 loops leave the GPU nearly idle while 54 of them sit in sandboxes.
A V1 separate_async run has 8 replicas, max_num_seqs 256, train_batch_size 128, n 16 and num_warmup_batches 1. Tools take ~20 s and each turn generates ~200 tokens. Which statement is most likely true?
V1 dispatches prompts and spawns loops per prompt without a cap, so . max_num_seqs limits only concurrent decoding; loops beyond it queue in the engine while staying alive. With s and of a few seconds, only a small fraction of loops is generating at any moment, so per replica , well under 256 — environment-bound, with ~4,096 pods if each trajectory owns one.
Summary
- verl runs every dispatched trajectory as a coroutine immediately:
AgentLoopWorker→ToolAgentLoop(PENDING → GENERATING ⇄ PROCESSING_TOOLS → TERMINATED), talking token-in/token-out to a least-loaded, sticky LLM replica;response_maskmarks model tokens with 1 and tool tokens with 0. - Live loops: (V1 sync), up to (V1 async), (fully-async recipe, =
concurrent_samples_per_replica, default 16), with . max_num_seqscaps decoding, not loops; queued loops keep their sandboxes.- Little’s law splits loops into generating and in-tool; the server saturates only past loops per replica.
- Pods for per-trajectory sandboxes, for per-call ones. LLM-bound → add replicas; environment-bound → add concurrency or speed up the environment.
해 볼 것: 레시피 모드 기본값에서 rollout 노드를 12개로 두면 이고 두 상한이 모두 384가 된다(개 loop). trigger_parameter_sync_step을 2로 내리면 대신 학습 쪽 상한이 묶는다(1536). V1 separate_async에서 tool 지연을 30초, turn을 30으로 올리면 점이 곡선의 선형 구간으로 미끄러진다 — 환경 병목, GPU가 논다 — 해법은 rollout 노드를 늘리는 것이 아니라 더 큰 train_batch_size나 더 많은 warmup 배치(더 많은 loop)다.
다른 프레임워크는 동시성을 어떻게 묶나
| 시스템 | 살아 있는 trajectory를 묶는 손잡이 | 기본값 |
|---|---|---|
| AReaL | rollout.max_concurrent_rollouts(DP rank에 나눔), 그리고 staleness 입장 규칙 | = consumer_batch_size |
| slime | 엔진당 --sglang-server-concurrency → 전역 semaphore; fully-async group pool = 그 값 × 엔진 수 / n_samples_per_prompt × prefetch factor | 512 |
| prime-rl | [orchestrator.concurrency] 적응형 제어기(max_inflight는 “에피소드가 붙잡는 외부 자원, 예: sandbox를 묶기 위해”), dispatch_per_minute | 무제한 / 없음 |
| SkyRL | fully_async.num_parallel_generation_workers; 엔진당 요청 semaphore; skyrl_gym.max_env_workers 스레드 풀; Harbor 속도 제한 | 768; 512; 32 |
| ROLL (agentic) | env manager: num_env_groups × group_size개 환경, max_env_num_per_worker; 추론 DP rank당 max_running_requests | 128 group; 128 |
| OpenRLHF | 없음: generate 배치 전체를 분배; backpressure는 async_queue_size뿐 | — |
가장 새로운 패턴은 agent를 학습기에서 완전히 떼어 낸다. 수정하지 않은 agent harness가 OpenAI 호환 endpoint를 부르고, 학습기가 그 뒤에서 토큰 단위 trace를 기록한다(Agent Lightning; SkyRL의 Harbor 통합은 Docker/Daytona/Modal sandbox에서 agent를 돌리고, agent는 sticky routing을 위한 X-Session-ID 헤더와 함께 LiteLLM을 통해 vLLM을 부른다). 위의 동시성 산수는 그대로다 — 을 정하는 곳이 harness로 옮겨갈 뿐이다.
import numpy as np
# ---- 1. How many agent loops does verl keep alive? (formulas from the code) ----
def loops_alive(mode, n, B=None, warmup=1.0, H=None, c=16, B_mini=None, R=None, S=None, T=None):
if mode == 'sync': # every trajectory of the batch is a coroutine at once
return B * n
if mode in ('colocate_async', 'separate_async'): # prompts dispatched ahead: warmup + 1 batch
return int((1 + warmup) * B * n) # upper bound (refills replace evicted groups 1:1)
if mode == 'recipe': # verl-recipe fully_async_policy (pinned to verl v0.9.1)
return min(H * c, int(B_mini * R * (1 + S) * T)) * n
H = 32 // 4 # 4 rollout nodes x 8 GPUs, TP=4 -> 8 vLLM replicas
print('sync :', loops_alive('sync', n=8, B=64))
print('separate_async:', loops_alive('separate_async', n=8, B=64, warmup=1))
print('recipe :', loops_alive('recipe', n=8, H=H, B_mini=32, R=2, S=0.5, T=4),
' (H*16 =', H * 16, ' vs B_mini*R*(1+S)*T =', int(32 * 2 * 1.5 * 4), ')')
# ---- 2. Steady state on one replica: fixed point vs a direct simulation ----
V1, VMAX = 60.0, 4000.0 # single-stream and saturated tokens/s (assumed)
t0, t1 = 1 / V1, 1 / VMAX # per-sequence step time t0 + t1*b
def fixed_point(x, g, tau, cap):
lo, hi = 0.0, float(x)
for _ in range(60): # solve w = x * Tg(w) / (Tg(w) + tau)
w = (lo + hi) / 2; b = min(w, cap)
Tg = g * (t0 + t1 * max(b, 1)) * (w / max(b, 1e-9))
lo, hi = (w, hi) if x * Tg / (Tg + tau) > w else (lo, w)
b = min(w, cap)
return b / (t0 + t1 * max(b, 1)), x - w # tokens/s, loops inside a tool call
def simulate(x, g, tau, cap, T=150.0, dt=0.025, seed=0):
rng = np.random.default_rng(seed)
left = rng.uniform(0.5, 1.5, x) * g # all loops start generating
tool = np.zeros(x)
gen = np.ones(x, bool)
tokens, in_tool = 0.0, []
for step in range(int(T / dt)):
idx = np.flatnonzero(gen)[:cap] # at most cap sequences decode (FIFO by index)
v = 1 / (t0 + t1 * max(len(idx), 1))
left[idx] -= v * dt; tokens += v * dt * len(idx)
done = idx[left[idx] <= 0]
gen[done] = False; tool[done] = rng.exponential(tau, len(done))
tool[~gen] -= dt
back = (~gen) & (tool <= 0)
gen[back] = True; left[back] = rng.uniform(0.5, 1.5, back.sum()) * g
if step * dt > T / 3: in_tool.append((~gen).sum())
return tokens / T, np.mean(in_tool)
print('\nloops/replica tool(s) | tokens/s fixed-pt sim | loops in tool fixed-pt sim')
for x, tau in [(16, 5.0), (64, 5.0), (256, 5.0), (64, 30.0)]:
f_tps, f_tool = fixed_point(x, g=300, tau=tau, cap=256)
s_tps, s_tool = simulate(x, g=300, tau=tau, cap=256)
print(f'{x:13d} {tau:7.0f} | {f_tps:17.0f} {s_tps:5.0f} | {f_tool:22.1f} {s_tool:5.1f}')처음 세 줄은 표를 재현한다. 두 번째 블록은 고정점 추정을 replica 하나 위의 loop 개 직접 시뮬레이션(processor-sharing decode, 지수분포 tool 시간)과 비교한다. 토큰/s와 tool 중인 loop 수가 약 10% 안에서 맞는다(시뮬레이션에는 warm-up이 포함된다). tool 5초에 loop 16개면 replica는 최대 4,000 토큰/s의 약 11%로 돌고 loop의 절반이 tool 안에 있다. loop 256개면 약 75%에 닿는다. tool 30초면 loop 64개 중 54개가 sandbox에 앉아 있고 GPU는 거의 논다.
V1 separate_async run이 replica 8개, max_num_seqs 256, train_batch_size 128, n 16, num_warmup_batches 1이다. tool은 약 20초, turn당 약 200토큰을 생성한다. 가장 그럴듯한 설명은?
V1은 개 prompt를 분배하고 prompt마다 loop 개를 상한 없이 띄우므로 이다. max_num_seqs는 동시 decode만 제한하고, 그것을 넘는 loop는 살아 있는 채로 엔진 안에서 줄을 선다. 초, 가 몇 초면 어느 순간에도 생성 중인 loop는 일부뿐이라 replica당 으로 256보다 한참 작다 — 환경 병목이고, trajectory마다 하나씩이면 pod는 약 4,096개다.
정리
- verl은 분배된 trajectory를 모두 즉시 coroutine으로 돌린다.
AgentLoopWorker→ToolAgentLoop(PENDING → GENERATING ⇄ PROCESSING_TOOLS → TERMINATED)이 가장 한가하고 sticky한 LLM replica와 token-in/token-out으로 대화하며,response_mask는 모델 토큰을 1, tool 토큰을 0으로 표시한다. - 살아 있는 loop: (V1 sync), 최대 (V1 async), (fully-async 레시피, =
concurrent_samples_per_replica, 기본 16), . max_num_seqs는 decode를 제한하지 loop를 제한하지 않는다. 대기 중인 loop도 sandbox를 붙잡고 있다.- Little’s law는 loop를 생성 중과 tool 중으로 나눈다. 서버는 replica당 loop가 를 넘어야 포화한다.
- pod 수는 trajectory별 sandbox면 , 호출별이면 . LLM 병목 → replica를 늘린다. 환경 병목 → 동시성을 늘리거나 환경을 빠르게 한다.
더 읽을거리Further reading
- verl docs, Agent Loop (advance/agent_loop) and code in verl/experimental/agent_loop (main @ 4525109) — AgentLoopBase/Worker/Manager, LLM 서버 클라이언트, chat completion 대신 token-in-token-out을 쓰는 이유.AgentLoopBase / Worker / Manager, the LLM-server client, and why token-in/token-out instead of chat completion.
- Jin et al., Search-R1 (arXiv 2503.09516) and Feng et al., ReTool (arXiv 2504.11536) — tool 출력과 검색 결과 토큰을 손실에서 masking하는 멀티턴 tool RL의 기준 레시피.The reference recipes for multi-turn tool RL that mask retrieved and interpreter tokens out of the loss.
- SandboxFusion (ByteDance Seed) — 여러 언어의 코드를 실행·채점하는 sandbox. verl의 reward 쪽 sandbox_fusion 설정이 이것을 부른다.A multi-language sandbox to run and judge code; verl's reward-side sandbox_fusion config calls it.
- Luo et al., Agent Lightning: Train ANY AI Agents with Reinforcement Learning (arXiv 2508.03680) — 수정하지 않은 agent가 학습기가 제공하는 LLM endpoint를 부르고, 그 호출을 토큰 단위 trace로 기록해 RL한다.Unmodified agents call an LLM endpoint served by the trainer; the calls are recorded as token-level traces for RL.
- Little, A Proof for the Queuing Formula L = λW (Operations Research, 1961) — 정상상태에서 평균 체류 수 = 도착률 × 평균 체류 시간. 이 레슨의 모든 동시성 계산의 바탕.In steady state, mean number in system = arrival rate × mean time in system — the basis of every concurrency estimate here.
- prime-rl docs (inference.md: concurrency controller) and SkyRL Harbor integration docs — sandbox 같은 외부 자원을 묶기 위한 max_inflight, Little's law 기반 in-flight 목표; SkyRL은 sandbox 속도 제한과 sticky routing.max_inflight to bound external resources such as sandboxes and a Little's-law in-flight target; SkyRL's sandbox rate limits and sticky routing.