From 8ba507811d05a9761ef98ed1728b6c103309400a Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Thu, 1 Oct 2026 13:47:55 -0600 Subject: [PATCH 01/46] feat(scheduler): commit completed prefill blocks to the prefix cache 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. --- docs/TESTING.md | 6 + omlx/cache/prefix_cache.py | 12 +- omlx/scheduler.py | 314 ++++++++++ .../test_scheduler_prefill_progress_commit.py | 549 ++++++++++++++++++ 4 files changed, 879 insertions(+), 2 deletions(-) create mode 100644 tests/test_scheduler_prefill_progress_commit.py diff --git a/docs/TESTING.md b/docs/TESTING.md index f39b692391..aeb9da1a04 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -228,3 +228,9 @@ Run `python -m pytest -q tests/integration/test_server_endpoints.py -k structure Run `python -m pytest -q tests/test_qwen4_qsa_decode_gather.py -k "batch_bank or batch_gather"` to check the batched QSA paths. The row-bank cases drive one attention layer through right-padded chunked prompt prefill, decode, verify windows, ragged vector rollback, reorder and drop filters, extend, trim and state restore, and require layer outputs and cache state to be bit-identical with fresh per-row indexer caches. The gathered cases compare batched decode steps and verify windows with the dense masked path: outputs allclose, cache state identical, every query bounded to the QSA budget plus its tail, and each fail-closed case kept on the dense path. Both groups include the served ratio 4 / top-k 512 geometry. For a real-server comparison, use the same model, prompts and cache state on main and the branch, with sessions of different lengths well past the QSA crossover (e.g. a 100K shared prompt plus 2K unshared tokens per session). Report aggregate decode while every stream is decoding, per batch size, with Lightning MTP on and off, and check a temperature-0 cold/warm identity and a multi-session codeword fan-out with prompts of different lengths. + +# Incremental prefill commit tests + +Run `python -m pytest -q tests/test_scheduler_prefill_progress_commit.py tests/test_settings.py -k "prefill_progress or commit"` to check `scheduler.prefill_progress_commit_blocks` (also `OMLX_PREFILL_PROGRESS_COMMIT_BLOCKS`; 0 = off, the default). The cases drive the real chunked and external prefill loops on a small initialized Qwen3.5 hybrid model (inline and split-GDN snapshots) and a small dense model, against real paged-SSD, boundary-snapshot and prefix stores, and compare restored-prefix logits with a cold forward pass. They cover commits every N blocks, a request aborted mid-prefill whose same-prompt re-issue resumes from the last committed boundary, completion after commits (same stored prefix, no duplicate blocks or leftover snapshot markers), a commit window longer than the restored prefix, TurboQuant windows matching whole-prefix conversion bit for bit, the memory-pressure skip, and the cold retry after a prefill memory failure. + +Mocked tests do not replace hardware validation: with a real model, abort a long prompt mid-prefill (for example with a low memory ceiling and two concurrent prompts), re-issue it, and check that the log reports a prefix cache restore at the last committed boundary instead of a full prefill. diff --git a/omlx/cache/prefix_cache.py b/omlx/cache/prefix_cache.py index 8cf3395a0e..d4f9c8e5c4 100644 --- a/omlx/cache/prefix_cache.py +++ b/omlx/cache/prefix_cache.py @@ -899,6 +899,7 @@ def store_cache( hot_cache_write_back: bool = True, _store_exact_terminal: bool = False, _store_tail_terminal: bool = False, + cache_covers_suffix_only: bool = False, ) -> BlockTable | None: """ Store computed cache for future reuse. @@ -926,6 +927,11 @@ def store_cache( ordinary prefix matching. _store_tail_terminal: Persist the trailing partial block as a tail block; ``tokens`` must end on a snapshot in ``boundary_snapshots``. + cache_covers_suffix_only: ``cache_data`` holds only the tokens + after the request's existing block table (an incremental + commit during prefill), never the whole sequence. Without this + a window longer than the stored prefix is indistinguishable + from a full-sequence cache. Returns: BlockTable for the stored cache, or None on failure @@ -1356,8 +1362,10 @@ def store_cache( # BatchGenerator.extract_cache() currently returns full-sequence cache. # When existing_tokens > 0, slicing with relative indices would save # wrong KV ranges for new blocks and corrupt future cache hits. - cache_uses_global_indices = existing_tokens > 0 and cache_seq_len >= ( - existing_tokens + 1 + cache_uses_global_indices = ( + not cache_covers_suffix_only + and existing_tokens > 0 + and cache_seq_len >= (existing_tokens + 1) ) if cache_uses_global_indices: cache_start = global_start diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 32c941e351..6502d54dd9 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -1335,6 +1335,12 @@ def _is_turboquant_kv_family_cache(cache_obj: Any) -> bool: ) or _is_turboquant_kv_cache(cache_obj) +def _prefill_commit_blocks(config: Any) -> int: + """``prefill_progress_commit_blocks`` of a config, 0 when unset or invalid.""" + value = getattr(config, "prefill_progress_commit_blocks", 0) + return value if isinstance(value, int) and value > 0 else 0 + + class _BoundaryStoreUnavailable(Exception): """No boundary-aligned snapshot exists for non-sliceable cache state. @@ -1845,6 +1851,12 @@ class SchedulerConfig: decode_fairness: bool = True # Set by the engine when MoE expert offload wrapped the model. moe_offload_active: bool = False + # Commit completed prefill blocks to the prefix cache every N blocks while + # a prompt is still being prefilled (0 = off, blocks are stored only when + # the request finishes). A request aborted mid-prefill then keeps its + # completed blocks, and a re-issue of the same prompt resumes from the last + # committed block boundary instead of prefilling from token zero. + prefill_progress_commit_blocks: int = 0 # Paged cache settings (internal defaults) paged_cache_block_size: int = 256 # Tokens per block @@ -2208,6 +2220,9 @@ def __init__( "max_rows": 0, "failures": 0, } + # request_id -> (future, committed token count) of the in-flight + # incremental prefill commit (see _commit_prefill_progress). + self._prefill_commits: dict[str, tuple[concurrent.futures.Future, int]] = {} self.requests: dict[str, Request] = {} # All requests by ID self.finished_req_ids: set[str] = set() # Recently finished self._generation_overflow_recovery_ids: set[str] = set() @@ -2758,9 +2773,15 @@ def _async_store_cache_worker( extra_key_token_start: int | None, extra_key_ranges: list[tuple[int, tuple[Any, ...]]] | None, hot_cache_write_back: bool = True, + incremental_commit: bool = False, ) -> None: """Run store_cache + paged_cache cleanup off the inference thread. + ``incremental_commit`` marks a mid-prefill commit: ``cache_to_store`` + holds only the tokens after the request's existing block table, and + the table stays alive so the next commit (or the final store) extends + it instead of re-storing from token zero. + Pre-conditions enforced by the caller (_cleanup_finished): - mx.eval() (a FULL, blocking eval — NOT async_eval) was called on the inference thread for all KV cache arrays in cache_to_store, so @@ -2793,6 +2814,7 @@ def _async_store_cache_worker( threading.RLock so concurrent access from main and worker is safe. """ self._store_cache_thread_id = threading.get_ident() + window_kwargs = {"cache_covers_suffix_only": True} if incremental_commit else {} try: # Hold _mx_buffer_access_lock across the worker's mx-buffer # access. store_cache eventually drives _extract_tensor_bytes, @@ -2817,6 +2839,7 @@ def _async_store_cache_worker( extra_key_token_start=extra_key_token_start, extra_key_ranges=extra_key_ranges, _store_tail_terminal=store_tail_terminal, + **window_kwargs, ) else: block_table = self.block_aware_cache.store_cache( @@ -2830,7 +2853,10 @@ def _async_store_cache_worker( extra_key_ranges=extra_key_ranges, hot_cache_write_back=False, _store_tail_terminal=store_tail_terminal, + **window_kwargs, ) + if incremental_commit: + return if block_table is None and self.paged_cache_manager is not None: block_table = self.paged_cache_manager.get_block_table(request_id) if block_table and self.paged_cache_manager is not None: @@ -4485,6 +4511,10 @@ def _chunk_route(n_tokens: int, cache_tokens: int) -> bool: self._emit_prefill_tail_snapshot( request, prompt_cache, total_tokens ) + if vlm_embeds is None: + Scheduler._commit_prefill_progress( + self, request, prompt_cache, base_size + processed_tokens + ) Scheduler._check_post_prefill_memory( self, @@ -6751,6 +6781,9 @@ def _finish_prefill_row(self, plan: _PrefillChunkPlan) -> None: self._emit_prefill_tail_snapshot( state.request, state.cache, total_tokens ) + Scheduler._commit_prefill_progress( + self, state.request, state.cache, state.base_size + state.tokens_processed + ) # Progress callback so the admin UI prefilling list advances during # chunked prefill. _do_external_prefill calls _on_prompt_progress @@ -7607,6 +7640,260 @@ def _emit_prefill_boundary_snapshot( ), ) + def _prefill_commit_blocked_by_pressure(self) -> bool: + """True while memory sits at or above the soft limit. + + A commit slices KV, quantizes it and materializes a snapshot, all of + which allocate; doing that when the guard is already struggling would + add to the pressure it is meant to survive. The hard limit lies above + the soft one, so this also covers hard pressure. + """ + limit = self._memory_limit_bytes + if limit <= 0: + return False + try: + return self._current_usage_bytes() >= limit + except Exception: + return True + + def _prefill_commit_window( + self, prompt_cache: list[Any], start: int, end: int + ) -> list[Any] | None: + """Detached cache list holding KV tokens ``[start, end)`` of a prefill. + + KV layers become windowed copies, TurboQuant layers get the same + conversion the finished request would receive, and non-sliceable layers + pass through untouched. Returns None for a layout whose window cannot + be stored faithfully (composite or unknown sliceable caches). + + The final store quantizes the whole fp16 prefix with the same + per-vector codec (norm, fixed-seed rotation, midpoints), so converting + a window yields byte-identical blocks. The layer signature is stamped + by the same ``_apply_turboquant_kv_convert`` rules. + """ + from mlx_vlm.turboquant import TurboQuantKVCache, _slice_state_range + + window: list[Any] = [] + for layer in prompt_cache: + if type(layer) in (_MLXKVCache, _vlm_cache.KVCache): + if layer.keys is None or layer.offset < end: + return None + piece = type(layer)() + piece.keys = layer.keys[..., start:end, :] + piece.values = layer.values[..., start:end, :] + piece.offset = end - start + window.append(piece) + elif type(layer).__name__ == "TurboQuantKVCache": + # A restored TurboQuant prefix keeps quantizing in place, so + # the window is a slice of the packed state. + if layer.keys is None or layer.offset < end: + return None + piece = TurboQuantKVCache( + bits=layer.bits, + seed=layer.seed, + key_bits=layer.key_bits, + value_bits=layer.value_bits, + ) + piece.key_codec = layer.key_codec + piece.value_codec = layer.value_codec + piece.keys = _slice_state_range(layer.keys, start, end) + piece.values = _slice_state_range(layer.values, start, end) + piece.offset = end - start + window.append(piece) + elif type(layer).__name__ in _KNOWN_SLICEABLE_CACHE_TYPES or type( + layer + ).__name__ in ("CacheList", "BatchRotatingKVCache"): + return None + else: + window.append(layer) + if self._turboquant_kv_bits is not None and self._turboquant_eligible( + prompt_cache + ): + self._apply_turboquant_kv_convert(window) + return window + + def _reap_prefill_commit(self, request_id: str) -> None: + """Retire a finished commit: drop snapshot markers it consumed. + + Runs on the inference thread. The commit worker moves (split-GDN) or + reads (inline) the staged snapshot of every committed boundary, so + their markers must not reach the final store, which would try to load + a moved file. A failed commit leaves them in place for the next try. + """ + pending = (getattr(self, "_prefill_commits", None) or {}).get(request_id) + if pending is None: + return + future, committed_tokens = pending + if not future.done(): + return + del self._prefill_commits[request_id] + try: + ok = bool(future.result()) + except Exception: + ok = False + if not ok: + return + snapshots = self._boundary_cache_snapshots.get(request_id) + if snapshots: + for token_count in [tc for tc in snapshots if tc <= committed_tokens]: + del snapshots[token_count] + + def _settle_prefill_commits(self, request_id: str) -> None: + """Wait for an in-flight commit before its request is torn down. + + Teardown releases the block table and removes the snapshot directory, + which the commit worker is still reading. Commits are a few blocks, so + the wait is short; the blocks it stores stay in the prefix cache. + """ + pending = (getattr(self, "_prefill_commits", None) or {}).get(request_id) + if pending is None: + return + try: + pending[0].result(timeout=60) + except Exception as e: + logger.warning("Prefill commit for %s did not settle: %s", request_id, e) + self._reap_prefill_commit(request_id) + self._prefill_commits.pop(request_id, None) + + def _commit_prefill_progress( + self, request: "Request", prompt_cache: list[Any], total_tokens: int + ) -> None: + """Make completed prefill blocks durable while the prompt is prefilling. + + Every ``prefill_progress_commit_blocks`` completed blocks, store them in + the prefix cache under the request's own block table, which stays alive + so the next commit and the final store extend it. A request aborted + later keeps these blocks: a re-issue of the same prompt matches them + and resumes at the last committed boundary. + """ + commit_blocks = _prefill_commit_blocks(getattr(self, "config", None)) + if commit_blocks <= 0: + return + try: + self._commit_prefill_progress_unchecked( + request, prompt_cache, total_tokens, commit_blocks + ) + except Exception as e: + # Durability is best effort; it must never fail the prefill. + logger.warning( + "Prefill progress commit failed for %s: %s", request.request_id, e + ) + + def _commit_prefill_progress_unchecked( + self, + request: "Request", + prompt_cache: list[Any], + total_tokens: int, + commit_blocks: int, + ) -> None: + rid = request.request_id + block_size = self.config.paged_cache_block_size + if ( + block_size <= 0 + or self.block_aware_cache is None + or self.paged_cache_manager is None + or self.paged_ssd_cache_manager is None + or self._store_cache_executor is None + ): + return + # Prompts that are not a plain token prefix cannot be keyed by token. + if ( + getattr(request, "vlm_extra_keys_for_cache", None) + or getattr(request, "vlm_extra_key_ranges_for_cache", None) + or getattr(request, "specprefill_indices", None) is not None + or self._specprefill_active_request_id == rid + ): + return + prompt = request.prompt_token_ids + aligned = min(total_tokens, len(prompt)) // block_size * block_size + + self._reap_prefill_commit(rid) + if rid in self._prefill_commits: + return # previous commit still running + table = self.paged_cache_manager.get_block_table(rid) + existing = table.num_tokens if table else 0 + if existing % block_size or (aligned - existing) // block_size < commit_blocks: + return + if self._prefill_commit_blocked_by_pressure(): + return + + window = self._prefill_commit_window(prompt_cache, existing, aligned) + if window is None: + if not getattr(self, "_prefill_commit_layout_logged", False): + self._prefill_commit_layout_logged = True + logger.info( + "Prefill progress commit disabled for this cache layout " + "(composite or non-standard sliceable layers)" + ) + return + tokens = list(prompt[:aligned]) + provider = None + with mx.stream(self._stream): + extracted, model_cache_config = self._extract_cache_states(window) + if _prompt_cache_needs_snapshots(prompt_cache): + override = self._get_boundary_store_override(rid, tokens) + if override is None: + return + tokens, boundary_cache, _, provider = override + if ( + getattr(provider, "tail_terminal_token_count", None) is not None + or len(tokens) <= existing + ): + return + extracted = self._merge_boundary_with_full_cache( + boundary_cache, extracted + ) + arrays = self._collect_arrays_from_extracted_cache(extracted) + if provider is not None: + for snapshot_cache in provider.iter_in_memory_extracted(): + arrays.extend( + self._collect_arrays_from_extracted_cache(snapshot_cache) + ) + if arrays: + # Concrete on this thread before the worker slices them (MLX + # streams are thread-local; see _async_store_cache_worker). + mx.eval(*arrays) + + future = self._store_cache_executor.submit( + self._commit_prefill_worker, + rid, + tokens, + extracted, + model_cache_config, + provider, + ) + self._prefill_commits[rid] = (future, len(tokens)) + logger.debug( + "Committing prefill progress for %s: %d -> %d tokens", + rid, + existing, + len(tokens), + ) + + def _commit_prefill_worker( + self, + request_id: str, + tokens: list[int], + window_cache: list[Any], + model_cache_config: Any | None, + snapshots: Any | None, + ) -> bool: + """Store a committed prefill window; True when the table covers it.""" + self._async_store_cache_worker( + request_id, + tokens, + window_cache, + model_cache_config, + snapshots, + None, + None, + None, + True, + incremental_commit=True, + ) + table = self.paged_cache_manager.get_block_table(request_id) + return bool(table is not None and table.num_tokens >= len(tokens)) + def _resolve_generation_prompt_start(self, request: "Request") -> None: """Locate the generation prompt; accept it only if its tokens end the prompt.""" suffix = getattr(request, "generation_prompt_text", None) @@ -10182,6 +10469,23 @@ def _model_has_unreconstructible_cache(self) -> bool: self._unreconstructible_cache_model = result return result + def _retry_prefills_cold_after_oom(self, request: Request) -> bool: + """Keep the cold retry that _requeue_or_fail_prefill promises. + + Re-attaching a cached prefix reproduced the oversized SDPA span that + failed the first attempt, so a request requeued after a prefill memory + failure prefills from token zero. With incremental commits enabled the + failed attempt leaves committed blocks in the prefix cache, which would + otherwise be attached here; a client re-issue still resumes from them. + Gated on the setting so the default behavior is unchanged. + """ + retries = getattr(request, "prefill_oom_retries", 0) + return ( + isinstance(retries, int) + and retries > 0 + and _prefill_commit_blocks(getattr(self, "config", None)) > 0 + ) + def _prepare_prefix_cache_for_request(self, request: Request) -> None: if request.request_id in self._prefix_cache_prepared: return @@ -10197,6 +10501,7 @@ def _prepare_prefix_cache_for_request(self, request: Request) -> None: if ( self.block_aware_cache is not None and not self._model_has_unreconstructible_cache() + and not self._retry_prefills_cold_after_oom(request) ): # Use paged cache fetch_started = time.perf_counter() @@ -11429,6 +11734,9 @@ def _do_abort_request(self, request_id: str) -> bool: return False self._clear_request_admission_bookkeeping(request_id) + # Committed prefill blocks stay in the prefix cache; let an in-flight + # commit finish before the table and snapshots are released below. + self._settle_prefill_commits(request_id) # Remove from waiting queue if request.status == RequestStatus.WAITING: @@ -11616,6 +11924,7 @@ def _drop_boundary_snapshots_for_request(self, request_id: str) -> None: must do the same or every failure strands a snapshot set until process exit (#3226). """ + self._settle_prefill_commits(request_id) self._boundary_cache_snapshots.pop(request_id, None) if self._boundary_snapshot_store is not None: try: @@ -13397,6 +13706,7 @@ def _release_paged_cache_for_request(self, request_id: str) -> None: very memory pressure that triggered the rejection) and orphan ``_request_tables`` entries. """ + self._settle_prefill_commits(request_id) if self.block_aware_cache is not None: self.block_aware_cache.release_cache(request_id) elif self.paged_cache_manager is not None: @@ -13447,6 +13757,9 @@ def _cleanup_finished(self, finished_ids: set[str]) -> None: if finished_drafter is not None: finished_drafter.release_request(request_id) request = self.running.get(request_id) + # A mid-prefill commit still in flight must land (and retire its + # consumed snapshot markers) before the final store reads them. + self._settle_prefill_commits(request_id) # Store cache for future reuse (G2-async): submit to background # executor so the post-finish 28GB+ memcpy doesn't block response @@ -14173,6 +14486,7 @@ def collect(request: Request | None) -> None: for request in retry_candidates: request.generation_overflow_retries += 1 request_id = request.request_id + self._settle_prefill_commits(request_id) self._boundary_cache_snapshots.pop(request_id, None) if self._boundary_snapshot_store is not None: self._boundary_snapshot_store.cleanup_request(request_id) diff --git a/tests/test_scheduler_prefill_progress_commit.py b/tests/test_scheduler_prefill_progress_commit.py new file mode 100644 index 0000000000..6d2ba72f47 --- /dev/null +++ b/tests/test_scheduler_prefill_progress_commit.py @@ -0,0 +1,549 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Incremental prefill commit: completed blocks become durable during prefill. + +The tests drive the real chunked-prefill step against a small initialized +Qwen3.5 hybrid model (GatedDeltaNet + full attention) with real paged-SSD, +boundary-snapshot and prefix-cache stores, then compare restored-prefix logits +with a cold forward pass. +""" + +import concurrent.futures + +import mlx.core as mx +import pytest +from mlx_lm.models.qwen3_5 import Model, ModelArgs + +from omlx.cache.boundary_snapshot_store import BoundarySnapshotSSDStore +from omlx.cache.paged_cache import PagedCacheManager +from omlx.cache.paged_ssd_cache import PagedSSDCacheManager +from omlx.cache.prefix_cache import BlockAwarePrefixCache +from omlx.request import Request, SamplingParams +from omlx.scheduler import Scheduler, SchedulerConfig + +BLOCK = 4 + + +def _tiny_hybrid_model(): + return Model( + ModelArgs( + model_type="qwen3_5", + text_config=dict( + hidden_size=32, + intermediate_size=64, + num_hidden_layers=2, + num_attention_heads=2, + num_key_value_heads=1, + head_dim=16, + full_attention_interval=2, + vocab_size=32, + linear_num_value_heads=2, + linear_num_key_heads=2, + linear_key_head_dim=16, + linear_value_head_dim=16, + linear_conv_kernel_dim=4, + partial_rotary_factor=1.0, + ), + ) + ) + + +class _Rig: + """A scheduler wired to real stores, plus helpers to drive prefill.""" + + def __init__(self, tmp_path, tokenizer, *, split, commit_blocks, tq_bits=None): + mx.random.seed(11) + self.model = _tiny_hybrid_model() + self.scheduler = Scheduler( + model=self.model, + tokenizer=tokenizer, + config=SchedulerConfig( + paged_cache_block_size=BLOCK, + gdn_ssd_split_enabled=split, + chunked_prefill=True, + prefill_step_size=BLOCK, + prefill_progress_commit_blocks=commit_blocks, + ), + ) + self.paged = PagedCacheManager( + block_size=BLOCK, max_blocks=64, initial_blocks=64, model_name="tiny" + ) + kv_type = "TurboQuantKVCache" if tq_bits else "KVCache" + self.ssd = PagedSSDCacheManager( + cache_dir=tmp_path / "cache", + max_size_bytes=16 * 1024**2, + expected_model_name="tiny", + expected_num_layers=2, + expected_block_size=BLOCK, + expected_layer_cache_types=["ArraysCache", kv_type], + gdn_ssd_split_enabled=split, + ) + self.boundary = BoundarySnapshotSSDStore(tmp_path / "cache") + self.prefix = BlockAwarePrefixCache( + model=self.model, + paged_cache_manager=self.paged, + paged_ssd_cache_manager=self.ssd, + gdn_ssd_split_enabled=split, + ) + self.prefix.set_gdn_checkpoint_loader(self.boundary.load_file) + s = self.scheduler + s.paged_cache_manager = self.paged + s.paged_ssd_cache_manager = self.ssd + s._boundary_snapshot_store = self.boundary + s.block_aware_cache = self.prefix + s._store_cache_executor = concurrent.futures.ThreadPoolExecutor( + max_workers=1, thread_name_prefix="omlx-store-cache" + ) + if tq_bits: + s._turboquant_kv_bits = float(tq_bits) + s.refresh_ssd_layer_signature() + + def start(self, request_id, tokens): + request = Request( + request_id=request_id, + prompt=list(tokens), + sampling_params=SamplingParams(max_tokens=1), + ) + self.scheduler.add_request(request) + self.scheduler.waiting.clear() + request.remaining_tokens = list(tokens) + return request, self.scheduler._begin_prefill(request, list(tokens), None) + + def step(self, state, chunks): + done = False + for _ in range(chunks): + done = self.scheduler._step_prefill_chunk(state) + self.drain() + return done + + def drain(self): + """Wait for every in-flight store or commit on the store executor.""" + self.scheduler._store_cache_executor.submit(lambda: None).result(timeout=20) + + def close(self): + self.scheduler.shutdown() + + def table_tokens(self, request_id): + table = self.paged.get_block_table(request_id) + return table.num_tokens if table else 0 + + def probe(self, tokens): + """Prefix lookup a fresh request with the same prompt would perform.""" + table, remaining = self.prefix.fetch_cache("probe", list(tokens)) + return table, remaining + + +PROMPT = list(range(3, 20)) # 17 tokens -> 16 prefill tokens -> four blocks + + +@pytest.fixture(params=[False, True], ids=["inline-gdn", "split-gdn"]) +def split(request): + return request.param + + +def test_setting_off_stores_nothing_during_prefill(tmp_path, mock_tokenizer, split): + rig = _Rig(tmp_path, mock_tokenizer, split=split, commit_blocks=0) + try: + _, state = rig.start("r1", PROMPT) + rig.step(state, 3) + assert rig.table_tokens("r1") == 0 + table, remaining = rig.probe(PROMPT) + assert table is None + assert remaining == PROMPT + finally: + rig.close() + + +def test_commit_every_n_blocks_stores_completed_blocks(tmp_path, mock_tokenizer, split): + rig = _Rig(tmp_path, mock_tokenizer, split=split, commit_blocks=2) + try: + _, state = rig.start("r1", PROMPT) + rig.step(state, 1) + assert rig.table_tokens("r1") == 0 # one block done, below the threshold + rig.step(state, 1) + assert rig.table_tokens("r1") == 2 * BLOCK + rig.step(state, 1) + assert rig.table_tokens("r1") == 2 * BLOCK # third block waits for N=2 + rig.step(state, 1) + assert rig.table_tokens("r1") == 4 * BLOCK + finally: + rig.close() + + +def test_abort_mid_prefill_keeps_committed_blocks_for_a_reissue( + tmp_path, mock_tokenizer, split +): + rig = _Rig(tmp_path, mock_tokenizer, split=split, commit_blocks=2) + try: + _, state = rig.start("r1", PROMPT) + rig.step(state, 3) # blocks 1-2 committed, block 3 only in flight + assert rig.scheduler._do_abort_request("r1") + + table, remaining = rig.probe(PROMPT) + assert table is not None and table.num_tokens == 2 * BLOCK + assert remaining == PROMPT[2 * BLOCK :] + + restored = rig.prefix.reconstruct_cache(table) + assert restored is not None + model = rig.model + with mx.stream(rig.scheduler._stream): + warm = model(mx.array([remaining]), cache=restored) + cold = model(mx.array([PROMPT]), cache=model.make_cache()) + mx.eval(warm, cold) + assert mx.allclose(warm[:, -1], cold[:, -1], atol=1e-4) + finally: + rig.close() + + +def test_commit_is_skipped_under_memory_pressure( + tmp_path, mock_tokenizer, monkeypatch, split +): + rig = _Rig(tmp_path, mock_tokenizer, split=split, commit_blocks=1) + try: + scheduler = rig.scheduler + pressured = {"on": True} + monkeypatch.setattr( + scheduler, "_prefill_commit_blocked_by_pressure", lambda: pressured["on"] + ) + _, state = rig.start("r1", PROMPT) + rig.step(state, 2) + assert rig.table_tokens("r1") == 0 + + pressured["on"] = False + rig.step(state, 1) + # Everything completed so far is committed once pressure clears. + assert rig.table_tokens("r1") == 3 * BLOCK + finally: + rig.close() + + +@pytest.mark.parametrize( + "usage,limit,expected", [(500, 1000, False), (1000, 1000, True), (900, 0, False)] +) +def test_pressure_gate_follows_the_soft_limit( + tmp_path, mock_tokenizer, monkeypatch, usage, limit, expected +): + rig = _Rig(tmp_path, mock_tokenizer, split=False, commit_blocks=1) + try: + scheduler = rig.scheduler + scheduler._memory_limit_bytes = limit + monkeypatch.setattr(scheduler, "_current_usage_bytes", lambda **kw: usage) + assert scheduler._prefill_commit_blocked_by_pressure() is expected + finally: + rig.close() + + +def _packed(layer): + """Flat list of the arrays that make up a restored KV layer.""" + out = [] + + def walk(x): + if isinstance(x, mx.array): + out.append(x) + elif hasattr(x, "_fields"): + for name in x._fields: + walk(getattr(x, name)) + elif isinstance(x, (list, tuple)): + for item in x: + walk(item) + + walk(layer.state) + return out + + +def test_turboquant_blocks_committed_per_window_match_whole_prefix_conversion( + tmp_path, mock_tokenizer, split +): + from mlx_vlm.turboquant import TurboQuantKVCache + + import omlx.turboquant_kv # noqa: F401 (installs TurboQuantKVCache.from_cache) + + # One block per commit: the 8 stored tokens come from two separate windows. + rig = _Rig(tmp_path, mock_tokenizer, split=split, commit_blocks=1, tq_bits=4) + try: + _, state = rig.start("r1", PROMPT) + rig.step(state, 2) + assert rig.table_tokens("r1") == 2 * BLOCK + + table, _ = rig.probe(PROMPT) + restored = rig.prefix.reconstruct_cache(table) + assert restored is not None + assert type(restored[1]).__name__ == "TurboQuantKVCache" + + live = state.cache[1] # still fp16: conversion happens after prefill + assert type(live).__name__ == "KVCache" + whole = TurboQuantKVCache.from_cache(_window(live, 0, 2 * BLOCK), bits=4.0) + for got, want in zip(_packed(restored[1]), _packed(whole), strict=True): + assert mx.array_equal(got, want).item() + finally: + rig.close() + + +def _window(layer, start, end): + piece = type(layer)() + piece.keys = layer.keys[..., start:end, :] + piece.values = layer.values[..., start:end, :] + piece.offset = end - start + return piece + + +def test_window_longer_than_the_restored_prefix_is_stored_by_position( + tmp_path, mock_tokenizer, split +): + rig = _Rig(tmp_path, mock_tokenizer, split=split, commit_blocks=1) + try: + # Seed the cache with the first block, as an earlier request would. + _, state = rig.start("seed", PROMPT) + rig.step(state, 1) + assert rig.table_tokens("seed") == BLOCK + assert rig.scheduler._do_abort_request("seed") + + # The re-issue restores one block; its commit window (3 blocks) is + # then longer than the restored prefix (1 block). + rig.scheduler.config.prefill_progress_commit_blocks = 3 + request = Request( + request_id="again", + prompt=list(PROMPT), + sampling_params=SamplingParams(max_tokens=1), + ) + rig.scheduler.add_request(request) + rig.scheduler.waiting.clear() + rig.scheduler._prepare_prefix_cache_for_request(request) + assert request.cached_tokens == BLOCK + state = rig.scheduler._begin_prefill( + request, request.remaining_tokens[: len(PROMPT)], request.prompt_cache + ) + rig.step(state, 3) + assert rig.table_tokens("again") == 4 * BLOCK + assert rig.scheduler._do_abort_request("again") + + table, remaining = rig.probe(PROMPT) + assert table.num_tokens == 4 * BLOCK + restored = rig.prefix.reconstruct_cache(table) + model = rig.model + with mx.stream(rig.scheduler._stream): + warm = model(mx.array([remaining]), cache=restored) + cold = model(mx.array([PROMPT]), cache=model.make_cache()) + mx.eval(warm, cold) + assert mx.allclose(warm[:, -1], cold[:, -1], atol=1e-4) + finally: + rig.close() + + +def test_committed_boundary_markers_are_retired_once_stored( + tmp_path, mock_tokenizer, split +): + rig = _Rig(tmp_path, mock_tokenizer, split=split, commit_blocks=2) + try: + scheduler = rig.scheduler + _, state = rig.start("r1", PROMPT) + rig.step(state, 3) + scheduler._reap_prefill_commit("r1") + # Boundaries 4 and 8 were committed (a split-GDN commit moves their + # staged files); only the in-flight boundary 12 may remain. + assert sorted(scheduler._boundary_cache_snapshots["r1"]) == [3 * BLOCK] + finally: + rig.close() + + +def _finish(rig, request, state): + """Run prefill to the end, insert, decode one token and finalize.""" + from mlx_lm.generate import BatchGenerator + + scheduler = rig.scheduler + while not rig.step(state, 1): + pass + scheduler._emit_final_boundary_if_needed(state) + scheduler.batch_generator = BatchGenerator( + rig.model, + max_tokens=1, + sampler=lambda logits: mx.zeros(logits.shape[:-1], dtype=mx.int32), + stream=scheduler._stream, + ) + sampler, per_row = scheduler._build_sampler_and_processors(request.sampling_params) + state.sampler = sampler + state.sm = scheduler._build_state_machine(request) + state.per_row_lps = per_row + scheduler._insert_prefilled_request(request, state, []) + for _ in range(6): + _, responses = scheduler.batch_generator.next() + if responses: + break + _, finished = scheduler._process_batch_responses(responses) + scheduler._cleanup_finished(finished) + for future in list(scheduler._inflight_store_futures.values()): + future.result(timeout=20) + scheduler._drain_pending_async_removes() + rig.drain() + + +@pytest.mark.parametrize("commit_blocks", [0, 1, 2, 3]) +def test_completion_after_commits_stores_the_same_prefix_once( + tmp_path, mock_tokenizer, split, commit_blocks +): + rig = _Rig(tmp_path, mock_tokenizer, split=split, commit_blocks=commit_blocks) + try: + request, state = rig.start("r1", PROMPT) + _finish(rig, request, state) + + table, remaining = rig.probe(PROMPT) + assert table is not None and table.num_tokens == 4 * BLOCK + assert remaining == PROMPT[4 * BLOCK :] + assert len(table.block_ids) == len(set(table.block_ids)) == 4 + restored = rig.prefix.reconstruct_cache(table) + assert restored is not None + model = rig.model + with mx.stream(rig.scheduler._stream): + warm = model(mx.array([remaining]), cache=restored) + cold = model(mx.array([PROMPT]), cache=model.make_cache()) + mx.eval(warm, cold) + assert mx.allclose(warm[:, -1], cold[:, -1], atol=1e-4) + # No commit or snapshot bookkeeping outlives the request. + assert "r1" not in rig.scheduler._prefill_commits + assert "r1" not in rig.scheduler._boundary_cache_snapshots + finally: + rig.close() + + +def test_retry_after_prefill_oom_prefills_cold_even_with_committed_blocks( + tmp_path, mock_tokenizer +): + rig = _Rig(tmp_path, mock_tokenizer, split=False, commit_blocks=1) + try: + _, state = rig.start("r1", PROMPT) + rig.step(state, 2) + assert rig.scheduler._do_abort_request("r1") + + def lookup(request_id, retries): + request = Request( + request_id=request_id, + prompt=list(PROMPT), + sampling_params=SamplingParams(max_tokens=1), + ) + request.prefill_oom_retries = retries + rig.scheduler.add_request(request) + rig.scheduler._prepare_prefix_cache_for_request(request) + return request + + # A client re-issue resumes from the committed boundary... + assert lookup("reissue", 0).cached_tokens == 2 * BLOCK + # ...but the scheduler's own retry after a prefill memory failure + # stays cold (see _requeue_or_fail_prefill). + retry = lookup("retry", 1) + assert retry.cached_tokens == 0 + assert retry.remaining_tokens == PROMPT + finally: + rig.close() + + +def test_external_prefill_loop_commits_progress_too(tmp_path, mock_tokenizer, split): + rig = _Rig(tmp_path, mock_tokenizer, split=split, commit_blocks=2) + try: + scheduler = rig.scheduler + scheduler.config.chunked_prefill = False + request = Request( + request_id="ext", + prompt=list(PROMPT), + sampling_params=SamplingParams(max_tokens=1), + ) + scheduler.add_request(request) + scheduler.waiting.clear() + request.remaining_tokens = list(PROMPT) + scheduler.requests[request.request_id] = request + scheduler._do_external_prefill(request, list(PROMPT), None) + rig.drain() + assert rig.table_tokens("ext") == 4 * BLOCK + assert scheduler._do_abort_request("ext") + table, remaining = rig.probe(PROMPT) + assert table.num_tokens == 4 * BLOCK + assert remaining == PROMPT[4 * BLOCK :] + finally: + rig.close() + + +def test_dense_attention_model_commits_without_snapshots(tmp_path, mock_tokenizer): + from mlx_lm.models.llama import Model, ModelArgs + + mx.random.seed(5) + model = Model( + ModelArgs( + model_type="llama", + hidden_size=32, + num_hidden_layers=2, + intermediate_size=64, + num_attention_heads=2, + num_key_value_heads=1, + rms_norm_eps=1e-5, + vocab_size=32, + ) + ) + rig = _Rig(tmp_path, mock_tokenizer, split=False, commit_blocks=2) + try: + # Swap the hybrid model for a dense one under the same stores. + rig.model = rig.scheduler.model = model + rig.prefix.model = model + rig.ssd._expected_layer_cache_types = ["KVCache", "KVCache"] + _, state = rig.start("r1", PROMPT) + assert not state.boundary_enabled + rig.step(state, 3) + assert rig.table_tokens("r1") == 2 * BLOCK + assert rig.scheduler._do_abort_request("r1") + + table, remaining = rig.probe(PROMPT) + assert table.num_tokens == 2 * BLOCK + restored = rig.prefix.reconstruct_cache(table) + with mx.stream(rig.scheduler._stream): + warm = model(mx.array([remaining]), cache=restored) + cold = model(mx.array([PROMPT]), cache=model.make_cache()) + mx.eval(warm, cold) + assert mx.allclose(warm[:, -1], cold[:, -1], atol=1e-4) + finally: + rig.close() + + +def test_window_of_a_restored_turboquant_prefix_slices_the_packed_state( + tmp_path, mock_tokenizer +): + from mlx_lm.models.cache import KVCache + from mlx_vlm.turboquant import TurboQuantKVCache, _slice_state_range + + import omlx.turboquant_kv # noqa: F401 + + rig = _Rig(tmp_path, mock_tokenizer, split=False, commit_blocks=1) + try: + mx.random.seed(2) + k = mx.random.normal((1, 1, 12, 16)).astype(mx.float16) + fp16 = KVCache() + fp16.update_and_fetch(k, k) + packed = TurboQuantKVCache.from_cache(fp16, bits=4.0) + tail = KVCache() # the skipped last KV layer stays fp16 + tail.update_and_fetch(k, k) + + window = rig.scheduler._prefill_commit_window([packed, tail], 4, 12) + + assert window is not None + assert type(window[0]).__name__ == "TurboQuantKVCache" + assert window[0].offset == 8 + want = _slice_state_range(packed.keys, 4, 12) + assert mx.array_equal(window[0].keys.norms[:, :, :8], want.norms[:, :, :8]) + assert type(window[1]).__name__ == "KVCache" + assert window[1].offset == 8 + finally: + rig.close() + + +def test_window_refuses_composite_and_unknown_sliceable_layers( + tmp_path, mock_tokenizer +): + from mlx_lm.models.cache import CacheList, KVCache + + rig = _Rig(tmp_path, mock_tokenizer, split=False, commit_blocks=1) + try: + k = mx.zeros((1, 1, 8, 16), dtype=mx.float16) + kv = KVCache() + kv.update_and_fetch(k, k) + composite = CacheList(KVCache(), KVCache()) + assert rig.scheduler._prefill_commit_window([composite], 0, 8) is None + # A cache that has not reached the window end yet cannot be sliced. + assert rig.scheduler._prefill_commit_window([kv], 0, 12) is None + finally: + rig.close() From b30e72b6d0456d1602d0ff7c94d2fb3a4058c00f Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Thu, 1 Oct 2026 13:47:55 -0600 Subject: [PATCH 02/46] feat(settings): expose prefill_progress_commit_blocks 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. --- omlx/settings.py | 24 ++++++++++++++++++++++++ tests/test_settings.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/omlx/settings.py b/omlx/settings.py index c4590e04a5..7effced767 100644 --- a/omlx/settings.py +++ b/omlx/settings.py @@ -351,6 +351,10 @@ class SchedulerSettings: # any engine decodes, and each chunk accrues a decode time debt repaid # before the next chunk runs. Off restores the pre-fairness behavior. decode_fairness: bool = True + # Commit completed prefill blocks to the prefix cache every N blocks while a + # prompt is still prefilling, so an aborted or re-issued request resumes from + # the last committed block instead of token zero. 0 disables it. + prefill_progress_commit_blocks: int = 0 def to_dict(self) -> dict[str, Any]: """Convert to dictionary.""" @@ -371,12 +375,16 @@ def from_dict(cls, data: dict[str, Any]) -> SchedulerSettings: prefill_priority = data.get("prefill_priority", "context") if prefill_priority not in ("context", "speed"): prefill_priority = "context" + commit_blocks = data.get("prefill_progress_commit_blocks", 0) + if not isinstance(commit_blocks, int) or commit_blocks < 0: + commit_blocks = 0 return cls( max_concurrent_requests=value, embedding_batch_size=embedding_batch_size, chunked_prefill=bool(data.get("chunked_prefill", False)), prefill_priority=prefill_priority, decode_fairness=bool(data.get("decode_fairness", True)), + prefill_progress_commit_blocks=commit_blocks, ) @@ -1259,6 +1267,14 @@ def _apply_env_overrides(self) -> None: logger.warning( f"Invalid OMLX_EMBEDDING_BATCH_SIZE value: {embedding_batch_size}" ) + if commit_blocks := os.getenv("OMLX_PREFILL_PROGRESS_COMMIT_BLOCKS"): + try: + self.scheduler.prefill_progress_commit_blocks = int(commit_blocks) + except ValueError: + logger.warning( + f"Invalid OMLX_PREFILL_PROGRESS_COMMIT_BLOCKS value: " + f"{commit_blocks}" + ) # Cache settings if cache_enabled := os.getenv("OMLX_CACHE_ENABLED"): @@ -1770,6 +1786,11 @@ def validate(self) -> list[str]: f"Invalid embedding_batch_size: " f"{self.scheduler.embedding_batch_size} (must be > 0)" ) + if self.scheduler.prefill_progress_commit_blocks < 0: + errors.append( + f"Invalid prefill_progress_commit_blocks: " + f"{self.scheduler.prefill_progress_commit_blocks} (must be >= 0)" + ) # Cache validation if self.cache.gdn_ssd_split_enabled is True and self.cache.hot_cache_only: @@ -1945,6 +1966,9 @@ def to_scheduler_config(self) -> SchedulerConfig: chunked_prefill=self.scheduler.chunked_prefill, prefill_speed_priority=(self.scheduler.prefill_priority == "speed"), decode_fairness=self.scheduler.decode_fairness, + prefill_progress_commit_blocks=( + self.scheduler.prefill_progress_commit_blocks + ), initial_cache_blocks=self.cache.initial_cache_blocks, paged_ssd_cache_dir=str(ssd_dir) if ssd_dir else None, hot_cache_only=self.cache.hot_cache_only, diff --git a/tests/test_settings.py b/tests/test_settings.py index 416b71e9c6..1f3f6a5a8b 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -394,8 +394,40 @@ def test_to_dict(self): "chunked_prefill": False, "prefill_priority": "context", "decode_fairness": True, + "prefill_progress_commit_blocks": 0, } + def test_prefill_progress_commit_blocks_from_dict(self): + """Off by default; a positive count round-trips; junk falls back to off.""" + assert SchedulerSettings.from_dict({}).prefill_progress_commit_blocks == 0 + settings = SchedulerSettings.from_dict({"prefill_progress_commit_blocks": 4}) + assert settings.prefill_progress_commit_blocks == 4 + for bad in ("many", None, -3): + assert ( + SchedulerSettings.from_dict( + {"prefill_progress_commit_blocks": bad} + ).prefill_progress_commit_blocks + == 0 + ) + + def test_prefill_progress_commit_blocks_reaches_scheduler_config(self, tmp_path): + settings = GlobalSettings(base_path=tmp_path) + assert settings.to_scheduler_config().prefill_progress_commit_blocks == 0 + settings.scheduler.prefill_progress_commit_blocks = 3 + assert settings.to_scheduler_config().prefill_progress_commit_blocks == 3 + + def test_prefill_progress_commit_blocks_env_override(self, tmp_path): + with patch.dict( + os.environ, {"OMLX_PREFILL_PROGRESS_COMMIT_BLOCKS": "2"}, clear=False + ): + settings = GlobalSettings.load(base_path=tmp_path) + assert settings.scheduler.prefill_progress_commit_blocks == 2 + + def test_prefill_progress_commit_blocks_must_not_be_negative(self, tmp_path): + settings = GlobalSettings(base_path=tmp_path) + settings.scheduler.prefill_progress_commit_blocks = -1 + assert any("prefill_progress_commit_blocks" in e for e in settings.validate()) + def test_decode_fairness_from_dict(self): """Defaults on; explicit false round-trips.""" assert SchedulerSettings.from_dict({}).decode_fairness is True From bf1611b5291b030250ef3b5d37128a3c4882b6e0 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Thu, 1 Oct 2026 14:55:13 -0600 Subject: [PATCH 03/46] fix(settings): reject bool for prefill_progress_commit_blocks --- omlx/settings.py | 7 ++++++- tests/test_settings.py | 2 +- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/omlx/settings.py b/omlx/settings.py index 7effced767..d363d0f111 100644 --- a/omlx/settings.py +++ b/omlx/settings.py @@ -376,7 +376,12 @@ def from_dict(cls, data: dict[str, Any]) -> SchedulerSettings: if prefill_priority not in ("context", "speed"): prefill_priority = "context" commit_blocks = data.get("prefill_progress_commit_blocks", 0) - if not isinstance(commit_blocks, int) or commit_blocks < 0: + # bool is an int subclass: True must not silently become 1 block. + if ( + not isinstance(commit_blocks, int) + or isinstance(commit_blocks, bool) + or commit_blocks < 0 + ): commit_blocks = 0 return cls( max_concurrent_requests=value, diff --git a/tests/test_settings.py b/tests/test_settings.py index 1f3f6a5a8b..b4218c8366 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -402,7 +402,7 @@ def test_prefill_progress_commit_blocks_from_dict(self): assert SchedulerSettings.from_dict({}).prefill_progress_commit_blocks == 0 settings = SchedulerSettings.from_dict({"prefill_progress_commit_blocks": 4}) assert settings.prefill_progress_commit_blocks == 4 - for bad in ("many", None, -3): + for bad in ("many", None, -3, True, False): assert ( SchedulerSettings.from_dict( {"prefill_progress_commit_blocks": bad} From 797f7e4f00f9f59342a70c07ec89b94dd9072563 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Thu, 1 Oct 2026 14:55:13 -0600 Subject: [PATCH 04/46] fix(scheduler): defer prefill commit teardown instead of blocking the 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. --- omlx/scheduler.py | 376 ++++++++++++----- .../test_scheduler_prefill_progress_commit.py | 377 +++++++++++++++++- 2 files changed, 652 insertions(+), 101 deletions(-) diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 6502d54dd9..83c100fa1b 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -1335,6 +1335,14 @@ def _is_turboquant_kv_family_cache(cache_obj: Any) -> bool: ) or _is_turboquant_kv_cache(cache_obj) +# Bounded wait for in-flight prefill commits at shutdown only; the hot path +# never waits (see Scheduler._after_commit). +PREFILL_COMMIT_SHUTDOWN_WAIT_S = 30.0 +# A teardown deferred behind a commit that has not finished after this long +# is logged once; it stays pending and is dropped at shutdown. +PREFILL_COMMIT_STUCK_LOG_S = 60.0 + + def _prefill_commit_blocks(config: Any) -> int: """``prefill_progress_commit_blocks`` of a config, 0 when unset or invalid.""" value = getattr(config, "prefill_progress_commit_blocks", 0) @@ -2223,6 +2231,17 @@ def __init__( # request_id -> (future, committed token count) of the in-flight # incremental prefill commit (see _commit_prefill_progress). self._prefill_commits: dict[str, tuple[concurrent.futures.Future, int]] = {} + # Own single-thread executor so commits never queue behind the + # post-finish final stores (28GB+ memcpys) on _store_cache_executor. + self._prefill_commit_executor: concurrent.futures.ThreadPoolExecutor | None = ( + None + ) + # request_id -> destructive teardown steps (release block table, + # retire snapshots, ...) postponed until that request's in-flight + # commit has finished. Touched on the scheduler thread only. + self._deferred_teardowns: dict[str, list[Callable[[], None]]] = {} + self._deferred_teardown_since: dict[str, float] = {} + self._stuck_teardown_logged: set[str] = set() self.requests: dict[str, Request] = {} # All requests by ID self.finished_req_ids: set[str] = set() # Recently finished self._generation_overflow_recovery_ids: set[str] = set() @@ -2533,6 +2552,7 @@ def __init__( max_workers=1, thread_name_prefix="omlx-store-cache", ) + self._ensure_prefill_commit_executor() # Gate caps the post-completion store-cache pipeline so a burst # of finishes cannot pile up unbounded KV caches in memory while # the single writer drains. Cap starts at max_concurrent_requests @@ -2774,9 +2794,14 @@ def _async_store_cache_worker( extra_key_ranges: list[tuple[int, tuple[Any, ...]]] | None, hot_cache_write_back: bool = True, incremental_commit: bool = False, + after_commit: concurrent.futures.Future | None = None, ) -> None: """Run store_cache + paged_cache cleanup off the inference thread. + ``after_commit`` is the request's in-flight incremental commit: the + store waits for it here, on this worker, so the two never race on the + block table and the inference thread never waits. + ``incremental_commit`` marks a mid-prefill commit: ``cache_to_store`` holds only the tokens after the request's existing block table, and the table stays alive so the next commit (or the final store) extends @@ -2814,6 +2839,8 @@ def _async_store_cache_worker( threading.RLock so concurrent access from main and worker is safe. """ self._store_cache_thread_id = threading.get_ident() + if after_commit is not None: + concurrent.futures.wait([after_commit]) window_kwargs = {"cache_covers_suffix_only": True} if incremental_commit else {} try: # Hold _mx_buffer_access_lock across the worker's mx-buffer @@ -7712,13 +7739,34 @@ def _prefill_commit_window( self._apply_turboquant_kv_convert(window) return window + def _ensure_prefill_commit_executor( + self, + ) -> concurrent.futures.ThreadPoolExecutor: + executor = self._prefill_commit_executor + if executor is None: + executor = concurrent.futures.ThreadPoolExecutor( + max_workers=1, thread_name_prefix="omlx-prefill-commit" + ) + self._prefill_commit_executor = executor + return executor + + def _retire_committed_markers(self, request_id: str, committed_tokens: int) -> None: + """Drop snapshot markers a commit covering ``committed_tokens`` consumed. + + The commit worker moves (split-GDN) or reads (inline) the staged + snapshot of every committed boundary, so their markers must not reach + the final store, which would try to load a moved file. + """ + snapshots = self._boundary_cache_snapshots.get(request_id) + if snapshots: + for token_count in [tc for tc in snapshots if tc <= committed_tokens]: + del snapshots[token_count] + def _reap_prefill_commit(self, request_id: str) -> None: """Retire a finished commit: drop snapshot markers it consumed. - Runs on the inference thread. The commit worker moves (split-GDN) or - reads (inline) the staged snapshot of every committed boundary, so - their markers must not reach the final store, which would try to load - a moved file. A failed commit leaves them in place for the next try. + Runs on the inference thread and never waits. A failed commit leaves + its markers in place for the next try. """ pending = (getattr(self, "_prefill_commits", None) or {}).get(request_id) if pending is None: @@ -7729,31 +7777,91 @@ def _reap_prefill_commit(self, request_id: str) -> None: del self._prefill_commits[request_id] try: ok = bool(future.result()) - except Exception: + except Exception as e: + logger.warning("Prefill commit for %s failed: %s", request_id, e) ok = False - if not ok: - return - snapshots = self._boundary_cache_snapshots.get(request_id) - if snapshots: - for token_count in [tc for tc in snapshots if tc <= committed_tokens]: - del snapshots[token_count] + if ok: + self._retire_committed_markers(request_id, committed_tokens) + + def _inflight_commit_future( + self, request_id: str + ) -> concurrent.futures.Future | None: + """The request's commit future while it is still running, else None.""" + self._reap_prefill_commit(request_id) + pending = (getattr(self, "_prefill_commits", None) or {}).get(request_id) + return pending[0] if pending is not None else None - def _settle_prefill_commits(self, request_id: str) -> None: - """Wait for an in-flight commit before its request is torn down. + def _after_commit(self, request_id: str, teardown: Callable[[], None]) -> bool: + """Run a destructive teardown step once the request's commit is done. Teardown releases the block table and removes the snapshot directory, - which the commit worker is still reading. Commits are a few blocks, so - the wait is short; the blocks it stores stay in the prefix cache. - """ - pending = (getattr(self, "_prefill_commits", None) or {}).get(request_id) - if pending is None: - return + which the commit worker may still be reading or moving. Never waits: + with no commit in flight the step runs now; otherwise it is queued and + runs from ``_process_finished_commits`` on the scheduler thread, after + the commit finished (successfully or not). Returns True when deferred. + """ + if self._inflight_commit_future(request_id) is None: + self._run_deferred_teardowns(request_id) # keep submission order + self._run_teardown_step(request_id, teardown) + return False + self._deferred_teardowns.setdefault(request_id, []).append(teardown) + self._deferred_teardown_since.setdefault(request_id, time.monotonic()) + logger.debug( + "Deferring teardown of %s until its prefill commit ends", request_id + ) + return True + + def _teardown_pending(self, request_id: str) -> bool: + """True while a deferred teardown of this request id has not run.""" + return request_id in self._deferred_teardowns + + def _run_teardown_step(self, request_id: str, teardown: Callable[[], None]) -> None: try: - pending[0].result(timeout=60) + teardown() except Exception as e: - logger.warning("Prefill commit for %s did not settle: %s", request_id, e) - self._reap_prefill_commit(request_id) - self._prefill_commits.pop(request_id, None) + logger.warning("Teardown step for %s failed: %s", request_id, e) + + def _run_deferred_teardowns(self, request_id: str) -> None: + steps = self._deferred_teardowns.pop(request_id, None) + self._deferred_teardown_since.pop(request_id, None) + self._stuck_teardown_logged.discard(request_id) + for teardown in steps or (): + self._run_teardown_step(request_id, teardown) + + def _process_finished_commits(self) -> None: + """Retire finished commits and run the teardowns waiting on them. + + Called at the start of every step on the scheduler thread; only reads + future state, so commit workers never touch scheduler state. + """ + for request_id in list(self._prefill_commits): + self._reap_prefill_commit(request_id) + if request_id not in self._prefill_commits: + self._run_deferred_teardowns(request_id) + now = time.monotonic() + for request_id, since in self._deferred_teardown_since.items(): + if ( + now - since >= PREFILL_COMMIT_STUCK_LOG_S + and request_id not in self._stuck_teardown_logged + ): + self._stuck_teardown_logged.add(request_id) + logger.warning( + "Teardown of %s still waits for its prefill commit after %.0fs", + request_id, + now - since, + ) + + def _wait_for_prefill_commits(self, timeout: float) -> int: + """Block until every commit ends or ``timeout``; returns the stragglers. + + Reset and shutdown only: the hot path never waits on a commit. + """ + futures = [future for future, _ in self._prefill_commits.values()] + not_done: set = set() + if futures: + _done, not_done = concurrent.futures.wait(futures, timeout=timeout) + self._process_finished_commits() + return len(not_done) def _commit_prefill_progress( self, request: "Request", prompt_cache: list[Any], total_tokens: int @@ -7854,7 +7962,7 @@ def _commit_prefill_progress_unchecked( # streams are thread-local; see _async_store_cache_worker). mx.eval(*arrays) - future = self._store_cache_executor.submit( + future = self._ensure_prefill_commit_executor().submit( self._commit_prefill_worker, rid, tokens, @@ -11734,9 +11842,6 @@ def _do_abort_request(self, request_id: str) -> bool: return False self._clear_request_admission_bookkeeping(request_id) - # Committed prefill blocks stay in the prefix cache; let an in-flight - # commit finish before the table and snapshots are released below. - self._settle_prefill_commits(request_id) # Remove from waiting queue if request.status == RequestStatus.WAITING: @@ -11783,24 +11888,32 @@ def _do_abort_request(self, request_id: str) -> bool: # forever (#766). self._cleanup_specprefill(request_id) - # Release blocks for eviction (same as _cleanup_finished) - if self.paged_cache_manager is not None: - block_table = self.paged_cache_manager.get_block_table(request_id) - if block_table is None and hasattr(request, "block_table"): - block_table = request.block_table - if block_table: - released = self.paged_cache_manager.release_for_eviction( - block_table.block_ids - ) - if released > 0: - logger.debug( - f"Released {released} blocks for eviction on abort " - f"(request {request_id})" + # Release blocks for eviction (same as _cleanup_finished) and drop the + # request's block-aware entry, boundary snapshots (RAM and SSD). Blocks + # an incremental prefill commit stored stay in the prefix cache; if a + # commit is still running, these steps wait for it (without blocking + # this thread) because the worker is using the table and snapshots. + def release_cache_state() -> None: + if self.paged_cache_manager is not None: + block_table = self.paged_cache_manager.get_block_table(request_id) + if block_table is None and hasattr(request, "block_table"): + block_table = request.block_table + if block_table: + released = self.paged_cache_manager.release_for_eviction( + block_table.block_ids ) + if released > 0: + logger.debug( + f"Released {released} blocks for eviction on abort " + f"(request {request_id})" + ) + if self.block_aware_cache is not None: + self.block_aware_cache.clear_request_entry(request_id) + self._boundary_cache_snapshots.pop(request_id, None) + if self._boundary_snapshot_store is not None: + self._boundary_snapshot_store.cleanup_request(request_id) - # Clear request entry from block_aware_cache - if self.block_aware_cache is not None: - self.block_aware_cache.clear_request_entry(request_id) + self._after_commit(request_id, release_cache_state) # Clean up streaming detokenizer to prevent state contamination self._cleanup_detokenizer(request_id) @@ -11814,11 +11927,6 @@ def _do_abort_request(self, request_id: str) -> bool: if hasattr(self.model, "clear_pending_embeddings"): self.model.clear_pending_embeddings() - # Drop any boundary snapshot for this request. - self._boundary_cache_snapshots.pop(request_id, None) - if self._boundary_snapshot_store is not None: - self._boundary_snapshot_store.cleanup_request(request_id) - # Remove from prefill progress tracker. get_prefill_tracker().remove(request_id) @@ -11861,6 +11969,7 @@ def has_requests(self) -> bool: or self.prefilling or self.running or self._pending_async_removes + or self._deferred_teardowns or self._deferred_clear_at is not None or self._pending_reclaim_request or self._pending_pressure_clear @@ -11915,6 +12024,11 @@ def _effective_max_num_seqs(self) -> int: return 1 return max(1, self.config.max_num_seqs) + def _drop_snapshots_now(self, request_id: str) -> None: + self._boundary_cache_snapshots.pop(request_id, None) + if self._boundary_snapshot_store is not None: + self._boundary_snapshot_store.cleanup_request(request_id) + def _drop_boundary_snapshots_for_request(self, request_id: str) -> None: """Release a failed request's boundary snapshots (RAM and SSD). @@ -11924,17 +12038,20 @@ def _drop_boundary_snapshots_for_request(self, request_id: str) -> None: must do the same or every failure strands a snapshot set until process exit (#3226). """ - self._settle_prefill_commits(request_id) - self._boundary_cache_snapshots.pop(request_id, None) - if self._boundary_snapshot_store is not None: - try: - self._boundary_snapshot_store.cleanup_request(request_id) - except Exception as e: - logger.debug( - "Boundary snapshot store cleanup failed for %s: %s", - request_id, - e, - ) + + def drop() -> None: + self._boundary_cache_snapshots.pop(request_id, None) + if self._boundary_snapshot_store is not None: + try: + self._boundary_snapshot_store.cleanup_request(request_id) + except Exception as e: + logger.debug( + "Boundary snapshot store cleanup failed for %s: %s", + request_id, + e, + ) + + self._after_commit(request_id, drop) def fail_all_requests(self) -> list[str]: """Remove all running and waiting requests after unrecoverable error. @@ -12653,6 +12770,11 @@ def _schedule_waiting( self._clear_store_cache_admission_blocker(request.request_id) if self._should_defer_for_cache_freshness(request): break + if self._teardown_pending(request.request_id): + # A previous run of this id is still being torn down behind + # its prefill commit; the head waits (no blocking) so the + # deferred cleanup cannot hit the new run's state. + break request = self.waiting.popleft() self._cache_freshness_waits.pop(request.request_id, None) @@ -13706,11 +13828,16 @@ def _release_paged_cache_for_request(self, request_id: str) -> None: very memory pressure that triggered the rejection) and orphan ``_request_tables`` entries. """ - self._settle_prefill_commits(request_id) - if self.block_aware_cache is not None: - self.block_aware_cache.release_cache(request_id) - elif self.paged_cache_manager is not None: - self.paged_cache_manager.delete_block_table(request_id) + + def release_table() -> None: + if self.block_aware_cache is not None: + self.block_aware_cache.release_cache(request_id) + elif self.paged_cache_manager is not None: + self.paged_cache_manager.delete_block_table(request_id) + + # An in-flight prefill commit is still using the table: wait for it + # without blocking this thread. + self._after_commit(request_id, release_table) # SpecPrefill primes an independent ``_draft_prefix_cache`` in # ``_try_specprefill_scoring`` whose block refs are tracked @@ -13729,6 +13856,19 @@ def _release_paged_cache_for_request(self, request_id: str) -> None: exc_info=True, ) + def _release_finished_table( + self, request_id: str, request: "Request | None" = None + ) -> None: + """Release a finished request's blocks for eviction; drop its entry.""" + block_table = None + if self.paged_cache_manager: + block_table = self.paged_cache_manager.get_block_table(request_id) + if block_table is None and request is not None: + block_table = getattr(request, "block_table", None) + if block_table and self.paged_cache_manager: + self.paged_cache_manager.release_for_eviction(block_table.block_ids) + self.block_aware_cache.clear_request_entry(request_id) + def _cleanup_finished(self, finished_ids: set[str]) -> None: """Clean up finished requests and store caches for reuse.""" # Synchronize pending engine stream operations before cache storage. @@ -13757,9 +13897,16 @@ def _cleanup_finished(self, finished_ids: set[str]) -> None: if finished_drafter is not None: finished_drafter.release_request(request_id) request = self.running.get(request_id) - # A mid-prefill commit still in flight must land (and retire its - # consumed snapshot markers) before the final store reads them. - self._settle_prefill_commits(request_id) + # A mid-prefill commit still in flight consumes its snapshot + # markers and extends the block table. Retire those markers from + # the final store's view now (assuming success: a failed commit + # only costs the cached tail), and chain the store after the + # commit on its worker so the two never race on the table. + commit_future = self._inflight_commit_future(request_id) + if commit_future is not None: + self._retire_committed_markers( + request_id, self._prefill_commits[request_id][1] + ) # Store cache for future reuse (G2-async): submit to background # executor so the post-finish 28GB+ memcpy doesn't block response @@ -13986,6 +14133,7 @@ def _cleanup_finished(self, finished_ids: set[str]) -> None: request.vlm_extra_key_token_start_for_cache, request.vlm_extra_key_ranges_for_cache, hot_cache_write_back, + after_commit=commit_future, ) except BaseException: if gate is not None: @@ -14076,34 +14224,24 @@ def _cleanup_finished(self, finished_ids: set[str]) -> None: block_size, available_boundaries, ) - block_table = None - if self.paged_cache_manager: - block_table = self.paged_cache_manager.get_block_table( - request_id - ) - if block_table and self.paged_cache_manager: - self.paged_cache_manager.release_for_eviction( - block_table.block_ids - ) - self.block_aware_cache.clear_request_entry(request_id) + self._after_commit( + request_id, + lambda rid=request_id: self._release_finished_table( + rid + ), + ) except Exception as e: logger.debug( f"Failed to submit async store for {request_id}: {e}" ) else: # No extracted_cache to store, but ensure block leak guard. - block_table = None - if self.paged_cache_manager: - block_table = self.paged_cache_manager.get_block_table( - request_id - ) - if block_table is None and hasattr(request, "block_table"): - block_table = request.block_table - if block_table and self.paged_cache_manager: - self.paged_cache_manager.release_for_eviction( - block_table.block_ids - ) - self.block_aware_cache.clear_request_entry(request_id) + self._after_commit( + request_id, + lambda rid=request_id, req=request: ( + self._release_finished_table(rid, req) + ), + ) # Remove from running if request_id in self.running: @@ -14157,7 +14295,12 @@ def _cleanup_finished(self, finished_ids: set[str]) -> None: # an async store_future is in flight, defer cleanup until the # worker finishes (handled in _drain_pending_async_removes). if self._boundary_snapshot_store is not None and store_future is None: - self._boundary_snapshot_store.cleanup_request(request_id) + self._after_commit( + request_id, + lambda rid=request_id: self._boundary_snapshot_store.cleanup_request( + rid + ), + ) # Track as finished self.finished_req_ids.add(request_id) @@ -14486,10 +14629,10 @@ def collect(request: Request | None) -> None: for request in retry_candidates: request.generation_overflow_retries += 1 request_id = request.request_id - self._settle_prefill_commits(request_id) - self._boundary_cache_snapshots.pop(request_id, None) - if self._boundary_snapshot_store is not None: - self._boundary_snapshot_store.cleanup_request(request_id) + self._after_commit( + request_id, + lambda rid=request_id: self._drop_snapshots_now(rid), + ) get_prefill_tracker().remove(request_id) if request.generation_overflow_retries > max_generation_overflow_retries: failed_ids.append(request_id) @@ -14654,6 +14797,10 @@ def step(self) -> SchedulerOutput: self._decode_activity_key, len(self.running) ) + # Retire finished prefill commits and run the teardowns that waited + # for them (never blocks: only reads future state). + self._process_finished_commits() + # Process pending aborts FIRST (thread-safe with hybrid executor) self._process_pending_aborts() @@ -14994,6 +15141,12 @@ def reset(self) -> None: # use the same bounded teardown barrier as shutdown() before aborting # requests or clearing caches. The drain performs the request-local # cleanup only after every future has completed. + if self._wait_for_prefill_commits(FATAL_TEARDOWN_TIMEOUT_S): + fatal_exit( + "Scheduler reset timed out after " + f"{FATAL_TEARDOWN_TIMEOUT_S:.0f}s waiting for prefill commit(s)" + ) + return inflight = list(self._inflight_store_futures.values()) if inflight: logger.info( @@ -15035,6 +15188,10 @@ def reset(self) -> None: self._pending_async_removes.clear() self._inflight_store_futures.clear() self._inflight_store_info.clear() + self._deferred_teardowns.clear() + self._deferred_teardown_since.clear() + self._stuck_teardown_logged.clear() + self._prefill_commits.clear() self._cache_freshness_waits.clear() self._prefix_cache_prepared.clear() self.batch_generator = None @@ -15115,6 +15272,36 @@ def deep_reset(self) -> None: logger.info("Deep reset completed - all caches cleared") + def _shutdown_prefill_commits(self) -> None: + """Finish or safely abandon prefill commits and their teardowns. + + The bounded wait is acceptable here only. A commit that outlives it + is abandoned: its pending teardowns are dropped (the snapshot + directories are removed by ``cleanup_all`` and the process is going + away), and its executor is not joined. + """ + executor = self._prefill_commit_executor + stragglers = self._wait_for_prefill_commits(PREFILL_COMMIT_SHUTDOWN_WAIT_S) + if stragglers: + logger.warning( + "Abandoning %d prefill commit(s) still running at shutdown " + "(%d pending teardown(s) dropped)", + stragglers, + len(self._deferred_teardowns), + ) + elif executor is not None: + try: + executor.submit(clear_thread_streams).result(timeout=10) + except Exception as e: + logger.warning("Prefill commit worker stream cleanup failed: %s", e) + self._deferred_teardowns.clear() + self._deferred_teardown_since.clear() + self._stuck_teardown_logged.clear() + self._prefill_commits.clear() + if executor is not None: + executor.shutdown(wait=False) + self._prefill_commit_executor = None + def _store_persistence_progress(self): manager = self.paged_ssd_cache_manager thread_id = getattr(self, "_store_cache_thread_id", None) @@ -15137,6 +15324,7 @@ def shutdown(self) -> None: # The store-cache gate is a non-blocking counter (#1496), so there is # no step-thread caller to wake here. Inflight futures are drained # below before the executor is asked to shut down. + self._shutdown_prefill_commits() # Wait for any inflight async store_cache futures + drain pending # batch_generator removes so the writer thread / underlying paged SSD # cache see all blocks before close(). diff --git a/tests/test_scheduler_prefill_progress_commit.py b/tests/test_scheduler_prefill_progress_commit.py index 6d2ba72f47..8706a50750 100644 --- a/tests/test_scheduler_prefill_progress_commit.py +++ b/tests/test_scheduler_prefill_progress_commit.py @@ -8,6 +8,8 @@ """ import concurrent.futures +import threading +import time import mlx.core as mx import pytest @@ -116,8 +118,13 @@ def step(self, state, chunks): return done def drain(self): - """Wait for every in-flight store or commit on the store executor.""" - self.scheduler._store_cache_executor.submit(lambda: None).result(timeout=20) + """Wait for every in-flight store or commit, then retire the commits.""" + s = self.scheduler + s._store_cache_executor.submit(lambda: None).result(timeout=20) + commit_executor = getattr(s, "_prefill_commit_executor", None) + if commit_executor is not None: + commit_executor.submit(lambda: None).result(timeout=20) + s._process_finished_commits() def close(self): self.scheduler.shutdown() @@ -345,13 +352,11 @@ def test_committed_boundary_markers_are_retired_once_stored( rig.close() -def _finish(rig, request, state): - """Run prefill to the end, insert, decode one token and finalize.""" +def _decode_to_finish(rig, request, state): + """Insert a fully prefilled request, decode one token, return finished ids.""" from mlx_lm.generate import BatchGenerator scheduler = rig.scheduler - while not rig.step(state, 1): - pass scheduler._emit_final_boundary_if_needed(state) scheduler.batch_generator = BatchGenerator( rig.model, @@ -369,7 +374,15 @@ def _finish(rig, request, state): if responses: break _, finished = scheduler._process_batch_responses(responses) - scheduler._cleanup_finished(finished) + return finished + + +def _finish(rig, request, state): + """Run prefill to the end, insert, decode one token and finalize.""" + scheduler = rig.scheduler + while not rig.step(state, 1): + pass + scheduler._cleanup_finished(_decode_to_finish(rig, request, state)) for future in list(scheduler._inflight_store_futures.values()): future.result(timeout=20) scheduler._drain_pending_async_removes() @@ -547,3 +560,353 @@ def test_window_refuses_composite_and_unknown_sliceable_layers( assert rig.scheduler._prefill_commit_window([kv], 0, 12) is None finally: rig.close() + + +# --- Teardown while a commit is in flight -------------------------------------- + + +class _CommitGate: + """Holds the commit worker on an Event so a test controls its lifetime.""" + + def __init__(self, scheduler, monkeypatch, fail=False): + self.release = threading.Event() + self.entered = threading.Event() + real = scheduler._commit_prefill_worker + + def gated(*args, **kwargs): + self.entered.set() + assert self.release.wait(30) + if fail: + raise RuntimeError("commit exploded") + return real(*args, **kwargs) + + monkeypatch.setattr(scheduler, "_commit_prefill_worker", gated) + + +@pytest.fixture +def gated(monkeypatch): + """Factory: rig with a controllable commit worker; released on teardown.""" + gates = [] + + def make(rig, fail=False): + gate = _CommitGate(rig.scheduler, monkeypatch, fail=fail) + gates.append(gate) + return gate + + yield make + for gate in gates: + gate.release.set() + + +def _returns_promptly(fn, *args, timeout=5.0): + """Run ``fn`` on a helper thread; fail if it blocks past ``timeout``.""" + box = {} + + def run(): + box["value"] = fn(*args) + + thread = threading.Thread(target=run, daemon=True) + thread.start() + thread.join(timeout) + assert not thread.is_alive(), f"{fn.__name__} blocked on the in-flight commit" + return box.get("value") + + +def _inflight_commit(rig, gate, split_chunks=2): + """Prefill until the first commit is submitted and held by the gate.""" + _, state = rig.start("r1", PROMPT) + for _ in range(split_chunks): + rig.scheduler._step_prefill_chunk(state) + assert gate.entered.wait(20) + future, _ = rig.scheduler._prefill_commits["r1"] + assert not future.done() + return state + + +def _await_teardown(rig, gate): + gate.release.set() + rig.drain() + assert not rig.scheduler._deferred_teardowns + + +def test_abort_with_a_commit_in_flight_defers_cleanup_until_it_completes( + tmp_path, mock_tokenizer, gated, split +): + rig = _Rig(tmp_path, mock_tokenizer, split=split, commit_blocks=2) + gate = gated(rig) + try: + scheduler = rig.scheduler + _inflight_commit(rig, gate) + cleanups = [] + real_cleanup = rig.boundary.cleanup_request + rig.boundary.cleanup_request = lambda rid: ( + cleanups.append(rid), + real_cleanup(rid), + ) + + assert _returns_promptly(scheduler._do_abort_request, "r1") + # The request is gone from the scheduler, but the snapshots and the + # block table the worker is using are untouched while it runs. + assert "r1" not in scheduler.requests + assert scheduler._boundary_cache_snapshots.get("r1") + assert cleanups == [] + assert scheduler.has_requests() + + _await_teardown(rig, gate) + assert cleanups == ["r1"] + assert "r1" not in scheduler._boundary_cache_snapshots + assert "r1" not in rig.prefix._request_tables + assert not scheduler._deferred_teardowns + + table, remaining = rig.probe(PROMPT) + assert table is not None and table.num_tokens == 2 * BLOCK + assert remaining == PROMPT[2 * BLOCK :] + restored = rig.prefix.reconstruct_cache(table) + assert restored is not None + model = rig.model + with mx.stream(scheduler._stream): + warm = model(mx.array([remaining]), cache=restored) + cold = model(mx.array([PROMPT]), cache=model.make_cache()) + mx.eval(warm, cold) + assert mx.allclose(warm[:, -1], cold[:, -1], atol=1e-4) + finally: + gate.release.set() + rig.close() + + +def test_prefill_failure_with_a_commit_in_flight_defers_cleanup( + tmp_path, mock_tokenizer, gated, split +): + rig = _Rig(tmp_path, mock_tokenizer, split=split, commit_blocks=2) + gate = gated(rig) + try: + scheduler = rig.scheduler + _inflight_commit(rig, gate) + + _returns_promptly(scheduler._drop_boundary_snapshots_for_request, "r1") + _returns_promptly(scheduler._release_paged_cache_for_request, "r1") + assert scheduler._boundary_cache_snapshots.get("r1") + assert scheduler.has_requests() + + _await_teardown(rig, gate) + assert "r1" not in scheduler._boundary_cache_snapshots + # The rejection path frees the table (release_cache), as before. + assert rig.paged.get_block_table("r1") is None + assert "r1" not in rig.prefix._request_tables + finally: + gate.release.set() + rig.close() + + +def test_overflow_retry_defers_snapshot_cleanup_and_holds_readmission( + tmp_path, mock_tokenizer, gated +): + rig = _Rig(tmp_path, mock_tokenizer, split=True, commit_blocks=2) + gate = gated(rig) + try: + scheduler = rig.scheduler + request, state = rig.start("r1", PROMPT) + for _ in range(2): + scheduler._step_prefill_chunk(state) + assert gate.entered.wait(20) + + _returns_promptly(scheduler._drop_boundary_snapshots_for_request, "r1") + scheduler.waiting.append(request) + scheduled, _ = scheduler._schedule_waiting() + # Same request id: the head of the queue waits for its own teardown. + assert scheduled == [] + assert list(scheduler.waiting) == [request] + + _await_teardown(rig, gate) + assert not scheduler._teardown_pending("r1") + finally: + gate.release.set() + rig.close() + + +def test_finish_with_a_commit_in_flight_chains_the_final_store_after_it( + tmp_path, mock_tokenizer, monkeypatch, gated, split +): + rig = _Rig(tmp_path, mock_tokenizer, split=split, commit_blocks=2) + gate = gated(rig) + try: + scheduler = rig.scheduler + request, state = rig.start("r1", PROMPT) + while not scheduler._step_prefill_chunk(state): + pass + assert gate.entered.wait(20) + events = [] + real_store = rig.prefix.store_cache + + def traced(*args, **kwargs): + kind = "commit" if kwargs.get("cache_covers_suffix_only") else "final" + events.append(f"{kind}-start") + try: + return real_store(*args, **kwargs) + finally: + events.append(f"{kind}-end") + + monkeypatch.setattr(rig.prefix, "store_cache", traced) + finished = _decode_to_finish(rig, request, state) + + # MLX streams are thread-local, so this runs on the test thread; the + # watchdog frees a regressed implementation that would block instead. + watchdog = threading.Timer(8.0, gate.release.set) + watchdog.start() + started = time.monotonic() + scheduler._cleanup_finished(finished) + elapsed = time.monotonic() - started + watchdog.cancel() + assert elapsed < 4.0, "_cleanup_finished blocked on the in-flight commit" + future = scheduler._inflight_store_futures["r1"] + time.sleep(0.3) + assert not future.done() # waiting for the commit, not racing it + assert events == [] # the final store has not touched the table yet + + gate.release.set() + future.result(timeout=20) + scheduler._drain_pending_async_removes() + rig.drain() + + # Strictly sequential: the commit ends before the final store starts. + assert events == ["commit-start", "commit-end", "final-start", "final-end"] + table, remaining = rig.probe(PROMPT) + assert table is not None and table.num_tokens == 4 * BLOCK + assert len(table.block_ids) == len(set(table.block_ids)) == 4 + assert rig.prefix.reconstruct_cache(table) is not None + assert not scheduler._deferred_teardowns + assert "r1" not in scheduler._prefill_commits + finally: + gate.release.set() + rig.close() + + +def test_commit_that_raises_still_runs_the_teardown_and_leaves_no_blocks( + tmp_path, mock_tokenizer, gated, split +): + rig = _Rig(tmp_path, mock_tokenizer, split=split, commit_blocks=2) + gate = gated(rig, fail=True) + try: + scheduler = rig.scheduler + _inflight_commit(rig, gate) + _returns_promptly(scheduler._do_abort_request, "r1") + + gate.release.set() + rig.drain() + assert not scheduler._deferred_teardowns + assert "r1" not in scheduler._prefill_commits + assert "r1" not in scheduler._boundary_cache_snapshots + assert rig.paged.get_block_table("r1") is None + table, remaining = rig.probe(PROMPT) + assert table is None + assert remaining == PROMPT + finally: + gate.release.set() + rig.close() + + +def test_step_retires_completed_commits_and_runs_their_teardown( + tmp_path, mock_tokenizer, gated +): + rig = _Rig(tmp_path, mock_tokenizer, split=False, commit_blocks=2) + gate = gated(rig) + try: + scheduler = rig.scheduler + _inflight_commit(rig, gate) + _returns_promptly(scheduler._do_abort_request, "r1") + gate.release.set() + scheduler._prefill_commits["r1"][0].result(timeout=20) + + scheduler.step() + assert not scheduler._deferred_teardowns + assert "r1" not in scheduler._boundary_cache_snapshots + finally: + gate.release.set() + rig.close() + + +def test_commits_do_not_queue_behind_a_final_store_of_another_request( + tmp_path, mock_tokenizer +): + rig = _Rig(tmp_path, mock_tokenizer, split=False, commit_blocks=2) + blocker = threading.Event() + try: + scheduler = rig.scheduler + # A long post-finish store occupies the store executor. + scheduler._store_cache_executor.submit(blocker.wait, 30) + _, state = rig.start("r1", PROMPT) + scheduler._step_prefill_chunk(state) + scheduler._step_prefill_chunk(state) + future, _ = scheduler._prefill_commits["r1"] + future.result(timeout=10) # would time out behind the blocked store + scheduler._process_finished_commits() + assert "r1" not in scheduler._prefill_commits + assert rig.table_tokens("r1") == 2 * BLOCK + finally: + blocker.set() + rig.close() + + +def test_same_prompt_reissue_during_a_pending_teardown_keeps_blocks_alive( + tmp_path, mock_tokenizer, gated +): + rig = _Rig(tmp_path, mock_tokenizer, split=False, commit_blocks=2) + gate = gated(rig) + try: + scheduler = rig.scheduler + _inflight_commit(rig, gate) + _returns_promptly(scheduler._do_abort_request, "r1") + gate.release.set() + scheduler._prefill_commits["r1"][0].result(timeout=20) + + # A re-issue matches the committed blocks before the teardown runs. + table, _ = rig.probe(PROMPT) + assert table is not None and table.num_tokens == 2 * BLOCK + scheduler._process_finished_commits() + + for block_id in table.block_ids: + assert rig.paged.allocated_blocks[block_id].ref_count == 1 + assert "r1" not in rig.prefix._request_tables + finally: + gate.release.set() + rig.close() + + +def test_shutdown_completes_pending_teardowns_within_the_bounded_wait( + tmp_path, mock_tokenizer, gated, monkeypatch +): + import omlx.scheduler as scheduler_module + + monkeypatch.setattr(scheduler_module, "PREFILL_COMMIT_SHUTDOWN_WAIT_S", 5.0) + rig = _Rig(tmp_path, mock_tokenizer, split=True, commit_blocks=2) + gate = gated(rig) + scheduler = rig.scheduler + _inflight_commit(rig, gate) + _returns_promptly(scheduler._do_abort_request, "r1") + threading.Timer(0.3, gate.release.set).start() + + scheduler.shutdown() + + assert not scheduler._deferred_teardowns + assert not scheduler._prefill_commits + assert "r1" not in scheduler._boundary_cache_snapshots + + +def test_shutdown_abandons_a_commit_that_never_completes( + tmp_path, mock_tokenizer, gated, monkeypatch +): + import omlx.scheduler as scheduler_module + + monkeypatch.setattr(scheduler_module, "PREFILL_COMMIT_SHUTDOWN_WAIT_S", 0.2) + rig = _Rig(tmp_path, mock_tokenizer, split=True, commit_blocks=2) + gate = gated(rig) + scheduler = rig.scheduler + _inflight_commit(rig, gate) + _returns_promptly(scheduler._do_abort_request, "r1") + + started = time.monotonic() + scheduler.shutdown() + assert time.monotonic() - started < 10 + assert not scheduler._deferred_teardowns + # The snapshot directory is gone even though the commit never finished. + assert not any((tmp_path / "cache").rglob("*r1*")) From 1cca37e252b845ab0b9e926d879e7f19acba7d59 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Thu, 1 Oct 2026 15:06:13 -0600 Subject: [PATCH 05/46] fix(scheduler): drain deferred teardowns on reap, skip held ids, cancel commits at shutdown --- omlx/scheduler.py | 172 ++++++++--- .../test_scheduler_prefill_progress_commit.py | 281 +++++++++++++++++- 2 files changed, 415 insertions(+), 38 deletions(-) diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 83c100fa1b..ceb77df011 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -17,6 +17,7 @@ import importlib import inspect import logging +import queue import threading import time from array import array @@ -1341,6 +1342,49 @@ def _is_turboquant_kv_family_cache(cache_obj: Any) -> bool: # A teardown deferred behind a commit that has not finished after this long # is logged once; it stays pending and is dropped at shutdown. PREFILL_COMMIT_STUCK_LOG_S = 60.0 +# Extra bounded wait at shutdown for a commit worker that is inside a store +# call after the cancel flag is set. Past it the stores are left unclosed. +PREFILL_COMMIT_CANCEL_WAIT_S = 10.0 + + +class _DaemonCommitExecutor: + """Single daemon worker thread with the ``submit``/``shutdown`` surface. + + ``ThreadPoolExecutor`` workers are non-daemon and joined at interpreter + exit, so a commit stuck in a store call would hang process exit. This + worker is a daemon: an abandoned commit cannot block exit, and shutdown + only waits for it through the cancel flag and the store lock. + """ + + def __init__(self, thread_name_prefix: str = "omlx-prefill-commit") -> None: + self._queue: queue.SimpleQueue = queue.SimpleQueue() + self._thread = threading.Thread( + target=self._run, name=f"{thread_name_prefix}_0", daemon=True + ) + self._thread.start() + + def _run(self) -> None: + while True: + item = self._queue.get() + if item is None: + return + future, fn, args, kwargs = item + if not future.set_running_or_notify_cancel(): + continue + try: + future.set_result(fn(*args, **kwargs)) + except BaseException as e: # noqa: BLE001 - delivered via the future + future.set_exception(e) + + def submit(self, fn: Callable[..., Any], *args: Any, **kwargs: Any): + future: concurrent.futures.Future = concurrent.futures.Future() + self._queue.put((future, fn, args, kwargs)) + return future + + def shutdown(self, wait: bool = False) -> None: + self._queue.put(None) + if wait: + self._thread.join() def _prefill_commit_blocks(config: Any) -> int: @@ -2233,9 +2277,11 @@ def __init__( self._prefill_commits: dict[str, tuple[concurrent.futures.Future, int]] = {} # Own single-thread executor so commits never queue behind the # post-finish final stores (28GB+ memcpys) on _store_cache_executor. - self._prefill_commit_executor: concurrent.futures.ThreadPoolExecutor | None = ( - None - ) + self._prefill_commit_executor: _DaemonCommitExecutor | None = None + # Shutdown sets the flag; the worker checks it under the lock before + # each store call, and shutdown takes the lock to know none is active. + self._commit_cancelled = threading.Event() + self._commit_store_lock = threading.Lock() # request_id -> destructive teardown steps (release block table, # retire snapshots, ...) postponed until that request's in-flight # commit has finished. Touched on the scheduler thread only. @@ -7739,14 +7785,10 @@ def _prefill_commit_window( self._apply_turboquant_kv_convert(window) return window - def _ensure_prefill_commit_executor( - self, - ) -> concurrent.futures.ThreadPoolExecutor: + def _ensure_prefill_commit_executor(self) -> _DaemonCommitExecutor: executor = self._prefill_commit_executor if executor is None: - executor = concurrent.futures.ThreadPoolExecutor( - max_workers=1, thread_name_prefix="omlx-prefill-commit" - ) + executor = _DaemonCommitExecutor("omlx-prefill-commit") self._prefill_commit_executor = executor return executor @@ -7782,6 +7824,9 @@ def _reap_prefill_commit(self, request_id: str) -> None: ok = False if ok: self._retire_committed_markers(request_id, committed_tokens) + # Draining is part of completion, not of whoever reaps: every path + # (step, finish, next commit) leaves no teardown without its commit. + self._run_deferred_teardowns(request_id) def _inflight_commit_future( self, request_id: str @@ -7836,8 +7881,12 @@ def _process_finished_commits(self) -> None: """ for request_id in list(self._prefill_commits): self._reap_prefill_commit(request_id) - if request_id not in self._prefill_commits: - self._run_deferred_teardowns(request_id) + # Safety net: a deferred teardown whose commit is no longer tracked + # would pin has_requests() and its request id forever. + for request_id in [ + rid for rid in self._deferred_teardowns if rid not in self._prefill_commits + ]: + self._run_deferred_teardowns(request_id) now = time.monotonic() for request_id, since in self._deferred_teardown_since.items(): if ( @@ -7986,19 +8035,27 @@ def _commit_prefill_worker( model_cache_config: Any | None, snapshots: Any | None, ) -> bool: - """Store a committed prefill window; True when the table covers it.""" - self._async_store_cache_worker( - request_id, - tokens, - window_cache, - model_cache_config, - snapshots, - None, - None, - None, - True, - incremental_commit=True, - ) + """Store a committed prefill window; True when the table covers it. + + Cancellation is checked under ``_commit_store_lock`` before the store + call, the only step that touches the stores; shutdown takes that lock + to learn that no store call is active. + """ + with self._commit_store_lock: + if self._commit_cancelled.is_set(): + return False + self._async_store_cache_worker( + request_id, + tokens, + window_cache, + model_cache_config, + snapshots, + None, + None, + None, + True, + incremental_commit=True, + ) table = self.paged_cache_manager.get_block_table(request_id) return bool(table is not None and table.num_tokens >= len(tokens)) @@ -12637,6 +12694,22 @@ def _preflight_safety_rejection( def _schedule_waiting( self, + ) -> tuple[list["Request"], list[RequestOutput]]: + """Admit waiting requests; see ``_schedule_waiting_scan``. + + Requests whose previous run of the same id is still being torn down + behind its prefill commit are set aside while the scan continues, so + one stuck commit never blocks the requests queued behind it; they + return to the front of the queue in their original order. + """ + held: list[Request] = [] + try: + return self._schedule_waiting_scan(held) + finally: + self.waiting.extendleft(reversed(held)) + + def _schedule_waiting_scan( + self, held: list["Request"] ) -> tuple[list["Request"], list[RequestOutput]]: """ Move requests from waiting queue to running. @@ -12772,9 +12845,10 @@ def _schedule_waiting( break if self._teardown_pending(request.request_id): # A previous run of this id is still being torn down behind - # its prefill commit; the head waits (no blocking) so the - # deferred cleanup cannot hit the new run's state. - break + # its prefill commit; only this request waits (no blocking) + # so the deferred cleanup cannot hit the new run's state. + held.append(self.waiting.popleft()) + continue request = self.waiting.popleft() self._cache_freshness_waits.pop(request.request_id, None) @@ -15272,22 +15346,40 @@ def deep_reset(self) -> None: logger.info("Deep reset completed - all caches cleared") - def _shutdown_prefill_commits(self) -> None: - """Finish or safely abandon prefill commits and their teardowns. + def _shutdown_prefill_commits(self) -> bool: + """Finish or cancel prefill commits and their teardowns. + + Returns True when a commit worker is still inside a store call after + the bounded waits; the caller must then leave the stores unclosed. The bounded wait is acceptable here only. A commit that outlives it - is abandoned: its pending teardowns are dropped (the snapshot - directories are removed by ``cleanup_all`` and the process is going - away), and its executor is not joined. + is cancelled: the worker checks ``_commit_cancelled`` under + ``_commit_store_lock`` before its store call, so it bails out cleanly + unless it is already inside one. Shutdown then waits a further + ``PREFILL_COMMIT_CANCEL_WAIT_S`` on that lock. The worker is a daemon + thread, so an abandoned commit cannot block interpreter exit. Pending + teardowns are dropped (``cleanup_all`` removes the snapshot + directories and the process is going away). """ executor = self._prefill_commit_executor stragglers = self._wait_for_prefill_commits(PREFILL_COMMIT_SHUTDOWN_WAIT_S) + store_busy = False if stragglers: + self._commit_cancelled.set() + if self._commit_store_lock.acquire(timeout=PREFILL_COMMIT_CANCEL_WAIT_S): + self._commit_store_lock.release() + else: + store_busy = True logger.warning( - "Abandoning %d prefill commit(s) still running at shutdown " - "(%d pending teardown(s) dropped)", + "Cancelled %d prefill commit(s) still running at shutdown " + "(%d pending teardown(s) dropped)%s", stragglers, len(self._deferred_teardowns), + ( + "; a commit is still inside a store call, stores stay open" + if store_busy + else "" + ), ) elif executor is not None: try: @@ -15301,6 +15393,7 @@ def _shutdown_prefill_commits(self) -> None: if executor is not None: executor.shutdown(wait=False) self._prefill_commit_executor = None + return store_busy def _store_persistence_progress(self): manager = self.paged_ssd_cache_manager @@ -15324,7 +15417,7 @@ def shutdown(self) -> None: # The store-cache gate is a non-blocking counter (#1496), so there is # no step-thread caller to wake here. Inflight futures are drained # below before the executor is asked to shut down. - self._shutdown_prefill_commits() + commit_store_busy = self._shutdown_prefill_commits() # Wait for any inflight async store_cache futures + drain pending # batch_generator removes so the writer thread / underlying paged SSD # cache see all blocks before close(). @@ -15393,7 +15486,7 @@ def shutdown(self) -> None: self._inflight_store_info.clear() self._cache_freshness_waits.clear() self._prefix_cache_prepared.clear() - if self._boundary_snapshot_store is not None: + if self._boundary_snapshot_store is not None and not commit_store_busy: try: self._boundary_snapshot_store.cleanup_all() except Exception as e: @@ -15406,7 +15499,12 @@ def shutdown(self) -> None: self._close_specprefill_draft_cache_manager() self._draft_prefix_cache = None self._specprefill_draft_model = None - if self.paged_ssd_cache_manager is not None: + if self.paged_ssd_cache_manager is not None and commit_store_busy: + logger.error( + "Leaving the paged SSD cache open: a prefill commit worker is " + "still inside a store call" + ) + elif self.paged_ssd_cache_manager is not None: if teardown is not None: teardown.set_phase( "primary_ssd", self.paged_ssd_cache_manager.persistence_progress diff --git a/tests/test_scheduler_prefill_progress_commit.py b/tests/test_scheduler_prefill_progress_commit.py index 8706a50750..0e0dce7545 100644 --- a/tests/test_scheduler_prefill_progress_commit.py +++ b/tests/test_scheduler_prefill_progress_commit.py @@ -114,7 +114,9 @@ def step(self, state, chunks): done = False for _ in range(chunks): done = self.scheduler._step_prefill_chunk(state) - self.drain() + # A commit still in flight makes the next chunk skip its own, so + # settle each one: the commit cadence stays deterministic. + self.drain() return done def drain(self): @@ -910,3 +912,280 @@ def test_shutdown_abandons_a_commit_that_never_completes( assert not scheduler._deferred_teardowns # The snapshot directory is gone even though the commit never finished. assert not any((tmp_path / "cache").rglob("*r1*")) + + +# --- Reaping, admission, shutdown, reset barrier ------------------------------- + + +def _orphans(scheduler): + """Deferred teardowns with neither a tracked commit nor a completion to run on.""" + return [ + rid + for rid in scheduler._deferred_teardowns + if rid not in scheduler._prefill_commits + ] + + +def test_teardowns_drain_when_another_path_reaps_the_commit_first( + tmp_path, mock_tokenizer, gated +): + rig = _Rig(tmp_path, mock_tokenizer, split=True, commit_blocks=2) + gate = gated(rig) + try: + scheduler = rig.scheduler + _inflight_commit(rig, gate) + _returns_promptly(scheduler._do_abort_request, "r1") + assert scheduler._teardown_pending("r1") + gate.release.set() + scheduler._prefill_commits["r1"][0].result(timeout=20) + + # _cleanup_finished-style reap, before _process_finished_commits runs. + assert scheduler._inflight_commit_future("r1") is None + + assert _orphans(scheduler) == [] + assert not scheduler._teardown_pending("r1") + assert "r1" not in scheduler._boundary_cache_snapshots + assert not scheduler._deferred_teardowns # has_requests() is not pinned + finally: + gate.release.set() + rig.close() + + +def test_orphaned_deferred_teardowns_are_swept_at_the_next_step( + tmp_path, mock_tokenizer +): + rig = _Rig(tmp_path, mock_tokenizer, split=False, commit_blocks=2) + try: + scheduler = rig.scheduler + ran = [] + scheduler._deferred_teardowns["ghost"] = [lambda: ran.append("ghost")] + scheduler._deferred_teardown_since["ghost"] = time.monotonic() + + scheduler._process_finished_commits() + + assert ran == ["ghost"] + assert _orphans(scheduler) == [] + assert not scheduler._teardown_pending("ghost") + finally: + rig.close() + + +def test_unrelated_request_is_admitted_behind_a_held_head( + tmp_path, mock_tokenizer, gated +): + rig = _Rig(tmp_path, mock_tokenizer, split=True, commit_blocks=2) + gate = gated(rig) + try: + scheduler = rig.scheduler + request, state = rig.start("r1", PROMPT) + for _ in range(2): + scheduler._step_prefill_chunk(state) + assert gate.entered.wait(20) + _returns_promptly(scheduler._drop_boundary_snapshots_for_request, "r1") + other = Request( + request_id="r2", + prompt=list(range(40, 57)), + sampling_params=SamplingParams(max_tokens=1), + ) + third = Request( + request_id="r3", + prompt=list(range(60, 77)), + sampling_params=SamplingParams(max_tokens=1), + ) + scheduler.add_request(other) + scheduler.add_request(third) + scheduler.waiting.clear() + scheduler.waiting.extend([request, other, third]) + + scheduled, _ = scheduler._schedule_waiting() + + assert [r.request_id for r in scheduled] + [ + r.request_id for r in scheduler.prefilling + ] != [] + queued = [r.request_id for r in scheduler.waiting] + assert queued[0] == "r1" # the held head keeps its place + assert "r2" not in queued # the unrelated request got through + finally: + gate.release.set() + rig.close() + + +class _BlockingStore: + """Replaces store_cache with a call that blocks until released.""" + + def __init__(self, rig, monkeypatch): + self.entered = threading.Event() + self.release = threading.Event() + self.calls = 0 + real = rig.prefix.store_cache + + def blocking(*args, **kwargs): + self.calls += 1 + self.entered.set() + assert self.release.wait(30) + return real(*args, **kwargs) + + monkeypatch.setattr(rig.prefix, "store_cache", blocking) + + +def test_shutdown_cancels_a_commit_that_has_not_reached_the_store( + tmp_path, mock_tokenizer, gated, monkeypatch +): + import omlx.scheduler as scheduler_module + + monkeypatch.setattr(scheduler_module, "PREFILL_COMMIT_SHUTDOWN_WAIT_S", 0.2) + rig = _Rig(tmp_path, mock_tokenizer, split=True, commit_blocks=2) + gate = gated(rig) + scheduler = rig.scheduler + _inflight_commit(rig, gate) + future, _ = scheduler._prefill_commits["r1"] + stores = [] + real_store = rig.prefix.store_cache + monkeypatch.setattr( + rig.prefix, + "store_cache", + lambda *a, **k: (stores.append(1), real_store(*a, **k))[1], + ) + + started = time.monotonic() + scheduler.shutdown() + assert time.monotonic() - started < 10 + + gate.release.set() + assert future.result(timeout=10) is False # bailed out, no store attempted + assert stores == [] + + +def test_shutdown_does_not_close_the_stores_under_an_active_store_call( + tmp_path, mock_tokenizer, monkeypatch +): + import omlx.scheduler as scheduler_module + + monkeypatch.setattr(scheduler_module, "PREFILL_COMMIT_SHUTDOWN_WAIT_S", 0.2) + monkeypatch.setattr(scheduler_module, "PREFILL_COMMIT_CANCEL_WAIT_S", 0.3) + rig = _Rig(tmp_path, mock_tokenizer, split=True, commit_blocks=2) + blocking = _BlockingStore(rig, monkeypatch) + scheduler = rig.scheduler + closed = [] + real_ssd_close = rig.ssd.close + real_boundary_shutdown = rig.boundary.shutdown + monkeypatch.setattr( + rig.ssd, + "close", + lambda *a, **k: (closed.append("ssd"), real_ssd_close(*a, **k)), + ) + monkeypatch.setattr( + rig.boundary, + "shutdown", + lambda *a, **k: (closed.append("boundary"), real_boundary_shutdown(*a, **k)), + ) + try: + _, state = rig.start("r1", PROMPT) + for _ in range(2): + scheduler._step_prefill_chunk(state) + assert blocking.entered.wait(20) + + started = time.monotonic() + scheduler.shutdown() + assert time.monotonic() - started < 10 # bounded + assert closed == [] # worker is still inside the store call + finally: + blocking.release.set() + time.sleep(0.2) + real_ssd_close() + real_boundary_shutdown() + + +def test_commit_executor_threads_cannot_block_interpreter_exit( + tmp_path, mock_tokenizer +): + rig = _Rig(tmp_path, mock_tokenizer, split=False, commit_blocks=2) + try: + executor = rig.scheduler._ensure_prefill_commit_executor() + seen = executor.submit(lambda: threading.current_thread()).result(timeout=10) + assert seen.daemon + assert seen.name.startswith("omlx-prefill-commit") + finally: + rig.close() + + +def test_reset_runs_deferred_teardowns_before_clearing_state( + tmp_path, mock_tokenizer, gated, monkeypatch +): + import omlx.scheduler as scheduler_module + + monkeypatch.setattr(scheduler_module, "FATAL_TEARDOWN_TIMEOUT_S", 10.0) + rig = _Rig(tmp_path, mock_tokenizer, split=True, commit_blocks=2) + gate = gated(rig) + scheduler = rig.scheduler + try: + _inflight_commit(rig, gate) + _returns_promptly(scheduler._do_abort_request, "r1") + events = [] + real_cleanup = rig.boundary.cleanup_request + real_clear = rig.prefix.clear + monkeypatch.setattr( + rig.boundary, + "cleanup_request", + lambda rid: (events.append("teardown"), real_cleanup(rid))[1], + ) + monkeypatch.setattr( + rig.prefix, "clear", lambda: (events.append("clear"), real_clear())[1] + ) + threading.Timer(0.3, gate.release.set).start() + + scheduler.reset() + + assert events[:2] == ["teardown", "clear"] + assert not scheduler._deferred_teardowns + assert not scheduler._prefill_commits + finally: + gate.release.set() + rig.close() + + +def test_reset_is_fatal_when_a_commit_outlives_the_barrier( + tmp_path, mock_tokenizer, gated, monkeypatch +): + import omlx.scheduler as scheduler_module + + monkeypatch.setattr(scheduler_module, "FATAL_TEARDOWN_TIMEOUT_S", 0.2) + fatal = [] + monkeypatch.setattr(scheduler_module, "fatal_exit", lambda msg: fatal.append(msg)) + rig = _Rig(tmp_path, mock_tokenizer, split=True, commit_blocks=2) + gate = gated(rig) + scheduler = rig.scheduler + try: + _inflight_commit(rig, gate) + scheduler.reset() + assert len(fatal) == 1 + assert "prefill commit" in fatal[0] + assert "r1" in scheduler._prefill_commits # nothing was cleared + finally: + gate.release.set() + rig.close() + + +def test_stuck_teardown_warning_is_logged_once( + tmp_path, mock_tokenizer, gated, monkeypatch, caplog +): + import logging + + import omlx.scheduler as scheduler_module + + monkeypatch.setattr(scheduler_module, "PREFILL_COMMIT_STUCK_LOG_S", 0.0) + rig = _Rig(tmp_path, mock_tokenizer, split=True, commit_blocks=2) + gate = gated(rig) + scheduler = rig.scheduler + try: + _inflight_commit(rig, gate) + _returns_promptly(scheduler._do_abort_request, "r1") + with caplog.at_level(logging.WARNING, logger="omlx.scheduler"): + for _ in range(3): + scheduler._process_finished_commits() + stuck = [r for r in caplog.records if "still waits" in r.getMessage()] + assert len(stuck) == 1 + assert "r1" in stuck[0].getMessage() + finally: + gate.release.set() + rig.close() From 2be13399bd2dc3fa046b6ea64fbf673b2690ac16 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Thu, 1 Oct 2026 15:29:50 -0600 Subject: [PATCH 06/46] fix(scheduler): bound the final store's wait on an in-flight prefill 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. --- omlx/scheduler.py | 50 ++++++++++++- .../test_scheduler_prefill_progress_commit.py | 70 +++++++++++++++++++ 2 files changed, 118 insertions(+), 2 deletions(-) diff --git a/omlx/scheduler.py b/omlx/scheduler.py index ceb77df011..46ecbff71d 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -1345,6 +1345,10 @@ def _is_turboquant_kv_family_cache(cache_obj: Any) -> bool: # Extra bounded wait at shutdown for a commit worker that is inside a store # call after the cancel flag is set. Past it the stores are left unclosed. PREFILL_COMMIT_CANCEL_WAIT_S = 10.0 +# Bound on the final-store worker waiting for the request's in-flight commit. +# Past it the final store is skipped so a stuck commit cannot hold the store +# worker (and the gate slots queued behind it). +PREFILL_COMMIT_FINAL_STORE_WAIT_S = 120.0 class _DaemonCommitExecutor: @@ -2288,6 +2292,10 @@ def __init__( self._deferred_teardowns: dict[str, list[Callable[[], None]]] = {} self._deferred_teardown_since: dict[str, float] = {} self._stuck_teardown_logged: set[str] = set() + # Final stores skipped because the request's commit never ended within + # PREFILL_COMMIT_FINAL_STORE_WAIT_S. Added on the store worker (GIL-atomic + # set.add), consumed by _drain_pending_async_removes on the scheduler thread. + self._skipped_final_stores: set[str] = set() self.requests: dict[str, Request] = {} # All requests by ID self.finished_req_ids: set[str] = set() # Recently finished self._generation_overflow_recovery_ids: set[str] = set() @@ -2886,7 +2894,21 @@ def _async_store_cache_worker( """ self._store_cache_thread_id = threading.get_ident() if after_commit is not None: - concurrent.futures.wait([after_commit]) + done, _pending = concurrent.futures.wait( + [after_commit], timeout=PREFILL_COMMIT_FINAL_STORE_WAIT_S + ) + if not done: + # Skip this final store; table and snapshot teardown stays + # deferred behind the commit (scheduler thread), the gate slot + # is released when the drain sees this future done. + logger.warning( + "Skipping final store for %s: its prefill commit did not " + "finish within %.0fs", + request_id, + PREFILL_COMMIT_FINAL_STORE_WAIT_S, + ) + self._skipped_final_stores.add(request_id) + return window_kwargs = {"cache_covers_suffix_only": True} if incremental_commit else {} try: # Hold _mx_buffer_access_lock across the worker's mx-buffer @@ -2939,6 +2961,21 @@ def _async_store_cache_worker( except Exception as e: logger.warning("Async store_cache failed for %s: %s", request_id, e) + def _skipped_store_teardown(self, request_id: str) -> Callable[[], None]: + """Teardown for a request whose final store was skipped (stuck commit).""" + + def teardown() -> None: + if self._boundary_snapshot_store is not None: + self._boundary_snapshot_store.cleanup_request(request_id) + if self.paged_cache_manager is not None: + block_table = self.paged_cache_manager.get_block_table(request_id) + if block_table: + self.paged_cache_manager.release_for_eviction(block_table.block_ids) + if self.block_aware_cache is not None: + self.block_aware_cache.clear_request_entry(request_id) + + return teardown + def _drain_pending_async_removes(self) -> bool: """Process deferred batch_generator.remove() calls from prior steps. @@ -2998,7 +3035,15 @@ def _drain_pending_async_removes(self) -> bool: # delete now that the future has completed. Cleanup was # deferred from _cleanup_finished to avoid racing the worker's # boundary_snapshot_store.load() calls with rmtree. - if self._boundary_snapshot_store is not None: + if request_id in self._skipped_final_stores: + # The final store never ran: the stuck commit may still + # read the snapshots and use the table, so both are torn + # down once it ends, exactly as the worker would have. + self._skipped_final_stores.discard(request_id) + self._after_commit( + request_id, self._skipped_store_teardown(request_id) + ) + elif self._boundary_snapshot_store is not None: self._boundary_snapshot_store.cleanup_request(request_id) # Worker no longer holds extracted_cache — pop request from # self.requests and drop the cache buffer references so MLX @@ -15265,6 +15310,7 @@ def reset(self) -> None: self._deferred_teardowns.clear() self._deferred_teardown_since.clear() self._stuck_teardown_logged.clear() + self._skipped_final_stores.clear() self._prefill_commits.clear() self._cache_freshness_waits.clear() self._prefix_cache_prepared.clear() diff --git a/tests/test_scheduler_prefill_progress_commit.py b/tests/test_scheduler_prefill_progress_commit.py index 0e0dce7545..2bf88a5dc6 100644 --- a/tests/test_scheduler_prefill_progress_commit.py +++ b/tests/test_scheduler_prefill_progress_commit.py @@ -1189,3 +1189,73 @@ def test_stuck_teardown_warning_is_logged_once( finally: gate.release.set() rig.close() + + +# --- Bounded wait of the final store on an in-flight commit -------------------- + + +def test_stuck_commit_times_out_the_final_store_and_frees_the_slot( + tmp_path, mock_tokenizer, monkeypatch, gated, caplog +): + """A commit that never ends must not hold the final-store worker or gate. + + The final store is skipped (logged once), the store-gate slot is released, + and a later request's final store proceeds on the same worker thread. + """ + import logging + + import omlx.scheduler as scheduler_module + + monkeypatch.setattr(scheduler_module, "PREFILL_COMMIT_FINAL_STORE_WAIT_S", 0.3) + rig = _Rig(tmp_path, mock_tokenizer, split=False, commit_blocks=2) + gate = gated(rig) + try: + scheduler = rig.scheduler + request, state = rig.start("r1", PROMPT) + while not scheduler._step_prefill_chunk(state): + pass + assert gate.entered.wait(20) + finished = _decode_to_finish(rig, request, state) + + class _Gate: + submitted = 0 + done = 0 + + def note_submitted(self): + self.submitted += 1 + + def note_done(self): + self.done += 1 + + store_gate = _Gate() + scheduler._store_cache_gate = store_gate + with caplog.at_level(logging.WARNING, logger="omlx.scheduler"): + scheduler._cleanup_finished(finished) + scheduler._inflight_store_futures["r1"].result(timeout=10) + scheduler._drain_pending_async_removes() + + # Skipped, logged once, slot released although the commit still runs. + timeouts = [r for r in caplog.records if "final store" in r.getMessage()] + assert len(timeouts) == 1 + assert store_gate.submitted == 1 and store_gate.done == 1 + assert "r1" not in scheduler._inflight_store_futures + assert not scheduler._pending_async_removes + + # Table state is released through the deferred teardown once it ends. + assert scheduler._teardown_pending("r1") + gate.release.set() + rig.drain() + assert not scheduler._teardown_pending("r1") + assert "r1" not in rig.prefix._request_tables + # The blocks the commit stored stay reusable by a re-issue. + table, _ = rig.probe(PROMPT) + assert table is not None and table.num_tokens >= BLOCK + + # A later final store proceeds. + request2, state2 = rig.start("r2", list(range(40, 57))) + _finish(rig, request2, state2) + table, _ = rig.probe(list(range(40, 57))) + assert table is not None and table.num_tokens == 4 * BLOCK + finally: + gate.release.set() + rig.close() From beea8719bdf9b02d460a91c4ee9cae078d1e2483 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Fri, 2 Oct 2026 09:17:11 -0600 Subject: [PATCH 07/46] refactor(scheduler): move the prefill commit executor into its own module 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. --- omlx/prefill_commit_executor.py | 54 +++++++++++++++++++++++++++++++++ omlx/scheduler.py | 42 +------------------------ 2 files changed, 55 insertions(+), 41 deletions(-) create mode 100644 omlx/prefill_commit_executor.py diff --git a/omlx/prefill_commit_executor.py b/omlx/prefill_commit_executor.py new file mode 100644 index 0000000000..49550b4f63 --- /dev/null +++ b/omlx/prefill_commit_executor.py @@ -0,0 +1,54 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Single daemon-thread executor for incremental prefill commits. + +Kept out of ``scheduler.py`` so the scheduler module has exactly one +``shutdown`` definition (``Scheduler.shutdown``). +""" + +from __future__ import annotations + +import concurrent.futures +import queue +import threading +from collections.abc import Callable +from typing import Any + + +class DaemonCommitExecutor: + """Single daemon worker thread with the ``submit``/``shutdown`` surface. + + ``ThreadPoolExecutor`` workers are non-daemon and joined at interpreter + exit, so a commit stuck in a store call would hang process exit. This + worker is a daemon: an abandoned commit cannot block exit, and shutdown + only waits for it through the cancel flag and the store lock. + """ + + def __init__(self, thread_name_prefix: str = "omlx-prefill-commit") -> None: + self._queue: queue.SimpleQueue = queue.SimpleQueue() + self._thread = threading.Thread( + target=self._run, name=f"{thread_name_prefix}_0", daemon=True + ) + self._thread.start() + + def _run(self) -> None: + while True: + item = self._queue.get() + if item is None: + return + future, fn, args, kwargs = item + if not future.set_running_or_notify_cancel(): + continue + try: + future.set_result(fn(*args, **kwargs)) + except BaseException as e: # noqa: BLE001 - delivered via the future + future.set_exception(e) + + def submit(self, fn: Callable[..., Any], *args: Any, **kwargs: Any): + future: concurrent.futures.Future = concurrent.futures.Future() + self._queue.put((future, fn, args, kwargs)) + return future + + def shutdown(self, wait: bool = False) -> None: + self._queue.put(None) + if wait: + self._thread.join() diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 46ecbff71d..a7462066e4 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -17,7 +17,6 @@ import importlib import inspect import logging -import queue import threading import time from array import array @@ -78,6 +77,7 @@ clamp_prefill_chunk_to_boundary, should_emit_prefill_boundary, ) +from .prefill_commit_executor import DaemonCommitExecutor as _DaemonCommitExecutor from .prefill_progress import get_prefill_tracker from .prefill_transient_tracker import PrefillTransientTracker from .request import Request, RequestOutput, RequestStatus, SamplingParams @@ -1351,46 +1351,6 @@ def _is_turboquant_kv_family_cache(cache_obj: Any) -> bool: PREFILL_COMMIT_FINAL_STORE_WAIT_S = 120.0 -class _DaemonCommitExecutor: - """Single daemon worker thread with the ``submit``/``shutdown`` surface. - - ``ThreadPoolExecutor`` workers are non-daemon and joined at interpreter - exit, so a commit stuck in a store call would hang process exit. This - worker is a daemon: an abandoned commit cannot block exit, and shutdown - only waits for it through the cancel flag and the store lock. - """ - - def __init__(self, thread_name_prefix: str = "omlx-prefill-commit") -> None: - self._queue: queue.SimpleQueue = queue.SimpleQueue() - self._thread = threading.Thread( - target=self._run, name=f"{thread_name_prefix}_0", daemon=True - ) - self._thread.start() - - def _run(self) -> None: - while True: - item = self._queue.get() - if item is None: - return - future, fn, args, kwargs = item - if not future.set_running_or_notify_cancel(): - continue - try: - future.set_result(fn(*args, **kwargs)) - except BaseException as e: # noqa: BLE001 - delivered via the future - future.set_exception(e) - - def submit(self, fn: Callable[..., Any], *args: Any, **kwargs: Any): - future: concurrent.futures.Future = concurrent.futures.Future() - self._queue.put((future, fn, args, kwargs)) - return future - - def shutdown(self, wait: bool = False) -> None: - self._queue.put(None) - if wait: - self._thread.join() - - def _prefill_commit_blocks(config: Any) -> int: """``prefill_progress_commit_blocks`` of a config, 0 when unset or invalid.""" value = getattr(config, "prefill_progress_commit_blocks", 0) From e37bdfc83b65a79e857b3bd005b1208bd6223394 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Thu, 1 Oct 2026 15:34:03 -0600 Subject: [PATCH 08/46] feat(enforcer): request a prefill park before aborting at hard pressure 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. --- omlx/process_memory_enforcer.py | 74 +++++++++++++++++ omlx/scheduler.py | 5 ++ omlx/settings.py | 43 ++++++++++ tests/test_process_memory_enforcer.py | 110 ++++++++++++++++++++++++++ tests/test_settings.py | 59 ++++++++++++++ 5 files changed, 291 insertions(+) diff --git a/omlx/process_memory_enforcer.py b/omlx/process_memory_enforcer.py index e021adee0b..b0e9448d21 100644 --- a/omlx/process_memory_enforcer.py +++ b/omlx/process_memory_enforcer.py @@ -468,6 +468,9 @@ def __init__( # prefill chunk / step boundary. See the grace check in # _check_and_enforce. self._pressure_reclaim_grace_polls: int = 0 + # Consecutive hard-pressure polls whose abort was deferred in favor of + # parking a prefill victim. See _request_scheduler_park. + self._park_deferred_polls: int = 0 # Last value passed to mx.set_wired_limit (0 if not yet applied # or the call failed). Used by the admin dashboard to surface a # warning when the kernel iogpu.wired_limit_mb is below this. @@ -1271,6 +1274,10 @@ def _shrink_hot_cache_by( # while a reclaimable pool drains. Prefill chunks run ~5s at full step # size, so 5 one-second polls cover at least one chunk boundary. _PRESSURE_RECLAIM_GRACE_POLLS_MAX = 5 + # Max consecutive hard-pressure polls the abort is deferred because a + # scheduler reports a prefill victim to park (or one just parked). Bounds + # the deferral if the scheduler never gets to act on the request. + _PARK_DEFER_POLLS_MAX = 30 def _pool_bytes(self) -> int: """MLX buffer-pool size, 0 when unreadable (mocked mx in tests).""" @@ -1321,6 +1328,45 @@ def _request_scheduler_cache_reclaim(self, freed_hot: int) -> int: ) return requested + def _request_scheduler_park(self) -> int: + """Ask each scheduler to park one prefill victim instead of aborting. + + Sets a GIL-atomic flag on the scheduler; the park itself runs on the + inference thread at the next step boundary, so the enforcer never + touches request or Metal state. A scheduler answers ``True`` only when + a victim is parkable or a park is still settling; any other answer + (park disabled, nothing parkable, no API) leaves the legacy abort in + place. Returns the number of schedulers that accepted. + """ + accepted = 0 + for entry in self._engine_pool._entries.values(): + scheduler = self._resolve_scheduler(entry) + request = getattr(scheduler, "request_park_prefill", None) + if not callable(request): + continue + try: + if request() is True: + accepted += 1 + except Exception as exc: # noqa: BLE001 + logger.warning("Prefill park request failed: %s", exc) + return accepted + + def _note_pressure_poll(self, level: str) -> None: + """Report this poll's pressure level to every scheduler. + + Schedulers count consecutive ``ok`` polls to decide when parked + requests may resume (hysteresis). Called once per enforcement tick. + """ + for entry in self._engine_pool._entries.values(): + scheduler = self._resolve_scheduler(entry) + note = getattr(scheduler, "note_pressure_poll", None) + if not callable(note): + continue + try: + note(level) + except Exception as exc: # noqa: BLE001 + logger.debug("Pressure poll report failed: %s", exc) + def get_pressure_level(self) -> str: """Return cached pressure level: 'ok', 'soft', or 'hard'. @@ -1692,6 +1738,8 @@ async def _check_and_enforce(self) -> None: self._pressure_level = "ok" self._over_ceiling_polls = 0 self._pressure_reclaim_grace_polls = 0 + self._park_deferred_polls = 0 + self._note_pressure_poll("ok") return current = self._current_usage_bytes() @@ -1717,6 +1765,10 @@ async def _check_and_enforce(self) -> None: else: new_level = "hard" + self._note_pressure_poll(new_level) + if new_level != "hard": + self._park_deferred_polls = 0 + if new_level == "ok": # The pressure episode ended (drain worked or the load finished): # the next one gets a fresh reclaim-grace budget. Must happen @@ -1802,6 +1854,28 @@ async def _check_and_enforce(self) -> None: self._walk_store_cache_caps() return + # Park before abort: a scheduler with a parkable prefill victim pauses + # it (work already done survives in the prefix cache) and the abort + # below only runs when nothing is left to park, the deferral budget is + # spent, or pressure is an emergency (beyond the real ceiling). + if ( + new_level == "hard" + and not emergency + and self._park_deferred_polls < self._PARK_DEFER_POLLS_MAX + ): + parked_on = self._request_scheduler_park() + if parked_on: + self._park_deferred_polls += 1 + logger.info( + "Hard memory pressure: parking a prefill victim on %d " + "scheduler(s) instead of aborting (poll %d/%d)", + parked_on, + self._park_deferred_polls, + self._PARK_DEFER_POLLS_MAX, + ) + self._walk_store_cache_caps() + return + # Recover below soft regardless of level — prevents oscillation # at the boundary. target = soft diff --git a/omlx/scheduler.py b/omlx/scheduler.py index a7462066e4..e597c02eea 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -1873,6 +1873,11 @@ class SchedulerConfig: # completed blocks, and a re-issue of the same prompt resumes from the last # committed block boundary instead of prefilling from token zero. prefill_progress_commit_blocks: int = 0 + # Park (pause without error) the most recent prefilling request under hard + # memory pressure instead of aborting; see Scheduler.request_park_prefill. + memory_pressure_park: bool = False + max_parks_per_request: int = 3 + park_resume_ok_polls: int = 3 # Paged cache settings (internal defaults) paged_cache_block_size: int = 256 # Tokens per block diff --git a/omlx/settings.py b/omlx/settings.py index d363d0f111..b468b08366 100644 --- a/omlx/settings.py +++ b/omlx/settings.py @@ -355,6 +355,15 @@ class SchedulerSettings: # prompt is still prefilling, so an aborted or re-issued request resumes from # the last committed block instead of token zero. 0 disables it. prefill_progress_commit_blocks: int = 0 + # Under hard memory pressure, pause (park) the most recent prefilling + # request instead of aborting everything; it re-queues without an error + # and resumes from its last committed prefix once pressure has cleared. + # Best with prefill_progress_commit_blocks > 0 (otherwise it resumes cold). + memory_pressure_park: bool = False + # Parks a single request may take before it falls back to the abort. + max_parks_per_request: int = 3 + # Consecutive "ok" pressure polls before parked requests may resume. + park_resume_ok_polls: int = 3 def to_dict(self) -> dict[str, Any]: """Convert to dictionary.""" @@ -383,6 +392,13 @@ def from_dict(cls, data: dict[str, Any]) -> SchedulerSettings: or commit_blocks < 0 ): commit_blocks = 0 + + def positive_int(key: str, default: int) -> int: + value = data.get(key, default) + if not isinstance(value, int) or isinstance(value, bool) or value < 1: + return default + return value + return cls( max_concurrent_requests=value, embedding_batch_size=embedding_batch_size, @@ -390,6 +406,9 @@ def from_dict(cls, data: dict[str, Any]) -> SchedulerSettings: prefill_priority=prefill_priority, decode_fairness=bool(data.get("decode_fairness", True)), prefill_progress_commit_blocks=commit_blocks, + memory_pressure_park=data.get("memory_pressure_park") is True, + max_parks_per_request=positive_int("max_parks_per_request", 3), + park_resume_ok_polls=positive_int("park_resume_ok_polls", 3), ) @@ -1280,6 +1299,17 @@ def _apply_env_overrides(self) -> None: f"Invalid OMLX_PREFILL_PROGRESS_COMMIT_BLOCKS value: " f"{commit_blocks}" ) + if park := os.getenv("OMLX_MEMORY_PRESSURE_PARK"): + self.scheduler.memory_pressure_park = park.lower() in ("true", "1", "yes") + for env_name, attr in ( + ("OMLX_MAX_PARKS_PER_REQUEST", "max_parks_per_request"), + ("OMLX_PARK_RESUME_OK_POLLS", "park_resume_ok_polls"), + ): + if raw := os.getenv(env_name): + try: + setattr(self.scheduler, attr, int(raw)) + except ValueError: + logger.warning(f"Invalid {env_name} value: {raw}") # Cache settings if cache_enabled := os.getenv("OMLX_CACHE_ENABLED"): @@ -1796,6 +1826,16 @@ def validate(self) -> list[str]: f"Invalid prefill_progress_commit_blocks: " f"{self.scheduler.prefill_progress_commit_blocks} (must be >= 0)" ) + if self.scheduler.max_parks_per_request < 1: + errors.append( + f"Invalid max_parks_per_request: " + f"{self.scheduler.max_parks_per_request} (must be >= 1)" + ) + if self.scheduler.park_resume_ok_polls < 1: + errors.append( + f"Invalid park_resume_ok_polls: " + f"{self.scheduler.park_resume_ok_polls} (must be >= 1)" + ) # Cache validation if self.cache.gdn_ssd_split_enabled is True and self.cache.hot_cache_only: @@ -1974,6 +2014,9 @@ def to_scheduler_config(self) -> SchedulerConfig: prefill_progress_commit_blocks=( self.scheduler.prefill_progress_commit_blocks ), + memory_pressure_park=self.scheduler.memory_pressure_park, + max_parks_per_request=self.scheduler.max_parks_per_request, + park_resume_ok_polls=self.scheduler.park_resume_ok_polls, initial_cache_blocks=self.cache.initial_cache_blocks, paged_ssd_cache_dir=str(ssd_dir) if ssd_dir else None, hot_cache_only=self.cache.hot_cache_only, diff --git a/tests/test_process_memory_enforcer.py b/tests/test_process_memory_enforcer.py index 14c1bbbd18..6205d56b08 100644 --- a/tests/test_process_memory_enforcer.py +++ b/tests/test_process_memory_enforcer.py @@ -3378,3 +3378,113 @@ async def test_image_cache_reclaim_remeasures_retained_request_memory(mock_engin assert active_image.getpixel((0, 0)) == (0, 0, 255) finally: images.clear_image_decode_cache() + + +class TestPrefillParkRequest: + """Hard pressure asks the scheduler to park a prefill victim before it + falls back to the legacy abort. Park off (the scheduler answers False or + has no park API) keeps the abort exactly as before.""" + + @pytest.fixture + def enforcer(self, mock_engine_pool): + # Two watermarks: hard (95 GB) sits below the 100 GB ceiling, so + # repeated hard polls are not escalated to emergency pressure. + return _make_enforcer( + mock_engine_pool, + ceiling=100 * 1024**3, + soft_threshold=0.85, + hard_threshold=0.95, + ) + + def _setup(self, enforcer, park_answer): + engine = MagicMock() + engine.has_active_requests.return_value = False + engine.abort_all_requests = AsyncMock(return_value=1) + scheduler = SimpleNamespace( + request_park_prefill=MagicMock(return_value=park_answer), + note_pressure_poll=MagicMock(), + adjust_store_cache_cap=MagicMock(), + ) + engine.scheduler = scheduler + entry = _make_entry("big-model", engine=engine) + entry.in_use = 1 + enforcer._engine_pool._entries = {"big-model": entry} + enforcer._engine_pool._find_lru_victim.return_value = None + return engine, scheduler + + async def _tick(self, enforcer, usage=96 * 1024**3): + with patch("omlx.process_memory_enforcer.mx") as mock_mx: + mock_mx.get_active_memory.return_value = usage + mock_mx.get_cache_memory.return_value = 0 + await enforcer._check_and_enforce() + + @pytest.mark.asyncio + async def test_park_disabled_still_aborts_as_before(self, enforcer): + engine, scheduler = self._setup(enforcer, park_answer=False) + await self._tick(enforcer) + scheduler.request_park_prefill.assert_called_once() + engine.abort_all_requests.assert_awaited_once() + + @pytest.mark.asyncio + async def test_scheduler_without_park_api_aborts_as_before(self, enforcer): + engine, scheduler = self._setup(enforcer, park_answer=False) + del scheduler.request_park_prefill + await self._tick(enforcer) + engine.abort_all_requests.assert_awaited_once() + + @pytest.mark.asyncio + async def test_parkable_victim_defers_the_abort(self, enforcer): + engine, scheduler = self._setup(enforcer, park_answer=True) + await self._tick(enforcer) + scheduler.request_park_prefill.assert_called_once() + engine.abort_all_requests.assert_not_awaited() + enforcer._engine_pool._unload_engine.assert_not_awaited() + + @pytest.mark.asyncio + async def test_abort_after_nothing_is_left_to_park(self, enforcer): + engine, scheduler = self._setup(enforcer, park_answer=True) + await self._tick(enforcer) + engine.abort_all_requests.assert_not_awaited() + scheduler.request_park_prefill.return_value = False + await self._tick(enforcer) + engine.abort_all_requests.assert_awaited_once() + + @pytest.mark.asyncio + async def test_a_scheduler_that_never_parks_cannot_defer_forever(self, enforcer): + engine, scheduler = self._setup(enforcer, park_answer=True) + for _ in range(enforcer._PARK_DEFER_POLLS_MAX): + await self._tick(enforcer) + engine.abort_all_requests.assert_not_awaited() + await self._tick(enforcer) + engine.abort_all_requests.assert_awaited_once() + + @pytest.mark.asyncio + async def test_emergency_pressure_aborts_without_parking(self, enforcer): + engine, scheduler = self._setup(enforcer, park_answer=True) + await self._tick(enforcer, usage=103 * 1024**3) + scheduler.request_park_prefill.assert_not_called() + engine.abort_all_requests.assert_awaited() + + @pytest.mark.asyncio + async def test_a_truthy_non_bool_answer_is_not_a_park(self, enforcer): + engine, scheduler = self._setup(enforcer, park_answer=MagicMock()) + await self._tick(enforcer) + engine.abort_all_requests.assert_awaited_once() + + @pytest.mark.asyncio + async def test_park_deferral_budget_resets_when_pressure_clears(self, enforcer): + engine, scheduler = self._setup(enforcer, park_answer=True) + for _ in range(3): + await self._tick(enforcer) + assert enforcer._park_deferred_polls == 3 + await self._tick(enforcer, usage=1 * 1024**3) + assert enforcer._park_deferred_polls == 0 + + @pytest.mark.asyncio + async def test_every_poll_reports_its_level_to_the_scheduler(self, enforcer): + engine, scheduler = self._setup(enforcer, park_answer=False) + await self._tick(enforcer, usage=1 * 1024**3) + scheduler.note_pressure_poll.assert_called_with("ok") + await self._tick(enforcer, usage=96 * 1024**3) + scheduler.note_pressure_poll.assert_called_with("hard") + assert scheduler.note_pressure_poll.call_count == 2 diff --git a/tests/test_settings.py b/tests/test_settings.py index b4218c8366..5def31bfa6 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -395,6 +395,9 @@ def test_to_dict(self): "prefill_priority": "context", "decode_fairness": True, "prefill_progress_commit_blocks": 0, + "memory_pressure_park": False, + "max_parks_per_request": 3, + "park_resume_ok_polls": 3, } def test_prefill_progress_commit_blocks_from_dict(self): @@ -428,6 +431,62 @@ def test_prefill_progress_commit_blocks_must_not_be_negative(self, tmp_path): settings.scheduler.prefill_progress_commit_blocks = -1 assert any("prefill_progress_commit_blocks" in e for e in settings.validate()) + def test_park_settings_defaults_and_round_trip(self): + """Park is off by default; valid values round-trip; junk falls back.""" + defaults = SchedulerSettings.from_dict({}) + assert defaults.memory_pressure_park is False + assert defaults.max_parks_per_request == 3 + assert defaults.park_resume_ok_polls == 3 + custom = SchedulerSettings.from_dict( + { + "memory_pressure_park": True, + "max_parks_per_request": 5, + "park_resume_ok_polls": 1, + } + ) + assert custom.memory_pressure_park is True + assert custom.max_parks_per_request == 5 + assert custom.park_resume_ok_polls == 1 + for bad in ("many", None, -1, 0, True): + junk = SchedulerSettings.from_dict( + {"max_parks_per_request": bad, "park_resume_ok_polls": bad} + ) + assert junk.max_parks_per_request == 3 + assert junk.park_resume_ok_polls == 3 + + def test_park_settings_reach_scheduler_config(self, tmp_path): + settings = GlobalSettings(base_path=tmp_path) + config = settings.to_scheduler_config() + assert config.memory_pressure_park is False + assert (config.max_parks_per_request, config.park_resume_ok_polls) == (3, 3) + settings.scheduler.memory_pressure_park = True + settings.scheduler.max_parks_per_request = 2 + settings.scheduler.park_resume_ok_polls = 4 + config = settings.to_scheduler_config() + assert config.memory_pressure_park is True + assert (config.max_parks_per_request, config.park_resume_ok_polls) == (2, 4) + + def test_park_settings_env_override(self, tmp_path): + env = { + "OMLX_MEMORY_PRESSURE_PARK": "true", + "OMLX_MAX_PARKS_PER_REQUEST": "7", + "OMLX_PARK_RESUME_OK_POLLS": "2", + } + with patch.dict(os.environ, env, clear=False): + settings = GlobalSettings.load(base_path=tmp_path) + assert settings.scheduler.memory_pressure_park is True + assert settings.scheduler.max_parks_per_request == 7 + assert settings.scheduler.park_resume_ok_polls == 2 + + def test_park_settings_validation(self, tmp_path): + settings = GlobalSettings(base_path=tmp_path) + assert not any("park" in e for e in settings.validate()) + settings.scheduler.max_parks_per_request = 0 + settings.scheduler.park_resume_ok_polls = 0 + errors = settings.validate() + assert any("max_parks_per_request" in e for e in errors) + assert any("park_resume_ok_polls" in e for e in errors) + def test_decode_fairness_from_dict(self): """Defaults on; explicit false round-trips.""" assert SchedulerSettings.from_dict({}).decode_fairness is True From 21dc1902e5a4f8e7962ba3f22343b92591028bfd Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Thu, 1 Oct 2026 15:42:49 -0600 Subject: [PATCH 09/46] feat(scheduler): park a chunked prefill under memory pressure instead 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. --- docs/TESTING.md | 6 + omlx/cache/paged_ssd_cache.py | 54 +- omlx/engine_core.py | 8 +- omlx/request.py | 6 + omlx/scheduler.py | 296 +++++++++ tests/test_engine_core.py | 25 + tests/test_scheduler_park.py | 585 ++++++++++++++++++ .../test_scheduler_prefill_progress_commit.py | 12 +- 8 files changed, 987 insertions(+), 5 deletions(-) create mode 100644 tests/test_scheduler_park.py diff --git a/docs/TESTING.md b/docs/TESTING.md index aeb9da1a04..7706308202 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -234,3 +234,9 @@ For a real-server comparison, use the same model, prompts and cache state on mai Run `python -m pytest -q tests/test_scheduler_prefill_progress_commit.py tests/test_settings.py -k "prefill_progress or commit"` to check `scheduler.prefill_progress_commit_blocks` (also `OMLX_PREFILL_PROGRESS_COMMIT_BLOCKS`; 0 = off, the default). The cases drive the real chunked and external prefill loops on a small initialized Qwen3.5 hybrid model (inline and split-GDN snapshots) and a small dense model, against real paged-SSD, boundary-snapshot and prefix stores, and compare restored-prefix logits with a cold forward pass. They cover commits every N blocks, a request aborted mid-prefill whose same-prompt re-issue resumes from the last committed boundary, completion after commits (same stored prefix, no duplicate blocks or leftover snapshot markers), a commit window longer than the restored prefix, TurboQuant windows matching whole-prefix conversion bit for bit, the memory-pressure skip, and the cold retry after a prefill memory failure. Mocked tests do not replace hardware validation: with a real model, abort a long prompt mid-prefill (for example with a low memory ceiling and two concurrent prompts), re-issue it, and check that the log reports a prefix cache restore at the last committed boundary instead of a full prefill. + +# Memory-pressure park tests + +Run `python -m pytest -q tests/test_scheduler_park.py tests/test_process_memory_enforcer.py tests/test_settings.py -k "park or Park"` to check `scheduler.memory_pressure_park` (also `OMLX_MEMORY_PRESSURE_PARK`; off by default), `scheduler.max_parks_per_request` (`OMLX_MAX_PARKS_PER_REQUEST`, default 3) and `scheduler.park_resume_ok_polls` (`OMLX_PARK_RESUME_OK_POLLS`, default 3). With the setting on, hard (non-emergency) memory pressure parks the most recent chunked-prefill request instead of aborting: it is re-queued without an error, keeps its stream, and resumes in arrival order after enough consecutive ok pressure polls, restoring the blocks that `prefill_progress_commit_blocks` committed (without it the park resumes cold). The oldest admitted request is protected, parked blocks are pinned against eviction until the resume, and the legacy abort remains for emergency pressure, nothing parkable, an exhausted park budget, or external-loop (non-chunked, VLM) and SpecPrefill prefills, which cannot be parked between steps. The scheduler cases run on a small Qwen3.5 hybrid model and compare a resumed request's output with an uninterrupted run; its prompts must stay below the tiny vocabulary of 32 ids, or the embedding read is undefined and the output is nondeterministic. + +Mocked tests do not replace hardware validation: with a real model, run three concurrent long prompts under a ceiling too low for all of them and check that each completes with the park/resume log lines and a cached count close to the last commit, and that no client sees a memory error. diff --git a/omlx/cache/paged_ssd_cache.py b/omlx/cache/paged_ssd_cache.py index e2d7d1aeb7..7904ad5b64 100644 --- a/omlx/cache/paged_ssd_cache.py +++ b/omlx/cache/paged_ssd_cache.py @@ -30,6 +30,7 @@ import time import uuid from collections import OrderedDict +from collections.abc import Iterable from dataclasses import dataclass from pathlib import Path from typing import Any @@ -1774,6 +1775,11 @@ def __init__( # promoted into the raw-byte hot cache. They still consume the same # shared SSD budget as the two main block indexes. self._gdn_sidecar_index = GDNCheckpointIndex(max_size_bytes) + # Block hashes held by parked requests: size enforcement skips them + # (and their GDN sidecars) so a parked prefix survives until resume. + # Refcounted so overlapping prompts can pin the same block. + self._pinned_hashes: dict[bytes, int] = {} + self._pin_lock = threading.Lock() self._hot_cache_only = hot_cache_only self._expected_model_name = expected_model_name self._expected_num_layers = expected_num_layers @@ -4795,6 +4801,33 @@ def _get_effective_max_size(self) -> int: disk_limit = int(disk_available * self._DISK_SAFE_RATIO) return min(self._max_size, disk_limit) + def pin_blocks(self, block_hashes: Iterable[bytes]) -> None: + """Protect blocks (and their GDN sidecars) from size-based eviction.""" + with self._pin_lock: + for block_hash in block_hashes: + key = bytes(block_hash) + self._pinned_hashes[key] = self._pinned_hashes.get(key, 0) + 1 + + def unpin_blocks(self, block_hashes: Iterable[bytes]) -> None: + """Release one pin per hash taken by :meth:`pin_blocks`.""" + with self._pin_lock: + for block_hash in block_hashes: + key = bytes(block_hash) + remaining = self._pinned_hashes.get(key, 0) - 1 + if remaining > 0: + self._pinned_hashes[key] = remaining + else: + self._pinned_hashes.pop(key, None) + + @property + def pinned_block_count(self) -> int: + with self._pin_lock: + return len(self._pinned_hashes) + + def _pinned_snapshot(self) -> frozenset[bytes]: + with self._pin_lock: + return frozenset(self._pinned_hashes) + def _evict_tracked_until_size( self, target_size: int, @@ -4809,14 +4842,29 @@ def _evict_tracked_until_size( avoiding a second, competing budget for GDN history. """ evicted: list[tuple[Any, Any]] = [] + pinned = self._pinned_snapshot() + # Look past pinned entries so one parked prefix never blocks the walk. + depth = 1 + len(pinned) + + def oldest_unpinned(entries: list[Any], hash_attr: str) -> list[Any]: + for entry in entries: + if getattr(entry, hash_attr) not in pinned: + return [entry] + return [] while self._tracked_ssd_size() > target_size: if max_count is not None and len(evicted) >= max_count: break - compatible = self._index.get_lru_entries(1) - incompatible = self._incompatible_index.get_lru_entries(1) - sidecars = self._gdn_sidecar_index.get_lru_entries(1) + compatible = oldest_unpinned( + self._index.get_lru_entries(depth), "block_hash" + ) + incompatible = oldest_unpinned( + self._incompatible_index.get_lru_entries(depth), "block_hash" + ) + sidecars = oldest_unpinned( + self._gdn_sidecar_index.get_lru_entries(depth), "source_block_hash" + ) candidates: list[tuple[float, int, Any, Any]] = [] if compatible: candidates.append((compatible[0].last_access, 0, self._index, compatible[0])) diff --git a/omlx/engine_core.py b/omlx/engine_core.py index b28919e99f..b42c14c06d 100644 --- a/omlx/engine_core.py +++ b/omlx/engine_core.py @@ -851,10 +851,16 @@ async def abort_all_requests( pending_aborts = set( getattr(sched_for_filter, "_pending_abort_ids", None) or () ) + # A parked request holds no live memory: aborting it for memory + # pressure frees nothing and throws away its committed prefix. An + # explicit reason (unload, shutdown) still aborts everything. + is_parked = getattr(sched_for_filter, "is_request_parked", None) request_ids = [ rid for rid in self._output_collectors - if rid not in self._finished_at and rid not in pending_aborts + if rid not in self._finished_at + and rid not in pending_aborts + and not (reason is None and callable(is_parked) and is_parked(rid) is True) ] ceiling = 0 watermark = 0 diff --git a/omlx/request.py b/omlx/request.py index f61053a99b..02f00e2677 100644 --- a/omlx/request.py +++ b/omlx/request.py @@ -244,6 +244,12 @@ def vlm_extra_key_ranges_for_cache( ) packed_prefill_excluded: bool = False # Retries alone after a failed pack + # Memory-pressure park: a prefilling request paused without an error. It + # keeps its client stream and place in line and resumes from its last + # committed prefix. ``parked`` is True from the park until the resume. + parked: bool = False + park_count: int = 0 # Parks taken so far (bounded by max_parks_per_request) + # Request-scoped tool schemas used by protocol output parsers. tools: list[dict[str, Any]] | None = None diff --git a/omlx/scheduler.py b/omlx/scheduler.py index e597c02eea..bc6a9a7be6 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -1351,6 +1351,21 @@ def _is_turboquant_kv_family_cache(cache_obj: Any) -> bool: PREFILL_COMMIT_FINAL_STORE_WAIT_S = 120.0 +# Enforcer polls after a park during which the scheduler still reports "park +# in progress", so the abort waits for the freed memory to return to the OS. +PARK_SETTLE_POLLS = 3 +# A pressure monitor that has not reported for this long is considered gone; +# parked requests then resume instead of waiting for polls that never come. +PARK_SIGNAL_STALE_S = 60.0 + + +class _ParkPins(NamedTuple): + """Block refs and SSD hashes a parked request holds against eviction.""" + + block_ids: list[int] + hashes: list[bytes] + + def _prefill_commit_blocks(config: Any) -> int: """``prefill_progress_commit_blocks`` of a config, 0 when unset or invalid.""" value = getattr(config, "prefill_progress_commit_blocks", 0) @@ -2261,6 +2276,19 @@ def __init__( # PREFILL_COMMIT_FINAL_STORE_WAIT_S. Added on the store worker (GIL-atomic # set.add), consumed by _drain_pending_async_removes on the scheduler thread. self._skipped_final_stores: set[str] = set() + # Memory-pressure park (see request_park_prefill). The flag and the + # poll counters are written by the enforcer thread (GIL-atomic) and + # consumed on the MLX thread. + self._park_requested: bool = False + self._park_settle_polls: int = 0 + self._ok_polls: int = 0 + self._last_pressure_poll_at: float | None = None + self._park_pins: dict[str, _ParkPins] = {} + self._park_stats: dict[str, int] = { + "parks": 0, + "resumes": 0, + "tokens_preserved": 0, + } self.requests: dict[str, Request] = {} # All requests by ID self.finished_req_ids: set[str] = set() # Recently finished self._generation_overflow_recovery_ids: set[str] = set() @@ -5611,6 +5639,10 @@ def get_active_hot_cache_block_hashes(self) -> set[bytes]: continue if block_hash is not None: hashes.add(bytes(block_hash)) + # Parked requests hold no live table, but their pinned prefix must + # survive a hot-cache shrink too. + for pins in list(self._park_pins.values()): + hashes.update(pins.hashes) return hashes def _clear_memory_admission_blocker(self, request_id: str | None = None) -> None: @@ -5696,6 +5728,11 @@ def _memory_admission_stall_output(self, reason: str) -> RequestOutput | None: request = self.waiting[0] request_id = request.request_id + if request.parked: + # Parked on purpose: it waits as long as pressure lasts; the + # client's own timeouts apply. + self._clear_memory_admission_blocker(request_id) + return None now = time.monotonic() if request_id != self._memory_admission_blocked_request_id: self._memory_admission_blocked_request_id = request_id @@ -5761,6 +5798,9 @@ def _store_cache_admission_stall_output( request = self.waiting[0] request_id = request.request_id + if request.parked: + self._clear_store_cache_admission_blocker(request_id) + return None now = time.monotonic() if request_id != self._store_cache_admission_blocked_request_id: self._store_cache_admission_blocked_request_id = request_id @@ -10654,6 +10694,9 @@ def _retry_prefills_cold_after_oom(self, request: Request) -> bool: otherwise be attached here; a client re-issue still resumes from them. Gated on the setting so the default behavior is unchanged. """ + if getattr(request, "parked", False): + # A parked request resumes from its committed blocks by design. + return False retries = getattr(request, "prefill_oom_retries", 0) return ( isinstance(retries, int) @@ -11798,6 +11841,236 @@ def _cleanup_prefill_abort_request( self._pending_abort_ids.discard(request.request_id) self._do_abort_request(request.request_id) + # ------------------------------------------------------------------ + # Memory-pressure park: pause a prefilling request instead of aborting. + # ------------------------------------------------------------------ + + def _park_enabled(self) -> bool: + return getattr(self.config, "memory_pressure_park", False) is True + + def note_pressure_poll(self, level: str) -> None: + """Record one enforcer poll (thread-safe; counters only). + + Parked requests resume after ``park_resume_ok_polls`` consecutive + ``ok`` polls (hysteresis against flapping at the watermark). + """ + self._last_pressure_poll_at = time.monotonic() + if level == "ok": + self._ok_polls += 1 + self._park_settle_polls = 0 + else: + self._ok_polls = 0 + + def _park_resume_allowed(self) -> bool: + """True once enough consecutive ok polls were seen (or no monitor runs).""" + seen = self._last_pressure_poll_at + if seen is None or time.monotonic() - seen > PARK_SIGNAL_STALE_S: + return True # no live pressure monitor: never starve a parked request + need = getattr(self.config, "park_resume_ok_polls", 3) + return self._ok_polls >= max(1, need) + + def is_request_parked(self, request_id: str) -> bool: + """Whether the request is currently parked (holds no live memory).""" + request = self.requests.get(request_id) + return bool(request is not None and request.parked) + + def get_park_stats(self) -> dict[str, int]: + """Counters for the diagnostics/admin stats.""" + stats = dict(self._park_stats) + stats["parked_now"] = sum(1 for r in list(self.waiting) if r.parked) + stats["pinned_requests"] = len(self._park_pins) + return stats + + def _parkable_prefills(self) -> list[Request]: + """Chunked prefills that can be parked safely. + + Only requests in the chunked-prefill loop qualify: their state lives + between steps. External-loop prefills (non-chunked, VLM) run to + completion inside one ``_schedule_waiting`` call and are never + between steps; VLM embeds and SpecPrefill patch model-wide state, so + they are excluded as well. + """ + budget = getattr(self.config, "max_parks_per_request", 3) + return [ + request + for request in list(self.prefilling) + if request.request_id in self._prefill_states + and request.park_count < budget + and request.specprefill_indices is None + and request.vlm_inputs_embeds is None + ] + + def _select_park_victim(self) -> Request | None: + """Most recent arrival first; the oldest admitted request is protected. + + The oldest request among everything admitted (prefilling or decoding) + is skipped while any other prefill is parkable. It is only parked + when it is the sole candidate, which still helps when the pressure + comes from outside this process. + """ + candidates = self._parkable_prefills() + if not candidates: + return None + admitted = list(self.prefilling) + list(self.running.values()) + oldest = min(admitted, key=lambda r: (r.arrival_time, r.request_id)) + candidates.sort(key=lambda r: (r.arrival_time, r.request_id), reverse=True) + for request in candidates: + if request.request_id != oldest.request_id: + return request + return candidates[0] + + def request_park_prefill(self) -> bool: + """Ask for a prefill victim to be parked (thread-safe, flag only). + + Called by ProcessMemoryEnforcer on the asyncio thread at hard + pressure. Returns True when a victim is parkable, a park is pending, + or one just ran and its memory is still returning; the enforcer then + defers its abort. False (park disabled, nothing parkable, budget + spent) leaves the legacy abort in place. + """ + if not self._park_enabled(): + return False + if self._park_requested: + return True + try: + victim = self._select_park_victim() + except RuntimeError: # queue mutated mid-read on the MLX thread + victim = True + if victim is not None: + self._park_requested = True + return True + if self._park_settle_polls > 0: + self._park_settle_polls -= 1 + return True + return False + + def _process_pending_park(self) -> bool: + """Park one victim if the enforcer asked (MLX thread, step start).""" + if not self._park_requested: + return False + self._park_requested = False + if not self._park_enabled(): + return False + victim = self._select_park_victim() + if victim is None: + return False + self._park_prefill(victim, reason="hard memory pressure") + self._park_settle_polls = PARK_SETTLE_POLLS + return True + + def _park_prefill(self, request: Request, reason: str) -> None: + """Pause a chunked prefill without an error and without blocking. + + The request keeps its client stream, prompt, sampling params and + arrival time. Its live cache is dropped; blocks an incremental commit + stored stay in the prefix cache, pinned against eviction, and the + re-admission does a fresh prefix lookup that restores them. Teardown + steps run behind any in-flight commit through ``_after_commit``. + """ + rid = request.request_id + table = ( + self.paged_cache_manager.get_block_table(rid) + if self.paged_cache_manager is not None + else None + ) + committed = table.num_tokens if table else 0 + self._prefill_states.pop(rid, None) + self.prefilling = deque(r for r in self.prefilling if r.request_id != rid) + self._reset_request_for_reprefill(request) + request.parked = True + request.park_count += 1 + self._clear_request_admission_bookkeeping(rid) + get_prefill_tracker().remove(rid) + # Order matters: pin first, then release the table's own refs. + self._after_commit(rid, lambda: self._pin_parked_blocks(rid)) + self._release_paged_cache_for_request(rid) + self._drop_boundary_snapshots_for_request(rid) + self._enqueue_parked(request) + self._ok_polls = 0 + self._park_stats["parks"] += 1 + Scheduler._clear_cache(self) + budget = getattr(self.config, "max_parks_per_request", 3) + logger.info( + "Parked request %s at %d tokens committed (park %d/%d), reason: %s%s", + rid, + committed, + request.park_count, + budget, + reason, + ( + "" + if _prefill_commit_blocks(self.config) > 0 + else " (prefill_progress_commit_blocks is off: it will resume cold)" + ), + ) + + def _enqueue_parked(self, request: Request) -> None: + """Queue a parked request in arrival order, ahead of unparked ones.""" + key = (request.arrival_time, request.request_id) + index = 0 + for queued in self.waiting: + if queued.parked and (queued.arrival_time, queued.request_id) <= key: + index += 1 + else: + break + self.waiting.insert(index, request) + + def _pin_parked_blocks(self, request_id: str) -> None: + """Hold the committed blocks of a parked request against eviction. + + Takes one extra block ref per committed block (so the table's own + release leaves them referenced) and pins their hashes in the SSD + index, whose size enforcement skips them. Skipped when the request + was aborted or already resumed before this deferred step ran. + """ + request = self.requests.get(request_id) + manager = self.paged_cache_manager + if request is None or not request.parked or manager is None: + return + table = manager.get_block_table(request_id) + if not table or not table.block_ids: + return + self._unpin_parked(request_id) + block_ids: list[int] = [] + hashes: list[bytes] = [] + for block_id in table.block_ids: + if not manager.increment_ref(block_id): + continue + block_ids.append(block_id) + block = manager.allocated_blocks.get(block_id) + block_hash = getattr(block, "block_hash", None) + if block_hash is not None: + hashes.append(bytes(block_hash)) + if not block_ids: + return + self._park_pins[request_id] = _ParkPins(block_ids, hashes) + ssd = self.paged_ssd_cache_manager + if ssd is not None and hasattr(ssd, "pin_blocks"): + ssd.pin_blocks(hashes) + + def _unpin_parked(self, request_id: str) -> None: + pins = self._park_pins.pop(request_id, None) + if pins is None: + return + if self.paged_cache_manager is not None: + self.paged_cache_manager.release_for_eviction(pins.block_ids) + ssd = self.paged_ssd_cache_manager + if ssd is not None and hasattr(ssd, "unpin_blocks"): + ssd.unpin_blocks(pins.hashes) + + def _finish_park_resume(self, request: Request) -> None: + """Re-admission of a parked request: its fresh lookup holds the blocks.""" + self._unpin_parked(request.request_id) + request.parked = False + self._park_settle_polls = 0 + self._park_stats["resumes"] += 1 + self._park_stats["tokens_preserved"] += request.cached_tokens or 0 + logger.info( + "Resumed parked request %s: cached=%d", + request.request_id, + request.cached_tokens or 0, + ) + def request_idle_reclaim(self) -> None: """Enqueue a between-turn Metal reclaim (thread-safe, no Metal touch). @@ -11909,6 +12182,7 @@ def _do_abort_request(self, request_id: str) -> bool: return False self._clear_request_admission_bookkeeping(request_id) + self._unpin_parked(request_id) # Remove from waiting queue if request.status == RequestStatus.WAITING: @@ -12040,6 +12314,7 @@ def has_requests(self) -> bool: or self._deferred_clear_at is not None or self._pending_reclaim_request or self._pending_pressure_clear + or self._park_requested ) def has_pending_route_preflight_cleanup(self) -> bool: @@ -12752,6 +13027,12 @@ def _schedule_waiting_scan( # crosses soft_threshold. New prefills wait; in-flight requests # continue. First request always passes (no admitted work yet) # so admission can recover by completing the current generation. + # Parked requests sit at the front in arrival order and resume + # only after enough consecutive ok pressure polls; nothing newer + # overtakes them while they wait. + if self.waiting[0].parked and not self._park_resume_allowed(): + break + admitted = self._num_admitted_requests() if self._admission_paused and admitted: logger.debug( @@ -12884,6 +13165,8 @@ def _schedule_waiting_scan( # #2183/#2197 chunk-view and #2235 batch-KV-mutation fixes. with mx.stream(self._stream): self._prepare_prefix_cache_for_request(request) + if request.parked: + self._finish_park_resume(request) # Determine tokens to process and cache to use # Note: Don't use `remaining_tokens or prompt_token_ids` because empty list @@ -14899,6 +15182,11 @@ def step(self) -> SchedulerOutput: if drained_async_removes: output.has_work = True + # Park a prefill victim requested by the memory enforcer. Runs before + # any chunk so a parked request never has a forward in flight. + if self._process_pending_park(): + output.has_work = True + # Check memory pressure and evict if needed (tiered cache) if self.memory_monitor is not None: self._check_memory_pressure() @@ -15204,6 +15492,8 @@ def get_stats(self) -> dict[str, Any]: # Include cache stats if self.block_aware_cache is not None: stats["ssd_cache"] = self.block_aware_cache.get_stats() + if getattr(self.config, "memory_pressure_park", False) is True: + stats["park"] = self.get_park_stats() return stats def get_cache_stats(self) -> dict[str, Any] | None: @@ -15276,6 +15566,10 @@ def reset(self) -> None: self._deferred_teardown_since.clear() self._stuck_teardown_logged.clear() self._skipped_final_stores.clear() + for parked_id in list(self._park_pins): + self._unpin_parked(parked_id) + self._park_requested = False + self._park_settle_polls = 0 self._prefill_commits.clear() self._cache_freshness_waits.clear() self._prefix_cache_prepared.clear() @@ -15429,6 +15723,8 @@ def shutdown(self) -> None: # no step-thread caller to wake here. Inflight futures are drained # below before the executor is asked to shut down. commit_store_busy = self._shutdown_prefill_commits() + for parked_id in list(self._park_pins): + self._unpin_parked(parked_id) # Wait for any inflight async store_cache futures + drain pending # batch_generator removes so the writer thread / underlying paged SSD # cache see all blocks before close(). diff --git a/tests/test_engine_core.py b/tests/test_engine_core.py index f5f2b1165f..60df9862f6 100644 --- a/tests/test_engine_core.py +++ b/tests/test_engine_core.py @@ -1280,6 +1280,31 @@ async def test_abort_all_requests_skips_requests_already_aborted( await engine.stop() engine.close() + @pytest.mark.asyncio + async def test_abort_all_requests_leaves_parked_requests_alone( + self, mock_model, mock_tokenizer + ): + """A parked request holds no memory; a pressure abort must keep it.""" + with patch("omlx.engine_core.get_registry") as mock_registry: + mock_registry.return_value.acquire.return_value = True + engine = EngineCore(model=mock_model, tokenizer=mock_tokenizer) + try: + await engine.start() + engine.scheduler.has_requests = lambda: False + parked_id = await engine.add_request(prompt="Hello") + live_id = await engine.add_request(prompt="World") + engine.scheduler.requests[parked_id].parked = True + + assert await engine.abort_all_requests() == 1 + assert engine._output_collectors[parked_id].get_nowait() is None + assert engine._output_collectors[live_id].get_nowait().finished + + # An explicit reason (manual unload, shutdown) aborts it too. + assert await engine.abort_all_requests(reason="unloading") == 1 + finally: + await engine.stop() + engine.close() + @pytest.mark.asyncio async def test_abort_all_requests_uses_explicit_unload_reason( self, mock_model, mock_tokenizer diff --git a/tests/test_scheduler_park.py b/tests/test_scheduler_park.py new file mode 100644 index 0000000000..763cc76599 --- /dev/null +++ b/tests/test_scheduler_park.py @@ -0,0 +1,585 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Park-instead-of-abort for chunked prefill under memory pressure. + +The tests drive the real scheduler step loop on a small initialized Qwen3.5 +hybrid model against real paged-SSD, boundary-snapshot and prefix stores. A +parked request keeps its client stream and its place in line, drops its live +cache, and resumes from the blocks an incremental commit stored. +""" + +import time +from types import SimpleNamespace + +import test_scheduler_prefill_progress_commit as commit_rig +from test_scheduler_prefill_progress_commit import BLOCK, _returns_promptly, _Rig + +from omlx.request import Request, RequestStatus, SamplingParams + +# Controllable commit worker fixture shared with the incremental-commit suite. +gated = commit_rig.gated + + +def _prompt(seed): + """24 tokens (23 prefill tokens: five full blocks plus a tail). + + Token ids stay below the tiny model's vocabulary of 32; an out-of-range id + reads undefined embedding memory and makes the output nondeterministic. + """ + return [3 + (seed * 5 + i * 7) % 28 for i in range(24)] + + +PROMPT_A = _prompt(1) +PROMPT_B = _prompt(2) +PROMPT_C = _prompt(3) +PROMPT_D = _prompt(4) + + +def make_rig(tmp_path, tokenizer, *, park=True, max_parks=3, ok_polls=3, commit=1): + rig = _Rig( + tmp_path, + tokenizer, + split=False, + commit_blocks=commit, + memory_pressure_park=park, + max_parks_per_request=max_parks, + park_resume_ok_polls=ok_polls, + ) + # The pressure monitor is "live": the hold gate waits for ok polls. + rig.scheduler.note_pressure_poll("soft") + return rig + + +def submit(rig, request_id, tokens, arrival, max_tokens=3): + request = Request( + request_id=request_id, + prompt=list(tokens), + sampling_params=SamplingParams(max_tokens=max_tokens, temperature=0), + arrival_time=arrival, + ) + rig.scheduler.add_request(request) + return request + + +def step(rig, n=1): + """Step the scheduler, settling commit workers so cadence is deterministic.""" + outputs = [] + for _ in range(n): + result = rig.scheduler.step() + outputs.extend(result.outputs) + rig.drain() + return outputs + + +def prefilling_ids(rig): + return [r.request_id for r in rig.scheduler.prefilling] + + +def waiting_ids(rig): + return [r.request_id for r in rig.scheduler.waiting] + + +def step_until(rig, predicate, limit=60): + outputs = [] + for _ in range(limit): + if predicate(): + return outputs + outputs.extend(step(rig)) + raise AssertionError("condition not reached") + + +def prefill_two(rig): + """Old (A) and young (B) both mid-prefill with committed blocks.""" + old = submit(rig, "old", PROMPT_A, arrival=1.0) + young = submit(rig, "young", PROMPT_B, arrival=2.0) + step_until( + rig, + lambda: set(prefilling_ids(rig)) == {"old", "young"} + and rig.table_tokens("young") >= BLOCK, + ) + return old, young + + +def run_to_completion(rig, requests, limit=200): + outputs = [] + for _ in range(limit): + if all( + r.is_finished() or r.request_id not in rig.scheduler.requests + for r in requests + ): + break + outputs.extend(step(rig)) + for future in list(rig.scheduler._inflight_store_futures.values()): + future.result(timeout=30) + rig.scheduler._drain_pending_async_removes() + return outputs + + +def finish_ok_polls(rig, n): + for _ in range(n): + rig.scheduler.note_pressure_poll("ok") + + +# --- Request side of the enforcer contract ---------------------------------- + + +def test_park_disabled_never_accepts_a_park_request(tmp_path, mock_tokenizer): + rig = make_rig(tmp_path, mock_tokenizer, park=False) + try: + prefill_two(rig) + assert rig.scheduler.request_park_prefill() is False + step(rig) + assert set(prefilling_ids(rig)) == {"old", "young"} + finally: + rig.close() + + +def test_nothing_parkable_is_reported_so_the_enforcer_aborts(tmp_path, mock_tokenizer): + rig = make_rig(tmp_path, mock_tokenizer) + try: + assert rig.scheduler.request_park_prefill() is False # nothing admitted + request = submit(rig, "only", PROMPT_A, arrival=1.0) + # Still waiting (not prefilling): not parkable. + assert rig.scheduler.request_park_prefill() is False + assert not request.parked + finally: + rig.close() + + +def test_a_request_that_cannot_be_parked_safely_is_not_a_victim( + tmp_path, mock_tokenizer +): + """VLM and SpecPrefill prefills run outside the chunked loop or patch the + whole model; they are never victims.""" + rig = make_rig(tmp_path, mock_tokenizer) + try: + old, young = prefill_two(rig) + young.vlm_inputs_embeds = object() + old.specprefill_indices = [0] + assert rig.scheduler.request_park_prefill() is False + finally: + rig.close() + + +# --- Victim policy ------------------------------------------------------------ + + +def test_hard_pressure_parks_the_youngest_prefill_without_an_error( + tmp_path, mock_tokenizer +): + rig = make_rig(tmp_path, mock_tokenizer) + try: + old, young = prefill_two(rig) + scheduler = rig.scheduler + assert scheduler.request_park_prefill() is True + outputs = step(rig) + + assert not [o for o in outputs if o.finished or o.error] + assert prefilling_ids(rig) == ["old"] # the oldest keeps running + assert waiting_ids(rig) == ["young"] + assert young.parked and young.park_count == 1 + assert young.status == RequestStatus.WAITING + assert "young" in scheduler.requests # the client stream stays open + assert "young" not in scheduler._prefill_states + assert young.prompt_cache is None + assert young.arrival_time == 2.0 + assert young.prompt_token_ids == PROMPT_B + finally: + rig.close() + + +def test_the_oldest_is_protected_while_a_younger_prefill_is_parkable( + tmp_path, mock_tokenizer +): + rig = make_rig(tmp_path, mock_tokenizer) + try: + prefill_two(rig) + rig.scheduler.request_park_prefill() + step(rig) + # The younger one was parked; the oldest keeps prefilling. + assert waiting_ids(rig) == ["young"] + assert rig.scheduler.requests["old"].park_count == 0 + finally: + rig.close() + + +def test_a_sole_prefill_is_parkable_when_pressure_comes_from_elsewhere( + tmp_path, mock_tokenizer +): + rig = make_rig(tmp_path, mock_tokenizer) + try: + only = submit(rig, "only", PROMPT_A, arrival=1.0) + step_until(rig, lambda: prefilling_ids(rig) == ["only"]) + assert rig.scheduler.request_park_prefill() is True + step(rig) + assert only.parked and waiting_ids(rig) == ["only"] + finally: + rig.close() + + +def test_one_victim_is_parked_per_step_and_per_request(tmp_path, mock_tokenizer): + rig = make_rig(tmp_path, mock_tokenizer) + try: + submit(rig, "r1", PROMPT_A, arrival=1.0) + submit(rig, "r2", PROMPT_B, arrival=2.0) + submit(rig, "r3", PROMPT_C, arrival=3.0) + step_until(rig, lambda: len(prefilling_ids(rig)) == 3) + rig.scheduler.request_park_prefill() + step(rig) + assert waiting_ids(rig) == ["r3"] # one victim only + assert set(prefilling_ids(rig)) == {"r1", "r2"} + finally: + rig.close() + + +def test_parked_requests_resume_in_arrival_order_ahead_of_newer_ones( + tmp_path, mock_tokenizer +): + rig = make_rig(tmp_path, mock_tokenizer) + try: + submit(rig, "r1", PROMPT_A, arrival=1.0) + submit(rig, "r2", PROMPT_B, arrival=2.0) + submit(rig, "r3", PROMPT_C, arrival=3.0) + step_until(rig, lambda: len(prefilling_ids(rig)) == 3) + # A newer, never-admitted request is already queued. + submit(rig, "r4", PROMPT_D, arrival=4.0) + rig.scheduler.request_park_prefill() + step(rig) # parks r3 + rig.scheduler.request_park_prefill() + step(rig) # parks r2 (r1 protected) + assert waiting_ids(rig) == ["r2", "r3", "r4"] + finally: + rig.close() + + +# --- Hold gate ---------------------------------------------------------------- + + +def test_no_resume_before_the_required_consecutive_ok_polls(tmp_path, mock_tokenizer): + rig = make_rig(tmp_path, mock_tokenizer, ok_polls=3) + try: + old, young = prefill_two(rig) + rig.scheduler.request_park_prefill() + step(rig) + assert waiting_ids(rig) == ["young"] + + finish_ok_polls(rig, 2) + step(rig, 3) + assert waiting_ids(rig) == ["young"] # two ok polls are not enough + + rig.scheduler.note_pressure_poll("soft") # the streak is broken + finish_ok_polls(rig, 2) + step(rig, 3) + assert waiting_ids(rig) == ["young"] + + finish_ok_polls(rig, 1) # third consecutive ok poll + step_until( + rig, lambda: "young" in prefilling_ids(rig) or young.output_token_ids + ) + assert not young.parked + finally: + rig.close() + + +def test_new_requests_do_not_overtake_a_parked_one(tmp_path, mock_tokenizer): + rig = make_rig(tmp_path, mock_tokenizer) + try: + prefill_two(rig) + rig.scheduler.request_park_prefill() + step(rig) + submit(rig, "newer", PROMPT_C, arrival=9.0) + step(rig, 4) + assert waiting_ids(rig) == ["young", "newer"] + assert "newer" not in prefilling_ids(rig) + finally: + rig.close() + + +def test_parked_request_is_exempt_from_the_admission_stall_timeout( + tmp_path, mock_tokenizer +): + rig = make_rig(tmp_path, mock_tokenizer) + try: + scheduler = rig.scheduler + scheduler._MEMORY_ADMISSION_STALL_TIMEOUT_S = 0.0 + scheduler._STORE_CACHE_ADMISSION_STALL_TIMEOUT_S = 0.0 + old, young = prefill_two(rig) + scheduler.request_park_prefill() + step(rig) + scheduler._admission_paused = True + for _ in range(3): + assert scheduler._memory_admission_stall_output("admission_paused") is None + time.sleep(0.01) + outputs = step(rig, 5) + assert not [o for o in outputs if o.error] + assert waiting_ids(rig) == ["young"] + assert "young" in scheduler.requests + finally: + rig.close() + + +def test_the_resume_signal_is_not_awaited_when_no_monitor_reports( + tmp_path, mock_tokenizer +): + """Without an enforcer (no poll ever seen) a parked request is not starved.""" + rig = _Rig( + tmp_path, + mock_tokenizer, + split=False, + commit_blocks=1, + memory_pressure_park=True, + ) + try: + assert rig.scheduler._park_resume_allowed() is True + rig.scheduler.note_pressure_poll("hard") + assert rig.scheduler._park_resume_allowed() is False + finally: + rig.close() + + +# --- Resume ------------------------------------------------------------------ + + +def uninterrupted_output(tmp_path, tokenizer): + rig = make_rig(tmp_path / "baseline", tokenizer, park=False) + try: + request = submit(rig, "young", PROMPT_B, arrival=2.0) + run_to_completion(rig, [request]) + return list(request.output_token_ids) + finally: + rig.close() + + +def test_resume_restores_the_committed_boundary_and_matches_an_uninterrupted_run( + tmp_path, mock_tokenizer, caplog +): + import logging + + expected = uninterrupted_output(tmp_path, mock_tokenizer) + assert expected + + rig = make_rig(tmp_path / "park", mock_tokenizer) + try: + old, young = prefill_two(rig) + scheduler = rig.scheduler + with caplog.at_level(logging.INFO, logger="omlx.scheduler"): + scheduler.request_park_prefill() + step(rig) + rig.drain() + committed = rig.probe(PROMPT_B)[0].num_tokens + assert committed >= BLOCK + assert any( + "Parked request young" in r.getMessage() + and "park 1/3" in r.getMessage() + for r in caplog.records + ) + + finish_ok_polls(rig, 3) + step_until(rig, lambda: "young" in prefilling_ids(rig)) + assert young.cached_tokens == committed + assert any( + f"Resumed parked request young: cached={committed}" in r.getMessage() + for r in caplog.records + ) + outputs = run_to_completion(rig, [old, young]) + assert not [o for o in outputs if o.error] + assert list(young.output_token_ids) == expected + assert young.park_count == 1 and not young.parked + stats = scheduler.get_park_stats() + assert stats["parks"] == 1 and stats["resumes"] == 1 + finally: + rig.close() + + +def test_the_cold_retry_guard_is_bypassed_for_a_parked_request( + tmp_path, mock_tokenizer +): + rig = make_rig(tmp_path, mock_tokenizer) + try: + old, young = prefill_two(rig) + young.prefill_oom_retries = 1 # an earlier internal SDPA-OOM requeue + assert rig.scheduler._retry_prefills_cold_after_oom(young) is True + young.parked = True + assert rig.scheduler._retry_prefills_cold_after_oom(young) is False + finally: + rig.close() + + +def test_park_budget_exhaustion_falls_back_to_the_abort(tmp_path, mock_tokenizer): + rig = make_rig(tmp_path, mock_tokenizer, max_parks=1, ok_polls=1) + try: + only = submit(rig, "only", PROMPT_A, arrival=1.0) + step_until(rig, lambda: prefilling_ids(rig) == ["only"]) + assert rig.scheduler.request_park_prefill() is True + step(rig) + finish_ok_polls(rig, 1) + step_until(rig, lambda: "only" in prefilling_ids(rig)) + assert only.park_count == 1 + # The one allowed park is spent: the enforcer is told to abort. + assert rig.scheduler.request_park_prefill() is False + finally: + rig.close() + + +def test_settling_after_a_park_defers_the_abort_for_a_few_polls( + tmp_path, mock_tokenizer +): + rig = make_rig(tmp_path, mock_tokenizer, max_parks=1) + try: + submit(rig, "only", PROMPT_A, arrival=1.0) + step_until(rig, lambda: prefilling_ids(rig) == ["only"]) + rig.scheduler.request_park_prefill() + step(rig) + # Memory is returning to the OS; the enforcer must not abort yet. + answers = [rig.scheduler.request_park_prefill() for _ in range(6)] + assert answers[0] is True + assert answers[-1] is False + finally: + rig.close() + + +# --- Eviction safety (pinning) -------------------------------------------------- + + +def test_committed_blocks_are_pinned_while_parked_and_released_after_resume( + tmp_path, mock_tokenizer +): + rig = make_rig(tmp_path, mock_tokenizer, ok_polls=1) + try: + old, young = prefill_two(rig) + scheduler = rig.scheduler + scheduler.request_park_prefill() + step(rig) + rig.drain() + + pins = scheduler._park_pins["young"] + assert pins.block_ids and pins.hashes + assert rig.ssd.pinned_block_count == len(pins.hashes) + for block_id in pins.block_ids: + assert rig.paged.allocated_blocks[block_id].ref_count >= 1 + + # Even an unbounded size enforcement keeps the parked prefix on disk. + rig.ssd._evict_tracked_until_size(0) + table, remaining = rig.probe(PROMPT_B) + assert table is not None and table.num_tokens >= BLOCK + assert scheduler.get_active_hot_cache_block_hashes() >= set(pins.hashes) + + finish_ok_polls(rig, 1) + step_until(rig, lambda: "young" in prefilling_ids(rig)) + assert "young" not in scheduler._park_pins + assert rig.ssd.pinned_block_count == 0 + finally: + rig.close() + + +def test_pins_are_released_when_a_parked_request_is_aborted(tmp_path, mock_tokenizer): + rig = make_rig(tmp_path, mock_tokenizer) + try: + prefill_two(rig) + scheduler = rig.scheduler + scheduler.request_park_prefill() + step(rig) + rig.drain() + assert "young" in scheduler._park_pins + + assert scheduler.abort_request("young") + step(rig, 2) + assert "young" not in scheduler._park_pins + assert rig.ssd.pinned_block_count == 0 + assert "young" not in scheduler.requests + assert "young" not in waiting_ids(rig) + finally: + rig.close() + + +def test_pinned_blocks_are_not_evicted_from_the_ssd_index_by_lru( + tmp_path, mock_tokenizer +): + rig = make_rig(tmp_path, mock_tokenizer) + try: + old, young = prefill_two(rig) + rig.drain() + table, _ = rig.probe(PROMPT_B) + assert table is not None + hashes = [ + bytes(rig.paged.allocated_blocks[b].block_hash) for b in table.block_ids + ] + rig.ssd.pin_blocks(hashes) + rig.ssd._evict_tracked_until_size(0) + for block_hash in hashes: + assert rig.ssd._index.get(block_hash) is not None + rig.ssd.unpin_blocks(hashes) + rig.ssd._evict_tracked_until_size(0) + assert all(rig.ssd._index.get(h) is None for h in hashes) + assert rig.ssd.pinned_block_count == 0 + finally: + rig.close() + + +# --- Teardown never blocks the MLX thread ------------------------------------------ + + +def test_park_with_a_commit_in_flight_defers_the_teardown_without_blocking( + tmp_path, mock_tokenizer, gated +): + rig = make_rig(tmp_path, mock_tokenizer, ok_polls=1) + gate = None + try: + scheduler = rig.scheduler + old, young = prefill_two(rig) # commits ran before the gate was armed + gate = gated(rig) + # Run until the young request has a commit that cannot finish. + for _ in range(8): + if "young" in scheduler._prefill_commits: + break + scheduler.step() + assert "young" in scheduler._prefill_commits + assert not scheduler._prefill_commits["young"][0].done() + scheduler.request_park_prefill() + + assert _returns_promptly(scheduler._process_pending_park) + assert young.parked and waiting_ids(rig)[0] == "young" + assert scheduler._teardown_pending("young") # waits behind the commit + + # A held head is set aside; it is not admitted while its teardown pends. + finish_ok_polls(rig, 1) + scheduler.step() + assert "young" not in prefilling_ids(rig) + + gate.release.set() + rig.drain() + assert not scheduler._teardown_pending("young") + assert "young" in scheduler._park_pins + finally: + if gate is not None: + gate.release.set() + rig.close() + + +def test_reset_and_shutdown_release_every_pin(tmp_path, mock_tokenizer): + rig = make_rig(tmp_path, mock_tokenizer) + try: + prefill_two(rig) + rig.scheduler.request_park_prefill() + step(rig) + rig.drain() + assert rig.ssd.pinned_block_count > 0 + rig.scheduler.reset() + assert not rig.scheduler._park_pins + assert rig.ssd.pinned_block_count == 0 + finally: + rig.close() + + +# --- Engine bulk abort ------------------------------------------------------------- + + +def test_is_request_parked_reads_the_request_flag(): + """EngineCore.abort_all_requests uses it to spare parked requests.""" + from omlx.scheduler import Scheduler + + scheduler = SimpleNamespace( + requests={"p": SimpleNamespace(parked=True), "l": SimpleNamespace(parked=False)} + ) + assert Scheduler.is_request_parked(scheduler, "p") is True + assert Scheduler.is_request_parked(scheduler, "l") is False + assert Scheduler.is_request_parked(scheduler, "missing") is False diff --git a/tests/test_scheduler_prefill_progress_commit.py b/tests/test_scheduler_prefill_progress_commit.py index 2bf88a5dc6..5c23e10592 100644 --- a/tests/test_scheduler_prefill_progress_commit.py +++ b/tests/test_scheduler_prefill_progress_commit.py @@ -52,7 +52,16 @@ def _tiny_hybrid_model(): class _Rig: """A scheduler wired to real stores, plus helpers to drive prefill.""" - def __init__(self, tmp_path, tokenizer, *, split, commit_blocks, tq_bits=None): + def __init__( + self, + tmp_path, + tokenizer, + *, + split, + commit_blocks, + tq_bits=None, + **config_overrides, + ): mx.random.seed(11) self.model = _tiny_hybrid_model() self.scheduler = Scheduler( @@ -64,6 +73,7 @@ def __init__(self, tmp_path, tokenizer, *, split, commit_blocks, tq_bits=None): chunked_prefill=True, prefill_step_size=BLOCK, prefill_progress_commit_blocks=commit_blocks, + **config_overrides, ), ) self.paged = PagedCacheManager( From 3c459e2ddc6202eb55979631a0c1e63ea8d0d709 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Thu, 1 Oct 2026 15:48:38 -0600 Subject: [PATCH 10/46] fix(engine): spare parked requests only when the caller keeps the model 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. --- omlx/engine/batched.py | 2 + omlx/engine/vlm.py | 2 + omlx/engine_core.py | 18 ++++- omlx/process_memory_enforcer.py | 35 +++++++- tests/test_engine_core.py | 41 ++++++++-- tests/test_process_memory_enforcer.py | 112 ++++++++++++++++++++++++++ 6 files changed, 198 insertions(+), 12 deletions(-) diff --git a/omlx/engine/batched.py b/omlx/engine/batched.py index 4ca34435a1..aaef48d678 100644 --- a/omlx/engine/batched.py +++ b/omlx/engine/batched.py @@ -1578,11 +1578,13 @@ async def abort_all_requests( *, reason: str | None = None, error_code: str | None = None, + spare_parked: bool = False, ) -> int: """Abort all active requests without stopping the engine.""" if self._engine and self._engine.engine: return await self._engine.engine.abort_all_requests( reason=reason, error_code=error_code, + spare_parked=spare_parked, ) return 0 diff --git a/omlx/engine/vlm.py b/omlx/engine/vlm.py index c537e4df2d..0c1d3e84ad 100644 --- a/omlx/engine/vlm.py +++ b/omlx/engine/vlm.py @@ -6024,6 +6024,7 @@ async def abort_all_requests( *, reason: str | None = None, error_code: str | None = None, + spare_parked: bool = False, ) -> int: """Abort all active requests.""" if self.is_diffusion_model: @@ -6035,5 +6036,6 @@ async def abort_all_requests( return await self._engine.engine.abort_all_requests( reason=reason, error_code=error_code, + spare_parked=spare_parked, ) return 0 diff --git a/omlx/engine_core.py b/omlx/engine_core.py index b42c14c06d..ff18d94479 100644 --- a/omlx/engine_core.py +++ b/omlx/engine_core.py @@ -827,6 +827,7 @@ async def abort_all_requests( *, reason: str | None = None, error_code: str | None = None, + spare_parked: bool = False, ) -> int: """Abort all active requests without stopping the engine. @@ -834,6 +835,12 @@ async def abort_all_requests( for deferred abort in the scheduler. Cleanup is handled by the consumer (stream_outputs/generate). Without an explicit reason, preserve the memory-pressure error used by the process enforcer. + + Parked requests (memory-pressure park) are aborted too unless the + caller passes ``spare_parked=True``. Only a caller that keeps the + model loaded and lets the scheduler resume them may spare them; + every unload, eviction, emergency or shutdown path must abort them, + or they are orphaned (or block the unload from ever draining). """ from .utils.proc_memory import get_phys_footprint @@ -852,15 +859,15 @@ async def abort_all_requests( getattr(sched_for_filter, "_pending_abort_ids", None) or () ) # A parked request holds no live memory: aborting it for memory - # pressure frees nothing and throws away its committed prefix. An - # explicit reason (unload, shutdown) still aborts everything. + # pressure frees nothing and throws away its committed prefix. Only + # an explicit ``spare_parked`` keeps it (keep-loaded hard path). is_parked = getattr(sched_for_filter, "is_request_parked", None) request_ids = [ rid for rid in self._output_collectors if rid not in self._finished_at and rid not in pending_aborts - and not (reason is None and callable(is_parked) and is_parked(rid) is True) + and not (spare_parked and callable(is_parked) and is_parked(rid) is True) ] ceiling = 0 watermark = 0 @@ -1480,12 +1487,15 @@ async def abort_all_requests( *, reason: str | None = None, error_code: str | None = None, + spare_parked: bool = False, ) -> int: """Abort all active requests without stopping the engine.""" engine = getattr(self, "engine", None) if engine is None: return 0 - return await engine.abort_all_requests(reason=reason, error_code=error_code) + return await engine.abort_all_requests( + reason=reason, error_code=error_code, spare_parked=spare_parked + ) async def stream_outputs( self, diff --git a/omlx/process_memory_enforcer.py b/omlx/process_memory_enforcer.py index b0e9448d21..32ecf83c61 100644 --- a/omlx/process_memory_enforcer.py +++ b/omlx/process_memory_enforcer.py @@ -1571,6 +1571,21 @@ def _walk_store_cache_caps(self) -> None: if adjust is not None: adjust(self._pressure_level) + @staticmethod + async def _abort_all_requests(engine: Any, *, spare_parked: bool) -> Any: + """Call ``abort_all_requests``, passing ``spare_parked`` explicitly. + + Engines without parking (DFlash, distributed) have a no-argument hook + and cannot hold parked requests, so the keyword is dropped for them. + A model held by parked requests only is NOT idle (they own a collector, + so ``has_active_requests`` is true): LRU eviction skips it, and only + this explicit abort (``spare_parked=False``) lets an unload drain it. + """ + try: + return await engine.abort_all_requests(spare_parked=spare_parked) + except TypeError: + return await engine.abort_all_requests() + async def _abort_loaded_requests_for_memory_emergency(self) -> int: """Abort active requests on loaded models without unloading them.""" aborted_total = 0 @@ -1584,7 +1599,11 @@ async def _abort_loaded_requests_for_memory_emergency(self) -> int: continue try: - result = abort_all() + # Emergency: parked requests are aborted too. + try: + result = abort_all(spare_parked=False) + except TypeError: + result = abort_all() if inspect.isawaitable(result): result = await result except Exception as exc: # noqa: BLE001 @@ -1905,7 +1924,11 @@ async def _check_and_enforce(self) -> None: and entry.engine is not None and hasattr(entry.engine, "abort_all_requests") ): - result = await entry.engine.abort_all_requests() + # The model is about to be unloaded: parked + # requests would be orphaned, abort them too. + result = await self._abort_all_requests( + entry.engine, spare_parked=False + ) aborted = max(0, int(result or 0)) if aborted > 0: logger.warning( @@ -1934,7 +1957,13 @@ async def _check_and_enforce(self) -> None: and entry.engine is not None and hasattr(entry.engine, "abort_all_requests") ): - aborted = await entry.engine.abort_all_requests() + # Only the non-emergency path keeps the model + # loaded and lets parked requests resume; an + # emergency unload must abort them, or they keep + # the engine non-idle and the unload never drains. + aborted = await self._abort_all_requests( + entry.engine, spare_parked=not emergency + ) if not emergency: logger.warning( "Hard memory pressure: aborted %d request(s) on " diff --git a/tests/test_engine_core.py b/tests/test_engine_core.py index 60df9862f6..d9db219f3b 100644 --- a/tests/test_engine_core.py +++ b/tests/test_engine_core.py @@ -1281,10 +1281,10 @@ async def test_abort_all_requests_skips_requests_already_aborted( engine.close() @pytest.mark.asyncio - async def test_abort_all_requests_leaves_parked_requests_alone( + async def test_abort_all_requests_spares_parked_only_when_asked( self, mock_model, mock_tokenizer ): - """A parked request holds no memory; a pressure abort must keep it.""" + """Only the keep-loaded caller may spare parked requests, explicitly.""" with patch("omlx.engine_core.get_registry") as mock_registry: mock_registry.return_value.acquire.return_value = True engine = EngineCore(model=mock_model, tokenizer=mock_tokenizer) @@ -1295,12 +1295,43 @@ async def test_abort_all_requests_leaves_parked_requests_alone( live_id = await engine.add_request(prompt="World") engine.scheduler.requests[parked_id].parked = True - assert await engine.abort_all_requests() == 1 + assert await engine.abort_all_requests(spare_parked=True) == 1 assert engine._output_collectors[parked_id].get_nowait() is None assert engine._output_collectors[live_id].get_nowait().finished - # An explicit reason (manual unload, shutdown) aborts it too. - assert await engine.abort_all_requests(reason="unloading") == 1 + # No implicit default: unload, eviction, emergency and shutdown + # callers pass nothing (or a reason) and abort it too. + assert await engine.abort_all_requests() == 1 + out = engine._output_collectors[parked_id].get_nowait() + assert out.finished and out.error + finally: + await engine.stop() + engine.close() + + @pytest.mark.asyncio + async def test_abort_all_requests_with_reason_aborts_parked( + self, mock_model, mock_tokenizer + ): + """An unload reason aborts parked requests with the unload error.""" + with patch("omlx.engine_core.get_registry") as mock_registry: + mock_registry.return_value.acquire.return_value = True + engine = EngineCore(model=mock_model, tokenizer=mock_tokenizer) + try: + await engine.start() + engine.scheduler.has_requests = lambda: False + parked_id = await engine.add_request(prompt="Hello") + engine.scheduler.requests[parked_id].parked = True + + assert ( + await engine.abort_all_requests( + reason="unloading", error_code="model_unloading" + ) + == 1 + ) + out = engine._output_collectors[parked_id].get_nowait() + assert out.finished and out.error == "unloading" + assert out.error_code == "model_unloading" + assert parked_id in engine.scheduler._pending_abort_ids finally: await engine.stop() engine.close() diff --git a/tests/test_process_memory_enforcer.py b/tests/test_process_memory_enforcer.py index 6205d56b08..244ce287f2 100644 --- a/tests/test_process_memory_enforcer.py +++ b/tests/test_process_memory_enforcer.py @@ -3126,6 +3126,118 @@ def test_disabled_guard_reports_zero_components(self): } +class _ParkedOnlyEngine: + """Engine whose only work is a parked request (owns a collector).""" + + def __init__(self): + # A scheduler with no park/reclaim API: the enforcer goes straight to + # its abort/evict paths instead of deferring. + self._engine = SimpleNamespace( + engine=SimpleNamespace(scheduler=SimpleNamespace()) + ) + self.parked = ["parked-1"] + self.aborted = [] + self.calls = [] + + def has_active_requests(self): + return bool(self.parked) + + async def abort_all_requests(self, *, spare_parked=False): + self.calls.append(spare_parked) + if spare_parked: + return 0 + n = len(self.parked) + self.aborted.extend(self.parked) + self.parked.clear() + return n + + +class TestParkedRequestsOnUnloadPaths: + """Parked requests are spared only where the model stays loaded.""" + + @pytest.mark.asyncio + async def test_idle_lru_eviction_aborts_parked_then_unloads(self, enforcer): + engine = _ParkedOnlyEngine() + entry = _make_entry("idle-model", engine=engine) + other = _make_entry("other", engine=MagicMock()) + enforcer._engine_pool._entries = {"idle-model": entry, "other": other} + enforcer._engine_pool._find_lru_victim.return_value = "idle-model" + + async def fake_unload(model_id): + enforcer._engine_pool._entries[model_id].engine = None + + enforcer._engine_pool._unload_engine.side_effect = fake_unload + + with patch.object( + enforcer, + "_current_usage_bytes", + side_effect=_cycling([15 * 1024**3, 15 * 1024**3, 8 * 1024**3]), + ): + await enforcer._check_and_enforce() + + assert engine.calls == [False] + assert engine.aborted == ["parked-1"] + enforcer._engine_pool._unload_engine.assert_awaited_once_with("idle-model") + + @pytest.mark.asyncio + async def test_emergency_busy_victim_aborts_parked_and_unload_completes( + self, enforcer + ): + engine = _ParkedOnlyEngine() + entry = _make_entry("big-model", engine=engine) + enforcer._engine_pool._entries = {"big-model": entry} + enforcer._engine_pool._find_lru_victim.return_value = None + + with patch.object( + enforcer, + "_current_usage_bytes", + side_effect=_cycling([13 * 1024**3, 13 * 1024**3]), + ): + await enforcer._check_and_enforce() + + assert engine.calls == [False] + assert engine.aborted == ["parked-1"] + # Nothing keeps the engine busy: the pending unload drained at once. + enforcer._engine_pool._unload_engine.assert_awaited_once_with("big-model") + assert entry.pending_unload_reason is None + + @pytest.mark.asyncio + async def test_keep_loaded_hard_path_spares_parked(self, enforcer): + engine = _ParkedOnlyEngine() + entry = _make_entry("big-model", engine=engine) + enforcer._engine_pool._entries = {"big-model": entry} + enforcer._engine_pool._find_lru_victim.return_value = None + + with patch.object( + enforcer, + "_current_usage_bytes", + side_effect=_cycling([11 * 1024**3, 11 * 1024**3]), + ): + await enforcer._check_and_enforce() + + assert engine.calls == [True] + assert engine.parked == ["parked-1"] + enforcer._engine_pool._unload_engine.assert_not_awaited() + assert entry.pending_unload_reason is None + + @pytest.mark.asyncio + async def test_emergency_abort_of_loaded_models_aborts_parked(self, enforcer): + engine = _ParkedOnlyEngine() + enforcer._engine_pool._entries = {"m": _make_entry("m", engine=engine)} + + assert await enforcer._abort_loaded_requests_for_memory_emergency() == 1 + assert engine.calls == [False] + assert engine.parked == [] + + @pytest.mark.asyncio + async def test_engines_without_parking_keep_the_no_argument_hook(self, enforcer): + class Legacy: + async def abort_all_requests(self): + return 2 + + assert await enforcer._abort_all_requests(Legacy(), spare_parked=True) == 2 + + class TestPressureReclaimGrace: """Reclaim-first grace gives pooled Metal buffers a bounded chance to drain before destructive hot-cache shrinking or request aborts.""" From 4fed9d391319e6f1374b3397ec51420187f85fc6 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Thu, 1 Oct 2026 16:27:50 -0600 Subject: [PATCH 11/46] fix(scheduler): bound the park hold gate and let a parked head pass when idle --- omlx/request.py | 1 + omlx/scheduler.py | 18 +++++++++++++++- tests/test_scheduler_park.py | 41 ++++++++++++++++++++++++++++++++++++ 3 files changed, 59 insertions(+), 1 deletion(-) diff --git a/omlx/request.py b/omlx/request.py index 02f00e2677..adfa77c4c4 100644 --- a/omlx/request.py +++ b/omlx/request.py @@ -248,6 +248,7 @@ def vlm_extra_key_ranges_for_cache( # keeps its client stream and place in line and resumes from its last # committed prefix. ``parked`` is True from the park until the resume. parked: bool = False + parked_at: float = 0.0 # time.monotonic() of the latest park park_count: int = 0 # Parks taken so far (bounded by max_parks_per_request) # Request-scoped tool schemas used by protocol output parsers. diff --git a/omlx/scheduler.py b/omlx/scheduler.py index bc6a9a7be6..d5a71e88a0 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -1357,6 +1357,8 @@ def _is_turboquant_kv_family_cache(cache_obj: Any) -> bool: # A pressure monitor that has not reported for this long is considered gone; # parked requests then resume instead of waiting for polls that never come. PARK_SIGNAL_STALE_S = 60.0 +# Longest a parked head holds admission on a non-hard pressure level. +PARK_MAX_HOLD_S = 300.0 class _ParkPins(NamedTuple): @@ -2283,6 +2285,7 @@ def __init__( self._park_settle_polls: int = 0 self._ok_polls: int = 0 self._last_pressure_poll_at: float | None = None + self._last_pressure_level: str = "ok" self._park_pins: dict[str, _ParkPins] = {} self._park_stats: dict[str, int] = { "parks": 0, @@ -11855,6 +11858,7 @@ def note_pressure_poll(self, level: str) -> None: ``ok`` polls (hysteresis against flapping at the watermark). """ self._last_pressure_poll_at = time.monotonic() + self._last_pressure_level = level if level == "ok": self._ok_polls += 1 self._park_settle_polls = 0 @@ -11869,6 +11873,17 @@ def _park_resume_allowed(self) -> bool: need = getattr(self.config, "park_resume_ok_polls", 3) return self._ok_polls >= max(1, need) + def _park_hold_applies(self, head: "Request") -> bool: + """Whether a parked head still blocks admission. + + Never when nothing is admitted (admission must be able to recover), + and not past PARK_MAX_HOLD_S unless the last pressure was hard. + """ + if self._park_resume_allowed() or not self._num_admitted_requests(): + return False + held_s = time.monotonic() - head.parked_at + return held_s < PARK_MAX_HOLD_S or self._last_pressure_level == "hard" + def is_request_parked(self, request_id: str) -> bool: """Whether the request is currently parked (holds no live memory).""" request = self.requests.get(request_id) @@ -11978,6 +11993,7 @@ def _park_prefill(self, request: Request, reason: str) -> None: self.prefilling = deque(r for r in self.prefilling if r.request_id != rid) self._reset_request_for_reprefill(request) request.parked = True + request.parked_at = time.monotonic() request.park_count += 1 self._clear_request_admission_bookkeeping(rid) get_prefill_tracker().remove(rid) @@ -13030,7 +13046,7 @@ def _schedule_waiting_scan( # Parked requests sit at the front in arrival order and resume # only after enough consecutive ok pressure polls; nothing newer # overtakes them while they wait. - if self.waiting[0].parked and not self._park_resume_allowed(): + if self.waiting[0].parked and self._park_hold_applies(self.waiting[0]): break admitted = self._num_admitted_requests() diff --git a/tests/test_scheduler_park.py b/tests/test_scheduler_park.py index 763cc76599..1115a8b9cb 100644 --- a/tests/test_scheduler_park.py +++ b/tests/test_scheduler_park.py @@ -13,6 +13,7 @@ import test_scheduler_prefill_progress_commit as commit_rig from test_scheduler_prefill_progress_commit import BLOCK, _returns_promptly, _Rig +import omlx.scheduler as scheduler_module from omlx.request import Request, RequestStatus, SamplingParams # Controllable commit worker fixture shared with the incremental-commit suite. @@ -209,6 +210,7 @@ def test_a_sole_prefill_is_parkable_when_pressure_comes_from_elsewhere( try: only = submit(rig, "only", PROMPT_A, arrival=1.0) step_until(rig, lambda: prefilling_ids(rig) == ["only"]) + rig.scheduler._park_hold_applies = lambda head: True # isolate the park assert rig.scheduler.request_park_prefill() is True step(rig) assert only.parked and waiting_ids(rig) == ["only"] @@ -280,6 +282,44 @@ def test_no_resume_before_the_required_consecutive_ok_polls(tmp_path, mock_token rig.close() +def _parked_young(rig, level): + prefill_two(rig) + rig.scheduler.request_park_prefill() + step(rig) + assert waiting_ids(rig) == ["young"] + rig.scheduler.note_pressure_poll(level) + return rig.scheduler.requests["young"] + + +def test_parked_head_passes_when_nothing_is_admitted( + tmp_path, mock_tokenizer, monkeypatch +): + rig = make_rig(tmp_path, mock_tokenizer) + try: + _parked_young(rig, "soft") + monkeypatch.setattr(rig.scheduler, "_num_admitted_requests", lambda: 0) + assert rig.scheduler._park_hold_applies(rig.scheduler.waiting[0]) is False + step_until(rig, lambda: "young" in prefilling_ids(rig)) + finally: + rig.close() + + +def test_parked_head_is_released_after_the_max_hold_unless_hard( + tmp_path, mock_tokenizer +): + rig = make_rig(tmp_path, mock_tokenizer) + try: + young = _parked_young(rig, "soft") + scheduler = rig.scheduler + assert scheduler._park_hold_applies(young) is True # fresh park holds + young.parked_at -= scheduler_module.PARK_MAX_HOLD_S + 1 + assert scheduler._park_hold_applies(young) is False # soft: bounded + scheduler.note_pressure_poll("hard") + assert scheduler._park_hold_applies(young) is True # hard: still held + finally: + rig.close() + + def test_new_requests_do_not_overtake_a_parked_one(tmp_path, mock_tokenizer): rig = make_rig(tmp_path, mock_tokenizer) try: @@ -427,6 +467,7 @@ def test_settling_after_a_park_defers_the_abort_for_a_few_polls( try: submit(rig, "only", PROMPT_A, arrival=1.0) step_until(rig, lambda: prefilling_ids(rig) == ["only"]) + rig.scheduler._park_hold_applies = lambda head: True # isolate the park rig.scheduler.request_park_prefill() step(rig) # Memory is returning to the OS; the enforcer must not abort yet. From 5ed4e2256d16ab84998bb1ba8ccfad1e21879684 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Thu, 1 Oct 2026 16:33:09 -0600 Subject: [PATCH 12/46] fix(scheduler): resume parked requests one per window and keep parked 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 --- omlx/scheduler.py | 83 ++++++++++++------ tests/test_scheduler_park.py | 157 ++++++++++++++++++++++++++++++++++- 2 files changed, 214 insertions(+), 26 deletions(-) diff --git a/omlx/scheduler.py b/omlx/scheduler.py index d5a71e88a0..44bdb8ad23 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -2282,8 +2282,15 @@ def __init__( # poll counters are written by the enforcer thread (GIL-atomic) and # consumed on the MLX thread. self._park_requested: bool = False - self._park_settle_polls: int = 0 + # Enforcer polls since the latest park, or None when no park is + # settling. Counted in note_pressure_poll, never per query. + self._polls_since_park: int | None = None self._ok_polls: int = 0 + # Hysteresis between resumes: at most one parked request resumes per + # scheduling pass, and the next one needs a fresh ok streak (or, for + # the max-hold escape, as many polls since the last resume). + self._park_resumed_this_pass: bool = False + self._polls_since_resume: int = 1 << 30 self._last_pressure_poll_at: float | None = None self._last_pressure_level: str = "ok" self._park_pins: dict[str, _ParkPins] = {} @@ -5642,10 +5649,11 @@ def get_active_hot_cache_block_hashes(self) -> set[bytes]: continue if block_hash is not None: hashes.add(bytes(block_hash)) - # Parked requests hold no live table, but their pinned prefix must - # survive a hot-cache shrink too. - for pins in list(self._park_pins.values()): - hashes.update(pins.hashes) + # Parked requests are deliberately absent: parking exists because RAM + # is short, so a shrink may reclaim their blocks. That is safe because + # a dirty hot-cache eviction is written back to the SSD + # (PagedSSDCacheManager._handle_hot_cache_eviction) where the park pin + # keeps them from LRU eviction, and resume restores them from there. return hashes def _clear_memory_admission_blocker(self, request_id: str | None = None) -> None: @@ -11859,9 +11867,12 @@ def note_pressure_poll(self, level: str) -> None: """ self._last_pressure_poll_at = time.monotonic() self._last_pressure_level = level + self._polls_since_resume = min(self._polls_since_resume + 1, 1 << 30) + if self._polls_since_park is not None: + self._polls_since_park += 1 if level == "ok": self._ok_polls += 1 - self._park_settle_polls = 0 + self._polls_since_park = None # pressure gone: nothing left to settle else: self._ok_polls = 0 @@ -11877,12 +11888,20 @@ def _park_hold_applies(self, head: "Request") -> bool: """Whether a parked head still blocks admission. Never when nothing is admitted (admission must be able to recover), - and not past PARK_MAX_HOLD_S unless the last pressure was hard. + and not past PARK_MAX_HOLD_S unless the last pressure was hard. Every + escape resumes one request per scheduling pass, and the max-hold + escape also waits ``park_resume_ok_polls`` polls after the previous + resume, so a burst of resumes cannot re-trigger hard pressure. """ + if self._park_resumed_this_pass: + return True if self._park_resume_allowed() or not self._num_admitted_requests(): return False + need = max(1, getattr(self.config, "park_resume_ok_polls", 3)) held_s = time.monotonic() - head.parked_at - return held_s < PARK_MAX_HOLD_S or self._last_pressure_level == "hard" + if held_s >= PARK_MAX_HOLD_S and self._last_pressure_level != "hard": + return self._polls_since_resume < need + return True def is_request_parked(self, request_id: str) -> bool: """Whether the request is currently parked (holds no live memory).""" @@ -11947,17 +11966,21 @@ def request_park_prefill(self) -> bool: return False if self._park_requested: return True + victim_may_exist = False try: - victim = self._select_park_victim() - except RuntimeError: # queue mutated mid-read on the MLX thread - victim = True - if victim is not None: + victim_may_exist = self._select_park_victim() is not None + except RuntimeError: + # The queues mutated mid-read on the MLX thread; assume a victim + # exists and let the step-boundary selection decide. + victim_may_exist = True + if victim_may_exist: self._park_requested = True return True - if self._park_settle_polls > 0: - self._park_settle_polls -= 1 - return True - return False + # A park just ran and its memory is still returning to the OS. + return ( + self._polls_since_park is not None + and self._polls_since_park <= PARK_SETTLE_POLLS + ) def _process_pending_park(self) -> bool: """Park one victim if the enforcer asked (MLX thread, step start).""" @@ -11970,7 +11993,7 @@ def _process_pending_park(self) -> bool: if victim is None: return False self._park_prefill(victim, reason="hard memory pressure") - self._park_settle_polls = PARK_SETTLE_POLLS + self._polls_since_park = 0 return True def _park_prefill(self, request: Request, reason: str) -> None: @@ -11998,7 +12021,7 @@ def _park_prefill(self, request: Request, reason: str) -> None: self._clear_request_admission_bookkeeping(rid) get_prefill_tracker().remove(rid) # Order matters: pin first, then release the table's own refs. - self._after_commit(rid, lambda: self._pin_parked_blocks(rid)) + self._after_commit(rid, lambda: self._pin_parked_blocks(rid, request)) self._release_paged_cache_for_request(rid) self._drop_boundary_snapshots_for_request(rid) self._enqueue_parked(request) @@ -12031,17 +12054,21 @@ def _enqueue_parked(self, request: Request) -> None: break self.waiting.insert(index, request) - def _pin_parked_blocks(self, request_id: str) -> None: + def _pin_parked_blocks(self, request_id: str, request: Request) -> None: """Hold the committed blocks of a parked request against eviction. Takes one extra block ref per committed block (so the table's own release leaves them referenced) and pins their hashes in the SSD index, whose size enforcement skips them. Skipped when the request - was aborted or already resumed before this deferred step ran. + was aborted, reset or already resumed before this deferred step ran: + the request must still be the registered, parked one. """ - request = self.requests.get(request_id) manager = self.paged_cache_manager - if request is None or not request.parked or manager is None: + if ( + self.requests.get(request_id) is not request + or not request.parked + or manager is None + ): return table = manager.get_block_table(request_id) if not table or not table.block_ids: @@ -12078,7 +12105,11 @@ def _finish_park_resume(self, request: Request) -> None: """Re-admission of a parked request: its fresh lookup holds the blocks.""" self._unpin_parked(request.request_id) request.parked = False - self._park_settle_polls = 0 + self._polls_since_park = None + # One resume per hysteresis window: consume the ok streak. + self._ok_polls = 0 + self._polls_since_resume = 0 + self._park_resumed_this_pass = True self._park_stats["resumes"] += 1 self._park_stats["tokens_preserved"] += request.cached_tokens or 0 logger.info( @@ -12199,6 +12230,8 @@ def _do_abort_request(self, request_id: str) -> bool: self._clear_request_admission_bookkeeping(request_id) self._unpin_parked(request_id) + # A deferred pin step must not re-pin an aborted request's blocks. + request.parked = False # Remove from waiting queue if request.status == RequestStatus.WAITING: @@ -13035,6 +13068,7 @@ def _schedule_waiting_scan( # Track SpecPrefill: these requests must be alone (RoPE patching affects whole model) batch_specprefill_status: bool | None = None + self._park_resumed_this_pass = False while ( self.waiting and self._num_admitted_requests() < self._effective_max_num_seqs() @@ -15585,7 +15619,8 @@ def reset(self) -> None: for parked_id in list(self._park_pins): self._unpin_parked(parked_id) self._park_requested = False - self._park_settle_polls = 0 + self._polls_since_park = None + self._park_resumed_this_pass = False self._prefill_commits.clear() self._cache_freshness_waits.clear() self._prefix_cache_prepared.clear() diff --git a/tests/test_scheduler_park.py b/tests/test_scheduler_park.py index 1115a8b9cb..123722b29b 100644 --- a/tests/test_scheduler_park.py +++ b/tests/test_scheduler_park.py @@ -471,7 +471,10 @@ def test_settling_after_a_park_defers_the_abort_for_a_few_polls( rig.scheduler.request_park_prefill() step(rig) # Memory is returning to the OS; the enforcer must not abort yet. - answers = [rig.scheduler.request_park_prefill() for _ in range(6)] + answers = [] + for _ in range(6): + rig.scheduler.note_pressure_poll("hard") + answers.append(rig.scheduler.request_park_prefill()) assert answers[0] is True assert answers[-1] is False finally: @@ -502,7 +505,6 @@ def test_committed_blocks_are_pinned_while_parked_and_released_after_resume( rig.ssd._evict_tracked_until_size(0) table, remaining = rig.probe(PROMPT_B) assert table is not None and table.num_tokens >= BLOCK - assert scheduler.get_active_hot_cache_block_hashes() >= set(pins.hashes) finish_ok_polls(rig, 1) step_until(rig, lambda: "young" in prefilling_ids(rig)) @@ -611,6 +613,157 @@ def test_reset_and_shutdown_release_every_pin(tmp_path, mock_tokenizer): rig.close() +# --- Leaks, resume bursts, hot cache, settle polls ----------------------------- + + +def test_abort_of_a_parked_request_with_a_commit_in_flight_leaves_no_pins( + tmp_path, mock_tokenizer, gated +): + rig = make_rig(tmp_path, mock_tokenizer, ok_polls=1) + gate = None + try: + scheduler = rig.scheduler + _, young = prefill_two(rig) + gate = gated(rig) + for _ in range(8): + if "young" in scheduler._prefill_commits: + break + scheduler.step() + assert not scheduler._prefill_commits["young"][0].done() + scheduler.request_park_prefill() + scheduler._process_pending_park() + assert scheduler._teardown_pending("young") + + assert scheduler.abort_request("young") + scheduler.step() # the abort runs while the commit is still in flight + gate.release.set() + rig.drain() + step(rig, 3) + + assert not young.parked # an aborted request is no longer parked + assert "young" not in scheduler._park_pins + assert rig.ssd.pinned_block_count == 0 + finally: + if gate is not None: + gate.release.set() + rig.close() + + +def _park_three(rig): + """r1 prefilling (protected); r2, r3, r4 parked, all unpinned-ready.""" + for i, (rid, prompt) in enumerate( + [("r1", PROMPT_A), ("r2", PROMPT_B), ("r3", PROMPT_C), ("r4", PROMPT_D)] + ): + submit(rig, rid, prompt, arrival=float(i + 1), max_tokens=50) + step_until(rig, lambda: len(prefilling_ids(rig)) == 4) + for _ in range(3): + rig.scheduler.request_park_prefill() + step(rig) + assert waiting_ids(rig) == ["r2", "r3", "r4"] + + +def _resumed(rig): + return rig.scheduler.get_park_stats()["resumes"] + + +def test_parked_requests_resume_one_per_hysteresis_window(tmp_path, mock_tokenizer): + rig = make_rig(tmp_path, mock_tokenizer, ok_polls=2) + try: + _park_three(rig) + finish_ok_polls(rig, 2) + step(rig, 2) + assert _resumed(rig) == 1 # not a burst of three + + step(rig, 3) # no new polls: the streak was consumed by the resume + assert _resumed(rig) == 1 + + finish_ok_polls(rig, 2) + step(rig, 2) + assert _resumed(rig) == 2 + finally: + rig.close() + + +def test_the_max_hold_escape_resumes_one_request_at_a_time(tmp_path, mock_tokenizer): + rig = make_rig(tmp_path, mock_tokenizer, ok_polls=3) + try: + _park_three(rig) + rig.scheduler.note_pressure_poll("soft") + for request in list(rig.scheduler.waiting): + request.parked_at -= scheduler_module.PARK_MAX_HOLD_S + 1 + step(rig, 2) + assert _resumed(rig) == 1 + step(rig, 3) # still no polls: the escape does not chain + assert _resumed(rig) == 1 + finally: + rig.close() + + +def test_a_stale_monitor_resumes_one_request_per_step(tmp_path, mock_tokenizer): + rig = make_rig(tmp_path, mock_tokenizer) + try: + _park_three(rig) + rig.scheduler._last_pressure_poll_at = ( + time.monotonic() - scheduler_module.PARK_SIGNAL_STALE_S - 1 + ) + rig.scheduler._schedule_waiting() + assert _resumed(rig) == 1 + finally: + rig.close() + + +def test_a_hot_cache_shrink_reclaims_parked_blocks_that_stay_restorable( + tmp_path, mock_tokenizer +): + rig = make_rig(tmp_path, mock_tokenizer, ok_polls=1) + try: + rig.ssd._hot_cache_max_bytes = 64 * 1024**2 + rig.ssd._hot_cache_enabled = True + old, young = prefill_two(rig) + scheduler = rig.scheduler + scheduler.request_park_prefill() + step(rig) + rig.drain() + pins = scheduler._park_pins["young"] + assert pins.hashes + assert set(pins.hashes) & set(rig.ssd._hot_cache) # blocks sit in RAM + + protected = scheduler.get_active_hot_cache_block_hashes() + assert not protected & set(pins.hashes) # parked blocks are not RAM-pinned + rig.ssd.shrink_hot_cache_to(0, protected_hashes=protected) + assert not set(pins.hashes) & set(rig.ssd._hot_cache) + + # Dirty evictions were written back: SSD LRU still holds them (pinned). + rig.ssd._evict_tracked_until_size(0) + table, _ = rig.probe(PROMPT_B) + assert table is not None and table.num_tokens >= BLOCK + + finish_ok_polls(rig, 1) + step_until(rig, lambda: "young" in prefilling_ids(rig)) + assert young.cached_tokens >= BLOCK + finally: + rig.close() + + +def test_the_settle_window_counts_enforcer_polls_not_queries(tmp_path, mock_tokenizer): + rig = make_rig(tmp_path, mock_tokenizer, max_parks=1) + try: + submit(rig, "only", PROMPT_A, arrival=1.0) + step_until(rig, lambda: prefilling_ids(rig) == ["only"]) + rig.scheduler._park_hold_applies = lambda head: True # isolate the park + rig.scheduler.request_park_prefill() + step(rig) + # Repeated queries within one poll never consume the window. + assert all(rig.scheduler.request_park_prefill() for _ in range(10)) + for _ in range(scheduler_module.PARK_SETTLE_POLLS): + rig.scheduler.note_pressure_poll("hard") + assert rig.scheduler.request_park_prefill() is True + rig.scheduler.note_pressure_poll("hard") + assert rig.scheduler.request_park_prefill() is False + finally: + rig.close() + + # --- Engine bulk abort ------------------------------------------------------------- From 96c8c5cbb0a7bdd37c6bd04d8b1bd416753cd6f3 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Fri, 2 Oct 2026 01:20:51 -0600 Subject: [PATCH 13/46] refactor(scheduler): name the resume-poll saturation sentinel and test lost hot-cache write-back on resume --- omlx/scheduler.py | 11 ++++-- tests/test_scheduler_park.py | 67 ++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 2 deletions(-) diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 44bdb8ad23..08ed989ea7 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -1359,6 +1359,11 @@ def _is_turboquant_kv_family_cache(cache_obj: Any) -> bool: PARK_SIGNAL_STALE_S = 60.0 # Longest a parked head holds admission on a non-hard pressure level. PARK_MAX_HOLD_S = 300.0 +# Saturation value of ``_polls_since_resume``: "long enough since the last +# resume that the hysteresis gate is open". It is the initial value (no resume +# has happened yet) and the cap that keeps the counter from growing without +# bound; any value above every realistic ``park_resume_ok_polls`` works. +_POLLS_SINCE_RESUME_SATURATION = 1 << 30 class _ParkPins(NamedTuple): @@ -2290,7 +2295,7 @@ def __init__( # scheduling pass, and the next one needs a fresh ok streak (or, for # the max-hold escape, as many polls since the last resume). self._park_resumed_this_pass: bool = False - self._polls_since_resume: int = 1 << 30 + self._polls_since_resume: int = _POLLS_SINCE_RESUME_SATURATION self._last_pressure_poll_at: float | None = None self._last_pressure_level: str = "ok" self._park_pins: dict[str, _ParkPins] = {} @@ -11867,7 +11872,9 @@ def note_pressure_poll(self, level: str) -> None: """ self._last_pressure_poll_at = time.monotonic() self._last_pressure_level = level - self._polls_since_resume = min(self._polls_since_resume + 1, 1 << 30) + self._polls_since_resume = min( + self._polls_since_resume + 1, _POLLS_SINCE_RESUME_SATURATION + ) if self._polls_since_park is not None: self._polls_since_park += 1 if level == "ok": diff --git a/tests/test_scheduler_park.py b/tests/test_scheduler_park.py index 123722b29b..9350dba771 100644 --- a/tests/test_scheduler_park.py +++ b/tests/test_scheduler_park.py @@ -10,6 +10,7 @@ import time from types import SimpleNamespace +import pytest import test_scheduler_prefill_progress_commit as commit_rig from test_scheduler_prefill_progress_commit import BLOCK, _returns_promptly, _Rig @@ -745,6 +746,61 @@ def test_a_hot_cache_shrink_reclaims_parked_blocks_that_stay_restorable( rig.close() +@pytest.mark.parametrize("failure", ["dropped", "raises"]) +def test_resume_degrades_safely_when_the_hot_cache_writeback_is_lost( + tmp_path, mock_tokenizer, caplog, failure +): + """A parked request's dirty hot-cache blocks are reclaimed and the SSD + write-back does not happen (queue unavailable) or fails: resume must fall + back to whatever is restorable, finish the request and leave a log line.""" + import logging + + expected = uninterrupted_output(tmp_path, mock_tokenizer) + rig = make_rig(tmp_path / "park", mock_tokenizer, ok_polls=1) + try: + rig.ssd._hot_cache_max_bytes = 64 * 1024**2 + rig.ssd._hot_cache_enabled = True + old, young = prefill_two(rig) + scheduler = rig.scheduler + scheduler.request_park_prefill() + step(rig) + rig.drain() + pins = scheduler._park_pins["young"] + assert set(pins.hashes) & set(rig.ssd._hot_cache) + + def lost_write(block_hash, entry, **kwargs): + if failure == "raises": + raise OSError("ssd write queue unavailable") + return False + + rig.ssd._enqueue_ssd_write = lost_write + protected = scheduler.get_active_hot_cache_block_hashes() + try: + rig.ssd.shrink_hot_cache_to(0, protected_hashes=protected) + except OSError: + pass # the cache layer may surface the failure; the scheduler must not care + finally: + del rig.ssd._enqueue_ssd_write # back to the real queue for teardown + # Whatever the SSD index still knows is gone too: nothing is restorable. + rig.ssd._evict_tracked_until_size(0) + + with caplog.at_level(logging.INFO, logger="omlx.scheduler"): + finish_ok_polls(rig, 1) + step_until(rig, lambda: "young" in prefilling_ids(rig)) + assert any( + "Resumed parked request young" in r.getMessage() for r in caplog.records + ) + assert young.parked is False + outputs = run_to_completion(rig, [old, young]) + assert not [o for o in outputs if o.error] + assert list(young.output_token_ids) == expected + stats = scheduler.get_park_stats() + assert stats["resumes"] == 1 + assert not scheduler._park_pins + finally: + rig.close() + + def test_the_settle_window_counts_enforcer_polls_not_queries(tmp_path, mock_tokenizer): rig = make_rig(tmp_path, mock_tokenizer, max_parks=1) try: @@ -777,3 +833,14 @@ def test_is_request_parked_reads_the_request_flag(): assert Scheduler.is_request_parked(scheduler, "p") is True assert Scheduler.is_request_parked(scheduler, "l") is False assert Scheduler.is_request_parked(scheduler, "missing") is False + + +def test_polls_since_resume_saturates_at_a_named_constant(tmp_path, mock_tokenizer): + rig = make_rig(tmp_path, mock_tokenizer) + try: + cap = scheduler_module._POLLS_SINCE_RESUME_SATURATION + assert rig.scheduler._polls_since_resume == cap + rig.scheduler.note_pressure_poll("ok") + assert rig.scheduler._polls_since_resume == cap # saturated, no growth + finally: + rig.close() From 289a9d46d91e53453a2a2b4378ec35644c762cba Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Fri, 2 Oct 2026 03:15:50 -0600 Subject: [PATCH 14/46] fix(scheduler): commit prefill progress for media prompts and log every 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. --- omlx/scheduler.py | 207 ++++++++-- tests/test_scheduler_prefill_commit_vlm.py | 453 +++++++++++++++++++++ 2 files changed, 632 insertions(+), 28 deletions(-) create mode 100644 tests/test_scheduler_prefill_commit_vlm.py diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 08ed989ea7..81c4131067 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -4637,10 +4637,10 @@ def _chunk_route(n_tokens: int, cache_tokens: int) -> bool: self._emit_prefill_tail_snapshot( request, prompt_cache, total_tokens ) - if vlm_embeds is None: - Scheduler._commit_prefill_progress( - self, request, prompt_cache, base_size + processed_tokens - ) + # Media prompts commit too, under the request's own cache keys. + Scheduler._commit_prefill_progress( + self, request, prompt_cache, base_size + processed_tokens + ) Scheduler._check_post_prefill_memory( self, @@ -8002,6 +8002,28 @@ def _commit_prefill_progress( "Prefill progress commit failed for %s: %s", request.request_id, e ) + def _note_prefill_commit_skip( + self, request: "Request", key: str, detail: str + ) -> None: + """Log why a prefill commit did not run, once per request and reason. + + Every early return of the commit path ends here, so a prefill that + never becomes durable always says why in the server log. + """ + seen = getattr(request, "_prefill_commit_skips", None) + if seen is None: + seen = set() + try: + request._prefill_commit_skips = seen + except AttributeError: + return + if key in seen: + return + seen.add(key) + logger.info( + "Prefill progress commit skipped for %s: %s", request.request_id, detail + ) + def _commit_prefill_progress_unchecked( self, request: "Request", @@ -8010,6 +8032,7 @@ def _commit_prefill_progress_unchecked( commit_blocks: int, ) -> None: rid = request.request_id + skip = self._note_prefill_commit_skip block_size = self.config.paged_cache_block_size if ( block_size <= 0 @@ -8018,30 +8041,89 @@ def _commit_prefill_progress_unchecked( or self.paged_ssd_cache_manager is None or self._store_cache_executor is None ): + skip( + request, + "stores", + "no paged block size, prefix cache, SSD cache or store executor", + ) + return + if getattr(request, "skip_cache_store", False): + skip(request, "skip_cache_store", "the request opted out of cache stores") + return + if self._model_has_unreconstructible_cache(): + skip( + request, "unreconstructible", "the model's cache layout is not storable" + ) return # Prompts that are not a plain token prefix cannot be keyed by token. if ( - getattr(request, "vlm_extra_keys_for_cache", None) - or getattr(request, "vlm_extra_key_ranges_for_cache", None) - or getattr(request, "specprefill_indices", None) is not None + getattr(request, "specprefill_indices", None) is not None or self._specprefill_active_request_id == rid ): + skip(request, "specprefill", "sparse prefill (SpecPrefill) is active") + return + # Media prompts commit under the cache keys their final store uses. Those + # keys come from the whole prompt before prefill starts and a block's key + # depends only on where the block ends, never on later tokens, so the + # committed prefix is exactly what a re-issue's lookup asks for. Models + # that insist on prefilling the media prefix in one piece cannot resume + # from a committed part of it. + extra_keys = getattr(request, "vlm_extra_keys_for_cache", None) + extra_start = getattr(request, "vlm_extra_key_token_start_for_cache", None) + extra_ranges = getattr(request, "vlm_extra_key_ranges_for_cache", None) + has_media_keys = bool(extra_keys or extra_ranges) + if has_media_keys and self._minimum_prefill_prefix(request) > 0: + skip( + request, + "atomic_media_prefix", + "the model needs an atomic multimodal prefix", + ) return prompt = request.prompt_token_ids aligned = min(total_tokens, len(prompt)) // block_size * block_size self._reap_prefill_commit(rid) if rid in self._prefill_commits: - return # previous commit still running + skip(request, "in_flight", "the previous commit is still running") + return table = self.paged_cache_manager.get_block_table(rid) existing = table.num_tokens if table else 0 - if existing % block_size or (aligned - existing) // block_size < commit_blocks: + if existing % block_size: + skip( + request, + "unaligned_table", + f"the block table holds {existing} tokens, off the " + f"{block_size}-token block grid", + ) + return + if (aligned - existing) // block_size < commit_blocks: + skip( + request, + "below_threshold", + f"{(aligned - existing) // block_size} of {commit_blocks} " + f"blocks complete past {existing} tokens (first commit pending)", + ) return if self._prefill_commit_blocked_by_pressure(): + try: + usage = f"{self._current_usage_bytes() / 1024**3:.1f}GB" + except Exception: + usage = "unknown" + skip( + request, + "pressure", + f"memory usage {usage} is at or above the soft limit " + f"{self._memory_limit_bytes / 1024**3:.1f}GB", + ) return window = self._prefill_commit_window(prompt_cache, existing, aligned) if window is None: + skip( + request, + "layout", + "composite or non-standard sliceable cache layers", + ) if not getattr(self, "_prefill_commit_layout_logged", False): self._prefill_commit_layout_logged = True logger.info( @@ -8056,12 +8138,29 @@ def _commit_prefill_progress_unchecked( if _prompt_cache_needs_snapshots(prompt_cache): override = self._get_boundary_store_override(rid, tokens) if override is None: + held = len(self._boundary_cache_snapshots.get(rid) or {}) + skip( + request, + "no_snapshot", + f"no recurrent-state snapshot at or before {aligned} " + f"tokens ({held} held)", + ) return tokens, boundary_cache, _, provider = override - if ( - getattr(provider, "tail_terminal_token_count", None) is not None - or len(tokens) <= existing - ): + if getattr(provider, "tail_terminal_token_count", None) is not None: + skip( + request, + "tail_terminal", + "the newest snapshot is an off-grid tail", + ) + return + if len(tokens) <= existing: + skip( + request, + "no_new_snapshot", + f"the newest snapshot ({len(tokens)} tokens) is not " + f"past the committed {existing}", + ) return extracted = self._merge_boundary_with_full_cache( boundary_cache, extracted @@ -8084,13 +8183,17 @@ def _commit_prefill_progress_unchecked( extracted, model_cache_config, provider, + extra_key_args=( + (extra_keys, extra_start, extra_ranges) if has_media_keys else None + ), ) self._prefill_commits[rid] = (future, len(tokens)) - logger.debug( - "Committing prefill progress for %s: %d -> %d tokens", + logger.info( + "Committing prefill progress for %s: tokens [%d, %d)%s", rid, existing, len(tokens), + " under media cache keys" if has_media_keys else "", ) def _commit_prefill_worker( @@ -8100,9 +8203,13 @@ def _commit_prefill_worker( window_cache: list[Any], model_cache_config: Any | None, snapshots: Any | None, + extra_key_args: tuple[Any, Any, Any] | None = None, ) -> bool: """Store a committed prefill window; True when the table covers it. + ``extra_key_args`` are the request's media cache keys (keys, token + start, ranges), passed exactly as its final store passes them. + Cancellation is checked under ``_commit_store_lock`` before the store call, the only step that touches the stores; shutdown takes that lock to learn that no store call is active. @@ -8110,15 +8217,16 @@ def _commit_prefill_worker( with self._commit_store_lock: if self._commit_cancelled.is_set(): return False + extra_keys, extra_start, extra_ranges = extra_key_args or (None, None, None) self._async_store_cache_worker( request_id, tokens, window_cache, model_cache_config, snapshots, - None, - None, - None, + extra_keys, + extra_start, + extra_ranges, True, incremental_commit=True, ) @@ -11922,25 +12030,66 @@ def get_park_stats(self) -> dict[str, int]: stats["pinned_requests"] = len(self._park_pins) return stats - def _parkable_prefills(self) -> list[Request]: - """Chunked prefills that can be parked safely. + def _park_exclusion_reason(self, request: Request) -> str | None: + """Why ``request`` cannot be parked now, or None when it can. Only requests in the chunked-prefill loop qualify: their state lives - between steps. External-loop prefills (non-chunked, VLM) run to - completion inside one ``_schedule_waiting`` call and are never - between steps; VLM embeds and SpecPrefill patch model-wide state, so - they are excluded as well. + between steps. External-loop prefills (non-chunked, media prompts) run + to completion inside one ``_schedule_waiting`` call and are never + between steps; media embeddings and SpecPrefill patch model-wide state, + so they are excluded as well. A text prompt on a VLM engine takes the + chunked loop like any other model and is parkable. """ budget = getattr(self.config, "max_parks_per_request", 3) + if request.request_id in self.running: + return "decoding, not in chunked prefill" + if request.park_count >= budget: + return f"park budget spent ({request.park_count}/{budget})" + if request.specprefill_indices is not None: + return "SpecPrefill sparse prefill patches model-wide state" + if request.vlm_inputs_embeds is not None: + return ( + "multimodal prompt (fused media embeddings) prefills in the " + "external loop, not between steps" + ) + if request.request_id not in self._prefill_states: + return "prefill runs in the external loop, not between steps" + return None + + def _parkable_prefills(self) -> list[Request]: + """Chunked prefills that can be parked safely.""" return [ request for request in list(self.prefilling) - if request.request_id in self._prefill_states - and request.park_count < budget - and request.specprefill_indices is None - and request.vlm_inputs_embeds is None + if self._park_exclusion_reason(request) is None ] + def _log_no_parkable_victim(self) -> None: + """Say once per request why a park was wanted and nobody could be parked.""" + try: + admitted = list(self.requests.values()) + queued = {r.request_id for r in list(self.waiting)} + except RuntimeError: + return # the queues mutated mid-read on the MLX thread + for request in admitted: + if request.request_id in queued or request.is_finished(): + continue + reason = self._park_exclusion_reason(request) + if reason is None or reason in getattr(request, "_park_skip_logged", ()): + continue + try: + request._park_skip_logged = ( + *getattr(request, "_park_skip_logged", ()), + reason, + ) + except AttributeError: + continue + logger.info( + "Park skipped for %s: %s (memory pressure falls back to abort)", + request.request_id, + reason, + ) + def _select_park_victim(self) -> Request | None: """Most recent arrival first; the oldest admitted request is protected. @@ -11983,6 +12132,7 @@ def request_park_prefill(self) -> bool: if victim_may_exist: self._park_requested = True return True + self._log_no_parkable_victim() # A park just ran and its memory is still returning to the OS. return ( self._polls_since_park is not None @@ -11998,6 +12148,7 @@ def _process_pending_park(self) -> bool: return False victim = self._select_park_victim() if victim is None: + self._log_no_parkable_victim() return False self._park_prefill(victim, reason="hard memory pressure") self._polls_since_park = 0 diff --git a/tests/test_scheduler_prefill_commit_vlm.py b/tests/test_scheduler_prefill_commit_vlm.py new file mode 100644 index 0000000000..a08ff346a0 --- /dev/null +++ b/tests/test_scheduler_prefill_commit_vlm.py @@ -0,0 +1,453 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Incremental prefill commit on the VLM engine path. + +``VLMBatchedEngine`` runs a text prompt through the same chunked prefill as any +other engine, but a prompt whose conversation carries an image (pi resends the +whole history every turn) arrives with fused embeddings and request-wide media +cache keys. It takes the external prefill loop instead. These tests drive that +path against a small initialized Qwen3.5 hybrid wrapped to accept +``inputs_embeds`` the way the mlx-vlm language model does. +""" + +import logging + +import mlx.core as mx +import mlx.nn as nn +import pytest +from test_scheduler_prefill_progress_commit import ( # noqa: F401 + BLOCK, + PROMPT, + _decode_to_finish, + _Rig, + gated, +) + +from omlx.request import Request, SamplingParams + +IMAGE_KEY = ("image-a",) +IMAGE_START = 6 # inside the second block: block one stays a plain text prefix + + +class _VLMLikeModel(nn.Module): + """Hybrid text model with the mlx-vlm language-model call signature.""" + + def __init__(self, inner, minimum_prefix=0): + super().__init__() + self.inner = inner + self._minimum_prefix = minimum_prefix + + @property + def layers(self): + return self.inner.layers + + def make_cache(self): + return self.inner.make_cache() + + def embed(self, tokens): + return self.inner.language_model.model.embed_tokens(mx.array([tokens])) + + def clear_vlm_position_state(self): + pass + + def __call__(self, inputs, cache=None, inputs_embeds=None, **_): + return self.inner(inputs, cache=cache, input_embeddings=inputs_embeds) + + def minimum_prefill_prefix(self, tokens): + return self._minimum_prefix + + +@pytest.fixture +def split(request): + return request.param + + +def _rig(tmp_path, tokenizer, split, *, commit_blocks=2, minimum_prefix=0): + rig = _Rig(tmp_path, tokenizer, split=split, commit_blocks=commit_blocks) + wrapped = _VLMLikeModel(rig.model, minimum_prefix) + rig.scheduler.model = wrapped + rig.wrapped = wrapped + return rig + + +def _media_request(rig, rid="mm", prompt=PROMPT, **overrides): + embeds = rig.wrapped.embed(list(prompt)) + request = Request( + request_id=rid, + prompt=list(prompt), + sampling_params=SamplingParams(max_tokens=1), + vlm_inputs_embeds=embeds, + vlm_image_hash=IMAGE_KEY[0], + vlm_cache_key_start=IMAGE_START, + **overrides, + ) + rig.scheduler.add_request(request) + rig.scheduler.waiting.clear() + request.remaining_tokens = list(prompt) + return request, embeds + + +def _prefill_externally(rig, request, embeds): + rig.scheduler._do_external_prefill( + request, list(request.prompt_token_ids), None, vlm_embeds=(embeds, {}, 0) + ) + rig.drain() + + +def _lookup(rig, tokens, keyed): + kwargs = ( + {"extra_keys": IMAGE_KEY, "extra_key_token_start": IMAGE_START} if keyed else {} + ) + return rig.prefix.fetch_cache("probe", list(tokens), **kwargs) + + +@pytest.mark.parametrize( + "split", [False, True], ids=["inline-gdn", "split-gdn"], indirect=True +) +def test_media_prompt_commits_progress_under_its_own_cache_keys( + tmp_path, mock_tokenizer, split +): + rig = _rig(tmp_path, mock_tokenizer, split) + try: + request, embeds = _media_request(rig) + _prefill_externally(rig, request, embeds) + assert rig.table_tokens("mm") == 4 * BLOCK + + # A re-issue of the same media prompt resumes at the committed boundary + # and the restored prefix equals a cold forward pass. + assert rig.scheduler._do_abort_request("mm") + table, remaining = _lookup(rig, PROMPT, keyed=True) + assert table is not None and table.num_tokens == 4 * BLOCK + assert remaining == PROMPT[4 * BLOCK :] + restored = rig.prefix.reconstruct_cache(table) + assert restored is not None + with mx.stream(rig.scheduler._stream): + warm = rig.wrapped( + mx.array([remaining]), + cache=restored, + inputs_embeds=rig.wrapped.embed(remaining), + ) + cold = rig.wrapped( + mx.array([PROMPT]), + cache=rig.wrapped.make_cache(), + inputs_embeds=rig.wrapped.embed(PROMPT), + ) + mx.eval(warm, cold) + assert mx.allclose(warm[:, -1], cold[:, -1], atol=1e-4) + finally: + rig.close() + + +@pytest.mark.parametrize( + "split", [False, True], ids=["inline-gdn", "split-gdn"], indirect=True +) +def test_committed_media_blocks_are_not_visible_to_a_text_only_lookup( + tmp_path, mock_tokenizer, split +): + rig = _rig(tmp_path, mock_tokenizer, split) + try: + request, embeds = _media_request(rig) + _prefill_externally(rig, request, embeds) + assert rig.scheduler._do_abort_request("mm") + + # Block one ends before the image starts, so it is an ordinary text + # prefix; every later block carries the media key and must not match. + table, remaining = _lookup(rig, PROMPT, keyed=False) + assert table is not None and table.num_tokens == BLOCK + assert remaining == PROMPT[BLOCK:] + finally: + rig.close() + + +@pytest.mark.parametrize( + "split", [False, True], ids=["inline-gdn", "split-gdn"], indirect=True +) +def test_media_commit_matches_the_final_store_keys(tmp_path, mock_tokenizer, split): + rig = _rig(tmp_path, mock_tokenizer, split) + try: + request, embeds = _media_request(rig) + _prefill_externally(rig, request, embeds) + committed = [ + rig.paged.allocated_blocks[b].block_hash + for b in rig.paged.get_block_table("mm").block_ids + ] + # The chain the final store would produce for the same prompt and keys. + from omlx.cache.paged_cache import compute_block_hash, resolve_block_extra_keys + + parent, expected = None, [] + for start in range(0, 4 * BLOCK, BLOCK): + parent = compute_block_hash( + parent, + PROMPT[start : start + BLOCK], + extra_keys=resolve_block_extra_keys( + start + BLOCK, + extra_keys=IMAGE_KEY, + extra_key_token_start=IMAGE_START, + ), + model_name=rig.paged.model_name, + ) + expected.append(parent) + assert committed == expected + finally: + rig.close() + + +@pytest.mark.parametrize("split", [False], ids=["inline-gdn"], indirect=True) +def test_models_needing_an_atomic_media_prefix_do_not_commit( + tmp_path, mock_tokenizer, split, caplog +): + rig = _rig(tmp_path, mock_tokenizer, split, minimum_prefix=BLOCK) + try: + request, embeds = _media_request(rig) + with caplog.at_level(logging.INFO, logger="omlx.scheduler"): + _prefill_externally(rig, request, embeds) + assert rig.table_tokens("mm") == 0 + assert any( + "skipped for mm" in r.getMessage() and "atomic" in r.getMessage() + for r in caplog.records + ) + finally: + rig.close() + + +@pytest.mark.parametrize( + "split", [False, True], ids=["inline-gdn", "split-gdn"], indirect=True +) +def test_text_prompt_on_the_vlm_engine_commits_through_chunked_prefill( + tmp_path, mock_tokenizer, split +): + rig = _rig(tmp_path, mock_tokenizer, split) + try: + request = Request( + request_id="txt", + prompt=list(PROMPT), + sampling_params=SamplingParams(max_tokens=1), + ) + rig.scheduler.add_request(request) + rig.scheduler.waiting.clear() + request.remaining_tokens = list(PROMPT) + state = rig.scheduler._begin_prefill(request, list(PROMPT), None) + rig.step(state, 3) + assert rig.table_tokens("txt") == 2 * BLOCK + finally: + rig.close() + + +# --- Observability: a prefill that is not durable always says why --------------- + + +def _info(caplog, needle): + return [ + r.getMessage() + for r in caplog.records + if r.levelno == logging.INFO and needle in r.getMessage() + ] + + +def _chunked_text_prefill(rig, rid="r1", chunks=4): + request = Request( + request_id=rid, + prompt=list(PROMPT), + sampling_params=SamplingParams(max_tokens=1), + ) + rig.scheduler.add_request(request) + rig.scheduler.waiting.clear() + request.remaining_tokens = list(PROMPT) + state = rig.scheduler._begin_prefill(request, list(PROMPT), None) + rig.step(state, chunks) + return request + + +@pytest.mark.parametrize("split", [False], ids=["inline-gdn"], indirect=True) +def test_each_successful_commit_logs_its_token_range_once( + tmp_path, mock_tokenizer, split, caplog +): + rig = _rig(tmp_path, mock_tokenizer, split) + try: + with caplog.at_level(logging.INFO, logger="omlx.scheduler"): + _chunked_text_prefill(rig) + assert _info(caplog, "Committing prefill progress for r1") == [ + "Committing prefill progress for r1: tokens [0, 8)", + "Committing prefill progress for r1: tokens [8, 16)", + ] + finally: + rig.close() + + +@pytest.mark.parametrize("split", [False], ids=["inline-gdn"], indirect=True) +def test_media_commit_log_names_the_media_keys(tmp_path, mock_tokenizer, split, caplog): + rig = _rig(tmp_path, mock_tokenizer, split) + try: + request, embeds = _media_request(rig) + with caplog.at_level(logging.INFO, logger="omlx.scheduler"): + _prefill_externally(rig, request, embeds) + assert _info( + caplog, "Committing prefill progress for mm: tokens [0, 8) under media" + ) + finally: + rig.close() + + +@pytest.mark.parametrize("split", [False], ids=["inline-gdn"], indirect=True) +def test_waiting_for_the_first_commit_is_logged_once_per_request( + tmp_path, mock_tokenizer, split, caplog +): + rig = _rig(tmp_path, mock_tokenizer, split, commit_blocks=3) + try: + with caplog.at_level(logging.INFO, logger="omlx.scheduler"): + _chunked_text_prefill(rig, chunks=2) + lines = _info(caplog, "Prefill progress commit skipped for r1") + assert len(lines) == 1 + assert "of 3 blocks complete" in lines[0] + finally: + rig.close() + + +@pytest.mark.parametrize("split", [False], ids=["inline-gdn"], indirect=True) +def test_pressure_skip_is_logged_once_with_the_usage( + tmp_path, mock_tokenizer, split, caplog, monkeypatch +): + rig = _rig(tmp_path, mock_tokenizer, split) + try: + monkeypatch.setattr( + rig.scheduler, "_prefill_commit_blocked_by_pressure", lambda: True + ) + with caplog.at_level(logging.INFO, logger="omlx.scheduler"): + _chunked_text_prefill(rig, chunks=4) + lines = [ + m + for m in _info(caplog, "Prefill progress commit skipped for r1") + if "soft limit" in m + ] + assert len(lines) == 1 + assert rig.table_tokens("r1") == 0 + finally: + rig.close() + + +@pytest.mark.parametrize("split", [False], ids=["inline-gdn"], indirect=True) +def test_missing_snapshot_skip_is_logged_once( + tmp_path, mock_tokenizer, split, caplog, monkeypatch +): + rig = _rig(tmp_path, mock_tokenizer, split) + try: + monkeypatch.setattr( + rig.scheduler, "_get_boundary_store_override", lambda *a: None + ) + with caplog.at_level(logging.INFO, logger="omlx.scheduler"): + _chunked_text_prefill(rig, chunks=4) + lines = _info(caplog, "no recurrent-state snapshot") + assert len(lines) == 1 and "skipped for r1" in lines[0] + finally: + rig.close() + + +@pytest.mark.parametrize("split", [False], ids=["inline-gdn"], indirect=True) +def test_opt_out_and_specprefill_skips_say_so(tmp_path, mock_tokenizer, split, caplog): + rig = _rig(tmp_path, mock_tokenizer, split) + try: + with caplog.at_level(logging.INFO, logger="omlx.scheduler"): + request, embeds = _media_request(rig, rid="opt", skip_cache_store=True) + _prefill_externally(rig, request, embeds) + request, embeds = _media_request(rig, rid="sp") + request.specprefill_indices = mx.array([0, 1]) + _prefill_externally(rig, request, embeds) + assert _info(caplog, "skipped for opt: the request opted out") + assert _info(caplog, "skipped for sp: sparse prefill") + assert rig.table_tokens("opt") == 0 and rig.table_tokens("sp") == 0 + finally: + rig.close() + + +# --- Park on the VLM engine ------------------------------------------------------ + + +def _park_rig(tmp_path, tokenizer): + import test_scheduler_park as park + + rig = park.make_rig(tmp_path, tokenizer) + rig.wrapped = rig.scheduler.model = _VLMLikeModel(rig.model) + return park, rig + + +@pytest.mark.parametrize("split", [False], ids=["inline-gdn"], indirect=True) +def test_text_prompt_in_chunked_prefill_on_the_vlm_engine_is_a_park_victim( + tmp_path, mock_tokenizer, split +): + park, rig = _park_rig(tmp_path, mock_tokenizer) + try: + request = park.submit(rig, "txt", park.PROMPT_A, arrival=1.0) + park.step_until( + rig, + lambda: park.prefilling_ids(rig) == ["txt"] + and rig.table_tokens("txt") >= BLOCK, + ) + assert rig.scheduler._park_exclusion_reason(request) is None + assert rig.scheduler._select_park_victim() is request + assert rig.scheduler.request_park_prefill() is True + finally: + rig.close() + + +@pytest.mark.parametrize("split", [False], ids=["inline-gdn"], indirect=True) +def test_exclusion_reasons_name_each_unparkable_case(tmp_path, mock_tokenizer, split): + park, rig = _park_rig(tmp_path, mock_tokenizer) + try: + scheduler = rig.scheduler + media, _ = _media_request(rig, rid="media") + scheduler.prefilling.append(media) + scheduler._prefill_states["media"] = object() + assert "multimodal" in scheduler._park_exclusion_reason(media) + + sparse = Request( + request_id="sparse", prompt=[3, 4], sampling_params=SamplingParams() + ) + sparse.specprefill_indices = mx.array([0]) + assert "SpecPrefill" in scheduler._park_exclusion_reason(sparse) + + external = Request( + request_id="ext", prompt=[3, 4], sampling_params=SamplingParams() + ) + assert "external loop" in scheduler._park_exclusion_reason(external) + + spent = Request( + request_id="spent", prompt=[3, 4], sampling_params=SamplingParams() + ) + spent.park_count = scheduler.config.max_parks_per_request + assert "park budget spent" in scheduler._park_exclusion_reason(spent) + + decoding = Request( + request_id="dec", prompt=[3, 4], sampling_params=SamplingParams() + ) + scheduler.running["dec"] = decoding + assert scheduler._park_exclusion_reason(decoding) == ( + "decoding, not in chunked prefill" + ) + finally: + rig.close() + + +@pytest.mark.parametrize("split", [False], ids=["inline-gdn"], indirect=True) +def test_no_parkable_victim_is_logged_once_per_request_with_its_reason( + tmp_path, mock_tokenizer, split, caplog +): + park, rig = _park_rig(tmp_path, mock_tokenizer) + try: + scheduler = rig.scheduler + decoding = Request( + request_id="dec", prompt=[3, 4], sampling_params=SamplingParams() + ) + scheduler.requests["dec"] = decoding + scheduler.running["dec"] = decoding + external = Request( + request_id="ext", prompt=[3, 4], sampling_params=SamplingParams() + ) + scheduler.requests["ext"] = external # admitted, in the external loop + with caplog.at_level(logging.INFO, logger="omlx.scheduler"): + assert scheduler.request_park_prefill() is False + assert scheduler.request_park_prefill() is False + lines = _info(caplog, "Park skipped for") + assert len(lines) == 2 + assert any("dec: decoding, not in chunked prefill" in m for m in lines) + assert any("ext: prefill runs in the external loop" in m for m in lines) + finally: + rig.close() From 7be02915d6cd5b2dda84f371bd2a21690f87e9c2 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Fri, 2 Oct 2026 03:15:58 -0600 Subject: [PATCH 15/46] fix(scheduler): keep shutdown waits on prefill commits inside the teardown 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. --- omlx/scheduler.py | 42 +++++++++-- tests/test_scheduler_prefill_commit_vlm.py | 87 ++++++++++++++++++++++ 2 files changed, 121 insertions(+), 8 deletions(-) diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 81c4131067..6c7d545121 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -1337,14 +1337,18 @@ def _is_turboquant_kv_family_cache(cache_obj: Any) -> bool: # Bounded wait for in-flight prefill commits at shutdown only; the hot path -# never waits (see Scheduler._after_commit). -PREFILL_COMMIT_SHUTDOWN_WAIT_S = 30.0 +# never waits (see Scheduler._after_commit). The three shutdown waits below add +# up to at most 20s, a third of FATAL_TEARDOWN_TIMEOUT_S, so a stuck commit can +# never eat the engine-teardown watchdog's budget before the SSD stores close. +PREFILL_COMMIT_SHUTDOWN_WAIT_S = 10.0 # A teardown deferred behind a commit that has not finished after this long # is logged once; it stays pending and is dropped at shutdown. PREFILL_COMMIT_STUCK_LOG_S = 60.0 # Extra bounded wait at shutdown for a commit worker that is inside a store # call after the cancel flag is set. Past it the stores are left unclosed. -PREFILL_COMMIT_CANCEL_WAIT_S = 10.0 +PREFILL_COMMIT_CANCEL_WAIT_S = 5.0 +# Bound on clearing the commit worker's MLX streams at shutdown. +PREFILL_COMMIT_STREAM_CLEANUP_WAIT_S = 5.0 # Bound on the final-store worker waiting for the request's in-flight commit. # Past it the final store is skipped so a stuck commit cannot hold the store # worker (and the gate slots queued behind it). @@ -2902,18 +2906,33 @@ def _async_store_cache_worker( """ self._store_cache_thread_id = threading.get_ident() if after_commit is not None: - done, _pending = concurrent.futures.wait( - [after_commit], timeout=PREFILL_COMMIT_FINAL_STORE_WAIT_S - ) + # Poll in short slices so a shutdown that cancels the commits + # frees this worker at once instead of after the full bound, + # which would hold the teardown (and its watchdog) behind it. + deadline = time.monotonic() + PREFILL_COMMIT_FINAL_STORE_WAIT_S + done = False + while not done: + left = deadline - time.monotonic() + if left <= 0 or self._commit_cancelled.is_set(): + break + done_set, _pending = concurrent.futures.wait( + [after_commit], timeout=min(1.0, left) + ) + done = bool(done_set) if not done: # Skip this final store; table and snapshot teardown stays # deferred behind the commit (scheduler thread), the gate slot # is released when the drain sees this future done. logger.warning( "Skipping final store for %s: its prefill commit did not " - "finish within %.0fs", + "finish within %.0fs%s", request_id, PREFILL_COMMIT_FINAL_STORE_WAIT_S, + ( + " (cancelled at shutdown)" + if self._commit_cancelled.is_set() + else "" + ), ) self._skipped_final_stores.add(request_id) return @@ -15876,6 +15895,11 @@ def _shutdown_prefill_commits(self) -> bool: directories and the process is going away). """ executor = self._prefill_commit_executor + teardown = getattr(self, "_engine_teardown", None) + if teardown is not None and self._prefill_commits: + # A commit that is still writing counts as persistence progress + # for the teardown watchdog; a stuck one does not. + teardown.set_phase("prefill_commits", self._store_persistence_progress) stragglers = self._wait_for_prefill_commits(PREFILL_COMMIT_SHUTDOWN_WAIT_S) store_busy = False if stragglers: @@ -15897,7 +15921,9 @@ def _shutdown_prefill_commits(self) -> bool: ) elif executor is not None: try: - executor.submit(clear_thread_streams).result(timeout=10) + executor.submit(clear_thread_streams).result( + timeout=PREFILL_COMMIT_STREAM_CLEANUP_WAIT_S + ) except Exception as e: logger.warning("Prefill commit worker stream cleanup failed: %s", e) self._deferred_teardowns.clear() diff --git a/tests/test_scheduler_prefill_commit_vlm.py b/tests/test_scheduler_prefill_commit_vlm.py index a08ff346a0..e123d2e09a 100644 --- a/tests/test_scheduler_prefill_commit_vlm.py +++ b/tests/test_scheduler_prefill_commit_vlm.py @@ -451,3 +451,90 @@ def test_no_parkable_victim_is_logged_once_per_request_with_its_reason( assert any("ext: prefill runs in the external loop" in m for m in lines) finally: rig.close() + + +# --- Teardown budget: our waits must fit inside the engine watchdog -------------- + + +def test_shutdown_commit_waits_fit_a_fraction_of_the_teardown_watchdog(): + import omlx.scheduler as sm + from omlx.utils.fatal import FATAL_TEARDOWN_TIMEOUT_S + + worst = ( + sm.PREFILL_COMMIT_SHUTDOWN_WAIT_S + + sm.PREFILL_COMMIT_CANCEL_WAIT_S + + sm.PREFILL_COMMIT_STREAM_CLEANUP_WAIT_S + ) + assert worst <= FATAL_TEARDOWN_TIMEOUT_S / 2 + + +def _stuck_final_store(rig, gated, monkeypatch): # noqa: F811 + """A final store queued behind a commit that never ends (gate held).""" + import omlx.scheduler as sm + + gate = gated(rig) + request, state = rig.start("r1", PROMPT) + while not rig.scheduler._step_prefill_chunk(state): + pass + assert gate.entered.wait(20) + finished = _decode_to_finish(rig, request, state) + rig.scheduler._cleanup_finished(finished) + fatal = [] + monkeypatch.setattr(sm, "fatal_exit", lambda msg: fatal.append(msg)) + return gate, fatal + + +@pytest.mark.parametrize("split", [False], ids=["inline-gdn"], indirect=True) +def test_shutdown_cancels_a_final_store_waiting_on_a_stuck_commit( + tmp_path, mock_tokenizer, split, monkeypatch, gated # noqa: F811 +): + import time + + import omlx.scheduler as sm + + # The final store would wait a full minute for the commit; the teardown + # watchdog allows far less. Shutdown must not inherit that wait. + monkeypatch.setattr(sm, "PREFILL_COMMIT_FINAL_STORE_WAIT_S", 60.0) + monkeypatch.setattr(sm, "PREFILL_COMMIT_SHUTDOWN_WAIT_S", 0.3) + monkeypatch.setattr(sm, "PREFILL_COMMIT_CANCEL_WAIT_S", 0.3) + monkeypatch.setattr(sm, "FATAL_TEARDOWN_TIMEOUT_S", 5.0) + rig = _rig(tmp_path, mock_tokenizer, split) + try: + gate, fatal = _stuck_final_store(rig, gated, monkeypatch) + started = time.monotonic() + rig.scheduler.shutdown() + elapsed = time.monotonic() - started + assert fatal == [] + assert elapsed < 4.0 + finally: + gate.release.set() + rig.close() + + +@pytest.mark.parametrize("split", [False], ids=["inline-gdn"], indirect=True) +def test_shutdown_reports_commit_progress_to_the_teardown_watchdog( + tmp_path, mock_tokenizer, split, monkeypatch, gated # noqa: F811 +): + import omlx.scheduler as sm + + monkeypatch.setattr(sm, "PREFILL_COMMIT_SHUTDOWN_WAIT_S", 0.3) + monkeypatch.setattr(sm, "PREFILL_COMMIT_CANCEL_WAIT_S", 0.3) + rig = _rig(tmp_path, mock_tokenizer, split) + try: + phases = [] + + class _Teardown: + def set_phase(self, phase, progress=None): + phases.append((phase, progress)) + + def remaining(self, *, mlx=False): + return 5.0 + + gate, _ = _stuck_final_store(rig, gated, monkeypatch) + rig.scheduler._engine_teardown = _Teardown() + rig.scheduler.shutdown() + waiting = [p for p in phases if p[0] == "prefill_commits"] + assert waiting and callable(waiting[0][1]) + finally: + gate.release.set() + rig.close() From 4ddc6a45bed26740aaeb89435b88ce871fabbcb3 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Mon, 5 Oct 2026 12:46:07 -0600 Subject: [PATCH 16/46] feat(memory): abort one victim instead of all when nothing is parkable 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). --- docs/TESTING.md | 2 + omlx/engine/batched.py | 8 + omlx/engine/vlm.py | 10 ++ omlx/engine_core.py | 199 ++++++++++++++++-------- omlx/process_memory_enforcer.py | 52 +++++++ omlx/request.py | 10 ++ omlx/scheduler.py | 44 +++++- omlx/server.py | 1 + omlx/settings.py | 7 + tests/test_memory_single_victim.py | 214 ++++++++++++++++++++++++++ tests/test_process_memory_enforcer.py | 155 +++++++++++++++++++ tests/test_settings.py | 26 ++++ 12 files changed, 660 insertions(+), 68 deletions(-) create mode 100644 tests/test_memory_single_victim.py diff --git a/docs/TESTING.md b/docs/TESTING.md index 7706308202..d19215d021 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -239,4 +239,6 @@ Mocked tests do not replace hardware validation: with a real model, abort a long Run `python -m pytest -q tests/test_scheduler_park.py tests/test_process_memory_enforcer.py tests/test_settings.py -k "park or Park"` to check `scheduler.memory_pressure_park` (also `OMLX_MEMORY_PRESSURE_PARK`; off by default), `scheduler.max_parks_per_request` (`OMLX_MAX_PARKS_PER_REQUEST`, default 3) and `scheduler.park_resume_ok_polls` (`OMLX_PARK_RESUME_OK_POLLS`, default 3). With the setting on, hard (non-emergency) memory pressure parks the most recent chunked-prefill request instead of aborting: it is re-queued without an error, keeps its stream, and resumes in arrival order after enough consecutive ok pressure polls, restoring the blocks that `prefill_progress_commit_blocks` committed (without it the park resumes cold). The oldest admitted request is protected, parked blocks are pinned against eviction until the resume, and the legacy abort remains for emergency pressure, nothing parkable, an exhausted park budget, or external-loop (non-chunked, VLM) and SpecPrefill prefills, which cannot be parked between steps. The scheduler cases run on a small Qwen3.5 hybrid model and compare a resumed request's output with an uninterrupted run; its prompts must stay below the tiny vocabulary of 32 ids, or the embedding read is undefined and the output is nondeterministic. +Run `python -m pytest -q tests/test_memory_single_victim.py tests/test_process_memory_enforcer.py -k "single or victim"` to check `memory.abort_single_victim` (env `OMLX_MEMORY_ABORT_SINGLE_VICTIM`, default off). On the non-emergency hard path with nothing parkable, the enforcer aborts only the live request holding the most KV (newest arrival on ties), waits for its memory to drain before choosing another, and keeps the rest running. Emergency pressure and model unload still abort everything. Off keeps the abort-all. + Mocked tests do not replace hardware validation: with a real model, run three concurrent long prompts under a ceiling too low for all of them and check that each completes with the park/resume log lines and a cached count close to the last commit, and that no client sees a memory error. diff --git a/omlx/engine/batched.py b/omlx/engine/batched.py index aaef48d678..646c89ac62 100644 --- a/omlx/engine/batched.py +++ b/omlx/engine/batched.py @@ -1573,6 +1573,14 @@ def get_cache_stats(self) -> dict[str, Any] | None: return self._engine.get_cache_stats() return None + async def abort_one_request_for_memory(self, *, spare_parked: bool = True): + """Abort the single request that frees the most memory, or None.""" + if self._engine and self._engine.engine: + return await self._engine.engine.abort_one_request_for_memory( + spare_parked=spare_parked + ) + return None + async def abort_all_requests( self, *, diff --git a/omlx/engine/vlm.py b/omlx/engine/vlm.py index 0c1d3e84ad..9b99f1d57c 100644 --- a/omlx/engine/vlm.py +++ b/omlx/engine/vlm.py @@ -6019,6 +6019,16 @@ def get_cache_stats(self) -> dict[str, Any] | None: return self._engine.get_cache_stats() return None + async def abort_one_request_for_memory(self, *, spare_parked: bool = True): + """Abort the single request that frees the most memory, or None.""" + if self.is_diffusion_model: + return None + if self._engine and self._engine.engine: + return await self._engine.engine.abort_one_request_for_memory( + spare_parked=spare_parked + ) + return None + async def abort_all_requests( self, *, diff --git a/omlx/engine_core.py b/omlx/engine_core.py index ff18d94479..5304057e08 100644 --- a/omlx/engine_core.py +++ b/omlx/engine_core.py @@ -44,7 +44,7 @@ ) from .model_registry import get_registry from .output_collector import RequestOutputCollector, RequestStreamState -from .request import Request, RequestOutput, SamplingParams +from .request import MemoryVictim, Request, RequestOutput, SamplingParams from .scheduler import Scheduler, SchedulerConfig, _sync_and_clear_cache from .utils.fatal import ( FATAL_TEARDOWN_TIMEOUT_S, @@ -842,8 +842,6 @@ async def abort_all_requests( every unload, eviction, emergency or shutdown path must abort them, or they are orphaned (or block the unload from ever draining). """ - from .utils.proc_memory import get_phys_footprint - # Only abort requests not already finished or pending abort. The # enforcer calls this once per poll (1s) while pressure persists; a # deferred abort can take many seconds to drain (it executes at the @@ -869,6 +867,53 @@ async def abort_all_requests( and rid not in pending_aborts and not (spare_parked and callable(is_parked) and is_parked(rid) is True) ] + ctx = self._memory_abort_context(reason) + for rid in request_ids: + self.scheduler.abort_request(rid) + self._emit_memory_abort(rid, ctx, reason, error_code) + self._mark_request_finished(rid) + if request_ids: + if reason is None: + logger.warning( + f"Aborted {len(request_ids)} requests due to memory pressure" + ) + else: + logger.warning("Aborted %d requests: %s", len(request_ids), reason) + self._wake_engine_loop() + return len(request_ids) + + async def abort_one_request_for_memory( + self, *, spare_parked: bool = True + ) -> MemoryVictim | None: + """Abort the single live request that frees the most memory. + + The victim is chosen by the scheduler (largest live KV, newest arrival + on ties) and receives the same error frame ``abort_all_requests`` + sends under memory pressure; every other request keeps running. + Returns the victim, or None when nothing live can be aborted. + """ + sched = self.scheduler + select = getattr(sched, "select_memory_victim", None) + if sched is None or not callable(select): + return None + victim = select(spare_parked=spare_parked) + if victim is None: + return None + rid = victim.request_id + # Only a request with a client attached (and not already finished) is + # worth aborting: otherwise the abort frees nothing observable. + if rid not in self._output_collectors or rid in self._finished_at: + return None + sched.abort_request(rid) + self._emit_memory_abort(rid, self._memory_abort_context(None), None, None) + self._mark_request_finished(rid) + self._wake_engine_loop() + return victim + + def _memory_abort_context(self, reason: str | None) -> dict[str, Any]: + """Measured usage, limits and advice behind a memory-pressure abort.""" + from .utils.proc_memory import get_phys_footprint + ceiling = 0 watermark = 0 sched = self.scheduler @@ -898,73 +943,84 @@ async def abort_all_requests( ) advice = f"{advice}." ceiling_label = f"{binding} ceiling" if binding != "effective" else "ceiling" - for rid in request_ids: - self.scheduler.abort_request(rid) - collector = self._output_collectors.get(rid) - if collector is not None: - # Name the watermark that actually tripped; printing only the - # ceiling reads as "usage below limit yet aborted" (#2321). - if reason is not None: - error_msg = reason - elif watermark > 0 and ceiling > 0: - error_msg = ( - f"Request aborted: process memory limit exceeded " - f"(usage {usage_gb:.1f} GB, abort threshold " - f"(hard watermark) {watermark_gb:.1f} GB, " - f"{ceiling_label} {ceiling_gb:.1f} GB). " - f"{advice}" - ) - elif ceiling > 0: - error_msg = ( - f"Request aborted: process memory limit exceeded " - f"(usage {usage_gb:.1f} GB, " - f"{ceiling_label} {ceiling_gb:.1f} GB). " - f"{advice}" - ) - else: - error_msg = ( - f"Request aborted: process memory limit exceeded " - f"(usage {usage_gb:.1f} GB). " - f"{advice}" - ) - collector.put( - RequestOutput( - request_id=rid, - finished=True, - finish_reason="error", - new_text=f"\n\n[Error: {error_msg}]", - error=error_msg, - # Without a code this surfaced as a bare RuntimeError: - # the JSON keepalive wrapper never saw a memory error, - # so the response generator died mid-body and the - # client got a truncated read plus a 500 traceback - # instead of the same actionable 400 the pre-flight - # guard returns. - error_code=error_code or "prefill_memory_aborted", - error_metadata={ - "request_id": rid, - # Only the limit is reported: the exception's - # estimated_bytes means "predicted peak", and this - # abort fires on measured usage, which the message - # already states. - "limit_bytes": ( - watermark or ceiling or None - if reason is None - else None - ), - }, - ) + return { + "usage_gb": usage_gb, + "ceiling": ceiling, + "watermark": watermark, + "ceiling_gb": ceiling_gb, + "watermark_gb": watermark_gb, + "ceiling_label": ceiling_label, + "advice": advice, + } + + def _emit_memory_abort( + self, + rid: str, + ctx: dict[str, Any], + reason: str | None, + error_code: str | None, + ) -> None: + """Send the memory-abort error frame to ``rid``'s consumer.""" + usage_gb = ctx["usage_gb"] + ceiling = ctx["ceiling"] + watermark = ctx["watermark"] + ceiling_gb = ctx["ceiling_gb"] + watermark_gb = ctx["watermark_gb"] + ceiling_label = ctx["ceiling_label"] + advice = ctx["advice"] + collector = self._output_collectors.get(rid) + if collector is not None: + # Name the watermark that actually tripped; printing only the + # ceiling reads as "usage below limit yet aborted" (#2321). + if reason is not None: + error_msg = reason + elif watermark > 0 and ceiling > 0: + error_msg = ( + f"Request aborted: process memory limit exceeded " + f"(usage {usage_gb:.1f} GB, abort threshold " + f"(hard watermark) {watermark_gb:.1f} GB, " + f"{ceiling_label} {ceiling_gb:.1f} GB). " + f"{advice}" ) - self._mark_request_finished(rid) - if request_ids: - if reason is None: - logger.warning( - f"Aborted {len(request_ids)} requests due to memory pressure" + elif ceiling > 0: + error_msg = ( + f"Request aborted: process memory limit exceeded " + f"(usage {usage_gb:.1f} GB, " + f"{ceiling_label} {ceiling_gb:.1f} GB). " + f"{advice}" ) else: - logger.warning("Aborted %d requests: %s", len(request_ids), reason) - self._wake_engine_loop() - return len(request_ids) + error_msg = ( + f"Request aborted: process memory limit exceeded " + f"(usage {usage_gb:.1f} GB). " + f"{advice}" + ) + collector.put( + RequestOutput( + request_id=rid, + finished=True, + finish_reason="error", + new_text=f"\n\n[Error: {error_msg}]", + error=error_msg, + # Without a code this surfaced as a bare RuntimeError: + # the JSON keepalive wrapper never saw a memory error, + # so the response generator died mid-body and the + # client got a truncated read plus a 500 traceback + # instead of the same actionable 400 the pre-flight + # guard returns. + error_code=error_code or "prefill_memory_aborted", + error_metadata={ + "request_id": rid, + # Only the limit is reported: the exception's + # estimated_bytes means "predicted peak", and this + # abort fires on measured usage, which the message + # already states. + "limit_bytes": ( + watermark or ceiling or None if reason is None else None + ), + }, + ) + ) def _mark_request_finished(self, request_id: str) -> None: """Signal the consumer a request finished and stamp the finish time. @@ -1482,6 +1538,15 @@ async def abort_request(self, request_id: str) -> bool: return False return await engine.abort_request(request_id) + async def abort_one_request_for_memory( + self, *, spare_parked: bool = True + ) -> MemoryVictim | None: + """Abort the single request that frees the most memory.""" + engine = getattr(self, "engine", None) + if engine is None: + return None + return await engine.abort_one_request_for_memory(spare_parked=spare_parked) + async def abort_all_requests( self, *, diff --git a/omlx/process_memory_enforcer.py b/omlx/process_memory_enforcer.py index 32ecf83c61..f4646146b7 100644 --- a/omlx/process_memory_enforcer.py +++ b/omlx/process_memory_enforcer.py @@ -401,6 +401,7 @@ def __init__( hard_threshold: float | None = None, prefill_safe_zone_ratio: float = 0.89, prefill_min_chunk_tokens: int = 256, + abort_single_victim: bool = False, ): """ Initialize the process memory enforcer. @@ -430,6 +431,8 @@ def __init__( prefill_safe_zone_ratio: Fraction of hard cap below which prefill runs at full chunk size; above triggers adaptive shrink. prefill_min_chunk_tokens: Floor for adaptive shrink. + abort_single_victim: On the non-emergency hard path with nothing + parkable, abort one victim instead of every request. """ self._engine_pool = engine_pool self._memory_guard_tier = self._normalize_tier(memory_guard_tier) @@ -454,6 +457,7 @@ def __init__( self._prefill_headroom_safety = self._get_prefill_headroom_safety() self._prefill_safe_zone_ratio = prefill_safe_zone_ratio self._prefill_min_chunk_tokens = prefill_min_chunk_tokens + self._single_victim_on = bool(abort_single_victim) self._task: asyncio.Task | None = None self._loop: asyncio.AbstractEventLoop | None = None self._wake_event: asyncio.Event | None = None @@ -1586,6 +1590,40 @@ async def _abort_all_requests(engine: Any, *, spare_parked: bool) -> Any: except TypeError: return await engine.abort_all_requests() + def _abort_single_victim_enabled(self) -> bool: + """``memory.abort_single_victim`` (default off). + + Off keeps the legacy abort-all on the non-emergency hard path. + """ + return self._single_victim_on + + async def _abort_single_victim(self, engine: Any, model_id: str) -> Any: + """Abort the one request freeing the most memory; None means fall back. + + Returns None when the switch is off, the engine has no such hook, or + no live request can be chosen, so the caller aborts everything as + before. At most one victim per call, so the next poll re-measures + before another request is sacrificed. + """ + if not self._abort_single_victim_enabled(): + return None + abort_one = getattr(engine, "abort_one_request_for_memory", None) + if not callable(abort_one): + return None + victim = await abort_one(spare_parked=True) + if victim is None: + return None + logger.warning( + "Hard memory pressure: aborted 1 victim %s (%d tokens, ~%.1f GB) " + "on '%s'; %d request(s) kept", + victim.request_id, + victim.tokens, + victim.est_bytes / 1024**3, + model_id, + victim.kept, + ) + return victim + async def _abort_loaded_requests_for_memory_emergency(self) -> int: """Abort active requests on loaded models without unloading them.""" aborted_total = 0 @@ -1961,6 +1999,20 @@ async def _check_and_enforce(self) -> None: # loaded and lets parked requests resume; an # emergency unload must abort them, or they keep # the engine non-idle and the unload never drains. + # Deliberate safety brake: only the non-emergency + # hard path narrows to one victim. The emergency + # path (beyond the ceiling) and model unload keep + # abort-all, since a half-measure there risks the + # process being killed for memory. + single = ( + None + if emergency + else await self._abort_single_victim( + entry.engine, busy_victim + ) + ) + if single is not None: + break aborted = await self._abort_all_requests( entry.engine, spare_parked=not emergency ) diff --git a/omlx/request.py b/omlx/request.py index adfa77c4c4..62b21ac702 100644 --- a/omlx/request.py +++ b/omlx/request.py @@ -95,6 +95,16 @@ def __post_init__(self): self.stop_token_ids = [] +@dataclass(frozen=True) +class MemoryVictim: + """The one request a memory-pressure abort chose, and what it held.""" + + request_id: str + tokens: int # live KV tokens (prompt + generated, or prefilled so far) + est_bytes: int # estimated KV bytes freed (0 when no estimator is wired) + kept: int # live requests left running + + @dataclass class Request: """ diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 6c7d545121..042b5cce3c 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -80,7 +80,13 @@ from .prefill_commit_executor import DaemonCommitExecutor as _DaemonCommitExecutor from .prefill_progress import get_prefill_tracker from .prefill_transient_tracker import PrefillTransientTracker -from .request import Request, RequestOutput, RequestStatus, SamplingParams +from .request import ( + MemoryVictim, + Request, + RequestOutput, + RequestStatus, + SamplingParams, +) from .speculative.processing_sampler import ( MTPProcessingSampler, MTPProcessorContractError, @@ -12037,6 +12043,42 @@ def _park_hold_applies(self, head: "Request") -> bool: return self._polls_since_resume < need return True + def select_memory_victim(self, *, spare_parked: bool = True) -> MemoryVictim | None: + """Pick the one live request whose abort frees the most memory. + + Largest live KV footprint first (a decoding request holds prompt plus + generated tokens, a chunked prefill what it has computed so far); the + most recent arrival breaks ties, since it has lost the least work. + Parked requests hold no live memory and are spared by default, as are + queued requests with no KV and requests already pending an abort. + Returns None when nothing live can be chosen. Read-only: the caller + aborts the victim. + """ + pending = set(self._pending_abort_ids) + prefilling_ids = {r.request_id for r in self.prefilling} + live: list[tuple[int, float, str]] = [] + for rid, request in list(self.requests.items()): + if rid in pending: + continue + if spare_parked and self.is_request_parked(rid): + continue + if rid in self.running: + tokens = request.num_tokens + elif rid in prefilling_ids or rid in self._prefill_states: + tokens = request.num_computed_tokens + else: + continue + if tokens > 0: + live.append((tokens, request.arrival_time, rid)) + if not live: + return None + tokens, _, rid = max(live, key=lambda item: (item[0], item[1])) + monitor = self.memory_monitor + est_bytes = ( + int(monitor.estimate_prompt_kv_bytes(tokens)) if monitor is not None else 0 + ) + return MemoryVictim(rid, tokens, est_bytes, kept=len(live) - 1) + def is_request_parked(self, request_id: str) -> bool: """Whether the request is currently parked (holds no live memory).""" request = self.requests.get(request_id) diff --git a/omlx/server.py b/omlx/server.py index ee0aacea6e..ce05e4a098 100644 --- a/omlx/server.py +++ b/omlx/server.py @@ -595,6 +595,7 @@ async def _bonjour_supervisor() -> None: hard_threshold=memory_settings.hard_threshold, prefill_safe_zone_ratio=memory_settings.prefill_safe_zone_ratio, prefill_min_chunk_tokens=memory_settings.prefill_min_chunk_tokens, + abort_single_victim=memory_settings.abort_single_victim, ) _server_state.process_memory_enforcer = enforcer _server_state.engine_pool._process_memory_enforcer = enforcer diff --git a/omlx/settings.py b/omlx/settings.py index b468b08366..0441bc7a84 100644 --- a/omlx/settings.py +++ b/omlx/settings.py @@ -611,6 +611,9 @@ class MemorySettings: # aborted via the same cleanup path the hard-limit RuntimeError uses. prefill_safe_zone_ratio: float = 0.80 prefill_min_chunk_tokens: int = 32 + # On the non-emergency hard path with nothing parkable, abort only the + # live request holding the most KV instead of every request. + abort_single_victim: bool = False def to_dict(self) -> dict[str, Any]: """Convert to dictionary.""" @@ -622,6 +625,7 @@ def to_dict(self) -> dict[str, Any]: "hard_threshold": self.hard_threshold, "prefill_safe_zone_ratio": self.prefill_safe_zone_ratio, "prefill_min_chunk_tokens": self.prefill_min_chunk_tokens, + "abort_single_victim": self.abort_single_victim, } @classmethod @@ -640,6 +644,7 @@ def from_dict(cls, data: dict[str, Any]) -> MemorySettings: hard_threshold=float(data.get("hard_threshold", 0.95)), prefill_safe_zone_ratio=float(data.get("prefill_safe_zone_ratio", 0.80)), prefill_min_chunk_tokens=int(data.get("prefill_min_chunk_tokens", 32)), + abort_single_victim=data.get("abort_single_victim") is True, ) @@ -1299,6 +1304,8 @@ def _apply_env_overrides(self) -> None: f"Invalid OMLX_PREFILL_PROGRESS_COMMIT_BLOCKS value: " f"{commit_blocks}" ) + if single := os.getenv("OMLX_MEMORY_ABORT_SINGLE_VICTIM"): + self.memory.abort_single_victim = single.lower() in ("true", "1", "yes") if park := os.getenv("OMLX_MEMORY_PRESSURE_PARK"): self.scheduler.memory_pressure_park = park.lower() in ("true", "1", "yes") for env_name, attr in ( diff --git a/tests/test_memory_single_victim.py b/tests/test_memory_single_victim.py new file mode 100644 index 0000000000..baf34c20b3 --- /dev/null +++ b/tests/test_memory_single_victim.py @@ -0,0 +1,214 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Single-victim memory abort: pick one request instead of aborting them all. + +Covers the scheduler's victim choice (largest live KV, newest arrival breaks +ties, parked and KV-less requests never chosen) and the engine's abort of that +one request, which must hand its client the same error frame as the abort-all +path. +""" + +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import pytest + +from omlx.engine_core import EngineCore +from omlx.request import MemoryVictim, Request, RequestStatus, SamplingParams +from omlx.scheduler import Scheduler + +GB = 1024**3 + + +def _req(rid, prompt_tokens, output_tokens=0, arrival=0.0, parked=False): + request = Request( + request_id=rid, + prompt=[1] * prompt_tokens, + sampling_params=SamplingParams(max_tokens=64), + arrival_time=arrival, + ) + request.num_prompt_tokens = prompt_tokens + request.output_token_ids = [2] * output_tokens + request.num_computed_tokens = prompt_tokens + output_tokens + request.status = RequestStatus.RUNNING + request.parked = parked + return request + + +def _fake_scheduler(running=(), prefilling=(), waiting=(), pending=(), monitor=None): + """The attributes ``Scheduler.select_memory_victim`` reads.""" + everything = [*running, *prefilling, *waiting] + fake = SimpleNamespace( + requests={r.request_id: r for r in everything}, + running={r.request_id: r for r in running}, + prefilling=list(prefilling), + waiting=list(waiting), + _pending_abort_ids=set(pending), + _prefill_states={r.request_id: object() for r in prefilling}, + memory_monitor=monitor, + ) + fake.is_request_parked = lambda rid: bool(fake.requests[rid].parked) + return fake + + +def _select(fake, **kwargs): + return Scheduler.select_memory_victim(fake, **kwargs) + + +class TestSelectMemoryVictim: + def test_largest_live_kv_is_chosen_among_three_decoding_requests(self): + fake = _fake_scheduler( + running=[ + _req("small", 1_000, 10, arrival=1.0), + _req("big", 90_000, 500, arrival=2.0), + _req("mid", 30_000, 200, arrival=3.0), + ] + ) + + victim = _select(fake) + + assert victim.request_id == "big" + assert victim.tokens == 90_500 + assert victim.kept == 2 + + def test_tie_goes_to_the_most_recent_arrival(self): + fake = _fake_scheduler( + running=[ + _req("old", 5_000, 0, arrival=1.0), + _req("new", 5_000, 0, arrival=9.0), + _req("mid", 5_000, 0, arrival=4.0), + ] + ) + + assert _select(fake).request_id == "new" + + def test_a_prefilling_request_counts_by_computed_tokens(self): + prefill = _req("pf", 200_000, 0, arrival=2.0) + prefill.num_computed_tokens = 120_000 + fake = _fake_scheduler( + running=[_req("dec", 50_000, 100, arrival=1.0)], prefilling=[prefill] + ) + + victim = _select(fake) + + assert victim.request_id == "pf" + assert victim.tokens == 120_000 + + def test_parked_requests_are_never_chosen(self): + fake = _fake_scheduler( + running=[_req("live", 1_000, 0, arrival=1.0)], + waiting=[_req("parked", 150_000, 0, arrival=2.0, parked=True)], + ) + + assert _select(fake).request_id == "live" + + def test_requests_without_live_kv_are_never_chosen(self): + waiting = _req("queued", 10_000, 0, arrival=5.0) + waiting.num_computed_tokens = 0 + fake = _fake_scheduler(waiting=[waiting]) + + assert _select(fake) is None + + def test_a_request_with_a_pending_abort_is_skipped(self): + fake = _fake_scheduler( + running=[ + _req("gone", 90_000, 0, arrival=1.0), + _req("live", 1_000, 0, arrival=2.0), + ], + pending={"gone"}, + ) + + victim = _select(fake) + + assert victim.request_id == "live" + assert victim.kept == 0 + + def test_estimated_bytes_use_the_kv_estimator_when_available(self): + monitor = SimpleNamespace(estimate_prompt_kv_bytes=lambda n: n * 1000.0) + fake = _fake_scheduler(running=[_req("a", 2_000, 0)], monitor=monitor) + + assert _select(fake).est_bytes == 2_000_000 + + +def _engine(scheduler, collectors): + engine = object.__new__(EngineCore) + engine.scheduler = scheduler + engine._output_collectors = collectors + engine._finished_at = {} + engine._finished_events = {} + engine._closed = False + engine._mark_request_finished = lambda rid: engine._finished_at.setdefault(rid, 1.0) + engine._wake_engine_loop = lambda: None + return engine + + +def _scheduler_for_engine(victim_rid, kept=2): + sched = MagicMock() + sched._pending_abort_ids = set() + sched._memory_hard_limit_bytes = 100 * GB + sched._memory_hard_watermark_bytes = 95 * GB + sched.is_request_parked.return_value = False + sched.select_memory_victim.return_value = ( + None + if victim_rid is None + else MemoryVictim(victim_rid, tokens=90_000, est_bytes=6 * GB, kept=kept) + ) + return sched + + +class TestEngineAbortOneRequestForMemory: + @pytest.mark.asyncio + async def test_only_the_victim_is_aborted_and_the_others_keep_running(self): + sched = _scheduler_for_engine("big") + collectors = {rid: MagicMock() for rid in ("big", "b", "c")} + engine = _engine(sched, collectors) + + with patch("omlx.utils.proc_memory.get_phys_footprint", return_value=97 * GB): + victim = await engine.abort_one_request_for_memory() + + assert victim.request_id == "big" + sched.abort_request.assert_called_once_with("big") + collectors["big"].put.assert_called_once() + collectors["b"].put.assert_not_called() + collectors["c"].put.assert_not_called() + assert set(engine._finished_at) == {"big"} + + @pytest.mark.asyncio + async def test_victim_gets_the_same_error_frame_as_abort_all(self): + with patch("omlx.utils.proc_memory.get_phys_footprint", return_value=97 * GB): + one_sched = _scheduler_for_engine("r") + one = {"r": MagicMock()} + await _engine(one_sched, one).abort_one_request_for_memory() + + all_sched = _scheduler_for_engine(None) + all_sched._pending_abort_ids = set() + every = {"r": MagicMock()} + await _engine(all_sched, every).abort_all_requests() + + single = one["r"].put.call_args.args[0] + legacy = every["r"].put.call_args.args[0] + assert single.finished is True + assert single.finish_reason == legacy.finish_reason == "error" + assert single.error_code == legacy.error_code == "prefill_memory_aborted" + assert single.error == legacy.error + assert "process memory limit exceeded" in single.error + assert single.new_text == legacy.new_text + assert single.error_metadata == legacy.error_metadata + + @pytest.mark.asyncio + async def test_no_victim_aborts_nothing_and_returns_none(self): + sched = _scheduler_for_engine(None) + collectors = {"a": MagicMock()} + engine = _engine(sched, collectors) + + assert await engine.abort_one_request_for_memory() is None + + sched.abort_request.assert_not_called() + collectors["a"].put.assert_not_called() + + @pytest.mark.asyncio + async def test_a_victim_without_a_collector_is_not_reported(self): + sched = _scheduler_for_engine("ghost") + engine = _engine(sched, {"other": MagicMock()}) + + assert await engine.abort_one_request_for_memory() is None + sched.abort_request.assert_not_called() diff --git a/tests/test_process_memory_enforcer.py b/tests/test_process_memory_enforcer.py index 244ce287f2..baee873477 100644 --- a/tests/test_process_memory_enforcer.py +++ b/tests/test_process_memory_enforcer.py @@ -3600,3 +3600,158 @@ async def test_every_poll_reports_its_level_to_the_scheduler(self, enforcer): await self._tick(enforcer, usage=96 * 1024**3) scheduler.note_pressure_poll.assert_called_with("hard") assert scheduler.note_pressure_poll.call_count == 2 + + +class TestSingleVictimFallback: + """Hard pressure with nothing parkable aborts one victim, not every request. + + The emergency path (beyond the ceiling) and model unload keep abort-all as + a deliberate safety brake. ``memory.abort_single_victim`` off restores + the legacy abort-all on the hard path. + """ + + @pytest.fixture + def enforcer(self, mock_engine_pool): + # Hard watermark (95 GB) below the ceiling (100 GB): hard is not + # emergency until usage passes the ceiling by the emergency margin. + return _make_enforcer( + mock_engine_pool, + ceiling=100 * 1024**3, + soft_threshold=0.85, + hard_threshold=0.95, + ) + + @staticmethod + def _engine(victims): + from omlx.request import MemoryVictim + + engine = MagicMock() + engine.has_active_requests.return_value = False + engine.abort_all_requests = AsyncMock(return_value=3) + engine.abort_one_request_for_memory = AsyncMock( + side_effect=[ + MemoryVictim(rid, 90_000, 6 * 1024**3, kept) for rid, kept in victims + ] + + [None] + ) + return engine + + @staticmethod + def _busy(enforcer, engine): + entry = _make_entry("big-model", engine=engine) + entry.in_use = 1 + enforcer._engine_pool._entries = {"big-model": entry} + enforcer._engine_pool._find_lru_victim.return_value = None + return entry + + @staticmethod + async def _tick(enforcer, usage_gb): + with patch("omlx.process_memory_enforcer.mx") as mock_mx: + mock_mx.get_active_memory.side_effect = _cycling([usage_gb * 1024**3]) + await enforcer._check_and_enforce() + + @pytest.mark.asyncio + async def test_hard_pressure_aborts_exactly_one_victim( + self, enforcer, monkeypatch, caplog + ): + enforcer._single_victim_on = True + engine = self._engine([("req-big", 2)]) + entry = self._busy(enforcer, engine) + + with caplog.at_level("WARNING"): + await self._tick(enforcer, 97) + + engine.abort_one_request_for_memory.assert_awaited_once_with(spare_parked=True) + engine.abort_all_requests.assert_not_awaited() + assert entry.engine is engine + assert entry.pending_unload_reason is None + assert "aborted 1 victim req-big (90000 tokens" in caplog.text + assert "2 request(s) kept" in caplog.text + assert "'big-model'" in caplog.text + + @pytest.mark.asyncio + async def test_persisting_pressure_aborts_one_more_victim_per_poll( + self, enforcer, monkeypatch + ): + enforcer._single_victim_on = True + engine = self._engine([("first", 2), ("second", 1)]) + self._busy(enforcer, engine) + + await self._tick(enforcer, 97) + assert engine.abort_one_request_for_memory.await_count == 1 + + await self._tick(enforcer, 97) + assert engine.abort_one_request_for_memory.await_count == 2 + engine.abort_all_requests.assert_not_awaited() + + @pytest.mark.asyncio + async def test_recovered_pressure_aborts_no_second_victim( + self, enforcer, monkeypatch + ): + enforcer._single_victim_on = True + engine = self._engine([("first", 2), ("second", 1)]) + self._busy(enforcer, engine) + + await self._tick(enforcer, 97) + await self._tick(enforcer, 1) + + assert engine.abort_one_request_for_memory.await_count == 1 + + @pytest.mark.asyncio + async def test_emergency_still_aborts_everything(self, enforcer, monkeypatch): + enforcer._single_victim_on = True + engine = self._engine([("req-big", 2)]) + entry = self._busy(enforcer, engine) + + await self._tick(enforcer, 103) + + engine.abort_all_requests.assert_awaited_once_with(spare_parked=False) + engine.abort_one_request_for_memory.assert_not_awaited() + assert entry.pending_unload_reason == "hard memory pressure" + + @pytest.mark.asyncio + async def test_flag_off_keeps_the_legacy_abort_all(self, enforcer, monkeypatch): + enforcer._single_victim_on = False + engine = self._engine([("req-big", 2)]) + self._busy(enforcer, engine) + + await self._tick(enforcer, 97) + + engine.abort_all_requests.assert_awaited_once_with(spare_parked=True) + engine.abort_one_request_for_memory.assert_not_awaited() + + @pytest.mark.asyncio + async def test_flag_unset_keeps_the_legacy_abort_all(self, enforcer, monkeypatch): + engine = self._engine([("req-big", 2)]) + self._busy(enforcer, engine) + + await self._tick(enforcer, 97) + + engine.abort_all_requests.assert_awaited_once() + engine.abort_one_request_for_memory.assert_not_awaited() + + @pytest.mark.asyncio + async def test_no_victim_falls_back_to_abort_all_sparing_parked( + self, enforcer, monkeypatch + ): + enforcer._single_victim_on = True + engine = self._engine([]) + self._busy(enforcer, engine) + + await self._tick(enforcer, 97) + + engine.abort_one_request_for_memory.assert_awaited_once() + engine.abort_all_requests.assert_awaited_once_with(spare_parked=True) + + @pytest.mark.asyncio + async def test_engine_without_the_hook_falls_back_to_abort_all( + self, enforcer, monkeypatch + ): + enforcer._single_victim_on = True + engine = _ParkedOnlyEngine() + self._busy(enforcer, engine) + + with patch.object(enforcer, "_current_usage_bytes", return_value=97 * 1024**3): + await enforcer._check_and_enforce() + + assert engine.calls == [True] diff --git a/tests/test_settings.py b/tests/test_settings.py index 5def31bfa6..4ce0c57f06 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -3358,3 +3358,29 @@ def test_inference_opt_in_keeps_network_management_requirements( allow_unauthenticated_inference=True, ) assert any("non-loopback" in error for error in settings.validate()) + + +class TestAbortSingleVictimSetting: + """memory.abort_single_victim: off by default, round-trips, env override.""" + + def test_defaults_off_and_round_trips(self): + assert MemorySettings.from_dict({}).abort_single_victim is False + on = MemorySettings.from_dict({"abort_single_victim": True}) + assert on.abort_single_victim is True + assert on.to_dict()["abort_single_victim"] is True + junk = MemorySettings.from_dict({"abort_single_victim": "yes"}) + assert junk.abort_single_victim is False + + def test_env_override(self, tmp_path): + env = {"OMLX_MEMORY_ABORT_SINGLE_VICTIM": "true"} + with patch.dict(os.environ, env, clear=False): + settings = GlobalSettings.load(base_path=tmp_path) + assert settings.memory.abort_single_victim is True + + def test_reaches_the_enforcer(self): + from omlx.process_memory_enforcer import ProcessMemoryEnforcer + + default = ProcessMemoryEnforcer(engine_pool=MagicMock()) + assert default._abort_single_victim_enabled() is False + on = ProcessMemoryEnforcer(engine_pool=MagicMock(), abort_single_victim=True) + assert on._abort_single_victim_enabled() is True From 4b30e60c3d57756951e87b70b284846ae07b0a2e Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Mon, 5 Oct 2026 13:52:05 -0600 Subject: [PATCH 17/46] feat(cache): domain-isolated exact-prefix chains and exact-chain pins 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. --- omlx/cache/prefix_cache.py | 88 ++++++++++++++++++++++++++++-------- omlx/scheduler.py | 41 ++++++++++++++--- tests/test_prefix_cache.py | 79 ++++++++++++++++++++++++++++++++ tests/test_scheduler_park.py | 74 ++++++++++++++++++++++++++++++ 4 files changed, 257 insertions(+), 25 deletions(-) diff --git a/omlx/cache/prefix_cache.py b/omlx/cache/prefix_cache.py index d4f9c8e5c4..695e91b693 100644 --- a/omlx/cache/prefix_cache.py +++ b/omlx/cache/prefix_cache.py @@ -196,6 +196,30 @@ def _wrap_cachelist_sub_marker( _EXACT_PREFIX_TERMINAL_KEY = "specprefill-static-exact-v1" _EXACT_PREFIX_SPLIT_BLOCK_KEY = "specprefill-static-exact-split-v1" +# Exact chains stored under a caller domain (for example one request's paused +# decode) carry the domain in every block hash, so two requests with identical +# tokens never share or overwrite each other's chain, and none of its blocks +# enter ordinary prefix matching. +_EXACT_PREFIX_DOMAIN_KEY = "exact-prefix-domain-v1" + + +def _exact_block_extra_keys( + *, + terminal: bool, + split_gdn_layout: bool, + domain_key: tuple[str, ...] | None, +) -> tuple[Any, ...] | None: + """Hash extra keys of one exact-prefix block (store and fetch agree).""" + if domain_key is not None: + domain = (_EXACT_PREFIX_DOMAIN_KEY, *domain_key) + return (*domain, _EXACT_PREFIX_TERMINAL_KEY) if terminal else domain + if split_gdn_layout: + return (_EXACT_PREFIX_SPLIT_BLOCK_KEY,) + if terminal: + return (_EXACT_PREFIX_TERMINAL_KEY,) + return None + + _POOLING_CACHE_SUB_CLASSES = frozenset({"PoolingCache", "BatchPoolingCache"}) # Sentinel: the CacheList restore chain carries no PoolingCacheDelta # markers, so the caller restores the boundary member last-block-wins. @@ -900,6 +924,7 @@ def store_cache( _store_exact_terminal: bool = False, _store_tail_terminal: bool = False, cache_covers_suffix_only: bool = False, + _exact_domain_key: tuple[str, ...] | None = None, ) -> BlockTable | None: """ Store computed cache for future reuse. @@ -932,6 +957,8 @@ def store_cache( commit during prefill), never the whole sequence. Without this a window longer than the stored prefix is indistinguishable from a full-sequence cache. + _exact_domain_key: Exact-prefix mode only: isolate the whole + chain under this caller domain (see store_exact_prefix). Returns: BlockTable for the stored cache, or None on failure @@ -1194,19 +1221,26 @@ def store_cache( is_exact_split_block = _store_exact_terminal and split_gdn_layout is_exact_terminal = _store_exact_terminal and i == num_new_blocks - 1 + # A domain-isolated exact chain is reachable only through + # fetch_exact_prefix(): no dedup, no ordinary prefix index. + is_exact_domain_block = ( + _store_exact_terminal and _exact_domain_key is not None + ) is_tail_terminal = ( _store_tail_terminal and i == num_new_blocks - 1 and len(block_tokens) < self.block_size ) block_extra_keys: tuple[Any, ...] | None - if is_exact_split_block: - # Isolate the whole chain. Intermediate split-GDN exact-prefix - # blocks carry structural recurrent placeholders and must never - # enter ordinary partial-prefix matching. - block_extra_keys = (_EXACT_PREFIX_SPLIT_BLOCK_KEY,) - elif is_exact_terminal: - block_extra_keys = (_EXACT_PREFIX_TERMINAL_KEY,) + if is_exact_split_block or is_exact_terminal or is_exact_domain_block: + # Split-GDN exact chains are isolated as a whole: their + # intermediate blocks carry structural recurrent placeholders + # and must never enter ordinary partial-prefix matching. + block_extra_keys = _exact_block_extra_keys( + terminal=is_exact_terminal, + split_gdn_layout=split_gdn_layout, + domain_key=_exact_domain_key, + ) else: block_extra_keys = resolve_block_extra_keys( global_end, @@ -1217,7 +1251,7 @@ def store_cache( # Check if this block already exists (deduplication) if (len(block_tokens) == self.block_size or is_tail_terminal) and not ( - is_exact_terminal or is_exact_split_block + is_exact_terminal or is_exact_split_block or is_exact_domain_block ): existing_block = self.paged_cache.find_cached_block( block_tokens, @@ -1339,12 +1373,16 @@ def store_cache( len(block_tokens) == self.block_size and not is_exact_terminal and not is_exact_split_block + and not is_exact_domain_block ): self.paged_cache.register_block_hash( block, block_tokens, parent_hash, extra_keys=block_extra_keys ) elif ( - is_exact_terminal or is_exact_split_block or is_tail_terminal + is_exact_terminal + or is_exact_split_block + or is_exact_domain_block + or is_tail_terminal ) and block.block_hash is not None: # Tail blocks join the parent-keyed tail index once saved. self.paged_cache.cached_block_hash_to_block.insert( @@ -1697,6 +1735,8 @@ def store_exact_prefix( tokens: list[int], cache_data: list[Any], model_cache_config: ModelCacheConfig | None = None, + *, + domain_key: tuple[str, ...] | None = None, ) -> BlockTable | None: """Persist a complete prefix, including its exact terminal boundary. @@ -1705,6 +1745,12 @@ def store_exact_prefix( never the only durable copy. Split-GDN layouts domain-separate the whole chain and store one recurrent sidecar at the exact terminal; preceding blocks contain only KV slices and structural recurrent placeholders. + + ``domain_key`` (strings) isolates the whole chain: only a fetch with + the same domain finds it, so requests with identical tokens (or + identical image placeholder tokens over different images) never + collide. The returned table's blocks are unreferenced; a caller that + must keep the chain takes its own block refs and SSD pins. """ if not tokens or self.paged_ssd_cache is None: return None @@ -1749,6 +1795,7 @@ def store_exact_prefix( model_cache_config=model_cache_config, hot_cache_write_back=False, _store_exact_terminal=True, + _exact_domain_key=domain_key, ) if block_table is None or block_table.num_tokens != len(tokens): self.paged_cache.delete_block_table(request_id) @@ -1765,7 +1812,11 @@ def store_exact_prefix( self._exact_prefix_stores += 1 return stored_table - def _exact_prefix_hashes(self, tokens: list[int]) -> list[tuple[BlockHash, int]]: + def _exact_prefix_hashes( + self, + tokens: list[int], + domain_key: tuple[str, ...] | None = None, + ) -> list[tuple[BlockHash, int]]: """Return deterministic hashes for an exact prefix.""" block_hashes_and_token_counts: list[tuple[BlockHash, int]] = [] parent_hash: BlockHash | None = None @@ -1777,12 +1828,11 @@ def _exact_prefix_hashes(self, tokens: list[int]) -> list[tuple[BlockHash, int]] for block_start in range(0, len(tokens), self.block_size): block_tokens = tokens[block_start : block_start + self.block_size] - if split_gdn_layout: - extra_keys = (_EXACT_PREFIX_SPLIT_BLOCK_KEY,) - elif block_start == terminal_start: - extra_keys = (_EXACT_PREFIX_TERMINAL_KEY,) - else: - extra_keys = None + extra_keys = _exact_block_extra_keys( + terminal=block_start == terminal_start, + split_gdn_layout=split_gdn_layout, + domain_key=domain_key, + ) block_hash = compute_block_hash( parent_hash, block_tokens, @@ -1798,13 +1848,14 @@ def fetch_exact_prefix( self, request_id: str, tokens: list[int], + domain_key: tuple[str, ...] | None = None, ) -> BlockTable | None: """Acquire an all-or-nothing exact prefix chain from hot cache or SSD.""" if not tokens or self.paged_ssd_cache is None: return None acquired_blocks: list[CacheBlock] = [] - for block_hash, token_count in self._exact_prefix_hashes(tokens): + for block_hash, token_count in self._exact_prefix_hashes(tokens, domain_key): cached_block = self.paged_cache.cached_block_hash_to_block.get_block( block_hash ) @@ -1851,9 +1902,10 @@ def restore_exact_prefix( tokens: list[int], *, promote_to_hot_cache: bool, + domain_key: tuple[str, ...] | None = None, ) -> list[Any] | None: """Reconstruct a complete exact prefix and release temporary block refs.""" - block_table = self.fetch_exact_prefix(request_id, tokens) + block_table = self.fetch_exact_prefix(request_id, tokens, domain_key) if block_table is None: self._exact_prefix_misses += 1 return None diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 042b5cce3c..dd6bd7a1d7 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -53,7 +53,7 @@ from .cache.deepseek_v41_delta import compact_snapshot as compact_deepseek_v41_snapshot from .cache.observability import BoundarySnapshotDiagnostics, CacheRateTracker -from .cache.paged_cache import PagedCacheManager +from .cache.paged_cache import BlockTable, PagedCacheManager from .cache.pooling_delta import compact_pooling_cache_snapshot from .cache.prefix_cache import BlockAwarePrefixCache, cachelist_pm_member_plan from .decode_activity import get_decode_activity @@ -12292,23 +12292,50 @@ def _pin_parked_blocks(self, request_id: str, request: Request) -> None: table = manager.get_block_table(request_id) if not table or not table.block_ids: return + self._pin_blocks(request_id, table.block_ids) + + def _pin_exact_chain(self, request_id: str, table: BlockTable) -> bool: + """Hold a stored exact-prefix chain (all blocks or none) for a resume. + + ``store_exact_prefix`` leaves its blocks unreferenced and evictable; + a chain missing any block cannot be restored, so a partial pin would + only hold memory. Released by ``_unpin_parked``. + """ + return self._pin_blocks(request_id, table.block_ids, require_all=True) + + def _pin_blocks( + self, request_id: str, block_ids: list[int], *, require_all: bool = False + ) -> bool: + """Take one block ref per block and pin their hashes in the SSD index. + + Replaces any pins ``request_id`` already holds. A block whose metadata + is gone is skipped, or, with ``require_all``, makes the whole pin fail + and give back the refs it took. Returns whether pins are now held. + """ + manager = self.paged_cache_manager + if manager is None or not block_ids: + return False self._unpin_parked(request_id) - block_ids: list[int] = [] + pinned_ids: list[int] = [] hashes: list[bytes] = [] - for block_id in table.block_ids: + for block_id in block_ids: if not manager.increment_ref(block_id): + if require_all: + manager.release_for_eviction(pinned_ids) + return False continue - block_ids.append(block_id) + pinned_ids.append(block_id) block = manager.allocated_blocks.get(block_id) block_hash = getattr(block, "block_hash", None) if block_hash is not None: hashes.append(bytes(block_hash)) - if not block_ids: - return - self._park_pins[request_id] = _ParkPins(block_ids, hashes) + if not pinned_ids: + return False + self._park_pins[request_id] = _ParkPins(pinned_ids, hashes) ssd = self.paged_ssd_cache_manager if ssd is not None and hasattr(ssd, "pin_blocks"): ssd.pin_blocks(hashes) + return True def _unpin_parked(self, request_id: str) -> None: pins = self._park_pins.pop(request_id, None) diff --git a/tests/test_prefix_cache.py b/tests/test_prefix_cache.py index db00417f0a..bd0a9a6926 100644 --- a/tests/test_prefix_cache.py +++ b/tests/test_prefix_cache.py @@ -563,6 +563,85 @@ def test_exact_prefix_honors_global_hot_cache_only_mode(self, tmp_path): finally: ssd_manager.close() + @staticmethod + def _exact_kv(token_count: int, offset: float) -> list[dict]: + import mlx.core as mx + + keys = mx.arange(token_count, dtype=mx.float32).reshape(1, 1, token_count, 1) + return [ + { + "state": (keys + offset, keys + offset + 0.5), + "meta_state": (token_count,), + "class_name": "KVCache", + "cache_type": "KVCache", + } + ] + + def test_exact_prefix_domains_isolate_identical_token_sequences(self, tmp_path): + """Two requests with the same tokens never read each other's exact chain.""" + import mlx.core as mx + + prefix_cache, _, ssd_manager = self._make_ssd_prefix_cache( + tmp_path / "exact-domains" + ) + tokens = list(range(11)) # two full blocks plus a partial terminal + try: + for domain, offset in ((("req-a",), 0.0), (("req-b",), 100.0)): + stored = prefix_cache.store_exact_prefix( + f"store-{domain[0]}", + tokens, + self._exact_kv(len(tokens), offset), + domain_key=domain, + ) + assert stored is not None and stored.num_tokens == len(tokens) + + for domain, offset in ((("req-a",), 0.0), (("req-b",), 100.0)): + restored = prefix_cache.restore_exact_prefix( + f"restore-{domain[0]}", + tokens, + promote_to_hot_cache=False, + domain_key=domain, + ) + assert restored is not None + keys, _ = restored[0].keys_and_values() + assert keys.shape[2] == len(tokens) + expected = self._exact_kv(len(tokens), offset)[0]["state"][0] + assert mx.array_equal(keys, expected).item() + + # Another domain, or no domain at all, sees nothing. + for domain in (("req-c",), None): + assert ( + prefix_cache.restore_exact_prefix( + "restore-other", + tokens, + promote_to_hot_cache=False, + domain_key=domain, + ) + is None + ) + # Domain blocks never enter ordinary prefix matching. + table, remaining = prefix_cache.fetch_cache("ordinary", [*tokens, 30]) + assert table is None and remaining == [*tokens, 30] + finally: + ssd_manager.close() + + def test_exact_prefix_hashes_depend_on_the_domain(self, tmp_path): + prefix_cache, _, ssd_manager = self._make_ssd_prefix_cache( + tmp_path / "exact-domain-hashes" + ) + tokens = list(range(9)) + try: + plain = prefix_cache._exact_prefix_hashes(tokens) + first = prefix_cache._exact_prefix_hashes(tokens, domain_key=("a",)) + second = prefix_cache._exact_prefix_hashes(tokens, domain_key=("b",)) + assert len(plain) == len(first) == len(second) == 3 + assert not {h for h, _ in plain} & {h for h, _ in first} + assert not {h for h, _ in first} & {h for h, _ in second} + # Deterministic for the same domain. + assert first == prefix_cache._exact_prefix_hashes(tokens, domain_key=("a",)) + finally: + ssd_manager.close() + def test_store_cache_creates_block_table(self, prefix_cache): """Test store_cache creates a block table.""" tokens = [1, 2, 3, 4] # One full block diff --git a/tests/test_scheduler_park.py b/tests/test_scheduler_park.py index 9350dba771..81ceead2cd 100644 --- a/tests/test_scheduler_park.py +++ b/tests/test_scheduler_park.py @@ -559,6 +559,80 @@ def test_pinned_blocks_are_not_evicted_from_the_ssd_index_by_lru( rig.close() +def _stored_exact_chain(rig, request_id, tokens, domain): + """Prefill ``tokens`` for real and store the exact chain under ``domain``.""" + source, state = rig.start(f"{request_id}-source", tokens) + while not rig.step(state, 1): + pass + cache_data, config = rig.scheduler._extract_cache_states(state.cache) + table = rig.prefix.store_exact_prefix( + request_id, + list(tokens[:-1]), + cache_data, + model_cache_config=config, + domain_key=domain, + ) + assert table is not None and table.num_tokens == len(tokens) - 1 + return table + + +def test_an_exact_chain_stays_restorable_while_pinned_and_unpin_releases_it( + tmp_path, mock_tokenizer +): + rig = make_rig(tmp_path, mock_tokenizer) + try: + scheduler = rig.scheduler + tokens = PROMPT_A + table = _stored_exact_chain(rig, "paused", tokens, ("paused",)) + + assert scheduler._pin_exact_chain("paused", table) is True + pins = scheduler._park_pins["paused"] + assert pins.block_ids == table.block_ids + assert len(pins.hashes) == len(table.block_ids) + assert rig.ssd.pinned_block_count == len(pins.hashes) + for block_id in pins.block_ids: + assert rig.paged.allocated_blocks[block_id].ref_count >= 1 + + # An unbounded size enforcement keeps the pinned chain on disk. + rig.ssd._evict_tracked_until_size(0) + restored = rig.prefix.restore_exact_prefix( + "probe", + list(tokens[:-1]), + promote_to_hot_cache=False, + domain_key=("paused",), + ) + assert restored is not None + + scheduler._unpin_parked("paused") + assert "paused" not in scheduler._park_pins + assert rig.ssd.pinned_block_count == 0 + for block_id in pins.block_ids: + block = rig.paged.allocated_blocks.get(block_id) + assert block is None or block.ref_count == 0 + rig.ssd._evict_tracked_until_size(0) + assert all(rig.ssd._index.get(h) is None for h in pins.hashes) + finally: + rig.close() + + +def test_pinning_an_incomplete_exact_chain_takes_no_pins(tmp_path, mock_tokenizer): + """A chain whose block metadata is already gone cannot be held: fail closed.""" + rig = make_rig(tmp_path, mock_tokenizer) + try: + table = _stored_exact_chain(rig, "paused", PROMPT_A, ("paused",)) + rig.paged.allocated_blocks.pop(table.block_ids[-1]) + before = { + b: rig.paged.allocated_blocks[b].ref_count for b in table.block_ids[:-1] + } + assert rig.scheduler._pin_exact_chain("paused", table) is False + assert "paused" not in rig.scheduler._park_pins + assert rig.ssd.pinned_block_count == 0 + for block_id, ref_count in before.items(): + assert rig.paged.allocated_blocks[block_id].ref_count == ref_count + finally: + rig.close() + + # --- Teardown never blocks the MLX thread ------------------------------------------ From efd970ef0ca2d670c9a734071d62c93e30cc7eb4 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Mon, 5 Oct 2026 14:05:35 -0600 Subject: [PATCH 18/46] fix(memory): wait for a single victim to drain before choosing another 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. --- omlx/engine/batched.py | 6 ++ omlx/engine/vlm.py | 8 ++ omlx/engine_core.py | 32 ++++++- omlx/process_memory_enforcer.py | 118 ++++++++++++++++++++++++-- omlx/request.py | 3 + tests/test_memory_single_victim.py | 50 ++++++++++- tests/test_process_memory_enforcer.py | 118 +++++++++++++++++++++++++- 7 files changed, 319 insertions(+), 16 deletions(-) diff --git a/omlx/engine/batched.py b/omlx/engine/batched.py index 646c89ac62..c6c85fc23b 100644 --- a/omlx/engine/batched.py +++ b/omlx/engine/batched.py @@ -1581,6 +1581,12 @@ async def abort_one_request_for_memory(self, *, spare_parked: bool = True): ) return None + def memory_victim_pending(self, request_id: str) -> bool: + """Whether a memory victim's deferred abort has not run yet.""" + if self._engine and self._engine.engine: + return self._engine.engine.memory_victim_pending(request_id) + return False + async def abort_all_requests( self, *, diff --git a/omlx/engine/vlm.py b/omlx/engine/vlm.py index 9b99f1d57c..891861df80 100644 --- a/omlx/engine/vlm.py +++ b/omlx/engine/vlm.py @@ -6029,6 +6029,14 @@ async def abort_one_request_for_memory(self, *, spare_parked: bool = True): ) return None + def memory_victim_pending(self, request_id: str) -> bool: + """Whether a memory victim's deferred abort has not run yet.""" + if self.is_diffusion_model: + return False + if self._engine and self._engine.engine: + return self._engine.engine.memory_victim_pending(request_id) + return False + async def abort_all_requests( self, *, diff --git a/omlx/engine_core.py b/omlx/engine_core.py index 5304057e08..2819b22a56 100644 --- a/omlx/engine_core.py +++ b/omlx/engine_core.py @@ -21,7 +21,7 @@ import time import uuid from contextlib import suppress -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from typing import ( Any, AsyncIterator, @@ -890,7 +890,11 @@ async def abort_one_request_for_memory( The victim is chosen by the scheduler (largest live KV, newest arrival on ties) and receives the same error frame ``abort_all_requests`` sends under memory pressure; every other request keeps running. - Returns the victim, or None when nothing live can be aborted. + Returns the aborted victim, None when nothing live can be chosen, or + the chosen victim with ``skipped`` set ("no_client": no consumer is + attached; "already_finished": its client was already finished) when + it was not aborted. The abort itself runs at the next scheduler step; + ``memory_victim_pending`` tells when it has. """ sched = self.scheduler select = getattr(sched, "select_memory_victim", None) @@ -902,14 +906,29 @@ async def abort_one_request_for_memory( rid = victim.request_id # Only a request with a client attached (and not already finished) is # worth aborting: otherwise the abort frees nothing observable. - if rid not in self._output_collectors or rid in self._finished_at: - return None + if rid not in self._output_collectors: + return replace(victim, skipped="no_client") + if rid in self._finished_at: + return replace(victim, skipped="already_finished") sched.abort_request(rid) self._emit_memory_abort(rid, self._memory_abort_context(None), None, None) self._mark_request_finished(rid) self._wake_engine_loop() return victim + def memory_victim_pending(self, request_id: str) -> bool: + """Whether a memory victim's deferred abort has not run yet. + + True while the scheduler still queues the abort or still holds the + request (and with it the request's KV); False once it is dropped. + """ + sched = self.scheduler + if sched is None: + return False + return request_id in getattr( + sched, "_pending_abort_ids", () + ) or request_id in getattr(sched, "requests", {}) + def _memory_abort_context(self, reason: str | None) -> dict[str, Any]: """Measured usage, limits and advice behind a memory-pressure abort.""" from .utils.proc_memory import get_phys_footprint @@ -1547,6 +1566,11 @@ async def abort_one_request_for_memory( return None return await engine.abort_one_request_for_memory(spare_parked=spare_parked) + def memory_victim_pending(self, request_id: str) -> bool: + """Whether a memory victim's deferred abort has not run yet.""" + engine = getattr(self, "engine", None) + return engine is not None and engine.memory_victim_pending(request_id) + async def abort_all_requests( self, *, diff --git a/omlx/process_memory_enforcer.py b/omlx/process_memory_enforcer.py index f4646146b7..19b0437211 100644 --- a/omlx/process_memory_enforcer.py +++ b/omlx/process_memory_enforcer.py @@ -33,6 +33,7 @@ import subprocess import time from contextlib import suppress +from dataclasses import dataclass from typing import TYPE_CHECKING, Any import mlx.core as mx @@ -379,6 +380,16 @@ def preview_tier_ceilings() -> dict[str, dict[str, Any]]: return previews +@dataclass +class _DrainingVictim: + """The single victim whose memory the enforcer waits on before another.""" + + model_id: str + victim: Any # MemoryVictim + polls: int = 0 # polls since its abort was requested + executed: bool = False # its abort was seen to have run + + class ProcessMemoryEnforcer: """ Background task that enforces process-level memory limits. @@ -475,6 +486,10 @@ def __init__( # Consecutive hard-pressure polls whose abort was deferred in favor of # parking a prefill victim. See _request_scheduler_park. self._park_deferred_polls: int = 0 + # The single victim aborted on the hard path whose memory has not + # settled yet; no other victim is chosen meanwhile. See + # _abort_single_victim. + self._draining_victim: _DrainingVictim | None = None # Last value passed to mx.set_wired_limit (0 if not yet applied # or the call failed). Used by the admin dashboard to surface a # warning when the kernel iogpu.wired_limit_mb is below this. @@ -1282,6 +1297,10 @@ def _shrink_hot_cache_by( # scheduler reports a prefill victim to park (or one just parked). Bounds # the deferral if the scheduler never gets to act on the request. _PARK_DEFER_POLLS_MAX = 30 + # Max polls the next single victim waits for the previous one's abort to + # run and its memory to settle. A prefill chunk can hold the scheduler + # step for ~5 one-second polls, so this covers two chunk boundaries. + _SINGLE_VICTIM_SETTLE_MAX_POLLS = 10 def _pool_bytes(self) -> int: """MLX buffer-pool size, 0 when unreadable (mocked mx in tests).""" @@ -1600,19 +1619,47 @@ def _abort_single_victim_enabled(self) -> bool: async def _abort_single_victim(self, engine: Any, model_id: str) -> Any: """Abort the one request freeing the most memory; None means fall back. - Returns None when the switch is off, the engine has no such hook, or - no live request can be chosen, so the caller aborts everything as - before. At most one victim per call, so the next poll re-measures - before another request is sacrificed. + Returns None when the switch is off, the engine has no such hook, the + hook fails, no live request can be chosen, or the chosen one could + not be aborted (``skipped``), so the caller aborts everything as + before for this poll. The abort itself is deferred to the scheduler + step, so while the previous victim's abort is pending or its memory + has not settled (abort seen to have run, then one more poll) the + same victim is returned and nobody else is sacrificed, for at most + ``_SINGLE_VICTIM_SETTLE_MAX_POLLS`` polls. Emergency pressure never + reaches this path: it aborts everything. """ if not self._abort_single_victim_enabled(): return None abort_one = getattr(engine, "abort_one_request_for_memory", None) if not callable(abort_one): return None - victim = await abort_one(spare_parked=True) + draining = self._still_draining_victim(engine, model_id) + if draining is not None: + return draining + try: + victim = await abort_one(spare_parked=True) + except Exception as exc: # noqa: BLE001 + logger.warning( + "Single-victim abort failed on '%s': %s; falling back to " + "aborting all requests", + model_id, + exc, + ) + return None if victim is None: return None + skipped = getattr(victim, "skipped", None) + if skipped: + logger.warning( + "Single-victim abort skipped %s on '%s' (%s); falling back to " + "aborting all requests", + victim.request_id, + model_id, + skipped, + ) + return None + self._draining_victim = _DrainingVictim(model_id, victim) logger.warning( "Hard memory pressure: aborted 1 victim %s (%d tokens, ~%.1f GB) " "on '%s'; %d request(s) kept", @@ -1624,6 +1671,57 @@ async def _abort_single_victim(self, engine: Any, model_id: str) -> Any: ) return victim + def _still_draining_victim(self, engine: Any, model_id: str) -> Any: + """The previous single victim while its memory settles, else None.""" + draining = self._draining_victim + if draining is None: + return None + draining.polls += 1 + rid = draining.victim.request_id + if draining.model_id != model_id: + self._draining_victim = None + return None + if draining.polls > self._SINGLE_VICTIM_SETTLE_MAX_POLLS: + logger.warning( + "Hard memory pressure: victim %s memory did not drain within %d " + "polls on '%s'; choosing another victim", + rid, + self._SINGLE_VICTIM_SETTLE_MAX_POLLS, + model_id, + ) + self._draining_victim = None + return None + if draining.executed: + # Its abort ran and a further poll was observed: settled. + self._draining_victim = None + return None + draining.executed = not self._victim_abort_pending(engine, rid) + logger.info( + "Hard memory pressure: waiting for victim %s memory to drain on " + "'%s' (poll %d/%d, abort %s)", + rid, + model_id, + draining.polls, + self._SINGLE_VICTIM_SETTLE_MAX_POLLS, + "ran" if draining.executed else "pending", + ) + return draining.victim + + @staticmethod + def _victim_abort_pending(engine: Any, request_id: str) -> bool: + """Whether the engine still holds the victim (abort not run yet). + + An engine without the probe, or a failing probe, counts as run: the + settle poll that follows still lets its memory return. + """ + probe = getattr(engine, "memory_victim_pending", None) + if not callable(probe): + return False + try: + return probe(request_id) is True + except Exception: # noqa: BLE001 + return False + async def _abort_loaded_requests_for_memory_emergency(self) -> int: """Abort active requests on loaded models without unloading them.""" aborted_total = 0 @@ -1825,6 +1923,8 @@ async def _check_and_enforce(self) -> None: self._note_pressure_poll(new_level) if new_level != "hard": self._park_deferred_polls = 0 + # The episode ended: a later one starts without a draining victim. + self._draining_victim = None if new_level == "ok": # The pressure episode ended (drain worked or the load finished): @@ -1995,10 +2095,6 @@ async def _check_and_enforce(self) -> None: and entry.engine is not None and hasattr(entry.engine, "abort_all_requests") ): - # Only the non-emergency path keeps the model - # loaded and lets parked requests resume; an - # emergency unload must abort them, or they keep - # the engine non-idle and the unload never drains. # Deliberate safety brake: only the non-emergency # hard path narrows to one victim. The emergency # path (beyond the ceiling) and model unload keep @@ -2013,6 +2109,10 @@ async def _check_and_enforce(self) -> None: ) if single is not None: break + # Only the non-emergency path keeps the model + # loaded and lets parked requests resume; an + # emergency unload must abort them, or they keep + # the engine non-idle and the unload never drains. aborted = await self._abort_all_requests( entry.engine, spare_parked=not emergency ) diff --git a/omlx/request.py b/omlx/request.py index 62b21ac702..7257919839 100644 --- a/omlx/request.py +++ b/omlx/request.py @@ -103,6 +103,9 @@ class MemoryVictim: tokens: int # live KV tokens (prompt + generated, or prefilled so far) est_bytes: int # estimated KV bytes freed (0 when no estimator is wired) kept: int # live requests left running + # Why the chosen request was NOT aborted ("no_client", "already_finished"), + # None when it was. "No victim at all" is reported as None instead. + skipped: str | None = None @dataclass diff --git a/tests/test_memory_single_victim.py b/tests/test_memory_single_victim.py index baf34c20b3..1c3eb3c7dd 100644 --- a/tests/test_memory_single_victim.py +++ b/tests/test_memory_single_victim.py @@ -206,9 +206,55 @@ async def test_no_victim_aborts_nothing_and_returns_none(self): collectors["a"].put.assert_not_called() @pytest.mark.asyncio - async def test_a_victim_without_a_collector_is_not_reported(self): + async def test_a_victim_without_a_collector_is_reported_as_skipped(self): + """Distinct from "no victim" (None): the caller can tell them apart.""" sched = _scheduler_for_engine("ghost") engine = _engine(sched, {"other": MagicMock()}) - assert await engine.abort_one_request_for_memory() is None + victim = await engine.abort_one_request_for_memory() + + assert victim is not None and victim.request_id == "ghost" + assert victim.skipped == "no_client" sched.abort_request.assert_not_called() + + @pytest.mark.asyncio + async def test_an_already_finished_victim_is_reported_as_skipped(self): + sched = _scheduler_for_engine("done") + collectors = {"done": MagicMock()} + engine = _engine(sched, collectors) + engine._finished_at["done"] = 1.0 + + victim = await engine.abort_one_request_for_memory() + + assert victim is not None and victim.skipped == "already_finished" + sched.abort_request.assert_not_called() + collectors["done"].put.assert_not_called() + + @pytest.mark.asyncio + async def test_an_aborted_victim_is_not_skipped(self): + sched = _scheduler_for_engine("big") + engine = _engine(sched, {"big": MagicMock()}) + + with patch("omlx.utils.proc_memory.get_phys_footprint", return_value=97 * GB): + victim = await engine.abort_one_request_for_memory() + + assert victim.skipped is None + + +class TestMemoryVictimPending: + """The enforcer asks whether a victim's deferred abort has run yet.""" + + def test_pending_until_the_scheduler_has_run_the_abort(self): + sched = SimpleNamespace(_pending_abort_ids={"big"}, requests={"big": 1}) + engine = _engine(sched, {}) + assert engine.memory_victim_pending("big") is True + + sched._pending_abort_ids.clear() # step popped it, abort in progress + assert engine.memory_victim_pending("big") is True + + sched.requests.clear() # _do_abort_request dropped the request + assert engine.memory_victim_pending("big") is False + + def test_no_scheduler_means_nothing_pending(self): + engine = _engine(None, {}) + assert engine.memory_victim_pending("big") is False diff --git a/tests/test_process_memory_enforcer.py b/tests/test_process_memory_enforcer.py index baee873477..2e075dda55 100644 --- a/tests/test_process_memory_enforcer.py +++ b/tests/test_process_memory_enforcer.py @@ -3634,6 +3634,8 @@ def _engine(victims): ] + [None] ) + # Each victim's deferred abort has already run by the next poll. + engine.memory_victim_pending = MagicMock(return_value=False) return engine @staticmethod @@ -3670,7 +3672,7 @@ async def test_hard_pressure_aborts_exactly_one_victim( assert "'big-model'" in caplog.text @pytest.mark.asyncio - async def test_persisting_pressure_aborts_one_more_victim_per_poll( + async def test_persisting_pressure_aborts_the_next_victim_once_the_first_drained( self, enforcer, monkeypatch ): enforcer._single_victim_on = True @@ -3680,10 +3682,124 @@ async def test_persisting_pressure_aborts_one_more_victim_per_poll( await self._tick(enforcer, 97) assert engine.abort_one_request_for_memory.await_count == 1 + # The abort ran; this poll lets its memory return to the OS. await self._tick(enforcer, 97) + assert engine.abort_one_request_for_memory.await_count == 1 + + await self._tick(enforcer, 97) + assert engine.abort_one_request_for_memory.await_count == 2 + engine.abort_all_requests.assert_not_awaited() + + @pytest.mark.asyncio + async def test_no_second_victim_while_the_first_abort_is_pending( + self, enforcer, monkeypatch, caplog + ): + enforcer._single_victim_on = True + engine = self._engine([("first", 2), ("second", 1)]) + engine.memory_victim_pending = MagicMock(side_effect=[True, True, False]) + self._busy(enforcer, engine) + + await self._tick(enforcer, 97) + with caplog.at_level("INFO"): + for _ in range(3): # pending, pending, then ran (settling) + await self._tick(enforcer, 97) + assert engine.abort_one_request_for_memory.await_count == 1 + engine.abort_all_requests.assert_not_awaited() + assert "waiting for victim first memory to drain" in caplog.text + engine.memory_victim_pending.assert_called_with("first") + + await self._tick(enforcer, 97) + assert engine.abort_one_request_for_memory.await_count == 2 + engine.abort_all_requests.assert_not_awaited() + + @pytest.mark.asyncio + async def test_a_victim_that_never_drains_is_waited_on_for_bounded_polls( + self, enforcer, monkeypatch, caplog + ): + enforcer._single_victim_on = True + engine = self._engine([("first", 2), ("second", 1)]) + engine.memory_victim_pending = MagicMock(return_value=True) + self._busy(enforcer, engine) + bound = enforcer._SINGLE_VICTIM_SETTLE_MAX_POLLS + + await self._tick(enforcer, 97) + for _ in range(bound): + await self._tick(enforcer, 97) + assert engine.abort_one_request_for_memory.await_count == 1 + + with caplog.at_level("WARNING"): + await self._tick(enforcer, 97) assert engine.abort_one_request_for_memory.await_count == 2 + assert "did not drain" in caplog.text engine.abort_all_requests.assert_not_awaited() + @pytest.mark.asyncio + async def test_emergency_while_a_victim_drains_aborts_everything( + self, enforcer, monkeypatch + ): + enforcer._single_victim_on = True + engine = self._engine([("first", 2)]) + engine.memory_victim_pending = MagicMock(return_value=True) + self._busy(enforcer, engine) + + await self._tick(enforcer, 97) + await self._tick(enforcer, 103) + + engine.abort_all_requests.assert_awaited_once_with(spare_parked=False) + assert engine.abort_one_request_for_memory.await_count == 1 + + @pytest.mark.asyncio + async def test_relief_below_hard_forgets_the_draining_victim( + self, enforcer, monkeypatch + ): + enforcer._single_victim_on = True + engine = self._engine([("first", 2), ("second", 1)]) + engine.memory_victim_pending = MagicMock(return_value=True) + self._busy(enforcer, engine) + + await self._tick(enforcer, 97) + await self._tick(enforcer, 90) # soft: the episode is over + await self._tick(enforcer, 97) + + assert engine.abort_one_request_for_memory.await_count == 2 + + @pytest.mark.asyncio + async def test_a_failing_hook_falls_back_to_abort_all_for_that_poll( + self, enforcer, monkeypatch, caplog + ): + enforcer._single_victim_on = True + engine = self._engine([]) + engine.abort_one_request_for_memory = AsyncMock( + side_effect=RuntimeError("scheduler gone") + ) + self._busy(enforcer, engine) + + with caplog.at_level("WARNING"): + await self._tick(enforcer, 97) + + engine.abort_all_requests.assert_awaited_once_with(spare_parked=True) + assert "scheduler gone" in caplog.text + assert "falling back to aborting all requests" in caplog.text + + @pytest.mark.asyncio + async def test_a_skipped_victim_falls_back_to_abort_all( + self, enforcer, monkeypatch, caplog + ): + from omlx.request import MemoryVictim + + enforcer._single_victim_on = True + engine = self._engine([]) + engine.abort_one_request_for_memory = AsyncMock( + return_value=MemoryVictim("ghost", 10, 0, 1, skipped="no_client") + ) + self._busy(enforcer, engine) + + with caplog.at_level("WARNING"): + await self._tick(enforcer, 97) + + engine.abort_all_requests.assert_awaited_once_with(spare_parked=True) + assert "ghost" in caplog.text and "no_client" in caplog.text + @pytest.mark.asyncio async def test_recovered_pressure_aborts_no_second_victim( self, enforcer, monkeypatch From c12cf7e47c98442303b10c9f154d5b5243491f65 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Mon, 5 Oct 2026 13:59:38 -0600 Subject: [PATCH 19/46] feat(scheduler): pause a decoding row into an exact SSD prefix 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. --- omlx/cache/prefix_cache.py | 15 + omlx/scheduler.py | 386 +++++++++++++++++- tests/test_scheduler_decode_pause.py | 327 +++++++++++++++ tests/test_scheduler_prefill_commit_vlm.py | 6 +- .../test_scheduler_prefill_progress_commit.py | 6 +- 5 files changed, 718 insertions(+), 22 deletions(-) create mode 100644 tests/test_scheduler_decode_pause.py diff --git a/omlx/cache/prefix_cache.py b/omlx/cache/prefix_cache.py index 695e91b693..de51cf336d 100644 --- a/omlx/cache/prefix_cache.py +++ b/omlx/cache/prefix_cache.py @@ -1812,6 +1812,21 @@ def store_exact_prefix( self._exact_prefix_stores += 1 return stored_table + def exact_prefix_store_supported(self) -> bool: + """Whether ``store_exact_prefix`` can persist this model's layout. + + False without a paged SSD tier, and for a split-GDN layout whose + terminal recurrent sidecar has no writer attached. + """ + if self.paged_ssd_cache is None: + return False + expected_layer_types = getattr( + self.paged_ssd_cache, "_expected_layer_cache_types", None + ) + return not self._gdn_split_layout_supported(expected_layer_types) or callable( + self._exact_gdn_checkpoint_writer + ) + def _exact_prefix_hashes( self, tokens: list[int], diff --git a/omlx/scheduler.py b/omlx/scheduler.py index dd6bd7a1d7..6b02708e79 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -1383,6 +1383,28 @@ class _ParkPins(NamedTuple): hashes: list[bytes] +@dataclass +class _DecodeResume: + """What a paused decoding row needs to continue exactly where it stopped. + + The exact chain under ``domain_key`` holds the KV of ``tokens`` (prompt + plus every output token but the last). ``kickoff`` is that last output + token: already streamed to the client, not yet in the KV, so the resumed + row starts by feeding it, exactly as the uninterrupted row would have. + """ + + storage_id: str + domain_key: tuple[str, ...] + tokens: list[int] + kickoff: int + remaining_max_tokens: int + sampler: Any + logits_processors: list + stop_sequences: Any + # Stop-sequence automaton position after the kickoff (stop continuity). + stop_matcher: Any = None + + def _prefill_commit_blocks(config: Any) -> int: """``prefill_progress_commit_blocks`` of a config, 0 when unset or invalid.""" value = getattr(config, "prefill_progress_commit_blocks", 0) @@ -2309,10 +2331,17 @@ def __init__( self._last_pressure_poll_at: float | None = None self._last_pressure_level: str = "ok" self._park_pins: dict[str, _ParkPins] = {} + # Decode pause: ids asked for by request_decode_pause (thread-safe set, + # drained at step start) and the resume record of each paused row. + self._pending_decode_pauses: set[str] = set() + self._decode_resumes: dict[str, _DecodeResume] = {} self._park_stats: dict[str, int] = { "parks": 0, "resumes": 0, "tokens_preserved": 0, + "decode_pauses": 0, + "decode_resumes": 0, + "decode_resume_lost": 0, } self.requests: dict[str, Request] = {} # All requests by ID self.finished_req_ids: set[str] = set() # Recently finished @@ -12094,18 +12123,20 @@ def get_park_stats(self) -> dict[str, int]: def _park_exclusion_reason(self, request: Request) -> str | None: """Why ``request`` cannot be parked now, or None when it can. - Only requests in the chunked-prefill loop qualify: their state lives + Requests in the chunked-prefill loop qualify: their state lives between steps. External-loop prefills (non-chunked, media prompts) run to completion inside one ``_schedule_waiting`` call and are never between steps; media embeddings and SpecPrefill patch model-wide state, so they are excluded as well. A text prompt on a VLM engine takes the - chunked loop like any other model and is parkable. + chunked loop like any other model and is parkable. A decoding row + qualifies for a decode pause unless ``_decode_pause_exclusion_reason`` + names why not. """ budget = getattr(self.config, "max_parks_per_request", 3) - if request.request_id in self.running: - return "decoding, not in chunked prefill" if request.park_count >= budget: return f"park budget spent ({request.park_count}/{budget})" + if request.request_id in self.running: + return self._decode_pause_exclusion_reason(request) if request.specprefill_indices is not None: return "SpecPrefill sparse prefill patches model-wide state" if request.vlm_inputs_embeds is not None: @@ -12117,6 +12148,42 @@ def _park_exclusion_reason(self, request: Request) -> str | None: return "prefill runs in the external loop, not between steps" return None + def _generation_batch(self) -> Any: + batch_generator = self.batch_generator + if batch_generator is None: + return None + return getattr(batch_generator, "_generation_batch", None) + + def _decode_pause_exclusion_reason(self, request: Request) -> str | None: + """Why a decoding row cannot be paused exactly (v1), or None.""" + rid = request.request_id + if ( + request.specprefill_indices is not None + or self._specprefill_active_request_id == rid + ): + return "SpecPrefill decode runs with an offset RoPE installed model-wide" + uid = self.request_id_to_uid.get(rid) + if uid is not None and uid < 0: + return "VLM-MTP decode runs outside the batch generator" + generation_batch = self._generation_batch() + if uid is None or generation_batch is None or uid not in generation_batch.uids: + return "decoding row is not in the generation batch" + if _block_drafter_for(self.model) is not None: + return "DFlash drafter state is not handed off on a decode pause" + if ( + getattr(generation_batch, "_omlx_mtp_state", None) is not None + or getattr(generation_batch, "_omlx_mtp_batch_state", None) is not None + ): + return "MTP speculative decode is active (its queue is not handed off)" + prefix_cache = self.block_aware_cache + if prefix_cache is None or self.paged_ssd_cache_manager is None: + return "no paged SSD cache to hold the exact prefix" + if not prefix_cache.exact_prefix_store_supported(): + return "split-GDN exact-prefix sidecar writer is unavailable" + if self._model_has_unreconstructible_cache(): + return "cache layout cannot round-trip through paged storage" + return None + def _parkable_prefills(self) -> list[Request]: """Chunked prefills that can be parked safely.""" return [ @@ -12200,21 +12267,279 @@ def request_park_prefill(self) -> bool: and self._polls_since_park <= PARK_SETTLE_POLLS ) - def _process_pending_park(self) -> bool: - """Park one victim if the enforcer asked (MLX thread, step start).""" - if not self._park_requested: + def request_decode_pause(self, request_id: str) -> bool: + """Ask for a decoding row to be paused at the next step start. + + Thread-safe (flag only). Returns False when parking is disabled, the + request is not decoding, or ``_park_exclusion_reason`` names why the + row cannot pause; the step re-checks before it pauses. + """ + if not self._park_enabled() or request_id not in self.running: + return False + request = self.requests.get(request_id) + if request is None: + return False + try: + reason = self._park_exclusion_reason(request) + except RuntimeError: + reason = None # queues mutated mid-read; the step re-checks + if reason is not None: + logger.info("Decode pause skipped for %s: %s", request_id, reason) return False + self._pending_decode_pauses.add(request_id) + return True + + def _process_pending_park(self, output: SchedulerOutput | None = None) -> bool: + """Pause or park requested victims (MLX thread, step start). + + Outputs a decode pause emits (its pending token) go to ``output``. + """ + acted = self._process_pending_decode_pauses(output) + if not self._park_requested: + return acted self._park_requested = False if not self._park_enabled(): - return False + return acted victim = self._select_park_victim() if victim is None: self._log_no_parkable_victim() - return False + return acted self._park_prefill(victim, reason="hard memory pressure") self._polls_since_park = 0 return True + def _process_pending_decode_pauses(self, output: SchedulerOutput | None) -> bool: + acted = False + while self._pending_decode_pauses: + rid = self._pending_decode_pauses.pop() + request = self.requests.get(rid) + if ( + request is None + or rid not in self.running + or rid in self._pending_abort_ids + or not self._park_enabled() + ): + continue + reason = self._park_exclusion_reason(request) + if reason is not None: + logger.info("Decode pause skipped for %s: %s", rid, reason) + continue + if self._pause_decoding_request(request, output): + self._polls_since_park = 0 + acted = True + return acted + + def _pause_decoding_request( + self, request: Request, output: SchedulerOutput | None + ) -> bool: + """Pause one decoding row exactly; True when it was paused. + + After ``GenerationBatch.next()`` the row's KV holds every emitted + token and ``_next_tokens[row]`` is sampled but not emitted. The + pending token is emitted through the normal response path (a token + that finishes the request is left to the step, which completes it + normally), the KV is stored as an exact chain under a request domain + and pinned, and the row leaves the batch the way an abort removes it + while the request keeps its output, detokenizer, parser session and + client stream. Any failure before the emission leaves the row + decoding untouched. + """ + rid = request.request_id + uid = self.request_id_to_uid[rid] + generation_batch = self._generation_batch() + _safe_sync_stream(self._stream) + row = generation_batch.uids.index(uid) + with mx.stream(self._stream): + mx.eval(generation_batch._next_tokens) + pending = int(generation_batch._next_tokens[row].item()) + + matcher = generation_batch._matchers[row] + stop_matcher = type(matcher)(matcher._root) + stop_matcher._node = matcher._node + stops = stop_matcher.advance(pending) + emitted = generation_batch._num_tokens[row] + 1 + max_tokens = generation_batch.max_tokens[row] + if stops or emitted >= max_tokens: + logger.info( + "Decode pause skipped for %s: its pending token finishes the " + "request", + rid, + ) + return False + + row_cache, row_tokens = self.batch_generator.extract_cache([uid])[uid] + saved_tokens = [int(t) for t in row_tokens] + offset = max((_cache_layer_token_count(c) for c in row_cache), default=0) + expected = request.num_prompt_tokens + request.num_output_tokens + if offset != len(saved_tokens) or len(saved_tokens) != expected: + logger.warning( + "Decode pause declined for %s: cache offset %d, batch tokens %d, " + "prompt + output %d disagree", + rid, + offset, + len(saved_tokens), + expected, + ) + return False + + park_number = request.park_count + 1 + storage_id = f"{rid}:decode-pause-{park_number}" + domain_key = ( + "decode-resume", + rid, + str(park_number), + str(request.vlm_extra_keys_for_cache or ()), + ) + cache_states, model_cache_config = self._extract_cache_states(row_cache) + table = None + if cache_states: + with mx.stream(self._stream): + arrays = self._collect_arrays_from_extracted_cache(cache_states) + if arrays: + mx.eval(*arrays) + table = self.block_aware_cache.store_exact_prefix( + storage_id, + saved_tokens, + cache_states, + model_cache_config=model_cache_config, + domain_key=domain_key, + ) + if table is None or not self._pin_exact_chain(rid, table): + logger.warning( + "Decode pause declined for %s: the exact prefix of %d tokens " + "could not be stored and pinned", + rid, + len(saved_tokens), + ) + return False + + response = GenerationBatch.Response( + uid=uid, + token=pending, + logprobs=( + generation_batch._next_logprobs[row] + if row < len(generation_batch._next_logprobs) + else None + ), + finish_reason=None, + prompt_cache=None, + all_tokens=None, + ) + outputs, finished_ids = self._process_batch_responses([response]) + if output is not None: + output.outputs.extend(outputs) + output.finished_request_ids.update(finished_ids) + if finished_ids: + # A stop string or parser stop ended it: no pause after all. + self._unpin_parked(rid) + self._cleanup_finished(finished_ids) + return False + + from .api.grammar import GrammarConstraintProcessor + + processors = list(generation_batch.logits_processors[row] or ()) + for processor in processors: + if isinstance(processor, GrammarConstraintProcessor) and processor.pending: + processor.accept_token(pending) + + self._decode_resumes[rid] = _DecodeResume( + storage_id=storage_id, + domain_key=domain_key, + tokens=saved_tokens, + kickoff=pending, + remaining_max_tokens=max_tokens - emitted, + sampler=generation_batch.samplers[row], + logits_processors=processors, + stop_sequences=generation_batch.stop_sequences[row], + stop_matcher=stop_matcher, + ) + self._remove_decoding_row(rid, uid) + request.status = RequestStatus.WAITING + request.batch_uid = None + request.prompt_cache = None + request.parked = True + request.parked_at = time.monotonic() + request.park_count = park_number + self._enqueue_parked(request) + self._ok_polls = 0 + self._park_stats["parks"] += 1 + self._park_stats["decode_pauses"] += 1 + Scheduler._clear_cache(self) + logger.info( + "Paused decoding request %s at %d tokens (prompt %d + output %d), " + "stored exact prefix", + rid, + request.num_tokens, + request.num_prompt_tokens, + request.num_output_tokens, + ) + return True + + def _remove_decoding_row(self, request_id: str, uid: int) -> None: + """Take a row out of the batch as an abort does, keeping the request.""" + _safe_sync_stream(self._stream) + self._remove_uid_from_active_batch(uid) + if hasattr(self.model, "unregister_rope_delta"): + self.model.unregister_rope_delta(uid) + _unregister_uid_row(self.model, uid) + self.uid_to_request_id.pop(uid, None) + self.request_id_to_uid.pop(request_id, None) + self.running.pop(request_id, None) + _mtp_priming.release_request(self.model, request_id) + + def _resume_decoding_request( + self, + request: Request, + scheduled: list[Request], + rejected_outputs: list[RequestOutput], + ) -> None: + """Re-admit a paused decoding row from its exact chain.""" + record = self._decode_resumes.pop(request.request_id) + self._finish_park_resume(request, preserved_tokens=0, log=False) + self._finish_decode_resume_lost( + request, record, rejected_outputs, "exact resume is unavailable" + ) + + def _finish_decode_resume_lost( + self, + request: Request, + record: _DecodeResume, + rejected_outputs: list[RequestOutput], + detail: str, + ) -> None: + """End a paused row whose exact state is gone with a structured error. + + Re-prefilling prompt plus output would not continue the stream + exactly (sampler state, stop and grammar machines), so the client is + told instead of waiting forever. + """ + rid = request.request_id + self._park_stats["decode_resume_lost"] += 1 + metadata: dict[str, int | str] = { + "request_id": rid, + "prompt_tokens": request.num_prompt_tokens, + "output_tokens": request.num_output_tokens, + "exact_prefix_tokens": len(record.tokens), + } + logger.warning( + "Decode resume lost for %s: %s (%d exact-prefix tokens); finishing " + "it with an error", + rid, + detail, + len(record.tokens), + ) + self._do_abort_request(rid) + rejected_outputs.append( + RequestOutput( + request_id=rid, + finished=True, + finish_reason="error", + error=f"decode_resume_lost: {detail}", + error_code="decode_resume_lost", + error_metadata=metadata, + ) + ) + def _park_prefill(self, request: Request, reason: str) -> None: """Pause a chunked prefill without an error and without blocking. @@ -12347,7 +12672,13 @@ def _unpin_parked(self, request_id: str) -> None: if ssd is not None and hasattr(ssd, "unpin_blocks"): ssd.unpin_blocks(pins.hashes) - def _finish_park_resume(self, request: Request) -> None: + def _finish_park_resume( + self, + request: Request, + *, + preserved_tokens: int | None = None, + log: bool = True, + ) -> None: """Re-admission of a parked request: its fresh lookup holds the blocks.""" self._unpin_parked(request.request_id) request.parked = False @@ -12357,12 +12688,15 @@ def _finish_park_resume(self, request: Request) -> None: self._polls_since_resume = 0 self._park_resumed_this_pass = True self._park_stats["resumes"] += 1 - self._park_stats["tokens_preserved"] += request.cached_tokens or 0 - logger.info( - "Resumed parked request %s: cached=%d", - request.request_id, - request.cached_tokens or 0, - ) + if preserved_tokens is None: + preserved_tokens = request.cached_tokens or 0 + self._park_stats["tokens_preserved"] += preserved_tokens + if log: + logger.info( + "Resumed parked request %s: cached=%d", + request.request_id, + request.cached_tokens or 0, + ) def request_idle_reclaim(self) -> None: """Enqueue a between-turn Metal reclaim (thread-safe, no Metal touch). @@ -12476,6 +12810,8 @@ def _do_abort_request(self, request_id: str) -> bool: self._clear_request_admission_bookkeeping(request_id) self._unpin_parked(request_id) + self._pending_decode_pauses.discard(request_id) + self._decode_resumes.pop(request_id, None) # A deferred pin step must not re-pin an aborted request's blocks. request.parked = False @@ -13450,6 +13786,15 @@ def _schedule_waiting_scan( self.waiting.appendleft(request) break + if request.request_id in self._decode_resumes: + # A paused decoding row: no prefill, no preflight. It waits + # while a SpecPrefill offset RoPE is installed model-wide. + if self._specprefill_active_request_id is not None: + self.waiting.appendleft(request) + break + self._resume_decoding_request(request, scheduled, rejected_outputs) + continue + # Prefix cache reconstruction must run on the per-engine stream. # The reconstruct chain (mx.concatenate in prefix_cache / # type_handlers, exact-hit trim) otherwise binds its lazy ops to @@ -15478,9 +15823,10 @@ def step(self) -> SchedulerOutput: if drained_async_removes: output.has_work = True - # Park a prefill victim requested by the memory enforcer. Runs before - # any chunk so a parked request never has a forward in flight. - if self._process_pending_park(): + # Park a prefill victim or pause a decoding row requested by the + # memory enforcer. Runs before any chunk or decode step so a parked + # request never has a forward in flight. + if self._process_pending_park(output): output.has_work = True # Check memory pressure and evict if needed (tiered cache) @@ -15864,6 +16210,8 @@ def reset(self) -> None: self._skipped_final_stores.clear() for parked_id in list(self._park_pins): self._unpin_parked(parked_id) + self._pending_decode_pauses.clear() + self._decode_resumes.clear() self._park_requested = False self._polls_since_park = None self._park_resumed_this_pass = False diff --git a/tests/test_scheduler_decode_pause.py b/tests/test_scheduler_decode_pause.py new file mode 100644 index 0000000000..0d2f46a7ea --- /dev/null +++ b/tests/test_scheduler_decode_pause.py @@ -0,0 +1,327 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Pause a decoding request under memory pressure and resume it exactly. + +The tests drive the real scheduler step loop on a small initialized Qwen3.5 +hybrid model (GatedDeltaNet + full attention) against real paged-SSD, +boundary-snapshot and prefix stores (the ``_Rig`` of the park suite). A +paused row emits its pending token, stores its exact KV under a request +domain, leaves the batch and waits parked with its client stream open. +""" + +import logging + +import pytest +import test_scheduler_park as park +from conftest import MockTokenizer + +import omlx.scheduler as scheduler_module +from omlx.request import Request, RequestStatus, SamplingParams +from omlx.scheduler import _BoundarySnapshotProvider + +PROMPT = park.PROMPT_B # 24 tokens; every id is below the tiny vocabulary +OTHER = park.PROMPT_C +# Enough paged blocks for prompt plus several hundred generated tokens. +MAX_BLOCKS = 256 + + +def _tokenizer(): + """EOS outside the tiny model's vocabulary: decode runs to max_tokens.""" + tokenizer = MockTokenizer() + tokenizer.eos_token_id = 99 + return tokenizer + + +def make_rig(tmp_path, *, split=False, exact_writer=True, park_enabled=True): + rig = park._Rig( + tmp_path, + _tokenizer(), + split=split, + commit_blocks=1, + max_blocks=MAX_BLOCKS, + memory_pressure_park=park_enabled, + max_parks_per_request=3, + park_resume_ok_polls=3, + ) + if split and exact_writer: + rig.prefix.set_exact_gdn_checkpoint_writer( + lambda **kwargs: _BoundarySnapshotProvider.stage_and_commit( + store=rig.boundary, paged_ssd_manager=rig.ssd, **kwargs + ) + ) + rig.scheduler.note_pressure_poll("soft") + return rig + + +def submit(rig, request_id, tokens, max_tokens, **sampling): + request = Request( + request_id=request_id, + prompt=list(tokens), + sampling_params=SamplingParams( + max_tokens=max_tokens, temperature=0, **sampling + ), + arrival_time=float(len(rig.scheduler.requests) + 1), + ) + rig.scheduler.add_request(request) + return request + + +def step_until_outputs(rig, request, count, outputs, limit=1000): + for _ in range(limit): + if len(request.output_token_ids) >= count: + return + outputs.extend(park.step(rig)) + raise AssertionError("output count not reached") + + +def streamed_tokens(outputs, request_id): + return [t for o in outputs if o.request_id == request_id for t in o.new_token_ids] + + +def baseline(tmp_path, max_tokens, *, second=False, **sampling): + """Token ids of an uninterrupted greedy run (optionally beside a second row).""" + rig = make_rig(tmp_path / "baseline", park_enabled=False) + try: + request = submit(rig, "a", PROMPT, max_tokens, **sampling) + rows = [request] + if second: + rows.append(submit(rig, "b", OTHER, max_tokens)) + park.run_to_completion(rig, rows, limit=4 * max_tokens) + return [list(r.output_token_ids) for r in rows] + finally: + rig.close() + + +# --- Pause primitive ------------------------------------------------------------ + + +def test_pause_emits_the_pending_token_once_and_parks_the_row(tmp_path, caplog): + (expected,) = baseline(tmp_path, 40) + rig = make_rig(tmp_path / "pause") + try: + scheduler = rig.scheduler + scheduler._park_hold_applies = lambda head: True # isolate the pause + request = submit(rig, "a", PROMPT, 40) + outputs = [] + step_until_outputs(rig, request, 3, outputs) + uid = scheduler.request_id_to_uid["a"] + + assert scheduler.request_decode_pause("a") is True + with caplog.at_level(logging.INFO, logger="omlx.scheduler"): + pause_outputs = park.step(rig) + outputs.extend(pause_outputs) + + # The pending token reached the client exactly once, then the row left. + assert streamed_tokens(pause_outputs, "a") == [expected[3]] + assert list(request.output_token_ids) == expected[:4] + assert streamed_tokens(outputs, "a") == expected[:4] + assert not [o for o in outputs if o.finished or o.error] + assert request.parked and request.park_count == 1 + assert request.status == RequestStatus.WAITING + assert park.waiting_ids(rig) == ["a"] + assert "a" not in scheduler.running + assert "a" not in scheduler.request_id_to_uid + assert uid not in scheduler.uid_to_request_id + assert uid not in scheduler.batch_generator._generation_batch.uids + assert "a" in scheduler.requests # the client stream stays open + + record = scheduler._decode_resumes["a"] + assert record.tokens == PROMPT + expected[:3] # the KV holds these + assert record.kickoff == expected[3] # emitted, not yet in the KV + assert record.remaining_max_tokens == 40 - 4 + assert scheduler._park_pins["a"].hashes + assert rig.ssd.pinned_block_count == len(scheduler._park_pins["a"].hashes) + assert scheduler.get_park_stats()["decode_pauses"] == 1 + assert any( + "Paused decoding request a at 28 tokens (prompt 24 + output 4), " + "stored exact prefix" in r.getMessage() + for r in caplog.records + ) + finally: + rig.close() + + +def test_a_pending_token_that_reaches_max_tokens_finishes_without_a_pause(tmp_path): + (expected,) = baseline(tmp_path, 5) + rig = make_rig(tmp_path / "pause") + try: + scheduler = rig.scheduler + request = submit(rig, "a", PROMPT, 5) + outputs = [] + step_until_outputs(rig, request, 4, outputs) + assert scheduler.request_decode_pause("a") is True + outputs.extend(park.run_to_completion(rig, [request])) + + assert request.status == RequestStatus.FINISHED_LENGTH_CAPPED + assert list(request.output_token_ids) == expected + assert streamed_tokens(outputs, "a") == expected + assert not request.parked and request.park_count == 0 + assert "a" not in scheduler._decode_resumes + assert rig.ssd.pinned_block_count == 0 + finally: + rig.close() + + +def test_a_pending_stop_token_finishes_without_a_pause(tmp_path): + (free_run,) = baseline(tmp_path, 40) + # The first token that has not appeared before becomes the stop token. + index = next(i for i in range(2, 40) if free_run[i] not in free_run[:i]) + stop = free_run[index] + rig = make_rig(tmp_path / "pause") + try: + scheduler = rig.scheduler + request = submit(rig, "a", PROMPT, 40, stop_token_ids=[stop]) + outputs = [] + step_until_outputs(rig, request, index, outputs) + assert scheduler.request_decode_pause("a") is True + outputs.extend(park.run_to_completion(rig, [request])) + + assert request.status == RequestStatus.FINISHED_STOPPED + assert list(request.output_token_ids) == free_run[:index] + assert streamed_tokens(outputs, "a") == free_run[:index] + assert not request.parked and "a" not in scheduler._decode_resumes + assert rig.ssd.pinned_block_count == 0 + finally: + rig.close() + + +def _decoding(rig, request_id="a", max_tokens=40): + request = submit(rig, request_id, PROMPT, max_tokens) + step_until_outputs(rig, request, 2, []) + return request + + +def test_a_decoding_row_is_pausable_when_nothing_excludes_it(tmp_path): + rig = make_rig(tmp_path) + try: + request = _decoding(rig) + assert rig.scheduler._park_exclusion_reason(request) is None + finally: + rig.close() + + +@pytest.mark.parametrize( + "case, expected", + [ + ("specprefill", "SpecPrefill"), + ("dflash", "DFlash"), + ("mtp", "MTP"), + ("vlm_mtp", "VLM-MTP"), + ("no_ssd", "no paged SSD cache"), + ("budget", "park budget spent"), + ], +) +def test_v1_exclusions_name_why_a_decoding_row_cannot_pause( + tmp_path, monkeypatch, case, expected +): + rig = make_rig(tmp_path) + try: + scheduler = rig.scheduler + request = _decoding(rig) + if case == "specprefill": + request.specprefill_indices = [0] + elif case == "dflash": + monkeypatch.setattr( + scheduler_module, "_block_drafter_for", lambda model: object() + ) + elif case == "mtp": + scheduler.batch_generator._generation_batch._omlx_mtp_state = object() + elif case == "vlm_mtp": + uid = scheduler.request_id_to_uid["a"] + scheduler.request_id_to_uid["a"] = -7 + elif case == "no_ssd": + monkeypatch.setattr(scheduler, "paged_ssd_cache_manager", None) + elif case == "budget": + request.park_count = 3 + reason = scheduler._park_exclusion_reason(request) + assert reason is not None and expected in reason + assert scheduler.request_decode_pause("a") is False + if case == "mtp": + del scheduler.batch_generator._generation_batch._omlx_mtp_state + if case == "vlm_mtp": + scheduler.request_id_to_uid["a"] = uid + finally: + rig.close() + + +def test_split_gdn_without_an_exact_sidecar_writer_is_excluded(tmp_path): + rig = make_rig(tmp_path, split=True, exact_writer=False) + try: + request = _decoding(rig) + reason = rig.scheduler._park_exclusion_reason(request) + assert reason is not None and "split-GDN" in reason + assert rig.scheduler.request_decode_pause("a") is False + finally: + rig.close() + + +def test_decode_pause_requires_the_park_feature(tmp_path): + rig = make_rig(tmp_path, park_enabled=False) + try: + _decoding(rig) + assert rig.scheduler.request_decode_pause("a") is False + finally: + rig.close() + + +# --- Paused requests: abort, lost chain --------------------------------------------- + + +def _paused(rig, request_id="a", at=3, max_tokens=40): + scheduler = rig.scheduler + scheduler._park_hold_applies = lambda head: True # hold it parked + request = submit(rig, request_id, PROMPT, max_tokens) + outputs = [] + step_until_outputs(rig, request, at, outputs) + assert scheduler.request_decode_pause(request_id) is True + outputs.extend(park.step(rig)) + assert request.parked and request_id in scheduler._decode_resumes + return request, outputs + + +def test_abort_while_paused_leaves_no_pins_and_no_resume_record(tmp_path): + rig = make_rig(tmp_path) + try: + scheduler = rig.scheduler + _paused(rig) + assert rig.ssd.pinned_block_count > 0 + assert scheduler.abort_request("a") + park.step(rig, 2) + assert "a" not in scheduler.requests + assert "a" not in scheduler._decode_resumes + assert "a" not in scheduler._park_pins + assert rig.ssd.pinned_block_count == 0 + assert park.waiting_ids(rig) == [] + finally: + rig.close() + + +def test_a_lost_exact_chain_ends_the_request_with_a_structured_error(tmp_path): + rig = make_rig(tmp_path) + try: + scheduler = rig.scheduler + request, _ = _paused(rig) + # Lose the chain: drop the pins, then every SSD file and pool entry. + hashes = scheduler._park_pins["a"].hashes + scheduler._unpin_parked("a") + rig.ssd._evict_tracked_until_size(0) + for block_id, block in list(rig.paged.allocated_blocks.items()): + if block.block_hash in set(hashes): + rig.paged.allocated_blocks.pop(block_id) + rig.paged.cached_block_hash_to_block.pop(block.block_hash, block_id) + + del scheduler._park_hold_applies # resume as soon as admission allows + outputs = park.step(rig) + errors = [o for o in outputs if o.request_id == "a" and o.error] + assert len(errors) == 1 + error = errors[0] + assert error.finished and error.finish_reason == "error" + assert error.error_code == "decode_resume_lost" + assert error.error_metadata["request_id"] == "a" + assert error.error_metadata["output_tokens"] == 4 + assert "a" not in scheduler.requests + assert "a" not in scheduler._decode_resumes + assert rig.ssd.pinned_block_count == 0 + assert scheduler.get_park_stats()["decode_resume_lost"] == 1 + assert not park.waiting_ids(rig) and not scheduler.running + finally: + rig.close() diff --git a/tests/test_scheduler_prefill_commit_vlm.py b/tests/test_scheduler_prefill_commit_vlm.py index e123d2e09a..67293a1bb0 100644 --- a/tests/test_scheduler_prefill_commit_vlm.py +++ b/tests/test_scheduler_prefill_commit_vlm.py @@ -420,7 +420,7 @@ def test_exclusion_reasons_name_each_unparkable_case(tmp_path, mock_tokenizer, s ) scheduler.running["dec"] = decoding assert scheduler._park_exclusion_reason(decoding) == ( - "decoding, not in chunked prefill" + "decoding row is not in the generation batch" ) finally: rig.close() @@ -447,7 +447,9 @@ def test_no_parkable_victim_is_logged_once_per_request_with_its_reason( assert scheduler.request_park_prefill() is False lines = _info(caplog, "Park skipped for") assert len(lines) == 2 - assert any("dec: decoding, not in chunked prefill" in m for m in lines) + assert any( + "dec: decoding row is not in the generation batch" in m for m in lines + ) assert any("ext: prefill runs in the external loop" in m for m in lines) finally: rig.close() diff --git a/tests/test_scheduler_prefill_progress_commit.py b/tests/test_scheduler_prefill_progress_commit.py index 5c23e10592..ca375d52f1 100644 --- a/tests/test_scheduler_prefill_progress_commit.py +++ b/tests/test_scheduler_prefill_progress_commit.py @@ -60,6 +60,7 @@ def __init__( split, commit_blocks, tq_bits=None, + max_blocks=64, **config_overrides, ): mx.random.seed(11) @@ -77,7 +78,10 @@ def __init__( ), ) self.paged = PagedCacheManager( - block_size=BLOCK, max_blocks=64, initial_blocks=64, model_name="tiny" + block_size=BLOCK, + max_blocks=max_blocks, + initial_blocks=max_blocks, + model_name="tiny", ) kv_type = "TurboQuantKVCache" if tq_bits else "KVCache" self.ssd = PagedSSDCacheManager( From 34839e9f04eb54b6ad8c00e273dde8f0480e9a6c Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Mon, 5 Oct 2026 14:01:53 -0600 Subject: [PATCH 20/46] feat(scheduler): resume a paused decoding row from its exact prefix 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. --- omlx/scheduler.py | 78 ++++++++++++++-- tests/test_scheduler_decode_pause.py | 127 +++++++++++++++++++++++++++ 2 files changed, 200 insertions(+), 5 deletions(-) diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 6b02708e79..5e592a42aa 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -12493,11 +12493,79 @@ def _resume_decoding_request( scheduled: list[Request], rejected_outputs: list[RequestOutput], ) -> None: - """Re-admit a paused decoding row from its exact chain.""" - record = self._decode_resumes.pop(request.request_id) - self._finish_park_resume(request, preserved_tokens=0, log=False) - self._finish_decode_resume_lost( - request, record, rejected_outputs, "exact resume is unavailable" + """Re-admit a paused decoding row from its exact chain. + + No prefill and no preflight: the exact chain holds the KV of every + token but the kickoff, which the inserted row feeds first, exactly + as the uninterrupted row would have. The stashed sampler, logits + processors and stop machine continue; the RNG is not reseeded and + prompt usage is not counted again. + """ + rid = request.request_id + record = self._decode_resumes.pop(rid) + restored = None + if self.block_aware_cache is not None: + with mx.stream(self._stream): + restored = self.block_aware_cache.restore_exact_prefix( + record.storage_id, + record.tokens, + promote_to_hot_cache=not self._bypass_hot_cache_under_pressure(), + domain_key=record.domain_key, + ) + # The chain was reconstructed (or is gone): its pins are released. + self._finish_park_resume( + request, + preserved_tokens=len(record.tokens) if restored is not None else 0, + log=False, + ) + if restored is None: + self._finish_decode_resume_lost( + request, record, rejected_outputs, "the exact prefix chain is gone" + ) + return + restore_cache = getattr(self.model, "restore_cache", None) + cache = restore_cache(restored) if callable(restore_cache) else restored + offset = max((_cache_layer_token_count(c) for c in cache), default=0) + if offset != len(record.tokens): + self._finish_decode_resume_lost( + request, + record, + rejected_outputs, + f"restored {offset} tokens, expected {len(record.tokens)}", + ) + return + + with mx.stream(self._stream): + uids = self.batch_generator.insert( + [[record.kickoff]], + max_tokens=[record.remaining_max_tokens], + caches=[cache], + all_tokens=[list(record.tokens)], + samplers=[record.sampler], + logits_processors=[record.logits_processors], + stop_sequences=[record.stop_sequences], + ) + uid = uids[0] + _register_uid_rows( + self.model, uids, [record.sampler], [record.logits_processors] + ) + _mtp_priming.bind_uid(self.model, rid, uid) + self._dflash_bind_uid(rid, uid) + self.request_id_to_uid[rid] = uid + self.uid_to_request_id[uid] = rid + request.batch_uid = uid + request.status = RequestStatus.RUNNING + request.last_activity_at = time.monotonic() + self.running[rid] = request + scheduled.append(request) + if hasattr(self.model, "register_rope_delta"): + self.model.register_rope_delta(uid, request.rope_deltas) + _mark_text_positions(self.model, request, uid) + self._park_stats["decode_resumes"] += 1 + logger.info( + "Resumed decoding request %s: restored %d tokens exactly", + rid, + len(record.tokens), ) def _finish_decode_resume_lost( diff --git a/tests/test_scheduler_decode_pause.py b/tests/test_scheduler_decode_pause.py index 0d2f46a7ea..4a2bca5625 100644 --- a/tests/test_scheduler_decode_pause.py +++ b/tests/test_scheduler_decode_pause.py @@ -325,3 +325,130 @@ def test_a_lost_exact_chain_ends_the_request_with_a_structured_error(tmp_path): assert not park.waiting_ids(rig) and not scheduler.running finally: rig.close() + + +# --- Resume: greedy identity and stream continuity ----------------------------- + +RESUME_MAX_TOKENS = 300 + + +def baseline_outputs(tmp_path, max_tokens, *, second=False, split=False): + """Uninterrupted run: per-row token ids, streamed text and final output.""" + rig = make_rig(tmp_path / "baseline", split=split, park_enabled=False) + try: + rows = [submit(rig, "a", PROMPT, max_tokens)] + if second: + rows.append(submit(rig, "b", OTHER, max_tokens)) + outputs = park.run_to_completion(rig, rows, limit=4 * max_tokens) + return outputs, rows + finally: + rig.close() + + +def paused_outputs(tmp_path, pause_at, max_tokens, *, second=False, split=False): + """The same run with row ``a`` paused after ``pause_at`` output tokens.""" + rig = make_rig(tmp_path / "paused", split=split) + rows = [submit(rig, "a", PROMPT, max_tokens)] + if second: + rows.append(submit(rig, "b", OTHER, max_tokens)) + outputs = [] + step_until_outputs(rig, rows[0], pause_at, outputs) + assert rig.scheduler.request_decode_pause("a") is True + outputs.extend(park.step(rig)) + assert rows[0].park_count == 1 + park.finish_ok_polls(rig, 3) + outputs.extend(park.run_to_completion(rig, rows, limit=4 * max_tokens)) + return rig, outputs, rows + + +def _final(outputs, request_id): + (final,) = [o for o in outputs if o.request_id == request_id and o.finished] + return final + + +def assert_identical_stream(base_outputs, base_row, outputs, row): + rid = row.request_id + expected = list(base_row.output_token_ids) + assert list(row.output_token_ids) == expected + # Every token reached the client exactly once, in order. + assert streamed_tokens(outputs, rid) == expected + streamed_text = "".join(o.new_text for o in outputs if o.request_id == rid) + base_text = "".join(o.new_text for o in base_outputs if o.request_id == rid) + assert streamed_text == base_text + final, base_final = _final(outputs, rid), _final(base_outputs, rid) + assert not final.error + assert final.finish_reason == base_final.finish_reason == "length" + assert final.output_text == base_final.output_text + # Usage is not double counted. + assert final.prompt_tokens == base_final.prompt_tokens == len(row.prompt) + assert final.completion_tokens == base_final.completion_tokens == len(expected) + + +@pytest.mark.parametrize("pause_at", [1, 255, 256]) +@pytest.mark.parametrize("split", [False, True], ids=["inline-gdn", "split-gdn"]) +def test_greedy_output_after_a_decode_pause_equals_an_uninterrupted_run( + tmp_path, caplog, pause_at, split +): + base_outputs, (base_row,) = baseline_outputs( + tmp_path, RESUME_MAX_TOKENS, split=split + ) + with caplog.at_level(logging.INFO, logger="omlx.scheduler"): + rig, outputs, (row,) = paused_outputs( + tmp_path, pause_at, RESUME_MAX_TOKENS, split=split + ) + try: + assert_identical_stream(base_outputs, base_row, outputs, row) + scheduler = rig.scheduler + restored = len(PROMPT) + pause_at + assert any( + f"Resumed decoding request a: restored {restored} tokens exactly" + in r.getMessage() + for r in caplog.records + ) + stats = scheduler.get_park_stats() + assert stats["decode_pauses"] == stats["decode_resumes"] == 1 + assert stats["decode_resume_lost"] == 0 + assert rig.prefix.get_stats().exact_prefix_hits == 1 + # No re-prefill: the prompt was admitted once. + assert scheduler.total_prompt_tokens == len(PROMPT) + assert scheduler.total_completion_tokens == RESUME_MAX_TOKENS + assert not scheduler._park_pins and rig.ssd.pinned_block_count == 0 + assert not scheduler._decode_resumes + finally: + rig.close() + + +@pytest.mark.parametrize("pause_at", [1, 255, 256]) +def test_greedy_identity_holds_beside_a_second_decoding_row(tmp_path, pause_at): + base_outputs, base_rows = baseline_outputs(tmp_path, RESUME_MAX_TOKENS, second=True) + rig, outputs, rows = paused_outputs( + tmp_path, pause_at, RESUME_MAX_TOKENS, second=True + ) + try: + for base_row, row in zip(base_rows, rows): + assert_identical_stream(base_outputs, base_row, outputs, row) + assert rig.scheduler.get_park_stats()["decode_resumes"] == 1 + finally: + rig.close() + + +def test_the_paused_row_waits_parked_while_others_decode(tmp_path): + """With another row admitted, the paused one is held until ok polls.""" + rig = make_rig(tmp_path) + try: + scheduler = rig.scheduler + a = submit(rig, "a", PROMPT, 60) + b = submit(rig, "b", OTHER, 60) + step_until_outputs(rig, a, 5, []) + assert scheduler.request_decode_pause("a") is True + park.step(rig) + frozen = list(a.output_token_ids) + park.step(rig, 3) + assert park.waiting_ids(rig) == ["a"] and a.parked + assert list(a.output_token_ids) == frozen # nothing decoded while parked + assert len(b.output_token_ids) > 5 + park.finish_ok_polls(rig, 3) + park.step(rig) + assert "a" in scheduler.running and not a.parked + finally: + rig.close() From 0f7b00dba205b11e4a599e664047d3ce70342cd6 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Mon, 5 Oct 2026 14:25:02 -0600 Subject: [PATCH 21/46] fix(scheduler): continue stop, parser and processor state across a decode 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. --- omlx/scheduler.py | 32 +- tests/test_scheduler_decode_pause.py | 6 +- .../test_scheduler_decode_pause_continuity.py | 389 ++++++++++++++++++ 3 files changed, 423 insertions(+), 4 deletions(-) create mode 100644 tests/test_scheduler_decode_pause_continuity.py diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 5e592a42aa..d01b73961b 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -1405,6 +1405,30 @@ class _DecodeResume: stop_matcher: Any = None +class _ResumedStopSequences: + """Stop sequences whose first matcher resumes at a saved position. + + mlx-lm builds a fresh matcher for every row it starts. A resumed decode + row must continue a stop sequence that began before its pause instead, + so the first ``matcher()`` call hands out the stashed position; later + calls (a row restart) start fresh like the wrapped automaton. + """ + + def __init__(self, base: StopSequences, matcher: Any): + self.base = base + self._matcher = matcher + + def matcher(self) -> Any: + matcher, self._matcher = self._matcher, None + return matcher if matcher is not None else self.base.matcher() + + +def _unwrap_stop_sequences(stop_sequences: Any) -> Any: + if isinstance(stop_sequences, _ResumedStopSequences): + return stop_sequences.base + return stop_sequences + + def _prefill_commit_blocks(config: Any) -> int: """``prefill_progress_commit_blocks`` of a config, 0 when unset or invalid.""" value = getattr(config, "prefill_progress_commit_blocks", 0) @@ -12450,7 +12474,7 @@ def _pause_decoding_request( remaining_max_tokens=max_tokens - emitted, sampler=generation_batch.samplers[row], logits_processors=processors, - stop_sequences=generation_batch.stop_sequences[row], + stop_sequences=_unwrap_stop_sequences(generation_batch.stop_sequences[row]), stop_matcher=stop_matcher, ) self._remove_decoding_row(rid, uid) @@ -12535,6 +12559,10 @@ def _resume_decoding_request( ) return + stop_sequences = record.stop_sequences + if record.stop_matcher is not None: + # Continue a stop sequence that began before the pause. + stop_sequences = _ResumedStopSequences(stop_sequences, record.stop_matcher) with mx.stream(self._stream): uids = self.batch_generator.insert( [[record.kickoff]], @@ -12543,7 +12571,7 @@ def _resume_decoding_request( all_tokens=[list(record.tokens)], samplers=[record.sampler], logits_processors=[record.logits_processors], - stop_sequences=[record.stop_sequences], + stop_sequences=[stop_sequences], ) uid = uids[0] _register_uid_rows( diff --git a/tests/test_scheduler_decode_pause.py b/tests/test_scheduler_decode_pause.py index 4a2bca5625..b7c4aeaaae 100644 --- a/tests/test_scheduler_decode_pause.py +++ b/tests/test_scheduler_decode_pause.py @@ -31,10 +31,12 @@ def _tokenizer(): return tokenizer -def make_rig(tmp_path, *, split=False, exact_writer=True, park_enabled=True): +def make_rig( + tmp_path, *, split=False, exact_writer=True, park_enabled=True, tokenizer=None +): rig = park._Rig( tmp_path, - _tokenizer(), + tokenizer if tokenizer is not None else _tokenizer(), split=split, commit_blocks=1, max_blocks=MAX_BLOCKS, diff --git a/tests/test_scheduler_decode_pause_continuity.py b/tests/test_scheduler_decode_pause_continuity.py new file mode 100644 index 0000000000..6a30333ec6 --- /dev/null +++ b/tests/test_scheduler_decode_pause_continuity.py @@ -0,0 +1,389 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Stop, parser and logits-processor state carry across a decode pause. + +Each case runs the same greedy request twice on the real scheduler step loop +(the ``_Rig`` of the park suite: a tiny Qwen3.5 hybrid model against real +paged-SSD stores): once uninterrupted and once paused at a chosen output +token and resumed. The token ids, the streamed text, the final text, the tool +calls and the finish reason must be identical. +""" + +import re + +import pytest +import test_scheduler_decode_pause as dp +import test_scheduler_park as park +from conftest import MockTokenizer + +from omlx.adapter.output_parser import ( + OutputParserFactory, + OutputParserFinalizeResult, + OutputParserTokenResult, +) +from omlx.request import Request, SamplingParams + +PROMPT = dp.PROMPT +EOS = 99 # outside the tiny vocabulary: decode runs to a stop or max_tokens + + +class TextTokenizer(MockTokenizer): + """Token ``t`` reads as ````: stop strings encode back to their ids.""" + + def __init__(self): + super().__init__() + self.eos_token_id = EOS + + def encode(self, text, add_special_tokens=True): + ids = [int(match) for match in re.findall(r"<(\d+)>", text)] + return ([self.bos_token_id] if add_special_tokens else []) + ids + + def decode(self, token_ids, skip_special_tokens=True): + return "".join( + f"<{int(t)}>" + for t in token_ids + if not (skip_special_tokens and int(t) == self.eos_token_id) + ) + + +class _SpanParserSession: + """A stateful protocol parser. + + Tokens between two ``toggle`` tokens are buffered as one tool call instead + of being streamed; the second ``stop`` token ends the request. + """ + + def __init__(self, toggle, stop): + self.toggle, self.stop = toggle, stop + self.in_span = False + self.span: list[int] = [] + self.stops_seen = 0 + self.tool_calls: list[dict[str, str]] = [] + + def process_token(self, token_id): + token_id = int(token_id) + if token_id == self.stop: + self.stops_seen += 1 + if self.stops_seen == 2: + return OutputParserTokenResult(is_stop=True) + if token_id == self.toggle: + if self.in_span: + arguments = "".join(f"<{t}>" for t in self.span) + self.tool_calls.append({"name": "span", "arguments": arguments}) + self.span = [] + self.in_span = not self.in_span + return OutputParserTokenResult() + if self.in_span: + self.span.append(token_id) + return OutputParserTokenResult() + text = f"<{token_id}>" + return OutputParserTokenResult(stream_text=text, visible_text=text) + + def finalize(self): + tail = "".join(f"<{t}>" for t in self.span) + return OutputParserFinalizeResult( + stream_text=tail, visible_text=tail, tool_calls=list(self.tool_calls) + ) + + +def _install_span_parser(toggle, stop): + def setup(rig): + rig.scheduler._output_parser_factory = OutputParserFactory( + kind="test-span", + create_session=lambda tokenizer: _SpanParserSession(toggle, stop), + ) + + return setup + + +def run( + tmp_path, + name, + *, + max_tokens, + pauses=(), + tokenizer=None, + setup=None, + request_attrs=None, + **sampling, +): + """Run request ``a``; pause it once its output reaches each count in ``pauses``.""" + rig = dp.make_rig(tmp_path / name, park_enabled=bool(pauses), tokenizer=tokenizer) + if setup is not None: + setup(rig) + request = Request( + request_id="a", + prompt=list(PROMPT), + sampling_params=SamplingParams( + max_tokens=max_tokens, temperature=0, **sampling + ), + arrival_time=1.0, + ) + for attr, value in (request_attrs or {}).items(): + setattr(request, attr, value) + rig.scheduler.add_request(request) + outputs = [] + for at in pauses: + _step_until_pausable(rig, request, at, outputs) + # The pending token the pause emits is output token ``at``. + assert len(request.output_token_ids) == at + assert rig.scheduler.request_decode_pause("a") is True + outputs.extend(park.step(rig)) + park.finish_ok_polls(rig, 3) + outputs.extend(park.run_to_completion(rig, [request], limit=4 * max_tokens)) + return rig, request, outputs + + +def _step_until_pausable(rig, request, count, outputs, limit=1000): + """Step until the output reaches ``count`` and the row decodes again.""" + scheduler = rig.scheduler + for _ in range(limit): + if ( + len(request.output_token_ids) >= count + and "a" in scheduler.running + and scheduler._park_exclusion_reason(request) is None + ): + return + outputs.extend(park.step(rig)) + raise AssertionError("pause point not reached") + + +def _final(outputs): + (final,) = [o for o in outputs if o.request_id == "a" and o.finished] + return final + + +def assert_same_run(baseline, paused): + (_, base_row, base_outputs), (_, row, outputs) = baseline, paused + assert list(row.output_token_ids) == list(base_row.output_token_ids) + assert dp.streamed_tokens(outputs, "a") == dp.streamed_tokens(base_outputs, "a") + assert "".join(o.new_text for o in outputs if o.request_id == "a") == "".join( + o.new_text for o in base_outputs if o.request_id == "a" + ) + final, base_final = _final(outputs), _final(base_outputs) + assert not final.error and not base_final.error + assert final.finish_reason == base_final.finish_reason + assert final.output_text == base_final.output_text + assert final.tool_calls == base_final.tool_calls + assert final.completion_tokens == base_final.completion_tokens + + +def close(*runs): + for rig, _, _ in runs: + rig.close() + + +@pytest.fixture +def free_run(tmp_path): + """Greedy output ids of an unconstrained 80-token run.""" + rig, row, _ = run(tmp_path, "free", max_tokens=80) + rig.close() + return list(row.output_token_ids) + + +def _first_new_ngram(tokens, n=3): + """Index of the first n-gram that never appeared before (nor overlaps).""" + for i in range(2, len(tokens) - n): + gram = tokens[i : i + n] + earlier = tokens[: i + n - 1] + if not any(earlier[j : j + n] == gram for j in range(len(earlier) - n + 1)): + return i + raise AssertionError("no fresh n-gram in the free run") + + +# --- Stop sequences -------------------------------------------------------------- + + +@pytest.mark.parametrize("offset", [0, 1], ids=["after-first", "after-second"]) +def test_a_stop_sequence_spanning_the_pause_matches_like_an_uninterrupted_run( + tmp_path, free_run, offset +): + i = _first_new_ngram(free_run) + stop = "".join(f"<{t}>" for t in free_run[i : i + 3]) + common = dict(max_tokens=80, tokenizer=TextTokenizer(), stop=[stop]) + baseline = run(tmp_path, "base", **common) + # The pending token emitted at the pause is stop token ``offset``. + paused = run(tmp_path, "paused", pauses=[i + offset], **common) + try: + assert _final(baseline[2]).finish_reason == "stop" + assert list(baseline[1].output_token_ids) == free_run[: i + 2] + assert paused[1].park_count == 1 + assert_same_run(baseline, paused) + finally: + close(baseline, paused) + + +def test_a_held_stop_prefix_is_released_when_it_diverges_after_the_resume( + tmp_path, free_run +): + i = _first_new_ngram(free_run) + # Token 50 is never generated: the prefix is held, then released. + stop = f"<{free_run[i]}><{free_run[i + 1]}><50>" + common = dict(max_tokens=60, tokenizer=TextTokenizer(), stop=[stop]) + baseline = run(tmp_path, "base", **common) + paused = run(tmp_path, "paused", pauses=[i], **common) + try: + assert _final(baseline[2]).finish_reason == "length" + assert paused[1].park_count == 1 + assert_same_run(baseline, paused) + finally: + close(baseline, paused) + + +def test_a_text_stop_completed_by_the_pending_token_finishes_without_a_pause( + tmp_path, free_run +): + """A stop string with no token form (it straddles two tokens' text).""" + tokenizer = TextTokenizer() + text = tokenizer.decode(free_run) + for i in range(3, 60): + stop = f"{str(free_run[i - 1])[-1]}><{str(free_run[i])[0]}" + if text.find(stop) == len(tokenizer.decode(free_run[:i])) - 2: + break + else: + raise AssertionError("no straddling stop string in the free run") + assert tokenizer.encode(stop, add_special_tokens=False) == [] + common = dict(max_tokens=60, tokenizer=TextTokenizer(), stop=[stop]) + baseline = run(tmp_path, "base", **common) + paused = run(tmp_path, "paused", pauses=[i], **common) + try: + assert _final(baseline[2]).finish_reason == "stop" + # The pending token ended the request: no pause, nothing pinned. + assert paused[1].park_count == 0 + assert "a" not in paused[0].scheduler._decode_resumes + assert paused[0].ssd.pinned_block_count == 0 + assert_same_run(baseline, paused) + finally: + close(baseline, paused) + + +# --- Protocol parser --------------------------------------------------------------- + + +def _occurrences(tokens, token): + return [i for i, t in enumerate(tokens) if t == token] + + +def _span_parser_case(free_run): + """A toggle token with a span before a stop token seen twice.""" + for toggle in dict.fromkeys(free_run): + spots = _occurrences(free_run, toggle) + if len(spots) < 2 or spots[1] - spots[0] < 3: + continue + for stop in dict.fromkeys(free_run[spots[1] + 1 :]): + stops = _occurrences(free_run, stop) + if stop != toggle and len(stops) >= 2 and stops[0] > spots[1]: + return toggle, spots, stop, stops + raise AssertionError("no parser case in the free run") + + +@pytest.mark.parametrize("where", ["inside-span", "between-stops"]) +def test_parser_state_carries_across_the_pause(tmp_path, free_run, where): + toggle, spots, stop, stops = _span_parser_case(free_run) + pause_at = spots[0] + 1 if where == "inside-span" else stops[0] + 1 + common = dict(max_tokens=80, setup=_install_span_parser(toggle, stop)) + baseline = run(tmp_path, "base", **common) + paused = run(tmp_path, "paused", pauses=[pause_at], **common) + try: + final = _final(baseline[2]) + assert final.finish_reason == "stop" + assert final.tool_calls + assert paused[1].park_count == 1 + assert_same_run(baseline, paused) + finally: + close(baseline, paused) + + +def test_a_parser_stop_on_the_pending_token_finishes_without_a_pause( + tmp_path, free_run +): + toggle, _, stop, stops = _span_parser_case(free_run) + common = dict(max_tokens=80, setup=_install_span_parser(toggle, stop)) + baseline = run(tmp_path, "base", **common) + # The pending token is the second stop token: the parser ends the request. + paused = run(tmp_path, "paused", pauses=[stops[1]], **common) + try: + assert _final(baseline[2]).finish_reason == "stop" + assert paused[1].park_count == 0 + assert "a" not in paused[0].scheduler._decode_resumes + assert paused[0].ssd.pinned_block_count == 0 + assert_same_run(baseline, paused) + finally: + close(baseline, paused) + + +# --- Logits processors and max_tokens ---------------------------------------------- + +THINK_END, THINK_LEAD, THINK_TRAIL = 5, 6, [7, 8] +BUDGET = 10 + + +def _thinking_setup(rig): + rig.scheduler._resolve_think_close_pattern = lambda *args: ( + [THINK_LEAD], + list(THINK_TRAIL), + ) + + +# Before the budget, on it, and inside the forced close sequence. +@pytest.mark.parametrize("pause_at", [BUDGET - 3, BUDGET - 1, BUDGET + 1, BUDGET + 3]) +def test_the_thinking_budget_forces_its_close_at_the_same_position(tmp_path, pause_at): + common = dict( + max_tokens=40, + setup=_thinking_setup, + request_attrs={"needs_think_prefix": True, "think_end_token_id": THINK_END}, + thinking_budget=BUDGET, + ) + baseline = run(tmp_path, "base", **common) + paused = run(tmp_path, "paused", pauses=[pause_at], **common) + try: + forced = [THINK_LEAD, THINK_END, *THINK_TRAIL] + tokens = list(baseline[1].output_token_ids) + start = next( + i for i in range(len(tokens)) if tokens[i : i + len(forced)] == forced + ) + assert start <= BUDGET # the budget closed thinking here + assert paused[1].park_count == 1 + assert_same_run(baseline, paused) + finally: + close(baseline, paused) + + +@pytest.mark.parametrize("pause_at", [5, 40]) +def test_repetition_penalty_context_carries_across_the_pause(tmp_path, pause_at): + common = dict(max_tokens=80, repetition_penalty=1.5, repetition_context_size=16) + baseline = run(tmp_path, "base", **common) + paused = run(tmp_path, "paused", pauses=[pause_at], **common) + try: + assert paused[1].park_count == 1 + assert_same_run(baseline, paused) + finally: + close(baseline, paused) + + +def test_two_pauses_keep_the_max_tokens_budget_exact(tmp_path): + baseline = run(tmp_path, "base", max_tokens=90) + paused = run(tmp_path, "paused", max_tokens=90, pauses=[3, 50]) + try: + assert paused[1].park_count == 2 + stats = paused[0].scheduler.get_park_stats() + assert stats["decode_pauses"] == stats["decode_resumes"] == 2 + assert len(paused[1].output_token_ids) == 90 + assert _final(paused[2]).finish_reason == "length" + assert_same_run(baseline, paused) + finally: + close(baseline, paused) + + +def test_a_stop_sequence_survives_two_pauses_inside_it(tmp_path, free_run): + i = _first_new_ngram(free_run, n=4) + stop = "".join(f"<{t}>" for t in free_run[i : i + 4]) + common = dict(max_tokens=80, tokenizer=TextTokenizer(), stop=[stop]) + baseline = run(tmp_path, "base", **common) + # A resumed row emits one token in its resume step, so the second pause + # comes two tokens later; both land inside the four-token sequence. + paused = run(tmp_path, "paused", pauses=[i, i + 2], **common) + try: + assert paused[1].park_count == 2 + assert_same_run(baseline, paused) + finally: + close(baseline, paused) From e4fde40b43c769e5b439466fe79711a30565881f Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Mon, 5 Oct 2026 14:35:25 -0600 Subject: [PATCH 22/46] feat(memory): pause a decoding victim at hard pressure before aborting 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. --- omlx/cache/paged_ssd_cache.py | 5 + omlx/process_memory_enforcer.py | 80 +++- omlx/scheduler.py | 411 ++++++++++++----- tests/test_memory_decode_pause.py | 437 +++++++++++++++++++ tests/test_scheduler_decode_pause_victims.py | 369 ++++++++++++++++ 5 files changed, 1181 insertions(+), 121 deletions(-) create mode 100644 tests/test_memory_decode_pause.py create mode 100644 tests/test_scheduler_decode_pause_victims.py diff --git a/omlx/cache/paged_ssd_cache.py b/omlx/cache/paged_ssd_cache.py index 7904ad5b64..c03936f8b4 100644 --- a/omlx/cache/paged_ssd_cache.py +++ b/omlx/cache/paged_ssd_cache.py @@ -4824,6 +4824,11 @@ def pinned_block_count(self) -> int: with self._pin_lock: return len(self._pinned_hashes) + def has_pending_writes(self, block_hashes: Iterable[bytes]) -> bool: + """Whether any block still waits in memory for the background writer.""" + with self._pending_write_hashes_lock: + return any(bytes(h) in self._pending_write_hashes for h in block_hashes) + def _pinned_snapshot(self) -> frozenset[bytes]: with self._pin_lock: return frozenset(self._pinned_hashes) diff --git a/omlx/process_memory_enforcer.py b/omlx/process_memory_enforcer.py index 19b0437211..a9d854320a 100644 --- a/omlx/process_memory_enforcer.py +++ b/omlx/process_memory_enforcer.py @@ -388,6 +388,9 @@ class _DrainingVictim: victim: Any # MemoryVictim polls: int = 0 # polls since its abort was requested executed: bool = False # its abort was seen to have run + # A decode-pause victim reports through its scheduler instead of the + # engine's abort probe: "pending", "declined" or "done". + status: Any = None # Callable[[], str] | None class ProcessMemoryEnforcer: @@ -1695,18 +1698,87 @@ def _still_draining_victim(self, engine: Any, model_id: str) -> Any: # Its abort ran and a further poll was observed: settled. self._draining_victim = None return None - draining.executed = not self._victim_abort_pending(engine, rid) + if draining.status is not None: + draining.executed = self._pause_status(draining) != "pending" + else: + draining.executed = not self._victim_abort_pending(engine, rid) logger.info( "Hard memory pressure: waiting for victim %s memory to drain on " - "'%s' (poll %d/%d, abort %s)", + "'%s' (poll %d/%d, %s %s)", rid, model_id, draining.polls, self._SINGLE_VICTIM_SETTLE_MAX_POLLS, + "pause" if draining.status is not None else "abort", "ran" if draining.executed else "pending", ) return draining.victim + @staticmethod + def _pause_status(draining: _DrainingVictim) -> str: + """A decode-pause victim's status; a failing probe counts as done.""" + try: + status = draining.status() + except Exception: # noqa: BLE001 + return "done" + return status if status in ("pending", "declined") else "done" + + def _request_decode_pause(self) -> int: + """At hard pressure with no prefill to park, pause one decoding row. + + Runs after ``_request_scheduler_park`` found no prefill victim. While + a pause victim drains (its pause has not run, or its exact chain still + waits for the SSD writer, then one settle poll) nothing else is + paused or aborted. A declined pause is forgotten at once, so the same + poll pauses another row or falls back to the single-victim abort. + While an aborted victim drains, no row is paused either. Returns 1 + when the abort is deferred, else 0. + """ + draining = self._draining_victim + if draining is not None and draining.status is None: + # An aborted victim is draining: the abort path waits for it. + return 0 + if draining is not None: + if self._pause_status(draining) == "declined": + logger.warning( + "Hard memory pressure: the decode pause of %s was declined " + "on '%s'", + draining.victim.request_id, + draining.model_id, + ) + self._draining_victim = None + elif self._still_draining_victim(None, draining.model_id) is not None: + return 1 + for model_id, entry in self._engine_pool._entries.items(): + scheduler = self._resolve_scheduler(entry) + select = getattr(scheduler, "select_decode_pause_victim", None) + pause = getattr(scheduler, "request_decode_pause", None) + status = getattr(scheduler, "decode_pause_status", None) + if not (callable(select) and callable(pause) and callable(status)): + continue + try: + victim = select() + rid = getattr(victim, "request_id", None) + if not isinstance(rid, str) or pause(rid) is not True: + continue + except Exception as exc: # noqa: BLE001 + logger.warning("Decode pause request failed on '%s': %s", model_id, exc) + continue + self._draining_victim = _DrainingVictim( + model_id, victim, status=lambda rid=rid, probe=status: probe(rid) + ) + logger.warning( + "Hard memory pressure: pausing decoding victim %s instead of " + "aborting (%d tokens, ~%.1f GB) on '%s'; %d request(s) kept", + rid, + victim.tokens, + victim.est_bytes / 1024**3, + model_id, + victim.kept, + ) + return 1 + return 0 + @staticmethod def _victim_abort_pending(engine: Any, request_id: str) -> bool: """Whether the engine still holds the victim (abort not run yet). @@ -2021,10 +2093,12 @@ async def _check_and_enforce(self) -> None: and self._park_deferred_polls < self._PARK_DEFER_POLLS_MAX ): parked_on = self._request_scheduler_park() + if not parked_on: + parked_on = self._request_decode_pause() if parked_on: self._park_deferred_polls += 1 logger.info( - "Hard memory pressure: parking a prefill victim on %d " + "Hard memory pressure: parking or pausing a victim on %d " "scheduler(s) instead of aborting (poll %d/%d)", parked_on, self._park_deferred_polls, diff --git a/omlx/scheduler.py b/omlx/scheduler.py index d01b73961b..ea14ab636c 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -1405,6 +1405,10 @@ class _DecodeResume: stop_matcher: Any = None +class _DecodePauseDeclinedError(Exception): + """A decode pause cannot proceed; the row keeps decoding (message: why).""" + + class _ResumedStopSequences: """Stop sequences whose first matcher resumes at a saved position. @@ -12181,6 +12185,9 @@ def _generation_batch(self) -> Any: def _decode_pause_exclusion_reason(self, request: Request) -> str | None: """Why a decoding row cannot be paused exactly (v1), or None.""" rid = request.request_id + failed = getattr(request, "_decode_pause_failed", None) + if failed: + return f"an earlier decode pause failed ({failed})" if ( request.specprefill_indices is not None or self._specprefill_active_request_id == rid @@ -12335,24 +12342,97 @@ def _process_pending_park(self, output: SchedulerOutput | None = None) -> bool: def _process_pending_decode_pauses(self, output: SchedulerOutput | None) -> bool: acted = False while self._pending_decode_pauses: - rid = self._pending_decode_pauses.pop() - request = self.requests.get(rid) - if ( - request is None - or rid not in self.running - or rid in self._pending_abort_ids - or not self._park_enabled() - ): - continue - reason = self._park_exclusion_reason(request) - if reason is not None: - logger.info("Decode pause skipped for %s: %s", rid, reason) - continue - if self._pause_decoding_request(request, output): - self._polls_since_park = 0 - acted = True + # The id stays pending until its pause has run, so the enforcer's + # drain probe never sees a pause in progress as finished. + rid = next(iter(list(self._pending_decode_pauses))) + try: + acted = self._process_one_decode_pause(rid, output) or acted + finally: + self._pending_decode_pauses.discard(rid) return acted + def _process_one_decode_pause( + self, rid: str, output: SchedulerOutput | None + ) -> bool: + request = self.requests.get(rid) + if ( + request is None + or rid not in self.running + or rid in self._pending_abort_ids + or not self._park_enabled() + ): + return False + reason = self._park_exclusion_reason(request) + if reason is not None: + logger.info("Decode pause skipped for %s: %s", rid, reason) + return False + if not self._pause_decoding_request(request, output): + return False + self._polls_since_park = 0 + return True + + def select_decode_pause_victim(self) -> MemoryVictim | None: + """Pick the decoding row whose pause frees the most memory. + + Candidates are decoding rows ``_park_exclusion_reason`` accepts that + are not already pending an abort or a pause. The largest live KV + (prompt plus output) goes first, the most recent arrival breaks ties. + The oldest admitted request is protected unless it is the only + candidate, as for a prefill park. Read-only: the caller asks for the + pause with ``request_decode_pause``. None when nothing is pausable. + """ + if not self._park_enabled(): + return None + try: + running = list(self.running.values()) + admitted = list(self.prefilling) + running + busy = set(self._pending_abort_ids) | set(self._pending_decode_pauses) + candidates = [ + request + for request in running + if request.request_id not in busy + and self._park_exclusion_reason(request) is None + ] + except RuntimeError: + return None # the queues mutated mid-read on the MLX thread + if not candidates: + return None + oldest = min(admitted, key=lambda r: (r.arrival_time, r.request_id)) + candidates.sort( + key=lambda r: (r.num_tokens, r.arrival_time, r.request_id), reverse=True + ) + victim = next( + (r for r in candidates if r.request_id != oldest.request_id), + candidates[0], + ) + tokens = victim.num_tokens + monitor = self.memory_monitor + est_bytes = ( + int(monitor.estimate_prompt_kv_bytes(tokens)) if monitor is not None else 0 + ) + return MemoryVictim(victim.request_id, tokens, est_bytes, kept=len(running) - 1) + + def decode_pause_status(self, request_id: str) -> str: + """Where a requested decode pause stands, for the memory enforcer. + + ``pending`` while the pause waits for its step or runs, and after it + ran while its exact chain's SSD writes still sit in memory; + ``declined`` when it failed and the row kept decoding; ``done`` once + the row's memory is free (paused and written, finished, or gone). + """ + if request_id in self._pending_decode_pauses: + return "pending" + request = self.requests.get(request_id) + if request is not None and getattr(request, "_decode_pause_failed", None): + return "declined" + pins = self._park_pins.get(request_id) + ssd = self.paged_ssd_cache_manager + if request_id in self._decode_resumes and pins is not None and ssd is not None: + has_pending = getattr(ssd, "has_pending_writes", None) + if callable(has_pending) and has_pending(pins.hashes) is True: + return "pending" + return "done" + def _pause_decoding_request( self, request: Request, output: SchedulerOutput | None ) -> bool: @@ -12365,119 +12445,130 @@ def _pause_decoding_request( normally), the KV is stored as an exact chain under a request domain and pinned, and the row leaves the batch the way an abort removes it while the request keeps its output, detokenizer, parser session and - client stream. Any failure before the emission leaves the row - decoding untouched. + client stream. + + Any failure before the emission leaves the row decoding untouched: + a stored chain is unpinned and deleted, the request is marked so it + is not chosen again, and the caller falls back to an abort. A failure + after the emission cannot keep decoding (the token is streamed but + still pending in the batch), so the request ends with an error. """ rid = request.request_id - uid = self.request_id_to_uid[rid] - generation_batch = self._generation_batch() - _safe_sync_stream(self._stream) - row = generation_batch.uids.index(uid) - with mx.stream(self._stream): - mx.eval(generation_batch._next_tokens) - pending = int(generation_batch._next_tokens[row].item()) - - matcher = generation_batch._matchers[row] - stop_matcher = type(matcher)(matcher._root) - stop_matcher._node = matcher._node - stops = stop_matcher.advance(pending) - emitted = generation_batch._num_tokens[row] + 1 - max_tokens = generation_batch.max_tokens[row] - if stops or emitted >= max_tokens: - logger.info( - "Decode pause skipped for %s: its pending token finishes the " - "request", + chain = None # (tokens, domain) once a store may have written blocks + emitting = False + try: + uid = self.request_id_to_uid[rid] + generation_batch = self._generation_batch() + _safe_sync_stream(self._stream) + row = generation_batch.uids.index(uid) + with mx.stream(self._stream): + mx.eval(generation_batch._next_tokens) + pending = int(generation_batch._next_tokens[row].item()) + + matcher = generation_batch._matchers[row] + stop_matcher = type(matcher)(matcher._root) + stop_matcher._node = matcher._node + stops = stop_matcher.advance(pending) + emitted = generation_batch._num_tokens[row] + 1 + max_tokens = generation_batch.max_tokens[row] + if stops or emitted >= max_tokens: + logger.info( + "Decode pause skipped for %s: its pending token finishes the " + "request", + rid, + ) + return False + + row_cache, row_tokens = self.batch_generator.extract_cache([uid])[uid] + saved_tokens = [int(t) for t in row_tokens] + offset = max((_cache_layer_token_count(c) for c in row_cache), default=0) + expected = request.num_prompt_tokens + request.num_output_tokens + if offset != len(saved_tokens) or len(saved_tokens) != expected: + raise _DecodePauseDeclinedError( + f"cache offset {offset}, batch tokens {len(saved_tokens)}, " + f"prompt + output {expected} disagree" + ) + + park_number = request.park_count + 1 + storage_id = f"{rid}:decode-pause-{park_number}" + domain_key = ( + "decode-resume", rid, + str(park_number), + str(request.vlm_extra_keys_for_cache or ()), ) - return False + cache_states, model_cache_config = self._extract_cache_states(row_cache) + table = None + if cache_states: + with mx.stream(self._stream): + arrays = self._collect_arrays_from_extracted_cache(cache_states) + if arrays: + mx.eval(*arrays) + chain = (saved_tokens, domain_key) + table = self.block_aware_cache.store_exact_prefix( + storage_id, + saved_tokens, + cache_states, + model_cache_config=model_cache_config, + domain_key=domain_key, + ) + if table is None or not self._pin_exact_chain(rid, table): + raise _DecodePauseDeclinedError( + f"the exact prefix of {len(saved_tokens)} tokens could not be " + "stored and pinned" + ) - row_cache, row_tokens = self.batch_generator.extract_cache([uid])[uid] - saved_tokens = [int(t) for t in row_tokens] - offset = max((_cache_layer_token_count(c) for c in row_cache), default=0) - expected = request.num_prompt_tokens + request.num_output_tokens - if offset != len(saved_tokens) or len(saved_tokens) != expected: - logger.warning( - "Decode pause declined for %s: cache offset %d, batch tokens %d, " - "prompt + output %d disagree", - rid, - offset, - len(saved_tokens), - expected, + response = GenerationBatch.Response( + uid=uid, + token=pending, + logprobs=( + generation_batch._next_logprobs[row] + if row < len(generation_batch._next_logprobs) + else None + ), + finish_reason=None, + prompt_cache=None, + all_tokens=None, ) - return False + emitting = True + outputs, finished_ids = self._process_batch_responses([response]) + if output is not None: + output.outputs.extend(outputs) + output.finished_request_ids.update(finished_ids) + if finished_ids: + # A stop string or parser stop ended it: no pause after all. + self._discard_exact_chain(rid, chain) + self._cleanup_finished(finished_ids) + return False - park_number = request.park_count + 1 - storage_id = f"{rid}:decode-pause-{park_number}" - domain_key = ( - "decode-resume", - rid, - str(park_number), - str(request.vlm_extra_keys_for_cache or ()), - ) - cache_states, model_cache_config = self._extract_cache_states(row_cache) - table = None - if cache_states: - with mx.stream(self._stream): - arrays = self._collect_arrays_from_extracted_cache(cache_states) - if arrays: - mx.eval(*arrays) - table = self.block_aware_cache.store_exact_prefix( - storage_id, - saved_tokens, - cache_states, - model_cache_config=model_cache_config, + from .api.grammar import GrammarConstraintProcessor + + processors = list(generation_batch.logits_processors[row] or ()) + for processor in processors: + if ( + isinstance(processor, GrammarConstraintProcessor) + and processor.pending + ): + processor.accept_token(pending) + + self._decode_resumes[rid] = _DecodeResume( + storage_id=storage_id, domain_key=domain_key, + tokens=saved_tokens, + kickoff=pending, + remaining_max_tokens=max_tokens - emitted, + sampler=generation_batch.samplers[row], + logits_processors=processors, + stop_sequences=_unwrap_stop_sequences( + generation_batch.stop_sequences[row] + ), + stop_matcher=stop_matcher, ) - if table is None or not self._pin_exact_chain(rid, table): - logger.warning( - "Decode pause declined for %s: the exact prefix of %d tokens " - "could not be stored and pinned", - rid, - len(saved_tokens), - ) - return False - - response = GenerationBatch.Response( - uid=uid, - token=pending, - logprobs=( - generation_batch._next_logprobs[row] - if row < len(generation_batch._next_logprobs) - else None - ), - finish_reason=None, - prompt_cache=None, - all_tokens=None, - ) - outputs, finished_ids = self._process_batch_responses([response]) - if output is not None: - output.outputs.extend(outputs) - output.finished_request_ids.update(finished_ids) - if finished_ids: - # A stop string or parser stop ended it: no pause after all. - self._unpin_parked(rid) - self._cleanup_finished(finished_ids) + self._remove_decoding_row(rid, uid) + except Exception as exc: # noqa: BLE001 + self._decode_pause_failed(request, chain, exc, emitted=emitting, out=output) return False - from .api.grammar import GrammarConstraintProcessor - - processors = list(generation_batch.logits_processors[row] or ()) - for processor in processors: - if isinstance(processor, GrammarConstraintProcessor) and processor.pending: - processor.accept_token(pending) - - self._decode_resumes[rid] = _DecodeResume( - storage_id=storage_id, - domain_key=domain_key, - tokens=saved_tokens, - kickoff=pending, - remaining_max_tokens=max_tokens - emitted, - sampler=generation_batch.samplers[row], - logits_processors=processors, - stop_sequences=_unwrap_stop_sequences(generation_batch.stop_sequences[row]), - stop_matcher=stop_matcher, - ) - self._remove_decoding_row(rid, uid) request.status = RequestStatus.WAITING request.batch_uid = None request.prompt_cache = None @@ -12499,6 +12590,90 @@ def _pause_decoding_request( ) return True + def _decode_pause_failed( + self, + request: Request, + chain: tuple[list[int], tuple[str, ...]] | None, + exc: Exception, + *, + emitted: bool, + out: SchedulerOutput | None, + ) -> None: + """Undo a failed decode pause (see ``_pause_decoding_request``).""" + rid = request.request_id + reason = ( + str(exc) + if isinstance(exc, _DecodePauseDeclinedError) + else f"{type(exc).__name__}: {exc}" + ) + self._decode_resumes.pop(rid, None) + try: + self._discard_exact_chain(rid, chain) + except Exception: # noqa: BLE001 + logger.warning( + "Decode pause cleanup for %s could not delete its exact chain", + rid, + exc_info=True, + ) + # Never chosen again: the enforcer falls back to its abort instead. + request._decode_pause_failed = reason # type: ignore[attr-defined] + if not emitted: + logger.warning( + "Decode pause declined for %s: %s; the row keeps decoding", + rid, + reason, + ) + return + logger.error( + "Decode pause failed for %s after its pending token was streamed: %s; " + "ending the request with an error", + rid, + reason, + exc_info=not isinstance(exc, _DecodePauseDeclinedError), + ) + self._do_abort_request(rid) + if out is not None: + out.outputs.append( + RequestOutput( + request_id=rid, + finished=True, + finish_reason="error", + error=f"decode_pause_failed: {reason}", + error_code="decode_pause_failed", + ) + ) + out.finished_request_ids.add(rid) + + def _discard_exact_chain( + self, + request_id: str, + chain: tuple[list[int], tuple[str, ...]] | None, + ) -> None: + """Unpin and delete an exact chain stored for a pause that did not happen. + + The chain is found by its domain hashes, so blocks a store wrote + before it failed are found too. They belong to one request domain + (never shared by dedup), so deleting them cannot hurt another request. + """ + self._unpin_parked(request_id) + cache = self.block_aware_cache + exact_hashes = getattr(cache, "_exact_prefix_hashes", None) + if chain is None or not callable(exact_hashes): + return + tokens, domain_key = chain + manager = self.paged_cache_manager + ssd = self.paged_ssd_cache_manager + for block_hash, _ in exact_hashes(tokens, domain_key): + if ssd is not None: + ssd.delete_block(bytes(block_hash)) + block = ( + manager.cached_block_hash_to_block.get_block(block_hash) + if manager is not None + else None + ) + if block is not None and block.ref_count == 0: + manager.evict_block_permanently(block.block_id) + def _remove_decoding_row(self, request_id: str, uid: int) -> None: """Take a row out of the batch as an abort does, keeping the request.""" _safe_sync_stream(self._stream) diff --git a/tests/test_memory_decode_pause.py b/tests/test_memory_decode_pause.py new file mode 100644 index 0000000000..edfbe82416 --- /dev/null +++ b/tests/test_memory_decode_pause.py @@ -0,0 +1,437 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Hard memory pressure pauses a decoding row before it aborts anything. + +The enforcer asks for a prefill park first; with no prefill to park it pauses +one decoding row (``request_decode_pause``) and waits for that pause to run +and its exact chain to reach the SSD before it counts the memory as freed. +Only when no row can be paused does it fall back to the single-victim abort. +Emergency pressure still aborts everything. + +The first group drives the enforcer against a scripted scheduler; the second +wires the real enforcer to the real scheduler of the park suite's ``_Rig``. +""" + +import logging +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest +import test_scheduler_decode_pause as dp +import test_scheduler_park as park +from test_process_memory_enforcer import ( # noqa: F401 (fixture) + _make_enforcer, + _make_entry, + mock_engine_pool, +) + +from omlx.request import MemoryVictim, Request, SamplingParams + +GB = 1024**3 + + +@pytest.fixture +def enforcer(mock_engine_pool): # noqa: F811 + # Hard watermark (95 GB) below the ceiling (100 GB): hard is not an + # emergency until usage passes the ceiling by the emergency margin. + return _make_enforcer( + mock_engine_pool, + ceiling=100 * GB, + soft_threshold=0.85, + hard_threshold=0.95, + ) + + +async def tick(enforcer, usage_gb): + with patch("omlx.process_memory_enforcer.mx") as mock_mx: + mock_mx.get_active_memory.return_value = usage_gb * GB + mock_mx.get_cache_memory.return_value = 0 + await enforcer._check_and_enforce() + + +def _busy(enforcer, engine): + entry = _make_entry("big-model", engine=engine) + entry.in_use = 1 + enforcer._engine_pool._entries = {"big-model": entry} + enforcer._engine_pool._find_lru_victim.return_value = None + return entry + + +class _ScriptedScheduler: + """The scheduler surface the enforcer's park and pause paths use.""" + + def __init__(self, victims): + self.victims = list(victims) + self.paused: list[str] = [] + self.status: dict[str, str] = {} + self.park_answer = False + + def request_park_prefill(self): + return self.park_answer + + def select_decode_pause_victim(self): + return self.victims[0] if self.victims else None + + def request_decode_pause(self, request_id): + self.paused.append(request_id) + self.victims = [v for v in self.victims if v.request_id != request_id] + self.status[request_id] = "pending" + return True + + def decode_pause_status(self, request_id): + return self.status.get(request_id, "done") + + def note_pressure_poll(self, level): + pass + + def adjust_store_cache_cap(self, *args, **kwargs): + pass + + +def _engine(scheduler, abort_victims=()): + engine = MagicMock() + engine.has_active_requests.return_value = False + engine.scheduler = scheduler + engine.abort_all_requests = AsyncMock(return_value=3) + engine.abort_one_request_for_memory = AsyncMock( + side_effect=[MemoryVictim(rid, 9_000, GB, 1) for rid in abort_victims] + [None] + ) + engine.memory_victim_pending = MagicMock(return_value=False) + return engine + + +def _victim(rid, kept=2): + return MemoryVictim(rid, 90_000, 6 * GB, kept) + + +@pytest.fixture(autouse=True) +def single_victim_on(monkeypatch): + """Every enforcer built here aborts one victim (memory.abort_single_victim).""" + from omlx.process_memory_enforcer import ProcessMemoryEnforcer + + real_init = ProcessMemoryEnforcer.__init__ + + def init(self, *args, **kwargs): + kwargs.setdefault("abort_single_victim", True) + real_init(self, *args, **kwargs) + + monkeypatch.setattr(ProcessMemoryEnforcer, "__init__", init) + + +class TestEnforcerPausesDecodingVictims: + @pytest.mark.asyncio + async def test_hard_pressure_pauses_one_decoding_row_instead_of_aborting( + self, enforcer, caplog + ): + scheduler = _ScriptedScheduler([_victim("big"), _victim("next", kept=1)]) + engine = _engine(scheduler) + _busy(enforcer, engine) + + with caplog.at_level(logging.WARNING): + await tick(enforcer, 97) + + assert scheduler.paused == ["big"] + engine.abort_one_request_for_memory.assert_not_awaited() + engine.abort_all_requests.assert_not_awaited() + assert ( + "Hard memory pressure: pausing decoding victim big instead of aborting" + in caplog.text + ) + + @pytest.mark.asyncio + async def test_a_prefill_park_comes_before_any_decode_pause(self, enforcer): + scheduler = _ScriptedScheduler([_victim("big")]) + scheduler.park_answer = True + engine = _engine(scheduler) + _busy(enforcer, engine) + + await tick(enforcer, 97) + + assert scheduler.paused == [] + engine.abort_all_requests.assert_not_awaited() + + @pytest.mark.asyncio + async def test_no_second_victim_while_the_pause_or_its_store_drains(self, enforcer): + scheduler = _ScriptedScheduler([_victim("big"), _victim("next", kept=1)]) + engine = _engine(scheduler) + _busy(enforcer, engine) + + await tick(enforcer, 97) # pause requested + for _ in range(3): # not run yet, then its chain still being written + await tick(enforcer, 97) + assert scheduler.paused == ["big"] + + scheduler.status["big"] = "done" + await tick(enforcer, 97) # seen done: one settle poll + assert scheduler.paused == ["big"] + await tick(enforcer, 97) # settled and still hard: the next one + assert scheduler.paused == ["big", "next"] + engine.abort_one_request_for_memory.assert_not_awaited() + engine.abort_all_requests.assert_not_awaited() + + @pytest.mark.asyncio + async def test_a_pause_that_never_drains_is_bounded(self, enforcer): + scheduler = _ScriptedScheduler([_victim("big"), _victim("next", kept=1)]) + engine = _engine(scheduler) + _busy(enforcer, engine) + + await tick(enforcer, 97) + for _ in range(enforcer._SINGLE_VICTIM_SETTLE_MAX_POLLS): + await tick(enforcer, 97) + assert scheduler.paused == ["big"] + await tick(enforcer, 97) + assert scheduler.paused == ["big", "next"] + + @pytest.mark.asyncio + async def test_a_declined_pause_falls_back_to_the_single_victim_abort_at_once( + self, enforcer, caplog + ): + scheduler = _ScriptedScheduler([_victim("big")]) + engine = _engine(scheduler, abort_victims=["big"]) + _busy(enforcer, engine) + + await tick(enforcer, 97) + assert scheduler.paused == ["big"] + scheduler.status["big"] = "declined" + with caplog.at_level(logging.WARNING): + await tick(enforcer, 97) + + assert "decode pause of big was declined" in caplog.text + engine.abort_one_request_for_memory.assert_awaited_once_with(spare_parked=True) + engine.abort_all_requests.assert_not_awaited() + + @pytest.mark.asyncio + async def test_nothing_pausable_falls_back_to_the_single_victim_abort( + self, enforcer + ): + scheduler = _ScriptedScheduler([]) + engine = _engine(scheduler, abort_victims=["big"]) + _busy(enforcer, engine) + + await tick(enforcer, 97) + + engine.abort_one_request_for_memory.assert_awaited_once_with(spare_parked=True) + engine.abort_all_requests.assert_not_awaited() + + @pytest.mark.asyncio + async def test_no_pause_while_an_aborted_victim_drains(self, enforcer): + scheduler = _ScriptedScheduler([]) + engine = _engine(scheduler, abort_victims=["big"]) + engine.memory_victim_pending.return_value = True + _busy(enforcer, engine) + await tick(enforcer, 97) # aborts ``big`` + scheduler.victims = [_victim("other")] + + await tick(enforcer, 97) + + assert scheduler.paused == [] + assert engine.abort_one_request_for_memory.await_count == 1 + + @pytest.mark.asyncio + async def test_emergency_aborts_everything_without_pausing(self, enforcer): + scheduler = _ScriptedScheduler([_victim("big")]) + engine = _engine(scheduler) + _busy(enforcer, engine) + + await tick(enforcer, 103) + + assert scheduler.paused == [] + engine.abort_all_requests.assert_awaited_once_with(spare_parked=False) + + @pytest.mark.asyncio + async def test_a_failing_scheduler_hook_falls_back_to_the_abort( + self, enforcer, caplog + ): + scheduler = _ScriptedScheduler([_victim("big")]) + scheduler.request_decode_pause = MagicMock(side_effect=RuntimeError("gone")) + engine = _engine(scheduler, abort_victims=["big"]) + _busy(enforcer, engine) + + with caplog.at_level(logging.WARNING): + await tick(enforcer, 97) + + assert "Decode pause request failed on 'big-model': gone" in caplog.text + engine.abort_one_request_for_memory.assert_awaited_once() + + @pytest.mark.asyncio + async def test_a_scheduler_without_the_pause_api_aborts_as_before(self, enforcer): + scheduler = SimpleNamespace( + request_park_prefill=lambda: False, + note_pressure_poll=lambda level: None, + adjust_store_cache_cap=lambda *a, **k: None, + ) + engine = _engine(scheduler, abort_victims=["big"]) + _busy(enforcer, engine) + + await tick(enforcer, 97) + + engine.abort_one_request_for_memory.assert_awaited_once() + + +# --- Real enforcer, real scheduler ------------------------------------------------- + +PROMPTS = {"a": dp.PROMPT, "b": dp.OTHER, "c": park.PROMPT_D} +MAX_TOKENS = 60 + + +def _submit_three(rig): + rows = [] + for i, (rid, tokens) in enumerate(PROMPTS.items()): + request = Request( + request_id=rid, + prompt=list(tokens), + sampling_params=SamplingParams(max_tokens=MAX_TOKENS, temperature=0), + arrival_time=float(i + 1), + ) + rig.scheduler.add_request(request) + rows.append(request) + return rows + + +def _baseline(tmp_path): + rig = dp.make_rig(tmp_path / "baseline", park_enabled=False) + try: + rows = _submit_three(rig) + outputs = park.run_to_completion(rig, rows, limit=10 * MAX_TOKENS) + return {r.request_id: list(r.output_token_ids) for r in rows}, outputs + finally: + rig.close() + + +def _decoding(rig, rows, count=5, outputs=None): + scheduler = rig.scheduler + outputs = [] if outputs is None else outputs + for _ in range(400): + if all( + len(r.output_token_ids) >= count and r.request_id in scheduler.running + for r in rows + ): + return + outputs.extend(park.step(rig)) + raise AssertionError("rows are not all decoding") + + +def _rig_engine(rig): + scheduler = rig.scheduler + engine = SimpleNamespace( + scheduler=scheduler, + has_active_requests=lambda: False, + abort_all_requests=AsyncMock(return_value=0), + abort_one_request_for_memory=AsyncMock(return_value=None), + memory_victim_pending=lambda rid: False, + ) + return engine + + +def _text(outputs, rid): + return "".join(o.new_text for o in outputs if o.request_id == rid) + + +@pytest.mark.asyncio +async def test_three_decoding_rows_at_hard_pressure_pause_one_and_finish_identically( + tmp_path, enforcer, caplog +): + expected, base_outputs = _baseline(tmp_path) + rig = dp.make_rig(tmp_path / "paused") + try: + scheduler = rig.scheduler + engine = _rig_engine(rig) + _busy(enforcer, engine) + rows = _submit_three(rig) + outputs = [] + _decoding(rig, rows, outputs=outputs) + + with caplog.at_level(logging.WARNING): + await tick(enforcer, 97) + (paused_id,) = [ + rid for rid in PROMPTS if rid in scheduler._pending_decode_pauses + ] + assert paused_id != "a" # the oldest admitted request is protected + assert f"pausing decoding victim {paused_id} instead of aborting" in caplog.text + outputs.extend(park.step(rig)) + + paused = scheduler.requests[paused_id] + others = [r for r in rows if r.request_id != paused_id] + assert paused.parked and paused_id not in scheduler.running + assert all(r.request_id in scheduler.running for r in others) + engine.abort_one_request_for_memory.assert_not_awaited() + engine.abort_all_requests.assert_not_awaited() + + # Still hard: no second row is paused while the first one settles, + # and the others keep decoding. + before = {r.request_id: len(r.output_token_ids) for r in others} + frozen = len(paused.output_token_ids) + await tick(enforcer, 97) + outputs.extend(park.step(rig, 3)) + assert not scheduler._pending_decode_pauses + assert all(len(r.output_token_ids) > before[r.request_id] for r in others) + assert len(paused.output_token_ids) == frozen + + # Pressure clears: the paused row resumes and every row completes. + for _ in range(4): + await tick(enforcer, 1) + outputs.extend(park.step(rig)) + outputs.extend(park.run_to_completion(rig, rows, limit=10 * MAX_TOKENS)) + + for row in rows: + rid = row.request_id + assert list(row.output_token_ids) == expected[rid] + assert dp.streamed_tokens(outputs, rid) == expected[rid] + assert _text(outputs, rid) == _text(base_outputs, rid) + (final,) = [o for o in outputs if o.request_id == rid and o.finished] + assert final.finish_reason == "length" and not final.error + stats = scheduler.get_park_stats() + assert stats["decode_pauses"] == stats["decode_resumes"] == 1 + engine.abort_one_request_for_memory.assert_not_awaited() + engine.abort_all_requests.assert_not_awaited() + finally: + rig.close() + + +@pytest.mark.asyncio +async def test_nothing_pausable_on_the_real_scheduler_aborts_a_single_victim( + tmp_path, enforcer, monkeypatch +): + rig = dp.make_rig(tmp_path) + try: + scheduler = rig.scheduler + engine = _rig_engine(rig) + engine.abort_one_request_for_memory = AsyncMock( + return_value=MemoryVictim("b", 30, 0, 2) + ) + _busy(enforcer, engine) + rows = _submit_three(rig) + _decoding(rig, rows) + monkeypatch.setattr( + scheduler, "_decode_pause_exclusion_reason", lambda request: "test" + ) + + await tick(enforcer, 97) + + assert not scheduler._pending_decode_pauses + engine.abort_one_request_for_memory.assert_awaited_once_with(spare_parked=True) + engine.abort_all_requests.assert_not_awaited() + finally: + rig.close() + + +@pytest.mark.asyncio +async def test_emergency_on_the_real_scheduler_still_aborts_everything( + tmp_path, enforcer +): + rig = dp.make_rig(tmp_path) + try: + scheduler = rig.scheduler + engine = _rig_engine(rig) + _busy(enforcer, engine) + rows = _submit_three(rig) + _decoding(rig, rows) + + await tick(enforcer, 103) + park.step(rig) + + assert not scheduler._pending_decode_pauses + assert not any(r.parked for r in rows) + engine.abort_all_requests.assert_awaited_once_with(spare_parked=False) + engine.abort_one_request_for_memory.assert_not_awaited() + finally: + rig.close() diff --git a/tests/test_scheduler_decode_pause_victims.py b/tests/test_scheduler_decode_pause_victims.py new file mode 100644 index 0000000000..5e0d67637e --- /dev/null +++ b/tests/test_scheduler_decode_pause_victims.py @@ -0,0 +1,369 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Decode-pause victims: who is paused, how the enforcer follows a pause, and +what a pause that fails leaves behind. + +Runs the real scheduler step loop on the park suite's ``_Rig`` (tiny Qwen3.5 +hybrid model, real paged-SSD stores). A pause that fails before the row +leaves the batch must leave it decoding exactly as if nothing was asked, with +its stored chain unpinned and deleted, and mark it so the enforcer falls back +to the abort instead of choosing it again. +""" + +import logging + +import pytest +import test_scheduler_decode_pause as dp +import test_scheduler_park as park + +from omlx.adapter.output_parser import ( + OutputParserFactory, + OutputParserFinalizeResult, + OutputParserTokenResult, +) +from omlx.request import Request, SamplingParams + +PROMPT, OTHER = dp.PROMPT, dp.OTHER +THIRD = park.PROMPT_D + + +def submit(rig, request_id, tokens, max_tokens, arrival): + request = Request( + request_id=request_id, + prompt=list(tokens), + sampling_params=SamplingParams(max_tokens=max_tokens, temperature=0), + arrival_time=arrival, + ) + rig.scheduler.add_request(request) + return request + + +def step_until_decoding(rig, requests, count=3, limit=400): + """Step until every row has ``count`` outputs and is pausable.""" + scheduler = rig.scheduler + for _ in range(limit): + if all( + len(r.output_token_ids) >= count + and r.request_id in scheduler.running + and scheduler._park_exclusion_reason(r) is None + for r in requests + ): + return + park.step(rig) + raise AssertionError("rows are not all decoding") + + +# --- Victim choice ----------------------------------------------------------------- + + +def _three_decoding(rig, prompts=(PROMPT, OTHER, THIRD), max_tokens=80): + rows = [ + submit(rig, rid, tokens, max_tokens, arrival=float(i + 1)) + for i, (rid, tokens) in enumerate(zip("abc", prompts)) + ] + step_until_decoding(rig, rows) + return rows + + +def test_the_largest_live_kv_is_paused_and_the_oldest_is_protected(tmp_path): + rig = dp.make_rig(tmp_path) + try: + # ``a`` is oldest and holds the largest KV (a 120-token prompt). + a, b, c = _three_decoding( + rig, prompts=(PROMPT * 5, OTHER, THIRD), max_tokens=200 + ) + # Equalize the output counts the prefill order skews, then give + # ``b`` the larger KV of the two younger rows. + for row in (a, b, c): + row.output_token_ids = row.output_token_ids[:3] + b.output_token_ids = b.output_token_ids + [3, 3] + assert a.num_tokens > b.num_tokens > c.num_tokens + victim = rig.scheduler.select_decode_pause_victim() + assert victim.request_id == "b" + assert victim.tokens == b.num_tokens + assert victim.kept == 2 + finally: + rig.close() + + +def test_equal_kv_goes_to_the_most_recent_arrival(tmp_path): + rig = dp.make_rig(tmp_path) + try: + a, b, c = _three_decoding(rig, prompts=(PROMPT, PROMPT, PROMPT)) + # Same prompt length; equalize the output counts the prefill order skews. + for row in (a, b, c): + row.output_token_ids = row.output_token_ids[:3] + assert rig.scheduler.select_decode_pause_victim().request_id == "c" + finally: + rig.close() + + +def test_the_oldest_is_paused_when_it_is_the_only_candidate(tmp_path): + rig = dp.make_rig(tmp_path) + try: + (a,) = [submit(rig, "a", PROMPT, 80, arrival=1.0)] + step_until_decoding(rig, [a]) + assert rig.scheduler.select_decode_pause_victim().request_id == "a" + finally: + rig.close() + + +def test_excluded_and_already_pending_rows_are_never_chosen(tmp_path): + rig = dp.make_rig(tmp_path) + try: + scheduler = rig.scheduler + a, b, c = _three_decoding(rig) + c._decode_pause_failed = "test" + assert scheduler.request_decode_pause("b") is True + # ``a`` is the oldest, but it is the only candidate left. + assert scheduler.select_decode_pause_victim().request_id == "a" + scheduler._pending_abort_ids.add("a") + assert scheduler.select_decode_pause_victim() is None + finally: + rig.close() + + +def test_nothing_is_chosen_when_park_is_disabled(tmp_path): + rig = dp.make_rig(tmp_path, park_enabled=False) + try: + _three_decoding(rig) + assert rig.scheduler.select_decode_pause_victim() is None + finally: + rig.close() + + +# --- Status the enforcer drains on --------------------------------------------------- + + +def test_the_status_is_pending_until_the_pause_ran_and_its_chain_is_written( + tmp_path, monkeypatch +): + rig = dp.make_rig(tmp_path) + try: + scheduler = rig.scheduler + scheduler._park_hold_applies = lambda head: True # keep it parked + (a,) = [submit(rig, "a", PROMPT, 80, arrival=1.0)] + step_until_decoding(rig, [a]) + assert scheduler.decode_pause_status("a") == "done" # nothing asked + + assert scheduler.request_decode_pause("a") is True + assert scheduler.decode_pause_status("a") == "pending" + + writes = {"pending": True} + monkeypatch.setattr( + rig.ssd, "has_pending_writes", lambda hashes: writes["pending"] + ) + park.step(rig) + assert a.parked + assert scheduler.decode_pause_status("a") == "pending" # still writing + writes["pending"] = False + assert scheduler.decode_pause_status("a") == "done" + finally: + rig.close() + + +def test_the_status_stays_pending_while_the_pause_runs(tmp_path, monkeypatch): + rig = dp.make_rig(tmp_path) + try: + scheduler = rig.scheduler + (a,) = [submit(rig, "a", PROMPT, 80, arrival=1.0)] + step_until_decoding(rig, [a]) + seen = [] + original = scheduler._pause_decoding_request + + def observe(request, output): + seen.append(scheduler.decode_pause_status("a")) + return original(request, output) + + monkeypatch.setattr(scheduler, "_pause_decoding_request", observe) + assert scheduler.request_decode_pause("a") is True + park.step(rig) + assert seen == ["pending"] + assert not scheduler._pending_decode_pauses + finally: + rig.close() + + +# --- A pause that fails -------------------------------------------------------------- + + +def _ids_of(rig, table): + hashes = [] + for block_id in table.block_ids: + block = rig.paged.allocated_blocks.get(block_id) + hashes.append(bytes(block.block_hash)) + return hashes + + +def _fail_extract(rig, monkeypatch, store): + def boom(uids): + raise RuntimeError("extract exploded") + + monkeypatch.setattr(rig.scheduler.batch_generator, "extract_cache", boom) + + +def _fail_after_store(rig, monkeypatch, store): + original = rig.prefix.store_exact_prefix + + def store_then_fail(*args, **kwargs): + table = original(*args, **kwargs) + store["hashes"] = _ids_of(rig, table) + raise OSError("disk vanished mid-store") + + monkeypatch.setattr(rig.prefix, "store_exact_prefix", store_then_fail) + + +def _fail_pin(rig, monkeypatch, store): + original = rig.prefix.store_exact_prefix + + def store_and_record(*args, **kwargs): + table = original(*args, **kwargs) + store["hashes"] = _ids_of(rig, table) + return table + + monkeypatch.setattr(rig.prefix, "store_exact_prefix", store_and_record) + monkeypatch.setattr(rig.scheduler, "_pin_exact_chain", lambda rid, table: False) + + +@pytest.mark.parametrize( + "inject, reason", + [ + (_fail_extract, "RuntimeError: extract exploded"), + (_fail_after_store, "OSError: disk vanished mid-store"), + (_fail_pin, "could not be stored and pinned"), + ], + ids=["extract", "store", "pin"], +) +def test_a_pause_failing_before_the_row_leaves_keeps_it_decoding_exactly( + tmp_path, monkeypatch, caplog, inject, reason +): + (expected,) = dp.baseline(tmp_path, 40) + rig = dp.make_rig(tmp_path / "paused") + try: + scheduler = rig.scheduler + request = submit(rig, "a", PROMPT, 40, arrival=1.0) + outputs = [] + dp.step_until_outputs(rig, request, 5, outputs) + store = {} + inject(rig, monkeypatch, store) + + assert scheduler.request_decode_pause("a") is True + with caplog.at_level(logging.WARNING, logger="omlx.scheduler"): + outputs.extend(park.step(rig)) + monkeypatch.undo() + + warnings = [ + r.getMessage() + for r in caplog.records + if r.levelno == logging.WARNING + and "Decode pause declined for a" in r.getMessage() + ] + assert len(warnings) == 1 and reason in warnings[0] + assert "the row keeps decoding" in warnings[0] + assert "a" in scheduler.running and not request.parked + assert request.park_count == 0 + assert "a" not in scheduler._decode_resumes + assert not scheduler._park_pins and rig.ssd.pinned_block_count == 0 + for block_hash in store.get("hashes", ()): + assert not rig.ssd.has_block(block_hash) + # Never chosen again: the enforcer falls back to the abort. + assert "an earlier decode pause failed" in scheduler._park_exclusion_reason( + request + ) + assert scheduler.decode_pause_status("a") == "declined" + assert scheduler.select_decode_pause_victim() is None + + outputs.extend(park.run_to_completion(rig, [request])) + assert list(request.output_token_ids) == expected + assert dp.streamed_tokens(outputs, "a") == expected + assert not [o for o in outputs if o.error] + finally: + rig.close() + + +def test_a_pause_failing_after_the_pending_token_streamed_ends_with_an_error( + tmp_path, monkeypatch, caplog +): + (expected,) = dp.baseline(tmp_path, 40) + rig = dp.make_rig(tmp_path / "paused") + try: + scheduler = rig.scheduler + request = submit(rig, "a", PROMPT, 40, arrival=1.0) + outputs = [] + dp.step_until_outputs(rig, request, 5, outputs) + + def boom(request_id, uid): + raise RuntimeError("batch filter exploded") + + monkeypatch.setattr(scheduler, "_remove_decoding_row", boom) + assert scheduler.request_decode_pause("a") is True + with caplog.at_level(logging.ERROR, logger="omlx.scheduler"): + step_outputs = park.step(rig) + monkeypatch.undo() + outputs.extend(step_outputs) + + # The pending token reached the client once, then the error. + assert dp.streamed_tokens(outputs, "a") == expected[:6] + (error,) = [o for o in outputs if o.error] + assert error.finished and error.finish_reason == "error" + assert error.error_code == "decode_pause_failed" + assert "batch filter exploded" in error.error + assert "a" not in scheduler.running and "a" not in scheduler.requests + assert not scheduler._park_pins and rig.ssd.pinned_block_count == 0 + assert "a" not in scheduler._decode_resumes + assert any( + "after its pending token was streamed" in r.getMessage() + for r in caplog.records + ) + park.step(rig, 2) # the batch keeps working without the row + finally: + rig.close() + + +class _StopOnDemand: + """A parser session that stops the request once ``armed`` is set.""" + + armed = False + + def process_token(self, token_id): + return OutputParserTokenResult( + stream_text=f"<{token_id}>", is_stop=_StopOnDemand.armed + ) + + def finalize(self): + return OutputParserFinalizeResult() + + +def test_a_parser_stop_on_the_pending_token_deletes_the_chain_it_stored( + tmp_path, monkeypatch +): + rig = dp.make_rig(tmp_path) + try: + scheduler = rig.scheduler + scheduler._output_parser_factory = OutputParserFactory( + kind="test-stop", create_session=lambda tokenizer: _StopOnDemand() + ) + monkeypatch.setattr(_StopOnDemand, "armed", False) + request = submit(rig, "a", PROMPT, 40, arrival=1.0) + dp.step_until_outputs(rig, request, 5, []) + store = {} + original = rig.prefix.store_exact_prefix + + def store_and_record(*args, **kwargs): + table = original(*args, **kwargs) + store["hashes"] = _ids_of(rig, table) + return table + + monkeypatch.setattr(rig.prefix, "store_exact_prefix", store_and_record) + _StopOnDemand.armed = True + assert scheduler.request_decode_pause("a") is True + outputs = park.step(rig) + + (final,) = [o for o in outputs if o.request_id == "a" and o.finished] + assert final.finish_reason == "stop" and not final.error + assert store["hashes"] + for block_hash in store["hashes"]: + assert not rig.ssd.has_block(block_hash) + assert not scheduler._park_pins and rig.ssd.pinned_block_count == 0 + assert request.park_count == 0 + finally: + rig.close() From 28733ee82b52bb3d56631c2e0ccc2ed2233c760c Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Mon, 5 Oct 2026 14:41:03 -0600 Subject: [PATCH 23/46] feat(scheduler): hand a Lightning MTP row off to standard decode before 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. --- omlx/patches/mlx_lm_mtp/batch_generator.py | 22 +++ omlx/scheduler.py | 78 +++++++--- tests/test_mlx_lm_mtp_pause_handoff.py | 146 +++++++++++++++++++ tests/test_scheduler_decode_pause.py | 7 +- tests/test_scheduler_decode_pause_victims.py | 111 ++++++++++++++ 5 files changed, 344 insertions(+), 20 deletions(-) create mode 100644 tests/test_mlx_lm_mtp_pause_handoff.py diff --git a/omlx/patches/mlx_lm_mtp/batch_generator.py b/omlx/patches/mlx_lm_mtp/batch_generator.py index 3d8abcc06e..2d1b53ec20 100644 --- a/omlx/patches/mlx_lm_mtp/batch_generator.py +++ b/omlx/patches/mlx_lm_mtp/batch_generator.py @@ -3699,6 +3699,28 @@ def _handoff_mtp_for_late_join(gen_batch: Any, state: _MtpState) -> bool: return True +def handoff_singleton_mtp_for_pause(gen_batch: Any) -> str: + """Return a singleton Lightning MTP row to the standard step for a pause. + + A decode pause stores the KV of every streamed token and resumes from the + pending ``_next_tokens``, which only the standard step defines. This is + the late-join handoff, taken at the same drained-queue boundary where it + is exact. Returns ``"standard"`` when no MTP state is active, + ``"deferred"`` while more than one committed token is still queued (the + queue drains by one per step), ``"handed_off"`` after the handoff, and + ``"failed"`` for a stale state or a handoff that could not feed the next + token. + """ + state = getattr(gen_batch, "_omlx_mtp_state", None) + if state is None: + return "standard" + if not _mtp_state_valid_for_batch(gen_batch, state): + return "failed" + if len(state.queue) > 1: + return "deferred" + return "handed_off" if _handoff_mtp_for_late_join(gen_batch, state) else "failed" + + def _mtp_next(gen_batch: Any, state: _MtpState) -> Any: """Emit one token; run a verify cycle if the queue is empty.""" if state.queue: diff --git a/omlx/scheduler.py b/omlx/scheduler.py index ea14ab636c..13382f0c3f 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -64,6 +64,9 @@ ) from .patches.mlx_lm_mtp import prompt_priming as _mtp_priming from .patches.mlx_lm_mtp.batch_generator import _drafter_for as _block_drafter_for +from .patches.mlx_lm_mtp.batch_generator import ( + handoff_singleton_mtp_for_pause as _mtp_pause_handoff, +) from .patches.mlx_lm_mtp.batch_generator import interrupt_batch_timing from .patches.vlm_batch_kv_capacity import apply_batch_kv_capacity_patch from .prefill.packed import ( @@ -1405,6 +1408,12 @@ class _DecodeResume: stop_matcher: Any = None +# Step starts a decode pause waits for a Lightning MTP queue to drain to one +# token (it drains by one per step, so this only bounds a stuck queue). +_DECODE_PAUSE_MAX_DEFERRED_STEPS = 32 +_PAUSE_DEFERRED = "deferred" + + class _DecodePauseDeclinedError(Exception): """A decode pause cannot proceed; the row keeps decoding (message: why).""" @@ -2363,6 +2372,8 @@ def __init__( # drained at step start) and the resume record of each paused row. self._pending_decode_pauses: set[str] = set() self._decode_resumes: dict[str, _DecodeResume] = {} + # Step starts each pending pause has waited for an MTP queue to drain. + self._decode_pause_deferrals: dict[str, int] = {} self._park_stats: dict[str, int] = { "parks": 0, "resumes": 0, @@ -12201,11 +12212,10 @@ def _decode_pause_exclusion_reason(self, request: Request) -> str | None: return "decoding row is not in the generation batch" if _block_drafter_for(self.model) is not None: return "DFlash drafter state is not handed off on a decode pause" - if ( - getattr(generation_batch, "_omlx_mtp_state", None) is not None - or getattr(generation_batch, "_omlx_mtp_batch_state", None) is not None - ): - return "MTP speculative decode is active (its queue is not handed off)" + # A singleton Lightning MTP row hands off to the standard step at the + # pause; the multi-row batch state has no such handoff (v1). + if getattr(generation_batch, "_omlx_mtp_batch_state", None) is not None: + return "batched Lightning MTP decode is active (no pause handoff)" prefix_cache = self.block_aware_cache if prefix_cache is None or self.paged_ssd_cache_manager is None: return "no paged SSD cache to hold the exact prefix" @@ -12341,19 +12351,23 @@ def _process_pending_park(self, output: SchedulerOutput | None = None) -> bool: def _process_pending_decode_pauses(self, output: SchedulerOutput | None) -> bool: acted = False - while self._pending_decode_pauses: - # The id stays pending until its pause has run, so the enforcer's - # drain probe never sees a pause in progress as finished. - rid = next(iter(list(self._pending_decode_pauses))) + # An id stays pending until its pause has run (or waits for an MTP + # queue), so the enforcer's drain probe never sees it as finished. + for rid in list(self._pending_decode_pauses): + outcome = None try: - acted = self._process_one_decode_pause(rid, output) or acted + outcome = self._process_one_decode_pause(rid, output) finally: - self._pending_decode_pauses.discard(rid) + if outcome != _PAUSE_DEFERRED: + self._pending_decode_pauses.discard(rid) + self._decode_pause_deferrals.pop(rid, None) + acted = acted or outcome == "paused" return acted def _process_one_decode_pause( self, rid: str, output: SchedulerOutput | None - ) -> bool: + ) -> str | None: + """Run one requested pause: "paused", ``_PAUSE_DEFERRED`` or None.""" request = self.requests.get(rid) if ( request is None @@ -12365,11 +12379,28 @@ def _process_one_decode_pause( reason = self._park_exclusion_reason(request) if reason is not None: logger.info("Decode pause skipped for %s: %s", rid, reason) - return False - if not self._pause_decoding_request(request, output): - return False + return None + outcome = self._pause_decoding_request(request, output) + if outcome == _PAUSE_DEFERRED: + waited = self._decode_pause_deferrals.get(rid, 0) + 1 + if waited <= _DECODE_PAUSE_MAX_DEFERRED_STEPS: + self._decode_pause_deferrals[rid] = waited + return _PAUSE_DEFERRED + self._decode_pause_failed( + request, + None, + _DecodePauseDeclinedError( + "the Lightning MTP queue did not drain within " + f"{_DECODE_PAUSE_MAX_DEFERRED_STEPS} steps" + ), + emitted=False, + out=output, + ) + return None + if outcome is not True: + return None self._polls_since_park = 0 - return True + return "paused" def select_decode_pause_victim(self) -> MemoryVictim | None: """Pick the decoding row whose pause frees the most memory. @@ -12435,9 +12466,13 @@ def decode_pause_status(self, request_id: str) -> str: def _pause_decoding_request( self, request: Request, output: SchedulerOutput | None - ) -> bool: + ) -> bool | str: """Pause one decoding row exactly; True when it was paused. + A singleton Lightning MTP row first hands off to the standard step + (``_PAUSE_DEFERRED`` while more than one committed token is queued), + which defines the pending token and keeps the KV exact. + After ``GenerationBatch.next()`` the row's KV holds every emitted token and ``_next_tokens[row]`` is sampled but not emitted. The pending token is emitted through the normal response path (a token @@ -12459,6 +12494,13 @@ def _pause_decoding_request( try: uid = self.request_id_to_uid[rid] generation_batch = self._generation_batch() + handoff = _mtp_pause_handoff(generation_batch) + if handoff == "deferred": + return _PAUSE_DEFERRED + if handoff == "failed": + raise _DecodePauseDeclinedError( + "the Lightning MTP row could not hand off to standard decode" + ) _safe_sync_stream(self._stream) row = generation_batch.uids.index(uid) with mx.stream(self._stream): @@ -13082,6 +13124,7 @@ def _do_abort_request(self, request_id: str) -> bool: self._clear_request_admission_bookkeeping(request_id) self._unpin_parked(request_id) self._pending_decode_pauses.discard(request_id) + self._decode_pause_deferrals.pop(request_id, None) self._decode_resumes.pop(request_id, None) # A deferred pin step must not re-pin an aborted request's blocks. request.parked = False @@ -16483,6 +16526,7 @@ def reset(self) -> None: self._unpin_parked(parked_id) self._pending_decode_pauses.clear() self._decode_resumes.clear() + self._decode_pause_deferrals.clear() self._park_requested = False self._polls_since_park = None self._park_resumed_this_pass = False diff --git a/tests/test_mlx_lm_mtp_pause_handoff.py b/tests/test_mlx_lm_mtp_pause_handoff.py new file mode 100644 index 0000000000..5b107d331e --- /dev/null +++ b/tests/test_mlx_lm_mtp_pause_handoff.py @@ -0,0 +1,146 @@ +# SPDX-License-Identifier: Apache-2.0 +"""A singleton Lightning MTP row hands off to the standard step for a pause. + +A decode pause stores the KV of every streamed token and resumes from the +pending ``_next_tokens``, which only the standard step defines. The handoff +waits until at most one committed token is still queued, then leaves the +batch in the standard invariant: the KV holds exactly prompt plus streamed +tokens, and ``_next_tokens`` is the next token an uninterrupted MTP run +streams. The tests drive the real patched mlx-lm ``BatchGenerator`` on the +MTP suite's ``CountingModel``, whose KV stores its input ids verbatim. +""" + +from collections import deque +from types import SimpleNamespace + +import mlx.core as mx +from mlx_lm.generate import BatchGenerator +from test_mlx_lm_mtp_patch import CountingModel + +from omlx.patches.mlx_lm_mtp import batch_generator as bg +from omlx.patches.mlx_lm_mtp import cache_rollback + +PROMPT = [1, 2] +LIMIT = 24 + + +def _generator(model): + bg.apply() + cache_rollback.apply() + return BatchGenerator( + model, + sampler=lambda lp: mx.argmax(lp, -1), + prefill_batch_size=1, + max_tokens=LIMIT, + ) + + +def _run(gen, out, limit=200): + for _ in range(limit): + _, responses = gen.next() + for response in responses: + out.append(response.token) + if response.finish_reason: + return response + raise AssertionError("generation did not finish") + + +def _uninterrupted(): + gen = _generator(CountingModel()) + try: + gen.insert([PROMPT], max_tokens=[LIMIT]) + out = [] + _run(gen, out) + return out + finally: + gen.close() + + +def test_a_pause_handoff_keeps_the_exact_cache_and_greedy_identity_with_mtp(): + expected = _uninterrupted() + model = CountingModel() + gen = _generator(model) + (uid,) = gen.insert([PROMPT], max_tokens=[LIMIT]) + out, results, mtp_steps, requested = [], [], 0, False + try: + for _ in range(200): + batch = gen._generation_batch + state = getattr(batch, "_omlx_mtp_state", None) + if state is not None: + mtp_steps += 1 + # Ask for the pause at a step start with a deep queue. + requested = requested or ( + len(out) >= 4 and state is not None and len(state.queue) > 1 + ) + if requested: + queued = len(state.queue) + result = bg.handoff_singleton_mtp_for_pause(batch) + results.append((queued, result)) + if result == "handed_off": + break + assert result == "deferred" and queued > 1 + _, responses = gen.next() + out.extend(r.token for r in responses) + # Deferred while more than one committed token was queued. + assert results[0] == (2, "deferred") + assert results[-1][1] == "handed_off" and results[-1][0] <= 1 + assert mtp_steps > 0 # MTP really ran before the pause + assert not hasattr(batch, "_omlx_mtp_state") + + # The standard invariant the pause relies on. + pending = int(batch._next_tokens[0].item()) + cache, tokens = gen.extract_cache([uid])[uid] + offset = cache[0].offset + assert offset == len(tokens) == len(PROMPT) + len(out) + assert tokens == PROMPT + out + assert cache[0].keys[0, 0, :offset, 0].tolist() == tokens + out.append(pending) + finally: + gen.close() + + # Resume from the stored state on a fresh generator (MTP on again). + resumed = _generator(CountingModel()) + try: + resumed.insert( + [[pending]], + max_tokens=[LIMIT - len(out)], + caches=[cache], + all_tokens=[tokens], + ) + final = _run(resumed, out) + finally: + resumed.close() + assert final.finish_reason == "length" + assert out == expected + + +def test_a_deep_queue_defers_the_handoff_and_a_drained_one_hands_off(monkeypatch): + lp = mx.zeros((8,)) + calls = [] + monkeypatch.setattr( + bg, + "_handoff_mtp_for_late_join", + lambda batch, state: calls.append(len(state.queue)) or True, + ) + state = bg._MtpState(uid=7, queue=deque([(1, lp, "draft"), (2, lp, "bonus")])) + batch = SimpleNamespace(uids=[7], _omlx_mtp_state=state) + + assert bg.handoff_singleton_mtp_for_pause(batch) == "deferred" + assert calls == [] + state.queue.popleft() + assert bg.handoff_singleton_mtp_for_pause(batch) == "handed_off" + assert calls == [1] + + +def test_no_mtp_state_is_already_standard_and_a_stale_state_fails(): + assert bg.handoff_singleton_mtp_for_pause(SimpleNamespace(uids=[3])) == "standard" + stale = bg._MtpState(uid=9, queue=deque()) + batch = SimpleNamespace(uids=[3], _omlx_mtp_state=stale) + assert bg.handoff_singleton_mtp_for_pause(batch) == "failed" + + +def test_a_handoff_that_cannot_feed_the_next_token_fails(monkeypatch): + monkeypatch.setattr(bg, "_handoff_mtp_for_late_join", lambda batch, state: False) + state = bg._MtpState(uid=7, queue=deque()) + batch = SimpleNamespace(uids=[7], _omlx_mtp_state=state) + assert bg.handoff_singleton_mtp_for_pause(batch) == "failed" diff --git a/tests/test_scheduler_decode_pause.py b/tests/test_scheduler_decode_pause.py index b7c4aeaaae..d0410f11ad 100644 --- a/tests/test_scheduler_decode_pause.py +++ b/tests/test_scheduler_decode_pause.py @@ -206,7 +206,7 @@ def test_a_decoding_row_is_pausable_when_nothing_excludes_it(tmp_path): [ ("specprefill", "SpecPrefill"), ("dflash", "DFlash"), - ("mtp", "MTP"), + ("mtp", "batched Lightning MTP"), ("vlm_mtp", "VLM-MTP"), ("no_ssd", "no paged SSD cache"), ("budget", "park budget spent"), @@ -226,7 +226,8 @@ def test_v1_exclusions_name_why_a_decoding_row_cannot_pause( scheduler_module, "_block_drafter_for", lambda model: object() ) elif case == "mtp": - scheduler.batch_generator._generation_batch._omlx_mtp_state = object() + batch = scheduler.batch_generator._generation_batch + batch._omlx_mtp_batch_state = object() elif case == "vlm_mtp": uid = scheduler.request_id_to_uid["a"] scheduler.request_id_to_uid["a"] = -7 @@ -238,7 +239,7 @@ def test_v1_exclusions_name_why_a_decoding_row_cannot_pause( assert reason is not None and expected in reason assert scheduler.request_decode_pause("a") is False if case == "mtp": - del scheduler.batch_generator._generation_batch._omlx_mtp_state + del scheduler.batch_generator._generation_batch._omlx_mtp_batch_state if case == "vlm_mtp": scheduler.request_id_to_uid["a"] = uid finally: diff --git a/tests/test_scheduler_decode_pause_victims.py b/tests/test_scheduler_decode_pause_victims.py index 5e0d67637e..11ac6800cb 100644 --- a/tests/test_scheduler_decode_pause_victims.py +++ b/tests/test_scheduler_decode_pause_victims.py @@ -15,6 +15,7 @@ import test_scheduler_decode_pause as dp import test_scheduler_park as park +import omlx.scheduler as scheduler_module from omlx.adapter.output_parser import ( OutputParserFactory, OutputParserFinalizeResult, @@ -367,3 +368,113 @@ def store_and_record(*args, **kwargs): assert request.park_count == 0 finally: rig.close() + + +# --- Lightning MTP handoff ----------------------------------------------------------- + + +def test_a_singleton_mtp_row_is_pausable(tmp_path): + rig = dp.make_rig(tmp_path) + try: + (a,) = [submit(rig, "a", PROMPT, 80, arrival=1.0)] + step_until_decoding(rig, [a]) + batch = rig.scheduler.batch_generator._generation_batch + batch._omlx_mtp_state = object() + try: + assert rig.scheduler._park_exclusion_reason(a) is None + finally: + del batch._omlx_mtp_state + finally: + rig.close() + + +def _scripted_handoff(monkeypatch, script): + """Replace the MTP handoff with scripted answers; record each call.""" + calls = [] + + def handoff(batch): + calls.append(batch) + return script[min(len(calls), len(script)) - 1] + + monkeypatch.setattr(scheduler_module, "_mtp_pause_handoff", handoff) + return calls + + +def test_the_pause_waits_for_the_mtp_queue_then_resumes_identically( + tmp_path, monkeypatch +): + base_outputs, (base_row,) = dp.baseline_outputs(tmp_path, 60) + rig = dp.make_rig(tmp_path / "paused") + try: + scheduler = rig.scheduler + calls = _scripted_handoff(monkeypatch, ["deferred", "deferred", "handed_off"]) + request = submit(rig, "a", PROMPT, 60, arrival=1.0) + outputs = [] + dp.step_until_outputs(rig, request, 5, outputs) + + assert scheduler.request_decode_pause("a") is True + for _ in range(2): # queue still deep: the row keeps decoding + before = len(request.output_token_ids) + outputs.extend(park.step(rig)) + assert "a" in scheduler.running and not request.parked + assert len(request.output_token_ids) == before + 1 + assert scheduler.decode_pause_status("a") == "pending" + outputs.extend(park.step(rig)) # drained: handed off, then paused + assert len(calls) == 3 + # Paused (and, with nothing else admitted, resumed in the same step). + assert request.park_count == 1 + assert scheduler.get_park_stats()["decode_pauses"] == 1 + + park.finish_ok_polls(rig, 3) + outputs.extend(park.run_to_completion(rig, [request], limit=400)) + dp.assert_identical_stream(base_outputs, base_row, outputs, request) + finally: + rig.close() + + +def test_a_failed_mtp_handoff_declines_and_keeps_decoding( + tmp_path, monkeypatch, caplog +): + (expected,) = dp.baseline(tmp_path, 40) + rig = dp.make_rig(tmp_path / "paused") + try: + scheduler = rig.scheduler + _scripted_handoff(monkeypatch, ["failed"]) + request = submit(rig, "a", PROMPT, 40, arrival=1.0) + outputs = [] + dp.step_until_outputs(rig, request, 5, outputs) + assert scheduler.request_decode_pause("a") is True + with caplog.at_level(logging.WARNING, logger="omlx.scheduler"): + outputs.extend(park.step(rig)) + assert "could not hand off to standard decode" in caplog.text + assert scheduler.decode_pause_status("a") == "declined" + assert not request.parked and rig.ssd.pinned_block_count == 0 + outputs.extend(park.run_to_completion(rig, [request])) + assert list(request.output_token_ids) == expected + assert dp.streamed_tokens(outputs, "a") == expected + finally: + rig.close() + + +def test_an_mtp_queue_that_never_drains_declines_after_a_bounded_wait( + tmp_path, monkeypatch, caplog +): + rig = dp.make_rig(tmp_path) + try: + scheduler = rig.scheduler + calls = _scripted_handoff(monkeypatch, ["deferred"]) + request = submit(rig, "a", PROMPT, 200, arrival=1.0) + dp.step_until_outputs(rig, request, 3, []) + assert scheduler.request_decode_pause("a") is True + bound = scheduler_module._DECODE_PAUSE_MAX_DEFERRED_STEPS + with caplog.at_level(logging.WARNING, logger="omlx.scheduler"): + park.step(rig, bound) + assert scheduler.decode_pause_status("a") == "pending" + park.step(rig) + assert len(calls) == bound + 1 + assert scheduler.decode_pause_status("a") == "declined" + assert "queue did not drain" in caplog.text + assert "a" in scheduler.running and not request.parked + assert not scheduler._pending_decode_pauses + finally: + rig.close() From cbf7f2259222e525fa901a69adbd238667f77082 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Mon, 5 Oct 2026 15:04:13 -0600 Subject: [PATCH 24/46] feat(scheduler): resume a parked request when its memory need fits A parked head (prefill-parked or decode-paused) now resumes once the estimated free memory under the admission line covers its need plus a 2% margin, instead of after a fixed streak of ok pressure polls. - Need: a paused decode is priced at the KV of its final length (saved context, kickoff, remaining max_tokens) plus one decode transient; a parked prefill at the KV of prompt plus max_tokens plus the prefill transient of what is left to compute. - Free: admission line minus current usage minus the KV that running prefills still have to allocate. - The head never resumes on hard pressure; the stale-monitor and nothing-admitted escapes stay. The head-of-line hold is the reservation: nothing newer is admitted while the head waits, FIFO among parked. - Without an estimate the ok-poll rule and the max-hold escape remain. - Logs the wait (rate-limited) and the fit that released the head. --- docs/TESTING.md | 2 +- omlx/request.py | 2 + omlx/scheduler.py | 176 +++++++++- omlx/settings.py | 4 +- tests/test_scheduler_park_resume_priority.py | 348 +++++++++++++++++++ 5 files changed, 520 insertions(+), 12 deletions(-) create mode 100644 tests/test_scheduler_park_resume_priority.py diff --git a/docs/TESTING.md b/docs/TESTING.md index d19215d021..ffb453a87e 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -237,7 +237,7 @@ Mocked tests do not replace hardware validation: with a real model, abort a long # Memory-pressure park tests -Run `python -m pytest -q tests/test_scheduler_park.py tests/test_process_memory_enforcer.py tests/test_settings.py -k "park or Park"` to check `scheduler.memory_pressure_park` (also `OMLX_MEMORY_PRESSURE_PARK`; off by default), `scheduler.max_parks_per_request` (`OMLX_MAX_PARKS_PER_REQUEST`, default 3) and `scheduler.park_resume_ok_polls` (`OMLX_PARK_RESUME_OK_POLLS`, default 3). With the setting on, hard (non-emergency) memory pressure parks the most recent chunked-prefill request instead of aborting: it is re-queued without an error, keeps its stream, and resumes in arrival order after enough consecutive ok pressure polls, restoring the blocks that `prefill_progress_commit_blocks` committed (without it the park resumes cold). The oldest admitted request is protected, parked blocks are pinned against eviction until the resume, and the legacy abort remains for emergency pressure, nothing parkable, an exhausted park budget, or external-loop (non-chunked, VLM) and SpecPrefill prefills, which cannot be parked between steps. The scheduler cases run on a small Qwen3.5 hybrid model and compare a resumed request's output with an uninterrupted run; its prompts must stay below the tiny vocabulary of 32 ids, or the embedding read is undefined and the output is nondeterministic. +Run `python -m pytest -q tests/test_scheduler_park.py tests/test_scheduler_park_resume_priority.py tests/test_process_memory_enforcer.py tests/test_settings.py -k "park or Park"` to check `scheduler.memory_pressure_park` (also `OMLX_MEMORY_PRESSURE_PARK`; off by default), `scheduler.max_parks_per_request` (`OMLX_MAX_PARKS_PER_REQUEST`, default 3) and `scheduler.park_resume_ok_polls` (`OMLX_PARK_RESUME_OK_POLLS`, default 3). With the setting on, hard (non-emergency) memory pressure parks the most recent chunked-prefill request instead of aborting: it is re-queued without an error, keeps its stream, and resumes in arrival order once the estimated free memory under the admission line covers its need plus a 2% margin (a paused decode: the KV of its final length plus one decode step; a parked prefill: the KV of prompt plus max_tokens plus the prefill transient; KV that running prefills still have to allocate does not count as free), restoring the blocks that `prefill_progress_commit_blocks` committed (without it the park resumes cold). The oldest admitted request is protected, parked blocks are pinned against eviction until the resume, and the legacy abort remains for emergency pressure, nothing parkable, an exhausted park budget, or external-loop (non-chunked, VLM) and SpecPrefill prefills, which cannot be parked between steps. While the parked head waits, nothing newer is admitted, so a smaller request cannot take the headroom the head waits for; once the head fits, newer requests are admitted behind it. The head never resumes on hard pressure, and the nothing-admitted and stale-monitor escapes still release it. When no estimate is available (no admission line or no model dimensions), the older rule applies: enough consecutive ok pressure polls, or the max-hold escape. The scheduler cases run on a small Qwen3.5 hybrid model and compare a resumed request's output with an uninterrupted run; its prompts must stay below the tiny vocabulary of 32 ids, or the embedding read is undefined and the output is nondeterministic. Run `python -m pytest -q tests/test_memory_single_victim.py tests/test_process_memory_enforcer.py -k "single or victim"` to check `memory.abort_single_victim` (env `OMLX_MEMORY_ABORT_SINGLE_VICTIM`, default off). On the non-emergency hard path with nothing parkable, the enforcer aborts only the live request holding the most KV (newest arrival on ties), waits for its memory to drain before choosing another, and keeps the rest running. Emergency pressure and model unload still abort everything. Off keeps the abort-all. diff --git a/omlx/request.py b/omlx/request.py index 7257919839..a031da599d 100644 --- a/omlx/request.py +++ b/omlx/request.py @@ -263,6 +263,8 @@ def vlm_extra_key_ranges_for_cache( parked: bool = False parked_at: float = 0.0 # time.monotonic() of the latest park park_count: int = 0 # Parks taken so far (bounded by max_parks_per_request) + # Prompt tokens a prefill park left committed in the prefix cache. + park_committed_tokens: int = 0 # Request-scoped tool schemas used by protocol output parsers. tools: list[dict[str, Any]] | None = None diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 13382f0c3f..dfe9efc5b6 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -1370,8 +1370,14 @@ def _is_turboquant_kv_family_cache(cache_obj: Any) -> bool: # A pressure monitor that has not reported for this long is considered gone; # parked requests then resume instead of waiting for polls that never come. PARK_SIGNAL_STALE_S = 60.0 -# Longest a parked head holds admission on a non-hard pressure level. +# Longest a parked head holds admission on a non-hard pressure level when no +# memory estimate is available (with one, the head waits for its fit). PARK_MAX_HOLD_S = 300.0 +# Free memory a parked request must find beyond its own estimated need before +# it resumes, as a fraction of the admission line (estimate error margin). +PARK_RESUME_MARGIN_FRACTION = 0.02 +# Seconds between "waiting" log lines for the same parked head. +_PARK_WAIT_LOG_INTERVAL_S = 30.0 # Saturation value of ``_polls_since_resume``: "long enough since the last # resume that the hysteresis gate is open". It is the initial value (no resume # has happened yet) and the cap that keeps the counter from growing without @@ -2367,6 +2373,10 @@ def __init__( self._polls_since_resume: int = _POLLS_SINCE_RESUME_SATURATION self._last_pressure_poll_at: float | None = None self._last_pressure_level: str = "ok" + # Memory-aware resume: the fit that released the head (request id, + # need, free) for the resume log, and the last "waiting" log line. + self._park_resume_fit: tuple[str, int, int] | None = None + self._park_wait_logged: tuple[str, float] | None = None self._park_pins: dict[str, _ParkPins] = {} # Decode pause: ids asked for by request_decode_pause (thread-safe set, # drained at step start) and the resume record of each paused row. @@ -12084,26 +12094,52 @@ def note_pressure_poll(self, level: str) -> None: else: self._ok_polls = 0 - def _park_resume_allowed(self) -> bool: - """True once enough consecutive ok polls were seen (or no monitor runs).""" + def _park_signal_stale(self) -> bool: + """No live pressure monitor (never polled, or silent for too long).""" seen = self._last_pressure_poll_at - if seen is None or time.monotonic() - seen > PARK_SIGNAL_STALE_S: - return True # no live pressure monitor: never starve a parked request + return seen is None or time.monotonic() - seen > PARK_SIGNAL_STALE_S + + def _park_ok_polls_met(self) -> bool: need = getattr(self.config, "park_resume_ok_polls", 3) return self._ok_polls >= max(1, need) + def _park_resume_allowed(self, head: "Request | None" = None) -> bool: + """Whether a parked request may resume now. + + With no live pressure monitor, always (never starve a parked + request). Otherwise, when ``head`` has a memory estimate, once the + free memory covers its need plus a margin; without an estimate, once + enough consecutive ok polls were seen. + """ + if self._park_signal_stale(): + return True + if head is not None: + fit = self._park_memory_fit(head) + if fit is not None: + return fit + return self._park_ok_polls_met() + def _park_hold_applies(self, head: "Request") -> bool: """Whether a parked head still blocks admission. - Never when nothing is admitted (admission must be able to recover), - and not past PARK_MAX_HOLD_S unless the last pressure was hard. Every - escape resumes one request per scheduling pass, and the max-hold + The hold is the head's reservation: nothing newer is admitted while + it waits, so nothing consumes the headroom it waits for. It never + applies when nothing is admitted (admission must be able to recover) + or without a live pressure monitor. With a memory estimate the head + resumes when it fits. Without one it resumes after an ok-poll streak, + or past PARK_MAX_HOLD_S unless the last pressure was hard; that escape also waits ``park_resume_ok_polls`` polls after the previous - resume, so a burst of resumes cannot re-trigger hard pressure. + resume. Every escape resumes one request per scheduling pass, so a + burst of resumes cannot re-trigger hard pressure. """ if self._park_resumed_this_pass: return True - if self._park_resume_allowed() or not self._num_admitted_requests(): + if not self._num_admitted_requests() or self._park_signal_stale(): + return False + fit = self._park_memory_fit(head) + if fit is not None: + return not fit + if self._park_ok_polls_met(): return False need = max(1, getattr(self.config, "park_resume_ok_polls", 3)) held_s = time.monotonic() - head.parked_at @@ -12111,6 +12147,114 @@ def _park_hold_applies(self, head: "Request") -> bool: return self._polls_since_resume < need return True + def _park_memory_fit(self, head: "Request") -> bool | None: + """Whether the free memory covers ``head``'s need plus the margin. + + None when either side cannot be estimated (the caller falls back to + the ok-poll rule). A head never resumes on hard pressure, whatever + the estimate says. Logs the wait (rate-limited) and records the fit + for the resume log. + """ + need = self._parked_resume_need_bytes(head) + free = self._park_free_bytes() + if need is None or free is None: + return None + margin = int(self._admission_limit_bytes() * PARK_RESUME_MARGIN_FRACTION) + if self._last_pressure_level == "hard" or free < need + margin: + self._log_park_wait(head.request_id, need, free) + return False + self._park_resume_fit = (head.request_id, need, free) + return True + + def _log_park_wait(self, request_id: str, need: int, free: int) -> None: + now = time.monotonic() + last = self._park_wait_logged + if ( + last is not None + and last[0] == request_id + and now - last[1] < _PARK_WAIT_LOG_INTERVAL_S + ): + return + self._park_wait_logged = (request_id, now) + logger.info( + "Parked request %s waiting: need %.1f GB, free %.1f GB", + request_id, + need / 1024**3, + free / 1024**3, + ) + + def _parked_resume_need_bytes(self, request: "Request") -> int | None: + """Live bytes a parked request needs to resume and run to its end. + + A paused decoding row: the KV of its final length (saved context, + the kickoff and every remaining token) plus one decode step's + transient. A parked prefill: the KV of prompt plus max_tokens (the + committed prefix comes back from SSD into memory, so it counts too) + plus the prefill transient of what is left to compute. None when + nothing can be estimated. + """ + monitor = self.memory_monitor + if monitor is None: + return None + record = self._decode_resumes.get(request.request_id) + if record is not None: + final = len(record.tokens) + 1 + max(0, record.remaining_max_tokens) + kv = monitor.estimate_resident_kv_bytes(final) + transient = monitor.estimate_chunk_transient_bytes(1, final) + else: + prompt = int(request.num_prompt_tokens or 0) + max_tokens = int(getattr(request.sampling_params, "max_tokens", 0) or 0) + final = prompt + max(0, max_tokens) + kv = monitor.estimate_resident_kv_bytes(final) + est = self._admission_estimate( + num_prompt_tokens=prompt, + cached_tokens=min(int(request.park_committed_tokens or 0), prompt), + current=0, + ) + transient = ( + est.transient + if est is not None + else monitor.estimate_chunk_transient_bytes(1, final) + ) + need = int(kv + transient) + return need if need > 0 else None + + def _park_free_bytes(self) -> int | None: + """Free bytes under the admission line, net of in-flight prefills. + + None without an admission line (no limit was propagated). + """ + limit = self._admission_limit_bytes() + if limit <= 0: + return None + return ( + limit - self._current_usage_bytes() - self._inflight_prefill_reserve_bytes() + ) + + def _inflight_prefill_reserve_bytes(self) -> int: + """KV the running prefills still have to allocate. + + A prefill that resumed (or was admitted) a pass ago has allocated + only its first chunks; the next parked head must not count the rest + as free memory. + """ + monitor = self.memory_monitor + if monitor is None: + return 0 + total = 0 + for request in list(self.prefilling): + state = self._prefill_states.get(request.request_id) + if state is None: + continue + prompt = int(request.num_prompt_tokens or 0) + done = int(state.base_size) + int(state.tokens_processed) + if prompt > done: + remaining = monitor.estimate_resident_kv_bytes( + prompt + ) - monitor.estimate_resident_kv_bytes(done) + total += max(0, int(remaining)) + return total + def select_memory_victim(self, *, spare_parked: bool = True) -> MemoryVictim | None: """Pick the one live request whose abort frees the most memory. @@ -12875,6 +13019,7 @@ def _park_prefill(self, request: Request, reason: str) -> None: request.parked = True request.parked_at = time.monotonic() request.park_count += 1 + request.park_committed_tokens = committed self._clear_request_admission_bookkeeping(rid) get_prefill_tracker().remove(rid) # Order matters: pin first, then release the table's own refs. @@ -13004,6 +13149,15 @@ def _finish_park_resume( if preserved_tokens is None: preserved_tokens = request.cached_tokens or 0 self._park_stats["tokens_preserved"] += preserved_tokens + fit = self._park_resume_fit + self._park_resume_fit = None + if fit is not None and fit[0] == request.request_id: + logger.info( + "Resuming parked request %s: need %.1f GB fits in free %.1f GB", + request.request_id, + fit[1] / 1024**3, + fit[2] / 1024**3, + ) if log: logger.info( "Resumed parked request %s: cached=%d", @@ -16530,6 +16684,8 @@ def reset(self) -> None: self._park_requested = False self._polls_since_park = None self._park_resumed_this_pass = False + self._park_resume_fit = None + self._park_wait_logged = None self._prefill_commits.clear() self._cache_freshness_waits.clear() self._prefix_cache_prepared.clear() diff --git a/omlx/settings.py b/omlx/settings.py index 0441bc7a84..4eb8b044a5 100644 --- a/omlx/settings.py +++ b/omlx/settings.py @@ -362,7 +362,9 @@ class SchedulerSettings: memory_pressure_park: bool = False # Parks a single request may take before it falls back to the abort. max_parks_per_request: int = 3 - # Consecutive "ok" pressure polls before parked requests may resume. + # Consecutive "ok" pressure polls before parked requests may resume when + # no memory estimate is available (with one, a parked request resumes + # once the estimated free memory covers its need). park_resume_ok_polls: int = 3 def to_dict(self) -> dict[str, Any]: diff --git a/tests/test_scheduler_park_resume_priority.py b/tests/test_scheduler_park_resume_priority.py new file mode 100644 index 0000000000..22622ba461 --- /dev/null +++ b/tests/test_scheduler_park_resume_priority.py @@ -0,0 +1,348 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Memory-aware resume of parked requests (prefill-parked and decode-paused). + +A parked head resumes once the estimated free memory covers its need plus a +margin, instead of after a fixed streak of ok pressure polls. While it waits, +the head-of-line hold keeps newer requests out, so nothing consumes the +headroom it is waiting for. The ok-poll rule stays as the fallback when no +estimate is available. +""" + +import logging +import time +from types import SimpleNamespace + +import pytest +from test_scheduler_park import ( + PROMPT_A, + PROMPT_B, + PROMPT_C, + make_rig, + prefill_two, + prefilling_ids, + step, + step_until, + submit, + waiting_ids, +) +from test_scheduler_prefill_memory_guard import _make_scheduler + +import omlx.scheduler as scheduler_module +from omlx.request import Request, SamplingParams +from omlx.scheduler import _DecodeResume + +GB = 1024**3 + + +def _parked_request(rid="parked", prompt_tokens=4000, max_tokens=1000, committed=0): + request = Request( + request_id=rid, + prompt=list(range(prompt_tokens)), + sampling_params=SamplingParams(max_tokens=max_tokens), + arrival_time=1.0, + ) + request.prompt_token_ids = list(range(prompt_tokens)) + request.num_prompt_tokens = prompt_tokens + request.parked = True + request.parked_at = time.monotonic() + request.park_committed_tokens = committed + return request + + +def _decode_record(context_tokens, remaining): + return _DecodeResume( + storage_id="paused", + domain_key=("paused", "1"), + tokens=list(range(context_tokens)), + kickoff=7, + remaining_max_tokens=remaining, + sampler=None, + logits_processors=[], + stop_sequences=None, + ) + + +@pytest.fixture +def live(monkeypatch): + """A scheduler with a live pressure monitor, one admitted row and a + 100 GB admission line; ``usage[0]`` is the current usage it reads.""" + scheduler = _make_scheduler() + scheduler._memory_hard_limit_bytes = 100 * GB + scheduler.note_pressure_poll("soft") + usage = [0] + monkeypatch.setattr(scheduler, "_current_usage_bytes", lambda **_kw: usage[0]) + monkeypatch.setattr(scheduler, "_num_admitted_requests", lambda: 1) + return scheduler, usage + + +def _margin(scheduler): + return int( + scheduler._admission_limit_bytes() + * scheduler_module.PARK_RESUME_MARGIN_FRACTION + ) + + +# --- Need ---------------------------------------------------------------- + + +def test_decode_paused_need_is_final_kv_plus_one_decode_transient(): + scheduler = _make_scheduler() + request = _parked_request("paused") + scheduler._decode_resumes["paused"] = _decode_record(999, remaining=500) + monitor = scheduler.memory_monitor + final = 999 + 1 + 500 # saved context, the kickoff, the remaining tokens + expected = monitor.estimate_resident_kv_bytes( + final + ) + monitor.estimate_chunk_transient_bytes(1, final) + assert expected > 0 + assert scheduler._parked_resume_need_bytes(request) == int(expected) + + +def test_prefill_parked_need_is_full_kv_with_max_tokens_plus_prefill_transient(): + """The committed prefix comes back from SSD into memory, so it counts.""" + scheduler = _make_scheduler() + request = _parked_request(prompt_tokens=4000, max_tokens=1000, committed=2048) + monitor = scheduler.memory_monitor + est = scheduler._admission_estimate( + num_prompt_tokens=4000, cached_tokens=2048, current=0 + ) + expected = monitor.estimate_resident_kv_bytes(4000 + 1000) + est.transient + assert scheduler._parked_resume_need_bytes(request) == int(expected) + + +def test_need_is_unavailable_without_a_monitor(): + scheduler = _make_scheduler() + scheduler.memory_monitor = None + assert scheduler._parked_resume_need_bytes(_parked_request()) is None + + +# --- Resume decision ------------------------------------------------------- + + +def test_parked_head_resumes_once_free_memory_covers_need_plus_margin(live): + scheduler, usage = live + head = _parked_request() + need = scheduler._parked_resume_need_bytes(head) + limit = scheduler._admission_limit_bytes() + + usage[0] = limit - need - _margin(scheduler) + 1 # one byte short + assert scheduler._park_hold_applies(head) is True + + usage[0] = limit - need - _margin(scheduler) + assert scheduler._park_hold_applies(head) is False + + +def test_decode_paused_head_resumes_on_its_own_need(live): + scheduler, usage = live + head = _parked_request("paused") + scheduler._decode_resumes["paused"] = _decode_record(20_000, remaining=4000) + need = scheduler._parked_resume_need_bytes(head) + limit = scheduler._admission_limit_bytes() + usage[0] = limit - need - _margin(scheduler) + 1 + assert scheduler._park_hold_applies(head) is True + usage[0] -= 1 + assert scheduler._park_hold_applies(head) is False + + +def test_ok_polls_alone_do_not_resume_a_head_that_does_not_fit(live): + scheduler, usage = live + head = _parked_request() + usage[0] = scheduler._admission_limit_bytes() # no free memory at all + for _ in range(10): + scheduler.note_pressure_poll("ok") + assert scheduler._park_hold_applies(head) is True + + +def test_hard_pressure_holds_a_head_the_estimate_says_fits(live): + scheduler, usage = live + head = _parked_request() + usage[0] = 0 + scheduler.note_pressure_poll("hard") + assert scheduler._park_hold_applies(head) is True + + +def test_max_hold_does_not_release_a_head_that_does_not_fit(live): + """Without an estimate the max-hold escape bounds the wait; with one, the + running rows finish and the nothing-admitted escape releases the head.""" + scheduler, usage = live + head = _parked_request() + usage[0] = scheduler._admission_limit_bytes() + head.parked_at -= scheduler_module.PARK_MAX_HOLD_S + 1 + assert scheduler._park_hold_applies(head) is True + + +def test_nothing_admitted_and_stale_monitor_escapes_still_release(live, monkeypatch): + scheduler, usage = live + head = _parked_request() + usage[0] = scheduler._admission_limit_bytes() + assert scheduler._park_hold_applies(head) is True + + monkeypatch.setattr(scheduler, "_num_admitted_requests", lambda: 0) + assert scheduler._park_hold_applies(head) is False + + monkeypatch.setattr(scheduler, "_num_admitted_requests", lambda: 1) + scheduler._last_pressure_poll_at = ( + time.monotonic() - scheduler_module.PARK_SIGNAL_STALE_S - 1 + ) + assert scheduler._park_hold_applies(head) is False + + +def test_ok_poll_rule_is_the_fallback_without_an_estimate(live): + scheduler, usage = live + scheduler._memory_hard_limit_bytes = 0 # no admission line: no estimate + head = _parked_request() + assert scheduler._park_hold_applies(head) is True + for _ in range(scheduler.config.park_resume_ok_polls): + scheduler.note_pressure_poll("ok") + assert scheduler._park_hold_applies(head) is False + + +def test_in_flight_prefill_growth_is_reserved_against_the_head(live): + """A prefill that already resumed still has KV to allocate: the next + parked head must not count that memory as free.""" + scheduler, usage = live + head = _parked_request("head") + need = scheduler._parked_resume_need_bytes(head) + limit = scheduler._admission_limit_bytes() + usage[0] = limit - need - _margin(scheduler) + assert scheduler._park_hold_applies(head) is False + + growing = _parked_request("growing", prompt_tokens=30_000) + growing.parked = False + scheduler.prefilling.append(growing) + scheduler._prefill_states["growing"] = SimpleNamespace( + base_size=2000, tokens_processed=8000 + ) + monitor = scheduler.memory_monitor + reserve = monitor.estimate_resident_kv_bytes( + 30_000 + ) - monitor.estimate_resident_kv_bytes(10_000) + assert scheduler._inflight_prefill_reserve_bytes() == int(reserve) + assert scheduler._park_hold_applies(head) is True + + +def test_wait_and_resume_are_logged_with_need_and_free(live, caplog): + scheduler, usage = live + head = _parked_request("big") + need = scheduler._parked_resume_need_bytes(head) + limit = scheduler._admission_limit_bytes() + usage[0] = limit - need // 2 + with caplog.at_level(logging.INFO, logger="omlx.scheduler"): + scheduler._park_hold_applies(head) + scheduler._park_hold_applies(head) # rate-limited: one line + waits = [r for r in caplog.records if "waiting: need" in r.getMessage()] + assert len(waits) == 1 + assert "Parked request big waiting: need" in waits[0].getMessage() + assert "GB, free" in waits[0].getMessage() + + usage[0] = 0 + assert scheduler._park_hold_applies(head) is False + scheduler._finish_park_resume(head, log=False) + resumes = [ + r.getMessage() for r in caplog.records if "Resuming parked" in r.getMessage() + ] + assert len(resumes) == 1 + assert resumes[0].startswith("Resuming parked request big: need ") + assert " GB fits in free " in resumes[0] + + +# --- Reservation on the real scheduler loop --------------------------------- + + +def _reserved_rig(tmp_path, tokenizer, monkeypatch, *, free_gb, head_need_gb): + rig = make_rig(tmp_path, tokenizer) + scheduler = rig.scheduler + prefill_two(rig) + scheduler.request_park_prefill() + step(rig) + assert waiting_ids(rig) == ["young"] + # A 100 GB machine whose usage leaves ``free_gb`` under the admission + # line; the guard prices newer requests against the same usage. + scheduler._memory_hard_limit_bytes = 100 * GB + scheduler._prefill_memory_guard = True + limit = scheduler._admission_limit_bytes() + monkeypatch.setattr( + scheduler, "_current_usage_bytes", lambda **_kw: limit - free_gb * GB + ) + real_need = scheduler._parked_resume_need_bytes + monkeypatch.setattr( + scheduler, + "_parked_resume_need_bytes", + lambda r: head_need_gb * GB if r.request_id == "young" else real_need(r), + ) + return rig + + +def test_a_smaller_newer_request_does_not_take_a_waiting_heads_headroom( + tmp_path, mock_tokenizer, monkeypatch +): + rig = _reserved_rig( + tmp_path, mock_tokenizer, monkeypatch, free_gb=30, head_need_gb=40 + ) + try: + scheduler = rig.scheduler + newer = submit(rig, "newer", PROMPT_C, arrival=9.0) + # On its own the newer request fits the free memory comfortably. + est = scheduler._admission_estimate( + num_prompt_tokens=newer.num_prompt_tokens, + cached_tokens=0, + current=scheduler._current_usage_bytes(), + ) + assert est is not None + assert est.estimated <= scheduler._admission_limit_bytes() + step(rig, 4) + assert waiting_ids(rig) == ["young", "newer"] + assert "newer" not in prefilling_ids(rig) + assert not newer.output_token_ids + finally: + rig.close() + + +def test_a_newer_request_backfills_once_there_is_room_for_both( + tmp_path, mock_tokenizer, monkeypatch +): + rig = _reserved_rig( + tmp_path, mock_tokenizer, monkeypatch, free_gb=60, head_need_gb=40 + ) + try: + young = rig.scheduler.requests["young"] + newer = submit(rig, "newer", PROMPT_C, arrival=9.0) + step_until( + rig, + lambda: (not young.parked) + and ("newer" in prefilling_ids(rig) or newer.output_token_ids), + ) + assert "newer" not in waiting_ids(rig) + finally: + rig.close() + + +def test_parked_requests_stay_fifo_under_the_memory_rule( + tmp_path, mock_tokenizer, monkeypatch +): + """Only the head is priced: a smaller parked request behind it waits.""" + rig = make_rig(tmp_path, mock_tokenizer) + try: + scheduler = rig.scheduler + submit(rig, "r1", PROMPT_A, arrival=1.0) + submit(rig, "r2", PROMPT_B, arrival=2.0) + submit(rig, "r3", PROMPT_C, arrival=3.0) + step_until(rig, lambda: len(prefilling_ids(rig)) == 3) + scheduler.request_park_prefill() + step(rig) + scheduler.request_park_prefill() + step(rig) + assert waiting_ids(rig) == ["r2", "r3"] + scheduler._memory_hard_limit_bytes = 100 * GB + limit = scheduler._admission_limit_bytes() + monkeypatch.setattr( + scheduler, "_current_usage_bytes", lambda **_kw: limit - 10 * GB + ) + needs = {"r2": 40 * GB, "r3": 1 * GB} + monkeypatch.setattr( + scheduler, "_parked_resume_need_bytes", lambda r: needs[r.request_id] + ) + step(rig, 4) + assert waiting_ids(rig) == ["r2", "r3"] + finally: + rig.close() From cd65a348defd232b8f5bfc6bbce8b7fd0c5cf3f5 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Mon, 5 Oct 2026 15:53:14 -0600 Subject: [PATCH 25/46] feat(scheduler): prefill a cached-media prompt's text suffix in the chunked path A request with any image in its history carried fused embeddings and always prefilled in the synchronous external loop, even when every media token sat inside the restored prefix. It froze concurrent decode and could not be parked. The VLM engine now records Request.vlm_media_end, the token index after the last image, video or audio placeholder. Behind the scheduler.media_text_suffix_chunked setting (default off), admission routes such a request to the text path when the cached prefix reaches the media end, the mRoPE delta was captured, there is no atomic media prefix or SpecPrefill, more than one token is left, and every suffix position equals k + delta on all planes. The delta is bound before the first chunk; the embeddings stay on the request for an OOM requeue or a park re-admit. The decode text-position proof is kept only for a zero delta, the suffix is priced like a media request, and a text-suffix request is parkable. --- docs/TESTING.md | 6 + omlx/engine/vlm.py | 40 ++ omlx/engine_core.py | 4 + omlx/request.py | 6 + omlx/scheduler.py | 173 ++++- omlx/settings.py | 9 + tests/test_scheduler_media_text_suffix.py | 769 ++++++++++++++++++++++ tests/test_settings.py | 25 + 8 files changed, 1004 insertions(+), 28 deletions(-) create mode 100644 tests/test_scheduler_media_text_suffix.py diff --git a/docs/TESTING.md b/docs/TESTING.md index ffb453a87e..425c5fd894 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -235,6 +235,12 @@ Run `python -m pytest -q tests/test_scheduler_prefill_progress_commit.py tests/t Mocked tests do not replace hardware validation: with a real model, abort a long prompt mid-prefill (for example with a low memory ceiling and two concurrent prompts), re-issue it, and check that the log reports a prefix cache restore at the last committed boundary instead of a full prefill. +# Media text-suffix tests + +Run `python -m pytest -q tests/test_scheduler_media_text_suffix.py` to check `scheduler.media_text_suffix_chunked` (env `OMLX_MEDIA_TEXT_SUFFIX_CHUNKED`, off by default). With it on, a media request whose cached prefix reaches the token after its last image, video or audio placeholder (`Request.vlm_media_end`, computed by the VLM engine from the processor's token ids) prefills the uncached text suffix through the chunked text path: decode fairness interleaves decode steps and the prefill can be parked. The route also needs the captured mRoPE delta, no atomic media prefix, no SpecPrefill, more than one token left, and the proof that every suffix position equals `k + delta` on all three planes; otherwise the external media path runs. The cases drive the real scheduler and `VLMModelAdapter` on a small Qwen3.5 hybrid whose output depends on every mRoPE plane, against real paged-SSD stores. They compare the chunked suffix positions with the external slice, greedy tokens, final cache and committed block hashes with the flag on and off, and cover the fallbacks, a decode row advancing between suffix chunks, a park and resume from the committed blocks, abort, an OOM requeue that retries cold through the external path, and teardown. + +Mocked tests do not replace hardware validation: with a real Qwen VL model, send a follow-up turn after an image turn and check the log for the text-suffix route, then compare its greedy output with the flag off. + # Memory-pressure park tests Run `python -m pytest -q tests/test_scheduler_park.py tests/test_scheduler_park_resume_priority.py tests/test_process_memory_enforcer.py tests/test_settings.py -k "park or Park"` to check `scheduler.memory_pressure_park` (also `OMLX_MEMORY_PRESSURE_PARK`; off by default), `scheduler.max_parks_per_request` (`OMLX_MAX_PARKS_PER_REQUEST`, default 3) and `scheduler.park_resume_ok_polls` (`OMLX_PARK_RESUME_OK_POLLS`, default 3). With the setting on, hard (non-emergency) memory pressure parks the most recent chunked-prefill request instead of aborting: it is re-queued without an error, keeps its stream, and resumes in arrival order once the estimated free memory under the admission line covers its need plus a 2% margin (a paused decode: the KV of its final length plus one decode step; a parked prefill: the KV of prompt plus max_tokens plus the prefill transient; KV that running prefills still have to allocate does not count as free), restoring the blocks that `prefill_progress_commit_blocks` committed (without it the park resumes cold). The oldest admitted request is protected, parked blocks are pinned against eviction until the resume, and the legacy abort remains for emergency pressure, nothing parkable, an exhausted park budget, or external-loop (non-chunked, VLM) and SpecPrefill prefills, which cannot be parked between steps. While the parked head waits, nothing newer is admitted, so a smaller request cannot take the headroom the head waits for; once the head fits, newer requests are admitted behind it. The head never resumes on hard pressure, and the nothing-admitted and stale-monitor escapes still release it. When no estimate is available (no admission line or no model dimensions), the older rule applies: enough consecutive ok pressure polls, or the max-hold escape. The scheduler cases run on a small Qwen3.5 hybrid model and compare a resumed request's output with an uninterrupted run; its prompts must stay below the tiny vocabulary of 32 ids, or the embedding read is undefined and the output is nondeterministic. diff --git a/omlx/engine/vlm.py b/omlx/engine/vlm.py index 891861df80..a84d6138ea 100644 --- a/omlx/engine/vlm.py +++ b/omlx/engine/vlm.py @@ -205,6 +205,36 @@ def _capture_vlm_position_state(lm: Any, extra_kwargs: dict[str, Any]) -> None: mx.eval(*lazy_state) +_MEDIA_TOKEN_ID_ATTRS = ( + "image_token_id", + "image_token_index", + "video_token_id", + "video_token_index", + "audio_token_id", + "audio_token_index", +) + + +def _vlm_media_end(token_ids: Any, config: Any) -> int | None: + """Token index just after the last image, video or audio placeholder. + + Uses the same placeholder ids as the cache-boundary helpers. None when the + config names no media token or none appears in ``token_ids``: the + scheduler then keeps the external media prefill. + """ + media_ids = set() + for attr in _MEDIA_TOKEN_ID_ATTRS: + value = getattr(config, attr, None) + if isinstance(value, int) and not isinstance(value, bool): + media_ids.add(value) + if not media_ids or not isinstance(token_ids, (list, tuple)): + return None + for index in range(len(token_ids) - 1, -1, -1): + if token_ids[index] in media_ids: + return index + 1 + return None + + def _apply_minimax_m3_thinking_mode( model_type: str | None, template_kwargs: dict[str, Any], @@ -4745,6 +4775,14 @@ def _inject_specprefill_system_end( except Exception as e: logger.debug(f"SpecPrefill: system_end calc failed: {e}") + def _media_end_kwargs(self, prompt: Any, vlm_inputs_embeds: Any) -> dict[str, int]: + """``vlm_media_end`` for a media request's processor token ids, if known.""" + if vlm_inputs_embeds is None: + return {} + config = getattr(self._vlm_model, "config", None) + media_end = _vlm_media_end(prompt, config) if config is not None else None + return {} if media_end is None else {"vlm_media_end": media_end} + async def generate( self, prompt: str | list[int], @@ -4837,6 +4875,7 @@ async def generate( vlm_image_hash=vlm_image_hash, vlm_cache_key_start=vlm_cache_key_start, vlm_cache_key_ranges=vlm_cache_key_ranges, + **self._media_end_kwargs(prompt, vlm_inputs_embeds), tools=tools, preserve_reasoning=bool(kwargs.get("preserve_reasoning", False)), **specprefill_kwargs, @@ -4953,6 +4992,7 @@ async def stream_generate( vlm_image_hash=vlm_image_hash, vlm_cache_key_start=vlm_cache_key_start, vlm_cache_key_ranges=vlm_cache_key_ranges, + **self._media_end_kwargs(prompt, vlm_inputs_embeds), skip_cache_store=bool(kwargs.get("skip_cache_store", False)), preserve_reasoning=bool(kwargs.get("preserve_reasoning", False)), benchmark_trace=bool(kwargs.get("benchmark_trace", False)), diff --git a/omlx/engine_core.py b/omlx/engine_core.py index 2819b22a56..b87864f17e 100644 --- a/omlx/engine_core.py +++ b/omlx/engine_core.py @@ -663,6 +663,7 @@ async def add_request( vlm_image_hash: Optional[str] = None, vlm_cache_key_start: int = 0, vlm_cache_key_ranges: Optional[List[Tuple[int, str]]] = None, + vlm_media_end: int | None = None, specprefill: Optional[bool] = None, specprefill_keep_pct: Optional[float] = None, specprefill_threshold: Optional[int] = None, @@ -687,6 +688,8 @@ async def add_request( vlm_inputs_embeds: Pre-computed vision+text embeddings for VLM vlm_extra_kwargs: Model-specific VLM kwargs (e.g., position_ids) vlm_image_hash: SHA256 hash of images for prefix cache + vlm_media_end: Token index after the last media placeholder + (None when unknown) specprefill: Per-request SpecPrefill override (True/False/None) specprefill_keep_pct: Per-request keep rate override specprefill_threshold: Per-request threshold override (min tokens) @@ -712,6 +715,7 @@ async def add_request( vlm_image_hash=vlm_image_hash, vlm_cache_key_start=vlm_cache_key_start, vlm_cache_key_ranges=vlm_cache_key_ranges, + vlm_media_end=vlm_media_end, skip_cache_store=skip_cache_store, preserve_reasoning=preserve_reasoning, benchmark_trace=benchmark_trace, diff --git a/omlx/request.py b/omlx/request.py index a031da599d..8ed8d4bd7b 100644 --- a/omlx/request.py +++ b/omlx/request.py @@ -195,6 +195,12 @@ class Request: vlm_cache_key_ranges: Optional[List[Tuple[int, str]]] = ( None # [(token_start, cumulative_image_hash)] ) + # Token index just after the last image/video/audio placeholder, or None + # when unknown. A media request whose cached prefix reaches it prefills + # only text and can take the chunked text path. + vlm_media_end: int | None = None + # Set at admission when that text-suffix route was taken (parkable). + media_text_suffix: bool = False rope_deltas: float = 0.0 # Per-request mRoPE position delta (set after VLM prefill) @property diff --git a/omlx/scheduler.py b/omlx/scheduler.py index dfe9efc5b6..eac7c98b70 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -1694,6 +1694,43 @@ def _materialize_cache_storage(cache_list: list[Any]) -> None: mx.eval(*arrays) +def _captured_rope_delta(request: Any) -> float | None: + """The per-request mRoPE delta captured at embedding time, or None.""" + extra = getattr(request, "vlm_extra_kwargs", None) or {} + captured = extra.get("_captured_rope_deltas") + if captured is None: + return None + if isinstance(captured, mx.array): + return float(captured.reshape(-1)[0].item()) + if hasattr(captured, "item"): + return float(captured.item()) + return float(captured) + + +def _media_suffix_positions_are_text( + position_ids: Any, cached: int, total: int, delta: float +) -> bool: + """True when every uncached position is a text position ``k + delta``. + + That is what the chunked text path computes from the cache offset and the + bound delta; an image, video or audio token in the suffix has grid + positions that differ across the mRoPE planes and fails the check. + """ + if not isinstance(position_ids, mx.array) or delta != int(delta): + return False + if position_ids.ndim == 3 and position_ids.shape[1] == 1: + rows = position_ids[:, 0, :] + elif position_ids.ndim == 2 and position_ids.shape[0] == 1: + rows = position_ids + else: + return False + if rows.shape[-1] != total or not 0 < cached < total: + return False + expected = mx.arange(cached + int(delta), total + int(delta)) + suffix = rows[:, cached:] + return bool(mx.array_equal(suffix, mx.broadcast_to(expected, suffix.shape)).item()) + + def _seed_text_only_mrope_delta_for_cached_prefill(model: Any, request: Any) -> None: """Seed zero mRoPE delta after clearing text-only cached-prefix state.""" if getattr(request, "cached_tokens", 0) <= 0: @@ -1974,6 +2011,10 @@ class SchedulerConfig: # memory pressure instead of aborting; see Scheduler.request_park_prefill. memory_pressure_park: bool = False max_parks_per_request: int = 3 + # Prefill a media request's uncached text suffix through the chunked text + # path when its last media token is inside the cached prefix (decode + # fairness, parkable). Off keeps the external media prefill. + media_text_suffix_chunked: bool = False park_resume_ok_polls: int = 3 # Paged cache settings (internal defaults) @@ -4635,7 +4676,11 @@ def _chunk_route(n_tokens: int, cache_tokens: int) -> bool: self.model, getattr(request, "rope_deltas", 0.0), ) - request.text_positions_proven = True + # A media text suffix runs here with its non-zero delta; + # only canonical positions keep the decode proof. + request.text_positions_proven = ( + getattr(request, "rope_deltas", 0.0) == 0.0 + ) if embeds_array is not None and embeds_array.shape[1] > 0: model_kwargs["inputs_embeds"] = embeds_array[:, :n_to_process] if extra_kwargs: @@ -6764,7 +6809,8 @@ def _plan_prefill_chunk( # if even prefill_min_chunk_tokens would exceed the cap; #1405 # cleanup paths in _schedule_waiting / _advance_chunked_prefills # convert that into a finish_reason="error" output for the client. - # Chunked prefill is text-only (VLM never builds _PrefillState). + # Media requests reach it only on the text-suffix route; they are + # priced like the admission estimate (not text-only). qwen4_accounting = Scheduler._qwen4_prefill_accounting_enabled(self) cache_tokens = state.base_size + state.tokens_processed @@ -6965,7 +7011,9 @@ def _forward_prefill_chunk(self, plan: _PrefillChunkPlan) -> None: self.model, getattr(state.request, "rope_deltas", 0.0), ) - state.request.text_positions_proven = True + state.request.text_positions_proven = ( + getattr(state.request, "rope_deltas", 0.0) == 0.0 + ) prefill_model = getattr(self.model, "_omlx_prefill", self.model) chunk_kwargs = {} if self._supports_skip_lm_head(): @@ -6988,7 +7036,11 @@ def _forward_packed_prefill(self, plans: list[_PrefillChunkPlan]) -> None: state = plan.state chunk = state.tokens_remaining[:, : plan.tokens] state.tokens_remaining = state.tokens_remaining[:, plan.tokens :] - state.request.text_positions_proven = True + # A media text suffix keeps its non-zero delta; only canonical + # positions keep the decode proof (as in _forward_prefill_chunk). + state.request.text_positions_proven = ( + getattr(state.request, "rope_deltas", 0.0) == 0.0 + ) rows.append( PackedRow( request_id=state.request.request_id, @@ -12303,6 +12355,72 @@ def get_park_stats(self) -> dict[str, int]: stats["pinned_requests"] = len(self._park_pins) return stats + def _capture_request_rope_deltas(self, request: Request) -> None: + """Capture a media request's mRoPE delta for its text positions. + + Prefers ``_captured_rope_deltas`` from the request's extra kwargs (set + during get_input_embeddings): the model-global ``_rope_deltas`` may be + stale when explicit position_ids are used. + """ + captured = _captured_rope_delta(request) + if captured is not None: + request.rope_deltas = captured + elif hasattr(self.model, "get_last_rope_deltas"): + request.rope_deltas = self.model.get_last_rope_deltas() + + def _media_text_suffix_route( + self, request: Request, tokens_to_process: list[int] + ) -> bool: + """Whether a media request may prefill its uncached suffix as text. + + Requires the switch, a known media end inside the cached prefix, a + captured mRoPE delta, no atomic media prefix, no SpecPrefill, more + than one token left, and the data proof that every suffix position + is the text position ``k + delta`` the chunked path will compute. + Anything else keeps the external media path. + """ + if getattr(self.config, "media_text_suffix_chunked", False) is not True: + return False + media_end = getattr(request, "vlm_media_end", None) + cached = int(request.cached_tokens or 0) + if not isinstance(media_end, int) or media_end <= 0 or cached < media_end: + return False + if request.specprefill_indices is not None or len(tokens_to_process) <= 1: + return False + total = int(request.num_prompt_tokens) + if cached + len(tokens_to_process) != total: + return False + delta = _captured_rope_delta(request) + if delta is None: + return False + prefix_hook = getattr(self.model, "minimum_prefill_prefix", None) + if callable(prefix_hook): + minimum_prefix = prefix_hook(tokens_to_process) + if isinstance(minimum_prefix, int) and minimum_prefix > 0: + return False + extra = request.vlm_extra_kwargs or {} + with mx.stream(self._stream): + proven = _media_suffix_positions_are_text( + extra.get("position_ids"), cached, total, delta + ) + if not proven: + logger.info( + "Media text-suffix route declined for %s: the uncached " + "positions are not text positions (external media prefill)", + request.request_id, + ) + return False + logger.debug( + "Media text-suffix route for %s: %d cached (media end %d), %d " + "text tokens chunked, rope delta %d", + request.request_id, + cached, + media_end, + len(tokens_to_process), + int(delta), + ) + return True + def _park_exclusion_reason(self, request: Request) -> str | None: """Why ``request`` cannot be parked now, or None when it can. @@ -12311,7 +12429,8 @@ def _park_exclusion_reason(self, request: Request) -> str | None: to completion inside one ``_schedule_waiting`` call and are never between steps; media embeddings and SpecPrefill patch model-wide state, so they are excluded as well. A text prompt on a VLM engine takes the - chunked loop like any other model and is parkable. A decoding row + chunked loop like any other model and is parkable, and so does a media + prompt on the text-suffix route (its media are all cached). A decoding row qualifies for a decode pause unless ``_decode_pause_exclusion_reason`` names why not. """ @@ -12322,7 +12441,10 @@ def _park_exclusion_reason(self, request: Request) -> str | None: return self._decode_pause_exclusion_reason(request) if request.specprefill_indices is not None: return "SpecPrefill sparse prefill patches model-wide state" - if request.vlm_inputs_embeds is not None: + if ( + request.vlm_inputs_embeds is not None + and getattr(request, "media_text_suffix", False) is not True + ): return ( "multimodal prompt (fused media embeddings) prefills in the " "external loop, not between steps" @@ -14584,12 +14706,23 @@ def _report_sparse_progress(processed: int, total: int) -> None: # SpecPrefill already handled its own prefill above, so skip for those. if request.specprefill_indices is None and len(tokens_to_process) > 1: vlm_embeds = None + request.media_text_suffix = False if request.vlm_inputs_embeds is not None: - vlm_embeds = ( - request.vlm_inputs_embeds, - request.vlm_extra_kwargs or {}, - request.cached_tokens, - ) + # Re-proven by the route below (or never, externally). + request.text_positions_proven = False + if self._media_text_suffix_route(request, tokens_to_process): + # Every media token is cached: the suffix is plain + # text at offset + delta. Bind the delta before the + # first chunk; the embeddings stay on the request for + # an OOM requeue or a park re-admit. + request.media_text_suffix = True + self._capture_request_rope_deltas(request) + else: + vlm_embeds = ( + request.vlm_inputs_embeds, + request.vlm_extra_kwargs or {}, + request.cached_tokens, + ) # Chunked prefill: non-VLM prompts longer than one step are # spread across multiple step() calls. The first chunk is run @@ -14799,24 +14932,8 @@ def _report_sparse_progress(processed: int, total: int) -> None: cache_to_use = prefilled_cache tokens_to_process = last_token - # Capture per-request mRoPE rope_deltas for decode. - # Prefer _captured_rope_deltas from per-request extra_kwargs - # (set during get_input_embeddings), since the global - # _rope_deltas may be stale when explicit position_ids are used. if request.vlm_inputs_embeds is not None: - extra = request.vlm_extra_kwargs or {} - captured = extra.get("_captured_rope_deltas") - if captured is not None: - if isinstance(captured, mx.array): - request.rope_deltas = float( - captured.reshape(-1)[0].item() - ) - elif hasattr(captured, "item"): - request.rope_deltas = float(captured.item()) - else: - request.rope_deltas = float(captured) - elif hasattr(self.model, "get_last_rope_deltas"): - request.rope_deltas = self.model.get_last_rope_deltas() + self._capture_request_rope_deltas(request) # Build per-request state machine for stop tokens sm = self._build_state_machine(request) diff --git a/omlx/settings.py b/omlx/settings.py index 4eb8b044a5..fc0d28141f 100644 --- a/omlx/settings.py +++ b/omlx/settings.py @@ -362,6 +362,10 @@ class SchedulerSettings: memory_pressure_park: bool = False # Parks a single request may take before it falls back to the abort. max_parks_per_request: int = 3 + # Prefill a media request's uncached text suffix through the chunked text + # path when its last media token is inside the cached prefix, so it shares + # the GPU with decodes and can be parked. Off keeps the external prefill. + media_text_suffix_chunked: bool = False # Consecutive "ok" pressure polls before parked requests may resume when # no memory estimate is available (with one, a parked request resumes # once the estimated free memory covers its need). @@ -409,6 +413,7 @@ def positive_int(key: str, default: int) -> int: decode_fairness=bool(data.get("decode_fairness", True)), prefill_progress_commit_blocks=commit_blocks, memory_pressure_park=data.get("memory_pressure_park") is True, + media_text_suffix_chunked=data.get("media_text_suffix_chunked") is True, max_parks_per_request=positive_int("max_parks_per_request", 3), park_resume_ok_polls=positive_int("park_resume_ok_polls", 3), ) @@ -1308,6 +1313,9 @@ def _apply_env_overrides(self) -> None: ) if single := os.getenv("OMLX_MEMORY_ABORT_SINGLE_VICTIM"): self.memory.abort_single_victim = single.lower() in ("true", "1", "yes") + if media := os.getenv("OMLX_MEDIA_TEXT_SUFFIX_CHUNKED"): + chunked = media.lower() in ("true", "1", "yes") + self.scheduler.media_text_suffix_chunked = chunked if park := os.getenv("OMLX_MEMORY_PRESSURE_PARK"): self.scheduler.memory_pressure_park = park.lower() in ("true", "1", "yes") for env_name, attr in ( @@ -2024,6 +2032,7 @@ def to_scheduler_config(self) -> SchedulerConfig: self.scheduler.prefill_progress_commit_blocks ), memory_pressure_park=self.scheduler.memory_pressure_park, + media_text_suffix_chunked=self.scheduler.media_text_suffix_chunked, max_parks_per_request=self.scheduler.max_parks_per_request, park_resume_ok_polls=self.scheduler.park_resume_ok_polls, initial_cache_blocks=self.cache.initial_cache_blocks, diff --git a/tests/test_scheduler_media_text_suffix.py b/tests/test_scheduler_media_text_suffix.py new file mode 100644 index 0000000000..46e077d42b --- /dev/null +++ b/tests/test_scheduler_media_text_suffix.py @@ -0,0 +1,769 @@ +# SPDX-License-Identifier: Apache-2.0 +"""A media prompt whose images are all cached prefills its text suffix chunked. + +Any image in a conversation's history gives the request fused embeddings, and +those used to force the synchronous external prefill loop even when every +image sat inside the restored prefix. Such a request froze concurrent decode +and could not be parked. With ``scheduler.media_text_suffix_chunked`` on, a request +whose last media token is cached prefills the uncached text suffix through the +chunked text path with the request's mRoPE delta bound per chunk. + +The tests drive the real scheduler, the real ``VLMModelAdapter`` and real +paged-SSD stores. The language model is a small Qwen3.5 hybrid that also adds +a term computed from every mRoPE plane of its ``position_ids``, so a position +that differs between the two paths changes the logits and the greedy tokens. +""" + +from types import SimpleNamespace + +import mlx.core as mx +import mlx.nn as nn +import pytest +from test_scheduler_prefill_progress_commit import BLOCK, _Rig + +from omlx.models.vlm import VLMModelAdapter +from omlx.request import Request, SamplingParams + +IMAGE_TOKEN = 30 +IMAGE_START = 2 +IMAGE_LEN = 4 # one 1x2x2 grid image +MEDIA_END = IMAGE_START + IMAGE_LEN +DELTA = -2 # Qwen get_rope_index: max(image positions) + 1 - MEDIA_END +IMAGE_HASH = "img-a" + + +def _text(seed, n): + return [3 + (seed * 5 + i * 7) % 26 for i in range(n)] + + +TURN1 = _text(1, 25) # 24 prefill tokens: the stored prefix is block aligned +TURN1[IMAGE_START:MEDIA_END] = [IMAGE_TOKEN] * IMAGE_LEN +TURN2 = TURN1 + _text(2, 18) + + +def _mrope_positions(n, image_start=IMAGE_START): + """(3, 1, n) positions the way Qwen get_rope_index lays out one image.""" + planes = [[], [], []] + for k in range(image_start): + for p in planes: + p.append(k) + for dh, dw in ((0, 0), (0, 1), (1, 0), (1, 1)): + planes[0].append(image_start) + planes[1].append(image_start + dh) + planes[2].append(image_start + dw) + for k in range(image_start + IMAGE_LEN, n): + for p in planes: + p.append(k + DELTA) + return mx.array([[p] for p in planes], dtype=mx.int32) + + +class _MRoPELanguageModel(nn.Module): + """Tiny hybrid whose output depends on all three mRoPE planes.""" + + def __init__(self, inner): + super().__init__() + self.inner = inner + self.model = inner.language_model.model + self._position_ids = None + self._rope_deltas = None + self.unpositioned_calls = 0 + hidden = self.model.embed_tokens.weight.shape[1] + self._planes = mx.random.normal((3, hidden), key=mx.random.key(7)) * 0.2 + + def make_cache(self): + return self.inner.make_cache() + + def _position_term(self, position_ids, batch, length, cache): + if position_ids is None: + self.unpositioned_calls += 1 + offset = next(c.offset for c in cache if hasattr(c, "offset")) + position_ids = mx.arange(length)[None] + offset + if position_ids.ndim == 2: + position_ids = mx.broadcast_to( + position_ids[None], (3, position_ids.shape[0], length) + ) + freqs = mx.array([0.3, 0.7, 1.1])[:, None, None] + waves = mx.sin(position_ids.astype(mx.float32) * freqs) # (3, B, T) + term = (waves[..., None] * self._planes[:, None, None, :]).sum(axis=0) + return mx.broadcast_to(term, (batch, length, term.shape[-1])) + + def __call__(self, inputs, inputs_embeds=None, cache=None, position_ids=None, **_): + if inputs_embeds is None: + inputs_embeds = self.model.embed_tokens(inputs) + batch, length = inputs_embeds.shape[:2] + hidden = inputs_embeds + self._position_term( + position_ids, batch, length, cache + ).astype(inputs_embeds.dtype) + return self.inner(inputs, cache=cache, input_embeddings=hidden) + + +class _FakeQwenVL(nn.Module): + def __init__(self, inner): + super().__init__() + self.language_model = _MRoPELanguageModel(inner) + self.config = SimpleNamespace( + model_type="qwen3_vl", + text_config=SimpleNamespace( + rope_scaling={"mrope_section": [8, 4, 4]}, rope_parameters=None + ), + ) + + +def _set_route(monkeypatch, on): + """Build every SchedulerConfig with media_text_suffix_chunked=on.""" + from omlx.scheduler import SchedulerConfig + + real_init = SchedulerConfig.__init__ + + def init(self, *args, **kwargs): + kwargs.setdefault("media_text_suffix_chunked", on) + real_init(self, *args, **kwargs) + + monkeypatch.setattr(SchedulerConfig, "__init__", init) + + +def _rig(tmp_path, tokenizer, **overrides): + rig = _Rig(tmp_path, tokenizer, split=False, commit_blocks=1, **overrides) + rig.adapter = VLMModelAdapter(_FakeQwenVL(rig.model)) + rig.scheduler.model = rig.adapter + return rig + + +@pytest.fixture +def flag_on(monkeypatch): + _set_route(monkeypatch, True) + + +@pytest.fixture +def flag_off(monkeypatch): + _set_route(monkeypatch, False) + + +def _embeds(rig, tokens): + lm = rig.adapter._language_model + embeds = lm.model.embed_tokens(mx.array([tokens])) + image = mx.random.normal((1, IMAGE_LEN, embeds.shape[-1]), key=mx.random.key(3)) + return mx.concatenate( + [embeds[:, :IMAGE_START], image.astype(embeds.dtype), embeds[:, MEDIA_END:]], + axis=1, + ) + + +def _media_request(rig, rid, tokens, *, max_tokens=4, arrival=None, **overrides): + extra = { + "position_ids": _mrope_positions(len(tokens)), + "_captured_rope_deltas": mx.array([[DELTA]]), + } + fields = dict( + vlm_inputs_embeds=_embeds(rig, tokens), + vlm_extra_kwargs=extra, + vlm_image_hash=IMAGE_HASH, + vlm_cache_key_start=IMAGE_START, + vlm_media_end=MEDIA_END, + ) + fields.update(overrides) + request = Request( + request_id=rid, + prompt=list(tokens), + sampling_params=SamplingParams(max_tokens=max_tokens, temperature=0), + **({"arrival_time": arrival} if arrival is not None else {}), + **fields, + ) + rig.scheduler.add_request(request) + return request + + +def _text_request(rig, rid, tokens, *, max_tokens, arrival): + request = Request( + request_id=rid, + prompt=list(tokens), + sampling_params=SamplingParams(max_tokens=max_tokens, temperature=0), + arrival_time=arrival, + ) + rig.scheduler.add_request(request) + return request + + +def _step(rig, n=1): + outputs = [] + for _ in range(n): + outputs.extend(rig.scheduler.step().outputs) + rig.drain() + return outputs + + +def _run(rig, requests, limit=200, on_step=None): + for _ in range(limit): + if all( + r.is_finished() or r.request_id not in rig.scheduler.requests + for r in requests + ): + break + _step(rig) + if on_step is not None: + on_step() + for future in list(rig.scheduler._inflight_store_futures.values()): + future.result(timeout=30) + rig.scheduler._drain_pending_async_removes() + rig.drain() + + +class _Spy: + """Record which prefill path each admission took.""" + + def __init__(self, rig, monkeypatch): + self.external_media = [] + self.begun = [] + scheduler = rig.scheduler + real_external = scheduler._do_external_prefill + real_begin = scheduler._begin_prefill + + def external(request, tokens, cache, vlm_embeds=None): + if vlm_embeds is not None: + self.external_media.append(request.request_id) + return real_external(request, tokens, cache, vlm_embeds=vlm_embeds) + + def begin(request, tokens, cache): + self.begun.append((request.request_id, request.rope_deltas)) + return real_begin(request, tokens, cache) + + monkeypatch.setattr(scheduler, "_do_external_prefill", external) + monkeypatch.setattr(scheduler, "_begin_prefill", begin) + + +def _warm_turn(rig): + """Turn one prefills cold (external) and stores its media-keyed prefix.""" + first = _media_request(rig, "t1", TURN1, max_tokens=1) + _run(rig, [first]) + return first + + +def _probe(rig, tokens): + return rig.prefix.fetch_cache( + "probe", + list(tokens), + extra_keys=(IMAGE_HASH,), + extra_key_token_start=IMAGE_START, + ) + + +# --- 1. Routing -------------------------------------------------------------- + + +def test_last_image_cached_takes_the_chunked_text_path( + tmp_path, mock_tokenizer, flag_on, monkeypatch +): + rig = _rig(tmp_path, mock_tokenizer) + try: + _warm_turn(rig) + spy = _Spy(rig, monkeypatch) + second = _media_request(rig, "t2", TURN2) + _step(rig) + assert second.cached_tokens >= MEDIA_END + assert second.media_text_suffix is True + assert spy.external_media == [] + # The delta is bound before the first chunk forms its positions. + assert spy.begun == [("t2", float(DELTA))] + assert "t2" in rig.scheduler._prefill_states + # Embeddings stay on the request (park re-admit and OOM requeue). + assert second.vlm_inputs_embeds is not None + _run(rig, [second]) + assert second.vlm_inputs_embeds is None # freed at the first token + finally: + rig.close() + + +def _route_after_warm(rig, monkeypatch, **overrides): + _warm_turn(rig) + spy = _Spy(rig, monkeypatch) + second = _media_request(rig, "t2", TURN2, **overrides) + _step(rig) + return spy, second + + +@pytest.mark.parametrize( + "case", + ["image_in_suffix", "unknown_media_end", "no_captured_delta", "failed_proof"], +) +def test_fallbacks_take_the_external_media_path( + tmp_path, mock_tokenizer, flag_on, monkeypatch, case +): + rig = _rig(tmp_path, mock_tokenizer) + try: + overrides = {} + if case == "image_in_suffix": + overrides["vlm_media_end"] = len(TURN2) - 2 + elif case == "unknown_media_end": + overrides["vlm_media_end"] = None + elif case == "no_captured_delta": + overrides["vlm_extra_kwargs"] = { + "position_ids": _mrope_positions(len(TURN2)) + } + elif case == "failed_proof": + # A suffix plane that is not text positions (an image grid there). + pid = _mrope_positions(len(TURN2)) + planes = pid.tolist() + planes[1][0][-3] += 1 + overrides["vlm_extra_kwargs"] = { + "position_ids": mx.array(planes, dtype=mx.int32), + "_captured_rope_deltas": mx.array([[DELTA]]), + } + spy, second = _route_after_warm(rig, monkeypatch, **overrides) + assert second.cached_tokens > 0 + assert spy.external_media == ["t2"] + assert not second.media_text_suffix + assert "t2" not in rig.scheduler._prefill_states + finally: + rig.close() + + +def test_flag_off_keeps_the_external_media_path( + tmp_path, mock_tokenizer, flag_off, monkeypatch +): + rig = _rig(tmp_path, mock_tokenizer) + try: + spy, second = _route_after_warm(rig, monkeypatch) + assert second.cached_tokens >= MEDIA_END + assert spy.external_media == ["t2"] + assert not second.media_text_suffix + finally: + rig.close() + + +def test_flag_is_off_by_default(tmp_path, mock_tokenizer, monkeypatch): + rig = _rig(tmp_path, mock_tokenizer) + try: + spy, _ = _route_after_warm(rig, monkeypatch) + assert spy.external_media == ["t2"] + finally: + rig.close() + + +def test_minimum_prefill_prefix_keeps_the_external_path( + tmp_path, mock_tokenizer, flag_on, monkeypatch +): + rig = _rig(tmp_path, mock_tokenizer) + try: + _warm_turn(rig) + spy = _Spy(rig, monkeypatch) + second = _media_request(rig, "t2", TURN2) + route = rig.scheduler._media_text_suffix_route + monkeypatch.setattr( + type(rig.adapter), "minimum_prefill_prefix", lambda self, tokens: 3 + ) + assert route(second, list(TURN2[20:])) is False + monkeypatch.setattr( + type(rig.adapter), "minimum_prefill_prefix", lambda self, tokens: 0 + ) + second.cached_tokens = 20 + assert route(second, list(TURN2[20:])) is True + assert route(second, list(TURN2[-1:])) is False # one token left + assert spy.external_media == [] + finally: + rig.close() + + +# --- 2. Position equality ---------------------------------------------------- + + +def test_chunked_positions_equal_the_external_slice( + tmp_path, mock_tokenizer, flag_on, monkeypatch +): + """Every suffix forward sees the positions the external slice would pass.""" + rig = _rig(tmp_path, mock_tokenizer) + try: + _warm_turn(rig) + lm = rig.adapter._language_model + seen = [] + real_call = type(lm).__call__ + + def record( + self, inputs, inputs_embeds=None, cache=None, position_ids=None, **kw + ): + offset = next(c.offset for c in cache if hasattr(c, "offset")) + if isinstance(offset, int) and inputs.shape[1] > 1: + seen.append((offset, position_ids)) + return real_call( + self, + inputs, + inputs_embeds=inputs_embeds, + cache=cache, + position_ids=position_ids, + **kw, + ) + + monkeypatch.setattr(type(lm), "__call__", record) + second = _media_request(rig, "t2", TURN2) + _run(rig, [second]) + assert second.media_text_suffix is True + full = _mrope_positions(len(TURN2)) + chunks = [(o, p) for o, p in seen if o >= second.cached_tokens] + assert chunks, "the suffix never reached the model" + for offset, positions in chunks: + n = positions.shape[-1] + expected = full[:, :, offset : offset + n] + if positions.ndim == 2: + positions = mx.broadcast_to(positions[None], expected.shape) + assert positions.tolist() == expected.tolist() + assert lm.unpositioned_calls == 0 + finally: + rig.close() + + +# --- 3. Greedy equality end to end, 5. block keys and next-turn lookup -------- + + +def _second_turn(tmp_path, tokenizer, monkeypatch, flag): + _set_route(monkeypatch, flag == "true") + rig = _rig(tmp_path, tokenizer) + _warm_turn(rig) + second = _media_request(rig, "t2", TURN2, max_tokens=6) + _run(rig, [second]) + return rig, second + + +def _restored_arrays(rig, tokens): + table, _ = _probe(rig, tokens) + assert table is not None + hashes = [rig.paged.allocated_blocks[b].block_hash for b in table.block_ids] + cache = rig.prefix.reconstruct_cache(table) + arrays = [] + for layer in cache: + arrays.extend(a for a in layer.state if isinstance(a, mx.array)) + return table.num_tokens, hashes, arrays + + +def test_greedy_tokens_and_final_cache_equal_the_external_path( + tmp_path, mock_tokenizer, monkeypatch +): + on, on_req = _second_turn(tmp_path / "on", mock_tokenizer, monkeypatch, "true") + off, off_req = _second_turn(tmp_path / "off", mock_tokenizer, monkeypatch, "false") + try: + assert on_req.media_text_suffix is True + assert not off_req.media_text_suffix + assert on_req.cached_tokens == off_req.cached_tokens >= MEDIA_END + assert len(on_req.output_token_ids) == 6 + assert on_req.output_token_ids == off_req.output_token_ids + assert on_req.rope_deltas == off_req.rope_deltas == float(DELTA) + + next_turn = TURN2 + on_req.output_token_ids + _text(3, 8) + n_on, hashes_on, arrays_on = _restored_arrays(on, next_turn) + n_off, hashes_off, arrays_off = _restored_arrays(off, next_turn) + # The next turn hits everything the second turn prefilled. + assert n_on == n_off >= (len(TURN2) - 1) // BLOCK * BLOCK + assert hashes_on == hashes_off + assert len(arrays_on) == len(arrays_off) > 0 + for a, b in zip(arrays_on, arrays_off): + assert mx.allclose(a, b, atol=1e-5) + finally: + on.close() + off.close() + + +# --- 4. Fairness --------------------------------------------------------------- + + +def test_a_decode_row_emits_tokens_between_suffix_chunks( + tmp_path, mock_tokenizer, flag_on +): + rig = _rig(tmp_path, mock_tokenizer) + try: + _warm_turn(rig) + talker = _text_request(rig, "dec", _text(7, 9), max_tokens=40, arrival=1.0) + _step(rig, 3) + assert "dec" in rig.scheduler.running + second = _media_request(rig, "t2", TURN2, arrival=2.0) + interleaved = [] + + def watch(): + if second.request_id in rig.scheduler._prefill_states: + interleaved.append(len(talker.output_token_ids)) + + _run(rig, [second], on_step=watch) + assert second.media_text_suffix is True + assert len(interleaved) >= 2 + assert interleaved[-1] > interleaved[0] # decode advanced mid-prefill + finally: + rig.close() + + +# --- 6. Park -------------------------------------------------------------------- + + +def test_text_suffix_media_request_parks_and_resumes_with_its_commits( + tmp_path, mock_tokenizer, monkeypatch +): + baseline, base_req = _second_turn( + tmp_path / "base", mock_tokenizer, monkeypatch, "true" + ) + baseline.close() + rig = _rig( + tmp_path / "park", + mock_tokenizer, + memory_pressure_park=True, + park_resume_ok_polls=1, + ) + try: + rig.scheduler.note_pressure_poll("soft") + _warm_turn(rig) + second = _media_request(rig, "t2", TURN2, max_tokens=6) + admitted_cached = [] + for _ in range(40): + _step(rig) + if second.request_id in rig.scheduler._prefill_states: + admitted_cached.append(second.cached_tokens) + if rig.table_tokens("t2") >= second.cached_tokens + BLOCK: + break + assert second.media_text_suffix is True + assert rig.scheduler._park_exclusion_reason(second) is None + assert rig.scheduler.request_park_prefill() is True # hard pressure + _step(rig) + # Parked at the step start; alone, it is re-admitted at once. + assert second.park_count == 1 + committed = second.park_committed_tokens + assert committed > admitted_cached[0] + assert second.vlm_inputs_embeds is not None # kept for the re-admit + + rig.scheduler.note_pressure_poll("ok") + _run(rig, [second]) + assert second.park_count == 1 + assert second.cached_tokens == committed # resumed from its commits + assert second.media_text_suffix is True + assert second.output_token_ids == base_req.output_token_ids + finally: + rig.close() + + +def test_external_media_prefill_stays_excluded_from_park( + tmp_path, mock_tokenizer, flag_on +): + rig = _rig(tmp_path, mock_tokenizer) + try: + media = _media_request(rig, "m", TURN1) + rig.scheduler.waiting.clear() + rig.scheduler.prefilling.append(media) + rig.scheduler._prefill_states["m"] = object() + assert "multimodal" in rig.scheduler._park_exclusion_reason(media) + media.media_text_suffix = True + assert rig.scheduler._park_exclusion_reason(media) is None + finally: + rig.close() + + +# --- 7. Abort, OOM requeue, teardown ------------------------------------------- + + +def test_abort_mid_suffix_cleans_up(tmp_path, mock_tokenizer, flag_on): + rig = _rig(tmp_path, mock_tokenizer) + try: + _warm_turn(rig) + second = _media_request(rig, "t2", TURN2) + _step(rig) + assert "t2" in rig.scheduler._prefill_states + rig.scheduler.abort_request("t2") + _step(rig, 2) + assert "t2" not in rig.scheduler._prefill_states + assert "t2" not in rig.scheduler.requests + assert not rig.scheduler.prefilling + assert second.media_text_suffix is True + finally: + rig.close() + + +def test_oom_requeue_goes_back_to_the_external_path( + tmp_path, mock_tokenizer, flag_on, monkeypatch +): + rig = _rig(tmp_path, mock_tokenizer) + try: + _warm_turn(rig) + spy = _Spy(rig, monkeypatch) + scheduler = rig.scheduler + real_chunk = scheduler._step_prefill_chunk + failed = [] + + def chunk(state): + if not failed: + failed.append(state.request.request_id) + raise RuntimeError("Memory limit exceeded during chunked prefill") + return real_chunk(state) + + monkeypatch.setattr(scheduler, "_step_prefill_chunk", chunk) + second = _media_request(rig, "t2", TURN2) + _step(rig) + assert failed == ["t2"] + assert second.prefill_oom_retries == 1 + assert second.cached_tokens == 0 + assert second.vlm_inputs_embeds is not None + _run(rig, [second]) + assert spy.external_media == ["t2"] # cold retry: images are uncached + assert not second.media_text_suffix + assert second.output_token_ids + finally: + rig.close() + + +def test_teardown_with_a_suffix_in_flight(tmp_path, mock_tokenizer, flag_on): + rig = _rig(tmp_path, mock_tokenizer) + _warm_turn(rig) + _media_request(rig, "t2", TURN2) + _step(rig) + assert "t2" in rig.scheduler._prefill_states + rig.close() # shutdown with a suffix chunk state and commits in flight + assert not rig.scheduler._prefill_commits + + +# --- Media end from the processor's token ids (engine/vlm.py) ------------------- + + +def _config(**ids): + return SimpleNamespace(**ids) + + +@pytest.mark.parametrize( + "tokens,config,expected", + [ + ([1, 9, 9, 2, 3], _config(image_token_id=9), 3), + ([1, 9, 2, 8, 8, 4, 5], _config(image_token_id=9, video_token_id=8), 5), + ([7, 1, 2], _config(image_token_index=9, audio_token_id=7), 1), + ([7, 7, 1], _config(audio_token_index=7), 2), + ([1, 2, 3], _config(image_token_id=9), None), + ([1, 9, 3], _config(), None), + ], +) +def test_media_end_is_the_index_after_the_last_media_token(tokens, config, expected): + from omlx.engine.vlm import _vlm_media_end + + assert _vlm_media_end(tokens, config) == expected + + +def test_engine_core_threads_media_end_onto_the_request(): + import asyncio + from unittest.mock import MagicMock + + from omlx.engine_core import EngineCore + + core = EngineCore.__new__(EngineCore) + core.scheduler = MagicMock() + core.scheduler._specprefill_draft_model = None + core.config = SimpleNamespace(stream_interval=1) + core._mlx_executor = None + core._output_collectors = {} + core._stream_states = {} + core._finished_events = {} + core._wake_engine_loop = lambda: None + + asyncio.run(core.add_request([1, 2, 3], request_id="r", vlm_media_end=2)) + request = core.scheduler.add_request.call_args.args[0] + assert request.vlm_media_end == 2 + + +async def test_vlm_engine_streams_the_media_end_to_the_core(): + from unittest.mock import AsyncMock, MagicMock + + from test_vlm_engine import _make_loaded_engine + + engine = _make_loaded_engine(model_type="test-vlm") + engine._vlm_model.config.image_token_id = 9 + engine._engine = MagicMock() + engine._engine.add_request = AsyncMock(return_value="req-1") + engine._engine.abort_request = AsyncMock(return_value=True) + + async def one_output(_request_id): + yield SimpleNamespace( + output_text="ok", + new_text="ok", + prompt_tokens=4, + completion_tokens=1, + finished=True, + finish_reason="stop", + tool_calls=None, + cached_tokens=0, + ) + + engine._engine.stream_outputs = one_output + async for _ in engine.stream_generate( + [1, 9, 9, 2, 3], vlm_inputs_embeds=mx.zeros((1, 5, 4)) + ): + pass + assert engine._engine.add_request.call_args.kwargs["vlm_media_end"] == 3 + + # Text-only turns carry no media end (the core default None applies). + async for _ in engine.stream_generate([1, 9, 2]): + pass + assert "vlm_media_end" not in engine._engine.add_request.call_args.kwargs + + +async def test_vlm_engine_generate_forwards_the_media_end(): + from unittest.mock import AsyncMock + + from test_vlm_engine import _make_loaded_engine + + engine = _make_loaded_engine(model_type="test-vlm") + engine._vlm_model.config.video_token_id = 8 + output = SimpleNamespace( + output_text="ok", + prompt_tokens=4, + completion_tokens=1, + finish_reason="stop", + tool_calls=None, + cached_tokens=0, + first_token_at=None, + ) + engine._engine = SimpleNamespace(generate=AsyncMock(return_value=output)) + await engine.generate([8, 8, 1, 2], vlm_inputs_embeds=mx.zeros((1, 4, 4))) + assert engine._engine.generate.call_args.kwargs["vlm_media_end"] == 2 + + +class _ForwardCache: + def __init__(self): + self.state = mx.zeros((1,)) + + +def _forward_plan(rid, delta, n=4): + request = SimpleNamespace( + request_id=rid, rope_deltas=delta, text_positions_proven=None + ) + state = SimpleNamespace( + request=request, + tokens_remaining=mx.arange(n).reshape(1, n), + cache=[_ForwardCache()], + base_size=0, + tokens_processed=0, + ) + return SimpleNamespace(state=state, tokens=n) + + +def _forward_host(): + return SimpleNamespace( + model=lambda chunk, cache=None, **_: chunk, + _supports_skip_lm_head=lambda: False, + _dflash_prefill_capture=lambda *_: None, + ) + + +@pytest.mark.parametrize("delta, proven", [(0.0, True), (float(DELTA), False)]) +def test_single_row_forward_keeps_the_proof_only_for_a_zero_delta(delta, proven): + from omlx.scheduler import Scheduler + + plan = _forward_plan("single", delta) + Scheduler._forward_prefill_chunk(_forward_host(), plan) + assert plan.state.request.text_positions_proven is proven + + +def test_packed_forward_keeps_the_proof_only_for_a_zero_delta(monkeypatch): + import omlx.scheduler as scheduler_module + + seen = [] + monkeypatch.setattr( + scheduler_module, + "run_packed_prefill", + lambda model, rows: seen.extend((r.request_id, r.rope_delta) for r in rows), + ) + text = _forward_plan("text", 0.0) + suffix = _forward_plan("suffix", float(DELTA)) + scheduler_module.Scheduler._forward_packed_prefill(_forward_host(), [text, suffix]) + assert seen == [("text", 0.0), ("suffix", float(DELTA))] + assert text.state.request.text_positions_proven is True + # A media text suffix keeps its non-zero delta; only canonical positions + # keep the decode proof, as on the single-row path. + assert suffix.state.request.text_positions_proven is False diff --git a/tests/test_settings.py b/tests/test_settings.py index 4ce0c57f06..fed66288d0 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -396,6 +396,7 @@ def test_to_dict(self): "decode_fairness": True, "prefill_progress_commit_blocks": 0, "memory_pressure_park": False, + "media_text_suffix_chunked": False, "max_parks_per_request": 3, "park_resume_ok_polls": 3, } @@ -3384,3 +3385,27 @@ def test_reaches_the_enforcer(self): assert default._abort_single_victim_enabled() is False on = ProcessMemoryEnforcer(engine_pool=MagicMock(), abort_single_victim=True) assert on._abort_single_victim_enabled() is True + + +class TestMediaTextSuffixChunkedSetting: + """scheduler.media_text_suffix_chunked: off by default, reaches the config.""" + + def test_defaults_off_and_round_trips(self): + assert SchedulerSettings.from_dict({}).media_text_suffix_chunked is False + on = SchedulerSettings.from_dict({"media_text_suffix_chunked": True}) + assert on.media_text_suffix_chunked is True + assert on.to_dict()["media_text_suffix_chunked"] is True + junk = SchedulerSettings.from_dict({"media_text_suffix_chunked": "yes"}) + assert junk.media_text_suffix_chunked is False + + def test_reaches_scheduler_config(self, tmp_path): + settings = GlobalSettings(base_path=tmp_path) + assert settings.to_scheduler_config().media_text_suffix_chunked is False + settings.scheduler.media_text_suffix_chunked = True + assert settings.to_scheduler_config().media_text_suffix_chunked is True + + def test_env_override(self, tmp_path): + env = {"OMLX_MEDIA_TEXT_SUFFIX_CHUNKED": "true"} + with patch.dict(os.environ, env, clear=False): + settings = GlobalSettings.load(base_path=tmp_path) + assert settings.scheduler.media_text_suffix_chunked is True From 78082f4357c37ca2e5c14fb3e04568d1e5e98b76 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Sat, 10 Oct 2026 17:54:44 -0600 Subject: [PATCH 26/46] feat(memory): add the memory_scheduling setting and resolve it in the enforcer The admission features that follow (the never-fits 400 with the capacity numbers and header, the fits-later wait with the solo admission of a lone head, the progress-based admission-stall clock, and the external-loop prefill exemption at hard pressure) plan against a fixed memory budget. That budget only holds when the operator pinned the ceiling and expects memory pressure, so each of them is gated by this setting from its first commit and main's admission is unchanged unless it is on. - memory.memory_scheduling (OMLX_MEMORY_SCHEDULING): "auto" (default) is on when the guard is on and an explicit ceiling is set (custom tier with a ceiling > 0); "on" forces it on but still needs the guard (warning otherwise); "off" forces it off. - The enforcer resolves it at startup and on every live change of the mode, guard, tier or ceiling, logs "Memory scheduling: on (explicit ceiling 48.0 GB)" or the reason it is off, and propagates it to every scheduler (Scheduler._memory_scheduling, off until an enforcer sets it). - Exposed in the admin global settings (GET and live POST). Nothing reads it yet, so behaviour is unchanged. --- docs/TESTING.md | 4 + omlx/admin/routes.py | 26 +++ omlx/process_memory_enforcer.py | 125 +++++++++++++ omlx/scheduler.py | 8 + omlx/server.py | 1 + omlx/settings.py | 36 ++++ tests/test_memory_scheduling_gate.py | 269 +++++++++++++++++++++++++++ 7 files changed, 469 insertions(+) create mode 100644 tests/test_memory_scheduling_gate.py diff --git a/docs/TESTING.md b/docs/TESTING.md index 425c5fd894..801905377f 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -235,6 +235,10 @@ Run `python -m pytest -q tests/test_scheduler_prefill_progress_commit.py tests/t Mocked tests do not replace hardware validation: with a real model, abort a long prompt mid-prefill (for example with a low memory ceiling and two concurrent prompts), re-issue it, and check that the log reports a prefix cache restore at the last committed boundary instead of a full prefill. +# Memory scheduling gate tests + +Run `python -m pytest -q tests/test_memory_scheduling_gate.py` to check `memory.memory_scheduling` (env `OMLX_MEMORY_SCHEDULING`; `auto`, `on` or `off`, default `auto`). The admission features that plan against a fixed memory budget consult it; off, admission behaves as on upstream `main`. `auto` is on when the prefill memory guard is on and an explicit ceiling is set (`memory_guard_tier: custom` with `memory_guard_custom_ceiling_gb` > 0; a ceiling value left under another tier does not count). `on` forces it on but still needs the guard (with the guard off it stays off and logs a warning). `off` forces it off. The `ProcessMemoryEnforcer` resolves the mode at startup and whenever the mode, the guard, the tier or the ceiling changes (the admin settings apply live), logs `Memory scheduling: on (explicit ceiling 48.0 GB)` or the reason it is off, and propagates the result to every scheduler (`Scheduler._memory_scheduling`, False until an enforcer sets it). The tests cover the resolution matrix, the enforcer's startup and live resolution and its propagation, and the setting (default, `to_dict`, `from_dict`, env override, validation, the admin GET and POST). + # Media text-suffix tests Run `python -m pytest -q tests/test_scheduler_media_text_suffix.py` to check `scheduler.media_text_suffix_chunked` (env `OMLX_MEDIA_TEXT_SUFFIX_CHUNKED`, off by default). With it on, a media request whose cached prefix reaches the token after its last image, video or audio placeholder (`Request.vlm_media_end`, computed by the VLM engine from the processor's token ids) prefills the uncached text suffix through the chunked text path: decode fairness interleaves decode steps and the prefill can be parked. The route also needs the captured mRoPE delta, no atomic media prefix, no SpecPrefill, more than one token left, and the proof that every suffix position equals `k + delta` on all three planes; otherwise the external media path runs. The cases drive the real scheduler and `VLMModelAdapter` on a small Qwen3.5 hybrid whose output depends on every mRoPE plane, against real paged-SSD stores. They compare the chunked suffix positions with the external slice, greedy tokens, final cache and committed block hashes with the flag on and off, and cover the fallbacks, a decode row advancing between suffix chunks, a park and resume from the committed blocks, abort, an OOM requeue that retries cold through the external path, and teardown. diff --git a/omlx/admin/routes.py b/omlx/admin/routes.py index b9e4a18ba6..6d9808f0ee 100644 --- a/omlx/admin/routes.py +++ b/omlx/admin/routes.py @@ -689,6 +689,7 @@ class GlobalSettingsRequest(BaseModel): memory_guard_custom_ceiling_gb: float | None = ( None # only used when tier == "custom" ) + memory_scheduling: str | None = None # "auto" / "on" / "off" # Scheduler settings max_concurrent_requests: int | None = None @@ -4683,6 +4684,7 @@ def _global_settings_response(global_settings): "prefill_memory_guard": global_settings.memory.prefill_memory_guard, "memory_guard_tier": global_settings.memory.memory_guard_tier, "memory_guard_custom_ceiling_gb": global_settings.memory.memory_guard_custom_ceiling_gb, + "memory_scheduling": global_settings.memory.memory_scheduling, }, "scheduler": { "max_concurrent_requests": global_settings.scheduler.max_concurrent_requests, @@ -5120,6 +5122,30 @@ async def update_global_settings( f"{'enabled' if request.memory_prefill_memory_guard else 'disabled'}" ) + # Apply memory scheduling mode (Live): the enforcer re-resolves it + # against the guard and ceiling and propagates it to every scheduler. + if request.memory_scheduling is not None: + from ..settings import ( + VALID_MEMORY_SCHEDULING_MODES, + normalize_memory_scheduling, + ) + + mode = normalize_memory_scheduling(request.memory_scheduling) + if mode is None: + raise HTTPException( + status_code=400, + detail=[ + f"Invalid memory_scheduling: {request.memory_scheduling!r} " + f"(must be one of {', '.join(VALID_MEMORY_SCHEDULING_MODES)})" + ], + ) + global_settings.memory.memory_scheduling = mode + from ..server import _server_state + + if _server_state.process_memory_enforcer is not None: + _server_state.process_memory_enforcer.memory_scheduling = mode + runtime_applied.append("memory_scheduling") + # Apply scheduler settings if request.max_concurrent_requests is not None: if ( diff --git a/omlx/process_memory_enforcer.py b/omlx/process_memory_enforcer.py index a9d854320a..0ffe5d241a 100644 --- a/omlx/process_memory_enforcer.py +++ b/omlx/process_memory_enforcer.py @@ -138,6 +138,73 @@ def _format_gb(b: int) -> str: return f"{b / 1024**3:.1f}GB" +@dataclass(frozen=True) +class MemorySchedulingState: + """Resolved ``memory.memory_scheduling``. + + ``enabled`` turns on the never-fits gate and capacity hint, the + fits-later wait (with the solo admission of a lone head) and the + progress-based admission-stall clock. ``warn``: the operator forced it + on but it cannot be (the guard is off). + """ + + mode: str + enabled: bool + reason: str + warn: bool = False + + def log_line(self) -> str: + return f"Memory scheduling: {'on' if self.enabled else 'off'} ({self.reason})" + + +def resolve_memory_scheduling( + mode: Any, + *, + prefill_memory_guard: bool, + memory_guard_tier: str, + custom_ceiling_bytes: int, +) -> MemorySchedulingState: + """Whether memory scheduling is on, and why. + + These behaviours plan against a fixed memory budget: a request that + "fits later" waits for memory that is expected to come back, and the + capacity numbers promise what fits alone. That holds when the operator + pinned the ceiling (custom tier with a ceiling > 0: deterministic + resources, memory pressure expected). On a tier the ceiling follows the + other apps' memory, so "auto" keeps upstream admission there. A custom + ceiling value left under another tier pins nothing and does not count. + "on" forces it on but still needs the prefill memory guard; "off" + forces it off. An unknown mode resolves as "auto". + """ + resolved = _settings.normalize_memory_scheduling(mode) or "auto" + if resolved == "off": + return MemorySchedulingState(resolved, False, "memory_scheduling=off") + if not prefill_memory_guard: + if resolved == "on": + return MemorySchedulingState( + resolved, + False, + "memory_scheduling=on needs the prefill memory guard, and the " + "prefill memory guard is off", + warn=True, + ) + return MemorySchedulingState(resolved, False, "prefill memory guard is off") + if resolved == "on": + return MemorySchedulingState(resolved, True, "memory_scheduling=on") + if memory_guard_tier == "custom" and custom_ceiling_bytes > 0: + return MemorySchedulingState( + resolved, + True, + f"explicit ceiling {custom_ceiling_bytes / 1024**3:.1f} GB", + ) + return MemorySchedulingState( + resolved, + False, + "no explicit memory ceiling; set memory_guard_tier=custom with " + "memory_guard_custom_ceiling_gb, or memory_scheduling=on", + ) + + def get_macos_vm_stats() -> dict[str, int] | None: """Snapshot of mach `vm_statistics64` in bytes. @@ -416,6 +483,7 @@ def __init__( prefill_safe_zone_ratio: float = 0.89, prefill_min_chunk_tokens: int = 256, abort_single_victim: bool = False, + memory_scheduling: str = "auto", ): """ Initialize the process memory enforcer. @@ -447,6 +515,8 @@ def __init__( prefill_min_chunk_tokens: Floor for adaptive shrink. abort_single_victim: On the non-emergency hard path with nothing parkable, abort one victim instead of every request. + memory_scheduling: "auto", "on" or "off"; see + resolve_memory_scheduling. Propagated to every scheduler. """ self._engine_pool = engine_pool self._memory_guard_tier = self._normalize_tier(memory_guard_tier) @@ -472,6 +542,11 @@ def __init__( self._prefill_safe_zone_ratio = prefill_safe_zone_ratio self._prefill_min_chunk_tokens = prefill_min_chunk_tokens self._single_victim_on = bool(abort_single_victim) + self._memory_scheduling_mode = ( + _settings.normalize_memory_scheduling(memory_scheduling) or "auto" + ) + self._memory_scheduling_state: MemorySchedulingState | None = None + self._resolve_memory_scheduling() self._task: asyncio.Task | None = None self._loop: asyncio.AbstractEventLoop | None = None self._wake_event: asyncio.Event | None = None @@ -557,6 +632,7 @@ def memory_guard_tier(self, value: str) -> None: old = self._memory_guard_tier self._memory_guard_tier = new_tier self._refresh_tier_thresholds() + self._resolve_memory_scheduling() if self._running: if self._prefill_memory_guard: self._refresh_effective_metal_cap_bytes() @@ -579,6 +655,7 @@ def memory_guard_custom_ceiling_bytes(self, value: int) -> None: return old = self._memory_guard_custom_ceiling_bytes self._memory_guard_custom_ceiling_bytes = new_value + self._resolve_memory_scheduling() if self._running: if self._prefill_memory_guard: self._refresh_effective_metal_cap_bytes() @@ -1409,10 +1486,57 @@ def prefill_memory_guard(self) -> bool: @prefill_memory_guard.setter def prefill_memory_guard(self, value: bool) -> None: self._prefill_memory_guard = value + self._resolve_memory_scheduling() if self._running: self._propagate_memory_limit() logger.info(f"Prefill memory guard: {'enabled' if value else 'disabled'}") + @property + def memory_scheduling(self) -> str: + """The configured mode: "auto", "on" or "off".""" + return self._memory_scheduling_mode + + @memory_scheduling.setter + def memory_scheduling(self, value: str) -> None: + mode = _settings.normalize_memory_scheduling(value) + if mode is None: + raise ValueError(f"Invalid memory_scheduling: {value!r}") + self._memory_scheduling_mode = mode + self._resolve_memory_scheduling() + if self._running: + self._propagate_memory_limit() + + @property + def memory_scheduling_enabled(self) -> bool: + """Whether memory scheduling is on (see resolve_memory_scheduling).""" + state = self._memory_scheduling_state + return state is not None and state.enabled + + @property + def memory_scheduling_reason(self) -> str: + state = self._memory_scheduling_state + return state.reason if state is not None else "" + + def _resolve_memory_scheduling(self) -> None: + """Re-resolve the mode against the guard and ceiling; log a change. + + Runs at startup and whenever the mode, the guard, the tier or the + custom ceiling changes (admin settings apply live). + """ + state = resolve_memory_scheduling( + self._memory_scheduling_mode, + prefill_memory_guard=self._prefill_memory_guard, + memory_guard_tier=self._memory_guard_tier, + custom_ceiling_bytes=self._memory_guard_custom_ceiling_bytes, + ) + if state == self._memory_scheduling_state: + return + self._memory_scheduling_state = state + if state.warn: + logger.warning(state.log_line()) + else: + logger.info(state.log_line()) + @staticmethod def _resolve_scheduler(entry: Any) -> Any | None: """Resolve the watermark target (Scheduler or DFlash guard) from an @@ -1571,6 +1695,7 @@ def _propagate_memory_limit(self) -> None: # the distinction to point at the right knob. scheduler._memory_guard_tier = self._memory_guard_tier scheduler._prefill_memory_guard = self._prefill_memory_guard + scheduler._memory_scheduling = self.memory_scheduling_enabled scheduler._admission_paused = admission_paused scheduler._prefill_headroom_safety = self._prefill_headroom_safety scheduler._prefill_safe_zone_ratio = self._prefill_safe_zone_ratio diff --git a/omlx/scheduler.py b/omlx/scheduler.py index eac7c98b70..c239e2a9df 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -2501,6 +2501,10 @@ def __init__( # must steer the user to that knob instead of "close other apps". self._memory_guard_tier: str = "balanced" self._prefill_memory_guard: bool = False # set by ProcessMemoryEnforcer + # Memory scheduling: resolved by ProcessMemoryEnforcer from + # memory.memory_scheduling. The admission features that plan against + # a fixed memory budget consult it; off keeps upstream admission. + self._memory_scheduling: bool = False # Set to True by ProcessMemoryEnforcer when phys_footprint crosses # soft_threshold. Schedulers stop admitting new prefills while this is # set; in-flight requests proceed. @@ -5884,6 +5888,10 @@ def _clear_request_admission_bookkeeping(self, request_id: str) -> None: self._clear_memory_admission_blocker(request_id) self._clear_store_cache_admission_blocker(request_id) + def _memory_scheduling_on(self) -> bool: + """Whether memory scheduling is on (see ``_memory_scheduling``).""" + return getattr(self, "_memory_scheduling", False) is True + def _memory_admission_stall_output(self, reason: str) -> RequestOutput | None: """Fail one head-of-line request after persistent memory admission stall.""" if not self.waiting: diff --git a/omlx/server.py b/omlx/server.py index ce05e4a098..b6c90293c3 100644 --- a/omlx/server.py +++ b/omlx/server.py @@ -596,6 +596,7 @@ async def _bonjour_supervisor() -> None: prefill_safe_zone_ratio=memory_settings.prefill_safe_zone_ratio, prefill_min_chunk_tokens=memory_settings.prefill_min_chunk_tokens, abort_single_victim=memory_settings.abort_single_victim, + memory_scheduling=memory_settings.memory_scheduling, ) _server_state.process_memory_enforcer = enforcer _server_state.engine_pool._process_memory_enforcer = enforcer diff --git a/omlx/settings.py b/omlx/settings.py index fc0d28141f..3c4009a039 100644 --- a/omlx/settings.py +++ b/omlx/settings.py @@ -589,6 +589,15 @@ def from_dict(cls, data: dict[str, Any]) -> CacheSettings: MemoryGuardTier = Literal["safe", "balanced", "aggressive", "custom"] VALID_MEMORY_GUARD_TIERS: set[str] = {"safe", "balanced", "aggressive", "custom"} +# memory.memory_scheduling: "auto" turns memory scheduling on only with an +# explicit ceiling (custom tier); "on" and "off" force it. +VALID_MEMORY_SCHEDULING_MODES: tuple[str, ...] = ("auto", "on", "off") + + +def normalize_memory_scheduling(value: Any) -> str | None: + """Lower-cased mode, or None when ``value`` is not a known mode.""" + mode = str(value).strip().lower() + return mode if mode in VALID_MEMORY_SCHEDULING_MODES else None # KV cache storage formats `splash serve --kv-format` accepts. SPLASH_KV_FORMATS = frozenset({"int8", "bf16"}) @@ -621,6 +630,13 @@ class MemorySettings: # On the non-emergency hard path with nothing parkable, abort only the # live request holding the most KV instead of every request. abort_single_victim: bool = False + # Memory scheduling: the never-fits 400 and capacity hint, the fits-later + # wait (with the solo admission) and the progress-based admission-stall + # clock. They plan against a fixed memory budget, so "auto" turns them on + # only when the guard is on and an explicit ceiling is set (custom tier). + # "on" forces them on (still needs the guard), "off" keeps upstream + # admission. Resolved by the ProcessMemoryEnforcer. + memory_scheduling: str = "auto" def to_dict(self) -> dict[str, Any]: """Convert to dictionary.""" @@ -633,6 +649,7 @@ def to_dict(self) -> dict[str, Any]: "prefill_safe_zone_ratio": self.prefill_safe_zone_ratio, "prefill_min_chunk_tokens": self.prefill_min_chunk_tokens, "abort_single_victim": self.abort_single_victim, + "memory_scheduling": self.memory_scheduling, } @classmethod @@ -652,6 +669,10 @@ def from_dict(cls, data: dict[str, Any]) -> MemorySettings: prefill_safe_zone_ratio=float(data.get("prefill_safe_zone_ratio", 0.80)), prefill_min_chunk_tokens=int(data.get("prefill_min_chunk_tokens", 32)), abort_single_victim=data.get("abort_single_victim") is True, + memory_scheduling=normalize_memory_scheduling( + data.get("memory_scheduling", "auto") + ) + or "auto", ) @@ -1311,6 +1332,15 @@ def _apply_env_overrides(self) -> None: f"Invalid OMLX_PREFILL_PROGRESS_COMMIT_BLOCKS value: " f"{commit_blocks}" ) + if raw := os.getenv("OMLX_MEMORY_SCHEDULING"): + mode = normalize_memory_scheduling(raw) + if mode is not None: + self.memory.memory_scheduling = mode + else: + logger.warning( + f"Invalid OMLX_MEMORY_SCHEDULING value: {raw} " + f"(must be one of {', '.join(VALID_MEMORY_SCHEDULING_MODES)})" + ) if single := os.getenv("OMLX_MEMORY_ABORT_SINGLE_VICTIM"): self.memory.abort_single_victim = single.lower() in ("true", "1", "yes") if media := os.getenv("OMLX_MEDIA_TEXT_SUFFIX_CHUNKED"): @@ -1816,6 +1846,12 @@ def validate(self) -> list[str]: "memory_guard_tier is 'custom'" ) + if normalize_memory_scheduling(self.memory.memory_scheduling) is None: + errors.append( + f"Invalid memory_scheduling: {self.memory.memory_scheduling!r} " + f"(must be one of {', '.join(VALID_MEMORY_SCHEDULING_MODES)})" + ) + if not 0.5 <= self.memory.prefill_safe_zone_ratio <= 0.99: errors.append( f"prefill_safe_zone_ratio must be in [0.5, 0.99], " diff --git a/tests/test_memory_scheduling_gate.py b/tests/test_memory_scheduling_gate.py new file mode 100644 index 0000000000..fe1e345052 --- /dev/null +++ b/tests/test_memory_scheduling_gate.py @@ -0,0 +1,269 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Memory scheduling is on only where memory pressure is planned for. + +``memory.memory_scheduling`` is ``auto`` (default: on with an explicit custom +ceiling), ``on`` or ``off``. The process memory enforcer resolves it against +the prefill memory guard and the ceiling, logs the result and propagates it to +every scheduler. The admission features that plan against a fixed memory +budget consult it; off, admission behaves as on upstream ``main``. +""" + +import logging +from types import SimpleNamespace + +import pytest +import test_process_memory_enforcer as enforcer_tests +from test_process_memory_enforcer import _make_enforcer +from test_scheduler_prefill_memory_guard import _make_scheduler + +import omlx.server as server +from omlx.process_memory_enforcer import resolve_memory_scheduling +from omlx.settings import GlobalSettings, MemorySettings + +GB = 1024**3 + +# Shared fixtures: an enforcer's engine pool. +mock_engine_pool = enforcer_tests.mock_engine_pool + +# --- Resolution ------------------------------------------------------------- + + +def _resolve(mode, *, guard=True, tier="custom", ceiling_gb=48.0): + return resolve_memory_scheduling( + mode, + prefill_memory_guard=guard, + memory_guard_tier=tier, + custom_ceiling_bytes=int(ceiling_gb * GB), + ) + + +def test_auto_is_on_with_an_explicit_ceiling(): + state = _resolve("auto") + assert state.enabled is True + assert state.mode == "auto" + assert state.reason == "explicit ceiling 48.0 GB" + assert state.warn is False + + +@pytest.mark.parametrize("tier", ["safe", "balanced", "aggressive"]) +def test_auto_is_off_without_an_explicit_ceiling(tier): + """The custom ceiling only applies under the custom tier: a value left + over under another tier pins nothing.""" + for ceiling_gb in (0.0, 48.0): + state = _resolve("auto", tier=tier, ceiling_gb=ceiling_gb) + assert state.enabled is False + assert "no explicit memory ceiling" in state.reason + assert state.warn is False + + +def test_auto_is_off_with_the_guard_off(): + state = _resolve("auto", guard=False) + assert state.enabled is False + assert state.reason == "prefill memory guard is off" + assert state.warn is False + + +def test_on_forces_it_on_without_a_ceiling(): + state = _resolve("on", tier="balanced", ceiling_gb=0) + assert state.enabled is True + assert state.reason == "memory_scheduling=on" + + +def test_on_still_needs_the_guard_and_warns(): + state = _resolve("on", guard=False) + assert state.enabled is False + assert state.warn is True + assert "prefill memory guard is off" in state.reason + + +def test_off_forces_it_off_with_a_ceiling(): + state = _resolve("off") + assert state.enabled is False + assert state.reason == "memory_scheduling=off" + assert state.warn is False + + +def test_an_unknown_mode_resolves_as_auto(): + assert _resolve("sometimes").mode == "auto" + assert _resolve(" ON ").mode == "on" + + +# --- Settings ---------------------------------------------------------------- + + +def test_the_setting_defaults_to_auto_and_round_trips(): + assert MemorySettings().memory_scheduling == "auto" + assert MemorySettings().to_dict()["memory_scheduling"] == "auto" + assert MemorySettings.from_dict({"memory_scheduling": "On"}).memory_scheduling == ( + "on" + ) + assert MemorySettings.from_dict( + {"memory_scheduling": "bogus"} + ).memory_scheduling == ("auto") + assert MemorySettings.from_dict({}).memory_scheduling == "auto" + + +@pytest.mark.parametrize( + "raw,expected", [("on", "on"), ("OFF", "off"), ("auto", "auto")] +) +def test_the_env_override_sets_the_mode(tmp_path, monkeypatch, raw, expected): + monkeypatch.setenv("OMLX_MEMORY_SCHEDULING", raw) + settings = GlobalSettings.load(base_path=tmp_path) + assert settings.memory.memory_scheduling == expected + + +def test_an_invalid_env_value_is_ignored_with_a_warning(tmp_path, monkeypatch, caplog): + monkeypatch.setenv("OMLX_MEMORY_SCHEDULING", "maybe") + with caplog.at_level(logging.WARNING, logger="omlx.settings"): + settings = GlobalSettings.load(base_path=tmp_path) + assert settings.memory.memory_scheduling == "auto" + assert "Invalid OMLX_MEMORY_SCHEDULING value: maybe" in caplog.text + + +def test_validate_rejects_an_unknown_mode(tmp_path): + settings = GlobalSettings.load(base_path=tmp_path) + settings.memory.memory_scheduling = "sometimes" + assert any("memory_scheduling" in e for e in settings.validate()) + settings.memory.memory_scheduling = "off" + assert not any("memory_scheduling" in e for e in settings.validate()) + + +# --- Enforcer: resolve at startup and on live changes, then propagate -------- + + +def test_the_enforcer_resolves_and_logs_at_startup( + mock_engine_pool, + caplog, +): + with caplog.at_level(logging.INFO, logger="omlx.process_memory_enforcer"): + enforcer = _make_enforcer( + mock_engine_pool, + tier="custom", + memory_guard_custom_ceiling_gb=48.0, + ) + assert enforcer.memory_scheduling == "auto" + assert enforcer.memory_scheduling_enabled is True + assert "Memory scheduling: on (explicit ceiling 48.0 GB)" in caplog.text + + +def test_the_enforcer_defaults_to_off_on_a_tier(mock_engine_pool, caplog): + with caplog.at_level(logging.INFO, logger="omlx.process_memory_enforcer"): + enforcer = _make_enforcer(mock_engine_pool) + assert enforcer.memory_scheduling_enabled is False + assert "Memory scheduling: off (no explicit memory ceiling" in caplog.text + + +def test_on_with_the_guard_off_logs_a_warning(mock_engine_pool, caplog): + with caplog.at_level(logging.WARNING, logger="omlx.process_memory_enforcer"): + enforcer = _make_enforcer( + mock_engine_pool, memory_scheduling="on", prefill_memory_guard=False + ) + assert enforcer.memory_scheduling_enabled is False + assert any( + r.levelno == logging.WARNING and "Memory scheduling: off" in r.getMessage() + for r in caplog.records + ) + + +def test_live_changes_re_resolve_and_log(mock_engine_pool, caplog): + enforcer = _make_enforcer( + mock_engine_pool, tier="custom", memory_guard_custom_ceiling_gb=48.0 + ) + caplog.clear() # only the lines logged by the live changes below + with caplog.at_level(logging.INFO, logger="omlx.process_memory_enforcer"): + enforcer.memory_guard_tier = "balanced" + assert enforcer.memory_scheduling_enabled is False + enforcer.memory_scheduling = "on" + assert enforcer.memory_scheduling_enabled is True + enforcer.prefill_memory_guard = False + assert enforcer.memory_scheduling_enabled is False + enforcer.prefill_memory_guard = True + enforcer.memory_scheduling = "auto" + enforcer.memory_guard_tier = "custom" + enforcer.memory_guard_custom_ceiling_bytes = 40 * GB + assert enforcer.memory_scheduling_enabled is True + messages = [ + r.getMessage() + for r in caplog.records + if r.getMessage().startswith("Memory scheduling:") + ] + assert messages[0].startswith("Memory scheduling: off (no explicit memory ceiling") + assert messages[1] == "Memory scheduling: on (memory_scheduling=on)" + assert messages[-1] == "Memory scheduling: on (explicit ceiling 40.0 GB)" + + +def test_the_enforcer_propagates_the_state_to_schedulers( + mock_engine_pool, +): + from unittest.mock import MagicMock + + scheduler = _make_scheduler() + assert scheduler._memory_scheduling is False # upstream until told + engine = MagicMock(spec=[]) + engine.scheduler = scheduler + mock_engine_pool._entries = {"m": SimpleNamespace(engine=engine)} + enforcer = _make_enforcer( + mock_engine_pool, tier="custom", memory_guard_custom_ceiling_gb=48.0 + ) + enforcer._propagate_memory_limit() + assert scheduler._memory_scheduling is True + enforcer.memory_scheduling = "off" + enforcer._propagate_memory_limit() + assert scheduler._memory_scheduling is False + + +# --- Admin settings ----------------------------------------------------------- + + +def test_admin_saves_the_mode_and_applies_it_live( + mock_engine_pool, + monkeypatch, +): + import asyncio + + from fastapi import HTTPException + from test_admin_server_aliases import ( + _make_global_settings, + _patched_global_settings, + ) + + import omlx.admin.routes as admin_routes + from omlx.admin.routes import GlobalSettingsRequest + + enforcer = _make_enforcer(mock_engine_pool) + monkeypatch.setattr(server._server_state, "process_memory_enforcer", enforcer) + gs = _make_global_settings() + gs.memory.memory_scheduling = "auto" + with _patched_global_settings(gs): + result = asyncio.run( + admin_routes.update_global_settings( + request=GlobalSettingsRequest(memory_scheduling="ON"), is_admin=True + ) + ) + assert "memory_scheduling" in result["runtime_applied"] + assert gs.memory.memory_scheduling == "on" + assert enforcer.memory_scheduling == "on" + assert enforcer.memory_scheduling_enabled is True + with pytest.raises(HTTPException) as info: + asyncio.run( + admin_routes.update_global_settings( + request=GlobalSettingsRequest(memory_scheduling="maybe"), + is_admin=True, + ) + ) + assert info.value.status_code == 400 + assert enforcer.memory_scheduling == "on" + + +def test_admin_lists_the_mode_with_the_memory_settings(tmp_path): + import asyncio + + from test_admin_server_aliases import _patched_global_settings + + import omlx.admin.routes as admin_routes + + gs = GlobalSettings.load(base_path=tmp_path) + gs.memory.memory_scheduling = "off" + with _patched_global_settings(gs): + payload = asyncio.run(admin_routes.get_global_settings(is_admin=True)) + assert payload["memory"]["memory_scheduling"] == "off" From f5ce3704ed202e131361ac8b23cef4f5cff806fe Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Wed, 7 Oct 2026 04:40:23 -0600 Subject: [PATCH 27/46] fix(memory): log only the live enforcer's scheduling state and expose it The settings page's tier previews (preview_tier_ceilings, run on every GET /admin/api/global-settings) build one throwaway enforcer per tier with the default mode, and each logged "Memory scheduling: off (no explicit memory ceiling ...)". Those lines read as the live enforcer turning off after admin saves; it never changed. Only an enforcer that drives an engine pool logs its state now. An explicit memory_scheduling POST logs the resolved state even when it is unchanged and re-propagates it. GET /admin/api/global-settings reports the live state as memory.memory_scheduling_effective (enabled and reason, null without an enforcer), and the POST response carries it. --- docs/TESTING.md | 2 + omlx/admin/routes.py | 23 ++- omlx/process_memory_enforcer.py | 17 +- tests/test_memory_scheduling_admin_state.py | 195 ++++++++++++++++++++ 4 files changed, 231 insertions(+), 6 deletions(-) create mode 100644 tests/test_memory_scheduling_admin_state.py diff --git a/docs/TESTING.md b/docs/TESTING.md index 801905377f..c86a76dd53 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -239,6 +239,8 @@ Mocked tests do not replace hardware validation: with a real model, abort a long Run `python -m pytest -q tests/test_memory_scheduling_gate.py` to check `memory.memory_scheduling` (env `OMLX_MEMORY_SCHEDULING`; `auto`, `on` or `off`, default `auto`). The admission features that plan against a fixed memory budget consult it; off, admission behaves as on upstream `main`. `auto` is on when the prefill memory guard is on and an explicit ceiling is set (`memory_guard_tier: custom` with `memory_guard_custom_ceiling_gb` > 0; a ceiling value left under another tier does not count). `on` forces it on but still needs the guard (with the guard off it stays off and logs a warning). `off` forces it off. The `ProcessMemoryEnforcer` resolves the mode at startup and whenever the mode, the guard, the tier or the ceiling changes (the admin settings apply live), logs `Memory scheduling: on (explicit ceiling 48.0 GB)` or the reason it is off, and propagates the result to every scheduler (`Scheduler._memory_scheduling`, False until an enforcer sets it). The tests cover the resolution matrix, the enforcer's startup and live resolution and its propagation, and the setting (default, `to_dict`, `from_dict`, env override, validation, the admin GET and POST). +Run `python -m pytest -q tests/test_memory_scheduling_admin_state.py` to check memory scheduling across admin settings saves. The cases load the real settings with `memory_scheduling: "on"` in `settings.json`, build the live enforcer from them as the server does, and drive the real admin routes. A save of `max_concurrent_requests`, `chunked_prefill` or `memory_guard_tier` keeps the mode on the live settings object and in `settings.json` (a reload sees it again), keeps it on and propagated, and logs no `Memory scheduling:` line. Loading the settings page (`GET /admin/api/global-settings`, which builds one tier-preview enforcer per tier) logs none either: only an enforcer that drives an engine pool logs its state. An explicit `memory_scheduling` POST, including one that repeats the current mode, re-resolves, logs the state and propagates it to the schedulers. The GET reports the live state as `memory.memory_scheduling_effective` (`enabled` and `reason`, `null` without an enforcer), the POST response carries it, and the factory defaults response does not. + # Media text-suffix tests Run `python -m pytest -q tests/test_scheduler_media_text_suffix.py` to check `scheduler.media_text_suffix_chunked` (env `OMLX_MEDIA_TEXT_SUFFIX_CHUNKED`, off by default). With it on, a media request whose cached prefix reaches the token after its last image, video or audio placeholder (`Request.vlm_media_end`, computed by the VLM engine from the processor's token ids) prefills the uncached text suffix through the chunked text path: decode fairness interleaves decode steps and the prefill can be parked. The route also needs the captured mRoPE delta, no atomic media prefix, no SpecPrefill, more than one token left, and the proof that every suffix position equals `k + delta` on all three planes; otherwise the external media path runs. The cases drive the real scheduler and `VLMModelAdapter` on a small Qwen3.5 hybrid whose output depends on every mRoPE plane, against real paged-SSD stores. They compare the chunked suffix positions with the external slice, greedy tokens, final cache and committed block hashes with the flag on and off, and cover the fallbacks, a decode row advancing between suffix chunks, a park and resume from the committed blocks, abort, an OOM requeue that retries cold through the external path, and teardown. diff --git a/omlx/admin/routes.py b/omlx/admin/routes.py index 6d9808f0ee..96c6c9d779 100644 --- a/omlx/admin/routes.py +++ b/omlx/admin/routes.py @@ -4566,7 +4566,27 @@ async def get_global_settings(is_admin: bool = Depends(require_admin)): await asyncio.to_thread( find_splash_binary, global_settings.integrations.splash_path ) - return _global_settings_response(global_settings) + response = _global_settings_response(global_settings) + response["memory"]["memory_scheduling_effective"] = _memory_scheduling_effective() + return response + + +def _memory_scheduling_effective() -> dict[str, Any] | None: + """The live enforcer's resolved memory scheduling: enabled and why. + + ``memory.memory_scheduling`` is the configured mode; this is what the + enforcer resolved it to against the guard, tier and ceiling (and pushes + to every scheduler). None when no enforcer runs. + """ + from ..server import _server_state + + enforcer = getattr(_server_state, "process_memory_enforcer", None) + if enforcer is None: + return None + return { + "enabled": bool(enforcer.memory_scheduling_enabled), + "reason": str(enforcer.memory_scheduling_reason), + } @router.get("/api/global-settings/defaults") @@ -5971,6 +5991,7 @@ async def update_global_settings( "success": True, "message": message, "runtime_applied": runtime_applied, + "memory_scheduling_effective": _memory_scheduling_effective(), } diff --git a/omlx/process_memory_enforcer.py b/omlx/process_memory_enforcer.py index 0ffe5d241a..54e32a33ed 100644 --- a/omlx/process_memory_enforcer.py +++ b/omlx/process_memory_enforcer.py @@ -1502,7 +1502,9 @@ def memory_scheduling(self, value: str) -> None: if mode is None: raise ValueError(f"Invalid memory_scheduling: {value!r}") self._memory_scheduling_mode = mode - self._resolve_memory_scheduling() + # An explicit mode set always logs the result, even unchanged, so an + # admin POST is visible in the log; the propagation re-pushes it. + self._resolve_memory_scheduling(announce=True) if self._running: self._propagate_memory_limit() @@ -1517,11 +1519,15 @@ def memory_scheduling_reason(self) -> str: state = self._memory_scheduling_state return state.reason if state is not None else "" - def _resolve_memory_scheduling(self) -> None: + def _resolve_memory_scheduling(self, *, announce: bool = False) -> None: """Re-resolve the mode against the guard and ceiling; log a change. Runs at startup and whenever the mode, the guard, the tier or the - custom ceiling changes (admin settings apply live). + custom ceiling changes (admin settings apply live). ``announce`` logs + the state even when it did not change. Only an enforcer that drives + an engine pool logs: the settings page's tier previews and the + cluster memory probe build throwaway enforcers (``engine_pool=None``) + with the default mode, and their lines read as the live one changing. """ state = resolve_memory_scheduling( self._memory_scheduling_mode, @@ -1529,9 +1535,10 @@ def _resolve_memory_scheduling(self) -> None: memory_guard_tier=self._memory_guard_tier, custom_ceiling_bytes=self._memory_guard_custom_ceiling_bytes, ) - if state == self._memory_scheduling_state: - return + changed = state != self._memory_scheduling_state self._memory_scheduling_state = state + if self._engine_pool is None or not (changed or announce): + return if state.warn: logger.warning(state.log_line()) else: diff --git a/tests/test_memory_scheduling_admin_state.py b/tests/test_memory_scheduling_admin_state.py new file mode 100644 index 0000000000..561f4d71af --- /dev/null +++ b/tests/test_memory_scheduling_admin_state.py @@ -0,0 +1,195 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Memory scheduling across admin settings saves. + +The live settings object keeps ``memory.memory_scheduling`` through every +admin save; a save leaves the scheduling mode alone unless it changes the mode +(the tier, ceiling and guard re-resolve ``auto`` only); an explicit mode POST +re-resolves, logs and propagates even when the mode is unchanged; and the +admin settings report the live effective state, so it can be checked without +the log. + +Only the enforcer that drives the engine pool logs its state. The settings +page's tier previews build one throwaway enforcer per tier with the default +mode; their "Memory scheduling: off" lines used to read as the live enforcer +turning off after every settings page load. +""" + +import asyncio +import json +import logging +import os +from types import SimpleNamespace +from unittest.mock import MagicMock + +import pytest +import test_process_memory_enforcer as enforcer_tests +from test_admin_server_aliases import _patched_global_settings +from test_process_memory_enforcer import _make_enforcer +from test_scheduler_prefill_memory_guard import _make_scheduler + +import omlx.admin.routes as admin_routes +import omlx.server as server +from omlx.admin.routes import GlobalSettingsRequest +from omlx.process_memory_enforcer import preview_tier_ceilings +from omlx.settings import GlobalSettings + +mock_engine_pool = enforcer_tests.mock_engine_pool + +ENFORCER_LOGGER = "omlx.process_memory_enforcer" + + +def _scheduling_lines(caplog) -> list[str]: + return [ + r.getMessage() + for r in caplog.records + if r.name == ENFORCER_LOGGER and r.getMessage().startswith("Memory scheduling:") + ] + + +@pytest.fixture +def live(tmp_path, mock_engine_pool, monkeypatch): + """Real settings with memory scheduling on in settings.json, a live + enforcer built from them as the server builds it, and one scheduler it + propagates to.""" + for name in list(os.environ): + if name.startswith("OMLX_"): + monkeypatch.delenv(name, raising=False) + base = tmp_path / "omlx-home" + base.mkdir() + (base / "settings.json").write_text( + json.dumps( + {"memory": {"memory_guard_tier": "aggressive", "memory_scheduling": "on"}} + ) + ) + settings = GlobalSettings.load(base_path=base) + scheduler = _make_scheduler() + engine = MagicMock(spec=[]) + engine.scheduler = scheduler + mock_engine_pool._entries = {"m": SimpleNamespace(engine=engine)} + enforcer = _make_enforcer( + mock_engine_pool, + tier=settings.memory.memory_guard_tier, + prefill_memory_guard=settings.memory.prefill_memory_guard, + memory_scheduling=settings.memory.memory_scheduling, + ) + enforcer._running = True # setters propagate only while running + enforcer._propagate_memory_limit() + monkeypatch.setattr(server._server_state, "process_memory_enforcer", enforcer) + monkeypatch.setattr(server._server_state, "engine_pool", None) + with _patched_global_settings(settings): + yield SimpleNamespace( + base=base, settings=settings, enforcer=enforcer, scheduler=scheduler + ) + enforcer._running = False + + +def _post(**fields) -> dict: + return asyncio.run( + admin_routes.update_global_settings( + request=GlobalSettingsRequest(**fields), is_admin=True + ) + ) + + +def _get() -> dict: + return asyncio.run(admin_routes.get_global_settings(is_admin=True)) + + +def test_the_live_enforcer_starts_on_from_the_settings(live): + assert live.settings.memory.memory_scheduling == "on" + assert live.enforcer.memory_scheduling_enabled is True + assert live.scheduler._memory_scheduling is True + + +@pytest.mark.parametrize( + "fields", + [ + {"max_concurrent_requests": 7}, + {"chunked_prefill": False}, + {"memory_guard_tier": "balanced"}, + ], + ids=["max_concurrent_requests", "chunked_prefill", "memory_guard_tier"], +) +def test_an_admin_save_keeps_the_mode(live, caplog, fields): + with caplog.at_level(logging.INFO, logger=ENFORCER_LOGGER): + _post(**fields) + assert live.settings.memory.memory_scheduling == "on" + assert live.enforcer.memory_scheduling == "on" + assert live.enforcer.memory_scheduling_enabled is True + assert live.scheduler._memory_scheduling is True + assert _scheduling_lines(caplog) == [] + # The mode is still saved, and a restart sees it. + saved = json.loads((live.base / "settings.json").read_text()) + assert saved["memory"]["memory_scheduling"] == "on" + again = GlobalSettings.load(base_path=live.base) + assert again.memory.memory_scheduling == "on" + + +def test_loading_the_settings_page_logs_no_scheduling_change(live, caplog): + with caplog.at_level(logging.INFO, logger=ENFORCER_LOGGER): + _get() + assert _scheduling_lines(caplog) == [] + + +def test_tier_previews_never_log_a_scheduling_state(caplog): + with caplog.at_level(logging.INFO, logger=ENFORCER_LOGGER): + previews = preview_tier_ceilings() + assert set(previews) == {"safe", "balanced", "aggressive", "custom"} + assert _scheduling_lines(caplog) == [] + + +def test_the_settings_report_the_live_effective_state(live): + payload = _get() + assert payload["memory"]["memory_scheduling"] == "on" + assert payload["memory"]["memory_scheduling_effective"] == { + "enabled": True, + "reason": "memory_scheduling=on", + } + live.enforcer.prefill_memory_guard = False + effective = _get()["memory"]["memory_scheduling_effective"] + assert effective["enabled"] is False + assert effective["reason"].startswith("memory_scheduling=on needs the prefill") + + +def test_the_effective_state_is_null_without_a_live_enforcer(live, monkeypatch): + monkeypatch.setattr(server._server_state, "process_memory_enforcer", None) + assert _get()["memory"]["memory_scheduling_effective"] is None + + +def test_the_factory_defaults_carry_no_live_state(live): + payload = asyncio.run(admin_routes.get_global_settings_defaults(is_admin=True)) + assert "memory_scheduling_effective" not in payload["memory"] + + +def test_an_explicit_mode_post_re_resolves_logs_and_propagates(live, caplog): + with caplog.at_level(logging.INFO, logger=ENFORCER_LOGGER): + result = _post(memory_scheduling="off") + assert _scheduling_lines(caplog) == [ + "Memory scheduling: off (memory_scheduling=off)" + ] + assert live.scheduler._memory_scheduling is False + assert result["memory_scheduling_effective"] == { + "enabled": False, + "reason": "memory_scheduling=off", + } + + caplog.clear() + with caplog.at_level(logging.INFO, logger=ENFORCER_LOGGER): + result = _post(memory_scheduling="on") + assert _scheduling_lines(caplog) == ["Memory scheduling: on (memory_scheduling=on)"] + assert live.scheduler._memory_scheduling is True + assert result["memory_scheduling_effective"]["enabled"] is True + + +def test_an_explicit_post_of_the_current_mode_still_logs_and_propagates(live, caplog): + live.scheduler._memory_scheduling = False # a scheduler that missed a tick + with caplog.at_level(logging.INFO, logger=ENFORCER_LOGGER): + _post(memory_scheduling="on") + assert _scheduling_lines(caplog) == ["Memory scheduling: on (memory_scheduling=on)"] + assert live.scheduler._memory_scheduling is True + + +def test_a_save_without_a_live_enforcer_reports_no_effective_state(live, monkeypatch): + monkeypatch.setattr(server._server_state, "process_memory_enforcer", None) + result = _post(max_concurrent_requests=3) + assert result["memory_scheduling_effective"] is None From 1e7e87f88744c7f0cf4289a23a920d6df05050e9 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Mon, 5 Oct 2026 15:16:44 -0600 Subject: [PATCH 28/46] feat(memory): reject never-fits requests and let fits-later requests wait The preflight compared a request against current usage, so a request that would fit once the running ones finish was rejected. The decision is now split. - Never fits alone: weights + exact KV of prompt plus max_tokens + prefill transient over the capacity line (the tighter of the admission line and the prefill safety cap) raises ContextExceedsCapacityError, whatever the current usage. HTTP 400 keeps the existing envelope and adds omlx_code context_exceeds_capacity, required/capacity/weights bytes, kv_bytes_per_token, the requested tokens, max_viable_context_tokens and retryable: false. No eviction is asked for it; the in-stream admission ends it with the same structured error. - Fits alone but not now: the route preflight lets it queue while other work is admitted or queued, and the in-stream admission keeps it at the head until the admitted rows free memory. With nothing admitted, or without an estimate, the old rejection applies. - Capacity hint: GET /v1/omlx/capacity?model= returns the same numbers plus free_bytes_now (inference API key, never loads a model), and chat completions carry a cached X-oMLX-Max-Context-Tokens header. - Weights are summed once from the model's parameter arrays; max_tokens is threaded from the chat and completion preflights. On current main: no text_only parameter (#3482); the capacity estimate prices the transient through the shared admission estimate, so it follows the execution-route predicate. The fits-later wait sits behind upstream's hot-cache credit (#4252): only a request that is over the line after the credit waits or is rejected. All of this is memory scheduling (memory.memory_scheduling): with it off, the default for a stock install, there is no capacity estimate, so the route preflight and the in-stream admission keep the current-usage rejection, chat completions carry no header, and the capacity endpoint answers available: false with memory_scheduling: "off" and the reason. --- README.md | 26 +- docs/TESTING.md | 8 +- omlx/engine/base.py | 41 +++ omlx/engine/batched.py | 12 +- omlx/engine/vlm.py | 4 + omlx/engine_core.py | 9 + omlx/exceptions.py | 36 +++ omlx/scheduler.py | 385 +++++++++++++++++++++++++- omlx/server.py | 118 +++++++- tests/test_memory_scheduling_gate.py | 107 ++++++- tests/test_scheduler_capacity_gate.py | 357 ++++++++++++++++++++++++ tests/test_server_context_capacity.py | 265 ++++++++++++++++++ 12 files changed, 1341 insertions(+), 27 deletions(-) create mode 100644 tests/test_scheduler_capacity_gate.py create mode 100644 tests/test_server_context_capacity.py diff --git a/README.md b/README.md index 21aca317e3..ca43546d25 100644 --- a/README.md +++ b/README.md @@ -273,6 +273,27 @@ Drop-in replacement for OpenAI and Anthropic APIs. Supports streaming usage stat | `POST /v1/systemone` | Typed decisions with decision models (TypeSafe System One) | | `GET /v1/models` | List available models | | `POST /tokenize`, `POST /detokenize` | vLLM-compatible tokenizer API (also under `/v1`) | +| `GET /v1/omlx/capacity?model=` | Memory capacity of a loaded model (see below) | + +#### Memory capacity + +These capacity features plan against a fixed memory budget, so they are part of **memory scheduling**, which is on only when that budget is fixed: + +| `memory.memory_scheduling` (env `OMLX_MEMORY_SCHEDULING`) | Effect | +|---|---| +| `auto` (default) | On when the prefill memory guard is on and an explicit ceiling is set (`memory_guard_tier: custom` with `memory_guard_custom_ceiling_gb` > 0, or `--memory-guard-gb`). Off on the `safe` / `balanced` / `aggressive` tiers. | +| `on` | On whatever the tier. It still needs the prefill memory guard; with the guard off it stays off and logs a warning. | +| `off` | Off. Admission is the same as without these features. | + +Why an explicit ceiling: waiting for memory and promising what fits alone only make sense when the budget is fixed and memory pressure is expected. On a tier, the ceiling follows the memory other apps use, so a request that fits now may not fit a minute later. At startup, and whenever the mode, the guard, the tier or the ceiling changes, the server logs the resolved state, for example `Memory scheduling: on (explicit ceiling 48.0 GB)` or `Memory scheduling: off (no explicit memory ceiling; ...)`. An explicit mode save from the admin settings logs the state even when it did not change. `GET /admin/api/global-settings` reports the live state as `memory.memory_scheduling_effective` (`{"enabled": true, "reason": "memory_scheduling=on"}`, or `null` when no enforcer runs); the `POST` response carries the same field. `memory.memory_scheduling` is the configured mode. + +With memory scheduling on: + +- **Never fits.** A request that cannot fit even with nothing else running (model weights + KV for the prompt plus `max_tokens` + the prefill transient, over the memory guard's capacity line) is rejected up front with HTTP 400 and `omlx_code: "context_exceeds_capacity"`. The usual error envelope stays (`message`, `type`, `code`, `estimated_bytes`, `limit_bytes`) and adds `required_bytes`, `capacity_bytes`, `weights_bytes`, `kv_bytes_per_token`, `requested_context_tokens`, `requested_max_tokens`, `max_viable_context_tokens` and `retryable: false`. Compact or shorten the context, or lower `max_tokens`, before retrying. +- **Fits later.** A request that fits alone but not right now is not rejected. It waits at the head of the queue until running requests free memory. +- **Capacity numbers.** `GET /v1/omlx/capacity?model=&context_tokens=&max_tokens=` (API key like the other `/v1` routes) returns the same numbers for a request of that size plus `free_bytes_now`, without loading the model. An unknown model is a 404 and an unloaded one a 409; `available: false` when no estimate exists. Chat completions also carry an `X-oMLX-Max-Context-Tokens` header: the largest prompt plus `max_tokens` that fits alone. + +With memory scheduling off, a request is checked against the current usage and rejected if it does not fit now, a queued request fails 60 s after it started waiting for memory, and there is no header. The capacity endpoint still answers for a loaded model, with `available: false`, `memory_scheduling: "off"` and the reason. The admin API for settings, models, downloads, quantization, and benchmarks takes the main API key as a Bearer token and also works in headless mode. See [Admin API](docs/admin-api.md). @@ -334,9 +355,12 @@ omlx serve --model-dir ~/models # Choose a memory guard tier at startup omlx serve --model-dir ~/models --memory-guard safe -# Set a custom memory guard ceiling in GB +# Set a custom memory guard ceiling in GB (also turns memory scheduling on) omlx serve --model-dir ~/models --memory-guard-gb 48 +# Force memory scheduling on or off (default auto) +OMLX_MEMORY_SCHEDULING=on omlx serve --model-dir ~/models + # Enable SSD cache for KV blocks omlx serve --model-dir ~/models --paged-ssd-cache-dir ~/.omlx/cache diff --git a/docs/TESTING.md b/docs/TESTING.md index c86a76dd53..c66f1e6814 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -237,10 +237,16 @@ Mocked tests do not replace hardware validation: with a real model, abort a long # Memory scheduling gate tests -Run `python -m pytest -q tests/test_memory_scheduling_gate.py` to check `memory.memory_scheduling` (env `OMLX_MEMORY_SCHEDULING`; `auto`, `on` or `off`, default `auto`). The admission features that plan against a fixed memory budget consult it; off, admission behaves as on upstream `main`. `auto` is on when the prefill memory guard is on and an explicit ceiling is set (`memory_guard_tier: custom` with `memory_guard_custom_ceiling_gb` > 0; a ceiling value left under another tier does not count). `on` forces it on but still needs the guard (with the guard off it stays off and logs a warning). `off` forces it off. The `ProcessMemoryEnforcer` resolves the mode at startup and whenever the mode, the guard, the tier or the ceiling changes (the admin settings apply live), logs `Memory scheduling: on (explicit ceiling 48.0 GB)` or the reason it is off, and propagates the result to every scheduler (`Scheduler._memory_scheduling`, False until an enforcer sets it). The tests cover the resolution matrix, the enforcer's startup and live resolution and its propagation, and the setting (default, `to_dict`, `from_dict`, env override, validation, the admin GET and POST). +Run `python -m pytest -q tests/test_memory_scheduling_gate.py` to check `memory.memory_scheduling` (env `OMLX_MEMORY_SCHEDULING`; `auto`, `on` or `off`, default `auto`). It gates the never-fits 400 with the capacity endpoint numbers and the `X-oMLX-Max-Context-Tokens` header, and the fits-later wait. `auto` is on when the prefill memory guard is on and an explicit ceiling is set (`memory_guard_tier: custom` with `memory_guard_custom_ceiling_gb` > 0; a ceiling value left under another tier does not count). `on` forces it on but still needs the guard (with the guard off it stays off and logs a warning). `off` forces it off. The `ProcessMemoryEnforcer` resolves the mode at startup and whenever the mode, the guard, the tier or the ceiling changes (the admin settings apply live), logs `Memory scheduling: on (explicit ceiling 48.0 GB)` or the reason it is off, and propagates the result to every scheduler (`Scheduler._memory_scheduling`, False until an enforcer sets it). The tests cover the resolution matrix, the setting (default, `to_dict`, `from_dict`, env override, validation, the admin GET and POST), and, with it off, upstream behaviour on each path: no capacity estimate, snapshot or header (a cached hint is not served either); a request whose `max_tokens` can never fit passes when its prompt fits now; a fits-alone-but-not-now request gets the old current-usage rejection; and the capacity endpoint returns `available: false` with `memory_scheduling: "off"` and the reason, while unknown and unloaded models keep their 404 and 409. The suites below that test these behaviours set the mode on explicitly (`scheduler._memory_scheduling = True`). Run `python -m pytest -q tests/test_memory_scheduling_admin_state.py` to check memory scheduling across admin settings saves. The cases load the real settings with `memory_scheduling: "on"` in `settings.json`, build the live enforcer from them as the server does, and drive the real admin routes. A save of `max_concurrent_requests`, `chunked_prefill` or `memory_guard_tier` keeps the mode on the live settings object and in `settings.json` (a reload sees it again), keeps it on and propagated, and logs no `Memory scheduling:` line. Loading the settings page (`GET /admin/api/global-settings`, which builds one tier-preview enforcer per tier) logs none either: only an enforcer that drives an engine pool logs its state. An explicit `memory_scheduling` POST, including one that repeats the current mode, re-resolves, logs the state and propagates it to the schedulers. The GET reports the live state as `memory.memory_scheduling_effective` (`enabled` and `reason`, `null` without an enforcer), the POST response carries it, and the factory defaults response does not. +# Never-fits gate tests + +Run `python -m pytest -q tests/test_scheduler_capacity_gate.py tests/test_server_context_capacity.py` to check the feasibility gate. A request whose weights + exact KV of prompt plus `max_tokens` + prefill transient exceed the capacity line (the tighter of the admission line and the prefill safety cap) is rejected with `ContextExceedsCapacityError` (HTTP 400, `omlx_code: context_exceeds_capacity`, the byte and token fields, `retryable: false`) whatever the current usage. One that fits alone but not now is not rejected: the route preflight lets it queue while other work is admitted or queued, and the in-stream admission keeps it at the head (nothing overtakes it) until the admitted rows free memory. With nothing admitted, or when the capacity cannot be estimated (no memory limit, unknown weights or KV dimensions), the older current-usage rejection applies. The server cases cover the 400 body on API and non-API routes, `GET /v1/omlx/capacity` (fields, 404/409, auth) and the `X-oMLX-Max-Context-Tokens` header on streaming and non-streaming chat completions. These cases run with memory scheduling on (see the memory scheduling gate tests above); off, there is no capacity estimate and the older current-usage rejection applies. + +Mocked tests do not replace hardware validation: with a real model, send a prompt larger than `max_viable_context_tokens` and check for an immediate 400 with the fields, then send two prompts that each fit alone but not together and check that the second waits and completes without an error. + # Media text-suffix tests Run `python -m pytest -q tests/test_scheduler_media_text_suffix.py` to check `scheduler.media_text_suffix_chunked` (env `OMLX_MEDIA_TEXT_SUFFIX_CHUNKED`, off by default). With it on, a media request whose cached prefix reaches the token after its last image, video or audio placeholder (`Request.vlm_media_end`, computed by the VLM engine from the processor's token ids) prefills the uncached text suffix through the chunked text path: decode fairness interleaves decode steps and the prefill can be parked. The route also needs the captured mRoPE delta, no atomic media prefix, no SpecPrefill, more than one token left, and the proof that every suffix position equals `k + delta` on all three planes; otherwise the external media path runs. The cases drive the real scheduler and `VLMModelAdapter` on a small Qwen3.5 hybrid whose output depends on every mRoPE plane, against real paged-SSD stores. They compare the chunked suffix positions with the external slice, greedy tokens, final cache and committed block hashes with the flag on and off, and cover the fallbacks, a decode row advancing between suffix chunks, a park and resume from the committed blocks, abort, an OOM requeue that retries cold through the external path, and teardown. diff --git a/omlx/engine/base.py b/omlx/engine/base.py index f505e3aae7..0101122148 100644 --- a/omlx/engine/base.py +++ b/omlx/engine/base.py @@ -88,6 +88,7 @@ async def _run_scheduler_preflight_with_cleanup_retry( request_id: str | None, eviction_callback: Any | None, executor: Any | None = None, + max_tokens: int | None = None, ) -> None: """Run route preflight after transient post-request cleanup settles. @@ -103,16 +104,20 @@ async def _run_scheduler_preflight_with_cleanup_retry( """ deadline = time.monotonic() + _PREFLIGHT_CLEANUP_WAIT_TIMEOUT_S waited_for_cleanup = False + # max_tokens feeds the never-fits gate; omitted when the caller has none. + output_budget = {"max_tokens": max_tokens} if max_tokens is not None else {} while True: eviction_request = scheduler.preflight_eviction_request( num_prompt_tokens=num_prompt_tokens, request_id=request_id, + **output_budget, ) if eviction_request is None: scheduler.preflight_or_raise( num_prompt_tokens=num_prompt_tokens, request_id=request_id, + **output_budget, ) return @@ -188,6 +193,7 @@ async def _run_scheduler_preflight_with_cleanup_retry( scheduler.preflight_or_raise( num_prompt_tokens=num_prompt_tokens, request_id=request_id, + **output_budget, ) return @@ -568,6 +574,41 @@ async def tokenize_chat( f"{type(self).__name__} does not support chat tokenization" ) + def _capacity_scheduler(self) -> Any: + """The scheduler behind an EngineCore-backed engine, or None.""" + core = getattr(getattr(self, "_engine", None), "engine", None) + return getattr(core, "scheduler", None) + + def capacity_snapshot( + self, *, context_tokens: int = 0, max_tokens: int = 0 + ) -> dict[str, int] | None: + """Never-fits capacity numbers plus the free bytes now, or None. + + Engines whose scheduler has no memory estimate (or no scheduler at + all) return None. + """ + fn = getattr(self._capacity_scheduler(), "capacity_snapshot", None) + if not callable(fn): + return None + try: + snapshot = fn(context_tokens=context_tokens, max_tokens=max_tokens) + except Exception: # noqa: BLE001 - a hint must never fail a request + return None + return snapshot if isinstance(snapshot, dict) else None + + def max_context_tokens_hint(self) -> int | None: + """Cached largest context plus max_tokens that fits alone, or None.""" + fn = getattr(self._capacity_scheduler(), "max_viable_context_tokens", None) + if not callable(fn): + return None + try: + hint = fn() + except Exception: # noqa: BLE001 - a hint must never fail a request + return None + if isinstance(hint, bool) or not isinstance(hint, int): + return None + return hint + class ActivityTrackingMixin: """In-flight operation tracking for admin visibility. diff --git a/omlx/engine/batched.py b/omlx/engine/batched.py index c6c85fc23b..a53b71b65a 100644 --- a/omlx/engine/batched.py +++ b/omlx/engine/batched.py @@ -107,6 +107,7 @@ async def _preflight_or_raise_with_eviction( *, num_prompt_tokens: int, request_id: str | None, + max_tokens: int | None = None, ) -> None: await _run_scheduler_preflight_with_cleanup_retry( scheduler, @@ -118,6 +119,7 @@ async def _preflight_or_raise_with_eviction( "_mlx_executor", None, ), + max_tokens=max_tokens, ) @property @@ -1429,7 +1431,10 @@ async def preflight_chat( _warn_scheduler_unreachable_once(self, "preflight_chat") return await self._preflight_or_raise_with_eviction( - scheduler, num_prompt_tokens=num_tokens, request_id=request_id + scheduler, + num_prompt_tokens=num_tokens, + request_id=request_id, + max_tokens=kwargs.get("max_tokens"), ) async def preflight_completion( @@ -1459,7 +1464,10 @@ async def preflight_completion( _warn_scheduler_unreachable_once(self, "preflight_completion") return await self._preflight_or_raise_with_eviction( - scheduler, num_prompt_tokens=num_tokens, request_id=request_id + scheduler, + num_prompt_tokens=num_tokens, + request_id=request_id, + max_tokens=kwargs.get("max_tokens"), ) async def stream_chat( diff --git a/omlx/engine/vlm.py b/omlx/engine/vlm.py index a84d6138ea..0ebd02da52 100644 --- a/omlx/engine/vlm.py +++ b/omlx/engine/vlm.py @@ -1902,6 +1902,7 @@ async def _preflight_or_raise_with_eviction( *, num_prompt_tokens: int, request_id: str | None, + max_tokens: int | None = None, ) -> None: await _run_scheduler_preflight_with_cleanup_retry( scheduler, @@ -1913,6 +1914,7 @@ async def _preflight_or_raise_with_eviction( "_mlx_executor", None, ), + max_tokens=max_tokens, ) @property @@ -5257,6 +5259,7 @@ async def preflight_chat( scheduler, num_prompt_tokens=num_tokens, request_id=request_id, + max_tokens=kwargs.get("max_tokens"), ) async def preflight_completion( @@ -5292,6 +5295,7 @@ async def preflight_completion( scheduler, num_prompt_tokens=num_tokens, request_id=request_id, + max_tokens=kwargs.get("max_tokens"), ) async def stream_chat( diff --git a/omlx/engine_core.py b/omlx/engine_core.py index b87864f17e..233ed43f9a 100644 --- a/omlx/engine_core.py +++ b/omlx/engine_core.py @@ -37,6 +37,7 @@ import mlx.core as mx from .exceptions import ( + ContextExceedsCapacityError, PrefillMemoryAbortedError, PrefillMemoryExceededError, RequestAbortedError, @@ -165,6 +166,14 @@ def __exit__(self, *exc): def _raise_request_output_error(output: RequestOutput) -> None: + if output.error_code == "context_exceeds_capacity": + metadata = dict(output.error_metadata or {}) + request_id = metadata.pop("request_id", None) + raise ContextExceedsCapacityError( + message=output.error or "Context exceeds capacity", + request_id=str(request_id) if request_id is not None else output.request_id, + capacity_fields=metadata, + ) if output.error_code in ("prefill_memory_exceeded", "prefill_memory_aborted"): metadata = output.error_metadata or {} request_id = metadata.get("request_id") diff --git a/omlx/exceptions.py b/omlx/exceptions.py index 91b369c914..699113e36a 100644 --- a/omlx/exceptions.py +++ b/omlx/exceptions.py @@ -474,6 +474,42 @@ def __init__( self.limit_bytes = limit_bytes +class ContextExceedsCapacityError(PrefillMemoryExceededError): + """ + The request cannot fit even with nothing else running. + + Raised by the never-fits gate when the model weights plus the KV of the + whole context (prompt plus max_tokens) plus the prefill transient exceed + the memory guard's capacity line. Waiting cannot help, so it is not + retryable as is: the client must compact or shorten the context, or + lower max_tokens. Subclassing PrefillMemoryExceededError keeps the + HTTP 400 mapping and the existing error envelope. + + Attributes: + capacity_fields: ``required_bytes``, ``capacity_bytes``, + ``weights_bytes``, ``kv_bytes_per_token``, + ``requested_context_tokens``, ``requested_max_tokens`` and + ``max_viable_context_tokens`` (prompt plus max_tokens). + """ + + omlx_code = "context_exceeds_capacity" + + def __init__( + self, + message: str, + request_id: str | None = None, + *, + capacity_fields: dict, + ): + super().__init__( + message, + request_id=request_id, + estimated_bytes=capacity_fields.get("required_bytes"), + limit_bytes=capacity_fields.get("capacity_bytes"), + ) + self.capacity_fields = dict(capacity_fields) + + class PrefillMemoryAbortedError(PrefillMemoryExceededError): """ An admitted request was aborted mid-prefill by the memory enforcer. diff --git a/omlx/scheduler.py b/omlx/scheduler.py index c239e2a9df..7f4711b7a6 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -58,6 +58,7 @@ from .cache.prefix_cache import BlockAwarePrefixCache, cachelist_pm_member_plan from .decode_activity import get_decode_activity from .exceptions import ( + ContextExceedsCapacityError, PrefillMemoryExceededError, describe_ceiling_binding, is_cache_corruption_error, @@ -213,6 +214,55 @@ class _PreflightRejection: message: str estimated_bytes: int limit_bytes: int + # Set when the request cannot fit even alone (never-fits gate). + capacity: "_CapacityEstimate | None" = None + + +@dataclass(frozen=True) +class _CapacityEstimate: + """Whether a request fits this model's memory with nothing else running. + + ``required_bytes`` is weights + exact KV of context plus max_tokens + + the prefill transient, compared against ``capacity_bytes`` (the tighter + of the admission line and the prefill safety cap). + ``max_viable_context_tokens`` is the largest context plus max_tokens + that fits alone. + """ + + required_bytes: int + capacity_bytes: int + weights_bytes: int + kv_bytes_per_token: int + requested_context_tokens: int + requested_max_tokens: int + max_viable_context_tokens: int + + @property + def fits_alone(self) -> bool: + return self.required_bytes <= self.capacity_bytes + + def fields(self) -> dict[str, int]: + return { + "required_bytes": self.required_bytes, + "capacity_bytes": self.capacity_bytes, + "weights_bytes": self.weights_bytes, + "kv_bytes_per_token": self.kv_bytes_per_token, + "requested_context_tokens": self.requested_context_tokens, + "requested_max_tokens": self.requested_max_tokens, + "max_viable_context_tokens": self.max_viable_context_tokens, + } + + +class _PreflightDeferredError(Exception): + """The request fits alone but not now: it waits at the head of the queue.""" + + +# Upper bound of the max-viable-context search (tokens). +_MAX_VIABLE_CONTEXT_SEARCH_CAP = 1 << 24 +# Seconds a computed max viable context stays cached for the response header. +_MAX_VIABLE_CONTEXT_CACHE_TTL_S = 30.0 +# Seconds between "fits later" log lines for the same waiting request. +_FITS_LATER_LOG_INTERVAL_S = 30.0 @dataclass @@ -597,6 +647,21 @@ def _prefill_memory_error_output( ) +def _context_capacity_error_output( + request_id: str, message: str, capacity: "_CapacityEstimate" +) -> RequestOutput: + metadata: dict[str, int | str] = {"request_id": request_id} + metadata.update(capacity.fields()) + return RequestOutput( + request_id=request_id, + finished=True, + finish_reason="error", + error=message, + error_code="context_exceeds_capacity", + error_metadata=metadata, + ) + + def _prefill_memory_exception_output( request_id: str, exc: PrefillMemoryExceededError, @@ -2466,6 +2531,13 @@ def __init__( "waiting": [], } + # Never-fits gate: model weight bytes (None until first measured), + # the cached max viable context (key, value, computed_at) and the + # last "fits later" log line (request id, monotonic). + self._weights_bytes: int | None = None + self._max_viable_cache: tuple[tuple, int, float] | None = None + self._fits_later_logged: tuple[str, float] | None = None + # Memory limits for inline prefill checking. # Set by ProcessMemoryEnforcer; propagated to BatchGenerator. self._memory_limit_bytes: int = 0 # soft limit (dynamic, jittery) @@ -11288,6 +11360,7 @@ def add_request(self, request: Request) -> None: num_prompt_tokens=request.num_prompt_tokens, cached_tokens=request.cached_tokens or 0, request_id=request.request_id, + max_tokens=getattr(request.sampling_params, "max_tokens", None), ) except Exception: self._release_paged_cache_for_request(request.request_id) @@ -13793,6 +13866,21 @@ def _preflight_memory_check( if request.prompt_cache is not None: return None + capacity = self._capacity_estimate( + context_tokens=prompt_tokens, + max_tokens=getattr(request.sampling_params, "max_tokens", 0), + ) + if capacity is not None and not capacity.fits_alone: + return _PreflightRejection( + message=self._never_fits_message(capacity), + estimated_bytes=capacity.required_bytes, + limit_bytes=capacity.capacity_bytes, + capacity=capacity, + ) + # Fits alone: while rows are admitted, their memory comes back when + # they finish, so the request waits at the head instead of failing. + fits_later = capacity is not None and self._num_admitted_requests() > 0 + # A request resumed after an eviction pause keeps its prompt cache. # Capacity reserved there already holds part of the KV priced below. current = max( @@ -13826,6 +13914,9 @@ def _preflight_memory_check( requested_tokens=est.floor_chunk, reason="prefill_preflight", ) + if fits_later: + self._log_fits_later(request.request_id, est.estimated, hard_limit) + raise _PreflightDeferredError() message = self._format_rejection_message( estimated=est.estimated, @@ -13853,6 +13944,13 @@ def _preflight_memory_check( requested_tokens=est.floor_chunk, reason="prefill_safety_cap", ) + if fits_later: + self._log_fits_later( + request.request_id, + safety_rejection.estimated_bytes, + safety_rejection.limit_bytes, + ) + raise _PreflightDeferredError() return safety_rejection return None @@ -13987,12 +14085,226 @@ def _format_rejection_message( f"({' - '.join(parts)}). {advice}." ) + # ------------------------------------------------------------------ + # Never-fits gate and capacity hint. + # ------------------------------------------------------------------ + + def _model_weights_bytes(self) -> int: + """Resident bytes of this model's weights; 0 when unknown. + + Summed once from the model's parameter arrays (shape metadata only, + nothing is evaluated); a measured monitor baseline is the fallback. + """ + cached = self._weights_bytes + if cached is not None: + return cached + total = 0 + try: + total = sum( + int(value.nbytes) + for _, value in tree_flatten(self.model.parameters()) + if isinstance(value, mx.array) + ) + except Exception: # noqa: BLE001 - unknown model shape: no estimate + total = 0 + if total <= 0 and self.memory_monitor is not None: + baseline = getattr(self.memory_monitor, "_baseline_memory", 0) + if isinstance(baseline, int) and not isinstance(baseline, bool): + total = baseline + if total > 0: + self._weights_bytes = total + return total + + def _capacity_limit_bytes(self) -> int: + """The line a request must fit under alone: the tighter of the + admission line and the prefill safety cap (0 when no limit).""" + limits = [ + v + for v in (self._admission_limit_bytes(), self._prefill_abort_cap()) + if v > 0 + ] + return min(limits) if limits else 0 + + def _required_alone_bytes(self, tokens: int, weights: int) -> int: + """Weights + exact KV of ``tokens`` + the prefill transient. + + The transient is priced by the shared admission estimate, so it + follows the same execution-route predicate as admission (#3482). + """ + est = self._admission_estimate( + num_prompt_tokens=tokens, + cached_tokens=0, + current=weights, + ) + return int(est.estimated) if est is not None else int(weights) + + def _capacity_estimate( + self, + *, + context_tokens: int, + max_tokens: int | None, + ) -> _CapacityEstimate | None: + """Whether ``context_tokens + max_tokens`` fits with nothing else running. + + None when it cannot be estimated: no monitor, no memory limit, model + weights or KV dimensions unknown, or memory scheduling off. Without + an estimate there is no never-fits error, no fits-later wait and no + capacity hint: the upstream current-usage preflight. + """ + if not self._memory_scheduling_on(): + return None + monitor = self.memory_monitor + if monitor is None: + return None + capacity = self._capacity_limit_bytes() + weights = self._model_weights_bytes() + if capacity <= 0 or weights <= 0: + return None + if ( + self._admission_estimate( + num_prompt_tokens=4096, + cached_tokens=0, + current=0, + ) + is None + ): + return None + context = max(0, int(context_tokens or 0)) + output = max(0, int(max_tokens or 0)) + return _CapacityEstimate( + required_bytes=self._required_alone_bytes(context + output, weights), + capacity_bytes=capacity, + weights_bytes=weights, + kv_bytes_per_token=int( + round(float(monitor.estimate_prompt_kv_bytes(1024)) / 1024) + ), + requested_context_tokens=context, + requested_max_tokens=output, + max_viable_context_tokens=self._max_viable_context(capacity, weights), + ) + + def _max_viable_context(self, capacity: int, weights: int) -> int: + """Largest context plus max_tokens that fits alone (cached briefly).""" + key = (int(capacity), int(weights)) + now = time.monotonic() + cached = self._max_viable_cache + if ( + cached is not None + and cached[0] == key + and now - cached[2] < _MAX_VIABLE_CONTEXT_CACHE_TTL_S + ): + return cached[1] + + def fits(tokens: int) -> bool: + return self._required_alone_bytes(tokens, weights) <= capacity + + cap = _MAX_VIABLE_CONTEXT_SEARCH_CAP + if not fits(0): + best = 0 + else: + lo, hi = 0, 4096 + while hi < cap and fits(hi): + lo, hi = hi, hi * 2 + if hi >= cap and fits(cap): + best = cap + else: + hi = min(hi, cap) + while hi - lo > 1: # invariant: fits(lo), not fits(hi) + mid = (lo + hi) // 2 + if fits(mid): + lo = mid + else: + hi = mid + best = lo + self._max_viable_cache = (key, best, now) + return best + + def max_viable_context_tokens(self) -> int | None: + """Cached capacity hint: the largest text context plus max_tokens + that fits with nothing else running, or None when unknown or memory + scheduling is off.""" + if not self._memory_scheduling_on(): + return None + capacity = self._capacity_limit_bytes() + weights = self._model_weights_bytes() + if capacity <= 0 or weights <= 0: + return None + cached = self._max_viable_cache + if ( + cached is not None + and cached[0] == (capacity, weights) + and time.monotonic() - cached[2] < _MAX_VIABLE_CONTEXT_CACHE_TTL_S + ): + return cached[1] + estimate = self._capacity_estimate(context_tokens=0, max_tokens=0) + return estimate.max_viable_context_tokens if estimate is not None else None + + def capacity_snapshot( + self, *, context_tokens: int = 0, max_tokens: int = 0 + ) -> dict[str, int] | None: + """Capacity numbers for a text request plus the free bytes right now. + + Safe off the MLX thread (uses the cached MLX sample). None when the + capacity cannot be estimated. + """ + estimate = self._capacity_estimate( + context_tokens=context_tokens, max_tokens=max_tokens + ) + if estimate is None: + return None + snapshot = estimate.fields() + snapshot["free_bytes_now"] = int(estimate.capacity_bytes) - int( + self._current_usage_bytes(refresh_mlx_active=False) + ) + return snapshot + + def _never_fits_message(self, capacity: _CapacityEstimate) -> str: + binding_str, advice = describe_ceiling_binding( + static=self._memory_static_ceiling_bytes, + dynamic=self._memory_dynamic_ceiling_bytes, + metal_cap=self._memory_metal_cap_bytes, + metal_cap_raw=getattr(self, "_memory_metal_cap_raw_bytes", 0), + tier=self._memory_guard_tier, + current=capacity.weights_bytes, + fmt=format_bytes, + tail=["compact or shorten the context", "lower max_tokens"], + ) + return ( + f"Request needs ~{format_bytes(capacity.required_bytes)} " + f"(weights {format_bytes(capacity.weights_bytes)} + KV and " + f"transient for {capacity.requested_context_tokens} context + " + f"{capacity.requested_max_tokens} max tokens) but this model's " + f"memory capacity under the {binding_str} ceiling is " + f"{format_bytes(capacity.capacity_bytes)} even with nothing else " + f"running; at most {capacity.max_viable_context_tokens} tokens of " + f"context plus max_tokens fit. {advice}." + ) + + def _log_fits_later(self, request_id: str, estimated: int, limit: int) -> None: + now = time.monotonic() + last = self._fits_later_logged + if ( + last is not None + and last[0] == request_id + and now - last[1] < _FITS_LATER_LOG_INTERVAL_S + ): + return + self._fits_later_logged = (request_id, now) + logger.info( + "Request %s fits alone but not now (needs %.1f GB, line %.1f GB); " + "waiting for running requests to finish", + request_id, + estimated / 1024**3, + limit / 1024**3, + ) + def preflight_or_raise( self, *, num_prompt_tokens: int, cached_tokens: int = 0, request_id: str | None = None, + max_tokens: int | None = None, ) -> None: """Pre-StreamingResponse prefill memory check. @@ -14005,6 +14317,12 @@ def preflight_or_raise( directly (no Request object) and raises instead of returning a message — the in-stream re-check inside ``_schedule_waiting`` remains as defense-in-depth. + + A request that cannot fit even alone (weights + KV of prompt plus + ``max_tokens`` + transient over the capacity line) raises + ``ContextExceedsCapacityError`` whatever the current usage. One that + fits alone but not now passes while other work is admitted or + queued: it waits for that work to finish instead of being rejected. """ if not self._prefill_memory_guard: return @@ -14013,6 +14331,31 @@ def preflight_or_raise( if self.memory_monitor is None: return + if not request_id: + import uuid as _uuid + + request_id = f"preflight-{_uuid.uuid4().hex[:8]}" + + capacity = self._capacity_estimate( + context_tokens=num_prompt_tokens, + max_tokens=max_tokens, + ) + if capacity is not None and not capacity.fits_alone: + message = self._never_fits_message(capacity) + logger.warning( + "Preflight rejected, never fits (%d tokens, max_tokens=%d, " + "request_id=%s): %s", + num_prompt_tokens, + capacity.requested_max_tokens, + request_id, + message, + ) + raise ContextExceedsCapacityError( + message=message, + request_id=request_id, + capacity_fields=capacity.fields(), + ) + current = self._current_usage_bytes(refresh_mlx_active=False) est = self._admission_estimate( num_prompt_tokens=num_prompt_tokens, @@ -14022,14 +14365,17 @@ def preflight_or_raise( if est is None: return - if not request_id: - import uuid as _uuid - - request_id = f"preflight-{_uuid.uuid4().hex[:8]}" - + # Fits alone (checked above) and something running or queued will + # free memory: wait instead of rejecting. + fits_later = capacity is not None and ( + self._num_admitted_requests() > 0 or len(self.waiting) > 0 + ) hot_cache_credit = self._releasable_hot_cache_credit(est.kv_exact) admission_limit = self._admission_limit_bytes() if est.estimated - hot_cache_credit > admission_limit: + if fits_later: + self._log_fits_later(request_id, est.estimated, admission_limit) + return message = self._format_rejection_message( estimated=est.estimated, current=current, @@ -14058,6 +14404,13 @@ def preflight_or_raise( ) if safety_rejection is None: return + if fits_later: + self._log_fits_later( + request_id, + safety_rejection.estimated_bytes, + safety_rejection.limit_bytes, + ) + return logger.warning( "Preflight safety-cap rejected (%d tokens, cached=%d, " @@ -14080,6 +14433,7 @@ def preflight_eviction_request( num_prompt_tokens: int, cached_tokens: int = 0, request_id: str | None = None, + max_tokens: int | None = None, ) -> PrefillEvictionRequest | None: """Return an idle-model eviction request for route-level preflight. @@ -14096,6 +14450,13 @@ def preflight_eviction_request( if self.memory_monitor is None: return None + capacity = self._capacity_estimate( + context_tokens=num_prompt_tokens, + max_tokens=max_tokens, + ) + if capacity is not None and not capacity.fits_alone: + return None # evicting cannot help; preflight_or_raise rejects it + current = self._current_usage_bytes(refresh_mlx_active=False) request_id = request_id or "preflight" stale_usage = self.route_preflight_usage_is_stale() @@ -14513,6 +14874,11 @@ def _schedule_waiting_scan( except _PrefillEvictionNeeded as e: self._pause_for_prefill_eviction(request, e.request) break + except _PreflightDeferredError: + # Fits alone but not now: it keeps its place at the head and + # nothing behind it overtakes it while the admitted rows run. + self.waiting.appendleft(request) + break if preflight_rejection is not None: logger.warning( f"Request {request.request_id} rejected by prefill " @@ -14521,6 +14887,15 @@ def _schedule_waiting_scan( self._release_paged_cache_for_request(request.request_id) self.requests.pop(request.request_id, None) self._clear_request_admission_bookkeeping(request.request_id) + if preflight_rejection.capacity is not None: + rejected_outputs.append( + _context_capacity_error_output( + request.request_id, + preflight_rejection.message, + preflight_rejection.capacity, + ) + ) + continue rejected_outputs.append( _prefill_memory_error_output( request.request_id, diff --git a/omlx/server.py b/omlx/server.py index b6c90293c3..9fbf961117 100644 --- a/omlx/server.py +++ b/omlx/server.py @@ -53,9 +53,9 @@ from dataclasses import asdict, dataclass, field from enum import Enum from pathlib import Path -from typing import Optional, Union +from typing import Any, Optional, Union -from fastapi import Depends, FastAPI, HTTPException, Response +from fastapi import Depends, FastAPI, HTTPException, Query, Response from fastapi import Request as FastAPIRequest from fastapi.encoders import jsonable_encoder from fastapi.exceptions import RequestValidationError @@ -209,6 +209,7 @@ ModelLoadingError, ModelNotFoundError, ModelTooLargeError, + ContextExceedsCapacityError, ModelUnavailableError, PrefillMemoryAbortedError, PrefillMemoryExceededError, @@ -1077,6 +1078,10 @@ async def distributed_unavailable_handler( def _prefill_memory_error_detail(exc: PrefillMemoryExceededError) -> str: + if isinstance(exc, ContextExceedsCapacityError): + # Waiting cannot help: the message carries the capacity numbers and + # tells the client to compact, shorten or lower max_tokens. + return f"oMLX memory guard rejected this request: {str(exc)}" if isinstance(exc, PrefillMemoryAbortedError): # This request was admitted and then killed mid-prefill, so "rejected # this prompt" would be wrong. The message already names usage, the @@ -1108,16 +1113,27 @@ def _streaming_error_payload(e: Exception, context: str) -> dict: return {"error": {"message": str(e), "type": "server_error"}} +def _prefill_memory_code(exc: PrefillMemoryExceededError) -> str: + if isinstance(exc, ContextExceedsCapacityError): + return ContextExceedsCapacityError.omlx_code + if isinstance(exc, PrefillMemoryAbortedError): + return "prefill_memory_aborted" + return "prefill_memory_exceeded" + + +def _add_capacity_fields(target: dict, exc: PrefillMemoryExceededError) -> None: + """Never-fits numbers (bytes and tokens) and ``retryable: false``.""" + if isinstance(exc, ContextExceedsCapacityError): + target.update(exc.capacity_fields) + target["retryable"] = False + + def _prefill_memory_openai_error_body( exc: PrefillMemoryExceededError, *, status_code: int = 400, ) -> dict: - code = ( - "prefill_memory_aborted" - if isinstance(exc, PrefillMemoryAbortedError) - else "prefill_memory_exceeded" - ) + code = _prefill_memory_code(exc) content = _openai_error_body( _prefill_memory_error_detail(exc), status_code, @@ -1129,6 +1145,7 @@ def _prefill_memory_openai_error_body( content["error"]["estimated_bytes"] = exc.estimated_bytes if exc.limit_bytes is not None: content["error"]["limit_bytes"] = exc.limit_bytes + _add_capacity_fields(content["error"], exc) return content @@ -1173,12 +1190,17 @@ async def prefill_memory_exceeded_handler( else: content = { "detail": detail, - "omlx_code": "prefill_memory_exceeded", + "omlx_code": ( + ContextExceedsCapacityError.omlx_code + if isinstance(exc, ContextExceedsCapacityError) + else "prefill_memory_exceeded" + ), } if exc.estimated_bytes is not None: content["estimated_bytes"] = exc.estimated_bytes if exc.limit_bytes is not None: content["limit_bytes"] = exc.limit_bytes + _add_capacity_fields(content, exc) return JSONResponse(status_code=status_code, content=content) @@ -3792,6 +3814,77 @@ async def load_model_public(model_id: str, _: bool = Depends(verify_api_key)): return {"status": "ok", "model_id": model_id, "message": f"Loaded {model_id}"} +@app.get("/v1/omlx/capacity") +async def get_model_capacity( + model: str, + context_tokens: int = Query(0, ge=0), + max_tokens: int = Query(0, ge=0), + _: bool = Depends(verify_inference_api_key), +): + """Memory capacity of a loaded model for a request of the given size. + + Returns whether ``context_tokens + max_tokens`` fits with nothing else + running (the never-fits gate's numbers: ``required_bytes``, + ``capacity_bytes``, ``weights_bytes``, ``kv_bytes_per_token``, + ``max_viable_context_tokens``) plus ``free_bytes_now``. Never loads a + model: an unloaded one is a 409. ``available`` is false when the + capacity cannot be estimated (no memory limit, unknown weights), or when + memory scheduling is off (``memory.memory_scheduling``): the endpoint + still answers, with ``memory_scheduling: "off"`` and the reason. + """ + if _server_state.engine_pool is None: + raise HTTPException(status_code=503, detail="Server not initialized") + model_id = resolve_model_id(model) or model + entry = _server_state.engine_pool.get_entry(model_id) + if entry is None: + raise HTTPException(status_code=404, detail=f"Model not found: {model}") + engine = entry.engine + if engine is None: + raise HTTPException(status_code=409, detail=f"Model not loaded: {model}") + snapshot_fn = getattr(engine, "capacity_snapshot", None) + snapshot = ( + snapshot_fn(context_tokens=context_tokens, max_tokens=max_tokens) + if callable(snapshot_fn) + else None + ) + if not isinstance(snapshot, dict): + enforcer = _server_state.process_memory_enforcer + if enforcer is not None and not getattr( + enforcer, "memory_scheduling_enabled", True + ): + reason = getattr(enforcer, "memory_scheduling_reason", "") + return { + "model": model_id, + "available": False, + "memory_scheduling": "off", + "reason": f"memory scheduling is off ({reason})", + } + return { + "model": model_id, + "available": False, + "reason": "capacity cannot be estimated for this model", + } + return {"model": model_id, "available": True, **snapshot} + + +_MAX_CONTEXT_TOKENS_HEADER = "X-oMLX-Max-Context-Tokens" + + +def _capacity_headers(engine: Any) -> dict[str, str]: + """``X-oMLX-Max-Context-Tokens``: the largest context plus max_tokens + that fits alone (cached by the scheduler); empty when unknown.""" + hint_fn = getattr(engine, "max_context_tokens_hint", None) + if not callable(hint_fn): + return {} + try: + hint = hint_fn() + except Exception: # noqa: BLE001 - a hint must never fail a request + return {} + if isinstance(hint, bool) or not isinstance(hint, int) or hint < 0: + return {} + return {_MAX_CONTEXT_TOKENS_HEADER: str(hint)} + + # ============================================================================= # Embeddings Endpoint # ============================================================================= @@ -4819,6 +4912,7 @@ async def create_chat_completion( sse_headers = {"X-Accel-Buffering": "no", "Cache-Control": "no-cache"} if response_format_warning: sse_headers["Warning"] = response_format_warning + sse_headers.update(_capacity_headers(engine)) return StreamingResponse( _release_after_stream( _with_request_disconnect_abort( @@ -4990,10 +5084,14 @@ async def _build_chat_completion(): ).model_dump_json(exclude_none=True) json_headers = ( - {"Warning": response_format_warning} if response_format_warning else None + {"Warning": response_format_warning} if response_format_warning else {} ) + json_headers.update(_capacity_headers(engine)) return await _json_response_or_keepalive( - http_request, _build_chat_completion(), lease=lease, headers=json_headers + http_request, + _build_chat_completion(), + lease=lease, + headers=json_headers or None, ) except BaseException: diff --git a/tests/test_memory_scheduling_gate.py b/tests/test_memory_scheduling_gate.py index fe1e345052..657b371a1e 100644 --- a/tests/test_memory_scheduling_gate.py +++ b/tests/test_memory_scheduling_gate.py @@ -2,10 +2,15 @@ """Memory scheduling is on only where memory pressure is planned for. ``memory.memory_scheduling`` is ``auto`` (default: on with an explicit custom -ceiling), ``on`` or ``off``. The process memory enforcer resolves it against -the prefill memory guard and the ceiling, logs the result and propagates it to -every scheduler. The admission features that plan against a fixed memory -budget consult it; off, admission behaves as on upstream ``main``. +ceiling), ``on`` or ``off``. It gates the admission behaviours that plan +against a fixed memory budget: + +1. the never-fits 400 ``context_exceeds_capacity``, ``GET /v1/omlx/capacity`` + numbers and the ``X-oMLX-Max-Context-Tokens`` header; +2. the fits-later wait (a request that fits alone waits instead of being + rejected on current usage). + +Off, these paths behave as on upstream ``main``. """ import logging @@ -13,17 +18,25 @@ import pytest import test_process_memory_enforcer as enforcer_tests +import test_scheduler_capacity_gate as gate_tests +import test_server_context_capacity as server_tests +from fastapi.testclient import TestClient from test_process_memory_enforcer import _make_enforcer -from test_scheduler_prefill_memory_guard import _make_scheduler +from test_scheduler_capacity_gate import GB +from test_scheduler_prefill_memory_guard import _make_request, _make_scheduler +from test_server_context_capacity import _engine_with_scheduler +import omlx.scheduler as scheduler_module import omlx.server as server +from omlx.exceptions import ContextExceedsCapacityError, PrefillMemoryExceededError from omlx.process_memory_enforcer import resolve_memory_scheduling from omlx.settings import GlobalSettings, MemorySettings -GB = 1024**3 - -# Shared fixtures: an enforcer's engine pool. +# Shared fixtures: an enforcer's engine pool, a guarded scheduler and the +# capacity endpoint's engine pool. mock_engine_pool = enforcer_tests.mock_engine_pool +gated = gate_tests.gated +capacity_env = server_tests.capacity_env # --- Resolution ------------------------------------------------------------- @@ -212,6 +225,84 @@ def test_the_enforcer_propagates_the_state_to_schedulers( assert scheduler._memory_scheduling is False +# --- Off: these paths behave as on main -------------------------------------- + + +def test_off_has_no_capacity_estimate_snapshot_or_hint(gated): + scheduler, _usage, _admitted = gated + scheduler._memory_scheduling = True + assert scheduler.max_viable_context_tokens() is not None + scheduler._memory_scheduling = False + assert scheduler._capacity_estimate(context_tokens=10, max_tokens=0) is None + assert scheduler.capacity_snapshot(context_tokens=10, max_tokens=0) is None + # Off after on: the cached hint is not served either. + assert scheduler.max_viable_context_tokens() is None + assert _engine_with_scheduler(scheduler).max_context_tokens_hint() is None + + +def test_off_prices_only_the_prompt_against_current_usage(gated): + """A request whose max_tokens can never fit passes the route preflight on + main when its prompt fits now; only on gives the never-fits 400.""" + scheduler, usage, _admitted = gated + scheduler._memory_scheduling = True + best = scheduler.max_viable_context_tokens() + with pytest.raises(ContextExceedsCapacityError): + scheduler.preflight_or_raise(num_prompt_tokens=best - 10_000, max_tokens=20_000) + scheduler._memory_scheduling = False + usage[0] = 0 + scheduler.preflight_or_raise(num_prompt_tokens=best - 10_000, max_tokens=20_000) + + +def test_off_rejects_a_fits_later_request_with_the_old_error(gated): + scheduler, usage, admitted = gated + usage[0] = 99 * GB + admitted[0] = 2 + scheduler._memory_scheduling = True + scheduler.preflight_or_raise(num_prompt_tokens=50_000, max_tokens=1_000) + request = _make_request(50_000) + with pytest.raises(scheduler_module._PreflightDeferredError): + scheduler._preflight_memory_check(request) + + scheduler._memory_scheduling = False + with pytest.raises(PrefillMemoryExceededError) as info: + scheduler.preflight_or_raise(num_prompt_tokens=50_000, max_tokens=1_000) + assert not isinstance(info.value, ContextExceedsCapacityError) + assert "Prefill would require" in str(info.value) + rejection = scheduler._preflight_memory_check(request) + assert rejection is not None + assert rejection.capacity is None # the old current-usage rejection + assert rejection.message.startswith("Prefill would require") + + +def test_off_endpoint_says_why_capacity_is_unavailable( + capacity_env, + monkeypatch, +): + engine, _snapshot = capacity_env + engine.capacity_snapshot.return_value = None + monkeypatch.setattr( + server._server_state, + "process_memory_enforcer", + SimpleNamespace( + memory_scheduling_enabled=False, + memory_scheduling_reason="no explicit memory ceiling", + ), + ) + client = TestClient(server.app) + resp = client.get("/v1/omlx/capacity", params={"model": "loaded-model"}) + assert resp.status_code == 200 + body = resp.json() + assert body["available"] is False + assert body["memory_scheduling"] == "off" + assert body["reason"] == "memory scheduling is off (no explicit memory ceiling)" + # Unknown and unloaded models keep their 404 and 409. + assert client.get("/v1/omlx/capacity", params={"model": "nope"}).status_code == 404 + assert ( + client.get("/v1/omlx/capacity", params={"model": "cold-model"}).status_code + == 409 + ) + + # --- Admin settings ----------------------------------------------------------- diff --git a/tests/test_scheduler_capacity_gate.py b/tests/test_scheduler_capacity_gate.py new file mode 100644 index 0000000000..69b692897a --- /dev/null +++ b/tests/test_scheduler_capacity_gate.py @@ -0,0 +1,357 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Never-fits feasibility gate and capacity hint. + +The preflight used to compare a request against CURRENT usage, so a request +that would fit once the running ones finish was rejected. The decision is now +split: a request that cannot fit even alone (weights + KV of context plus +max_tokens + transient over the capacity line) is rejected with a structured +``context_exceeds_capacity`` error; one that fits alone but not now waits. +""" + +import pytest +from test_scheduler_park import ( + PROMPT_A, + PROMPT_C, + make_rig, + step, + step_until, + submit, + waiting_ids, +) +from test_scheduler_prefill_memory_guard import _make_request, _make_scheduler + +import omlx.scheduler as scheduler_module +from omlx.engine_core import _raise_request_output_error +from omlx.exceptions import ContextExceedsCapacityError, PrefillMemoryExceededError +from omlx.request import RequestOutput + +GB = 1024**3 + +CAPACITY_FIELDS = { + "required_bytes", + "capacity_bytes", + "weights_bytes", + "kv_bytes_per_token", + "requested_context_tokens", + "requested_max_tokens", + "max_viable_context_tokens", +} + + +@pytest.fixture +def gated(monkeypatch): + """Guard on, a 100 GB hard limit, 20 GB of weights; ``usage[0]`` and + ``admitted[0]`` are the current usage and admitted rows it reads.""" + scheduler = _make_scheduler() + scheduler._prefill_memory_guard = True + scheduler._memory_scheduling = True # memory.memory_scheduling resolved on + scheduler._memory_hard_limit_bytes = 100 * GB + scheduler._weights_bytes = 20 * GB + usage = [0] + admitted = [0] + monkeypatch.setattr(scheduler, "_current_usage_bytes", lambda **_kw: usage[0]) + monkeypatch.setattr(scheduler, "_num_admitted_requests", lambda: admitted[0]) + return scheduler, usage, admitted + + +def _required(scheduler, tokens): + est = scheduler._admission_estimate( + num_prompt_tokens=tokens, + cached_tokens=0, + current=scheduler._model_weights_bytes(), + ) + return est.estimated + + +# --- Math ----------------------------------------------------------------- + + +def test_capacity_is_the_tighter_of_admission_line_and_safety_cap(gated): + scheduler, _usage, _admitted = gated + expected = min(scheduler._admission_limit_bytes(), scheduler._prefill_abort_cap()) + assert scheduler._capacity_limit_bytes() == expected > 0 + + +def test_required_is_weights_plus_kv_of_context_and_max_tokens_plus_transient( + gated, +): + scheduler, _usage, _admitted = gated + cap = scheduler._capacity_estimate(context_tokens=30_000, max_tokens=2_000) + monitor = scheduler.memory_monitor + est = scheduler._admission_estimate( + num_prompt_tokens=32_000, cached_tokens=0, current=0 + ) + assert est.kv_exact == int( + monitor.estimate_resident_kv_bytes(32_000, chunk_tokens=est.floor_chunk) + ) + assert cap.required_bytes == 20 * GB + est.kv_exact + est.transient + assert cap.weights_bytes == 20 * GB + assert cap.capacity_bytes == scheduler._capacity_limit_bytes() + assert cap.requested_context_tokens == 30_000 + assert cap.requested_max_tokens == 2_000 + # 32 layers x 8 KV heads x head_dim 192 x 2 bytes x (K + V) + assert cap.kv_bytes_per_token == 32 * 8 * 192 * 2 * 2 + assert cap.fits_alone + + +def test_max_viable_context_is_the_largest_total_that_fits_alone(gated): + scheduler, _usage, _admitted = gated + cap = scheduler._capacity_estimate(context_tokens=0, max_tokens=0) + best = cap.max_viable_context_tokens + assert best > 1000 + assert _required(scheduler, best) <= cap.capacity_bytes + assert _required(scheduler, best + 1) > cap.capacity_bytes + + +def test_weights_over_capacity_leave_no_viable_context(gated): + scheduler, _usage, _admitted = gated + scheduler._weights_bytes = 200 * GB + cap = scheduler._capacity_estimate(context_tokens=10, max_tokens=0) + assert cap.max_viable_context_tokens == 0 + assert not cap.fits_alone + + +def test_capacity_is_unavailable_without_weights_or_a_limit(gated): + scheduler, _usage, _admitted = gated + scheduler._weights_bytes = None + assert scheduler._model_weights_bytes() == 0 # MagicMock model: unknown + assert scheduler._capacity_estimate(context_tokens=10, max_tokens=0) is None + scheduler._weights_bytes = 20 * GB + scheduler._memory_hard_limit_bytes = 0 + assert scheduler._capacity_estimate(context_tokens=10, max_tokens=0) is None + + +def test_weights_are_read_from_the_model_parameters(): + import mlx.core as mx + import mlx.nn as nn + + scheduler = _make_scheduler() + scheduler.model = nn.Linear(64, 32) + mx.eval(scheduler.model.parameters()) + expected = 64 * 32 * 4 + 32 * 4 # fp32 weight and bias + scheduler._weights_bytes = None + assert scheduler._model_weights_bytes() == expected + + +def test_capacity_snapshot_adds_free_bytes_now(gated): + scheduler, usage, _admitted = gated + usage[0] = 30 * GB + snap = scheduler.capacity_snapshot(context_tokens=1000, max_tokens=100) + assert set(snap) >= CAPACITY_FIELDS + assert snap["free_bytes_now"] == snap["capacity_bytes"] - 30 * GB + assert scheduler.max_viable_context_tokens() == snap["max_viable_context_tokens"] + + +def test_max_viable_context_is_cached(gated, monkeypatch): + scheduler, _usage, _admitted = gated + first = scheduler.max_viable_context_tokens() + calls = [] + real = scheduler._admission_estimate + monkeypatch.setattr( + scheduler, + "_admission_estimate", + lambda **kw: calls.append(kw) or real(**kw), + ) + assert scheduler.max_viable_context_tokens() == first + assert calls == [] + + +# --- Route preflight ------------------------------------------------------------ + + +def test_never_fits_alone_is_rejected_with_the_capacity_numbers(gated): + scheduler, _usage, _admitted = gated + best = scheduler.max_viable_context_tokens() + with pytest.raises(ContextExceedsCapacityError) as info: + scheduler.preflight_or_raise( + num_prompt_tokens=best, max_tokens=4096, request_id="huge" + ) + exc = info.value + assert isinstance(exc, PrefillMemoryExceededError) # same HTTP 400 mapping + assert exc.request_id == "huge" + assert set(exc.capacity_fields) >= CAPACITY_FIELDS + assert exc.capacity_fields["requested_context_tokens"] == best + assert exc.capacity_fields["requested_max_tokens"] == 4096 + assert exc.capacity_fields["max_viable_context_tokens"] == best + assert exc.estimated_bytes == exc.capacity_fields["required_bytes"] + assert exc.limit_bytes == exc.capacity_fields["capacity_bytes"] + assert exc.estimated_bytes > exc.limit_bytes + assert "compact or shorten the context" in str(exc).lower() + + +def test_never_fits_is_checked_even_when_nothing_else_uses_memory(gated): + """Current usage is irrelevant: a request that could start now but whose + max_tokens cannot fit would otherwise be paused and never resumed.""" + scheduler, usage, _admitted = gated + usage[0] = 0 + best = scheduler.max_viable_context_tokens() + scheduler.preflight_or_raise(num_prompt_tokens=best - 10_000, max_tokens=0) + with pytest.raises(ContextExceedsCapacityError): + scheduler.preflight_or_raise(num_prompt_tokens=best - 10_000, max_tokens=20_000) + + +def test_fits_alone_but_not_now_waits_while_other_work_runs(gated): + scheduler, usage, admitted = gated + usage[0] = 99 * GB # almost everything is taken by running requests + admitted[0] = 2 + scheduler.preflight_or_raise(num_prompt_tokens=50_000, max_tokens=1_000) + + +def test_fits_alone_but_not_now_on_an_idle_scheduler_keeps_the_old_rejection(gated): + """Nothing running will free the memory, so waiting cannot help.""" + scheduler, usage, admitted = gated + usage[0] = 99 * GB + admitted[0] = 0 + with pytest.raises(PrefillMemoryExceededError) as info: + scheduler.preflight_or_raise(num_prompt_tokens=50_000, max_tokens=1_000) + assert not isinstance(info.value, ContextExceedsCapacityError) + + +def test_unknown_capacity_keeps_the_old_rejection(gated): + scheduler, usage, admitted = gated + scheduler._weights_bytes = None # MagicMock model: weights unknown + usage[0] = 99 * GB + admitted[0] = 2 + with pytest.raises(PrefillMemoryExceededError) as info: + scheduler.preflight_or_raise(num_prompt_tokens=50_000, max_tokens=1_000) + assert not isinstance(info.value, ContextExceedsCapacityError) + + +def test_a_never_fits_request_does_not_ask_for_an_eviction(gated): + scheduler, usage, _admitted = gated + usage[0] = 99 * GB + best = scheduler.max_viable_context_tokens() + assert ( + scheduler.preflight_eviction_request(num_prompt_tokens=best + 1, max_tokens=0) + is None + ) + assert ( + scheduler.preflight_eviction_request(num_prompt_tokens=50_000, max_tokens=0) + is not None + ) + + +# --- In-stream admission -------------------------------------------------------- + + +def test_in_stream_never_fits_returns_a_rejection_carrying_the_capacity(gated): + scheduler, _usage, _admitted = gated + best = scheduler.max_viable_context_tokens() + request = _make_request(best) + request.sampling_params.max_tokens = 100 + rejection = scheduler._preflight_memory_check(request) + assert rejection is not None + assert rejection.capacity is not None + assert not rejection.capacity.fits_alone + + +def test_in_stream_fits_later_defers_while_rows_are_admitted(gated): + scheduler, usage, admitted = gated + usage[0] = 99 * GB + admitted[0] = 1 + request = _make_request(50_000) + with pytest.raises(scheduler_module._PreflightDeferredError): + scheduler._preflight_memory_check(request) + admitted[0] = 0 + rejection = scheduler._preflight_memory_check(request) + assert rejection is not None and rejection.capacity is None + + +def test_engine_core_maps_the_output_to_the_typed_error(): + fields = { + "required_bytes": 9, + "capacity_bytes": 8, + "weights_bytes": 5, + "kv_bytes_per_token": 1, + "requested_context_tokens": 3, + "requested_max_tokens": 1, + "max_viable_context_tokens": 2, + } + output = RequestOutput( + request_id="r", + finished=True, + finish_reason="error", + error="does not fit", + error_code="context_exceeds_capacity", + error_metadata={"request_id": "r", **fields}, + ) + with pytest.raises(ContextExceedsCapacityError) as info: + _raise_request_output_error(output) + assert info.value.capacity_fields == fields + assert info.value.request_id == "r" + + +# --- Real scheduler loop ---------------------------------------------------------- + + +def _guarded_rig(tmp_path, tokenizer, monkeypatch, *, weights_gb, free_gb): + rig = make_rig(tmp_path, tokenizer) + scheduler = rig.scheduler + scheduler._memory_scheduling = True # memory.memory_scheduling resolved on + scheduler._memory_hard_limit_bytes = 100 * GB + scheduler._weights_bytes = weights_gb * GB + usage = [scheduler._admission_limit_bytes() - free_gb * GB] + monkeypatch.setattr(scheduler, "_current_usage_bytes", lambda **_kw: usage[0]) + return rig, usage + + +def test_a_request_that_fits_later_waits_in_line_without_an_error( + tmp_path, mock_tokenizer, monkeypatch +): + rig, usage = _guarded_rig( + tmp_path, mock_tokenizer, monkeypatch, weights_gb=20, free_gb=50 + ) + try: + scheduler = rig.scheduler + scheduler._prefill_memory_guard = True + # Rows that hold the memory are admitted (the tiny model would end a + # real one at EOS within a few steps); there is no room right now. + admitted = [1] + monkeypatch.setattr(scheduler, "_num_admitted_requests", lambda: admitted[0]) + usage[0] = scheduler._admission_limit_bytes() + later = submit(rig, "later", PROMPT_C, arrival=1.0) + newer = submit(rig, "newer", PROMPT_A, arrival=2.0) + outputs = step(rig, 4) + assert not [o for o in outputs if o.error] + # It keeps its place and nothing behind it overtakes it. + assert waiting_ids(rig) == ["later", "newer"] + assert "later" in scheduler.requests + + # The admitted rows finish and their memory comes back. + monkeypatch.setattr( + scheduler, + "_num_admitted_requests", + lambda: len(scheduler.running) + len(scheduler.prefilling), + ) + usage[0] = scheduler._admission_limit_bytes() - 50 * GB + step_until( + rig, + lambda: "later" not in waiting_ids(rig) and "newer" not in waiting_ids(rig), + ) + assert later.finish_reason != "error" + assert newer.finish_reason != "error" + finally: + rig.close() + + +def test_a_request_that_never_fits_ends_with_the_structured_error( + tmp_path, mock_tokenizer, monkeypatch +): + rig, _usage = _guarded_rig( + tmp_path, mock_tokenizer, monkeypatch, weights_gb=200, free_gb=50 + ) + try: + scheduler = rig.scheduler + scheduler._prefill_memory_guard = True + submit(rig, "big", PROMPT_C, arrival=1.0, max_tokens=7) + outputs = step(rig, 2) + errors = [o for o in outputs if o.request_id == "big" and o.error] + assert len(errors) == 1 + assert errors[0].error_code == "context_exceeds_capacity" + meta = errors[0].error_metadata + assert set(meta) >= CAPACITY_FIELDS + assert meta["requested_max_tokens"] == 7 + assert meta["weights_bytes"] == 200 * GB + assert "big" not in scheduler.requests + finally: + rig.close() diff --git a/tests/test_server_context_capacity.py b/tests/test_server_context_capacity.py new file mode 100644 index 0000000000..1abc059782 --- /dev/null +++ b/tests/test_server_context_capacity.py @@ -0,0 +1,265 @@ +# SPDX-License-Identifier: Apache-2.0 +"""HTTP surface of the never-fits gate: the 400 body, the capacity endpoint +and the ``X-oMLX-Max-Context-Tokens`` header.""" + +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +import omlx.server as server +from omlx.engine.base import BaseEngine, GenerationOutput +from omlx.exceptions import ContextExceedsCapacityError, PrefillMemoryExceededError + +FIELDS = { + "required_bytes": 140_000_000_000, + "capacity_bytes": 96_000_000_000, + "weights_bytes": 28_000_000_000, + "kv_bytes_per_token": 65_536, + "requested_context_tokens": 1_200_000, + "requested_max_tokens": 32_768, + "max_viable_context_tokens": 1_036_000, +} + + +def _never_fits(): + return ContextExceedsCapacityError( + message="Request needs ~130.4 GB but capacity is 89.4 GB.", + request_id="req-huge", + capacity_fields=dict(FIELDS), + ) + + +# --- 400 body --------------------------------------------------------------------- + + +def _handler_app(): + app = FastAPI() + app.add_exception_handler( + PrefillMemoryExceededError, server.prefill_memory_exceeded_handler + ) + + @app.get("/v1/raise") + def raise_api(): + raise _never_fits() + + @app.get("/health/raise") + def raise_other(): + raise _never_fits() + + return app + + +def test_never_fits_maps_to_400_with_the_existing_envelope_and_capacity_fields(): + with TestClient(_handler_app()) as client: + resp = client.get("/v1/raise") + assert resp.status_code == 400 + body = resp.json() + assert body["type"] == "error" + error = body["error"] + # Existing envelope, unchanged for clients that already parse it. + assert error["type"] == "invalid_request_error" + assert error["param"] is None + assert "Request needs ~130.4 GB" in error["message"] + assert error["estimated_bytes"] == FIELDS["required_bytes"] + assert error["limit_bytes"] == FIELDS["capacity_bytes"] + # New classification and numbers. + assert error["code"] == "context_exceeds_capacity" + assert error["omlx_code"] == "context_exceeds_capacity" + for name, value in FIELDS.items(): + assert error[name] == value + assert error["retryable"] is False + + +def test_non_api_routes_carry_the_same_fields(): + with TestClient(_handler_app()) as client: + resp = client.get("/health/raise") + assert resp.status_code == 400 + body = resp.json() + assert body["omlx_code"] == "context_exceeds_capacity" + assert body["retryable"] is False + for name, value in FIELDS.items(): + assert body[name] == value + + +def test_streaming_error_payload_keeps_the_capacity_fields(): + body = server._streaming_error_payload(_never_fits(), "chat") + assert body["error"]["omlx_code"] == "context_exceeds_capacity" + assert body["error"]["max_viable_context_tokens"] == 1_036_000 + + +# --- Engine hooks ------------------------------------------------------------------- + + +def _engine_with_scheduler(scheduler): + engine = MagicMock(spec=BaseEngine) + engine._engine = SimpleNamespace(engine=SimpleNamespace(scheduler=scheduler)) + engine._capacity_scheduler = BaseEngine._capacity_scheduler.__get__(engine) + engine.capacity_snapshot = BaseEngine.capacity_snapshot.__get__(engine) + engine.max_context_tokens_hint = BaseEngine.max_context_tokens_hint.__get__(engine) + return engine + + +def test_base_engine_reads_the_scheduler_and_ignores_non_numbers(): + scheduler = SimpleNamespace( + capacity_snapshot=lambda **kw: {"free_bytes_now": 1, **kw}, + max_viable_context_tokens=lambda: 4096, + ) + engine = _engine_with_scheduler(scheduler) + assert engine.capacity_snapshot(context_tokens=5, max_tokens=6) == { + "free_bytes_now": 1, + "context_tokens": 5, + "max_tokens": 6, + } + assert engine.max_context_tokens_hint() == 4096 + + broken = _engine_with_scheduler(MagicMock()) + assert broken.capacity_snapshot() is None + assert broken.max_context_tokens_hint() is None + assert _engine_with_scheduler(None).max_context_tokens_hint() is None + + +# --- Capacity endpoint ----------------------------------------------------------- + + +@pytest.fixture +def capacity_env(monkeypatch): + snapshot = {**FIELDS, "free_bytes_now": 12_000_000_000} + engine = MagicMock() + engine.capacity_snapshot = MagicMock(return_value=snapshot) + entries = { + "loaded-model": SimpleNamespace(engine=engine), + "cold-model": SimpleNamespace(engine=None), + } + pool = MagicMock() + pool.get_entry = MagicMock(side_effect=entries.get) + monkeypatch.setattr(server._server_state, "engine_pool", pool) + monkeypatch.setattr(server, "resolve_model_id", lambda name: name) + monkeypatch.setattr(server._server_state, "api_key", None) + monkeypatch.setattr(server._server_state, "global_settings", None) + return engine, snapshot + + +def test_capacity_endpoint_returns_the_numbers_and_free_bytes(capacity_env): + engine, snapshot = capacity_env + client = TestClient(server.app) + resp = client.get( + "/v1/omlx/capacity", + params={"model": "loaded-model", "context_tokens": 1000, "max_tokens": 50}, + ) + assert resp.status_code == 200 + body = resp.json() + assert body["model"] == "loaded-model" + assert body["available"] is True + for name, value in snapshot.items(): + assert body[name] == value + engine.capacity_snapshot.assert_called_once_with(context_tokens=1000, max_tokens=50) + + +def test_capacity_endpoint_unknown_cold_and_unavailable(capacity_env): + engine, _snapshot = capacity_env + client = TestClient(server.app) + assert client.get("/v1/omlx/capacity", params={"model": "nope"}).status_code == 404 + assert ( + client.get("/v1/omlx/capacity", params={"model": "cold-model"}).status_code + == 409 + ) + engine.capacity_snapshot.return_value = None + resp = client.get("/v1/omlx/capacity", params={"model": "loaded-model"}) + assert resp.status_code == 200 + assert resp.json()["available"] is False + + +def test_capacity_endpoint_requires_the_api_key(capacity_env, monkeypatch): + monkeypatch.setattr(server._server_state, "api_key", "secret-key") + monkeypatch.setattr(server, "allows_unauthenticated_inference", lambda: False) + client = TestClient(server.app) + params = {"model": "loaded-model"} + assert client.get("/v1/omlx/capacity", params=params).status_code == 401 + resp = client.get( + "/v1/omlx/capacity", + params=params, + headers={"Authorization": "Bearer secret-key"}, + ) + assert resp.status_code == 200 + + +# --- Header on chat completions ------------------------------------------------- + + +def _chat_env(monkeypatch, hint): + from omlx.engine.vlm import VLMBatchedEngine + + engine = MagicMock(spec=VLMBatchedEngine) + engine.tokenizer = SimpleNamespace( + encode=lambda t, **kw: t.split(), tool_call_start=None, tool_call_end=None + ) + engine.start = AsyncMock() + engine.preflight_chat = AsyncMock() + engine.count_chat_tokens = MagicMock(return_value=10) + engine.chat = AsyncMock( + return_value=GenerationOutput( + text="hello", prompt_tokens=3, completion_tokens=1, finish_reason="stop" + ) + ) + engine.is_diffusion_model = False + engine.message_extractor = None + engine.supports_multimodal_fallback = False + engine.max_context_tokens_hint = MagicMock(return_value=hint) + + async def _get_engine(model_id, *, lease=None): + return engine + + pool = MagicMock() + pool.get_entry = MagicMock( + return_value=SimpleNamespace(preserve_thinking_default=False) + ) + monkeypatch.setattr(server, "get_engine_for_model", _get_engine) + monkeypatch.setattr(server, "resolve_model_id", lambda name: name) + monkeypatch.setattr(server, "validate_context_window", lambda *a, **k: None) + monkeypatch.setattr(server, "get_engine_pool", lambda: pool) + monkeypatch.setitem( + server.app.dependency_overrides, server.verify_inference_api_key, lambda: True + ) + return engine + + +def _chat(client): + return client.post( + "/v1/chat/completions", + json={ + "model": "m", + "stream": False, + "messages": [{"role": "user", "content": "hi"}], + }, + ) + + +def test_chat_completion_carries_the_max_context_header(monkeypatch): + _chat_env(monkeypatch, hint=123_456) + resp = _chat(TestClient(server.app)) + assert resp.status_code == 200 + assert resp.headers["X-oMLX-Max-Context-Tokens"] == "123456" + + +def test_chat_completion_omits_the_header_without_an_estimate(monkeypatch): + _chat_env(monkeypatch, hint=None) + resp = _chat(TestClient(server.app)) + assert resp.status_code == 200 + assert "X-oMLX-Max-Context-Tokens" not in resp.headers + + +def test_streaming_chat_completion_carries_the_max_context_header(monkeypatch): + _chat_env(monkeypatch, hint=65_536) + client = TestClient(server.app, raise_server_exceptions=False) + resp = client.post( + "/v1/chat/completions", + json={ + "model": "m", + "stream": True, + "messages": [{"role": "user", "content": "hi"}], + }, + ) + assert resp.headers["X-oMLX-Max-Context-Tokens"] == "65536" From fe598232a177b5217e1d3bfb08d19e1cd6843227 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Mon, 5 Oct 2026 16:07:46 -0600 Subject: [PATCH 29/46] fix(memory): align the never-fits route and in-stream checks Four fixes to the capacity gate: - The route preflight priced an omitted max_tokens as 0 output tokens while the in-stream check used the resolved value. The completion route now resolves max_tokens before its preflight, and engine preflights fall back to the engine default (ENGINE_DEFAULT_MAX_TOKENS) a direct call runs with. - The route preflight let a request wait whenever anything was queued. Both checks now share one predicate: fits later only while admitted rows hold memory that comes back. - A deferred request kept its restored prefix and block-table refs while it waited. The defer path now releases them (PagedCacheManager release_block_table keeps the blocks findable) and the re-admission repeats the lookup. - Unknown weights fell back to the monitor's process baseline and were cached for good. Unknown weights now mean no estimate, are never cached, and never reject as never-fits. --- docs/TESTING.md | 2 +- omlx/cache/paged_cache.py | 12 ++ omlx/engine/base.py | 21 ++- omlx/engine/batched.py | 14 +- omlx/engine/vlm.py | 14 +- omlx/scheduler.py | 60 ++++++-- omlx/server.py | 14 +- tests/test_batched_engine.py | 8 +- tests/test_scheduler_capacity_gate.py | 207 ++++++++++++++++++++++++++ 9 files changed, 317 insertions(+), 35 deletions(-) diff --git a/docs/TESTING.md b/docs/TESTING.md index c66f1e6814..bf1bc01600 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -243,7 +243,7 @@ Run `python -m pytest -q tests/test_memory_scheduling_admin_state.py` to check m # Never-fits gate tests -Run `python -m pytest -q tests/test_scheduler_capacity_gate.py tests/test_server_context_capacity.py` to check the feasibility gate. A request whose weights + exact KV of prompt plus `max_tokens` + prefill transient exceed the capacity line (the tighter of the admission line and the prefill safety cap) is rejected with `ContextExceedsCapacityError` (HTTP 400, `omlx_code: context_exceeds_capacity`, the byte and token fields, `retryable: false`) whatever the current usage. One that fits alone but not now is not rejected: the route preflight lets it queue while other work is admitted or queued, and the in-stream admission keeps it at the head (nothing overtakes it) until the admitted rows free memory. With nothing admitted, or when the capacity cannot be estimated (no memory limit, unknown weights or KV dimensions), the older current-usage rejection applies. The server cases cover the 400 body on API and non-API routes, `GET /v1/omlx/capacity` (fields, 404/409, auth) and the `X-oMLX-Max-Context-Tokens` header on streaming and non-streaming chat completions. These cases run with memory scheduling on (see the memory scheduling gate tests above); off, there is no capacity estimate and the older current-usage rejection applies. +Run `python -m pytest -q tests/test_scheduler_capacity_gate.py tests/test_server_context_capacity.py` to check the feasibility gate. A request whose weights + exact KV of prompt plus `max_tokens` + prefill transient exceed the capacity line (the tighter of the admission line and the prefill safety cap) is rejected with `ContextExceedsCapacityError` (HTTP 400, `omlx_code: context_exceeds_capacity`, the byte and token fields, `retryable: false`) whatever the current usage. One that fits alone but not now is not rejected: the route preflight lets it queue while other work is admitted (queued requests hold no memory and do not count), and the in-stream admission keeps it at the head (nothing overtakes it) until the admitted rows free memory; both checks share one predicate. A deferred request releases its restored prefix and its block-table refs while it waits, and its re-admission repeats the lookup. Both checks price the same output budget: the route preflight uses the resolved `max_tokens` (request, model setting or server default; the engine default when an engine is called directly). With nothing admitted, or when the capacity cannot be estimated (no memory limit, unknown weights or KV dimensions), the older current-usage rejection applies; unknown weights are never cached and never produce a never-fits rejection. The server cases cover the 400 body on API and non-API routes, `GET /v1/omlx/capacity` (fields, 404/409, auth) and the `X-oMLX-Max-Context-Tokens` header on streaming and non-streaming chat completions. These cases run with memory scheduling on (see the memory scheduling gate tests above); off, there is no capacity estimate and the older current-usage rejection applies. Mocked tests do not replace hardware validation: with a real model, send a prompt larger than `max_viable_context_tokens` and check for an immediate 400 with the fields, then send two prompts that each fit alone but not together and check that the second waits and completes without an error. diff --git a/omlx/cache/paged_cache.py b/omlx/cache/paged_cache.py index dfa83ad944..062f579f07 100644 --- a/omlx/cache/paged_cache.py +++ b/omlx/cache/paged_cache.py @@ -1298,6 +1298,18 @@ def delete_block_table(self, request_id: str) -> None: for block_id in table.block_ids: self.free_block(block_id) + def release_block_table(self, request_id: str) -> None: + """Drop a request's block table without freeing its blocks. + + Its references are released for eviction (``release_for_eviction``), + so the blocks stay cached and findable by later prefix lookups, as + after a completed request's store. + """ + with self._lock: + table = self.request_tables.pop(request_id, None) + if table: + self.release_for_eviction(table.block_ids) + def add_block_to_table( self, table: BlockTable, diff --git a/omlx/engine/base.py b/omlx/engine/base.py index 0101122148..0151e05e19 100644 --- a/omlx/engine/base.py +++ b/omlx/engine/base.py @@ -19,9 +19,22 @@ logger = logging.getLogger(__name__) _preflight_logger = logging.getLogger("omlx.engine.preflight") +# Output budget an engine call runs with when the caller omits max_tokens. +# The route preflight prices the same value, so the never-fits gate and the +# in-stream admission agree on a request's output tokens. +ENGINE_DEFAULT_MAX_TOKENS = 256 + _PREFLIGHT_CLEANUP_WAIT_TIMEOUT_S = 4.0 _PREFLIGHT_CLEANUP_POLL_INTERVAL_S = 0.05 + +def preflight_max_tokens(kwargs: dict[str, Any]) -> int: + """The max_tokens a route preflight prices: the caller's resolved value, + else the engine default the request itself will run with.""" + value = kwargs.get("max_tokens") + return ENGINE_DEFAULT_MAX_TOKENS if value is None else int(value) + + # Per-process record of (engine_class_name, method) pairs that have # already logged a "scheduler unreachable" warning. The warning marks a # wrapper-chain misconfiguration — a deployment bug rather than a @@ -345,7 +358,7 @@ async def stop(self) -> None: async def generate( self, prompt: str | list[int], - max_tokens: int = 256, + max_tokens: int = ENGINE_DEFAULT_MAX_TOKENS, temperature: float = 0.7, top_p: float = 0.9, top_k: int = 0, @@ -377,7 +390,7 @@ async def generate( async def stream_generate( self, prompt: str | list[int], - max_tokens: int = 256, + max_tokens: int = ENGINE_DEFAULT_MAX_TOKENS, temperature: float = 0.7, top_p: float = 0.9, top_k: int = 0, @@ -409,7 +422,7 @@ async def stream_generate( async def chat( self, messages: List[Dict[str, Any]], - max_tokens: int = 256, + max_tokens: int = ENGINE_DEFAULT_MAX_TOKENS, temperature: float = 0.7, top_p: float = 0.9, top_k: int = 0, @@ -441,7 +454,7 @@ async def chat( async def stream_chat( self, messages: List[Dict[str, Any]], - max_tokens: int = 256, + max_tokens: int = ENGINE_DEFAULT_MAX_TOKENS, temperature: float = 0.7, top_p: float = 0.9, top_k: int = 0, diff --git a/omlx/engine/batched.py b/omlx/engine/batched.py index a53b71b65a..07dd07ea81 100644 --- a/omlx/engine/batched.py +++ b/omlx/engine/batched.py @@ -23,12 +23,14 @@ from ..reasoning_effort import apply_chat_template_with_reasoning_effort_fallback from ..utils.tokenizer import get_tokenizer_config from .base import ( + ENGINE_DEFAULT_MAX_TOKENS, BaseEngine, GenerationOutput, _clear_teardown_references, _close_engine_core, _run_scheduler_preflight_with_cleanup_retry, _warn_scheduler_unreachable_once, + preflight_max_tokens, ) logger = logging.getLogger(__name__) @@ -1089,7 +1091,7 @@ def _prepare_k2_tool_grammar(self, tools, kwargs): async def generate( self, prompt: str | list[int], - max_tokens: int = 256, + max_tokens: int = ENGINE_DEFAULT_MAX_TOKENS, temperature: float = 0.7, top_p: float = 0.9, top_k: int = 0, @@ -1170,7 +1172,7 @@ async def generate( async def stream_generate( self, prompt: str | list[int], - max_tokens: int = 256, + max_tokens: int = ENGINE_DEFAULT_MAX_TOKENS, temperature: float = 0.7, top_p: float = 0.9, top_k: int = 0, @@ -1303,7 +1305,7 @@ async def stream_generate( async def chat( self, messages: list[dict[str, Any]], - max_tokens: int = 256, + max_tokens: int = ENGINE_DEFAULT_MAX_TOKENS, temperature: float = 0.7, top_p: float = 0.9, top_k: int = 0, @@ -1434,7 +1436,7 @@ async def preflight_chat( scheduler, num_prompt_tokens=num_tokens, request_id=request_id, - max_tokens=kwargs.get("max_tokens"), + max_tokens=preflight_max_tokens(kwargs), ) async def preflight_completion( @@ -1467,13 +1469,13 @@ async def preflight_completion( scheduler, num_prompt_tokens=num_tokens, request_id=request_id, - max_tokens=kwargs.get("max_tokens"), + max_tokens=preflight_max_tokens(kwargs), ) async def stream_chat( self, messages: list[dict[str, Any]], - max_tokens: int = 256, + max_tokens: int = ENGINE_DEFAULT_MAX_TOKENS, temperature: float = 0.7, top_p: float = 0.9, top_k: int = 0, diff --git a/omlx/engine/vlm.py b/omlx/engine/vlm.py index 0ebd02da52..10caef34d2 100644 --- a/omlx/engine/vlm.py +++ b/omlx/engine/vlm.py @@ -68,12 +68,14 @@ write_video_data_uri, ) from .base import ( + ENGINE_DEFAULT_MAX_TOKENS, BaseEngine, GenerationOutput, _clear_teardown_references, _close_engine_core, _run_scheduler_preflight_with_cleanup_retry, _warn_scheduler_unreachable_once, + preflight_max_tokens, ) logger = logging.getLogger(__name__) @@ -4788,7 +4790,7 @@ def _media_end_kwargs(self, prompt: Any, vlm_inputs_embeds: Any) -> dict[str, in async def generate( self, prompt: str | list[int], - max_tokens: int = 256, + max_tokens: int = ENGINE_DEFAULT_MAX_TOKENS, temperature: float = 0.7, top_p: float = 0.9, top_k: int = 0, @@ -4898,7 +4900,7 @@ async def generate( async def stream_generate( self, prompt: str | list[int], - max_tokens: int = 256, + max_tokens: int = ENGINE_DEFAULT_MAX_TOKENS, temperature: float = 0.7, top_p: float = 0.9, top_k: int = 0, @@ -5052,7 +5054,7 @@ async def stream_generate( async def chat( self, messages: list[dict[str, Any]], - max_tokens: int = 256, + max_tokens: int = ENGINE_DEFAULT_MAX_TOKENS, temperature: float = 0.7, top_p: float = 0.9, top_k: int = 0, @@ -5259,7 +5261,7 @@ async def preflight_chat( scheduler, num_prompt_tokens=num_tokens, request_id=request_id, - max_tokens=kwargs.get("max_tokens"), + max_tokens=preflight_max_tokens(kwargs), ) async def preflight_completion( @@ -5295,13 +5297,13 @@ async def preflight_completion( scheduler, num_prompt_tokens=num_tokens, request_id=request_id, - max_tokens=kwargs.get("max_tokens"), + max_tokens=preflight_max_tokens(kwargs), ) async def stream_chat( self, messages: list[dict[str, Any]], - max_tokens: int = 256, + max_tokens: int = ENGINE_DEFAULT_MAX_TOKENS, temperature: float = 0.7, top_p: float = 0.9, top_k: int = 0, diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 7f4711b7a6..d97da34a4f 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -13879,7 +13879,7 @@ def _preflight_memory_check( ) # Fits alone: while rows are admitted, their memory comes back when # they finish, so the request waits at the head instead of failing. - fits_later = capacity is not None and self._num_admitted_requests() > 0 + fits_later = self._fits_later(capacity) # A request resumed after an eviction pause keeps its prompt cache. # Capacity reserved there already holds part of the KV priced below. @@ -14092,8 +14092,11 @@ def _format_rejection_message( def _model_weights_bytes(self) -> int: """Resident bytes of this model's weights; 0 when unknown. - Summed once from the model's parameter arrays (shape metadata only, - nothing is evaluated); a measured monitor baseline is the fallback. + Summed from the model's parameter arrays (shape metadata only, + nothing is evaluated) and cached once known. Unknown stays 0 and is + recomputed on the next call: the gate then has no estimate and never + rejects as never-fits. The monitor's process baseline is not a + weights size and is not used. """ cached = self._weights_bytes if cached is not None: @@ -14107,13 +14110,38 @@ def _model_weights_bytes(self) -> int: ) except Exception: # noqa: BLE001 - unknown model shape: no estimate total = 0 - if total <= 0 and self.memory_monitor is not None: - baseline = getattr(self.memory_monitor, "_baseline_memory", 0) - if isinstance(baseline, int) and not isinstance(baseline, bool): - total = baseline if total > 0: self._weights_bytes = total - return total + return max(0, total) + + def _fits_later(self, capacity: "_CapacityEstimate | None") -> bool: + """A request that fits alone waits instead of failing only while + admitted rows hold memory that comes back when they finish. Queued + requests hold none, so they never justify waiting.""" + return capacity is not None and self._num_admitted_requests() > 0 + + def _release_deferred_admission(self, request: "Request") -> None: + """Undo this admission attempt for a request that waits (fits later). + + Releases the paged-cache refs and the restored prefix the prefix + lookup took, so the request holds no memory while it waits. The next + attempt repeats the lookup (and any SpecPrefill scoring). + """ + rid = request.request_id + self._release_paged_cache_for_request(rid) + # fetch_cache builds the lookup's block table without registering it + # with the prefix cache, so release_cache above leaves it. Release its + # refs for eviction: the blocks stay findable for the re-admission. + manager = self.paged_cache_manager + if manager is not None and hasattr(manager, "release_block_table"): + self._after_commit(rid, lambda: manager.release_block_table(rid)) + request.prompt_cache = None + request.block_table = None + request.cached_tokens = 0 + request.shared_prefix_blocks = 0 + request.remaining_tokens = request.prompt_token_ids + request.specprefill_indices = None + self._prefix_cache_prepared.discard(rid) def _capacity_limit_bytes(self) -> int: """The line a request must fit under alone: the tighter of the @@ -14321,8 +14349,8 @@ def preflight_or_raise( A request that cannot fit even alone (weights + KV of prompt plus ``max_tokens`` + transient over the capacity line) raises ``ContextExceedsCapacityError`` whatever the current usage. One that - fits alone but not now passes while other work is admitted or - queued: it waits for that work to finish instead of being rejected. + fits alone but not now passes while other work is admitted: it waits + for that work to finish instead of being rejected. """ if not self._prefill_memory_guard: return @@ -14365,11 +14393,9 @@ def preflight_or_raise( if est is None: return - # Fits alone (checked above) and something running or queued will - # free memory: wait instead of rejecting. - fits_later = capacity is not None and ( - self._num_admitted_requests() > 0 or len(self.waiting) > 0 - ) + # Fits alone (checked above) and admitted rows will free memory: + # wait instead of rejecting (the same rule as the in-stream check). + fits_later = self._fits_later(capacity) hot_cache_credit = self._releasable_hot_cache_credit(est.kv_exact) admission_limit = self._admission_limit_bytes() if est.estimated - hot_cache_credit > admission_limit: @@ -14876,7 +14902,9 @@ def _schedule_waiting_scan( break except _PreflightDeferredError: # Fits alone but not now: it keeps its place at the head and - # nothing behind it overtakes it while the admitted rows run. + # nothing behind it overtakes it while the admitted rows run, + # holding no paged-cache refs or restored prefix meanwhile. + self._release_deferred_admission(request) self.waiting.appendleft(request) break if preflight_rejection is not None: diff --git a/omlx/server.py b/omlx/server.py index 9fbf961117..c471f5c760 100644 --- a/omlx/server.py +++ b/omlx/server.py @@ -4262,9 +4262,21 @@ async def create_completion( # log line and the FastAPI handler trace correlate with whatever # the client is using on its side. upstream_request_id = http_request.headers.get("x-request-id") + # The never-fits gate prices the output budget the generation will + # actually use (request, model setting or server default). + preflight_max_tokens = get_sampling_params( + request.temperature, + request.top_p, + request.model, + req_max_tokens=request.max_tokens, + )[7] await _raise_if_llm_lease_abort_requested(lease) for prompt in prompts: - await engine.preflight_completion(prompt, request_id=upstream_request_id) + await engine.preflight_completion( + prompt, + request_id=upstream_request_id, + max_tokens=preflight_max_tokens, + ) await _raise_if_llm_lease_abort_requested(lease) inference_request_id = _request_abort_id(engine) diff --git a/tests/test_batched_engine.py b/tests/test_batched_engine.py index 06956df7c6..3f6e8e4880 100644 --- a/tests/test_batched_engine.py +++ b/tests/test_batched_engine.py @@ -20,7 +20,12 @@ import pytest -from omlx.engine.base import BaseEngine, BaseNonStreamingEngine, GenerationOutput +from omlx.engine.base import ( + ENGINE_DEFAULT_MAX_TOKENS, + BaseEngine, + BaseNonStreamingEngine, + GenerationOutput, +) class FakeStreamingCore: @@ -1262,6 +1267,7 @@ async def test_reuses_prepared_prompt_through_preflight_and_generation( engine._engine.engine.scheduler, num_prompt_tokens=3, request_id="prepared-request", + max_tokens=ENGINE_DEFAULT_MAX_TOKENS, ) engine._tokenizer.apply_chat_template.assert_called_once() rendered_options = engine._tokenizer.apply_chat_template.call_args.kwargs diff --git a/tests/test_scheduler_capacity_gate.py b/tests/test_scheduler_capacity_gate.py index 69b692897a..0a08710cce 100644 --- a/tests/test_scheduler_capacity_gate.py +++ b/tests/test_scheduler_capacity_gate.py @@ -355,3 +355,210 @@ def test_a_request_that_never_fits_ends_with_the_structured_error( assert "big" not in scheduler.requests finally: rig.close() + + +# --- Route and in-stream never-fits checks agree --------------------------------- + + +@pytest.mark.parametrize( + "engine_kind,method", + [ + ("batched", "preflight_chat"), + ("batched", "preflight_completion"), + ("vlm", "preflight_chat"), + ("vlm", "preflight_completion"), + ], +) +async def test_route_preflight_prices_the_resolved_default_max_tokens( + engine_kind, method +): + """An omitted max_tokens is not 0 output + tokens; the gate uses the default the request itself will run with.""" + from test_engine_preflight import _build_engine_with_stub_scheduler + + from omlx.engine.base import ENGINE_DEFAULT_MAX_TOKENS + from omlx.engine.batched import BatchedEngine + from omlx.engine.vlm import VLMBatchedEngine + + seen = [] + + class _Scheduler: + def preflight_eviction_request(self, **kw): + seen.append(("eviction", kw.get("max_tokens"))) + return None + + def preflight_or_raise(self, **kw): + seen.append(("check", kw.get("max_tokens"))) + + cls = BatchedEngine if engine_kind == "batched" else VLMBatchedEngine + engine = _build_engine_with_stub_scheduler(cls, _Scheduler()) + engine._preprocess_messages = lambda m: m + if method == "preflight_chat": + await engine.preflight_chat(messages=[{"role": "user", "content": "x"}]) + else: + await engine.preflight_completion(prompt="x") + assert seen and all(value == ENGINE_DEFAULT_MAX_TOKENS for _, value in seen) + + seen.clear() + if method == "preflight_chat": + await engine.preflight_chat( + messages=[{"role": "user", "content": "x"}], max_tokens=77 + ) + else: + await engine.preflight_completion(prompt="x", max_tokens=77) + assert seen and all(value == 77 for _, value in seen) + + +def test_engine_default_max_tokens_matches_the_generate_default(): + import inspect + + from omlx.engine.base import ENGINE_DEFAULT_MAX_TOKENS + from omlx.engine.batched import BatchedEngine + from omlx.engine.vlm import VLMBatchedEngine + + for cls in (BatchedEngine, VLMBatchedEngine): + for name in ("generate", "stream_generate", "chat", "stream_chat"): + default = inspect.signature(getattr(cls, name)).parameters["max_tokens"] + assert default.default == ENGINE_DEFAULT_MAX_TOKENS + + +async def test_completion_route_preflights_with_the_resolved_max_tokens(monkeypatch): + from types import SimpleNamespace + from unittest.mock import MagicMock + + import omlx.server as server + from omlx.api.openai_models import CompletionRequest + + class _StopError(Exception): + pass + + seen = {} + + async def preflight_completion(prompt, request_id=None, **kwargs): + seen.update(kwargs) + raise _StopError() + + engine = MagicMock() + engine.tokenizer.encode = lambda text: [1, 2, 3] + engine.preflight_completion = preflight_completion + + async def get_engine(model, lease=None): + return engine + + monkeypatch.setattr(server, "get_engine_for_model", get_engine) + monkeypatch.setattr(server, "validate_context_window", lambda *a, **k: None) + monkeypatch.setattr(server, "_serving_model_id", lambda lease, model: model) + monkeypatch.setattr(server._server_state, "oq_manager", None) + monkeypatch.setattr(server._server_state, "settings_manager", None) + monkeypatch.setattr(server._server_state.sampling, "max_tokens", 777) + expected = server.get_sampling_params(None, None, "m")[7] + assert expected == 777 + request = CompletionRequest(model="m", prompt="hi") + with pytest.raises(_StopError): + await server.create_completion(request, SimpleNamespace(headers={})) + assert seen.get("max_tokens") == expected + + seen.clear() + request = CompletionRequest(model="m", prompt="hi", max_tokens=33) + with pytest.raises(_StopError): + await server.create_completion(request, SimpleNamespace(headers={})) + assert seen.get("max_tokens") == 33 + + +def test_route_preflight_with_only_queued_work_keeps_the_rejection(gated): + """Queued requests hold no memory, so with + nothing admitted waiting cannot help; both checks share one predicate.""" + scheduler, usage, admitted = gated + usage[0] = 99 * GB + admitted[0] = 0 + scheduler.waiting.append(_make_request(10)) + with pytest.raises(PrefillMemoryExceededError): + scheduler.preflight_or_raise(num_prompt_tokens=50_000, max_tokens=1_000) + admitted[0] = 1 + scheduler.preflight_or_raise(num_prompt_tokens=50_000, max_tokens=1_000) + + +def test_route_and_in_stream_fits_later_share_one_predicate(gated): + scheduler, _usage, admitted = gated + capacity = scheduler._capacity_estimate(context_tokens=10, max_tokens=0) + scheduler.waiting.append(_make_request(10)) + admitted[0] = 0 + assert scheduler._fits_later(capacity) is False + admitted[0] = 2 + assert scheduler._fits_later(capacity) is True + assert scheduler._fits_later(None) is False + + +def test_weights_fallback_is_not_cached_and_gives_no_estimate(gated): + """Unknown weights mean no estimate (never + a never-fits rejection) and are recomputed on the next call.""" + scheduler, _usage, _admitted = gated + scheduler._weights_bytes = None + scheduler.memory_monitor._baseline_memory = 64 * GB + assert scheduler._model_weights_bytes() == 0 + assert scheduler._weights_bytes is None + assert scheduler._capacity_estimate(context_tokens=10, max_tokens=0) is None + huge = 10_000_000 + scheduler._memory_hard_limit_bytes = 100 * GB + try: + scheduler.preflight_or_raise(num_prompt_tokens=huge, max_tokens=0) + except ContextExceedsCapacityError: # pragma: no cover - the defect + pytest.fail("unknown weights must not reject as never-fits") + except PrefillMemoryExceededError: + pass # the older current-usage rejection may still apply + + +def test_a_deferred_request_releases_its_prefix_restore_and_readmits( + tmp_path, mock_tokenizer, monkeypatch +): + """A fits-later request holds no paged-cache refs + or restored prefix while it waits, and its re-admission works.""" + rig, usage = _guarded_rig( + tmp_path, mock_tokenizer, monkeypatch, weights_gb=20, free_gb=50 + ) + try: + scheduler = rig.scheduler + # Warm the prefix so the deferred request restores cached blocks. + first = submit(rig, "warm", PROMPT_C, arrival=0.5, max_tokens=1) + step_until(rig, lambda: first.is_finished()) + for future in list(scheduler._inflight_store_futures.values()): + future.result(timeout=30) + rig.drain() + + scheduler._prefill_memory_guard = True + admitted = [1] + monkeypatch.setattr(scheduler, "_num_admitted_requests", lambda: admitted[0]) + usage[0] = scheduler._admission_limit_bytes() + restores = [] + real_prepare = scheduler._prepare_prefix_cache_for_request + + def prepare(request): + real_prepare(request) + restores.append(request.cached_tokens) + + monkeypatch.setattr(scheduler, "_prepare_prefix_cache_for_request", prepare) + # Longer than the warm prompt: a prefix hit plus a suffix to prefill. + # No idle model to evict: the request defers (an eviction pause keeps + # the restore on purpose, #2180, and is not what this checks). + monkeypatch.setattr( + scheduler, "_raise_prefill_eviction_if_available", lambda **_kw: None + ) + later = submit(rig, "later", PROMPT_C + PROMPT_A[:12], arrival=1.0) + outputs = step(rig, 2) + assert not [o for o in outputs if o.error] + assert waiting_ids(rig) == ["later"] + assert restores and restores[0] > 0 # it did restore a prefix + # ...and gave it back while it waits. + assert later.prompt_cache is None + assert later.block_table is None + assert later.cached_tokens == 0 + assert rig.paged.get_block_table("later") is None + assert "later" not in scheduler._prefix_cache_prepared + + admitted[0] = 0 + usage[0] = scheduler._admission_limit_bytes() - 50 * GB + step_until(rig, lambda: later.is_finished()) + assert later.finish_reason != "error" + assert restores[-1] > 0, restores # the re-admission restored it again + finally: + rig.close() From 61eea318b9387764bb791441b6ac78f43b37d84c Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Mon, 5 Oct 2026 17:25:55 -0600 Subject: [PATCH 30/46] fix(scheduler): key the deferred release to its table and back off the deferred head Two fixes to the fits-later wait. - The block-table release of a deferred admission can wait behind an in-flight prefill commit. It was keyed only by request id, so if it ran after a re-admission it would release the new table. It now captures the attempt's table: release_block_table(rid, table=...) gives back that table's refs and drops the entry only while it is still that table. A deferred head whose release still waits keeps the head-of-line hold instead of being set aside for backfill. - A deferred head gave back its restored prefix and was retried on the next step, restoring the prefix from SSD again every step while memory stayed tight. It now retries only when the memory picture changed: an admitted row left (finished, aborted or paused), free memory rose by more than 2% of the admission line, or an exponential backoff expired (0.25 s doubling per deferral, capped at 4 s). The release stays, FIFO and the hold are unchanged. Rig: 10 restores in 10 unchanged steps before, 1 after. --- docs/TESTING.md | 2 +- omlx/cache/paged_cache.py | 14 +- omlx/scheduler.py | 96 ++++++- tests/test_scheduler_deferred_admission.py | 299 +++++++++++++++++++++ 4 files changed, 407 insertions(+), 4 deletions(-) create mode 100644 tests/test_scheduler_deferred_admission.py diff --git a/docs/TESTING.md b/docs/TESTING.md index bf1bc01600..01ccb3828c 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -243,7 +243,7 @@ Run `python -m pytest -q tests/test_memory_scheduling_admin_state.py` to check m # Never-fits gate tests -Run `python -m pytest -q tests/test_scheduler_capacity_gate.py tests/test_server_context_capacity.py` to check the feasibility gate. A request whose weights + exact KV of prompt plus `max_tokens` + prefill transient exceed the capacity line (the tighter of the admission line and the prefill safety cap) is rejected with `ContextExceedsCapacityError` (HTTP 400, `omlx_code: context_exceeds_capacity`, the byte and token fields, `retryable: false`) whatever the current usage. One that fits alone but not now is not rejected: the route preflight lets it queue while other work is admitted (queued requests hold no memory and do not count), and the in-stream admission keeps it at the head (nothing overtakes it) until the admitted rows free memory; both checks share one predicate. A deferred request releases its restored prefix and its block-table refs while it waits, and its re-admission repeats the lookup. Both checks price the same output budget: the route preflight uses the resolved `max_tokens` (request, model setting or server default; the engine default when an engine is called directly). With nothing admitted, or when the capacity cannot be estimated (no memory limit, unknown weights or KV dimensions), the older current-usage rejection applies; unknown weights are never cached and never produce a never-fits rejection. The server cases cover the 400 body on API and non-API routes, `GET /v1/omlx/capacity` (fields, 404/409, auth) and the `X-oMLX-Max-Context-Tokens` header on streaming and non-streaming chat completions. These cases run with memory scheduling on (see the memory scheduling gate tests above); off, there is no capacity estimate and the older current-usage rejection applies. +Run `python -m pytest -q tests/test_scheduler_capacity_gate.py tests/test_scheduler_deferred_admission.py tests/test_server_context_capacity.py` to check the feasibility gate. A request whose weights + exact KV of prompt plus `max_tokens` + prefill transient exceed the capacity line (the tighter of the admission line and the prefill safety cap) is rejected with `ContextExceedsCapacityError` (HTTP 400, `omlx_code: context_exceeds_capacity`, the byte and token fields, `retryable: false`) whatever the current usage. One that fits alone but not now is not rejected: the route preflight lets it queue while other work is admitted (queued requests hold no memory and do not count), and the in-stream admission keeps it at the head (nothing overtakes it) until the admitted rows free memory; both checks share one predicate. A deferred request releases its restored prefix and its block-table refs while it waits, and its re-admission repeats the lookup. The block-table release can wait behind an in-flight prefill commit; it is keyed to the deferred attempt's table, so it never frees a table the request got since. The deferred head is not retried (and its prefix not restored again) on every step: it retries once an admitted row left (finished, aborted or paused), free memory rose by more than 2% of the admission line, or its backoff expired (0.25 s doubling per deferral, capped at 4 s); it keeps the head-of-line hold meanwhile, also while its release still waits behind a commit. Both checks price the same output budget: the route preflight uses the resolved `max_tokens` (request, model setting or server default; the engine default when an engine is called directly). With nothing admitted, or when the capacity cannot be estimated (no memory limit, unknown weights or KV dimensions), the older current-usage rejection applies; unknown weights are never cached and never produce a never-fits rejection. The server cases cover the 400 body on API and non-API routes, `GET /v1/omlx/capacity` (fields, 404/409, auth) and the `X-oMLX-Max-Context-Tokens` header on streaming and non-streaming chat completions. These cases run with memory scheduling on (see the memory scheduling gate tests above); off, there is no capacity estimate and the older current-usage rejection applies. Mocked tests do not replace hardware validation: with a real model, send a prompt larger than `max_viable_context_tokens` and check for an immediate 400 with the fields, then send two prompts that each fit alone but not together and check that the second waits and completes without an error. diff --git a/omlx/cache/paged_cache.py b/omlx/cache/paged_cache.py index 062f579f07..c7b91990bb 100644 --- a/omlx/cache/paged_cache.py +++ b/omlx/cache/paged_cache.py @@ -1298,15 +1298,25 @@ def delete_block_table(self, request_id: str) -> None: for block_id in table.block_ids: self.free_block(block_id) - def release_block_table(self, request_id: str) -> None: + def release_block_table( + self, request_id: str, table: BlockTable | None = None + ) -> None: """Drop a request's block table without freeing its blocks. Its references are released for eviction (``release_for_eviction``), so the blocks stay cached and findable by later prefix lookups, as after a completed request's store. + + With ``table``, only that table instance is released: its refs are + given back, and the request's entry is dropped only while it still + is that table. A newer table the request got since (a re-admission + replaces the entry) keeps its entry and its refs. """ with self._lock: - table = self.request_tables.pop(request_id, None) + if table is None: + table = self.request_tables.pop(request_id, None) + elif self.request_tables.get(request_id) is table: + del self.request_tables[request_id] if table: self.release_for_eviction(table.block_ids) diff --git a/omlx/scheduler.py b/omlx/scheduler.py index d97da34a4f..4b8868f7b5 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -264,6 +264,34 @@ class _PreflightDeferredError(Exception): # Seconds between "fits later" log lines for the same waiting request. _FITS_LATER_LOG_INTERVAL_S = 30.0 +# A fits-later head that deferred gave back its restored prefix, so each +# retry restores it again (from SSD). It is retried only once the memory +# picture changed: an admitted row left (finished, aborted or paused), free +# memory rose by more than this fraction of the admission line, or its +# exponential backoff (base doubling per deferral, capped) expired. +DEFERRED_ADMISSION_FREE_DELTA_FRACTION = 0.02 +DEFERRED_ADMISSION_RETRY_BASE_S = 0.25 +DEFERRED_ADMISSION_RETRY_MAX_S = 4.0 + + +def _deferred_admission_backoff_s(attempts: int) -> float: + """Seconds a head waits after its ``attempts``-th consecutive deferral.""" + exponent = min(max(int(attempts), 1) - 1, 32) + return min( + DEFERRED_ADMISSION_RETRY_BASE_S * (2**exponent), + DEFERRED_ADMISSION_RETRY_MAX_S, + ) + + +@dataclass +class _DeferredAdmissionWait: + """The memory picture a fits-later head deferred on.""" + + attempts: int + retry_at: float + free_bytes: int | None + admitted_ids: frozenset[str] + @dataclass class _AdmissionEstimate: @@ -2432,6 +2460,8 @@ def __init__( # Chunked prefill queue: requests whose prefill spans multiple steps. # Populated when chunked_prefill=True and prompt exceeds prefill_step_size. self.prefilling: deque[Request] = deque() + # Fits-later heads that deferred, and the memory picture they wait on. + self._deferred_admissions: dict[str, _DeferredAdmissionWait] = {} self._prefill_states: dict[str, _PrefillState] = {} # Packed prefill: "" once the model is known to be unsupported. self._packed_prefill_family: str | None = None @@ -14132,9 +14162,16 @@ def _release_deferred_admission(self, request: "Request") -> None: # fetch_cache builds the lookup's block table without registering it # with the prefix cache, so release_cache above leaves it. Release its # refs for eviction: the blocks stay findable for the re-admission. + # The release may wait behind an in-flight prefill commit, so it is + # keyed to this attempt's table: run after a re-admission, it gives + # back only the old table's refs and leaves the new table alone. manager = self.paged_cache_manager if manager is not None and hasattr(manager, "release_block_table"): - self._after_commit(rid, lambda: manager.release_block_table(rid)) + table = manager.get_block_table(rid) + if table is not None: + self._after_commit( + rid, lambda: manager.release_block_table(rid, table=table) + ) request.prompt_cache = None request.block_table = None request.cached_tokens = 0 @@ -14143,6 +14180,53 @@ def _release_deferred_admission(self, request: "Request") -> None: request.specprefill_indices = None self._prefix_cache_prepared.discard(rid) + def _admitted_request_ids(self) -> frozenset[str]: + """Ids of the rows occupying scheduler capacity (running, prefilling).""" + return frozenset(self.running) | frozenset( + r.request_id for r in self.prefilling + ) + + def _note_deferred_admission(self, request: "Request") -> None: + """Record the memory picture a fits-later head deferred on.""" + rid = request.request_id + # Requests that left the scheduler while waiting drop their record. + for stale in [r for r in self._deferred_admissions if r not in self.requests]: + self._deferred_admissions.pop(stale, None) + previous = self._deferred_admissions.get(rid) + attempts = (previous.attempts if previous is not None else 0) + 1 + self._deferred_admissions[rid] = _DeferredAdmissionWait( + attempts=attempts, + retry_at=time.monotonic() + _deferred_admission_backoff_s(attempts), + free_bytes=self._park_free_bytes(), + admitted_ids=self._admitted_request_ids(), + ) + + def _deferred_admission_holds(self, head: "Request") -> bool: + """Whether a deferred fits-later ``head`` waits instead of retrying. + + It retries once the memory picture changed since it deferred: no row + is admitted any more (the fits-later wait no longer applies), a row + it waited on left (finished, aborted or paused), free memory rose by + more than ``DEFERRED_ADMISSION_FREE_DELTA_FRACTION`` of the admission + line, or its backoff expired. The record stays, so a new deferral + doubles the backoff. + """ + wait = self._deferred_admissions.get(head.request_id) + if wait is None: + return False + if not self._num_admitted_requests(): + return False + if not wait.admitted_ids <= self._admitted_request_ids(): + return False + free = self._park_free_bytes() + if free is not None and wait.free_bytes is not None: + threshold = int( + self._admission_limit_bytes() * DEFERRED_ADMISSION_FREE_DELTA_FRACTION + ) + if free - wait.free_bytes > threshold: + return False + return time.monotonic() < wait.retry_at + def _capacity_limit_bytes(self) -> int: """The line a request must fit under alone: the tighter of the admission line and the prefill safety cap (0 when no limit).""" @@ -14649,6 +14733,10 @@ def _schedule_waiting_scan( # overtakes them while they wait. if self.waiting[0].parked and self._park_hold_applies(self.waiting[0]): break + # A fits-later head that deferred keeps the hold until the memory + # picture changes; retrying earlier only restores its prefix again. + if self._deferred_admission_holds(self.waiting[0]): + break admitted = self._num_admitted_requests() if self._admission_paused and admitted: @@ -14755,6 +14843,10 @@ def _schedule_waiting_scan( # A previous run of this id is still being torn down behind # its prefill commit; only this request waits (no blocking) # so the deferred cleanup cannot hit the new run's state. + # A deferred fits-later head is not set aside: nothing behind + # it overtakes it, so it keeps the hold until the release ran. + if request.request_id in self._deferred_admissions: + break held.append(self.waiting.popleft()) continue @@ -14905,8 +14997,10 @@ def _schedule_waiting_scan( # nothing behind it overtakes it while the admitted rows run, # holding no paged-cache refs or restored prefix meanwhile. self._release_deferred_admission(request) + self._note_deferred_admission(request) self.waiting.appendleft(request) break + self._deferred_admissions.pop(request.request_id, None) if preflight_rejection is not None: logger.warning( f"Request {request.request_id} rejected by prefill " diff --git a/tests/test_scheduler_deferred_admission.py b/tests/test_scheduler_deferred_admission.py new file mode 100644 index 0000000000..7ebb2b0e1b --- /dev/null +++ b/tests/test_scheduler_deferred_admission.py @@ -0,0 +1,299 @@ +# SPDX-License-Identifier: Apache-2.0 +"""A fits-later request that waits at the head of the queue. + +``_release_deferred_admission`` gives back everything a deferred admission +attempt took (restored prefix, block table, SpecPrefill indices), so the +waiting request holds no memory. Two further cases: + +- the block-table release queued behind an in-flight prefill commit must not + free a table the request got after it was re-admitted; +- the deferred head is not retried, and its prefix not restored from SSD + again, on every step while the memory picture is unchanged. +""" + +import concurrent.futures + +from test_scheduler_capacity_gate import GB, _guarded_rig +from test_scheduler_park import PROMPT_A, PROMPT_C, step, submit, waiting_ids + +import omlx.scheduler as scheduler_module + + +def _warm_prefix(rig): + """Finish one request on PROMPT_C so later prompts restore its blocks.""" + scheduler = rig.scheduler + first = submit(rig, "warm", PROMPT_C, arrival=0.5, max_tokens=1) + for _ in range(60): + if first.is_finished(): + break + step(rig) + for future in list(scheduler._inflight_store_futures.values()): + future.result(timeout=30) + rig.drain() + + +# --- A stale deferred release never frees a newer block table ----------------- + + +def test_a_stale_deferred_release_leaves_the_readmitted_table_intact( + tmp_path, mock_tokenizer, monkeypatch +): + rig, _usage = _guarded_rig( + tmp_path, mock_tokenizer, monkeypatch, weights_gb=20, free_gb=50 + ) + try: + scheduler = rig.scheduler + paged = rig.paged + request = submit(rig, "r", PROMPT_C, arrival=1.0) + + # The deferred attempt's lookup built table A holding one block ref. + old_table = paged.create_block_table("r") + old_block = paged.allocate_block() + paged.add_block_to_table(old_table, old_block, 4) + + # A prefill commit for "r" is still running: the release is queued. + pending = concurrent.futures.Future() + commit_running = [True] + real_inflight = scheduler._inflight_commit_future + monkeypatch.setattr( + scheduler, + "_inflight_commit_future", + lambda rid: pending if commit_running[0] else real_inflight(rid), + ) + scheduler._release_deferred_admission(request) + assert paged.get_block_table("r") is old_table # still queued + + # The request is re-admitted with a NEW table before the commit ends. + new_table = paged.create_block_table("r") + new_block = paged.allocate_block() + paged.add_block_to_table(new_table, new_block, 4) + + # The commit ends; the queued release runs at the next step start. + commit_running[0] = False + pending.set_result(None) + scheduler._process_finished_commits() + + assert paged.get_block_table("r") is new_table + assert new_table.block_ids == [new_block.block_id] + assert new_block.ref_count == 1 # the new run keeps its ref + assert old_block.ref_count == 0 # the old attempt's ref is released + finally: + rig.close() + + +def test_a_deferred_release_without_a_commit_runs_now( + tmp_path, mock_tokenizer, monkeypatch +): + rig, _usage = _guarded_rig( + tmp_path, mock_tokenizer, monkeypatch, weights_gb=20, free_gb=50 + ) + try: + scheduler = rig.scheduler + paged = rig.paged + request = submit(rig, "r", PROMPT_C, arrival=1.0) + table = paged.create_block_table("r") + block = paged.allocate_block() + paged.add_block_to_table(table, block, 4) + + scheduler._release_deferred_admission(request) + + assert paged.get_block_table("r") is None + assert block.ref_count == 0 + assert block.block_id in paged.allocated_blocks # still findable + finally: + rig.close() + + +# --- The deferred head waits for a memory change before it retries ------------- + + +def _deferring_rig(tmp_path, tokenizer, monkeypatch, *, base_s=60.0, max_s=60.0): + """A warm prefix, the guard on, one admitted row (constant) and no free + memory: a request longer than the warm prompt restores a prefix and then + defers. Returns the rig, the usage cell, the admitted-ids cell and the + list of the "later" request's restored prefix lengths (one entry per + restore from cache).""" + rig, usage = _guarded_rig( + tmp_path, tokenizer, monkeypatch, weights_gb=20, free_gb=50 + ) + scheduler = rig.scheduler + _warm_prefix(rig) + monkeypatch.setattr( + scheduler_module, "DEFERRED_ADMISSION_RETRY_BASE_S", base_s, raising=False + ) + monkeypatch.setattr( + scheduler_module, "DEFERRED_ADMISSION_RETRY_MAX_S", max_s, raising=False + ) + scheduler._prefill_memory_guard = True + monkeypatch.setattr(scheduler, "_num_admitted_requests", lambda: 1) + admitted_ids = [frozenset({"busy"})] + monkeypatch.setattr( + scheduler, "_admitted_request_ids", lambda: admitted_ids[0], raising=False + ) + # No idle model to evict: the request defers (an eviction pause keeps + # the restore on purpose, #2180). + monkeypatch.setattr( + scheduler, "_raise_prefill_eviction_if_available", lambda **_kw: None + ) + usage[0] = scheduler._admission_limit_bytes() + restores = [] + real_prepare = scheduler._prepare_prefix_cache_for_request + + def prepare(request): + real_prepare(request) + if request.request_id == "later" and request.cached_tokens > 0: + restores.append(request.cached_tokens) + + monkeypatch.setattr(scheduler, "_prepare_prefix_cache_for_request", prepare) + return rig, usage, admitted_ids, restores + + +LATER_PROMPT = PROMPT_C + PROMPT_A[:12] # a prefix hit plus a suffix to prefill +# An exact hit of the warm prompt leaves nothing to prefill, so the preflight +# admits it whatever the memory: only the hold keeps it behind the head. +NEWER_PROMPT = PROMPT_C + + +def test_an_unchanged_memory_picture_restores_the_deferred_head_once( + tmp_path, mock_tokenizer, monkeypatch +): + rig, _usage, _ids, restores = _deferring_rig(tmp_path, mock_tokenizer, monkeypatch) + try: + submit(rig, "later", LATER_PROMPT, arrival=1.0) + submit(rig, "newer", NEWER_PROMPT, arrival=2.0) + outputs = step(rig, 10) + assert not [o for o in outputs if o.error] + assert len(restores) == 1, restores + # FIFO and the head-of-line hold: nothing overtakes the deferred head. + assert waiting_ids(rig) == ["later", "newer"] + assert rig.scheduler.requests["later"].prompt_cache is None + finally: + rig.close() + + +def test_a_finished_admitted_row_triggers_the_next_attempt( + tmp_path, mock_tokenizer, monkeypatch +): + rig, _usage, admitted_ids, restores = _deferring_rig( + tmp_path, mock_tokenizer, monkeypatch + ) + try: + submit(rig, "later", LATER_PROMPT, arrival=1.0) + step(rig, 3) + assert len(restores) == 1 + # The admitted row finishes (or aborts, or is paused): one re-attempt + # on the next step, then the head waits again. + admitted_ids[0] = frozenset() + step(rig) + assert len(restores) == 2, restores + step(rig, 5) + assert len(restores) == 2, restores + assert waiting_ids(rig) == ["later"] + finally: + rig.close() + + +def test_free_memory_rising_past_the_threshold_triggers_the_next_attempt( + tmp_path, mock_tokenizer, monkeypatch +): + rig, usage, _ids, restores = _deferring_rig(tmp_path, mock_tokenizer, monkeypatch) + try: + scheduler = rig.scheduler + limit = scheduler._admission_limit_bytes() + delta = scheduler_module.DEFERRED_ADMISSION_FREE_DELTA_FRACTION + submit(rig, "later", LATER_PROMPT, arrival=1.0) + step(rig, 2) + assert len(restores) == 1 + usage[0] = limit - int(limit * delta / 2) # below the threshold + step(rig, 3) + assert len(restores) == 1, restores + usage[0] = limit - int(limit * delta * 2) # past it + step(rig) + assert len(restores) == 2, restores + step(rig, 3) # the new baseline is the freer picture + assert len(restores) == 2, restores + finally: + rig.close() + + +def test_an_expired_backoff_triggers_the_next_attempt( + tmp_path, mock_tokenizer, monkeypatch +): + import time + + rig, _usage, _ids, restores = _deferring_rig( + tmp_path, mock_tokenizer, monkeypatch, base_s=0.5, max_s=60.0 + ) + try: + submit(rig, "later", LATER_PROMPT, arrival=1.0) + step(rig, 2) + assert len(restores) == 1 + time.sleep(0.55) + step(rig) + assert len(restores) == 2, restores + # The backoff doubled to 1 s: half a second later it still waits. + time.sleep(0.55) + step(rig) + assert len(restores) == 2, restores + finally: + rig.close() + + +def test_the_backoff_doubles_and_is_capped(monkeypatch): + monkeypatch.setattr(scheduler_module, "DEFERRED_ADMISSION_RETRY_BASE_S", 0.25) + monkeypatch.setattr(scheduler_module, "DEFERRED_ADMISSION_RETRY_MAX_S", 4.0) + backoff = scheduler_module._deferred_admission_backoff_s + assert [backoff(n) for n in range(1, 8)] == [0.25, 0.5, 1.0, 2.0, 4.0, 4.0, 4.0] + assert backoff(10_000) == 4.0 # no overflow on a long wait + + +def test_a_deferred_head_with_a_pending_teardown_keeps_the_hold( + tmp_path, mock_tokenizer, monkeypatch +): + """When its retry is due but its release still waits behind a commit, the + head keeps the hold instead of being set aside for backfill.""" + rig, _usage, admitted_ids, restores = _deferring_rig( + tmp_path, mock_tokenizer, monkeypatch + ) + try: + scheduler = rig.scheduler + submit(rig, "later", LATER_PROMPT, arrival=1.0) + submit(rig, "newer", NEWER_PROMPT, arrival=2.0) + step(rig) + assert waiting_ids(rig) == ["later", "newer"] + real_pending = scheduler._teardown_pending + monkeypatch.setattr( + scheduler, + "_teardown_pending", + lambda rid: rid == "later" or real_pending(rid), + ) + admitted_ids[0] = frozenset() # a retry is due + step(rig, 2) + assert waiting_ids(rig) == ["later", "newer"] + assert "newer" not in scheduler.running + finally: + rig.close() + + +def test_the_deferred_head_is_admitted_once_memory_frees( + tmp_path, mock_tokenizer, monkeypatch +): + rig, usage, _ids, restores = _deferring_rig(tmp_path, mock_tokenizer, monkeypatch) + try: + scheduler = rig.scheduler + later = submit(rig, "later", LATER_PROMPT, arrival=1.0) + step(rig, 3) + monkeypatch.setattr( + scheduler, + "_num_admitted_requests", + lambda: len(scheduler.running) + len(scheduler.prefilling), + ) + usage[0] = scheduler._admission_limit_bytes() - 50 * GB + for _ in range(60): + if later.is_finished(): + break + step(rig) + assert later.finish_reason != "error" + assert "later" not in scheduler._deferred_admissions + finally: + rig.close() From 8550d94d8020bc61ca18edaee01c0b870704c540 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Mon, 5 Oct 2026 17:26:46 -0600 Subject: [PATCH 31/46] fix(server): return named sampling params and read max_tokens by name The completion route took the resolved max_tokens for the never-fits preflight from position [7] of the tuple get_sampling_params returns. get_sampling_params now returns a ResolvedSampling NamedTuple in the same field order, so positional unpacking keeps working, and the route reads `.max_tokens`. No behaviour change; tests pin the field order and the request > model > global resolution of `.max_tokens`. --- omlx/server.py | 49 +++++++++++++++++++-------- tests/test_scheduler_capacity_gate.py | 2 +- tests/test_server.py | 39 +++++++++++++++++++++ 3 files changed, 74 insertions(+), 16 deletions(-) diff --git a/omlx/server.py b/omlx/server.py index c471f5c760..2b7324c922 100644 --- a/omlx/server.py +++ b/omlx/server.py @@ -53,7 +53,7 @@ from dataclasses import asdict, dataclass, field from enum import Enum from pathlib import Path -from typing import Any, Optional, Union +from typing import Any, NamedTuple, Optional, Union from fastapi import Depends, FastAPI, HTTPException, Query, Response from fastapi import Request as FastAPIRequest @@ -1820,6 +1820,25 @@ async def get_decision_engine(model: str, lease: _LLMEngineLease) -> DecisionEng return engine +class ResolvedSampling(NamedTuple): + """Effective sampling parameters from ``get_sampling_params``. + + A tuple in this field order, so positional unpacking keeps working; new + callers read fields by name. + """ + + temperature: float + top_p: float + top_k: int + repetition_penalty: float + min_p: float + presence_penalty: float + frequency_penalty: float + max_tokens: int + xtc_probability: float + xtc_threshold: float + + def get_sampling_params( req_temperature: float | None, req_top_p: float | None, @@ -1833,7 +1852,7 @@ def get_sampling_params( ocr_defaults: dict | None = None, req_xtc_probability: float | None = None, req_xtc_threshold: float | None = None, -) -> tuple[float, float, int, float, float, float, float, int, float, float]: +) -> ResolvedSampling: """ Get effective sampling parameters with per-model settings support. @@ -1845,7 +1864,7 @@ def get_sampling_params( - Otherwise: request > model settings > ocr_defaults > global defaults. Returns: - tuple of (temperature, top_p, top_k, repetition_penalty, min_p, presence_penalty, frequency_penalty, max_tokens, xtc_probability, xtc_threshold) + ResolvedSampling (temperature, top_p, top_k, repetition_penalty, min_p, presence_penalty, frequency_penalty, max_tokens, xtc_probability, xtc_threshold) """ global_sampling = _server_state.sampling @@ -1973,17 +1992,17 @@ def get_sampling_params( f"{' (forced)' if force else ''}" f"{f' (model: {model_id})' if model_id else ''}" ) - return ( - temperature, - top_p, - top_k, - repetition_penalty, - min_p, - presence_penalty, - frequency_penalty, - max_tokens, - xtc_probability, - xtc_threshold, + return ResolvedSampling( + temperature=temperature, + top_p=top_p, + top_k=top_k, + repetition_penalty=repetition_penalty, + min_p=min_p, + presence_penalty=presence_penalty, + frequency_penalty=frequency_penalty, + max_tokens=max_tokens, + xtc_probability=xtc_probability, + xtc_threshold=xtc_threshold, ) @@ -4269,7 +4288,7 @@ async def create_completion( request.top_p, request.model, req_max_tokens=request.max_tokens, - )[7] + ).max_tokens await _raise_if_llm_lease_abort_requested(lease) for prompt in prompts: await engine.preflight_completion( diff --git a/tests/test_scheduler_capacity_gate.py b/tests/test_scheduler_capacity_gate.py index 0a08710cce..be72cf67c3 100644 --- a/tests/test_scheduler_capacity_gate.py +++ b/tests/test_scheduler_capacity_gate.py @@ -451,7 +451,7 @@ async def get_engine(model, lease=None): monkeypatch.setattr(server._server_state, "oq_manager", None) monkeypatch.setattr(server._server_state, "settings_manager", None) monkeypatch.setattr(server._server_state.sampling, "max_tokens", 777) - expected = server.get_sampling_params(None, None, "m")[7] + expected = server.get_sampling_params(None, None, "m").max_tokens assert expected == 777 request = CompletionRequest(model="m", prompt="hi") with pytest.raises(_StopError): diff --git a/tests/test_server.py b/tests/test_server.py index 94f9efaa86..c191d93f23 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -432,6 +432,45 @@ def test_returns_10_tuple(self): assert isinstance(result, tuple) assert len(result) == 10 + def test_fields_are_named_in_tuple_order(self): + """The result is a named tuple: callers read fields by name, while + positional unpacking keeps its order.""" + result = get_sampling_params(None, None, req_max_tokens=321) + assert result._fields == ( + "temperature", + "top_p", + "top_k", + "repetition_penalty", + "min_p", + "presence_penalty", + "frequency_penalty", + "max_tokens", + "xtc_probability", + "xtc_threshold", + ) + assert result.max_tokens == 321 + assert result.max_tokens == result[7] + + def test_named_max_tokens_resolves_request_model_then_global(self): + """``.max_tokens`` follows request > model setting > global default.""" + import tempfile + from pathlib import Path + + with tempfile.TemporaryDirectory() as tmpdir: + manager = ModelSettingsManager(Path(tmpdir)) + manager.set_settings("test-model", ModelSettings(max_tokens=8192)) + self._state.settings_manager = manager + self._state.sampling = SamplingDefaults(max_tokens=4096) + + assert get_sampling_params(None, None, "test-model").max_tokens == 8192 + assert ( + get_sampling_params( + None, None, "test-model", req_max_tokens=64 + ).max_tokens + == 64 + ) + assert get_sampling_params(None, None, "other").max_tokens == 4096 + def test_defaults(self): """Test default values with no request or model params.""" ( From 61cd18ae08a70051956a65654fa286c9318bfadd Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Mon, 5 Oct 2026 21:22:49 -0600 Subject: [PATCH 32/46] test(scheduler): drive the deferred-admission backoff test with a controlled clock --- tests/test_scheduler_deferred_admission.py | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/tests/test_scheduler_deferred_admission.py b/tests/test_scheduler_deferred_admission.py index 7ebb2b0e1b..f573313c1f 100644 --- a/tests/test_scheduler_deferred_admission.py +++ b/tests/test_scheduler_deferred_admission.py @@ -220,6 +220,16 @@ def test_an_expired_backoff_triggers_the_next_attempt( tmp_path, mock_tokenizer, monkeypatch ): import time + import types + + # Advance only the scheduler's clock, so the test does not depend on + # wall-clock sleeps (which were flaky with a 50 ms margin). + offset = [0.0] + fake_time = types.SimpleNamespace( + **{name: getattr(time, name) for name in dir(time) if not name.startswith("__")} + ) + fake_time.monotonic = lambda: time.monotonic() + offset[0] + monkeypatch.setattr(scheduler_module, "time", fake_time) rig, _usage, _ids, restores = _deferring_rig( tmp_path, mock_tokenizer, monkeypatch, base_s=0.5, max_s=60.0 @@ -228,13 +238,16 @@ def test_an_expired_backoff_triggers_the_next_attempt( submit(rig, "later", LATER_PROMPT, arrival=1.0) step(rig, 2) assert len(restores) == 1 - time.sleep(0.55) + offset[0] += 0.75 # past the 0.5 s backoff step(rig) assert len(restores) == 2, restores - # The backoff doubled to 1 s: half a second later it still waits. - time.sleep(0.55) + # The backoff doubled to 1 s: 0.25 s later it still waits. + offset[0] += 0.25 step(rig) assert len(restores) == 2, restores + offset[0] += 1.0 # past the doubled backoff + step(rig) + assert len(restores) == 3, restores finally: rig.close() From 2ea07bd6368ddcbd18334d0babf88054a21df87e Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Tue, 6 Oct 2026 01:15:56 -0600 Subject: [PATCH 33/46] fix(memory): size VLM weights through the adapter for the never-fits gate VLMModelAdapter keeps the mlx-vlm model in _vlm_model, which nn.Module.parameters() skips, so the scheduler summed 0 bytes of weights, capacity_snapshot returned None and the never-fits gate and capacity hint were dead on VLMBatchedEngine. Unwrap the adapter (and the VLM-MTP proxy) and count each array once. Tests use a tiny real mlx-vlm Qwen3.5 model behind the real adapter: the capacity is available, kv_bytes_per_token prices the TurboQuant prefill peak, quantized scales and biases count, and max_tokens 2,000,000 reaches the gate unclamped and is rejected as never-fits. --- docs/TESTING.md | 2 +- omlx/scheduler.py | 45 ++++- tests/test_scheduler_capacity_vlm.py | 256 +++++++++++++++++++++++++++ 3 files changed, 298 insertions(+), 5 deletions(-) create mode 100644 tests/test_scheduler_capacity_vlm.py diff --git a/docs/TESTING.md b/docs/TESTING.md index 01ccb3828c..f779106eac 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -243,7 +243,7 @@ Run `python -m pytest -q tests/test_memory_scheduling_admin_state.py` to check m # Never-fits gate tests -Run `python -m pytest -q tests/test_scheduler_capacity_gate.py tests/test_scheduler_deferred_admission.py tests/test_server_context_capacity.py` to check the feasibility gate. A request whose weights + exact KV of prompt plus `max_tokens` + prefill transient exceed the capacity line (the tighter of the admission line and the prefill safety cap) is rejected with `ContextExceedsCapacityError` (HTTP 400, `omlx_code: context_exceeds_capacity`, the byte and token fields, `retryable: false`) whatever the current usage. One that fits alone but not now is not rejected: the route preflight lets it queue while other work is admitted (queued requests hold no memory and do not count), and the in-stream admission keeps it at the head (nothing overtakes it) until the admitted rows free memory; both checks share one predicate. A deferred request releases its restored prefix and its block-table refs while it waits, and its re-admission repeats the lookup. The block-table release can wait behind an in-flight prefill commit; it is keyed to the deferred attempt's table, so it never frees a table the request got since. The deferred head is not retried (and its prefix not restored again) on every step: it retries once an admitted row left (finished, aborted or paused), free memory rose by more than 2% of the admission line, or its backoff expired (0.25 s doubling per deferral, capped at 4 s); it keeps the head-of-line hold meanwhile, also while its release still waits behind a commit. Both checks price the same output budget: the route preflight uses the resolved `max_tokens` (request, model setting or server default; the engine default when an engine is called directly). With nothing admitted, or when the capacity cannot be estimated (no memory limit, unknown weights or KV dimensions), the older current-usage rejection applies; unknown weights are never cached and never produce a never-fits rejection. The server cases cover the 400 body on API and non-API routes, `GET /v1/omlx/capacity` (fields, 404/409, auth) and the `X-oMLX-Max-Context-Tokens` header on streaming and non-streaming chat completions. These cases run with memory scheduling on (see the memory scheduling gate tests above); off, there is no capacity estimate and the older current-usage rejection applies. +Run `python -m pytest -q tests/test_scheduler_capacity_gate.py tests/test_scheduler_capacity_vlm.py tests/test_scheduler_deferred_admission.py tests/test_server_context_capacity.py` to check the feasibility gate. A request whose weights + exact KV of prompt plus `max_tokens` + prefill transient exceed the capacity line (the tighter of the admission line and the prefill safety cap) is rejected with `ContextExceedsCapacityError` (HTTP 400, `omlx_code: context_exceeds_capacity`, the byte and token fields, `retryable: false`) whatever the current usage. One that fits alone but not now is not rejected: the route preflight lets it queue while other work is admitted (queued requests hold no memory and do not count), and the in-stream admission keeps it at the head (nothing overtakes it) until the admitted rows free memory; both checks share one predicate. A deferred request releases its restored prefix and its block-table refs while it waits, and its re-admission repeats the lookup. The block-table release can wait behind an in-flight prefill commit; it is keyed to the deferred attempt's table, so it never frees a table the request got since. The deferred head is not retried (and its prefix not restored again) on every step: it retries once an admitted row left (finished, aborted or paused), free memory rose by more than 2% of the admission line, or its backoff expired (0.25 s doubling per deferral, capped at 4 s); it keeps the head-of-line hold meanwhile, also while its release still waits behind a commit. Both checks price the same output budget: the route preflight uses the resolved `max_tokens` (request, model setting or server default; the engine default when an engine is called directly). With nothing admitted, or when the capacity cannot be estimated (no memory limit, unknown weights or KV dimensions), the older current-usage rejection applies; unknown weights are never cached and never produce a never-fits rejection. The server cases cover the 400 body on API and non-API routes, `GET /v1/omlx/capacity` (fields, 404/409, auth) and the `X-oMLX-Max-Context-Tokens` header on streaming and non-streaming chat completions. `tests/test_scheduler_capacity_vlm.py` builds a tiny real mlx-vlm Qwen3.5 model (vision tower plus hybrid language model) behind the real `VLMModelAdapter`: the adapter keeps the model in `_vlm_model`, which `nn.Module.parameters()` skips, so the weights are summed from the unwrapped model, each array once. It checks the capacity of that model and of the text model on the batched engine, that `kv_bytes_per_token` prices the TurboQuant prefill peak (full-width KV plus the quantized copy, the last full-attention layer kept full width when there is more than one), that quantized weights count their scales and biases, and that `max_tokens` 2,000,000 reaches the gate unclamped (no route clamps `max_tokens` to the context window) and is rejected as never-fits. These cases run with memory scheduling on (see the memory scheduling gate tests above); off, there is no capacity estimate and the older current-usage rejection applies. Mocked tests do not replace hardware validation: with a real model, send a prompt larger than `max_viable_context_tokens` and check for an immediate 400 with the fields, then send two prompts that each fit alone but not together and check that the second waits and completes without an error. diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 4b8868f7b5..41afc507c3 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -274,6 +274,38 @@ class _PreflightDeferredError(Exception): DEFERRED_ADMISSION_RETRY_MAX_S = 4.0 +def _weights_parameter_root(model: Any) -> Any: + """The module whose ``parameters()`` hold a scheduler model's weights. + + ``nn.Module.parameters()`` skips attributes whose name starts with an + underscore. ``VLMModelAdapter`` keeps the mlx-vlm model (vision tower, + language model, MTP head) in ``_vlm_model``, and the VLM-MTP proxy keeps + the adapter in ``_adapter``, so their own parameters are empty. Unwrap + both; any other model is its own root. + """ + + def own(node: Any, attr: str) -> Any: + # Own attributes only: proxies and mocks answer any getattr. + if isinstance(node, dict): # nn.Module stores children as items + return node.get(attr) + try: + return vars(node).get(attr) + except TypeError: + return None + + seen: set[int] = set() + node = model + while id(node) not in seen: + seen.add(id(node)) + inner = own(node, "_adapter") + if inner is None: + inner = own(node, "_vlm_model") + if inner is None: + break + node = inner + return node + + def _deferred_admission_backoff_s(attempts: int) -> float: """Seconds a head waits after its ``attempts``-th consecutive deferral.""" exponent = min(max(int(attempts), 1) - 1, 32) @@ -14133,11 +14165,16 @@ def _model_weights_bytes(self) -> int: return cached total = 0 try: - total = sum( - int(value.nbytes) - for _, value in tree_flatten(self.model.parameters()) + # Each array once: a wrapper may reach the same arrays twice (the + # VLM adapter holds the model and its language model). + arrays = { + id(value): int(value.nbytes) + for _, value in tree_flatten( + _weights_parameter_root(self.model).parameters() + ) if isinstance(value, mx.array) - ) + } + total = sum(arrays.values()) except Exception: # noqa: BLE001 - unknown model shape: no estimate total = 0 if total > 0: diff --git a/tests/test_scheduler_capacity_vlm.py b/tests/test_scheduler_capacity_vlm.py new file mode 100644 index 0000000000..d517cafbd7 --- /dev/null +++ b/tests/test_scheduler_capacity_vlm.py @@ -0,0 +1,256 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The never-fits gate on real VLM and text model structures. + +On ``VLMBatchedEngine`` the scheduler's model is the ``VLMModelAdapter``. It +keeps the mlx-vlm model in ``_vlm_model``, and ``nn.Module.parameters()`` +skips attributes that start with an underscore, so the weights summed to 0, +``capacity_snapshot`` returned None, ``/v1/omlx/capacity`` said +``available: false`` and a 60k prompt with ``max_tokens`` 2,000,000 passed the +route with HTTP 200 on a real model. + +These tests build a tiny but real mlx-vlm Qwen3.5 model (vision tower plus the +hybrid GDN/full-attention language model), wrap it in the real adapter, and +read the capacity the way the engine does. +""" + +import mlx.core as mx +import mlx.nn as nn +import pytest +from mlx.utils import tree_flatten +from mlx_vlm.models.qwen3_5 import Model as VLMModel +from mlx_vlm.models.qwen3_5 import ModelConfig +from test_scheduler_prefill_progress_commit import _tiny_hybrid_model + +from omlx.engine.base import preflight_max_tokens +from omlx.exceptions import ContextExceedsCapacityError +from omlx.models.vlm import VLMModelAdapter +from omlx.scheduler import Scheduler, SchedulerConfig + +MB = 1024**2 +TQ_BITS = 4.0 +HEAD_DIM = 16 +KV_HEADS = 1 +FULL_ATTENTION_LAYERS = 1 # two layers, full attention every second one + + +def _tiny_vlm_model(num_layers: int = 2) -> VLMModel: + mx.random.seed(5) + text = dict( + model_type="qwen3_5", + hidden_size=32, + intermediate_size=64, + num_hidden_layers=num_layers, + num_attention_heads=2, + num_key_value_heads=KV_HEADS, + head_dim=HEAD_DIM, + full_attention_interval=2, + vocab_size=32, + linear_num_value_heads=2, + linear_num_key_heads=2, + linear_key_head_dim=16, + linear_value_head_dim=16, + linear_conv_kernel_dim=4, + rms_norm_eps=1e-6, + max_position_embeddings=4096, + rope_parameters={ + "rope_type": "default", + "rope_theta": 10000.0, + "partial_rotary_factor": 1.0, + "mrope_section": [4, 2, 2], + }, + ) + vision = dict( + model_type="qwen3_5", + depth=1, + hidden_size=16, + intermediate_size=32, + out_hidden_size=32, + num_heads=2, + patch_size=2, + spatial_patch_size=2, + temporal_patch_size=1, + num_position_embeddings=16, + fullatt_block_indexes=[0], + ) + return VLMModel( + ModelConfig.from_dict( + dict( + model_type="qwen3_5", + text_config=text, + vision_config=vision, + vocab_size=32, + image_token_id=30, + video_token_id=31, + ) + ) + ) + + +def _unique_nbytes(module: nn.Module) -> int: + seen: dict[int, int] = {} + for _, value in tree_flatten(module.parameters()): + seen[id(value)] = int(value.nbytes) + return sum(seen.values()) + + +def _scheduler(model, tokenizer, *, tq_bits=TQ_BITS, capacity=160 * MB): + scheduler = Scheduler( + model=model, + tokenizer=tokenizer, + config=SchedulerConfig(max_num_seqs=4, paged_cache_block_size=0), + ) + if tq_bits is not None: + scheduler._turboquant_kv_bits = float(tq_bits) + scheduler._set_model_info_for_monitor() + # What the enforcer propagates: guard on, memory scheduling on, a + # capacity line. + scheduler._prefill_memory_guard = True + scheduler._memory_scheduling = True + scheduler._memory_hard_limit_bytes = capacity + scheduler._memory_hard_watermark_bytes = capacity + scheduler._prefill_headroom_safety = 1.0 + scheduler._current_usage_bytes = lambda **_kw: 0 + return scheduler + + +@pytest.fixture +def vlm(): + return _tiny_vlm_model() + + +def test_vlm_adapter_hides_its_model_from_parameters(vlm): + """The premise: the adapter alone reports no parameters at all.""" + adapter = VLMModelAdapter(vlm) + assert tree_flatten(adapter.parameters()) == [] + assert _unique_nbytes(vlm) > 0 + + +def test_capacity_snapshot_is_available_behind_the_real_vlm_adapter( + vlm, mock_tokenizer +): + scheduler = _scheduler(VLMModelAdapter(vlm), mock_tokenizer) + + snapshot = scheduler.capacity_snapshot(context_tokens=1000, max_tokens=500) + + assert snapshot is not None + # Vision tower and language model, each array counted once (the adapter + # also holds ``_language_model``, the same arrays again). + assert snapshot["weights_bytes"] == _unique_nbytes(vlm) + assert snapshot["capacity_bytes"] == scheduler._capacity_limit_bytes() > 0 + assert snapshot["requested_context_tokens"] == 1000 + assert snapshot["requested_max_tokens"] == 500 + assert snapshot["required_bytes"] > snapshot["weights_bytes"] + assert snapshot["max_viable_context_tokens"] > 0 + + +def test_capacity_kv_per_token_prices_the_turboquant_prefill_peak(vlm, mock_tokenizer): + """TurboQuant quantizes after prefill: the peak holds the full-width KV + and the quantized copy. A lone full-attention layer is quantized (the + last-layer skip applies only with more than one).""" + scheduler = _scheduler(VLMModelAdapter(vlm), mock_tokenizer) + + snapshot = scheduler.capacity_snapshot() + + base = 2.0 # bf16/fp16 activations + tq = TQ_BITS / 8.0 + 2.0 / HEAD_DIM + per_token = FULL_ATTENTION_LAYERS * KV_HEADS * HEAD_DIM * 2 * (base + tq) + assert snapshot["kv_bytes_per_token"] == round(per_token) + monitor = scheduler.memory_monitor + assert monitor.estimate_prompt_kv_bytes(1024) == pytest.approx(1024 * per_token) + + +def test_capacity_kv_per_token_with_turboquant_on_two_full_attention_layers( + mock_tokenizer, +): + """Same check where TurboQuant actually shrinks a layer: four layers, two + full attention, the last one kept at full width.""" + four = _tiny_vlm_model(num_layers=4) + scheduler = _scheduler(VLMModelAdapter(four), mock_tokenizer) + + snapshot = scheduler.capacity_snapshot() + + base = 2.0 + tq = TQ_BITS / 8.0 + 2.0 / HEAD_DIM + stored = (1 * tq + base) / 2 # one quantized layer, the last at full width + per_token = 2 * KV_HEADS * HEAD_DIM * 2 * (base + stored) + assert snapshot is not None + assert snapshot["weights_bytes"] == _unique_nbytes(four) + assert snapshot["kv_bytes_per_token"] == round(per_token) + + +def test_quantized_vlm_weights_count_scales_and_biases(vlm, mock_tokenizer): + nn.quantize(vlm.language_model, group_size=32, bits=4) + scheduler = _scheduler(VLMModelAdapter(vlm), mock_tokenizer) + + weights = scheduler._model_weights_bytes() + + assert weights == _unique_nbytes(vlm) + names = {name for name, _ in tree_flatten(vlm.parameters())} + assert any(name.endswith(".scales") for name in names) + + +def test_text_model_on_the_batched_engine_has_a_capacity(mock_tokenizer): + model = _tiny_hybrid_model() + scheduler = _scheduler(model, mock_tokenizer) + + snapshot = scheduler.capacity_snapshot(context_tokens=100, max_tokens=10) + + assert snapshot is not None + assert snapshot["weights_bytes"] == _unique_nbytes(model) + + +def test_max_tokens_two_million_is_priced_unclamped_and_never_fits(vlm, mock_tokenizer): + """No route clamps max_tokens to the context window (only the prompt is + validated), so the gate prices the value the request asked for and + rejects it in one admission with the structured error.""" + scheduler = _scheduler(VLMModelAdapter(vlm), mock_tokenizer) + max_tokens = preflight_max_tokens({"max_tokens": 2_000_000}) + assert max_tokens == 2_000_000 + + with pytest.raises(ContextExceedsCapacityError) as excinfo: + scheduler.preflight_or_raise( + num_prompt_tokens=60_000, + request_id="never", + max_tokens=max_tokens, + ) + + fields = excinfo.value.capacity_fields + assert fields["requested_context_tokens"] == 60_000 + assert fields["requested_max_tokens"] == 2_000_000 + assert fields["required_bytes"] > fields["capacity_bytes"] + assert fields["capacity_bytes"] == scheduler._capacity_limit_bytes() + assert 0 < fields["max_viable_context_tokens"] < 2_060_000 + + +def test_the_same_prompt_with_a_small_max_tokens_passes_the_gate(vlm, mock_tokenizer): + scheduler = _scheduler(VLMModelAdapter(vlm), mock_tokenizer) + + scheduler.preflight_or_raise( + num_prompt_tokens=60_000, request_id="fits", max_tokens=256 + ) + + +@pytest.mark.parametrize("engine_cls", ["vlm", "batched"]) +def test_engine_capacity_reaches_the_scheduler_behind_the_core( + engine_cls, vlm, mock_tokenizer +): + """No engine type check stands in the way: both engines read the + scheduler behind ``_engine.engine`` (AsyncEngineCore -> EngineCore).""" + from types import SimpleNamespace + + from omlx.engine.batched import BatchedEngine + from omlx.engine.vlm import VLMBatchedEngine + + cls = VLMBatchedEngine if engine_cls == "vlm" else BatchedEngine + model = VLMModelAdapter(vlm) if engine_cls == "vlm" else _tiny_hybrid_model() + scheduler = _scheduler(model, mock_tokenizer) + engine = SimpleNamespace( + _engine=SimpleNamespace(engine=SimpleNamespace(scheduler=scheduler)) + ) + engine._capacity_scheduler = lambda: cls._capacity_scheduler(engine) + + snapshot = cls.capacity_snapshot(engine, context_tokens=10, max_tokens=5) + hint = cls.max_context_tokens_hint(engine) + + assert snapshot is not None and snapshot["weights_bytes"] > 0 + assert isinstance(hint, int) and hint == snapshot["max_viable_context_tokens"] From ac6b63c7b4188a4eb17ebcae2d76f204f3a17ecb Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Fri, 9 Oct 2026 13:59:35 -0600 Subject: [PATCH 34/46] fix(scheduler): report a resumed park's own committed blocks as resumed prefill Upstream #4383 reports only genuine prefix-cache hits as cached tokens: prefill work a request computed itself and kept across a pause is counted in prefill_resumed_tokens and subtracted from usage. A prefill park drops the live cache and the re-admission lookup restores the blocks the request committed itself, so usage counted that resumed work as a cache hit. The park now records the prompt tokens its lookups found (park_cache_hit_tokens); every later lookup sets prefill_resumed_tokens to the restored tokens beyond them. A fits-later deferral that releases the restore also clears prefill_resumed_tokens, as upstream's resets do. --- omlx/request.py | 4 ++ omlx/scheduler.py | 10 +++++ tests/test_scheduler_capacity_gate.py | 4 ++ tests/test_scheduler_park.py | 57 +++++++++++++++++++++++++++ 4 files changed, 75 insertions(+) diff --git a/omlx/request.py b/omlx/request.py index 8ed8d4bd7b..f998a34b14 100644 --- a/omlx/request.py +++ b/omlx/request.py @@ -271,6 +271,10 @@ def vlm_extra_key_ranges_for_cache( park_count: int = 0 # Parks taken so far (bounded by max_parks_per_request) # Prompt tokens a prefill park left committed in the prefix cache. park_committed_tokens: int = 0 + # Prompt tokens the request's own lookups found before its first park. + # A re-admission restores its committed blocks too; only these count as + # cached in usage, the rest is resumed prefill (#4383). + park_cache_hit_tokens: int | None = None # Request-scoped tool schemas used by protocol output parsers. tools: list[dict[str, Any]] | None = None diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 41afc507c3..afa393fa66 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -13280,6 +13280,10 @@ def _park_prefill(self, request: Request, reason: str) -> None: committed = table.num_tokens if table else 0 self._prefill_states.pop(rid, None) self.prefilling = deque(r for r in self.prefilling if r.request_id != rid) + # Its committed blocks are resumed work, not a cache hit (#4383). + request.park_cache_hit_tokens = max( + 0, (request.cached_tokens or 0) - request.prefill_resumed_tokens + ) self._reset_request_for_reprefill(request) request.parked = True request.parked_at = time.monotonic() @@ -14212,6 +14216,7 @@ def _release_deferred_admission(self, request: "Request") -> None: request.prompt_cache = None request.block_table = None request.cached_tokens = 0 + request.prefill_resumed_tokens = 0 request.shared_prefix_blocks = 0 request.remaining_tokens = request.prompt_token_ids request.specprefill_indices = None @@ -14920,6 +14925,11 @@ def _schedule_waiting_scan( # #2183/#2197 chunk-view and #2235 batch-KV-mutation fixes. with mx.stream(self._stream): self._prepare_prefix_cache_for_request(request) + if request.park_cache_hit_tokens is not None: + # Blocks it committed before a park are resumed work (#4383). + request.prefill_resumed_tokens = max( + 0, (request.cached_tokens or 0) - request.park_cache_hit_tokens + ) if request.parked: self._finish_park_resume(request) diff --git a/tests/test_scheduler_capacity_gate.py b/tests/test_scheduler_capacity_gate.py index be72cf67c3..cb81c6d8b3 100644 --- a/tests/test_scheduler_capacity_gate.py +++ b/tests/test_scheduler_capacity_gate.py @@ -534,6 +534,9 @@ def test_a_deferred_request_releases_its_prefix_restore_and_readmits( def prepare(request): real_prepare(request) + if not restores: + # As a once-parked request's re-admission sets it (#4383). + request.prefill_resumed_tokens = 1 restores.append(request.cached_tokens) monkeypatch.setattr(scheduler, "_prepare_prefix_cache_for_request", prepare) @@ -552,6 +555,7 @@ def prepare(request): assert later.prompt_cache is None assert later.block_table is None assert later.cached_tokens == 0 + assert later.prefill_resumed_tokens == 0 assert rig.paged.get_block_table("later") is None assert "later" not in scheduler._prefix_cache_prepared diff --git a/tests/test_scheduler_park.py b/tests/test_scheduler_park.py index 81ceead2cd..7ab229a1d9 100644 --- a/tests/test_scheduler_park.py +++ b/tests/test_scheduler_park.py @@ -431,6 +431,63 @@ def test_resume_restores_the_committed_boundary_and_matches_an_uninterrupted_run rig.close() +def test_a_resumed_park_reports_only_its_original_prefix_hit_as_cached( + tmp_path, mock_tokenizer +): + """#4383: blocks the request committed itself are resumed work, not cache. + + The re-admission lookup restores them (``cached_tokens`` counts every KV + token), but usage reports only what the first lookup found: none for a + cold prompt, through a second park as well. + """ + rig = make_rig(tmp_path, mock_tokenizer) + try: + old, young = prefill_two(rig) + assert young.cached_tokens == 0 + for park in (1, 2): + rig.scheduler.request_park_prefill() + step(rig) + rig.drain() + assert young.parked and young.park_count == park + finish_ok_polls(rig, 3) + step_until(rig, lambda: "young" in prefilling_ids(rig)) + assert young.cached_tokens >= park * BLOCK + assert young.prefill_resumed_tokens == young.cached_tokens + if park == 1: + step_until(rig, lambda: rig.table_tokens("young") >= 2 * BLOCK) + outputs = run_to_completion(rig, [old, young]) + finished = [o for o in outputs if o.request_id == "young" and o.finished] + assert finished and not finished[-1].error + assert finished[-1].cached_tokens == 0 + finally: + rig.close() + + +def test_a_resumed_park_keeps_a_genuine_prefix_hit_as_cached(tmp_path, mock_tokenizer): + rig = make_rig(tmp_path, mock_tokenizer) + try: + warm = submit(rig, "warm", PROMPT_B[: 3 * BLOCK + 1], arrival=0.5) + run_to_completion(rig, [warm]) + old, young = prefill_two(rig) + hit = young.cached_tokens + assert hit >= 2 * BLOCK + step_until(rig, lambda: rig.table_tokens("young") >= hit + BLOCK) + rig.scheduler.request_park_prefill() + step(rig) + rig.drain() + assert young.parked + finish_ok_polls(rig, 3) + step_until(rig, lambda: "young" in prefilling_ids(rig)) + assert young.cached_tokens >= hit + BLOCK + assert young.prefill_resumed_tokens == young.cached_tokens - hit + outputs = run_to_completion(rig, [old, young]) + finished = [o for o in outputs if o.request_id == "young" and o.finished] + assert finished and not finished[-1].error + assert finished[-1].cached_tokens == hit + finally: + rig.close() + + def test_the_cold_retry_guard_is_bypassed_for_a_parked_request( tmp_path, mock_tokenizer ): From 3c362db794f7db72509919505c8a471adaa8211a Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Tue, 6 Oct 2026 01:25:14 -0600 Subject: [PATCH 35/46] fix(scheduler): resume parked requests under the hard watermark without thrashing Under forced memory pressure, a lone 130k request decoding over the hard watermark was paused, resumed on the next step by the park hold's nothing-admitted escape (which never asked whether it fit), paused again, and aborted once its park budget (3/3) ran out. No memory-aware resume line was logged in any run. - A parked head is measured whenever it has an estimate. Beside admitted work it resumes only under the admission line minus 2% and the hard watermark minus 5%. - Anti-thrash: a head parked or paused twice within 60 s waits, even when it fits, for an admitted row to leave or free memory to rise by 5%. - With nothing admitted, a head that fits only under the ceiling, keeps being paused while alone, or waited PARK_MAX_HOLD_S resumes as the solo request: nothing else is admitted beside it, and the enforcer neither pauses nor aborts it below the emergency threshold while every other engine is idle. The emergency brake still aborts it. - Decode pauses get their own budget, max_decode_pauses_per_request (default 8, OMLX_MAX_DECODE_PAUSES_PER_REQUEST): a pause keeps every generated token, while the abort after an exhausted budget loses them. Real-rig tests with the real enforcer replay the readings of that run: every request completes with its uninterrupted greedy output and no abort. --- docs/TESTING.md | 4 +- omlx/process_memory_enforcer.py | 66 +++ omlx/request.py | 8 +- omlx/scheduler.py | 287 ++++++++-- omlx/settings.py | 21 +- tests/test_memory_resume_thrash.py | 524 +++++++++++++++++++ tests/test_scheduler_decode_pause.py | 6 +- tests/test_scheduler_park_resume_priority.py | 9 +- tests/test_settings.py | 1 + 9 files changed, 884 insertions(+), 42 deletions(-) create mode 100644 tests/test_memory_resume_thrash.py diff --git a/docs/TESTING.md b/docs/TESTING.md index f779106eac..3b15dc8832 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -255,8 +255,10 @@ Mocked tests do not replace hardware validation: with a real Qwen VL model, send # Memory-pressure park tests -Run `python -m pytest -q tests/test_scheduler_park.py tests/test_scheduler_park_resume_priority.py tests/test_process_memory_enforcer.py tests/test_settings.py -k "park or Park"` to check `scheduler.memory_pressure_park` (also `OMLX_MEMORY_PRESSURE_PARK`; off by default), `scheduler.max_parks_per_request` (`OMLX_MAX_PARKS_PER_REQUEST`, default 3) and `scheduler.park_resume_ok_polls` (`OMLX_PARK_RESUME_OK_POLLS`, default 3). With the setting on, hard (non-emergency) memory pressure parks the most recent chunked-prefill request instead of aborting: it is re-queued without an error, keeps its stream, and resumes in arrival order once the estimated free memory under the admission line covers its need plus a 2% margin (a paused decode: the KV of its final length plus one decode step; a parked prefill: the KV of prompt plus max_tokens plus the prefill transient; KV that running prefills still have to allocate does not count as free), restoring the blocks that `prefill_progress_commit_blocks` committed (without it the park resumes cold). The oldest admitted request is protected, parked blocks are pinned against eviction until the resume, and the legacy abort remains for emergency pressure, nothing parkable, an exhausted park budget, or external-loop (non-chunked, VLM) and SpecPrefill prefills, which cannot be parked between steps. While the parked head waits, nothing newer is admitted, so a smaller request cannot take the headroom the head waits for; once the head fits, newer requests are admitted behind it. The head never resumes on hard pressure, and the nothing-admitted and stale-monitor escapes still release it. When no estimate is available (no admission line or no model dimensions), the older rule applies: enough consecutive ok pressure polls, or the max-hold escape. The scheduler cases run on a small Qwen3.5 hybrid model and compare a resumed request's output with an uninterrupted run; its prompts must stay below the tiny vocabulary of 32 ids, or the embedding read is undefined and the output is nondeterministic. +Run `python -m pytest -q tests/test_scheduler_park.py tests/test_scheduler_park_resume_priority.py tests/test_process_memory_enforcer.py tests/test_settings.py -k "park or Park"` to check `scheduler.memory_pressure_park` (also `OMLX_MEMORY_PRESSURE_PARK`; off by default), `scheduler.max_parks_per_request` (`OMLX_MAX_PARKS_PER_REQUEST`, default 3) and `scheduler.park_resume_ok_polls` (`OMLX_PARK_RESUME_OK_POLLS`, default 3). With the setting on, hard (non-emergency) memory pressure parks the most recent chunked-prefill request instead of aborting: it is re-queued without an error, keeps its stream, and resumes in arrival order once the estimated free memory under the admission line covers its need plus a 2% margin (a paused decode: the KV of its final length plus one decode step; a parked prefill: the KV of prompt plus max_tokens plus the prefill transient; KV that running prefills still have to allocate does not count as free), restoring the blocks that `prefill_progress_commit_blocks` committed (without it the park resumes cold). The oldest admitted request is protected, parked blocks are pinned against eviction until the resume, and the legacy abort remains for emergency pressure, nothing parkable, an exhausted park budget, or external-loop (non-chunked, VLM) and SpecPrefill prefills, which cannot be parked between steps. While the parked head waits, nothing newer is admitted, so a smaller request cannot take the headroom the head waits for; once the head fits, newer requests are admitted behind it. The head never resumes on hard pressure; the stale-monitor escape still releases it, and with nothing admitted it resumes only when it fits (see the resume-thrash tests below). When no estimate is available (no admission line or no model dimensions), the older rule applies: enough consecutive ok pressure polls, or the max-hold escape. The scheduler cases run on a small Qwen3.5 hybrid model and compare a resumed request's output with an uninterrupted run; its prompts must stay below the tiny vocabulary of 32 ids, or the embedding read is undefined and the output is nondeterministic. Run `python -m pytest -q tests/test_memory_single_victim.py tests/test_process_memory_enforcer.py -k "single or victim"` to check `memory.abort_single_victim` (env `OMLX_MEMORY_ABORT_SINGLE_VICTIM`, default off). On the non-emergency hard path with nothing parkable, the enforcer aborts only the live request holding the most KV (newest arrival on ties), waits for its memory to drain before choosing another, and keeps the rest running. Emergency pressure and model unload still abort everything. Off keeps the abort-all. +Run `python -m pytest -q tests/test_memory_resume_thrash.py` to check that a paused request does not thrash. Beside admitted work a parked head resumes only when current usage plus in-flight prefill reserve plus its need stays under the admission line minus 2% and under the hard watermark minus 5% (`PARK_RESUME_HARD_MARGIN_FRACTION`); the enforcer pauses at the watermark, so resuming right up to it pauses the request again at the next poll. A head parked or paused twice within 60 s (`PARK_THRASH_PAUSES`, `PARK_THRASH_WINDOW_S`) waits, even when it fits, until an admitted row leaves (finishes, aborts or pauses) or free memory rises by more than 5% of the resume line. With nothing admitted, a head that fits resumes; one that fits only under the ceiling (the scheduler hard limit and the prefill safety cap, minus 2%), one that keeps being paused while alone, or one that waited `PARK_MAX_HOLD_S` resumes as the solo request: nothing else is admitted while it runs, and at hard pressure below the emergency threshold the enforcer neither pauses nor aborts it (only when every other loaded engine is idle). The emergency brake beyond the ceiling still aborts it. Decode pauses have their own budget, `scheduler.max_decode_pauses_per_request` (`OMLX_MAX_DECODE_PAUSES_PER_REQUEST`, default 8), apart from the prefill park budget: a decode pause keeps every generated token exactly, while the abort that follows an exhausted budget loses them all. The real-rig cases wire the real enforcer to the real scheduler and script the memory readings of a forced-pressure run (a lone request decoding over the hard watermark; three requests one at a time; two rows where the newer one is paused twice): every request completes with its uninterrupted greedy output and no abort. + Mocked tests do not replace hardware validation: with a real model, run three concurrent long prompts under a ceiling too low for all of them and check that each completes with the park/resume log lines and a cached count close to the last commit, and that no client sees a memory error. diff --git a/omlx/process_memory_enforcer.py b/omlx/process_memory_enforcer.py index 54e32a33ed..e839863c60 100644 --- a/omlx/process_memory_enforcer.py +++ b/omlx/process_memory_enforcer.py @@ -568,6 +568,8 @@ def __init__( # settled yet; no other victim is chosen meanwhile. See # _abort_single_victim. self._draining_victim: _DrainingVictim | None = None + # The solo request last logged as exempt (one line per request). + self._solo_logged: str | None = None # Last value passed to mx.set_wired_limit (0 if not yet applied # or the call failed). Used by the admin dashboard to surface a # warning when the kernel iogpu.wired_limit_mb is below this. @@ -1911,6 +1913,57 @@ def _request_decode_pause(self) -> int: return 1 return 0 + def _solo_exempt_request(self) -> tuple[str, str] | None: + """(model id, request id) of a request running alone, else None. + + A scheduler reports its solo request (``memory_pressure_solo_request``) + only while it is that scheduler's only admitted request. It is exempt + from hard-pressure pauses and aborts only when nothing else runs in + the process either: every other loaded engine is idle. Pausing it + would resume it at once (nothing else is admitted while it waits), + so below the emergency threshold the enforcer leaves it running; the + emergency brake beyond the ceiling still aborts it. + """ + solo: tuple[str, str] | None = None + for model_id, entry in self._engine_pool._entries.items(): + engine = getattr(entry, "engine", None) + if engine is None: + continue + scheduler = self._resolve_scheduler(entry) + probe = getattr(scheduler, "memory_pressure_solo_request", None) + rid = None + if callable(probe): + try: + rid = probe() + except Exception: # noqa: BLE001 - no exemption on a failing probe + return None + if isinstance(rid, str): + if solo is not None: + return None + solo = (model_id, rid) + continue + active = getattr(engine, "has_active_requests", None) + try: + busy = bool(active()) if callable(active) else True + except Exception: # noqa: BLE001 + busy = True + if busy: + return None + return solo + + def _log_solo_exempt(self, solo: tuple[str, str], ceiling: int) -> None: + model_id, rid = solo + if self._solo_logged == rid: + return + self._solo_logged = rid + logger.warning( + "Hard memory pressure: %s runs alone (solo) on '%s'; it is not " + "paused or aborted below the emergency threshold (ceiling %s)", + rid, + model_id, + _format_gb(ceiling), + ) + @staticmethod def _victim_abort_pending(engine: Any, request_id: str) -> bool: """Whether the engine still holds the victim (abort not run yet). @@ -2215,6 +2268,16 @@ async def _check_and_enforce(self) -> None: self._walk_store_cache_caps() return + # A request running alone is neither paused nor aborted below the + # emergency threshold: nothing else could use the memory it frees. + solo = ( + self._solo_exempt_request() + if new_level == "hard" and not emergency + else None + ) + if solo is not None: + self._log_solo_exempt(solo, ceiling) + # Park before abort: a scheduler with a parkable prefill victim pauses # it (work already done survives in the prefix cache) and the abort # below only runs when nothing is left to park, the deferral budget is @@ -2222,6 +2285,7 @@ async def _check_and_enforce(self) -> None: if ( new_level == "hard" and not emergency + and solo is None and self._park_deferred_polls < self._PARK_DEFER_POLLS_MAX ): parked_on = self._request_scheduler_park() @@ -2292,6 +2356,8 @@ async def _check_and_enforce(self) -> None: # No non-pinned victim. Loaded models are pinned or no loaded # engines exist at all. if new_level == "hard": + if solo is not None: + break busy_victim = self._find_lru_busy_non_pinned_victim_locked() if busy_victim is not None: entry = self._engine_pool._entries.get(busy_victim) diff --git a/omlx/request.py b/omlx/request.py index f998a34b14..bca8dd7bd0 100644 --- a/omlx/request.py +++ b/omlx/request.py @@ -268,7 +268,13 @@ def vlm_extra_key_ranges_for_cache( # committed prefix. ``parked`` is True from the park until the resume. parked: bool = False parked_at: float = 0.0 # time.monotonic() of the latest park - park_count: int = 0 # Parks taken so far (bounded by max_parks_per_request) + # Parks and decode pauses taken so far (the sequence number of the next + # one's storage id). Prefill parks are bounded by max_parks_per_request, + # decode pauses by max_decode_pauses_per_request. + park_count: int = 0 + decode_pause_count: int = 0 # Decode pauses among ``park_count`` + # time.monotonic() of each park or decode pause, for the thrash rule. + park_times: list[float] = field(default_factory=list) # Prompt tokens a prefill park left committed in the prefix cache. park_committed_tokens: int = 0 # Prompt tokens the request's own lookups found before its first park. diff --git a/omlx/scheduler.py b/omlx/scheduler.py index afa393fa66..864aa32848 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -315,6 +315,15 @@ def _deferred_admission_backoff_s(attempts: int) -> float: ) +@dataclass +class _ParkThrashWait: + """The memory picture a thrashing parked head waits to see change.""" + + park_count: int + free_bytes: int + admitted_ids: frozenset[str] + + @dataclass class _DeferredAdmissionWait: """The memory picture a fits-later head deferred on.""" @@ -1501,6 +1510,20 @@ def _is_turboquant_kv_family_cache(cache_obj: Any) -> bool: # Free memory a parked request must find beyond its own estimated need before # it resumes, as a fraction of the admission line (estimate error margin). PARK_RESUME_MARGIN_FRACTION = 0.02 +# Hysteresis under the hard watermark: a parked head resumes beside admitted +# work only when current + reserve + need stays this fraction of the hard +# watermark below it. The enforcer pauses at the watermark; resuming right up +# to it re-triggers the pause at the next poll (seen under forced memory +# pressure: pause, resume, pressure, pause until the park budget ran out and +# the request was aborted). +PARK_RESUME_HARD_MARGIN_FRACTION = 0.05 +# Anti-thrash: a head parked or paused this many times within the window +# waits for a stronger signal than "fits" before it resumes beside admitted +# work: an admitted row left (finished, aborted, paused) or free memory rose +# by more than PARK_THRASH_FREE_DELTA_FRACTION of the resume line. +PARK_THRASH_PAUSES = 2 +PARK_THRASH_WINDOW_S = 60.0 +PARK_THRASH_FREE_DELTA_FRACTION = 0.05 # Seconds between "waiting" log lines for the same parked head. _PARK_WAIT_LOG_INTERVAL_S = 30.0 # Saturation value of ``_polls_since_resume``: "long enough since the last @@ -2140,6 +2163,10 @@ class SchedulerConfig: # path when its last media token is inside the cached prefix (decode # fairness, parkable). Off keeps the external media prefill. media_text_suffix_chunked: bool = False + # Decode pauses are budgeted apart from prefill parks, and more generously: + # a pause keeps every generated token exactly (no re-prefill), while the + # abort that follows an exhausted budget loses them all. + max_decode_pauses_per_request: int = 8 park_resume_ok_polls: int = 3 # Paged cache settings (internal defaults) @@ -2546,6 +2573,14 @@ def __init__( self._park_resume_fit: tuple[str, int, int] | None = None self._park_wait_logged: tuple[str, float] | None = None self._park_pins: dict[str, _ParkPins] = {} + # Anti-thrash records of parked heads (see _park_thrash_holds). + self._park_thrash_waits: dict[str, _ParkThrashWait] = {} + # Solo run: a request that fits under the ceiling only when nothing + # else runs. While it is admitted nothing else is admitted, and the + # enforcer does not pause or abort it below the emergency threshold + # (see memory_pressure_solo_request). Read by the enforcer thread. + self._solo_request_id: str | None = None + self._solo_logged: tuple[str, int] | None = None # Decode pause: ids asked for by request_decode_pause (thread-safe set, # drained at step start) and the resume record of each paused row. self._pending_decode_pauses: set[str] = set() @@ -12302,9 +12337,9 @@ def _park_resume_allowed(self, head: "Request | None" = None) -> bool: """Whether a parked request may resume now. With no live pressure monitor, always (never starve a parked - request). Otherwise, when ``head`` has a memory estimate, once the - free memory covers its need plus a margin; without an estimate, once - enough consecutive ok polls were seen. + request). Otherwise, when ``head`` has a memory estimate, once it + fits under the resume line; without an estimate, once enough + consecutive ok polls were seen. """ if self._park_signal_stale(): return True @@ -12318,48 +12353,215 @@ def _park_hold_applies(self, head: "Request") -> bool: """Whether a parked head still blocks admission. The hold is the head's reservation: nothing newer is admitted while - it waits, so nothing consumes the headroom it waits for. It never - applies when nothing is admitted (admission must be able to recover) - or without a live pressure monitor. With a memory estimate the head - resumes when it fits. Without one it resumes after an ok-poll streak, - or past PARK_MAX_HOLD_S unless the last pressure was hard; that - escape also waits ``park_resume_ok_polls`` polls after the previous - resume. Every escape resumes one request per scheduling pass, so a - burst of resumes cannot re-trigger hard pressure. + it waits, so nothing consumes the headroom it waits for. Without a + live pressure monitor it never applies. With a memory estimate + (``_park_resume_verdict``): + + - beside admitted work the head resumes only when it fits under the + hard watermark minus the hysteresis margin, and a head that was + parked or paused twice within PARK_THRASH_WINDOW_S also waits for + an admitted row to leave or free memory to rise (anti-thrash); + - with nothing admitted it resumes when it fits; when it fits only + under the ceiling, or it keeps being paused while alone, it resumes + as the solo request (``_mark_solo``): nothing else is admitted + while it runs and the enforcer leaves it alone below the emergency + threshold, so pausing it again cannot loop. One that does not fit + even alone waits at most PARK_MAX_HOLD_S, then runs solo. + + Without an estimate, the older rules apply: nothing admitted + releases the head; otherwise an ok-poll streak, or past + PARK_MAX_HOLD_S unless the last pressure was hard (that escape also + waits ``park_resume_ok_polls`` polls after the previous resume). + Every escape resumes one request per scheduling pass. """ if self._park_resumed_this_pass: return True - if not self._num_admitted_requests() or self._park_signal_stale(): + if self._park_signal_stale(): return False - fit = self._park_memory_fit(head) - if fit is not None: - return not fit - if self._park_ok_polls_met(): + admitted = self._num_admitted_requests() + verdict = self._park_resume_verdict(head) + if verdict is None: + if not admitted: + return False + if self._park_ok_polls_met(): + return False + need = max(1, getattr(self.config, "park_resume_ok_polls", 3)) + held_s = time.monotonic() - head.parked_at + if held_s >= PARK_MAX_HOLD_S and self._last_pressure_level != "hard": + return self._polls_since_resume < need + return True + if admitted: + if verdict != "fits": + return True + return self._park_thrash_holds(head) + if verdict == "fits" and not self._park_thrashing(head): + return False + if verdict in ("fits", "solo"): + self._mark_solo(head, verdict) + return False + if time.monotonic() - head.parked_at >= PARK_MAX_HOLD_S: + self._mark_solo(head, "max_hold") return False - need = max(1, getattr(self.config, "park_resume_ok_polls", 3)) - held_s = time.monotonic() - head.parked_at - if held_s >= PARK_MAX_HOLD_S and self._last_pressure_level != "hard": - return self._polls_since_resume < need return True def _park_memory_fit(self, head: "Request") -> bool | None: - """Whether the free memory covers ``head``'s need plus the margin. - - None when either side cannot be estimated (the caller falls back to - the ok-poll rule). A head never resumes on hard pressure, whatever - the estimate says. Logs the wait (rate-limited) and records the fit - for the resume log. + """Whether ``head`` fits under the resume line (None: no estimate).""" + verdict = self._park_resume_verdict(head) + return None if verdict is None else verdict == "fits" + + def _park_resume_lines(self) -> tuple[int, int] | None: + """(fit line, solo line) a parked head is measured against. + + The fit line is the admission line minus the estimate margin, and + never above the hard watermark minus the hysteresis margin: the + enforcer pauses at the watermark, so a head resumed right up to it + is paused again at the next poll. The solo line is what a request + running alone must stay under: the ceiling (and the prefill safety + cap) minus the estimate margin. None without an admission line. + """ + admission = self._admission_limit_bytes() + if admission <= 0: + return None + fit_line = admission - int(admission * PARK_RESUME_MARGIN_FRACTION) + watermark = self._memory_hard_watermark_bytes + if watermark > 0: + fit_line = min( + fit_line, + watermark - int(watermark * PARK_RESUME_HARD_MARGIN_FRACTION), + ) + ceilings = [ + v + for v in (self._memory_hard_limit_bytes, self._prefill_abort_cap()) + if v > 0 + ] + ceiling = min(ceilings) if ceilings else admission + solo_line = max(fit_line, ceiling - int(ceiling * PARK_RESUME_MARGIN_FRACTION)) + return fit_line, solo_line + + def _park_resume_verdict(self, head: "Request") -> str | None: + """Where ``head`` stands: "fits", "solo", "wait", or None. + + "fits": current + in-flight reserve + need is under the fit line. + "solo": only under the solo line (the ceiling). "wait": neither, or + the last pressure poll was hard (memory may still be draining). None + when need or the lines cannot be estimated. Logs the wait + (rate-limited) and records a fit for the resume log. """ need = self._parked_resume_need_bytes(head) - free = self._park_free_bytes() - if need is None or free is None: + lines = self._park_resume_lines() + if need is None or lines is None: return None - margin = int(self._admission_limit_bytes() * PARK_RESUME_MARGIN_FRACTION) - if self._last_pressure_level == "hard" or free < need + margin: + fit_line, solo_line = lines + used = self._current_usage_bytes() + self._inflight_prefill_reserve_bytes() + free = fit_line - used + if self._last_pressure_level == "hard" or used + need > solo_line: self._log_park_wait(head.request_id, need, free) - return False + return "wait" + if need > free: + self._log_park_wait(head.request_id, need, free) + return "solo" self._park_resume_fit = (head.request_id, need, free) - return True + return "fits" + + def _park_thrashing(self, head: "Request") -> bool: + """Parked or paused PARK_THRASH_PAUSES times within the window.""" + now = time.monotonic() + recent = [t for t in head.park_times if now - t <= PARK_THRASH_WINDOW_S] + return len(recent) >= PARK_THRASH_PAUSES + + def _park_thrash_holds(self, head: "Request") -> bool: + """Whether a thrashing head that fits still waits (beside admitted work). + + The first time it fits after its latest pause, the memory picture + (free bytes under the fit line, admitted rows) is recorded and it + waits. It resumes once an admitted row left (finished, aborted or + paused) or free memory rose by more than + PARK_THRASH_FREE_DELTA_FRACTION of the fit line. + """ + if not self._park_thrashing(head): + return False + rid = head.request_id + lines = self._park_resume_lines() + fit_line = lines[0] if lines is not None else 0 + free = fit_line - ( + self._current_usage_bytes() + self._inflight_prefill_reserve_bytes() + ) + admitted_ids = self._admitted_request_ids() + for stale in [ + r for r in self._park_thrash_waits if r != rid and r not in self.requests + ]: + self._park_thrash_waits.pop(stale, None) + wait = self._park_thrash_waits.get(rid) + if wait is None or wait.park_count != head.park_count: + self._park_thrash_waits[rid] = _ParkThrashWait( + park_count=head.park_count, + free_bytes=free, + admitted_ids=admitted_ids, + ) + logger.info( + "Parked request %s was paused %d times within %.0f s; it " + "resumes when a running request finishes or pauses, or free " + "memory rises by %.1f GB", + rid, + len(head.park_times), + PARK_THRASH_WINDOW_S, + fit_line * PARK_THRASH_FREE_DELTA_FRACTION / 1024**3, + ) + return True + if not wait.admitted_ids <= admitted_ids: + return False + return free - wait.free_bytes <= int(fit_line * PARK_THRASH_FREE_DELTA_FRACTION) + + def _mark_solo(self, head: "Request", why: str) -> None: + """Let ``head`` resume as the solo request (nothing else admitted).""" + self._solo_request_id = head.request_id + key = (head.request_id, head.park_count) + if self._solo_logged == key: + return + self._solo_logged = key + reasons = { + "solo": "it fits under the ceiling only with nothing else running", + "fits": "it was paused again while running alone", + "max_hold": "it waited the longest hold while nothing ran", + } + logger.info( + "Resuming parked request %s alone (solo): %s; nothing else is " + "admitted until it finishes, and memory pressure below the " + "emergency threshold does not pause it again", + head.request_id, + reasons.get(why, why), + ) + + def _solo_request(self) -> "Request | None": + """The live solo request (admitted, not parked), clearing a stale mark.""" + rid = self._solo_request_id + if rid is None: + return None + request = self.requests.get(rid) + if request is None or request.is_finished(): + self._solo_request_id = None + return None + return None if request.parked else request + + def _solo_holds(self, head: "Request") -> bool: + """Whether a running solo request keeps ``head`` from being admitted.""" + solo = self._solo_request() + return solo is not None and solo is not head + + def memory_pressure_solo_request(self) -> str | None: + """The solo request when it is the only admitted request, else None. + + Thread-safe read for the memory enforcer: at hard pressure below + the emergency threshold it neither pauses nor aborts this request, + because nothing else runs and pausing it would only resume it again. + """ + try: + solo = self._solo_request() + if solo is None or self._admitted_request_ids() != {solo.request_id}: + return None + return solo.request_id + except RuntimeError: # the queues mutated mid-read on the MLX thread + return None def _log_park_wait(self, request_id: str, need: int, free: int) -> None: now = time.monotonic() @@ -12577,11 +12779,18 @@ def _park_exclusion_reason(self, request: Request) -> str | None: qualifies for a decode pause unless ``_decode_pause_exclusion_reason`` names why not. """ - budget = getattr(self.config, "max_parks_per_request", 3) - if request.park_count >= budget: - return f"park budget spent ({request.park_count}/{budget})" if request.request_id in self.running: + budget = getattr(self.config, "max_decode_pauses_per_request", 8) + if request.decode_pause_count >= budget: + return ( + f"decode pause budget spent " + f"({request.decode_pause_count}/{budget})" + ) return self._decode_pause_exclusion_reason(request) + budget = getattr(self.config, "max_parks_per_request", 3) + parks = request.park_count - request.decode_pause_count + if parks >= budget: + return f"park budget spent ({parks}/{budget})" if request.specprefill_indices is not None: return "SpecPrefill sparse prefill patches model-wide state" if ( @@ -13026,6 +13235,8 @@ def _pause_decoding_request( request.parked = True request.parked_at = time.monotonic() request.park_count = park_number + request.decode_pause_count += 1 + request.park_times.append(request.parked_at) self._enqueue_parked(request) self._ok_polls = 0 self._park_stats["parks"] += 1 @@ -13288,6 +13499,7 @@ def _park_prefill(self, request: Request, reason: str) -> None: request.parked = True request.parked_at = time.monotonic() request.park_count += 1 + request.park_times.append(request.parked_at) request.park_committed_tokens = committed self._clear_request_admission_bookkeeping(rid) get_prefill_tracker().remove(rid) @@ -13304,7 +13516,7 @@ def _park_prefill(self, request: Request, reason: str) -> None: "Parked request %s at %d tokens committed (park %d/%d), reason: %s%s", rid, committed, - request.park_count, + request.park_count - request.decode_pause_count, budget, reason, ( @@ -14775,6 +14987,9 @@ def _schedule_waiting_scan( # overtakes them while they wait. if self.waiting[0].parked and self._park_hold_applies(self.waiting[0]): break + # A solo request runs alone: nothing is admitted beside it. + if self._solo_holds(self.waiting[0]): + break # A fits-later head that deferred keeps the hold until the memory # picture changes; retrying earlier only restores its prefix again. if self._deferred_admission_holds(self.waiting[0]): diff --git a/omlx/settings.py b/omlx/settings.py index 3c4009a039..c10a15e6e3 100644 --- a/omlx/settings.py +++ b/omlx/settings.py @@ -360,12 +360,16 @@ class SchedulerSettings: # and resumes from its last committed prefix once pressure has cleared. # Best with prefill_progress_commit_blocks > 0 (otherwise it resumes cold). memory_pressure_park: bool = False - # Parks a single request may take before it falls back to the abort. + # Prefill parks a single request may take before it falls back to the abort. max_parks_per_request: int = 3 # Prefill a media request's uncached text suffix through the chunked text # path when its last media token is inside the cached prefix, so it shares # the GPU with decodes and can be parked. Off keeps the external prefill. media_text_suffix_chunked: bool = False + # Decode pauses a single request may take before it falls back to the + # abort. Separate and larger than the park budget: a decode pause keeps + # every generated token exactly, while the abort loses them all. + max_decode_pauses_per_request: int = 8 # Consecutive "ok" pressure polls before parked requests may resume when # no memory estimate is available (with one, a parked request resumes # once the estimated free memory covers its need). @@ -415,6 +419,9 @@ def positive_int(key: str, default: int) -> int: memory_pressure_park=data.get("memory_pressure_park") is True, media_text_suffix_chunked=data.get("media_text_suffix_chunked") is True, max_parks_per_request=positive_int("max_parks_per_request", 3), + max_decode_pauses_per_request=positive_int( + "max_decode_pauses_per_request", 8 + ), park_resume_ok_polls=positive_int("park_resume_ok_polls", 3), ) @@ -1350,6 +1357,10 @@ def _apply_env_overrides(self) -> None: self.scheduler.memory_pressure_park = park.lower() in ("true", "1", "yes") for env_name, attr in ( ("OMLX_MAX_PARKS_PER_REQUEST", "max_parks_per_request"), + ( + "OMLX_MAX_DECODE_PAUSES_PER_REQUEST", + "max_decode_pauses_per_request", + ), ("OMLX_PARK_RESUME_OK_POLLS", "park_resume_ok_polls"), ): if raw := os.getenv(env_name): @@ -1884,6 +1895,11 @@ def validate(self) -> list[str]: f"Invalid max_parks_per_request: " f"{self.scheduler.max_parks_per_request} (must be >= 1)" ) + if self.scheduler.max_decode_pauses_per_request < 1: + errors.append( + f"Invalid max_decode_pauses_per_request: " + f"{self.scheduler.max_decode_pauses_per_request} (must be >= 1)" + ) if self.scheduler.park_resume_ok_polls < 1: errors.append( f"Invalid park_resume_ok_polls: " @@ -2070,6 +2086,9 @@ def to_scheduler_config(self) -> SchedulerConfig: memory_pressure_park=self.scheduler.memory_pressure_park, media_text_suffix_chunked=self.scheduler.media_text_suffix_chunked, max_parks_per_request=self.scheduler.max_parks_per_request, + max_decode_pauses_per_request=( + self.scheduler.max_decode_pauses_per_request + ), park_resume_ok_polls=self.scheduler.park_resume_ok_polls, initial_cache_blocks=self.cache.initial_cache_blocks, paged_ssd_cache_dir=str(ssd_dir) if ssd_dir else None, diff --git a/tests/test_memory_resume_thrash.py b/tests/test_memory_resume_thrash.py new file mode 100644 index 0000000000..39bf3ab64a --- /dev/null +++ b/tests/test_memory_resume_thrash.py @@ -0,0 +1,524 @@ +# SPDX-License-Identifier: Apache-2.0 +"""A paused request does not thrash between pause and resume. + +Forced pressure (Qwen3.8-27B at a 42 GB ceiling): one 130k request decoded +alone above the hard watermark (34-37 GB against 33.6 GB); the other two were +held out of the batch. The enforcer paused it, nothing else was admitted, and +the nothing-admitted escape of the park hold resumed it on the next step +without asking whether it fit. Pressure returned, it was paused again, and +after ``park budget spent (3/3)`` the single-victim abort killed it. Not one +"waiting: need" or "fits in free" line was logged in any branch run: the +memory-aware resume never ran. + +The resume now measures every parked head: + +- beside admitted work it resumes only under the hard watermark minus a + hysteresis margin, and a head paused twice within a short window waits for + an admitted row to leave or free memory to rise (anti-thrash); +- with nothing admitted, a head that fits only under the ceiling runs alone + (solo): nothing else is admitted beside it and the enforcer does not pause + or abort it below the emergency threshold. The emergency brake stays. +- decode pauses have their own, larger budget. + +The real-rig tests wire the real enforcer to the real scheduler (tiny Qwen3.5 +hybrid, real paged SSD stores) and script the memory readings that run's log +shows; only the byte sizes are scripted, at the scale of the real run. +""" + +import logging +import time +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest +import test_scheduler_decode_pause as dp +import test_scheduler_park as park +from test_memory_decode_pause import ( + _busy, + _engine, + _ScriptedScheduler, + _victim, + tick, +) +from test_process_memory_enforcer import ( # noqa: F401 (fixture) + _make_enforcer, + mock_engine_pool, +) +from test_scheduler_park_resume_priority import _parked_request +from test_scheduler_prefill_memory_guard import _make_scheduler + +import omlx.scheduler as scheduler_module +from omlx.request import Request, SamplingParams +from omlx.settings import GlobalSettings, SchedulerSettings + +GB = 1024**3 + + +@pytest.fixture(autouse=True) +def single_victim_on(monkeypatch): + """Every enforcer built here aborts one victim (memory.abort_single_victim).""" + from omlx.process_memory_enforcer import ProcessMemoryEnforcer + + real_init = ProcessMemoryEnforcer.__init__ + + def init(self, *args, **kwargs): + kwargs.setdefault("abort_single_victim", True) + real_init(self, *args, **kwargs) + + monkeypatch.setattr(ProcessMemoryEnforcer, "__init__", init) + + +@pytest.fixture +def enforcer(mock_engine_pool): # noqa: F811 + # Ceiling 100 GB, soft 85 GB, hard watermark 95 GB: hard is not an + # emergency until usage passes the ceiling by the emergency margin. + return _make_enforcer( + mock_engine_pool, + ceiling=100 * GB, + soft_threshold=0.85, + hard_threshold=0.95, + ) + + +# --- Resume line and anti-thrash (scheduler unit) -------------------------- + + +@pytest.fixture +def lined(monkeypatch): + """A live scheduler with the enforcer's lines: 100 GB ceiling, 95 GB hard + watermark; ``usage[0]`` is its usage, ``admitted`` its admitted ids.""" + scheduler = _make_scheduler() + scheduler._memory_hard_limit_bytes = 100 * GB + scheduler._memory_hard_watermark_bytes = 95 * GB + scheduler._memory_abort_limit_bytes = 200 * GB # physical cap not binding + scheduler.note_pressure_poll("soft") + usage = [0] + admitted = {"ids": frozenset({"other"})} + monkeypatch.setattr(scheduler, "_current_usage_bytes", lambda **_kw: usage[0]) + monkeypatch.setattr( + scheduler, "_num_admitted_requests", lambda: len(admitted["ids"]) + ) + monkeypatch.setattr(scheduler, "_admitted_request_ids", lambda: admitted["ids"]) + return scheduler, usage, admitted + + +def _fit_line(scheduler): + return scheduler._park_resume_lines()[0] + + +def test_resume_beside_admitted_work_stays_under_the_hard_watermark_margin(lined): + scheduler, usage, _ = lined + head = _parked_request() + need = scheduler._parked_resume_need_bytes(head) + watermark = 95 * GB + hard_line = watermark - int( + watermark * scheduler_module.PARK_RESUME_HARD_MARGIN_FRACTION + ) + assert _fit_line(scheduler) == hard_line + + # The old line (admission line minus 2%) would resume this head. + admission = scheduler._admission_limit_bytes() + old_line = admission - int(admission * scheduler_module.PARK_RESUME_MARGIN_FRACTION) + usage[0] = old_line - need + assert scheduler._park_hold_applies(head) is True + + usage[0] = hard_line - need + 1 + assert scheduler._park_hold_applies(head) is True + usage[0] = hard_line - need + assert scheduler._park_hold_applies(head) is False + + +def test_a_head_that_fits_only_alone_waits_while_others_run(lined): + scheduler, usage, admitted = lined + head = _parked_request() + need = scheduler._parked_resume_need_bytes(head) + usage[0] = _fit_line(scheduler) - need + GB # over the fit line, under the ceiling + + assert scheduler._park_hold_applies(head) is True + assert scheduler._solo_request_id is None + + admitted["ids"] = frozenset() + assert scheduler._park_hold_applies(head) is False + assert scheduler._solo_request_id == head.request_id + + +def test_a_head_paused_twice_quickly_waits_for_a_row_to_leave(lined, caplog): + scheduler, usage, admitted = lined + head = _parked_request() + now = time.monotonic() + head.park_times = [now - 5, now - 1] + head.park_count = 2 + usage[0] = 0 # fits easily + + with caplog.at_level(logging.INFO, logger="omlx.scheduler"): + assert scheduler._park_hold_applies(head) is True + assert scheduler._park_hold_applies(head) is True + assert "was paused 2 times within" in caplog.text + + admitted["ids"] = frozenset() # the row it waited on left + admitted["ids"] = frozenset({"another"}) + assert scheduler._park_hold_applies(head) is False + + +def test_a_thrashing_head_resumes_when_free_memory_rises_enough(lined): + scheduler, usage, _ = lined + head = _parked_request() + now = time.monotonic() + head.park_times = [now - 5, now - 1] + head.park_count = 2 + usage[0] = 40 * GB + assert scheduler._park_hold_applies(head) is True # records the picture + + delta = int(_fit_line(scheduler) * scheduler_module.PARK_THRASH_FREE_DELTA_FRACTION) + usage[0] -= delta + assert scheduler._park_hold_applies(head) is True # not more than the delta + usage[0] -= 1 + assert scheduler._park_hold_applies(head) is False + + +def test_pauses_outside_the_window_are_not_thrash(lined): + scheduler, usage, _ = lined + head = _parked_request() + now = time.monotonic() + window = scheduler_module.PARK_THRASH_WINDOW_S + head.park_times = [now - window - 5, now - 1] + usage[0] = 0 + assert scheduler._park_hold_applies(head) is False + + +def test_a_lone_head_paused_twice_runs_solo_even_when_it_fits(lined): + """The estimate said it fits, yet it was paused again while alone: the + estimate under-counts it, so it runs solo instead of looping.""" + scheduler, usage, admitted = lined + admitted["ids"] = frozenset() + head = _parked_request() + now = time.monotonic() + head.park_times = [now - 5, now - 1] + usage[0] = 0 + assert scheduler._park_hold_applies(head) is False + assert scheduler._solo_request_id == head.request_id + + +def test_hard_pressure_still_holds_a_lone_head(lined): + scheduler, usage, admitted = lined + admitted["ids"] = frozenset() + head = _parked_request() + usage[0] = 0 + scheduler.note_pressure_poll("hard") + assert scheduler._park_hold_applies(head) is True + + +# --- Budgets ---------------------------------------------------------------- + + +def test_prefill_parks_and_decode_pauses_have_separate_budgets(): + scheduler = _make_scheduler() + request = _parked_request() + request.parked = False + request.park_count = 5 + request.decode_pause_count = 3 # two prefill parks + assert "budget" not in (scheduler._park_exclusion_reason(request) or "") + request.park_count = 6 + assert scheduler._park_exclusion_reason(request) == "park budget spent (3/3)" + + +def test_decode_pause_budget_defaults_to_eight_and_is_configurable( + tmp_path, monkeypatch +): + assert scheduler_module.SchedulerConfig().max_decode_pauses_per_request == 8 + assert SchedulerSettings().max_decode_pauses_per_request == 8 + custom = SchedulerSettings.from_dict({"max_decode_pauses_per_request": 12}) + assert custom.max_decode_pauses_per_request == 12 + for bad in (0, -1, "many", True): + junk = SchedulerSettings.from_dict({"max_decode_pauses_per_request": bad}) + assert junk.max_decode_pauses_per_request == 8 + + monkeypatch.setenv("OMLX_MAX_DECODE_PAUSES_PER_REQUEST", "5") + settings = GlobalSettings.load(base_path=tmp_path) + assert settings.scheduler.max_decode_pauses_per_request == 5 + assert settings.to_scheduler_config().max_decode_pauses_per_request == 5 + settings.scheduler.max_decode_pauses_per_request = 0 + assert any("max_decode_pauses_per_request" in e for e in settings.validate()) + + +# --- Enforcer: the solo request is exempt below the emergency threshold --- + + +class _SoloScheduler(_ScriptedScheduler): + def __init__(self, victims, solo): + super().__init__(victims) + self.solo = solo + + def memory_pressure_solo_request(self): + return self.solo + + +class TestEnforcerLeavesTheSoloRequestAlone: + @pytest.mark.asyncio + async def test_hard_pressure_neither_pauses_nor_aborts_it(self, enforcer, caplog): + scheduler = _SoloScheduler([_victim("a", kept=0)], solo="a") + engine = _engine(scheduler, abort_victims=["a"]) + _busy(enforcer, engine) + + with caplog.at_level(logging.WARNING): + await tick(enforcer, 97) + await tick(enforcer, 98) + + assert scheduler.paused == [] + engine.abort_one_request_for_memory.assert_not_awaited() + engine.abort_all_requests.assert_not_awaited() + assert caplog.text.count("a runs alone (solo) on 'big-model'") == 1 + + @pytest.mark.asyncio + async def test_the_emergency_brake_still_aborts_it(self, enforcer): + scheduler = _SoloScheduler([_victim("a", kept=0)], solo="a") + engine = _engine(scheduler) + _busy(enforcer, engine) + + await tick(enforcer, 103) + + engine.abort_all_requests.assert_awaited_once_with(spare_parked=False) + + @pytest.mark.asyncio + async def test_another_busy_engine_removes_the_exemption(self, enforcer): + scheduler = _SoloScheduler([_victim("a", kept=0)], solo="a") + engine = _engine(scheduler) + entry = _busy(enforcer, engine) + other = SimpleNamespace( + engine=SimpleNamespace(has_active_requests=lambda: True), + is_pinned=True, + is_loading=False, + in_use=1, + last_access=0.0, + model_id="other", + ) + enforcer._engine_pool._entries = {"big-model": entry, "other": other} + # Usage is read from the scripted MLX sample, not the executor cache. + enforcer._has_active_requests = lambda: False + + await tick(enforcer, 97) + + assert scheduler.paused == ["a"] + + @pytest.mark.asyncio + async def test_a_failing_probe_gives_no_exemption(self, enforcer): + scheduler = _SoloScheduler([_victim("a", kept=0)], solo="a") + scheduler.memory_pressure_solo_request = lambda: 1 / 0 + engine = _engine(scheduler) + _busy(enforcer, engine) + + await tick(enforcer, 97) + + assert scheduler.paused == ["a"] + + +# --- Real enforcer, real scheduler: the forced-pressure sequence ----------- + +MAX_TOKENS = 60 + + +def _rig(tmp_path, *, park_enabled=True, **config): + rig = park._Rig( + tmp_path, + dp._tokenizer(), + split=False, + commit_blocks=1, + max_blocks=dp.MAX_BLOCKS, + memory_pressure_park=park_enabled, + max_parks_per_request=3, + park_resume_ok_polls=3, + **config, + ) + rig.scheduler.note_pressure_poll("soft") + return rig + + +def _submit(rig, rid, tokens, arrival): + request = Request( + request_id=rid, + prompt=list(tokens), + sampling_params=SamplingParams(max_tokens=MAX_TOKENS, temperature=0), + arrival_time=arrival, + ) + rig.scheduler.add_request(request) + return request + + +def _baseline(tmp_path, prompts): + rig = _rig(tmp_path / "baseline", park_enabled=False) + try: + rows = [ + _submit(rig, rid, tokens, float(i + 1)) + for i, (rid, tokens) in enumerate(prompts.items()) + ] + park.run_to_completion(rig, rows, limit=20 * MAX_TOKENS) + return {r.request_id: list(r.output_token_ids) for r in rows} + finally: + rig.close() + + +def _rig_engine(rig): + return SimpleNamespace( + scheduler=rig.scheduler, + has_active_requests=lambda: False, + abort_all_requests=AsyncMock(return_value=0), + abort_one_request_for_memory=AsyncMock(return_value=None), + memory_victim_pending=lambda rid: False, + ) + + +def _decoding_ids(scheduler): + return list(scheduler.running) + + +def _script(rig, monkeypatch, *, reading, need): + """Scripted memory: ``reading(decoding_ids)`` is the usage both the + enforcer and the scheduler read; ``need`` maps a request to its resume + need. The run's lone request: 21.6 GB of weights plus 8-10 GB of KV, close + to the hard watermark.""" + scheduler = rig.scheduler + + def usage(**_kw): + return reading(_decoding_ids(scheduler)) + + monkeypatch.setattr(scheduler, "_current_usage_bytes", usage) + monkeypatch.setattr( + scheduler, "_parked_resume_need_bytes", lambda r: need[r.request_id] + ) + return lambda: usage() / GB + + +async def _drive(rig, enforcer, gb, rows, limit=40 * MAX_TOKENS): + outputs = [] + for _ in range(limit): + if all(r.is_finished() for r in rows): + break + await tick(enforcer, gb()) + outputs.extend(park.step(rig)) + for future in list(rig.scheduler._inflight_store_futures.values()): + future.result(timeout=30) + rig.scheduler._drain_pending_async_removes() + return outputs + + +def _assert_no_abort(engine, rows, expected, outputs): + engine.abort_one_request_for_memory.assert_not_awaited() + engine.abort_all_requests.assert_not_awaited() + for row in rows: + rid = row.request_id + assert list(row.output_token_ids) == expected[rid] + assert dp.streamed_tokens(outputs, rid) == expected[rid] + (final,) = [o for o in outputs if o.request_id == rid and o.finished] + assert final.finish_reason == "length" and not final.error + + +@pytest.mark.asyncio +async def test_lone_request_over_the_hard_watermark_pauses_once_then_runs_solo( + tmp_path, enforcer, monkeypatch, caplog +): + """pause -> resume -> pressure -> pause used to loop to the abort.""" + prompts = {"a": dp.PROMPT} + expected = _baseline(tmp_path, prompts) + rig = _rig(tmp_path / "solo") + try: + engine = _rig_engine(rig) + _busy(enforcer, engine) + # Decoding alone: 97 GB, over the 95 GB hard watermark; paused: 20 GB. + gb = _script( + rig, + monkeypatch, + reading=lambda ids: 97 * GB if ids else 20 * GB, + need={"a": 74 * GB}, # 20 + 74 > 90.25 (fit line), < 98 (ceiling) + ) + (row,) = [_submit(rig, "a", dp.PROMPT, 1.0)] + + with caplog.at_level(logging.INFO): + outputs = await _drive(rig, enforcer, gb, [row]) + + scheduler = rig.scheduler + _assert_no_abort(engine, [row], expected, outputs) + assert row.decode_pause_count == 1 + stats = scheduler.get_park_stats() + assert stats["decode_pauses"] == stats["decode_resumes"] == 1 + assert "Resuming parked request a alone (solo)" in caplog.text + assert "a runs alone (solo)" in caplog.text + assert "budget spent" not in caplog.text + finally: + rig.close() + + +@pytest.mark.asyncio +async def test_requests_that_fit_one_at_a_time_all_complete_without_aborts( + tmp_path, enforcer, monkeypatch +): + """The forced-pressure decode run: three long requests, one admitted at a time, + each over the hard watermark while it decodes. Total demand fits + sequentially, so every request completes and nothing is aborted.""" + prompts = {"a": dp.PROMPT, "b": dp.OTHER, "c": park.PROMPT_D} + expected = _baseline(tmp_path, prompts) + rig = _rig(tmp_path / "sequential", max_num_seqs=1) + try: + engine = _rig_engine(rig) + _busy(enforcer, engine) + gb = _script( + rig, + monkeypatch, + reading=lambda ids: 97 * GB if ids else 20 * GB, + need={"a": 74 * GB, "b": 72 * GB, "c": 73 * GB}, + ) + rows = [ + _submit(rig, rid, tokens, float(i + 1)) + for i, (rid, tokens) in enumerate(prompts.items()) + ] + + outputs = await _drive(rig, enforcer, gb, rows) + + _assert_no_abort(engine, rows, expected, outputs) + assert all(r.decode_pause_count <= 1 for r in rows) + finally: + rig.close() + + +@pytest.mark.asyncio +async def test_a_row_paused_twice_waits_for_the_other_row_instead_of_thrashing( + tmp_path, enforcer, monkeypatch, caplog +): + """Two rows over the watermark: the newer one is paused, fits beside the + older one, resumes, and pressure returns. After its second pause it waits + until the older row finishes, then completes; nothing is aborted.""" + prompts = {"a": dp.PROMPT, "b": dp.OTHER} + expected = _baseline(tmp_path, prompts) + rig = _rig(tmp_path / "thrash") + try: + scheduler = rig.scheduler + engine = _rig_engine(rig) + _busy(enforcer, engine) + decoding = {"both": False} + + def reading(ids): + if len(ids) >= 2: + decoding["both"] = True + return 97 * GB + return 60 * GB if ids else 20 * GB + + gb = _script( + rig, + monkeypatch, + reading=reading, + need={"a": 30 * GB, "b": 30 * GB}, # 60 + 30 = 90 <= 90.25 + ) + rows = [_submit(rig, "a", dp.PROMPT, 1.0), _submit(rig, "b", dp.OTHER, 2.0)] + + with caplog.at_level(logging.INFO): + outputs = await _drive(rig, enforcer, gb, rows) + + _assert_no_abort(engine, rows, expected, outputs) + b = rows[1] + assert b.decode_pause_count == 2 + assert rows[0].decode_pause_count == 0 # the oldest row is protected + assert "Parked request b was paused 2 times within" in caplog.text + # It resumed only after ``a`` finished. + assert len(b.output_token_ids) == MAX_TOKENS + assert scheduler.get_park_stats()["decode_resumes"] == 2 + finally: + rig.close() diff --git a/tests/test_scheduler_decode_pause.py b/tests/test_scheduler_decode_pause.py index d0410f11ad..832a1d3a55 100644 --- a/tests/test_scheduler_decode_pause.py +++ b/tests/test_scheduler_decode_pause.py @@ -209,7 +209,7 @@ def test_a_decoding_row_is_pausable_when_nothing_excludes_it(tmp_path): ("mtp", "batched Lightning MTP"), ("vlm_mtp", "VLM-MTP"), ("no_ssd", "no paged SSD cache"), - ("budget", "park budget spent"), + ("budget", "decode pause budget spent (8/8)"), ], ) def test_v1_exclusions_name_why_a_decoding_row_cannot_pause( @@ -234,7 +234,9 @@ def test_v1_exclusions_name_why_a_decoding_row_cannot_pause( elif case == "no_ssd": monkeypatch.setattr(scheduler, "paged_ssd_cache_manager", None) elif case == "budget": - request.park_count = 3 + # Decode pauses have their own budget; prefill parks do not count. + request.park_count = 11 + request.decode_pause_count = 8 reason = scheduler._park_exclusion_reason(request) assert reason is not None and expected in reason assert scheduler.request_decode_pause("a") is False diff --git a/tests/test_scheduler_park_resume_priority.py b/tests/test_scheduler_park_resume_priority.py index 22622ba461..0a227ac7fd 100644 --- a/tests/test_scheduler_park_resume_priority.py +++ b/tests/test_scheduler_park_resume_priority.py @@ -171,14 +171,21 @@ def test_max_hold_does_not_release_a_head_that_does_not_fit(live): assert scheduler._park_hold_applies(head) is True -def test_nothing_admitted_and_stale_monitor_escapes_still_release(live, monkeypatch): +def test_nothing_admitted_releases_only_a_head_that_fits_alone(live, monkeypatch): + """Nothing admitted used to release any head at once, even one that + alone overflows the line: it resumed, was paused at the next poll and + looped until its park budget ran out. Now it waits, bounded by + PARK_MAX_HOLD_S, unless it fits; the stale-monitor escape stays.""" scheduler, usage = live head = _parked_request() usage[0] = scheduler._admission_limit_bytes() assert scheduler._park_hold_applies(head) is True monkeypatch.setattr(scheduler, "_num_admitted_requests", lambda: 0) + assert scheduler._park_hold_applies(head) is True + head.parked_at -= scheduler_module.PARK_MAX_HOLD_S + 1 assert scheduler._park_hold_applies(head) is False + assert scheduler._solo_request_id == head.request_id monkeypatch.setattr(scheduler, "_num_admitted_requests", lambda: 1) scheduler._last_pressure_poll_at = ( diff --git a/tests/test_settings.py b/tests/test_settings.py index fed66288d0..71b1c243a3 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -398,6 +398,7 @@ def test_to_dict(self): "memory_pressure_park": False, "media_text_suffix_chunked": False, "max_parks_per_request": 3, + "max_decode_pauses_per_request": 8, "park_resume_ok_polls": 3, } From 68e2502d83214e22305ef3f1fedd030b89204fba Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Wed, 7 Oct 2026 20:33:37 -0600 Subject: [PATCH 36/46] test(memory): pin the physical cap in the resume-thrash enforcer fixture Upstream's _make_enforcer now pins _get_abort_limit_bytes to the ceiling (#4312), and the emergency brake measures against that physical cap. The resume-thrash fixture took its physical cap from the host before (120 GB on a 128 GB machine), so its solo line depended on the machine: with the cap at the ceiling, the prefill safety cap binds and the lone request never resumes solo. The fixture now keeps the physical cap out of the way (200 GB), as the scheduler-unit fixture in the same file does, and the emergency-brake case pins it to the ceiling, the line it tests. --- tests/test_memory_resume_thrash.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/tests/test_memory_resume_thrash.py b/tests/test_memory_resume_thrash.py index 39bf3ab64a..73396b305c 100644 --- a/tests/test_memory_resume_thrash.py +++ b/tests/test_memory_resume_thrash.py @@ -71,13 +71,16 @@ def init(self, *args, **kwargs): @pytest.fixture def enforcer(mock_engine_pool): # noqa: F811 # Ceiling 100 GB, soft 85 GB, hard watermark 95 GB: hard is not an - # emergency until usage passes the ceiling by the emergency margin. - return _make_enforcer( + # emergency until usage passes the ceiling by the emergency margin. The + # physical cap is not binding (200 GB), whatever the host's memory. + enforcer = _make_enforcer( mock_engine_pool, ceiling=100 * GB, soft_threshold=0.85, hard_threshold=0.95, ) + enforcer._get_abort_limit_bytes = lambda: 200 * GB + return enforcer # --- Resume line and anti-thrash (scheduler unit) -------------------------- @@ -271,6 +274,9 @@ async def test_hard_pressure_neither_pauses_nor_aborts_it(self, enforcer, caplog @pytest.mark.asyncio async def test_the_emergency_brake_still_aborts_it(self, enforcer): + # The emergency brake measures against the physical cap (#4312); here + # it is the ceiling. + enforcer._get_abort_limit_bytes = lambda: 100 * GB scheduler = _SoloScheduler([_victim("a", kept=0)], solo="a") engine = _engine(scheduler) _busy(enforcer, engine) From 1c20affad3c3d6c60eeeaa85696693e757f04cdc Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Tue, 6 Oct 2026 01:33:30 -0600 Subject: [PATCH 37/46] fix(memory): spare external-loop prefills and pause before the emergency abort-all In a real-model image-decode run, at the end of a lone 130k image prefill usage reached 35.3 GB, over the 33.6 GB hard watermark but under the 42 GB ceiling, so the emergency brake did not fire. The non-emergency path found nothing to park or pause, the single-victim selection found no live request (the external prefill is neither running nor a chunked prefill, queued requests hold no KV), and the enforcer fell back to abort-all: every request was lost and aborting the queued ones freed nothing. - A request in the external prefill loop with nothing else admitted runs alone: the enforcer neither pauses nor aborts it below the emergency threshold. A decoding row beside it is paused instead. - With no live request to abort, the non-emergency path aborts nothing. - Emergency pause-first: beyond the ceiling, one decode pause of the largest pausable row that brings usage back under it comes before abort-all, waited on for at most two polls while usage does not grow. - With the park feature on, a media prefill beside admitted work whose estimated peak crosses the hard watermark minus 5% waits at the head instead of spiking past it. Tests poll the real enforcer while the real scheduler's thread sits inside the external prefill. The external-loop exemption is memory scheduling (memory.memory_scheduling): with it off, the default for a stock install, a lone external-loop prefill is not reported as solo and the enforcer's hard path stays main's. --- docs/TESTING.md | 4 +- omlx/process_memory_enforcer.py | 135 +++++- omlx/scheduler.py | 81 +++- tests/test_memory_decode_pause.py | 4 +- tests/test_memory_external_prefill.py | 592 ++++++++++++++++++++++++++ tests/test_memory_resume_thrash.py | 5 +- tests/test_memory_scheduling_gate.py | 11 + tests/test_process_memory_enforcer.py | 13 +- 8 files changed, 828 insertions(+), 17 deletions(-) create mode 100644 tests/test_memory_external_prefill.py diff --git a/docs/TESTING.md b/docs/TESTING.md index 3b15dc8832..0964b7e3a0 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -237,7 +237,7 @@ Mocked tests do not replace hardware validation: with a real model, abort a long # Memory scheduling gate tests -Run `python -m pytest -q tests/test_memory_scheduling_gate.py` to check `memory.memory_scheduling` (env `OMLX_MEMORY_SCHEDULING`; `auto`, `on` or `off`, default `auto`). It gates the never-fits 400 with the capacity endpoint numbers and the `X-oMLX-Max-Context-Tokens` header, and the fits-later wait. `auto` is on when the prefill memory guard is on and an explicit ceiling is set (`memory_guard_tier: custom` with `memory_guard_custom_ceiling_gb` > 0; a ceiling value left under another tier does not count). `on` forces it on but still needs the guard (with the guard off it stays off and logs a warning). `off` forces it off. The `ProcessMemoryEnforcer` resolves the mode at startup and whenever the mode, the guard, the tier or the ceiling changes (the admin settings apply live), logs `Memory scheduling: on (explicit ceiling 48.0 GB)` or the reason it is off, and propagates the result to every scheduler (`Scheduler._memory_scheduling`, False until an enforcer sets it). The tests cover the resolution matrix, the setting (default, `to_dict`, `from_dict`, env override, validation, the admin GET and POST), and, with it off, upstream behaviour on each path: no capacity estimate, snapshot or header (a cached hint is not served either); a request whose `max_tokens` can never fit passes when its prompt fits now; a fits-alone-but-not-now request gets the old current-usage rejection; and the capacity endpoint returns `available: false` with `memory_scheduling: "off"` and the reason, while unknown and unloaded models keep their 404 and 409. The suites below that test these behaviours set the mode on explicitly (`scheduler._memory_scheduling = True`). +Run `python -m pytest -q tests/test_memory_scheduling_gate.py` to check `memory.memory_scheduling` (env `OMLX_MEMORY_SCHEDULING`; `auto`, `on` or `off`, default `auto`). It gates the never-fits 400 with the capacity endpoint numbers and the `X-oMLX-Max-Context-Tokens` header, and the fits-later wait. `auto` is on when the prefill memory guard is on and an explicit ceiling is set (`memory_guard_tier: custom` with `memory_guard_custom_ceiling_gb` > 0; a ceiling value left under another tier does not count). `on` forces it on but still needs the guard (with the guard off it stays off and logs a warning). `off` forces it off. The `ProcessMemoryEnforcer` resolves the mode at startup and whenever the mode, the guard, the tier or the ceiling changes (the admin settings apply live), logs `Memory scheduling: on (explicit ceiling 48.0 GB)` or the reason it is off, and propagates the result to every scheduler (`Scheduler._memory_scheduling`, False until an enforcer sets it). The tests cover the resolution matrix, the setting (default, `to_dict`, `from_dict`, env override, validation, the admin GET and POST), and, with it off, upstream behaviour on each path: no capacity estimate, snapshot or header (a cached hint is not served either); a request whose `max_tokens` can never fit passes when its prompt fits now; a fits-alone-but-not-now request gets the old current-usage rejection; an external-loop prefill is not reported as solo to the enforcer; and the capacity endpoint returns `available: false` with `memory_scheduling: "off"` and the reason, while unknown and unloaded models keep their 404 and 409. `tests/test_memory_external_prefill.py` also drives the real enforcer with park, single victim and memory scheduling off: the lone external prefill at hard pressure gets upstream's abort-all. The suites below that test these behaviours set the mode on explicitly (`scheduler._memory_scheduling = True`, or `memory_scheduling="on"` on the real enforcer). Run `python -m pytest -q tests/test_memory_scheduling_admin_state.py` to check memory scheduling across admin settings saves. The cases load the real settings with `memory_scheduling: "on"` in `settings.json`, build the live enforcer from them as the server does, and drive the real admin routes. A save of `max_concurrent_requests`, `chunked_prefill` or `memory_guard_tier` keeps the mode on the live settings object and in `settings.json` (a reload sees it again), keeps it on and propagated, and logs no `Memory scheduling:` line. Loading the settings page (`GET /admin/api/global-settings`, which builds one tier-preview enforcer per tier) logs none either: only an enforcer that drives an engine pool logs its state. An explicit `memory_scheduling` POST, including one that repeats the current mode, re-resolves, logs the state and propagates it to the schedulers. The GET reports the live state as `memory.memory_scheduling_effective` (`enabled` and `reason`, `null` without an enforcer), the POST response carries it, and the factory defaults response does not. @@ -261,4 +261,6 @@ Run `python -m pytest -q tests/test_memory_single_victim.py tests/test_process_m Run `python -m pytest -q tests/test_memory_resume_thrash.py` to check that a paused request does not thrash. Beside admitted work a parked head resumes only when current usage plus in-flight prefill reserve plus its need stays under the admission line minus 2% and under the hard watermark minus 5% (`PARK_RESUME_HARD_MARGIN_FRACTION`); the enforcer pauses at the watermark, so resuming right up to it pauses the request again at the next poll. A head parked or paused twice within 60 s (`PARK_THRASH_PAUSES`, `PARK_THRASH_WINDOW_S`) waits, even when it fits, until an admitted row leaves (finishes, aborts or pauses) or free memory rises by more than 5% of the resume line. With nothing admitted, a head that fits resumes; one that fits only under the ceiling (the scheduler hard limit and the prefill safety cap, minus 2%), one that keeps being paused while alone, or one that waited `PARK_MAX_HOLD_S` resumes as the solo request: nothing else is admitted while it runs, and at hard pressure below the emergency threshold the enforcer neither pauses nor aborts it (only when every other loaded engine is idle). The emergency brake beyond the ceiling still aborts it. Decode pauses have their own budget, `scheduler.max_decode_pauses_per_request` (`OMLX_MAX_DECODE_PAUSES_PER_REQUEST`, default 8), apart from the prefill park budget: a decode pause keeps every generated token exactly, while the abort that follows an exhausted budget loses them all. The real-rig cases wire the real enforcer to the real scheduler and script the memory readings of a forced-pressure run (a lone request decoding over the hard watermark; three requests one at a time; two rows where the newer one is paused twice): every request completes with its uninterrupted greedy output and no abort. +Run `python -m pytest -q tests/test_memory_external_prefill.py` to check memory pressure while a prompt prefills in the external loop (a media prompt whose images are not all cached; it cannot be parked). A request in that loop with nothing else admitted runs alone: at hard pressure below the emergency threshold the enforcer neither pauses nor aborts it. With a decoding row beside it, the decoding row is paused instead. When the single-victim selection finds no live request (queued requests hold no memory), the non-emergency path aborts nothing; before, it fell back to aborting every request. At emergency pressure (beyond the ceiling) the enforcer first pauses the largest pausable decoding row when freeing its estimate brings usage back under the ceiling, and waits for that pause at most two polls (`_EMERGENCY_PAUSE_MAX_POLLS`) and only while usage does not grow; abort-all stays the last resort when nothing is pausable, no pause gets under the ceiling, or the pause is declined or too slow. With the park feature on, a media prefill beside admitted work whose estimated peak (current usage, exact KV and transient) crosses the resume line (the hard watermark minus 5%) waits at the head until an admitted row leaves; it does not pause a decoding row for room, because the paused row would be parked ahead of it and resume first. The external-loop tests block the scheduler's own thread inside the external prefill so the real enforcer polls while it runs, as in production. The lone external prefill counts as solo only with memory scheduling on; these tests set it on. + Mocked tests do not replace hardware validation: with a real model, run three concurrent long prompts under a ceiling too low for all of them and check that each completes with the park/resume log lines and a cached count close to the last commit, and that no client sees a memory error. diff --git a/omlx/process_memory_enforcer.py b/omlx/process_memory_enforcer.py index e839863c60..10277e78e6 100644 --- a/omlx/process_memory_enforcer.py +++ b/omlx/process_memory_enforcer.py @@ -132,6 +132,10 @@ def tier_reserve_bytes(tier: str, total_ram: int) -> int: # Longest a prefill waits for released dirty hot-cache blocks to reach SSD. _HOT_CACHE_WRITE_WAIT_S = 5.0 +# ``_abort_single_victim`` result when the engine found no live request to +# abort: queued requests hold no memory, so aborting them frees nothing. +_NO_LIVE_VICTIM = object() + def _format_gb(b: int) -> str: """Format bytes as GB string.""" @@ -570,6 +574,9 @@ def __init__( self._draining_victim: _DrainingVictim | None = None # The solo request last logged as exempt (one line per request). self._solo_logged: str | None = None + # Emergency pause-first in flight: (model id, request id, polls, the + # usage it started at, the status probe). See _emergency_pause_first. + self._emergency_pause: tuple[str, str, int, int, Any] | None = None # Last value passed to mx.set_wired_limit (0 if not yet applied # or the call failed). Used by the admin dashboard to surface a # warning when the kernel iogpu.wired_limit_mb is below this. @@ -1383,6 +1390,11 @@ def _shrink_hot_cache_by( # run and its memory to settle. A prefill chunk can hold the scheduler # step for ~5 one-second polls, so this covers two chunk boundaries. _SINGLE_VICTIM_SETTLE_MAX_POLLS = 10 + # Emergency pause-first: polls the abort-all waits for one decode pause + # that brings usage under the ceiling. The pause runs at the next step and + # its exact store must reach the SSD, so one poll is often not enough; + # two bound the extra exposure beyond the ceiling. + _EMERGENCY_PAUSE_MAX_POLLS = 2 def _pool_bytes(self) -> int: """MLX buffer-pool size, 0 when unreadable (mocked mx in tests).""" @@ -1757,9 +1769,10 @@ async def _abort_single_victim(self, engine: Any, model_id: str) -> Any: """Abort the one request freeing the most memory; None means fall back. Returns None when the switch is off, the engine has no such hook, the - hook fails, no live request can be chosen, or the chosen one could - not be aborted (``skipped``), so the caller aborts everything as - before for this poll. The abort itself is deferred to the scheduler + hook fails, or the chosen one could not be aborted (``skipped``), so + the caller aborts everything as before for this poll. Returns + ``_NO_LIVE_VICTIM`` when no live request can be chosen: what is left + is queued requests holding no memory, and the caller aborts nothing. The abort itself is deferred to the scheduler step, so while the previous victim's abort is pending or its memory has not settled (abort seen to have run, then one more poll) the same victim is returned and nobody else is sacrificed, for at most @@ -1785,7 +1798,7 @@ async def _abort_single_victim(self, engine: Any, model_id: str) -> Any: ) return None if victim is None: - return None + return _NO_LIVE_VICTIM skipped = getattr(victim, "skipped", None) if skipped: logger.warning( @@ -1913,6 +1926,102 @@ def _request_decode_pause(self) -> int: return 1 return 0 + def _emergency_pause_first(self, current: int, ceiling: int) -> bool: + """At emergency pressure, pause one decoding row before abort-all. + + Asks every scheduler for its largest pausable decoding row + (``select_decode_pause_victim``) and pauses the largest one only when + freeing its estimated bytes brings usage under the ceiling. While + that pause is pending (not run yet, or its exact chain still on its + way to the SSD) the abort-all waits, for at most + ``_EMERGENCY_PAUSE_MAX_POLLS`` polls and only while usage does not + grow past where it started. Returns True when the abort-all is + deferred this poll. Nothing pausable, a pause that would not get + under the ceiling, a declined or exhausted one: False, and the + emergency abort-all runs as the last resort. + """ + pending = self._emergency_pause + if pending is not None: + model_id, rid, polls, started_at, status = pending + try: + state = status() + except Exception: # noqa: BLE001 + state = "declined" + if ( + state == "pending" + and polls < self._EMERGENCY_PAUSE_MAX_POLLS + and current <= started_at + ): + self._emergency_pause = (model_id, rid, polls + 1, started_at, status) + logger.warning( + "Emergency memory pressure: waiting for the decode pause of " + "%s on '%s' before aborting (poll %d/%d)", + rid, + model_id, + polls + 1, + self._EMERGENCY_PAUSE_MAX_POLLS, + ) + return True + self._emergency_pause = None + # A pause that ran (done) and still left an emergency, or one that + # was declined or ran out of polls: abort-all, the last resort. + return False + best = None + for model_id, entry in self._engine_pool._entries.items(): + scheduler = self._resolve_scheduler(entry) + select = getattr(scheduler, "select_decode_pause_victim", None) + pause = getattr(scheduler, "request_decode_pause", None) + status = getattr(scheduler, "decode_pause_status", None) + if not (callable(select) and callable(pause) and callable(status)): + continue + try: + victim = select() + except Exception: # noqa: BLE001 + continue + est = int(getattr(victim, "est_bytes", 0) or 0) + rid = getattr(victim, "request_id", None) + if not isinstance(rid, str) or est <= 0: + continue + if best is None or est > best[0]: + best = (est, model_id, rid, pause, status) + if best is None: + return False + est, model_id, rid, pause, status = best + if current - est >= ceiling: + logger.warning( + "Emergency memory pressure: pausing %s (~%s) would not bring " + "usage %s under the ceiling %s; aborting instead", + rid, + _format_gb(est), + _format_gb(current), + _format_gb(ceiling), + ) + return False + try: + accepted = pause(rid) is True + except Exception as exc: # noqa: BLE001 + logger.warning("Emergency decode pause of %s failed: %s", rid, exc) + return False + if not accepted: + return False + self._emergency_pause = ( + model_id, + rid, + 0, + current, + lambda rid=rid, probe=status: probe(rid), + ) + logger.warning( + "Emergency memory pressure: pausing decoding request %s (~%s) on " + "'%s' before aborting everything (current=%s, ceiling=%s)", + rid, + _format_gb(est), + model_id, + _format_gb(current), + _format_gb(ceiling), + ) + return True + def _solo_exempt_request(self) -> tuple[str, str] | None: """(model id, request id) of a request running alone, else None. @@ -2303,6 +2412,15 @@ async def _check_and_enforce(self) -> None: self._walk_store_cache_caps() return + # Emergency pause-first: beyond the ceiling, one decode pause that + # frees enough to get back under it comes before aborting everything. + if new_level == "hard" and emergency: + if self._emergency_pause_first(current, ceiling): + self._walk_store_cache_caps() + return + else: + self._emergency_pause = None + # Recover below soft regardless of level — prevents oscillation # at the boundary. target = soft @@ -2379,6 +2497,15 @@ async def _check_and_enforce(self) -> None: entry.engine, busy_victim ) ) + if single is _NO_LIVE_VICTIM: + logger.warning( + "Hard memory pressure on '%s': no live " + "request holds memory to free (queued " + "requests hold none); nothing aborted, the " + "emergency brake stays armed", + busy_victim, + ) + break if single is not None: break # Only the non-emergency path keeps the model diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 864aa32848..e6936efc5b 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -2581,6 +2581,12 @@ def __init__( # (see memory_pressure_solo_request). Read by the enforcer thread. self._solo_request_id: str | None = None self._solo_logged: tuple[str, int] | None = None + # The request running the external (non-chunked) prefill loop, set for + # the duration of that loop. It cannot be parked; the enforcer reads + # it through memory_pressure_solo_request. + self._external_prefill_request_id: str | None = None + # Last "media prefill deferred" log line (request id, park count). + self._media_reservation_logged: str | None = None # Decode pause: ids asked for by request_decode_pause (thread-safe set, # drained at step start) and the resume record of each paused row. self._pending_decode_pauses: set[str] = set() @@ -12549,13 +12555,24 @@ def _solo_holds(self, head: "Request") -> bool: return solo is not None and solo is not head def memory_pressure_solo_request(self) -> str | None: - """The solo request when it is the only admitted request, else None. - - Thread-safe read for the memory enforcer: at hard pressure below - the emergency threshold it neither pauses nor aborts this request, - because nothing else runs and pausing it would only resume it again. + """The request running alone, for the memory enforcer, else None. + + The solo request when it is the only admitted request, or a request + in the external prefill loop with nothing else admitted (it cannot + be parked, and with nothing else running aborting it frees memory + for nobody; with memory scheduling on only, so the enforcer's hard + path stays upstream's otherwise). Thread-safe read: at hard pressure + below the emergency threshold the enforcer neither pauses nor aborts + it. """ try: + external = self._external_prefill_request_id + if ( + external is not None + and self._memory_scheduling_on() + and not self._admitted_request_ids() + ): + return external solo = self._solo_request() if solo is None or self._admitted_request_ids() != {solo.request_id}: return None @@ -14230,8 +14247,59 @@ def _preflight_memory_check( ) raise _PreflightDeferredError() return safety_rejection + if self._external_media_reservation_short(request, est): + raise _PreflightDeferredError() return None + def _external_media_reservation_short( + self, request: "Request", est: "_AdmissionEstimate" + ) -> bool: + """Whether a media prefill must wait for room under the hard line. + + A media prompt whose images are not all cached prefills in the + external loop: it cannot be parked, and its KV plus chunk working set + lands at once. Beside admitted work its estimated peak (current + usage, exact KV and transient; the embeddings are already in current) + is reserved against the resume line, the hard watermark minus the + hysteresis margin, so its spike cannot push the process past the + watermark into an abort. When it does not fit it waits at the head + (deferred, nothing overtakes it) until an admitted row leaves or + memory frees. It does not pause a decoding row to make room: the + paused row would be parked ahead of it (parked requests resume in + arrival order) and take the room back first. With nothing admitted + it runs: alone, the enforcer leaves its external loop to the + emergency brake (see memory_pressure_solo_request). Only with the + park feature on. + """ + if not self._park_enabled(): + return False + if getattr(request, "vlm_inputs_embeds", None) is None: + return False + media_end = getattr(request, "vlm_media_end", None) + if ( + isinstance(media_end, int) + and media_end > 0 + and int(request.cached_tokens or 0) >= media_end + and getattr(self.config, "media_text_suffix_chunked", False) is True + ): + return False # every image cached: the chunked text-suffix route + if not self._num_admitted_requests(): + return False + lines = self._park_resume_lines() + if lines is None or est.estimated <= lines[0]: + return False + if self._media_reservation_logged != request.request_id: + self._media_reservation_logged = request.request_id + logger.info( + "Deferring media prefill %s: its external-loop peak ~%.1f GB " + "would cross the hard watermark line %.1f GB beside admitted " + "work; it waits for admitted requests to finish", + request.request_id, + est.estimated / 1024**3, + lines[0] / 1024**3, + ) + return True + def _admission_estimate( self, *, @@ -15624,6 +15692,7 @@ def _report_sparse_progress(processed: int, total: int) -> None: self.request_id_to_uid[request.request_id] = temp_uid self.uid_to_request_id[temp_uid] = request.request_id + self._external_prefill_request_id = request.request_id try: prefilled_cache, last_token = self._do_external_prefill( request, @@ -15687,6 +15756,8 @@ def _report_sparse_progress(processed: int, total: int) -> None: ) ) continue + finally: + self._external_prefill_request_id = None # Clean up temp UID mapping del self.uid_to_request_id[temp_uid] diff --git a/tests/test_memory_decode_pause.py b/tests/test_memory_decode_pause.py index edfbe82416..5f5cab0c89 100644 --- a/tests/test_memory_decode_pause.py +++ b/tests/test_memory_decode_pause.py @@ -228,7 +228,9 @@ async def test_no_pause_while_an_aborted_victim_drains(self, enforcer): @pytest.mark.asyncio async def test_emergency_aborts_everything_without_pausing(self, enforcer): - scheduler = _ScriptedScheduler([_victim("big")]) + # A pause of ~1 GB cannot bring 103 GB under the 100 GB ceiling, so + # the emergency pause-first does not apply. + scheduler = _ScriptedScheduler([MemoryVictim("big", 9_000, GB, 2)]) engine = _engine(scheduler) _busy(enforcer, engine) diff --git a/tests/test_memory_external_prefill.py b/tests/test_memory_external_prefill.py new file mode 100644 index 0000000000..1b7142aaff --- /dev/null +++ b/tests/test_memory_external_prefill.py @@ -0,0 +1,592 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Memory pressure while a media prompt prefills in the external loop. + +Forced-pressure image decode (42 GB ceiling): a 130k image prompt prefilled +alone in the external loop while two requests waited in the queue. At the end +of its prefill usage reached 35.3 GB, over the 33.6 GB hard watermark but +under the ceiling, so it was NOT the emergency brake. The non-emergency hard +path found nothing to park ("multimodal prompt ... prefills in the external +loop") and nothing to pause; the single-victim selection found no live +request (the external prefill sits in neither ``running`` nor a chunked +prefill state, and queued requests hold no KV), so the enforcer fell back to +abort-all: "Aborted 2 requests due to memory pressure", then 1 more. Every +request was lost and nothing was freed by aborting the queued ones. + +Now: + +- a request in the external loop with nothing else admitted runs alone: the + enforcer neither pauses nor aborts it below the emergency threshold; +- with a decoding row beside it, the decoding row is paused instead; +- with no live request at all, the non-emergency path aborts nothing; +- at emergency pressure one decode pause that brings usage back under the + ceiling comes before abort-all, which stays the last resort; +- beside admitted work, a media prefill whose estimated peak crosses the hard + watermark line waits at the head instead of spiking past it. + +The tests drive the real enforcer and the real scheduler (tiny Qwen3.5 hybrid +behind an mlx-vlm style ``inputs_embeds`` call, real paged SSD stores); the +memory readings are scripted at the scale of the real run. +""" + +import asyncio +import concurrent.futures +import functools +import logging +import threading +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest +import test_scheduler_decode_pause as dp +import test_scheduler_park as park +from test_memory_decode_pause import _busy, _ScriptedScheduler, tick +from test_process_memory_enforcer import ( # noqa: F401 (fixture) + _make_enforcer, + mock_engine_pool, +) +from test_scheduler_prefill_commit_vlm import IMAGE_KEY, IMAGE_START, _VLMLikeModel +from test_scheduler_prefill_progress_commit import _Rig + +from omlx.request import MemoryVictim, Request, SamplingParams + +GB = 1024**3 +MAX_TOKENS = 30 +TEXT = dp.PROMPT +MEDIA = park.PROMPT_D + + +@pytest.fixture(autouse=True) +def single_victim_on(monkeypatch): + """Every enforcer built here aborts one victim (memory.abort_single_victim).""" + from omlx.process_memory_enforcer import ProcessMemoryEnforcer + + real_init = ProcessMemoryEnforcer.__init__ + + def init(self, *args, **kwargs): + kwargs.setdefault("abort_single_victim", True) + real_init(self, *args, **kwargs) + + monkeypatch.setattr(ProcessMemoryEnforcer, "__init__", init) + + +@pytest.fixture +def enforcer(mock_engine_pool): # noqa: F811 + # Ceiling 100 GB, soft 85 GB, hard watermark 95 GB; emergency from 102 GB. + return _make_enforcer( + mock_engine_pool, + ceiling=100 * GB, + soft_threshold=0.85, + hard_threshold=0.95, + memory_scheduling="on", + ) + + +def _rig(tmp_path, *, park_enabled=True, max_num_seqs=None): + config = {"max_num_seqs": max_num_seqs} if max_num_seqs else {} + rig = _Rig( + tmp_path, + dp._tokenizer(), + split=False, + commit_blocks=1, + max_blocks=dp.MAX_BLOCKS, + memory_pressure_park=park_enabled, + max_parks_per_request=3, + park_resume_ok_polls=3, + **config, + ) + rig.wrapped = _VLMLikeModel(rig.model) + rig.scheduler.model = rig.wrapped + rig.scheduler.note_pressure_poll("soft") + return rig + + +def _text(rig, rid, arrival, tokens=TEXT): + request = Request( + request_id=rid, + prompt=list(tokens), + sampling_params=SamplingParams(max_tokens=MAX_TOKENS, temperature=0), + arrival_time=arrival, + ) + rig.scheduler.add_request(request) + return request + + +def _media(rig, rid, arrival, tokens=MEDIA): + embeds = rig.wrapped.embed(list(tokens)) + request = Request( + request_id=rid, + prompt=list(tokens), + sampling_params=SamplingParams(max_tokens=MAX_TOKENS, temperature=0), + arrival_time=arrival, + vlm_inputs_embeds=embeds, + vlm_image_hash=IMAGE_KEY[0], + vlm_cache_key_start=IMAGE_START, + ) + rig.scheduler.add_request(request) + return request + + +def _baseline(tmp_path, build): + rig = _rig(tmp_path / "baseline", park_enabled=False) + try: + rows = build(rig) + park.run_to_completion(rig, rows, limit=20 * MAX_TOKENS) + return {r.request_id: list(r.output_token_ids) for r in rows} + finally: + rig.close() + + +def _rig_engine(rig): + return SimpleNamespace( + scheduler=rig.scheduler, + has_active_requests=lambda: False, + abort_all_requests=AsyncMock(return_value=0), + abort_one_request_for_memory=AsyncMock(return_value=None), + memory_victim_pending=lambda rid: False, + ) + + +class _Readings: + """One scripted usage figure read by the enforcer and the scheduler.""" + + def __init__(self, rig, monkeypatch, gb): + self.gb = gb + monkeypatch.setattr( + rig.scheduler, "_current_usage_bytes", lambda **_kw: int(self.gb * GB) + ) + + +def _hold_external_prefill(rig, monkeypatch, rid): + """Block the MLX thread inside ``rid``'s external prefill until released, + so the enforcer can poll while it runs (as in production).""" + entered, release = threading.Event(), threading.Event() + scheduler = rig.scheduler + original = scheduler._do_external_prefill + + def held(request, *args, **kwargs): + if request.request_id == rid: + entered.set() + assert release.wait(30) + return original(request, *args, **kwargs) + + monkeypatch.setattr(scheduler, "_do_external_prefill", held) + return entered, release + + +class _MLXThread: + """The scheduler's own thread: its MLX stream is thread-local, so the rig + is built, stepped and closed there while the test polls the enforcer.""" + + def __init__(self): + self._pool = concurrent.futures.ThreadPoolExecutor( + max_workers=1, thread_name_prefix="test-mlx" + ) + + async def run(self, fn, *args, **kwargs): + loop = asyncio.get_running_loop() + return await loop.run_in_executor( + self._pool, functools.partial(fn, *args, **kwargs) + ) + + def close(self): + self._pool.shutdown(wait=True) + + +@pytest.fixture +def mlx_thread(): + thread = _MLXThread() + yield thread + thread.close() + + +def _drain_stores(rig): + for future in list(rig.scheduler._inflight_store_futures.values()): + future.result(timeout=30) + rig.scheduler._drain_pending_async_removes() + + +async def _finish(rig, enforcer, readings, rows, gb_when_done=20, mlx=None): + outputs = [] + for _ in range(40 * MAX_TOKENS): + if all(r.is_finished() for r in rows): + break + readings.gb = gb_when_done + await tick(enforcer, readings.gb) + if mlx is None: + outputs.extend(park.step(rig)) + else: + outputs.extend(await mlx.run(park.step, rig)) + if mlx is None: + _drain_stores(rig) + else: + await mlx.run(_drain_stores, rig) + return outputs + + +def _assert_completed(rows, expected, outputs): + for row in rows: + rid = row.request_id + assert list(row.output_token_ids) == expected[rid], rid + assert dp.streamed_tokens(outputs, rid) == expected[rid], rid + (final,) = [o for o in outputs if o.request_id == rid and o.finished] + assert final.finish_reason == "length" and not final.error + + +def _decoding(rig, rows, outputs): + for _ in range(400): + if all(r.request_id in rig.scheduler.running for r in rows): + return + outputs.extend(park.step(rig)) + raise AssertionError("rows are not all decoding") + + +# --- Lone external prefill: the forced-pressure image-decode case --------- + + +@pytest.mark.asyncio +async def test_lone_external_media_prefill_at_hard_pressure_is_not_aborted( + tmp_path, enforcer, monkeypatch, caplog, mlx_thread +): + def build(rig): + return [_media(rig, "m", 1.0), _text(rig, "q1", 2.0), _text(rig, "q2", 3.0)] + + expected = _baseline(tmp_path, build) + rig = await mlx_thread.run(_rig, tmp_path / "lone", max_num_seqs=1) + try: + engine = _rig_engine(rig) + _busy(enforcer, engine) + readings = _Readings(rig, monkeypatch, 30) + entered, release = _hold_external_prefill(rig, monkeypatch, "m") + rows = await mlx_thread.run(build, rig) + + stepping = asyncio.create_task(mlx_thread.run(park.step, rig)) + assert await asyncio.to_thread(entered.wait, 30) + readings.gb = 97 # the end-of-prefill spike: over hard, under the ceiling + with caplog.at_level(logging.INFO): + await tick(enforcer, 97) + await tick(enforcer, 98) + engine.abort_all_requests.assert_not_awaited() # was abort-all here + assert rig.scheduler.memory_pressure_solo_request() == "m" + release.set() + outputs = list(await stepping) + outputs.extend(await _finish(rig, enforcer, readings, rows, mlx=mlx_thread)) + + engine.abort_one_request_for_memory.assert_not_awaited() + engine.abort_all_requests.assert_not_awaited() + assert "m runs alone (solo)" in caplog.text + _assert_completed(rows, expected, outputs) + finally: + await mlx_thread.run(rig.close) + + +@pytest.mark.asyncio +async def test_memory_scheduling_off_keeps_upstream_abort_all_for_the_lone_prefill( + tmp_path, mock_engine_pool, monkeypatch, mlx_thread # noqa: F811 +): + """Park, single victim and memory scheduling off: + the lone external prefill is not reported as solo, so hard pressure + aborts everything as on main.""" + enforcer = _make_enforcer( + mock_engine_pool, + abort_single_victim=False, + ceiling=100 * GB, + soft_threshold=0.85, + hard_threshold=0.95, + memory_scheduling="off", + ) + rig = await mlx_thread.run(_rig, tmp_path / "off", park_enabled=False) + try: + engine = _rig_engine(rig) + _busy(enforcer, engine) + readings = _Readings(rig, monkeypatch, 30) + entered, release = _hold_external_prefill(rig, monkeypatch, "m") + await mlx_thread.run(_media, rig, "m", 1.0) + + stepping = asyncio.create_task(mlx_thread.run(park.step, rig)) + assert await asyncio.to_thread(entered.wait, 30) + readings.gb = 97 # over hard, under the ceiling + await tick(enforcer, 97) + assert rig.scheduler._memory_scheduling is False + assert rig.scheduler.memory_pressure_solo_request() is None + engine.abort_all_requests.assert_awaited() + release.set() + await stepping + finally: + await mlx_thread.run(rig.close) + + +# --- A decoding row beside the external prefill is paused instead --------- + + +@pytest.mark.asyncio +async def test_spike_during_external_prefill_pauses_the_decoding_row( + tmp_path, enforcer, monkeypatch, caplog, mlx_thread +): + def build(rig): + return [_text(rig, "a", 1.0), _media(rig, "m", 2.0)] + + expected = _baseline(tmp_path, build) + rig = await mlx_thread.run(_rig, tmp_path / "beside") + try: + scheduler = rig.scheduler + engine = _rig_engine(rig) + _busy(enforcer, engine) + readings = _Readings(rig, monkeypatch, 30) + outputs = [] + a = await mlx_thread.run(_text, rig, "a", 1.0) + await mlx_thread.run(_decoding, rig, [a], outputs) + entered, release = _hold_external_prefill(rig, monkeypatch, "m") + m = await mlx_thread.run(_media, rig, "m", 2.0) + + stepping = asyncio.create_task(mlx_thread.run(park.step, rig)) + assert await asyncio.to_thread(entered.wait, 30) + readings.gb = 97 # the spike, over hard and under the ceiling + with caplog.at_level(logging.WARNING): + await tick(enforcer, 97) + assert scheduler.memory_pressure_solo_request() is None + assert scheduler._pending_decode_pauses == {"a"} + assert "pausing decoding victim a instead of aborting" in caplog.text + release.set() + outputs.extend(await stepping) + outputs.extend(await mlx_thread.run(park.step, rig)) # the pause runs + assert scheduler.requests["a"].parked + + outputs.extend(await _finish(rig, enforcer, readings, [a, m], mlx=mlx_thread)) + + engine.abort_one_request_for_memory.assert_not_awaited() + engine.abort_all_requests.assert_not_awaited() + assert a.decode_pause_count == 1 + _assert_completed([a, m], expected, outputs) + finally: + await mlx_thread.run(rig.close) + + +# --- Emergency: one pause first, abort-all as the last resort -------------- + + +def _emergency_victim(scheduler, monkeypatch, est_gb): + """The decode-pause victim's estimate at the real run's scale.""" + select = scheduler.select_decode_pause_victim + + def scaled(): + victim = select() + if victim is None: + return None + return MemoryVictim(victim.request_id, victim.tokens, int(est_gb * GB), 1) + + monkeypatch.setattr(scheduler, "select_decode_pause_victim", scaled) + + +@pytest.mark.asyncio +async def test_emergency_pauses_one_row_when_that_gets_back_under_the_ceiling( + tmp_path, enforcer, monkeypatch, caplog +): + def build(rig): + return [_text(rig, "a", 1.0), _text(rig, "b", 2.0, dp.OTHER)] + + expected = _baseline(tmp_path, build) + rig = _rig(tmp_path / "emergency") + try: + scheduler = rig.scheduler + engine = _rig_engine(rig) + _busy(enforcer, engine) + readings = _Readings(rig, monkeypatch, 30) + rows = build(rig) + outputs = [] + _decoding(rig, rows, outputs) + _emergency_victim(scheduler, monkeypatch, est_gb=6) + + readings.gb = 103 # beyond ceiling + 2 GB: emergency + with caplog.at_level(logging.WARNING): + await tick(enforcer, 103) + assert scheduler._pending_decode_pauses == {"b"} # the oldest is kept + assert "Emergency memory pressure: pausing decoding request b" in caplog.text + engine.abort_all_requests.assert_not_awaited() + + outputs.extend(park.step(rig)) # the pause runs + readings.gb = 97 # back under the ceiling + outputs.extend(await _finish(rig, enforcer, readings, rows)) + + engine.abort_all_requests.assert_not_awaited() + engine.abort_one_request_for_memory.assert_not_awaited() + _assert_completed(rows, expected, outputs) + finally: + rig.close() + + +@pytest.mark.asyncio +async def test_emergency_aborts_all_when_no_pause_gets_under_the_ceiling( + tmp_path, enforcer, monkeypatch +): + rig = _rig(tmp_path) + try: + scheduler = rig.scheduler + engine = _rig_engine(rig) + _busy(enforcer, engine) + readings = _Readings(rig, monkeypatch, 30) + rows = [_text(rig, "a", 1.0), _text(rig, "b", 2.0, dp.OTHER)] + _decoding(rig, rows, []) + _emergency_victim(scheduler, monkeypatch, est_gb=1) + + readings.gb = 103 + await tick(enforcer, 103) + + assert not scheduler._pending_decode_pauses + engine.abort_all_requests.assert_awaited_once_with(spare_parked=False) + finally: + rig.close() + + +@pytest.mark.asyncio +async def test_emergency_aborts_all_when_nothing_is_pausable( + tmp_path, enforcer, monkeypatch +): + rig = _rig(tmp_path) + try: + scheduler = rig.scheduler + engine = _rig_engine(rig) + _busy(enforcer, engine) + readings = _Readings(rig, monkeypatch, 30) + rows = [_text(rig, "a", 1.0), _text(rig, "b", 2.0, dp.OTHER)] + _decoding(rig, rows, []) + monkeypatch.setattr( + scheduler, "_decode_pause_exclusion_reason", lambda request: "test" + ) + + readings.gb = 103 + await tick(enforcer, 103) + + engine.abort_all_requests.assert_awaited_once_with(spare_parked=False) + finally: + rig.close() + + +class TestEmergencyPauseFirstBounds: + @pytest.mark.asyncio + async def test_a_pause_still_pending_after_the_bound_gives_way_to_abort_all( + self, enforcer + ): + scheduler = _ScriptedScheduler([MemoryVictim("b", 9_000, 6 * GB, 1)]) + engine = _scripted_engine(scheduler) + _busy(enforcer, engine) + + await tick(enforcer, 103) # pause requested + for _ in range(enforcer._EMERGENCY_PAUSE_MAX_POLLS): + await tick(enforcer, 103) # still pending: waits + engine.abort_all_requests.assert_not_awaited() + await tick(enforcer, 103) + + assert scheduler.paused == ["b"] + engine.abort_all_requests.assert_awaited_once_with(spare_parked=False) + + @pytest.mark.asyncio + async def test_growing_usage_does_not_wait_for_the_pause(self, enforcer): + scheduler = _ScriptedScheduler([MemoryVictim("b", 9_000, 6 * GB, 1)]) + engine = _scripted_engine(scheduler) + _busy(enforcer, engine) + + await tick(enforcer, 103) + await tick(enforcer, 105) + + engine.abort_all_requests.assert_awaited_once_with(spare_parked=False) + + @pytest.mark.asyncio + async def test_a_declined_pause_gives_way_to_abort_all(self, enforcer): + scheduler = _ScriptedScheduler([MemoryVictim("b", 9_000, 6 * GB, 1)]) + engine = _scripted_engine(scheduler) + _busy(enforcer, engine) + + await tick(enforcer, 103) + scheduler.status["b"] = "declined" + await tick(enforcer, 103) + + engine.abort_all_requests.assert_awaited_once_with(spare_parked=False) + + +def _scripted_engine(scheduler): + engine = SimpleNamespace( + scheduler=scheduler, + has_active_requests=lambda: False, + abort_all_requests=AsyncMock(return_value=2), + abort_one_request_for_memory=AsyncMock(return_value=None), + memory_victim_pending=lambda rid: False, + ) + return engine + + +# --- Transient reservation before an external media prefill --------------- + + +@pytest.mark.asyncio +async def test_media_prefill_whose_peak_crosses_the_hard_line_waits_beside_work( + tmp_path, enforcer, monkeypatch, caplog +): + def build(rig): + return [_text(rig, "a", 1.0), _media(rig, "m", 2.0)] + + expected = _baseline(tmp_path, build) + rig = _rig(tmp_path / "reserve") + try: + scheduler = rig.scheduler + engine = _rig_engine(rig) + _busy(enforcer, engine) + await tick(enforcer, 30) # propagate the lines + readings = _Readings(rig, monkeypatch, 30) + outputs = [] + a = _text(rig, "a", 1.0) + _decoding(rig, [a], outputs) + + # Usage under the soft line (admission is open) and a media prefill + # whose KV lands between the resume line and the admission line: the + # plain preflight passes it, the reservation does not. + fit_line = scheduler._park_resume_lines()[0] + admission = scheduler._admission_limit_bytes() + readings.gb = 80 + kv = (fit_line + admission) // 2 - 80 * GB + monitor = scheduler.memory_monitor + monkeypatch.setattr( + monitor, "estimate_resident_kv_bytes", lambda n, chunk_tokens=1: kv + ) + m = _media(rig, "m", 2.0) + + with caplog.at_level(logging.INFO): + outputs.extend(park.step(rig, 3)) + assert "m" not in scheduler.running + assert [r.request_id for r in scheduler.waiting] == ["m"] + assert "Deferring media prefill m" in caplog.text + + outputs.extend(await _finish(rig, enforcer, readings, [a, m])) + engine.abort_all_requests.assert_not_awaited() + engine.abort_one_request_for_memory.assert_not_awaited() + _assert_completed([a, m], expected, outputs) + finally: + rig.close() + + +def test_the_reservation_needs_the_park_feature(tmp_path, monkeypatch): + rig = _rig(tmp_path, park_enabled=False) + try: + scheduler = rig.scheduler + m = _media(rig, "m", 1.0) + est = SimpleNamespace(estimated=10**15) + assert scheduler._external_media_reservation_short(m, est) is False + finally: + rig.close() + + +def test_a_media_prompt_whose_images_are_cached_is_not_reserved(tmp_path, monkeypatch): + rig = _rig(tmp_path) + rig.scheduler.config.media_text_suffix_chunked = True + try: + scheduler = rig.scheduler + scheduler._num_admitted_requests = lambda: 1 + scheduler._memory_hard_limit_bytes = 100 * GB + m = _media(rig, "m", 1.0) + m.vlm_media_end = 8 + m.cached_tokens = 8 + est = SimpleNamespace(estimated=10**15) + assert scheduler._external_media_reservation_short(m, est) is False + m.cached_tokens = 4 + assert scheduler._external_media_reservation_short(m, est) is True + finally: + rig.close() diff --git a/tests/test_memory_resume_thrash.py b/tests/test_memory_resume_thrash.py index 73396b305c..2ce4fa1d7f 100644 --- a/tests/test_memory_resume_thrash.py +++ b/tests/test_memory_resume_thrash.py @@ -48,7 +48,7 @@ from test_scheduler_prefill_memory_guard import _make_scheduler import omlx.scheduler as scheduler_module -from omlx.request import Request, SamplingParams +from omlx.request import MemoryVictim, Request, SamplingParams from omlx.settings import GlobalSettings, SchedulerSettings GB = 1024**3 @@ -274,10 +274,11 @@ async def test_hard_pressure_neither_pauses_nor_aborts_it(self, enforcer, caplog @pytest.mark.asyncio async def test_the_emergency_brake_still_aborts_it(self, enforcer): + # Pausing ~1 GB cannot get 103 GB under the ceiling: no pause-first. # The emergency brake measures against the physical cap (#4312); here # it is the ceiling. enforcer._get_abort_limit_bytes = lambda: 100 * GB - scheduler = _SoloScheduler([_victim("a", kept=0)], solo="a") + scheduler = _SoloScheduler([MemoryVictim("a", 9_000, GB, 0)], solo="a") engine = _engine(scheduler) _busy(enforcer, engine) diff --git a/tests/test_memory_scheduling_gate.py b/tests/test_memory_scheduling_gate.py index 657b371a1e..9c0810c731 100644 --- a/tests/test_memory_scheduling_gate.py +++ b/tests/test_memory_scheduling_gate.py @@ -274,6 +274,17 @@ def test_off_rejects_a_fits_later_request_with_the_old_error(gated): assert rejection.message.startswith("Prefill would require") +def test_off_does_not_exempt_an_external_prefill_from_the_enforcer(): + """An external-loop prefill with nothing admitted is not reported as solo + off, so the enforcer's hard-pressure path stays upstream's.""" + scheduler = _make_scheduler() + scheduler._external_prefill_request_id = "ext" + scheduler._memory_scheduling = True + assert scheduler.memory_pressure_solo_request() == "ext" + scheduler._memory_scheduling = False + assert scheduler.memory_pressure_solo_request() is None + + def test_off_endpoint_says_why_capacity_is_unavailable( capacity_env, monkeypatch, diff --git a/tests/test_process_memory_enforcer.py b/tests/test_process_memory_enforcer.py index 2e075dda55..37bb9fd479 100644 --- a/tests/test_process_memory_enforcer.py +++ b/tests/test_process_memory_enforcer.py @@ -3847,17 +3847,22 @@ async def test_flag_unset_keeps_the_legacy_abort_all(self, enforcer, monkeypatch engine.abort_one_request_for_memory.assert_not_awaited() @pytest.mark.asyncio - async def test_no_victim_falls_back_to_abort_all_sparing_parked( - self, enforcer, monkeypatch + async def test_no_live_victim_aborts_nothing_below_the_emergency( + self, enforcer, monkeypatch, caplog ): + """No live request means only queued ones are left, and they hold no + memory: aborting them frees nothing (a forced-pressure image-decode run + aborted queued requests this way). The emergency brake stays armed.""" enforcer._single_victim_on = True engine = self._engine([]) self._busy(enforcer, engine) - await self._tick(enforcer, 97) + with caplog.at_level("WARNING"): + await self._tick(enforcer, 97) engine.abort_one_request_for_memory.assert_awaited_once() - engine.abort_all_requests.assert_awaited_once_with(spare_parked=True) + engine.abort_all_requests.assert_not_awaited() + assert "no live request holds memory to free" in caplog.text @pytest.mark.asyncio async def test_engine_without_the_hook_falls_back_to_abort_all( From 31a8f6348d57340228c763e81a67f270336f120d Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Tue, 6 Oct 2026 02:07:30 -0600 Subject: [PATCH 38/46] fix(memory): keep the emergency brake on no-live-victim and make the solo read thread-safe - The no-live-victim relief skipped abort-all without re-checking the level. Usage that grew past the emergency line during the poll now gets the last resort: one decode pause first when it gets back under the ceiling, then abort-all. The relief stays below the emergency level only. The re-check does not count another over-ceiling poll. - memory_pressure_solo_request (enforcer thread) cleared _solo_request_id for a finished request while the MLX thread could be marking a new one. The enforcer read is now read-only; only the scheduler thread (_solo_holds) clears the mark. --- omlx/process_memory_enforcer.py | 31 +++++++++++ omlx/scheduler.py | 25 +++++++-- tests/test_memory_external_prefill.py | 77 ++++++++++++++++++++++++++- tests/test_memory_resume_thrash.py | 47 +++++++++++++++- 4 files changed, 173 insertions(+), 7 deletions(-) diff --git a/omlx/process_memory_enforcer.py b/omlx/process_memory_enforcer.py index 10277e78e6..db6c12cb4d 100644 --- a/omlx/process_memory_enforcer.py +++ b/omlx/process_memory_enforcer.py @@ -1098,6 +1098,17 @@ def _is_emergency_pressure(self, current: int, ceiling: int) -> bool: return True return self._over_ceiling_polls >= _EMERGENCY_OVER_CEILING_POLLS + def _at_emergency_level(self, current: int, ceiling: int) -> bool: + """``_is_emergency_pressure`` without counting another poll. + + For a re-check within the poll that already counted itself. + """ + if ceiling <= 0 or current < ceiling: + return False + if current >= ceiling + _EMERGENCY_OVER_CEILING_MARGIN_BYTES: + return True + return self._over_ceiling_polls >= _EMERGENCY_OVER_CEILING_POLLS + def _refresh_effective_metal_cap_bytes(self) -> int: """Refresh the cached effective Metal cap outside the poll hot path.""" self._effective_metal_cap_bytes = get_effective_metal_cap_bytes() @@ -2497,6 +2508,26 @@ async def _check_and_enforce(self) -> None: entry.engine, busy_victim ) ) + if single is _NO_LIVE_VICTIM: + # The relief is for the non-emergency path + # only: if usage grew past the emergency line + # meanwhile, the brake gets its last resort + # (one pause first, then abort-all below). + now = self._current_usage_bytes() + if self._at_emergency_level(now, ceiling): + logger.warning( + "Hard memory pressure on '%s' reached " + "the emergency level (current=%s, " + "ceiling=%s) with no live victim; " + "applying the emergency brake", + busy_victim, + _format_gb(now), + _format_gb(ceiling), + ) + if self._emergency_pause_first(now, ceiling): + break + emergency = True + single = None if single is _NO_LIVE_VICTIM: logger.warning( "Hard memory pressure on '%s': no live " diff --git a/omlx/scheduler.py b/omlx/scheduler.py index e6936efc5b..ecca6ff505 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -12539,18 +12539,33 @@ def _mark_solo(self, head: "Request", why: str) -> None: ) def _solo_request(self) -> "Request | None": - """The live solo request (admitted, not parked), clearing a stale mark.""" + """The live solo request (admitted, not parked), else None. + + Read-only: the enforcer thread calls it through + ``memory_pressure_solo_request`` while the MLX thread may be marking + a new solo request, so only ``_solo_holds`` (MLX thread) clears a + stale mark. + """ rid = self._solo_request_id if rid is None: return None request = self.requests.get(rid) - if request is None or request.is_finished(): - self._solo_request_id = None + if request is None or request.is_finished() or request.parked: return None - return None if request.parked else request + return request def _solo_holds(self, head: "Request") -> bool: - """Whether a running solo request keeps ``head`` from being admitted.""" + """Whether a running solo request keeps ``head`` from being admitted. + + Runs on the MLX thread, the only writer of ``_solo_request_id``: it + clears the mark once its request is gone or finished. + """ + rid = self._solo_request_id + if rid is not None: + request = self.requests.get(rid) + if request is None or request.is_finished(): + self._solo_request_id = None + return False solo = self._solo_request() return solo is not None and solo is not head diff --git a/tests/test_memory_external_prefill.py b/tests/test_memory_external_prefill.py index 1b7142aaff..f6f1bbdc5e 100644 --- a/tests/test_memory_external_prefill.py +++ b/tests/test_memory_external_prefill.py @@ -34,7 +34,7 @@ import logging import threading from types import SimpleNamespace -from unittest.mock import AsyncMock +from unittest.mock import AsyncMock, patch import pytest import test_scheduler_decode_pause as dp @@ -590,3 +590,78 @@ def test_a_media_prompt_whose_images_are_cached_is_not_reserved(tmp_path, monkey assert scheduler._external_media_reservation_short(m, est) is True finally: rig.close() + + +# --- No live victim when usage grows past the emergency line ---------------- + + +async def _tick_growing(enforcer, start_gb, grown_gb): + """One poll whose first reading is ``start_gb`` and every later one + ``grown_gb``: usage keeps growing while the poll runs.""" + readings = iter([start_gb * GB]) + + def active(): + return next(readings, grown_gb * GB) + + with patch("omlx.process_memory_enforcer.mx") as mock_mx: + mock_mx.get_active_memory.side_effect = active + mock_mx.get_cache_memory.return_value = 0 + await enforcer._check_and_enforce() + + +class TestNoLiveVictimNeverDisarmsTheEmergencyBrake: + @pytest.mark.asyncio + async def test_hard_but_not_emergency_aborts_nothing(self, enforcer): + engine = _scripted_engine(_ScriptedScheduler([])) + _busy(enforcer, engine) + + await tick(enforcer, 97) + + engine.abort_one_request_for_memory.assert_awaited_once() + engine.abort_all_requests.assert_not_awaited() + + @pytest.mark.asyncio + async def test_usage_growing_into_emergency_still_aborts_all(self, enforcer): + """The poll starts below the ceiling (single-victim path), finds no + live victim, and usage has meanwhile grown past ceiling + 2 GB: the + last resort runs instead of "nothing aborted".""" + engine = _scripted_engine(_ScriptedScheduler([])) + _busy(enforcer, engine) + + await _tick_growing(enforcer, 97, 103) + + engine.abort_all_requests.assert_awaited_once_with(spare_parked=False) + + @pytest.mark.asyncio + async def test_usage_growing_into_emergency_tries_one_pause_first( + self, enforcer, caplog + ): + """A row that becomes pausable only once usage reached the emergency + (the hard-path pause found none) is paused before abort-all.""" + scheduler = _ScriptedScheduler([]) + victim = MemoryVictim("b", 9_000, 6 * GB, 1) + calls = [] + + def select(): + calls.append(1) + return victim if len(calls) > 1 else None + + scheduler.select_decode_pause_victim = select + engine = _scripted_engine(scheduler) + _busy(enforcer, engine) + + with caplog.at_level(logging.WARNING): + await _tick_growing(enforcer, 97, 103) + + assert scheduler.paused == ["b"] + assert "Emergency memory pressure: pausing decoding request b" in caplog.text + engine.abort_all_requests.assert_not_awaited() + + @pytest.mark.asyncio + async def test_emergency_with_no_live_victim_aborts_all(self, enforcer): + engine = _scripted_engine(_ScriptedScheduler([])) + _busy(enforcer, engine) + + await tick(enforcer, 103) + + engine.abort_all_requests.assert_awaited_once_with(spare_parked=False) diff --git a/tests/test_memory_resume_thrash.py b/tests/test_memory_resume_thrash.py index 2ce4fa1d7f..87eaf074a1 100644 --- a/tests/test_memory_resume_thrash.py +++ b/tests/test_memory_resume_thrash.py @@ -48,7 +48,7 @@ from test_scheduler_prefill_memory_guard import _make_scheduler import omlx.scheduler as scheduler_module -from omlx.request import MemoryVictim, Request, SamplingParams +from omlx.request import MemoryVictim, Request, RequestStatus, SamplingParams from omlx.settings import GlobalSettings, SchedulerSettings GB = 1024**3 @@ -529,3 +529,48 @@ def reading(ids): assert scheduler.get_park_stats()["decode_resumes"] == 2 finally: rig.close() + + +# --- A solo mark raced between the enforcer and the MLX thread ----------------- + + +def test_the_enforcer_read_never_clears_a_solo_mark_set_meanwhile(lined): + """The enforcer thread reads a finished solo request while the MLX thread + marks a new one: the new mark survives (the enforcer side is read-only).""" + scheduler, _, admitted = lined + old = _parked_request("old") + old.parked = False + old.status = RequestStatus.FINISHED_STOPPED + new = _parked_request("new") + scheduler.requests = {"old": old} + scheduler._solo_request_id = "old" + admitted["ids"] = frozenset() + + class _Interleaved(dict): + def get(self, key, default=None): + value = super().get(key, default) + if key == "old": + # MLX thread, between the enforcer's read and any write back. + scheduler._mark_solo(new, "solo") + return value + + scheduler.requests = _Interleaved(scheduler.requests) + + assert scheduler.memory_pressure_solo_request() is None + assert scheduler._solo_request_id == "new" + + +def test_only_the_scheduler_thread_clears_a_finished_solo_mark(lined): + scheduler, _, _ = lined + old = _parked_request("old") + old.parked = False + old.status = RequestStatus.FINISHED_STOPPED + scheduler.requests = {"old": old} + scheduler._solo_request_id = "old" + + assert scheduler.memory_pressure_solo_request() is None + assert scheduler._solo_request_id == "old" # the enforcer read wrote nothing + + head = _parked_request("head") + assert scheduler._solo_holds(head) is False # scheduler thread + assert scheduler._solo_request_id is None From 60c4fcd80a187e894fe6947134910d6bc56062c5 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Tue, 6 Oct 2026 04:17:41 -0600 Subject: [PATCH 39/46] fix(scheduler): keep queued requests waiting while memory is scheduled on purpose The admission-stall clock started when the head first met memory pressure and kept running while a solo request decoded (the solo hold breaks before the stall check) and while another request prefilled chunk after chunk. In a real-model run the first check after the solo run failed the third request ("memory pressure persisted for 90.6s (store_cache_backpressure)"; image prefill: 67.5s, admission_paused) although the server progressed all along. The clock now measures time without progress: a token emitted, a prefill chunk processed, an external prefill finished, a request admitted or a store-cache write drained restarts it. Without progress the head still fails after 60 s. While a solo request runs, a fits-later head backs off, or a parked or decode-paused request waits, the bound is scheduler.admission_no_progress_timeout_s (OMLX_ADMISSION_NO_PROGRESS_TIMEOUT_S, default 600 s), so a genuine deadlock surfaces with memory_admission_stalled and no_progress_seconds. Store-cache backpressure is not a failure while the writer drains. "Admission waiting for memory: ; request(s) progressing" is logged every 30 s per head. The progress clock is memory scheduling (memory.memory_scheduling): with it off, the default for a stock install, the head fails 60 s after it first blocked, whatever else progresses, with main's message and metadata (no no_progress_seconds) and no wait log. --- README.md | 1 + docs/TESTING.md | 4 +- omlx/scheduler.py | 153 ++++++- omlx/settings.py | 45 ++ tests/test_memory_scheduling_gate.py | 71 ++- tests/test_scheduler_admission_progress.py | 488 +++++++++++++++++++++ tests/test_settings.py | 1 + 7 files changed, 743 insertions(+), 20 deletions(-) create mode 100644 tests/test_scheduler_admission_progress.py diff --git a/README.md b/README.md index ca43546d25..b78da1690b 100644 --- a/README.md +++ b/README.md @@ -291,6 +291,7 @@ With memory scheduling on: - **Never fits.** A request that cannot fit even with nothing else running (model weights + KV for the prompt plus `max_tokens` + the prefill transient, over the memory guard's capacity line) is rejected up front with HTTP 400 and `omlx_code: "context_exceeds_capacity"`. The usual error envelope stays (`message`, `type`, `code`, `estimated_bytes`, `limit_bytes`) and adds `required_bytes`, `capacity_bytes`, `weights_bytes`, `kv_bytes_per_token`, `requested_context_tokens`, `requested_max_tokens`, `max_viable_context_tokens` and `retryable: false`. Compact or shorten the context, or lower `max_tokens`, before retrying. - **Fits later.** A request that fits alone but not right now is not rejected. It waits at the head of the queue until running requests free memory. +- **Stall clock.** A queued request fails after 60 s without progress by any request (a token, a prefill chunk, a drained cache write), not 60 s after it started waiting. While memory is held on purpose, the bound is `scheduler.admission_no_progress_timeout_s` (default 600 s). - **Capacity numbers.** `GET /v1/omlx/capacity?model=&context_tokens=&max_tokens=` (API key like the other `/v1` routes) returns the same numbers for a request of that size plus `free_bytes_now`, without loading the model. An unknown model is a 404 and an unloaded one a 409; `available: false` when no estimate exists. Chat completions also carry an `X-oMLX-Max-Context-Tokens` header: the largest prompt plus `max_tokens` that fits alone. With memory scheduling off, a request is checked against the current usage and rejected if it does not fit now, a queued request fails 60 s after it started waiting for memory, and there is no header. The capacity endpoint still answers for a loaded model, with `available: false`, `memory_scheduling: "off"` and the reason. diff --git a/docs/TESTING.md b/docs/TESTING.md index 0964b7e3a0..219c479af7 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -237,7 +237,7 @@ Mocked tests do not replace hardware validation: with a real model, abort a long # Memory scheduling gate tests -Run `python -m pytest -q tests/test_memory_scheduling_gate.py` to check `memory.memory_scheduling` (env `OMLX_MEMORY_SCHEDULING`; `auto`, `on` or `off`, default `auto`). It gates the never-fits 400 with the capacity endpoint numbers and the `X-oMLX-Max-Context-Tokens` header, and the fits-later wait. `auto` is on when the prefill memory guard is on and an explicit ceiling is set (`memory_guard_tier: custom` with `memory_guard_custom_ceiling_gb` > 0; a ceiling value left under another tier does not count). `on` forces it on but still needs the guard (with the guard off it stays off and logs a warning). `off` forces it off. The `ProcessMemoryEnforcer` resolves the mode at startup and whenever the mode, the guard, the tier or the ceiling changes (the admin settings apply live), logs `Memory scheduling: on (explicit ceiling 48.0 GB)` or the reason it is off, and propagates the result to every scheduler (`Scheduler._memory_scheduling`, False until an enforcer sets it). The tests cover the resolution matrix, the setting (default, `to_dict`, `from_dict`, env override, validation, the admin GET and POST), and, with it off, upstream behaviour on each path: no capacity estimate, snapshot or header (a cached hint is not served either); a request whose `max_tokens` can never fit passes when its prompt fits now; a fits-alone-but-not-now request gets the old current-usage rejection; an external-loop prefill is not reported as solo to the enforcer; and the capacity endpoint returns `available: false` with `memory_scheduling: "off"` and the reason, while unknown and unloaded models keep their 404 and 409. `tests/test_memory_external_prefill.py` also drives the real enforcer with park, single victim and memory scheduling off: the lone external prefill at hard pressure gets upstream's abort-all. The suites below that test these behaviours set the mode on explicitly (`scheduler._memory_scheduling = True`, or `memory_scheduling="on"` on the real enforcer). +Run `python -m pytest -q tests/test_memory_scheduling_gate.py` to check `memory.memory_scheduling` (env `OMLX_MEMORY_SCHEDULING`; `auto`, `on` or `off`, default `auto`). It gates three behaviours: the never-fits 400 with the capacity endpoint numbers and the `X-oMLX-Max-Context-Tokens` header; the fits-later wait; and the progress-based admission-stall clock. `auto` is on when the prefill memory guard is on and an explicit ceiling is set (`memory_guard_tier: custom` with `memory_guard_custom_ceiling_gb` > 0; a ceiling value left under another tier does not count). `on` forces it on but still needs the guard (with the guard off it stays off and logs a warning). `off` forces it off. The `ProcessMemoryEnforcer` resolves the mode at startup and whenever the mode, the guard, the tier or the ceiling changes (the admin settings apply live), logs `Memory scheduling: on (explicit ceiling 48.0 GB)` or the reason it is off, and propagates the result to every scheduler (`Scheduler._memory_scheduling`, False until an enforcer sets it). The tests cover the resolution matrix, the setting (default, `to_dict`, `from_dict`, env override, validation, the admin GET and POST), and, with it off, upstream behaviour on each path: no capacity estimate, snapshot or header (a cached hint is not served either); a request whose `max_tokens` can never fit passes when its prompt fits now; a fits-alone-but-not-now request gets the old current-usage rejection; the stall clock fails the head 60 s after it first blocked, whatever else progresses, with the old message and metadata (no `no_progress_seconds`), also behind a solo request and for store-cache backpressure; an external-loop prefill is not reported as solo to the enforcer; and the capacity endpoint returns `available: false` with `memory_scheduling: "off"` and the reason, while unknown and unloaded models keep their 404 and 409. `tests/test_memory_external_prefill.py` also drives the real enforcer with park, single victim and memory scheduling off: the lone external prefill at hard pressure gets upstream's abort-all. The suites below that test these behaviours set the mode on explicitly (`scheduler._memory_scheduling = True`, or `memory_scheduling="on"` on the real enforcer). Run `python -m pytest -q tests/test_memory_scheduling_admin_state.py` to check memory scheduling across admin settings saves. The cases load the real settings with `memory_scheduling: "on"` in `settings.json`, build the live enforcer from them as the server does, and drive the real admin routes. A save of `max_concurrent_requests`, `chunked_prefill` or `memory_guard_tier` keeps the mode on the live settings object and in `settings.json` (a reload sees it again), keeps it on and propagated, and logs no `Memory scheduling:` line. Loading the settings page (`GET /admin/api/global-settings`, which builds one tier-preview enforcer per tier) logs none either: only an enforcer that drives an engine pool logs its state. An explicit `memory_scheduling` POST, including one that repeats the current mode, re-resolves, logs the state and propagates it to the schedulers. The GET reports the live state as `memory.memory_scheduling_effective` (`enabled` and `reason`, `null` without an enforcer), the POST response carries it, and the factory defaults response does not. @@ -263,4 +263,6 @@ Run `python -m pytest -q tests/test_memory_resume_thrash.py` to check that a pau Run `python -m pytest -q tests/test_memory_external_prefill.py` to check memory pressure while a prompt prefills in the external loop (a media prompt whose images are not all cached; it cannot be parked). A request in that loop with nothing else admitted runs alone: at hard pressure below the emergency threshold the enforcer neither pauses nor aborts it. With a decoding row beside it, the decoding row is paused instead. When the single-victim selection finds no live request (queued requests hold no memory), the non-emergency path aborts nothing; before, it fell back to aborting every request. At emergency pressure (beyond the ceiling) the enforcer first pauses the largest pausable decoding row when freeing its estimate brings usage back under the ceiling, and waits for that pause at most two polls (`_EMERGENCY_PAUSE_MAX_POLLS`) and only while usage does not grow; abort-all stays the last resort when nothing is pausable, no pause gets under the ceiling, or the pause is declined or too slow. With the park feature on, a media prefill beside admitted work whose estimated peak (current usage, exact KV and transient) crosses the resume line (the hard watermark minus 5%) waits at the head until an admitted row leaves; it does not pause a decoding row for room, because the paused row would be parked ahead of it and resume first. The external-loop tests block the scheduler's own thread inside the external prefill so the real enforcer polls while it runs, as in production. The lone external prefill counts as solo only with memory scheduling on; these tests set it on. +Run `python -m pytest -q tests/test_scheduler_admission_progress.py` to check that a queued request waits while memory is scheduled on purpose. The admission-stall clock measures time without progress: a token emitted, a prefill chunk processed, an external prefill finished, a request admitted or a store-cache write drained restarts it. Without progress the head fails after 60 s; while a solo request runs, a fits-later head backs off, or a parked or decode-paused request waits, it fails only after `scheduler.admission_no_progress_timeout_s` (`OMLX_ADMISSION_NO_PROGRESS_TIMEOUT_S`, default 600 s) without progress, so a genuine deadlock still surfaces with `memory_admission_stalled` and `no_progress_seconds`. Store-cache backpressure is not a failure while the writer drains. The scheduler logs `Admission waiting for memory: ; request(s) progressing` every 30 s per head. The real-rig cases drive the real enforcer and scheduler on a controlled clock (2 s per step): three requests that fit one at a time complete in sequence (the old clock failed the second after 60 s while the first still decoded), and a wedged decode still fails the queued request. These cases run with memory scheduling on; off, the clock is upstream's fixed 60 s from when the head first blocked. + Mocked tests do not replace hardware validation: with a real model, run three concurrent long prompts under a ceiling too low for all of them and check that each completes with the park/resume log lines and a cached count close to the last commit, and that no client sees a memory error. diff --git a/omlx/scheduler.py b/omlx/scheduler.py index ecca6ff505..f4b9befc2e 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -1526,6 +1526,8 @@ def _is_turboquant_kv_family_cache(cache_obj: Any) -> bool: PARK_THRASH_FREE_DELTA_FRACTION = 0.05 # Seconds between "waiting" log lines for the same parked head. _PARK_WAIT_LOG_INTERVAL_S = 30.0 +# Seconds between "Admission waiting for memory" lines for the same head. +_ADMISSION_WAIT_LOG_INTERVAL_S = 30.0 # Saturation value of ``_polls_since_resume``: "long enough since the last # resume that the hysteresis gate is open". It is the initial value (no resume # has happened yet) and the cap that keeps the counter from growing without @@ -2167,6 +2169,12 @@ class SchedulerConfig: # a pause keeps every generated token exactly (no re-prefill), while the # abort that follows an exhausted budget loses them all. max_decode_pauses_per_request: int = 8 + # A queued request waiting for memory fails only when no request made + # progress (a token, a prefill chunk, an admission, a drained store-cache + # write) for this long while memory is scheduled on purpose (a parked or + # decode-paused request, a solo request, a deferred fits-later head). + # Otherwise the 60 s no-progress line applies. + admission_no_progress_timeout_s: float = 600.0 park_resume_ok_polls: int = 3 # Paged cache settings (internal defaults) @@ -2736,6 +2744,11 @@ def __init__( self._memory_admission_blocked_since: float = 0.0 self._store_cache_admission_blocked_request_id: str | None = None self._store_cache_admission_blocked_since: float = 0.0 + # Last time any request made progress (see _note_admission_progress); + # the admission-stall clocks run from it. None until the first one. + self._admission_progress_at: float | None = None + # Last "Admission waiting for memory" line (head id, time). + self._admission_wait_logged: tuple[str, float] | None = None # EWMA estimator of per-token chunk transient bytes, used by # _adaptive_chunk_size in the caution zone. Owned per-scheduler. _tracker_model_id = "" @@ -3390,6 +3403,9 @@ def _drain_pending_async_removes(self) -> bool: drained = True self._pending_async_removes = pending if drained: + # A drained store-cache write is progress: backpressure is not a + # stall while the writer drains. + self._note_admission_progress() # The completion-time deferred clear may have already fired while # the async store worker still owned extracted KV buffers. Anchor # another ordinary deferred clear to the point where those final @@ -6067,8 +6083,62 @@ def _memory_scheduling_on(self) -> bool: """Whether memory scheduling is on (see ``_memory_scheduling``).""" return getattr(self, "_memory_scheduling", False) is True + def _note_admission_progress(self) -> None: + """Record that a request made progress: a token was emitted, a + prefill chunk or an external prefill ran, a request was admitted, or + a store-cache write drained. The admission-stall clocks restart + (with memory scheduling on).""" + self._admission_progress_at = time.monotonic() + + def _admission_idle_since(self, blocked_since: float) -> float: + """Start of the current no-progress stretch for a blocked head. + + With memory scheduling off the clock is upstream's: it runs from + when the head first blocked, whatever else progresses. + """ + progress = self._admission_progress_at + if progress is None or not self._memory_scheduling_on(): + return blocked_since + return max(blocked_since, progress) + + def _deliberate_memory_hold(self) -> bool: + """Whether memory is being scheduled on purpose: a solo request runs, + a fits-later head backs off, or a parked or decode-paused request + waits. A queued request then waits under the long no-progress bound. + """ + if self._solo_request() is not None or self._deferred_admissions: + return True + return any(request.parked for request in self.waiting) + + def _log_admission_wait(self, request_id: str, reason: str) -> None: + now = time.monotonic() + last = self._admission_wait_logged + if ( + last is not None + and last[0] == request_id + and now - last[1] < _ADMISSION_WAIT_LOG_INTERVAL_S + ): + return + self._admission_wait_logged = (request_id, now) + logger.info( + "Admission waiting for memory: %s; %d request(s) progressing", + reason, + self._num_admitted_requests(), + ) + def _memory_admission_stall_output(self, reason: str) -> RequestOutput | None: - """Fail one head-of-line request after persistent memory admission stall.""" + """Fail one head-of-line request after a persistent memory admission + stall in which no request made progress. + + Progress by any request (``_note_admission_progress``) restarts the + clock: admitted work that drains will free the memory the head waits + for. The line is ``_MEMORY_ADMISSION_STALL_TIMEOUT_S`` without + progress, or ``admission_no_progress_timeout_s`` while memory is + scheduled on purpose (``_deliberate_memory_hold``), so a genuine + deadlock still surfaces with an error. With memory scheduling off + the clock is upstream's: ``_MEMORY_ADMISSION_STALL_TIMEOUT_S`` from + when the head first blocked. + """ if not self.waiting: self._clear_memory_admission_blocker() return None @@ -6080,10 +6150,13 @@ def _memory_admission_stall_output(self, reason: str) -> RequestOutput | None: # client's own timeouts apply. self._clear_memory_admission_blocker(request_id) return None + progress_clock = self._memory_scheduling_on() now = time.monotonic() if request_id != self._memory_admission_blocked_request_id: self._memory_admission_blocked_request_id = request_id self._memory_admission_blocked_since = now + if progress_clock: + self._log_admission_wait(request_id, reason) return None timeout = getattr( @@ -6091,7 +6164,17 @@ def _memory_admission_stall_output(self, reason: str) -> RequestOutput | None: "_MEMORY_ADMISSION_STALL_TIMEOUT_S", Scheduler._MEMORY_ADMISSION_STALL_TIMEOUT_S, ) - if now - self._memory_admission_blocked_since < timeout: + if progress_clock and self._deliberate_memory_hold(): + timeout = max( + timeout, + float(getattr(self.config, "admission_no_progress_timeout_s", 600.0)), + ) + idle_for = now - self._admission_idle_since( + self._memory_admission_blocked_since + ) + if idle_for < timeout: + if progress_clock: + self._log_admission_wait(request_id, reason) return None stalled_for = now - self._memory_admission_blocked_since @@ -6112,10 +6195,23 @@ def _memory_admission_stall_output(self, reason: str) -> RequestOutput | None: fmt=format_bytes, tail=["reduce context length", "lower hot_cache_max_size"], ) - message = ( - "Request could not be admitted because memory pressure persisted " - f"for {stalled_for:.1f}s ({reason}). {advice}." - ) + metadata = { + "request_id": request_id, + "reason": reason, + "stalled_seconds": int(stalled_for), + } + if progress_clock: + message = ( + "Request could not be admitted because memory pressure persisted " + f"for {stalled_for:.1f}s ({reason}) and no request made progress " + f"for {idle_for:.1f}s. {advice}." + ) + metadata["no_progress_seconds"] = int(idle_for) + else: + message = ( + "Request could not be admitted because memory pressure persisted " + f"for {stalled_for:.1f}s ({reason}). {advice}." + ) logger.warning("Memory admission stalled for %s: %s", request_id, message) return RequestOutput( request_id=request_id, @@ -6123,11 +6219,7 @@ def _memory_admission_stall_output(self, reason: str) -> RequestOutput | None: finish_reason="error", error=message, error_code="memory_admission_stalled", - error_metadata={ - "request_id": request_id, - "reason": reason, - "stalled_seconds": int(stalled_for), - }, + error_metadata=metadata, ) def _store_cache_admission_stall_output( @@ -6148,18 +6240,29 @@ def _store_cache_admission_stall_output( if request.parked: self._clear_store_cache_admission_blocker(request_id) return None + progress_clock = self._memory_scheduling_on() now = time.monotonic() if request_id != self._store_cache_admission_blocked_request_id: self._store_cache_admission_blocked_request_id = request_id self._store_cache_admission_blocked_since = now + if progress_clock: + self._log_admission_wait(request_id, reason) return None + # Backpressure, not a failure, while the writer drains (a drained + # write is progress) or other requests progress. Memory scheduling + # off: upstream's fixed timeout from when the head first blocked. timeout = getattr( self, "_STORE_CACHE_ADMISSION_STALL_TIMEOUT_S", Scheduler._STORE_CACHE_ADMISSION_STALL_TIMEOUT_S, ) - if now - self._store_cache_admission_blocked_since < timeout: + idle_for = now - self._admission_idle_since( + self._store_cache_admission_blocked_since + ) + if idle_for < timeout: + if progress_clock: + self._log_admission_wait(request_id, reason) return None stalled_for = now - self._store_cache_admission_blocked_since @@ -6169,11 +6272,16 @@ def _store_cache_admission_stall_output( self._clear_request_admission_bookkeeping(request_id) get_prefill_tracker().remove(request_id) + progress = ( + f" and no request made progress for {idle_for:.1f}s" + if progress_clock + else "" + ) message = ( "Request could not be admitted because store-cache cleanup stayed " - f"full for {stalled_for:.1f}s ({reason}). The previous response " - "cache is still being persisted; retry after the cache writer drains " - "or reduce cache/write pressure." + f"full for {stalled_for:.1f}s ({reason}){progress}. The previous " + "response cache is still being persisted; retry after the cache " + "writer drains or reduce cache/write pressure." ) logger.warning( "Store-cache admission stalled for %s: %s " @@ -6194,6 +6302,7 @@ def _store_cache_admission_stall_output( "request_id": request_id, "reason": reason, "stalled_seconds": int(stalled_for), + **({"no_progress_seconds": int(idle_for)} if progress_clock else {}), "store_cache_in_flight": gate_in_flight, "pending_store_cleanups": pending_cleanups, "store_cache_cap": gate_cap, @@ -7765,6 +7874,7 @@ def too_short_to_pack(request: Request) -> bool: raise _PackedPrefillError(error) from error else: done = self._run_prefill_chunks(plans) if plans else [True] + self._note_admission_progress() except _PackedPrefillError as e: logger.error( "Packed prefill failed for %s: %s", @@ -15070,12 +15180,19 @@ def _schedule_waiting_scan( # overtakes them while they wait. if self.waiting[0].parked and self._park_hold_applies(self.waiting[0]): break - # A solo request runs alone: nothing is admitted beside it. + # A solo request runs alone: nothing is admitted beside it. The + # head waits while it progresses (the long no-progress bound). if self._solo_holds(self.waiting[0]): + stalled = self._memory_admission_stall_output("solo_hold") + if stalled is not None: + rejected_outputs.append(stalled) break # A fits-later head that deferred keeps the hold until the memory # picture changes; retrying earlier only restores its prefix again. if self._deferred_admission_holds(self.waiting[0]): + stalled = self._memory_admission_stall_output("deferred_admission") + if stalled is not None: + rejected_outputs.append(stalled) break admitted = self._num_admitted_requests() @@ -15773,6 +15890,7 @@ def _report_sparse_progress(processed: int, total: int) -> None: continue finally: self._external_prefill_request_id = None + self._note_admission_progress() # Clean up temp UID mapping del self.uid_to_request_id[temp_uid] @@ -17299,6 +17417,8 @@ def step(self) -> SchedulerOutput: scheduled = chunked_scheduled + scheduled output.scheduled_request_ids = [r.request_id for r in scheduled] output.num_scheduled_tokens = sum(r.num_prompt_tokens for r in scheduled) + if scheduled: + self._note_admission_progress() # A step that advanced chunked prefills is work even with no # decode running: without this the engine loop sleeps up to # step_interval between chunks. A step that merely HELD a @@ -17344,6 +17464,7 @@ def step(self) -> SchedulerOutput: output.has_work = True if responses: + self._note_admission_progress() outputs, finished_ids = self._process_batch_responses(responses) output.outputs.extend(outputs) output.finished_request_ids.update(finished_ids) diff --git a/omlx/settings.py b/omlx/settings.py index c10a15e6e3..1f38cbfbb1 100644 --- a/omlx/settings.py +++ b/omlx/settings.py @@ -23,6 +23,7 @@ import json import logging +import math import os import shutil from dataclasses import asdict, dataclass, field @@ -331,6 +332,16 @@ def from_dict(cls, data: dict[str, Any]) -> ModelSettings: ) +def _is_valid_positive_seconds(value: Any) -> bool: + """A positive finite number; bool is an int subclass and is rejected.""" + return ( + isinstance(value, (int, float)) + and not isinstance(value, bool) + and math.isfinite(value) + and value > 0 + ) + + @dataclass class SchedulerSettings: """Scheduler configuration settings.""" @@ -370,6 +381,12 @@ class SchedulerSettings: # abort. Separate and larger than the park budget: a decode pause keeps # every generated token exactly, while the abort loses them all. max_decode_pauses_per_request: int = 8 + # Seconds a queued request waits for memory with no request making + # progress while memory is scheduled on purpose (a parked or paused + # request, a solo request, a deferred head) before it fails. Progress by + # any request (a token, a prefill chunk, a drained cache write) restarts + # the clock. + admission_no_progress_timeout_s: float = 600.0 # Consecutive "ok" pressure polls before parked requests may resume when # no memory estimate is available (with one, a parked request resumes # once the estimated free memory covers its need). @@ -409,6 +426,10 @@ def positive_int(key: str, default: int) -> int: return default return value + no_progress_s = data.get("admission_no_progress_timeout_s", 600.0) + if not _is_valid_positive_seconds(no_progress_s): + no_progress_s = 600.0 + return cls( max_concurrent_requests=value, embedding_batch_size=embedding_batch_size, @@ -422,6 +443,7 @@ def positive_int(key: str, default: int) -> int: max_decode_pauses_per_request=positive_int( "max_decode_pauses_per_request", 8 ), + admission_no_progress_timeout_s=float(no_progress_s), park_resume_ok_polls=positive_int("park_resume_ok_polls", 3), ) @@ -1368,6 +1390,18 @@ def _apply_env_overrides(self) -> None: setattr(self.scheduler, attr, int(raw)) except ValueError: logger.warning(f"Invalid {env_name} value: {raw}") + if raw := os.getenv("OMLX_ADMISSION_NO_PROGRESS_TIMEOUT_S"): + try: + no_progress_s = float(raw) + except ValueError: + no_progress_s = None + if no_progress_s is not None and _is_valid_positive_seconds(no_progress_s): + self.scheduler.admission_no_progress_timeout_s = no_progress_s + else: + logger.warning( + f"Invalid OMLX_ADMISSION_NO_PROGRESS_TIMEOUT_S value: {raw} " + "(must be a finite number > 0)" + ) # Cache settings if cache_enabled := os.getenv("OMLX_CACHE_ENABLED"): @@ -1900,6 +1934,14 @@ def validate(self) -> list[str]: f"Invalid max_decode_pauses_per_request: " f"{self.scheduler.max_decode_pauses_per_request} (must be >= 1)" ) + if not _is_valid_positive_seconds( + self.scheduler.admission_no_progress_timeout_s + ): + errors.append( + f"Invalid admission_no_progress_timeout_s: " + f"{self.scheduler.admission_no_progress_timeout_s!r} " + "(must be a finite number > 0)" + ) if self.scheduler.park_resume_ok_polls < 1: errors.append( f"Invalid park_resume_ok_polls: " @@ -2089,6 +2131,9 @@ def to_scheduler_config(self) -> SchedulerConfig: max_decode_pauses_per_request=( self.scheduler.max_decode_pauses_per_request ), + admission_no_progress_timeout_s=( + self.scheduler.admission_no_progress_timeout_s + ), park_resume_ok_polls=self.scheduler.park_resume_ok_polls, initial_cache_blocks=self.cache.initial_cache_blocks, paged_ssd_cache_dir=str(ssd_dir) if ssd_dir else None, diff --git a/tests/test_memory_scheduling_gate.py b/tests/test_memory_scheduling_gate.py index 9c0810c731..0bc35e9df3 100644 --- a/tests/test_memory_scheduling_gate.py +++ b/tests/test_memory_scheduling_gate.py @@ -8,7 +8,10 @@ 1. the never-fits 400 ``context_exceeds_capacity``, ``GET /v1/omlx/capacity`` numbers and the ``X-oMLX-Max-Context-Tokens`` header; 2. the fits-later wait (a request that fits alone waits instead of being - rejected on current usage). + rejected on current usage); +3. the progress-based admission-stall clock (600 s bound while memory is + held on purpose, store-cache backpressure not a failure while writes + drain). Off, these paths behave as on upstream ``main``. """ @@ -18,10 +21,12 @@ import pytest import test_process_memory_enforcer as enforcer_tests +import test_scheduler_admission_progress as progress_tests import test_scheduler_capacity_gate as gate_tests import test_server_context_capacity as server_tests from fastapi.testclient import TestClient from test_process_memory_enforcer import _make_enforcer +from test_scheduler_admission_progress import _schedule from test_scheduler_capacity_gate import GB from test_scheduler_prefill_memory_guard import _make_request, _make_scheduler from test_server_context_capacity import _engine_with_scheduler @@ -30,12 +35,16 @@ import omlx.server as server from omlx.exceptions import ContextExceedsCapacityError, PrefillMemoryExceededError from omlx.process_memory_enforcer import resolve_memory_scheduling +from omlx.scheduler import _StoreCacheGate from omlx.settings import GlobalSettings, MemorySettings -# Shared fixtures: an enforcer's engine pool, a guarded scheduler and the +# Shared fixtures: an enforcer's engine pool, a guarded scheduler, a scheduler +# whose head waits under memory pressure with a controlled clock, and the # capacity endpoint's engine pool. mock_engine_pool = enforcer_tests.mock_engine_pool gated = gate_tests.gated +clock = progress_tests.clock +pressured = progress_tests.pressured capacity_env = server_tests.capacity_env # --- Resolution ------------------------------------------------------------- @@ -225,7 +234,7 @@ def test_the_enforcer_propagates_the_state_to_schedulers( assert scheduler._memory_scheduling is False -# --- Off: these paths behave as on main -------------------------------------- +# --- Off: the three paths behave as on main ---------------------------------- def test_off_has_no_capacity_estimate_snapshot_or_hint(gated): @@ -274,6 +283,62 @@ def test_off_rejects_a_fits_later_request_with_the_old_error(gated): assert rejection.message.startswith("Prefill would require") +def test_off_uses_the_fixed_stall_timeout(pressured, clock): + """Progress by others does not restart the clock and the error is the + one main returns.""" + scheduler, _head, _running = pressured + scheduler._memory_scheduling = False + timeout = scheduler._MEMORY_ADMISSION_STALL_TIMEOUT_S + assert _schedule(scheduler) == [] + clock.advance(timeout - 10) + scheduler._note_admission_progress() + clock.advance(9) + assert _schedule(scheduler) == [] + clock.advance(1) + (failed,) = _schedule(scheduler) + assert failed.error_code == "memory_admission_stalled" + assert failed.error_metadata == { + "request_id": "head", + "reason": "admission_paused", + "stalled_seconds": int(timeout), + } + assert "no request made progress" not in failed.error + assert f"persisted for {timeout:.1f}s (admission_paused). " in failed.error + + +def test_off_has_no_long_bound_for_deliberate_holds(pressured, clock): + scheduler, _head, solo = pressured + scheduler._memory_scheduling = False + scheduler._solo_request_id = solo.request_id # a parked head resumed solo + assert _schedule(scheduler) == [] + clock.advance(scheduler._MEMORY_ADMISSION_STALL_TIMEOUT_S) + (failed,) = _schedule(scheduler) + assert failed.error_metadata["reason"] == "solo_hold" + + +def test_off_store_cache_backpressure_uses_the_fixed_timeout( + pressured, + clock, +): + scheduler, _head, running = pressured + scheduler._memory_scheduling = False + del scheduler.running[running.request_id] + scheduler._admission_paused = False + gate = _StoreCacheGate(cap=1) + gate.note_submitted() + scheduler._store_cache_gate = gate + timeout = scheduler._STORE_CACHE_ADMISSION_STALL_TIMEOUT_S + assert _schedule(scheduler) == [] + clock.advance(timeout - 1) + scheduler._note_admission_progress() # a drained write + assert _schedule(scheduler) == [] + clock.advance(1) + (failed,) = _schedule(scheduler) + assert failed.error_code == "store_cache_admission_stalled" + assert "no_progress_seconds" not in failed.error_metadata + assert "no request made progress" not in failed.error + + def test_off_does_not_exempt_an_external_prefill_from_the_enforcer(): """An external-loop prefill with nothing admitted is not reported as solo off, so the enforcer's hard-pressure path stays upstream's.""" diff --git a/tests/test_scheduler_admission_progress.py b/tests/test_scheduler_admission_progress.py new file mode 100644 index 0000000000..d240f9cfbe --- /dev/null +++ b/tests/test_scheduler_admission_progress.py @@ -0,0 +1,488 @@ +# SPDX-License-Identifier: Apache-2.0 +"""A queued request waits while memory is scheduled on purpose. + +Forced pressure (Qwen3.8-27B at a 48 GB ceiling): the third queued +request failed with "memory pressure persisted for 90.6s +(store_cache_backpressure)" (text decode) and with ``admission_paused`` after +67.5 s (image prefill) while the other requests ran. The admission-stall +clock started when the head first met pressure and kept running while a solo +request decoded (the solo hold breaks before the stall check, so the clock is +neither checked nor reset) and while another request prefilled chunk after +chunk. The first check after the solo request finished found 90 s on it and +failed the head, although the server had been making progress all along. + +The clock now measures time without progress: a token emitted, a prefill +chunk processed, an external prefill finished, a request admitted or a +store-cache write drained resets it. While memory is scheduled on purpose (a +parked or decode-paused request, a solo request, a deferred fits-later head) +the head waits under a long, configurable bound +(``admission_no_progress_timeout_s``) instead of the 60 s one, so a genuine +deadlock still surfaces with a clear error. +""" + +import logging +import time +from collections import deque +from concurrent.futures import Future +from types import SimpleNamespace +from unittest.mock import MagicMock + +import pytest +import test_scheduler_decode_pause as dp +import test_scheduler_park as park +from test_memory_decode_pause import _busy, tick +from test_memory_resume_thrash import _rig_engine +from test_process_memory_enforcer import ( # noqa: F401 (fixture) + _make_enforcer, + mock_engine_pool, +) +from test_scheduler_prefill_memory_guard import _make_scheduler + +import omlx.scheduler as scheduler_module +from omlx.request import Request, RequestStatus, SamplingParams +from omlx.scheduler import SchedulerConfig, _StoreCacheGate +from omlx.settings import GlobalSettings, SchedulerSettings + +GB = 1024**3 +MAX_TOKENS = 60 +STEP_S = 2.0 # controlled clock: every scheduler step takes 2 s + + +class _Clock: + """The scheduler's ``time`` module with a controlled monotonic clock.""" + + def __init__(self, start=1000.0): + self.now = start + + def monotonic(self): + return self.now + + def advance(self, seconds): + self.now += seconds + + def __getattr__(self, name): + return getattr(time, name) + + +@pytest.fixture +def clock(monkeypatch): + fake = _Clock() + monkeypatch.setattr(scheduler_module, "time", fake) + return fake + + +@pytest.fixture(autouse=True) +def single_victim_on(monkeypatch): + """Every enforcer built here aborts one victim (memory.abort_single_victim).""" + from omlx.process_memory_enforcer import ProcessMemoryEnforcer + + real_init = ProcessMemoryEnforcer.__init__ + + def init(self, *args, **kwargs): + kwargs.setdefault("abort_single_victim", True) + real_init(self, *args, **kwargs) + + monkeypatch.setattr(ProcessMemoryEnforcer, "__init__", init) + + +@pytest.fixture +def enforcer(mock_engine_pool): # noqa: F811 + # Ceiling 100 GB: soft 85 GB pauses admission, hard 95 GB pauses rows. + return _make_enforcer( + mock_engine_pool, + ceiling=100 * GB, + soft_threshold=0.85, + hard_threshold=0.95, + memory_scheduling="on", + ) + + +# --- Real enforcer, real scheduler, controlled clock ---------------------- + + +def _submit(rig, rid, tokens, arrival): + request = Request( + request_id=rid, + prompt=list(tokens), + sampling_params=SamplingParams(max_tokens=MAX_TOKENS, temperature=0), + arrival_time=arrival, + ) + rig.scheduler.add_request(request) + return request + + +def _baseline(tmp_path, prompts): + rig = park._Rig( + tmp_path / "baseline", + dp._tokenizer(), + split=False, + commit_blocks=1, + max_blocks=dp.MAX_BLOCKS, + ) + try: + rows = [ + _submit(rig, rid, tokens, float(i + 1)) + for i, (rid, tokens) in enumerate(prompts.items()) + ] + park.run_to_completion(rig, rows, limit=20 * MAX_TOKENS) + return {r.request_id: list(r.output_token_ids) for r in rows} + finally: + rig.close() + + +def _admitted_ids(scheduler): + return list(scheduler.running) + [r.request_id for r in scheduler.prefilling] + + +def _finished(rows, outputs): + done = {o.request_id for o in outputs if o.finished} + return all(r.is_finished() or r.request_id in done for r in rows) + + +async def _drive(rig, enforcer, clock, rows, *, submit_later=(), limit=None): + """Tick the enforcer on the scripted reading, step, advance the clock. + + ``submit_later`` requests arrive after the first step (the real run + staggered them 0.5 s), so they meet the pressure the first request causes. + """ + scheduler = rig.scheduler + outputs = [] + limit = limit or 12 * MAX_TOKENS + for index in range(limit): + if _finished(rows, outputs): + break + # One request fits at a time: with one admitted, usage sits in the + # soft band (admission paused); idle, it is low. + gb = 90 if _admitted_ids(scheduler) else 20 + await tick(enforcer, gb) + outputs.extend(park.step(rig)) + clock.advance(STEP_S) + if index == 0: + for rid, tokens, arrival in submit_later: + rows.append(_submit(rig, rid, tokens, arrival)) + for future in list(scheduler._inflight_store_futures.values()): + future.result(timeout=30) + scheduler._drain_pending_async_removes() + return outputs + + +@pytest.mark.asyncio +async def test_three_requests_that_fit_one_at_a_time_complete_without_a_stall( + tmp_path, enforcer, clock, monkeypatch, caplog +): + """Each request decodes for 120 s of controlled time while the others + wait under soft pressure. The old 60 s clock failed the second request + while the first was still emitting tokens.""" + prompts = {"a": dp.PROMPT, "b": dp.OTHER, "c": park.PROMPT_D} + expected = _baseline(tmp_path, prompts) + rig = park._Rig( + tmp_path / "sequential", + dp._tokenizer(), + split=False, + commit_blocks=1, + max_blocks=dp.MAX_BLOCKS, + memory_pressure_park=True, + ) + try: + rig.scheduler.note_pressure_poll("soft") + engine = _rig_engine(rig) + _busy(enforcer, engine) + rows = [_submit(rig, "a", dp.PROMPT, 1.0)] + + with caplog.at_level(logging.INFO, logger="omlx.scheduler"): + outputs = await _drive( + rig, + enforcer, + clock, + rows, + submit_later=[("b", dp.OTHER, 2.0), ("c", park.PROMPT_D, 3.0)], + ) + + errors = [o for o in outputs if o.error] + assert errors == [] + engine.abort_one_request_for_memory.assert_not_awaited() + engine.abort_all_requests.assert_not_awaited() + for row in rows: + rid = row.request_id + assert list(row.output_token_ids) == expected[rid] + assert dp.streamed_tokens(outputs, rid) == expected[rid] + (final,) = [o for o in outputs if o.request_id == rid and o.finished] + assert final.finish_reason == "length" + # They ran one at a time: c started only after b finished. + assert "Admission waiting for memory: admission_paused" in caplog.text + assert "request(s) progressing" in caplog.text + finally: + rig.close() + + +@pytest.mark.asyncio +async def test_a_queued_request_still_fails_when_nothing_progresses( + tmp_path, enforcer, clock, monkeypatch +): + """A genuine stall: the admitted request emits nothing (its decode is + wedged) while pressure persists. The head fails after the stall timeout + with a clear error, because nothing progressed.""" + rig = park._Rig( + tmp_path / "wedged", + dp._tokenizer(), + split=False, + commit_blocks=1, + max_blocks=dp.MAX_BLOCKS, + ) + try: + scheduler = rig.scheduler + engine = _rig_engine(rig) + _busy(enforcer, engine) + rows = [_submit(rig, "a", dp.PROMPT, 1.0)] + outputs = [] + for _ in range(20): # until a is admitted and decoding + await tick(enforcer, 90) + outputs.extend(park.step(rig)) + clock.advance(STEP_S) + if "a" in scheduler.running: + break + assert "a" in scheduler.running + rows.append(_submit(rig, "b", dp.OTHER, 2.0)) + # From here a's decode emits nothing. + monkeypatch.setattr(scheduler.batch_generator, "next_generated", lambda: []) + + timeout = scheduler._MEMORY_ADMISSION_STALL_TIMEOUT_S + for _ in range(int(timeout / STEP_S) + 3): + await tick(enforcer, 90) + outputs.extend(park.step(rig)) + clock.advance(STEP_S) + + (failed,) = [o for o in outputs if o.request_id == "b" and o.finished] + assert failed.error_code == "memory_admission_stalled" + assert "no request made progress" in failed.error + assert failed.error_metadata["no_progress_seconds"] >= int(timeout) + assert "b" not in scheduler.requests + finally: + rig.close() + + +# --- Scheduler unit: progress resets the clock ----------------------------- + + +def _request(rid, prompt_tokens=64): + return Request( + request_id=rid, + prompt=list(range(prompt_tokens)), + sampling_params=SamplingParams(max_tokens=16), + ) + + +@pytest.fixture +def pressured(monkeypatch, clock): + """A scheduler with one running row ``run`` and a queued head ``head``, + admission paused by memory pressure.""" + scheduler = _make_scheduler() + running = _request("run") + scheduler.running[running.request_id] = running + scheduler.requests[running.request_id] = running + head = _request("head") + scheduler.waiting.append(head) + scheduler.requests[head.request_id] = head + scheduler._admission_paused = True + scheduler._ensure_batch_generator = MagicMock() + scheduler._memory_scheduling = True # memory.memory_scheduling resolved on + return scheduler, head, running + + +def _schedule(scheduler): + scheduled, rejected = scheduler._schedule_waiting() + assert scheduled == [] + return rejected + + +def test_progress_by_others_resets_the_stall_clock(pressured, clock): + scheduler, head, _ = pressured + timeout = scheduler._MEMORY_ADMISSION_STALL_TIMEOUT_S + assert _schedule(scheduler) == [] # the head starts waiting + + clock.advance(timeout - 10) + scheduler._note_admission_progress() # the running row emitted a token + clock.advance(timeout - 1) + assert _schedule(scheduler) == [] # 2 * timeout waiting, 59 s idle + + clock.advance(1) + (failed,) = _schedule(scheduler) + assert failed.request_id == "head" + assert failed.error_code == "memory_admission_stalled" + assert failed.error_metadata["reason"] == "admission_paused" + assert failed.error_metadata["no_progress_seconds"] == int(timeout) + assert failed.error_metadata["stalled_seconds"] == int(2 * timeout - 10) + assert "no request made progress" in failed.error + + +def test_a_long_solo_run_does_not_fail_the_head_when_it_finishes( + pressured, clock, caplog +): + """Text decode under forced pressure: the head met pressure, then a solo + request decoded for 90 s; the first check after it finished (store-cache + backpressure under memory pressure) failed the head.""" + scheduler, head, solo = pressured + scheduler._solo_request_id = solo.request_id + scheduler._admission_paused = True + assert _schedule(scheduler) == [] # clock starts (solo hold) + + for _ in range(45): # 90 s of solo decode, a token each step + clock.advance(STEP_S) + scheduler._note_admission_progress() + assert _schedule(scheduler) == [] + # The solo request finishes; its store-cache write is in flight. + del scheduler.running[solo.request_id] + solo.set_finished(RequestStatus.FINISHED_LENGTH_CAPPED) + gate = _StoreCacheGate(cap=1) + gate.note_submitted() + scheduler._store_cache_gate = gate + scheduler._prefill_memory_guard = True + scheduler._memory_limit_bytes = 100 + scheduler._current_usage_bytes = MagicMock(return_value=101) + clock.advance(0.6) + + with caplog.at_level(logging.INFO, logger="omlx.scheduler"): + assert _schedule(scheduler) == [] + assert list(scheduler.waiting) == [head] + assert "Memory admission stalled" not in caplog.text + + +def test_a_solo_hold_waits_under_the_long_bound_and_then_fails(pressured, clock): + """Deliberate scheduling: the head waits behind a solo request. A solo + request that emits nothing for ``admission_no_progress_timeout_s`` is a + genuine deadlock: the head fails with a clear error.""" + scheduler, head, solo = pressured + scheduler._solo_request_id = solo.request_id + bound = scheduler.config.admission_no_progress_timeout_s + assert bound == 600.0 + assert _schedule(scheduler) == [] + + clock.advance(bound - 1) + assert _schedule(scheduler) == [] # far past the 60 s line, still waiting + clock.advance(1) + (failed,) = _schedule(scheduler) + assert failed.error_code == "memory_admission_stalled" + assert failed.error_metadata["reason"] == "solo_hold" + assert failed.error_metadata["no_progress_seconds"] == int(bound) + assert "no request made progress for 600" in failed.error + assert list(scheduler.waiting) == [] + + +def test_a_deferred_head_waits_under_the_long_bound(pressured, clock): + scheduler, head, _ = pressured + scheduler._deferred_admissions[head.request_id] = SimpleNamespace( + admitted_ids=frozenset({"run"}), + free_bytes=None, + retry_at=clock.now + 10_000, + ) + assert _schedule(scheduler) == [] + clock.advance(scheduler._MEMORY_ADMISSION_STALL_TIMEOUT_S * 3) + assert _schedule(scheduler) == [] + clock.advance(scheduler.config.admission_no_progress_timeout_s) + (failed,) = _schedule(scheduler) + assert failed.error_metadata["reason"] == "deferred_admission" + + +def test_the_waiting_log_is_rate_limited(pressured, clock, caplog): + scheduler, _, _ = pressured + with caplog.at_level(logging.INFO, logger="omlx.scheduler"): + for _ in range(20): + _schedule(scheduler) + scheduler._note_admission_progress() + clock.advance(1.0) + lines = [ + r.getMessage() + for r in caplog.records + if r.getMessage().startswith("Admission waiting for memory") + ] + assert lines == [ + "Admission waiting for memory: admission_paused; 1 request(s) progressing" + ] + clock.advance(scheduler_module._ADMISSION_WAIT_LOG_INTERVAL_S) + with caplog.at_level(logging.INFO, logger="omlx.scheduler"): + _schedule(scheduler) + assert ( + sum( + r.getMessage().startswith("Admission waiting for memory") + for r in caplog.records + ) + == 2 + ) + + +# --- Store-cache backpressure: drains are progress ------------------------- + + +def _drain_one(scheduler): + """The writer finishes one job; the next one is already queued, so the + gate stays full.""" + future = Future() + future.set_result(None) + scheduler._pending_async_removes = deque([(12345, "gone", future)]) + assert scheduler._drain_pending_async_removes() is True + scheduler._store_cache_gate.note_submitted() + + +def test_store_cache_backpressure_waits_while_writes_drain(pressured, clock): + """Not memory related (no pressure): the store-cache stall fails only + when the writer stops draining.""" + scheduler, head, running = pressured + del scheduler.running[running.request_id] + scheduler._admission_paused = False + gate = _StoreCacheGate(cap=1) + gate.note_submitted() + scheduler._store_cache_gate = gate + timeout = scheduler._STORE_CACHE_ADMISSION_STALL_TIMEOUT_S + assert _schedule(scheduler) == [] + + for _ in range(3): # 3 * (timeout - 1) s, the writer drains a job each time + clock.advance(timeout - 1) + _drain_one(scheduler) + assert _schedule(scheduler) == [] + + clock.advance(timeout) + (failed,) = _schedule(scheduler) + assert failed.error_code == "store_cache_admission_stalled" + assert failed.error_metadata["no_progress_seconds"] == int(timeout) + + +def test_memory_related_store_backpressure_waits_while_writes_drain(pressured, clock): + """The forced-pressure shape: nothing admitted, memory pressure, the finished + request's write in flight.""" + scheduler, head, running = pressured + del scheduler.running[running.request_id] + gate = _StoreCacheGate(cap=1) + gate.note_submitted() + scheduler._store_cache_gate = gate + timeout = scheduler._MEMORY_ADMISSION_STALL_TIMEOUT_S + assert _schedule(scheduler) == [] + for _ in range(3): + clock.advance(timeout - 1) + _drain_one(scheduler) + assert _schedule(scheduler) == [] + clock.advance(timeout) + (failed,) = _schedule(scheduler) + assert failed.error_code == "memory_admission_stalled" + assert failed.error_metadata["reason"] == "store_cache_backpressure" + + +# --- Configuration ---------------------------------------------------------- + + +def test_the_no_progress_bound_defaults_to_ten_minutes_and_is_configurable( + tmp_path, monkeypatch +): + assert SchedulerConfig().admission_no_progress_timeout_s == 600.0 + assert SchedulerSettings().admission_no_progress_timeout_s == 600.0 + custom = SchedulerSettings.from_dict({"admission_no_progress_timeout_s": 1800}) + assert custom.admission_no_progress_timeout_s == 1800.0 + for bad in (0, -1, "long", True, float("inf")): + junk = SchedulerSettings.from_dict({"admission_no_progress_timeout_s": bad}) + assert junk.admission_no_progress_timeout_s == 600.0 + + monkeypatch.setenv("OMLX_ADMISSION_NO_PROGRESS_TIMEOUT_S", "900") + settings = GlobalSettings.load(base_path=tmp_path) + assert settings.scheduler.admission_no_progress_timeout_s == 900.0 + assert settings.to_scheduler_config().admission_no_progress_timeout_s == 900.0 + settings.scheduler.admission_no_progress_timeout_s = 0 + assert any("admission_no_progress_timeout_s" in e for e in settings.validate()) diff --git a/tests/test_settings.py b/tests/test_settings.py index 71b1c243a3..9ca6948718 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -399,6 +399,7 @@ def test_to_dict(self): "media_text_suffix_chunked": False, "max_parks_per_request": 3, "max_decode_pauses_per_request": 8, + "admission_no_progress_timeout_s": 600.0, "park_resume_ok_polls": 3, } From eaba0f1a838b978ff556ea64ee395514a50a19eb Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Tue, 6 Oct 2026 06:45:40 -0600 Subject: [PATCH 40/46] fix(scheduler): run a lone head that fits under the ceiling alone instead of rejecting it Two real-model image-prefill runs at a 46 GB ceiling: when the request ahead finished, the next image request reached the in-stream preflight with nothing admitted. It fits alone by estimate, but the usage reading also held memory no admitted request owns (queued requests' vision embeddings and other residue, 2.9-4.3 GB over the weights), so current + KV + transient crossed the admission line by under 1 GB (33.01 > 32.79 GB, 33.23 > 32.54 GB) and the prefill memory guard rejected it, with the 46 GB ceiling far above its peak. A parked head in that position already resumes alone (solo). A queued head now follows the same rule: with nothing admitted and no store write pending, a request that fits alone and whose peak stays under the solo line (ceiling and prefill safety cap minus 2%) is admitted as the solo request. Nothing is admitted beside it and the enforcer leaves it to the emergency brake. The route preflight lets it queue. Over the solo line, or with park off, the older rejection applies. The solo admission needs the capacity estimate, so it is memory scheduling (memory.memory_scheduling) as well: with it off, the default for a stock install, a lone head gets the current-usage rejection as on main. --- README.md | 2 +- docs/TESTING.md | 4 +- omlx/scheduler.py | 73 +++++++++---- tests/test_memory_scheduling_gate.py | 29 ++++- tests/test_scheduler_solo_admission.py | 142 +++++++++++++++++++++++++ 5 files changed, 223 insertions(+), 27 deletions(-) create mode 100644 tests/test_scheduler_solo_admission.py diff --git a/README.md b/README.md index b78da1690b..37e94451f6 100644 --- a/README.md +++ b/README.md @@ -290,7 +290,7 @@ Why an explicit ceiling: waiting for memory and promising what fits alone only m With memory scheduling on: - **Never fits.** A request that cannot fit even with nothing else running (model weights + KV for the prompt plus `max_tokens` + the prefill transient, over the memory guard's capacity line) is rejected up front with HTTP 400 and `omlx_code: "context_exceeds_capacity"`. The usual error envelope stays (`message`, `type`, `code`, `estimated_bytes`, `limit_bytes`) and adds `required_bytes`, `capacity_bytes`, `weights_bytes`, `kv_bytes_per_token`, `requested_context_tokens`, `requested_max_tokens`, `max_viable_context_tokens` and `retryable: false`. Compact or shorten the context, or lower `max_tokens`, before retrying. -- **Fits later.** A request that fits alone but not right now is not rejected. It waits at the head of the queue until running requests free memory. +- **Fits later.** A request that fits alone but not right now is not rejected. It waits at the head of the queue until running requests free memory. With the park feature on and nothing running, it can run alone (solo) instead of being rejected. - **Stall clock.** A queued request fails after 60 s without progress by any request (a token, a prefill chunk, a drained cache write), not 60 s after it started waiting. While memory is held on purpose, the bound is `scheduler.admission_no_progress_timeout_s` (default 600 s). - **Capacity numbers.** `GET /v1/omlx/capacity?model=&context_tokens=&max_tokens=` (API key like the other `/v1` routes) returns the same numbers for a request of that size plus `free_bytes_now`, without loading the model. An unknown model is a 404 and an unloaded one a 409; `available: false` when no estimate exists. Chat completions also carry an `X-oMLX-Max-Context-Tokens` header: the largest prompt plus `max_tokens` that fits alone. diff --git a/docs/TESTING.md b/docs/TESTING.md index 219c479af7..50f6bc23cc 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -237,13 +237,13 @@ Mocked tests do not replace hardware validation: with a real model, abort a long # Memory scheduling gate tests -Run `python -m pytest -q tests/test_memory_scheduling_gate.py` to check `memory.memory_scheduling` (env `OMLX_MEMORY_SCHEDULING`; `auto`, `on` or `off`, default `auto`). It gates three behaviours: the never-fits 400 with the capacity endpoint numbers and the `X-oMLX-Max-Context-Tokens` header; the fits-later wait; and the progress-based admission-stall clock. `auto` is on when the prefill memory guard is on and an explicit ceiling is set (`memory_guard_tier: custom` with `memory_guard_custom_ceiling_gb` > 0; a ceiling value left under another tier does not count). `on` forces it on but still needs the guard (with the guard off it stays off and logs a warning). `off` forces it off. The `ProcessMemoryEnforcer` resolves the mode at startup and whenever the mode, the guard, the tier or the ceiling changes (the admin settings apply live), logs `Memory scheduling: on (explicit ceiling 48.0 GB)` or the reason it is off, and propagates the result to every scheduler (`Scheduler._memory_scheduling`, False until an enforcer sets it). The tests cover the resolution matrix, the setting (default, `to_dict`, `from_dict`, env override, validation, the admin GET and POST), and, with it off, upstream behaviour on each path: no capacity estimate, snapshot or header (a cached hint is not served either); a request whose `max_tokens` can never fit passes when its prompt fits now; a fits-alone-but-not-now request gets the old current-usage rejection; the stall clock fails the head 60 s after it first blocked, whatever else progresses, with the old message and metadata (no `no_progress_seconds`), also behind a solo request and for store-cache backpressure; an external-loop prefill is not reported as solo to the enforcer; and the capacity endpoint returns `available: false` with `memory_scheduling: "off"` and the reason, while unknown and unloaded models keep their 404 and 409. `tests/test_memory_external_prefill.py` also drives the real enforcer with park, single victim and memory scheduling off: the lone external prefill at hard pressure gets upstream's abort-all. The suites below that test these behaviours set the mode on explicitly (`scheduler._memory_scheduling = True`, or `memory_scheduling="on"` on the real enforcer). +Run `python -m pytest -q tests/test_memory_scheduling_gate.py` to check `memory.memory_scheduling` (env `OMLX_MEMORY_SCHEDULING`; `auto`, `on` or `off`, default `auto`). It gates three behaviours: the never-fits 400 with the capacity endpoint numbers and the `X-oMLX-Max-Context-Tokens` header; the fits-later wait, including the solo admission of a lone head; and the progress-based admission-stall clock. `auto` is on when the prefill memory guard is on and an explicit ceiling is set (`memory_guard_tier: custom` with `memory_guard_custom_ceiling_gb` > 0; a ceiling value left under another tier does not count). `on` forces it on but still needs the guard (with the guard off it stays off and logs a warning). `off` forces it off. The `ProcessMemoryEnforcer` resolves the mode at startup and whenever the mode, the guard, the tier or the ceiling changes (the admin settings apply live), logs `Memory scheduling: on (explicit ceiling 48.0 GB)` or the reason it is off, and propagates the result to every scheduler (`Scheduler._memory_scheduling`, False until an enforcer sets it). The tests cover the resolution matrix, the setting (default, `to_dict`, `from_dict`, env override, validation, the admin GET and POST), and, with it off, upstream behaviour on each path: no capacity estimate, snapshot or header (a cached hint is not served either); a request whose `max_tokens` can never fit passes when its prompt fits now; a fits-alone-but-not-now request gets the old current-usage rejection; a lone head is not admitted solo; the stall clock fails the head 60 s after it first blocked, whatever else progresses, with the old message and metadata (no `no_progress_seconds`), also behind a solo request and for store-cache backpressure; an external-loop prefill is not reported as solo to the enforcer; and the capacity endpoint returns `available: false` with `memory_scheduling: "off"` and the reason, while unknown and unloaded models keep their 404 and 409. `tests/test_memory_external_prefill.py` also drives the real enforcer with park, single victim and memory scheduling off: the lone external prefill at hard pressure gets upstream's abort-all. The suites below that test these behaviours set the mode on explicitly (`scheduler._memory_scheduling = True`, or `memory_scheduling="on"` on the real enforcer). Run `python -m pytest -q tests/test_memory_scheduling_admin_state.py` to check memory scheduling across admin settings saves. The cases load the real settings with `memory_scheduling: "on"` in `settings.json`, build the live enforcer from them as the server does, and drive the real admin routes. A save of `max_concurrent_requests`, `chunked_prefill` or `memory_guard_tier` keeps the mode on the live settings object and in `settings.json` (a reload sees it again), keeps it on and propagated, and logs no `Memory scheduling:` line. Loading the settings page (`GET /admin/api/global-settings`, which builds one tier-preview enforcer per tier) logs none either: only an enforcer that drives an engine pool logs its state. An explicit `memory_scheduling` POST, including one that repeats the current mode, re-resolves, logs the state and propagates it to the schedulers. The GET reports the live state as `memory.memory_scheduling_effective` (`enabled` and `reason`, `null` without an enforcer), the POST response carries it, and the factory defaults response does not. # Never-fits gate tests -Run `python -m pytest -q tests/test_scheduler_capacity_gate.py tests/test_scheduler_capacity_vlm.py tests/test_scheduler_deferred_admission.py tests/test_server_context_capacity.py` to check the feasibility gate. A request whose weights + exact KV of prompt plus `max_tokens` + prefill transient exceed the capacity line (the tighter of the admission line and the prefill safety cap) is rejected with `ContextExceedsCapacityError` (HTTP 400, `omlx_code: context_exceeds_capacity`, the byte and token fields, `retryable: false`) whatever the current usage. One that fits alone but not now is not rejected: the route preflight lets it queue while other work is admitted (queued requests hold no memory and do not count), and the in-stream admission keeps it at the head (nothing overtakes it) until the admitted rows free memory; both checks share one predicate. A deferred request releases its restored prefix and its block-table refs while it waits, and its re-admission repeats the lookup. The block-table release can wait behind an in-flight prefill commit; it is keyed to the deferred attempt's table, so it never frees a table the request got since. The deferred head is not retried (and its prefix not restored again) on every step: it retries once an admitted row left (finished, aborted or paused), free memory rose by more than 2% of the admission line, or its backoff expired (0.25 s doubling per deferral, capped at 4 s); it keeps the head-of-line hold meanwhile, also while its release still waits behind a commit. Both checks price the same output budget: the route preflight uses the resolved `max_tokens` (request, model setting or server default; the engine default when an engine is called directly). With nothing admitted, or when the capacity cannot be estimated (no memory limit, unknown weights or KV dimensions), the older current-usage rejection applies; unknown weights are never cached and never produce a never-fits rejection. The server cases cover the 400 body on API and non-API routes, `GET /v1/omlx/capacity` (fields, 404/409, auth) and the `X-oMLX-Max-Context-Tokens` header on streaming and non-streaming chat completions. `tests/test_scheduler_capacity_vlm.py` builds a tiny real mlx-vlm Qwen3.5 model (vision tower plus hybrid language model) behind the real `VLMModelAdapter`: the adapter keeps the model in `_vlm_model`, which `nn.Module.parameters()` skips, so the weights are summed from the unwrapped model, each array once. It checks the capacity of that model and of the text model on the batched engine, that `kv_bytes_per_token` prices the TurboQuant prefill peak (full-width KV plus the quantized copy, the last full-attention layer kept full width when there is more than one), that quantized weights count their scales and biases, and that `max_tokens` 2,000,000 reaches the gate unclamped (no route clamps `max_tokens` to the context window) and is rejected as never-fits. These cases run with memory scheduling on (see the memory scheduling gate tests above); off, there is no capacity estimate and the older current-usage rejection applies. +Run `python -m pytest -q tests/test_scheduler_capacity_gate.py tests/test_scheduler_capacity_vlm.py tests/test_scheduler_deferred_admission.py tests/test_scheduler_solo_admission.py tests/test_server_context_capacity.py` to check the feasibility gate. A request whose weights + exact KV of prompt plus `max_tokens` + prefill transient exceed the capacity line (the tighter of the admission line and the prefill safety cap) is rejected with `ContextExceedsCapacityError` (HTTP 400, `omlx_code: context_exceeds_capacity`, the byte and token fields, `retryable: false`) whatever the current usage. One that fits alone but not now is not rejected: the route preflight lets it queue while other work is admitted (queued requests hold no memory and do not count), and the in-stream admission keeps it at the head (nothing overtakes it) until the admitted rows free memory; both checks share one predicate. With nothing admitted, a head that fits alone but whose peak priced on the current usage (which also holds memory no admitted request owns, such as queued requests' vision embeddings) lands between the admission line and the solo line (the ceiling and prefill safety cap minus 2%) runs alone, as a parked head does: `Admitting request alone (solo)`, nothing is admitted beside it, and the route preflight lets it queue. Over the solo line, or with the park feature off, the older rejection applies. The solo-admission cases drive the real scheduler loop with the admission line set by a hard watermark under the ceiling. A deferred request releases its restored prefix and its block-table refs while it waits, and its re-admission repeats the lookup. The block-table release can wait behind an in-flight prefill commit; it is keyed to the deferred attempt's table, so it never frees a table the request got since. The deferred head is not retried (and its prefix not restored again) on every step: it retries once an admitted row left (finished, aborted or paused), free memory rose by more than 2% of the admission line, or its backoff expired (0.25 s doubling per deferral, capped at 4 s); it keeps the head-of-line hold meanwhile, also while its release still waits behind a commit. Both checks price the same output budget: the route preflight uses the resolved `max_tokens` (request, model setting or server default; the engine default when an engine is called directly). With nothing admitted, or when the capacity cannot be estimated (no memory limit, unknown weights or KV dimensions), the older current-usage rejection applies; unknown weights are never cached and never produce a never-fits rejection. The server cases cover the 400 body on API and non-API routes, `GET /v1/omlx/capacity` (fields, 404/409, auth) and the `X-oMLX-Max-Context-Tokens` header on streaming and non-streaming chat completions. `tests/test_scheduler_capacity_vlm.py` builds a tiny real mlx-vlm Qwen3.5 model (vision tower plus hybrid language model) behind the real `VLMModelAdapter`: the adapter keeps the model in `_vlm_model`, which `nn.Module.parameters()` skips, so the weights are summed from the unwrapped model, each array once. It checks the capacity of that model and of the text model on the batched engine, that `kv_bytes_per_token` prices the TurboQuant prefill peak (full-width KV plus the quantized copy, the last full-attention layer kept full width when there is more than one), that quantized weights count their scales and biases, and that `max_tokens` 2,000,000 reaches the gate unclamped (no route clamps `max_tokens` to the context window) and is rejected as never-fits. These cases run with memory scheduling on (see the memory scheduling gate tests above); off, there is no capacity estimate and the older current-usage rejection applies. Mocked tests do not replace hardware validation: with a real model, send a prompt larger than `max_viable_context_tokens` and check for an immediate 400 with the fields, then send two prompts that each fit alone but not together and check that the second waits and completes without an error. diff --git a/omlx/scheduler.py b/omlx/scheduler.py index f4b9befc2e..14f4aa5812 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -2684,9 +2684,10 @@ def __init__( # must steer the user to that knob instead of "close other apps". self._memory_guard_tier: str = "balanced" self._prefill_memory_guard: bool = False # set by ProcessMemoryEnforcer - # Memory scheduling: resolved by ProcessMemoryEnforcer from - # memory.memory_scheduling. The admission features that plan against - # a fixed memory budget consult it; off keeps upstream admission. + # Memory scheduling (the never-fits gate and capacity hint, the + # fits-later wait with the solo admission, the progress-based stall + # clock): resolved by ProcessMemoryEnforcer from + # memory.memory_scheduling. Off keeps upstream admission. self._memory_scheduling: bool = False # Set to True by ProcessMemoryEnforcer when phys_footprint crosses # soft_threshold. Schedulers stop admitting new prefills while this is @@ -12629,21 +12630,25 @@ def _park_thrash_holds(self, head: "Request") -> bool: return free - wait.free_bytes <= int(fit_line * PARK_THRASH_FREE_DELTA_FRACTION) def _mark_solo(self, head: "Request", why: str) -> None: - """Let ``head`` resume as the solo request (nothing else admitted).""" + """Let ``head`` run as the solo request (nothing else admitted): + a parked head resuming, or a queued head admitted ("admit").""" self._solo_request_id = head.request_id key = (head.request_id, head.park_count) if self._solo_logged == key: return self._solo_logged = key reasons = { + "admit": "it fits under the ceiling only with nothing else running", "solo": "it fits under the ceiling only with nothing else running", "fits": "it was paused again while running alone", "max_hold": "it waited the longest hold while nothing ran", } + action = "Admitting request" if why == "admit" else "Resuming parked request" logger.info( - "Resuming parked request %s alone (solo): %s; nothing else is " + "%s %s alone (solo): %s; nothing else is " "admitted until it finishes, and memory pressure below the " "emergency threshold does not pause it again", + action, head.request_id, reasons.get(why, why), ) @@ -14337,18 +14342,21 @@ def _preflight_memory_check( if fits_later: self._log_fits_later(request.request_id, est.estimated, hard_limit) raise _PreflightDeferredError() - - message = self._format_rejection_message( - estimated=est.estimated, - current=current, - peak=peak, - hard_limit=hard_limit, - ) - return _PreflightRejection( - message=message, - estimated_bytes=int(est.estimated), - limit_bytes=int(hard_limit), - ) + if not self._fits_solo(capacity, est): + message = self._format_rejection_message( + estimated=est.estimated, + current=current, + peak=peak, + hard_limit=hard_limit, + ) + return _PreflightRejection( + message=message, + estimated_bytes=int(est.estimated), + limit_bytes=int(hard_limit), + ) + solo = True + else: + solo = False safety_rejection = self._preflight_safety_rejection( est=est, current_usage_bytes=current, @@ -14374,8 +14382,33 @@ def _preflight_memory_check( return safety_rejection if self._external_media_reservation_short(request, est): raise _PreflightDeferredError() + if solo: + self._mark_solo(request, "admit") return None + def _fits_solo( + self, capacity: "_CapacityEstimate | None", est: "_AdmissionEstimate" + ) -> bool: + """A head over the admission line runs alone instead of failing. + + With nothing admitted (and no store write giving memory back), a + request that fits alone by estimate but whose peak, priced on the + current usage, lands between the admission line and the solo line + (the ceiling and prefill safety cap minus the estimate margin) runs + as the solo request: the same rule a parked head follows. The + usage it is priced on holds memory no admitted request owns (queued + requests' vision embeddings, settling buffers). Nothing is admitted + beside it and the enforcer leaves it to the emergency brake; the + chunk guard still bounds each prefill chunk. Only with the park + feature and memory scheduling on (no capacity estimate otherwise). + """ + if not self._park_enabled() or capacity is None or not capacity.fits_alone: + return False + if self._num_admitted_requests(): + return False + lines = self._park_resume_lines() + return lines is not None and est.estimated <= lines[1] + def _external_media_reservation_short( self, request: "Request", est: "_AdmissionEstimate" ) -> bool: @@ -14707,8 +14740,8 @@ def _capacity_estimate( None when it cannot be estimated: no monitor, no memory limit, model weights or KV dimensions unknown, or memory scheduling off. Without - an estimate there is no never-fits error, no fits-later wait and no - capacity hint: the upstream current-usage preflight. + an estimate there is no never-fits error, no fits-later wait, no solo + admission and no capacity hint: the upstream current-usage preflight. """ if not self._memory_scheduling_on(): return None @@ -14933,6 +14966,8 @@ def preflight_or_raise( if fits_later: self._log_fits_later(request_id, est.estimated, admission_limit) return + if self._fits_solo(capacity, est): + return # queues; the in-stream admission runs it alone message = self._format_rejection_message( estimated=est.estimated, current=current, diff --git a/tests/test_memory_scheduling_gate.py b/tests/test_memory_scheduling_gate.py index 0bc35e9df3..bb38ea3efd 100644 --- a/tests/test_memory_scheduling_gate.py +++ b/tests/test_memory_scheduling_gate.py @@ -1,19 +1,21 @@ # SPDX-License-Identifier: Apache-2.0 """Memory scheduling is on only where memory pressure is planned for. -``memory.memory_scheduling`` is ``auto`` (default: on with an explicit custom -ceiling), ``on`` or ``off``. It gates the admission behaviours that plan -against a fixed memory budget: +Three behaviours of the pause-resume cycle used to be on whenever the prefill +memory guard was on (its default), which changed admission for every user: 1. the never-fits 400 ``context_exceeds_capacity``, ``GET /v1/omlx/capacity`` numbers and the ``X-oMLX-Max-Context-Tokens`` header; 2. the fits-later wait (a request that fits alone waits instead of being - rejected on current usage); + rejected on current usage), including the solo admission of a lone head; 3. the progress-based admission-stall clock (600 s bound while memory is held on purpose, store-cache backpressure not a failure while writes drain). -Off, these paths behave as on upstream ``main``. +They plan against a fixed memory budget, so they are on only when the +operator pinned one: ``memory.memory_scheduling`` is ``auto`` (default: on +with an explicit custom ceiling), ``on`` or ``off``. Off, these paths behave +as on upstream ``main``. """ import logging @@ -28,7 +30,9 @@ from test_process_memory_enforcer import _make_enforcer from test_scheduler_admission_progress import _schedule from test_scheduler_capacity_gate import GB +from test_scheduler_park import PROMPT_C, step, submit from test_scheduler_prefill_memory_guard import _make_request, _make_scheduler +from test_scheduler_solo_admission import _lone_rig from test_server_context_capacity import _engine_with_scheduler import omlx.scheduler as scheduler_module @@ -283,6 +287,21 @@ def test_off_rejects_a_fits_later_request_with_the_old_error(gated): assert rejection.message.startswith("Prefill would require") +def test_off_does_not_admit_a_lone_head_solo(tmp_path, mock_tokenizer, monkeypatch): + rig, _usage, _solo = _lone_rig(tmp_path, mock_tokenizer, monkeypatch) + try: + scheduler = rig.scheduler + scheduler._memory_scheduling = False + submit(rig, "lone", PROMPT_C, arrival=1.0) + outputs = step(rig) + (failed,) = [o for o in outputs if o.error] + assert failed.request_id == "lone" + assert failed.error_code != "context_exceeds_capacity" + assert scheduler._solo_request_id is None + finally: + rig.close() + + def test_off_uses_the_fixed_stall_timeout(pressured, clock): """Progress by others does not restart the clock and the error is the one main returns.""" diff --git a/tests/test_scheduler_solo_admission.py b/tests/test_scheduler_solo_admission.py new file mode 100644 index 0000000000..12d4d4dc57 --- /dev/null +++ b/tests/test_scheduler_solo_admission.py @@ -0,0 +1,142 @@ +# SPDX-License-Identifier: Apache-2.0 +"""A queued head that fits alone runs alone instead of failing. + +Forced-pressure image prefill (46 GB): when the request before it finished, +the next image request reached the in-stream preflight with nothing admitted. +Its estimate fits alone (weights + KV + transient under the capacity line), +but the usage reading also held memory no admitted request owns (the queued +requests' vision embeddings and other residue), so ``current + KV + +transient`` crossed the admission line by under 1 GB and the request was +rejected by the prefill memory guard. The peak (~33 GB) was far under the +46 GB ceiling: a parked head in the same position resumes alone (solo), +so a fresh head does too. Nothing is admitted beside it and the enforcer +leaves it to the emergency brake; over the solo line the older rejection +still applies. + +The tests drive the real scheduler loop on the tiny hybrid model. +""" + +import logging + +import pytest +from test_scheduler_capacity_gate import GB, _guarded_rig, gated # noqa: F401 +from test_scheduler_park import PROMPT_A, PROMPT_C, step, submit, waiting_ids + +from omlx.exceptions import PrefillMemoryExceededError + + +def _lone_rig(tmp_path, tokenizer, monkeypatch): + """Guard on, nothing admitted, no idle model to evict; the usage cell + starts 1 GB over the admission line (residue nothing admitted owns).""" + rig, usage = _guarded_rig( + tmp_path, tokenizer, monkeypatch, weights_gb=20, free_gb=50 + ) + scheduler = rig.scheduler + scheduler._prefill_memory_guard = True + monkeypatch.setattr( + scheduler, "_raise_prefill_eviction_if_available", lambda **_kw: None + ) + # As in production: the enforcer's hard watermark (ceiling x hard + # threshold) sets the admission line well under the ceiling. + scheduler._memory_hard_watermark_bytes = 80 * GB + _fit, solo_line = scheduler._park_resume_lines() + admission = scheduler._admission_limit_bytes() + assert solo_line - admission > 2 * GB # room between the two lines + usage[0] = admission + 1 * GB + return rig, usage, solo_line + + +def test_a_lone_head_that_fits_under_the_ceiling_runs_alone( + tmp_path, mock_tokenizer, monkeypatch, caplog +): + rig, _usage, _solo = _lone_rig(tmp_path, mock_tokenizer, monkeypatch) + try: + scheduler = rig.scheduler + with caplog.at_level(logging.INFO, logger="omlx.scheduler"): + request = submit(rig, "lone", PROMPT_C, arrival=1.0) + outputs = step(rig) + assert not [o for o in outputs if o.error], [o.error for o in outputs] + assert scheduler._solo_request_id == "lone" + for _ in range(60): + if request.is_finished(): + break + outputs.extend(step(rig)) + assert request.is_finished() + assert request.finish_reason != "error" + assert not [o for o in outputs if o.error] + assert "Admitting request lone alone (solo)" in caplog.text + finally: + rig.close() + + +def test_nothing_is_admitted_beside_the_lone_head( + tmp_path, mock_tokenizer, monkeypatch +): + rig, usage, _solo = _lone_rig(tmp_path, mock_tokenizer, monkeypatch) + try: + scheduler = rig.scheduler + submit(rig, "lone", PROMPT_C + PROMPT_A[:12], arrival=1.0) + submit(rig, "next", PROMPT_A, arrival=2.0) + outputs = step(rig) + assert not [o for o in outputs if o.error] + assert "lone" in scheduler.running or "lone" in [ + r.request_id for r in scheduler.prefilling + ] + assert waiting_ids(rig) == ["next"] + # Plenty of room now: the solo mark alone keeps "next" waiting. + usage[0] = scheduler._admission_limit_bytes() - 50 * GB + step(rig) + assert "next" in waiting_ids(rig) or scheduler.requests["lone"].is_finished() + finally: + rig.close() + + +def test_over_the_solo_line_the_old_rejection_still_applies( + tmp_path, mock_tokenizer, monkeypatch +): + rig, usage, solo_line = _lone_rig(tmp_path, mock_tokenizer, monkeypatch) + try: + scheduler = rig.scheduler + usage[0] = solo_line + submit(rig, "lone", PROMPT_C, arrival=1.0) + outputs = step(rig, 2) + errors = [o for o in outputs if o.request_id == "lone" and o.error] + assert len(errors) == 1 + assert "lone" not in scheduler.requests + assert scheduler._solo_request_id is None + finally: + rig.close() + + +def test_without_the_park_feature_the_old_rejection_still_applies( + tmp_path, mock_tokenizer, monkeypatch +): + rig, _usage, _solo = _lone_rig(tmp_path, mock_tokenizer, monkeypatch) + try: + scheduler = rig.scheduler + scheduler.config.memory_pressure_park = False + submit(rig, "lone", PROMPT_C, arrival=1.0) + outputs = step(rig, 2) + assert [o for o in outputs if o.request_id == "lone" and o.error] + finally: + rig.close() + + +# --- Route preflight: the same predicate -------------------------------------- + + +def test_the_route_preflight_lets_a_lone_request_that_fits_under_the_ceiling_queue( + gated, # noqa: F811 +): + scheduler, usage, admitted = gated + scheduler.config.memory_pressure_park = True + admitted[0] = 0 + scheduler._memory_hard_watermark_bytes = 80 * GB + _fit, solo_line = scheduler._park_resume_lines() + admission = scheduler._admission_limit_bytes() + assert solo_line - admission > 2 * GB + usage[0] = admission + 1 * GB + scheduler.preflight_or_raise(num_prompt_tokens=1_000, max_tokens=100) + usage[0] = solo_line + with pytest.raises(PrefillMemoryExceededError): + scheduler.preflight_or_raise(num_prompt_tokens=1_000, max_tokens=100) From cd1fedcb9057f3c00e4eef6c5794d1f7d0337b1a Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Fri, 9 Oct 2026 17:31:40 -0600 Subject: [PATCH 41/46] fix(scheduler): keep a lone head that fits alone from failing on a stale reading In an image-decode run under forced memory pressure (42 GB ceiling), req1 fits alone and was deferred while req0 ran. Both prefill-eviction retries were spent in that wait (retry=1/2, insufficient_headroom). When req0 finished, req1 was re-checked as the lone head 9 ms after req0's SSD write-through was dispatched, on a reading that still held pooled Metal buffers and the finished request's KV (current 30.27 GB, ~40.05 GB peak over the 31.28 GB line). With no retry left and the stale estimate over the solo line, the prefill memory guard rejected it. 0.1 s later the ladder freed 6.21 + 2.55 GB for req2. - The eviction budget is per admission attempt: when a fits-later wait ends (a row it waited on left or a store write it waited on drained) or a park resumes, request.prefill_eviction_retries restarts at 0. A retry on backoff beside the same rows keeps the spent budget, so the ladder does not run on every retry. The deferral record stays (the head keeps its hold) with the current picture, so the reset happens once. - A lone head (nothing admitted) that fits alone and is over the admission line or the safety cap returns the pooled buffers on the scheduler thread and is re-measured before any decision. - The fits-later wait also holds while the store-cache pipeline still owns a finished request's KV (gate in-flight or a pending deferred remove); the deferred head retries when a write drains. The run above shows the need: the second ladder pass found another 2.55 GB in the pool within ~170 ms of the finish. With nothing admitted, nothing draining and nothing reclaimed, the older rejection still applies; a request that never fits still gets the 400. --- docs/TESTING.md | 2 +- omlx/scheduler.py | 126 ++++++- tests/test_scheduler_admission_progress.py | 1 + tests/test_scheduler_capacity_gate.py | 16 + tests/test_scheduler_lone_head_after_wait.py | 335 +++++++++++++++++++ 5 files changed, 463 insertions(+), 17 deletions(-) create mode 100644 tests/test_scheduler_lone_head_after_wait.py diff --git a/docs/TESTING.md b/docs/TESTING.md index 50f6bc23cc..e71fbcf65c 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -243,7 +243,7 @@ Run `python -m pytest -q tests/test_memory_scheduling_admin_state.py` to check m # Never-fits gate tests -Run `python -m pytest -q tests/test_scheduler_capacity_gate.py tests/test_scheduler_capacity_vlm.py tests/test_scheduler_deferred_admission.py tests/test_scheduler_solo_admission.py tests/test_server_context_capacity.py` to check the feasibility gate. A request whose weights + exact KV of prompt plus `max_tokens` + prefill transient exceed the capacity line (the tighter of the admission line and the prefill safety cap) is rejected with `ContextExceedsCapacityError` (HTTP 400, `omlx_code: context_exceeds_capacity`, the byte and token fields, `retryable: false`) whatever the current usage. One that fits alone but not now is not rejected: the route preflight lets it queue while other work is admitted (queued requests hold no memory and do not count), and the in-stream admission keeps it at the head (nothing overtakes it) until the admitted rows free memory; both checks share one predicate. With nothing admitted, a head that fits alone but whose peak priced on the current usage (which also holds memory no admitted request owns, such as queued requests' vision embeddings) lands between the admission line and the solo line (the ceiling and prefill safety cap minus 2%) runs alone, as a parked head does: `Admitting request alone (solo)`, nothing is admitted beside it, and the route preflight lets it queue. Over the solo line, or with the park feature off, the older rejection applies. The solo-admission cases drive the real scheduler loop with the admission line set by a hard watermark under the ceiling. A deferred request releases its restored prefix and its block-table refs while it waits, and its re-admission repeats the lookup. The block-table release can wait behind an in-flight prefill commit; it is keyed to the deferred attempt's table, so it never frees a table the request got since. The deferred head is not retried (and its prefix not restored again) on every step: it retries once an admitted row left (finished, aborted or paused), free memory rose by more than 2% of the admission line, or its backoff expired (0.25 s doubling per deferral, capped at 4 s); it keeps the head-of-line hold meanwhile, also while its release still waits behind a commit. Both checks price the same output budget: the route preflight uses the resolved `max_tokens` (request, model setting or server default; the engine default when an engine is called directly). With nothing admitted, or when the capacity cannot be estimated (no memory limit, unknown weights or KV dimensions), the older current-usage rejection applies; unknown weights are never cached and never produce a never-fits rejection. The server cases cover the 400 body on API and non-API routes, `GET /v1/omlx/capacity` (fields, 404/409, auth) and the `X-oMLX-Max-Context-Tokens` header on streaming and non-streaming chat completions. `tests/test_scheduler_capacity_vlm.py` builds a tiny real mlx-vlm Qwen3.5 model (vision tower plus hybrid language model) behind the real `VLMModelAdapter`: the adapter keeps the model in `_vlm_model`, which `nn.Module.parameters()` skips, so the weights are summed from the unwrapped model, each array once. It checks the capacity of that model and of the text model on the batched engine, that `kv_bytes_per_token` prices the TurboQuant prefill peak (full-width KV plus the quantized copy, the last full-attention layer kept full width when there is more than one), that quantized weights count their scales and biases, and that `max_tokens` 2,000,000 reaches the gate unclamped (no route clamps `max_tokens` to the context window) and is rejected as never-fits. These cases run with memory scheduling on (see the memory scheduling gate tests above); off, there is no capacity estimate and the older current-usage rejection applies. +Run `python -m pytest -q tests/test_scheduler_capacity_gate.py tests/test_scheduler_capacity_vlm.py tests/test_scheduler_deferred_admission.py tests/test_scheduler_solo_admission.py tests/test_scheduler_lone_head_after_wait.py tests/test_server_context_capacity.py` to check the feasibility gate. A request whose weights + exact KV of prompt plus `max_tokens` + prefill transient exceed the capacity line (the tighter of the admission line and the prefill safety cap) is rejected with `ContextExceedsCapacityError` (HTTP 400, `omlx_code: context_exceeds_capacity`, the byte and token fields, `retryable: false`) whatever the current usage. One that fits alone but not now is not rejected: the route preflight lets it queue while other work is admitted (queued requests hold no memory and do not count), and the in-stream admission keeps it at the head (nothing overtakes it) until the admitted rows free memory; both checks share one predicate. The same wait applies while the store-cache pipeline still owns a finished request's KV (the gate's in-flight count or a pending deferred remove): right after a request finishes that memory is still in the usage reading, and it comes back when the write drains. With nothing admitted, a head that fits alone and is over the admission line or the prefill safety cap first returns the pooled Metal buffers on the scheduler thread and is re-measured before any decision, because the reading can lag a finished request's release. Eviction retries spent while a head waits (fits-later, or parked) do not count against its next attempt: the budget renews when a row it waited on leaves, a store write it waited on drains, or a park resumes; a retry on backoff beside the same rows keeps the spent budget. `tests/test_scheduler_lone_head_after_wait.py` replays the stale-reading case on the real scheduler loop (a stand-in for the engine pool's eviction ladder frees what the ladder can free when it runs, and the real async store worker is held mid-write): the head spends both retries beside an admitted row, the row finishes, the reading stays stale until an eviction runs, and the head completes; behind a held store write it waits (nothing overtakes it, not retried every step) and runs once the write drains; with nothing admitted, nothing draining and nothing reclaimed, the older rejection still applies. With nothing admitted, a head that fits alone but whose peak priced on the current usage (which also holds memory no admitted request owns, such as queued requests' vision embeddings) lands between the admission line and the solo line (the ceiling and prefill safety cap minus 2%) runs alone, as a parked head does: `Admitting request alone (solo)`, nothing is admitted beside it, and the route preflight lets it queue. Over the solo line, or with the park feature off, the older rejection applies. The solo-admission cases drive the real scheduler loop with the admission line set by a hard watermark under the ceiling. A deferred request releases its restored prefix and its block-table refs while it waits, and its re-admission repeats the lookup. The block-table release can wait behind an in-flight prefill commit; it is keyed to the deferred attempt's table, so it never frees a table the request got since. The deferred head is not retried (and its prefix not restored again) on every step: it retries once an admitted row left (finished, aborted or paused), a store write it waited on drained, free memory rose by more than 2% of the admission line, or its backoff expired (0.25 s doubling per deferral, capped at 4 s); it keeps the head-of-line hold meanwhile, also while its release still waits behind a commit. Both checks price the same output budget: the route preflight uses the resolved `max_tokens` (request, model setting or server default; the engine default when an engine is called directly). With nothing admitted and no store write pending, or when the capacity cannot be estimated (no memory limit, unknown weights or KV dimensions), the older current-usage rejection applies; unknown weights are never cached and never produce a never-fits rejection. The server cases cover the 400 body on API and non-API routes, `GET /v1/omlx/capacity` (fields, 404/409, auth) and the `X-oMLX-Max-Context-Tokens` header on streaming and non-streaming chat completions. `tests/test_scheduler_capacity_vlm.py` builds a tiny real mlx-vlm Qwen3.5 model (vision tower plus hybrid language model) behind the real `VLMModelAdapter`: the adapter keeps the model in `_vlm_model`, which `nn.Module.parameters()` skips, so the weights are summed from the unwrapped model, each array once. It checks the capacity of that model and of the text model on the batched engine, that `kv_bytes_per_token` prices the TurboQuant prefill peak (full-width KV plus the quantized copy, the last full-attention layer kept full width when there is more than one), that quantized weights count their scales and biases, and that `max_tokens` 2,000,000 reaches the gate unclamped (no route clamps `max_tokens` to the context window) and is rejected as never-fits. These cases run with memory scheduling on (see the memory scheduling gate tests above); off, there is no capacity estimate and the older current-usage rejection applies. Mocked tests do not replace hardware validation: with a real model, send a prompt larger than `max_viable_context_tokens` and check for an immediate 400 with the fields, then send two prompts that each fit alone but not together and check that the second waits and completes without an error. diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 14f4aa5812..1e075039c3 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -332,6 +332,8 @@ class _DeferredAdmissionWait: retry_at: float free_bytes: int | None admitted_ids: frozenset[str] + # Post-completion store jobs still owning a finished request's KV. + store_jobs: int = 0 @dataclass @@ -13768,6 +13770,9 @@ def _finish_park_resume( """Re-admission of a parked request: its fresh lookup holds the blocks.""" self._unpin_parked(request.request_id) request.parked = False + # A park is a deliberate wait: eviction retries spent before it do not + # count against the re-admission (as after a fits-later wait). + request.prefill_eviction_retries = 0 self._polls_since_park = None # One resume per hysteresis window: consume the ok streak. self._ok_polls = 0 @@ -14308,11 +14313,8 @@ def _preflight_memory_check( # A request resumed after an eviction pause keeps its prompt cache. # Capacity reserved there already holds part of the KV priced below. - current = max( - 0, - self._current_usage_bytes() - - _reserved_spare_bytes(getattr(request, "prompt_cache", None)), - ) + reserved = _reserved_spare_bytes(getattr(request, "prompt_cache", None)) + current = max(0, self._current_usage_bytes() - reserved) est = self._admission_estimate( num_prompt_tokens=prompt_tokens, cached_tokens=cached_tokens, @@ -14320,6 +14322,16 @@ def _preflight_memory_check( ) if est is None: return None # can't estimate, skip + reclaimed = self._remeasure_lone_head(capacity, est) + if reclaimed is not None: + current = max(0, reclaimed - reserved) + est = self._admission_estimate( + num_prompt_tokens=prompt_tokens, + cached_tokens=cached_tokens, + current=current, + ) + if est is None: + return None hard_limit = self._admission_limit_bytes() peak = est.kv_exact + est.transient @@ -14625,9 +14637,55 @@ def _model_weights_bytes(self) -> int: def _fits_later(self, capacity: "_CapacityEstimate | None") -> bool: """A request that fits alone waits instead of failing only while - admitted rows hold memory that comes back when they finish. Queued - requests hold none, so they never justify waiting.""" - return capacity is not None and self._num_admitted_requests() > 0 + memory that comes back is held: admitted rows (freed when they + finish) or a finished request's KV still owned by the store-cache + pipeline (freed when its write drains). Queued requests hold none, + so they never justify waiting.""" + if capacity is None: + return False + return self._num_admitted_requests() > 0 or self._store_cache_jobs() > 0 + + def _store_cache_jobs(self) -> int: + """Post-completion store jobs that still own a finished request's KV. + + The gate counts submissions until ``_drain_pending_async_removes`` + drops the cache references; a deferred remove without a gate counts + too. Right after a request finishes this memory is still in the usage + reading (one run: re-checked 9 ms after the write-through was dispatched), + so a preflight charges it although it comes back.""" + gate = getattr(self, "_store_cache_gate", None) + in_flight = gate.in_flight if gate is not None else 0 + pending = len(getattr(self, "_pending_async_removes", None) or ()) + return max(in_flight, pending) + + def _remeasure_lone_head( + self, + capacity: "_CapacityEstimate | None", + est: "_AdmissionEstimate", + ) -> int | None: + """Usage after a reclaim, for a lone head the reading would refuse. + + With nothing admitted, a request that fits alone and whose estimate is + over the admission line or the prefill safety cap may be priced on a + reading that lags a finished request's release: pooled Metal buffers + that only a reclaim returns (one run: 6.21 GB freed 0.1 s after such a + head was rejected). Nothing runs beside it, so the pool is cleared + here, on the scheduler thread, before any decision. None when the + head is not such a case (memory scheduling only: no capacity + estimate otherwise). + """ + if capacity is None or not capacity.fits_alone: + return None + if self._num_admitted_requests(): + return None + lines = [ + v + for v in (self._admission_limit_bytes(), self._prefill_abort_cap()) + if v > 0 + ] + if not lines or est.estimated <= min(lines): + return None + return self._reclaim_prefill_headroom() def _release_deferred_admission(self, request: "Request") -> None: """Undo this admission attempt for a request that waits (fits later). @@ -14679,24 +14737,59 @@ def _note_deferred_admission(self, request: "Request") -> None: retry_at=time.monotonic() + _deferred_admission_backoff_s(attempts), free_bytes=self._park_free_bytes(), admitted_ids=self._admitted_request_ids(), + store_jobs=self._store_cache_jobs(), ) + def _deferred_wait_ended(self, wait: _DeferredAdmissionWait) -> bool: + """Whether memory a fits-later head waited on came back: a store write + it waited on drained, or a row it waited on left (finished, aborted + or paused). Measured against the recorded picture only, so a picture + refreshed by ``_end_deferred_wait`` does not end again by itself.""" + if self._store_cache_jobs() < wait.store_jobs: + return True + return not wait.admitted_ids <= self._admitted_request_ids() + + def _end_deferred_wait(self, head: "Request") -> None: + """Start a new admission attempt for a head whose wait ended. + + Eviction retries spent while it waited (the ladder could not make + room beside the rows it waited on) do not count against the attempt + that follows: a head that spent both beside a running request was + then rejected as the lone head with no retry left. The record stays + (the head keeps its hold, e.g. behind a pending teardown), now holding + the current picture and a due retry, so the eviction pause that may + follow is neither held nor renewed again. A retry on backoff or a + free-memory rise beside the same rows keeps the spent budget (no + ladder pass on every retry). + """ + wait = self._deferred_admissions.get(head.request_id) + if wait is None or not self._deferred_wait_ended(wait): + return + self._deferred_admissions[head.request_id] = _DeferredAdmissionWait( + attempts=wait.attempts, + retry_at=time.monotonic(), + free_bytes=wait.free_bytes, + admitted_ids=self._admitted_request_ids(), + store_jobs=self._store_cache_jobs(), + ) + head.prefill_eviction_retries = 0 + def _deferred_admission_holds(self, head: "Request") -> bool: """Whether a deferred fits-later ``head`` waits instead of retrying. - It retries once the memory picture changed since it deferred: no row - is admitted any more (the fits-later wait no longer applies), a row - it waited on left (finished, aborted or paused), free memory rose by - more than ``DEFERRED_ADMISSION_FREE_DELTA_FRACTION`` of the admission - line, or its backoff expired. The record stays, so a new deferral - doubles the backoff. + It retries once nothing is admitted or draining any more (the + fits-later wait no longer applies), the memory it waited on came back + (see ``_deferred_wait_ended``), free memory rose by more than + ``DEFERRED_ADMISSION_FREE_DELTA_FRACTION`` of the admission line, or + its backoff expired. The record stays, so a new deferral doubles the + backoff. """ wait = self._deferred_admissions.get(head.request_id) if wait is None: return False - if not self._num_admitted_requests(): + if not self._num_admitted_requests() and not self._store_cache_jobs(): return False - if not wait.admitted_ids <= self._admitted_request_ids(): + if self._deferred_wait_ended(wait): return False free = self._park_free_bytes() if free is not None and wait.free_bytes is not None: @@ -15229,6 +15322,7 @@ def _schedule_waiting_scan( if stalled is not None: rejected_outputs.append(stalled) break + self._end_deferred_wait(self.waiting[0]) admitted = self._num_admitted_requests() if self._admission_paused and admitted: diff --git a/tests/test_scheduler_admission_progress.py b/tests/test_scheduler_admission_progress.py index d240f9cfbe..62116cc503 100644 --- a/tests/test_scheduler_admission_progress.py +++ b/tests/test_scheduler_admission_progress.py @@ -374,6 +374,7 @@ def test_a_deferred_head_waits_under_the_long_bound(pressured, clock): admitted_ids=frozenset({"run"}), free_bytes=None, retry_at=clock.now + 10_000, + store_jobs=0, ) assert _schedule(scheduler) == [] clock.advance(scheduler._MEMORY_ADMISSION_STALL_TIMEOUT_S * 3) diff --git a/tests/test_scheduler_capacity_gate.py b/tests/test_scheduler_capacity_gate.py index cb81c6d8b3..31cfcb0f37 100644 --- a/tests/test_scheduler_capacity_gate.py +++ b/tests/test_scheduler_capacity_gate.py @@ -207,6 +207,22 @@ def test_fits_alone_but_not_now_on_an_idle_scheduler_keeps_the_old_rejection(gat assert not isinstance(info.value, ContextExceedsCapacityError) +def test_fits_alone_but_not_now_waits_while_a_finished_requests_store_drains(gated): + """Right after a request finishes, the store-cache pipeline still owns + its KV, so the reading still holds it. That memory comes back when the + write drains, so the request waits (route and in-stream share this).""" + scheduler, usage, admitted = gated + usage[0] = 99 * GB + admitted[0] = 0 + gate = scheduler_module._StoreCacheGate(cap=3) + gate.note_submitted() + scheduler._store_cache_gate = gate + scheduler.preflight_or_raise(num_prompt_tokens=50_000, max_tokens=1_000) + gate.note_done() # drained: nothing comes back any more + with pytest.raises(PrefillMemoryExceededError): + scheduler.preflight_or_raise(num_prompt_tokens=50_000, max_tokens=1_000) + + def test_unknown_capacity_keeps_the_old_rejection(gated): scheduler, usage, admitted = gated scheduler._weights_bytes = None # MagicMock model: weights unknown diff --git a/tests/test_scheduler_lone_head_after_wait.py b/tests/test_scheduler_lone_head_after_wait.py new file mode 100644 index 0000000000..a4596355df --- /dev/null +++ b/tests/test_scheduler_lone_head_after_wait.py @@ -0,0 +1,335 @@ +# SPDX-License-Identifier: Apache-2.0 +"""A head that fits alone, waits beside admitted work, then becomes the lone head. + +Forced pressure (image decode at a 42 GB ceiling): req1 fits alone and was +correctly deferred while req0 ran ("fits alone but not now"). Its two +prefill-eviction retries were spent in that wait. When req0 finished, req1 was +the only waiting request and was re-checked on a usage reading that still held +pooled Metal buffers and the finished request's KV in the store pipeline +(current 30.27 GB, ~40.05 GB peak over the 31.28 GB line). With no retry left +and the stale estimate over the solo line too, it was rejected by the prefill +memory guard. 0.1 s later the eviction ladder freed 6.21 + 2.55 GB for the +next request. + +The tests drive the real scheduler loop on the tiny model against real stores. +The usage reading is controlled; the engine pool's eviction ladder is stood in +by a servicer that frees what the ladder can free when an eviction runs. +""" + +import threading + +from test_scheduler_capacity_gate import GB, _guarded_rig +from test_scheduler_park import PROMPT_A, PROMPT_C, submit, waiting_ids + +import omlx.scheduler as scheduler_module + + +class _Ladder: + """Stands in for EnginePool's prefill-eviction ladder (EngineCore runs it + between steps for the request a step paused).""" + + def __init__(self): + self.calls = [] + self.frees = None # callable run when a pass can free memory + + def run(self, eviction_request): + self.calls.append(eviction_request.request_id) + if self.frees is not None: + self.frees() + + +def _step(rig, ladder, n=1): + outputs = [] + for _ in range(n): + result = rig.scheduler.step() + outputs.extend(result.outputs) + if result.prefill_eviction_request is not None: + ladder.run(result.prefill_eviction_request) + rig.drain() + return outputs + + +def _step_until(rig, ladder, predicate, limit=80): + outputs = [] + for _ in range(limit): + if predicate(): + return outputs + outputs.extend(_step(rig, ladder)) + raise AssertionError("condition not reached") + + +def _done(scheduler, request): + """Finished, or dropped by a rejection (which leaves no live request).""" + return request.is_finished() or request.request_id not in scheduler.requests + + +def _stale_usage(scheduler): + """A reading whose estimate is over the admission line and the solo line + (the observed rejection: ~40.05 GB against a 31.28 GB line).""" + return max(scheduler._admission_limit_bytes(), scheduler._park_resume_lines()[1]) + + +def _defer_beside_admitted_work(rig, ladder, monkeypatch, usage): + """Phase 1: rows are admitted and hold the memory; the head defers after + spending both eviction retries on passes that free nothing.""" + scheduler = rig.scheduler + scheduler._prefill_memory_guard = True + admitted = [1] + monkeypatch.setattr(scheduler, "_num_admitted_requests", lambda: admitted[0]) + monkeypatch.setattr( + scheduler, + "_admitted_request_ids", + lambda: frozenset({"req0"} if admitted[0] else ()), + ) + usage[0] = scheduler._admission_limit_bytes() + later = submit(rig, "later", PROMPT_C, arrival=1.0) + outputs = _step(rig, ladder, 4) + assert not [o for o in outputs if o.error] + assert waiting_ids(rig) == ["later"] + assert "later" in scheduler._deferred_admissions + assert ladder.calls == ["later", "later"] + return later, admitted + + +def test_a_fits_later_wait_does_not_spend_the_lone_heads_eviction_budget( + tmp_path, mock_tokenizer, monkeypatch +): + """The stale-reading scenario: once the rows it waited on leave, the head gets a + fresh eviction budget, the ladder frees the stale memory, and it runs.""" + rig, usage = _guarded_rig( + tmp_path, mock_tokenizer, monkeypatch, weights_gb=20, free_gb=50 + ) + ladder = _Ladder() + try: + scheduler = rig.scheduler + later, admitted = _defer_beside_admitted_work(rig, ladder, monkeypatch, usage) + + # req0 finishes. The reading lags its release: only an eviction pass + # (hot cache, idle model, pooled buffers on the engine thread) frees it. + admitted[0] = 0 + usage[0] = _stale_usage(scheduler) + free_now = scheduler._admission_limit_bytes() - 50 * GB + ladder.frees = lambda: usage.__setitem__(0, free_now) + outputs = _step_until(rig, ladder, lambda: _done(scheduler, later)) + assert later.finish_reason != "error" + assert not [o for o in outputs if o.request_id == "later" and o.error] + assert ladder.calls[2:] == ["later"] # the ladder ran for it again + finally: + rig.close() + + +def test_a_backoff_retry_beside_the_same_rows_gets_no_fresh_budget( + tmp_path, mock_tokenizer, monkeypatch +): + """While the rows it waits on still run, a retry on backoff does not pause + for the ladder again: the budget renews only when the wait ends.""" + monkeypatch.setattr(scheduler_module, "DEFERRED_ADMISSION_RETRY_BASE_S", 0.0) + rig, usage = _guarded_rig( + tmp_path, mock_tokenizer, monkeypatch, weights_gb=20, free_gb=50 + ) + ladder = _Ladder() + try: + later, _admitted = _defer_beside_admitted_work(rig, ladder, monkeypatch, usage) + outputs = _step(rig, ladder, 6) + assert not [o for o in outputs if o.error] + assert waiting_ids(rig) == ["later"] + assert ladder.calls == ["later", "later"] + assert later.prefill_eviction_retries == 2 + finally: + rig.close() + + +def test_a_lone_head_on_a_stale_reading_reclaims_and_rechecks_before_rejecting( + tmp_path, mock_tokenizer, monkeypatch +): + """With no eviction left to ask for, the lone head that fits alone first + returns the pooled buffers on the scheduler thread and re-measures.""" + rig, usage = _guarded_rig( + tmp_path, mock_tokenizer, monkeypatch, weights_gb=20, free_gb=50 + ) + ladder = _Ladder() + try: + scheduler = rig.scheduler + scheduler._prefill_memory_guard = True + monkeypatch.setattr( + scheduler, "_raise_prefill_eviction_if_available", lambda **_kw: None + ) + free_now = scheduler._admission_limit_bytes() - 50 * GB + reclaims = [] + + def reclaim(): + reclaims.append(usage[0]) + usage[0] = free_now # the pooled buffers return + return usage[0] + + monkeypatch.setattr(scheduler, "_reclaim_prefill_headroom", reclaim) + usage[0] = _stale_usage(scheduler) + only = submit(rig, "only", PROMPT_C, arrival=1.0) + outputs = _step_until(rig, ladder, lambda: _done(scheduler, only)) + assert only.finish_reason != "error" + assert not [o for o in outputs if o.error] + assert reclaims, "the head was not re-measured after a reclaim" + finally: + rig.close() + + +def test_a_lone_head_that_still_does_not_fit_after_the_reclaim_is_rejected( + tmp_path, mock_tokenizer, monkeypatch +): + """Memory nothing gives back (another app, a leak) is not waited on: with + nothing admitted, nothing draining and the reclaim freeing nothing, the + older rejection still applies.""" + rig, usage = _guarded_rig( + tmp_path, mock_tokenizer, monkeypatch, weights_gb=20, free_gb=50 + ) + ladder = _Ladder() + try: + scheduler = rig.scheduler + scheduler._prefill_memory_guard = True + usage[0] = _stale_usage(scheduler) + submit(rig, "only", PROMPT_C, arrival=1.0) + outputs = _step(rig, ladder, 4) + errors = [o for o in outputs if o.request_id == "only" and o.error] + assert len(errors) == 1 + assert errors[0].error_code != "context_exceeds_capacity" + assert "only" not in scheduler.requests + finally: + rig.close() + + +# --- The finished request's KV in the store pipeline ----------------------------- + + +def _step_unheld(rig, ladder, n=1): + """Step without waiting for the (held) store-cache worker.""" + outputs = [] + scheduler = rig.scheduler + for _ in range(n): + result = scheduler.step() + outputs.extend(result.outputs) + if result.prefill_eviction_request is not None: + ladder.run(result.prefill_eviction_request) + commit_executor = getattr(scheduler, "_prefill_commit_executor", None) + if commit_executor is not None: + commit_executor.submit(lambda: None).result(timeout=20) + scheduler._process_finished_commits() + return outputs + + +def _store_held_rig(tmp_path, tokenizer, monkeypatch, ladder): + """A request finished and its store-cache write is held in flight. + + While the pipeline owns the payload, the reading is over the solo line; + once it gives the payload back the reading drops 50 GB under the line. + """ + rig, _usage = _guarded_rig( + tmp_path, tokenizer, monkeypatch, weights_gb=20, free_gb=50 + ) + scheduler = rig.scheduler + scheduler._prefill_memory_guard = True + scheduler._store_cache_gate = scheduler_module._StoreCacheGate(cap=3) + release = threading.Event() + real_worker = scheduler._async_store_cache_worker + + def held_worker(*args, **kwargs): + # Only the post-completion store is held; prefill progress commits + # run on their own executor and are not held. + if threading.current_thread().name.startswith("omlx-store-cache"): + release.wait(timeout=30) + return real_worker(*args, **kwargs) + + monkeypatch.setattr(scheduler, "_async_store_cache_worker", held_worker) + stale = _stale_usage(scheduler) + free_now = scheduler._admission_limit_bytes() - 50 * GB + + def usage(**_kw): + gate = scheduler._store_cache_gate + owned = (gate is not None and gate.in_flight > 0) or bool( + scheduler._pending_async_removes + ) + return stale if owned else free_now + + monkeypatch.setattr(scheduler, "_current_usage_bytes", usage) + first = submit(rig, "first", PROMPT_A, arrival=0.5, max_tokens=2) + for _ in range(60): + if first.is_finished(): + break + _step_unheld(rig, ladder) + assert first.is_finished() and first.finish_reason != "error" + assert scheduler._num_admitted_requests() == 0 + assert scheduler._store_cache_gate.in_flight == 1 + return rig, release + + +def test_a_lone_head_behind_a_draining_store_write_waits_then_runs( + tmp_path, mock_tokenizer, monkeypatch +): + ladder = _Ladder() + rig, release = _store_held_rig(tmp_path, mock_tokenizer, monkeypatch, ladder) + try: + scheduler = rig.scheduler + second = submit(rig, "second", PROMPT_C, arrival=1.0) + submit(rig, "newer", PROMPT_A, arrival=2.0) + outputs = _step_unheld(rig, ladder, 6) + assert not [o for o in outputs if o.error], [o.error for o in outputs] + assert waiting_ids(rig) == ["second", "newer"] # nothing overtakes it + + release.set() # the write finishes; the pipeline gives the KV back + for _ in range(200): + if second.is_finished(): + break + outputs.extend(_step_unheld(rig, ladder)) + scheduler._store_cache_executor.submit(lambda: None).result(timeout=20) + assert second.is_finished() + assert second.finish_reason != "error" + assert not [o for o in outputs if o.error] + finally: + release.set() + rig.close() + + +def test_the_head_behind_a_store_write_is_not_retried_every_step( + tmp_path, mock_tokenizer, monkeypatch +): + monkeypatch.setattr(scheduler_module, "DEFERRED_ADMISSION_RETRY_BASE_S", 60.0) + monkeypatch.setattr(scheduler_module, "DEFERRED_ADMISSION_RETRY_MAX_S", 60.0) + ladder = _Ladder() + rig, release = _store_held_rig(tmp_path, mock_tokenizer, monkeypatch, ladder) + try: + scheduler = rig.scheduler + attempts = [] + real_check = scheduler._preflight_memory_check + + def check(request): + if request.request_id == "second": + attempts.append(request.prefill_eviction_retries) + return real_check(request) + + monkeypatch.setattr(scheduler, "_preflight_memory_check", check) + submit(rig, "second", PROMPT_C, arrival=1.0) + _step_unheld(rig, ladder, 10) + # Two eviction passes, then one deferral; no retry while it holds. + assert len(attempts) == 3, attempts + assert waiting_ids(rig) == ["second"] + finally: + release.set() + rig.close() + + +# --- Park --------------------------------------------------------------------------- + + +def test_a_park_resume_starts_a_fresh_eviction_budget(tmp_path, mock_tokenizer): + """A park is a deliberate wait: retries spent before it do not count + against the re-admission.""" + from test_scheduler_park import make_rig + + rig = make_rig(tmp_path, mock_tokenizer) + try: + request = submit(rig, "parked", PROMPT_C, arrival=1.0) + request.parked = True + request.prefill_eviction_retries = 2 + rig.scheduler._finish_park_resume(request, log=False) + assert request.prefill_eviction_retries == 0 + finally: + rig.close() From cbf624f58ee65cd8b551ecfd24663c6be88e961a Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Fri, 9 Oct 2026 19:42:05 -0600 Subject: [PATCH 42/46] fix(scheduler): renew a deferred head's eviction budget on a store drain only when it blocked The fits-later wait ended, and the eviction budget reset, whenever the store-job count fell below the count recorded at deferral, even while the admitted rows the head waited on still ran. An unrelated earlier request's write draining then gave the head fresh ladder passes beside the same rows. A store drain now ends the wait only for a head that waited on no admitted row (a lone head waiting on the write). Beside rows it waits on, only one of them leaving ends the wait. The stale-reading case stays covered: the waited-on row leaving ends the wait and renews the budget. --- omlx/scheduler.py | 12 +++++---- tests/test_scheduler_lone_head_after_wait.py | 28 ++++++++++++++++++++ 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 1e075039c3..c55565a1c4 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -14741,13 +14741,15 @@ def _note_deferred_admission(self, request: "Request") -> None: ) def _deferred_wait_ended(self, wait: _DeferredAdmissionWait) -> bool: - """Whether memory a fits-later head waited on came back: a store write - it waited on drained, or a row it waited on left (finished, aborted - or paused). Measured against the recorded picture only, so a picture + """Whether memory a fits-later head waited on came back: a row it + waited on left (finished, aborted or paused), or, for a head that + waited on no row (only on store writes), a write drained. Beside rows + it waits on, a drain is some earlier request's write, not what blocks + it. Measured against the recorded picture only, so a picture refreshed by ``_end_deferred_wait`` does not end again by itself.""" - if self._store_cache_jobs() < wait.store_jobs: + if not wait.admitted_ids <= self._admitted_request_ids(): return True - return not wait.admitted_ids <= self._admitted_request_ids() + return not wait.admitted_ids and self._store_cache_jobs() < wait.store_jobs def _end_deferred_wait(self, head: "Request") -> None: """Start a new admission attempt for a head whose wait ended. diff --git a/tests/test_scheduler_lone_head_after_wait.py b/tests/test_scheduler_lone_head_after_wait.py index a4596355df..6d1d2f5bc7 100644 --- a/tests/test_scheduler_lone_head_after_wait.py +++ b/tests/test_scheduler_lone_head_after_wait.py @@ -139,6 +139,34 @@ def test_a_backoff_retry_beside_the_same_rows_gets_no_fresh_budget( rig.close() +def test_an_unrelated_store_drain_beside_the_same_rows_gets_no_fresh_budget( + tmp_path, mock_tokenizer, monkeypatch +): + """An earlier request's store write in flight at deferral is not what the + head waits on: its drain, while the rows it waits on still run, does not + end the wait or renew the eviction budget.""" + rig, usage = _guarded_rig( + tmp_path, mock_tokenizer, monkeypatch, weights_gb=20, free_gb=50 + ) + ladder = _Ladder() + try: + scheduler = rig.scheduler + gate = scheduler_module._StoreCacheGate(cap=3) + gate.note_submitted() # an unrelated earlier request's write + scheduler._store_cache_gate = gate + later, _admitted = _defer_beside_admitted_work(rig, ladder, monkeypatch, usage) + assert scheduler._deferred_admissions["later"].store_jobs == 1 + + gate.note_done() # it drains; req0 still runs + outputs = _step(rig, ladder, 6) + assert not [o for o in outputs if o.error] + assert waiting_ids(rig) == ["later"] + assert ladder.calls == ["later", "later"] + assert later.prefill_eviction_retries == 2 + finally: + rig.close() + + def test_a_lone_head_on_a_stale_reading_reclaims_and_rechecks_before_rejecting( tmp_path, mock_tokenizer, monkeypatch ): From 2b83b55886d40f00253fcad11039b01d6aa4da08 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Tue, 6 Oct 2026 13:22:49 -0600 Subject: [PATCH 43/46] fix(scheduler): keep the progress clock while a park hold is active With memory scheduling off and park on, a parked head still resumes as the solo request (park only), but the head queued behind it got upstream's fixed 60 s clock and failed while the solo request was still emitting tokens, as in the forced memory-pressure run. The admission-stall clocks now measure time without progress, with the 600 s bound for deliberate holds, whenever memory scheduling is on or a hold the park feature created is active: a parked or decode-paused request running solo or waiting in the queue. With park off such holds never exist, so upstream's fixed clock is unchanged. memory_scheduling keeps gating the never-fits 400 with the capacity numbers and header, the fits-later wait, the solo admission of a lone head and the external-prefill solo. --- README.md | 4 +- docs/TESTING.md | 4 +- omlx/scheduler.py | 41 +++++++++--- tests/test_memory_scheduling_gate.py | 28 ++++++++- tests/test_scheduler_admission_progress.py | 72 ++++++++++++++++++++++ 5 files changed, 134 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 37e94451f6..398ebd193c 100644 --- a/README.md +++ b/README.md @@ -291,10 +291,10 @@ With memory scheduling on: - **Never fits.** A request that cannot fit even with nothing else running (model weights + KV for the prompt plus `max_tokens` + the prefill transient, over the memory guard's capacity line) is rejected up front with HTTP 400 and `omlx_code: "context_exceeds_capacity"`. The usual error envelope stays (`message`, `type`, `code`, `estimated_bytes`, `limit_bytes`) and adds `required_bytes`, `capacity_bytes`, `weights_bytes`, `kv_bytes_per_token`, `requested_context_tokens`, `requested_max_tokens`, `max_viable_context_tokens` and `retryable: false`. Compact or shorten the context, or lower `max_tokens`, before retrying. - **Fits later.** A request that fits alone but not right now is not rejected. It waits at the head of the queue until running requests free memory. With the park feature on and nothing running, it can run alone (solo) instead of being rejected. -- **Stall clock.** A queued request fails after 60 s without progress by any request (a token, a prefill chunk, a drained cache write), not 60 s after it started waiting. While memory is held on purpose, the bound is `scheduler.admission_no_progress_timeout_s` (default 600 s). +- **Stall clock.** A queued request fails after 60 s without progress by any request (a token, a prefill chunk, a drained cache write), not 60 s after it started waiting. While memory is held on purpose, the bound is `scheduler.admission_no_progress_timeout_s` (default 600 s). With the park feature on (`scheduler.memory_pressure_park`), this clock also applies while a parked or paused request runs alone or waits, whatever `memory_scheduling` says. - **Capacity numbers.** `GET /v1/omlx/capacity?model=&context_tokens=&max_tokens=` (API key like the other `/v1` routes) returns the same numbers for a request of that size plus `free_bytes_now`, without loading the model. An unknown model is a 404 and an unloaded one a 409; `available: false` when no estimate exists. Chat completions also carry an `X-oMLX-Max-Context-Tokens` header: the largest prompt plus `max_tokens` that fits alone. -With memory scheduling off, a request is checked against the current usage and rejected if it does not fit now, a queued request fails 60 s after it started waiting for memory, and there is no header. The capacity endpoint still answers for a loaded model, with `available: false`, `memory_scheduling: "off"` and the reason. +With memory scheduling off, a request is checked against the current usage and rejected if it does not fit now, a queued request fails 60 s after it started waiting for memory (unless a park hold is active, see above), and there is no header. The capacity endpoint still answers for a loaded model, with `available: false`, `memory_scheduling: "off"` and the reason. The admin API for settings, models, downloads, quantization, and benchmarks takes the main API key as a Bearer token and also works in headless mode. See [Admin API](docs/admin-api.md). diff --git a/docs/TESTING.md b/docs/TESTING.md index e71fbcf65c..9adeb6fdc5 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -237,7 +237,7 @@ Mocked tests do not replace hardware validation: with a real model, abort a long # Memory scheduling gate tests -Run `python -m pytest -q tests/test_memory_scheduling_gate.py` to check `memory.memory_scheduling` (env `OMLX_MEMORY_SCHEDULING`; `auto`, `on` or `off`, default `auto`). It gates three behaviours: the never-fits 400 with the capacity endpoint numbers and the `X-oMLX-Max-Context-Tokens` header; the fits-later wait, including the solo admission of a lone head; and the progress-based admission-stall clock. `auto` is on when the prefill memory guard is on and an explicit ceiling is set (`memory_guard_tier: custom` with `memory_guard_custom_ceiling_gb` > 0; a ceiling value left under another tier does not count). `on` forces it on but still needs the guard (with the guard off it stays off and logs a warning). `off` forces it off. The `ProcessMemoryEnforcer` resolves the mode at startup and whenever the mode, the guard, the tier or the ceiling changes (the admin settings apply live), logs `Memory scheduling: on (explicit ceiling 48.0 GB)` or the reason it is off, and propagates the result to every scheduler (`Scheduler._memory_scheduling`, False until an enforcer sets it). The tests cover the resolution matrix, the setting (default, `to_dict`, `from_dict`, env override, validation, the admin GET and POST), and, with it off, upstream behaviour on each path: no capacity estimate, snapshot or header (a cached hint is not served either); a request whose `max_tokens` can never fit passes when its prompt fits now; a fits-alone-but-not-now request gets the old current-usage rejection; a lone head is not admitted solo; the stall clock fails the head 60 s after it first blocked, whatever else progresses, with the old message and metadata (no `no_progress_seconds`), also behind a solo request and for store-cache backpressure; an external-loop prefill is not reported as solo to the enforcer; and the capacity endpoint returns `available: false` with `memory_scheduling: "off"` and the reason, while unknown and unloaded models keep their 404 and 409. `tests/test_memory_external_prefill.py` also drives the real enforcer with park, single victim and memory scheduling off: the lone external prefill at hard pressure gets upstream's abort-all. The suites below that test these behaviours set the mode on explicitly (`scheduler._memory_scheduling = True`, or `memory_scheduling="on"` on the real enforcer). +Run `python -m pytest -q tests/test_memory_scheduling_gate.py` to check `memory.memory_scheduling` (env `OMLX_MEMORY_SCHEDULING`; `auto`, `on` or `off`, default `auto`). It gates three behaviours: the never-fits 400 with the capacity endpoint numbers and the `X-oMLX-Max-Context-Tokens` header; the fits-later wait, including the solo admission of a lone head; and the progress-based admission-stall clock. `auto` is on when the prefill memory guard is on and an explicit ceiling is set (`memory_guard_tier: custom` with `memory_guard_custom_ceiling_gb` > 0; a ceiling value left under another tier does not count). `on` forces it on but still needs the guard (with the guard off it stays off and logs a warning). `off` forces it off. The `ProcessMemoryEnforcer` resolves the mode at startup and whenever the mode, the guard, the tier or the ceiling changes (the admin settings apply live), logs `Memory scheduling: on (explicit ceiling 48.0 GB)` or the reason it is off, and propagates the result to every scheduler (`Scheduler._memory_scheduling`, False until an enforcer sets it). The tests cover the resolution matrix, the setting (default, `to_dict`, `from_dict`, env override, validation, the admin GET and POST), and, with it off, upstream behaviour on each path: no capacity estimate, snapshot or header (a cached hint is not served either); a request whose `max_tokens` can never fit passes when its prompt fits now; a fits-alone-but-not-now request gets the old current-usage rejection; a lone head is not admitted solo; the stall clock fails the head 60 s after it first blocked, whatever else progresses, with the old message and metadata (no `no_progress_seconds`), also for store-cache backpressure; with the park feature on, a hold it created (a parked or decode-paused request running solo or waiting) keeps the progress clock and its 600 s bound whatever the mode, because the head waits for work held back on purpose (park off, no such hold exists); an external-loop prefill is not reported as solo to the enforcer; and the capacity endpoint returns `available: false` with `memory_scheduling: "off"` and the reason, while unknown and unloaded models keep their 404 and 409. `tests/test_memory_external_prefill.py` also drives the real enforcer with park, single victim and memory scheduling off: the lone external prefill at hard pressure gets upstream's abort-all. The suites below that test these behaviours set the mode on explicitly (`scheduler._memory_scheduling = True`, or `memory_scheduling="on"` on the real enforcer). Run `python -m pytest -q tests/test_memory_scheduling_admin_state.py` to check memory scheduling across admin settings saves. The cases load the real settings with `memory_scheduling: "on"` in `settings.json`, build the live enforcer from them as the server does, and drive the real admin routes. A save of `max_concurrent_requests`, `chunked_prefill` or `memory_guard_tier` keeps the mode on the live settings object and in `settings.json` (a reload sees it again), keeps it on and propagated, and logs no `Memory scheduling:` line. Loading the settings page (`GET /admin/api/global-settings`, which builds one tier-preview enforcer per tier) logs none either: only an enforcer that drives an engine pool logs its state. An explicit `memory_scheduling` POST, including one that repeats the current mode, re-resolves, logs the state and propagates it to the schedulers. The GET reports the live state as `memory.memory_scheduling_effective` (`enabled` and `reason`, `null` without an enforcer), the POST response carries it, and the factory defaults response does not. @@ -263,6 +263,6 @@ Run `python -m pytest -q tests/test_memory_resume_thrash.py` to check that a pau Run `python -m pytest -q tests/test_memory_external_prefill.py` to check memory pressure while a prompt prefills in the external loop (a media prompt whose images are not all cached; it cannot be parked). A request in that loop with nothing else admitted runs alone: at hard pressure below the emergency threshold the enforcer neither pauses nor aborts it. With a decoding row beside it, the decoding row is paused instead. When the single-victim selection finds no live request (queued requests hold no memory), the non-emergency path aborts nothing; before, it fell back to aborting every request. At emergency pressure (beyond the ceiling) the enforcer first pauses the largest pausable decoding row when freeing its estimate brings usage back under the ceiling, and waits for that pause at most two polls (`_EMERGENCY_PAUSE_MAX_POLLS`) and only while usage does not grow; abort-all stays the last resort when nothing is pausable, no pause gets under the ceiling, or the pause is declined or too slow. With the park feature on, a media prefill beside admitted work whose estimated peak (current usage, exact KV and transient) crosses the resume line (the hard watermark minus 5%) waits at the head until an admitted row leaves; it does not pause a decoding row for room, because the paused row would be parked ahead of it and resume first. The external-loop tests block the scheduler's own thread inside the external prefill so the real enforcer polls while it runs, as in production. The lone external prefill counts as solo only with memory scheduling on; these tests set it on. -Run `python -m pytest -q tests/test_scheduler_admission_progress.py` to check that a queued request waits while memory is scheduled on purpose. The admission-stall clock measures time without progress: a token emitted, a prefill chunk processed, an external prefill finished, a request admitted or a store-cache write drained restarts it. Without progress the head fails after 60 s; while a solo request runs, a fits-later head backs off, or a parked or decode-paused request waits, it fails only after `scheduler.admission_no_progress_timeout_s` (`OMLX_ADMISSION_NO_PROGRESS_TIMEOUT_S`, default 600 s) without progress, so a genuine deadlock still surfaces with `memory_admission_stalled` and `no_progress_seconds`. Store-cache backpressure is not a failure while the writer drains. The scheduler logs `Admission waiting for memory: ; request(s) progressing` every 30 s per head. The real-rig cases drive the real enforcer and scheduler on a controlled clock (2 s per step): three requests that fit one at a time complete in sequence (the old clock failed the second after 60 s while the first still decoded), and a wedged decode still fails the queued request. These cases run with memory scheduling on; off, the clock is upstream's fixed 60 s from when the head first blocked. +Run `python -m pytest -q tests/test_scheduler_admission_progress.py` to check that a queued request waits while memory is scheduled on purpose. The admission-stall clock measures time without progress: a token emitted, a prefill chunk processed, an external prefill finished, a request admitted or a store-cache write drained restarts it. Without progress the head fails after 60 s; while a solo request runs, a fits-later head backs off, or a parked or decode-paused request waits, it fails only after `scheduler.admission_no_progress_timeout_s` (`OMLX_ADMISSION_NO_PROGRESS_TIMEOUT_S`, default 600 s) without progress, so a genuine deadlock still surfaces with `memory_admission_stalled` and `no_progress_seconds`. Store-cache backpressure is not a failure while the writer drains. The scheduler logs `Admission waiting for memory: ; request(s) progressing` every 30 s per head. The real-rig cases drive the real enforcer and scheduler on a controlled clock (2 s per step): three requests that fit one at a time complete in sequence (the old clock failed the second after 60 s while the first still decoded), and a wedged decode still fails the queued request. These cases run with memory scheduling on; off, the clock is upstream's fixed 60 s from when the head first blocked, unless a park hold is active. A real-rig case runs park on and memory scheduling off: a request paused twice while alone resumes as the solo request, and the head queued behind it waits while the solo request decodes and then completes (the fixed clock failed it after 60 s in a forced-pressure run). Mocked tests do not replace hardware validation: with a real model, run three concurrent long prompts under a ceiling too low for all of them and check that each completes with the park/resume log lines and a cached count close to the last commit, and that no client sees a memory error. diff --git a/omlx/scheduler.py b/omlx/scheduler.py index c55565a1c4..fb71ea8658 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -6093,14 +6093,36 @@ def _note_admission_progress(self) -> None: (with memory scheduling on).""" self._admission_progress_at = time.monotonic() + def _progress_clock_on(self) -> bool: + """Whether the admission-stall clocks measure time without progress. + + With memory scheduling on, always. Off, only while a hold the park + feature created is active (``_park_memory_hold``): the head then + waits for work the scheduler holds back on purpose, and upstream's + clock (from when the head first blocked) would fail it while that + work progresses. With park off such holds never exist, so the clock + stays upstream's. + """ + return self._memory_scheduling_on() or self._park_memory_hold() + + def _park_memory_hold(self) -> bool: + """A hold the park feature created: a parked or decode-paused + request running solo, or one waiting in the queue.""" + if not self._park_enabled(): + return False + if self._solo_request() is not None: + return True + return any(request.parked for request in self.waiting) + def _admission_idle_since(self, blocked_since: float) -> float: """Start of the current no-progress stretch for a blocked head. - With memory scheduling off the clock is upstream's: it runs from - when the head first blocked, whatever else progresses. + Without the progress clock (``_progress_clock_on``) the clock is + upstream's: it runs from when the head first blocked, whatever else + progresses. """ progress = self._admission_progress_at - if progress is None or not self._memory_scheduling_on(): + if progress is None or not self._progress_clock_on(): return blocked_since return max(blocked_since, progress) @@ -6139,8 +6161,9 @@ def _memory_admission_stall_output(self, reason: str) -> RequestOutput | None: progress, or ``admission_no_progress_timeout_s`` while memory is scheduled on purpose (``_deliberate_memory_hold``), so a genuine deadlock still surfaces with an error. With memory scheduling off - the clock is upstream's: ``_MEMORY_ADMISSION_STALL_TIMEOUT_S`` from - when the head first blocked. + and no park hold (``_progress_clock_on``) the clock is upstream's: + ``_MEMORY_ADMISSION_STALL_TIMEOUT_S`` from when the head first + blocked. """ if not self.waiting: self._clear_memory_admission_blocker() @@ -6153,7 +6176,7 @@ def _memory_admission_stall_output(self, reason: str) -> RequestOutput | None: # client's own timeouts apply. self._clear_memory_admission_blocker(request_id) return None - progress_clock = self._memory_scheduling_on() + progress_clock = self._progress_clock_on() now = time.monotonic() if request_id != self._memory_admission_blocked_request_id: self._memory_admission_blocked_request_id = request_id @@ -6243,7 +6266,7 @@ def _store_cache_admission_stall_output( if request.parked: self._clear_store_cache_admission_blocker(request_id) return None - progress_clock = self._memory_scheduling_on() + progress_clock = self._progress_clock_on() now = time.monotonic() if request_id != self._store_cache_admission_blocked_request_id: self._store_cache_admission_blocked_request_id = request_id @@ -6253,8 +6276,8 @@ def _store_cache_admission_stall_output( return None # Backpressure, not a failure, while the writer drains (a drained - # write is progress) or other requests progress. Memory scheduling - # off: upstream's fixed timeout from when the head first blocked. + # write is progress) or other requests progress. Without the progress + # clock: upstream's fixed timeout from when the head first blocked. timeout = getattr( self, "_STORE_CACHE_ADMISSION_STALL_TIMEOUT_S", diff --git a/tests/test_memory_scheduling_gate.py b/tests/test_memory_scheduling_gate.py index bb38ea3efd..414ec5c0f0 100644 --- a/tests/test_memory_scheduling_gate.py +++ b/tests/test_memory_scheduling_gate.py @@ -325,14 +325,38 @@ def test_off_uses_the_fixed_stall_timeout(pressured, clock): assert f"persisted for {timeout:.1f}s (admission_paused). " in failed.error -def test_off_has_no_long_bound_for_deliberate_holds(pressured, clock): +def test_off_without_park_has_no_long_bound_for_a_solo_mark(pressured, clock): + """Park off: no park hold exists, so the clock stays upstream's.""" scheduler, _head, solo = pressured scheduler._memory_scheduling = False - scheduler._solo_request_id = solo.request_id # a parked head resumed solo + assert scheduler._park_enabled() is False + scheduler._solo_request_id = solo.request_id assert _schedule(scheduler) == [] clock.advance(scheduler._MEMORY_ADMISSION_STALL_TIMEOUT_S) (failed,) = _schedule(scheduler) assert failed.error_metadata["reason"] == "solo_hold" + assert "no_progress_seconds" not in failed.error_metadata + + +def test_off_with_park_a_parked_solo_keeps_the_progress_clock(pressured, clock): + """Park on: a parked head resumed solo is a hold the park feature created, + so the head behind it waits while the solo request progresses (the + progress clock and its 600 s bound) whatever memory_scheduling says.""" + scheduler, _head, solo = pressured + scheduler._memory_scheduling = False + scheduler.config.memory_pressure_park = True + scheduler._solo_request_id = solo.request_id + assert _schedule(scheduler) == [] + for _ in range(3): + clock.advance(scheduler._MEMORY_ADMISSION_STALL_TIMEOUT_S - 1) + scheduler._note_admission_progress() # the solo request emits a token + assert _schedule(scheduler) == [] + clock.advance(scheduler.config.admission_no_progress_timeout_s) + (failed,) = _schedule(scheduler) + assert failed.error_metadata["reason"] == "solo_hold" + assert failed.error_metadata["no_progress_seconds"] == int( + scheduler.config.admission_no_progress_timeout_s + ) def test_off_store_cache_backpressure_uses_the_fixed_timeout( diff --git a/tests/test_scheduler_admission_progress.py b/tests/test_scheduler_admission_progress.py index 62116cc503..1d3a698028 100644 --- a/tests/test_scheduler_admission_progress.py +++ b/tests/test_scheduler_admission_progress.py @@ -215,6 +215,78 @@ async def test_three_requests_that_fit_one_at_a_time_complete_without_a_stall( rig.close() +@pytest.mark.asyncio +async def test_a_head_behind_a_parked_solo_waits_with_memory_scheduling_off( + tmp_path, mock_engine_pool, clock, monkeypatch, caplog # noqa: F811 +): + """Park on, memory scheduling off (no explicit ceiling). A request paused + twice while alone resumes as the solo request (park only). The head + queued behind it must wait while the solo request emits tokens: the + fixed 60 s clock failed it in the forced-pressure run, although the + server progressed.""" + prompts = {"a": dp.PROMPT, "b": dp.OTHER} + expected = _baseline(tmp_path, prompts) + enforcer = _make_enforcer( + mock_engine_pool, + ceiling=100 * GB, + soft_threshold=0.85, + hard_threshold=0.95, + memory_scheduling="off", + ) + rig = park._Rig( + tmp_path / "solo-off", + dp._tokenizer(), + split=False, + commit_blocks=1, + max_blocks=dp.MAX_BLOCKS, + memory_pressure_park=True, + ) + try: + scheduler = rig.scheduler + scheduler.note_pressure_poll("soft") + engine = _rig_engine(rig) + _busy(enforcer, engine) + rows = [_submit(rig, "a", dp.PROMPT, 1.0)] + outputs = [] + + async def advance(gb=90): + await tick(enforcer, gb) + outputs.extend(park.step(rig)) + clock.advance(STEP_S) + + async def until(predicate, limit=60): + for _ in range(limit): + if predicate(): + return + await advance() + raise AssertionError("condition not reached") + + # a decodes; two pauses while it is alone make it the solo request. + await until(lambda: "a" in scheduler.running and rows[0].output_token_ids) + for pauses in (1, 2): + assert scheduler.request_decode_pause("a") is True + await until(lambda n=pauses: rows[0].park_count == n) + await until(lambda: "a" in scheduler.running) + assert scheduler._memory_scheduling is False + assert scheduler._solo_request_id == "a" + assert len(rows[0].output_token_ids) < MAX_TOKENS - 35 # > 70 s left + + rows.append(_submit(rig, "b", dp.OTHER, 2.0)) + with caplog.at_level(logging.INFO, logger="omlx.scheduler"): + await until(lambda: _finished(rows, outputs), limit=12 * MAX_TOKENS) + + assert [o for o in outputs if o.error] == [] + engine.abort_one_request_for_memory.assert_not_awaited() + engine.abort_all_requests.assert_not_awaited() + for row in rows: + rid = row.request_id + assert list(row.output_token_ids) == expected[rid] + assert dp.streamed_tokens(outputs, rid) == expected[rid] + assert "Admission waiting for memory: solo_hold" in caplog.text + finally: + rig.close() + + @pytest.mark.asyncio async def test_a_queued_request_still_fails_when_nothing_progresses( tmp_path, enforcer, clock, monkeypatch From 5de0dcbd31331e34e15f4398c5040d0c73984d6d Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Wed, 7 Oct 2026 20:35:18 -0600 Subject: [PATCH 44/46] fix(memory): count the releasable hot cache in the never-fits gate Upstream's route preflight credits the hot cache a request would release (#4252), and the in-stream eviction ladder releases it, so main admits and runs a request the hot cache can make room for. The never-fits gate compared the request against the capacity line without that credit and answered with a permanent 400 (retryable: false) for the same request. The gate checks (route preflight, the eviction request and the in-stream admission) now count the same credit when a request is over the line otherwise, with the request's own prefix bounded by the exact KV of its context, as upstream does. The 400 body, the capacity endpoint and the X-oMLX-Max-Context-Tokens header stay credit-free. With memory scheduling off there is no capacity estimate and nothing changes. --- docs/TESTING.md | 2 +- omlx/scheduler.py | 40 ++++++++++-- tests/test_scheduler_capacity_gate.py | 87 +++++++++++++++++++++++++++ 3 files changed, 124 insertions(+), 5 deletions(-) diff --git a/docs/TESTING.md b/docs/TESTING.md index 9adeb6fdc5..2bd222c55d 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -243,7 +243,7 @@ Run `python -m pytest -q tests/test_memory_scheduling_admin_state.py` to check m # Never-fits gate tests -Run `python -m pytest -q tests/test_scheduler_capacity_gate.py tests/test_scheduler_capacity_vlm.py tests/test_scheduler_deferred_admission.py tests/test_scheduler_solo_admission.py tests/test_scheduler_lone_head_after_wait.py tests/test_server_context_capacity.py` to check the feasibility gate. A request whose weights + exact KV of prompt plus `max_tokens` + prefill transient exceed the capacity line (the tighter of the admission line and the prefill safety cap) is rejected with `ContextExceedsCapacityError` (HTTP 400, `omlx_code: context_exceeds_capacity`, the byte and token fields, `retryable: false`) whatever the current usage. One that fits alone but not now is not rejected: the route preflight lets it queue while other work is admitted (queued requests hold no memory and do not count), and the in-stream admission keeps it at the head (nothing overtakes it) until the admitted rows free memory; both checks share one predicate. The same wait applies while the store-cache pipeline still owns a finished request's KV (the gate's in-flight count or a pending deferred remove): right after a request finishes that memory is still in the usage reading, and it comes back when the write drains. With nothing admitted, a head that fits alone and is over the admission line or the prefill safety cap first returns the pooled Metal buffers on the scheduler thread and is re-measured before any decision, because the reading can lag a finished request's release. Eviction retries spent while a head waits (fits-later, or parked) do not count against its next attempt: the budget renews when a row it waited on leaves, a store write it waited on drains, or a park resumes; a retry on backoff beside the same rows keeps the spent budget. `tests/test_scheduler_lone_head_after_wait.py` replays the stale-reading case on the real scheduler loop (a stand-in for the engine pool's eviction ladder frees what the ladder can free when it runs, and the real async store worker is held mid-write): the head spends both retries beside an admitted row, the row finishes, the reading stays stale until an eviction runs, and the head completes; behind a held store write it waits (nothing overtakes it, not retried every step) and runs once the write drains; with nothing admitted, nothing draining and nothing reclaimed, the older rejection still applies. With nothing admitted, a head that fits alone but whose peak priced on the current usage (which also holds memory no admitted request owns, such as queued requests' vision embeddings) lands between the admission line and the solo line (the ceiling and prefill safety cap minus 2%) runs alone, as a parked head does: `Admitting request alone (solo)`, nothing is admitted beside it, and the route preflight lets it queue. Over the solo line, or with the park feature off, the older rejection applies. The solo-admission cases drive the real scheduler loop with the admission line set by a hard watermark under the ceiling. A deferred request releases its restored prefix and its block-table refs while it waits, and its re-admission repeats the lookup. The block-table release can wait behind an in-flight prefill commit; it is keyed to the deferred attempt's table, so it never frees a table the request got since. The deferred head is not retried (and its prefix not restored again) on every step: it retries once an admitted row left (finished, aborted or paused), a store write it waited on drained, free memory rose by more than 2% of the admission line, or its backoff expired (0.25 s doubling per deferral, capped at 4 s); it keeps the head-of-line hold meanwhile, also while its release still waits behind a commit. Both checks price the same output budget: the route preflight uses the resolved `max_tokens` (request, model setting or server default; the engine default when an engine is called directly). With nothing admitted and no store write pending, or when the capacity cannot be estimated (no memory limit, unknown weights or KV dimensions), the older current-usage rejection applies; unknown weights are never cached and never produce a never-fits rejection. The server cases cover the 400 body on API and non-API routes, `GET /v1/omlx/capacity` (fields, 404/409, auth) and the `X-oMLX-Max-Context-Tokens` header on streaming and non-streaming chat completions. `tests/test_scheduler_capacity_vlm.py` builds a tiny real mlx-vlm Qwen3.5 model (vision tower plus hybrid language model) behind the real `VLMModelAdapter`: the adapter keeps the model in `_vlm_model`, which `nn.Module.parameters()` skips, so the weights are summed from the unwrapped model, each array once. It checks the capacity of that model and of the text model on the batched engine, that `kv_bytes_per_token` prices the TurboQuant prefill peak (full-width KV plus the quantized copy, the last full-attention layer kept full width when there is more than one), that quantized weights count their scales and biases, and that `max_tokens` 2,000,000 reaches the gate unclamped (no route clamps `max_tokens` to the context window) and is rejected as never-fits. These cases run with memory scheduling on (see the memory scheduling gate tests above); off, there is no capacity estimate and the older current-usage rejection applies. +Run `python -m pytest -q tests/test_scheduler_capacity_gate.py tests/test_scheduler_capacity_vlm.py tests/test_scheduler_deferred_admission.py tests/test_scheduler_solo_admission.py tests/test_scheduler_lone_head_after_wait.py tests/test_server_context_capacity.py` to check the feasibility gate. A request whose weights + exact KV of prompt plus `max_tokens` + prefill transient exceed the capacity line (the tighter of the admission line and the prefill safety cap) is rejected with `ContextExceedsCapacityError` (HTTP 400, `omlx_code: context_exceeds_capacity`, the byte and token fields, `retryable: false`) whatever the current usage. One that fits alone but not now is not rejected: the route preflight lets it queue while other work is admitted (queued requests hold no memory and do not count), and the in-stream admission keeps it at the head (nothing overtakes it) until the admitted rows free memory; both checks share one predicate. The same wait applies while the store-cache pipeline still owns a finished request's KV (the gate's in-flight count or a pending deferred remove): right after a request finishes that memory is still in the usage reading, and it comes back when the write drains. With nothing admitted, a head that fits alone and is over the admission line or the prefill safety cap first returns the pooled Metal buffers on the scheduler thread and is re-measured before any decision, because the reading can lag a finished request's release. Eviction retries spent while a head waits (fits-later, or parked) do not count against its next attempt: the budget renews when a row it waited on leaves, a store write it waited on drains, or a park resumes; a retry on backoff beside the same rows keeps the spent budget. `tests/test_scheduler_lone_head_after_wait.py` replays the stale-reading case on the real scheduler loop (a stand-in for the engine pool's eviction ladder frees what the ladder can free when it runs, and the real async store worker is held mid-write): the head spends both retries beside an admitted row, the row finishes, the reading stays stale until an eviction runs, and the head completes; behind a held store write it waits (nothing overtakes it, not retried every step) and runs once the write drains; with nothing admitted, nothing draining and nothing reclaimed, the older rejection still applies. With nothing admitted, a head that fits alone but whose peak priced on the current usage (which also holds memory no admitted request owns, such as queued requests' vision embeddings) lands between the admission line and the solo line (the ceiling and prefill safety cap minus 2%) runs alone, as a parked head does: `Admitting request alone (solo)`, nothing is admitted beside it, and the route preflight lets it queue. Over the solo line, or with the park feature off, the older rejection applies. The solo-admission cases drive the real scheduler loop with the admission line set by a hard watermark under the ceiling. A deferred request releases its restored prefix and its block-table refs while it waits, and its re-admission repeats the lookup. The block-table release can wait behind an in-flight prefill commit; it is keyed to the deferred attempt's table, so it never frees a table the request got since. The deferred head is not retried (and its prefix not restored again) on every step: it retries once an admitted row left (finished, aborted or paused), a store write it waited on drained, free memory rose by more than 2% of the admission line, or its backoff expired (0.25 s doubling per deferral, capped at 4 s); it keeps the head-of-line hold meanwhile, also while its release still waits behind a commit. Both checks price the same output budget: the route preflight uses the resolved `max_tokens` (request, model setting or server default; the engine default when an engine is called directly). With nothing admitted and no store write pending, or when the capacity cannot be estimated (no memory limit, unknown weights or KV dimensions), the older current-usage rejection applies; unknown weights are never cached and never produce a never-fits rejection. The gate checks (route preflight, eviction request, in-stream admission) count the hot cache that would be released for the request, the credit upstream's route preflight counts (#4252), so a request the hot cache can make room for is not a never-fits 400; the 400 body, the capacity endpoint and the header stay credit-free. The server cases cover the 400 body on API and non-API routes, `GET /v1/omlx/capacity` (fields, 404/409, auth) and the `X-oMLX-Max-Context-Tokens` header on streaming and non-streaming chat completions. `tests/test_scheduler_capacity_vlm.py` builds a tiny real mlx-vlm Qwen3.5 model (vision tower plus hybrid language model) behind the real `VLMModelAdapter`: the adapter keeps the model in `_vlm_model`, which `nn.Module.parameters()` skips, so the weights are summed from the unwrapped model, each array once. It checks the capacity of that model and of the text model on the batched engine, that `kv_bytes_per_token` prices the TurboQuant prefill peak (full-width KV plus the quantized copy, the last full-attention layer kept full width when there is more than one), that quantized weights count their scales and biases, and that `max_tokens` 2,000,000 reaches the gate unclamped (no route clamps `max_tokens` to the context window) and is rejected as never-fits. These cases run with memory scheduling on (see the memory scheduling gate tests above); off, there is no capacity estimate and the older current-usage rejection applies. Mocked tests do not replace hardware validation: with a real model, send a prompt larger than `max_viable_context_tokens` and check for an immediate 400 with the fields, then send two prompts that each fit alone but not together and check that the second waits and completes without an error. diff --git a/omlx/scheduler.py b/omlx/scheduler.py index fb71ea8658..9bc74eacd7 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -224,9 +224,11 @@ class _CapacityEstimate: ``required_bytes`` is weights + exact KV of context plus max_tokens + the prefill transient, compared against ``capacity_bytes`` (the tighter - of the admission line and the prefill safety cap). + of the admission line and the prefill safety cap) plus + ``hot_cache_credit_bytes``, the hot cache that would be released for the + request (#4252; only the gate checks count it, never the hint). ``max_viable_context_tokens`` is the largest context plus max_tokens - that fits alone. + that fits alone without that credit. """ required_bytes: int @@ -236,10 +238,11 @@ class _CapacityEstimate: requested_context_tokens: int requested_max_tokens: int max_viable_context_tokens: int + hot_cache_credit_bytes: int = 0 @property def fits_alone(self) -> bool: - return self.required_bytes <= self.capacity_bytes + return self.required_bytes - self.hot_cache_credit_bytes <= self.capacity_bytes def fields(self) -> dict[str, int]: return { @@ -14322,6 +14325,7 @@ def _preflight_memory_check( capacity = self._capacity_estimate( context_tokens=prompt_tokens, max_tokens=getattr(request.sampling_params, "max_tokens", 0), + count_hot_cache=True, ) if capacity is not None and not capacity.fits_alone: return _PreflightRejection( @@ -14848,11 +14852,27 @@ def _required_alone_bytes(self, tokens: int, weights: int) -> int: ) return int(est.estimated) if est is not None else int(weights) + def _capacity_hot_cache_credit(self, context_tokens: int) -> int: + """Hot cache released for a request of ``context_tokens``. + + Upstream's route preflight credit (#4252), with the request's own + prefix bounded by the exact KV of its whole context, as there. + """ + est = self._admission_estimate( + num_prompt_tokens=context_tokens, cached_tokens=0, current=0 + ) + own_prefix = int(est.kv_exact) if est is not None else 0 + try: + return max(0, int(self._releasable_hot_cache_credit(own_prefix))) + except Exception: # noqa: BLE001 - no credit is the strict answer + return 0 + def _capacity_estimate( self, *, context_tokens: int, max_tokens: int | None, + count_hot_cache: bool = False, ) -> _CapacityEstimate | None: """Whether ``context_tokens + max_tokens`` fits with nothing else running. @@ -14860,6 +14880,11 @@ def _capacity_estimate( weights or KV dimensions unknown, or memory scheduling off. Without an estimate there is no never-fits error, no fits-later wait, no solo admission and no capacity hint: the upstream current-usage preflight. + + ``count_hot_cache`` (the gate checks) credits the hot cache that would + be released for the request when it is over the line otherwise, the + same credit upstream's route preflight counts (#4252), so a request + the hot cache can make room for is never a permanent never-fits 400. """ if not self._memory_scheduling_on(): return None @@ -14881,8 +14906,13 @@ def _capacity_estimate( return None context = max(0, int(context_tokens or 0)) output = max(0, int(max_tokens or 0)) + required = self._required_alone_bytes(context + output, weights) + credit = 0 + if count_hot_cache and required > capacity: + credit = self._capacity_hot_cache_credit(context) return _CapacityEstimate( - required_bytes=self._required_alone_bytes(context + output, weights), + required_bytes=required, + hot_cache_credit_bytes=credit, capacity_bytes=capacity, weights_bytes=weights, kv_bytes_per_token=int( @@ -15049,6 +15079,7 @@ def preflight_or_raise( capacity = self._capacity_estimate( context_tokens=num_prompt_tokens, max_tokens=max_tokens, + count_hot_cache=True, ) if capacity is not None and not capacity.fits_alone: message = self._never_fits_message(capacity) @@ -15163,6 +15194,7 @@ def preflight_eviction_request( capacity = self._capacity_estimate( context_tokens=num_prompt_tokens, max_tokens=max_tokens, + count_hot_cache=True, ) if capacity is not None and not capacity.fits_alone: return None # evicting cannot help; preflight_or_raise rejects it diff --git a/tests/test_scheduler_capacity_gate.py b/tests/test_scheduler_capacity_gate.py index 31cfcb0f37..b59bb11b0f 100644 --- a/tests/test_scheduler_capacity_gate.py +++ b/tests/test_scheduler_capacity_gate.py @@ -247,6 +247,93 @@ def test_a_never_fits_request_does_not_ask_for_an_eviction(gated): ) +# --- Hot-cache credit (#4252) --------------------------------------------------- + + +def _over_by(scheduler, extra_tokens=20_000): + """A context over the max viable one and the bytes it is over by.""" + context = scheduler.max_viable_context_tokens() + extra_tokens + cap = scheduler._capacity_estimate(context_tokens=context, max_tokens=0) + assert not cap.fits_alone + return context, cap.required_bytes - cap.capacity_bytes + + +def _hot_cache_credit(monkeypatch, scheduler, credit): + seen = [] + + def credit_fn(own_prefix_bytes): + seen.append(own_prefix_bytes) + return credit + + monkeypatch.setattr(scheduler, "_releasable_hot_cache_credit", credit_fn) + return seen + + +def test_never_fits_counts_the_releasable_hot_cache(gated, monkeypatch): + """Upstream's route preflight admits a request the hot cache can make + room for (#4252), so it is not a permanent never-fits 400.""" + scheduler, _usage, _admitted = gated + context, over = _over_by(scheduler) + seen = _hot_cache_credit(monkeypatch, scheduler, over + GB) + scheduler.preflight_or_raise(num_prompt_tokens=context, max_tokens=0) + # The request's own cached prefix stays protected, as in upstream. + assert seen and all(own > 0 for own in seen) + + +def test_never_fits_beyond_the_hot_cache_credit_is_still_rejected(gated, monkeypatch): + scheduler, _usage, _admitted = gated + context, over = _over_by(scheduler) + _hot_cache_credit(monkeypatch, scheduler, over // 2) + with pytest.raises(ContextExceedsCapacityError) as info: + scheduler.preflight_or_raise(num_prompt_tokens=context, max_tokens=0) + # The 400 body keeps the credit-free numbers. + fields = info.value.capacity_fields + assert fields["required_bytes"] - fields["capacity_bytes"] == over + + +def test_in_stream_never_fits_counts_the_releasable_hot_cache(gated, monkeypatch): + """The in-stream check must not reject what the route preflight let in.""" + scheduler, _usage, _admitted = gated + context, over = _over_by(scheduler) + request = _make_request(context) + request.sampling_params.max_tokens = 0 + _hot_cache_credit(monkeypatch, scheduler, over // 2) + rejection = scheduler._preflight_memory_check(request) + assert rejection is not None and rejection.capacity is not None + _hot_cache_credit(monkeypatch, scheduler, over + GB) + rejection = scheduler._preflight_memory_check(request) + assert rejection is None or rejection.capacity is None + + +def test_eviction_request_is_priced_when_the_hot_cache_makes_it_fit(gated, monkeypatch): + scheduler, usage, _admitted = gated + context, over = _over_by(scheduler) + usage[0] = 99 * GB + _hot_cache_credit(monkeypatch, scheduler, over // 2) + assert ( + scheduler.preflight_eviction_request(num_prompt_tokens=context, max_tokens=0) + is None + ) + _hot_cache_credit(monkeypatch, scheduler, over + GB) + assert ( + scheduler.preflight_eviction_request(num_prompt_tokens=context, max_tokens=0) + is not None + ) + + +def test_capacity_hint_does_not_count_the_hot_cache(gated, monkeypatch): + """The header and endpoint stay a static, credit-free bound.""" + scheduler, _usage, _admitted = gated + first = scheduler.max_viable_context_tokens() + scheduler._max_viable_cache = None + _hot_cache_credit(monkeypatch, scheduler, 50 * GB) + assert scheduler.max_viable_context_tokens() == first + assert ( + scheduler.capacity_snapshot(context_tokens=first + 20_000)["required_bytes"] + > scheduler.capacity_snapshot()["capacity_bytes"] + ) + + # --- In-stream admission -------------------------------------------------------- From f0dfe4e8306e01391229dcd6b0fd07ab2a3b3f60 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Wed, 7 Oct 2026 21:06:56 -0600 Subject: [PATCH 45/46] fix(memory): raise the never-fits line by the hot cache instead of crediting the request The never-fits gate subtracted the releasable hot cache from the request's required bytes, while max_viable_context_tokens and the 400 body were priced against the credit-free line. One estimate could say fits_alone above its own max viable context, and the 400 named a boundary the gate did not use. The credit belongs on the line: the scheduler's limits are the ceiling minus the hot-cache reservation, and upstream's eviction ladder releases cold blocks and raises them (#4252), so main runs a request the released hot cache makes room for. The gate estimate now carries capacity_bytes = line + credit (the request's own prefix still protected), fits_alone compares required_bytes with it alone, and max_viable_context_tokens is searched under the same line. The 400 message names the credited hot cache. The capacity endpoint and the header stay credit-free; the current-usage checks keep main's credit. --- docs/TESTING.md | 2 +- omlx/scheduler.py | 45 +++++++----- tests/test_scheduler_capacity_gate.py | 99 ++++++++++++++++++++++++++- 3 files changed, 127 insertions(+), 19 deletions(-) diff --git a/docs/TESTING.md b/docs/TESTING.md index 2bd222c55d..4da7cbbe63 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -243,7 +243,7 @@ Run `python -m pytest -q tests/test_memory_scheduling_admin_state.py` to check m # Never-fits gate tests -Run `python -m pytest -q tests/test_scheduler_capacity_gate.py tests/test_scheduler_capacity_vlm.py tests/test_scheduler_deferred_admission.py tests/test_scheduler_solo_admission.py tests/test_scheduler_lone_head_after_wait.py tests/test_server_context_capacity.py` to check the feasibility gate. A request whose weights + exact KV of prompt plus `max_tokens` + prefill transient exceed the capacity line (the tighter of the admission line and the prefill safety cap) is rejected with `ContextExceedsCapacityError` (HTTP 400, `omlx_code: context_exceeds_capacity`, the byte and token fields, `retryable: false`) whatever the current usage. One that fits alone but not now is not rejected: the route preflight lets it queue while other work is admitted (queued requests hold no memory and do not count), and the in-stream admission keeps it at the head (nothing overtakes it) until the admitted rows free memory; both checks share one predicate. The same wait applies while the store-cache pipeline still owns a finished request's KV (the gate's in-flight count or a pending deferred remove): right after a request finishes that memory is still in the usage reading, and it comes back when the write drains. With nothing admitted, a head that fits alone and is over the admission line or the prefill safety cap first returns the pooled Metal buffers on the scheduler thread and is re-measured before any decision, because the reading can lag a finished request's release. Eviction retries spent while a head waits (fits-later, or parked) do not count against its next attempt: the budget renews when a row it waited on leaves, a store write it waited on drains, or a park resumes; a retry on backoff beside the same rows keeps the spent budget. `tests/test_scheduler_lone_head_after_wait.py` replays the stale-reading case on the real scheduler loop (a stand-in for the engine pool's eviction ladder frees what the ladder can free when it runs, and the real async store worker is held mid-write): the head spends both retries beside an admitted row, the row finishes, the reading stays stale until an eviction runs, and the head completes; behind a held store write it waits (nothing overtakes it, not retried every step) and runs once the write drains; with nothing admitted, nothing draining and nothing reclaimed, the older rejection still applies. With nothing admitted, a head that fits alone but whose peak priced on the current usage (which also holds memory no admitted request owns, such as queued requests' vision embeddings) lands between the admission line and the solo line (the ceiling and prefill safety cap minus 2%) runs alone, as a parked head does: `Admitting request alone (solo)`, nothing is admitted beside it, and the route preflight lets it queue. Over the solo line, or with the park feature off, the older rejection applies. The solo-admission cases drive the real scheduler loop with the admission line set by a hard watermark under the ceiling. A deferred request releases its restored prefix and its block-table refs while it waits, and its re-admission repeats the lookup. The block-table release can wait behind an in-flight prefill commit; it is keyed to the deferred attempt's table, so it never frees a table the request got since. The deferred head is not retried (and its prefix not restored again) on every step: it retries once an admitted row left (finished, aborted or paused), a store write it waited on drained, free memory rose by more than 2% of the admission line, or its backoff expired (0.25 s doubling per deferral, capped at 4 s); it keeps the head-of-line hold meanwhile, also while its release still waits behind a commit. Both checks price the same output budget: the route preflight uses the resolved `max_tokens` (request, model setting or server default; the engine default when an engine is called directly). With nothing admitted and no store write pending, or when the capacity cannot be estimated (no memory limit, unknown weights or KV dimensions), the older current-usage rejection applies; unknown weights are never cached and never produce a never-fits rejection. The gate checks (route preflight, eviction request, in-stream admission) count the hot cache that would be released for the request, the credit upstream's route preflight counts (#4252), so a request the hot cache can make room for is not a never-fits 400; the 400 body, the capacity endpoint and the header stay credit-free. The server cases cover the 400 body on API and non-API routes, `GET /v1/omlx/capacity` (fields, 404/409, auth) and the `X-oMLX-Max-Context-Tokens` header on streaming and non-streaming chat completions. `tests/test_scheduler_capacity_vlm.py` builds a tiny real mlx-vlm Qwen3.5 model (vision tower plus hybrid language model) behind the real `VLMModelAdapter`: the adapter keeps the model in `_vlm_model`, which `nn.Module.parameters()` skips, so the weights are summed from the unwrapped model, each array once. It checks the capacity of that model and of the text model on the batched engine, that `kv_bytes_per_token` prices the TurboQuant prefill peak (full-width KV plus the quantized copy, the last full-attention layer kept full width when there is more than one), that quantized weights count their scales and biases, and that `max_tokens` 2,000,000 reaches the gate unclamped (no route clamps `max_tokens` to the context window) and is rejected as never-fits. These cases run with memory scheduling on (see the memory scheduling gate tests above); off, there is no capacity estimate and the older current-usage rejection applies. +Run `python -m pytest -q tests/test_scheduler_capacity_gate.py tests/test_scheduler_capacity_vlm.py tests/test_scheduler_deferred_admission.py tests/test_scheduler_solo_admission.py tests/test_scheduler_lone_head_after_wait.py tests/test_server_context_capacity.py` to check the feasibility gate. A request whose weights + exact KV of prompt plus `max_tokens` + prefill transient exceed the capacity line (the tighter of the admission line and the prefill safety cap) is rejected with `ContextExceedsCapacityError` (HTTP 400, `omlx_code: context_exceeds_capacity`, the byte and token fields, `retryable: false`) whatever the current usage. One that fits alone but not now is not rejected: the route preflight lets it queue while other work is admitted (queued requests hold no memory and do not count), and the in-stream admission keeps it at the head (nothing overtakes it) until the admitted rows free memory; both checks share one predicate. The same wait applies while the store-cache pipeline still owns a finished request's KV (the gate's in-flight count or a pending deferred remove): right after a request finishes that memory is still in the usage reading, and it comes back when the write drains. With nothing admitted, a head that fits alone and is over the admission line or the prefill safety cap first returns the pooled Metal buffers on the scheduler thread and is re-measured before any decision, because the reading can lag a finished request's release. Eviction retries spent while a head waits (fits-later, or parked) do not count against its next attempt: the budget renews when a row it waited on leaves, a store write it waited on drains, or a park resumes; a retry on backoff beside the same rows keeps the spent budget. `tests/test_scheduler_lone_head_after_wait.py` replays the stale-reading case on the real scheduler loop (a stand-in for the engine pool's eviction ladder frees what the ladder can free when it runs, and the real async store worker is held mid-write): the head spends both retries beside an admitted row, the row finishes, the reading stays stale until an eviction runs, and the head completes; behind a held store write it waits (nothing overtakes it, not retried every step) and runs once the write drains; with nothing admitted, nothing draining and nothing reclaimed, the older rejection still applies. With nothing admitted, a head that fits alone but whose peak priced on the current usage (which also holds memory no admitted request owns, such as queued requests' vision embeddings) lands between the admission line and the solo line (the ceiling and prefill safety cap minus 2%) runs alone, as a parked head does: `Admitting request alone (solo)`, nothing is admitted beside it, and the route preflight lets it queue. Over the solo line, or with the park feature off, the older rejection applies. The solo-admission cases drive the real scheduler loop with the admission line set by a hard watermark under the ceiling. A deferred request releases its restored prefix and its block-table refs while it waits, and its re-admission repeats the lookup. The block-table release can wait behind an in-flight prefill commit; it is keyed to the deferred attempt's table, so it never frees a table the request got since. The deferred head is not retried (and its prefix not restored again) on every step: it retries once an admitted row left (finished, aborted or paused), a store write it waited on drained, free memory rose by more than 2% of the admission line, or its backoff expired (0.25 s doubling per deferral, capped at 4 s); it keeps the head-of-line hold meanwhile, also while its release still waits behind a commit. Both checks price the same output budget: the route preflight uses the resolved `max_tokens` (request, model setting or server default; the engine default when an engine is called directly). With nothing admitted and no store write pending, or when the capacity cannot be estimated (no memory limit, unknown weights or KV dimensions), the older current-usage rejection applies; unknown weights are never cached and never produce a never-fits rejection. The capacity line subtracts the hot-cache reservation, and upstream's eviction ladder releases cold hot-cache blocks and raises it (#4252), so the gate checks (route preflight, eviction request, in-stream admission) raise the line by the hot cache that would be released for the request (its own prefix stays protected): a request that released hot cache makes room for is not a never-fits 400, and one over the raised line is, whatever hot cache is resident. The 400 body reports that raised line and the largest context plus `max_tokens` under it, so its numbers agree with the decision; the capacity endpoint and the header stay credit-free (a static bound). With memory scheduling on, the current-usage checks keep main's hot-cache credit. The server cases cover the 400 body on API and non-API routes, `GET /v1/omlx/capacity` (fields, 404/409, auth) and the `X-oMLX-Max-Context-Tokens` header on streaming and non-streaming chat completions. `tests/test_scheduler_capacity_vlm.py` builds a tiny real mlx-vlm Qwen3.5 model (vision tower plus hybrid language model) behind the real `VLMModelAdapter`: the adapter keeps the model in `_vlm_model`, which `nn.Module.parameters()` skips, so the weights are summed from the unwrapped model, each array once. It checks the capacity of that model and of the text model on the batched engine, that `kv_bytes_per_token` prices the TurboQuant prefill peak (full-width KV plus the quantized copy, the last full-attention layer kept full width when there is more than one), that quantized weights count their scales and biases, and that `max_tokens` 2,000,000 reaches the gate unclamped (no route clamps `max_tokens` to the context window) and is rejected as never-fits. These cases run with memory scheduling on (see the memory scheduling gate tests above); off, there is no capacity estimate and the older current-usage rejection applies. Mocked tests do not replace hardware validation: with a real model, send a prompt larger than `max_viable_context_tokens` and check for an immediate 400 with the fields, then send two prompts that each fit alone but not together and check that the second waits and completes without an error. diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 9bc74eacd7..e34712a282 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -223,12 +223,14 @@ class _CapacityEstimate: """Whether a request fits this model's memory with nothing else running. ``required_bytes`` is weights + exact KV of context plus max_tokens + - the prefill transient, compared against ``capacity_bytes`` (the tighter - of the admission line and the prefill safety cap) plus - ``hot_cache_credit_bytes``, the hot cache that would be released for the - request (#4252; only the gate checks count it, never the hint). - ``max_viable_context_tokens`` is the largest context plus max_tokens - that fits alone without that credit. + the prefill transient, compared against ``capacity_bytes``: the tighter + of the admission line and the prefill safety cap, raised by + ``hot_cache_credit_bytes`` in the gate checks. Those lines subtract the + hot-cache reservation and rise as the eviction ladder releases cold + blocks (#4252), so the gate credits what would be released for the + request; the hint never does. ``max_viable_context_tokens`` is the + largest context plus max_tokens that fits under that same + ``capacity_bytes``, so it always agrees with ``fits_alone``. """ required_bytes: int @@ -242,7 +244,7 @@ class _CapacityEstimate: @property def fits_alone(self) -> bool: - return self.required_bytes - self.hot_cache_credit_bytes <= self.capacity_bytes + return self.required_bytes <= self.capacity_bytes def fields(self) -> dict[str, int]: return { @@ -14881,19 +14883,22 @@ def _capacity_estimate( an estimate there is no never-fits error, no fits-later wait, no solo admission and no capacity hint: the upstream current-usage preflight. - ``count_hot_cache`` (the gate checks) credits the hot cache that would - be released for the request when it is over the line otherwise, the - same credit upstream's route preflight counts (#4252), so a request - the hot cache can make room for is never a permanent never-fits 400. + ``count_hot_cache`` (the gate checks) raises the capacity line by the + hot cache that would be released for the request when it is over the + line otherwise. The line subtracts the hot-cache reservation, and + upstream's eviction ladder releases cold blocks and raises it (#4252), + so a request the released hot cache makes room for is never a + permanent never-fits 400. The 400 body reports that raised line and + the max viable context under it. """ if not self._memory_scheduling_on(): return None monitor = self.memory_monitor if monitor is None: return None - capacity = self._capacity_limit_bytes() + line = self._capacity_limit_bytes() weights = self._model_weights_bytes() - if capacity <= 0 or weights <= 0: + if line <= 0 or weights <= 0: return None if ( self._admission_estimate( @@ -14908,8 +14913,9 @@ def _capacity_estimate( output = max(0, int(max_tokens or 0)) required = self._required_alone_bytes(context + output, weights) credit = 0 - if count_hot_cache and required > capacity: + if count_hot_cache and required > line: credit = self._capacity_hot_cache_credit(context) + capacity = line + credit return _CapacityEstimate( required_bytes=required, hot_cache_credit_bytes=credit, @@ -15009,14 +15015,21 @@ def _never_fits_message(self, capacity: _CapacityEstimate) -> str: fmt=format_bytes, tail=["compact or shorten the context", "lower max_tokens"], ) + hot_cache = ( + f" (including {format_bytes(capacity.hot_cache_credit_bytes)} of " + "hot cache it would release)" + if capacity.hot_cache_credit_bytes > 0 + else "" + ) return ( f"Request needs ~{format_bytes(capacity.required_bytes)} " f"(weights {format_bytes(capacity.weights_bytes)} + KV and " f"transient for {capacity.requested_context_tokens} context + " f"{capacity.requested_max_tokens} max tokens) but this model's " f"memory capacity under the {binding_str} ceiling is " - f"{format_bytes(capacity.capacity_bytes)} even with nothing else " - f"running; at most {capacity.max_viable_context_tokens} tokens of " + f"{format_bytes(capacity.capacity_bytes)}{hot_cache} even with " + f"nothing else running; at most " + f"{capacity.max_viable_context_tokens} tokens of " f"context plus max_tokens fit. {advice}." ) diff --git a/tests/test_scheduler_capacity_gate.py b/tests/test_scheduler_capacity_gate.py index b59bb11b0f..da54ff4a88 100644 --- a/tests/test_scheduler_capacity_gate.py +++ b/tests/test_scheduler_capacity_gate.py @@ -282,13 +282,108 @@ def test_never_fits_counts_the_releasable_hot_cache(gated, monkeypatch): def test_never_fits_beyond_the_hot_cache_credit_is_still_rejected(gated, monkeypatch): scheduler, _usage, _admitted = gated + base = scheduler._capacity_limit_bytes() context, over = _over_by(scheduler) _hot_cache_credit(monkeypatch, scheduler, over // 2) with pytest.raises(ContextExceedsCapacityError) as info: scheduler.preflight_or_raise(num_prompt_tokens=context, max_tokens=0) - # The 400 body keeps the credit-free numbers. + # The 400 body reports the line the gate compared against: the capacity + # line raised by the hot cache the request would release. fields = info.value.capacity_fields - assert fields["required_bytes"] - fields["capacity_bytes"] == over + assert fields["capacity_bytes"] == base + over // 2 + assert fields["required_bytes"] - fields["capacity_bytes"] == over - over // 2 + assert "of hot cache it would release" in str(info.value) + + +@pytest.mark.parametrize("credit_of_over", [0.5, 2.0]) +def test_gate_estimate_fits_alone_agrees_with_its_max_viable_context( + gated, monkeypatch, credit_of_over +): + """One estimate never says it fits alone above its own max viable context.""" + scheduler, _usage, _admitted = gated + context, over = _over_by(scheduler) + _hot_cache_credit(monkeypatch, scheduler, int(over * credit_of_over)) + cap = scheduler._capacity_estimate( + context_tokens=context, max_tokens=0, count_hot_cache=True + ) + assert cap.fits_alone == (context <= cap.max_viable_context_tokens) + assert cap.fits_alone == (cap.required_bytes <= cap.capacity_bytes) + assert cap.fits_alone is (credit_of_over > 1) + + +def test_never_fits_400_names_the_largest_request_the_gate_admits(gated, monkeypatch): + """The 400 body's max_viable_context_tokens is the gate's own boundary.""" + scheduler, _usage, _admitted = gated + context, over = _over_by(scheduler) + _hot_cache_credit(monkeypatch, scheduler, over // 2) + with pytest.raises(ContextExceedsCapacityError) as info: + scheduler.preflight_or_raise(num_prompt_tokens=context, max_tokens=0) + best = info.value.capacity_fields["max_viable_context_tokens"] + assert best < context + scheduler.preflight_or_raise(num_prompt_tokens=best, max_tokens=0) + with pytest.raises(ContextExceedsCapacityError): + scheduler.preflight_or_raise(num_prompt_tokens=best + 1, max_tokens=0) + + +def _real_hot_cache(scheduler, monkeypatch, context, *, releasable, reserved=None): + """Hot cache holding the request's own prefix (its KV) plus ``releasable`` + bytes of other blocks, read by the real ``_releasable_hot_cache_credit``.""" + own = scheduler._admission_estimate( + num_prompt_tokens=context, cached_tokens=0, current=0 + ).kv_exact + held = own + releasable + scheduler._memory_hot_cache_reserved_bytes = reserved or held + monkeypatch.setattr(scheduler, "_hot_cache_cpu_bytes", lambda: held) + return own + + +def test_never_fits_credits_only_hot_cache_that_can_be_released(gated, monkeypatch): + """Main's limits subtract the hot-cache reservation and its eviction ladder + releases cold blocks and raises the limit (#4252), so main runs a request + the released hot cache makes room for. The request's own prefix stays + protected: a resident hot cache holding only that prefix earns no credit, + and a request over the line by more than the released bytes is a 400.""" + scheduler, usage, _admitted = gated + usage[0] = scheduler._model_weights_bytes() # nothing else running + context, over = _over_by(scheduler, extra_tokens=5_000) + factor = scheduler._hot_cache_limit_factor() + assert 0.5 < factor <= 1 + + _real_hot_cache(scheduler, monkeypatch, context, releasable=2 * over) + scheduler.preflight_or_raise(num_prompt_tokens=context, max_tokens=0) + + _real_hot_cache(scheduler, monkeypatch, context, releasable=over // 4) + with pytest.raises(ContextExceedsCapacityError): + scheduler.preflight_or_raise(num_prompt_tokens=context, max_tokens=0) + + _real_hot_cache(scheduler, monkeypatch, context, releasable=0, reserved=50 * GB) + with pytest.raises(ContextExceedsCapacityError): + scheduler.preflight_or_raise(num_prompt_tokens=context, max_tokens=0) + + +def test_current_usage_check_still_credits_the_hot_cache_as_main(gated, monkeypatch): + """With memory scheduling on, a request that fits alone but whose peak + on the current usage is over the admission line by less than the + releasable hot cache passes the route preflight, as on main (#4252).""" + scheduler, usage, _admitted = gated + context = scheduler.max_viable_context_tokens() // 2 + est = scheduler._admission_estimate( + num_prompt_tokens=context, cached_tokens=0, current=0 + ) + over = 2 * GB + # Over the capacity line (the tighter of the admission line and the + # safety cap) by ``over`` on the current usage. + usage[0] = scheduler._capacity_limit_bytes() - est.estimated + over + _real_hot_cache(scheduler, monkeypatch, context, releasable=4 * over) + scheduler.preflight_or_raise(num_prompt_tokens=context, max_tokens=0) + assert ( + scheduler.preflight_eviction_request(num_prompt_tokens=context, max_tokens=0) + is None + ) + _real_hot_cache(scheduler, monkeypatch, context, releasable=0) + with pytest.raises(PrefillMemoryExceededError) as info: + scheduler.preflight_or_raise(num_prompt_tokens=context, max_tokens=0) + assert type(info.value) is PrefillMemoryExceededError # not never-fits def test_in_stream_never_fits_counts_the_releasable_hot_cache(gated, monkeypatch): From 9ff04734b8c08f3e76ccf85ed50350eafa40b69e Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Wed, 7 Oct 2026 21:08:46 -0600 Subject: [PATCH 46/46] fix(scheduler): restart the fixed stall clock when a park hold ends With memory scheduling off and park on, the stall checks switch between the progress clock (while a park hold is active) and upstream's fixed clock on every call. The fixed clock ran from when the head first blocked, so a head still blocked when the hold ended jumped back to that time and failed at once on the 60 s timeout, for time it spent waiting through the hold. The scheduler now records when the progress clock turns off, and the fixed clock of a blocked head never starts before that moment: the head gets the full upstream timeout after the hold ends. A head that blocks later keeps upstream's clock unchanged. Covers the memory and store-cache stalls. --- docs/TESTING.md | 2 +- omlx/scheduler.py | 44 +++++++++++++++------ tests/test_memory_scheduling_gate.py | 59 ++++++++++++++++++++++++++++ 3 files changed, 93 insertions(+), 12 deletions(-) diff --git a/docs/TESTING.md b/docs/TESTING.md index 4da7cbbe63..3e7c29f2b2 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -237,7 +237,7 @@ Mocked tests do not replace hardware validation: with a real model, abort a long # Memory scheduling gate tests -Run `python -m pytest -q tests/test_memory_scheduling_gate.py` to check `memory.memory_scheduling` (env `OMLX_MEMORY_SCHEDULING`; `auto`, `on` or `off`, default `auto`). It gates three behaviours: the never-fits 400 with the capacity endpoint numbers and the `X-oMLX-Max-Context-Tokens` header; the fits-later wait, including the solo admission of a lone head; and the progress-based admission-stall clock. `auto` is on when the prefill memory guard is on and an explicit ceiling is set (`memory_guard_tier: custom` with `memory_guard_custom_ceiling_gb` > 0; a ceiling value left under another tier does not count). `on` forces it on but still needs the guard (with the guard off it stays off and logs a warning). `off` forces it off. The `ProcessMemoryEnforcer` resolves the mode at startup and whenever the mode, the guard, the tier or the ceiling changes (the admin settings apply live), logs `Memory scheduling: on (explicit ceiling 48.0 GB)` or the reason it is off, and propagates the result to every scheduler (`Scheduler._memory_scheduling`, False until an enforcer sets it). The tests cover the resolution matrix, the setting (default, `to_dict`, `from_dict`, env override, validation, the admin GET and POST), and, with it off, upstream behaviour on each path: no capacity estimate, snapshot or header (a cached hint is not served either); a request whose `max_tokens` can never fit passes when its prompt fits now; a fits-alone-but-not-now request gets the old current-usage rejection; a lone head is not admitted solo; the stall clock fails the head 60 s after it first blocked, whatever else progresses, with the old message and metadata (no `no_progress_seconds`), also for store-cache backpressure; with the park feature on, a hold it created (a parked or decode-paused request running solo or waiting) keeps the progress clock and its 600 s bound whatever the mode, because the head waits for work held back on purpose (park off, no such hold exists); an external-loop prefill is not reported as solo to the enforcer; and the capacity endpoint returns `available: false` with `memory_scheduling: "off"` and the reason, while unknown and unloaded models keep their 404 and 409. `tests/test_memory_external_prefill.py` also drives the real enforcer with park, single victim and memory scheduling off: the lone external prefill at hard pressure gets upstream's abort-all. The suites below that test these behaviours set the mode on explicitly (`scheduler._memory_scheduling = True`, or `memory_scheduling="on"` on the real enforcer). +Run `python -m pytest -q tests/test_memory_scheduling_gate.py` to check `memory.memory_scheduling` (env `OMLX_MEMORY_SCHEDULING`; `auto`, `on` or `off`, default `auto`). It gates three behaviours: the never-fits 400 with the capacity endpoint numbers and the `X-oMLX-Max-Context-Tokens` header; the fits-later wait, including the solo admission of a lone head; and the progress-based admission-stall clock. `auto` is on when the prefill memory guard is on and an explicit ceiling is set (`memory_guard_tier: custom` with `memory_guard_custom_ceiling_gb` > 0; a ceiling value left under another tier does not count). `on` forces it on but still needs the guard (with the guard off it stays off and logs a warning). `off` forces it off. The `ProcessMemoryEnforcer` resolves the mode at startup and whenever the mode, the guard, the tier or the ceiling changes (the admin settings apply live), logs `Memory scheduling: on (explicit ceiling 48.0 GB)` or the reason it is off, and propagates the result to every scheduler (`Scheduler._memory_scheduling`, False until an enforcer sets it). The tests cover the resolution matrix, the setting (default, `to_dict`, `from_dict`, env override, validation, the admin GET and POST), and, with it off, upstream behaviour on each path: no capacity estimate, snapshot or header (a cached hint is not served either); a request whose `max_tokens` can never fit passes when its prompt fits now; a fits-alone-but-not-now request gets the old current-usage rejection; a lone head is not admitted solo; the stall clock fails the head 60 s after it first blocked, whatever else progresses, with the old message and metadata (no `no_progress_seconds`), also for store-cache backpressure; with the park feature on, a hold it created (a parked or decode-paused request running solo or waiting) keeps the progress clock and its 600 s bound whatever the mode, because the head waits for work held back on purpose (park off, no such hold exists); when that hold ends while the head is still blocked, the fixed 60 s clock starts at that moment, never from when the head first blocked, so it is not failed at once for time spent waiting through the hold (memory and store-cache stalls); an external-loop prefill is not reported as solo to the enforcer; and the capacity endpoint returns `available: false` with `memory_scheduling: "off"` and the reason, while unknown and unloaded models keep their 404 and 409. `tests/test_memory_external_prefill.py` also drives the real enforcer with park, single victim and memory scheduling off: the lone external prefill at hard pressure gets upstream's abort-all. The suites below that test these behaviours set the mode on explicitly (`scheduler._memory_scheduling = True`, or `memory_scheduling="on"` on the real enforcer). Run `python -m pytest -q tests/test_memory_scheduling_admin_state.py` to check memory scheduling across admin settings saves. The cases load the real settings with `memory_scheduling: "on"` in `settings.json`, build the live enforcer from them as the server does, and drive the real admin routes. A save of `max_concurrent_requests`, `chunked_prefill` or `memory_guard_tier` keeps the mode on the live settings object and in `settings.json` (a reload sees it again), keeps it on and propagated, and logs no `Memory scheduling:` line. Loading the settings page (`GET /admin/api/global-settings`, which builds one tier-preview enforcer per tier) logs none either: only an enforcer that drives an engine pool logs its state. An explicit `memory_scheduling` POST, including one that repeats the current mode, re-resolves, logs the state and propagates it to the schedulers. The GET reports the live state as `memory.memory_scheduling_effective` (`enabled` and `reason`, `null` without an enforcer), the POST response carries it, and the factory defaults response does not. diff --git a/omlx/scheduler.py b/omlx/scheduler.py index e34712a282..2d820afa46 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -2755,6 +2755,10 @@ def __init__( # Last time any request made progress (see _note_admission_progress); # the admission-stall clocks run from it. None until the first one. self._admission_progress_at: float | None = None + # The progress clock as last observed, and when it last turned off + # (see _observe_progress_clock). + self._progress_clock_was_on: bool = False + self._progress_clock_off_at: float | None = None # Last "Admission waiting for memory" line (head id, time). self._admission_wait_logged: tuple[str, float] | None = None # EWMA estimator of per-token chunk transient bytes, used by @@ -6119,17 +6123,35 @@ def _park_memory_hold(self) -> bool: return True return any(request.parked for request in self.waiting) - def _admission_idle_since(self, blocked_since: float) -> float: + def _observe_progress_clock(self, now: float) -> bool: + """``_progress_clock_on`` at ``now``, recording when it turns off. + + The stall checks call this once per step, so a park hold that ends + is seen as the clock turning off at the first check after it. + """ + on = self._progress_clock_on() + if self._progress_clock_was_on and not on: + self._progress_clock_off_at = now + self._progress_clock_was_on = on + return on + + def _admission_idle_since( + self, blocked_since: float, progress_clock: bool + ) -> float: """Start of the current no-progress stretch for a blocked head. - Without the progress clock (``_progress_clock_on``) the clock is + With the progress clock, the last progress. Without it the clock is upstream's: it runs from when the head first blocked, whatever else - progresses. + progresses, but never from before the progress clock last turned + off. A head still blocked when a park hold ends then gets the full + fixed timeout from that moment instead of failing at once on time + it spent waiting through the hold. """ - progress = self._admission_progress_at - if progress is None or not self._progress_clock_on(): - return blocked_since - return max(blocked_since, progress) + if progress_clock: + progress = self._admission_progress_at + return blocked_since if progress is None else max(blocked_since, progress) + off_at = self._progress_clock_off_at + return blocked_since if off_at is None else max(blocked_since, off_at) def _deliberate_memory_hold(self) -> bool: """Whether memory is being scheduled on purpose: a solo request runs, @@ -6181,8 +6203,8 @@ def _memory_admission_stall_output(self, reason: str) -> RequestOutput | None: # client's own timeouts apply. self._clear_memory_admission_blocker(request_id) return None - progress_clock = self._progress_clock_on() now = time.monotonic() + progress_clock = self._observe_progress_clock(now) if request_id != self._memory_admission_blocked_request_id: self._memory_admission_blocked_request_id = request_id self._memory_admission_blocked_since = now @@ -6201,7 +6223,7 @@ def _memory_admission_stall_output(self, reason: str) -> RequestOutput | None: float(getattr(self.config, "admission_no_progress_timeout_s", 600.0)), ) idle_for = now - self._admission_idle_since( - self._memory_admission_blocked_since + self._memory_admission_blocked_since, progress_clock ) if idle_for < timeout: if progress_clock: @@ -6271,8 +6293,8 @@ def _store_cache_admission_stall_output( if request.parked: self._clear_store_cache_admission_blocker(request_id) return None - progress_clock = self._progress_clock_on() now = time.monotonic() + progress_clock = self._observe_progress_clock(now) if request_id != self._store_cache_admission_blocked_request_id: self._store_cache_admission_blocked_request_id = request_id self._store_cache_admission_blocked_since = now @@ -6289,7 +6311,7 @@ def _store_cache_admission_stall_output( Scheduler._STORE_CACHE_ADMISSION_STALL_TIMEOUT_S, ) idle_for = now - self._admission_idle_since( - self._store_cache_admission_blocked_since + self._store_cache_admission_blocked_since, progress_clock ) if idle_for < timeout: if progress_clock: diff --git a/tests/test_memory_scheduling_gate.py b/tests/test_memory_scheduling_gate.py index 414ec5c0f0..956e897f82 100644 --- a/tests/test_memory_scheduling_gate.py +++ b/tests/test_memory_scheduling_gate.py @@ -359,6 +359,65 @@ def test_off_with_park_a_parked_solo_keeps_the_progress_clock(pressured, clock): ) +def test_off_with_park_the_fixed_clock_restarts_when_the_hold_ends(pressured, clock): + """The clock switch is monotone: when the park hold ends while the head + is still blocked, upstream's fixed clock starts at that moment, not at + when the head first blocked (which would fail it at once).""" + scheduler, _head, solo = pressured + scheduler._memory_scheduling = False + scheduler.config.memory_pressure_park = True + timeout = scheduler._MEMORY_ADMISSION_STALL_TIMEOUT_S + scheduler._solo_request_id = solo.request_id + assert _schedule(scheduler) == [] + for _ in range(3): + clock.advance(timeout - 1) + scheduler._note_admission_progress() # the solo request emits a token + assert _schedule(scheduler) == [] + clock.advance(timeout - 1) # no progress since: idle just under timeout + scheduler._solo_request_id = None # the hold ends; the head still blocks + assert _schedule(scheduler) == [] + clock.advance(timeout - 1) + assert _schedule(scheduler) == [] + clock.advance(1) + (failed,) = _schedule(scheduler) + assert failed.error_code == "memory_admission_stalled" + assert "no_progress_seconds" not in failed.error_metadata + + +def test_off_with_park_store_cache_fixed_clock_restarts_when_the_hold_ends( + pressured, clock +): + scheduler, head, running = pressured + scheduler._memory_scheduling = False + scheduler.config.memory_pressure_park = True + del scheduler.running[running.request_id] + scheduler._admission_paused = False + gate = _StoreCacheGate(cap=1) + gate.note_submitted() + scheduler._store_cache_gate = gate + parked = progress_tests._request("parked") + parked.parked = True + scheduler.waiting.append(parked) # a parked request behind the head + scheduler.requests[parked.request_id] = parked + timeout = scheduler._STORE_CACHE_ADMISSION_STALL_TIMEOUT_S + assert _schedule(scheduler) == [] + for _ in range(3): + clock.advance(timeout - 1) + scheduler._note_admission_progress() # a drained write + assert _schedule(scheduler) == [] + scheduler.waiting.remove(parked) # the hold ends; the head still blocks + del scheduler.requests[parked.request_id] + assert scheduler.waiting[0] is head + clock.advance(1) + assert _schedule(scheduler) == [] + clock.advance(timeout - 1) + assert _schedule(scheduler) == [] + clock.advance(1) + (failed,) = _schedule(scheduler) + assert failed.error_code == "store_cache_admission_stalled" + assert "no_progress_seconds" not in failed.error_metadata + + def test_off_store_cache_backpressure_uses_the_fixed_timeout( pressured, clock,