Repository navigation
[rl] Evict an ended rollout's KV from vLLM's prefix cache - #5919
felipemello1 wants to merge 24 commits into
Conversation
|
Reply from claude: @claude please review |
|
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. |
There was a problem hiding this comment.
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
- The PR description's "Summary (human-written)" is empty. The author needs to write it (CONTRIBUTING.md, "AI-assisted contributions").
- 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_kvandengine._session_kv_holderin 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
BlockPoolinternals (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 realKVCacheManager, 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()iteratessets ofstr/bytes, whose order depends on the per-process hash seed. The only order-sensitive effect is the free-queue prepend, and that is sorted byblock_id. Map pop/reinsert in_cached_copiesrestores 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_messagesmakes 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. Sofinish()'sself._requests.pop(request_id)can't hitKeyErrorfrom the known paths. - Validation. Validation groups (
-(i+1)) always getrelease_groups(controller.py:745), so_session_ids_by_groupdoesn't grow without bound. - Callsites. Making
routing_session_idrequired is safe: every in-repoGenerateFncaller already passes it, andGenerator.generatealready 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.
| 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" | ||
| ) |
There was a problem hiding this comment.
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.
| # 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). |
There was a problem hiding this comment.
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.
148a53f to
f1a7d9d
Compare
|
Reply from claude: @claude please review again. Changes since your review (head
The human-written Summary is Felipe's to write. |
|
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. |
There was a problem hiding this comment.
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-109raisesValueErrorwhen any KV cache group'sblock_sizediffers fromblock_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_raisecovers 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)
- The PR description's "Summary (human-written)" is still empty. Felipe has to write it (CONTRIBUTING.md, "AI-assisted contributions").
- #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
BlockPoolinternals on the main generation path. Is that acceptable until vllm-project/vllm#51428 lands? The CPU tests run on the realKVCacheManager, 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. Therl_grpo_qwen3_5_debug_tp2_batch_invariantCI 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 // 2on 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.
|
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 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. |
|
Reply from claude: on the question about always-on use of vLLM's private
The calls: |
3d0504a to
f1a7d9d
Compare
f1a7d9d to
e078523
Compare
e078523 to
1b9ad81
Compare
|
Reply from claude: @claude please review again. The head is now
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 finished @felipemello1's task in 3m 41s —— View job Needs discussion: no new code problems at |
There was a problem hiding this comment.
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)
- The PR description's "Summary (human-written)" is still empty. Felipe has to write it (CONTRIBUTING.md, "AI-assisted contributions").
- #5847 (@acisseJZhong, open, updated 2026-11-20) still imports
VLLMSessionKVHolderand readsholds_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_sessionsis now only a backstop.release_groupsdrops 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 thereserveTODO, and that case also leaks the router's two new dicts, whichmax_sessionsdoesn't cap. You could delete the knob in the routing-only follow-up named in theRoutingContext.session_idTODO.
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
BlockPoolinternals 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 realKVCacheManager, 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_sessioncalled 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.
reservehas noawait, andrelease_groupsupdates its dicts before it awaits the fanout. So the Monarch concurrent endpoints can't interleave halfway through an update.release_sessionpops the session's generators before it awaits. Every in-reporeservecaller passesgroup_id(controller.py:704,actors/monarch/router.py:38, tests). EveryGenerateFncaller passes astrsession id (rollouter.py:530,verifiers/generation_server.py:243). _session_ids_by_groupgrowth. Training groups getrelease_groupson 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_closedis used only by the two release puts, and the crash path dropsSessionReleaseMessages that are still queued. - vLLM engine.
trackruns only in theelseof the admissiontry, 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.
|
Reply from claude: on the two open points in the last review. SGLang: closing a session while its request waits. Safe, at the commit
So the late request runs normally, and nothing keeps its session alive. With main's order, the request re-opened the session (
|
|
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 |
|
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. |
There was a problem hiding this comment.
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)
- 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
BlockPoolinternals (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.
1b9ad81 to
866d659
Compare
|
Reply from claude: @claude please review again. This PR is rewritten; the head is now
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. |
There was a problem hiding this comment.
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 inRequest.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_toocovers the [32, 16] layout on the realKVCacheManager, 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)
- 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
BlockPoolinternals (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.
… and why it waits
…s comment says group ids are used once
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).
|
Reply from claude: @claude please review 698de6e. Changes since your review of 44b74e3 (the body describes each):
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 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. |
There was a problem hiding this comment.
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
- 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
maintoo, so it can be its own PR. Keep the vLLMtrackskip here. 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).session_kv_evictor.py:435-- the one-copy pass and the GDN sweep work around vLLM behavior, but have no upstream issueTODO(inline).
Should consider
session_kv_evictor.py:256--num_evicted_live_session_blocksalso 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:62andSIMPLE_CPU_OFFLOAD.md:62say 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_hitandRequest.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_previoushands counts over, andnum_countedis a prefix. So_forget's "one counter fromindexon" holds. - Every
_num_requests_by_hash[...]read in the sweep comes after_count_all_new_block_hashes. - TP order:
releaseis sorted; the_sessionsorder and therescan_startskeys are sorted; prepends are sorted by block id. The connector sorts too. _gdn_block_size == 0is short-circuited for dense models.- A prefix-cache reset only makes later lookups miss.
- The counting stays prefix-closed.
- Group ids are used once: checked against
rollout/data.pyand the validation counter incontroller.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.
| # 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 |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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.
| for request in finished: | ||
| self._evict_duplicate_copies(request) |
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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.
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.VLLMEngine.Config.session_kv_holder, off by default: pins live sessions' blocksVLLMSessionKVEvictoralways runs and pins nothingGenerationEngine.holds_session_kv)reset_kv_cache_on_model_state_dict_load=FalsetrackProblem
Solution
ensure_session_generation), and nothing closes it again. Both engines remember the last 4,096 released groups (NUM_RELEASED_GROUP_IDS_KEPT).after_stepevicts it, unless a request counts its hash again.release_session_cache) once the saves pending at their eviction finish, so their CPU blocks go first too.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_unitand the align split.num_evicted_blockscounts ended sessions' blocks;num_evicted_live_session_blockscounts the blocks live sessions no longer need (superseded states, extra copies).log_statslogs both.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):
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
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):
trackafter a rewrite (counts the whole prompt), for scaleA turn that extends its history counts only its new hashes:
tracktakes ~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 withprefix_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.
You may ask:
release_session).use_eagle=True).Request.take_prefill_stats).prefix_cache_retention_interval=0, which caches no decode states? Each next turn would recompute the previous reply.Known issues / TODOs
release_session).__init__).NOTE:
Test plan
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 carrieslate/1).