Skip to content

[Refactor] mem_cache: Plan, admit and reclaim unified memory through one layout search - #48012

Merged
ch-wan merged 1 commit into
mainfrom
cheng/refactor/unified-kv-window-names
Nov 9, 2026
Merged

ch-wan merged 1 commit into
mainfrom
cheng/refactor/unified-kv-window-names

Conversation

@ch-wan

@ch-wan ch-wan commented Nov 3, 2026 •

Copy link
Copy Markdown
Collaborator

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:

  • a take could refuse what admission had let through, or move pages admission had not priced;
  • a host load-back admitted on room only eviction makes raised its reservation before the eviction ran, and its reservation scope was skipped on chains with at most one window;
  • admission shrank a chunk under transient pressure, so a request that would fit once running requests finished was cut into chunks that could never all fit at once;
  • capacity reads disagreed with what a take could serve, since only a take counted the room a relayout makes.

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):

  • Every chain take comes from one planned layout: ChainAllocator.realize applies first_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, in move_order).
  • A relocation goes through the page gate: its destinations are acquired, its sources released and fenced for their readers, and its hole list is 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 (network_held_pending, held_pending_count), and fixes them while it runs; a PD receive row moves only when nothing else fits.
  • A host load's reservation pins exactly the pages its take handed out (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).
  • A planned take uses holes, then settles the oldest pending batches that cover it, then its planned extension; a float's planned take never grows without its block, and a float a settle left with no live or fixed page parks before a planned placement, as the planner priced it. Planned and unplanned takes share that order.
  • A relief that must rearrange the chain first checks that some layout serves the demand (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_into asserts that its float holds none, and _lay_out compacts the listed ends with flush_for_allocation. A relief served in place moves nothing and settles only what its takes need.
  • The read-ahead before a relief's first wait includes the held receive rows a relief reads (network_rows). _plan_and_take, realize, lay_out_for, the relief and take_planned_pages each run as one allocator operation, so a multi-band take reads every band once before its first wait.
  • State slots are taken at the frontier and bound in one kernel.
  • A HiCache load-back takes every part inside one reservation scope (scoped_physical_takes), on every chain shape.

Capacity reads (chain.py, kv/storage.py, allocator/*.py, new mem_cache/capacity.py):

  • units_available, state_slots_available and the window and state usages are the planner's answer (memoized per demand shape until the capacity changes, so available_size and full_available_size of 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.py holds 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), and discipline chooses, 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):

  • 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. It waits only while something will free memory (work admitted earlier in the pass, a forward or host copy in flight, including HiCache buffer-only write-through, rows held by other running work); otherwise it takes the largest chunk that fits now, and a request no chunk fits is aborted with HTTP 503 instead of waiting forever (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.
  • Admission (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).
  • Every admission path of a unified chain selects its chunk limit through one helper (_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.
  • Under --enable-unified-memory with 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 and fit_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-size below the grid is refused at startup.
  • The whole-request check on an empty pool counts the state slots a cached prefix hit already holds or pins (the working copy, its tracking slots and the cached checkpoint, 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 in demand.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.
  • On ROCm, where the MegaMoE backend retires window rows once per forward rather than once per interval of tokens, the demand's retirement interval is SGLANG_SWA_EVICTION_INTERVAL times the draft tokens a forward commits (demand.windows_retire_by_forward).
  • Each request's demand is built once per purpose (demand_inputs), with the scheduler's window retirement (demand.window_retirement, a WindowRetirement: one configured chunk behind a prefill's frontier under the overlap scheduler without prefix sharing; for decode, SGLANG_SWA_EVICTION_INTERVAL and 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_rows and only_parked_rows_held count 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 read pre_alloc_size low.

Reclaim (unified_radix_cache.py, base_prefix_cache.py, unified_cache/components/*.py):

  • The prefix cache owns reclaim: 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).
  • _reclaim first 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.
  • Under the write-back policy, on a chain without window bands, allocation-driven reclaim evicts the fewest token sub-pool tokens whose eviction admits the demand as one target (_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.
  • Components ask for what their load or copy takes (KVDemand) instead of a precomputed shortfall.

PD decode preallocation (disaggregation/decode.py, prefill.py):

  • One demand sizes a preallocation: the owner's fill and every window's tail in whole pages, plus the decode reservation, computed once per request and admitted through 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_alloc and 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.py alone is 1404 lines). Suggested order:

  1. kv/alloc/chain.py (realize, admits, units_available, scoped_physical_takes) and band.py (relocate_into, take_planned_pages, relieve): the take path over the planner from the previous PR.
  2. mem_cache/capacity.py and allocator/base.py: one entry point per capacity question, and the reclaim discipline.
  3. prefill_budget.py (ChainPrefillBudget.check_prefill) and schedule_policy.py (_check_prefill_budget, _select_prefill_admission, add_one_req_ignore_eos): the admission rule and the chunk limit.
  4. unified_radix_cache.py (evict_for_alloc, _reclaim, _owner_tokens_short, reclaim_jointly): cache-owned reclaim.
  5. disaggregation/decode.py: the preallocation demand and per-window budgets.
  6. Tests: 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, above min_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, and TestAdmission: 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.py replays recorded sequences, among them a planned placement of a float a settle emptied), test_unified_release_after_forward.py (on relocate_into, plan and token_demand), and the main tests rewritten from the interim policy and the movers to the planner.
  • Capacity contracts kept by their callers: lazy Mamba tracking passes the total slots it needs (KVDemand(state_slots=len(candidates))) to evict_for_alloc, which subtracts what is free itself; ChainPrefillBudget's scalar remaining_total / remaining_current count owner (FULL) tokens (full_available_size), the unit priority preemption compares against.

Behaviour changes

With --enable-unified-memory:

  • Admission waits under transient pressure instead of shrinking the chunk; it shrinks a chunk only when the request could never fit whole on an empty pool, priced over its whole prompt.
  • With the prefix cache disabled (ignore_eos admission), a unified request is admitted at the same chunk limit as ordinary admission.
  • Under write-back HiCache without window bands, a reclaim's dirty victims are backed up in one submission instead of one per victim; with a state sub-pool, only the shortfall token evictions alone can serve is batched.
  • Reported availabilities (the pool stats and every capacity read) come from the planner, so they include the room a relayout makes.
  • A decode preallocation and a host load-back are admitted on the same rule as a prefill.
  • Each window's demand covers the rows the scheduler's retirement keeps live: during decode up to SGLANG_SWA_EVICTION_INTERVAL rows (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.
  • The memory clip prices a lone request as admission does, with one page of allocation rounding per sub-pool, so in a pool of a few pages a prompt within a page of the capacity is refused where the per-band arithmetic admitted it (a main unit test with a 6-page pool now uses 8 pages).

Everything else the unified pool served before is still served. Without --enable-unified-memory nothing changes: static pools keep their own reclaim hooks through the same entry points.

Accuracy Tests

This stack is validated at its top, on main a4b8801197: 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 against main, all reported in #48014.

Checklist

  • Format with pre-commit on the changed files.
  • Unit tests added and updated.

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-test to run the tests your change touches, or copy this prompt for an agent:

Find the registered tests this PR affects and run them with /rerun-test, following https://github.com/sgl-project/sglang/blob/main/.agents/skills/rerun-test/SKILL.md

@github-actions github-actions Bot added hicache Hierarchical Caching for SGLang blackwell SM100/SM120 unified-radix-cache memory-pool labels Nov 3, 2026
@ch-wan
ch-wan force-pushed the cheng/refactor/unified-kv-float-placement branch from b6195ea to f292a70 Compare November 4, 2026 06:18
@ch-wan
ch-wan force-pushed the cheng/refactor/unified-kv-window-names branch from 39809f6 to 164edbf Compare November 4, 2026 06:18
@ch-wan
ch-wan force-pushed the cheng/refactor/unified-kv-float-placement branch from f292a70 to c2ff1e1 Compare November 4, 2026 07:42
@ch-wan
ch-wan force-pushed the cheng/refactor/unified-kv-window-names branch from 164edbf to 87d1e52 Compare November 4, 2026 07:42
@ch-wan
ch-wan force-pushed the cheng/refactor/unified-kv-float-placement branch from c2ff1e1 to b151c13 Compare November 4, 2026 08:02
@ch-wan
ch-wan force-pushed the cheng/refactor/unified-kv-window-names branch 2 times, most recently from d5f0cd4 to 1e87663 Compare November 4, 2026 09:14
@ch-wan
ch-wan force-pushed the cheng/refactor/unified-kv-float-placement branch 2 times, most recently from 0e9fa77 to 68e9611 Compare November 4, 2026 09:31
@ch-wan
ch-wan force-pushed the cheng/refactor/unified-kv-window-names branch from 1e87663 to b1ed043 Compare November 4, 2026 09:31
This was referenced Nov 4, 2026
@ch-wan
ch-wan force-pushed the cheng/refactor/unified-kv-window-names branch from 37356ef to 11bafd4 Compare November 6, 2026 01:16
@github-actions

This comment has been minimized.

@ch-wan
ch-wan force-pushed the cheng/refactor/unified-kv-float-placement branch from 5561fd1 to c346787 Compare November 6, 2026 03:37
@ch-wan
ch-wan force-pushed the cheng/refactor/unified-kv-window-names branch from 11bafd4 to 2fe3264 Compare November 6, 2026 03:37
@github-actions

This comment has been minimized.

@ch-wan
ch-wan force-pushed the cheng/refactor/unified-kv-float-placement branch from c346787 to a947dc4 Compare November 6, 2026 06:34
@ch-wan
ch-wan force-pushed the cheng/refactor/unified-kv-window-names branch from 2fe3264 to 2f0af51 Compare November 6, 2026 06:34
@github-actions

This comment has been minimized.

@ch-wan
ch-wan force-pushed the cheng/refactor/unified-kv-float-placement branch from a947dc4 to ab9752e Compare November 6, 2026 10:43
@ch-wan
ch-wan force-pushed the cheng/refactor/unified-kv-window-names branch from 2f0af51 to c2aca19 Compare November 6, 2026 10:43
@github-actions

This comment has been minimized.

@ch-wan
ch-wan force-pushed the cheng/refactor/unified-kv-float-placement branch from ab9752e to cf19426 Compare November 6, 2026 12:31
@github-actions

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

apple-silicon blackwell SM100/SM120 documentation Improvements or additions to documentation hicache Hierarchical Caching for SGLang memory-pool unified-radix-cache

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant