Repository navigation
fix(sglang): retry prefill batches that the kvcached pools cannot back - #554
Conversation
A hybrid model runs two kvcached pools in one SGLang process, and each pool reports its free count from the whole device's free memory, so a batch admitted against the token count can still miss on the Mamba slots or on the tokens. SGLang treats a miss after admission as fatal, and the scheduler exits. Inside the batch allocation window the elastic allocators now raise KVCachePoolExhausted instead of returning None. The alloc_for_extend wrapper releases the rows and slots the batch received and raises a batch-carrying miss. At the scheduler the wrapper releases the admission lock and the match-time Mamba state, returns the requests to the head of the waiting queue, caps the next round at one request fewer, and returns no batch. For decode the elastic allocators take over the 0.5.19+ gate and reserve the step's pages there, and a shortfall retracts instead of failing in alloc. Fixes ovg-project#547 Signed-off-by: Rishabh Sinha <[email protected]>
shipiyouniao
left a comment
There was a problem hiding this comment.
The 23 existing capacity-miss tests pass. Two additional CPU fault-injection probes expose incomplete recovery: an asymmetric TP allocation miss produces different batch decisions, and a partial SWA allocation loses the successful child's token blocks on each retry. Details inline. These probes use the patched wrappers; the SWA probe also executes the unchanged v0.5.20 composite alloc method. They are not GPU/NCCL validation.
After these are fixed, please validate the recovery path on SGLang with real GPU pressure, including an asymmetric TP miss. Also, please use Refs #547 rather than Fixes #547 while the shared-budget part and the explicitly excluded exhaustion paths remain outstanding.
…apacity-miss Signed-off-by: Rishabh Sinha <[email protected]>
…artial allocations Each SGLang TP rank drives its own kvcached pool, so a prefill batch can miss on one rank and fit on its peers, and the peers would carry the batch into the forward while the missing rank retries alone. The alloc_for_extend wrapper now follows every local attempt with one MAX all-reduce of a miss flag over the attention TP and CP CPU groups, once per attempt and never conditional on allocator state, so a miss anywhere unwinds every rank the same way and the requeue and the cap are identical. The decode gate reduces its reservation verdict the same way, so one short rank retracts everywhere. The batch window journals the token blocks the elastic allocators hand out, and a miss returns them to the manager that gave them: a peer's miss returns this rank's whole allocation, and a miss in the SWA composite's second child returns the first child's blocks instead of leaking them on every retry. Refs ovg-project#547 Signed-off-by: Rishabh Sinha <[email protected]>
…nt order The rendezvous recorded the two ranks' miss flags in thread arrival order, so the assertion on them depended on which thread deposited first. CPU pytest 3.11 saw [1, 0] against the expected [0, 1]. The fake now records the flags sorted. Signed-off-by: Rishabh Sinha <[email protected]>
|
round 2 pushed, head fb39167. both probes are regressions now, red at 57b07f5 and green at the head, 29 tests in the file. for tp the verdict is one MAX all-reduce per alloc_for_extend call and per decode gate over the attention tp and cp cpu groups, the groups sglang broadcasts the queue along. it runs whatever the local outcome and the ranks stay in step, and a peer that fit returns everything its own call handed out and requeues with the same cap. for swa the window journals token blocks, and the composite's partial allocation goes back through it. body updated with the coverage statement, dp attention covered, pp not, admission reading per-rank counts stays with the shared-budget pr, plus Refs #547. full cpu manifest 1299 passed with the failure set identical to main, mypy 3.10 to 3.13 clean. a two gpu tp run with an asymmetric miss is still pending on my side, runbook written for a 2x L40S box, logs follow once it has run. |
|
/ci run |
Nightly correctness · 2026-10-13 · PASSRun · kvcached b6fa209 (merged into main at 80450dc) All 22 cases passed. Setup of every caseOn request in a pull request (gpu-pr.yml) on 2x NVIDIA L4 (23034 MiB, driver 580.178.04); the SGLang and vLLM cases run at the same time, one GPU each. kvcached is installed from the pull request merged into main into each engine's official image; each case starts one server in it.
CasesEach kvcached case is compared with the native case of the same engine and model.
Each case:
Elastic tests
Limit tests
Logs: artifact, kept 30 days: serve.log and cmd.txt per case, summary.json with every request's tokens, setup.json, run.log, GPU state at the end. |
|
The ci result shows this PR fixes the problem on single GPU. But the multi-gpu problem still needs @rishabhsinha17 's effort |
|
opened #577 with a weekly ci case for the tp path: qwen3.5-4b at tp2 across both l4s, plus a second 4b pinned to gpu 1 that gets its load while the tp server holds its own, so rank 1 runs short and rank 0 does not. three checks read the miss lines of both ranks in serve.log. meant for /ci run weekly against this pr once that one merges. the pod runbook stays the fallback if the runner is busy. |
|
the shared-budget half is up as #578, stacked on this one. once per scheduler iteration the ranks of a queue group MIN-reduce their pools' free counts and admit and evict from the smallest, so the batches and the radix trees match and the miss flags line up after. the weekly case in #577 is the real test. |
shipiyouniao
left a comment
There was a problem hiding this comment.
Rechecked b6fa209: 30 existing capacity/autopatch tests pass. The findings below use CPU reproductions and SGLang 0.5.20 code inspection; I have not run real TP/PP GPU recovery.
Also confirmed the admission/eviction gap already tracked in #578: budgets 16/6 admit [a,b]/[a] despite both allocations succeeding; Mamba eviction differs by four slots and decode eviction by two tokens. The MAX reduction at patches.py:2609 happens after those decisions. These three CPU regressions fail here and pass on #578, confirming the existing dependency.
|
@rishabhsinha17 I checked #554/#578 against #487 and prepared a local combined candidate. I'd like to keep physical accounting and reservation ownership in #487, with #554 handling rollback/requeue and #578 providing the agreed scheduling budget. The separate In the local combination, I removed the separate guard registration without changing your production implementation. 121 targeted CPU tests pass, including constructed allocation-denial and rollback cases. We still need the normal SGLang 0.5.20 elastic-serving scenario and real TP validation before retiring the guard. The cleanup must land together with, or after, the recovery path; it isn't safe to merge independently. Does this split work for you? |
The retry and the decode gate agree a miss within a pipeline stage only, so a stage that recovers a miss alone leaves the other stages waiting on its sends. With more than one pipeline stage, keep SGLang's own behaviour: the prefill wrappers pass through and the decode gate is the native one. The decode gate reserved the step's blocks with alloc(), which keeps a request's blocks on one page, and the paged allocator's alloc_packed() then took those reserved blocks first, so decode stopped filling the small holes: with pages of 3, 5 and 40 free blocks, a gated alloc_packed(7) took all seven from the 40. try_to_reserve() can now place blocks as alloc_packed() would, and the paged gate asks for that.
|
/ci run weekly |
|
i fixed changes requested by @shipiyouniao. After the ci run weekly succeed, i will merge this one, then #487 |
Weekly correctness · 2026-10-18 · PASSRun · kvcached 9702a79 (merged into main at d5de5d7) All 26 cases passed. These cases pass, though some prompts' greedy tokens differ from native: fewer than half of each phase's prompts, which is most likely numerical. Greedy decoding flips between near-tied tokens, and the engines also do this between their own runs.
Setup of every caseOn request in a pull request (gpu-pr.yml) on 2x NVIDIA L4 (23034 MiB, driver 580.178.04). kvcached is installed from the pull request merged into main into each engine's official image; each case starts one server in it.
CasesEach kvcached case is compared with the native case of the same engine and model.
Each case:
Elastic tests
Logs: artifact, kept 30 days: serve.log and cmd.txt per case, summary.json with every request's tokens, setup.json, run.log, GPU state at the end. |
|
The weekly correctness result above looks like indeterministic of inference engine, as this pr modifies the sglang end, not vllm end. And last weekly correctness result is ok. This result means this pr fixed the problem on TP scenario in SGLang, but the test which will be added in #577 should still fail until #578 got merged. |
shipiyouniao
left a comment
There was a problem hiding this comment.
LGTM, both review points are addressed. Thanks for the fixes!
…dles misses ovg-project#554 returns a prefill batch that the pools cannot back to the waiting queue, so the separate admission guard is no longer needed; both wrapped Scheduler._get_new_batch_prefill_raw. Also drop the A/B benchmark script.
|
the split works for me. i rebased #578 on main at 1f6517e, one commit over #554 and #487. on the ledger it adds one agreed forecast per iteration. every rank reads each manager's available_size(), the count #487 clamps to the per-GPU ledger, one MIN reduce over the queue groups makes the shortest forecast the budget of all, and the allocators serve it plus the round's own moves. nothing to unregister on the guard, c511e8d on the #487 branch dropped admission.py and its tests before the merge, so main has one recovery path. a pipeline skips the round, like the miss patches. 40 tests in the capacity-miss file, 6 red without the round, cpu manifest 1471 passed, failure set as main, mypy 3.10 to 3.13 clean. the weekly case in #577 is the acceptance test once its rework is in. |
The round hooks the same methods from 0.5.13 on: the three scheduler entries it wraps, the attention TP and CP groups it reduces over, and the elastic SWA and Mamba slot allocators it reads, which first exist at 0.5.13 (the allocator split). Users of 0.5.13 to 0.5.19 hit the same TP admission desync as 0.5.20, so the gate moves from 0.5.20 to 0.5.13. The two miss patches of ovg-project#554 keep 0.5.20, where check_decode_capacity and the prefill unwind they rely on exist, so below 0.5.20 the ranks admit the same batch and a physical miss stays fatal, as native. A boundary test pins the range: at 0.5.13 two ranks admit the same batch from one MIN reduce and no MAX reduce follows, at 0.5.12 nothing is wrapped and each rank admits from its own count. The 0.5.19 test now expects the round in and the miss patches out. Signed-off-by: Rishabh Sinha <[email protected]>
Summary
Part of #419 item 3. Hybrid models such as Qwen3.5-4B run two kvcached pools in one SGLang process, the attention tokens and the Mamba slots, and each pool reports its free count from the whole device's free memory. SGLang admits a prefill batch against the token count and then allocates Mamba slots and tokens. Any miss after admission is fatal by native design, because native pools are static and the budget cannot be wrong. With kvcached the budget is a snapshot that the sibling pool, or another process (#467), consumes first, and the scheduler exits with the two errors in #547. This PR adds the fallback, the second of the two parts #547 lists. Either pool missing during batch preparation releases the rows and slots the batch received and returns its requests to the waiting queue, SGLang's own retry path. Under TP the ranks that share the waiting queue agree on the verdict before any of them runs the batch. Its shared budget is the first part and a separate PR. This fallback matters with or without it, because the cross-process case stays.
Root cause
Admission reads only the attention allocator.
PrefillAdder.rem_total_tokensisavailable_size()of the token allocator plus the evictable tree (schedule_policy.py#L720), andalloc_req_slotsreads the Mamba count only after the batch exists (allocation.py#L301-L322).Past admission the path is fail-loud. None from a token allocation raises RuntimeError (allocation.py#L160-L169, #L229-L238), and
HybridReqToTokenPool.allocasserts on a None Mamba slot (memory_pool.py#L1445) and ping-pong pair (#L1597) after it has already bound request rows and earlier slots. No handler exists in the scheduler loop.run_scheduler_processlogs the traceback and signals the parent (scheduler.py#L5859-L5862).For decode there is a gate, but it compares a snapshot.
check_decode_memasks the allocator (allocator/base.py#L79-L93) and retracts on False. Thenprepare_for_decodeadvances the penalizer state before it allocates (schedule_batch.py#L3453-L3464), and a miss there cannot run the preparation again.Under TP each rank has a kvcached pool of its own (
interfaces.pybuilds the manager withworld_size=1), while SGLang hands every rank of the queue group the same requests (request_receiver.py#L170-L213) and expects them to build the same batch. A miss on one rank after admission is a rank-local event, and a rank that retries alone leaves its peers in the forward with a batch it does not have.vLLM has one pool and a native miss channel. #453 and #511 turn its exhaustion into
allocate_slotsreturning None, and the scheduler preempts and retries.Changes
Allocator level. The elastic token and paged allocators,
ElasticMambaPoolandElasticMambaSlotAllocatorkeep returning None on a miss (the #545 contract) except inside a batch allocation window, where they raiseKVCachePoolExhausted, the type #453 introduced. The SWA composite's own pre-check None gets the same typed raise inside the window. Such a window exists because every None insidealloc_for_extendis fatal natively, whilealloc_group_beginand the lazy ping-pong slot rely on the None outside it. Only a capacity shortfall makes the manager return None, and its contract violations and native fatal errors raise on their own, which keeps the translation as narrow as the vLLM one.Inside the window the elastic token allocators also journal every token block they hand out, as
(manager, block ids). Rolling back returns those ids, and no others, to the manager that gave them, newest first, before anything has bound them. That journal is what makes a partial allocation safe to retry: the SWA composite allocates from its full-attention child first and its SWA child second (swa.py#L219-L232), and a miss in the second child used to leave the first child's blocks with nobody to return them. SGLang writes the full-to-SWA mapping only after both children succeed, so no mapping entry exists at that point.ScheduleBatchCapacityMissPatchwrapsschedule_batch.alloc_for_extendin the window. On the typed miss it returns the journaled blocks, frees the request rows, the Mamba slot and the ping-pong slots that the call handed to requests which held none at entry, and raisesSGLangPrefillCapacityMisswith the batch. Rows and slots that a request already owned at entry, the chunked continuation's, are left alone.TP. After the local attempt, and before the exception or the result leaves the wrapper, every rank of the queue group reduces a miss flag: one MAX all-reduce over the attention TP CPU group and, with context parallelism, one over the attention CP CPU group, the two groups SGLang itself broadcasts the queue along (
attn_cp_tp_broadcast_pyobj), andget_attn_tp_groupis the TP group itself when DP attention is off. Whatever the local outcome, the reduce runs once peralloc_for_extendcall. Every rank then issues the same number of collectives, and nothing waits on a peer that took another branch. A rank whose own allocation succeeded while a peer missed returns its journaled blocks and the rows and slots it handed out, restores the KV lengths the call wrote, and raises the same signal with a peer-miss cause. Every rank's scheduler wrapper then runs the same unwind, the same requeue and the same cap. Agreement sits afteralloc_for_extendbecauseprepare_for_extendmutates request state only after that call returns (schedule_batch.py#L2677-L2770). So a peer that has to let go of a batch has none of that to undo. Attp_size == 1, or without a parallel state, the local verdict stands and no collective runs, so the single-GPU path does what round 1 did.SchedulerCapacityMissPatchwrapsScheduler._get_new_batch_prefill_raw. On that miss it releases the admission lock with its receipt and the match-time Mamba state, the same revert the scheduler applies to a candidate it did not add (scheduler.py#L3951-L3966), restores the chunked request parked with nothing new to cache, returns the requests to the head of the waiting queue in order, clearsbatch_is_fulland returns no batch. Its next prefill round admits one request fewer than the batch that missed, through the schedule bag's scoped override ofprefill_max_requests, and a round that fits lifts the cap, which shrinks the retry instead of repeating the same batch. One request that cannot fit waits for the running batch or the other process to free memory, as on vLLM. Any other exception still exits the scheduler.Decode. Here the elastic allocators define
check_decode_capacity(0.5.19+): evict as native, then reserve the step's pages throughKVCacheManager.try_to_reserve. That reservation verdict goes through the same reduce, once per call, so one short rank retracts everywhere. Whichever rank reserved keeps its pages, and the retract loop's next gate re-reserves the same set. Failing the reservation takes the native retract path, and the allocation that follows draws the reserved pages, which cannot run out inside the process.Coverage under the parallel modes. Covered: a post-admission miss on any subset of the ranks sharing a waiting queue, with or without DP attention (each DP rank's attention TP group decides for its own queue, and the native DP-wide MLP sync runs after it as before), and context parallelism by construction, not by a GPU run. Not covered: pipeline parallelism. Each PP stage reduces within its own TP group, and the stages attempt different microbatches, so a miss on one stage retries on that stage alone, as a stage-local exhaustion would natively. Admission itself can also read different
available_size()on different ranks before any allocation, since the count is per-GPU physical memory. It belongs to the shared-budget part and the separate PR.Both scheduler-side patches read the 0.5.20 request and batch shapes and register for
>=0.5.20. Out of scope and still fail-loud as native: the match-time COW slot inMambaRadixCache._alloc_mamba_slot(mamba_radix_cache.py#L1061-L1068), which asserts on its own under the same exhaustion and needs an SGLang-side fallback, mixed-chunk decode preparation (scheduler.py#L4049-L4051), which runs without the gate, and allocations outsidealloc_for_extend, such as the speculative draft's and the PD decode side'salloc_extend_swa_tail, which keep the None contract.Validation
CPU only, mock-based, in the existing test style: 29 tests in tests/test_sglang_capacity_miss.py.
Against main at debcb09 the file does not import, and its unpatched-pipeline controls reproduce the issue's two errors, AssertionError "Not enough space for mamba ping pong idx" and RuntimeError "Out of memory", with the requests gone from the queue and their rows and slots still bound. Patched, both become a retry: free lists byte-equal to before the round in both pools, locks released with their receipts, queue order preserved, cap applied on the next round and lifted after a round that fits.
Round 2 adds the two review probes as regressions, each run against the round 1 head 57b07f5 before the fix.
test_tp_peer_miss_unwinds_every_rankruns two fake ranks on two threads over a rendezvous that replaces the gloo all-reduce, with only rank 1's token pool missing. At 57b07f5 rank 0 ends withhas_batch=True, queued=[], holds_row=[True, True], cap=Noneand rank 1 with the opposite; now both end identical, requeued with cap 1, free lists back to before on both, one collective with flags[0, 1], and the same capped batch on both once rank 1's pressure lifts.test_tp_peer_miss_unwinds_mamba_slots_toodoes the same with the hybrid pools, andtest_decode_gate_agrees_across_rankspins the decode verdict,[True, False]before and[False, False]after, with the reserving rank keeping its pages.test_swa_partial_allocation_is_returned_before_retryruns the composite'sallocshape over two elastic children with the SWA child missing after the pre-check: at 57b07f5 the full child's free count falls 16, 12, 8 on three retries; now it stays 16 on every retry, the mapping is never written, and the request runs once the child is back.test_window_journals_token_blocks_and_returns_themandtest_paged_window_journals_the_new_pages_onlypin that the window records the ids the manager returned, including only the new pages of a pagedalloc_extend, and that a rollback returns them newest first.Full CPU manifest 1299 passed, failure set identical to main at 43ed583 on the same machine (the same 12 environment cases). check_test_classification valid, cpu=63. ruff, isort, codespell clean. CI-exact mypy 1.11.1 without torch, 3.10 to 3.13, clean on kvcached and tests.
No GPU run on my side yet. One two-GPU TP=2 run on SGLang 0.5.20 remains the check, and the runbook for it is ready: Qwen3.5-4B, symmetric pressure as in the issue's reproduction, then an asymmetric miss forced on one rank only by a process pinning memory on one GPU mid-serve, with the pass criteria being no hang, the same miss line and cap on both ranks in the same iteration, and the queued requests completing after the pressure lifts.
Refs #547
Signed-off-by: Rishabh Sinha [email protected]