diff --git a/omlx/admin/context_benchmark.py b/omlx/admin/context_benchmark.py index c4bccd74d8..efc01bc740 100644 --- a/omlx/admin/context_benchmark.py +++ b/omlx/admin/context_benchmark.py @@ -244,7 +244,7 @@ def _guard_ready(scheduler: Any) -> bool: def _make_fits(scheduler: Any) -> Callable[[int], bool]: def fits(n: int) -> bool: try: - scheduler.preflight_or_raise(num_prompt_tokens=n, text_only=True) + scheduler.preflight_or_raise(num_prompt_tokens=n) except PrefillMemoryExceededError: return False return True diff --git a/omlx/engine/base.py b/omlx/engine/base.py index 0c648ea682..f42f3aa1c0 100644 --- a/omlx/engine/base.py +++ b/omlx/engine/base.py @@ -88,7 +88,6 @@ async def _run_scheduler_preflight_with_cleanup_retry( request_id: str | None, eviction_callback: Any | None, executor: Any | None = None, - text_only: bool = False, ) -> None: """Run route preflight after transient post-request cleanup settles. @@ -109,13 +108,11 @@ async def _run_scheduler_preflight_with_cleanup_retry( eviction_request = scheduler.preflight_eviction_request( num_prompt_tokens=num_prompt_tokens, request_id=request_id, - text_only=text_only, ) if eviction_request is None: scheduler.preflight_or_raise( num_prompt_tokens=num_prompt_tokens, request_id=request_id, - text_only=text_only, ) return @@ -191,7 +188,6 @@ async def _run_scheduler_preflight_with_cleanup_retry( scheduler.preflight_or_raise( num_prompt_tokens=num_prompt_tokens, request_id=request_id, - text_only=text_only, ) return diff --git a/omlx/engine/batched.py b/omlx/engine/batched.py index 7b8a22df77..d3ac3ce500 100644 --- a/omlx/engine/batched.py +++ b/omlx/engine/batched.py @@ -118,7 +118,6 @@ async def _preflight_or_raise_with_eviction( "_mlx_executor", None, ), - text_only=True, ) @property diff --git a/omlx/engine/vlm.py b/omlx/engine/vlm.py index 0231e29745..e763f17fab 100644 --- a/omlx/engine/vlm.py +++ b/omlx/engine/vlm.py @@ -1873,7 +1873,6 @@ async def _preflight_or_raise_with_eviction( *, num_prompt_tokens: int, request_id: str | None, - text_only: bool = False, ) -> None: await _run_scheduler_preflight_with_cleanup_retry( scheduler, @@ -1885,7 +1884,6 @@ async def _preflight_or_raise_with_eviction( "_mlx_executor", None, ), - text_only=text_only, ) @property @@ -5218,7 +5216,6 @@ async def preflight_chat( scheduler, num_prompt_tokens=num_tokens, request_id=request_id, - text_only=image_tokens == 0 and video_tokens == 0, ) async def preflight_completion( @@ -5254,7 +5251,6 @@ async def preflight_completion( scheduler, num_prompt_tokens=num_tokens, request_id=request_id, - text_only=True, ) async def stream_chat( diff --git a/omlx/memory_monitor.py b/omlx/memory_monitor.py index b2b2c9c1da..436e8dbee7 100644 --- a/omlx/memory_monitor.py +++ b/omlx/memory_monitor.py @@ -13,6 +13,7 @@ from __future__ import annotations import logging +import os import threading import time from collections import Counter @@ -43,6 +44,61 @@ # different head dimensions; unsupported cases fall back to an unfused # score-matrix allocation. _SDPA_VECTOR_QUERY_TOKEN_THRESHOLD = 8 + + +def qwen4_gathered_min_query_tokens() -> int: + """Keep narrow Lightning MTP windows on masked SDPA (M5 crossover).""" + try: + return max( + 2, int(os.environ.get("OMLX_QWEN4_GATHERED_MIN_QUERY", "16")) + ) + except ValueError: + return 16 + + +def qwen4_gathered_prefill_route( + query_tokens: int, cache_tokens: int, indexer_budget: int +) -> bool: + """Whether Qwen4 text prefill uses sparse gathered QSA.""" + return ( + query_tokens >= qwen4_gathered_min_query_tokens() + and cache_tokens + query_tokens > indexer_budget + ) + + +_TEXT_MROPE_EQUAL_PLANES: list[tuple[Any, int, bool]] = [] + + +def qwen4_text_mrope_broadcast(position_ids: Any, length: int) -> bool: + """True for missing/2-D text ids, or 3-D mRoPE that is a text broadcast. + + The parent LanguageModel tiles identical ``(1, L)`` positions to + ``(3, 1, L)`` for text-only mRoPE. Real image grids differ across the + three planes and must stay on the official mask+SDPA path. Shared by the + Qwen4 runtime eligibility gate and the scheduler's route pricing so both + sides decide identically for image-region chunks. + """ + if position_ids is None: + return True + if mx is None or not isinstance(position_ids, mx.array): + return False + if position_ids.ndim == 2: + return tuple(position_ids.shape) == (1, length) + if position_ids.ndim != 3 or tuple(position_ids.shape) != (3, 1, length): + return False + for cached_ids, cached_len, cached_same in _TEXT_MROPE_EQUAL_PLANES: + if cached_ids is position_ids and cached_len == length: + return cached_same + same = bool( + mx.array_equal(position_ids[0], position_ids[1]).item() + and mx.array_equal(position_ids[1], position_ids[2]).item() + ) + _TEXT_MROPE_EQUAL_PLANES.append((position_ids, length, same)) + if len(_TEXT_MROPE_EQUAL_PLANES) > 8: + del _TEXT_MROPE_EQUAL_PLANES[:-8] + return same + + _SDPA_FULL_SUPPORTED_HEAD_DIMS = frozenset({64, 72, 80, 96, 128}) _SDPA_VECTOR_SUPPORTED_HEAD_DIMS = frozenset({64, 96, 128, 256}) # Default bytes/elem for the materialized unfused score matrix when the model's @@ -873,6 +929,16 @@ def uses_flat_overhead_accounting(self) -> bool: ), ) + def qwen4_gathered_prefill_route( + self, query_tokens: int, cache_tokens: int + ) -> bool: + profile = self._prefill_memory_profile + return isinstance( + profile, _Qwen4ExpPrefillMemoryProfile + ) and qwen4_gathered_prefill_route( + query_tokens, cache_tokens, profile.indexer_budget + ) + def estimate_chunk_transient_bytes( self, n_tokens: int, diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/language.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/language.py index 8e825fb3ab..e2b2f13d7c 100644 --- a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/language.py +++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/language.py @@ -23,6 +23,14 @@ import mlx.nn as nn import numpy as np +from omlx.memory_monitor import ( + qwen4_gathered_min_query_tokens as _gathered_min_query_tokens, +) +from omlx.memory_monitor import qwen4_gathered_prefill_route +from omlx.memory_monitor import ( + qwen4_text_mrope_broadcast as _broadcast_text_mrope_position_ids, +) + from omlx.patches.mlx_vlm_qwen4_exp_compat.ple_load_resources import register_ple_resource from omlx.patches import row_exact_qmv from omlx.patches.qwen35_verify_qmm import is_row_exact_armed @@ -57,39 +65,6 @@ _PLE_RUNTIME_MODEL_PATH: Path | None = None _PLE_RUNTIME_MODE = "resident" _HYPER_SPLIT_INDICES: dict[tuple[int, int], tuple[mx.array, mx.array]] = {} -# Identity cache: keep the array alive so CPython cannot recycle id(). -_TEXT_MROPE_EQUAL_PLANES: list[tuple[Any, int, bool]] = [] - - -def _broadcast_text_mrope_position_ids( - position_ids: Optional[mx.array], - length: int, -) -> bool: - """True for missing/2-D text ids, or 3-D MRoPE that is a text broadcast. - - Parent LanguageModel tiles identical ``(1, L)`` positions to ``(3, 1, L)`` - for text-only mRoPE. Real image grids differ across the three planes and - must stay on the official mask+SDPA path. - """ - if position_ids is None: - return True - if not isinstance(position_ids, mx.array): - return False - if position_ids.ndim == 2: - return tuple(position_ids.shape) == (1, length) - if position_ids.ndim != 3 or tuple(position_ids.shape) != (3, 1, length): - return False - for cached_ids, cached_len, cached_same in _TEXT_MROPE_EQUAL_PLANES: - if cached_ids is position_ids and cached_len == length: - return cached_same - same = bool( - mx.array_equal(position_ids[0], position_ids[1]).item() - and mx.array_equal(position_ids[1], position_ids[2]).item() - ) - _TEXT_MROPE_EQUAL_PLANES.append((position_ids, length, same)) - if len(_TEXT_MROPE_EQUAL_PLANES) > 8: - del _TEXT_MROPE_EQUAL_PLANES[:-8] - return same def _rank_two_text_position_ids( @@ -106,17 +81,6 @@ def _rank_two_text_position_ids( ) -def _gathered_min_query_tokens() -> int: - """Keep narrow Lightning MTP windows on masked SDPA (M5 crossover).""" - raw = os.environ.get("OMLX_QWEN4_GATHERED_MIN_QUERY", "").strip() - if raw: - try: - return max(2, int(raw)) - except ValueError: - pass - return 16 - - def _row_exact_verify_armed() -> bool: """Inside an armed MTP verify whose rows must equal serial decode steps.""" return is_row_exact_armed() @@ -1495,10 +1459,6 @@ def _gathered_text_prefill_eligible( if not ( x.ndim == 3 and x.shape[0] == 1 - # Narrow multi-row windows (Lightning MTP history/verify passes) - # are cheaper on the official masked path; see - # _gathered_min_query_tokens. - and x.shape[1] >= _gathered_min_query_tokens() and causal_mask and type(cache) is QSAKVCache and isinstance(cache.offset, int) @@ -1507,11 +1467,8 @@ def _gathered_text_prefill_eligible( and self._batch_one_text_position_ids(position_ids, x.shape[1]) ): return False - return bool( - # Below the QSA budget the official path attends the complete - # prefix directly and is faster than building gathered blocks. - # Switch only after sparse selection can reduce actual work. - cache.offset + x.shape[1] > self.indexer.token_budget + return qwen4_gathered_prefill_route( + x.shape[1], cache.offset, self.indexer.token_budget ) def _gathered_text_decode_eligible( diff --git a/omlx/scheduler.py b/omlx/scheduler.py index a67f25ad46..8154b302e7 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -386,6 +386,7 @@ def has_capacity(self) -> bool: estimate_mla_kv_bytes_per_token, estimate_qwen4_exp_kv_bytes_per_token, make_prefill_memory_profile, + qwen4_text_mrope_broadcast, ) HAS_TIERED_CACHE = True @@ -398,6 +399,7 @@ def has_capacity(self) -> bool: estimate_mla_kv_bytes_per_token = None estimate_qwen4_exp_kv_bytes_per_token = None make_prefill_memory_profile = None + qwen4_text_mrope_broadcast = None HAS_TIERED_CACHE = False # Import cache type handlers for hybrid cache support @@ -3760,14 +3762,44 @@ def _prefill_flat_overhead_enabled(self) -> bool: return checker() is True return Scheduler._qwen4_prefill_accounting_enabled(self) - def _qwen4_text_gathered_pricing(self, text_only: bool) -> bool: - """True when this engine can price Qwen4 text prefill as gathered QSA. - - Callers that do not know whether the request is text-only must pass - False. Preflight and prefill then share an argument instead of a - mutable flag on the shared monitor. - """ - return text_only is True and Scheduler._qwen4_prefill_accounting_enabled(self) + def _qwen4_text_gathered_pricing( + self, + *, + query_tokens: int, + cache_tokens: int, + position_ids: Any = None, + prompt_cache: list[Any] | None = None, + ) -> bool: + """Predict the Qwen4 prefill route for one concrete chunk. + + Mirrors the runtime gate ``_gathered_text_prefill_eligible``: the + shared query/cache budget predicate plus the mRoPE plane test. + Callers that know the chunk's position_ids (the external VLM prefill + loop slices them from ``vlm_extra_kwargs``) pass them so image-region + chunks stay dense-priced; callers without them (admission) assume a + text chunk. The mid-prefill guard re-prices every real chunk with + its actual position_ids, so an image-bearing tail is still caught + before Metal sees it. + """ + if prompt_cache is not None: + try: + from mlx_vlm.models.qwen4_exp.language import QSAKVCache + except ImportError: + return False + qsa_caches = [ + cache + for cache in prompt_cache + if callable(getattr(cache, "reserve_index_capacity", None)) + ] + if not qsa_caches or any(type(cache) is not QSAKVCache for cache in qsa_caches): + return False + monitor = getattr(self, "memory_monitor", None) + checker = getattr(monitor, "qwen4_gathered_prefill_route", None) + if not (callable(checker) and checker(query_tokens, cache_tokens) is True): + return False + if position_ids is None or qwen4_text_mrope_broadcast is None: + return True + return qwen4_text_mrope_broadcast(position_ids, query_tokens) is True @staticmethod def _qwen4_actual_gathered_pricing( @@ -3813,7 +3845,6 @@ def _do_external_prefill( """ _mtp_priming.activate_request(self.model, request.request_id) n_tokens = len(tokens) - gathered_core = self._qwen4_text_gathered_pricing(vlm_embeds is None) if n_tokens <= 1: # Nothing to prefill, return cache + tokens as-is. cache = existing_cache or make_prompt_cache(self.model) @@ -3858,7 +3889,9 @@ def _do_external_prefill( if getattr(request, "benchmark_trace", False): request.benchmark_boundary_enabled = boundary_enabled request.benchmark_cache_block_size = block_size if boundary_enabled else 0 - base_size = _cache_base_sizes(prompt_cache) if boundary_enabled else 0 + base_size = max(int(getattr(request, "cached_tokens", 0)), 0) + if boundary_enabled: + base_size = _cache_base_sizes(prompt_cache) # Sanity check: base_size from cache offsets should match the number # of tokens actually cached. A mismatch indicates stale meta_state # in a restored RotatingKVCache (e.g. shared layer_meta_states from @@ -3954,6 +3987,21 @@ def _do_external_prefill( self._reserve_qsa_index_capacity(prompt_cache, reserve_tokens) Scheduler._announce_first_prefill_chunk(self, input_arr, base_size, boundary_enabled, block_size, embeds_array) + + def _chunk_route(n_tokens: int, cache_tokens: int) -> bool: + # Price the exact chunk execution will run: the shared + # query/cache predicate plus the chunk's mRoPE plane test when + # the VLM pipeline supplies position_ids. Image-region chunks + # have differing planes and stay dense-priced; text chunks + # gather, with or without images elsewhere in the prompt. + sliced = _slice_vlm_extra(extra_kwargs, n_tokens) if extra_kwargs else {} + return self._qwen4_text_gathered_pricing( + query_tokens=n_tokens, + cache_tokens=cache_tokens, + position_ids=sliced.get("position_ids"), + prompt_cache=prompt_cache, + ) + while input_arr.shape[1] > 0: _trace_chunk_start = time.perf_counter() _trace_processed_before = processed_tokens @@ -3990,25 +4038,40 @@ def _do_external_prefill( ) n_to_process = max(n_to_process, atomic_prefix) + cache_tokens = base_size + processed_tokens + gathered_core = _chunk_route(n_to_process, cache_tokens) try: if not atomic_prefix: n_to_process = self._adaptive_chunk_size( n_to_process, request_id=request.request_id, loop_label="external", - kv_len=base_size + processed_tokens, + kv_len=cache_tokens, gathered_core=gathered_core, ) + gathered_core = _chunk_route(n_to_process, cache_tokens) # Check the predicted peak before submitting work to Metal. n_to_process = self._guard_prefill_chunk( n_to_process, - kv_len=base_size + processed_tokens, + kv_len=cache_tokens, progress=processed_tokens, loop_label="external", request_id=request.request_id, gathered_core=gathered_core, **({"minimum_tokens": atomic_prefix} if atomic_prefix else {}), ) + final_route = _chunk_route(n_to_process, cache_tokens) + if final_route != gathered_core: + gathered_core = final_route + n_to_process = self._guard_prefill_chunk( + n_to_process, + kv_len=cache_tokens, + progress=processed_tokens, + loop_label="external", + request_id=request.request_id, + gathered_core=gathered_core, + **({"minimum_tokens": atomic_prefix} if atomic_prefix else {}), + ) except _PrefillEvictionNeeded: # Keep token progress aligned with the advanced KV on retry. # Cold requests must also retain their locally created cache. @@ -6123,27 +6186,46 @@ def _step_prefill_chunk(self, state: _PrefillState) -> bool: # convert that into a finish_reason="error" output for the client. # Chunked prefill is text-only (VLM never builds _PrefillState). qwen4_accounting = Scheduler._qwen4_prefill_accounting_enabled(self) - if qwen4_accounting and state.qwen4_gathered_core is None: - state.qwen4_gathered_core = self._qwen4_text_gathered_pricing(True) - gathered_core = state.qwen4_gathered_core or False + cache_tokens = state.base_size + state.tokens_processed + + def qwen4_route(query_tokens: int) -> bool: + return qwen4_accounting and self._qwen4_text_gathered_pricing( + query_tokens=query_tokens, + cache_tokens=cache_tokens, + prompt_cache=state.cache, + ) + + gathered_core = qwen4_route(n) n = self._adaptive_chunk_size( n, request_id=state.request.request_id, loop_label="chunked_step", - kv_len=state.base_size + state.tokens_processed, + kv_len=cache_tokens, gathered_core=gathered_core, ) + gathered_core = qwen4_route(n) # Pre-chunk safety guard (mirrors the external loop): never submit a # chunk whose predicted peak would trip the uncatchable async Metal OOM. n = self._guard_prefill_chunk( n, - kv_len=state.base_size + state.tokens_processed, + kv_len=cache_tokens, progress=state.tokens_processed, loop_label="chunked_step", request_id=state.request.request_id, gathered_core=gathered_core, ) + final_route = qwen4_route(n) + if final_route != gathered_core: + gathered_core = final_route + n = self._guard_prefill_chunk( + n, + kv_len=cache_tokens, + progress=state.tokens_processed, + loop_label="chunked_step", + request_id=state.request.request_id, + gathered_core=gathered_core, + ) # Count only tokens actually passed to the model. n = min(n, remaining) if getattr(state.request, "benchmark_trace", False): @@ -9693,7 +9775,6 @@ 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, - text_only=getattr(request, "vlm_inputs_embeds", None) is None, ) except Exception: self._release_paged_cache_for_request(request.request_id) @@ -11023,7 +11104,6 @@ def _preflight_memory_check( num_prompt_tokens=prompt_tokens, cached_tokens=cached_tokens, current=current, - text_only=getattr(request, "vlm_inputs_embeds", None) is None, ) if est is None: return None # can't estimate, skip @@ -11082,7 +11162,6 @@ def _admission_estimate( num_prompt_tokens: int, cached_tokens: int, current: int, - text_only: bool = False, ) -> _AdmissionEstimate | None: """Deterministic admission estimate shared by every preflight path. @@ -11133,7 +11212,9 @@ def _admission_estimate( kv_exact = int( monitor.estimate_resident_kv_bytes(new_tokens, chunk_tokens=floor_chunk) ) - gathered_core = self._qwen4_text_gathered_pricing(text_only) + gathered_core = self._qwen4_text_gathered_pricing( + query_tokens=floor_chunk, cache_tokens=kv_len + ) transient = int( self._admission_transient_bound( floor_chunk, kv_len, gathered_core=gathered_core @@ -11212,7 +11293,6 @@ def preflight_or_raise( num_prompt_tokens: int, cached_tokens: int = 0, request_id: str | None = None, - text_only: bool = False, ) -> None: """Pre-StreamingResponse prefill memory check. @@ -11238,7 +11318,6 @@ def preflight_or_raise( num_prompt_tokens=num_prompt_tokens, cached_tokens=cached_tokens, current=current, - text_only=text_only, ) if est is None: return @@ -11301,7 +11380,6 @@ def preflight_eviction_request( num_prompt_tokens: int, cached_tokens: int = 0, request_id: str | None = None, - text_only: bool = False, ) -> PrefillEvictionRequest | None: """Return an idle-model eviction request for route-level preflight. @@ -11326,7 +11404,6 @@ def preflight_eviction_request( num_prompt_tokens=num_prompt_tokens, cached_tokens=cached_tokens, current=current, - text_only=text_only, ) if est is None: return None diff --git a/tests/test_context_benchmark.py b/tests/test_context_benchmark.py index dc7e3244c8..317ee19d5c 100644 --- a/tests/test_context_benchmark.py +++ b/tests/test_context_benchmark.py @@ -167,7 +167,6 @@ def preflight_or_raise( num_prompt_tokens, cached_tokens=0, request_id=None, - text_only=False, ): if num_prompt_tokens > self.boundary: raise PrefillMemoryExceededError( diff --git a/tests/test_engine_preflight.py b/tests/test_engine_preflight.py index 903a6eba25..dec9eaae88 100644 --- a/tests/test_engine_preflight.py +++ b/tests/test_engine_preflight.py @@ -221,12 +221,10 @@ async def _evict(request): scheduler.preflight_eviction_request.assert_called_once_with( num_prompt_tokens=123, request_id="req-evict", - text_only=True, ) scheduler.preflight_or_raise.assert_called_once_with( num_prompt_tokens=123, request_id="req-evict", - text_only=True, ) assert order == [("evict", "req-evict"), ("final", "checked")] @@ -271,7 +269,6 @@ async def _no_sleep(_delay): scheduler.preflight_or_raise.assert_called_once_with( num_prompt_tokens=60_000, request_id="req-next", - text_only=True, ) evict.assert_not_awaited() @@ -321,7 +318,6 @@ async def test_stale_idle_preflight_refreshes_before_eviction(): request_id="req-stale", eviction_callback=evict, executor=executor, - text_only=True, ) finally: executor.shutdown(wait=True) @@ -331,7 +327,6 @@ async def test_stale_idle_preflight_refreshes_before_eviction(): scheduler.preflight_or_raise.assert_called_once_with( num_prompt_tokens=60_000, request_id="req-stale", - text_only=True, ) evict.assert_not_awaited() diff --git a/tests/test_prefill_oom_graceful.py b/tests/test_prefill_oom_graceful.py index 1e9670feca..d6c572666a 100644 --- a/tests/test_prefill_oom_graceful.py +++ b/tests/test_prefill_oom_graceful.py @@ -1814,7 +1814,7 @@ def forward(*args, **kwargs): original_adaptive = ns._adaptive_chunk_size def adaptive(n, **kwargs): - charges.append(ns._prefill_transient_tracker.flat_overhead_charge_for(True)) + charges.append(ns._prefill_transient_tracker.flat_overhead_charge_for(False)) return original_adaptive(n, **kwargs) ns._adaptive_chunk_size = adaptive diff --git a/tests/test_scheduler_prefill_memory_guard.py b/tests/test_scheduler_prefill_memory_guard.py index 0889f06d1b..77a2cae79e 100644 --- a/tests/test_scheduler_prefill_memory_guard.py +++ b/tests/test_scheduler_prefill_memory_guard.py @@ -1157,92 +1157,120 @@ def _attach_qwen4_profile(scheduler: Scheduler) -> None: ) -def test_qwen4_text_admission_uses_gathered_transient(): +def test_qwen4_admission_prices_the_gathered_route(): + """Admission prices the floor chunk by the shared execution predicate. + + Execution gathers every text chunk, with or without images elsewhere in + the prompt, so the request's media type must not change the admission + price. Image-region chunks are re-priced exactly by the per-chunk guard, + which sees each real chunk's mRoPE position_ids. + """ scheduler = _make_scheduler() _attach_qwen4_profile(scheduler) current = 147 * 1024**3 - dense = scheduler._admission_estimate( + est = scheduler._admission_estimate( num_prompt_tokens=233_472, cached_tokens=0, current=current, - text_only=False, ) - gathered = scheduler._admission_estimate( - num_prompt_tokens=233_472, - cached_tokens=0, - current=current, - text_only=True, + assert est is not None + assert est.kv_exact > 0 + assert est.transient == int( + scheduler._admission_transient_bound( + est.floor_chunk, est.kv_len, gathered_core=True + ) ) - assert dense is not None and gathered is not None - assert gathered.kv_exact == dense.kv_exact - assert gathered.transient * 4 < dense.transient - assert scheduler._qwen4_text_gathered_pricing(True) is True - assert scheduler._qwen4_text_gathered_pricing(False) is False -def test_qwen4_preflight_doors_use_gathered_for_text_only(): +def test_qwen4_pricing_tracks_execution_route(monkeypatch): + from omlx.patches import mlx_vlm_qwen4_exp_compat as compat + + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp.language import ( + QSAKVCache, + QSAQuantizedKVCache, + ) + + monkeypatch.delenv("OMLX_QWEN4_GATHERED_MIN_QUERY", raising=False) + scheduler = _make_scheduler() + _attach_qwen4_profile(scheduler) + route = scheduler._qwen4_text_gathered_pricing + + assert route(query_tokens=2048, cache_tokens=0) is False + assert route(query_tokens=2048, cache_tokens=2048) is True + assert route(query_tokens=15, cache_tokens=2048) is False + assert route(query_tokens=16, cache_tokens=2048) is True + + # Without position info the chunk is assumed text: execution gathers it. + assert route(query_tokens=2048, cache_tokens=2048) is True + + # VLM text chunks (broadcast-identical mRoPE planes) gather exactly like + # execution; image-region chunks (differing planes) stay dense-priced. + n = 32 + equal = mx.zeros((3, 1, n), dtype=mx.int64) + differing = mx.zeros((3, 1, n), dtype=mx.int64) + differing[2] = differing[2] + 1 + assert route(query_tokens=n, cache_tokens=2048, position_ids=equal) is True + assert route(query_tokens=n, cache_tokens=2048, position_ids=differing) is False + + # Runtime requires the exact floating-point QSA cache type. Quantized QSA + # caches use the official dense path and must be priced that way before it runs. + assert route( + query_tokens=n, + cache_tokens=2048, + position_ids=equal, + prompt_cache=[QSAKVCache()], + ) is True + assert route( + query_tokens=n, + cache_tokens=2048, + position_ids=equal, + prompt_cache=[QSAQuantizedKVCache()], + ) is False + + +def test_qwen4_preflight_doors_admit_at_the_gathered_price(): scheduler = _make_scheduler() _attach_qwen4_profile(scheduler) scheduler._prefill_memory_guard = True current = 147 * 1024**3 - dense = scheduler._admission_estimate( - num_prompt_tokens=233_472, - cached_tokens=0, - current=current, - text_only=False, - ) - gathered = scheduler._admission_estimate( + est = scheduler._admission_estimate( num_prompt_tokens=233_472, cached_tokens=0, current=current, - text_only=True, ) - assert dense is not None and gathered is not None - cap = (dense.estimated + gathered.estimated) // 2 - scheduler._memory_hard_limit_bytes = cap + assert est is not None + scheduler._memory_hard_limit_bytes = current + est.estimated scheduler._memory_abort_limit_bytes = 10**18 with ( patch("omlx.scheduler.mx.get_active_memory", return_value=current), patch("omlx.scheduler.get_phys_footprint", return_value=current), ): - with pytest.raises(PrefillMemoryExceededError): - scheduler.preflight_or_raise( - num_prompt_tokens=233_472, text_only=False - ) - scheduler.preflight_or_raise(num_prompt_tokens=233_472, text_only=True) + scheduler.preflight_or_raise(num_prompt_tokens=233_472) assert ( - scheduler.preflight_eviction_request( - num_prompt_tokens=233_472, text_only=True - ) + scheduler.preflight_eviction_request(num_prompt_tokens=233_472) is None ) - assert ( - scheduler.preflight_eviction_request( - num_prompt_tokens=233_472, text_only=False - ) - is not None - ) -def test_qwen4_image_request_preflight_stays_dense(): +def test_qwen4_image_request_preflight_admits_at_gathered_price(): + """Image-bearing requests admit at the gathered price. + + Their text chunks execute gathered; the mid-prefill guard prices the + actual image-region chunks dense via their mRoPE position_ids (covered + by test_qwen4_pricing_tracks_execution_route). + """ scheduler = _make_scheduler() _attach_qwen4_profile(scheduler) scheduler._prefill_memory_guard = True current = 147 * 1024**3 - dense = scheduler._admission_estimate( - num_prompt_tokens=233_472, - cached_tokens=0, - current=current, - text_only=False, - ) - gathered = scheduler._admission_estimate( + est = scheduler._admission_estimate( num_prompt_tokens=233_472, cached_tokens=0, current=current, - text_only=True, ) - assert dense is not None and gathered is not None - scheduler._memory_hard_limit_bytes = (dense.estimated + gathered.estimated) // 2 + assert est is not None + scheduler._memory_hard_limit_bytes = current + est.estimated scheduler._memory_abort_limit_bytes = 10**18 request = _make_request(233_472) request.vlm_inputs_embeds = object() @@ -1251,4 +1279,4 @@ def test_qwen4_image_request_preflight_stays_dense(): patch("omlx.scheduler.get_phys_footprint", return_value=current), ): rejection = scheduler._preflight_memory_check(request) - assert rejection is not None + assert rejection is None diff --git a/tests/test_vlm_engine.py b/tests/test_vlm_engine.py index 0a2dd908c6..5a8980bd4a 100644 --- a/tests/test_vlm_engine.py +++ b/tests/test_vlm_engine.py @@ -3577,4 +3577,3 @@ async def test_preflight_counts_video_tokens(self): assert estimate.call_count == 2 kwargs = engine._preflight_or_raise_with_eviction.call_args.kwargs assert kwargs["num_prompt_tokens"] == 1002 - assert kwargs["text_only"] is False