Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion omlx/admin/context_benchmark.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 0 additions & 4 deletions omlx/engine/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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

Expand Down Expand Up @@ -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

Expand Down
1 change: 0 additions & 1 deletion omlx/engine/batched.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,6 @@ async def _preflight_or_raise_with_eviction(
"_mlx_executor",
None,
),
text_only=True,
)

@property
Expand Down
4 changes: 0 additions & 4 deletions omlx/engine/vlm.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -1885,7 +1884,6 @@ async def _preflight_or_raise_with_eviction(
"_mlx_executor",
None,
),
text_only=text_only,
)

@property
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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(
Expand Down
66 changes: 66 additions & 0 deletions omlx/memory_monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from __future__ import annotations

import logging
import os
import threading
import time
from collections import Counter
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand All @@ -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()
Expand Down Expand Up @@ -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)
Expand All @@ -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(
Expand Down
Loading
Loading