Repository navigation
[rl] Size generator max_num_seqs for every rollout sequence - #5531
Conversation
| # Ceiling (not target) for the generator's max_num_seqs: the per-generator | ||
| # upper bound on concurrently scheduled sequences. vLLM may admit fewer if KV | ||
| # is tight; this also sets CUDA-graph capture sizes. |
There was a problem hiding this comment.
For cudagraph I can understand. Other than curious what's the main motivation for vllm to have this field? I ask because I wonder if we should work so hard to set it accurate.
There was a problem hiding this comment.
Why this field: (I think 2 is more important, and this field might originated from a serving purspective)
- Preallocation. Per-request state is allocated up front at this size: the CPU token buffer (max_num_seqs x max_model_len), the sampling parameters, the block table and the sampler's logits. CUDA graphs and the persistent batch both need fixed-size buffers.
- Latency control. More concurrent sequences make a larger decode batch, which raises inter-token latency (ITL). Serving setups use this cap to trade throughput against latency. Our A/B showed the same effect: raising the cap from 5 to 12 increased ITL from 38.7 ms to 43.7 ms.
- CUDA graphs. It sets the default capture range. vLLM's default largest capture size is
min(2 x max_num_seqs, 512). - GDN/Mamba layers. Each sequence needs one state block, so with FULL decode CUDA graphs, vLLM refuses to start when max_num_seqs exceeds the number of available state blocks.
512 I don't know why, but it coincidentally aligned with vllm's default cudagraph capture side (point 3 above). It has been there for a while : first async RL loop (#3642)
| async_loop = self.config.async_loop | ||
| max_active_rollout_groups = async_loop.max_active_rollout_groups | ||
| num_validation_groups = len( | ||
| self._rollouter.get_validation_samples(async_loop.validation.steps) | ||
| ) | ||
| rollout_concurrency = max( | ||
| max_active_rollout_groups * async_loop.num_samples_per_prompt, | ||
| num_validation_groups, | ||
| ) |
There was a problem hiding this comment.
most of these are only needed for the util function you introduced -- could you reorganize to make it cleaner?
| peak_load_ratio *= _peak_load_ratio(intra_generator_router.strategy) | ||
| num_dp_ranks = num_generators * generator_dp_degree | ||
| max_num_seqs = min( | ||
| math.ceil(rollout_concurrency * peak_load_ratio / num_dp_ranks), 512 |
There was a problem hiding this comment.
concurrency / num_dp_ranks is the avg load, but I don't think avg load * peak ratio gives the max. Can I get a proof?
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| def _peak_load_ratio(strategy: RoutingStrategy.Config) -> float: |
There was a problem hiding this comment.
maybe make this nested, o/w too many util functions at the top of "main entry" of titan rl
|
@claude review |
|
Claude finished @tianyu-l's task in 2m 49s —— View job Request changes: review posted. All of tianyu-l's comments are still open at HEAD, and the sizing bound holds only under assumptions the PR doesn't state. |
There was a problem hiding this comment.
Verdict: Request changes -- all five of @tianyu-l's comments are still open at HEAD (ad328c8 predates that review). The sizing bound holds only under unstated assumptions, and two helpers plus a test file serve one call site.
What this PR does. Before, each generator DP rank's vLLM max_num_seqs was the even share ceil(rollout_concurrency / (G*D)). Now that share is multiplied by repin_load_ratio for each routing layer that is sticky and has more than one candidate. The goal is to stop vLLM from queueing requests on a rank whose sibling ranks still have free slots.
Example. C=80 concurrent rollouts, G=4 generators, D=4 DP ranks, default sticky routing with r=1.5 on both layers:
main: ceil(80 / 16) = 5 -> busy rank queues at 6 while siblings sit at 3
PR: ceil(80 * 1.5 * 1.5 / 16) = 12
least-loaded or repin=None on both layers -> 5 (unchanged)
Must fix
controller.py:170-177-- @tianyu-l asked for a proof. The inline comment gives one: a per-layer boundload <= floor(r*(C-1)/N)+1 <= ceil(r*C/N). It holds only when the mean is taken over all N candidates, total in-flight is at most C, and r/N <= 1. A drain withhot_swap=Falsebreaks the first condition. Put the argument and its assumptions in the docstring.controller.py:140-178-- @tianyu-l (L140, L623): nest or inline the helpers and drop the tuple return and the extra imports. A sketch is inline.controller.py:591-- @tianyu-l's "why cap at 512?" is unanswered. The 512 comes frommain, but this PR raises how often the cap is hit, so it needs a one-line comment explaining the value (e.g. if it tracks vLLM's default max CUDA-graph capture size, say so).
Should consider
tests/rl/unit_tests/cpu/test_controller_max_num_seqs.py-- imports a private helper and only re-checks the formula. Delete it, or replace it with a routing test that asserts peakreserved_load <= cap(inline).
Questions
- On @tianyu-l's "should we work so hard to set it accurately":
max_num_seqsis a ceiling, and the KV budget still limits admission. Overshooting therefore mostly costs startup time and memory for extra CUDA-graph capture sizes and per-request buffers, while undershooting queues requests (the bug here). If that cost is small,min(ceil(C / G), 512)would be simpler. It ignores the intra-generator layer and needs no reasoning about strategies, since one generator can never hold more than its whole share. Have you measured the startup/memory cost of a larger cap? Your A/B ran 5 vs 12 only. - The A/B ran on a runtime where sticky sessions never repinned. That is the
repin_load_ratio=Nonecase, which this PR leaves at the even share. So the evidence argues for headroom in general, not for this formula in particular.
Not verified: what vLLM's max_num_seqs sizes internally (CUDA-graph capture range, persistent buffers), and whether rollout_concurrency truly bounds in-flight generate calls in multi-turn agent rollouts.
| if num_generators > 1: | ||
| peak_load_ratio *= _peak_load_ratio(generator_router.strategy) | ||
| if generator_dp_degree > 1: | ||
| peak_load_ratio *= _peak_load_ratio(intra_generator_router.strategy) | ||
| num_dp_ranks = num_generators * generator_dp_degree | ||
| max_num_seqs = min( | ||
| math.ceil(rollout_concurrency * peak_load_ratio / num_dp_ranks), 512 | ||
| ) |
There was a problem hiding this comment.
Re @tianyu-l's question about a proof: the formula is an upper bound, but only under assumptions that neither the code nor the docstring states. The argument should be in the docstring.
Per layer, with N candidates and at most C requests in flight in total: load only grows on admission. StickySessionRoutingStrategy.choose (strategies.py) keeps a session on its pinned candidate only while load_before <= r * mean_before. Because mean_before <= (C-1)/N, the load after admission is at most floor(r*(C-1)/N) + 1, which is <= ceil(r*C/N) when r/N <= 1. The least-loaded fallback admits at load_before <= mean, so it stays inside the same bound. Composing the two layers (generator load L_g <= ~r1*C/G, then a DP rank <= ~r2*L_g/D) gives about r1*r2*C/(G*D), up to rounding. I checked some small cases by hand and the ceil absorbed the rounding. I haven't proven that it always does.
The bound depends on assumptions that can fail:
- The mean is taken over the candidates present at that moment, not all N. With
hot_swap=False, a draining generator leaves_candidates()(inter_generator.py:119). While k generators are out, the others' mean isC/(G-k), so the bound becomesr*C/(G-k)and the cap is exceeded. Either say the bound is for the full candidate set, or note it in a TODO next to [rl] Move weight-sync draining from the router into the generator #5253. - Total in flight <=
rollout_concurrency. This needs one in-flightgenerateper rollout, and validation must not overlap training rollouts, sincerollout_concurrencyismax(...), not a sum. r/N <= 1.repin_load_ratio=3with 2 DP ranks breaks thefloor(...)+1 <= ceil(...)step.
As written, the docstring says a candidate can run that far "before sessions move". That describes the threshold, not a bound on load.
| def _peak_load_ratio(strategy: RoutingStrategy.Config) -> float: | ||
| """Return the routing skew factor used to size each generator's sequence cap. | ||
|
|
||
| Sticky sessions stay pinned until their candidate passes ``repin_load_ratio`` x the | ||
| mean load. Keep the previous even-share factor of 1.0 for other strategies | ||
| and sticky routing without repinning; 1.0 is not a bound on their load skew. | ||
| """ | ||
| if ( | ||
| isinstance(strategy, StickySessionRoutingStrategy.Config) | ||
| and strategy.repin_load_ratio is not None | ||
| ): | ||
| return strategy.repin_load_ratio | ||
| return 1.0 | ||
|
|
||
|
|
||
| def _generator_max_num_seqs( |
There was a problem hiding this comment.
This addresses @tianyu-l's comments here and at L623. Two module-level helpers serve one call site. They also need new imports (IntraGeneratorRouter, RoutingStrategy, StickySessionRoutingStrategy) and a tuple return that exists only for the log line. Meanwhile setup_async still keeps generator_dp_degree and num_generator_dp_shards around just to feed the helper and the log.
Smaller version: inline it into setup_async, keeping a nested _repin_ratio(strategy) if you want one:
def _repin_ratio(strategy):
if isinstance(strategy, StickySessionRoutingStrategy.Config) and strategy.repin_load_ratio is not None:
return strategy.repin_load_ratio
return 1.0
peak_load_ratio = (
(_repin_ratio(config.generator_router.strategy) if config.num_generators > 1 else 1.0)
* (_repin_ratio(config.generator.intra_generator_router.strategy) if generator_dp_degree > 1 else 1.0)
)
max_num_seqs = min(math.ceil(rollout_concurrency * peak_load_ratio / num_generator_dp_shards), 512)That removes both top-level functions, the tuple, and the RoutingStrategy import. The diff becomes about 15 lines.
There was a problem hiding this comment.
This file imports the private _generator_max_num_seqs across modules. If the helper is nested or inlined as requested, the import can't work. The tests also re-derive one line of arithmetic: 84 lines and 5 tests, each restating ceil(C * r1 * r2 / N) for a different input. Nothing here checks the property that matters, namely that routing never puts more than max_num_seqs on one rank. Suggest deleting the file. If you want a guard, a short test against StickySessionRoutingStrategy that drives C sessions and asserts that peak reserved_load <= cap would test the bound itself, and would fit with the existing routing tests.
|
i think that there are 3 points here:
|
Let's be clear about "actual max of an llm" and the router: recording the
|
The controller capped each generator DP rank at an even share of the rollout concurrency. Sticky-session routing (the default for both the inter- and intra-generator routers) keeps a session on its generator and DP rank until that one's in-flight load passes repin_load_ratio (1.5) x the mean, so a rank can run up to 1.5 x 1.5 = 2.25x an even share before sessions move. With the cap at the even share, requests queue in vLLM on the busy rank while its siblings have free slots. Seen on a multi-turn SWE agent run (80 sessions over 4 generators x DP 4, cap 5): every rank reached 5 running, 2-9% of gauge samples had requests waiting (up to 3), a sibling rank of the same generator was below the cap in 36% of those, and generator queue time was 1.4 s mean / 33 s max per call. Scale the even share by each multi-candidate routing layer's repin ratio (1.0 for least-loaded, round-robin, or sticky without repinning). Here the cap becomes 12. The KV budget still bounds admission; the extra CUDA-graph capture sizes are small.
Replace the routing-skew sizing (rollout_concurrency x repin_load_ratio per routing layer / DP ranks) with min(rollout_concurrency, 512). Any single DP rank can receive every in-flight rollout sequence, so this cap never binds before the KV budget and needs no assumptions about the routing strategy. Remove the two module-level helpers, their imports, and the unit test that re-derived the formula.
ad328c8 to
31932e6
Compare
|
@claude Review again |
|
Claude finished @wwwjn's task in 2m 41s —— View job Approve -- please address the items before merging (one comment fix; Qwen3.5 startup check requested): review posted. |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The new revision takes the simplest sizing and removes the code the earlier reviews objected to. What's left is a wrong comment and one recipe class (hybrid GDN models) that hasn't been measured. A maintainer still needs to review (@tianyu-l's CHANGES_REQUESTED is still in place).
What this PR does. Each generator DP rank's vLLM max_num_seqs used to be the even share ceil(C / (G*D)). It is now min(C, 512). A single rank can never hold more than every in-flight rollout sequence, so the cap no longer binds before the KV budget does, whatever the routing strategy.
Example.
PR's SWE run: C=80, G=4 x D=4: ceil(80/16)=5 -> 80
terminal-bench Qwen3.5-9B (verifiers_terminal_bench.py:159):
C=48 groups x 32 = 1536, G=8 x D=1:
ceil(1536/8)=192 -> 512 (one GPU, 128K ctx)
Earlier findings
- Proof of the
repin_load_ratiobound: no longer needed, since the formula is gone. - Nest or inline the helpers (@tianyu-l): resolved. Both helpers, the tuple return, and the extra imports are removed.
- Test that re-derived the formula: resolved, deleted.
- "Why cap at 512?" (@tianyu-l): answered in the thread, but the new code comment states a reason that doesn't hold. See below.
Must fix
controller.py:597-599-- the comment says 512 is vLLM's default largest capture size. torchtitan always passes explicit capture sizes, so that default never applies. A suggested rewording is inline.
Should consider
controller.py:600-- the PR body traces the A10G crash to Dao-AILab/flash-attention#3117. It also says somemax_num_seqsvalues (e.g. 48 with the default 2048-token budget) still give FA2 dummy requests 65+ query tokens during profiling. Per CLAUDE.md principle 3, add a one-lineTODOwith that issue link here. Then the next illegal memory access at generator startup can be traced back to it.
Questions
- In your reply to @tianyu-l, you noted that with full decode CUDA graphs, GDN/Mamba models refuse to start when
max_num_seqsexceeds the available state blocks. The startup tables only cover dense Qwen3-0.6B. The recipe this change affects most is the Qwen3.5-9B terminal-bench one above: 192 -> 512 on one GPU,FULL_DECODE_ONLY, 248K vocab for the sampler warmup. A rough estimate is 24 GDN layers x ~1 MiB of bf16 state, about 12 GiB for 512 sequences. That likely fits on 80 GB, but could you start that generator once (ortorchtitan.rl.generatewith Qwen3.5-9B, TP1,max_num_seqs=512) and report init time and KV GiB?
Not verified: vLLM's hybrid state-block startup check and the sampler-warmup size for a 248K vocab; RL GPU integration tests are still queued.
| # every rollout sequence and let the KV budget limit admission. Capped at 512, | ||
| # vLLM's default largest CUDA graph capture size, to bound per-request buffers; | ||
| # this also sets CUDA-graph capture sizes. |
There was a problem hiding this comment.
The comment says 512 is "vLLM's default largest CUDA graph capture size", but that default never applies here. VLLMCudaGraphConfig.get_vllm_compilation_config (rl/generator/vllm/config.py:161-164) always passes explicit cudagraph_capture_sizes. Their maximum is max(max_num_seqs, max_num_batched_tokens) in FULL mode and max_num_seqs in FULL_DECODE_ONLY, so vLLM's min(2 x max_num_seqs, 512) rule is never used. In your reply you said you don't know where 512 came from (#3642), so the comment shouldn't give a reason the code doesn't support. Describe what the cap bounds, which your measurements back up:
| # every rollout sequence and let the KV budget limit admission. Capped at 512, | |
| # vLLM's default largest CUDA graph capture size, to bound per-request buffers; | |
| # this also sets CUDA-graph capture sizes. | |
| # every rollout sequence and let the KV budget limit admission. The 512 cap | |
| # bounds per-request buffers and the sampler warmup taken from the KV budget; | |
| # max_num_seqs is also a CUDA graph capture size (see VLLMCudaGraphConfig). |
Summary
max_num_seqsis vLLM's cap on concurrently running sequences per engine. Requests above it wait in vLLM's queue even when the KV cache has room. The controller sized each generator DP rank's cap at the even share,ceil(rollout_concurrency / (num_generators x dp_degree)). Sticky routing keeps a session on its generator and DP rank until that rank passesrepin_load_ratiox the mean load, so ranks regularly run above the even share and queue requests while sibling ranks have free slots.This PR sets the cap to
min(rollout_concurrency, 512). No rank can ever hold more than every in-flight rollout sequence, so the cap no longer binds before the KV budget, and the value does not depend on the routing strategy. The 512 cap is unchanged from main.For 80 concurrent sequences over 4 generators x DP 4, the cap changes from
ceil(80 / 16) = 5to 80.The previous revision multiplied the even share by
repin_load_ratiofor each routing layer (5 -> 12). That value is an upper bound only under extra assumptions: a least-loaded fallback, and no generator draining withhot_swap=False. The measurements below show a larger cap costs little, so exact sizing is not worth those assumptions.Cost of a larger cap
max_num_seqssizes three things in vLLM:max_num_seqs x max_model_len;In the default
FULLmode the capture cap is alreadymax(max_num_seqs, max_num_batched_tokens), somax_num_seqsadds one capture size.Generator startup with Qwen3-0.6B, TP4,
FULLCUDA graphs, standalonetorchtitan.rl.generate:Graph capture took 4-5 s on A100 and 13-18 s on GB300 at every value. GB300 init varied between 33 and 85 s from run to run, with no trend in
max_num_seqs. A100 at 80 is missing; see below.Evidence for headroom
In a multi-turn SWE agent run with 80 sessions over 4 generators x DP 4, all ranks reached the old cap of 5. In 78 of 218 waiting-gauge samples, a sibling rank of the same generator was below the cap. Generator queue time reached 1.4 s mean and 33 s max per call.
A step-1 A/B with similar response lengths raised the cap from 5 to 12:
That runtime's sticky routing did not repin, so the A/B shows the cost of a binding cap under skew. It is not an end-to-end throughput result.
CI failure on the previous revision
The previous revision failed
rl_grpo_checkpoint_resumeon A10G with an illegal memory access.softmax_lsewith the padded layout, which runs out of bounds for varlen + paged KV.seq_len = 1for every request, splitting 2048 query tokens acrossmax_num_seqsrequests. Any dummy request with 65 or more query tokens reaches the early exit.max_num_seqs = 48, so 2048 / 48 leaves 74 tokens for the last request. Main gives 32 (64 tokens each) and this revision gives 64 (32 each), so neither reaches it.The bug is not fixed here. On FA2 GPUs, any
max_num_seqsthat leaves a dummy request with 65+ query tokens writes out of bounds during profiling. On main that includes the 8 and 22 values of some CI configs, where the writes land in mapped memory and do not crash.Tests
test_verifiers.pyandtest_dapo_math.pywere not run locally because their optional packages are missing.pre-commit run --files torchtitan/rl/controller/controller.py: passed. Pyrefly was not run; RL is excluded from the repo's Pyrefly project.