Skip to content

[rl] Evict an ended rollout's KV from vLLM's prefix cache - #5919

Draft
felipemello1 wants to merge 24 commits into
pytorch:mainfrom
felipemello1:felipemello1/kv-evict-on-rollout-end
Draft

felipemello1 wants to merge 24 commits into
pytorch:mainfrom
felipemello1:felipemello1/kv-evict-on-rollout-end

Conversation

@felipemello1

@felipemello1 felipemello1 commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Agent details

Supersedes the session KV holder PRs: "Turn the vLLM session KV holder on by default", "session KV holder: release running sessions' holds last, not never", "per-step session-KV metrics (7/7)" and "offload idle session KV to CPU (6/6)". Stacked on this PR: "Log KV cache occupancy and usage on each completion".

TLDR: The session KV holder becomes VLLMSessionKVEvictor, and it stops pinning blocks. When a rollout ends, its cached KV blocks that no other request may reuse lose their prefix-cache hash and move to the front of vLLM's free queue. New requests take them before the cached history of rollouts that wait on a tool call. With SimpleCPU offload, the same hashes go to the CPU tier's front. On GDN models (Qwen3.5), a live rollout keeps one GDN state per GDN group, the one its next turn resumes from. It keeps the holder's three methods and their call path. Multi-turn Qwen3.5-4B with a full KV cache: 60% fewer prefix tokens prefilled again, 10% more prefix-cache hits, KV occupancy at the median 0.41 against 0.99, wall time about the noise band (no speed claim). Source +635 / -380.

On main, a new rollout takes the cached history of a rollout that waits on a tool call; with this PR, an ended rollout's blocks leave the prefix cache and go first.

