Skip to content

[rl] vLLM generator: report KV cache capacity for admission - #6008

Draft
felipemello1 wants to merge 3 commits into
felipemello1/kv-room-admissionfrom
felipemello1/kv-admission-gate
Draft

felipemello1 wants to merge 3 commits into
felipemello1/kv-room-admissionfrom
felipemello1/kv-admission-gate

Conversation

@felipemello1

@felipemello1 felipemello1 commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Agent details

Stays a draft until a cluster run with admission on. Stacked on "Admit new rollout groups by KV room, before their envs start", which adds KVCacheCapacity and the router's admission.

TLDR: VLLMEngine.kv_cache_capacity() reports vLLM's KV cache to the router's admission: its blocks, each attention group's block size, and the GDN state blocks a session takes. With it, InterGeneratorRouter.Config.admission works with vLLM generators. Nothing changes unless a recipe sets admission.

per KV cache group (vLLM's kv_cache_config, fixed at build):
  full attention (and MLA, the MTP draft layer)   a block per block_size tokens
  align-mode Mamba (GDN)                          1 block per state: 1 state idle (the one the evictor keeps),
                                                  2 + speculative + prefill-checkpoint blocks + 1 while running
  anything else (sliding window, chunked local)   raises at start_engine_loop
num_blocks = kv_cache_config.num_blocks - 1 (block 0 is vLLM's null block)

Problem

  1. The admission PR below places groups by each generator's kv_cache_capacity().
  2. GenerationEngine.kv_cache_capacity() raises NotImplementedError by default, and only SGLang implements it there.
  3. So admission can't run on vLLM generators.

Solution

  1. VLLMEngine.kv_cache_capacity() walks scheduler.kv_cache_config's groups, as the table above shows. The state counts follow vLLM's own per-request bound (MambaSpec.max_memory_usage_bytes).
  2. Idle sessions keep 1 GDN state per group: the session KV evictor drops a live session's superseded states.
  3. It raises for data parallelism > 1 and for KV cache groups it can't count.
  4. Unchanged: everything with admission=None.

Results

CPU, vLLM's real KVCacheManager (1 attention group + 3 align GDN groups, 16-token blocks, 120 blocks):
  kv_cache_capacity() = 119 blocks, (16,), 3 blocks per state, 1 idle, 3 running
  2 sessions of one 40-token prompt, prefilled in one step (each caches its own copy, as vLLM does for a
  group's first calls), 3 turns:
    blocks held while running - running charge:   -19 to 0 (never over)
    blocks held / charged while idle:              15 / 16, 21 / 22, 25 / 26
    without the base PR's one-copy rule:          20 / 16 after turn 0
Qwen3.5-27B on one GB300 with fp8 KV: 3,411 blocks -> num_blocks 3,410, admission line 3,239.

You may ask:

  • Why not read the free blocks? vLLM counts an idle session's cached blocks as free, which is what admission keeps room for.
  • Why charge the shared prompt's GDN states nowhere? They are the group's: the per-session prompt over-count in the admission PR covers them when G x ceil(prompt / prefill chunk) <= (n - 1) x ceil(prompt / block), for n sessions and G GDN groups (3 on Qwen3.5).

NOTE:

  • Sliding-window and chunked-local KV groups raise (CPU test), and so does a UniformTypeKVCacheSpecs group (same-type layers with different shapes); no TorchTitan model builds one. A subclass of FullAttentionSpec with a window is charged its full context, which over-counts.
  • Not run with MTP drafts: they add num_speculative_blocks state blocks per running request, which the charge counts from vLLM's spec. The evictor PR keeps one copy of each block MTP caches again (CPU stress with use_eagle=True: 0 extra copies in 217 idle checks). Rerun the capacity test with use_eagle=True when the vLLM MTP stack rebases.
  • kv_cache_capacity() reads the scheduler's kv_cache_config through the private engine_core.engine_core, as the engine loop already does (the TODO at _has_unfinished_local_requests names it).
  • Idle sessions stay within the charge of 1 GDN state per GDN group. In the evictor PR's harness run at its head, no 2 s sample held more unshared GDN states than that per idle rollout (0 of 127 samples above it; worst 1.00). In a CPU stress of the evictor on vLLM's KV cache manager (40 seeds x 400 random actions), 0 of 217 idle checks held more than 1 own state per group, with and without MTP drafts. A superseded state that other sessions count (a group prompt's, or one a late sibling cached again) goes once at most one session counts it: at once if that session is idle.

Test plan

pytest tests/rl/unit_tests/cpu/test_session_kv_evictor.py -k kv_cache_capacity   # 2 passed
pytest tests/rl/unit_tests/cpu   # 791 passed, 2 failed, 8 skipped
# The 2 failures, test_terminal_cleanup_preserves_block_identity[FINISHED_ABORTED-True] and [FINISHED_ERROR-True],
# fail on main too in the same venv: main names the queue `kv_holding_waiting`; the vLLM wheel that
# `scripts/install_rl_env.sh` pins names it `skipped_waiting`.
  • test_vllm_kv_cache_capacity_bounds_what_vllm_keeps builds the capacity from vLLM's real KV cache config and runs 2 sessions of one group for 3 turns: at every step, blocks held <= the running charge; while idle, charged - 2 - (one partial block per session) <= held <= charged. With num_idle_states=2, its idle lower bound fails, and without the base PR's one-copy rule its idle upper bound fails (mutation runs).
  • test_vllm_kv_cache_capacity_raises_for_a_sliding_window_kv_cache_group: a sliding-window group raises ValueError naming it.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 10, 2026
`VLLMEngine.kv_cache_capacity()` reports the KV cache's blocks and what one
session takes in them, for the router's admission:

- full attention groups (MLA and the MTP draft layer included): a block per
  block_size tokens;
- align-mode Mamba (GDN) groups: idle, the one state the session KV evictor
  keeps; running, vLLM's state blocks per request plus that one;
- any other KV cache group, or data_parallel_size > 1, raises.

A test runs two sessions of one group through vLLM's real KV cache manager
and the evictor, and checks that what vLLM keeps stays under the charge.
…d groups

The capacity test now prefills the 2 siblings' first calls in one step, as
vLLM schedules a group's first calls, so each caches its own copy of the
shared prompt; the bounds still hold once the evictor keeps one copy. A new
test checks that a sliding-window KV cache group raises. The TODO on the
private `engine_core.engine_core` reads names the `kv_cache_config` read.
@felipemello1
felipemello1 changed the base branch from felipemello1/kv-evict-on-rollout-end to felipemello1/kv-room-admission November 27, 2026 22:44
@felipemello1
felipemello1 force-pushed the felipemello1/kv-admission-gate branch from f5edcc8 to 9b9395f Compare November 27, 2026 22:44
@felipemello1 felipemello1 changed the title [rl] Admit new rollout groups by KV room, before their envs start [rl] vLLM generator: report KV cache capacity for admission Nov 27, 2026
@felipemello1
felipemello1 added this pull request to stack #6421 November 27, 2026 22:45
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review 9b9395f. This PR is rebased onto #6420, its new base; the diff is only the vLLM capacity report.

@claude

claude Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 4m 27s —— View job


Approve -- please address the items below before merging (1 mechanical must-fix: move the duplicated DP check into the config): review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: Approve -- please address the items below before merging. The capacity report is small, raises on every KV cache group it can't count, and a CPU test checks it against vLLM's real KVCacheManager. The one must-fix item is a mechanical move of a duplicated check.

Reviewed at 9b9395f against felipemello1/kv-room-admission (#6420): +152/-2 across 2 files, 54 lines of logic.

What this PR does. VLLMEngine.kv_cache_capacity() reads scheduler.kv_cache_config and turns it into the base PR's KVCacheCapacity:

  • each FullAttentionSpec group (MLA included) adds its block_size;
  • each align-mode MambaSpec group adds 1 block per state;
  • any other kind of group raises.

The idle charge is 1 state, the one the evictor keeps. The running charge is vLLM's per-request state blocks plus 1. Without it, InterGeneratorRouter.Config.admission raises NotImplementedError on vLLM generators.

Example. Qwen3.5-like layout: 1 attention group plus 3 align GDN groups, 16-token blocks, 120 blocks.

kv_cache_capacity() -> num_blocks=119 (block 0 is the null block), attention_block_sizes=(16,),
                       blocks_per_state=3, num_idle_states=1, num_running_states=2+0+0+1=3
session of 40 tokens, running: ceil(40/16) + 3*3 = 12 blocks
session of 50 tokens, idle:    ceil(50/16) + 3*1 = 7 blocks
add a SlidingWindowSpec group -> ValueError at start_engine_loop
data_parallel_size=2          -> ValueError at start_engine_loop

Must fix

  1. torchtitan/rl/generator/vllm/engine.py:705 -- the DP > 1 raise copies SGLang's word for word, and its reason is about the router. Raise it once in Controller.Config.__post_init__ and delete both engine copies (see the inline comment).

Should consider

  • torchtitan/rl/generator/vllm/engine.py:719 -- the GDN group test is written out again here, apart from the evictor's at session_kv_evictor.py:116. The idle charge of 1 state holds only while both pick the same groups (see the inline comment).
Details
  • Gate. Admission can't run on vLLM today: the base class raises NotImplementedError (engine.py:134). The engine owns its KV layout, so the engine is the right place for this. The private engine_core.engine_core read goes through the existing TODO linking vllm#69786, the same handle the evictor and the engine loop already use. No new knob, config field or dependency. Nothing changes unless admission is set.
  • Counterparts. SGLang's kv_cache_capacity has the same shape: a DP raise, then per-pool sizes. The only part that should be shared between the two is the DP rule (must-fix 1). The null-block - 1 matches #6291 (num_gpu_blocks - 1).
  • Safety of the counts.
    • FullAttentionSpec carrying a sliding_window/attention_chunk_size is charged its full context. That over-counts, which is safe.
    • SlidingWindowSpec, UniformTypeKVCacheSpecs, and MambaSpec in "none" mode raise. Banning is right; "all" mode already raises in linear_attention.py:110.
    • Taking the max of num_running_states across GDN groups over-counts if the groups differ, which is safe.
  • Tests. test_vllm_kv_cache_capacity_bounds_what_vllm_keeps guards the invariant that matters (charge >= what vLLM holds, against the pinned wheel), and it sits next to the evictor fixtures it reuses. The sliding-window test guards a silent under-count if the isinstance dispatch is loosened. Both are cheap CPU tests.
  • Overlap search. Searched kv_cache_capacity, admission KV, vllm engine.py kv cache. Found:
    • #6420 (the base);
    • #6291 (KV occupancy logging; no conflict);
    • #6287 (vLLM MTP: rerun the capacity test with use_eagle=True when it lands, as the description says);
    • #5956 (model runner V2; touches initialize_kv_cache, not scheduler.kv_cache_config).

Not verified: I couldn't read vLLM's source here, so I didn't check that 2 + num_speculative_blocks + num_prefill_checkpoint_blocks matches MambaSpec.max_memory_usage_bytes. The CPU test covers it only with both extra counts at 0, and the MTP path (num_speculative_blocks > 0) hasn't been run. No cluster run with admission on yet. A maintainer still needs to review.

Before merge: fill in the human-written summary.

Comment on lines +705 to +710
if self.data_parallel_size > 1:
raise ValueError(
f"Admission needs vLLM's data_parallel_size at 1, got "
f"{self.data_parallel_size}: IntraGeneratorRouter spreads a group's sessions "
"over the DP replicas without looking at their KV."
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a second copy of the DP rule in SGLangEngine.kv_cache_capacity (sglang/engine.py:558-563). The reason it gives ("IntraGeneratorRouter spreads a group's sessions over the DP replicas") is about the router, not the engine, and it is known at config time. As written, every new engine has to copy the check, and a DP > 1 run with admission set only fails once start_engine_loop has spawned every generator.

Smallest fix: raise once in Controller.Config.__post_init__ (controller/controller.py:446), which already reads both values:

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, got "
        f"{self.generator.parallelism.data_parallel_degree}: IntraGeneratorRouter spreads a "
        "group's sessions over the DP replicas without looking at their KV."
    )

Then delete this block and the SGLang one. generator.py:304 already checks that engine.data_parallel_size equals this degree. That is about -12/+8 LoC.

spec = kv_cache_group.kv_cache_spec
if isinstance(spec, FullAttentionSpec):
attention_block_sizes.append(spec.block_size)
elif isinstance(spec, MambaSpec) and spec.mamba_cache_mode == "align":

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should consider: num_idle_states=1 is only a safe charge for the groups the evictor actually sweeps, and the evictor picks those groups with the same test at session_kv_evictor.py:116-117. If one copy of the test changes and the other doesn't (say the evictor starts handling "all" mode, or this branch accepts a group the evictor skips), the idle charge silently under-counts. Either expose the evictor's GDN group ids publicly and count blocks_per_state from them, or add a one-line comment here pointing at the evictor's test so both stay the same.

felipemello1 added a commit to felipemello1/torchtitan that referenced this pull request Nov 29, 2026
…ng's own check goes (r10 review C6)

P4's floors can leave nothing: SGLang raised in kv_cache_capacity, vLLM
returned 0 or less, and admission then divided by it (0: ZeroDivisionError;
negative: every group fits). KVRoomAdmission.__init__ now checks both
engines' numbers in one place and names the generator and its capacity.

Test: test_a_generator_with_no_kv_blocks_to_fill_raises (fails before: no
raise).

PR placement: P2 (admission) and P4 (SGLang's check removed). The pytorch#6008
floor branch gets the same check in its admission.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant