Repository navigation
[rl] Admit new rollout groups by KV room, before their envs start - #6420
felipemello1 wants to merge 6 commits into
Conversation
With `generator_router.admission=KVRoomAdmission.Config()`, the controller awaits `acquire_group` before a rollout group's envs start. The router places the group on the generator with the most KV room left, or retries each second; every call of the group then goes to that generator. Validation groups go first. Calls of a started group never wait. The router counts the room itself (`KVRoomAdmission`): an engine counts an idle session's cached KV as free. Per session it charges the last prompt + reply while idle, the latest prompt + the mean reply while a call runs, and the mean first prompt for a session that has not called. GDN states are charged per `KVCacheCapacity`, which each engine reports once at start. SGLang reports its token pool, the state slot cost and its state pool, and now caps the states kept per cached path (`mamba_max_states_per_path=2`) for linear attention models, so an idle session holds a bounded number. A GPU test bounds what 2 sessions of one group hold by that capacity. For every user: a shutdown cancel now releases the cancelled rollout and validation groups, waiting at most 30 s, then logs one warning line.
SGLang's unified pool splits one byte buffer between tokens and state slots, so its slots are the buffer over one state's size: a session's blocks, states included, already bound its slots. `KVCacheCapacity` drops `num_state_slots`, and `place` and the charged fraction count blocks only. A call of a session that `release_session` released now raises, as a call of a released group does, so a late call's history is not counted as a new first prompt. A call that raised (a 0-token reply) no longer pulls the mean reply down. SGLang: the per-path state cap's comments say it is soft (a path can also hold the fork's state), the private `_calculate_mamba_ratio` call gets a TODO, and the README says what an idle session keeps.
Without the unified pool (`enable_unified_memory` off, as SGLang's MTP path builds it), SGLang keeps linear attention states in a fixed pool of state slots that counting tokens doesn't bound. `kv_cache_capacity()` treated that pool as the unified one; it now checks the pool kind (`ChainAllocator`) and raises on the classic pool, with its sizes. It reads the sizes the build fixed when called; `__init__` keeps only the token count, read while no request holds memory. New 1-GPU class `TestSGLangBitwiseParityGDNClassicPool` builds the Qwen3.5 debug model on the classic pool and expects the raise; the B200 job runs it next to the KDA class.
|
Claude finished @felipemello1's task in 3m 25s —— View job Request changes -- review (posted as a PR review with inline comments). |
There was a problem hiding this comment.
Verdict: Request changes -- this adds about 1,200 lines and a config option that no recipe sets, and the gain it is for has not been measured. It also changes SGLang prefix caching for every linear-attention run, with admission off too, and that has not been measured either.
What this PR does. With InterGeneratorRouter.Config.admission set, the router keeps a block count of what each placed group holds (KVRoomAdmission). A newly claimed group waits in acquire_group until one generator has room for all its sessions, and every call of that group then goes to that generator. SGLang reports its pool size and the GDN-state cost through a new kv_cache_capacity(). Separately, SGLang now caps cached GDN/KDA states at 2 per prefix-tree path for every linear-attention run.
Example. Two generators of 1,000 blocks each, 16-session groups. The running mean is 2,000 prompt tokens plus 500 reply tokens, which charges 40 blocks per session, so 640 per group:
main: every claimed group starts its envs; sticky routing spreads sessions by load.
Once the idle histories outgrow the KV, the engine evicts them and the next turn re-prefills.
this PR: g0 -> gen0 (640 charged), g1 -> gen1 (640), g2 waits: neither gen has room (640 + 640 > 950).
It retries every 1 s, with no env started, until a session or group release brings a charge under 310.
Must fix
- Gate: no evidence of value yet. By the description's own account, the cost is "not measured on this stack" and no run has used admission. The 95% line is carried over from a different holder, and the option is off everywhere.
.claude/rules/config.mdsays to expose only options that a verified recipe uses, andCONTRIBUTING.mdasks for proof of value. Land this together with the cluster A/B againstadmission=None(prefix-hit rate by idle time, end-to-end tok/s) and turn it on in the agent recipe in this PR, instead of leaving a TODO at the default. torchtitan/rl/generator/sglang/engine.py:493--mamba_max_states_per_path=2changes caching on the default path. It is reserved, so it can't be reverted, and it is unmeasured. Measure it, or apply it only for admission (see the inline comment).torchtitan/rl/generator/sglang/engine.py:558-- the DP > 1 check belongs inController.Config.__post_init__, not atstart_engine_loop.torchtitan/rl/generator/sglang/engine.py:577-580-- the private_calculate_mamba_ratio()call needs an upstream issue link in its TODO.
Should consider
torchtitan/rl/routing/admission.py:190-- sessions that haven't called yet are counted per session, not per rollout, so multi-session rollouts and retries under-charge.tests/rl/unit_tests/gpu/test_sglang_bitwise_parity.py:688-- a GPU engine build to test a raise that can't be reached until #6414.torchtitan/rl/generator/sglang/README.md:213-- the text overstates the cap as a hard bound, and admission has no user-facing doc.
Questions
- Dense models on SGLang with admission on:
kv_cache_capacity()readsallocator.state_slotson the non-ChainAllocatorpath. Does SGLang's plainTokenToKVPoolAllocatorhave that attribute? No test callskv_cache_capacity()on a dense model, and I couldn't read the SGLang source here (unverified).
Details
-
Overlap. I searched open PRs for "admission", "kv_cache_capacity", "mamba_max_states_per_path", "inter_generator router" and "SGLang MTP". They are all in the author's stack:
- #5919: the base.
- #6008: vLLM capacity, stacked on this PR.
- #6414: SGLang MTP. It turns the unified pool off and so makes the classic-pool raise reachable.
- #6291: KV occupancy metrics.
None of them supersedes this PR.
-
Ledger correctness. I checked these and they hold:
reserveraises before it touchesreserved_load.end_callpops_running_callsbefore it looks up the group, so a late call doesn't leak.- Calling
release_groupsagain is a no-op. - A waiter dropped by
release_groupsexits without being placed. - A generator with no group always fits, so an oversized group can't deadlock.
- Training and validation group ids can't collide: one counts up, the other counts down from -1.
One gap is left: a caller cancelled while awaiting
reserve.call_oneleaks one_running_callsentry until its group is released. That predates this PR, and the TODO atcontroller.py:747notes it. -
Shutdown release. It runs with admission off too, and on crash paths. The waits run concurrently, so the delay is at most about 30 s in total. The release is needed under admission: a cancelled group would otherwise hold its charge, and the post-training validation might never get placed.
-
Design note, not a finding. With admission on,
reservestill callsstrategy.pinned_candidateand ignores the result, and__post_init__bans a non-default strategy. That works. If a second admission policy ever appears, admission andstrategyshould become one selector.
Not verified: the SGLang internals (ChainAllocator.admission_rules().state_slot_cost, _calculate_mamba_ratio(), the mamba_max_states_per_path ServerArgs field). I also couldn't run the CPU tests in this sandbox.
Before merge: fill in the human-written summary.
| server_kwargs["enable_unified_memory"] = True | ||
| # Bound the states an idle session keeps, so admission can count them. The cap never | ||
| # evicts a path's tail, a fork or a locked state: a session keeps 2 of its own. | ||
| server_kwargs["mamba_max_states_per_path"] = _MAMBA_MAX_STATES_PER_PATH |
There was a problem hiding this comment.
Must fix: this cap is set for every linear-attention SGLang run, admission=None (the default) included. Adding the key to _TORCHTITAN_SERVER_ARGS (line 97) also takes away extra_server_args as a way to get the old behaviour back. The PR's own table lists the prefix-cache losses on the default path:
- a late sibling caches 0 of 600 shared-prompt tokens, against 576 on main;
- a rewritten history resumes from an earlier checkpoint.
No run measures either effect with admission off. CLAUDE.md principle 6 says main-path performance must not change silently.
Two ways to close this:
- (a) Measure it. Take an existing GDN recipe with admission off and compare prefix-cache hit rate and output tok/s, cap vs no cap.
- (b) Apply the cap only when admission needs it. Drop the key from
_TORCHTITAN_SERVER_ARGS, leave SGLang's default alone, and havekv_cache_capacity()readnum_idle_statesfromserver_args.mamba_max_states_per_path. It raises aValueErrorwhen that field is unbounded. The recipe that turns on admission then sets the field throughextra_server_args. That is about 10 lines, and the default path is left untouched.
| def kv_cache_capacity(self) -> KVCacheCapacity: | ||
| """Return the token pool's size and what one session takes in it; it reads only | ||
| sizes the build fixed.""" | ||
| if self._dp_size > 1: |
There was a problem hiding this comment.
Must fix: this rejects a configuration that is already known at config time, but it only raises at start_engine_loop, after every engine is built and its loop has started. .claude/rules/config.md says to validate in the owning config's __post_init__.
Controller.Config.__post_init__ sees both generator_router.admission and generator.parallelism.data_parallel_degree. That degree is the same value that sets SGLang's attn_dp_size (line 448) and vLLM's DP. Move the check there:
if self.generator_router.admission is not None and self.generator.parallelism.data_parallel_degree > 1:
raise ValueError(
"generator_router.admission needs generator.parallelism.data_parallel_degree=1: "
"IntraGeneratorRouter spreads a group's sessions over DP ranks without looking at their KV"
)That one check covers both engines, so #6008 doesn't need its own copy.
| # TODO: SGLang has no public field with the states per running request it sized | ||
| # its state pool with, so this calls its private sizing method, which reads | ||
| # only the build's settings. | ||
| num_running_states=kv_cache_configurator._calculate_mamba_ratio(), |
There was a problem hiding this comment.
Must fix: this TODO covers a call to SGLang's private _calculate_mamba_ratio() but has no upstream issue link, which CLAUDE.md principle 3 requires. The description says the issue text is ready. File it and put the link in this TODO before merge.
| ) | ||
|
|
||
| # Sessions that have not called yet; retried attempts can open more than the group. | ||
| num_not_called = max(0, group.num_sessions - group.num_started) |
There was a problem hiding this comment.
Should consider: num_started counts every session that has called. That includes retries and the extra sessions of a multi-session rollout, the sub-agent case the description has in mind.
Example: a group of 8 rollouts where rollout 0 opens 4 sessions before any sibling calls. num_started reaches 4, so only 4 of the 7 siblings that haven't called are still charged. Those 3 uncharged sessions are free room as far as place can tell, which is the exact over-admission this ledger exists to prevent.
Two ways to fix it:
- Count rollouts that have started, not sessions.
start_callcould take the rollout index, which the session id already carries as"<group>/<i>". - Or document that admission assumes one session per rollout, and raise once
num_started > num_sessions.
| dist.is_initialized() or "RANK" in os.environ, | ||
| "requires torchrun launcher", | ||
| ) | ||
| class TestSGLangBitwiseParityGDNClassicPool(unittest.TestCase): |
There was a problem hiding this comment.
Should consider: at this PR's head, no torchtitan config can reach the classic pool. enable_unified_memory is reserved and forced on for linear attention (engine.py:490), so this class only gets there by patching ServerArgs.
That makes it a full SGLang engine build in B200 CI, about 64 s plus a torchrun launch, to check a raise that has no consumer until #6414 lands. The description already says #6414's test class will assert this raise.
Suggestions:
- Keep the cheap raise in
engine.py, but drop this class and the CI entry, and let [rl] SGLang generator: MTP speculative decoding for Qwen3.5 #6414 test the path it creates. - If it stays,
cuda_graph="none"avoids the capture cost. - The class checks no parity, so the
BitwiseParityname doesn't fit it.
| referenced KV only when nothing else is left, so the next turn usually reuses | ||
| the whole history; no request ever waits for a held session. | ||
|
|
||
| Linear attention models keep at most 2 GDN or KDA states of each session cached |
There was a problem hiding this comment.
Should consider: "keep at most 2" reads as a hard bound. The code comment (engine.py:491-492) and the GPU test (which allows +1 shared state) treat it as a soft cap: SGLang never evicts a path's tail, a fork, or a locked state. Suggest: "keep about 2 ... (a soft cap: SGLang never evicts a path's tail, a fork or a locked state)".
Separately, admission itself has no user-facing doc. A few lines next to this one, or in torchtitan/rl/README.md's routing paragraph, would cover it:
- how to enable it (
InterGeneratorRouter.Config(admission=KVRoomAdmission.Config())); - its constraints: SGLang only in this PR, DP 1, the unified pool, and the default strategy;
- its metric keys.
…iewed heads) git diff 864785c 420ef1e (branch 203/kv-classic-count), applied in place of 011c084 (cherry-pick of aec77aed1, reverted in the previous commit): - 1018fb9 "[rl] SGLang capacity: charge a running session the states it holds" (pytorch#6420's head: running = cap + 1 + tracking on the unified pool too); - 420ef1e "[rl] Admission: count GDN states on SGLang's separate state pool" (the separate-pool count, split KV/state gauges, the state-gauge router test). One conflict: 864785c's TODO above the separate-pool raise, which this tree never had; the raise goes, as in 420ef1e.
Summary (human-written)
Agent details
Stays a draft until a cluster run with
admissionon. Stacked on the code of "Evict an ended rollout's KV from vLLM's prefix cache": this PR's base branch holds that PR's head. The vLLM capacity is the next PR.TLDR: Opt-in
InterGeneratorRouter.Config.admissionholds each new rollout group, before its envs start, until one generator has KV room for the whole group. Then every call of the group goes to that generator. The router counts the room itself (KVRoomAdmission): vLLM and SGLang both count an idle session's cached history as free. SGLang reports its capacity in this PR. One change applies with admission off too: SGLang's soft cap on cached GDN and KDA states per prefix-tree path is now 2 (unlimited before), so an idle session keeps 2 of its own.Problem
admissionon measures it: prefix-cache hits by how long a session was idle, against a run without.Solution
GenerationEngine.kv_cache_capacity()returnsKVCacheCapacity: its KV blocks, the attention block sizes, and the GDN states a session takes while idle and while running.start_engine_loopreads it from every generator's rank 0, so a setup admission can't count raises there.Controller._rollout_loopawaitsacquire_group(group_id, num_sessions=num_samples_per_prompt, validation=False)before the group's envs start. Each validation group acquires withvalidation=True, and training groups wait while one waits. A waiting group holds no env, sandbox or KV.KVRoomAdmission.placepicks the generator with the most block room left after the group. If none fits, the group tries again in 1 s. Before any first prompt, only a generator with no group takes one.reserve(..., group_id, num_prompt_tokens)sends each call to its group's generator and charges the prompt.release_reservation(..., num_reply_tokens)records the reply.release_sessionandrelease_groupsend the charge. A release of something already gone is a no-op. A call of a released session or group raises to its caller.SGLangEnginesetsmamba_max_states_per_path=2for linear-attention models (GDN and KDA). An idle session then keeps 2 states of its own: its newest prompt's checkpoint and its reply's end. The charge counts both. SGLang's unified pool splits one byte buffer between tokens and state slots, so counting a state's tokens (blocks_per_state) also bounds the slots: 7,413 slots x 1,590 = 11,786,670 of 11,786,684 blocks.admission=None, the default: routing, and the controller's calls apart from a no-opacquire_groupper group.What SGLang keeps per session, with the cap (Qwen3.5-0.8B on 1 GB300, 2 sessions of one 600-token prompt; states sit at multiples of 64 tokens):
Results
You may ask:
NOTE:
admission=None). The TODO at the default: set it in the agent recipes once a cluster A/B againstadmission=Noneshows a gain.start_engine_loop:IntraGeneratorRouterspreads a group's sessions over replicas without looking at KV.kv_cache_capacity()reads it. Rerun the capacity test with MTP on when both land.enable_unified_memoryoff), linear attention states live in the request table's own pool, a fixed slot count that counting tokens doesn't bound. TorchTitan turns the unified pool on for every linear-attention model, but the SGLang MTP path turns it off.kv_cache_capacity()checks the pool kind (ChainAllocator) and raises there, with the pool's sizes (TestSGLangBitwiseParityGDNClassicPool, a real classic-pool build on 1 GPU, added to the B200 job next to KDA). Whichever of the SGLang MTP PR and this one lands second counts the classic pool's slots. When the SGLang MTP PR lands, its test class asserts this raise, andTestSGLangBitwiseParityGDNClassicPoolcan go.sliding_windoworlayer_types(torchtitan/rl/generator/sglang/registry.py:72-89), and its architecture is not in SGLang's hybrid-SWA list, so SGLang setsis_hybrid_swa=False(configs/model_config.py:1272-1276,is_hybrid_swa_modelat:2759). A probe agrees (Muse Glimmer debug model at TP 1:TokenToKVPoolAllocator,is_hybrid_swa=False, 36,115,312 tokens). vLLM gives windowed layers their own KV cache group, which the vLLM PR'skv_cache_capacity()refuses. If SGLang ever builds its window pool for a TorchTitan model, the pool reports the smaller of its two sizes (SWATokenToKVPoolAllocator.size), so admission under-admits, which is safe.kv_cache_capacity()reads SGLang's private_calculate_mamba_ratio(). Its TODO gets an SGLang issue link once the issue is filed (text ready, not filed yet).reserveraises to it: its group is already released.Test plan
TestSGLangBitwiseParityGDNClassicPool::test_kv_cache_capacity_raises: the Qwen3.5 debug model at TP 1 built withenable_unified_memoryoff;kv_cache_capacity()raises. 1 passed on 1 GB300 (64 s).test_kv_cache_capacity_bounds_what_sglang_holds(GDN classes, B200 CI): 2 sessions, 3 turns, the third rewriting a reply. It bounds the states on each session's path and the state slots while running by the capacity's charge, and checks each turn resumes from the deepest state on its prompt's path. Run locally on 1 GPU through a runner (the classes need 2), with and without HiCache: passed; with SGLang's cap turned off at runtime, it fails (3 own states > 2).release_reservation.broadcastandrelease_sessionafterrelease_groups, a cancelled waiter.