Before (main) After (this PR)
VLLMEngine.Config.session_kv_holder, off by default: pins live sessions' blocks removed; VLLMSessionKVEvictor always runs and pins nothing
releases reach vLLM only with the holder on (GenerationEngine.holds_session_kv) removed: every engine gets releases; a release after the generator closes is dropped
a release un-pins: blocks go to the back of the free queue, still cached a release evicts: blocks no request may reuse go to the front, without their hash
the holder requires reset_kv_cache_on_model_state_dict_load=False no requirement
SimpleCPU offload release hints only with the holder on every SimpleCPU offload run sends them; a hash a later prompt drops gets its hint at the next track
GDN: vLLM caches a state at every block boundary of every session (dense retention); under pressure, LRU drops an idle session's history before other sessions' older states a live session keeps 1 state per GDN group, the one vLLM's prefix lookup picks for its tokens
siblings that prefill one prompt in the same step each keep a cached copy of it; a turn that computes a cached block again caches a second copy (MTP's block drop, a prompt that ends on a block boundary); vLLM doesn't de-duplicate once a request leaves vLLM, each of its blocks keeps one cached copy; the other free copies go to the front

Problem

  1. vLLM keeps a finished request's full blocks cached in its free queue and reuses the least recently used first.
  2. A rollout that ended a second ago has newer blocks than a live rollout that waits on a 60 s tool call.
  3. Under KV pressure, vLLM reuses the live rollout's history first, and its next turn prefills it again.
  4. On GDN models, each session also caches a state per block boundary, and LRU drops an idle session's needed history before another session's older states (CPU test: an idle session's next-turn hit falls from 48 tokens to 0).
  5. Main's holder pins live rollouts' blocks instead, so running requests can't use them. It is off in every recipe.

Solution

  1. The evictor counts, per block hash, the requests that may still reuse it: each live rollout's newest request, and any replaced or released request still in vLLM. A turn that extends its history takes over the previous request's counts and counts only its new hashes. A preempted request's output is counted before any eviction.
  2. A rollout's release, or its group's, uncounts its requests. Each free copy of a hash at count 0 loses the hash and moves to the free-queue front, in block id order, so every TP rank keeps the same queue. A late request of a released group (an abandoned attempt still in transit) starts no session; vLLM's LRU reuses its blocks. The SGLang engine skips it the same way: the request runs without a session id. On main, a late request of a released group makes SGLang reopen its session (ensure_session_generation), and nothing closes it again. Both engines remember the last 4,096 released groups (NUM_RELEASED_GROUP_IDS_KEPT).
  3. A block in use (a running request, a KV connector's save) keeps its hash; its free copies still go. Once it is free, a later after_step evicts it, unless a request counts its hash again.
  4. With SimpleCPU offload, the evicted hashes go to the connector (release_session_cache) once the saves pending at their eviction finish, so their CPU blocks go first too.
  5. GDN: per live session and per align-mode GDN group, the evictor keeps the state find_longest_cache_hit(block_hashes, num_tokens) returns, and evicts the session's other states that no other request counts. It sweeps when a request's computed tokens cross a GDN block, and after it leaves vLLM, again at each step while a state it drops is still in use. A state it keeps because others count it (the group's prompt, a state a late sibling cached again) waits for those requests to be uncounted. With none left, it goes. With one left, that request's session sweeps again from it: at once if idle, else at its next sweep. Hashes chain, so every still-counted hash after it has that same one counter, and one lookup per uncounted request finds it. vLLM's own lookup handles MTP's block drop, prefix_match_unit and the align split.
  6. Siblings that prefill one prompt in the same step each cache their own copy of its blocks. A turn that computes a cached block again caches a second copy: MTP's block drop, a prompt that ends on a block boundary (vLLM never hits a prompt's last token), and on GDN models a turn that resumes from an older state after a rewrite. Once a request leaves vLLM, each of its blocks keeps one cached copy per KV cache group: a copy in use if there is one, else the one prefix lookups return. The other free copies go to the free-queue front. Two copies still held by KV connector saves when the last request holding the block leaves stay until a later turn holding it leaves vLLM or the group ends.
  7. Kept on purpose, each with a test:
    • a system prompt that live groups share, and its GDN state;
    • a preempted request's output;
    • a rollout released while its request runs (evicted when it finishes);
    • a retry while the old request is preempted;
    • a turn that drops an old reply (the dropped blocks go);
    • with MTP drafts, the state one block before the deepest, which the next turn hits.
  8. num_evicted_blocks counts ended sessions' blocks; num_evicted_live_session_blocks counts the blocks live sessions no longer need (superseded states, extra copies). log_stats logs both.
  9. Unchanged: vLLM's scheduler code, the engine loop's order (releases apply before admissions) and the router (a session's release goes to its pinned generator, a group's release to all).

What one GDN state per session keeps and loses (CPU, vLLM's KV cache manager, 6 turns of one session; "main" with every state cached, no KV pressure):

next turn's prefix hit, in tokens main this PR this PR, a sibling still counts the prompt
tool result, extends the previous turn 64 64 64
new user message, 2 replies rewritten 32 0 32
tool result, extends the previous turn 128 128 128
new user message, 2 replies rewritten 96 0 32
new user message, 1 reply rewritten 160 0 32

Without MTP drafts, a turn that extends its history hits all of it, as on main. TorchTitan's default keeps all thinking, so its prompts always extend. A turn after a rewrite (thinking stripped, a compacted history) recomputes the history after the shared prompt.

The file is renamed with git mv. It is 9% similar to main's holder, so git shows a delete and an add; git log --follow -M5% pairs them.

Results

Multi-turn, Qwen3.5-4B TP1 on 1 GB300, 358 blocks of 640 tokens (no preemptions), 8 groups x 8 rollouts
(4 groups at once), 4-10 turns, ~384-token replies, ~8 s tool calls, greedy. One cell each, same workload and seed.
                                     main       this PR    PR vs main (band *)
wall time per cell, s                263.6      260.1      -1.3%  (1.1%)  about the band; no speed claim
prefix-cache hit tokens              1.86M      2.06M      +10.2% (1.5%)  more
prefix tokens prefilled again **     313K       125K       -60%   (9.6%)  fewer
KV cache occupancy, median / max     0.99/1.00  0.41/0.85
dead cached blocks, max (of pool)    0.88       0
GDN blocks per idle rollout, median  6.5        3.0        1 per GDN group; max 3.0 too
evictor share of engine step time    -          0.16% ***
*  band: the largest gap between two cells of one variant in an earlier revision's 3-pair run on this workload.
** per later turn: the previous prompt + reply tokens that missed the cache. Each turn's last, partial block
   (up to 639 tokens) is never cached; without it, 188K -> 0.
*** about 0.04% of it is the harness's own timers: the main cell, whose evictor methods do nothing, reads 0.04%.
  • Cost: the evictor took 0.16% of engine step time in the run above (all of it: hints, GDN sweep, one-copy rule; the harness's own timers read 0.04%). One GDN sweep at long contexts (CPU probe, vLLM's KV cache manager): 2.04 ms at 65,536 tokens with 16-token hashes, 0.50 ms at 16,384; 1.9 of the 2.0 ms is vLLM's own lookup. A request is swept once per GDN block it decodes. The one-copy pass at each request's end looks up every block of the request and touches only blocks with several cached copies (CPU probe, 16-token hashes):

    tokens dense, 1 KV cache group 1 attention + 3 GDN groups track after a rewrite (counts the whole prompt), for scale
    16,384 0.22 ms 0.75 ms 0.08 ms
    65,536 0.85 ms 3.02 ms 0.34 ms

    A turn that extends its history counts only its new hashes: track takes ~0.005 ms at both lengths (CPU probe, dense, 16-token hashes).

    Not measured end to end on a dense model with 16-token blocks; there each request's end costs the table's dense column.

    16-token hashes are vLLM's default block for dense models (CacheConfig.DEFAULT_BLOCK_SIZE); GDN models get them only with prefix_match_unit, which no recipe sets. Their 640-token hashes are 40x fewer, as in the run above.

  • An earlier CPU bench, before the hints and the GDN sweep (16-token blocks, 512 rollouts in flight): 0.16 ms per ended rollout.

  • GPU probe, CI's hybrid-tail settings (Qwen3.5 debug model, SimpleCPU offload, prefix_match_unit=32, 1 GPU): 1 cached GDN state per group after each of 3 turns (without the GDN sweep: 2, 3, then 5); each turn hits the kept state (768, then 928 tokens, the same as without the sweep); after the release, the session's CPU blocks are at the CPU free queue's front.

  • Batch-invariant runs: CI's RL loss guard checks bitwise loss against the committed golden (trainer TP4, generator TP4). Not run locally. Elsewhere, which prefixes hit the cache changes, as with any cache change.

How the run was made

A standalone harness, not in this PR, builds one TorchTitan vLLM generator and replays a fixed multi-turn workload per cell. Each cell starts with an empty prefix cache and a fresh evictor; "main" switches the evictor's methods off. "Dead cached blocks": every 2 s, an exact count of cached free blocks that no live rollout and no request in vLLM uses, over the pool.

python session_kv_ab.py --model 4B --kv-gib 7 --decode 384 --gap 8 --gap-cap 30 --greedy --oracle \
  --cells lru,evict --out r.json

You may ask:

  • Why count hashes instead of evicting the ended group's blocks? Live groups share the system prompt's blocks, and vLLM's lookup stops at the first miss (CPU test).
  • Why not rebuild the live set at each release? 34-110 ms per release at 16-token blocks with 512 live rollouts (CPU probe), against 0.1-0.5 ms for the count.
  • Why does only the pinned generator get a session's release? Main's router does that, and the group's release reaches all generators. Sending to every generator's rank 0 is 3 lines. It costs N calls per rollout end, wakes each idle engine loop once, and, on SGLang, fills its 8,192-entry closed-session list N times faster (TODO at release_session).
  • Why no init check that each KV cache group's block equals the hash block? vLLM hashes a prompt in fixed-size pieces and caches a larger block under the hash of its last piece. The request's hash list holds that hash, so eviction reaches the block (CPU test with 32- and 16-token groups).
  • Why keep the state vLLM's lookup picks, not the deepest one? With MTP drafts, vLLM drops the last block of a hit, so the next turn needs the state one block back. The deepest-state rule hits 0 there where main hits 48 and 96 tokens (CPU test with use_eagle=True).
  • Why does the one-copy pass look up every block of a request, not only the block past its prefix hit? On GDN models, a turn after a rewrite resumes from an older state, and vLLM recomputes every cached attention block up to the rewrite (CPU probe: 3 of 4 extra copies stay with the one-block pass). Also, the pinned vLLM's request doesn't keep its hit length after the first output (Request.take_prefill_stats).
  • Why not prefix_cache_retention_interval=0, which caches no decode states? Each next turn would recompute the previous reply.
  • Why no config switch? No recipe would set it. The tests run on vLLM's real KVCacheManager, so a vLLM bump that breaks these calls fails CI.

Known issues / TODOs

  • A re-pinned session, or any session under non-sticky routing, keeps KV on other generators until its group's release (TODO at release_session).
  • An attempt Verifiers retried keeps its cached KV until its group's release (TODO in the Verifiers rollouter).
  • A request that reaches the engine after its own session's release re-creates the session, which then lasts until its group's release.
  • The one-copy pass at each request's end does one lookup per block and KV cache group: 0.22 ms on dense models and 0.75 ms on GDN models at 16,384 tokens with 16-token hashes (table under Cost). 640-token blocks pay ~1/40.
  • With vLLM's partial-block prefix hits on, evicting a block also drops its partial hits. A warning at init says so.
  • It reads and edits vLLM's KV cache manager internals. vLLM's session KV hint RFC would replace them (TODO at __init__).

NOTE:

  • GRPO siblings start seconds apart. If the first sibling's sweep runs before a second is tracked, the shared prompt's GDN state goes (count 1 then), and the second sibling prefills the prompt again once. Cost: at most one extra prefill of the shared prompt per group.
  • With MTP drafts, the next turn hits what main hits, but a turn two later can hit one block less (13 of 568 turns in a CPU stress). That turn can need a deeper state that the evictor dropped, because vLLM's lookup had picked the state one block back. Keeping that state too would give 2 idle states per GDN group with MTP. The vLLM MTP stack owns that choice.
  • The GDN sweep and the 12 commits after it (one copy per shared block, the re-sweep of a state in use, the counters, the copy in use that stays, the idle session's re-sweep, the log text, one copy of each of a request's blocks, the re-sweep of the one session left counting a hash, comment text, the other-group test, the one-copy comments, the one-copy pass's skip of single copies) are the 13 commits before the merge of main, so they can move to their own PR above this one. An earlier revision of this PR deferred it, to keep this PR to one change. It is in now because the KV admission PR above needs a bounded state count per session.

Test plan

pytest tests/rl/unit_tests/cpu/test_session_kv_evictor.py   # 27, on vLLM's real KVCacheManager
pytest tests/rl/unit_tests/cpu/test_engine_loop.py -k session_releases   # 3
pytest tests/rl/unit_tests/cpu/test_generator.py -k "session_kv_evictor or resolves_reply or offload or mooncake"   # 7
pytest tests/rl/unit_tests/cpu/test_kv_offload_coordination.py   # 10 passed, 2 failed (the same 2 fail on main)
pytest tests/rl/unit_tests/cpu   # 779 passed, 2 failed, 8 skipped (6 need `verifiers`, 1 needs dist_moe, 1 TODO)
# 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`.
# CI first (2 x world_size GPUs; not run at this head): tests/rl/unit_tests/gpu/test_kv_offload.py. Its "release"
# block now runs in every case: its first CI run is cpu-tp2-dp2-ep4 and cpu-hybrid-tail-tp2. cpu-hybrid-tail and
# cpu-tp2-session have no CI runner.
# CI: RL loss guard (TP4, golden), batch-invariant integration entries
  • New evictor tests: a late request of a released group starts no session; a retry of a running request leaves that request's reply to evict; the CPU hint waits for decode and saves and skips a shared prefix; a hash a later prompt drops gets its hint; a block a connector holds keeps its hash until freed (and stays if counted again); an idle session's history outlasts another session's superseded GDN states; one GDN state per session plus the group's prompt; a GDN block over several hashes; MTP drafts (use_eagle=True); siblings prefilled in one step keep one copy of their shared prompt (dense and hybrid); a copy in use when its sibling leaves is the copy that stays (dense and hybrid); with MTP drafts, a state in use at a turn's last sweep goes once free; an idle session drops its prompt's state once no other session counts it (a sibling, or another group's rollout with the same system prompt); an idle session drops a state its late sibling cached again; with MTP drafts, one copy of each computed block stays after each turn.
  • TestSGLangBitwiseParityGDN::test_a_late_request_of_a_released_group_starts_no_session (B200 CI, TP 2): a late request of a released group reaches SGLang without a session id, and the engine keeps no session for the group. Run locally on 1 GB300 through a TP-1 subclass: passed; with the skip removed, it fails (the request carries late/1).

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 7, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 7, 2026
@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 5m 25s —— View job


Needs discussion: the evictor looks correct, but deleting the holder conflicts with open PRs #5902 and #5847, and the human-written summary is empty. See the 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: Needs discussion -- this PR deletes VLLMSessionKVHolder and holds_session_kv, which two open PRs build on (#5902 turns the holder on by default; @acisseJZhong's #5847 extends it for CPU offload). The maintainers need to pick holder vs. evictor before this lands. The evictor itself looks correct.

What this PR does. It replaces the opt-in holder with an always-on VLLMSessionKVEvictor. The evictor counts, per block hash, the live rollouts whose history holds it. When a rollout or group is released, free blocks whose hash has no live owner lose the hash and move to the front of vLLM's free queue, so new requests take them before a waiting rollout's history. Releases now apply after a STEP's admissions instead of before every decision, and the router sends each release to every generator the session's calls went to. Two new per-completion metrics: kv_cache_occupancy and kv_cache_usage.

Example.

pool: A (ended 1 s ago) cached, B (live, 60 s tool call) cached, shared system prompt S
main:    new request takes B's blocks first (older in the LRU) -> B's next turn prefills again
this PR: release(A) -> A's blocks lose their hash and go to the front; S (B still owns it) and B stay
         new request takes A's blocks first

Must fix

  1. The PR description's "Summary (human-written)" is empty. The author needs to write it (CONTRIBUTING.md, "AI-assisted contributions").
  2. Direction conflict with #5902 and #5847. Please say in the description that this supersedes #5902 (and close it), and agree with @acisseJZhong how #5847 moves onto the evictor. #5847 reads holds_session_kv and engine._session_kv_holder in several places. The "save in flight" TODO (session_kv_evictor.py:198) also becomes live once a KV connector lands.

Should consider

  • torchtitan/rl/generator/vllm/session_kv_evictor.py:94 -- with unequal KV cache group block sizes, eviction silently misses those groups and occupancy counts their dead blocks as live. Raise at init instead, and delete the alias lookup in _has_live_owner (inline).
  • tests/rl/unit_tests/cpu/test_engine_loop.py:1441 -- unrelated flake TODO; move it to its own PR (inline).

Questions

  • Always-on means every vLLM generator run now reads and edits vLLM's private BlockPool internals (cached_block_hash_to_block, free_block_queue.prepend_n, evict_blocks, cached_block_hashes_by_block) on the main generation path. The CPU tests use the real KVCacheManager, so a vLLM bump that breaks these fails CI rather than silently. Are the maintainers OK carrying this until vllm-project/vllm#51428 lands?
Details

Checked and found no problem:

  • TP rank consistency. release() iterates sets of str/bytes, whose order depends on the per-process hash seed. The only order-sensitive effect is the free-queue prepend, and that is sorted by block_id. Map pop/reinsert in _cached_copies restores the original order. So TP ranks end in the same state.
  • Engine loop. A release taken off the queue with a load waits for the next STEP. pending_release_messages makes that STEP immediate even with nothing outstanding. A request queued in the same drain as its rollout's release is admitted first and marked released.
  • Request ids. In-flight duplicates are rejected by the dispatcher (dispatcher.py:122), and there are no aborts in torchtitan RL. So finish()'s self._requests.pop(request_id) can't hit KeyError from the known paths.
  • Validation. Validation groups (-(i+1)) always get release_groups (controller.py:745), so _session_ids_by_group doesn't grow without bound.
  • Callsites. Making routing_session_id required is safe: every in-repo GenerateFn caller already passes it, and Generator.generate already required it.

Not verified: vLLM API names and behavior (no vLLM in this environment), and the GPU A/B and bitwise results, which also came from an earlier revision. A maintainer still needs to review.

Comment on lines +94 to +99
num_block_pools = len({id(manager.block_pool) for manager in managers})
if num_block_pools > 1:
raise ValueError(
"VLLMSessionKVEvictor needs every KV cache group in one vLLM block pool; "
f"found {num_block_pools} block pools for {len(managers)} KV cache groups"
)

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.

The class assumes every KV cache group's block size equals vLLM's hash block size: _evict_hash looks up make_block_hash_with_group_id(h, group_id) for each h in request.block_hashes, which vLLM computes at hash_block_size granularity. For a group with a larger block size, vLLM caches the block under a merged hash (BlockHashListWithBlockSize), so that lookup always misses. The result is silent: the group's dead blocks are never evicted, and kv_cache_occupancy counts them as live. The comment at _has_live_owner (:283-284) says the case only works today because Qwen3/Qwen3.5 have equal sizes.

Since the constructor already raises on multiple block pools, raise here too when any single_type_manager's block size differs from the manager's hash block size. That also lets you delete the alias lookup in _has_live_owner (:285-289), which the comment says only applies with unequal block sizes. It would shrink to return get_block_hash(block.block_hash) in self._num_owners_by_hash. Unverified: I couldn't import vLLM here to confirm the attribute names.

Comment on lines +1441 to +1442
# TODO: this reads dispatcher state off the engine thread, which frees the reservation
# just after it resolves the reply, so the assert can run first (a flake under load).

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 TODO is about a flake in the peer-result drain test and has nothing to do with session release or eviction. Please move it to its own PR (one concern per PR), or better, fix the race there.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review again. Changes since your review (head f1a7d9dcd):

The human-written Summary is Felipe's to write.

@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 1m 30s —— View job


Needs discussion: the code findings are fixed. The empty human-written summary, #5847's move off the holder, and the always-on use of vLLM's private internals are left for maintainers and authors. See the 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: Needs discussion -- the code findings from the last review are fixed at f1a7d9dcd. What's left is for the maintainers and authors to decide: the empty human-written summary, how #5847 moves off the deleted holder, and whether always-on use of vLLM's private BlockPool internals is acceptable.

Re-review of f1a7d9dcd (changes since the review on 2026-11-07 03:26).

Resolved

  • Unequal block sizes now raise: session_kv_evictor.py:100-109 raises ValueError when any KV cache group's block_size differs from block_pool.hash_block_size, and _has_live_owner (:292-293) is down to a single lookup. test_kv_cache_groups_with_blocks_larger_than_the_hash_block_raise covers the raise.
  • The drain-test flake TODO is gone from test_engine_loop.py.
  • The description now says this PR supersedes #5902, #5477, #5338 and #5299. I checked #5902 and it is closed.

Must fix (still open)

  1. The PR description's "Summary (human-written)" is still empty. Felipe has to write it (CONTRIBUTING.md, "AI-assisted contributions").
  2. #5847 (@acisseJZhong, open, last updated 2026-11-06) still builds on VLLMSessionKVHolder / holds_session_kv, and this PR deletes both. Felipe will settle this with its author directly. Until that's agreed, the PR shouldn't land, or #5847 breaks on rebase. When a KV connector lands, the "save in flight" TODO (session_kv_evictor.py:208) becomes real work.

Questions

  • Still unanswered by a maintainer: the evictor is always on, so every vLLM generator run reads and edits vLLM's private BlockPool internals on the main generation path. Is that acceptable until vllm-project/vllm#51428 lands? The CPU tests run on the real KVCacheManager, so a vLLM bump that breaks these calls fails CI instead of failing silently.
Details
  • The new raise and in-repo recipes. The evictor is built for every vLLM engine (vllm/engine.py:183), and no recipe turns off prefix caching. So any recipe whose vLLM KV config fails the new check would now fail at generator init, where main runs. RL recipes use Qwen3, Qwen3.5/3.6 (hybrid), gpt-oss-20b and Muse-Glimmer-30B. The last two mix sliding-window and full attention: two KV cache groups in one pool, which should have equal block sizes. Unverified: this needs vLLM. The rl_grpo_qwen3_5_debug_tp2_batch_invariant CI job checks the hybrid case. A quick run of the gpt-oss or Muse-Glimmer recipe would confirm the sliding-window case.
  • The new test sets hash_block_size = BLOCK // 2 on a real block pool. That is cheap and guards the one contract the raise exists for. Fine.

Not verified: vLLM attribute names and behavior (vLLM isn't installed in this environment), and the GPU results. A maintainer still needs to review.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: on the open check in the last review (does the new block-size raise fire for the sliding-window recipes?): no. Checked on CPU with each recipe's real generator layers, TorchTitan's block-size choice, vLLM's get_kv_cache_groups and resolve_kv_cache_block_sizes, and the evictor built on a real KVCacheManager (only the GPU kind is mocked).

recipe                                   groups  H100 FA3  GB300 FA4  GB300 FA4 batch-inv.  A100
gpt-oss-20b alphabet_sort                2       16        128        16                    256
Muse-Glimmer-30B terminal_bench          4       16        128        16                    256
Muse-Glimmer-30B search_r1               4       16        128        16                    256

Every group's block size equals the hash block size, and the evictor init passes. Both models store the same bytes per token in every layer (same KV heads and head dim), so vLLM gives the sliding-window and full groups the same block size. Control: giving the sliding-window layers 1 KV head and the full layers 2 makes the groups [32, 16], and the evictor raises.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: on the question about always-on use of vLLM's private BlockPool internals. Why we think it's acceptable until vllm-project/vllm#51428 lands:

  1. No public API yet. vLLM can't evict by session today. The installed nightly's session_id only tags KV cache events (block_pool.py:377, :558); it doesn't change eviction. The RFC above (open) would add the hint; the TODO at the top of VLLMSessionKVEvictor points to it.
  2. A break fails CI, not a run. Every internal call is in one file, session_kv_evictor.py, and the 9 test cases run it on vLLM's real KVCacheManager. A vLLM bump that renames or changes these calls fails test_session_kv_evictor.py.
  3. A wrong eviction costs cache hits, never wrong values. The evictor only drops the hash of a free block (ref_cnt == 0, session_kv_evictor.py:273), through vLLM's own evict_blocks. A block a running request uses is never touched.
  4. Unsupported layouts fail at startup. Several block pools, or a group whose block size differs from the hash block size, raise ValueError at init.
  5. Cost: 1.1% of engine step time in the worst case measured (16-token blocks, single-turn).

The calls: cached_block_hash_to_block (get_one_block, pop, insert), free_block_queue (iter_blocks_after, remove, prepend_n), evict_blocks, hash_block_size, scheduler.requests and the coordinator's single_type_managers.

@felipemello1
felipemello1 force-pushed the felipemello1/kv-evict-on-rollout-end branch 2 times, most recently from 3d0504a to f1a7d9d Compare November 7, 2026 06:09
@felipemello1
felipemello1 force-pushed the felipemello1/kv-evict-on-rollout-end branch from f1a7d9d to e078523 Compare November 10, 2026 17:47
@felipemello1
felipemello1 force-pushed the felipemello1/kv-evict-on-rollout-end branch from e078523 to 1b9ad81 Compare November 20, 2026 05:17
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review again. The head is now 1b9ad8113, rebased on main b1c259cd3. Changes since your last review:

  • Main's router now only reserves a generator. So InterGeneratorRouter.reserve takes group_id and records each session's generators and each group's sessions. release_session goes to each recorded generator. release_groups also drops the group's routing pins.
  • SGLangEngine.holds_session_kv (new on main) is deleted with the base property. SGLang now gets each release after the step's admissions, as vLLM does.
  • Outside vllm/, comments say "release" instead of "evict": SGLang's release drops references and doesn't evict. The new TODOs name their fix.
  • The description lists the open PRs that build on the deleted holder or edit reserve. Felipe settles the holder one with its author.

Tests: RL CPU suite 689 passed, 7 skipped. The 1-GPU RL unit tests pass except one MXFP8 test, which fails the same way on main.

@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 3m 41s —— View job


Needs discussion: no new code problems at 1b9ad8113. Still open: the empty human-written summary, #5847 still building on the deleted holder, and no maintainer answer on vLLM's private internals. See the 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: Needs discussion -- I found no new code problems at 1b9ad8113. The blockers from the last review are still open: the human-written summary is empty, #5847 still builds on the holder this PR deletes, and no maintainer has answered the vLLM-internals question.

Re-review of 1b9ad8113 (rebased on b1c259cd3; changes since the 2026-11-07 03:45 review).

What changed. InterGeneratorRouter.reserve now takes group_id. It records the generators each session's calls went to and the sessions in each group. release_session goes to each recorded generator, and release_groups also drops the group's routing pins. holds_session_kv is gone from GenerationEngine and SGLangEngine, so SGLang now gets releases after the step's admissions, the same as vLLM.

Example.

round-robin routing, session s0's two turns -> gen0, gen1; s1 -> gen2
main:    release_session(s0) -> only the pinned generator (none without sticky routing)
this PR: release_session(s0) -> gen0 and gen1; gen2 gets nothing
         release_groups([g]) -> forgets g's sessions and pins, then fans out to every generator

Must fix (still open)

  1. The PR description's "Summary (human-written)" is still empty. Felipe has to write it (CONTRIBUTING.md, "AI-assisted contributions").
  2. #5847 (@acisseJZhong, open, updated 2026-11-20) still imports VLLMSessionKVHolder and reads holds_session_kv / engine._session_kv_holder. This PR deletes all three. Until the two authors agree on the move to the evictor, landing this breaks #5847 on rebase.

Should consider

  • torchtitan/rl/routing/strategies.py:139 -- StickySessionRoutingStrategy.Config.max_sessions is now only a backstop. release_groups drops the pins of every session in the group, retried attempts included. The only leak left is the "call after its group's release" case in the reserve TODO, and that case also leaks the router's two new dicts, which max_sessions doesn't cap. You could delete the knob in the routing-only follow-up named in the RoutingContext.session_id TODO.

Questions

  • Maintainers: still unanswered from the last two reviews. The evictor is always on, so every vLLM generator run reads and edits vLLM's private BlockPool internals on the main generation path. Is that acceptable until vllm-project/vllm#51428 lands? Felipe's reply (no public API exists, every call sits in one file tested on the real KVCacheManager, a wrong eviction only costs cache hits) is the case for yes.
  • SGLang: since releases now come after admission, a request admitted in the same STEP as its group's release now has release_radix_session called on its session while that request waits in the queue. Before this PR, the release came first and the request re-opened the session. Does SGLang handle closing a session that has a waiting request? This only happens for a late, abandoned attempt, and the description says it was not run with SGLang.
Details

Checked at HEAD and found no problem:

  • Router bookkeeping. reserve has no await, and release_groups updates its dicts before it awaits the fanout. So the Monarch concurrent endpoints can't interleave halfway through an update. release_session pops the session's generators before it awaits. Every in-repo reserve caller passes group_id (controller.py:704, actors/monarch/router.py:38, tests). Every GenerateFn caller passes a str session id (rollouter.py:530, verifiers/generation_server.py:243).
  • _session_ids_by_group growth. Training groups get release_groups on both the success and failure paths (controller.py:1246). Validation ids come from a counter that never repeats (controller.py:624, :878), so a late release can't hit a later validation round's group.
  • Engine loop. Releases taken off the queue with a load or a drain stay in pending_release_messages. The non-empty list makes the next decision run immediately, so the first admitting STEP applies them. A drain holds them on purpose: requests taken off the queue in the same batch aren't admitted yet, and releasing first could evict a prefix those requests share. drop_if_closed is used only by the two release puts, and the crash path drops SessionReleaseMessages that are still queued.
  • vLLM engine. track runs only in the else of the admission try, so a request vLLM rejects is never tracked.

Not verified: vLLM and SGLang behavior (neither is installed here), and the GPU results, which came from an earlier revision. A maintainer still needs to review.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: on the two open points in the last review.

SGLang: closing a session while its request waits. Safe, at the commit scripts/install_rl_env.sh pins (SGLang 851642ade):

  1. Admission opens the session's generation (scheduler.py:3212). The release then tombstones the session and drops that generation (session_ref_tracker.py:101-109).
  2. A waiting request holds no session reference. The tracker registers one only when the request finishes (unified_radix_cache.py:1596).
  3. At that point register_session_ref sees the tombstone and skips the request (session_ref_tracker.py:67). Its KV enters the radix tree as an untagged entry, evictable like any other.

So the late request runs normally, and nothing keeps its session alive. With main's order, the request re-opened the session (open_radix_session pops the tombstone, :89-90), and that session was never released.

max_sessions. Kept here. No config sets it, and it still caps pins in the late-call case. The routing-only follow-up named in the RoutingContext.session_id TODO can decide whether to drop it.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review again. On must-fix 2, Felipe decided that #5847 and #5727 rebase onto this PR after it lands. When they do, they move their release hints from the holder to the evictor's release path. The description now says so (Known issues). The code is unchanged since your review at 1b9ad8113.

@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 43s —— View job


Needs discussion: the holder conflict is settled by the plan to rebase #5847 and #5727 onto this PR. Still open: the empty human-written summary and no maintainer answer on vLLM's private internals. See the 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: Needs discussion -- The holder conflict is settled. Two blockers remain: the human-written summary is still empty, and no maintainer has answered whether always-on use of vLLM's private internals is acceptable.

Re-review of 1b9ad8113. The code is unchanged since the 2026-11-20 05:22 review, and I confirmed the head SHA. Only the description changed.

Resolved

  • #5847 and #5727 vs. the deleted holder. Both are still open and still reference VLLMSessionKVHolder / holds_session_kv: 43 lines in #5847's diff and 7 in #5727's. Felipe decided they rebase onto this PR after it lands and move their release hints to the evictor's release path. The description's Known issues now says so. That answers the earlier must-fix; the remaining work belongs to those PRs.

Must fix (still open)

  1. The PR description's "Summary (human-written)" is still the template placeholder. Felipe has to write it (CONTRIBUTING.md, "AI-assisted contributions").

Questions

  • Maintainers, still unanswered: the evictor is always on, so every vLLM generator run reads and edits vLLM's private BlockPool internals (cached_block_hash_to_block, free_block_queue, evict_blocks) on the main generation path. Is that acceptable until vllm-project/vllm#51428 lands? Felipe's reply on 2026-11-07 makes the case for yes:
    • vLLM has no public API for this.
    • Every call sits in one file, tested on the real KVCacheManager.
    • Unsupported layouts raise at init.
    • A wrong eviction only costs cache hits.

No new code findings. The should-consider on max_sessions (strategies.py:139) is deferred to the routing-only follow-up, as Felipe said. The SGLang question was answered with source references at the pinned commit. Not verified here, since SGLang isn't installed.

Not verified: vLLM and SGLang behavior, and the GPU results, which came from an earlier revision. A maintainer still needs to review.

@felipemello1
felipemello1 force-pushed the felipemello1/kv-evict-on-rollout-end branch from 1b9ad81 to 866d659 Compare November 20, 2026 16:18
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review again. This PR is rewritten; the head is now 866d659cc on main a618f3ba6. Felipe asked for the smallest change on top of main's session KV holder. What changed since your last review:

  • Main's holder file and class become VLLMSessionKVEvictor in session_kv_evictor.py (git mv). It keeps the holder's track / after_step / release methods and their call path. It stops pinning, and a release evicts.
  • It counts, per block hash, the requests that may still reuse it. The previous version's per-session sets, released flag and finish hook are gone.
  • The router, reserve, GenerateFn and the engine loop's order are main's again. The reserve(group_id) change and the router's two maps are gone.
  • The KV cache metric moved to the stacked PR [rl] Log KV cache occupancy and usage on each completion #6291.
  • Source +259 / -268 against main (the previous version: +497 / -317).

Tests: RL CPU suite 689 passed, 7 skipped (main 694 / 7: 13 holder cases and 1 reset test removed, 9 evictor cases added). The 1-GPU RL unit tests pass except one MXFP8 test, which fails the same way on main.

@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: Needs discussion -- the block-size finding is resolved and there are no new code problems at 44b74e3f3. Two items are still open: the human-written summary is empty, and no maintainer has answered on always-on use of vLLM's private internals.

Re-review of 44b74e3f3 (changes since the 2026-11-20 16:23 review: a new test, a comment at the init check, and body edits).

Example (the layout the new test builds):

groups: sliding-window 32-token blocks (group 0), full 16-token blocks (group 1); hash block 16
a = shared[0:64] + own[64:128], b = shared[0:64] + other
group 0 caches a's blocks under hash indices [1, 3, 5, 7] (each 32-token block under its last hash)
release_groups([a's group]) -> group 0: [1, 3] stay (b shares them), [5, 7] evicted
                               group 1: [0..3] stay, [4..7] evicted

Resolved

  • session_kv_evictor.py:65-67 -- the dropped block-size raise. Your reply is correct: a group block larger than the hash block is cached under the hash of its last hash block, and that hash is in Request.block_hashes. So _evict's per-hash, per-group lookup reaches it. Lookups at the other indices miss, which costs nothing. Chained hashes keep a block that straddles a shared prefix unique to its request, so a partly shared block can't be evicted early. test_a_kv_cache_group_with_blocks_larger_than_the_hash_block_is_evicted_too covers the [32, 16] layout on the real KVCacheManager, and the mutation you describe makes it fail. My earlier finding was wrong.
  • Partial hash hits stay a warning. That is acceptable: the setup is supported, and the cost is at most one block prefilled again per live session, not a silent wrong path. The reason is now a comment at the check.

Must fix (still open)

  1. The PR description's "Summary (human-written)" is still the template placeholder. Felipe has to write it (CONTRIBUTING.md, "AI-assisted contributions").

Questions

  • Maintainers, still unanswered: the evictor runs on every vLLM generator and reads and edits vLLM's private BlockPool internals (cached_block_hash_to_block, free_block_queue.remove/prepend_n, evict_blocks, scheduler.requests) on the main generation path. Is that acceptable until vllm-project/vllm#51428 lands? Felipe's 2026-11-07 reply makes the case for yes.

Not verified: vLLM's BlockHashListWithBlockSize behavior, which I couldn't import here (the new CPU test is the evidence), and the GPU A/B. A maintainer still needs to review.

Conflicts: main's CPU-offload PRs (SimpleCPU, Mooncake) extended the session KV
holder that this branch replaces with VLLMSessionKVEvictor. This merge keeps
main's offload code and the evictor; the holder's CPU release hints move to the
evictor in the next commit.
- vllm/engine.py: no session_kv_holder field; the evictor always runs.
- test_generator.py: the two offload tests check the evictor's constructor.
- gpu/test_kv_offload.py: no hold_sessions case; the release case returns with
  the hints.
Main's SimpleCPU offload sent CPU release hints from the session KV holder,
which this PR deletes. The evictor now sends them: the hashes it evicts from
GPU go to `connector.release_session_cache(released_hashes, active_hashes)`
once the saves pending when they were batched finish.

- A hash a request counts again by then is left out (it is in active_hashes).
- `has_pending_work` keeps the engine loop stepping while a hint waits.
- Mooncake gets no connector: it has no release hints.

Two behavior changes from main:
- Hints run for every SimpleCPU user (main sent them only with the holder on).
- A hash a later prompt drops (e.g. stripped reasoning) gets its hint mid-session.
When the evictor evicts a hash, a copy still in use (vLLM's CPU offload holds
a block by ref_cnt while it saves it) keeps its hash and returns cached to the
free queue's tail. Main now has two KV connectors, so this happens.

`_evict` now records those hashes, and `after_step` evicts them once the copy
is free. A hash a request counts again by then stays: that request's end
evicts it.
TorchTitan's vLLM engine caches a GDN (align-mode Mamba) state at every block
boundary (dense retention). An idle session needs only the one its next turn
resumes from, but the others stay cached, and vLLM's LRU reuses an idle
session's needed blocks before another session's superseded states.

After each step, the evictor now sweeps a live session's newest request when
its computed tokens cross a GDN block, and once after it leaves vLLM. Per GDN
group it keeps the state vLLM's own prefix lookup picks for the request's
tokens (`coordinator.find_longest_cache_hit`), so MTP's block drop,
`prefix_match_unit` and vLLM's alignment apply as they do for the next turn. It
evicts the older states that no other request counts, and, once the request
left vLLM, the newer ones too. A state still in use during a sweep is looked up
again in the next sweep. Attention blocks and a group's shared prompt (counted
by its siblings) stay.

Kept: a turn that extends the history hits all of it. Lost: a turn that
rewrites the session's own history (e.g. stripped thinking) resumes from the
group's shared prompt instead of the last unchanged block.
Siblings that prefill one prompt in the same step each cache their own copy
of its blocks: vLLM doesn't de-duplicate cached blocks. The evictor kept
every free copy while the prompt was counted, so idle sessions held extra
copies of their shared prompt, uncharged by admission (on Qwen3.5-4B, 42 of
358 blocks at the median, all GDN states).

Once a request leaves vLLM, each block it shares with other requests now
keeps one cached copy per KV cache group, the one prefix lookups return (and
any copy in use); the other free copies go to the free queue's front. This
runs for every model, also for replaced or released requests leaving vLLM.
… in use

A turn's last sweep runs once its request leaves vLLM. If a superseded GDN
state is still in use then (a CPU offload save, or a free that async
scheduling defers), the session left the sweep list and the state stayed
until its next turn. With MTP's block drop, an idle session then kept 2
states per GDN group, where admission charges 1.

The session now stays in the sweep list until no state it drops is in use,
and a sweep's scan never starts past the state it keeps.
`num_evicted_blocks` counts the blocks of ended sessions and requests again;
`num_evicted_live_session_blocks` counts the blocks live sessions no longer
need (superseded GDN states, extra copies of shared blocks). `log_stats`
reports both. The `__init__` TODO now names the KV cache manager internals
the class reads, not only the BlockPool's.
…t stays

When siblings prefill one prompt in the same step, vLLM caches a copy per sibling. The
one-copy pass kept the copy lookups return first, even when it was free and another copy was
in use: two copies stayed, and if the copy in use belonged to a request that had left (a KV
connector's save), nothing evicted either later. Now a copy in use is the one that stays
and every free copy goes.
…GDN state loses its last sharer

A sweep keeps a superseded GDN state that other requests count (a group's prompt) and moved
its scan past it, so the state stayed after the siblings ended, while the session waited
between turns. Now the sweep records those states with the session and keeps its scan start
at or before them; when `_forget` leaves at most one request counting such a state, the
session sweeps once more.
… its own included

With MTP drafts, vLLM drops the last block of a prefix hit, so the turn computes that block
again and caches a second copy under the same hash. The one-copy pass at a request's end
covered only blocks other requests count, so the session's own second copy stayed, one per
turn. The pass now covers all of the request's blocks.
…a late sibling's state included

A sibling that starts after a session's sweep dropped the group prompt's GDN state caches that
state again, below the blocks the session's sweeps look at, so the session's record of shared
states missed it and the state stayed after the sibling ended. Now _forget finds, per request
it uncounts, the one request left counting its hashes (hashes chain, so one lookup per request).
If that request is a live session's, the session sweeps again from there. This replaces the
record of shared states, so a sweep's scan again starts at the kept state.
The sweep comment says when `_forget` evicts or sweeps again a state others count, the
chained-hash comment in `_forget` names which hashes share one counter, and the MTP row of
the one-copy picture fits one line.
… group's rollout leaves

The test of an idle session dropping its prompt's state now runs with b in a's group and in
another group. With the counter search limited to the leaving request's group, the second case
fails.
The one-copy pass covers every block of a request: a turn computes a cached block again with
MTP's block drop, with a prompt that ends on a block boundary, and on GDN models after a rewrite.
The comments say so, and the _forget docstring no longer implies one counter for every remaining
hash.
…ed copy

vLLM stores one cached copy of a hash as the block itself and several as a dict, so a type
check finds the hashes with extra copies without popping and re-inserting every key. At a
request's end, 65,536 tokens with 16-token hashes: 2.84 -> 0.85 ms (dense), 6.71 -> 3.02 ms
(1 attention + 3 GDN groups).
# Conflicts:
#	tests/rl/unit_tests/cpu/test_session_kv_holder.py
#	torchtitan/rl/generator/vllm/session_kv_holder.py
… session

An abandoned attempt still in transit can reach the engine after its group's release. track
re-created its session, and nothing released it: its hashes stayed counted. The evictor now
remembers the last 4,096 released groups and leaves their late requests to vLLM's LRU.
Hashes chain, so a turn that extends the previous request's history starts with all of its
hashes. track now takes over the previous request's counts and counts only the new hashes,
instead of counting the whole prompt and uncounting the previous request. At 65,536 tokens with
16-token hashes: 0.33 -> 0.006 ms per turn (dense, CPU probe). A rewritten history still takes
the full path.
SGLangEngine sends a request of a released group without a session id and keeps it out of
_group_sessions, as the vLLM session KV evictor skips it. Both remember the last
NUM_RELEASED_GROUP_IDS_KEPT released groups (torchtitan/rl/generator/engine.py).
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review 698de6e. Changes since your review of 44b74e3 (the body describes each):

  • Merged main (latest 90ae735).
  • SimpleCPU offload: evicted hashes go to the connector's release hints once the saves pending at eviction finish.
  • A block in use at eviction keeps its hash. A later after_step evicts it once it is free.
  • GDN models: a live session keeps one GDN state per GDN group, the one vLLM's prefix lookup picks.
  • Once a request leaves vLLM, each of its blocks keeps one cached copy. Its other free copies go to the free-queue front.
  • New counter num_evicted_live_session_blocks.
  • A turn that extends its history counts only its new hashes.
  • A late request of a released group starts no session, on vLLM and on SGLang (SGLang gets session_id=None). Both engines remember the last 4,096 released groups.
  • Tests: 27 evictor tests on vLLM's real KVCacheManager, and one SGLang GPU test for the late request.

The next two PRs (#6420, #6008) stack on an upstream copy of this branch at 698de6e, because a GitHub stack can't span forks.

@claude

claude Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 5m 33s —— View job


Request changes: the PR now bundles the GDN sweep, one-copy pass and SGLang late-request fix with the ended-rollout eviction, and released-group tracking is duplicated across engines. See the 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: Request changes -- since 44b74e3f3 the PR has grown from one change (evict an ended rollout's KV) into three. The GDN-state sweep with the one-copy pass, and the SGLang late-request fix, are separate concerns. The late-request fix also adds a second, duplicated memory of released groups. I found no correctness bug in the counting.

Re-review of 698de6ee8 (all commits since 44b74e3f3, including the merge of main).

What this PR does now. It does everything the last revision did, plus:

  • CPU-offload release hints.
  • Retries for blocks that were in use at eviction.
  • On GDN models, each live session keeps one state per GDN group (the one vLLM's lookup picks).
  • When a request leaves vLLM, its blocks keep one cached copy each.
  • A late request of a released group starts no session, on vLLM and on SGLang.

The evictor went from about 210 to 542 lines.

Example.

Qwen3.5, session B: states cached at GDN blocks 3, 4, 5; siblings A and B prefilled prompt P in one step
before (44b74e3f3): B idle -> states 3, 4, 5 all cached; P cached twice until the group ends
now:                B idle -> 5 stays, 3 and 4 evicted; A leaves -> one copy of P stays
                    B's next turn rewrites block 4 -> resumes from P's state (main: from 3)

Must fix

  1. One concern per PR (CLAUDE.md, PR expectations 6). The 13 GDN-sweep and one-copy commits are not "evict an ended rollout's KV". The description says they "can move to their own PR above this one". The reason given for keeping them, that #6420 needs bounded states, is met by stacking them under #6420. The SGLang late-request fix is a bug on main too, so it can be its own PR. Keep the vLLM track skip here.
  2. session_kv_evictor.py:159 -- released-group memory is defined twice, in vLLM and SGLang, and the engine loop has the same leak through its group pins. The engine loop should own it once (inline).
  3. session_kv_evictor.py:435 -- the one-copy pass and the GDN sweep work around vLLM behavior, but have no upstream issue TODO (inline).

Should consider

  • session_kv_evictor.py:256 -- num_evicted_live_session_blocks also counts ended requests' copies (inline).
  • test_sglang_bitwise_parity.py:503 -- the test runs twice and checks only engine-side state (inline).
  • session_kv_evictor.py:62 and SIMPLE_CPU_OFFLOAD.md:62 say that evicted hashes go to the connector. Only _forget's do: superseded GDN states and extra copies get no CPU hint. Say so.

Questions

  • Maintainers, still open: always-on reads and edits of vLLM internals. The list now also includes BlockHashToBlockMap._cache, coordinator.find_longest_cache_hit and Request.num_computed_tokens.
  • Why drop the hash rather than only prepend the blocks? vLLM drops the hash when it allocates the block, so prepending with the hash would still get them reused first. It would also keep a system prompt that no live group holds at that moment hittable for the next group, which this PR now evicts. If lazy offload saving dead blocks is the reason, say so in the docstring.
  • Main-path cost: the only end-to-end number is GDN multi-turn with 640-token blocks. The common path is a dense single-turn recipe with 16-token blocks, where each request end now runs a one-copy pass. Can you show a number for it?
Details
  • Resolved earlier: the block-size raise, and #5847 / #5727. Both are merged now, and their hints moved to the evictor here.
  • Checked, no problem found:
    • The counting stays prefix-closed. extends_previous hands counts over, and num_counted is a prefix. So _forget's "one counter from index on" holds.
    • Every _num_requests_by_hash[...] read in the sweep comes after _count_all_new_block_hashes.
    • TP order: release is sorted; the _sessions order and the rescan_starts keys are sorted; prepends are sorted by block id. The connector sorts too.
    • _gdn_block_size == 0 is short-circuited for dense models.
    • A prefix-cache reset only makes later lookups miss.
  • Group ids are used once: checked against rollout/data.py and the validation counter in controller.py.
  • Overlap searches: "session kv" and "prefix cache vllm". These found #6008, #6420 and #6291 (stacked on this PR) and #5953. None rewrites the evictor.

Not verified: vLLM and SGLang behavior (neither is installed here); test_kv_offload.py's release block, which now runs on every config, at this head. A maintainer still needs to review.

Before merge: fill in the human-written summary.

Comment on lines +159 to +163
# A late request of a released group (an abandoned attempt still in transit) would
# re-create a session that nothing releases. vLLM's LRU reuses its blocks instead.
# Group ids are used once, so a released id only comes back with a late request.
if group_id in self._released_group_ids:
return

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.

Released-group memory is defined twice: here (plus the trim at :269-271) and in SGLangEngine (sglang/engine.py:382, :605, :788-790). Both share NUM_RELEASED_GROUP_IDS_KEPT in the base engine.py. The engine loop has the same late-request leak one layer up: _decide_next_action re-creates a released group's pin with _group_min_policy_versions.setdefault(...) (engine_loop.py:530), and nothing pops it again.

Rank 0's engine loop sees every release and every admission in order, and the releases in a decision come before its admissions. So it can own this once. In _decide_next_action, record message.group_ids from each SessionReleaseMessage. At stamping, mark a request of a released group as sessionless (e.g. routing_session_id = None) and skip its pin. Then track returns on None, SGLang passes it through, and both _released_group_ids copies go away. That is roughly +10 lines in engine_loop.py and -15 across the engines. The decision is broadcast, so every TP rank sees the same field.

has_state_in_use = has_state_in_use or bool(held_indices)
return has_state_in_use

def _evict_duplicate_copies(self, request: _TrackedRequest) -> None:

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 pass and _evict_superseded_gdn_states (:375) work around vLLM behavior that isn't specific to torchtitan. vLLM caches a second copy when a block is computed again (the docstring at :72 says "vLLM doesn't de-duplicate"), and align-mode GDN keeps a state at every block boundary of every request. Every vLLM user with siblings, MTP or hybrid models pays for both.

CLAUDE.md principle 3 asks for a TODO with an upstream issue link for each gap. The only TODO here (:94) points to vllm-project/vllm#51428, a session eviction hint, which wouldn't de-duplicate copies or bound GDN retention. Please file the vLLM issues, or show that #51428 covers them, and link them in a TODO at each method.

Comment on lines +255 to +256
for request in finished:
self._evict_duplicate_copies(request)

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.

finished holds replaced or released requests, but _evict_duplicate_copies always passes live_session=True. So a released group's extra copies are counted in num_evicted_live_session_blocks, which log_stats describes as "blocks live sessions no longer need". Either pass live_session=False here, or rename the counter to what it counts (e.g. num_evicted_extra_blocks: superseded states and extra copies).

self.engine._scheduler.token_to_kv_pool_allocator, ChainAllocator
)

def test_a_late_request_of_a_released_group_starts_no_session(self):

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 test runs twice on B200 CI. TestSGLangBitwiseParityGDNHiCache inherits it, and integration_test_rl_b200.yaml:124 launches both GDN and GDNHiCache. It has nothing to do with GDN or parity, so put it in TestSGLangBitwiseParityVarlen, which runs once. It also only checks the session_id the engine hands to SGLang and the engine's private _group_sessions. If it is meant to guard "SGLang reopens the session", assert on SGLang's own session table instead. Unverified: I didn't look up that attribute's name.

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