Repository navigation
feat(scheduler): requeue requests under memory pressure and cache cancelled prompts - #4509
Conversation
…orting them At the hard watermark the enforcer asks the scheduler to keep a busy model's requests. The scheduler stores their KV to the paged SSD cache, drops the batch in one step, and resumes them one at a time on the same stream.
…uest A client disconnect or cancel now stores a decoding request's prompt and a chunked prefill's progress, so a resend of the same prompt restores them.
|
A gap in the cancel path: external (non-chunked) prefill Thanks for the smaller rewrite — this is much easier to reason about than the stack. My independent numbers line up with yours: cancel during decode on a 32.5k-token prompt gives I think the cancel-keeps-cache path misses one case, and it happens to be the one long-prompt agent traffic hits. What I read in After
With This PR does not touch Evidence from my deployment
That is exactly the shape of the problem this PR targets: an agent client gives up on a long cold prefill, and the resend starts from zero. The missing branch, if it helps I had implemented this case before finding the stack, and it is small. The live
Measured on
For the decode row: 5 runs per arm, alternating, no overlap between arms (feature off → 0 cached and a full re-prefill every time). The prefill row is a single run, so treat it as an existence check. And repeated time-limited attempts converge: one 238,484-token prompt cut at 42 s each time gave Happy to send that as a patch or a PR against this one if it's useful — or leave it to you if you'd rather keep the shape of the change yours. I can also just test a branch on this model and report, whichever is more useful. |
With chunked prefill off, a cancel lands inside the external prefill loop, where the request is neither running nor a chunked prefill. Extract the progress at the abort point and store it the same way as a cancelled chunked prefill.
|
@xain Confirmed. With chunked prefill off (the default), a cancel happens inside the external prefill, so the progress wasn't saved. My own test had chunked prefill on, so I missed it. Fixed in aa5d2f6. On Qwen3.8-27B with chunked prefill off, cancelling 60s into a 38k prompt and resending now reuses 24,576 cached tokens, and TTFT drops from 106s to 40s. Thanks for catching this. If you get a chance to try it on DeepSeek-V4.1, that would help too. |
|
With TurboQuant KV enabled, neither the requeue nor the cancel path keeps any tokens I ran #4509 through our pause/resume harness, rebased cleanly on main 64bf5d1, next to main itself. Setup: M5 Max 128 GB, Qwen3.8-27B-oQ4e-mtp with TurboQuant KV 4-bit and MTP, memory ceiling pinned at 48 GB, three greedy prompts of 130k, 115k and 100k tokens sent together. The requeue does what it promises. main aborts all three requests 26 s in; #4509 requeues them once and all three finish (3/3). Same result with images (3/3 vs 0/3). But nothing reaches the SSD cache. Pressure hit while the three were still prefilling, and the log shows:
The comment says prefill KV is still dense while TurboQuant blocks use another layout, so this looks like a known limit rather than a slip. Two options, depending on what you prefer:
Two smaller observations, in case they are useful:
Decode rows with TurboQuant were not exercised, since pressure always hit during prefill. Happy to rerun anything on aa5d2f6 if that helps. |
|
Tested on DeepSeek-V4.1 with chunked prefill off — the fix holds here too Ran
The log for the first row: and the resend reported One caveat on scope: this was with TurboQuant KV off, so it does not speak to the TurboQuant gate e-Evolution raised. |
|
@e-Evolution Confirmed. The prefill store skipped TurboQuant because the prefill KV is still dense at that point. Rather than logging the skip, the partial prefill cache now gets the same conversion a finished prefill gets before it is stored, so the blocks match what a normal TurboQuant request writes. This covers the requeue, the chunked cancel and the external cancel path. Fixed in e0c956f. On Qwen3.8-27B with TurboQuant 4-bit, the requeue log now shows 8192/8192 for each prefilling row instead of 0. I also ran three turns of 25k, 53k and 80k tokens with two mid-prefill cancels per turn, so every resend restored a TurboQuant prefix that had been saved, restored and extended again. All needles were found in every turn, the answers stayed coherent, and they drifted from a cold no-cache run no more than a normal TurboQuant prefix hit does. The lone-request and DFlash cases behave as intended, since neither is requeued. Thanks for running this through your harness. |
|
Thanks for e0c956f. I checked it with tests that compare the stored blocks byte for byte against a TurboQuant conversion of the whole prefix: requeue of a prefilling row, chunked cancel and external cancel. All match. The in-place conversion is fine where you use it, since those caches are dropped right after the store. For the record, I also ran aa5d2f6 against our stack on the same main (2c53654): same harness and runtime, Qwen3.8-27B-oQ4e-mtp with TurboQuant 4-bit and MTP. With three long requests decoding at a 48 GB ceiling, #4509 finishes 3/3. Our stack gets 2/3 because it cannot pause a batched Lightning MTP decode row. So your requeue covers a case ours did not. Three things the stack does that #4509 does not, in case any are worth a small follow-up. Each lives in its own PR, so you can take them separately or ignore them:
If you are not interested, feel free to close the stack PRs whenever it suits you. They have done their job as a reference. |
On v0.7.0 a request with max_tokens of 0 or below failed every request on its model: it was queued and fully prefilled, then mlx-lm's BatchGenerator.insert raised "Sequence N's max_tokens must be > 0." inside scheduler.step(), and engine_core's loop answers any step error with scheduler.fail_all_requests(). v0.7.1's requeue work (jundot#4509) clamps the insert cap to 1 (_insert_max_tokens), so such a request no longer takes the engine down, but it is still accepted: the whole prompt is prefilled and the client gets one token and HTTP 200, where the OpenAI and Anthropic APIs answer 400. And insert still refuses a row for other reasons (an empty prompt), which still fails every request on the engine. Fix it in three places: - The four generation routes check their cap first, before model load, lease or queueing: max_tokens on /v1/chat/completions (which also receives max_completion_tokens through the validation alias), /v1/completions and /v1/messages, and max_output_tokens on /v1/responses. A value below 1 raises InvalidRequestError, so the client gets the server's existing 400 validation shape: invalid_request_error with the field as param. The check runs before a StreamingResponse exists, so streamed requests get the 400 too. - Scheduler.add_request refuses max_tokens below 1 before it tracks or queues the request. That covers callers that do not come through these routes, such as a model-settings default. engine_core's add_request already cleans up and re-raises the typed error to its caller alone. - Both BatchGenerator.insert call sites catch ValueError and fail only the request being inserted: the direct insert in _schedule_waiting (cache hits, one-shot prefills and SpecPrefill) and _insert_prefilled_request, which completes a chunked prefill. On v0.7.1 the latter runs through _complete_chunked_prefill for both the head request and a packed companion, and inline for a first chunk that completes its prefill; each caller reports the refusal. mlx-lm validates every row (a non-empty prompt, max_tokens > 0, one option per segment) before it touches batch state, and each call inserts a single request. The refused request is torn down through _do_abort_request, the same path a client abort between prefill and insert takes, and gets a finish_reason="error" output. Other ValueErrors from insert are therefore isolated too, while step errors outside insert keep the fail-all recovery, because there the batch state is unknown. Tests: - Every route rejects 0 and -5, streamed or not, with 400, invalid_request_error, the field as param and the message, and never asks the pool for an engine. max_completion_tokens is covered too, and a cap of 1 is accepted on every route. - The installed mlx-lm's insert raises for max_tokens 0 or -5 and for an empty prompt without advancing uids or queueing anything; the isolation depends on this. - Scheduler.add_request refuses 0 and -5, accepts 1, and leaves nothing tracked or queued. - A refused insert (an empty prompt, the refusal that still reaches insert past the clamp) fails only that request on the cache-hit path, the chunked-prefill path, a first chunk that completes its prefill and a packed companion. The next queued request is inserted, a request already decoding stays running, another request still mid-prefill keeps its prefill state and tracking, the refused request's paged-cache blocks are released for eviction as a client abort does, and after a lone refusal the scheduler goes idle and a late abort of the refused id is a no-op. - With mlx-lm's real BatchGenerator and a tiny llama, an empty prompt fails alone while a decoding request finishes all its tokens. - scheduler.step() returns the refusal as that request's error output instead of raising. - EngineCore.add_request raises InvalidRequestError to its caller alone, leaves no collector behind, keeps an admitted request, and never calls fail_all_requests. Without the fix, the route, admission and isolation tests fail. Rebased onto v0.7.1 (was 9744036 on v0.7.0, with 0238c8a's tests folded in). The insert tests now trigger the refusal with an empty prompt, because the clamp turns their old max_tokens of 0 into 1; the chunked-prefill plumbing follows upstream's _complete_chunked_prefill; the first-chunk, packed-companion and real-BatchGenerator tests are new. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UnUQdL7be1M9NXFzY6AHab Claude-Session: https://claude.ai/code/session_01G7DbsyUGKr5LUjAL6Vr533
This replaces the pause-and-resume stack in #4478, #4479, #4480, #4481, #4482, #4483, #4484, #4485, #4486, #4487, #4488 and #4489 with a smaller change aimed at the same root cause. It was developed from @e-Evolution's idea and analysis in #4440. The never-fits capacity API and the cached-media suffix route from that stack are not part of this PR. The external prefill gap in the cancel path was reported by @xain, and the TurboQuant gap by @e-Evolution.
Summary
Two changes so the server stops throwing away work it has already done.
Works with text and vision models. No new settings.
Details
Validation
Qwen3.8-27B-oQ4e-mtp on the VLM engine with Lightning MTP, M3 Ultra.
Three concurrent long prompts (38k, 32.5k and 28k tokens) with a 40 GB custom ceiling and a 0.8 hard threshold:
The requeue stored the live rows in 0.8 to 1.0 s, and the resumed text continues at the seam with no repeated or missing tokens.
Cancel, then resend the same request:
Notes