Repository navigation
feat(scheduler): pause and resume a decoding row through an exact SSD prefix - #4481
Closed
e-Evolution wants to merge 23 commits into
Closed
e-Evolution wants to merge 23 commits into
e-Evolution wants to merge 23 commits into
Conversation
…during prefill Blocks were stored only when a request finished, so a request aborted mid-prefill lost all of its prefill work and a re-issue of the same prompt prefilled from token zero. With prefill_progress_commit_blocks = N (0 = off, the default), chunked and external prefill now store every N completed blocks under the request's own block table, which stays alive so later commits and the final store extend it. Each commit window is detached from the live cache; TurboQuant layers are converted with the same rules as the final conversion (the codec is per-vector and fixed-seed, so windowed blocks are byte-identical to whole-prefix ones), and a restored TurboQuant prefix is sliced from its packed state. Commits are skipped under soft or hard memory pressure, while a previous commit is in flight, and for prompts that are not a plain token prefix. Aborts and prefill failures wait for an in-flight commit and leave the committed blocks in the prefix cache. A request requeued after a prefill memory failure still prefills cold, as _requeue_or_fail_prefill documents, when the setting is on. BlockAwarePrefixCache.store_cache gains cache_covers_suffix_only so a window longer than the stored prefix is not mistaken for a full-sequence cache.
Add scheduler.prefill_progress_commit_blocks to the scheduler settings (and OMLX_PREFILL_PROGRESS_COMMIT_BLOCKS), validate that it is not negative, and pass it to SchedulerConfig.
… MLX thread Teardown of a request with an in-flight incremental prefill commit no longer waits up to 60s on the inference thread. The destructive steps (block release, snapshot retirement and cleanup) are queued and run on the scheduler thread once the commit future has finished, whether it succeeded or not. Commits get their own single-thread executor so they never queue behind final stores, and the final store of a request is chained after its own commit on the store worker. Shutdown waits a bounded time and abandons stuck commits.
…el commits at shutdown
…commit A stuck commit blocked the final-store worker forever, holding store-gate slots and stalling admission. The wait is now bounded; on timeout the final store is skipped, logged once, the gate slot is released and the table and snapshot teardown stays deferred behind the commit.
…dule Scheduler.shutdown was no longer the first shutdown definition in scheduler.py, so the registry-cleanup guard test inspected the executor's shutdown instead and failed (a regression from the deferred commit teardown earlier in this series). Behavior is unchanged: Scheduler.shutdown still releases registry rows by model.
Add scheduler.memory_pressure_park, max_parks_per_request and park_resume_ok_polls settings (env overrides, default off). At hard, non-emergency pressure the enforcer asks each scheduler to park a prefill victim and defers the abort while one is parkable; the legacy abort runs when nothing is left to park, the deferral budget is spent, or pressure is an emergency. Every poll reports its level to the schedulers for the resume hysteresis.
… of aborting it With memory_pressure_park on, the scheduler consumes the enforcer's park flag at step start and parks one victim per step: the most recent chunked-prefill arrival, never the oldest while another is parkable. The request keeps its stream, prompt and arrival time, drops its live cache through the deferred teardown, and re-queues in arrival order ahead of newer requests. It resumes after park_resume_ok_polls consecutive ok polls with a fresh prefix lookup that restores the committed blocks, bypasses the cold-retry guard and the admission-stall timeout, and its committed blocks are pinned (block refs plus SSD index hashes) until the resume, finish or abort. Bulk pressure aborts spare parked requests.
…el loaded abort_all_requests spared parked requests whenever no reason was given, so idle-LRU eviction and the emergency busy-victim path left them orphaned or blocked the pending unload from draining. Make it an explicit spare_parked keyword (default False) and pass True only from the non-emergency hard keep-loaded path.
… blocks reclaimable from RAM - clear parked on abort and guard the deferred pin by request identity - consume the ok streak on resume; max-hold and stale-monitor escapes resume one per pass - stop pinning parked blocks in the hot cache; SSD pin plus dirty-eviction write-back keeps them restorable - count the settle window in enforcer polls instead of queries - replace the victim sentinel with an explicit flag
…t lost hot-cache write-back on resume
…ry skip reason Conversations that carry an image resend it every turn, so the VLM engine prefills them through the external loop with fused embeddings and request-wide media cache keys. That loop never called the incremental commit and the commit guard excluded any prompt with media keys, so long prompts never became durable and were re-prefilled in full after an abort. Media prompts now commit under the same extra-key arguments their final store uses (block keys depend only on where a block ends), except for models that need an atomic multimodal prefix. Every early return of the commit path logs its reason once per request at INFO, each commit logs its token range, and a park request that finds no victim logs why per request.
…rdown watchdog The engine-close watchdog exits the process after 60s without SSD write progress. A final store waited up to 120s for a stuck commit and shutdown could spend 40s on commit waits before reporting any progress. The final-store wait now polls and stops as soon as shutdown cancels the commits, the shutdown waits total at most 20s, and a commit that is still writing is reported to the watchdog as persistence progress.
On the non-emergency hard path with no parkable request, abort only the live request holding the most KV (newest arrival breaks ties) and keep the rest running; the enforcer re-measures next poll, at most one victim per poll. Emergency and unload keep abort-all as a safety brake. Parked requests stay spared. Gated by the memory.abort_single_victim setting (off by default).
store/fetch/restore_exact_prefix take an optional domain_key that enters every block hash of the chain, so two requests with identical tokens (or identical image placeholders over different images) never collide, and domain blocks stay out of dedup and ordinary prefix matching. Scheduler._pin_blocks generalizes the parked-prefill pin; _pin_exact_chain holds a stored exact chain all-or-nothing in the block pool and the SSD index until _unpin_parked releases it.
The single-victim abort is deferred to the next scheduler step, so a following enforcer poll could see the first victim's memory still held and sacrifice a second request, cascading back toward abort-all. The enforcer now tracks the draining victim: while its abort is pending (EngineCore.memory_victim_pending) or until one more poll after it ran, no other victim is chosen, bounded by _SINGLE_VICTIM_SETTLE_MAX_POLLS. Relief below hard forgets it; emergency still aborts everything. A failing engine hook now falls back to abort-all for that poll, and abort_one_request_for_memory reports a chosen-but-not-aborted victim with skipped="no_client" or "already_finished" instead of the None that means no victim at all. The single-victim block no longer splits the emergency/spare_parked comment from its call.
Scheduler.request_decode_pause asks for a decoding row to be paused at the next step start. The pause emits the row's pending token through the normal response path (a token that finishes the request is left to the step, which completes it normally), stores the row's KV as an exact chain under a request domain, pins it, and removes the row the way an abort does while the request keeps its output, detokenizer, parser session, rope deltas and client stream. A _DecodeResume record keeps the sampler, logits processors, stop machine, remaining max_tokens and the KV token sequence; the request waits parked in arrival order. _park_exclusion_reason names the v1 exclusions for decoding rows: SpecPrefill, VLM-MTP, DFlash, active MTP speculation, no paged SSD tier, a split-GDN layout without an exact sidecar writer, and layouts that cannot round-trip. Nothing selects decoding victims yet. Until the exact resume lands, re-admitting a paused row ends it with the structured error decode_resume_lost (with its token counts) instead of waiting forever.
A re-admitted paused row skips the prefix lookup, prefill and preflight: restore_exact_prefix rebuilds the row's KV under its request domain, the pins are released, and the row is inserted with the last output token as kickoff, the saved token sequence as all_tokens, the remaining max_tokens and the stashed sampler, logits processors and stop machine. The RNG is not reseeded and prompt usage is not counted again; the batched-decode gate already counts prompt plus output. An exact-restore miss (or a restored length that disagrees) ends the request with the structured error decode_resume_lost, counted in the park stats. Greedy output after a pause at decode token 1, 255 or 256 equals an uninterrupted run, alone or beside a second row, inline and split GDN.
…code pause A resumed decode row got a fresh stop-sequence matcher, so a multi-token stop sequence that began before the pause was missed: the stop token was appended and caught only by the text matcher. The resume now hands mlx-lm the stashed matcher position through a one-shot StopSequences wrapper. Greedy-identity tests cover stop sequences spanning one and two pauses, held stop prefixes, text and parser stops completed by the pending token, parser tool-call state, the thinking budget, repetition penalty context and the max_tokens budget over two pauses.
With no prefill to park, the enforcer now pauses one decoding row through request_decode_pause: the largest live KV first, the newest arrival on ties, the oldest admitted request only when it is the sole candidate. The pause is tracked as the draining victim; its status stays pending until the pause ran and its exact chain left the SSD write buffers, then one settle poll passes before another victim is chosen. Only when no row is pausable, or a pause was declined, does the single-victim abort run. Emergency pressure still aborts everything. A pause that fails before the row leaves the batch (extract, store, pin or any exception) keeps the row decoding untouched, unpins and deletes the chain found by its domain hashes, and marks the request so it is not chosen again. A failure after the pending token streamed ends the request with decode_pause_failed. A parser or text stop on the pending token also deletes the chain it stored.
…re a pause A singleton Lightning MTP row was excluded from decode pause because its pending token lives in the speculative queue. The pause now asks handoff_singleton_mtp_for_pause for the late-join handoff: it waits while more than one committed token is queued (the pause stays pending, bounded by _DECODE_PAUSE_MAX_DEFERRED_STEPS), then leaves the batch in the standard invariant, so the exact-prefix store and its offset guard apply unchanged. A failed handoff declines the pause and the row keeps decoding. Batched Lightning MTP, DFlash, VLM-MTP and SpecPrefill stay excluded. The handoff is checked on the real patched BatchGenerator with the MTP suite's CountingModel: the KV holds exactly prompt plus streamed tokens, and a resume on a fresh generator with MTP on matches an uninterrupted MTP run.
This was referenced Oct 12, 2026
Closed
This was referenced Oct 12, 2026
Owner
|
I'm closing this PR as part of the pause-and-resume stack replaced by #4509. I've posted the replacement's scope and remaining proposals in the discussion update. |
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.
Summary
Slice 4 of 12 of the pause-and-resume cycle proposed in #4440 (the improvement is explained in the write-up's section The strategy: pause, don't abort). Depends on #4480 (S1). GitHub shows every earlier unmerged slice in this diff; please review only this slice's 5 commits below. I keep it as a draft and rebase it on
mainafter the previous slice merges.A decoding row could not be paused, so the first spike after a park hit decoding requests and the fallback aborted them. This slice pauses one decoding row instead.
extract_cache([uid])(with an offset guard),store_exact_prefixunder a per-request domain key, pin, and the row leaves the batch without wiping its output. The sampler, logits processors, stop-sequence matcher position, parser state and remainingmax_tokensare stashed, and the request is queued as parked. The client stream stays open and usage is not double-counted.restore_exact_prefixplusinsertwith the last output token as kickoff and the stashed state: no prefill, no preflight, no RNG reseed. A cache miss ends the request withdecode_resume_lost.Default: Behind
scheduler.memory_pressure_park(off) from P-b; with it off no row is ever paused.Stack and merge order
Each slice applies on the one before and keeps
main's behaviour with its switches at their defaults. Merge in this order:Commits in this slice (12 files changed, 2719 insertions(+), 25 deletions(-)):
Validation
python -m pytest tests/test_memory_decode_pause.py tests/test_mlx_lm_mtp_pause_handoff.py tests/test_scheduler_decode_pause.py tests/test_scheduler_decode_pause_continuity.py tests/test_scheduler_decode_pause_victims.py tests/test_scheduler_prefill_memory_guard.py tests/test_process_memory_enforcer.py tests/test_prefix_cache.py tests/test_paged_ssd_cache.py tests/test_engine_core.pypytest tests/ -m "not slow and not integration" -n 3 --dist loadgroup, Python 3.11, a venv withmain's pins) at this slice's tip onmainf3ad34d: 17,356 passed, 4 failed, 721 skipped;mainf3ad34d: 17,119 passed, 3 failed, 718 skipped. The 3 failures aretests/test_gemma4_rendering.pyon both (a local asset model without a chat template). One more failure in this run,tests/test_cluster_rdma_mailbox.py::test_a_daemon_ending_the_registration_is_noticed, is load-sensitive: it passes alone 3/3 on this tip, and the stack touches no cluster files.main; Black is clean on the changed lines. Every commit importsomlx.serverandomlx.schedulerand collects its tests.The real-model numbers below are in the write-up's Final results section.
Real-model runs: Apple M5 Max (128 GB), macOS 27.0.1, Python 3.11, Qwen3.8-27B-oQ4e-mtp (4-bit, Lightning MTP, TurboQuant 4-bit KV), one server at a time, one run per scenario. They used my fork rebased on
mainc0b1056 (this whole cycle plus my fork's other features), againstmainc0b1056 from the same venv; the stack on currentmainwas not run on the real model.max_tokensover two pauses are covered too.What remains untested: Batched Lightning MTP, DFlash, VLM-MTP and SpecPrefill rows are not pausable. Reusing the prompt blocks in the exact chain, or an off-thread store, is a follow-up. One Mac and one model family.
Checklist
Contribution from the lead maintainer of ADempiere (https://github.com/adempiere/adempiere/tree/hotfix/3.9.4.002). Author: victor.perez@e-evolution.com.