Repository navigation
[Refactor] mem_cache: Plan, admit and reclaim unified memory through one layout search - #48012
Merged
Merged
Conversation
ch-wan
force-pushed
the
cheng/refactor/unified-kv-float-placement
branch
from
November 4, 2026 06:18
b6195ea to
f292a70
Compare
ch-wan
force-pushed
the
cheng/refactor/unified-kv-window-names
branch
from
November 4, 2026 06:18
39809f6 to
164edbf
Compare
ch-wan
force-pushed
the
cheng/refactor/unified-kv-float-placement
branch
from
November 4, 2026 07:42
f292a70 to
c2ff1e1
Compare
ch-wan
force-pushed
the
cheng/refactor/unified-kv-window-names
branch
from
November 4, 2026 07:42
164edbf to
87d1e52
Compare
ch-wan
force-pushed
the
cheng/refactor/unified-kv-float-placement
branch
from
November 4, 2026 08:02
c2ff1e1 to
b151c13
Compare
ch-wan
force-pushed
the
cheng/refactor/unified-kv-window-names
branch
2 times, most recently
from
November 4, 2026 09:14
d5f0cd4 to
1e87663
Compare
ch-wan
force-pushed
the
cheng/refactor/unified-kv-float-placement
branch
2 times, most recently
from
November 4, 2026 09:31
0e9fa77 to
68e9611
Compare
ch-wan
force-pushed
the
cheng/refactor/unified-kv-window-names
branch
from
November 4, 2026 09:31
1e87663 to
b1ed043
Compare
This was referenced Nov 4, 2026
Merged
Merged
Merged
ch-wan
force-pushed
the
cheng/refactor/unified-kv-window-names
branch
from
November 6, 2026 01:16
37356ef to
11bafd4
Compare
This comment has been minimized.
This comment has been minimized.
ch-wan
force-pushed
the
cheng/refactor/unified-kv-float-placement
branch
from
November 6, 2026 03:37
5561fd1 to
c346787
Compare
ch-wan
force-pushed
the
cheng/refactor/unified-kv-window-names
branch
from
November 6, 2026 03:37
11bafd4 to
2fe3264
Compare
This comment has been minimized.
This comment has been minimized.
ch-wan
force-pushed
the
cheng/refactor/unified-kv-float-placement
branch
from
November 6, 2026 06:34
c346787 to
a947dc4
Compare
ch-wan
force-pushed
the
cheng/refactor/unified-kv-window-names
branch
from
November 6, 2026 06:34
2fe3264 to
2f0af51
Compare
This comment has been minimized.
This comment has been minimized.
4 of 5 tasks
ch-wan
force-pushed
the
cheng/refactor/unified-kv-float-placement
branch
from
November 6, 2026 10:43
a947dc4 to
ab9752e
Compare
ch-wan
force-pushed
the
cheng/refactor/unified-kv-window-names
branch
from
November 6, 2026 10:43
2f0af51 to
c2aca19
Compare
This comment has been minimized.
This comment has been minimized.
ch-wan
force-pushed
the
cheng/refactor/unified-kv-float-placement
branch
from
November 6, 2026 12:31
ab9752e to
cf19426
Compare
This comment has been minimized.
This comment has been minimized.
…one layout search A unified chain answered its capacity questions through a per-shape interim policy (`kv/alloc/interim.py`): two token ends priced their shared gap jointly, a floating window was priced in place with per-member end flushes, and admission, reclaim, the capacity reads and the takes each re-derived that answer. A take could then disagree with the admission that let it through, and a host load-back could be admitted and then fail its reservation. Takes and reliefs: - Every chain take comes from one planned layout (`ChainAllocator.realize` over `pricing.first_plan`): bands in place take holes and extend, ends compact only when the layout needs it, and floats relocate into their planned block (`FloatBand.relocate_into`, `Band.take_planned_pages`). The relocation goes through the page gate: its destinations are acquired, its sources released and fenced, and its hole list marked for rebuilding. - A relief keeps rows a network transfer touches and held receive rows in place whenever a layout serves the demand that way, and fixes them while it runs, so a PD receive is moved only when nothing else fits. - State slots are taken at the frontier and bound in one kernel. - A host load-back takes every part inside one reservation scope (`scoped_physical_takes`), on every chain shape. Capacity and admission: - Capacity reads (`units_available`, `state_slots_available`, the window and state usages) are the planner's answer, so a read counts the room a relayout makes, as a take does. - One admission rule: `ChainAllocator.admits(KVDemand)` is asked by the prefill budget, the decode capacity check, the memory clip and the PD decode preallocation alike. Under transient pressure a request waits; its chunk is cut only when the whole request could never fit. A request is not left waiting when only parked session rows hold memory. - Each request's demand is built once per purpose (`demand_inputs`): the memory clip prices the request on the token capacity with its state slots and a draft's own window and cuts on the truncation alignment, and the prefill adder passes the admitted chunk limit to the budget. Reclaim: - The prefix cache owns reclaim: `evict_for_alloc(KVDemand)` evicts victims in its own order until the demand is served, window entries first where a cached prefix is worth more than its windows, and pools sharing one memory are reclaimed jointly. `capacity.discipline` picks the shared-memory or per-pool way from what the allocator declares, in one place. - The decode preallocation sizes the owner's fill and every window's tail in whole pages from one demand, computed once per request. Removed: `interim.py`, the per-shape pricing (`ends_*`, `float_*`, `no_relief_plan`, `sequential_fit`), the float movers (`make_room`, `compact_holes`, `_relocate_to_positions`) with their mover waits, the neighbour-credit reads, and the no-relief planned take.
This was referenced Nov 9, 2026
[Feat] deepseek-v4: Rebuild the evicted SWA window on a cache hit instead of prefilling again
#43009
Open
Merged
3 of 5 tasks
4 of 5 tasks
Closed
3 of 5 tasks
Open
3 of 5 tasks
4 of 5 tasks
2 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This PR is part of a stack (oldest at bottom):
Motivation
Under
--enable-unified-memory, a chain of bands answered its capacity questions through a per-shape interim policy (kv/alloc/interim.py, about 1400 lines): two token ends priced their shared gap jointly, a floating window was priced in place with per-member end flushes, and float movers made room on demand. Admission, reclaim, the capacity reads and the takes each re-derived their answer from those rules. They could disagree:The previous PR added a layout planner and a demand type with no caller. This PR switches every capacity question of a unified chain to them and removes the interim policy. Replacing only some consumers would leave two capacity rules side by side, which is how the disagreements above arose, so the switch is one PR.
Modifications
Takes and reliefs (
kv/alloc/chain.py,band.py,page_usage.py,pricing.py):ChainAllocator.realizeappliesfirst_plan's layout. Bands in place take holes and extend, ends compact only when the layout needs it, and floats relocate into their planned block (FloatBand.relocate_into,Band.take_planned_pages, inmove_order).network_held_pending,held_pending_count), and fixes them while it runs; a PD receive row moves only when nothing else fits.Band._acquired_host: the extension range and the holes taken, from the free list's host copy), so cancelling it unpins everything it pinned, also when the take placed an emptied float afresh (TestACancelledLoadReleasesItsPins).feasible): a demand none serves is refused before any pending page settles. It then enters the urgent-recovery scope over every band (settle_pending_for_recovery): read ahead, settle every pending page, park a float left with no live page. The plan is made inside it, so the plan and its realization see holes and live pages only;FloatBand.relocate_intoasserts that its float holds none, and_lay_outcompacts the listed ends withflush_for_allocation. A relief served in place moves nothing and settles only what its takes need.network_rows)._plan_and_take,realize,lay_out_for, the relief andtake_planned_pageseach run as one allocator operation, so a multi-band take reads every band once before its first wait.scoped_physical_takes), on every chain shape.Capacity reads (
chain.py,kv/storage.py,allocator/*.py, newmem_cache/capacity.py):units_available,state_slots_availableand the window and state usages are the planner's answer (memoized per demand shape until the capacity changes, soavailable_sizeandfull_available_sizeof a chain without windows share one answer; a chain with no float, one band or two ends, computes it directly, joint queries over several sub-pools included (_ends_only_fit, confirmed by one feasibility check at the value and one past it) instead of searching), so a read counts the room a relayout makes, as a take does.capacity.pyholds the questions the scheduler asks of a cache and its allocator together (check_decode_capacity,evict_to_free_tokens,reclaim_for_prealloc,admit_preallocation,create_prefill_budget), anddisciplinechooses, in one place, whether a pool's sub-pools share one memory (evict, then check the whole demand) or are pools of their own (each pool's shortfall).Admission (
prefill_budget.py,managers/schedule_policy.py,managers/scheduler.py):ChainAllocator.admits(KVDemand)is asked by the prefill budget, the decode capacity check, the memory clip and the PD decode preallocation alike.AddReqResult.UNSCHEDULABLE). Whether it could ever fit is priced on an empty pool over the whole request: every prompt row, nothing cached, host-hit rows as prompt rows (check_prefill(host_hit_tokens=)), since the request's own cached prefix is locked while it is admitted and is not pressure that subsides; the rest of the request is then asked to fit now at the limit that check gives. A request is not left waiting when only parked streaming-session rows hold memory.ChainPrefillBudget.check_prefill) and the final shape check (can_allocate_prefill) charge a host hit's token rows alike, page-ceiled with the extend they join, so a request one admits the other does not refuse (test_prefill_demand_agreement.py::TestHostHitChargedAlike)._check_prefill_budget), runs that chunk and commits the rest of the request at it: the ignore-EOS path (prefix cache disabled) included, for budgets that price whole requests (admits_whole_requests). Static budgets ignore the new arguments.--enable-unified-memorywith window sub-pools and a prefix-sharing cache that keeps Mamba checkpoints, every prefill chunk but a prompt's last is cut on the checkpoint grid (mamba_prefill_chunk_grid, through the truncation alignment andfit_chunk): a chunk shorter than the grid takes no checkpoint, and without one the window rows behind it are never retired during prefill. A configured--chunked-prefill-sizebelow the grid is refused at startup.KVStorage.held_state_slots), so such a request is cut to a smaller chunk instead of waiting on state only it holds (TestCachedStateHitMakesProgress). A request's commitment (reserve) is priced with the same cached prefix its admission credited (TestCommitmentIsTheAdmittedDemand). Known limit (FIXME at the bound indemand.py): the window bound assumes state checkpoints advance; when state slots run out, lazy tracking can skip a checkpoint and a checkpoint can fail to enter the prefix tree, so the window rows behind the old checkpoint stay live longer than priced. Every later chunk and decode step is still checked against the pool as it is, so such a request waits or is retracted; the bound is optimistic only while state slots are exhausted, so admission is an estimate there, not a guarantee that the request finishes.SGLANG_SWA_EVICTION_INTERVALtimes the draft tokens a forward commits (demand.windows_retire_by_forward).demand_inputs), with the scheduler's window retirement (demand.window_retirement, aWindowRetirement: one configured chunk behind a prefill's frontier under the overlap scheduler without prefix sharing; for decode,SGLANG_SWA_EVICTION_INTERVALand the rows a decode allocates ahead: the per-step allocation reserve under speculative decoding (get_alloc_reserve_per_decode), else one row under the overlap scheduler and none without it). The prefill budget reads it for its tree cache, and the scheduler passes it to the memory clip (max_new_tokens_for_memory(retirement=)). The memory clip prices a request on the token capacity, with its state slots and a draft's own window, and cuts on the truncation alignment; when no shorter chunk is on the grid it prices the configured chunk. The prefill adder passes the admitted chunk limit to the budget.KVStorage.others_hold_rowsandonly_parked_rows_heldcount rows by state, which the admission reads: the request table's free list spans the PD preallocation rows too, so a count derived from it readpre_alloc_sizelow.Reclaim (
unified_radix_cache.py,base_prefix_cache.py,unified_cache/components/*.py):evict_for_alloc(KVDemand)evicts victims in the cache's own order until the demand is served (_reclaim), window entries first where a cached prefix is worth more than its windows, and pools sharing one memory are reclaimed jointly (reclaim_jointly). A pool of its own is reclaimed by its shortfall (evict_pool_shortfalls)._reclaimfirst returns the frees queued in the caller's free group (fits_after_frees), before any decision, so a reclaim inside a free group (a state checkpoint during prefill result processing) finds the room they make._owner_tokens_short), so dirty victims share one copy submission and one wait; a per-victim stop serves only what is left short. With a state sub-pool, evicting a token entry also frees its checkpoint, so only the tokens no other free can serve (past the live-token cap or the owner's virtual ids,ChainAllocator.owner_tokens_only_owner_frees_serve) are evicted as one target, and the per-victim stop serves the rest. Other policies and chains with window bands keep the per-victim stop.KVDemand) instead of a precomputed shortfall.PD decode preallocation (
disaggregation/decode.py,prefill.py):admit_preallocation, which folds the decode and retraction reserves into the demand and asks the chain's joint admission once, so a request is never refused on one sub-pool's scalar budget when evicting another sub-pool's entries would make room (TestSharedBytesServeEitherSide). Window budgets and retractable tokens are kept per window. Resuming retracted requests and popping preallocated ones read no capacity when their queue is empty.Removed:
kv/alloc/interim.py, the per-shape pricing (ends_*,float_*,no_relief_plan,sequential_fit), the float movers (make_room,compact_holes,_relocate_to_positions) and their waits,relieve_for_allocand the float's two-sided deficit relief,Band.begin_relief(the recovery scope reads ahead), the neighbour-credit reads, and the no-relief planned take.Reviewer guide
About 3200 production lines are added and 4200 removed; most of the removal is whole functions (
interim.pyalone is 1404 lines). Suggested order:kv/alloc/chain.py(realize,admits,units_available,scoped_physical_takes) andband.py(relocate_into,take_planned_pages,relieve): the take path over the planner from the previous PR.mem_cache/capacity.pyandallocator/base.py: one entry point per capacity question, and the reclaim discipline.prefill_budget.py(ChainPrefillBudget.check_prefill) andschedule_policy.py(_check_prefill_budget,_select_prefill_admission,add_one_req_ignore_eos): the admission rule and the chunk limit.unified_radix_cache.py(evict_for_alloc,_reclaim,_owner_tokens_short,reclaim_jointly): cache-owned reclaim.disaggregation/decode.py: the preallocation demand and per-window budgets.test_unified_chain_realize.py(a planned layout is reachable, and reads equal takes, as seeded properties; its relief cases free only live owner pages, abovemin_page_index), its admission cases (an admitted demand is served),test_unified_reclaim_victim_loop.py(victims in cache order, stopping at the first fit),test_prefill_demand_agreement.py(the purpose table, the memory clip, andTestAdmission: a locked prefix that needs a smaller chunk, ignore-EOS admission on an empty pool),test_multi_ended_allocator.py(a state reclaim inside a free group),test_write_back_eviction_batching.py(the copy submissions of allocation-driven reclaim on both tree cores, a reclaim over token and Mamba entries that stops once the demand fits, and one submission for a shortfall under the live-token cap with Mamba entries), the page-safety stress harness (python/sglang/test/unified_page_safety_harness.py,test/manual/mem_cache/unified_page_safety_stress.py: random allocation, free, forward and transfer sequences checked for host reads after a wait and for unsafe page reuse, with the pending batches of [Perf] mem_cache: Defer reuse of freed unified pages instead of waiting on every free #48852;test_unified_page_safety_stress.pyreplays recorded sequences, among them a planned placement of a float a settle emptied),test_unified_release_after_forward.py(onrelocate_into,planandtoken_demand), and the main tests rewritten from the interim policy and the movers to the planner.KVDemand(state_slots=len(candidates))) toevict_for_alloc, which subtracts what is free itself;ChainPrefillBudget's scalarremaining_total/remaining_currentcount owner (FULL) tokens (full_available_size), the unit priority preemption compares against.Behaviour changes
With
--enable-unified-memory:ignore_eosadmission), a unified request is admitted at the same chunk limit as ordinary admission.SGLANG_SWA_EVICTION_INTERVALrows (128 by default) past the window plus the rows decode allocates before retirement sees them, and for a chunked prefill under the overlap scheduler without prefix sharing one configured chunk more. The window demand is a deliberately conservative bound ([Refactor] mem_cache: Add a layout planner and request demand for the unified chain #48011), so a small window pool admits fewer requests at once than before, and the memory clip may grant fewer new tokens. A window-only prefix-sharing cache is priced a whole chunk more for the branch window it may lock, so such requests are admitted later or cut to smaller chunks.Everything else the unified pool served before is still served. Without
--enable-unified-memorynothing changes: static pools keep their own reclaim hooks through the same entry points.Accuracy Tests
This stack is validated at its top, on
maina4b8801197: the affected unit tests at the default and strict invariant levels, the CPU unit suite, the page-safety stress run and sweep, and serving accuracy and speed againstmain, all reported in #48014.Checklist
pre-commiton the changed files.CI States
Latest PR Test (Base): 🚫 Run #42608870994
Latest PR Test (Extra): 🚫 Run #42608870798
Latest PR Test (AMD ROCm 10): 🚫 Run #42608870793
Tip
Base CI only covers the core cases, and its workload may not exercise your change. Use
/rerun-testto run the tests your change touches, or copy this prompt for an agent: