From 4e7fea96aa3dbb5e8f083fcf51a1ef901c7169d3 Mon Sep 17 00:00:00 2001 From: Roman Melnyk Date: Thu, 27 Aug 2026 02:45:54 +0200 Subject: [PATCH 001/132] feat(audio): make the 100MB upload cap configurable (#3160) Make the audio upload limit configurable through settings, environment variables, CLI, and the admin API while preserving the existing 100MB default. --- omlx/admin/routes.py | 19 +++++ omlx/api/audio_routes.py | 25 ++++++- omlx/cli.py | 10 +++ omlx/settings.py | 24 +++++++ tests/test_admin_server_aliases.py | 35 +++++++++ tests/test_audio_stt.py | 111 +++++++++++++++++++++++++++++ tests/test_cli.py | 6 ++ tests/test_settings.py | 65 +++++++++++++++++ 8 files changed, 292 insertions(+), 3 deletions(-) diff --git a/omlx/admin/routes.py b/omlx/admin/routes.py index 30781c6732..a0553818ee 100644 --- a/omlx/admin/routes.py +++ b/omlx/admin/routes.py @@ -247,6 +247,7 @@ class GlobalSettingsRequest(BaseModel): burst_decode_mode: str | None = None # "off" / "light" / "balanced" / "aggressive" preserve_mid_system_cache: bool | None = None distributed_inference_enabled: bool | None = None + max_audio_upload_size: str | None = None # Model settings model_dirs: list[str] | None = None @@ -3471,6 +3472,7 @@ async def get_global_settings(is_admin: bool = Depends(require_admin)): False, ) ), + "max_audio_upload_size": global_settings.server.max_audio_upload_size, }, "model": { "model_dirs": [ @@ -3717,6 +3719,23 @@ async def update_global_settings( global_settings.server.distributed_inference_enabled = ( request.distributed_inference_enabled ) + if request.max_audio_upload_size is not None: + from ..config import parse_size + + try: + audio_upload_size = parse_size(request.max_audio_upload_size) + except (AttributeError, TypeError, ValueError) as exc: + raise HTTPException( + status_code=400, + detail=f"Invalid max_audio_upload_size: {exc}", + ) from exc + if audio_upload_size <= 0: + raise HTTPException( + status_code=400, + detail="max_audio_upload_size must be positive", + ) + global_settings.server.max_audio_upload_size = request.max_audio_upload_size + runtime_applied.append("max_audio_upload_size") if request.server_aliases is not None: from ..utils.network import is_valid_alias diff --git a/omlx/api/audio_routes.py b/omlx/api/audio_routes.py index 438c4fe64b..19c0c13752 100644 --- a/omlx/api/audio_routes.py +++ b/omlx/api/audio_routes.py @@ -47,7 +47,8 @@ # {"type": "start"} message instead. realtime_router = APIRouter() -# Maximum upload size for audio files (100 MB). +# Maximum upload size for audio files (100 MB). Used as the default when +# server settings are not initialized. MAX_AUDIO_UPLOAD_BYTES = 100 * 1024 * 1024 # Maximum base64-encoded ref_audio size (~15 MB raw audio, enough for ~60s). @@ -134,8 +135,26 @@ def _record_audio_request(model_id: str) -> None: logger.warning("Failed to record audio metrics for %s: %s", model_id, exc) +def _max_audio_upload_bytes() -> int: + """Return the configured audio upload limit, falling back to the default.""" + try: + from omlx.settings import get_settings + + return get_settings().server.max_audio_upload_bytes() + except RuntimeError: + return MAX_AUDIO_UPLOAD_BYTES + except (AttributeError, TypeError, ValueError) as exc: + logger.warning( + "Invalid max_audio_upload_size; using %s byte default: %s", + MAX_AUDIO_UPLOAD_BYTES, + exc, + ) + return MAX_AUDIO_UPLOAD_BYTES + + async def _read_upload(file: UploadFile) -> bytes: """Read an uploaded file in chunks, bailing early if it exceeds the limit.""" + limit = _max_audio_upload_bytes() chunks: list[bytes] = [] total = 0 while True: @@ -143,12 +162,12 @@ async def _read_upload(file: UploadFile) -> bytes: if not chunk: break total += len(chunk) - if total > MAX_AUDIO_UPLOAD_BYTES: + if total > limit: raise HTTPException( status_code=413, detail=( f"Audio file exceeds maximum allowed size " - f"({MAX_AUDIO_UPLOAD_BYTES} bytes)" + f"({limit} bytes)" ), ) chunks.append(chunk) diff --git a/omlx/cli.py b/omlx/cli.py index 362c26abc1..6653c264f3 100644 --- a/omlx/cli.py +++ b/omlx/cli.py @@ -54,6 +54,7 @@ def _has_cli_overrides(args) -> bool: "host", "log_level", "sse_keepalive_mode", + "max_audio_upload_size", "max_concurrent_requests", "embedding_batch_size", "memory_guard", @@ -1070,6 +1071,15 @@ def main(): "OpenClaw / WorkBuddy; 'comment' emits the legacy ': keep-alive' SSE " "comment; 'off' disables keepalive entirely", ) + serve_parser.add_argument( + "--max-audio-upload-size", + type=str, + default=None, + help="Maximum audio upload size for /v1/audio/transcriptions and " + "/v1/audio/process (e.g. '100MB', '500MB'). Overrides the value " + "in settings.json (built-in default: 100MB). Uploads are buffered " + "in memory, so this is also a per-request RAM cap", + ) # Scheduler options (for BatchedEngine) serve_parser.add_argument( diff --git a/omlx/settings.py b/omlx/settings.py index 4622e0c7f5..baeb2c9409 100644 --- a/omlx/settings.py +++ b/omlx/settings.py @@ -176,6 +176,15 @@ class ServerSettings: burst_decode_mode: str = DEFAULT_BURST_DECODE_MODE preserve_mid_system_cache: bool = True distributed_inference_enabled: bool = False + # Human-readable size, same grammar as cache limits ("100MB", "1GB"). + max_audio_upload_size: str = "100MB" + + def max_audio_upload_bytes(self) -> int: + """Configured audio upload limit in bytes. Non-positive sizes raise ValueError.""" + size = parse_size(self.max_audio_upload_size) + if size <= 0: + raise ValueError("max_audio_upload_size must be positive") + return size def to_dict(self) -> dict[str, Any]: """Convert to dictionary.""" @@ -199,6 +208,7 @@ def from_dict(cls, data: dict[str, Any]) -> ServerSettings: "distributed_inference_enabled", False, ), + max_audio_upload_size=data.get("max_audio_upload_size", "100MB"), ) @@ -1087,6 +1097,8 @@ def _apply_env_overrides(self) -> None: self.server.preserve_mid_system_cache = ( preserve_mid_system_cache.strip().lower() in {"1", "true", "yes", "on"} ) + if max_audio_upload_size := os.getenv("OMLX_MAX_AUDIO_UPLOAD_SIZE"): + self.server.max_audio_upload_size = max_audio_upload_size # Model settings if model_dir := os.getenv("OMLX_MODEL_DIR"): @@ -1224,6 +1236,11 @@ def _apply_cli_overrides(self, args: Any, *, include_api_key: bool = True) -> No self.server.log_level = args.log_level if hasattr(args, "sse_keepalive_mode") and args.sse_keepalive_mode is not None: self.server.sse_keepalive_mode = args.sse_keepalive_mode + if ( + hasattr(args, "max_audio_upload_size") + and args.max_audio_upload_size is not None + ): + self.server.max_audio_upload_size = args.max_audio_upload_size # Model settings if hasattr(args, "model_dir") and args.model_dir is not None: @@ -1487,6 +1504,13 @@ def validate(self) -> list[str]: f"(must be one of {valid_keepalive_modes})" ) + try: + audio_upload_size = parse_size(self.server.max_audio_upload_size) + if audio_upload_size <= 0: + errors.append("max_audio_upload_size must be positive") + except (AttributeError, TypeError, ValueError) as e: + errors.append(f"Invalid max_audio_upload_size: {e}") + # Memory guard tier validation if self.memory.memory_guard_tier not in VALID_MEMORY_GUARD_TIERS: errors.append( diff --git a/tests/test_admin_server_aliases.py b/tests/test_admin_server_aliases.py index e4a626fec5..5f6c4b8e85 100644 --- a/tests/test_admin_server_aliases.py +++ b/tests/test_admin_server_aliases.py @@ -574,6 +574,7 @@ def test_returns_gdn_split_settings(self): gs = GlobalSettings() gs.cache.gdn_ssd_split_enabled = True gs.cache.gdn_ssd_pending_max_size = "768MB" + gs.server.max_audio_upload_size = "500MB" memory_info = { "total_bytes": 16 * 1024**3, @@ -599,6 +600,40 @@ def test_returns_gdn_split_settings(self): assert result["cache"]["gdn_ssd_split_enabled"] is True assert result["cache"]["gdn_snapshot_storage"] == "ssd_sidecar" assert result["cache"]["gdn_ssd_pending_max_size"] == "768MB" + assert result["server"]["max_audio_upload_size"] == "500MB" + + +class TestUpdateGlobalSettingsAudioUpload: + """update_global_settings: persist the audio upload size cap.""" + + def test_saves_max_audio_upload_size(self): + gs = _make_global_settings() + gs.server.max_audio_upload_size = "100MB" + request = GlobalSettingsRequest(max_audio_upload_size="250MB") + + with _patched_global_settings(gs): + result = asyncio.run( + admin_routes.update_global_settings(request=request, is_admin=True) + ) + + assert result["success"] is True + assert "max_audio_upload_size" in result["runtime_applied"] + assert gs.server.max_audio_upload_size == "250MB" + gs.save.assert_called_once() + + def test_rejects_invalid_max_audio_upload_size(self): + gs = _make_global_settings() + request = GlobalSettingsRequest(max_audio_upload_size="bogus") + + with _patched_global_settings(gs): + with pytest.raises(HTTPException) as exc_info: + asyncio.run( + admin_routes.update_global_settings(request=request, is_admin=True) + ) + + assert exc_info.value.status_code == 400 + assert "max_audio_upload_size" in exc_info.value.detail + gs.save.assert_not_called() class TestApplyCacheSettingsRuntimeGdn: diff --git a/tests/test_audio_stt.py b/tests/test_audio_stt.py index cbfc1485c4..de7d834bd0 100644 --- a/tests/test_audio_stt.py +++ b/tests/test_audio_stt.py @@ -265,6 +265,87 @@ def server_audio_client(): # --------------------------------------------------------------------------- +class TestAudioUploadLimitSettings: + """_max_audio_upload_bytes() against the settings singleton. + + Snapshot/restore so reset_settings() here cannot leak into later tests. + """ + + @pytest.fixture(autouse=True) + def restore_global_settings(self): + import omlx.settings as settings_mod + + snapshot = settings_mod._global_settings + try: + yield + finally: + settings_mod._global_settings = snapshot + + def test_uninitialized_settings_keep_default_limit(self): + """Without init_settings(), the 100MB default still applies.""" + from omlx.api.audio_routes import ( + MAX_AUDIO_UPLOAD_BYTES, + _max_audio_upload_bytes, + ) + from omlx.settings import reset_settings + + reset_settings() + assert _max_audio_upload_bytes() == MAX_AUDIO_UPLOAD_BYTES + assert MAX_AUDIO_UPLOAD_BYTES == 100 * 1024 * 1024 + + def test_reads_limit_from_initialized_settings(self, tmp_path): + """init_settings() with a CLI override is what _read_upload enforces.""" + from argparse import Namespace + + from omlx.api.audio_routes import _max_audio_upload_bytes + from omlx.settings import init_settings, reset_settings + + reset_settings() + init_settings( + base_path=tmp_path, + cli_args=Namespace(max_audio_upload_size="2MB"), + ) + assert _max_audio_upload_bytes() == 2 * 1024 * 1024 + + def test_invalid_configured_size_warns_and_falls_back(self, caplog): + """Garbage settings.json/env values log a warning instead of failing silent.""" + from omlx.api.audio_routes import ( + MAX_AUDIO_UPLOAD_BYTES, + _max_audio_upload_bytes, + ) + from omlx.settings import ServerSettings + + bogus = ServerSettings(max_audio_upload_size="bogus") + with ( + patch( + "omlx.settings.get_settings", + return_value=type("GS", (), {"server": bogus})(), + ), + caplog.at_level("WARNING", logger="omlx.api.audio_routes"), + ): + assert _max_audio_upload_bytes() == MAX_AUDIO_UPLOAD_BYTES + assert "Invalid max_audio_upload_size" in caplog.text + + def test_non_positive_configured_size_warns_and_falls_back(self, caplog): + """0MB parses cleanly but would reject every upload; fall back instead.""" + from omlx.api.audio_routes import ( + MAX_AUDIO_UPLOAD_BYTES, + _max_audio_upload_bytes, + ) + from omlx.settings import ServerSettings + + zero = ServerSettings(max_audio_upload_size="0MB") + with ( + patch( + "omlx.settings.get_settings", + return_value=type("GS", (), {"server": zero})(), + ), + caplog.at_level("WARNING", logger="omlx.api.audio_routes"), + ): + assert _max_audio_upload_bytes() == MAX_AUDIO_UPLOAD_BYTES + assert "Invalid max_audio_upload_size" in caplog.text + + class TestSTTEndpointBasic: """Core STT endpoint behaviour.""" @@ -314,6 +395,36 @@ def test_engine_loaded_via_pool(self, server_audio_client): ) mock_pool.get_engine.assert_awaited() + def test_upload_exceeding_limit_returns_413(self, server_audio_client): + """A payload larger than the resolved limit is rejected with 413.""" + client, _ = server_audio_client + oversized = b"\x00" * 2048 + with patch( + "omlx.api.audio_routes._max_audio_upload_bytes", + return_value=1024, + ): + response = client.post( + "/v1/audio/transcriptions", + files={"file": ("audio.wav", oversized, "audio/wav")}, + data={"model": "whisper-tiny"}, + ) + assert response.status_code == 413 + assert "1024" in response.json()["detail"] + + def test_upload_within_raised_limit_returns_200(self, server_audio_client): + """Raising the limit allows an upload that the default cap would reject.""" + client, _ = server_audio_client + with patch( + "omlx.api.audio_routes._max_audio_upload_bytes", + return_value=len(TINY_WAV) + 1, + ): + response = client.post( + "/v1/audio/transcriptions", + files={"file": ("audio.wav", TINY_WAV, "audio/wav")}, + data={"model": "whisper-tiny"}, + ) + assert response.status_code == 200 + def test_language_parameter_accepted(self, server_audio_client): """language= form field is accepted without error.""" client, _ = server_audio_client diff --git a/tests/test_cli.py b/tests/test_cli.py index dae9e7dd8c..4367b94448 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -260,6 +260,9 @@ def test_serve_has_scheduler_options(self): ) assert "--max-concurrent-requests" in result.stdout assert "--embedding-batch-size" in result.stdout + assert "--max-audio-upload-size" in result.stdout + assert "settings.json" in result.stdout + assert "Default: 100MB" not in result.stdout def test_serve_has_cache_options(self): """Test that serve command has cache options.""" @@ -933,6 +936,7 @@ def _make_serve_args(tmp_path, host="127.0.0.1", port=8000, **overrides): "port": port, "log_level": None, "sse_keepalive_mode": None, + "max_audio_upload_size": None, "max_concurrent_requests": None, "embedding_batch_size": None, "memory_guard": None, @@ -1215,6 +1219,7 @@ def _make_args(**kwargs): "host": None, "log_level": None, "sse_keepalive_mode": None, + "max_audio_upload_size": None, "max_concurrent_requests": None, "embedding_batch_size": None, "memory_guard": None, @@ -1291,6 +1296,7 @@ def test_hf_cache_explicit(self): ("field", "value"), [ ("sse_keepalive_mode", "off"), + ("max_audio_upload_size", "250MB"), ("max_concurrent_requests", 2), ("paged_ssd_cache_dir", "/tmp/cache"), ("paged_ssd_cache_max_size", "2GB"), diff --git a/tests/test_settings.py b/tests/test_settings.py index a5078eb8c9..9e608f1d6b 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -53,6 +53,8 @@ def test_defaults(self): assert settings.burst_decode_mode == "balanced" assert settings.preserve_mid_system_cache is True assert settings.distributed_inference_enabled is False + assert settings.max_audio_upload_size == "100MB" + assert settings.max_audio_upload_bytes() == 100 * 1024 * 1024 def test_custom_values(self): """Test custom values.""" @@ -82,6 +84,7 @@ def test_to_dict(self): "burst_decode_mode": "balanced", "preserve_mid_system_cache": True, "distributed_inference_enabled": False, + "max_audio_upload_size": "100MB", } def test_from_dict_distributed_inference_is_opt_in(self): @@ -129,6 +132,25 @@ def test_from_dict_auto_start_on_launch(self): assert settings.auto_start_on_launch is False assert settings.to_dict()["auto_start_on_launch"] is False + def test_from_dict_max_audio_upload_size(self): + """max_audio_upload_size round-trips through from_dict / to_dict.""" + settings = ServerSettings.from_dict({"max_audio_upload_size": "500MB"}) + assert settings.max_audio_upload_size == "500MB" + assert settings.max_audio_upload_bytes() == 500 * 1024 * 1024 + assert settings.to_dict()["max_audio_upload_size"] == "500MB" + + def test_from_dict_max_audio_upload_size_default(self): + """A settings.json without max_audio_upload_size keeps the 100MB default.""" + settings = ServerSettings.from_dict({}) + assert settings.max_audio_upload_size == "100MB" + + def test_max_audio_upload_bytes_rejects_non_positive(self): + """0MB / negative sizes parse as integers but are not usable limits.""" + with pytest.raises(ValueError, match="must be positive"): + ServerSettings(max_audio_upload_size="0MB").max_audio_upload_bytes() + with pytest.raises(ValueError, match="must be positive"): + ServerSettings(max_audio_upload_size="-1MB").max_audio_upload_bytes() + def test_from_dict(self): """Test creation from dictionary.""" data = {"host": "0.0.0.0", "port": 9000, "log_level": "debug"} @@ -1434,6 +1456,25 @@ def test_validate_valid_sse_keepalive_modes(self): errors = settings.validate() assert errors == [] + def test_validate_invalid_max_audio_upload_size(self): + """Validation rejects unparseable or non-positive audio upload limits.""" + settings = GlobalSettings() + settings.server.max_audio_upload_size = "bogus" + errors = settings.validate() + assert any("max_audio_upload_size" in e for e in errors) + + settings = GlobalSettings() + settings.server.max_audio_upload_size = "0MB" + errors = settings.validate() + assert any("max_audio_upload_size" in e for e in errors) + + def test_validate_valid_max_audio_upload_size(self): + """Validation accepts human-readable audio upload sizes.""" + settings = GlobalSettings() + settings.server.max_audio_upload_size = "250MB" + errors = settings.validate() + assert not any("max_audio_upload_size" in e for e in errors) + def test_validate_memory_guard_tier_valid(self): """Test validation accepts each known tier.""" for tier in ("safe", "balanced", "aggressive"): @@ -1644,6 +1685,30 @@ def test_env_override_server(self): assert settings.server.port == 9999 assert settings.server.log_level == "debug" + def test_env_override_max_audio_upload_size(self): + """OMLX_MAX_AUDIO_UPLOAD_SIZE overrides the default 100MB cap.""" + with tempfile.TemporaryDirectory() as tmpdir: + with patch.dict( + os.environ, + {"OMLX_MAX_AUDIO_UPLOAD_SIZE": "250MB"}, + clear=False, + ): + settings = GlobalSettings.load(base_path=tmpdir) + assert settings.server.max_audio_upload_size == "250MB" + assert settings.server.max_audio_upload_bytes() == 250 * 1024 * 1024 + + def test_cli_override_max_audio_upload_size(self): + """--max-audio-upload-size is applied via CLI overrides.""" + from argparse import Namespace + + with tempfile.TemporaryDirectory() as tmpdir: + settings = GlobalSettings.load( + base_path=tmpdir, + cli_args=Namespace(max_audio_upload_size="500MB"), + ) + assert settings.server.max_audio_upload_size == "500MB" + assert settings.server.max_audio_upload_bytes() == 500 * 1024 * 1024 + def test_env_override_model(self): """Test environment variable override for model settings.""" with tempfile.TemporaryDirectory() as tmpdir: From 2e3781adf7b05ebd4ed3dab3a1fdf26ef9938a55 Mon Sep 17 00:00:00 2001 From: jundot Date: Thu, 27 Aug 2026 10:21:00 +0900 Subject: [PATCH 002/132] fix(audio): finish configurable upload limit support (#3160) --- apps/omlx-mac/Resources/Localizable.xcstrings | 72 +++++++++++++++++++ .../AppView/Screens/ServerScreen.swift | 23 ++++-- .../AppView/ViewModels/ServerScreenVM.swift | 43 +++++++++++ .../Sources/Net/DTO/GlobalSettingsDTO.swift | 3 + .../GlobalSettingsSamplingTests.swift | 27 +++++++ .../ServerScreenVMStorageDiffTests.swift | 20 ++++++ omlx/admin/i18n/en.json | 3 + omlx/admin/i18n/es.json | 3 + omlx/admin/i18n/fr.json | 3 + omlx/admin/i18n/ja.json | 3 + omlx/admin/i18n/ko.json | 3 + omlx/admin/i18n/pt-BR.json | 3 + omlx/admin/i18n/ru.json | 3 + omlx/admin/i18n/zh-TW.json | 3 + omlx/admin/i18n/zh.json | 3 + omlx/admin/static/js/dashboard.js | 4 +- omlx/admin/templates/dashboard/_settings.html | 20 ++++++ omlx/config.py | 6 +- tests/test_admin_audio_upload_ui.py | 44 ++++++++++++ tests/test_admin_server_aliases.py | 5 +- tests/test_audio_stt.py | 2 +- tests/test_config.py | 8 +++ 22 files changed, 295 insertions(+), 9 deletions(-) create mode 100644 tests/test_admin_audio_upload_ui.py diff --git a/apps/omlx-mac/Resources/Localizable.xcstrings b/apps/omlx-mac/Resources/Localizable.xcstrings index 3e8efc8978..f431fb44c5 100644 --- a/apps/omlx-mac/Resources/Localizable.xcstrings +++ b/apps/omlx-mac/Resources/Localizable.xcstrings @@ -17102,6 +17102,54 @@ } } }, + "server.advanced.max_audio_upload_size" : { + "comment" : "Advanced row label for the audio upload size limit", + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Maximum Audio Upload Size" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Максимальный размер загрузки аудио" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "最大音频上传大小" + } + } + } + }, + "server.advanced.max_audio_upload_size.sub" : { + "comment" : "Sublabel describing the audio upload size limit", + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Maximum file size accepted by audio transcription and processing endpoints. Higher values can increase memory use for concurrent requests." + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Максимальный размер файла для расшифровки и обработки аудио. Большие значения могут увеличить использование памяти при одновременных запросах." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "音频转录和处理接口接受的最大文件大小。较大的值可能会增加并发请求的内存使用量。" + } + } + } + }, "server.advanced.sse_keepalive" : { "comment" : "Advanced row label for the SSE keep-alive mode picker", "extractionState" : "manual", @@ -17342,6 +17390,30 @@ } } }, + "server.error.audio_upload_size_invalid" : { + "comment" : "Server screen error when the audio upload size is invalid", + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Maximum Audio Upload Size must be a positive value such as 100MB or 1GB." + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Максимальный размер загрузки аудио должен быть положительным значением, например 100MB или 1GB." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "最大音频上传大小必须是正值,例如 100MB 或 1GB。" + } + } + } + }, "server.error.base_path_empty" : { "comment" : "Server screen error when Base Path is empty on Apply", "extractionState" : "manual", diff --git a/apps/omlx-mac/Sources/AppView/Screens/ServerScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/ServerScreen.swift index 406c82c487..c2e03561c6 100644 --- a/apps/omlx-mac/Sources/AppView/Screens/ServerScreen.swift +++ b/apps/omlx-mac/Sources/AppView/Screens/ServerScreen.swift @@ -640,10 +640,10 @@ private struct APIEndpointsList: View { // MARK: - Advanced disclosure /// Phase 4 — Server identity / protocol knobs that the average user never -/// touches: `server_aliases` (extra host names the server identifies as for -/// cookie + host-header purposes) and `sse_keepalive_mode`. Hidden behind a -/// chevron so they don't crowd the main ServerScreen surface, but rendered -/// inline (not in a popover) so power users can scroll-find them. +/// touches: request limits, `server_aliases` (extra host names the server +/// identifies as for cookie + host-header purposes), and SSE keep-alive. +/// Hidden behind a chevron so they don't crowd the main ServerScreen surface, +/// but rendered inline (not in a popover) so power users can scroll-find them. private struct ServerAdvancedSection: View { @Bindable var vm: ServerScreenVM @@ -683,6 +683,21 @@ private struct ServerAdvancedSection: View { if expanded { ListGroup { + Row( + label: String(localized: "server.advanced.max_audio_upload_size", + defaultValue: "Maximum Audio Upload Size", + comment: "Advanced row label for the audio upload size limit"), + sublabel: String(localized: "server.advanced.max_audio_upload_size.sub", + defaultValue: "Maximum file size accepted by audio transcription and processing endpoints. Higher values can increase memory use for concurrent requests.", + comment: "Sublabel describing the audio upload size limit") + ) { + TextInput( + text: $vm.maxAudioUploadSizeText, + placeholder: "100MB", + mono: true, + width: 130 + ) + } Row( label: String(localized: "server.advanced.sse_keepalive", defaultValue: "SSE Keep-Alive Mode", diff --git a/apps/omlx-mac/Sources/AppView/ViewModels/ServerScreenVM.swift b/apps/omlx-mac/Sources/AppView/ViewModels/ServerScreenVM.swift index a9a97c1c5a..15ba43abf1 100644 --- a/apps/omlx-mac/Sources/AppView/ViewModels/ServerScreenVM.swift +++ b/apps/omlx-mac/Sources/AppView/ViewModels/ServerScreenVM.swift @@ -10,6 +10,7 @@ final class ServerScreenVM { // Phase 4 — Advanced disclosure. var sseKeepaliveMode: String = "chunk" + var maxAudioUploadSizeText: String = "100MB" /// Comma-separated text shown in the input. Parsed to `[String]` on save /// so the user can edit incrementally without intermediate trips to the /// server. Empty string clears all aliases. @@ -50,6 +51,7 @@ final class ServerScreenVM { private var baselineSamplingTopKText: String = "0" private var baselineSamplingRepetitionPenaltyText: String = "1.0" private var baselineServerAliasesText: String = "" + private var baselineMaxAudioUploadSizeText: String = "100MB" private var baselineModelDirs: [String] = [] private var baselineHfCacheEnabled: Bool = true @@ -70,6 +72,7 @@ final class ServerScreenVM { self.effectiveHost = AppConfig.connectableHost(for: dto.server.host) self.effectivePort = dto.server.port self.sseKeepaliveMode = dto.server.sseKeepaliveMode ?? "chunk" + self.maxAudioUploadSizeText = dto.server.maxAudioUploadSize ?? "100MB" self.serverAliasesText = dto.server.serverAliases.joined(separator: ", ") let modelDirs = Self.cleanedModelDirs( dto.model?.modelDirs ?? dto.model?.modelDir.map { [$0] } ?? [] @@ -108,6 +111,7 @@ final class ServerScreenVM { baselineSamplingTopKText = t(samplingTopKText) baselineSamplingRepetitionPenaltyText = t(samplingRepetitionPenaltyText) baselineServerAliasesText = serverAliasesText + baselineMaxAudioUploadSizeText = t(maxAudioUploadSizeText) baselineModelDirs = Self.normalizedModelDirs(from: modelDirTexts) baselineHfCacheEnabled = hfCacheEnabled } @@ -126,6 +130,7 @@ final class ServerScreenVM { if t(samplingTopKText) != baselineSamplingTopKText { return true } if t(samplingRepetitionPenaltyText) != baselineSamplingRepetitionPenaltyText { return true } if parseAliases(serverAliasesText) != parseAliases(baselineServerAliasesText) { return true } + if t(maxAudioUploadSizeText) != baselineMaxAudioUploadSizeText { return true } if hfCacheEnabled != baselineHfCacheEnabled { return true } return hasPendingStorageChanges(services: services) } @@ -206,6 +211,18 @@ final class ServerScreenVM { } patch.samplingRepetitionPenalty = v } + if t(maxAudioUploadSizeText) != baselineMaxAudioUploadSizeText { + let value = t(maxAudioUploadSizeText) + guard Self.isValidAudioUploadSize(value) else { + self.lastError = String( + localized: "server.error.audio_upload_size_invalid", + defaultValue: "Maximum Audio Upload Size must be a positive value such as 100MB or 1GB.", + comment: "Server screen error when the audio upload size is invalid" + ) + return + } + patch.maxAudioUploadSize = value + } let newAliases = parseAliases(serverAliasesText) if newAliases != parseAliases(baselineServerAliasesText) { @@ -239,6 +256,7 @@ final class ServerScreenVM { || patch.samplingTopP != nil || patch.samplingTopK != nil || patch.samplingRepetitionPenalty != nil + || patch.maxAudioUploadSize != nil || patch.serverAliases != nil || patch.hfCacheEnabled != nil || patch.modelDirs != nil @@ -317,6 +335,31 @@ final class ServerScreenVM { return parts.filter { seen.insert($0).inserted } } + /// Mirror the server's human-readable size grammar closely enough to + /// reject incomplete edits before sending a multi-field settings patch. + static func isValidAudioUploadSize(_ raw: String) -> Bool { + let text = raw + .trimmingCharacters(in: .whitespacesAndNewlines) + .uppercased() + let units: [(suffix: String, multiplier: Double)] = [ + ("TB", 1024 * 1024 * 1024 * 1024), + ("GB", 1024 * 1024 * 1024), + ("MB", 1024 * 1024), + ("KB", 1024), + ("B", 1), + ] + + for unit in units where text.hasSuffix(unit.suffix) { + let number = String(text.dropLast(unit.suffix.count)) + guard let value = Double(number), value.isFinite else { return false } + let bytes = value * unit.multiplier + return bytes.isFinite && bytes >= 1 + } + + guard let bytes = Int(text) else { return false } + return bytes > 0 + } + func modelDirText(at index: Int) -> String { guard modelDirTexts.indices.contains(index) else { return "" } return modelDirTexts[index] diff --git a/apps/omlx-mac/Sources/Net/DTO/GlobalSettingsDTO.swift b/apps/omlx-mac/Sources/Net/DTO/GlobalSettingsDTO.swift index c0f40bb20a..f2fe269944 100644 --- a/apps/omlx-mac/Sources/Net/DTO/GlobalSettingsDTO.swift +++ b/apps/omlx-mac/Sources/Net/DTO/GlobalSettingsDTO.swift @@ -58,6 +58,7 @@ struct GlobalSettingsDTO: Codable, Equatable, Sendable { let serverAliases: [String] let sseKeepaliveMode: String? let autoStartOnLaunch: Bool? + let maxAudioUploadSize: String? } struct ModelSettings: Codable, Equatable, Sendable { @@ -212,6 +213,8 @@ struct GlobalSettingsPatch: Encodable, Equatable, Sendable { /// `"off"`. Server rejects anything else with a 400. var sseKeepaliveMode: String? = nil var autoStartOnLaunch: Bool? = nil + /// Human-readable cap such as `100MB` or `1GB`. Applied immediately. + var maxAudioUploadSize: String? = nil // Claude Code (PR 9) var claudeCodeContextScalingEnabled: Bool? = nil diff --git a/apps/omlx-mac/Tests/oMLXTests/GlobalSettingsSamplingTests.swift b/apps/omlx-mac/Tests/oMLXTests/GlobalSettingsSamplingTests.swift index 603bf33a36..46f1d0ce59 100644 --- a/apps/omlx-mac/Tests/oMLXTests/GlobalSettingsSamplingTests.swift +++ b/apps/omlx-mac/Tests/oMLXTests/GlobalSettingsSamplingTests.swift @@ -201,4 +201,31 @@ final class GlobalSettingsSamplingTests: XCTestCase { XCTAssertTrue(str.contains("\"port\":9000")) XCTAssertFalse(str.contains("sampling_")) } + + func testServerDecodesAudioUploadSize() throws { + let json = """ + { + "server": { + "host": "127.0.0.1", + "port": 8080, + "log_level": "info", + "server_aliases": [], + "max_audio_upload_size": "500MB" + } + } + """.data(using: .utf8)! + + let dto = try decoder.decode(GlobalSettingsDTO.self, from: json) + XCTAssertEqual(dto.server.maxAudioUploadSize, "500MB") + } + + func testPatchEncodesAudioUploadSizeAsFlatSnakeCaseKey() throws { + var patch = GlobalSettingsPatch() + patch.maxAudioUploadSize = "1GB" + + let data = try encoder.encode(patch) + let json = try JSONSerialization.jsonObject(with: data) as! [String: Any] + + XCTAssertEqual(json["max_audio_upload_size"] as? String, "1GB") + } } diff --git a/apps/omlx-mac/Tests/oMLXTests/ServerScreenVMStorageDiffTests.swift b/apps/omlx-mac/Tests/oMLXTests/ServerScreenVMStorageDiffTests.swift index 5d2c59c030..144490c4de 100644 --- a/apps/omlx-mac/Tests/oMLXTests/ServerScreenVMStorageDiffTests.swift +++ b/apps/omlx-mac/Tests/oMLXTests/ServerScreenVMStorageDiffTests.swift @@ -228,4 +228,24 @@ final class ServerScreenVMStorageDiffTests: XCTestCase { XCTAssertFalse(vm.autoStartOnLaunch) } + + func testAudioUploadSizeValidation() { + for valid in ["1B", "100MB", "1.5GB", "1024"] { + XCTAssertTrue(ServerScreenVM.isValidAudioUploadSize(valid), valid) + } + for invalid in ["", "0MB", "-1MB", "100 MB", "infMB", "bogus"] { + XCTAssertFalse(ServerScreenVM.isValidAudioUploadSize(invalid), invalid) + } + } + + func testAudioUploadChangeEnablesApply() { + let services = makeServices(basePath: "/Users/Fido/.omlx", + modelDir: "/Users/Fido/.omlx/models") + let vm = ServerScreenVM() + vm.basePathText = "/Users/Fido/.omlx" + vm.modelDirTexts = ["/Users/Fido/.omlx/models"] + vm.maxAudioUploadSizeText = "250MB" + + XCTAssertTrue(vm.hasPendingServerChanges(services: services)) + } } diff --git a/omlx/admin/i18n/en.json b/omlx/admin/i18n/en.json index f42172c732..4f60616176 100644 --- a/omlx/admin/i18n/en.json +++ b/omlx/admin/i18n/en.json @@ -519,6 +519,9 @@ "settings.advanced.gdn_sidecar_state_precision_bf16": "BF16", "settings.advanced.gdn_sidecar_state_precision_int8": "Int8 (row-wise)", "settings.advanced.gdn_sidecar_state_precision_rht_int8": "RHT + int8 (row-wise)", + "settings.advanced.uploads": "Uploads", + "settings.advanced.max_audio_upload_size": "Maximum Audio Upload Size", + "settings.advanced.max_audio_upload_size_hint": "Maximum file size accepted by audio transcription and processing endpoints. Higher values can increase memory use for concurrent requests.", "settings.advanced.streaming": "Streaming", "settings.advanced.sse_keepalive_mode": "SSE Keepalive Mode", "settings.advanced.sse_keepalive_mode_hint": "How streaming HTTP connections stay alive during long prefills. 'Chunk' is most compatible (default). Switch to 'Comment' for the legacy ': keep-alive' format, or 'Off' to disable.", diff --git a/omlx/admin/i18n/es.json b/omlx/admin/i18n/es.json index ecd5756c36..d28f80073c 100644 --- a/omlx/admin/i18n/es.json +++ b/omlx/admin/i18n/es.json @@ -519,6 +519,9 @@ "settings.advanced.gdn_sidecar_state_precision_bf16": "BF16", "settings.advanced.gdn_sidecar_state_precision_int8": "Int8 (row-wise)", "settings.advanced.gdn_sidecar_state_precision_rht_int8": "RHT + int8 (row-wise)", + "settings.advanced.uploads": "Uploads", + "settings.advanced.max_audio_upload_size": "Maximum Audio Upload Size", + "settings.advanced.max_audio_upload_size_hint": "Maximum file size accepted by audio transcription and processing endpoints. Higher values can increase memory use for concurrent requests.", "settings.advanced.streaming": "Streaming", "settings.advanced.sse_keepalive_mode": "SSE Keepalive Mode", "settings.advanced.sse_keepalive_mode_hint": "How streaming HTTP connections stay alive during long prefills. 'Chunk' is most compatible (default). Switch to 'Comment' for the legacy ': keep-alive' format, or 'Off' to disable.", diff --git a/omlx/admin/i18n/fr.json b/omlx/admin/i18n/fr.json index a05e4c9b46..b0606fcf78 100644 --- a/omlx/admin/i18n/fr.json +++ b/omlx/admin/i18n/fr.json @@ -519,6 +519,9 @@ "settings.advanced.gdn_sidecar_state_precision_bf16": "BF16", "settings.advanced.gdn_sidecar_state_precision_int8": "Int8 (row-wise)", "settings.advanced.gdn_sidecar_state_precision_rht_int8": "RHT + int8 (row-wise)", + "settings.advanced.uploads": "Uploads", + "settings.advanced.max_audio_upload_size": "Maximum Audio Upload Size", + "settings.advanced.max_audio_upload_size_hint": "Maximum file size accepted by audio transcription and processing endpoints. Higher values can increase memory use for concurrent requests.", "settings.advanced.streaming": "Streaming", "settings.advanced.sse_keepalive_mode": "SSE Keepalive Mode", "settings.advanced.sse_keepalive_mode_hint": "How streaming HTTP connections stay alive during long prefills. 'Chunk' is most compatible (default). Switch to 'Comment' for the legacy ': keep-alive' format, or 'Off' to disable.", diff --git a/omlx/admin/i18n/ja.json b/omlx/admin/i18n/ja.json index 87412f77ce..7f2039fbc1 100644 --- a/omlx/admin/i18n/ja.json +++ b/omlx/admin/i18n/ja.json @@ -519,6 +519,9 @@ "settings.advanced.gdn_sidecar_state_precision_bf16": "BF16", "settings.advanced.gdn_sidecar_state_precision_int8": "Int8 (row-wise)", "settings.advanced.gdn_sidecar_state_precision_rht_int8": "RHT + int8 (row-wise)", + "settings.advanced.uploads": "Uploads", + "settings.advanced.max_audio_upload_size": "Maximum Audio Upload Size", + "settings.advanced.max_audio_upload_size_hint": "Maximum file size accepted by audio transcription and processing endpoints. Higher values can increase memory use for concurrent requests.", "settings.advanced.streaming": "Streaming", "settings.advanced.sse_keepalive_mode": "SSE Keepalive Mode", "settings.advanced.sse_keepalive_mode_hint": "How streaming HTTP connections stay alive during long prefills. 'Chunk' is most compatible (default). Switch to 'Comment' for the legacy ': keep-alive' format, or 'Off' to disable.", diff --git a/omlx/admin/i18n/ko.json b/omlx/admin/i18n/ko.json index ce69bb27df..498d9c416e 100644 --- a/omlx/admin/i18n/ko.json +++ b/omlx/admin/i18n/ko.json @@ -519,6 +519,9 @@ "settings.advanced.gdn_sidecar_state_precision_bf16": "BF16", "settings.advanced.gdn_sidecar_state_precision_int8": "Int8(행 단위)", "settings.advanced.gdn_sidecar_state_precision_rht_int8": "RHT + int8(행 단위)", + "settings.advanced.uploads": "Uploads", + "settings.advanced.max_audio_upload_size": "Maximum Audio Upload Size", + "settings.advanced.max_audio_upload_size_hint": "Maximum file size accepted by audio transcription and processing endpoints. Higher values can increase memory use for concurrent requests.", "settings.advanced.streaming": "Streaming", "settings.advanced.sse_keepalive_mode": "SSE Keepalive Mode", "settings.advanced.sse_keepalive_mode_hint": "How streaming HTTP connections stay alive during long prefills. 'Chunk' is most compatible (default). Switch to 'Comment' for the legacy ': keep-alive' format, or 'Off' to disable.", diff --git a/omlx/admin/i18n/pt-BR.json b/omlx/admin/i18n/pt-BR.json index 5a2caf9328..61d5dac6a0 100644 --- a/omlx/admin/i18n/pt-BR.json +++ b/omlx/admin/i18n/pt-BR.json @@ -519,6 +519,9 @@ "settings.advanced.gdn_sidecar_state_precision_bf16": "BF16", "settings.advanced.gdn_sidecar_state_precision_int8": "Int8 (row-wise)", "settings.advanced.gdn_sidecar_state_precision_rht_int8": "RHT + int8 (row-wise)", + "settings.advanced.uploads": "Uploads", + "settings.advanced.max_audio_upload_size": "Maximum Audio Upload Size", + "settings.advanced.max_audio_upload_size_hint": "Maximum file size accepted by audio transcription and processing endpoints. Higher values can increase memory use for concurrent requests.", "settings.advanced.streaming": "Streaming", "settings.advanced.sse_keepalive_mode": "Modo SSE Keepalive", "settings.advanced.sse_keepalive_mode_hint": "Como as conexões HTTP de streaming permanecem ativas durante prefills longos. 'Chunk' é mais compatível (padrão). Mude para 'Comment' para o formato legado ': keep-alive', ou 'Off' para desativar.", diff --git a/omlx/admin/i18n/ru.json b/omlx/admin/i18n/ru.json index de4ce8a69c..844f11720e 100644 --- a/omlx/admin/i18n/ru.json +++ b/omlx/admin/i18n/ru.json @@ -519,6 +519,9 @@ "settings.advanced.gdn_sidecar_state_precision_bf16": "BF16", "settings.advanced.gdn_sidecar_state_precision_int8": "Int8 (row-wise)", "settings.advanced.gdn_sidecar_state_precision_rht_int8": "RHT + int8 (row-wise)", + "settings.advanced.uploads": "Uploads", + "settings.advanced.max_audio_upload_size": "Maximum Audio Upload Size", + "settings.advanced.max_audio_upload_size_hint": "Maximum file size accepted by audio transcription and processing endpoints. Higher values can increase memory use for concurrent requests.", "settings.advanced.streaming": "Стриминг", "settings.advanced.sse_keepalive_mode": "Режим keep-alive для SSE", "settings.advanced.sse_keepalive_mode_hint": "Определяет, как потоковые HTTP-соединения остаются активными во время долгого prefill. «Chunk» наиболее совместим (по умолчанию). Переключитесь на «Comment» для устаревшего формата «: keep-alive» или выберите «Off», чтобы отключить keep-alive.", diff --git a/omlx/admin/i18n/zh-TW.json b/omlx/admin/i18n/zh-TW.json index 787e339a29..b3ae1490b2 100644 --- a/omlx/admin/i18n/zh-TW.json +++ b/omlx/admin/i18n/zh-TW.json @@ -519,6 +519,9 @@ "settings.advanced.gdn_sidecar_state_precision_bf16": "BF16", "settings.advanced.gdn_sidecar_state_precision_int8": "Int8 (row-wise)", "settings.advanced.gdn_sidecar_state_precision_rht_int8": "RHT + int8 (row-wise)", + "settings.advanced.uploads": "Uploads", + "settings.advanced.max_audio_upload_size": "Maximum Audio Upload Size", + "settings.advanced.max_audio_upload_size_hint": "Maximum file size accepted by audio transcription and processing endpoints. Higher values can increase memory use for concurrent requests.", "settings.advanced.streaming": "串流", "settings.advanced.sse_keepalive_mode": "SSE 保持連線模式", "settings.advanced.sse_keepalive_mode_hint": "串流 HTTP 連線在長時間預填充期間如何保持連線。「Chunk」相容性最佳(預設)。切換為「Comment」使用舊版 ': keep-alive' 格式,或「關閉」以停用。", diff --git a/omlx/admin/i18n/zh.json b/omlx/admin/i18n/zh.json index a898c5b9ae..5d59d51df1 100644 --- a/omlx/admin/i18n/zh.json +++ b/omlx/admin/i18n/zh.json @@ -519,6 +519,9 @@ "settings.advanced.gdn_sidecar_state_precision_bf16": "BF16", "settings.advanced.gdn_sidecar_state_precision_int8": "Int8 (row-wise)", "settings.advanced.gdn_sidecar_state_precision_rht_int8": "RHT + int8 (row-wise)", + "settings.advanced.uploads": "Uploads", + "settings.advanced.max_audio_upload_size": "Maximum Audio Upload Size", + "settings.advanced.max_audio_upload_size_hint": "Maximum file size accepted by audio transcription and processing endpoints. Higher values can increase memory use for concurrent requests.", "settings.advanced.streaming": "流式传输", "settings.advanced.sse_keepalive_mode": "SSE 保活模式", "settings.advanced.sse_keepalive_mode_hint": "流式 HTTP 连接在长时间预填充期间如何保持连接。'Chunk' 兼容性最好(默认)。切换为 'Comment' 使用旧版 ': keep-alive' 格式,或 'Off' 禁用。", diff --git a/omlx/admin/static/js/dashboard.js b/omlx/admin/static/js/dashboard.js index 94ee35fff4..cc5a22d61e 100644 --- a/omlx/admin/static/js/dashboard.js +++ b/omlx/admin/static/js/dashboard.js @@ -121,7 +121,7 @@ // Global settings globalSettings: { base_path: '', - server: { host: '127.0.0.1', port: 8000, log_level: 'info', sse_keepalive_mode: 'chunk', burst_decode_mode: 'balanced', preserve_mid_system_cache: true, distributed_inference_enabled: false, distributed_inference_active: false }, + server: { host: '127.0.0.1', port: 8000, log_level: 'info', sse_keepalive_mode: 'chunk', burst_decode_mode: 'balanced', preserve_mid_system_cache: true, distributed_inference_enabled: false, distributed_inference_active: false, max_audio_upload_size: '100MB' }, model: { model_dirs: [''], model_fallback: false, hide_helper_models: false }, memory: { prefill_memory_guard: true, memory_guard_tier: 'balanced', memory_guard_custom_ceiling_gb: 0 }, scheduler: { max_concurrent_requests: 8, embedding_batch_size: 32, chunked_prefill: false, prefill_priority: 'context', decode_fairness: true }, @@ -6665,6 +6665,7 @@ const s = this.globalSettings; if (!s.server.host) errors.push('Host'); if (!s.server.port) errors.push('Port'); + if (!s.server.max_audio_upload_size) errors.push('Maximum Audio Upload Size'); if (!s.model.model_dirs || !s.model.model_dirs.some(d => d.trim())) errors.push('Model Directory'); if (!s.scheduler.max_concurrent_requests) errors.push('Max Concurrent Requests'); if (!s.scheduler.embedding_batch_size) errors.push('Embedding Batch Size'); @@ -6707,6 +6708,7 @@ burst_decode_mode: this.globalSettings.server.burst_decode_mode, preserve_mid_system_cache: this.globalSettings.server.preserve_mid_system_cache, distributed_inference_enabled: this.globalSettings.server.distributed_inference_enabled, + max_audio_upload_size: this.globalSettings.server.max_audio_upload_size, model_dirs: this.globalSettings.model.model_dirs.filter(d => d.trim()), model_fallback: this.globalSettings.model.model_fallback, hide_helper_models: this.globalSettings.model.hide_helper_models, diff --git a/omlx/admin/templates/dashboard/_settings.html b/omlx/admin/templates/dashboard/_settings.html index fb6bb2913b..786f057a23 100644 --- a/omlx/admin/templates/dashboard/_settings.html +++ b/omlx/admin/templates/dashboard/_settings.html @@ -970,6 +970,26 @@

{{ t('settings.gl + +
+
+ + {{ t('settings.advanced.uploads') }} +
+
+
+
+
+ +

{{ t('settings.advanced.max_audio_upload_size_hint') }}

+
+ +
+
+
diff --git a/omlx/config.py b/omlx/config.py index e8f08993d5..11dff78d43 100644 --- a/omlx/config.py +++ b/omlx/config.py @@ -10,6 +10,7 @@ """ import logging +import math import os from dataclasses import dataclass, field from pathlib import Path @@ -43,7 +44,10 @@ def parse_size(size_str: str) -> int: if size_str.endswith(unit): try: value = float(size_str[: -len(unit)]) - return int(value * multiplier) + byte_value = value * multiplier + if not math.isfinite(byte_value): + raise ValueError + return int(byte_value) except ValueError: pass diff --git a/tests/test_admin_audio_upload_ui.py b/tests/test_admin_audio_upload_ui.py new file mode 100644 index 0000000000..72277d2b2d --- /dev/null +++ b/tests/test_admin_audio_upload_ui.py @@ -0,0 +1,44 @@ +import json +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +SETTINGS_TEMPLATE = ROOT / "omlx/admin/templates/dashboard/_settings.html" +DASHBOARD_JS = ROOT / "omlx/admin/static/js/dashboard.js" + +AUDIO_UPLOAD_I18N_KEYS = { + "settings.advanced.uploads", + "settings.advanced.max_audio_upload_size", + "settings.advanced.max_audio_upload_size_hint", +} + + +def test_settings_template_exposes_audio_upload_limit_under_advanced_uploads(): + template = SETTINGS_TEMPLATE.read_text() + + advanced_start = template.index(" +
+
+
+ {{ t('modal.model_settings.qwen4_ple_ssd_offload') }} +

{{ t('modal.model_settings.qwen4_ple_ssd_offload_hint') }}

+
+ +
+

{{ t('modal.model_settings.qwen4_ple_ssd_offload_forced') }}

+
+
diff --git a/omlx/api/openai_models.py b/omlx/api/openai_models.py index f2b711dda9..d0df0743a7 100644 --- a/omlx/api/openai_models.py +++ b/omlx/api/openai_models.py @@ -34,13 +34,6 @@ class ImageURL(BaseModel): detail: Optional[str] = "auto" # "low", "high", "auto" -class VideoURL(BaseModel): - """Inline base64 video data URI for video-capable VLMs.""" - - url: str - fps: Optional[float] = 2.0 - - class InputAudio(BaseModel): """Audio input data for multimodal models (OpenAI format).""" @@ -76,7 +69,6 @@ class ContentPart(BaseModel): type: str # "text", "image_url", "input_audio", or "file" text: Optional[str] = None image_url: Optional[ImageURL] = None - video_url: Optional[VideoURL] = None input_audio: Optional[InputAudio] = None file: Optional[FileContent] = None diff --git a/omlx/api/utils.py b/omlx/api/utils.py index 51e084ddcb..34514a7cd8 100644 --- a/omlx/api/utils.py +++ b/omlx/api/utils.py @@ -8,6 +8,7 @@ import re from typing import Any, List +from ..exceptions import InvalidRequestError from .openai_models import Message # Model families whose chat templates consume message.reasoning_content directly. @@ -173,7 +174,7 @@ def _extract_text_from_content_list(content: list) -> str: def _extract_multimodal_content_list(content: list) -> list: """Extract text, image, and audio parts from a content array. - Keeps text, image_url, video_url, and input_audio items for VLM processing. + Keeps text, image_url, and input_audio items for VLM processing. Other content types (tool_use, thinking, refusal, etc.) are dropped. """ parts = [] @@ -240,13 +241,10 @@ def _extract_multimodal_content_list(content: list) -> list: } ) elif item_type in ("video_url", "input_video"): - video_value = item.get("video_url", item.get("input_video")) - if isinstance(video_value, str): - video_value = {"url": video_value} - if isinstance(video_value, dict) and video_value.get("url"): - parts.append( - {"type": "video_url", "video_url": video_value} - ) + raise InvalidRequestError( + "Video input is not supported by oMLX.", + field="messages", + ) return parts @@ -1269,7 +1267,7 @@ def extract_multimodal_content( elif isinstance(content, list): # Preserve image_url and input_audio parts for VLM processing multimodal_parts = _extract_multimodal_content_list(content) - multimodal_types = {"image_url", "video_url", "input_audio"} + multimodal_types = {"image_url", "input_audio"} has_multimodal = any( p.get("type") in multimodal_types for p in multimodal_parts ) diff --git a/omlx/cache/type_handlers.py b/omlx/cache/type_handlers.py index 9c36bd3491..0ef8f0c7d5 100644 --- a/omlx/cache/type_handlers.py +++ b/omlx/cache/type_handlers.py @@ -40,6 +40,9 @@ class CacheType(Enum): BATCH_POOLING_CACHE = "BatchPoolingCache" MINIMAX_M3_KVCACHE = "MiniMaxM3KVCache" MINIMAX_M3_BATCH_KVCACHE = "MiniMaxM3BatchKVCache" + QWEN4_QSA_KVCACHE = "QSAKVCache" + QWEN4_QSA_QUANTIZED_KVCACHE = "QSAQuantizedKVCache" + QWEN4_BATCH_QSA_KVCACHE = "BatchQSAKVCache" @dataclass @@ -1421,6 +1424,298 @@ def reconstruct_cache( return self.deserialize_state(tuple(elements), meta_state) +def _serialize_qsa_positions(position_ids: Any) -> Any: + """Normalize text/MRoPE positions to a fixed ``[B, C, S]`` layout.""" + if position_ids is None or not hasattr(position_ids, "ndim"): + return position_ids + if position_ids.ndim == 2: + return position_ids[:, None, :] + if position_ids.ndim == 3: + return position_ids.transpose(1, 0, 2) + raise ValueError( + "QSA position IDs must be [B, S] or [3, B, S], got " f"{position_ids.shape}." + ) + + +def _deserialize_qsa_positions(position_ids: Any) -> Any: + """Restore the model-facing text/MRoPE position layout.""" + if position_ids is None or not hasattr(position_ids, "ndim"): + return position_ids + if position_ids.ndim != 3: + raise ValueError( + "Serialized QSA position IDs must be [B, C, S], got " + f"{position_ids.shape}." + ) + if position_ids.shape[1] == 1: + return position_ids[:, 0, :] + return position_ids.transpose(1, 0, 2) + + +class Qwen4QSAKVCacheHandler(CacheTypeHandler): + """Handler for Qwen4 QSA caches with raw index keys and positions.""" + + @property + def cache_type(self) -> CacheType: + return CacheType.QWEN4_QSA_KVCACHE + + @property + def supports_block_slicing(self) -> bool: + return True + + def get_state_axis_info(self) -> tuple[CacheStateAxisInfo, ...]: + return ( + CacheStateAxisInfo("keys", 2, True), + CacheStateAxisInfo("values", 2, True), + CacheStateAxisInfo("index_keys", 1, True), + CacheStateAxisInfo("index_position_ids", 2, True), + ) + + def serialize_state(self, cache_obj: Any) -> tuple[Any, ...]: + keys, values, index_keys, position_ids = cache_obj.state + return ( + keys, + values, + index_keys, + _serialize_qsa_positions(position_ids), + ) + + def extract_state(self, cache_obj: Any) -> dict[str, Any]: + elements = self.serialize_state(cache_obj) + return { + "keys": elements[0], + "values": elements[1], + "index_keys": elements[2], + "index_position_ids": elements[3], + "states": elements, + "offset": getattr(cache_obj, "offset", 0), + "cache_type": self.cache_type.value, + } + + def get_seq_len(self, state: dict[str, Any]) -> int: + keys = state.get("keys") + return int(keys.shape[2]) if keys is not None else 0 + + def slice_state( + self, + state: dict[str, Any], + start_idx: int, + end_idx: int, + ) -> dict[str, Any] | None: + if not HAS_MLX: + return None + elements = state.get("states") + if elements is None: + elements = tuple( + state.get(info.name) for info in self.get_state_axis_info() + ) + seq_len = self.get_state_seq_len_from_tuple(tuple(elements)) + actual_end = min(end_idx, seq_len) + if seq_len <= 0 or start_idx >= actual_end: + return None + sliced = [] + for info, element in zip(self.get_state_axis_info(), elements): + if element is None: + sliced.append(None) + continue + slices = [slice(None)] * element.ndim + slices[info.sequence_axis] = slice(start_idx, actual_end) + sliced.append(element[tuple(slices)]) + return { + **{ + info.name: value + for info, value in zip(self.get_state_axis_info(), sliced) + }, + "states": tuple(sliced), + "cache_type": self.cache_type.value, + } + + def concatenate_states(self, states: list[dict[str, Any]]) -> dict[str, Any]: + if not HAS_MLX or not states: + return {} + grouped: list[list[Any]] = [[] for _ in self.get_state_axis_info()] + for state in states: + elements = state.get("states") + if elements is None: + elements = tuple( + state.get(info.name) for info in self.get_state_axis_info() + ) + for index, element in enumerate(elements): + if element is not None: + grouped[index].append(element) + concatenated = [] + for info, elements in zip(self.get_state_axis_info(), grouped): + concatenated.append( + mx.concatenate(elements, axis=info.sequence_axis) if elements else None + ) + return { + **{ + info.name: value + for info, value in zip(self.get_state_axis_info(), concatenated) + }, + "states": tuple(concatenated), + "cache_type": self.cache_type.value, + } + + def deserialize_state( + self, + elements: tuple[Any, ...], + meta_state: Any | None = None, + ) -> Any: + del meta_state + try: + from ..patches.mlx_vlm_qwen4_exp_compat import ( + apply_mlx_vlm_qwen4_exp_compat_patch, + ) + + apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp.language import QSAKVCache + except Exception as exc: # noqa: BLE001 + logger.error("Qwen4 QSAKVCache unavailable: %s", exc) + return None + + padded = tuple(elements) + (None,) * max(0, 4 - len(elements)) + keys, values, index_keys, position_ids = padded[:4] + cache = QSAKVCache() + cache.state = ( + keys, + values, + index_keys, + _deserialize_qsa_positions(position_ids), + ) + return cache + + def reconstruct_cache( + self, + state: dict[str, Any], + meta_state: tuple | None = None, + ) -> Any: + elements = state.get("states") + if elements is None: + elements = tuple( + state.get(info.name) for info in self.get_state_axis_info() + ) + return self.deserialize_state(tuple(elements), meta_state) + + +class Qwen4QSAQuantizedKVCacheHandler(Qwen4QSAKVCacheHandler): + """Store Qwen4 quantized QSA caches as dense APC-compatible blocks.""" + + @property + def cache_type(self) -> CacheType: + return CacheType.QWEN4_QSA_QUANTIZED_KVCACHE + + def serialize_state(self, cache_obj: Any) -> tuple[Any, ...]: + keys, values = cache_obj.dequantize_for_apc() + return ( + keys, + values, + cache_obj.index_keys, + _serialize_qsa_positions(cache_obj.index_position_ids), + ) + + +class Qwen4BatchQSAKVCacheHandler(CacheTypeHandler): + """Full-state handler for batched Qwen4 QSA caches.""" + + @property + def cache_type(self) -> CacheType: + return CacheType.QWEN4_BATCH_QSA_KVCACHE + + @property + def supports_block_slicing(self) -> bool: + return False + + def get_state_axis_info(self) -> tuple[CacheStateAxisInfo, ...]: + return ( + CacheStateAxisInfo("keys", 2, False), + CacheStateAxisInfo("values", 2, False), + CacheStateAxisInfo("offset", None, False), + CacheStateAxisInfo("left_padding", None, False), + CacheStateAxisInfo("index_keys", 1, False), + CacheStateAxisInfo("index_position_ids", 2, False), + ) + + def serialize_state(self, cache_obj: Any) -> tuple[Any, ...]: + kv_state, index_keys, position_ids = cache_obj.state + keys, values, offset, left_padding = kv_state + return ( + keys, + values, + offset, + left_padding, + index_keys, + _serialize_qsa_positions(position_ids), + ) + + def extract_state(self, cache_obj: Any) -> dict[str, Any]: + elements = self.serialize_state(cache_obj) + return { + **{ + info.name: value + for info, value in zip(self.get_state_axis_info(), elements) + }, + "states": elements, + "is_full_state": True, + "cache_type": self.cache_type.value, + } + + def get_seq_len(self, state: dict[str, Any]) -> int: + keys = state.get("keys") + return int(keys.shape[2]) if keys is not None else 0 + + def slice_state( + self, + state: dict[str, Any], + start_idx: int, + end_idx: int, + ) -> dict[str, Any] | None: + del start_idx, end_idx + return {**state, "is_full_state": True} + + def concatenate_states(self, states: list[dict[str, Any]]) -> dict[str, Any]: + return states[-1] if states else {} + + def deserialize_state( + self, + elements: tuple[Any, ...], + meta_state: Any | None = None, + ) -> Any: + del meta_state + try: + from ..patches.mlx_vlm_qwen4_exp_compat import ( + apply_mlx_vlm_qwen4_exp_compat_patch, + ) + + apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp.language import BatchQSAKVCache + except Exception as exc: # noqa: BLE001 + logger.error("Qwen4 BatchQSAKVCache unavailable: %s", exc) + return None + + padded = tuple(elements) + (None,) * max(0, 6 - len(elements)) + keys, values, offset, left_padding, index_keys, position_ids = padded[:6] + left_padding_arg = left_padding if left_padding is not None else [0] + cache = BatchQSAKVCache(left_padding_arg) + cache.state = ( + (keys, values, offset, left_padding_arg), + index_keys, + _deserialize_qsa_positions(position_ids), + ) + return cache + + def reconstruct_cache( + self, + state: dict[str, Any], + meta_state: tuple | None = None, + ) -> Any: + elements = state.get("states") + if elements is None: + elements = tuple( + state.get(info.name) for info in self.get_state_axis_info() + ) + return self.deserialize_state(tuple(elements), meta_state) + + # Default handler for unknown types - falls back to KVCache behavior class DefaultCacheHandler(KVCacheHandler): """Default handler that assumes KVCache-like behavior. diff --git a/omlx/cache/type_registry.py b/omlx/cache/type_registry.py index 2cc926d445..c2922d7166 100644 --- a/omlx/cache/type_registry.py +++ b/omlx/cache/type_registry.py @@ -18,6 +18,9 @@ KVCacheHandler, MiniMaxM3BatchKVCacheHandler, MiniMaxM3KVCacheHandler, + Qwen4BatchQSAKVCacheHandler, + Qwen4QSAKVCacheHandler, + Qwen4QSAQuantizedKVCacheHandler, RotatingKVCacheHandler, SizedArraysCache, ) @@ -73,6 +76,9 @@ class CacheTypeRegistry: "BatchPoolingCache": CacheType.BATCH_POOLING_CACHE, "MiniMaxM3KVCache": CacheType.MINIMAX_M3_KVCACHE, "MiniMaxM3BatchKVCache": CacheType.MINIMAX_M3_BATCH_KVCACHE, + "QSAKVCache": CacheType.QWEN4_QSA_KVCACHE, + "QSAQuantizedKVCache": CacheType.QWEN4_QSA_QUANTIZED_KVCACHE, + "BatchQSAKVCache": CacheType.QWEN4_BATCH_QSA_KVCACHE, } # Default handler instance @@ -263,6 +269,9 @@ def _initialize_default_handlers() -> None: CacheTypeRegistry.register(CacheListHandler()) CacheTypeRegistry.register(MiniMaxM3KVCacheHandler()) CacheTypeRegistry.register(MiniMaxM3BatchKVCacheHandler()) + CacheTypeRegistry.register(Qwen4QSAKVCacheHandler()) + CacheTypeRegistry.register(Qwen4QSAQuantizedKVCacheHandler()) + CacheTypeRegistry.register(Qwen4BatchQSAKVCacheHandler()) # Initialize handlers when module is imported diff --git a/omlx/engine/vlm.py b/omlx/engine/vlm.py index ab214a7193..73558a419e 100644 --- a/omlx/engine/vlm.py +++ b/omlx/engine/vlm.py @@ -1655,29 +1655,6 @@ def _load_vlm_sync(): self._model_name, trust_remote_code=self._trust_remote_code, ) - if _read_config_model_type(self._model_name) == QWEN4_EXP_MODEL_TYPE: - processor = loaded[1] - if not hasattr(processor, "video_processor"): - from mlx_vlm.models.qwen3_vl.processing_qwen3_vl import ( - Qwen3VLVideoProcessor, - ) - - image_processor = processor.image_processor - processor.video_processor = Qwen3VLVideoProcessor( - patch_size=getattr(image_processor, "patch_size", 16), - temporal_patch_size=getattr( - image_processor, "temporal_patch_size", 2 - ), - merge_size=getattr(image_processor, "merge_size", 2), - min_pixels=getattr( - image_processor, "min_pixels", 128 * 32 * 32 - ), - max_pixels=getattr( - image_processor, "max_pixels", 32 * 32 * 768 - ), - image_mean=getattr(image_processor, "image_mean", None), - image_std=getattr(image_processor, "image_std", None), - ) return loaded loop = asyncio.get_running_loop() @@ -2378,7 +2355,6 @@ def _format_messages_for_vlm_template( messages: list[dict[str, Any]], num_images: int, num_audios: int = 0, - num_videos: int = 0, ) -> tuple[list[dict[str, Any]], list[tuple[int, int]]]: """Format VLM messages with image/audio tokens on media-bearing user turns.""" from mlx_vlm.prompt_utils import extract_text_from_content, get_message_json @@ -2391,7 +2367,6 @@ def _format_messages_for_vlm_template( image_part_types = {"image", "image_url", "input_image"} audio_part_types = {"input_audio"} - video_part_types = {"video", "video_url", "input_video"} has_explicit_images = any( isinstance(msg, dict) and self._count_content_parts(msg.get("content"), image_part_types) > 0 @@ -2406,10 +2381,8 @@ def _format_messages_for_vlm_template( remaining_images = num_images remaining_audios = num_audios - remaining_videos = num_videos assigned_fallback_images = False assigned_fallback_audios = False - assigned_fallback_videos = False formatted_messages: list[dict[str, Any]] = [] image_message_ranges: list[tuple[int, int]] = [] @@ -2423,7 +2396,6 @@ def _format_messages_for_vlm_template( msg_num_images = 0 msg_num_audios = 0 - msg_num_videos = 0 if role == "user": explicit_images = self._count_content_parts( raw_content, image_part_types @@ -2431,9 +2403,6 @@ def _format_messages_for_vlm_template( explicit_audios = self._count_content_parts( raw_content, audio_part_types ) - explicit_videos = self._count_content_parts( - raw_content, video_part_types - ) if explicit_images > 0 and remaining_images > 0: msg_num_images = min(explicit_images, remaining_images) remaining_images -= msg_num_images @@ -2458,14 +2427,6 @@ def _format_messages_for_vlm_template( remaining_audios = 0 assigned_fallback_audios = True - if explicit_videos > 0 and remaining_videos > 0: - msg_num_videos = min(explicit_videos, remaining_videos) - remaining_videos -= msg_num_videos - elif remaining_videos > 0 and not assigned_fallback_videos: - msg_num_videos = remaining_videos - remaining_videos = 0 - assigned_fallback_videos = True - if msg_num_images > 0: image_message_ranges.append((idx, msg_num_images)) @@ -2493,15 +2454,10 @@ def _format_messages_for_vlm_template( skip_audio_token=role != "user" or msg_num_audios == 0, num_images=msg_num_images, num_audios=msg_num_audios, - video=( - ["inline-video"] * msg_num_videos - if msg_num_videos - else None - ), ) # Collapse text-only list content to plain string so that # simplified chat templates (without render_content macro) - # can handle it. Image/audio/video parts stay as list. + # can handle it. Image/audio parts stay as a list. fc = formatted.get("content") if isinstance(fc, list) and all( isinstance(p, dict) and p.get("type") == "text" for p in fc @@ -2594,8 +2550,6 @@ def _compute_vision_features( # Strategy 2: qwen-style (vision_tower + grid_thw) if model_type in _QWEN_VISION_MODELS: grid_thw = extra_model_inputs.get("image_grid_thw") - if grid_thw is None: - grid_thw = extra_model_inputs.get("video_grid_thw") if grid_thw is None: return None dtype = model.vision_tower.patch_embed.proj.weight.dtype @@ -2810,7 +2764,6 @@ def _prepare_vision_inputs( messages: list[dict[str, Any]], images: list[Any], audio: list | None = None, - videos: list | None = None, chat_template_kwargs: dict[str, Any] | None = None, tools: list[dict] | None = None, is_partial: bool | None = None, @@ -2861,7 +2814,6 @@ def _prepare_vision_inputs( num_images = len(images) num_audios = len(audio) if audio else 0 - num_videos = len(videos) if videos else 0 model_type = self.model_type or "" if model_type == COHERE2_MOE_MODEL_TYPE and ( @@ -2874,7 +2826,7 @@ def _prepare_vision_inputs( ) if model_type == QWEN4_EXP_MODEL_TYPE and num_audios > 0: raise InvalidRequestError( - "Qwen4-Exp supports text, image, and video input but not audio.", + "Qwen4-Exp supports text and image input but not audio.", field="messages", ) @@ -2907,7 +2859,6 @@ def _prepare_vision_inputs( messages, num_images=num_images, num_audios=num_audios, - num_videos=num_videos, ) ) except Exception as e: @@ -3013,14 +2964,11 @@ def _prepare_vision_inputs( self._processor, images=images if images else None, audio=audio if audio else None, - videos=videos if videos else None, prompts=[prompt] if isinstance(prompt, str) else prompt, ) input_ids = inputs["input_ids"] pixel_values = inputs.get("pixel_values") - if pixel_values is None and num_videos: - pixel_values = inputs.get("pixel_values_videos") attention_mask = inputs.get("attention_mask") image_cache_key_start = 0 @@ -3104,16 +3052,13 @@ def _prepare_vision_inputs( "input_ids", "attention_mask", "pixel_values", - "pixel_values_videos", ) and v is not None } # Check for any multimodal inputs: images or audio has_audio = "input_features" in extra_model_inputs - has_multimodal = ( - pixel_values is not None and (num_images > 0 or num_videos > 0) - ) or has_audio + has_multimodal = (pixel_values is not None and num_images > 0) or has_audio if has_multimodal: # Build call kwargs from extra_model_inputs (includes input_features @@ -4045,9 +3990,7 @@ def _process_chat_messages( Tuple of (prompt_or_token_ids, vlm_embeds, vlm_kwargs, image_hash) """ # Extract images from messages - text_messages, images, audio, videos = extract_images_from_messages( - messages, include_videos=True - ) + text_messages, images, audio = extract_images_from_messages(messages) ct_kwargs = kwargs.pop("chat_template_kwargs", None) partial = kwargs.pop("is_partial", None) @@ -4055,11 +3998,7 @@ def _process_chat_messages( # Keep VLM-capable models on one prompt-rendering path, even before the # first image arrives. Otherwise the conversation switches prompt families # on the first image-bearing turn and invalidates early prefix blocks. - vlm_messages = ( - self._apply_ocr_prompt(messages) - if images - else (messages if videos else text_messages) - ) + vlm_messages = self._apply_ocr_prompt(messages) if images else text_messages template_tools = convert_tools_for_template(tools) if tools else None ( token_ids, @@ -4072,13 +4011,12 @@ def _process_chat_messages( vlm_messages, images, audio=audio if audio else None, - videos=videos if videos else None, chat_template_kwargs=ct_kwargs, tools=template_tools, is_partial=partial, ) - if images or videos: + if images: # Free Metal intermediates from vision encoding. mx.synchronize() mx.clear_cache() diff --git a/omlx/engine_pool.py b/omlx/engine_pool.py index 7154fe1ece..ba7837c53e 100644 --- a/omlx/engine_pool.py +++ b/omlx/engine_pool.py @@ -14,6 +14,7 @@ from __future__ import annotations import asyncio +import copy import gc import json import logging @@ -348,6 +349,11 @@ def _entry_runtime_resident_size( base = self._entry_resident_size(entry) if base_size is None else base_size if self._distributed_deployment_for_entry(entry) is not None: return base + qwen4_offload, _, qwen4_estimate = self._qwen4_ple_offload_status( + entry, runtime_settings + ) + if qwen4_offload and qwen4_estimate is not None: + base = min(base, qwen4_estimate.mmap_bytes) extra = _qwen35_cpu_share_estimated_bytes(entry.model_path, runtime_settings) if extra is None: # An enabled CPU path with unreadable geometry must not silently @@ -367,6 +373,52 @@ def _entry_runtime_resident_size( ) return base + extra + def _qwen4_ple_offload_status( + self, + entry: EngineEntry, + settings: object | None, + ) -> tuple[bool, bool, object | None]: + """Resolve requested/forced Qwen4 PLE mmap mode for this process.""" + + model_type = (entry.config_model_type or "").replace("-", "_").lower() + if model_type != "qwen4_exp": + return False, False, None + try: + from .patches.mlx_vlm_qwen4_exp_compat.residency import ( + qwen4_exp_residency_estimate, + ) + + estimate = qwen4_exp_residency_estimate(entry.model_path) + except (OSError, TypeError, ValueError): + logger.debug( + "Could not inspect Qwen4-Exp PLE residency for %s", + entry.model_id, + exc_info=True, + ) + return False, False, None + ceiling = self._fallback_admission_ceiling() + if ceiling <= 0: + ceiling = self._current_ceiling() + forced = estimate.force_ssd_offload(ceiling) + requested = bool( + settings is not None and getattr(settings, "qwen4_ple_ssd_offload", False) + ) + return requested or forced, forced, estimate if estimate.supported else None + + def _effective_qwen4_model_settings( + self, + entry: EngineEntry, + settings: object | None, + ) -> object | None: + """Apply a forced mmap decision without mutating persisted settings.""" + + enabled, forced, _ = self._qwen4_ple_offload_status(entry, settings) + if not enabled or not forced or settings is None: + return settings + effective = copy.copy(settings) + setattr(effective, "qwen4_ple_ssd_offload", True) + return effective + @property def current_model_memory(self) -> int: """Current memory used by loaded models in bytes.""" @@ -534,6 +586,9 @@ def add(key: str, value: object) -> None: # force a reload when the corresponding feature is disabled. mtp_active = bool(data.get("mtp_enabled", False)) add("mtp_enabled", mtp_active) + if entry is not None: + qwen4_offload, _, _ = self._qwen4_ple_offload_status(entry, settings) + add("qwen4_ple_ssd_offload", qwen4_offload) turboquant_active = bool(data.get("turboquant_kv_enabled", False)) add("turboquant_kv_enabled", turboquant_active) @@ -2461,6 +2516,7 @@ async def _load_engine( model_settings = runtime_settings if model_settings is None and self._settings_manager is not None: model_settings = self._settings_manager.get_settings(model_id) + model_settings = self._effective_qwen4_model_settings(entry, model_settings) deployment = self._distributed_deployment_for_entry(entry) base_resident_size = self._entry_resident_size(entry) diff --git a/omlx/memory_monitor.py b/omlx/memory_monitor.py index 98633bea19..1cf691299d 100644 --- a/omlx/memory_monitor.py +++ b/omlx/memory_monitor.py @@ -91,9 +91,7 @@ def register_attention_bias_transient(dtype_size: float | None) -> None: model load/swap: the setting is process-wide, like the tiled head_dim registry above.""" global _ATTENTION_BIAS_TRANSIENT_DTYPE_SIZE - _ATTENTION_BIAS_TRANSIENT_DTYPE_SIZE = ( - float(dtype_size) if dtype_size else None - ) + _ATTENTION_BIAS_TRANSIENT_DTYPE_SIZE = float(dtype_size) if dtype_size else None def estimate_unfused_sdpa_call_bytes( @@ -737,7 +735,9 @@ def _estimate_sdpa_activation_bytes(self, query_tokens: int, kv_len: int) -> int and query_tokens > 1 and kv_len >= _SDPA_TILED_MIN_KV_LEN ): - tile_scores = n_q * query_tokens * min(kv_tile, kv_len) * self._score_dtype_size + tile_scores = ( + n_q * query_tokens * min(kv_tile, kv_len) * self._score_dtype_size + ) return output + tile_scores + bias return ( @@ -1057,14 +1057,7 @@ def _indexer_fallback_bytes(self, query_tokens: int, pooled_tokens: int) -> int: # conservative bound for the unfused MLX path. topk_workspace = 6 * reduced_scores selected = query_tokens * min(self.index_topk, pooled_tokens) * 4 - return ( - query - + keys - + weights - + materialized_scores - + topk_workspace - + selected - ) + return query + keys + weights + materialized_scores + topk_workspace + selected def _indexer_native_bytes(self, query_tokens: int, pooled_tokens: int) -> int: """Bound the fused native indexer score and deterministic top-k path.""" @@ -1273,8 +1266,9 @@ def make_prefill_memory_profile( ) # Fixed-state recurrent caches (GDN/Mamba). Matches # Scheduler._cache_tree_has_arrays_cache plus mlx-lm's MambaCache. -_ARRAYS_CACHE_CLASS_NAMES = frozenset( - {"ArraysCache", "SizedArraysCache", "MambaCache"} +_ARRAYS_CACHE_CLASS_NAMES = frozenset({"ArraysCache", "SizedArraysCache", "MambaCache"}) +_FULL_KV_CACHE_CLASS_NAMES = frozenset( + {"QSAKVCache", "QSAQuantizedKVCache", "BatchQSAKVCache"} ) @@ -1305,7 +1299,7 @@ def collect_kv_layer_specs( def _walk(c: Any) -> None: nonlocal full, arrays - if type(c) is KVCache: + if type(c) is KVCache or type(c).__name__ in _FULL_KV_CACHE_CLASS_NAMES: full += 1 return if isinstance(c, CacheList): @@ -1333,6 +1327,48 @@ def _walk(c: Any) -> None: return full, specs, arrays +def estimate_qwen4_exp_kv_bytes_per_token( + config: Any, + cache_list: Any, + dtype_size: float, +) -> float | None: + """Price Qwen4 QSA K/V plus its raw index keys and MRoPE positions.""" + if not str(_cfg_get(config, "model_type", "")).startswith("qwen4_exp"): + return None + if cache_list is None: + return None + + try: + qsa_layers = sum( + 1 + for cache in cache_list + if type(cache).__name__ + in {"QSAKVCache", "QSAQuantizedKVCache", "BatchQSAKVCache"} + ) + except Exception: + return None + if qsa_layers <= 0: + return None + + num_kv_heads = _cfg_get(config, "num_key_value_heads") + head_dim = _cfg_get(config, "head_dim") + indexer_head_dim = _cfg_get(config, "indexer_head_dim") + if not all(_pos_int(value) for value in (num_kv_heads, head_dim, indexer_head_dim)): + return None + if not isinstance(dtype_size, (int, float)) or dtype_size <= 0: + return None + + # QSA keeps ordinary K/V, one raw index-key vector, and up to three int64 + # MRoPE coordinates for every cached token. Text-only positions use one + # coordinate, but charging all three keeps image requests conservative. + per_layer = ( + 2 * num_kv_heads * head_dim * float(dtype_size) + + indexer_head_dim * float(dtype_size) + + 3 * 8 + ) + return float(qsa_layers * per_layer) + + def estimate_mla_kv_bytes_per_token( config: Any, cache_list: Any, @@ -1497,9 +1533,9 @@ def set_model_info_from_model(monitor: "MemoryMonitor", model: Any) -> None: except Exception: pass - kv_bytes_per_token = estimate_mla_kv_bytes_per_token( + kv_bytes_per_token = estimate_qwen4_exp_kv_bytes_per_token( config, cache_list, dtype_size - ) + ) or estimate_mla_kv_bytes_per_token(config, cache_list, dtype_size) # Truthiness alone isn't enough — MagicMock proxies leaking through the # descent (test scaffolds that don't fully spec ``model.config``) are @@ -1619,7 +1655,10 @@ def raise_if_prefill_exceeds( request_id = f"preflight-{_uuid.uuid4().hex[:8]}" logger.warning( "Preflight rejected (%d tokens, cached=%d, request_id=%s): %s", - num_prompt_tokens, cached_tokens, request_id, message, + num_prompt_tokens, + cached_tokens, + request_id, + message, ) raise PrefillMemoryExceededError( message=message, diff --git a/omlx/model_profiles.py b/omlx/model_profiles.py index db8ab82235..1b6aa32f4a 100644 --- a/omlx/model_profiles.py +++ b/omlx/model_profiles.py @@ -102,6 +102,8 @@ "model_type_override", "active_profile_name", "ttl_seconds", + # Hardware-specific residency choice; never propagate across models. + "qwen4_ple_ssd_offload", # Security flag must be explicit per model — never propagated via profiles. "trust_remote_code", } diff --git a/omlx/model_settings.py b/omlx/model_settings.py index 686cb0cd9b..2edb0afa40 100644 --- a/omlx/model_settings.py +++ b/omlx/model_settings.py @@ -212,6 +212,10 @@ class ModelSettings: enable_thinking: Optional[bool] = ( None # Explicit toggle for thinking/reasoning mode (None = auto) ) + # Qwen4-Exp only: keep the large PLE N-gram table on SSD and gather rows + # through mmap. The runtime may force this on when resident loading cannot + # fit under the configured model-memory ceiling but mmap loading can. + qwen4_ple_ssd_offload: bool = False preserve_thinking: Optional[bool] = ( None # Keep blocks in historical turns (None = auto, True when template supports it) ) diff --git a/omlx/models/vlm.py b/omlx/models/vlm.py index afcc43d32c..af2d62d0ab 100644 --- a/omlx/models/vlm.py +++ b/omlx/models/vlm.py @@ -70,6 +70,9 @@ def __init__(self, vlm_model: nn.Module): def release_resources(self) -> None: """Drop references to VLM-owned MLX arrays before engine teardown reclaim.""" + close = getattr(self._vlm_model, "close", None) + if callable(close): + close() self._pending_embeds = None self._pending_kwargs = {} self._uid_rope_deltas.clear() @@ -77,6 +80,47 @@ def release_resources(self) -> None: self._language_model = None self._vlm_model = None + @property + def mtp(self): + """Expose an attached Lightning MTP head, when the model provides one.""" + language_model = self._language_model + getter = getattr(language_model, "get_mtp_module", None) + if callable(getter): + return getter() + return getattr(language_model, "mtp", None) + + def mtp_forward( + self, + hidden_states, + next_token_ids, + mtp_cache, + return_hidden: bool = False, + logits_keep: int = 0, + ): + return self._language_model.mtp_forward( + hidden_states, + next_token_ids, + mtp_cache, + return_hidden=return_hidden, + logits_keep=logits_keep, + ) + + def make_mtp_cache(self): + make_cache = getattr(self._language_model, "make_mtp_cache", None) + return make_cache() if callable(make_cache) else [] + + def rollback_speculative_cache(self, caches, gdn_states, accepted, block_size): + return self._language_model.rollback_speculative_cache( + caches, + gdn_states, + accepted, + block_size, + ) + + # Runtime family patches use this marker to avoid installing an older, + # model-specific copy of the same adapter plumbing. + _omlx_mtp_adapter_patched = True + @property def layers(self): """Expose language model layers for cache creation. diff --git a/omlx/oq.py b/omlx/oq.py index 615c0fb867..c7e2a57bca 100644 --- a/omlx/oq.py +++ b/omlx/oq.py @@ -48,6 +48,12 @@ _GLM_INDEXER_Q8 = {"bits": 8, "group_size": 64, "mode": "affine"} _GLM_INDEXER_PROJECTIONS = ("wq_b", "wk", "weights_proj") +_QWEN4_EXP_NGRAM_GROUP_SIZE = 32 +_QWEN4_EXP_NGRAM_SHARD_RE = re.compile( + r"\.ple\.ple_embedding\.ngram_embedding\." + r"(?:shard_\d+|shards\.\d+)$" +) + _MAX_MODEL_RAM_FRACTION = 0.75 # Auto-built proxy for sensitivity measurement when the source model @@ -319,6 +325,26 @@ def _glm_indexer_q8_override(path: str, config: dict) -> dict | None: return dict(_GLM_INDEXER_Q8) +def _is_qwen4_exp_ngram_embedding_tensor(path: str, config: dict) -> bool: + """Return whether *path* is one Qwen4-Exp PLE embedding shard. + + The source checkpoint spells shards as ``shard_N`` while the model + sanitizer maps them to the runtime module path ``shards.N``. Match both + forms so proxy construction and final streaming quantization use the same + policy. + """ + text_config = config.get("text_config") + if not isinstance(text_config, dict): + text_config = {} + model_types = ( + str(config.get("model_type") or "").lower(), + str(text_config.get("model_type") or "").lower(), + ) + if not any(model_type.startswith("qwen4_exp") for model_type in model_types): + return False + return _QWEN4_EXP_NGRAM_SHARD_RE.search(_normalize_quant_path(path)) is not None + + def universal_quant_predicate( path: str, module, config: dict, oq_level: int = 4 ) -> Union[bool, dict]: @@ -688,6 +714,29 @@ def _estimate_effective_bpw( return total_bits / max(total_params, 1) +def _structural_quant_overrides( + named_shapes: dict[str, tuple], config: dict, oq_level: int +) -> dict[str, dict]: + """Layouts fixed by a model invariant rather than the bit allocator. + + Qwen4-Exp PLE rows are 160 elements wide. The writer always uses group + size 32 for them, but pricing them at the default group size 64 makes the + planner classify the table as an unquantizable 16-bpw tensor. Since PLE + is about 51B parameters, that false cost can exhaust the entire budget and + suppress every protection boost even though the writer emits Q4/group32. + """ + base_bits = _base_bits_for_level(oq_level) + return { + path: { + "bits": base_bits, + "group_size": _QWEN4_EXP_NGRAM_GROUP_SIZE, + "mode": "affine", + } + for path in named_shapes + if _is_qwen4_exp_ngram_embedding_tensor(path, config) + } + + def _collect_named_weight_shapes_from_model(model) -> dict[str, tuple]: """Collect quantizable weight shapes from the in-memory model.""" named_shapes = {} @@ -3195,13 +3244,17 @@ def _source_quant_info(name): pos_sens[str(i)] = 0.01 config["_oq_sensitivity_map"] = pos_sens + plan_fixed_overrides = { + **fixed_overrides, + **_structural_quant_overrides(named_shapes, config, oq_level), + } plan = _build_quant_plan( named_shapes, config, oq_level, target_bpw=_level_targets[0], hard_cap_bpw=_level_targets[1], - fixed_overrides=fixed_overrides, + fixed_overrides=plan_fixed_overrides, ) config["_oq_boost_map"] = plan.boost_map else: @@ -3807,6 +3860,13 @@ class _Proxy: audio_tower = _AUDIO_SENTINEL embed_audio = _AUDIO_SENTINEL + # Runtime mmap models intentionally discard checkpoint PLE + # weights because DiskBackedShardedEmbedding reads them + # directly. The streaming quantizer still needs those + # tensors in the sanitize plan so it can write the compact + # affine PLE artifact. + _omlx_preserve_qwen4_ple_for_quantization = True + # Some sanitizes call sibling instance methods (inkling's # ``self._map_llm_layer`` / ``self._map_experts``) or read # class attributes (``self._ATTN``). Resolve anything the @@ -4139,6 +4199,14 @@ def _get_predicate_bits( base_bits = _base_bits_for_level(oq_level) + # Qwen4-Exp's PLE rows are 160 elements wide, so the default group size + # 64 leaves the 100 GB N-gram table unquantized. Keep the table uniform at + # the selected oQ level and use the group-32 layout published by existing + # Qwen4-Exp quantizations. Embeddings have no input-channel imatrix entry; + # the streaming loop deliberately applies ordinary affine quantization. + if _is_qwen4_exp_ngram_embedding_tensor(tensor_name, config): + return base_bits, _QWEN4_EXP_NGRAM_GROUP_SIZE, "affine" + result = universal_quant_predicate(tensor_name, None, config, oq_level) if result is False: return None, None, None @@ -4336,6 +4404,16 @@ def source_shape(self, key): meta = self._index.get(key) return None if meta is None else meta[4] + def source_dtype(self, key): + """Safetensors dtype spelling for ``key``, or None when absent. + + Model-specific virtual-tensor registrars use this alongside + :meth:`source_shape` to distinguish packed storage from an already + materialized floating-point checkpoint without reading tensor data. + """ + meta = self._index.get(key) + return None if meta is None else meta[5] + def load_source(self, key): """Load an on-disk tensor verbatim, bypassing fp8 pairing.""" return self._load_raw(key) @@ -5083,11 +5161,19 @@ def _lookup_imatrix_importance( tensor_name: str, shape: tuple[int, ...], *, + config: dict | None = None, strict: bool, report: dict[str, Any] | None, ): if imatrix is None or not tensor_name.endswith(".weight"): return None + if config is not None and _is_qwen4_exp_ngram_embedding_tensor( + tensor_name, config + ): + # The collector measures Linear/SwitchLinear input channels, not + # embedding rows. Do not turn the intentionally uniform PLE policy + # into a missing-entry error under imatrix_strict. + return None base = tensor_name[: -len(".weight")] entry = imatrix.entries.get(base) @@ -5878,13 +5964,17 @@ def _imatrix_load_path() -> str: if _level_targets is not None: _t = target_bpw if target_bpw is not None else _level_targets[0] _c = hard_cap_bpw if hard_cap_bpw is not None else _level_targets[1] + plan_fixed_overrides = { + **fixed_overrides, + **_structural_quant_overrides(named_shapes, config, oq_level), + } plan = _build_quant_plan( named_shapes, config, oq_level, target_bpw=_t, hard_cap_bpw=_c, - fixed_overrides=fixed_overrides, + fixed_overrides=plan_fixed_overrides, ) config["_oq_boost_map"] = plan.boost_map logger.info( @@ -5987,6 +6077,7 @@ def _imatrix_load_path() -> str: imatrix_data, tensor_name, tuple(shape), + config=config, strict=imatrix_strict, report=imatrix_report, ) @@ -6509,6 +6600,7 @@ def _find_model_layers(model): _GEMMA4_LAYER_STATE_KIND = "gemma4_shared_kv" +_QWEN4_EXP_LAYER_STATE_KIND = "qwen4_exp" def _find_layer_model(model, layers): @@ -6655,6 +6747,57 @@ def _prepare_gemma4_layer_inputs(model, layers, calib_data, inputs): return inputs, layer_masks, state +def _prepare_qwen4_exp_layer_inputs(model, layers, calib_data, inputs): + """Build Qwen4-Exp's hyper-connection layer-walk inputs. + + Qwen4 decoder blocks do not use the generic Transformer signature. The + trunk tiles token embeddings across ``hc_count`` residual streams and each + block receives the original token ids before mask/cache/position state. + Replaying a block with the generic calibration call silently skips every + layer, leaving an installed oQe collector with zero captured entries. + """ + layer_model = _find_layer_model(model, layers) + if layer_model is None: + return None + args = getattr(layer_model, "args", None) + model_type = str(getattr(args, "model_type", "")).lower() + if not model_type.startswith("qwen4_exp"): + return None + + hc_count = _object_config_int(args, "hc_count") + hidden_size = _object_config_int(args, "hidden_size") + if hc_count <= 0 or hidden_size <= 0: + raise RuntimeError( + "Qwen4-Exp calibration requires positive hc_count and hidden_size" + ) + expected_width = hc_count * hidden_size + if int(inputs.shape[-1]) == hidden_size: + inputs = mx.tile(inputs, (1, 1, hc_count)) + elif int(inputs.shape[-1]) != expected_width: + raise RuntimeError( + "Qwen4-Exp calibration received an invalid hidden width: " + f"{int(inputs.shape[-1])} (expected {hidden_size} or {expected_width})" + ) + + seq_len = int(calib_data.shape[1]) + full_attention_mask = nn.MultiHeadAttention.create_additive_causal_mask(seq_len) + full_attention_mask = full_attention_mask.astype(inputs.dtype) + layer_masks = [ + None if bool(getattr(layer, "is_linear", False)) else full_attention_mask + for layer in layers + ] + position_ids = mx.broadcast_to( + mx.arange(seq_len, dtype=mx.int32)[None], + (int(calib_data.shape[0]), seq_len), + ) + state = { + "kind": _QWEN4_EXP_LAYER_STATE_KIND, + "input_ids": calib_data, + "position_ids": position_ids, + } + return inputs, layer_masks, state + + def _forward_gemma4_layer_result(block, inputs, mask, state, layer_idx: int): if not 0 <= int(layer_idx) < len(state["previous_kvs"]): raise RuntimeError(f"Invalid Gemma 4 calibration layer index: {layer_idx}") @@ -6705,6 +6848,26 @@ def _forward_layer_result(block, inputs, mask, position_ids, layer_idx=None): return _forward_gemma4_layer_result( block, inputs, mask, position_ids, int(layer_idx) ) + if ( + isinstance(position_ids, dict) + and position_ids.get("kind") == _QWEN4_EXP_LAYER_STATE_KIND + ): + try: + result = block( + inputs, + position_ids["input_ids"], + mask=mask, + cache=None, + position_ids=position_ids["position_ids"], + ) + except (TypeError, ValueError, RuntimeError, AttributeError) as e: + suffix = f" at layer {layer_idx}" if layer_idx is not None else "" + raise RuntimeError( + f"Qwen4-Exp calibration forward failed{suffix}: {e}" + ) from e + if isinstance(result, tuple): + return result[0], result[1] if len(result) > 1 else None + return result, None if isinstance(position_ids, dict) and position_ids.get("kind") == "glm_moe_dsa": try: result = block( @@ -6880,6 +7043,11 @@ def _prepare_layer_inputs(model, layers, calib_data, inputs): gemma4_inputs = _prepare_gemma4_layer_inputs(model, layers, calib_data, inputs) if gemma4_inputs is not None: return gemma4_inputs + qwen4_exp_inputs = _prepare_qwen4_exp_layer_inputs( + model, layers, calib_data, inputs + ) + if qwen4_exp_inputs is not None: + return qwen4_exp_inputs if model_type.startswith("deepseek_v4"): args = model.args h = mx.broadcast_to( @@ -7117,6 +7285,12 @@ def _collect_mtp_head_imatrix( """ inner = getattr(model, "language_model", None) or model mtp = getattr(inner, "mtp", None) + if mtp is None: + get_mtp_module = getattr(inner, "get_mtp_module", None) + if callable(get_mtp_module): + mtp = get_mtp_module() + if mtp is None: + mtp = getattr(model, "mtp", None) if mtp is None: return False try: @@ -7130,6 +7304,23 @@ def _collect_mtp_head_imatrix( out = dspark_calibration(target_hidden, batch) mx.eval(out) return True + if type(mtp).__name__ == "Qwen4ExpMTPModule": + core = getattr(inner, "model", None) or inner + embed = getattr(core, "embed_tokens", None) + if embed is None: + return False + make_cache = getattr(inner, "make_mtp_cache", None) + mtp_cache = ( + make_cache() + if callable(make_cache) + else [None for _ in getattr(mtp, "layers", ())] + ) + out = mtp(hidden[:, :-1, :], batch[:, 1:], embed, mtp_cache) + if isinstance(out, tuple): + mx.eval(*out) + else: + mx.eval(out) + return True if isinstance(mtp, (list, tuple)): # DeepSeek-V4 style: MTPBlock stack consuming the raw (4D) # trunk hidden; Model.mtp_forward wires mask/cache/embedding. @@ -7437,10 +7628,22 @@ def _collect_imatrix( is_vlm = _is_vlm_load(config) has_mtp_weights = _checkpoint_has_mtp_weights(model_path) - maybe_apply_pre_load_patches(model_path, for_vlm=is_vlm) + has_mtp_heads = _has_mtp_heads(config) + calibration_settings = None + if has_mtp_heads and has_mtp_weights: + from types import SimpleNamespace + + calibration_settings = SimpleNamespace( + mtp_enabled=True, + mtp_num_draft_tokens=1, + ) + patch_kwargs: dict[str, Any] = {"for_vlm": is_vlm} + if calibration_settings is not None: + patch_kwargs["model_settings"] = calibration_settings + maybe_apply_pre_load_patches(model_path, **patch_kwargs) restore_mtp_active = None - if _has_mtp_heads(config) and has_mtp_weights: + if has_mtp_heads and has_mtp_weights: # Attach the MTP head on the temporary calibration model so the # head-forward pass in _collect_imatrix_from_model can exercise its # linears (they'd otherwise land in the imatrix "missing" list). @@ -7756,24 +7959,31 @@ def _measure_sensitivity( # ship a vision_config but must load through the patched mlx-lm class. is_vlm = _is_vlm_load(config) has_mtp_weights = _checkpoint_has_mtp_weights(model_path) + has_mtp_heads = _has_mtp_heads(config) # Reuse the centralised pre-load dispatch so every current and future # patch (MTP sanitize, DeepSeek V4, nested-visual, load_config, …) is # applied exactly as in the production load path. - maybe_apply_pre_load_patches(model_path, for_vlm=is_vlm) - - # maybe_apply_pre_load_patches leaves mtp_active False, which is correct - # for the text path: the patched qwen35_model.sanitize self-consistently - # strips mtp.* when no head is attached. The VLM path needs both patches. - # apply_mlx_vlm_mtp_patch fixes Model.sanitize so language_model.mtp.* - # weights survive the load with the correct keys (stock mlx-vlm sanitize - # strips them, which is what made the strict load fail with "Missing N - # parameters" and the measurement silently return {}). The runtime patch - # then attaches the MTP head so the checkpoint matches the model. Both - # are idempotent. Sensitivity only reads backbone decoder layers, so this - # is load-only. + calibration_settings = None + if has_mtp_heads and has_mtp_weights: + from types import SimpleNamespace + + calibration_settings = SimpleNamespace( + mtp_enabled=True, + mtp_num_draft_tokens=1, + ) + patch_kwargs: dict[str, Any] = {"for_vlm": is_vlm} + if calibration_settings is not None: + patch_kwargs["model_settings"] = calibration_settings + maybe_apply_pre_load_patches(model_path, **patch_kwargs) + + # The central dispatch receives an explicit MTP calibration setting so + # model-specific constructors such as Qwen4's root-owned MTP head are + # enabled before load. The VLM patch below also covers the generic + # qwen3_5 classes whose MTP module is attached by the shared runtime. + # Sensitivity only reads backbone decoder layers, so this is load-only. restore_mtp_active = None - if is_vlm and _has_mtp_heads(config) and has_mtp_weights: + if is_vlm and has_mtp_heads and has_mtp_weights: try: from omlx.patches.mlx_lm_mtp import is_mtp_active, set_mtp_active from omlx.patches.mlx_vlm_mtp import ( @@ -8044,14 +8254,23 @@ def _flush_shard() -> None: pred = universal_quant_predicate( tensor_name, None, config, _PROXY_QUANT_BITS ) - if pred is not False and len(shape) >= 2 and shape[-1] % base_gs == 0: + tensor_gs = ( + _QWEN4_EXP_NGRAM_GROUP_SIZE + if _is_qwen4_exp_ngram_embedding_tensor(tensor_name, config) + else base_gs + ) + if ( + pred is not False + and len(shape) >= 2 + and shape[-1] % tensor_gs == 0 + ): if ( mx.issubdtype(w_mx.dtype, mx.floating) and w_mx.dtype != target_dtype ): w_mx = w_mx.astype(target_dtype) qw, scales, biases = _quantize_chunked( - w_mx, base_gs, base_bits, base_mode + w_mx, tensor_gs, base_bits, base_mode ) base = ( tensor_name[:-7] @@ -8062,6 +8281,12 @@ def _flush_shard() -> None: out_shard_data[f"{base}.scales"] = scales if biases is not None: out_shard_data[f"{base}.biases"] = biases + if tensor_gs != base_gs: + per_layer_config[base] = { + "bits": base_bits, + "group_size": tensor_gs, + "mode": base_mode, + } del qw, scales, biases else: if cast_predicate is None or cast_predicate(tensor_name): @@ -8159,12 +8384,24 @@ def _measure_sensitivity_from_quantized_model( # Idempotent; harmless for plain mlx-lm proxies. is_vlm = _is_vlm_load(config) has_mtp_weights = _checkpoint_has_mtp_weights(model_path) - maybe_apply_pre_load_patches(model_path, for_vlm=is_vlm) + has_mtp_heads = _has_mtp_heads(config) + calibration_settings = None + if has_mtp_heads and has_mtp_weights: + from types import SimpleNamespace + + calibration_settings = SimpleNamespace( + mtp_enabled=True, + mtp_num_draft_tokens=1, + ) + patch_kwargs: dict[str, Any] = {"for_vlm": is_vlm} + if calibration_settings is not None: + patch_kwargs["model_settings"] = calibration_settings + maybe_apply_pre_load_patches(model_path, **patch_kwargs) restore_mtp_active = None try: if is_vlm: - if _has_mtp_heads(config) and has_mtp_weights: + if has_mtp_heads and has_mtp_weights: try: from omlx.patches.mlx_lm_mtp import is_mtp_active, set_mtp_active from omlx.patches.mlx_vlm_mtp import ( diff --git a/omlx/patches/mlx_lm_mtp/prompt_priming.py b/omlx/patches/mlx_lm_mtp/prompt_priming.py index be027a8a39..5b58f9f541 100644 --- a/omlx/patches/mlx_lm_mtp/prompt_priming.py +++ b/omlx/patches/mlx_lm_mtp/prompt_priming.py @@ -259,10 +259,12 @@ def drop_ctx(model: Any) -> None: def _host_eligible(host: Any) -> bool: + get_mtp = getattr(host, "get_mtp_module", None) + mtp = get_mtp() if callable(get_mtp) else getattr(host, "mtp", None) return bool( getattr(host, "_omlx_mtp_decode_enabled", False) and getattr(host, "_omlx_mtp_chain", False) - and getattr(host, "mtp", None) is not None + and mtp is not None ) @@ -360,9 +362,7 @@ def maybe_capture( if ctx.pending_hidden is not None: if seq_len > 1: - pairs_hidden = mx.concatenate( - [ctx.pending_hidden, normed[:, :-1]], axis=1 - ) + pairs_hidden = mx.concatenate([ctx.pending_hidden, normed[:, :-1]], axis=1) else: pairs_hidden = ctx.pending_hidden pairs_tokens = inputs diff --git a/omlx/patches/mlx_vlm_mtp/qwen38_fp8.py b/omlx/patches/mlx_vlm_mtp/qwen38_fp8.py index 1deb0ea8dd..9dcc45329f 100644 --- a/omlx/patches/mlx_vlm_mtp/qwen38_fp8.py +++ b/omlx/patches/mlx_vlm_mtp/qwen38_fp8.py @@ -13,9 +13,11 @@ def dequantize_fp8_weights( weights: dict[str, Any], dtype: Any = mx.bfloat16, + *, + copy_weights: bool = True, ) -> dict[str, Any]: """Expand Qwen3.8 block-FP8 tensors using their inverse-scale grids.""" - weights = dict(weights) + weights = dict(weights) if copy_weights else weights scale_suffix = ".weight_scale_inv" for scale_key in [key for key in weights if key.endswith(scale_suffix)]: diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/__init__.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/__init__.py index ba91196a73..f6a9932dc3 100644 --- a/omlx/patches/mlx_vlm_qwen4_exp_compat/__init__.py +++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/__init__.py @@ -70,11 +70,29 @@ def is_applied() -> bool: def configure_qwen4_exp_runtime( model_path: str | Path, mode: str | None = None, + *, + mtp_enabled: bool = False, ) -> str: - """Select resident or SSD-backed PLE before model construction.""" + """Select PLE storage and optional Lightning MTP before construction.""" apply_mlx_vlm_qwen4_exp_compat_patch() - from mlx_vlm.models.qwen4_exp.language import configure_ple_runtime + from mlx_vlm.models.qwen4_exp.language import ( + configure_mtp_runtime, + configure_ple_runtime, + ) resolved = configure_ple_runtime(model_path, mode=mode) + mtp_runtime = configure_mtp_runtime(model_path, enabled=mtp_enabled) logger.info("Qwen4-Exp PLE mode for %s: %s", model_path, resolved) + if mtp_enabled and not mtp_runtime.enabled: + logger.warning( + "Qwen4-Exp Lightning MTP was requested for %s, but no embedded " + "MTP tensors were found", + model_path, + ) + elif mtp_runtime.enabled: + logger.info( + "Qwen4-Exp Lightning MTP enabled for %s (checkpoint layout: %s)", + model_path, + mtp_runtime.checkpoint_prefix, + ) return resolved diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/residency.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/residency.py new file mode 100644 index 0000000000..790e9dc18e --- /dev/null +++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/residency.py @@ -0,0 +1,141 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Qwen4-Exp PLE storage estimates shared by runtime and settings UIs.""" + +from __future__ import annotations + +import json +import struct +from dataclasses import dataclass +from functools import lru_cache +from pathlib import Path + +_MODEL_OVERHEAD_FACTOR = 1.05 +_NGRAM_EMBEDDING_MARKER = ".ngram_embedding." + + +@dataclass(frozen=True) +class Qwen4ExpResidencyEstimate: + """Estimated resident bytes with and without the PLE embedding table.""" + + supported: bool + checkpoint_bytes: int + ple_bytes: int + resident_bytes: int + mmap_bytes: int + + def force_ssd_offload(self, memory_ceiling: int) -> bool: + """Return True only when mmap turns an otherwise impossible load viable.""" + + return ( + self.supported + and memory_ceiling > 0 + and self.resident_bytes > memory_ceiling + and self.mmap_bytes <= memory_ceiling + ) + + +def _resolve_ple_path(model_path: Path) -> Path: + config_path = model_path / "config.json" + if not config_path.is_file(): + return model_path + try: + config = json.loads(config_path.read_text()) + except (OSError, ValueError): + return model_path + artifact = config.get("qwen4_exp_artifact") or {} + relative_ple = artifact.get("ple_artifact") + if relative_ple is None: + return model_path + relative_ple = Path(relative_ple) + if relative_ple.is_absolute(): + return model_path + candidate = (model_path / relative_ple).resolve() + artifact_root = model_path.parent.resolve() + if candidate != artifact_root and artifact_root not in candidate.parents: + return model_path + return candidate + + +def _safetensors_header(path: Path) -> dict: + with path.open("rb") as file: + raw_size = file.read(8) + if len(raw_size) != 8: + return {} + header_size = struct.unpack(" tuple[int, bool]: + index_path = ple_path / "model.safetensors.index.json" + if not index_path.is_file(): + return 0, False + try: + weight_map = json.loads(index_path.read_text()).get("weight_map") or {} + except (OSError, ValueError): + return 0, False + + selected: dict[str, list[str]] = {} + for key, filename in weight_map.items(): + if _NGRAM_EMBEDDING_MARKER in key: + selected.setdefault(filename, []).append(key) + if not selected: + return 0, False + + total = 0 + try: + for filename, keys in selected.items(): + header = _safetensors_header(ple_path / filename) + for key in keys: + start, end = header[key]["data_offsets"] + total += int(end) - int(start) + except (KeyError, OSError, TypeError, ValueError): + return 0, False + return total, total > 0 + + +@lru_cache(maxsize=128) +def _cached_residency_estimate( + ple_path_string: str, + checkpoint_signature: tuple[tuple[str, int, int], ...], + _index_signature: tuple[int, int] | None, +) -> Qwen4ExpResidencyEstimate: + ple_path = Path(ple_path_string) + checkpoint_bytes = sum(size for _, size, _ in checkpoint_signature) + ple_bytes, supported = _ple_tensor_bytes(ple_path) + resident_bytes = int(checkpoint_bytes * _MODEL_OVERHEAD_FACTOR) + mmap_bytes = int(max(0, checkpoint_bytes - ple_bytes) * _MODEL_OVERHEAD_FACTOR) + return Qwen4ExpResidencyEstimate( + supported=supported, + checkpoint_bytes=checkpoint_bytes, + ple_bytes=ple_bytes, + resident_bytes=resident_bytes, + mmap_bytes=mmap_bytes, + ) + + +def qwen4_exp_residency_estimate( + model_path: str | Path, +) -> Qwen4ExpResidencyEstimate: + """Inspect Qwen4 checkpoint headers without materializing tensor data.""" + + compute_path = Path(model_path).expanduser().resolve() + ple_path = _resolve_ple_path(compute_path) + roots = {compute_path, ple_path} + checkpoint_files = { + path.resolve() for root in roots for path in root.glob("*.safetensors") + } + signature = tuple( + sorted( + (str(path), stat.st_size, stat.st_mtime_ns) + for path in checkpoint_files + for stat in (path.stat(),) + ) + ) + index_path = ple_path / "model.safetensors.index.json" + index_stat = index_path.stat() if index_path.is_file() else None + index_signature = ( + (index_stat.st_size, index_stat.st_mtime_ns) + if index_stat is not None + else None + ) + return _cached_residency_estimate(str(ple_path), signature, index_signature) diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/config.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/config.py index 2813cdb7e8..8b8e213ac3 100644 --- a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/config.py +++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/config.py @@ -61,6 +61,9 @@ class TextConfig(BaseModelConfig): output_gate_type: str = "sigmoid" hidden_act: str = "silu" norm_topk_prob: bool = True + mtp_num_hidden_layers: int = 1 + mtp_use_dedicated_embeddings: bool = False + mtp: Optional[Dict] = None eos_token_id: Optional[Union[int, List[int]]] = None tie_word_embeddings: bool = False attention_bias: bool = False 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 0e305cfc4f..523de27eed 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 @@ -5,7 +5,9 @@ import mmap import os import struct +import weakref from bisect import bisect_right +from dataclasses import dataclass, replace from pathlib import Path from types import SimpleNamespace from typing import Any, Optional @@ -21,6 +23,7 @@ Qwen3_5GatedDeltaNet, _create_qwen3_5_attention_mask, _create_qwen3_5_ssm_mask, + _target_verify_linear, ) from ..qwen3_5_moe.language import Qwen3_5MoeSparseMoeBlock from .config import ModelConfig, TextConfig @@ -29,6 +32,74 @@ _PLE_RUNTIME_MODE = "resident" +@dataclass(frozen=True) +class Qwen4ExpMTPRuntime: + """Lightning MTP construction decision for the next model load.""" + + enabled: bool = False + checkpoint_prefix: str | None = None + + +_MTP_RUNTIME = Qwen4ExpMTPRuntime() + + +def configure_mtp_runtime( + model_path: str | Path, + *, + enabled: bool, +) -> Qwen4ExpMTPRuntime: + """Detect and bind an embedded Qwen4 Lightning MTP checkpoint head.""" + global _MTP_RUNTIME + + checkpoint_prefix = None + if enabled: + model_path = Path(model_path) + index_path = model_path / "model.safetensors.index.json" + if index_path.is_file(): + try: + weight_map = json.loads(index_path.read_text()).get("weight_map") or {} + except (OSError, ValueError): + weight_map = {} + for prefix in ( + "mtp.", + "language_model.mtp.", + "model.mtp.", + "model.language_model.mtp.", + ): + if any(key.startswith(prefix) for key in weight_map): + checkpoint_prefix = prefix + break + else: + try: + import safetensors + + for shard in sorted(model_path.glob("*.safetensors")): + with safetensors.safe_open(str(shard), framework="numpy") as file: + for prefix in ( + "mtp.", + "language_model.mtp.", + "model.mtp.", + "model.language_model.mtp.", + ): + if any(key.startswith(prefix) for key in file.keys()): + checkpoint_prefix = prefix + break + if checkpoint_prefix is not None: + break + except Exception: + checkpoint_prefix = None + + _MTP_RUNTIME = Qwen4ExpMTPRuntime( + enabled=bool(enabled and checkpoint_prefix), + checkpoint_prefix=checkpoint_prefix, + ) + return _MTP_RUNTIME + + +def get_mtp_runtime() -> Qwen4ExpMTPRuntime: + return _MTP_RUNTIME + + def resolve_ple_runtime_mode( requested: str, *, checkpoint_bytes: int, physical_memory: int ) -> str: @@ -80,6 +151,10 @@ def configure_ple_runtime(model_path: str | Path, mode: str | None = None) -> st return _PLE_RUNTIME_MODE +def get_ple_runtime_mode() -> str: + return _PLE_RUNTIME_MODE + + def _append_indexer_positions( cached: Optional[mx.array], position_ids: mx.array ) -> mx.array: @@ -639,15 +714,25 @@ def __call__( hidden_states: mx.array, cache: Optional[QSAKVCache], position_ids: Optional[mx.array], + target_verify: bool = False, + ) -> Optional[mx.array]: + projected = _target_verify_linear( + self.index_qk_proj, hidden_states, target_verify + ) + return self.from_projected(projected, cache, position_ids) + + def from_projected( + self, + qk: mx.array, + cache: Optional[QSAKVCache], + position_ids: Optional[mx.array], ) -> Optional[mx.array]: - batch, seq_len, _ = hidden_states.shape + batch, seq_len, _ = qk.shape past_len = cache.offset if cache is not None else 0 if position_ids is None: position_ids = self._default_position_ids(batch, past_len, seq_len) - qk = self.index_qk_proj(hidden_states).reshape( - batch, seq_len, self.n_heads + self.kv_heads, self.head_dim - ) + qk = qk.reshape(batch, seq_len, self.n_heads + self.kv_heads, self.head_dim) query = qk[:, :, : self.n_heads] raw_keys = qk[:, :, self.n_heads :].squeeze(2) query = self.q_layernorm(query).transpose(0, 2, 1, 3) @@ -746,8 +831,14 @@ def __call__( cache: Optional[Any] = None, position_ids: Optional[mx.array] = None, position_embeddings: Optional[tuple[mx.array, mx.array]] = None, + target_verify: bool = False, ) -> mx.array: - qsa_mask = self.indexer(x, cache, position_ids) + qsa_mask = self.indexer( + x, + cache, + position_ids, + target_verify=target_verify, + ) if qsa_mask is not None: if mask is None or (isinstance(mask, str) and mask == "causal"): mask = qsa_mask @@ -766,6 +857,7 @@ def __call__( cache=cache, position_ids=position_ids, position_embeddings=position_embeddings, + target_verify=target_verify, ) @@ -791,17 +883,35 @@ def __init__(self, config: TextConfig, use_combine: bool = True): hc_hidden_size, self.hc_count, bias=False ) - def __call__(self, hyper_input: mx.array): + def __call__(self, hyper_input: mx.array, target_verify: bool = False): normed = self.hc_norm(hyper_input) - mix = nn.silu(self.input_mix_weight_down(normed) / self.hc_count) - mix = mx.sigmoid(self.input_mix_weight_up(mix)) + mix = nn.silu( + _target_verify_linear( + self.input_mix_weight_down, + normed, + target_verify, + ) + / self.hc_count + ) + mix = mx.sigmoid( + _target_verify_linear( + self.input_mix_weight_up, + mix, + target_verify, + ) + ) mix = mix.reshape(*mix.shape[:-1], self.hc_count, self.hidden_size) streams = normed.reshape(*normed.shape[:-1], self.hc_count, self.hidden_size) mixed_input = mx.mean(mix * streams, axis=-2) if "block_inject_weight" not in self: return mixed_input injection_weights = 2 * mx.sigmoid( - self.block_inject_weight(normed) / self.hc_count + _target_verify_linear( + self.block_inject_weight, + normed, + target_verify, + ) + / self.hc_count ) return mixed_input, hyper_input, injection_weights @@ -855,7 +965,7 @@ def _find_nth_prime_after(start: int, count: int) -> int: class _SafeTensorMMap: - """Read sparse BF16 embedding rows without making the table resident.""" + """Read selected dense or affine-packed rows without resident weights.""" def __init__(self, path: Path): self.path = path @@ -872,23 +982,39 @@ def __init__(self, path: Path): def tensor_shape(self, key: str) -> tuple[int, ...]: return tuple(self._header[key]["shape"]) + def tensor_dtype(self, key: str) -> str: + return str(self._header[key]["dtype"]) + def rows(self, key: str, rows: list[int]) -> mx.array: entry = self._header[key] - if entry["dtype"] != "BF16": - raise TypeError(f"SSD-backed Qwen4 PLE requires BF16, got {entry['dtype']}") shape = tuple(entry["shape"]) start, end = entry["data_offsets"] - if len(shape) != 2 or end - start != math.prod(shape) * 2: + dtype = entry["dtype"] + dtype_info = { + "BF16": (np.dtype(" _SafeTensorMMap: + filename = weight_map[key] reader = self._readers.get(filename) if reader is None: reader = _SafeTensorMMap(model_path / filename) self._readers[filename] = reader - if reader.tensor_shape(key) != (shard_size, dims): + self._tensor_readers[key] = reader + return reader + + runtime_prefix = prefix + if runtime_prefix.startswith("model.language_model."): + runtime_prefix = ( + "language_model.model." + runtime_prefix[len("model.language_model.") :] + ) + for shard_index, shard_size in enumerate(self.shard_sizes): + bases = ( + f"{prefix}.shard_{shard_index}", + f"{prefix}.shards.{shard_index}", + f"{runtime_prefix}.shard_{shard_index}", + f"{runtime_prefix}.shards.{shard_index}", + ) + base = next( + ( + candidate + for candidate in bases + if f"{candidate}.weight" in weight_map + ), + None, + ) + if base is None: + raise KeyError( + f"SSD-backed PLE shard {shard_index} is absent; " + f"checked {', '.join(bases)}" + ) + + weight_key = f"{base}.weight" + scales_key = f"{base}.scales" + biases_key = f"{base}.biases" + weight_reader = register_reader(weight_key) + weight_shape = weight_reader.tensor_shape(weight_key) + weight_dtype = weight_reader.tensor_dtype(weight_key) + if len(weight_shape) != 2 or weight_shape[0] != shard_size: + raise ValueError(f"Unexpected shape for {weight_key}: {weight_shape}") + + if scales_key not in weight_map and biases_key not in weight_map: + if weight_shape[1] != dims: + raise ValueError( + f"Unexpected dense PLE width for {weight_key}: " + f"expected {dims}, got {weight_shape[1]}" + ) + if weight_dtype not in {"BF16", "F16", "F32", "F8_E4M3"}: + raise TypeError( + f"SSD-backed dense Qwen4 PLE does not support {weight_dtype}" + ) + self._shard_specs[shard_index] = ( + weight_key, + None, + None, + None, + None, + ) + continue + + if scales_key not in weight_map or biases_key not in weight_map: raise ValueError( - f"Unexpected shape for {key}: {reader.tensor_shape(key)}" + f"Incomplete affine PLE tensors for {base}: both scales and " + "biases are required" + ) + if weight_dtype != "U32": + raise TypeError( + f"Affine Qwen4 PLE weight must be U32, got {weight_dtype} " + f"for {weight_key}" ) - self._tensor_readers[key] = reader + + scales_reader = register_reader(scales_key) + biases_reader = register_reader(biases_key) + scales_shape = scales_reader.tensor_shape(scales_key) + biases_shape = biases_reader.tensor_shape(biases_key) + if scales_shape != biases_shape or len(scales_shape) != 2: + raise ValueError( + f"Invalid affine PLE parameter shapes for {base}: " + f"scales={scales_shape}, biases={biases_shape}" + ) + if scales_shape[0] != shard_size or scales_shape[1] <= 0: + raise ValueError( + f"Unexpected affine PLE scale shape for {base}: {scales_shape}" + ) + if dims % scales_shape[1] != 0: + raise ValueError( + f"Cannot infer affine PLE group size for {base}: " + f"dims={dims}, scales={scales_shape}" + ) + group_size = dims // scales_shape[1] + packed_bits = weight_shape[1] * 32 + if packed_bits % dims != 0: + raise ValueError( + f"Cannot infer affine PLE bits for {base}: " + f"dims={dims}, packed_shape={weight_shape}" + ) + bits = packed_bits // dims + if bits not in {2, 3, 4, 5, 6, 8} or group_size not in {32, 64, 128}: + raise ValueError( + f"Unsupported affine PLE layout for {base}: " + f"bits={bits}, group_size={group_size}" + ) + if dims % group_size or weight_shape[1] != dims * bits // 32: + raise ValueError( + f"Inconsistent affine PLE layout for {base}: " + f"weight={weight_shape}, scales={scales_shape}, dims={dims}" + ) + self._shard_specs[shard_index] = ( + weight_key, + scales_key, + biases_key, + bits, + group_size, + ) def __call__(self, indices: mx.array) -> mx.array: shape = indices.shape @@ -960,14 +1194,32 @@ def __call__(self, indices: mx.array) -> mx.array: result = mx.zeros((len(host_indices), self.dims), dtype=mx.bfloat16) for shard_index in touched: positions = [ - i for i, current_shard in enumerate(shard_indices) + i + for i, current_shard in enumerate(shard_indices) if current_shard == shard_index ] local = [ host_indices[i] - self.shard_offsets[shard_index] for i in positions ] - key = f"{self._prefix}.shard_{shard_index}.weight" - values = self._tensor_readers[key].rows(key, local) + weight_key, scales_key, biases_key, bits, group_size = self._shard_specs[ + shard_index + ] + values = self._tensor_readers[weight_key].rows(weight_key, local) + if bits is not None: + assert scales_key is not None + assert biases_key is not None + assert group_size is not None + scales = self._tensor_readers[scales_key].rows(scales_key, local) + biases = self._tensor_readers[biases_key].rows(biases_key, local) + values = mx.dequantize( + values, + scales, + biases, + group_size=group_size, + bits=bits, + mode="affine", + ) + values = values.astype(mx.bfloat16) * self.weight_scale self.rows_read += len(local) result = result.at[mx.array(positions, dtype=mx.int32)].add(values) return result.reshape(*shape, self.dims) @@ -977,6 +1229,7 @@ def close(self): reader.close() self._readers.clear() self._tensor_readers.clear() + self._shard_specs.clear() @property def _prefix(self): @@ -999,6 +1252,9 @@ def __init__(self, num_embeddings: int, dims: int, num_shards: int): base + (1 if index < remainder else 0) for index in range(num_shards) ) self.shards = [nn.Embedding(size, dims) for size in self.shard_sizes] + # Official FP8 checkpoints keep one shared scale for every PLE shard. + # Decode only the selected rows so the 100 GB table stays compact. + self.weight_scale = mx.ones((1,), dtype=mx.bfloat16) offsets = [0] for size in self.shard_sizes: offsets.append(offsets[-1] + size) @@ -1032,6 +1288,9 @@ def __call__(self, indices: mx.array) -> mx.array: ] positions = mx.array(positions_list, dtype=mx.int32) values = self.shards[shard_index](mx.array(local_indices, dtype=mx.int32)) + if values.dtype == mx.uint8: + values = mx.from_fp8(values, dtype=mx.bfloat16) + values = values * self.weight_scale if result is None: result = mx.zeros((len(host_indices), self.dims), dtype=values.dtype) result = result.at[positions].add(values) @@ -1217,12 +1476,13 @@ def __call__( input_ids: mx.array, cache: Optional[ArraysCache], mask: Optional[mx.array], + target_verify: bool = False, ): embeddings = self.ple_embedding(input_ids, cache) - keys = self.norm_key(self.key_proj(embeddings)).reshape( - *hidden_states.shape[:-1], self.hc_count, self.hidden_size - ) - values = self.value_proj(embeddings) + keys = self.norm_key( + _target_verify_linear(self.key_proj, embeddings, target_verify) + ).reshape(*hidden_states.shape[:-1], self.hc_count, self.hidden_size) + values = _target_verify_linear(self.value_proj, embeddings, target_verify) queries = self.norm_query(hidden_states).reshape( *hidden_states.shape[:-1], self.hc_count, self.hidden_size ) @@ -1265,26 +1525,46 @@ def __call__( mask: Optional[mx.array], cache: Optional[Any], position_ids: Optional[mx.array], + gdn_sink=None, + target_verify: bool = False, ): if "ple" in self: hidden_states = hidden_states + self.ple( - hidden_states, input_ids, cache, mask + hidden_states, + input_ids, + cache, + mask, + target_verify=target_verify, ) mixed, hyper_input, injection_weights = self.attn_hyper_connection( - hidden_states + hidden_states, + target_verify=target_verify, ) if self.is_linear: - branch = self.linear_attn(mixed, mask=mask, cache=cache) + branch = self.linear_attn( + mixed, + mask=mask, + cache=cache, + gdn_sink=gdn_sink, + target_verify=target_verify, + ) else: branch = self.self_attn( - mixed, mask=mask, cache=cache, position_ids=position_ids + mixed, + mask=mask, + cache=cache, + position_ids=position_ids, + target_verify=target_verify, ) injection = branch[..., None, :] * injection_weights[..., None] hidden_states = hyper_input + injection.reshape(*hyper_input.shape) - mixed, hyper_input, injection_weights = self.mlp_hyper_connection(hidden_states) - branch = self.mlp(mixed) + mixed, hyper_input, injection_weights = self.mlp_hyper_connection( + hidden_states, + target_verify=target_verify, + ) + branch = self.mlp(mixed, target_verify=target_verify) injection = branch[..., None, :] * injection_weights[..., None] return hyper_input + injection.reshape(*hyper_input.shape) @@ -1315,6 +1595,7 @@ def __call__( position_ids: Optional[mx.array] = None, capture_layer_ids=None, hidden_sink=None, + gdn_sink=None, **kwargs, ): del kwargs @@ -1339,11 +1620,138 @@ def __call__( mask=layer_mask, cache=layer_cache, position_ids=position_ids, + gdn_sink=gdn_sink, + target_verify=gdn_sink is not None, ) if hidden_sink is not None and index in capture: - hidden_sink.append(self.hyper_connection_mixer(hidden_states)) + hidden_sink.append( + self.hyper_connection_mixer( + hidden_states, + target_verify=gdn_sink is not None, + ) + ) + + if inputs_embeds is None and gdn_sink is None: + host_ref = getattr(self, "_omlx_mtp_prime_host", None) + host = host_ref() if host_ref is not None else None + if host is not None: + from omlx.patches.mlx_lm_mtp import prompt_priming + + if prompt_priming.capture_eligible(host, cache): + prompt_priming.maybe_capture( + host, + inputs, + hidden_states, + cache, + ) + + if hidden_sink is not None and capture_layer_ids == []: + # Lightning MTP consumes all residual streams before the final + # mixer. Ordinary layer captures retain their mixed representation. + hidden_sink.append(hidden_states) + + return self.hyper_connection_mixer( + hidden_states, + target_verify=gdn_sink is not None, + ) + + +class Qwen4ExpMTPModule(nn.Module): + """Embedded one-layer draft head for Qwen4 Lightning MTP.""" + + def __init__(self, args: TextConfig): + super().__init__() + self.hidden_size = args.hidden_size + self.hc_count = args.hc_count + hc_hidden_size = self.hc_count * self.hidden_size + self.pre_fc_norm_embedding = Qwen4ExpRMSNorm( + self.hidden_size, + eps=args.rms_norm_eps, + ) + self.pre_fc_norm_hidden = Qwen4ExpRMSNorm( + hc_hidden_size, + eps=args.rms_norm_eps, + ) + self.fc_embedding = nn.Linear( + self.hidden_size, + self.hidden_size, + bias=False, + ) + self.fc_hidden = nn.Linear( + self.hidden_size, + self.hidden_size, + bias=False, + ) + + layer_config = replace( + args, + num_hidden_layers=1, + layer_types=["qwen_sparse_attention"], + full_attention_interval=1, + ple_layer_ids=[], + ) + self.layers = [Qwen4ExpDecoderLayer(layer_config, layer_idx=0)] + self.hyper_connection_mixer = Qwen4ExpGatedResidual( + layer_config, + use_combine=False, + ) - return self.hyper_connection_mixer(hidden_states) + def fuse_inputs( + self, + token_embeddings: mx.array, + hidden_states: mx.array, + ) -> mx.array: + expected_width = self.hc_count * self.hidden_size + if hidden_states.ndim == 4: + hidden_states = hidden_states.reshape( + *hidden_states.shape[:-2], + expected_width, + ) + if hidden_states.ndim != 3 or hidden_states.shape[-1] != expected_width: + raise ValueError( + "Qwen4 Lightning MTP expects hidden shape " + "[batch, tokens, hc_count * hidden_size]." + ) + + projected_embedding = self.fc_embedding( + self.pre_fc_norm_embedding(token_embeddings) + ) + hidden_streams = self.pre_fc_norm_hidden(hidden_states).reshape( + *hidden_states.shape[:-1], + self.hc_count, + self.hidden_size, + ) + projected_hidden = self.fc_hidden(hidden_streams) + return (projected_embedding[..., None, :] + projected_hidden).reshape( + hidden_states.shape + ) + + def __call__( + self, + hidden_states: mx.array, + next_token_ids: mx.array, + embed_tokens, + cache=None, + ) -> tuple[mx.array, mx.array]: + hidden_states = self.fuse_inputs( + embed_tokens(next_token_ids), + hidden_states, + ) + if cache is None: + cache = [None] * len(self.layers) + mask = _create_qwen3_5_attention_mask( + hidden_states, + cache[0] if cache else None, + ) + for layer, layer_cache in zip(self.layers, cache): + hidden_states = layer( + hidden_states, + next_token_ids, + mask=mask, + cache=layer_cache, + position_ids=None, + ) + return self.hyper_connection_mixer(hidden_states), hidden_states class LanguageModel(Qwen3_5LanguageModel): @@ -1353,11 +1761,77 @@ def __init__(self, args: TextConfig, config: ModelConfig = None): self.config = config self.model_type = args.model_type self.model = Qwen4ExpModel(args) + self.model._omlx_mtp_prime_host = weakref.ref(self) self._position_ids = None self._rope_deltas = None if not args.tie_word_embeddings: self.lm_head = nn.Linear(args.hidden_size, args.vocab_size, bias=False) + def bind_mtp_owner(self, owner) -> None: + """Reference a root-level Lightning MTP head without double registration.""" + self._omlx_qwen4_mtp_owner = weakref.ref(owner) + self._enable_mtp_decode_markers() + + def _enable_mtp_decode_markers(self) -> None: + from omlx.patches.mlx_lm_mtp import get_mtp_depth + + self._omlx_mtp_decode_enabled = True + self._omlx_mtp_chain = True + self._omlx_mtp_depth = get_mtp_depth() + self._omlx_mtp_head_prenorm = True + + def get_mtp_module(self): + module = getattr(self, "mtp", None) + if module is not None: + return module + owner_ref = getattr(self, "_omlx_qwen4_mtp_owner", None) + owner = owner_ref() if owner_ref is not None else None + return getattr(owner, "mtp", None) if owner is not None else None + + def __call__(self, inputs, inputs_embeds=None, mask=None, cache=None, **kwargs): + return_hidden = bool(kwargs.get("return_hidden", False)) + mtp_capture = return_hidden and kwargs.get("capture_layer_ids") is None + if mtp_capture: + kwargs["capture_layer_ids"] = [] + output = super().__call__(inputs, inputs_embeds, mask, cache, **kwargs) + if mtp_capture and output.hidden_states: + output.hidden_states = [output.hidden_states[0]] + return output + + def mtp_forward( + self, + hidden_states, + next_token_ids, + mtp_cache, + return_hidden: bool = False, + logits_keep: int = 0, + ): + mtp = self.get_mtp_module() + if mtp is None: + raise RuntimeError( + "Qwen4 Lightning MTP forward called without an attached head." + ) + mtp_output, hc_hidden = mtp( + hidden_states, + next_token_ids, + self.model.embed_tokens, + mtp_cache, + ) + logits_source = mtp_output + if logits_keep and logits_source.shape[1] > logits_keep: + logits_source = logits_source[:, -logits_keep:, :] + if self.args.tie_word_embeddings: + logits = self.model.embed_tokens.as_linear(logits_source) + else: + logits = self.lm_head(logits_source) + if return_hidden: + return logits, hc_hidden + return logits + + def make_mtp_cache(self): + mtp = self.get_mtp_module() + return [QSAKVCache() for _ in mtp.layers] if mtp is not None else [] + def make_cache(self): caches = [] for layer in self.layers: diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/qwen4_exp.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/qwen4_exp.py index 88c2e93a6c..4f38e5baf9 100644 --- a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/qwen4_exp.py +++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/qwen4_exp.py @@ -1,14 +1,32 @@ import re +import mlx.core as mx import mlx.nn as nn +from omlx.patches.mlx_vlm_mtp.qwen38_fp8 import dequantize_fp8_weights + from ..qwen3_5 import Model as Qwen3_5Model from ..qwen3_5.qwen3_5 import sanitize_key from .config import ModelConfig -from .language import LanguageModel +from .language import ( + LanguageModel, + Qwen4ExpMTPModule, + get_mtp_runtime, + get_ple_runtime_mode, +) from .vision import VisionModel _NGRAM_SHARD_RE = re.compile(r"\.ngram_embedding\.shard_(\d+)(?=\.)") +_NGRAM_STORAGE_RE = re.compile( + r"\.ple\.ple_embedding\.ngram_embedding\." + r"(?:shard_\d+|shards\.\d+)\.(?:weight|scales|biases)$" +) +_MTP_PREFIXES = ( + "model.language_model.mtp.", + "language_model.mtp.", + "model.mtp.", + "mtp.", +) class Model(Qwen3_5Model): @@ -17,32 +35,116 @@ def __init__(self, config: ModelConfig): self.config = config self.vision_tower = VisionModel(config.vision_config) self.language_model = LanguageModel(config.text_config, config) + if get_mtp_runtime().enabled: + self.mtp = Qwen4ExpMTPModule(config.text_config) + self.language_model.bind_mtp_owner(self) def sanitize(self, weights): - # The MTP predictor is a separate speculative artifact and is not part - # of the base conditional-generation model. - weights = { - key: value for key, value in weights.items() if not key.startswith("mtp.") - } + if get_ple_runtime_mode() == "mmap" and not getattr( + self, "_omlx_preserve_qwen4_ple_for_quantization", False + ): + for key in [key for key in weights if _NGRAM_STORAGE_RE.search(key)]: + weights.pop(key) + weights = dequantize_fp8_weights(weights, copy_weights=False) + for layer_id in getattr(self.config.text_config, "ple_layer_ids", ()): + source_scale_key = ( + f"model.language_model.layers.{int(layer_id) - 1}.ple." + "ple_embedding.ngram_embedding.weight_scale" + ) + runtime_scale_key = ( + f"language_model.model.layers.{int(layer_id) - 1}.ple." + "ple_embedding.ngram_embedding.weight_scale" + ) + # Converted MLX checkpoints already use the runtime prefix. Do not + # add the raw-HF default as a second key: sanitize_key() maps both + # spellings to runtime_scale_key, and the default would otherwise + # overwrite a real shared FP8 PLE scale during normalization. + if ( + source_scale_key not in weights + and runtime_scale_key not in weights + ): + weights[source_scale_key] = mx.ones((1,), dtype=mx.bfloat16) + mtp_enabled = get_mtp_runtime().enabled + + normalized = {} + for key, value in weights.items(): + mtp_key = next( + (prefix for prefix in _MTP_PREFIXES if key.startswith(prefix)), + None, + ) + if mtp_key is not None: + if not mtp_enabled: + continue + key = "mtp." + key[len(mtp_key) :] + normalized[key] = value + weights = normalized if self.config.text_config.tie_word_embeddings: weights.pop("lm_head.weight", None) + num_experts = int(getattr(self.config.text_config, "num_experts", 0) or 0) + + def stack_experts(prefix): + if f"{prefix}.switch_mlp.gate_proj.weight" in weights: + return + + gate_up_key = next( + ( + key + for key in ( + f"{prefix}.experts.gate_up_proj", + f"{prefix}.experts.gate_up_proj.weight", + ) + if key in weights + ), + None, + ) + if gate_up_key is not None: + gate, up = mx.split(weights.pop(gate_up_key), 2, axis=-2) + weights[f"{prefix}.switch_mlp.gate_proj.weight"] = gate + weights[f"{prefix}.switch_mlp.up_proj.weight"] = up + for down_key in ( + f"{prefix}.experts.down_proj", + f"{prefix}.experts.down_proj.weight", + ): + if down_key in weights: + weights[f"{prefix}.switch_mlp.down_proj.weight"] = weights.pop( + down_key + ) + break + return + + if f"{prefix}.experts.0.gate_proj.weight" not in weights: + return + for projection in ("gate_proj", "up_proj", "down_proj"): + for suffix in ("weight", "scales", "biases"): + first = f"{prefix}.experts.0.{projection}.{suffix}" + if first not in weights: + continue + weights[f"{prefix}.switch_mlp.{projection}.{suffix}"] = mx.stack( + [ + weights.pop( + f"{prefix}.experts.{expert}.{projection}.{suffix}" + ) + for expert in range(num_experts) + ] + ) + for layer_idx in range(self.config.text_config.num_hidden_layers): - prefix = f"model.language_model.layers.{layer_idx}.mlp" - gate_up_key = f"{prefix}.experts.gate_up_proj" - if gate_up_key in weights: - gate_up = weights.pop(gate_up_key) - midpoint = gate_up.shape[-2] // 2 - weights[f"{prefix}.switch_mlp.gate_proj.weight"] = gate_up[ - ..., :midpoint, : - ] - weights[f"{prefix}.switch_mlp.up_proj.weight"] = gate_up[ - ..., midpoint:, : - ] - weights[f"{prefix}.switch_mlp.down_proj.weight"] = weights.pop( - f"{prefix}.experts.down_proj" - ) + stack_experts(f"model.language_model.layers.{layer_idx}.mlp") + + if mtp_enabled: + mtp_layer_indices = sorted( + { + int(key.split(".")[2]) + for key in weights + if key.startswith("mtp.layers.") + and len(key.split(".")) > 2 + and key.split(".")[2].isdigit() + } + ) + for layer_idx in mtp_layer_indices: + stack_experts(f"mtp.layers.{layer_idx}.mlp") sanitized = {} for key, value in weights.items(): @@ -57,7 +159,9 @@ def close(self): """Release external PLE mmap handles during oMLX model unload.""" for layer in self.language_model.model.layers: ple = getattr(layer, "ple", None) - embedding = getattr(getattr(ple, "ple_embedding", None), "ngram_embedding", None) + embedding = getattr( + getattr(ple, "ple_embedding", None), "ngram_embedding", None + ) close = getattr(embedding, "close", None) if close is not None: close() diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/virtual_ple.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/virtual_ple.py new file mode 100644 index 0000000000..6fabfdfd92 --- /dev/null +++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/virtual_ple.py @@ -0,0 +1,108 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Streaming FP8 PLE support for Qwen4-Exp oQ conversion. + +The FP8 Qwen3.8-Flash-Next checkpoint variant stores each N-gram PLE shard +as raw F8_E4M3 rows and keeps one shared ``weight_scale`` for the whole +sharded embedding. That layout is intentionally different from the +ordinary ``weight`` + per-module scale pairs handled by +:class:`_LazyTensorIndex`. The official BF16 checkpoint uses the same shard +names but remains on the normal floating-point path. + +The runtime decodes a selected FP8 row first and applies the shared scale +afterwards. oQ must preserve the same ordering: decode the raw FP8 shard, +quantize those unscaled values to affine storage, and keep ``weight_scale`` +for the runtime to apply exactly once. Exposing the shard as a virtual BF16 +tensor makes sanitize-plan discovery and the streaming quantizer see the +correct logical dtype without materializing the 51.2B PLE table eagerly. +""" + +from __future__ import annotations + +import logging +import weakref + +import mlx.core as mx + +logger = logging.getLogger(__name__) + +_FP8_DTYPE = "F8_E4M3" + + +def _is_qwen4_exp(config: dict) -> bool: + text_config = config.get("text_config") + if not isinstance(text_config, dict): + text_config = {} + return any( + str(model_type or "").lower().startswith("qwen4_exp") + for model_type in (config.get("model_type"), text_config.get("model_type")) + ) + + +def _candidate_keys(config: dict): + text_config = config.get("text_config") + if not isinstance(text_config, dict): + return + num_shards = int(text_config.get("split_ngram_parts", 0) or 0) + if num_shards <= 0: + return + for layer_id in text_config.get("ple_layer_ids", ()) or (): + layer_index = int(layer_id) - 1 + if layer_index < 0: + continue + prefixes = ( + f"model.language_model.layers.{layer_index}.ple.ple_embedding." + "ngram_embedding", + f"language_model.model.layers.{layer_index}.ple.ple_embedding." + "ngram_embedding", + ) + for shard_index in range(num_shards): + for prefix in prefixes: + yield f"{prefix}.shard_{shard_index}.weight" + yield f"{prefix}.shards.{shard_index}.weight" + + +def _materializer(index_ref, key: str): + def materialize(): + index = index_ref() + if index is None: + raise RuntimeError( + "Qwen4 PLE materializer outlived its tensor index; the index " + "must stay alive while virtual tensors are being read" + ) + raw = index.load_source(key) + decoded = mx.from_fp8(raw, dtype=mx.bfloat16) + mx.eval(decoded) + del raw + return decoded + + return materialize + + +def register(index, config: dict) -> int: + """Expose raw Qwen4 PLE FP8 shards as unscaled BF16 virtual tensors.""" + if not _is_qwen4_exp(config): + return 0 + + index_ref = weakref.ref(index) + registered = 0 + for key in _candidate_keys(config): + shape = index.source_shape(key) + if shape is None or index.source_dtype(key) != _FP8_DTYPE: + continue + if len(shape) != 2: + raise ValueError(f"Qwen4 PLE shard must be rank 2, got {key}: {shape}") + index.register_virtual( + key, + shape, + "BF16", + _materializer(index_ref, key), + hides=(key,), + ) + registered += 1 + + if registered: + logger.info( + "Qwen4 PLE: %d raw FP8 shards exposed as streaming BF16 tensors", + registered, + ) + return registered diff --git a/omlx/patches/virtual_tensors.py b/omlx/patches/virtual_tensors.py index 65bd94739d..c62d1891b2 100644 --- a/omlx/patches/virtual_tensors.py +++ b/omlx/patches/virtual_tensors.py @@ -36,9 +36,12 @@ def register_virtual_tensors(index, config) -> int: quantized silently. """ from .mimo_v2.virtual_qkv import register as register_mimo_v2_qkv + from .mlx_vlm_qwen4_exp_compat.virtual_ple import ( + register as register_qwen4_exp_ple, + ) # Import errors are deliberately not caught. A registrar that fails to # load leaves its checkpoint in the layout the quantizer cannot read, so # swallowing that would turn a packaging fault into a silently wrong # quantization. - return register_mimo_v2_qkv(index, config) + return register_mimo_v2_qkv(index, config) + register_qwen4_exp_ple(index, config) diff --git a/omlx/scheduler.py b/omlx/scheduler.py index d22f4f4dd5..a808da92ac 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -358,6 +358,7 @@ def has_capacity(self) -> bool: MemoryMonitor, collect_kv_layer_specs, estimate_mla_kv_bytes_per_token, + estimate_qwen4_exp_kv_bytes_per_token, make_prefill_memory_profile, ) @@ -368,6 +369,7 @@ def has_capacity(self) -> bool: MemoryMonitor = None collect_kv_layer_specs = None estimate_mla_kv_bytes_per_token = None + estimate_qwen4_exp_kv_bytes_per_token = None make_prefill_memory_profile = None HAS_TIERED_CACHE = False @@ -7455,6 +7457,9 @@ def _extract_cache_states( if handler is not None and class_name in ( "MiniMaxM3KVCache", "MiniMaxM3BatchKVCache", + "QSAKVCache", + "QSAQuantizedKVCache", + "BatchQSAKVCache", ): state = handler.serialize_state(layer_cache) meta = handler.serialize_meta_state(layer_cache) @@ -12217,15 +12222,22 @@ def _dtype_matches(dtype: Any, expected: Any) -> bool: else: dtype_size = tq_dtype_size - kv_bytes_per_token = ( - estimate_mla_kv_bytes_per_token( + kv_bytes_per_token = None + if estimate_qwen4_exp_kv_bytes_per_token is not None: + kv_bytes_per_token = estimate_qwen4_exp_kv_bytes_per_token( + config, + cache_list_for_tq, + base_dtype_size, + ) + if ( + kv_bytes_per_token is None + and estimate_mla_kv_bytes_per_token is not None + ): + kv_bytes_per_token = estimate_mla_kv_bytes_per_token( config, cache_list_for_tq, base_dtype_size, ) - if estimate_mla_kv_bytes_per_token is not None - else None - ) prefill_memory_profile = ( make_prefill_memory_profile( config, diff --git a/omlx/utils/image.py b/omlx/utils/image.py index 734138149e..56e4f6a97c 100644 --- a/omlx/utils/image.py +++ b/omlx/utils/image.py @@ -11,14 +11,12 @@ import binascii import hashlib import io -import tempfile from typing import Any, Dict, List, Optional, Tuple from PIL import Image, ImageOps from ..exceptions import InvalidRequestError - _IMAGE_INPUT_ERROR = ( "Image inputs must be base64 data URIs " "(data:image/...;base64,...). Remote URLs and local file paths are not supported." @@ -27,10 +25,6 @@ "input_audio.data must be a base64 string or base64 data URI. " "Local file paths are not supported." ) -_VIDEO_INPUT_ERROR = ( - "video_url.url must be a base64 data URI (data:video/...;base64,...). " - "Remote URLs and local file paths are not supported." -) def _decode_base64_data_uri(value: str, *, field: str) -> bytes: @@ -82,35 +76,6 @@ def _decode_input_audio_data(data: str, *, field: str = "input_audio.data") -> b raise InvalidRequestError(_AUDIO_INPUT_ERROR, field=field) from exc -def load_video_data_uri(value: str, *, field: str = "video_url.url", fps=2.0): - """Decode an inline video and return the sampled frame array.""" - if not isinstance(value, str) or not value.strip().startswith("data:video/"): - raise InvalidRequestError(_VIDEO_INPUT_ERROR, field=field) - prefix, separator, encoded = value.strip().partition(",") - if separator != "," or ";base64" not in prefix.lower(): - raise InvalidRequestError(_VIDEO_INPUT_ERROR, field=field) - try: - payload = base64.b64decode(encoded, validate=True) - except (binascii.Error, ValueError) as exc: - raise InvalidRequestError(_VIDEO_INPUT_ERROR, field=field) from exc - subtype = prefix.split("/", 1)[1].split(";", 1)[0].lower() - suffix = ".mov" if subtype in {"quicktime", "mov"} else f".{subtype}" - from mlx_vlm.utils import load_video - - try: - with tempfile.NamedTemporaryFile(suffix=suffix) as handle: - handle.write(payload) - handle.flush() - frames, sampled_fps = load_video(handle.name, fps=float(fps or 2.0)) - except InvalidRequestError: - raise - except Exception as exc: - raise InvalidRequestError( - f"{field} does not contain a decodable video.", field=field - ) from exc - return frames, sampled_fps - - def validate_image_data_uri(value: str, *, field: str = "image") -> str: """Validate that a request-facing image reference is an inline data URI.""" _decode_base64_data_uri(value, field=field) @@ -151,9 +116,7 @@ def load_image(url_or_base64: str, *, field: str = "image_url") -> Image.Image: def extract_images_from_messages( messages: List[Dict[str, Any]], - *, - include_videos: bool = False, -): +) -> Tuple[List[Dict[str, Any]], List[Image.Image], List]: """ Extract images and audio from OpenAI-format messages. @@ -175,7 +138,6 @@ def extract_images_from_messages( text_messages = [] images = [] audio = [] - videos = [] for msg in messages: role = msg.get("role", "user") @@ -247,23 +209,10 @@ def extract_images_from_messages( audio.append(data) elif part_type in ("video", "video_url", "input_video"): - video_obj = ( - part.get("video_url") - if isinstance(part, dict) - else getattr(part, "video_url", None) + raise InvalidRequestError( + "Video input is not supported by oMLX.", + field="messages", ) - if video_obj is None and isinstance(part, dict): - video_obj = part.get("video") or part.get("input_video") - if isinstance(video_obj, str): - url, fps = video_obj, 2.0 - elif isinstance(video_obj, dict): - url, fps = video_obj.get("url"), video_obj.get("fps", 2.0) - else: - url = getattr(video_obj, "url", None) - fps = getattr(video_obj, "fps", 2.0) - if url: - frames, _sampled_fps = load_video_data_uri(url, fps=fps) - videos.append(frames) new_msg = {"role": role, "content": "\n".join(text_parts) if text_parts else ""} # Preserve extra fields @@ -272,8 +221,6 @@ def extract_images_from_messages( new_msg[key] = msg[key] text_messages.append(new_msg) - if include_videos: - return text_messages, images, audio, videos return text_messages, images, audio diff --git a/omlx/utils/model_loading.py b/omlx/utils/model_loading.py index 0b54ea3dd4..ee8d2b1d38 100644 --- a/omlx/utils/model_loading.py +++ b/omlx/utils/model_loading.py @@ -627,7 +627,52 @@ def maybe_apply_pre_load_patches( "Qwen4-Exp mlx-vlm compatibility patch applied for %s", model_name, ) - configure_qwen4_exp_runtime(model_name) + mtp_requested = bool( + model_settings is not None and getattr(model_settings, "mtp_enabled", False) + ) + has_mtp_weights = _checkpoint_has_mtp_weights(model_name) + mtp_active = mtp_requested and has_mtp_weights + if mtp_requested and not has_mtp_weights: + logger.warning( + "Qwen4-Exp Lightning MTP was requested for %s, but no embedded " + "MTP tensors were found", + model_name, + ) + + from ..patches.mlx_lm_mtp import ( + apply_mlx_lm_mtp_patch, + set_mtp_active, + set_mtp_depth, + ) + + set_mtp_active(mtp_active) + depth = ( + getattr(model_settings, "mtp_num_draft_tokens", None) + if model_settings is not None + else None + ) + # Qwen4-Exp uses the same adaptive draft-depth controller as the + # general Lightning MTP path. A single MTP hidden layer can be + # chained autoregressively, so default to the validated max depth 3. + set_mtp_depth(int(depth) if depth else 3) + if mtp_active and not apply_mlx_lm_mtp_patch(): + logger.warning( + "Qwen4-Exp Lightning MTP dispatch patch failed for %s; " + "speculative decoding will remain inactive", + model_name, + ) + set_mtp_active(False) + mtp_active = False + configure_qwen4_exp_runtime( + model_name, + mode=( + "mmap" + if model_settings is not None + and getattr(model_settings, "qwen4_ple_ssd_offload", False) + else "resident" if model_settings is not None else None + ), + mtp_enabled=mtp_active, + ) # Apply the MTP patch whenever the model has MTP heads on a compatible # model_type — even when mtp_enabled is False. The patch is required @@ -784,7 +829,11 @@ def maybe_apply_pre_load_patches( "load only)", model_name, ) - elif model_settings is not None and getattr(model_settings, "mtp_enabled", False): + elif ( + model_type != "qwen4_exp" + and model_settings is not None + and getattr(model_settings, "mtp_enabled", False) + ): logger.warning( "mtp_enabled=True for %s but model is incompatible " "(model_type=%r, mtp_heads=%s); MTP path will be inactive", diff --git a/tests/test_admin_api_key.py b/tests/test_admin_api_key.py index 39f69caa91..da7fac43b6 100644 --- a/tests/test_admin_api_key.py +++ b/tests/test_admin_api_key.py @@ -81,6 +81,58 @@ def test_list_models_includes_all_model_settings_fields(self): assert settings_dict["max_tokens"] == 4096 assert settings_dict["temperature"] == 0.7 + def test_list_models_reports_forced_qwen4_ple_offload(self, tmp_path): + from omlx.patches.mlx_vlm_qwen4_exp_compat.residency import ( + Qwen4ExpResidencyEstimate, + ) + + model_path = tmp_path / "qwen4" + model_path.mkdir() + estimate = Qwen4ExpResidencyEstimate( + supported=True, + checkpoint_bytes=950, + ple_bytes=550, + resident_bytes=1000, + mmap_bytes=400, + ) + pool = MagicMock() + pool.get_status.return_value = { + "models": [ + { + "id": "qwen4", + "model_path": str(model_path), + "config_model_type": "qwen4_exp", + "estimated_size": 1000, + } + ] + } + pool._fallback_admission_ceiling.return_value = 500 + manager = MagicMock() + manager.get_all_settings.return_value = {} + state = MagicMock(default_model=None) + + with ( + patch.object(admin_routes, "_get_engine_pool", return_value=pool), + patch.object(admin_routes, "_get_settings_manager", return_value=manager), + patch.object(admin_routes, "_get_server_state", return_value=state), + patch.object(admin_routes, "_get_global_settings", return_value=None), + patch.object(admin_routes, "_dflash_compat_for_model", return_value=(False, "")), + patch.object(admin_routes, "_mtp_compat_for_model", return_value=(False, "")), + patch.object(admin_routes, "_paroquant_compat_for_model", return_value=(False, "")), + patch( + "omlx.patches.mlx_vlm_qwen4_exp_compat.residency." + "qwen4_exp_residency_estimate", + return_value=estimate, + ), + ): + result = asyncio.run(admin_routes.list_models(is_admin=True)) + + model = result["models"][0] + assert model["qwen4_ple_ssd_offload_supported"] is True + assert model["qwen4_ple_ssd_offload_forced"] is True + assert model["qwen4_ple_resident_bytes"] == 1000 + assert model["qwen4_ple_mmap_bytes"] == 400 + def test_list_models_adds_display_name_without_changing_id(self, tmp_path): """Ensure nested model paths only affect UI display names.""" model_root = tmp_path / "models" diff --git a/tests/test_admin_model_settings.py b/tests/test_admin_model_settings.py index c3f914e026..b211ed6d0e 100644 --- a/tests/test_admin_model_settings.py +++ b/tests/test_admin_model_settings.py @@ -168,6 +168,35 @@ async def test_qwen_ane_prefill_accepts_qwen38_config_type(): assert settings.qwen35_ane_prefill_enabled is True +@pytest.mark.asyncio +async def test_qwen4_ple_ssd_offload_is_persisted_for_qwen4_only(): + pool, entry = _failed_pool() + entry.config_model_type = "qwen4_exp" + settings = ModelSettings() + + await _update_settings( + pool, + settings, + admin_routes.ModelSettingsRequest(qwen4_ple_ssd_offload=True), + ) + + assert settings.qwen4_ple_ssd_offload is True + + +@pytest.mark.asyncio +async def test_qwen4_ple_ssd_offload_is_ignored_for_other_models(): + pool, _ = _failed_pool() + settings = ModelSettings() + + await _update_settings( + pool, + settings, + admin_routes.ModelSettingsRequest(qwen4_ple_ssd_offload=True), + ) + + assert settings.qwen4_ple_ssd_offload is False + + @pytest.mark.asyncio async def test_qwen_ane_prefill_rejects_invalid_block_size(): pool, entry = _failed_pool() diff --git a/tests/test_api_utils.py b/tests/test_api_utils.py index 89038dca7e..61db90588f 100644 --- a/tests/test_api_utils.py +++ b/tests/test_api_utils.py @@ -56,6 +56,7 @@ prepare_system_messages_for_template, uses_native_reasoning_content, ) +from omlx.exceptions import InvalidRequestError class TestReasoningEffortChatTemplateKwargs: @@ -3109,6 +3110,13 @@ def test_input_audio_with_model_dump(self): assert parts[0]["type"] == "input_audio" assert parts[0]["input_audio"]["format"] == "wav" + @pytest.mark.parametrize("part_type", ["video_url", "input_video"]) + def test_video_input_is_rejected(self, part_type): + with pytest.raises(InvalidRequestError, match="Video input is not supported"): + _extract_multimodal_content_list( + [{"type": part_type, part_type: {"url": "data:video/mp4;base64,AA=="}}] + ) + # ============================================================================= # Partial Mode & Name Preservation diff --git a/tests/test_engine_pool.py b/tests/test_engine_pool.py index f03986b613..1cd94ad8ef 100644 --- a/tests/test_engine_pool.py +++ b/tests/test_engine_pool.py @@ -632,6 +632,47 @@ def test_enabled_cpu_share_fails_closed_when_geometry_is_unreadable(self, tmp_pa assert pool._entry_runtime_resident_size(entry, settings) == 2000 + def test_qwen4_ple_offload_reduces_resident_projection(self, tmp_path): + from omlx.model_settings import ModelSettings + from omlx.patches.mlx_vlm_qwen4_exp_compat.residency import ( + Qwen4ExpResidencyEstimate, + ) + + model = tmp_path / "qwen4" + model.mkdir() + settings = ModelSettings(qwen4_ple_ssd_offload=False) + entry = EngineEntry( + model_id="qwen4", + model_path=str(model), + model_type="vlm", + engine_type="vlm", + config_model_type="qwen4_exp", + estimated_size=1000, + ) + estimate = Qwen4ExpResidencyEstimate( + supported=True, + checkpoint_bytes=950, + ple_bytes=550, + resident_bytes=1000, + mmap_bytes=400, + ) + pool = _make_pool(ceiling=500) + pool._entries[entry.model_id] = entry + + with patch( + "omlx.patches.mlx_vlm_qwen4_exp_compat.residency." + "qwen4_exp_residency_estimate", + return_value=estimate, + ): + projected = pool._entry_runtime_resident_size(entry, settings) + effective = pool._effective_qwen4_model_settings(entry, settings) + signature = dict(pool._engine_runtime_signature("qwen4", settings)) + + assert projected == 400 + assert settings.qwen4_ple_ssd_offload is False + assert effective.qwen4_ple_ssd_offload is True + assert signature["qwen4_ple_ssd_offload"] == "True" + class TestApplySettingsOverrides: """Tests for apply_settings_overrides method.""" diff --git a/tests/test_image_utils.py b/tests/test_image_utils.py index 293cf59757..c4887f2baa 100644 --- a/tests/test_image_utils.py +++ b/tests/test_image_utils.py @@ -419,8 +419,7 @@ def test_audio_mixed_with_images(self): assert "Describe this image and audio" in text_msgs[0]["content"] -def test_extract_inline_video_when_requested(): - frames = MagicMock(name="frames") +def test_video_input_is_rejected(): messages = [ { "role": "user", @@ -437,18 +436,8 @@ def test_extract_inline_video_when_requested(): } ] - with patch( - "omlx.utils.image.load_video_data_uri", return_value=(frames, 3.0) - ) as load: - text, images, audio, videos = extract_images_from_messages( - messages, include_videos=True - ) - - load.assert_called_once_with("data:video/mp4;base64,AAAA", fps=3) - assert text == [{"role": "user", "content": "Describe"}] - assert images == [] - assert audio == [] - assert videos == [frames] + with pytest.raises(InvalidRequestError, match="Video input is not supported"): + extract_images_from_messages(messages) # ============================================================================= diff --git a/tests/test_memory_monitor_vlm_config.py b/tests/test_memory_monitor_vlm_config.py index ef5fa53e4f..0bee8fd696 100644 --- a/tests/test_memory_monitor_vlm_config.py +++ b/tests/test_memory_monitor_vlm_config.py @@ -22,7 +22,9 @@ _SDPA_VECTOR_QUERY_TOKEN_THRESHOLD, _SDPA_VECTOR_SUPPORTED_HEAD_DIMS, MemoryMonitor, + collect_kv_layer_specs, estimate_mla_kv_bytes_per_token, + estimate_qwen4_exp_kv_bytes_per_token, ) from omlx.scheduler import Scheduler, SchedulerConfig @@ -95,6 +97,17 @@ class _GlmMlaConfig: index_head_dim = 128 +class _Qwen4Config: + model_type = "qwen4_exp" + num_key_value_heads = 2 + head_dim = 128 + indexer_head_dim = 128 + + +class QSAKVCache: + pass + + class _VLMConfigEmptySubConfigs: """Sub-configs are present but expose no layer count — skip and fall back to the top-level config. Defends against accidentally walking @@ -107,6 +120,20 @@ class _VLMConfigEmptySubConfigs: text_config = MagicMock(spec=["something_else"]) # no layer count +def test_qwen4_qsa_memory_includes_indexer_and_mrope_state(): + caches = [QSAKVCache() for _ in range(12)] + + full_layers, rotating, arrays = collect_kv_layer_specs(caches) + estimate = estimate_qwen4_exp_kv_bytes_per_token( + _Qwen4Config(), + caches, + dtype_size=2, + ) + + assert (full_layers, rotating, arrays) == (12, [], 0) + assert estimate == 12 * (2 * 2 * 128 * 2 + 128 * 2 + 3 * 8) + + class TestSetModelInfoForMonitorVLMWalk: """``_set_model_info_for_monitor`` must prefer LM dimensions from a nested sub-config when one exists, otherwise fall back to top-level.""" diff --git a/tests/test_mlx_vlm_qwen4_exp_compat.py b/tests/test_mlx_vlm_qwen4_exp_compat.py index a85ae13c8f..0ae4b54473 100644 --- a/tests/test_mlx_vlm_qwen4_exp_compat.py +++ b/tests/test_mlx_vlm_qwen4_exp_compat.py @@ -121,6 +121,105 @@ def test_qwen4_exp_sanitize_keeps_converted_norm_values(): assert mx.array_equal(result["language_model.model.norm.weight"], norm).item() +def test_qwen4_exp_sanitize_keeps_converted_ple_shared_scale(): + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp.qwen4_exp import Model + + key = ( + "language_model.model.layers.1.ple.ple_embedding." + "ngram_embedding.weight_scale" + ) + scale = mx.array([0.0002], dtype=mx.bfloat16) + model = SimpleNamespace( + config=SimpleNamespace( + text_config=SimpleNamespace( + tie_word_embeddings=False, + num_hidden_layers=0, + num_experts=0, + ple_layer_ids=[2], + ) + ) + ) + + result = Model.sanitize(model, {key: scale}) + + assert list(name for name in result if name.endswith("weight_scale")) == [key] + assert mx.array_equal(result[key], scale).item() + + +def test_qwen4_exp_sanitize_adds_unit_ple_scale_for_bf16_checkpoint(): + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp.qwen4_exp import Model + + key = ( + "language_model.model.layers.1.ple.ple_embedding." + "ngram_embedding.weight_scale" + ) + model = SimpleNamespace( + config=SimpleNamespace( + text_config=SimpleNamespace( + tie_word_embeddings=False, + num_hidden_layers=0, + num_experts=0, + ple_layer_ids=[2], + ) + ) + ) + + result = Model.sanitize(model, {}) + + assert list(name for name in result if name.endswith("weight_scale")) == [key] + assert mx.array_equal( + result[key], mx.ones((1,), dtype=mx.bfloat16) + ).item() + + +def test_qwen4_quantization_sanitize_keeps_mmap_ple_shards(tmp_path): + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp.language import configure_ple_runtime + from mlx_vlm.models.qwen4_exp.qwen4_exp import Model + + config = SimpleNamespace( + text_config=SimpleNamespace( + tie_word_embeddings=False, + num_hidden_layers=0, + num_experts=0, + ple_layer_ids=(), + ) + ) + key = ( + "model.language_model.layers.1.ple.ple_embedding." + "ngram_embedding.shard_0.weight" + ) + base = key.removesuffix(".weight") + weights = { + key: mx.zeros((2, 20), dtype=mx.uint32), + f"{base}.scales": mx.ones((2, 5), dtype=mx.bfloat16), + f"{base}.biases": mx.zeros((2, 5), dtype=mx.bfloat16), + } + runtime_model = SimpleNamespace(config=config) + quantization_proxy = SimpleNamespace( + config=config, + _omlx_preserve_qwen4_ple_for_quantization=True, + ) + + configure_ple_runtime(tmp_path, mode="mmap") + try: + assert Model.sanitize(runtime_model, dict(weights)) == {} + sanitized = Model.sanitize(quantization_proxy, dict(weights)) + finally: + configure_ple_runtime(tmp_path, mode="resident") + + sanitized_key = ( + "language_model.model.layers.1.ple.ple_embedding." + "ngram_embedding.shards.0.weight" + ) + assert sanitized_key in sanitized + assert sanitized[sanitized_key].shape == (2, 20) + assert sanitized_key.removesuffix(".weight") + ".scales" in sanitized + assert sanitized_key.removesuffix(".weight") + ".biases" in sanitized + + def test_qwen4_exp_tiny_text_prefill_and_decode(): from mlx_vlm.models.qwen4_exp.language import LanguageModel @@ -134,7 +233,183 @@ def test_qwen4_exp_tiny_text_prefill_and_decode(): assert next_logits.logits.shape == (1, 1, 64) +def test_qwen4_fp8_ple_dequantizes_only_selected_rows(): + _tiny_config() + from mlx_vlm.models.qwen4_exp.language import ShardedEmbedding + + embedding = ShardedEmbedding(num_embeddings=4, dims=2, num_shards=2) + embedding.shards[0].weight = mx.to_fp8( + mx.array([[1.0, 2.0], [3.0, 4.0]], dtype=mx.float32) + ) + embedding.shards[1].weight = mx.to_fp8( + mx.array([[5.0, 6.0], [7.0, 8.0]], dtype=mx.float32) + ) + embedding.weight_scale = mx.array([0.25], dtype=mx.bfloat16) + + result = embedding(mx.array([[1, 2]], dtype=mx.int32)) + expected = mx.array([[[0.75, 1.0], [1.25, 1.5]]], dtype=mx.bfloat16) + + assert mx.array_equal(result, expected).item() + + +def test_qwen4_qsa_cache_round_trip_preserves_greedy_decode(): + config = _tiny_config() + from mlx_vlm.models.qwen4_exp.language import LanguageModel + + from omlx.cache.type_registry import CacheTypeRegistry + + model = LanguageModel(config.text_config, config) + full_cache = model.make_cache() + prefix_cache = model.make_cache() + + full = model(mx.array([[2, 3, 4, 5]], dtype=mx.int32), cache=full_cache) + model(mx.array([[2, 3, 4]], dtype=mx.int32), cache=prefix_cache) + + restored = [] + for cache in prefix_cache: + handler = CacheTypeRegistry.get_handler_by_class_name(type(cache).__name__) + state = handler.extract_state(cache) + if type(cache).__name__ == "ArraysCache": + restored.append(handler.reconstruct_cache(state, token_count=3)) + else: + restored.append(handler.reconstruct_cache(state)) + + resumed = model(mx.array([[5]], dtype=mx.int32), cache=restored) + expected = mx.argmax(full.logits[:, -1], axis=-1) + actual = mx.argmax(resumed.logits[:, -1], axis=-1) + mx.eval(expected, actual) + + assert mx.array_equal(actual, expected).item() + assert restored[1].index_keys.shape[1] == 4 + assert restored[1].index_position_ids.shape[-1] == 4 + + +def test_qwen4_verify_matches_singleton_greedy_and_rolls_back_qsa(): + config = _tiny_config() + from mlx_vlm.models.qwen4_exp.language import LanguageModel + + model = LanguageModel(config.text_config, config) + verify_cache = model.make_cache() + singleton_cache = model.make_cache() + prefix = mx.array([[2, 3, 4]], dtype=mx.int32) + model(prefix, cache=verify_cache) + model(prefix, cache=singleton_cache) + + verified = model( + mx.array([[5, 6]], dtype=mx.int32), + cache=verify_cache, + return_hidden=True, + ) + first = model(mx.array([[5]], dtype=mx.int32), cache=singleton_cache) + second = model(mx.array([[6]], dtype=mx.int32), cache=singleton_cache) + singleton_logits = mx.concatenate([first.logits, second.logits], axis=1) + verified_tokens = mx.argmax(verified.logits, axis=-1) + singleton_tokens = mx.argmax(singleton_logits, axis=-1) + mx.eval(verified_tokens, singleton_tokens) + + assert mx.array_equal(verified_tokens, singleton_tokens).item() + assert verified.hidden_states[0].shape == (1, 2, 64) + assert len(verified.gdn_states) == 1 + + model.rollback_speculative_cache( + verify_cache, + verified.gdn_states, + accepted=0, + block_size=2, + ) + qsa_cache = verify_cache[1] + assert qsa_cache.offset == 4 + assert qsa_cache.index_keys.shape[1] == 4 + assert qsa_cache.index_position_ids.shape[-1] == 4 + + +def test_qwen4_lightning_mtp_fusion_and_runtime_attachment(tmp_path): + config = _tiny_config() + from mlx_vlm.models.qwen4_exp.language import ( + Qwen4ExpMTPModule, + configure_mtp_runtime, + ) + from mlx_vlm.models.qwen4_exp.qwen4_exp import Model + + (tmp_path / "model.safetensors.index.json").write_text( + json.dumps({"weight_map": {"mtp.fc_hidden.weight": "model.safetensors"}}), + encoding="utf-8", + ) + configure_mtp_runtime(tmp_path, enabled=True) + try: + model = Model(config) + assert isinstance(model.mtp, Qwen4ExpMTPModule) + assert model.language_model.get_mtp_module() is model.mtp + assert model.language_model._omlx_mtp_decode_enabled is True + + head = model.mtp + head.fc_embedding.weight = mx.eye(config.text_config.hidden_size) + head.fc_hidden.weight = mx.eye(config.text_config.hidden_size) + embedding = mx.arange(1, 33, dtype=mx.float32).reshape(1, 1, 32) + hidden = mx.arange(1, 65, dtype=mx.float32).reshape(1, 1, 64) + actual = head.fuse_inputs(embedding, hidden) + expected_embedding = embedding * mx.rsqrt( + mx.mean(embedding * embedding, axis=-1, keepdims=True) + + config.text_config.rms_norm_eps + ) + expected_hidden = hidden * mx.rsqrt( + mx.mean(hidden * hidden, axis=-1, keepdims=True) + + config.text_config.rms_norm_eps + ) + expected = ( + expected_embedding[..., None, :] + expected_hidden.reshape(1, 1, 2, 32) + ).reshape(1, 1, 64) + + assert mx.allclose(actual, expected, atol=2e-5).item() + finally: + configure_mtp_runtime(tmp_path, enabled=False) + + +def test_qwen4_sanitize_dequantizes_and_stacks_fp8_experts(tmp_path): + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp.language import configure_mtp_runtime + from mlx_vlm.models.qwen4_exp.qwen4_exp import Model + + (tmp_path / "model.safetensors.index.json").write_text( + json.dumps({"weight_map": {"mtp.fc_hidden.weight": "model.safetensors"}}), + encoding="utf-8", + ) + configure_mtp_runtime(tmp_path, enabled=True) + try: + model = SimpleNamespace( + config=SimpleNamespace( + text_config=SimpleNamespace( + tie_word_embeddings=False, + num_hidden_layers=1, + num_experts=4, + ) + ) + ) + weights = {} + for root in ( + "model.language_model.layers.0.mlp", + "mtp.layers.0.mlp", + ): + for expert in range(4): + for projection in ("gate_proj", "up_proj", "down_proj"): + key = f"{root}.experts.{expert}.{projection}.weight" + weights[key] = mx.to_fp8(mx.ones((2, 2), dtype=mx.float32)) + weights[f"{key}_scale_inv"] = mx.ones((1, 1)) + + result = Model.sanitize(model, weights) + + base_key = "language_model.model.layers.0.mlp.switch_mlp.gate_proj.weight" + mtp_key = "mtp.layers.0.mlp.switch_mlp.gate_proj.weight" + assert result[base_key].shape == (4, 2, 2) + assert result[mtp_key].shape == (4, 2, 2) + assert result[base_key].dtype == mx.bfloat16 + assert not any(key.endswith("weight_scale_inv") for key in result) + finally: + configure_mtp_runtime(tmp_path, enabled=False) + + def test_disk_backed_bf16_ple_reads_only_requested_rows(tmp_path): + compat.apply_mlx_vlm_qwen4_exp_compat_patch() from mlx_vlm.models.qwen4_exp.language import DiskBackedShardedEmbedding prefix = ( @@ -167,6 +442,63 @@ def test_disk_backed_bf16_ple_reads_only_requested_rows(tmp_path): embedding.close() +@pytest.mark.parametrize("bits", [2, 3, 4, 5, 6, 8]) +def test_disk_backed_affine_ple_supports_all_oq_bits(tmp_path, bits): + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp.language import DiskBackedShardedEmbedding + + source_prefix = "model.language_model.layers.1.ple.ple_embedding.ngram_embedding" + stored_prefix = "language_model.model.layers.1.ple.ple_embedding.ngram_embedding" + tensors = {} + expected_rows = [] + for shard_index in range(2): + dense = ( + mx.arange(4 * 160, dtype=mx.float32).reshape(4, 160) / 97 + + shard_index * 10 + ).astype(mx.bfloat16) + weight, scales, biases = mx.quantize( + dense, group_size=32, bits=bits, mode="affine" + ) + base = f"{stored_prefix}.shards.{shard_index}" + tensors[f"{base}.weight"] = weight + tensors[f"{base}.scales"] = scales + tensors[f"{base}.biases"] = biases + expected_rows.append( + mx.dequantize( + weight, + scales, + biases, + group_size=32, + bits=bits, + mode="affine", + ) + ) + + filename = "model-00001-of-00001.safetensors" + mx.save_safetensors(str(tmp_path / filename), tensors, metadata={"format": "mlx"}) + (tmp_path / "model.safetensors.index.json").write_text( + json.dumps({"weight_map": {key: filename for key in tensors}}), + encoding="utf-8", + ) + + embedding = DiskBackedShardedEmbedding( + tmp_path, + source_prefix, + num_embeddings=8, + dims=160, + num_shards=2, + ) + values = embedding(mx.array([[1, 6]], dtype=mx.int32)) + mx.eval(values) + expected = mx.stack([expected_rows[0][1], expected_rows[1][2]])[None] + + assert mx.allclose(values, expected, atol=2e-2, rtol=2e-2).item() + assert embedding.last_touched_shards == (0, 1) + assert embedding.rows_read == 2 + assert embedding._shard_specs[0][3:] == (bits, 32) + embedding.close() + + def test_external_ple_path_is_bounded_and_ssd_alias_resolves(tmp_path): compute = tmp_path / "compute" ple = tmp_path / "ple" @@ -183,4 +515,9 @@ def test_external_ple_path_is_bounded_and_ssd_alias_resolves(tmp_path): ), encoding="utf-8", ) - assert compat.configure_qwen4_exp_runtime(compute) == "mmap" + try: + assert compat.configure_qwen4_exp_runtime(compute) == "mmap" + finally: + from mlx_vlm.models.qwen4_exp.language import configure_ple_runtime + + configure_ple_runtime(compute, mode="resident") diff --git a/tests/test_openai_models.py b/tests/test_openai_models.py index e60b958bc0..e7e073e492 100644 --- a/tests/test_openai_models.py +++ b/tests/test_openai_models.py @@ -73,15 +73,6 @@ def test_file_content_part(self): assert part.file.filename == "sample.pdf" assert part.file.file_data.endswith("ZA==") - def test_video_url_content_part(self): - part = ContentPart( - type="video_url", - video_url={"url": "data:video/mp4;base64,AAAA", "fps": 3}, - ) - - assert part.video_url.url.startswith("data:video/mp4") - assert part.video_url.fps == 3 - class TestMessage: """Tests for Message model.""" diff --git a/tests/test_oq.py b/tests/test_oq.py index a759cdc598..cd780f0875 100644 --- a/tests/test_oq.py +++ b/tests/test_oq.py @@ -1211,6 +1211,119 @@ def test_get_predicate_bits_8bit(self): assert gs == 64 assert mode == "affine" + @pytest.mark.parametrize("oq_level, expected_bits", [(4, 4), (6, 6), (8, 8)]) + @pytest.mark.parametrize( + "path", + [ + "model.language_model.layers.1.ple.ple_embedding." + "ngram_embedding.shard_0.weight", + "model.language_model.layers.1.ple.ple_embedding." + "ngram_embedding.shards.0.weight", + ], + ) + def test_qwen4_ngram_uses_base_bits_and_group32( + self, oq_level, expected_bits, path + ): + config = { + "model_type": "qwen4_exp", + "text_config": {"model_type": "qwen4_exp_text"}, + "_oq_boost_map": { + path.removesuffix(".weight"): { + "bits": 8, + "group_size": 64, + "mode": "affine", + } + }, + } + + bits, gs, mode = _get_predicate_bits(path, config, oq_level, 64) + + assert (bits, gs, mode) == (expected_bits, 32, "affine") + + def test_non_qwen4_ngram_keeps_default_group_size(self): + path = ( + "model.layers.1.ple.ple_embedding.ngram_embedding." + "shards.0.weight" + ) + + bits, gs, mode = _get_predicate_bits( + path, {"model_type": "other"}, 4, 64 + ) + + assert (bits, gs, mode) == (4, 64, "affine") + + def test_qwen4_ngram_is_exempt_from_strict_imatrix_lookup(self): + from omlx.oq import OQImatrixData, _lookup_imatrix_importance + + path = ( + "model.language_model.layers.1.ple.ple_embedding." + "ngram_embedding.shards.0.weight" + ) + imatrix = OQImatrixData(entries={}, metadata={}, path="unused.npz") + report = {"missing": [], "mismatched": [], "applied": []} + + importance = _lookup_imatrix_importance( + imatrix, + path, + (156_250, 160), + config={"model_type": "qwen4_exp"}, + strict=True, + report=report, + ) + + assert importance is None + assert report["missing"] == [] + + def test_qwen4_ngram_group32_is_priced_into_budget_plan(self): + from omlx.oq import _structural_quant_overrides + + ple = ( + "language_model.model.layers.1.ple.ple_embedding." + "ngram_embedding.shards.0" + ) + named_shapes = { + ple: (2_800, 160), + "language_model.model.layers.0.mlp.switch_mlp.gate_proj": ( + 100, + 64, + 256, + ), + "language_model.lm_head": (16, 256), + } + config = { + "model_type": "qwen4_exp", + "text_config": {"model_type": "qwen4_exp_text"}, + "_oq_use_budget_plan": True, + "_oq_sensitivity_map": {"0": 1.0, "1": 0.5}, + } + + unpriced = _build_quant_plan( + named_shapes, + config, + 4, + target_bpw=4.6, + hard_cap_bpw=4.7, + ) + fixed = _structural_quant_overrides(named_shapes, config, 4) + plan = _build_quant_plan( + named_shapes, + config, + 4, + target_bpw=4.6, + hard_cap_bpw=4.7, + fixed_overrides=fixed, + ) + + assert unpriced.effective_bpw > 5.5 + assert fixed[ple] == { + "bits": 4, + "group_size": 32, + "mode": "affine", + } + assert plan.effective_bpw <= 4.7 + assert ple not in plan.boost_map + assert plan.boost_map["language_model.lm_head"]["bits"] == 8 + def test_build_quant_plan_respects_hard_cap(self): named_shapes = { "lm_head": (4096, 4096), @@ -3137,6 +3250,55 @@ def test_streaming_proxy_writes_loadable_quantized_config(self, tmp_path): assert config["quantization"]["group_size"] == _PROXY_QUANT_GROUP_SIZE assert (out / "model.safetensors").exists() + @pytest.mark.skipif(not HAS_MLX, reason="MLX not available") + def test_qwen4_streaming_proxy_records_group32_for_ngram_table(self, tmp_path): + """The BF16-source calibration proxy must match Qwen4 PLE layout.""" + from safetensors.numpy import save_file as np_save + + src = tmp_path / "src" + out = tmp_path / "proxy" + src.mkdir() + (src / "config.json").write_text( + json.dumps( + { + "model_type": "qwen4_exp", + "text_config": {"model_type": "qwen4_exp_text"}, + } + ), + encoding="utf-8", + ) + prefix = "model.language_model.layers.1.ple" + table = f"{prefix}.ple_embedding.ngram_embedding.shard_0" + np_save( + { + f"{table}.weight": np.ones((2, 160), dtype=np.float16), + f"{prefix}.key_proj.weight": np.ones( + (32, 256), dtype=np.float16 + ), + f"{prefix}.value_proj.weight": np.ones( + (32, 256), dtype=np.float16 + ), + }, + str(src / "model.safetensors"), + ) + + with ( + patch("omlx.oq._build_model_sanitizer", return_value=None), + patch("omlx.oq._build_non_quantizable_set", return_value=set()), + ): + _build_streaming_proxy_for_sensitivity(str(src), out, dtype="bfloat16") + + config = json.loads((out / "config.json").read_text(encoding="utf-8")) + quantization = config["quantization"] + assert quantization["group_size"] == _PROXY_QUANT_GROUP_SIZE + assert quantization[table] == { + "bits": _PROXY_QUANT_BITS, + "group_size": 32, + "mode": "affine", + } + assert f"{prefix}.key_proj" not in quantization + assert f"{prefix}.value_proj" not in quantization + class TestSensitivityRequiredEnforcement: """Regression tests: quantize_oq_streaming must abort when sensitivity @@ -3357,6 +3519,134 @@ def _fake_imatrix(*_args, load_path_factory=None, **_kwargs): @pytest.mark.skipif(not HAS_MLX, reason="MLX not available") class TestOnTheFlyFp8Dequant: + def test_qwen4_ple_bf16_shard_stays_on_standard_float_path(self, tmp_path): + dense = mx.array( + [ + [1.0, -0.5, 0.25, 2.0] * 8, + [-1.0, 0.5, -0.25, -2.0] * 8, + ], + dtype=mx.bfloat16, + ) + key = ( + "model.language_model.layers.1.ple.ple_embedding." + "ngram_embedding.shard_0.weight" + ) + path = str(tmp_path / "qwen4_ple_bf16.safetensors") + _write_safetensors( + path, + { + key: ( + np.asarray(dense.view(mx.uint16)).tobytes(), + list(dense.shape), + "BF16", + ), + }, + ) + config = { + "model_type": "qwen4_exp", + "text_config": { + "model_type": "qwen4_exp_text", + "ple_layer_ids": [2], + "split_ngram_parts": 1, + }, + } + + idx = _LazyTensorIndex([path], config=config) + + assert idx.source_dtype(key) == "BF16" + assert idx.logical_metadata()[key] == (tuple(dense.shape), "BF16") + assert key not in idx._virtual + loaded = idx.pop(key) + mx.eval(loaded, dense) + assert loaded.dtype == mx.bfloat16 + assert mx.array_equal(loaded, dense).item() + + from omlx.oq import _quantize_chunked + + weight, scales, biases = _quantize_chunked( + loaded, group_size=32, bits=4, mode="affine" + ) + mx.eval(weight, scales, biases) + assert weight.dtype == mx.uint32 + assert weight.shape == (2, 4) + assert scales.shape == biases.shape == (2, 1) + + def test_qwen4_ple_fp8_shard_is_decoded_before_affine_quantization(self, tmp_path): + dense = mx.array( + [ + [1.0, -0.5, 0.25, 2.0] * 8, + [-1.0, 0.5, -0.25, -2.0] * 8, + ], + dtype=mx.bfloat16, + ) + fp8 = mx.to_fp8(dense) + key = ( + "model.language_model.layers.1.ple.ple_embedding." + "ngram_embedding.shard_0.weight" + ) + scale_key = ( + "model.language_model.layers.1.ple.ple_embedding." + "ngram_embedding.weight_scale" + ) + path = str(tmp_path / "qwen4_ple.safetensors") + _write_safetensors( + path, + { + key: ( + np.asarray(fp8).tobytes(), + list(fp8.shape), + "F8_E4M3", + ), + scale_key: np.array([0.125], dtype=np.float16), + }, + ) + config = { + "model_type": "qwen4_exp", + "text_config": { + "model_type": "qwen4_exp_text", + "ple_layer_ids": [2], + "split_ngram_parts": 1, + }, + } + + idx = _LazyTensorIndex([path], config=config) + + assert idx.source_dtype(key) == "F8_E4M3" + assert idx.logical_metadata()[key] == (tuple(fp8.shape), "BF16") + assert scale_key in idx + decoded = idx.pop(key) + expected = mx.from_fp8(fp8, dtype=mx.bfloat16) + mx.eval(decoded, expected) + assert decoded.dtype == mx.bfloat16 + assert mx.array_equal(decoded, expected).item() + + from omlx.oq import _quantize_chunked + + weight, scales, biases = _quantize_chunked( + decoded, group_size=32, bits=4, mode="affine" + ) + mx.eval(weight, scales, biases) + assert weight.dtype == mx.uint32 + assert weight.shape == (2, 4) + assert scales.shape == biases.shape == (2, 1) + + def test_qwen4_ple_virtual_decode_does_not_claim_other_models(self, tmp_path): + raw = np.arange(64, dtype=np.uint8).reshape(2, 32) + key = ( + "model.language_model.layers.1.ple.ple_embedding." + "ngram_embedding.shard_0.weight" + ) + path = str(tmp_path / "other_ple.safetensors") + _write_safetensors( + path, + {key: (raw.tobytes(), list(raw.shape), "F8_E4M3")}, + ) + + idx = _LazyTensorIndex([path], config={"model_type": "other"}) + + assert idx.logical_metadata()[key] == (tuple(raw.shape), "F8_E4M3") + assert idx[key].dtype == mx.uint8 + def test_vllm_scale_inv_convention(self, tmp_path): """vLLM convention: weight (F8_E4M3) + weight_scale_inv (F32).""" w = np.random.randint(0, 255, (128, 128), dtype=np.uint8) @@ -6146,6 +6436,63 @@ def sanitize_fn(weights): np.testing.assert_array_equal(scale, np.ones(n_experts, dtype=np.float32)) +@pytest.mark.skipif(not HAS_MLX, reason="MLX not available") +class TestQwen4ExpLayerWalk: + def test_trunk_and_mtp_imatrix_hooks_execute(self, tmp_path): + from tests.test_mlx_vlm_qwen4_exp_compat import _tiny_config + + config = _tiny_config() + from mlx_vlm.models.qwen4_exp.language import configure_mtp_runtime + from mlx_vlm.models.qwen4_exp.qwen4_exp import Model + from omlx.oq import _collect_mtp_head_imatrix + + (tmp_path / "model.safetensors.index.json").write_text( + json.dumps({"weight_map": {"mtp.fc_hidden.weight": "model.safetensors"}}), + encoding="utf-8", + ) + configure_mtp_runtime(tmp_path, enabled=True) + try: + model = Model(config) + tokens = mx.array([[1, 2, 3, 4, 5, 6]], dtype=mx.int32) + layers = model.language_model.model.layers + inputs = model.language_model.model.embed_tokens(tokens) + inputs, masks, state = _prepare_layer_inputs( + model, layers, tokens, inputs + ) + + assert inputs.shape == (1, 6, 64) + assert state["kind"] == "qwen4_exp" + assert masks[0] is None + assert masks[1] is not None + + collector = OQImatrixCollector() + assert collector.install(model) > 0 + try: + for layer_idx, layer in enumerate(layers): + inputs, _ = _forward_layer_result( + layer, + inputs, + masks[layer_idx], + state, + layer_idx=layer_idx, + ) + mx.eval(inputs) + assert _collect_mtp_head_imatrix(model, tokens, inputs) + assert any( + name.startswith("language_model.model.layers.") + for name in collector.entries + ) + assert "mtp.fc_embedding" in collector.entries + assert any( + name.startswith("mtp.layers.0.mlp.switch_mlp.") + for name in collector.entries + ) + finally: + collector.restore(model) + finally: + configure_mtp_runtime(tmp_path, enabled=False) + + @pytest.mark.skipif(not HAS_MLX, reason="MLX not available") class TestInklingLayerWalk: """Calibration layer-walk wiring for inkling.""" diff --git a/tests/test_qwen4_exp_residency.py b/tests/test_qwen4_exp_residency.py new file mode 100644 index 0000000000..327e2c92d3 --- /dev/null +++ b/tests/test_qwen4_exp_residency.py @@ -0,0 +1,68 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Tests for Qwen4-Exp PLE resident/mmap size accounting.""" + +import json +import struct + +from omlx.patches.mlx_vlm_qwen4_exp_compat.residency import ( + qwen4_exp_residency_estimate, +) + + +def _write_safetensors(path, tensors: dict[str, int]) -> None: + offset = 0 + header = {} + for key, size in tensors.items(): + header[key] = { + "dtype": "U8", + "shape": [size], + "data_offsets": [offset, offset + size], + } + offset += size + encoded = json.dumps(header).encode() + path.write_bytes(struct.pack(" Date: Thu, 27 Aug 2026 20:39:17 +0900 Subject: [PATCH 008/132] fix: normalize Qwen4 RMSNorm checkpoint dialects (#3181) --- .../mlx_vlm/models/qwen4_exp/qwen4_exp.py | 100 +++++++++++ tests/test_mlx_vlm_qwen4_exp_compat.py | 155 ++++++++++++++++++ 2 files changed, 255 insertions(+) diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/qwen4_exp.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/qwen4_exp.py index 4f38e5baf9..3f73d80715 100644 --- a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/qwen4_exp.py +++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/qwen4_exp.py @@ -1,3 +1,4 @@ +import logging import re import mlx.core as mx @@ -11,11 +12,14 @@ from .language import ( LanguageModel, Qwen4ExpMTPModule, + Qwen4ExpRMSNorm, get_mtp_runtime, get_ple_runtime_mode, ) from .vision import VisionModel +logger = logging.getLogger(__name__) + _NGRAM_SHARD_RE = re.compile(r"\.ngram_embedding\.shard_(\d+)(?=\.)") _NGRAM_STORAGE_RE = re.compile( r"\.ple\.ple_embedding\.ngram_embedding\." @@ -27,6 +31,101 @@ "model.mtp.", "mtp.", ) +_RMSNORM_CENTER_ANCHOR_RE = re.compile( + r"^language_model\.model\.layers\.\d+" + r"\.attn_hyper_connection\.hc_norm\.weight$" +) +_RMSNORM_CENTER_MIN_ANCHORS = 8 +_RMSNORM_ONES_CENTERED_VOTE = 0.9 +_RMSNORM_ONES_CENTERED_MEDIAN_MIN = 0.75 +_RMSNORM_ONES_CENTERED_MEDIAN_MAX = 1.5 +_RMSNORM_ZERO_CENTERED_VOTE = 0.1 +_RMSNORM_ZERO_CENTERED_MEDIAN_MIN = -0.5 +_RMSNORM_ZERO_CENTERED_MEDIAN_MAX = 0.25 + + +def _normalize_ones_centered_rmsnorm_weights(model, weights): + """Canonicalize legacy direct-gamma Qwen4 RMSNorm checkpoints. + + Qwen4 stores most RMSNorm parameters as a residual around zero and applies + ``1 + weight`` at runtime. Some early community MLX conversions instead + stored the direct gamma around one. Use the stable per-layer attention + hyper-connection norms to identify that checkpoint-wide conversion, then + recenter only modules backed by :class:`Qwen4ExpRMSNorm`. + + The MTP head is normalized using the base-model decision. Its trained norm + means are not independently centered near zero, so sampling the MTP head + alone would be ambiguous. + """ + named_modules = getattr(model, "named_modules", None) + if named_modules is None: + return + + anchors = [ + value + for key, value in weights.items() + if _RMSNORM_CENTER_ANCHOR_RE.fullmatch(key) + and isinstance(value, mx.array) + and mx.issubdtype(value.dtype, mx.floating) + ] + if len(anchors) < _RMSNORM_CENTER_MIN_ANCHORS: + return + + means = mx.stack([mx.mean(value.astype(mx.float32)) for value in anchors]) + median = mx.median(means) + ones_vote = mx.mean((means > 0.5).astype(mx.float32)) + mx.eval(median, ones_vote) + median_value = float(median.item()) + ones_vote_value = float(ones_vote.item()) + + ones_centered = ( + ones_vote_value >= _RMSNORM_ONES_CENTERED_VOTE + and _RMSNORM_ONES_CENTERED_MEDIAN_MIN + <= median_value + <= _RMSNORM_ONES_CENTERED_MEDIAN_MAX + ) + zero_centered = ( + ones_vote_value <= _RMSNORM_ZERO_CENTERED_VOTE + and _RMSNORM_ZERO_CENTERED_MEDIAN_MIN + <= median_value + <= _RMSNORM_ZERO_CENTERED_MEDIAN_MAX + ) + if not ones_centered: + if not zero_centered: + logger.warning( + "Qwen4-Exp RMSNorm checkpoint centering is ambiguous " + "(%d anchors, median %.4f, ones-centered vote %.1f%%); " + "leaving weights unchanged", + len(anchors), + median_value, + ones_vote_value * 100.0, + ) + return + + target_keys = { + f"{path}.weight" + for path, module in named_modules() + if isinstance(module, Qwen4ExpRMSNorm) + } + normalized = 0 + for key in target_keys: + value = weights.get(key) + if not isinstance(value, mx.array) or not mx.issubdtype( + value.dtype, mx.floating + ): + continue + # Keep the residual in FP32. Subtracting in BF16 can lose information + # for direct gamma values below 0.5, which occur in the trained MTP head. + weights[key] = value.astype(mx.float32) - 1.0 + normalized += 1 + + logger.info( + "Canonicalized %d ones-centered Qwen4-Exp RMSNorm tensors " + "(%d anchors, median %.4f)", + normalized, + len(anchors), + median_value, + ) class Model(Qwen3_5Model): @@ -153,6 +252,7 @@ def stack_experts(prefix): if "conv1d.weight" in key and value.shape[-1] != 1: value = value.moveaxis(2, 1) sanitized[key] = value + _normalize_ones_centered_rmsnorm_weights(self, sanitized) return sanitized def close(self): diff --git a/tests/test_mlx_vlm_qwen4_exp_compat.py b/tests/test_mlx_vlm_qwen4_exp_compat.py index 0ae4b54473..9141cebeb9 100644 --- a/tests/test_mlx_vlm_qwen4_exp_compat.py +++ b/tests/test_mlx_vlm_qwen4_exp_compat.py @@ -121,6 +121,161 @@ def test_qwen4_exp_sanitize_keeps_converted_norm_values(): assert mx.array_equal(result["language_model.model.norm.weight"], norm).item() +def _qwen4_rmsnorm_sanitize_fixture(*, include_mtp=False): + from mlx_vlm.models.qwen4_exp.language import ( + Qwen4ExpRMSNorm, + Qwen4ExpRMSNormGated, + ) + + modules = [] + weights = {} + target_keys = set() + anchor_residuals = ( + -0.30, + -0.20, + -0.10, + -0.05, + 0.00, + 0.05, + 0.10, + 0.15, + 0.20, + 0.25, + 0.30, + 0.75, + ) + for layer_idx, residual in enumerate(anchor_residuals): + path = ( + f"language_model.model.layers.{layer_idx}." + "attn_hyper_connection.hc_norm" + ) + modules.append((path, Qwen4ExpRMSNorm(4))) + key = f"{path}.weight" + weights[key] = mx.full((4,), residual, dtype=mx.bfloat16) + target_keys.add(key) + + path = "language_model.model.hyper_connection_mixer.hc_norm" + modules.append((path, Qwen4ExpRMSNorm(4))) + weights[f"{path}.weight"] = mx.array([-0.25, 0.0, 0.25, 0.5], dtype=mx.bfloat16) + target_keys.add(f"{path}.weight") + + gated_path = "language_model.model.layers.0.linear_attn.norm" + modules.append((gated_path, Qwen4ExpRMSNormGated(4, eps=1e-6, activation="silu"))) + weights[f"{gated_path}.weight"] = mx.array( + [0.95, 1.0, 1.05, 1.1], dtype=mx.bfloat16 + ) + + if include_mtp: + for path, values in ( + ( + "mtp.hyper_connection_mixer.hc_norm", + [3.75, 3.875, 4.0, 4.125], + ), + ( + "mtp.pre_fc_norm_embedding", + [-0.8, -0.75, -0.7, -0.65], + ), + ): + modules.append((path, Qwen4ExpRMSNorm(4))) + weights[f"{path}.weight"] = mx.array(values, dtype=mx.bfloat16) + target_keys.add(f"{path}.weight") + + model = SimpleNamespace( + config=SimpleNamespace( + text_config=SimpleNamespace( + tie_word_embeddings=False, + num_hidden_layers=0, + num_experts=0, + ple_layer_ids=(), + ) + ), + named_modules=lambda: iter(modules), + ) + return model, modules, weights, target_keys + + +def test_qwen4_exp_sanitize_keeps_zero_centered_rmsnorms(): + from mlx_vlm.models.qwen4_exp.qwen4_exp import Model + + model, _, weights, target_keys = _qwen4_rmsnorm_sanitize_fixture() + result = Model.sanitize(model, dict(weights)) + + for key in target_keys: + assert mx.array_equal(result[key], weights[key]).item() + assert result[key].dtype == mx.bfloat16 + + +def test_qwen4_exp_sanitize_recenters_ones_centered_base_and_mtp(tmp_path, caplog): + from mlx_vlm.models.qwen4_exp.language import configure_mtp_runtime + from mlx_vlm.models.qwen4_exp.qwen4_exp import Model + + (tmp_path / "model.safetensors.index.json").write_text( + json.dumps({"weight_map": {"mtp.fc_hidden.weight": "model.safetensors"}}), + encoding="utf-8", + ) + configure_mtp_runtime(tmp_path, enabled=True) + try: + model, modules, canonical, target_keys = _qwen4_rmsnorm_sanitize_fixture( + include_mtp=True + ) + shifted = { + key: ( + value + mx.array(1.0, dtype=value.dtype) + if key in target_keys + else value + ) + for key, value in canonical.items() + } + + with caplog.at_level("INFO"): + result = Model.sanitize(model, dict(shifted)) + + for key in target_keys: + assert result[key].dtype == mx.float32 + assert mx.array_equal( + 1.0 + result[key], shifted[key].astype(mx.float32) + ).item() + + gated_key = "language_model.model.layers.0.linear_attn.norm.weight" + assert mx.array_equal(result[gated_key], shifted[gated_key]).item() + assert "Canonicalized 15 ones-centered" in caplog.text + + mtp_norm = dict(modules)["mtp.pre_fc_norm_embedding"] + mtp_norm.weight = result["mtp.pre_fc_norm_embedding.weight"] + x = mx.array([[1.0, -2.0, 3.0, -4.0]], dtype=mx.float32) + actual = mtp_norm(x) + rms = x * mx.rsqrt(mx.mean(x * x, axis=-1, keepdims=True) + 1e-6) + expected = rms * shifted["mtp.pre_fc_norm_embedding.weight"].astype(mx.float32) + assert mx.array_equal(actual, expected).item() + + second = Model.sanitize(model, dict(result)) + for key in target_keys: + assert mx.array_equal(second[key], result[key]).item() + finally: + configure_mtp_runtime(tmp_path, enabled=False) + + +def test_qwen4_exp_sanitize_leaves_ambiguous_rmsnorms_unchanged(caplog): + from mlx_vlm.models.qwen4_exp.qwen4_exp import Model + + model, _, weights, target_keys = _qwen4_rmsnorm_sanitize_fixture() + for index, key in enumerate( + sorted(key for key in target_keys if ".layers." in key) + ): + weights[key] = mx.full( + weights[key].shape, + 0.0 if index < 6 else 1.0, + dtype=mx.bfloat16, + ) + + with caplog.at_level("WARNING"): + result = Model.sanitize(model, dict(weights)) + + for key in target_keys: + assert mx.array_equal(result[key], weights[key]).item() + assert "RMSNorm checkpoint centering is ambiguous" in caplog.text + + def test_qwen4_exp_sanitize_keeps_converted_ple_shared_scale(): compat.apply_mlx_vlm_qwen4_exp_compat_patch() from mlx_vlm.models.qwen4_exp.qwen4_exp import Model From 4fc1d0916ed09c29e7696b00b42de9f78e3d9af4 Mon Sep 17 00:00:00 2001 From: scubamount <59990200+scubamount@users.noreply.github.com> Date: Thu, 27 Aug 2026 05:00:26 -0700 Subject: [PATCH 009/132] fix(load): chunk materialize_lazy_state eval to avoid Metal GPU watchdog (#3180) Fixes #3179. --- omlx/utils/model_loading.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/omlx/utils/model_loading.py b/omlx/utils/model_loading.py index ee8d2b1d38..4a29873588 100644 --- a/omlx/utils/model_loading.py +++ b/omlx/utils/model_loading.py @@ -1137,7 +1137,17 @@ def _scan_plain_object(obj: Any) -> None: _scan_plain_object(value) if arrays: - mx.eval(arrays) + # Evaluate in bounded chunks rather than one mx.eval(arrays). A single + # eval over the whole parameter tree submits one Metal command buffer + # spanning every array; on a multi-hundred-GB checkpoint (e.g. the raw + # BF16 Qwen3.8-Flash-Next base, ~336 GB / 1676 arrays) that buffer + # exceeds the GPU command-buffer watchdog and aborts the process with + # "[METAL] Command buffer execution failed: Caused GPU Timeout Error + # (kIOGPUCommandBufferCallbackErrorTimeout)". Chunking bounds each + # command buffer; small models see only a handful of chunks. See #3179. + _MATERIALIZE_EVAL_CHUNK = 8 + for start in range(0, len(arrays), _MATERIALIZE_EVAL_CHUNK): + mx.eval(arrays[start : start + _MATERIALIZE_EVAL_CHUNK]) def apply_post_load_transforms(model: Any, model_settings: Any = None) -> Any: From dece501e626a3d7db8f2bdd837e8c141c2d35fc9 Mon Sep 17 00:00:00 2001 From: jundot Date: Thu, 27 Aug 2026 21:18:56 +0900 Subject: [PATCH 010/132] fix: defer VLM parameter eval to chunked materialization (#3179) --- omlx/engine/vlm.py | 1 + omlx/utils/model_loading.py | 3 ++- tests/test_model_loading.py | 20 ++++++++++++++++++ tests/test_vlm_qwen4_exp_loader.py | 34 ++++++++++++++++++++++++++++++ 4 files changed, 57 insertions(+), 1 deletion(-) diff --git a/omlx/engine/vlm.py b/omlx/engine/vlm.py index 73558a419e..967ef63b30 100644 --- a/omlx/engine/vlm.py +++ b/omlx/engine/vlm.py @@ -1653,6 +1653,7 @@ def _load_vlm_sync(): ): loaded = vlm_load( self._model_name, + lazy=True, trust_remote_code=self._trust_remote_code, ) return loaded diff --git a/omlx/utils/model_loading.py b/omlx/utils/model_loading.py index 4a29873588..677c7bf41d 100644 --- a/omlx/utils/model_loading.py +++ b/omlx/utils/model_loading.py @@ -20,6 +20,8 @@ _CKPT_TEXT_PREFIX = "model.language_model." _RUNTIME_TEXT_PREFIX = "language_model.model." +_MATERIALIZE_EVAL_CHUNK = 8 + _MLX_LM_LOAD_CONFIG_PATCHED = False _REMOTE_CODE_METADATA_PATTERNS = [ @@ -1145,7 +1147,6 @@ def _scan_plain_object(obj: Any) -> None: # "[METAL] Command buffer execution failed: Caused GPU Timeout Error # (kIOGPUCommandBufferCallbackErrorTimeout)". Chunking bounds each # command buffer; small models see only a handful of chunks. See #3179. - _MATERIALIZE_EVAL_CHUNK = 8 for start in range(0, len(arrays), _MATERIALIZE_EVAL_CHUNK): mx.eval(arrays[start : start + _MATERIALIZE_EVAL_CHUNK]) diff --git a/tests/test_model_loading.py b/tests/test_model_loading.py index a85742d8aa..2cc837e8aa 100644 --- a/tests/test_model_loading.py +++ b/tests/test_model_loading.py @@ -801,6 +801,26 @@ def test_minimax_overrides_follow_the_mlx_lm_adapter_root(self): class TestMaterializeLazyState: + def test_evaluates_arrays_in_bounded_chunks(self, monkeypatch): + import mlx.core as mx + import mlx.nn as nn + + class _Model(nn.Module): + def __init__(self): + super().__init__() + self.tensor_list = [mx.array(i) * 2 for i in range(17)] + + chunk_sizes = [] + monkeypatch.setattr( + model_loading.mx, + "eval", + lambda arrays: chunk_sizes.append(len(arrays)), + ) + + model_loading.materialize_lazy_state(_Model()) + + assert chunk_sizes == [8, 8, 1] + def test_covers_arrays_in_plain_helper_objects(self): """Lazy arrays hidden in non-Module helpers must be materialized. diff --git a/tests/test_vlm_qwen4_exp_loader.py b/tests/test_vlm_qwen4_exp_loader.py index f861d148e9..c74a2f886f 100644 --- a/tests/test_vlm_qwen4_exp_loader.py +++ b/tests/test_vlm_qwen4_exp_loader.py @@ -59,6 +59,40 @@ def metadata(self): assert safetensors.safe_open is original +@pytest.mark.asyncio +async def test_qwen4_exp_loader_defers_parameter_eval_to_materialize( + tmp_path, monkeypatch +): + import mlx_vlm.utils as vlm_utils + + from omlx.utils import model_loading + + (tmp_path / "config.json").write_text( + json.dumps({"model_type": "qwen4_exp"}), encoding="utf-8" + ) + captured = {} + + def stop_after_load(model_name, **kwargs): + captured.update(kwargs) + raise RuntimeError("stop after load") + + monkeypatch.setattr(vlm_utils, "load", stop_after_load) + monkeypatch.setattr(vlm_module, "_patch_video_processor_bug", lambda: None) + monkeypatch.setattr(vlm_module, "_patch_torch_free_image_processor", lambda: None) + monkeypatch.setattr(vlm_module, "apply_pixtral_torch_free_patch", lambda: None) + monkeypatch.setattr( + model_loading, "maybe_apply_pre_load_patches", lambda *a, **k: None + ) + monkeypatch.setattr( + model_loading, "maybe_load_custom_quantization", lambda *a, **k: None + ) + + with pytest.raises(RuntimeError, match="stop after load"): + await VLMBatchedEngine(model_name=str(tmp_path)).start() + + assert captured["lazy"] is True + + def test_qwen4_exp_loader_enables_adaptive_depth_three_lightning_mtp(tmp_path): (tmp_path / "config.json").write_text( json.dumps( From 05145000c52e3ce1eaa1f4794b4ef760f72e58b9 Mon Sep 17 00:00:00 2001 From: jundot Date: Thu, 27 Aug 2026 21:33:39 +0900 Subject: [PATCH 011/132] fix: limit lazy VLM loading to qwen4_exp (#3179) --- omlx/engine/vlm.py | 11 ++++++++--- tests/test_vlm_qwen4_exp_loader.py | 15 +++++++++++---- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/omlx/engine/vlm.py b/omlx/engine/vlm.py index 967ef63b30..f04f14da9f 100644 --- a/omlx/engine/vlm.py +++ b/omlx/engine/vlm.py @@ -1643,7 +1643,8 @@ def _load_vlm_sync(): model, processor = custom_loaded return model, processor - if _read_config_model_type(self._model_name) == COHERE2_MOE_MODEL_TYPE: + model_type = _read_config_model_type(self._model_name) + if model_type == COHERE2_MOE_MODEL_TYPE: return _load_cohere2_moe_text_model( self._model_name, trust_remote_code=self._trust_remote_code, @@ -1651,10 +1652,14 @@ def _load_vlm_sync(): with _load_optiq_vision_sidecar_on_load( Path(self._model_name) ): + load_kwargs = { + "trust_remote_code": self._trust_remote_code, + } + if model_type == QWEN4_EXP_MODEL_TYPE: + load_kwargs["lazy"] = True loaded = vlm_load( self._model_name, - lazy=True, - trust_remote_code=self._trust_remote_code, + **load_kwargs, ) return loaded diff --git a/tests/test_vlm_qwen4_exp_loader.py b/tests/test_vlm_qwen4_exp_loader.py index c74a2f886f..4742439c8f 100644 --- a/tests/test_vlm_qwen4_exp_loader.py +++ b/tests/test_vlm_qwen4_exp_loader.py @@ -60,15 +60,19 @@ def metadata(self): @pytest.mark.asyncio -async def test_qwen4_exp_loader_defers_parameter_eval_to_materialize( - tmp_path, monkeypatch +@pytest.mark.parametrize( + ("model_type", "expected_lazy"), + [("qwen4_exp", True), ("qwen2_vl", None)], +) +async def test_only_qwen4_exp_loader_defers_parameter_eval_to_materialize( + tmp_path, monkeypatch, model_type, expected_lazy ): import mlx_vlm.utils as vlm_utils from omlx.utils import model_loading (tmp_path / "config.json").write_text( - json.dumps({"model_type": "qwen4_exp"}), encoding="utf-8" + json.dumps({"model_type": model_type}), encoding="utf-8" ) captured = {} @@ -90,7 +94,10 @@ def stop_after_load(model_name, **kwargs): with pytest.raises(RuntimeError, match="stop after load"): await VLMBatchedEngine(model_name=str(tmp_path)).start() - assert captured["lazy"] is True + if expected_lazy is None: + assert "lazy" not in captured + else: + assert captured["lazy"] is expected_lazy def test_qwen4_exp_loader_enables_adaptive_depth_three_lightning_mtp(tmp_path): From 18b97d15b4b8c6a1ac04e268ac2c078df92b208d Mon Sep 17 00:00:00 2001 From: Jun Kim <64250138+jundot@users.noreply.github.com> Date: Thu, 27 Aug 2026 22:00:24 +0900 Subject: [PATCH 012/132] fix(admin): retry failed Xet downloads over HTTP (#3158) (#3186) Co-authored-by: jundot --- omlx/_hf_download_worker.py | 70 ++++++++ omlx/admin/hf_downloader.py | 323 ++++++++++++++++++++++++++++------ tests/test_hf_downloader.py | 342 ++++++++++++++++++++++++++---------- 3 files changed, 590 insertions(+), 145 deletions(-) create mode 100644 omlx/_hf_download_worker.py diff --git a/omlx/_hf_download_worker.py b/omlx/_hf_download_worker.py new file mode 100644 index 0000000000..8beeb7027c --- /dev/null +++ b/omlx/_hf_download_worker.py @@ -0,0 +1,70 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Isolated Hugging Face HTTP download worker. + +The parent sends one JSON request over stdin. Keeping the token off argv and +setting ``HF_HUB_DISABLE_XET`` before importing huggingface_hub isolates the +fallback transport choice from the long-running oMLX server process. +""" + +from __future__ import annotations + +import json +import os +import sys +from collections.abc import Callable +from typing import Any + +_ALLOWED_DOWNLOAD_KWARGS = { + "endpoint", + "etag_timeout", + "ignore_patterns", + "local_dir", + "repo_id", + "token", +} + + +def _download_without_xet( + kwargs: dict[str, Any], + download_fn: Callable[..., Any] | None = None, +) -> None: + """Run snapshot_download after disabling xet before its first import.""" + os.environ["HF_HUB_DISABLE_XET"] = "1" + if download_fn is None: + from huggingface_hub import snapshot_download + + download_fn = snapshot_download + download_fn(**kwargs) + + +def _read_request() -> dict[str, Any]: + request = json.load(sys.stdin) + if not isinstance(request, dict) or not isinstance(request.get("kwargs"), dict): + raise ValueError("Invalid download worker request") + kwargs = request["kwargs"] + unknown = set(kwargs) - _ALLOWED_DOWNLOAD_KWARGS + if unknown: + names = ", ".join(sorted(unknown)) + raise ValueError(f"Unsupported download arguments: {names}") + return kwargs + + +def main() -> int: + try: + kwargs = _read_request() + _download_without_xet(kwargs) + except Exception as error: # noqa: BLE001 - report child failure to parent + response = { + "ok": False, + "error_type": type(error).__name__, + "message": str(error), + } + print(json.dumps(response), flush=True) + return 1 + + print(json.dumps({"ok": True}), flush=True) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/omlx/admin/hf_downloader.py b/omlx/admin/hf_downloader.py index b14ddb69e6..d426af5c8b 100644 --- a/omlx/admin/hf_downloader.py +++ b/omlx/admin/hf_downloader.py @@ -1,24 +1,29 @@ # SPDX-License-Identifier: Apache-2.0 """HuggingFace model downloader for oMLX admin panel. -Downloads models from HuggingFace Hub using huggingface_hub's snapshot_download -with directory-size-based progress polling. +Downloads models with huggingface_hub's snapshot_download, filesystem-based +progress polling, and an isolated HTTP retry for xet transport failures. """ import asyncio import enum +import errno +import json import logging +import os import shutil +import signal +import sys import time import uuid +from collections.abc import Callable from dataclasses import dataclass, field from pathlib import Path -from typing import Callable, Optional +from typing import Optional from urllib.parse import urlparse from huggingface_hub import HfApi, hf_hub_download, snapshot_download from huggingface_hub.utils import ( - EntryNotFoundError, GatedRepoError, HfHubHTTPError, RepositoryNotFoundError, @@ -38,6 +43,26 @@ # Seconds with no download progress before considering the download stalled. _STALL_TIMEOUT = 300 +# A separate first-activity deadline catches xet token/CAS hangs that never +# create a payload file. Once any write is observed, the more tolerant stall +# timeout above applies so slow but active connections are left alone. +_STARTUP_STALL_TIMEOUT = 120 + +_PROGRESS_POLL_INTERVAL = 2 +_SUBPROCESS_TERMINATE_TIMEOUT = 5 + +_NON_XET_WORKER_MODULE = "omlx._hf_download_worker" + +_XET_ERROR_MARKERS = ( + "cas service error", + "cas client", + "hf_xet", + "reqwestmiddleware", + "xet-read-token", + "xet storage", + "/xet-", +) + # Cache of (configured_endpoint -> resolved_endpoint) so we only probe each # endpoint once per process lifetime. Mirrors like hf-mirror.com permanently # 308-redirect to huggingface.co when accessed from IPs outside their region; @@ -112,6 +137,56 @@ class _DownloadCancelled(Exception): """Raised inside the download thread to interrupt a cancelled download.""" +class _DownloadStalledError(RuntimeError): + """Raised when a monitored transfer stops making observable progress.""" + + def __init__(self, *, transport: str, phase: str, timeout: float): + self.transport = transport + self.phase = phase + self.timeout = timeout + if phase == "startup": + detail = "no initial download activity" + else: + detail = "no download progress" + super().__init__(f"{transport} download stalled: {detail} for {timeout:g}s") + + +class _NonXetDownloadError(RuntimeError): + """Raised when the isolated HTTP fallback process fails.""" + + +@dataclass(frozen=True) +class _DownloadActivity: + """Filesystem signals used to distinguish slow transfers from stalls.""" + + file_count: int = 0 + logical_size: int = 0 + allocated_size: int = 0 + latest_mtime_ns: int = 0 + + +def _is_xet_transport_error(error: BaseException) -> bool: + """Return whether an exception identifies the xet/CAS transport path.""" + if isinstance( + error, + ( + _DownloadCancelled, + _DownloadStalledError, + GatedRepoError, + RepositoryNotFoundError, + ), + ): + return False + if isinstance(error, OSError) and error.errno in { + errno.EACCES, + errno.ENOSPC, + errno.EROFS, + }: + return False + detail = f"{type(error).__name__}: {error}".lower() + return any(marker in detail for marker in _XET_ERROR_MARKERS) + + def _make_cancellable_tqdm(should_cancel: Callable[[], bool]) -> type: """Build a tqdm subclass that aborts the download when cancelled. @@ -607,6 +682,8 @@ def __init__( self._progress_tasks: dict[str, asyncio.Task] = {} self._on_complete = on_complete self._cancelled: set[str] = set() + self._stalled: dict[str, _DownloadStalledError] = {} + self._fallback_processes: dict[str, asyncio.subprocess.Process] = {} self._download_sem = asyncio.Semaphore(1) @property @@ -887,23 +964,59 @@ async def _run_download(self, task_id: str, hf_token: str) -> None: f"Dry run failed for {task.repo_id}: {e}. {detail}" ) - # Start progress polling self._progress_tasks[task_id] = asyncio.create_task( self._poll_progress(task_id, target_dir) ) - # Run snapshot_download in a thread (blocking call). Cancel - # reaches the thread two ways: the cancellable tqdm raises on - # the next chunk of the http_get path, and abort_xet_session() - # (called by cancel/stall/shutdown) unwinds the xet path with - # a RuntimeError (the thread itself can't be force-killed). - await asyncio.to_thread( - snapshot_download, - **dl_kwargs, - tqdm_class=_make_cancellable_tqdm( - lambda: task_id in self._cancelled - ), - ) + xet_error: Exception | None = None + try: + # Awaiting the thread here is intentional: after a stall, + # fallback cannot start until abort_xet_session() has made + # the original writer return. + await asyncio.to_thread( + snapshot_download, + **dl_kwargs, + tqdm_class=_make_cancellable_tqdm( + lambda: task_id in self._cancelled + ), + ) + except Exception as error: + stalled = self._stalled.pop(task_id, None) + if stalled is not None: + xet_error = stalled + elif _is_xet_transport_error(error): + xet_error = error + else: + raise + else: + xet_error = self._stalled.pop(task_id, None) + + if xet_error is not None: + if task_id in self._cancelled: + raise _DownloadCancelled() + logger.warning( + "Xet download failed for %s: %s. " + "Retrying once over HTTP.", + task.repo_id, + xet_error, + ) + progress_task = self._progress_tasks.pop(task_id, None) + if progress_task and not progress_task.done(): + progress_task.cancel() + self._progress_tasks[task_id] = asyncio.create_task( + self._poll_progress(task_id, target_dir) + ) + try: + await self._run_http_fallback(task_id, dl_kwargs) + except asyncio.CancelledError: + raise + except Exception as error: + fallback_error = self._stalled.pop(task_id, None) or error + raise _NonXetDownloadError( + "Xet download failed " + f"({xet_error}); HTTP fallback also failed " + f"({fallback_error})" + ) from error # Check if cancelled while downloading if task_id in self._cancelled: @@ -961,9 +1074,7 @@ async def _run_download(self, task_id: str, hf_token: str) -> None: ) logger.error(f"Gated repo access denied: {task.repo_id}") except Exception as e: - # Skip when already cancelled (the xet abort surfaces here as a - # RuntimeError) or already FAILED by the stall detector, whose - # error message would otherwise be clobbered by the abort error. + # Do not clobber an earlier terminal error or a user cancellation. if ( task_id not in self._cancelled and task.status != DownloadStatus.FAILED @@ -976,10 +1087,79 @@ async def _run_download(self, task_id: str, hf_token: str) -> None: progress_task = self._progress_tasks.pop(task_id, None) if progress_task and not progress_task.done(): progress_task.cancel() + self._stalled.pop(task_id, None) # Remove from active tasks self._active_tasks.pop(task_id, None) + async def _run_http_fallback( + self, + task_id: str, + dl_kwargs: dict, + ) -> None: + env = os.environ.copy() + env["HF_HUB_DISABLE_XET"] = "1" + payload = json.dumps({"kwargs": dl_kwargs}).encode() + process = await asyncio.create_subprocess_exec( + sys.executable, + "-m", + _NON_XET_WORKER_MODULE, + stdin=asyncio.subprocess.PIPE, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + env=env, + ) + self._fallback_processes[task_id] = process + + try: + stdout, _ = await process.communicate(input=payload) + try: + response = json.loads(stdout.decode()) + except (UnicodeDecodeError, json.JSONDecodeError) as error: + raise _NonXetDownloadError( + f"HTTP fallback process exited with code {process.returncode}" + ) from error + if process.returncode != 0 or not response.get("ok"): + error_type = response.get("error_type", "DownloadError") + message = response.get("message", "unknown error") + raise _NonXetDownloadError(f"{error_type}: {message}") + except asyncio.CancelledError: + await self._stop_subprocess(process) + raise + finally: + self._fallback_processes.pop(task_id, None) + + @staticmethod + async def _stop_subprocess(process: asyncio.subprocess.Process) -> None: + if process.returncode is not None: + return + try: + process.send_signal(signal.SIGINT) + except ProcessLookupError: + return + try: + await asyncio.wait_for( + process.wait(), + timeout=_SUBPROCESS_TERMINATE_TIMEOUT, + ) + return + except TimeoutError: + try: + process.terminate() + except ProcessLookupError: + return + try: + await asyncio.wait_for( + process.wait(), + timeout=_SUBPROCESS_TERMINATE_TIMEOUT, + ) + except TimeoutError: + try: + process.kill() + except ProcessLookupError: + return + await process.wait() + async def _poll_progress(self, task_id: str, target_dir: Path) -> None: """Poll the target directory to estimate download progress. @@ -993,59 +1173,96 @@ async def _poll_progress(self, task_id: str, target_dir: Path) -> None: if task is None: return - last_size = 0 - last_activity_at = time.time() + last_activity = self._get_download_activity(target_dir) + last_activity_at = time.monotonic() + observed_activity = False try: while task.status == DownloadStatus.DOWNLOADING: - await asyncio.sleep(2) + await asyncio.sleep(_PROGRESS_POLL_INTERVAL) if task.status != DownloadStatus.DOWNLOADING: break - current_size = self._get_dir_size(target_dir) - task.downloaded_size = current_size + activity = self._get_download_activity(target_dir) + task.downloaded_size = activity.logical_size if task.total_size > 0: # Cap at 99% until snapshot_download confirms completion task.progress = min( - (current_size / task.total_size) * 100, 99.0 + (activity.logical_size / task.total_size) * 100, + 99.0, ) - # Activity detection: size change OR file mtime change - if current_size != last_size: - last_size = current_size - last_activity_at = time.time() - else: - latest_mtime = self._get_latest_mtime(target_dir) - if latest_mtime > last_activity_at: - last_activity_at = latest_mtime - - # Stall detection - if ( - current_size > 0 - and (time.time() - last_activity_at) > _STALL_TIMEOUT - ): - task.status = DownloadStatus.FAILED - task.error = ( - f"Download stalled: no progress for {_STALL_TIMEOUT}s. " - "Try retrying the download." + if activity != last_activity: + # A zero-byte temp file or metadata touch is not payload + # progress. APFS allocated blocks increase when bytes are + # actually written, including into sparse/preallocated files. + if activity.allocated_size > last_activity.allocated_size: + observed_activity = True + last_activity = activity + last_activity_at = time.monotonic() + continue + + timeout = ( + _STALL_TIMEOUT + if observed_activity + else _STARTUP_STALL_TIMEOUT + ) + if time.monotonic() - last_activity_at > timeout: + phase = "active" if observed_activity else "startup" + process = self._fallback_processes.get(task_id) + transport = "HTTP fallback" if process else "Xet" + stalled = _DownloadStalledError( + transport=transport, + phase=phase, + timeout=timeout, ) + self._stalled[task_id] = stalled logger.warning( - f"Download stalled for {task.repo_id} " - f"(task_id={task_id})" + "%s for %s (task_id=%s)", + stalled, + task.repo_id, + task_id, ) - # Cancel the snapshot_download thread. The task cancel - # only unblocks the awaiting coroutine; aborting the xet - # session is what actually reaps a wedged transfer thread. - active_task = self._active_tasks.get(task_id) - if active_task and not active_task.done(): - active_task.cancel() - abort_xet_session() + if process is not None: + await self._stop_subprocess(process) + else: + abort_xet_session() break except asyncio.CancelledError: pass + @staticmethod + def _get_download_activity(path: Path) -> _DownloadActivity: + """Return size, allocation, and mtime signals including Hub temp files.""" + if not path.exists(): + return _DownloadActivity() + file_count = 0 + logical_size = 0 + allocated_size = 0 + latest_mtime_ns = 0 + try: + for file_path in path.rglob("*"): + if not file_path.is_file(): + continue + try: + stat = file_path.stat() + except OSError: + continue + file_count += 1 + logical_size += stat.st_size + allocated_size += getattr(stat, "st_blocks", 0) * 512 + latest_mtime_ns = max(latest_mtime_ns, stat.st_mtime_ns) + except OSError: + pass + return _DownloadActivity( + file_count=file_count, + logical_size=logical_size, + allocated_size=allocated_size, + latest_mtime_ns=latest_mtime_ns, + ) + @staticmethod def _get_latest_mtime(path: Path) -> float: """Return the most recent modification time of any file in a directory.""" diff --git a/tests/test_hf_downloader.py b/tests/test_hf_downloader.py index ba8c4962c6..1e5403d158 100644 --- a/tests/test_hf_downloader.py +++ b/tests/test_hf_downloader.py @@ -3,25 +3,27 @@ import asyncio import json +import os import shutil import threading import time -from pathlib import Path from unittest.mock import AsyncMock, MagicMock, patch import httpx import pytest from huggingface_hub.utils import HfHubHTTPError +from omlx._hf_download_worker import _download_without_xet from omlx.admin.hf_downloader import ( DownloadStatus, DownloadTask, HFDownloader, + _DownloadActivity, _DownloadCancelled, + _is_xet_transport_error, _make_cancellable_tqdm, ) - # ============================================================================= # DownloadTask Tests # ============================================================================= @@ -2540,91 +2542,255 @@ def model_dir(self, tmp_path): return d @pytest.mark.asyncio - async def test_stall_detection_marks_task_failed(self, model_dir, monkeypatch): - """Download should be marked failed when stalled for _STALL_TIMEOUT seconds.""" + async def test_zero_byte_startup_stall_aborts_xet(self, model_dir, monkeypatch): + """No first write must trigger the startup deadline, including at 0%.""" import omlx.admin.hf_downloader as dl_module - # Use a very short stall timeout for testing - monkeypatch.setattr(dl_module, "_STALL_TIMEOUT", 2) - + monkeypatch.setattr(dl_module, "_STARTUP_STALL_TIMEOUT", 0.03) + monkeypatch.setattr(dl_module, "_PROGRESS_POLL_INTERVAL", 0.01) target = model_dir / "owner" / "model" target.mkdir(parents=True) - # Create a file so current_size > 0 (needed to trigger stall detection) - (target / "partial.bin").write_bytes(b"x" * 1000) + downloader = HFDownloader(model_dir=str(model_dir)) + task = DownloadTask( + task_id="t1", + repo_id="owner/model", + status=DownloadStatus.DOWNLOADING, + ) + downloader._tasks[task.task_id] = task + calls = 0 + + def zero_byte_temp(_path): + nonlocal calls + calls += 1 + if calls == 1: + return _DownloadActivity() + return _DownloadActivity(file_count=1, latest_mtime_ns=1) + + with patch.object( + downloader, + "_get_download_activity", + side_effect=zero_byte_temp, + ), patch("omlx.admin.hf_downloader.abort_xet_session") as mock_abort: + await downloader._poll_progress(task.task_id, target) + + stalled = downloader._stalled[task.task_id] + assert stalled.phase == "startup" + assert stalled.transport == "Xet" + mock_abort.assert_called_once() + @pytest.mark.asyncio + async def test_active_stall_uses_longer_timeout(self, model_dir, monkeypatch): + """After the first write, the active-transfer timeout must apply.""" + import omlx.admin.hf_downloader as dl_module + + monkeypatch.setattr(dl_module, "_STARTUP_STALL_TIMEOUT", 1) + monkeypatch.setattr(dl_module, "_STALL_TIMEOUT", 0.03) + monkeypatch.setattr(dl_module, "_PROGRESS_POLL_INTERVAL", 0.01) downloader = HFDownloader(model_dir=str(model_dir)) + task = DownloadTask( + task_id="t1", + repo_id="owner/model", + status=DownloadStatus.DOWNLOADING, + ) + downloader._tasks[task.task_id] = task + empty = _DownloadActivity() + writing = _DownloadActivity( + file_count=1, + logical_size=10, + allocated_size=4096, + latest_mtime_ns=1, + ) - def _slow_download(**kwargs): + with patch.object( + downloader, + "_get_download_activity", + side_effect=[empty, writing, writing, writing, writing, writing], + ), patch("omlx.admin.hf_downloader.abort_xet_session") as mock_abort: + await downloader._poll_progress(task.task_id, model_dir) + + stalled = downloader._stalled[task.task_id] + assert stalled.phase == "active" + assert stalled.timeout == 0.03 + mock_abort.assert_called_once() + + +# ============================================================================= +# Xet HTTP Fallback Tests +# ============================================================================= + + +class TestXetHTTPFallback: + @pytest.fixture + def model_dir(self, tmp_path): + path = tmp_path / "models" + path.mkdir() + return path + + @staticmethod + def _api(): + api = MagicMock() + info = MagicMock() + info.safetensors = {} + api.model_info.return_value = info + return api + + @pytest.mark.parametrize( + ("error", "expected"), + [ + ( + RuntimeError( + "CAS service error: ReqwestMiddleware request failed " + "for /xet-read-token" + ), + True, + ), + (RuntimeError("ordinary download failure"), False), + (OSError(28, "No space left on device"), False), + ], + ) + def test_xet_error_classification(self, error, expected): + assert _is_xet_transport_error(error) is expected + + @pytest.mark.asyncio + async def test_xet_error_retries_once_over_http(self, model_dir): + downloader = HFDownloader(model_dir=str(model_dir)) + task = DownloadTask(task_id="t1", repo_id="owner/model") + downloader._tasks[task.task_id] = task + + def fail_xet(**kwargs): if kwargs.get("dry_run"): return [] - time.sleep(30) + raise RuntimeError( + "CAS service error: ReqwestMiddleware request failed " + "for /xet-read-token" + ) with patch( - "omlx.admin.hf_downloader.HfApi" - ) as mock_api_cls, patch( - "omlx.admin.hf_downloader.snapshot_download", - side_effect=_slow_download, + "omlx.admin.hf_downloader._get_hf_api", + return_value=(self._api(), None), ), patch( - "omlx.admin.hf_downloader.abort_xet_session" - ) as mock_abort: - mock_api = MagicMock() - mock_info = MagicMock() - mock_info.safetensors = {"parameters": {"BF16": 5000}} - mock_api.model_info.return_value = mock_info - mock_api_cls.return_value = mock_api + "omlx.admin.hf_downloader.snapshot_download", + side_effect=fail_xet, + ), patch.object( + downloader, + "_run_http_fallback", + new_callable=AsyncMock, + ) as fallback: + await downloader._run_download(task.task_id, "secret-token") - task = await downloader.start_download("owner/model") + fallback.assert_awaited_once() + assert task.status == DownloadStatus.COMPLETED - # Wait for stall detection to kick in (2s timeout + polling intervals) - await asyncio.sleep(8) + @pytest.mark.asyncio + async def test_zero_byte_stall_waits_for_xet_exit_before_fallback( + self, model_dir, monkeypatch + ): + import omlx.admin.hf_downloader as dl_module - assert task.status == DownloadStatus.FAILED - assert "stalled" in task.error.lower() - # The stall handler must reap the wedged xet transfer thread. - mock_abort.assert_called() + monkeypatch.setattr(dl_module, "_STARTUP_STALL_TIMEOUT", 0.03) + monkeypatch.setattr(dl_module, "_PROGRESS_POLL_INTERVAL", 0.01) + downloader = HFDownloader(model_dir=str(model_dir)) + task = DownloadTask(task_id="t1", repo_id="owner/model") + downloader._tasks[task.task_id] = task + aborted = threading.Event() + events = [] - await downloader.shutdown() + def stalled_xet(**kwargs): + if kwargs.get("dry_run"): + return [] + assert aborted.wait(1) + events.append("xet_stopped") + raise RuntimeError("xet session aborted") - @pytest.mark.asyncio - async def test_no_stall_when_size_zero(self, model_dir, monkeypatch): - """Stall detection should not trigger when current_size is 0.""" - import omlx.admin.hf_downloader as dl_module + async def finish_http(*_args, **_kwargs): + events.append("http_started") - monkeypatch.setattr(dl_module, "_STALL_TIMEOUT", 1) + with patch( + "omlx.admin.hf_downloader._get_hf_api", + return_value=(self._api(), None), + ), patch( + "omlx.admin.hf_downloader.snapshot_download", + side_effect=stalled_xet, + ), patch( + "omlx.admin.hf_downloader.abort_xet_session", + side_effect=aborted.set, + ) as abort, patch.object( + downloader, + "_run_http_fallback", + side_effect=finish_http, + ) as fallback: + await downloader._run_download(task.task_id, "") - # Empty directory - no files yet - target = model_dir / "model" - target.mkdir() + assert events == ["xet_stopped", "http_started"] + abort.assert_called_once() + fallback.assert_awaited_once() + assert task.status == DownloadStatus.COMPLETED + @pytest.mark.asyncio + async def test_http_failure_preserves_both_errors(self, model_dir): downloader = HFDownloader(model_dir=str(model_dir)) + task = DownloadTask(task_id="t1", repo_id="owner/model") + downloader._tasks[task.task_id] = task - def _slow_download(**kwargs): + def fail_xet(**kwargs): if kwargs.get("dry_run"): return [] - time.sleep(10) + raise RuntimeError("CAS service error from hf_xet") with patch( - "omlx.admin.hf_downloader.HfApi" - ) as mock_api_cls, patch( + "omlx.admin.hf_downloader._get_hf_api", + return_value=(self._api(), None), + ), patch( "omlx.admin.hf_downloader.snapshot_download", - side_effect=_slow_download, + side_effect=fail_xet, + ), patch.object( + downloader, + "_run_http_fallback", + new_callable=AsyncMock, + side_effect=RuntimeError("HTTP offline"), ): - mock_api = MagicMock() - mock_info = MagicMock() - mock_info.safetensors = {"parameters": {"BF16": 5000}} - mock_api.model_info.return_value = mock_info - mock_api_cls.return_value = mock_api + await downloader._run_download(task.task_id, "") - task = await downloader.start_download("owner/model") - await asyncio.sleep(5) + assert task.status == DownloadStatus.FAILED + assert "CAS service error" in task.error + assert "HTTP offline" in task.error - # Should still be downloading, not stalled - assert task.status in ( - DownloadStatus.DOWNLOADING, - DownloadStatus.COMPLETED, - ) + @pytest.mark.asyncio + async def test_http_worker_disables_xet_without_token_in_argv(self, model_dir): + downloader = HFDownloader(model_dir=str(model_dir)) + process = MagicMock() + process.returncode = 0 + process.communicate = AsyncMock(return_value=(b'{"ok": true}\n', b"")) + kwargs = { + "repo_id": "owner/model", + "local_dir": str(model_dir / "owner" / "model"), + "token": "secret-token", + "endpoint": None, + "etag_timeout": 30, + } - await downloader.shutdown() + with patch( + "omlx.admin.hf_downloader.asyncio.create_subprocess_exec", + new_callable=AsyncMock, + return_value=process, + ) as spawn: + await downloader._run_http_fallback("t1", kwargs) + + argv = spawn.await_args.args + assert argv[1:] == ("-m", "omlx._hf_download_worker") + assert "secret-token" not in argv + assert spawn.await_args.kwargs["env"]["HF_HUB_DISABLE_XET"] == "1" + request = json.loads(process.communicate.await_args.kwargs["input"]) + assert request["kwargs"]["token"] == "secret-token" + + def test_worker_sets_disable_xet_before_download(self, monkeypatch): + monkeypatch.delenv("HF_HUB_DISABLE_XET", raising=False) + download = MagicMock() + + _download_without_xet({"repo_id": "owner/model"}, download) + + assert os.environ["HF_HUB_DISABLE_XET"] == "1" + download.assert_called_once_with(repo_id="owner/model") # ============================================================================= @@ -2716,51 +2882,43 @@ async def test_mtime_prevents_false_stall(self, model_dir, monkeypatch): """Download should not stall if file mtimes are updating.""" import omlx.admin.hf_downloader as dl_module - monkeypatch.setattr(dl_module, "_STALL_TIMEOUT", 3) - - target = model_dir / "model" - target.mkdir() - # Create a file (size won't change, but mtime will) - test_file = target / "partial.bin" - test_file.write_bytes(b"x" * 1000) - + monkeypatch.setattr(dl_module, "_STARTUP_STALL_TIMEOUT", 0.03) + monkeypatch.setattr(dl_module, "_STALL_TIMEOUT", 0.03) + monkeypatch.setattr(dl_module, "_PROGRESS_POLL_INTERVAL", 0.01) downloader = HFDownloader(model_dir=str(model_dir)) - - # Simulate mtime advancing on each call call_count = 0 - original_get_latest_mtime = HFDownloader._get_latest_mtime - @staticmethod - def mock_get_latest_mtime(path): + def active_download(_path): nonlocal call_count call_count += 1 - # Return current time to simulate active writes - return time.time() + return _DownloadActivity( + file_count=1, + logical_size=1000, + allocated_size=4096, + latest_mtime_ns=call_count, + ) - monkeypatch.setattr( - HFDownloader, "_get_latest_mtime", mock_get_latest_mtime + task = DownloadTask( + task_id="t1", + repo_id="owner/model", + status=DownloadStatus.DOWNLOADING, ) + downloader._tasks[task.task_id] = task - with patch( - "omlx.admin.hf_downloader.HfApi" - ) as mock_api_cls, patch( - "omlx.admin.hf_downloader.snapshot_download", - side_effect=lambda **kwargs: time.sleep(30), - ): - mock_api = MagicMock() - mock_info = MagicMock() - mock_info.safetensors = {"parameters": {"BF16": 5000}} - mock_api.model_info.return_value = mock_info - mock_api_cls.return_value = mock_api - - task = await downloader.start_download("owner/model") - # Wait longer than stall timeout - await asyncio.sleep(8) - - # Should still be downloading because mtime keeps updating - assert task.status == DownloadStatus.DOWNLOADING + with patch.object( + downloader, + "_get_download_activity", + side_effect=active_download, + ), patch("omlx.admin.hf_downloader.abort_xet_session") as mock_abort: + poll = asyncio.create_task( + downloader._poll_progress(task.task_id, model_dir) + ) + await asyncio.sleep(0.08) + task.status = DownloadStatus.COMPLETED + await poll - await downloader.shutdown() + assert task.task_id not in downloader._stalled + mock_abort.assert_not_called() # ============================================================================= From c520d7e6124cf6255868e589c6beb75cf4cee8f9 Mon Sep 17 00:00:00 2001 From: jundot Date: Thu, 27 Aug 2026 19:09:55 +0900 Subject: [PATCH 013/132] feat: add GLM-5.3-Flash support --- omlx/cluster/planner.py | 45 +- omlx/engine/vlm.py | 57 +- omlx/memory_monitor.py | 23 +- omlx/model_discovery.py | 3 + omlx/oq.py | 56 +- omlx/patches/deepseek_v4/__init__.py | 51 +- omlx/patches/deepseek_v4/switch_layers.py | 14 +- .../mlx_vlm_glm5_next_compat/__init__.py | 62 + .../vendor/__init__.py | 1 + .../vendor/mlx_vlm/__init__.py | 1 + .../vendor/mlx_vlm/models/__init__.py | 1 + .../vendor/mlx_vlm/models/glm5_next/README.md | 23 + .../mlx_vlm/models/glm5_next/__init__.py | 18 + .../vendor/mlx_vlm/models/glm5_next/config.py | 136 +++ .../mlx_vlm/models/glm5_next/gated_delta.py | 302 +++++ .../mlx_vlm/models/glm5_next/glm5_next.py | 177 +++ .../mlx_vlm/models/glm5_next/language.py | 1006 +++++++++++++++++ .../vendor/mlx_vlm/models/glm5_next/linear.py | 108 ++ .../mlx_vlm/models/glm5_next/processing.py | 496 ++++++++ .../vendor/mlx_vlm/models/glm5_next/vision.py | 359 ++++++ omlx/utils/model_loading.py | 11 + tests/test_cluster_kv_reservation.py | 21 + tests/test_memory_monitor_vlm_config.py | 17 + tests/test_mlx_vlm_glm5_next_compat.py | 610 ++++++++++ 24 files changed, 3554 insertions(+), 44 deletions(-) create mode 100644 omlx/patches/mlx_vlm_glm5_next_compat/__init__.py create mode 100644 omlx/patches/mlx_vlm_glm5_next_compat/vendor/__init__.py create mode 100644 omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/__init__.py create mode 100644 omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/__init__.py create mode 100644 omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/README.md create mode 100644 omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/__init__.py create mode 100644 omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/config.py create mode 100644 omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/gated_delta.py create mode 100644 omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/glm5_next.py create mode 100644 omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/language.py create mode 100644 omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/linear.py create mode 100644 omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/processing.py create mode 100644 omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/vision.py create mode 100644 tests/test_mlx_vlm_glm5_next_compat.py diff --git a/omlx/cluster/planner.py b/omlx/cluster/planner.py index 2b5ae26ff8..cdc31edecf 100644 --- a/omlx/cluster/planner.py +++ b/omlx/cluster/planner.py @@ -581,6 +581,25 @@ def _config_int( ) +def _config_nonnegative_int(config: dict[str, Any], key: str) -> int | None: + """Read an explicitly present, bounded integer that may be zero.""" + candidates = [config] + for nested in ("text_config", "language_config", "llm_config"): + value = config.get(nested) + if isinstance(value, dict): + candidates.append(value) + return next( + ( + value + for candidate in candidates + if isinstance((value := candidate.get(key)), int) + and not isinstance(value, bool) + and 0 <= value <= 4096 + ), + None, + ) + + def _supports_tensor_parallel(config: dict[str, Any]) -> bool: """Whether this architecture has a runtime-safe tensor strategy. @@ -796,7 +815,7 @@ def _kv_cache_replicated_across_tp(config: dict[str, Any]) -> bool: return ( _config_int(config, "kv_lora_rank", 0) > 0 - and _config_int(config, "qk_rope_head_dim", 0) > 0 + and _config_nonnegative_int(config, "qk_rope_head_dim") is not None ) @@ -819,7 +838,29 @@ def _kv_bytes_per_token_per_layer(config: dict[str, Any]) -> int: if _kv_cache_replicated_across_tp(config): # One KV head holding latent + RoPE, not expanded K/V tensors. kv_lora_rank = _config_int(config, "kv_lora_rank", 0) - rope_dim = _config_int(config, "qk_rope_head_dim", 0) + rope_dim = _config_nonnegative_int(config, "qk_rope_head_dim") or 0 + text_config = config.get("text_config") + layer_config = text_config if isinstance(text_config, dict) else config + layer_types = layer_config.get("layer_types") + if config.get("model_type") == "glm5_next" and isinstance( + layer_types, list + ): + num_layers = _config_int(config, "num_hidden_layers", 0) + sparse_layers = sum( + layer_type != "linear_attention" for layer_type in layer_types + ) + index_dim = _config_int(config, "index_head_dim", 0) + index_pool = _config_int(config, "index_kpool", 1) + if num_layers > 0 and sparse_layers > 0: + # ModelLayout stores one integral average per layer. Keep the + # exact full-model total conservative by rounding upward. + numerator = ( + sparse_layers + * ((kv_lora_rank + rope_dim) * index_pool + index_dim) + * dtype_size + ) + denominator = num_layers * index_pool + return (numerator + denominator - 1) // denominator return (kv_lora_rank + rope_dim) * dtype_size heads = _config_int(config, "num_attention_heads", 0) diff --git a/omlx/engine/vlm.py b/omlx/engine/vlm.py index f04f14da9f..c72ab5070c 100644 --- a/omlx/engine/vlm.py +++ b/omlx/engine/vlm.py @@ -1036,7 +1036,7 @@ def _patched_sanitize_moe_weights(weights: dict, args: Any) -> None: @contextlib.contextmanager def _force_qwen4_exp_sanitize_on_load(model_dir: Path): - """Run Qwen4-Exp key sanitization before quantization selection. + """Run vendored-model key sanitization before quantization selection. Converted MLX checkpoints legitimately declare ``format=mlx``, but the published Qwen4 layout still uses ``model.language_model.*`` and @@ -1046,7 +1046,8 @@ def _force_qwen4_exp_sanitize_on_load(model_dir: Path): the format marker for this model and this load so sanitization happens at the point expected by the upstream loader: before ``nn.quantize``. """ - if _read_config_model_type(model_dir) != "qwen4_exp": + model_type = _read_config_model_type(model_dir) + if model_type not in ("qwen4_exp", "glm5_next"): yield return @@ -1088,7 +1089,11 @@ def _patched_safe_open(filename, *args, **kwargs): safetensors.safe_open = _patched_safe_open try: - logger.info("Qwen4-Exp pre-quantization sanitize active for %s", model_dir.name) + logger.info( + "%s pre-quantization sanitize active for %s", + model_type, + model_dir.name, + ) yield finally: safetensors.safe_open = original_safe_open @@ -1178,7 +1183,7 @@ def _uses_mrope(vlm_model) -> bool: return False -# Qwen-style VLMs: vision_tower takes (pixel_values, grid_thw) +# Qwen-style VLMs: vision_tower takes (pixel_values, grid_thw). _QWEN_VISION_MODELS = { "qwen3_5", "qwen3_5_moe", @@ -1188,6 +1193,9 @@ def _uses_mrope(vlm_model) -> bool: "qwen2_5_vl", } +# Grid-based VLMs whose flat vision features can be split with grid_thw. +_GRID_VISION_MODELS = _QWEN_VISION_MODELS | {"glm5_next"} + # Conservative fallback upper bound on image-placeholder tokens per image # content part. Used by ``preflight_chat`` only when the actual @@ -1204,9 +1212,10 @@ def _uses_mrope(vlm_model) -> bool: def _derive_image_token_upper_bound(processor: Any) -> int: """Derive the per-image token upper bound from the processor config. - Qwen-style image processors expose ``max_pixels`` (an *area*) and - pack pixels into ``patch_size`` × ``patch_size`` patches, then merge - ``merge_size`` × ``merge_size`` patches into one model token. The + GLM processors expose the final ``max_image_tokens`` bound directly. + Qwen-style image processors expose ``max_pixels`` (an *area*) and pack + pixels into ``patch_size`` × ``patch_size`` patches, then merge + ``merge_size`` × ``merge_size`` patches into one model token. Their per-image token bound is therefore:: max_tokens = max_pixels / (patch_size**2 * merge_size**2) @@ -1218,6 +1227,9 @@ def _derive_image_token_upper_bound(processor: Any) -> int: if processor is None: return _IMAGE_TOKEN_UPPER_BOUND_FALLBACK ip = getattr(processor, "image_processor", None) or processor + max_image_tokens = getattr(ip, "max_image_tokens", None) + if isinstance(max_image_tokens, int) and max_image_tokens > 0: + return max(max_image_tokens, _IMAGE_TOKEN_UPPER_BOUND_FALLBACK) max_pixels = getattr(ip, "max_pixels", None) patch_size = getattr(ip, "patch_size", None) merge_size = getattr(ip, "merge_size", None) @@ -1353,8 +1365,13 @@ def _count_image_tokens_real( ms = getattr(ip, "merge_size", None) minp = getattr(ip, "min_pixels", None) maxp = getattr(ip, "max_pixels", None) - qwen_ok = all( - isinstance(x, int) and x > 0 for x in (ps, ms, minp, maxp) + qwen_ok = all(isinstance(x, int) and x > 0 for x in (ps, ms, minp, maxp)) + patch_counter = getattr(ip, "get_number_of_image_patches", None) + glm_ok = ( + callable(patch_counter) + and isinstance(ms, int) + and ms > 0 + and isinstance(getattr(ip, "max_image_tokens", None), int) ) total = 0 @@ -1367,9 +1384,14 @@ def _count_image_tokens_real( continue if part.get("type") not in ("image_url", "image", "input_image"): continue - wh = _read_image_dims(part) if qwen_ok else None + wh = _read_image_dims(part) if qwen_ok or glm_ok else None if wh is None: total += upper_bound + elif glm_ok: + try: + total += int(patch_counter(wh[1], wh[0]) // (ms**2)) + except Exception: + total += upper_bound else: total += _smart_resize_tokens(wh[1], wh[0], ps, ms, minp, maxp) return total @@ -1824,6 +1846,12 @@ def _load_vlm_sync(): scheduler = self._engine.engine.scheduler if self._model_settings is not None: tq_enabled = getattr(self._model_settings, "turboquant_kv_enabled", False) + if tq_enabled and self.model_type == "glm5_next": + logger.warning( + "TurboQuant KV cache is not supported for GLM-5.3-Flash's " + "composite latent/indexer cache; using the native cache layout" + ) + tq_enabled = False if tq_enabled: from ..patches.turboquant_attention import ( apply_turboquant_attention_patch, @@ -2648,13 +2676,14 @@ def _split_vision_features( return result # Qwen: flat (total_merged_tokens, dim) → split using grid_thw - if model_type in _QWEN_VISION_MODELS and features.ndim == 2: + if model_type in _GRID_VISION_MODELS and features.ndim == 2: grid_thw = extra_model_inputs.get("image_grid_thw") if grid_thw is None: return None - spatial_merge_size = getattr( - self._vlm_model.vision_tower, "spatial_merge_size", 2 - ) + vision_tower = getattr(self._vlm_model, "vision_tower", None) + if vision_tower is None: + vision_tower = getattr(self._vlm_model, "vision_model", None) + spatial_merge_size = getattr(vision_tower, "spatial_merge_size", 2) merge_sq = spatial_merge_size**2 per_image_tokens = [] for i in range(num_images): diff --git a/omlx/memory_monitor.py b/omlx/memory_monitor.py index 1cf691299d..39cb9ecb27 100644 --- a/omlx/memory_monitor.py +++ b/omlx/memory_monitor.py @@ -919,6 +919,10 @@ def _pos_int(v: Any) -> bool: return isinstance(v, int) and not isinstance(v, bool) and v > 0 +def _nonnegative_int(v: Any) -> bool: + return isinstance(v, int) and not isinstance(v, bool) and v >= 0 + + @dataclass(frozen=True) class _DeepSeekV4PrefillMemoryProfile: """Exact-shape prefill estimator for DeepSeek V4's hybrid attention. @@ -1379,20 +1383,21 @@ def estimate_mla_kv_bytes_per_token( GLM/DeepSeek MLA models do not store expanded ``num_kv_heads * head_dim`` K/V tensors. Their main cache stores a latent key and RoPE value (``kv_lora_rank + qk_rope_head_dim``) with a single KV head. GLM-5.2's DSA - indexer adds a second cache on full-indexer layers containing only - ``index_head_dim`` keys and zero-width values. Falling back to the standard - uniform KV formula over-counts GLM-5.2 by more than an order of magnitude. + indexer adds a second cache on full-indexer layers. GLM-5.2 stores one + ``index_head_dim`` key per token, while GLM-5.3 pools those keys by the + cache's compression ratio. Falling back to the standard uniform KV formula + over-counts these models by more than an order of magnitude. """ kv_lora_rank = _cfg_get(config, "kv_lora_rank") rope_dim = _cfg_get(config, "qk_rope_head_dim") - if not (_pos_int(kv_lora_rank) and _pos_int(rope_dim)): + if not (_pos_int(kv_lora_rank) and _nonnegative_int(rope_dim)): return None if cache_list is None: return None main_cache_layers = 0 - indexer_cache_layers = 0 + indexer_cache_token_ratio = 0.0 try: for layer_cache in cache_list: caches = getattr(layer_cache, "caches", None) @@ -1402,7 +1407,11 @@ def estimate_mla_kv_bytes_per_token( if n_caches >= 1: main_cache_layers += 1 if n_caches >= 2: - indexer_cache_layers += 1 + indexer_cache = caches[1] + ratio = getattr(indexer_cache, "ratio", 1) + if not _pos_int(ratio): + ratio = 1 + indexer_cache_token_ratio += 1.0 / ratio except Exception: return None @@ -1415,7 +1424,7 @@ def estimate_mla_kv_bytes_per_token( elems_per_token = ( main_cache_layers * (kv_lora_rank + rope_dim) - + indexer_cache_layers * index_head_dim + + indexer_cache_token_ratio * index_head_dim ) return float(elems_per_token) * float(dtype_size) diff --git a/omlx/model_discovery.py b/omlx/model_discovery.py index 56f2861955..62ff6eb8f0 100644 --- a/omlx/model_discovery.py +++ b/omlx/model_discovery.py @@ -68,6 +68,7 @@ "inkling", "inkling_mm_model", # config model_type of Inkling Small checkpoints "muse_glimmer", + "glm5_next", } # Text-only model families that are implemented in mlx-vlm rather than @@ -75,6 +76,7 @@ # models and adapts their language model to oMLX's scheduler. VLM_NATIVE_TEXT_MODEL_TYPES = { "cohere2_moe", + "glm5_next", "minimax_m3", } @@ -162,6 +164,7 @@ def is_helper_model_config(config: dict) -> bool: "UnlimitedOCRForCausalLM", # baidu/Unlimited-OCR "InklingForConditionalGeneration", # thinkingmachines/Inkling-Small "MuseGlimmerForConditionalGeneration", # meta-models/Muse-Glimmer-30B + "Glm5NextForConditionalGeneration", # zai-org/GLM-5.3-Flash } # Known embedding model types from mlx-embeddings diff --git a/omlx/oq.py b/omlx/oq.py index c7e2a57bca..c8a451dd52 100644 --- a/omlx/oq.py +++ b/omlx/oq.py @@ -34,6 +34,7 @@ from omlx.model_discovery import ( MLX_LM_TEXT_ONLY_MODEL_TYPES, + VLM_NATIVE_TEXT_MODEL_TYPES, _has_vision_subconfig, ) @@ -146,7 +147,7 @@ def _is_vlm_load(config: dict) -> bool: ``mlx_vlm.speculative.drafters.`` lookup and fails. """ model_type = str(config.get("model_type", "")).lower().replace("-", "_") - return ( + return model_type in VLM_NATIVE_TEXT_MODEL_TYPES or ( _has_vision_subconfig(config) and model_type not in MLX_LM_TEXT_ONLY_MODEL_TYPES ) @@ -315,7 +316,13 @@ def _glm_indexer_q8_override(path: str, config: dict) -> dict | None: while making the saved checkpoint incompatible with the fused Q8 loader. Keep backbone and preserved-MTP indexers on the same explicit format. """ - if config.get("model_type") != "glm_moe_dsa": + text_config = config.get("text_config") + text_model_type = ( + text_config.get("model_type") if isinstance(text_config, dict) else None + ) + if config.get("model_type") not in ("glm_moe_dsa", "glm5_next") and ( + text_model_type != "glm5_next_text" + ): return None path = _normalize_quant_path(path) if ".self_attn.indexer." not in path: @@ -3761,6 +3768,7 @@ def _build_model_sanitizer(config: dict, text_only: bool = False): is_vlm = ( any("ForConditionalGeneration" in a for a in architectures) or _has_vision_subconfig(config) + or model_type in VLM_NATIVE_TEXT_MODEL_TYPES ) and not (text_only or mlx_lm_text_only) if is_vlm: @@ -3793,8 +3801,14 @@ def _build_model_sanitizer(config: dict, text_only: bool = False): ) apply_mlx_vlm_muse_glimmer_compat_patch() + if model_type == "glm5_next": + from omlx.patches.mlx_vlm_glm5_next_compat import ( + apply_mlx_vlm_glm5_next_compat_patch, + ) + + apply_mlx_vlm_glm5_next_compat_patch() except Exception as patch_err: - logger.debug(f"MiniMax M3 mlx-vlm patch not applied: {patch_err}") + logger.debug(f"mlx-vlm compatibility patch not applied: {patch_err}") from mlx_vlm.utils import get_model_and_args, sanitize_weights @@ -3886,6 +3900,31 @@ def __getattr__(self, name): # discovery works without instantiating the full model. _lm_proxy = type("_LMProxy", (), {})() _lm_proxy.args = text_config + if model_type == "glm5_next": + attention_proxy = type("_AttentionProxy", (), {"embed_q": None}) + layer_proxy = type( + "_LayerProxy", + (), + {"self_attn": attention_proxy()}, + ) + _lm_proxy.model = type( + "_ModelProxy", + (), + { + "layers": [ + layer_proxy() + for _ in range(text_config.num_hidden_layers) + ] + }, + )() + _lm_proxy.sanitize = lambda weights: model_module.LanguageModel.sanitize( + _lm_proxy, weights + ) + _vision_proxy = type("_VisionProxy", (), {})() + _vision_proxy.sanitize = ( + lambda weights: model_module.VisionModel.sanitize(weights) + ) + proxy.vision_model = _vision_proxy proxy.language_model = _lm_proxy # Model.sanitize is an instance method (self, weights) for most # VLMs, but a @staticmethod (weights) for the DeepSeek-OCR family @@ -3902,13 +3941,20 @@ def __getattr__(self, name): # (inkling's __init__ has no VisionModel); a missing class # simply has no per-tower sanitize to run. vision_cls = getattr(model_module, "VisionModel", None) - if vision_cls is not None: + if vision_cls is not None and model_type != "glm5_next": w = sanitize_weights(vision_cls, w, vision_config) language_cls = getattr(model_module, "LanguageModel", None) - if language_cls is not None: + if language_cls is not None and model_type != "glm5_next": w = sanitize_weights(language_cls, w, text_config) return w + if model_type == "glm5_next": + from mlx_vlm.models.glm5_next.language import ( + glm5_next_cast_predicate, + ) + + _vlm_sanitize._omlx_cast_predicate = glm5_next_cast_predicate + logger.info( f"Using mlx-vlm full sanitize chain for " f"{model_module.Model.__name__} " diff --git a/omlx/patches/deepseek_v4/__init__.py b/omlx/patches/deepseek_v4/__init__.py index 1759f70599..fb0ce6a7f3 100644 --- a/omlx/patches/deepseek_v4/__init__.py +++ b/omlx/patches/deepseek_v4/__init__.py @@ -46,6 +46,7 @@ PR_URL = "https://github.com/ml-explore/mlx-lm/pull/1192" _APPLIED = False +_POOLING_APPLIED = False def _inject_cache_extras() -> None: @@ -160,6 +161,28 @@ def _probe_native_indexer_kernels() -> None: ) +def apply_pooling_cache_support() -> bool: + """Install the model-neutral PoolingCache runtime and oMLX handlers.""" + global _POOLING_APPLIED + if _POOLING_APPLIED: + return False + + try: + import mlx_lm # noqa: F401 + except ImportError: + logger.debug("mlx-lm not importable — pooling cache support skipped") + return False + + _inject_cache_extras() + + from .generate_patch import apply_generate_patch + + apply_generate_patch() + _register_cache_handlers() + _POOLING_APPLIED = True + return True + + def apply_deepseek_v4_patch() -> bool: """Apply the DeepSeek V4 patch to mlx-lm. Idempotent. @@ -179,9 +202,9 @@ def apply_deepseek_v4_patch() -> bool: return False # Order matters: - # 1. Inject PoolingCache / BatchPoolingCache so the deepseek_v4 module - # can ``from .cache import PoolingCache`` at exec time. - _inject_cache_extras() + # 1. Inject PoolingCache / BatchPoolingCache and install their batch/cache + # integration. GLM-5.3 also consumes this model-neutral subset. + apply_pooling_cache_support() # 2. Register hyper_connection BEFORE deepseek_v4 (deepseek_v4 imports # HyperConnection / HyperHead / hc_expand from it). @@ -196,12 +219,7 @@ def apply_deepseek_v4_patch() -> bool: apply_utils_patch() - # 5. Patch generate._make_cache (PoolingCache → BatchPoolingCache). - from .generate_patch import apply_generate_patch - - apply_generate_patch() - - # 6. Wrap tokenizer_utils.AutoTokenizer (deepseek_v4 fallback for + # 5. Wrap tokenizer_utils.AutoTokenizer (deepseek_v4 fallback for # transformers releases that pre-date PR 45643 / 2026-05-02). from .tokenizer_patch import apply_load_patch, apply_tokenizer_patch @@ -212,13 +230,10 @@ def apply_deepseek_v4_patch() -> bool: # minimal and lacks tool grammar. apply_load_patch() - # 8. Register omlx-side cache handlers. - _register_cache_handlers() - - # 9. One-time native indexer kernel probe (INFO/WARNING only). + # 6. One-time native indexer kernel probe (INFO/WARNING only). _probe_native_indexer_kernels() - # 10. sanitize() stacks the expert biases, so sharded_load's weight-index + # 7. sanitize() stacks the expert biases, so sharded_load's weight-index # gate would reject a local checkpoint the normal loader handles fine. from omlx.patches.mlx_lm_sharded_load import install_local_sharded_load_fallback @@ -233,4 +248,10 @@ def is_applied() -> bool: return _APPLIED -__all__ = ["apply_deepseek_v4_patch", "is_applied", "PR_HEAD_SHA", "PR_URL"] +__all__ = [ + "PR_HEAD_SHA", + "PR_URL", + "apply_deepseek_v4_patch", + "apply_pooling_cache_support", + "is_applied", +] diff --git a/omlx/patches/deepseek_v4/switch_layers.py b/omlx/patches/deepseek_v4/switch_layers.py index 07d0fa7413..6b1d4c57dd 100644 --- a/omlx/patches/deepseek_v4/switch_layers.py +++ b/omlx/patches/deepseek_v4/switch_layers.py @@ -413,7 +413,7 @@ def __init__( self.down_proj = SwitchLinear(hidden_dims, input_dims, num_experts, bias=bias) self.activation = activation - def __call__(self, x, indices, scores=None) -> mx.array: + def __call__(self, x, indices, scores=None, weighted_sum=False) -> mx.array: x = mx.expand_dims(x, (-2, -3)) original_dtype = x.dtype @@ -556,6 +556,18 @@ def __call__(self, x, indices, scores=None) -> mx.array: block_plan=block_plan, ) + if ( + weighted_sum + and scores is not None + and do_sort + and scores.shape[-1] in (6, 8) + and scores.dtype == mx.float32 + and x.dtype in (mx.float16, mx.bfloat16) + and glm_fast.has_symbol("glm_moe_weighted_sum") + ): + y = glm_fast.glm_moe_weighted_sum(x, inv_order, scores) + return y.astype(original_dtype) if use_f16_moe else y + if do_sort: x = _scatter_unsort(x, inv_order, indices.shape) diff --git a/omlx/patches/mlx_vlm_glm5_next_compat/__init__.py b/omlx/patches/mlx_vlm_glm5_next_compat/__init__.py new file mode 100644 index 0000000000..8397c2a388 --- /dev/null +++ b/omlx/patches/mlx_vlm_glm5_next_compat/__init__.py @@ -0,0 +1,62 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Register the vendored GLM-5.3-Flash implementation with mlx-vlm.""" + +from __future__ import annotations + +import importlib +import logging +from pathlib import Path +from typing import Any + +logger = logging.getLogger(__name__) + +PR_URL = "https://github.com/Blaizzy/mlx-vlm/pull/2030" +PR_MERGE_SHA = "fa27a9a692770c39fdf57b9a985fad084a90aec2" +_VENDOR_MLX_VLM = Path(__file__).resolve().parent / "vendor" / "mlx_vlm" +_APPLIED = False + + +def _append_package_path(package: Any, path: Path) -> None: + package_path = getattr(package, "__path__", None) + if package_path is None: + return + path_string = str(path) + if path_string not in package_path: + package_path.append(path_string) + + +def apply_mlx_vlm_glm5_next_compat_patch() -> bool: + """Expose ``mlx_vlm.models.glm5_next`` from oMLX's vendor tree.""" + global _APPLIED + if _APPLIED: + return False + + try: + import mlx_vlm + import mlx_vlm.models + + from omlx.patches.deepseek_v4 import apply_pooling_cache_support + + apply_pooling_cache_support() + _append_package_path(mlx_vlm, _VENDOR_MLX_VLM) + _append_package_path(mlx_vlm.models, _VENDOR_MLX_VLM / "models") + importlib.import_module("mlx_vlm.models.glm5_next") + except Exception as exc: # noqa: BLE001 + logger.debug("GLM-5.3 mlx-vlm registration failed: %s", exc) + return False + + _APPLIED = True + logger.info("GLM-5.3 mlx-vlm compatibility patch applied") + return True + + +def is_applied() -> bool: + return _APPLIED + + +__all__ = [ + "PR_MERGE_SHA", + "PR_URL", + "apply_mlx_vlm_glm5_next_compat_patch", + "is_applied", +] diff --git a/omlx/patches/mlx_vlm_glm5_next_compat/vendor/__init__.py b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/__init__.py new file mode 100644 index 0000000000..90ea2eae64 --- /dev/null +++ b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/__init__.py @@ -0,0 +1 @@ +"""Vendored dependency namespace.""" diff --git a/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/__init__.py b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/__init__.py new file mode 100644 index 0000000000..7cc6358c41 --- /dev/null +++ b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/__init__.py @@ -0,0 +1 @@ +"""Vendored mlx-vlm extensions.""" diff --git a/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/__init__.py b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/__init__.py new file mode 100644 index 0000000000..e8d02c18a0 --- /dev/null +++ b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/__init__.py @@ -0,0 +1 @@ +"""Vendored mlx-vlm model extensions.""" diff --git a/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/README.md b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/README.md new file mode 100644 index 0000000000..a3976660fa --- /dev/null +++ b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/README.md @@ -0,0 +1,23 @@ +# Vendored GLM-5.3-Flash support + +This package is based on the GLM-5 Next model implementation merged by +[`Blaizzy/mlx-vlm#2030`](https://github.com/Blaizzy/mlx-vlm/pull/2030) at +`fa27a9a692770c39fdf57b9a985fad084a90aec2`. It is vendored because oMLX's +pinned mlx-vlm release predates that model family. + +The text and vision paths also carry the non-speculative correctness fixes from +[`Blaizzy/mlx-vlm#2044`](https://github.com/Blaizzy/mlx-vlm/pull/2044), plus +oMLX runtime integration: + +- pooled indexer caches that support continuous batching and cache lifecycle + operations; +- GLM-5.2 DSA, sparse MLA, MoE weighted-sum, and gated-delta kernels where the + GLM-5.3 tensor contracts match; +- shared affine prefill QMM kernels for supported Q2/Q4/Q5/Q6/Q8 projections; +- a torch-free NumPy/Pillow image processor compatible with the official + checkpoint metadata and oMLX's pinned Transformers release. + +Lightning MTP is intentionally not included in this compatibility layer. The +base model drops `mtp.*` tensors during sanitization; GLM-5.3 Lightning MTP can +be added independently after its recurrent-state rollback and batched cache +semantics are validated. diff --git a/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/__init__.py b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/__init__.py new file mode 100644 index 0000000000..622d250fb6 --- /dev/null +++ b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/__init__.py @@ -0,0 +1,18 @@ +import mlx_vlm.models.glm5_next.processing # noqa: F401 (installs processor patch) + +from .config import ModelConfig, TextConfig, VisionConfig +from .glm5_next import Model +from .language import LanguageModel +from .processing import Glm5NextImageProcessor, Glm5NextProcessor +from .vision import VisionModel + +__all__ = [ + "Model", + "ModelConfig", + "TextConfig", + "VisionConfig", + "LanguageModel", + "VisionModel", + "Glm5NextImageProcessor", + "Glm5NextProcessor", +] diff --git a/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/config.py b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/config.py new file mode 100644 index 0000000000..ecfd774902 --- /dev/null +++ b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/config.py @@ -0,0 +1,136 @@ +from dataclasses import dataclass, field +from typing import Any, Dict, List, Optional + +from ..base import BaseModelConfig + + +@dataclass +class TextConfig(BaseModelConfig): + model_type: str + vocab_size: int + hidden_size: int + intermediate_size: int + moe_intermediate_size: int + num_hidden_layers: int + num_attention_heads: int + num_key_value_heads: int + n_shared_experts: Optional[int] + n_routed_experts: Optional[int] + routed_scaling_factor: float + kv_lora_rank: int + q_lora_rank: int + qk_rope_head_dim: int + v_head_dim: int + qk_nope_head_dim: int + num_experts_per_tok: int + first_k_dense_replace: int + max_position_embeddings: int + rms_norm_eps: float + index_topk: int + index_head_dim: int + index_n_heads: int + layer_types: List[str] + mlp_layer_types: List[str] + linear_attn_config: Dict[str, Any] + linear_num_heads: int = 64 + linear_head_dim: int = 128 + linear_conv_kernel_dim: int = 4 + linear_lower_bound: Optional[float] = -5.0 + qk_head_dim: int = 256 + head_dim: int = 0 + n_group: int = 1 + topk_group: int = 1 + moe_layer_freq: int = 1 + norm_topk_prob: bool = True + scoring_func: str = "sigmoid" + topk_method: str = "noaux_tc" + hidden_act: str = "silu" + attention_bias: bool = False + attention_dropout: float = 0.0 + tie_word_embeddings: bool = False + mla_use_nope: bool = True + indexer_rope_interleave: bool = True + indexer_types: Optional[List[str]] = None + index_kpool: int = 4 + index_kpool_compress: bool = True + index_kpool_always_select_tail: bool = True + swiglu_limit: float = 10.0 + hc_mult: int = 4 + hc_eps: float = 1e-06 + hc_sinkhorn_iters: int = 20 + mhc: bool = True + moe_router_dtype: str = "float32" + num_nextn_predict_layers: int = 0 + router_aux_loss_coef: float = 0.001 + output_router_logits: bool = False + rope_theta: float = 10000.0 + rope_parameters: Optional[Dict] = None + rope_scaling: Optional[Dict] = None + pad_token_id: int = 154820 + eos_token_id: Optional[List[int]] = None + + def __post_init__(self): + if self.rope_parameters is not None: + self.rope_scaling = self.rope_parameters + self.rope_theta = self.rope_parameters.get("rope_theta", self.rope_theta) + + cfg = self.linear_attn_config or {} + self.linear_num_heads = cfg.get("num_heads", self.linear_num_heads) + self.linear_head_dim = cfg.get("head_dim", self.linear_head_dim) + self.linear_conv_kernel_dim = cfg.get( + "short_conv_kernel_size", self.linear_conv_kernel_dim + ) + self.linear_lower_bound = cfg.get("gate_lower_bound", self.linear_lower_bound) + if cfg.get("safe_gate", True) and self.linear_lower_bound is None: + self.linear_lower_bound = -5.0 + + +@dataclass +class VisionConfig(BaseModelConfig): + model_type: str + depth: int + hidden_size: int + intermediate_size: int + num_heads: int + patch_size: int + out_hidden_size: int + projection_intermediate_size: int = 10240 + image_size: int = 448 + in_channels: int = 3 + rms_norm_eps: float = 1e-05 + attention_bias: bool = True + attention_dropout: float = 0.0 + hidden_act: str = "silu" + initializer_range: float = 0.02 + spatial_merge_size: int = 2 + temporal_patch_size: int = 2 + swiglu_limit: float = 10.0 + + @classmethod + def from_dict(cls, params): + # mlx-vlm inserts an empty vision_config for text-only checkpoints. + # Preserve that distinction instead of trying to construct a vision + # tower from missing required dimensions. + if not params: + return None + return super().from_dict(params) + + +@dataclass +class ModelConfig(BaseModelConfig): + text_config: TextConfig + model_type: str + vision_config: Optional[VisionConfig] = None + image_token_id: int = 154854 + video_token_id: int = 154855 + image_start_token_id: int = 154830 + image_end_token_id: int = 154831 + video_start_token_id: int = 154832 + video_end_token_id: int = 154833 + tie_word_embeddings: bool = False + pad_token_id: int = 154820 + eos_token_id: Optional[List[int]] = None + + def __post_init__(self): + if self.eos_token_id is None: + self.eos_token_id = [154820, 154827, 154829] diff --git a/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/gated_delta.py b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/gated_delta.py new file mode 100644 index 0000000000..ce5416cdad --- /dev/null +++ b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/gated_delta.py @@ -0,0 +1,302 @@ +from functools import partial +from typing import Optional, Tuple + +import mlx.core as mx +import mlx.nn as nn + + +@partial(mx.compile, shapeless=True) +def compute_g(A_log, a, dt_bias): + return mx.exp(-mx.exp(A_log.astype(mx.float32)) * nn.softplus(a + dt_bias)) + + +@partial(mx.compile, shapeless=True) +def compute_g_safe(A_log, a, dt_bias, lower_bound): + return mx.exp( + lower_bound * mx.sigmoid(mx.exp(A_log.astype(mx.float32)) * (a + dt_bias)) + ) + + +def _make_gated_delta_kernel(has_mask=False, vectorized=False): + if not mx.metal.is_available(): + return None + mask_source = "mask[b_idx * T + t]" if has_mask else "true" + + # Configure g indexing based on whether gating is vectorized + if vectorized: + g_comment = "// g: [B, T, Hv, Dk]" + g_setup = "auto g_ = g + (b_idx * T * Hv + hv_idx) * Dk;" + g_access = "g_[s_idx]" + g_advance = "g_ += Hv * Dk;" + else: + g_comment = "// g: [B, T, Hv]" + g_setup = "auto g_ = g + b_idx * T * Hv;" + g_access = "g_[hv_idx]" + g_advance = "g_ += Hv;" + + source = f""" + auto n = thread_position_in_grid.z; + auto b_idx = n / Hv; + auto hv_idx = n % Hv; + auto hk_idx = hv_idx / (Hv / Hk); + constexpr int n_per_t = Dk / 32; + + // q, k: [B, T, Hk, Dk] + auto q_ = q + b_idx * T * Hk * Dk + hk_idx * Dk; + auto k_ = k + b_idx * T * Hk * Dk + hk_idx * Dk; + + // v, y: [B, T, Hv, Dv] + auto v_ = v + b_idx * T * Hv * Dv + hv_idx * Dv; + y += b_idx * T * Hv * Dv + hv_idx * Dv; + + auto dk_idx = thread_position_in_threadgroup.x; + auto dv_idx = thread_position_in_grid.y; + + // state_in, state_out: [B, Hv, Dv, Dk] + auto i_state = state_in + (n * Dv + dv_idx) * Dk; + auto o_state = state_out + (n * Dv + dv_idx) * Dk; + + float state[n_per_t]; + for (int i = 0; i < n_per_t; ++i) {{ + auto s_idx = n_per_t * dk_idx + i; + state[i] = static_cast(i_state[s_idx]); + }} + + {g_comment} + {g_setup} + auto beta_ = beta + b_idx * T * Hv; + + for (int t = 0; t < T; ++t) {{ + if ({mask_source}) {{ + float kv_mem = 0.0f; + for (int i = 0; i < n_per_t; ++i) {{ + auto s_idx = n_per_t * dk_idx + i; + state[i] = state[i] * {g_access}; + kv_mem += state[i] * k_[s_idx]; + }} + kv_mem = simd_sum(kv_mem); + + auto delta = (v_[dv_idx] - kv_mem) * beta_[hv_idx]; + + float out = 0.0f; + for (int i = 0; i < n_per_t; ++i) {{ + auto s_idx = n_per_t * dk_idx + i; + state[i] = state[i] + k_[s_idx] * delta; + out += state[i] * q_[s_idx]; + }} + out = simd_sum(out); + if (thread_index_in_simdgroup == 0) {{ + y[dv_idx] = static_cast(out); + }} + }} else {{ + y[dv_idx] = static_cast(0); + }} + // Increment data pointers to next time step + q_ += Hk * Dk; + k_ += Hk * Dk; + v_ += Hv * Dv; + y += Hv * Dv; + {g_advance} + beta_ += Hv; + }} + for (int i = 0; i < n_per_t; ++i) {{ + auto s_idx = n_per_t * dk_idx + i; + o_state[s_idx] = static_cast(state[i]); + }} + """ + inputs = ["q", "k", "v", "g", "beta", "state_in", "T"] + if has_mask: + inputs.append("mask") + + suffix = "" + if vectorized: + suffix += "_vec" + if has_mask: + suffix += "_mask" + + return mx.fast.metal_kernel( + name=f"gated_delta_step{suffix}", + input_names=inputs, + output_names=["y", "state_out"], + source=source, + ) + + +_gated_delta_kernel = _make_gated_delta_kernel(has_mask=False, vectorized=False) +_gated_delta_kernel_masked = _make_gated_delta_kernel(has_mask=True, vectorized=False) +_gated_delta_kernel_vec = _make_gated_delta_kernel(has_mask=False, vectorized=True) +_gated_delta_kernel_vec_masked = _make_gated_delta_kernel( + has_mask=True, vectorized=True +) + + +@mx.compile +def _gated_delta_step_ops( + q: mx.array, + k: mx.array, + v: mx.array, + g: mx.array, + beta: mx.array, + state: mx.array, + mask: Optional[mx.array] = None, +) -> Tuple[mx.array, mx.array]: + """ + Ops-based reference implementation for a single recurrent step. + + Shapes: + - q, k: [B, H, Dk] + - v: [B, H, Dv] + - g: [B, H] or [B, H, Dk] + - beta: [B, H] + - state: [B, H, Dv, Dk] + Returns: + - y: [B, H, Dv] + - new_state: [B, H, Dv, Dk] + """ + + # Decay + old_state = state + if g.ndim == 2: + decay = g[..., None, None] + elif g.ndim == 3: + decay = g[..., None, :] + else: + raise ValueError(f"Unsupported gating shape {g.shape}") + state = state * decay + kv_mem = (state * k[..., None, :]).sum(axis=-1) # [B, H, Dv] + delta = (v - kv_mem) * beta[..., None] # [B, H, Dv] + state = state + k[..., None, :] * delta[..., None] + # Output projection along key dim with q + y = (state * q[..., None, :]).sum(axis=-1) # [B, H, Dv] + + if mask is not None: + state_mask = mx.expand_dims(mask, axis=(1, 2, 3)) + output_mask = mx.expand_dims(mask, axis=(1, 2)) + state = mx.where(state_mask, state, old_state) + y = mx.where(output_mask, y, 0) + return y.astype(q.dtype), state + + +def gated_delta_kernel( + q: mx.array, + k: mx.array, + v: mx.array, + g: mx.array, + beta: mx.array, + state: mx.array, + mask: Optional[mx.array] = None, +) -> Tuple[mx.array, mx.array]: + B, T, Hk, Dk = k.shape + Hv, Dv = v.shape[2:] + input_type = q.dtype + state_type = state.dtype + if g.ndim == 4: + kernel = _gated_delta_kernel_vec + inputs = [q, k, v, g, beta, state, T] + if mask is not None: + kernel = _gated_delta_kernel_vec_masked + inputs.append(mask) + else: + kernel = _gated_delta_kernel + inputs = [q, k, v, g, beta, state, T] + if mask is not None: + kernel = _gated_delta_kernel_masked + inputs.append(mask) + + return kernel( + inputs=inputs, + template=[ + ("InT", input_type), + ("StT", state_type), + ("Dk", Dk), + ("Dv", Dv), + ("Hk", Hk), + ("Hv", Hv), + ], + grid=(32, Dv, B * Hv), + threadgroup=(32, 4, 1), + output_shapes=[(B, T, Hv, Dv), state.shape], + output_dtypes=[input_type, state_type], + ) + + +def gated_delta_ops( + q: mx.array, + k: mx.array, + v: mx.array, + g: mx.array, + beta: mx.array, + state: Optional[mx.array] = None, + mask: Optional[mx.array] = None, +) -> Tuple[mx.array, mx.array]: + """ + Ops-based reference implementation for prompt prefill (sequential loop). + Supports both scalar and vectorized gating. + + Shapes: + - q, k: [B, T, Hk, Dk] + - v: [B, T, Hv, Dv] + - g: [B, T, Hv] (scalar) or [B, T, Hv, Dk] (vectorized) + - beta: [B, T, Hv] + - state: [B, Hv, Dv, Dk] + Returns: + - y: [B, T, Hv, Dv] + - state: [B, Hv, Dv, Dk] + """ + B, T, Hk, Dk = q.shape + Hv, Dv = v.shape[-2:] + if state is None: + state = mx.zeros((B, Hv, Dv, Dk), dtype=mx.float32) + + if (repeat_factor := Hv // Hk) > 1: + q = mx.repeat(q, repeat_factor, -2) + k = mx.repeat(k, repeat_factor, -2) + + ys = [] + for t in range(T): + y, state = _gated_delta_step_ops( + q[:, t], + k[:, t], + v[:, t], + g[:, t], + beta[:, t], + state, + None if mask is None else mask[:, t], + ) + ys.append(y) + y = mx.stack(ys, axis=1) + return y, state + + +def gated_delta_update( + q: mx.array, + k: mx.array, + v: mx.array, + a: mx.array, + b: mx.array, + A_log: mx.array, + dt_bias: mx.array, + state: Optional[mx.array] = None, + mask: Optional[mx.array] = None, + use_kernel: bool = True, + lower_bound: Optional[float] = None, +) -> Tuple[mx.array, mx.array]: + beta = mx.sigmoid(b) + if lower_bound is None: + g = compute_g(A_log, a, dt_bias) + else: + g = compute_g_safe(A_log, a, dt_bias, lower_bound) + if state is None: + B, _, Hk, Dk = q.shape + Hv, Dv = v.shape[-2:] + state = mx.zeros((B, Hv, Dv, Dk), dtype=mx.float32) + + if ( + not use_kernel + or mx.default_device() != mx.gpu + or not mx.metal.is_available() + or k.shape[-1] < 32 + or k.shape[-1] % 32 != 0 + ): + return gated_delta_ops(q, k, v, g, beta, state, mask) + return gated_delta_kernel(q, k, v, g, beta, state, mask) diff --git a/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/glm5_next.py b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/glm5_next.py new file mode 100644 index 0000000000..a27d8c9646 --- /dev/null +++ b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/glm5_next.py @@ -0,0 +1,177 @@ +import mlx.core as mx +import mlx.nn as nn + +from ..base import InputEmbeddingsFeatures, LanguageModelOutput +from .config import ModelConfig +from .language import LanguageModel +from .vision import VisionModel + + +class Model(nn.Module): + def __init__(self, config: ModelConfig): + super().__init__() + self.config = config + self.model_type = config.model_type + self.language_model = LanguageModel(config.text_config, config) + self.vision_model = ( + VisionModel(config.vision_config) + if config.vision_config is not None + else None + ) + + def encode_image( + self, + pixel_values: mx.array, + image_grid_thw: mx.array | None = None, + **kwargs, + ) -> mx.array: + if self.vision_model is None: + raise ValueError("Vision inputs were provided, but vision_config is None.") + if image_grid_thw is None: + raise ValueError("image_grid_thw is required to encode GLM-5.3 images.") + dtype = self.vision_model.patch_embed.proj.weight.dtype + return self.vision_model(pixel_values.astype(dtype), image_grid_thw) + + @staticmethod + def merge_input_ids_with_image_features( + image_token_id, + video_token_id, + image_features, + inputs_embeds, + input_ids, + ): + image_positions = input_ids == image_token_id + if mx.sum(image_positions) == 0: + image_positions = input_ids == video_token_id + + batch_size, seq_len = input_ids.shape + batch_outputs = [] + feature_start_idx = 0 + + for batch_idx in range(batch_size): + image_mask = image_positions[batch_idx] + num_positions = mx.sum(image_mask).item() + + if num_positions > 0: + batch_features = image_features[ + feature_start_idx : feature_start_idx + num_positions + ] + if batch_features.shape[0] != num_positions: + raise ValueError( + f"Number of image token positions ({num_positions}) does not match " + f"number of image features ({batch_features.shape[0]}) for batch {batch_idx}" + ) + cumsum = mx.cumsum(image_mask.astype(mx.int32)) + feature_indices = mx.where(image_mask, cumsum - 1, 0) + gathered_features = batch_features[feature_indices] + image_mask_expanded = mx.expand_dims(image_mask, axis=-1) + batch_output = mx.where( + image_mask_expanded, gathered_features, inputs_embeds[batch_idx] + ) + feature_start_idx += num_positions + else: + batch_output = inputs_embeds[batch_idx] + + batch_outputs.append(batch_output) + + return mx.stack(batch_outputs, axis=0) + + def get_input_embeddings( + self, + input_ids: mx.array | None = None, + pixel_values: mx.array | None = None, + **kwargs, + ) -> InputEmbeddingsFeatures: + inputs_embeds = self.language_model.model.embed_tokens(input_ids) + + if pixel_values is None: + return InputEmbeddingsFeatures(inputs_embeds=inputs_embeds) + + if self.vision_model is None: + raise ValueError("Vision inputs were provided, but vision_config is None.") + + image_grid_thw = kwargs.get("image_grid_thw") + video_grid_thw = kwargs.get("video_grid_thw") + grid_thw = image_grid_thw if image_grid_thw is not None else video_grid_thw + + hidden_states = kwargs.get("cached_image_features") + if hidden_states is None: + hidden_states = self.encode_image( + pixel_values, + image_grid_thw=grid_thw, + ) + + final_inputs_embeds = self.merge_input_ids_with_image_features( + self.config.image_token_id, + self.config.video_token_id, + hidden_states, + inputs_embeds, + input_ids, + ) + return InputEmbeddingsFeatures(inputs_embeds=final_inputs_embeds) + + def __call__( + self, + input_ids: mx.array, + pixel_values: mx.array | None = None, + mask: mx.array | None = None, + cache=None, + **kwargs, + ) -> LanguageModelOutput: + features = self.get_input_embeddings(input_ids, pixel_values, **kwargs) + return self.language_model( + input_ids, + inputs_embeds=features.inputs_embeds, + mask=mask, + cache=cache, + ) + + def sanitize(self, weights): + # HF container: Glm5NextForConditionalGeneration -> model.{visual,language_model} + lm_head + remapped = {} + for k, v in weights.items(): + nk = k + if nk.startswith("model.visual."): + nk = "vision_model." + nk[len("model.visual.") :] + elif nk.startswith("visual."): + nk = "vision_model." + nk[len("visual.") :] + elif nk.startswith("model.language_model."): + nk = "language_model.model." + nk[len("model.language_model.") :] + elif nk.startswith("lm_head."): + nk = "language_model." + nk + remapped[nk] = v + + lang, vis, other = {}, {}, {} + for k, v in remapped.items(): + if k.startswith("language_model."): + lang[k[len("language_model.") :]] = v + elif k.startswith("vision_model."): + vis[k[len("vision_model.") :]] = v + else: + other[k] = v + + lang = self.language_model.sanitize(lang) + if self.vision_model is not None: + vis = self.vision_model.sanitize(vis) + else: + vis = VisionModel.sanitize(vis) + + out = {f"language_model.{k}": v for k, v in lang.items()} + out.update({f"vision_model.{k}": v for k, v in vis.items()}) + out.update(other) + return out + + @property + def layers(self): + return self.language_model.model.layers + + @property + def quant_predicate(self): + return self.language_model.quant_predicate + + @property + def cast_predicate(self): + return self.language_model.cast_predicate + + def make_cache(self): + return self.language_model.make_cache() diff --git a/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/language.py b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/language.py new file mode 100644 index 0000000000..593bcd9f54 --- /dev/null +++ b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/language.py @@ -0,0 +1,1006 @@ +import logging +from typing import Any, Optional + +import mlx.core as mx +import mlx.nn as nn + +from ..base import ( + LanguageModelOutput, + create_attention_mask, + create_ssm_mask, + scaled_dot_product_attention, +) +from ..cache import ArraysCache, CacheList, KVCache +from ..deepseek_v4.hyper_connection import HyperConnection, hc_expand +from mlx_lm.models.mla import MultiLinear +from omlx.patches.deepseek_v4.switch_layers import SwitchGLU +from omlx.patches.glm_moe_dsa.deepseek_v32 import ( + Model as DSV32Model, + group_expert_select, +) +from omlx.patches.glm_moe_dsa.sparse_mla import ( + exact_block_token_attention, + q8_vup_flat, + sparse_mla_attention, +) +from .config import ModelConfig, TextConfig +from .gated_delta import gated_delta_update +from .linear import fused_quantized_matmul, linear_forward + +logger = logging.getLogger(__name__) +_NATIVE_INDEXER_WARNED = False + + +def glm5_next_cast_predicate(key: str) -> bool: + """Keep numerically sensitive GLM-5.3 parameters in FP32.""" + return not ( + "e_score_correction_bias" in key + or ".attn_hc." in key + or ".ffn_hc." in key + or key.endswith("A_log") + or key.endswith("dt_bias") + or key.endswith("mlp.gate.weight") + ) + + +class Glm5NextRMSNormGated(nn.Module): + def __init__(self, hidden_size: int, eps: float = 1e-6): + super().__init__() + self.eps = eps + self.weight = mx.ones(hidden_size) + + def __call__(self, hidden_states: mx.array, gate: mx.array) -> mx.array: + dt = hidden_states.dtype + x = hidden_states.astype(mx.float32) + var = (x * x).mean(-1, keepdims=True) + x = x * mx.rsqrt(var + self.eps) + x = self.weight.astype(mx.float32) * x + x = x * mx.sigmoid(gate.astype(mx.float32)) + return x.astype(dt) + + +class Glm5NextForgetGate(nn.Module): + def __init__(self, config: TextConfig): + super().__init__() + self.head_dim = config.linear_head_dim + self.num_heads = config.linear_num_heads + self.qkv_dim = self.head_dim * self.num_heads + self.f_a_proj = nn.Linear(config.hidden_size, self.head_dim, bias=False) + self.f_b_proj = nn.Linear(self.head_dim, self.qkv_dim, bias=False) + self.dt_bias = mx.zeros(self.qkv_dim) + self.A_log = mx.zeros(self.num_heads) + self.safe_gate_lower_bound = config.linear_lower_bound + + def __call__(self, hidden_states: mx.array) -> mx.array: + B, S, _ = hidden_states.shape + fg = self.f_b_proj(self.f_a_proj(hidden_states)) + g = (fg.astype(mx.float32) + self.dt_bias.astype(mx.float32)).reshape( + B, S, self.num_heads, self.head_dim + ) + decay = mx.exp(self.A_log.astype(mx.float32)).reshape(1, 1, self.num_heads, 1) + if self.safe_gate_lower_bound is not None: + return self.safe_gate_lower_bound * mx.sigmoid(decay * g) + g_softplus = mx.where(g > 20.0, g, mx.log(1.0 + mx.exp(g))) + return -decay * g_softplus + + +def _l2norm(x: mx.array, eps: float = 1e-6) -> mx.array: + return x * mx.rsqrt((x * x).sum(axis=-1, keepdims=True) + eps) + + +def recurrent_kimi_delta( + query: mx.array, + key: mx.array, + value: mx.array, + g: mx.array, + beta: mx.array, + state: Optional[mx.array] = None, +): + # Reference O(S) recurrence for Kimi Delta Attention, kept as the readable + # spec and the equivalence oracle for tests. The forward path runs this on + # the shared fused gated_delta kernel (see Glm5NextLinearAttention). + dt = query.dtype + query = _l2norm(query.astype(mx.float32)) + key = _l2norm(key.astype(mx.float32)) + value = value.astype(mx.float32) + g = g.astype(mx.float32) + beta = beta.astype(mx.float32) + B, S, H, Dk = key.shape + Dv = value.shape[-1] + query = query * (Dk**-0.5) + if state is None: + state = mx.zeros((B, H, Dk, Dv), dtype=mx.float32) + else: + state = state.astype(mx.float32) + outs = [] + for i in range(S): + q_i = query[:, i] + k_i = key[:, i] + v_i = value[:, i] + g_i = mx.exp(g[:, i])[..., None] + b_i = beta[:, i][..., None] + state = state * g_i + kv_mem = (state * k_i[..., None]).sum(axis=-2) + delta = (v_i - kv_mem) * b_i + state = state + k_i[..., None] * delta[..., None, :] + out_i = (state * q_i[..., None]).sum(axis=-2) + outs.append(out_i) + out = mx.stack(outs, axis=1).astype(dt) + return out, state + + +class Glm5NextLinearAttention(nn.Module): + def __init__(self, config: TextConfig): + super().__init__() + self.hidden_size = config.hidden_size + self.num_heads = config.linear_num_heads + self.head_dim = config.linear_head_dim + self.qkv_dim = self.num_heads * self.head_dim + self.conv_kernel_size = config.linear_conv_kernel_dim + + self.q_proj = nn.Linear(self.hidden_size, self.qkv_dim, bias=False) + self.k_proj = nn.Linear(self.hidden_size, self.qkv_dim, bias=False) + self.v_proj = nn.Linear(self.hidden_size, self.qkv_dim, bias=False) + + self.conv_dim = self.qkv_dim * 3 + self.conv1d = nn.Conv1d( + in_channels=self.conv_dim, + out_channels=self.conv_dim, + bias=False, + kernel_size=self.conv_kernel_size, + groups=self.conv_dim, + padding=0, + ) + + self.forget_gate = Glm5NextForgetGate(config) + self.b_proj = nn.Linear(self.hidden_size, self.num_heads, bias=False) + self.g_a_proj = nn.Linear(self.hidden_size, self.head_dim, bias=False) + self.g_b_proj = nn.Linear(self.head_dim, self.qkv_dim, bias=False) + self.o_norm = Glm5NextRMSNormGated(self.head_dim, eps=config.rms_norm_eps) + self.o_proj = nn.Linear(self.qkv_dim, self.hidden_size, bias=False) + self.fuse_in = True + self._fused_ready = False + + def _fused_in_proj(self, inputs): + # q,k,v,f_a,g_a,b all take `inputs`; fuse into one matmul via a lossless + # output-axis concat of the (quantized) weights, built once and cached. + if not self._fused_ready: + mods = [ + self.q_proj, + self.k_proj, + self.v_proj, + self.forget_gate.f_a_proj, + self.g_a_proj, + self.b_proj, + ] + quantized = [hasattr(m, "scales") for m in mods] + if any(quantized) and not all(quantized): + return tuple(linear_forward(m, inputs) for m in mods) + if all(quantized): + specs = { + (m.group_size, m.bits, getattr(m, "mode", "affine")) for m in mods + } + if len(specs) != 1: + return tuple(linear_forward(m, inputs) for m in mods) + pts, acc = [], 0 + for m in mods[:-1]: + acc += m.weight.shape[0] + pts.append(acc) + self._split_pts = pts + self._fq = hasattr(mods[0], "scales") + self._fw = mx.concatenate([m.weight for m in mods], axis=0) + if self._fq: + self._fs = mx.concatenate([m.scales for m in mods], axis=0) + self._fb = mx.concatenate([m.biases for m in mods], axis=0) + self._gs, self._bits = mods[0].group_size, mods[0].bits + self._fused_ready = True + if self._fq: + out = fused_quantized_matmul( + inputs, + self._fw, + self._fs, + self._fb, + bits=self._bits, + group_size=self._gs, + ) + else: + out = inputs @ self._fw.T + return mx.split(out, self._split_pts, axis=-1) + + def __call__( + self, + inputs: mx.array, + mask: Optional[mx.array] = None, + cache: Optional[Any] = None, + ) -> mx.array: + B, S, _ = inputs.shape + if self.fuse_in: + q_o, k_o, v_o, fa_o, ga_o, b_o = self._fused_in_proj(inputs) + mixed = mx.concatenate([q_o, k_o, v_o], axis=-1) + else: + mixed = mx.concatenate( + [self.q_proj(inputs), self.k_proj(inputs), self.v_proj(inputs)], axis=-1 + ) + fa_o = self.forget_gate.f_a_proj(inputs) + ga_o = self.g_a_proj(inputs) + b_o = self.b_proj(inputs) + if mask is not None and mask.dtype == mx.bool_: + mixed = mx.where(mask[..., None], mixed, 0) + + if cache is not None and cache[0] is not None: + conv_state = cache[0] + else: + conv_state = mx.zeros( + (B, self.conv_kernel_size - 1, self.conv_dim), dtype=inputs.dtype + ) + conv_input = mx.concatenate([conv_state, mixed], axis=1) + if cache is not None: + cache[0] = mx.contiguous(conv_input[:, -(self.conv_kernel_size - 1) :, :]) + conv_out = nn.silu(self.conv1d(conv_input)) + + q, k, v = mx.split(conv_out, [self.qkv_dim, 2 * self.qkv_dim], axis=-1) + q = q.reshape(B, S, self.num_heads, self.head_dim) + k = k.reshape(B, S, self.num_heads, self.head_dim) + v = v.reshape(B, S, self.num_heads, self.head_dim) + + fg = self.forget_gate + a = linear_forward(fg.f_b_proj, fa_o).reshape( + B, S, self.num_heads, self.head_dim + ) + in_dtype = q.dtype + q = (_l2norm(q.astype(mx.float32)) * (self.head_dim**-0.5)).astype(in_dtype) + k = _l2norm(k.astype(mx.float32)).astype(in_dtype) + + state = cache[1] if cache is not None else None + out, state = gated_delta_update( + q, + k, + v, + a, + b_o, + fg.A_log.reshape(self.num_heads, 1), + fg.dt_bias.reshape(self.num_heads, self.head_dim), + state=state, + mask=mask if mask is not None and mask.dtype == mx.bool_ else None, + lower_bound=fg.safe_gate_lower_bound, + ) + if cache is not None: + cache[1] = state + cache.advance(S) + + gate = linear_forward(self.g_b_proj, ga_o).reshape( + B, S, self.num_heads, self.head_dim + ) + out = self.o_norm(out, gate).reshape(B, S, -1) + return linear_forward(self.o_proj, out) + + +class Glm5NextIndexer(nn.Module): + def __init__(self, args: TextConfig): + super().__init__() + self.dim = args.hidden_size + self.n_heads = args.index_n_heads + self.head_dim = args.index_head_dim + self.index_topk = args.index_topk + self.index_kpool = args.index_kpool + self.index_kpool_always_select_tail = args.index_kpool_always_select_tail + self.q_lora_rank = args.q_lora_rank + self.wq_b = nn.Linear( + self.q_lora_rank, self.n_heads * self.head_dim, bias=False + ) + self.wk = nn.Linear(self.dim, self.head_dim, bias=False) + self.k_norm = nn.LayerNorm(self.head_dim, eps=1e-6) + self.weights_proj = nn.Linear(self.dim, self.n_heads, bias=False) + self.softmax_scale = self.head_dim**-0.5 + self.weight_scale = self.n_heads**-0.5 * self.softmax_scale + self.index_kpool_compress_ape = mx.zeros((self.index_kpool, self.head_dim)) + self.index_kpool_compress_gate = mx.zeros((self.head_dim, self.dim)) + + def _compress_windows(self, keys, gate_scores): + B, S, hd = keys.shape + kp = self.index_kpool + if S == 0: + return mx.zeros((B, 0, hd), dtype=keys.dtype) + usable = (S // kp) * kp + keys = keys[:, :usable].reshape(B, -1, kp, hd) + gate_scores = gate_scores[:, :usable].reshape(B, -1, kp, hd) + logits = gate_scores + self.index_kpool_compress_ape[None, None] + probs = mx.softmax(logits, axis=2) + return mx.sum(probs * keys, axis=2) + + @staticmethod + def _processed(cache): + processed = getattr(cache, "_processed", None) + if processed is not None: + return list(processed) + return int(cache.size() * cache.ratio + cache.remainder) + + @staticmethod + def _pool_lengths(cache): + lengths = getattr(cache, "_pool_lengths", None) + if lengths is not None: + return list(lengths) + return int(cache.size()) + + def _native_scores(self, q, pool_keys, weights): + global _NATIVE_INDEXER_WARNED + if ( + q.shape[2] != self.n_heads + or self.n_heads != 32 + or self.head_dim != 128 + or q.dtype not in (mx.float16, mx.bfloat16) + or pool_keys.dtype != q.dtype + ): + return None + try: + from omlx.custom_kernels.glm_moe_dsa import fast + + if not fast.has_symbol("dsa_indexer_scores"): + return None + qt = q.transpose(0, 2, 1, 3) + keys = pool_keys[:, None] + q_pad = (-qt.shape[2]) % 64 + k_pad = (-keys.shape[2]) % 64 + if q_pad: + qt = mx.pad(qt, [(0, 0), (0, 0), (0, q_pad), (0, 0)]) + weights = mx.pad(weights, [(0, 0), (0, q_pad), (0, 0)]) + if k_pad: + keys = mx.pad(keys, [(0, 0), (0, 0), (0, k_pad), (0, 0)]) + scores = fast.dsa_indexer_scores( + qt, + keys, + weights, + causal=False, + ) + return scores[:, 0, : q.shape[1], : pool_keys.shape[1]] + except (AttributeError, RuntimeError, TypeError, ValueError): + if not _NATIVE_INDEXER_WARNED: + logger.warning( + "GLM-5.3 native DSA indexer failed; using the MLX fallback", + exc_info=True, + ) + _NATIVE_INDEXER_WARNED = True + return None + + @staticmethod + def _native_topk(scores, topk): + if topk != 512: + return None + try: + from omlx.custom_kernels.glm_moe_dsa import fast + + if fast.has_symbol("dsa_topk_indices"): + return fast.dsa_topk_indices(scores[:, None], topk)[:, 0] + except (AttributeError, RuntimeError, TypeError, ValueError): + pass + return None + + def __call__(self, x, qr, mask, cache=None, kv_cache=None): + B, S, _ = x.shape + q = linear_forward(self.wq_b, qr).reshape(B, S, self.n_heads, self.head_dim) + k = self.k_norm(linear_forward(self.wk, x)).reshape(B, S, self.head_dim) + gate_scores = x @ self.index_kpool_compress_gate.swapaxes(-1, -2) + + if cache is not None: + before = self._processed(cache) + cache_offset = ( + mx.array(before, dtype=mx.int32) if isinstance(before, list) else before + ) + ready_k, ready_gate, _ = cache.accumulate_windows( + k, gate_scores, cache_offset + ) + compressed = self._compress_windows(ready_k, ready_gate) + pool_keys = cache.update_and_fetch(compressed) + after = self._processed(cache) + pool_lengths = self._pool_lengths(cache) + if isinstance(after, list): + before_a = mx.array(before, dtype=mx.int32) + valid_lengths = mx.array( + [a - b for a, b in zip(after, before)], dtype=mx.int32 + ) + valid_cur = mx.arange(S)[None] < valid_lengths[:, None] + total_max = max(after) + else: + before_a = mx.full((B,), before, dtype=mx.int32) + valid_cur = mx.ones((B, S), dtype=mx.bool_) + total_max = after + else: + before_a = mx.zeros((B,), dtype=mx.int32) + valid_cur = mx.ones((B, S), dtype=mx.bool_) + usable = (S // self.index_kpool) * self.index_kpool + pool_keys = self._compress_windows(k[:, :usable], gate_scores[:, :usable]) + pool_lengths = usable // self.index_kpool + total_max = S + + # The pool has already advanced, even when sparse selection is unnecessary. + if getattr(self, "bypass_short", True) and total_max <= self.index_topk: + return None + + P = pool_keys.shape[1] + select_k = min(self.index_topk // self.index_kpool, P) + pool_idx = mx.arange(P) + pool_end = (pool_idx + 1) * self.index_kpool - 1 + if isinstance(pool_lengths, list): + pool_lengths_a = mx.array(pool_lengths, dtype=mx.int32) + else: + pool_lengths_a = mx.full((B,), pool_lengths, dtype=mx.int32) + left_padding = getattr(kv_cache, "left_padding", None) + if left_padding is None: + left_padding = mx.zeros((B,), dtype=mx.int32) + tail_on = self.index_kpool_always_select_tail and self.index_kpool > 1 + output_width = self.index_topk + (self.index_kpool - 1 if tail_on else 0) + + chunk = 512 if S > 512 else S + out = [] + for c0 in range(0, S, chunk): + c1 = min(c0 + chunk, S) + cs = c1 - c0 + q_chunk = q[:, c0:c1] + weights = linear_forward(self.weights_proj, x[:, c0:c1]) + weights = (weights * self.weight_scale).astype(q_chunk.dtype) + index_scores = self._native_scores(q_chunk, pool_keys, weights) + if index_scores is None: + head_scores = q_chunk @ pool_keys[:, None].swapaxes(-1, -2) + index_scores = mx.sum( + weights[..., None] + * mx.maximum(head_scores, mx.array(0, head_scores.dtype)), + axis=2, + ) + query_pos = before_a[:, None] + mx.arange(c0, c1)[None] + valid_candidates = ( + pool_idx[None, None] < pool_lengths_a[:, None, None] + ) & (pool_end[None, None] <= query_pos[..., None]) + index_scores = mx.where(valid_candidates, index_scores, -1e30) + selected = self._native_topk(index_scores, select_k) + if selected is None: + selected = mx.argpartition(-index_scores, kth=select_k - 1, axis=-1)[ + ..., :select_k + ] + selected_valid = mx.take_along_axis(valid_candidates, selected, axis=-1) + selected_indices = ( + selected[..., None] * self.index_kpool + + mx.arange(self.index_kpool)[None, None, None] + + left_padding[:, None, None, None] + ) + topk = selected_indices.reshape(B, cs, -1) + sv = mx.broadcast_to( + selected_valid[..., None], (B, cs, select_k, self.index_kpool) + ).reshape(B, cs, -1) + topk = mx.where(sv, topk, -1) + if tail_on: + tail_width = self.index_kpool - 1 + tail_count = (query_pos + 1) % self.index_kpool + tail_start = query_pos + 1 - tail_count + tail_offsets = mx.arange(tail_width) + tail = tail_start[..., None] + tail_offsets + tail_valid = tail_offsets[None, None] < tail_count[..., None] + tail = tail + left_padding[:, None, None] + topk = mx.concatenate([topk, mx.where(tail_valid, tail, -1)], axis=-1) + if topk.shape[-1] < output_width: + pad = mx.full( + (B, cs, output_width - topk.shape[-1]), -1, dtype=topk.dtype + ) + topk = mx.concatenate([topk, pad], axis=-1) + topk = topk[..., :output_width] + topk = mx.where(valid_cur[:, c0:c1][..., None], topk, -1) + out.append(topk) + topk = out[0] if len(out) == 1 else mx.concatenate(out, axis=1) + return topk[:, None].astype(mx.int32) + + +class Glm5NextSparseAttention(nn.Module): + def __init__(self, config: TextConfig): + super().__init__() + self.config = config + self.hidden_size = config.hidden_size + self.num_heads = config.num_attention_heads + self.q_lora_rank = config.q_lora_rank + self.qk_rope_head_dim = config.qk_rope_head_dim + self.kv_lora_rank = config.kv_lora_rank + self.v_head_dim = config.v_head_dim + self.qk_nope_head_dim = config.qk_nope_head_dim + self.use_nope = config.mla_use_nope or config.qk_rope_head_dim == 0 + # GLM-5-Next is NoPE by design (qk_rope_head_dim=0, mla_use_nope=True); the + # config carries no rope parameters. Fail loudly rather than run wrong math + # if a future config ever requests a RoPE MLA. + if not self.use_nope: + raise NotImplementedError( + "glm5_next implements NoPE MLA only; qk_rope_head_dim>0 with " + "mla_use_nope=False is not supported." + ) + self.q_head_dim = config.qk_nope_head_dim + self.scale = self.q_head_dim**-0.5 + + self.q_a_proj = nn.Linear( + self.hidden_size, self.q_lora_rank, bias=config.attention_bias + ) + self.q_a_layernorm = nn.RMSNorm(self.q_lora_rank, eps=config.rms_norm_eps) + self.q_b_proj = nn.Linear( + self.q_lora_rank, self.num_heads * self.q_head_dim, bias=False + ) + self.kv_a_proj_with_mqa = nn.Linear( + self.hidden_size, self.kv_lora_rank, bias=config.attention_bias + ) + self.kv_a_layernorm = nn.RMSNorm(self.kv_lora_rank, eps=config.rms_norm_eps) + self.embed_q = MultiLinear( + self.qk_nope_head_dim, self.kv_lora_rank, self.num_heads + ) + self.unembed_out = MultiLinear( + self.kv_lora_rank, self.v_head_dim, self.num_heads + ) + self.o_proj = nn.Linear( + self.num_heads * self.v_head_dim, + self.hidden_size, + bias=config.attention_bias, + ) + self.indexer = Glm5NextIndexer(config) + + def __call__( + self, + x: mx.array, + mask: Optional[mx.array] = None, + cache: Optional[Any] = None, + ) -> mx.array: + B, L, D = x.shape + + qr = self.q_a_layernorm(linear_forward(self.q_a_proj, x)) + q = linear_forward(self.q_b_proj, qr) + q = q.reshape(B, L, self.num_heads, self.q_head_dim).transpose(0, 2, 1, 3) + + compressed_kv = linear_forward(self.kv_a_proj_with_mqa, x) + kv_latent = self.kv_a_layernorm(compressed_kv) + kv_latent = mx.expand_dims(kv_latent, axis=1) + + if cache is not None: + # NoPE attention only needs the latent once. A zero-width value + # cache avoids storing a duplicate 512-wide tensor per sparse + # layer while retaining the standard KVCache lifecycle. + empty_values = mx.zeros((B, 1, L, 0), dtype=kv_latent.dtype) + kv_latent, _ = cache[0].update_and_fetch(kv_latent, empty_values) + else: + cache = [None] * 2 + + topk_indices = self.indexer( + x, + qr, + mask, + cache=cache[1], + kv_cache=cache[0], + ) + attn_mask = mask + if topk_indices is not None: + Kv = kv_latent.shape[2] + valid_sel = topk_indices >= 0 + if L == 1: + clamped = mx.clip(topk_indices[:, :, 0, :], 0, Kv - 1) + idx = clamped[..., None] + kv_latent = mx.take_along_axis( + kv_latent, + mx.broadcast_to(idx, idx.shape[:-1] + (kv_latent.shape[-1],)), + axis=2, + ) + sel_mask = valid_sel[:, :, 0, :][:, :, None, :] + if mask is not None and mask.dtype == mx.bool_: + # Single-stream decode passes mask=None here; under continuous + # batching the batched cache supplies a left-pad mask that can be + # 4-D ([B, 1, 1, Kv]) while `clamped` is 3-D. At S=1 the mask is + # purely per-key (no causal), so reduce it to [B, Kv] and gather the + # selected key positions -- rank-agnostic and batch-safe. + mkeys = mask.reshape(B, -1, Kv)[:, 0, :] + gathered = mx.take_along_axis( + mx.broadcast_to(mkeys[:, None, :], (B, clamped.shape[1], Kv)), + clamped, + axis=-1, + ) + sel_mask = sel_mask & gathered[:, :, None, :] + attn_mask = sel_mask + elif L <= 8: + return self._gathered_attention(q, kv_latent, topk_indices) + else: + q_latent = self.embed_q(q) + q_pe = mx.zeros(q_latent.shape[:-1] + (64,), dtype=q_latent.dtype) + k_pe = mx.zeros(kv_latent.shape[:-1] + (64,), dtype=kv_latent.dtype) + output = None + if Kv >= 4096: + output = sparse_mla_attention( + q_latent, + q_pe, + kv_latent, + k_pe, + topk_indices, + self.scale, + ) + if output is not None: + output_flat = q8_vup_flat( + output, + self.unembed_out, + key_length=Kv, + ) + if output_flat is None: + output = self.unembed_out(output) + output_flat = output.transpose(0, 2, 1, 3).reshape(B, L, -1) + return linear_forward(self.o_proj, output_flat) + + k = self.embed_q(kv_latent, transpose=False) + v = self.unembed_out(kv_latent) + output = exact_block_token_attention( + q, + k, + v, + topk_indices, + self.scale, + ) + if output is not None: + output = output.transpose(0, 2, 1, 3).reshape(B, L, -1) + return linear_forward(self.o_proj, output) + + shape = list(topk_indices.shape) + shape[-1] = Kv + 1 + safe_idx = mx.where(valid_sel, topk_indices, Kv) + sparse_mask = mx.zeros(shape, dtype=mx.bool_) + sparse_mask = mx.put_along_axis( + sparse_mask, safe_idx, mx.array(True), axis=-1 + )[..., :Kv] + if mask is not None and mask.dtype == mx.bool_: + sparse_mask = sparse_mask & mask + attn_mask = sparse_mask + + if ( + cache is not None + and cache[0] is not None + and cache[1] is not None + and cache[1].pooled is not None + ): + deps = tuple(v for v in cache[1].state if isinstance(v, mx.array)) + if deps: + cache[0].keys = mx.depends(cache[0].keys, deps) + + if L == 1: + q = self.embed_q(q) + k = v = kv_latent + else: + k = self.embed_q(kv_latent, transpose=False) + v = self.unembed_out(kv_latent) + + output = scaled_dot_product_attention( + q, k, v, cache=cache, scale=self.scale, mask=attn_mask + ) + if L == 1: + output = self.unembed_out(output) + + output = output.transpose(0, 2, 1, 3).reshape(B, L, -1) + return linear_forward(self.o_proj, output) + + def _gathered_attention(self, q, kv_latent, topk_indices): + B, H, L, _ = q.shape + Kv = kv_latent.shape[2] + dim = kv_latent.shape[-1] + selected = topk_indices[:, 0] + topk = selected.shape[-1] + clamped = mx.clip(selected, 0, Kv - 1) + gathered = mx.take_along_axis( + mx.broadcast_to(kv_latent[:, 0, None], (B, L, Kv, dim)), + mx.broadcast_to(clamped[..., None], (B, L, topk, dim)), + axis=2, + ) + q_latent = self.embed_q(q).transpose(0, 2, 1, 3).reshape(B * L, H, 1, dim) + gathered = gathered.reshape(B * L, 1, topk, dim) + valid = (selected >= 0).reshape(B * L, 1, 1, topk) + output = scaled_dot_product_attention( + q_latent, + gathered, + gathered, + cache=None, + scale=self.scale, + mask=valid, + ) + output = output.reshape(B, L, H, dim).transpose(0, 2, 1, 3) + output = self.unembed_out(output).transpose(0, 2, 1, 3).reshape(B, L, -1) + return linear_forward(self.o_proj, output) + + +class Glm5NextClampedSwiGLU(nn.Module): + def __init__(self, limit: Optional[float]): + super().__init__() + self.limit = limit + + def __call__(self, x_up: mx.array, x_gate: mx.array) -> mx.array: + if self.limit is not None: + x_gate = mx.clip(x_gate, a_min=None, a_max=self.limit) + x_up = mx.clip(x_up, a_min=-self.limit, a_max=self.limit) + return nn.silu(x_gate) * x_up + + +class Glm5NextMLP(nn.Module): + def __init__(self, config, intermediate_size=None): + super().__init__() + intermediate_size = intermediate_size or config.intermediate_size + self.limit = config.swiglu_limit + self.gate_proj = nn.Linear(config.hidden_size, intermediate_size, bias=False) + self.up_proj = nn.Linear(config.hidden_size, intermediate_size, bias=False) + self.down_proj = nn.Linear(intermediate_size, config.hidden_size, bias=False) + + def __call__(self, x: mx.array) -> mx.array: + gate = linear_forward(self.gate_proj, x) + up = linear_forward(self.up_proj, x) + if self.limit is not None: + gate = mx.clip(gate, a_min=None, a_max=self.limit) + up = mx.clip(up, a_min=-self.limit, a_max=self.limit) + return linear_forward(self.down_proj, nn.silu(gate) * up) + + +class Glm5NextMoEGate(nn.Module): + def __init__(self, config): + super().__init__() + self.top_k = config.num_experts_per_tok + self.norm_topk_prob = config.norm_topk_prob + self.n_group = config.n_group + self.topk_group = config.topk_group + self.routed_scaling_factor = config.routed_scaling_factor + self.weight = mx.zeros((config.n_routed_experts, config.hidden_size)) + self.e_score_correction_bias = mx.zeros((config.n_routed_experts,)) + + def __call__(self, x): + logits = x.astype(mx.float32) @ self.weight.astype(mx.float32).T + return group_expert_select( + logits, + self.e_score_correction_bias, + self.top_k, + self.n_group, + self.topk_group, + self.routed_scaling_factor, + self.norm_topk_prob, + ) + + +class Glm5NextMoE(nn.Module): + def __init__(self, config): + super().__init__() + self.switch_mlp = SwitchGLU( + config.hidden_size, + config.moe_intermediate_size, + config.n_routed_experts, + activation=Glm5NextClampedSwiGLU(config.swiglu_limit), + ) + self.gate = Glm5NextMoEGate(config) + self.shared_experts = None + if config.n_shared_experts is not None: + self.shared_experts = Glm5NextMLP( + config, + intermediate_size=( + config.moe_intermediate_size * config.n_shared_experts + ), + ) + + def __call__(self, x): + indices, scores = self.gate(x) + y = self.switch_mlp(x, indices, scores=scores, weighted_sum=True) + if y.ndim == x.ndim + 1: + y = (y * scores[..., None]).sum(axis=-2).astype(x.dtype) + if self.shared_experts is not None: + y = y + self.shared_experts(x) + return y + + +class Glm5NextDecoderLayer(nn.Module): + def __init__(self, config: TextConfig, layer_idx: int): + super().__init__() + layer_type = config.layer_types[layer_idx] + self.is_linear = layer_type == "linear_attention" + if self.is_linear: + self.self_attn = Glm5NextLinearAttention(config) + else: + self.self_attn = Glm5NextSparseAttention(config) + + is_sparse = ( + config.n_routed_experts is not None + and layer_idx >= config.first_k_dense_replace + and config.mlp_layer_types[layer_idx] == "sparse" + ) + self.mlp = Glm5NextMoE(config) if is_sparse else Glm5NextMLP(config) + + self.input_layernorm = nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.post_attention_layernorm = nn.RMSNorm( + config.hidden_size, eps=config.rms_norm_eps + ) + self.attn_hc = HyperConnection(config) + self.ffn_hc = HyperConnection(config) + self.compile_ffn = True + self._ffn_c = None + + def __call__( + self, + x: mx.array, + mask: Optional[mx.array] = None, + cache: Optional[Any] = None, + ) -> mx.array: + residual = x + xc, post, comb = self.attn_hc(x) + r = self.self_attn(self.input_layernorm(xc), mask, cache) + x = hc_expand(r, residual, post, comb) + # Compile the FFN block only for single-stream decode (B=1, S=1) -- the shape it + # was validated on and where its win lives. Compiling the 288-expert MoE at a + # batched or prefill shape spikes memory (it can OOM alongside the resident + # weights), so those shapes take the eager path. + if self.compile_ffn and x.shape[0] == 1 and x.shape[1] == 1: + if self._ffn_c is None: + self._ffn_c = mx.compile(self._ffn_block) + return self._ffn_c(x) + return self._ffn_block(x) + + def _ffn_block(self, x: mx.array) -> mx.array: + # Stateless FFN half (no cache) -> compiles cleanly at a fixed decode shape. + residual = x + xc, post, comb = self.ffn_hc(x) + m = self.mlp(self.post_attention_layernorm(xc)) + return hc_expand(m, residual, post, comb) + + +class Glm5NextModel(nn.Module): + def __init__(self, config: TextConfig): + super().__init__() + self.config = config + self.hc_mult = config.hc_mult + self.vocab_size = config.vocab_size + self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size) + self.layers = [ + Glm5NextDecoderLayer(config, idx) for idx in range(config.num_hidden_layers) + ] + self.norm = nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.ssm_idx = next((i for i, l in enumerate(self.layers) if l.is_linear), 0) + self.fa_idx = next((i for i, l in enumerate(self.layers) if not l.is_linear), 0) + + def __call__( + self, + inputs: mx.array, + cache: Optional[Any] = None, + inputs_embeds: Optional[mx.array] = None, + ) -> mx.array: + h = self.embed_tokens(inputs) if inputs_embeds is None else inputs_embeds + + if cache is None: + cache = [None] * len(self.layers) + + fa_cache = cache[self.fa_idx] + fa_mask = create_attention_mask( + h, fa_cache[0] if fa_cache else None, return_array=True + ) + ssm_mask = create_ssm_mask(h, cache[self.ssm_idx]) + + h = mx.broadcast_to( + h[:, :, None, :], (h.shape[0], h.shape[1], self.hc_mult, h.shape[2]) + ) + h = mx.contiguous(h) + + for layer, c in zip(self.layers, cache): + mask = ssm_mask if layer.is_linear else fa_mask + h = layer(h, mask=mask, cache=c) + + h = h.mean(axis=2) + return self.norm(h) + + +class LanguageModel(nn.Module): + def __init__(self, args: TextConfig, config: ModelConfig = None): + super().__init__() + self.args = args + self.config = args + self.model_type = args.model_type + self.model = Glm5NextModel(args) + if not args.tie_word_embeddings: + self.lm_head = nn.Linear(args.hidden_size, args.vocab_size, bias=False) + + def __call__( + self, + inputs: Optional[mx.array] = None, + inputs_embeds: Optional[mx.array] = None, + cache: Optional[Any] = None, + mask: Optional[mx.array] = None, + **kwargs, + ) -> LanguageModelOutput: + if inputs is None: + inputs = kwargs.get("input_ids") + out = self.model(inputs, cache=cache, inputs_embeds=inputs_embeds) + # Only the last few positions' logits are ever needed for generation; slicing + # before the (vocab-wide) projection skips it on discarded prefill positions. + nlk = kwargs.get("num_logits_to_keep", 0) + if nlk: + out = out[:, -nlk:, :] + if self.args.tie_word_embeddings: + out = self.model.embed_tokens.as_linear(out) + else: + out = linear_forward(self.lm_head, out) + return LanguageModelOutput(logits=out) + + def sanitize(self, weights): + weights = {k: v for k, v in weights.items() if "mtp." not in k} + weights = DSV32Model.sanitize(self, weights) + + remapped = {} + conv_parts = {} + fg_parts = ("A_log", "dt_bias", "f_a_proj.weight", "f_b_proj.weight") + for k, v in weights.items(): + nk = k.replace(".hc_attn_", ".attn_hc.").replace(".hc_ffn_", ".ffn_hc.") + + fused = False + for part in ("q_conv1d.weight", "k_conv1d.weight", "v_conv1d.weight"): + suffix = ".self_attn." + part + if nk.endswith(suffix): + prefix = nk[: -len(part)] + conv_parts.setdefault(prefix, {})[part[0]] = v + fused = True + break + if fused: + continue + + for p in fg_parts: + suffix = ".self_attn." + p + if nk.endswith(suffix): + nk = nk[: -len(p)] + "forget_gate." + p + break + + remapped[nk] = v + + for prefix, parts in conv_parts.items(): + if all(c in parts for c in ("q", "k", "v")): + remapped[prefix + "conv1d.weight"] = mx.concatenate( + [parts["q"], parts["k"], parts["v"]], axis=0 + ) + else: + for c, w in parts.items(): + remapped[prefix + c + "_conv1d.weight"] = w + + weights = remapped + for k, v in list(weights.items()): + if "conv1d.weight" in k and v.ndim == 3 and v.shape[-1] != 1: + weights[k] = v.moveaxis(2, 1) + for k, v in list(weights.items()): + keep_fp32 = ( + ".attn_hc." in k + or ".ffn_hc." in k + or k.endswith("A_log") + or k.endswith("dt_bias") + or k.endswith("mlp.gate.weight") + or k.endswith("e_score_correction_bias") + ) + if ( + keep_fp32 + and mx.issubdtype(v.dtype, mx.floating) + and v.dtype != mx.float32 + ): + weights[k] = v.astype(mx.float32) + return weights + + @property + def layers(self): + return self.model.layers + + @property + def cast_predicate(self): + return glm5_next_cast_predicate + + @property + def quant_predicate(self): + def predicate(path, _): + if path.endswith("mlp.gate") or "e_score_correction_bias" in path: + return False + if ".indexer" in path: + return {"group_size": 64, "bits": 8} + return True + + return predicate + + def make_cache(self): + caches = [] + for layer in self.layers: + if layer.is_linear: + caches.append(ArraysCache(size=2)) + else: + from mlx_lm.models.cache import PoolingCache + + caches.append( + CacheList( + KVCache(), PoolingCache(layer.self_attn.indexer.index_kpool) + ) + ) + return caches diff --git a/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/linear.py b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/linear.py new file mode 100644 index 0000000000..414e27b83d --- /dev/null +++ b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/linear.py @@ -0,0 +1,108 @@ +"""Model-neutral affine qmm routing for GLM-5.3 projections.""" + +from __future__ import annotations + +import mlx.core as mx +import mlx.nn as nn + + +def _native_qmm(linear: nn.QuantizedLinear, x: mx.array): + bits = int(getattr(linear, "bits", 0) or 0) + group_size = int(getattr(linear, "group_size", 0) or 0) + if bits not in (2, 4, 5, 6, 8) or group_size not in (64, 128): + return None + if getattr(linear, "mode", None) != "affine" or "bias" in linear: + return None + min_tokens = 1024 if bits == 8 else 128 + if x.ndim < 2 or x.shape[-2] < min_tokens: + return None + + try: + from omlx.patches.qwen35_q4_mlp import _is_supported_affine_linear + from omlx.custom_kernels.qwen35_prefill import fast + + name = f"qwen35_q{bits}_affine_qmm_t" + if not fast.has_symbol(name) or not _is_supported_affine_linear(linear, x): + return None + return getattr(fast, name)( + x, + linear.weight, + linear.scales, + linear.biases, + 8, + group_size, + ) + except (AttributeError, RuntimeError, TypeError, ValueError): + return None + + +def linear_forward(linear: nn.Module, x: mx.array) -> mx.array: + """Use oMLX's affine prefill tile when it is supported and profitable.""" + if isinstance(linear, nn.QuantizedLinear): + if ( + "bias" in linear + and getattr(linear, "mode", None) == "affine" + and getattr(linear, "biases", None) is not None + ): + out = fused_quantized_matmul( + x, + linear.weight, + linear.scales, + linear.biases, + bits=int(linear.bits), + group_size=int(linear.group_size), + ) + return out + linear.bias + out = _native_qmm(linear, x) + if out is not None: + return out + return linear(x) + + +def fused_quantized_matmul( + x: mx.array, + weight: mx.array, + scales: mx.array, + biases: mx.array, + *, + bits: int, + group_size: int, +) -> mx.array: + """Route a concatenated projection through the same native affine tile.""" + min_tokens = 1024 if bits == 8 else 128 + if ( + x.ndim >= 2 + and x.shape[-2] >= min_tokens + and bits in (2, 4, 5, 6, 8) + and group_size in (64, 128) + and weight.ndim == scales.ndim == biases.ndim == 2 + and weight.dtype == mx.uint32 + and scales.dtype == x.dtype + and biases.dtype == x.dtype + and weight.shape[0] % 64 == 0 + and x.shape[-1] % 64 == 0 + ): + try: + from omlx.custom_kernels.qwen35_prefill import fast + + name = f"qwen35_q{bits}_affine_qmm_t" + if fast.has_symbol(name) and fast.qmm_supports_group_size(group_size): + return getattr(fast, name)( + x, + weight, + scales, + biases, + 8, + group_size, + ) + except (AttributeError, RuntimeError, TypeError, ValueError): + pass + return mx.quantized_matmul( + x, + weight, + scales, + biases, + transpose=True, + group_size=group_size, + bits=bits, + ) diff --git a/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/processing.py b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/processing.py new file mode 100644 index 0000000000..33219a658c --- /dev/null +++ b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/processing.py @@ -0,0 +1,496 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Torch-free processor support for GLM-5.3-Flash. + +The official checkpoint targets a newer Transformers release than oMLX. This +module mirrors the GLM-5 Next image layout with NumPy and Pillow so image +requests remain available without pulling in torch or torchvision. +""" + +from __future__ import annotations + +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np +from PIL import Image +from transformers import AutoTokenizer +from transformers.feature_extraction_utils import BatchFeature +from transformers.image_processing_utils import ImageProcessingMixin +from transformers.processing_utils import ProcessorMixin + +from ..base import install_auto_processor_patch, load_chat_template, to_mlx + +OPENAI_CLIP_MEAN = (0.48145466, 0.4578275, 0.40821073) +OPENAI_CLIP_STD = (0.26862954, 0.26130258, 0.27577711) + +_IMAGE_KWARGS = { + "do_convert_rgb", + "do_normalize", + "do_rescale", + "image_mean", + "image_std", + "max_image_tokens", + "merge_size", + "min_image_tokens", + "patch_expand_factor", + "patch_size", + "rescale_factor", + "temporal_patch_size", +} + + +def smart_resize( + num_frames: int, + height: int, + width: int, + *, + temporal_factor: int = 2, + factor: int = 28, + min_image_tokens: int = 16, + max_image_tokens: int = 8000, +) -> tuple[int, int]: + """Return GLM's aligned canvas dimensions for an image or video.""" + if num_frames <= 0 or height <= 0 or width <= 0: + raise ValueError("Image dimensions and frame count must be positive.") + + pixels_per_token = temporal_factor * factor**2 + min_pixels = min_image_tokens * pixels_per_token + max_pixels = max_image_tokens * pixels_per_token + + def align(value: int) -> int: + return math.ceil(value / factor) * factor + + aligned_frames = max( + temporal_factor, + round(num_frames / temporal_factor) * temporal_factor, + ) + aligned_height = align(height) + aligned_width = align(width) + aligned_pixel_budget = aligned_frames * aligned_height * aligned_width + + if aligned_pixel_budget < min_pixels: + scale = math.sqrt(min_pixels / (num_frames * height * width)) + aligned_height = align(max(1, math.ceil(height * scale))) + aligned_width = align(max(1, math.ceil(width * scale))) + aligned_pixel_budget = aligned_frames * aligned_height * aligned_width + + if aligned_pixel_budget <= max_pixels: + return aligned_height, aligned_width + + minimum_pixels = aligned_frames * factor**2 + if max_pixels < minimum_pixels: + raise ValueError( + f"max_image_tokens={max_image_tokens} is too small for one " + "aligned patch." + ) + + low, high = 1, height + best_height, best_width = factor, factor + while low <= high: + content_height = (low + high) // 2 + content_width = max(1, math.floor(width * content_height / height)) + candidate_height = align(content_height) + candidate_width = align(content_width) + if aligned_frames * candidate_height * candidate_width <= max_pixels: + best_height, best_width = candidate_height, candidate_width + low = content_height + 1 + else: + high = content_height - 1 + return best_height, best_width + + +def _to_channel_first(image: Any, do_convert_rgb: bool) -> np.ndarray: + if isinstance(image, (str, Path)): + image = Image.open(image) + if hasattr(image, "convert"): + if do_convert_rgb: + image = image.convert("RGB") + array = np.asarray(image) + else: + array = np.asarray(image) + + if array.ndim == 2: + array = np.repeat(array[..., None], 3, axis=-1) + if array.ndim != 3: + raise ValueError(f"Expected a 3D image, got shape {array.shape}.") + if array.shape[-1] in (1, 3, 4): + array = np.transpose(array, (2, 0, 1)) + if array.shape[0] == 4: + array = array[:3] + if array.shape[0] == 1 and do_convert_rgb: + array = np.repeat(array, 3, axis=0) + if array.shape[0] != 3: + raise ValueError(f"Expected an RGB image, got shape {array.shape}.") + return array + + +def _resize_channel_first( + image: np.ndarray, target_height: int, target_width: int +) -> np.ndarray: + if image.shape[-2:] == (target_height, target_width): + return image + array = np.transpose(image, (1, 2, 0)) + if array.dtype != np.uint8: + if np.issubdtype(array.dtype, np.floating) and array.max(initial=0) <= 1: + array = array * 255 + array = np.clip(array, 0, 255).astype(np.uint8) + resized = Image.fromarray(array).resize( + (target_width, target_height), + resample=Image.Resampling.BICUBIC, + ) + return np.transpose(np.asarray(resized), (2, 0, 1)) + + +class Glm5NextImageProcessor(ImageProcessingMixin): + """NumPy/Pillow implementation of the GLM-5 Next image processor.""" + + model_input_names = ["pixel_values", "image_grid_thw"] + + def __init__( + self, + patch_size: int = 14, + temporal_patch_size: int = 2, + merge_size: int = 2, + patch_expand_factor: int = 1, + min_image_tokens: int = 16, + max_image_tokens: int = 8000, + do_rescale: bool = True, + rescale_factor: float = 1 / 255.0, + do_normalize: bool = True, + image_mean: list[float] | None = None, + image_std: list[float] | None = None, + do_convert_rgb: bool = True, + **kwargs, + ): + super().__init__(**kwargs) + self.patch_size = patch_size + self.temporal_patch_size = temporal_patch_size + self.merge_size = merge_size + self.patch_expand_factor = patch_expand_factor + self.min_image_tokens = min_image_tokens + self.max_image_tokens = max_image_tokens + self.do_rescale = do_rescale + self.rescale_factor = rescale_factor + self.do_normalize = do_normalize + self.image_mean = list(image_mean or OPENAI_CLIP_MEAN) + self.image_std = list(image_std or OPENAI_CLIP_STD) + self.do_convert_rgb = do_convert_rgb + + def fetch_images(self, images): + if not isinstance(images, list): + images = [images] + return [_to_channel_first(image, self.do_convert_rgb) for image in images] + + def _process_one(self, image: Any, **kwargs) -> tuple[np.ndarray, list[int]]: + do_convert_rgb = kwargs.get("do_convert_rgb", self.do_convert_rgb) + do_rescale = kwargs.get("do_rescale", self.do_rescale) + rescale_factor = kwargs.get("rescale_factor", self.rescale_factor) + do_normalize = kwargs.get("do_normalize", self.do_normalize) + image_mean = kwargs.get("image_mean", self.image_mean) + image_std = kwargs.get("image_std", self.image_std) + image = _to_channel_first(image, do_convert_rgb) + _, height, width = image.shape + patch_size = kwargs.get("patch_size", self.patch_size) + temporal_patch_size = kwargs.get( + "temporal_patch_size", self.temporal_patch_size + ) + merge_size = kwargs.get("merge_size", self.merge_size) + patch_expand_factor = kwargs.get( + "patch_expand_factor", self.patch_expand_factor + ) + min_image_tokens = kwargs.get("min_image_tokens", self.min_image_tokens) + max_image_tokens = kwargs.get("max_image_tokens", self.max_image_tokens) + factor = patch_size * merge_size * patch_expand_factor + target_height, target_width = smart_resize( + temporal_patch_size, + height, + width, + temporal_factor=temporal_patch_size, + factor=factor, + min_image_tokens=min_image_tokens, + max_image_tokens=max_image_tokens, + ) + + pixels_per_token = temporal_patch_size * factor**2 + scale = min(target_height / height, target_width / width) + if temporal_patch_size * height * width >= ( + pixels_per_token * min_image_tokens + ): + scale = min(1.0, scale) + content_height = max(1, min(target_height, math.floor(height * scale))) + content_width = max(1, min(target_width, math.floor(width * scale))) + image = _resize_channel_first(image, content_height, content_width) + + canvas = np.zeros( + (image.shape[0], target_height, target_width), dtype=image.dtype + ) + canvas[:, :content_height, :content_width] = image + image = canvas.astype(np.float32) + if do_rescale: + image *= rescale_factor + if do_normalize: + mean = np.asarray(image_mean, dtype=np.float32)[:, None, None] + std = np.asarray(image_std, dtype=np.float32)[:, None, None] + image = (image - mean) / std + + channels = image.shape[0] + grid_h = target_height // patch_size + grid_w = target_width // patch_size + patches = image.reshape( + channels, + grid_h // merge_size, + merge_size, + patch_size, + grid_w // merge_size, + merge_size, + patch_size, + ) + patches = patches.transpose(1, 4, 2, 5, 0, 3, 6) + patches = np.expand_dims(patches, axis=5) + patches = np.repeat(patches, temporal_patch_size, axis=5) + patches = patches.reshape( + grid_h * grid_w, + channels * temporal_patch_size * patch_size * patch_size, + ) + return patches.astype(np.float32), [1, grid_h, grid_w] + + def __call__(self, images=None, **kwargs): + return self.preprocess(images=images, **kwargs) + + def preprocess(self, images=None, return_tensors=None, **kwargs) -> BatchFeature: + if images is None: + raise ValueError("images must not be None") + if not isinstance(images, list): + images = [images] + image_kwargs = { + key: value for key, value in kwargs.items() if key in _IMAGE_KWARGS + } + processed = [self._process_one(image, **image_kwargs) for image in images] + data = { + "pixel_values": np.concatenate([item[0] for item in processed], axis=0), + "image_grid_thw": np.asarray( + [item[1] for item in processed], dtype=np.int64 + ), + } + return BatchFeature(data=data, tensor_type=return_tensors) + + def get_number_of_image_patches( + self, height: int, width: int, images_kwargs: dict | None = None + ) -> int: + images_kwargs = images_kwargs or {} + patch_size = images_kwargs.get("patch_size", self.patch_size) + merge_size = images_kwargs.get("merge_size", self.merge_size) + patch_expand_factor = images_kwargs.get( + "patch_expand_factor", self.patch_expand_factor + ) + target_height, target_width = smart_resize( + images_kwargs.get("temporal_patch_size", self.temporal_patch_size), + height, + width, + temporal_factor=images_kwargs.get( + "temporal_patch_size", self.temporal_patch_size + ), + factor=patch_size * merge_size * patch_expand_factor, + min_image_tokens=images_kwargs.get( + "min_image_tokens", self.min_image_tokens + ), + max_image_tokens=images_kwargs.get( + "max_image_tokens", self.max_image_tokens + ), + ) + return (target_height // patch_size) * (target_width // patch_size) + + +def _load_json(model_path: str | Path, filename: str) -> dict | None: + local = Path(model_path) / filename + if local.exists(): + return json.loads(local.read_text()) + try: + from huggingface_hub import hf_hub_download + + downloaded = hf_hub_download(str(model_path), filename) + return json.loads(Path(downloaded).read_text()) + except Exception: + return None + + +def _image_processor_kwargs(model_path: str | Path) -> dict: + config = _load_json(model_path, "config.json") or {} + vision = config.get("vision_config", {}) or {} + processor = _load_json(model_path, "processor_config.json") or {} + image = processor.get("image_processor", {}) or {} + + result = {} + for key in _IMAGE_KWARGS: + if key in image: + result[key] = image[key] + for source, target in ( + ("patch_size", "patch_size"), + ("temporal_patch_size", "temporal_patch_size"), + ("spatial_merge_size", "merge_size"), + ): + if target not in result and source in vision: + result[target] = vision[source] + return result + + +class Glm5NextProcessor(ProcessorMixin): + attributes = ["image_processor", "tokenizer"] + valid_kwargs = ["chat_template"] + image_processor_class = "AutoImageProcessor" + tokenizer_class = "AutoTokenizer" + + def check_argument_for_proper_class(self, argument_name, argument): + return type(argument) + + def __init__( + self, + image_processor=None, + tokenizer=None, + chat_template=None, + **kwargs, + ): + image_processor = image_processor or Glm5NextImageProcessor() + self.image_token = "<|image|>" + self.video_token = "<|video|>" + self.image_token_id = ( + tokenizer.convert_tokens_to_ids(self.image_token) if tokenizer else None + ) + self.video_token_id = ( + tokenizer.convert_tokens_to_ids(self.video_token) if tokenizer else None + ) + super().__init__( + image_processor, + tokenizer, + chat_template=chat_template, + ) + + def __call__( + self, + images=None, + text=None, + padding=True, + padding_side=None, + add_special_tokens=False, + return_tensors="mlx", + return_mm_token_type_ids=True, + **kwargs, + ) -> BatchFeature: + image_inputs = {} + if images is not None: + image_kwargs = { + key: value for key, value in kwargs.items() if key in _IMAGE_KWARGS + } + image_inputs = dict( + self.image_processor( + images=images, + return_tensors=None, + **image_kwargs, + ) + ) + + if text is None: + text = [""] + elif not isinstance(text, list): + text = [text] + text = ["" if item is None else str(item) for item in text] + + if image_inputs: + placeholder = "<|glm5_next_image_placeholder|>" + image_idx = 0 + grids = image_inputs["image_grid_thw"] + for prompt_idx, prompt in enumerate(text): + while self.image_token in prompt: + if image_idx >= len(grids): + raise ValueError("More image tokens were provided than images.") + count = int( + np.prod(grids[image_idx]) // self.image_processor.merge_size**2 + ) + prompt = prompt.replace(self.image_token, placeholder * count, 1) + image_idx += 1 + text[prompt_idx] = prompt.replace(placeholder, self.image_token) + if image_idx != len(grids): + raise ValueError("More images were provided than image tokens.") + + tokenizer_kwargs = dict(kwargs) + for key in _IMAGE_KWARGS: + tokenizer_kwargs.pop(key, None) + if padding_side is not None: + tokenizer_kwargs["padding_side"] = padding_side + text_inputs = dict( + self.tokenizer( + text, + padding=padding, + add_special_tokens=add_special_tokens, + return_tensors=None, + **tokenizer_kwargs, + ) + ) + + if return_mm_token_type_ids and self.image_token_id is not None: + input_ids = np.asarray(text_inputs["input_ids"]) + mm_token_type_ids = np.zeros_like(input_ids) + mm_token_type_ids[input_ids == self.image_token_id] = 1 + text_inputs["mm_token_type_ids"] = mm_token_type_ids.tolist() + + data = {**text_inputs, **image_inputs} + if return_tensors == "mlx": + data = to_mlx(data) + return BatchFeature(data=data) + + def batch_decode(self, *args, **kwargs): + return self.tokenizer.batch_decode(*args, **kwargs) + + def decode(self, *args, **kwargs): + return self.tokenizer.decode(*args, **kwargs) + + def apply_chat_template(self, *args, **kwargs): + return self.tokenizer.apply_chat_template(*args, **kwargs) + + @property + def model_input_names(self): + tokenizer_names = getattr(self.tokenizer, "model_input_names", []) + return list( + dict.fromkeys( + tokenizer_names + + self.image_processor.model_input_names + + ["mm_token_type_ids"] + ) + ) + + @classmethod + def from_pretrained(cls, pretrained_model_name_or_path, **kwargs): + tokenizer_kwargs = dict(kwargs) + chat_template = tokenizer_kwargs.pop("chat_template", None) + tokenizer_kwargs.pop("return_tensors", None) + tokenizer = AutoTokenizer.from_pretrained( + pretrained_model_name_or_path, + **tokenizer_kwargs, + ) + if Path(pretrained_model_name_or_path).exists(): + load_chat_template(tokenizer, pretrained_model_name_or_path) + processor_config = ( + _load_json(pretrained_model_name_or_path, "processor_config.json") or {} + ) + return cls( + image_processor=Glm5NextImageProcessor( + **_image_processor_kwargs(pretrained_model_name_or_path) + ), + tokenizer=tokenizer, + chat_template=( + chat_template + or processor_config.get("chat_template") + or getattr(tokenizer, "chat_template", None) + ), + ) + + +install_auto_processor_patch("glm5_next", Glm5NextProcessor) + +__all__ = [ + "Glm5NextImageProcessor", + "Glm5NextProcessor", + "smart_resize", +] diff --git a/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/vision.py b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/vision.py new file mode 100644 index 0000000000..d1b94c1259 --- /dev/null +++ b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/vision.py @@ -0,0 +1,359 @@ +from typing import Optional + +import mlx.core as mx +import mlx.nn as nn + +from .config import VisionConfig +from .linear import linear_forward + + +def check_array_shape(arr): + shape = arr.shape + + if len(shape) == 4: + out_channels, kH, KW, _ = shape + return (out_channels >= kH) and (out_channels >= KW) and (kH == KW) + elif len(shape) == 5: + out_channels, kT, kH, KW, _ = shape + return (out_channels >= kH) and (out_channels >= KW) and (kH == KW) + else: + return False + + +def rotate_half(x): + x1 = x[..., : x.shape[-1] // 2] + x2 = x[..., x.shape[-1] // 2 :] + return mx.concatenate([-x2, x1], axis=-1) + + +def apply_rotary_pos_emb_vision( + q: mx.array, k: mx.array, cos: mx.array, sin: mx.array +) -> tuple: + orig_q_dtype = q.dtype + orig_k_dtype = k.dtype + q, k = q.astype(mx.float32), k.astype(mx.float32) + cos = mx.expand_dims(cos, axis=-2).astype(mx.float32) + sin = mx.expand_dims(sin, axis=-2).astype(mx.float32) + q_embed = (q * cos) + (rotate_half(q) * sin) + k_embed = (k * cos) + (rotate_half(k) * sin) + q_embed = q_embed.astype(orig_q_dtype) + k_embed = k_embed.astype(orig_k_dtype) + return q_embed, k_embed + + +class Glm5NextVisionRotaryEmbedding(nn.Module): + def __init__(self, dim: int, theta: float = 10000.0) -> None: + super().__init__() + self.dim = dim + self.theta = theta + + def __call__(self, seqlen: int) -> mx.array: + inv_freq = 1.0 / ( + self.theta ** (mx.arange(0, self.dim, 2, dtype=mx.float32) / self.dim) + ) + seq = mx.arange(seqlen, dtype=inv_freq.dtype) + freqs = mx.outer(seq, inv_freq) + return freqs + + +class Glm5NextVisionPatchEmbed(nn.Module): + def __init__(self, config: VisionConfig) -> None: + super().__init__() + self.config = config + self.patch_size = config.patch_size + self.temporal_patch_size = config.temporal_patch_size + self.in_channels = config.in_channels + self.embed_dim = config.hidden_size + + kernel_size = [self.temporal_patch_size, self.patch_size, self.patch_size] + self.proj = nn.Conv3d( + self.in_channels, + self.embed_dim, + kernel_size=kernel_size, + stride=kernel_size, + bias=True, + ) + + def __call__(self, hidden_states: mx.array) -> mx.array: + hidden_states = hidden_states.reshape( + -1, + self.in_channels, + self.temporal_patch_size, + self.patch_size, + self.patch_size, + ).moveaxis(1, 4) + + hidden_states = self.proj(hidden_states) + hidden_states = hidden_states.reshape(-1, self.embed_dim) + return hidden_states + + +class Glm5NextVisionPatchMerger(nn.Module): + def __init__( + self, + dim: int, + context_dim: int, + hidden_act: str, + swiglu_limit: float, + bias: bool = False, + ) -> None: + super().__init__() + self.swiglu_limit = swiglu_limit + self.proj = nn.Linear(dim, dim, bias=bias) + self.post_projection_norm = nn.LayerNorm(dim) + self.gate_proj = nn.Linear(dim, context_dim, bias=bias) + self.up_proj = nn.Linear(dim, context_dim, bias=bias) + self.down_proj = nn.Linear(context_dim, dim, bias=bias) + + def __call__(self, x: mx.array) -> mx.array: + x = linear_forward(self.proj, x) + x = nn.gelu(self.post_projection_norm(x)) + gate = linear_forward(self.gate_proj, x) + up = linear_forward(self.up_proj, x) + if self.swiglu_limit is not None: + gate = mx.clip(gate, a_min=None, a_max=self.swiglu_limit) + up = mx.clip(up, a_min=-self.swiglu_limit, a_max=self.swiglu_limit) + return linear_forward(self.down_proj, nn.silu(gate) * up) + + +class Glm5NextVisionAttention(nn.Module): + def __init__(self, config: VisionConfig) -> None: + super().__init__() + self.config = config + self.dim = config.hidden_size + self.num_heads = config.num_heads + self.head_dim = self.dim // self.num_heads + self.scale = self.head_dim**-0.5 + + self.qkv = nn.Linear( + config.hidden_size, config.hidden_size * 3, bias=config.attention_bias + ) + self.proj = nn.Linear( + config.hidden_size, config.hidden_size, bias=config.attention_bias + ) + + self.q_norm = nn.RMSNorm(self.head_dim, eps=config.rms_norm_eps) + self.k_norm = nn.RMSNorm(self.head_dim, eps=config.rms_norm_eps) + + def __call__( + self, + hidden_states: mx.array, + cu_seqlens: mx.array, + position_embeddings: tuple, + ) -> mx.array: + seq_length = hidden_states.shape[0] + + qkv = linear_forward(self.qkv, hidden_states) + qkv = qkv.reshape(seq_length, 3, self.num_heads, -1) + qkv = qkv.transpose(1, 0, 2, 3) + q, k, v = mx.split(qkv, 3, axis=0) + q = q.squeeze(0) + k = k.squeeze(0) + v = v.squeeze(0) + + q = self.q_norm(q) + k = self.k_norm(k) + + cos, sin = position_embeddings + q, k = apply_rotary_pos_emb_vision(q, k, cos, sin) + + q = q.transpose(1, 0, 2)[None, ...] + k = k.transpose(1, 0, 2)[None, ...] + v = v.transpose(1, 0, 2)[None, ...] + + lengths = (cu_seqlens[1:] - cu_seqlens[:-1]).tolist() + split_indices = [] + cumsum = 0 + for i, length in enumerate(lengths[:-1]): + cumsum += length + split_indices.append(cumsum) + + q_splits = mx.split(q, split_indices, axis=2) + k_splits = mx.split(k, split_indices, axis=2) + v_splits = mx.split(v, split_indices, axis=2) + + attn_outputs = [] + for q_chunk, k_chunk, v_chunk in zip(q_splits, k_splits, v_splits): + output = mx.fast.scaled_dot_product_attention( + q_chunk, k_chunk, v_chunk, scale=self.scale, mask=None + ) + attn_outputs.append(output) + + attn_output = mx.concatenate(attn_outputs, axis=2) + attn_output = attn_output.transpose(0, 2, 1, 3).reshape(seq_length, -1) + attn_output = linear_forward(self.proj, attn_output) + return attn_output + + +class Glm5NextVisionMLP(nn.Module): + def __init__(self, config: VisionConfig) -> None: + super().__init__() + self.swiglu_limit = config.swiglu_limit + self.gate_proj = nn.Linear( + config.hidden_size, config.intermediate_size, bias=config.attention_bias + ) + self.up_proj = nn.Linear( + config.hidden_size, config.intermediate_size, bias=config.attention_bias + ) + self.down_proj = nn.Linear( + config.intermediate_size, config.hidden_size, bias=config.attention_bias + ) + + def __call__(self, x: mx.array) -> mx.array: + gate = linear_forward(self.gate_proj, x) + up = linear_forward(self.up_proj, x) + if self.swiglu_limit is not None: + gate = mx.clip(gate, a_min=None, a_max=self.swiglu_limit) + up = mx.clip(up, a_min=-self.swiglu_limit, a_max=self.swiglu_limit) + return linear_forward(self.down_proj, nn.silu(gate) * up) + + +class Glm5NextVisionBlock(nn.Module): + def __init__(self, config: VisionConfig) -> None: + super().__init__() + self.norm1 = nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.norm2 = nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.attn = Glm5NextVisionAttention(config) + self.mlp = Glm5NextVisionMLP(config) + + def __call__( + self, hidden_states: mx.array, cu_seqlens: mx.array, position_embeddings: tuple + ) -> mx.array: + hidden_states = hidden_states + self.attn( + self.norm1(hidden_states), + cu_seqlens=cu_seqlens, + position_embeddings=position_embeddings, + ) + hidden_states = hidden_states + self.mlp(self.norm2(hidden_states)) + return hidden_states + + +class VisionModel(nn.Module): + def __init__(self, config: VisionConfig) -> None: + super().__init__() + self.config = config + self.model_type = config.model_type + self.spatial_merge_size = config.spatial_merge_size + self.patch_size = config.patch_size + + self.patch_embed = Glm5NextVisionPatchEmbed(config) + + head_dim = config.hidden_size // config.num_heads + self.rotary_pos_emb = Glm5NextVisionRotaryEmbedding(head_dim // 2) + + self.blocks = [Glm5NextVisionBlock(config) for _ in range(config.depth)] + + self.merger = Glm5NextVisionPatchMerger( + dim=config.out_hidden_size, + context_dim=config.projection_intermediate_size, + hidden_act=config.hidden_act, + swiglu_limit=config.swiglu_limit, + ) + + self.downsample = nn.Conv2d( + in_channels=config.hidden_size, + out_channels=config.out_hidden_size, + kernel_size=config.spatial_merge_size, + stride=config.spatial_merge_size, + bias=True, + ) + + self.post_layernorm = nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + + def rot_pos_emb(self, grid_thw: mx.array): + pos_ids = [] + + for t, h, w in grid_thw.tolist(): + hpos_ids = mx.expand_dims(mx.arange(h), 1) + hpos_ids = mx.repeat(hpos_ids, w, axis=1) + hpos_ids = hpos_ids.reshape( + h // self.spatial_merge_size, + self.spatial_merge_size, + w // self.spatial_merge_size, + self.spatial_merge_size, + ) + hpos_ids = mx.transpose(hpos_ids, (0, 2, 1, 3)) + hpos_ids = hpos_ids.flatten() + + wpos_ids = mx.expand_dims(mx.arange(w), 0) + wpos_ids = mx.repeat(wpos_ids, h, axis=0) + wpos_ids = wpos_ids.reshape( + h // self.spatial_merge_size, + self.spatial_merge_size, + w // self.spatial_merge_size, + self.spatial_merge_size, + ) + wpos_ids = mx.transpose(wpos_ids, (0, 2, 1, 3)) + wpos_ids = wpos_ids.flatten() + + stacked_pos_ids = mx.stack([hpos_ids, wpos_ids], axis=-1) + pos_ids.append(mx.tile(stacked_pos_ids, (t, 1))) + + pos_ids = mx.concatenate(pos_ids, axis=0) + max_grid_size = mx.max(grid_thw[:, 1:]) + rotary_pos_emb_full = self.rotary_pos_emb(max_grid_size.item()) + rotary_pos_emb = rotary_pos_emb_full[pos_ids].reshape(pos_ids.shape[0], -1) + + emb = mx.concatenate((rotary_pos_emb, rotary_pos_emb), axis=-1) + return (mx.cos(emb), mx.sin(emb)), pos_ids + + def __call__( + self, + hidden_states: mx.array, + grid_thw: mx.array, + output_hidden_states: Optional[bool] = None, + ) -> mx.array: + hidden_states = self.patch_embed(hidden_states) + position_embeddings, _ = self.rot_pos_emb(grid_thw) + + seq_lens = grid_thw[:, 1] * grid_thw[:, 2] + repeats = grid_thw[:, 0] + repeated_values = [] + for seq_len, repeat_count in zip(seq_lens.tolist(), repeats.tolist()): + repeated_values.extend([seq_len] * repeat_count) + + cu_seqlens = mx.array(repeated_values).cumsum(axis=0) + cu_seqlens = mx.pad(cu_seqlens, (1, 0), constant_values=0) + + for blk in self.blocks: + hidden_states = blk( + hidden_states, + cu_seqlens=cu_seqlens, + position_embeddings=position_embeddings, + ) + + hidden_states = self.post_layernorm(hidden_states) + + hidden_states = hidden_states.reshape( + -1, + self.spatial_merge_size, + self.spatial_merge_size, + hidden_states.shape[-1], + ) + hidden_states = self.downsample(hidden_states).reshape( + -1, self.config.out_hidden_size + ) + + merged_hidden_states = self.merger(hidden_states) + return merged_hidden_states + + @staticmethod + def sanitize(weights): + sanitized_weights = {} + for k, v in weights.items(): + if "position_ids" in k: + continue + elif "patch_embed.proj.weight" in k or "downsample.weight" in k: + if check_array_shape(v): + sanitized_weights[k] = v + else: + if v.ndim == 5: + sanitized_weights[k] = v.transpose(0, 2, 3, 4, 1) + elif v.ndim == 4: + sanitized_weights[k] = v.transpose(0, 2, 3, 1) + else: + sanitized_weights[k] = v + else: + sanitized_weights[k] = v + + return sanitized_weights diff --git a/omlx/utils/model_loading.py b/omlx/utils/model_loading.py index 677c7bf41d..d384ef5b80 100644 --- a/omlx/utils/model_loading.py +++ b/omlx/utils/model_loading.py @@ -676,6 +676,17 @@ def maybe_apply_pre_load_patches( mtp_enabled=mtp_active, ) + if for_vlm and model_type == "glm5_next": + from ..patches.mlx_vlm_glm5_next_compat import ( + apply_mlx_vlm_glm5_next_compat_patch, + ) + + if apply_mlx_vlm_glm5_next_compat_patch(): + logger.info( + "GLM-5.3 mlx-vlm compatibility patch applied for %s", + model_name, + ) + # Apply the MTP patch whenever the model has MTP heads on a compatible # model_type — even when mtp_enabled is False. The patch is required # for *sanitize correctness*: stock mlx-lm Model.sanitize triggers a diff --git a/tests/test_cluster_kv_reservation.py b/tests/test_cluster_kv_reservation.py index df0cd316b5..177c93a429 100644 --- a/tests/test_cluster_kv_reservation.py +++ b/tests/test_cluster_kv_reservation.py @@ -103,6 +103,27 @@ def test_mla_models_are_not_over_counted(): assert _kv_cache_replicated_across_tp(uniform) is False +def test_glm5_next_nope_hybrid_uses_sparse_layer_average(): + text_config = { + "num_hidden_layers": 4, + "kv_lora_rank": 512, + "qk_rope_head_dim": 0, + "index_head_dim": 128, + "index_kpool": 4, + "layer_types": [ + "linear_attention", + "linear_attention", + "linear_attention", + "deepseek_sparse_attention", + ], + } + config = {"model_type": "glm5_next", "text_config": text_config} + + # One of four layers grows with context: (512 + 128 / 4) * fp16 / 4. + assert _kv_bytes_per_token_per_layer(config) == 272 + assert _kv_cache_replicated_across_tp(config) is True + + def test_an_unreadable_config_reserves_nothing_rather_than_guessing(): assert _kv_bytes_per_token_per_layer({}) == 0 assert _kv_bytes_per_token_per_layer({"num_attention_heads": 8}) == 0 diff --git a/tests/test_memory_monitor_vlm_config.py b/tests/test_memory_monitor_vlm_config.py index 0bee8fd696..3ab6277331 100644 --- a/tests/test_memory_monitor_vlm_config.py +++ b/tests/test_memory_monitor_vlm_config.py @@ -280,6 +280,23 @@ def test_monitor_uses_mla_kv_override_for_prompt_kv(self): assert actual == tokens * bytes_per_token assert actual < standard / 20 + def test_nope_mla_accepts_zero_rope_and_prices_pooling_ratio(self): + from omlx.patches.deepseek_v4 import apply_pooling_cache_support + + apply_pooling_cache_support() + from mlx_lm.models.cache import CacheList, KVCache, PoolingCache + + config = type( + "NopeMlaConfig", + (), + {"kv_lora_rank": 512, "qk_rope_head_dim": 0, "index_head_dim": 128}, + )() + caches = [CacheList(KVCache(), PoolingCache(4)) for _ in range(11)] + + assert estimate_mla_kv_bytes_per_token(config, caches, 2) == ( + 11 * (512 + 128 / 4) * 2 + ) + def test_scheduler_passes_mla_kv_override_to_monitor(self): sched = _make_scheduler() sched.memory_monitor = MagicMock() diff --git a/tests/test_mlx_vlm_glm5_next_compat.py b/tests/test_mlx_vlm_glm5_next_compat.py new file mode 100644 index 0000000000..b3c75fedaa --- /dev/null +++ b/tests/test_mlx_vlm_glm5_next_compat.py @@ -0,0 +1,610 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Regression tests for the GLM-5.3-Flash mlx-vlm compatibility overlay.""" + +from __future__ import annotations + +import base64 +import importlib +import io +import json + +import mlx.core as mx +import pytest +from PIL import Image + +from omlx.memory_monitor import estimate_mla_kv_bytes_per_token +from omlx.model_discovery import detect_model_type +from omlx.oq import ( + _build_model_sanitizer, + _is_vlm_load, + universal_quant_predicate, +) +from omlx.patches import mlx_vlm_glm5_next_compat as compat + + +@pytest.fixture(autouse=True) +def _apply_glm5_next_compat(): + compat.apply_mlx_vlm_glm5_next_compat_patch() + + +def _tiny_config(*, with_vision: bool = False): + from mlx_vlm.models import glm5_next + + text = glm5_next.TextConfig( + model_type="glm5_next_text", + vocab_size=128, + hidden_size=32, + intermediate_size=64, + moe_intermediate_size=16, + num_hidden_layers=2, + num_attention_heads=2, + num_key_value_heads=1, + n_shared_experts=None, + n_routed_experts=None, + routed_scaling_factor=1.0, + kv_lora_rank=8, + q_lora_rank=8, + qk_rope_head_dim=0, + v_head_dim=8, + qk_nope_head_dim=8, + num_experts_per_tok=2, + first_k_dense_replace=99, + max_position_embeddings=128, + rms_norm_eps=1e-5, + index_topk=4, + index_head_dim=8, + index_n_heads=2, + layer_types=["linear_attention", "deepseek_sparse_attention"], + mlp_layer_types=["dense", "dense"], + linear_attn_config={ + "num_heads": 2, + "head_dim": 32, + "short_conv_kernel_size": 4, + "gate_lower_bound": -5.0, + }, + index_kpool=2, + hc_mult=2, + hc_sinkhorn_iters=2, + ) + vision = None + if with_vision: + vision = glm5_next.VisionConfig( + model_type="glm5_next_vision", + depth=1, + hidden_size=32, + intermediate_size=64, + num_heads=4, + patch_size=2, + out_hidden_size=32, + projection_intermediate_size=64, + image_size=4, + spatial_merge_size=2, + temporal_patch_size=2, + ) + return glm5_next.ModelConfig( + text_config=text, + model_type="glm5_next", + vision_config=vision, + image_token_id=120, + video_token_id=121, + ) + + +def _tiny_config_dict(*, with_vision: bool = False) -> dict: + config = _tiny_config(with_vision=with_vision) + text = dict(vars(config.text_config)) + text["linear_attn_config"] = { + "num_heads": config.text_config.linear_num_heads, + "head_dim": config.text_config.linear_head_dim, + "short_conv_kernel_size": config.text_config.linear_conv_kernel_dim, + "gate_lower_bound": config.text_config.linear_lower_bound, + } + payload = { + "model_type": "glm5_next", + "architectures": [ + "Glm5NextForConditionalGeneration" if with_vision else "Glm5NextForCausalLM" + ], + "text_config": text, + } + if with_vision: + payload["vision_config"] = dict(vars(config.vision_config)) + return payload + + +def _feed_pool(cache, token_count: int) -> None: + width = 4 + values = mx.arange(token_count * width, dtype=mx.float32).reshape( + 1, token_count, width + ) + gates = mx.zeros_like(values) + ready, _, _ = cache.accumulate_windows(values, gates, 0) + pooled = ready.reshape(1, -1, cache.ratio, width).mean(axis=2) + cache.update_and_fetch(pooled) + + +def test_glm5_next_registers_pinned_upstream_model(): + assert compat.apply_mlx_vlm_glm5_next_compat_patch() in {True, False} + from mlx_vlm.models import glm5_next + from mlx_vlm.utils import get_model_and_args, update_module_configs + + module, model_type = get_model_and_args(_tiny_config_dict(with_vision=True)) + config_dict = _tiny_config_dict(with_vision=True) + model_config = module.ModelConfig.from_dict(config_dict) + model_config = update_module_configs( + model_config, module, config_dict, ["text", "vision"] + ) + + assert model_type == "glm5_next" + assert module is glm5_next + assert model_config.text_config.model_type == "glm5_next_text" + assert model_config.vision_config.model_type == "glm5_next_vision" + assert compat.PR_URL.endswith("/2030") + + +@pytest.mark.parametrize("with_vision", [False, True]) +def test_glm5_next_discovery_uses_vlm_loader(tmp_path, with_vision): + (tmp_path / "config.json").write_text( + json.dumps(_tiny_config_dict(with_vision=with_vision)) + ) + assert detect_model_type(tmp_path) == "vlm" + + +def test_text_only_config_does_not_construct_a_vision_tower(): + from mlx_vlm.models import glm5_next + from mlx_vlm.utils import update_module_configs + + config_dict = _tiny_config_dict() + config_dict["vision_config"] = {} + model_config = glm5_next.ModelConfig.from_dict(config_dict) + model_config = update_module_configs( + model_config, glm5_next, config_dict, ["text", "vision"] + ) + model = glm5_next.Model(model_config) + + assert model.vision_model is None + with pytest.raises(ValueError, match="vision_config is None"): + model.get_input_embeddings( + input_ids=mx.array([[1]], dtype=mx.int32), + pixel_values=mx.zeros((1, 1)), + ) + + +def test_torch_free_processor_expands_image_tokens_and_runs_vision_path(): + from mlx_vlm.models import glm5_next + + class TokenizerStub: + model_input_names = ["input_ids", "attention_mask"] + + @staticmethod + def convert_tokens_to_ids(token): + return {"<|image|>": 120, "<|video|>": 121}[token] + + @staticmethod + def __call__(texts, **kwargs): + del kwargs + rows = [] + for text in texts: + rows.append([1] + [120] * text.count("<|image|>") + [2]) + return { + "input_ids": rows, + "attention_mask": [[1] * len(row) for row in rows], + } + + image_processor = glm5_next.Glm5NextImageProcessor( + patch_size=2, + temporal_patch_size=2, + merge_size=2, + min_image_tokens=1, + max_image_tokens=4, + ) + processor = glm5_next.Glm5NextProcessor( + image_processor=image_processor, + tokenizer=TokenizerStub(), + ) + inputs = processor( + images=[Image.new("RGB", (8, 4), "blue")], + text=["<|begin_of_image|><|image|><|end_of_image|>"], + ) + + image_tokens = int(mx.sum(inputs["input_ids"] == 120).item()) + expected_tokens = int(inputs["image_grid_thw"][0].prod().item()) // 4 + assert image_tokens == expected_tokens == 2 + assert inputs["pixel_values"].shape == (8, 24) + + model = glm5_next.Model(_tiny_config(with_vision=True)) + features = model.encode_image( + inputs["pixel_values"], + image_grid_thw=inputs["image_grid_thw"], + ) + embeddings = model.get_input_embeddings( + inputs["input_ids"], + inputs["pixel_values"], + image_grid_thw=inputs["image_grid_thw"], + ).inputs_embeds + mx.eval(features, embeddings) + + assert features.shape == (2, 32) + assert embeddings.shape == (1, 4, 32) + assert mx.all(mx.isfinite(features)).item() + + +def test_glm_image_budget_uses_8k_limit_and_exact_resize_count(): + from mlx_vlm.models.glm5_next import Glm5NextImageProcessor + + from omlx.engine.vlm import ( + _count_image_tokens_real, + _derive_image_token_upper_bound, + ) + + processor = Glm5NextImageProcessor() + wrapper = type("Processor", (), {"image_processor": processor})() + buffer = io.BytesIO() + Image.new("RGB", (56, 42)).save(buffer, format="PNG") + data_uri = "data:image/png;base64," + base64.b64encode(buffer.getvalue()).decode() + messages = [ + { + "role": "user", + "content": [{"type": "image_url", "image_url": {"url": data_uri}}], + } + ] + + assert _derive_image_token_upper_bound(wrapper) == 8000 + assert _count_image_tokens_real(messages, wrapper, upper_bound=8000) == 20 + + +def test_tiny_text_prefill_decode_and_batch_match(): + from mlx_vlm.models.glm5_next.language import LanguageModel + + config = _tiny_config() + model = LanguageModel(config.text_config, config) + single_cache = model.make_cache() + prompt = mx.array([[2, 3, 4, 5, 6, 7]], dtype=mx.int32) + prefill = model(prompt, cache=single_cache).logits + decoded = model(mx.array([[8]], dtype=mx.int32), cache=single_cache).logits + mx.eval(prefill, decoded) + + assert prefill.shape == (1, 6, 128) + assert decoded.shape == (1, 1, 128) + assert mx.all(mx.isfinite(prefill)).item() + sparse_cache = single_cache[1] + assert type(sparse_cache).__name__ == "CacheList" + assert sparse_cache[0].values.shape[-1] == 0 + assert type(sparse_cache[1]).__name__ == "PoolingCache" + + generate = importlib.import_module("mlx_lm.generate") + batch_cache = generate._make_cache(model, [0, 0], None) + batch_tokens = mx.concatenate([prompt, prompt], axis=0) + batch_logits = model(batch_tokens, cache=batch_cache).logits + left_logits = model(prompt, cache=model.make_cache()).logits + right_logits = model(prompt, cache=model.make_cache()).logits + mx.eval(batch_logits, left_logits, right_logits) + + assert type(batch_cache[1][1]).__name__ == "BatchPoolingCache" + assert mx.allclose(batch_logits[:1], left_logits, atol=3e-4).item() + assert mx.allclose(batch_logits[1:], right_logits, atol=3e-4).item() + + +def test_variable_length_batch_matches_single_request_greedy_tokens(): + from mlx_lm.generate import BatchGenerator + from mlx_vlm.models.glm5_next import Model + + from omlx.models.vlm import VLMModelAdapter + + mx.random.seed(17) + config = _tiny_config() + model = VLMModelAdapter(Model(config)) + + def generate(prompts, max_tokens=4): + generator = BatchGenerator( + model, + max_tokens=max_tokens, + prefill_batch_size=len(prompts), + completion_batch_size=len(prompts), + sampler=lambda logits: mx.argmax(logits, axis=-1), + ) + uids = generator.insert(prompts, max_tokens=[max_tokens] * len(prompts)) + outputs = {uid: [] for uid in uids} + for _ in range(max_tokens + 4): + _, responses = generator.next() + for response in responses: + outputs[response.uid].append(response.token) + if all(len(tokens) == max_tokens for tokens in outputs.values()): + break + return [outputs[uid] for uid in uids] + + short_prompt = [2, 3, 4, 5, 6, 7] + long_prompt = [8, 9, 10, 11, 12, 13, 14, 15, 16, 17] + single = generate([short_prompt])[0] + batched = generate([short_prompt, long_prompt])[0] + + assert batched == single + + +def test_late_join_batch_matches_single_request_greedy_tokens(): + from mlx_lm.generate import BatchGenerator + from mlx_vlm.models.glm5_next import Model + + from omlx.models.vlm import VLMModelAdapter + + mx.random.seed(31) + model = VLMModelAdapter(Model(_tiny_config())) + prompts = [ + [2, 3, 4, 5, 6, 7], + [8, 9, 10, 11, 12, 13, 14, 15, 16, 17], + ] + max_tokens = 4 + + def generate_single(prompt): + generator = BatchGenerator( + model, + max_tokens=max_tokens, + prefill_batch_size=1, + completion_batch_size=2, + sampler=lambda logits: mx.argmax(logits, axis=-1), + ) + uid = generator.insert([prompt], max_tokens=[max_tokens])[0] + output = [] + while len(output) < max_tokens: + _, responses = generator.next() + output.extend(r.token for r in responses if r.uid == uid) + return output + + expected = [generate_single(prompt) for prompt in prompts] + generator = BatchGenerator( + model, + max_tokens=max_tokens, + prefill_batch_size=1, + completion_batch_size=2, + sampler=lambda logits: mx.argmax(logits, axis=-1), + ) + first_uid = generator.insert([prompts[0]], max_tokens=[max_tokens])[0] + outputs = {first_uid: []} + _, responses = generator.next() + outputs[first_uid].extend(r.token for r in responses if r.uid == first_uid) + + second_uid = generator.insert([prompts[1]], max_tokens=[max_tokens])[0] + outputs[second_uid] = [] + for _ in range(max_tokens + 6): + _, responses = generator.next() + for response in responses: + outputs[response.uid].append(response.token) + if all(len(tokens) == max_tokens for tokens in outputs.values()): + break + + assert outputs[first_uid] == expected[0] + assert outputs[second_uid] == expected[1] + + +def test_pooling_cache_filter_extend_and_reorder_preserve_row_state(): + from mlx_lm.models.cache import BatchPoolingCache, PoolingCache + + first = PoolingCache(2) + second = PoolingCache(2) + third = PoolingCache(2) + _feed_pool(first, 5) + _feed_pool(second, 3) + _feed_pool(third, 7) + + batch = BatchPoolingCache.merge([first, second]) + assert batch._processed == [5, 3] + batch.filter(mx.array([1], dtype=mx.int32)) + batch.extend(BatchPoolingCache.merge([third])) + assert batch._processed == [3, 7] + + batch.filter(mx.array([1, 0], dtype=mx.int32)) + assert batch._processed == [7, 3] + assert batch._pool_lengths == [3, 1] + assert batch.extract(0).remainder == 1 + assert batch.extract(1).remainder == 1 + + +def test_nope_mla_memory_estimate_accounts_for_pooled_indexer(): + from mlx_vlm.models.glm5_next.language import LanguageModel + + config = _tiny_config() + model = LanguageModel(config.text_config, config) + # One sparse layer: 8 latent elements/token plus 8/2 pooled-index elements. + assert ( + estimate_mla_kv_bytes_per_token( + config.text_config, model.make_cache(), dtype_size=2 + ) + == 24 + ) + + +def test_sanitize_and_oq_keep_sensitive_parameters_in_fp32(): + config_dict = _tiny_config_dict() + assert _is_vlm_load(config_dict) is True + sanitizer = _build_model_sanitizer(config_dict) + assert sanitizer is not None + + weights = { + "model.language_model.layers.0.self_attn.A_log": mx.ones( + (2,), dtype=mx.bfloat16 + ), + "model.language_model.layers.0.hc_attn_alpha": mx.ones((2,), dtype=mx.bfloat16), + "model.language_model.mtp.fc.weight": mx.ones((2, 2)), + "model.language_model.layers.1.self_attn.kv_b_proj.weight": mx.ones( + (32, 8), dtype=mx.bfloat16 + ), + } + sanitized = sanitizer(weights) + + a_log = "language_model.model.layers.0.self_attn.forget_gate.A_log" + hc = "language_model.model.layers.0.attn_hc.alpha" + assert sanitized[a_log].dtype == mx.float32 + assert sanitized[hc].dtype == mx.float32 + assert sanitized[ + "language_model.model.layers.1.self_attn.embed_q.weight" + ].shape == (2, 8, 8) + assert sanitized[ + "language_model.model.layers.1.self_attn.unembed_out.weight" + ].shape == (2, 8, 8) + assert not any("mtp" in key for key in sanitized) + assert sanitizer._omlx_cast_predicate(a_log) is False + assert universal_quant_predicate( + "model.layers.1.self_attn.indexer.wk", + None, + config_dict, + oq_level=4, + ) == {"bits": 8, "group_size": 64, "mode": "affine"} + + +def test_vector_gate_kernel_matches_reference_with_padding_mask(): + from mlx_vlm.models.glm5_next.gated_delta import gated_delta_update + + mx.random.seed(19) + shape = (1, 4, 2, 32) + q = mx.random.normal(shape, dtype=mx.float16) + k = mx.random.normal(shape, dtype=mx.float16) + v = mx.random.normal(shape, dtype=mx.float16) + a = mx.random.normal(shape, dtype=mx.float16) + beta = mx.random.normal((1, 4, 2), dtype=mx.float16) + a_log = mx.zeros((2, 1), dtype=mx.float32) + dt_bias = mx.zeros((2, 32), dtype=mx.float32) + mask = mx.array([[True, True, False, True]]) + + expected, expected_state = gated_delta_update( + q, + k, + v, + a, + beta, + a_log, + dt_bias, + mask=mask, + use_kernel=False, + lower_bound=-5.0, + ) + actual, actual_state = gated_delta_update( + q, + k, + v, + a, + beta, + a_log, + dt_bias, + mask=mask, + use_kernel=True, + lower_bound=-5.0, + ) + mx.eval(expected, expected_state, actual, actual_state) + + assert mx.allclose(actual, expected, atol=2e-3, rtol=2e-3).item() + assert mx.allclose(actual_state, expected_state, atol=2e-3, rtol=2e-3).item() + + +def test_native_glm_indexer_scores_match_mlx_reference_when_available(): + from mlx_vlm.models.glm5_next.language import Glm5NextIndexer + + from omlx.custom_kernels.glm_moe_dsa import fast + + if not fast.has_symbol("dsa_indexer_scores"): + pytest.skip("GLM DSA native indexer extension is not built") + + config = _tiny_config().text_config + config.index_n_heads = 32 + config.index_head_dim = 128 + indexer = Glm5NextIndexer(config) + mx.random.seed(23) + q = mx.random.normal((1, 5, 32, 128), dtype=mx.float16) + keys = mx.random.normal((1, 7, 128), dtype=mx.float16) + weights = mx.random.normal((1, 5, 32), dtype=mx.float16) + actual = indexer._native_scores(q, keys, weights) + if actual is None: + pytest.skip("GLM DSA indexer kernel rejected the installed ABI") + reference = mx.sum( + weights[..., None] * mx.maximum(q @ keys[:, None].swapaxes(-1, -2), 0), + axis=2, + ) + mx.eval(actual, reference) + assert mx.allclose(actual, reference, atol=0.08, rtol=0.02).item() + + +def test_glm5_next_switch_moe_uses_opt_in_native_weighted_sum(): + from omlx.custom_kernels.glm_moe_dsa import fast + from omlx.patches.deepseek_v4.switch_layers import SwitchGLU + + if not fast.has_symbol("glm_moe_weighted_sum"): + pytest.skip("GLM native MoE weighted-sum extension is not built") + + mx.random.seed(29) + layer = SwitchGLU(16, 8, 8) + layer.set_dtype(mx.float16) + x = mx.random.normal((1, 8, 16), dtype=mx.float16) + indices = mx.array( + [[[(token + expert) % 8 for expert in range(8)] for token in range(8)]], + dtype=mx.int32, + ) + scores = mx.softmax(mx.random.normal(indices.shape, dtype=mx.float32), axis=-1) + + native = layer(x, indices, scores=scores, weighted_sum=True) + experts = layer(x, indices, scores=scores, weighted_sum=False) + reference = (experts * scores[..., None]).sum(axis=-2).astype(native.dtype) + mx.eval(native, reference) + + assert native.shape == (1, 8, 16) + assert mx.allclose(native, reference, atol=2e-3, rtol=2e-3).item() + + +def test_glm5_next_affine_prefill_uses_shared_qmm_kernel(monkeypatch): + import mlx.nn as nn + from mlx_vlm.models.glm5_next.linear import linear_forward + + from omlx.custom_kernels.qwen35_prefill import fast + + if not fast.has_symbol("qwen35_q4_affine_qmm_t"): + pytest.skip("Qwen affine prefill QMM extension is not built") + + base = nn.Linear(64, 64, bias=False) + base.set_dtype(mx.float16) + linear = base.to_quantized(group_size=64, bits=4, mode="affine") + x = mx.random.normal((1, 128, 64), dtype=mx.float16) + reference = linear(x) + + original = fast.qwen35_q4_affine_qmm_t + calls = 0 + + def spy(*args, **kwargs): + nonlocal calls + calls += 1 + return original(*args, **kwargs) + + monkeypatch.setattr(fast, "qwen35_q4_affine_qmm_t", spy) + actual = linear_forward(linear, x) + mx.eval(actual, reference) + + assert calls == 1 + assert mx.allclose(actual, reference, atol=2e-3, rtol=2e-3).item() + + +def test_glm5_next_q8_indexer_prefill_uses_shared_qmm_kernel(monkeypatch): + import mlx.nn as nn + from mlx_vlm.models.glm5_next.linear import linear_forward + + from omlx.custom_kernels.qwen35_prefill import fast + + if not fast.has_symbol("qwen35_q8_affine_qmm_t"): + pytest.skip("Qwen Q8 affine prefill QMM extension is not built") + + mx.random.seed(37) + base = nn.Linear(1536, 4096, bias=False) + base.set_dtype(mx.float16) + linear = base.to_quantized(group_size=64, bits=8, mode="affine") + x = mx.random.normal((1, 1024, 1536), dtype=mx.float16) + reference = linear(x) + + original = fast.qwen35_q8_affine_qmm_t + calls = 0 + + def spy(*args, **kwargs): + nonlocal calls + calls += 1 + return original(*args, **kwargs) + + monkeypatch.setattr(fast, "qwen35_q8_affine_qmm_t", spy) + actual = linear_forward(linear, x) + mx.eval(actual, reference) + + assert calls == 1 + assert mx.allclose(actual, reference, atol=2e-3, rtol=2e-3).item() From 3ae7778b100f659d8fe4dde79c0a18f1e8916ebb Mon Sep 17 00:00:00 2001 From: jundot Date: Thu, 27 Aug 2026 21:30:00 +0900 Subject: [PATCH 014/132] fix: complete GLM-5.3 multimodal and oQe support --- omlx/engine/vlm.py | 39 +++++++++ omlx/oq.py | 183 +++++++++++++++++++++++++++++++++++++-- tests/test_oq.py | 143 ++++++++++++++++++++++++++++++ tests/test_vlm_engine.py | 52 +++++++++++ 4 files changed, 412 insertions(+), 5 deletions(-) diff --git a/omlx/engine/vlm.py b/omlx/engine/vlm.py index c72ab5070c..2f4c720973 100644 --- a/omlx/engine/vlm.py +++ b/omlx/engine/vlm.py @@ -2479,6 +2479,45 @@ def _format_messages_for_vlm_template( ) ): formatted_messages.append(msg) + elif model_type == "glm5_next" and msg_num_images > 0: + # mlx-vlm does not yet register glm5_next in MODEL_CONFIG, so + # get_message_json() treats it as unsupported and its generic + # fallback strips image parts. Preserve their relative order + # as template-visible markers; the checkpoint's native chat + # template expands each marker to the GLM image token triplet. + glm_content: list[Any] = [] + inserted_images = 0 + if isinstance(raw_content, list): + for item in raw_content: + if isinstance(item, dict): + item_type = item.get("type", "") + item_text = item.get("text", "") + else: + item_type = getattr(item, "type", "") + item_text = getattr(item, "text", "") + + if item_type in image_part_types: + if inserted_images < msg_num_images: + glm_content.append({"type": "image"}) + inserted_images += 1 + elif item_type == "text": + glm_content.append({"type": "text", "text": item_text}) + elif isinstance(item, str): + glm_content.append(item) + + if inserted_images < msg_num_images: + glm_content[:0] = [ + {"type": "image"} + for _ in range(msg_num_images - inserted_images) + ] + if not any( + isinstance(item, str) + or (isinstance(item, dict) and item.get("type") == "text") + for item in glm_content + ): + glm_content.append({"type": "text", "text": content}) + + formatted_messages.append({"role": role, "content": glm_content}) else: formatted = get_message_json( model_type, diff --git a/omlx/oq.py b/omlx/oq.py index c8a451dd52..c8256cef6f 100644 --- a/omlx/oq.py +++ b/omlx/oq.py @@ -352,6 +352,18 @@ def _is_qwen4_exp_ngram_embedding_tensor(path: str, config: dict) -> bool: return _QWEN4_EXP_NGRAM_SHARD_RE.search(_normalize_quant_path(path)) is not None +def _is_token_embedding_tensor(path: str) -> bool: + """Return whether a weight is indexed by token id rather than activations.""" + return path.lower().endswith( + ( + ".embed_tokens.weight", + ".tok_embeddings.weight", + ".word_embeddings.weight", + ".wte.weight", + ) + ) + + def universal_quant_predicate( path: str, module, config: dict, oq_level: int = 4 ) -> Union[bool, dict]: @@ -2246,12 +2258,25 @@ def moveaxis(self, src_ax, dst_ax): new_shape = tuple(self.shape[d] for d in dims) if self.transform == "nested_unreplayable": return self._unreplayable(shape=new_shape) + op = ("moveaxis", src_ax, dst_ax) + if len(self.sources) > 1: + expr = self.as_expr() + expr = self._wrap_expr_op(expr, op) if expr is not None else None + if expr is None: + return self._unreplayable(shape=new_shape) + return _TrackedTensor( + new_shape, + self.dtype, + list(self.sources), + "expr", + expr=expr, + ) return _TrackedTensor( new_shape, self.dtype, list(self.sources), f"moveaxis_{src_ax}_{dst_ax}", - recipe=list(self.recipe) + [("moveaxis", src_ax, dst_ax)], + recipe=list(self.recipe) + [op], ) def transpose(self, *axes): @@ -2406,6 +2431,7 @@ def _discover_sanitize_plan(sanitize_fn, lazy_index): "contiguous": getattr(mx, "contiguous", None), "from_fp8": getattr(mx, "from_fp8", None), "pad": getattr(mx, "pad", None), + "issubdtype": mx.issubdtype, } def _is_plain_source(tensor): @@ -2549,6 +2575,28 @@ def _fake_contiguous(tensor, *args, **kwargs): def _noop(*a, **kw): pass + def _fake_issubdtype(dtype, category): + if isinstance(dtype, str): + dtype = { + "BF16": mx.bfloat16, + "F16": mx.float16, + "F32": mx.float32, + "F64": mx.float32, + "F8_E4M3": mx.float16, + "F8_E5M2": mx.float16, + "F8_E8M0": mx.uint8, + "I8": mx.int8, + "I16": mx.int16, + "I32": mx.int32, + "I64": mx.int64, + "U8": mx.uint8, + "U16": mx.uint16, + "U32": mx.uint32, + "U64": mx.uint64, + "BOOL": mx.bool_, + }.get(dtype.upper(), dtype) + return _orig["issubdtype"](dtype, category) + mx.stack = _fake_stack mx.concatenate = _fake_concatenate mx.split = _fake_split @@ -2558,6 +2606,7 @@ def _noop(*a, **kw): mx.moveaxis = _fake_moveaxis mx.transpose = _fake_transpose mx.expand_dims = _fake_expand_dims + mx.issubdtype = _fake_issubdtype if _orig["swapaxes"] is not None: mx.swapaxes = _fake_swapaxes if _orig["contiguous"] is not None: @@ -5026,6 +5075,10 @@ def _source_imatrix_signature( # Invalidate caches produced by the old independent-block walk, which # captured only q_proj in the shared-KV tail of E2B/E4B. signature["layer_walk"] = "gemma4_shared_kv_v1" + elif str(config.get("model_type", "")).lower() == "glm5_next": + # GLM-5.3 needs its mHC-expanded layer walk plus the untied output-head + # capture. Older caches completed without either and must not be reused. + signature["layer_walk"] = "glm5_next_hc_moe_lm_head_v3" return signature @@ -5220,6 +5273,10 @@ def _lookup_imatrix_importance( # embedding rows. Do not turn the intentionally uniform PLE policy # into a missing-entry error under imatrix_strict. return None + if _is_token_embedding_tensor(tensor_name): + # Embedding columns are gathered by token id, not consumed as input + # activation channels, so a Linear-style imatrix entry cannot exist. + return None base = tensor_name[: -len(".weight")] entry = imatrix.entries.get(base) @@ -6334,6 +6391,7 @@ def _imatrix_load_path() -> str: _OQE_MIN_EXPERT_COUNT = 16 _OQE_MIN_EXPERT_COUNT_PERCENTILE = 5 _OQE_SWITCH_LINEAR_CLASSES = {"SwitchLinear", "QuantizedSwitchLinear"} +_OQE_MULTI_LINEAR_CLASSES = {"MultiLinear", "QuantizedMultiLinear"} _OQ_CODE_MULTILINGUAL_KEYS = ( "code", "en", @@ -6647,6 +6705,7 @@ def _find_model_layers(model): _GEMMA4_LAYER_STATE_KIND = "gemma4_shared_kv" _QWEN4_EXP_LAYER_STATE_KIND = "qwen4_exp" +_GLM5_NEXT_LAYER_STATE_KIND = "glm5_next" def _find_layer_model(model, layers): @@ -6914,6 +6973,20 @@ def _forward_layer_result(block, inputs, mask, position_ids, layer_idx=None): if isinstance(result, tuple): return result[0], result[1] if len(result) > 1 else None return result, None + if ( + isinstance(position_ids, dict) + and position_ids.get("kind") == _GLM5_NEXT_LAYER_STATE_KIND + ): + try: + result = block(inputs, mask=mask, cache=None) + except (TypeError, ValueError, RuntimeError, AttributeError) as e: + suffix = f" at layer {layer_idx}" if layer_idx is not None else "" + raise RuntimeError( + f"GLM-5.3 calibration forward failed{suffix}: {e}" + ) from e + if isinstance(result, tuple): + return result[0], result[1] if len(result) > 1 else None + return result, None if isinstance(position_ids, dict) and position_ids.get("kind") == "glm_moe_dsa": try: result = block( @@ -7094,6 +7167,23 @@ def _prepare_layer_inputs(model, layers, calib_data, inputs): ) if qwen4_exp_inputs is not None: return qwen4_exp_inputs + if model_type == "glm5_next": + language_model = getattr(model, "language_model", None) + args = getattr(language_model, "args", None) + hc_mult = _object_config_int(args, "hc_mult") + if hc_mult <= 0: + raise RuntimeError("GLM-5.3 calibration requires a positive hc_mult") + hidden = mx.broadcast_to( + inputs[:, :, None, :], + (inputs.shape[0], inputs.shape[1], hc_mult, inputs.shape[2]), + ) + hidden = mx.contiguous(hidden) + attention_mask = create_attention_mask(inputs, None, return_array=True) + masks = [ + None if bool(getattr(layer, "is_linear", False)) else attention_mask + for layer in layers + ] + return hidden, masks, {"kind": _GLM5_NEXT_LAYER_STATE_KIND} if model_type.startswith("deepseek_v4"): args = model.args h = mx.broadcast_to( @@ -7153,6 +7243,11 @@ def __call__(self, *args, **kwargs): self._collector.collect_switch( self._name, self._module, args[0], args[1] ) + elif type(self._module).__name__ in _OQE_MULTI_LINEAR_CLASSES: + transpose = kwargs.get("transpose", args[1] if len(args) >= 2 else True) + self._collector.collect_multi( + self._name, self._module, args[0], transpose=transpose + ) else: self._collector.collect_dense(self._name, self._module, args[0]) return self._module(*args, **kwargs) @@ -7164,6 +7259,7 @@ class OQImatrixCollector: def __init__(self): self.entries: dict[str, OQImatrixEntry] = {} self._original_modules: dict[str, Any] = {} + self._saved_attributes: list[tuple[Any, str, Any]] = [] self.capture_module_classes: dict[str, int] = {} self.switch_capture_modules = 0 @@ -7172,6 +7268,8 @@ def _is_capture_module(module) -> bool: cls = type(module).__name__ if cls in _OQE_SWITCH_LINEAR_CLASSES: return hasattr(module, "weight") and getattr(module.weight, "ndim", 0) == 3 + if cls in _OQE_MULTI_LINEAR_CLASSES: + return hasattr(module, "weight") and getattr(module.weight, "ndim", 0) == 3 # QuantizedLinear capture lets imatrix collection run against # already-quantized checkpoints (e.g. deriving a recalibrated MTP # head from an oQ8 model when the bf16 source is gone). @@ -7192,6 +7290,15 @@ def _module_in_dim(module) -> int: def install(self, model) -> int: replacements = [] for name, module in model.named_modules(): + if type(module).__name__ == "Glm5NextLinearAttention" and bool( + getattr(module, "fuse_in", False) + ): + # The fused KDA input projection reads six Linear weights + # directly, bypassing their calls and therefore the capture + # wrappers. Calibration temporarily takes the equivalent + # unfused path so every input-channel statistic is observed. + self._saved_attributes.append((module, "fuse_in", module.fuse_in)) + module.fuse_in = False if not name or not self._is_capture_module(module): continue cls = type(module).__name__ @@ -7213,6 +7320,9 @@ def restore(self, model) -> None: strict=False, ) self._original_modules.clear() + for module, attribute, value in self._saved_attributes: + setattr(module, attribute, value) + self._saved_attributes.clear() def _ensure_entry(self, name: str, sums_shape, counts_shape) -> OQImatrixEntry: entry = self.entries.get(name) @@ -7239,6 +7349,39 @@ def collect_dense(self, name: str, module, x) -> None: except Exception as e: logger.debug("oQe imatrix dense capture skipped for %s: %s", name, e) + def collect_multi(self, name: str, module, x, *, transpose: bool = True) -> None: + """Capture per-head input energy for MLA MultiLinear weights.""" + try: + if not transpose: + # The same MLA projection may be used in reverse. Quantization + # groups the stored weight's last dimension, whose matching + # activation is observed by the normal transpose=True call. + return + weight = module.weight + n_heads = int(weight.shape[0]) + bits = getattr(module, "bits", None) + in_dim = ( + int(weight.shape[-1] * 32 // int(bits)) + if bits and weight.dtype == mx.uint32 + else int(weight.shape[-1]) + ) + if not getattr(x, "shape", ()) or int(x.shape[-1]) != in_dim: + return + mx.eval(x) + x_np = np.asarray(x.astype(mx.float32)) + if x_np.ndim >= 2 and x_np.shape[-2] in (1, n_heads): + per_head = np.moveaxis(x_np, -2, 0).reshape(x_np.shape[-2], -1, in_dim) + if per_head.shape[0] == 1 and n_heads > 1: + per_head = np.repeat(per_head, n_heads, axis=0) + else: + shared = x_np.reshape(-1, in_dim) + per_head = np.repeat(shared[None], n_heads, axis=0) + entry = self._ensure_entry(name, (n_heads, in_dim), (n_heads,)) + entry.in_sum2 += np.square(per_head, dtype=np.float32).sum(axis=1) + entry.counts += per_head.shape[1] + except Exception as e: + logger.debug("oQe imatrix multi capture skipped for %s: %s", name, e) + @staticmethod def _accumulate_switch( entry: OQImatrixEntry, @@ -7314,6 +7457,29 @@ def collect_switch(self, name: str, module, x, indices) -> None: logger.debug("oQe imatrix switch capture skipped for %s: %s", name, e) +def _collect_glm5_next_lm_head_imatrix(model, hidden, collector) -> bool: + """Capture the untied GLM-5.3 output head without materializing logits.""" + if str(getattr(model, "model_type", "")) != "glm5_next": + return False + + language_model = getattr(model, "language_model", None) + core = getattr(language_model, "model", None) + norm = getattr(core, "norm", None) + if language_model is None or core is None or norm is None: + return False + + name = "language_model.lm_head" + module = collector._original_modules.get(name) + if module is None: + # Tied checkpoints project through embed_tokens and have no lm_head. + return False + + if getattr(hidden, "ndim", 0) == 4: + hidden = hidden.mean(axis=2) + collector.collect_dense(name, module, norm(hidden)) + return name in collector.entries + + def _collect_mtp_head_imatrix( model, batch, @@ -7531,6 +7697,8 @@ def _collect_imatrix_from_model( mx.synchronize() mx.clear_cache() + _collect_glm5_next_lm_head_imatrix(model, inputs, collector) + # MTP-head pass: the layer walk above leaves ``inputs`` as # the final-layer hidden states; feed them (post-norm) plus # the shifted token ids through the head so its linears @@ -7773,14 +7941,19 @@ def _lenient_load_weights(self, file_or_weights, *args, **kwargs): mx.clear_cache() -def _oqe_cache_missing_mtp_entries(cache: OQImatrixData, config: dict) -> bool: +def _oqe_cache_missing_mtp_entries( + cache: OQImatrixData, config: dict, model_path: str +) -> bool: """True when the model declares MTP heads but the cache predates the MTP-head collection pass (no ``mtp.*`` entries) — force a recollect so the head gets calibrated quantization instead of landing in "missing".""" try: - from omlx.utils.model_loading import _has_mtp_heads + from omlx.utils.model_loading import ( + _checkpoint_has_mtp_weights, + _has_mtp_heads, + ) - if not _has_mtp_heads(config): + if not _has_mtp_heads(config) or not _checkpoint_has_mtp_weights(model_path): return False except Exception: return False @@ -7817,7 +7990,7 @@ def _load_or_collect_imatrix( if reuse_cache and path.exists(): cache = _load_oqe_imatrix(path) if _oqe_cache_matches(cache, expected): - if _oqe_cache_missing_mtp_entries(cache, config): + if _oqe_cache_missing_mtp_entries(cache, config, model_path): logger.info( "oQe imatrix: cache predates MTP-head collection " "(no mtp.* entries), recollecting %s", diff --git a/tests/test_oq.py b/tests/test_oq.py index cd780f0875..a4224641ce 100644 --- a/tests/test_oq.py +++ b/tests/test_oq.py @@ -1274,6 +1274,24 @@ def test_qwen4_ngram_is_exempt_from_strict_imatrix_lookup(self): assert importance is None assert report["missing"] == [] + def test_token_embedding_is_exempt_from_strict_imatrix_lookup(self): + from omlx.oq import OQImatrixData, _lookup_imatrix_importance + + imatrix = OQImatrixData(entries={}, metadata={}, path="unused.npz") + report = {"missing": [], "mismatched": [], "applied": []} + + importance = _lookup_imatrix_importance( + imatrix, + "language_model.model.embed_tokens.weight", + (154_880, 256), + config={"model_type": "glm5_next"}, + strict=True, + report=report, + ) + + assert importance is None + assert report["missing"] == [] + def test_qwen4_ngram_group32_is_priced_into_budget_plan(self): from omlx.oq import _structural_quant_overrides @@ -2641,6 +2659,25 @@ def drop_sanitize(weights): assert "model.embed_tokens.weight" not in plan assert len(plan) == len(tensors) - 1 + def test_safetensors_dtype_supports_issubdtype_sanitize(self, sf_file): + path, tensors = sf_file + idx = _LazyTensorIndex([path]) + + def cast_floating_sanitize(weights): + return { + key: ( + value.astype(mx.float32) + if mx.issubdtype(value.dtype, mx.floating) + else value + ) + for key, value in weights.items() + } + + plan = _discover_sanitize_plan(cast_floating_sanitize, idx) + + assert set(plan) == set(tensors) + assert all(info["transform"] == "astype" for info in plan.values()) + def test_swapaxes_sanitize(self, sf_file): path, _tensors = sf_file idx = _LazyTensorIndex([path]) @@ -2704,6 +2741,26 @@ def glm_like_sanitize(weights): atol=1e-3, ) + def test_concatenate_moveaxis_sanitize_replays(self, tmp_path): + path = tmp_path / "weights.safetensors" + tensors = { + f"conv.{index}.weight": np.full((2, 3, 1), index, dtype=np.float16) + for index in range(3) + } + _write_safetensors(str(path), tensors) + idx = _LazyTensorIndex([str(path)]) + + def sanitize(weights): + fused = mx.concatenate(list(weights.values()), axis=1) + return {"conv.weight": fused.moveaxis(2, 1)} + + plan = _discover_sanitize_plan(sanitize, idx) + assert plan["conv.weight"]["transform"] == "expr" + result = _DiscoveredPlan(plan, idx).pop("conv.weight") + expected = np.concatenate(list(tensors.values()), axis=1).transpose(0, 2, 1) + + np.testing.assert_array_equal(np.array(result), expected) + def test_expand_dims_sanitize_replays(self, tmp_path): path = tmp_path / "weights.safetensors" tensor = np.arange(6, dtype=np.float16).reshape(2, 3) @@ -6493,6 +6550,92 @@ def test_trunk_and_mtp_imatrix_hooks_execute(self, tmp_path): configure_mtp_runtime(tmp_path, enabled=False) +@pytest.mark.skipif(not HAS_MLX, reason="MLX not available") +class TestGlm5NextLayerWalk: + def test_cache_without_checkpoint_mtp_weights_is_reusable(self, tmp_path): + from omlx.oq import OQImatrixData, _oqe_cache_missing_mtp_entries + + cache = OQImatrixData(entries={}, metadata={}, path="unused.npz") + config = { + "model_type": "glm5_next", + "text_config": {"num_nextn_predict_layers": 1}, + } + + assert not _oqe_cache_missing_mtp_entries(cache, config, str(tmp_path)) + + def test_cache_signature_tracks_glm5_next_layer_walk(self, tmp_path): + signature = _source_imatrix_signature( + tmp_path, + { + "model_type": "glm5_next", + "text_config": {"model_type": "glm5_next_text"}, + }, + num_samples=128, + seq_length=512, + calib_dataset="test", + ) + + assert signature["layer_walk"] == "glm5_next_hc_moe_lm_head_v3" + + def test_hyper_connections_and_moe_imatrix_hooks_execute(self): + from omlx.patches import mlx_vlm_glm5_next_compat + from omlx.oq import _collect_glm5_next_lm_head_imatrix + from tests.test_mlx_vlm_glm5_next_compat import _tiny_config + + mlx_vlm_glm5_next_compat.apply_mlx_vlm_glm5_next_compat_patch() + from mlx_vlm.models.glm5_next import Model + + config = _tiny_config() + config.text_config.n_routed_experts = 4 + config.text_config.n_shared_experts = 1 + config.text_config.first_k_dense_replace = 1 + config.text_config.mlp_layer_types = ["dense", "sparse"] + model = Model(config) + tokens = mx.array([[1, 2, 3, 4, 5, 6]], dtype=mx.int32) + layers = model.language_model.model.layers + inputs = model.language_model.model.embed_tokens(tokens) + inputs, masks, state = _prepare_layer_inputs(model, layers, tokens, inputs) + + assert inputs.shape == (1, 6, 2, 32) + assert state["kind"] == "glm5_next" + assert masks[0] is None + assert masks[1] is not None + + collector = OQImatrixCollector() + linear_attention = layers[0].self_attn + assert linear_attention.fuse_in + assert collector.install(model) > 0 + assert not linear_attention.fuse_in + try: + for layer_idx, layer in enumerate(layers): + inputs, _ = _forward_layer_result( + layer, + inputs, + masks[layer_idx], + state, + layer_idx=layer_idx, + ) + mx.eval(inputs) + + assert _collect_glm5_next_lm_head_imatrix(model, inputs, collector) + switch_entries = { + name: entry + for name, entry in collector.entries.items() + if ".switch_mlp." in name + } + assert switch_entries + assert "language_model.lm_head" in collector.entries + assert "language_model.model.layers.0.self_attn.b_proj" in collector.entries + embed_q = "language_model.model.layers.1.self_attn.embed_q" + assert embed_q in collector.entries + assert collector.entries[embed_q].counts.shape == (2,) + assert all(entry.counts.shape == (4,) for entry in switch_entries.values()) + assert all(int(entry.counts.sum()) > 0 for entry in switch_entries.values()) + finally: + collector.restore(model) + assert linear_attention.fuse_in + + @pytest.mark.skipif(not HAS_MLX, reason="MLX not available") class TestInklingLayerWalk: """Calibration layer-walk wiring for inkling.""" diff --git a/tests/test_vlm_engine.py b/tests/test_vlm_engine.py index 4946c5ad97..0faa448854 100644 --- a/tests/test_vlm_engine.py +++ b/tests/test_vlm_engine.py @@ -1603,6 +1603,58 @@ def test_image_messages_retain_list_content(self): assert isinstance(formatted[1]["content"], list) assert self._count_image_placeholders([formatted[1]]) == 1 + def test_glm5_next_preserves_image_parts_for_native_template(self): + """GLM-5.3 image parts must survive mlx-vlm's generic fallback.""" + engine = _make_loaded_engine(model_type="glm5_next") + messages = [ + { + "role": "user", + "content": [ + {"type": "text", "text": "Before"}, + { + "type": "image_url", + "image_url": {"url": "data:image/png;base64,abc"}, + }, + {"type": "text", "text": "After"}, + ], + } + ] + + formatted, image_ranges = engine._format_messages_for_vlm_template( + messages, num_images=1 + ) + + assert formatted == [ + { + "role": "user", + "content": [ + {"type": "text", "text": "Before"}, + {"type": "image"}, + {"type": "text", "text": "After"}, + ], + } + ] + assert image_ranges == [(0, 1)] + + def test_glm5_next_inserts_fallback_image_marker(self): + """Legacy GLM callers with separate images still receive a marker.""" + engine = _make_loaded_engine(model_type="glm5_next") + + formatted, image_ranges = engine._format_messages_for_vlm_template( + [{"role": "user", "content": "Describe this"}], num_images=1 + ) + + assert formatted == [ + { + "role": "user", + "content": [ + {"type": "image"}, + {"type": "text", "text": "Describe this"}, + ], + } + ] + assert image_ranges == [(0, 1)] + def test_reasoning_content_preserved_verbatim(self): """Assistant messages with reasoning_content must skip get_message_json. From 9b93696ed27dc7b0c7ad20e2c4bd612ff0d4dea6 Mon Sep 17 00:00:00 2001 From: DiscoStew6082 <229735125+DiscoStew6082@users.noreply.github.com> Date: Thu, 27 Aug 2026 22:17:36 +0900 Subject: [PATCH 015/132] fix(vlm): preserve GLM batch convolution state --- .../mlx_vlm/models/glm5_next/language.py | 17 +++++++- tests/test_mlx_vlm_glm5_next_compat.py | 42 +++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/language.py b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/language.py index 593bcd9f54..5bf7203a9d 100644 --- a/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/language.py +++ b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/language.py @@ -214,6 +214,9 @@ def __call__( cache: Optional[Any] = None, ) -> mx.array: B, S, _ = inputs.shape + has_right_padding = cache is not None and cache.lengths is not None + if has_right_padding: + mask = mx.arange(S)[None] < cache.lengths[:, None] if self.fuse_in: q_o, k_o, v_o, fa_o, ga_o, b_o = self._fused_in_proj(inputs) mixed = mx.concatenate([q_o, k_o, v_o], axis=-1) @@ -235,7 +238,19 @@ def __call__( ) conv_input = mx.concatenate([conv_state, mixed], axis=1) if cache is not None: - cache[0] = mx.contiguous(conv_input[:, -(self.conv_kernel_size - 1) :, :]) + state_size = self.conv_kernel_size - 1 + if has_right_padding: + valid_lengths = mx.sum(mask, axis=-1).astype(mx.int32) + state_indices = valid_lengths[:, None] + mx.arange(state_size)[None] + state_indices = mx.broadcast_to( + state_indices[..., None], + (B, state_size, self.conv_dim), + ) + cache[0] = mx.contiguous( + mx.take_along_axis(conv_input, state_indices, axis=1) + ) + else: + cache[0] = mx.contiguous(conv_input[:, -state_size:, :]) conv_out = nn.silu(self.conv1d(conv_input)) q, k, v = mx.split(conv_out, [self.qkv_dim, 2 * self.qkv_dim], axis=-1) diff --git a/tests/test_mlx_vlm_glm5_next_compat.py b/tests/test_mlx_vlm_glm5_next_compat.py index b3c75fedaa..d33f66f7d8 100644 --- a/tests/test_mlx_vlm_glm5_next_compat.py +++ b/tests/test_mlx_vlm_glm5_next_compat.py @@ -320,6 +320,48 @@ def generate(prompts, max_tokens=4): assert batched == single +def test_variable_length_batch_logits_match_single_requests(): + from mlx_lm.generate import BatchGenerator + from mlx_vlm.models.glm5_next import Model + + from omlx.models.vlm import VLMModelAdapter + + mx.random.seed(3184) + model = VLMModelAdapter(Model(_tiny_config())) + + def first_logits(prompts): + captured = [] + + def sampler(logits): + mx.eval(logits) + captured.append(logits) + return mx.argmax(logits, axis=-1) + + generator = BatchGenerator( + model, + max_tokens=3, + prefill_batch_size=len(prompts), + completion_batch_size=len(prompts), + sampler=sampler, + ) + generator.insert(prompts, max_tokens=[3] * len(prompts)) + for _ in range(4): + generator.next() + if captured: + break + assert len(captured) == 1 + return captured[0] + + short_prompt = [2, 3, 4] + long_prompt = [2, 3, 4, 5] + short_logits = first_logits([short_prompt])[0] + long_logits = first_logits([long_prompt])[0] + batch_logits = first_logits([short_prompt, long_prompt]) + + assert mx.allclose(batch_logits[0], short_logits, atol=3e-4, rtol=3e-4).item() + assert mx.allclose(batch_logits[1], long_logits, atol=3e-4, rtol=3e-4).item() + + def test_late_join_batch_matches_single_request_greedy_tokens(): from mlx_lm.generate import BatchGenerator from mlx_vlm.models.glm5_next import Model From 9cc8d38223d70a0b275cb6cbe5f0d9c4b96a2c49 Mon Sep 17 00:00:00 2001 From: DiscoStew Date: Thu, 27 Aug 2026 10:21:46 -0400 Subject: [PATCH 016/132] fix(vlm): honor model-owned batch cache conversion (#3188) --- omlx/patches/deepseek_v4/generate_patch.py | 31 ++++++++++-- omlx/scheduler.py | 44 +++++++++++++++++ tests/test_deepseek_v4_patch.py | 56 ++++++++++++++++++++++ tests/test_mlx_vlm_qwen4_exp_compat.py | 35 ++++++++++++++ tests/test_singleton_cache_passthrough.py | 21 +++++++- 5 files changed, 182 insertions(+), 5 deletions(-) diff --git a/omlx/patches/deepseek_v4/generate_patch.py b/omlx/patches/deepseek_v4/generate_patch.py index f0599e13e0..d3544cce0e 100644 --- a/omlx/patches/deepseek_v4/generate_patch.py +++ b/omlx/patches/deepseek_v4/generate_patch.py @@ -5,9 +5,10 @@ ``_make_cache``: ``isinstance(c, PoolingCache)`` → ``BatchPoolingCache``. The closure is not externally hookable, so we replace ``_make_cache`` -itself with a copy whose body is identical to PR 1192. ``_make_cache`` is -called via the module-level binding from inside ``mlx_lm.generate``, so -overwriting the attribute is sufficient. +with a compatible wrapper that adds PR 1192's PoolingCache conversion while +preserving any previously installed model-owned cache conversion. +``_make_cache`` is called via the module-level binding from inside +``mlx_lm.generate``, so overwriting the attribute is sufficient. When mlx-lm merges PR 1192 upstream this patch should be removed. """ @@ -50,13 +51,26 @@ def apply_generate_patch() -> bool: _gen = importlib.import_module("mlx_lm.generate") from mlx_lm.models.cache import BatchPoolingCache, PoolingCache + previous_make_cache = _gen._make_cache + + def has_pooling_cache(cache_obj): + if isinstance(cache_obj, PoolingCache): + return True + sub_caches = getattr(cache_obj, "caches", None) + return isinstance(sub_caches, (list, tuple)) and any( + has_pooling_cache(child) for child in sub_caches + ) + def _patched_make_cache(model, left_padding, max_kv_size): """Convert a list of regular caches into their corresponding batch-aware caches. """ def to_batch_cache(c): - if type(c) is KVCache: + model_owned_to_batch = getattr(c, "to_batch", None) + if callable(model_owned_to_batch): + return model_owned_to_batch(left_padding) + elif type(c) is KVCache: return BatchKVCache(left_padding) elif isinstance(c, ArraysCache): c.left_padding = mx.array(left_padding) @@ -76,6 +90,15 @@ def to_batch_cache(c): if hasattr(model, "make_cache"): cache = model.make_cache() + if not any(has_pooling_cache(c) for c in cache): + + class _CachedModel: + layers = getattr(model, "layers", ()) + + def make_cache(self): + return cache + + return previous_make_cache(_CachedModel(), left_padding, max_kv_size) return [to_batch_cache(c) for c in cache] else: if max_kv_size is not None: diff --git a/omlx/scheduler.py b/omlx/scheduler.py index a808da92ac..c34562aa22 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -923,11 +923,54 @@ def _turboquant_filter_singleton(self, batch_indices): _TQ_SINGLETON_CACHE_TYPE.extend = _regular_cache_extend_singleton _mlx_lm_generate_module = importlib.import_module("mlx_lm.generate") +_original_make_cache = _mlx_lm_generate_module._make_cache _original_merge_caches = _mlx_lm_generate_module._merge_caches _original_ppb_split = PromptProcessingBatch.split _REGULAR_SINGLETON_CACHE_TYPES = (_MLXKVCache, _MLXRotatingKVCache) +def _patched_make_cache(model, left_padding, max_kv_size): + """Honor model-owned batch conversion before MLX-LM's fallbacks.""" + if not hasattr(model, "make_cache"): + return _original_make_cache(model, left_padding, max_kv_size) + + model_cache = model.make_cache() + + def has_model_owned_conversion(cache_obj): + if callable(getattr(cache_obj, "to_batch", None)): + return True + sub_caches = getattr(cache_obj, "caches", None) + return isinstance(sub_caches, (list, tuple)) and any( + has_model_owned_conversion(child) for child in sub_caches + ) + + class _SingleCacheModel: + layers = (None,) + + def __init__(self, cache_obj): + self.cache_obj = cache_obj + + def make_cache(self): + return [self.cache_obj] + + def convert(cache_obj): + to_batch = getattr(cache_obj, "to_batch", None) + if callable(to_batch): + return to_batch(left_padding) + + sub_caches = getattr(cache_obj, "caches", None) + if isinstance(sub_caches, (list, tuple)) and any( + has_model_owned_conversion(child) for child in sub_caches + ): + return type(cache_obj)(*(convert(child) for child in sub_caches)) + + return _original_make_cache( + _SingleCacheModel(cache_obj), left_padding, max_kv_size + )[0] + + return [convert(cache_obj) for cache_obj in model_cache] + + def _cache_layer_supports_singleton_passthrough(cache_obj: Any) -> bool: sub_caches = getattr(cache_obj, "caches", None) if isinstance(sub_caches, (list, tuple)): @@ -1025,6 +1068,7 @@ def _patched_ppb_split(self, indices): return _original_ppb_split(self, indices) +_mlx_lm_generate_module._make_cache = _patched_make_cache _mlx_lm_generate_module._merge_caches = _patched_merge_caches _mlx_lm_generate_module._extend_cache = _patched_extend_cache PromptProcessingBatch.split = _patched_ppb_split diff --git a/tests/test_deepseek_v4_patch.py b/tests/test_deepseek_v4_patch.py index 3694f6c7cd..7659cb3d2c 100644 --- a/tests/test_deepseek_v4_patch.py +++ b/tests/test_deepseek_v4_patch.py @@ -4,7 +4,11 @@ import importlib import inspect import json +import os +import subprocess import sys +import textwrap +from pathlib import Path from types import SimpleNamespace from unittest.mock import MagicMock @@ -222,6 +226,58 @@ def make_cache(self): assert len(result) == 1 assert isinstance(result[0], BatchPoolingCache) + @pytest.mark.parametrize("patch_order", ("scheduler-first", "deepseek-first")) + def test_deepseek_patch_preserves_mixed_model_owned_conversion( + self, patch_order + ): + if patch_order == "scheduler-first": + patch_setup = ( + "import omlx.scheduler\n apply_deepseek_v4_patch()" + ) + else: + patch_setup = ( + "apply_deepseek_v4_patch()\n import omlx.scheduler" + ) + script = textwrap.dedent( + f""" + import importlib + + from omlx.patches.deepseek_v4 import apply_deepseek_v4_patch + from omlx.patches.mlx_vlm_qwen4_exp_compat import ( + apply_mlx_vlm_qwen4_exp_compat_patch, + ) + + {patch_setup} + apply_mlx_vlm_qwen4_exp_compat_patch() + + from mlx_lm.models.cache import BatchPoolingCache, CacheList, PoolingCache + from mlx_vlm.models.qwen4_exp.language import BatchQSAKVCache, QSAKVCache + + class Model: + layers = (object(),) + + def make_cache(self): + return [CacheList(PoolingCache(4), QSAKVCache())] + + generate = importlib.import_module("mlx_lm.generate") + caches = generate._make_cache(Model(), [0], None) + assert isinstance(caches[0].caches[0], BatchPoolingCache) + assert isinstance(caches[0].caches[1], BatchQSAKVCache) + """ + ) + env = dict(os.environ) + env["PYTHONDONTWRITEBYTECODE"] = "1" + result = subprocess.run( + [sys.executable, "-B", "-c", script], + cwd=Path(__file__).resolve().parents[1], + env=env, + capture_output=True, + text=True, + check=False, + ) + + assert result.returncode == 0, result.stderr + class TestTokenizerPatch: """mlx_lm.tokenizer_utils.AutoTokenizer wrapped with deepseek_v4 fallback.""" diff --git a/tests/test_mlx_vlm_qwen4_exp_compat.py b/tests/test_mlx_vlm_qwen4_exp_compat.py index 9141cebeb9..8430cd8efc 100644 --- a/tests/test_mlx_vlm_qwen4_exp_compat.py +++ b/tests/test_mlx_vlm_qwen4_exp_compat.py @@ -3,6 +3,7 @@ from __future__ import annotations +import importlib import json from types import SimpleNamespace @@ -388,6 +389,40 @@ def test_qwen4_exp_tiny_text_prefill_and_decode(): assert next_logits.logits.shape == (1, 1, 64) +def test_qwen4_batch_factory_honors_model_owned_cache_conversion(): + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp.language import BatchQSAKVCache, QSAKVCache + + import omlx.scheduler # noqa: F401 (installs BatchGenerator cache patches) + + qsa_cache = QSAKVCache() + qsa_cache.state = ( + mx.arange(24, dtype=mx.float32).reshape(1, 2, 3, 4), + mx.arange(24, 48, dtype=mx.float32).reshape(1, 2, 3, 4), + mx.arange(12, dtype=mx.float32).reshape(1, 3, 4), + mx.array([[5, 6, 7]], dtype=mx.int32), + ) + + class Model: + layers = (object(),) + + def make_cache(self): + return [qsa_cache] + + generate = importlib.import_module("mlx_lm.generate") + caches = generate._make_cache(Model(), [0], None) + + assert len(caches) == 1 + assert isinstance(caches[0], BatchQSAKVCache) + mx.eval(caches[0].offset, caches[0].index_keys, caches[0].index_position_ids) + assert caches[0].offset.tolist() == [3] + assert caches[0].index_offset == 3 + assert mx.array_equal(caches[0].index_keys, qsa_cache.index_keys).item() + assert mx.array_equal( + caches[0].index_position_ids, qsa_cache.index_position_ids + ).item() + + def test_qwen4_fp8_ple_dequantizes_only_selected_rows(): _tiny_config() from mlx_vlm.models.qwen4_exp.language import ShardedEmbedding diff --git a/tests/test_singleton_cache_passthrough.py b/tests/test_singleton_cache_passthrough.py index 965a04c833..fff2fe8877 100644 --- a/tests/test_singleton_cache_passthrough.py +++ b/tests/test_singleton_cache_passthrough.py @@ -4,7 +4,7 @@ import mlx.core as mx from mlx_lm.generate import PromptProcessingBatch, SequenceStateMachine -from mlx_lm.models.cache import ArraysCache, BatchKVCache, KVCache +from mlx_lm.models.cache import ArraysCache, BatchKVCache, CacheList, KVCache from mlx_vlm.turboquant import TurboQuantKVCache import omlx.scheduler # noqa: F401 (applies BatchGenerator cache patches) @@ -94,6 +94,25 @@ def test_extend_keeps_arrays_cache_in_place(): assert arrays_a[0].shape[0] == 2 +def test_make_cache_finds_nested_model_owned_batch_conversion(): + gen = importlib.import_module("mlx_lm.generate") + + class CustomCache: + def to_batch(self, left_padding): + return ("custom-batch", tuple(left_padding)) + + class Model: + layers = (object(),) + + def make_cache(self): + return [CacheList(CacheList(CustomCache()))] + + caches = gen._make_cache(Model(), [2, 0], None) + + nested = caches[0].caches[0].caches[0] + assert nested == ("custom-batch", (2, 0)) + + def test_prompt_batch_full_split_moves_cache_without_copy(): arrays = _arrays_cache() kv = _kv_cache(3) From 7519683bd8016c9286b408d056449f5f383cec24 Mon Sep 17 00:00:00 2001 From: Qianhe Chen <54462604+chenqianhe@users.noreply.github.com> Date: Thu, 27 Aug 2026 22:22:30 +0800 Subject: [PATCH 017/132] fix(updater): clean up mounted update DMGs before relaunch (#3190) --- .../omlx-mac/Sources/Updater/AppUpdater.swift | 63 ++++++++++++++++-- .../Tests/oMLXTests/AppUpdaterTests.swift | 64 +++++++++++++++++++ apps/omlx-mac/oMLX.xcodeproj/project.pbxproj | 4 ++ 3 files changed, 124 insertions(+), 7 deletions(-) create mode 100644 apps/omlx-mac/Tests/oMLXTests/AppUpdaterTests.swift diff --git a/apps/omlx-mac/Sources/Updater/AppUpdater.swift b/apps/omlx-mac/Sources/Updater/AppUpdater.swift index e536e5bb6c..be1d10fc81 100644 --- a/apps/omlx-mac/Sources/Updater/AppUpdater.swift +++ b/apps/omlx-mac/Sources/Updater/AppUpdater.swift @@ -20,6 +20,8 @@ final class AppUpdater { case notWritable(String) case downloadFailed(String) case mountFailed(String) + case unmountFailed(String) + case cleanupFailed(String) case appNotFoundInVolume case stageFailed(String) case cancelled @@ -30,6 +32,8 @@ final class AppUpdater { return "Cannot write to \(path). Move oMLX.app to a writable location and try again." case .downloadFailed(let m): return "Download failed: \(m)" case .mountFailed(let m): return "Could not mount DMG: \(m)" + case .unmountFailed(let m): return "Could not unmount DMG: \(m)" + case .cleanupFailed(let m): return "Could not clean up update files: \(m)" case .appNotFoundInVolume: return "oMLX.app not found inside the downloaded DMG" case .stageFailed(let m): return "Could not stage the update: \(m)" case .cancelled: return "Update cancelled" @@ -124,7 +128,12 @@ final class AppUpdater { onError(.downloadFailed("Could not create temp dir: \(error.localizedDescription)")) return } - defer { try? FileManager.default.removeItem(at: tmpDir) } + var temporaryDirectoryNeedsCleanup = true + defer { + if temporaryDirectoryNeedsCleanup { + try? FileManager.default.removeItem(at: tmpDir) + } + } let dmgPath = tmpDir.appendingPathComponent("oMLX-\(version).dmg") @@ -150,7 +159,12 @@ final class AppUpdater { onError(.mountFailed(error.localizedDescription)); return } - defer { _ = try? unmountDMG(at: mountPoint) } + var mountedDMGNeedsCleanup = true + defer { + if mountedDMGNeedsCleanup { + try? unmountDMG(at: mountPoint) + } + } if cancelled { return } onProgress(.staging) @@ -165,8 +179,40 @@ final class AppUpdater { } if cancelled { return } - onProgress(.ready) - onReady() + do { + try Self.finishStagedUpdate( + detach: { + try unmountDMG(at: mountPoint) + mountedDMGNeedsCleanup = false + }, + removeTemporaryFiles: { + try FileManager.default.removeItem(at: tmpDir) + temporaryDirectoryNeedsCleanup = false + }, + notifyReady: { + onProgress(.ready) + onReady() + } + ) + } catch let err as UpdateError { + onError(err) + } catch { + onError(.cleanupFailed(error.localizedDescription)) + } + } + + /// Releases every resource owned by a staged update before notifying the + /// controller. `notifyReady` may synchronously terminate the process, so + /// moving either cleanup step after it would leak the mounted image and + /// its downloaded backing file. + static func finishStagedUpdate( + detach: () throws -> Void, + removeTemporaryFiles: () throws -> Void, + notifyReady: () -> Void + ) throws { + try detach() + try removeTemporaryFiles() + notifyReady() } // MARK: - Download @@ -313,13 +359,16 @@ final class AppUpdater { throw UpdateError.mountFailed("Could not parse hdiutil output") } - @discardableResult - private func unmountDMG(at mountPoint: URL) throws -> Bool { + private func unmountDMG(at mountPoint: URL) throws { let result = try runProcess( "/usr/bin/hdiutil", args: ["detach", mountPoint.path, "-force"] ) - return result.status == 0 + guard result.status == 0 else { + throw UpdateError.unmountFailed( + result.stderr.isEmpty ? result.stdout : result.stderr + ) + } } // MARK: - Stage diff --git a/apps/omlx-mac/Tests/oMLXTests/AppUpdaterTests.swift b/apps/omlx-mac/Tests/oMLXTests/AppUpdaterTests.swift new file mode 100644 index 0000000000..1b899e0cb1 --- /dev/null +++ b/apps/omlx-mac/Tests/oMLXTests/AppUpdaterTests.swift @@ -0,0 +1,64 @@ +import XCTest +@testable import oMLX + +@MainActor +final class AppUpdaterTests: XCTestCase { + private enum TestError: Error, Equatable { + case detachFailed + case removalFailed + } + + func testReadyIsNotifiedOnlyAfterMountedResourcesAreReleased() throws { + var events: [String] = [] + + try AppUpdater.finishStagedUpdate( + detach: { events.append("detach") }, + removeTemporaryFiles: { events.append("remove temporary files") }, + notifyReady: { events.append("ready") } + ) + + XCTAssertEqual(events, [ + "detach", + "remove temporary files", + "ready", + ]) + } + + func testDetachFailurePreventsTemporaryRemovalAndReadyNotification() { + var events: [String] = [] + + XCTAssertThrowsError( + try AppUpdater.finishStagedUpdate( + detach: { + events.append("detach") + throw TestError.detachFailed + }, + removeTemporaryFiles: { events.append("remove temporary files") }, + notifyReady: { events.append("ready") } + ) + ) { error in + XCTAssertEqual(error as? TestError, .detachFailed) + } + + XCTAssertEqual(events, ["detach"]) + } + + func testTemporaryRemovalFailurePreventsReadyNotification() { + var events: [String] = [] + + XCTAssertThrowsError( + try AppUpdater.finishStagedUpdate( + detach: { events.append("detach") }, + removeTemporaryFiles: { + events.append("remove temporary files") + throw TestError.removalFailed + }, + notifyReady: { events.append("ready") } + ) + ) { error in + XCTAssertEqual(error as? TestError, .removalFailed) + } + + XCTAssertEqual(events, ["detach", "remove temporary files"]) + } +} diff --git a/apps/omlx-mac/oMLX.xcodeproj/project.pbxproj b/apps/omlx-mac/oMLX.xcodeproj/project.pbxproj index 5d08e07a02..acba9ef7b9 100644 --- a/apps/omlx-mac/oMLX.xcodeproj/project.pbxproj +++ b/apps/omlx-mac/oMLX.xcodeproj/project.pbxproj @@ -133,6 +133,7 @@ DBB000000000000000000108 /* ModelSettingsScreenVMTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DCC000000000000000000108 /* ModelSettingsScreenVMTests.swift */; }; DBB000000000000000000113 /* PerformanceScreenVMTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DCC000000000000000000113 /* PerformanceScreenVMTests.swift */; }; DBB000000000000000000114 /* UpdateInstallerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DCC000000000000000000114 /* UpdateInstallerTests.swift */; }; + DBB000000000000000000115 /* AppUpdaterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DCC000000000000000000115 /* AppUpdaterTests.swift */; }; EBB000000000000000000001 /* MarkdownUI in Frameworks */ = {isa = PBXBuildFile; productRef = ECC000000000000000000001 /* MarkdownUI */; }; /* End PBXBuildFile section */ @@ -277,6 +278,7 @@ DCC000000000000000000108 /* ModelSettingsScreenVMTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModelSettingsScreenVMTests.swift; sourceTree = ""; }; DCC000000000000000000113 /* PerformanceScreenVMTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PerformanceScreenVMTests.swift; sourceTree = ""; }; DCC000000000000000000114 /* UpdateInstallerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UpdateInstallerTests.swift; sourceTree = ""; }; + DCC000000000000000000115 /* AppUpdaterTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppUpdaterTests.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -347,6 +349,7 @@ DCC000000000000000000108 /* ModelSettingsScreenVMTests.swift */, DCC000000000000000000113 /* PerformanceScreenVMTests.swift */, DCC000000000000000000114 /* UpdateInstallerTests.swift */, + DCC000000000000000000115 /* AppUpdaterTests.swift */, ); path = oMLXTests; sourceTree = ""; @@ -815,6 +818,7 @@ DBB000000000000000000108 /* ModelSettingsScreenVMTests.swift in Sources */, DBB000000000000000000113 /* PerformanceScreenVMTests.swift in Sources */, DBB000000000000000000114 /* UpdateInstallerTests.swift in Sources */, + DBB000000000000000000115 /* AppUpdaterTests.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; From 7e6f4224d24ca9a6f19a1ffddfb5da9714777657 Mon Sep 17 00:00:00 2001 From: Qianhe Chen <54462604+chenqianhe@users.noreply.github.com> Date: Thu, 27 Aug 2026 22:56:48 +0800 Subject: [PATCH 018/132] feat(hy_v3): fuse routed MoE gate and up projections (#3055) --- omlx/engine/batched.py | 4 +-- omlx/engine/vlm.py | 4 +-- omlx/patches/qwen35_moe_gate_up.py | 21 ++++++++++------ tests/test_qwen35_moe_gate_up.py | 39 +++++++++++++++++++++++++++--- 4 files changed, 53 insertions(+), 15 deletions(-) diff --git a/omlx/engine/batched.py b/omlx/engine/batched.py index 4cc09001fc..d31b4117b5 100644 --- a/omlx/engine/batched.py +++ b/omlx/engine/batched.py @@ -291,7 +291,7 @@ def _load_model_sync(): get_mlx_executor(), materialize_lazy_state, self._model ) - # Qwen3.5/3.6 MoE gate+up regroup: concatenate the routed experts' + # Supported MoE gate+up regroup: concatenate the routed experts' # gate and up projections so decode runs 2 gather_qmm launches per # MoE layer instead of 3 (issue #2238). Bit-exact; runs on the MLX # executor because it rewrites weights in place. @@ -310,7 +310,7 @@ def _load_model_sync(): self._model, ) except Exception: - logger.debug("Qwen MoE gate+up fusion not applied", exc_info=True) + logger.debug("MoE gate+up fusion not applied", exc_info=True) # Qwen MoE decode router: fuse the top-k select + renormalize chain # into one launch (the composed argpartition chain is ~2 ms/token on diff --git a/omlx/engine/vlm.py b/omlx/engine/vlm.py index 2f4c720973..4a7e9a7059 100644 --- a/omlx/engine/vlm.py +++ b/omlx/engine/vlm.py @@ -1738,7 +1738,7 @@ def _load_vlm_sync(): except Exception: logger.debug("t5 bias free skipped", exc_info=True) - # Qwen3.5/3.6 MoE gate+up regroup: concatenate the routed experts' + # Supported MoE gate+up regroup: concatenate the routed experts' # gate and up projections so decode runs 2 gather_qmm launches per # MoE layer instead of 3 (issue #2238). Bit-exact; also swaps the # mlx-vlm target-verify helper for a fused-aware version. Runs on @@ -1758,7 +1758,7 @@ def _load_vlm_sync(): self._vlm_model, ) except Exception: - logger.debug("Qwen MoE gate+up fusion not applied", exc_info=True) + logger.debug("MoE gate+up fusion not applied", exc_info=True) _fix_processor_none_pixels(self._processor) self._diffusion_family = self._detect_diffusion_family() diff --git a/omlx/patches/qwen35_moe_gate_up.py b/omlx/patches/qwen35_moe_gate_up.py index 26daeb3fd0..0719386e19 100644 --- a/omlx/patches/qwen35_moe_gate_up.py +++ b/omlx/patches/qwen35_moe_gate_up.py @@ -1,5 +1,5 @@ # SPDX-License-Identifier: Apache-2.0 -"""Fuse Qwen3.5/3.6 MoE routed gate/up projections into one gather_qmm. +"""Fuse supported MoE routed gate/up projections into one gather_qmm. At single-token decode the routed-expert path runs three tiny ``gather_qmm`` launches per MoE layer (gate, up, down). Affine @@ -45,10 +45,17 @@ _CALL_PATCHED = False -# Loaded model classes whose module path marks a supported SwitchGLU family -# (mlx_lm qwen3_5 / qwen3_5_moe, Qwen4-Exp's inherited SwitchGLU, the omlx -# single-checkpoint MTP wrapper, and the vendored laguna module). -_FAMILY_TOKENS = ("qwen3_5", "qwen3_6", "qwen35", "qwen4_exp", "laguna") +# Loaded model classes whose module path marks a supported SwitchGLU family: +# mlx-lm Qwen3.5/3.6 and HyV3, Qwen4-Exp's inherited SwitchGLU, the oMLX +# single-checkpoint MTP wrapper, and the vendored Laguna module. +_FAMILY_TOKENS = ( + "qwen3_5", + "qwen3_6", + "qwen35", + "qwen4_exp", + "laguna", + "hy_v3", +) def _is_supported_family(model: Any) -> bool: @@ -188,7 +195,7 @@ def _ensure_call_patch() -> None: def apply_qwen35_moe_gate_up_fusion(model: Any) -> int: - """Fuse gate+up expert projections on a loaded Qwen3.5/3.6 MoE model. + """Fuse gate+up expert projections on a supported loaded MoE model. Returns the number of fused ``SwitchGLU`` instances (0 when disabled via ``OMLX_QWEN35_MOE_GATE_UP=0``, the model family is unsupported, @@ -213,7 +220,7 @@ def apply_qwen35_moe_gate_up_fusion(model: Any) -> int: # ~2/3 of the expert bytes (#2304). Drain per fused layer to bound # the transient to a single layer's worth. _sync_and_clear_cache() - logger.info("Qwen MoE gate+up fusion applied: %d layers", len(targets)) + logger.info("MoE gate+up fusion applied: %d layers", len(targets)) return len(targets) diff --git a/tests/test_qwen35_moe_gate_up.py b/tests/test_qwen35_moe_gate_up.py index b9614de657..98d36aad6f 100644 --- a/tests/test_qwen35_moe_gate_up.py +++ b/tests/test_qwen35_moe_gate_up.py @@ -1,5 +1,5 @@ # SPDX-License-Identifier: Apache-2.0 -"""Tests for the Qwen3.5/3.6 MoE gate+up fusion patch (issue #2238).""" +"""Tests for the supported MoE gate+up fusion patch (issue #2238).""" from __future__ import annotations @@ -35,14 +35,27 @@ class _FakeOtherModel: _FakeOtherModel.__module__ = "mlx_lm.models.deepseek_v3" -def _make_model(quantize=True, model_cls=_FakeQwenModel, n_blocks=2): +class _FakeHyV3Model: + pass + + +_FakeHyV3Model.__module__ = "mlx_lm.models.hy_v3" + + +def _make_model( + quantize=True, + model_cls=_FakeQwenModel, + n_blocks=2, + group_size=32, + bits=4, +): mx.random.seed(7) blocks = [] for _ in range(n_blocks): glu = SwitchGLU(HIDDEN, INTER, E) if quantize: - glu.gate_proj = glu.gate_proj.to_quantized(32, 4) - glu.up_proj = glu.up_proj.to_quantized(32, 4) + glu.gate_proj = glu.gate_proj.to_quantized(group_size, bits) + glu.up_proj = glu.up_proj.to_quantized(group_size, bits) glu.down_proj = glu.down_proj.to_quantized(32, 4) blocks.append(glu) model = model_cls() @@ -145,6 +158,24 @@ def test_laguna_family_fused_bit_exact(): assert mx.array_equal(ref, out).item() +@pytest.mark.parametrize("bits", [5, 6, 8]) +def test_hy_v3_family_fused_bit_exact(bits): + """HyV3 uses stock SwitchGLU and receives the same bit-exact fusion.""" + model = _make_model(model_cls=_FakeHyV3Model, group_size=64, bits=bits) + x = (mx.random.normal(shape=(1, 1, HIDDEN)) * 0.5).astype(mx.bfloat16) + indices = mx.random.randint(0, E, shape=(1, 1, TOPK)) + + ref = _forward_all(model, x, indices) + mx.eval(ref) + + assert apply_qwen35_moe_gate_up_fusion(model) == 2 + out = _forward_all(model, x, indices) + mx.eval(out) + + for expected, actual in zip(ref, out): + assert mx.array_equal(expected, actual).item() + + def test_qwen4_exp_family_is_eligible_for_gate_up_fusion(): model = _make_model(model_cls=_FakeQwen4Model, n_blocks=1) From bceb44e694454f3b2a9d96999b6a0368f1b90373 Mon Sep 17 00:00:00 2001 From: jundot Date: Fri, 28 Aug 2026 01:07:31 +0900 Subject: [PATCH 019/132] fix: cover GLM-5.3 oQe sparse calibration paths --- omlx/oq.py | 49 ++++++++++++++++++++++++++++++++++-- tests/test_oq.py | 65 +++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 111 insertions(+), 3 deletions(-) diff --git a/omlx/oq.py b/omlx/oq.py index c8256cef6f..b70aef600b 100644 --- a/omlx/oq.py +++ b/omlx/oq.py @@ -5078,7 +5078,7 @@ def _source_imatrix_signature( elif str(config.get("model_type", "")).lower() == "glm5_next": # GLM-5.3 needs its mHC-expanded layer walk plus the untied output-head # capture. Older caches completed without either and must not be reused. - signature["layer_walk"] = "glm5_next_hc_moe_lm_head_v3" + signature["layer_walk"] = "glm5_next_hc_moe_lm_head_v4" return signature @@ -5280,6 +5280,22 @@ def _lookup_imatrix_importance( base = tensor_name[: -len(".weight")] entry = imatrix.entries.get(base) + if entry is None and config is not None: + text_config = config.get("text_config") + text_model_type = ( + text_config.get("model_type") if isinstance(text_config, dict) else None + ) + if ( + config.get("model_type") == "glm5_next" + or text_model_type == "glm5_next_text" + ) and base.endswith(".self_attn.indexer.weights_proj"): + # The GLM-5.3 indexer feeds the same hidden-state input to wk and + # weights_proj. Short calibration sequences bypass sparse scoring + # after wk, before weights_proj is called, so its wrapper cannot + # collect a separate entry. Reuse the mathematically identical wk + # input-channel statistics instead of weakening strict coverage. + wk_base = base[: -len("weights_proj")] + "wk" + entry = imatrix.entries.get(wk_base) if entry is None: if report is not None: report["missing"].append(base) @@ -7250,7 +7266,10 @@ def __call__(self, *args, **kwargs): ) else: self._collector.collect_dense(self._name, self._module, args[0]) - return self._module(*args, **kwargs) + result = self._module(*args, **kwargs) + if args and self._name.endswith(".self_attn.q_b_proj"): + self._collector.collect_glm5_next_embed_q(self._name, result) + return result class OQImatrixCollector: @@ -7382,6 +7401,32 @@ def collect_multi(self, name: str, module, x, *, transpose: bool = True) -> None except Exception as e: logger.debug("oQe imatrix multi capture skipped for %s: %s", name, e) + def collect_glm5_next_embed_q(self, q_b_name: str, q) -> None: + """Capture the GLM-5.3 embed_q input from q_b_proj's exact output. + + Short calibration sequences take the algebraically equivalent reverse + embed_q path, whose activation width does not match the stored weight's + quantization axis. Long sparse-attention requests use the forward path + on q_b_proj's reshaped output, so collect that tensor directly without + forcing calibration past the production indexer's short-prefix bypass. + """ + embed_name = q_b_name[: -len("q_b_proj")] + "embed_q" + module = self._original_modules.get(embed_name) + if module is None or type(module).__name__ not in _OQE_MULTI_LINEAR_CLASSES: + return + try: + weight = module.weight + n_heads = int(weight.shape[0]) + in_dim = self._module_in_dim(module) + if not getattr(q, "shape", ()) or int(q.shape[-1]) != n_heads * in_dim: + return + shaped_q = q.reshape(*q.shape[:-1], n_heads, in_dim) + self.collect_multi(embed_name, module, shaped_q) + except Exception as e: + logger.debug( + "oQe GLM-5.3 embed_q capture skipped for %s: %s", embed_name, e + ) + @staticmethod def _accumulate_switch( entry: OQImatrixEntry, diff --git a/tests/test_oq.py b/tests/test_oq.py index a4224641ce..eb08ebc79a 100644 --- a/tests/test_oq.py +++ b/tests/test_oq.py @@ -1292,6 +1292,68 @@ def test_token_embedding_is_exempt_from_strict_imatrix_lookup(self): assert importance is None assert report["missing"] == [] + def test_glm5_next_indexer_weights_proj_reuses_wk_imatrix(self): + from omlx.oq import OQImatrixData, _lookup_imatrix_importance + + wk_base = "language_model.model.layers.11.self_attn.indexer.wk" + values = np.arange(64, dtype=np.float32) + 1 + imatrix = OQImatrixData( + entries={ + wk_base: OQImatrixEntry( + in_sum2=values * 4, + counts=np.array([4], dtype=np.int64), + ) + }, + metadata={}, + path="unused.npz", + ) + report = {"missing": [], "mismatched": [], "applied": []} + weights_proj = wk_base[: -len("wk")] + "weights_proj.weight" + + importance = _lookup_imatrix_importance( + imatrix, + weights_proj, + (32, 64), + config={ + "model_type": "glm5_next", + "text_config": {"model_type": "glm5_next_text"}, + }, + strict=True, + report=report, + ) + + np.testing.assert_array_equal(np.asarray(importance), values) + assert report["applied"] == [weights_proj.removesuffix(".weight")] + assert report["missing"] == [] + + def test_non_glm_weights_proj_still_requires_its_own_imatrix(self): + from omlx.oq import OQImatrixData, _lookup_imatrix_importance + + base = "model.layers.0.self_attn.indexer" + imatrix = OQImatrixData( + entries={ + f"{base}.wk": OQImatrixEntry( + in_sum2=np.ones(64, dtype=np.float32), + counts=np.ones(1, dtype=np.int64), + ) + }, + metadata={}, + path="unused.npz", + ) + report = {"missing": [], "mismatched": [], "applied": []} + + with pytest.raises(RuntimeError, match="missing entry"): + _lookup_imatrix_importance( + imatrix, + f"{base}.weights_proj.weight", + (32, 64), + config={"model_type": "deepseek_v4"}, + strict=True, + report=report, + ) + + assert report["missing"] == [f"{base}.weights_proj"] + def test_qwen4_ngram_group32_is_priced_into_budget_plan(self): from omlx.oq import _structural_quant_overrides @@ -6575,7 +6637,7 @@ def test_cache_signature_tracks_glm5_next_layer_walk(self, tmp_path): calib_dataset="test", ) - assert signature["layer_walk"] == "glm5_next_hc_moe_lm_head_v3" + assert signature["layer_walk"] == "glm5_next_hc_moe_lm_head_v4" def test_hyper_connections_and_moe_imatrix_hooks_execute(self): from omlx.patches import mlx_vlm_glm5_next_compat @@ -6590,6 +6652,7 @@ def test_hyper_connections_and_moe_imatrix_hooks_execute(self): config.text_config.n_shared_experts = 1 config.text_config.first_k_dense_replace = 1 config.text_config.mlp_layer_types = ["dense", "sparse"] + config.text_config.index_topk = 2048 model = Model(config) tokens = mx.array([[1, 2, 3, 4, 5, 6]], dtype=mx.int32) layers = model.language_model.model.layers From 62bc9d6cd7c657b80b089aedbc9c0cae57b79505 Mon Sep 17 00:00:00 2001 From: jundot Date: Fri, 28 Aug 2026 01:09:21 +0900 Subject: [PATCH 020/132] chore: bump version to 0.6.3 --- omlx/_version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/omlx/_version.py b/omlx/_version.py index 3ca6e74483..63af88769b 100644 --- a/omlx/_version.py +++ b/omlx/_version.py @@ -1 +1 @@ -__version__ = "0.6.3rc3" +__version__ = "0.6.3" From 12844b40a6db9a409fe551523dc3214caa22c1c2 Mon Sep 17 00:00:00 2001 From: williamxyl <50697245+williamxie1989@users.noreply.github.com> Date: Fri, 28 Aug 2026 00:24:52 +0800 Subject: [PATCH 021/132] fix(admin): let the Lightning MTP toggle through for Qwen3.8 Flash Next (#3200) Qwen3.8 Flash Next uses a dedicated VLM Lightning MTP path that intentionally bypasses the generic mlx-lm compatibility whitelist. Allow qwen4_exp checkpoints with embedded MTP weights through the admin compatibility and save gates. --- omlx/admin/routes.py | 14 ++++- tests/test_qwen4_exp_mtp_admin_gate.py | 83 ++++++++++++++++++++++++++ 2 files changed, 95 insertions(+), 2 deletions(-) create mode 100644 tests/test_qwen4_exp_mtp_admin_gate.py diff --git a/omlx/admin/routes.py b/omlx/admin/routes.py index f862caa09c..4c6c9bcdd7 100644 --- a/omlx/admin/routes.py +++ b/omlx/admin/routes.py @@ -704,7 +704,14 @@ def _mtp_compat_for_model(model_info: dict) -> tuple[bool, str]: model_type = cfg.get("model_type") if not _has_mtp_heads(cfg): return False, "model has no MTP heads in config" - if not _is_mtp_compatible(cfg, model_type): + # qwen4_exp (Qwen3.8 Flash Next) attaches its Lightning MTP head through + # the dedicated VLM path in omlx.utils.model_loading (vendored mlx-vlm + # qwen4_exp model + mlx_lm_mtp dispatch patch) and never goes through the + # mlx-lm ``_is_mtp_compatible`` whitelist, which gates the generic + # text-model patch. Mirroring the runtime, the admin gate accepts + # qwen4_exp and relies on the embedded ``mtp.*`` weight check below — + # the same condition the runtime path uses. + if model_type != "qwen4_exp" and not _is_mtp_compatible(cfg, model_type): return False, ( f"model_type={model_type!r} is not on the MTP whitelist " "(supported: qwen3_5*, qwen3_6*, deepseek_v4*, glm_moe_dsa, " @@ -2686,7 +2693,10 @@ async def update_model_settings( detail=f"MTP enabled but failed to read model config: {e}", ) model_type = cfg.get("model_type") - if not _is_mtp_compatible(cfg, model_type): + # qwen4_exp routes through the dedicated VLM Lightning MTP path + # (see _mtp_compat_for_model); skip the mlx-lm whitelist here but + # keep the mtp.* weight check below. + if model_type != "qwen4_exp" and not _is_mtp_compatible(cfg, model_type): raise HTTPException( status_code=400, detail=( diff --git a/tests/test_qwen4_exp_mtp_admin_gate.py b/tests/test_qwen4_exp_mtp_admin_gate.py new file mode 100644 index 0000000000..7cc06e6b7a --- /dev/null +++ b/tests/test_qwen4_exp_mtp_admin_gate.py @@ -0,0 +1,83 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Regression tests for the admin Lightning-MTP gates with qwen4_exp. + +Qwen3.8 Flash Next (``model_type == "qwen4_exp"``) attaches its Lightning +MTP head through the dedicated VLM path in ``omlx.utils.model_loading`` +(vendored mlx-vlm qwen4_exp model + ``mlx_lm_mtp`` dispatch patch) and is +deliberately absent from the mlx-lm ``_is_mtp_compatible`` whitelist, which +is the runtime gate for the *generic* text-model patch. + +Both admin gates reused that whitelist, so the Lightning MTP toggle reported +"model_type='qwen4_exp' is not on the MTP whitelist" and saving the setting +returned 400 even though the runtime supports the head as shipped by the +#3174 converter. The admin gates must instead accept qwen4_exp and fall +through to the embedded ``mtp.*`` weight check — the same condition the +runtime path applies. +""" + +import json + +import pytest + +from omlx.admin.routes import _mtp_compat_for_model + +QWEN4_EXP_CONFIG = { + "model_type": "qwen4_exp", + "text_config": { + "model_type": "qwen4_exp_text", + "num_hidden_layers": 48, + "mtp_num_hidden_layers": 1, + "mtp": {"hybrid": True, "num_hidden_layers": 1}, + }, +} + + +def _make_checkpoint(tmp_path, config, mtp_weights, name="Qwen3.8-Flash-Next"): + model_dir = tmp_path / name + model_dir.mkdir() + (model_dir / "config.json").write_text(json.dumps(config)) + weight_map = {"model.layers.0.mlp.down.weight": "model.safetensors"} + if mtp_weights: + weight_map["mtp.fc_hidden.weight"] = "model.safetensors" + (model_dir / "model.safetensors.index.json").write_text( + json.dumps({"metadata": {}, "weight_map": weight_map}) + ) + return model_dir + + +class TestMtpCompatForModelQwen4Exp: + def test_qwen4_exp_with_embedded_mtp_weights_is_compatible(self, tmp_path): + model_dir = _make_checkpoint(tmp_path, QWEN4_EXP_CONFIG, mtp_weights=True) + ok, reason = _mtp_compat_for_model({"model_path": str(model_dir)}) + assert ok, f"qwen4_exp with mtp.* weights must pass: {reason}" + assert reason == "" + + def test_qwen4_exp_without_mtp_weights_is_blocked_on_weights(self, tmp_path): + model_dir = _make_checkpoint(tmp_path, QWEN4_EXP_CONFIG, mtp_weights=False) + ok, reason = _mtp_compat_for_model({"model_path": str(model_dir)}) + assert not ok + # The rejection must come from the missing-weight check, not the + # whitelist: the weights check is what the runtime path enforces. + assert "whitelist" not in reason + assert "mtp.* tensors" in reason + + def test_qwen4_exp_without_mtp_heads_is_blocked(self, tmp_path): + config = {"model_type": "qwen4_exp", "text_config": {}} + model_dir = _make_checkpoint(tmp_path, config, mtp_weights=True) + ok, reason = _mtp_compat_for_model({"model_path": str(model_dir)}) + assert not ok + assert "no MTP heads" in reason + + def test_unsupported_model_type_still_hits_the_whitelist(self, tmp_path): + config = {"model_type": "llama", "mtp_num_hidden_layers": 1} + model_dir = _make_checkpoint(tmp_path, config, mtp_weights=True) + ok, reason = _mtp_compat_for_model({"model_path": str(model_dir)}) + assert not ok + assert "not on the MTP whitelist" in reason + + @pytest.mark.parametrize("model_type", ["qwen3_5_moe", "qwen3_6", "deepseek_v4"]) + def test_generic_whitelisted_types_still_pass(self, tmp_path, model_type): + config = {"model_type": model_type, "mtp_num_hidden_layers": 1} + model_dir = _make_checkpoint(tmp_path, config, mtp_weights=True, name="m") + ok, reason = _mtp_compat_for_model({"model_path": str(model_dir)}) + assert ok, f"{model_type} must remain compatible: {reason}" From 19f9125e68fbc06dd044d5ffbb43819f3897a734 Mon Sep 17 00:00:00 2001 From: jundot Date: Fri, 28 Aug 2026 01:34:40 +0900 Subject: [PATCH 022/132] fix: align Qwen4 Lightning MTP weight detection (#3200) --- omlx/admin/routes.py | 19 ++++- .../mlx_vlm/models/qwen4_exp/language.py | 38 +-------- omlx/utils/model_loading.py | 79 ++++++++++++------- tests/test_admin_model_settings.py | 58 ++++++++++++++ tests/test_mlx_vlm_qwen4_exp_compat.py | 35 ++++++++ tests/test_model_loading.py | 38 ++++++++- tests/test_qwen4_exp_mtp_admin_gate.py | 23 +++++- 7 files changed, 223 insertions(+), 67 deletions(-) diff --git a/omlx/admin/routes.py b/omlx/admin/routes.py index 4c6c9bcdd7..94932b2593 100644 --- a/omlx/admin/routes.py +++ b/omlx/admin/routes.py @@ -675,8 +675,9 @@ def _mtp_compat_for_model(model_info: dict) -> tuple[bool, str]: converter actually preserved the MTP tensors, using the loader's ``_checkpoint_has_mtp_weights`` so native nextn layouts (``model.layers..*``, e.g. GLM-5.2) count as - present (issue #2326). Default mlx-lm converters strip ``mtp.*``; - PR 990 ships a separate path that keeps them. + present (issue #2326). Qwen4-Exp uses its narrower runtime detector, + which accepts only embedded ``mtp.*`` tensors. Default mlx-lm converters + strip ``mtp.*``; PR 990 ships a separate path that keeps them. """ import json from pathlib import Path @@ -727,6 +728,11 @@ def _mtp_compat_for_model(model_info: dict) -> tuple[bool, str]: "MTPLX side-car detected but not imported. Import it to " "merge the MTP head into the checkpoint index." ) + if model_type == "qwen4_exp": + return False, ( + "Qwen4-Exp Lightning MTP requires embedded mtp.* tensors; " + "native nextn layers are not supported by its dedicated runtime." + ) return False, ( "Config declares MTP layers but the weight files contain neither " "mtp.* tensors nor native nextn layers. Re-convert from HF with a " @@ -2708,6 +2714,15 @@ async def update_model_settings( ), ) if not _checkpoint_has_mtp_weights(entry.model_path): + if model_type == "qwen4_exp": + raise HTTPException( + status_code=400, + detail=( + "Qwen4-Exp Lightning MTP requires embedded mtp.* " + "tensors; native nextn layers are not supported by " + "its dedicated runtime." + ), + ) raise HTTPException( status_code=400, detail=( 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 523de27eed..31255b5433 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 @@ -53,41 +53,9 @@ def configure_mtp_runtime( checkpoint_prefix = None if enabled: - model_path = Path(model_path) - index_path = model_path / "model.safetensors.index.json" - if index_path.is_file(): - try: - weight_map = json.loads(index_path.read_text()).get("weight_map") or {} - except (OSError, ValueError): - weight_map = {} - for prefix in ( - "mtp.", - "language_model.mtp.", - "model.mtp.", - "model.language_model.mtp.", - ): - if any(key.startswith(prefix) for key in weight_map): - checkpoint_prefix = prefix - break - else: - try: - import safetensors - - for shard in sorted(model_path.glob("*.safetensors")): - with safetensors.safe_open(str(shard), framework="numpy") as file: - for prefix in ( - "mtp.", - "language_model.mtp.", - "model.mtp.", - "model.language_model.mtp.", - ): - if any(key.startswith(prefix) for key in file.keys()): - checkpoint_prefix = prefix - break - if checkpoint_prefix is not None: - break - except Exception: - checkpoint_prefix = None + from omlx.utils.model_loading import _checkpoint_qwen4_mtp_weight_prefix + + checkpoint_prefix = _checkpoint_qwen4_mtp_weight_prefix(model_path) _MTP_RUNTIME = Qwen4ExpMTPRuntime( enabled=bool(enabled and checkpoint_prefix), diff --git a/omlx/utils/model_loading.py b/omlx/utils/model_loading.py index d384ef5b80..49b1da3148 100644 --- a/omlx/utils/model_loading.py +++ b/omlx/utils/model_loading.py @@ -1002,60 +1002,83 @@ def _nextn_weight_prefixes(model_path: str | Path) -> tuple[str, ...]: config = json.loads((Path(model_path) / "config.json").read_text()) except Exception: return () + if config.get("model_type") == "qwen4_exp": + # The dedicated Qwen4 runtime constructs a root-level MTP module and + # can bind only the embedded mtp.* layouts. Extra nextn decoder layers + # must not make generic callers report this checkpoint as compatible. + return () return _nextn_weight_prefixes_from_config(config) -def _checkpoint_has_mtp_weights(model_path: str | Path) -> bool: - """True iff the checkpoint at *model_path* ships any MTP weight tensor. - - Matches both the ``mtp.*`` naming and the nextn layout (extra decoder - layers past ``num_hidden_layers``, see ``_nextn_weight_prefixes``). - - Some Qwen3.6 MoE VLM exports declare ``mtp_num_hidden_layers > 0`` in - ``config.json`` but strip the MTP weights during conversion (e.g. - ``unsloth/Qwen3.6-35B-A3B-UD-MLX-*bit``). Attaching ``MTPModule`` for - such a checkpoint causes mlx-vlm's strict ``load_weights`` to fail with - "Missing N parameters: language_model.mtp.*", the engine falls back to - LLM, and vision is silently dropped (issue #1426). - - Reads ``model.safetensors.index.json`` when present (no shard I/O). - Falls back to the first safetensors shard's metadata header. Returns - False when neither resolves — callers treat that as "no MTP weights" - (the conservative choice: skip MTPModule attachment). - """ +def _checkpoint_weight_prefix( + model_path: str | Path, + prefixes: tuple[str, ...], +) -> str | None: + """Return the first supported prefix present in a checkpoint.""" p = Path(model_path) if not p.is_dir(): - return False - - prefixes = _MTP_WEIGHT_PREFIXES + _nextn_weight_prefixes(p) + return None index_path = p / "model.safetensors.index.json" if index_path.exists(): try: data = json.loads(index_path.read_text()) weight_map = data.get("weight_map") or {} - return any(k.startswith(prefixes) for k in weight_map) + for prefix in prefixes: + if any(key.startswith(prefix) for key in weight_map): + return prefix + return None except Exception as e: logger.debug("Failed to read %s for mtp weight scan: %s", index_path, e) shards = sorted(p.glob("*.safetensors")) if not shards: - return False + return None try: import safetensors except Exception as e: logger.debug("safetensors import failed for mtp weight scan: %s", e) - return False + return None for shard in shards: try: with safetensors.safe_open(str(shard), framework="numpy") as f: - for k in f.keys(): - if k.startswith(prefixes): - return True + keys = tuple(f.keys()) + for prefix in prefixes: + if any(key.startswith(prefix) for key in keys): + return prefix except Exception as e: logger.debug("Failed to read %s header for mtp weight scan: %s", shard, e) - return False + return None + + +def _checkpoint_qwen4_mtp_weight_prefix(model_path: str | Path) -> str | None: + """Return the embedded MTP prefix supported by the Qwen4 runtime.""" + return _checkpoint_weight_prefix(model_path, _MTP_WEIGHT_PREFIXES) + + +def _checkpoint_has_mtp_weights(model_path: str | Path) -> bool: + """True iff the checkpoint at *model_path* ships any MTP weight tensor. + + Matches both the ``mtp.*`` naming and compatible nextn layouts (extra + decoder layers past ``num_hidden_layers``, see ``_nextn_weight_prefixes``). + Qwen4-Exp is intentionally restricted to ``mtp.*`` because its dedicated + runtime cannot bind native nextn layers. + + Some Qwen3.6 MoE VLM exports declare ``mtp_num_hidden_layers > 0`` in + ``config.json`` but strip the MTP weights during conversion (e.g. + ``unsloth/Qwen3.6-35B-A3B-UD-MLX-*bit``). Attaching ``MTPModule`` for + such a checkpoint causes mlx-vlm's strict ``load_weights`` to fail with + "Missing N parameters: language_model.mtp.*", the engine falls back to + LLM, and vision is silently dropped (issue #1426). + + Reads ``model.safetensors.index.json`` when present (no shard I/O). + Falls back to the first safetensors shard's metadata header. Returns + False when neither resolves — callers treat that as "no MTP weights" + (the conservative choice: skip MTPModule attachment). + """ + prefixes = _MTP_WEIGHT_PREFIXES + _nextn_weight_prefixes(model_path) + return _checkpoint_weight_prefix(model_path, prefixes) is not None def _is_mtp_compatible(config: dict, model_type: str | None) -> bool: diff --git a/tests/test_admin_model_settings.py b/tests/test_admin_model_settings.py index b211ed6d0e..31c289a5d3 100644 --- a/tests/test_admin_model_settings.py +++ b/tests/test_admin_model_settings.py @@ -1,6 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 """Tests for load-failure invalidation in admin model settings.""" +import json from unittest.mock import AsyncMock, MagicMock, patch import pytest @@ -27,6 +28,26 @@ def _failed_pool() -> tuple[EnginePool, EngineEntry]: return pool, entry +def _write_qwen4_mtp_checkpoint(tmp_path, *, embedded_mtp: bool) -> None: + config = { + "model_type": "qwen4_exp", + "text_config": { + "num_hidden_layers": 48, + "mtp_num_hidden_layers": 1, + "num_nextn_predict_layers": 1, + }, + } + (tmp_path / "config.json").write_text(json.dumps(config)) + weight_key = ( + "mtp.fc_hidden.weight" + if embedded_mtp + else "model.layers.48.self_attn.q_proj.weight" + ) + (tmp_path / "model.safetensors.index.json").write_text( + json.dumps({"weight_map": {weight_key: "model.safetensors"}}) + ) + + async def _update_settings( pool: EnginePool, settings: ModelSettings, @@ -197,6 +218,43 @@ async def test_qwen4_ple_ssd_offload_is_ignored_for_other_models(): assert settings.qwen4_ple_ssd_offload is False +@pytest.mark.asyncio +async def test_qwen4_mtp_setting_accepts_embedded_head(tmp_path): + _write_qwen4_mtp_checkpoint(tmp_path, embedded_mtp=True) + pool, entry = _failed_pool() + entry.model_path = str(tmp_path) + entry.config_model_type = "qwen4_exp" + settings = ModelSettings() + + await _update_settings( + pool, + settings, + admin_routes.ModelSettingsRequest(mtp_enabled=True), + ) + + assert settings.mtp_enabled is True + + +@pytest.mark.asyncio +async def test_qwen4_mtp_setting_rejects_nextn_only_layout(tmp_path): + _write_qwen4_mtp_checkpoint(tmp_path, embedded_mtp=False) + pool, entry = _failed_pool() + entry.model_path = str(tmp_path) + entry.config_model_type = "qwen4_exp" + settings = ModelSettings() + + with pytest.raises(admin_routes.HTTPException) as exc_info: + await _update_settings( + pool, + settings, + admin_routes.ModelSettingsRequest(mtp_enabled=True), + ) + + assert exc_info.value.status_code == 400 + assert "native nextn layers are not supported" in exc_info.value.detail + assert settings.mtp_enabled is False + + @pytest.mark.asyncio async def test_qwen_ane_prefill_rejects_invalid_block_size(): pool, entry = _failed_pool() diff --git a/tests/test_mlx_vlm_qwen4_exp_compat.py b/tests/test_mlx_vlm_qwen4_exp_compat.py index 8430cd8efc..b29a8e881d 100644 --- a/tests/test_mlx_vlm_qwen4_exp_compat.py +++ b/tests/test_mlx_vlm_qwen4_exp_compat.py @@ -513,6 +513,41 @@ def test_qwen4_verify_matches_singleton_greedy_and_rolls_back_qsa(): assert qsa_cache.index_position_ids.shape[-1] == 4 +def test_qwen4_lightning_mtp_rejects_nextn_only_layout(tmp_path): + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp.language import configure_mtp_runtime + + (tmp_path / "config.json").write_text( + json.dumps( + { + "model_type": "qwen4_exp", + "text_config": { + "num_hidden_layers": 2, + "num_nextn_predict_layers": 1, + }, + } + ), + encoding="utf-8", + ) + (tmp_path / "model.safetensors.index.json").write_text( + json.dumps( + { + "weight_map": { + "model.layers.2.self_attn.q_proj.weight": "model.safetensors" + } + } + ), + encoding="utf-8", + ) + + runtime = configure_mtp_runtime(tmp_path, enabled=True) + try: + assert runtime.enabled is False + assert runtime.checkpoint_prefix is None + finally: + configure_mtp_runtime(tmp_path, enabled=False) + + def test_qwen4_lightning_mtp_fusion_and_runtime_attachment(tmp_path): config = _tiny_config() from mlx_vlm.models.qwen4_exp.language import ( diff --git a/tests/test_model_loading.py b/tests/test_model_loading.py index 2cc837e8aa..6dd0a0d547 100644 --- a/tests/test_model_loading.py +++ b/tests/test_model_loading.py @@ -613,7 +613,10 @@ def test_returns_true_when_index_has_language_model_mtp(self, tmp_path): }, ) assert model_loading._checkpoint_has_mtp_weights(str(tmp_path)) is True - + assert ( + model_loading._checkpoint_qwen4_mtp_weight_prefix(str(tmp_path)) + == "language_model.mtp." + ) def test_returns_true_when_index_has_bare_mtp(self, tmp_path): self._write_index( @@ -621,6 +624,9 @@ def test_returns_true_when_index_has_bare_mtp(self, tmp_path): {"mtp.layers.0.self_attn.q_proj.weight": "model.safetensors"}, ) assert model_loading._checkpoint_has_mtp_weights(str(tmp_path)) is True + assert ( + model_loading._checkpoint_qwen4_mtp_weight_prefix(str(tmp_path)) == "mtp." + ) def test_returns_true_when_index_has_model_language_model_mtp(self, tmp_path): # mlx-vlm HF-source layout before sanitize-time remap (oQ writes this). @@ -629,6 +635,10 @@ def test_returns_true_when_index_has_model_language_model_mtp(self, tmp_path): {"model.language_model.mtp.norm.weight": "model.safetensors"}, ) assert model_loading._checkpoint_has_mtp_weights(str(tmp_path)) is True + assert ( + model_loading._checkpoint_qwen4_mtp_weight_prefix(str(tmp_path)) + == "model.language_model.mtp." + ) def test_returns_false_when_index_lacks_mtp(self, tmp_path): # Unsloth Qwen3.6 UD MLX layout: vision_tower + language_model.model.* @@ -642,6 +652,7 @@ def test_returns_false_when_index_lacks_mtp(self, tmp_path): }, ) assert model_loading._checkpoint_has_mtp_weights(str(tmp_path)) is False + assert model_loading._checkpoint_qwen4_mtp_weight_prefix(str(tmp_path)) is None @pytest.mark.parametrize( "prefix", @@ -667,6 +678,27 @@ def test_returns_true_for_nextn_layout(self, tmp_path, prefix): }, ) assert model_loading._checkpoint_has_mtp_weights(str(tmp_path)) is True + assert model_loading._checkpoint_qwen4_mtp_weight_prefix(str(tmp_path)) is None + + def test_returns_false_for_qwen4_nextn_layout(self, tmp_path): + import json as _json + + (tmp_path / "config.json").write_text( + _json.dumps( + { + "model_type": "qwen4_exp", + "text_config": { + "num_hidden_layers": 78, + "num_nextn_predict_layers": 1, + }, + } + ) + ) + self._write_index( + tmp_path, + {"model.layers.78.eh_proj.weight": "model.safetensors"}, + ) + assert model_loading._checkpoint_has_mtp_weights(str(tmp_path)) is False def test_returns_false_for_nextn_config_without_weights(self, tmp_path): # Config declares nextn layers but the checkpoint stripped them. @@ -715,6 +747,10 @@ def test_returns_true_when_later_shard_has_mtp(self, tmp_path): ) assert model_loading._checkpoint_has_mtp_weights(str(tmp_path)) is True + assert ( + model_loading._checkpoint_qwen4_mtp_weight_prefix(str(tmp_path)) + == "language_model.mtp." + ) class TestExpandPerLayerQuantKeys: diff --git a/tests/test_qwen4_exp_mtp_admin_gate.py b/tests/test_qwen4_exp_mtp_admin_gate.py index 7cc06e6b7a..8aca143891 100644 --- a/tests/test_qwen4_exp_mtp_admin_gate.py +++ b/tests/test_qwen4_exp_mtp_admin_gate.py @@ -32,13 +32,21 @@ } -def _make_checkpoint(tmp_path, config, mtp_weights, name="Qwen3.8-Flash-Next"): +def _make_checkpoint( + tmp_path, + config, + mtp_weights, + name="Qwen3.8-Flash-Next", + nextn_weights=False, +): model_dir = tmp_path / name model_dir.mkdir() (model_dir / "config.json").write_text(json.dumps(config)) weight_map = {"model.layers.0.mlp.down.weight": "model.safetensors"} if mtp_weights: weight_map["mtp.fc_hidden.weight"] = "model.safetensors" + if nextn_weights: + weight_map["model.layers.48.self_attn.q_proj.weight"] = "model.safetensors" (model_dir / "model.safetensors.index.json").write_text( json.dumps({"metadata": {}, "weight_map": weight_map}) ) @@ -61,6 +69,19 @@ def test_qwen4_exp_without_mtp_weights_is_blocked_on_weights(self, tmp_path): assert "whitelist" not in reason assert "mtp.* tensors" in reason + def test_qwen4_exp_with_only_nextn_weights_is_blocked(self, tmp_path): + config = json.loads(json.dumps(QWEN4_EXP_CONFIG)) + config["text_config"]["num_nextn_predict_layers"] = 1 + model_dir = _make_checkpoint( + tmp_path, + config, + mtp_weights=False, + nextn_weights=True, + ) + ok, reason = _mtp_compat_for_model({"model_path": str(model_dir)}) + assert not ok + assert "native nextn layers are not supported" in reason + def test_qwen4_exp_without_mtp_heads_is_blocked(self, tmp_path): config = {"model_type": "qwen4_exp", "text_config": {}} model_dir = _make_checkpoint(tmp_path, config, mtp_weights=True) From 85708e4b9a585df42241c826b6be2b4dba018406 Mon Sep 17 00:00:00 2001 From: jundot Date: Fri, 28 Aug 2026 01:35:32 +0900 Subject: [PATCH 023/132] chore: finalize 0.6.3 release From a20ec09d6a0ca68a162c8ced9f12f5de027d9c2f Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Thu, 27 Aug 2026 17:04:20 +0000 Subject: [PATCH 024/132] formula: bump to 0.6.3 --- Formula/omlx.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Formula/omlx.rb b/Formula/omlx.rb index d28365edb9..46db2ab6e0 100644 --- a/Formula/omlx.rb +++ b/Formula/omlx.rb @@ -3,8 +3,8 @@ class Omlx < Formula desc "LLM inference server optimized for Apple Silicon" homepage "https://github.com/jundot/omlx" - url "https://github.com/jundot/omlx/archive/refs/tags/v0.6.3rc3.tar.gz" - sha256 "1d08ff4585eb796f34f56d266b69cae65b51a48d98a4b213caca094d7c82a839" + url "https://github.com/jundot/omlx/archive/refs/tags/v0.6.3.tar.gz" + sha256 "3a5588c09b086c5064604165ca23c4d61eb94c2003cd236f3febd8a53cc045cb" license "Apache-2.0" head "https://github.com/jundot/omlx.git", branch: "main" From 701a6cc70f72e0d82809a351e39e5ca74d2ce961 Mon Sep 17 00:00:00 2001 From: e-Evolution Date: Sat, 29 Aug 2026 04:04:33 -0600 Subject: [PATCH 025/132] fix: isolate cross-engine patches between DFlash and Lightning MTP (#3285) Compose the shared Qwen class patches so DFlash and Lightning MTP keep their own call paths, and scope the Qwen3.5 VLM runtime patch to exact instances.\n\nFixes #2972 --- omlx/patches/dflash_lifecycle.py | 54 ++++++++++++++++++- omlx/patches/mlx_lm_mtp/qwen35_model.py | 25 ++++++++- .../patches/mlx_vlm_mtp/qwen35_vlm_runtime.py | 12 +++++ 3 files changed, 88 insertions(+), 3 deletions(-) diff --git a/omlx/patches/dflash_lifecycle.py b/omlx/patches/dflash_lifecycle.py index f636521337..18b5762ef7 100644 --- a/omlx/patches/dflash_lifecycle.py +++ b/omlx/patches/dflash_lifecycle.py @@ -65,6 +65,20 @@ def _wrap_installer(mod: Any, fn_name: str, flag_name: str) -> bool: def wrapped(module_target: Any) -> Any: cls = type(module_target) + current = cls.__dict__.get("__call__") + if getattr(cls, flag_name, False) and getattr( + current, "_omlx_mtp_call_marker", False + ): + # A Native-MTP self-heal replaced dflash's hook while the + # idempotency flag stayed set (issue #2972): dflash's installer + # would skip re-installing and the engine would run without its + # speculative hook. Clear the stale flag and re-snapshot the + # current (MTP) __call__ as the base to restore/fall back to. + try: + delattr(cls, flag_name) + except AttributeError: + pass + _DFLASH_BACKUP[cls] = {"call": current, "flag": flag_name} if not getattr(cls, flag_name, False): # First time dflash installs on this class — snapshot the # current __call__ so restore can put it back unchanged. @@ -105,14 +119,50 @@ def _install_batch_cache_guard(cls: type) -> None: def guarded_call( self: Any, x: Any, mask: Any = None, cache: Any = None, **kwargs: Any ) -> Any: - if isinstance(getattr(cache, "offset", None), mx.array): - return pre_dflash_call(self, x, mask=mask, cache=cache, **kwargs) + # Resolve the fallback base dynamically: a Native-MTP load may + # legitimately swap the non-dflash implementation underneath this + # guard while a DFlash engine stays resident (issue #2972). + live = _DFLASH_BACKUP.get(cls) + base = live["call"] if live is not None else pre_dflash_call + if kwargs.get("n_confirmed") or isinstance( + getattr(cache, "offset", None), mx.array + ): + return base(self, x, mask=mask, cache=cache, **kwargs) return dflash_call(self, x, mask=mask, cache=cache, **kwargs) guarded_call._omlx_dflash_batch_guard = True # type: ignore[attr-defined] cls.__call__ = guarded_call # type: ignore[method-assign] +def dflash_owns_call(cls: type) -> bool: + """True iff the armed batch-cache guard currently owns ``cls.__call__``.""" + return getattr(cls.__dict__.get("__call__"), "_omlx_dflash_batch_guard", False) + + +def get_backup_base(cls: type) -> Any: + """Return the non-dflash base ``__call__`` recorded for ``cls``, if any.""" + info = _DFLASH_BACKUP.get(cls) + return None if info is None else info["call"] + + +def swap_backup_base(cls: type, new_call: Any) -> bool: + """Swap the non-dflash base implementation under an armed guard. + + Used by the Native-MTP self-heal (issue #2972): instead of clobbering + the dflash guard on a shared class, the MTP patch installs its + ``__call__`` as the guard's fallback base. DFlash traffic (int-offset + caches, no ``n_confirmed``) keeps the speculative hook; everything + else — batch caches and MTP verify forwards — runs the new base. + ``restore_dflash_class_patches()`` then restores this base, keeping + MTP ownership intact after the DFlash engine stops. + """ + info = _DFLASH_BACKUP.get(cls) + if info is None: + return False + info["call"] = new_call + return True + + def install_dflash_lifecycle_wrap() -> bool: """Monkey-patch dflash's hook installers to record pre-dflash class state. diff --git a/omlx/patches/mlx_lm_mtp/qwen35_model.py b/omlx/patches/mlx_lm_mtp/qwen35_model.py index 08731c7ff9..ffdd201a83 100644 --- a/omlx/patches/mlx_lm_mtp/qwen35_model.py +++ b/omlx/patches/mlx_lm_mtp/qwen35_model.py @@ -238,6 +238,23 @@ def _patch_gated_delta_net(q35: Any) -> None: if _is_our_method(cls, "__call__", "_omlx_mtp_call_marker"): return + # dflash coexistence (issue #2972): if the dflash batch-cache guard owns + # ``cls.__call__``, do not clobber it — that silently strips the resident + # DFlash engine's speculative hook and its generations degenerate into + # repetition loops. Instead install our body as the guard's fallback + # base: dflash traffic keeps its hook, MTP/batched traffic gets ours. + try: + from ..dflash_lifecycle import ( + dflash_owns_call, + get_backup_base, + swap_backup_base, + ) + except ImportError: + dflash_owns_call = None # type: ignore[assignment] + if dflash_owns_call is not None and dflash_owns_call(cls): + if getattr(get_backup_base(cls), "_omlx_mtp_call_marker", False): + return # our body already sits under the dflash guard + import mlx.core as mx import mlx.nn as nn from mlx.nn.layers.distributed import sum_gradients @@ -356,7 +373,13 @@ def __call__( cls._process_chunk = _process_chunk __call__._omlx_mtp_call_marker = True - cls.__call__ = __call__ + if dflash_owns_call is not None and dflash_owns_call(cls): + # Compose with the armed dflash guard instead of replacing it + # (issue #2972): our body becomes the guard's fallback base. + if not swap_backup_base(cls, __call__): + cls.__call__ = __call__ + else: + cls.__call__ = __call__ # --------------------------------------------------------------------------- diff --git a/omlx/patches/mlx_vlm_mtp/qwen35_vlm_runtime.py b/omlx/patches/mlx_vlm_mtp/qwen35_vlm_runtime.py index 0130170a30..83687c07c8 100644 --- a/omlx/patches/mlx_vlm_mtp/qwen35_vlm_runtime.py +++ b/omlx/patches/mlx_vlm_mtp/qwen35_vlm_runtime.py @@ -273,6 +273,12 @@ def __init__(self, args, config=None): from . import is_mtp_attach_enabled from ..mlx_lm_mtp import is_mtp_active + if type(self) is not cls: + # Subclasses (e.g. the qwen4_exp vendor LanguageModel, which + # inherits from this class) own their MTP wiring; running the + # Qwen3.5 attach here would bolt a q35 MTPModule onto a + # foreign architecture (issue #2972, reverse leg). + return original_init(self, args, config) original_init(self, args, config) # Attach MTPModule when the config declares MTP heads so mlx-vlm's # load_weights (which skips Model.sanitize for is_mlx_format @@ -314,6 +320,12 @@ def __call__(self, inputs, inputs_embeds=None, mask=None, cache=None, **kwargs): is accepted and discarded — the mlx-vlm path uses post-hoc ``rollback_speculative_cache`` instead of a confirmed/draft split. """ + if type(self) is not cls: + # Subclasses (qwen4_exp vendor) reach here via super().__call__ + # and implement their own return_hidden / capture contract. + # Reshaping their kwargs here collapses the raw hyper-stream + # hidden that Qwen4 Lightning MTP requires (issue #2972). + return original_call(self, inputs, inputs_embeds, mask, cache, **kwargs) return_hidden = kwargs.pop("return_hidden", False) return_shared_kv = kwargs.pop("return_shared_kv", False) kwargs.pop("n_confirmed", None) From 5463c0f4fd10f432b98bd0d7d904afdc024cba77 Mon Sep 17 00:00:00 2001 From: jundot Date: Sat, 29 Aug 2026 19:42:09 +0900 Subject: [PATCH 026/132] fix: harden DFlash and Lightning MTP patch composition Keep the DFlash guard installed during Lightning MTP repatching and cover DFlash, Qwen4, and cross-family isolation regressions. Refs #3285 --- omlx/patches/dflash_lifecycle.py | 48 ++++----- omlx/patches/mlx_lm_mtp/qwen35_model.py | 24 ++--- tests/test_dflash_lifecycle.py | 137 +++++++++++++++++++++++- tests/test_mlx_vlm_qwen4_exp_compat.py | 53 +++++++++ tests/test_vlm_mtp.py | 54 ++++++++++ 5 files changed, 269 insertions(+), 47 deletions(-) diff --git a/omlx/patches/dflash_lifecycle.py b/omlx/patches/dflash_lifecycle.py index 18b5762ef7..f20860edcb 100644 --- a/omlx/patches/dflash_lifecycle.py +++ b/omlx/patches/dflash_lifecycle.py @@ -36,6 +36,7 @@ from __future__ import annotations import logging +from contextlib import suppress from typing import Any import mlx.core as mx @@ -69,15 +70,13 @@ def wrapped(module_target: Any) -> Any: if getattr(cls, flag_name, False) and getattr( current, "_omlx_mtp_call_marker", False ): - # A Native-MTP self-heal replaced dflash's hook while the + # A Lightning MTP self-heal replaced dflash's hook while the # idempotency flag stayed set (issue #2972): dflash's installer # would skip re-installing and the engine would run without its # speculative hook. Clear the stale flag and re-snapshot the # current (MTP) __call__ as the base to restore/fall back to. - try: + with suppress(AttributeError): delattr(cls, flag_name) - except AttributeError: - pass _DFLASH_BACKUP[cls] = {"call": current, "flag": flag_name} if not getattr(cls, flag_name, False): # First time dflash installs on this class — snapshot the @@ -119,7 +118,7 @@ def _install_batch_cache_guard(cls: type) -> None: def guarded_call( self: Any, x: Any, mask: Any = None, cache: Any = None, **kwargs: Any ) -> Any: - # Resolve the fallback base dynamically: a Native-MTP load may + # Resolve the fallback base dynamically: a Lightning MTP load may # legitimately swap the non-dflash implementation underneath this # guard while a DFlash engine stays resident (issue #2972). live = _DFLASH_BACKUP.get(cls) @@ -134,33 +133,24 @@ def guarded_call( cls.__call__ = guarded_call # type: ignore[method-assign] -def dflash_owns_call(cls: type) -> bool: - """True iff the armed batch-cache guard currently owns ``cls.__call__``.""" - return getattr(cls.__dict__.get("__call__"), "_omlx_dflash_batch_guard", False) - - -def get_backup_base(cls: type) -> Any: - """Return the non-dflash base ``__call__`` recorded for ``cls``, if any.""" +def get_dflash_guard_base(cls: type) -> Any | None: + """Return the fallback base owned by an armed dflash guard.""" + current = cls.__dict__.get("__call__") + if not getattr(current, "_omlx_dflash_batch_guard", False): + return None info = _DFLASH_BACKUP.get(cls) - return None if info is None else info["call"] - + if info is None: + raise RuntimeError("dflash guard has no fallback base") + return info["call"] -def swap_backup_base(cls: type, new_call: Any) -> bool: - """Swap the non-dflash base implementation under an armed guard. - Used by the Native-MTP self-heal (issue #2972): instead of clobbering - the dflash guard on a shared class, the MTP patch installs its - ``__call__`` as the guard's fallback base. DFlash traffic (int-offset - caches, no ``n_confirmed``) keeps the speculative hook; everything - else — batch caches and MTP verify forwards — runs the new base. - ``restore_dflash_class_patches()`` then restores this base, keeping - MTP ownership intact after the DFlash engine stops. - """ +def set_dflash_guard_base(cls: type, new_call: Any) -> None: + """Replace the fallback base under an armed dflash guard.""" + current = cls.__dict__.get("__call__") info = _DFLASH_BACKUP.get(cls) - if info is None: - return False + if not getattr(current, "_omlx_dflash_batch_guard", False) or info is None: + raise RuntimeError("dflash guard state changed during MTP patching") info["call"] = new_call - return True def install_dflash_lifecycle_wrap() -> bool: @@ -229,10 +219,8 @@ def restore_dflash_class_patches() -> None: continue flag = info["flag"] if flag in cls.__dict__: - try: + with suppress(AttributeError): delattr(cls, flag) - except AttributeError: - pass restored += 1 _DFLASH_BACKUP.clear() diff --git a/omlx/patches/mlx_lm_mtp/qwen35_model.py b/omlx/patches/mlx_lm_mtp/qwen35_model.py index ffdd201a83..2540b8e4e6 100644 --- a/omlx/patches/mlx_lm_mtp/qwen35_model.py +++ b/omlx/patches/mlx_lm_mtp/qwen35_model.py @@ -1,5 +1,5 @@ # SPDX-License-Identifier: Apache-2.0 -"""Monkey-patch for ml-explore/mlx-lm PR #990 — Qwen3.5/3.6 native MTP. +"""Monkey-patch for ml-explore/mlx-lm PR #990 — Qwen3.5/3.6 Lightning MTP. Adds an MTP head to ``mlx_lm.models.qwen3_5.TextModel`` (the language-model half) and a pass-through on ``mlx_lm.models.qwen3_5.Model`` (the VLM-outer @@ -51,6 +51,7 @@ import logging from typing import Any, Optional +from ..dflash_lifecycle import get_dflash_guard_base, set_dflash_guard_base from . import prompt_priming logger = logging.getLogger(__name__) @@ -60,7 +61,7 @@ def _is_our_method(cls: Any, attr: str, marker: str) -> bool: Used as a self-healing idempotency check: when another patch (e.g. dflash's speculative hook) overwrites ``__call__`` between two - Native-MTP loads in the same process, the marker disappears and the + Lightning MTP loads in the same process, the marker disappears and the caller knows to re-apply. Reading from ``cls.__dict__`` instead of ``getattr`` avoids resolving inherited attributes — only what is actually defined on this class counts. @@ -243,17 +244,9 @@ def _patch_gated_delta_net(q35: Any) -> None: # DFlash engine's speculative hook and its generations degenerate into # repetition loops. Instead install our body as the guard's fallback # base: dflash traffic keeps its hook, MTP/batched traffic gets ours. - try: - from ..dflash_lifecycle import ( - dflash_owns_call, - get_backup_base, - swap_backup_base, - ) - except ImportError: - dflash_owns_call = None # type: ignore[assignment] - if dflash_owns_call is not None and dflash_owns_call(cls): - if getattr(get_backup_base(cls), "_omlx_mtp_call_marker", False): - return # our body already sits under the dflash guard + dflash_base = get_dflash_guard_base(cls) + if getattr(dflash_base, "_omlx_mtp_call_marker", False): + return # our body already sits under the dflash guard import mlx.core as mx import mlx.nn as nn @@ -373,11 +366,10 @@ def __call__( cls._process_chunk = _process_chunk __call__._omlx_mtp_call_marker = True - if dflash_owns_call is not None and dflash_owns_call(cls): + if dflash_base is not None: # Compose with the armed dflash guard instead of replacing it # (issue #2972): our body becomes the guard's fallback base. - if not swap_backup_base(cls, __call__): - cls.__call__ = __call__ + set_dflash_guard_base(cls, __call__) else: cls.__call__ = __call__ diff --git a/tests/test_dflash_lifecycle.py b/tests/test_dflash_lifecycle.py index d05992719d..d0cd69937c 100644 --- a/tests/test_dflash_lifecycle.py +++ b/tests/test_dflash_lifecycle.py @@ -175,7 +175,7 @@ def __call__(self, x, mask=None, cache=None): assert FakeLinearAttn.__call__ is stock_call assert "_dflash_speculative_call_installed" not in FakeLinearAttn.__dict__ - # Simulate a Native MTP patch replacing __call__. + # Simulate a Lightning MTP patch replacing __call__. def mtp_call(self, x, mask=None, cache=None, n_confirmed=0): return ("mtp", n_confirmed) FakeLinearAttn.__call__ = mtp_call @@ -327,6 +327,141 @@ def __call__(self, x, mask=None, cache=None): assert FakeAttention.__call__ is stock_call assert "_dflash_full_attention_gqa_installed" not in FakeAttention.__dict__ + def test_swapped_base_routes_batch_and_mtp_calls(self, _clear_backup_state): + import mlx.core as mx + + from omlx.patches.dflash_lifecycle import ( + get_dflash_guard_base, + restore_dflash_class_patches, + set_dflash_guard_base, + ) + + mod = _make_fake_dflash_module() + + class FakeAttention: + def __call__(self, x, mask=None, cache=None): + return "stock-attn" + + stock_call = FakeAttention.__call__ + self._arm(mod, FakeAttention) + assert get_dflash_guard_base(FakeAttention) is stock_call + + def mtp_call(self, x, mask=None, cache=None, n_confirmed=0): + return ("mtp", n_confirmed) + + mtp_call._omlx_mtp_call_marker = True + set_dflash_guard_base(FakeAttention, mtp_call) + + class ScalarCache: + offset = 4 + + class BatchCache: + offset = mx.array([4, 9]) + + assert FakeAttention()("x", cache=ScalarCache()) == "x" + assert FakeAttention()("x", cache=BatchCache()) == ("mtp", 0) + assert FakeAttention()( + "x", cache=ScalarCache(), n_confirmed=2 + ) == ("mtp", 2) + + restore_dflash_class_patches() + assert FakeAttention.__call__ is mtp_call + + +class TestDFlashMTPComposition: + def test_mtp_self_heal_keeps_active_dflash_guard(self, _clear_backup_state): + from types import SimpleNamespace + + from omlx.patches.dflash_lifecycle import ( + _wrap_installer, + get_dflash_guard_base, + restore_dflash_class_patches, + ) + from omlx.patches.mlx_lm_mtp import qwen35_model + + mod = _make_fake_dflash_module() + + class FakeGatedDeltaNet: + def __call__(self, x, mask=None, cache=None): + return "stock-gdn" + + _wrap_installer( + mod, + "_install_speculative_linear_cache_hook", + "_dflash_speculative_call_installed", + ) + mod._install_speculative_linear_cache_hook(FakeGatedDeltaNet()) + guard = FakeGatedDeltaNet.__call__ + + q35 = SimpleNamespace(GatedDeltaNet=FakeGatedDeltaNet) + qwen35_model._patch_gated_delta_net(q35) + + assert FakeGatedDeltaNet.__call__ is guard + mtp_base = get_dflash_guard_base(FakeGatedDeltaNet) + assert getattr(mtp_base, "_omlx_mtp_call_marker", False) + + qwen35_model._patch_gated_delta_net(q35) + assert get_dflash_guard_base(FakeGatedDeltaNet) is mtp_base + + restore_dflash_class_patches() + assert FakeGatedDeltaNet.__call__ is mtp_base + + def test_stale_mtp_replacement_rearms_dflash(self, _clear_backup_state): + from omlx.patches.dflash_lifecycle import ( + _wrap_installer, + get_dflash_guard_base, + restore_dflash_class_patches, + ) + + mod = _make_fake_dflash_module() + + class FakeGatedDeltaNet: + def __call__(self, x, mask=None, cache=None): + return "stock-gdn" + + _wrap_installer( + mod, + "_install_speculative_linear_cache_hook", + "_dflash_speculative_call_installed", + ) + target = FakeGatedDeltaNet() + mod._install_speculative_linear_cache_hook(target) + + def mtp_call(self, x, mask=None, cache=None, n_confirmed=0): + return ("mtp", n_confirmed) + + mtp_call._omlx_mtp_call_marker = True + FakeGatedDeltaNet.__call__ = mtp_call + assert FakeGatedDeltaNet._dflash_speculative_call_installed is True + + mod._install_speculative_linear_cache_hook(target) + + assert getattr( + FakeGatedDeltaNet.__call__, "_omlx_dflash_batch_guard", False + ) + assert get_dflash_guard_base(FakeGatedDeltaNet) is mtp_call + assert target("x") == "x" + + restore_dflash_class_patches() + assert FakeGatedDeltaNet.__call__ is mtp_call + + def test_guard_without_backup_fails_loudly(self, _clear_backup_state): + from omlx.patches.dflash_lifecycle import ( + get_dflash_guard_base, + set_dflash_guard_base, + ) + + class FakeAttention: + def __call__(self, x, mask=None, cache=None): + return x + + FakeAttention.__call__._omlx_dflash_batch_guard = True + + with pytest.raises(RuntimeError, match="no fallback base"): + get_dflash_guard_base(FakeAttention) + with pytest.raises(RuntimeError, match="state changed"): + set_dflash_guard_base(FakeAttention, lambda self, x: x) + class TestRealDflashIntegration: """Integration tests against the real dflash-mlx module if installed.""" diff --git a/tests/test_mlx_vlm_qwen4_exp_compat.py b/tests/test_mlx_vlm_qwen4_exp_compat.py index b29a8e881d..4b62f06b5d 100644 --- a/tests/test_mlx_vlm_qwen4_exp_compat.py +++ b/tests/test_mlx_vlm_qwen4_exp_compat.py @@ -746,3 +746,56 @@ def test_external_ple_path_is_bounded_and_ssd_alias_resolves(tmp_path): from mlx_vlm.models.qwen4_exp.language import configure_ple_runtime configure_ple_runtime(compute, mode="resident") + + +def _make_bound_qwen4_language_model(config): + from mlx_vlm.models.qwen4_exp.language import LanguageModel, Qwen4ExpMTPModule + + class MTPOwner: + pass + + model = LanguageModel(config.text_config, config) + owner = MTPOwner() + owner.mtp = Qwen4ExpMTPModule(config.text_config) + model.bind_mtp_owner(owner) + return model, owner + + +def _assert_qwen4_lightning_mtp_hidden_width(model, text_config): + expected_width = text_config.hc_count * text_config.hidden_size + output = model( + mx.array([[2, 3, 4]], dtype=mx.int32), + cache=model.make_cache(), + return_hidden=True, + ) + hidden = output.hidden_states[-1] + logits, head_hidden = model.mtp_forward( + hidden[:, -1:], + mx.array([[7]], dtype=mx.uint32), + model.make_mtp_cache(), + return_hidden=True, + logits_keep=1, + ) + mx.eval(hidden, logits, head_hidden) + + assert hidden.shape == (1, 3, expected_width) + assert logits.shape == (1, 1, text_config.vocab_size) + assert head_hidden.shape == (1, 1, expected_width) + + +def test_qwen4_lightning_mtp_isolated_from_dense_qwen35_runtime_patch(): + """Qwen3.5 patching must preserve resident and later Qwen4 MTP models.""" + from omlx.patches.mlx_vlm_mtp import apply_mlx_vlm_mtp_runtime_patch + + config = _tiny_config() + resident_model, resident_owner = _make_bound_qwen4_language_model(config) + _assert_qwen4_lightning_mtp_hidden_width(resident_model, config.text_config) + + apply_mlx_vlm_mtp_runtime_patch() + _assert_qwen4_lightning_mtp_hidden_width(resident_model, config.text_config) + + later_model, later_owner = _make_bound_qwen4_language_model(config) + _assert_qwen4_lightning_mtp_hidden_width(later_model, config.text_config) + + assert resident_owner.mtp is not None + assert later_owner.mtp is not None diff --git a/tests/test_vlm_mtp.py b/tests/test_vlm_mtp.py index a588cdbad1..f97a603bc1 100644 --- a/tests/test_vlm_mtp.py +++ b/tests/test_vlm_mtp.py @@ -603,6 +603,60 @@ def __call__( assert model.forward_kwargs["capture_layer_ids"] == [1] +def test_dense_vlm_runtime_delegates_foreign_subclasses_unchanged(): + """The dense Qwen3.5 runtime patch must not wire foreign subclasses.""" + from omlx.patches.mlx_vlm_mtp import qwen35_vlm_runtime + + class FakeLanguageModel: + def __init__(self, args, config=None): + self.args = args + self.config = config + self.forward_kwargs = None + + def __call__( + self, + inputs, + inputs_embeds=None, + mask=None, + cache=None, + **kwargs, + ): + self.forward_kwargs = kwargs + return "stock-subclass-output" + + q35_lang = SimpleNamespace( + LanguageModel=FakeLanguageModel, + MTPModule=lambda args: SimpleNamespace(args=args), + ) + qwen35_vlm_runtime._patch_vlm_language_model(q35_lang) + + class ForeignLanguageModel(FakeLanguageModel): + pass + + model = ForeignLanguageModel( + SimpleNamespace(mtp_num_hidden_layers=1, tie_word_embeddings=True), + config=SimpleNamespace(model_type="foreign"), + ) + result = model( + mx.array([[1, 2]], dtype=mx.int32), + cache=[], + return_hidden=True, + return_shared_kv=True, + n_confirmed=2, + capture_layer_ids=[], + ) + + assert result == "stock-subclass-output" + assert not hasattr(model, "mtp") + assert not hasattr(model, "_omlx_mtp_decode_enabled") + assert model.forward_kwargs == { + "return_hidden": True, + "return_shared_kv": True, + "n_confirmed": 2, + "capture_layer_ids": [], + } + + def test_moe_vlm_sanitize_unfuses_gate_up_by_midpoint(monkeypatch): """The VLM MoE sanitize patch must preserve upstream midpoint slicing.""" from omlx.patches.mlx_vlm_mtp import qwen35_moe_vlm_model From 107ff1f2dce2566d5ea2beb58fa22e2b1f3c6391 Mon Sep 17 00:00:00 2001 From: David Torcivia Date: Sat, 29 Aug 2026 06:58:47 -0400 Subject: [PATCH 027/132] fix(glm5_next): copy strided inputs before the affine prefill tile (#3275) The GLM-5.3 fused input projection produces strided split views, while the native affine QMM tile reads inputs as row-major contiguous. Materialize the inputs before both native dispatch sites and cover the q5/q8 thresholds with regression tests. --- .../vendor/mlx_vlm/models/glm5_next/linear.py | 5 ++ tests/test_mlx_vlm_glm5_next_compat.py | 63 +++++++++++++++++++ 2 files changed, 68 insertions(+) diff --git a/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/linear.py b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/linear.py index 414e27b83d..489ee9ef0a 100644 --- a/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/linear.py +++ b/omlx/patches/mlx_vlm_glm5_next_compat/vendor/mlx_vlm/models/glm5_next/linear.py @@ -24,6 +24,9 @@ def _native_qmm(linear: nn.QuantizedLinear, x: mx.array): name = f"qwen35_q{bits}_affine_qmm_t" if not fast.has_symbol(name) or not _is_supported_affine_linear(linear, x): return None + # The tile indexes x as row-major packed and ignores its strides, so a + # last-axis view reads the wrong lanes. + x = mx.contiguous(x) return getattr(fast, name)( x, linear.weight, @@ -87,6 +90,8 @@ def fused_quantized_matmul( name = f"qwen35_q{bits}_affine_qmm_t" if fast.has_symbol(name) and fast.qmm_supports_group_size(group_size): + # The tile ignores the input's strides. See _native_qmm. + x = mx.contiguous(x) return getattr(fast, name)( x, weight, diff --git a/tests/test_mlx_vlm_glm5_next_compat.py b/tests/test_mlx_vlm_glm5_next_compat.py index d33f66f7d8..1ead0cfa35 100644 --- a/tests/test_mlx_vlm_glm5_next_compat.py +++ b/tests/test_mlx_vlm_glm5_next_compat.py @@ -650,3 +650,66 @@ def spy(*args, **kwargs): assert calls == 1 assert mx.allclose(actual, reference, atol=2e-3, rtol=2e-3).item() + + +@pytest.mark.parametrize(("bits", "tokens"), [(5, 128), (8, 1024)]) +def test_glm5_next_prefill_qmm_handles_strided_input(bits, tokens): + import mlx.nn as nn + from mlx_vlm.models.glm5_next.linear import linear_forward + + from omlx.custom_kernels.qwen35_prefill import fast + + name = f"qwen35_q{bits}_affine_qmm_t" + if not fast.has_symbol(name): + pytest.skip(f"{name} native kernel is not built") + + mx.random.seed(11) + dims = 128 + base = nn.Linear(dims, dims, bias=False) + base.set_dtype(mx.float16) + linear = base.to_quantized(group_size=64, bits=bits, mode="affine") + + wide = mx.random.normal((1, tokens, 2 * dims), dtype=mx.float16) + mx.eval(wide) + strided = mx.split(wide, [dims], axis=-1)[1] + + reference = linear(strided) + actual = linear_forward(linear, strided) + mx.eval(actual, reference) + + assert mx.allclose(actual, reference, atol=2e-3, rtol=2e-3).item() + + +@pytest.mark.parametrize(("bits", "tokens"), [(5, 128), (8, 1024)]) +def test_glm5_next_fused_qmm_handles_strided_input(bits, tokens): + import mlx.nn as nn + from mlx_vlm.models.glm5_next.linear import fused_quantized_matmul + + from omlx.custom_kernels.qwen35_prefill import fast + + name = f"qwen35_q{bits}_affine_qmm_t" + if not fast.has_symbol(name): + pytest.skip(f"{name} native kernel is not built") + + mx.random.seed(11) + dims = 128 + base = nn.Linear(dims, dims, bias=False) + base.set_dtype(mx.float16) + linear = base.to_quantized(group_size=64, bits=bits, mode="affine") + + wide = mx.random.normal((1, tokens, 2 * dims), dtype=mx.float16) + mx.eval(wide) + strided = mx.split(wide, [dims], axis=-1)[1] + + reference = linear(strided) + actual = fused_quantized_matmul( + strided, + linear.weight, + linear.scales, + linear.biases, + bits=bits, + group_size=64, + ) + mx.eval(actual, reference) + + assert mx.allclose(actual, reference, atol=2e-3, rtol=2e-3).item() From 7aec9df0d2868c13626fa65bedccac9ce1797288 Mon Sep 17 00:00:00 2001 From: Henri Sara Date: Sat, 29 Aug 2026 16:16:46 +0300 Subject: [PATCH 028/132] fix(scheduler): materialize restored mRoPE seed (#3279) --- omlx/scheduler.py | 2 + tests/test_scheduler.py | 96 ++++++++++++++++++++++++++++++++++++++--- 2 files changed, 92 insertions(+), 6 deletions(-) diff --git a/omlx/scheduler.py b/omlx/scheduler.py index c34562aa22..d2cbd65e43 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -1382,6 +1382,8 @@ def _seed_text_only_mrope_delta_for_cached_prefill(model: Any, request: Any) -> if lm is None or not hasattr(lm, "_rope_deltas"): return lm._rope_deltas = mx.zeros((1, 1), dtype=mx.int64) + # Keep the restore-only seed concrete before the engine-stream graph uses it. + mx.eval(lm._rope_deltas) def _vlm_extra_seq_slice(val: mx.array, s: slice) -> mx.array: diff --git a/tests/test_scheduler.py b/tests/test_scheduler.py index c8d3288300..a20f94bbbb 100644 --- a/tests/test_scheduler.py +++ b/tests/test_scheduler.py @@ -5751,18 +5751,102 @@ def test_cached_text_only_prefill_seeds_zero_mrope_delta(self, mock_tokenizer): request.num_prompt_tokens = 4 request.cached_tokens = 2048 - scheduler._do_external_prefill( - request, - tokens=[1, 2, 3, 4], - existing_cache=[], - vlm_embeds=None, - ) + with patch.object( + scheduler_module, + "_seed_text_only_mrope_delta_for_cached_prefill", + wraps=scheduler_module._seed_text_only_mrope_delta_for_cached_prefill, + ) as seed_mrope: + scheduler._do_external_prefill( + request, + tokens=[1, 2, 3, 4], + existing_cache=[], + vlm_embeds=None, + ) model.clear_vlm_position_state.assert_called_once() + seed_mrope.assert_called_once_with(model, request) seeded = model._language_model._rope_deltas assert seeded.shape == (1, 1) + assert seeded.dtype == mx.int64 assert seeded.item() == 0 + def test_cached_text_only_mrope_seed_is_materialized(self): + """The exact restore-only seed must be concrete before prefill starts.""" + language_model = SimpleNamespace(_rope_deltas=mx.array([[123]])) + model = SimpleNamespace(_language_model=language_model) + request = SimpleNamespace(cached_tokens=2048) + + with patch.object(scheduler_module.mx, "eval") as eval_mock: + scheduler_module._seed_text_only_mrope_delta_for_cached_prefill( + model, request + ) + + seeded = language_model._rope_deltas + assert seeded.shape == (1, 1) + assert seeded.dtype == mx.int64 + assert eval_mock.call_count == 1 + assert eval_mock.call_args.args[0] is seeded + + def test_fresh_text_only_prefill_does_not_seed_or_evaluate_mrope(self): + previous = mx.array([[123]]) + language_model = SimpleNamespace(_rope_deltas=previous) + model = SimpleNamespace(_language_model=language_model) + request = SimpleNamespace(cached_tokens=0) + + with patch.object(scheduler_module.mx, "eval") as eval_mock: + scheduler_module._seed_text_only_mrope_delta_for_cached_prefill( + model, request + ) + + assert language_model._rope_deltas is previous + eval_mock.assert_not_called() + + @pytest.mark.parametrize( + "model", + [ + SimpleNamespace(), + SimpleNamespace(_language_model=SimpleNamespace()), + ], + ) + def test_text_only_mrope_seed_ignores_models_without_state(self, model): + before = vars(model).copy() + request = SimpleNamespace(cached_tokens=2048) + + with patch.object(scheduler_module.mx, "eval") as eval_mock: + scheduler_module._seed_text_only_mrope_delta_for_cached_prefill( + model, request + ) + + assert vars(model) == before + eval_mock.assert_not_called() + + def test_chunked_prefill_initialization_seeds_cached_text_mrope( + self, mock_tokenizer + ): + model = self._make_vlm_model() + model._language_model = SimpleNamespace(_rope_deltas=mx.array([[123]])) + scheduler = Scheduler(model=model, tokenizer=mock_tokenizer) + request = Request( + request_id="text-cached-chunked-001", + prompt="hello world", + sampling_params=SamplingParams(max_tokens=50), + ) + request.cached_tokens = 2048 + + with patch.object( + scheduler_module, + "_seed_text_only_mrope_delta_for_cached_prefill", + wraps=scheduler_module._seed_text_only_mrope_delta_for_cached_prefill, + ) as seed_mrope: + scheduler._begin_prefill( + request, + tokens=[1, 2, 3, 4], + existing_cache=[], + ) + + model.clear_vlm_position_state.assert_called_once() + seed_mrope.assert_called_once_with(model, request) + class TestBuildStateMachineStopStrings: """Tests for _build_state_machine stop-string tokenization. From ffc2d05924674f6ccff69b2f2029e02b70b62065 Mon Sep 17 00:00:00 2001 From: Augusto Pietroski <31279961+Pietroski@users.noreply.github.com> Date: Sat, 29 Aug 2026 10:19:37 -0300 Subject: [PATCH 029/132] fix(scheduler): stop Metal resource-count exhaustion on ArraysCache hybrids (#3227) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(api): strip Claude Code total_tokens budget markers from system text Claude Code appends a freshly decremented `N tokens left` block to the end of the system prompt on every request while keeping the stale copies, so the prompt head both changes and grows each call. No stored prefix can match past it, which degrades every turn of an agentic session into a full re-prefill (measured at ~106k tokens per turn, minutes of latency at long context). Strip the marker wholesale in the anthropic adapter, mirroring the existing x-anthropic-billing-header filter: in _extract_system_text for the canonical system field, and on system/developer-role messages in both convert paths for clients that send system content inline. The marker is informational only; nothing downstream parses it. Adds TestClientBudgetMarkerStripping covering the system field, block lists, inline system messages, and the guarantee that user-quoted marker text is left untouched. Co-Authored-By: Claude Fable 5 * fix(scheduler): stop Metal resource-count exhaustion on ArraysCache hybrids GLM-5.3-Flash (and other ArraysCache hybrid models) hit '[metal::malloc] Resource limit (499000) exceeded' during long-context decode. The limit is MLX's guard on Metal's per-process buffer-object count, not bytes: the failure reproduces with active memory far below the wired ceiling (observed after a fresh model reload on a 512GB M3 Ultra). Four contributing defects, all fixed here: - Decode KV/recurrent-state materialization defaulted on only for MiniMax by model-name substring. Every ArraysCache hybrid rebinds its recurrent state lazily per decode step, pinning one buffer chain per step per layer; the interval now defaults to 256 for any model whose cache layout contains ArraysCache. - fail_all_requests and the chunked-prefill error handlers never released the failed requests' boundary snapshots (live mx.arrays in the in-memory fallback, orphaned dirs on SSD) nor their paged-cache block refs, so every engine failure permanently stranded a snapshot set — a positive feedback loop toward the next OOM. - The periodic pool-clear byte gate scaled with the soft memory limit (~146GB on a 512GB machine), so it effectively never fired even while the pool hoarded buffer handles. It is now capped at 16GiB. - The dedup backfill inspection load promoted every inspected block into the hot cache; for pm-ineligible CacheList layouts (CacheList(KVCache, PoolingCache)) those payloads carry the full cumulative KV prefix and were retained for nothing. Root cause of the cumulative payloads themselves: cachelist_pm_member_plan returns None when a CacheList member is PoolingCache, which routes GLM-5.3's 11 attention layers onto the pre-#2550 quadratic store/restore path. Making that layout pm-eligible needs coordinated changes in paged_ssd_cache and is left for a follow-up. Co-Authored-By: Claude Fable 5 --------- Co-authored-by: Claude Fable 5 --- omlx/cache/prefix_cache.py | 11 ++- omlx/scheduler.py | 80 ++++++++++++++++++++- tests/test_scheduler.py | 141 +++++++++++++++++++++++++++++++++++++ 3 files changed, 229 insertions(+), 3 deletions(-) diff --git a/omlx/cache/prefix_cache.py b/omlx/cache/prefix_cache.py index aac44d034b..460e64cae4 100644 --- a/omlx/cache/prefix_cache.py +++ b/omlx/cache/prefix_cache.py @@ -1933,7 +1933,16 @@ def _maybe_backfill_dedup_block_payload( if self.paged_ssd_cache is None or not HAS_MLX: return True try: - data, meta = self.paged_ssd_cache.load_block_with_metadata(block_hash) + # Inspection load only: do not promote into the hot cache. A + # legacy-cumulative block (pm-ineligible CacheList layouts, e.g. + # CacheList(KVCache, PoolingCache)) carries the full cumulative + # KV prefix; promoting every inspected block retains those + # oversized payloads in RAM for nothing when the common outcome + # is "payload already real, no rewrite" (#3226). + data, meta = self.paged_ssd_cache.load_block_with_metadata( + block_hash, + promote_to_hot_cache=False, + ) if not data or not meta: return False types = meta.get("layer_cache_types") or [] diff --git a/omlx/scheduler.py b/omlx/scheduler.py index d2cbd65e43..fbbeb175f6 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -1992,8 +1992,21 @@ def __init__( # can log their divergence point at INFO (#2333). self._cache_probe_seqs: deque[tuple[str, array | list[int]]] = deque(maxlen=4) + # Hybrid models whose recurrent state is REBOUND per decode step + # (ArraysCache/SizedArraysCache: MiniMax, Qwen3.5-Next, GLM-5.3, ...) + # never materialize those states through mx.async_eval alone. The + # unevaluated per-step chain pins every intermediate Metal buffer, + # and the allocator's per-process resource count (499,000 buffers) + # is exhausted long before any byte limit — the + # "[metal::malloc] Resource limit (499000) exceeded" failure (#3226). + # Periodic materialization collapses the chain; enable it for every + # ArraysCache hybrid, not just MiniMax. model_name_lower = (self.config.model_name or "").lower() - default_kv_eval_interval = 256 if "minimax" in model_name_lower else 0 + default_kv_eval_interval = ( + 256 + if "minimax" in model_name_lower or self._model_has_arrays_cache() + else 0 + ) self._decode_eval_kv_cache_interval: int = max( 0, _env_int( @@ -2287,9 +2300,18 @@ def _periodic_clear_threshold_bytes(self) -> int: the entire MLX buffer pool in one batch; gating it on accumulated bytes avoids producing IOGPUFamily refcount bursts when the pool is already small. + + The memory_limit/3 term is additionally capped at 16 GiB: on + large-memory machines (soft limit ~438 GB on a 512 GB Studio) an + uncapped threshold (~146 GB) meant the periodic clear effectively + never fired, letting the pool hoard buffer *handles* against the + Metal per-process resource count even while byte usage stayed + modest (#3226). """ + cap = 16 * 1024**3 if self._memory_limit_bytes > 0: - return max(self._memory_limit_bytes // 3, 2 * 1024**3) + return min(max(self._memory_limit_bytes // 3, 2 * 1024**3), cap) + return 2 * 1024**3 def _should_periodic_clear_cache(self) -> bool: @@ -2770,6 +2792,21 @@ def _enlarge_block_size_for_arrays_cache(self) -> None: ) self.config.paged_cache_block_size = target + def _model_has_arrays_cache(self) -> bool: + """Whether the model's cache layout contains ArraysCache layers.""" + if not hasattr(self.model, "make_cache"): + return False + try: + cache_list = self.model.make_cache() + except Exception: + return False + if not cache_list: + return False + + return any( + self._cache_tree_has_arrays_cache(cache_obj) for cache_obj in cache_list + ) + @staticmethod def _cache_tree_has_arrays_cache(cache_obj: Any) -> bool: """Return True if cache_obj contains ArraysCache (recursively).""" @@ -5452,6 +5489,7 @@ def _advance_chunked_prefills( logger.error("Chunked prefill capacity rejected for %s: %s", rid, e) self._prefill_states.pop(rid, None) self._release_paged_cache_for_request(rid) + self._drop_boundary_snapshots_for_request(rid) self.requests.pop(rid, None) self._clear_request_admission_bookkeeping(rid) get_prefill_tracker().remove(rid) @@ -5462,6 +5500,7 @@ def _advance_chunked_prefills( logger.error("Chunked prefill failed for %s: %s", rid, e) self._prefill_states.pop(rid, None) self._release_paged_cache_for_request(rid) + self._drop_boundary_snapshots_for_request(rid) self.requests.pop(rid, None) self._clear_request_admission_bookkeeping(rid) get_prefill_tracker().remove(rid) @@ -9131,6 +9170,26 @@ def _effective_max_num_seqs(self) -> int: return 1 return max(1, self.config.max_num_seqs) + def _drop_boundary_snapshots_for_request(self, request_id: str) -> None: + """Release a failed request's boundary snapshots (RAM and SSD). + + The in-memory dict values can hold live mx.arrays (the SSD-store + fallback path), and the store keeps a per-request snapshot dir on + disk. Both are normally released in _cleanup_finished; error paths + must do the same or every failure strands a snapshot set until + process exit (#3226). + """ + 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 fail_all_requests(self) -> list[str]: """Remove all running and waiting requests after unrecoverable error. @@ -9207,6 +9266,16 @@ def fail_all_requests(self) -> list[str]: if uid is not None: self.uid_to_request_id.pop(uid, None) self._generation_overflow_recovery_ids.difference_update(failed_ids) + # Drop boundary snapshots and paged-cache reservations for every + # failed request. Without this, each engine-loop failure strands a + # full per-request snapshot set (live mx.arrays for the in-memory + # fallback, orphaned snapshot dirs on SSD) and its block refs until + # process exit — a Metal buffer/byte ratchet across failures (#3226). + # failed_ids excludes _inflight_store_futures ids, so snapshots the + # async store worker still reads are left intact. + for rid in failed_ids: + self._drop_boundary_snapshots_for_request(rid) + self._release_paged_cache_for_request(rid) # Reset batch generator only (cache is not corrupted). Every row dies # with it; survivors re-register at re-insert. _unregister_uid_rows_for_model(self.model) @@ -11716,6 +11785,13 @@ def step(self) -> SchedulerOutput: if self._tokens_since_clear_cache >= 1024: _sync_and_clear_cache(self._stream) self._tokens_since_clear_cache = 0 + # Refresh the executor-owned MLX active-memory sample. + # The background enforcer reads this cached value + # during active decode; without a decode-side refresh + # it stays frozen at the last prefill's reading for + # the whole generation, blinding the hard-watermark + # abort to decode-time growth (#3226). + self._current_usage_bytes() except _PrefillAbortedError: # Prefill was interrupted by a pending abort. diff --git a/tests/test_scheduler.py b/tests/test_scheduler.py index a20f94bbbb..7f5f9fbb83 100644 --- a/tests/test_scheduler.py +++ b/tests/test_scheduler.py @@ -6373,3 +6373,144 @@ class NoCall: scheduler = self._scheduler_with_model(NoCall()) assert scheduler._supports_skip_lm_head() is False + + +class TestFailAllRequestsSnapshotCleanup: + """fail_all_requests must release boundary snapshots and block refs. + + Regression tests for the failure-path leak (#3226): every engine-loop + error used to strand the failed requests' boundary snapshot sets (live + mx.arrays in the in-memory fallback, orphaned dirs on SSD) and their + paged-cache reservations until process exit. + """ + + def _scheduler(self, mock_model, mock_tokenizer): + config = SchedulerConfig(paged_cache_block_size=4) + return Scheduler( + model=mock_model, tokenizer=mock_tokenizer, config=config + ) + + def test_fail_all_requests_drops_boundary_snapshots( + self, mock_model, mock_tokenizer + ): + scheduler = self._scheduler(mock_model, mock_tokenizer) + request = Request( + request_id="req-fail", + prompt="hello", + sampling_params=SamplingParams(), + ) + scheduler.running["req-fail"] = request + scheduler.requests["req-fail"] = request + scheduler._boundary_cache_snapshots["req-fail"] = {4: [MagicMock()]} + store = MagicMock() + scheduler._boundary_snapshot_store = store + + with patch.object( + scheduler, "_release_paged_cache_for_request" + ) as release: + failed = scheduler.fail_all_requests() + + assert failed == ["req-fail"] + assert "req-fail" not in scheduler._boundary_cache_snapshots + store.cleanup_request.assert_called_once_with("req-fail") + release.assert_called_once_with("req-fail") + + def test_fail_all_requests_keeps_inflight_store_snapshots( + self, mock_model, mock_tokenizer + ): + scheduler = self._scheduler(mock_model, mock_tokenizer) + request = Request( + request_id="req-storing", + prompt="hello", + sampling_params=SamplingParams(), + ) + scheduler.requests["req-storing"] = request + scheduler._inflight_store_futures["req-storing"] = MagicMock() + scheduler._boundary_cache_snapshots["req-storing"] = {4: None} + store = MagicMock() + scheduler._boundary_snapshot_store = store + + failed = scheduler.fail_all_requests() + + assert "req-storing" not in failed + assert "req-storing" in scheduler._boundary_cache_snapshots + store.cleanup_request.assert_not_called() + + def test_drop_helper_tolerates_store_errors( + self, mock_model, mock_tokenizer + ): + scheduler = self._scheduler(mock_model, mock_tokenizer) + scheduler._boundary_cache_snapshots["req-x"] = {4: None} + store = MagicMock() + store.cleanup_request.side_effect = OSError("disk gone") + scheduler._boundary_snapshot_store = store + + scheduler._drop_boundary_snapshots_for_request("req-x") + + assert "req-x" not in scheduler._boundary_cache_snapshots + + +class TestPeriodicClearThresholdCap: + """The periodic-clear byte gate must stay reachable on big machines.""" + + def test_threshold_capped_at_16gib(self, mock_model, mock_tokenizer): + scheduler = Scheduler( + model=mock_model, + tokenizer=mock_tokenizer, + config=SchedulerConfig(), + ) + scheduler._memory_limit_bytes = 438 * 1024**3 # 512GB-class soft limit + assert scheduler._periodic_clear_threshold_bytes() == 16 * 1024**3 + + def test_threshold_small_limits_unchanged(self, mock_model, mock_tokenizer): + scheduler = Scheduler( + model=mock_model, + tokenizer=mock_tokenizer, + config=SchedulerConfig(), + ) + scheduler._memory_limit_bytes = 24 * 1024**3 + assert scheduler._periodic_clear_threshold_bytes() == 8 * 1024**3 + scheduler._memory_limit_bytes = 0 + assert scheduler._periodic_clear_threshold_bytes() == 2 * 1024**3 + + +class TestHybridDecodeKvEvalDefault: + """ArraysCache hybrids get periodic decode KV materialization by default. + + Regression test for the Metal resource-count exhaustion (#3226): the + lazily rebound recurrent state of ArraysCache hybrid models (GLM-5.3, + Qwen3.5-Next, ...) pins one buffer chain per decode step unless it is + periodically materialized; the interval used to default on only for + MiniMax by name. + """ + + class _ArraysCacheStub: + pass + + def _model_with_cache(self, cache_objs): + model = MagicMock() + model.make_cache = MagicMock(return_value=cache_objs) + model.config = SimpleNamespace(model_type="test") + return model + + def test_arrays_cache_model_defaults_to_256(self, mock_tokenizer): + stub = type("ArraysCache", (), {})() + model = self._model_with_cache([stub]) + scheduler = Scheduler( + model=model, tokenizer=mock_tokenizer, config=SchedulerConfig() + ) + assert scheduler._decode_eval_kv_cache_interval == 256 + + def test_plain_kv_model_defaults_to_0(self, mock_tokenizer): + stub = type("KVCache", (), {})() + model = self._model_with_cache([stub]) + scheduler = Scheduler( + model=model, tokenizer=mock_tokenizer, config=SchedulerConfig() + ) + assert scheduler._decode_eval_kv_cache_interval == 0 + + def test_no_make_cache_defaults_to_0(self, mock_model, mock_tokenizer): + scheduler = Scheduler( + model=mock_model, tokenizer=mock_tokenizer, config=SchedulerConfig() + ) + assert scheduler._decode_eval_kv_cache_interval == 0 From 72626eb263105bad990f4552a3b77302cba9cad6 Mon Sep 17 00:00:00 2001 From: jundot Date: Sat, 29 Aug 2026 22:23:03 +0900 Subject: [PATCH 030/132] test: cover decode cache materialization boundary (#3227) --- tests/test_scheduler.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/tests/test_scheduler.py b/tests/test_scheduler.py index 7f5f9fbb83..2cb77bd170 100644 --- a/tests/test_scheduler.py +++ b/tests/test_scheduler.py @@ -265,6 +265,31 @@ def test_decode_outputs_preserve_prefill_rejections( assert output.finished_request_ids == {"running"} scheduler._cleanup_finished.assert_called_once_with({"running"}) + def test_decode_materializes_cache_at_configured_interval( + self, mock_model, mock_tokenizer + ): + scheduler = Scheduler(model=mock_model, tokenizer=mock_tokenizer) + + scheduler._schedule_waiting = MagicMock(return_value=([], [])) + scheduler._process_batch_responses = MagicMock(return_value=([], set())) + scheduler._cleanup_finished = MagicMock() + + scheduler.running = {"running": MagicMock()} + scheduler.batch_generator = MagicMock() + scheduler.batch_generator.next_generated.return_value = iter([MagicMock()]) + scheduler._decode_eval_kv_cache_interval = 256 + scheduler._tokens_since_kv_cache_eval = 255 + + with patch.object( + scheduler_module, + "_eval_generation_batch_cache", + return_value=1, + ) as eval_cache: + scheduler.step() + + eval_cache.assert_called_once_with(scheduler.batch_generator) + assert scheduler._tokens_since_kv_cache_eval == 0 + class TestSchedulerInitialization: """Tests for Scheduler initialization.""" From 5dba970751e353fff0d446fc4f1fd7a8ab8f64cb Mon Sep 17 00:00:00 2001 From: daveycodez Date: Sat, 29 Aug 2026 06:26:46 -0700 Subject: [PATCH 031/132] fix: handle Qwen4 late-join batching (#3246) Honor model-owned to_batch conversions during joins, use aligned QSA indexer offsets, and trim batched QSA index arrays consistently. Fixes #3245 --- omlx/patches/mlx_lm_mtp/batch_generator.py | 9 ++ .../mlx_vlm/models/qwen4_exp/language.py | 14 ++ omlx/scheduler.py | 7 + tests/test_mlx_lm_mtp_patch.py | 30 +++++ tests/test_mlx_vlm_qwen4_exp_compat.py | 120 ++++++++++++++++++ 5 files changed, 180 insertions(+) diff --git a/omlx/patches/mlx_lm_mtp/batch_generator.py b/omlx/patches/mlx_lm_mtp/batch_generator.py index 66df1bdb95..2a92010c9e 100644 --- a/omlx/patches/mlx_lm_mtp/batch_generator.py +++ b/omlx/patches/mlx_lm_mtp/batch_generator.py @@ -2309,6 +2309,15 @@ def _chain_next_drafts( """ import mlx.core as mx + if getattr(hidden_rows, "ndim", 0) == 3 and hidden_rows.shape[0] != 1: + # A row joined mid-cycle (continuous batching): the singleton head + # cache cannot fold a multi-row trunk hidden. Skip this fold — the + # late-join handoff/park path rebuilds MTP state afterwards. + state.drafts = mx.zeros((0,), dtype=mx.uint32) + state.draft_lps = [] + state.draft_accept_lps = [] + return + model = gen_batch.model if _dspark_host(model) is not None: return _dspark_next_drafts( 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 31255b5433..99bc3938d8 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 @@ -475,6 +475,15 @@ def is_trimmable(self): def trim(self, n): trimmed = self.kv_cache.trim(n) self.index_offset = max(0, self.index_offset - trimmed) + # Slice the physical arrays like the singleton trim does: + # update_indexer concatenates onto them and re-derives index_offset + # from shape[1], so stale draft columns would otherwise fossilize + # and desync the indexer from the KV by the trimmed amount. + if trimmed and self.index_keys is not None: + self.index_keys = self.index_keys[:, : self.index_offset] + self.index_position_ids = self.index_position_ids[ + ..., : self.index_offset + ] return trimmed @property @@ -711,6 +720,11 @@ def from_projected( full_position_ids = position_ids key_len = raw_keys.shape[1] + if isinstance(past_len, mx.array): + # Batched rows carry per-row KV offsets, but the indexer cache is + # left-padded to one width; the masks below need aligned-column + # scalars or the (batch,) offsets broadcast into the seq axis. + past_len = key_len - seq_len max_complete_blocks = key_len // self.compress_ratio if max_complete_blocks <= self.block_topk: return None diff --git a/omlx/scheduler.py b/omlx/scheduler.py index fbbeb175f6..8f792765e6 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -992,6 +992,13 @@ def _to_batched_cache_layer(cache_obj: Any) -> Any: and type(cache_obj) is _TQ_SINGLETON_CACHE_TYPE ): return cache_obj.merge([cache_obj]) + # Model-owned singletons (e.g. qwen4_exp QSAKVCache) declare their batch + # conversion via to_batch, which _patched_make_cache honors at creation; + # honor it on the continuous-batching join path too, or extend() hits a + # singleton without the method. A warm singleton is one unpadded row. + to_batch = getattr(cache_obj, "to_batch", None) + if callable(to_batch): + return to_batch([0]) return cache_obj diff --git a/tests/test_mlx_lm_mtp_patch.py b/tests/test_mlx_lm_mtp_patch.py index 13d6cc10a7..a69f3573ab 100644 --- a/tests/test_mlx_lm_mtp_patch.py +++ b/tests/test_mlx_lm_mtp_patch.py @@ -2821,3 +2821,33 @@ def test_recently_active_window(self): assert tracker.recently_active(3.0) # just-finished counts tracker.clear() assert not tracker.recently_active(3.0) + + +class TestChainNextDraftsLateJoin: + """Regression for the multi-row fold guard (issue #3245, PR #3246).""" + + def test_multi_row_trunk_hidden_skips_singleton_fold(self): + """A row joining mid-MTP-cycle hands the singleton fold a batch-shaped + trunk hidden; the fold must bail out with empty drafts instead of + crashing in the model's mtp_forward/fuse_inputs.""" + import mlx.core as mx + + from omlx.patches.mlx_lm_mtp import batch_generator as bg + + calls = [] + + def boom(*args, **kwargs): + calls.append(args) + raise AssertionError("mtp_forward must not run for a multi-row fold") + + gen_batch = SimpleNamespace(model=SimpleNamespace(mtp_forward=boom)) + state = bg._MtpState(uid=1, chain=True, depth=2, mtp_cache=[]) + hidden_rows = mx.zeros((2, 3, 8), dtype=mx.float32) + committed = mx.array([1, 2, 3], dtype=mx.uint32) + + bg._chain_next_drafts(gen_batch, state, hidden_rows, committed, None) + + assert not calls + assert state.drafts is not None and state.drafts.size == 0 + assert state.draft_lps == [] + assert state.draft_accept_lps == [] diff --git a/tests/test_mlx_vlm_qwen4_exp_compat.py b/tests/test_mlx_vlm_qwen4_exp_compat.py index 4b62f06b5d..0a824b9d05 100644 --- a/tests/test_mlx_vlm_qwen4_exp_compat.py +++ b/tests/test_mlx_vlm_qwen4_exp_compat.py @@ -748,6 +748,126 @@ def test_external_ple_path_is_bounded_and_ssd_alias_resolves(tmp_path): configure_ple_runtime(compute, mode="resident") +# --------------------------------------------------------------------------- +# Continuous-batching join regressions (issue #3245, PR #3246) +# --------------------------------------------------------------------------- + + +def _warm_qsa_row(length: int, start: int, index_dim: int = 4): + """Build a warm singleton QSAKVCache holding ``length`` cached tokens. + + Adapted from the fixture in PR #3215 (DiscoStew6082). + """ + from mlx_vlm.models.qwen4_exp.language import QSAKVCache + + cache = QSAKVCache() + values = mx.arange(start, start + 2 * length * 4, dtype=mx.float32).reshape( + 1, 2, length, 4 + ) + cache.state = ( + values, + values + 100, + mx.arange(start, start + length * index_dim, dtype=mx.float32).reshape( + 1, length, index_dim + ), + mx.arange(start, start + length, dtype=mx.int32)[None], + ) + return cache + + +def test_qwen4_cache_extension_promotes_singletons_to_model_owned_batch(): + """A warm QSA singleton joining a running batch must be promoted via the + model-owned ``to_batch`` before ``extend`` — previously the join path + raised AttributeError ('QSAKVCache' object has no attribute 'extend'). + + Adapted from PR #3215 (DiscoStew6082), which fixes the same seam. + """ + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp.language import BatchQSAKVCache + + import omlx.scheduler # noqa: F401 (installs BatchGenerator cache patches) + + left = _warm_qsa_row(3, 10) + right = _warm_qsa_row(1, 30) + generate = importlib.import_module("mlx_lm.generate") + + caches = generate._extend_cache([left], [right]) + + assert len(caches) == 1 + assert isinstance(caches[0], BatchQSAKVCache) + mx.eval(caches[0].offset, caches[0].index_keys, caches[0].index_position_ids) + assert caches[0].offset.tolist() == [3, 1] + assert caches[0].index_offset == 3 + assert caches[0].extract(0).offset == 3 + assert caches[0].extract(1).offset == 1 + assert mx.array_equal( + caches[0].extract(1).index_position_ids, right.index_position_ids + ).item() + + +def test_qwen4_qsa_indexer_handles_ragged_batch_offsets(): + """``from_projected`` on a batched cache whose ``offset`` is a per-row + array must keep the mask math on aligned-column scalars — previously the + (batch,) offsets broadcast into the seq axis and produced selected_tokens + of shape (batch, batch, key_len), crashing mx.concatenate.""" + config = _tiny_config().text_config + from mlx_vlm.models.qwen4_exp.language import BatchQSAKVCache, Qwen4ExpQSAIndexer + + class _PassthroughRope: + @staticmethod + def apply_rotary(q, k, position_ids, unsqueeze_dim=1): + return q, k + + indexer = Qwen4ExpQSAIndexer(config, _PassthroughRope()) + index_dim = config.indexer_head_dim + + batch = _warm_qsa_row(12, 0, index_dim=index_dim).to_batch([0]) + batch.extend(_warm_qsa_row(4, 100, index_dim=index_dim).to_batch([0])) + assert isinstance(batch, BatchQSAKVCache) + assert isinstance(batch.offset, mx.array) # ragged per-row KV offsets + assert batch.offset.tolist() == [12, 4] + + total = (config.indexer_n_heads + config.indexer_kv_heads) * index_dim + qk = (mx.arange(2 * total, dtype=mx.float32) / total).reshape(2, 1, total) + positions = mx.array([[12], [4]], dtype=mx.int32) + + selected = indexer.from_projected(qk, batch, positions) + + assert selected is not None + mx.eval(selected) + key_len = batch.index_offset + assert key_len == 13 + assert selected.shape == (2, 1, 1, key_len) + assert selected.dtype == mx.bool_ + + +def test_qwen4_batch_qsa_trim_slices_indexer_arrays(): + """``BatchQSAKVCache.trim`` must slice the physical indexer arrays like the + singleton trim does — previously only ``index_offset`` was decremented, so + a later ``update_indexer`` resynced it to the stale physical width and the + rejected draft columns fossilized inside the index.""" + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + + batch = _warm_qsa_row(6, 0).to_batch([0]) + assert batch.index_offset == 6 + + trimmed = batch.trim(2) + + assert trimmed == 2 + assert batch.offset.tolist() == [4] + assert batch.index_offset == 4 + assert batch.index_keys.shape[1] == 4 + assert batch.index_position_ids.shape[-1] == 4 + + # The next indexer update must resync against the trimmed length, not the + # stale physical width. + batch.update_indexer( + mx.zeros((1, 1, 4), dtype=mx.float32), + mx.array([[4]], dtype=mx.int32), + ) + assert batch.index_offset == 5 + assert batch.index_keys.shape[1] == 5 + assert batch.index_position_ids.shape[-1] == 5 def _make_bound_qwen4_language_model(config): from mlx_vlm.models.qwen4_exp.language import LanguageModel, Qwen4ExpMTPModule From 266e9eb0be268e50cb276736d7e12b0f0ea01e94 Mon Sep 17 00:00:00 2001 From: jundot Date: Sat, 29 Aug 2026 22:31:52 +0900 Subject: [PATCH 032/132] fix: remove unreachable MTP fold guard (#3246) Current _chain_next_drafts() callers only pass singleton hidden states. Late joins hand off before batch extension, and row-wise MTP operates on singleton row views, so the multi-row branch cannot be reached. Remove the silent fallback and its synthetic test rather than masking a future invariant violation. --- omlx/patches/mlx_lm_mtp/batch_generator.py | 9 ------- tests/test_mlx_lm_mtp_patch.py | 30 ---------------------- 2 files changed, 39 deletions(-) diff --git a/omlx/patches/mlx_lm_mtp/batch_generator.py b/omlx/patches/mlx_lm_mtp/batch_generator.py index 2a92010c9e..66df1bdb95 100644 --- a/omlx/patches/mlx_lm_mtp/batch_generator.py +++ b/omlx/patches/mlx_lm_mtp/batch_generator.py @@ -2309,15 +2309,6 @@ def _chain_next_drafts( """ import mlx.core as mx - if getattr(hidden_rows, "ndim", 0) == 3 and hidden_rows.shape[0] != 1: - # A row joined mid-cycle (continuous batching): the singleton head - # cache cannot fold a multi-row trunk hidden. Skip this fold — the - # late-join handoff/park path rebuilds MTP state afterwards. - state.drafts = mx.zeros((0,), dtype=mx.uint32) - state.draft_lps = [] - state.draft_accept_lps = [] - return - model = gen_batch.model if _dspark_host(model) is not None: return _dspark_next_drafts( diff --git a/tests/test_mlx_lm_mtp_patch.py b/tests/test_mlx_lm_mtp_patch.py index a69f3573ab..13d6cc10a7 100644 --- a/tests/test_mlx_lm_mtp_patch.py +++ b/tests/test_mlx_lm_mtp_patch.py @@ -2821,33 +2821,3 @@ def test_recently_active_window(self): assert tracker.recently_active(3.0) # just-finished counts tracker.clear() assert not tracker.recently_active(3.0) - - -class TestChainNextDraftsLateJoin: - """Regression for the multi-row fold guard (issue #3245, PR #3246).""" - - def test_multi_row_trunk_hidden_skips_singleton_fold(self): - """A row joining mid-MTP-cycle hands the singleton fold a batch-shaped - trunk hidden; the fold must bail out with empty drafts instead of - crashing in the model's mtp_forward/fuse_inputs.""" - import mlx.core as mx - - from omlx.patches.mlx_lm_mtp import batch_generator as bg - - calls = [] - - def boom(*args, **kwargs): - calls.append(args) - raise AssertionError("mtp_forward must not run for a multi-row fold") - - gen_batch = SimpleNamespace(model=SimpleNamespace(mtp_forward=boom)) - state = bg._MtpState(uid=1, chain=True, depth=2, mtp_cache=[]) - hidden_rows = mx.zeros((2, 3, 8), dtype=mx.float32) - committed = mx.array([1, 2, 3], dtype=mx.uint32) - - bg._chain_next_drafts(gen_batch, state, hidden_rows, committed, None) - - assert not calls - assert state.drafts is not None and state.drafts.size == 0 - assert state.draft_lps == [] - assert state.draft_accept_lps == [] From b6a4fca9f7de03c6dbeb48023487fcca4fad67e1 Mon Sep 17 00:00:00 2001 From: jundot Date: Sat, 29 Aug 2026 22:41:48 +0900 Subject: [PATCH 033/132] test: cover QSA cache batch extension edges (#3214) Add coverage for extending a singleton QSA cache with an existing batched cache and for retaining an already-batched QSA cache in place. Adapted from PR #3214 by HaloFour. --- tests/test_mlx_vlm_qwen4_exp_compat.py | 48 ++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/tests/test_mlx_vlm_qwen4_exp_compat.py b/tests/test_mlx_vlm_qwen4_exp_compat.py index 0a824b9d05..7f93a68cb7 100644 --- a/tests/test_mlx_vlm_qwen4_exp_compat.py +++ b/tests/test_mlx_vlm_qwen4_exp_compat.py @@ -805,6 +805,54 @@ def test_qwen4_cache_extension_promotes_singletons_to_model_owned_batch(): ).item() +def test_qwen4_cache_extension_accepts_existing_model_owned_batch(): + """A singleton QSA row can join an existing model-owned batch. + + Adapted from PR #3214 (HaloFour). + """ + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp.language import BatchQSAKVCache + + import omlx.scheduler # noqa: F401 (installs BatchGenerator cache patches) + + left = _warm_qsa_row(3, 10) + right_rows = [_warm_qsa_row(2, 30), _warm_qsa_row(1, 50)] + right = BatchQSAKVCache.merge(right_rows) + generate = importlib.import_module("mlx_lm.generate") + + caches = generate._extend_cache([left], [right]) + + assert len(caches) == 1 + assert isinstance(caches[0], BatchQSAKVCache) + mx.eval(caches[0].offset, caches[0].left_padding, caches[0].index_keys) + assert caches[0].offset.tolist() == [3, 2, 1] + assert caches[0].left_padding.tolist() == [0, 1, 2] + assert [caches[0].extract(i).offset for i in range(3)] == [3, 2, 1] + + +def test_qwen4_cache_extension_keeps_existing_batch_in_place(): + """Extending two batched QSA caches must retain the left batch object. + + Adapted from PR #3214 (HaloFour). + """ + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp.language import BatchQSAKVCache + + import omlx.scheduler # noqa: F401 (installs BatchGenerator cache patches) + + left = BatchQSAKVCache.merge([_warm_qsa_row(3, 10)]) + right = BatchQSAKVCache.merge([_warm_qsa_row(2, 30)]) + generate = importlib.import_module("mlx_lm.generate") + + caches = generate._extend_cache([left], [right]) + + assert caches[0] is left + mx.eval(left.offset, left.left_padding, left.index_keys) + assert left.offset.tolist() == [3, 2] + assert left.left_padding.tolist() == [0, 1] + assert [left.extract(i).offset for i in range(2)] == [3, 2] + + def test_qwen4_qsa_indexer_handles_ragged_batch_offsets(): """``from_projected`` on a batched cache whose ``offset`` is a per-row array must keep the mask math on aligned-column scalars — previously the From 1abb9511aa5fe868bb52efd45e4ec87aa3cb4558 Mon Sep 17 00:00:00 2001 From: Darren Peck Date: Sat, 29 Aug 2026 06:52:52 -0700 Subject: [PATCH 034/132] fix: apply sanitize wrapper to symlinked models (#3224) Preserve the lexical safetensors path when matching checkpoint shards so Hugging Face cache symlinks still run the model sanitize path. --- omlx/engine/vlm.py | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/omlx/engine/vlm.py b/omlx/engine/vlm.py index 4a7e9a7059..6d31adb1f9 100644 --- a/omlx/engine/vlm.py +++ b/omlx/engine/vlm.py @@ -959,10 +959,20 @@ def metadata(self): def _patched_safe_open(filename, *args, **kwargs): handle = original_safe_open(filename, *args, **kwargs) try: - path = Path(filename).resolve() + path = Path(filename) + resolved = path.resolve() except TypeError: return handle - if path.parent == target_dir and path.suffix == ".safetensors": + # Judge the path as handed to us, not only the fully resolved one. A + # model served from the HuggingFace cache is a symlinked snapshot whose + # shards point into a sibling blobs/ directory, where files are named by + # hash with no extension. Resolving first therefore loses both the + # directory match and the .safetensors suffix, so this wrapper never + # gets applied and sanitize stays skipped for format=mlx checkpoints. + if path.suffix == ".safetensors" and ( + resolved.parent == target_dir + or path.parent.resolve() == target_dir + ): return _SafeOpenMetadataWrapper(handle) return handle @@ -1080,10 +1090,20 @@ def metadata(self): def _patched_safe_open(filename, *args, **kwargs): handle = original_safe_open(filename, *args, **kwargs) try: - path = Path(filename).resolve() + path = Path(filename) + resolved = path.resolve() except TypeError: return handle - if path.parent == target_dir and path.suffix == ".safetensors": + # Judge the path as handed to us, not only the fully resolved one. A + # model served from the HuggingFace cache is a symlinked snapshot whose + # shards point into a sibling blobs/ directory, where files are named by + # hash with no extension. Resolving first therefore loses both the + # directory match and the .safetensors suffix, so this wrapper never + # gets applied and sanitize stays skipped for format=mlx checkpoints. + if path.suffix == ".safetensors" and ( + resolved.parent == target_dir + or path.parent.resolve() == target_dir + ): return _SafeOpenMetadataWrapper(handle) return handle From 4d274bac0fc0fe52d7293677f989eb02aa2df9fc Mon Sep 17 00:00:00 2001 From: Baris Tankut Date: Sat, 29 Aug 2026 17:03:59 +0300 Subject: [PATCH 035/132] fix(glm5_next): register the model in mlx-vlm's prompt MODEL_CONFIG (#3278) Any GLM-5.3-Flash conversation that carries an image alongside a plain turn fails with: Failed to process inputs with error: More images were provided than image tokens. In practice this is every agentic session that looks at a screenshot - ZCode after a browser capture, Codex `view_image` - and the client shows "Reconnecting 1/5..5/5" as the stream dies. mlx-vlm has no glm5_next entry in MODEL_CONFIG, so get_message_json() raises "Unsupported model: glm5_next" for turns without an image. That propagates out of _format_messages_for_vlm_template(), so vlm.chat() falls back to mlx-vlm's generic formatter, which emits no image placeholders - while oMLX still extracts the images. images=1 against image_tokens=0 then trips the processor. The glm5_next image-marker branch already in _format_messages_for_vlm_template() never gets to run. A lone image in a user message works, which is why this only shows up once a conversation also contains a text-only turn. Registering the model lets the existing branch do its job: with the entry present, get_message_json returns [{"type": "image"}, {"type": "text"}] for image turns, and the checkpoint's own template expands each marker to the GLM image-token triplet. Verified on /v1/messages (Anthropic tool_result with an image), /v1/chat/completions and /v1/responses (function_call_output with an image); tool calling and text-only turns unaffected. Claude-Session: https://claude.ai/code/session_01RJwibs8QV24fw7qKuQbM6p Co-authored-by: Baris Tankut Co-authored-by: Claude Opus 5 (1M context) --- omlx/patches/mlx_vlm_glm5_next_compat/__init__.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/omlx/patches/mlx_vlm_glm5_next_compat/__init__.py b/omlx/patches/mlx_vlm_glm5_next_compat/__init__.py index 8397c2a388..4c277cb5c2 100644 --- a/omlx/patches/mlx_vlm_glm5_next_compat/__init__.py +++ b/omlx/patches/mlx_vlm_glm5_next_compat/__init__.py @@ -41,6 +41,18 @@ def apply_mlx_vlm_glm5_next_compat_patch() -> bool: _append_package_path(mlx_vlm, _VENDOR_MLX_VLM) _append_package_path(mlx_vlm.models, _VENDOR_MLX_VLM / "models") importlib.import_module("mlx_vlm.models.glm5_next") + + # mlx-vlm has no glm5_next entry in MODEL_CONFIG, so get_message_json() + # raises "Unsupported model: glm5_next" on every turn that carries no + # image. That aborts _format_messages_for_vlm_template() as a whole, + # so the engine falls back to mlx-vlm's generic formatter, which emits + # no image placeholders -- while oMLX still extracts the images. Any + # conversation mixing an image with a plain turn then fails with + # "More images were provided than image tokens." GLM-5.3 takes the + # same list-with-image-first shape as glm4v. + from mlx_vlm.prompt_utils import MODEL_CONFIG, MessageFormat + + MODEL_CONFIG.setdefault("glm5_next", MessageFormat.LIST_WITH_IMAGE_FIRST) except Exception as exc: # noqa: BLE001 logger.debug("GLM-5.3 mlx-vlm registration failed: %s", exc) return False From dd183fb871ba3cb7725ec48f73f20a4dc84b4092 Mon Sep 17 00:00:00 2001 From: Jordi Posthumus Date: Sat, 29 Aug 2026 23:04:44 +0900 Subject: [PATCH 036/132] test: cover GLM-5.3 mixed image history (#3278) --- tests/test_vlm_engine.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/tests/test_vlm_engine.py b/tests/test_vlm_engine.py index 0faa448854..fe83957c67 100644 --- a/tests/test_vlm_engine.py +++ b/tests/test_vlm_engine.py @@ -18,6 +18,10 @@ import pytest +from omlx.patches.mlx_vlm_glm5_next_compat import ( + apply_mlx_vlm_glm5_next_compat_patch, +) + try: import mlx.core as mx @@ -1636,6 +1640,34 @@ def test_glm5_next_preserves_image_parts_for_native_template(self): ] assert image_ranges == [(0, 1)] + def test_glm5_next_handles_text_history_before_image(self): + """Text turns before an image must stay on GLM's native template path.""" + apply_mlx_vlm_glm5_next_compat_patch() + engine = _make_loaded_engine(model_type="glm5_next") + messages = [ + {"role": "system", "content": "You are helpful."}, + {"role": "user", "content": "Earlier question"}, + {"role": "assistant", "content": "Earlier answer"}, + { + "role": "user", + "content": [ + {"type": "text", "text": "Inspect this"}, + { + "type": "image_url", + "image_url": {"url": "data:image/png;base64,abc"}, + }, + ], + }, + ] + + formatted, image_ranges = engine._format_messages_for_vlm_template( + messages, num_images=1 + ) + + assert formatted[:3] == messages[:3] + assert self._count_image_placeholders(formatted) == 1 + assert image_ranges == [(3, 1)] + def test_glm5_next_inserts_fallback_image_marker(self): """Legacy GLM callers with separate images still receive a marker.""" engine = _make_loaded_engine(model_type="glm5_next") From 94800452b820a2a0ef23cc71254f176b840b24de Mon Sep 17 00:00:00 2001 From: jundot Date: Sat, 29 Aug 2026 23:08:47 +0900 Subject: [PATCH 037/132] fix: harden symlinked checkpoint shard matching --- omlx/engine/vlm.py | 50 +++++++++++------------------- tests/test_vlm_qwen4_exp_loader.py | 38 +++++++++++++++++------ 2 files changed, 46 insertions(+), 42 deletions(-) diff --git a/omlx/engine/vlm.py b/omlx/engine/vlm.py index 6d31adb1f9..0c1f113b5c 100644 --- a/omlx/engine/vlm.py +++ b/omlx/engine/vlm.py @@ -907,6 +907,20 @@ def _should_pack_minimax_m3_shared_expert(args: Any) -> bool: ) +def _model_shard_matcher(model_dir: Path): + """Return a predicate for safetensors shards directly under *model_dir*.""" + target_dir = model_dir.resolve() + + def matches(filename: object) -> bool: + try: + path = Path(filename) + return path.suffix == ".safetensors" and path.parent.resolve() == target_dir + except (TypeError, OSError, RuntimeError): + return False + + return matches + + @contextlib.contextmanager def _force_minimax_m3_moe_sanitize_on_load(model_dir: Path): """Force mlx-vlm's MiniMax M3 MoE sanitize path for MLX-format checkpoints. @@ -933,7 +947,7 @@ def _force_minimax_m3_moe_sanitize_on_load(model_dir: Path): original_safe_open = safetensors.safe_open original_sanitize_moe_weights = _minimax_m3_vl._sanitize_moe_weights - target_dir = model_dir.resolve() + is_target_shard = _model_shard_matcher(model_dir) class _SafeOpenMetadataWrapper: def __init__(self, inner): @@ -958,21 +972,7 @@ def metadata(self): def _patched_safe_open(filename, *args, **kwargs): handle = original_safe_open(filename, *args, **kwargs) - try: - path = Path(filename) - resolved = path.resolve() - except TypeError: - return handle - # Judge the path as handed to us, not only the fully resolved one. A - # model served from the HuggingFace cache is a symlinked snapshot whose - # shards point into a sibling blobs/ directory, where files are named by - # hash with no extension. Resolving first therefore loses both the - # directory match and the .safetensors suffix, so this wrapper never - # gets applied and sanitize stays skipped for format=mlx checkpoints. - if path.suffix == ".safetensors" and ( - resolved.parent == target_dir - or path.parent.resolve() == target_dir - ): + if is_target_shard(filename): return _SafeOpenMetadataWrapper(handle) return handle @@ -1064,7 +1064,7 @@ def _force_qwen4_exp_sanitize_on_load(model_dir: Path): import safetensors original_safe_open = safetensors.safe_open - target_dir = model_dir.resolve() + is_target_shard = _model_shard_matcher(model_dir) class _SafeOpenMetadataWrapper: def __init__(self, inner): @@ -1089,21 +1089,7 @@ def metadata(self): def _patched_safe_open(filename, *args, **kwargs): handle = original_safe_open(filename, *args, **kwargs) - try: - path = Path(filename) - resolved = path.resolve() - except TypeError: - return handle - # Judge the path as handed to us, not only the fully resolved one. A - # model served from the HuggingFace cache is a symlinked snapshot whose - # shards point into a sibling blobs/ directory, where files are named by - # hash with no extension. Resolving first therefore loses both the - # directory match and the .safetensors suffix, so this wrapper never - # gets applied and sanitize stays skipped for format=mlx checkpoints. - if path.suffix == ".safetensors" and ( - resolved.parent == target_dir - or path.parent.resolve() == target_dir - ): + if is_target_shard(filename): return _SafeOpenMetadataWrapper(handle) return handle diff --git a/tests/test_vlm_qwen4_exp_loader.py b/tests/test_vlm_qwen4_exp_loader.py index 4742439c8f..ae7f843acd 100644 --- a/tests/test_vlm_qwen4_exp_loader.py +++ b/tests/test_vlm_qwen4_exp_loader.py @@ -30,12 +30,26 @@ def test_qwen4_exp_runtime_rejects_audio_only(): ) -def test_qwen4_exp_mlx_metadata_is_hidden_during_load(tmp_path, monkeypatch): - (tmp_path / "config.json").write_text( +@pytest.mark.parametrize("symlinked", [False, True], ids=["plain", "hf-symlink"]) +def test_qwen4_exp_mlx_metadata_is_hidden_only_for_model_shards( + tmp_path, monkeypatch, symlinked +): + model_dir = tmp_path / "snapshot" + model_dir.mkdir() + (model_dir / "config.json").write_text( json.dumps({"model_type": "qwen4_exp"}), encoding="utf-8" ) - weight_file = tmp_path / "model.safetensors" - weight_file.touch() + weight_file = model_dir / "model.safetensors" + if symlinked: + blob_dir = tmp_path / "blobs" + blob_dir.mkdir() + blob = blob_dir / "content-hash" + blob.touch() + weight_file.symlink_to(blob) + else: + weight_file.touch() + outside_file = tmp_path / "outside.safetensors" + outside_file.touch() class FakeHandle: def __enter__(self): @@ -49,14 +63,18 @@ def metadata(self): import safetensors - original = lambda *_args, **_kwargs: FakeHandle() - monkeypatch.setattr(safetensors, "safe_open", original) + def fake_safe_open(*_args, **_kwargs): + return FakeHandle() + + monkeypatch.setattr(safetensors, "safe_open", fake_safe_open) - with vlm_module._force_qwen4_exp_sanitize_on_load(tmp_path): - with safetensors.safe_open(weight_file) as handle: - assert handle.metadata() == {"source": "test"} + with vlm_module._force_qwen4_exp_sanitize_on_load(model_dir): + target_handle = safetensors.safe_open(weight_file) + outside_handle = safetensors.safe_open(outside_file) + assert target_handle.metadata() == {"source": "test"} + assert outside_handle.metadata() == {"format": "mlx", "source": "test"} - assert safetensors.safe_open is original + assert safetensors.safe_open is fake_safe_open @pytest.mark.asyncio From e0f6eaa9b15d06a07448a614f5ab949bca3434c7 Mon Sep 17 00:00:00 2001 From: Ho-Jin Lee Date: Sat, 29 Aug 2026 23:13:11 +0900 Subject: [PATCH 038/132] fix(qwen4_exp): restore PLE state after rejected Lightning MTP drafts (#3232) Restore Qwen4-Exp PLE n-gram history and short-convolution state to the committed prefix after rejected or partially accepted Lightning MTP drafts. Co-Authored-By: hojin12312 Co-Authored-By: Claude Sonnet 5 --- .../mlx_vlm/models/qwen4_exp/language.py | 219 +++++++++++++++++- tests/test_mlx_vlm_qwen4_exp_compat.py | 159 +++++++++++++ 2 files changed, 374 insertions(+), 4 deletions(-) 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 99bc3938d8..28ea0d480c 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 @@ -43,6 +43,34 @@ class Qwen4ExpMTPRuntime: _MTP_RUNTIME = Qwen4ExpMTPRuntime() +@dataclass +class _PLESpeculativeState: + """PLE inputs needed to restore a partially accepted verify window. + + Captured across a single target-verify forward and consumed exactly once by + ``rollback_speculative_cache``. ``complete`` gates the consume: it is set + only after *both* the n-gram-history capture and the paired short-conv + capture have run in the same forward, so a snapshot left half-written by an + aborted forward is rejected instead of being applied as a mixed-epoch state. + """ + + history: mx.array + input_ids: mx.array + conv_state: mx.array | None = None + conv_inputs: mx.array | None = None + complete: bool = False + + +class _PLESpeculativeRollbackError(RuntimeError): + """Raised before any cache mutation when a PLE snapshot cannot be trusted. + + The caller's speculative-decode loop treats a raising ``rollback_speculative_cache`` + as a failed rollback and reconciles by rebuilding the cache from the committed + token stream, so failing closed here is safe and leaves no partially rolled + back cache behind. + """ + + def configure_mtp_runtime( model_path: str | Path, *, @@ -1362,7 +1390,13 @@ def _shift_right_ignore_eos(self, token_ids: mx.array, shift: int): valid = (position_in_segment >= shift) & (source_positions[None] >= 0) return mx.where(valid, shifted, self.eos_token_id) - def __call__(self, input_ids: mx.array, cache: Optional[ArraysCache]): + def __call__( + self, + input_ids: mx.array, + cache: Optional[ArraysCache], + *, + capture_speculative_state: bool = False, + ): input_ids = input_ids.astype(mx.int64) batch = input_ids.shape[0] if cache is not None and cache[3] is not None: @@ -1372,6 +1406,20 @@ def __call__(self, input_ids: mx.array, cache: Optional[ArraysCache]): (batch, self.context_len), self.eos_token_id, dtype=mx.int64 ) + if cache is not None: + if capture_speculative_state: + # Arm a fresh snapshot for this target-verify forward. + cache._qwen4_exp_ple_speculative_state = _PLESpeculativeState( + history=previous_context, + input_ids=input_ids, + ) + elif getattr(cache, "_qwen4_exp_ple_speculative_state", None) is not None: + # Ordinary forward: any snapshot still attached belongs to an + # earlier verify cycle that was fully accepted (no rollback) or + # aborted. It can never describe this committed position, so + # disarm it before it can be consumed by a later rollback. + cache._qwen4_exp_ple_speculative_state = None + token_history = mx.concatenate([previous_context, input_ids], axis=-1) if cache is not None: cache[3] = mx.contiguous(token_history[:, -self.context_len :]) @@ -1439,7 +1487,13 @@ def __init__(self, config: TextConfig, layer_idx: int, ple_layer_index: int): bias=False, ) - def _short_conv(self, x: mx.array, cache: Optional[ArraysCache]): + def _short_conv( + self, + x: mx.array, + cache: Optional[ArraysCache], + *, + capture_speculative_state: bool = False, + ): batch = x.shape[0] if cache is not None and cache[2] is not None: state = cache[2] @@ -1448,6 +1502,13 @@ def _short_conv(self, x: mx.array, cache: Optional[ArraysCache]): (batch, self.short_conv_state_len, x.shape[-1]), dtype=x.dtype ) conv_input = mx.concatenate([state, x], axis=1) + if capture_speculative_state and cache is not None: + snapshot = getattr(cache, "_qwen4_exp_ple_speculative_state", None) + if snapshot is not None: + snapshot.conv_state = state + snapshot.conv_inputs = x + # Both paired captures for this verify forward have now run. + snapshot.complete = True if cache is not None: cache[2] = mx.contiguous(conv_input[:, -self.short_conv_state_len :]) return nn.silu(self.conv1d(conv_input)) @@ -1460,7 +1521,12 @@ def __call__( mask: Optional[mx.array], target_verify: bool = False, ): - embeddings = self.ple_embedding(input_ids, cache) + capture_speculative_state = target_verify and input_ids.shape[1] > 1 + embeddings = self.ple_embedding( + input_ids, + cache, + capture_speculative_state=capture_speculative_state, + ) keys = self.norm_key( _target_verify_linear(self.key_proj, embeddings, target_verify) ).reshape(*hidden_states.shape[:-1], self.hc_count, self.hidden_size) @@ -1478,7 +1544,11 @@ def __call__( if mask is not None and isinstance(mask, mx.array) and mask.ndim == 2: gated_values = mx.where(mask[..., None], gated_values, 0) normed = mx.where(mask[..., None], normed, 0) - return gated_values + self._short_conv(normed, cache) + return gated_values + self._short_conv( + normed, + cache, + capture_speculative_state=capture_speculative_state, + ) class Qwen4ExpDecoderLayer(nn.Module): @@ -1822,3 +1892,144 @@ def make_cache(self): else: caches.append(QSAKVCache()) return caches + + @staticmethod + def _normalize_accepted_counts(accepted): + if isinstance(accepted, int): + return [accepted] + if isinstance(accepted, mx.array): + return [int(value) for value in accepted.reshape(-1).tolist()] + return [int(value) for value in accepted] + + @staticmethod + def _discard_ple_snapshots(caches): + for cache in caches: + if getattr(cache, "_qwen4_exp_ple_speculative_state", None) is not None: + cache._qwen4_exp_ple_speculative_state = None + + @staticmethod + def _validate_ple_snapshot(snapshot, accepted_values): + """Reject a snapshot that cannot be applied as a clean single-epoch state.""" + if not snapshot.complete: + raise _PLESpeculativeRollbackError( + "PLE speculative snapshot is incomplete " + "(target-verify forward did not finish both captures)" + ) + if snapshot.history.ndim != 2 or snapshot.input_ids.ndim != 2: + raise _PLESpeculativeRollbackError( + "PLE speculative snapshot history/input_ids are not rank-2" + ) + batch, window = snapshot.input_ids.shape + if window < 1: + raise _PLESpeculativeRollbackError( + "PLE speculative snapshot has an empty verify window" + ) + if snapshot.history.shape[0] != batch: + raise _PLESpeculativeRollbackError( + "PLE speculative snapshot batch mismatch (history vs input_ids)" + ) + if len(accepted_values) not in (1, batch): + raise _PLESpeculativeRollbackError( + "PLE speculative rollback accepted count does not match batch size" + ) + if any(value < 0 for value in accepted_values): + raise _PLESpeculativeRollbackError( + "PLE speculative rollback accepted count is negative" + ) + if snapshot.conv_state is not None or snapshot.conv_inputs is not None: + if ( + snapshot.conv_state is None + or snapshot.conv_inputs is None + or snapshot.conv_state.ndim != 3 + or snapshot.conv_inputs.ndim != 3 + or snapshot.conv_state.shape[0] != batch + or snapshot.conv_inputs.shape[0] != batch + ): + raise _PLESpeculativeRollbackError( + "PLE speculative snapshot short-conv capture is malformed" + ) + + @staticmethod + def _restore_ple_state(cache, snapshot, accepted_values): + batch = snapshot.input_ids.shape[0] + values = accepted_values * batch if len(accepted_values) == 1 else accepted_values + accepted_array = mx.array(values, dtype=mx.int32) + window = snapshot.input_ids.shape[1] + retained = mx.clip(accepted_array + 1, 0, window) + + history_len = snapshot.history.shape[1] + history = mx.concatenate([snapshot.history, snapshot.input_ids], axis=1) + history_positions = retained[:, None] + mx.arange( + history_len, dtype=mx.int32 + )[None, :] + cache[3] = mx.contiguous( + mx.take_along_axis(history, history_positions, axis=1) + ) + + if snapshot.conv_state is not None and snapshot.conv_inputs is not None: + state_len = snapshot.conv_state.shape[1] + if state_len: + conv_input = mx.concatenate( + [snapshot.conv_state, snapshot.conv_inputs], axis=1 + ) + conv_positions = retained[:, None] + mx.arange( + state_len, dtype=mx.int32 + )[None, :] + conv_positions = mx.broadcast_to( + conv_positions[..., None], + (batch, state_len, snapshot.conv_state.shape[-1]), + ) + cache[2] = mx.contiguous( + mx.take_along_axis(conv_input, conv_positions, axis=1) + ) + + def rollback_speculative_cache(self, caches, gdn_states, accepted, block_size): + """Restore PLE state to the accepted verifier prefix. + + The inherited Qwen3.5 rollback restores QSA and GDN state, but PLE's + n-gram history and short-convolution slots are additional recurrent + state. During a multi-token verifier forward we retain the pre-window + history and convolution inputs, then select the state after the + confirmed token plus the accepted draft prefix. + + The restore is run as a small transaction so QSA/GDN (slots 0/1) and PLE + (slots 2/3) can never end up at different committed positions: + + 1. Validate every attached PLE snapshot *before* touching any cache. A + bad snapshot raises ``_PLESpeculativeRollbackError`` with nothing + mutated; the caller then reconciles by rebuilding the cache. + 2. Run the inherited QSA/GDN rollback. + 3. Commit the PLE slot restores, consuming each snapshot exactly once. + + Any snapshot still attached on exit is dropped, so a fully accepted + cycle (which never calls this method) cannot leak a stale snapshot into + a later rollback either. + """ + accepted_values = self._normalize_accepted_counts(accepted) + + pending = [] + try: + for cache in caches: + snapshot = getattr(cache, "_qwen4_exp_ple_speculative_state", None) + if snapshot is None: + continue + self._validate_ple_snapshot(snapshot, accepted_values) + pending.append((cache, snapshot)) + except _PLESpeculativeRollbackError: + self._discard_ple_snapshots(caches) + raise + + try: + result = super().rollback_speculative_cache( + caches, gdn_states, accepted, block_size + ) + except Exception: + self._discard_ple_snapshots(caches) + raise + + try: + for cache, snapshot in pending: + self._restore_ple_state(cache, snapshot, accepted_values) + finally: + self._discard_ple_snapshots(caches) + return result diff --git a/tests/test_mlx_vlm_qwen4_exp_compat.py b/tests/test_mlx_vlm_qwen4_exp_compat.py index 7f93a68cb7..cc3ae978f4 100644 --- a/tests/test_mlx_vlm_qwen4_exp_compat.py +++ b/tests/test_mlx_vlm_qwen4_exp_compat.py @@ -513,6 +513,165 @@ def test_qwen4_verify_matches_singleton_greedy_and_rolls_back_qsa(): assert qsa_cache.index_position_ids.shape[-1] == 4 +def _assert_ple_state_matches(actual_cache, expected_cache): + mx.eval( + actual_cache[2], + actual_cache[3], + expected_cache[2], + expected_cache[3], + ) + assert mx.array_equal(actual_cache[3], expected_cache[3]).item() + assert mx.allclose(actual_cache[2], expected_cache[2], rtol=1e-3, atol=1e-3).item() + + +def test_qwen4_ple_rollback_keeps_only_committed_verify_prefix(): + config = _tiny_config() + from mlx_vlm.models.qwen4_exp.language import LanguageModel + + model = LanguageModel(config.text_config, config) + verify_cache = model.make_cache() + replay_cache = model.make_cache() + prefix = mx.array([[2, 3, 4]], dtype=mx.int32) + confirmed = mx.array([[5]], dtype=mx.int32) + draft = mx.array([[6]], dtype=mx.int32) + next_token = mx.array([[7]], dtype=mx.int32) + model(prefix, cache=verify_cache) + model(prefix, cache=replay_cache) + + verified = model( + mx.concatenate([confirmed, draft], axis=1), + cache=verify_cache, + return_hidden=True, + ) + model(confirmed, cache=replay_cache) + model.rollback_speculative_cache( + verify_cache, + verified.gdn_states, + accepted=0, + block_size=2, + ) + + _assert_ple_state_matches(verify_cache[0], replay_cache[0]) + rolled_back = model(next_token, cache=verify_cache) + replayed = model(next_token, cache=replay_cache) + mx.eval(rolled_back.logits, replayed.logits) + assert mx.allclose(rolled_back.logits, replayed.logits, rtol=1e-3, atol=1e-3).item() + + +def test_qwen4_ple_partial_rollback_and_accept_match_sequential_replay(): + config = _tiny_config() + from mlx_vlm.models.qwen4_exp.language import LanguageModel + + model = LanguageModel(config.text_config, config) + prefix = mx.array([[2, 3, 4]], dtype=mx.int32) + verify_tokens = mx.array([[5, 6, 7, 8]], dtype=mx.int32) + + accepted_cache = model.make_cache() + sequential_cache = model.make_cache() + model(prefix, cache=accepted_cache) + model(prefix, cache=sequential_cache) + model(verify_tokens, cache=accepted_cache, return_hidden=True) + for token in (5, 6, 7, 8): + model(mx.array([[token]], dtype=mx.int32), cache=sequential_cache) + _assert_ple_state_matches(accepted_cache[0], sequential_cache[0]) + + partial_cache = model.make_cache() + replay_cache = model.make_cache() + model(prefix, cache=partial_cache) + model(prefix, cache=replay_cache) + verified = model(verify_tokens, cache=partial_cache, return_hidden=True) + for token in (5, 6, 7): + model(mx.array([[token]], dtype=mx.int32), cache=replay_cache) + model.rollback_speculative_cache( + partial_cache, + verified.gdn_states, + accepted=2, + block_size=4, + ) + + _assert_ple_state_matches(partial_cache[0], replay_cache[0]) + + +def test_qwen4_ple_ordinary_forward_disarms_stale_snapshot(): + """A fully accepted verify cycle never calls rollback. The snapshot it armed + must be dropped by the next ordinary forward so it cannot be mistaken for the + current committed position by a later rollback.""" + config = _tiny_config() + from mlx_vlm.models.qwen4_exp.language import LanguageModel + + model = LanguageModel(config.text_config, config) + cache = model.make_cache() + ple_cache = cache[0] + model(mx.array([[2, 3, 4]], dtype=mx.int32), cache=cache) + + model(mx.array([[5, 6]], dtype=mx.int32), cache=cache, return_hidden=True) + assert getattr(ple_cache, "_qwen4_exp_ple_speculative_state", None) is not None + + # ordinary decode forward (no verify): the stale snapshot must be gone + model(mx.array([[7]], dtype=mx.int32), cache=cache) + assert getattr(ple_cache, "_qwen4_exp_ple_speculative_state", None) is None + + +def test_qwen4_ple_rollback_fails_closed_on_incomplete_snapshot(): + """An aborted verify forward can leave a half-written snapshot. Rollback must + reject it before mutating any cache, not apply a mixed-epoch state.""" + config = _tiny_config() + from mlx_vlm.models.qwen4_exp.language import ( + LanguageModel, + _PLESpeculativeRollbackError, + ) + + model = LanguageModel(config.text_config, config) + cache = model.make_cache() + model(mx.array([[2, 3, 4]], dtype=mx.int32), cache=cache) + verified = model( + mx.array([[5, 6]], dtype=mx.int32), cache=cache, return_hidden=True + ) + + ple_cache, qsa_cache = cache[0], cache[1] + before_hist = mx.array(ple_cache[3]) + before_conv = mx.array(ple_cache[2]) + before_offset = int(qsa_cache.offset) + + ple_cache._qwen4_exp_ple_speculative_state.complete = False + with pytest.raises(_PLESpeculativeRollbackError): + model.rollback_speculative_cache( + cache, verified.gdn_states, accepted=0, block_size=2 + ) + + mx.eval(ple_cache[3], ple_cache[2]) + assert mx.array_equal(ple_cache[3], before_hist).item() + assert mx.array_equal(ple_cache[2], before_conv).item() + assert int(qsa_cache.offset) == before_offset + assert getattr(ple_cache, "_qwen4_exp_ple_speculative_state", None) is None + + +def test_qwen4_ple_rollback_validates_snapshot_before_qsa_mutation(): + """A malformed accepted-count aborts the whole rollback with QSA/GDN + untouched (validation runs before the inherited rollback).""" + config = _tiny_config() + from mlx_vlm.models.qwen4_exp.language import ( + LanguageModel, + _PLESpeculativeRollbackError, + ) + + model = LanguageModel(config.text_config, config) + cache = model.make_cache() + model(mx.array([[2, 3, 4]], dtype=mx.int32), cache=cache) + verified = model( + mx.array([[5, 6]], dtype=mx.int32), cache=cache, return_hidden=True + ) + before_offset = int(cache[1].offset) + + # batch is 1, so a 2-element accepted list cannot match + with pytest.raises(_PLESpeculativeRollbackError): + model.rollback_speculative_cache( + cache, verified.gdn_states, accepted=[0, 0], block_size=2 + ) + assert int(cache[1].offset) == before_offset + assert getattr(cache[0], "_qwen4_exp_ple_speculative_state", None) is None + + def test_qwen4_lightning_mtp_rejects_nextn_only_layout(tmp_path): compat.apply_mlx_vlm_qwen4_exp_compat_patch() from mlx_vlm.models.qwen4_exp.language import configure_mtp_runtime From 0bb2b5ac169939203e610c38b9f8ad1529828dcc Mon Sep 17 00:00:00 2001 From: actualrealhuman <216738440+actualrealhuman@users.noreply.github.com> Date: Sat, 29 Aug 2026 07:18:59 -0700 Subject: [PATCH 039/132] fix(oq): calibrate Qwen4 through RAM-safe proxies (#3269) --- omlx/oq.py | 465 ++++++++++++++++++++------ omlx/process_memory_enforcer.py | 63 +++- tests/test_oq.py | 426 ++++++++++++++++++++++- tests/test_process_memory_enforcer.py | 28 ++ 4 files changed, 858 insertions(+), 124 deletions(-) diff --git a/omlx/oq.py b/omlx/oq.py index b70aef600b..43d3586ec3 100644 --- a/omlx/oq.py +++ b/omlx/oq.py @@ -14,6 +14,7 @@ import logging import re import shutil +import struct as _struct import tempfile import time as _time from dataclasses import dataclass @@ -55,6 +56,37 @@ r"(?:shard_\d+|shards\.\d+)$" ) + +def _is_qwen4_exp_config(config: dict) -> bool: + """Return whether *config* selects the Qwen4-Exp/Flash-Next family.""" + text_config = config.get("text_config") + if not isinstance(text_config, dict): + text_config = {} + return any( + str(model_type or "").lower().startswith("qwen4_exp") + for model_type in (config.get("model_type"), text_config.get("model_type")) + ) + + +def _configure_qwen4_exp_quantization_runtime( + model_path: str | Path, + config: dict, + *, + preserve_mtp: bool, +) -> bool: + """Register Qwen4 and bind its mmap PLE/MTP state for quantization.""" + if not _is_qwen4_exp_config(config): + return False + from omlx.patches.mlx_vlm_qwen4_exp_compat import configure_qwen4_exp_runtime + + configure_qwen4_exp_runtime( + model_path, + mode="mmap", + mtp_enabled=bool(preserve_mtp), + ) + return True + + _MAX_MODEL_RAM_FRACTION = 0.75 # Auto-built proxy for sensitivity measurement when the source model @@ -153,6 +185,28 @@ def _is_vlm_load(config: dict) -> bool: ) +def _calibration_model_settings( + config: dict, + *, + has_mtp_heads: bool, + has_mtp_weights: bool, +): + """Build the temporary serving settings used by calibration loads.""" + mtp_enabled = bool(has_mtp_heads and has_mtp_weights) + if not mtp_enabled and not _is_qwen4_exp_config(config): + return None + from types import SimpleNamespace + + return SimpleNamespace( + mtp_enabled=mtp_enabled, + mtp_num_draft_tokens=1, + # Calibration executes Qwen4 PLE, but only as sparse row gathers. + # Force the existing SSD mmap path even when a compact proxy falls + # below serving's automatic offload threshold. + qwen4_ple_ssd_offload=_is_qwen4_exp_config(config), + ) + + def _uses_quantized_source_sensitivity(config: dict) -> bool: """Return whether source sensitivity must perturb quantized modules.""" quantization_config = config.get("quantization_config") or {} @@ -340,14 +394,7 @@ def _is_qwen4_exp_ngram_embedding_tensor(path: str, config: dict) -> bool: forms so proxy construction and final streaming quantization use the same policy. """ - text_config = config.get("text_config") - if not isinstance(text_config, dict): - text_config = {} - model_types = ( - str(config.get("model_type") or "").lower(), - str(text_config.get("model_type") or "").lower(), - ) - if not any(model_type.startswith("qwen4_exp") for model_type in model_types): + if not _is_qwen4_exp_config(config): return False return _QWEN4_EXP_NGRAM_SHARD_RE.search(_normalize_quant_path(path)) is not None @@ -3226,7 +3273,11 @@ def estimate_bpw_and_size( # the raw header names when discovery is unavailable. plan_view = None try: - _sanitize_fn = _build_model_sanitizer(config) + _sanitize_fn = _build_model_sanitizer( + config, + model_path=source, + preserve_mtp=preserve_mtp, + ) if _sanitize_fn is not None: _plan = _discover_sanitize_plan(_sanitize_fn, idx) if _plan: @@ -3467,6 +3518,40 @@ def _metal_available_memory_bytes() -> int: return max(0, max_working_set - active) +def _calibration_capability_capacity_bytes( + fallback_system_bytes: int = 0, +) -> int: + """Return stable hardware/configuration capacity for calibration.""" + tier = "balanced" + custom_ceiling_bytes = 0 + try: + from omlx.settings import get_settings + + memory = get_settings().memory + tier = str(memory.memory_guard_tier) + custom_ceiling_bytes = int( + float(memory.memory_guard_custom_ceiling_gb) * 1024**3 + ) + except Exception: + # Direct library callers may not have initialized GlobalSettings. + pass + + try: + from omlx.process_memory_enforcer import ( + get_memory_capability_ceiling_bytes, + ) + + capacity = get_memory_capability_ceiling_bytes( + tier, + custom_ceiling_bytes, + ) + if capacity > 0: + return int(capacity) + except Exception as exc: + logger.debug("Calibration capability ceiling unavailable: %s", exc) + return max(0, int(fallback_system_bytes)) + + def _checkpoint_storage_bytes(weight_files) -> int: """Return the complete on-disk size of checkpoint weight shards. @@ -3484,28 +3569,109 @@ def _checkpoint_storage_bytes(weight_files) -> int: return total +def _qwen4_exp_checkpoint_roots(model_path: str | Path, config: dict) -> set[Path]: + """Return the compute and optional bounded external PLE artifact roots.""" + compute_path = Path(model_path).expanduser().resolve() + roots = {compute_path} + artifact = config.get("qwen4_exp_artifact") or {} + relative_ple = artifact.get("ple_artifact") + if relative_ple is None: + return roots + relative_ple = Path(relative_ple) + if relative_ple.is_absolute(): + return roots + candidate = (compute_path / relative_ple).resolve() + artifact_root = compute_path.parent.resolve() + if candidate == artifact_root or artifact_root in candidate.parents: + roots.add(candidate) + return roots + + +def _calibration_resident_checkpoint_bytes( + model_path: str | Path, + config: dict, +) -> int: + """Estimate checkpoint bytes touched by calibration model forwards. + + Ordinary architectures retain the historical complete-file accounting. + Qwen4-Exp calibration reads PLE rows through SSD mmap and its manual text + layer walk invokes neither the vision tower nor the ordinary ``lm_head``. + Safetensors headers and every other tensor remain charged to the model. + """ + roots = ( + _qwen4_exp_checkpoint_roots(model_path, config) + if _is_qwen4_exp_config(config) + else {Path(model_path)} + ) + weight_files = sorted( + {path.resolve() for root in roots for path in root.glob("*.safetensors")} + ) + checkpoint_bytes = _checkpoint_storage_bytes(weight_files) + if not _is_qwen4_exp_config(config): + return checkpoint_bytes + + deferred_bytes = 0 + for path in weight_files: + try: + with path.open("rb") as file: + raw_size = file.read(8) + if len(raw_size) != 8: + continue + header_size = _struct.unpack(" dict[str, int | bool]: - """Return the live memory budget for full-model calibration forwards. - - Apple Silicon uses unified memory, but Metal exposes a recommended working - set that can be smaller than physical RAM. The safe capacity is therefore - the smaller positive value of live system memory and remaining Metal - working-set memory. A proportional 25% reserve scales down to 16/32 GiB - machines without imposing a fixed reserve that would reject every model. + """Return the stable capability budget for calibration forwards. + + Hard admission uses total RAM minus the configured tier's OS reserve, + capped by Metal (and by a configured custom ceiling). Live availability is + retained as diagnostics and for downstream micro-batch sizing, but other + applications and transient file cache do not redefine machine capability. + A proportional 25% reserve remains between the resident checkpoint and + the stable capability ceiling. """ system_available = _system_available_memory_bytes() metal_available = _metal_available_memory_bytes() - candidates = [value for value in (system_available, metal_available) if value > 0] - capacity = min(candidates) if candidates else max(0, int(fallback_system_bytes)) + live_candidates = [ + value for value in (system_available, metal_available) if value > 0 + ] + live_capacity = min(live_candidates) if live_candidates else 0 + capability_capacity = _calibration_capability_capacity_bytes( + fallback_system_bytes=fallback_system_bytes, + ) + capacity = capability_capacity or live_capacity or max( + 0, int(fallback_system_bytes) + ) model_limit = int(capacity * _MAX_MODEL_RAM_FRACTION) checkpoint_bytes = max(0, int(checkpoint_bytes)) return { "system_available_bytes": int(system_available), "metal_available_bytes": int(metal_available), + "live_capacity_bytes": int(live_capacity), + "capability_capacity_bytes": int(capability_capacity), "capacity_bytes": int(capacity), "model_limit_bytes": int(model_limit), "reserve_bytes": max(0, int(capacity) - int(model_limit)), @@ -3791,7 +3957,13 @@ def _cast_passthrough_tensor(tensor_name: str, w_mx, target_dtype): return w_mx -def _build_model_sanitizer(config: dict, text_only: bool = False): +def _build_model_sanitizer( + config: dict, + text_only: bool = False, + *, + model_path: str | Path | None = None, + preserve_mtp: bool = False, +): """Build a sanitize function from the model class. For VLM models, uses mlx-vlm's model class (preserves vision weights). @@ -3820,6 +3992,27 @@ def _build_model_sanitizer(config: dict, text_only: bool = False): or model_type in VLM_NATIVE_TEXT_MODEL_TYPES ) and not (text_only or mlx_lm_text_only) + # Serving normally registers oMLX's vendored Qwen4 implementation before + # mlx-vlm class lookup. Quantization does not pass through that loader. + # Without this setup the lookup fails, sanitize is skipped, and the raw + # packed MoE tensors (which lack a ``.weight`` suffix) remain BF16. + if _is_qwen4_exp_config(config): + try: + if model_path is not None: + _configure_qwen4_exp_quantization_runtime( + model_path, + config, + preserve_mtp=preserve_mtp, + ) + else: + from omlx.patches.mlx_vlm_qwen4_exp_compat import ( + apply_mlx_vlm_qwen4_exp_compat_patch, + ) + + apply_mlx_vlm_qwen4_exp_compat_patch() + except Exception as patch_err: + logger.debug("Qwen4-Exp quantization patch not applied: %s", patch_err) + if is_vlm: try: try: @@ -4349,8 +4542,6 @@ def _gs_for_mode(bits: int, default_gs: int) -> int: # --- chunked-quantize helpers (added for Qwen3.5-397B) --------------------- -import struct as _struct - import numpy as _np @@ -5736,12 +5927,13 @@ def cb( if _model_requires_proxy and static_sensitivity_map is None: logger.info( f"oQ{oq_level:g}: calibration footprint ({_format_size(_calibration_bytes)}) " - f"exceeds {int(_MAX_MODEL_RAM_FRACTION * 100)}% of calibration " - f"capacity ({_format_size(int(_calibration_budget['capacity_bytes']))}; " + f"exceeds {int(_MAX_MODEL_RAM_FRACTION * 100)}% of stable calibration " + "capability " + f"({_format_size(int(_calibration_budget['capacity_bytes']))}; " f"limit={_format_size(int(_calibration_budget['model_limit_bytes']))}, " - "system available=" + "live system available=" f"{_format_size(int(_calibration_budget['system_available_bytes']))}, " - "Metal available=" + "live Metal available=" f"{_format_size(int(_calibration_budget['metal_available_bytes']))}). " "Full-model calibration will use a proxy." ) @@ -5778,8 +5970,12 @@ def _ensure_ram_safe_proxy() -> Path: preserve_mtp=preserve_mtp, ) proxy_bytes = _checkpoint_storage_bytes(candidate.glob("*.safetensors")) + proxy_resident_bytes = _calibration_resident_checkpoint_bytes( + candidate, + config, + ) proxy_budget = _calibration_memory_budget( - proxy_bytes, + proxy_resident_bytes, fallback_system_bytes=_system_ram, ) if int(proxy_budget["capacity_bytes"]) > 0 and bool( @@ -5787,16 +5983,21 @@ def _ensure_ram_safe_proxy() -> Path: ): shutil.rmtree(candidate, ignore_errors=True) raise RuntimeError( - "calibration proxy is still too large for the live memory " + "calibration proxy is still too large for the stable capability " f"budget (proxy={_format_size(proxy_bytes)}, " + f"resident={_format_size(proxy_resident_bytes)}, " f"limit={_format_size(int(proxy_budget['model_limit_bytes']))}, " - f"capacity={_format_size(int(proxy_budget['capacity_bytes']))})" + f"capability={_format_size(int(proxy_budget['capacity_bytes']))}, " + f"live={_format_size(int(proxy_budget['live_capacity_bytes']))})" ) _ram_safe_proxy_dir = candidate logger.info( f"oQ{oq_level:g}: calibration proxy size " - f"{_format_size(proxy_bytes)} within " - f"{_format_size(int(proxy_budget['model_limit_bytes']))} limit" + f"{_format_size(proxy_bytes)} on disk, resident calibration " + f"footprint {_format_size(proxy_resident_bytes)} within " + f"{_format_size(int(proxy_budget['model_limit_bytes']))} stable " + "capability limit (live capacity " + f"{_format_size(int(proxy_budget['live_capacity_bytes']))})" ) return _ram_safe_proxy_dir @@ -5996,7 +6197,12 @@ def _imatrix_load_path() -> str: ) # --- Sanitize-plan discovery ------------------------------------------ - sanitize_fn = _build_model_sanitizer(config, text_only=text_only) + sanitize_fn = _build_model_sanitizer( + config, + text_only=text_only, + model_path=source, + preserve_mtp=preserve_mtp, + ) cast_predicate = getattr(sanitize_fn, "_omlx_cast_predicate", None) # When preserve_mtp is True, the patched sanitize functions # (mlx_lm_mtp/qwen35_model.py and mlx_vlm_mtp/qwen35_vlm_model.py) @@ -7638,11 +7844,33 @@ def _collect_imatrix_from_model( seq_length=seq_length, ) if calib_data is None: - return {}, {"dataset": calib_dataset, "processed_samples": 0} + return {}, { + "dataset": calib_dataset, + "processed_samples": 0, + "failure_stage": "dataset", + "failure_reason": "calibration dataset produced no usable samples", + } embed_fn, layers = _find_model_layers(model) if embed_fn is None or layers is None: - return {}, {"dataset": calib_dataset, "processed_samples": 0} + return {}, { + "dataset": calib_dataset, + "processed_samples": 0, + "model_class": f"{type(model).__module__}.{type(model).__name__}", + "failure_stage": "layer_discovery", + "failure_reason": "no embedding function or decoder layers found", + } + + layer_model = _find_layer_model(model, layers) + layer_args = getattr(layer_model, "args", None) + layer_config = getattr(layer_model, "config", None) + layer_model_type = str( + getattr(layer_args, "model_type", "") + or getattr(layer_config, "model_type", "") + or getattr(model, "model_type", "") + or "" + ) + layer_count = len(layers) collector = OQImatrixCollector() installed = collector.install(model) @@ -7651,6 +7879,16 @@ def _collect_imatrix_from_model( "dataset": calib_dataset, "installed_modules": 0, "processed_samples": 0, + "model_class": f"{type(model).__module__}.{type(model).__name__}", + "layer_model_class": ( + f"{type(layer_model).__module__}.{type(layer_model).__name__}" + if layer_model is not None + else None + ), + "layer_model_type": layer_model_type, + "layer_count": layer_count, + "failure_stage": "collector_install", + "failure_reason": "no supported capture modules found", } available_samples = int(calib_data.shape[0]) @@ -7673,6 +7911,10 @@ def _collect_imatrix_from_model( micro_batch_size = int(batch_plan["micro_batch_size"]) processed_samples = 0 micro_batches = 0 + layer_state_kind = None + successful_layer_forwards = 0 + skipped_layer_forwards = 0 + mtp_head_forwards = 0 rounds: list[dict[str, Any]] = [] require_expert_counts = _imatrix_requires_expert_counts( config, collector.switch_capture_modules @@ -7702,6 +7944,10 @@ def _collect_imatrix_from_model( inputs, layer_masks, position_ids = _prepare_layer_inputs( model, layers, batch, inputs ) + if isinstance(position_ids, dict): + layer_state_kind = position_ids.get("kind") + elif layer_state_kind is None: + layer_state_kind = "generic" inner = getattr(model, "language_model", None) or model args = getattr(inner, "args", None) @@ -7728,7 +7974,9 @@ def _collect_imatrix_from_model( layer_idx=layer_idx, ) if out is None: + skipped_layer_forwards += 1 continue + successful_layer_forwards += 1 mx.eval(out) inputs = out # DSpark config uses one-based completed layer depths, @@ -7754,6 +8002,7 @@ def _collect_imatrix_from_model( inputs, dspark_hiddens=dspark_hiddens, ): + mtp_head_forwards += 1 mx.synchronize() mx.clear_cache() @@ -7853,6 +8102,18 @@ def _collect_imatrix_from_model( "micro_batches": micro_batches, "batch_plan": batch_plan, "processed_samples": processed_samples, + "model_class": f"{type(model).__module__}.{type(model).__name__}", + "layer_model_class": ( + f"{type(layer_model).__module__}.{type(layer_model).__name__}" + if layer_model is not None + else None + ), + "layer_model_type": layer_model_type, + "layer_count": layer_count, + "layer_state_kind": layer_state_kind, + "successful_layer_forwards": successful_layer_forwards, + "skipped_layer_forwards": skipped_layer_forwards, + "mtp_head_forwards": mtp_head_forwards, "installed_modules": installed, "capture_module_classes": dict( sorted(collector.capture_module_classes.items()) @@ -7864,6 +8125,19 @@ def _collect_imatrix_from_model( "coverage": coverage, "rounds": rounds, } + if not collector.entries: + metadata["failure_stage"] = "layer_forward" + if successful_layer_forwards == 0: + metadata["failure_reason"] = ( + "no decoder layer forward completed successfully" + ) + else: + metadata["failure_stage"] = "capture" + metadata["failure_reason"] = ( + f"{installed} hooks were installed and " + f"{successful_layer_forwards} layer forwards completed, " + "but no hook captured a compatible activation" + ) return collector.entries, metadata @@ -7888,14 +8162,11 @@ def _collect_imatrix( is_vlm = _is_vlm_load(config) has_mtp_weights = _checkpoint_has_mtp_weights(model_path) has_mtp_heads = _has_mtp_heads(config) - calibration_settings = None - if has_mtp_heads and has_mtp_weights: - from types import SimpleNamespace - - calibration_settings = SimpleNamespace( - mtp_enabled=True, - mtp_num_draft_tokens=1, - ) + calibration_settings = _calibration_model_settings( + config, + has_mtp_heads=has_mtp_heads, + has_mtp_weights=has_mtp_weights, + ) patch_kwargs: dict[str, Any] = {"for_vlm": is_vlm} if calibration_settings is not None: patch_kwargs["model_settings"] = calibration_settings @@ -7929,24 +8200,19 @@ def _restore_mtp_active(): try: if is_vlm: - import mlx.nn as _nn from mlx_vlm.utils import load_model as vlm_load_model - _orig_lw = _nn.Module.load_weights - - def _lenient_load_weights(self, file_or_weights, *args, **kwargs): - kwargs.pop("strict", None) - return _orig_lw(self, file_or_weights, *args, strict=False, **kwargs) - - _nn.Module.load_weights = _lenient_load_weights - try: - model = vlm_load_model( - Path(model_path), - lazy=True, - trust_remote_code=trust_remote_code, - ) - finally: - _nn.Module.load_weights = _orig_lw + # Calibration proxies deliberately retain SSD-mapped tensors that + # are consumed by model-specific mmap modules rather than owned as + # normal MLX parameters (Qwen4 PLE shards are the primary case). + # mlx-vlm exposes ``strict`` specifically for this final weight + # load; pass it directly instead of monkeypatching Module globally. + model = vlm_load_model( + Path(model_path), + lazy=True, + trust_remote_code=trust_remote_code, + strict=False, + ) from mlx_lm.tokenizer_utils import load as load_tokenizer tokenizer = load_tokenizer(Path(model_path)) @@ -7961,13 +8227,13 @@ def _lenient_load_weights(self, file_or_weights, *args, **kwargs): ) except Exception as e: logger.error("oQe imatrix: model load failed (%s)", e) - return {}, {"dataset": calib_dataset, "processed_samples": 0} + raise RuntimeError(f"oQe imatrix model load failed: {e}") from e finally: if restore_mtp_active is not None: restore_mtp_active() try: - model_bytes = _checkpoint_storage_bytes(Path(model_path).glob("*.safetensors")) + model_bytes = _calibration_resident_checkpoint_bytes(model_path, config) return _collect_imatrix_from_model( model, tokenizer, @@ -8086,7 +8352,16 @@ def _load_or_collect_imatrix( progress_end=progress_end, ) if not entries: - raise RuntimeError("oQe imatrix collection produced no entries") + stage = str(collection_metadata.get("failure_stage", "unknown")) + reason = str( + collection_metadata.get( + "failure_reason", "collector returned no captured activations" + ) + ) + raise RuntimeError( + "oQe imatrix collection produced no entries " + f"(stage={stage}: {reason})" + ) metadata = { **expected, "entry_count": len(entries), @@ -8228,14 +8503,11 @@ def _measure_sensitivity( # Reuse the centralised pre-load dispatch so every current and future # patch (MTP sanitize, DeepSeek V4, nested-visual, load_config, …) is # applied exactly as in the production load path. - calibration_settings = None - if has_mtp_heads and has_mtp_weights: - from types import SimpleNamespace - - calibration_settings = SimpleNamespace( - mtp_enabled=True, - mtp_num_draft_tokens=1, - ) + calibration_settings = _calibration_model_settings( + config, + has_mtp_heads=has_mtp_heads, + has_mtp_weights=has_mtp_weights, + ) patch_kwargs: dict[str, Any] = {"for_vlm": is_vlm} if calibration_settings is not None: patch_kwargs["model_settings"] = calibration_settings @@ -8265,31 +8537,17 @@ def _measure_sensitivity( try: if is_vlm: - import mlx.nn as _nn from mlx_vlm.utils import load_model as vlm_load_model - # mlx_vlm.load_model calls model.load_weights(weights) without strict=False. - # Shared-KV models (e.g. Gemma 4 2B/4B) omit k/v weights for shared layers, - # so strict=True raises ValueError. Relax temporarily — sensitivity only needs - # approximate weights; shared layers receive pre-computed KV at inference time. - _orig_lw = _nn.Module.load_weights - - def _lenient_load_weights(self, file_or_weights, *args, **kwargs): - kwargs.pop("strict", None) - return _orig_lw(self, file_or_weights, *args, strict=False, **kwargs) - - _nn.Module.load_weights = _lenient_load_weights - try: - # No QAT config override needed here: mlx_vlm.utils.load_model - # uses quantization_config.get("quant_method") rather than direct - # key access, so a missing quant_method falls through silently. - model = vlm_load_model( - Path(model_path), - lazy=True, - trust_remote_code=trust_remote_code, - ) - finally: - _nn.Module.load_weights = _orig_lw + # Sensitivity uses the same proxy representation as imatrix + # calibration. Allow intentionally unowned mmap/shared-KV tensors + # through mlx-vlm's supported load option. + model = vlm_load_model( + Path(model_path), + lazy=True, + trust_remote_code=trust_remote_code, + strict=False, + ) from mlx_lm.tokenizer_utils import load as load_tokenizer tokenizer = load_tokenizer(Path(model_path)) @@ -8430,7 +8688,12 @@ def _build_streaming_proxy_for_sensitivity( raise ValueError(f"No .safetensors files found in {model_path}") all_weights = _LazyTensorIndex(weight_files, config=config) - sanitize_fn = _build_model_sanitizer(config, text_only=False) + sanitize_fn = _build_model_sanitizer( + config, + text_only=False, + model_path=source, + preserve_mtp=preserve_mtp, + ) cast_predicate = getattr(sanitize_fn, "_omlx_cast_predicate", None) if sanitize_fn is not None: try: @@ -8649,14 +8912,11 @@ def _measure_sensitivity_from_quantized_model( is_vlm = _is_vlm_load(config) has_mtp_weights = _checkpoint_has_mtp_weights(model_path) has_mtp_heads = _has_mtp_heads(config) - calibration_settings = None - if has_mtp_heads and has_mtp_weights: - from types import SimpleNamespace - - calibration_settings = SimpleNamespace( - mtp_enabled=True, - mtp_num_draft_tokens=1, - ) + calibration_settings = _calibration_model_settings( + config, + has_mtp_heads=has_mtp_heads, + has_mtp_weights=has_mtp_weights, + ) patch_kwargs: dict[str, Any] = {"for_vlm": is_vlm} if calibration_settings is not None: patch_kwargs["model_settings"] = calibration_settings @@ -8693,6 +8953,11 @@ def _measure_sensitivity_from_quantized_model( Path(model_path), lazy=True, trust_remote_code=trust_remote_code, + # Quantized calibration proxies may retain model-specific + # tensors consumed directly by mmap modules rather than + # represented as ordinary MLX parameters (Qwen4 PLE shards). + # Match the imatrix and non-proxy sensitivity load paths. + strict=False, ) tokenizer = load_tokenizer(Path(model_path)) else: diff --git a/omlx/process_memory_enforcer.py b/omlx/process_memory_enforcer.py index f99f6bce33..9afce8fd0e 100644 --- a/omlx/process_memory_enforcer.py +++ b/omlx/process_memory_enforcer.py @@ -75,6 +75,22 @@ "aggressive": 0.8, } + +def _static_memory_ceiling_bytes(system_bytes: int, tier: str) -> int: + """Return total RAM minus the tier-scaled OS reserve.""" + system_bytes = max(0, int(system_bytes)) + tier = (tier or "").strip().lower() + if tier not in _STATIC_RESERVE_LARGE: + tier = "balanced" + if tier == "custom": + reserve = _STATIC_RESERVE_LARGE["custom"] + elif system_bytes < _SMALL_SYSTEM_THRESHOLD: + reserve = _SMALL_SYSTEM_RESERVE + else: + reserve = _STATIC_RESERVE_LARGE[tier] + return max(0, system_bytes - reserve) + + # Default soft watermark per tier. A saved 0.85 from older configs is treated # as the legacy default so balanced / aggressive can move to their tier defaults. _LEGACY_SOFT_THRESHOLD = 0.85 @@ -184,6 +200,37 @@ def get_effective_metal_cap_bytes() -> int: return _get_max_metal_working_set_bytes() +def get_memory_capability_ceiling_bytes( + memory_guard_tier: str = "balanced", + memory_guard_custom_ceiling_bytes: int = 0, +) -> int: + """Return the stable machine/configuration memory ceiling. + + Unlike the enforcer's dynamic ceiling, this deliberately excludes live + free/active/inactive page counts. It answers whether the machine is + fundamentally capable of a workload: total RAM minus the tier's static OS + reserve, capped by Metal and by an explicit custom ceiling when configured. + """ + tier = (memory_guard_tier or "").strip().lower() + if tier not in _STATIC_RESERVE_LARGE: + tier = "balanced" + try: + total = max(0, int(_settings.get_system_memory())) + except Exception: # noqa: BLE001 + total = 0 + + static_ceiling = _static_memory_ceiling_bytes(total, tier) + + candidates = [static_ceiling] if static_ceiling > 0 else [] + metal_cap = get_effective_metal_cap_bytes() + if metal_cap > 0: + candidates.append(int(metal_cap)) + custom_ceiling = max(0, int(memory_guard_custom_ceiling_bytes)) + if tier == "custom" and custom_ceiling > 0: + candidates.append(custom_ceiling) + return min(candidates) if candidates else 0 + + def _wired_limit_suggestion_bytes(desired_bytes: int) -> int: """Clamp and align a wired-limit recommendation to leave 5% of RAM. @@ -563,16 +610,12 @@ def wake(self, *, active: bool = False) -> None: def _get_static_ceiling(self) -> int: """Total RAM minus tier-scaled static reserve.""" - from .settings import get_system_memory - - system_bytes = get_system_memory() - if self._memory_guard_tier == "custom": - return max(0, system_bytes - _STATIC_RESERVE_LARGE["custom"]) - if system_bytes < _SMALL_SYSTEM_THRESHOLD: - reserve = _SMALL_SYSTEM_RESERVE - else: - reserve = _STATIC_RESERVE_LARGE[self._memory_guard_tier] - return max(0, system_bytes - reserve) + tier = self._memory_guard_tier + try: + system_bytes = max(0, int(_settings.get_system_memory())) + except Exception: # noqa: BLE001 + system_bytes = 0 + return _static_memory_ceiling_bytes(system_bytes, tier) def _get_dynamic_ceiling(self) -> int: """Tier-aware reclaimable-memory ceiling. diff --git a/tests/test_oq.py b/tests/test_oq.py index eb08ebc79a..3265b39268 100644 --- a/tests/test_oq.py +++ b/tests/test_oq.py @@ -3025,6 +3025,68 @@ def test_checkpoint_storage_counts_hidden_fp8_scales(self, tmp_path): assert index.nbytes() == weight.nbytes assert _checkpoint_storage_bytes([path]) >= weight.nbytes + scales.nbytes + def test_qwen4_calibration_charges_only_touched_resident_storage(self, tmp_path): + from safetensors.numpy import save_file as np_save + + from omlx.oq import _calibration_resident_checkpoint_bytes + + resident = np.zeros((32, 64), dtype=np.float16) + ple_weight = np.zeros((256, 20), dtype=np.uint32) + ple_scales = np.zeros((256, 5), dtype=np.float16) + ple_biases = np.zeros((256, 5), dtype=np.float16) + vision = np.zeros((16, 64), dtype=np.float16) + lm_head = np.zeros((32, 64), dtype=np.float16) + ple = ( + "language_model.model.layers.1.ple.ple_embedding." + "ngram_embedding.shards.0" + ) + tensors = { + "language_model.model.layers.0.self_attn.q_proj.weight": resident, + f"{ple}.weight": ple_weight, + f"{ple}.scales": ple_scales, + f"{ple}.biases": ple_biases, + "vision_tower.blocks.0.attn.q_proj.weight": vision, + "language_model.lm_head.weight": lm_head, + } + path = tmp_path / "model.safetensors" + np_save(tensors, str(path)) + config = { + "model_type": "qwen4_exp", + "text_config": {"model_type": "qwen4_exp_text"}, + } + + deferred = sum( + tensor.nbytes + for name, tensor in tensors.items() + if name.startswith(ple) + or name.startswith("vision_tower.") + or name.endswith("lm_head.weight") + ) + assert _calibration_resident_checkpoint_bytes(tmp_path, config) == ( + path.stat().st_size - deferred + ) + + def test_non_qwen4_resident_accounting_remains_complete_storage(self, tmp_path): + from safetensors.numpy import save_file as np_save + + from omlx.oq import _calibration_resident_checkpoint_bytes + + path = tmp_path / "model.safetensors" + np_save( + { + "model.layers.0.weight": np.zeros((32, 64), dtype=np.float16), + # A similarly named tensor has no mmap contract on other models. + "model.ngram_embedding.shards.0.weight": np.zeros( + (128, 64), dtype=np.float16 + ), + }, + str(path), + ) + + assert _calibration_resident_checkpoint_bytes( + tmp_path, {"model_type": "llama"} + ) == path.stat().st_size + @pytest.mark.parametrize("capacity_gib", [16, 32, 64]) def test_budget_reserves_25_percent_on_smaller_systems( self, monkeypatch, capacity_gib @@ -3034,10 +3096,7 @@ def test_budget_reserves_25_percent_on_smaller_systems( gib = 1024**3 capacity = capacity_gib * gib monkeypatch.setattr( - oq_module, "_system_available_memory_bytes", lambda: capacity - ) - monkeypatch.setattr( - oq_module, "_metal_available_memory_bytes", lambda: capacity + oq_module, "_calibration_capability_capacity_bytes", lambda **_k: capacity ) budget = _calibration_memory_budget() @@ -3046,15 +3105,14 @@ def test_budget_reserves_25_percent_on_smaller_systems( assert budget["model_limit_bytes"] == int(capacity * 0.75) assert budget["reserve_bytes"] == capacity - int(capacity * 0.75) - def test_budget_uses_smaller_metal_working_set(self, monkeypatch): + def test_budget_uses_stable_capability_ceiling(self, monkeypatch): from omlx import oq as oq_module gib = 1024**3 monkeypatch.setattr( - oq_module, "_system_available_memory_bytes", lambda: 512 * gib - ) - monkeypatch.setattr( - oq_module, "_metal_available_memory_bytes", lambda: 464 * gib + oq_module, + "_calibration_capability_capacity_bytes", + lambda **_k: 464 * gib, ) budget = _calibration_memory_budget(413 * gib) @@ -3068,18 +3126,87 @@ def test_guard_boundary_is_strict(self, monkeypatch): capacity = 4000 monkeypatch.setattr( - oq_module, "_system_available_memory_bytes", lambda: capacity - ) - monkeypatch.setattr( - oq_module, "_metal_available_memory_bytes", lambda: capacity + oq_module, "_calibration_capability_capacity_bytes", lambda **_k: capacity ) at_limit = int(capacity * _MAX_MODEL_RAM_FRACTION) assert _calibration_memory_budget(at_limit)["requires_proxy"] is False assert _calibration_memory_budget(at_limit + 1)["requires_proxy"] is True + def test_capability_admission_ignores_live_memory_pressure(self, monkeypatch): + from omlx import oq as oq_module + + gib = 1024**3 + capability = int(107.5 * gib) + monkeypatch.setattr( + oq_module, + "_calibration_capability_capacity_bytes", + lambda **_k: capability, + ) + monkeypatch.setattr( + oq_module, "_system_available_memory_bytes", lambda: int(72.9 * gib) + ) + monkeypatch.setattr( + oq_module, "_metal_available_memory_bytes", lambda: int(107.5 * gib) + ) + + budget = _calibration_memory_budget(int(67.0 * gib)) + + assert budget["live_capacity_bytes"] == int(72.9 * gib) + assert budget["capacity_bytes"] == capability + assert budget["model_limit_bytes"] == int(capability * 0.75) + assert budget["requires_proxy"] is False + + def test_capability_admission_still_rejects_unsafe_resident_model( + self, monkeypatch + ): + from omlx import oq as oq_module + + gib = 1024**3 + capability = int(107.5 * gib) + monkeypatch.setattr( + oq_module, + "_calibration_capability_capacity_bytes", + lambda **_k: capability, + ) + monkeypatch.setattr( + oq_module, "_system_available_memory_bytes", lambda: int(72.9 * gib) + ) + monkeypatch.setattr( + oq_module, "_metal_available_memory_bytes", lambda: int(107.5 * gib) + ) + + budget = _calibration_memory_budget(int(81.0 * gib)) + + assert budget["model_limit_bytes"] == int(capability * 0.75) + assert budget["requires_proxy"] is True + class TestOqeCalibrationBatchPlan: + def test_qwen4_calibration_forces_ssd_ple_and_keeps_mtp(self): + from omlx.oq import _calibration_model_settings + + settings = _calibration_model_settings( + {"model_type": "qwen4_exp"}, + has_mtp_heads=True, + has_mtp_weights=True, + ) + + assert settings.qwen4_ple_ssd_offload is True + assert settings.mtp_enabled is True + + def test_ordinary_non_mtp_calibration_has_no_serving_override(self): + from omlx.oq import _calibration_model_settings + + assert ( + _calibration_model_settings( + {"model_type": "llama"}, + has_mtp_heads=False, + has_mtp_weights=False, + ) + is None + ) + def test_subtracts_lazy_model_footprint(self, monkeypatch): from omlx import oq as oq_module @@ -3418,6 +3545,80 @@ def test_qwen4_streaming_proxy_records_group32_for_ngram_table(self, tmp_path): assert f"{prefix}.key_proj" not in quantization assert f"{prefix}.value_proj" not in quantization + @pytest.mark.skipif(not HAS_MLX, reason="MLX not available") + def test_qwen4_proxy_quantizes_packed_experts_and_preserves_mtp_vision( + self, tmp_path, monkeypatch + ): + """Exercise the source layout that produced the 263.1 GiB proxy.""" + from safetensors import safe_open + from safetensors.numpy import save_file as np_save + + src = tmp_path / "src" + out = tmp_path / "proxy" + src.mkdir() + config = { + "model_type": "qwen4_exp", + "architectures": ["Qwen4ExpForConditionalGeneration"], + "text_config": {"model_type": "qwen4_exp_text"}, + "vision_config": {"hidden_size": 16}, + } + (src / "config.json").write_text(json.dumps(config), encoding="utf-8") + raw = "model.language_model.layers.0.mlp.experts" + ngram = ( + "model.language_model.layers.0.ple.ple_embedding." + "ngram_embedding.shard_0" + ) + vision = "model.visual.blocks.0.attn.q_proj.weight" + np_save( + { + f"{raw}.gate_up_proj": np.ones((2, 128, 64), dtype=np.float16), + f"{raw}.down_proj": np.ones((2, 64, 64), dtype=np.float16), + f"{ngram}.weight": np.ones((4, 160), dtype=np.float16), + "mtp.fc_hidden.weight": np.ones((64, 64), dtype=np.float16), + vision: np.ones((16, 64), dtype=np.float16), + }, + str(src / "model.safetensors"), + ) + + def qwen4_sanitize(weights): + gate_up = weights.pop(f"{raw}.gate_up_proj") + gate, up = mx.split(gate_up, 2, axis=-2) + prefix = "language_model.model.layers.0.mlp.switch_mlp" + weights[f"{prefix}.gate_proj.weight"] = gate + weights[f"{prefix}.up_proj.weight"] = up + weights[f"{prefix}.down_proj.weight"] = weights.pop( + f"{raw}.down_proj" + ) + return weights + + monkeypatch.setattr( + "omlx.oq._build_model_sanitizer", + lambda *_args, **_kwargs: qwen4_sanitize, + ) + monkeypatch.setattr("omlx.oq._build_non_quantizable_set", lambda _c: set()) + _build_streaming_proxy_for_sensitivity( + str(src), + out, + dtype="bfloat16", + preserve_mtp=True, + ) + + keys = set() + for path in out.glob("*.safetensors"): + with safe_open(str(path), framework="numpy") as file: + keys.update(file.keys()) + prefix = "language_model.model.layers.0.mlp.switch_mlp" + for projection in ("gate_proj", "up_proj", "down_proj"): + assert f"{prefix}.{projection}.scales" in keys + assert not any("mlp.experts.gate_up_proj" in key for key in keys) + assert f"{ngram}.scales" in keys + assert "mtp.fc_hidden.scales" in keys + assert vision in keys + assert vision.removesuffix(".weight") + ".scales" not in keys + + quantization = json.loads((out / "config.json").read_text())["quantization"] + assert quantization[ngram]["group_size"] == 32 + class TestSensitivityRequiredEnforcement: """Regression tests: quantize_oq_streaming must abort when sensitivity @@ -3443,6 +3644,9 @@ def test_opt_out_with_model_exceeding_ram_raises(self, tmp_path, monkeypatch): from omlx import settings as _settings monkeypatch.setattr(_settings, "get_system_memory", lambda: 0) + monkeypatch.setattr( + _oq, "_calibration_capability_capacity_bytes", lambda **_k: 0 + ) monkeypatch.setattr(_oq, "_system_available_memory_bytes", lambda: 0) monkeypatch.setattr(_oq, "_metal_available_memory_bytes", lambda: 0) @@ -3484,6 +3688,9 @@ def test_streaming_discovery_failure_with_model_exceeding_ram_raises( from omlx import oq as _oq + monkeypatch.setattr( + _oq, "_calibration_capability_capacity_bytes", lambda **_k: 0 + ) monkeypatch.setattr(_oq, "_system_available_memory_bytes", lambda: 0) monkeypatch.setattr(_oq, "_metal_available_memory_bytes", lambda: 0) @@ -3532,6 +3739,9 @@ def test_proxy_build_failure_raises(self, tmp_path, monkeypatch): monkeypatch.setattr(_settings, "get_system_memory", lambda: 0) from omlx import oq as _oq + monkeypatch.setattr( + _oq, "_calibration_capability_capacity_bytes", lambda **_k: 0 + ) monkeypatch.setattr(_oq, "_system_available_memory_bytes", lambda: 0) monkeypatch.setattr(_oq, "_metal_available_memory_bytes", lambda: 0) @@ -3564,6 +3774,9 @@ def test_oversized_proxy_is_rejected_and_cleaned(self, tmp_path, monkeypatch): from omlx import oq as oq_module + monkeypatch.setattr( + oq_module, "_calibration_capability_capacity_bytes", lambda **_k: 1000 + ) monkeypatch.setattr(oq_module, "_system_available_memory_bytes", lambda: 1000) monkeypatch.setattr(oq_module, "_metal_available_memory_bytes", lambda: 1000) proxy = tmp_path / "proxy" @@ -3585,7 +3798,9 @@ def _fake_build(*_args, **_kwargs): assert not proxy.exists() - def test_oqe_uses_proxy_when_source_exceeds_live_limit(self, tmp_path, monkeypatch): + def test_oqe_uses_proxy_when_source_exceeds_capability_limit( + self, tmp_path, monkeypatch + ): if not HAS_MLX: pytest.skip("mlx not available") from safetensors.numpy import save_file as np_save @@ -3600,6 +3815,9 @@ def test_oqe_uses_proxy_when_source_exceeds_live_limit(self, tmp_path, monkeypat from omlx import oq as oq_module + monkeypatch.setattr( + oq_module, "_calibration_capability_capacity_bytes", lambda **_k: 1000 + ) monkeypatch.setattr(oq_module, "_system_available_memory_bytes", lambda: 1000) monkeypatch.setattr(oq_module, "_metal_available_memory_bytes", lambda: 1000) proxy = tmp_path / "proxy" @@ -4974,6 +5192,110 @@ def apply_compat_patch(): assert sanitize({"weight": 1}) == {"weight": 1} +class TestBuildModelSanitizerQwen4Compat: + def test_qwen4_applies_compat_before_model_lookup(self, monkeypatch): + pytest.importorskip("mlx_vlm.utils") + from types import SimpleNamespace + + import mlx_vlm.utils as vlm_utils + + from omlx.oq import _build_model_sanitizer + + class _Cfg: + def __init__(self, **fields): + self.__dict__.update(fields) + + @classmethod + def from_dict(cls, fields): + return cls(**fields) + + class _FakeModel: + @staticmethod + def sanitize(_proxy, weights): + return weights + + fake_module = SimpleNamespace( + Model=_FakeModel, + ModelConfig=_Cfg, + VisionConfig=_Cfg, + TextConfig=_Cfg, + VisionModel=object, + LanguageModel=object, + ) + applied = [] + + def unsupported_get_model_and_args(_config): + raise ValueError("Model type qwen4_exp not supported") + + def apply_compat_patch(): + applied.append(True) + vlm_utils.get_model_and_args = lambda _config: (fake_module, "qwen4_exp") + return True + + monkeypatch.setattr( + vlm_utils, + "get_model_and_args", + unsupported_get_model_and_args, + ) + monkeypatch.setattr( + "omlx.patches.mlx_vlm_qwen4_exp_compat." + "apply_mlx_vlm_qwen4_exp_compat_patch", + apply_compat_patch, + ) + monkeypatch.setattr( + "mlx_vlm.utils.sanitize_weights", + lambda _model, weights, _config: weights, + ) + config = { + "architectures": ["Qwen4ExpForConditionalGeneration"], + "model_type": "qwen4_exp", + "text_config": { + "model_type": "qwen4_exp_text", + "num_hidden_layers": 1, + "hidden_size": 16, + }, + "vision_config": {"hidden_size": 8}, + } + + sanitize = _build_model_sanitizer(config, text_only=False) + + assert applied == [True] + assert sanitize is not None + + def test_qwen4_model_path_binds_mmap_and_preserve_mtp( + self, tmp_path, monkeypatch + ): + from omlx import oq + + configured = MagicMock(return_value=True) + monkeypatch.setattr( + oq, + "_configure_qwen4_exp_quantization_runtime", + configured, + ) + # The registration behavior itself is covered above; this assertion + # isolates the path/MTP state passed by quantization call sites. + monkeypatch.setattr( + "omlx.patches.mlx_vlm_qwen4_exp_compat." + "apply_mlx_vlm_qwen4_exp_compat_patch", + lambda: True, + ) + oq._build_model_sanitizer( + { + "model_type": "qwen4_exp", + "architectures": [], + "text_config": {"model_type": "qwen4_exp_text"}, + }, + model_path=tmp_path, + preserve_mtp=True, + ) + + configured.assert_called_once() + assert configured.call_args.args[0] == tmp_path + assert configured.call_args.args[1]["model_type"] == "qwen4_exp" + assert configured.call_args.kwargs == {"preserve_mtp": True} + + # ============================================================================= # Test _vlm_sanitize proxy exposes the gemma-4 audio-guard attributes # ============================================================================= @@ -5321,6 +5643,78 @@ def test_uses_compat_loader_without_trust_remote_code(self, monkeypatch): assert "trust_remote_code" not in mock_load.call_args.kwargs + def test_vlm_proxy_passes_lenient_load_directly(self, monkeypatch): + """SSD-mapped proxy tensors are not normal model parameters. + + The supported mlx-vlm ``strict`` option must reach load_model itself; + patching Module.load_weights globally did not reliably affect the real + Qwen4 proxy load and rejected every retained PLE shard. + """ + import omlx.utils.model_loading as model_loading + + from omlx import oq as oq_mod + + vlm_load = MagicMock(return_value=MagicMock()) + tokenizer_load = MagicMock(return_value=MagicMock()) + monkeypatch.setitem( + sys.modules, "mlx_vlm.utils", MagicMock(load_model=vlm_load) + ) + monkeypatch.setitem( + sys.modules, + "mlx_lm.tokenizer_utils", + MagicMock(load=tokenizer_load), + ) + monkeypatch.setattr( + model_loading, "_checkpoint_has_mtp_weights", lambda _path: False + ) + monkeypatch.setattr(model_loading, "_has_mtp_heads", lambda _config: False) + monkeypatch.setattr(model_loading, "maybe_apply_pre_load_patches", MagicMock()) + monkeypatch.setattr( + oq_mod, "_collect_imatrix_from_model", MagicMock(return_value=({}, {})) + ) + + oq_mod._collect_imatrix( + "/fake/qwen4-proxy", + { + "model_type": "qwen4_exp", + "vision_config": {"hidden_size": 8}, + "text_config": {"model_type": "qwen4_exp_text"}, + }, + trust_remote_code=True, + ) + + assert vlm_load.call_args.kwargs["strict"] is False + assert vlm_load.call_args.kwargs["trust_remote_code"] is True + + def test_empty_collection_reports_the_failed_stage(self, monkeypatch, tmp_path): + from omlx import oq as oq_mod + + monkeypatch.setattr( + oq_mod, + "_collect_imatrix", + MagicMock( + return_value=( + {}, + { + "failure_stage": "collector_install", + "failure_reason": "no supported capture modules found", + }, + ) + ), + ) + + with pytest.raises(RuntimeError, match="stage=collector_install"): + oq_mod._load_or_collect_imatrix( + str(tmp_path), + {}, + cache_path=str(tmp_path / "imatrix.npz"), + reuse_cache=False, + num_samples=1, + seq_length=8, + strict=False, + trust_remote_code=False, + ) + class TestMeasureSensitivityQuantizedVlm: def test_quantized_vlm_proxy_uses_vlm_loader(self, monkeypatch): @@ -5375,6 +5769,7 @@ def test_quantized_vlm_proxy_uses_vlm_loader(self, monkeypatch): assert vlm_load.call_args.args[0] == Path("/fake/minimax-proxy") assert vlm_load.call_args.kwargs["lazy"] is True assert vlm_load.call_args.kwargs["trust_remote_code"] is True + assert vlm_load.call_args.kwargs["strict"] is False tokenizer_load.assert_called_once_with(Path("/fake/minimax-proxy")) lm_load.assert_not_called() @@ -6269,6 +6664,9 @@ def test_dequantized_footprint_flips_requires_proxy(self, monkeypatch): import omlx.oq as oq # Fixed capacity 400 -> model_limit = int(0.75 * 400) = 300. + monkeypatch.setattr( + oq, "_calibration_capability_capacity_bytes", lambda **_k: 400 + ) monkeypatch.setattr(oq, "_system_available_memory_bytes", lambda: 400) monkeypatch.setattr(oq, "_metal_available_memory_bytes", lambda: 400) diff --git a/tests/test_process_memory_enforcer.py b/tests/test_process_memory_enforcer.py index c927d74135..fac9191ac3 100644 --- a/tests/test_process_memory_enforcer.py +++ b/tests/test_process_memory_enforcer.py @@ -951,6 +951,34 @@ def test_custom_uses_2gb_reserve_on_small_system(self, mock_engine_pool): result = enforcer._get_static_ceiling() assert result == 10 * 1024**3 + def test_capability_ceiling_uses_static_ram_and_metal_cap(self): + gib = 1024**3 + with ( + patch("omlx.settings.get_system_memory", return_value=128 * gib), + patch( + "omlx.process_memory_enforcer.get_effective_metal_cap_bytes", + return_value=int(107.5 * gib), + ), + ): + result = pme.get_memory_capability_ceiling_bytes("balanced") + + assert result == int(107.5 * gib) + + def test_capability_ceiling_respects_explicit_custom_limit(self): + gib = 1024**3 + with ( + patch("omlx.settings.get_system_memory", return_value=128 * gib), + patch( + "omlx.process_memory_enforcer.get_effective_metal_cap_bytes", + return_value=int(107.5 * gib), + ), + ): + result = pme.get_memory_capability_ceiling_bytes( + "custom", 70 * gib + ) + + assert result == 70 * gib + class TestDynamicCeilingActiveRatio: """Dynamic ceiling sums free + inactive + active * tier ratio From ea3cc9a40a73fb217813f3cb4422f26ed58dc0ec Mon Sep 17 00:00:00 2001 From: jundot Date: Sat, 29 Aug 2026 23:23:28 +0900 Subject: [PATCH 040/132] fix: simplify Qwen4 calibration proxy policy --- omlx/oq.py | 121 ++++-------------- .../mlx_vlm_qwen4_exp_compat/residency.py | 30 +---- .../mlx_vlm/models/qwen4_exp/language.py | 24 +--- omlx/process_memory_enforcer.py | 64 ++------- tests/test_mlx_vlm_qwen4_exp_compat.py | 25 ---- tests/test_oq.py | 79 +++--------- tests/test_process_memory_enforcer.py | 29 ----- 7 files changed, 59 insertions(+), 313 deletions(-) diff --git a/omlx/oq.py b/omlx/oq.py index 43d3586ec3..41f9f1e37a 100644 --- a/omlx/oq.py +++ b/omlx/oq.py @@ -3518,40 +3518,6 @@ def _metal_available_memory_bytes() -> int: return max(0, max_working_set - active) -def _calibration_capability_capacity_bytes( - fallback_system_bytes: int = 0, -) -> int: - """Return stable hardware/configuration capacity for calibration.""" - tier = "balanced" - custom_ceiling_bytes = 0 - try: - from omlx.settings import get_settings - - memory = get_settings().memory - tier = str(memory.memory_guard_tier) - custom_ceiling_bytes = int( - float(memory.memory_guard_custom_ceiling_gb) * 1024**3 - ) - except Exception: - # Direct library callers may not have initialized GlobalSettings. - pass - - try: - from omlx.process_memory_enforcer import ( - get_memory_capability_ceiling_bytes, - ) - - capacity = get_memory_capability_ceiling_bytes( - tier, - custom_ceiling_bytes, - ) - if capacity > 0: - return int(capacity) - except Exception as exc: - logger.debug("Calibration capability ceiling unavailable: %s", exc) - return max(0, int(fallback_system_bytes)) - - def _checkpoint_storage_bytes(weight_files) -> int: """Return the complete on-disk size of checkpoint weight shards. @@ -3569,24 +3535,6 @@ def _checkpoint_storage_bytes(weight_files) -> int: return total -def _qwen4_exp_checkpoint_roots(model_path: str | Path, config: dict) -> set[Path]: - """Return the compute and optional bounded external PLE artifact roots.""" - compute_path = Path(model_path).expanduser().resolve() - roots = {compute_path} - artifact = config.get("qwen4_exp_artifact") or {} - relative_ple = artifact.get("ple_artifact") - if relative_ple is None: - return roots - relative_ple = Path(relative_ple) - if relative_ple.is_absolute(): - return roots - candidate = (compute_path / relative_ple).resolve() - artifact_root = compute_path.parent.resolve() - if candidate == artifact_root or artifact_root in candidate.parents: - roots.add(candidate) - return roots - - def _calibration_resident_checkpoint_bytes( model_path: str | Path, config: dict, @@ -3598,14 +3546,7 @@ def _calibration_resident_checkpoint_bytes( layer walk invokes neither the vision tower nor the ordinary ``lm_head``. Safetensors headers and every other tensor remain charged to the model. """ - roots = ( - _qwen4_exp_checkpoint_roots(model_path, config) - if _is_qwen4_exp_config(config) - else {Path(model_path)} - ) - weight_files = sorted( - {path.resolve() for root in roots for path in root.glob("*.safetensors")} - ) + weight_files = sorted(Path(model_path).glob("*.safetensors")) checkpoint_bytes = _checkpoint_storage_bytes(weight_files) if not _is_qwen4_exp_config(config): return checkpoint_bytes @@ -3644,34 +3585,23 @@ def _calibration_memory_budget( *, fallback_system_bytes: int = 0, ) -> dict[str, int | bool]: - """Return the stable capability budget for calibration forwards. - - Hard admission uses total RAM minus the configured tier's OS reserve, - capped by Metal (and by a configured custom ceiling). Live availability is - retained as diagnostics and for downstream micro-batch sizing, but other - applications and transient file cache do not redefine machine capability. - A proportional 25% reserve remains between the resident checkpoint and - the stable capability ceiling. + """Return the live memory budget for full-model calibration forwards. + + Apple Silicon uses unified memory, but Metal exposes a recommended working + set that can be smaller than physical RAM. The safe capacity is therefore + the smaller positive value of live system memory and remaining Metal + working-set memory. A proportional 25% reserve scales down to 16/32 GiB + machines without imposing a fixed reserve that would reject every model. """ system_available = _system_available_memory_bytes() metal_available = _metal_available_memory_bytes() - live_candidates = [ - value for value in (system_available, metal_available) if value > 0 - ] - live_capacity = min(live_candidates) if live_candidates else 0 - capability_capacity = _calibration_capability_capacity_bytes( - fallback_system_bytes=fallback_system_bytes, - ) - capacity = capability_capacity or live_capacity or max( - 0, int(fallback_system_bytes) - ) + candidates = [value for value in (system_available, metal_available) if value > 0] + capacity = min(candidates) if candidates else max(0, int(fallback_system_bytes)) model_limit = int(capacity * _MAX_MODEL_RAM_FRACTION) checkpoint_bytes = max(0, int(checkpoint_bytes)) return { "system_available_bytes": int(system_available), "metal_available_bytes": int(metal_available), - "live_capacity_bytes": int(live_capacity), - "capability_capacity_bytes": int(capability_capacity), "capacity_bytes": int(capacity), "model_limit_bytes": int(model_limit), "reserve_bytes": max(0, int(capacity) - int(model_limit)), @@ -5927,13 +5857,13 @@ def cb( if _model_requires_proxy and static_sensitivity_map is None: logger.info( f"oQ{oq_level:g}: calibration footprint ({_format_size(_calibration_bytes)}) " - f"exceeds {int(_MAX_MODEL_RAM_FRACTION * 100)}% of stable calibration " - "capability " + f"exceeds {int(_MAX_MODEL_RAM_FRACTION * 100)}% of calibration " + "capacity " f"({_format_size(int(_calibration_budget['capacity_bytes']))}; " f"limit={_format_size(int(_calibration_budget['model_limit_bytes']))}, " - "live system available=" + "system available=" f"{_format_size(int(_calibration_budget['system_available_bytes']))}, " - "live Metal available=" + "Metal available=" f"{_format_size(int(_calibration_budget['metal_available_bytes']))}). " "Full-model calibration will use a proxy." ) @@ -5974,30 +5904,23 @@ def _ensure_ram_safe_proxy() -> Path: candidate, config, ) - proxy_budget = _calibration_memory_budget( - proxy_resident_bytes, - fallback_system_bytes=_system_ram, - ) - if int(proxy_budget["capacity_bytes"]) > 0 and bool( - proxy_budget["requires_proxy"] - ): + prebuild_capacity = int(_calibration_budget["capacity_bytes"]) + prebuild_limit = int(_calibration_budget["model_limit_bytes"]) + if prebuild_capacity > 0 and proxy_resident_bytes > prebuild_limit: shutil.rmtree(candidate, ignore_errors=True) raise RuntimeError( - "calibration proxy is still too large for the stable capability " - f"budget (proxy={_format_size(proxy_bytes)}, " + "calibration proxy is still too large for the pre-build live " + f"memory budget (proxy={_format_size(proxy_bytes)}, " f"resident={_format_size(proxy_resident_bytes)}, " - f"limit={_format_size(int(proxy_budget['model_limit_bytes']))}, " - f"capability={_format_size(int(proxy_budget['capacity_bytes']))}, " - f"live={_format_size(int(proxy_budget['live_capacity_bytes']))})" + f"limit={_format_size(prebuild_limit)}, " + f"capacity={_format_size(prebuild_capacity)})" ) _ram_safe_proxy_dir = candidate logger.info( f"oQ{oq_level:g}: calibration proxy size " f"{_format_size(proxy_bytes)} on disk, resident calibration " f"footprint {_format_size(proxy_resident_bytes)} within " - f"{_format_size(int(proxy_budget['model_limit_bytes']))} stable " - "capability limit (live capacity " - f"{_format_size(int(proxy_budget['live_capacity_bytes']))})" + f"{_format_size(prebuild_limit)} pre-build live memory limit" ) return _ram_safe_proxy_dir diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/residency.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/residency.py index 790e9dc18e..c2bf1274be 100644 --- a/omlx/patches/mlx_vlm_qwen4_exp_compat/residency.py +++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/residency.py @@ -34,28 +34,6 @@ def force_ssd_offload(self, memory_ceiling: int) -> bool: ) -def _resolve_ple_path(model_path: Path) -> Path: - config_path = model_path / "config.json" - if not config_path.is_file(): - return model_path - try: - config = json.loads(config_path.read_text()) - except (OSError, ValueError): - return model_path - artifact = config.get("qwen4_exp_artifact") or {} - relative_ple = artifact.get("ple_artifact") - if relative_ple is None: - return model_path - relative_ple = Path(relative_ple) - if relative_ple.is_absolute(): - return model_path - candidate = (model_path / relative_ple).resolve() - artifact_root = model_path.parent.resolve() - if candidate != artifact_root and artifact_root not in candidate.parents: - return model_path - return candidate - - def _safetensors_header(path: Path) -> dict: with path.open("rb") as file: raw_size = file.read(8) @@ -118,12 +96,8 @@ def qwen4_exp_residency_estimate( ) -> Qwen4ExpResidencyEstimate: """Inspect Qwen4 checkpoint headers without materializing tensor data.""" - compute_path = Path(model_path).expanduser().resolve() - ple_path = _resolve_ple_path(compute_path) - roots = {compute_path, ple_path} - checkpoint_files = { - path.resolve() for root in roots for path in root.glob("*.safetensors") - } + ple_path = Path(model_path).expanduser().resolve() + checkpoint_files = {path.resolve() for path in ple_path.glob("*.safetensors")} signature = tuple( sorted( (str(path), stat.st_size, stat.st_mtime_ns) 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 28ea0d480c..61b7963524 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 @@ -110,32 +110,16 @@ def resolve_ple_runtime_mode( def configure_ple_runtime(model_path: str | Path, mode: str | None = None) -> str: - """Bind the external PLE artifact before Qwen4 model construction.""" + """Bind same-directory PLE storage before Qwen4 model construction.""" global _PLE_RUNTIME_MODEL_PATH, _PLE_RUNTIME_MODE compute_path = Path(model_path).expanduser().resolve() - ple_path = compute_path - artifact = {} - config_path = compute_path / "config.json" - if config_path.is_file(): - artifact = json.loads(config_path.read_text()).get("qwen4_exp_artifact") or {} - relative_ple = artifact.get("ple_artifact") - if relative_ple is not None: - relative_ple = Path(relative_ple) - if relative_ple.is_absolute(): - raise ValueError("Qwen4-Exp PLE artifact path must be relative") - ple_path = (compute_path / relative_ple).resolve() - artifact_root = compute_path.parent.resolve() - if ple_path != artifact_root and artifact_root not in ple_path.parents: - raise ValueError("Qwen4-Exp PLE artifact escapes its artifact root") - requested = mode or os.environ.get("OMLX_QWEN4_PLE_MODE") if requested is None: - requested = artifact.get("ple_residency", "auto") + requested = "auto" checkpoint_bytes = sum( path.stat().st_size - for root in {compute_path, ple_path} - for path in root.glob("*.safetensors") + for path in compute_path.glob("*.safetensors") ) physical_memory = os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES") _PLE_RUNTIME_MODE = resolve_ple_runtime_mode( @@ -143,7 +127,7 @@ def configure_ple_runtime(model_path: str | Path, mode: str | None = None) -> st checkpoint_bytes=checkpoint_bytes, physical_memory=physical_memory, ) - _PLE_RUNTIME_MODEL_PATH = ple_path + _PLE_RUNTIME_MODEL_PATH = compute_path return _PLE_RUNTIME_MODE diff --git a/omlx/process_memory_enforcer.py b/omlx/process_memory_enforcer.py index 9afce8fd0e..43e40ffeec 100644 --- a/omlx/process_memory_enforcer.py +++ b/omlx/process_memory_enforcer.py @@ -75,22 +75,6 @@ "aggressive": 0.8, } - -def _static_memory_ceiling_bytes(system_bytes: int, tier: str) -> int: - """Return total RAM minus the tier-scaled OS reserve.""" - system_bytes = max(0, int(system_bytes)) - tier = (tier or "").strip().lower() - if tier not in _STATIC_RESERVE_LARGE: - tier = "balanced" - if tier == "custom": - reserve = _STATIC_RESERVE_LARGE["custom"] - elif system_bytes < _SMALL_SYSTEM_THRESHOLD: - reserve = _SMALL_SYSTEM_RESERVE - else: - reserve = _STATIC_RESERVE_LARGE[tier] - return max(0, system_bytes - reserve) - - # Default soft watermark per tier. A saved 0.85 from older configs is treated # as the legacy default so balanced / aggressive can move to their tier defaults. _LEGACY_SOFT_THRESHOLD = 0.85 @@ -199,38 +183,6 @@ def get_effective_metal_cap_bytes() -> int: return sysctl_cap return _get_max_metal_working_set_bytes() - -def get_memory_capability_ceiling_bytes( - memory_guard_tier: str = "balanced", - memory_guard_custom_ceiling_bytes: int = 0, -) -> int: - """Return the stable machine/configuration memory ceiling. - - Unlike the enforcer's dynamic ceiling, this deliberately excludes live - free/active/inactive page counts. It answers whether the machine is - fundamentally capable of a workload: total RAM minus the tier's static OS - reserve, capped by Metal and by an explicit custom ceiling when configured. - """ - tier = (memory_guard_tier or "").strip().lower() - if tier not in _STATIC_RESERVE_LARGE: - tier = "balanced" - try: - total = max(0, int(_settings.get_system_memory())) - except Exception: # noqa: BLE001 - total = 0 - - static_ceiling = _static_memory_ceiling_bytes(total, tier) - - candidates = [static_ceiling] if static_ceiling > 0 else [] - metal_cap = get_effective_metal_cap_bytes() - if metal_cap > 0: - candidates.append(int(metal_cap)) - custom_ceiling = max(0, int(memory_guard_custom_ceiling_bytes)) - if tier == "custom" and custom_ceiling > 0: - candidates.append(custom_ceiling) - return min(candidates) if candidates else 0 - - def _wired_limit_suggestion_bytes(desired_bytes: int) -> int: """Clamp and align a wired-limit recommendation to leave 5% of RAM. @@ -610,12 +562,16 @@ def wake(self, *, active: bool = False) -> None: def _get_static_ceiling(self) -> int: """Total RAM minus tier-scaled static reserve.""" - tier = self._memory_guard_tier - try: - system_bytes = max(0, int(_settings.get_system_memory())) - except Exception: # noqa: BLE001 - system_bytes = 0 - return _static_memory_ceiling_bytes(system_bytes, tier) + from .settings import get_system_memory + + system_bytes = get_system_memory() + if self._memory_guard_tier == "custom": + return max(0, system_bytes - _STATIC_RESERVE_LARGE["custom"]) + if system_bytes < _SMALL_SYSTEM_THRESHOLD: + reserve = _SMALL_SYSTEM_RESERVE + else: + reserve = _STATIC_RESERVE_LARGE[self._memory_guard_tier] + return max(0, system_bytes - reserve) def _get_dynamic_ceiling(self) -> int: """Tier-aware reclaimable-memory ceiling. diff --git a/tests/test_mlx_vlm_qwen4_exp_compat.py b/tests/test_mlx_vlm_qwen4_exp_compat.py index cc3ae978f4..1f7808c147 100644 --- a/tests/test_mlx_vlm_qwen4_exp_compat.py +++ b/tests/test_mlx_vlm_qwen4_exp_compat.py @@ -882,31 +882,6 @@ def test_disk_backed_affine_ple_supports_all_oq_bits(tmp_path, bits): assert embedding._shard_specs[0][3:] == (bits, 32) embedding.close() - -def test_external_ple_path_is_bounded_and_ssd_alias_resolves(tmp_path): - compute = tmp_path / "compute" - ple = tmp_path / "ple" - compute.mkdir() - ple.mkdir() - (compute / "config.json").write_text( - json.dumps( - { - "qwen4_exp_artifact": { - "ple_artifact": "../ple", - "ple_residency": "ssd_mmap", - } - } - ), - encoding="utf-8", - ) - try: - assert compat.configure_qwen4_exp_runtime(compute) == "mmap" - finally: - from mlx_vlm.models.qwen4_exp.language import configure_ple_runtime - - configure_ple_runtime(compute, mode="resident") - - # --------------------------------------------------------------------------- # Continuous-batching join regressions (issue #3245, PR #3246) # --------------------------------------------------------------------------- diff --git a/tests/test_oq.py b/tests/test_oq.py index 3265b39268..f4ca2230aa 100644 --- a/tests/test_oq.py +++ b/tests/test_oq.py @@ -3096,7 +3096,10 @@ def test_budget_reserves_25_percent_on_smaller_systems( gib = 1024**3 capacity = capacity_gib * gib monkeypatch.setattr( - oq_module, "_calibration_capability_capacity_bytes", lambda **_k: capacity + oq_module, "_system_available_memory_bytes", lambda: capacity + ) + monkeypatch.setattr( + oq_module, "_metal_available_memory_bytes", lambda: capacity ) budget = _calibration_memory_budget() @@ -3105,14 +3108,15 @@ def test_budget_reserves_25_percent_on_smaller_systems( assert budget["model_limit_bytes"] == int(capacity * 0.75) assert budget["reserve_bytes"] == capacity - int(capacity * 0.75) - def test_budget_uses_stable_capability_ceiling(self, monkeypatch): + def test_budget_uses_smaller_metal_working_set(self, monkeypatch): from omlx import oq as oq_module gib = 1024**3 monkeypatch.setattr( - oq_module, - "_calibration_capability_capacity_bytes", - lambda **_k: 464 * gib, + oq_module, "_system_available_memory_bytes", lambda: 512 * gib + ) + monkeypatch.setattr( + oq_module, "_metal_available_memory_bytes", lambda: 464 * gib ) budget = _calibration_memory_budget(413 * gib) @@ -3126,23 +3130,20 @@ def test_guard_boundary_is_strict(self, monkeypatch): capacity = 4000 monkeypatch.setattr( - oq_module, "_calibration_capability_capacity_bytes", lambda **_k: capacity + oq_module, "_system_available_memory_bytes", lambda: capacity + ) + monkeypatch.setattr( + oq_module, "_metal_available_memory_bytes", lambda: capacity ) at_limit = int(capacity * _MAX_MODEL_RAM_FRACTION) assert _calibration_memory_budget(at_limit)["requires_proxy"] is False assert _calibration_memory_budget(at_limit + 1)["requires_proxy"] is True - def test_capability_admission_ignores_live_memory_pressure(self, monkeypatch): + def test_budget_uses_live_memory_pressure(self, monkeypatch): from omlx import oq as oq_module gib = 1024**3 - capability = int(107.5 * gib) - monkeypatch.setattr( - oq_module, - "_calibration_capability_capacity_bytes", - lambda **_k: capability, - ) monkeypatch.setattr( oq_module, "_system_available_memory_bytes", lambda: int(72.9 * gib) ) @@ -3152,33 +3153,9 @@ def test_capability_admission_ignores_live_memory_pressure(self, monkeypatch): budget = _calibration_memory_budget(int(67.0 * gib)) - assert budget["live_capacity_bytes"] == int(72.9 * gib) - assert budget["capacity_bytes"] == capability - assert budget["model_limit_bytes"] == int(capability * 0.75) - assert budget["requires_proxy"] is False - - def test_capability_admission_still_rejects_unsafe_resident_model( - self, monkeypatch - ): - from omlx import oq as oq_module - - gib = 1024**3 - capability = int(107.5 * gib) - monkeypatch.setattr( - oq_module, - "_calibration_capability_capacity_bytes", - lambda **_k: capability, - ) - monkeypatch.setattr( - oq_module, "_system_available_memory_bytes", lambda: int(72.9 * gib) - ) - monkeypatch.setattr( - oq_module, "_metal_available_memory_bytes", lambda: int(107.5 * gib) - ) - - budget = _calibration_memory_budget(int(81.0 * gib)) - - assert budget["model_limit_bytes"] == int(capability * 0.75) + capacity = int(72.9 * gib) + assert budget["capacity_bytes"] == capacity + assert budget["model_limit_bytes"] == int(capacity * 0.75) assert budget["requires_proxy"] is True @@ -3644,9 +3621,6 @@ def test_opt_out_with_model_exceeding_ram_raises(self, tmp_path, monkeypatch): from omlx import settings as _settings monkeypatch.setattr(_settings, "get_system_memory", lambda: 0) - monkeypatch.setattr( - _oq, "_calibration_capability_capacity_bytes", lambda **_k: 0 - ) monkeypatch.setattr(_oq, "_system_available_memory_bytes", lambda: 0) monkeypatch.setattr(_oq, "_metal_available_memory_bytes", lambda: 0) @@ -3688,9 +3662,6 @@ def test_streaming_discovery_failure_with_model_exceeding_ram_raises( from omlx import oq as _oq - monkeypatch.setattr( - _oq, "_calibration_capability_capacity_bytes", lambda **_k: 0 - ) monkeypatch.setattr(_oq, "_system_available_memory_bytes", lambda: 0) monkeypatch.setattr(_oq, "_metal_available_memory_bytes", lambda: 0) @@ -3739,9 +3710,6 @@ def test_proxy_build_failure_raises(self, tmp_path, monkeypatch): monkeypatch.setattr(_settings, "get_system_memory", lambda: 0) from omlx import oq as _oq - monkeypatch.setattr( - _oq, "_calibration_capability_capacity_bytes", lambda **_k: 0 - ) monkeypatch.setattr(_oq, "_system_available_memory_bytes", lambda: 0) monkeypatch.setattr(_oq, "_metal_available_memory_bytes", lambda: 0) @@ -3774,9 +3742,6 @@ def test_oversized_proxy_is_rejected_and_cleaned(self, tmp_path, monkeypatch): from omlx import oq as oq_module - monkeypatch.setattr( - oq_module, "_calibration_capability_capacity_bytes", lambda **_k: 1000 - ) monkeypatch.setattr(oq_module, "_system_available_memory_bytes", lambda: 1000) monkeypatch.setattr(oq_module, "_metal_available_memory_bytes", lambda: 1000) proxy = tmp_path / "proxy" @@ -3798,7 +3763,7 @@ def _fake_build(*_args, **_kwargs): assert not proxy.exists() - def test_oqe_uses_proxy_when_source_exceeds_capability_limit( + def test_proxy_reuses_prebuild_live_budget( self, tmp_path, monkeypatch ): if not HAS_MLX: @@ -3815,10 +3780,10 @@ def test_oqe_uses_proxy_when_source_exceeds_capability_limit( from omlx import oq as oq_module + system_available = MagicMock(side_effect=[1000, 1]) monkeypatch.setattr( - oq_module, "_calibration_capability_capacity_bytes", lambda **_k: 1000 + oq_module, "_system_available_memory_bytes", system_available ) - monkeypatch.setattr(oq_module, "_system_available_memory_bytes", lambda: 1000) monkeypatch.setattr(oq_module, "_metal_available_memory_bytes", lambda: 1000) proxy = tmp_path / "proxy" build_proxy = MagicMock() @@ -3846,6 +3811,7 @@ def _fake_imatrix(*_args, load_path_factory=None, **_kwargs): ) build_proxy.assert_called_once() + system_available.assert_called_once() assert not proxy.exists() @@ -6664,9 +6630,6 @@ def test_dequantized_footprint_flips_requires_proxy(self, monkeypatch): import omlx.oq as oq # Fixed capacity 400 -> model_limit = int(0.75 * 400) = 300. - monkeypatch.setattr( - oq, "_calibration_capability_capacity_bytes", lambda **_k: 400 - ) monkeypatch.setattr(oq, "_system_available_memory_bytes", lambda: 400) monkeypatch.setattr(oq, "_metal_available_memory_bytes", lambda: 400) diff --git a/tests/test_process_memory_enforcer.py b/tests/test_process_memory_enforcer.py index fac9191ac3..f396f7023a 100644 --- a/tests/test_process_memory_enforcer.py +++ b/tests/test_process_memory_enforcer.py @@ -951,35 +951,6 @@ def test_custom_uses_2gb_reserve_on_small_system(self, mock_engine_pool): result = enforcer._get_static_ceiling() assert result == 10 * 1024**3 - def test_capability_ceiling_uses_static_ram_and_metal_cap(self): - gib = 1024**3 - with ( - patch("omlx.settings.get_system_memory", return_value=128 * gib), - patch( - "omlx.process_memory_enforcer.get_effective_metal_cap_bytes", - return_value=int(107.5 * gib), - ), - ): - result = pme.get_memory_capability_ceiling_bytes("balanced") - - assert result == int(107.5 * gib) - - def test_capability_ceiling_respects_explicit_custom_limit(self): - gib = 1024**3 - with ( - patch("omlx.settings.get_system_memory", return_value=128 * gib), - patch( - "omlx.process_memory_enforcer.get_effective_metal_cap_bytes", - return_value=int(107.5 * gib), - ), - ): - result = pme.get_memory_capability_ceiling_bytes( - "custom", 70 * gib - ) - - assert result == 70 * gib - - class TestDynamicCeilingActiveRatio: """Dynamic ceiling sums free + inactive + active * tier ratio (host_statistics64 path) for safe / balanced / aggressive.""" From d451552bada7762c947682e832f1608800234280 Mon Sep 17 00:00:00 2001 From: jundot Date: Sat, 29 Aug 2026 23:32:35 +0900 Subject: [PATCH 041/132] refactor(qwen4_exp): simplify PLE rollback snapshots --- .../mlx_vlm/models/qwen4_exp/language.py | 212 +++++------------- tests/test_mlx_vlm_qwen4_exp_compat.py | 48 +--- 2 files changed, 59 insertions(+), 201 deletions(-) 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 61b7963524..e8d0c31ca6 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 @@ -43,32 +43,14 @@ class Qwen4ExpMTPRuntime: _MTP_RUNTIME = Qwen4ExpMTPRuntime() -@dataclass +@dataclass(frozen=True) class _PLESpeculativeState: - """PLE inputs needed to restore a partially accepted verify window. - - Captured across a single target-verify forward and consumed exactly once by - ``rollback_speculative_cache``. ``complete`` gates the consume: it is set - only after *both* the n-gram-history capture and the paired short-conv - capture have run in the same forward, so a snapshot left half-written by an - aborted forward is rejected instead of being applied as a mixed-epoch state. - """ + """PLE inputs needed to restore a partially accepted verify window.""" history: mx.array input_ids: mx.array - conv_state: mx.array | None = None - conv_inputs: mx.array | None = None - complete: bool = False - - -class _PLESpeculativeRollbackError(RuntimeError): - """Raised before any cache mutation when a PLE snapshot cannot be trusted. - - The caller's speculative-decode loop treats a raising ``rollback_speculative_cache`` - as a failed rollback and reconciles by rebuilding the cache from the committed - token stream, so failing closed here is safe and leaves no partially rolled - back cache behind. - """ + conv_state: mx.array + conv_inputs: mx.array def configure_mtp_runtime( @@ -1374,35 +1356,19 @@ def _shift_right_ignore_eos(self, token_ids: mx.array, shift: int): valid = (position_in_segment >= shift) & (source_positions[None] >= 0) return mx.where(valid, shifted, self.eos_token_id) - def __call__( - self, - input_ids: mx.array, - cache: Optional[ArraysCache], - *, - capture_speculative_state: bool = False, - ): - input_ids = input_ids.astype(mx.int64) + def _previous_context( + self, input_ids: mx.array, cache: ArraysCache | None + ) -> mx.array: batch = input_ids.shape[0] if cache is not None and cache[3] is not None: - previous_context = cache[3] - else: - previous_context = mx.full( - (batch, self.context_len), self.eos_token_id, dtype=mx.int64 - ) + return cache[3] + return mx.full( + (batch, self.context_len), self.eos_token_id, dtype=mx.int64 + ) - if cache is not None: - if capture_speculative_state: - # Arm a fresh snapshot for this target-verify forward. - cache._qwen4_exp_ple_speculative_state = _PLESpeculativeState( - history=previous_context, - input_ids=input_ids, - ) - elif getattr(cache, "_qwen4_exp_ple_speculative_state", None) is not None: - # Ordinary forward: any snapshot still attached belongs to an - # earlier verify cycle that was fully accepted (no rollback) or - # aborted. It can never describe this committed position, so - # disarm it before it can be consumed by a later rollback. - cache._qwen4_exp_ple_speculative_state = None + def __call__(self, input_ids: mx.array, cache: Optional[ArraysCache]): + input_ids = input_ids.astype(mx.int64) + previous_context = self._previous_context(input_ids, cache) token_history = mx.concatenate([previous_context, input_ids], axis=-1) if cache is not None: @@ -1471,13 +1437,7 @@ def __init__(self, config: TextConfig, layer_idx: int, ple_layer_index: int): bias=False, ) - def _short_conv( - self, - x: mx.array, - cache: Optional[ArraysCache], - *, - capture_speculative_state: bool = False, - ): + def _short_conv(self, x: mx.array, cache: Optional[ArraysCache]): batch = x.shape[0] if cache is not None and cache[2] is not None: state = cache[2] @@ -1486,16 +1446,9 @@ def _short_conv( (batch, self.short_conv_state_len, x.shape[-1]), dtype=x.dtype ) conv_input = mx.concatenate([state, x], axis=1) - if capture_speculative_state and cache is not None: - snapshot = getattr(cache, "_qwen4_exp_ple_speculative_state", None) - if snapshot is not None: - snapshot.conv_state = state - snapshot.conv_inputs = x - # Both paired captures for this verify forward have now run. - snapshot.complete = True if cache is not None: cache[2] = mx.contiguous(conv_input[:, -self.short_conv_state_len :]) - return nn.silu(self.conv1d(conv_input)) + return nn.silu(self.conv1d(conv_input)), state def __call__( self, @@ -1506,11 +1459,14 @@ def __call__( target_verify: bool = False, ): capture_speculative_state = target_verify and input_ids.shape[1] > 1 - embeddings = self.ple_embedding( - input_ids, - cache, - capture_speculative_state=capture_speculative_state, - ) + if cache is not None: + cache._qwen4_exp_ple_speculative_state = None + history = None + if capture_speculative_state and cache is not None: + history = self.ple_embedding._previous_context( + input_ids.astype(mx.int64), cache + ) + embeddings = self.ple_embedding(input_ids, cache) keys = self.norm_key( _target_verify_linear(self.key_proj, embeddings, target_verify) ).reshape(*hidden_states.shape[:-1], self.hc_count, self.hidden_size) @@ -1528,11 +1484,15 @@ def __call__( if mask is not None and isinstance(mask, mx.array) and mask.ndim == 2: gated_values = mx.where(mask[..., None], gated_values, 0) normed = mx.where(mask[..., None], normed, 0) - return gated_values + self._short_conv( - normed, - cache, - capture_speculative_state=capture_speculative_state, - ) + conv_output, conv_state = self._short_conv(normed, cache) + if history is not None and cache is not None: + cache._qwen4_exp_ple_speculative_state = _PLESpeculativeState( + history=history, + input_ids=input_ids.astype(mx.int64), + conv_state=conv_state, + conv_inputs=normed, + ) + return gated_values + conv_output class Qwen4ExpDecoderLayer(nn.Module): @@ -1893,53 +1853,22 @@ def _discard_ple_snapshots(caches): @staticmethod def _validate_ple_snapshot(snapshot, accepted_values): - """Reject a snapshot that cannot be applied as a clean single-epoch state.""" - if not snapshot.complete: - raise _PLESpeculativeRollbackError( - "PLE speculative snapshot is incomplete " - "(target-verify forward did not finish both captures)" - ) - if snapshot.history.ndim != 2 or snapshot.input_ids.ndim != 2: - raise _PLESpeculativeRollbackError( - "PLE speculative snapshot history/input_ids are not rank-2" - ) batch, window = snapshot.input_ids.shape - if window < 1: - raise _PLESpeculativeRollbackError( - "PLE speculative snapshot has an empty verify window" - ) - if snapshot.history.shape[0] != batch: - raise _PLESpeculativeRollbackError( - "PLE speculative snapshot batch mismatch (history vs input_ids)" - ) if len(accepted_values) not in (1, batch): - raise _PLESpeculativeRollbackError( + raise ValueError( "PLE speculative rollback accepted count does not match batch size" ) - if any(value < 0 for value in accepted_values): - raise _PLESpeculativeRollbackError( - "PLE speculative rollback accepted count is negative" + if any(value < 0 or value >= window for value in accepted_values): + raise ValueError( + "PLE speculative rollback accepted count is outside the verify window" ) - if snapshot.conv_state is not None or snapshot.conv_inputs is not None: - if ( - snapshot.conv_state is None - or snapshot.conv_inputs is None - or snapshot.conv_state.ndim != 3 - or snapshot.conv_inputs.ndim != 3 - or snapshot.conv_state.shape[0] != batch - or snapshot.conv_inputs.shape[0] != batch - ): - raise _PLESpeculativeRollbackError( - "PLE speculative snapshot short-conv capture is malformed" - ) @staticmethod def _restore_ple_state(cache, snapshot, accepted_values): batch = snapshot.input_ids.shape[0] values = accepted_values * batch if len(accepted_values) == 1 else accepted_values accepted_array = mx.array(values, dtype=mx.int32) - window = snapshot.input_ids.shape[1] - retained = mx.clip(accepted_array + 1, 0, window) + retained = accepted_array + 1 history_len = snapshot.history.shape[1] history = mx.concatenate([snapshot.history, snapshot.input_ids], axis=1) @@ -1950,45 +1879,24 @@ def _restore_ple_state(cache, snapshot, accepted_values): mx.take_along_axis(history, history_positions, axis=1) ) - if snapshot.conv_state is not None and snapshot.conv_inputs is not None: - state_len = snapshot.conv_state.shape[1] - if state_len: - conv_input = mx.concatenate( - [snapshot.conv_state, snapshot.conv_inputs], axis=1 - ) - conv_positions = retained[:, None] + mx.arange( - state_len, dtype=mx.int32 - )[None, :] - conv_positions = mx.broadcast_to( - conv_positions[..., None], - (batch, state_len, snapshot.conv_state.shape[-1]), - ) - cache[2] = mx.contiguous( - mx.take_along_axis(conv_input, conv_positions, axis=1) - ) + state_len = snapshot.conv_state.shape[1] + if state_len: + conv_input = mx.concatenate( + [snapshot.conv_state, snapshot.conv_inputs], axis=1 + ) + conv_positions = retained[:, None] + mx.arange( + state_len, dtype=mx.int32 + )[None, :] + conv_positions = mx.broadcast_to( + conv_positions[..., None], + (batch, state_len, snapshot.conv_state.shape[-1]), + ) + cache[2] = mx.contiguous( + mx.take_along_axis(conv_input, conv_positions, axis=1) + ) def rollback_speculative_cache(self, caches, gdn_states, accepted, block_size): - """Restore PLE state to the accepted verifier prefix. - - The inherited Qwen3.5 rollback restores QSA and GDN state, but PLE's - n-gram history and short-convolution slots are additional recurrent - state. During a multi-token verifier forward we retain the pre-window - history and convolution inputs, then select the state after the - confirmed token plus the accepted draft prefix. - - The restore is run as a small transaction so QSA/GDN (slots 0/1) and PLE - (slots 2/3) can never end up at different committed positions: - - 1. Validate every attached PLE snapshot *before* touching any cache. A - bad snapshot raises ``_PLESpeculativeRollbackError`` with nothing - mutated; the caller then reconciles by rebuilding the cache. - 2. Run the inherited QSA/GDN rollback. - 3. Commit the PLE slot restores, consuming each snapshot exactly once. - - Any snapshot still attached on exit is dropped, so a fully accepted - cycle (which never calls this method) cannot leak a stale snapshot into - a later rollback either. - """ + """Restore PLE state to the accepted prefix after inherited rollback.""" accepted_values = self._normalize_accepted_counts(accepted) pending = [] @@ -1999,21 +1907,11 @@ def rollback_speculative_cache(self, caches, gdn_states, accepted, block_size): continue self._validate_ple_snapshot(snapshot, accepted_values) pending.append((cache, snapshot)) - except _PLESpeculativeRollbackError: - self._discard_ple_snapshots(caches) - raise - - try: result = super().rollback_speculative_cache( caches, gdn_states, accepted, block_size ) - except Exception: - self._discard_ple_snapshots(caches) - raise - - try: for cache, snapshot in pending: self._restore_ple_state(cache, snapshot, accepted_values) + return result finally: self._discard_ple_snapshots(caches) - return result diff --git a/tests/test_mlx_vlm_qwen4_exp_compat.py b/tests/test_mlx_vlm_qwen4_exp_compat.py index 1f7808c147..fb939c6476 100644 --- a/tests/test_mlx_vlm_qwen4_exp_compat.py +++ b/tests/test_mlx_vlm_qwen4_exp_compat.py @@ -612,48 +612,9 @@ def test_qwen4_ple_ordinary_forward_disarms_stale_snapshot(): assert getattr(ple_cache, "_qwen4_exp_ple_speculative_state", None) is None -def test_qwen4_ple_rollback_fails_closed_on_incomplete_snapshot(): - """An aborted verify forward can leave a half-written snapshot. Rollback must - reject it before mutating any cache, not apply a mixed-epoch state.""" +def test_qwen4_ple_rollback_validates_accepted_count_before_qsa_mutation(): config = _tiny_config() - from mlx_vlm.models.qwen4_exp.language import ( - LanguageModel, - _PLESpeculativeRollbackError, - ) - - model = LanguageModel(config.text_config, config) - cache = model.make_cache() - model(mx.array([[2, 3, 4]], dtype=mx.int32), cache=cache) - verified = model( - mx.array([[5, 6]], dtype=mx.int32), cache=cache, return_hidden=True - ) - - ple_cache, qsa_cache = cache[0], cache[1] - before_hist = mx.array(ple_cache[3]) - before_conv = mx.array(ple_cache[2]) - before_offset = int(qsa_cache.offset) - - ple_cache._qwen4_exp_ple_speculative_state.complete = False - with pytest.raises(_PLESpeculativeRollbackError): - model.rollback_speculative_cache( - cache, verified.gdn_states, accepted=0, block_size=2 - ) - - mx.eval(ple_cache[3], ple_cache[2]) - assert mx.array_equal(ple_cache[3], before_hist).item() - assert mx.array_equal(ple_cache[2], before_conv).item() - assert int(qsa_cache.offset) == before_offset - assert getattr(ple_cache, "_qwen4_exp_ple_speculative_state", None) is None - - -def test_qwen4_ple_rollback_validates_snapshot_before_qsa_mutation(): - """A malformed accepted-count aborts the whole rollback with QSA/GDN - untouched (validation runs before the inherited rollback).""" - config = _tiny_config() - from mlx_vlm.models.qwen4_exp.language import ( - LanguageModel, - _PLESpeculativeRollbackError, - ) + from mlx_vlm.models.qwen4_exp.language import LanguageModel model = LanguageModel(config.text_config, config) cache = model.make_cache() @@ -663,10 +624,9 @@ def test_qwen4_ple_rollback_validates_snapshot_before_qsa_mutation(): ) before_offset = int(cache[1].offset) - # batch is 1, so a 2-element accepted list cannot match - with pytest.raises(_PLESpeculativeRollbackError): + with pytest.raises(ValueError, match="outside the verify window"): model.rollback_speculative_cache( - cache, verified.gdn_states, accepted=[0, 0], block_size=2 + cache, verified.gdn_states, accepted=2, block_size=2 ) assert int(cache[1].offset) == before_offset assert getattr(cache[0], "_qwen4_exp_ple_speculative_state", None) is None From 9934b288ce1a83467e448a6c44875070d7540cda Mon Sep 17 00:00:00 2001 From: jundot Date: Sat, 29 Aug 2026 23:37:24 +0900 Subject: [PATCH 042/132] fix(qwen4_exp): bound QSA long-prefill memory (#3283) --- omlx/patches/sdpa256_attention.py | 36 +++++++- omlx/patches/turboquant_attention.py | 35 ++++---- omlx/scheduler.py | 4 + tests/test_qwen4_qsa_prefill_memory.py | 114 +++++++++++++++++++++++++ tests/test_turboquant.py | 57 ++++++++++++- 5 files changed, 223 insertions(+), 23 deletions(-) create mode 100644 tests/test_qwen4_qsa_prefill_memory.py diff --git a/omlx/patches/sdpa256_attention.py b/omlx/patches/sdpa256_attention.py index 153a6cdb65..e18f854651 100644 --- a/omlx/patches/sdpa256_attention.py +++ b/omlx/patches/sdpa256_attention.py @@ -157,13 +157,26 @@ def _tiled_route_required(queries, keys) -> bool: return True # headroom info unavailable -> memory-safe default +def _broadcast_mask_5d(mask, batch, n_kv, group_size, q_len, k_len): + """Reshape a boolean mask for the tiled GQA attention layout.""" + if mask.ndim == 4: + if mask.shape[1] == 1: + return mask[:, :, None] + return mask.reshape(batch, n_kv, group_size, q_len, k_len) + if mask.ndim == 3: + return mask[:, None, None] + if mask.ndim == 2: + return mask[None, None, None] + raise ValueError(f"unsupported attention mask ndim: {mask.ndim}") + + def _flash_sdpa256(queries, keys, values, scale, mask): """Flash-style online-softmax attention for head_dim=256 prefill. queries: [batch, n_q, q_len, head_dim] keys/values: [batch, n_kv, k_len, head_dim] (n_q % n_kv == 0) - mask: "causal" or None. Returns [batch, n_q, q_len, head_dim] in - queries.dtype. + mask: "causal", None, or a boolean array. Returns + [batch, n_q, q_len, head_dim] in queries.dtype. Tiles over Q and KV, keeping a running (max m, sum denom, accumulator acc) per query row so the [q x full_kv] score matrix is never materialized. fp32 @@ -177,7 +190,14 @@ def _flash_sdpa256(queries, keys, values, scale, mask): batch, n_q, q_len, head_dim = queries.shape _, n_kv, k_len, _ = keys.shape group_size = n_q // n_kv - causal = mask == "causal" + causal = isinstance(mask, str) and mask == "causal" + bool_mask = None + if isinstance(mask, mx.array): + if mask.dtype != mx.bool_: + raise ValueError("_flash_sdpa256 only supports boolean array masks") + bool_mask = _broadcast_mask_5d( + mask, batch, n_kv, group_size, q_len, k_len + ) qr = queries.reshape(batch, n_kv, group_size, q_len, head_dim) kr = keys.reshape(batch, n_kv, 1, k_len, head_dim) @@ -210,6 +230,9 @@ def _flash_sdpa256(queries, keys, values, scale, mask): if causal: k_pos = mx.arange(kj0, kj1).reshape(1, 1, 1, 1, kt) s = mx.where(k_pos > q_pos, _NEG_INF, s) + elif bool_mask is not None: + tile_mask = bool_mask[..., qi0:qi1, kj0:kj1] + s = mx.where(tile_mask, s, _NEG_INF) m_tile = mx.max(s, axis=-1, keepdims=True) m_new = mx.maximum(m, m_tile) @@ -248,7 +271,12 @@ def _should_route(queries, keys, cache, mask, sinks) -> bool: # hasattr(cache, "bits"); let the quant-aware path handle it. if cache is not None and hasattr(cache, "bits"): return False - if not (mask is None or (isinstance(mask, str) and mask == "causal")): + mask_is_bool = isinstance(mask, mx.array) and mask.dtype == mx.bool_ + if not ( + mask is None + or (isinstance(mask, str) and mask == "causal") + or mask_is_bool + ): return False n_q = queries.shape[-3] n_kv = keys.shape[-3] diff --git a/omlx/patches/turboquant_attention.py b/omlx/patches/turboquant_attention.py index 40a92df91f..ca911a904c 100644 --- a/omlx/patches/turboquant_attention.py +++ b/omlx/patches/turboquant_attention.py @@ -9,8 +9,8 @@ are folded into the GQA repeat dimension so the codecs' decode kernels apply, with the causal tail mask injected between key scoring and the value weighted sum — one lazy pass over the KV, no dequantize - - Prefill (L>1): cache.prefill_attention() fast path, fallback to - dequantize + mx.fast.scaled_dot_product_attention + - Prefill (L>1): tiled quantized attention first for long contexts; + cache.prefill_attention() first for short contexts; then dequantized SDPA """ import logging @@ -606,25 +606,16 @@ def patched_sdpa( "falling back to prefill paths", exc_info=True, ) - # Prefill: try quantized fast path, fallback to dequantize+SDPA - result = real_cache.prefill_attention( - queries, - keys_state=keys, - values_state=values, - scale=scale, - mask=mask, - ) - if result is not None: - return result keys_state = getattr(keys, "_state", keys) try: total_tokens = _state_length(keys_state) except Exception: total_tokens = 0 - if ( + use_tiled_first = ( total_tokens > _LONG_PREFILL_QUANTIZED_THRESHOLD and hasattr(real_cache, "quantized_attention") - ): + ) + if use_tiled_first: old_query_block_size = getattr( real_cache, "prefill_query_block_size", None ) @@ -646,7 +637,7 @@ def patched_sdpa( except Exception: logger.debug( "TurboQuant quantized prefill attention failed; " - "falling back to dequantize+SDPA", + "falling back to prefill_attention / dequantize+SDPA", exc_info=True, ) finally: @@ -654,7 +645,19 @@ def patched_sdpa( real_cache.prefill_query_block_size = old_query_block_size if old_key_chunk_size is not None: real_cache.prefill_key_chunk_size = old_key_chunk_size - dequantized_keys, dequantized_values = real_cache.dequantize() + result = real_cache.prefill_attention( + queries, + keys_state=keys, + values_state=values, + scale=scale, + mask=mask, + ) + if result is not None: + return result + dequantized_keys, dequantized_values = real_cache.dequantize( + keys_state=keys, + values_state=values, + ) return mx.fast.scaled_dot_product_attention( queries, dequantized_keys.astype(queries.dtype), diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 8f792765e6..2baa60af81 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -1231,6 +1231,10 @@ def _patched_ppb_prompt(self, tokens): "BatchTurboQuantKVCache", "ChunkedKVCache", "MiniMaxM3KVCache", + # Both QSA handlers support block slicing, so their growing KV and + # index state must not be copied into every boundary snapshot. + "QSAKVCache", + "QSAQuantizedKVCache", } ) diff --git a/tests/test_qwen4_qsa_prefill_memory.py b/tests/test_qwen4_qsa_prefill_memory.py new file mode 100644 index 0000000000..125258603d --- /dev/null +++ b/tests/test_qwen4_qsa_prefill_memory.py @@ -0,0 +1,114 @@ +"""Regression smoke tests for Qwen4 QSA long-prefill memory routing.""" + +from types import SimpleNamespace + +import mlx.core as mx +import pytest +from mlx_lm.models.cache import KVCache +from mlx_vlm.turboquant import TurboQuantKVCache + + +class QSAKVCache: + def __init__(self, token_count: int): + self.state = ( + mx.zeros((1, 2, token_count, 32), dtype=mx.float16), + mx.zeros((1, 2, token_count, 32), dtype=mx.float16), + ) + + +class QSAQuantizedKVCache(QSAKVCache): + pass + + +@pytest.mark.parametrize("cache_cls", [QSAKVCache, QSAQuantizedKVCache]) +def test_qsa_cache_is_not_retained_in_boundary_snapshots(cache_cls): + from omlx.scheduler import Scheduler + + captured = [] + scheduler = SimpleNamespace( + _on_prefill_boundary_snapshot=( + lambda request_id, snapshot_cache, token_count: captured.append( + snapshot_cache + ) + ) + ) + request = SimpleNamespace(request_id="qsa-smoke") + + for token_count in (16, 32, 48): + cache = cache_cls(token_count) + mx.eval(*cache.state) + Scheduler._emit_prefill_boundary_snapshot( + scheduler, request, [cache], token_count + ) + + retained_bytes = sum( + sum(array.nbytes for array in snapshot[0].state) + for snapshot in captured + if snapshot[0] is not None + ) + assert retained_bytes == 0 + + +def test_bool_mask_uses_tiled_sdpa_and_matches_dense(monkeypatch): + from omlx.patches import sdpa256_attention as sdpa256 + + monkeypatch.setattr(sdpa256, "_HEADROOM_PROVIDER", None) + monkeypatch.setattr(sdpa256, "_FORCE_TILED", None) + monkeypatch.setattr(sdpa256, "_SDPA256_MIN_KV_LEN", 64) + monkeypatch.setattr(sdpa256, "_Q_TILE", 16) + monkeypatch.setattr(sdpa256, "_KV_TILE", 64) + + mx.random.seed(0) + queries = mx.random.normal((1, 4, 32, 256)).astype(mx.float16) + keys = mx.random.normal((1, 2, 128, 256)).astype(mx.float16) + values = mx.random.normal((1, 2, 128, 256)).astype(mx.float16) + mask = mx.zeros((1, 1, 32, 128), dtype=mx.bool_) + mask[..., 64:] = True + mx.eval(queries, keys, values, mask) + + assert sdpa256._should_route(queries, keys, None, mask, None) is True + tiled = sdpa256._flash_sdpa256(queries, keys, values, 256**-0.5, mask) + dense = mx.fast.scaled_dot_product_attention( + queries, keys, values, scale=256**-0.5, mask=mask + ) + mx.eval(tiled, dense) + error = mx.max(mx.abs(tiled.astype(mx.float32) - dense.astype(mx.float32))).item() + assert error < 2e-2 + + +def test_long_bool_mask_turboquant_prefill_is_tiled_first(monkeypatch): + from mlx_lm.models import base as mlx_base + + from omlx.patches import turboquant_attention as tq_attention + + tq_attention.apply_turboquant_attention_patch() + monkeypatch.setattr(tq_attention, "_LONG_PREFILL_QUANTIZED_THRESHOLD", 4) + + fp_cache = KVCache() + fp_cache.update_and_fetch( + mx.random.normal((1, 2, 8, 32)), + mx.random.normal((1, 2, 8, 32)), + ) + cache = TurboQuantKVCache.from_cache(fp_cache, bits=4.0) + keys, values = cache.state + calls = [] + + def fake_prefill(self, *args, **kwargs): + calls.append("prefill") + return mx.zeros_like(args[0]) + + def fake_quantized(self, *args, **kwargs): + calls.append("quantized") + return mx.zeros_like(args[0]) + + monkeypatch.setattr(TurboQuantKVCache, "prefill_attention", fake_prefill) + monkeypatch.setattr(TurboQuantKVCache, "quantized_attention", fake_quantized) + + queries = mx.random.normal((1, 4, 2, 32)) + mask = mx.ones((1, 1, 2, 8), dtype=mx.bool_) + result = mlx_base.scaled_dot_product_attention( + queries, keys, values, cache, scale=32**-0.5, mask=mask + ) + + assert result.shape == queries.shape + assert calls == ["quantized"] diff --git a/tests/test_turboquant.py b/tests/test_turboquant.py index 8621f2e64c..92dd316b1e 100644 --- a/tests/test_turboquant.py +++ b/tests/test_turboquant.py @@ -478,13 +478,52 @@ def fake_quantized_attention( ) assert out.shape == queries.shape - assert prefill_calls == [(ks, vs)] + assert prefill_calls == [] assert len(calls) == 1 assert calls[0][0] is ks assert calls[0][1] is vs assert calls[0][2] == 256 +def test_attention_patch_keeps_short_prefill_fast_path(monkeypatch): + from mlx_lm.models import base as mlx_base + + from omlx.patches import turboquant_attention as tq_attention + + tq_attention.apply_turboquant_attention_patch() + monkeypatch.setattr(tq_attention, "_LONG_PREFILL_QUANTIZED_THRESHOLD", 4096) + + fp_cache = KVCache() + fp_cache.update_and_fetch( + mx.random.normal((1, 2, 8, 32)), + mx.random.normal((1, 2, 8, 32)), + ) + tq = TurboQuantKVCache.from_cache(fp_cache, bits=4.0) + keys, values = tq.state + calls = [] + + def fake_prefill(self, queries, **kwargs): + calls.append("prefill") + return mx.zeros_like(queries) + + def fake_quantized(self, queries, **kwargs): + calls.append("quantized") + return mx.zeros_like(queries) + + monkeypatch.setattr(TurboQuantKVCache, "prefill_attention", fake_prefill) + monkeypatch.setattr( + TurboQuantKVCache, "quantized_attention", fake_quantized + ) + + queries = mx.random.normal((1, 4, 2, 32)) + result = mlx_base.scaled_dot_product_attention( + queries, keys, values, tq, scale=32**-0.5, mask=None + ) + + assert result.shape == queries.shape + assert calls == ["prefill"] + + def test_attention_patch_falls_back_when_quantized_prefill_fails(monkeypatch): from mlx_lm.models import base as mlx_base @@ -500,16 +539,22 @@ def test_attention_patch_falls_back_when_quantized_prefill_fails(monkeypatch): ) tq = TurboQuantKVCache.from_cache(fp_cache, bits=4.0) ks, vs = tq.state - calls = {"quantized": 0, "dequantize": 0} + calls = {"quantized": 0, "prefill": 0, "dequantize": 0} def failing_quantized_attention(self, *args, **kwargs): calls["quantized"] += 1 raise RuntimeError("forced quantized prefill failure") + def none_prefill_attention(self, *args, **kwargs): + calls["prefill"] += 1 + return None + original_dequantize = TurboQuantKVCache.dequantize + dequant_kwargs = {} def spy_dequantize(self, *args, **kwargs): calls["dequantize"] += 1 + dequant_kwargs.update(kwargs) return original_dequantize(self, *args, **kwargs) monkeypatch.setattr( @@ -517,6 +562,11 @@ def spy_dequantize(self, *args, **kwargs): "quantized_attention", failing_quantized_attention, ) + monkeypatch.setattr( + TurboQuantKVCache, + "prefill_attention", + none_prefill_attention, + ) monkeypatch.setattr(TurboQuantKVCache, "dequantize", spy_dequantize) queries = mx.random.normal((1, 4, 2, 32)) @@ -526,7 +576,8 @@ def spy_dequantize(self, *args, **kwargs): mx.eval(out) assert out.shape == queries.shape - assert calls == {"quantized": 1, "dequantize": 1} + assert calls == {"quantized": 1, "prefill": 1, "dequantize": 1} + assert dequant_kwargs == {"keys_state": ks, "values_state": vs} @pytest.mark.parametrize("q_len", [2, 4, 9]) From 119d2049437704154a3dee639de3b583030203a2 Mon Sep 17 00:00:00 2001 From: rsnow Date: Sat, 29 Aug 2026 09:47:48 -0500 Subject: [PATCH 043/132] fix(cache): normalize mixed Qwen4 QSA positions (#3219) Normalize mixed serialized QSA text and MRoPE position states during prefix-cache reconstruction. --- omlx/cache/type_handlers.py | 51 +++++++ .../test_qwen4_qsa_position_reconstruction.py | 125 ++++++++++++++++++ 2 files changed, 176 insertions(+) create mode 100644 tests/test_qwen4_qsa_position_reconstruction.py diff --git a/omlx/cache/type_handlers.py b/omlx/cache/type_handlers.py index 0ef8f0c7d5..4c5d7dae42 100644 --- a/omlx/cache/type_handlers.py +++ b/omlx/cache/type_handlers.py @@ -1451,6 +1451,55 @@ def _deserialize_qsa_positions(position_ids: Any) -> Any: return position_ids.transpose(1, 0, 2) +def _normalize_qsa_position_states(position_states: list[Any]) -> list[Any]: + """Promote mixed text/MRoPE QSA positions to [B, 3, S]. + + Qwen4 represents text positions as [B, S] and MRoPE positions as + [3, B, S]. Serialization stores those as [B, 1, S] and [B, 3, S] + respectively. The model's indexer cache promotes the text form by + broadcasting it across all three MRoPE coordinates when the two forms + meet, so block reconstruction must perform the equivalent operation + before concatenating along the sequence axis. + """ + if not position_states: + return position_states + + batch_size = None + channels: set[int] = set() + for position_state in position_states: + if not hasattr(position_state, "ndim") or position_state.ndim != 3: + shape = getattr(position_state, "shape", None) + raise ValueError( + "Serialized QSA position IDs must be [B, C, S], " + f"got {shape}." + ) + current_batch, current_channels, _ = position_state.shape + if current_channels not in (1, 3): + raise ValueError( + "Serialized QSA position IDs require 1 text channel or 3 " + f"MRoPE channels, got {position_state.shape}." + ) + if batch_size is None: + batch_size = current_batch + elif current_batch != batch_size: + raise ValueError( + "Serialized QSA position IDs must have a consistent batch " + f"dimension, got {batch_size} and {current_batch}." + ) + channels.add(current_channels) + + # Preserve both homogeneous paths without introducing broadcast views. + if len(channels) == 1: + return position_states + + return [ + mx.broadcast_to(state, (state.shape[0], 3, state.shape[2])) + if state.shape[1] == 1 + else state + for state in position_states + ] + + class Qwen4QSAKVCacheHandler(CacheTypeHandler): """Handler for Qwen4 QSA caches with raw index keys and positions.""" @@ -1544,6 +1593,8 @@ def concatenate_states(self, states: list[dict[str, Any]]) -> dict[str, Any]: grouped[index].append(element) concatenated = [] for info, elements in zip(self.get_state_axis_info(), grouped): + if info.name == "index_position_ids": + elements = _normalize_qsa_position_states(elements) concatenated.append( mx.concatenate(elements, axis=info.sequence_axis) if elements else None ) diff --git a/tests/test_qwen4_qsa_position_reconstruction.py b/tests/test_qwen4_qsa_position_reconstruction.py new file mode 100644 index 0000000000..9b62fb88c2 --- /dev/null +++ b/tests/test_qwen4_qsa_position_reconstruction.py @@ -0,0 +1,125 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Regression tests for mixed Qwen4 QSA text/MRoPE cache positions.""" + +import mlx.core as mx +import pytest + +from omlx.cache.type_handlers import Qwen4QSAKVCacheHandler + + +def _state(positions): + return {"states": (None, None, None, positions)} + + +def _text(value, length, batch=1): + return mx.full((batch, 1, length), value, dtype=mx.int32) + + +def _mrope(values, length, batch=1): + return mx.stack( + [mx.full((batch, length), value, dtype=mx.int32) for value in values], + axis=1, + ) + + +def _positions(*segments): + result = Qwen4QSAKVCacheHandler().concatenate_states( + [_state(segment) for segment in segments] + )["index_position_ids"] + mx.eval(result) + return result + + +@pytest.mark.parametrize( + ("segments", "expected"), + [ + ( + (_text(7, 2), _mrope((10, 20, 30), 1)), + [[[7, 7, 10], [7, 7, 20], [7, 7, 30]]], + ), + ( + (_mrope((10, 20, 30), 1), _text(7, 2)), + [[[10, 7, 7], [20, 7, 7], [30, 7, 7]]], + ), + ( + ( + _text(1, 1), + _mrope((2, 3, 4), 1), + _text(5, 1), + _mrope((6, 7, 8), 1), + ), + [[[1, 2, 5, 6], [1, 3, 5, 7], [1, 4, 5, 8]]], + ), + ], +) +def test_mixed_text_positions_promote_to_mrope(segments, expected): + result = _positions(*segments) + + assert result.shape == (1, 3, len(expected[0][0])) + assert result.tolist() == expected + + +def test_all_text_positions_keep_one_channel(): + result = _positions(_text(1, 2), _text(2, 3)) + + assert result.shape == (1, 1, 5) + assert result.tolist() == [[[1, 1, 2, 2, 2]]] + + +def test_all_mrope_positions_keep_three_channels(): + result = _positions(_mrope((1, 2, 3), 2), _mrope((4, 5, 6), 1)) + + assert result.shape == (1, 3, 3) + assert result.tolist() == [[[1, 1, 4], [2, 2, 5], [3, 3, 6]]] + + +@pytest.mark.parametrize( + "segments", + [ + (mx.zeros((1, 2, 4), dtype=mx.int32),), + (_text(1, 2), mx.zeros((1, 2, 4), dtype=mx.int32)), + ], +) +def test_unsupported_channel_count_is_rejected_in_every_state(segments): + with pytest.raises(ValueError, match="require 1 text channel or 3 MRoPE channels"): + _positions(*segments) + + +def test_incompatible_batch_shape_is_rejected(): + with pytest.raises(ValueError, match="consistent batch dimension"): + _positions(_text(1, 2, batch=1), _mrope((2, 3, 4), 2, batch=2)) + + +@pytest.mark.parametrize( + "segments", + [ + (mx.zeros((1, 4), dtype=mx.int32),), + (_mrope((1, 2, 3), 1), mx.zeros((1, 4), dtype=mx.int32)), + ], +) +def test_non_serialized_position_shape_is_rejected_in_every_state(segments): + with pytest.raises(ValueError, match=r"must be \[B, C, S\]"): + _positions(*segments) + + +def test_card_572_fourteen_block_topology_reconstructs_exact_prefix(): + block_size = 2048 + segments = [_text(block, block_size) for block in range(14)] + segments[9] = _mrope((90, 91, 92), block_size) + + result = _positions(*segments) + + assert result.shape == (1, 3, 28_672) + # Text blocks on either side are duplicated into every MRoPE coordinate. + expected_text_prefix = [ + block for block in range(9) for _ in range(block_size) + ] + for channel in range(3): + assert result[0, channel, : 9 * block_size].tolist() == expected_text_prefix + assert result[0, channel, 10 * block_size : 11 * block_size].tolist() == ( + [10] * block_size + ) + for channel, value in enumerate((90, 91, 92)): + assert result[0, channel, 9 * block_size : 10 * block_size].tolist() == ( + [value] * block_size + ) From fe8fe7edecc3b5f7ba69ac912bce5ee635052f4b Mon Sep 17 00:00:00 2001 From: MDX Tom Date: Sat, 29 Aug 2026 22:48:20 +0800 Subject: [PATCH 044/132] feat(cache): expose hybrid boundary diagnostics (#3249) Expose content-free boundary snapshot and prefix reuse diagnostics through runtime cache observability. --- omlx/admin/routes.py | 11 + omlx/cache/observability.py | 83 ++++++++ omlx/scheduler.py | 236 ++++++++++++++++++++-- tests/test_cache_observability.py | 47 ++++- tests/test_runtime_cache_observability.py | 25 +++ tests/test_scheduler.py | 55 ++++- 6 files changed, 437 insertions(+), 20 deletions(-) diff --git a/omlx/admin/routes.py b/omlx/admin/routes.py index 94932b2593..fbe12b2a03 100644 --- a/omlx/admin/routes.py +++ b/omlx/admin/routes.py @@ -5053,6 +5053,12 @@ def _build_runtime_cache_observability( gdn_last_restore = prefix_stats.get("gdn_last_restore") if not isinstance(gdn_last_restore, dict): gdn_last_restore = None + boundary_snapshots = runtime_stats.get("boundary_snapshots") + if not isinstance(boundary_snapshots, dict): + boundary_snapshots = None + last_prefix_lookup = runtime_stats.get("last_prefix_lookup") + if not isinstance(last_prefix_lookup, dict): + last_prefix_lookup = None # Keep the cache fields at the model-row level so the dashboard and # external admin clients can inspect them without knowing scheduler's @@ -5128,6 +5134,11 @@ def _build_runtime_cache_observability( "gdn_staging": gdn_staging_payload, } + if boundary_snapshots is not None: + model_payload["boundary_snapshots"] = boundary_snapshots + if last_prefix_lookup is not None: + model_payload["last_prefix_lookup"] = last_prefix_lookup + for field in ssd_counter_fields: if field in ssd_stats: model_payload[field] = int(ssd_stats.get(field, 0) or 0) diff --git a/omlx/cache/observability.py b/omlx/cache/observability.py index f42d4e8ba3..680a3f6ea5 100644 --- a/omlx/cache/observability.py +++ b/omlx/cache/observability.py @@ -76,6 +76,89 @@ def clear(self) -> None: self._snapshots.clear() +class BoundarySnapshotDiagnostics: + """Thread-safe counters for hybrid-cache boundary snapshot decisions. + + The scheduler writes these counters on its inference thread while the + admin endpoint can read them concurrently. Reasons are intentionally + stable, content-free identifiers so operators can tell whether a cache + store was missed because capture never ran, positional alignment failed, + or a persisted snapshot could not be restored. + """ + + _COUNTERS = ( + "capture_attempts", + "captures", + "captures_ssd", + "captures_memory", + "ssd_fallbacks", + "override_attempts", + "override_hits", + "override_misses", + "store_skips", + ) + + def __init__(self) -> None: + self._counters = {name: 0 for name in self._COUNTERS} + self._reasons: dict[str, int] = {} + self._last_event: dict[str, Any] | None = None + self._lock = threading.Lock() + + def record( + self, + event: str, + *, + reason: str | None = None, + request_id: str | None = None, + token_count: int | None = None, + block_size: int | None = None, + source: str | None = None, + storage: str | None = None, + available_boundaries: int | None = None, + ) -> None: + counter = { + "capture_attempt": "capture_attempts", + "capture_success": "captures", + "ssd_fallback": "ssd_fallbacks", + "override_attempt": "override_attempts", + "override_hit": "override_hits", + "override_miss": "override_misses", + "store_skip": "store_skips", + }.get(event) + + with self._lock: + if counter is not None: + self._counters[counter] += 1 + if event == "capture_success" and storage in {"ssd", "memory"}: + self._counters[f"captures_{storage}"] += 1 + if reason: + self._reasons[reason] = self._reasons.get(reason, 0) + 1 + + last_event: dict[str, Any] = {"event": event} + for key, value in ( + ("reason", reason), + ("request_id", request_id), + ("token_count", token_count), + ("block_size", block_size), + ("source", source), + ("storage", storage), + ("available_boundaries", available_boundaries), + ): + if value is not None: + last_event[key] = value + self._last_event = last_event + + def snapshot(self) -> dict[str, Any]: + with self._lock: + return { + **self._counters, + "reasons": dict(sorted(self._reasons.items())), + "last_event": ( + dict(self._last_event) if self._last_event is not None else None + ), + } + + def _window_label(seconds: int) -> str: if seconds < 60: return f"{seconds}s" diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 2baa60af81..6440acc355 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -47,7 +47,7 @@ ) from mlx_lm.sample_utils import make_logits_processors -from .cache.observability import CacheRateTracker +from .cache.observability import BoundarySnapshotDiagnostics, CacheRateTracker from .cache.paged_cache import PagedCacheManager from .cache.pooling_delta import compact_pooling_cache_snapshot from .cache.prefix_cache import BlockAwarePrefixCache, cachelist_pm_member_plan @@ -2087,12 +2087,14 @@ def __init__( self._boundary_snapshot_required: bool | None = None # SSD store for offloading boundary snapshots (initialized in _init_tiered_cache). self._boundary_snapshot_store: BoundarySnapshotSSDStore | None = None + self._boundary_snapshot_diagnostics = BoundarySnapshotDiagnostics() # paged SSD cache for KV state persistence (oMLX only supports paged SSD-based caching) self.paged_cache_manager: PagedCacheManager | None = None self.block_aware_cache: BlockAwarePrefixCache | None = None self.paged_ssd_cache_manager: PagedSSDCacheManager | None = None self._cache_rate_tracker = CacheRateTracker() + self._last_prefix_cache_lookup: dict[str, Any] | None = None # Prefill-peak estimator used by ``_preflight_memory_check`` / # ``preflight_or_raise``. Only the estimator path is exercised # here (it reads head_dim / num_layers / num_kv_heads via @@ -6263,14 +6265,45 @@ def _on_prefill_boundary_snapshot( ``BatchGenerator`` yet and the uid mapping does not exist — routing through it dropped every snapshot silently (#TBD). """ + block_size = self.config.paged_cache_block_size + self._boundary_snapshot_diagnostics.record( + "capture_attempt", + request_id=request_id, + token_count=token_count, + block_size=block_size, + source="prefill", + ) if self.block_aware_cache is None: + self._boundary_snapshot_diagnostics.record( + "capture_skipped", + reason="prefix_cache_disabled", + request_id=request_id, + token_count=token_count, + block_size=block_size, + source="prefill", + ) return - block_size = self.config.paged_cache_block_size if block_size <= 0 or token_count <= 0 or token_count % block_size != 0: + self._boundary_snapshot_diagnostics.record( + "capture_skipped", + reason="unaligned_token_count", + request_id=request_id, + token_count=token_count, + block_size=block_size, + source="prefill", + ) return if not self._cache_list_needs_boundary_snapshot(snapshot_cache): + self._boundary_snapshot_diagnostics.record( + "capture_skipped", + reason="no_stateful_cache", + request_id=request_id, + token_count=token_count, + block_size=block_size, + source="prefill", + ) return if request_id not in self._boundary_cache_snapshots: @@ -6278,6 +6311,14 @@ def _on_prefill_boundary_snapshot( # Skip if we already have a snapshot at this token count if token_count in self._boundary_cache_snapshots[request_id]: + self._boundary_snapshot_diagnostics.record( + "capture_skipped", + reason="duplicate_boundary", + request_id=request_id, + token_count=token_count, + block_size=block_size, + source="prefill", + ) return # Offload snapshot to SSD if store is available, keeping only a @@ -6299,7 +6340,17 @@ def _on_prefill_boundary_snapshot( ) if saved: self._boundary_cache_snapshots[request_id][token_count] = None + storage = "ssd" else: + self._boundary_snapshot_diagnostics.record( + "ssd_fallback", + reason="ssd_save_failed", + request_id=request_id, + token_count=token_count, + block_size=block_size, + source="prefill", + storage="memory", + ) self._boundary_cache_snapshots[request_id][token_count] = ( _compact_boundary_snapshot_value( self._prefill_snapshot_value(snapshot_cache), @@ -6308,6 +6359,7 @@ def _on_prefill_boundary_snapshot( self._stream, ) ) + storage = "memory" else: self._boundary_cache_snapshots[request_id][token_count] = ( _compact_boundary_snapshot_value( @@ -6317,13 +6369,23 @@ def _on_prefill_boundary_snapshot( self._stream, ) ) + storage = "memory" self._boundary_snapshot_required = True self._enable_mtp_boundary_alignment() + self._boundary_snapshot_diagnostics.record( + "capture_success", + request_id=request_id, + token_count=token_count, + block_size=block_size, + source="prefill", + storage=storage, + ) logger.debug( - "Captured prefill boundary cache snapshot for %s at %s tokens", + "Captured prefill boundary cache snapshot for %s at %s tokens (%s)", request_id, token_count, + storage, ) _PREFILL_SNAPSHOT_MARKER = "__prefill_extracted__" @@ -6547,7 +6609,10 @@ def _enable_mtp_boundary_alignment(self) -> None: pass def _extract_boundary_snapshot( - self, uid: int, expected_tokens: int | None = None + self, + uid: int, + expected_tokens: int | None = None, + request_id: str | None = None, ) -> list[Any] | None: """Extract a per-request prompt cache snapshot via extract_cache(). @@ -6565,7 +6630,20 @@ def _extract_boundary_snapshot( on hybrid models; skipping the capture merely costs a reuse opportunity. """ + block_size = self.config.paged_cache_block_size + + def record_skip(reason: str) -> None: + self._boundary_snapshot_diagnostics.record( + "capture_skipped", + reason=reason, + request_id=request_id, + token_count=expected_tokens, + block_size=block_size, + source="decode", + ) + if self.batch_generator is None: + record_skip("batch_generator_unavailable") return None try: @@ -6577,6 +6655,7 @@ def _extract_boundary_snapshot( with mx.stream(self._stream): result = self.batch_generator.extract_cache([uid]) if uid not in result: + record_skip("uid_not_found") return None cache_list, _tokens = result[uid] if expected_tokens is not None: @@ -6597,11 +6676,12 @@ def _extract_boundary_snapshot( offset, expected_tokens, ) + record_skip("cache_offset_mismatch") return None break # Only extract non-sliceable layers to avoid costly # deep-copy accumulation (same rationale as prefill path). - return [ + snapshot = [ ( c if type(c).__name__ not in _KNOWN_SLICEABLE_CACHE_TYPES @@ -6609,10 +6689,15 @@ def _extract_boundary_snapshot( ) for c in cache_list ] + if not snapshot: + record_skip("empty_snapshot") + return None + return snapshot except Exception as e: logger.debug( f"Failed to extract boundary cache snapshot for uid={uid}: {e}" ) + record_skip("extract_error") return None def _maybe_capture_boundary_snapshot(self, request: Request, uid: int) -> None: @@ -6631,8 +6716,17 @@ def _maybe_capture_boundary_snapshot(self, request: Request, uid: int) -> None: if not self._detect_boundary_snapshot_need(): return + self._boundary_snapshot_diagnostics.record( + "capture_attempt", + request_id=request.request_id, + token_count=total_tokens, + block_size=block_size, + source="decode", + ) snapshot_cache = self._extract_boundary_snapshot( - uid, expected_tokens=total_tokens + uid, + expected_tokens=total_tokens, + request_id=request.request_id, ) if not snapshot_cache: return @@ -6652,7 +6746,17 @@ def _maybe_capture_boundary_snapshot(self, request: Request, uid: int) -> None: ) if saved: self._boundary_cache_snapshots[request.request_id][total_tokens] = None + storage = "ssd" else: + self._boundary_snapshot_diagnostics.record( + "ssd_fallback", + reason="ssd_save_failed", + request_id=request.request_id, + token_count=total_tokens, + block_size=block_size, + source="decode", + storage="memory", + ) # In-memory fallback: the store-cache worker slices this snapshot # off-thread (via _BoundarySnapshotProvider -> _extract_cache_states). # MLX streams are thread-local, so force the leaves concrete now on @@ -6664,16 +6768,26 @@ def _maybe_capture_boundary_snapshot(self, request: Request, uid: int) -> None: snapshot_cache, total_tokens, block_size ) ) + storage = "memory" else: self._boundary_cache_snapshots[request.request_id][total_tokens] = ( self._decode_boundary_snapshot_value( snapshot_cache, total_tokens, block_size ) ) + storage = "memory" + self._boundary_snapshot_diagnostics.record( + "capture_success", + request_id=request.request_id, + token_count=total_tokens, + block_size=block_size, + source="decode", + storage=storage, + ) logger.debug( f"Captured boundary cache snapshot for {request.request_id} at " - f"{total_tokens} tokens" + f"{total_tokens} tokens ({storage})" ) def _get_boundary_store_override( @@ -6697,12 +6811,33 @@ def _get_boundary_store_override( intermediate_snapshots) where intermediate_snapshots maps token_count -> extracted cache states for per-block storage. """ + total_tokens = len(full_token_sequence) + block_size = self.config.paged_cache_block_size + self._boundary_snapshot_diagnostics.record( + "override_attempt", + request_id=request_id, + token_count=total_tokens, + block_size=block_size, + ) + + def miss(reason: str, available_boundaries: int = 0) -> None: + self._boundary_snapshot_diagnostics.record( + "override_miss", + reason=reason, + request_id=request_id, + token_count=total_tokens, + block_size=block_size, + available_boundaries=available_boundaries, + ) + snapshots = self._boundary_cache_snapshots.get(request_id) if not snapshots: + miss("no_snapshots") return None - total_tokens = len(full_token_sequence) - block_size = self.config.paged_cache_block_size + if block_size <= 0: + miss("invalid_block_size", len(snapshots)) + return None # Find all valid boundary-aligned snapshot token counts valid_counts = sorted( @@ -6711,6 +6846,7 @@ def _get_boundary_store_override( if 0 < tc <= total_tokens and tc % block_size == 0 ) if not valid_counts: + miss("no_aligned_snapshots", len(snapshots)) return None # Find the latest snapshot that leaves trailing partial tokens @@ -6724,6 +6860,7 @@ def _get_boundary_store_override( # provide intermediate snapshots for per-block storage. latest_tc = total_tokens else: + miss("latest_snapshot_not_usable", len(valid_counts)) return None # Load latest snapshot — may be on SSD (None marker) or in memory. @@ -6738,6 +6875,7 @@ def _get_boundary_store_override( # Offloaded to SSD — load back. extracted_cache = self._boundary_snapshot_store.load(request_id, latest_tc) if not extracted_cache: + miss("ssd_load_failed", len(valid_counts)) return None # Build model_cache_config from the main request cache config # since the SSD snapshot doesn't carry it. @@ -6761,8 +6899,10 @@ def _get_boundary_store_override( latest_snapshot ) if not extracted_cache: + miss("snapshot_extract_failed", len(valid_counts)) return None else: + miss("snapshot_value_unavailable", len(valid_counts)) return None # Build provider for intermediate snapshots. SSD-backed snapshots remain @@ -6806,6 +6946,13 @@ def _get_boundary_store_override( else full_token_sequence ) + self._boundary_snapshot_diagnostics.record( + "override_hit", + request_id=request_id, + token_count=latest_tc, + block_size=block_size, + available_boundaries=len(valid_counts), + ) return ( token_sequence, extracted_cache, @@ -7703,7 +7850,35 @@ def _log_prefix_divergence(self, request: Request) -> None: logs. """ prompt = request.prompt_token_ids or [] - if not prompt or not self._cache_probe_seqs: + cached = request.cached_tokens or 0 + block = max(1, self.config.paged_cache_block_size) + base_observation: dict[str, Any] = { + "request_id": request.request_id, + "prompt_tokens": len(prompt), + "reused_kv_tokens": cached, + "reprefill_tokens": max(0, len(prompt) - cached), + "block_size": block, + "matched_blocks": cached // block, + } + if not prompt: + self._last_prefix_cache_lookup = { + **base_observation, + "reason": "empty_prompt", + "closest_request_id": None, + "common_prefix_tokens": 0, + "comparable_tokens": 0, + "unreused_common_prefix_tokens": 0, + } + return + if not self._cache_probe_seqs: + self._last_prefix_cache_lookup = { + **base_observation, + "reason": "no_recent_store_probe", + "closest_request_id": None, + "common_prefix_tokens": 0, + "comparable_tokens": 0, + "unreused_common_prefix_tokens": 0, + } return best_id, best_seq, best_p = None, None, -1 for ref_id, seq in list(self._cache_probe_seqs): @@ -7712,10 +7887,16 @@ def _log_prefix_divergence(self, request: Request) -> None: best_id, best_seq, best_p = ref_id, seq, p if best_seq is None: return - cached = request.cached_tokens or 0 reusable = min(len(prompt), len(best_seq)) - block = max(1, self.config.paged_cache_block_size) reprefill = len(prompt) - cached + self._last_prefix_cache_lookup = { + **base_observation, + "reason": "closest_recent_store", + "closest_request_id": best_id, + "common_prefix_tokens": best_p, + "comparable_tokens": reusable, + "unreused_common_prefix_tokens": max(0, best_p - cached), + } if reprefill >= self._REPREFILL_INFO_MIN_TOKENS and best_p >= block: logger.info( "prefix cache: request %s re-prefills %d of %d tokens " @@ -11099,13 +11280,27 @@ def _cleanup_finished(self, finished_ids: set[str]) -> None: f"{len(request.output_token_ids)} output)" ) except _BoundaryStoreUnavailable: - logger.debug( - "Skipping cache store for %s: no boundary-aligned " - "snapshot for non-sliceable cache state (all " - "captures skipped, e.g. by the speculative-decode " - "skew guard); storing live state would corrupt " + available_boundaries = len( + self._boundary_cache_snapshots.get(request_id, {}) + ) + self._boundary_snapshot_diagnostics.record( + "store_skip", + reason="boundary_snapshot_unavailable", + request_id=request_id, + token_count=len(cacheable_sequence), + block_size=self.config.paged_cache_block_size, + available_boundaries=available_boundaries, + ) + logger.info( + "Skipping cache store for %s: reason=%s " + "tokens=%d block_size=%d available_boundaries=%d; " + "storing live non-sliceable state would corrupt " "later prefix hits", request_id, + "boundary_snapshot_unavailable", + len(cacheable_sequence), + self.config.paged_cache_block_size, + available_boundaries, ) block_table = None if self.paged_cache_manager: @@ -13025,6 +13220,13 @@ def get_ssd_cache_stats(self) -> dict[str, Any] | None: if self.block_aware_cache is not None: prefix_stats = self.block_aware_cache.get_stats_dict() stats["prefix_cache"] = prefix_stats + stats["boundary_snapshots"] = ( + self._boundary_snapshot_diagnostics.snapshot() + ) + if self._last_prefix_cache_lookup is not None: + stats["last_prefix_lookup"] = dict( + self._last_prefix_cache_lookup + ) specprefill_cache_stats = { "target_static_hits": prefix_stats["exact_prefix_hits"], "target_static_misses": prefix_stats["exact_prefix_misses"], diff --git a/tests/test_cache_observability.py b/tests/test_cache_observability.py index 0703d23c79..f9921c26f4 100644 --- a/tests/test_cache_observability.py +++ b/tests/test_cache_observability.py @@ -8,7 +8,7 @@ import pytest -from omlx.cache.observability import CacheRateTracker +from omlx.cache.observability import BoundarySnapshotDiagnostics, CacheRateTracker def _make_counters( @@ -233,3 +233,48 @@ def test_clear_resets_state(self): tracker.maybe_snapshot(_make_counters(prefix_hits=100)) tracker.clear() assert tracker.get_rates() == {"windows": {}, "cumulative": {}} + + +def test_boundary_snapshot_diagnostics_are_structured_and_thread_safe(): + diagnostics = BoundarySnapshotDiagnostics() + diagnostics.record( + "capture_attempt", + request_id="req-a", + token_count=4096, + block_size=4096, + source="prefill", + ) + diagnostics.record( + "ssd_fallback", + reason="ssd_save_failed", + request_id="req-a", + token_count=4096, + block_size=4096, + source="prefill", + storage="memory", + ) + diagnostics.record( + "capture_success", + request_id="req-a", + token_count=4096, + block_size=4096, + source="prefill", + storage="memory", + ) + + snapshot = diagnostics.snapshot() + + assert snapshot["capture_attempts"] == 1 + assert snapshot["captures"] == 1 + assert snapshot["captures_memory"] == 1 + assert snapshot["captures_ssd"] == 0 + assert snapshot["ssd_fallbacks"] == 1 + assert snapshot["reasons"] == {"ssd_save_failed": 1} + assert snapshot["last_event"] == { + "event": "capture_success", + "request_id": "req-a", + "token_count": 4096, + "block_size": 4096, + "source": "prefill", + "storage": "memory", + } diff --git a/tests/test_runtime_cache_observability.py b/tests/test_runtime_cache_observability.py index 385e6bd6d6..8b5cf00ae7 100644 --- a/tests/test_runtime_cache_observability.py +++ b/tests/test_runtime_cache_observability.py @@ -126,6 +126,25 @@ class Engine: "sidecar_count": 84, "sidecar_size_bytes": 4096, }, + "boundary_snapshots": { + "capture_attempts": 5, + "captures": 4, + "override_misses": 1, + "reasons": {"cache_offset_mismatch": 1}, + "last_event": { + "event": "capture_skipped", + "reason": "cache_offset_mismatch", + }, + }, + "last_prefix_lookup": { + "request_id": "lookup-a", + "prompt_tokens": 20000, + "reused_kv_tokens": 16384, + "reprefill_tokens": 3616, + "common_prefix_tokens": 18000, + "unreused_common_prefix_tokens": 1616, + "block_size": 2048, + }, "ssd_cache": { "num_files": 84, "total_size_bytes": 5000, @@ -170,6 +189,12 @@ class Engine: assert row["loads"] == 6 assert row["errors"] == 1 assert row["hot_cache_hits"] == 4 + assert row["boundary_snapshots"]["capture_attempts"] == 5 + assert row["boundary_snapshots"]["reasons"] == { + "cache_offset_mismatch": 1 + } + assert row["last_prefix_lookup"]["reused_kv_tokens"] == 16384 + assert row["last_prefix_lookup"]["unreused_common_prefix_tokens"] == 1616 def test_engine_returning_none_stats_is_skipped(tmp_path): diff --git a/tests/test_scheduler.py b/tests/test_scheduler.py index 2cb77bd170..655ea18d8f 100644 --- a/tests/test_scheduler.py +++ b/tests/test_scheduler.py @@ -2425,6 +2425,10 @@ def test_capture_boundary_snapshot_at_block_boundary( scheduler._maybe_capture_boundary_snapshot(request, 123) assert 4 in scheduler._boundary_cache_snapshots["req-boundary"] + diagnostics = scheduler._boundary_snapshot_diagnostics.snapshot() + assert diagnostics["capture_attempts"] == 1 + assert diagnostics["captures"] == 1 + assert diagnostics["captures_memory"] == 1 snapshot = scheduler._boundary_cache_snapshots["req-boundary"][4] # The in-memory fallback pre-extracts eagerly (retaining raw cache # objects kept the full KV member of pm-eligible CacheLists alive @@ -2472,6 +2476,10 @@ def test_boundary_snapshot_skipped_on_speculative_skew( scheduler._maybe_capture_boundary_snapshot(request, 123) assert "req-skew" not in scheduler._boundary_cache_snapshots + diagnostics = scheduler._boundary_snapshot_diagnostics.snapshot() + assert diagnostics["capture_attempts"] == 1 + assert diagnostics["captures"] == 0 + assert diagnostics["reasons"]["cache_offset_mismatch"] == 1 @staticmethod def _cache_list_layer(leaf_offset: int): @@ -2548,7 +2556,7 @@ def test_boundary_snapshot_captured_through_cachelist( assert 4 in scheduler._boundary_cache_snapshots["req-cl-ok"] def test_cleanup_finished_skips_store_without_boundary_snapshot( - self, mock_model, mock_tokenizer + self, mock_model, mock_tokenizer, caplog ): """Snapshot-needing models must not store live non-sliceable state when no boundary-aligned snapshot exists (e.g. every capture was @@ -2574,12 +2582,55 @@ def test_cleanup_finished_skips_store_without_boundary_snapshot( scheduler.requests["req-no-snap"] = request # No boundary snapshots recorded for this request. - scheduler._cleanup_finished({"req-no-snap"}) + with caplog.at_level("INFO", logger="omlx.scheduler"): + scheduler._cleanup_finished({"req-no-snap"}) scheduler.block_aware_cache.store_cache.assert_not_called() scheduler.block_aware_cache.clear_request_entry.assert_called_with( "req-no-snap" ) + diagnostics = scheduler._boundary_snapshot_diagnostics.snapshot() + assert diagnostics["override_attempts"] == 1 + assert diagnostics["override_misses"] == 1 + assert diagnostics["store_skips"] == 1 + assert diagnostics["reasons"] == { + "boundary_snapshot_unavailable": 1, + "no_snapshots": 1, + } + assert "reason=boundary_snapshot_unavailable" in caplog.text + + def test_prefix_lookup_observation_explains_reprefill_boundary( + self, mock_model, mock_tokenizer + ): + config = SchedulerConfig(paged_cache_block_size=4) + scheduler = Scheduler(model=mock_model, tokenizer=mock_tokenizer, config=config) + scheduler._cache_probe_seqs.append( + ("stored-a", [1, 2, 3, 4, 5, 6, 7, 8]) + ) + request = Request( + request_id="lookup-a", + prompt="hello", + sampling_params=SamplingParams(), + ) + request.prompt_token_ids = [1, 2, 3, 4, 5, 6, 7, 99] + request.num_prompt_tokens = 8 + request.cached_tokens = 4 + + scheduler._log_prefix_divergence(request) + + assert scheduler._last_prefix_cache_lookup == { + "request_id": "lookup-a", + "prompt_tokens": 8, + "reused_kv_tokens": 4, + "reprefill_tokens": 4, + "block_size": 4, + "matched_blocks": 1, + "reason": "closest_recent_store", + "closest_request_id": "stored-a", + "common_prefix_tokens": 7, + "comparable_tokens": 8, + "unreused_common_prefix_tokens": 3, + } def test_cleanup_finished_skips_output_tokens_for_reasoning_model( self, mock_model, mock_tokenizer From 4a082f4bb883cdae1de3f444d4a5ae050d39d213 Mon Sep 17 00:00:00 2001 From: "Aka.Fido" Date: Sat, 29 Aug 2026 22:57:27 +0800 Subject: [PATCH 045/132] fix: allow TurboQuant with Lightning MTP in macOS app (#3254) --- .../AppView/ViewModels/ModelSettingsScreenVM.swift | 10 +++------- .../Tests/oMLXTests/ModelSettingsScreenVMTests.swift | 12 ++++++++++++ 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/apps/omlx-mac/Sources/AppView/ViewModels/ModelSettingsScreenVM.swift b/apps/omlx-mac/Sources/AppView/ViewModels/ModelSettingsScreenVM.swift index adbf82c9e4..b1286154e9 100644 --- a/apps/omlx-mac/Sources/AppView/ViewModels/ModelSettingsScreenVM.swift +++ b/apps/omlx-mac/Sources/AppView/ViewModels/ModelSettingsScreenVM.swift @@ -1013,19 +1013,15 @@ final class ModelSettingsScreenVM { || type.hasPrefix("qwen3_8") } - /// MTP can't co-exist with DFlash or TurboQuant KV. The toggle uses - /// this to disable itself and surface the conflict reason. + /// Native Lightning MTP can't co-exist with the other speculative + /// decoders. TurboQuant KV supports its decode-shaped multi-row verify + /// path, so it is intentionally not a conflict here. var mtpConflictReason: String? { if dflashEnabled { return String(localized: "settings.mtp.conflict.dflash", defaultValue: "Disable DFlash before enabling MTP.", comment: "Tooltip / sublabel shown when MTP can't be enabled because DFlash is on") } - if turboquantKvEnabled { - return String(localized: "settings.mtp.conflict.turboquant", - defaultValue: "Disable TurboQuant KV before enabling MTP.", - comment: "Tooltip / sublabel shown when MTP can't be enabled because TurboQuant KV is on") - } if vlmMtpEnabled { return String(localized: "settings.mtp.conflict.vlm_mtp", defaultValue: "Disable VLM MTP before enabling Lightning MTP.", diff --git a/apps/omlx-mac/Tests/oMLXTests/ModelSettingsScreenVMTests.swift b/apps/omlx-mac/Tests/oMLXTests/ModelSettingsScreenVMTests.swift index cca3232144..b92e7c829f 100644 --- a/apps/omlx-mac/Tests/oMLXTests/ModelSettingsScreenVMTests.swift +++ b/apps/omlx-mac/Tests/oMLXTests/ModelSettingsScreenVMTests.swift @@ -23,6 +23,18 @@ final class ModelSettingsScreenVMTests: XCTestCase { ) } + func testLightningMtpAllowsTurboQuantInWorkingProfile() { + let vm = ModelSettingsScreenVM() + vm.mtpEnabled = true + vm.turboquantKvEnabled = true + + XCTAssertNil(vm.mtpConflictReason) + + let settings = vm.currentSettingsDict() + XCTAssertEqual(settings["mtp_enabled"]?.value as? Bool, true) + XCTAssertEqual(settings["turboquant_kv_enabled"]?.value as? Bool, true) + } + func testVlmMtpDraftModelOptionsIncludeQwenMtpConfigType() { let vm = ModelSettingsScreenVM() vm.modelID = "Qwopus3.6-35B-A3B-v1-4bit-MLXVLM-Target" From dc18a1814e4bbfab0a757b570adfa7ff248cc435 Mon Sep 17 00:00:00 2001 From: Cold Cloud <64406210+yanzhaohui1999@users.noreply.github.com> Date: Sat, 29 Aug 2026 23:07:58 +0800 Subject: [PATCH 046/132] fix(admin): persist mtp_num_draft_tokens via settings PUT (#3280) Persist `mtp_num_draft_tokens`, `preserve_thinking`, and `turboquant_skip_last` through the admin settings PUT path, reject unknown fields, and reload active Lightning MTP engines when draft depth changes. Co-authored-by: Alyta Phoenix --- omlx/admin/routes.py | 27 +++++++- omlx/engine_pool.py | 5 ++ tests/test_admin_model_settings.py | 108 +++++++++++++++++++++++++++++ 3 files changed, 139 insertions(+), 1 deletion(-) diff --git a/omlx/admin/routes.py b/omlx/admin/routes.py index fbe12b2a03..bc4b52e07a 100644 --- a/omlx/admin/routes.py +++ b/omlx/admin/routes.py @@ -28,7 +28,7 @@ from fastapi import APIRouter, Depends, HTTPException, Request, Response from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse from fastapi.templating import Jinja2Templates -from pydantic import BaseModel, Field, field_validator +from pydantic import BaseModel, ConfigDict, Field, field_validator from ..api.markitdown import MARKITDOWN_MODEL_ID, markitdown_model_visible from ..api.openai_models import _coerce_tool_call_arguments @@ -112,6 +112,8 @@ class CacheProbeRequest(BaseModel): class ModelSettingsRequest(BaseModel): """Request model for updating per-model settings.""" + model_config = ConfigDict(extra="forbid") + model_alias: str | None = None model_type_override: str | None = None max_context_window: int | None = None @@ -129,12 +131,18 @@ class ModelSettingsRequest(BaseModel): ttl_seconds: int | None = None index_cache_freq: int | None = None enable_thinking: bool | None = None + # Keep thinking blocks in historical turns (None = auto, True when the + # template supports it). Mirrors ModelSettings.preserve_thinking. + preserve_thinking: bool | None = None qwen4_ple_ssd_offload: bool | None = None thinking_budget_enabled: bool | None = None thinking_budget_tokens: int | None = None + # MTP draft tokens per cycle for legacy MTP (None = adaptive default). + mtp_num_draft_tokens: int | None = None # TurboQuant KV cache (mlx-vlm backend) turboquant_kv_enabled: bool | None = None turboquant_kv_bits: float | None = None + turboquant_skip_last: bool | None = None # Private Qwen3.5/3.6/3.8 ANE/GPU fixed-shape prefill qwen35_ane_prefill_enabled: bool | None = None qwen35_ane_prefill_sequence_length: int | None = None @@ -2358,6 +2366,16 @@ async def update_model_settings( if request.thinking_budget_tokens and request.thinking_budget_tokens > 0 else None ) + if "mtp_num_draft_tokens" in sent: + value = request.mtp_num_draft_tokens + if value is not None and value < 1: + raise HTTPException( + status_code=400, + detail="mtp_num_draft_tokens must be a positive integer (or null).", + ) + current_settings.mtp_num_draft_tokens = value + if "preserve_thinking" in sent: + current_settings.preserve_thinking = request.preserve_thinking if "chat_template_kwargs" in sent: current_settings.chat_template_kwargs = request.chat_template_kwargs if "forced_ct_kwargs" in sent: @@ -2376,6 +2394,13 @@ async def update_model_settings( current_settings.turboquant_kv_enabled = request.turboquant_kv_enabled or False if "turboquant_kv_bits" in sent: current_settings.turboquant_kv_bits = request.turboquant_kv_bits or 4 + if "turboquant_skip_last" in sent: + # null = clear to the model default (True); bool(None) would flip it + # to False and silently disable the skip-last corruption guard. + current_settings.turboquant_skip_last = ( + True if request.turboquant_skip_last is None + else bool(request.turboquant_skip_last) + ) # Private Qwen3.5/3.6/3.8 ANE/GPU fixed-shape prefill. These are all load-time # controls; the runtime signature below causes a loaded model to be # re-created when the user applies a changed profile. diff --git a/omlx/engine_pool.py b/omlx/engine_pool.py index ba7837c53e..9ec150669f 100644 --- a/omlx/engine_pool.py +++ b/omlx/engine_pool.py @@ -586,6 +586,11 @@ def add(key: str, value: object) -> None: # force a reload when the corresponding feature is disabled. mtp_active = bool(data.get("mtp_enabled", False)) add("mtp_enabled", mtp_active) + # Draft depth is read once at engine construction; it must be in the + # signature while Lightning MTP is active so a change reloads the + # engine, but a stale value must not force one when MTP is off. + if mtp_active: + add("mtp_num_draft_tokens", data.get("mtp_num_draft_tokens")) if entry is not None: qwen4_offload, _, _ = self._qwen4_ple_offload_status(entry, settings) add("qwen4_ple_ssd_offload", qwen4_offload) diff --git a/tests/test_admin_model_settings.py b/tests/test_admin_model_settings.py index 31c289a5d3..d1d4310825 100644 --- a/tests/test_admin_model_settings.py +++ b/tests/test_admin_model_settings.py @@ -334,3 +334,111 @@ async def test_qwen_ane_prefill_rejects_other_model_families(): ModelSettings(), admin_routes.ModelSettingsRequest(qwen35_ane_prefill_enabled=True), ) + + +@pytest.mark.asyncio +async def test_mtp_draft_tokens_is_persisted_not_dropped(): + """#2823: mtp_num_draft_tokens used to be silently discarded by PUT.""" + pool, _ = _failed_pool() + settings = ModelSettings(mtp_num_draft_tokens=None) + + result = await _update_settings( + pool, + settings, + admin_routes.ModelSettingsRequest(mtp_num_draft_tokens=8), + ) + + assert settings.mtp_num_draft_tokens == 8 + assert result["settings"]["mtp_num_draft_tokens"] == 8 + + +@pytest.mark.asyncio +async def test_preserve_thinking_and_turboquant_skip_last_are_persisted(): + """Same silent-drop class as #2823 for the other two engine settings.""" + pool, _ = _failed_pool() + settings = ModelSettings( + preserve_thinking=False, + turboquant_skip_last=True, + ) + + result = await _update_settings( + pool, + settings, + admin_routes.ModelSettingsRequest( + preserve_thinking=True, + turboquant_skip_last=False, + ), + ) + + assert settings.preserve_thinking is True + assert settings.turboquant_skip_last is False + assert result["settings"]["preserve_thinking"] is True + assert result["settings"]["turboquant_skip_last"] is False + + +@pytest.mark.asyncio +async def test_mtp_draft_tokens_rejects_non_positive_values(): + pool, _ = _failed_pool() + + with pytest.raises( + admin_routes.HTTPException, match="must be a positive integer" + ): + await _update_settings( + pool, + ModelSettings(), + admin_routes.ModelSettingsRequest(mtp_num_draft_tokens=0), + ) + + +def test_unknown_settings_fields_are_rejected_loudly(): + """Unknown keys must 422 instead of silently returning success:true.""" + import pydantic + + with pytest.raises(pydantic.ValidationError, match="bogus_field"): + # Simulate a client sending a field that has no admin-PUT support. + admin_routes.ModelSettingsRequest(mtp_num_draft_tokens=8, bogus_field=1) + + +@pytest.mark.asyncio +async def test_turboquant_skip_last_null_preserves_default_true(): + """null = clear to the model default; it must not flip the default to + False via bool(None) (review feedback on the silent-drop fix).""" + pool, _ = _failed_pool() + settings = ModelSettings() # default turboquant_skip_last=True + + result = await _update_settings( + pool, + settings, + admin_routes.ModelSettingsRequest(turboquant_skip_last=None), + ) + + assert settings.turboquant_skip_last is True + assert result["settings"]["turboquant_skip_last"] is True + + +def test_runtime_signature_gates_mtp_depth_on_lightning_mtp(): + """mtp_num_draft_tokens must be part of the engine runtime signature only + while Lightning MTP (mtp_enabled) is active (review feedback), so a depth + change reloads a loaded engine, but a stale value never forces one.""" + from omlx.engine_pool import EnginePool + + pool = EnginePool() + + depth_3_on = ModelSettings(mtp_enabled=True, mtp_num_draft_tokens=3) + depth_8_on = ModelSettings(mtp_enabled=True, mtp_num_draft_tokens=8) + depth_3_off = ModelSettings(mtp_enabled=False, mtp_num_draft_tokens=3) + depth_8_off = ModelSettings(mtp_enabled=False, mtp_num_draft_tokens=8) + + on_keys = {k for k, _ in pool._engine_runtime_signature("m", depth_3_on)} + assert "mtp_num_draft_tokens" in on_keys + off_keys = {k for k, _ in pool._engine_runtime_signature("m", depth_3_off)} + assert "mtp_num_draft_tokens" not in off_keys + + # Active MTP: different depths produce different signatures (reload). + assert pool._engine_runtime_signature("m", depth_3_on) != pool._engine_runtime_signature( + "m", depth_8_on + ) + # Inactive MTP: the value is invisible to the signature (no reload). + assert pool._engine_runtime_signature("m", depth_3_off) == pool._engine_runtime_signature( + "m", depth_8_off + ) From b798e651bb489cec5ce80a93a17a45ad9bbabdcf Mon Sep 17 00:00:00 2001 From: jundot Date: Sun, 30 Aug 2026 00:08:55 +0900 Subject: [PATCH 047/132] fix(cache): keep boundary diagnostics accurate --- omlx/cache/observability.py | 17 +++++++++++++ omlx/scheduler.py | 4 ++++ tests/test_cache_observability.py | 40 +++++++++++++++++++++++++++++++ tests/test_scheduler.py | 32 +++++++++++++++++++++++++ 4 files changed, 93 insertions(+) diff --git a/omlx/cache/observability.py b/omlx/cache/observability.py index 680a3f6ea5..ca7bd95b74 100644 --- a/omlx/cache/observability.py +++ b/omlx/cache/observability.py @@ -127,6 +127,15 @@ def record( }.get(event) with self._lock: + cause = None + if ( + event == "store_skip" + and self._last_event is not None + and self._last_event.get("event") == "override_miss" + and self._last_event.get("request_id") == request_id + ): + cause = self._last_event.get("reason") + if counter is not None: self._counters[counter] += 1 if event == "capture_success" and storage in {"ssd", "memory"}: @@ -143,6 +152,7 @@ def record( ("source", source), ("storage", storage), ("available_boundaries", available_boundaries), + ("cause", cause), ): if value is not None: last_event[key] = value @@ -158,6 +168,13 @@ def snapshot(self) -> dict[str, Any]: ), } + def clear(self) -> None: + with self._lock: + for name in self._counters: + self._counters[name] = 0 + self._reasons.clear() + self._last_event = None + def _window_label(seconds: int) -> str: if seconds < 60: diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 6440acc355..87fd4fb5aa 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -11480,6 +11480,8 @@ def _recover_from_cache_error(self) -> None: if self.block_aware_cache is not None: self.block_aware_cache.clear() self._cache_rate_tracker.clear() + self._boundary_snapshot_diagnostics.clear() + self._last_prefix_cache_lookup = None # Clear UID mappings _unregister_uid_rows_for_model(self.model) @@ -12239,6 +12241,8 @@ def reset(self) -> None: if self.block_aware_cache is not None: self.block_aware_cache.clear() self._cache_rate_tracker.clear() + self._boundary_snapshot_diagnostics.clear() + self._last_prefix_cache_lookup = None # Clear detokenizers self._request_detokenizers.clear() diff --git a/tests/test_cache_observability.py b/tests/test_cache_observability.py index f9921c26f4..6a267a86ea 100644 --- a/tests/test_cache_observability.py +++ b/tests/test_cache_observability.py @@ -278,3 +278,43 @@ def test_boundary_snapshot_diagnostics_are_structured_and_thread_safe(): "source": "prefill", "storage": "memory", } + + +def test_boundary_snapshot_diagnostics_preserve_store_skip_cause(): + diagnostics = BoundarySnapshotDiagnostics() + diagnostics.record( + "override_miss", + reason="ssd_load_failed", + request_id="req-a", + token_count=4096, + block_size=2048, + available_boundaries=2, + ) + + diagnostics.record( + "store_skip", + reason="boundary_snapshot_unavailable", + request_id="req-a", + token_count=4096, + block_size=2048, + available_boundaries=2, + ) + + assert diagnostics.snapshot()["last_event"]["cause"] == "ssd_load_failed" + + +def test_boundary_snapshot_diagnostics_clear_resets_state(): + diagnostics = BoundarySnapshotDiagnostics() + diagnostics.record( + "capture_attempt", + request_id="req-a", + token_count=4096, + block_size=2048, + ) + + diagnostics.clear() + + snapshot = diagnostics.snapshot() + assert snapshot["capture_attempts"] == 0 + assert snapshot["reasons"] == {} + assert snapshot["last_event"] is None diff --git a/tests/test_scheduler.py b/tests/test_scheduler.py index 655ea18d8f..023c055496 100644 --- a/tests/test_scheduler.py +++ b/tests/test_scheduler.py @@ -1734,6 +1734,13 @@ class TestSchedulerReset: def test_reset_clears_state(self, mock_model, mock_tokenizer): """Test reset() clears all scheduler state.""" scheduler = Scheduler(model=mock_model, tokenizer=mock_tokenizer) + scheduler._boundary_snapshot_diagnostics.record( + "capture_attempt", + request_id="before-reset", + token_count=4, + block_size=4, + ) + scheduler._last_prefix_cache_lookup = {"request_id": "before-reset"} # Add some requests for i in range(3): @@ -1751,12 +1758,36 @@ def test_reset_clears_state(self, mock_model, mock_tokenizer): assert len(scheduler.running) == 0 assert len(scheduler.requests) == 0 assert scheduler.batch_generator is None + diagnostics = scheduler._boundary_snapshot_diagnostics.snapshot() + assert diagnostics["capture_attempts"] == 0 + assert diagnostics["last_event"] is None + assert scheduler._last_prefix_cache_lookup is None # reset() only drops Python references (bytes move INTO the pooled # cache), so an enforcer reclaim request must survive it: the # enforcer never re-issues below hard pressure, and dropping the # request anywhere re-opens the 2179 wedge. assert scheduler._pending_reclaim_request is True + def test_cache_recovery_clears_cache_observability( + self, mock_model, mock_tokenizer + ): + scheduler = Scheduler(model=mock_model, tokenizer=mock_tokenizer) + scheduler.block_aware_cache = MagicMock() + scheduler._boundary_snapshot_diagnostics.record( + "capture_attempt", + request_id="before-recovery", + token_count=4, + block_size=4, + ) + scheduler._last_prefix_cache_lookup = {"request_id": "before-recovery"} + + scheduler._recover_from_cache_error() + + diagnostics = scheduler._boundary_snapshot_diagnostics.snapshot() + assert diagnostics["capture_attempts"] == 0 + assert diagnostics["last_event"] is None + assert scheduler._last_prefix_cache_lookup is None + def test_reset_clears_async_store_cache_bookkeeping( self, mock_model, mock_tokenizer ): @@ -2597,6 +2628,7 @@ def test_cleanup_finished_skips_store_without_boundary_snapshot( "boundary_snapshot_unavailable": 1, "no_snapshots": 1, } + assert diagnostics["last_event"]["cause"] == "no_snapshots" assert "reason=boundary_snapshot_unavailable" in caplog.text def test_prefix_lookup_observation_explains_reprefill_boundary( From 64e63cb7b00680a5964431ae30169bc4f83139be Mon Sep 17 00:00:00 2001 From: jundot Date: Sun, 30 Aug 2026 00:17:05 +0900 Subject: [PATCH 048/132] fix(admin): validate Lightning MTP draft depth (#3280) --- omlx/admin/routes.py | 12 +++++++++--- omlx/model_settings.py | 4 ++++ omlx/patches/mlx_lm_mtp/__init__.py | 4 +++- tests/test_admin_model_settings.py | 9 ++++----- 4 files changed, 20 insertions(+), 9 deletions(-) diff --git a/omlx/admin/routes.py b/omlx/admin/routes.py index bc4b52e07a..479b00e104 100644 --- a/omlx/admin/routes.py +++ b/omlx/admin/routes.py @@ -35,7 +35,10 @@ from ..api.utils import _try_parse_json from ..model_discovery import model_display_name as _model_display_name from ..model_profiles import EXCLUDED_FROM_PROFILES -from ..model_settings import merge_chat_template_kwargs +from ..model_settings import ( + MAX_LIGHTNING_MTP_DRAFT_TOKENS, + merge_chat_template_kwargs, +) from ..settings import BURST_DECODE_MODES, SubKeyEntry, burst_decode_env from ..utils.release_check import normalize_update_channel, select_latest_release from ..websearch import ( @@ -2368,10 +2371,13 @@ async def update_model_settings( ) if "mtp_num_draft_tokens" in sent: value = request.mtp_num_draft_tokens - if value is not None and value < 1: + if value is not None and not 1 <= value <= MAX_LIGHTNING_MTP_DRAFT_TOKENS: raise HTTPException( status_code=400, - detail="mtp_num_draft_tokens must be a positive integer (or null).", + detail=( + "mtp_num_draft_tokens must be between 1 and " + f"{MAX_LIGHTNING_MTP_DRAFT_TOKENS} (or null)." + ), ) current_settings.mtp_num_draft_tokens = value if "preserve_thinking" in sent: diff --git a/omlx/model_settings.py b/omlx/model_settings.py index 2edb0afa40..9280e09924 100644 --- a/omlx/model_settings.py +++ b/omlx/model_settings.py @@ -29,6 +29,10 @@ # Current settings file format version SETTINGS_VERSION = 1 +# The Lightning MTP runtime clamps deeper requests to this global ceiling. +# Keep API validation and runtime normalization on the same contract. +MAX_LIGHTNING_MTP_DRAFT_TOKENS = 8 + def vlm_mtp_processor_conflicts(data: dict) -> list: """Names of settings that need per-request logits processors and diff --git a/omlx/patches/mlx_lm_mtp/__init__.py b/omlx/patches/mlx_lm_mtp/__init__.py index 564148fae6..fa79e1ff0f 100644 --- a/omlx/patches/mlx_lm_mtp/__init__.py +++ b/omlx/patches/mlx_lm_mtp/__init__.py @@ -30,6 +30,8 @@ import logging +from ...model_settings import MAX_LIGHTNING_MTP_DRAFT_TOKENS + logger = logging.getLogger(__name__) # Process-wide construction flag read by the patched ``Model.__init__`` @@ -70,7 +72,7 @@ def is_mtp_active() -> bool: def set_mtp_depth(depth: int) -> None: global _MTP_DEPTH - _MTP_DEPTH = max(1, min(8, int(depth))) + _MTP_DEPTH = max(1, min(MAX_LIGHTNING_MTP_DRAFT_TOKENS, int(depth))) def get_mtp_depth() -> int: diff --git a/tests/test_admin_model_settings.py b/tests/test_admin_model_settings.py index d1d4310825..4ec2366d35 100644 --- a/tests/test_admin_model_settings.py +++ b/tests/test_admin_model_settings.py @@ -377,16 +377,15 @@ async def test_preserve_thinking_and_turboquant_skip_last_are_persisted(): @pytest.mark.asyncio -async def test_mtp_draft_tokens_rejects_non_positive_values(): +@pytest.mark.parametrize("value", [0, 9]) +async def test_mtp_draft_tokens_rejects_out_of_range_values(value): pool, _ = _failed_pool() - with pytest.raises( - admin_routes.HTTPException, match="must be a positive integer" - ): + with pytest.raises(admin_routes.HTTPException, match="must be between 1 and 8"): await _update_settings( pool, ModelSettings(), - admin_routes.ModelSettingsRequest(mtp_num_draft_tokens=0), + admin_routes.ModelSettingsRequest(mtp_num_draft_tokens=value), ) From 87066830cfc6d7bd367379614fc6c718cdaef5ab Mon Sep 17 00:00:00 2001 From: jundot Date: Sun, 30 Aug 2026 00:35:16 +0900 Subject: [PATCH 049/132] fix(cache): initialize boundary diagnostics in snapshot test --- tests/test_prefix_cache_cachelist_mixed.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/test_prefix_cache_cachelist_mixed.py b/tests/test_prefix_cache_cachelist_mixed.py index 29094f5f06..e09efcbbde 100644 --- a/tests/test_prefix_cache_cachelist_mixed.py +++ b/tests/test_prefix_cache_cachelist_mixed.py @@ -31,6 +31,7 @@ import pytest +from omlx.cache.observability import BoundarySnapshotDiagnostics from omlx.cache.paged_cache import BlockTable, PagedCacheManager from omlx.cache.paged_ssd_cache import PagedSSDCacheManager from omlx.cache.prefix_cache import BlockAwarePrefixCache @@ -314,6 +315,7 @@ def test_prefill_snapshot_decoupled_from_live_cache(): _cache_list_needs_boundary_snapshot=lambda cache: True, _boundary_cache_snapshots={}, _boundary_snapshot_store=None, + _boundary_snapshot_diagnostics=BoundarySnapshotDiagnostics(), _boundary_snapshot_required=False, _stream=mx.default_stream(mx.default_device()), _PREFILL_SNAPSHOT_MARKER=Scheduler._PREFILL_SNAPSHOT_MARKER, From 7467dce8df8030dbb17b79bcf7e2050e01db5df7 Mon Sep 17 00:00:00 2001 From: Jonathan Spangler Date: Sat, 29 Aug 2026 09:35:24 -0700 Subject: [PATCH 050/132] perf(qwen4): flatten exact QSA prefill and accelerate Lightning MTP (#3244) Adds exact QSA prefill/decode paths, resident PLE and projection optimizations, and Lightning MTP prefix-state restoration for Qwen4. Co-authored-by: Jonathan Spangler --- Formula/omlx.rb | 4 +- README.md | 2 +- benchmarks/bench_qwen4_qsa_sparse_gqa.py | 146 +++ omlx/cache/prefix_cache.py | 133 ++- omlx/custom_kernels/__init__.py | 8 +- .../backend/metal/kernels/steel/attn/params.h | 19 + omlx/custom_kernels/decode_fast/__init__.py | 6 + .../decode_fast/csrc/CMakeLists.txt | 63 ++ .../decode_fast/csrc/MLX_LICENSE.txt | 21 + .../decode_fast/csrc/bindings.cpp | 35 + .../decode_fast/csrc/sdpa_decode.cpp | 497 ++++++++++ .../decode_fast/csrc/sdpa_decode.h | 35 + .../decode_fast/csrc/sdpa_decode.metal | 51 + .../decode_fast/csrc/sdpa_decode_kernels.h | 602 ++++++++++++ omlx/custom_kernels/decode_fast/fast.py | 96 ++ .../glm_moe_dsa/csrc/CMakeLists.txt | 2 + .../glm_moe_dsa/csrc/MLX_LICENSE.txt | 21 + .../glm_moe_dsa/csrc/MLX_SERVE_LICENSE.txt | 31 + .../glm_moe_dsa/csrc/bindings.cpp | 27 + .../glm_moe_dsa/csrc/dsa_indexer.cpp | 251 +++++ .../glm_moe_dsa/csrc/dsa_indexer.h | 25 + .../glm_moe_dsa/csrc/dsa_indexer.metal | 26 +- .../csrc/kernels/steel_dsa_indexer_score.h | 182 +++- .../csrc/kernels/steel_qwen4_qsa_sparse_gqa.h | 322 ++++++ .../glm_moe_dsa/csrc/qwen4_qsa_sparse_gqa.cpp | 200 ++++ .../glm_moe_dsa/csrc/qwen4_qsa_sparse_gqa.h | 18 + .../csrc/qwen4_qsa_sparse_gqa.metal | 24 + omlx/custom_kernels/glm_moe_dsa/fast.py | 92 ++ omlx/models/vlm.py | 12 + omlx/patches/mlx_lm_mtp/prompt_priming.py | 382 +++++++- .../vendor/mlx_vlm/models/qwen4_exp/cache.py | 55 +- .../mlx_vlm/models/qwen4_exp/hc_projection.py | 420 ++++++++ .../mlx_vlm/models/qwen4_exp/language.py | 927 ++++++++++++++++-- .../mlx_vlm/models/qwen4_exp/qsa_fast.py | 697 +++++++++++++ .../mlx_vlm/models/qwen4_exp/qwen4_exp.py | 28 + .../vendor/mlx_vlm/models/qwen4_exp/vision.py | 85 ++ omlx/patches/qwen35_gdn_prework.py | 502 ++++++++++ omlx/scheduler.py | 36 +- pyproject.toml | 1 + setup.py | 4 + tests/test_decode_fast_sdpa.py | 52 + tests/test_mlx_vlm_qwen4_exp_compat.py | 362 +++++++ tests/test_mtp_prompt_priming.py | 198 ++++ tests/test_qwen35_gdn_prework.py | 337 ++++++- tests/test_qwen4_hc_projection.py | 191 ++++ tests/test_qwen4_qsa_decode_gather.py | 377 +++++++ tests/test_qwen4_qsa_incremental_cache.py | 230 +++++ tests/test_qwen4_qsa_native_indexer.py | 229 +++++ tests/test_qwen4_qsa_native_topk.py | 146 +++ tests/test_qwen4_qsa_sparse_gqa.py | 307 ++++++ tests/test_qwen4_vision_grid_compat.py | 74 ++ tests/test_scheduler.py | 23 + 52 files changed, 8493 insertions(+), 121 deletions(-) create mode 100644 benchmarks/bench_qwen4_qsa_sparse_gqa.py create mode 100644 omlx/custom_kernels/decode_fast/__init__.py create mode 100644 omlx/custom_kernels/decode_fast/csrc/CMakeLists.txt create mode 100644 omlx/custom_kernels/decode_fast/csrc/MLX_LICENSE.txt create mode 100644 omlx/custom_kernels/decode_fast/csrc/bindings.cpp create mode 100644 omlx/custom_kernels/decode_fast/csrc/sdpa_decode.cpp create mode 100644 omlx/custom_kernels/decode_fast/csrc/sdpa_decode.h create mode 100644 omlx/custom_kernels/decode_fast/csrc/sdpa_decode.metal create mode 100644 omlx/custom_kernels/decode_fast/csrc/sdpa_decode_kernels.h create mode 100644 omlx/custom_kernels/decode_fast/fast.py create mode 100644 omlx/custom_kernels/glm_moe_dsa/csrc/MLX_LICENSE.txt create mode 100644 omlx/custom_kernels/glm_moe_dsa/csrc/MLX_SERVE_LICENSE.txt create mode 100644 omlx/custom_kernels/glm_moe_dsa/csrc/kernels/steel_qwen4_qsa_sparse_gqa.h create mode 100644 omlx/custom_kernels/glm_moe_dsa/csrc/qwen4_qsa_sparse_gqa.cpp create mode 100644 omlx/custom_kernels/glm_moe_dsa/csrc/qwen4_qsa_sparse_gqa.h create mode 100644 omlx/custom_kernels/glm_moe_dsa/csrc/qwen4_qsa_sparse_gqa.metal create mode 100644 omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/hc_projection.py create mode 100644 omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/qsa_fast.py create mode 100644 tests/test_decode_fast_sdpa.py create mode 100644 tests/test_qwen4_hc_projection.py create mode 100644 tests/test_qwen4_qsa_decode_gather.py create mode 100644 tests/test_qwen4_qsa_incremental_cache.py create mode 100644 tests/test_qwen4_qsa_native_indexer.py create mode 100644 tests/test_qwen4_qsa_native_topk.py create mode 100644 tests/test_qwen4_qsa_sparse_gqa.py create mode 100644 tests/test_qwen4_vision_grid_compat.py diff --git a/Formula/omlx.rb b/Formula/omlx.rb index 46db2ab6e0..b618e83c5c 100644 --- a/Formula/omlx.rb +++ b/Formula/omlx.rb @@ -1,5 +1,5 @@ class Omlx < Formula - CUSTOM_KERNELS = %w[bonsai glm_moe_dsa minimax_m3 qwen35_prefill].freeze + CUSTOM_KERNELS = %w[bonsai decode_fast glm_moe_dsa minimax_m3 qwen35_prefill].freeze desc "LLM inference server optimized for Apple Silicon" homepage "https://github.com/jundot/omlx" @@ -10,7 +10,7 @@ class Omlx < Formula head "https://github.com/jundot/omlx.git", branch: "main" option "with-custom-kernel", - "Build native custom kernels for Bonsai, GLM-5.2, MiniMax M3 and Qwen3.5/3.6 acceleration" + "Build native custom kernels for Bonsai, GLM-5.2, MiniMax M3 and Qwen3.5/3.6/4 acceleration" option "with-grammar", "Install xgrammar for structured output (requires torch, ~2GB)" depends_on "rust" => :build diff --git a/README.md b/README.md index 10c14359d4..fff77a9242 100644 --- a/README.md +++ b/README.md @@ -435,5 +435,5 @@ Contributions are welcome! See [Contributing Guide](docs/CONTRIBUTING.md) for de - [mlx-embeddings](https://github.com/Blaizzy/mlx-embeddings) - Embedding model support for Apple Silicon - [dflash-mlx](https://github.com/bstnxbt/dflash-mlx) - Block diffusion speculative decoding on Apple Silicon - [MTPLX](https://github.com/youssofal/mtplx) - Lightning MTP's verify-shape Metal kernels are powered by MTPLX by Youssof Altoukhi, which also inspired the depth-k pipeline -- [mlx-serve](https://github.com/ddalcu/mlx-serve) - The fused GDN verify prework kernel is adapted from mlx-serve's port of the mlxfast-challenge qwen35_packed_gdn_prework kernel +- [mlx-serve](https://github.com/ddalcu/mlx-serve) - The fused GDN verify prework kernel is adapted from mlx-serve's port of the mlxfast-challenge qwen35_packed_gdn_prework kernel; Qwen4 QSA's 128-bit K/V staging is adapted from mlx-serve's MIT-licensed `msv_attn_p256` kernel - [SiliconScope](https://github.com/kennss/SiliconScope) - The menu bar statistics take their design and rendering approach from SiliconScope by Kennt Kim, which also inspired the energy-efficient re-render gating diff --git a/benchmarks/bench_qwen4_qsa_sparse_gqa.py b/benchmarks/bench_qwen4_qsa_sparse_gqa.py new file mode 100644 index 0000000000..c4e99ec627 --- /dev/null +++ b/benchmarks/bench_qwen4_qsa_sparse_gqa.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python3 +"""Benchmark Qwen4 direct-index sparse GQA against the gathered MLX path.""" + +# SPDX-License-Identifier: Apache-2.0 + +from __future__ import annotations + +import argparse +import statistics +import time + +import mlx.core as mx +import numpy as np + +from omlx.custom_kernels.glm_moe_dsa import fast +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 import qsa_fast # noqa: E402 + + +def _time(call, repetitions: int): + samples = [] + output = None + for _ in range(repetitions): + start = time.perf_counter() + output = call() + mx.eval(output) + mx.synchronize() + samples.append((time.perf_counter() - start) * 1000.0) + return samples, output + + +def _portable(queries, keys, values, selected, selected_valid): + query_tokens = queries.shape[2] + selected_keys = qsa_fast._batch_gather_tokens( + keys.transpose(0, 2, 1, 3), selected + ).transpose(0, 1, 3, 2, 4) + selected_values = qsa_fast._batch_gather_tokens( + values.transpose(0, 2, 1, 3), selected + ).transpose(0, 1, 3, 2, 4) + grouped_queries = queries.transpose(0, 2, 1, 3).reshape( + 1, query_tokens, 2, 12, 256 + ) + scores = ( + grouped_queries.astype(mx.float32) + @ selected_keys.astype(mx.float32).swapaxes(-1, -2) + ) / (256**0.5) + scores = mx.where( + selected_valid[:, :, None, None, :], + scores, + mx.finfo(scores.dtype).min, + ) + probabilities = mx.softmax(scores, axis=-1).astype(queries.dtype) + return (probabilities @ selected_values).reshape( + 1, query_tokens, 24, 256 + ) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--key-tokens", type=int, default=50_000) + parser.add_argument("--query-tokens", type=int, default=128) + parser.add_argument("--repetitions", type=int, default=10) + parser.add_argument("--seed", type=int, default=927) + args = parser.parse_args() + if not fast.is_native_available() or not fast.has_symbol( + "qwen4_qsa_sparse_gqa_attention" + ): + raise SystemExit("rebuild glm_moe_dsa with the Qwen4 sparse GQA ABI") + if args.key_tokens - args.query_tokens < 2048: + raise SystemExit("benchmark needs at least 2,048 visible prefix tokens") + + mx.random.seed(args.seed) + rng = np.random.default_rng(args.seed) + q_offset = args.key_tokens - args.query_tokens + queries = mx.random.normal((1, 24, args.query_tokens, 256)).astype(mx.bfloat16) + keys = mx.random.normal((1, 2, args.key_tokens, 256)).astype(mx.bfloat16) + values = mx.random.normal((1, 2, args.key_tokens, 256)).astype(mx.bfloat16) + blocks = [] + expanded = [] + expanded_valid = [] + for row in range(args.query_tokens): + complete = (q_offset + row + 1) // 4 + chosen = np.sort(rng.choice(complete, size=512, replace=False)).astype( + np.uint32 + ) + blocks.append(chosen) + tokens = (chosen[:, None] * 4 + np.arange(4, dtype=np.uint32)).reshape(-1) + tail_start = complete * 4 + tail = np.arange(tail_start, q_offset + row + 1, dtype=np.uint32) + expanded.append(np.pad(np.concatenate((tokens, tail)), (0, 3 - len(tail)))) + expanded_valid.append( + np.concatenate( + ( + np.ones(2048 + len(tail), dtype=np.bool_), + np.zeros(3 - len(tail), dtype=np.bool_), + ) + ) + ) + selected_blocks = mx.array(np.stack(blocks)[None]) + selected_tokens = mx.array(np.stack(expanded)[None]) + valid = mx.array(np.stack(expanded_valid)[None]) + selected_tokens = mx.where(valid, selected_tokens, 0) + mx.eval(queries, keys, values, selected_blocks, selected_tokens) + + reference = _portable(queries, keys, values, selected_tokens, valid) + mx.eval(reference) + for key_tile, dimension_tile in ((128, 32), (64, 64)): + def call(key_tile=key_tile, dimension_tile=dimension_tile): + return fast.qwen4_qsa_sparse_gqa_attention( + queries, + keys, + values, + selected_blocks[:, None], + 256**-0.5, + q_offset, + key_tile=key_tile, + dimension_tile=dimension_tile, + ) + + mx.eval(call()) + samples, native = _time(call, args.repetitions) + native_rows = native.transpose(0, 2, 1, 3) + error = mx.abs(native_rows.astype(mx.float32) - reference.astype(mx.float32)) + mx.eval(error) + print( + f"native BK={key_tile} DC={dimension_tile}: " + f"median={statistics.median(samples):.3f} ms " + f"min={min(samples):.3f} max={max(samples):.3f} " + f"max_error={float(mx.max(error).item()):.7f}" + ) + + samples, _ = _time( + lambda: _portable(queries, keys, values, selected_tokens, valid), + args.repetitions, + ) + print( + f"portable gathered: median={statistics.median(samples):.3f} ms " + f"min={min(samples):.3f} max={max(samples):.3f}" + ) + + +if __name__ == "__main__": + main() diff --git a/omlx/cache/prefix_cache.py b/omlx/cache/prefix_cache.py index 460e64cae4..ae2700e0fb 100644 --- a/omlx/cache/prefix_cache.py +++ b/omlx/cache/prefix_cache.py @@ -8,7 +8,9 @@ import logging import math +import threading import time +from collections import OrderedDict from collections.abc import Callable from dataclasses import dataclass from typing import Any @@ -98,6 +100,16 @@ def cachelist_pm_member_plan( # lineage map. _BACKFILL_CHECKED_MAX_ENTRIES = 4096 +# Lightning-MTP prompt priming has one small attention cache of its own. The +# normal prefix cache stores only the backbone cache, so a warm trunk restore +# used to lose the MTP history and restart speculative decode unprimed. Keep a +# deliberately tiny in-memory sidecar of full-block boundary snapshots. Four +# entries bounds the worst-case Qwen4 100K-context footprint to roughly the +# same order as one ordinary request cache while covering the recent branches +# of an interactive conversation. The entries are keyed by the *same* chain +# hash as the backbone block and are dropped with that block/hash lifecycle. +_MTP_PREFIX_SNAPSHOT_MAX_ENTRIES = 4 + def _wrap_cachelist_sub_marker( sub_idx: int, @@ -247,6 +259,16 @@ def __init__( # rewrite saved). Each hash is inspected at most once per run. self._backfill_checked_hashes: set[bytes] = set() + # Full-block Lightning-MTP prompt-history snapshots. Values are + # opaque to the generic prefix cache; prompt_priming owns their shape. + # Access can race with the asynchronous backbone store worker's hash + # callbacks, so use a private lock rather than relying on the GIL for + # the multi-step LRU operations. + self._mtp_prefix_snapshots: OrderedDict[bytes, tuple[int, Any]] = ( + OrderedDict() + ) + self._mtp_prefix_snapshot_lock = threading.RLock() + # Callback for restoring cold blocks (deprecated in paged SSD-only mode) # Kept for API compatibility self._cold_restore_callback: Callable[[int, bytes], bool] | None = None @@ -4757,10 +4779,113 @@ def _on_block_hash_dropped(self, block_hash: bytes) -> None: from any thread; it must not call back into the paged cache. """ self._prefix_index.pop(block_hash, None) + with self._mtp_prefix_snapshot_lock: + self._mtp_prefix_snapshots.pop(block_hash, None) def _on_hash_map_cleared(self) -> None: """Drop all prefix-index entries after a wholesale hash-map clear.""" self._prefix_index.clear() + with self._mtp_prefix_snapshot_lock: + self._mtp_prefix_snapshots.clear() + + def _mtp_prefix_chain_tip( + self, + tokens: list[int], + boundary_tokens: int, + *, + extra_keys: tuple[Any, ...] | None = None, + extra_key_token_start: int | None = None, + extra_key_ranges: list[tuple[int, tuple[Any, ...]]] | None = None, + ) -> bytes | None: + """Return the ordinary full-block chain hash for an MTP sidecar. + + VLM requests can change hidden states without changing token ids. The + generic prefix cache supports per-range media keys, but + ``compute_chain_hashes`` cannot reproduce that resolution from a lone + boundary snapshot. Fail closed for those two complex forms; text-only + requests and a single request-wide ``extra_keys`` tuple remain exact. + """ + boundary_tokens = int(boundary_tokens) + if ( + boundary_tokens <= 0 + or boundary_tokens > len(tokens) + or boundary_tokens % self.block_size != 0 + or extra_key_token_start is not None + or extra_key_ranges is not None + ): + return None + parent_hash: BlockHash | None = None + for start in range(0, boundary_tokens, self.block_size): + parent_hash = compute_block_hash( + parent_hash, + tokens[start : start + self.block_size], + extra_keys=extra_keys, + model_name=self.paged_cache.model_name, + ) + return parent_hash + + def store_mtp_prefix_snapshot( + self, + tokens: list[int], + boundary_tokens: int, + snapshot: Any, + *, + extra_keys: tuple[Any, ...] | None = None, + extra_key_token_start: int | None = None, + extra_key_ranges: list[tuple[int, tuple[Any, ...]]] | None = None, + ) -> bool: + """Keep an exact Lightning-MTP history at one backbone block boundary. + + This is intentionally memory-only. SSD persistence would require a + versioned serialization contract for every model family's MTP cache; + an unsupported or stale sidecar must merely fall back to unprimed MTP, + never make the target model consume an invented history. + """ + tip = self._mtp_prefix_chain_tip( + tokens, + boundary_tokens, + extra_keys=extra_keys, + extra_key_token_start=extra_key_token_start, + extra_key_ranges=extra_key_ranges, + ) + if tip is None or snapshot is None: + return False + with self._mtp_prefix_snapshot_lock: + self._mtp_prefix_snapshots[tip] = (int(boundary_tokens), snapshot) + self._mtp_prefix_snapshots.move_to_end(tip) + while len(self._mtp_prefix_snapshots) > _MTP_PREFIX_SNAPSHOT_MAX_ENTRIES: + self._mtp_prefix_snapshots.popitem(last=False) + return True + + def restore_mtp_prefix_snapshot( + self, + tokens: list[int], + boundary_tokens: int, + *, + extra_keys: tuple[Any, ...] | None = None, + extra_key_token_start: int | None = None, + extra_key_ranges: list[tuple[int, tuple[Any, ...]]] | None = None, + ) -> Any | None: + """Return the exact MTP sidecar matching a reconstructed trunk prefix.""" + tip = self._mtp_prefix_chain_tip( + tokens, + boundary_tokens, + extra_keys=extra_keys, + extra_key_token_start=extra_key_token_start, + extra_key_ranges=extra_key_ranges, + ) + if tip is None: + return None + # A snapshot published before completion is not reusable until the + # matching backbone block has actually been stored and remains live. + if self.paged_cache.cached_block_hash_to_block.get_block(tip) is None: + return None + with self._mtp_prefix_snapshot_lock: + entry = self._mtp_prefix_snapshots.get(tip) + if entry is None or entry[0] != int(boundary_tokens): + return None + self._mtp_prefix_snapshots.move_to_end(tip) + return entry[1] def get_stats(self) -> PrefixCacheStats: """ @@ -4858,9 +4983,15 @@ def clear(self) -> int: Returns: Number of entries cleared. """ - cleared_count = len(self._request_tables) + len(self._prefix_index) + with self._mtp_prefix_snapshot_lock: + mtp_snapshot_count = len(self._mtp_prefix_snapshots) + cleared_count = ( + len(self._request_tables) + len(self._prefix_index) + mtp_snapshot_count + ) self._request_tables.clear() self._prefix_index.clear() + with self._mtp_prefix_snapshot_lock: + self._mtp_prefix_snapshots.clear() self.paged_cache.clear() self.reset_stats() return cleared_count diff --git a/omlx/custom_kernels/__init__.py b/omlx/custom_kernels/__init__.py index 33ae183b3c..dfcfb6b402 100644 --- a/omlx/custom_kernels/__init__.py +++ b/omlx/custom_kernels/__init__.py @@ -5,7 +5,13 @@ import importlib -NATIVE_KERNEL_PACKAGES = ("bonsai", "glm_moe_dsa", "minimax_m3", "qwen35_prefill") +NATIVE_KERNEL_PACKAGES = ( + "bonsai", + "decode_fast", + "glm_moe_dsa", + "minimax_m3", + "qwen35_prefill", +) def native_kernel_status() -> dict[str, dict[str, object]]: diff --git a/omlx/custom_kernels/common/csrc/mlx/backend/metal/kernels/steel/attn/params.h b/omlx/custom_kernels/common/csrc/mlx/backend/metal/kernels/steel/attn/params.h index 4919496da4..7894276ae9 100644 --- a/omlx/custom_kernels/common/csrc/mlx/backend/metal/kernels/steel/attn/params.h +++ b/omlx/custom_kernels/common/csrc/mlx/backend/metal/kernels/steel/attn/params.h @@ -164,6 +164,25 @@ struct DeepseekV4SparseAttentionParams { int64_t O_strides[3]; ///< Output strides (B, H, L, D = 1) }; +struct Qwen4QSASparseGQAParams { + int B; ///< Batch size (the current native ABI fixes this to one) + int q_heads; ///< Main-attention query heads + int kv_heads; ///< Main-attention key/value heads + int qL; ///< Query rows in this prefill tile + int kL; ///< Full cached key/value rows + int topk; ///< Fixed-width selected four-token block list per query + int gqa_factor; ///< Query heads sharing one key/value head + int q_offset; ///< Absolute position of query row zero + + float scale; ///< Attention scale + + int64_t Q_strides[3]; ///< Query strides (B, H, L, D = 1) + int64_t K_strides[3]; ///< Key strides (B, Hkv, L, D = 1) + int64_t V_strides[3]; ///< Value strides (B, Hkv, L, D = 1) + int64_t Topk_strides[3]; ///< Selected-token strides (B, 1, L, topk = 1) + int64_t O_strides[3]; ///< Output strides (B, H, L, D = 1) +}; + struct AttnChunkReduceParams { int C; ///< Number of key chunks int H; ///< Heads diff --git a/omlx/custom_kernels/decode_fast/__init__.py b/omlx/custom_kernels/decode_fast/__init__.py new file mode 100644 index 0000000000..2e84841edb --- /dev/null +++ b/omlx/custom_kernels/decode_fast/__init__.py @@ -0,0 +1,6 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Optional exact decode SDPA kernel used by Qwen4 QSA.""" + +from .fast import NATIVE_AVAILABLE, sdpa_decode + +__all__ = ["NATIVE_AVAILABLE", "sdpa_decode"] diff --git a/omlx/custom_kernels/decode_fast/csrc/CMakeLists.txt b/omlx/custom_kernels/decode_fast/csrc/CMakeLists.txt new file mode 100644 index 0000000000..1aca23a68d --- /dev/null +++ b/omlx/custom_kernels/decode_fast/csrc/CMakeLists.txt @@ -0,0 +1,63 @@ +# SPDX-License-Identifier: Apache-2.0 +cmake_minimum_required(VERSION 3.27) +project(omlx_decode_fast_kernels LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_POSITION_INDEPENDENT_CODE ON) +option(BUILD_SHARED_LIBS "Build extensions as a shared library" ON) + +find_package(Python 3.8 COMPONENTS Interpreter Development.Module REQUIRED) +execute_process( + COMMAND "${Python_EXECUTABLE}" -m nanobind --cmake_dir + OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE nanobind_ROOT) +find_package(nanobind CONFIG REQUIRED) +execute_process( + COMMAND "${Python_EXECUTABLE}" -m mlx --cmake-dir + OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE MLX_ROOT) +find_package(MLX CONFIG REQUIRED) + +add_library(omlx_decode_fast_kernel_ops) +target_sources(omlx_decode_fast_kernel_ops PRIVATE + ${CMAKE_CURRENT_LIST_DIR}/sdpa_decode.cpp) +target_include_directories(omlx_decode_fast_kernel_ops PUBLIC + ${CMAKE_CURRENT_LIST_DIR}) +target_link_libraries(omlx_decode_fast_kernel_ops PUBLIC mlx) + +if(MLX_BUILD_METAL) + set(SDPA_METAL ${CMAKE_CURRENT_LIST_DIR}/sdpa_decode.metal) + set(SDPA_AIR ${CMAKE_CURRENT_BINARY_DIR}/sdpa_decode.air) + set(SDPA_METALLIB + ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/omlx_decode_fast_kernels.metallib) + set(SDPA_INCLUDE_ARGS -I${CMAKE_CURRENT_LIST_DIR}) + foreach(INCLUDE_DIR IN LISTS MLX_INCLUDE_DIRS) + list(APPEND SDPA_INCLUDE_ARGS -I${INCLUDE_DIR}) + endforeach() + set(SDPA_METAL_FLAGS -x metal -Wall -Wextra -fno-fast-math + -Wno-c++17-extensions -Wno-c++20-extensions) + if(NOT CMAKE_OSX_DEPLOYMENT_TARGET STREQUAL "") + list(APPEND SDPA_METAL_FLAGS + "-mmacosx-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET}") + endif() + add_custom_command( + OUTPUT ${SDPA_AIR} + COMMAND xcrun -sdk macosx metal ${SDPA_METAL_FLAGS} -c ${SDPA_METAL} + ${SDPA_INCLUDE_ARGS} -o ${SDPA_AIR} + DEPENDS ${SDPA_METAL} ${CMAKE_CURRENT_LIST_DIR}/sdpa_decode_kernels.h + VERBATIM) + add_custom_command( + OUTPUT ${SDPA_METALLIB} + COMMAND xcrun -sdk macosx metal ${SDPA_AIR} -o ${SDPA_METALLIB} + DEPENDS ${SDPA_AIR} VERBATIM) + add_custom_target(omlx_decode_fast_kernels_metallib DEPENDS ${SDPA_METALLIB}) + add_dependencies(omlx_decode_fast_kernel_ops + omlx_decode_fast_kernels_metallib) +endif() + +nanobind_add_module(_ext NB_STATIC STABLE_ABI LTO NOMINSIZE NB_DOMAIN mlx + ${CMAKE_CURRENT_LIST_DIR}/bindings.cpp) +target_link_libraries(_ext PRIVATE omlx_decode_fast_kernel_ops) +if(BUILD_SHARED_LIBS) + target_link_options(_ext PRIVATE -Wl,-rpath,@loader_path + -Wl,-rpath,@loader_path/../../../mlx/lib) +endif() diff --git a/omlx/custom_kernels/decode_fast/csrc/MLX_LICENSE.txt b/omlx/custom_kernels/decode_fast/csrc/MLX_LICENSE.txt new file mode 100644 index 0000000000..98ff47b9ef --- /dev/null +++ b/omlx/custom_kernels/decode_fast/csrc/MLX_LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright © 2023 Apple Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/omlx/custom_kernels/decode_fast/csrc/bindings.cpp b/omlx/custom_kernels/decode_fast/csrc/bindings.cpp new file mode 100644 index 0000000000..f587eb0697 --- /dev/null +++ b/omlx/custom_kernels/decode_fast/csrc/bindings.cpp @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: Apache-2.0 +#include +#include +#include + +#include "sdpa_decode.h" + +namespace nb = nanobind; +using namespace nb::literals; + +NB_MODULE(_ext, m) { + m.doc() = "Native exact decode SDPA for Qwen4 QSA"; + m.def( + "abi_probe", + [](const mlx::core::array& a) { return static_cast(a.size()); }, + "a"_a); + m.def( + "sdpa_decode_supported", + &omlx::decode_fast_kernels::sdpa_decode_supported, + "q"_a, + "k"_a, + "v"_a, + "stream"_a = nb::none()); + m.def( + "sdpa_decode", + &omlx::decode_fast_kernels::sdpa_decode, + "q"_a, + "k"_a, + "v"_a, + "scale"_a, + "causal"_a, + "mask"_a = nb::none(), + "sinks"_a = nb::none(), + "stream"_a = nb::none()); +} diff --git a/omlx/custom_kernels/decode_fast/csrc/sdpa_decode.cpp b/omlx/custom_kernels/decode_fast/csrc/sdpa_decode.cpp new file mode 100644 index 0000000000..9ce561505b --- /dev/null +++ b/omlx/custom_kernels/decode_fast/csrc/sdpa_decode.cpp @@ -0,0 +1,497 @@ +// SPDX-License-Identifier: Apache-2.0 +// Decode-mode SDPA (query length <= 8) using the omlx_sdpa_decode kernels: +// a port of ml-explore/mlx#4294 (closed unmerged upstream) — tiled online +// softmax, vectorized KV loads, context-scaled 2-pass split on 'd'-class +// GPUs, fp32 partials. Host dispatch mirrors mlx's +// scaled_dot_product_attention.cpp vector paths, with kernel names and the +// metallib swapped for the omlx ones. +// +// Layout contract matches the other decode_fast ops: realized inputs must +// satisfy the stride predicates below (KV caches and decode-time queries in +// omlx always do). A misaligned realized input is a hard error, since +// neither a nested eval nor an immediate contiguous copy is legal inside +// eval_gpu; use the mx.fast fallback for exotic layouts. + +#include "sdpa_decode.h" + +#include +#include +#include +#include +#include +#include + +#include "mlx/allocator.h" +#include "mlx/backend/common/utils.h" +#include "mlx/backend/metal/device.h" +#include "mlx/backend/metal/metal.h" +#include "mlx/backend/metal/utils.h" +#include "mlx/primitives.h" +#include "mlx/utils.h" + +namespace omlx::decode_fast_kernels { + +namespace { + +using namespace mlx::core; + +std::string sdpa_type_name(Dtype dtype) { + if (dtype == float32) { + return "float"; + } + if (dtype == float16) { + return "float16_t"; + } + if (dtype == bfloat16) { + return "bfloat16_t"; + } + std::ostringstream msg; + msg << "Unsupported sdpa_decode dtype: " << dtype << "."; + throw std::invalid_argument(msg.str()); +} + +std::string current_binary_dir_sdpa() { + static std::string binary_dir = []() { + Dl_info info; + if (!dladdr(reinterpret_cast(¤t_binary_dir_sdpa), &info)) { + throw std::runtime_error("Unable to get omlx_decode_fast binary dir."); + } + return std::filesystem::path(info.dli_fname).parent_path().string(); + }(); + return binary_dir; +} + +// Layout predicates mirrored from ScaledDotProductAttention::eval_gpu. +bool q_layout_ok(const array& arr) { + if (arr.flags().row_contiguous) { + return true; + } + auto& strides = arr.strides(); + auto& shape = arr.shape(); + if (shape[0] == 1 || shape[1] == 1) { + auto bidx = shape[0] == 1 ? 1 : 0; + return (strides[3] == 1) && (strides[2] == shape[3] * shape[bidx]) && + (strides[bidx] == shape[3]); + } + return false; +} + +bool kv_layout_ok(const array& arr) { + auto& strides = arr.strides(); + auto& shape = arr.shape(); + if (strides.back() != 1) { + return false; + } + auto per_thread = shape[3] / 32; + if ((shape[2] > 1 && strides[2] % per_thread != 0) || + (shape[1] > 1 && strides[1] % per_thread != 0)) { + return false; + } + if (shape[0] == 1 || shape[1] == 1) { + return true; + } + return (strides[0] == strides[1] * shape[1]); +} + +void sdpa_decode_1pass( + const Stream& s, + metal::Device& d, + MTL::Library* lib, + const array& q, + const array& k, + const array& v, + array& out, + float scale, + bool do_causal, + const std::optional& mask, + const std::optional& sinks) { + std::string kname; + kname.reserve(64); + concatenate( + kname, + "omlx_sdpa_decode_", + sdpa_type_name(q.dtype()), + "_", + q.shape(-1), + "_", + v.shape(-1)); + + int gqa_factor = q.shape(1) / k.shape(1); + int N = k.shape(2); + size_t k_head_stride = k.shape(1) == 1 ? k.strides(0) : k.strides(1); + size_t k_seq_stride = k.strides()[2]; + size_t v_head_stride = v.shape(1) == 1 ? v.strides(0) : v.strides(1); + size_t v_seq_stride = v.strides()[2]; + + MTL::Size group_dims(1024, 1, 1); + MTL::Size grid_dims(q.shape(0) * q.shape(1), q.shape(2), 1); + + bool has_mask = mask.has_value(); + bool bool_mask = has_mask && (*mask).dtype() == bool_; + bool float_mask = has_mask && !bool_mask; + bool query_transposed = !q.flags().row_contiguous; + bool has_sinks = sinks.has_value(); + metal::MTLFCList func_consts = { + {&has_mask, MTL::DataType::DataTypeBool, 20}, + {&query_transposed, MTL::DataType::DataTypeBool, 21}, + {&do_causal, MTL::DataType::DataTypeBool, 22}, + {&bool_mask, MTL::DataType::DataTypeBool, 23}, + {&float_mask, MTL::DataType::DataTypeBool, 24}, + {&has_sinks, MTL::DataType::DataTypeBool, 25}, + }; + std::string hash_name = kname; + hash_name += has_mask ? (bool_mask ? "_boolmask" : "_floatmask") : "_nomask"; + hash_name += query_transposed ? "_qt" : "_qnt"; + hash_name += do_causal ? "_c" : "_nc"; + hash_name += has_sinks ? "_sinks" : "_nosinks"; + + auto& compute_encoder = metal::get_command_encoder(s); + auto kernel = d.get_kernel(kname, lib, hash_name, func_consts); + compute_encoder.set_compute_pipeline_state(kernel); + + compute_encoder.set_input_array(q, 0); + compute_encoder.set_input_array(k, 1); + compute_encoder.set_input_array(v, 2); + compute_encoder.set_output_array(out, 3); + compute_encoder.set_bytes(gqa_factor, 4); + compute_encoder.set_bytes(N, 5); + compute_encoder.set_bytes(k_head_stride, 6); + compute_encoder.set_bytes(k_seq_stride, 7); + compute_encoder.set_bytes(v_head_stride, 8); + compute_encoder.set_bytes(v_seq_stride, 9); + compute_encoder.set_bytes(scale, 10); + if (has_mask) { + auto& m = *mask; + compute_encoder.set_input_array(m, 11 + float_mask); + int32_t kv_seq_stride = m.shape(3) > 1 ? m.strides(3) : 0; + int32_t q_seq_stride = m.shape(2) > 1 ? m.strides(2) : 0; + int32_t head_stride = + m.shape(1) > 1 ? m.strides(1) : (m.shape(0) > 1 ? m.strides(0) : 0); + compute_encoder.set_bytes(kv_seq_stride, 13); + compute_encoder.set_bytes(q_seq_stride, 14); + compute_encoder.set_bytes(head_stride, 15); + } + if (has_sinks) { + compute_encoder.set_input_array(*sinks, 16); + compute_encoder.set_bytes(q.shape(1), 17); + } + + compute_encoder.dispatch_threadgroups(grid_dims, group_dims); +} + +void sdpa_decode_2pass( + const Stream& s, + metal::Device& d, + MTL::Library* lib, + const array& q, + const array& k, + const array& v, + array& out, + float scale, + bool do_causal, + const std::optional& mask, + const std::optional& sinks) { + std::string kname; + kname.reserve(64); + concatenate( + kname, + "omlx_sdpa_decode_2pass_1_", + sdpa_type_name(q.dtype()), + "_", + q.shape(-1), + "_", + v.shape(-1)); + + int gqa_factor = q.shape(1) / k.shape(1); + int n_simds = gqa_factor * q.shape(2); + + char devc = d.get_architecture().back(); + int N = k.shape(2); + int blocks; + if (devc == 's') { + blocks = 64; + if (N > 1024 && n_simds > 4) { + if (N <= 8192) { + blocks = 128; + } else if (N <= 32768) { + blocks = 256; + } else if (N <= 65536) { + blocks = 512; + } else { + blocks = 1024; + } + } + } else if (devc == 'd') { + // Split the KV sequence so that each threadgroup processes a contiguous + // chunk of ~256 keys, while keeping at least 32-64 blocks for parallelism + // and capping at 256 to bound the partials traffic. Tuned on M3 Ultra. + int b = (((N + 255) / 256 + 31) / 32) * 32; + blocks = std::min(256, std::max(N >= 4096 ? 64 : 32, b)); + } else { + if (n_simds >= 4) { + blocks = 64; + } else { + blocks = 32; + } + } + + size_t k_head_stride = k.shape(1) == 1 ? k.strides(0) : k.strides(1); + size_t k_seq_stride = k.strides()[2]; + size_t v_head_stride = v.shape(1) == 1 ? v.strides(0) : v.strides(1); + size_t v_seq_stride = v.strides()[2]; + MTL::Size group_dims(32, gqa_factor, q.shape(2)); + MTL::Size grid_dims(k.shape(1), q.shape(0), blocks); + + // Partials in float32 for accuracy (PR #4294); tiny vs the KV read. + Shape intermediate_shape; + intermediate_shape.reserve(out.ndim() + 1); + intermediate_shape.insert( + intermediate_shape.end(), out.shape().begin(), out.shape().end() - 1); + intermediate_shape.push_back(blocks); + intermediate_shape.push_back(out.shape().back()); + array intermediate(intermediate_shape, float32, nullptr, {}); + intermediate_shape.pop_back(); + array sums(intermediate_shape, float32, nullptr, {}); + array maxs(std::move(intermediate_shape), float32, nullptr, {}); + intermediate.set_data(allocator::malloc(intermediate.nbytes())); + sums.set_data(allocator::malloc(sums.nbytes())); + maxs.set_data(allocator::malloc(maxs.nbytes())); + auto& compute_encoder = metal::get_command_encoder(s); + compute_encoder.add_temporary(intermediate); + compute_encoder.add_temporary(sums); + compute_encoder.add_temporary(maxs); + + bool has_mask = mask.has_value(); + bool bool_mask = has_mask && (*mask).dtype() == bool_; + bool float_mask = has_mask && !bool_mask; + bool query_transposed = !q.flags().row_contiguous; + bool has_sinks = sinks.has_value(); + metal::MTLFCList func_consts = { + {&has_mask, MTL::DataType::DataTypeBool, 20}, + {&query_transposed, MTL::DataType::DataTypeBool, 21}, + {&do_causal, MTL::DataType::DataTypeBool, 22}, + {&bool_mask, MTL::DataType::DataTypeBool, 23}, + {&float_mask, MTL::DataType::DataTypeBool, 24}, + {&has_sinks, MTL::DataType::DataTypeBool, 25}, + {&blocks, MTL::DataType::DataTypeInt, 26}, + }; + std::string hash_name = kname; + hash_name += has_mask ? (bool_mask ? "_boolmask" : "_floatmask") : "_nomask"; + hash_name += query_transposed ? "_qt" : "_qnt"; + hash_name += do_causal ? "_c" : "_nc"; + hash_name += has_sinks ? "_sinks_" : "_nosinks_"; + hash_name += std::to_string(blocks); + + auto kernel = d.get_kernel(kname, lib, hash_name, func_consts); + compute_encoder.set_compute_pipeline_state(kernel); + + compute_encoder.set_input_array(q, 0); + compute_encoder.set_input_array(k, 1); + compute_encoder.set_input_array(v, 2); + compute_encoder.set_output_array(intermediate, 3); + compute_encoder.set_output_array(sums, 4); + compute_encoder.set_output_array(maxs, 5); + compute_encoder.set_bytes(N, 7); + compute_encoder.set_bytes(k_head_stride, 8); + compute_encoder.set_bytes(k_seq_stride, 9); + compute_encoder.set_bytes(v_head_stride, 10); + compute_encoder.set_bytes(v_seq_stride, 11); + compute_encoder.set_bytes(scale, 12); + if (has_mask) { + auto& m = *mask; + compute_encoder.set_input_array(m, 13 + float_mask); + int32_t kv_seq_stride = m.shape(3) > 1 ? m.strides(3) : 0; + int32_t q_seq_stride = m.shape(2) > 1 ? m.strides(2) : 0; + int32_t head_stride = + m.shape(1) > 1 ? m.strides(1) : (m.shape(0) > 1 ? m.strides(0) : 0); + compute_encoder.set_bytes(kv_seq_stride, 15); + compute_encoder.set_bytes(q_seq_stride, 16); + compute_encoder.set_bytes(head_stride, 17); + } + if (has_sinks) { + compute_encoder.set_input_array(*sinks, 18); + } + + compute_encoder.dispatch_threadgroups(grid_dims, group_dims); + + // Final reduction pass. + kname.clear(); + concatenate( + kname, + "omlx_sdpa_decode_2pass_2_", + sdpa_type_name(q.dtype()), + "_", + v.shape(-1)); + + kernel = d.get_kernel(kname, lib); + compute_encoder.set_compute_pipeline_state(kernel); + + compute_encoder.set_input_array(intermediate, 0); + compute_encoder.set_input_array(sums, 1); + compute_encoder.set_input_array(maxs, 2); + compute_encoder.set_output_array(out, 3); + compute_encoder.set_bytes(blocks, 4); + + group_dims = MTL::Size(1024, 1, 1); + grid_dims = MTL::Size(q.shape(0) * q.shape(1), q.shape(2), 1); + compute_encoder.dispatch_threadgroups(grid_dims, group_dims); +} + +class SdpaDecodePrimitive : public Primitive { + public: + SdpaDecodePrimitive(Stream stream, float scale, bool do_causal) + : Primitive(stream), scale_(scale), do_causal_(do_causal) {} + + void eval_cpu( + const std::vector& /* inputs */, + std::vector& /* outputs */) override { + throw std::runtime_error("SdpaDecodePrimitive has no CPU path."); + } + + void eval_gpu( + const std::vector& inputs, + std::vector& outputs) override { + auto& s = stream(); + auto& d = metal::device(s.device); + + auto& q = inputs[0]; + auto& k = inputs[1]; + auto& v = inputs[2]; + auto& o = outputs[0]; + + std::optional sinks = std::nullopt; + std::optional mask = std::nullopt; + if (has_sinks_) { + sinks = inputs[3]; + if (inputs.size() > 4) { + mask = inputs[4]; + } + } else if (inputs.size() > 3) { + mask = inputs[3]; + } + + if (!q_layout_ok(q) || !kv_layout_ok(k) || !kv_layout_ok(v) || + (mask && !(*mask).flags().row_contiguous && + !(q.shape(0) == 1 || q.shape(1) == 1 || + (*mask).strides(0) == (*mask).strides(1) * (*mask).shape(1))) || + (sinks && (*sinks).strides(-1) != 1)) { + throw std::runtime_error( + "[omlx_decode_fast.sdpa_decode] realized input layout is not " + "compatible with the vectorized decode kernels; use " + "mx.fast.scaled_dot_product_attention for this layout."); + } + + o.set_data(allocator::malloc(o.nbytes())); + + bool do_causal = do_causal_ && q.shape(2) > 1; + char devc = d.get_architecture().back(); + bool gqa = k.shape(1) < q.shape(1); + bool use_2pass; + if (devc == 'd') { + use_2pass = gqa ? (k.shape(2) >= 1024) : (k.shape(2) >= 32768); + } else { + use_2pass = + (devc == 's' && k.shape(2) >= 1024) || (gqa && k.shape(2) >= 4096); + } + + auto lib = d.get_library( + "omlx_decode_fast_kernels", current_binary_dir_sdpa()); + if (use_2pass) { + sdpa_decode_2pass( + s, d, lib, q, k, v, o, scale_, do_causal, mask, sinks); + } else { + sdpa_decode_1pass(s, d, lib, q, k, v, o, scale_, do_causal, mask, sinks); + } + } + + DEFINE_NAME(OMLXSdpaDecode) + + bool is_equivalent(const Primitive& other) const override { + const auto& rhs = static_cast(other); + return scale_ == rhs.scale_ && do_causal_ == rhs.do_causal_ && + has_sinks_ == rhs.has_sinks_; + } + + bool has_sinks_ = false; + + private: + float scale_; + bool do_causal_; +}; + +} // namespace + +bool sdpa_decode_supported( + const mx::array& q, + const mx::array& k, + const mx::array& v, + mx::StreamOrDevice s_) { + auto s = to_stream(s_); + if (s.device == Device::cpu) { + return false; + } + if (q.ndim() != 4 || k.ndim() != 4 || v.ndim() != 4) { + return false; + } + auto t = q.dtype(); + if (t != float32 && t != float16 && t != bfloat16) { + return false; + } + if (k.dtype() != t || v.dtype() != t) { + return false; + } + const int qk_dim = q.shape(-1); + const int v_dim = v.shape(-1); + const bool head_dim_ok = + (qk_dim == v_dim && + (qk_dim == 64 || qk_dim == 96 || qk_dim == 128 || qk_dim == 256)) || + (qk_dim == 192 && v_dim == 128); + if (!head_dim_ok || k.shape(-1) != qk_dim) { + return false; + } + const int qL = q.shape(2); + const int kL = k.shape(2); + if (qL < 1 || qL > 8 || qL > kL) { + return false; + } + if (k.shape(0) != q.shape(0) || v.shape(0) != q.shape(0) || + v.shape(1) != k.shape(1) || v.shape(2) != kL) { + return false; + } + const int gqa_factor = q.shape(1) / k.shape(1); + if (q.shape(1) % k.shape(1) != 0 || qL * gqa_factor > 32) { + return false; + } + return true; +} + +mx::array sdpa_decode( + const mx::array& q, + const mx::array& k, + const mx::array& v, + float scale, + bool causal, + const std::optional& mask, + const std::optional& sinks, + mx::StreamOrDevice s_) { + if (!sdpa_decode_supported(q, k, v, s_)) { + throw std::invalid_argument( + "[omlx_decode_fast.sdpa_decode] unsupported shapes/dtypes for the " + "decode kernels."); + } + auto s = to_stream(s_); + std::vector inputs = {q, k, v}; + auto primitive = std::make_shared(s, scale, causal); + if (sinks.has_value()) { + primitive->has_sinks_ = true; + inputs.push_back(*sinks); + } + if (mask.has_value()) { + inputs.push_back(*mask); + } + Shape out_shape{q.shape(0), q.shape(1), q.shape(2), v.shape(-1)}; + return array( + std::move(out_shape), q.dtype(), std::move(primitive), std::move(inputs)); +} + +} // namespace omlx::decode_fast_kernels diff --git a/omlx/custom_kernels/decode_fast/csrc/sdpa_decode.h b/omlx/custom_kernels/decode_fast/csrc/sdpa_decode.h new file mode 100644 index 0000000000..8038732b58 --- /dev/null +++ b/omlx/custom_kernels/decode_fast/csrc/sdpa_decode.h @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +#include + +#include "mlx/array.h" +#include "mlx/stream.h" +#include "mlx/utils.h" + +namespace mx = mlx::core; + +namespace omlx::decode_fast_kernels { + +// True when the decode SDPA kernels apply: Metal stream, 4-D fp32/fp16/bf16 +// q/k/v, query length <= 8, supported head dims, GQA fan-out within limits. +bool sdpa_decode_supported( + const mx::array& q, + const mx::array& k, + const mx::array& v, + mx::StreamOrDevice s = {}); + +// Decode-mode scaled dot product attention (port of mlx#4294). Returns an +// array of shape (B, H, qL, v_head_dim). Optional mask (broadcastable to +// (B, H, qL, kL), bool or q's dtype) and attention sinks (per query head). +mx::array sdpa_decode( + const mx::array& q, + const mx::array& k, + const mx::array& v, + float scale, + bool causal, + const std::optional& mask = std::nullopt, + const std::optional& sinks = std::nullopt, + mx::StreamOrDevice s = {}); + +} // namespace omlx::decode_fast_kernels diff --git a/omlx/custom_kernels/decode_fast/csrc/sdpa_decode.metal b/omlx/custom_kernels/decode_fast/csrc/sdpa_decode.metal new file mode 100644 index 0000000000..e51da85550 --- /dev/null +++ b/omlx/custom_kernels/decode_fast/csrc/sdpa_decode.metal @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: Apache-2.0 +// omlx decode SDPA (vector) kernels — port of ml-explore/mlx#4295's sibling +// PR #4294 (closed unmerged upstream): tiled online softmax, vectorized KV +// loads, context-scaled 2-pass split for 'd'-class GPUs, fp32 partials. +// Kernel bodies live in sdpa_decode_kernels.h (omlx_sdpa_decode*, renamed to +// stay collision-free with mlx's own sdpa_vector kernels). + +#include + +// clang-format off +#include "mlx/backend/metal/kernels/utils.h" +#include "sdpa_decode_kernels.h" + +using namespace metal; + +#define instantiate_omlx_sdpa_decode_aggregation(type, value_dim) \ + instantiate_kernel( \ + "omlx_sdpa_decode_2pass_2_" #type "_" #value_dim, \ + omlx_sdpa_decode_2pass_2, \ + type, \ + value_dim) + +#define instantiate_omlx_sdpa_decode(type, qk_dim, value_dim) \ + instantiate_kernel( \ + "omlx_sdpa_decode_" #type "_" #qk_dim "_" #value_dim, \ + omlx_sdpa_decode, \ + type, \ + qk_dim, \ + value_dim) \ + instantiate_kernel( \ + "omlx_sdpa_decode_2pass_1_" #type "_" #qk_dim "_" #value_dim, \ + omlx_sdpa_decode_2pass_1, \ + type, \ + qk_dim, \ + value_dim) + +#define instantiate_omlx_sdpa_decode_heads(type) \ + instantiate_omlx_sdpa_decode(type, 64, 64) \ + instantiate_omlx_sdpa_decode(type, 96, 96) \ + instantiate_omlx_sdpa_decode(type, 128, 128) \ + instantiate_omlx_sdpa_decode(type, 192, 128) \ + instantiate_omlx_sdpa_decode(type, 256, 256) \ + instantiate_omlx_sdpa_decode_aggregation(type, 64) \ + instantiate_omlx_sdpa_decode_aggregation(type, 96) \ + instantiate_omlx_sdpa_decode_aggregation(type, 128) \ + instantiate_omlx_sdpa_decode_aggregation(type, 256) + +instantiate_omlx_sdpa_decode_heads(float) +instantiate_omlx_sdpa_decode_heads(bfloat16_t) +instantiate_omlx_sdpa_decode_heads(float16_t) +// clang-format on diff --git a/omlx/custom_kernels/decode_fast/csrc/sdpa_decode_kernels.h b/omlx/custom_kernels/decode_fast/csrc/sdpa_decode_kernels.h new file mode 100644 index 0000000000..04e2ee0a99 --- /dev/null +++ b/omlx/custom_kernels/decode_fast/csrc/sdpa_decode_kernels.h @@ -0,0 +1,602 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright © 2024 Apple Inc. + +#include + +using namespace metal; + +constant bool has_mask [[function_constant(20)]]; +constant bool query_transposed [[function_constant(21)]]; +constant bool do_causal [[function_constant(22)]]; +constant bool bool_mask [[function_constant(23)]]; +constant bool float_mask [[function_constant(24)]]; +constant bool has_sinks [[function_constant(25)]]; +constant int blocks [[function_constant(26)]]; + +// Load N contiguous elements of type T with as few (and as wide) loads as +// possible. The address must be aligned to N * sizeof(T) bytes (capped at 16 +// byte transactions), which the caller guarantees via the stride checks in +// scaled_dot_product_attention.cpp. +template +inline void load_vec(thread T (&dst)[N], const device T* p) { + if constexpr (N == 2 || N == 4) { + *reinterpret_cast*>(dst) = + *reinterpret_cast*>(p); + } else if constexpr (N == 8 && sizeof(T) == 2) { + *reinterpret_cast*>(dst) = + *reinterpret_cast*>(p); + } else if constexpr (N == 8) { + *reinterpret_cast*>(dst) = + *reinterpret_cast*>(p); + *reinterpret_cast*>(dst + 4) = + *reinterpret_cast*>(p + 4); + } else { +#pragma unroll + for (int i = 0; i < N; i++) { + dst[i] = p[i]; + } + } +} + +template +[[kernel]] void omlx_sdpa_decode( + const device T* queries [[buffer(0)]], + const device T* keys [[buffer(1)]], + const device T* values [[buffer(2)]], + device T* out [[buffer(3)]], + const constant int& gqa_factor [[buffer(4)]], + const constant int& N [[buffer(5)]], + const constant size_t& k_head_stride [[buffer(6)]], + const constant size_t& k_seq_stride [[buffer(7)]], + const constant size_t& v_head_stride [[buffer(8)]], + const constant size_t& v_seq_stride [[buffer(9)]], + const constant float& scale [[buffer(10)]], + const device bool* bmask [[buffer(11), function_constant(bool_mask)]], + const device T* fmask [[buffer(12), function_constant(float_mask)]], + const constant int& mask_kv_seq_stride + [[buffer(13), function_constant(has_mask)]], + const constant int& mask_q_seq_stride + [[buffer(14), function_constant(has_mask)]], + const constant int& mask_head_stride + [[buffer(15), function_constant(has_mask)]], + const device T* sinks [[buffer(16), function_constant(has_sinks)]], + const constant int& num_q_heads + [[buffer(17), function_constant(has_sinks)]], + uint3 tid [[threadgroup_position_in_grid]], + uint3 tpg [[threadgroups_per_grid]], + uint simd_gid [[simdgroup_index_in_threadgroup]], + uint simd_lid [[thread_index_in_simdgroup]]) { + constexpr int BN = 32; + constexpr int BD = 32; + // Keys are processed in tiles of TK so the online softmax update (max, exp + // and rescale of the accumulator) happens once per tile instead of per key. + constexpr int TK = 4; + constexpr int qk_per_thread = D / BD; + constexpr int v_per_thread = V / BD; + int inner_k_stride = BN * TK * int(k_seq_stride); + int inner_v_stride = BN * TK * int(v_seq_stride); + + typedef float U; + + thread U q[qk_per_thread]; + thread U o[v_per_thread]; + + threadgroup U outputs[BN * BD]; + threadgroup U max_scores[BN]; + threadgroup U sum_exp_scores[BN]; + + // Adjust positions + const int q_batch_head_idx = tid.x; + const int q_seq_idx = tid.y; + const int kv_head_idx = q_batch_head_idx / gqa_factor; + const int o_offset = q_batch_head_idx * tpg.y + q_seq_idx; + const int q_offset = + query_transposed ? tpg.x * q_seq_idx + q_batch_head_idx : o_offset; + queries += q_offset * D + simd_lid * qk_per_thread; + keys += kv_head_idx * k_head_stride + simd_gid * TK * k_seq_stride + + simd_lid * qk_per_thread; + values += kv_head_idx * v_head_stride + simd_gid * TK * v_seq_stride + + simd_lid * v_per_thread; + if (bool_mask) { + bmask += q_batch_head_idx * mask_head_stride + + simd_gid * TK * mask_kv_seq_stride + q_seq_idx * mask_q_seq_stride; + } + if (float_mask) { + fmask += q_batch_head_idx * mask_head_stride + + simd_gid * TK * mask_kv_seq_stride + q_seq_idx * mask_q_seq_stride; + } + + out += o_offset * V + simd_gid * v_per_thread; + + // Read the query and 0 the output accumulator + { + thread T qt[qk_per_thread]; + load_vec(qt, queries); + for (int i = 0; i < qk_per_thread; i++) { + q[i] = static_cast(scale) * static_cast(qt[i]); + } + } + for (int i = 0; i < v_per_thread; i++) { + o[i] = 0; + } + + U max_score = Limits::finite_min; + U sum_exp_score = 0; + if (has_sinks && simd_gid == 0) { + max_score = static_cast(sinks[q_batch_head_idx % num_q_heads]); + sum_exp_score = 1; + } + + // For each tile of TK keys + int i = simd_gid * TK; + for (; i + TK <= N; i += BN * TK) { + // Read the keys and compute the scores + thread T ks[TK][qk_per_thread]; + U scores[TK]; + bool use_key[TK]; +#pragma unroll + for (int t = 0; t < TK; t++) { + load_vec(ks[t], keys + t * int(k_seq_stride)); + } +#pragma unroll + for (int t = 0; t < TK; t++) { + U score = 0; + for (int j = 0; j < qk_per_thread; j++) { + score += q[j] * static_cast(ks[t][j]); + } + score = simd_sum(score); + + use_key[t] = true; + if (do_causal) { + use_key[t] = i + t <= (N - int(tpg.y) + int(q_seq_idx)); + } else if (bool_mask) { + use_key[t] = bmask[t * mask_kv_seq_stride]; + } else if (float_mask) { + use_key[t] = fmask[t * mask_kv_seq_stride] >= Limits::finite_min; + } + if (use_key[t] && float_mask) { + score += static_cast(fmask[t * mask_kv_seq_stride]); + } + scores[t] = use_key[t] ? score : Limits::finite_min; + } + + U tile_max = scores[0]; +#pragma unroll + for (int t = 1; t < TK; t++) { + tile_max = max(tile_max, scores[t]); + } + U new_max = max(max_score, tile_max); + + // Read the values + thread T vs[TK][v_per_thread]; +#pragma unroll + for (int t = 0; t < TK; t++) { + load_vec(vs[t], values + t * int(v_seq_stride)); + } + + // Rescale the accumulators only when the running max actually increased + if (new_max > max_score) { + U factor = fast::exp(max_score - new_max); + sum_exp_score *= factor; + for (int j = 0; j < v_per_thread; j++) { + o[j] *= factor; + } + max_score = new_max; + } + + // Update the accumulators +#pragma unroll + for (int t = 0; t < TK; t++) { + U p = use_key[t] ? fast::exp(scores[t] - max_score) : U(0); + sum_exp_score += p; +#pragma unroll + for (int j = 0; j < v_per_thread; j++) { + o[j] += p * static_cast(vs[t][j]); + } + } + + // Move the pointers to the next tile + keys += inner_k_stride; + values += inner_v_stride; + if (bool_mask) { + bmask += BN * TK * mask_kv_seq_stride; + } + if (float_mask) { + fmask += BN * TK * mask_kv_seq_stride; + } + } + + // Process the remaining keys of the last partial tile + const int tail_end = min(N, i + TK); + for (; i < tail_end; i++) { + bool use_key = true; + if (do_causal) { + use_key = i <= (N - int(tpg.y) + int(q_seq_idx)); + } else if (bool_mask) { + use_key = bmask[0]; + } else if (float_mask) { + use_key = (fmask[0] >= Limits::finite_min); + } + if (use_key) { + // Read the key + thread T k[qk_per_thread]; + load_vec(k, keys); + + // Compute the i-th score + U score = 0; + for (int j = 0; j < qk_per_thread; j++) { + score += q[j] * static_cast(k[j]); + } + score = simd_sum(score); + if (float_mask) { + score += static_cast(fmask[0]); + } + + // Update the accumulators + U new_max = max(max_score, score); + U factor = fast::exp(max_score - new_max); + U exp_score = fast::exp(score - new_max); + + max_score = new_max; + sum_exp_score = sum_exp_score * factor + exp_score; + + // Update the output accumulator + thread T vt[v_per_thread]; + load_vec(vt, values); + for (int j = 0; j < v_per_thread; j++) { + o[j] = o[j] * factor + exp_score * static_cast(vt[j]); + } + } + + // Move the pointers to the next kv + keys += int(k_seq_stride); + values += int(v_seq_stride); + if (bool_mask) { + bmask += mask_kv_seq_stride; + } + if (float_mask) { + fmask += mask_kv_seq_stride; + } + } + + // Each thread has a partial part of the output so we need to combine them. + + // First let's communicate the max and sum_exp + if (simd_lid == 0) { + max_scores[simd_gid] = max_score; + sum_exp_scores[simd_gid] = sum_exp_score; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + max_score = max_scores[simd_lid]; + U new_max = simd_max(max_score); + U factor = fast::exp(max_score - new_max); + sum_exp_score = simd_sum(sum_exp_scores[simd_lid] * factor); + + // Now we need to aggregate all the outputs + for (int i = 0; i < v_per_thread; i++) { + outputs[simd_lid * BD + simd_gid] = o[i]; + threadgroup_barrier(mem_flags::mem_threadgroup); + o[i] = simd_sum(outputs[simd_gid * BD + simd_lid] * factor); + o[i] = sum_exp_score == 0 ? o[i] : (o[i] / sum_exp_score); + threadgroup_barrier(mem_flags::mem_threadgroup); + } + + // And write the output + if (simd_lid == 0) { + for (int i = 0; i < v_per_thread; i++) { + out[i] = static_cast(o[i]); + } + } +} + +template +[[kernel]] void omlx_sdpa_decode_2pass_1( + const device T* queries [[buffer(0)]], + const device T* keys [[buffer(1)]], + const device T* values [[buffer(2)]], + device float* out [[buffer(3)]], + device float* sums [[buffer(4)]], + device float* maxs [[buffer(5)]], + const constant int& N [[buffer(7)]], + const constant size_t& k_head_stride [[buffer(8)]], + const constant size_t& k_seq_stride [[buffer(9)]], + const constant size_t& v_head_stride [[buffer(10)]], + const constant size_t& v_seq_stride [[buffer(11)]], + const constant float& scale [[buffer(12)]], + const device bool* bmask [[buffer(13), function_constant(bool_mask)]], + const device T* fmask [[buffer(14), function_constant(float_mask)]], + const constant int& mask_kv_seq_stride + [[buffer(15), function_constant(has_mask)]], + const constant int& mask_q_seq_stride + [[buffer(16), function_constant(has_mask)]], + const constant int& mask_head_stride + [[buffer(17), function_constant(has_mask)]], + const device T* sinks [[buffer(18), function_constant(has_sinks)]], + uint3 tptg [[threads_per_threadgroup]], + uint3 tidtg [[thread_position_in_threadgroup]], + uint3 tid [[threadgroup_position_in_grid]], + uint3 tpg [[threadgroups_per_grid]], + uint simd_lid [[thread_index_in_simdgroup]]) { + constexpr int BD = 32; + // Keys are processed in tiles of TK so the online softmax update (max, exp + // and rescale of the accumulator) happens once per tile instead of per key. + constexpr int TK = 4; + constexpr int qk_per_thread = D / BD; + constexpr int v_per_thread = V / BD; + + typedef float U; + + thread U q[qk_per_thread]; + thread U o[v_per_thread] = {0}; + + // Adjust positions + const int kv_head_idx = tid.x; + const int batch_idx = tid.y; + const int block_idx = tid.z; + const int gqa_factor = tptg.y; + const int q_seq_len = tptg.z; + const int q_seq_idx = tidtg.z; + const int q_head_idx = gqa_factor * kv_head_idx + tidtg.y; + const int num_kv_heads = tpg.x; + const int num_q_heads = num_kv_heads * gqa_factor; + const int q_batch_head_idx = (batch_idx * num_q_heads + q_head_idx); + const int o_offset = q_batch_head_idx * q_seq_len + q_seq_idx; + const int q_offset = + query_transposed ? num_q_heads * q_seq_idx + q_batch_head_idx : o_offset; + + queries += q_offset * D + simd_lid * qk_per_thread; + + // Each block processes a contiguous chunk of the KV sequence. + const int chunk = (N + blocks - 1) / blocks; + const int k_start = block_idx * chunk; + const int k_end = min(N, k_start + chunk); + + const int kv_batch_head_idx = batch_idx * num_kv_heads + kv_head_idx; + keys += kv_batch_head_idx * k_head_stride + k_start * k_seq_stride + + simd_lid * qk_per_thread; + values += kv_batch_head_idx * v_head_stride + k_start * v_seq_stride + + simd_lid * v_per_thread; + out += o_offset * blocks * V + block_idx * V + simd_lid * v_per_thread; + if (bool_mask) { + bmask += q_batch_head_idx * mask_head_stride + + k_start * mask_kv_seq_stride + q_seq_idx * mask_q_seq_stride; + } + if (float_mask) { + fmask += q_batch_head_idx * mask_head_stride + + k_start * mask_kv_seq_stride + q_seq_idx * mask_q_seq_stride; + } + sums += o_offset * blocks + block_idx; + maxs += o_offset * blocks + block_idx; + + // Read the query + { + thread T qt[qk_per_thread]; + load_vec(qt, queries); + for (int i = 0; i < qk_per_thread; i++) { + q[i] = static_cast(scale) * static_cast(qt[i]); + } + } + + U max_score = Limits::finite_min; + U sum_exp_score = 0; + if (has_sinks && block_idx == 0) { + max_score = static_cast(sinks[q_head_idx]); + sum_exp_score = 1; + } + + // For each tile of TK keys in this block's chunk + int i = k_start; + for (; i + TK <= k_end; i += TK) { + // Read the keys and compute the scores + thread T ks[TK][qk_per_thread]; + U scores[TK]; + bool use_key[TK]; +#pragma unroll + for (int t = 0; t < TK; t++) { + load_vec(ks[t], keys + t * int(k_seq_stride)); + } +#pragma unroll + for (int t = 0; t < TK; t++) { + U score = 0; + for (int j = 0; j < qk_per_thread; j++) { + score += q[j] * static_cast(ks[t][j]); + } + score = simd_sum(score); + + use_key[t] = true; + if (do_causal) { + use_key[t] = i + t <= (N - q_seq_len + int(q_seq_idx)); + } else if (bool_mask) { + use_key[t] = bmask[t * mask_kv_seq_stride]; + } else if (float_mask) { + use_key[t] = fmask[t * mask_kv_seq_stride] >= Limits::finite_min; + } + if (use_key[t] && float_mask) { + score += static_cast(fmask[t * mask_kv_seq_stride]); + } + scores[t] = use_key[t] ? score : Limits::finite_min; + } + + U tile_max = scores[0]; +#pragma unroll + for (int t = 1; t < TK; t++) { + tile_max = max(tile_max, scores[t]); + } + U new_max = max(max_score, tile_max); + + // Read the values + thread T vs[TK][v_per_thread]; +#pragma unroll + for (int t = 0; t < TK; t++) { + load_vec(vs[t], values + t * int(v_seq_stride)); + } + + // Rescale the accumulators only when the running max actually increased + if (new_max > max_score) { + U factor = fast::exp(max_score - new_max); + sum_exp_score *= factor; + for (int j = 0; j < v_per_thread; j++) { + o[j] *= factor; + } + max_score = new_max; + } + + // Update the accumulators +#pragma unroll + for (int t = 0; t < TK; t++) { + U p = use_key[t] ? fast::exp(scores[t] - max_score) : U(0); + sum_exp_score += p; +#pragma unroll + for (int j = 0; j < v_per_thread; j++) { + o[j] += p * static_cast(vs[t][j]); + } + } + + // Move the pointers to the next tile + keys += TK * int(k_seq_stride); + values += TK * int(v_seq_stride); + if (bool_mask) { + bmask += TK * mask_kv_seq_stride; + } + if (float_mask) { + fmask += TK * mask_kv_seq_stride; + } + } + + // Process the remaining keys of the chunk + for (; i < k_end; i++) { + bool use_key = true; + if (do_causal) { + use_key = i <= (N - q_seq_len + int(q_seq_idx)); + } else if (bool_mask) { + use_key = bmask[0]; + } else if (float_mask) { + use_key = (fmask[0] >= Limits::finite_min); + } + if (use_key) { + // Compute the i-th score + thread T k[qk_per_thread]; + load_vec(k, keys); + U score = 0; + for (int j = 0; j < qk_per_thread; j++) { + score += q[j] * static_cast(k[j]); + } + score = simd_sum(score); + + if (float_mask) { + score += fmask[0]; + } + + // Update the accumulators + U new_max = max(max_score, score); + U factor = fast::exp(max_score - new_max); + U exp_score = fast::exp(score - new_max); + + max_score = new_max; + sum_exp_score = sum_exp_score * factor + exp_score; + + // Update the output accumulator + thread T vt[v_per_thread]; + load_vec(vt, values); + for (int j = 0; j < v_per_thread; j++) { + o[j] = o[j] * factor + exp_score * static_cast(vt[j]); + } + } + + // Move the pointers to the next kv + keys += int(k_seq_stride); + values += int(v_seq_stride); + if (bool_mask) { + bmask += mask_kv_seq_stride; + } + if (float_mask) { + fmask += mask_kv_seq_stride; + } + } + + // Write the sum and max and outputs + if (simd_lid == 0) { + sums[0] = sum_exp_score; + maxs[0] = max_score; + } + + for (int i = 0; i < v_per_thread; i++) { + out[i] = o[i]; + } +} + +template +[[kernel]] void omlx_sdpa_decode_2pass_2( + const device float* partials [[buffer(0)]], + const device float* sums [[buffer(1)]], + const device float* maxs [[buffer(2)]], + device T* out [[buffer(3)]], + const constant int& blocks [[buffer(4)]], + uint3 tid [[threadgroup_position_in_grid]], + uint3 tpg [[threadgroups_per_grid]], + uint simd_gid [[simdgroup_index_in_threadgroup]], + uint simd_lid [[thread_index_in_simdgroup]]) { + constexpr int BN = 32; + constexpr int BD = 32; + constexpr int elem_per_thread = D / BD; + + typedef float U; + + thread U o[elem_per_thread] = {0}; + threadgroup U outputs[BN * BD]; + + // Adjust positions + const int head_idx = tid.x; + const int q_seq_idx = tid.y; + const int q_offset = head_idx * tpg.y + q_seq_idx; + partials += q_offset * blocks * D + simd_gid * D + simd_lid * elem_per_thread; + sums += q_offset * blocks; + maxs += q_offset * blocks; + out += q_offset * D + simd_gid * elem_per_thread; + + // Set defaults + U sum_exp_score = 0.0; + U max_score = Limits::finite_min; + + // Reduce the max + for (int b = 0; b < blocks / BN; ++b) { + max_score = max(max_score, maxs[simd_lid + BN * b]); + } + max_score = simd_max(max_score); + + // Reduce the d + for (int b = 0; b < blocks / BN; ++b) { + U factor = fast::exp(maxs[simd_lid + BN * b] - max_score); + sum_exp_score += factor * sums[simd_lid + BN * b]; + } + sum_exp_score = simd_sum(sum_exp_score); + + // Reduce the sum exp and partials + for (int b = 0; b < blocks / BN; ++b) { + U factor = fast::exp(maxs[simd_gid] - max_score); + + // Update the output accumulator + for (int i = 0; i < elem_per_thread; i++) { + o[i] += factor * partials[i]; + } + maxs += BN; + sums += BN; + partials += BN * D; + } + + // Use shared memory to transpose and reduce the final block + for (int i = 0; i < elem_per_thread; i++) { + outputs[simd_lid * BD + simd_gid] = o[i]; + threadgroup_barrier(mem_flags::mem_threadgroup); + o[i] = simd_sum(outputs[simd_gid * BD + simd_lid]); + o[i] = sum_exp_score == 0 ? o[i] : (o[i] / sum_exp_score); + threadgroup_barrier(mem_flags::mem_threadgroup); + } + + // And write the output + if (simd_lid == 0) { + for (int i = 0; i < elem_per_thread; i++) { + out[i] = static_cast(o[i]); + } + } +} diff --git a/omlx/custom_kernels/decode_fast/fast.py b/omlx/custom_kernels/decode_fast/fast.py new file mode 100644 index 0000000000..a7b1327803 --- /dev/null +++ b/omlx/custom_kernels/decode_fast/fast.py @@ -0,0 +1,96 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Exact decode-mode SDPA with a fail-closed MLX fallback.""" + +from __future__ import annotations + +import logging +from pathlib import Path +from typing import Optional + +import mlx.core as mx + +logger = logging.getLogger(__name__) + + +def _detach_import_error(exc: Exception) -> Exception: + exc.__traceback__ = None + exc.__cause__ = None + exc.__context__ = None + return exc + + +try: + from . import _ext +except Exception as exc: # pragma: no cover - depends on local native build + _ext = None + _IMPORT_ERROR = _detach_import_error(exc) + if any(Path(__file__).parent.glob("_ext*.so")): + logger.warning( + "%s: native extension failed to load; using exact MLX SDPA: %s", + __name__, + _IMPORT_ERROR, + ) +else: + _IMPORT_ERROR = None + + +def _verify_abi(ext, import_error): + """Disable the native symbol when nanobind rejects MLX arrays.""" + if ext is None: + return ext, import_error + probe = getattr(ext, "abi_probe", None) + if probe is None: + return ext, import_error + try: + probe(mx.zeros((1,))) + except TypeError as exc: + logger.warning( + "%s: native SDPA disabled after nanobind ABI mismatch", + __name__, + ) + return None, _detach_import_error(exc) + return ext, import_error + + +_ext, _IMPORT_ERROR = _verify_abi(_ext, _IMPORT_ERROR) +NATIVE_AVAILABLE = _ext is not None + + +def is_native_available() -> bool: + return NATIVE_AVAILABLE + + +def import_error() -> Exception | None: + return _IMPORT_ERROR + + +def sdpa_decode( + q: mx.array, + k: mx.array, + v: mx.array, + scale: float, + causal: bool = False, + mask: Optional[mx.array] = None, + sinks: Optional[mx.array] = None, + *, + stream: Optional[mx.Stream] = None, + force_fallback: bool = False, +) -> mx.array: + """Run native decode SDPA when its exact ABI accepts the inputs.""" + if ( + not force_fallback + and _ext is not None + and _ext.sdpa_decode_supported(q, k, v, stream) + ): + return _ext.sdpa_decode(q, k, v, scale, causal, mask, sinks, stream) + return mx.fast.scaled_dot_product_attention( + q, + k, + v, + scale=scale, + mask=mask, + sinks=sinks, + ) + + +__all__ = ["NATIVE_AVAILABLE", "is_native_available", "import_error", "sdpa_decode"] diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/CMakeLists.txt b/omlx/custom_kernels/glm_moe_dsa/csrc/CMakeLists.txt index a9445df057..ad55edb8d7 100644 --- a/omlx/custom_kernels/glm_moe_dsa/csrc/CMakeLists.txt +++ b/omlx/custom_kernels/glm_moe_dsa/csrc/CMakeLists.txt @@ -38,6 +38,7 @@ target_sources( ${CMAKE_CURRENT_LIST_DIR}/dspark_qmv.cpp ${CMAKE_CURRENT_LIST_DIR}/exact_block_attention.cpp ${CMAKE_CURRENT_LIST_DIR}/fused_moe.cpp + ${CMAKE_CURRENT_LIST_DIR}/qwen4_qsa_sparse_gqa.cpp ${CMAKE_CURRENT_LIST_DIR}/sparse_mla.cpp) target_include_directories( omlx_glm_kernel_ops @@ -57,6 +58,7 @@ if(MLX_BUILD_METAL) ${CMAKE_CURRENT_LIST_DIR}/dsa_indexer.metal ${CMAKE_CURRENT_LIST_DIR}/exact_block_attention.metal ${CMAKE_CURRENT_LIST_DIR}/fused_moe.metal + ${CMAKE_CURRENT_LIST_DIR}/qwen4_qsa_sparse_gqa.metal ${CMAKE_CURRENT_LIST_DIR}/sparse_mla.metal) file(GLOB_RECURSE OMLX_GLM_METAL_HEADERS CONFIGURE_DEPENDS ${CMAKE_CURRENT_LIST_DIR}/*.h diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/MLX_LICENSE.txt b/omlx/custom_kernels/glm_moe_dsa/csrc/MLX_LICENSE.txt new file mode 100644 index 0000000000..98ff47b9ef --- /dev/null +++ b/omlx/custom_kernels/glm_moe_dsa/csrc/MLX_LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright © 2023 Apple Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/MLX_SERVE_LICENSE.txt b/omlx/custom_kernels/glm_moe_dsa/csrc/MLX_SERVE_LICENSE.txt new file mode 100644 index 0000000000..fa6c781bf4 --- /dev/null +++ b/omlx/custom_kernels/glm_moe_dsa/csrc/MLX_SERVE_LICENSE.txt @@ -0,0 +1,31 @@ +MIT License + +Copyright (c) 2026 David Dalcu + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +------------------------------------------------------------------------------- + +The MIT terms above cover mlx-serve's own code. This distribution also includes +third-party software under its own licenses, including the Apache License 2.0, +the BSD 3-Clause License, and further MIT-licensed components. Those licenses +continue to apply to those portions. + +See NOTICE for the list and the required attributions, and LICENSE-APACHE-2.0 +for the text of the Apache License, Version 2.0. diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/bindings.cpp b/omlx/custom_kernels/glm_moe_dsa/csrc/bindings.cpp index 3f962178e1..da6219a9e9 100644 --- a/omlx/custom_kernels/glm_moe_dsa/csrc/bindings.cpp +++ b/omlx/custom_kernels/glm_moe_dsa/csrc/bindings.cpp @@ -9,6 +9,7 @@ #include "dspark_qmv.h" #include "exact_block_attention.h" #include "fused_moe.h" +#include "qwen4_qsa_sparse_gqa.h" #include "sparse_mla.h" namespace nb = nanobind; @@ -51,6 +52,32 @@ NB_MODULE(_ext, m) { "mask_ratio"_a = 0, "mask_q_offset"_a = 0, "stream"_a = nb::none()); + m.def( + "qwen4_qsa_indexer_scores", + &omlx::glm_kernels::qwen4_qsa_indexer_scores, + "queries"_a, + "pooled_keys"_a, + "mask_ratio"_a = 4, + "mask_q_offset"_a = 0, + "stream"_a = nb::none()); + m.def( + "qwen4_qsa_topk_indices", + &omlx::glm_kernels::qwen4_qsa_topk_indices, + "scores"_a, + "topk"_a = 512, + "stream"_a = nb::none()); + m.def( + "qwen4_qsa_sparse_gqa_attention", + &omlx::glm_kernels::qwen4_qsa_sparse_gqa_attention, + "queries"_a, + "keys"_a, + "values"_a, + "selected_blocks"_a, + "scale"_a, + "q_offset"_a, + "key_tile"_a = 128, + "dimension_tile"_a = 32, + "stream"_a = nb::none()); m.def( "dsa_topk_indices", &omlx::glm_kernels::dsa_topk_indices, diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/dsa_indexer.cpp b/omlx/custom_kernels/glm_moe_dsa/csrc/dsa_indexer.cpp index e4b0830bc1..239c90a4ef 100644 --- a/omlx/custom_kernels/glm_moe_dsa/csrc/dsa_indexer.cpp +++ b/omlx/custom_kernels/glm_moe_dsa/csrc/dsa_indexer.cpp @@ -2,6 +2,7 @@ #include "kernels/mma_dsa_indexer_score.h" +#include #include #include #include @@ -258,6 +259,133 @@ class DSAIndexerScoresPrimitive : public Primitive { int mask_q_offset_; }; +class Qwen4QSAIndexerScoresPrimitive : public Primitive { + public: + Qwen4QSAIndexerScoresPrimitive( + Stream stream, + int mask_ratio, + int mask_q_offset) + : Primitive(stream), + mask_ratio_(mask_ratio), + mask_q_offset_(mask_q_offset) {} + + static bool unsupported(const array& q, const array& k, Stream s) { + if (s.device == Device::cpu || q.dtype() != k.dtype()) { + return true; + } + if (q.dtype() != float16 && q.dtype() != bfloat16) { + return true; + } + if (!row_contiguous(q) || !row_contiguous(k)) { + return true; + } + if (q.ndim() != 4 || k.ndim() != 4) { + return true; + } + // This is intentionally the production Qwen4-Exp geometry only. A stale + // config or generalized caller must stay on qsa_fast's fp32 MLX path. + return q.shape(0) != 1 || k.shape(0) != 1 || q.shape(1) != 4 || + k.shape(1) != 1 || q.shape(2) <= 0 || k.shape(2) <= 0 || + q.shape(3) != 128 || k.shape(3) != 128; + } + + void eval_cpu( + const std::vector& /* inputs */, + std::vector& /* outputs */) override { + throw std::runtime_error( + "Qwen4QSAIndexerScoresPrimitive has no CPU path."); + } + + void eval_gpu( + const std::vector& inputs, + std::vector& outputs) override { + auto& s = stream(); + auto& d = metal::device(s.device); + auto& out = outputs[0]; + const auto& q = inputs[0]; + const auto& k = inputs[1]; + + out.set_data(allocator::malloc(out.nbytes())); + + constexpr int bm = 64; + constexpr int bn = 64; + constexpr int bk = 16; + constexpr int wm = 2; + constexpr int wn = 2; + const int B = q.shape(0); + const int H = q.shape(1); + const int M = q.shape(2); + const int N = k.shape(2); + const int D = q.shape(3); + const int tiles_m = (M + bm - 1) / bm; + const int tiles_n = (N + bn - 1) / bn; + + mlx::steel::GEMMParams params{ + /* const int M = */ M, + /* const int N = */ N, + /* const int K = */ D, + /* const int lda = */ D, + /* const int ldb = */ D, + /* const int ldd = */ N, + /* const int tiles_n = */ tiles_n, + /* const int tiles_m = */ tiles_m, + /* const int64_t batch_stride_a = */ int64_t(H) * M * D, + /* const int64_t batch_stride_b = */ int64_t(N) * D, + /* const int64_t batch_stride_d = */ int64_t(M) * N, + /* const int swizzle_log = */ 0, + /* const int gemm_k_iterations_aligned = */ D / bk, + /* const int batch_ndim = */ 1}; + + std::string base_name; + concatenate( + base_name, + "qwen4_qsa_indexer_score_", + type_to_name(q), + "_bm", + bm, + "_bn", + bn, + "_bk", + bk, + "_wm", + wm, + "_wn", + wn); + + auto lib = d.get_library("omlx_glm_kernels", current_binary_dir()); + auto kernel = d.get_kernel(base_name, lib); + auto& encoder = metal::get_command_encoder(s); + encoder.set_compute_pipeline_state(kernel); + encoder.set_input_array(q, 0); + encoder.set_input_array(k, 1); + encoder.set_output_array(out, 2); + encoder.set_bytes(params, 3); + encoder.set_bytes(mask_ratio_, 4); + encoder.set_bytes(mask_q_offset_, 5); + const float score_divisor = std::sqrt(static_cast(D)); + encoder.set_bytes(score_divisor, 6); + encoder.dispatch_threadgroups( + MTL::Size(tiles_n, tiles_m, B), + MTL::Size(wm * wn * 32, 1, 1)); + } + + DEFINE_NAME(OMLXQwen4QSAIndexerScores) + DEFINE_INPUT_OUTPUT_SHAPE() + bool is_equivalent(const Primitive& other) const override { + const auto& rhs = + static_cast(other); + return mask_ratio_ == rhs.mask_ratio_ && + mask_q_offset_ == rhs.mask_q_offset_; + } + auto state() const { + return std::make_tuple(mask_ratio_, mask_q_offset_); + } + + private: + int mask_ratio_; + int mask_q_offset_; +}; + // ── v25 M2 MMA score kernel (mma_dsa_indexer_score.h) ─────────────────────── // Split dispatch: the interior instantiation runs the unmodified hot loop on // fully-interior tiles; the boundary instantiation handles partial edge tiles @@ -558,6 +686,57 @@ class DSparkFP32TopKIndicesPrimitive : public Primitive { } }; +class Qwen4QSAFP32TopKIndicesPrimitive : public Primitive { + public: + explicit Qwen4QSAFP32TopKIndicesPrimitive(Stream stream) + : Primitive(stream) {} + + void eval_cpu( + const std::vector& /* inputs */, + std::vector& /* outputs */) override { + throw std::runtime_error("Qwen4 QSA FP32 top-k has no CPU path."); + } + + void eval_gpu( + const std::vector& inputs, + std::vector& outputs) override { + auto& s = stream(); + auto& d = metal::device(s.device); + const auto& scores = inputs[0]; + auto& out = outputs[0]; + out.set_data(allocator::malloc(out.nbytes())); + + constexpr int topk = 512; + constexpr int threads = 256; + const int rows = scores.shape(1); + DSATopKParams params{ + /* int rows = */ rows, + /* int L = */ rows, + /* int K = */ scores.shape(2), + /* int topk = */ topk, + /* bool causal_valid_prefix = */ false}; + + auto lib = d.get_library("omlx_glm_kernels", current_binary_dir()); + auto kernel = + d.get_kernel("qwen4_qsa_fp32_topk_indices_topk512_t256", lib); + auto& encoder = metal::get_command_encoder(s); + encoder.set_compute_pipeline_state(kernel); + encoder.set_input_array(scores, 0); + encoder.set_output_array(out, 1); + encoder.set_bytes(params, 2); + encoder.dispatch_threadgroups( + MTL::Size(rows, 1, 1), MTL::Size(threads, 1, 1)); + } + + DEFINE_NAME(OMLXQwen4QSAFP32TopKIndices) + DEFINE_INPUT_OUTPUT_SHAPE() + bool is_equivalent(const Primitive& /* other */) const override { + return true; + } + auto state() const { + return std::make_tuple(nullptr); + } +}; // ── DC-1: fused decode indexer scan ───────────────────────────────────────── // One kernel computes the head-summed indexer scores for a single query position // (s == 1) directly into [B,1,1,S] with fp32 accumulation, replacing the decode @@ -826,6 +1005,53 @@ array dsa_indexer_scores( std::move(inputs)); } +array qwen4_qsa_indexer_scores( + const array& queries, + const array& pooled_keys, + int mask_ratio, + int mask_q_offset, + StreamOrDevice s) { + if (queries.ndim() != 4 || pooled_keys.ndim() != 4) { + std::ostringstream msg; + msg << "[omlx_glm_kernels.qwen4_qsa_indexer_scores] expected q/k rank " + << "4, got " << queries.shape() << " and " << pooled_keys.shape() + << "."; + throw std::invalid_argument(msg.str()); + } + if (queries.dtype() != pooled_keys.dtype() || + (queries.dtype() != float16 && queries.dtype() != bfloat16)) { + throw std::invalid_argument( + "[omlx_glm_kernels.qwen4_qsa_indexer_scores] q/k must have matching " + "float16 or bfloat16 dtype."); + } + if (mask_ratio != 4 || mask_q_offset < 0) { + std::ostringstream msg; + msg << "[omlx_glm_kernels.qwen4_qsa_indexer_scores] requires " + << "mask_ratio=4 and a non-negative mask_q_offset, got " + << mask_ratio << " and " << mask_q_offset << "."; + throw std::invalid_argument(msg.str()); + } + + auto stream = to_stream(s); + auto q = ensure_row_contiguous(queries, stream); + auto k = ensure_row_contiguous(pooled_keys, stream); + if (Qwen4QSAIndexerScoresPrimitive::unsupported(q, k, stream)) { + std::ostringstream msg; + msg << "[omlx_glm_kernels.qwen4_qsa_indexer_scores] unsupported shape " + << "or layout; expected q [1,4,M,128] and k [1,1,N,128], got " + << q.shape() << " and " << k.shape() << "."; + throw std::invalid_argument(msg.str()); + } + + Shape out_shape{1, q.shape(2), k.shape(2)}; + return array( + std::move(out_shape), + float32, + std::make_shared( + stream, mask_ratio, mask_q_offset), + std::vector{q, k}); +} + array dsa_indexer_scores_mma( const array& queries, const array& keys, @@ -918,6 +1144,31 @@ array dspark_fp32_topk_indices( std::vector{contiguous_scores}); } +array qwen4_qsa_topk_indices( + const array& scores, + int topk, + StreamOrDevice s) { + if (scores.ndim() != 3 || scores.shape(0) != 1 || + scores.shape(1) < 1 || scores.dtype() != float32 || topk != 512 || + scores.shape(2) < topk) { + std::ostringstream msg; + msg << "[omlx_glm_kernels.qwen4_qsa_topk_indices] expected FP32 " + << "scores [1, M>=1, N>=512] and topk=512, got " << scores.shape() + << ", topk=" << topk << "."; + throw std::invalid_argument(msg.str()); + } + auto stream = to_stream(s); + if (stream.device == Device::cpu) { + throw std::invalid_argument("Qwen4 QSA FP32 top-k requires Metal."); + } + auto contiguous_scores = ensure_row_contiguous(scores, stream); + Shape out_shape{1, contiguous_scores.shape(1), topk}; + return array( + std::move(out_shape), + uint32, + std::make_shared(stream), + std::vector{contiguous_scores}); +} array dsa_decode_scores( const array& queries, const array& keys, diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/dsa_indexer.h b/omlx/custom_kernels/glm_moe_dsa/csrc/dsa_indexer.h index d01ed7ff45..acdb83bc8e 100644 --- a/omlx/custom_kernels/glm_moe_dsa/csrc/dsa_indexer.h +++ b/omlx/custom_kernels/glm_moe_dsa/csrc/dsa_indexer.h @@ -39,6 +39,31 @@ mx::array dsa_indexer_scores_mma( int mask_q_offset = 0, mx::StreamOrDevice s = {}); +// Qwen4-Exp QSA prefill score fusion. This deliberately narrow ABI consumes +// q [1,4,M,128] and pooled k [1,1,N,128] in fp16/bf16 and writes the exact +// selection domain directly as fp32 [1,M,N]: +// +// sum_h relu(q_h @ k.T) / sqrt(128) +// +// The pooled causal mask is applied in the epilogue, so no [1,4,M,N] +// intermediate is materialized. Unsupported shapes fail closed at the ABI; +// the QSA caller retains its portable float32 implementation as fallback. +mx::array qwen4_qsa_indexer_scores( + const mx::array& queries, + const mx::array& pooled_keys, + int mask_ratio = 4, + int mask_q_offset = 0, + mx::StreamOrDevice s = {}); + +// Lossless fixed-width Qwen4 QSA block selection. Scores are the contiguous +// fp32 [1, M, N] result of qwen4_qsa_indexer_scores; the output is uint32 +// [1, M, 512]. Cutoff ties deliberately retain the highest block indices to +// match mx.argpartition(scores, kth=-512)[..., -512:] set membership. +mx::array qwen4_qsa_topk_indices( + const mx::array& scores, + int topk = 512, + mx::StreamOrDevice s = {}); + mx::array dsa_topk_indices( const mx::array& scores, int topk, diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/dsa_indexer.metal b/omlx/custom_kernels/glm_moe_dsa/csrc/dsa_indexer.metal index 9ae186a09b..e3b86da1c3 100644 --- a/omlx/custom_kernels/glm_moe_dsa/csrc/dsa_indexer.metal +++ b/omlx/custom_kernels/glm_moe_dsa/csrc/dsa_indexer.metal @@ -25,6 +25,12 @@ struct OMLXDSATopKParams { "_bm" #bm "_bn" #bn "_bk" #bk "_wm" #wm "_wn" #wn, \ dsa_indexer_score, itype, bm, bn, bk, wm, wn) +#define instantiate_qwen4_qsa_indexer_score(iname, itype, bm, bn, bk, wm, wn) \ + instantiate_kernel( \ + "qwen4_qsa_indexer_score_" #iname \ + "_bm" #bm "_bn" #bn "_bk" #bk "_wm" #wm "_wn" #wn, \ + qwen4_qsa_indexer_score, itype, bm, bn, bk, wm, wn) + #define instantiate_dsa_topk_indices(iname, itype, topk, threads) \ instantiate_kernel( \ "steel_dsa_topk_indices_" #iname "_topk" #topk "_t" #threads, \ @@ -45,6 +51,12 @@ struct OMLXDSATopKParams { instantiate_dsa_indexer_score(float16, half, 64, 64, 16, 2, 2); instantiate_dsa_indexer_score(bfloat16, bfloat16_t, 64, 64, 16, 2, 2); +// Qwen4 QSA scores use the same validated M3 Steel tile, but write fp32 after +// reducing the fixed four heads. Keeping this in the existing metallib also +// lets stale extension builds fail closed at the missing ABI symbol. +instantiate_qwen4_qsa_indexer_score(float16, half, 64, 64, 16, 2, 2); +instantiate_qwen4_qsa_indexer_score(bfloat16, bfloat16_t, 64, 64, 16, 2, 2); + instantiate_dsa_topk_indices(float16, half, 2048, 1024); instantiate_dsa_topk_indices(bfloat16, bfloat16_t, 2048, 1024); instantiate_dsa_topk_indices(float16, half, 512, 1024); @@ -54,7 +66,19 @@ instantiate_kernel( "dspark_fp32_topk_indices_topk512_t256", dspark_fp32_topk_indices, 512, - 256); + 256, + false); + +// Qwen4's fixed 2048-token budget selects 512 complete four-token blocks. +// This shares DSpark's O(1)-workspace FP32 radix selector, but reverses the +// deterministic traversal so cutoff ties match mx.argpartition's highest-index +// membership exactly. +instantiate_kernel( + "qwen4_qsa_fp32_topk_indices_topk512_t256", + dspark_fp32_topk_indices, + 512, + 256, + true); // ── DC-1: fused decode indexer scan ────────────────────────────────────────── // One thread per key position: score(key) = sum_h w_h * relu(q_h · k_key), fp32 diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/kernels/steel_dsa_indexer_score.h b/omlx/custom_kernels/glm_moe_dsa/csrc/kernels/steel_dsa_indexer_score.h index e6ed2a1b04..9e82f074bb 100644 --- a/omlx/custom_kernels/glm_moe_dsa/csrc/kernels/steel_dsa_indexer_score.h +++ b/omlx/custom_kernels/glm_moe_dsa/csrc/kernels/steel_dsa_indexer_score.h @@ -211,15 +211,165 @@ template } } +// Qwen4 QSA's indexer has only four heads, but its portable score expression +// casts both operands to fp32 and materializes [B,M,H,N] before the ReLU/head +// reduction. This kernel keeps the same fp32 accumulation and final score +// dtype while carrying only one MMA tile per thread. The input layout is the +// natural GEMM-friendly [B,H,M,D] view; the public ABI fixes B=1,H=4,D=128. +template +[[kernel, max_total_threads_per_threadgroup(WM* WN * 32)]] void +qwen4_qsa_indexer_score( + const device T* Q [[buffer(0)]], + const device T* K [[buffer(1)]], + device float* O [[buffer(2)]], + const constant GEMMParams* params [[buffer(3)]], + const constant int& mask_ratio [[buffer(4)]], + const constant int& mask_q_offset [[buffer(5)]], + const constant float& score_divisor [[buffer(6)]], + uint simd_lane_id [[thread_index_in_simdgroup]], + uint simd_group_id [[simdgroup_index_in_threadgroup]], + uint3 tid [[threadgroup_position_in_grid]], + uint3 lid [[thread_position_in_threadgroup]]) { + (void)lid; + + using gemm_kernel = GEMMKernel< + T, + T, + BM, + BN, + BK, + WM, + WN, + false, + true, + true, + true, + float>; + using loader_a_t = typename gemm_kernel::loader_a_t; + using loader_b_t = typename gemm_kernel::loader_b_t; + using mma_t = typename gemm_kernel::mma_t; + + const int tid_y = ((tid.y) << params->swizzle_log) + + ((tid.x) & ((1 << params->swizzle_log) - 1)); + const int tid_x = (tid.x) >> params->swizzle_log; + if (params->tiles_n <= tid_x || params->tiles_m <= tid_y) { + return; + } + + constexpr int H = 4; + const int M = params->M; + const int N = params->N; + const int D = params->K; + const int c_row = tid_y * BM; + const int c_col = tid_x * BN; + const short tgp_bm = short(metal::min(BM, M - c_row)); + const short tgp_bn = short(metal::min(BN, N - c_col)); + + Q += size_t(tid.z) * H * M * D; + K += size_t(tid.z) * N * D; + O += size_t(tid.z) * M * N + size_t(c_row) * params->ldd + c_col; + + threadgroup T As[gemm_kernel::tgp_mem_size_a]; + threadgroup T Bs[gemm_kernel::tgp_mem_size_b]; + thread mma_t mma_op(simd_group_id, simd_lane_id); + + float accum[decltype(mma_op.Ctile)::kElemsPerTile]; + STEEL_PRAGMA_UNROLL + for (short i = 0; i < decltype(mma_op.Ctile)::kElemsPerTile; ++i) { + accum[i] = 0.0f; + } + + STEEL_PRAGMA_UNROLL + for (short h = 0; h < H; ++h) { + mma_op.Ctile.clear(); + const device T* A = Q + size_t(h) * M * D + size_t(c_row) * D; + const device T* B = K + size_t(c_col) * D; + thread loader_a_t loader_a(A, params->lda, As, simd_group_id, simd_lane_id); + thread loader_b_t loader_b(B, params->ldb, Bs, simd_group_id, simd_lane_id); + + for (int d = 0; d < params->gemm_k_iterations_aligned; ++d) { + threadgroup_barrier(mem_flags::mem_threadgroup); + if (tgp_bm == BM) { + loader_a.load_unsafe(); + } else { + loader_a.load_safe(short2(BK, tgp_bm)); + } + if (tgp_bn == BN) { + loader_b.load_unsafe(); + } else { + loader_b.load_safe(short2(BK, tgp_bn)); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + mma_op.mma(As, Bs); + loader_a.next(); + loader_b.next(); + } + threadgroup_barrier(mem_flags::mem_none); + + short ai = 0; + STEEL_PRAGMA_UNROLL + for (short i = 0; i < decltype(mma_op.Ctile)::kTileRows; ++i) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < decltype(mma_op.Ctile)::kTileCols; ++j) { + thread const auto& frag = mma_op.Ctile.frag_at(i, j); + STEEL_PRAGMA_UNROLL + for (short e = 0; e < decltype(mma_op.Ctile)::kElemsPerFrag; ++e) { + accum[ai++] += metal::max(frag[e], 0.0f); + } + } + } + } + + const float pooled_sentinel = as_type(uint(0xFF7FFFFF)); + device float* Dst = O + size_t(mma_op.sm) * params->ldd + mma_op.sn; + short ai = 0; + STEEL_PRAGMA_UNROLL + for (short i = 0; i < decltype(mma_op.Ctile)::kTileRows; ++i) { + const int row = c_row + mma_op.sm + i * mma_t::TM_stride; + STEEL_PRAGMA_UNROLL + for (short j = 0; j < decltype(mma_op.Ctile)::kTileCols; ++j) { + const int col_base = c_col + mma_op.sn + j * mma_t::TN_stride; + const int out_base = + (i * decltype(mma_op.Ctile)::kFragRows) * WM * params->ldd + + (j * decltype(mma_op.Ctile)::kFragCols) * WN; + STEEL_PRAGMA_UNROLL + for (short e = 0; e < decltype(mma_op.Ctile)::kElemsPerFrag; ++e) { + const int col = col_base + e; + const bool pooled_masked = + col >= (mask_q_offset + row + 1) / mask_ratio; + const float value = pooled_masked + ? pooled_sentinel + : accum[ai] / score_divisor; + if (row < M && col < N) { + Dst[out_base + e] = value; + } + ai++; + } + } + } +} + +template METAL_FUNC uint dsa_ordered_key_32(float x) { - const uint bits = as_type(x); + uint bits = as_type(x); + if (NUMERIC_ZERO_TIES && (bits & 0x7fffffffu) == 0u) { + bits = 0u; + } return (bits & 0x80000000u) ? ~bits : (bits | 0x80000000u); } -// Exact FP32 selection for DSpark's decode-consistent index scores. Four -// byte-wise radix passes identify the cutoff, then a deterministic segmented -// scan writes the selected set directly in temporal order. -template +// Exact FP32 selection for DSpark's decode-consistent index scores and Qwen4 +// QSA block scores. Four byte-wise radix passes identify the cutoff, then a +// deterministic segmented scan writes the selected set without materializing +// an O(K) index sheet. DSpark keeps the historical lowest-index-first cutoff +// tie policy. Qwen4 uses HIGHEST_INDEX_TIES because +// +// mx.argpartition(scores, kth=-TOPK)[..., -TOPK:] +// +// retains the highest-index members when an exact tie straddles the cutoff. +// Reversing both segment ownership and each segment's scan makes that policy +// deterministic without another row pass or a score perturbation. +template [[kernel, max_total_threads_per_threadgroup(THREADS)]] void dspark_fp32_topk_indices( const device float* scores [[buffer(0)]], @@ -245,8 +395,10 @@ dspark_fp32_topk_indices( const uint K = uint(params->K); const uint segment = (K + THREADS - 1) / THREADS; - const uint start = tid * segment; + const uint logical_tid = HIGHEST_INDEX_TIES ? THREADS - 1 - tid : tid; + const uint start = logical_tid * segment; const uint stop = metal::min(start + segment, K); + const uint count = start < K ? stop - start : 0u; const device float* row_scores = scores + size_t(row) * K; for (int shift = 24; shift >= 0; shift -= 8) { @@ -256,8 +408,10 @@ dspark_fp32_topk_indices( threadgroup_barrier(mem_flags::mem_threadgroup); const uint prefix = state[0]; - for (uint index = start; index < stop; ++index) { - const uint key = dsa_ordered_key_32(row_scores[index]); + for (uint step = 0; step < count; ++step) { + const uint index = HIGHEST_INDEX_TIES ? stop - 1 - step : start + step; + const uint key = + dsa_ordered_key_32(row_scores[index]); const bool prefix_match = shift == 24 || (key >> uint(shift + 8)) == (prefix >> uint(shift + 8)); if (prefix_match) { @@ -289,8 +443,10 @@ dspark_fp32_topk_indices( const uint greater_total = state[1]; uint local_greater = 0; uint local_ties = 0; - for (uint index = start; index < stop; ++index) { - const uint key = dsa_ordered_key_32(row_scores[index]); + for (uint step = 0; step < count; ++step) { + const uint index = HIGHEST_INDEX_TIES ? stop - 1 - step : start + step; + const uint key = + dsa_ordered_key_32(row_scores[index]); local_greater += key > threshold ? 1u : 0u; local_ties += key == threshold ? 1u : 0u; } @@ -343,8 +499,10 @@ dspark_fp32_topk_indices( uint output_pos = partial_a[simd] + pre_selected; uint ties_seen = pre_ties; device uint* row_out = out + size_t(row) * TOPK; - for (uint index = start; index < stop; ++index) { - const uint key = dsa_ordered_key_32(row_scores[index]); + for (uint step = 0; step < count; ++step) { + const uint index = HIGHEST_INDEX_TIES ? stop - 1 - step : start + step; + const uint key = + dsa_ordered_key_32(row_scores[index]); bool selected = key > threshold; if (key == threshold) { selected = ties_seen < tie_budget; diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/kernels/steel_qwen4_qsa_sparse_gqa.h b/omlx/custom_kernels/glm_moe_dsa/csrc/kernels/steel_qwen4_qsa_sparse_gqa.h new file mode 100644 index 0000000000..aba4047d8e --- /dev/null +++ b/omlx/custom_kernels/glm_moe_dsa/csrc/kernels/steel_qwen4_qsa_sparse_gqa.h @@ -0,0 +1,322 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright © 2026 OpenAI + +#pragma once + +#include "mlx/backend/metal/kernels/steel/attn/attn.h" +#include "mlx/backend/metal/kernels/steel/attn/params.h" + +using namespace mlx::steel; + +struct Qwen4SparseMaxOp { + template METAL_FUNC static constexpr T apply(T x, T y) { + return metal::max(x, y); + } +}; + +struct Qwen4SparseSumOp { + template METAL_FUNC static constexpr T apply(T x, T y) { + return x + y; + } +}; + +struct Qwen4SparseMulOp { + template METAL_FUNC static constexpr T apply(T x, T y) { + return x * y; + } +}; + +struct Qwen4SparseExpSubOp { + template METAL_FUNC static constexpr T apply(T x, T y) { + return fast::exp2(x - y); + } +}; + +struct Qwen4SparseDivOp { + template METAL_FUNC static constexpr T apply(T x, T y) { + return x / y; + } +}; + +// Exact Qwen4 QSA main attention over query-specific selected four-token +// blocks. +// +// One threadgroup owns one (query row, KV head). Qwen's 12 query heads per +// KV head are padded to one 16-row Steel MMA tile, letting both main GQA groups +// reuse each randomly addressed K/V tile without materializing the enormous +// [query, selected, kv-head, dim] gathered tensors. Invalid early-prefix +// blocks are masked before online FP32 softmax. The +// selected block list is chronological, and the zero-to-three causal tail is +// generated in-kernel, so accumulation follows the checkpoint's dense-mask +// token order without materializing an expanded 2,051-index tensor. +// The 128-bit global K/V staging pattern is adapted from mlx-serve's MIT +// ``msv_attn_p256`` kernel (Copyright 2026 David Dalcu); the query-specific +// direct-index/GQA organization and Steel MMA implementation are oMLX-specific. +// clang-format off +template < + typename T, + int BK, + int DC, + int GQA, + int H_PAD, + int D, + int WM, + typename IndexT, + typename AccumType = float> +[[kernel, max_total_threads_per_threadgroup(WM * 32)]] void +qwen4_qsa_sparse_gqa_attention( + const device T* Q [[buffer(0)]], + const device T* K [[buffer(1)]], + const device T* V [[buffer(2)]], + const device IndexT* Topk [[buffer(3)]], + device T* O [[buffer(4)]], + const constant Qwen4QSASparseGQAParams* params [[buffer(5)]], + uint simd_lane_id [[thread_index_in_simdgroup]], + uint simd_group_id [[simdgroup_index_in_threadgroup]], + uint3 tid [[threadgroup_position_in_grid]]) { // clang-format on + + constexpr short kFragSize = 8; + constexpr short padQ = 16 / sizeof(T); + constexpr short padK = 16 / sizeof(T); + constexpr short padV = 16 / sizeof(T); + + constexpr short LDQ = DC + padQ; + constexpr short LDK = BK + padK; + constexpr short LDV = DC + padV; + + constexpr int kNWarps = WM; + constexpr int TQ = H_PAD / (kNWarps * kFragSize); + constexpr int TK = BK / kFragSize; + constexpr int TDC = DC / kFragSize; + constexpr int D_CHUNKS = D / DC; + + static_assert(GQA <= H_PAD, "Qwen GQA heads must fit the padded MMA tile."); + static_assert(TQ == 1, "Qwen sparse GQA expects one query-head tile."); + static_assert(H_PAD % (kNWarps * kFragSize) == 0, + "Padded query heads must divide evenly across simdgroups."); + static_assert(BK % kFragSize == 0, "BK must be a multiple of eight."); + static_assert(DC % kFragSize == 0, "DC must be a multiple of eight."); + static_assert(D % DC == 0, "Head dimension must divide DC."); + + constexpr int tgp_size = WM * 32; + const int lane = int(simd_group_id * 32 + simd_lane_id); + const int q_pos = int(tid.x); + const int kv_head = int(tid.y); + const int b = int(tid.z); + + threadgroup T Qs[H_PAD * LDQ]; + threadgroup T KVs[(BK * LDV > DC * LDK) ? BK * LDV : DC * LDK]; + threadgroup int selected[BK]; + + using MMAFragAcc = BaseMMAFrag; + MMATile Qtile; + MMATile Ktile; + MMATile Stile; + MMATile Vtile; + MMATile Otile; + Otile.clear(); + + const short2 simd_coord = MMAFragAcc::get_coord(simd_lane_id); + const short sm = simd_coord.y; + const short sn = simd_coord.x; + const short tm = kFragSize * TQ * simd_group_id; + const short Qs_offset = (tm + sm) * LDQ + sn; + const short Ks_offset = sm * LDK + sn; + const short Vs_offset = sm * LDV + sn; + + const AccumType scale = AccumType(params->scale * M_LOG2E_F); + constexpr short rows_per_thread = decltype(Stile)::kRowsPerThread; + AccumType max_score[rows_per_thread]; + AccumType sum_score[rows_per_thread] = {0}; + STEEL_PRAGMA_UNROLL + for (short i = 0; i < rows_per_thread; ++i) { + max_score[i] = Limits::finite_min; + } + + const int query_head_base = kv_head * GQA; + const device T *q_base = Q + size_t(b) * params->Q_strides[0] + + size_t(query_head_base) * params->Q_strides[1] + + size_t(q_pos) * params->Q_strides[2]; + const device T *k_base = K + size_t(b) * params->K_strides[0] + + size_t(kv_head) * params->K_strides[1]; + const device T *v_base = V + size_t(b) * params->V_strides[0] + + size_t(kv_head) * params->V_strides[1]; + const device IndexT *topk_base = Topk + size_t(b) * params->Topk_strides[0] + + size_t(q_pos) * params->Topk_strides[2]; + + const int q_abs = params->q_offset + q_pos; + constexpr int kCompressRatio = 4; + constexpr int kTail = kCompressRatio - 1; + const int selected_tokens = params->topk * kCompressRatio + kTail; + const int complete_blocks = (q_abs + 1) / kCompressRatio; + const int valid_blocks = metal::min(params->topk, complete_blocks); + const int n_tiles = (selected_tokens + BK - 1) / BK; + + for (int ktile = 0; ktile < n_tiles; ++ktile) { + const int topk_off = ktile * BK; + for (int k = lane; k < BK; k += tgp_size) { + const int slot = topk_off + k; + int k_pos = -1; + if (slot < params->topk * kCompressRatio) { + const int block_slot = slot / kCompressRatio; + if (block_slot < valid_blocks) { + const IndexT raw_block = topk_base[block_slot]; + const ulong candidate = ulong(raw_block) * ulong(kCompressRatio) + + ulong(slot % kCompressRatio); + if (candidate < ulong(params->kL) && candidate <= ulong(q_abs)) { + k_pos = int(candidate); + } + } + } else if (slot < selected_tokens) { + const int tail_offset = slot - params->topk * kCompressRatio; + const int candidate = complete_blocks * kCompressRatio + tail_offset; + if (candidate < params->kL && candidate <= q_abs) { + k_pos = candidate; + } + } + selected[k] = k_pos; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + Stile.clear(); + STEEL_PRAGMA_UNROLL + for (short dchunk = 0; dchunk < D_CHUNKS; ++dchunk) { + const int dbase = int(dchunk) * DC; + for (int elem = lane; elem < H_PAD * (DC / 8); elem += tgp_size) { + const int h = elem / (DC / 8); + const int d8 = elem - h * (DC / 8); + uint4 word = uint4(0); + if (h < GQA) { + word = *((const device uint4 *)(q_base + + size_t(h) * params->Q_strides[1] + + dbase) + + d8); + } + *((threadgroup uint4 *)(Qs + h * LDQ) + d8) = word; + } + for (int elem = lane; elem < BK * (DC / 8); elem += tgp_size) { + const int k = elem / (DC / 8); + const int d8 = elem - k * (DC / 8); + const int k_pos = selected[k]; + uint4 word = uint4(0); + if (k_pos >= 0) { + word = *((const device uint4 *)(k_base + + size_t(k_pos) * params->K_strides[2] + + dbase) + + d8); + } + thread T *values = (thread T *)&word; + const int d = d8 * 8; + STEEL_PRAGMA_UNROLL + for (short e = 0; e < 8; ++e) { + KVs[k + (d + e) * LDK] = values[e]; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + STEEL_PRAGMA_UNROLL + for (short dd = 0; dd < TDC; ++dd) { + simdgroup_barrier(mem_flags::mem_none); + Qtile.template load(&Qs[Qs_offset + dd * kFragSize]); + Ktile.template load( + &KVs[Ks_offset + dd * kFragSize * LDK]); + simdgroup_barrier(mem_flags::mem_none); + tile_matmad(Stile, Qtile, Ktile, Stile); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + + STEEL_PRAGMA_UNROLL + for (short i = 0; i < decltype(Stile)::kElemsPerTile; ++i) { + Stile.elems()[i] *= scale; + } + { + using stile_t = decltype(Stile); + using selem_t = typename stile_t::elem_type; + // Early first-chunk rows can have no complete block, so entire leading + // tiles are invalid before the causal tail in the final tile. True + // -INFINITY makes those tiles contribute exp2(-inf - finite_max) == 0; + // finite_min would incorrectly add one to the softmax denominator. + constexpr auto neg_inf = selem_t(-INFINITY); + STEEL_PRAGMA_UNROLL + for (short i = 0; i < stile_t::kTileRows; ++i) { + STEEL_PRAGMA_UNROLL + for (short j = 0; j < stile_t::kTileCols; ++j) { + const short col_pos = sn + j * stile_t::kFragCols; + STEEL_PRAGMA_UNROLL + for (short e = 0; e < stile_t::MMAFrag_t::kElemCols; ++e) { + if (selected[col_pos + e] < 0) { + Stile.frag_at(i, j)[e] = neg_inf; + } + } + } + } + } + + AccumType new_max[rows_per_thread]; + AccumType factor[rows_per_thread]; + STEEL_PRAGMA_UNROLL + for (short i = 0; i < rows_per_thread; ++i) { + new_max[i] = max_score[i]; + } + Stile.template row_reduce(new_max); + Stile.template row_bin_op(new_max); + STEEL_PRAGMA_UNROLL + for (short i = 0; i < rows_per_thread; ++i) { + factor[i] = fast::exp2(max_score[i] - new_max[i]); + max_score[i] = new_max[i]; + } + AccumType sum_score_tmp[rows_per_thread] = {0}; + Stile.template row_reduce(sum_score_tmp); + STEEL_PRAGMA_UNROLL + for (short i = 0; i < rows_per_thread; ++i) { + sum_score[i] = sum_score[i] * factor[i] + sum_score_tmp[i]; + } + Otile.template row_bin_op(factor); + + STEEL_PRAGMA_UNROLL + for (short vchunk = 0; vchunk < D_CHUNKS; ++vchunk) { + const int dbase = int(vchunk) * DC; + for (int elem = lane; elem < BK * (DC / 8); elem += tgp_size) { + const int k = elem / (DC / 8); + const int d8 = elem - k * (DC / 8); + const int k_pos = selected[k]; + uint4 word = uint4(0); + if (k_pos >= 0) { + word = *((const device uint4 *)(v_base + + size_t(k_pos) * params->V_strides[2] + + dbase) + + d8); + } + *((threadgroup uint4 *)(KVs + k * LDV) + d8) = word; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + STEEL_PRAGMA_UNROLL + for (short iq = 0; iq < TQ; ++iq) { + STEEL_PRAGMA_UNROLL + for (short id = 0; id < TDC; ++id) { + STEEL_PRAGMA_UNROLL + for (short ik = 0; ik < TK; ++ik) { + const short kk = ik * kFragSize; + const short dd = id * kFragSize; + Vtile.template load( + &KVs[Vs_offset + kk * LDV + dd]); + MMAFragAcc::mma(Otile.frag_at(iq, vchunk * TDC + id), + Stile.frag_at(iq, ik), Vtile.frag_at(0, 0), + Otile.frag_at(iq, vchunk * TDC + id)); + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + } + + Otile.template row_bin_op(sum_score); + device T *out = O + size_t(b) * params->O_strides[0] + + size_t(query_head_base + tm + sm) * params->O_strides[1] + + size_t(q_pos) * params->O_strides[2] + sn; + const short rows_left = short(GQA - (tm + sm)); + if (rows_left > 0) { + Otile.template store_safe(out, params->O_strides[1], + short2(D - sn, rows_left)); + } +} diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/qwen4_qsa_sparse_gqa.cpp b/omlx/custom_kernels/glm_moe_dsa/csrc/qwen4_qsa_sparse_gqa.cpp new file mode 100644 index 0000000000..43ab9a909f --- /dev/null +++ b/omlx/custom_kernels/glm_moe_dsa/csrc/qwen4_qsa_sparse_gqa.cpp @@ -0,0 +1,200 @@ +// SPDX-License-Identifier: Apache-2.0 + +#include "qwen4_qsa_sparse_gqa.h" + +#include +#include +#include + +#include "mlx/backend/common/utils.h" +#include "mlx/backend/metal/device.h" +#include "mlx/backend/metal/utils.h" +#include "mlx/ops.h" +#include "mlx/utils.h" + +namespace omlx::glm_kernels { + +namespace { + +using namespace mlx::core; + +std::string current_binary_dir() { + static std::string binary_dir = []() { + Dl_info info; + if (!dladdr(reinterpret_cast(¤t_binary_dir), &info)) { + throw std::runtime_error("Unable to get omlx_glm_kernels binary dir."); + } + return std::filesystem::path(info.dli_fname).parent_path().string(); + }(); + return binary_dir; +} + +bool last_dim_contiguous(const array &arr) { return arr.strides(-1) == 1; } + +struct Qwen4QSASparseGQAParams { + int B; + int q_heads; + int kv_heads; + int qL; + int kL; + int topk; + int gqa_factor; + int q_offset; + + float scale; + + int64_t Q_strides[3]; + int64_t K_strides[3]; + int64_t V_strides[3]; + int64_t Topk_strides[3]; + int64_t O_strides[3]; +}; + +class Qwen4QSASparseGQAPrimitive : public Primitive { +public: + Qwen4QSASparseGQAPrimitive(Stream stream, float scale, int q_offset, + int key_tile, int dimension_tile) + : Primitive(stream), scale_(scale), q_offset_(q_offset), + key_tile_(key_tile), dimension_tile_(dimension_tile) {} + + static bool unsupported(const array &q, const array &k, const array &v, + const array &selected, int q_offset, int key_tile, + int dimension_tile, Stream stream) { + if (stream.device == Device::cpu || q.dtype() != k.dtype() || + q.dtype() != v.dtype()) { + return true; + } + if (q.dtype() != float16 && q.dtype() != bfloat16) { + return true; + } + if (q.ndim() != 4 || k.ndim() != 4 || v.ndim() != 4 || + selected.ndim() != 4 || selected.dtype() != uint32) { + return true; + } + if (!last_dim_contiguous(q) || !last_dim_contiguous(k) || + !last_dim_contiguous(v) || !last_dim_contiguous(selected)) { + return true; + } + if (q.shape(0) != 1 || k.shape(0) != 1 || v.shape(0) != 1 || + selected.shape(0) != 1 || q.shape(1) != 24 || k.shape(1) != 2 || + v.shape(1) != 2 || q.shape(3) != 256 || k.shape(3) != 256 || + v.shape(3) != 256 || k.shape(2) != v.shape(2) || q.shape(2) <= 0 || + selected.shape(1) != 1 || selected.shape(2) != q.shape(2) || + selected.shape(3) != 512) { + return true; + } + if (q_offset < 0 || q_offset + q.shape(2) > k.shape(2) || + !((dimension_tile == 32 && (key_tile == 128 || key_tile == 256)) || + (dimension_tile == 64 && (key_tile == 64 || key_tile == 128)))) { + return true; + } + return false; + } + + void eval_cpu(const std::vector & /* inputs */, + std::vector & /* outputs */) override { + throw std::runtime_error("Qwen4QSASparseGQAPrimitive has no CPU path."); + } + + void eval_gpu(const std::vector &inputs, + std::vector &outputs) override { + auto &stream = this->stream(); + auto &device = metal::device(stream.device); + const auto &q = inputs[0]; + const auto &k = inputs[1]; + const auto &v = inputs[2]; + const auto &selected = inputs[3]; + auto &out = outputs[0]; + + constexpr int gqa = 12; + constexpr int dim = 256; + constexpr int wm = 2; + constexpr int hpad = 16; + + out.set_data(allocator::malloc(out.nbytes())); + Qwen4QSASparseGQAParams params{ + /* int B = */ 1, + /* int q_heads = */ 24, + /* int kv_heads = */ 2, + /* int qL = */ q.shape(2), + /* int kL = */ k.shape(2), + /* int topk = */ selected.shape(3), + /* int gqa_factor = */ gqa, + /* int q_offset = */ q_offset_, + /* float scale = */ scale_, + /* int64_t Q_strides[3] = */ {q.strides(0), q.strides(1), q.strides(2)}, + /* int64_t K_strides[3] = */ {k.strides(0), k.strides(1), k.strides(2)}, + /* int64_t V_strides[3] = */ {v.strides(0), v.strides(1), v.strides(2)}, + /* int64_t Topk_strides[3] = */ + {selected.strides(0), selected.strides(1), selected.strides(2)}, + /* int64_t O_strides[3] = */ + {out.strides(0), out.strides(1), out.strides(2)}}; + + std::string kernel_name; + concatenate(kernel_name, "qwen4_qsa_sparse_gqa_", type_to_name(q), "_bk", + key_tile_, "_dc", dimension_tile_, "_gqa", gqa, "_hp", hpad, + "_d", dim, "_wm", wm); + + auto library = device.get_library("omlx_glm_kernels", current_binary_dir()); + auto kernel = device.get_kernel(kernel_name, library); + auto &encoder = metal::get_command_encoder(stream); + encoder.set_compute_pipeline_state(kernel); + encoder.set_input_array(q, 0); + encoder.set_input_array(k, 1); + encoder.set_input_array(v, 2); + encoder.set_input_array(selected, 3); + encoder.set_output_array(out, 4); + encoder.set_bytes(params, 5); + encoder.dispatch_threadgroups(MTL::Size(q.shape(2), k.shape(1), 1), + MTL::Size(32, wm, 1)); + } + + DEFINE_NAME(OMLXQwen4QSASparseGQAAttention) + DEFINE_INPUT_OUTPUT_SHAPE() + bool is_equivalent(const Primitive &other) const override { + const auto &rhs = static_cast(other); + return scale_ == rhs.scale_ && q_offset_ == rhs.q_offset_ && + key_tile_ == rhs.key_tile_ && dimension_tile_ == rhs.dimension_tile_; + } + auto state() const { + return std::make_tuple(nullptr, scale_, q_offset_, key_tile_, + dimension_tile_); + } + +private: + float scale_; + int q_offset_; + int key_tile_; + int dimension_tile_; +}; + +} // namespace + +array qwen4_qsa_sparse_gqa_attention(const array &queries, const array &keys, + const array &values, + const array &selected_blocks, float scale, + int q_offset, int key_tile, + int dimension_tile, StreamOrDevice s) { + auto stream = to_stream(s); + if (Qwen4QSASparseGQAPrimitive::unsupported( + queries, keys, values, selected_blocks, q_offset, key_tile, + dimension_tile, stream)) { + std::ostringstream msg; + msg << "[omlx_glm_kernels.qwen4_qsa_sparse_gqa_attention] expected " + << "q=[1,24,M,256], k/v=[1,2,K,256], uint32 selected blocks=" + << "[1,1,M,512], q_offset>=0, (BK,DC) in " + << "{(128,32),(256,32),(64,64),(128,64)}; got " << queries.shape() + << ", " << keys.shape() << ", " << values.shape() << ", " + << selected_blocks.shape() << "."; + throw std::invalid_argument(msg.str()); + } + + Shape out_shape{queries.shape(0), queries.shape(1), queries.shape(2), + queries.shape(3)}; + return array(std::move(out_shape), queries.dtype(), + std::make_shared( + stream, scale, q_offset, key_tile, dimension_tile), + std::vector{queries, keys, values, selected_blocks}); +} + +} // namespace omlx::glm_kernels diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/qwen4_qsa_sparse_gqa.h b/omlx/custom_kernels/glm_moe_dsa/csrc/qwen4_qsa_sparse_gqa.h new file mode 100644 index 0000000000..b62246f4d2 --- /dev/null +++ b/omlx/custom_kernels/glm_moe_dsa/csrc/qwen4_qsa_sparse_gqa.h @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include "mlx/array.h" +#include "mlx/stream.h" +#include "mlx/utils.h" + +namespace mx = mlx::core; + +namespace omlx::glm_kernels { + +mx::array qwen4_qsa_sparse_gqa_attention( + const mx::array &queries, const mx::array &keys, const mx::array &values, + const mx::array &selected_blocks, float scale, int q_offset, + int key_tile = 128, int dimension_tile = 32, mx::StreamOrDevice s = {}); + +} // namespace omlx::glm_kernels diff --git a/omlx/custom_kernels/glm_moe_dsa/csrc/qwen4_qsa_sparse_gqa.metal b/omlx/custom_kernels/glm_moe_dsa/csrc/qwen4_qsa_sparse_gqa.metal new file mode 100644 index 0000000000..8937e720c0 --- /dev/null +++ b/omlx/custom_kernels/glm_moe_dsa/csrc/qwen4_qsa_sparse_gqa.metal @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Include order is load-bearing: Steel's attention header provides Limits +// used by the specialized Qwen kernel. +// clang-format off +#include "mlx/backend/metal/kernels/utils.h" +#include "mlx/backend/metal/kernels/steel/attn/kernels/steel_attention.h" +#include "kernels/steel_qwen4_qsa_sparse_gqa.h" +// clang-format on + +#define instantiate_qwen4_sparse_gqa(tname, dtype, bk, dc) \ + instantiate_kernel("qwen4_qsa_sparse_gqa_" #tname "_bk" #bk "_dc" #dc \ + "_gqa12_hp16_d256_wm2", \ + qwen4_qsa_sparse_gqa_attention, dtype, bk, dc, 12, 16, \ + 256, 2, uint, float) + +instantiate_qwen4_sparse_gqa(float16, half, 128, 32); +instantiate_qwen4_sparse_gqa(float16, half, 256, 32); +instantiate_qwen4_sparse_gqa(float16, half, 64, 64); +instantiate_qwen4_sparse_gqa(float16, half, 128, 64); +instantiate_qwen4_sparse_gqa(bfloat16, bfloat16_t, 128, 32); +instantiate_qwen4_sparse_gqa(bfloat16, bfloat16_t, 256, 32); +instantiate_qwen4_sparse_gqa(bfloat16, bfloat16_t, 64, 64); +instantiate_qwen4_sparse_gqa(bfloat16, bfloat16_t, 128, 64); diff --git a/omlx/custom_kernels/glm_moe_dsa/fast.py b/omlx/custom_kernels/glm_moe_dsa/fast.py index 199c0f2de3..ea4cca56df 100644 --- a/omlx/custom_kernels/glm_moe_dsa/fast.py +++ b/omlx/custom_kernels/glm_moe_dsa/fast.py @@ -101,6 +101,9 @@ def _probe_mma_score(ext) -> bool: NATIVE_SYMBOLS = ( "dsa_decode_scores", "dsa_indexer_scores", + "qwen4_qsa_indexer_scores", + "qwen4_qsa_topk_indices", + "qwen4_qsa_sparse_gqa_attention", "dsa_topk_indices", "dspark_fp32_topk_indices", "dspark_exact_mxfp8_qmv_pair", @@ -257,6 +260,95 @@ def dsa_indexer_scores( return scores +def qwen4_qsa_indexer_scores( + queries: mx.array, + pooled_keys: mx.array, + mask_ratio: int = 4, + mask_q_offset: int = 0, + *, + stream=None, +) -> mx.array: + """Fused, fp32 Qwen4 QSA block scores for the M3 prefill geometry. + + ``queries`` is ``[1, 4, M, 128]`` and ``pooled_keys`` is + ``[1, 1, N, 128]`` in matching bf16/fp16. The result is fp32 + ``[1, M, N]`` after head-summed ReLU, ``1/sqrt(128)`` scaling, and the + pooled-causal mask. The dedicated ABI intentionally has no implicit + fallback; ``qsa_fast`` owns the portable float32 fallback. + """ + if _ext is None or not hasattr(_ext, "qwen4_qsa_indexer_scores"): + raise RuntimeError( + "qwen4_qsa_indexer_scores requires a local extension build that " + "exposes the Qwen4 QSA score kernel" + ) + return _ext.qwen4_qsa_indexer_scores( + queries, + pooled_keys, + mask_ratio=mask_ratio, + mask_q_offset=mask_q_offset, + **_native_stream_kwargs(stream), + ) + + +def qwen4_qsa_topk_indices( + scores: mx.array, + topk: int = 512, + *, + stream=None, +) -> mx.array: + """Select Qwen4's top 512 block indices from fp32 ``[1, M, N]`` scores. + + The native radix path returns only ``[1, M, 512]`` uint32 indices, avoiding + the full-width index allocation made by ``mx.argpartition``. Exact cutoff + ties retain their highest-index members, matching the set selected by the + portable QSA expression. The ABI is deliberately fixed to ``topk=512`` and + fails closed when the rebuilt extension or production geometry is absent. + """ + if _ext is None or not hasattr(_ext, "qwen4_qsa_topk_indices"): + raise RuntimeError("Qwen4 QSA FP32 top-k kernel is unavailable") + return _ext.qwen4_qsa_topk_indices( + scores, + topk, + **_native_stream_kwargs(stream), + ) + + +def qwen4_qsa_sparse_gqa_attention( + queries: mx.array, + keys: mx.array, + values: mx.array, + selected_blocks: mx.array, + scale: float, + q_offset: int, + *, + key_tile: int = 128, + dimension_tile: int = 32, + stream=None, +) -> mx.array: + """Exact Qwen4 main GQA over query-specific selected cache rows. + + The narrow native ABI consumes 512 chronological uint32 block IDs directly, + expands each to four tokens, appends the causal tail in-kernel, and + keeps QK scores, online softmax state, and the weighted output in fp32. + It supports only Qwen3.8-Flash-Next's batch-one ``24q/2kv/D256`` geometry; + callers own the portable gathered fallback for every other shape. + """ + + if _ext is None or not hasattr(_ext, "qwen4_qsa_sparse_gqa_attention"): + raise RuntimeError("Qwen4 QSA sparse GQA kernel is unavailable") + return _ext.qwen4_qsa_sparse_gqa_attention( + queries, + keys, + values, + selected_blocks, + scale, + q_offset, + key_tile, + dimension_tile, + **_native_stream_kwargs(stream), + ) + + def dsa_decode_scores( queries: mx.array, keys: mx.array, diff --git a/omlx/models/vlm.py b/omlx/models/vlm.py index af2d62d0ab..949177682a 100644 --- a/omlx/models/vlm.py +++ b/omlx/models/vlm.py @@ -148,6 +148,11 @@ def model_type(self) -> str: return self._vlm_model.config.model_type return "vlm" + @property + def supports_skip_lm_head(self) -> bool: + """Whether the wrapped official language model has a cache-only pass.""" + return self.model_type == "qwen4_exp" + @property def config(self): """Expose model config.""" @@ -338,6 +343,7 @@ def __call__( self, input_ids: mx.array, cache: Optional[List[Any]] = None, + skip_lm_head: bool = False, **kwargs, ) -> Any: """ @@ -359,6 +365,12 @@ def __call__( Model output (logits as mx.array) """ return_hidden = bool(kwargs.get("return_hidden", False)) + if skip_lm_head: + # Scheduler prefill chunks discard their logits. Translate the + # shared cache-only contract into the official Qwen model hook so + # those chunks do not project every token over the full vocabulary. + if self.model_type == "qwen4_exp": + kwargs["skip_logits"] = True inputs_embeds = kwargs.pop("inputs_embeds", None) vlm_extra = kwargs.pop("vlm_extra_kwargs", None) or {} vlm_extra.pop("_captured_rope_deltas", None) diff --git a/omlx/patches/mlx_lm_mtp/prompt_priming.py b/omlx/patches/mlx_lm_mtp/prompt_priming.py index 5b58f9f541..37d22024f3 100644 --- a/omlx/patches/mlx_lm_mtp/prompt_priming.py +++ b/omlx/patches/mlx_lm_mtp/prompt_priming.py @@ -71,6 +71,7 @@ HEAD_HIDDEN_POST_NORM = True _CTX_ATTR = "_omlx_mtp_prime_ctx" +_PLAN_ATTR = "_omlx_mtp_prime_plan" _SUPPRESS = threading.local() @@ -131,6 +132,52 @@ class _PrimeCtx: # The current contiguous timeline exceeded OMLX_MTP_PRIME_WINDOW. Keep a # lightweight marker so later small chunks cannot restart priming. window_exceeded: bool = False + # Absolute MTP history is ``folded``; this counter is only the work folded + # by the current request. A warm prefix restore starts at a nonzero + # absolute history but must still apply OMLX_MTP_PRIME_WINDOW to the small + # uncached suffix, preserving the option's documented meaning. + folded_this_request: int = 0 + # Request/prefix-cache metadata used to publish and restore one exact + # full-block MTP boundary snapshot. The cache itself remains generic and + # treats the snapshot as an opaque sidecar. + request_id: Optional[str] = None + prompt_tokens: Optional[tuple[int, ...]] = None + block_size: int = 0 + prefix_cache: Any = None + extra_keys: Optional[tuple[Any, ...]] = None + extra_key_token_start: Optional[int] = None + extra_key_ranges: Optional[list[tuple[int, tuple[Any, ...]]]] = None + snapshot_candidate: Any = None + + +@dataclass +class _PrimePlan: + """Scheduler-owned metadata for the next singleton prompt timeline.""" + + request_id: str + prompt_tokens: tuple[int, ...] + block_size: int + prefix_cache: Any + extra_keys: Optional[tuple[Any, ...]] = None + extra_key_token_start: Optional[int] = None + extra_key_ranges: Optional[list[tuple[int, tuple[Any, ...]]]] = None + + +@dataclass +class _MtpPrefixSnapshot: + """Detached MTP-head state at a backbone full-block boundary.""" + + boundary_tokens: int + mtp_cache: List[Any] + pending_hidden: Any + + +@dataclass +class _MtpBoundaryCandidate: + """Cheap boundary marker retained until activation publishes a snapshot.""" + + boundary_tokens: int + pending_hidden: Any def _read_offset(entry: Any) -> Optional[int]: @@ -246,28 +293,113 @@ def _find_ctx(model: Any) -> Optional[_PrimeCtx]: return None +def _find_plan(model: Any) -> Optional[_PrimePlan]: + for host in _host_candidates(model): + plan = getattr(host, _PLAN_ATTR, None) + if isinstance(plan, _PrimePlan): + return plan + return None + + def drop_ctx(model: Any) -> None: - """Remove any priming context from the model's host slot.""" + """Remove any priming context/plan from the model's host slots.""" if model is None: return for host in _host_candidates(model): - if getattr(host, _CTX_ATTR, None) is not None: - try: - delattr(host, _CTX_ATTR) - except AttributeError: - pass + for attr in (_CTX_ATTR, _PLAN_ATTR): + if getattr(host, attr, None) is not None: + try: + delattr(host, attr) + except AttributeError: + pass def _host_eligible(host: Any) -> bool: get_mtp = getattr(host, "get_mtp_module", None) mtp = get_mtp() if callable(get_mtp) else getattr(host, "mtp", None) - return bool( - getattr(host, "_omlx_mtp_decode_enabled", False) - and getattr(host, "_omlx_mtp_chain", False) + return ( + getattr(host, "_omlx_mtp_decode_enabled", False) is True + and getattr(host, "_omlx_mtp_chain", False) is True and mtp is not None ) +def _eligible_host(model: Any) -> Any | None: + for host in _host_candidates(model): + if _host_eligible(host): + return host + return None + + +def _clone_mtp_cache(cache: List[Any]) -> List[Any]: + """Detach an MTP cache so later decode writes cannot mutate a snapshot.""" + import copy + + import mlx.core as mx + + def clone_one(entry: Any) -> Any: + if entry is None: + return None + subs = getattr(entry, "caches", None) + if subs is not None: + return type(entry)(*[clone_one(sub) for sub in subs]) + clone = copy.copy(entry) + for attr, value in vars(entry).items(): + if isinstance(value, mx.array): + setattr(clone, attr, value + 0) + elif isinstance(value, list): + setattr(clone, attr, list(value)) + return clone + + return [clone_one(entry) for entry in cache] + + +def _flat_cache_entries(cache: List[Any]): + for entry in cache: + subs = getattr(entry, "caches", None) + if subs is None: + yield entry + else: + yield from subs + + +def _cache_at_offset(cache: List[Any], target: int) -> Optional[List[Any]]: + """Return a detached, exactly trimmed MTP cache or fail closed.""" + if target < 0 or not cache: + return None + cloned = _clone_mtp_cache(cache) + saw_offset = False + for entry in _flat_cache_entries(cloned): + current = _read_offset(entry) + if current is None: + continue + saw_offset = True + if current < target: + return None + extra = current - target + if extra: + trim = getattr(entry, "trim", None) + if not callable(trim) or int(trim(extra)) != extra: + return None + if _read_offset(entry) != target: + return None + return cloned if saw_offset else None + + +def _snapshot_arrays(snapshot: _MtpPrefixSnapshot) -> list[Any]: + """Arrays that must be materialized to sever the live prefill graph.""" + import mlx.core as mx + + arrays: list[Any] = [] + if isinstance(snapshot.pending_hidden, mx.array): + arrays.append(snapshot.pending_hidden) + for entry in _flat_cache_entries(snapshot.mtp_cache): + for value in vars(entry).values(): + if isinstance(value, mx.array): + arrays.append(value) + return arrays + + def capture_eligible(host: Any, cache: Optional[List[Any]]) -> bool: """Cheap pre-check for capture sites that must decide the forward shape. @@ -285,6 +417,213 @@ def capture_eligible(host: Any, cache: Optional[List[Any]]) -> bool: ) +def prepare_prefix_context( + model: Any, + *, + request_id: str, + prompt_tokens: list[int], + cached_tokens: int, + prefix_cache: Any, + extra_keys: Optional[tuple[Any, ...]] = None, + extra_key_token_start: Optional[int] = None, + extra_key_ranges: Optional[list[tuple[int, tuple[Any, ...]]]] = None, +) -> bool: + """Prepare exact MTP priming for one scheduler-owned prompt timeline. + + ``cached_tokens`` is the final reconstructed backbone offset (after any + exact-hit trim). A matching sidecar restores the MTP-head KV at + ``cached_tokens - 1`` plus the pending trunk hidden at the boundary, so + the uncached suffix can continue folding without replaying the trunk. + Missing, stale, VLM-range-keyed, or shape-incompatible snapshots fail + closed to the existing unprimed path. + + Returns True only when a warm sidecar was restored. Repeating the call + for the same request is idempotent and never double-primes a live suffix. + """ + host = _eligible_host(model) + if host is None or not priming_enabled() or prefix_cache is None: + drop_ctx(model) + return False + + tokens = tuple(int(token) for token in prompt_tokens) + cached_tokens = max(0, int(cached_tokens)) + existing = _find_ctx(model) + plan = _find_plan(model) + if ( + (existing is not None and existing.request_id == request_id) + or ( + plan is not None + and plan.request_id == request_id + and plan.prompt_tokens == tokens + ) + ): + return existing is not None and existing.expected_offset >= cached_tokens + + drop_ctx(model) + plan = _PrimePlan( + request_id=request_id, + prompt_tokens=tokens, + block_size=max(0, int(getattr(prefix_cache, "block_size", 0) or 0)), + prefix_cache=prefix_cache, + extra_keys=extra_keys, + extra_key_token_start=extra_key_token_start, + extra_key_ranges=( + list(extra_key_ranges) if extra_key_ranges is not None else None + ), + ) + setattr(host, _PLAN_ATTR, plan) + if cached_tokens <= 0: + return False + + restore = getattr(prefix_cache, "restore_mtp_prefix_snapshot", None) + if not callable(restore): + return False + try: + snapshot = restore( + list(tokens), + cached_tokens, + extra_keys=extra_keys, + extra_key_token_start=extra_key_token_start, + extra_key_ranges=extra_key_ranges, + ) + except Exception as exc: + logger.debug("MTP prefix sidecar lookup failed closed: %s", exc) + return False + if not isinstance(snapshot, _MtpPrefixSnapshot): + return False + if snapshot.boundary_tokens != cached_tokens or cached_tokens < 2: + return False + + target_offset = cached_tokens - 1 + try: + restored_cache = _cache_at_offset(snapshot.mtp_cache, target_offset) + if restored_cache is None or snapshot.pending_hidden is None: + return False + + import mlx.core as mx + + pending_hidden = snapshot.pending_hidden + 0 + except Exception as exc: + logger.debug("MTP prefix sidecar restore failed closed: %s", exc) + return False + ctx = _PrimeCtx( + mtp_cache=restored_cache, + pending_hidden=pending_hidden, + folded=target_offset, + expected_offset=cached_tokens, + request_id=request_id, + prompt_tokens=tokens, + block_size=plan.block_size, + prefix_cache=prefix_cache, + extra_keys=extra_keys, + extra_key_token_start=extra_key_token_start, + extra_key_ranges=plan.extra_key_ranges, + ) + setattr(host, _CTX_ATTR, ctx) + try: + arrays = [pending_hidden, *_snapshot_arrays(snapshot)] + if arrays: + mx.async_eval(arrays) + except Exception as exc: + drop_ctx(model) + logger.debug("MTP prefix sidecar materialization failed closed: %s", exc) + return False + logger.debug( + "MTP prompt history restored at %d cached tokens for %s", + cached_tokens, + request_id, + ) + return True + + +def _capture_boundary_candidate( + ctx: _PrimeCtx, + normed: Any, + *, + seq_start: int, + seq_end: int, +) -> None: + """Detach the newest full-block MTP boundary crossed by this chunk.""" + block = int(ctx.block_size or 0) + if ( + block <= 0 + or ctx.prefix_cache is None + or not ctx.prompt_tokens + or seq_end < block + ): + return + boundary = (seq_end // block) * block + if boundary <= seq_start or boundary > len(ctx.prompt_tokens): + return + previous = ctx.snapshot_candidate + if ( + isinstance(previous, _MtpBoundaryCandidate) + and previous.boundary_tokens >= boundary + ): + return + + # A backbone boundary at C tokens needs MTP pairs through C-1 and keeps + # hidden(token[C-1]) pending for the next token. ``normed`` spans + # [seq_start, seq_end), so the boundary row is available without replay. + if boundary <= 1 or ctx.folded < boundary - 1: + return + row = boundary - seq_start - 1 + if row < 0 or row >= int(normed.shape[1]): + return + try: + import mlx.core as mx + + candidate = _MtpBoundaryCandidate( + boundary_tokens=boundary, + pending_hidden=normed[:, row : row + 1] + 0, + ) + mx.async_eval(candidate.pending_hidden) + except Exception as exc: + logger.debug("MTP prefix boundary capture failed closed: %s", exc) + return + ctx.snapshot_candidate = candidate + + +def _publish_boundary_candidate(ctx: _PrimeCtx) -> None: + candidate = ctx.snapshot_candidate + store = getattr(ctx.prefix_cache, "store_mtp_prefix_snapshot", None) + if not isinstance(candidate, _MtpBoundaryCandidate) or not callable(store): + return + try: + snapshot_cache = _cache_at_offset( + ctx.mtp_cache, candidate.boundary_tokens - 1 + ) + if snapshot_cache is None: + return + snapshot = _MtpPrefixSnapshot( + boundary_tokens=candidate.boundary_tokens, + mtp_cache=snapshot_cache, + pending_hidden=candidate.pending_hidden, + ) + arrays = _snapshot_arrays(snapshot) + if arrays: + import mlx.core as mx + + mx.async_eval(arrays) + stored = store( + list(ctx.prompt_tokens or ()), + snapshot.boundary_tokens, + snapshot, + extra_keys=ctx.extra_keys, + extra_key_token_start=ctx.extra_key_token_start, + extra_key_ranges=ctx.extra_key_ranges, + ) + except Exception as exc: + logger.debug("MTP prefix sidecar publish failed closed: %s", exc) + return + if stored: + logger.debug( + "MTP prompt history cached at %d-token boundary for %s", + snapshot.boundary_tokens, + ctx.request_id or "anonymous request", + ) + + def maybe_capture( host: Any, inputs: Any, normed: Any, cache: Optional[List[Any]] ) -> None: @@ -340,7 +679,7 @@ def maybe_capture( # not the absolute prompt offset: on a warm prefix cache only the # boundary remainder is ever folded, so a long-context request with a # small remainder is exactly the cheap case priming is for (#2909). - folded = ctx.folded if ctx is not None else 0 + folded = ctx.folded_this_request if ctx is not None else 0 if folded + seq_len > window: setattr( host, @@ -355,7 +694,19 @@ def maybe_capture( if seq_len <= 1: # A lone decode step cannot start a prompt timeline. return - ctx = _PrimeCtx(mtp_cache=host.make_mtp_cache()) + plan = _find_plan(host) + ctx = _PrimeCtx( + mtp_cache=host.make_mtp_cache(), + request_id=plan.request_id if plan is not None else None, + prompt_tokens=plan.prompt_tokens if plan is not None else None, + block_size=plan.block_size if plan is not None else 0, + prefix_cache=plan.prefix_cache if plan is not None else None, + extra_keys=plan.extra_keys if plan is not None else None, + extra_key_token_start=( + plan.extra_key_token_start if plan is not None else None + ), + extra_key_ranges=(plan.extra_key_ranges if plan is not None else None), + ) if not ctx.mtp_cache: return setattr(host, _CTX_ATTR, ctx) @@ -380,8 +731,15 @@ def maybe_capture( # on them, so the lm_head tail costs nothing. host.mtp_forward(pairs_hidden, pairs_tokens, ctx.mtp_cache, logits_keep=1) ctx.folded += int(pairs_tokens.shape[1]) + ctx.folded_this_request += int(pairs_tokens.shape[1]) ctx.pending_hidden = normed[:, -1:] ctx.expected_offset = offset_after + _capture_boundary_candidate( + ctx, + normed, + seq_start=offset_after - seq_len, + seq_end=offset_after, + ) # Materialize the head-cache buffers per chunk so the fold graph never # accumulates across a long prefill; the (1,1,H) pending row is evaluated # alongside so the chunk's full hidden can be freed. @@ -457,6 +815,7 @@ def take_primed( except Exception as exc: logger.debug("MTP priming discarded: seam fold failed: %s", exc) return None + _publish_boundary_candidate(ctx) return ctx.mtp_cache, ctx.folded + 1 @@ -470,6 +829,7 @@ def prime_ctx_stats(model: Any) -> Optional[int]: "HEAD_HIDDEN_POST_NORM", "priming_enabled", "prime_window", + "prepare_prefix_context", "suppress_capture", "maybe_capture", "take_primed", diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/cache.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/cache.py index 59a246879c..7e12a2e32d 100644 --- a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/cache.py +++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/cache.py @@ -232,6 +232,7 @@ def _dequantize_uniform(keys_tuple, values_tuple, length, group_size, bits): class QuantizedKVCache(_BaseCache): step = 256 + geometric_growth = False def __init__(self, group_size: int = 64, bits: int = 8): self.keys = None @@ -239,6 +240,7 @@ def __init__(self, group_size: int = 64, bits: int = 8): self.offset = 0 self.group_size = group_size self.bits = bits + self._geometric_capacity_managed = True def update_and_fetch(self, keys, values): B, n_kv_heads, num_steps, k_head_dim = keys.shape @@ -247,8 +249,16 @@ def update_and_fetch(self, keys, values): if self.keys is None or (prev + num_steps) > self.keys[0].shape[-2]: el_per_int = 8 * mx.uint32.size // self.bits - new_steps = (self.step + num_steps - 1) // self.step * self.step - shape = (B, n_kv_heads, new_steps) + if self.geometric_growth: + old_capacity = 0 if self.keys is None else self.keys[0].shape[-2] + needed = prev + num_steps + capacity = ((needed + self.step - 1) // self.step) * self.step + if old_capacity and self._geometric_capacity_managed: + capacity = max(capacity, 2 * old_capacity) + shape = (B, n_kv_heads, capacity) + else: + new_steps = (self.step + num_steps - 1) // self.step * self.step + shape = (B, n_kv_heads, new_steps) def init_quant(dim): return ( @@ -258,6 +268,10 @@ def init_quant(dim): ) def expand_quant(x): + if self.geometric_growth: + new_x = mx.zeros((*shape, x.shape[-1]), dtype=x.dtype) + new_x[..., :prev, :] = x[..., :prev, :] + return new_x new_x = mx.zeros((*shape, x.shape[-1]), dtype=x.dtype) return mx.concatenate([x, new_x], axis=-2) @@ -272,6 +286,8 @@ def expand_quant(x): ) else: self.keys, self.values = init_quant(k_head_dim), init_quant(v_head_dim) + if self.geometric_growth: + self._geometric_capacity_managed = True self.offset += num_steps @@ -295,6 +311,7 @@ def state(self): @state.setter def state(self, v): self.keys, self.values = v + self._geometric_capacity_managed = False @property def meta_state(self): @@ -336,30 +353,47 @@ def nbytes(self): class KVCache(_BaseCache): step = 256 + geometric_growth = False def __init__(self): self.keys = None self.values = None self.offset = 0 + self._geometric_capacity_managed = True def update_and_fetch(self, keys, values): prev = self.offset if self.keys is None or (prev + keys.shape[2]) > self.keys.shape[2]: B, n_kv_heads, _, k_head_dim = keys.shape v_head_dim = values.shape[3] - n_steps = (self.step + keys.shape[2] - 1) // self.step - k_shape = (B, n_kv_heads, n_steps * self.step, k_head_dim) - v_shape = (B, n_kv_heads, n_steps * self.step, v_head_dim) + if self.geometric_growth: + old_capacity = 0 if self.keys is None else self.keys.shape[2] + needed = prev + keys.shape[2] + capacity = ((needed + self.step - 1) // self.step) * self.step + if old_capacity and self._geometric_capacity_managed: + capacity = max(capacity, 2 * old_capacity) + else: + n_steps = (self.step + keys.shape[2] - 1) // self.step + capacity = n_steps * self.step + k_shape = (B, n_kv_heads, capacity, k_head_dim) + v_shape = (B, n_kv_heads, capacity, v_head_dim) new_k = mx.zeros(k_shape, keys.dtype) new_v = mx.zeros(v_shape, values.dtype) if self.keys is not None: - if prev % self.step != 0: - self.keys = self.keys[..., :prev, :] - self.values = self.values[..., :prev, :] - self.keys = mx.concatenate([self.keys, new_k], axis=2) - self.values = mx.concatenate([self.values, new_v], axis=2) + if self.geometric_growth: + new_k[..., :prev, :] = self.keys[..., :prev, :] + new_v[..., :prev, :] = self.values[..., :prev, :] + self.keys, self.values = new_k, new_v + else: + if prev % self.step != 0: + self.keys = self.keys[..., :prev, :] + self.values = self.values[..., :prev, :] + self.keys = mx.concatenate([self.keys, new_k], axis=2) + self.values = mx.concatenate([self.values, new_v], axis=2) else: self.keys, self.values = new_k, new_v + if self.geometric_growth: + self._geometric_capacity_managed = True self.offset += keys.shape[2] self.keys[..., prev : self.offset, :] = keys @@ -383,6 +417,7 @@ def state(self): def state(self, v): self.keys, self.values = v self.offset = self.keys.shape[2] + self._geometric_capacity_managed = False def is_trimmable(self): return True diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/hc_projection.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/hc_projection.py new file mode 100644 index 0000000000..d490d7eb07 --- /dev/null +++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/hc_projection.py @@ -0,0 +1,420 @@ +# SPDX-License-Identifier: Apache-2.0 + +"""Lossless one-dispatch Qwen4 hyperconnection input projection. + +The Metal arithmetic in this module is transcribed from MLX core at pinned +commit ``ceab91938`` (``mlx/backend/metal/kernels/quantized.h``): its first +320 rows use MLX's literal ``qmv_fast`` traversal and its final four rows use +the literal standalone-N=4 general ``qmv`` traversal. This preserves both raw +projection outputs while avoiding the two-dispatch canonical implementation. + +MLX is Copyright © 2023 Apple Inc. and licensed under the MIT License: + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +""" + +from __future__ import annotations + +import logging +import os + +import mlx.core as mx +import mlx.nn as nn + +logger = logging.getLogger(__name__) + +_HC_COUNT = 4 +_HIDDEN_SIZE = 2560 +_STREAM_WIDTH = _HC_COUNT * _HIDDEN_SIZE +_LOW_RANK = 320 +_GROUP_SIZE = 64 +_SUPPORTED_BITS = (4, 5, 6, 8) +_DISABLED = os.environ.get("OMLX_QWEN4_HC_HYBRID", "1").strip().lower() in { + "0", + "false", + "off", + "no", +} +_KERNEL = None +_RUNTIME_FAILED = False +_FAILURE_LOGGED = False + + +_HEADER = r""" +using namespace metal; + +template +inline constexpr short hc_pack_factor() { + return bits == 5 ? 8 : (bits == 6 ? 4 : 32 / bits); +} + +template +inline constexpr short hc_bytes_per_pack() { + constexpr int power_of_2_bits = (bits & (bits - 1)) == 0; + return power_of_2_bits ? 4 : (bits == 5 ? 5 : 3); +} + +template +inline float hc_load_vector(const device T* x, thread float* xt) { + float sum = 0.0f; + if (bits == 4) { + for (int i = 0; i < N; i += 4) { + sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + xt[i] = x[i]; + xt[i + 1] = x[i + 1] / 16.0f; + xt[i + 2] = x[i + 2] / 256.0f; + xt[i + 3] = x[i + 3] / 4096.0f; + } + } else if (bits == 5) { + for (int i = 0; i < N; i += 8) { + sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3] + + x[i + 4] + x[i + 5] + x[i + 6] + x[i + 7]; + xt[i] = x[i]; + xt[i + 1] = x[i + 1] / 32.0f; + xt[i + 2] = x[i + 2] / 4.0f; + xt[i + 3] = x[i + 3] / 128.0f; + xt[i + 4] = x[i + 4] / 16.0f; + xt[i + 5] = x[i + 5] / 2.0f; + xt[i + 6] = x[i + 6] / 64.0f; + xt[i + 7] = x[i + 7] / 8.0f; + } + } else if (bits == 6) { + for (int i = 0; i < N; i += 4) { + sum += x[i] + x[i + 1] + x[i + 2] + x[i + 3]; + xt[i] = x[i]; + xt[i + 1] = x[i + 1] / 64.0f; + xt[i + 2] = x[i + 2] / 16.0f; + xt[i + 3] = x[i + 3] / 4.0f; + } + } else if (bits == 8) { + for (int i = 0; i < N; ++i) { + sum += x[i]; + xt[i] = x[i]; + } + } + return sum; +} + +template +inline float hc_qdot( + const device uint8_t* w, + const thread float* xt, + float scale, + float bias, + float sum) { + float accum = 0.0f; + if (bits == 4) { + const device uint16_t* ws = (const device uint16_t*)w; + for (int i = 0; i < N / 4; ++i) { + accum += + (xt[4 * i] * (ws[i] & 0x000f) + + xt[4 * i + 1] * (ws[i] & 0x00f0) + + xt[4 * i + 2] * (ws[i] & 0x0f00) + + xt[4 * i + 3] * (ws[i] & 0xf000)); + } + } else if (bits == 5) { + for (int i = 0; i < N / 8; ++i) { + xt += 8 * i; + w += 5 * i; + accum += (w[0] & 0x1f) * xt[0]; + accum += (w[0] & 0xe0) * xt[1]; + accum += (w[1] & 0x3) * (xt[1] * 256.0f); + accum += (w[1] & 0x7c) * xt[2]; + accum += (w[1] & 0x80) * xt[3]; + accum += (w[2] & 0xf) * (xt[3] * 256.0f); + accum += (w[2] & 0xf0) * xt[4]; + accum += (w[3] & 0x1) * (xt[4] * 256.0f); + accum += (w[3] & 0x3e) * xt[5]; + accum += (w[3] & 0xc0) * xt[6]; + accum += (w[4] & 0x7) * (xt[6] * 256.0f); + accum += (w[4] & 0xf8) * xt[7]; + } + } else if (bits == 6) { + for (int i = 0; i < N / 4; ++i) { + xt += 4 * i; + w += 3 * i; + accum += (w[0] & 0x3f) * xt[0]; + accum += (w[0] & 0xc0) * xt[1]; + accum += (w[1] & 0x0f) * (xt[1] * 256.0f); + accum += (w[1] & 0xf0) * xt[2]; + accum += (w[2] & 0x03) * (xt[2] * 256.0f); + accum += (w[2] & 0xfc) * xt[3]; + } + } else if (bits == 8) { + for (int i = 0; i < N; ++i) accum += xt[i] * w[i]; + } + return scale * accum + sum * bias; +} + +template +inline float hc_qdot_safe( + const device uint8_t* w, + const thread float* xt, + float scale, + float bias, + float sum) { + float accum = 0.0f; + if (bits == 4) { + const device uint16_t* ws = (const device uint16_t*)w; + for (int i = 0; i < N / 4; ++i) { + accum += + (xt[4 * i] * (ws[i] & 0x000f) + + xt[4 * i + 1] * (ws[i] & 0x00f0) + + xt[4 * i + 2] * (ws[i] & 0x0f00) + + xt[4 * i + 3] * (ws[i] & 0xf000)); + } + } else if (bits == 5) { + for (int i = 0; i < N / 8; ++i) { + xt += 8 * i; + w += 5 * i; + accum += (w[0] & 0x1f) * xt[0]; + accum += (w[0] & 0xe0) * xt[1]; + accum += (w[1] & 0x3) * (xt[1] * 256.0f); + accum += (w[1] & 0x7c) * xt[2]; + accum += (w[1] & 0x80) * xt[3]; + accum += (w[2] & 0xf) * (xt[3] * 256.0f); + accum += (w[2] & 0xf0) * xt[4]; + accum += (w[3] & 0x1) * (xt[4] * 256.0f); + accum += (w[3] & 0x3e) * xt[5]; + accum += (w[3] & 0xc0) * xt[6]; + accum += (w[4] & 0x7) * (xt[6] * 256.0f); + accum += (w[4] & 0xf8) * xt[7]; + } + } else if (bits == 6) { + for (int i = 0; i < N / 4; ++i) { + xt += 4 * i; + w += 3 * i; + accum += (w[0] & 0x3f) * xt[0]; + accum += (w[0] & 0xc0) * xt[1]; + accum += (w[1] & 0x0f) * (xt[1] * 256.0f); + accum += (w[1] & 0xf0) * xt[2]; + accum += (w[2] & 0x03) * (xt[2] * 256.0f); + accum += (w[2] & 0xfc) * xt[3]; + } + } else if (bits == 8) { + for (int i = 0; i < N; ++i) accum += xt[i] * w[i]; + } + return scale * accum + sum * bias; +} +""" + + +_SOURCE = r""" + const uint tg = threadgroup_position_in_grid.y; + const uint sg = simdgroup_index_in_threadgroup; + const uint lane = thread_index_in_simdgroup; + constexpr int PF = hc_pack_factor(); + constexpr int BP = hc_bytes_per_pack(); + constexpr int GROUPS = K / 64; + constexpr int ROW_BYTES = K * BP / PF; + + if (tg < 40) { + constexpr int PPT = 2; + constexpr int VPT = PF * PPT; + constexpr int BLOCK = VPT * 32; + constexpr int SCALE_STEP = 64 / VPT; + const int out_row = int(tg) * 8 + int(sg) * 4; + const device uint8_t* wp = (const device uint8_t*)down_w + + out_row * ROW_BYTES + int(lane) * PPT * BP; + const device T* sp = down_s + out_row * GROUPS + + int(lane) / SCALE_STEP; + const device T* bp = down_b + out_row * GROUPS + + int(lane) / SCALE_STEP; + const device T* xp = x + int(lane) * VPT; + float result[4] = {0.0f}; + float xv[VPT]; + for (int k = 0; k < K; k += BLOCK) { + float sum = hc_load_vector(xp, xv); + for (int row = 0; row < 4; ++row) { + result[row] += hc_qdot( + wp + row * ROW_BYTES, + xv, + float(sp[row * GROUPS]), + float(bp[row * GROUPS]), + sum); + } + wp += BLOCK * BP / PF; + sp += BLOCK / 64; + bp += BLOCK / 64; + xp += BLOCK; + } + for (int row = 0; row < 4; ++row) { + result[row] = simd_sum(result[row]); + if (lane == 0) combined[out_row + row] = T(result[row]); + } + return; + } + + if (sg != 0) return; + constexpr int PPT = 1; + constexpr int VPT = PF; + constexpr int BLOCK = VPT * 32; + constexpr int SCALE_STEP = 64 / VPT; + const device uint8_t* wp = (const device uint8_t*)inject_w + + int(lane) * BP; + const device T* sp = inject_s + int(lane) / SCALE_STEP; + const device T* bp = inject_b + int(lane) / SCALE_STEP; + const device T* xp = x + int(lane) * VPT; + float result[4] = {0.0f}; + float xv[VPT]; + int k = 0; + for (; k < K - BLOCK; k += BLOCK) { + float sum = hc_load_vector(xp, xv); + for (int row = 0; row < 4; ++row) { + result[row] += hc_qdot( + wp + row * ROW_BYTES, + xv, + float(sp[row * GROUPS]), + float(bp[row * GROUPS]), + sum); + } + wp += BLOCK * BP / PF; + sp += BLOCK / 64; + bp += BLOCK / 64; + xp += BLOCK; + } + float sum = hc_load_vector(xp, xv); + for (int row = 0; row < 4; ++row) { + result[row] += hc_qdot_safe( + wp + row * ROW_BYTES, + xv, + float(sp[row * GROUPS]), + float(bp[row * GROUPS]), + sum); + result[row] = simd_sum(result[row]); + if (lane == 0) combined[320 + row] = T(result[row]); + } +""" + + +def _kernel(): + global _KERNEL + if _KERNEL is None: + _KERNEL = mx.fast.metal_kernel( + name="omlx_qwen4_hc_hybrid_qmv", + input_names=[ + "x", + "down_w", + "down_s", + "down_b", + "inject_w", + "inject_s", + "inject_b", + ], + output_names=["combined"], + header=_HEADER, + source=_SOURCE, + ensure_row_contiguous=True, + ) + return _KERNEL + + +def compatible_projections(down, injection) -> bool: + """Whether two raw Qwen4 projection banks match the native contract.""" + if _DISABLED: + return False + if not ( + type(down) is nn.QuantizedLinear + and type(injection) is nn.QuantizedLinear + and getattr(down, "group_size", None) + == getattr(injection, "group_size", None) + == _GROUP_SIZE + and getattr(down, "bits", None) == getattr(injection, "bits", None) + and getattr(down, "bits", None) in _SUPPORTED_BITS + and getattr(down, "mode", None) + == getattr(injection, "mode", None) + == "affine" + and "bias" not in down + and "bias" not in injection + ): + return False + tensors = tuple( + getattr(projection, name, None) + for projection in (down, injection) + for name in ("weight", "scales", "biases") + ) + if not all(isinstance(value, mx.array) for value in tensors): + return False + packed_width = _STREAM_WIDTH * down.bits // 32 + return bool( + down.weight.shape == (_LOW_RANK, packed_width) + and injection.weight.shape == (_HC_COUNT, packed_width) + and down.weight.dtype == injection.weight.dtype == mx.uint32 + and down.scales.shape == (_LOW_RANK, _STREAM_WIDTH // _GROUP_SIZE) + and injection.scales.shape + == (_HC_COUNT, _STREAM_WIDTH // _GROUP_SIZE) + and down.biases.shape == down.scales.shape + and injection.biases.shape == injection.scales.shape + and down.scales.dtype == down.biases.dtype == mx.bfloat16 + and injection.scales.dtype == injection.biases.dtype == mx.bfloat16 + ) + + +def hybrid_projection( + x: mx.array, + down, + injection, +) -> mx.array | None: + """Return exact concatenated ``down, inject`` output or fail closed.""" + global _RUNTIME_FAILED, _FAILURE_LOGGED + + if not ( + not _RUNTIME_FAILED + and isinstance(x, mx.array) + and x.shape == (1, 1, _STREAM_WIDTH) + and x.dtype == mx.bfloat16 + and compatible_projections(down, injection) + and mx.default_device() == mx.gpu + and mx.metal.is_available() + ): + return None + try: + return _kernel()( + inputs=[ + x, + down.weight, + down.scales, + down.biases, + injection.weight, + injection.scales, + injection.biases, + ], + template=[ + ("T", x.dtype), + ("BITS", down.bits), + ("K", _STREAM_WIDTH), + ], + grid=(32, 82, 1), + threadgroup=(32, 2, 1), + output_shapes=[(1, 1, _LOW_RANK + _HC_COUNT)], + output_dtypes=[x.dtype], + )[0] + except Exception as exc: # noqa: BLE001 - optional native path + _RUNTIME_FAILED = True + if not _FAILURE_LOGGED: + _FAILURE_LOGGED = True + logger.warning( + "Qwen4 exact hybrid HC projection failed closed; using " + "canonical split projections: %s", + exc, + ) + return None + + +__all__ = ["compatible_projections", "hybrid_projection"] 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 e8d0c31ca6..a6e998d199 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 @@ -24,12 +24,19 @@ _create_qwen3_5_attention_mask, _create_qwen3_5_ssm_mask, _target_verify_linear, + _target_verify_linears, ) from ..qwen3_5_moe.language import Qwen3_5MoeSparseMoeBlock from .config import ModelConfig, TextConfig +from .qsa_fast import ( + contiguous_causal_gathered_qsa, + contiguous_causal_gathered_qsa_decode, + pool_completed_index_keys, +) _PLE_RUNTIME_MODEL_PATH: Path | None = None _PLE_RUNTIME_MODE = "resident" +_HYPER_SPLIT_INDICES: dict[tuple[int, int], tuple[mx.array, mx.array]] = {} @dataclass(frozen=True) @@ -137,29 +144,245 @@ def _append_indexer_positions( return mx.concatenate([cached, position_ids], axis=-1) -class QSAKVCache(KVCache): +class _QSAIndexerCache: + """Capacity-backed raw and completed-block state shared by QSA caches. + + Raw keys and positions remain part of the public/persisted cache state. + The normalized, RoPE-rotated block bank is deliberately ephemeral: state + restore, row extraction/filtering, and rollback can rebuild it exactly from + those raw tensors without changing the serialized cache schema. + """ + + index_step = 8192 + + def _init_indexer_cache(self): + self._index_keys = None + self._index_position_ids = None + self._index_offset = 0 + self._index_capacity_managed = True + self._invalidate_pooled_indexer() + + @property + def index_keys(self): + if self._index_keys is None: + return None + return self._index_keys[:, : self._index_offset] + + @index_keys.setter + def index_keys(self, value): + self._index_keys = value + self._index_offset = 0 if value is None else int(value.shape[1]) + self._index_capacity_managed = False + self._invalidate_pooled_indexer() + + @property + def index_position_ids(self): + if self._index_position_ids is None: + return None + return self._index_position_ids[..., : self._index_offset] + + @index_position_ids.setter + def index_position_ids(self, value): + self._index_position_ids = value + self._invalidate_pooled_indexer() + + def _restore_indexer_state(self, keys, position_ids): + if (keys is None) != (position_ids is None): + raise ValueError("QSA raw keys and positions must be restored together") + if keys is not None and ( + keys.ndim != 3 + or position_ids.ndim not in {2, 3} + or keys.shape[1] != position_ids.shape[-1] + ): + raise ValueError("Restored QSA raw keys and positions are misaligned") + self._index_keys = keys + self._index_position_ids = position_ids + self._index_offset = 0 if keys is None else int(keys.shape[1]) + self._index_capacity_managed = False + self._invalidate_pooled_indexer() + + @staticmethod + def _growth_capacity(current: int, needed: int, step: int) -> int: + stepped = ((needed + step - 1) // step) * step + return max(stepped, 2 * current if current else step) + + def _ensure_indexer_capacity( + self, + sample_keys: mx.array, + sample_positions: mx.array, + needed: int, + ) -> None: + if self._index_keys is None: + current = 0 + else: + current = min( + int(self._index_keys.shape[1]), + int(self._index_position_ids.shape[-1]), + ) + if needed <= current: + return + capacity = ((needed + self.index_step - 1) // self.index_step) * self.index_step + if current and self._index_capacity_managed: + capacity = max(capacity, 2 * current) + new_keys = mx.zeros( + (sample_keys.shape[0], capacity, sample_keys.shape[-1]), + dtype=sample_keys.dtype, + ) + if sample_positions.ndim == 3: + position_shape = ( + sample_positions.shape[0], + sample_positions.shape[1], + capacity, + ) + else: + position_shape = (sample_positions.shape[0], capacity) + new_positions = mx.zeros(position_shape, dtype=sample_positions.dtype) + if self._index_keys is not None and self._index_offset: + new_keys[:, : self._index_offset] = self._index_keys[ + :, : self._index_offset + ] + new_positions[..., : self._index_offset] = self._index_position_ids[ + ..., : self._index_offset + ] + self._index_keys = new_keys + self._index_position_ids = new_positions + self._index_capacity_managed = True + + def update_indexer(self, keys: mx.array, position_ids: mx.array): + if keys.ndim != 3 or position_ids.ndim not in {2, 3}: + raise ValueError("QSA index updates require [B,S,D] keys and positions") + length = int(keys.shape[1]) + if position_ids.shape[-1] != length: + raise ValueError("QSA index update keys and positions are misaligned") + + if self._index_position_ids is not None: + if self._index_position_ids.ndim == 3 and position_ids.ndim == 2: + position_ids = mx.broadcast_to( + position_ids[None], + (self._index_position_ids.shape[0], *position_ids.shape), + ) + elif self._index_position_ids.ndim == 2 and position_ids.ndim == 3: + # MRoPE promotion is rare. Collapse the old position backing to + # its logical prefix so the capacity grow below creates a + # writable three-coordinate allocation. + old_positions = self._index_position_ids[ + ..., : self._index_offset + ] + self._index_position_ids = mx.broadcast_to( + old_positions[None], + (position_ids.shape[0], *old_positions.shape), + ) + self._index_capacity_managed = False + elif self._index_position_ids.ndim != position_ids.ndim: + raise ValueError("QSA position rank changed incompatibly") + + end = self._index_offset + length + self._ensure_indexer_capacity(keys, position_ids, end) + self._index_keys[:, self._index_offset : end] = keys + self._index_position_ids[..., self._index_offset : end] = position_ids + self._index_offset = end + return self.index_keys, self.index_position_ids + + def _invalidate_pooled_indexer(self): + self._pooled_index_keys = None + self._pooled_index_offset = 0 + self._pooled_index_ratio = None + self._pooled_index_tag = None + + def pooled_indexer_keys( + self, + compress_ratio: int, + index_key_norm, + apply_index_rope, + *, + cache_tag=None, + ) -> mx.array: + """Return the completed block bank, computing only its new suffix.""" + + if self._index_keys is None or self._index_position_ids is None: + raise ValueError("QSA pooled keys require raw indexer state") + complete_blocks = self._index_offset // compress_ratio + if ( + self._pooled_index_ratio != compress_ratio + or self._pooled_index_tag is not cache_tag + or self._pooled_index_offset > complete_blocks + ): + self._invalidate_pooled_indexer() + self._pooled_index_ratio = compress_ratio + self._pooled_index_tag = cache_tag + + start_block = self._pooled_index_offset + if start_block < complete_blocks: + new_pooled = pool_completed_index_keys( + self.index_keys, + self.index_position_ids, + compress_ratio=compress_ratio, + index_key_norm=index_key_norm, + apply_index_rope=apply_index_rope, + start_block=start_block, + stop_block=complete_blocks, + ) + current_capacity = ( + 0 + if self._pooled_index_keys is None + else int(self._pooled_index_keys.shape[1]) + ) + if complete_blocks > current_capacity: + block_step = max(1, self.index_step // compress_ratio) + capacity = self._growth_capacity( + current_capacity, + complete_blocks, + block_step, + ) + new_buffer = mx.zeros( + (new_pooled.shape[0], capacity, new_pooled.shape[-1]), + dtype=new_pooled.dtype, + ) + if self._pooled_index_keys is not None and start_block: + new_buffer[:, :start_block] = self._pooled_index_keys[ + :, :start_block + ] + self._pooled_index_keys = new_buffer + self._pooled_index_keys[:, start_block:complete_blocks] = new_pooled + self._pooled_index_offset = complete_blocks + + if self._pooled_index_keys is None: + return mx.zeros( + (self._index_keys.shape[0], 0, self._index_keys.shape[-1]), + dtype=self._index_keys.dtype, + ) + return self._pooled_index_keys[:, : self._pooled_index_offset] + + def _trim_indexer(self, length: int): + self._index_offset = min(self._index_offset, max(0, int(length))) + self._invalidate_pooled_indexer() + + @property + def indexer_nbytes(self): + size = 0 + for array in ( + self._index_keys, + self._index_position_ids, + self._pooled_index_keys, + ): + if array is not None: + size += array.nbytes + return size + + +class QSAKVCache(_QSAIndexerCache, KVCache): """KV cache with the raw indexer keys and multimodal positions used by QSA.""" # Hybrid/TurboQuant caches do not currently expose a way to carry the # indexer's unprojected keys. Uniform quantization uses the specialized # QSAQuantizedKVCache below; other schemes leave this cache in float. preserve_auxiliary_kv_state = True + step = 8192 + geometric_growth = True def __init__(self): super().__init__() - self.index_keys = None - self.index_position_ids = None - - def update_indexer(self, keys: mx.array, position_ids: mx.array): - if self.index_keys is None: - self.index_keys = keys - self.index_position_ids = position_ids - else: - self.index_keys = mx.concatenate([self.index_keys, keys], axis=1) - self.index_position_ids = _append_indexer_positions( - self.index_position_ids, position_ids - ) - return self.index_keys, self.index_position_ids + self._init_indexer_cache() @property def state(self): @@ -174,33 +397,39 @@ def state(self): @state.setter def state(self, value): - self.keys, self.values, self.index_keys, self.index_position_ids = value + self.keys, self.values, index_keys, index_position_ids = value self.offset = 0 if self.keys is None else self.keys.shape[2] + self._geometric_capacity_managed = False + self._restore_indexer_state(index_keys, index_position_ids) def trim(self, n): n = min(self.offset, n) super().trim(n) - if self.index_keys is not None: - self.index_keys = self.index_keys[:, : self.offset] - self.index_position_ids = self.index_position_ids[..., : self.offset] + self._trim_indexer(self.offset) return n def extract(self, idx): cache = QSAKVCache() if self.keys is not None: - cache.keys = mx.contiguous(self.keys[idx : idx + 1]) - cache.values = mx.contiguous(self.values[idx : idx + 1]) + cache.keys = mx.contiguous( + self.keys[idx : idx + 1, :, : self.offset, :] + ) + cache.values = mx.contiguous( + self.values[idx : idx + 1, :, : self.offset, :] + ) cache.offset = self.offset + cache._geometric_capacity_managed = False if self.index_keys is not None: - cache.index_keys = mx.contiguous(self.index_keys[idx : idx + 1]) + index_keys = mx.contiguous(self.index_keys[idx : idx + 1]) if self.index_position_ids.ndim == 3: - cache.index_position_ids = mx.contiguous( + index_position_ids = mx.contiguous( self.index_position_ids[:, idx : idx + 1] ) else: - cache.index_position_ids = mx.contiguous( + index_position_ids = mx.contiguous( self.index_position_ids[idx : idx + 1] ) + cache._restore_indexer_state(index_keys, index_position_ids) return cache def filter(self, batch_indices): @@ -272,10 +501,7 @@ def to_quantized(self, group_size: int = 64, bits: int = 4): @property def nbytes(self): - size = super().nbytes - if self.index_keys is not None: - size += self.index_keys.nbytes + self.index_position_ids.nbytes - return size + return super().nbytes + self.indexer_nbytes class BatchQSAKVCache: @@ -510,26 +736,16 @@ def nbytes(self): return self.kv_cache.nbytes + extra -class QSAQuantizedKVCache(QuantizedKVCache): +class QSAQuantizedKVCache(_QSAIndexerCache, QuantizedKVCache): """Uniformly quantized QSA cache that retains float indexer state.""" preserve_auxiliary_kv_state = True + step = 8192 + geometric_growth = True def __init__(self, group_size: int = 64, bits: int = 8): super().__init__(group_size=group_size, bits=bits) - self.index_keys = None - self.index_position_ids = None - - def update_indexer(self, keys: mx.array, position_ids: mx.array): - if self.index_keys is None: - self.index_keys = keys - self.index_position_ids = position_ids - else: - self.index_keys = mx.concatenate([self.index_keys, keys], axis=1) - self.index_position_ids = _append_indexer_positions( - self.index_position_ids, position_ids - ) - return self.index_keys, self.index_position_ids + self._init_indexer_cache() @property def state(self): @@ -541,33 +757,41 @@ def state(self): @state.setter def state(self, value): - self.keys, self.values, self.index_keys, self.index_position_ids = value + self.keys, self.values, index_keys, index_position_ids = value self.offset = 0 if self.keys is None else self.keys[0].shape[2] + self._geometric_capacity_managed = False + self._restore_indexer_state(index_keys, index_position_ids) def trim(self, n): n = min(self.offset, n) super().trim(n) - if self.index_keys is not None: - self.index_keys = self.index_keys[:, : self.offset] - self.index_position_ids = self.index_position_ids[..., : self.offset] + self._trim_indexer(self.offset) return n def extract(self, idx): cache = QSAQuantizedKVCache(self.group_size, self.bits) if self.keys is not None: - cache.keys = tuple(mx.contiguous(x[idx : idx + 1]) for x in self.keys) - cache.values = tuple(mx.contiguous(x[idx : idx + 1]) for x in self.values) + cache.keys = tuple( + mx.contiguous(x[idx : idx + 1, :, : self.offset, :]) + for x in self.keys + ) + cache.values = tuple( + mx.contiguous(x[idx : idx + 1, :, : self.offset, :]) + for x in self.values + ) cache.offset = self.offset + cache._geometric_capacity_managed = False if self.index_keys is not None: - cache.index_keys = mx.contiguous(self.index_keys[idx : idx + 1]) + index_keys = mx.contiguous(self.index_keys[idx : idx + 1]) if self.index_position_ids.ndim == 3: - cache.index_position_ids = mx.contiguous( + index_position_ids = mx.contiguous( self.index_position_ids[:, idx : idx + 1] ) else: - cache.index_position_ids = mx.contiguous( + index_position_ids = mx.contiguous( self.index_position_ids[idx : idx + 1] ) + cache._restore_indexer_state(index_keys, index_position_ids) return cache def filter(self, batch_indices): @@ -584,9 +808,7 @@ def filter(self, batch_indices): @property def nbytes(self): size = 0 if self.keys is None else super().nbytes - if self.index_keys is not None: - size += self.index_keys.nbytes + self.index_position_ids.nbytes - return size + return size + self.indexer_nbytes class Qwen4ExpRMSNorm(nn.Module): @@ -725,19 +947,22 @@ def from_projected( query = self._apply_rope(query, position_ids) complete_key_len = max_complete_blocks * self.compress_ratio - pooled_keys = raw_keys[:, :complete_key_len].reshape( - batch, max_complete_blocks, self.compress_ratio, self.head_dim - ) - pooled_keys = mx.expand_dims( - self.k_layernorm( - mx.mean(pooled_keys.astype(mx.float32), axis=2).astype(raw_keys.dtype) - ), - axis=1, - ) - - block_starts = mx.arange(max_complete_blocks) * self.compress_ratio - block_position_ids = full_position_ids[..., block_starts] - pooled_keys = self._apply_rope(pooled_keys, block_position_ids) + if cache is not None and hasattr(cache, "pooled_indexer_keys"): + pooled_keys = cache.pooled_indexer_keys( + self.compress_ratio, + self.k_layernorm, + self._apply_rope, + cache_tag=self, + ) + else: + pooled_keys = pool_completed_index_keys( + raw_keys, + full_position_ids, + compress_ratio=self.compress_ratio, + index_key_norm=self.k_layernorm, + apply_index_rope=self._apply_rope, + ) + pooled_keys = mx.expand_dims(pooled_keys, axis=1) # Score in float32, as the reference does: which blocks win is a discrete # choice, and rounding the products flips the ones near the cut-off. @@ -800,6 +1025,278 @@ def __init__(self, config: TextConfig): self.k_norm = Qwen4ExpRMSNorm(self.head_dim, eps=config.rms_norm_eps) self.indexer = Qwen4ExpQSAIndexer(config, self.rotary_emb) + @staticmethod + def _batch_one_text_position_ids( + position_ids: Optional[mx.array], + length: int, + ) -> bool: + """Accept absent or shape-matched 2-D text positions, never MRoPE.""" + + return position_ids is None or bool( + isinstance(position_ids, mx.array) + and position_ids.ndim == 2 + and position_ids.shape == (1, length) + ) + + def _gathered_text_prefill_eligible( + self, + x: mx.array, + mask: Optional[mx.array], + cache: Optional[Any], + position_ids: Optional[mx.array], + position_embeddings: Optional[tuple[mx.array, mx.array]], + target_verify: bool, + ) -> bool: + """Fail closed outside the proven contiguous batch-one text shape.""" + + causal_mask = mask is None or (isinstance(mask, str) and mask == "causal") + if not ( + x.ndim == 3 + and x.shape[0] == 1 + and x.shape[1] > 1 + and causal_mask + and type(cache) is QSAKVCache + and isinstance(cache.offset, int) + and position_embeddings is None + and not target_verify + 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 + ) + + def _gathered_text_decode_eligible( + self, + x: mx.array, + mask: Optional[mx.array], + cache: Optional[Any], + position_ids: Optional[mx.array], + position_embeddings: Optional[tuple[mx.array, mx.array]], + target_verify: bool, + ) -> bool: + """Fail closed outside scalar-offset batch-one text decode.""" + + causal_mask = mask is None or (isinstance(mask, str) and mask == "causal") + if not ( + x.ndim == 3 + and x.shape[:2] == (1, 1) + and causal_mask + and type(cache) is QSAKVCache + and isinstance(cache.offset, int) + and position_embeddings is None + and not target_verify + and self._batch_one_text_position_ids(position_ids, 1) + ): + return False + + # A restored/foreign cache without aligned auxiliary indexer state must + # stay on the official path. The gathered arm cannot safely discover + # that mismatch after it has appended the new main K/V row. + if cache.offset: + if cache.index_keys is None or cache.index_position_ids is None: + return False + if ( + cache.index_keys.shape[1] != cache.offset + or cache.index_position_ids.shape[-1] != cache.offset + ): + return False + + prospective_blocks = (cache.offset + 1) // self.indexer.compress_ratio + return prospective_blocks > self.indexer.block_topk + + def _gathered_text_prefill( + self, + x: mx.array, + cache: QSAKVCache, + position_ids: Optional[mx.array] = None, + ) -> mx.array: + """Project once, append both caches, and attend only to selected K/V.""" + + batch, length, _ = x.shape + q_proj_output, keys, values = _target_verify_linears( + (self.q_proj, self.k_proj, self.v_proj), + x, + False, + ) + queries, gate = mx.split( + q_proj_output.reshape(batch, length, self.num_attention_heads, -1), + 2, + axis=-1, + ) + gate = gate.reshape(batch, length, -1) + queries = self.q_norm(queries).transpose(0, 2, 1, 3) + keys = self.k_norm( + keys.reshape(batch, length, self.num_key_value_heads, self.head_dim) + ).transpose(0, 2, 1, 3) + values = values.reshape( + batch, length, self.num_key_value_heads, self.head_dim + ).transpose(0, 2, 1, 3) + + past_len = cache.offset + if position_ids is None: + text_position_ids = mx.arange( + past_len, past_len + length, dtype=mx.int32 + )[None] + rotary_position_ids = mx.broadcast_to( + text_position_ids, + (3, batch, length), + ) + else: + text_position_ids = position_ids + rotary_position_ids = position_ids + queries, keys = self.rotary_emb.apply_rotary( + queries, + keys, + rotary_position_ids, + unsqueeze_dim=1, + ) + keys, values = cache.update_and_fetch(keys, values) + + projected = self.indexer.index_qk_proj(x).reshape( + batch, + length, + self.indexer.n_heads + self.indexer.kv_heads, + self.indexer.head_dim, + ) + index_queries = self.indexer.q_layernorm( + projected[:, :, : self.indexer.n_heads] + ).transpose(0, 2, 1, 3) + raw_index_keys = projected[:, :, self.indexer.n_heads :].squeeze(2) + raw_index_keys, full_position_ids = cache.update_indexer( + raw_index_keys, + text_position_ids, + ) + pooled_index_keys = cache.pooled_indexer_keys( + self.indexer.compress_ratio, + self.indexer.k_layernorm, + self.indexer._apply_rope, + cache_tag=self.indexer, + ) + index_queries = self.indexer._apply_rope( + index_queries, + text_position_ids, + ).transpose(0, 2, 1, 3) + + output = contiguous_causal_gathered_qsa( + queries, + keys, + values, + index_queries, + raw_index_keys, + full_position_ids, + num_query_heads=self.num_attention_heads, + num_key_value_heads=self.num_key_value_heads, + head_dim=self.head_dim, + indexer_head_dim=self.indexer.head_dim, + compress_ratio=self.indexer.compress_ratio, + token_budget=self.indexer.token_budget, + index_key_norm=self.indexer.k_layernorm, + apply_index_rope=self.indexer._apply_rope, + pooled_index_keys=pooled_index_keys, + ) + output = output.reshape(batch, length, -1) + return self.o_proj(output * mx.sigmoid(gate)) + + def _gathered_text_decode( + self, + x: mx.array, + cache: QSAKVCache, + position_ids: Optional[mx.array] = None, + ) -> mx.array: + """Append one token and attend only to QSA-selected cached K/V rows.""" + + batch, length, _ = x.shape + q_proj_output, new_keys, new_values = _target_verify_linears( + (self.q_proj, self.k_proj, self.v_proj), + x, + False, + ) + queries, gate = mx.split( + q_proj_output.reshape(batch, length, self.num_attention_heads, -1), + 2, + axis=-1, + ) + gate = gate.reshape(batch, length, -1) + queries = self.q_norm(queries).transpose(0, 2, 1, 3) + new_keys = self.k_norm( + new_keys.reshape( + batch, + length, + self.num_key_value_heads, + self.head_dim, + ) + ).transpose(0, 2, 1, 3) + new_values = new_values.reshape( + batch, + length, + self.num_key_value_heads, + self.head_dim, + ).transpose(0, 2, 1, 3) + + past_len = cache.offset + if position_ids is None: + text_position_ids = mx.arange( + past_len, + past_len + 1, + dtype=mx.int32, + )[None] + rotary_position_ids = mx.broadcast_to( + text_position_ids, + (3, batch, length), + ) + else: + text_position_ids = position_ids + rotary_position_ids = position_ids + queries, new_keys = self.rotary_emb.apply_rotary( + queries, + new_keys, + rotary_position_ids, + unsqueeze_dim=1, + ) + keys, values = cache.update_and_fetch(new_keys, new_values) + + projected = self.indexer.index_qk_proj(x).reshape( + batch, + length, + self.indexer.n_heads + self.indexer.kv_heads, + self.indexer.head_dim, + ) + index_queries = self.indexer.q_layernorm( + projected[:, :, : self.indexer.n_heads] + ).transpose(0, 2, 1, 3) + raw_index_keys = projected[:, :, self.indexer.n_heads :].squeeze(2) + cache.update_indexer(raw_index_keys, text_position_ids) + pooled_index_keys = cache.pooled_indexer_keys( + self.indexer.compress_ratio, + self.indexer.k_layernorm, + self.indexer._apply_rope, + cache_tag=self.indexer, + ) + index_queries = self.indexer._apply_rope( + index_queries, + text_position_ids, + ).transpose(0, 2, 1, 3) + + output = contiguous_causal_gathered_qsa_decode( + queries, + keys, + values, + index_queries, + pooled_index_keys, + num_query_heads=self.num_attention_heads, + num_key_value_heads=self.num_key_value_heads, + head_dim=self.head_dim, + indexer_head_dim=self.indexer.head_dim, + compress_ratio=self.indexer.compress_ratio, + token_budget=self.indexer.token_budget, + ) + output = output.reshape(batch, length, -1) + return self.o_proj(output * mx.sigmoid(gate)) + def __call__( self, x: mx.array, @@ -809,6 +1306,26 @@ def __call__( position_embeddings: Optional[tuple[mx.array, mx.array]] = None, target_verify: bool = False, ) -> mx.array: + if self._gathered_text_decode_eligible( + x, + mask, + cache, + position_ids, + position_embeddings, + target_verify, + ): + return self._gathered_text_decode(x, cache, position_ids) + + if self._gathered_text_prefill_eligible( + x, + mask, + cache, + position_ids, + position_embeddings, + target_verify, + ): + return self._gathered_text_prefill(x, cache, position_ids) + qsa_mask = self.indexer( x, cache, @@ -842,6 +1359,7 @@ def __init__(self, config: TextConfig, use_combine: bool = True): super().__init__() self.hc_count = config.hc_count self.hidden_size = config.hidden_size + self.hc_lowrank = config.hc_lowrank hc_hidden_size = self.hc_count * self.hidden_size self.hc_norm = Qwen4ExpRMSNorm( hc_hidden_size, @@ -860,15 +1378,73 @@ def __init__(self, config: TextConfig, use_combine: bool = True): ) def __call__(self, hyper_input: mx.array, target_verify: bool = False): + compiled_forward = getattr(self, "_compiled_forward", None) + if ( + compiled_forward is not None + and not target_verify + and hyper_input.ndim == 3 + and hyper_input.shape[:2] == (1, 1) + and hyper_input.dtype == mx.bfloat16 + and not get_mtp_runtime().enabled + ): + return compiled_forward(hyper_input) + return self._forward(hyper_input, target_verify=target_verify) + + def _forward(self, hyper_input: mx.array, target_verify: bool = False): normed = self.hc_norm(hyper_input) - mix = nn.silu( - _target_verify_linear( + hybrid = None + if ( + getattr(self, "_omlx_exact_hybrid_projection", False) + and not target_verify + and hyper_input.shape == (1, 1, 10240) + and hyper_input.dtype == mx.bfloat16 + and not get_mtp_runtime().enabled + ): + from .hc_projection import hybrid_projection + + hybrid = hybrid_projection( + normed, self.input_mix_weight_down, + self.block_inject_weight, + ) + input_inject_weight = getattr(self, "input_inject_weight", None) + if hybrid is not None: + mix = hybrid[..., : self.hc_lowrank] + block_injection = hybrid[ + ..., self.hc_lowrank : self.hc_lowrank + self.hc_count + ] + elif input_inject_weight is None: + mix = _target_verify_linear( + self.input_mix_weight_down, normed, target_verify + ) + block_injection = ( + _target_verify_linear( + self.block_inject_weight, normed, target_verify + ) + if "block_inject_weight" in self + else None + ) + else: + combined = _target_verify_linear( + input_inject_weight, normed, target_verify, ) - / self.hc_count - ) + indices = _HYPER_SPLIT_INDICES.get((self.hc_lowrank, self.hc_count)) + if indices is None: + indices = ( + mx.arange(self.hc_lowrank, dtype=mx.int32), + mx.arange( + self.hc_lowrank, + self.hc_lowrank + self.hc_count, + dtype=mx.int32, + ), + ) + _HYPER_SPLIT_INDICES[(self.hc_lowrank, self.hc_count)] = indices + mix = mx.take(combined, indices[0], axis=-1) + block_injection = mx.take(combined, indices[1], axis=-1) + + mix = nn.silu(mix / self.hc_count) mix = mx.sigmoid( _target_verify_linear( self.input_mix_weight_up, @@ -879,19 +1455,126 @@ def __call__(self, hyper_input: mx.array, target_verify: bool = False): mix = mix.reshape(*mix.shape[:-1], self.hc_count, self.hidden_size) streams = normed.reshape(*normed.shape[:-1], self.hc_count, self.hidden_size) mixed_input = mx.mean(mix * streams, axis=-2) - if "block_inject_weight" not in self: + if block_injection is None: return mixed_input injection_weights = 2 * mx.sigmoid( - _target_verify_linear( - self.block_inject_weight, - normed, - target_verify, - ) - / self.hc_count + block_injection / self.hc_count ) return mixed_input, hyper_input, injection_weights +def _matching_projection_tensor(left: nn.Module, right: nn.Module, name: str) -> bool: + left_has = hasattr(left, name) + right_has = hasattr(right, name) + if left_has != right_has: + return False + if not left_has: + return True + + left_value = getattr(left, name) + right_value = getattr(right, name) + if left_value is None or right_value is None: + return left_value is None and right_value is None + return ( + isinstance(left_value, mx.array) + and isinstance(right_value, mx.array) + and left_value.ndim > 0 + and left_value.ndim == right_value.ndim + and left_value.shape[1:] == right_value.shape[1:] + and left_value.dtype == right_value.dtype + ) + + +def _can_fuse_hyper_connection(module: Qwen4ExpGatedResidual) -> bool: + """Fail closed unless both projections have identical MLX semantics.""" + if type(module) is not Qwen4ExpGatedResidual: + return False + if ( + hasattr(module, "input_inject_weight") + or hasattr(module, "_compiled_forward") + or getattr(module, "_omlx_exact_hybrid_projection", False) + ): + return False + + down = getattr(module, "input_mix_weight_down", None) + injection = getattr(module, "block_inject_weight", None) + if down is None or injection is None or type(down) is not type(injection): + return False + if type(down) not in (nn.Linear, nn.QuantizedLinear): + return False + if not _matching_projection_tensor(down, injection, "weight"): + return False + if ( + down.weight.shape[0] != module.hc_lowrank + or injection.weight.shape[0] != module.hc_count + ): + return False + for attribute in ("group_size", "bits", "mode"): + if getattr(down, attribute, None) != getattr(injection, attribute, None): + return False + return all( + _matching_projection_tensor(down, injection, name) + for name in ("scales", "biases", "bias") + ) + + +def _can_prepare_exact_hybrid(module: Qwen4ExpGatedResidual) -> bool: + if not ( + module.hc_count == 4 + and module.hidden_size == 2560 + and module.hc_lowrank == 320 + ): + return False + from .hc_projection import compatible_projections + + return compatible_projections( + module.input_mix_weight_down, + module.block_inject_weight, + ) + + +def _unique_hyper_connections(model: nn.Module): + modules = [model] + modules.extend(module for _, module in model.named_modules() if module is not model) + seen = set() + for module in modules: + if id(module) in seen: + continue + seen.add(id(module)) + if type(module) is Qwen4ExpGatedResidual: + yield module + + +def fuse_hyper_connection_projections(model: nn.Module) -> int: + """Prepare the lossless one-dispatch Qwen4 decode projection. + + The tempting 324-row concatenation was rejected because MLX changes its + QMV traversal at that width and can change raw BF16 outputs. The raw + 320-row low-rank and four-row injection banks deliberately remain separate + so every fallback retains the checkpoint's canonical two projections. + """ + targets = [ + module + for module in _unique_hyper_connections(model) + if _can_fuse_hyper_connection(module) + and _can_prepare_exact_hybrid(module) + ] + for module in targets: + module._omlx_exact_hybrid_projection = True + return len(targets) + + +def compile_hyper_connections(model: nn.Module) -> int: + """Compile each hyper-connection's strict single-token decode path once.""" + compiled = 0 + for module in _unique_hyper_connections(model): + if hasattr(module, "_compiled_forward"): + continue + module._compiled_forward = mx.compile(module._forward) + compiled += 1 + return compiled + + _MASK64 = (1 << 64) - 1 _SPLITMIX_GAMMA = 0x9E3779B97F4A7C15 _SPLITMIX_M1 = 0xBF58476D1CE4E5B9 @@ -1238,6 +1921,10 @@ def __init__(self, num_embeddings: int, dims: int, num_shards: int): self.dims = dims def __call__(self, indices: mx.array) -> mx.array: + fused = getattr(self, "fused", None) + if fused is not None: + return fused(indices) * self.weight_scale + flat = indices.reshape(-1) # One tiny host sync avoids scheduling gathers against all 128 giant # PLE shards for every token. @@ -1272,6 +1959,92 @@ def __call__(self, indices: mx.array) -> mx.array: result = result.at[positions].add(values) return result.reshape(*indices.shape, self.dims) + def fuse_quantized_shards(self) -> bool: + """Join compatible packed shards without dequantizing the PLE table. + + Resident Qwen4 PLE otherwise synchronizes token IDs to the host before + every lookup so it can choose among 128 enormous shard buffers. A + single packed embedding keeps exactly the same affine rows while making + the lookup a normal device-side gather. The caller owns the temporary + peak-memory admission check required while old and joined buffers + coexist. + """ + + if getattr(self, "fused", None) is not None: + return False + shards = list(self.shards) + if not shards or not all( + type(shard) is nn.QuantizedEmbedding for shard in shards + ): + return False + first = shards[0] + if not all( + shard.dims == first.dims + and shard.group_size == first.group_size + and shard.bits == first.bits + and shard.mode == first.mode + and shard.weight.dtype == first.weight.dtype + and shard.scales.dtype == first.scales.dtype + and (shard.biases is None) == (first.biases is None) + and (shard.biases is None or shard.biases.dtype == first.biases.dtype) + for shard in shards + ): + return False + + total_rows = sum(int(shard.weight.shape[0]) for shard in shards) + if total_rows != self.shard_offsets[-1] or first.dims != self.dims: + return False + + fused = nn.QuantizedEmbedding( + 1, + self.dims, + group_size=first.group_size, + bits=first.bits, + mode=first.mode, + ) + fused.weight = mx.concatenate([shard.weight for shard in shards], axis=0) + fused.scales = mx.concatenate([shard.scales for shard in shards], axis=0) + if first.biases is None: + fused.biases = None + else: + fused.biases = mx.concatenate([shard.biases for shard in shards], axis=0) + fused.num_embeddings = total_rows + arrays = [fused.weight, fused.scales] + if fused.biases is not None: + arrays.append(fused.biases) + mx.eval(*arrays) + self.fused = fused + self.shards = [] + return True + + +def fuse_resident_ple_embeddings( + model: nn.Module, + *, + minimum_physical_memory: int = 192 * 1024**3, +) -> int: + """Fuse resident affine PLE shards only where the temporary peak is safe.""" + + if get_ple_runtime_mode() != "resident": + return 0 + physical_memory = os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES") + if physical_memory < minimum_physical_memory: + return 0 + + fused = 0 + language_model = getattr(model, "language_model", None) + layers = getattr(getattr(language_model, "model", None), "layers", ()) + for layer in layers: + ple = getattr(layer, "ple", None) + embedding = getattr( + getattr(ple, "ple_embedding", None), + "ngram_embedding", + None, + ) + if type(embedding) is ShardedEmbedding and embedding.fuse_quantized_shards(): + fused += 1 + return fused + class Qwen4ExpNGramEmbedding(nn.Module): def __init__( diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/qsa_fast.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/qsa_fast.py new file mode 100644 index 0000000000..8dd799ea91 --- /dev/null +++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/qsa_fast.py @@ -0,0 +1,697 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Exact gathered QSA prefill for contiguous batch-one text prompts. + +This is the exact path proven by Fusion's native Qwen4-Exp bring-up. It never +constructs the full ``[query_tokens, key_tokens]`` main-attention matrix: QSA +selects complete four-token micro-blocks, then the production native kernel +reads those rows directly from K/V. Portable MLX gathers only the selected +rows (plus the incomplete causal tail) when that narrow ABI is unavailable. + +The caller owns eligibility. In particular, this module is only used for a +single contiguous text prompt. Batched, padded, multimodal and target-verify +requests stay on mlx-vlm's general QSA implementation. +""" + +from __future__ import annotations + +import math +from collections.abc import Callable + +import mlx.core as mx + + +IndexKeyNorm = Callable[[mx.array], mx.array] +IndexRoPE = Callable[[mx.array, mx.array], mx.array] + + +_NATIVE_QSA_SCORE_DISABLED = False +_NATIVE_QSA_SCORE_PROVEN = False +_NATIVE_QSA_TOPK_DISABLED = False +_NATIVE_QSA_TOPK_PROVEN = False +_NATIVE_QSA_MAIN_DISABLED = False +_NATIVE_QSA_MAIN_PROVEN = False + + +def contiguous_causal_query_chunk(key_tokens: int) -> int: + """Keep long-context score sheets bounded without tiny launch overhead.""" + + if key_tokens <= 4096: + return 32 + if key_tokens <= 16384: + return 64 + return 128 + + +def _batch_gather_tokens(values: mx.array, indices: mx.array) -> mx.array: + """Gather token rows independently for every batch without a host read.""" + + batch, tokens = values.shape[:2] + trailing = values.shape[2:] + offset_shape = (batch,) + (1,) * (indices.ndim - 1) + offsets = mx.arange(batch, dtype=mx.int32).reshape(offset_shape) * tokens + flat_indices = (indices.astype(mx.int32) + offsets).reshape(-1) + flat_values = values.reshape(batch * tokens, *trailing) + return flat_values[flat_indices].reshape(*indices.shape, *trailing) + + +def _portable_indexer_scores( + queries: mx.array, + pooled_keys: mx.array, + head_dim: int, +) -> mx.array: + """Current float32 MLX QSA score reference.""" + + batch, query_tokens, query_heads, _ = queries.shape + # Flatten the query-token and index-head axes so MLX emits one FP32 GEMM + # for the chunk instead of a broadcasted batch of tiny matmuls. Each + # output dot product and the following head reduction are unchanged. + scores = ( + queries.astype(mx.float32).reshape( + batch, query_tokens * query_heads, head_dim + ) + @ pooled_keys.astype(mx.float32).swapaxes(-1, -2) + ).reshape(batch, query_tokens, query_heads, pooled_keys.shape[1]) + return mx.sum(mx.maximum(scores, 0), axis=-2) / math.sqrt(head_dim) + + +def pool_completed_index_keys( + index_keys: mx.array, + index_position_ids: mx.array, + *, + compress_ratio: int, + index_key_norm: IndexKeyNorm, + apply_index_rope: IndexRoPE, + start_block: int = 0, + stop_block: int | None = None, +) -> mx.array: + """Pool, normalize, and rotate a contiguous range of complete QSA blocks.""" + + if index_keys.ndim != 3: + raise ValueError("QSA raw index keys must have shape [B, S, D]") + if compress_ratio <= 0: + raise ValueError("QSA compression ratio must be positive") + complete_blocks = index_keys.shape[1] // compress_ratio + if stop_block is None: + stop_block = complete_blocks + if not 0 <= start_block <= stop_block <= complete_blocks: + raise ValueError( + "QSA pooled block range must lie within the complete raw-key prefix" + ) + if index_position_ids.ndim not in {2, 3} or ( + index_position_ids.shape[-1] != index_keys.shape[1] + ): + raise ValueError("QSA index positions do not match raw index keys") + + block_count = stop_block - start_block + raw_start = start_block * compress_ratio + raw_stop = stop_block * compress_ratio + pooled = index_keys[:, raw_start:raw_stop].reshape( + index_keys.shape[0], + block_count, + compress_ratio, + index_keys.shape[-1], + ) + pooled = mx.mean(pooled.astype(mx.float32), axis=-2).astype(index_keys.dtype) + pooled = index_key_norm(pooled) + block_starts = mx.arange( + raw_start, + raw_stop, + compress_ratio, + dtype=mx.int32, + ) + pooled_positions = index_position_ids[..., block_starts] + return apply_index_rope(pooled[:, None], pooled_positions)[:, 0] + + +def _native_indexer_scores( + queries: mx.array, + pooled_keys: mx.array, + *, + head_dim: int, + compress_ratio: int, + mask_q_offset: int, +) -> mx.array | None: + """Use the narrow native M3 score ABI or fail closed to the MLX path.""" + + global _NATIVE_QSA_SCORE_DISABLED, _NATIVE_QSA_SCORE_PROVEN + if _NATIVE_QSA_SCORE_DISABLED: + return None + if ( + queries.ndim != 4 + or queries.shape[0] != 1 + or queries.shape[-2:] != (4, 128) + or pooled_keys.ndim != 3 + or pooled_keys.shape[0] != 1 + or pooled_keys.shape[-1] != 128 + or queries.dtype != pooled_keys.dtype + or queries.dtype not in {mx.float16, mx.bfloat16} + or head_dim != 128 + or compress_ratio != 4 + or mask_q_offset < 0 + ): + return None + + try: + from omlx.custom_kernels.glm_moe_dsa import fast + + if not fast.is_native_available() or not fast.has_symbol( + "qwen4_qsa_indexer_scores" + ): + _NATIVE_QSA_SCORE_DISABLED = True + return None + # The caller's [B,M,H,D] view transposes back to the GEMM-friendly + # [B,H,M,D] ABI. The native wrapper only copies when the resulting + # view is not row-contiguous (for example an offset query chunk). + scores = fast.qwen4_qsa_indexer_scores( + queries.transpose(0, 2, 1, 3), + pooled_keys[:, None], + mask_ratio=compress_ratio, + mask_q_offset=mask_q_offset, + ) + if not _NATIVE_QSA_SCORE_PROVEN: + # MLX primitives are lazy, so a missing Metal pipeline would not + # otherwise surface until the enclosing attention graph is + # evaluated and can no longer fall back. Pay one process-wide + # synchronization to prove the extension/pipeline pair. + mx.eval(scores) + _NATIVE_QSA_SCORE_PROVEN = True + return scores + except Exception: + # A stale binary or rejected ABI should cost one attempt per process. + # Shape misses were excluded above and remain eligible on later calls. + _NATIVE_QSA_SCORE_DISABLED = True + return None + + +def _native_topk_indices(scores: mx.array, topk: int) -> mx.array | None: + """Use Qwen's exact FP32 top-k ABI or fail closed to argpartition.""" + + global _NATIVE_QSA_TOPK_DISABLED, _NATIVE_QSA_TOPK_PROVEN + if _NATIVE_QSA_TOPK_DISABLED: + return None + if ( + scores.ndim != 3 + or scores.shape[0] != 1 + or scores.shape[1] < 1 + or scores.shape[2] < topk + or scores.dtype != mx.float32 + or topk != 512 + ): + return None + try: + from omlx.custom_kernels.glm_moe_dsa import fast + + if not fast.is_native_available() or not fast.has_symbol( + "qwen4_qsa_topk_indices" + ): + _NATIVE_QSA_TOPK_DISABLED = True + return None + indices = fast.qwen4_qsa_topk_indices(scores, topk=topk).astype(mx.int32) + if not _NATIVE_QSA_TOPK_PROVEN: + mx.eval(indices) + _NATIVE_QSA_TOPK_PROVEN = True + return indices + except Exception: + _NATIVE_QSA_TOPK_DISABLED = True + return None + + +def _native_sparse_gqa_attention( + queries: mx.array, + keys: mx.array, + values: mx.array, + selected_blocks: mx.array, + *, + q_offset: int, +) -> mx.array | None: + """Consume Qwen's selected rows directly in the exact native GQA kernel.""" + + global _NATIVE_QSA_MAIN_DISABLED, _NATIVE_QSA_MAIN_PROVEN + if _NATIVE_QSA_MAIN_DISABLED: + return None + if ( + queries.ndim != 4 + or queries.shape[0] != 1 + or queries.shape[1] != 24 + or queries.shape[-1] != 256 + or keys.ndim != 4 + or values.shape != keys.shape + or keys.shape[0] != 1 + or keys.shape[1] != 2 + or keys.shape[-1] != 256 + or queries.dtype != keys.dtype + or queries.dtype != values.dtype + or queries.dtype not in {mx.float16, mx.bfloat16} + or selected_blocks.ndim != 3 + or selected_blocks.shape != (1, queries.shape[2], 512) + or q_offset < 0 + or q_offset + queries.shape[2] > keys.shape[2] + ): + return None + try: + from omlx.custom_kernels.glm_moe_dsa import fast + + if not fast.is_native_available() or not fast.has_symbol( + "qwen4_qsa_sparse_gqa_attention" + ): + _NATIVE_QSA_MAIN_DISABLED = True + return None + native_blocks = mx.contiguous(selected_blocks.astype(mx.uint32)[:, None]) + output = fast.qwen4_qsa_sparse_gqa_attention( + queries, + keys, + values, + native_blocks, + queries.shape[-1] ** -0.5, + q_offset, + key_tile=64, + dimension_tile=64, + ) + if not _NATIVE_QSA_MAIN_PROVEN: + # Prove the rebuilt extension and Metal pipeline before the lazy + # graph advances cache state past a point where fallback is safe. + mx.eval(output) + _NATIVE_QSA_MAIN_PROVEN = True + return output.transpose(0, 2, 1, 3) + except Exception: + _NATIVE_QSA_MAIN_DISABLED = True + return None + + +def _decode_qsa_sdpa( + queries: mx.array, + keys: mx.array, + values: mx.array, + scale: float, +) -> mx.array: + """Run exact unmasked singleton SDPA through the narrow native seam. + + The gathered decode caller has already applied QSA selection, so there is + no causal or sparse mask left to interpret. Only the decode_fast ABI's + explicitly supported shape/dtype contract may use the native primitive; + missing/stale extensions and every other shape fail closed to MLX SDPA. + Inputs are made contiguous by the caller, avoiding a lazy layout failure + after the model caches have advanced. + """ + + try: + from omlx.custom_kernels.decode_fast import fast + + extension = getattr(fast, "_ext", None) + supported = getattr(extension, "sdpa_decode_supported", None) + if ( + bool(getattr(fast, "NATIVE_AVAILABLE", False)) + and supported is not None + and bool(supported(queries, keys, values)) + ): + return fast.sdpa_decode( + queries, + keys, + values, + scale, + causal=False, + ) + except Exception: + # Capability probing is eager and happens before a native primitive is + # added to the lazy graph, so this fallback cannot leave partial work. + pass + + return mx.fast.scaled_dot_product_attention( + queries, + keys, + values, + scale=scale, + ) + + +def contiguous_causal_gathered_qsa_decode( + queries: mx.array, + keys: mx.array, + values: mx.array, + index_queries: mx.array, + pooled_index_keys: mx.array, + *, + num_query_heads: int, + num_key_value_heads: int, + head_dim: int, + indexer_head_dim: int, + compress_ratio: int, + token_budget: int, +) -> mx.array: + """Run exact batch-one QSA decode over only the selected K/V rows. + + This is the singleton counterpart to :func:`contiguous_causal_gathered_qsa`. + The query is the final visible token, so every completed compressed block + is causal. QSA chooses ``token_budget / compress_ratio`` complete blocks; + their token rows are gathered in chronological order and the zero-to-three + incomplete tail rows are appended. Main attention therefore remains + bounded by ``token_budget + compress_ratio - 1`` instead of scanning a + dense full-length mask. + """ + + if queries.ndim != 4 or queries.shape[:3] != (1, num_query_heads, 1): + raise ValueError("gathered QSA decode requires [1, H, 1, D] queries") + if queries.shape[-1] != head_dim: + raise ValueError("QSA decode queries do not match the configured head dim") + if keys.ndim != 4 or values.shape != keys.shape: + raise ValueError("QSA decode K/V must be matching rank-four arrays") + if keys.shape[0] != 1 or keys.shape[1] != num_key_value_heads: + raise ValueError("QSA decode K/V do not match the configured head count") + if keys.shape[-1] != head_dim or keys.dtype != queries.dtype: + raise ValueError("QSA decode K/V dtype or head dim does not match queries") + if values.dtype != queries.dtype: + raise ValueError("QSA decode values must match the query dtype") + if ( + index_queries.ndim != 4 + or index_queries.shape[0] != 1 + or index_queries.shape[1] != 1 + or index_queries.shape[-1] != indexer_head_dim + ): + raise ValueError("QSA decode index queries must have shape [1, 1, H, D]") + if compress_ratio <= 0 or token_budget <= 0 or token_budget % compress_ratio: + raise ValueError("QSA decode token budget must contain complete blocks") + if num_query_heads % num_key_value_heads: + raise ValueError("QSA decode query heads must divide over K/V heads") + + key_tokens = int(keys.shape[2]) + max_blocks = key_tokens // compress_ratio + block_budget = token_budget // compress_ratio + if max_blocks <= block_budget: + raise ValueError("gathered QSA decode requires a sparse block crossover") + if pooled_index_keys.shape != (1, max_blocks, indexer_head_dim): + raise ValueError("QSA decode pooled index-key cache has the wrong shape") + + block_scores = _native_indexer_scores( + index_queries, + pooled_index_keys, + head_dim=indexer_head_dim, + compress_ratio=compress_ratio, + mask_q_offset=key_tokens - 1, + ) + if block_scores is None: + block_scores = _portable_indexer_scores( + index_queries, + pooled_index_keys, + indexer_head_dim, + ) + + selected_blocks = _native_topk_indices(block_scores, block_budget) + if selected_blocks is None: + selected_blocks = mx.argpartition( + block_scores, + kth=-block_budget, + axis=-1, + )[..., -block_budget:].astype(mx.int32) + # Argpartition/native radix order is not chronological. Sorting the + # selected set preserves the official key order for deterministic SDPA. + selected_blocks = mx.sort(selected_blocks, axis=-1) + selected_tokens = ( + selected_blocks[..., None] * compress_ratio + + mx.arange(compress_ratio, dtype=mx.int32) + ).reshape(1, block_budget * compress_ratio) + + complete_key_len = max_blocks * compress_ratio + if complete_key_len < key_tokens: + tail = mx.arange(complete_key_len, key_tokens, dtype=mx.int32)[None] + selected_tokens = mx.concatenate((selected_tokens, tail), axis=-1) + + key_rows = keys.transpose(0, 2, 1, 3) + value_rows = values.transpose(0, 2, 1, 3) + selected_keys = mx.contiguous( + _batch_gather_tokens(key_rows, selected_tokens).transpose(0, 2, 1, 3) + ) + selected_values = mx.contiguous( + _batch_gather_tokens(value_rows, selected_tokens).transpose(0, 2, 1, 3) + ) + output = _decode_qsa_sdpa( + queries, + selected_keys, + selected_values, + head_dim**-0.5, + ) + return output.transpose(0, 2, 1, 3) + + +def contiguous_causal_gathered_qsa( + queries: mx.array, + keys: mx.array, + values: mx.array, + index_queries: mx.array, + index_keys: mx.array, + index_position_ids: mx.array, + *, + num_query_heads: int, + num_key_value_heads: int, + head_dim: int, + indexer_head_dim: int, + compress_ratio: int, + token_budget: int, + index_key_norm: IndexKeyNorm, + apply_index_rope: IndexRoPE, + pooled_index_keys: mx.array | None = None, + query_chunk: int | None = None, +) -> mx.array: + """Run exact QSA over gathered K/V for one contiguous causal prompt. + + ``queries`` and ``keys`` must already carry their main-attention RoPE. + ``index_queries`` must likewise be normalized and RoPE-rotated. Raw + indexer keys remain unrotated because Qwen pools each complete micro-block + before applying its checkpoint k-norm and the block-start RoPE. + """ + + if queries.ndim != 4 or queries.shape[0] != 1 or queries.shape[2] <= 1: + raise ValueError( + "gathered QSA requires rank-four batch-one multi-token queries" + ) + batch, actual_query_heads, query_tokens, actual_head_dim = queries.shape + if actual_query_heads != num_query_heads or actual_head_dim != head_dim: + raise ValueError("QSA queries do not match the configured geometry") + if keys.ndim != 4 or values.shape != keys.shape: + raise ValueError("QSA keys and values must be matching rank-four arrays") + if keys.shape[0] != batch or keys.shape[1:] != ( + num_key_value_heads, + keys.shape[2], + head_dim, + ): + raise ValueError("QSA K/V do not match the configured geometry") + key_tokens = keys.shape[2] + if query_tokens > key_tokens: + raise ValueError("QSA query length cannot exceed cached key length") + if index_queries.ndim != 4 or index_queries.shape[:2] != ( + batch, + query_tokens, + ): + raise ValueError("QSA index queries do not match the current prompt") + if index_queries.shape[-1] != indexer_head_dim: + raise ValueError("QSA index queries have the wrong head dimension") + if index_keys.shape != (batch, key_tokens, indexer_head_dim): + raise ValueError("QSA raw index keys do not match cached K/V") + if ( + index_position_ids.ndim not in {2, 3} + or index_position_ids.shape[-1] != key_tokens + ): + raise ValueError("QSA index positions do not match cached K/V") + if compress_ratio <= 0 or token_budget <= 0 or token_budget % compress_ratio: + raise ValueError("QSA token budget must contain complete micro-blocks") + if num_query_heads % num_key_value_heads: + raise ValueError("QSA query heads must divide evenly over K/V heads") + + if query_chunk is None: + query_chunk = contiguous_causal_query_chunk(key_tokens) + # The direct-index main-attention kernel carries no per-query gathered + # K/V tensor, so a 256-row score tile stays comfortably bounded and + # halves Python/Metal dispatch overhead. Preserve the smaller portable + # tiles whenever the exact production ABI is absent. + if ( + queries.shape[1:] == (24, query_tokens, 256) + and keys.shape[1] == 2 + and queries.dtype in {mx.float16, mx.bfloat16} + and not _NATIVE_QSA_MAIN_DISABLED + ): + try: + from omlx.custom_kernels.glm_moe_dsa import fast + + if fast.is_native_available() and fast.has_symbol( + "qwen4_qsa_sparse_gqa_attention" + ): + query_chunk = max(query_chunk, 256) + except Exception: + pass + if query_chunk <= 0: + raise ValueError("QSA query chunk must be positive") + + ratio = compress_ratio + max_blocks = key_tokens // ratio + block_budget = token_budget // ratio + query_start = key_tokens - query_tokens + key_rows = keys.transpose(0, 2, 1, 3) + value_rows = values.transpose(0, 2, 1, 3) + + # A contiguous prompt shares the same block bank for every query. The + # caller can provide its cache of completed blocks; standalone users still + # get the exact one-shot construction. + if max_blocks: + if pooled_index_keys is None: + pooled = pool_completed_index_keys( + index_keys, + index_position_ids, + compress_ratio=ratio, + index_key_norm=index_key_norm, + apply_index_rope=apply_index_rope, + ) + else: + if pooled_index_keys.shape != (batch, max_blocks, indexer_head_dim): + raise ValueError("QSA pooled index-key cache has the wrong shape") + pooled = pooled_index_keys + else: + if pooled_index_keys is not None and pooled_index_keys.shape != ( + batch, + 0, + indexer_head_dim, + ): + raise ValueError("QSA pooled index-key cache has the wrong shape") + pooled = None + + outputs: list[mx.array] = [] + groups = num_query_heads // num_key_value_heads + for start in range(0, query_tokens, query_chunk): + stop = min(start + query_chunk, query_tokens) + chunk_tokens = stop - start + absolute_queries = query_start + mx.arange(start, stop, dtype=mx.int32) + visible_counts = mx.broadcast_to( + (absolute_queries + 1)[None], (batch, chunk_tokens) + ) + complete_counts = visible_counts // ratio + + if max_blocks: + chunk_index_queries = index_queries[:, start:stop] + block_scores = _native_indexer_scores( + chunk_index_queries, + pooled, + head_dim=indexer_head_dim, + compress_ratio=ratio, + mask_q_offset=query_start + start, + ) + if block_scores is None: + block_scores = _portable_indexer_scores( + chunk_index_queries, + pooled, + indexer_head_dim, + ) + valid_blocks = ( + mx.arange(max_blocks)[None, None, :] + < complete_counts[..., None] + ) + block_scores = mx.where( + valid_blocks, + block_scores, + mx.finfo(block_scores.dtype).min, + ) + + selected_width = min(max_blocks, block_budget) + canonical = mx.broadcast_to( + mx.arange(selected_width, dtype=mx.int32)[None, None], + (batch, chunk_tokens, selected_width), + ) + if max_blocks > block_budget: + ranked = _native_topk_indices(block_scores, block_budget) + if ranked is None: + ranked = mx.argpartition( + block_scores, + kth=-block_budget, + axis=-1, + )[..., -block_budget:].astype(mx.int32) + selected_block_rows = mx.where( + (complete_counts <= block_budget)[..., None], + canonical, + ranked, + ) + else: + selected_block_rows = canonical + + # The top-k set is unordered. Restore checkpoint/dense-mask token + # order before either the portable gathered SDPA or the direct + # native kernel performs its FP32 online-softmax reduction. + selected_block_rows = mx.sort(selected_block_rows, axis=-1) + + selected_count = mx.minimum(complete_counts, block_budget) + + native_output = _native_sparse_gqa_attention( + queries[:, :, start:stop], + keys, + values, + selected_block_rows, + q_offset=query_start + start, + ) + if native_output is not None: + outputs.append(native_output) + continue + + selected_indices = ( + selected_block_rows[..., None] * ratio + + mx.arange(ratio, dtype=mx.int32) + ).reshape(batch, chunk_tokens, selected_width * ratio) + selected_valid = mx.broadcast_to( + mx.arange(selected_width)[None, None, :, None] + < selected_count[..., None, None], + (batch, chunk_tokens, selected_width, ratio), + ).reshape(batch, chunk_tokens, selected_width * ratio) + else: + selected_indices = mx.zeros( + (batch, chunk_tokens, 0), dtype=mx.int32 + ) + selected_valid = mx.zeros( + (batch, chunk_tokens, 0), dtype=mx.bool_ + ) + + # The zero-to-three visible tokens after the final complete block are + # always retained by the published QSA contract. + tail_width = ratio - 1 + tail = complete_counts[..., None] * ratio + mx.arange( + tail_width, dtype=mx.int32 + ) + tail_valid = tail < visible_counts[..., None] + selected_indices = mx.concatenate((selected_indices, tail), axis=-1) + selected_valid = mx.concatenate((selected_valid, tail_valid), axis=-1) + + safe_selected = mx.where(selected_valid, selected_indices, 0).astype(mx.int32) + + selected_keys = _batch_gather_tokens(key_rows, safe_selected).transpose( + 0, 1, 3, 2, 4 + ) + selected_values = _batch_gather_tokens(value_rows, safe_selected).transpose( + 0, 1, 3, 2, 4 + ) + + chunk_queries = queries[:, :, start:stop].transpose(0, 2, 1, 3) + grouped_queries = chunk_queries.reshape( + batch, + chunk_tokens, + num_key_value_heads, + groups, + head_dim, + ) + scores = ( + grouped_queries.astype(mx.float32) + @ selected_keys.astype(mx.float32).swapaxes(-1, -2) + ) / math.sqrt(head_dim) + scores = mx.where( + selected_valid[:, :, None, None, :], + scores, + mx.finfo(scores.dtype).min, + ) + probabilities = mx.softmax(scores, axis=-1).astype(chunk_queries.dtype) + output = probabilities @ selected_values + outputs.append( + output.reshape(batch, chunk_tokens, num_query_heads, head_dim) + ) + + return mx.concatenate(outputs, axis=1) + + +__all__ = [ + "contiguous_causal_gathered_qsa", + "contiguous_causal_gathered_qsa_decode", + "contiguous_causal_query_chunk", + "pool_completed_index_keys", +] diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/qwen4_exp.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/qwen4_exp.py index 3f73d80715..2c0bb39b16 100644 --- a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/qwen4_exp.py +++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/qwen4_exp.py @@ -13,6 +13,9 @@ LanguageModel, Qwen4ExpMTPModule, Qwen4ExpRMSNorm, + compile_hyper_connections, + fuse_hyper_connection_projections, + fuse_resident_ple_embeddings, get_mtp_runtime, get_ple_runtime_mode, ) @@ -255,6 +258,31 @@ def stack_experts(prefix): _normalize_ones_centered_rmsnorm_weights(self, sanitized) return sanitized + def load_weights(self, weights, strict=True): + result = super().load_weights(weights, strict=strict) + mtp_enabled = get_mtp_runtime().enabled + hybrid = 0 if mtp_enabled else fuse_hyper_connection_projections(self) + fused_ple = fuse_resident_ple_embeddings(self) + compiled = compile_hyper_connections(self) + if mtp_enabled: + logger.info( + "Skipped Qwen4-Exp exact hybrid projections while " + "Lightning MTP target verification is enabled" + ) + logger.info( + "Enabled Qwen4-Exp hyper-connection optimizations: " + "%d exact hybrid projection pairs, %d compiled decode paths", + hybrid, + compiled, + ) + if fused_ple: + logger.info( + "Fused %d resident Qwen4-Exp PLE table into one packed " + "device-side embedding", + fused_ple, + ) + return result + def close(self): """Release external PLE mmap handles during oMLX model unload.""" for layer in self.language_model.model.layers: diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/vision.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/vision.py index 6cecf50677..14d1e9e788 100644 --- a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/vision.py +++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/vision.py @@ -1,3 +1,31 @@ +"""Qwen4 vision compatibility bridge for the pinned mlx-vlm revision. + +The ``VisionModel.__call__`` implementation below follows mlx-vlm commit +``1249c7d`` (PR #1982) and is used under mlx-vlm's MIT license: + +Copyright © 2025 Prince Canuma + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +""" + +import mlx.core as mx + from ..qwen3_vl import VisionModel as Qwen3VLVisionModel @@ -12,3 +40,60 @@ def __init__(self, config): finally: config.model_type = original_type self.model_type = original_type + + def __call__( + self, + hidden_states: mx.array, + grid_thw: mx.array, + **kwargs, + ) -> mx.array: + """Run the shared Qwen ViT with MLX-safe temporal repeat counts. + + oMLX currently pins mlx-vlm before upstream #1982. That revision + passes a scalar ``mx.array`` as ``mx.repeat(..., repeats=...)``, which + newer MLX releases reject. Qwen4-Exp inherits that tower for both + images and videos, so keep the upstream computation verbatim while + scalarizing only the temporal repeat count. This is the same fix + shipped by mlx-vlm commit 1249c7d. + """ + del kwargs + + hidden_states = self.patch_embed(hidden_states) + pos_embeds = self.fast_pos_embed_interpolate(grid_thw) + hidden_states = hidden_states + pos_embeds + rotary_pos_emb = self.rot_pos_emb(grid_thw) + + seq_len = hidden_states.shape[0] + hidden_states = hidden_states.reshape(seq_len, -1) + rotary_pos_emb = rotary_pos_emb.reshape(seq_len, -1) + + cu_seqlens = [] + for i in range(grid_thw.shape[0]): + spatial_seq_len = grid_thw[i, 1] * grid_thw[i, 2] + temporal_patches = int(grid_thw[i, 0]) + cu_seqlens.append(mx.repeat(spatial_seq_len, temporal_patches)) + + cu_seqlens = mx.concatenate(cu_seqlens) + cu_seqlens = mx.cumsum(cu_seqlens.astype(mx.int32), axis=0) + cu_seqlens = mx.pad( + cu_seqlens, + (1, 0), + mode="constant", + constant_values=0, + ) + + deepstack_feature_lists = [] + for layer_num, block in enumerate(self.blocks): + hidden_states = block( + hidden_states, + cu_seqlens=cu_seqlens, + rotary_pos_emb=rotary_pos_emb, + ) + if layer_num in self.deepstack_visual_indexes: + deepstack_feature = self.deepstack_merger_list[ + self.deepstack_visual_indexes.index(layer_num) + ](hidden_states) + deepstack_feature_lists.append(deepstack_feature) + + hidden_states = self.merger(hidden_states) + return hidden_states, deepstack_feature_lists diff --git a/omlx/patches/qwen35_gdn_prework.py b/omlx/patches/qwen35_gdn_prework.py index 73b280aa09..7950430668 100644 --- a/omlx/patches/qwen35_gdn_prework.py +++ b/omlx/patches/qwen35_gdn_prework.py @@ -28,12 +28,16 @@ import logging import mlx.core as mx +import mlx.nn as nn logger = logging.getLogger(__name__) _PATCHED = False _ENGAGED_LOGGED = False _KERNEL = None +_QWEN4_DECODE_KERNEL = None +_QWEN4_NORM_GATE_KERNEL = None +_QWEN4_DECODE_ENGAGED_LOGGED = False _SOURCE = """ uint lane = thread_position_in_threadgroup.x; @@ -99,6 +103,153 @@ """ +# Copyright (c) 2026 David Dalcu. The Qwen4 decode prework and norm-gate +# kernels below are adapted from ddalcu/mlx-serve's MIT-licensed +# ``src/transformer.zig`` at tag ``v26.8.11-pre-release.1``. Preserve this +# scoped notice with those kernels. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. +# +# Qwen4 decode-only continuation of the donor kernel. This is deliberately a +# separate ABI from the verify kernel above: the production Qwen4 recurrence +# consumes an FP32 forget gate, while the older donor stores that gate as BF16. +# Keeping distinct outputs lets this path match mlx-vlm's current arithmetic +# exactly instead of silently changing the recurrent state update. +_QWEN4_DECODE_HEADER = """ + inline float omlx_log1p(float x) { + float xp1 = 1.0f + x; + if (xp1 == metal::numeric_limits::max()) { + return metal::numeric_limits::max(); + } + if (xp1 == 1.0f) { + return x; + } + return x * (metal::log(xp1) / (xp1 - 1.0f)); + } +""" + + +_QWEN4_DECODE_SOURCE = """ + uint lane = thread_position_in_threadgroup.x; + uint logical_head = threadgroup_position_in_grid.z; + constexpr uint q_heads = uint(HK); + constexpr uint k_head_base = uint(HK); + constexpr uint v_head_base = 2 * uint(HK); + bool is_q = logical_head < q_heads; + bool is_k = logical_head >= k_head_base && logical_head < v_head_base; + uint head = is_q ? logical_head + : (is_k ? logical_head - k_head_base + : logical_head - v_head_base); + uint channel_base = is_q ? head * uint(DK) + : (is_k ? uint(HK) * uint(DK) + head * uint(DK) + : 2 * uint(HK) * uint(DK) + head * uint(DV)); + + T activated[4]; + float sumsq = 0.0f; + for (uint i = 0; i < 4; ++i) { + uint channel = channel_base + lane * 4 + i; + float acc = 0.0f; + for (uint tap = 0; tap < 3; ++tap) { + acc += float(conv_state[tap * uint(C) + channel]) + * float(conv_w[channel * 4 + tap]); + } + acc += float(qkv[channel]) * float(conv_w[channel * 4 + 3]); + const T conv = T(acc); + T sy = T(1) / (T(1) + metal::exp(metal::abs(conv))); + const T act = conv * ((conv < T(0)) ? sy : T(1) - sy); + activated[i] = act; + float value = float(act); + sumsq += value * value; + + // T=1: [old0, old1, old2, qkv] -> [old1, old2, qkv]. Each + // channel is owned by exactly one thread, so no synchronization is + // needed between these three stores. + conv_out[channel] = conv_state[uint(C) + channel]; + conv_out[uint(C) + channel] = conv_state[2 * uint(C) + channel]; + conv_out[2 * uint(C) + channel] = qkv[channel]; + } + + if (is_q || is_k) { + sumsq = simd_sum(sumsq); + float inv = metal::precise::rsqrt(sumsq / float(DK) + 1e-6f); + float scale = is_q ? float(q_scale) : float(k_scale); + uint out_base = head * uint(DK) + lane * 4; + for (uint i = 0; i < 4; ++i) { + // rms_norm returns T; multiplying by the Python scalar also + // returns T, so preserve both rounding sites. + const T rms = T(float(activated[i]) * inv); + const T value = T(float(rms) * scale); + if (is_q) { + q_out[out_base + i] = value; + } else { + k_out[out_base + i] = value; + } + } + } else { + uint out_base = head * uint(DV) + lane * 4; + for (uint i = 0; i < 4; ++i) { + v_out[out_base + i] = activated[i]; + } + if (lane == 0) { + const T bv = b_in[head]; + T by = T(1) / (T(1) + metal::exp(metal::abs(bv))); + beta_out[head] = (bv < T(0)) ? by : T(1) - by; + + // compute_g casts A_log to FP32 but keeps softplus(a+dt_bias) + // in BF16 before the FP32 multiply and outer exp. + const T apd = T(float(a_in[head]) + float(dt_bias[head])); + const T neg_abs = -metal::abs(apd); + const T exp_term = T(metal::precise::exp(float(neg_abs))); + const T log_term = T(omlx_log1p(float(exp_term))); + const T positive = metal::max(apd, T(0)); + const T sp = T(float(positive) + float(log_term)); + float ea = metal::precise::exp(float(A_log[head])); + g_out[head] = metal::precise::exp(-(ea * float(sp))); + } + } +""" + + +_QWEN4_NORM_GATE_SOURCE = """ + uint lane = thread_position_in_threadgroup.x; + uint head = threadgroup_position_in_grid.z; + uint base = head * uint(DV) + lane * 4; + float xs[4]; + float sumsq = 0.0f; + for (uint i = 0; i < 4; ++i) { + xs[i] = float(y[base + i]); + sumsq += xs[i] * xs[i]; + } + sumsq = simd_sum(sumsq); + float inv = metal::precise::rsqrt(sumsq / float(DV) + float(eps)); + for (uint i = 0; i < 4; ++i) { + // mx.fast.rms_norm materializes BF16 before Qwen4 casts it back to + // FP32 for the sigmoid product. + const T normed = norm_w[lane * 4 + i] * T(xs[i] * inv); + float zv = float(z[base + i]); + float sy = 1.0f / (1.0f + metal::precise::exp(metal::abs(zv))); + float sig = zv < 0.0f ? sy : 1.0f - sy; + out[base + i] = T(float(normed) * sig); + } +""" + + def _kernel(): global _KERNEL if _KERNEL is None: @@ -140,6 +291,252 @@ def gdn_prework_fused(qkv, conv_state, conv_w, q_scale, k_scale, hk, hv, dk, dv) return outs +def _qwen4_decode_kernel(): + global _QWEN4_DECODE_KERNEL + if _QWEN4_DECODE_KERNEL is None: + _QWEN4_DECODE_KERNEL = mx.fast.metal_kernel( + name="omlx_qwen4_gdn_decode_prework", + input_names=[ + "qkv", + "conv_state", + "conv_w", + "q_scale", + "k_scale", + "b_in", + "a_in", + "A_log", + "dt_bias", + ], + output_names=[ + "q_out", + "k_out", + "v_out", + "conv_out", + "g_out", + "beta_out", + ], + header=_QWEN4_DECODE_HEADER, + source=_QWEN4_DECODE_SOURCE, + ) + return _QWEN4_DECODE_KERNEL + + +def qwen4_decode_prework_fused( + qkv, + conv_state, + conv_w, + q_scale, + k_scale, + b, + a, + A_log, + dt_bias, + hk, + hv, + dk, + dv, +): + """Fuse the exact Qwen4 B1/T1 GDN prework into one Metal dispatch.""" + + c_dim = int(qkv.shape[-1]) + return _qwen4_decode_kernel()( + inputs=[ + qkv, + conv_state, + conv_w, + q_scale, + k_scale, + b, + a, + A_log, + dt_bias, + ], + template=[ + ("T", qkv.dtype), + ("HK", hk), + ("HV", hv), + ("DK", dk), + ("DV", dv), + ("C", c_dim), + ], + grid=(32, 1, 2 * hk + hv), + threadgroup=(32, 1, 1), + output_shapes=[ + (1, 1, hk, dk), + (1, 1, hk, dk), + (1, 1, hv, dv), + (1, 3, c_dim), + (1, 1, hv), + (1, 1, hv), + ], + output_dtypes=[ + qkv.dtype, + qkv.dtype, + qkv.dtype, + qkv.dtype, + mx.float32, + qkv.dtype, + ], + ) + + +def _qwen4_norm_gate_kernel(): + global _QWEN4_NORM_GATE_KERNEL + if _QWEN4_NORM_GATE_KERNEL is None: + _QWEN4_NORM_GATE_KERNEL = mx.fast.metal_kernel( + name="omlx_qwen4_gdn_decode_norm_gate", + input_names=["y", "z", "norm_w", "eps"], + output_names=["out"], + source=_QWEN4_NORM_GATE_SOURCE, + ) + return _QWEN4_NORM_GATE_KERNEL + + +def qwen4_decode_norm_gate_fused(y, z, norm_w, *, hv, dv, eps): + """Fuse Qwen4's BF16 RMSNorm + FP32 sigmoid-gate at B1/T1.""" + + return _qwen4_norm_gate_kernel()( + inputs=[y, z, norm_w, mx.array(eps, dtype=mx.float32)], + template=[ + ("T", y.dtype), + ("HV", hv), + ("DV", dv), + ], + grid=(32, 1, hv), + threadgroup=(32, 1, 1), + output_shapes=[(1, 1, hv * dv)], + output_dtypes=[y.dtype], + )[0] + + +def _qwen4_decode_recurrence(q, k, v, g, beta, state): + from mlx_lm.models.gated_delta import gated_delta_kernel + + return gated_delta_kernel(q, k, v, g, beta, state, None) + + +def _qwen4_decode_static_eligible(module) -> bool: + """Fail closed unless this is the shipped Qwen4 oQe decode geometry.""" + + conv_dim = 2 * 16 * 128 + 48 * 128 + if ( + type(module).__name__ != "Qwen4ExpGatedDeltaNet" + or type(module).__module__ != "mlx_vlm.models.qwen4_exp.language" + or module.training + or module.num_k_heads != 16 + or module.num_v_heads != 48 + or module.head_k_dim != 128 + or module.head_v_dim != 128 + or module.conv_kernel_size != 4 + ): + return False + + conv = getattr(module, "conv1d", None) + norm = getattr(module, "norm", None) + if ( + conv is None + or getattr(conv, "bias", None) is not None + or conv.weight.shape != (conv_dim, 4, 1) + or conv.weight.dtype != mx.bfloat16 + or norm is None + or getattr(norm, "activation", None) != "sigmoid" + or norm.weight.shape != (128,) + or norm.weight.dtype != mx.bfloat16 + or module.A_log.shape != (48,) + or module.A_log.dtype != mx.bfloat16 + or module.dt_bias.shape != (48,) + or module.dt_bias.dtype != mx.bfloat16 + ): + return False + + def canonical_projection(linear, rows, signatures): + if type(linear) is not nn.QuantizedLinear or linear.mode != "affine": + return False + signature = (linear.bits, linear.group_size) + if signature not in signatures: + return False + bits, group_size = signature + packed_cols = 2560 * bits // 32 + scale_cols = 2560 // group_size + return ( + linear.weight.shape == (rows, packed_cols) + and linear.weight.dtype == mx.uint32 + and linear.scales.shape == (rows, scale_cols) + and linear.scales.dtype == mx.bfloat16 + and linear.biases is not None + and linear.biases.shape == (rows, scale_cols) + and linear.biases.dtype == mx.bfloat16 + and "bias" not in linear + ) + + # The shipped oQe allocation is intentionally mixed per tensor. This + # kernel begins after those projections, so accept only the exact + # canonical layouts emitted by the converter rather than demanding that + # all four happen to share layer 0's q6/g64 allocation. + if not canonical_projection( + module.in_proj_qkv, + conv_dim, + {(4, 64), (5, 64), (6, 64)}, + ): + return False + for linear, rows in ( + (module.in_proj_z, 48 * 128), + (module.in_proj_b, 48), + (module.in_proj_a, 48), + ): + if not canonical_projection(linear, rows, {(5, 128), (6, 64)}): + return False + + out = module.out_proj + return ( + type(out) is nn.QuantizedLinear + and out.bits == 5 + and out.group_size == 128 + and out.mode == "affine" + and out.weight.shape == (2560, 960) + and out.weight.dtype == mx.uint32 + and out.scales.shape == (2560, 48) + and out.scales.dtype == mx.bfloat16 + and out.biases is not None + and out.biases.shape == (2560, 48) + and out.biases.dtype == mx.bfloat16 + and "bias" not in out + ) + + +def _qwen4_decode_dynamic_eligible( + module, + inputs, + mask, + cache, + gdn_sink, + target_verify, +) -> bool: + if ( + target_verify + or gdn_sink is not None + or mask is not None + or cache is None + or not isinstance(inputs, mx.array) + or inputs.shape != (1, 1, 2560) + or inputs.dtype != mx.bfloat16 + or getattr(cache, "lengths", None) is not None + or getattr(cache, "left_padding", None) is not None + ): + return False + conv_state = cache[0] + recurrent_state = cache[1] + return ( + isinstance(conv_state, mx.array) + and conv_state.shape == (1, 3, 10240) + and conv_state.dtype == mx.bfloat16 + and isinstance(recurrent_state, mx.array) + and recurrent_state.shape == (1, 48, 128, 128) + and recurrent_state.dtype == mx.float32 + and _qwen4_decode_static_eligible(module) + ) + + def apply_qwen35_gdn_prework_patch() -> bool: """Route the batch-1 target-verify GDN prework through the fused kernel. @@ -179,6 +576,7 @@ def apply_qwen35_gdn_prework_patch() -> bool: orig_call = cls.__call__ disabled = {"flag": False} + qwen4_decode_disabled = {"flag": False} def _eligible(self, inputs, mask, cache, gdn_sink, s_len): if gdn_sink is None or cache is None: @@ -207,6 +605,110 @@ def _eligible(self, inputs, mask, cache, gdn_sink, s_len): def patched_call(self, inputs, mask=None, cache=None, gdn_sink=None, target_verify=False): S = inputs.shape[1] + if ( + not qwen4_decode_disabled["flag"] + and _qwen4_decode_dynamic_eligible( + self, + inputs, + mask, + cache, + gdn_sink, + target_verify, + ) + ): + conv_state = cache[0] + recurrent_state = cache[1] + try: + mixed_qkv, z, b, a = q35._target_verify_linears( + ( + self.in_proj_qkv, + self.in_proj_z, + self.in_proj_b, + self.in_proj_a, + ), + inputs, + False, + ) + inv_scale = self.head_k_dim**-0.5 + q_scale = getattr(self, "_omlx_qwen4_decode_q_scale", None) + k_scale = getattr(self, "_omlx_qwen4_decode_k_scale", None) + if q_scale is None or k_scale is None: + q_scale = mx.array( + inv_scale * inv_scale, + dtype=mx.bfloat16, + ) + k_scale = mx.array(inv_scale, dtype=mx.bfloat16) + self._omlx_qwen4_decode_q_scale = q_scale + self._omlx_qwen4_decode_k_scale = k_scale + + q, k, v, next_conv_state, g, beta = ( + qwen4_decode_prework_fused( + mixed_qkv, + conv_state, + self.conv1d.weight, + q_scale, + k_scale, + b, + a, + self.A_log, + self.dt_bias, + self.num_k_heads, + self.num_v_heads, + self.head_k_dim, + self.head_v_dim, + ) + ) + out, next_recurrent_state = _qwen4_decode_recurrence( + q, + k, + v, + g, + beta, + recurrent_state, + ) + flat = qwen4_decode_norm_gate_fused( + out, + z, + self.norm.weight, + hv=self.num_v_heads, + dv=self.head_v_dim, + eps=self.norm.eps, + ) + result = q35._target_verify_linear( + self.out_proj, + flat, + False, + ) + + # Commit cache ownership only after every fallible graph + # construction step succeeded. This mirrors the verify + # route below and keeps a fallback from applying the token + # twice after a late error. + cache[0] = next_conv_state + cache[1] = next_recurrent_state + if hasattr(cache, "advance"): + cache.advance(1) + q35._qwen3_5_advance_left_padding_info(cache, 1) + q35._qwen3_5_advance_lengths_info(cache, 1) + + global _QWEN4_DECODE_ENGAGED_LOGGED + if not _QWEN4_DECODE_ENGAGED_LOGGED: + _QWEN4_DECODE_ENGAGED_LOGGED = True + logger.info( + "Qwen4 fused B1/T1 GDN decode prework and norm-gate " + "engaged" + ) + return result + except Exception: + cache[0] = conv_state + cache[1] = recurrent_state + qwen4_decode_disabled["flag"] = True + logger.warning( + "Qwen4 fused GDN decode arm failed; reverting to stock " + "for the rest of the process", + exc_info=True, + ) + if disabled["flag"] or not _eligible(self, inputs, mask, cache, gdn_sink, S): return orig_call(self, inputs, mask=mask, cache=cache, gdn_sink=gdn_sink, target_verify=target_verify) diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 87fd4fb5aa..4e0c38b8d5 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -2723,22 +2723,24 @@ def _align_block_size_with_rotating_window(self) -> None: self.config.paged_cache_block_size = target_block_size def _detect_qwen35_prefill_floor(self) -> int: - """Return the wide-prefill floor for the Qwen3.5 architecture family.""" + """Return the wide-prefill floor for Qwen hybrid architectures.""" try: model_type = str(getattr(self.model, "model_type", "") or "") if not model_type: model_type = str( getattr(getattr(self.model, "config", None), "model_type", "") or "" ) - if model_type.startswith("qwen3_5"): + if model_type.startswith(("qwen3_5", "qwen4_exp")): from .custom_kernels.nax import is_nax_available from .settings import get_system_memory if get_system_memory() >= 64 * 1024**3 and not is_nax_available(): # Measured on the 27B (M3 Ultra, 2026-08-17): chunk 4096 # beats the 2048 default +3.2% at 4k prompts / +1.0% at - # 16k; 8192 is flat versus 4096. Keep 2048 on NAX/M5, - # where wider prefill regresses throughput (#2880). + # 16k; 8192 is flat versus 4096. Qwen4's direct-index QSA + # likewise removes the selected-K/V memory reason for + # 2048-row tiles. Keep 2048 on NAX/M5, where wider Qwen + # prefill regresses throughput (#2880). return 4096 except Exception: logger.debug("qwen3_5 prefill floor probe failed", exc_info=True) @@ -8229,6 +8231,32 @@ def _prepare_prefix_cache_for_request(self, request: Request) -> None: # No paged SSD cache configured - process all tokens request.remaining_tokens = request.prompt_token_ids + # Lightning-MTP has a small prompt-history cache separate from the + # backbone KV restored above. Bind an exact full-block sidecar (when + # one exists) to this singleton timeline before any uncached suffix is + # forwarded. The hook is intentionally best-effort/fail-closed: + # ordinary inference and prefix reuse stay valid if MTP is disabled, + # the sidecar was evicted, or this model family does not support it. + try: + from .patches.mlx_lm_mtp import prompt_priming + + prompt_priming.prepare_prefix_context( + self.model, + request_id=request.request_id, + prompt_tokens=request.prompt_token_ids, + cached_tokens=request.cached_tokens, + prefix_cache=self.block_aware_cache, + extra_keys=request.vlm_extra_keys_for_cache, + extra_key_token_start=request.vlm_extra_key_token_start_for_cache, + extra_key_ranges=request.vlm_extra_key_ranges_for_cache, + ) + except Exception as exc: + logger.debug( + "MTP prefix-history preparation failed closed for %s: %s", + request.request_id, + exc, + ) + # Trace where this prompt diverges from recently stored cache # sequences: one INFO line for large re-prefills (#2333/#2349 # triage), decoded token context at DEBUG (issue #1003). diff --git a/pyproject.toml b/pyproject.toml index 1b8a1b3fe7..a9f98f143a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -262,6 +262,7 @@ include = ["omlx*"] ] "omlx.eval" = ["data/*.jsonl"] "omlx.custom_kernels.glm_moe_dsa" = ["*.metallib", "*.dylib", "*.so"] +"omlx.custom_kernels.decode_fast" = ["*.metallib", "*.dylib", "*.so"] "omlx.custom_kernels.minimax_m3" = ["*.metallib", "*.dylib", "*.so"] "omlx.custom_kernels.qwen35_prefill" = ["*.metallib", "*.dylib", "*.so"] diff --git a/setup.py b/setup.py index 22146dc54f..7d67bc6c60 100644 --- a/setup.py +++ b/setup.py @@ -54,6 +54,10 @@ def _custom_kernel_build_kwargs() -> dict: "omlx.custom_kernels.bonsai._ext", sourcedir="omlx/custom_kernels/bonsai/csrc", ), + extension.CMakeExtension( + "omlx.custom_kernels.decode_fast._ext", + sourcedir="omlx/custom_kernels/decode_fast/csrc", + ), extension.CMakeExtension( "omlx.custom_kernels.glm_moe_dsa._ext", sourcedir="omlx/custom_kernels/glm_moe_dsa/csrc", diff --git a/tests/test_decode_fast_sdpa.py b/tests/test_decode_fast_sdpa.py new file mode 100644 index 0000000000..c56733cf51 --- /dev/null +++ b/tests/test_decode_fast_sdpa.py @@ -0,0 +1,52 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Decode SDPA (decode_fast) matches mx.fast.scaled_dot_product_attention.""" + +import pytest +import mlx.core as mx + +fast = pytest.importorskip("omlx.custom_kernels.decode_fast.fast") + +@pytest.mark.skipif( + not fast.NATIVE_AVAILABLE, reason="native extension not built" +) +@pytest.mark.parametrize("dtype", [mx.float32, mx.bfloat16, mx.float16]) +@pytest.mark.parametrize( + "B,H,Hkv,qL,kL,D", + [ + (1, 8, 1, 1, 512, 128), + (1, 8, 1, 1, 4096, 128), + (1, 8, 1, 4, 2048, 128), # causal, gqa*qL = 32 (limit) + (1, 4, 4, 1, 1024, 64), # MHA + (2, 8, 2, 1, 1500, 96), # odd kL, head 96 + (1, 8, 1, 1, 777, 128), # odd kL 1-pass + (1, 16, 2, 1, 16384, 128), + ], +) +def test_matches_mx_fast(dtype, B, H, Hkv, qL, kL, D): + mx.random.seed(0) + q = mx.random.normal((B, H, qL, D)).astype(dtype) + k = mx.random.normal((B, Hkv, kL, D)).astype(dtype) + v = mx.random.normal((B, Hkv, kL, D)).astype(dtype) + scale = 1.0 / (D ** 0.5) + causal = qL > 1 + assert fast._ext.sdpa_decode_supported(q, k, v) + out = fast._ext.sdpa_decode(q, k, v, scale, causal) + if causal: + mask = mx.triu(mx.full((qL, kL), float("-inf")), k=kL - qL + 1) + mask = mask.astype(dtype) + ref = mx.fast.scaled_dot_product_attention(q, k, v, scale=scale, mask=mask) + else: + ref = mx.fast.scaled_dot_product_attention(q, k, v, scale=scale) + mx.eval(out, ref) + tol = 1e-5 if dtype == mx.float32 else 5e-3 + assert mx.allclose(out, ref, atol=tol, rtol=tol).item() + + +def test_wrapper_falls_back_for_long_query(): + q = mx.random.normal((1, 4, 16, 64)) # qL=16 > 8: not decode mode + k = mx.random.normal((1, 4, 64, 64)) + v = mx.random.normal((1, 4, 64, 64)) + out = fast.sdpa_decode(q, k, v, 0.125) + ref = mx.fast.scaled_dot_product_attention(q, k, v, scale=0.125) + mx.eval(out, ref) + assert mx.allclose(out, ref, atol=1e-5, rtol=1e-5).item() diff --git a/tests/test_mlx_vlm_qwen4_exp_compat.py b/tests/test_mlx_vlm_qwen4_exp_compat.py index fb939c6476..18c34623aa 100644 --- a/tests/test_mlx_vlm_qwen4_exp_compat.py +++ b/tests/test_mlx_vlm_qwen4_exp_compat.py @@ -6,6 +6,7 @@ import importlib import json from types import SimpleNamespace +from unittest.mock import MagicMock import mlx.core as mx import pytest @@ -107,6 +108,230 @@ def test_qwen4_exp_config_normalizes_reference_layer_type(): assert config.text_config.rope_parameters["type"] == "default" +@pytest.mark.parametrize("quantized", [False, True]) +def test_qwen4_small_hyper_connection_fusion_fails_closed(quantized): + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp.language import ( + Qwen4ExpGatedResidual, + compile_hyper_connections, + fuse_hyper_connection_projections, + ) + + config = SimpleNamespace( + hc_count=2, + hidden_size=32, + hc_lowrank=32, + rms_norm_eps=1e-6, + ) + mx.random.seed(17) + module = Qwen4ExpGatedResidual(config) + if quantized: + module.input_mix_weight_down = module.input_mix_weight_down.to_quantized( + 32, 4 + ) + module.block_inject_weight = module.block_inject_weight.to_quantized(32, 4) + + inputs = mx.random.normal((2, 3, 64)).astype(mx.bfloat16) + eager = module(inputs) + verify_eager = module(inputs, target_verify=True) + mx.eval(*eager, *verify_eager) + + assert fuse_hyper_connection_projections(module) == 0 + assert fuse_hyper_connection_projections(module) == 0 + fused = module(inputs) + verify_fused = module(inputs, target_verify=True) + mx.eval(*fused, *verify_fused) + + assert not hasattr(module, "input_inject_weight") + assert hasattr(module, "input_mix_weight_down") + assert hasattr(module, "block_inject_weight") + for expected, actual in zip(eager, fused): + assert mx.array_equal(expected, actual).item() + for expected, actual in zip(verify_eager, verify_fused): + assert mx.array_equal(expected, actual).item() + + assert compile_hyper_connections(module) == 1 + assert compile_hyper_connections(module) == 0 + prefill = module(inputs) + decode_inputs = inputs[:1, :1] + decode_eager = module._forward(decode_inputs) + decode_compiled = module(decode_inputs) + verify_compiled = module(inputs, target_verify=True) + mx.eval(*prefill, *decode_eager, *decode_compiled, *verify_compiled) + for expected, actual in zip(fused, prefill): + assert mx.array_equal(expected, actual).item() + for expected, actual in zip(decode_eager, decode_compiled): + assert mx.array_equal(expected, actual).item() + for expected, actual in zip(verify_fused, verify_compiled): + assert mx.array_equal(expected, actual).item() + + compiled_forward = module._compiled_forward + module._compiled_forward = MagicMock( + side_effect=AssertionError("target verification entered compiled decode") + ) + verify_decode = module(decode_inputs, target_verify=True) + mx.eval(*verify_decode) + module._compiled_forward.assert_not_called() + module._compiled_forward = compiled_forward + + +def test_qwen4_hyper_connection_optimizations_fail_closed(): + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp.language import ( + Qwen4ExpGatedResidual, + compile_hyper_connections, + fuse_hyper_connection_projections, + ) + + config = SimpleNamespace( + hc_count=2, + hidden_size=32, + hc_lowrank=32, + rms_norm_eps=1e-6, + ) + incompatible = Qwen4ExpGatedResidual(config) + incompatible.block_inject_weight = incompatible.block_inject_weight.to_quantized( + 32, 4 + ) + assert fuse_hyper_connection_projections(incompatible) == 0 + assert hasattr(incompatible, "input_mix_weight_down") + assert hasattr(incompatible, "block_inject_weight") + + already_compiled = Qwen4ExpGatedResidual(config) + assert compile_hyper_connections(already_compiled) == 1 + assert fuse_hyper_connection_projections(already_compiled) == 0 + + +def test_qwen4_hyper_connection_compile_covers_uncombined_mixer(): + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp.language import ( + Qwen4ExpGatedResidual, + compile_hyper_connections, + ) + + config = SimpleNamespace( + hc_count=2, + hidden_size=32, + hc_lowrank=32, + rms_norm_eps=1e-6, + ) + mixer = Qwen4ExpGatedResidual(config, use_combine=False) + inputs = mx.random.normal((1, 1, 64)).astype(mx.bfloat16) + eager = mixer._forward(inputs) + assert compile_hyper_connections(mixer) == 1 + compiled = mixer(inputs) + mx.eval(eager, compiled) + + assert mx.allclose(eager, compiled, rtol=1e-5, atol=1e-6).item() + + +def test_qwen4_resident_ple_fuses_packed_shards_exactly(): + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + import mlx.nn as nn + from mlx_vlm.models.qwen4_exp.language import ShardedEmbedding + + mx.random.seed(43) + embedding = ShardedEmbedding(32, 64, 4) + embedding.shards = [ + nn.QuantizedEmbedding.from_embedding( + shard, + group_size=32, + bits=4, + mode="affine", + ) + for shard in embedding.shards + ] + indices = mx.array([[0, 9, 17, 31, 9]], dtype=mx.int32) + expected = embedding(indices) + mx.eval(expected) + + assert embedding.fuse_quantized_shards() is True + assert embedding.fuse_quantized_shards() is False + assert embedding.shards == [] + # The fused arm performs one device gather and no longer consults the host + # shard boundaries after load. + embedding.shard_offsets = () + actual = embedding(indices) + mx.eval(actual) + + assert mx.array_equal(actual, expected).item() + + +def test_qwen4_exp_load_enables_hyper_connection_optimizations(monkeypatch, caplog): + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + import mlx.nn as nn + from mlx_vlm.models.qwen3_5 import Model as Qwen3_5Model + from mlx_vlm.models.qwen4_exp import qwen4_exp as model_module + + model = model_module.Model.__new__(model_module.Model) + nn.Module.__init__(model) + base_load = MagicMock(return_value="loaded") + fuse = MagicMock(return_value=96) + fuse_ple = MagicMock(return_value=1) + compile_connections = MagicMock(return_value=97) + monkeypatch.setattr(Qwen3_5Model, "load_weights", base_load) + monkeypatch.setattr(model_module, "fuse_hyper_connection_projections", fuse) + monkeypatch.setattr(model_module, "fuse_resident_ple_embeddings", fuse_ple) + monkeypatch.setattr(model_module, "compile_hyper_connections", compile_connections) + monkeypatch.setattr( + model_module, + "get_mtp_runtime", + MagicMock(return_value=SimpleNamespace(enabled=False)), + ) + caplog.set_level("INFO", logger=model_module.__name__) + + weights = [("language_model.model.embed_tokens.weight", object())] + result = model.load_weights(weights, strict=False) + + assert result == "loaded" + base_load.assert_called_once_with(weights, strict=False) + fuse.assert_called_once_with(model) + fuse_ple.assert_called_once_with(model) + compile_connections.assert_called_once_with(model) + assert ( + "96 exact hybrid projection pairs, 97 compiled decode paths" + in caplog.text + ) + assert "Fused 1 resident Qwen4-Exp PLE table" in caplog.text + + +def test_qwen4_exp_load_skips_projection_fusion_during_mtp_verify( + monkeypatch, caplog +): + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + import mlx.nn as nn + from mlx_vlm.models.qwen3_5 import Model as Qwen3_5Model + from mlx_vlm.models.qwen4_exp import qwen4_exp as model_module + + model = model_module.Model.__new__(model_module.Model) + nn.Module.__init__(model) + base_load = MagicMock(return_value=model) + fuse = MagicMock(return_value=96) + fuse_ple = MagicMock(return_value=1) + compile_connections = MagicMock(return_value=100) + monkeypatch.setattr(Qwen3_5Model, "load_weights", base_load) + monkeypatch.setattr(model_module, "fuse_hyper_connection_projections", fuse) + monkeypatch.setattr(model_module, "fuse_resident_ple_embeddings", fuse_ple) + monkeypatch.setattr(model_module, "compile_hyper_connections", compile_connections) + monkeypatch.setattr( + model_module, + "get_mtp_runtime", + MagicMock(return_value=SimpleNamespace(enabled=True)), + ) + caplog.set_level("INFO", logger=model_module.__name__) + + assert model.load_weights([], strict=False) is model + + fuse.assert_not_called() + fuse_ple.assert_called_once_with(model) + compile_connections.assert_called_once_with(model) + assert "Skipped Qwen4-Exp exact hybrid projections" in caplog.text + assert ( + "0 exact hybrid projection pairs, 100 compiled decode paths" + in caplog.text + ) + + def test_qwen4_exp_sanitize_keeps_converted_norm_values(): from mlx_vlm.models.qwen4_exp.qwen4_exp import Model @@ -389,6 +614,143 @@ def test_qwen4_exp_tiny_text_prefill_and_decode(): assert next_logits.logits.shape == (1, 1, 64) +def test_qwen4_gathered_qsa_prefill_matches_official_mask_path(monkeypatch): + config = _tiny_config() + import mlx_vlm.models.qwen4_exp.language as language + from mlx_vlm.models.qwen4_exp.language import QSAKVCache, Qwen4ExpAttention + + attention = Qwen4ExpAttention(config.text_config) + mx.eval(attention.parameters()) + hidden = mx.random.normal((1, 20, config.text_config.hidden_size)) + + calls = [] + gathered = language.contiguous_causal_gathered_qsa + + def tracked(*args, **kwargs): + calls.append((args[0].shape, args[1].shape)) + return gathered(*args, **kwargs) + + monkeypatch.setattr(language, "contiguous_causal_gathered_qsa", tracked) + fast_cache = QSAKVCache() + actual = attention(hidden, mask="causal", cache=fast_cache) + + monkeypatch.setattr( + Qwen4ExpAttention, + "_gathered_text_prefill_eligible", + staticmethod(lambda *args, **kwargs: False), + ) + reference_cache = QSAKVCache() + expected = attention(hidden, mask="causal", cache=reference_cache) + mx.eval(actual, expected) + + assert calls == [((1, 4, 20, 8), (1, 2, 20, 8))] + assert mx.allclose(actual, expected, rtol=2e-5, atol=2e-5).item() + assert fast_cache.offset == reference_cache.offset == 20 + assert mx.array_equal(fast_cache.index_keys, reference_cache.index_keys).item() + assert mx.array_equal( + fast_cache.index_position_ids, + reference_cache.index_position_ids, + ).item() + + +def test_qwen4_gathered_qsa_fails_closed_for_multimodal_positions(monkeypatch): + config = _tiny_config() + import mlx_vlm.models.qwen4_exp.language as language + from mlx_vlm.models.qwen4_exp.language import QSAKVCache, Qwen4ExpAttention + + def must_not_run(*args, **kwargs): + raise AssertionError("multimodal positions must use mlx-vlm's general QSA") + + monkeypatch.setattr(language, "contiguous_causal_gathered_qsa", must_not_run) + attention = Qwen4ExpAttention(config.text_config) + hidden = mx.random.normal((1, 3, config.text_config.hidden_size)) + position_ids = mx.array( + [ + [[0, 1, 2]], + [[0, 1, 2]], + [[0, 0, 1]], + ], + dtype=mx.int32, + ) + + output = attention( + hidden, + mask="causal", + cache=QSAKVCache(), + position_ids=position_ids, + ) + mx.eval(output) + + assert output.shape == hidden.shape + + +def test_qwen4_gathered_qsa_fails_closed_for_batched_prefill(monkeypatch): + config = _tiny_config() + import mlx_vlm.models.qwen4_exp.language as language + from mlx_vlm.models.qwen4_exp.language import QSAKVCache, Qwen4ExpAttention + + def must_not_run(*args, **kwargs): + raise AssertionError("batched requests must use mlx-vlm's general QSA") + + monkeypatch.setattr(language, "contiguous_causal_gathered_qsa", must_not_run) + attention = Qwen4ExpAttention(config.text_config) + hidden = mx.random.normal((2, 3, config.text_config.hidden_size)) + + output = attention(hidden, mask="causal", cache=QSAKVCache()) + mx.eval(output) + + assert output.shape == hidden.shape + + +def test_qwen4_gathered_qsa_keeps_official_path_at_sparse_budget(monkeypatch): + config = _tiny_config() + import mlx_vlm.models.qwen4_exp.language as language + from mlx_vlm.models.qwen4_exp.language import QSAKVCache, Qwen4ExpAttention + + def must_not_run(*args, **kwargs): + raise AssertionError("at-budget prefill must use the official full path") + + monkeypatch.setattr(language, "contiguous_causal_gathered_qsa", must_not_run) + attention = Qwen4ExpAttention(config.text_config) + budget = attention.indexer.token_budget + hidden = mx.random.normal((1, budget, config.text_config.hidden_size)) + + output = attention(hidden, mask="causal", cache=QSAKVCache()) + mx.eval(output) + + assert output.shape == hidden.shape + + +def test_qwen4_gathered_qsa_chunk_grows_with_context(): + _tiny_config() + from mlx_vlm.models.qwen4_exp.qsa_fast import contiguous_causal_query_chunk + + assert contiguous_causal_query_chunk(4096) == 32 + assert contiguous_causal_query_chunk(4097) == 64 + assert contiguous_causal_query_chunk(16384) == 64 + assert contiguous_causal_query_chunk(16385) == 128 + + +def test_qwen4_adapter_cache_only_prefill_skips_vocab_projection(): + from mlx_vlm.models.qwen4_exp import Model + + from omlx.models.vlm import VLMModelAdapter + + model = VLMModelAdapter(Model(_tiny_config())) + cache = model.make_cache() + result = model( + mx.array([[2, 3, 4, 5]], dtype=mx.int32), + cache=cache, + skip_lm_head=True, + ) + mx.eval([member.state for member in cache]) + + assert result is None + offsets = [member.offset for member in cache if hasattr(member, "offset")] + assert offsets and max(offsets) == 4 + + + def test_qwen4_batch_factory_honors_model_owned_cache_conversion(): compat.apply_mlx_vlm_qwen4_exp_compat_patch() from mlx_vlm.models.qwen4_exp.language import BatchQSAKVCache, QSAKVCache diff --git a/tests/test_mtp_prompt_priming.py b/tests/test_mtp_prompt_priming.py index 8c94139491..25ca3ff6f8 100644 --- a/tests/test_mtp_prompt_priming.py +++ b/tests/test_mtp_prompt_priming.py @@ -8,6 +8,8 @@ wiring is exercised by the real-model smoke test. """ +import threading +from collections import OrderedDict from types import SimpleNamespace import pytest @@ -110,6 +112,108 @@ def _reference_head_cache(model, tokens, extra_tok=None): return ref_cache +class _MemoryMtpPrefixCache: + """Minimal scheduler/cache contract for prompt-history integration tests.""" + + def __init__(self, block_size=8): + self.block_size = block_size + self.snapshots = {} + + def _key(self, tokens, boundary): + return tuple(tokens[:boundary]), int(boundary) + + def store_mtp_prefix_snapshot(self, tokens, boundary, snapshot, **kwargs): + self.snapshots[self._key(tokens, boundary)] = snapshot + return True + + def restore_mtp_prefix_snapshot(self, tokens, boundary, **kwargs): + return self.snapshots.get(self._key(tokens, boundary)) + + +def test_block_prefix_cache_mtp_sidecar_uses_live_chain_hash_and_evicts(): + """The production sidecar is only visible while its backbone tip lives.""" + from omlx.cache.prefix_cache import BlockAwarePrefixCache + + class _HashMap: + def __init__(self): + self.blocks = {} + + def get_block(self, key): + return self.blocks.get(key) + + hash_map = _HashMap() + cache = BlockAwarePrefixCache.__new__(BlockAwarePrefixCache) + cache.block_size = 4 + cache.paged_cache = SimpleNamespace( + model_name="tiny-mtp-test", + cached_block_hash_to_block=hash_map, + ) + cache._prefix_index = {} + cache._mtp_prefix_snapshots = OrderedDict() + cache._mtp_prefix_snapshot_lock = threading.RLock() + + tokens = list(range(8)) + snapshot = object() + assert cache.store_mtp_prefix_snapshot(tokens, 8, snapshot) + tip = cache._mtp_prefix_chain_tip(tokens, 8) + assert tip is not None + # Publishing precedes the async backbone store, so the snapshot must not + # become restorable until the matching ordinary block is live. + assert cache.restore_mtp_prefix_snapshot(tokens, 8) is None + hash_map.blocks[tip] = object() + assert cache.restore_mtp_prefix_snapshot(tokens, 8) is snapshot + + cache._on_block_hash_dropped(tip) + assert cache.restore_mtp_prefix_snapshot(tokens, 8) is None + + +def test_block_prefix_cache_mtp_sidecar_lru_four_and_clear_lifecycle(): + """MTP sidecars remain bounded and follow wholesale cache clears.""" + from omlx.cache.prefix_cache import BlockAwarePrefixCache + + class _HashMap: + def __init__(self): + self.blocks = {} + + def get_block(self, key): + return self.blocks.get(key) + + hash_map = _HashMap() + cache = BlockAwarePrefixCache.__new__(BlockAwarePrefixCache) + cache.block_size = 4 + cache.paged_cache = SimpleNamespace( + model_name="tiny-mtp-lru-test", + cached_block_hash_to_block=hash_map, + ) + cache._prefix_index = {} + cache._mtp_prefix_snapshots = OrderedDict() + cache._mtp_prefix_snapshot_lock = threading.RLock() + + entries = [] + for branch in range(5): + tokens = [branch * 100 + i for i in range(8)] + snapshot = object() + assert cache.store_mtp_prefix_snapshot(tokens, 8, snapshot) + tip = cache._mtp_prefix_chain_tip(tokens, 8) + assert tip is not None + hash_map.blocks[tip] = object() + entries.append((tokens, tip, snapshot)) + + assert len(cache._mtp_prefix_snapshots) == 4 + assert cache.restore_mtp_prefix_snapshot(entries[0][0], 8) is None + assert cache.restore_mtp_prefix_snapshot(entries[-1][0], 8) is entries[-1][2] + + # Individual backbone eviction removes the matching sidecar even if a + # stale test hash-map entry remains, then the wholesale clear drops all + # remaining sidecars and the ordinary prefix index together. + cache._on_block_hash_dropped(entries[-1][1]) + assert cache.restore_mtp_prefix_snapshot(entries[-1][0], 8) is None + cache._prefix_index[b"ordinary"] = (1, 2, 3) + cache._on_hash_map_cleared() + assert not cache._mtp_prefix_snapshots + assert not cache._prefix_index + + @pytest.fixture(autouse=True) def _apply_patch(): try: @@ -175,6 +279,100 @@ def test_chunked_capture_matches_oneshot_fold(self, model): assert mx.allclose(k, rk, rtol=1e-4, atol=1e-4) assert mx.allclose(v, rv, rtol=1e-4, atol=1e-4) + def test_warm_prefix_restores_exact_head_history_without_trunk_reforward( + self, strict_model + ): + """A backbone hit at C restores MTP(C-1)+hidden(C-1), then folds + only the uncached suffix and activation seam. The resulting head + cache must equal a one-shot cold oracle exactly within model dtype. + Repeating scheduler preparation for the same request is idempotent. + """ + model = strict_model + tokens = _tokens(13, seed=40) + main_tok = _tokens(1, seed=41) + sidecar = _MemoryMtpPrefixCache(block_size=8) + + cold_cache = _make_cache(model) + assert not prompt_priming.prepare_prefix_context( + model, + request_id="cold", + prompt_tokens=tokens.tolist(), + cached_tokens=0, + prefix_cache=sidecar, + ) + _chunked_prefill(model, cold_cache, tokens, [8, 5]) + cold_ctx = prompt_priming._find_ctx(model) + assert cold_ctx is not None + cold_final_pending = cold_ctx.pending_hidden + 0 + mx.eval(cold_final_pending) + model(main_tok[None, :], cache=cold_cache, return_hidden=True) + cold_primed = prompt_priming.take_primed(model, cold_cache, main_tok) + assert cold_primed is not None + snapshot_key = (tuple(tokens[:8].tolist()), 8) + assert snapshot_key in sidecar.snapshots + boundary_pending = sidecar.snapshots[snapshot_key].pending_hidden + + # Build the already-restored backbone cache outside capture. Start + # tracing only after sidecar restore: a correct warm path invokes the + # MTP head for suffix(5)+seam(1), never for the cached trunk(8). + warm_cache = _make_cache(model) + with prompt_priming.suppress_capture(): + model(tokens[:8][None, :], cache=warm_cache) + assert prompt_priming.prepare_prefix_context( + model, + request_id="warm", + prompt_tokens=tokens.tolist(), + cached_tokens=8, + prefix_cache=sidecar, + ) + warm_ctx = prompt_priming._find_ctx(model) + assert warm_ctx is not None + assert warm_ctx.folded == 7 + assert warm_ctx.expected_offset == 8 + assert mx.array_equal(warm_ctx.pending_hidden, boundary_pending).item() + + # The scheduler's prepared-set normally prevents this second call; + # the hook itself also guarantees it cannot reset/double-prime a live + # request if invoked twice. + assert prompt_priming.prepare_prefix_context( + model, + request_id="warm", + prompt_tokens=tokens.tolist(), + cached_tokens=8, + prefix_cache=sidecar, + ) + assert prompt_priming._find_ctx(model) is warm_ctx + + mtp_rows = [] + original_mtp_forward = model.mtp_forward + + def traced_mtp_forward(hidden, next_ids, cache, **kwargs): + mtp_rows.append(int(next_ids.shape[1])) + return original_mtp_forward(hidden, next_ids, cache, **kwargs) + + model.mtp_forward = traced_mtp_forward + _chunked_prefill(model, warm_cache, tokens[8:], [5]) + warm_final_ctx = prompt_priming._find_ctx(model) + assert warm_final_ctx is not None + assert mx.array_equal( + warm_final_ctx.pending_hidden, cold_final_pending + ).item() + model(main_tok[None, :], cache=warm_cache, return_hidden=True) + warm_primed = prompt_priming.take_primed(model, warm_cache, main_tok) + assert warm_primed is not None + assert warm_primed[1] == len(tokens) + assert mtp_rows == [5, 1] + + mx.eval( + [c.state for c in cold_primed[0]], + [c.state for c in warm_primed[0]], + ) + for (k, v), (rk, rv) in zip( + _kv_entries(warm_primed[0]), _kv_entries(cold_primed[0]) + ): + assert mx.array_equal(k, rk).item() + assert mx.array_equal(v, rv).item() + def test_chunk_size_one_seam_is_dense(self, model): """A trailing S==1 forward (the __init__ _step seam) still folds.""" n = 8 diff --git a/tests/test_qwen35_gdn_prework.py b/tests/test_qwen35_gdn_prework.py index 8f4413c2be..94678a7ea7 100644 --- a/tests/test_qwen35_gdn_prework.py +++ b/tests/test_qwen35_gdn_prework.py @@ -15,7 +15,11 @@ import pytest from omlx.patches import qwen35_gdn_prework as prework_mod -from omlx.patches.qwen35_gdn_prework import gdn_prework_fused +from omlx.patches.qwen35_gdn_prework import ( + gdn_prework_fused, + qwen4_decode_norm_gate_fused, + qwen4_decode_prework_fused, +) HK, HV, DK, DV = 16, 48, 128, 128 C = 2 * HK * DK + HV * DV @@ -57,6 +61,80 @@ def test_fused_prework_bit_exact(seq): assert bool((r == g).all().item()), f"{name} not bit-exact at S={seq}" +@pytest.mark.skipif(not mx.metal.is_available(), reason="requires Metal") +def test_qwen4_decode_prework_is_bit_exact_including_fp32_gate(): + from mlx_vlm.models.qwen3_5.gated_delta import _compute_g_beta + + mx.random.seed(29) + conv_w = (mx.random.normal((C, 4, 1)) * 0.2).astype(mx.bfloat16) + conv1d = nn.Conv1d(C, C, kernel_size=4, groups=C, bias=False) + conv1d.weight = conv_w + qkv = (mx.random.normal((1, 1, C)) * 0.5).astype(mx.bfloat16) + state = (mx.random.normal((1, 3, C)) * 0.5).astype(mx.bfloat16) + a = (mx.random.normal((1, 1, HV)) * 0.2).astype(mx.bfloat16) + b = (mx.random.normal((1, 1, HV)) * 0.2).astype(mx.bfloat16) + A_log = (mx.random.normal((HV,)) * 0.2).astype(mx.bfloat16) + dt_bias = (mx.random.normal((HV,)) * 0.2).astype(mx.bfloat16) + inv = DK**-0.5 + q_scale = mx.array(inv * inv, dtype=mx.bfloat16) + k_scale = mx.array(inv, dtype=mx.bfloat16) + + q, k, v, next_state = _composed(qkv, state, conv1d) + g, beta = _compute_g_beta(A_log, a, b, dt_bias) + reference = (q, k, v, next_state, g, beta) + actual = qwen4_decode_prework_fused( + qkv, + state, + conv_w, + q_scale, + k_scale, + b, + a, + A_log, + dt_bias, + HK, + HV, + DK, + DV, + ) + mx.eval(*reference, *actual) + for name, expected, observed in zip( + ("q", "k", "v", "conv_state", "g", "beta"), + reference, + actual, + ): + assert expected.dtype == observed.dtype, name + assert mx.array_equal(expected, observed).item(), name + + +@pytest.mark.skipif(not mx.metal.is_available(), reason="requires Metal") +def test_qwen4_decode_norm_gate_is_bit_exact(): + from omlx.patches.mlx_vlm_qwen4_exp_compat import ( + apply_mlx_vlm_qwen4_exp_compat_patch, + ) + + apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp.language import Qwen4ExpRMSNormGated + + mx.random.seed(31) + y = (mx.random.normal((1, 1, HV, DV)) * 0.25).astype(mx.bfloat16) + z = (mx.random.normal((1, 1, HV, DV)) * 0.25).astype(mx.bfloat16) + norm = Qwen4ExpRMSNormGated(DV, eps=1e-6, activation="sigmoid") + norm.weight = (1 + mx.random.normal((DV,)) * 0.1).astype(mx.bfloat16) + + expected = norm(y, z).reshape(1, 1, HV * DV) + observed = qwen4_decode_norm_gate_fused( + y, + z, + norm.weight, + hv=HV, + dv=DV, + eps=norm.eps, + ) + mx.eval(expected, observed) + assert mx.array_equal(expected, observed).item() + + class _FakeCache: """Minimal cache[0]/cache[1]/advance duck-type for patched_call.""" @@ -75,6 +153,263 @@ def advance(self, n): self.advance_calls += 1 +def test_qwen4_decode_dynamic_gate_is_strictly_b1_t1_nonverify(monkeypatch): + monkeypatch.setattr(prework_mod, "_qwen4_decode_static_eligible", lambda _: True) + module = object() + inputs = mx.zeros((1, 1, 2560), dtype=mx.bfloat16) + cache = _FakeCache( + mx.zeros((1, 3, C), dtype=mx.bfloat16), + mx.zeros((1, HV, DV, DK), dtype=mx.float32), + ) + cache.left_padding = None + + def eligible(**changes): + args = { + "module": module, + "inputs": inputs, + "mask": None, + "cache": cache, + "gdn_sink": None, + "target_verify": False, + } + args.update(changes) + return prework_mod._qwen4_decode_dynamic_eligible(**args) + + assert eligible() + assert not eligible(inputs=mx.zeros((2, 1, 2560), dtype=mx.bfloat16)) + assert not eligible(inputs=mx.zeros((1, 2, 2560), dtype=mx.bfloat16)) + assert not eligible(inputs=mx.zeros((1, 1, 2560), dtype=mx.float16)) + assert not eligible(mask="causal") + assert not eligible(gdn_sink=[]) + assert not eligible(target_verify=True) + + cache.lengths = mx.array([1]) + assert not eligible() + cache.lengths = None + cache.left_padding = mx.array([0]) + assert not eligible() + cache.left_padding = None + cache[1] = mx.zeros((1, HV, DV, DK), dtype=mx.bfloat16) + assert not eligible() + + +def _fake_quantized_linear(input_dims, output_dims, bits, group_size): + linear = nn.QuantizedLinear.__new__(nn.QuantizedLinear) + nn.Module.__init__(linear) + linear.bits = bits + linear.group_size = group_size + linear.mode = "affine" + linear.weight = mx.zeros( + (output_dims, input_dims * bits // 32), + dtype=mx.uint32, + ) + linear.scales = mx.zeros( + (output_dims, input_dims // group_size), + dtype=mx.bfloat16, + ) + linear.biases = mx.zeros_like(linear.scales) + return linear + + +@pytest.mark.parametrize( + "signatures", + [ + ((6, 64), (6, 64), (6, 64), (6, 64)), # physical layer 0 + ((4, 64), (5, 128), (5, 128), (5, 128)), # physical layer 1 + ((5, 64), (6, 64), (6, 64), (6, 64)), # physical layer 29 + ], +) +def test_qwen4_decode_static_gate_accepts_canonical_oqe_allocations(signatures): + module_type = type("Qwen4ExpGatedDeltaNet", (), {}) + module_type.__module__ = "mlx_vlm.models.qwen4_exp.language" + module = module_type() + module.training = False + module.num_k_heads = HK + module.num_v_heads = HV + module.head_k_dim = DK + module.head_v_dim = DV + module.conv_kernel_size = 4 + module.conv1d = SimpleNamespace( + weight=mx.zeros((C, 4, 1), dtype=mx.bfloat16), + bias=None, + ) + module.norm = SimpleNamespace( + activation="sigmoid", + weight=mx.ones((DV,), dtype=mx.bfloat16), + ) + module.A_log = mx.zeros((HV,), dtype=mx.bfloat16) + module.dt_bias = mx.zeros((HV,), dtype=mx.bfloat16) + rows = (C, HV * DV, HV, HV) + projections = [ + _fake_quantized_linear(2560, output, bits, group) + for output, (bits, group) in zip(rows, signatures) + ] + ( + module.in_proj_qkv, + module.in_proj_z, + module.in_proj_b, + module.in_proj_a, + ) = projections + module.out_proj = _fake_quantized_linear(6144, 2560, 5, 128) + + assert prework_mod._qwen4_decode_static_eligible(module) + module.in_proj_z.group_size = 64 if module.in_proj_z.group_size == 128 else 128 + assert not prework_mod._qwen4_decode_static_eligible(module) + + +def test_qwen4_decode_route_commits_both_states_and_advances_once(monkeypatch): + q35 = pytest.importorskip("mlx_vlm.models.qwen3_5.language") + cls = q35.Qwen3_5GatedDeltaNet + old_conv = mx.zeros((1, 3, C), dtype=mx.bfloat16) + old_recurrent = mx.zeros((1, HV, DV, DK), dtype=mx.float32) + next_conv = mx.ones_like(old_conv) + next_recurrent = mx.ones_like(old_recurrent) + fused = mx.ones((1, 1, 2560), dtype=mx.bfloat16) + + def stock(*args, **kwargs): + raise AssertionError("eligible Qwen4 decode unexpectedly fell back") + + monkeypatch.setattr(prework_mod, "_PATCHED", False) + monkeypatch.setattr(prework_mod, "_QWEN4_DECODE_ENGAGED_LOGGED", False) + monkeypatch.setattr(cls, "__call__", stock, raising=False) + monkeypatch.setattr(cls, "_omlx_gdn_prework_patched", False, raising=False) + monkeypatch.setattr( + prework_mod, + "_qwen4_decode_dynamic_eligible", + lambda *args, **kwargs: True, + ) + monkeypatch.setattr( + q35, + "_target_verify_linears", + lambda *args, **kwargs: ( + mx.zeros((1, 1, C), dtype=mx.bfloat16), + mx.zeros((1, 1, HV * DV), dtype=mx.bfloat16), + mx.zeros((1, 1, HV), dtype=mx.bfloat16), + mx.zeros((1, 1, HV), dtype=mx.bfloat16), + ), + ) + monkeypatch.setattr( + prework_mod, + "qwen4_decode_prework_fused", + lambda *args, **kwargs: (None, None, None, next_conv, None, None), + ) + monkeypatch.setattr( + prework_mod, + "_qwen4_decode_recurrence", + lambda *args, **kwargs: (None, next_recurrent), + ) + monkeypatch.setattr( + prework_mod, + "qwen4_decode_norm_gate_fused", + lambda *args, **kwargs: fused, + ) + monkeypatch.setattr(q35, "_target_verify_linear", lambda *args: fused) + + assert prework_mod.apply_qwen35_gdn_prework_patch() + module = SimpleNamespace( + in_proj_qkv=None, + in_proj_z=None, + in_proj_b=None, + in_proj_a=None, + conv1d=SimpleNamespace(weight=None), + head_k_dim=DK, + head_v_dim=DV, + num_k_heads=HK, + num_v_heads=HV, + A_log=None, + dt_bias=None, + norm=SimpleNamespace(weight=None, eps=1e-6), + out_proj=None, + ) + cache = _FakeCache(old_conv, old_recurrent) + result = cls.__call__( + module, + mx.zeros((1, 1, 2560), dtype=mx.bfloat16), + cache=cache, + ) + assert result is fused + assert cache[0] is next_conv + assert cache[1] is next_recurrent + assert cache.advance_calls == 1 + + +def test_qwen4_decode_route_restores_states_before_stock_fallback(monkeypatch): + q35 = pytest.importorskip("mlx_vlm.models.qwen3_5.language") + cls = q35.Qwen3_5GatedDeltaNet + old_conv = mx.zeros((1, 3, C), dtype=mx.bfloat16) + old_recurrent = mx.zeros((1, HV, DV, DK), dtype=mx.float32) + seen = [] + + def stock(self, inputs, mask=None, cache=None, gdn_sink=None, + target_verify=False): + seen.append((cache[0], cache[1], cache.advance_calls)) + return "stock" + + monkeypatch.setattr(prework_mod, "_PATCHED", False) + monkeypatch.setattr(cls, "__call__", stock, raising=False) + monkeypatch.setattr(cls, "_omlx_gdn_prework_patched", False, raising=False) + monkeypatch.setattr( + prework_mod, + "_qwen4_decode_dynamic_eligible", + lambda *args, **kwargs: True, + ) + monkeypatch.setattr( + q35, + "_target_verify_linears", + lambda *args, **kwargs: (None, None, None, None), + ) + monkeypatch.setattr( + prework_mod, + "qwen4_decode_prework_fused", + lambda *args, **kwargs: ( + None, + None, + None, + mx.ones_like(old_conv), + None, + None, + ), + ) + monkeypatch.setattr( + prework_mod, + "_qwen4_decode_recurrence", + lambda *args, **kwargs: (None, mx.ones_like(old_recurrent)), + ) + monkeypatch.setattr( + prework_mod, + "qwen4_decode_norm_gate_fused", + lambda *args, **kwargs: (_ for _ in ()).throw(RuntimeError("late")), + ) + + assert prework_mod.apply_qwen35_gdn_prework_patch() + module = SimpleNamespace( + in_proj_qkv=None, + in_proj_z=None, + in_proj_b=None, + in_proj_a=None, + conv1d=SimpleNamespace(weight=None), + head_k_dim=DK, + head_v_dim=DV, + num_k_heads=HK, + num_v_heads=HV, + A_log=None, + dt_bias=None, + norm=SimpleNamespace(weight=None, eps=1e-6), + out_proj=None, + ) + cache = _FakeCache(old_conv, old_recurrent) + result = cls.__call__( + module, + mx.zeros((1, 1, 2560), dtype=mx.bfloat16), + cache=cache, + ) + assert result == "stock" + assert len(seen) == 1 + assert seen[0][0] is old_conv + assert seen[0][1] is old_recurrent + assert seen[0][2] == 0 + + @pytest.mark.skipif(not mx.metal.is_available(), reason="requires Metal") def test_patched_call_restores_conv_state_and_skips_advance_on_failure(monkeypatch): """E3 regression: an exception raised after cache[0] is set to the fused diff --git a/tests/test_qwen4_hc_projection.py b/tests/test_qwen4_hc_projection.py new file mode 100644 index 0000000000..45f07ab33d --- /dev/null +++ b/tests/test_qwen4_hc_projection.py @@ -0,0 +1,191 @@ +# SPDX-License-Identifier: Apache-2.0 + +from __future__ import annotations + +from types import SimpleNamespace +from unittest.mock import MagicMock + +import mlx.core as mx +import mlx.nn as nn +import pytest + +from omlx.patches import mlx_vlm_qwen4_exp_compat as compat + + +def _production_module(bits: int): + from mlx_vlm.models.qwen4_exp.language import ( + Qwen4ExpGatedResidual, + Qwen4ExpRMSNorm, + ) + + module = Qwen4ExpGatedResidual.__new__(Qwen4ExpGatedResidual) + nn.Module.__init__(module) + module.hc_count = 4 + module.hidden_size = 2560 + module.hc_lowrank = 320 + module.hc_norm = Qwen4ExpRMSNorm( + 10240, + group_size=2560, + eps=1e-6, + ) + module.hc_norm.weight = ( + mx.random.normal((10240,)) * 0.02 + ).astype(mx.bfloat16) + module.input_mix_weight_down = nn.QuantizedLinear( + 10240, + 320, + bias=False, + group_size=64, + bits=bits, + mode="affine", + ) + module.block_inject_weight = nn.QuantizedLinear( + 10240, + 4, + bias=False, + group_size=64, + bits=bits, + mode="affine", + ) + module.input_mix_weight_up = nn.QuantizedLinear( + 320, + 10240, + bias=False, + group_size=64, + bits=bits, + mode="affine", + ) + for projection in ( + module.input_mix_weight_down, + module.block_inject_weight, + module.input_mix_weight_up, + ): + projection.scales = projection.scales.astype(mx.bfloat16) + projection.biases = projection.biases.astype(mx.bfloat16) + return module + + +@pytest.mark.parametrize("bits", [4, 5, 6, 8]) +@pytest.mark.skipif(not mx.metal.is_available(), reason="requires Metal") +def test_qwen4_exact_hybrid_raw_and_full_outputs_are_bit_exact(bits): + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp.hc_projection import hybrid_projection + from mlx_vlm.models.qwen4_exp.language import ( + compile_hyper_connections, + fuse_hyper_connection_projections, + ) + + mx.random.seed(20260900 + bits) + module = _production_module(bits) + down = module.input_mix_weight_down + injection = module.block_inject_weight + down_id = id(down) + injection_id = id(injection) + + for seed in range(4): + mx.random.seed(20261000 + 100 * bits + seed) + stream = mx.random.normal((1, 1, 10240)).astype(mx.bfloat16) + normed = module.hc_norm(stream) + expected_down = down(normed) + expected_injection = injection(normed) + combined = hybrid_projection(normed, down, injection) + assert combined is not None + mx.eval(expected_down, expected_injection, combined) + assert mx.array_equal(expected_down, combined[..., :320]).item() + assert mx.array_equal( + expected_injection, + combined[..., 320:324], + ).item() + + stream = mx.random.normal((1, 1, 10240)).astype(mx.bfloat16) + canonical = module._forward(stream) + mx.eval(*canonical) + assert fuse_hyper_connection_projections(module) == 1 + assert fuse_hyper_connection_projections(module) == 0 + assert id(module.input_mix_weight_down) == down_id + assert id(module.block_inject_weight) == injection_id + assert not hasattr(module, "input_inject_weight") + assert compile_hyper_connections(module) == 1 + actual = module(stream) + mx.eval(*actual) + for expected, value in zip(canonical, actual): + assert mx.array_equal(expected, value).item() + + +@pytest.mark.skipif(not mx.metal.is_available(), reason="requires Metal") +def test_qwen4_exact_hybrid_fallbacks_never_enter_native(monkeypatch): + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp import hc_projection + from mlx_vlm.models.qwen4_exp import language + + mx.random.seed(20261100) + module = _production_module(5) + assert language.fuse_hyper_connection_projections(module) == 1 + assert language.compile_hyper_connections(module) == 1 + bomb = MagicMock(side_effect=AssertionError("native HC projection entered")) + monkeypatch.setattr(hc_projection, "hybrid_projection", bomb) + + cases = [ + (mx.random.normal((2, 1, 10240)).astype(mx.bfloat16), False), + (mx.random.normal((1, 2, 10240)).astype(mx.bfloat16), False), + (mx.random.normal((1, 1, 10240)).astype(mx.float16), False), + (mx.random.normal((1, 1, 10240)).astype(mx.bfloat16), True), + ] + for stream, target_verify in cases: + output = module(stream, target_verify=target_verify) + mx.eval(*output) + + monkeypatch.setattr( + language, + "_MTP_RUNTIME", + language.Qwen4ExpMTPRuntime(enabled=True), + ) + mtp_output = module(mx.zeros((1, 1, 10240), dtype=mx.bfloat16)) + mx.eval(*mtp_output) + bomb.assert_not_called() + + +def test_qwen4_exact_hybrid_preparation_fails_closed_for_other_geometry(): + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp.hc_projection import compatible_projections + from mlx_vlm.models.qwen4_exp.language import ( + Qwen4ExpGatedResidual, + fuse_hyper_connection_projections, + ) + + small = Qwen4ExpGatedResidual( + SimpleNamespace( + hc_count=2, + hidden_size=32, + hc_lowrank=32, + rms_norm_eps=1e-6, + ) + ) + assert fuse_hyper_connection_projections(small) == 0 + assert hasattr(small, "input_mix_weight_down") + assert hasattr(small, "block_inject_weight") + + mx.random.seed(20261200) + unsupported = _production_module(3) + assert not compatible_projections( + unsupported.input_mix_weight_down, + unsupported.block_inject_weight, + ) + assert fuse_hyper_connection_projections(unsupported) == 0 + assert not hasattr(unsupported, "_omlx_exact_hybrid_projection") + + missing = _production_module(5) + del missing.input_mix_weight_down.scales + assert not compatible_projections( + missing.input_mix_weight_down, + missing.block_inject_weight, + ) + assert fuse_hyper_connection_projections(missing) == 0 + + none_metadata = _production_module(5) + none_metadata.block_inject_weight.biases = None + assert not compatible_projections( + none_metadata.input_mix_weight_down, + none_metadata.block_inject_weight, + ) + assert fuse_hyper_connection_projections(none_metadata) == 0 diff --git a/tests/test_qwen4_qsa_decode_gather.py b/tests/test_qwen4_qsa_decode_gather.py new file mode 100644 index 0000000000..08a37b8c8c --- /dev/null +++ b/tests/test_qwen4_qsa_decode_gather.py @@ -0,0 +1,377 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Batch-one Qwen4 QSA decode gather regression tests.""" + +# SPDX-License-Identifier: Apache-2.0 + +from __future__ import annotations + +from types import SimpleNamespace + +import mlx.core as mx +import pytest + +from omlx.patches import mlx_vlm_qwen4_exp_compat as compat + + +def _tiny_text_config(): + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp import TextConfig + + return TextConfig( + model_type="qwen4_exp_text", + hidden_size=32, + num_hidden_layers=2, + num_attention_heads=4, + linear_num_value_heads=4, + linear_num_key_heads=2, + linear_key_head_dim=8, + linear_value_head_dim=8, + linear_conv_kernel_dim=3, + num_experts=4, + num_experts_per_tok=2, + shared_expert_intermediate_size=16, + moe_intermediate_size=16, + rms_norm_eps=1e-6, + vocab_size=64, + num_key_value_heads=2, + max_position_embeddings=128, + hc_count=2, + hc_lowrank=8, + head_dim=8, + layer_types=["linear_attention", "qwen_sparse_attention"], + ple_layer_ids=[], + ple_embed_dim=32, + ple_conv_kernel_size=3, + ngram_size=3, + heads_per_ngram=2, + ngram_vocab_size_base=17, + make_ngram_vocab_size_divisible_by=4, + split_ngram_parts=4, + indexer_n_heads=2, + indexer_kv_heads=1, + indexer_head_dim=8, + indexer_budget=8, + indexer_compress_ratio=2, + eos_token_id=1, + rope_parameters={ + "rope_type": "default", + "mrope_section": [2, 1, 1], + "rope_theta": 10_000, + "partial_rotary_factor": 1.0, + }, + ) + + +def test_qwen4_decode_gathers_budget_and_tail_and_matches_official(monkeypatch): + config = _tiny_text_config() + import mlx_vlm.models.qwen4_exp.language as language + import mlx_vlm.models.qwen4_exp.qsa_fast as qsa_fast + + attention = language.Qwen4ExpAttention(config) + mx.eval(attention.parameters()) + fast_cache = language.QSAKVCache() + reference_cache = language.QSAKVCache() + + mx.random.seed(19) + prefix = mx.random.normal((1, 10, config.hidden_size)) + decode = mx.random.normal((1, 1, config.hidden_size)) + fast_prefix = attention(prefix, mask="causal", cache=fast_cache) + reference_prefix = attention(prefix, mask="causal", cache=reference_cache) + mx.eval(fast_prefix, reference_prefix) + + gathered_lengths = [] + original_sdpa = qsa_fast._decode_qsa_sdpa + + def tracked_sdpa(queries, keys, values, scale): + gathered_lengths.append(int(keys.shape[2])) + return original_sdpa(queries, keys, values, scale) + + monkeypatch.setattr(qsa_fast, "_decode_qsa_sdpa", tracked_sdpa) + actual = attention(decode, cache=fast_cache) + + monkeypatch.setattr( + language.Qwen4ExpAttention, + "_gathered_text_decode_eligible", + lambda *args, **kwargs: False, + ) + expected = attention(decode, cache=reference_cache) + mx.eval(actual, expected) + + # key_len=11, budget=8, incomplete causal tail=1. + assert gathered_lengths == [9] + assert mx.allclose(actual, expected, rtol=2e-5, atol=2e-5).item() + assert mx.array_equal( + mx.argmax(actual, axis=-1), + mx.argmax(expected, axis=-1), + ).item() + assert fast_cache.offset == reference_cache.offset == 11 + for fast_value, reference_value in zip( + fast_cache.state, + reference_cache.state, + ): + assert mx.array_equal(fast_value, reference_value).item() + + +def test_qwen4_language_wrapper_routes_2d_text_positions_to_gather(monkeypatch): + config = _tiny_text_config() + import mlx_vlm.models.qwen4_exp.language as language + + root_config = SimpleNamespace( + vision_config=SimpleNamespace(spatial_merge_size=2), + image_token_id=60, + video_token_id=61, + vision_start_token_id=58, + ) + model = language.LanguageModel(config, root_config) + mx.eval(model.parameters()) + fast_cache = model.make_cache() + reference_cache = model.make_cache() + calls = [] + + original_prefill = language.Qwen4ExpAttention._gathered_text_prefill + original_decode = language.Qwen4ExpAttention._gathered_text_decode + original_prefill_eligible = ( + language.Qwen4ExpAttention._gathered_text_prefill_eligible + ) + original_decode_eligible = language.Qwen4ExpAttention._gathered_text_decode_eligible + + def tracked_prefill(self, x, cache, position_ids=None): + calls.append(("prefill", position_ids.ndim, position_ids.shape)) + return original_prefill(self, x, cache, position_ids) + + def tracked_decode(self, x, cache, position_ids=None): + calls.append(("decode", position_ids.ndim, position_ids.shape)) + return original_decode(self, x, cache, position_ids) + + monkeypatch.setattr( + language.Qwen4ExpAttention, + "_gathered_text_prefill", + tracked_prefill, + ) + monkeypatch.setattr( + language.Qwen4ExpAttention, + "_gathered_text_decode", + tracked_decode, + ) + + prefix = mx.arange(2, 12, dtype=mx.int32)[None] + fast_prefix = model(prefix, cache=fast_cache) + + # Replay the same wrapper-owned text sequence through the official path. + model._position_ids = None + model._rope_deltas = None + monkeypatch.setattr( + language.Qwen4ExpAttention, + "_gathered_text_prefill_eligible", + lambda *args, **kwargs: False, + ) + reference_prefix = model(prefix, cache=reference_cache) + monkeypatch.setattr( + language.Qwen4ExpAttention, + "_gathered_text_prefill_eligible", + original_prefill_eligible, + ) + + decode_token = mx.array([[12]], dtype=mx.int32) + actual = model(decode_token, cache=fast_cache) + monkeypatch.setattr( + language.Qwen4ExpAttention, + "_gathered_text_decode_eligible", + lambda *args, **kwargs: False, + ) + expected = model(decode_token, cache=reference_cache) + mx.eval(fast_prefix.logits, reference_prefix.logits, actual.logits, expected.logits) + + assert calls == [ + ("prefill", 2, (1, 10)), + ("decode", 2, (1, 1)), + ] + assert mx.allclose( + fast_prefix.logits, + reference_prefix.logits, + rtol=2e-5, + atol=2e-5, + ).item() + assert mx.allclose(actual.logits, expected.logits, rtol=2e-5, atol=2e-5).item() + assert mx.array_equal( + mx.argmax(actual.logits[:, -1], axis=-1), + mx.argmax(expected.logits[:, -1], axis=-1), + ).item() + + +def test_qwen4_decode_keeps_official_path_until_complete_block_crossover( + monkeypatch, +): + config = _tiny_text_config() + import mlx_vlm.models.qwen4_exp.language as language + + attention = language.Qwen4ExpAttention(config) + cache = language.QSAKVCache() + prefix = mx.random.normal((1, 8, config.hidden_size)) + attention(prefix, mask="causal", cache=cache) + + def must_not_gather(*args, **kwargs): + raise AssertionError("decode at the QSA block budget must stay official") + + monkeypatch.setattr(language, "contiguous_causal_gathered_qsa_decode", must_not_gather) + output = attention(mx.random.normal((1, 1, config.hidden_size)), cache=cache) + mx.eval(output) + + # Nine visible rows still contain only four complete two-token blocks. + assert cache.offset == 9 + assert output.shape == (1, 1, config.hidden_size) + + +def test_qwen4_decode_gather_eligibility_fails_closed_for_general_paths(): + config = _tiny_text_config() + import mlx_vlm.models.qwen4_exp.language as language + + attention = language.Qwen4ExpAttention(config) + cache = language.QSAKVCache() + prefix = mx.random.normal((1, 10, config.hidden_size)) + mx.eval(attention(prefix, mask="causal", cache=cache)) + token = mx.random.normal((1, 1, config.hidden_size)) + + assert attention._gathered_text_decode_eligible( + token, None, cache, None, None, False + ) + assert not attention._gathered_text_decode_eligible( + token, "left_padded_decode", cache, None, None, False + ) + assert attention._gathered_text_decode_eligible( + token, None, cache, mx.array([[10]], dtype=mx.int32), None, False + ) + assert not attention._gathered_text_decode_eligible( + token, + None, + cache, + mx.array([[[10]], [[10]], [[10]]], dtype=mx.int32), + None, + False, + ) + assert not attention._gathered_text_decode_eligible( + token, None, cache, None, None, True + ) + assert not attention._gathered_text_decode_eligible( + mx.broadcast_to(token, (2, 1, config.hidden_size)), + None, + cache, + None, + None, + False, + ) + + incomplete = language.QSAKVCache() + incomplete.offset = cache.offset + assert not attention._gathered_text_decode_eligible( + token, None, incomplete, None, None, False + ) + + +@pytest.mark.parametrize("key_tokens", [4097, 32769]) +def test_qwen4_decode_gather_stays_budget_bounded_at_long_cache( + monkeypatch, + key_tokens, +): + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + import mlx_vlm.models.qwen4_exp.qsa_fast as qsa_fast + + mx.random.seed(23) + queries = mx.random.normal((1, 4, 1, 8)).astype(mx.float32) + keys = mx.random.normal((1, 2, key_tokens, 8)).astype(mx.float32) + values = mx.random.normal((1, 2, key_tokens, 8)).astype(mx.float32) + index_queries = mx.random.normal((1, 1, 2, 8)).astype(mx.float32) + pooled = mx.random.normal((1, key_tokens // 2, 8)).astype(mx.float32) + + gathered_lengths = [] + original_sdpa = qsa_fast._decode_qsa_sdpa + + def tracked_sdpa(q, k, v, scale): + gathered_lengths.append(int(k.shape[2])) + return original_sdpa(q, k, v, scale) + + monkeypatch.setattr(qsa_fast, "_decode_qsa_sdpa", tracked_sdpa) + output = qsa_fast.contiguous_causal_gathered_qsa_decode( + queries, + keys, + values, + index_queries, + pooled, + num_query_heads=4, + num_key_value_heads=2, + head_dim=8, + indexer_head_dim=8, + compress_ratio=2, + token_budget=8, + ) + mx.eval(output) + + assert gathered_lengths == [9] + assert output.shape == (1, 1, 4, 8) + + +def test_qwen4_decode_sdpa_fails_closed_when_native_shape_is_rejected(monkeypatch): + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + import mlx_vlm.models.qwen4_exp.qsa_fast as qsa_fast + from omlx.custom_kernels.decode_fast import fast + + q = mx.random.normal((1, 4, 1, 8)) + k = mx.random.normal((1, 2, 9, 8)) + v = mx.random.normal((1, 2, 9, 8)) + monkeypatch.setattr(fast, "NATIVE_AVAILABLE", True) + monkeypatch.setattr( + fast, + "_ext", + SimpleNamespace(sdpa_decode_supported=lambda *args: False), + ) + + def must_not_run(*args, **kwargs): + raise AssertionError("rejected decode_fast shape must use MLX SDPA") + + monkeypatch.setattr(fast, "sdpa_decode", must_not_run) + actual = qsa_fast._decode_qsa_sdpa(q, k, v, 8**-0.5) + expected = mx.fast.scaled_dot_product_attention(q, k, v, scale=8**-0.5) + mx.eval(actual, expected) + + assert mx.array_equal(actual, expected).item() + + +def test_qwen4_decode_sdpa_uses_native_only_after_capability_accepts(monkeypatch): + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + import mlx_vlm.models.qwen4_exp.qsa_fast as qsa_fast + from omlx.custom_kernels.decode_fast import fast + + q = mx.random.normal((1, 24, 1, 256)).astype(mx.bfloat16) + k = mx.random.normal((1, 2, 2051, 256)).astype(mx.bfloat16) + v = mx.random.normal((1, 2, 2051, 256)).astype(mx.bfloat16) + calls = [] + + def supported(queries, keys, values): + calls.append((queries.shape, keys.shape, values.shape, "probe")) + return True + + def native(queries, keys, values, scale, causal=False): + calls.append((scale, causal, "native")) + return mx.fast.scaled_dot_product_attention( + queries, + keys, + values, + scale=scale, + ) + + monkeypatch.setattr(fast, "NATIVE_AVAILABLE", True) + monkeypatch.setattr( + fast, + "_ext", + SimpleNamespace(sdpa_decode_supported=supported), + ) + monkeypatch.setattr(fast, "sdpa_decode", native) + actual = qsa_fast._decode_qsa_sdpa(q, k, v, 256**-0.5) + expected = mx.fast.scaled_dot_product_attention(q, k, v, scale=256**-0.5) + mx.eval(actual, expected) + + assert calls == [ + (q.shape, k.shape, v.shape, "probe"), + (256**-0.5, False, "native"), + ] + assert mx.array_equal(actual, expected).item() diff --git a/tests/test_qwen4_qsa_incremental_cache.py b/tests/test_qwen4_qsa_incremental_cache.py new file mode 100644 index 0000000000..136a891cb6 --- /dev/null +++ b/tests/test_qwen4_qsa_incremental_cache.py @@ -0,0 +1,230 @@ +"""Exactness and lifecycle tests for incremental Qwen4 QSA block caching.""" + +# SPDX-License-Identifier: Apache-2.0 + +from __future__ import annotations + +import importlib +import math + +import mlx.core as mx +import pytest + +from omlx.patches import mlx_vlm_qwen4_exp_compat as compat + + +compat.apply_mlx_vlm_qwen4_exp_compat_patch() +language = importlib.import_module("mlx_vlm.models.qwen4_exp.language") +qsa_fast = importlib.import_module("mlx_vlm.models.qwen4_exp.qsa_fast") + + +def _identity_rope(x, position_ids): + del position_ids + return x + + +def _append(cache, raw_keys, start, stop): + length = stop - start + keys = raw_keys[:, start:stop, :4].reshape(1, 1, length, 4) + values = (keys + 1).astype(keys.dtype) + cache.update_and_fetch(keys, values) + cache.update_indexer( + raw_keys[:, start:stop], + mx.arange(start, stop, dtype=mx.int32)[None], + ) + + +def test_qsa_kv_and_raw_index_buffers_grow_geometrically_with_logical_views(): + cache = language.QSAKVCache() + raw = mx.arange(8194 * 8, dtype=mx.float32).reshape(1, 8194, 8) + + _append(cache, raw, 0, 2050) + kv_backing = cache.keys + index_backing = cache._index_keys + assert cache.keys.shape[2] == 8192 + assert cache._index_keys.shape[1] == 8192 + assert cache.index_keys.shape == (1, 2050, 8) + + _append(cache, raw, 2050, 4098) + assert cache.keys is kv_backing + assert cache._index_keys is index_backing + assert cache.state[0].shape[2] == 4098 + assert cache.state[2].shape[1] == 4098 + + _append(cache, raw, 4098, 8194) + assert cache.keys.shape[2] == 16384 + assert cache._index_keys.shape[1] == 16384 + assert cache.state[0].shape[2] == 8194 + assert cache.state[2].shape[1] == 8194 + assert language.QSAQuantizedKVCache.step == 8192 + assert language.QSAQuantizedKVCache.geometric_growth is True + + +@pytest.mark.parametrize("chunks", [(2048, 2048, 2048), (2050, 2048, 2047)]) +def test_completed_qsa_blocks_match_one_shot_and_only_compute_new_suffix(chunks): + total = sum(chunks) + raw = mx.sin(mx.arange(total * 8, dtype=mx.float32)).reshape(1, total, 8) + incremental = language.QSAKVCache() + block_calls = [] + + def tracked_norm(x): + block_calls.append(int(x.shape[1])) + return x * mx.array(1.25, dtype=x.dtype) + + start = 0 + for length in chunks: + stop = start + length + incremental.update_indexer( + raw[:, start:stop], + mx.arange(start, stop, dtype=mx.int32)[None], + ) + actual = incremental.pooled_indexer_keys( + 4, + tracked_norm, + _identity_rope, + cache_tag=tracked_norm, + ) + start = stop + + calls_before_noop = list(block_calls) + cached_again = incremental.pooled_indexer_keys( + 4, + tracked_norm, + _identity_rope, + cache_tag=tracked_norm, + ) + assert block_calls == calls_before_noop + assert block_calls == [512, 512, 512] + + one_shot = qsa_fast.pool_completed_index_keys( + raw, + mx.arange(total, dtype=mx.int32)[None], + compress_ratio=4, + index_key_norm=lambda x: x * mx.array(1.25, dtype=x.dtype), + apply_index_rope=_identity_rope, + ) + mx.eval(actual, cached_again, one_shot) + assert mx.array_equal(actual, one_shot).item() + assert mx.array_equal(cached_again, one_shot).item() + + +@pytest.mark.parametrize("chunks", [(8, 8, 8), (6, 7, 12)]) +def test_gathered_qsa_one_shot_and_incremental_appends_are_exact(chunks, monkeypatch): + total = sum(chunks) + mx.random.seed(431) + queries = mx.random.normal((1, 4, total, 8)).astype(mx.float16) + keys = mx.random.normal((1, 2, total, 8)).astype(mx.float16) + values = mx.random.normal((1, 2, total, 8)).astype(mx.float16) + index_queries = mx.random.normal((1, total, 3, 8)).astype(mx.float16) + index_keys = mx.random.normal((1, total, 8)).astype(mx.float16) + positions = mx.arange(total, dtype=mx.int32)[None] + kwargs = dict( + num_query_heads=4, + num_key_value_heads=2, + head_dim=8, + indexer_head_dim=8, + compress_ratio=4, + token_budget=8, + index_key_norm=lambda x: x, + apply_index_rope=_identity_rope, + query_chunk=3, + ) + monkeypatch.setattr(qsa_fast, "_native_indexer_scores", lambda *a, **k: None) + + expected = qsa_fast.contiguous_causal_gathered_qsa( + queries, + keys, + values, + index_queries, + index_keys, + positions, + **kwargs, + ) + + cache = language.QSAKVCache() + outputs = [] + start = 0 + for length in chunks: + stop = start + length + cache.update_indexer(index_keys[:, start:stop], positions[:, start:stop]) + pooled = cache.pooled_indexer_keys( + 4, + kwargs["index_key_norm"], + kwargs["apply_index_rope"], + cache_tag=kwargs["index_key_norm"], + ) + outputs.append( + qsa_fast.contiguous_causal_gathered_qsa( + queries[:, :, start:stop], + keys[:, :, :stop], + values[:, :, :stop], + index_queries[:, start:stop], + cache.index_keys, + cache.index_position_ids, + pooled_index_keys=pooled, + **kwargs, + ) + ) + start = stop + actual = mx.concatenate(outputs, axis=1) + mx.eval(actual, expected) + assert mx.array_equal(actual, expected).item() + + +def test_qsa_ephemeral_pool_rebuilds_after_restore_extract_and_trim(): + cache = language.QSAKVCache() + raw = mx.sin(mx.arange(13 * 8, dtype=mx.float32)).reshape(1, 13, 8) + _append(cache, raw, 0, 13) + pooled = cache.pooled_indexer_keys( + 4, lambda x: x, _identity_rope, cache_tag=cache + ) + mx.eval(pooled) + assert cache._pooled_index_offset == 3 + assert len(cache.state) == 4 + + restored = language.QSAKVCache() + restored.prefix_cache_restore(cache.prefix_cache_snapshot()) + assert restored._pooled_index_keys is None + restored_pool = restored.pooled_indexer_keys( + 4, lambda x: x, _identity_rope, cache_tag=restored + ) + + extracted = cache.extract(0) + assert extracted._pooled_index_keys is None + extracted_pool = extracted.pooled_indexer_keys( + 4, lambda x: x, _identity_rope, cache_tag=extracted + ) + mx.eval(restored_pool, extracted_pool, pooled) + assert mx.array_equal(restored_pool, pooled).item() + assert mx.array_equal(extracted_pool, pooled).item() + + assert cache.trim(3) == 3 + assert cache._pooled_index_keys is None + replacement = mx.cos(mx.arange(3 * 8, dtype=mx.float32)).reshape(1, 3, 8) + _append(cache, mx.concatenate([raw[:, :10], replacement], axis=1), 10, 13) + rebuilt = cache.pooled_indexer_keys( + 4, lambda x: x, _identity_rope, cache_tag=cache + ) + expected = qsa_fast.pool_completed_index_keys( + cache.index_keys, + cache.index_position_ids, + compress_ratio=4, + index_key_norm=lambda x: x, + apply_index_rope=_identity_rope, + ) + mx.eval(rebuilt, expected) + assert mx.array_equal(rebuilt, expected).item() + + +@pytest.mark.parametrize("dtype", [mx.float16, mx.bfloat16]) +def test_portable_qsa_flattened_gemm_is_exactly_the_broadcast_reference(dtype): + mx.random.seed(909) + queries = mx.random.normal((1, 7, 4, 128)).astype(dtype) + pooled = mx.random.normal((1, 19, 128)).astype(dtype) + broadcast = queries.astype(mx.float32) @ pooled[:, None].astype( + mx.float32 + ).swapaxes(-1, -2) + expected = mx.sum(mx.maximum(broadcast, 0), axis=-2) / math.sqrt(128) + actual = qsa_fast._portable_indexer_scores(queries, pooled, 128) + mx.eval(actual, expected) + assert mx.array_equal(actual, expected).item() diff --git a/tests/test_qwen4_qsa_native_indexer.py b/tests/test_qwen4_qsa_native_indexer.py new file mode 100644 index 0000000000..dd78211281 --- /dev/null +++ b/tests/test_qwen4_qsa_native_indexer.py @@ -0,0 +1,229 @@ +"""Qwen4 QSA native H=4/D=128 indexer-score regression tests.""" + +# SPDX-License-Identifier: Apache-2.0 + +from __future__ import annotations + +import importlib +import math + +import mlx.core as mx +import pytest + +from omlx.custom_kernels.glm_moe_dsa import fast +from omlx.patches import mlx_vlm_qwen4_exp_compat as compat + + +compat.apply_mlx_vlm_qwen4_exp_compat_patch() +qsa_fast = importlib.import_module("mlx_vlm.models.qwen4_exp.qsa_fast") + + +def _native_available() -> bool: + return fast.is_native_available() and fast.has_symbol( + "qwen4_qsa_indexer_scores" + ) + + +def _reference_scores(q, k, *, mask_ratio=4, mask_q_offset=2048): + # Native q is [B,H,M,D]; the portable QSA expression uses [B,M,H,D]. + q_bmhd = q.transpose(0, 2, 1, 3) + scores = q_bmhd.astype(mx.float32) @ k.astype(mx.float32).swapaxes(-1, -2) + scores = mx.sum(mx.maximum(scores, 0), axis=-2) / math.sqrt(q.shape[-1]) + valid = mx.arange(k.shape[2])[None, None, :] < ( + mask_q_offset + mx.arange(q.shape[2])[None, :, None] + 1 + ) // mask_ratio + return mx.where(valid, scores, mx.finfo(mx.float32).min) + + +def _topk_sets(scores, topk): + indices = mx.argpartition(scores, kth=-topk, axis=-1)[..., -topk:] + return mx.sort(indices.astype(mx.int32), axis=-1) + + +def test_qwen4_qsa_symbol_is_part_of_the_extension_abi(): + assert "qwen4_qsa_indexer_scores" in fast.NATIVE_SYMBOLS + + +def test_qwen4_qsa_production_geometry_routes_to_native_abi(monkeypatch): + q = mx.zeros((1, 7, 4, 128), dtype=mx.bfloat16) + k = mx.zeros((1, 19, 128), dtype=mx.bfloat16) + seen = [] + + def scores(queries, pooled_keys, **kwargs): + seen.append((queries.shape, pooled_keys.shape, kwargs)) + return mx.zeros((1, 7, 19), dtype=mx.float32) + + monkeypatch.setattr(fast, "is_native_available", lambda: True) + monkeypatch.setattr(fast, "has_symbol", lambda name: True) + monkeypatch.setattr(fast, "qwen4_qsa_indexer_scores", scores) + monkeypatch.setattr(qsa_fast, "_NATIVE_QSA_SCORE_DISABLED", False) + monkeypatch.setattr(qsa_fast, "_NATIVE_QSA_SCORE_PROVEN", False) + + actual = qsa_fast._native_indexer_scores( + q, + k, + head_dim=128, + compress_ratio=4, + mask_q_offset=4096, + ) + assert actual is not None + assert seen == [ + ( + (1, 4, 7, 128), + (1, 1, 19, 128), + {"mask_ratio": 4, "mask_q_offset": 4096}, + ) + ] + assert qsa_fast._NATIVE_QSA_SCORE_PROVEN is True + + +def test_qwen4_native_dispatch_rejection_latches_to_portable(monkeypatch): + q = mx.zeros((1, 3, 4, 128), dtype=mx.bfloat16) + k = mx.zeros((1, 16, 128), dtype=mx.bfloat16) + calls = 0 + + def reject(*args, **kwargs): + nonlocal calls + calls += 1 + raise RuntimeError("stale native extension") + + monkeypatch.setattr(fast, "is_native_available", lambda: True) + monkeypatch.setattr(fast, "has_symbol", lambda name: True) + monkeypatch.setattr(fast, "qwen4_qsa_indexer_scores", reject) + monkeypatch.setattr(qsa_fast, "_NATIVE_QSA_SCORE_DISABLED", False) + monkeypatch.setattr(qsa_fast, "_NATIVE_QSA_SCORE_PROVEN", False) + + kwargs = dict( + head_dim=128, + compress_ratio=4, + mask_q_offset=2048, + ) + assert qsa_fast._native_indexer_scores(q, k, **kwargs) is None + assert qsa_fast._native_indexer_scores(q, k, **kwargs) is None + assert calls == 1 + + +def test_gathered_qsa_native_score_hook_matches_portable_path(monkeypatch): + mx.random.seed(19) + queries = mx.random.normal((1, 4, 20, 8)).astype(mx.bfloat16) + keys = mx.random.normal((1, 2, 20, 8)).astype(mx.bfloat16) + values = mx.random.normal((1, 2, 20, 8)).astype(mx.bfloat16) + index_queries = mx.random.normal((1, 20, 4, 128)).astype(mx.bfloat16) + index_keys = mx.random.normal((1, 20, 128)).astype(mx.bfloat16) + positions = mx.arange(20, dtype=mx.int32)[None] + seen_offsets = [] + + def fused_scores(q, k, **kwargs): + offset = kwargs["mask_q_offset"] + seen_offsets.append(offset) + scores = qsa_fast._portable_indexer_scores(q, k, 128) + valid = mx.arange(k.shape[1])[None, None, :] < ( + offset + mx.arange(q.shape[1])[None, :, None] + 1 + ) // 4 + return mx.where(valid, scores, mx.finfo(mx.float32).min) + + kwargs = dict( + num_query_heads=4, + num_key_value_heads=2, + head_dim=8, + indexer_head_dim=128, + compress_ratio=4, + token_budget=8, + index_key_norm=lambda x: x, + apply_index_rope=lambda x, position_ids: x, + query_chunk=7, + ) + monkeypatch.setattr(qsa_fast, "_native_indexer_scores", fused_scores) + actual = qsa_fast.contiguous_causal_gathered_qsa( + queries, + keys, + values, + index_queries, + index_keys, + positions, + **kwargs, + ) + monkeypatch.setattr(qsa_fast, "_native_indexer_scores", lambda *a, **k: None) + expected = qsa_fast.contiguous_causal_gathered_qsa( + queries, + keys, + values, + index_queries, + index_keys, + positions, + **kwargs, + ) + mx.eval(actual, expected) + + assert seen_offsets == [0, 7, 14] + assert mx.array_equal(actual, expected).item() + + +@pytest.mark.parametrize("dtype", [mx.bfloat16, mx.float16]) +@pytest.mark.skipif( + not _native_available(), + reason="native Qwen4 QSA indexer-score ABI is unavailable", +) +def test_qwen4_qsa_native_scores_and_topk_match_fp32_reference(dtype): + mx.random.seed(1729) + q = (mx.random.normal((1, 4, 67, 128)) * 0.25).astype(dtype) + k = (mx.random.normal((1, 1, 521, 128)) * 0.25).astype(dtype) + mask_q_offset = 2048 + + actual = fast.qwen4_qsa_indexer_scores( + q, + k, + mask_ratio=4, + mask_q_offset=mask_q_offset, + ) + expected = _reference_scores( + q, + k, + mask_ratio=4, + mask_q_offset=mask_q_offset, + ) + mx.eval(actual, expected) + + assert actual.shape == (1, 67, 521) + assert actual.dtype == mx.float32 + assert mx.array_equal(actual, expected).item() + assert mx.array_equal(_topk_sets(actual, 64), _topk_sets(expected, 64)).item() + + +@pytest.mark.skipif( + not _native_available(), + reason="native Qwen4 QSA indexer-score ABI is unavailable", +) +def test_qwen4_qsa_native_fuses_exact_float32_pooled_causal_sentinel(): + q = mx.ones((1, 4, 5, 128), dtype=mx.bfloat16) + k = mx.ones((1, 1, 11, 128), dtype=mx.bfloat16) + offset = 8 + actual = fast.qwen4_qsa_indexer_scores( + q, + k, + mask_ratio=4, + mask_q_offset=offset, + ) + mx.eval(actual) + + valid = mx.arange(11)[None, None, :] < ( + offset + mx.arange(5)[None, :, None] + 1 + ) // 4 + invalid_values = mx.where(valid, mx.finfo(mx.float32).min, actual) + assert mx.array_equal( + invalid_values, + mx.full(actual.shape, mx.finfo(mx.float32).min), + ).item() + + +@pytest.mark.skipif( + not _native_available(), + reason="native Qwen4 QSA indexer-score ABI is unavailable", +) +def test_qwen4_qsa_native_abi_rejects_nonproduction_geometry(): + with pytest.raises(ValueError, match="expected q"): + fast.qwen4_qsa_indexer_scores( + mx.zeros((1, 3, 8, 128), dtype=mx.bfloat16), + mx.zeros((1, 1, 16, 128), dtype=mx.bfloat16), + mask_q_offset=64, + ) diff --git a/tests/test_qwen4_qsa_native_topk.py b/tests/test_qwen4_qsa_native_topk.py new file mode 100644 index 0000000000..310466ec07 --- /dev/null +++ b/tests/test_qwen4_qsa_native_topk.py @@ -0,0 +1,146 @@ +"""Lossless native Qwen4 QSA FP32 top-512 regression tests.""" + +# SPDX-License-Identifier: Apache-2.0 + +from __future__ import annotations + +import mlx.core as mx +import numpy as np +import pytest + +from omlx.custom_kernels.glm_moe_dsa import fast + +TOPK = 512 + + +def _native_available() -> bool: + return fast.is_native_available() and fast.has_symbol("qwen4_qsa_topk_indices") + + +def _reference_indices(scores: mx.array) -> mx.array: + return mx.argpartition(scores, kth=-TOPK, axis=-1)[..., -TOPK:] + + +def _sorted_sets(indices: mx.array) -> mx.array: + return mx.sort(indices.astype(mx.int32), axis=-1) + + +def test_qwen4_qsa_topk_symbol_is_part_of_the_extension_abi(): + assert "qwen4_qsa_topk_indices" in fast.NATIVE_SYMBOLS + + +@pytest.mark.skipif( + not _native_available(), + reason="native Qwen4 QSA top-k ABI is unavailable", +) +@pytest.mark.parametrize("blocks", [12_500, 25_000]) +def test_qwen4_qsa_topk_matches_argpartition_at_50k_100k_equivalent(blocks): + """50K/100K tokens at Qwen4's four-token compression ratio.""" + rng = np.random.default_rng(41 + blocks) + scores = rng.standard_normal((1, 4, blocks), dtype=np.float32) + actual = fast.qwen4_qsa_topk_indices(mx.array(scores)) + expected = _reference_indices(mx.array(scores)) + mx.eval(actual, expected) + + assert actual.shape == (1, 4, TOPK) + assert actual.dtype == mx.uint32 + assert mx.array_equal(_sorted_sets(actual), _sorted_sets(expected)).item() + + +@pytest.mark.skipif( + not _native_available(), + reason="native Qwen4 QSA top-k ABI is unavailable", +) +def test_qwen4_qsa_topk_cutoff_ties_match_argpartition_membership(): + """MLX keeps the highest indices when a tie crosses the top-k cutoff.""" + scores = np.full((1, 1, 2048), -4.0, dtype=np.float32) + tie_indices = np.arange(200, 1600, dtype=np.int32) + strict_indices = np.concatenate( + ( + np.arange(0, 73, dtype=np.int32), + np.arange(1800, 1887, dtype=np.int32), + ) + ) + scores[0, 0, tie_indices] = np.float32(0.5) + scores[0, 0, strict_indices] = np.float32(1.0) + + actual = fast.qwen4_qsa_topk_indices(mx.array(scores)) + reference = _reference_indices(mx.array(scores)) + mx.eval(actual, reference) + + tie_budget = TOPK - strict_indices.size + expected = np.sort(np.concatenate((strict_indices, tie_indices[-tie_budget:]))) + actual_set = np.sort(np.asarray(actual, dtype=np.uint32)[0, 0]) + reference_set = np.sort(np.asarray(reference, dtype=np.uint32)[0, 0]) + np.testing.assert_array_equal(actual_set, expected) + np.testing.assert_array_equal(actual_set, reference_set) + + +@pytest.mark.skipif( + not _native_available(), + reason="native Qwen4 QSA top-k ABI is unavailable", +) +def test_qwen4_qsa_topk_treats_signed_zero_as_one_numeric_tie(): + scores = np.empty((1, 1, 1024), dtype=np.float32) + scores[..., ::2] = np.float32(-0.0) + scores[..., 1::2] = np.float32(0.0) + actual = fast.qwen4_qsa_topk_indices(mx.array(scores)) + reference = _reference_indices(mx.array(scores)) + mx.eval(actual, reference) + assert mx.array_equal(_sorted_sets(actual), _sorted_sets(reference)).item() + + +@pytest.mark.skipif( + not _native_available(), + reason="native Qwen4 QSA top-k ABI is unavailable", +) +@pytest.mark.parametrize("sentinel", [float("-inf"), np.finfo(np.float32).min]) +def test_qwen4_qsa_topk_matches_causal_sentinel_rows(sentinel): + """Sentinels sort below valid ties and keep MLX's tie membership.""" + blocks = 2048 + valid_counts = (257, 513, 617, 1025, 1537) + scores = np.full((1, len(valid_counts), blocks), sentinel, dtype=np.float32) + # Exact zero bands exercise QSA's ReLU ties at the same time as the mask. + for row, valid in enumerate(valid_counts): + scores[0, row, :valid] = np.float32(0.0) + + actual = fast.qwen4_qsa_topk_indices(mx.array(scores)) + reference = _reference_indices(mx.array(scores)) + mx.eval(actual, reference) + + assert mx.array_equal(_sorted_sets(actual), _sorted_sets(reference)).item() + actual_np = np.asarray(actual, dtype=np.uint32)[0] + for row, valid in enumerate(valid_counts): + if valid >= TOPK: + assert np.all(actual_np[row] < valid) + expected = np.arange(valid - TOPK, valid, dtype=np.uint32) + else: + # The ranked branch is discarded by QSA's canonical short-row + # selection, but the native primitive itself still matches MLX: + # every valid zero plus the highest-index sentinel ties. + expected = np.concatenate( + ( + np.arange(valid, dtype=np.uint32), + np.arange(blocks - (TOPK - valid), blocks, dtype=np.uint32), + ) + ) + np.testing.assert_array_equal(np.sort(actual_np[row]), expected) + + +@pytest.mark.skipif( + not _native_available(), + reason="native Qwen4 QSA top-k ABI is unavailable", +) +@pytest.mark.parametrize( + ("scores", "topk"), + [ + (mx.zeros((2, 1, 512), dtype=mx.float32), 512), + (mx.zeros((1, 512), dtype=mx.float32), 512), + (mx.zeros((1, 1, 512), dtype=mx.float16), 512), + (mx.zeros((1, 1, 511), dtype=mx.float32), 512), + (mx.zeros((1, 1, 512), dtype=mx.float32), 256), + ], +) +def test_qwen4_qsa_topk_fails_closed_outside_fixed_contract(scores, topk): + with pytest.raises(ValueError, match="qwen4_qsa_topk_indices"): + fast.qwen4_qsa_topk_indices(scores, topk) diff --git a/tests/test_qwen4_qsa_sparse_gqa.py b/tests/test_qwen4_qsa_sparse_gqa.py new file mode 100644 index 0000000000..a92126ab32 --- /dev/null +++ b/tests/test_qwen4_qsa_sparse_gqa.py @@ -0,0 +1,307 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Narrow native Qwen4 QSA main-attention regression tests.""" + +# SPDX-License-Identifier: Apache-2.0 + +from __future__ import annotations + +import mlx.core as mx +import pytest + +from omlx.custom_kernels.glm_moe_dsa import fast +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 import qsa_fast # noqa: E402 + + +def _native_available() -> bool: + return fast.is_native_available() and fast.has_symbol( + "qwen4_qsa_sparse_gqa_attention" + ) + + +def test_qwen4_sparse_gqa_symbol_is_part_of_extension_abi(): + assert "qwen4_qsa_sparse_gqa_attention" in fast.NATIVE_SYMBOLS + + +def test_qwen4_sparse_gqa_route_forwards_compact_blocks_and_transposes(monkeypatch): + queries = mx.zeros((1, 24, 3, 256), dtype=mx.bfloat16) + keys = mx.zeros((1, 2, 20, 256), dtype=mx.bfloat16) + values = mx.zeros_like(keys) + blocks = mx.broadcast_to( + mx.arange(512, dtype=mx.int32)[None, None], + (1, 3, 512), + ) + calls = [] + + monkeypatch.setattr(fast, "is_native_available", lambda: True) + monkeypatch.setattr(fast, "has_symbol", lambda name: True) + + def native( + q, + k, + v, + selected, + scale, + q_offset, + *, + key_tile=128, + dimension_tile=32, + stream=None, + ): + del k, v, stream + mx.eval(selected) + calls.append( + (selected.shape, selected.dtype, scale, q_offset, key_tile, dimension_tile) + ) + return mx.zeros(q.shape, dtype=q.dtype) + + monkeypatch.setattr(fast, "qwen4_qsa_sparse_gqa_attention", native) + monkeypatch.setattr(qsa_fast, "_NATIVE_QSA_MAIN_DISABLED", False) + monkeypatch.setattr(qsa_fast, "_NATIVE_QSA_MAIN_PROVEN", False) + + output = qsa_fast._native_sparse_gqa_attention( + queries, + keys, + values, + blocks, + q_offset=10, + ) + assert output is not None + mx.eval(output) + assert output.shape == (1, 3, 24, 256) + assert calls == [ + ( + (1, 1, 3, 512), + mx.uint32, + 256**-0.5, + 10, + 64, + 64, + ) + ] + + +def test_qwen4_sparse_gqa_route_fails_closed_outside_production_geometry( + monkeypatch, +): + monkeypatch.setattr(qsa_fast, "_NATIVE_QSA_MAIN_DISABLED", False) + bad_queries = mx.zeros((1, 4, 2, 256), dtype=mx.bfloat16) + keys = mx.zeros((1, 2, 4, 256), dtype=mx.bfloat16) + blocks = mx.zeros((1, 2, 3), dtype=mx.int32) + assert ( + qsa_fast._native_sparse_gqa_attention( + bad_queries, + keys, + keys, + blocks, + q_offset=2, + ) + is None + ) + + +def test_qwen4_prefill_restores_chronological_selected_order(monkeypatch): + mx.random.seed(81) + total = 10 + queries = mx.random.normal((1, 24, total, 256)).astype(mx.float16) + keys = mx.random.normal((1, 2, total, 256)).astype(mx.float16) + values = mx.random.normal((1, 2, total, 256)).astype(mx.float16) + index_queries = mx.random.normal((1, total, 2, 8)).astype(mx.float16) + index_keys = mx.random.normal((1, total, 8)).astype(mx.float16) + positions = mx.arange(total, dtype=mx.int32)[None] + captured = [] + + monkeypatch.setattr(qsa_fast, "_native_indexer_scores", lambda *a, **k: None) + + def reverse_topk(scores, topk): + del scores + return mx.broadcast_to( + mx.arange(topk - 1, -1, -1, dtype=mx.int32)[None, None], + (1, total, topk), + ) + + monkeypatch.setattr(qsa_fast, "_native_topk_indices", reverse_topk) + + def capture(q, k, v, selected, *, q_offset): + del k, v, q_offset + captured.append(selected) + return mx.zeros((1, q.shape[2], 24, 256), dtype=q.dtype) + + monkeypatch.setattr(qsa_fast, "_native_sparse_gqa_attention", capture) + output = qsa_fast.contiguous_causal_gathered_qsa( + queries, + keys, + values, + index_queries, + index_keys, + positions, + num_query_heads=24, + num_key_value_heads=2, + head_dim=256, + indexer_head_dim=8, + compress_ratio=2, + token_budget=8, + index_key_norm=lambda x: x, + apply_index_rope=lambda x, p: x, + query_chunk=total, + ) + mx.eval(output, *captured) + assert output.shape == (1, total, 24, 256) + selected = captured[0] + assert selected[0, -1].tolist() == [0, 1, 2, 3] + + +@pytest.mark.skipif(not _native_available(), reason="native Qwen4 GQA not built") +@pytest.mark.parametrize( + ("key_tile", "dimension_tile"), + [(64, 64), (128, 32), (256, 32)], +) +def test_qwen4_sparse_gqa_native_matches_fp32_gather_reference( + key_tile, + dimension_tile, +): + mx.random.seed(121) + query_tokens = 17 + key_tokens = 2111 + selected_blocks = 512 + q_offset = key_tokens - query_tokens + queries = mx.random.normal((1, 24, query_tokens, 256)).astype(mx.bfloat16) + keys = mx.random.normal((1, 2, key_tokens, 256)).astype(mx.bfloat16) + values = mx.random.normal((1, 2, key_tokens, 256)).astype(mx.bfloat16) + starts = mx.arange(query_tokens, dtype=mx.int32) + q_offset + blocks = mx.stack( + [ + mx.arange( + (int(end) + 1) // 4 - selected_blocks, + (int(end) + 1) // 4, + dtype=mx.int32, + ) + for end in starts + ], + axis=0, + )[None] + + native = fast.qwen4_qsa_sparse_gqa_attention( + queries, + keys, + values, + blocks[:, None].astype(mx.uint32), + 256**-0.5, + q_offset, + key_tile=key_tile, + dimension_tile=dimension_tile, + ) + complete = (starts + 1) // 4 + expanded = ( + blocks[..., None] * 4 + mx.arange(4, dtype=mx.int32) + ).reshape(1, query_tokens, 2048) + tail = complete[None, :, None] * 4 + mx.arange(3, dtype=mx.int32) + tail_valid = tail <= starts[None, :, None] + selected = mx.concatenate((expanded, tail), axis=-1) + selected_valid = mx.concatenate( + (mx.ones(expanded.shape, dtype=mx.bool_), tail_valid), axis=-1 + ) + key_rows = keys.transpose(0, 2, 1, 3) + value_rows = values.transpose(0, 2, 1, 3) + safe = mx.where(selected_valid, selected, 0) + gathered_k = qsa_fast._batch_gather_tokens(key_rows, safe).transpose( + 0, 1, 3, 2, 4 + ) + gathered_v = qsa_fast._batch_gather_tokens(value_rows, safe).transpose( + 0, 1, 3, 2, 4 + ) + grouped_q = queries.transpose(0, 2, 1, 3).reshape( + 1, query_tokens, 2, 12, 256 + ) + scores = ( + grouped_q.astype(mx.float32) + @ gathered_k.astype(mx.float32).swapaxes(-1, -2) + ) / (256**0.5) + scores = mx.where( + selected_valid[:, :, None, None], + scores, + mx.finfo(scores.dtype).min, + ) + probs = mx.softmax(scores, axis=-1).astype(queries.dtype) + reference = (probs @ gathered_v).reshape(1, query_tokens, 24, 256) + native_rows = native.transpose(0, 2, 1, 3) + mx.eval(native_rows, reference) + max_error = mx.max(mx.abs(native_rows.astype(mx.float32) - reference.astype(mx.float32))) + assert float(max_error.item()) <= 5e-3 + + +@pytest.mark.skipif(not _native_available(), reason="native Qwen4 GQA not built") +def test_qwen4_sparse_gqa_native_masks_future_blocks_in_first_chunk(): + """Canonical 0..511 placeholders must not expose future first-chunk K/V.""" + + mx.random.seed(313) + query_tokens = 33 + key_tokens = 4096 + queries = mx.random.normal((1, 24, query_tokens, 256)).astype(mx.bfloat16) + keys = mx.random.normal((1, 2, key_tokens, 256)).astype(mx.bfloat16) + values = mx.random.normal((1, 2, key_tokens, 256)).astype(mx.bfloat16) + blocks = mx.broadcast_to( + mx.arange(512, dtype=mx.uint32)[None, None], + (1, query_tokens, 512), + ) + + native = fast.qwen4_qsa_sparse_gqa_attention( + queries, + keys, + values, + blocks[:, None], + 256**-0.5, + 0, + key_tile=64, + dimension_tile=64, + ).transpose(0, 2, 1, 3) + + visible = mx.arange(1, query_tokens + 1, dtype=mx.int32)[None] + complete = visible // 4 + block_valid = mx.arange(512)[None, None, :] < complete[..., None] + expanded = ( + blocks.astype(mx.int32)[..., None] * 4 + + mx.arange(4, dtype=mx.int32) + ).reshape(1, query_tokens, 2048) + expanded_valid = mx.broadcast_to( + block_valid[..., None], (1, query_tokens, 512, 4) + ).reshape(1, query_tokens, 2048) + tail = complete[..., None] * 4 + mx.arange(3, dtype=mx.int32) + tail_valid = tail < visible[..., None] + selected = mx.concatenate((expanded, tail), axis=-1) + selected_valid = mx.concatenate((expanded_valid, tail_valid), axis=-1) + safe = mx.where(selected_valid, selected, 0) + + gathered_k = qsa_fast._batch_gather_tokens( + keys.transpose(0, 2, 1, 3), safe + ).transpose(0, 1, 3, 2, 4) + gathered_v = qsa_fast._batch_gather_tokens( + values.transpose(0, 2, 1, 3), safe + ).transpose(0, 1, 3, 2, 4) + grouped_q = queries.transpose(0, 2, 1, 3).reshape( + 1, query_tokens, 2, 12, 256 + ) + scores = ( + grouped_q.astype(mx.float32) + @ gathered_k.astype(mx.float32).swapaxes(-1, -2) + ) / (256**0.5) + scores = mx.where( + selected_valid[:, :, None, None], + scores, + mx.finfo(scores.dtype).min, + ) + reference = ( + mx.softmax(scores, axis=-1).astype(queries.dtype) @ gathered_v + ).reshape(1, query_tokens, 24, 256) + mx.eval(native, reference) + + error = mx.abs(native.astype(mx.float32) - reference.astype(mx.float32)) + # The zero-prefix row has exactly one visible value and must therefore be + # bit-identical; this is the strongest future-leak sentinel. Later tiny + # rows differ by at most one BF16 output ULP because native online softmax + # keeps probabilities in FP32 while the portable oracle casts them first. + assert mx.array_equal(native[:, :1], reference[:, :1]).item() + assert float(mx.max(error).item()) <= 2e-2 diff --git a/tests/test_qwen4_vision_grid_compat.py b/tests/test_qwen4_vision_grid_compat.py new file mode 100644 index 0000000000..3bd69b9ab0 --- /dev/null +++ b/tests/test_qwen4_vision_grid_compat.py @@ -0,0 +1,74 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Qwen4-Exp image/video grid compatibility with newer MLX releases.""" + +# SPDX-License-Identifier: Apache-2.0 + +from __future__ import annotations + +from types import SimpleNamespace + +import mlx.core as mx + +from omlx.patches import mlx_vlm_qwen4_exp_compat as compat + + +class _CaptureBlock: + def __init__(self): + self.cu_seqlens = None + + def __call__(self, hidden_states, *, cu_seqlens, rotary_pos_emb): + self.cu_seqlens = cu_seqlens + assert rotary_pos_emb.shape == hidden_states.shape + return hidden_states + + +def _vision_shell(): + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp import VisionModel + + # Exercise the real Qwen4 override while replacing expensive ViT modules + # with shape-preserving test doubles. This reaches the exact mlx.repeat + # boundary that regressed on MLX 0.32.2. + vision = VisionModel.__new__(VisionModel) + vision.patch_embed = lambda hidden_states: hidden_states + vision.fast_pos_embed_interpolate = lambda grid_thw: mx.zeros( + (int(mx.sum(mx.prod(grid_thw, axis=1)).item()), 4), dtype=mx.float32 + ) + vision.rot_pos_emb = lambda grid_thw: mx.zeros( + (int(mx.sum(mx.prod(grid_thw, axis=1)).item()), 4), dtype=mx.float32 + ) + block = _CaptureBlock() + vision.blocks = [block] + vision.deepstack_visual_indexes = [] + vision.deepstack_merger_list = [] + vision.merger = lambda hidden_states: hidden_states + return SimpleNamespace(vision=vision, block=block) + + +def test_qwen4_image_grid_scalarizes_mlx_repeat_count(): + shell = _vision_shell() + grid_thw = mx.array([[1, 2, 3]], dtype=mx.int64) + hidden_states = mx.zeros((6, 4), dtype=mx.float32) + + output, deepstack = shell.vision(hidden_states, grid_thw) + mx.eval(output, shell.block.cu_seqlens) + + assert output.shape == (6, 4) + assert deepstack == [] + assert shell.block.cu_seqlens.tolist() == [0, 6] + + +def test_qwen4_video_and_mixed_grids_preserve_frame_boundaries(): + shell = _vision_shell() + # One two-frame video followed by a one-frame image. The shared tower is + # used for both modalities, and each temporal patch needs its own spatial + # attention boundary. + grid_thw = mx.array([[2, 2, 3], [1, 2, 2]], dtype=mx.int64) + hidden_states = mx.zeros((16, 4), dtype=mx.float32) + + output, deepstack = shell.vision(hidden_states, grid_thw) + mx.eval(output, shell.block.cu_seqlens) + + assert output.shape == (16, 4) + assert deepstack == [] + assert shell.block.cu_seqlens.tolist() == [0, 6, 12, 16] diff --git a/tests/test_scheduler.py b/tests/test_scheduler.py index 023c055496..870d6fe746 100644 --- a/tests/test_scheduler.py +++ b/tests/test_scheduler.py @@ -3332,6 +3332,29 @@ def test_qwen35_wide_prefill_aligns_block_size_to_4096( finally: scheduler.shutdown() + def test_qwen4_wide_prefill_aligns_block_size_to_4096( + self, mock_tokenizer, tmp_path + ): + with ( + patch("omlx.settings.get_system_memory", return_value=256 * 1024**3), + patch("omlx.custom_kernels.nax.is_nax_available", return_value=False), + ): + scheduler = Scheduler( + model=self._hybrid_model(model_type="qwen4_exp_text"), + tokenizer=mock_tokenizer, + config=SchedulerConfig( + paged_ssd_cache_dir=str(tmp_path), + paged_cache_block_size=256, + ), + ) + + try: + assert scheduler._qwen35_prefill_floor == 4096 + assert scheduler._prefill_step_size_for_progress(0, 4096) == 4096 + assert scheduler.config.paged_cache_block_size == 4096 + finally: + scheduler.shutdown() + def test_qwen35_nax_host_keeps_2048_block(self, mock_tokenizer, tmp_path): with ( patch("omlx.settings.get_system_memory", return_value=64 * 1024**3), From 0a6ae09f599f34dd05e8daa4d0945cec44c6ca72 Mon Sep 17 00:00:00 2001 From: jundot Date: Sun, 30 Aug 2026 01:44:37 +0900 Subject: [PATCH 051/132] fix(qwen4): gate wide prefill on sparse native kernel (#3244) --- .../mlx_vlm/models/qwen4_exp/qsa_fast.py | 15 ++---- omlx/scheduler.py | 19 +++++--- tests/test_qwen4_qsa_decode_gather.py | 5 +- tests/test_qwen4_qsa_sparse_gqa.py | 3 -- tests/test_qwen4_vision_grid_compat.py | 2 - tests/test_scheduler.py | 47 +++++++++++++++++++ 6 files changed, 65 insertions(+), 26 deletions(-) diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/qsa_fast.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/qsa_fast.py index 8dd799ea91..399f7b5c0f 100644 --- a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/qsa_fast.py +++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/qsa_fast.py @@ -1,15 +1,9 @@ # SPDX-License-Identifier: Apache-2.0 -"""Exact gathered QSA prefill for contiguous batch-one text prompts. +"""Exact gathered QSA for contiguous batch-one text prompts. -This is the exact path proven by Fusion's native Qwen4-Exp bring-up. It never -constructs the full ``[query_tokens, key_tokens]`` main-attention matrix: QSA -selects complete four-token micro-blocks, then the production native kernel -reads those rows directly from K/V. Portable MLX gathers only the selected -rows (plus the incomplete causal tail) when that narrow ABI is unavailable. - -The caller owns eligibility. In particular, this module is only used for a -single contiguous text prompt. Batched, padded, multimodal and target-verify -requests stay on mlx-vlm's general QSA implementation. +The native path reads selected four-token blocks directly from K/V. The MLX +fallback gathers the selected rows and causal tail. Batched, padded, +multimodal, and target-verify requests use mlx-vlm's general implementation. """ from __future__ import annotations @@ -19,7 +13,6 @@ import mlx.core as mx - IndexKeyNorm = Callable[[mx.array], mx.array] IndexRoPE = Callable[[mx.array, mx.array], mx.array] diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 4e0c38b8d5..9cdd9f1f6a 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -2730,17 +2730,22 @@ def _detect_qwen35_prefill_floor(self) -> int: model_type = str( getattr(getattr(self.model, "config", None), "model_type", "") or "" ) - if model_type.startswith(("qwen3_5", "qwen4_exp")): + is_qwen35 = model_type.startswith("qwen3_5") + is_qwen4 = model_type.startswith("qwen4_exp") + if is_qwen4: + from .custom_kernels.glm_moe_dsa import fast + + if not fast.is_native_available() or not fast.has_symbol( + "qwen4_qsa_sparse_gqa_attention" + ): + return 0 + if is_qwen35 or is_qwen4: from .custom_kernels.nax import is_nax_available from .settings import get_system_memory if get_system_memory() >= 64 * 1024**3 and not is_nax_available(): - # Measured on the 27B (M3 Ultra, 2026-08-17): chunk 4096 - # beats the 2048 default +3.2% at 4k prompts / +1.0% at - # 16k; 8192 is flat versus 4096. Qwen4's direct-index QSA - # likewise removes the selected-K/V memory reason for - # 2048-row tiles. Keep 2048 on NAX/M5, where wider Qwen - # prefill regresses throughput (#2880). + # Qwen4 needs its sparse native path before wider chunks + # are safe. NAX/M5 stays at 2048 for both model families. return 4096 except Exception: logger.debug("qwen3_5 prefill floor probe failed", exc_info=True) diff --git a/tests/test_qwen4_qsa_decode_gather.py b/tests/test_qwen4_qsa_decode_gather.py index 08a37b8c8c..2b65845ff2 100644 --- a/tests/test_qwen4_qsa_decode_gather.py +++ b/tests/test_qwen4_qsa_decode_gather.py @@ -1,8 +1,6 @@ # SPDX-License-Identifier: Apache-2.0 """Batch-one Qwen4 QSA decode gather regression tests.""" -# SPDX-License-Identifier: Apache-2.0 - from __future__ import annotations from types import SimpleNamespace @@ -133,7 +131,6 @@ def test_qwen4_language_wrapper_routes_2d_text_positions_to_gather(monkeypatch): original_prefill_eligible = ( language.Qwen4ExpAttention._gathered_text_prefill_eligible ) - original_decode_eligible = language.Qwen4ExpAttention._gathered_text_decode_eligible def tracked_prefill(self, x, cache, position_ids=None): calls.append(("prefill", position_ids.ndim, position_ids.shape)) @@ -313,6 +310,7 @@ def tracked_sdpa(q, k, v, scale): def test_qwen4_decode_sdpa_fails_closed_when_native_shape_is_rejected(monkeypatch): compat.apply_mlx_vlm_qwen4_exp_compat_patch() import mlx_vlm.models.qwen4_exp.qsa_fast as qsa_fast + from omlx.custom_kernels.decode_fast import fast q = mx.random.normal((1, 4, 1, 8)) @@ -339,6 +337,7 @@ def must_not_run(*args, **kwargs): def test_qwen4_decode_sdpa_uses_native_only_after_capability_accepts(monkeypatch): compat.apply_mlx_vlm_qwen4_exp_compat_patch() import mlx_vlm.models.qwen4_exp.qsa_fast as qsa_fast + from omlx.custom_kernels.decode_fast import fast q = mx.random.normal((1, 24, 1, 256)).astype(mx.bfloat16) diff --git a/tests/test_qwen4_qsa_sparse_gqa.py b/tests/test_qwen4_qsa_sparse_gqa.py index a92126ab32..f7b85764d2 100644 --- a/tests/test_qwen4_qsa_sparse_gqa.py +++ b/tests/test_qwen4_qsa_sparse_gqa.py @@ -1,8 +1,6 @@ # SPDX-License-Identifier: Apache-2.0 """Narrow native Qwen4 QSA main-attention regression tests.""" -# SPDX-License-Identifier: Apache-2.0 - from __future__ import annotations import mlx.core as mx @@ -11,7 +9,6 @@ from omlx.custom_kernels.glm_moe_dsa import fast 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 import qsa_fast # noqa: E402 diff --git a/tests/test_qwen4_vision_grid_compat.py b/tests/test_qwen4_vision_grid_compat.py index 3bd69b9ab0..5b0c13690d 100644 --- a/tests/test_qwen4_vision_grid_compat.py +++ b/tests/test_qwen4_vision_grid_compat.py @@ -1,8 +1,6 @@ # SPDX-License-Identifier: Apache-2.0 """Qwen4-Exp image/video grid compatibility with newer MLX releases.""" -# SPDX-License-Identifier: Apache-2.0 - from __future__ import annotations from types import SimpleNamespace diff --git a/tests/test_scheduler.py b/tests/test_scheduler.py index 870d6fe746..54c773870c 100644 --- a/tests/test_scheduler.py +++ b/tests/test_scheduler.py @@ -3338,6 +3338,14 @@ def test_qwen4_wide_prefill_aligns_block_size_to_4096( with ( patch("omlx.settings.get_system_memory", return_value=256 * 1024**3), patch("omlx.custom_kernels.nax.is_nax_available", return_value=False), + patch( + "omlx.custom_kernels.glm_moe_dsa.fast.is_native_available", + return_value=True, + ), + patch( + "omlx.custom_kernels.glm_moe_dsa.fast.has_symbol", + return_value=True, + ), ): scheduler = Scheduler( model=self._hybrid_model(model_type="qwen4_exp_text"), @@ -3355,6 +3363,45 @@ def test_qwen4_wide_prefill_aligns_block_size_to_4096( finally: scheduler.shutdown() + @pytest.mark.parametrize( + ("native_available", "symbol_available"), + [(False, False), (True, False)], + ) + def test_qwen4_keeps_2048_without_sparse_native_path( + self, + mock_tokenizer, + tmp_path, + native_available, + symbol_available, + ): + with ( + patch("omlx.settings.get_system_memory", return_value=256 * 1024**3), + patch("omlx.custom_kernels.nax.is_nax_available", return_value=False), + patch( + "omlx.custom_kernels.glm_moe_dsa.fast.is_native_available", + return_value=native_available, + ), + patch( + "omlx.custom_kernels.glm_moe_dsa.fast.has_symbol", + return_value=symbol_available, + ), + ): + scheduler = Scheduler( + model=self._hybrid_model(model_type="qwen4_exp_text"), + tokenizer=mock_tokenizer, + config=SchedulerConfig( + paged_ssd_cache_dir=str(tmp_path), + paged_cache_block_size=256, + ), + ) + + try: + assert scheduler._qwen35_prefill_floor == 0 + assert scheduler._prefill_step_size_for_progress(0, 4096) == 2048 + assert scheduler.config.paged_cache_block_size == 2048 + finally: + scheduler.shutdown() + def test_qwen35_nax_host_keeps_2048_block(self, mock_tokenizer, tmp_path): with ( patch("omlx.settings.get_system_memory", return_value=64 * 1024**3), From 1d7826185c5b5b69b38b27cbe57d7597b7551fd7 Mon Sep 17 00:00:00 2001 From: jundot Date: Sun, 30 Aug 2026 01:45:20 +0900 Subject: [PATCH 052/132] chore: bump version to 0.6.4 --- omlx/_version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/omlx/_version.py b/omlx/_version.py index 63af88769b..364e7baed0 100644 --- a/omlx/_version.py +++ b/omlx/_version.py @@ -1 +1 @@ -__version__ = "0.6.3" +__version__ = "0.6.4" From e008a66b4703bc77404dab30f8f898a117d49dfe Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Sat, 29 Aug 2026 17:05:29 +0000 Subject: [PATCH 053/132] formula: bump to 0.6.4 --- Formula/omlx.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Formula/omlx.rb b/Formula/omlx.rb index b618e83c5c..e35b1876bb 100644 --- a/Formula/omlx.rb +++ b/Formula/omlx.rb @@ -3,8 +3,8 @@ class Omlx < Formula desc "LLM inference server optimized for Apple Silicon" homepage "https://github.com/jundot/omlx" - url "https://github.com/jundot/omlx/archive/refs/tags/v0.6.3.tar.gz" - sha256 "3a5588c09b086c5064604165ca23c4d61eb94c2003cd236f3febd8a53cc045cb" + url "https://github.com/jundot/omlx/archive/refs/tags/v0.6.4.tar.gz" + sha256 "5d8781c0c6a782e9b90f071d36b0d8dbe6161fafb5fef5e3f0d8ac71da214b70" license "Apache-2.0" head "https://github.com/jundot/omlx.git", branch: "main" From 8b2ade32b0aaac6ac851c3929d013f75f34fd603 Mon Sep 17 00:00:00 2001 From: Jun Kim <64250138+jundot@users.noreply.github.com> Date: Mon, 31 Aug 2026 23:09:02 +0900 Subject: [PATCH 054/132] build: upgrade MLX to 0.32.2 with runtime compatibility (#3332) --- .github/workflows/build-wheels.yml | 38 ++- docs/heterogeneous-cluster.md | 6 +- docs/laguna-mlxfast-port-correctness.md | 2 +- omlx/cache/boundary_snapshot_store.py | 10 + omlx/cluster/cuda_worker_bootstrap.py | 4 +- .../bonsai/csrc/bonsai_quantized.metal | 7 +- .../qwen35_prefill/csrc/qwen35_prefill.cpp | 2 +- omlx/engine_core.py | 106 +++---- omlx/engine_pool.py | 33 ++- omlx/memory_monitor.py | 67 +++-- omlx/models/embedding.py | 2 - omlx/models/reranker.py | 2 - omlx/patches/gemma4_verify_attention.py | 35 ++- omlx/patches/m5_gather_qmm.py | 4 +- omlx/patches/mlx_vlm_mlx0322_compat.py | 236 +++++++++++++++ .../patches/mlx_vlm_mtp/gemma4_vlm_runtime.py | 6 +- omlx/patches/qwen35_fa256_attention.py | 50 +++- omlx/patches/sdpa256_attention.py | 269 +++++++++--------- omlx/scheduler.py | 28 +- omlx/speculative/vlm_mtp.py | 31 +- omlx/utils/compile_cache.py | 108 ------- omlx/utils/metal_sync.py | 15 + omlx/utils/model_loading.py | 19 +- pyproject.toml | 14 +- tests/test_cluster_worker_bundle.py | 4 +- tests/test_compile_cache.py | 45 --- tests/test_embedding.py | 9 +- tests/test_engine_core.py | 52 ++-- tests/test_engine_pool.py | 20 +- tests/test_gdn_sidecar_quantization.py | 8 + tests/test_gemma4_verify_attention.py | 22 ++ tests/test_memory_monitor.py | 14 +- tests/test_memory_monitor_vlm_config.py | 8 +- tests/test_mlx0322_compat.py | 122 ++++++++ tests/test_per_engine_threads.py | 84 +++--- tests/test_qwen35_fa256_attention.py | 37 ++- tests/test_qwen4_qsa_prefill_memory.py | 1 + tests/test_reranker_causal_lm.py | 4 - tests/test_scheduler.py | 3 + tests/test_sdpa256_attention.py | 176 ++++++++++-- tests/test_vlm_mtp.py | 11 + 41 files changed, 1171 insertions(+), 543 deletions(-) create mode 100644 omlx/patches/mlx_vlm_mlx0322_compat.py delete mode 100644 omlx/utils/compile_cache.py delete mode 100644 tests/test_compile_cache.py create mode 100644 tests/test_mlx0322_compat.py diff --git a/.github/workflows/build-wheels.yml b/.github/workflows/build-wheels.yml index 9c67a168fe..156f03fea6 100644 --- a/.github/workflows/build-wheels.yml +++ b/.github/workflows/build-wheels.yml @@ -45,7 +45,7 @@ jobs: # we build against the job's Python and pin it for CMake explicitly. run: | python -m pip install --upgrade pip - python -m pip install build setuptools wheel "cmake>=3.27" "nanobind==2.13.0" "mlx==0.32.0" + python -m pip install build setuptools wheel "cmake>=3.27" "nanobind==2.15.0" "mlx==0.32.2" export CMAKE_ARGS="-DPython_EXECUTABLE=$(python -c 'import sys; print(sys.executable)')" python -m build --wheel --no-isolation @@ -60,14 +60,46 @@ jobs: cd /tmp /tmp/wheel-smoke/bin/python - <<'PY' import importlib + import mlx.core as mx + failed = [] - for pkg in ("bonsai", "glm_moe_dsa", "minimax_m3", "qwen35_prefill"): + for pkg in ( + "bonsai", + "decode_fast", + "glm_moe_dsa", + "minimax_m3", + "qwen35_prefill", + ): fast = importlib.import_module(f"omlx.custom_kernels.{pkg}.fast") ok = bool(fast.is_native_available()) print(f"{pkg}: native_available={ok} import_error={fast.import_error()}") if not ok: failed.append(pkg) - raise SystemExit(f"native kernels missing from wheel: {failed}" if failed else 0) + if failed: + raise SystemExit(f"native kernels missing from wheel: {failed}") + + # Exercise a real primitive from the newest native package, not just + # its nanobind ABI probe, so the wheel also proves dylib/metallib + # lookup and MLX 0.32.2 runtime dispatch. + from omlx.custom_kernels.decode_fast import fast as decode_fast + + mx.random.seed(3142) + q = mx.random.normal((1, 4, 1, 64)).astype(mx.float16) + k = mx.random.normal((1, 2, 128, 64)).astype(mx.float16) + v = mx.random.normal((1, 2, 128, 64)).astype(mx.float16) + if not decode_fast._ext.sdpa_decode_supported(q, k, v): + raise SystemExit("decode_fast rejected the wheel smoke shape") + out = decode_fast.sdpa_decode(q, k, v, 64 ** -0.5) + ref = mx.fast.scaled_dot_product_attention( + q, k, v, scale=64 ** -0.5 + ) + mx.eval(out, ref) + error = mx.max( + mx.abs(out.astype(mx.float32) - ref.astype(mx.float32)) + ).item() + print(f"decode_fast: shape={out.shape} max_abs={error}") + if error >= 5e-3: + raise SystemExit(f"decode_fast mismatch: max_abs={error}") PY - name: Upload wheel artifact diff --git a/docs/heterogeneous-cluster.md b/docs/heterogeneous-cluster.md index 31af302c50..7951ba573d 100644 --- a/docs/heterogeneous-cluster.md +++ b/docs/heterogeneous-cluster.md @@ -77,9 +77,9 @@ contiguous-layer and physical-memory checks may adjust or refuse. ## Current platform reality This design no longer depends on treating CUDA support as an unofficial MLX -experiment. [MLX 0.32.0 officially supports CUDA 12 and CUDA 13](https://ml-explore.github.io/mlx/build/html/install.html), +experiment. [MLX 0.32.2 officially supports CUDA 12 and CUDA 13](https://ml-explore.github.io/mlx/build/html/install.html), including Linux ARM wheels relevant to DGX Spark. oMLX already pins -`mlx==0.32.0` in this branch. +`mlx==0.32.2` in this branch. MLX provides several distributed transports: @@ -337,7 +337,7 @@ The Mac application remains a Metal distribution. The GUI bootstrap creates a headless Linux ARM64 environment using the official CUDA wheel set: ```text -mlx[cuda13]==0.32.0 +mlx[cuda13]==0.32.2 same pinned MLX-LM revision same oMLX cluster/runtime code no macOS app, Metal-only extension, or Mac authorization dependency diff --git a/docs/laguna-mlxfast-port-correctness.md b/docs/laguna-mlxfast-port-correctness.md index 4875d1e6f0..36ba0c994b 100644 --- a/docs/laguna-mlxfast-port-correctness.md +++ b/docs/laguna-mlxfast-port-correctness.md @@ -39,7 +39,7 @@ migration `4799830` and are not part of the current model surface). - **Optimization:** compile `[sigmoid(logits), -(sigmoid(logits)+bias)]` into one kernel (four elementwise launches per router call, 39 per token). - **Token-exactness issue:** a compiled function returning TWO outputs that consume the same `sigmoid(a)` intermediate is bit-exact on the GitHub `macos-14-arm64` runner but diverges from eager at ULP on an M3 Ultra (5.96e-8–2.38e-7, deterministic, isolated to the multi-consumer shape). Single-output compiled fusions reusing the same sigmoid are bit-exact, so the trigger is the two-output shape on affected GPUs. It feeds `argpartition` expert selection — a ULP flip at a near-tie boundary changes WHICH experts are gathered (a different forward, not a small perturbation), i.e. the challenge's own documented correctness cliff ("Rank is the wrong metric"). - **Mitigation:** kept eager in the port for portable token exactness; bounded numerical parity is pinned by `test_two_output_compiled_tail_is_numerically_close` on both bit-exact and ULP-divergent GPUs. -- **Hardware and MLX-version dependence:** property of MLX 0.32.0 compiled kernels varies by Apple GPU; re-verify across supported GPU generations after any MLX bump. +- **Hardware and MLX-version dependence:** property of MLX 0.32.2 compiled kernels varies by Apple GPU; re-verify across supported GPU generations after any MLX bump. ### C2 — `logits_last_only` head slicing is ULP-divergent (frame divergence) diff --git a/omlx/cache/boundary_snapshot_store.py b/omlx/cache/boundary_snapshot_store.py index 09ae91a0d0..a83726fcf6 100644 --- a/omlx/cache/boundary_snapshot_store.py +++ b/omlx/cache/boundary_snapshot_store.py @@ -425,6 +425,11 @@ def load( arrays, metadata = data else: return None + # mx.load returns file-backed lazy arrays. Materialize them while + # this ephemeral snapshot still exists so the reconstructed cache + # cannot retain a read primitive past cleanup or promotion. + if arrays: + mx.eval(*arrays.values()) return self._reconstruct_from_safetensors(arrays, metadata) except Exception as e: logger.debug( @@ -456,6 +461,11 @@ def load_file(self, file_path: Path) -> list[dict[str, Any]] | None: if not (isinstance(data, tuple) and len(data) == 2): return None arrays, metadata = data + # ``take_staged_file`` transfers this path to a caller that may + # move or unlink it immediately after load_file returns. Detach + # every lazy input from the file before returning cache state. + if arrays: + mx.eval(*arrays.values()) return self._reconstruct_from_safetensors(arrays, metadata) except Exception as e: logger.debug("Failed to load committed boundary snapshot %s: %s", file_path, e) diff --git a/omlx/cluster/cuda_worker_bootstrap.py b/omlx/cluster/cuda_worker_bootstrap.py index f38399c4a6..895c0fa63e 100644 --- a/omlx/cluster/cuda_worker_bootstrap.py +++ b/omlx/cluster/cuda_worker_bootstrap.py @@ -37,8 +37,8 @@ MAX_SOURCE_MEMBERS = 4096 WORKER_REQUIREMENTS = ( "numpy>=1.24.0,<2.4", - "mlx==0.32.0", - "mlx-cuda-13==0.32.0", + "mlx==0.32.2", + "mlx-cuda-13==0.32.2", "mlx-lm @ git+https://github.com/ml-explore/mlx-lm@ab1806e8f5d6aa035973af194a1b9198ab4754dc", "transformers>=5.12.1,<5.13", "mistral-common>=1.10", diff --git a/omlx/custom_kernels/bonsai/csrc/bonsai_quantized.metal b/omlx/custom_kernels/bonsai/csrc/bonsai_quantized.metal index d1c354cd8a..71a7de8016 100644 --- a/omlx/custom_kernels/bonsai/csrc/bonsai_quantized.metal +++ b/omlx/custom_kernels/bonsai/csrc/bonsai_quantized.metal @@ -1,10 +1,9 @@ // Copyright © 2026 oMLX contributors // SPDX-License-Identifier: Apache-2.0 // -// Instantiates only the Bonsai-specific kernel variants that are not present -// in the stock mlx 0.32.0 metallib: -// - affine_qmv_fast for bits=1 (1-bit path added by Bonsai MLX fork) -// - affine_qmv_wide for bits=1 and bits=2 (new kernel from Bonsai fork) +// Instantiates the Bonsai-specific entry points used by the native extension. +// Stock MLX 0.32.2 now includes generic 2-bit qmv_fast/qmv_wide kernels, while +// 1-bit support and the extension's symmetric-bias routes remain Bonsai-only. // // The vendored quantized.h in this directory is the Bonsai-patched version. // It must shadow the mlx-installed copy; CMake sets -I for this directory diff --git a/omlx/custom_kernels/qwen35_prefill/csrc/qwen35_prefill.cpp b/omlx/custom_kernels/qwen35_prefill/csrc/qwen35_prefill.cpp index b8b5004ecd..d871360d0a 100644 --- a/omlx/custom_kernels/qwen35_prefill/csrc/qwen35_prefill.cpp +++ b/omlx/custom_kernels/qwen35_prefill/csrc/qwen35_prefill.cpp @@ -831,7 +831,7 @@ class Qwen35MoeWeightedSumPrimitive : public Primitive { } // namespace bool is_nax_available() { - // Mirror of mlx::core::metal::is_nax_available() (mlx v0.32.0 device.cpp), + // Mirror of mlx::core::metal::is_nax_available() (mlx v0.32.2 device.cpp), // which libmlx does not export: macOS >= 26.2 and applegpu gen >= 17 // ('p'-suffix parts need gen >= 18). static bool available = []() { diff --git a/omlx/engine_core.py b/omlx/engine_core.py index 9f99d0e165..bb9aaadabe 100644 --- a/omlx/engine_core.py +++ b/omlx/engine_core.py @@ -44,12 +44,9 @@ from .output_collector import RequestOutputCollector, RequestStreamState from .request import Request, RequestOutput, SamplingParams from .scheduler import Scheduler, SchedulerConfig, _sync_and_clear_cache -from .utils.compile_cache import ( - clear_thread_compile_cache, - compile_cache_clear_available, -) from .utils.fatal import FATAL_TEARDOWN_TIMEOUT_S, fatal_exit from .utils.hardware import format_bytes +from .utils.metal_sync import clear_thread_streams logger = logging.getLogger(__name__) @@ -81,22 +78,21 @@ def _raise_request_output_error(output: RequestOutput) -> None: _global_mlx_executor: concurrent.futures.ThreadPoolExecutor | None = None -# Fallback only: used when the MLX compile-cache clear symbol is unavailable -# (see omlx/utils/compile_cache.py). In that case a per-engine MLX worker -# thread cannot exit safely (its thread_local ~CompilerCache would free -# @mx.compile graphs' Python objects without the GIL -> crash), so close() -# keeps the executor + stream alive here for the process lifetime instead of -# shutting the thread down. With the clear symbol present (the normal path) -# these stay empty and the worker threads shut down normally. -_immortal_mlx_executors: list = [] -_immortal_mlx_streams: list = [] - def _final_engine_thread_reclaim(stream: Any) -> None: """Drop Python cycles and reclaim MLX buffers on the engine worker thread.""" gc.collect() _sync_and_clear_cache(stream) gc.collect() + clear_thread_streams() + + +def _final_global_mlx_thread_reclaim() -> None: + """Reclaim MLX state before the process-wide worker thread exits.""" + gc.collect() + _sync_and_clear_cache() + gc.collect() + clear_thread_streams() def _init_mlx_thread() -> None: @@ -147,6 +143,34 @@ def get_mlx_executor() -> concurrent.futures.ThreadPoolExecutor: return _global_mlx_executor +def shutdown_mlx_executor() -> None: + """Shut down the global MLX worker after clearing its thread-local streams.""" + global _global_mlx_executor + executor = _global_mlx_executor + if executor is None: + return + + try: + future = executor.submit(_final_global_mlx_thread_reclaim) + except RuntimeError: + # An embedding application may have shut the executor down directly. + future = None + + if future is not None: + try: + future.result(timeout=FATAL_TEARDOWN_TIMEOUT_S) + except concurrent.futures.TimeoutError: + fatal_exit( + "Global MLX executor teardown timed out after " + f"{FATAL_TEARDOWN_TIMEOUT_S:.0f}s" + ) + except Exception as exc: + fatal_exit(f"Global MLX executor teardown failed: {exc!r}") + + executor.shutdown(wait=False) + _global_mlx_executor = None + + @dataclass class EngineConfig: """Configuration for the engine.""" @@ -1215,53 +1239,31 @@ def close(self) -> None: if self._mlx_executor is not None: try: - self._mlx_executor.submit( + reclaim_future = self._mlx_executor.submit( _final_engine_thread_reclaim, self._mlx_stream - ).result(timeout=FATAL_TEARDOWN_TIMEOUT_S) - except concurrent.futures.TimeoutError: - fatal_exit( - f"Engine teardown timed out after " - f"{FATAL_TEARDOWN_TIMEOUT_S:.0f}s while reclaiming " - f"MLX memory for engine {self._engine_id}" ) except RuntimeError: - pass - except Exception: - logger.warning( - "Engine %s: final MLX reclaim raised during close()", - self._engine_id, - exc_info=True, - ) + reclaim_future = None - # MLX's @mx.compile cache is a C++ thread_local CompilerCache. If - # this worker thread exits with a non-empty cache, ~CompilerCache - # frees the cached graphs' Python objects from a thread-exit handler - # WITHOUT the GIL -> "PyThreadState_Get: GIL is released" crash for - # models with module-scope @mx.compile graphs (DeepSeek V4 unload, - # ml-explore/mlx #3280). Clear the cache ON this worker thread (GIL - # held) before the thread is torn down so the destructor runs on an - # empty cache, then request shutdown without waiting indefinitely. - # See utils/compile_cache.py. - if compile_cache_clear_available(): + if reclaim_future is not None: try: - self._mlx_executor.submit(clear_thread_compile_cache).result( - timeout=FATAL_TEARDOWN_TIMEOUT_S - ) + reclaim_future.result(timeout=FATAL_TEARDOWN_TIMEOUT_S) except concurrent.futures.TimeoutError: fatal_exit( f"Engine teardown timed out after " - f"{FATAL_TEARDOWN_TIMEOUT_S:.0f}s while clearing " - f"MLX compile cache for engine {self._engine_id}" + f"{FATAL_TEARDOWN_TIMEOUT_S:.0f}s while reclaiming " + f"MLX memory for engine {self._engine_id}" ) - except RuntimeError: - pass - self._mlx_executor.shutdown(wait=False) - else: - # Fallback: the clear symbol is unavailable, so do NOT exit the - # worker thread (that would run the unsafe destructor). Keep it - # alive for the process lifetime via the module-global registry. - _immortal_mlx_executors.append(self._mlx_executor) - _immortal_mlx_streams.append(self._mlx_stream) + except Exception as exc: + fatal_exit( + f"Engine {self._engine_id}: final MLX reclaim failed: " + f"{exc!r}" + ) + + # MLX 0.32.2 makes compiled AttachedData destruction GIL-safe, and + # _final_engine_thread_reclaim clears the worker's per-thread stream + # registry before ThreadPoolExecutor lets that worker exit. + self._mlx_executor.shutdown(wait=False) self._mlx_executor = None logger.debug(f"Engine {self._engine_id} closed") diff --git a/omlx/engine_pool.py b/omlx/engine_pool.py index 9ec150669f..9e7969b446 100644 --- a/omlx/engine_pool.py +++ b/omlx/engine_pool.py @@ -39,7 +39,7 @@ from .engine.stt import STTEngine from .engine.tts import TTSEngine from .engine.vlm import VLMBatchedEngine -from .engine_core import get_mlx_executor +from .engine_core import get_mlx_executor, shutdown_mlx_executor from .exceptions import ( DEFAULT_CEILING_ADVICE, InsufficientMemoryError, @@ -299,6 +299,8 @@ def __init__( self._load_time_observations: int = 0 self._lease_release_tasks: set[asyncio.Task[None]] = set() self._pending_unload_tasks: dict[str, asyncio.Task[None]] = {} + self._failed_load_reclaim_tasks: set[asyncio.Task[None]] = set() + self._failed_load_reclaim_task: asyncio.Task[None] | None = None self._shutting_down = False self.configure_hot_cache_budget() @@ -2431,6 +2433,15 @@ async def _unload_engine(self, model_id: str) -> None: self._wake_process_memory_enforcer() + def _finish_failed_load_reclaim_task(self, task: asyncio.Task[None]) -> None: + self._failed_load_reclaim_tasks.discard(task) + try: + task.result() + except asyncio.CancelledError: + pass + except Exception: + logger.exception("Post-failed-load reclaim task failed") + def _schedule_failed_load_reclaim( self, model_id: str, pre_load_memory: int ) -> None: @@ -2474,11 +2485,15 @@ async def _reclaim() -> None: ) self._wake_process_memory_enforcer() - # Keep a reference so the task isn't garbage-collected mid-flight; - # one slot suffices -- a newer failure supersedes the previous task. - self._failed_load_reclaim_task = asyncio.get_running_loop().create_task( - _reclaim() + # Keep every task reachable until it finishes. Concurrent load failures + # can overlap, and shutdown must cancel/drain all of them before the + # process-wide MLX executor is reclaimed. + task = asyncio.get_running_loop().create_task( + _reclaim(), name=f"engine-failed-load-reclaim:{model_id}" ) + self._failed_load_reclaim_task = task + self._failed_load_reclaim_tasks.add(task) + task.add_done_callback(self._finish_failed_load_reclaim_task) async def _load_engine( self, @@ -3028,6 +3043,13 @@ async def preload_pinned_models(self) -> None: async def shutdown(self) -> None: """Shutdown all engines gracefully.""" self._shutting_down = True + reclaim_tasks = tuple(self._failed_load_reclaim_tasks) + for task in reclaim_tasks: + task.cancel() + if reclaim_tasks: + await asyncio.gather(*reclaim_tasks, return_exceptions=True) + self._failed_load_reclaim_tasks.clear() + self._failed_load_reclaim_task = None pending_tasks = tuple(self._pending_unload_tasks.values()) if pending_tasks: await asyncio.gather(*pending_tasks, return_exceptions=True) @@ -3041,6 +3063,7 @@ async def shutdown(self) -> None: except Exception as e: logger.error(f"Error unloading {model_id} during shutdown: {e}") + shutdown_mlx_executor() logger.info("Engine pool shutdown complete") def get_status(self) -> dict: diff --git a/omlx/memory_monitor.py b/omlx/memory_monitor.py index 39cb9ecb27..703feee9b1 100644 --- a/omlx/memory_monitor.py +++ b/omlx/memory_monitor.py @@ -43,7 +43,7 @@ # different head dimensions; unsupported cases fall back to an unfused # score-matrix allocation. _SDPA_VECTOR_QUERY_TOKEN_THRESHOLD = 8 -_SDPA_FULL_SUPPORTED_HEAD_DIMS = frozenset({64, 80, 128}) +_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 # compute dtype is unknown. MLX softmax accumulates in fp32, but the dominant @@ -58,22 +58,43 @@ # kernel instead of the unfused O(L^2) score-matrix fallback. Populated at # runtime by the kernel patch that installs the route (see # omlx/patches/sdpa256_attention.py); empty otherwise, so the estimate stays -# O(L^2) when no such kernel is active. Maps head_dim -> kv_tile (the kernel's -# KV block width, which bounds the per-chunk score transient). -_SDPA_TILED_PREFILL_HEAD_DIMS: dict[int, int] = {} -_SDPA_TILED_MIN_KV_LEN = 8192 +# O(L^2) when no such kernel is active. Each entry records the query/KV shape +# floor actually covered by the installed route plus a conservative score-tile +# width for admission accounting. + + +@dataclass(frozen=True) +class _BoundedSDPAPrefillRoute: + min_query_len: int + min_kv_len: int + kv_tile: int + + +_SDPA_TILED_PREFILL_HEAD_DIMS: dict[int, tuple[_BoundedSDPAPrefillRoute, ...]] = {} def register_tiled_prefill_head_dim( - head_dim: int, *, min_kv_len: int = 8192, kv_tile: int = 1024 + head_dim: int, + *, + min_query_len: int = 2, + min_kv_len: int = 8192, + kv_tile: int = 1024, ) -> None: - """Register a head_dim whose long-context prefill now uses an O(L) tiled - kernel, so the prefill memory estimate stops charging the O(L^2) score - matrix for it. Must be called in lockstep with installing the kernel route, - or the guard keeps rejecting valid long-context requests.""" - global _SDPA_TILED_MIN_KV_LEN - _SDPA_TILED_PREFILL_HEAD_DIMS[int(head_dim)] = int(kv_tile) - _SDPA_TILED_MIN_KV_LEN = int(min_kv_len) + """Register a bounded long-context route installed for one head dim. + + Multiple native routes may cover the same head dimension at different + thresholds. Store them independently so combining two registrations can + never invent shape coverage that neither route actually guarantees. + """ + head_dim = int(head_dim) + route = _BoundedSDPAPrefillRoute( + min_query_len=max(2, int(min_query_len)), + min_kv_len=max(1, int(min_kv_len)), + kv_tile=max(1, int(kv_tile)), + ) + routes = _SDPA_TILED_PREFILL_HEAD_DIMS.get(head_dim, ()) + if route not in routes: + _SDPA_TILED_PREFILL_HEAD_DIMS[head_dim] = (*routes, route) # Bytes/elem of a model-built additive attention bias materialized as a @@ -729,12 +750,14 @@ def _estimate_sdpa_activation_bytes(self, query_tokens: int, kv_len: int) -> int # [n_q, query_tokens, kv_len] matrix. This matches the kernel's route # gate (query_len > 1, kv_len >= threshold); any query_len <= 1 already # returned above via the fused vector path. - kv_tile = _SDPA_TILED_PREFILL_HEAD_DIMS.get(hd) - if ( - kv_tile is not None - and query_tokens > 1 - and kv_len >= _SDPA_TILED_MIN_KV_LEN - ): + bounded_routes = _SDPA_TILED_PREFILL_HEAD_DIMS.get(hd, ()) + matching_routes = [ + route + for route in bounded_routes + if query_tokens >= route.min_query_len and kv_len >= route.min_kv_len + ] + if matching_routes: + kv_tile = max(route.kv_tile for route in matching_routes) tile_scores = ( n_q * query_tokens * min(kv_tile, kv_len) * self._score_dtype_size ) @@ -760,9 +783,9 @@ def estimate_prefill_peak_bytes( cache pool / python heap overhead (absorbed by enforcer's hard threshold margin — see MemorySettings.hard_threshold). - MLX SDPA only uses fused full-attention kernels for the head dimensions - supported by ``ScaledDotProductAttention::use_fallback``. Unsupported - prefill chunks fall back to an unfused fp32 score matrix whose K + MLX SDPA uses its fused full-attention kernels only for shapes accepted + by ``ScaledDotProductAttention::use_fallback``. Other prefill chunks + fall back to an unfused score matrix whose K dimension spans the full key/value context. With prefix-cache hits, that context is ``new_tokens + cached_tokens``, not just the new suffix. Passing only ``new_tokens`` here silently under-counts long-context diff --git a/omlx/models/embedding.py b/omlx/models/embedding.py index 821fd89b4b..6cac890c50 100644 --- a/omlx/models/embedding.py +++ b/omlx/models/embedding.py @@ -19,7 +19,6 @@ import mlx.core as mx from mlx.utils import tree_flatten -from ..utils.compile_cache import clear_thread_compile_cache from ..utils.image import validate_image_data_uri from .base_model import last_token_pool, mean_pooling, normalize_embeddings from .mlx_embeddings_compat import ( @@ -741,7 +740,6 @@ def close(self) -> None: gc.collect() mx.synchronize() mx.clear_cache() - clear_thread_compile_cache() gc.collect() def embed( diff --git a/omlx/models/reranker.py b/omlx/models/reranker.py index fb6b9ef227..519d80513e 100644 --- a/omlx/models/reranker.py +++ b/omlx/models/reranker.py @@ -27,7 +27,6 @@ _is_causal_lm_reranker, ) from ..patches.qwen3_sliding_window import apply_qwen3_sliding_window_patch -from ..utils.compile_cache import clear_thread_compile_cache from ..utils.image import load_image from .mlx_embeddings_compat import ( patch_qwen3_vl_processor_for_torch_free_image_loading, @@ -943,7 +942,6 @@ def close(self) -> None: gc.collect() mx.synchronize() mx.clear_cache() - clear_thread_compile_cache() gc.collect() # Default max_length per model type diff --git a/omlx/patches/gemma4_verify_attention.py b/omlx/patches/gemma4_verify_attention.py index f74de81519..7db23903ee 100644 --- a/omlx/patches/gemma4_verify_attention.py +++ b/omlx/patches/gemma4_verify_attention.py @@ -1,12 +1,12 @@ # SPDX-License-Identifier: Apache-2.0 """Small-L attention route for gemma4 speculative verify forwards. -MLX's fused SDPA only covers head_dim {64, 80, 128} for multi-token -queries; gemma4 (head_dim 256 sliding / 512 global) therefore drops to the -unfused path for any L >= 2 forward. For the global layers that cost grows -with context — the L=1 -> L=2 step measured +88% at 16k ctx on the 26B MoE -— and is what makes MTP verify cycles lose to plain decoding on -low-accept content. +Gemma4 uses head_dim 256 for sliding layers and 512 for global layers. MLX +0.32.2 now handles small multi-row head-dim-256 calls with its native vector +kernel, so this patch explicitly leaves those shapes alone. Head-dim 512 still +has no fused MLX route; for global layers that unfused cost grows with context +and is what makes MTP verify cycles lose to plain decoding on low-accept +content. Two routes, picked per layer: @@ -57,6 +57,18 @@ _MAX_L = 3 # per-token route ceiling (sliding layers / kernel fallback) _KERNEL_MAX_L = 12 # fused kernel ceiling; stock batched wins past ~12 +_MLX0322_FULL_HEAD_DIMS = frozenset({64, 72, 80, 96, 128}) +_MLX0322_VECTOR_HEAD_DIMS = frozenset({64, 96, 128, 256}) + + +def _mlx0322_default_fused(head_dim: int, query_len: int, gqa_factor: int) -> bool: + if query_len <= 8: + return ( + head_dim in _MLX0322_VECTOR_HEAD_DIMS + and query_len * gqa_factor <= 32 + ) + return head_dim in _MLX0322_FULL_HEAD_DIMS + def apply() -> bool: """Wrap ``mlx_vlm.models.gemma4.language.Attention.__call__``. Idempotent.""" @@ -101,6 +113,7 @@ def _kernel_cache_ok(cache, dtype) -> bool: def __call__(self, x, mask=None, cache=None, shared_kv=None, offset=None): B, L, _ = x.shape + gqa_factor = self.n_heads // self.n_kv_heads if ( shared_kv is not None or cache is None @@ -112,6 +125,14 @@ def __call__(self, x, mask=None, cache=None, shared_kv=None, offset=None): self, x, mask, cache, shared_kv=shared_kv, offset=offset ) + # Do not replace a shape MLX 0.32.2 already sends to a native fused + # kernel. This is the common Gemma4 sliding-layer verify path at + # head_dim=256 and L<=4. + if _mlx0322_default_fused(self.head_dim, L, gqa_factor): + return original_call( + self, x, mask, cache, shared_kv=shared_kv, offset=offset + ) + use_kernel = ( not self.is_sliding and L <= _KERNEL_MAX_L @@ -122,7 +143,7 @@ def __call__(self, x, mask=None, cache=None, shared_kv=None, offset=None): # GPUs cap below 32 * gqa threads); infeasible geometry falls # back before the batched cache update commits us to the route. and gemma4_verify_kernel.kernel_max_rows( - self.n_heads // self.n_kv_heads, x.dtype + gqa_factor, x.dtype ) > 0 ) diff --git a/omlx/patches/m5_gather_qmm.py b/omlx/patches/m5_gather_qmm.py index 59ae18815b..ea1b3d9cc1 100644 --- a/omlx/patches/m5_gather_qmm.py +++ b/omlx/patches/m5_gather_qmm.py @@ -4,7 +4,7 @@ On M5-generation GPUs mlx dispatches ``sorted_indices=True`` quantized gather matmuls (the MoE sorted-prefill path) to the NAX ``*_gather_qmm_rhs_nax`` kernels. Two independent defects corrupt their -output on mlx <= 0.32.0: +output through mlx 0.32.2: - K remainder: the ``align_K=false`` tail bounds the activation tile load by ``BK`` instead of the K remainder @@ -15,7 +15,7 @@ issue #2267's bit-exactness test caught: with ``inter=32`` the test's ``down_proj`` runs at K=32. All dtypes are affected (bf16/fp16/fp32), and the mxfp4 variant carries the same tail bug. -- Row offsets: the int16 fix that landed in mlx 0.32.0 missed this +- Row offsets: the int16 fix that landed in mlx 0.32.0 still misses this kernel, so sorted row counts above 32768 overflow the row offset (ml-explore/mlx#3856). Reachable in production: a 4097+ token prefill chunk of a top-8 MoE crosses the boundary. diff --git a/omlx/patches/mlx_vlm_mlx0322_compat.py b/omlx/patches/mlx_vlm_mlx0322_compat.py new file mode 100644 index 0000000000..33dc33843d --- /dev/null +++ b/omlx/patches/mlx_vlm_mlx0322_compat.py @@ -0,0 +1,236 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Backport the narrow mlx-vlm changes required by MLX 0.32.2. + +The pinned mlx-vlm revision predates upstream PRs #1949, #1982, and #2006. +MLX 0.32.2 stopped accepting scalar ``mx.array`` objects where Python integer +dimensions are required and changed ``mx.random.state`` from a mutable list to +a proxy whose member arrays must be updated in place. Affected models otherwise +fail in speculative RNG restoration, ``mx.repeat``, shape construction, or +Metal grid dispatch. + +Moving the mlx-vlm pin to any of these merge commits would also import hundreds of +unrelated upstream changes. Instead, this module installs a source loader for +the exact affected modules and applies only the upstream integer conversions. +Each replacement is checked before compilation: an unexpected pinned source +fails loudly instead of leaving a partially applied compatibility patch. +""" + +from __future__ import annotations + +import importlib +import importlib.abc +import importlib.machinery +import inspect +import logging +import sys +from dataclasses import dataclass + +logger = logging.getLogger(__name__) + + +@dataclass(frozen=True) +class _Replacement: + old: str + new: str + count: int = 1 + + +_REPEAT_GRID = _Replacement( + "mx.repeat(seq_len, grid_thw[i, 0])", + "mx.repeat(seq_len, int(grid_thw[i, 0]))", +) + +_MODULE_REPLACEMENTS: dict[str, tuple[_Replacement, ...]] = { + "mlx_vlm.speculative.common": ( + _Replacement( + "mx.random.state[i] = value", + "mx.random.state[i][:] = value", + ), + ), + "mlx_vlm.models.aya_vision.vision": ( + _Replacement( + "height, width = spatial_shapes[i]", + "height, width = spatial_shapes[i].tolist()", + ), + ), + "mlx_vlm.models.dots_ocr.vision": (_REPEAT_GRID,), + "mlx_vlm.models.glm4v.vision": ( + _Replacement( + "mx.repeat(image_shapes[i, 1], lengths[i])", + "mx.repeat(image_shapes[i, 1], int(lengths[i]))", + ), + _Replacement( + "mx.repeat(image_shapes[i, 2], lengths[i])", + "mx.repeat(image_shapes[i, 2], int(lengths[i]))", + ), + ), + "mlx_vlm.models.glm4v_moe.vision": ( + _Replacement( + "mx.repeat(image_shapes[i, 1], lengths[i])", + "mx.repeat(image_shapes[i, 1], int(lengths[i]))", + ), + _Replacement( + "mx.repeat(image_shapes[i, 2], lengths[i])", + "mx.repeat(image_shapes[i, 2], int(lengths[i]))", + ), + ), + "mlx_vlm.models.lfm2_vl.lfm2_vl": ( + _Replacement( + "feature_org_h, feature_org_w = spatial_shapes[img_idx]", + "feature_org_h, feature_org_w = (\n" + " int(dim) for dim in spatial_shapes[img_idx]\n" + " )", + ), + ), + "mlx_vlm.models.paddleocr_vl.vision": (_REPEAT_GRID,), + "mlx_vlm.models.qwen2_5_vl.vision": (_REPEAT_GRID,), + "mlx_vlm.models.qwen2_vl.vision": ( + _Replacement( + "h, w = int(h), int(w) # Ensure h and w are integers", + "t, h, w = int(t), int(h), int(w)", + ), + _REPEAT_GRID, + ), + "mlx_vlm.models.qwen3_omni_moe.vision": (_REPEAT_GRID,), + "mlx_vlm.models.qwen3_vl.vision": (_REPEAT_GRID,), + "mlx_vlm.models.qwen3_vl_moe.vision": (_REPEAT_GRID,), + "mlx_vlm.models.kernels": ( + _Replacement( + "import mlx.core as mx", + "import math\n\nimport mlx.core as mx", + ), + _Replacement( + "grid=(mx.prod(mx.array(out_shape)), 1, 1)", + "grid=(math.prod(out_shape), 1, 1)", + ), + ), +} + +_INSTALLED = False + + +def _patch_source(fullname: str, source: str) -> str: + replacements = _MODULE_REPLACEMENTS[fullname] + patched = source + for replacement in replacements: + # Prefer the already-fixed form first. This matters when ``old`` is a + # substring of ``new`` (the kernels.py import insertion), and keeps a + # future upstream-fixed pin from receiving the same edit twice. + if patched.count(replacement.new) == replacement.count: + continue + old_count = patched.count(replacement.old) + if old_count == replacement.count: + patched = patched.replace( + replacement.old, replacement.new, replacement.count + ) + continue + + # Any other shape is an explicit pin/patch mismatch. + raise ImportError( + f"MLX 0.32.2 mlx-vlm compatibility patch mismatch for {fullname}: " + f"expected {replacement.count} occurrence(s), found {old_count}" + ) + return patched + + +class _CompatLoader(importlib.abc.Loader): + def __init__(self, fullname: str, delegate: importlib.abc.Loader): + self.fullname = fullname + self.delegate = delegate + + def create_module(self, spec): + create_module = getattr(self.delegate, "create_module", None) + return create_module(spec) if create_module is not None else None + + def exec_module(self, module) -> None: + get_source = getattr(self.delegate, "get_source", None) + if get_source is None: + raise ImportError(f"source unavailable for {self.fullname}") + source = get_source(self.fullname) + if source is None: + raise ImportError(f"source unavailable for {self.fullname}") + filename = getattr(module.__spec__, "origin", None) or self.fullname + code = compile(_patch_source(self.fullname, source), filename, "exec") + exec(code, module.__dict__) + + +class _CompatFinder(importlib.abc.MetaPathFinder): + _omlx_mlx_vlm_mlx0322_compat = True + + def find_spec(self, fullname, path=None, target=None): + if fullname not in _MODULE_REPLACEMENTS: + return None + spec = importlib.machinery.PathFinder.find_spec(fullname, path) + if spec is None or spec.loader is None: + return None + spec.loader = _CompatLoader(fullname, spec.loader) + return spec + + +def _reload_and_rebind(fullname: str, module) -> None: + """Patch an early import and update mlx-vlm's copied references.""" + old_objects = { + name: value + for name, value in vars(module).items() + if (inspect.isclass(value) or inspect.isfunction(value)) + and getattr(value, "__module__", None) == fullname + } + old_generation_stream = ( + getattr(module, "generation_stream", None) + if fullname == "mlx_vlm.speculative.common" + else None + ) + importlib.reload(module) + replacements = { + old: getattr(module, name) + for name, old in old_objects.items() + if hasattr(module, name) and getattr(module, name) is not old + } + new_generation_stream = ( + getattr(module, "generation_stream", None) + if old_generation_stream is not None + else None + ) + if not replacements and new_generation_stream is old_generation_stream: + return + for loaded_name, loaded in list(sys.modules.items()): + if loaded is None or not loaded_name.startswith("mlx_vlm."): + continue + for name, value in list(vars(loaded).items()): + if value is old_generation_stream: + setattr(loaded, name, new_generation_stream) + continue + if not (inspect.isclass(value) or inspect.isfunction(value)): + continue + replacement = replacements.get(value) + if replacement is not None: + setattr(loaded, name, replacement) + + +def apply_mlx_vlm_mlx0322_compat_patch() -> bool: + """Install the MLX 0.32.2 loader before mlx-vlm model imports.""" + global _INSTALLED + if _INSTALLED: + return False + + finder = _CompatFinder() + sys.meta_path.insert(0, finder) + + # Normal oMLX loading installs this hook before importing a model module. + # Reload any target imported by an embedding application earlier so the + # process cannot retain the incompatible code silently. + try: + for fullname in _MODULE_REPLACEMENTS: + module = sys.modules.get(fullname) + if module is not None: + _reload_and_rebind(fullname, module) + except Exception: + sys.meta_path.remove(finder) + raise + + _INSTALLED = True + logger.info("mlx-vlm MLX 0.32.2 compatibility patch installed") + return True + + +__all__ = ["apply_mlx_vlm_mlx0322_compat_patch"] diff --git a/omlx/patches/mlx_vlm_mtp/gemma4_vlm_runtime.py b/omlx/patches/mlx_vlm_mtp/gemma4_vlm_runtime.py index 2723f7f543..ca90f09ef6 100644 --- a/omlx/patches/mlx_vlm_mtp/gemma4_vlm_runtime.py +++ b/omlx/patches/mlx_vlm_mtp/gemma4_vlm_runtime.py @@ -81,9 +81,9 @@ def apply() -> bool: _patch_vlm_model_adapter() - # Small-L verify forwards otherwise pay gemma4's unfused multi-token - # attention (head_dim 256/512 has no fused SDPA above L=1); the - # decomposed route keeps shallow-depth speculation profitable. + # MLX 0.32.2 covers Gemma4's head-dim-256 small-L shapes natively. Global + # head-dim-512 verify still needs the custom fused route to keep + # shallow-depth speculation profitable. from ..gemma4_verify_attention import apply as apply_verify_attention apply_verify_attention() diff --git a/omlx/patches/qwen35_fa256_attention.py b/omlx/patches/qwen35_fa256_attention.py index c9961f1588..5ef9352e4b 100644 --- a/omlx/patches/qwen35_fa256_attention.py +++ b/omlx/patches/qwen35_fa256_attention.py @@ -83,6 +83,13 @@ def _has_quantized_cache(cache) -> bool: return cache is not None and hasattr(cache, "bits") +def _bounded_sdpa_fallback(queries, keys, values, scale, mask, sinks): + """Keep the registered O(L) contract if the steel kernel itself fails.""" + from .sdpa256_attention import _flash_sdpa256 + + return _flash_sdpa256(queries, keys, values, scale, mask, sinks) + + def _auto_dispatch_budget(kernel, q_block: int, k_block: int) -> int: """Size the dispatch budget from the kernel's measured throughput. @@ -190,14 +197,13 @@ def apply_qwen35_fa256_attention_patch(min_kv_len: int | None = None) -> bool: if steel_env == "0": return False if steel_env != "1" and is_nax_available(): - # Auto: on NAX GPUs (M5 family) stock SDPA's head_dim-256 fallback - # runs its matmuls on the tensor units and beats this pre-NAX steel - # kernel, so routing it would regress prefill (M5 Max report: - # 4k pp 828 -> 400 tok/s on 0.5.0). OMLX_FA256_STEEL=1 forces the - # kernel on for benchmarking; a NAX port of this kernel is the - # tracked follow-up. + # Auto: MLX 0.32.2 selects its native split-D fused kernel for NAX + # head-dim-256 causal prefills with at least 1024 queries. It beats + # this pre-NAX steel kernel, so intercepting it would regress prefill. + # OMLX_FA256_STEEL=1 still forces the kernel for benchmarking. logger.info( - "Qwen FA-256 steel patch skipped: NAX GPU, stock SDPA is faster" + "Qwen FA-256 steel patch skipped: NAX GPU, MLX native fused SDPA " + "is faster" ) return False @@ -263,7 +269,13 @@ def patched_lm_sdpa( dispatch_budget=dispatch_budget, ) except Exception: - logger.warning("fa256 steel lm kernel failed", exc_info=True) + logger.warning( + "fa256 steel lm kernel failed; using bounded MLX SDPA", + exc_info=True, + ) + return _bounded_sdpa_fallback( + queries, keys, values, scale, mask, sinks + ) return original_lm_sdpa(queries, keys, values, cache, scale, mask, sinks) mlx_base.scaled_dot_product_attention = patched_lm_sdpa @@ -313,7 +325,13 @@ def patched_vlm_sdpa( dispatch_budget=dispatch_budget, ) except Exception: - logger.warning("fa256 steel vlm kernel failed", exc_info=True) + logger.warning( + "fa256 steel vlm kernel failed; using bounded MLX SDPA", + exc_info=True, + ) + return _bounded_sdpa_fallback( + queries, keys, values, scale, mask, sinks + ) return original_vlm_sdpa( queries, keys, values, cache, scale, mask, sinks ) @@ -332,6 +350,20 @@ def patched_vlm_sdpa( pass if patched_any: + try: + from .. import memory_monitor + + memory_monitor.register_tiled_prefill_head_dim( + 256, + min_query_len=_MIN_ROUTE_Q_LEN, + min_kv_len=min_kv_len, + kv_tile=1024, + ) + except Exception: + logger.debug( + "could not register Qwen FA-256 with memory_monitor", + exc_info=True, + ) _PATCHED = True logger.info( "Qwen3.5/3.6 FA-256 steel attention patch applied " diff --git a/omlx/patches/sdpa256_attention.py b/omlx/patches/sdpa256_attention.py index e18f854651..5f2811fd1b 100644 --- a/omlx/patches/sdpa256_attention.py +++ b/omlx/patches/sdpa256_attention.py @@ -1,28 +1,22 @@ # SPDX-License-Identifier: Apache-2.0 -"""Patch scaled_dot_product_attention to fix head_dim=256 long-context prefill. - -MLX's fused SDPA kernel supports head_dim in {64, 80, 128} only, so head_dim=256 -(e.g. Qwen3.6-27B) multi-token prefill falls back to an unfused path that -materializes the full ``[n_q, query_len, kv_len]`` score matrix -> O(L^2) memory, -OOMing / tripping the prefill guard far below the context window. Decode -(query_len == 1) is unaffected (MLX has a fused vector kernel for 256). - -This routes head_dim=256 causal prefill to a flash-style online-softmax pass in -pure MLX array ops (tiled over KV; running max/sum/accumulator) that never -materializes the score matrix -> peak memory O(L). It rides MLX's GEMM, so speed -is on par with the fallback; the win is memory. ``register_tiled_prefill_head_dim`` -flips the prefill-guard estimator to O(L) in lockstep (else it keeps rejecting). - -The route is memory-aware (issue #2204): the unfused fallback is faster -everywhere its score matrix fits (on NAX GPUs its big GEMMs run on the tensor -units; even pre-NAX it is ~2x faster than the tiled pass at long context, issue -#2155), so when the Scheduler has registered a headroom provider the tiled pass -engages only if the unfused transient would NOT fit under the prefill-guard -ceiling. Without a provider (no Scheduler, ceiling not propagated yet) the -route keeps the memory-safe default: always tiled past the kv_len threshold. -``OMLX_SDPA256_TILED=1`` forces the tiled pass whenever the shape gates match -(pre-#2204 behavior); ``OMLX_SDPA256_TILED=0`` never engages it (restores the -O(L^2) memory wall — benchmarking only). +"""Keep head-dim-256 long-context prefill bounded on MLX 0.32.2. + +MLX 0.32.2 ships a fused full-attention kernel for head dimensions 192 and 256, +but deliberately keeps the faster unfused path as the default on pre-NAX GPUs. +That default materializes the full ``[n_q, query_len, kv_len]`` score matrix and +can still exceed oMLX's memory-guard ceiling. + +When the unfused transient fits, this patch preserves MLX's default routing. If +it does not fit (or no guard ceiling is available), it calls MLX 0.32.2 with +``force_fused=True``. This replaces oMLX's old pure-array tiled implementation: +the bounded route is now an upstream native fused kernel instead of the slow +sequential tile loop. On NAX, MLX's default already selects its fast split-D +head-dim-256 kernel for causal prefills with at least 1024 queries. + +``OMLX_SDPA256_TILED=1/0`` remains accepted for compatibility and now forces or +disables the bounded route. Metal uses the native fused kernel; CUDA retains +the prior array-tiled implementation because MLX 0.32.2's CUDA fused kernel +does not support head_dim 256. The default is memory-aware. Install mechanics mirror turboquant_attention.py (patch the module attr + rebind already-imported model modules). The route is strictly gated (see _should_route); @@ -42,38 +36,32 @@ _PATCHED = False HEAD_DIM = 256 -# Engage the tiled kernel only once the context is long enough that the unfused -# fallback's O(L^2) score matrix becomes a memory problem. Below this, the -# fused-GEMM fallback is faster and fits comfortably. Tunable. +# Force the bounded kernel only once the context is long enough that the +# default unfused route's O(L^2) score matrix becomes a memory problem. _SDPA256_MIN_KV_LEN = 8192 # Decode-shaped multi-row calls (MTP verify: q_len = 1 + draft depth <= 9) -# must not take this route: the per-KV-tile eval sync only amortizes over -# prefill-sized q tiles, and at tiny q_len it costs O(kv_len/tile) sequential -# dispatches per call — 8-22x slower than stock SDPA, collapsing long-context -# MTP throughput (issue #2127). Below this floor the stock path's score -# matrix is at most n_q * 15 * kv_len, which is never a memory problem. +# do not need the forced full-attention route. Below this floor the stock path's +# score matrix is at most n_q * 15 * kv_len and is not a memory problem. _SDPA256_MIN_Q_LEN = 16 -# Tile sizes for the online-softmax kernel (tuned on M2 Max). _Q_TILE = 512 +# A deliberately conservative score-tile width used only by the admission +# estimate. MLX's fused kernel keeps a smaller on-chip block, so this does not +# understate the bounded route's score working set. _KV_TILE = 1024 - -_NEG_INF = -1e30 # fp32 sentinel for masked logits (exp -> 0) +_NEG_INF = -1e30 # Live guard-headroom provider for memory-aware routing (issue #2204). # Registered by Scheduler.__init__ as a bound method returning the bytes left # under the adaptive-prefill-throttle target (hard ceiling x headroom safety, # clamped by the abort cap), or a negative value when no ceiling is active. # Held as a WeakMethod so a torn-down Scheduler auto-unregisters and the route -# falls back to the memory-safe always-tiled default. +# falls back to the memory-bounded native fused default. _HEADROOM_PROVIDER: "weakref.WeakMethod | None" = None -# OMLX_SDPA256_TILED override, parsed at apply time: True = always tiled, -# False = never tiled, None = memory-aware auto. +# Backward-compatible override: True = always force fused, False = never force, +# None = memory-aware auto. _FORCE_TILED: bool | None = None -# Tiled-route reasons already logged. The tiled pass trades substantial -# prefill throughput at long kv_len for O(L) memory, and nothing surfaced the -# route decision before (issue #2283 took an A/B repro to diagnose), so the -# first engagement per reason logs at INFO; repeats stay silent to keep the -# hot path quiet. +# Bounded-route reasons already logged. The first engagement per reason logs at +# INFO; repeats stay silent to keep the hot path quiet. _TILED_ROUTE_LOGGED: "set[str]" = set() @@ -82,8 +70,9 @@ def _note_tiled_route(reason: str, detail: str) -> None: return _TILED_ROUTE_LOGGED.add(reason) logger.info( - "sdpa256: head-dim-256 prefill taking the tiled (memory-safe, slower) " - "path: %s. The unfused fast path resumes when guard headroom allows; " + "sdpa256: head-dim-256 prefill forcing the memory-bounded path: %s. " + "The default fast path resumes when guard " + "headroom allows; " "OMLX_SDPA256_TILED=1/0 forces the route.", detail, ) @@ -107,10 +96,10 @@ def _parse_force_tiled_env() -> bool | None: def _tiled_route_required(queries, keys) -> bool: - """Decide tiled vs stock for a shape-matched prefill call (True = tiled). + """Decide forced-fused vs default for a matched call (True = force). The stock unfused fallback is faster wherever its score matrix fits - (issues #2155 / #2204), so take the tiled pass only when the unfused + (issues #2155 / #2204), so force the fused path only when the unfused transient would not fit under the guard ceiling — or when no headroom info is available, keeping the memory-safe #2025 behavior.""" if _FORCE_TILED is not None: @@ -158,54 +147,37 @@ def _tiled_route_required(queries, keys) -> bool: def _broadcast_mask_5d(mask, batch, n_kv, group_size, q_len, k_len): - """Reshape a boolean mask for the tiled GQA attention layout.""" + """Reshape an array mask for the tiled GQA attention layout.""" if mask.ndim == 4: - if mask.shape[1] == 1: - return mask[:, :, None] - return mask.reshape(batch, n_kv, group_size, q_len, k_len) - if mask.ndim == 3: - return mask[:, None, None] - if mask.ndim == 2: - return mask[None, None, None] - raise ValueError(f"unsupported attention mask ndim: {mask.ndim}") - - -def _flash_sdpa256(queries, keys, values, scale, mask): - """Flash-style online-softmax attention for head_dim=256 prefill. - - queries: [batch, n_q, q_len, head_dim] - keys/values: [batch, n_kv, k_len, head_dim] (n_q % n_kv == 0) - mask: "causal", None, or a boolean array. Returns - [batch, n_q, q_len, head_dim] in queries.dtype. - - Tiles over Q and KV, keeping a running (max m, sum denom, accumulator acc) per - query row so the [q x full_kv] score matrix is never materialized. fp32 - accumulators; output cast back to the input dtype. GQA via reshape+broadcast. - - MLX is lazy: without forcing materialization the whole tiled graph would stay - live until eval (peak dominated by graph buildup, not the O(L) working set), - so the running carry is eval'd per KV step / per finished Q tile to bound the - live graph to ~one tile -> true O(L) peak. - """ + pass + elif mask.ndim == 3: + # Preserve mlx-lm's convention: [batch, query, key]. + mask = mask[:, None, :, :] + elif mask.ndim == 2: + mask = mask[None, None, :, :] + elif mask.ndim == 1: + mask = mask[None, None, None, :] + else: + raise ValueError(f"unsupported attention mask ndim: {mask.ndim}") + n_q = n_kv * group_size + mask = mx.broadcast_to(mask, (batch, n_q, q_len, k_len)) + return mask.reshape(batch, n_kv, group_size, q_len, k_len) + + +def _array_tiled_sdpa256(queries, keys, values, scale, mask, sinks=None): + """Portable bounded fallback for shapes without a native fused kernel.""" batch, n_q, q_len, head_dim = queries.shape _, n_kv, k_len, _ = keys.shape + value_dim = values.shape[-1] group_size = n_q // n_kv causal = isinstance(mask, str) and mask == "causal" - bool_mask = None + array_mask = None if isinstance(mask, mx.array): - if mask.dtype != mx.bool_: - raise ValueError("_flash_sdpa256 only supports boolean array masks") - bool_mask = _broadcast_mask_5d( - mask, batch, n_kv, group_size, q_len, k_len - ) + array_mask = _broadcast_mask_5d(mask, batch, n_kv, group_size, q_len, k_len) qr = queries.reshape(batch, n_kv, group_size, q_len, head_dim) kr = keys.reshape(batch, n_kv, 1, k_len, head_dim) - vr = values.reshape(batch, n_kv, 1, k_len, head_dim) - - # MLX 'causal' aligns queries to the END of the key axis: with a cached - # prefix (k_len > q_len, chunked prefill) local query i is global position - # i + offset and attends keys 0..(i + offset). offset == 0 for square. + vr = values.reshape(batch, n_kv, 1, k_len, value_dim) offset = k_len - q_len out_q_tiles = [] @@ -215,9 +187,15 @@ def _flash_sdpa256(queries, keys, values, scale, mask): qt = qi1 - qi0 q_pos = mx.arange(qi0 + offset, qi1 + offset).reshape(1, 1, 1, qt, 1) - m = mx.full((batch, n_kv, group_size, qt, 1), _NEG_INF, dtype=mx.float32) - denom = mx.zeros((batch, n_kv, group_size, qt, 1), dtype=mx.float32) - acc = mx.zeros((batch, n_kv, group_size, qt, head_dim), dtype=mx.float32) + state_shape = (batch, n_kv, group_size, qt, 1) + if sinks is None: + m = mx.full(state_shape, _NEG_INF, dtype=mx.float32) + denom = mx.zeros(state_shape, dtype=mx.float32) + else: + sink_logits = sinks.astype(mx.float32).reshape(1, n_kv, group_size, 1, 1) + m = mx.broadcast_to(sink_logits, state_shape) + denom = mx.ones(state_shape, dtype=mx.float32) + acc = mx.zeros((batch, n_kv, group_size, qt, value_dim), dtype=mx.float32) kv_end = min(qi1 + offset, k_len) if causal else k_len for kj0 in range(0, kv_end, _KV_TILE): @@ -226,29 +204,52 @@ def _flash_sdpa256(queries, keys, values, scale, mask): vb = vr[:, :, :, kj0:kj1, :].astype(mx.float32) kt = kj1 - kj0 - s = (qb @ mx.swapaxes(kb, -1, -2)) * scale + scores = (qb @ mx.swapaxes(kb, -1, -2)) * scale if causal: k_pos = mx.arange(kj0, kj1).reshape(1, 1, 1, 1, kt) - s = mx.where(k_pos > q_pos, _NEG_INF, s) - elif bool_mask is not None: - tile_mask = bool_mask[..., qi0:qi1, kj0:kj1] - s = mx.where(tile_mask, s, _NEG_INF) - - m_tile = mx.max(s, axis=-1, keepdims=True) - m_new = mx.maximum(m, m_tile) - p = mx.exp(s - m_new) - corr = mx.exp(m - m_new) - denom = denom * corr + mx.sum(p, axis=-1, keepdims=True) - acc = acc * corr + (p @ vb) - m = m_new - mx.eval(m, denom, acc) # bound the live graph -> O(L) peak + scores = mx.where(k_pos > q_pos, _NEG_INF, scores) + elif array_mask is not None: + tile_mask = array_mask[..., qi0:qi1, kj0:kj1] + if tile_mask.dtype == mx.bool_: + scores = mx.where(tile_mask, scores, _NEG_INF) + else: + scores = scores + tile_mask.astype(mx.float32) + + tile_max = mx.max(scores, axis=-1, keepdims=True) + new_max = mx.maximum(m, tile_max) + probabilities = mx.exp(scores - new_max) + correction = mx.exp(m - new_max) + denom = denom * correction + mx.sum(probabilities, axis=-1, keepdims=True) + acc = acc * correction + (probabilities @ vb) + m = new_max + mx.eval(m, denom, acc) out_tile = (acc / denom).astype(queries.dtype) mx.eval(out_tile) out_q_tiles.append(out_tile) out = mx.concatenate(out_q_tiles, axis=3) - return out.reshape(batch, n_q, q_len, head_dim) + return out.reshape(batch, n_q, q_len, value_dim) + + +def _flash_sdpa256(queries, keys, values, scale, mask, sinks=None): + """Use MLX 0.32.2 native fused SDPA on Metal, portable tiling elsewhere.""" + native_shape = values.shape[-1] == HEAD_DIM and not ( + isinstance(mask, str) + and mask == "causal" + and queries.shape[-2] > keys.shape[-2] + ) + if mx.metal.is_available() and native_shape: + return mx.fast.scaled_dot_product_attention( + queries, + keys, + values, + scale=scale, + mask=mask, + sinks=sinks, + force_fused=True, + ) + return _array_tiled_sdpa256(queries, keys, values, scale, mask, sinks) def _should_route(queries, keys, cache, mask, sinks) -> bool: @@ -264,18 +265,15 @@ def _should_route(queries, keys, cache, mask, sinks) -> bool: return False if keys.shape[-2] < _SDPA256_MIN_KV_LEN: return False - if sinks is not None: - return False # Quantized KV cache (TurboQuant etc.): keys/values are packed state, # not plain [.., kv, hd] arrays. MLX's own dispatcher detects this via # hasattr(cache, "bits"); let the quant-aware path handle it. if cache is not None and hasattr(cache, "bits"): return False - mask_is_bool = isinstance(mask, mx.array) and mask.dtype == mx.bool_ if not ( mask is None or (isinstance(mask, str) and mask == "causal") - or mask_is_bool + or (isinstance(mask, mx.array) and 1 <= mask.ndim <= 4) ): return False n_q = queries.shape[-3] @@ -287,6 +285,25 @@ def _should_route(queries, keys, cache, mask, sinks) -> bool: return False +def _register_bounded_route(min_kv_len: int) -> bool: + """Publish only a runtime guarantee that is actually enabled.""" + if _FORCE_TILED is False: + return False + try: + from .. import memory_monitor + + memory_monitor.register_tiled_prefill_head_dim( + HEAD_DIM, + min_query_len=_SDPA256_MIN_Q_LEN, + min_kv_len=min_kv_len, + kv_tile=_KV_TILE, + ) + except Exception: + logger.debug("could not register sdpa256 with memory_monitor", exc_info=True) + return False + return True + + def apply_sdpa256_attention_patch(min_kv_len: int = _SDPA256_MIN_KV_LEN) -> bool: """Monkey-patch mlx-lm's scaled_dot_product_attention for head_dim=256 long-context prefill, and register the O(L) cost with the memory monitor.""" @@ -313,13 +330,7 @@ def patched_sdpa( sinks: mx.array | None = None, ) -> mx.array: if _should_route(queries, keys, cache, mask, sinks): - try: - return _flash_sdpa256(queries, keys, values, scale, mask) - except Exception: - logger.warning( - "sdpa256 prefill kernel failed; falling back to MLX SDPA", - exc_info=True, - ) + return _flash_sdpa256(queries, keys, values, scale, mask, sinks) return original_sdpa(queries, keys, values, cache, scale, mask, sinks) mlx_base.scaled_dot_product_attention = patched_sdpa @@ -364,14 +375,7 @@ def patched_vlm_sdpa( sinks=None, ) -> mx.array: if _should_route(queries, keys, cache, mask, sinks): - try: - return _flash_sdpa256(queries, keys, values, scale, mask) - except Exception: - logger.warning( - "sdpa256 prefill kernel failed; falling back to " - "MLX SDPA", - exc_info=True, - ) + return _flash_sdpa256(queries, keys, values, scale, mask, sinks) return original_vlm_sdpa( queries, keys, values, cache, scale, mask, sinks ) @@ -387,23 +391,18 @@ def patched_vlm_sdpa( mod.scaled_dot_product_attention = patched_vlm_sdpa # Keep the prefill memory guard in lockstep: tell the monitor head_dim 256 - # prefill is now O(L), so it stops charging the O(L^2) score matrix. - try: - from .. import memory_monitor - - memory_monitor.register_tiled_prefill_head_dim( - HEAD_DIM, min_kv_len=min_kv_len, kv_tile=_KV_TILE - ) - except Exception: - logger.debug("could not register sdpa256 with memory_monitor", exc_info=True) + # prefill is now O(L), so it stops charging the O(L^2) score matrix. The + # explicit benchmark override disables this guarantee, so registering it + # in that mode would under-estimate the same unfused path the user forced. + _register_bounded_route(min_kv_len) _PATCHED = True if _FORCE_TILED is None: - routing = "tiled only when unfused exceeds guard headroom" + routing = "force bounded when unfused exceeds guard headroom" elif _FORCE_TILED: - routing = "always tiled (OMLX_SDPA256_TILED=1)" + routing = "always force bounded (OMLX_SDPA256_TILED=1)" else: - routing = "never tiled (OMLX_SDPA256_TILED=0)" + routing = "never force bounded (OMLX_SDPA256_TILED=0)" logger.info( "sdpa256 attention patch applied (head_dim=256 prefill, kv_len>=%d, %s)", min_kv_len, diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 9cdd9f1f6a..be51b0748a 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -77,6 +77,7 @@ _default_generation_stream, _mx_buffer_access_lock, _sync_and_clear_cache, + clear_thread_streams, ) from .utils.proc_memory import get_phys_footprint from .utils.sampling import make_sampler as omlx_make_sampler @@ -1984,8 +1985,8 @@ def __init__( self._fixed_state_measure_armed: bool = False self._fixed_state_recorded: bool = False # Let the sdpa256 head_dim-256 prefill route ask for live guard - # headroom so it only takes the slow O(L) tiled pass when the faster - # unfused fallback would not fit (issue #2204). Weakly held; harmless + # headroom so it only forces bounded native SDPA when the faster + # unfused default would not fit (issue #2204). Weakly held; harmless # when the patch is never applied. set_unfused_headroom_provider(self._sdpa256_unfused_headroom) @@ -3959,11 +3960,10 @@ def _sdpa256_unfused_headroom(self) -> int: same target the adaptive prefill throttle enforces (hard ceiling x headroom safety, clamped by the abort cap). Negative when the ceiling is unknown (enforcer not propagated yet), which tells the - sdpa256 route to keep its memory-safe tiled default. When the guard + sdpa256 route to keep its memory-bounded default. When the guard is explicitly disabled there is no ceiling to respect: the user opted out of memory management, so the route gets unbounded - headroom and keeps the unfused fast path instead of pinning - guard-off servers to the ~2x-slower tiled pass (#2283). Called from + headroom and keeps the unfused fast path (#2283). Called from the route gate on the MLX step thread mid-prefill, where refreshing the active-memory sample is safe (issue #2204).""" hard_cap = self._memory_hard_limit_bytes @@ -3976,7 +3976,7 @@ def _sdpa256_unfused_headroom(self) -> int: "prefill keeps the unfused fast path with no memory " "ceiling (long-context OOM protection off). Enable " "the memory guard or set OMLX_SDPA256_TILED=1 for " - "the memory-safe tiled path." + "the memory-bounded path." ) return _SDPA256_UNBOUNDED_HEADROOM return -1 @@ -12373,6 +12373,22 @@ def shutdown(self) -> None: f"{len(not_done)} async store_cache future(s)" ) self._drain_pending_async_removes() + try: + clear_future = self._store_cache_executor.submit( + clear_thread_streams + ) + clear_future.result(timeout=FATAL_TEARDOWN_TIMEOUT_S) + except concurrent.futures.TimeoutError: + fatal_exit( + "Scheduler shutdown timed out after " + f"{FATAL_TEARDOWN_TIMEOUT_S:.0f}s while clearing " + "the store-cache worker's MLX streams" + ) + except Exception as exc: + fatal_exit( + "Scheduler store-cache worker stream cleanup failed: " + f"{exc!r}" + ) self._store_cache_executor.shutdown(wait=False) # Final drain after the bounded wait. If all workers finished # before the timeout, skipped entries are now drainable. If not, diff --git a/omlx/speculative/vlm_mtp.py b/omlx/speculative/vlm_mtp.py index 7637d0ac7e..e3a8082010 100644 --- a/omlx/speculative/vlm_mtp.py +++ b/omlx/speculative/vlm_mtp.py @@ -42,28 +42,47 @@ import mlx.core as mx import mlx.nn as nn -from mlx_vlm.speculative import load_drafter as _vlm_load_drafter +from ..patches.mlx_vlm_mlx0322_compat import ( + apply_mlx_vlm_mlx0322_compat_patch, +) + +# Install the MLX 0.32.2 source hook before importing mlx-vlm.speculative. +# Importing that package eagerly loads common, mtp, and utils; applying the +# hook afterwards can leave their copied generation_stream globals pointing +# at the stream from the pre-reload common module. +apply_mlx_vlm_mlx0322_compat_patch() + +from mlx_vlm.speculative import common as _vlm_common # noqa: E402, I001 +from mlx_vlm.speculative import load_drafter as _vlm_load_drafter # noqa: E402 # The round loops dispatch their target-verify and cache-rollback forwards # inside ``with mx.stream(generation_stream)``, using mlx-vlm's own # thread-local stream — a different object from mlx-lm's generation_stream # and from the per-engine stream. Draining the MTP work means draining this # one, resolved on the thread that advances the round loop. -from mlx_vlm.speculative.common import generation_stream as _vlm_generation_stream # PR #1169 (f96138e) moved the MTP round loop helpers from ``mlx_vlm.generate`` # into ``mlx_vlm.speculative.utils``. Import directly from the new location — # the symbols are still ``_``-prefixed but this is now their canonical home. -from mlx_vlm.speculative.utils import _mtp_rounds, _mtp_rounds_batch # noqa: SLF001 +from mlx_vlm.speculative.utils import ( # noqa: E402, SLF001 + _mtp_rounds, + _mtp_rounds_batch, +) try: - from mlx_vlm.speculative.mtp import _buffer_mtp_target_cache # noqa: SLF001 + from mlx_vlm.speculative.mtp import ( # noqa: E402, SLF001 + _buffer_mtp_target_cache, + ) except Exception: # pragma: no cover - compatibility with older mlx-vlm + def _buffer_mtp_target_cache(*_args: Any, **_kwargs: Any) -> None: return None -from ..utils.metal_sync import _sync_and_clear_cache -from ..utils.model_loading import materialize_lazy_state + +from ..utils.metal_sync import _sync_and_clear_cache # noqa: E402 +from ..utils.model_loading import materialize_lazy_state # noqa: E402 + +_vlm_generation_stream = _vlm_common.generation_stream logger = logging.getLogger(__name__) diff --git a/omlx/utils/compile_cache.py b/omlx/utils/compile_cache.py deleted file mode 100644 index ba9f5efad4..0000000000 --- a/omlx/utils/compile_cache.py +++ /dev/null @@ -1,108 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Thread-local MLX compile-cache clearing. - -MLX moved its ``mx.compile`` graph cache to a C++ ``thread_local`` -``CompilerCache`` (ml-explore/mlx #3280). When a thread that ran -``@mx.compile`` functions is destroyed, ``~CompilerCache`` frees the cached -graphs' Python objects from a thread-exit handler WITHOUT holding the GIL, -which aborts the process with ``Fatal Python error: PyThreadState_Get: ... -GIL is released`` (the underlying frame is ``_pthread_exit -> -ThreadLocalVariables::finalizeList -> CompilerCache::~CompilerCache -> -tupledealloc``). Any model with module-scope ``@mx.compile`` graphs hits this: -DeepSeek V4 on unload (the per-engine worker thread exits at close), Step 3.x -on process exit. - -MLX exposes no Python API to clear the compile cache. Its own atexit-based -clear at ``transforms.cpp`` is dead code (the registration lambda is never -invoked) and would run on the main thread anyway, so it cannot clear a worker -thread's thread_local cache. But the C++ symbol -``mlx::core::detail::compile_clear_cache()`` is exported from ``libmlx.dylib``, -so we resolve it via ctypes and call it ON the worker thread (with the GIL -held, via ``ctypes.PyDLL``) right before that thread is torn down. The cache -ends up empty, so ``~CompilerCache`` becomes a no-op and the thread can exit -normally. - -If the symbol cannot be resolved (e.g. a future MLX rename or a non-macOS -build), the helper is a no-op and callers fall back to keeping the worker -thread alive for the process lifetime instead of exiting it. -""" - -import ctypes -import logging -import os -import threading - -import mlx.core as mx - -logger = logging.getLogger(__name__) - -# Itanium-mangled ``mlx::core::detail::compile_clear_cache()`` (no args, void). -# "19" is the length of "compile_clear_cache". -_CLEAR_SYMBOL = "_ZN3mlx4core6detail19compile_clear_cacheEv" - -_resolve_lock = threading.Lock() -_resolved = False -_clear_fn = None # ctypes callable, or None if unresolvable - - -def _resolve_clear_fn(): - """Resolve compile_clear_cache from libmlx.dylib once (thread-safe).""" - global _resolved, _clear_fn - if _resolved: - return _clear_fn - with _resolve_lock: - if _resolved: - return _clear_fn - _resolved = True - try: - lib_dir = os.path.join(os.path.dirname(mx.__file__), "lib") - libmlx = os.path.join(lib_dir, "libmlx.dylib") - if not os.path.exists(libmlx): - logger.warning( - "MLX compile-cache clear unavailable: %s not found", libmlx - ) - return None - # PyDLL keeps the GIL held during the call (CDLL would release it). - # The cache clear decrefs Python objects, so the GIL MUST be held. - lib = ctypes.PyDLL(libmlx) - fn = None - for name in (_CLEAR_SYMBOL, "_" + _CLEAR_SYMBOL): - try: - fn = getattr(lib, name) - break - except AttributeError: - continue - if fn is None: - raise AttributeError(_CLEAR_SYMBOL) - fn.restype = None - fn.argtypes = [] - _clear_fn = fn - logger.info("MLX compile-cache clear resolved (%s)", _CLEAR_SYMBOL) - except (OSError, AttributeError) as e: - logger.warning( - "MLX compile-cache clear unavailable (%s); MLX worker threads " - "will be kept alive as a fallback to avoid the thread-exit " - "~CompilerCache crash", - e, - ) - _clear_fn = None - return _clear_fn - - -def compile_cache_clear_available() -> bool: - """True if the thread-local compile-cache clear symbol is resolvable.""" - return _resolve_clear_fn() is not None - - -def clear_thread_compile_cache() -> None: - """Clear the CALLING thread's MLX thread-local compile cache. - - MUST run ON the thread whose cache should be cleared (the cache is C++ - ``thread_local``). Call it on an MLX worker thread right before that thread - is destroyed so ``~CompilerCache`` runs on an empty cache and never frees - Python objects from a GIL-less thread-exit handler. No-op if the symbol - could not be resolved. - """ - fn = _resolve_clear_fn() - if fn is not None: - fn() diff --git a/omlx/utils/metal_sync.py b/omlx/utils/metal_sync.py index 1c129b764d..3b4edbe5f1 100644 --- a/omlx/utils/metal_sync.py +++ b/omlx/utils/metal_sync.py @@ -16,6 +16,7 @@ """ import threading +from contextlib import suppress import mlx.core as mx from mlx_lm.generate import generation_stream @@ -33,6 +34,20 @@ _mx_buffer_access_lock = threading.RLock() +def clear_thread_streams() -> None: + """Release every MLX stream owned by the current worker thread. + + MLX keeps a per-thread stream registry. Synchronizing and clearing the + buffer cache does not remove those entries, so a worker that touched MLX + must call ``mx.clear_streams()`` immediately before it exits. + """ + # A ThreadPoolExecutor starts lazily. If this is the worker's first task, + # no default stream exists yet and there is nothing to synchronize. + with suppress(RuntimeError): + mx.synchronize() + mx.clear_streams() + + def _sync_and_clear_cache(stream=None): """Synchronize in-flight GPU work before clearing the Metal buffer cache. diff --git a/omlx/utils/model_loading.py b/omlx/utils/model_loading.py index 49b1da3148..2acfd9f522 100644 --- a/omlx/utils/model_loading.py +++ b/omlx/utils/model_loading.py @@ -400,7 +400,7 @@ def maybe_apply_pre_load_patches( declares ``model_type == "glm_moe_dsa"``. Required because pinned mlx-lm exposes it as a bare DeepSeek-V3.2 subclass and cannot load checkpoints whose shared DSA layers carry no indexer weights. - - Native MTP patch (PR 990 + PR 15) when the config declares MTP heads + - Lightning MTP patch (PR 990 + PR 15) when the config declares MTP heads on a supported model_type. Always applied for sanitize correctness; head attachment is gated by ``model_settings.mtp_enabled``. - mlx-vlm side MTP runtime + nested-visual patches when ``for_vlm`` is @@ -416,8 +416,14 @@ def maybe_apply_pre_load_patches( and crashes with KeyError unless the mlx_vlm_mtp sanitize replacement is installed first. ``for_vlm=True`` is only passed by ``VLMBatchedEngine``, so no separate ``vision_config`` gate is needed. - Both patches inject modules into ``sys.modules`` and replace mlx-lm - internals; gating keeps non-affected models at zero cost. + - mlx-vlm MLX 0.32.2 compatibility backport when ``for_vlm`` is True. + This installs before model-module imports and carries only upstream PRs + #1949, #1982, and #2006, without moving the deliberately stable mlx-vlm + pin. + Some model patches inject modules into ``sys.modules`` or replace mlx-lm + internals; the mlx-vlm compatibility hook instead transforms only the + affected pinned sources as they load. Gating keeps non-affected models at + zero cost. Safe to call repeatedly; the patches are idempotent. """ @@ -430,6 +436,13 @@ def maybe_apply_pre_load_patches( _patch_mlx_lm_load_config() + if for_vlm: + from ..patches.mlx_vlm_mlx0322_compat import ( + apply_mlx_vlm_mlx0322_compat_patch, + ) + + apply_mlx_vlm_mlx0322_compat_patch() + # Machine-conditioned, model-independent: reroute sorted gather_qmm # around the defective M5 NAX kernels (issue #2267). Install is cheap # and self-gating — a canary at the first matching call decides diff --git a/pyproject.toml b/pyproject.toml index a9f98f143a..12d8fdd797 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -3,13 +3,13 @@ requires = [ "setuptools>=61.0", "wheel", "cmake>=3.27", - # Pin nanobind to match the ABI version MLX 0.32.0 was built with - # (MLX pins nanobind v2.13.0 via FetchContent in its CMakeLists.txt). + # Pin nanobind to match the ABI version MLX 0.32.2 was built with + # (MLX pins nanobind v2.15.0 via FetchContent in its CMakeLists.txt). # A mismatched nanobind isolates the `mlx` NB_DOMAIN, so custom kernel # extensions (omlx.custom_kernels.*) reject every mlx.core.array at the # type caster with `incompatible function arguments`. - "nanobind==2.13.0", - "mlx==0.32.0", + "nanobind==2.15.0", + "mlx==0.32.2", ] build-backend = "setuptools.build_meta" @@ -39,11 +39,11 @@ classifiers = [ ] dependencies = [ - # Vanilla MLX v0.32.0; optional custom kernels live under + # Vanilla MLX v0.32.2; optional custom kernels live under # omlx.custom_kernels.* when built for release. The bundled kernel # binaries are ABI-coupled to this exact mlx version — bumping the pin # requires rebuilding them (OMLX_WITH_CUSTOM_KERNEL=1 setup.py build_ext). - "mlx==0.32.0", + "mlx==0.32.2", # mlx-lm from commit (ab1806e, v0.31.3) - transformers 5.13+ # NewlineTokenizer registration compatibility, DeepSeek/GLM DSA indexer # RoPE fix, trust_remote_code load gate, transformers 5.7.0 @@ -270,7 +270,7 @@ include = ["omlx*"] # mlx and mlx-lm are git-pinned; override transitive pins # (e.g. mlx-audio -> mlx-lm==0.31.1) so the resolver accepts them. override-dependencies = [ - "mlx==0.32.0", + "mlx==0.32.2", "mlx-lm @ git+https://github.com/ml-explore/mlx-lm@ab1806e8f5d6aa035973af194a1b9198ab4754dc", ] diff --git a/tests/test_cluster_worker_bundle.py b/tests/test_cluster_worker_bundle.py index d4d332226c..0d47d9e12a 100644 --- a/tests/test_cluster_worker_bundle.py +++ b/tests/test_cluster_worker_bundle.py @@ -82,8 +82,8 @@ def test_worker_requirements_pin_numpy_and_the_cuda_backend(): requirements = cuda_worker_bootstrap.WORKER_REQUIREMENTS assert "numpy>=1.24.0,<2.4" in requirements - assert "mlx==0.32.0" in requirements - assert "mlx-cuda-13==0.32.0" in requirements + assert "mlx==0.32.2" in requirements + assert "mlx-cuda-13==0.32.2" in requirements assert "openai-harmony" in requirements assert "psutil>=5.9.0" in requirements diff --git a/tests/test_compile_cache.py b/tests/test_compile_cache.py deleted file mode 100644 index bac10d3cbd..0000000000 --- a/tests/test_compile_cache.py +++ /dev/null @@ -1,45 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Tests for omlx.utils.compile_cache (thread-local MLX compile-cache clear).""" - -import concurrent.futures as cf - -import mlx.core as mx - -import omlx.utils.compile_cache as cc - - -def test_clear_available_returns_bool(): - # Contract: never raises, always returns a bool. On a real Apple-Silicon - # MLX install the symbol resolves, but the helper must degrade gracefully. - assert isinstance(cc.compile_cache_clear_available(), bool) - - -def test_clear_thread_compile_cache_does_not_raise(): - # Safe to call on any thread, even with an empty cache. - cc.clear_thread_compile_cache() - - -def test_clear_after_compile_on_worker_then_shutdown(): - """Core scenario behind the fix: run an @mx.compile fn on a worker thread, - clear that thread's cache on the same thread, then shut the worker down. - Must not crash (~CompilerCache runs on an empty cache).""" - - @mx.compile - def f(x): - return x * 2 + 1 - - ex = cf.ThreadPoolExecutor(max_workers=1) - try: - ex.submit(lambda: mx.eval(f(mx.arange(8)))).result() - ex.submit(cc.clear_thread_compile_cache).result() - finally: - ex.shutdown(wait=True) - - -def test_noop_when_symbol_unavailable(monkeypatch): - """When the symbol cannot be resolved, available() is False and clear() is - a no-op (callers then fall back to keeping the worker thread alive).""" - monkeypatch.setattr(cc, "_resolved", True) - monkeypatch.setattr(cc, "_clear_fn", None) - assert cc.compile_cache_clear_available() is False - cc.clear_thread_compile_cache() # must not raise diff --git a/tests/test_embedding.py b/tests/test_embedding.py index f2bab05372..ce19b3aa03 100644 --- a/tests/test_embedding.py +++ b/tests/test_embedding.py @@ -849,11 +849,9 @@ def test_close_releases_compiled_model_and_processor_resources(self): model._compiled_embed = MagicMock() model._remap_input_ids_to_inputs = True - with patch("omlx.models.embedding.gc.collect") as collect, \ - patch("omlx.models.embedding.mx") as mock_mx, \ - patch( - "omlx.models.embedding.clear_thread_compile_cache" - ) as clear_compile_cache: + with patch("omlx.models.embedding.gc.collect") as collect, patch( + "omlx.models.embedding.mx" + ) as mock_mx: model.close() assert model.model is None @@ -866,7 +864,6 @@ def test_close_releases_compiled_model_and_processor_resources(self): assert model._remap_input_ids_to_inputs is False mock_mx.synchronize.assert_called_once() mock_mx.clear_cache.assert_called_once() - clear_compile_cache.assert_called_once() assert collect.call_count == 2 diff --git a/tests/test_engine_core.py b/tests/test_engine_core.py index 58d14ea7c0..57acc90cf9 100644 --- a/tests/test_engine_core.py +++ b/tests/test_engine_core.py @@ -674,41 +674,6 @@ def test_close_fatal_exits_when_teardown_future_times_out( future.result.assert_called_once_with(timeout=60.0) assert "Engine teardown timed out after 60s" in fatal.call_args.args[0] - def test_close_fatal_exits_when_compile_cache_clear_times_out( - self, mock_model, mock_tokenizer - ): - """A stuck MLX compile-cache clear is also fatal.""" - 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) - engine._mlx_executor.shutdown(wait=False) - - ok_future = MagicMock() - ok_future.result.return_value = None - timeout_future = MagicMock() - timeout_future.result.side_effect = concurrent.futures.TimeoutError - executor = MagicMock() - executor.submit.side_effect = [ - ok_future, - ok_future, - ok_future, - timeout_future, - ] - engine._mlx_executor = executor - - with ( - patch( - "omlx.engine_core.compile_cache_clear_available", return_value=True - ), - patch("omlx.engine_core.fatal_exit", side_effect=SystemExit) as fatal, - pytest.raises(SystemExit), - ): - engine.close() - - timeout_future.result.assert_called_once_with(timeout=60.0) - assert "MLX compile cache" in fatal.call_args.args[0] - class TestEngineCoreGetCacheStats: """Tests for EngineCore.get_cache_stats().""" @@ -1383,6 +1348,23 @@ async def test_abort_all_requests_engine_keeps_running( class TestGlobalMLXExecutor: """Tests for the global MLX executor singleton (issue #85).""" + def test_shutdown_reclaims_on_worker_before_executor_exit(self): + import omlx.engine_core as engine_core + + executor = MagicMock() + future = MagicMock() + executor.submit.return_value = future + + with patch.object(engine_core, "_global_mlx_executor", executor): + engine_core.shutdown_mlx_executor() + assert engine_core._global_mlx_executor is None + + executor.submit.assert_called_once_with( + engine_core._final_global_mlx_thread_reclaim + ) + future.result.assert_called_once_with(timeout=60.0) + executor.shutdown.assert_called_once_with(wait=False) + def test_get_mlx_executor_returns_singleton(self): """get_mlx_executor() must always return the same executor instance.""" from omlx.engine_core import get_mlx_executor diff --git a/tests/test_engine_pool.py b/tests/test_engine_pool.py index 1cd94ad8ef..77fc72977e 100644 --- a/tests/test_engine_pool.py +++ b/tests/test_engine_pool.py @@ -1563,7 +1563,10 @@ def create_engine(*args, **kwargs): engine_idx[0] += 1 return engine - with patch("omlx.engine_pool.BatchedEngine", side_effect=create_engine): + with ( + patch("omlx.engine_pool.BatchedEngine", side_effect=create_engine), + patch("omlx.engine_pool.shutdown_mlx_executor") as shutdown_executor, + ): await pool.get_engine("model-a") await pool.get_engine("model-b") @@ -1571,8 +1574,23 @@ def create_engine(*args, **kwargs): mock_engine_a.stop.assert_called_once() mock_engine_b.stop.assert_called_once() + shutdown_executor.assert_called_once_with() assert pool.loaded_model_count == 0 + @pytest.mark.asyncio + async def test_shutdown_cancels_failed_load_reclaim_before_global_worker(self): + pool = _make_pool(ceiling=10 * 1024**3) + pool._schedule_failed_load_reclaim("failed-model", pre_load_memory=0) + reclaim_task = pool._failed_load_reclaim_task + assert reclaim_task is not None + + with patch("omlx.engine_pool.shutdown_mlx_executor") as shutdown_executor: + await pool.shutdown() + + assert reclaim_task.cancelled() + assert not pool._failed_load_reclaim_tasks + shutdown_executor.assert_called_once_with() + class TestEnginePoolEviction: """Tests for memory-based eviction.""" diff --git a/tests/test_gdn_sidecar_quantization.py b/tests/test_gdn_sidecar_quantization.py index 213f079cb1..4f37ca82b7 100644 --- a/tests/test_gdn_sidecar_quantization.py +++ b/tests/test_gdn_sidecar_quantization.py @@ -149,6 +149,7 @@ def extract(_snapshot): staged = store.take_staged_file("durable", 2048, timeout_s=5.0) assert staged is not None arrays, metadata = mx.load(str(staged), return_metadata=True) + mx.eval(*arrays.values()) assert arrays["layer_0_state_1"].dtype == mx.int8 assert arrays["layer_0_state_1__scale"].dtype == mx.float32 assert metadata["gdn_sidecar_format_version"] == "2" @@ -287,6 +288,7 @@ def extract(_snapshot): staged = store.take_staged_file("rht-durable", 2048, timeout_s=5.0) assert staged is not None arrays, metadata = mx.load(str(staged), return_metadata=True) + mx.eval(*arrays.values()) assert arrays["layer_0_state_1"].dtype == mx.int8 assert arrays["layer_0_state_1__scale"].dtype == mx.float32 info = json.loads(metadata["layer_info"]) @@ -846,6 +848,9 @@ def extract(_snapshot): assert store.gdn_decode_failures == 0 arrays, metadata = mx.load(str(staged), return_metadata=True) + # Materialize before overwriting the same backing file. MLX 0.32.2 + # otherwise retains read primitives that fail after the truncate. + mx.eval(*arrays.values()) info = json.loads(metadata["layer_info"]) info[0]["state_1_original_dtype"] = "bfloat16" metadata["layer_info"] = json.dumps(info) @@ -1016,6 +1021,9 @@ def test_pending_raw_and_durable_file_restore_identically(tmp_path, mode): assert staged is not None durable = store.load_file(staged) assert durable is not None + # load_file must detach mx.load's lazy arrays from the ephemeral + # promotion file before ownership returns to the caller. + staged.unlink() pending_state = pending[0]["state"][1] durable_state = durable[0]["state"][1] diff --git a/tests/test_gemma4_verify_attention.py b/tests/test_gemma4_verify_attention.py index a959b0c444..dae707b061 100644 --- a/tests/test_gemma4_verify_attention.py +++ b/tests/test_gemma4_verify_attention.py @@ -46,6 +46,28 @@ def _language_model(extra: dict | None = None): return LanguageModel(TextConfig.from_dict(params)) +@pytest.mark.parametrize( + "head_dim,query_len,gqa_factor,expected", + [ + (256, 2, 8, True), + (256, 4, 8, True), + (256, 5, 8, False), + (192, 2, 8, False), + (96, 12, 8, True), + (512, 2, 8, False), + ], +) +def test_mlx0322_native_fused_shapes_are_not_intercepted( + head_dim, query_len, gqa_factor, expected +): + assert ( + gemma4_verify_attention._mlx0322_default_fused( + head_dim, query_len, gqa_factor + ) + is expected + ) + + def _run(lm, prompt_len: int, step_len: int, patched: bool): """Prefill ``prompt_len`` tokens then run one ``step_len`` forward.""" mx.random.seed(7) diff --git a/tests/test_memory_monitor.py b/tests/test_memory_monitor.py index 677174b2b2..12ed1acd79 100644 --- a/tests/test_memory_monitor.py +++ b/tests/test_memory_monitor.py @@ -505,7 +505,7 @@ def test_query_len_capped_at_new_tokens(self): def test_sdpa_dispatch_constants_match_mlx_use_fallback(self): assert _SDPA_VECTOR_QUERY_TOKEN_THRESHOLD == 8 - assert frozenset({64, 80, 128}) == _SDPA_FULL_SUPPORTED_HEAD_DIMS + assert frozenset({64, 72, 80, 96, 128}) == _SDPA_FULL_SUPPORTED_HEAD_DIMS assert frozenset({64, 96, 128, 256}) == _SDPA_VECTOR_SUPPORTED_HEAD_DIMS def test_vector_path_head_dim_256_is_output_only_for_short_query(self): @@ -520,16 +520,24 @@ def test_vector_path_head_dim_80_falls_back(self): self._expected_fallback_sdpa(8, 4, 10_000, 80) ) + def test_vector_path_head_dim_192_stays_conservative_without_force(self): + # MLX 0.32.2 instantiates this kernel, but its default dispatcher does + # not select it; only force_fused=True can make it memory-bounded. + m = self._make_monitor(head_dim=192, n_attn=8, n_kv=4, n_layers=48) + assert m.estimate_chunk_transient_bytes(4, 10_000) == ( + self._expected_fallback_sdpa(8, 4, 10_000, 192) + ) + def test_full_prefill_head_dim_80_is_output_only(self): m = self._make_monitor(head_dim=80, n_attn=8, n_kv=4, n_layers=48) assert m.estimate_chunk_transient_bytes(512, 10_000) == ( self._expected_output_sdpa(8, 512, 80) ) - def test_full_prefill_head_dim_96_falls_back(self): + def test_full_prefill_head_dim_96_is_output_only(self): m = self._make_monitor(head_dim=96, n_attn=8, n_kv=4, n_layers=48) assert m.estimate_chunk_transient_bytes(512, 10_000) == ( - self._expected_fallback_sdpa(8, 512, 10_000, 96) + self._expected_output_sdpa(8, 512, 96) ) def test_vector_path_gqa_limit_falls_back(self): diff --git a/tests/test_memory_monitor_vlm_config.py b/tests/test_memory_monitor_vlm_config.py index 3ab6277331..10c61aba7e 100644 --- a/tests/test_memory_monitor_vlm_config.py +++ b/tests/test_memory_monitor_vlm_config.py @@ -487,10 +487,12 @@ def test_reported_scale_fits_after_turboquant_skip_last_accounting(self): class TestSdpaDispatchEstimate: """MemoryMonitor mirrors MLX SDPA full/vector dispatch support.""" - def test_sdpa_dispatch_constants_match_mlx_031(self): + def test_sdpa_dispatch_constants_match_mlx_0322(self): assert _SDPA_VECTOR_QUERY_TOKEN_THRESHOLD == 8 - assert frozenset({64, 80, 128}) == _SDPA_FULL_SUPPORTED_HEAD_DIMS - assert frozenset({64, 96, 128, 256}) == _SDPA_VECTOR_SUPPORTED_HEAD_DIMS + assert frozenset({64, 72, 80, 96, 128}) == _SDPA_FULL_SUPPORTED_HEAD_DIMS + assert frozenset({64, 96, 128, 256}) == ( + _SDPA_VECTOR_SUPPORTED_HEAD_DIMS + ) def test_estimate_prefill_uses_full_fallback_for_head_dim_256(self): """head_dim=256 is not supported by MLX fused full prefill.""" diff --git a/tests/test_mlx0322_compat.py b/tests/test_mlx0322_compat.py new file mode 100644 index 0000000000..05e3f1636a --- /dev/null +++ b/tests/test_mlx0322_compat.py @@ -0,0 +1,122 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Regression coverage for the atomic MLX 0.32.2 upgrade.""" + +from __future__ import annotations + +import concurrent.futures +import importlib +import subprocess +import sys +from importlib.metadata import distribution +from pathlib import Path + +import mlx.core as mx + + +def test_runtime_uses_exact_mlx_0322(): + assert mx.__version__ == "0.32.2" + + +def test_mlx_vlm_backport_matches_every_pinned_source(): + from omlx.patches.mlx_vlm_mlx0322_compat import ( + _MODULE_REPLACEMENTS, + _patch_source, + ) + + package_root = Path(distribution("mlx-vlm").locate_file("")) + for fullname, replacements in _MODULE_REPLACEMENTS.items(): + source_path = package_root / f"{fullname.replace('.', '/')}.py" + source = source_path.read_text() + patched = _patch_source(fullname, source) + for replacement in replacements: + assert patched.count(replacement.new) == replacement.count + compile(patched, str(source_path), "exec") + + +def test_mlx_vlm_qwen2_array_grid_runs_after_backport(): + from omlx.patches.mlx_vlm_mlx0322_compat import ( + apply_mlx_vlm_mlx0322_compat_patch, + ) + + # Exercise the defensive early-import path as well as first-time imports. + vision = importlib.import_module("mlx_vlm.models.qwen2_vl.vision") + apply_mlx_vlm_mlx0322_compat_patch() + vision_model_cls = vision.VisionModel + + model = vision_model_cls.__new__(vision_model_cls) + model.spatial_merge_size = 1 + model.rotary_pos_emb = lambda _size: mx.zeros((1, 2)) + result = model.rot_pos_emb(mx.array([[2, 1, 1]], dtype=mx.int32)) + mx.eval(result) + assert result.shape[0] == 2 + + +def test_mlx_vlm_grid_sample_uses_python_integer_metal_grid(): + from omlx.patches.mlx_vlm_mlx0322_compat import ( + apply_mlx_vlm_mlx0322_compat_patch, + ) + + apply_mlx_vlm_mlx0322_compat_patch() + + from mlx_vlm.models.kernels import grid_sample + + values = mx.arange(4, dtype=mx.float32).reshape(1, 2, 2, 1) + grid = mx.zeros((1, 1, 1, 2), dtype=mx.float32) + result = grid_sample(values, grid) + mx.eval(result) + assert result.shape == (1, 1, 1, 1) + + +def test_mlx_vlm_speculative_rng_restores_random_state_in_place(): + from omlx.patches.mlx_vlm_mlx0322_compat import ( + apply_mlx_vlm_mlx0322_compat_patch, + ) + + apply_mlx_vlm_mlx0322_compat_patch() + + from mlx_vlm.speculative.common import _restore_rng_state + + original = [mx.array(value) for value in mx.random.state] + replacement = [value + 1 for value in original] + try: + _restore_rng_state(replacement) + mx.eval(*mx.random.state) + assert all( + bool(mx.all(actual == expected)) + for actual, expected in zip(mx.random.state, replacement) + ) + finally: + _restore_rng_state(original) + + +def test_early_mlx_vlm_import_rebinds_mtp_generation_stream(): + """The defensive reload path must not split common and MTP streams.""" + code = """ +from mlx_vlm.speculative import common, mtp +old_stream = common.generation_stream +assert mtp.generation_stream is old_stream + +from omlx.patches.mlx_vlm_mlx0322_compat import apply_mlx_vlm_mlx0322_compat_patch +apply_mlx_vlm_mlx0322_compat_patch() + +assert common.generation_stream is not old_stream +assert mtp.generation_stream is common.generation_stream +assert mtp._mtp_rounds.__globals__[\"generation_stream\"] is common.generation_stream +assert mtp._mtp_rounds_batch.__globals__[\"generation_stream\"] is common.generation_stream +""" + subprocess.run([sys.executable, "-c", code], check=True) + + +def _compiled_thread_call(value: int) -> int: + @mx.compile + def add_one(x): + return x + 1 + + return int(add_one(mx.array(value)).item()) + + +def test_compiled_worker_cache_can_be_destroyed_repeatedly(): + """MLX #4391 must make thread-local compiled-data teardown GIL-safe.""" + for value in range(20): + with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor: + assert executor.submit(_compiled_thread_call, value).result() == value + 1 diff --git a/tests/test_per_engine_threads.py b/tests/test_per_engine_threads.py index 1e8ef939ec..be5db9850c 100644 --- a/tests/test_per_engine_threads.py +++ b/tests/test_per_engine_threads.py @@ -2,7 +2,7 @@ import concurrent.futures from types import SimpleNamespace -from unittest.mock import MagicMock, patch +from unittest.mock import MagicMock, call, patch import mlx.core as mx import pytest @@ -250,22 +250,17 @@ def test_engine_passes_stream_to_scheduler(self): engine.close() - def test_close_clears_compile_cache_then_shuts_down(self): - """Normal path (compile-cache clear available): close() clears the - worker thread's MLX thread_local compile cache (so ~CompilerCache is a - no-op at thread exit) and then shuts the executor down normally.""" - import omlx.engine_core as ec - + def test_close_reclaims_then_shuts_down_worker(self): + """MLX 0.32.2 workers shut down normally after final reclaim.""" mock_model = MagicMock() mock_model.model_type = "test" mock_tokenizer = MagicMock() mock_tokenizer.eos_token_id = 0 - with patch("omlx.engine_core.get_registry") as mock_registry, patch( - "omlx.engine_core.compile_cache_clear_available", return_value=True - ), patch("omlx.engine_core.clear_thread_compile_cache") as mock_clear, patch( - "omlx.engine_core._final_engine_thread_reclaim" - ) as mock_reclaim: + with ( + patch("omlx.engine_core.get_registry") as mock_registry, + patch("omlx.engine_core._final_engine_thread_reclaim") as mock_reclaim, + ): mock_registry.return_value.acquire.return_value = True engine = EngineCore(mock_model, mock_tokenizer) @@ -280,45 +275,54 @@ def reclaim_side_effect(_stream): mock_model.release_resources.side_effect = lambda: events.append("release") mock_reclaim.side_effect = reclaim_side_effect - mock_clear.side_effect = lambda: events.append("compile") engine.close() - # Memory is reclaimed after dropping engine refs, then the compile - # cache is cleared on the worker thread before thread shutdown. + # Memory is reclaimed after dropping engine refs, then MLX 0.32.2 + # can tear the worker down without a private cache-clear symbol. mock_model.release_resources.assert_called_once_with() mock_reclaim.assert_called_once_with(engine._mlx_stream) - mock_clear.assert_called() - assert events == ["release", "reclaim", "compile"] + assert events == ["release", "reclaim"] assert engine._mlx_executor is None assert executor._shutdown - assert executor not in ec._immortal_mlx_executors - def test_close_keeps_executor_alive_when_clear_unavailable(self): - """Fallback (clear symbol unresolvable, e.g. a future MLX rename): - close() must NOT exit the worker thread, since that would run MLX's - thread_local ~CompilerCache and crash for @mx.compile models. The - executor + stream are pinned immortal for the process lifetime.""" - import omlx.engine_core as ec + def test_final_reclaim_clears_worker_thread_streams(self): + """The last operation on an MLX worker must release its stream registry.""" + from omlx.engine_core import _final_engine_thread_reclaim - mock_model = MagicMock() - mock_model.model_type = "test" - mock_tokenizer = MagicMock() - mock_tokenizer.eos_token_id = 0 - - with patch("omlx.engine_core.get_registry") as mock_registry, patch( - "omlx.engine_core.compile_cache_clear_available", return_value=False + order = [] + with ( + patch( + "omlx.engine_core.gc.collect", side_effect=lambda: order.append("gc") + ), + patch( + "omlx.engine_core._sync_and_clear_cache", + side_effect=lambda _stream: order.append("cache"), + ), + patch( + "omlx.engine_core.clear_thread_streams", + side_effect=lambda: order.append("streams"), + ), ): - mock_registry.return_value.acquire.return_value = True + _final_engine_thread_reclaim(object()) - engine = EngineCore(mock_model, mock_tokenizer) - executor = engine._mlx_executor - stream = engine._mlx_stream - engine.close() + assert order == ["gc", "cache", "gc", "streams"] - assert engine._mlx_executor is None - assert not executor._shutdown - assert executor in ec._immortal_mlx_executors - assert stream in ec._immortal_mlx_streams + def test_stream_cleanup_synchronizes_before_registry_clear(self): + from omlx.utils.metal_sync import clear_thread_streams + + with patch("omlx.utils.metal_sync.mx") as mock_mx: + clear_thread_streams() + + assert mock_mx.method_calls == [call.synchronize(), call.clear_streams()] + + def test_stream_cleanup_handles_an_unused_worker(self): + from omlx.utils.metal_sync import clear_thread_streams + + with patch("omlx.utils.metal_sync.mx") as mock_mx: + mock_mx.synchronize.side_effect = RuntimeError("no stream") + clear_thread_streams() + + mock_mx.clear_streams.assert_called_once_with() class TestConcurrentStreamIsolation: diff --git a/tests/test_qwen35_fa256_attention.py b/tests/test_qwen35_fa256_attention.py index e775bae17b..9954f8b5db 100644 --- a/tests/test_qwen35_fa256_attention.py +++ b/tests/test_qwen35_fa256_attention.py @@ -6,6 +6,7 @@ import math import sys import types +from unittest.mock import MagicMock import mlx.core as mx import pytest @@ -48,8 +49,10 @@ def original(q, k, v, cache, scale, mask=None, sinks=None): @pytest.fixture(autouse=True) def _fresh_fa256_patch(monkeypatch): import omlx.patches.qwen35_fa256_attention as patch + from omlx import memory_monitor monkeypatch.setattr(patch, "_PATCHED", False, raising=False) + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) # Pin the NAX auto-gate off so apply/route behavior stays identical on # M5-family test machines; the NAX gating tests override this locally. monkeypatch.setattr(patch, "is_nax_available", lambda: False) @@ -68,6 +71,7 @@ def _fresh_fa256_patch(monkeypatch): monkeypatch.delenv("OMLX_FA256_DISPATCH_BUDGET", raising=False) yield monkeypatch.setattr(patch, "_PATCHED", False, raising=False) + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) def test_route_gate_is_qwen_fa256_only(): @@ -138,6 +142,11 @@ def fake_kernel( ) ] + from omlx import memory_monitor + + routes = memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS[256] + assert any(route.min_query_len == 16 and route.min_kv_len == 16 for route in routes) + q_decode, _, _ = _qkv(1, 32) assert ( base.scaled_dot_product_attention(q_decode, k, v, None, scale, "causal") @@ -145,6 +154,29 @@ def fake_kernel( ) +def test_kernel_failure_keeps_registered_bounded_route(monkeypatch): + import omlx.patches.qwen35_fa256_attention as patch + + base, _ = _install_fake_vlm_base(monkeypatch) + monkeypatch.setattr( + patch, "_native_kernel", lambda: MagicMock(side_effect=RuntimeError("boom")) + ) + monkeypatch.setattr( + patch._fa256_fast, "fa256_supports_dispatch_budget", lambda: True + ) + monkeypatch.setattr(patch.mx.metal, "is_available", lambda: True) + bounded = MagicMock(return_value="bounded") + monkeypatch.setattr(patch, "_bounded_sdpa_fallback", bounded) + + assert patch.apply_qwen35_fa256_attention_patch(min_kv_len=16) + q, k, v = _qkv(32, 32) + scale = 1.0 / math.sqrt(256) + assert ( + base.scaled_dot_product_attention(q, k, v, None, scale, "causal") == "bounded" + ) + bounded.assert_called_once_with(q, k, v, scale, "causal", None) + + def test_dispatch_budget_env_and_capability_gate(monkeypatch): import omlx.patches.qwen35_fa256_attention as patch @@ -223,9 +255,8 @@ def fake_kernel( def test_apply_skips_on_nax_gpu(monkeypatch): - # On NAX GPUs stock SDPA's unfused head_dim-256 prefill runs its matmuls - # on the tensor units and beats the pre-NAX steel kernel (M5 Max report: - # 4k pp 828 -> 400 tok/s), so the auto mode must not install the patch. + # MLX 0.32.2 has a native NAX split-D fused path for head-dim-256 causal + # prefill, so the auto mode must not replace it with the pre-NAX kernel. import omlx.patches.qwen35_fa256_attention as patch monkeypatch.setattr(patch, "is_nax_available", lambda: True) diff --git a/tests/test_qwen4_qsa_prefill_memory.py b/tests/test_qwen4_qsa_prefill_memory.py index 125258603d..1846b64640 100644 --- a/tests/test_qwen4_qsa_prefill_memory.py +++ b/tests/test_qwen4_qsa_prefill_memory.py @@ -57,6 +57,7 @@ def test_bool_mask_uses_tiled_sdpa_and_matches_dense(monkeypatch): monkeypatch.setattr(sdpa256, "_SDPA256_MIN_KV_LEN", 64) monkeypatch.setattr(sdpa256, "_Q_TILE", 16) monkeypatch.setattr(sdpa256, "_KV_TILE", 64) + monkeypatch.setattr(sdpa256.mx.metal, "is_available", lambda: False) mx.random.seed(0) queries = mx.random.normal((1, 4, 32, 256)).astype(mx.float16) diff --git a/tests/test_reranker_causal_lm.py b/tests/test_reranker_causal_lm.py index 2e7e425141..08b6ac7f39 100644 --- a/tests/test_reranker_causal_lm.py +++ b/tests/test_reranker_causal_lm.py @@ -1170,9 +1170,6 @@ def test_close_releases_compiled_model_and_processor_resources(self): with ( patch("omlx.models.reranker.gc.collect") as collect, patch("omlx.models.reranker.mx") as mock_mx, - patch( - "omlx.models.reranker.clear_thread_compile_cache" - ) as clear_compile_cache, ): model.close() @@ -1195,5 +1192,4 @@ def test_close_releases_compiled_model_and_processor_resources(self): assert model._is_compiled is False mock_mx.synchronize.assert_called_once() mock_mx.clear_cache.assert_called_once() - clear_compile_cache.assert_called_once() assert collect.call_count == 2 diff --git a/tests/test_scheduler.py b/tests/test_scheduler.py index 54c773870c..f6d0f22fde 100644 --- a/tests/test_scheduler.py +++ b/tests/test_scheduler.py @@ -1957,6 +1957,9 @@ def record_executor_shutdown(wait=True): "executor_shutdown", "drain", ], f"Expected drain to bracket executor.shutdown, got: {call_order}" + fake_executor.submit.assert_called_once_with( + scheduler_module.clear_thread_streams + ) fake_executor.shutdown.assert_called_once_with(wait=False) def test_shutdown_closes_boundary_snapshot_store( diff --git a/tests/test_sdpa256_attention.py b/tests/test_sdpa256_attention.py index 93a891e588..3fb34e823b 100644 --- a/tests/test_sdpa256_attention.py +++ b/tests/test_sdpa256_attention.py @@ -2,7 +2,7 @@ """Tests for the head_dim=256 long-context prefill SDPA patch. Covers (without needing the full Qwen3.6 model): - - the flash kernel matches mx.fast.scaled_dot_product_attention numerically + - the forced native kernel matches default MLX SDPA numerically (square causal, chunked-prefill non-square causal, and decode shapes); - the route gate engages only for head_dim=256 / qL>1 / causal / long kv; - the patched SDPA passes through unchanged for non-256 / decode / short kv; @@ -10,7 +10,7 @@ registered, and stays O(L^2) otherwise; - memory-aware routing (issue #2204): with a headroom provider registered the route prefers the faster unfused fallback whenever its transient - fits, and falls back to always-tiled without headroom info. + fits, and falls back to forced fused without headroom info. """ import logging @@ -82,6 +82,97 @@ def test_flash_sdpa256_memory_is_sub_quadratic(): assert peaks[1] < 6 * peaks[0] +def test_metal_bounded_path_forces_mlx0322_fused_kernel(monkeypatch): + from omlx.patches import sdpa256_attention as sdpa256 + + calls = [] + + def fake_sdpa(q, k, v, **kwargs): + calls.append(kwargs) + return q + + monkeypatch.setattr(sdpa256.mx.metal, "is_available", lambda: True) + monkeypatch.setattr(sdpa256.mx.fast, "scaled_dot_product_attention", fake_sdpa) + q = types.SimpleNamespace(shape=(1, 4, 16, 256)) + k = types.SimpleNamespace(shape=(1, 2, 32, 256)) + v = types.SimpleNamespace(shape=(1, 2, 32, 256)) + assert sdpa256._flash_sdpa256(q, k, v, SCALE_256, "causal") is q + assert calls == [ + { + "scale": SCALE_256, + "mask": "causal", + "sinks": None, + "force_fused": True, + } + ] + + +@pytest.mark.parametrize("case", ["boolean", "additive", "sinks"]) +def test_bounded_path_preserves_array_masks_and_sinks(case): + """Exercise the real MLX 0.32.2 fused call on Metal when available.""" + from omlx.patches.sdpa256_attention import _flash_sdpa256 + + q, k, v = _qkv(16, 32, n_q=4, n_kv=2) + mask = None + sinks = None + if case == "boolean": + mask = mx.arange(32)[None, None, None, :] >= 8 + elif case == "additive": + allowed = mx.arange(32)[None, None, None, :] >= 8 + mask = mx.where(allowed, 0.0, -1e4).astype(mx.float16) + else: + sinks = mx.array([-0.5, 0.0, 0.5, 1.0], dtype=mx.float16) + + out = _flash_sdpa256(q, k, v, SCALE_256, mask, sinks) + ref = mx.fast.scaled_dot_product_attention( + q, k, v, scale=SCALE_256, mask=mask, sinks=sinks + ) + mx.eval(out, ref) + assert _max_abs(out, ref) < 2e-2 + + +@pytest.mark.parametrize("mask_kind", ["boolean", "additive"]) +def test_portable_array_mask_matches_reference(mask_kind, monkeypatch): + """CUDA's bounded fallback must preserve both MLX array-mask forms.""" + from omlx.patches import sdpa256_attention as sdpa256 + + monkeypatch.setattr(sdpa256.mx.metal, "is_available", lambda: False) + monkeypatch.setattr(sdpa256, "_Q_TILE", 16) + monkeypatch.setattr(sdpa256, "_KV_TILE", 32) + q, k, v = _qkv(32, 96, n_q=4, n_kv=2) + allowed = mx.arange(96)[None, None, None, :] >= 24 + if mask_kind == "boolean": + mask = allowed + else: + mask = mx.where(allowed, 0.0, -1e4).astype(mx.float16) + + out = sdpa256._flash_sdpa256(q, k, v, SCALE_256, mask) + ref = mx.fast.scaled_dot_product_attention(q, k, v, scale=SCALE_256, mask=mask) + mx.eval(out, ref) + assert _max_abs(out, ref) < 2e-2 + + +def test_portable_sinks_and_value_dimension_match_reference(monkeypatch): + """The portable path must cover sink models and non-square value heads.""" + from omlx.patches import sdpa256_attention as sdpa256 + + monkeypatch.setattr(sdpa256.mx.metal, "is_available", lambda: False) + monkeypatch.setattr(sdpa256, "_Q_TILE", 16) + monkeypatch.setattr(sdpa256, "_KV_TILE", 32) + mx.random.seed(1) + q = mx.random.normal((1, 4, 32, 256)).astype(mx.float16) + k = mx.random.normal((1, 2, 96, 256)).astype(mx.float16) + v = mx.random.normal((1, 2, 96, 128)).astype(mx.float16) + sinks = mx.array([-0.5, 0.0, 0.5, 1.0], dtype=mx.float16) + mx.eval(q, k, v, sinks) + + out = sdpa256._flash_sdpa256(q, k, v, SCALE_256, None, sinks) + ref = mx.fast.scaled_dot_product_attention(q, k, v, scale=SCALE_256, sinks=sinks) + mx.eval(out, ref) + assert out.shape == (1, 4, 32, 128) + assert _max_abs(out, ref) < 2e-2 + + # --- route gate ---------------------------------------------------------- @@ -95,7 +186,7 @@ def test_should_route_gate(): qd, kd, _ = _qkv(1, 16384) assert sdpa256._should_route(qd, kd, None, "causal", None) is False # decode-shaped multi-row (MTP verify, qL = 1 + depth <= 9) -> stock path; - # the per-tile eval sync collapses long-context MTP tok/s (issue #2127) + # tiny-query fused routing is already handled by MLX's vector kernel for q_len in (2, 4, 9, 15): qv, kv, _ = _qkv(q_len, 16384) assert sdpa256._should_route(qv, kv, None, "causal", None) is False @@ -107,9 +198,13 @@ def test_should_route_gate(): # wrong head_dim qh, kh, _ = _qkv(2048, 16384, head_dim=128) assert sdpa256._should_route(qh, kh, None, "causal", None) is False - # array mask / sinks -> passthrough - assert sdpa256._should_route(q, k, None, mx.zeros((2048, 16384)), None) is False - assert sdpa256._should_route(q, k, None, "causal", mx.zeros((4,))) is False + # Boolean/additive masks and attention sinks remain memory-bounded. + bool_mask = mx.ones((1, 1, 1, 16384), dtype=mx.bool_) + additive_mask = mx.zeros((1, 1, 1, 16384), dtype=mx.float16) + sinks = mx.zeros((24,), dtype=mx.float32) + assert sdpa256._should_route(q, k, None, bool_mask, None) is True + assert sdpa256._should_route(q, k, None, additive_mask, None) is True + assert sdpa256._should_route(q, k, None, "causal", sinks) is True # quantized KV cache (has .bits) -> passthrough to the quant-aware SDPA class _QuantCache: @@ -145,9 +240,9 @@ def counting_original(q, k, v, cache, scale, mask, sinks=None): real_flash = sdpa256._flash_sdpa256 - def counting_flash(q, k, v, scale, mask): + def counting_flash(q, k, v, scale, mask, sinks=None): calls["flash"] += 1 - return real_flash(q, k, v, scale, mask) + return real_flash(q, k, v, scale, mask, sinks) monkeypatch.setattr(sdpa256, "_flash_sdpa256", counting_flash) @@ -214,6 +309,33 @@ def test_estimator_switches_to_ol_when_registered(): mm._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) +def test_estimator_keeps_registered_route_thresholds_independent(): + """Two bounded kernels must not create coverage neither one provides.""" + from omlx import memory_monitor as mm + + monitor = mm.MemoryMonitor.__new__(mm.MemoryMonitor) + monitor._head_dim = 256 + monitor._num_attention_heads = 24 + monitor._num_kv_heads = 4 + monitor._score_dtype_size = 2 + + mm._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + mm.register_tiled_prefill_head_dim( + 256, min_query_len=16, min_kv_len=8192, kv_tile=1024 + ) + mm.register_tiled_prefill_head_dim( + 256, min_query_len=64, min_kv_len=2048, kv_tile=512 + ) + try: + # q=16 / kv=2048 satisfies one threshold from each registration but + # neither complete route, so the estimate must remain quadratic. + estimate = monitor._estimate_sdpa_activation_bytes(16, 2048) + assert estimate == mm.estimate_unfused_sdpa_call_bytes(24, 16, 2048, 256, 2) + assert monitor._estimate_sdpa_activation_bytes(64, 2048) < estimate * 4 + finally: + mm._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + + def test_unfused_call_bytes_shared_with_guard_estimator(): """The route gate and the guard must price the unfused path identically: the guard's unfused branch is the shared module function.""" @@ -268,7 +390,7 @@ def test_route_prefers_stock_when_unfused_fits(_sdpa256_provider_reset): need = estimate_unfused_sdpa_call_bytes(24, 2048, 16384, 256, q.dtype.size) owner.value = need assert sdpa256._should_route(q, k, None, "causal", None) is False - # ...one byte short -> tiled. + # ...one byte short -> forced fused. owner.value = need - 1 assert sdpa256._should_route(q, k, None, "causal", None) is True @@ -328,19 +450,37 @@ def test_parse_force_tiled_env(monkeypatch): assert sdpa256._parse_force_tiled_env() is False -# --- tiled-route engagement logging (issue #2283) -------------------------- +def test_force_off_does_not_publish_a_bounded_memory_route(monkeypatch): + """The O(L^2) benchmark override must keep conservative admission math.""" + from omlx import memory_monitor as mm + from omlx.patches import sdpa256_attention as sdpa256 + + mm._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + monkeypatch.setattr(sdpa256, "_FORCE_TILED", False) + assert sdpa256._register_bounded_route(8192) is False + assert 256 not in mm._SDPA_TILED_PREFILL_HEAD_DIMS + + monkeypatch.setattr(sdpa256, "_FORCE_TILED", None) + assert sdpa256._register_bounded_route(8192) is True + try: + assert 256 in mm._SDPA_TILED_PREFILL_HEAD_DIMS + finally: + mm._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + + +# --- bounded-route engagement logging (issue #2283) ------------------------ def _tiled_log_records(caplog): return [ r for r in caplog.records - if r.levelname == "INFO" and "tiled" in r.getMessage() + if r.levelname == "INFO" and "memory-bounded path" in r.getMessage() ] def test_tiled_route_logs_once_when_no_provider(_sdpa256_provider_reset, caplog): - """Guard-off servers land on the tiled path silently (issue #2283); the + """Guard-off servers land on forced fused silently (issue #2283); the first engagement must say so at INFO, repeats must stay quiet.""" sdpa256 = _sdpa256_provider_reset q, k, _ = _qkv(2048, 16384) @@ -415,7 +555,7 @@ def _current_usage_bytes(self): fake = _Fake() # Nothing propagated yet: guard state is unknown, so the negative - # sentinel keeps the tiled default even though the flag reads False. + # sentinel keeps the bounded default even though the flag reads False. assert Scheduler._sdpa256_unfused_headroom(fake) == -1 # Enforcer has spoken and the guard is explicitly off: the user opted @@ -472,8 +612,8 @@ class _Fake: def test_scheduler_init_registers_headroom_provider(_sdpa256_provider_reset): """Constructing a Scheduler must wire the provider (the production seam: - a rename that silently skips registration would revert #2204 to - always-tiled).""" + a rename that silently skips registration would revert #2204 to an + unbounded default).""" from unittest.mock import MagicMock from omlx.scheduler import Scheduler, SchedulerConfig @@ -493,7 +633,7 @@ def test_scheduler_init_registers_headroom_provider(_sdpa256_provider_reset): bound = ref() assert bound is not None assert bound.__self__ is scheduler - # Ceiling not propagated yet -> negative sentinel keeps the tiled default. + # Ceiling not propagated yet -> negative sentinel keeps the bounded default. assert bound() == -1 @@ -560,9 +700,9 @@ def test_vlm_submodule_rebind_covers_copied_reference( flash_calls = {"n": 0} real_flash = sdpa256._flash_sdpa256 - def counting_flash(q, k, v, scale, mask): + def counting_flash(q, k, v, scale, mask, sinks=None): flash_calls["n"] += 1 - return real_flash(q, k, v, scale, mask) + return real_flash(q, k, v, scale, mask, sinks) monkeypatch.setattr(sdpa256, "_flash_sdpa256", counting_flash) diff --git a/tests/test_vlm_mtp.py b/tests/test_vlm_mtp.py index f97a603bc1..c3bc060385 100644 --- a/tests/test_vlm_mtp.py +++ b/tests/test_vlm_mtp.py @@ -18,6 +18,17 @@ from omlx.speculative import vlm_mtp +def test_mtp_rounds_share_the_wrapper_generation_stream(): + """The wrapper must drain the same stream used inside both round loops.""" + from mlx_vlm.speculative import common, mtp + + stream = vlm_mtp._vlm_generation_stream + assert stream is common.generation_stream + assert stream is mtp.generation_stream + assert stream is vlm_mtp._mtp_rounds.__globals__["generation_stream"] + assert stream is vlm_mtp._mtp_rounds_batch.__globals__["generation_stream"] + + def test_qwen38_block_fp8_dequantization(): from omlx.patches.mlx_vlm_mtp.qwen38_fp8 import dequantize_fp8_weights From dc312e6e905e03d21ef0c4a86289cbfa2cf857cc Mon Sep 17 00:00:00 2001 From: jundot Date: Mon, 31 Aug 2026 23:44:02 +0900 Subject: [PATCH 055/132] fix: validate boundary snapshots before materialization --- omlx/cache/boundary_snapshot_store.py | 10 ++++++++-- tests/test_boundary_snapshot_store.py | 26 ++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/omlx/cache/boundary_snapshot_store.py b/omlx/cache/boundary_snapshot_store.py index a83726fcf6..fa7452b21f 100644 --- a/omlx/cache/boundary_snapshot_store.py +++ b/omlx/cache/boundary_snapshot_store.py @@ -425,12 +425,15 @@ def load( arrays, metadata = data else: return None + reconstructed = self._reconstruct_from_safetensors(arrays, metadata) + if reconstructed is None: + return None # mx.load returns file-backed lazy arrays. Materialize them while # this ephemeral snapshot still exists so the reconstructed cache # cannot retain a read primitive past cleanup or promotion. if arrays: mx.eval(*arrays.values()) - return self._reconstruct_from_safetensors(arrays, metadata) + return reconstructed except Exception as e: logger.debug( "Failed to load boundary snapshot %s/%d: %s", @@ -461,12 +464,15 @@ def load_file(self, file_path: Path) -> list[dict[str, Any]] | None: if not (isinstance(data, tuple) and len(data) == 2): return None arrays, metadata = data + reconstructed = self._reconstruct_from_safetensors(arrays, metadata) + if reconstructed is None: + return None # ``take_staged_file`` transfers this path to a caller that may # move or unlink it immediately after load_file returns. Detach # every lazy input from the file before returning cache state. if arrays: mx.eval(*arrays.values()) - return self._reconstruct_from_safetensors(arrays, metadata) + return reconstructed except Exception as e: logger.debug("Failed to load committed boundary snapshot %s: %s", file_path, e) return None diff --git a/tests/test_boundary_snapshot_store.py b/tests/test_boundary_snapshot_store.py index 1fb05eb776..9ef5e63c45 100644 --- a/tests/test_boundary_snapshot_store.py +++ b/tests/test_boundary_snapshot_store.py @@ -369,6 +369,32 @@ def test_load_from_disk_after_pending_writes_cleared(self): assert len(loaded) == 4 assert loaded[1]["class_name"] == "ArraysCache" + def test_invalid_disk_metadata_is_rejected_before_materialization( + self, monkeypatch + ): + from omlx.cache import boundary_snapshot_store as mod + + request_id = "invalid-metadata" + token_count = 1024 + file_path = self.store._file_path(request_id, token_count) + file_path.parent.mkdir(parents=True) + mx.save_safetensors( + str(file_path), + {"payload": mx.ones((8,), dtype=mx.float32)}, + metadata={ + "num_layers": "0", + "layer_info": "[]", + "gdn_sidecar_format_version": "999", + }, + ) + + eval_mock = MagicMock(side_effect=AssertionError("unexpected mx.eval")) + monkeypatch.setattr(mod.mx, "eval", eval_mock) + + assert self.store.load(request_id, token_count) is None + assert self.store.load_file(file_path) is None + eval_mock.assert_not_called() + def test_multiple_snapshots_per_request(self): """Multiple token boundaries for the same request.""" for tc in [1024, 2048, 3072, 4096]: From 61e102764161a892d534a54ba339db15363f8d99 Mon Sep 17 00:00:00 2001 From: KC <79471844+wolfyy970@users.noreply.github.com> Date: Tue, 1 Sep 2026 04:14:37 -0400 Subject: [PATCH 056/132] fix(qwen4_exp): gather text mRoPE prefills and stop pricing them as dense SDPA (#3350) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Parent LanguageModel tiles identical text positions to (3, 1, L), which failed gathered QSA eligibility, and the guard then priced the suffix as dense Q×kv with a leftover last_delta. Charge the 2048-token gathered core for text-only prefills and ignore 8× dense history only while that cheaper charge is on. Co-authored-by: Cursor --- omlx/memory_monitor.py | 136 +++++++++++++++++- .../mlx_vlm/models/qwen4_exp/language.py | 134 +++++++++++++---- omlx/scheduler.py | 66 +++++++-- tests/test_memory_monitor_vlm_config.py | 38 +++++ tests/test_mlx_vlm_qwen4_exp_compat.py | 34 ++++- tests/test_prefill_oom_graceful.py | 42 ++++++ 6 files changed, 406 insertions(+), 44 deletions(-) diff --git a/omlx/memory_monitor.py b/omlx/memory_monitor.py index 703feee9b1..05490b3223 100644 --- a/omlx/memory_monitor.py +++ b/omlx/memory_monitor.py @@ -249,6 +249,9 @@ def __init__( # Fixed per-sequence recurrent state (GDN/Mamba ArraysCache), # measured once from a live cache after the first prefill chunk. self._fixed_state_bytes: int = 0 + # When True, Qwen4 QSA prefill is priced as gathered (token budget) + # rather than dense Q x kv_len. Set only for text-only prefills. + self.qwen4_charge_gathered_core: bool = False # PagedCacheManager for KV cache memory measurement self._paged_cache_manager: Optional["PagedCacheManager"] = None @@ -854,9 +857,14 @@ def estimate_chunk_transient_bytes(self, n_tokens: int, kv_len: int) -> int: Returns 0 when model info is unavailable. """ if self._prefill_memory_profile is not None: - return self._prefill_memory_profile.estimate_prefill_transient_bytes( - n_tokens, kv_len - ) + profile = self._prefill_memory_profile + if isinstance(profile, _Qwen4ExpPrefillMemoryProfile): + return profile.estimate_prefill_transient_bytes( + n_tokens, + kv_len, + gathered_core=self.qwen4_charge_gathered_core, + ) + return profile.estimate_prefill_transient_bytes(n_tokens, kv_len) return self._estimate_sdpa_activation_bytes(n_tokens, kv_len) def estimate_blocks_to_free(self, bytes_to_free: int, block_size: int) -> int: @@ -1221,14 +1229,134 @@ def estimate_prefill_transient_bytes(self, query_tokens: int, kv_len: int) -> in return max(candidates, default=0) +@dataclass(frozen=True) +class _Qwen4ExpPrefillMemoryProfile: + """Prefill estimator for Qwen4 / Flash-Next hybrid GDN + QSA. + + GDN layers keep a fixed recurrent state. QSA core attention, once the + gathered path is active, attends at most ``indexer_budget`` tokens. + The indexer still scores every compressed block (``kv_len / r``). + Dense ``Q x kv_len`` SDPA is the wrong price for that core. + """ + + qsa_layers: int + num_attention_heads: int + num_kv_heads: int + head_dim: int + indexer_n_heads: int + indexer_head_dim: int + indexer_budget: int + compress_ratio: int + dtype_size: float + score_dtype_size: float + + def estimate_resident_kv_bytes( + self, num_tokens: int, *, chunk_tokens: int = 1 + ) -> int: + if num_tokens <= 0 or self.qsa_layers <= 0: + return 0 + per_layer = ( + 2 * self.num_kv_heads * self.head_dim * self.dtype_size + + self.indexer_head_dim * self.dtype_size + + 3 * 8 + ) + return int(self.qsa_layers * per_layer * int(num_tokens)) + + def estimate_prefill_transient_bytes( + self, + query_tokens: int, + kv_len: int, + *, + gathered_core: bool = False, + ) -> int: + if query_tokens <= 0 or kv_len <= 0: + return 0 + query_tokens = int(query_tokens) + kv_len = int(kv_len) + pooled = max(kv_len // max(self.compress_ratio, 1), 1) + indexer = int( + self.indexer_n_heads * query_tokens * pooled * 4 + + self.indexer_n_heads * query_tokens * self.indexer_head_dim * 4 + ) + core_kv = kv_len + if gathered_core and kv_len > self.indexer_budget: + core_kv = min(kv_len, self.indexer_budget + self.compress_ratio - 1) + core = estimate_unfused_sdpa_call_bytes( + self.num_attention_heads, + query_tokens, + core_kv, + self.head_dim, + self.score_dtype_size, + ) + return indexer + core + + +def _make_qwen4_exp_prefill_memory_profile( + config: Any, + *, + compute_dtype_size: float, +) -> PrefillMemoryProfile | None: + num_layers = _cfg_get(config, "num_hidden_layers") + num_attention_heads = _cfg_get(config, "num_attention_heads") + num_kv_heads = _cfg_get(config, "num_key_value_heads") + head_dim = _cfg_get(config, "head_dim") + indexer_n_heads = _cfg_get(config, "indexer_n_heads") + indexer_head_dim = _cfg_get(config, "indexer_head_dim") + indexer_budget = _cfg_get(config, "indexer_budget") + compress_ratio = _cfg_get(config, "indexer_compress_ratio") + required = ( + num_layers, + num_attention_heads, + num_kv_heads, + head_dim, + indexer_n_heads, + indexer_head_dim, + indexer_budget, + compress_ratio, + ) + if not all(_pos_int(value) for value in required): + return None + if not isinstance(compute_dtype_size, (int, float)) or compute_dtype_size <= 0: + return None + layer_types = _cfg_get(config, "layer_types") or () + qsa_layers = sum( + 1 + for kind in layer_types + if kind in {"qwen_sparse_attention", "full_attention"} + ) + if qsa_layers <= 0: + interval = _cfg_get(config, "full_attention_interval") or 4 + if not _pos_int(interval): + return None + qsa_layers = int(num_layers) // int(interval) + if qsa_layers <= 0: + return None + return _Qwen4ExpPrefillMemoryProfile( + qsa_layers=qsa_layers, + num_attention_heads=int(num_attention_heads), + num_kv_heads=int(num_kv_heads), + head_dim=int(head_dim), + indexer_n_heads=int(indexer_n_heads), + indexer_head_dim=int(indexer_head_dim), + indexer_budget=int(indexer_budget), + compress_ratio=int(compress_ratio), + dtype_size=float(compute_dtype_size), + score_dtype_size=float(compute_dtype_size), + ) + + def make_prefill_memory_profile( config: Any, *, compute_dtype_size: float, wsdpa_dtype_supported: bool = False, ) -> PrefillMemoryProfile | None: - """Build the one model-specific prefill strategy currently required.""" + """Build a model-specific prefill strategy when the uniform formulas fail.""" model_type = str(_cfg_get(config, "model_type", "") or "") + if model_type.startswith("qwen4_exp"): + return _make_qwen4_exp_prefill_memory_profile( + config, compute_dtype_size=compute_dtype_size + ) if not model_type.startswith("deepseek_v4"): return None 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 a6e998d199..c497cb5626 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 @@ -1,6 +1,7 @@ from __future__ import annotations import json +import logging import math import mmap import os @@ -37,6 +38,83 @@ _PLE_RUNTIME_MODEL_PATH: Path | None = None _PLE_RUNTIME_MODE = "resident" _HYPER_SPLIT_INDICES: dict[tuple[int, int], tuple[mx.array, mx.array]] = {} +_TEXT_MROPE_EQUAL_PLANES: dict[int, tuple[int, bool]] = {} +_LAST_QSA_PATH_LOG: tuple[Any, ...] | None = None +logger = logging.getLogger("omlx.qwen4_qsa") + + +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 + cache_key = id(position_ids) + cached = _TEXT_MROPE_EQUAL_PLANES.get(cache_key) + if cached is not None and cached[0] == length: + return cached[1] + same = bool( + mx.array_equal(position_ids[0], position_ids[1]).item() + and mx.array_equal(position_ids[1], position_ids[2]).item() + ) + if len(_TEXT_MROPE_EQUAL_PLANES) >= 8: + _TEXT_MROPE_EQUAL_PLANES.clear() + _TEXT_MROPE_EQUAL_PLANES[cache_key] = (length, same) + return same + + +def _split_text_mrope_positions( + position_ids: Optional[mx.array], + batch: int, + length: int, + past_len: int, +) -> tuple[mx.array, mx.array]: + """Indexer text ids vs rotary ids for the gathered QSA arms.""" + if position_ids is None: + text_position_ids = mx.arange( + past_len, past_len + length, dtype=mx.int32 + )[None] + rotary_position_ids = mx.broadcast_to( + text_position_ids, + (3, batch, length), + ) + return text_position_ids, rotary_position_ids + if position_ids.ndim == 3: + return position_ids[0], position_ids + return position_ids, position_ids + + +def _log_qsa_prefill_path( + path: str, + *, + kv_len: int, + query: int, + position_ndim: int | None, +) -> None: + global _LAST_QSA_PATH_LOG + key = (path, kv_len, query, position_ndim) + if key == _LAST_QSA_PATH_LOG: + return + _LAST_QSA_PATH_LOG = key + logger.info( + "qwen4 QSA prefill path=%s query=%d kv_len=%d position_ids.ndim=%s", + path, + query, + kv_len, + position_ndim, + ) @dataclass(frozen=True) @@ -1030,13 +1108,9 @@ def _batch_one_text_position_ids( position_ids: Optional[mx.array], length: int, ) -> bool: - """Accept absent or shape-matched 2-D text positions, never MRoPE.""" + """Accept absent, 2-D text, or broadcast-identical 3-D text mRoPE.""" - return position_ids is None or bool( - isinstance(position_ids, mx.array) - and position_ids.ndim == 2 - and position_ids.shape == (1, length) - ) + return _broadcast_text_mrope_position_ids(position_ids, length) def _gathered_text_prefill_eligible( self, @@ -1137,17 +1211,9 @@ def _gathered_text_prefill( ).transpose(0, 2, 1, 3) past_len = cache.offset - if position_ids is None: - text_position_ids = mx.arange( - past_len, past_len + length, dtype=mx.int32 - )[None] - rotary_position_ids = mx.broadcast_to( - text_position_ids, - (3, batch, length), - ) - else: - text_position_ids = position_ids - rotary_position_ids = position_ids + text_position_ids, rotary_position_ids = _split_text_mrope_positions( + position_ids, batch, length, past_len + ) queries, keys = self.rotary_emb.apply_rotary( queries, keys, @@ -1238,19 +1304,9 @@ def _gathered_text_decode( ).transpose(0, 2, 1, 3) past_len = cache.offset - if position_ids is None: - text_position_ids = mx.arange( - past_len, - past_len + 1, - dtype=mx.int32, - )[None] - rotary_position_ids = mx.broadcast_to( - text_position_ids, - (3, batch, length), - ) - else: - text_position_ids = position_ids - rotary_position_ids = position_ids + text_position_ids, rotary_position_ids = _split_text_mrope_positions( + position_ids, batch, length, past_len + ) queries, new_keys = self.rotary_emb.apply_rotary( queries, new_keys, @@ -1306,6 +1362,11 @@ def __call__( position_embeddings: Optional[tuple[mx.array, mx.array]] = None, target_verify: bool = False, ) -> mx.array: + query = int(x.shape[1]) if x.ndim == 3 else 0 + kv_len = int(getattr(cache, "offset", 0) or 0) + query + position_ndim = ( + int(position_ids.ndim) if isinstance(position_ids, mx.array) else None + ) if self._gathered_text_decode_eligible( x, mask, @@ -1324,8 +1385,21 @@ def __call__( position_embeddings, target_verify, ): + _log_qsa_prefill_path( + "gathered", + kv_len=kv_len, + query=query, + position_ndim=position_ndim, + ) return self._gathered_text_prefill(x, cache, position_ids) + if query > 1: + _log_qsa_prefill_path( + "mask_dense", + kv_len=kv_len, + query=query, + position_ndim=position_ndim, + ) qsa_mask = self.indexer( x, cache, diff --git a/omlx/scheduler.py b/omlx/scheduler.py index be51b0748a..556d7df3f7 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -3399,12 +3399,38 @@ def _apply_turboquant_kv_convert(self, prompt_cache: list[Any]) -> None: f"cache layers to {bits}-bit{skip_msg}" ) + @contextmanager + def _qwen4_gathered_core_charge(self, enabled: bool): + """Price Qwen4 QSA core as gathered for text-only prefills only.""" + monitor = self.memory_monitor + if monitor is None: + yield + return + previous = bool(getattr(monitor, "qwen4_charge_gathered_core", False)) + monitor.qwen4_charge_gathered_core = bool(enabled) + try: + yield + finally: + monitor.qwen4_charge_gathered_core = previous + def _do_external_prefill( self, request: "Request", tokens: list[int], existing_cache: list[Any] | None, vlm_embeds: tuple[mx.array, dict[str, Any], int] | None = None, + ) -> tuple[list[Any], list[int]]: + with self._qwen4_gathered_core_charge(vlm_embeds is None): + return self._do_external_prefill_impl( + request, tokens, existing_cache, vlm_embeds + ) + + def _do_external_prefill_impl( + self, + request: "Request", + tokens: list[int], + existing_cache: list[Any] | None, + vlm_embeds: tuple[mx.array, dict[str, Any], int] | None = None, ) -> tuple[list[Any], list[int]]: """Run prefill externally (outside BatchGenerator) for a single request. @@ -3872,21 +3898,43 @@ def _predicted_chunk_transient(self, n_tokens: int, kv_len: int) -> float: static_per_token = 0.0 recent_reclaim = 0 tracker = self._prefill_transient_tracker - if tracker is not None: - if tracker.last_n_tokens > 0 and tracker.last_delta_bytes > 0: - per_token = max( - per_token, tracker.last_delta_bytes / tracker.last_n_tokens - ) - if tracker.bytes_per_token > 0: - per_token = max(per_token, tracker.bytes_per_token) - recent_reclaim = tracker.recent_reclaim_bytes + # Gathered QSA prices a ~2K core, not Q×kv_len. A leftover dense + # last_delta/EWMA would still refuse that cheap chunk. Only ignore + # history while that cheaper charge is active — other models must + # keep max(last_delta, EWMA, static) or a real dense spike undercharges. + # `is True` so a MagicMock monitor in tests cannot trip this gate. + ignore_dense_history = ( + getattr(self.memory_monitor, "qwen4_charge_gathered_core", False) + is True + ) if self.memory_monitor is not None: static = self.memory_monitor.estimate_chunk_transient_bytes( n_tokens, kv_len + n_tokens ) static += self.memory_monitor.estimate_prompt_kv_bytes(n_tokens) static_per_token = float(static) / n_tokens - per_token = max(per_token, static_per_token) + per_token = static_per_token + if tracker is not None: + ewma = float(tracker.bytes_per_token) + recent_reclaim = tracker.recent_reclaim_bytes + outlier_ratio = PrefillTransientTracker._EWMA_OUTLIER_RATIO + dense_history_is_stale = ( + ignore_dense_history + and static_per_token > 0 + and ewma > static_per_token * outlier_ratio + ) + if ewma > 0 and not dense_history_is_stale: + per_token = max(per_token, ewma) + if tracker.last_n_tokens > 0 and tracker.last_delta_bytes > 0: + measured = tracker.last_delta_bytes / tracker.last_n_tokens + if ( + ignore_dense_history + and static_per_token > 0 + and measured > static_per_token * outlier_ratio + ): + measured = 0.0 + if measured > 0: + per_token = max(per_token, measured) base_prediction = per_token * n_tokens * self._PREFILL_TRANSIENT_SAFETY reallocation_prediction = ( static_per_token * n_tokens * self._PREFILL_TRANSIENT_SAFETY diff --git a/tests/test_memory_monitor_vlm_config.py b/tests/test_memory_monitor_vlm_config.py index 10c61aba7e..d81a5d2392 100644 --- a/tests/test_memory_monitor_vlm_config.py +++ b/tests/test_memory_monitor_vlm_config.py @@ -12,6 +12,7 @@ count, else fall back to the top-level config. """ +from types import SimpleNamespace from unittest.mock import MagicMock import mlx.core as mx @@ -134,6 +135,43 @@ def test_qwen4_qsa_memory_includes_indexer_and_mrope_state(): assert estimate == 12 * (2 * 2 * 128 * 2 + 128 * 2 + 3 * 8) +def test_qwen4_prefill_profile_gathered_core_caps_score_matrix(): + from omlx.memory_monitor import MemoryMonitor, make_prefill_memory_profile + + config = SimpleNamespace( + model_type="qwen4_exp", + num_hidden_layers=48, + num_attention_heads=24, + num_key_value_heads=2, + head_dim=256, + indexer_n_heads=4, + indexer_head_dim=128, + indexer_budget=2048, + indexer_compress_ratio=4, + full_attention_interval=4, + layer_types=None, + ) + profile = make_prefill_memory_profile(config, compute_dtype_size=2) + assert profile is not None + monitor = MemoryMonitor(max_kv_cache_memory=1024**3, eviction_enabled=False) + monitor.set_model_info( + num_layers=48, + num_kv_heads=2, + head_dim=256, + dtype_size=2, + num_attention_heads=24, + prefill_memory_profile=profile, + ) + query, kv_len = 4096, 233_472 + monitor.qwen4_charge_gathered_core = False + dense = monitor.estimate_chunk_transient_bytes(query, kv_len) + monitor.qwen4_charge_gathered_core = True + gathered = monitor.estimate_chunk_transient_bytes(query, kv_len) + assert gathered * 8 < dense + # 147GB resident + this gathered gulp stays under the 214GB safety cap. + assert gathered < 12 * 1024**3 + + class TestSetModelInfoForMonitorVLMWalk: """``_set_model_info_for_monitor`` must prefer LM dimensions from a nested sub-config when one exists, otherwise fall back to top-level.""" diff --git a/tests/test_mlx_vlm_qwen4_exp_compat.py b/tests/test_mlx_vlm_qwen4_exp_compat.py index 18c34623aa..3c34dcc802 100644 --- a/tests/test_mlx_vlm_qwen4_exp_compat.py +++ b/tests/test_mlx_vlm_qwen4_exp_compat.py @@ -684,7 +684,39 @@ def must_not_run(*args, **kwargs): assert output.shape == hidden.shape -def test_qwen4_gathered_qsa_fails_closed_for_batched_prefill(monkeypatch): +def test_qwen4_gathered_qsa_routes_broadcast_text_mrope(monkeypatch): + """Parent LM tiles identical text positions to (3,1,L). That is still text.""" + config = _tiny_config() + import mlx_vlm.models.qwen4_exp.language as language + from mlx_vlm.models.qwen4_exp.language import QSAKVCache, Qwen4ExpAttention + + attention = Qwen4ExpAttention(config.text_config) + mx.eval(attention.parameters()) + hidden = mx.random.normal((1, 20, config.text_config.hidden_size)) + text_ids = mx.arange(20, dtype=mx.int32)[None] + position_ids = mx.broadcast_to(text_ids[None], (3, 1, 20)) + + calls = [] + gathered = language.contiguous_causal_gathered_qsa + + def tracked(*args, **kwargs): + calls.append((args[0].shape, args[1].shape)) + return gathered(*args, **kwargs) + + monkeypatch.setattr(language, "contiguous_causal_gathered_qsa", tracked) + actual = attention( + hidden, + mask="causal", + cache=QSAKVCache(), + position_ids=position_ids, + ) + mx.eval(actual) + + assert calls, "broadcast text mRoPE must take gathered QSA, not mask+dense SDPA" + assert actual.shape == hidden.shape + + +def test_qwen4_gathered_qsa_fails_closed_for_batched_requests(monkeypatch): config = _tiny_config() import mlx_vlm.models.qwen4_exp.language as language from mlx_vlm.models.qwen4_exp.language import QSAKVCache, Qwen4ExpAttention diff --git a/tests/test_prefill_oom_graceful.py b/tests/test_prefill_oom_graceful.py index 6f22516416..3efb9dcc23 100644 --- a/tests/test_prefill_oom_graceful.py +++ b/tests/test_prefill_oom_graceful.py @@ -505,6 +505,48 @@ def test_predicted_transient_zero_without_signals(): assert ns._predicted_chunk_transient(4, 1000) == 0.0 +def test_predicted_transient_drops_dense_ewma_when_qsa_static_is_cheaper(): + """A leftover dense last_delta must not refuse gathered QSA static.""" + from omlx.memory_monitor import make_prefill_memory_profile + + config = SimpleNamespace( + model_type="qwen4_exp", + num_hidden_layers=48, + num_attention_heads=24, + num_key_value_heads=2, + head_dim=256, + indexer_n_heads=4, + indexer_head_dim=128, + indexer_budget=2048, + indexer_compress_ratio=4, + full_attention_interval=4, + layer_types=None, + ) + profile = make_prefill_memory_profile(config, compute_dtype_size=2) + monitor = MemoryMonitor(max_kv_cache_memory=_GB, eviction_enabled=False) + monitor.set_model_info( + num_layers=48, + num_kv_heads=2, + head_dim=256, + dtype_size=2, + num_attention_heads=24, + prefill_memory_profile=profile, + ) + monitor.qwen4_charge_gathered_core = True + tracker = PrefillTransientTracker() + tracker.update(4096, int(69.58 * _GB)) + ns = _throttle_ctx(current=0, hard=240 * _GB, samples_bpt=None, monitor=monitor) + ns._prefill_transient_tracker = tracker + predicted = ns._predicted_chunk_transient(4096, 233_472) + dense_poison = 69.58 * _GB * Scheduler._PREFILL_TRANSIENT_SAFETY + assert predicted < dense_poison / 8 + assert 147 * _GB + predicted < 214 * _GB + # Without the gathered flag, that same leftover gulp must still bind. + monitor.qwen4_charge_gathered_core = False + dense_predicted = ns._predicted_chunk_transient(4096, 233_472) + assert dense_predicted == pytest.approx(dense_poison, rel=1e-3) + + def test_adaptive_throttle_charges_recently_reclaimed_footprint(): """A pool drop must remain priced until the next chunk reallocates it.""" static_prediction = 11.18 * _GB From 8adac5fd5846482f0ab1a183f5d988fc1f676391 Mon Sep 17 00:00:00 2001 From: KC <79471844+wolfyy970@users.noreply.github.com> Date: Tue, 1 Sep 2026 04:29:03 -0400 Subject: [PATCH 057/132] test(qwen4_exp): treat broadcast text mRoPE as gathered-eligible on decode (#3350) CI failed because decode fail-closed still expected identical (3,1,1) planes to be rejected. That shape is text after the parent LM tiles mRoPE. Unequal planes stay fail-closed. Co-authored-by: Cursor --- tests/test_qwen4_qsa_decode_gather.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/tests/test_qwen4_qsa_decode_gather.py b/tests/test_qwen4_qsa_decode_gather.py index 2b65845ff2..34f097ff87 100644 --- a/tests/test_qwen4_qsa_decode_gather.py +++ b/tests/test_qwen4_qsa_decode_gather.py @@ -238,7 +238,8 @@ def test_qwen4_decode_gather_eligibility_fails_closed_for_general_paths(): assert attention._gathered_text_decode_eligible( token, None, cache, mx.array([[10]], dtype=mx.int32), None, False ) - assert not attention._gathered_text_decode_eligible( + # Parent LM tiles identical text positions to (3, 1, 1). That is still text. + assert attention._gathered_text_decode_eligible( token, None, cache, @@ -246,6 +247,14 @@ def test_qwen4_decode_gather_eligibility_fails_closed_for_general_paths(): None, False, ) + assert not attention._gathered_text_decode_eligible( + token, + None, + cache, + mx.array([[[10]], [[10]], [[9]]], dtype=mx.int32), + None, + False, + ) assert not attention._gathered_text_decode_eligible( token, None, cache, None, None, True ) From 262a2c6cac8103880a23f80c45690c084016d8f0 Mon Sep 17 00:00:00 2001 From: KC <79471844+wolfyy970@users.noreply.github.com> Date: Tue, 1 Sep 2026 08:16:03 -0400 Subject: [PATCH 058/132] fix(qwen4_exp): pin mRoPE equal-plane cache to the live array (#3350) Keying only on id() reused CPython identities after GC, so an image mRoPE tensor could inherit a text gathered hit. Hold the array and compare with `is`. Co-authored-by: Cursor --- .../mlx_vlm/models/qwen4_exp/language.py | 16 +++++++-------- tests/test_qwen4_qsa_decode_gather.py | 20 +++++++++++++++++++ 2 files changed, 28 insertions(+), 8 deletions(-) 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 c497cb5626..f40e8a64ee 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 @@ -38,7 +38,8 @@ _PLE_RUNTIME_MODEL_PATH: Path | None = None _PLE_RUNTIME_MODE = "resident" _HYPER_SPLIT_INDICES: dict[tuple[int, int], tuple[mx.array, mx.array]] = {} -_TEXT_MROPE_EQUAL_PLANES: dict[int, tuple[int, bool]] = {} +# Identity cache: keep the array alive so CPython cannot recycle id(). +_TEXT_MROPE_EQUAL_PLANES: list[tuple[Any, int, bool]] = [] _LAST_QSA_PATH_LOG: tuple[Any, ...] | None = None logger = logging.getLogger("omlx.qwen4_qsa") @@ -61,17 +62,16 @@ def _broadcast_text_mrope_position_ids( return tuple(position_ids.shape) == (1, length) if position_ids.ndim != 3 or tuple(position_ids.shape) != (3, 1, length): return False - cache_key = id(position_ids) - cached = _TEXT_MROPE_EQUAL_PLANES.get(cache_key) - if cached is not None and cached[0] == length: - return cached[1] + 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() ) - if len(_TEXT_MROPE_EQUAL_PLANES) >= 8: - _TEXT_MROPE_EQUAL_PLANES.clear() - _TEXT_MROPE_EQUAL_PLANES[cache_key] = (length, same) + _TEXT_MROPE_EQUAL_PLANES.append((position_ids, length, same)) + if len(_TEXT_MROPE_EQUAL_PLANES) > 8: + del _TEXT_MROPE_EQUAL_PLANES[:-8] return same diff --git a/tests/test_qwen4_qsa_decode_gather.py b/tests/test_qwen4_qsa_decode_gather.py index 34f097ff87..f5247d658d 100644 --- a/tests/test_qwen4_qsa_decode_gather.py +++ b/tests/test_qwen4_qsa_decode_gather.py @@ -274,6 +274,26 @@ def test_qwen4_decode_gather_eligibility_fails_closed_for_general_paths(): ) +def test_qwen4_text_mrope_equal_plane_cache_does_not_reuse_dead_ids(): + """CPython can recycle id() once a temporary mx.array is collected.""" + + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + import mlx_vlm.models.qwen4_exp.language as language + + equal = mx.array([[[10]], [[10]], [[10]]], dtype=mx.int32) + unequal = mx.array([[[10]], [[10]], [[9]]], dtype=mx.int32) + assert language._broadcast_text_mrope_position_ids(equal, 1) + assert not language._broadcast_text_mrope_position_ids(unequal, 1) + + for _ in range(64): + assert language._broadcast_text_mrope_position_ids( + mx.array([[[4]], [[4]], [[4]]], dtype=mx.int32), 1 + ) + assert not language._broadcast_text_mrope_position_ids( + mx.array([[[4]], [[4]], [[3]]], dtype=mx.int32), 1 + ) + + @pytest.mark.parametrize("key_tokens", [4097, 32769]) def test_qwen4_decode_gather_stays_budget_bounded_at_long_cache( monkeypatch, From ebf4f1faaf7791fb073a220ddf713cfd90caa0b7 Mon Sep 17 00:00:00 2001 From: jundot Date: Tue, 1 Sep 2026 21:35:19 +0900 Subject: [PATCH 059/132] fix: handle multi-row VLM rope deltas (#3343) --- omlx/models/vlm.py | 2 ++ omlx/scheduler.py | 6 +++++- tests/test_scheduler.py | 28 ++++++++++++++++++++++++++++ tests/test_vlm_model_adapter.py | 3 +++ 4 files changed, 38 insertions(+), 1 deletion(-) diff --git a/omlx/models/vlm.py b/omlx/models/vlm.py index 949177682a..5b08f7f874 100644 --- a/omlx/models/vlm.py +++ b/omlx/models/vlm.py @@ -330,6 +330,8 @@ def get_last_rope_deltas(self) -> float: rd = getattr(self._language_model, "_rope_deltas", None) if rd is None: return 0.0 + if isinstance(rd, mx.array): + return float(rd.reshape(-1)[0].item()) if hasattr(rd, "item"): return float(rd.item()) return float(rd) diff --git a/omlx/scheduler.py b/omlx/scheduler.py index be51b0748a..3a9f9ec68b 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -10624,7 +10624,11 @@ def _report_sparse_progress(processed: int, total: int) -> None: extra = request.vlm_extra_kwargs or {} captured = extra.get("_captured_rope_deltas") if captured is not None: - if hasattr(captured, "item"): + 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) diff --git a/tests/test_scheduler.py b/tests/test_scheduler.py index f6d0f22fde..d7eb738eff 100644 --- a/tests/test_scheduler.py +++ b/tests/test_scheduler.py @@ -5887,6 +5887,34 @@ def test_schedule_waiting_preserves_vlm_position_state(self, mock_tokenizer): model.clear_vlm_position_state.assert_not_called() + def test_schedule_waiting_uses_first_captured_rope_delta(self, mock_tokenizer): + """Per-request capture must tolerate a stale multi-row delta array.""" + model = self._make_vlm_model() + scheduler = Scheduler(model=model, tokenizer=mock_tokenizer) + + mock_bg = MagicMock() + mock_bg.insert = MagicMock(return_value=[42]) + scheduler.batch_generator = mock_bg + + request = Request( + request_id="vlm-multi-rope-delta", + prompt="describe this image", + sampling_params=SamplingParams(max_tokens=50), + ) + request.prompt_token_ids = [1, 2, 3, 4, 5] + request.num_prompt_tokens = 5 + request.vlm_inputs_embeds = mx.zeros((1, 5, 64)) + request.vlm_extra_kwargs = { + "_captured_rope_deltas": mx.array([[-42.0], [-7.0]]) + } + + scheduler.waiting.append(request) + scheduler.requests[request.request_id] = request + + scheduler._schedule_waiting() + + assert request.rope_deltas == -42.0 + def test_schedule_waiting_clears_text_only_position_state(self, mock_tokenizer): """Text-only request in _schedule_waiting should clear position state. diff --git a/tests/test_vlm_model_adapter.py b/tests/test_vlm_model_adapter.py index b91225111d..40c892b458 100644 --- a/tests/test_vlm_model_adapter.py +++ b/tests/test_vlm_model_adapter.py @@ -583,6 +583,9 @@ def test_get_last_rope_deltas(self): vlm.language_model._rope_deltas = mx.array(-42.0) assert adapter.get_last_rope_deltas() == -42.0 + vlm.language_model._rope_deltas = mx.array([[-42.0], [-7.0]]) + assert adapter.get_last_rope_deltas() == -42.0 + vlm.language_model._rope_deltas = None assert adapter.get_last_rope_deltas() == 0.0 From 44e51e39e1cbbd027dffb5c39ca5e8f52ee6da6d Mon Sep 17 00:00:00 2001 From: KC <79471844+wolfyy970@users.noreply.github.com> Date: Tue, 1 Sep 2026 10:19:43 -0400 Subject: [PATCH 060/132] fix(qwen4_exp): survive batched QSA offset and mixed-rank indexer extend (#3350) MTP late-join was crashing the engine on a logging int(offset) and on concatenating 2-D gathered indexer positions with 3-D mask_dense mRoPE. Co-authored-by: Cursor --- .../mlx_vlm/models/qwen4_exp/language.py | 68 +++++++++++++++++-- tests/test_mlx_vlm_qwen4_exp_compat.py | 48 +++++++++++++ tests/test_qwen4_qsa_decode_gather.py | 13 ++++ 3 files changed, 124 insertions(+), 5 deletions(-) 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 f40e8a64ee..1d3730935d 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 @@ -117,6 +117,62 @@ def _log_qsa_prefill_path( ) +def _python_cache_offset(offset: Any) -> int: + """Scalar KV length for logging. Batched offsets use the longest row. + + ``BatchQSAKVCache.offset`` is an ``mx.array`` of per-row lengths. ``int()`` + on that array raises ``[convert] Only length-1 arrays...`` and used to + abort the engine before eligibility could fail closed onto the official + path. Logging still wants one number; the longest row is the conservative + choice for ``kv_len``. + """ + if offset is None: + return 0 + if isinstance(offset, (int, np.integer)): + return int(offset) + shape = getattr(offset, "shape", None) + if shape is None: + try: + return int(offset) + except (TypeError, ValueError): + return 0 + size = 1 + for dim in shape: + size *= int(dim) + if size <= 1: + value = offset.reshape(-1)[0] if size == 1 else offset + return int(value.item()) if hasattr(value, "item") else int(value) + return int(mx.max(offset).item()) + + +def _promote_index_positions_to_3d(positions: mx.array, planes: int) -> mx.array: + if positions.ndim == 3: + if int(positions.shape[0]) != planes: + raise ValueError( + "QSA indexer mRoPE plane count mismatch during cache extend: " + f"{tuple(int(d) for d in positions.shape)} vs planes={planes}" + ) + return positions + return mx.broadcast_to(positions[None], (planes, *positions.shape)) + + +def _unify_index_position_list( + positions: list[mx.array], +) -> list[mx.array]: + """Promote 2-D text indexer positions to 3-D mRoPE so batch concat matches. + + Gathered QSA stores the text plane as ``(B, S)``. The official mask_dense + path stores full mRoPE as ``(3, B, S)``. MTP late-join ``extend`` used to + concatenate those ranks and raise ``[concatenate] ... dimensions 3 and 2``. + """ + if len(positions) < 2: + return positions + if all(item.ndim == positions[0].ndim for item in positions): + return positions + planes = next((int(item.shape[0]) for item in positions if item.ndim == 3), 3) + return [_promote_index_positions_to_3d(item, planes) for item in positions] + + @dataclass(frozen=True) class Qwen4ExpMTPRuntime: """Lightning MTP construction decision for the next model load.""" @@ -700,10 +756,11 @@ def extend(self, other): target = max(self.index_offset, other.index_offset) left = self._pad_index(self, target, sample_keys, sample_positions) right = self._pad_index(other, target, sample_keys, sample_positions) + left_pos, right_pos = _unify_index_position_list([left[1], right[1]]) self.index_keys = mx.concatenate([left[0], right[0]], axis=0) - position_axis = 1 if sample_positions.ndim == 3 else 0 + position_axis = 1 if left_pos.ndim == 3 else 0 self.index_position_ids = mx.concatenate( - [left[1], right[1]], axis=position_axis + [left_pos, right_pos], axis=position_axis ) self.index_offset = target @@ -754,9 +811,10 @@ def merge(cls, caches): for cache in caches ] out.index_keys = mx.concatenate([row[0] for row in rows], axis=0) - position_axis = 1 if sample.index_position_ids.ndim == 3 else 0 + unified_positions = _unify_index_position_list([row[1] for row in rows]) + position_axis = 1 if unified_positions[0].ndim == 3 else 0 out.index_position_ids = mx.concatenate( - [row[1] for row in rows], axis=position_axis + unified_positions, axis=position_axis ) out.index_offset = target return out @@ -1363,7 +1421,7 @@ def __call__( target_verify: bool = False, ) -> mx.array: query = int(x.shape[1]) if x.ndim == 3 else 0 - kv_len = int(getattr(cache, "offset", 0) or 0) + query + kv_len = _python_cache_offset(getattr(cache, "offset", 0)) + query position_ndim = ( int(position_ids.ndim) if isinstance(position_ids, mx.array) else None ) diff --git a/tests/test_mlx_vlm_qwen4_exp_compat.py b/tests/test_mlx_vlm_qwen4_exp_compat.py index 3c34dcc802..92c64f97c9 100644 --- a/tests/test_mlx_vlm_qwen4_exp_compat.py +++ b/tests/test_mlx_vlm_qwen4_exp_compat.py @@ -1404,6 +1404,54 @@ def test_qwen4_batch_qsa_trim_slices_indexer_arrays(): assert batch.index_offset == 5 assert batch.index_keys.shape[1] == 5 assert batch.index_position_ids.shape[-1] == 5 + + +def test_qwen4_batch_extend_unifies_2d_and_3d_indexer_positions(): + """MTP late-join mixed gathered 2-D text positions with mask_dense 3-D mRoPE. + + That used to raise ``[concatenate] ... dimensions 3 and 2`` at + ``BatchQSAKVCache.extend``. + """ + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp.language import BatchQSAKVCache + + left = _warm_qsa_row(4, 0) + right = _warm_qsa_row(2, 40) + right.index_position_ids = mx.broadcast_to( + right.index_position_ids[None], + (3, *right.index_position_ids.shape), + ) + left_batch = left.to_batch([0]) + right_batch = right.to_batch([0]) + + left_batch.extend(right_batch) + mx.eval(left_batch.index_position_ids, left_batch.index_keys) + + assert left_batch.index_position_ids.ndim == 3 + assert left_batch.index_position_ids.shape[0] == 3 + assert left_batch.index_keys.shape[0] == 2 + extracted_right = left_batch.extract(1) + assert extracted_right.index_position_ids.ndim == 3 + assert extracted_right.index_position_ids.shape[-1] == 2 + + +def test_qwen4_batch_merge_unifies_mixed_indexer_position_ranks(): + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp.language import BatchQSAKVCache + + text = _warm_qsa_row(3, 10) + mrope = _warm_qsa_row(1, 30) + mrope.index_position_ids = mx.broadcast_to( + mrope.index_position_ids[None], + (3, *mrope.index_position_ids.shape), + ) + merged = BatchQSAKVCache.merge([text, mrope]) + mx.eval(merged.index_position_ids) + assert merged.index_position_ids.ndim == 3 + assert merged.index_position_ids.shape[0] == 3 + assert merged.offset.tolist() == [3, 1] + + def _make_bound_qwen4_language_model(config): from mlx_vlm.models.qwen4_exp.language import LanguageModel, Qwen4ExpMTPModule diff --git a/tests/test_qwen4_qsa_decode_gather.py b/tests/test_qwen4_qsa_decode_gather.py index f5247d658d..e9321509b7 100644 --- a/tests/test_qwen4_qsa_decode_gather.py +++ b/tests/test_qwen4_qsa_decode_gather.py @@ -403,3 +403,16 @@ def native(queries, keys, values, scale, causal=False): (256**-0.5, False, "native"), ] assert mx.array_equal(actual, expected).item() + + +def test_python_cache_offset_accepts_batched_mx_array(): + """Batched MTP decode used to crash the QSA path log on ``int(offset)``.""" + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + import mlx_vlm.models.qwen4_exp.language as language + + assert language._python_cache_offset(None) == 0 + assert language._python_cache_offset(0) == 0 + assert language._python_cache_offset(11) == 11 + assert language._python_cache_offset(mx.array(7, dtype=mx.int32)) == 7 + assert language._python_cache_offset(mx.array([7], dtype=mx.int32)) == 7 + assert language._python_cache_offset(mx.array([10, 20], dtype=mx.int32)) == 20 From 61cd5585f6a28cc8a8b3fee7385b4cb3e66c8d4a Mon Sep 17 00:00:00 2001 From: KC <79471844+wolfyy970@users.noreply.github.com> Date: Tue, 1 Sep 2026 12:58:23 -0400 Subject: [PATCH 061/132] fix(qwen4_exp): price gathered QSA at admission, not only during forward (#3350) Preflight still used dense SDPA, so the #3350 continuation died at the door. Thread gathered vs dense as an argument, ignore leftover dense only on gathered Qwen4, charge fixed_state on the profile resident path, and keep 3-D gather on prefill only. Co-authored-by: Cursor --- omlx/admin/context_benchmark.py | 2 +- omlx/engine/base.py | 4 + omlx/engine/batched.py | 1 + omlx/engine/vlm.py | 15 +- omlx/memory_monitor.py | 33 ++++- .../mlx_vlm/models/qwen4_exp/language.py | 15 +- omlx/prefill_transient_tracker.py | 20 ++- omlx/scheduler.py | 124 ++++++++++++----- tests/test_context_benchmark.py | 7 +- tests/test_engine_preflight.py | 3 + tests/test_memory_monitor.py | 34 +++++ tests/test_mlx_vlm_qwen4_exp_compat.py | 49 +++++++ tests/test_prefill_oom_graceful.py | 59 +++++++- tests/test_qwen4_qsa_decode_gather.py | 4 +- tests/test_scheduler_prefill_memory_guard.py | 131 ++++++++++++++++++ 15 files changed, 445 insertions(+), 56 deletions(-) diff --git a/omlx/admin/context_benchmark.py b/omlx/admin/context_benchmark.py index efc01bc740..c4bccd74d8 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) + scheduler.preflight_or_raise(num_prompt_tokens=n, text_only=True) except PrefillMemoryExceededError: return False return True diff --git a/omlx/engine/base.py b/omlx/engine/base.py index 8c81dc374c..f8564ad022 100644 --- a/omlx/engine/base.py +++ b/omlx/engine/base.py @@ -71,6 +71,7 @@ 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. @@ -91,11 +92,13 @@ 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 @@ -150,6 +153,7 @@ 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 d31b4117b5..4fc7bfbd1a 100644 --- a/omlx/engine/batched.py +++ b/omlx/engine/batched.py @@ -97,6 +97,7 @@ 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 0c1f113b5c..d8cab3d0a8 100644 --- a/omlx/engine/vlm.py +++ b/omlx/engine/vlm.py @@ -1454,6 +1454,7 @@ 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, @@ -1465,6 +1466,7 @@ async def _preflight_or_raise_with_eviction( "_mlx_executor", None, ), + text_only=text_only, ) @property @@ -3868,19 +3870,23 @@ async def preflight_chat( return # Count images from the ORIGINAL messages (the stripped # ``text_messages`` no longer has the image content-parts). - num_tokens += _count_image_tokens_real( + image_tokens = _count_image_tokens_real( messages, getattr(self, "_processor", None), upper_bound=_derive_image_token_upper_bound( getattr(self, "_processor", None) ), ) + num_tokens += image_tokens scheduler = getattr(getattr(self._engine, "engine", None), "scheduler", None) if scheduler is None: _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, + text_only=image_tokens == 0, ) async def preflight_completion( @@ -3913,7 +3919,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, + text_only=True, ) async def stream_chat( diff --git a/omlx/memory_monitor.py b/omlx/memory_monitor.py index 05490b3223..db6d9ceff8 100644 --- a/omlx/memory_monitor.py +++ b/omlx/memory_monitor.py @@ -249,8 +249,8 @@ def __init__( # Fixed per-sequence recurrent state (GDN/Mamba ArraysCache), # measured once from a live cache after the first prefill chunk. self._fixed_state_bytes: int = 0 - # When True, Qwen4 QSA prefill is priced as gathered (token budget) - # rather than dense Q x kv_len. Set only for text-only prefills. + # Fallback for estimate_chunk_transient_bytes when the caller omits + # gathered_core=. Scheduler paths pass the argument explicitly. self.qwen4_charge_gathered_core: bool = False # PagedCacheManager for KV cache memory measurement @@ -691,8 +691,11 @@ def estimate_resident_kv_bytes( if num_tokens <= 0: return 0 if self._prefill_memory_profile is not None: - return self._prefill_memory_profile.estimate_resident_kv_bytes( - num_tokens, chunk_tokens=chunk_tokens + return ( + self._prefill_memory_profile.estimate_resident_kv_bytes( + num_tokens, chunk_tokens=chunk_tokens + ) + + self._fixed_state_bytes ) total = self.estimate_prompt_kv_bytes(num_tokens) @@ -840,7 +843,19 @@ def estimate_prefill_peak_bytes( kv = self.estimate_resident_kv_bytes(new_tokens, chunk_tokens=eff_chunk) return attn + kv + self._ane_prefill_transient_bytes - def estimate_chunk_transient_bytes(self, n_tokens: int, kv_len: int) -> int: + def is_qwen4_gathered_prefill_profile(self) -> bool: + """True when this monitor prices Qwen4 QSA gathered-core prefill.""" + return isinstance( + self._prefill_memory_profile, _Qwen4ExpPrefillMemoryProfile + ) + + def estimate_chunk_transient_bytes( + self, + n_tokens: int, + kv_len: int, + *, + gathered_core: bool | None = None, + ) -> int: """Transient SDPA activation bytes for ONE prefill chunk. Isolates the per-chunk attention transient — the spike that drives @@ -855,14 +870,20 @@ def estimate_chunk_transient_bytes(self, n_tokens: int, kv_len: int) -> int: and scale with total ``kv_len``. Returns 0 when model info is unavailable. + + ``gathered_core`` prices Qwen4 QSA as a gathered core instead of + dense Q×kv_len. Scheduler paths pass it explicitly. When omitted, + ``qwen4_charge_gathered_core`` is the fallback for older tests. """ + if gathered_core is None: + gathered_core = bool(self.qwen4_charge_gathered_core) if self._prefill_memory_profile is not None: profile = self._prefill_memory_profile if isinstance(profile, _Qwen4ExpPrefillMemoryProfile): return profile.estimate_prefill_transient_bytes( n_tokens, kv_len, - gathered_core=self.qwen4_charge_gathered_core, + gathered_core=bool(gathered_core), ) return profile.estimate_prefill_transient_bytes(n_tokens, kv_len) return self._estimate_sdpa_activation_bytes(n_tokens, kv_len) 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 1d3730935d..b4f70ca047 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 @@ -1210,7 +1210,12 @@ def _gathered_text_decode_eligible( position_embeddings: Optional[tuple[mx.array, mx.array]], target_verify: bool, ) -> bool: - """Fail closed outside scalar-offset batch-one text decode.""" + """Fail closed outside scalar-offset batch-one text decode. + + Prefill may accept broadcast-identical 3-D text mRoPE. Decode keeps + the 2-D / absent predicate until that arm has its own numerical + parity coverage. + """ causal_mask = mask is None or (isinstance(mask, str) and mask == "causal") if not ( @@ -1221,7 +1226,13 @@ def _gathered_text_decode_eligible( and isinstance(cache.offset, int) and position_embeddings is None and not target_verify - and self._batch_one_text_position_ids(position_ids, 1) + and ( + position_ids is None + or ( + position_ids.ndim == 2 + and tuple(position_ids.shape) == (1, 1) + ) + ) ): return False diff --git a/omlx/prefill_transient_tracker.py b/omlx/prefill_transient_tracker.py index c745072428..fed3b0e3fb 100644 --- a/omlx/prefill_transient_tracker.py +++ b/omlx/prefill_transient_tracker.py @@ -61,6 +61,11 @@ def __init__(self, model_id: str = "") -> None: # need to allocate that pool again on the next chunk, so the scheduler # prices it once until a positive measurement confirms reallocation. self._recent_reclaim_bytes: int = 0 + # True if the last recorded chunk was priced as gathered QSA core. + # None means no tagged sample yet. Used so leftover *dense* history + # can be ignored on a gathered Qwen4 chunk without discarding a + # spike measured on this same gathered request. + self._last_sample_gathered: bool | None = None def record_reclaim(self, reclaimed_bytes: int) -> None: """Accumulate footprint released since the last positive sample.""" @@ -78,7 +83,12 @@ def clear_reclaim(self) -> None: self._recent_reclaim_bytes = 0 def update( - self, n_tokens: int, transient_bytes: int, *, floor_sample: bool = False + self, + n_tokens: int, + transient_bytes: int, + *, + floor_sample: bool = False, + gathered_core: bool | None = None, ) -> None: """Record one chunk observation. @@ -150,6 +160,8 @@ def update( self._samples += 1 self._last_delta_bytes = transient_bytes self._last_n_tokens = n_tokens + if gathered_core is not None: + self._last_sample_gathered = bool(gathered_core) def predict(self, n_tokens: int, *, safety_factor: float = 1.2) -> int: """Predicted transient bytes for a chunk of `n_tokens`. @@ -191,6 +203,11 @@ def recent_reclaim_bytes(self) -> int: """Footprint released since the last positive chunk measurement.""" return self._recent_reclaim_bytes + @property + def last_sample_gathered(self) -> bool | None: + """Whether the last tagged sample was a gathered QSA core charge.""" + return self._last_sample_gathered + def reset(self) -> None: """Drop all observations (e.g. on model reload or after a long idle).""" self._ewma_per_token = 0.0 @@ -199,3 +216,4 @@ def reset(self) -> None: self._last_n_tokens = 0 self._observed_max_bytes = 0 self._recent_reclaim_bytes = 0 + self._last_sample_gathered = None diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 556d7df3f7..c4b685f312 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -3399,19 +3399,18 @@ def _apply_turboquant_kv_convert(self, prompt_cache: list[Any]) -> None: f"cache layers to {bits}-bit{skip_msg}" ) - @contextmanager - def _qwen4_gathered_core_charge(self, enabled: bool): - """Price Qwen4 QSA core as gathered for text-only prefills only.""" - monitor = self.memory_monitor - if monitor is None: - yield - return - previous = bool(getattr(monitor, "qwen4_charge_gathered_core", False)) - monitor.qwen4_charge_gathered_core = bool(enabled) - try: - yield - finally: - monitor.qwen4_charge_gathered_core = previous + 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. + """ + if text_only is not True: + return False + monitor = getattr(self, "memory_monitor", None) + checker = getattr(monitor, "is_qwen4_gathered_prefill_profile", None) + return callable(checker) and checker() is True def _do_external_prefill( self, @@ -3420,10 +3419,9 @@ def _do_external_prefill( existing_cache: list[Any] | None, vlm_embeds: tuple[mx.array, dict[str, Any], int] | None = None, ) -> tuple[list[Any], list[int]]: - with self._qwen4_gathered_core_charge(vlm_embeds is None): - return self._do_external_prefill_impl( - request, tokens, existing_cache, vlm_embeds - ) + return self._do_external_prefill_impl( + request, tokens, existing_cache, vlm_embeds + ) def _do_external_prefill_impl( self, @@ -3454,6 +3452,7 @@ def _do_external_prefill_impl( RuntimeError: If memory limit exceeded during prefill. """ 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) @@ -3591,6 +3590,7 @@ def _do_external_prefill_impl( request_id=request.request_id, loop_label="external", kv_len=base_size + processed_tokens, + gathered_core=gathered_core, ) # Pre-chunk safety guard: NEVER submit a chunk whose predicted peak @@ -3605,6 +3605,7 @@ def _do_external_prefill_impl( progress=processed_tokens, loop_label="external", request_id=request.request_id, + gathered_core=gathered_core, ) if getattr(request, "benchmark_trace", False): request.benchmark_prefill_chunks.append(int(n_to_process)) @@ -3653,6 +3654,7 @@ def _do_external_prefill_impl( loop_label="external", kv_len=base_size + processed_tokens, requested_step=prefill_step_size, + gathered_core=gathered_core, ) self._maybe_record_fixed_state_bytes(prompt_cache) # Enforcer-requested hard-pressure drain. The flag's normal @@ -3877,7 +3879,24 @@ def _do_external_prefill_impl( _MEMORY_ADMISSION_STALL_TIMEOUT_S: float = 60.0 _STORE_CACHE_ADMISSION_STALL_TIMEOUT_S: float = 60.0 - def _predicted_chunk_transient(self, n_tokens: int, kv_len: int) -> float: + def _estimate_chunk_transient_bytes( + self, n_tokens: int, kv_len: int, *, gathered_core: bool + ) -> int: + """Call the monitor with an explicit gathered_core flag. + + Test doubles often still take ``(n_tokens, kv_len)`` only. + """ + estimate = self.memory_monitor.estimate_chunk_transient_bytes + try: + return int( + estimate(n_tokens, kv_len, gathered_core=gathered_core) + ) + except TypeError: + return int(estimate(n_tokens, kv_len)) + + def _predicted_chunk_transient( + self, n_tokens: int, kv_len: int, *, gathered_core: bool = False + ) -> float: """Conservative predicted Metal peak growth for one prefill chunk. The per-chunk SDPA/MoE transient scales with ``query_len * kv_len``, so @@ -3899,17 +3918,19 @@ def _predicted_chunk_transient(self, n_tokens: int, kv_len: int) -> float: recent_reclaim = 0 tracker = self._prefill_transient_tracker # Gathered QSA prices a ~2K core, not Q×kv_len. A leftover dense - # last_delta/EWMA would still refuse that cheap chunk. Only ignore - # history while that cheaper charge is active — other models must - # keep max(last_delta, EWMA, static) or a real dense spike undercharges. - # `is True` so a MagicMock monitor in tests cannot trip this gate. + # last_delta/EWMA would still refuse that cheap chunk. Ignore that + # leftover only when this chunk is priced gathered AND the last + # recorded sample was not itself gathered (a gathered spike on this + # request must still bind). `is True` so a MagicMock cannot trip it. + last_gathered = getattr( + self._prefill_transient_tracker, "last_sample_gathered", None + ) ignore_dense_history = ( - getattr(self.memory_monitor, "qwen4_charge_gathered_core", False) - is True + gathered_core is True and last_gathered is not True ) if self.memory_monitor is not None: - static = self.memory_monitor.estimate_chunk_transient_bytes( - n_tokens, kv_len + n_tokens + static = self._estimate_chunk_transient_bytes( + n_tokens, kv_len + n_tokens, gathered_core=gathered_core ) static += self.memory_monitor.estimate_prompt_kv_bytes(n_tokens) static_per_token = float(static) / n_tokens @@ -3942,7 +3963,9 @@ def _predicted_chunk_transient(self, n_tokens: int, kv_len: int) -> float: ) return max(base_prediction, reallocation_prediction) - def _admission_transient_bound(self, n_tokens: int, kv_len: int) -> float: + def _admission_transient_bound( + self, n_tokens: int, kv_len: int, *, gathered_core: bool = False + ) -> float: """Transient charge for admission and the guard's pass/abort gates. The largest FLOOR-SIZE chunk transient observed this session is a @@ -3962,7 +3985,9 @@ def _admission_transient_bound(self, n_tokens: int, kv_len: int) -> float: shrink arithmetic stay on ``_predicted_chunk_transient``; a flat size-invariant bound would zero out their proportional response. """ - bound = self._predicted_chunk_transient(n_tokens, kv_len) + bound = self._predicted_chunk_transient( + n_tokens, kv_len, gathered_core=gathered_core + ) tracker = self._prefill_transient_tracker if tracker is not None: bound = max(bound, float(tracker.observed_max_bytes)) @@ -4102,6 +4127,7 @@ def _guard_prefill_chunk( progress: int, loop_label: str, request_id: str | None = None, + gathered_core: bool = False, ) -> int: """Clamp/abort a prefill chunk so its predicted peak can never reach the physical Metal cap (the uncatchable async OOM crash). @@ -4124,12 +4150,16 @@ def _guard_prefill_chunk( else: min_chunk = max(1, self._prefill_min_chunk_tokens) current = self._current_usage_bytes() - if current + self._admission_transient_bound(n_tokens, kv_len) <= cap: + if current + self._admission_transient_bound( + n_tokens, kv_len, gathered_core=gathered_core + ) <= cap: return n_tokens # Predicted to breach — reclaim transients and re-measure once. current = self._reclaim_prefill_headroom() - min_transient = self._admission_transient_bound(min_chunk, kv_len) + min_transient = self._admission_transient_bound( + min_chunk, kv_len, gathered_core=gathered_core + ) if current + min_transient > cap: maybe_raise_eviction = getattr( self, "_raise_prefill_eviction_if_available", None @@ -4210,7 +4240,9 @@ def _guard_prefill_chunk( ) # The floor fits — pick the largest chunk that still fits under the cap. - per_token = self._predicted_chunk_transient(n_tokens, kv_len) / n_tokens + per_token = self._predicted_chunk_transient( + n_tokens, kv_len, gathered_core=gathered_core + ) / n_tokens safe_n = int((cap - current) / per_token) if per_token > 0 else n_tokens n_fit = max(min_chunk, min(n_tokens, safe_n)) # Same quantization as the adaptive throttle: an off-grid size here @@ -4265,6 +4297,7 @@ def _adaptive_chunk_size( request_id: str, loop_label: str, kv_len: int = 0, + gathered_core: bool = False, ) -> int: """Size the next prefill chunk so its predicted peak stays under a safety margin below the hard cap. @@ -4321,7 +4354,9 @@ def _adaptive_chunk_size( # safety) — see _predicted_chunk_transient. Anchored on the most recent # measurement so it tracks growth with kv_len instead of lagging behind # a long-run average. - per_token = self._predicted_chunk_transient(requested, kv_len) / requested + per_token = self._predicted_chunk_transient( + requested, kv_len, gathered_core=gathered_core + ) / requested predictor = "measured" if per_token > 0 else "none" # Keep each chunk's predicted peak under the LOWER of the dynamic @@ -4696,6 +4731,7 @@ def _record_chunk_transient( loop_label: str, kv_len: int = 0, requested_step: int | None = None, + gathered_core: bool = False, ) -> None: """Feed one chunk's measured transient into the EWMA tracker. @@ -4770,7 +4806,10 @@ def _record_chunk_transient( ) return self._prefill_transient_tracker.update( - n_tokens, delta, floor_sample=n_tokens <= min_chunk + n_tokens, + delta, + floor_sample=n_tokens <= min_chunk, + gathered_core=gathered_core, ) logger.debug( "[throttle:%s] measure rid=%s n=%d kv_len=%d transient=%.2fMB per_token=%.1fKB ewma=%.1fKB observed_max=%.1fMB samples=%d", @@ -5193,11 +5232,14 @@ def _step_prefill_chunk(self, state: _PrefillState) -> bool: # 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). + gathered_core = self._qwen4_text_gathered_pricing(True) n = self._adaptive_chunk_size( n, request_id=state.request.request_id, loop_label="chunked_step", kv_len=state.base_size + state.tokens_processed, + gathered_core=gathered_core, ) # Pre-chunk safety guard (mirrors the external loop): never submit a @@ -5208,6 +5250,7 @@ def _step_prefill_chunk(self, state: _PrefillState) -> bool: progress=state.tokens_processed, loop_label="chunked_step", request_id=state.request.request_id, + gathered_core=gathered_core, ) if getattr(state.request, "benchmark_trace", False): state.request.benchmark_prefill_chunks.append(int(n)) @@ -5237,6 +5280,7 @@ def _step_prefill_chunk(self, state: _PrefillState) -> bool: loop_label="chunked_step", kv_len=state.base_size + state.tokens_processed, requested_step=prefill_step_size, + gathered_core=gathered_core, ) self._maybe_record_fixed_state_bytes(state.cache) state.tokens_processed += n @@ -8367,6 +8411,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, + text_only=getattr(request, "vlm_inputs_embeds", None) is None, ) except Exception: self._release_paged_cache_for_request(request.request_id) @@ -9627,6 +9672,7 @@ 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 @@ -9685,6 +9731,7 @@ 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. @@ -9737,7 +9784,12 @@ def _admission_estimate( kv_exact = int( monitor.estimate_resident_kv_bytes(new_tokens, chunk_tokens=floor_chunk) ) - transient = int(self._admission_transient_bound(floor_chunk, kv_len)) + gathered_core = self._qwen4_text_gathered_pricing(text_only) + transient = int( + self._admission_transient_bound( + floor_chunk, kv_len, gathered_core=gathered_core + ) + ) if kv_exact <= 0 and transient <= 0: return None return _AdmissionEstimate( @@ -9796,6 +9848,7 @@ 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. @@ -9821,6 +9874,7 @@ 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 @@ -9881,6 +9935,7 @@ 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. @@ -9904,6 +9959,7 @@ 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 8e64081989..dc7e3244c8 100644 --- a/tests/test_context_benchmark.py +++ b/tests/test_context_benchmark.py @@ -162,7 +162,12 @@ def __init__(self, boundary=50000, guard=True): self._prefill_transient_tracker = MagicMock() def preflight_or_raise( - self, *, num_prompt_tokens, cached_tokens=0, request_id=None + self, + *, + 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 4909329c04..e612daa616 100644 --- a/tests/test_engine_preflight.py +++ b/tests/test_engine_preflight.py @@ -181,10 +181,12 @@ 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")] @@ -229,6 +231,7 @@ 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() diff --git a/tests/test_memory_monitor.py b/tests/test_memory_monitor.py index 12ed1acd79..02b16dc6dc 100644 --- a/tests/test_memory_monitor.py +++ b/tests/test_memory_monitor.py @@ -700,6 +700,40 @@ def test_fixed_state_added_and_reset_by_set_model_info(self): assert m.fixed_state_bytes == 0 assert m.estimate_resident_kv_bytes(100) == base + def test_fixed_state_added_on_qwen4_profile_path(self): + from omlx.memory_monitor import make_prefill_memory_profile + + config = SimpleNamespace( + model_type="qwen4_exp", + num_hidden_layers=48, + num_attention_heads=24, + num_key_value_heads=2, + head_dim=256, + indexer_n_heads=4, + indexer_head_dim=128, + indexer_budget=2048, + indexer_compress_ratio=4, + full_attention_interval=4, + layer_types=None, + ) + profile = make_prefill_memory_profile(config, compute_dtype_size=2) + m = MemoryMonitor(max_kv_cache_memory=2 * 1024**3) + m.set_model_info( + num_layers=48, + num_kv_heads=2, + head_dim=256, + dtype_size=2, + num_attention_heads=24, + compute_dtype_size=2, + prefill_memory_profile=profile, + ) + assert m.is_qwen4_gathered_prefill_profile() is True + base = m.estimate_resident_kv_bytes(100) + prompt_kv = m.estimate_prompt_kv_bytes(100) + m.set_fixed_state_bytes(123_456_789) + assert m.estimate_resident_kv_bytes(100) == base + 123_456_789 + assert m.estimate_prompt_kv_bytes(100) == prompt_kv + def test_zero_tokens_returns_zero(self): m = self._make(num_kv_cache_layers=30) m.set_fixed_state_bytes(999) diff --git a/tests/test_mlx_vlm_qwen4_exp_compat.py b/tests/test_mlx_vlm_qwen4_exp_compat.py index 92c64f97c9..03fd03fb03 100644 --- a/tests/test_mlx_vlm_qwen4_exp_compat.py +++ b/tests/test_mlx_vlm_qwen4_exp_compat.py @@ -716,6 +716,55 @@ def tracked(*args, **kwargs): assert actual.shape == hidden.shape +def test_qwen4_gathered_qsa_prefill_matches_official_broadcast_text_mrope( + monkeypatch, +): + """Equal-plane 3-D text mRoPE gathered prefill matches the official path.""" + config = _tiny_config() + import mlx_vlm.models.qwen4_exp.language as language + from mlx_vlm.models.qwen4_exp.language import QSAKVCache, Qwen4ExpAttention + + attention = Qwen4ExpAttention(config.text_config) + mx.eval(attention.parameters()) + hidden = mx.random.normal((1, 20, config.text_config.hidden_size)) + plane = mx.arange(20, dtype=mx.int32) + position_ids = mx.stack([plane, plane, plane])[:, None, :] + + calls = [] + gathered = language.contiguous_causal_gathered_qsa + + def tracked(*args, **kwargs): + calls.append((args[0].shape, args[1].shape)) + return gathered(*args, **kwargs) + + monkeypatch.setattr(language, "contiguous_causal_gathered_qsa", tracked) + fast_cache = QSAKVCache() + actual = attention( + hidden, + mask="causal", + cache=fast_cache, + position_ids=position_ids, + ) + + monkeypatch.setattr( + Qwen4ExpAttention, + "_gathered_text_prefill_eligible", + staticmethod(lambda *args, **kwargs: False), + ) + reference_cache = QSAKVCache() + expected = attention( + hidden, + mask="causal", + cache=reference_cache, + position_ids=position_ids, + ) + mx.eval(actual, expected) + + assert calls, "materialized equal-plane 3-D text must take gathered QSA" + assert mx.allclose(actual, expected, rtol=2e-5, atol=2e-5).item() + assert fast_cache.offset == reference_cache.offset == 20 + + def test_qwen4_gathered_qsa_fails_closed_for_batched_requests(monkeypatch): config = _tiny_config() import mlx_vlm.models.qwen4_exp.language as language diff --git a/tests/test_prefill_oom_graceful.py b/tests/test_prefill_oom_graceful.py index 3efb9dcc23..f3c6aaee99 100644 --- a/tests/test_prefill_oom_graceful.py +++ b/tests/test_prefill_oom_graceful.py @@ -134,6 +134,9 @@ def _throttle_ctx( ns._predicted_chunk_transient = Scheduler._predicted_chunk_transient.__get__( ns, Scheduler ) + ns._estimate_chunk_transient_bytes = ( + Scheduler._estimate_chunk_transient_bytes.__get__(ns, Scheduler) + ) ns._admission_transient_bound = Scheduler._admission_transient_bound.__get__( ns, Scheduler ) @@ -532,21 +535,61 @@ def test_predicted_transient_drops_dense_ewma_when_qsa_static_is_cheaper(): num_attention_heads=24, prefill_memory_profile=profile, ) - monitor.qwen4_charge_gathered_core = True tracker = PrefillTransientTracker() - tracker.update(4096, int(69.58 * _GB)) + tracker.update(4096, int(69.58 * _GB), gathered_core=False) ns = _throttle_ctx(current=0, hard=240 * _GB, samples_bpt=None, monitor=monitor) ns._prefill_transient_tracker = tracker - predicted = ns._predicted_chunk_transient(4096, 233_472) + predicted = ns._predicted_chunk_transient( + 4096, 233_472, gathered_core=True + ) dense_poison = 69.58 * _GB * Scheduler._PREFILL_TRANSIENT_SAFETY assert predicted < dense_poison / 8 assert 147 * _GB + predicted < 214 * _GB - # Without the gathered flag, that same leftover gulp must still bind. - monitor.qwen4_charge_gathered_core = False - dense_predicted = ns._predicted_chunk_transient(4096, 233_472) + # Without gathered pricing, that same leftover gulp must still bind. + dense_predicted = ns._predicted_chunk_transient( + 4096, 233_472, gathered_core=False + ) assert dense_predicted == pytest.approx(dense_poison, rel=1e-3) +def test_predicted_transient_keeps_gathered_spike_from_this_request(): + """A gathered chunk's own measured spike must still bind the next chunk.""" + from omlx.memory_monitor import make_prefill_memory_profile + + config = SimpleNamespace( + model_type="qwen4_exp", + num_hidden_layers=48, + num_attention_heads=24, + num_key_value_heads=2, + head_dim=256, + indexer_n_heads=4, + indexer_head_dim=128, + indexer_budget=2048, + indexer_compress_ratio=4, + full_attention_interval=4, + layer_types=None, + ) + profile = make_prefill_memory_profile(config, compute_dtype_size=2) + monitor = MemoryMonitor(max_kv_cache_memory=_GB, eviction_enabled=False) + monitor.set_model_info( + num_layers=48, + num_kv_heads=2, + head_dim=256, + dtype_size=2, + num_attention_heads=24, + prefill_memory_profile=profile, + ) + tracker = PrefillTransientTracker() + tracker.update(4096, int(69.58 * _GB), gathered_core=True) + ns = _throttle_ctx(current=0, hard=240 * _GB, samples_bpt=None, monitor=monitor) + ns._prefill_transient_tracker = tracker + dense_poison = 69.58 * _GB * Scheduler._PREFILL_TRANSIENT_SAFETY + predicted = ns._predicted_chunk_transient( + 4096, 233_472, gathered_core=True + ) + assert predicted == pytest.approx(dense_poison, rel=1e-3) + + def test_adaptive_throttle_charges_recently_reclaimed_footprint(): """A pool drop must remain priced until the next chunk reallocates it.""" static_prediction = 11.18 * _GB @@ -910,6 +953,9 @@ def test_step_prefill_reclaims_before_first_guard(): ): setattr(ns, _name, getattr(Scheduler, _name).__get__(ns, Scheduler)) ns._step_prefill_chunk = Scheduler._step_prefill_chunk.__get__(ns, Scheduler) + ns._qwen4_text_gathered_pricing = Scheduler._qwen4_text_gathered_pricing.__get__( + ns, Scheduler + ) with ( patch.object( @@ -933,6 +979,7 @@ def test_step_prefill_reclaims_before_first_guard(): loop_label="chunked_step", kv_len=0, requested_step=2, + gathered_core=False, ) diff --git a/tests/test_qwen4_qsa_decode_gather.py b/tests/test_qwen4_qsa_decode_gather.py index e9321509b7..34730b6cd7 100644 --- a/tests/test_qwen4_qsa_decode_gather.py +++ b/tests/test_qwen4_qsa_decode_gather.py @@ -238,8 +238,8 @@ def test_qwen4_decode_gather_eligibility_fails_closed_for_general_paths(): assert attention._gathered_text_decode_eligible( token, None, cache, mx.array([[10]], dtype=mx.int32), None, False ) - # Parent LM tiles identical text positions to (3, 1, 1). That is still text. - assert attention._gathered_text_decode_eligible( + # 3-D equal planes are a decode-follow-up. Prefill still accepts them. + assert not attention._gathered_text_decode_eligible( token, None, cache, diff --git a/tests/test_scheduler_prefill_memory_guard.py b/tests/test_scheduler_prefill_memory_guard.py index f5dd00fd8b..744b35fbf8 100644 --- a/tests/test_scheduler_prefill_memory_guard.py +++ b/tests/test_scheduler_prefill_memory_guard.py @@ -989,3 +989,134 @@ def test_admission_compares_against_hard_watermark(): scheduler._memory_hard_watermark_bytes = int(est.estimated) + 1 with patches[0], patches[1]: scheduler.preflight_or_raise(num_prompt_tokens=32768) + + +def _qwen4_prefill_profile(): + from omlx.memory_monitor import make_prefill_memory_profile + + return make_prefill_memory_profile( + SimpleNamespace( + model_type="qwen4_exp", + num_hidden_layers=48, + num_attention_heads=24, + num_key_value_heads=2, + head_dim=256, + indexer_n_heads=4, + indexer_head_dim=128, + indexer_budget=2048, + indexer_compress_ratio=4, + full_attention_interval=4, + layer_types=None, + ), + compute_dtype_size=2, + ) + + +def _attach_qwen4_profile(scheduler: Scheduler) -> None: + profile = _qwen4_prefill_profile() + scheduler.memory_monitor.set_model_info( + num_layers=48, + num_kv_heads=2, + head_dim=256, + dtype_size=2, + num_attention_heads=24, + compute_dtype_size=2, + prefill_memory_profile=profile, + ) + + +def test_qwen4_text_admission_uses_gathered_transient(): + scheduler = _make_scheduler() + _attach_qwen4_profile(scheduler) + 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( + num_prompt_tokens=233_472, + cached_tokens=0, + current=current, + text_only=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(): + 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( + 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 + 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) + assert ( + scheduler.preflight_eviction_request( + num_prompt_tokens=233_472, text_only=True + ) + 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(): + 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( + 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 + scheduler._memory_abort_limit_bytes = 10**18 + request = _make_request(233_472) + request.vlm_inputs_embeds = object() + with ( + patch("omlx.scheduler.mx.get_active_memory", return_value=current), + patch("omlx.scheduler.get_phys_footprint", return_value=current), + ): + rejection = scheduler._preflight_memory_check(request) + assert rejection is not None From 2246290a1000ef50317151868b20537dd7e0e4c2 Mon Sep 17 00:00:00 2001 From: astro-15-alive Date: Wed, 2 Sep 2026 18:25:18 +1000 Subject: [PATCH 062/132] fix(qwen4): handle mixed-rank QSA cache joins (#3369) Handle mixed text/MRoPE position ranks and normalize QSA indexer lengths during batch-cache joins. Co-authored-by: astro-15-alive <273241066+astro-15-alive@users.noreply.github.com> --- .../mlx_vlm/models/qwen4_exp/language.py | 75 ++++++++++-- tests/test_qsa_batch_join_ranks.py | 113 ++++++++++++++++++ 2 files changed, 176 insertions(+), 12 deletions(-) create mode 100644 tests/test_qsa_batch_join_ranks.py 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 a6e998d199..9b0e3c1a5c 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 @@ -575,6 +575,8 @@ def filter(self, batch_indices): @staticmethod def _pad_index(cache, target, sample_keys, sample_positions): length = 0 if cache.index_keys is None else cache.index_offset + if isinstance(length, mx.array): + length = int(length.item()) left = target - length if cache.index_keys is None: keys = mx.zeros( @@ -593,6 +595,16 @@ def _pad_index(cache, target, sample_keys, sample_positions): else: keys = cache.index_keys[:, :length] positions = cache.index_position_ids[..., :length] + # Widen 2-D text positions to the join's widest rank before + # padding (#3294 item 2): the runtime update path already + # broadcasts text up to MRoPE in _append_indexer_positions; joins + # must apply the same rule or the concatenate below sees ranks 2 + # and 3. Replicating across MRoPE channels matches runtime. + if sample_positions.ndim == 3 and positions.ndim == 2: + positions = mx.broadcast_to( + positions[None], + (sample_positions.shape[0], *positions.shape), + ) if left: keys = mx.pad(keys, [(0, 0), (left, 0), (0, 0)]) positions = mx.pad( @@ -612,12 +624,25 @@ def extend(self, other): sample_keys = ( self.index_keys if self.index_keys is not None else other.index_keys ) - sample_positions = ( - self.index_position_ids - if self.index_position_ids is not None - else other.index_position_ids - ) - if sample_keys is None: + # Prefer the WIDEST position rank over "first non-None" (#3294 item + # 2): promotion only widens, so a 2-D sample would strand a 3-D row + # with nothing to promote to, and position_axis would be picked from + # the wrong rank. Order-sensitive defect, so pick from both sides. + self_positions = self.index_position_ids + other_positions = other.index_position_ids + if ( + self_positions is not None + and other_positions is not None + and self_positions.ndim != other_positions.ndim + ): + sample_positions = ( + other_positions if self_positions.ndim == 2 else self_positions + ) + elif self_positions is not None: + sample_positions = self_positions + else: + sample_positions = other_positions + if sample_keys is None or sample_positions is None: return target = max(self.index_offset, other.index_offset) left = self._pad_index(self, target, sample_keys, sample_positions) @@ -660,23 +685,49 @@ def merge(cls, caches): sample = next((cache for cache in caches if cache.index_keys is not None), None) if sample is None: return out - target = max(cache.offset for cache in caches) + # Pick the widest position rank across every cache, not the first + # non-None sample (#3294 item 2): promotion only widens, so a 2-D + # first sample would strand a 3-D row at concatenate time. + widest_positions = sample.index_position_ids + for cache in caches: + pos = cache.index_position_ids + if pos is not None and pos.ndim > widest_positions.ndim: + widest_positions = pos + # Row length comes from the *indexer* state, not the KV offset + # (#3294 item 4). Singleton QSAKVCache.index_keys is a property + # already sliced to its valid length; BatchQSAKVCache keeps a raw + # capacity buffer, so its valid length is index_offset. The old code + # passed cache.offset — an int for singletons but an mx.array of + # per-row offsets for batch inputs, making max() and + # mx.array([cache.offset]) ill-defined — and conflated KV length + # with indexer length. The two coincide whenever the caches are + # consistent, so this is behaviour-preserving except where they + # diverge, which is exactly the mis-slice this fix removes. + def _valid_index_length(cache): + if cache.index_keys is None: + return 0 + if isinstance(cache, BatchQSAKVCache): + return int(cache.index_offset) + return int(cache.index_keys.shape[1]) + + lengths = [_valid_index_length(cache) for cache in caches] + target = max(lengths) rows = [ cls._pad_index( SimpleNamespace( index_keys=cache.index_keys, index_position_ids=cache.index_position_ids, - index_offset=cache.offset, - offset=mx.array([cache.offset]), + index_offset=length, + offset=mx.array([length]), ), target, sample.index_keys, - sample.index_position_ids, + widest_positions, ) - for cache in caches + for cache, length in zip(caches, lengths) ] out.index_keys = mx.concatenate([row[0] for row in rows], axis=0) - position_axis = 1 if sample.index_position_ids.ndim == 3 else 0 + position_axis = 1 if widest_positions.ndim == 3 else 0 out.index_position_ids = mx.concatenate( [row[1] for row in rows], axis=position_axis ) diff --git a/tests/test_qsa_batch_join_ranks.py b/tests/test_qsa_batch_join_ranks.py new file mode 100644 index 0000000000..b42d17a838 --- /dev/null +++ b/tests/test_qsa_batch_join_ranks.py @@ -0,0 +1,113 @@ +# SPDX-License-Identifier: Apache-2.0 +"""BatchQSAKVCache joins: mixed text/MRoPE ranks and KV-vs-indexer offsets. + +Re-verification of #3294 items 2 and 4 against current main, after #3219 +normalized the *reconstruct* path and the singleton trim fix landed. The +*runtime* join path in BatchQSAKVCache still carries both defects: + +Item 2 — ``extend`` picks ``sample_positions`` from whichever operand is +first non-None and derives ``position_axis`` from its rank. Joining a +text-only row (2-D ``[B, S]``) with an image row (3-D ``[3, B, S]``) either +raises on concatenate or joins on the wrong axis, depending on operand order. +The promotion rule already exists for the update path +(``_append_indexer_positions``) but never runs here. + +Item 4 — ``merge`` passes the KV ``offset`` to ``_pad_index`` as +``index_offset``, which uses it as the indexer length. Any divergence between +KV length and indexer length is silently clamped into a mis-sized join. For +``BatchQSAKVCache`` inputs ``cache.offset`` is an ``mx.array``, which makes +``mx.array([cache.offset])`` a 2-D shape inside ``_pad_index``. + +Tiny synthetic tensors, no model load. Needs real mlx. +""" + +import pytest + +mx = pytest.importorskip("mlx.core") + +from omlx.patches.mlx_vlm_qwen4_exp_compat import ( + apply_mlx_vlm_qwen4_exp_compat_patch, +) + +apply_mlx_vlm_qwen4_exp_compat_patch() + +from mlx_vlm.models.qwen4_exp.language import ( # noqa: E402 + BatchQSAKVCache, +) + +D = 4 + + +def _batch_text(length: int) -> BatchQSAKVCache: + """Batch cache whose indexer positions are 2-D text [B, S].""" + c = BatchQSAKVCache([0]) + c.index_keys = mx.zeros((1, length, D), dtype=mx.float32) + c.index_position_ids = mx.arange(length)[None, :] # [1, S] ndim 2 + c.index_offset = length + c.kv_cache.offset = mx.array([length]) + return c + + +def _batch_mrope(length: int) -> BatchQSAKVCache: + """Batch cache whose indexer positions are 3-D MRoPE [C, B, S].""" + c = BatchQSAKVCache([0]) + c.index_keys = mx.zeros((1, length, D), dtype=mx.float32) + pos = mx.arange(length)[None, None, :] # [1, 1, S] then widen channels + c.index_position_ids = mx.repeat(pos, 3, axis=0) # [3, 1, S] ndim 3 + c.index_offset = length + c.kv_cache.offset = mx.array([length]) + return c + + +class TestExtendMixedRanks: + """#3294 item 2 — text row joined with MRoPE row.""" + + def test_text_self_image_other(self): + b = _batch_text(4) + b.extend(_batch_mrope(4)) # must not raise + assert b.index_position_ids.ndim == 3 + + def test_image_self_text_other(self): + b = _batch_mrope(4) + b.extend(_batch_text(4)) # must not raise + assert b.index_position_ids.ndim == 3 + + def test_join_width_correct(self): + """Two rows of 4 tokens => index_keys [2, 4, D]; positions must + carry both rows, 8 columns total, at the widest rank.""" + b = _batch_text(4) + b.extend(_batch_mrope(4)) + assert b.index_keys.shape == (2, 4, D) + assert b.index_offset == 4 + # the widest rank in the join is MRoPE 3-D; the text row must be + # promoted to it, not concatenated on the wrong axis + assert b.index_position_ids.ndim == 3 + assert b.index_position_ids.shape == (3, 2, 4) + + +class TestMergeOffsetSemantics: + """#3294 item 4 — merge confuses KV offset with indexer length.""" + + def test_merge_singleton_offsets(self): + """A single text cache merges at its length.""" + c = _batch_text(4) + # simulate a batch-cache input (offset is an mx.array property) + out = BatchQSAKVCache.merge([c]) + assert int(out.index_offset) == 4 + assert out.index_keys.shape == (1, 4, D) + + def test_merge_divergent_indexer_length(self): + """KV offset 8 but indexer only holds 6: the join must pad the + indexer to the *indexer* length semantics without inventing two + phantom columns — i.e. either the join raises loudly or it pads + deliberately; it must not silently clamp into wrong tokens.""" + c = _batch_text(8) + c.index_keys = c.index_keys[:, :6] + c.index_offset = 6 + out = BatchQSAKVCache.merge([c]) + # correct behaviour: indexer row is 8 wide, padded with 2 zeros + # beyond index_offset (matching the KV it must describe), and + # index_offset tracks... whichever value merge documents; today it + # mixes the two. Assert self-consistency instead of one magic number: + assert out.index_keys.shape[1] >= 6 + assert out.index_position_ids.shape[-1] == out.index_keys.shape[1] From e68058758c2506324329d3ae95d620b9fa35a3b8 Mon Sep 17 00:00:00 2001 From: jundot Date: Wed, 2 Sep 2026 17:42:43 +0900 Subject: [PATCH 063/132] fix(qwen4): harden QSA batch cache joins (#3294) --- .../mlx_vlm/models/qwen4_exp/language.py | 139 ++++++++++++------ tests/test_qsa_batch_join_ranks.py | 133 ++++++++++++----- 2 files changed, 189 insertions(+), 83 deletions(-) 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 9b0e3c1a5c..ad752ba471 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 @@ -9,7 +9,6 @@ from bisect import bisect_right from dataclasses import dataclass, replace from pathlib import Path -from types import SimpleNamespace from typing import Any, Optional import mlx.core as mx @@ -574,23 +573,35 @@ def filter(self, batch_indices): @staticmethod def _pad_index(cache, target, sample_keys, sample_positions): - length = 0 if cache.index_keys is None else cache.index_offset + length = ( + 0 + if cache.index_keys is None + else getattr(cache, "index_offset", cache.index_keys.shape[1]) + ) if isinstance(length, mx.array): + if length.size != 1: + raise ValueError( + "QSA index length must be scalar after row normalization" + ) length = int(length.item()) + else: + length = int(length) left = target - length if cache.index_keys is None: + offset = cache.offset + batch_size = offset.shape[0] if isinstance(offset, mx.array) else 1 keys = mx.zeros( - (cache.offset.shape[0], 0, sample_keys.shape[-1]), + (batch_size, 0, sample_keys.shape[-1]), dtype=sample_keys.dtype, ) if sample_positions.ndim == 3: positions = mx.zeros( - (sample_positions.shape[0], cache.offset.shape[0], 0), + (sample_positions.shape[0], batch_size, 0), dtype=sample_positions.dtype, ) else: positions = mx.zeros( - (cache.offset.shape[0], 0), dtype=sample_positions.dtype + (batch_size, 0), dtype=sample_positions.dtype ) else: keys = cache.index_keys[:, :length] @@ -620,7 +631,19 @@ def _pad_index(cache, target, sample_keys, sample_positions): def extend(self, other): if not isinstance(other, BatchQSAKVCache): raise TypeError(f"Cannot extend BatchQSAKVCache with {type(other)}") - self.kv_cache.extend(other.kv_cache) + + for cache in (self, other): + if (cache.index_keys is None) != (cache.index_position_ids is None): + raise ValueError("QSA raw keys and positions must be extended together") + if cache.index_keys is None: + if cache.kv_cache.size(): + raise ValueError("Cannot extend QSA KV state without indexer state") + elif cache.index_offset != cache.kv_cache.size(): + raise ValueError( + "QSA extend requires aligned KV and indexer widths, got " + f"kv={cache.kv_cache.size()} and indexer={cache.index_offset}" + ) + sample_keys = ( self.index_keys if self.index_keys is not None else other.index_keys ) @@ -643,15 +666,20 @@ def extend(self, other): else: sample_positions = other_positions if sample_keys is None or sample_positions is None: + self.kv_cache.extend(other.kv_cache) return target = max(self.index_offset, other.index_offset) left = self._pad_index(self, target, sample_keys, sample_positions) right = self._pad_index(other, target, sample_keys, sample_positions) - self.index_keys = mx.concatenate([left[0], right[0]], axis=0) + index_keys = mx.concatenate([left[0], right[0]], axis=0) position_axis = 1 if sample_positions.ndim == 3 else 0 - self.index_position_ids = mx.concatenate( + index_position_ids = mx.concatenate( [left[1], right[1]], axis=position_axis ) + + self.kv_cache.extend(other.kv_cache) + self.index_keys = index_keys + self.index_position_ids = index_position_ids self.index_offset = target def extract(self, idx): @@ -677,59 +705,82 @@ def extract(self, idx): @classmethod def merge(cls, caches): - caches = list(caches) - out = cls([0] * len(caches)) - if not caches: + rows = [] + for cache in caches: + if isinstance(cache, cls): + batch_size = int(cache.offset.shape[0]) + if cache.kv_cache.keys is None: + if cache.index_keys is not None: + raise ValueError( + "Cannot merge a QSA batch with indexer state but no KV state" + ) + rows.extend(QSAKVCache() for _ in range(batch_size)) + else: + rows.extend(cache.extract(idx) for idx in range(batch_size)) + elif isinstance(cache, QSAKVCache): + rows.append(cache) + else: + raise TypeError(f"Cannot merge QSA cache with {type(cache)}") + + out = cls([0] * len(rows)) + if not rows: return out - out.kv_cache = BatchKVCache.merge(caches) - sample = next((cache for cache in caches if cache.index_keys is not None), None) + + lengths = [] + for row in rows: + kv_length = int(row.offset) + if row.keys is None: + if kv_length: + raise ValueError("QSA cache has a non-zero offset without KV state") + elif kv_length > row.keys.shape[2]: + raise ValueError("QSA cache offset exceeds its KV storage") + + if (row.index_keys is None) != (row.index_position_ids is None): + raise ValueError("QSA raw keys and positions must be merged together") + index_length = 0 if row.index_keys is None else row.index_keys.shape[1] + if row.index_position_ids is not None and ( + row.index_position_ids.ndim not in {2, 3} + or row.index_position_ids.shape[-1] != index_length + ): + raise ValueError("QSA raw keys and positions are misaligned") + if index_length != kv_length: + raise ValueError( + "QSA merge requires aligned KV and indexer lengths, got " + f"kv={kv_length} and indexer={index_length}" + ) + lengths.append(index_length) + + out.kv_cache = BatchKVCache.merge(rows) + sample = next((row for row in rows if row.index_keys is not None), None) if sample is None: return out # Pick the widest position rank across every cache, not the first # non-None sample (#3294 item 2): promotion only widens, so a 2-D # first sample would strand a 3-D row at concatenate time. widest_positions = sample.index_position_ids - for cache in caches: - pos = cache.index_position_ids + for row in rows: + pos = row.index_position_ids if pos is not None and pos.ndim > widest_positions.ndim: widest_positions = pos - # Row length comes from the *indexer* state, not the KV offset - # (#3294 item 4). Singleton QSAKVCache.index_keys is a property - # already sliced to its valid length; BatchQSAKVCache keeps a raw - # capacity buffer, so its valid length is index_offset. The old code - # passed cache.offset — an int for singletons but an mx.array of - # per-row offsets for batch inputs, making max() and - # mx.array([cache.offset]) ill-defined — and conflated KV length - # with indexer length. The two coincide whenever the caches are - # consistent, so this is behaviour-preserving except where they - # diverge, which is exactly the mis-slice this fix removes. - def _valid_index_length(cache): - if cache.index_keys is None: - return 0 - if isinstance(cache, BatchQSAKVCache): - return int(cache.index_offset) - return int(cache.index_keys.shape[1]) - - lengths = [_valid_index_length(cache) for cache in caches] - target = max(lengths) - rows = [ + target = out.kv_cache.size() + if target != max(lengths): + raise ValueError( + "QSA merge produced different KV and indexer widths, got " + f"kv={target} and indexer={max(lengths)}" + ) + padded_rows = [ cls._pad_index( - SimpleNamespace( - index_keys=cache.index_keys, - index_position_ids=cache.index_position_ids, - index_offset=length, - offset=mx.array([length]), - ), + row, target, sample.index_keys, widest_positions, ) - for cache, length in zip(caches, lengths) + for row in rows ] - out.index_keys = mx.concatenate([row[0] for row in rows], axis=0) + out.index_keys = mx.concatenate([row[0] for row in padded_rows], axis=0) position_axis = 1 if widest_positions.ndim == 3 else 0 out.index_position_ids = mx.concatenate( - [row[1] for row in rows], axis=position_axis + [row[1] for row in padded_rows], axis=position_axis ) out.index_offset = target return out diff --git a/tests/test_qsa_batch_join_ranks.py b/tests/test_qsa_batch_join_ranks.py index b42d17a838..365fd4a29c 100644 --- a/tests/test_qsa_batch_join_ranks.py +++ b/tests/test_qsa_batch_join_ranks.py @@ -14,18 +14,18 @@ Item 4 — ``merge`` passes the KV ``offset`` to ``_pad_index`` as ``index_offset``, which uses it as the indexer length. Any divergence between -KV length and indexer length is silently clamped into a mis-sized join. For -``BatchQSAKVCache`` inputs ``cache.offset`` is an ``mx.array``, which makes -``mx.array([cache.offset])`` a 2-D shape inside ``_pad_index``. +KV length and indexer length is silently clamped into a mis-sized join. Batch +inputs also need to be expanded into singleton rows before ``BatchKVCache`` +can merge their underlying KV state. -Tiny synthetic tensors, no model load. Needs real mlx. +Small warmed caches with real KV and indexer tensors, no model load. Needs MLX. """ import pytest mx = pytest.importorskip("mlx.core") -from omlx.patches.mlx_vlm_qwen4_exp_compat import ( +from omlx.patches.mlx_vlm_qwen4_exp_compat import ( # noqa: E402 apply_mlx_vlm_qwen4_exp_compat_patch, ) @@ -33,30 +33,36 @@ from mlx_vlm.models.qwen4_exp.language import ( # noqa: E402 BatchQSAKVCache, + QSAKVCache, ) D = 4 -def _batch_text(length: int) -> BatchQSAKVCache: - """Batch cache whose indexer positions are 2-D text [B, S].""" - c = BatchQSAKVCache([0]) - c.index_keys = mx.zeros((1, length, D), dtype=mx.float32) - c.index_position_ids = mx.arange(length)[None, :] # [1, S] ndim 2 - c.index_offset = length - c.kv_cache.offset = mx.array([length]) - return c +def _singleton(length: int, *, mrope: bool, start: int = 0) -> QSAKVCache: + values = mx.arange(start, start + 2 * length * D, dtype=mx.float32).reshape( + 1, 2, length, D + ) + index_keys = mx.arange(start, start + length * D, dtype=mx.float32).reshape( + 1, length, D + ) + positions = mx.arange(start, start + length, dtype=mx.int32)[None] + if mrope: + positions = mx.repeat(positions[None], 3, axis=0) + cache = QSAKVCache() + cache.state = (values, values + 1000, index_keys, positions) + return cache -def _batch_mrope(length: int) -> BatchQSAKVCache: - """Batch cache whose indexer positions are 3-D MRoPE [C, B, S].""" - c = BatchQSAKVCache([0]) - c.index_keys = mx.zeros((1, length, D), dtype=mx.float32) - pos = mx.arange(length)[None, None, :] # [1, 1, S] then widen channels - c.index_position_ids = mx.repeat(pos, 3, axis=0) # [3, 1, S] ndim 3 - c.index_offset = length - c.kv_cache.offset = mx.array([length]) - return c + +def _batch_text(length: int, start: int = 0) -> BatchQSAKVCache: + """Warm batch cache whose indexer positions are 2-D text [B, S].""" + return _singleton(length, mrope=False, start=start).to_batch([0]) + + +def _batch_mrope(length: int, start: int = 0) -> BatchQSAKVCache: + """Warm batch cache whose positions are 3-D MRoPE [C, B, S].""" + return _singleton(length, mrope=True, start=start).to_batch([0]) class TestExtendMixedRanks: @@ -84,30 +90,79 @@ def test_join_width_correct(self): assert b.index_position_ids.ndim == 3 assert b.index_position_ids.shape == (3, 2, 4) + def test_empty_left_batch_keeps_kv_and_indexer_row_counts_equal(self): + """KV extension must not change the empty indexer's source row count.""" + batch = BatchQSAKVCache([0]) + + batch.extend(_batch_text(4)) + + mx.eval(batch.offset, batch.left_padding, batch.index_keys) + assert batch.offset.tolist() == [0, 4] + assert batch.left_padding.tolist() == [4, 0] + assert batch.index_keys.shape == (2, 4, D) + assert batch.index_position_ids.shape == (2, 4) + assert [batch.extract(idx).offset for idx in range(2)] == [0, 4] + + def test_extend_rejects_divergent_indexer_width(self): + """A partial indexer cannot safely describe the full KV columns.""" + left = _batch_text(8) + left.index_keys = left.index_keys[:, :6] + left.index_position_ids = left.index_position_ids[..., :6] + left.index_offset = 6 + + with pytest.raises(ValueError, match="requires aligned KV and indexer widths"): + left.extend(_batch_text(4)) + class TestMergeOffsetSemantics: """#3294 item 4 — merge confuses KV offset with indexer length.""" def test_merge_singleton_offsets(self): """A single text cache merges at its length.""" - c = _batch_text(4) - # simulate a batch-cache input (offset is an mx.array property) + c = _singleton(4, mrope=False) out = BatchQSAKVCache.merge([c]) + mx.eval(out.offset, out.index_keys) + assert out.offset.tolist() == [4] + assert out.kv_cache.size() == 4 assert int(out.index_offset) == 4 assert out.index_keys.shape == (1, 4, D) - def test_merge_divergent_indexer_length(self): - """KV offset 8 but indexer only holds 6: the join must pad the - indexer to the *indexer* length semantics without inventing two - phantom columns — i.e. either the join raises loudly or it pads - deliberately; it must not silently clamp into wrong tokens.""" - c = _batch_text(8) - c.index_keys = c.index_keys[:, :6] - c.index_offset = 6 - out = BatchQSAKVCache.merge([c]) - # correct behaviour: indexer row is 8 wide, padded with 2 zeros - # beyond index_offset (matching the KV it must describe), and - # index_offset tracks... whichever value merge documents; today it - # mixes the two. Assert self-consistency instead of one magic number: - assert out.index_keys.shape[1] >= 6 - assert out.index_position_ids.shape[-1] == out.index_keys.shape[1] + def test_merge_warm_batch_inputs(self): + """Existing batches are flattened to rows before their KV is merged.""" + originals = [ + _singleton(4, mrope=False, start=10), + _singleton(2, mrope=False, start=30), + _singleton(3, mrope=True, start=50), + ] + left = BatchQSAKVCache.merge(originals[:2]) + right = BatchQSAKVCache.merge(originals[2:]) + + out = BatchQSAKVCache.merge([left, right]) + + mx.eval(out.offset, out.left_padding, out.index_keys, out.index_position_ids) + assert out.offset.tolist() == [4, 2, 3] + assert out.left_padding.tolist() == [0, 2, 1] + assert out.kv_cache.size() == 4 + assert out.index_offset == 4 + assert out.index_keys.shape == (3, 4, D) + assert out.index_position_ids.shape == (3, 3, 4) + for idx, original in enumerate(originals): + extracted = out.extract(idx) + assert extracted.offset == original.offset + assert mx.array_equal(extracted.index_keys, original.index_keys).item() + + @pytest.mark.parametrize("batched", [False, True], ids=["singleton", "batch"]) + def test_merge_rejects_divergent_indexer_length(self, batched): + """Missing indexer columns cannot be reconstructed from the KV cache.""" + cache = _singleton(8, mrope=False) + if batched: + cache = cache.to_batch([0]) + cache.index_keys = cache.index_keys[:, :6] + cache.index_position_ids = cache.index_position_ids[..., :6] + cache.index_offset = 6 + else: + cache.index_keys = cache.index_keys[:, :6] + cache.index_position_ids = cache.index_position_ids[..., :6] + + with pytest.raises(ValueError, match="requires aligned KV and indexer lengths"): + BatchQSAKVCache.merge([cache]) From ffb5072e51e6751c88ca28166820a9f85fe3f306 Mon Sep 17 00:00:00 2001 From: Jonathan Spangler Date: Wed, 2 Sep 2026 02:08:55 -0700 Subject: [PATCH 064/132] fix(qwen4): preserve gathered prefill across mRoPE rebinds (#3355) Preserve canonical rank-two positions for scheduler-proven Qwen4 text prefills while keeping media and multi-row mRoPE binds fail-closed. --- omlx/models/vlm.py | 57 ++++++++++++++- omlx/scheduler.py | 40 ++++++++++ tests/test_mlx_vlm_qwen4_exp_compat.py | 96 ++++++++++++++++++++++++ tests/test_scheduler.py | 35 +++++++++ tests/test_scheduler_chunked_prefill.py | 97 +++++++++++++++++++++++++ tests/test_vlm_model_adapter.py | 96 ++++++++++++++++++++++++ 6 files changed, 418 insertions(+), 3 deletions(-) diff --git a/omlx/models/vlm.py b/omlx/models/vlm.py index 5b08f7f874..516e5faa16 100644 --- a/omlx/models/vlm.py +++ b/omlx/models/vlm.py @@ -67,6 +67,14 @@ def __init__(self, vlm_model: nn.Module): # from this dict + current batch UIDs before each step. self._uid_rope_deltas: Dict[int, float] = {} self._batch_rope_deltas: Optional[mx.array] = None + # External/chunked text prefill owns a stronger position-shape proof + # than the generic decode binder: the scheduler has already excluded + # media embeddings and is advancing one request's scalar cache. Qwen4 + # uses that proof to keep its position ids rank two, which is exactly + # equivalent to three broadcast-identical mRoPE planes and preserves + # the qualified gathered-QSA path. Generic/media/batched binds reset + # the proof and retain the ordinary rank-three fail-closed path. + self._qwen4_text_prefill_positions = False def release_resources(self) -> None: """Drop references to VLM-owned MLX arrays before engine teardown reclaim.""" @@ -77,6 +85,7 @@ def release_resources(self) -> None: self._pending_kwargs = {} self._uid_rope_deltas.clear() self._batch_rope_deltas = None + self._qwen4_text_prefill_positions = False self._language_model = None self._vlm_model = None @@ -253,6 +262,7 @@ def clear_vlm_position_state(self) -> None: self._language_model._position_ids = None self._language_model._rope_deltas = None self._batch_rope_deltas = None + self._qwen4_text_prefill_positions = False def register_rope_delta(self, uid: int, delta: float) -> None: """Register rope_delta for a UID after VLM prefill.""" @@ -269,6 +279,18 @@ def set_batch_rope_deltas(self, deltas: mx.array) -> None: an array of rope_deltas aligned to the batch slot order. """ self._batch_rope_deltas = deltas + self._qwen4_text_prefill_positions = False + + def set_text_prefill_rope_delta(self, delta: float) -> None: + """Bind one scheduler-proven text row for an imminent prefill call. + + This seam is intentionally separate from ``set_batch_rope_deltas``. + Only the scheduler's external/chunked non-media prefill paths may call + it. A later generic decode, media, or batched bind clears the proof. + """ + + self._batch_rope_deltas = mx.array([delta]) + self._qwen4_text_prefill_positions = True def _batch_rope_deltas_for_size(self, batch_size: int) -> Optional[mx.array]: """Return rope deltas aligned to the current model input batch size.""" @@ -300,7 +322,12 @@ def _batch_rope_deltas_for_size(self, batch_size: int) -> Optional[mx.array]: return mx.concatenate([deltas, pad], axis=0) def _position_ids_from_starts( - self, starts: mx.array, batch_size: int, seq_len: int + self, + starts: mx.array, + batch_size: int, + seq_len: int, + *, + qwen4_text_prefill_positions: bool = False, ) -> mx.array: """Build model-specific decode position_ids from per-row start offsets. @@ -319,6 +346,18 @@ def _position_ids_from_starts( seq_positions = starts[:, None] + steps[None, :] if self._uses_minimax_m3_positions: return seq_positions + if ( + self.model_type == "qwen4_exp" + and qwen4_text_prefill_positions + and batch_size == 1 + ): + # Qwen4's gathered-QSA qualification accepts canonical B1 text + # positions as (1, T), never general multimodal (3, B, T) mRoPE. + # The generic form constructed below is a broadcast of this exact + # row across all three planes, so avoiding that broadcast changes + # neither rotary values nor logits; it only preserves the proven + # text-only fast-path contract. + return seq_positions return mx.broadcast_to(seq_positions[None, :, :], (3, batch_size, seq_len)) def get_last_rope_deltas(self) -> float: @@ -366,6 +405,12 @@ def __call__( Returns: Model output (logits as mx.array) """ + # Consume the scheduler proof before doing any work. A failed/cancelled + # call therefore cannot leave a text-only capability armed for a later + # media or generic request. Each external prefill chunk explicitly + # re-arms it at its own model-call boundary. + qwen4_text_prefill_positions = self._qwen4_text_prefill_positions + self._qwen4_text_prefill_positions = False return_hidden = bool(kwargs.get("return_hidden", False)) if skip_lm_head: # Scheduler prefill chunks discard their logits. Translate the @@ -408,7 +453,10 @@ def __call__( if base_offsets is not None and deltas is not None: positions = base_offsets + deltas.astype(base_offsets.dtype) position_ids = self._position_ids_from_starts( - positions, batch_size, seq_len + positions, + batch_size, + seq_len, + qwen4_text_prefill_positions=(qwen4_text_prefill_positions), ) result = self._language_model( input_ids, cache=cache, position_ids=position_ids, **kwargs @@ -428,7 +476,10 @@ def __call__( if offsets is not None: batch_size, seq_len = input_ids.shape position_ids = self._position_ids_from_starts( - offsets, batch_size, seq_len + offsets, + batch_size, + seq_len, + qwen4_text_prefill_positions=(qwen4_text_prefill_positions), ) result = self._language_model( input_ids, cache=cache, position_ids=position_ids, **kwargs diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 3a9f9ec68b..cb8fb1595c 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -1398,6 +1398,24 @@ def _seed_text_only_mrope_delta_for_cached_prefill(model: Any, request: Any) -> mx.eval(lm._rope_deltas) +def _bind_text_prefill_rope_delta(model: Any, delta: float) -> None: + """Rebind one non-media prefill row without widening Qwen4 positions. + + ``VLMModelAdapter`` exposes a dedicated seam that records the scheduler's + text-only proof. Other model wrappers retain the original generic mRoPE + binder. Looking up the dedicated method on the class avoids treating an + auto-created ``MagicMock`` instance attribute as a production capability. + """ + + text_setter = getattr(type(model), "set_text_prefill_rope_delta", None) + if callable(text_setter): + text_setter(model, delta) + return + generic_setter = getattr(model, "set_batch_rope_deltas", None) + if callable(generic_setter): + generic_setter(mx.array([delta])) + + def _vlm_extra_seq_slice(val: mx.array, s: slice) -> mx.array: """Slice a VLM extra tensor along its seq dimension. @@ -3598,6 +3616,18 @@ def _do_external_prefill( _trace_model_start = time.perf_counter() with mx.stream(self._stream): model_kwargs: dict[str, Any] = {} + if embeds_array is None: + # External text prefill is interleaved chunk-by-chunk with + # active decode. A finishing VLM row clears the adapter's + # process-local position state, and a decode step may leave + # a differently shaped batch delta behind. Rebind this + # request immediately before every forward so neither + # event can make a singleton Qwen mRoPE chunk restart at + # local position zero inside an absolute QSA timeline. + _bind_text_prefill_rope_delta( + self.model, + getattr(request, "rope_deltas", 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: @@ -5174,6 +5204,16 @@ def _step_prefill_chunk(self, state: _PrefillState) -> bool: with mx.stream(self._stream): chunk = state.tokens_remaining[:, :n] state.tokens_remaining = state.tokens_remaining[:, n:] + # A chunked text prefill can yield to active decode between + # forwards. Completion cleanup or the intervening decode batch may + # replace the VLM adapter's process-local mRoPE state. Rebind this + # request at the model-call boundary so the next scalar-cache chunk + # continues from its absolute cache offset instead of restarting at + # local position zero. + _bind_text_prefill_rope_delta( + self.model, + getattr(state.request, "rope_deltas", 0.0), + ) if self._supports_skip_lm_head(): self.model(chunk, cache=state.cache, skip_lm_head=True) else: diff --git a/tests/test_mlx_vlm_qwen4_exp_compat.py b/tests/test_mlx_vlm_qwen4_exp_compat.py index 18c34623aa..fefb0e244e 100644 --- a/tests/test_mlx_vlm_qwen4_exp_compat.py +++ b/tests/test_mlx_vlm_qwen4_exp_compat.py @@ -653,6 +653,102 @@ def tracked(*args, **kwargs): ).item() +def test_qwen4_rank_two_text_positions_match_identical_mrope_plane_logits( + monkeypatch, +): + """Canonical text positions preserve exact values and unlock gathered QSA.""" + config = _tiny_config() + import mlx_vlm.models.qwen4_exp.language as language + from mlx_vlm.models.qwen4_exp.language import QSAKVCache, Qwen4ExpAttention + + mx.random.seed(831) + attention = Qwen4ExpAttention(config.text_config) + projection = mx.random.normal((config.text_config.hidden_size, 17)) + hidden = mx.random.normal((1, 20, config.text_config.hidden_size)) + text_positions = mx.arange(20, dtype=mx.int32)[None] + identical_mrope = mx.broadcast_to(text_positions[None], (3, 1, 20)) + mx.eval(attention.parameters(), projection, hidden) + + assert attention._gathered_text_prefill_eligible( + hidden, + "causal", + QSAKVCache(), + text_positions, + None, + False, + ) + assert not attention._gathered_text_prefill_eligible( + hidden, + "causal", + QSAKVCache(), + identical_mrope, + None, + False, + ) + + gathered_calls = [] + original_gathered = language.contiguous_causal_gathered_qsa + + def tracked_gathered(*args, **kwargs): + gathered_calls.append(True) + return original_gathered(*args, **kwargs) + + monkeypatch.setattr( + language, + "contiguous_causal_gathered_qsa", + tracked_gathered, + ) + fast_cache = QSAKVCache() + reference_cache = QSAKVCache() + actual = attention( + hidden, + mask="causal", + cache=fast_cache, + position_ids=text_positions, + ) + expected = attention( + hidden, + mask="causal", + cache=reference_cache, + position_ids=identical_mrope, + ) + actual_logits = actual @ projection + expected_logits = expected @ projection + mx.eval(actual_logits, expected_logits) + + assert gathered_calls == [True] + assert mx.allclose(actual, expected, rtol=2e-5, atol=2e-5).item() + assert mx.allclose( + actual_logits, + expected_logits, + rtol=2e-5, + atol=2e-5, + ).item() + assert mx.array_equal( + mx.argmax(actual_logits, axis=-1), + mx.argmax(expected_logits, axis=-1), + ).item() + assert fast_cache.offset == reference_cache.offset == 20 + fast_keys, fast_values, fast_index_keys, _ = fast_cache.state + reference_keys, reference_values, reference_index_keys, _ = reference_cache.state + for fast_value, reference_value in ( + (fast_keys, reference_keys), + (fast_values, reference_values), + ): + assert mx.allclose( + fast_value, + reference_value, + rtol=2e-5, + atol=2e-5, + ).item() + assert mx.allclose( + fast_index_keys, + reference_index_keys, + rtol=2e-5, + atol=2e-5, + ).item() + + def test_qwen4_gathered_qsa_fails_closed_for_multimodal_positions(monkeypatch): config = _tiny_config() import mlx_vlm.models.qwen4_exp.language as language diff --git a/tests/test_scheduler.py b/tests/test_scheduler.py index d7eb738eff..84b4679557 100644 --- a/tests/test_scheduler.py +++ b/tests/test_scheduler.py @@ -5849,10 +5849,12 @@ def _make_vlm_model(self): "clear_vlm_position_state", "parameters", "make_cache", + "set_batch_rope_deltas", ] ) model.clear_vlm_position_state = MagicMock() model.make_cache.return_value = [] + model.set_batch_rope_deltas = MagicMock() return model def test_schedule_waiting_preserves_vlm_position_state(self, mock_tokenizer): @@ -5944,6 +5946,39 @@ def test_schedule_waiting_clears_text_only_position_state(self, mock_tokenizer): model.clear_vlm_position_state.assert_called_once() + def test_external_text_prefill_rebinds_mrope_before_every_chunk( + self, mock_tokenizer + ): + """Concurrent decode or cleanup cannot leak adapter position state.""" + model = self._make_vlm_model() + scheduler = Scheduler( + model=model, + tokenizer=mock_tokenizer, + config=SchedulerConfig(prefill_step_size=512), + ) + request = Request( + request_id="text-mrope-chunks", + prompt="chunked", + sampling_params=SamplingParams(max_tokens=1), + ) + request.prompt_token_ids = list(range(1025)) + request.num_prompt_tokens = len(request.prompt_token_ids) + request.rope_deltas = 7.0 + + scheduler._do_external_prefill( + request, + tokens=request.prompt_token_ids, + existing_cache=[], + vlm_embeds=None, + ) + + assert model.call_count == 2 + assert model.set_batch_rope_deltas.call_count == 2 + for mock_call in model.set_batch_rope_deltas.call_args_list: + delta = mock_call.args[0] + assert delta.shape == (1,) + assert delta.item() == 7.0 + def test_cached_text_only_prefill_seeds_zero_mrope_delta(self, mock_tokenizer): """Cached text-only mRoPE suffixes must start at the restored offset.""" model = self._make_vlm_model() diff --git a/tests/test_scheduler_chunked_prefill.py b/tests/test_scheduler_chunked_prefill.py index 4300e52b3c..c331505071 100644 --- a/tests/test_scheduler_chunked_prefill.py +++ b/tests/test_scheduler_chunked_prefill.py @@ -237,6 +237,103 @@ def test_still_true_with_waiting_only(self): assert sched.has_requests() +# --------------------------------------------------------------------------- +# Chunk-local mRoPE ownership +# --------------------------------------------------------------------------- + + +class TestChunkedPrefillMRoPE: + def test_text_prefill_rebinds_delta_after_interleaved_cleanup(self): + class MRoPERecordingModel(_RecordingModel): + _uses_mrope = True + + def __init__(self): + super().__init__("vlm") + self.batch_deltas = None + self.delta_history = [] + + def set_text_prefill_rope_delta(self, delta): + self.batch_deltas = mx.array([delta]) + self.delta_history.append([delta]) + + def set_batch_rope_deltas(self, deltas): + raise AssertionError("text prefill must use the bounded binder") + + def __call__(self, tokens, cache=None): + assert self.batch_deltas is not None + super().__call__(tokens, cache=cache) + + model = MRoPERecordingModel() + tokenizer = MagicMock() + tokenizer.eos_token_id = 2 + scheduler = Scheduler( + model=model, + tokenizer=tokenizer, + config=SchedulerConfig( + prefill_step_size=4, + chunked_prefill=True, + paged_cache_block_size=0, + ), + ) + request = _make_request("mrope-interleaved", n_tokens=9) + request.rope_deltas = 7.0 + state = _make_prefill_state(scheduler, request, n_remaining=8) + + with patch("omlx.scheduler._sync_and_clear_cache"): + assert not scheduler._step_prefill_chunk(state) + # Reproduce a concurrent request's completion cleanup. + model.batch_deltas = None + assert scheduler._step_prefill_chunk(state) + + assert model.chunk_lengths == [4, 4] + assert model.delta_history == [[7.0], [7.0]] + + def test_mock_request_without_rope_delta_uses_text_default(self): + """Legacy/minimal request doubles retain the canonical text delta.""" + + class MRoPERecordingModel(_RecordingModel): + _uses_mrope = True + + def __init__(self): + super().__init__("vlm") + self.delta_history = [] + + def set_text_prefill_rope_delta(self, delta): + self.delta_history.append([delta]) + + model = MRoPERecordingModel() + tokenizer = MagicMock() + tokenizer.eos_token_id = 2 + scheduler = Scheduler( + model=model, + tokenizer=tokenizer, + config=SchedulerConfig( + prefill_step_size=4, + chunked_prefill=True, + paged_cache_block_size=0, + ), + ) + request = SimpleNamespace(request_id="mock-without-rope-delta") + state = _PrefillState( + request=request, + cache=[], + tokens_remaining=mx.zeros((1, 4), dtype=mx.int32), + last_token=[99], + tokens_processed=0, + base_size=0, + emitted_boundaries={}, + boundary_enabled=False, + block_size=0, + total_length=5, + ) + + with patch("omlx.scheduler._sync_and_clear_cache"): + assert scheduler._step_prefill_chunk(state) + + assert model.chunk_lengths == [4] + assert model.delta_history == [[0.0]] + + # --------------------------------------------------------------------------- # get_stats includes num_prefilling # --------------------------------------------------------------------------- diff --git a/tests/test_vlm_model_adapter.py b/tests/test_vlm_model_adapter.py index 40c892b458..7a06faf173 100644 --- a/tests/test_vlm_model_adapter.py +++ b/tests/test_vlm_model_adapter.py @@ -392,6 +392,13 @@ def _make_minimax_m3_vlm_model(self): vlm.config.text_config.rope_parameters = None return vlm + def _make_qwen4_mrope_vlm_model(self): + """Create the exact root/text model types shipped by Flash Next.""" + vlm = self._make_mrope_vlm_model() + vlm.config.model_type = "qwen4_exp" + vlm.config.text_config.model_type = "qwen4_exp_text" + return vlm + def test_mrope_decode_uses_language_model_with_position_ids(self): """mRoPE decode with batch_rope_deltas should use language_model with position_ids.""" import mlx.core as mx @@ -485,6 +492,95 @@ def test_mrope_decode_scalar_cache_offset_uses_position_ids(self): assert pos_ids.shape == (3, 1, 1) assert pos_ids[0, 0, 0].item() == 16384.0 + def test_qwen4_b1_text_prefill_uses_canonical_rank_two_positions(self): + """Three broadcast-identical text planes stay in QSA's proven shape.""" + import mlx.core as mx + + from omlx.models.vlm import VLMModelAdapter + + vlm = self._make_qwen4_mrope_vlm_model() + adapter = VLMModelAdapter(vlm) + assert adapter.model_type == "qwen4_exp" + + adapter.set_text_prefill_rope_delta(0.0) + cache_layer = MagicMock() + cache_layer.offset = 16384 + adapter(mx.zeros((1, 4), dtype=mx.int32), cache=[cache_layer]) + + position_ids = vlm.language_model.call_args.kwargs["position_ids"] + assert position_ids.shape == (1, 4) + assert position_ids.tolist() == [[16384, 16385, 16386, 16387]] + + def test_qwen4_text_prefill_proof_is_one_shot_after_failed_call(self): + """An exception cannot leak the text-only proof into the next call.""" + import mlx.core as mx + import pytest + + from omlx.models.vlm import VLMModelAdapter + + vlm = self._make_qwen4_mrope_vlm_model() + adapter = VLMModelAdapter(vlm) + cache_layer = MagicMock() + cache_layer.offset = 64 + vlm.language_model.side_effect = [RuntimeError("cancelled"), MagicMock()] + + adapter.set_text_prefill_rope_delta(0.0) + with pytest.raises(RuntimeError, match="cancelled"): + adapter(mx.zeros((1, 2), dtype=mx.int32), cache=[cache_layer]) + + # No rebind at all: the old delta array is still present, but the + # stronger text-only capability must have been consumed by the failed + # call and therefore cannot affect this later generic request. + adapter(mx.zeros((1, 2), dtype=mx.int32), cache=[cache_layer]) + position_ids = vlm.language_model.call_args.kwargs["position_ids"] + assert position_ids.shape == (3, 1, 2) + + def test_qwen4_text_prefill_b2_remains_rank_three(self): + """The text proof is not widened to an unqualified batched QSA path.""" + import mlx.core as mx + + from omlx.models.vlm import VLMModelAdapter + + vlm = self._make_qwen4_mrope_vlm_model() + adapter = VLMModelAdapter(vlm) + adapter.set_text_prefill_rope_delta(0.0) + # A synthetic second delta demonstrates that the adapter refuses to + # reinterpret the one-row proof when the model call is batched. + adapter._batch_rope_deltas = mx.array([0.0, 0.0]) + cache_layer = MagicMock() + cache_layer.offset = mx.array([128, 96]) + adapter(mx.zeros((2, 2), dtype=mx.int32), cache=[cache_layer]) + + position_ids = vlm.language_model.call_args.kwargs["position_ids"] + assert position_ids.shape == (3, 2, 2) + + def test_qwen4_media_positions_remain_divergent_rank_three(self): + """True mRoPE media planes bypass text canonicalization unchanged.""" + import mlx.core as mx + + from omlx.models.vlm import VLMModelAdapter + + vlm = self._make_qwen4_mrope_vlm_model() + adapter = VLMModelAdapter(vlm) + divergent = mx.array( + [ + [[10, 11, 12]], + [[10, 10, 11]], + [[7, 8, 8]], + ], + dtype=mx.int32, + ) + adapter( + mx.zeros((1, 3), dtype=mx.int32), + cache=[MagicMock()], + inputs_embeds=mx.zeros((1, 3, 8)), + vlm_extra_kwargs={"position_ids": divergent}, + ) + + position_ids = vlm.language_model.call_args.kwargs["position_ids"] + assert position_ids.shape == (3, 1, 3) + assert mx.array_equal(position_ids, divergent).item() + def test_non_minimax_mrope_mismatched_delta_size_keeps_existing_path(self): """Non-MiniMax mRoPE models keep prior no-position_ids mismatch behavior.""" import mlx.core as mx From ba45eaa7c0035f899f58e8b74f705619018dd327 Mon Sep 17 00:00:00 2001 From: jundot Date: Wed, 2 Sep 2026 18:18:12 +0900 Subject: [PATCH 065/132] fix(qwen4): isolate gathered prefill memory history (#3350) --- omlx/prefill_transient_tracker.py | 113 ++++++++++++++------ omlx/scheduler.py | 54 ++++------ tests/test_mlx_vlm_qwen4_exp_compat.py | 131 +----------------------- tests/test_prefill_oom_graceful.py | 12 +++ tests/test_prefill_transient_tracker.py | 39 +++++++ tests/test_qwen4_qsa_decode_gather.py | 42 -------- 6 files changed, 155 insertions(+), 236 deletions(-) diff --git a/omlx/prefill_transient_tracker.py b/omlx/prefill_transient_tracker.py index fed3b0e3fb..f84f0a385c 100644 --- a/omlx/prefill_transient_tracker.py +++ b/omlx/prefill_transient_tracker.py @@ -61,11 +61,29 @@ def __init__(self, model_id: str = "") -> None: # need to allocate that pool again on the next chunk, so the scheduler # prices it once until a positive measurement confirms reallocation. self._recent_reclaim_bytes: int = 0 - # True if the last recorded chunk was priced as gathered QSA core. - # None means no tagged sample yet. Used so leftover *dense* history - # can be ignored on a gathered Qwen4 chunk without discarding a - # spike measured on this same gathered request. - self._last_sample_gathered: bool | None = None + # Qwen4 gathered QSA and ordinary dense prefill have fundamentally + # different cost curves. Keep an independent history for gathered + # chunks so switching execution regimes cannot make a cheap gathered + # chunk inherit a dense EWMA, last sample, or floor maximum. The + # unprefixed fields above remain the default/dense history so existing + # callers and diagnostics retain their original behavior. + self._gathered_ewma_per_token: float = 0.0 + self._gathered_samples: int = 0 + self._gathered_last_delta_bytes: int = 0 + self._gathered_last_n_tokens: int = 0 + self._gathered_observed_max_bytes: int = 0 + + @staticmethod + def _history_prefix(gathered_core: bool | None) -> str: + return "_gathered_" if gathered_core is True else "_" + + def _history_value(self, name: str, gathered_core: bool | None) -> int | float: + return getattr(self, f"{self._history_prefix(gathered_core)}{name}") + + def _set_history_value( + self, name: str, value: int | float, gathered_core: bool | None + ) -> None: + setattr(self, f"{self._history_prefix(gathered_core)}{name}", value) def record_reclaim(self, reclaimed_bytes: int) -> None: """Accumulate footprint released since the last positive sample.""" @@ -118,13 +136,19 @@ def update( self._recent_reclaim_bytes = 0 - # The very first sample after a model load carries weight page-fault - # and load-residue noise, so it seeds the EWMA but is excluded from - # the running max. - if floor_sample and self._samples > 0: + samples = int(self._history_value("samples", gathered_core)) + ewma_per_token = float(self._history_value("ewma_per_token", gathered_core)) + observed_max_bytes = int( + self._history_value("observed_max_bytes", gathered_core) + ) + + # The very first sample in each execution regime carries weight + # page-fault and load-residue noise, so it seeds that regime's EWMA + # but is excluded from its running max. + if floor_sample and samples > 0: if transient_bytes <= self._OBSERVED_MAX_CLAMP_BYTES: - if transient_bytes > self._observed_max_bytes: - self._observed_max_bytes = transient_bytes + if transient_bytes > observed_max_bytes: + observed_max_bytes = transient_bytes else: logger.debug( "PrefillTransientTracker(%s): rejected %d-byte outlier " @@ -135,9 +159,9 @@ def update( ) per_token = transient_bytes / n_tokens - if self._samples == 0: - self._ewma_per_token = per_token - elif per_token > self._ewma_per_token * self._EWMA_OUTLIER_RATIO: + if samples == 0: + ewma_per_token = per_token + elif per_token > ewma_per_token * self._EWMA_OUTLIER_RATIO: # Reject from the EWMA blend: a single sample this far above # the running rate is more likely a noisy phys_footprint() # delta (see _record_chunk_transient's docstring on @@ -149,29 +173,55 @@ def update( "outlier from EWMA (current %.1f, ratio limit %.1fx)", self._model_id, per_token, - self._ewma_per_token, + ewma_per_token, self._EWMA_OUTLIER_RATIO, ) else: - self._ewma_per_token = ( - self._EWMA_ALPHA * per_token - + (1.0 - self._EWMA_ALPHA) * self._ewma_per_token + ewma_per_token = ( + self._EWMA_ALPHA * per_token + (1.0 - self._EWMA_ALPHA) * ewma_per_token ) - self._samples += 1 - self._last_delta_bytes = transient_bytes - self._last_n_tokens = n_tokens - if gathered_core is not None: - self._last_sample_gathered = bool(gathered_core) + self._set_history_value("ewma_per_token", ewma_per_token, gathered_core) + self._set_history_value("samples", samples + 1, gathered_core) + self._set_history_value("last_delta_bytes", transient_bytes, gathered_core) + self._set_history_value("last_n_tokens", n_tokens, gathered_core) + self._set_history_value("observed_max_bytes", observed_max_bytes, gathered_core) - def predict(self, n_tokens: int, *, safety_factor: float = 1.2) -> int: + def predict( + self, + n_tokens: int, + *, + safety_factor: float = 1.2, + gathered_core: bool = False, + ) -> int: """Predicted transient bytes for a chunk of `n_tokens`. Returns 0 when no samples have been observed yet — caller must fall back to a static estimator in that case. """ - if self._samples == 0 or n_tokens <= 0: + samples = self.samples_for(gathered_core) + if samples == 0 or n_tokens <= 0: return 0 - return int(self._ewma_per_token * n_tokens * safety_factor) + return int(self.bytes_per_token_for(gathered_core) * n_tokens * safety_factor) + + def bytes_per_token_for(self, gathered_core: bool) -> float: + """Return the EWMA for the selected execution regime.""" + return float(self._history_value("ewma_per_token", gathered_core)) + + def samples_for(self, gathered_core: bool) -> int: + """Return the sample count for the selected execution regime.""" + return int(self._history_value("samples", gathered_core)) + + def last_delta_bytes_for(self, gathered_core: bool) -> int: + """Return the latest measured delta for the selected regime.""" + return int(self._history_value("last_delta_bytes", gathered_core)) + + def last_n_tokens_for(self, gathered_core: bool) -> int: + """Return the latest measured width for the selected regime.""" + return int(self._history_value("last_n_tokens", gathered_core)) + + def observed_max_bytes_for(self, gathered_core: bool) -> int: + """Return the floor-size maximum for the selected regime.""" + return int(self._history_value("observed_max_bytes", gathered_core)) @property def bytes_per_token(self) -> float: @@ -203,11 +253,6 @@ def recent_reclaim_bytes(self) -> int: """Footprint released since the last positive chunk measurement.""" return self._recent_reclaim_bytes - @property - def last_sample_gathered(self) -> bool | None: - """Whether the last tagged sample was a gathered QSA core charge.""" - return self._last_sample_gathered - def reset(self) -> None: """Drop all observations (e.g. on model reload or after a long idle).""" self._ewma_per_token = 0.0 @@ -216,4 +261,8 @@ def reset(self) -> None: self._last_n_tokens = 0 self._observed_max_bytes = 0 self._recent_reclaim_bytes = 0 - self._last_sample_gathered = None + self._gathered_ewma_per_token = 0.0 + self._gathered_samples = 0 + self._gathered_last_delta_bytes = 0 + self._gathered_last_n_tokens = 0 + self._gathered_observed_max_bytes = 0 diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 2cebf9dc45..3b7dd32109 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -3947,17 +3947,6 @@ def _predicted_chunk_transient( static_per_token = 0.0 recent_reclaim = 0 tracker = self._prefill_transient_tracker - # Gathered QSA prices a ~2K core, not Q×kv_len. A leftover dense - # last_delta/EWMA would still refuse that cheap chunk. Ignore that - # leftover only when this chunk is priced gathered AND the last - # recorded sample was not itself gathered (a gathered spike on this - # request must still bind). `is True` so a MagicMock cannot trip it. - last_gathered = getattr( - self._prefill_transient_tracker, "last_sample_gathered", None - ) - ignore_dense_history = ( - gathered_core is True and last_gathered is not True - ) if self.memory_monitor is not None: static = self._estimate_chunk_transient_bytes( n_tokens, kv_len + n_tokens, gathered_core=gathered_core @@ -3966,24 +3955,18 @@ def _predicted_chunk_transient( static_per_token = float(static) / n_tokens per_token = static_per_token if tracker is not None: - ewma = float(tracker.bytes_per_token) + # Dense SDPA and gathered QSA have different cost curves. The + # tracker keeps their measured histories separate, so switching + # paths cannot reintroduce a stale dense charge after the first + # gathered sample. + ewma = tracker.bytes_per_token_for(gathered_core) recent_reclaim = tracker.recent_reclaim_bytes - outlier_ratio = PrefillTransientTracker._EWMA_OUTLIER_RATIO - dense_history_is_stale = ( - ignore_dense_history - and static_per_token > 0 - and ewma > static_per_token * outlier_ratio - ) - if ewma > 0 and not dense_history_is_stale: + if ewma > 0: per_token = max(per_token, ewma) - if tracker.last_n_tokens > 0 and tracker.last_delta_bytes > 0: - measured = tracker.last_delta_bytes / tracker.last_n_tokens - if ( - ignore_dense_history - and static_per_token > 0 - and measured > static_per_token * outlier_ratio - ): - measured = 0.0 + last_n_tokens = tracker.last_n_tokens_for(gathered_core) + last_delta_bytes = tracker.last_delta_bytes_for(gathered_core) + if last_n_tokens > 0 and last_delta_bytes > 0: + measured = last_delta_bytes / last_n_tokens if measured > 0: per_token = max(per_token, measured) base_prediction = per_token * n_tokens * self._PREFILL_TRANSIENT_SAFETY @@ -4020,7 +4003,10 @@ def _admission_transient_bound( ) tracker = self._prefill_transient_tracker if tracker is not None: - bound = max(bound, float(tracker.observed_max_bytes)) + bound = max( + bound, + float(tracker.observed_max_bytes_for(gathered_core)), + ) return bound def _prefill_abort_cap(self) -> int: @@ -4223,7 +4209,9 @@ def _guard_prefill_chunk( # is diagnosable from one log line instead of re-deriving it. tracker = self._prefill_transient_tracker observed_max = ( - float(tracker.observed_max_bytes) if tracker is not None else 0.0 + float(tracker.observed_max_bytes_for(gathered_core)) + if tracker is not None + else 0.0 ) ane_reservation = ( float(getattr(self.memory_monitor, "_ane_prefill_transient_bytes", 0)) @@ -4849,9 +4837,11 @@ def _record_chunk_transient( kv_len, delta / 1024**2, (delta / max(n_tokens, 1)) / 1024, - self._prefill_transient_tracker.bytes_per_token / 1024, - self._prefill_transient_tracker.observed_max_bytes / 1024**2, - self._prefill_transient_tracker.samples, + self._prefill_transient_tracker.bytes_per_token_for(gathered_core) + / 1024, + self._prefill_transient_tracker.observed_max_bytes_for(gathered_core) + / 1024**2, + self._prefill_transient_tracker.samples_for(gathered_core), ) def _supports_skip_lm_head(self) -> bool: diff --git a/tests/test_mlx_vlm_qwen4_exp_compat.py b/tests/test_mlx_vlm_qwen4_exp_compat.py index 69e3521b34..fefb0e244e 100644 --- a/tests/test_mlx_vlm_qwen4_exp_compat.py +++ b/tests/test_mlx_vlm_qwen4_exp_compat.py @@ -780,88 +780,7 @@ def must_not_run(*args, **kwargs): assert output.shape == hidden.shape -def test_qwen4_gathered_qsa_routes_broadcast_text_mrope(monkeypatch): - """Parent LM tiles identical text positions to (3,1,L). That is still text.""" - config = _tiny_config() - import mlx_vlm.models.qwen4_exp.language as language - from mlx_vlm.models.qwen4_exp.language import QSAKVCache, Qwen4ExpAttention - - attention = Qwen4ExpAttention(config.text_config) - mx.eval(attention.parameters()) - hidden = mx.random.normal((1, 20, config.text_config.hidden_size)) - text_ids = mx.arange(20, dtype=mx.int32)[None] - position_ids = mx.broadcast_to(text_ids[None], (3, 1, 20)) - - calls = [] - gathered = language.contiguous_causal_gathered_qsa - - def tracked(*args, **kwargs): - calls.append((args[0].shape, args[1].shape)) - return gathered(*args, **kwargs) - - monkeypatch.setattr(language, "contiguous_causal_gathered_qsa", tracked) - actual = attention( - hidden, - mask="causal", - cache=QSAKVCache(), - position_ids=position_ids, - ) - mx.eval(actual) - - assert calls, "broadcast text mRoPE must take gathered QSA, not mask+dense SDPA" - assert actual.shape == hidden.shape - - -def test_qwen4_gathered_qsa_prefill_matches_official_broadcast_text_mrope( - monkeypatch, -): - """Equal-plane 3-D text mRoPE gathered prefill matches the official path.""" - config = _tiny_config() - import mlx_vlm.models.qwen4_exp.language as language - from mlx_vlm.models.qwen4_exp.language import QSAKVCache, Qwen4ExpAttention - - attention = Qwen4ExpAttention(config.text_config) - mx.eval(attention.parameters()) - hidden = mx.random.normal((1, 20, config.text_config.hidden_size)) - plane = mx.arange(20, dtype=mx.int32) - position_ids = mx.stack([plane, plane, plane])[:, None, :] - - calls = [] - gathered = language.contiguous_causal_gathered_qsa - - def tracked(*args, **kwargs): - calls.append((args[0].shape, args[1].shape)) - return gathered(*args, **kwargs) - - monkeypatch.setattr(language, "contiguous_causal_gathered_qsa", tracked) - fast_cache = QSAKVCache() - actual = attention( - hidden, - mask="causal", - cache=fast_cache, - position_ids=position_ids, - ) - - monkeypatch.setattr( - Qwen4ExpAttention, - "_gathered_text_prefill_eligible", - staticmethod(lambda *args, **kwargs: False), - ) - reference_cache = QSAKVCache() - expected = attention( - hidden, - mask="causal", - cache=reference_cache, - position_ids=position_ids, - ) - mx.eval(actual, expected) - - assert calls, "materialized equal-plane 3-D text must take gathered QSA" - assert mx.allclose(actual, expected, rtol=2e-5, atol=2e-5).item() - assert fast_cache.offset == reference_cache.offset == 20 - - -def test_qwen4_gathered_qsa_fails_closed_for_batched_requests(monkeypatch): +def test_qwen4_gathered_qsa_fails_closed_for_batched_prefill(monkeypatch): config = _tiny_config() import mlx_vlm.models.qwen4_exp.language as language from mlx_vlm.models.qwen4_exp.language import QSAKVCache, Qwen4ExpAttention @@ -1549,54 +1468,6 @@ def test_qwen4_batch_qsa_trim_slices_indexer_arrays(): assert batch.index_offset == 5 assert batch.index_keys.shape[1] == 5 assert batch.index_position_ids.shape[-1] == 5 - - -def test_qwen4_batch_extend_unifies_2d_and_3d_indexer_positions(): - """MTP late-join mixed gathered 2-D text positions with mask_dense 3-D mRoPE. - - That used to raise ``[concatenate] ... dimensions 3 and 2`` at - ``BatchQSAKVCache.extend``. - """ - compat.apply_mlx_vlm_qwen4_exp_compat_patch() - from mlx_vlm.models.qwen4_exp.language import BatchQSAKVCache - - left = _warm_qsa_row(4, 0) - right = _warm_qsa_row(2, 40) - right.index_position_ids = mx.broadcast_to( - right.index_position_ids[None], - (3, *right.index_position_ids.shape), - ) - left_batch = left.to_batch([0]) - right_batch = right.to_batch([0]) - - left_batch.extend(right_batch) - mx.eval(left_batch.index_position_ids, left_batch.index_keys) - - assert left_batch.index_position_ids.ndim == 3 - assert left_batch.index_position_ids.shape[0] == 3 - assert left_batch.index_keys.shape[0] == 2 - extracted_right = left_batch.extract(1) - assert extracted_right.index_position_ids.ndim == 3 - assert extracted_right.index_position_ids.shape[-1] == 2 - - -def test_qwen4_batch_merge_unifies_mixed_indexer_position_ranks(): - compat.apply_mlx_vlm_qwen4_exp_compat_patch() - from mlx_vlm.models.qwen4_exp.language import BatchQSAKVCache - - text = _warm_qsa_row(3, 10) - mrope = _warm_qsa_row(1, 30) - mrope.index_position_ids = mx.broadcast_to( - mrope.index_position_ids[None], - (3, *mrope.index_position_ids.shape), - ) - merged = BatchQSAKVCache.merge([text, mrope]) - mx.eval(merged.index_position_ids) - assert merged.index_position_ids.ndim == 3 - assert merged.index_position_ids.shape[0] == 3 - assert merged.offset.tolist() == [3, 1] - - def _make_bound_qwen4_language_model(config): from mlx_vlm.models.qwen4_exp.language import LanguageModel, Qwen4ExpMTPModule diff --git a/tests/test_prefill_oom_graceful.py b/tests/test_prefill_oom_graceful.py index f3c6aaee99..c2befe276f 100644 --- a/tests/test_prefill_oom_graceful.py +++ b/tests/test_prefill_oom_graceful.py @@ -545,6 +545,18 @@ def test_predicted_transient_drops_dense_ewma_when_qsa_static_is_cheaper(): dense_poison = 69.58 * _GB * Scheduler._PREFILL_TRANSIENT_SAFETY assert predicted < dense_poison / 8 assert 147 * _GB + predicted < 214 * _GB + # Recording the first gathered observation must not make the next + # gathered chunk inherit the dense EWMA. Before the histories were split, + # this second prediction jumped from ~5.47 GiB to ~64.96 GiB. + tracker.update( + 4096, + int(predicted / Scheduler._PREFILL_TRANSIENT_SAFETY), + gathered_core=True, + ) + next_predicted = ns._predicted_chunk_transient( + 4096, 233_472, gathered_core=True + ) + assert next_predicted == pytest.approx(predicted, rel=1e-6) # Without gathered pricing, that same leftover gulp must still bind. dense_predicted = ns._predicted_chunk_transient( 4096, 233_472, gathered_core=False diff --git a/tests/test_prefill_transient_tracker.py b/tests/test_prefill_transient_tracker.py index c5ece7c01d..1b356b462a 100644 --- a/tests/test_prefill_transient_tracker.py +++ b/tests/test_prefill_transient_tracker.py @@ -179,6 +179,7 @@ class TestReset: def test_reset_clears_all(self): t = PrefillTransientTracker("m") t.update(1000, 100_000) + t.update(1000, 20_000, gathered_core=True) t.update(2000, 300_000) t.reset() assert t.samples == 0 @@ -187,3 +188,41 @@ def test_reset_clears_all(self): assert t.last_delta_bytes == 0 assert t.predict(2048) == 0 assert t.observed_max_bytes == 0 + assert t.samples_for(True) == 0 + assert t.bytes_per_token_for(True) == 0.0 + assert t.last_n_tokens_for(True) == 0 + assert t.last_delta_bytes_for(True) == 0 + assert t.predict(2048, gathered_core=True) == 0 + assert t.observed_max_bytes_for(True) == 0 + + +class TestExecutionRegimes: + def test_dense_and_gathered_rates_are_independent(self): + t = PrefillTransientTracker("m") + t.update(4096, 64 * 1024**3, gathered_core=False) + + assert t.samples == 1 + assert t.samples_for(True) == 0 + assert t.bytes_per_token_for(True) == 0.0 + assert t.last_delta_bytes_for(True) == 0 + + t.update(4096, 4 * 1024**3, gathered_core=True) + + assert t.samples == 1 + assert t.samples_for(True) == 1 + assert t.bytes_per_token == 16 * 1024**2 + assert t.bytes_per_token_for(True) == 1024**2 + assert t.last_delta_bytes == 64 * 1024**3 + assert t.last_delta_bytes_for(True) == 4 * 1024**3 + assert t.predict(4096, safety_factor=1.0) == 64 * 1024**3 + assert t.predict(4096, safety_factor=1.0, gathered_core=True) == 4 * 1024**3 + + def test_dense_floor_max_does_not_bind_gathered_admission(self): + t = PrefillTransientTracker("m") + t.update(32, 100 * 1024**2, floor_sample=True) + t.update(32, 900 * 1024**2, floor_sample=True) + t.update(32, 20 * 1024**2, floor_sample=True, gathered_core=True) + t.update(32, 40 * 1024**2, floor_sample=True, gathered_core=True) + + assert t.observed_max_bytes == 900 * 1024**2 + assert t.observed_max_bytes_for(True) == 40 * 1024**2 diff --git a/tests/test_qwen4_qsa_decode_gather.py b/tests/test_qwen4_qsa_decode_gather.py index 34730b6cd7..2b65845ff2 100644 --- a/tests/test_qwen4_qsa_decode_gather.py +++ b/tests/test_qwen4_qsa_decode_gather.py @@ -238,7 +238,6 @@ def test_qwen4_decode_gather_eligibility_fails_closed_for_general_paths(): assert attention._gathered_text_decode_eligible( token, None, cache, mx.array([[10]], dtype=mx.int32), None, False ) - # 3-D equal planes are a decode-follow-up. Prefill still accepts them. assert not attention._gathered_text_decode_eligible( token, None, @@ -247,14 +246,6 @@ def test_qwen4_decode_gather_eligibility_fails_closed_for_general_paths(): None, False, ) - assert not attention._gathered_text_decode_eligible( - token, - None, - cache, - mx.array([[[10]], [[10]], [[9]]], dtype=mx.int32), - None, - False, - ) assert not attention._gathered_text_decode_eligible( token, None, cache, None, None, True ) @@ -274,26 +265,6 @@ def test_qwen4_decode_gather_eligibility_fails_closed_for_general_paths(): ) -def test_qwen4_text_mrope_equal_plane_cache_does_not_reuse_dead_ids(): - """CPython can recycle id() once a temporary mx.array is collected.""" - - compat.apply_mlx_vlm_qwen4_exp_compat_patch() - import mlx_vlm.models.qwen4_exp.language as language - - equal = mx.array([[[10]], [[10]], [[10]]], dtype=mx.int32) - unequal = mx.array([[[10]], [[10]], [[9]]], dtype=mx.int32) - assert language._broadcast_text_mrope_position_ids(equal, 1) - assert not language._broadcast_text_mrope_position_ids(unequal, 1) - - for _ in range(64): - assert language._broadcast_text_mrope_position_ids( - mx.array([[[4]], [[4]], [[4]]], dtype=mx.int32), 1 - ) - assert not language._broadcast_text_mrope_position_ids( - mx.array([[[4]], [[4]], [[3]]], dtype=mx.int32), 1 - ) - - @pytest.mark.parametrize("key_tokens", [4097, 32769]) def test_qwen4_decode_gather_stays_budget_bounded_at_long_cache( monkeypatch, @@ -403,16 +374,3 @@ def native(queries, keys, values, scale, causal=False): (256**-0.5, False, "native"), ] assert mx.array_equal(actual, expected).item() - - -def test_python_cache_offset_accepts_batched_mx_array(): - """Batched MTP decode used to crash the QSA path log on ``int(offset)``.""" - compat.apply_mlx_vlm_qwen4_exp_compat_patch() - import mlx_vlm.models.qwen4_exp.language as language - - assert language._python_cache_offset(None) == 0 - assert language._python_cache_offset(0) == 0 - assert language._python_cache_offset(11) == 11 - assert language._python_cache_offset(mx.array(7, dtype=mx.int32)) == 7 - assert language._python_cache_offset(mx.array([7], dtype=mx.int32)) == 7 - assert language._python_cache_offset(mx.array([10, 20], dtype=mx.int32)) == 20 From 9ed3be21d0325a47a5feb42665af4ece7b3c45a4 Mon Sep 17 00:00:00 2001 From: jundot Date: Wed, 2 Sep 2026 20:13:28 +0900 Subject: [PATCH 066/132] fix(qwen4): reject corrupt QSA prefix states (#3294) --- omlx/cache/type_handlers.py | 105 ++++++++++++++++-- tests/test_prefix_cache.py | 100 +++++++++++++++-- .../test_qwen4_qsa_position_reconstruction.py | 64 ++++++++++- 3 files changed, 247 insertions(+), 22 deletions(-) diff --git a/omlx/cache/type_handlers.py b/omlx/cache/type_handlers.py index 4c5d7dae42..a6a7f22c45 100644 --- a/omlx/cache/type_handlers.py +++ b/omlx/cache/type_handlers.py @@ -1446,7 +1446,13 @@ def _deserialize_qsa_positions(position_ids: Any) -> Any: "Serialized QSA position IDs must be [B, C, S], got " f"{position_ids.shape}." ) - if position_ids.shape[1] == 1: + channels = int(position_ids.shape[1]) + if channels not in (1, 3): + raise ValueError( + "Serialized QSA position IDs require 1 text channel or 3 " + f"MRoPE channels, got {position_ids.shape}." + ) + if channels == 1: return position_ids[:, 0, :] return position_ids.transpose(1, 0, 2) @@ -1470,8 +1476,7 @@ def _normalize_qsa_position_states(position_states: list[Any]) -> list[Any]: if not hasattr(position_state, "ndim") or position_state.ndim != 3: shape = getattr(position_state, "shape", None) raise ValueError( - "Serialized QSA position IDs must be [B, C, S], " - f"got {shape}." + "Serialized QSA position IDs must be [B, C, S], " f"got {shape}." ) current_batch, current_channels, _ = position_state.shape if current_channels not in (1, 3): @@ -1493,9 +1498,11 @@ def _normalize_qsa_position_states(position_states: list[Any]) -> list[Any]: return position_states return [ - mx.broadcast_to(state, (state.shape[0], 3, state.shape[2])) - if state.shape[1] == 1 - else state + ( + mx.broadcast_to(state, (state.shape[0], 3, state.shape[2])) + if state.shape[1] == 1 + else state + ) for state in position_states ] @@ -1519,14 +1526,80 @@ def get_state_axis_info(self) -> tuple[CacheStateAxisInfo, ...]: CacheStateAxisInfo("index_position_ids", 2, True), ) + def _get_state_keys(self) -> tuple[str, ...]: + return tuple(info.name for info in self.get_state_axis_info()) + + @staticmethod + def _validate_serialized_state(elements: tuple[Any, ...]) -> int: + """Validate one complete, serialized QSA cache state.""" + if len(elements) != 4: + raise ValueError( + "Serialized QSA cache state requires keys, values, index keys, " + "and index positions" + ) + + keys, values, index_keys, position_ids = elements + present = tuple(element is not None for element in elements) + if not any(present): + return 0 + if not all(present): + raise ValueError( + "Non-empty QSA cache blocks require complete QSA auxiliary state" + ) + + shapes = tuple(getattr(element, "shape", None) for element in elements) + if any(shape is None for shape in shapes): + raise ValueError("Serialized QSA cache state must contain tensors") + if len(shapes[3]) != 3: + raise ValueError( + "Serialized QSA position IDs must be [B, C, S], got " f"{shapes[3]}." + ) + if len(shapes[0]) != 4 or len(shapes[1]) != 4 or len(shapes[2]) != 3: + raise ValueError( + "Serialized QSA cache state requires 4-D K/V and 3-D index " + f"keys, got {shapes[:3]}" + ) + + channels = int(shapes[3][1]) + if channels not in (1, 3): + raise ValueError( + "Serialized QSA position IDs require 1 text channel or 3 " + f"MRoPE channels, got {shapes[3]}." + ) + + batch_sizes = tuple(int(shape[0]) for shape in shapes) + if len(set(batch_sizes)) != 1: + raise ValueError( + "Serialized QSA state requires a consistent batch dimension, " + f"got {batch_sizes}." + ) + + lengths = ( + int(shapes[0][2]), + int(shapes[1][2]), + int(shapes[2][1]), + int(shapes[3][2]), + ) + if len(set(lengths)) != 1: + raise ValueError( + "Serialized QSA K/V and auxiliary state must have the same " + f"sequence length, got {lengths}." + ) + return lengths[0] + + def get_state_seq_len_from_tuple(self, state_tuple: tuple[Any, ...]) -> int: + return self._validate_serialized_state(tuple(state_tuple)) + def serialize_state(self, cache_obj: Any) -> tuple[Any, ...]: keys, values, index_keys, position_ids = cache_obj.state - return ( + elements = ( keys, values, index_keys, _serialize_qsa_positions(position_ids), ) + self._validate_serialized_state(elements) + return elements def extract_state(self, cache_obj: Any) -> dict[str, Any]: elements = self.serialize_state(cache_obj) @@ -1582,15 +1655,24 @@ def concatenate_states(self, states: list[dict[str, Any]]) -> dict[str, Any]: if not HAS_MLX or not states: return {} grouped: list[list[Any]] = [[] for _ in self.get_state_axis_info()] + state_lengths = [] for state in states: elements = state.get("states") if elements is None: elements = tuple( state.get(info.name) for info in self.get_state_axis_info() ) + elements = tuple(elements) + state_lengths.append(self._validate_serialized_state(elements)) for index, element in enumerate(elements): if element is not None: grouped[index].append(element) + if any(length == 0 for length in state_lengths) and any( + length > 0 for length in state_lengths + ): + raise ValueError( + "Non-empty QSA prefix chains cannot contain empty cache blocks" + ) concatenated = [] for info, elements in zip(self.get_state_axis_info(), grouped): if info.name == "index_position_ids": @@ -1624,8 +1706,9 @@ def deserialize_state( logger.error("Qwen4 QSAKVCache unavailable: %s", exc) return None - padded = tuple(elements) + (None,) * max(0, 4 - len(elements)) - keys, values, index_keys, position_ids = padded[:4] + elements = tuple(elements) + self._validate_serialized_state(elements) + keys, values, index_keys, position_ids = elements cache = QSAKVCache() cache.state = ( keys, @@ -1657,12 +1740,14 @@ def cache_type(self) -> CacheType: def serialize_state(self, cache_obj: Any) -> tuple[Any, ...]: keys, values = cache_obj.dequantize_for_apc() - return ( + elements = ( keys, values, cache_obj.index_keys, _serialize_qsa_positions(cache_obj.index_position_ids), ) + self._validate_serialized_state(elements) + return elements class Qwen4BatchQSAKVCacheHandler(CacheTypeHandler): diff --git a/tests/test_prefix_cache.py b/tests/test_prefix_cache.py index eaa043ce41..7839d3be54 100644 --- a/tests/test_prefix_cache.py +++ b/tests/test_prefix_cache.py @@ -208,8 +208,9 @@ def test_shared_prefix_hit_rejects_reassigned_block(self, prefix_cache): tokens = list(range(8)) # 2 full blocks at block_size=4 keys = mx.arange(8, dtype=mx.float32).reshape(1, 1, 8, 1) values = (keys + 100).astype(mx.float32) - cache_data = [{"state": (keys, values), "cache_type": "KVCache", - "class_name": "KVCache"}] + cache_data = [ + {"state": (keys, values), "cache_type": "KVCache", "class_name": "KVCache"} + ] table = prefix_cache.store_cache("req-store", tokens, cache_data) assert table is not None @@ -279,8 +280,8 @@ def test_exact_prefix_survives_ssd_manager_restart(self, tmp_path): first_prefix_cache.release_cache("ordinary-prefix") first_ssd_manager.close() - restarted_prefix_cache, _, restarted_ssd_manager = ( - self._make_ssd_prefix_cache(cache_directory) + restarted_prefix_cache, _, restarted_ssd_manager = self._make_ssd_prefix_cache( + cache_directory ) try: @@ -947,6 +948,93 @@ def load_block_with_metadata(block_hash, **kwargs): assert restored_cache.index_keys.tolist() == index_keys.tolist() assert restored_cache.index_offset == 8 + def test_qwen4_qsa_misaligned_auxiliary_state_is_not_stored( + self, prefix_cache_with_ssd + ): + """A QSA block with shorter indexer state must fail closed.""" + mx = pytest.importorskip("mlx.core") + keys = mx.zeros((1, 2, 8, 64)) + values = mx.zeros((1, 2, 8, 64)) + index_keys = mx.zeros((1, 4, 64)) + positions = mx.zeros((1, 1, 4), dtype=mx.int32) + + block = prefix_cache_with_ssd._extract_block_tensor_slice( + [ + { + "state": (keys, values, index_keys, positions), + "cache_type": "QSAKVCache", + } + ], + 4, + 8, + ) + + assert block is None + + def test_qwen4_qsa_sliceable_nstate_blocks_round_trip(self): + """Valid QSA blocks preserve K/V, index keys, and positions.""" + mx = pytest.importorskip("mlx.core") + paged_cache = PagedCacheManager( + block_size=4, + max_blocks=100, + model_name="test-model", + initial_blocks=100, + ) + mock_ssd = MagicMock() + saved_by_hash = {} + + def save_block(**kwargs): + saved_by_hash[kwargs["block_hash"]] = ( + kwargs["cache_data"], + { + "model_name": "test-model", + "num_layers": 1, + "block_size": 4, + "layer_cache_types": kwargs["layer_cache_types"], + "layer_meta_states": kwargs["layer_meta_states"], + }, + ) + return True + + mock_ssd.save_block.side_effect = save_block + cache = BlockAwarePrefixCache( + model=MockModel(num_layers=1), + paged_cache_manager=paged_cache, + paged_ssd_cache_manager=mock_ssd, + ) + + keys = mx.arange(1 * 2 * 8 * 64, dtype=mx.float32).reshape(1, 2, 8, 64) + values = keys + 1_000 + index_keys = mx.arange(1 * 8 * 64, dtype=mx.float32).reshape(1, 8, 64) + positions = mx.arange(8, dtype=mx.int32).reshape(1, 1, 8) + mx.eval(keys, values, index_keys, positions) + cache_data = [ + { + "state": (keys, values, index_keys, positions), + "cache_type": "QSAKVCache", + "class_name": "QSAKVCache", + "meta_state": (), + } + ] + + block_table = cache.store_cache("req-qsa", list(range(8)), cache_data) + + assert block_table is not None + assert len(block_table.block_ids) == 2 + + def load_block_with_metadata(block_hash, **kwargs): + return saved_by_hash.get(block_hash, (None, None)) + + mock_ssd.load_block_with_metadata.side_effect = load_block_with_metadata + restored = cache.reconstruct_cache(block_table) + + assert restored is not None + restored_state = restored[0].state + assert restored_state[0].tolist() == keys.tolist() + assert restored_state[1].tolist() == values.tolist() + assert restored_state[2].tolist() == index_keys.tolist() + assert restored_state[3].tolist() == positions[:, 0, :].tolist() + class TestPrefixIndexOperations: """Tests for prefix index operations.""" @@ -1668,9 +1756,7 @@ def test_store_cache_skips_partial_blocks(self, mx): assert stats.last_partial_tokens_skipped == 2 assert stats.last_tokens_to_next_block == 2 - def test_store_cache_arrayscache_partial_trailing_stores_placeholder( - self, mx - ): + def test_store_cache_arrayscache_partial_trailing_stores_placeholder(self, mx): """A1 regression: 7 tokens / block_size=4 stores 1 full block (4 tokens) and skips 3 trailing partial tokens -- but the ArraysCache conv/ssm state passed in is the LIVE state after all 7 tokens, not diff --git a/tests/test_qwen4_qsa_position_reconstruction.py b/tests/test_qwen4_qsa_position_reconstruction.py index 9b62fb88c2..342b0ff4e3 100644 --- a/tests/test_qwen4_qsa_position_reconstruction.py +++ b/tests/test_qwen4_qsa_position_reconstruction.py @@ -8,7 +8,16 @@ def _state(positions): - return {"states": (None, None, None, positions)} + batch = positions.shape[0] + length = positions.shape[-1] + return { + "states": ( + mx.zeros((batch, 1, length, 1)), + mx.zeros((batch, 1, length, 1)), + mx.zeros((batch, length, 1)), + positions, + ) + } def _text(value, length, batch=1): @@ -86,8 +95,17 @@ def test_unsupported_channel_count_is_rejected_in_every_state(segments): def test_incompatible_batch_shape_is_rejected(): + first = _state(_text(1, 2, batch=1)) + second = _state(_mrope((2, 3, 4), 2, batch=2)) + second["states"] = ( + mx.zeros((1, 1, 2, 1)), + mx.zeros((1, 1, 2, 1)), + mx.zeros((1, 2, 1)), + second["states"][3], + ) + with pytest.raises(ValueError, match="consistent batch dimension"): - _positions(_text(1, 2, batch=1), _mrope((2, 3, 4), 2, batch=2)) + Qwen4QSAKVCacheHandler().concatenate_states([first, second]) @pytest.mark.parametrize( @@ -102,6 +120,44 @@ def test_non_serialized_position_shape_is_rejected_in_every_state(segments): _positions(*segments) +def test_partial_auxiliary_state_is_rejected(): + full = _state(_text(1, 4)) + missing_auxiliary = { + "states": ( + mx.zeros((1, 1, 4, 1)), + mx.zeros((1, 1, 4, 1)), + None, + None, + ) + } + + with pytest.raises(ValueError, match="complete QSA auxiliary state"): + Qwen4QSAKVCacheHandler().concatenate_states([full, missing_auxiliary]) + + +def test_empty_cache_block_is_rejected_in_non_empty_prefix(): + with pytest.raises(ValueError, match="cannot contain empty cache blocks"): + Qwen4QSAKVCacheHandler().concatenate_states( + [_state(_text(1, 4)), {"states": (None, None, None, None)}] + ) + + +def test_direct_deserialize_rejects_unsupported_position_channels(): + state = _state(mx.zeros((1, 2, 4), dtype=mx.int32))["states"] + + with pytest.raises(ValueError, match="require 1 text channel or 3 MRoPE"): + Qwen4QSAKVCacheHandler().deserialize_state(state) + + +def test_state_info_lists_every_qsa_state_element(): + assert Qwen4QSAKVCacheHandler().get_state_info().state_keys == ( + "keys", + "values", + "index_keys", + "index_position_ids", + ) + + def test_card_572_fourteen_block_topology_reconstructs_exact_prefix(): block_size = 2048 segments = [_text(block, block_size) for block in range(14)] @@ -111,9 +167,7 @@ def test_card_572_fourteen_block_topology_reconstructs_exact_prefix(): assert result.shape == (1, 3, 28_672) # Text blocks on either side are duplicated into every MRoPE coordinate. - expected_text_prefix = [ - block for block in range(9) for _ in range(block_size) - ] + expected_text_prefix = [block for block in range(9) for _ in range(block_size)] for channel in range(3): assert result[0, channel, : 9 * block_size].tolist() == expected_text_prefix assert result[0, channel, 10 * block_size : 11 * block_size].tolist() == ( From e1280a2be56d417c86b089f1fc853ff533accea9 Mon Sep 17 00:00:00 2001 From: jundot Date: Wed, 2 Sep 2026 20:23:06 +0900 Subject: [PATCH 067/132] refactor: simplify Qwen4 prefill memory accounting (#3350) --- omlx/memory_monitor.py | 13 +-- omlx/prefill_transient_tracker.py | 116 +++++++------------ omlx/scheduler.py | 32 +---- tests/test_memory_monitor_vlm_config.py | 10 +- tests/test_prefill_oom_graceful.py | 13 +-- tests/test_scheduler_prefill_memory_guard.py | 2 +- 6 files changed, 62 insertions(+), 124 deletions(-) diff --git a/omlx/memory_monitor.py b/omlx/memory_monitor.py index db6d9ceff8..feed9fa25a 100644 --- a/omlx/memory_monitor.py +++ b/omlx/memory_monitor.py @@ -249,10 +249,6 @@ def __init__( # Fixed per-sequence recurrent state (GDN/Mamba ArraysCache), # measured once from a live cache after the first prefill chunk. self._fixed_state_bytes: int = 0 - # Fallback for estimate_chunk_transient_bytes when the caller omits - # gathered_core=. Scheduler paths pass the argument explicitly. - self.qwen4_charge_gathered_core: bool = False - # PagedCacheManager for KV cache memory measurement self._paged_cache_manager: Optional["PagedCacheManager"] = None self._block_size: int = 256 # Default block size @@ -854,7 +850,7 @@ def estimate_chunk_transient_bytes( n_tokens: int, kv_len: int, *, - gathered_core: bool | None = None, + gathered_core: bool = False, ) -> int: """Transient SDPA activation bytes for ONE prefill chunk. @@ -872,18 +868,15 @@ def estimate_chunk_transient_bytes( Returns 0 when model info is unavailable. ``gathered_core`` prices Qwen4 QSA as a gathered core instead of - dense Q×kv_len. Scheduler paths pass it explicitly. When omitted, - ``qwen4_charge_gathered_core`` is the fallback for older tests. + dense Q×kv_len. """ - if gathered_core is None: - gathered_core = bool(self.qwen4_charge_gathered_core) if self._prefill_memory_profile is not None: profile = self._prefill_memory_profile if isinstance(profile, _Qwen4ExpPrefillMemoryProfile): return profile.estimate_prefill_transient_bytes( n_tokens, kv_len, - gathered_core=bool(gathered_core), + gathered_core=gathered_core, ) return profile.estimate_prefill_transient_bytes(n_tokens, kv_len) return self._estimate_sdpa_activation_bytes(n_tokens, kv_len) diff --git a/omlx/prefill_transient_tracker.py b/omlx/prefill_transient_tracker.py index f84f0a385c..f2db08acb9 100644 --- a/omlx/prefill_transient_tracker.py +++ b/omlx/prefill_transient_tracker.py @@ -13,10 +13,20 @@ from __future__ import annotations import logging +from dataclasses import dataclass logger = logging.getLogger(__name__) +@dataclass +class _TransientHistory: + ewma_per_token: float = 0.0 + samples: int = 0 + last_delta_bytes: int = 0 + last_n_tokens: int = 0 + observed_max_bytes: int = 0 + + class PrefillTransientTracker: """EWMA estimator of MLX prefill chunk transient bytes per token. @@ -47,43 +57,15 @@ class PrefillTransientTracker: def __init__(self, model_id: str = "") -> None: self._model_id = model_id - self._ewma_per_token: float = 0.0 - self._samples: int = 0 - # Last observed delta for debug log inspection. - self._last_delta_bytes: int = 0 - self._last_n_tokens: int = 0 - # Largest floor-size chunk transient seen this session: a stable - # flat bound for admission and the pre-chunk guard's pass/abort - # gates, matching the floor-chunk charge they price. Never used - # for chunk sizing. - self._observed_max_bytes: int = 0 + self._dense_history = _TransientHistory() + self._gathered_history = _TransientHistory() # Net process footprint released by negative post-chunk deltas. MLX may # need to allocate that pool again on the next chunk, so the scheduler # prices it once until a positive measurement confirms reallocation. self._recent_reclaim_bytes: int = 0 - # Qwen4 gathered QSA and ordinary dense prefill have fundamentally - # different cost curves. Keep an independent history for gathered - # chunks so switching execution regimes cannot make a cheap gathered - # chunk inherit a dense EWMA, last sample, or floor maximum. The - # unprefixed fields above remain the default/dense history so existing - # callers and diagnostics retain their original behavior. - self._gathered_ewma_per_token: float = 0.0 - self._gathered_samples: int = 0 - self._gathered_last_delta_bytes: int = 0 - self._gathered_last_n_tokens: int = 0 - self._gathered_observed_max_bytes: int = 0 - - @staticmethod - def _history_prefix(gathered_core: bool | None) -> str: - return "_gathered_" if gathered_core is True else "_" - - def _history_value(self, name: str, gathered_core: bool | None) -> int | float: - return getattr(self, f"{self._history_prefix(gathered_core)}{name}") - - def _set_history_value( - self, name: str, value: int | float, gathered_core: bool | None - ) -> None: - setattr(self, f"{self._history_prefix(gathered_core)}{name}", value) + + def _history(self, gathered_core: bool) -> _TransientHistory: + return self._gathered_history if gathered_core is True else self._dense_history def record_reclaim(self, reclaimed_bytes: int) -> None: """Accumulate footprint released since the last positive sample.""" @@ -106,7 +88,7 @@ def update( transient_bytes: int, *, floor_sample: bool = False, - gathered_core: bool | None = None, + gathered_core: bool = False, ) -> None: """Record one chunk observation. @@ -136,19 +118,16 @@ def update( self._recent_reclaim_bytes = 0 - samples = int(self._history_value("samples", gathered_core)) - ewma_per_token = float(self._history_value("ewma_per_token", gathered_core)) - observed_max_bytes = int( - self._history_value("observed_max_bytes", gathered_core) - ) + history = self._history(gathered_core) # The very first sample in each execution regime carries weight # page-fault and load-residue noise, so it seeds that regime's EWMA # but is excluded from its running max. - if floor_sample and samples > 0: + if floor_sample and history.samples > 0: if transient_bytes <= self._OBSERVED_MAX_CLAMP_BYTES: - if transient_bytes > observed_max_bytes: - observed_max_bytes = transient_bytes + history.observed_max_bytes = max( + history.observed_max_bytes, transient_bytes + ) else: logger.debug( "PrefillTransientTracker(%s): rejected %d-byte outlier " @@ -159,9 +138,9 @@ def update( ) per_token = transient_bytes / n_tokens - if samples == 0: - ewma_per_token = per_token - elif per_token > ewma_per_token * self._EWMA_OUTLIER_RATIO: + if history.samples == 0: + history.ewma_per_token = per_token + elif per_token > history.ewma_per_token * self._EWMA_OUTLIER_RATIO: # Reject from the EWMA blend: a single sample this far above # the running rate is more likely a noisy phys_footprint() # delta (see _record_chunk_transient's docstring on @@ -173,18 +152,17 @@ def update( "outlier from EWMA (current %.1f, ratio limit %.1fx)", self._model_id, per_token, - ewma_per_token, + history.ewma_per_token, self._EWMA_OUTLIER_RATIO, ) else: - ewma_per_token = ( - self._EWMA_ALPHA * per_token + (1.0 - self._EWMA_ALPHA) * ewma_per_token + history.ewma_per_token = ( + self._EWMA_ALPHA * per_token + + (1.0 - self._EWMA_ALPHA) * history.ewma_per_token ) - self._set_history_value("ewma_per_token", ewma_per_token, gathered_core) - self._set_history_value("samples", samples + 1, gathered_core) - self._set_history_value("last_delta_bytes", transient_bytes, gathered_core) - self._set_history_value("last_n_tokens", n_tokens, gathered_core) - self._set_history_value("observed_max_bytes", observed_max_bytes, gathered_core) + history.samples += 1 + history.last_delta_bytes = transient_bytes + history.last_n_tokens = n_tokens def predict( self, @@ -205,48 +183,48 @@ def predict( def bytes_per_token_for(self, gathered_core: bool) -> float: """Return the EWMA for the selected execution regime.""" - return float(self._history_value("ewma_per_token", gathered_core)) + return self._history(gathered_core).ewma_per_token def samples_for(self, gathered_core: bool) -> int: """Return the sample count for the selected execution regime.""" - return int(self._history_value("samples", gathered_core)) + return self._history(gathered_core).samples def last_delta_bytes_for(self, gathered_core: bool) -> int: """Return the latest measured delta for the selected regime.""" - return int(self._history_value("last_delta_bytes", gathered_core)) + return self._history(gathered_core).last_delta_bytes def last_n_tokens_for(self, gathered_core: bool) -> int: """Return the latest measured width for the selected regime.""" - return int(self._history_value("last_n_tokens", gathered_core)) + return self._history(gathered_core).last_n_tokens def observed_max_bytes_for(self, gathered_core: bool) -> int: """Return the floor-size maximum for the selected regime.""" - return int(self._history_value("observed_max_bytes", gathered_core)) + return self._history(gathered_core).observed_max_bytes @property def bytes_per_token(self) -> float: """Current EWMA value (bytes per prefill token). 0.0 if no samples.""" - return self._ewma_per_token + return self._dense_history.ewma_per_token @property def samples(self) -> int: """Number of chunks recorded since last reset.""" - return self._samples + return self._dense_history.samples @property def last_delta_bytes(self) -> int: """Bytes added by the most recently measured chunk.""" - return self._last_delta_bytes + return self._dense_history.last_delta_bytes @property def last_n_tokens(self) -> int: """Token count of the most recently measured chunk.""" - return self._last_n_tokens + return self._dense_history.last_n_tokens @property def observed_max_bytes(self) -> int: """Largest accepted chunk transient this session (0 if none yet).""" - return self._observed_max_bytes + return self._dense_history.observed_max_bytes @property def recent_reclaim_bytes(self) -> int: @@ -255,14 +233,6 @@ def recent_reclaim_bytes(self) -> int: def reset(self) -> None: """Drop all observations (e.g. on model reload or after a long idle).""" - self._ewma_per_token = 0.0 - self._samples = 0 - self._last_delta_bytes = 0 - self._last_n_tokens = 0 - self._observed_max_bytes = 0 + self._dense_history = _TransientHistory() + self._gathered_history = _TransientHistory() self._recent_reclaim_bytes = 0 - self._gathered_ewma_per_token = 0.0 - self._gathered_samples = 0 - self._gathered_last_delta_bytes = 0 - self._gathered_last_n_tokens = 0 - self._gathered_observed_max_bytes = 0 diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 3b7dd32109..503d54dd56 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -3436,17 +3436,6 @@ def _do_external_prefill( tokens: list[int], existing_cache: list[Any] | None, vlm_embeds: tuple[mx.array, dict[str, Any], int] | None = None, - ) -> tuple[list[Any], list[int]]: - return self._do_external_prefill_impl( - request, tokens, existing_cache, vlm_embeds - ) - - def _do_external_prefill_impl( - self, - request: "Request", - tokens: list[int], - existing_cache: list[Any] | None, - vlm_embeds: tuple[mx.array, dict[str, Any], int] | None = None, ) -> tuple[list[Any], list[int]]: """Run prefill externally (outside BatchGenerator) for a single request. @@ -3909,21 +3898,6 @@ def _do_external_prefill_impl( _MEMORY_ADMISSION_STALL_TIMEOUT_S: float = 60.0 _STORE_CACHE_ADMISSION_STALL_TIMEOUT_S: float = 60.0 - def _estimate_chunk_transient_bytes( - self, n_tokens: int, kv_len: int, *, gathered_core: bool - ) -> int: - """Call the monitor with an explicit gathered_core flag. - - Test doubles often still take ``(n_tokens, kv_len)`` only. - """ - estimate = self.memory_monitor.estimate_chunk_transient_bytes - try: - return int( - estimate(n_tokens, kv_len, gathered_core=gathered_core) - ) - except TypeError: - return int(estimate(n_tokens, kv_len)) - def _predicted_chunk_transient( self, n_tokens: int, kv_len: int, *, gathered_core: bool = False ) -> float: @@ -3948,8 +3922,10 @@ def _predicted_chunk_transient( recent_reclaim = 0 tracker = self._prefill_transient_tracker if self.memory_monitor is not None: - static = self._estimate_chunk_transient_bytes( - n_tokens, kv_len + n_tokens, gathered_core=gathered_core + static = self.memory_monitor.estimate_chunk_transient_bytes( + n_tokens, + kv_len + n_tokens, + gathered_core=gathered_core, ) static += self.memory_monitor.estimate_prompt_kv_bytes(n_tokens) static_per_token = float(static) / n_tokens diff --git a/tests/test_memory_monitor_vlm_config.py b/tests/test_memory_monitor_vlm_config.py index d81a5d2392..3148d5733f 100644 --- a/tests/test_memory_monitor_vlm_config.py +++ b/tests/test_memory_monitor_vlm_config.py @@ -163,10 +163,12 @@ def test_qwen4_prefill_profile_gathered_core_caps_score_matrix(): prefill_memory_profile=profile, ) query, kv_len = 4096, 233_472 - monitor.qwen4_charge_gathered_core = False - dense = monitor.estimate_chunk_transient_bytes(query, kv_len) - monitor.qwen4_charge_gathered_core = True - gathered = monitor.estimate_chunk_transient_bytes(query, kv_len) + dense = monitor.estimate_chunk_transient_bytes( + query, kv_len, gathered_core=False + ) + gathered = monitor.estimate_chunk_transient_bytes( + query, kv_len, gathered_core=True + ) assert gathered * 8 < dense # 147GB resident + this gathered gulp stays under the 214GB safety cap. assert gathered < 12 * 1024**3 diff --git a/tests/test_prefill_oom_graceful.py b/tests/test_prefill_oom_graceful.py index c2befe276f..e12539b295 100644 --- a/tests/test_prefill_oom_graceful.py +++ b/tests/test_prefill_oom_graceful.py @@ -134,9 +134,6 @@ def _throttle_ctx( ns._predicted_chunk_transient = Scheduler._predicted_chunk_transient.__get__( ns, Scheduler ) - ns._estimate_chunk_transient_bytes = ( - Scheduler._estimate_chunk_transient_bytes.__get__(ns, Scheduler) - ) ns._admission_transient_bound = Scheduler._admission_transient_bound.__get__( ns, Scheduler ) @@ -607,7 +604,7 @@ def test_adaptive_throttle_charges_recently_reclaimed_footprint(): static_prediction = 11.18 * _GB released = 6.34 * _GB monitor = SimpleNamespace( - estimate_chunk_transient_bytes=lambda _n, _kv: ( + estimate_chunk_transient_bytes=lambda _n, _kv, *, gathered_core=False: ( static_prediction / Scheduler._PREFILL_TRANSIENT_SAFETY ), estimate_prompt_kv_bytes=lambda _n: 0, @@ -653,7 +650,7 @@ def test_predicted_transient_does_not_double_count_reclaim_covered_by_raw(): 512 * Scheduler._PREFILL_TRANSIENT_SAFETY ) monitor = SimpleNamespace( - estimate_chunk_transient_bytes=lambda _n, _kv: ( + estimate_chunk_transient_bytes=lambda _n, _kv, *, gathered_core=False: ( static_prediction / Scheduler._PREFILL_TRANSIENT_SAFETY ), estimate_prompt_kv_bytes=lambda _n: 0, @@ -1133,7 +1130,7 @@ def test_adaptive_chunk_size_ignores_observed_max(): before = _call(ns, 2048, kv_len=5000) assert before < 2048, "precondition: the throttle must actually shrink" - ns._prefill_transient_tracker._observed_max_bytes = 8 * _GB + ns._prefill_transient_tracker._dense_history.observed_max_bytes = 8 * _GB after = _call(ns, 2048, kv_len=5000) assert after == before @@ -1151,7 +1148,7 @@ def test_guard_abort_gate_charges_observed_max(): assert _guard_call(ns, 2048, kv_len=50_000) < 2048 # 2GB observed max no longer fits under the 1GB headroom: abort. - ns._prefill_transient_tracker._observed_max_bytes = 2 * _GB + ns._prefill_transient_tracker._dense_history.observed_max_bytes = 2 * _GB with pytest.raises(PrefillMemoryExceededError): _guard_call(ns, 2048, kv_len=50_000) @@ -1166,7 +1163,7 @@ def test_guard_shrink_math_unchanged_by_observed_max(): before = _guard_call(ns, 2048, kv_len=50_000) assert before < 2048 - ns._prefill_transient_tracker._observed_max_bytes = 512 * 1024**2 + ns._prefill_transient_tracker._dense_history.observed_max_bytes = 512 * 1024**2 after = _guard_call(ns, 2048, kv_len=50_000) assert after == before diff --git a/tests/test_scheduler_prefill_memory_guard.py b/tests/test_scheduler_prefill_memory_guard.py index 744b35fbf8..48b1e72c1e 100644 --- a/tests/test_scheduler_prefill_memory_guard.py +++ b/tests/test_scheduler_prefill_memory_guard.py @@ -949,7 +949,7 @@ def test_preflight_charges_observed_max_transient(): with patches[0], patches[1]: scheduler.preflight_or_raise(num_prompt_tokens=32768) # fits - scheduler._prefill_transient_tracker._observed_max_bytes = ( + scheduler._prefill_transient_tracker._dense_history.observed_max_bytes = ( est.transient + 2 * 1024**3 ) with patches[0], patches[1], pytest.raises(PrefillMemoryExceededError): From 1f6f4e284174fb9fea0eea9d3e32da261e5cd3b5 Mon Sep 17 00:00:00 2001 From: pedroberaldo87 <134068505+pedroberaldo87@users.noreply.github.com> Date: Wed, 2 Sep 2026 09:32:50 -0300 Subject: [PATCH 068/132] fix(engine_pool): keep the Qwen4 PLE table resident across a model swap (#3299) Keep the Qwen4 PLE residency decision stable across model swaps by separating it from the instantaneous admission ceiling. --- omlx/engine_pool.py | 37 ++++++++++++++++++++++++- omlx/process_memory_enforcer.py | 22 +++++++++++++++ omlx/server.py | 5 ++++ tests/test_qwen4_exp_residency.py | 45 +++++++++++++++++++++++++++++++ 4 files changed, 108 insertions(+), 1 deletion(-) diff --git a/omlx/engine_pool.py b/omlx/engine_pool.py index 9e7969b446..05d35dfe14 100644 --- a/omlx/engine_pool.py +++ b/omlx/engine_pool.py @@ -285,6 +285,7 @@ def __init__( self._get_final_ceiling: object | None = None # Set by server self._get_admission_ceiling: object | None = None # Set by server self._get_admission_soft_target: object | None = None # Set by server + self._get_residency_ceiling: object | None = None # Set by server self._settings_manager: object | None = None # Set by server self._cluster_registry: ClusterRegistry | None = None # Set by server self._suppress_ttl: bool = False # Suppress TTL during benchmarks @@ -398,10 +399,28 @@ def _qwen4_ple_offload_status( exc_info=True, ) return False, False, None - ceiling = self._fallback_admission_ceiling() + # Residency is a throughput decision, so it uses the ceiling that does + # not move with instantaneous pressure. Asking the admission ceiling + # here read vm_stat right after the previous model unloaded, before the + # OS had returned its pages: the ceiling dipped, a table that fits got + # forced to SSD, and the swapped-in model ran at 14.1 instead of 35.3 + # tok/s for the rest of its life in the process. + ceiling = self._residency_ceiling() + if ceiling <= 0: + ceiling = self._fallback_admission_ceiling() if ceiling <= 0: ceiling = self._current_ceiling() forced = estimate.force_ssd_offload(ceiling) + if forced: + logger.warning( + "Qwen4-Exp PLE forced to SSD for %s: resident %.1fGB exceeds the " + "%.1fGB residency ceiling (mmap needs %.1fGB). Decode will be " + "roughly 2.5x slower than a resident load.", + entry.model_id, + estimate.resident_bytes / 1e9, + ceiling / 1e9, + estimate.mmap_bytes / 1e9, + ) requested = bool( settings is not None and getattr(settings, "qwen4_ple_ssd_offload", False) ) @@ -472,6 +491,22 @@ def _fallback_admission_ceiling(self) -> int: except Exception: # noqa: BLE001 return 0 + def _residency_ceiling(self) -> int: + """Stable ceiling for the resident-vs-mmap call (#PLE residency). + + Wired to `enforcer.get_residency_ceiling`, which drops the vm_stat + component so a model swap does not push a table that fits onto SSD. + Returns 0 when no callback is wired up; callers fall back to the + admission ceiling. + """ + cb = self._get_residency_ceiling + if cb is None: + return 0 + try: + return int(cb()) + except Exception: # noqa: BLE001 + return 0 + def _admission_soft_target(self) -> int: """Soft watermark that pre-load eviction targets (#2319). diff --git a/omlx/process_memory_enforcer.py b/omlx/process_memory_enforcer.py index 43e40ffeec..3a90ee1a0e 100644 --- a/omlx/process_memory_enforcer.py +++ b/omlx/process_memory_enforcer.py @@ -707,6 +707,28 @@ def get_admission_ceiling(self) -> int: return self._get_hard_limit_bytes() return self._get_static_ceiling() + def get_residency_ceiling(self) -> int: + """Stable ceiling for *where weights live*, not for admitting a load. + + Admission must respect memory free right now — overcommitting thrashes + the machine. Choosing whether a model's PLE table stays resident or + falls back to mmap is a throughput call, and the instantaneous ceiling + is actively wrong for it: engine_pool asks right after the previous + model unloaded, before the OS has returned its pages, so ``dynamic`` + dips and a table that fits gets pushed to SSD for the rest of that + engine's life. Measured on a model swap here: 35.3 -> 14.1 tok/s. + + Uses only the two components that don't move with instantaneous + pressure. Returns 0 when the guard is off, like the other accessors. + """ + breakdown = self._get_ceiling_breakdown() + candidates = [ + value + for value in (breakdown["static"], breakdown["metal_cap"]) + if value > 0 + ] + return min(candidates) if candidates else 0 + def get_admission_soft_target(self) -> int: """Soft watermark that pre-load admission evicts down to (#2319). diff --git a/omlx/server.py b/omlx/server.py index 72a600687c..094291ddf9 100644 --- a/omlx/server.py +++ b/omlx/server.py @@ -499,6 +499,11 @@ async def _bonjour_supervisor() -> None: _server_state.engine_pool._get_admission_soft_target = ( enforcer.get_admission_soft_target ) + # Resident-vs-mmap is a throughput call and must not read the + # instantaneous ceiling, which dips right after a model swap. + _server_state.engine_pool._get_residency_ceiling = ( + enforcer.get_residency_ceiling + ) enforcer.start() # Startup: Preload pinned models in the background so uvicorn binds the diff --git a/tests/test_qwen4_exp_residency.py b/tests/test_qwen4_exp_residency.py index 327e2c92d3..72d3ae7ad3 100644 --- a/tests/test_qwen4_exp_residency.py +++ b/tests/test_qwen4_exp_residency.py @@ -66,3 +66,48 @@ def test_offload_is_forced_only_when_it_makes_the_model_fit(tmp_path): assert estimate.force_ssd_offload(between_modes) is True assert estimate.force_ssd_offload(estimate.resident_bytes) is False assert estimate.force_ssd_offload(max(0, estimate.mmap_bytes - 1)) is False + + +def test_residency_uses_the_stable_ceiling_not_the_instantaneous_one(tmp_path): + """A model swap must not push a table that fits onto SSD. + + engine_pool used to ask the admission ceiling, which reads vm_stat. On a + swap that reading lands right after the previous model unloaded, before + the OS returned its pages, so the ceiling dips below the resident size and + the table is forced to SSD for the rest of that engine's life. Measured + cost of that mistake on this machine: 35.3 -> 14.1 tok/s. + """ + from omlx.engine_pool import EngineEntry, EnginePool + + model = tmp_path / "qwen4" + model.mkdir() + ple_key = "model.language_model.ngram_embedding.shard_0.weight" + _write_safetensors(model / "model.safetensors", {ple_key: 100}) + (model / "model.safetensors.index.json").write_text( + json.dumps({"weight_map": {ple_key: "model.safetensors"}}) + ) + estimate = qwen4_exp_residency_estimate(model) + + pool = EnginePool.__new__(EnginePool) + pool._get_admission_ceiling = None + pool._get_admission_soft_target = None + pool._get_final_ceiling = None + entry = EngineEntry.__new__(EngineEntry) + entry.model_id = "qwen4" + entry.model_path = str(model) + entry.config_model_type = "qwen4_exp" + + # The instantaneous ceiling has dipped between the two modes — exactly the + # window right after a swap. The stable ceiling still clears resident. + deprimido = (estimate.resident_bytes + estimate.mmap_bytes) // 2 + pool._get_admission_ceiling = lambda: deprimido + pool._get_residency_ceiling = lambda: estimate.resident_bytes + + enabled, forced, _ = pool._qwen4_ple_offload_status(entry, None) + assert forced is False, "a dip in the instantaneous ceiling must not force SSD" + assert enabled is False + + # With no stable ceiling wired up we still fall back to the old behaviour. + pool._get_residency_ceiling = None + _, forced_sem_cb, _ = pool._qwen4_ple_offload_status(entry, None) + assert forced_sem_cb is True From 33ad1ea929d7f07cb12cbf50dbced317dc96c8dd Mon Sep 17 00:00:00 2001 From: jundot Date: Wed, 2 Sep 2026 21:42:22 +0900 Subject: [PATCH 069/132] fix: preserve Qwen4 PLE mmap admission fallback --- omlx/engine_pool.py | 60 +++++++++++++++++++++++++++++---------- tests/test_engine_pool.py | 57 +++++++++++++++++++++++++++++++++++++ 2 files changed, 102 insertions(+), 15 deletions(-) diff --git a/omlx/engine_pool.py b/omlx/engine_pool.py index 05d35dfe14..f835cf3eba 100644 --- a/omlx/engine_pool.py +++ b/omlx/engine_pool.py @@ -380,6 +380,8 @@ def _qwen4_ple_offload_status( self, entry: EngineEntry, settings: object | None, + *, + ceiling: int | None = None, ) -> tuple[bool, bool, object | None]: """Resolve requested/forced Qwen4 PLE mmap mode for this process.""" @@ -399,22 +401,20 @@ def _qwen4_ple_offload_status( exc_info=True, ) return False, False, None - # Residency is a throughput decision, so it uses the ceiling that does - # not move with instantaneous pressure. Asking the admission ceiling - # here read vm_stat right after the previous model unloaded, before the - # OS had returned its pages: the ceiling dipped, a table that fits got - # forced to SSD, and the swapped-in model ran at 14.1 instead of 35.3 - # tok/s for the rest of its life in the process. - ceiling = self._residency_ceiling() - if ceiling <= 0: - ceiling = self._fallback_admission_ceiling() - if ceiling <= 0: - ceiling = self._current_ceiling() + # Normal residency calls use the stable ceiling so a post-unload + # vm_stat dip cannot pin the new engine to SSD. Pre-load admission may + # pass its earlier live ceiling explicitly when only mmap fits. + if ceiling is None: + ceiling = self._residency_ceiling() + if ceiling <= 0: + ceiling = self._fallback_admission_ceiling() + if ceiling <= 0: + ceiling = self._current_ceiling() forced = estimate.force_ssd_offload(ceiling) if forced: logger.warning( "Qwen4-Exp PLE forced to SSD for %s: resident %.1fGB exceeds the " - "%.1fGB residency ceiling (mmap needs %.1fGB). Decode will be " + "%.1fGB memory ceiling (mmap needs %.1fGB). Decode will be " "roughly 2.5x slower than a resident load.", entry.model_id, estimate.resident_bytes / 1e9, @@ -430,10 +430,16 @@ def _effective_qwen4_model_settings( self, entry: EngineEntry, settings: object | None, + *, + ceiling: int | None = None, ) -> object | None: """Apply a forced mmap decision without mutating persisted settings.""" - enabled, forced, _ = self._qwen4_ple_offload_status(entry, settings) + enabled, forced, _ = self._qwen4_ple_offload_status( + entry, + settings, + ceiling=ceiling, + ) if not enabled or not forced or settings is None: return settings effective = copy.copy(settings) @@ -1518,6 +1524,16 @@ async def get_engine( model_id, runtime_settings, ) + qwen4_admission_ceiling = None + if ( + (entry.config_model_type or "").replace("-", "_").lower() + == "qwen4_exp" + ): + candidate = self._current_ceiling() + if candidate <= 0: + candidate = self._fallback_admission_ceiling() + if candidate > 0: + qwen4_admission_ceiling = candidate unloaded_for_admission = False # Already loaded - just update access time @@ -1605,9 +1621,18 @@ async def get_engine( get_settings = getattr(self._settings_manager, "get_settings", None) if callable(get_settings): admission_settings = get_settings(model_id) - admission_size = self._entry_runtime_resident_size( + load_settings = self._effective_qwen4_model_settings( entry, admission_settings, + ceiling=qwen4_admission_ceiling, + ) + qwen4_admission_override = load_settings is not admission_settings + runtime_load_settings = ( + load_settings if qwen4_admission_override else runtime_settings + ) + admission_size = self._entry_runtime_resident_size( + entry, + load_settings, base_size=admission_size, ) admission_kind = "local shard" if deployment is not None else "model" @@ -1751,10 +1776,15 @@ async def get_engine( await self._load_engine( model_id, force_lm=force_lm, - runtime_settings=runtime_settings, + runtime_settings=runtime_load_settings, ) loaded = self._entries[model_id] + if qwen4_admission_override and expected_signature is not None: + # Automatic mmap is local to this admission attempt. Keep the + # user's requested variant as the reuse key so the next request + # does not reload the model merely because pressure recovered. + loaded.runtime_settings_signature = expected_signature self._validate_llm_engine_ready(model_id, loaded.engine) if _lease: loaded.in_use += 1 diff --git a/tests/test_engine_pool.py b/tests/test_engine_pool.py index 77fc72977e..4665b15a49 100644 --- a/tests/test_engine_pool.py +++ b/tests/test_engine_pool.py @@ -673,6 +673,63 @@ def test_qwen4_ple_offload_reduces_resident_projection(self, tmp_path): assert effective.qwen4_ple_ssd_offload is True assert signature["qwen4_ple_ssd_offload"] == "True" + @pytest.mark.asyncio + async def test_qwen4_live_admission_keeps_viable_mmap_fallback(self, tmp_path): + """Real pressure may select mmap without making that override sticky.""" + from omlx.model_settings import ModelSettings + from omlx.patches.mlx_vlm_qwen4_exp_compat.residency import ( + Qwen4ExpResidencyEstimate, + ) + + model = tmp_path / "qwen4" + model.mkdir() + (model / "config.json").write_text(json.dumps({"model_type": "qwen4_exp"})) + settings = ModelSettings(qwen4_ple_ssd_offload=False) + entry = EngineEntry( + model_id="qwen4", + model_path=str(model), + model_type="llm", + engine_type="batched", + config_model_type="qwen4_exp", + estimated_size=1000, + ) + estimate = Qwen4ExpResidencyEstimate( + supported=True, + checkpoint_bytes=950, + ple_bytes=550, + resident_bytes=1000, + mmap_bytes=400, + ) + pool = _make_pool(ceiling=500) + pool._get_admission_soft_target = lambda: 500 + pool._get_residency_ceiling = lambda: 1000 + pool._entries[entry.model_id] = entry + mock_engine = MagicMock() + mock_engine.start = AsyncMock() + + with ( + patch("omlx.engine_pool.BatchedEngine", return_value=mock_engine) as cls, + patch("omlx.engine_pool.get_phys_footprint", return_value=0), + patch("omlx.engine_pool.mx.get_active_memory", return_value=0), + patch( + "omlx.patches.mlx_vlm_qwen4_exp_compat.residency." + "qwen4_exp_residency_estimate", + return_value=estimate, + ), + ): + loaded = await pool.get_engine("qwen4", runtime_settings=settings) + reused = await pool.get_engine("qwen4", runtime_settings=settings) + + assert loaded is mock_engine + assert reused is mock_engine + cls.assert_called_once() + effective = cls.call_args.kwargs["model_settings"] + assert effective.qwen4_ple_ssd_offload is True + assert settings.qwen4_ple_ssd_offload is False + assert entry.runtime_estimated_size == 400 + signature = dict(entry.runtime_settings_signature or ()) + assert signature["qwen4_ple_ssd_offload"] == "False" + class TestApplySettingsOverrides: """Tests for apply_settings_overrides method.""" From 1a7ab338f627ed0000d9f961a1c8dbff9e8adf65 Mon Sep 17 00:00:00 2001 From: jundot Date: Wed, 2 Sep 2026 21:44:10 +0900 Subject: [PATCH 070/132] fix: keep restored-prefix VLM prefill inputs off the default stream (#3305) Qwen ANE prefill timed out on every multimodal prefix-cache hit because the scheduler built the start_offset views on the worker's default stream and get_input_embeddings() left the mRoPE position ids lazy there. Both put a cross-stream fence into the engine-stream chunk graph, and the ANE pack primitive blocks on that buffer mid-eval before the producer buffer is committed, so the driver times it out. Build the views on the engine stream and materialize the captured position state at capture time, the same treatment #3279 gave the text-only seed. --- omlx/engine/vlm.py | 33 ++++++++++++++++++++------- omlx/scheduler.py | 15 +++++++++--- tests/test_scheduler.py | 47 ++++++++++++++++++++++++++++++++++++++ tests/test_vlm_engine.py | 49 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 133 insertions(+), 11 deletions(-) diff --git a/omlx/engine/vlm.py b/omlx/engine/vlm.py index d8cab3d0a8..a8682b6a44 100644 --- a/omlx/engine/vlm.py +++ b/omlx/engine/vlm.py @@ -171,6 +171,28 @@ def _is_missing_chat_template_error(exc: ValueError) -> bool: ) +def _capture_vlm_position_state(lm: Any, extra_kwargs: dict[str, Any]) -> None: + """Copy the language model's per-request mRoPE state into extra_kwargs. + + get_input_embeddings() leaves ``_position_ids`` and ``_rope_deltas`` lazy + on the executor's default stream. They are materialized here because a + lazy default-stream input inside the engine-stream prefill graph deadlocks + the Qwen ANE prefill primitive on restored-prefix requests (#3305, the + same class as the text-only seed in #3279). + """ + if lm is None: + return + pid = getattr(lm, "_position_ids", None) + if pid is not None and "position_ids" not in extra_kwargs: + extra_kwargs["position_ids"] = pid + rd = getattr(lm, "_rope_deltas", None) + if rd is not None: + extra_kwargs["_captured_rope_deltas"] = rd + lazy_state = [v for v in (pid, rd) if isinstance(v, mx.array)] + if lazy_state: + mx.eval(*lazy_state) + + def _apply_minimax_m3_thinking_mode( model_type: str | None, template_kwargs: dict[str, Any], @@ -3274,14 +3296,9 @@ def _prepare_vision_inputs( # global state that gets overwritten by subsequent calls. # Storing per-request ensures correct position computation # when multiple VLM requests are batched. - lm = getattr(self._vlm_model, "language_model", None) - if lm is not None: - pid = getattr(lm, "_position_ids", None) - if pid is not None and "position_ids" not in extra_kwargs: - extra_kwargs["position_ids"] = pid - rd = getattr(lm, "_rope_deltas", None) - if rd is not None: - extra_kwargs["_captured_rope_deltas"] = rd + _capture_vlm_position_state( + getattr(self._vlm_model, "language_model", None), extra_kwargs + ) # Extract token IDs as list token_ids = ( diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 503d54dd56..1bbb6faab5 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -3529,9 +3529,18 @@ def _do_external_prefill( extra_kwargs: dict[str, Any] | None = None if vlm_embeds is not None: embeds_array, extra_kwargs, start_offset = vlm_embeds - embeds_array = embeds_array[:, start_offset:] # skip cached portion - if start_offset > 0 and extra_kwargs: - extra_kwargs = _advance_vlm_extra(extra_kwargs, start_offset) + # Build the restored-prefix views on the engine stream. A + # worker-default-stream slice here sits at the head of the chunk + # graph, so MLX bridges it with a cross-stream fence whose + # producer buffer is only committed at the end of the eval. The + # Qwen ANE prefill primitive commits and waits on the engine + # stream buffer mid-eval, so that fence can never be satisfied + # and the driver times the buffer out (#3305). Fresh prefills + # never hit this: a full-range slice is a no-op in MLX. + with mx.stream(self._stream): + embeds_array = embeds_array[:, start_offset:] # skip cached portion + if start_offset > 0 and extra_kwargs: + extra_kwargs = _advance_vlm_extra(extra_kwargs, start_offset) # Force _position_ids path in language model for cached VLM # prefill. Without this, the delta approach gives sequential # positions to image tokens that need 3D mRoPE positions. diff --git a/tests/test_scheduler.py b/tests/test_scheduler.py index 84b4679557..7d91bc943c 100644 --- a/tests/test_scheduler.py +++ b/tests/test_scheduler.py @@ -6031,6 +6031,53 @@ def test_cached_text_only_mrope_seed_is_materialized(self): assert eval_mock.call_count == 1 assert eval_mock.call_args.args[0] is seeded + def test_cached_vlm_prefill_builds_start_offset_views_on_engine_stream( + self, mock_tokenizer + ): + """Restored-prefix VLM views must not come from the worker default stream. + + A default-stream slice at the head of the chunk graph leaves a + cross-stream fence that the Qwen ANE prefill primitive can never + satisfy while it blocks on the engine-stream buffer (#3305). + """ + model = self._make_vlm_model() + engine_stream = mx.new_stream(mx.cpu) + scheduler = Scheduler( + model=model, tokenizer=mock_tokenizer, stream=engine_stream + ) + request = Request( + request_id="vlm-cached-001", + prompt="describe this image", + sampling_params=SamplingParams(max_tokens=50), + ) + request.prompt_token_ids = [1, 2, 3, 4, 5, 6] + request.num_prompt_tokens = 6 + request.cached_tokens = 2 + embeds = mx.zeros((1, 6, 8)) + extra = {"position_ids": mx.zeros((3, 1, 6), dtype=mx.int32)} + seen_streams = [] + real_advance = scheduler_module._advance_vlm_extra + + def advance_spy(extra_kwargs, n): + seen_streams.append((n, mx.default_stream(mx.cpu))) + return real_advance(extra_kwargs, n) + + with patch.object( + scheduler_module, "_advance_vlm_extra", side_effect=advance_spy + ): + scheduler._do_external_prefill( + request, + tokens=[3, 4, 5, 6], + existing_cache=[], + vlm_embeds=(embeds, extra, 2), + ) + + # First advance skips the cached prefix, second advances past the chunk. + assert seen_streams == [(2, engine_stream), (3, engine_stream)] + chunk_kwargs = model.call_args.kwargs + assert chunk_kwargs["inputs_embeds"].shape == (1, 3, 8) + assert chunk_kwargs["vlm_extra_kwargs"]["position_ids"].shape == (3, 1, 3) + def test_fresh_text_only_prefill_does_not_seed_or_evaluate_mrope(self): previous = mx.array([[123]]) language_model = SimpleNamespace(_rope_deltas=previous) diff --git a/tests/test_vlm_engine.py b/tests/test_vlm_engine.py index fe83957c67..6213b93d45 100644 --- a/tests/test_vlm_engine.py +++ b/tests/test_vlm_engine.py @@ -25,6 +25,8 @@ try: import mlx.core as mx + from omlx.engine import vlm as vlm_module + HAS_MLX = True except ImportError: HAS_MLX = False @@ -2614,3 +2616,50 @@ def _mock_process(messages, tools, kwargs): call_kwargs = engine._engine.generate.call_args.kwargs assert call_kwargs["sampling_params"].frequency_penalty == 0.42 + + +# --------------------------------------------------------------------------- +# TestCaptureVLMPositionState +# --------------------------------------------------------------------------- + + +class TestCaptureVLMPositionState: + """_capture_vlm_position_state() must hand the scheduler concrete arrays. + + get_rope_index() leaves the mRoPE state lazy on the executor's default + stream; a lazy cross-stream input in the engine-stream prefill graph + deadlocks the Qwen ANE prefill primitive on restored prefixes (#3305). + """ + + @pytest.mark.skipif(not HAS_MLX, reason="MLX not available") + def test_captures_and_materializes_lazy_mrope_state(self): + pid = mx.arange(6).reshape(1, 6) + 1 + rd = mx.zeros((1, 1)) - 3 + lm = SimpleNamespace(_position_ids=pid, _rope_deltas=rd) + extra = {} + + with patch.object(vlm_module.mx, "eval", wraps=mx.eval) as eval_mock: + vlm_module._capture_vlm_position_state(lm, extra) + + assert extra["position_ids"] is pid + assert extra["_captured_rope_deltas"] is rd + eval_mock.assert_called_once() + assert [id(a) for a in eval_mock.call_args.args] == [id(pid), id(rd)] + + @pytest.mark.skipif(not HAS_MLX, reason="MLX not available") + def test_existing_position_ids_are_kept(self): + given = mx.zeros((1, 2)) + lm = SimpleNamespace(_position_ids=mx.ones((1, 2)), _rope_deltas=None) + extra = {"position_ids": given} + + vlm_module._capture_vlm_position_state(lm, extra) + + assert extra["position_ids"] is given + assert "_captured_rope_deltas" not in extra + + def test_missing_language_model_is_noop(self): + extra = {} + + vlm_module._capture_vlm_position_state(None, extra) + + assert extra == {} From e467261edc786efd33b1e9023d5c4a827f8aa1c1 Mon Sep 17 00:00:00 2001 From: Wenrui LI Date: Thu, 3 Sep 2026 20:53:27 +0800 Subject: [PATCH 071/132] fix(mac): align the macOS app UI with system conventions (#3376) Standardize control sizing, native button and picker styles, row switches, footers, spacing, and navigation behavior across the macOS settings screens. --- apps/omlx-mac/Sources/AppView/AppView.swift | 33 +++- .../Sources/AppView/Screens/AboutScreen.swift | 4 +- .../AppView/Screens/AccuracyBenchScreen.swift | 6 +- .../AppView/Screens/AppearanceScreen.swift | 31 +--- .../AppView/Screens/ContextBenchScreen.swift | 4 +- .../AppView/Screens/DownloadsScreen.swift | 27 ++- .../AppView/Screens/IntegrationsScreen.swift | 75 +++----- .../Sources/AppView/Screens/LogsScreen.swift | 12 +- .../AppView/Screens/ModelCardSheet.swift | 2 +- .../AppView/Screens/ModelSettingsScreen.swift | 166 +++++++----------- .../AppView/Screens/ModelsScreen.swift | 8 +- .../AppView/Screens/NetworkScreen.swift | 29 +-- .../AppView/Screens/PerformanceScreen.swift | 47 ++--- .../AppView/Screens/ProfileViews.swift | 12 +- .../AppView/Screens/QuantizationScreen.swift | 63 +++---- .../AppView/Screens/SecurityScreen.swift | 17 +- .../AppView/Screens/ServerScreen.swift | 73 +++----- .../AppView/Screens/StatusScreen.swift | 17 +- .../Screens/ThroughputBenchScreen.swift | 98 +++++------ .../Menubar/MenubarMetricPopover.swift | 11 +- .../Sources/Theme/Components/Button.swift | 89 ++++------ .../Sources/Theme/Components/Popup.swift | 76 ++------ .../Sources/Theme/Components/Row.swift | 57 ++++-- .../Theme/Components/ScreenScaffold.swift | 50 +++++- .../Theme/Components/SectionHeader.swift | 4 +- .../Sources/Theme/Components/TextInput.swift | 19 +- apps/omlx-mac/Sources/Theme/Theme.swift | 17 ++ .../Sources/Welcome/WelcomeWindow.swift | 4 +- 28 files changed, 465 insertions(+), 586 deletions(-) diff --git a/apps/omlx-mac/Sources/AppView/AppView.swift b/apps/omlx-mac/Sources/AppView/AppView.swift index 0f5b667624..8f5d6172cb 100644 --- a/apps/omlx-mac/Sources/AppView/AppView.swift +++ b/apps/omlx-mac/Sources/AppView/AppView.swift @@ -21,8 +21,12 @@ struct AppView: View { let theme = scheme == .dark ? OMLXTheme.dark : OMLXTheme.light let section = selectedSection - NavigationSplitView { + // The sidebar is the only way to switch screens, so it must never + // collapse: pin visibility to `.all` and remove the toolbar toggle, + // matching System Settings. + NavigationSplitView(columnVisibility: .constant(.all)) { SettingsSidebar(selection: bindingForSelection()) + .toolbar(removing: .sidebarToggle) } detail: { ContentScaffold(section: section, detailTitle: detailTitle) { screen(for: section) @@ -557,10 +561,37 @@ private struct ContentScaffold: View { } } .navigationTitle(titleText) + .modifier(ToolbarHeightKeeper()) .background(theme.windowBg) } } +/// macOS collapses the unified toolbar to a compact title bar on panes +/// that contribute no toolbar items. With the sidebar toggle removed, +/// only screens with their own items (Logs, Model Settings) kept the +/// full-height bar — so every screen contributes an invisible item to +/// keep the height uniform. On macOS 26 the Liquid Glass capsule that +/// toolbars draw around every item must be hidden explicitly, or the +/// invisible item shows up as a small vertical bar. +private struct ToolbarHeightKeeper: ViewModifier { + func body(content: Content) -> some View { + if #available(macOS 26.0, *) { + content.toolbar { + ToolbarItem { + Color.clear.frame(width: 1, height: 1) + } + .sharedBackgroundVisibility(.hidden) + } + } else { + content.toolbar { + ToolbarItem { + Color.clear.frame(width: 1, height: 1) + } + } + } + } +} + /// Composite identity used by `ContentScaffold`'s deep-link scroll /// `.task(id:)` so the scroll fires whenever either the section or the /// anchor changes — and re-fires if the same anchor is requested twice. diff --git a/apps/omlx-mac/Sources/AppView/Screens/AboutScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/AboutScreen.swift index 22cbad00ad..eab82ee08d 100644 --- a/apps/omlx-mac/Sources/AppView/Screens/AboutScreen.swift +++ b/apps/omlx-mac/Sources/AppView/Screens/AboutScreen.swift @@ -69,9 +69,9 @@ private struct HeroCard: View { .padding(18) .frame(maxWidth: .infinity, alignment: .leading) .background(theme.groupBg) - .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) + .clipShape(RoundedRectangle(cornerRadius: theme.cornerRadius, style: .continuous)) .overlay( - RoundedRectangle(cornerRadius: 12, style: .continuous) + RoundedRectangle(cornerRadius: theme.cornerRadius, style: .continuous) .strokeBorder(theme.groupBorder, lineWidth: 0.5) ) .padding(.horizontal, 14) diff --git a/apps/omlx-mac/Sources/AppView/Screens/AccuracyBenchScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/AccuracyBenchScreen.swift index 99e6f72620..775e3517e0 100644 --- a/apps/omlx-mac/Sources/AppView/Screens/AccuracyBenchScreen.swift +++ b/apps/omlx-mac/Sources/AppView/Screens/AccuracyBenchScreen.swift @@ -198,7 +198,7 @@ private struct ConfigurationSection: View { comment: "Sublabel under the Accuracy Bench model picker")) { Popup( selection: $selectedModelId, - width: 320, + width: .controlWide, options: modelOptions ) } @@ -222,7 +222,7 @@ private struct ConfigurationSection: View { defaultValue: "Enable per-question reasoning traces (slower)", comment: "Sublabel under the Accuracy Bench extended-thinking toggle") ) { - Toggle("", isOn: $enableThinking).labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: $enableThinking) } FreeRow { @@ -417,7 +417,7 @@ private struct BenchmarkCard: View { .foregroundStyle(theme.textTertiary) Popup( selection: $sampleSize, - width: 90, + width: .controlNarrow, options: sampleSizeOptions ) } diff --git a/apps/omlx-mac/Sources/AppView/Screens/AppearanceScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/AppearanceScreen.swift index e01562084d..ca04ecb69c 100644 --- a/apps/omlx-mac/Sources/AppView/Screens/AppearanceScreen.swift +++ b/apps/omlx-mac/Sources/AppView/Screens/AppearanceScreen.swift @@ -46,7 +46,7 @@ struct AppearanceScreen: View { comment: "Appearance row sublabel for the menubar refresh cadence picker" ) ) { - Popup(selection: $refreshInterval, width: 110, options: [ + Popup(selection: $refreshInterval, width: .controlCompact, options: [ (0.5, "0.5 s"), (1.0, "1 s"), (2.0, "2 s"), @@ -65,9 +65,7 @@ struct AppearanceScreen: View { comment: "Appearance row sublabel for the permanent Dock icon toggle" ) ) { - Toggle("", isOn: $showDockIcon) - .labelsHidden() - .toggleStyle(.switch) + RowSwitch(isOn: $showDockIcon) } // Sits right under the Dock toggle because that's where people // look for it — the Dock icon and the menu bar icon read as one @@ -140,7 +138,6 @@ struct AppearanceScreen: View { ) ), ]) - .frame(width: 200) } } @@ -170,9 +167,7 @@ struct AppearanceScreen: View { comment: "Appearance row sublabel for the LIV menubar item toggle" ) ) { - Toggle("", isOn: $showLiveActivity) - .labelsHidden() - .toggleStyle(.switch) + RowSwitch(isOn: $showLiveActivity) } Row( label: String( @@ -186,9 +181,7 @@ struct AppearanceScreen: View { comment: "Appearance row sublabel for the AVG menubar item toggle" ) ) { - Toggle("", isOn: $showAverageActivity) - .labelsHidden() - .toggleStyle(.switch) + RowSwitch(isOn: $showAverageActivity) } Row( label: String( @@ -202,9 +195,7 @@ struct AppearanceScreen: View { comment: "Appearance row sublabel for the ALL menubar item toggle" ) ) { - Toggle("", isOn: $showAlltimeActivity) - .labelsHidden() - .toggleStyle(.switch) + RowSwitch(isOn: $showAlltimeActivity) } Row( label: String( @@ -218,9 +209,7 @@ struct AppearanceScreen: View { comment: "Appearance row sublabel for the CPU usage bar menubar item toggle" ) ) { - Toggle("", isOn: $showCPUItem) - .labelsHidden() - .toggleStyle(.switch) + RowSwitch(isOn: $showCPUItem) } Row( label: String( @@ -234,9 +223,7 @@ struct AppearanceScreen: View { comment: "Appearance row sublabel for the GPU usage bar menubar item toggle" ) ) { - Toggle("", isOn: $showGPUItem) - .labelsHidden() - .toggleStyle(.switch) + RowSwitch(isOn: $showGPUItem) } Row( label: String( @@ -251,9 +238,7 @@ struct AppearanceScreen: View { ), isLast: true ) { - Toggle("", isOn: $showMemoryItem) - .labelsHidden() - .toggleStyle(.switch) + RowSwitch(isOn: $showMemoryItem) } } } diff --git a/apps/omlx-mac/Sources/AppView/Screens/ContextBenchScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/ContextBenchScreen.swift index 4738ce18cc..de5adb7bb3 100644 --- a/apps/omlx-mac/Sources/AppView/Screens/ContextBenchScreen.swift +++ b/apps/omlx-mac/Sources/AppView/Screens/ContextBenchScreen.swift @@ -118,7 +118,7 @@ private struct ConfigurationSection: View { comment: "Sublabel under the Context Bench model picker")) { Popup( selection: $selectedModelId, - width: 320, + width: .controlWide, options: modelOptions ) } @@ -135,7 +135,6 @@ private struct ConfigurationSection: View { (value: $0, label: "\($0 / 1024)k") } ) - .frame(width: 320) .disabled(running) } @@ -162,7 +161,6 @@ private struct ConfigurationSection: View { ], icons: ["arrow.up.left.and.arrow.down.right", "speedometer"] ) - .frame(width: 240) .disabled(running) } diff --git a/apps/omlx-mac/Sources/AppView/Screens/DownloadsScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/DownloadsScreen.swift index 8d51ab91f0..a936cc52bb 100644 --- a/apps/omlx-mac/Sources/AppView/Screens/DownloadsScreen.swift +++ b/apps/omlx-mac/Sources/AppView/Screens/DownloadsScreen.swift @@ -107,13 +107,7 @@ struct DownloadsScreen: View { onShowCard: { repo in vm.showModelCard(repoId: repo) } ) - if let error = vm.lastError { - Text(error) - .font(.omlxText(11)) - .foregroundStyle(.red) - .padding(.horizontal, 18) - .padding(.top, 8) - } + FooterBar(error: vm.lastError) } .task { await vm.start(client: services.client) } .onDisappear { vm.stop() } @@ -134,9 +128,11 @@ struct DownloadsScreen: View { // MARK: - Source switcher -/// Segmented HF / ModelScope toggle pinned at the top of Downloads. When -/// the server's modelscope SDK isn't installed (`/admin/api/ms/status` -/// returns `available: false`), the MS option is disabled with a tooltip +/// HF / ModelScope tabs pinned at the top of Downloads, rendered as a +/// centered segmented control — the macOS convention for top-of-pane tabs +/// (System Settings › Trackpad, Finder settings). When the server's +/// modelscope SDK isn't installed (`/admin/api/ms/status` returns +/// `available: false`), the MS option is disabled with a note underneath /// rather than hidden — so a user looking for it can see why it's not /// usable. private struct SourceSwitcher: View { @@ -144,21 +140,24 @@ private struct SourceSwitcher: View { let msAvailable: Bool var body: some View { - HStack(spacing: 8) { + VStack(spacing: 6) { Segmented( selection: $source, options: DownloadSource.allCases.map { ($0, $0.label) } ) .disabled(!msAvailable) + // A fixed frame makes the picker split the width into equal + // tab-sized segments instead of hugging the labels. + .frame(width: 280) if !msAvailable { Text(String(localized: "downloads.source.ms_unavailable", defaultValue: "ModelScope SDK unavailable in this build", - comment: "Inline note shown beside the source switcher when the ModelScope SDK isn't installed")) + comment: "Note shown under the source switcher when the ModelScope SDK isn't installed")) .font(.omlxText(10.5)) .foregroundStyle(.secondary) } - Spacer(minLength: 0) } + .frame(maxWidth: .infinity) .padding(.horizontal, 14) .padding(.top, 4) .padding(.bottom, 8) @@ -803,7 +802,7 @@ private struct SuggestedSection: View { HStack(spacing: 6) { Popup( selection: $sort, - width: 170, + width: .controlMedium, options: SuggestedSort.allCases.map { ($0, $0.label) } ) Button { diff --git a/apps/omlx-mac/Sources/AppView/Screens/IntegrationsScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/IntegrationsScreen.swift index c67f516977..ccc08aba16 100644 --- a/apps/omlx-mac/Sources/AppView/Screens/IntegrationsScreen.swift +++ b/apps/omlx-mac/Sources/AppView/Screens/IntegrationsScreen.swift @@ -25,13 +25,7 @@ struct IntegrationsScreen: View { OtherIntegrationsSection(vm: vm, client: services.client) MCPSection(vm: vm, client: services.client) - if let error = vm.lastError { - Text(error) - .font(.omlxText(11)) - .foregroundStyle(.red) - .padding(.horizontal, 18) - .padding(.top, 8) - } + FooterBar(error: vm.lastError) } .task { await vm.load(client: services.client) } } @@ -79,7 +73,7 @@ private struct ClaudeCodeSection: View { selection: vm.bind($vm.opusModel, save: { Task { await vm.save(.opusModel, client: client) } }), - width: 220, + width: .controlMedium, options: vm.modelOptions ) } @@ -90,7 +84,7 @@ private struct ClaudeCodeSection: View { selection: vm.bind($vm.sonnetModel, save: { Task { await vm.save(.sonnetModel, client: client) } }), - width: 220, + width: .controlMedium, options: vm.modelOptions ) } @@ -106,7 +100,7 @@ private struct ClaudeCodeSection: View { selection: vm.bind($vm.haikuModel, save: { Task { await vm.save(.haikuModel, client: client) } }), - width: 220, + width: .controlMedium, options: vm.modelOptions ) } @@ -120,10 +114,9 @@ private struct ClaudeCodeSection: View { comment: "Sublabel for the context scaling toggle"), isLast: !vm.contextScaling ) { - Toggle("", isOn: vm.bind($vm.contextScaling, save: { + RowSwitch(isOn: vm.bind($vm.contextScaling, save: { Task { await vm.save(.contextScaling, client: client) } })) - .labelsHidden().toggleStyle(.switch) } if vm.contextScaling { Row( @@ -139,14 +132,13 @@ private struct ClaudeCodeSection: View { text: $vm.targetContextSizeText, mono: true, suffix: "tk", - width: 130 + width: .controlCompact ) } } } if vm.contextScaling { - HStack { - Spacer() + FooterBar { Button(String(localized: "integrations.target_context.apply", defaultValue: "Apply", comment: "Apply button for the Claude Code target context size field")) { @@ -155,8 +147,6 @@ private struct ClaudeCodeSection: View { .buttonStyle(.omlx(.primary)) .disabled(!vm.hasPendingContextSizeChange) } - .padding(.horizontal, 18) - .padding(.top, 6) } } } @@ -237,36 +227,18 @@ private struct CommandBlock: View { .strokeBorder(theme.groupBorder, lineWidth: 0.5) ) - CopyButton(value: command) - .padding(.top, 6) - .padding(.trailing, 8) - } - } -} - -private struct CopyButton: View { - let value: String - @State private var copied = false - @Environment(\.omlxTheme) private var theme - - var body: some View { - Button { - let pb = NSPasteboard.general - pb.clearContents() - pb.setString(value, forType: .string) - copied = true - DispatchQueue.main.asyncAfter(deadline: .now() + 1.4) { - copied = false - } - } label: { - Image(systemName: copied ? "checkmark" : "document.on.document") - .font(.system(size: 11, weight: .medium)) - .foregroundStyle(copied ? theme.successText : theme.textSecondary) - .padding(5) - .background(theme.controlBg) - .clipShape(RoundedRectangle(cornerRadius: 5, style: .continuous)) + // Same quiet copy affordance as `CodeChip`/`CopyIconButton` + // everywhere else — the previous locally-drawn boxed button was a + // second copy-button style. + CopyIconButton( + value: command, + helpText: String(localized: "integrations.command.copy", + defaultValue: "Copy command", + comment: "Tooltip for the copy button on a shell command block") + ) + .padding(.top, 4) + .padding(.trailing, 4) } - .buttonStyle(.plain) } } @@ -392,7 +364,7 @@ private struct IntegrationRow: View { Spacer(minLength: 12) Popup( selection: modelBinding, - width: 220, + width: .controlMedium, options: modelOptions ) } @@ -413,7 +385,7 @@ private struct IntegrationRow: View { Spacer(minLength: 12) Popup( selection: profileBinding, - width: 160, + width: .controlMedium, options: [ ("minimal", String(localized: "integrations.openclaw.profile.minimal", defaultValue: "Minimal", @@ -478,12 +450,11 @@ private struct MCPSection: View { text: $vm.mcpConfigPath, placeholder: "/path/to/mcp.json", mono: true, - width: 320 + width: .controlWide ) } } - HStack { - Spacer() + FooterBar { Button(String(localized: "integrations.mcp.apply", defaultValue: "Apply", comment: "Apply button for the MCP config path")) { @@ -492,7 +463,5 @@ private struct MCPSection: View { .buttonStyle(.omlx(.primary)) .disabled(!vm.hasPendingMCPChanges) } - .padding(.horizontal, 18) - .padding(.top, 6) } } diff --git a/apps/omlx-mac/Sources/AppView/Screens/LogsScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/LogsScreen.swift index 5b6478728c..fb32b41e90 100644 --- a/apps/omlx-mac/Sources/AppView/Screens/LogsScreen.swift +++ b/apps/omlx-mac/Sources/AppView/Screens/LogsScreen.swift @@ -32,7 +32,7 @@ struct LogsScreen: View { isLast: true) { Popup( selection: $vm.selectedFile, - width: 220, + width: .controlMedium, options: vm.fileOptions ) } @@ -45,13 +45,7 @@ struct LogsScreen: View { .padding(.bottom, 8) .frame(maxWidth: .infinity, maxHeight: .infinity) - if let error = vm.lastError { - Text(error) - .font(.omlxText(11)) - .foregroundStyle(.red) - .padding(.horizontal, 18) - .padding(.top, 4) - } + FooterBar(error: vm.lastError) } .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) .toolbar { @@ -95,7 +89,7 @@ struct LogsScreen: View { Popup( selection: $vm.lines, - width: 110, + width: .controlCompact, options: lineOptions ) } diff --git a/apps/omlx-mac/Sources/AppView/Screens/ModelCardSheet.swift b/apps/omlx-mac/Sources/AppView/Screens/ModelCardSheet.swift index 2a8e6c4e78..f0d585442d 100644 --- a/apps/omlx-mac/Sources/AppView/Screens/ModelCardSheet.swift +++ b/apps/omlx-mac/Sources/AppView/Screens/ModelCardSheet.swift @@ -491,7 +491,7 @@ struct ModelCardSheet: View { .keyboardShortcut(.defaultAction) } } - .padding(.horizontal, 18) + .padding(.horizontal, 20) .padding(.vertical, 12) } diff --git a/apps/omlx-mac/Sources/AppView/Screens/ModelSettingsScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/ModelSettingsScreen.swift index aa41666594..886e03d632 100644 --- a/apps/omlx-mac/Sources/AppView/Screens/ModelSettingsScreen.swift +++ b/apps/omlx-mac/Sources/AppView/Screens/ModelSettingsScreen.swift @@ -53,13 +53,7 @@ struct ModelSettingsScreen: View { AdvancedTab(vm: vm, client: services.client) } - if let error = vm.lastError { - Text(error) - .font(.omlxText(11)) - .foregroundStyle(.red) - .padding(.horizontal, 18) - .padding(.top, 8) - } + FooterBar(error: vm.lastError) } .toolbar { ToolbarItem(placement: .navigation) { @@ -514,7 +508,7 @@ private struct BasicTab: View { sublabel: String(localized: "settings.basic.alias.sub", defaultValue: "Falls back to the model id", comment: "Sublabel for the model alias field")) { - TextInput(text: $vm.alias, placeholder: vm.modelID, mono: true, width: 220) + TextInput(text: $vm.alias, placeholder: vm.modelID, mono: true, width: .controlMedium) .onSubmit { Task { await vm.save(.alias, client: client) } } } Row(label: String(localized: "settings.basic.model_type.label", @@ -522,7 +516,7 @@ private struct BasicTab: View { comment: "Row label for the model type override popup")) { Popup( selection: vm.bind($vm.modelTypeOverride, save: { Task { await vm.save(.modelType, client: client) } }), - width: 170, + width: .controlMedium, options: ModelSettingsScreenVM.modelTypeOptions ) } @@ -532,7 +526,7 @@ private struct BasicTab: View { sublabel: String(localized: "settings.basic.context_window.sub", defaultValue: "Maximum tokens per request", comment: "Sublabel for the context window field")) { - TextInput(text: vm.bindProfile($vm.contextLength), mono: true, suffix: "tk", width: 110) + TextInput(text: vm.bindProfile($vm.contextLength), mono: true, suffix: "tk", width: .controlCompact) } Row(label: String(localized: "settings.basic.max_tokens.label", defaultValue: "Max Tokens", @@ -544,7 +538,7 @@ private struct BasicTab: View { placeholder: String(localized: "settings.basic.max_tokens.placeholder", defaultValue: "Default", comment: "Placeholder shown when Max Tokens is empty (server default applies)"), - mono: true, width: 110) + mono: true, width: .controlCompact) } Row(label: String(localized: "settings.basic.temperature.label", defaultValue: "Temperature", @@ -552,7 +546,7 @@ private struct BasicTab: View { sublabel: String(localized: "settings.basic.temperature.sub", defaultValue: "Sampling randomness (≥ 0). 0 = deterministic.", comment: "Sublabel describing the temperature field range")) { - TextInput(text: vm.bindProfile($vm.temperature), placeholder: "0.7", mono: true, width: 90) + TextInput(text: vm.bindProfile($vm.temperature), placeholder: "0.7", mono: true, width: .controlNarrow) } if !vm.isDiffusionModel { Row(label: String(localized: "settings.basic.top_p.label", @@ -561,7 +555,7 @@ private struct BasicTab: View { sublabel: String(localized: "settings.basic.top_p.sub", defaultValue: "Nucleus sampling cutoff (0 < p ≤ 1).", comment: "Sublabel describing the top-p valid range")) { - TextInput(text: vm.bindProfile($vm.topP), mono: true, width: 90) + TextInput(text: vm.bindProfile($vm.topP), mono: true, width: .controlNarrow) } Row(label: String(localized: "settings.basic.top_k.label", defaultValue: "Top K", @@ -569,7 +563,7 @@ private struct BasicTab: View { sublabel: String(localized: "settings.basic.top_k.sub", defaultValue: "Limit candidates to top K (positive integer).", comment: "Sublabel describing the top-k field")) { - TextInput(text: vm.bindProfile($vm.topK), mono: true, width: 90) + TextInput(text: vm.bindProfile($vm.topK), mono: true, width: .controlNarrow) } Row(label: String(localized: "settings.basic.min_p.label", defaultValue: "Min P", @@ -577,7 +571,7 @@ private struct BasicTab: View { sublabel: String(localized: "settings.basic.min_p.sub", defaultValue: "Minimum probability floor (0 ≤ p ≤ 1).", comment: "Sublabel describing the min-p field range")) { - TextInput(text: vm.bindProfile($vm.minP), mono: true, width: 90) + TextInput(text: vm.bindProfile($vm.minP), mono: true, width: .controlNarrow) } Row(label: String(localized: "settings.basic.repetition_penalty.label", defaultValue: "Repetition Penalty", @@ -587,7 +581,7 @@ private struct BasicTab: View { : String(localized: "settings.basic.repetition_penalty.sub", defaultValue: "Penalize repeated tokens (−2 to 2).", comment: "Sublabel describing repetition-penalty range")) { - TextInput(text: vm.bindProfile($vm.repetitionPenalty), mono: true, width: 90) + TextInput(text: vm.bindProfile($vm.repetitionPenalty), mono: true, width: .controlNarrow) .disabled(vm.vlmMtpEnabled) .help(vm.vlmMtpEnabled ? vm.vlmMtpProcessorLockedReason : "") } @@ -599,7 +593,7 @@ private struct BasicTab: View { : String(localized: "settings.basic.presence_penalty.sub", defaultValue: "Penalize tokens already present (−2 to 2).", comment: "Sublabel describing presence-penalty range")) { - TextInput(text: vm.bindProfile($vm.presencePenalty), mono: true, width: 90) + TextInput(text: vm.bindProfile($vm.presencePenalty), mono: true, width: .controlNarrow) .disabled(vm.vlmMtpEnabled) .help(vm.vlmMtpEnabled ? vm.vlmMtpProcessorLockedReason : "") } @@ -617,7 +611,7 @@ private struct BasicTab: View { placeholder: String(localized: "settings.basic.ttl.placeholder", defaultValue: "No TTL", comment: "Placeholder shown when no TTL is configured"), - mono: true, suffix: "s", width: 110) + mono: true, suffix: "s", width: .controlCompact) .onSubmit { Task { await vm.save(.ttl, client: client) } } } } @@ -708,8 +702,7 @@ private struct AdvancedTab: View { sublabel: String(localized: "settings.advanced.enable_thinking.sub", defaultValue: "Enable reasoning/thinking mode for this model", comment: "Sublabel for the enable-thinking toggle")) { - Toggle("", isOn: vm.bindProfile($vm.enableThinking)) - .labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: vm.bindProfile($vm.enableThinking)) } if vm.isQwen4Exp && vm.qwen4PleSsdOffloadSupported { Row(label: String(localized: "settings.advanced.qwen4_ssd_offload.label", @@ -722,7 +715,7 @@ private struct AdvancedTab: View { : String(localized: "settings.advanced.qwen4_ssd_offload.sub", defaultValue: "Keep the PLE N-gram table on SSD to save memory. Prefill can be slower after context changes.", comment: "Sublabel for the Qwen4 PLE SSD mmap toggle")) { - Toggle("", isOn: vm.bind( + RowSwitch(isOn: vm.bind( $vm.qwen4PleSsdOffload, save: { Task { @@ -730,8 +723,6 @@ private struct AdvancedTab: View { } } )) - .labelsHidden() - .toggleStyle(.switch) .disabled(vm.qwen4PleSsdOffloadForced) } } @@ -744,10 +735,9 @@ private struct AdvancedTab: View { HStack(spacing: 8) { if vm.thinkingBudgetEnabled { TextInput(text: vm.bindProfile($vm.thinkingBudgetTokens), - mono: true, suffix: "tk", width: 110) + mono: true, suffix: "tk", width: .controlCompact) } - Toggle("", isOn: vm.bindProfile($vm.thinkingBudgetEnabled)) - .labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: vm.bindProfile($vm.thinkingBudgetEnabled)) } } Row(label: String(localized: "settings.advanced.tool_result_limit.label", @@ -760,10 +750,9 @@ private struct AdvancedTab: View { if vm.limitToolResults { TextInput(text: vm.bindProfile($vm.toolResultLimitTokens), placeholder: "4096", - mono: true, suffix: "tk", width: 110) + mono: true, suffix: "tk", width: .controlCompact) } - Toggle("", isOn: vm.bindProfile($vm.limitToolResults)) - .labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: vm.bindProfile($vm.limitToolResults)) } } Row(label: String(localized: "settings.advanced.force_sampling.label", @@ -772,8 +761,7 @@ private struct AdvancedTab: View { sublabel: String(localized: "settings.advanced.force_sampling.sub", defaultValue: "Override request sampling parameters with configured values", comment: "Sublabel for the force-sampling toggle")) { - Toggle("", isOn: vm.bindProfile($vm.forceSampling)) - .labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: vm.bindProfile($vm.forceSampling)) } Row(label: String(localized: "settings.advanced.reasoning_parser.label", defaultValue: "Reasoning Parser", @@ -782,7 +770,7 @@ private struct AdvancedTab: View { defaultValue: "Override the chain-of-thought parser. Leave empty to use the model's default.", comment: "Sublabel for the reasoning-parser override field")) { TextInput(text: vm.bindProfile($vm.reasoningParser), - placeholder: "auto", mono: true, width: 150) + placeholder: "auto", mono: true, width: .controlCompact) } } Row(label: String(localized: "settings.advanced.pin_memory.label", @@ -791,10 +779,9 @@ private struct AdvancedTab: View { sublabel: String(localized: "settings.advanced.pin_memory.sub", defaultValue: "Keep this model resident between requests", comment: "Sublabel for the pin-in-memory toggle")) { - Toggle("", isOn: vm.bind($vm.isPinned, save: { + RowSwitch(isOn: vm.bind($vm.isPinned, save: { Task { await vm.save(.isPinned, client: client) } })) - .labelsHidden().toggleStyle(.switch) } Row(label: String(localized: "settings.advanced.favorite.label", defaultValue: "Favorite", @@ -802,10 +789,9 @@ private struct AdvancedTab: View { sublabel: String(localized: "settings.advanced.favorite.sub", defaultValue: "List this model first in model lists", comment: "Sublabel for the favorite toggle")) { - Toggle("", isOn: vm.bind($vm.isFavorite, save: { + RowSwitch(isOn: vm.bind($vm.isFavorite, save: { Task { await vm.save(.isFavorite, client: client) } })) - .labelsHidden().toggleStyle(.switch) } // Security-sensitive row — flagged red to match the HTML // editor's visual treatment. HF custom-code execution gives @@ -818,10 +804,9 @@ private struct AdvancedTab: View { defaultValue: "Execute HuggingFace custom model code. Only enable for models you trust. Per-model only — never inherited from profiles.", comment: "Sublabel describing the security implications of trust-remote-code"), isLast: true) { - Toggle("", isOn: vm.bind($vm.trustRemoteCode, save: { + RowSwitch(isOn: vm.bind($vm.trustRemoteCode, save: { Task { await vm.save(.trustRemoteCode, client: client) } })) - .labelsHidden().toggleStyle(.switch) .tint(theme.redDot) } } @@ -938,7 +923,7 @@ private struct EntryEditor: View { let client: OMLXClient let entryID: UUID - private static let reasoningEffortValueWidth: CGFloat = 130 + private static let reasoningEffortValueWidth: CGFloat = .controlCompact @Environment(\.omlxTheme) private var theme @@ -1009,7 +994,7 @@ private struct EntryEditor: View { HStack(spacing: 8) { Popup( selection: vm.bindProfile(binding.value), - width: 130, + width: .controlCompact, options: [("true", "true"), ("false", "false")] ) forceCheckbox @@ -1076,7 +1061,6 @@ private struct EntryEditor: View { Popup( selection: vm.bindProfile(binding.value), width: Self.reasoningEffortValueWidth, - fillsWidth: true, options: ChatTemplateKwargsCodec.reasoningEffortPresets.map { ($0, $0) } @@ -1115,8 +1099,7 @@ private struct AccelerationSection: View { comment: "Row label for the Lightning MTP toggle"), sublabel: mtpSublabel, isLast: true) { - Toggle("", isOn: vm.bindProfile($vm.mtpEnabled)) - .labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: vm.bindProfile($vm.mtpEnabled)) .disabled(mtpToggleDisabled) .help(vm.mtpConflictReason ?? vm.model?.mtpCompatibilityReason ?? "") } @@ -1162,8 +1145,7 @@ private struct ExperimentalSection: View { sublabel: String(localized: "settings.experimental.qwen_ane.sub", defaultValue: "Split fixed-shape Qwen 3.5/3.6/3.8 prompt processing across both ANEs and the GPU. Experimental private API; takes effect after the model reloads.", comment: "Sublabel describing Qwen ANE/GPU prefill acceleration")) { - Toggle("", isOn: vm.bindProfile($vm.qwen35AnePrefillEnabled)) - .labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: vm.bindProfile($vm.qwen35AnePrefillEnabled)) } Row(label: String(localized: "settings.experimental.qwen_ane.tuner.label", defaultValue: "Tune ANE Split", @@ -1291,7 +1273,7 @@ private struct ExperimentalSection: View { TextInput(text: vm.bindProfile($vm.qwen35AnePrefillSequenceLength), placeholder: "2048", mono: true, isNumeric: true, range: 1024...262_144, - step: 64, width: 190) + step: 64, width: .controlCompact) } Row(label: String(localized: "settings.experimental.qwen_ane.tail_padding.label", defaultValue: "Pad Intermediate Tails From", @@ -1302,7 +1284,7 @@ private struct ExperimentalSection: View { TextInput(text: vm.bindProfile($vm.qwen35AnePrefillTailPaddingMinTokens), placeholder: "0", mono: true, isNumeric: true, range: 0...262_143, - step: 1, width: 190) + step: 1, width: .controlCompact) } Row(label: String(localized: "settings.experimental.qwen_ane.mlp_fraction.label", defaultValue: "MLP on ANE", @@ -1313,7 +1295,7 @@ private struct ExperimentalSection: View { TextInput(text: vm.bindProfile($vm.qwen35AnePrefillFraction), placeholder: "0.53", mono: true, isNumeric: true, range: 0.05...0.90, - step: 0.005, width: 190) + step: 0.005, width: .controlCompact) } Row(label: String(localized: "settings.experimental.qwen_ane.mlp_layers.label", defaultValue: "MLP Layer Limit", @@ -1324,7 +1306,7 @@ private struct ExperimentalSection: View { TextInput(text: vm.bindProfile($vm.qwen35AnePrefillMaxLayers), placeholder: "64", mono: true, isNumeric: true, range: 1...256, - step: 1, width: 190) + step: 1, width: .controlCompact) } Row(label: String(localized: "settings.experimental.qwen_ane.dual.label", defaultValue: "Use Both ANEs", @@ -1332,8 +1314,7 @@ private struct ExperimentalSection: View { sublabel: String(localized: "settings.experimental.qwen_ane.dual.sub", defaultValue: "Pin one resident procedure bank to each physical ANE. Recommended on M3 Ultra.", comment: "Sublabel describing dual-ANE Qwen prefill")) { - Toggle("", isOn: vm.bindProfile($vm.qwen35AnePrefillDualAne)) - .labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: vm.bindProfile($vm.qwen35AnePrefillDualAne)) } Row(label: String(localized: "settings.experimental.qwen_ane.cpu.label", defaultValue: "Share MLP Work with CPU", @@ -1341,8 +1322,7 @@ private struct ExperimentalSection: View { sublabel: String(localized: "settings.experimental.qwen_ane.cpu.sub", defaultValue: "Requires a separate q4 checkpoint clone whose floating tensors are FP16. Retune the ANE MLP share when enabled.", comment: "Constraint and tuning guidance for Qwen CPU prefill sharing")) { - Toggle("", isOn: vm.bindProfile($vm.qwen35AnePrefillCpuEnabled)) - .labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: vm.bindProfile($vm.qwen35AnePrefillCpuEnabled)) } if vm.qwen35AnePrefillCpuEnabled { Row(label: String(localized: "settings.experimental.qwen_ane.cpu_fraction.label", @@ -1354,7 +1334,7 @@ private struct ExperimentalSection: View { TextInput(text: vm.bindProfile($vm.qwen35AnePrefillCpuFraction), placeholder: "0.135", mono: true, isNumeric: true, range: 0...0.25, - step: 0.005, width: 190) + step: 0.005, width: .controlCompact) } Row(label: String(localized: "settings.experimental.qwen_ane.cpu_threads.label", defaultValue: "CPU Workers", @@ -1365,7 +1345,7 @@ private struct ExperimentalSection: View { TextInput(text: vm.bindProfile($vm.qwen35AnePrefillCpuThreads), placeholder: "8", mono: true, isNumeric: true, range: 0...64, - step: 1, width: 190) + step: 1, width: .controlCompact) } Row(label: String(localized: "settings.experimental.qwen_ane.cpu_down_fraction.label", defaultValue: "Down Projection on CPU", @@ -1376,7 +1356,7 @@ private struct ExperimentalSection: View { TextInput(text: vm.bindProfile($vm.qwen35AnePrefillCpuDownFraction), placeholder: "0", mono: true, isNumeric: true, range: 0...0.50, - step: 0.005, width: 190) + step: 0.005, width: .controlCompact) } Row(label: String(localized: "settings.experimental.qwen_ane.cpu_gdn_fraction.label", defaultValue: "GDN on CPU", @@ -1387,7 +1367,7 @@ private struct ExperimentalSection: View { TextInput(text: vm.bindProfile($vm.qwen35AnePrefillCpuGdnFraction), placeholder: "0", mono: true, isNumeric: true, range: 0...0.50, - step: 0.005, width: 190) + step: 0.005, width: .controlCompact) } Row(label: String(localized: "settings.experimental.qwen_ane.cpu_scheduler.label", defaultValue: "Performance-Aware Scheduling", @@ -1395,8 +1375,7 @@ private struct ExperimentalSection: View { sublabel: String(localized: "settings.experimental.qwen_ane.cpu_scheduler.sub", defaultValue: "Distributes independent CPU shards across processor clusters and falls back automatically when unsupported.", comment: "Sublabel explaining performance-aware CPU scheduling")) { - Toggle("", isOn: vm.bindProfile($vm.qwen35AnePrefillCpuSharedResource)) - .labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: vm.bindProfile($vm.qwen35AnePrefillCpuSharedResource)) } } Row(label: String(localized: "settings.experimental.qwen_ane.gdn.label", @@ -1405,8 +1384,7 @@ private struct ExperimentalSection: View { sublabel: String(localized: "settings.experimental.qwen_ane.gdn.sub", defaultValue: "Also split eligible GDN z+qkv input projections across ANE and GPU.", comment: "Sublabel describing Qwen GDN ANE acceleration")) { - Toggle("", isOn: vm.bindProfile($vm.qwen35AnePrefillGdn)) - .labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: vm.bindProfile($vm.qwen35AnePrefillGdn)) } if vm.qwen35AnePrefillGdn { Row(label: String(localized: "settings.experimental.qwen_ane.gdn_fraction.label", @@ -1418,7 +1396,7 @@ private struct ExperimentalSection: View { TextInput(text: vm.bindProfile($vm.qwen35AnePrefillGdnFraction), placeholder: "0.5", mono: true, isNumeric: true, range: 0.05...0.90, - step: 0.005, width: 190) + step: 0.005, width: .controlCompact) } Row(label: String(localized: "settings.experimental.qwen_ane.gdn_layers.label", defaultValue: "GDN Layer Limit", @@ -1429,7 +1407,7 @@ private struct ExperimentalSection: View { TextInput(text: vm.bindProfile($vm.qwen35AnePrefillGdnMaxLayers), placeholder: "48", mono: true, isNumeric: true, range: 0...256, - step: 1, width: 190) + step: 1, width: .controlCompact) } } } @@ -1444,12 +1422,11 @@ private struct ExperimentalSection: View { if vm.turboquantKvEnabled { Popup( selection: vm.bindProfile($vm.turboquantKvBits), - width: 120, + width: .controlCompact, options: ModelSettingsScreenVM.turboquantKvBitsOptions ) } - Toggle("", isOn: vm.bindProfile($vm.turboquantKvEnabled)) - .labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: vm.bindProfile($vm.turboquantKvEnabled)) .disabled(vm.vlmMtpEnabled) .help(vm.vlmMtpEnabled ? vlmMtpOwnsSpeculativePathReason : "") } @@ -1467,10 +1444,9 @@ private struct ExperimentalSection: View { HStack(spacing: 8) { if vm.indexCacheEnabled { TextInput(text: vm.bindProfile($vm.indexCacheFreq), - placeholder: "4", mono: true, width: 80) + placeholder: "4", mono: true, width: .controlNarrow) } - Toggle("", isOn: vm.bindProfile($vm.indexCacheEnabled)) - .labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: vm.bindProfile($vm.indexCacheEnabled)) } } } @@ -1480,8 +1456,7 @@ private struct ExperimentalSection: View { defaultValue: "SpecPrefill", comment: "Row label for the SpecPrefill toggle"), sublabel: specprefillSublabel) { - Toggle("", isOn: vm.bindProfile($vm.specprefillEnabled)) - .labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: vm.bindProfile($vm.specprefillEnabled)) .disabled(vm.vlmMtpEnabled) .help(vm.vlmMtpEnabled ? vlmMtpOwnsSpeculativePathReason : "") } @@ -1494,7 +1469,7 @@ private struct ExperimentalSection: View { comment: "Sublabel for the SpecPrefill draft-model picker")) { Popup( selection: vm.bindProfile($vm.specprefillDraftModel), - width: 260, + width: .controlWide, options: vm.draftModelOptions() ) } @@ -1503,7 +1478,7 @@ private struct ExperimentalSection: View { comment: "Row label for the SpecPrefill keep-rate dropdown")) { Popup( selection: vm.bindProfile($vm.specprefillKeepPct), - width: 320, + width: .controlWide, options: ModelSettingsScreenVM.specprefillKeepPctOptions ) } @@ -1514,7 +1489,7 @@ private struct ExperimentalSection: View { defaultValue: "Min prompt tokens to trigger (shorter prompts use full prefill).", comment: "Sublabel for the SpecPrefill threshold field")) { TextInput(text: vm.bindProfile($vm.specprefillThreshold), - placeholder: "8192", mono: true, suffix: "tk", width: 110) + placeholder: "8192", mono: true, suffix: "tk", width: .controlCompact) } } @@ -1523,8 +1498,7 @@ private struct ExperimentalSection: View { defaultValue: "DFlash", comment: "Row label for the DFlash toggle"), sublabel: dflashSublabel) { - Toggle("", isOn: vm.bindProfile($vm.dflashEnabled)) - .labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: vm.bindProfile($vm.dflashEnabled)) .disabled(dflashToggleDisabled) .help(dflashHelp) } @@ -1534,7 +1508,7 @@ private struct ExperimentalSection: View { comment: "Row label for the DFlash draft-model picker")) { Popup( selection: vm.bindProfile($vm.dflashDraftModel), - width: 260, + width: .controlWide, options: vm.draftModelOptions() ) } @@ -1544,8 +1518,7 @@ private struct ExperimentalSection: View { sublabel: String(localized: "settings.experimental.dflash.draft_quant.sub", defaultValue: "Enable quantization for the draft model (weight, activation bits & group size).", comment: "Sublabel for the DFlash draft quantization toggle")) { - Toggle("", isOn: vm.bindProfile($vm.dflashDraftQuantEnabled)) - .labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: vm.bindProfile($vm.dflashDraftQuantEnabled)) } if vm.dflashDraftQuantEnabled { Row(label: String(localized: "settings.experimental.dflash.draft_quant_weight.label", @@ -1553,7 +1526,7 @@ private struct ExperimentalSection: View { comment: "Row label for the DFlash draft quantization weight bits picker")) { Popup( selection: vm.bindProfile($vm.dflashDraftQuantWeightBits), - width: 110, + width: .controlCompact, options: ModelSettingsScreenVM.dflashDraftQuantWeightBitsOptions ) } @@ -1562,7 +1535,7 @@ private struct ExperimentalSection: View { comment: "Row label for the DFlash draft quantization activation bits picker")) { Popup( selection: vm.bindProfile($vm.dflashDraftQuantActivationBits), - width: 110, + width: .controlCompact, options: ModelSettingsScreenVM.dflashDraftQuantActivationBitsOptions ) } @@ -1571,7 +1544,7 @@ private struct ExperimentalSection: View { comment: "Row label for the DFlash draft quantization group size picker")) { Popup( selection: vm.bindProfile($vm.dflashDraftQuantGroupSize), - width: 110, + width: .controlCompact, options: ModelSettingsScreenVM.dflashDraftQuantGroupSizeOptions ) } @@ -1586,7 +1559,7 @@ private struct ExperimentalSection: View { placeholder: String(localized: "settings.experimental.dflash.max_ctx.placeholder", defaultValue: "unlimited", comment: "Placeholder shown when DFlash max-context is unset (no cap)"), - mono: true, suffix: "tk", width: 130) + mono: true, suffix: "tk", width: .controlCompact) } Row(label: String(localized: "settings.experimental.dflash.verify_mode.label", defaultValue: "Verify Mode", @@ -1596,7 +1569,7 @@ private struct ExperimentalSection: View { comment: "Sublabel for the DFlash verify mode picker")) { Popup( selection: vm.bindProfile($vm.dflashVerifyMode), - width: 140, + width: .controlMedium, options: ModelSettingsScreenVM.dflashVerifyModeOptions ) } @@ -1607,7 +1580,7 @@ private struct ExperimentalSection: View { defaultValue: "Draft model sliding-attention window. Empty = dflash default (2048).", comment: "Sublabel for the DFlash draft window size field")) { TextInput(text: vm.bindProfile($vm.dflashDraftWindowSize), - placeholder: "2048", mono: true, width: 110) + placeholder: "2048", mono: true, width: .controlCompact) } Row(label: String(localized: "settings.experimental.dflash.sink_size.label", defaultValue: "Draft Sink Size", @@ -1616,7 +1589,7 @@ private struct ExperimentalSection: View { defaultValue: "Attention-sink tokens always kept in the window. Empty = dflash default (0).", comment: "Sublabel for the DFlash draft sink size field")) { TextInput(text: vm.bindProfile($vm.dflashDraftSinkSize), - placeholder: "0", mono: true, width: 110) + placeholder: "0", mono: true, width: .controlCompact) } Row(label: String(localized: "settings.experimental.dflash.block_size.label", defaultValue: "Runtime Block Size", @@ -1625,7 +1598,7 @@ private struct ExperimentalSection: View { defaultValue: "Maximum draft and verify tokens per cycle. Empty = checkpoint default.", comment: "Sublabel for the DFlash runtime block size field")) { TextInput(text: vm.bindProfile($vm.dflashBlockSize), - placeholder: "checkpoint", mono: true, width: 110) + placeholder: "checkpoint", mono: true, width: .controlCompact) } Row(label: String(localized: "settings.experimental.dflash.mem_cache.label", defaultValue: "DFlash in-memory cache", @@ -1636,10 +1609,9 @@ private struct ExperimentalSection: View { HStack(spacing: 8) { if vm.dflashInMemoryCache { TextInput(text: vm.bindProfile($vm.dflashInMemoryCacheGib), - placeholder: "8", mono: true, suffix: "GiB", width: 110) + placeholder: "8", mono: true, suffix: "GiB", width: .controlCompact) } - Toggle("", isOn: vm.bindProfile($vm.dflashInMemoryCache)) - .labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: vm.bindProfile($vm.dflashInMemoryCache)) } } if vm.dflashInMemoryCache { @@ -1650,15 +1622,14 @@ private struct ExperimentalSection: View { defaultValue: "Maximum prefix snapshots kept in RAM. Each entry stores KV + draft GDN state.", comment: "Sublabel for the DFlash L1 cache max entries field")) { TextInput(text: vm.bindProfile($vm.dflashInMemoryCacheMaxEntries), - placeholder: "4", mono: true, width: 110) + placeholder: "4", mono: true, width: .controlCompact) } } Row(label: String(localized: "settings.experimental.dflash.ssd_cache.label", defaultValue: "DFlash SSD cache", comment: "Row label for the DFlash L2 SSD cache toggle"), sublabel: dflashSsdSublabel) { - Toggle("", isOn: vm.bindProfile($vm.dflashSsdCache)) - .labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: vm.bindProfile($vm.dflashSsdCache)) .disabled(!(vm.model?.dflashSsdCacheAvailable ?? false) || !vm.dflashInMemoryCache) } if vm.dflashSsdCache && (vm.model?.dflashSsdCacheAvailable ?? false) { @@ -1669,7 +1640,7 @@ private struct ExperimentalSection: View { defaultValue: "Disk budget for L2 spill; oldest entries are evicted when exceeded.", comment: "Sublabel for the DFlash SSD cache size field")) { TextInput(text: vm.bindProfile($vm.dflashSsdCacheGib), - placeholder: "20", mono: true, suffix: "GiB", width: 110) + placeholder: "20", mono: true, suffix: "GiB", width: .controlCompact) } } } @@ -1681,8 +1652,7 @@ private struct ExperimentalSection: View { comment: "Row label for the VLM MTP toggle"), sublabel: vlmMtpSublabel, isLast: !vm.vlmMtpEnabled) { - Toggle("", isOn: vm.bindProfile($vm.vlmMtpEnabled)) - .labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: vm.bindProfile($vm.vlmMtpEnabled)) .disabled(vlmMtpToggleDisabled) .help(vm.vlmMtpConflictReason ?? "") } @@ -1695,7 +1665,7 @@ private struct ExperimentalSection: View { comment: "Sublabel for the VLM MTP draft-model picker")) { Popup( selection: vm.bindProfile($vm.vlmMtpDraftModel), - width: 260, + width: .controlWide, options: vm.vlmMtpDraftModelOptions() ) } @@ -1707,7 +1677,7 @@ private struct ExperimentalSection: View { comment: "Sublabel for the VLM MTP draft block-size field"), isLast: true) { TextInput(text: vm.bindProfile($vm.vlmMtpDraftBlockSize), - placeholder: "4", mono: true, width: 80) + placeholder: "4", mono: true, width: .controlNarrow) } } } diff --git a/apps/omlx-mac/Sources/AppView/Screens/ModelsScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/ModelsScreen.swift index 91f551ac77..98fa75cc62 100644 --- a/apps/omlx-mac/Sources/AppView/Screens/ModelsScreen.swift +++ b/apps/omlx-mac/Sources/AppView/Screens/ModelsScreen.swift @@ -34,13 +34,7 @@ struct ModelsScreen: View { onToggleFavorite: { id, fav in vm.setFavorite(id: id, favorite: fav, client: services.client) } ) - if let error = vm.lastError { - Text(error) - .font(.omlxText(11)) - .foregroundStyle(.red) - .padding(.horizontal, 18) - .padding(.top, 8) - } + FooterBar(error: vm.lastError) } .task { await vm.start(client: services.client) } .onDisappear { vm.stop() } diff --git a/apps/omlx-mac/Sources/AppView/Screens/NetworkScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/NetworkScreen.swift index ba16982fd6..1380c15fa2 100644 --- a/apps/omlx-mac/Sources/AppView/Screens/NetworkScreen.swift +++ b/apps/omlx-mac/Sources/AppView/Screens/NetworkScreen.swift @@ -25,8 +25,7 @@ struct NetworkScreen: View { ProxiesSection(vm: vm) TLSSection(vm: vm) - HStack { - Spacer() + FooterBar(error: vm.lastError) { Button(String(localized: "network.button.apply", defaultValue: "Apply", comment: "Footer button on the Network screen that commits the edited proxy/TLS values to the server")) { @@ -35,10 +34,6 @@ struct NetworkScreen: View { .buttonStyle(.omlx(.primary)) .disabled(!vm.hasPendingChanges || vm.isSaving) } - .padding(.horizontal, 18) - .padding(.top, 6) - - HintFooter(error: vm.lastError) } .task { await vm.load(client: services.client) } } @@ -67,7 +62,7 @@ private struct ProxiesSection: View { text: $vm.httpProxy, placeholder: "http://proxy.local:8080", mono: true, - width: 320 + width: .controlWide ) } Row(label: String(localized: "network.row.https_proxy.label", @@ -77,7 +72,7 @@ private struct ProxiesSection: View { text: $vm.httpsProxy, placeholder: "http://proxy.local:8080", mono: true, - width: 320 + width: .controlWide ) } Row( @@ -93,7 +88,7 @@ private struct ProxiesSection: View { text: $vm.noProxy, placeholder: "localhost,127.0.0.1,*.internal", mono: true, - width: 320 + width: .controlWide ) } } @@ -129,25 +124,11 @@ private struct TLSSection: View { text: $vm.caBundle, placeholder: "/etc/ssl/certs/ca-bundle.pem", mono: true, - width: 320 + width: .controlWide ) } } } } -// MARK: - Hint footer - -private struct HintFooter: View { - let error: String? - var body: some View { - if let error { - Text(error) - .font(.omlxText(11)) - .foregroundStyle(.red) - .padding(.horizontal, 18) - .padding(.top, 8) - } - } -} diff --git a/apps/omlx-mac/Sources/AppView/Screens/PerformanceScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/PerformanceScreen.swift index 586f96e6f9..bbc4a4cabd 100644 --- a/apps/omlx-mac/Sources/AppView/Screens/PerformanceScreen.swift +++ b/apps/omlx-mac/Sources/AppView/Screens/PerformanceScreen.swift @@ -27,8 +27,7 @@ struct PerformanceScreen: View { MemoryLifecycleSection(vm: vm) CacheSection(vm: vm) - HStack { - Spacer() + FooterBar(error: vm.lastError) { Button(String(localized: "performance.button.apply", defaultValue: "Apply", comment: "Apply button at the bottom of the Performance screen")) { @@ -37,16 +36,6 @@ struct PerformanceScreen: View { .buttonStyle(.omlx(.primary)) .disabled(!vm.hasPendingChanges || vm.isSaving) } - .padding(.horizontal, 18) - .padding(.top, 6) - - if let error = vm.lastError { - Text(error) - .font(.omlxText(11)) - .foregroundStyle(.red) - .padding(.horizontal, 18) - .padding(.top, 8) - } } .task { await vm.load(client: services.client) } } @@ -76,7 +65,7 @@ private struct SchedulerSection: View { defaultValue: "Cap on simultaneous /v1 requests.", comment: "Sublabel for max concurrent requests") ) { - TextInput(text: $vm.maxConcurrentText, mono: true, width: 90) + TextInput(text: $vm.maxConcurrentText, mono: true, width: .controlNarrow) } Row( label: String(localized: "performance.scheduler.embedding_batch_size", @@ -86,7 +75,7 @@ private struct SchedulerSection: View { defaultValue: "Max input texts per embedding forward pass.", comment: "Sublabel for embedding batch size") ) { - TextInput(text: $vm.embeddingBatchSizeText, mono: true, width: 90) + TextInput(text: $vm.embeddingBatchSizeText, mono: true, width: .controlNarrow) } Row( label: String(localized: "performance.scheduler.chunked_prefill", @@ -96,8 +85,7 @@ private struct SchedulerSection: View { defaultValue: "Split long prompts across scheduler ticks so other requests can interleave.", comment: "Sublabel for chunked prefill toggle") ) { - Toggle("", isOn: $vm.chunkedPrefill) - .labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: $vm.chunkedPrefill) } Row( label: String(localized: "performance.scheduler.prefill_priority", @@ -122,7 +110,6 @@ private struct SchedulerSection: View { ], icons: ["arrow.up.left.and.arrow.down.right", "speedometer"] ) - .frame(width: 240) } } } @@ -153,8 +140,7 @@ private struct MemoryLifecycleSection: View { defaultValue: "Preflight prefill memory before kicking the engine and defer generation scheduling near the ceiling.", comment: "Sublabel for prefill memory guard") ) { - Toggle("", isOn: $vm.prefillMemoryGuard) - .labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: $vm.prefillMemoryGuard) } Row( label: String(localized: "performance.memory.guard_tier", @@ -164,7 +150,7 @@ private struct MemoryLifecycleSection: View { ) { Popup( selection: $vm.memoryGuardTier, - width: 150, + width: .controlMedium, options: [ ("safe", String(localized: "performance.memory.guard_tier.safe", @@ -202,7 +188,7 @@ private struct MemoryLifecycleSection: View { comment: "Placeholder for custom memory guard ceiling"), mono: true, suffix: "GB", - width: 110 + width: .controlCompact ) } } @@ -224,7 +210,7 @@ private struct MemoryLifecycleSection: View { comment: "Placeholder text for the idle timeout field when disabled"), mono: true, suffix: "s", - width: 110 + width: .controlCompact ) } Row( @@ -236,8 +222,7 @@ private struct MemoryLifecycleSection: View { comment: "Sublabel for model fallback toggle"), isLast: true ) { - Toggle("", isOn: $vm.modelFallback) - .labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: $vm.modelFallback) } } } @@ -307,8 +292,7 @@ private struct CacheSection: View { defaultValue: "Master switch for the engine's KV cache subsystem.", comment: "Sublabel for the master cache enable toggle") ) { - Toggle("", isOn: $vm.cacheEnabled) - .labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: $vm.cacheEnabled) } Row( label: String(localized: "performance.cache.hot_only", @@ -318,8 +302,7 @@ private struct CacheSection: View { defaultValue: "Skip SSD spillover. Useful on fast machines with abundant RAM.", comment: "Sublabel for hot cache only toggle") ) { - Toggle("", isOn: $vm.hotCacheOnly) - .labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: $vm.hotCacheOnly) .disabled(!vm.cacheEnabled) } Row( @@ -334,7 +317,7 @@ private struct CacheSection: View { text: $vm.hotCacheMaxSize, placeholder: "0", mono: true, - width: 140 + width: .controlCompact ) .disabled(!vm.cacheEnabled) } @@ -350,7 +333,7 @@ private struct CacheSection: View { text: $vm.ssdCacheDir, placeholder: "/cache", mono: true, - width: 280 + width: .controlWide ) .disabled(!vm.cacheEnabled || vm.hotCacheOnly) } @@ -368,7 +351,7 @@ private struct CacheSection: View { defaultValue: "auto", comment: "Memory field placeholder meaning automatic"), mono: true, - width: 140 + width: .controlCompact ) .disabled(!vm.cacheEnabled || vm.hotCacheOnly) } @@ -387,7 +370,7 @@ private struct CacheSection: View { defaultValue: "auto", comment: "Memory field placeholder meaning automatic"), mono: true, - width: 110 + width: .controlCompact ) .disabled(!vm.cacheEnabled) } diff --git a/apps/omlx-mac/Sources/AppView/Screens/ProfileViews.swift b/apps/omlx-mac/Sources/AppView/Screens/ProfileViews.swift index 077d8cf347..62becedafb 100644 --- a/apps/omlx-mac/Sources/AppView/Screens/ProfileViews.swift +++ b/apps/omlx-mac/Sources/AppView/Screens/ProfileViews.swift @@ -324,10 +324,10 @@ struct ActiveProfileBanner: View { .padding(.vertical, isSlim ? 10 : 12) .background(bannerBackground) .overlay( - RoundedRectangle(cornerRadius: 12, style: .continuous) + RoundedRectangle(cornerRadius: theme.cornerRadius, style: .continuous) .strokeBorder(bannerBorder, lineWidth: 0.5) ) - .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) + .clipShape(RoundedRectangle(cornerRadius: theme.cornerRadius, style: .continuous)) .padding(.horizontal, 14) .padding(.bottom, 12) } @@ -491,10 +491,10 @@ struct SaveAsPopover: View { .padding(12) .background(theme.groupBg) .overlay( - RoundedRectangle(cornerRadius: 12, style: .continuous) + RoundedRectangle(cornerRadius: theme.cornerRadius, style: .continuous) .strokeBorder(theme.groupBorder, lineWidth: 0.5) ) - .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) + .clipShape(RoundedRectangle(cornerRadius: theme.cornerRadius, style: .continuous)) .padding(.horizontal, 14) .padding(.bottom, 12) .onAppear { nameFocused = true } @@ -1067,7 +1067,9 @@ struct ProfileDetailCard: View { .foregroundStyle(theme.textSecondary) } .toggleStyle(.switch) - .controlSize(.mini) + // Same switch size as `RowSwitch` so every switch in the + // app reads as one control. + .controlSize(.small) if exposeAsModel, let exposedModelId { Text(exposedModelId) .font(.omlxMono(11)) diff --git a/apps/omlx-mac/Sources/AppView/Screens/QuantizationScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/QuantizationScreen.swift index 8d85271ca7..6f5f465b0a 100644 --- a/apps/omlx-mac/Sources/AppView/Screens/QuantizationScreen.swift +++ b/apps/omlx-mac/Sources/AppView/Screens/QuantizationScreen.swift @@ -103,7 +103,11 @@ struct QuantizationScreen: View { MessageBanner(error: vm.lastError, success: vm.lastSuccess) if vm.modelsLoaded && vm.models.isEmpty { - EmptyModelsBanner() + HintLine(text: String(localized: "quant.empty_models", + defaultValue: "No full-precision models found on disk. Download one from the Downloads tab first.", + comment: "Banner shown when no full-precision models are available to quantize")) + .padding(.horizontal, 14) + .padding(.top, 6) } QueueSection( @@ -179,7 +183,7 @@ private struct SourceModelSection: View { ) { Popup( selection: $selectedModelPath, - width: 320, + width: .controlWide, options: modelOptions ) } @@ -195,7 +199,7 @@ private struct SourceModelSection: View { ) { Popup( selection: $sensitivityModelPath, - width: 320, + width: .controlWide, options: sensitivityOptions ) } @@ -209,7 +213,7 @@ private struct SourceModelSection: View { comment: "Row sublabel explaining the oQ level tradeoff")) { Popup( selection: $oqLevel, - width: 120, + width: .controlCompact, options: levelOptions ) } @@ -308,7 +312,7 @@ private struct EstimateStrip: View { defaultValue: "Output size: ~\(outputSizeText)", comment: "Estimate pill: predicted on-disk size of the quantized output. Placeholder is the formatted byte string")) } - .padding(.horizontal, 18) + .padding(.horizontal, 14) .padding(.top, 4) .padding(.bottom, 10) } @@ -373,7 +377,7 @@ private struct AdvancedSection: View { defaultValue: "Exclude vision encoder weights (~2-3% smaller, text-only output)", comment: "Toggle row sublabel: text-only quantization effect") ) { - Toggle("", isOn: $textOnly).labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: $textOnly) } } @@ -389,9 +393,7 @@ private struct AdvancedSection: View { defaultValue: "Unavailable — source model has no MTP heads", comment: "Toggle row sublabel when MTP isn't supported by the chosen source") ) { - Toggle("", isOn: $preserveMtp) - .labelsHidden() - .toggleStyle(.switch) + RowSwitch(isOn: $preserveMtp) .disabled(!selectedHasMTP) } @@ -446,7 +448,7 @@ private struct EnhancedQuantizationSection: View { comment: "Toggle sublabel explaining what enabling oQe does"), isLast: !enabled ) { - Toggle("", isOn: $enabled).labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: $enabled) } if enabled { @@ -458,7 +460,7 @@ private struct EnhancedQuantizationSection: View { defaultValue: "Use a compatible cached imatrix when available; otherwise collect a new one.", comment: "Toggle sublabel for the oQe imatrix cache reuse option") ) { - Toggle("", isOn: $reuseCache).labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: $reuseCache) } Row( @@ -475,7 +477,7 @@ private struct EnhancedQuantizationSection: View { defaultValue: "Automatic", comment: "Placeholder for an automatically selected oQe imatrix cache path"), mono: true, - width: 320 + width: .controlWide ) } @@ -488,36 +490,13 @@ private struct EnhancedQuantizationSection: View { comment: "Toggle sublabel for strict oQe imatrix coverage"), isLast: true ) { - Toggle("", isOn: $strictCoverage).labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: $strictCoverage) } } } } } -private struct EmptyModelsBanner: View { - @Environment(\.omlxTheme) private var theme - - var body: some View { - HStack(spacing: 8) { - Image(systemName: "info.circle") - .font(.system(size: 11)) - .foregroundStyle(theme.textTertiary) - Text(String(localized: "quant.empty_models", - defaultValue: "No full-precision models found on disk. Download one from the Downloads tab first.", - comment: "Banner shown when no full-precision models are available to quantize")) - .font(.omlxText(11.5)) - .foregroundStyle(theme.textSecondary) - Spacer(minLength: 0) - } - .padding(10) - .background(theme.codeBg) - .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous)) - .padding(.horizontal, 18) - .padding(.top, 6) - } -} - // MARK: - Queue private struct QueueSection: View { @@ -973,7 +952,7 @@ private struct UploadModalView: View { placeholder: "hf_…", isSecure: true, mono: true, - width: 220 + width: .controlMedium ) Button { Task { await vm.validateUploadToken(client: client) } @@ -1010,7 +989,7 @@ private struct UploadModalView: View { ) { Popup( selection: $vm.uploadNamespace, - width: 220, + width: .controlMedium, options: namespaceOptions ) } @@ -1063,7 +1042,7 @@ private struct UploadModalView: View { text: $repoName, placeholder: "model-id", mono: true, - width: 240 + width: .controlMedium ) } } @@ -1077,7 +1056,7 @@ private struct UploadModalView: View { comment: "Toggle row sublabel explaining the private flag"), isLast: true ) { - Toggle("", isOn: $isPrivate).labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: $isPrivate) } } } @@ -1101,7 +1080,7 @@ private struct UploadModalView: View { ) { Popup( selection: $readmeSourcePath, - width: 260, + width: .controlWide, options: readmeOptions ) } @@ -1115,7 +1094,7 @@ private struct UploadModalView: View { comment: "Toggle row sublabel for the re-download notice"), isLast: true ) { - Toggle("", isOn: $addRedownloadNotice).labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: $addRedownloadNotice) } } else { // Trailing row stays flush even when the toggle is hidden. diff --git a/apps/omlx-mac/Sources/AppView/Screens/SecurityScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/SecurityScreen.swift index b525ded717..24a5d8772e 100644 --- a/apps/omlx-mac/Sources/AppView/Screens/SecurityScreen.swift +++ b/apps/omlx-mac/Sources/AppView/Screens/SecurityScreen.swift @@ -27,13 +27,7 @@ struct SecurityScreen: View { AuthenticationSection(vm: vm, client: services.client) SubKeysSection(vm: vm, client: services.client) - if let error = vm.lastError { - Text(error) - .font(.omlxText(11)) - .foregroundStyle(.red) - .padding(.horizontal, 18) - .padding(.top, 8) - } + FooterBar(error: vm.lastError) } .task { await vm.load(client: services.client) } } @@ -103,7 +97,7 @@ private struct APIKeyEditorRow: View { comment: "Row label for the API key editor"), sublabel: sublabel, isLast: true) { HStack(spacing: 6) { - TextInput("security.api_key.row_label", text: $draft, placeholder: "sk-omlx-…", isSecure: !showKey, mono: true, width: 260) + TextInput("security.api_key.row_label", text: $draft, placeholder: "sk-omlx-…", isSecure: !showKey, mono: true, width: .controlMedium) .onSubmit { Task { await save() } } iconButton(systemName: showKey ? "eye.slash" : "eye", help: showKey @@ -216,10 +210,9 @@ private struct AuthenticationSection: View { comment: "Sublabel for the disable API key verification toggle"), isLast: true ) { - Toggle("", isOn: vm.bind($vm.skipApiKeyVerification, save: { + RowSwitch(isOn: vm.bind($vm.skipApiKeyVerification, save: { Task { await vm.saveSkipApiKeyVerification(client: client) } })) - .labelsHidden().toggleStyle(.switch) } } } @@ -270,7 +263,7 @@ private struct SubKeysSection: View { placeholder: String(localized: "security.sub_keys.name_placeholder", defaultValue: "Claude Code on laptop", comment: "Placeholder text for sub-key name input"), - width: 220) + width: .controlMedium) } Row(label: String(localized: "security.sub_keys.key_label", defaultValue: "Key", @@ -280,7 +273,7 @@ private struct SubKeysSection: View { placeholder: String(localized: "security.sub_keys.key_placeholder", defaultValue: "sk-omlx-sub-…", comment: "Placeholder text inside the sub-key value input"), - mono: true, width: 220) + mono: true, width: .controlMedium) Button { newKey = APIKeyGenerator.random() } label: { diff --git a/apps/omlx-mac/Sources/AppView/Screens/ServerScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/ServerScreen.swift index c2e03561c6..236e86f083 100644 --- a/apps/omlx-mac/Sources/AppView/Screens/ServerScreen.swift +++ b/apps/omlx-mac/Sources/AppView/Screens/ServerScreen.swift @@ -27,7 +27,7 @@ struct ServerScreen: View { comment: "Row label for the listen-address picker in Server screen")) { Popup( selection: vm.bind($vm.host, save: { vm.saveHost(services: services) }), - width: 220, + width: .controlMedium, options: [ ("127.0.0.1", String(localized: "server.host.local_only", defaultValue: "127.0.0.1 (Local only)", @@ -53,7 +53,7 @@ struct ServerScreen: View { comment: "Sublabel under the Port field"), isLast: true ) { - TextInput(text: $vm.portText, mono: true, width: 90) + TextInput(text: $vm.portText, mono: true, width: .controlNarrow) } } @@ -88,11 +88,9 @@ struct ServerScreen: View { comment: "Sublabel explaining the auto-start on launch setting"), isLast: true ) { - Toggle("", isOn: vm.bind($vm.autoStartOnLaunch, save: { + RowSwitch(isOn: vm.bind($vm.autoStartOnLaunch, save: { vm.saveAutoStartOnLaunch(services: services) })) - .labelsHidden() - .toggleStyle(.switch) } } @@ -106,7 +104,7 @@ struct ServerScreen: View { isLast: true) { Popup( selection: vm.bind($vm.logLevel, save: vm.saveLogLevel), - width: 130, + width: .controlCompact, options: [ ("error", String(localized: "server.log_level.error", defaultValue: "Error", @@ -145,7 +143,7 @@ struct ServerScreen: View { defaultValue: "OMLX_BASE_PATH. Files move and the server restarts when this changes.", comment: "Sublabel under the Base Path field") ) { - TextInput(text: $vm.basePathText, mono: true, width: 280) + TextInput(text: $vm.basePathText, mono: true, width: .controlWide) } FreeRow { ModelDirectoriesEditor(vm: vm) @@ -159,15 +157,17 @@ struct ServerScreen: View { comment: "Sublabel for enabling Hugging Face local cache discovery"), isLast: true ) { - Toggle("", isOn: $vm.hfCacheEnabled) - .labelsHidden() - .toggleStyle(.switch) + RowSwitch(isOn: $vm.hfCacheEnabled) } } ServerAdvancedSection(vm: vm) - HStack { - Spacer() + FooterBar( + hint: String(localized: "server.footer.hint", + defaultValue: "Listen Address, Log Level, and SSE Keep-Alive Mode apply the moment you change them. The rest (port, default profile, storage, aliases) commits when you click Apply. Port and storage changes take effect after a server restart.", + comment: "Hint footer text under the Server screen explaining which controls apply immediately vs. via the Apply button"), + error: vm.lastError + ) { Button(String(localized: "server.button.apply", defaultValue: "Apply", comment: "Button to apply pending server settings: port, default profile, storage, and aliases")) { @@ -177,10 +177,6 @@ struct ServerScreen: View { .disabled(!vm.hasPendingServerChanges(services: services) || vm.isMovingBasePath) } - .padding(.horizontal, 18) - .padding(.top, 6) - - HintFooter(error: vm.lastError) } .task { // services.config is already populated by AppDelegate before this @@ -253,7 +249,7 @@ private struct ModelDirectoriesEditor: View { TextInput(text: Binding( get: { vm.modelDirText(at: index) }, set: { vm.setModelDirText($0, at: index) } - ), mono: true, width: 340) + ), mono: true, width: .controlWide) Button { vm.browseModelDirectory(at: index) @@ -320,7 +316,7 @@ struct ServerHeroCard: View { // Hero card surface follows the grouped Settings style. Status is // carried by the pill/actions, not by a colored background wash. .background(heroBackground) - .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) + .clipShape(RoundedRectangle(cornerRadius: theme.cornerRadius, style: .continuous)) .padding(.horizontal, 14) .padding(.bottom, 14) } @@ -461,7 +457,7 @@ private struct ServerDefaultProfileEditor: View { sublabel: String(localized: "server.profile.context_window.sub", defaultValue: "Maximum prompt + completion tokens.", comment: "Sublabel for the context window field")) { - TextInput(text: $vm.samplingContextText, mono: true, suffix: "tk", width: 110) + TextInput(text: $vm.samplingContextText, mono: true, suffix: "tk", width: .controlCompact) } Row(label: String(localized: "server.profile.max_tokens", defaultValue: "Max Tokens", @@ -469,7 +465,7 @@ private struct ServerDefaultProfileEditor: View { sublabel: String(localized: "server.profile.max_tokens.sub", defaultValue: "Server-wide cap on generated tokens.", comment: "Sublabel for the max tokens field")) { - TextInput(text: $vm.samplingMaxTokensText, mono: true, suffix: "tk", width: 110) + TextInput(text: $vm.samplingMaxTokensText, mono: true, suffix: "tk", width: .controlCompact) } Row(label: String(localized: "server.profile.temperature", defaultValue: "Temperature", @@ -477,7 +473,7 @@ private struct ServerDefaultProfileEditor: View { sublabel: String(localized: "server.profile.temperature.sub", defaultValue: "Sampling randomness (0–2).", comment: "Sublabel for the temperature field")) { - TextInput(text: $vm.samplingTemperatureText, placeholder: "0.7", mono: true, width: 90) + TextInput(text: $vm.samplingTemperatureText, placeholder: "0.7", mono: true, width: .controlNarrow) } Row(label: String(localized: "server.profile.top_p", defaultValue: "Top P", @@ -485,7 +481,7 @@ private struct ServerDefaultProfileEditor: View { sublabel: String(localized: "server.profile.top_p.sub", defaultValue: "Nucleus sampling cutoff (0–1).", comment: "Sublabel for the Top P field")) { - TextInput(text: $vm.samplingTopPText, mono: true, width: 90) + TextInput(text: $vm.samplingTopPText, mono: true, width: .controlNarrow) } Row(label: String(localized: "server.profile.top_k", defaultValue: "Top K", @@ -493,7 +489,7 @@ private struct ServerDefaultProfileEditor: View { sublabel: String(localized: "server.profile.top_k.sub", defaultValue: "Limit candidates to top K. 0 = disabled.", comment: "Sublabel for the Top K field")) { - TextInput(text: $vm.samplingTopKText, mono: true, width: 90) + TextInput(text: $vm.samplingTopKText, mono: true, width: .controlNarrow) } Row(label: String(localized: "server.profile.repetition_penalty", defaultValue: "Repetition Penalty", @@ -503,7 +499,7 @@ private struct ServerDefaultProfileEditor: View { comment: "Sublabel for the repetition penalty field"), isLast: !expanded ) { - TextInput(text: $vm.samplingRepetitionPenaltyText, mono: true, width: 90) + TextInput(text: $vm.samplingRepetitionPenaltyText, mono: true, width: .controlNarrow) } if expanded { // The remaining design rows aren't server-backed yet — @@ -677,7 +673,8 @@ private struct ServerAdvancedSection: View { .contentShape(Rectangle()) } .buttonStyle(.plain) - .padding(.horizontal, 18) + // Matches SectionHeader's indent (card gutter + row inset). + .padding(.horizontal, 28) .padding(.top, 22) .padding(.bottom, 8) @@ -695,7 +692,7 @@ private struct ServerAdvancedSection: View { text: $vm.maxAudioUploadSizeText, placeholder: "100MB", mono: true, - width: 130 + width: .controlCompact ) } Row( @@ -708,7 +705,7 @@ private struct ServerAdvancedSection: View { ) { Popup( selection: vm.bind($vm.sseKeepaliveMode, save: vm.saveSseKeepaliveMode), - width: 130, + width: .controlCompact, options: [ ("chunk", String(localized: "server.advanced.sse_keepalive.chunk", defaultValue: "Chunk", @@ -735,7 +732,7 @@ private struct ServerAdvancedSection: View { text: $vm.serverAliasesText, placeholder: "omlx.local, oMLX.lan", mono: true, - width: 320 + width: .controlWide ) } } @@ -744,24 +741,4 @@ private struct ServerAdvancedSection: View { } } -// MARK: - Footer hint - -private struct HintFooter: View { - let error: String? - @Environment(\.omlxTheme) private var theme - var body: some View { - VStack(alignment: .leading, spacing: 4) { - HintLine(text: String(localized: "server.footer.hint", - defaultValue: "Listen Address, Log Level, and SSE Keep-Alive Mode apply the moment you change them. The rest (port, default profile, storage, aliases) commits when you click Apply. Port and storage changes take effect after a server restart.", - comment: "Hint footer text under the Server screen explaining which controls apply immediately vs. via the Apply button")) - if let error { - Text(error) - .font(.omlxText(11)) - .foregroundStyle(theme.redDot) - } - } - .padding(.horizontal, 18) - .padding(.top, 8) - } -} diff --git a/apps/omlx-mac/Sources/AppView/Screens/StatusScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/StatusScreen.swift index 56cd127a32..c55e4f6521 100644 --- a/apps/omlx-mac/Sources/AppView/Screens/StatusScreen.swift +++ b/apps/omlx-mac/Sources/AppView/Screens/StatusScreen.swift @@ -125,12 +125,7 @@ struct StatusScreen: View { comment: "Section header for the updates section")) UpdatesSection(updates: services.updates) - if let error = vm.lastError { - Text(error) - .font(.omlxText(11)) - .foregroundStyle(.red) - .padding(.horizontal, 18).padding(.top, 8) - } + FooterBar(error: vm.lastError) } .task(id: vm.scope) { await vm.start(client: services.client) @@ -619,7 +614,7 @@ private struct UpdatesSection: View { get: { updates.channel }, set: { updates.channel = $0 } ), - width: 190, + width: .controlMedium, options: UpdateChannel.allCases.map { ($0, $0.displayName) } ) } @@ -631,12 +626,10 @@ private struct UpdatesSection: View { defaultValue: "Look for updates daily in the background", comment: "Sublabel for the auto-check toggle") ) { - Toggle("", isOn: Binding( + RowSwitch(isOn: Binding( get: { updates.autoCheck }, set: { updates.autoCheck = $0 } )) - .labelsHidden() - .toggleStyle(.switch) } Row( label: String(localized: "status.updates.auto_download", @@ -647,12 +640,10 @@ private struct UpdatesSection: View { comment: "Sublabel for the automatic update notification toggle"), isLast: true ) { - Toggle("", isOn: Binding( + RowSwitch(isOn: Binding( get: { updates.autoNotify }, set: { updates.autoNotify = $0 } )) - .labelsHidden() - .toggleStyle(.switch) } } } diff --git a/apps/omlx-mac/Sources/AppView/Screens/ThroughputBenchScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/ThroughputBenchScreen.swift index d6b1c6c49c..63040d3ecc 100644 --- a/apps/omlx-mac/Sources/AppView/Screens/ThroughputBenchScreen.swift +++ b/apps/omlx-mac/Sources/AppView/Screens/ThroughputBenchScreen.swift @@ -129,7 +129,7 @@ private struct DeviceChip: View { .foregroundStyle(theme.textSecondary) Spacer(minLength: 0) } - .padding(.horizontal, 18) + .padding(.horizontal, 14) .padding(.top, 2) .padding(.bottom, 8) } @@ -197,7 +197,7 @@ private struct ConfigurationSection: View { comment: "Sublabel under the Throughput Bench model picker")) { Popup( selection: $selectedModelId, - width: 320, + width: .controlWide, options: modelOptions ) } @@ -210,7 +210,7 @@ private struct ConfigurationSection: View { comment: "Sublabel under the Throughput Bench context picker")) { Popup( selection: $contextProfile, - width: 220, + width: .controlMedium, options: BenchmarkContextProfile.allCases.map { PopupOption(value: $0, label: $0.localizedLabel) } @@ -232,7 +232,6 @@ private struct ConfigurationSection: View { defaultValue: "Full · 2,048", comment: "Full 2048-token ANE benchmark warm-up option")), ]) - .frame(width: 260) .disabled(running) } @@ -242,24 +241,22 @@ private struct ConfigurationSection: View { sublabel: String(localized: "bench.throughput.row.ane_alignment.sub", defaultValue: "Add one prompt token so PP4097 produces exactly 4,096 prefill rows. Aligned results remain local.", comment: "Explanation of the ANE-aligned throughput benchmark option")) { - Toggle("", isOn: $alignPromptToAne) - .labelsHidden() - .toggleStyle(.switch) + RowSwitch(isOn: $alignPromptToAne) .disabled(running) } - FreeRow { - ChipRow( - title: String(localized: "bench.throughput.row.context_lengths.title", - defaultValue: "Context lengths", - comment: "Inline title above the prompt-length chip row"), - sublabel: String(localized: "bench.throughput.row.context_lengths.sub", - defaultValue: "Prompt tokens to feed for each single-request trial", - comment: "Sublabel under the prompt-length chip row"), + Row(label: String(localized: "bench.throughput.row.context_lengths.title", + defaultValue: "Context lengths", + comment: "Inline title above the prompt-length chip row"), + sublabel: String(localized: "bench.throughput.row.context_lengths.sub", + defaultValue: "Prompt tokens to feed for each single-request trial", + comment: "Sublabel under the prompt-length chip row")) { + ChipGroup( options: Self.promptLengthOptions, selection: $promptLengths, format: Self.formatPromptLength ) + .disabled(running) } Row(label: String(localized: "bench.throughput.row.gen_length.label", @@ -272,22 +269,22 @@ private struct ConfigurationSection: View { text: $genLength, placeholder: "128", mono: true, - width: 110 + width: .controlCompact ) } - FreeRow { - ChipRow( - title: String(localized: "bench.throughput.row.batch_sizes.title", - defaultValue: "Batch sizes", - comment: "Inline title above the batch-size chip row"), - sublabel: String(localized: "bench.throughput.row.batch_sizes.sub", - defaultValue: "Concurrent requests per batch in the continuous-batching phase", - comment: "Sublabel under the batch-size chip row"), + Row(label: String(localized: "bench.throughput.row.batch_sizes.title", + defaultValue: "Batch sizes", + comment: "Inline title above the batch-size chip row"), + sublabel: String(localized: "bench.throughput.row.batch_sizes.sub", + defaultValue: "Concurrent requests per batch in the continuous-batching phase", + comment: "Sublabel under the batch-size chip row")) { + ChipGroup( options: Self.batchSizeOptions, selection: $batchSizes, format: { "\($0)" } ) + .disabled(running) } Row(isLast: true) { @@ -357,36 +354,24 @@ private struct ConfigurationSection: View { } } -// MARK: - Chip row +// MARK: - Chip group -private struct ChipRow: View { - let title: String - let sublabel: String +/// Multi-select strip of toggle chips, used as a `Row` trailing. Styled to +/// echo the segmented control — quiet fill, accent when selected — but with +/// detached segments and gaps because multiple values can be active at once. +private struct ChipGroup: View { let options: [Int] @Binding var selection: Set let format: (Int) -> String - @Environment(\.omlxTheme) private var theme - var body: some View { - VStack(alignment: .leading, spacing: 8) { - VStack(alignment: .leading, spacing: 2) { - Text(title) - .font(.omlxText(13, weight: .medium)) - .foregroundStyle(theme.text) - Text(sublabel) - .font(.omlxText(11.5)) - .foregroundStyle(theme.textSecondary) - } - HStack(spacing: 6) { - ForEach(options, id: \.self) { value in - Chip( - label: format(value), - isSelected: selection.contains(value), - onTap: { toggle(value) } - ) - } - Spacer(minLength: 0) + HStack(spacing: 5) { + ForEach(options, id: \.self) { value in + Chip( + label: format(value), + isSelected: selection.contains(value), + onTap: { toggle(value) } + ) } } } @@ -411,19 +396,16 @@ private struct Chip: View { Button(action: onTap) { Text(label) .font(.omlxText(11.5, weight: .medium)) - .foregroundStyle(isSelected ? theme.accentText : theme.textSecondary) + // Chips must never compress: under width pressure SwiftUI + // would otherwise wrap "128K" to "12/8K". The label column + // absorbs the squeeze instead. + .fixedSize() + .foregroundStyle(isSelected ? theme.accentText : theme.text) .padding(.horizontal, 10) .padding(.vertical, 4) .background( RoundedRectangle(cornerRadius: 6, style: .continuous) - .fill(isSelected ? theme.accent : theme.controlBg) - .overlay( - RoundedRectangle(cornerRadius: 6, style: .continuous) - .strokeBorder( - isSelected ? Color.clear : theme.inputBorder, - lineWidth: 0.5 - ) - ) + .fill(isSelected ? theme.accent : theme.hoverBg) ) .contentShape(Rectangle()) } @@ -917,7 +899,7 @@ private struct OwnerHashRow: View { } .buttonStyle(.omlx(.plain, size: .small)) } - .padding(.horizontal, 18) + .padding(.horizontal, 14) .padding(.top, 4) .padding(.bottom, 10) } diff --git a/apps/omlx-mac/Sources/Menubar/MenubarMetricPopover.swift b/apps/omlx-mac/Sources/Menubar/MenubarMetricPopover.swift index c89c1cca8a..053909a074 100644 --- a/apps/omlx-mac/Sources/Menubar/MenubarMetricPopover.swift +++ b/apps/omlx-mac/Sources/Menubar/MenubarMetricPopover.swift @@ -206,12 +206,19 @@ struct MetricSparkline: View { let isFlat = span <= .ulpOfOne let stepX = size.width / CGFloat(values.count - 1) + // Inset the plot range by half the stroke width so a series + // pinned to the floor (0%) or ceiling doesn't center its stroke + // on the canvas edge and render half-clipped. + let lineWidth: CGFloat = 1.2 + let plotTop = lineWidth / 2 + let plotHeight = size.height - lineWidth + var trace = Path() for (index, value) in values.enumerated() { let normalized = isFlat ? 0.5 : (value - low) / span let point = CGPoint( x: CGFloat(index) * stepX, - y: size.height * (1 - CGFloat(normalized)) + y: plotTop + plotHeight * (1 - CGFloat(normalized)) ) if index == 0 { trace.move(to: point) @@ -235,7 +242,7 @@ struct MetricSparkline: View { context.stroke( trace, with: .color(color), - style: StrokeStyle(lineWidth: 1.2, lineJoin: .round) + style: StrokeStyle(lineWidth: lineWidth, lineJoin: .round) ) } .frame(height: height) diff --git a/apps/omlx-mac/Sources/Theme/Components/Button.swift b/apps/omlx-mac/Sources/Theme/Components/Button.swift index bfd1954708..d5fc428e5f 100644 --- a/apps/omlx-mac/Sources/Theme/Components/Button.swift +++ b/apps/omlx-mac/Sources/Theme/Components/Button.swift @@ -1,15 +1,18 @@ -// PR 3 — button styles for primary / destructive / plain / regular. +// Button styles for primary / destructive / normal / plain. // // Use: // Button("Save") { … } // .buttonStyle(.omlx(.primary)) // -// The plain kind is the JSX "kind=plain" — borderless action label, e.g. the -// chevron-only row buttons in screens. +// primary / destructive / normal delegate to the native bordered styles so +// buttons share bezel metrics, fonts, and disabled/pressed treatment with +// the native fields and pickers they sit next to. plain stays a quiet +// custom label (text-colored, hover-highlight only) because the native +// borderless style would accent-tint the many icon-only row buttons. import SwiftUI -struct OMLXButtonStyle: ButtonStyle { +struct OMLXButtonStyle: PrimitiveButtonStyle { enum Kind: Sendable { case primary, destructive, normal, plain } enum Size: Sendable { case small, regular } @@ -17,72 +20,46 @@ struct OMLXButtonStyle: ButtonStyle { let size: Size @Environment(\.omlxTheme) private var theme - /// Without this, a `.disabled()` button keeps its enabled paint because the - /// custom background ignores SwiftUI's default isEnabled tint. Users then - /// click an enabled-looking primary button and see no press animation - /// (SwiftUI suppresses `isPressed` on disabled buttons) — leading to the - /// "Apply only animates the first time" report. Reading `isEnabled` here - /// dims the whole label so disabled state is visually unmistakable. - @Environment(\.isEnabled) private var isEnabled - - func makeBody(configuration: Configuration) -> some View { - let labelFont = Font.omlxText(size == .small ? 11.5 : 13, weight: .medium) - let hPad: CGFloat = size == .small ? 10 : 12 - let vPad: CGFloat = size == .small ? 4 : 6 - - return configuration.label - .font(labelFont) - .padding(.horizontal, hPad) - .padding(.vertical, vPad) - .foregroundStyle(foreground(configuration)) - .background(background(configuration)) - .clipShape(RoundedRectangle(cornerRadius: 6, style: .continuous)) - .overlay(border(configuration)) - .opacity(opacity(configuration)) - .contentShape(Rectangle()) - } - - /// Disabled state wins over press feedback. 0.45 is the macOS-feeling - /// "this control is inert" tint — tested against `.primary` (blue), - /// `.destructive` (red), `.normal` (themed control bg), and `.plain` - /// (transparent + dimmed text). - private func opacity(_ cfg: Configuration) -> Double { - guard isEnabled else { return 0.45 } - return cfg.isPressed ? 0.78 : 1.0 - } @ViewBuilder - private func background(_ cfg: Configuration) -> some View { + func makeBody(configuration: Configuration) -> some View { + let button = Button(configuration) + .controlSize(size == .small ? .small : .regular) switch kind { case .primary: - theme.accent + button.buttonStyle(.borderedProminent) case .destructive: - theme.redDot + button.buttonStyle(.borderedProminent).tint(theme.redDot) case .normal: - theme.controlBg + button.buttonStyle(.bordered) case .plain: - cfg.isPressed ? theme.hoverBg : Color.clear + button.buttonStyle(QuietButtonStyle(theme: theme, size: size)) } } +} - private func foreground(_ cfg: Configuration) -> Color { - switch kind { - case .primary, .destructive: return theme.accentText - case .normal: return theme.text - case .plain: return theme.text - } - } +/// The former custom "plain" rendering: label in text color, hover-style +/// highlight while pressed, dimmed when disabled. +private struct QuietButtonStyle: ButtonStyle { + let theme: OMLXTheme + let size: OMLXButtonStyle.Size - @ViewBuilder - private func border(_ cfg: Configuration) -> some View { - if kind == .normal { - RoundedRectangle(cornerRadius: 6, style: .continuous) - .strokeBorder(theme.inputBorder, lineWidth: 0.5) - } + @Environment(\.isEnabled) private var isEnabled + + func makeBody(configuration: Configuration) -> some View { + configuration.label + .font(.omlxText(size == .small ? 11.5 : 13, weight: .medium)) + .padding(.horizontal, size == .small ? 10 : 12) + .padding(.vertical, size == .small ? 4 : 6) + .foregroundStyle(theme.text) + .background(configuration.isPressed ? theme.hoverBg : Color.clear) + .clipShape(RoundedRectangle(cornerRadius: 6, style: .continuous)) + .opacity(isEnabled ? (configuration.isPressed ? 0.78 : 1.0) : 0.45) + .contentShape(Rectangle()) } } -extension ButtonStyle where Self == OMLXButtonStyle { +extension PrimitiveButtonStyle where Self == OMLXButtonStyle { static func omlx( _ kind: OMLXButtonStyle.Kind = .normal, size: OMLXButtonStyle.Size = .regular diff --git a/apps/omlx-mac/Sources/Theme/Components/Popup.swift b/apps/omlx-mac/Sources/Theme/Components/Popup.swift index 72e845e908..e834dce3a4 100644 --- a/apps/omlx-mac/Sources/Theme/Components/Popup.swift +++ b/apps/omlx-mac/Sources/Theme/Components/Popup.swift @@ -1,4 +1,5 @@ -// PR 3 — dropdown picker styled to match the JSX `Popup`. +// PR 3 — dropdown picker. Renders the native macOS menu picker so selects +// share one bezel, height, and font with the rest of the system controls. import SwiftUI @@ -13,78 +14,35 @@ struct Popup: View { var titleKey: LocalizedStringKey let options: [PopupOption] let width: CGFloat? - let fillsWidth: Bool - @Environment(\.omlxTheme) private var theme - - init(_ titleKey: LocalizedStringKey = "", selection: Binding, width: CGFloat? = nil, fillsWidth: Bool = false, options: [PopupOption]) { + init(_ titleKey: LocalizedStringKey = "", selection: Binding, width: CGFloat? = nil, options: [PopupOption]) { self.titleKey = titleKey self._selection = selection self.options = options self.width = width - self.fillsWidth = fillsWidth } - init(_ titleKey: LocalizedStringKey = "", selection: Binding, width: CGFloat? = nil, fillsWidth: Bool = false, options: [(Value, String)]) { + init(_ titleKey: LocalizedStringKey = "", selection: Binding, width: CGFloat? = nil, options: [(Value, String)]) { self.titleKey = titleKey self._selection = selection self.options = options.map { PopupOption(value: $0.0, label: $0.1) } self.width = width - self.fillsWidth = fillsWidth } var body: some View { - if fillsWidth, let width { - Menu { - ForEach(options) { opt in - Button { - selection = opt.value - } label: { - if opt.value == selection { - Label(opt.label, systemImage: "checkmark") - } else { - Text(opt.label) - } - } - } - } label: { - HStack(spacing: 8) { - Text(selectedOption?.label ?? "") - .lineLimit(1) - Spacer(minLength: 0) - Image(systemName: "chevron.up.chevron.down") - .font(.system(size: 10, weight: .semibold)) - } - .font(.omlxText(13, weight: .medium)) - .foregroundStyle(theme.text) - .padding(.horizontal, 10) - .padding(.vertical, 4) - .frame(width: width) - .background(theme.controlBg) - .clipShape(RoundedRectangle(cornerRadius: 6, style: .continuous)) - .overlay { - RoundedRectangle(cornerRadius: 6, style: .continuous) - .strokeBorder(theme.inputBorder, lineWidth: 0.5) - } - .contentShape(Rectangle()) - } - .menuStyle(.borderlessButton) - .accessibilityValue(selectedOption?.label ?? "") - } else { - Picker(titleKey, selection: $selection) { - ForEach(options) { opt in - Text(opt.label) - .tag(opt.value) - } + Picker(titleKey, selection: $selection) { + ForEach(options) { opt in + Text(opt.label) + .tag(opt.value) } - .labelsHidden() - .pickerStyle(.menu) - .frame(maxWidth: width) } - } - - private var selectedOption: PopupOption? { - options.first { $0.value == selection } + .labelsHidden() + .pickerStyle(.menu) + // The native popup bezel hugs its label, and a bare `maxWidth` frame + // would center it — leaving air on both sides. Pin it trailing so + // select bezels end flush with the other controls in the column; + // `width` stays the cap that keeps long labels from sprawling. + .frame(maxWidth: width, alignment: .trailing) } } @@ -93,13 +51,13 @@ struct Popup: View { @Previewable @State var quant = "q4" VStack(alignment: .leading, spacing: 14) { - Popup(selection: $host, width: 220, options: [ + Popup(selection: $host, width: .controlMedium, options: [ ("127.0.0.1", "127.0.0.1 (Local only)"), ("0.0.0.0", "0.0.0.0 (IPv4 only)"), ("::", "0.0.0.0 & :: (All Networks)"), ("localhost", "localhost"), ]) - Popup(selection: $quant, width: 120, options: [ + Popup(selection: $quant, width: .controlCompact, options: [ ("auto", "Auto"), ("q4", "q4"), ("q5", "q5"), ("q6", "q6"), ("q8", "q8"), ("fp16", "fp16"), ]) } diff --git a/apps/omlx-mac/Sources/Theme/Components/Row.swift b/apps/omlx-mac/Sources/Theme/Components/Row.swift index 087f703108..ec10000fe2 100644 --- a/apps/omlx-mac/Sources/Theme/Components/Row.swift +++ b/apps/omlx-mac/Sources/Theme/Components/Row.swift @@ -59,6 +59,24 @@ struct Row: View { } } +/// Trailing on/off switch for a `Row`. One shared control so every screen +/// gets the same size: `.small`, matching System Settings rows — the default +/// regular switch reads oversized next to 13 pt row labels. +struct RowSwitch: View { + @Binding var isOn: Bool + + init(isOn: Binding) { + self._isOn = isOn + } + + var body: some View { + Toggle("", isOn: $isOn) + .labelsHidden() + .toggleStyle(.switch) + .controlSize(.small) + } +} + extension Row where Trailing == EmptyView { /// Label-only row (no trailing slot). init(label: String, sublabel: String? = nil, isLast: Bool = false) { @@ -140,8 +158,16 @@ struct LinkRow: View { ) } + @State private var hovering = false + + // The whole row is one button (System Settings convention for rows + // that open a URL); the trailing ↗ is a passive indicator, not a + // separate control. Hover feedback replaces FreeRow so the highlight + // spans the full row width. var body: some View { - FreeRow(isLast: isLast) { + Button { + NSWorkspace.shared.open(url) + } label: { HStack(spacing: 10) { iconView .foregroundStyle(theme.textSecondary) @@ -158,13 +184,24 @@ struct LinkRow: View { Spacer(minLength: 8) - Button { - NSWorkspace.shared.open(url) - } label: { - Label("common.open", systemImage: "arrow.up.right.square") - .labelStyle(.iconOnly) - } - .buttonStyle(.omlx(.plain, size: .small)) + Image(systemName: "arrow.up.right.square") + .font(.system(size: 14)) + .foregroundStyle(theme.textSecondary) + } + .padding(.horizontal, 14) + .padding(.vertical, 10) + .frame(maxWidth: .infinity, alignment: .leading) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .background(hovering ? theme.hoverBg : .clear) + .onHover { hovering = $0 } + .overlay(alignment: .bottom) { + if !isLast { + Rectangle() + .fill(theme.rowSep) + .frame(height: 0.5) + .padding(.horizontal, 14) } } } @@ -182,14 +219,14 @@ struct LinkRow: View { CodeChip(value: "127.0.0.1:8000") } Row(label: "Auto-start on launch") { - Toggle("", isOn: $autoStart).labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: $autoStart) } Row( label: "Require API Key", sublabel: "Reject unauthenticated /v1 requests", isLast: true ) { - Toggle("", isOn: $requireKey).labelsHidden().toggleStyle(.switch) + RowSwitch(isOn: $requireKey) } } .padding(.vertical, 14) diff --git a/apps/omlx-mac/Sources/Theme/Components/ScreenScaffold.swift b/apps/omlx-mac/Sources/Theme/Components/ScreenScaffold.swift index 54969d3148..b70f295ec4 100644 --- a/apps/omlx-mac/Sources/Theme/Components/ScreenScaffold.swift +++ b/apps/omlx-mac/Sources/Theme/Components/ScreenScaffold.swift @@ -66,7 +66,7 @@ struct MessageBanner: View { row(icon: "checkmark.circle.fill", text: success, color: theme.greenDot) } } - .padding(.horizontal, 18) + .padding(.horizontal, 14) .padding(.top, (hasError || hasSuccess) ? 6 : 0) } @@ -106,6 +106,54 @@ struct HintLine: View { Text(text) .font(.omlxText(11)) .foregroundStyle(theme.textTertiary) + .fixedSize(horizontal: false, vertical: true) } } } + +/// Bottom action bar shared by screens with a trailing primary action +/// (Apply and friends): optional hint on the left that wraps under width +/// pressure, action buttons flush right, optional error line underneath. +/// One component so the button/note relationship is identical everywhere. +struct FooterBar: View { + var hint: String? = nil + var error: String? = nil + @ViewBuilder var actions: () -> Actions + + @Environment(\.omlxTheme) private var theme + + private var hasHint: Bool { !(hint ?? "").isEmpty } + private var hasError: Bool { !(error ?? "").isEmpty } + private var hasActions: Bool { Actions.self != EmptyView.self } + + var body: some View { + if hasHint || hasError || hasActions { + VStack(alignment: .leading, spacing: 6) { + if hasHint || hasActions { + HStack(alignment: .center, spacing: 12) { + if let hint, hasHint { + HintLine(text: hint) + } + Spacer(minLength: 0) + actions() + } + } + if let error, hasError { + Text(error) + .font(.omlxText(11)) + .foregroundStyle(theme.redDot) + } + } + .padding(.horizontal, 14) + .padding(.top, 8) + } + } +} + +extension FooterBar where Actions == EmptyView { + /// Error-only (or hint-only) footer — the standard trailing status line + /// under a screen. Renders nothing while there is nothing to show. + init(hint: String? = nil, error: String? = nil) { + self.init(hint: hint, error: error) { EmptyView() } + } +} diff --git a/apps/omlx-mac/Sources/Theme/Components/SectionHeader.swift b/apps/omlx-mac/Sources/Theme/Components/SectionHeader.swift index 8a414ffde7..a8ccd19fee 100644 --- a/apps/omlx-mac/Sources/Theme/Components/SectionHeader.swift +++ b/apps/omlx-mac/Sources/Theme/Components/SectionHeader.swift @@ -36,7 +36,9 @@ struct SectionHeader: View { Spacer(minLength: 0) trailing } - .padding(.horizontal, 14) + // 28 = card gutter (14) + row inset (14): header text lines up with + // the row text inside the ListGroup below, like System Settings. + .padding(.horizontal, 28) .padding(.top, 14) .padding(.bottom, 6) } diff --git a/apps/omlx-mac/Sources/Theme/Components/TextInput.swift b/apps/omlx-mac/Sources/Theme/Components/TextInput.swift index f548ea6ae6..f565d17ef0 100644 --- a/apps/omlx-mac/Sources/Theme/Components/TextInput.swift +++ b/apps/omlx-mac/Sources/Theme/Components/TextInput.swift @@ -40,7 +40,9 @@ struct TextInput: View { field .lineLimit(1) .textFieldStyle(.roundedBorder) - .font(mono ? .omlxMono(13, weight: .medium) : .omlxText(13, weight: .medium)) + // Regular weight: native macOS fields never render medium-weight + // content, and the bolder text read as a foreign control. + .font(mono ? .omlxMono(13) : .omlxText(13)) .foregroundStyle(theme.text) .overlay(alignment: .trailing) { HStack(spacing: 0) { @@ -55,7 +57,10 @@ struct TextInput: View { } } } - .frame(maxWidth: width) + // Fixed, not max: under `maxWidth` a long row label squeezes the + // field, so fields sharing a width token rendered ragged widths. + // A fixed frame makes equal tokens render equal; labels wrap. + .frame(width: width) } private var field: some View { @@ -93,11 +98,11 @@ struct TextInput: View { @Previewable @State var showKey = false @Previewable @State var alias = "" VStack(alignment: .leading, spacing: 14) { - TextInput(text: $port, placeholder: "Port", mono: true, width: 110) - TextInput(text: $qty, placeholder: "Quantity", isNumeric: true, suffix: "qty", width: 160) - TextInput(text: $temperature, placeholder: "Temperature", isNumeric: true, range: 0...2, step: 0.1, width: 160) + TextInput(text: $port, placeholder: "Port", mono: true, width: .controlCompact) + TextInput(text: $qty, placeholder: "Quantity", isNumeric: true, suffix: "qty", width: .controlCompact) + TextInput(text: $temperature, placeholder: "Temperature", isNumeric: true, range: 0...2, step: 0.1, width: .controlCompact) HStack { - TextInput(text: $pwd, placeholder: "Admin password", isSecure: !showKey, width: 200) + TextInput(text: $pwd, placeholder: "Admin password", isSecure: !showKey, width: .controlMedium) Button { showKey.toggle() } label: { @@ -107,7 +112,7 @@ struct TextInput: View { .buttonStyle(.plain) } TextInput(text: $alias, placeholder: "model-id-suffix", mono: true, - suffix: "alias", width: 240) + suffix: "alias", width: .controlMedium) } .padding(24) .omlxThemed() diff --git a/apps/omlx-mac/Sources/Theme/Theme.swift b/apps/omlx-mac/Sources/Theme/Theme.swift index 97b5b3e9c3..f4cf04e006 100644 --- a/apps/omlx-mac/Sources/Theme/Theme.swift +++ b/apps/omlx-mac/Sources/Theme/Theme.swift @@ -261,6 +261,23 @@ extension View { func omlxThemed() -> some View { modifier(OMLXThemeBinder()) } } +// MARK: - Control metrics + +/// Standard widths for trailing controls (text inputs, selects) in settings +/// rows. Every `TextInput`/`Popup` picks the smallest token that fits its +/// content instead of hand-tuning a per-row width, so control edges line up +/// between rows and across screens. +extension CGFloat { + /// Bare numbers: ports, counts, factors. + static let controlNarrow: CGFloat = 90 + /// Numbers with a suffix or stepper, short enum selects. + static let controlCompact: CGFloat = 130 + /// Names, keys, typical selects. + static let controlMedium: CGFloat = 220 + /// Paths, URLs, model-id selects. + static let controlWide: CGFloat = 320 +} + // MARK: - Color helpers extension Color { diff --git a/apps/omlx-mac/Sources/Welcome/WelcomeWindow.swift b/apps/omlx-mac/Sources/Welcome/WelcomeWindow.swift index e552b2aede..66d5d104c1 100644 --- a/apps/omlx-mac/Sources/Welcome/WelcomeWindow.swift +++ b/apps/omlx-mac/Sources/Welcome/WelcomeWindow.swift @@ -566,7 +566,7 @@ private struct WelcomeSetupBody: View { defaultValue: "Default 8000. Change this only if the port is already in use.", comment: "Sublabel for the port field with the recommended default") ) { - TextInput(text: $vm.portText, mono: true, width: 96) + TextInput(text: $vm.portText, mono: true, width: .controlNarrow) } WelcomeDivider() @@ -615,7 +615,7 @@ private struct WelcomeSetupBody: View { comment: "Sublabel explaining API key usage") ) { HStack(spacing: 0) { - TextInput("welcome.api_key.placeholder", text: $vm.apiKey, placeholder: "sk-omlx-…", isSecure: !keyVisible, mono: true, width: 210) + TextInput("welcome.api_key.placeholder", text: $vm.apiKey, placeholder: "sk-omlx-…", isSecure: !keyVisible, mono: true, width: .controlMedium) Button { keyVisible.toggle() } label: { From 080a2d932ed02665f8384599d776dbdf7472a526 Mon Sep 17 00:00:00 2001 From: Pedro Beraldo Date: Wed, 2 Sep 2026 07:43:30 -0300 Subject: [PATCH 072/132] fix(mtp): the chain rollback could not find the method behind the VLM adapter MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The mlx-vlm runtimes stamp mtp_partial_rollback on the inner LanguageModel, but the batch sees oMLX's VLMModelAdapter wrapper, which does not forward it. _chain_rollback looked only at the wrapper, found nothing, and every draft reject fell through to "cache layer rejects chain rollback" plus a full reconcile. Measured on a GLM-5.3 vision checkpoint before the fix: 2 tok/s with the MTP head reporting cycles=0 — speculation was on, doing nothing but paying the reconcile. After: 17.5 / 19.8 / 18.9 tok/s over 3x300 tokens at 73% acceptance, against 18.8 / 19.2 / 19.2 with the head off. The lookup now walks model, language_model and _language_model. --- omlx/patches/mlx_lm_mtp/batch_generator.py | 11 +++++++++- tests/test_mlx_lm_mtp_patch.py | 25 ++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/omlx/patches/mlx_lm_mtp/batch_generator.py b/omlx/patches/mlx_lm_mtp/batch_generator.py index 66df1bdb95..46185aae39 100644 --- a/omlx/patches/mlx_lm_mtp/batch_generator.py +++ b/omlx/patches/mlx_lm_mtp/batch_generator.py @@ -3201,7 +3201,16 @@ def _chain_rollback( except Exception as exc: logger.debug("rollback_speculative_cache failed: %s", exc) return False - rollback = getattr(model, "mtp_partial_rollback", None) + # The mlx-vlm runtimes stamp ``mtp_partial_rollback`` on the inner + # LanguageModel, but the batch sees oMLX's ``VLMModelAdapter`` wrapper, + # which does not forward it — measured on GLM-5.3 vision: every reject + # raised "cache layer rejects chain rollback" and reconciled (2 tok/s). + rollback = None + for candidate in (model, getattr(model, "language_model", None), + getattr(model, "_language_model", None)): + rollback = getattr(candidate, "mtp_partial_rollback", None) + if callable(rollback): + break if callable(rollback): try: return bool(rollback(prompt_cache, accepted, num_drafts)) diff --git a/tests/test_mlx_lm_mtp_patch.py b/tests/test_mlx_lm_mtp_patch.py index 13d6cc10a7..381558dbdd 100644 --- a/tests/test_mlx_lm_mtp_patch.py +++ b/tests/test_mlx_lm_mtp_patch.py @@ -2821,3 +2821,28 @@ def test_recently_active_window(self): assert tracker.recently_active(3.0) # just-finished counts tracker.clear() assert not tracker.recently_active(3.0) + + +def test_chain_rollback_finds_the_method_behind_the_vlm_adapter(): + """On the server the batch does not see the LanguageModel: it sees + ``VLMModelAdapter``, which does not forward ``mtp_partial_rollback``. The + chain rollback looked only at the wrapper, found nothing, and EVERY reject + fell through to "cache layer rejects chain rollback" plus a reconcile — + measured on a GLM-5.3 vision checkpoint at 2 tok/s with cycles=0. It now + looks at the inner model too. + """ + from omlx.patches.mlx_lm_mtp import batch_generator as bg + + calls = [] + + class _Language: + def mtp_partial_rollback(self, cache, accepted, num_drafts): + calls.append((accepted, num_drafts)) + return True + + class _Adapter: + def __init__(self): + self._language_model = _Language() + + assert bg._chain_rollback(_Adapter(), [], 1, 3, None) is True + assert calls == [(1, 3)] From 026edef62f97d587f36c8b8dd82bf5cef1b7bce5 Mon Sep 17 00:00:00 2001 From: ddark-il <44260906+ddark-il@users.noreply.github.com> Date: Fri, 4 Sep 2026 08:14:12 +0300 Subject: [PATCH 073/132] fix(qwen4_exp): restore gathered QSA for broadcast text mRoPE lost in merge 6f76565 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The #3350 series (61e1027, 262a2c6, 44e51e3, 61cd558) taught the gathered QSA prefill arm to accept text positions tiled to identical (3, 1, L) mRoPE planes, priced such prefills as gathered instead of dense in the memory guard, and added the equal-plane cache, the QSA path logger and _python_cache_offset. Merge 6f76565 resolved language.py to its first parent verbatim (diff vs ^1 is empty, vs ^2 is 507 lines), dropping all of it, and ba45eaa then deleted the tests that referenced the missing symbols. This is a correctness restore of upstream's intent rather than a throughput change on its own: the scheduler's chunked prefill already reaches the attention with 2-D or absent positions (measured at parity before/after, ~1.2-1.3k tok/s cold 48k prefill on an M5 Max), and 3-D planes show up on the Lightning MTP verify pass, which stays on the official path. The case #3350 reported — a continuation carrying mRoPE positions refused by the guard's dense pricing — is what comes back. Re-apply the language.py changes on top of the current batch-join code (the two conflicting hunks keep main's hardened _pad_index joins; the superseded _unify_index_position_list helper is not restored) and put the compat test back to expecting identical planes to gather. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01EJbV4uLny7wXtc7DVYPNtL --- .../mlx_vlm/models/qwen4_exp/language.py | 188 +++++++++++++++--- tests/test_mlx_vlm_qwen4_exp_compat.py | 17 +- 2 files changed, 171 insertions(+), 34 deletions(-) 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 ad752ba471..c32b00b12c 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 @@ -1,6 +1,7 @@ from __future__ import annotations import json +import logging import math import mmap import os @@ -36,6 +37,122 @@ _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]] = [] +_LAST_QSA_PATH_LOG: tuple[Any, ...] | None = None +logger = logging.getLogger("omlx.qwen4_qsa") + + +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 _split_text_mrope_positions( + position_ids: Optional[mx.array], + batch: int, + length: int, + past_len: int, +) -> tuple[mx.array, mx.array]: + """Indexer text ids vs rotary ids for the gathered QSA arms.""" + if position_ids is None: + text_position_ids = mx.arange( + past_len, past_len + length, dtype=mx.int32 + )[None] + rotary_position_ids = mx.broadcast_to( + text_position_ids, + (3, batch, length), + ) + return text_position_ids, rotary_position_ids + if position_ids.ndim == 3: + return position_ids[0], position_ids + return position_ids, position_ids + + +def _log_qsa_prefill_path( + path: str, + *, + kv_len: int, + query: int, + position_ndim: int | None, +) -> None: + global _LAST_QSA_PATH_LOG + key = (path, kv_len, query, position_ndim) + if key == _LAST_QSA_PATH_LOG: + return + _LAST_QSA_PATH_LOG = key + logger.info( + "qwen4 QSA prefill path=%s query=%d kv_len=%d position_ids.ndim=%s", + path, + query, + kv_len, + position_ndim, + ) + + +def _python_cache_offset(offset: Any) -> int: + """Scalar KV length for logging. Batched offsets use the longest row. + + ``BatchQSAKVCache.offset`` is an ``mx.array`` of per-row lengths. ``int()`` + on that array raises ``[convert] Only length-1 arrays...`` and used to + abort the engine before eligibility could fail closed onto the official + path. Logging still wants one number; the longest row is the conservative + choice for ``kv_len``. + """ + if offset is None: + return 0 + if isinstance(offset, (int, np.integer)): + return int(offset) + shape = getattr(offset, "shape", None) + if shape is None: + try: + return int(offset) + except (TypeError, ValueError): + return 0 + size = 1 + for dim in shape: + size *= int(dim) + if size <= 1: + value = offset.reshape(-1)[0] if size == 1 else offset + return int(value.item()) if hasattr(value, "item") else int(value) + return int(mx.max(offset).item()) + + +def _promote_index_positions_to_3d(positions: mx.array, planes: int) -> mx.array: + if positions.ndim == 3: + if int(positions.shape[0]) != planes: + raise ValueError( + "QSA indexer mRoPE plane count mismatch during cache extend: " + f"{tuple(int(d) for d in positions.shape)} vs planes={planes}" + ) + return positions + return mx.broadcast_to(positions[None], (planes, *positions.shape)) @dataclass(frozen=True) @@ -1132,13 +1249,9 @@ def _batch_one_text_position_ids( position_ids: Optional[mx.array], length: int, ) -> bool: - """Accept absent or shape-matched 2-D text positions, never MRoPE.""" + """Accept absent, 2-D text, or broadcast-identical 3-D text mRoPE.""" - return position_ids is None or bool( - isinstance(position_ids, mx.array) - and position_ids.ndim == 2 - and position_ids.shape == (1, length) - ) + return _broadcast_text_mrope_position_ids(position_ids, length) def _gathered_text_prefill_eligible( self, @@ -1180,7 +1293,12 @@ def _gathered_text_decode_eligible( position_embeddings: Optional[tuple[mx.array, mx.array]], target_verify: bool, ) -> bool: - """Fail closed outside scalar-offset batch-one text decode.""" + """Fail closed outside scalar-offset batch-one text decode. + + Prefill may accept broadcast-identical 3-D text mRoPE. Decode keeps + the 2-D / absent predicate until that arm has its own numerical + parity coverage. + """ causal_mask = mask is None or (isinstance(mask, str) and mask == "causal") if not ( @@ -1191,7 +1309,13 @@ def _gathered_text_decode_eligible( and isinstance(cache.offset, int) and position_embeddings is None and not target_verify - and self._batch_one_text_position_ids(position_ids, 1) + and ( + position_ids is None + or ( + position_ids.ndim == 2 + and tuple(position_ids.shape) == (1, 1) + ) + ) ): return False @@ -1239,17 +1363,9 @@ def _gathered_text_prefill( ).transpose(0, 2, 1, 3) past_len = cache.offset - if position_ids is None: - text_position_ids = mx.arange( - past_len, past_len + length, dtype=mx.int32 - )[None] - rotary_position_ids = mx.broadcast_to( - text_position_ids, - (3, batch, length), - ) - else: - text_position_ids = position_ids - rotary_position_ids = position_ids + text_position_ids, rotary_position_ids = _split_text_mrope_positions( + position_ids, batch, length, past_len + ) queries, keys = self.rotary_emb.apply_rotary( queries, keys, @@ -1340,19 +1456,9 @@ def _gathered_text_decode( ).transpose(0, 2, 1, 3) past_len = cache.offset - if position_ids is None: - text_position_ids = mx.arange( - past_len, - past_len + 1, - dtype=mx.int32, - )[None] - rotary_position_ids = mx.broadcast_to( - text_position_ids, - (3, batch, length), - ) - else: - text_position_ids = position_ids - rotary_position_ids = position_ids + text_position_ids, rotary_position_ids = _split_text_mrope_positions( + position_ids, batch, length, past_len + ) queries, new_keys = self.rotary_emb.apply_rotary( queries, new_keys, @@ -1408,6 +1514,11 @@ def __call__( position_embeddings: Optional[tuple[mx.array, mx.array]] = None, target_verify: bool = False, ) -> mx.array: + query = int(x.shape[1]) if x.ndim == 3 else 0 + kv_len = _python_cache_offset(getattr(cache, "offset", 0)) + query + position_ndim = ( + int(position_ids.ndim) if isinstance(position_ids, mx.array) else None + ) if self._gathered_text_decode_eligible( x, mask, @@ -1426,8 +1537,21 @@ def __call__( position_embeddings, target_verify, ): + _log_qsa_prefill_path( + "gathered", + kv_len=kv_len, + query=query, + position_ndim=position_ndim, + ) return self._gathered_text_prefill(x, cache, position_ids) + if query > 1: + _log_qsa_prefill_path( + "mask_dense", + kv_len=kv_len, + query=query, + position_ndim=position_ndim, + ) qsa_mask = self.indexer( x, cache, diff --git a/tests/test_mlx_vlm_qwen4_exp_compat.py b/tests/test_mlx_vlm_qwen4_exp_compat.py index fefb0e244e..e24acfcb66 100644 --- a/tests/test_mlx_vlm_qwen4_exp_compat.py +++ b/tests/test_mlx_vlm_qwen4_exp_compat.py @@ -677,7 +677,7 @@ def test_qwen4_rank_two_text_positions_match_identical_mrope_plane_logits( None, False, ) - assert not attention._gathered_text_prefill_eligible( + assert attention._gathered_text_prefill_eligible( hidden, "causal", QSAKVCache(), @@ -685,6 +685,18 @@ def test_qwen4_rank_two_text_positions_match_identical_mrope_plane_logits( None, False, ) + unequal_mrope = mx.concatenate( + [text_positions[None], text_positions[None], text_positions[None] + 1], + axis=0, + ) + assert not attention._gathered_text_prefill_eligible( + hidden, + "causal", + QSAKVCache(), + unequal_mrope, + None, + False, + ) gathered_calls = [] original_gathered = language.contiguous_causal_gathered_qsa @@ -716,7 +728,8 @@ def tracked_gathered(*args, **kwargs): expected_logits = expected @ projection mx.eval(actual_logits, expected_logits) - assert gathered_calls == [True] + # Both the 2-D and the broadcast 3-D text positions take the gathered arm. + assert gathered_calls == [True, True] assert mx.allclose(actual, expected, rtol=2e-5, atol=2e-5).item() assert mx.allclose( actual_logits, From 30b085c71af963dcad9b42c62fea1f26e6461708 Mon Sep 17 00:00:00 2001 From: ddark-il <44260906+ddark-il@users.noreply.github.com> Date: Fri, 4 Sep 2026 08:56:58 +0300 Subject: [PATCH 074/132] perf(qwen4_exp): keep narrow multi-row text windows on the official QSA path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With the #3350 arm restored, every batch-one multi-row text call above the QSA crossover gathers — including the 2-4 row history/verify passes that Lightning MTP issues on every cycle. Measured per attention layer on an M5 Max (Qwen3.8-Flash-Next geometry, native kernels, pooled index cache warm), gathered vs official mask+SDPA, ms: S=1 S=2 S=4 S=8 S=16 S=64 206k ctx 4.20 4.56 5.02 6.28 8.65 24.6 gathered 1.40 2.14 3.49 6.45 12.2 47.3 official 48k ctx 1.74 2.01 2.61 3.68 6.46 22.5 gathered 1.37 1.46 2.22 3.94 7.36 27.7 official The per-row gather of token_budget K/V rows only pays off from about eight query rows; below that MLX's masked SDPA over the full cache is 1.4-3x cheaper. Gate the gathered prefill arm at 16 query rows (OMLX_QWEN4_GATHERED_MIN_QUERY overrides) so real prefill chunks keep gathering and MTP windows stay on the official path. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01EJbV4uLny7wXtc7DVYPNtL --- .../mlx_vlm/models/qwen4_exp/language.py | 24 +++++++++- tests/test_qwen4_qsa_decode_gather.py | 44 +++++++++++++++++++ 2 files changed, 67 insertions(+), 1 deletion(-) 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 c32b00b12c..c53c904d29 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 @@ -74,6 +74,25 @@ def _broadcast_text_mrope_position_ids( return same +def _gathered_min_query_tokens() -> int: + """Query rows below which the official mask+SDPA path is faster. + + Measured on an M5 Max at 12k/48k/206k context (Qwen3.8-Flash-Next + geometry, native kernels): the per-row gather of ``token_budget`` K/V + rows costs more than MLX's masked SDPA over the full cache until about + eight query rows, and the official path wins by 1.4-3x for the 1-4 row + windows Lightning MTP issues. Real prefill chunks are far wider. + ``OMLX_QWEN4_GATHERED_MIN_QUERY`` overrides the default of 16. + """ + raw = os.environ.get("OMLX_QWEN4_GATHERED_MIN_QUERY", "").strip() + if raw: + try: + return max(2, int(raw)) + except ValueError: + pass + return 16 + + def _split_text_mrope_positions( position_ids: Optional[mx.array], batch: int, @@ -1268,7 +1287,10 @@ def _gathered_text_prefill_eligible( if not ( x.ndim == 3 and x.shape[0] == 1 - and x.shape[1] > 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) diff --git a/tests/test_qwen4_qsa_decode_gather.py b/tests/test_qwen4_qsa_decode_gather.py index 2b65845ff2..0ab3fb5f9c 100644 --- a/tests/test_qwen4_qsa_decode_gather.py +++ b/tests/test_qwen4_qsa_decode_gather.py @@ -111,6 +111,8 @@ def tracked_sdpa(queries, keys, values, scale): def test_qwen4_language_wrapper_routes_2d_text_positions_to_gather(monkeypatch): + # The fixture prefill is 10 rows; lower the gathered width gate for it. + monkeypatch.setenv("OMLX_QWEN4_GATHERED_MIN_QUERY", "2") config = _tiny_text_config() import mlx_vlm.models.qwen4_exp.language as language @@ -374,3 +376,45 @@ def native(queries, keys, values, scale, causal=False): (256**-0.5, False, "native"), ] assert mx.array_equal(actual, expected).item() + + +def _crossover_cache(config, attention, length=12, seed=23): + """Prefill ``length`` tokens so completed blocks exceed the QSA budget.""" + mx.random.seed(seed) + cache = _language().QSAKVCache() + prefix = mx.random.normal((1, length, config.hidden_size)) + mx.eval(attention(prefix, mask="causal", cache=cache)) + return cache + + +def _language(): + import mlx_vlm.models.qwen4_exp.language as language + + return language + + +def test_qwen4_gathered_prefill_requires_minimum_query_width(monkeypatch): + """Narrow multi-row windows (MTP passes) stay on the cheaper official path.""" + config = _tiny_text_config() + language = _language() + attention = language.Qwen4ExpAttention(config) + mx.eval(attention.parameters()) + cache = _crossover_cache(config, attention) + narrow = mx.random.normal((1, 4, config.hidden_size)) + wide = mx.random.normal((1, 16, config.hidden_size)) + + monkeypatch.delenv("OMLX_QWEN4_GATHERED_MIN_QUERY", raising=False) + assert language._gathered_min_query_tokens() == 16 + assert not attention._gathered_text_prefill_eligible( + narrow, "causal", cache, None, None, False + ) + assert attention._gathered_text_prefill_eligible( + wide, "causal", cache, None, None, False + ) + + monkeypatch.setenv("OMLX_QWEN4_GATHERED_MIN_QUERY", "2") + assert attention._gathered_text_prefill_eligible( + narrow, "causal", cache, None, None, False + ) + monkeypatch.setenv("OMLX_QWEN4_GATHERED_MIN_QUERY", "garbage") + assert language._gathered_min_query_tokens() == 16 From 8654ba85b66d2dacd8adabac7e119fb142767af7 Mon Sep 17 00:00:00 2001 From: ddark-il <44260906+ddark-il@users.noreply.github.com> Date: Fri, 4 Sep 2026 08:56:58 +0300 Subject: [PATCH 075/132] perf(qwen4_exp): keep the pooled QSA index prefix across cache trims QSAKVCache.trim() invalidated the whole pooled index-key bank, so the next attention call re-pooled every completed block of the context: 1.75 ms per QSA layer at 206k tokens. Lightning MTP trims after every cycle with a rejected draft, so long-context decode paid that on almost every cycle (~0.75 ms/layer net, ~9 ms per cycle over 12 layers measured in-process at 206k). Pooled blocks strictly below the new complete-block count are built from raw keys that trim does not touch, so clamp the pooled frontier instead and let pooled_indexer_keys() re-pool only the tail. Restore, extract and capacity growth still rebuild from scratch. Exactness is covered by comparing the retained prefix plus lazy tail against a full recompute after trims that do and do not cross a block boundary, and by a verify -> rollback -> decode parity check. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01EJbV4uLny7wXtc7DVYPNtL --- .../mlx_vlm/models/qwen4_exp/language.py | 13 +++- tests/test_qwen4_qsa_decode_gather.py | 78 +++++++++++++++++++ tests/test_qwen4_qsa_incremental_cache.py | 5 +- 3 files changed, 94 insertions(+), 2 deletions(-) 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 c53c904d29..cb4e36ae1e 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 @@ -490,7 +490,18 @@ def pooled_indexer_keys( def _trim_indexer(self, length: int): self._index_offset = min(self._index_offset, max(0, int(length))) - self._invalidate_pooled_indexer() + # Pooled blocks strictly below the new complete-block count are built + # from raw keys that trim does not touch, so keep them and only clamp + # the pooled frontier. Lightning MTP trims after every rejected + # draft; a full invalidation re-pooled every block of the context on + # the next call (1.75 ms/layer at 206k tokens). + if self._pooled_index_keys is not None and self._pooled_index_ratio: + self._pooled_index_offset = min( + self._pooled_index_offset, + self._index_offset // self._pooled_index_ratio, + ) + else: + self._invalidate_pooled_indexer() @property def indexer_nbytes(self): diff --git a/tests/test_qwen4_qsa_decode_gather.py b/tests/test_qwen4_qsa_decode_gather.py index 0ab3fb5f9c..269710da61 100644 --- a/tests/test_qwen4_qsa_decode_gather.py +++ b/tests/test_qwen4_qsa_decode_gather.py @@ -418,3 +418,81 @@ def test_qwen4_gathered_prefill_requires_minimum_query_width(monkeypatch): ) monkeypatch.setenv("OMLX_QWEN4_GATHERED_MIN_QUERY", "garbage") assert language._gathered_min_query_tokens() == 16 + + +def test_qwen4_trim_keeps_pooled_index_prefix_exact(): + """trim() clamps the pooled frontier instead of re-pooling every block.""" + config = _tiny_text_config() + language = _language() + attention = language.Qwen4ExpAttention(config) + mx.eval(attention.parameters()) + ratio = config.indexer_compress_ratio + indexer = attention.indexer + + cache = _crossover_cache(config, attention, length=14, seed=51) + pooled_before = cache.pooled_indexer_keys( + ratio, indexer.k_layernorm, indexer._apply_rope, cache_tag=indexer + ) + mx.eval(pooled_before) + assert cache._pooled_index_offset == 14 // ratio + + # Speculative window of 3 rows, then reject two of them (MTP rollback). + window = mx.random.normal((1, 3, config.hidden_size)) + mx.eval(attention(window, mask="causal", cache=cache, target_verify=True)) + assert cache.trim(2) == 2 + assert cache.offset == 15 + # Pooled blocks below the new complete count survive the trim. + assert cache._pooled_index_keys is not None + assert cache._pooled_index_offset == 15 // ratio + + incremental = cache.pooled_indexer_keys( + ratio, indexer.k_layernorm, indexer._apply_rope, cache_tag=indexer + ) + cache._invalidate_pooled_indexer() + full = cache.pooled_indexer_keys( + ratio, indexer.k_layernorm, indexer._apply_rope, cache_tag=indexer + ) + mx.eval(incremental, full) + assert incremental.shape == full.shape == (1, 15 // ratio, config.indexer_head_dim) + assert mx.array_equal(incremental, full).item() + + # A trim that crosses a completed block boundary drops that block too. + assert cache.trim(3) == 3 + assert cache._pooled_index_offset == 12 // ratio + again = cache.pooled_indexer_keys( + ratio, indexer.k_layernorm, indexer._apply_rope, cache_tag=indexer + ) + cache._invalidate_pooled_indexer() + again_full = cache.pooled_indexer_keys( + ratio, indexer.k_layernorm, indexer._apply_rope, cache_tag=indexer + ) + mx.eval(again, again_full) + assert mx.array_equal(again, again_full).item() + + +def test_qwen4_trim_then_decode_matches_official_after_partial_invalidation( + monkeypatch, +): + """Verify -> rollback -> decode stays exact with the retained pooled prefix.""" + config = _tiny_text_config() + language = _language() + monkeypatch.setenv("OMLX_QWEN4_GATHERED_MIN_QUERY", "2") + attention = language.Qwen4ExpAttention(config) + mx.eval(attention.parameters()) + fast_cache = _crossover_cache(config, attention, length=12, seed=61) + reference_cache = _crossover_cache(config, attention, length=12, seed=61) + + window = mx.random.normal((1, 4, config.hidden_size)) + mx.eval( + attention(window, mask="causal", cache=fast_cache, target_verify=True), + attention(window, mask="causal", cache=reference_cache, target_verify=True), + ) + assert fast_cache.trim(2) == reference_cache.trim(2) == 2 + # Reference: force a full re-pool as the previous behaviour did. + reference_cache._invalidate_pooled_indexer() + + token = mx.random.normal((1, 1, config.hidden_size)) + actual = attention(token, mask=None, cache=fast_cache) + expected = attention(token, mask=None, cache=reference_cache) + mx.eval(actual, expected) + assert mx.array_equal(actual, expected).item() diff --git a/tests/test_qwen4_qsa_incremental_cache.py b/tests/test_qwen4_qsa_incremental_cache.py index 136a891cb6..fb0d717cb6 100644 --- a/tests/test_qwen4_qsa_incremental_cache.py +++ b/tests/test_qwen4_qsa_incremental_cache.py @@ -199,7 +199,10 @@ def test_qsa_ephemeral_pool_rebuilds_after_restore_extract_and_trim(): assert mx.array_equal(extracted_pool, pooled).item() assert cache.trim(3) == 3 - assert cache._pooled_index_keys is None + # trim keeps the pooled blocks below the new complete count (10 // 4 = 2) + # and only clamps the pooled frontier; the tail is re-pooled lazily. + assert cache._pooled_index_keys is not None + assert cache._pooled_index_offset == 2 replacement = mx.cos(mx.arange(3 * 8, dtype=mx.float32)).reshape(1, 3, 8) _append(cache, mx.concatenate([raw[:, :10], replacement], axis=1), 10, 13) rebuilt = cache.pooled_indexer_keys( From ecbd955bc4306c0628289f723fac0af7ed4cadb2 Mon Sep 17 00:00:00 2001 From: Matthijs van den Bos Date: Sat, 5 Sep 2026 14:40:48 +0200 Subject: [PATCH 076/132] fix(qwen4_exp): stop QSA prefill-path logger spamming on every prefill _log_qsa_prefill_path dedups on (path, kv_len, query, position_ndim), but kv_len grows by query tokens on every prefill call, so consecutive prefills never produce the same key and the guard fires on every one. During streaming this logs a line every few ms. Drop kv_len from the dedup key (keep path/query/position_ndim); kv_len stays in the message as informational payload. --- .../vendor/mlx_vlm/models/qwen4_exp/language.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) 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 cb4e36ae1e..f1420d3888 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 @@ -121,8 +121,10 @@ def _log_qsa_prefill_path( query: int, position_ndim: int | None, ) -> None: + # kv_len grows by `query` on every prefill, so including it makes the + # dedup miss every time (context streams in -> spams one line per token). global _LAST_QSA_PATH_LOG - key = (path, kv_len, query, position_ndim) + key = (path, query, position_ndim) if key == _LAST_QSA_PATH_LOG: return _LAST_QSA_PATH_LOG = key From 72d76c057d0c75cbd50d2d5357e9a9e487ee7cfa Mon Sep 17 00:00:00 2001 From: Matthijs van den Bos Date: Sat, 5 Sep 2026 14:57:19 +0200 Subject: [PATCH 077/132] fix(qwen4_exp): throttle QSA path logging when keys alternate Consecutive-key dedup never fires in practice: a decode loop alternates (path, query, position_ndim) every cycle (ndim 3 <-> None when requests interleave) and kv_len changes on every call, so every call logs. Throttle each distinct key to one line per 5s interval instead; kv_len stays in the message as informational payload. --- .../vendor/mlx_vlm/models/qwen4_exp/language.py | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) 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 f1420d3888..cdba315330 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 @@ -3,6 +3,7 @@ import json import logging import math +import time import mmap import os import struct @@ -39,7 +40,8 @@ _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]] = [] -_LAST_QSA_PATH_LOG: tuple[Any, ...] | None = None +_LAST_QSA_PATH_LOG: dict[tuple[str, int, int | None], float] = {} +_QSA_PATH_LOG_MIN_INTERVAL_S = 5.0 logger = logging.getLogger("omlx.qwen4_qsa") @@ -121,13 +123,17 @@ def _log_qsa_prefill_path( query: int, position_ndim: int | None, ) -> None: - # kv_len grows by `query` on every prefill, so including it makes the - # dedup miss every time (context streams in -> spams one line per token). + # Consecutive-key dedup alone never fires: a decode loop alternates + # (path, query, ndim) every cycle (ndim 3 <-> None in interleaved + # requests) and kv_len changes on every call. Throttle each distinct + # key to one line per interval instead. global _LAST_QSA_PATH_LOG key = (path, query, position_ndim) - if key == _LAST_QSA_PATH_LOG: + now = time.monotonic() + last = _LAST_QSA_PATH_LOG.get(key) + if last is not None and now - last < _QSA_PATH_LOG_MIN_INTERVAL_S: return - _LAST_QSA_PATH_LOG = key + _LAST_QSA_PATH_LOG[key] = now logger.info( "qwen4 QSA prefill path=%s query=%d kv_len=%d position_ids.ndim=%s", path, From ffa19d10683203c5d3b80630118749a179138663 Mon Sep 17 00:00:00 2001 From: Matthijs van den Bos Date: Sat, 5 Sep 2026 16:44:58 +0200 Subject: [PATCH 078/132] fix(qwen4_exp): bound masked SDPA256 memory pricing Price the head-dim-256 unfused fallback at fp32, route explicit array masks through bounded tiling, and let the Qwen4 profile trust only array-mask-capable bounded routes. Retire stale unfused transient samples when the runtime route flips so EWMA cannot throttle the bounded regime. Keep regression tests standalone and restore patched global state. --- omlx/memory_monitor.py | 52 +++++- omlx/patches/sdpa256_attention.py | 44 +++++- omlx/prefill_transient_tracker.py | 11 +- omlx/scheduler.py | 9 ++ tests/test_memory_monitor.py | 209 +++++++++++++++++++++++++ tests/test_prefill_oom_graceful.py | 65 +++++++- tests/test_qwen4_qsa_prefill_memory.py | 129 +++++++++++++++ tests/test_sdpa256_attention.py | 124 ++++++++++++++- 8 files changed, 624 insertions(+), 19 deletions(-) diff --git a/omlx/memory_monitor.py b/omlx/memory_monitor.py index feed9fa25a..badaac4363 100644 --- a/omlx/memory_monitor.py +++ b/omlx/memory_monitor.py @@ -54,6 +54,18 @@ # dim-less path and matches the fp16/bf16 majority of MLX inference models. _SDPA_FALLBACK_SCORE_DTYPE_SIZE = 2 +# Bytes/elem the unfused head-dim-256 fallback actually materializes on +# Metal: MLX keeps the attention score matrix in fp32 even for bf16/fp16 +# models (measured ~33GiB IOAccelerator spike on a 160k-token VLM prefill at +# head_dim=256). Shared by the sdpa256 route gate +# (patches/sdpa256_attention._tiled_route_required) and the Qwen4 prefill +# profile so the router and the guard price the real fallback identically. +# Kept separate from _SDPA_FALLBACK_SCORE_DTYPE_SIZE: that default covers +# the dim-less generic path where the compute dtype is unknown and the +# fp16/bf16 majority is the better prior; widening it globally would +# re-price unrelated models without evidence. +SDPA256_UNFUSED_SCORE_DTYPE_SIZE = 4 + # Head dims whose multi-token prefill is routed to an O(L) tiled/online-softmax # kernel instead of the unfused O(L^2) score-matrix fallback. Populated at # runtime by the kernel patch that installs the route (see @@ -68,6 +80,7 @@ class _BoundedSDPAPrefillRoute: min_query_len: int min_kv_len: int kv_tile: int + supports_array_mask: bool _SDPA_TILED_PREFILL_HEAD_DIMS: dict[int, tuple[_BoundedSDPAPrefillRoute, ...]] = {} @@ -79,18 +92,20 @@ def register_tiled_prefill_head_dim( min_query_len: int = 2, min_kv_len: int = 8192, kv_tile: int = 1024, + supports_array_mask: bool = False, ) -> None: """Register a bounded long-context route installed for one head dim. Multiple native routes may cover the same head dimension at different - thresholds. Store them independently so combining two registrations can - never invent shape coverage that neither route actually guarantees. + thresholds and mask capabilities. Store them independently so combining + registrations cannot invent coverage no individual route guarantees. """ head_dim = int(head_dim) route = _BoundedSDPAPrefillRoute( min_query_len=max(2, int(min_query_len)), min_kv_len=max(1, int(min_kv_len)), kv_tile=max(1, int(kv_tile)), + supports_array_mask=bool(supports_array_mask), ) routes = _SDPA_TILED_PREFILL_HEAD_DIMS.get(head_dim, ()) if route not in routes: @@ -1295,13 +1310,44 @@ def estimate_prefill_transient_bytes( core_kv = kv_len if gathered_core and kv_len > self.indexer_budget: core_kv = min(kv_len, self.indexer_budget + self.compress_ratio - 1) + + # The head_dim-256 sdpa256 patch keeps long-context prefill O(L): + # consult the same bounded-route registry the generic estimator uses + # (issue #2204 follow-up). Without it this profile always charges the + # dense Q x kv_len matrix, which made the guard shrink VLM chunks to + # crawl speed on 160k-context prefills even though the router forces + # a bounded kernel there. core = estimate_unfused_sdpa_call_bytes( self.num_attention_heads, query_tokens, core_kv, self.head_dim, - self.score_dtype_size, + SDPA256_UNFUSED_SCORE_DTYPE_SIZE, ) + bounded_routes = _SDPA_TILED_PREFILL_HEAD_DIMS.get(self.head_dim, ()) + matching_routes = [ + route + for route in bounded_routes + if route.supports_array_mask + and query_tokens >= route.min_query_len + and core_kv >= route.min_kv_len + ] + if matching_routes: + # Match the generic estimator's O(L) bound: fp32 output plus one + # fp32 score tile (largest registered tile). The core_kv is the + # K width of the real core-attention call, so a gathered QSA call + # whose reduced K is below the route floor stays dense-priced. + kv_tile = max(route.kv_tile for route in matching_routes) + tile_scores = ( + self.num_attention_heads + * query_tokens + * min(kv_tile, core_kv) + * SDPA256_UNFUSED_SCORE_DTYPE_SIZE + ) + output = ( + self.num_attention_heads * query_tokens * self.head_dim * 4 + ) + core = int(output + tile_scores) return indexer + core diff --git a/omlx/patches/sdpa256_attention.py b/omlx/patches/sdpa256_attention.py index 5f2811fd1b..73e1c3fcc4 100644 --- a/omlx/patches/sdpa256_attention.py +++ b/omlx/patches/sdpa256_attention.py @@ -29,7 +29,10 @@ import mlx.core as mx -from omlx.memory_monitor import estimate_unfused_sdpa_call_bytes +from omlx.memory_monitor import ( + SDPA256_UNFUSED_SCORE_DTYPE_SIZE, + estimate_unfused_sdpa_call_bytes, +) logger = logging.getLogger(__name__) @@ -95,6 +98,17 @@ def _parse_force_tiled_env() -> bool | None: return None +def _notify_bounded_route(provider, active: bool) -> None: + """Let the scheduler retire measurements from the previous route.""" + try: + owner = getattr(provider, "__self__", None) + callback = getattr(owner, "_sdpa256_bounded_route_changed", None) + if callable(callback): + callback(active) + except Exception: + logger.debug("sdpa256 route notification failed", exc_info=True) + + def _tiled_route_required(queries, keys) -> bool: """Decide forced-fused vs default for a matched call (True = force). @@ -102,12 +116,13 @@ def _tiled_route_required(queries, keys) -> bool: (issues #2155 / #2204), so force the fused path only when the unfused transient would not fit under the guard ceiling — or when no headroom info is available, keeping the memory-safe #2025 behavior.""" + provider = _HEADROOM_PROVIDER() if _HEADROOM_PROVIDER is not None else None if _FORCE_TILED is not None: if _FORCE_TILED: _note_tiled_route("forced", "forced by OMLX_SDPA256_TILED=1") + _notify_bounded_route(provider, _FORCE_TILED) return _FORCE_TILED try: - provider = _HEADROOM_PROVIDER() if _HEADROOM_PROVIDER is not None else None if provider is None: _note_tiled_route( "no-provider", @@ -122,6 +137,7 @@ def _tiled_route_required(queries, keys) -> bool: "memory ceiling not available (enforcer state not yet " "propagated)", ) + _notify_bounded_route(provider, True) return True batch, n_q, q_len, _ = queries.shape transient = estimate_unfused_sdpa_call_bytes( @@ -129,17 +145,22 @@ def _tiled_route_required(queries, keys) -> bool: q_len, keys.shape[-2], HEAD_DIM, - score_dtype_size=queries.dtype.size, + # The unfused fallback materializes fp32 scores even for bf16 + # inputs (issue #2204 follow-up): pricing it at the query dtype + # halves the predicted matrix and admits OOM spikes at long + # context. Shared with the guard via the memory_monitor constant. + score_dtype_size=SDPA256_UNFUSED_SCORE_DTYPE_SIZE, ) - if transient > headroom: + bounded = transient > headroom + _notify_bounded_route(provider, bounded) + if bounded: _note_tiled_route( "insufficient-headroom", f"unfused transient ~{transient / 2**20:.0f}MiB exceeds live " f"guard headroom ~{headroom / 2**20:.0f}MiB at " f"kv_len={keys.shape[-2]}", ) - return True - return False + return bounded except Exception: _note_tiled_route("probe-error", "guard headroom probe failed") logger.debug("sdpa256 headroom probe failed", exc_info=True) @@ -233,7 +254,15 @@ def _array_tiled_sdpa256(queries, keys, values, scale, mask, sinks=None): def _flash_sdpa256(queries, keys, values, scale, mask, sinks=None): - """Use MLX 0.32.2 native fused SDPA on Metal, portable tiling elsewhere.""" + """Use MLX 0.32.2 native fused SDPA on Metal, portable tiling elsewhere. + + Explicit array masks never take the native fused call: MLX's fused + array-mask support is unproven and may silently fall back to the + unfused fp32 score matrix, which is exactly the O(L^2) spike this patch + exists to bound. The array-tiled implementation already handles bool and + additive masks, so route them there directly.""" + if isinstance(mask, mx.array): + return _array_tiled_sdpa256(queries, keys, values, scale, mask, sinks) native_shape = values.shape[-1] == HEAD_DIM and not ( isinstance(mask, str) and mask == "causal" @@ -297,6 +326,7 @@ def _register_bounded_route(min_kv_len: int) -> bool: min_query_len=_SDPA256_MIN_Q_LEN, min_kv_len=min_kv_len, kv_tile=_KV_TILE, + supports_array_mask=True, ) except Exception: logger.debug("could not register sdpa256 with memory_monitor", exc_info=True) diff --git a/omlx/prefill_transient_tracker.py b/omlx/prefill_transient_tracker.py index f2db08acb9..5b08aab8fc 100644 --- a/omlx/prefill_transient_tracker.py +++ b/omlx/prefill_transient_tracker.py @@ -231,8 +231,15 @@ def recent_reclaim_bytes(self) -> int: """Footprint released since the last positive chunk measurement.""" return self._recent_reclaim_bytes + def reset_history(self, *, gathered_core: bool = False) -> None: + """Drop observations for one execution regime.""" + if gathered_core: + self._gathered_history = _TransientHistory() + else: + self._dense_history = _TransientHistory() + def reset(self) -> None: """Drop all observations (e.g. on model reload or after a long idle).""" - self._dense_history = _TransientHistory() - self._gathered_history = _TransientHistory() + self.reset_history() + self.reset_history(gathered_core=True) self._recent_reclaim_bytes = 0 diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 1bbb6faab5..c7f5a711d6 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -1997,6 +1997,7 @@ def __init__( self._prefill_transient_tracker = PrefillTransientTracker( model_id=_tracker_model_id ) + self._sdpa256_bounded_route_active: bool | None = None # One-shot probe of the GDN/Mamba fixed recurrent-state footprint, # armed by _set_model_info_for_monitor when ArraysCache layers exist # and taken after the first prefill chunk's eval. @@ -4029,6 +4030,14 @@ def _prefill_abort_description(self) -> tuple[int, int, float]: safety_cap = self._prefill_abort_cap() return base_cap, safety_cap, self._prefill_abort_margin + def _sdpa256_bounded_route_changed(self, active: bool) -> None: + """Retire measurements when SDPA256 changes memory regimes.""" + previous = getattr(self, "_sdpa256_bounded_route_active", None) + active = bool(active) + self._sdpa256_bounded_route_active = active + if previous != active and (previous is not None or active): + self._prefill_transient_tracker.reset_history() + def _sdpa256_unfused_headroom(self) -> int: """Live headroom (bytes) for one unfused SDPA transient, under the same target the adaptive prefill throttle enforces (hard ceiling x diff --git a/tests/test_memory_monitor.py b/tests/test_memory_monitor.py index 02b16dc6dc..189c13331f 100644 --- a/tests/test_memory_monitor.py +++ b/tests/test_memory_monitor.py @@ -1078,6 +1078,215 @@ def test_non_v4_config_keeps_generic_estimator(self): assert make_prefill_memory_profile(config, compute_dtype_size=2) is None +class TestQwen4ExpPrefillMemoryProfile: + """Qwen4 profile must price the head-dim-256 core through the same + bounded-route registry the generic estimator uses: dense Q x kv_len fp32 + without a registered route, output + one fp32 score tile with one.""" + + @staticmethod + def _profile(): + from omlx.memory_monitor import make_prefill_memory_profile + + config = SimpleNamespace( + model_type="qwen4_exp", + num_hidden_layers=48, + num_attention_heads=24, + num_key_value_heads=2, + head_dim=256, + indexer_n_heads=4, + indexer_head_dim=128, + indexer_budget=2048, + indexer_compress_ratio=4, + full_attention_interval=4, + layer_types=None, + ) + return make_prefill_memory_profile(config, compute_dtype_size=2) + + def _monitor(self, profile): + from omlx.memory_monitor import MemoryMonitor + + monitor = MemoryMonitor(max_kv_cache_memory=None, eviction_enabled=False) + monitor.set_model_info( + num_layers=48, + num_kv_heads=2, + head_dim=256, + dtype_size=2, + num_attention_heads=24, + compute_dtype_size=2, + prefill_memory_profile=profile, + ) + return monitor + + @staticmethod + def _indexer_bytes(query_tokens, kv_len): + pooled = max(kv_len // 4, 1) + return 4 * query_tokens * pooled * 4 + 4 * query_tokens * 128 * 4 + + def test_no_registration_prices_dense_fp32_core(self): + import omlx.memory_monitor as memory_monitor + + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + try: + profile = self._profile() + query_tokens, kv_len = 2048, 160_000 + estimate = profile.estimate_prefill_transient_bytes( + query_tokens, kv_len + ) + # Dense unfused core is priced at the measured fp32 width, not + # the bf16 model compute dtype (issue #2204 follow-up). + assert estimate == self._indexer_bytes(query_tokens, kv_len) + ( + 24 * query_tokens * kv_len * 4 + 24 * query_tokens * 256 * 4 + ) + finally: + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + + def test_causal_only_registration_keeps_array_mask_core_dense(self): + import omlx.memory_monitor as memory_monitor + + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + memory_monitor.register_tiled_prefill_head_dim( + 256, min_query_len=16, min_kv_len=2048, kv_tile=1024 + ) + try: + profile = self._profile() + query_tokens, kv_len = 2048, 4096 + expected = self._indexer_bytes(query_tokens, kv_len) + ( + 24 * query_tokens * kv_len * 4 + 24 * query_tokens * 256 * 4 + ) + assert profile.estimate_prefill_transient_bytes( + query_tokens, kv_len + ) == expected + finally: + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + + def test_matching_registration_prices_output_plus_one_fp32_tile(self): + import omlx.memory_monitor as memory_monitor + + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + memory_monitor.register_tiled_prefill_head_dim( + 256, min_query_len=16, min_kv_len=8192, kv_tile=1024, supports_array_mask=True + ) + try: + profile = self._profile() + query_tokens, kv_len = 2048, 160_000 + estimate = profile.estimate_prefill_transient_bytes( + query_tokens, kv_len + ) + # Indexer charge is retained; the core is fp32 output plus one + # 1024-wide fp32 score tile — no Q x kv_len matrix. + expected = self._indexer_bytes(query_tokens, kv_len) + ( + 24 * query_tokens * 256 * 4 + 24 * query_tokens * 1024 * 4 + ) + assert estimate == expected + dense = self._indexer_bytes(query_tokens, kv_len) + ( + 24 * query_tokens * kv_len * 4 + 24 * query_tokens * 256 * 4 + ) + assert estimate < dense / 10 + finally: + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + + def test_threshold_misses_stay_dense(self): + import omlx.memory_monitor as memory_monitor + + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + memory_monitor.register_tiled_prefill_head_dim( + 256, min_query_len=16, min_kv_len=8192, kv_tile=1024, supports_array_mask=True + ) + try: + profile = self._profile() + dense_small_kv = self._indexer_bytes(2048, 4096) + ( + 24 * 2048 * 4096 * 4 + 24 * 2048 * 256 * 4 + ) + # kv below the route floor -> dense. + assert ( + profile.estimate_prefill_transient_bytes(2048, 4096) + == dense_small_kv + ) + # query below the route floor -> dense. + dense_short_q = self._indexer_bytes(8, 160_000) + ( + 24 * 8 * 160_000 * 4 + 24 * 8 * 256 * 4 + ) + assert ( + profile.estimate_prefill_transient_bytes(8, 160_000) + == dense_short_q + ) + finally: + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + + def test_crossed_registrations_never_invent_coverage(self): + """Two routes whose individual (query, kv) thresholds are not jointly + met must not produce a bounded price (mirror of the generic + estimator's threshold-independence regression).""" + import omlx.memory_monitor as memory_monitor + + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + memory_monitor.register_tiled_prefill_head_dim( + 256, min_query_len=16, min_kv_len=8192, kv_tile=1024, supports_array_mask=True + ) + memory_monitor.register_tiled_prefill_head_dim( + 256, min_query_len=64, min_kv_len=2048, kv_tile=512, supports_array_mask=True + ) + try: + profile = self._profile() + # q=16 / kv=2048 meets one threshold from each route but no + # complete route. + dense = self._indexer_bytes(16, 2048) + ( + 24 * 16 * 2048 * 4 + 24 * 16 * 256 * 4 + ) + assert profile.estimate_prefill_transient_bytes(16, 2048) == dense + # The widest tile among matching routes binds for full matches. + bounded = self._indexer_bytes(64, 8192) + ( + 24 * 64 * 256 * 4 + 24 * 64 * 1024 * 4 + ) + assert profile.estimate_prefill_transient_bytes(64, 8192) == bounded + finally: + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + + def test_gathered_core_below_route_floor_stays_dense(self): + """The route covers the dense core's actual K width. A gathered QSA + core attending ~indexer_budget tokens is below the 8192 route floor + and must not borrow a bounded price registered for the dense path.""" + import omlx.memory_monitor as memory_monitor + + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + memory_monitor.register_tiled_prefill_head_dim( + 256, min_query_len=16, min_kv_len=8192, kv_tile=1024, supports_array_mask=True + ) + try: + profile = self._profile() + query_tokens, kv_len = 2048, 160_000 + core_kv = min(kv_len, 2048 + 4 - 1) + dense = self._indexer_bytes(query_tokens, kv_len) + ( + 24 * query_tokens * core_kv * 4 + 24 * query_tokens * 256 * 4 + ) + assert ( + profile.estimate_prefill_transient_bytes( + query_tokens, kv_len, gathered_core=True + ) + == dense + ) + finally: + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + + def test_bounded_price_reaches_monitor_via_chunk_transient(self): + import omlx.memory_monitor as memory_monitor + + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + memory_monitor.register_tiled_prefill_head_dim( + 256, min_query_len=16, min_kv_len=8192, kv_tile=1024, supports_array_mask=True + ) + try: + profile = self._profile() + monitor = self._monitor(profile) + direct = profile.estimate_prefill_transient_bytes(2048, 160_000) + routed = monitor.estimate_chunk_transient_bytes( + 2048, 160_000, gathered_core=False + ) + assert routed == direct + finally: + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + + class TestAnePrefillTransientReserve: def test_ane_prefill_transient_is_added_to_the_peak(self): # issue #2841: the ANE I/O surfaces are dirtied by the first long diff --git a/tests/test_prefill_oom_graceful.py b/tests/test_prefill_oom_graceful.py index e12539b295..5e893120e0 100644 --- a/tests/test_prefill_oom_graceful.py +++ b/tests/test_prefill_oom_graceful.py @@ -505,6 +505,62 @@ def test_predicted_transient_zero_without_signals(): assert ns._predicted_chunk_transient(4, 1000) == 0.0 +def test_bounded_qwen4_route_drops_unfused_dense_history(): + """A route flip to bounded array-mask SDPA must retire unfused samples.""" + from omlx import memory_monitor + from omlx.memory_monitor import make_prefill_memory_profile + + config = SimpleNamespace( + model_type="qwen4_exp", + num_hidden_layers=48, + num_attention_heads=24, + num_key_value_heads=2, + head_dim=256, + indexer_n_heads=4, + indexer_head_dim=128, + indexer_budget=2048, + indexer_compress_ratio=4, + full_attention_interval=4, + layer_types=None, + ) + profile = make_prefill_memory_profile(config, compute_dtype_size=2) + monitor = MemoryMonitor(max_kv_cache_memory=_GB, eviction_enabled=False) + monitor.set_model_info( + num_layers=48, + num_kv_heads=2, + head_dim=256, + dtype_size=2, + num_attention_heads=24, + prefill_memory_profile=profile, + ) + routes = memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.get(256) + memory_monitor.register_tiled_prefill_head_dim( + 256, + min_query_len=16, + min_kv_len=8192, + kv_tile=1024, + supports_array_mask=True, + ) + try: + tracker = PrefillTransientTracker() + tracker.update(2048, int(25.4 * 1024**2 * 2048)) + ns = _throttle_ctx( + current=0, hard=240 * _GB, samples_bpt=None, monitor=monitor + ) + ns._prefill_transient_tracker = tracker + Scheduler._sdpa256_bounded_route_changed(ns, False) + Scheduler._sdpa256_bounded_route_changed(ns, True) + + predicted = ns._predicted_chunk_transient(2048, 174_000) + stale = 25.4 * 1024**2 * 2048 * Scheduler._PREFILL_TRANSIENT_SAFETY + assert predicted < stale / 8 + finally: + if routes is None: + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + else: + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS[256] = routes + + def test_predicted_transient_drops_dense_ewma_when_qsa_static_is_cheaper(): """A leftover dense last_delta must not refuse gathered QSA static.""" from omlx.memory_monitor import make_prefill_memory_profile @@ -554,11 +610,16 @@ def test_predicted_transient_drops_dense_ewma_when_qsa_static_is_cheaper(): 4096, 233_472, gathered_core=True ) assert next_predicted == pytest.approx(predicted, rel=1e-6) - # Without gathered pricing, that same leftover gulp must still bind. + # Without gathered pricing, the larger of that gulp and dense fp32 static + # pricing must bind. dense_predicted = ns._predicted_chunk_transient( 4096, 233_472, gathered_core=False ) - assert dense_predicted == pytest.approx(dense_poison, rel=1e-3) + dense_static = ( + monitor.estimate_chunk_transient_bytes(4096, 233_472 + 4096) + + monitor.estimate_prompt_kv_bytes(4096) + ) * Scheduler._PREFILL_TRANSIENT_SAFETY + assert dense_predicted == pytest.approx(max(dense_poison, dense_static), rel=1e-3) def test_predicted_transient_keeps_gathered_spike_from_this_request(): diff --git a/tests/test_qwen4_qsa_prefill_memory.py b/tests/test_qwen4_qsa_prefill_memory.py index 1846b64640..bd6ca16adc 100644 --- a/tests/test_qwen4_qsa_prefill_memory.py +++ b/tests/test_qwen4_qsa_prefill_memory.py @@ -1,5 +1,7 @@ """Regression smoke tests for Qwen4 QSA long-prefill memory routing.""" +import importlib +import sys from types import SimpleNamespace import mlx.core as mx @@ -113,3 +115,130 @@ def fake_quantized(self, *args, **kwargs): assert result.shape == queries.shape assert calls == ["quantized"] + + +def test_qwen4_mask_dense_seam_reaches_array_tiled_sdpa256(monkeypatch): + """Production seam: on the official mask_dense path the QSA indexer + builds an explicit array mask; with the sdpa256 patch installed that mask + must reach _array_tiled_sdpa256 (bounded) and never the native fused call + whose array-mask support could silently unfuse into the O(L^2) fp32 + score matrix. Uses a real Qwen4ExpAttention at production head_dim=256 + with gathered attention disabled by non-broadcast MRoPE positions.""" + from omlx import memory_monitor + from omlx.patches import mlx_vlm_qwen4_exp_compat as compat + from omlx.patches import sdpa256_attention as sdpa256 + + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp import TextConfig + from mlx_vlm.models.qwen4_exp.language import QSAKVCache, Qwen4ExpAttention + + cfg = TextConfig( + model_type="qwen4_exp_text", + hidden_size=512, + num_hidden_layers=1, + num_attention_heads=8, + linear_num_value_heads=4, + linear_num_key_heads=2, + linear_key_head_dim=8, + linear_value_head_dim=8, + linear_conv_kernel_dim=3, + num_experts=4, + num_experts_per_tok=2, + shared_expert_intermediate_size=16, + moe_intermediate_size=16, + rms_norm_eps=1e-6, + vocab_size=64, + num_key_value_heads=2, + max_position_embeddings=4096, + hc_count=2, + hc_lowrank=8, + head_dim=256, + layer_types=["full_attention"], + ple_layer_ids=[], + ple_embed_dim=32, + ple_conv_kernel_size=3, + ngram_size=3, + heads_per_ngram=2, + ngram_vocab_size_base=17, + make_ngram_vocab_size_divisible_by=4, + split_ngram_parts=4, + indexer_n_heads=2, + indexer_kv_heads=1, + indexer_head_dim=128, + indexer_budget=16, + indexer_compress_ratio=4, + eos_token_id=1, + rope_parameters={ + "rope_type": "default", + "mrope_section": [2, 1, 1], + "rope_theta": 10_000, + "partial_rotary_factor": 1.0, + }, + ) + attn = Qwen4ExpAttention(cfg) + mx.eval(attn.parameters()) + + # Keep the gathered fast path off so the official mask_dense path runs: + # 3-D MRoPE positions with differing planes fail the gathered text + # eligibility on both this branch (broadcast check) and upstream main + # (2-D-only predicate), unlike the env knob which only exists here. + prefill_len = 64 # > indexer_budget(16): the sparse mask engages + position_ids = mx.stack( + [ + mx.arange(prefill_len, dtype=mx.int32) * (1 + plane) + for plane in range(3) + ] + ).reshape(3, 1, prefill_len) + + # Fresh sdpa256 install with test-sized KV floor. + importlib.import_module("mlx_lm.models.base") + importlib.import_module("mlx_vlm.models.base") + sdpa_snap = { + mod: mod.scaled_dot_product_attention + for name, mod in tuple(sys.modules.items()) + if mod is not None + and name.startswith(("mlx_lm.models.", "mlx_vlm.models.")) + and hasattr(mod, "scaled_dot_product_attention") + } + min_kv_len_snap = sdpa256._SDPA256_MIN_KV_LEN + routes_snap = memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.get(256) + monkeypatch.setattr(sdpa256, "_PATCHED", False, raising=False) + monkeypatch.setattr(sdpa256, "_HEADROOM_PROVIDER", None, raising=False) + monkeypatch.setattr(sdpa256, "_FORCE_TILED", None, raising=False) + assert sdpa256.apply_sdpa256_attention_patch(min_kv_len=32) is True + + calls = [] + + def tiled(queries, keys, values, scale, mask, sinks=None): + calls.append(mask) + return mx.zeros(queries.shape, queries.dtype) + + def boom(*args, **kwargs): + raise AssertionError( + "native fused SDPA must not see the Qwen4 explicit array mask" + ) + + monkeypatch.setattr(sdpa256, "_array_tiled_sdpa256", tiled) + monkeypatch.setattr(sdpa256.mx.fast, "scaled_dot_product_attention", boom) + + try: + mx.random.seed(7) + x = mx.random.normal((1, prefill_len, 512)) + cache = QSAKVCache() + out = attn(x, mask="causal", cache=cache, position_ids=position_ids) + mx.eval(out) + + assert out.shape == (1, prefill_len, 512) + assert len(calls) == 1 + mask = calls[0] + assert isinstance(mask, mx.array) + assert 1 <= mask.ndim <= 4 + finally: + for mod, fn in sdpa_snap.items(): + mod.scaled_dot_product_attention = fn + sdpa256._SDPA256_MIN_KV_LEN = min_kv_len_snap + if routes_snap is None: + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + else: + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS[256] = routes_snap + monkeypatch.setattr(sdpa256, "_PATCHED", False, raising=False) diff --git a/tests/test_sdpa256_attention.py b/tests/test_sdpa256_attention.py index 3fb34e823b..ff6d10e2fe 100644 --- a/tests/test_sdpa256_attention.py +++ b/tests/test_sdpa256_attention.py @@ -109,7 +109,10 @@ def fake_sdpa(q, k, v, **kwargs): @pytest.mark.parametrize("case", ["boolean", "additive", "sinks"]) def test_bounded_path_preserves_array_masks_and_sinks(case): - """Exercise the real MLX 0.32.2 fused call on Metal when available.""" + """Array masks route to the bounded portable path on Metal too (native + fused array-mask support is unproven and may silently unfuse); causal/ + no-mask cases exercise the real MLX 0.32.2 fused call when available. + All cases stay numerically pinned against the reference SDPA.""" from omlx.patches.sdpa256_attention import _flash_sdpa256 q, k, v = _qkv(16, 32, n_q=4, n_kv=2) @@ -131,6 +134,72 @@ def test_bounded_path_preserves_array_masks_and_sinks(case): assert _max_abs(out, ref) < 2e-2 +@pytest.mark.parametrize("mask_kind", ["boolean", "additive"]) +def test_metal_array_masks_never_reach_native_fused(mask_kind, monkeypatch): + """On Metal, an explicit array mask must go straight to the bounded + array-tiled kernel — never to mx.fast.scaled_dot_product_attention with + force_fused=True, whose array-mask handling could silently unfuse into + the O(L^2) fp32 score matrix this patch exists to bound.""" + from omlx.patches import sdpa256_attention as sdpa256 + + calls = [] + + def boom(*args, **kwargs): + raise AssertionError("native fused SDPA must not see an array mask") + + def tiled(q, k, v, scale, mask, sinks=None): + calls.append((mask, sinks)) + return q + + monkeypatch.setattr(sdpa256.mx.metal, "is_available", lambda: True) + monkeypatch.setattr( + sdpa256.mx.fast, "scaled_dot_product_attention", boom + ) + monkeypatch.setattr(sdpa256, "_array_tiled_sdpa256", tiled) + + q, k, v = _qkv(16, 32, n_q=4, n_kv=2) + if mask_kind == "boolean": + mask = mx.arange(32)[None, None, None, :] >= 8 + else: + allowed = mx.arange(32)[None, None, None, :] >= 8 + mask = mx.where(allowed, 0.0, -1e4).astype(mx.float16) + sinks = mx.array([-0.5, 0.0, 0.5, 1.0], dtype=mx.float16) + + out = sdpa256._flash_sdpa256(q, k, v, SCALE_256, mask, sinks) + assert out is q + # Mask and sinks forwarded unchanged to the bounded kernel. + assert len(calls) == 1 + assert calls[0][0] is mask + assert calls[0][1] is sinks + + +@pytest.mark.parametrize("mask", ["causal", None], ids=["causal", "none"]) +def test_metal_causal_and_none_keep_native_fused(mask, monkeypatch): + """The router dtype fix must not push the proven causal/no-mask paths off + the native fused kernel.""" + from omlx.patches import sdpa256_attention as sdpa256 + + calls = [] + + def fake_sdpa(q, k, v, **kwargs): + calls.append(kwargs) + return q + + def tiled(*args, **kwargs): + raise AssertionError("causal/no-mask native shape must stay fused") + + monkeypatch.setattr(sdpa256.mx.metal, "is_available", lambda: True) + monkeypatch.setattr(sdpa256.mx.fast, "scaled_dot_product_attention", fake_sdpa) + monkeypatch.setattr(sdpa256, "_array_tiled_sdpa256", tiled) + + q, k, v = _qkv(16, 32, n_q=4, n_kv=2) + out = sdpa256._flash_sdpa256(q, k, v, SCALE_256, mask) + assert out is q + assert calls == [ + {"scale": SCALE_256, "mask": mask, "sinks": None, "force_fused": True} + ] + + @pytest.mark.parametrize("mask_kind", ["boolean", "additive"]) def test_portable_array_mask_matches_reference(mask_kind, monkeypatch): """CUDA's bounded fallback must preserve both MLX array-mask forms.""" @@ -361,10 +430,14 @@ class _HeadroomOwner: def __init__(self, value): self.value = value + self.route_changes = [] def headroom(self): return self.value + def _sdpa256_bounded_route_changed(self, active): + self.route_changes.append(active) + @pytest.fixture def _sdpa256_provider_reset(monkeypatch): @@ -379,15 +452,20 @@ def _sdpa256_provider_reset(monkeypatch): def test_route_prefers_stock_when_unfused_fits(_sdpa256_provider_reset): sdpa256 = _sdpa256_provider_reset - from omlx.memory_monitor import estimate_unfused_sdpa_call_bytes + from omlx.memory_monitor import ( + SDPA256_UNFUSED_SCORE_DTYPE_SIZE, + estimate_unfused_sdpa_call_bytes, + ) q, k, _ = _qkv(2048, 16384) owner = _HeadroomOwner(1 << 40) # ~1 TB headroom: unfused clearly fits sdpa256.set_unfused_headroom_provider(owner.headroom) assert sdpa256._should_route(q, k, None, "causal", None) is False - # Exactly at the estimated transient the unfused path still fits... - need = estimate_unfused_sdpa_call_bytes(24, 2048, 16384, 256, q.dtype.size) + # Exactly at the fp32-priced transient the unfused path still fits... + need = estimate_unfused_sdpa_call_bytes( + 24, 2048, 16384, 256, SDPA256_UNFUSED_SCORE_DTYPE_SIZE + ) owner.value = need assert sdpa256._should_route(q, k, None, "causal", None) is False # ...one byte short -> forced fused. @@ -397,6 +475,40 @@ def test_route_prefers_stock_when_unfused_fits(_sdpa256_provider_reset): # Negative headroom = no active ceiling -> memory-safe default. owner.value = -1 assert sdpa256._should_route(q, k, None, "causal", None) is True + assert owner.route_changes == [False, False, True, True] + + +def test_route_prices_bf16_fallback_at_fp32(_sdpa256_provider_reset): + """The unfused fallback materializes fp32 scores even for bf16 queries; + pricing at the query dtype (2B) admitted the O(L^2) matrix when only the + bf16-sized transient fit and produced the ~33GiB VLM prefill spike.""" + sdpa256 = _sdpa256_provider_reset + from omlx.memory_monitor import ( + SDPA256_UNFUSED_SCORE_DTYPE_SIZE, + estimate_unfused_sdpa_call_bytes, + ) + + q, k, _ = _qkv(2048, 16384, dtype=mx.bfloat16) + assert q.dtype.size == 2 # the wrongly-cheap price + assert SDPA256_UNFUSED_SCORE_DTYPE_SIZE == 4 # the real materialization + + bf16_price = estimate_unfused_sdpa_call_bytes( + 24, 2048, 16384, 256, q.dtype.size + ) + fp32_price = estimate_unfused_sdpa_call_bytes( + 24, 2048, 16384, 256, SDPA256_UNFUSED_SCORE_DTYPE_SIZE + ) + assert fp32_price > bf16_price + + # Headroom fits the bf16-sized matrix but not the real fp32 one -> the + # router must force the bounded path. + owner = _HeadroomOwner(int((bf16_price + fp32_price) / 2)) + sdpa256.set_unfused_headroom_provider(owner.headroom) + assert sdpa256._should_route(q, k, None, "causal", None) is True + + # Full fp32 headroom restores the faster stock path. + owner.value = fp32_price + assert sdpa256._should_route(q, k, None, "causal", None) is False def test_route_defaults_to_tiled_when_provider_owner_dies(_sdpa256_provider_reset): @@ -463,7 +575,9 @@ def test_force_off_does_not_publish_a_bounded_memory_route(monkeypatch): monkeypatch.setattr(sdpa256, "_FORCE_TILED", None) assert sdpa256._register_bounded_route(8192) is True try: - assert 256 in mm._SDPA_TILED_PREFILL_HEAD_DIMS + routes = mm._SDPA_TILED_PREFILL_HEAD_DIMS[256] + assert len(routes) == 1 + assert routes[0].supports_array_mask is True finally: mm._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) From df5c6e3ec90bf5557540c7aa0e4fc8f0fba4bd0c Mon Sep 17 00:00:00 2001 From: Matthijs van den Bos Date: Sat, 5 Sep 2026 20:37:25 +0200 Subject: [PATCH 079/132] fix(qwen4_exp): safely re-expand prefill chunks --- omlx/prefill_transient_tracker.py | 84 +++++++++ omlx/scheduler.py | 131 +++++++++++++- tests/test_prefill_oom_graceful.py | 231 ++++++++++++++++++++---- tests/test_prefill_transient_tracker.py | 97 ++++++++++ 4 files changed, 503 insertions(+), 40 deletions(-) diff --git a/omlx/prefill_transient_tracker.py b/omlx/prefill_transient_tracker.py index 5b08aab8fc..d897dd43ff 100644 --- a/omlx/prefill_transient_tracker.py +++ b/omlx/prefill_transient_tracker.py @@ -25,6 +25,12 @@ class _TransientHistory: last_delta_bytes: int = 0 last_n_tokens: int = 0 observed_max_bytes: int = 0 + flat_overhead_bytes: int = 0 + reclaim_debt_bytes: int = 0 + stable_streak: int = 0 + stable_chunk_size: int = 0 + expansion_limit: int = 0 + request_id: str = "" class PrefillTransientTracker: @@ -54,6 +60,9 @@ class PrefillTransientTracker: # above the largest observed legitimate fluctuation and below the # observed outlier. _EWMA_OUTLIER_RATIO = 8.0 + _FLAT_OVERHEAD_NOISE_BYTES = 64 * 1024**2 + _FLAT_OVERHEAD_STABLE_CHUNKS = 5 + _PREFILL_CHUNK_TIERS = (32, 64, 128, 256, 512, 1024, 2048) def __init__(self, model_id: str = "") -> None: self._model_id = model_id @@ -164,6 +173,81 @@ def update( history.last_delta_bytes = transient_bytes history.last_n_tokens = n_tokens + def observe_flat_overhead( + self, + n_tokens: int, + delta_bytes: int, + *, + static_bytes: int, + request_id: str, + gathered_core: bool = False, + representative: bool = True, + ) -> None: + """Track Qwen4 process-footprint noise as flat, never per-token work.""" + if n_tokens <= 0: + return + history = self._history(gathered_core) + if history.request_id != request_id: + history.request_id = request_id + history.stable_streak = 0 + history.stable_chunk_size = 0 + history.expansion_limit = 0 + + noise = max(self._FLAT_OVERHEAD_NOISE_BYTES, max(0, static_bytes) // 10) + if delta_bytes < -noise: + history.stable_streak = 0 + history.stable_chunk_size = 0 + history.reclaim_debt_bytes += -delta_bytes + return + + # A positive delta first repays a preceding pool release. Only net-new + # growth beyond both that repayment and the static profile is overhead. + reallocated = min(history.reclaim_debt_bytes, max(0, delta_bytes)) + history.reclaim_debt_bytes -= reallocated + residual = delta_bytes - reallocated - max(0, static_bytes) + if residual <= noise: + if not representative: + return + if history.stable_chunk_size == n_tokens: + history.stable_streak += 1 + else: + history.stable_chunk_size = n_tokens + history.stable_streak = 1 + if history.stable_streak == self._FLAT_OVERHEAD_STABLE_CHUNKS: + history.flat_overhead_bytes //= 2 + history.expansion_limit = next( + (tier for tier in self._PREFILL_CHUNK_TIERS if tier > n_tokens), + self._PREFILL_CHUNK_TIERS[-1], + ) + return + + history.stable_streak = 0 + history.stable_chunk_size = 0 + if not representative: + return + history.flat_overhead_bytes = max(history.flat_overhead_bytes, residual) + history.samples += 1 + history.last_delta_bytes = delta_bytes + history.last_n_tokens = n_tokens + + def flat_overhead_bytes_for(self, gathered_core: bool) -> int: + return self._history(gathered_core).flat_overhead_bytes + + def reclaim_debt_bytes_for(self, gathered_core: bool) -> int: + return self._history(gathered_core).reclaim_debt_bytes + + def flat_overhead_charge_for(self, gathered_core: bool) -> int: + history = self._history(gathered_core) + return max(history.flat_overhead_bytes, history.reclaim_debt_bytes) + + def expansion_limit_for( + self, gathered_core: bool, *, request_id: str = "" + ) -> int: + history = self._history(gathered_core) + if request_id and history.request_id != request_id: + return 0 + return history.expansion_limit + def predict( self, n_tokens: int, diff --git a/omlx/scheduler.py b/omlx/scheduler.py index c7f5a711d6..01cf8f6367 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -3940,7 +3940,20 @@ def _predicted_chunk_transient( static += self.memory_monitor.estimate_prompt_kv_bytes(n_tokens) static_per_token = float(static) / n_tokens per_token = static_per_token + qwen4_flat_overhead = bool( + MemoryMonitor is not None + and isinstance(self.memory_monitor, MemoryMonitor) + and self.memory_monitor.is_qwen4_gathered_prefill_profile() + ) if tracker is not None: + if qwen4_flat_overhead: + # Qwen4's profile (#3461) owns every token-scaled term. Raw + # process-footprint growth is pool noise/fixed allocation and + # must not be divided by one chunk then scaled to another. + return ( + static_per_token * n_tokens * self._PREFILL_TRANSIENT_SAFETY + + tracker.flat_overhead_charge_for(gathered_core) + ) # Dense SDPA and gathered QSA have different cost curves. The # tracker keeps their measured histories separate, so switching # paths cannot reintroduce a stale dense charge after the first @@ -4252,11 +4265,26 @@ def _guard_prefill_chunk( ) # The floor fits — pick the largest chunk that still fits under the cap. - per_token = self._predicted_chunk_transient( - n_tokens, kv_len, gathered_core=gathered_core - ) / n_tokens - safe_n = int((cap - current) / per_token) if per_token > 0 else n_tokens - n_fit = max(min_chunk, min(n_tokens, safe_n)) + qwen4_flat_overhead = bool( + MemoryMonitor is not None + and isinstance(self.memory_monitor, MemoryMonitor) + and self.memory_monitor.is_qwen4_gathered_prefill_profile() + ) + if qwen4_flat_overhead: + n_fit = Scheduler._largest_fitting_prefill_chunk( + self, + n_tokens, + min_chunk, + cap - current, + kv_len, + gathered_core=gathered_core, + ) + else: + per_token = self._predicted_chunk_transient( + n_tokens, kv_len, gathered_core=gathered_core + ) / n_tokens + safe_n = int((cap - current) / per_token) if per_token > 0 else n_tokens + n_fit = max(min_chunk, min(n_tokens, safe_n)) # Same quantization as the adaptive throttle: an off-grid size here # would reintroduce the near-miss buffers _snap_chunk_size exists to # avoid. @@ -4275,6 +4303,31 @@ def _guard_prefill_chunk( ) return n_fit + def _largest_fitting_prefill_chunk( + self, + requested: int, + min_chunk: int, + headroom: float, + kv_len: int, + *, + gathered_core: bool, + ) -> int: + """Binary-search Qwen4's nonlinear static-plus-flat prediction.""" + low, high = 1, max(1, requested // min_chunk) + best = min_chunk + while low <= high: + units = (low + high) // 2 + candidate = min(requested, units * min_chunk) + predicted = self._predicted_chunk_transient( + candidate, kv_len, gathered_core=gathered_core + ) + if predicted <= headroom: + best = candidate + low = units + 1 + else: + high = units - 1 + return best + def _snap_chunk_size(self, n: int, requested: int) -> int: """Quantize a throttled chunk to a multiple of the min-chunk floor. @@ -4361,6 +4414,18 @@ def _adaptive_chunk_size( current = self._current_usage_bytes() min_chunk = max(1, self._prefill_min_chunk_tokens) + monitor = self.memory_monitor + qwen4_flat_overhead = bool( + MemoryMonitor is not None + and isinstance(monitor, MemoryMonitor) + and monitor.is_qwen4_gathered_prefill_profile() + ) + if qwen4_flat_overhead: + expansion_limit = self._prefill_transient_tracker.expansion_limit_for( + gathered_core, request_id=request_id + ) + if expansion_limit > 0: + requested = min(requested, max(min_chunk, expansion_limit)) # Conservative per-token peak growth (measured-last / EWMA / static, × # safety) — see _predicted_chunk_transient. Anchored on the most recent @@ -4418,7 +4483,17 @@ def _adaptive_chunk_size( # cleanly instead of crawling at floor-size chunks. return requested headroom = max(target - current, 0) - n_fit = int(headroom / per_token) + if qwen4_flat_overhead: + n_fit = Scheduler._largest_fitting_prefill_chunk( + self, + requested, + min_chunk, + headroom, + kv_len, + gathered_core=gathered_core, + ) + else: + n_fit = int(headroom / per_token) n = max(min_chunk, min(requested, n_fit)) @@ -4771,6 +4846,50 @@ def _record_chunk_transient( charge. """ delta = post_bytes - pre_bytes + monitor = getattr(self, "memory_monitor", None) + if ( + MemoryMonitor is not None + and isinstance(monitor, MemoryMonitor) + and monitor.is_qwen4_gathered_prefill_profile() + ): + min_chunk = max(1, self._prefill_min_chunk_tokens) + representative = n_tokens >= min_chunk and not ( + getattr(self, "_prefill_speed_priority", False) + and requested_step is not None + and n_tokens < requested_step + ) + static = monitor.estimate_chunk_transient_bytes( + n_tokens, + kv_len + n_tokens, + gathered_core=gathered_core, + ) + monitor.estimate_prompt_kv_bytes(n_tokens) + self._prefill_transient_tracker.observe_flat_overhead( + n_tokens, + delta, + static_bytes=static, + request_id=request_id, + gathered_core=gathered_core, + representative=representative, + ) + logger.debug( + "[throttle:%s] qwen4-flat rid=%s n=%d kv_len=%d " + "delta=%.2fMB static=%.2fMB overhead=%.2fMB debt=%.2fMB", + loop_label, + request_id, + n_tokens, + kv_len, + delta / 1024**2, + static / 1024**2, + self._prefill_transient_tracker.flat_overhead_bytes_for( + gathered_core + ) + / 1024**2, + self._prefill_transient_tracker.reclaim_debt_bytes_for( + gathered_core + ) + / 1024**2, + ) + return # The reclaim ledger sees every measurement, including samples the # EWMA gates below skip: a release on a sub-floor tail must still be # priced, and any positive growth confirms the pool reallocation and diff --git a/tests/test_prefill_oom_graceful.py b/tests/test_prefill_oom_graceful.py index 5e893120e0..c1cc01f781 100644 --- a/tests/test_prefill_oom_graceful.py +++ b/tests/test_prefill_oom_graceful.py @@ -24,6 +24,7 @@ from omlx.memory_monitor import ( _SDPA_FALLBACK_SCORE_DTYPE_SIZE, MemoryMonitor, + make_prefill_memory_profile, ) from omlx.prefill_transient_tracker import PrefillTransientTracker from omlx.scheduler import Scheduler, _PrefillEvictionNeeded, _PrefillState @@ -48,6 +49,34 @@ def _monitor(head_dim): return m +def _qwen4_monitor(): + config = SimpleNamespace( + model_type="qwen4_exp", + num_hidden_layers=48, + num_attention_heads=24, + num_key_value_heads=2, + head_dim=256, + indexer_n_heads=4, + indexer_head_dim=128, + indexer_budget=2048, + indexer_compress_ratio=4, + full_attention_interval=4, + layer_types=None, + ) + monitor = MemoryMonitor(max_kv_cache_memory=_GB, eviction_enabled=False) + monitor.set_model_info( + num_layers=48, + num_kv_heads=2, + head_dim=256, + dtype_size=2, + num_attention_heads=24, + prefill_memory_profile=make_prefill_memory_profile( + config, compute_dtype_size=2 + ), + ) + return monitor + + def test_chunk_transient_unsupported_vector_head_dim_scales_with_kv_len(): """head_dim=192 is unsupported by vector/full MLX SDPA and falls back.""" m = _monitor(head_dim=192) @@ -152,13 +181,18 @@ def _reclaim(): return ns -def _call(ns, requested, kv_len=0): +def _call(ns, requested, kv_len=0, *, gathered_core=False): with ( patch.object(sched_mod.mx, "get_active_memory", return_value=0), patch.object(sched_mod, "get_phys_footprint", return_value=ns._fake_current), ): return Scheduler._adaptive_chunk_size( - ns, requested, request_id="r", loop_label="test", kv_len=kv_len + ns, + requested, + request_id="r", + loop_label="test", + kv_len=kv_len, + gathered_core=gathered_core, ) @@ -198,13 +232,18 @@ def test_adaptive_throttle_requests_eviction_before_shrinking(): assert result < 2048 -def _guard_call(ns, n, kv_len=0): +def _guard_call(ns, n, kv_len=0, *, gathered_core=False): with ( patch.object(sched_mod.mx, "get_active_memory", return_value=0), patch.object(sched_mod, "get_phys_footprint", return_value=ns._fake_current), ): return Scheduler._guard_prefill_chunk( - ns, n, kv_len=kv_len, progress=0, loop_label="test" + ns, + n, + kv_len=kv_len, + progress=0, + loop_label="test", + gathered_core=gathered_core, ) @@ -622,42 +661,166 @@ def test_predicted_transient_drops_dense_ewma_when_qsa_static_is_cheaper(): assert dense_predicted == pytest.approx(max(dense_poison, dense_static), rel=1e-3) -def test_predicted_transient_keeps_gathered_spike_from_this_request(): - """A gathered chunk's own measured spike must still bind the next chunk.""" - from omlx.memory_monitor import make_prefill_memory_profile +def test_qwen4_measured_excess_is_flat_not_scaled_to_the_next_chunk(): + monitor = _qwen4_monitor() + tracker = PrefillTransientTracker() + measured_tokens = 1600 + kv_len = 188_416 + measured_static = monitor.estimate_chunk_transient_bytes( + measured_tokens, kv_len + measured_tokens, gathered_core=True + ) + monitor.estimate_prompt_kv_bytes(measured_tokens) + tracker.observe_flat_overhead( + measured_tokens, + 20 * _GB, + static_bytes=measured_static, + request_id="r", + gathered_core=True, + ) + ns = _throttle_ctx(current=0, hard=240 * _GB, monitor=monitor) + ns._prefill_transient_tracker = tracker - config = SimpleNamespace( - model_type="qwen4_exp", - num_hidden_layers=48, - num_attention_heads=24, - num_key_value_heads=2, - head_dim=256, - indexer_n_heads=4, - indexer_head_dim=128, - indexer_budget=2048, - indexer_compress_ratio=4, - full_attention_interval=4, - layer_types=None, + candidate = 2048 + candidate_static = monitor.estimate_chunk_transient_bytes( + candidate, kv_len + candidate, gathered_core=True + ) + monitor.estimate_prompt_kv_bytes(candidate) + predicted = ns._predicted_chunk_transient( + candidate, kv_len, gathered_core=True ) - profile = make_prefill_memory_profile(config, compute_dtype_size=2) - monitor = MemoryMonitor(max_kv_cache_memory=_GB, eviction_enabled=False) - monitor.set_model_info( - num_layers=48, - num_kv_heads=2, - head_dim=256, - dtype_size=2, - num_attention_heads=24, - prefill_memory_profile=profile, + + assert predicted == pytest.approx( + candidate_static * Scheduler._PREFILL_TRANSIENT_SAFETY + + tracker.flat_overhead_charge_for(True) ) + assert predicted < 20 * _GB / measured_tokens * candidate + + +def test_non_qwen4_prediction_keeps_existing_measured_rate_behavior(): + monitor = _monitor(head_dim=192) tracker = PrefillTransientTracker() - tracker.update(4096, int(69.58 * _GB), gathered_core=True) - ns = _throttle_ctx(current=0, hard=240 * _GB, samples_bpt=None, monitor=monitor) + tracker.update(1600, 20 * _GB) + ns = _throttle_ctx(current=0, hard=240 * _GB, monitor=monitor) ns._prefill_transient_tracker = tracker - dense_poison = 69.58 * _GB * Scheduler._PREFILL_TRANSIENT_SAFETY - predicted = ns._predicted_chunk_transient( - 4096, 233_472, gathered_core=True + + predicted = ns._predicted_chunk_transient(2048, 188_416) + + assert predicted >= 20 * _GB / 1600 * 2048 + + +def test_qwen4_real_chunk_callsite_tracks_deltas_and_expands_one_tier(): + monitor = _qwen4_monitor() + ns = _throttle_ctx(current=0, hard=240 * _GB, monitor=monitor) + ns._record_chunk_transient = Scheduler._record_chunk_transient.__get__( + ns, Scheduler + ) + samples = [(100 * _GB, 110 * _GB), (110 * _GB, 109 * _GB)] + [ + (109 * _GB, 109 * _GB) + ] * 5 + for pre, post in samples: + ns._record_chunk_transient( + 512, + pre, + post, + request_id="r", + loop_label="test", + kv_len=180_000, + requested_step=2048, + gathered_core=True, + ) + + tracker = ns._prefill_transient_tracker + assert tracker.flat_overhead_bytes_for(True) > 0 + assert tracker.reclaim_debt_bytes_for(True) == _GB + assert tracker.expansion_limit_for(True, request_id="r") == 1024 + ns._fake_current = 0 + ns.requests = {} + ns.config = SimpleNamespace(model_name="qwen4") + ns._raise_prefill_eviction_if_available = ( + Scheduler._raise_prefill_eviction_if_available.__get__(ns, Scheduler) + ) + assert _call(ns, 2048, kv_len=180_000, gathered_core=True) == 1024 + + +@pytest.mark.parametrize( + ("trace", "expected_limit"), + [ + ( + [ + (160_000, 1024, 8 * _GB), + (166_000, 1024, 0), + (172_000, 1024, 32 * 1024**2), + (178_000, 1024, -32 * 1024**2), + (184_000, 1024, 0), + (190_000, 1024, 0), + ], + 2048, + ), + ( + [ + (350_000, 512, 4 * _GB), + (350_512, 512, 0), + (351_024, 512, 16 * 1024**2), + (351_536, 512, -16 * 1024**2), + (352_048, 512, 0), + (352_560, 512, 0), + ], + 1024, + ), + ], + ids=("160k-190k", "350k"), +) +def test_qwen4_long_context_plateau_replays(trace, expected_limit): + monitor = _qwen4_monitor() + ns = _throttle_ctx(current=0, hard=240 * _GB, monitor=monitor) + for kv_len, n_tokens, delta in trace: + Scheduler._record_chunk_transient( + ns, + n_tokens, + 100 * _GB, + 100 * _GB + delta, + request_id="r", + loop_label="replay", + kv_len=kv_len, + requested_step=2048, + gathered_core=True, + ) + + assert ns._prefill_transient_tracker.expansion_limit_for( + True, request_id="r" + ) == expected_limit + ns._fake_current = 0 + ns.requests = {} + ns.config = SimpleNamespace(model_name="qwen4") + ns._raise_prefill_eviction_if_available = ( + Scheduler._raise_prefill_eviction_if_available.__get__(ns, Scheduler) + ) + assert _call(ns, 2048, kv_len=trace[-1][0], gathered_core=True) == expected_limit + + +def test_qwen4_plateau_never_bypasses_abort_cap(): + monitor = _qwen4_monitor() + ns = _throttle_ctx(current=0, hard=5 * _GB, monitor=monitor, abort=5 * _GB) + ns._prefill_transient_tracker.observe_flat_overhead( + 512, + 6 * _GB, + static_bytes=100 * 1024**2, + request_id="r", + gathered_core=True, + ) + for _ in range(5): + ns._prefill_transient_tracker.observe_flat_overhead( + 512, + 0, + static_bytes=100 * 1024**2, + request_id="r", + gathered_core=True, + ) + ns._fake_current = 0 + + chosen = _guard_call(ns, 2048, kv_len=180_000, gathered_core=True) + predicted = ns._admission_transient_bound( + chosen, 180_000, gathered_core=True ) - assert predicted == pytest.approx(dense_poison, rel=1e-3) + assert predicted <= ns._prefill_abort_cap() def test_adaptive_throttle_charges_recently_reclaimed_footprint(): diff --git a/tests/test_prefill_transient_tracker.py b/tests/test_prefill_transient_tracker.py index 1b356b462a..73dac264df 100644 --- a/tests/test_prefill_transient_tracker.py +++ b/tests/test_prefill_transient_tracker.py @@ -226,3 +226,100 @@ def test_dense_floor_max_does_not_bind_gathered_admission(self): assert t.observed_max_bytes == 900 * 1024**2 assert t.observed_max_bytes_for(True) == 40 * 1024**2 + + +class TestFlatOverhead: + MB = 1024**2 + + def test_fixed_overhead_is_not_scaled_by_token_count(self): + t = PrefillTransientTracker("qwen4") + t.observe_flat_overhead( + 54, + 571 * self.MB, + static_bytes=self.MB, + request_id="r", + ) + assert t.flat_overhead_bytes_for(False) == 570 * self.MB + assert t.flat_overhead_charge_for(False) == 570 * self.MB + + def test_reclaim_debt_tracks_net_release(self): + t = PrefillTransientTracker("qwen4") + t.observe_flat_overhead( + 2048, -600 * self.MB, static_bytes=100 * self.MB, request_id="r" + ) + t.observe_flat_overhead( + 2048, -400 * self.MB, static_bytes=100 * self.MB, request_id="r" + ) + assert t.reclaim_debt_bytes_for(False) == 1000 * self.MB + t.observe_flat_overhead( + 2048, 250 * self.MB, static_bytes=100 * self.MB, request_id="r" + ) + assert t.reclaim_debt_bytes_for(False) == 750 * self.MB + + def test_reallocation_does_not_become_new_flat_overhead(self): + t = PrefillTransientTracker("qwen4") + t.observe_flat_overhead( + 2048, 4 * 1024 * self.MB, static_bytes=1024 * self.MB, request_id="r" + ) + t.observe_flat_overhead( + 2048, -16 * 1024 * self.MB, static_bytes=1024 * self.MB, request_id="r" + ) + t.observe_flat_overhead( + 2048, 17 * 1024 * self.MB, static_bytes=1024 * self.MB, request_id="r" + ) + assert t.flat_overhead_bytes_for(False) == 3 * 1024 * self.MB + assert t.reclaim_debt_bytes_for(False) == 0 + + def test_plateau_requires_static_covered_same_width_samples(self): + t = PrefillTransientTracker("qwen4") + static = 1024 * self.MB + t.observe_flat_overhead( + 512, 2 * 1024 * self.MB, static_bytes=static, request_id="r" + ) + for _ in range(4): + t.observe_flat_overhead( + 512, 500 * self.MB, static_bytes=static, request_id="r" + ) + assert t.expansion_limit_for(False) == 0 + t.observe_flat_overhead( + 512, 500 * self.MB, static_bytes=static, request_id="r" + ) + assert t.expansion_limit_for(False) == 1024 + + t.observe_flat_overhead( + 512, -2 * 1024 * self.MB, static_bytes=static, request_id="r" + ) + assert t.expansion_limit_for(False) == 1024 + assert t.reclaim_debt_bytes_for(False) == 2 * 1024 * self.MB + + def test_plateau_expands_to_the_next_fixed_tier(self): + t = PrefillTransientTracker("qwen4") + for _ in range(5): + t.observe_flat_overhead( + 96, 0, static_bytes=100 * self.MB, request_id="r" + ) + assert t.expansion_limit_for(False) == 128 + + def test_plateau_permission_does_not_cross_requests(self): + t = PrefillTransientTracker("qwen4") + for _ in range(5): + t.observe_flat_overhead( + 512, 0, static_bytes=100 * self.MB, request_id="r1" + ) + assert t.expansion_limit_for(False, request_id="r1") == 1024 + assert t.expansion_limit_for(False, request_id="r2") == 0 + t.observe_flat_overhead( + 512, 0, static_bytes=100 * self.MB, request_id="r2" + ) + assert t.expansion_limit_for(False, request_id="r2") == 0 + + def test_execution_regimes_are_independent(self): + t = PrefillTransientTracker("qwen4") + t.observe_flat_overhead( + 2048, + 500 * self.MB, + static_bytes=100 * self.MB, + request_id="r", + ) + assert t.flat_overhead_bytes_for(False) == 400 * self.MB + assert t.flat_overhead_bytes_for(True) == 0 From aa897e7469a7a9a5b88b378a62eaba7537f7e3d7 Mon Sep 17 00:00:00 2001 From: Matthijs van den Bos Date: Sun, 6 Sep 2026 00:08:18 +0200 Subject: [PATCH 080/132] fix(qwen4_exp): attribute prefill overhead to runtime route --- .../mlx_vlm/models/qwen4_exp/language.py | 3 ++ omlx/scheduler.py | 49 ++++++++++++++++++- tests/test_prefill_oom_graceful.py | 29 +++++++++++ 3 files changed, 79 insertions(+), 2 deletions(-) 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 ad752ba471..aa776a7c1a 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 @@ -1426,8 +1426,11 @@ def __call__( position_embeddings, target_verify, ): + cache._omlx_last_prefill_gathered = True return self._gathered_text_prefill(x, cache, position_ids) + if cache is not None and x.ndim == 3 and x.shape[1] > 1: + cache._omlx_last_prefill_gathered = False qsa_mask = self.indexer( x, cache, diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 01cf8f6367..3a7b462fc8 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -492,6 +492,7 @@ class _PrefillState: sampler: Any = None sm: Any = None per_row_lps: Any = None + qwen4_gathered_core: bool | None = None @dataclass @@ -3431,6 +3432,20 @@ def _qwen4_text_gathered_pricing(self, text_only: bool) -> bool: checker = getattr(monitor, "is_qwen4_gathered_prefill_profile", None) return callable(checker) and checker() is True + @staticmethod + def _qwen4_actual_gathered_pricing( + cache: list[Any], predicted: bool + ) -> bool: + """Return the QSA route that the just-finished chunk actually used.""" + routes = [ + route + for item in cache + if isinstance( + route := getattr(item, "_omlx_last_prefill_gathered", None), bool + ) + ] + return all(routes) if routes else predicted + def _do_external_prefill( self, request: "Request", @@ -3675,6 +3690,20 @@ def _do_external_prefill( extra_kwargs = _advance_vlm_extra(extra_kwargs, n_to_process) _trace_model_ms = (time.perf_counter() - _trace_model_start) * 1000.0 _throttle_post = get_phys_footprint() + actual_gathered_core = Scheduler._qwen4_actual_gathered_pricing( + prompt_cache, gathered_core + ) + if actual_gathered_core != gathered_core: + logger.info( + "Qwen4 prefill pricing route corrected after execution: " + "rid=%s predicted=%s actual=%s query=%d kv_len=%d", + request.request_id, + "gathered" if gathered_core else "mask_dense", + "gathered" if actual_gathered_core else "mask_dense", + n_to_process, + base_size + processed_tokens, + ) + gathered_core = actual_gathered_core self._record_chunk_transient( n_to_process, _throttle_pre, @@ -5366,7 +5395,9 @@ def _step_prefill_chunk(self, state: _PrefillState) -> bool: # 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). - gathered_core = self._qwen4_text_gathered_pricing(True) + if state.qwen4_gathered_core is None: + state.qwen4_gathered_core = self._qwen4_text_gathered_pricing(True) + gathered_core = state.qwen4_gathered_core n = self._adaptive_chunk_size( n, request_id=state.request.request_id, @@ -5415,6 +5446,20 @@ def _step_prefill_chunk(self, state: _PrefillState) -> bool: mx.eval([c.state for c in state.cache]) _trace_model_ms = (time.perf_counter() - _trace_model_start) * 1000.0 _throttle_post = get_phys_footprint() + actual_gathered_core = Scheduler._qwen4_actual_gathered_pricing( + state.cache, gathered_core + ) + if actual_gathered_core != gathered_core: + logger.info( + "Qwen4 prefill pricing route corrected after execution: " + "rid=%s predicted=%s actual=%s query=%d kv_len=%d", + state.request.request_id, + "gathered" if gathered_core else "mask_dense", + "gathered" if actual_gathered_core else "mask_dense", + n, + state.base_size + state.tokens_processed, + ) + state.qwen4_gathered_core = actual_gathered_core self._record_chunk_transient( n, _throttle_pre, @@ -5423,7 +5468,7 @@ def _step_prefill_chunk(self, state: _PrefillState) -> bool: loop_label="chunked_step", kv_len=state.base_size + state.tokens_processed, requested_step=prefill_step_size, - gathered_core=gathered_core, + gathered_core=actual_gathered_core, ) self._maybe_record_fixed_state_bytes(state.cache) state.tokens_processed += n diff --git a/tests/test_prefill_oom_graceful.py b/tests/test_prefill_oom_graceful.py index c1cc01f781..e706ad5c00 100644 --- a/tests/test_prefill_oom_graceful.py +++ b/tests/test_prefill_oom_graceful.py @@ -694,6 +694,35 @@ def test_qwen4_measured_excess_is_flat_not_scaled_to_the_next_chunk(): assert predicted < 20 * _GB / measured_tokens * candidate +def test_qwen4_mask_dense_chunk_does_not_poison_gathered_admission(): + """Replay the 143k false rejection from the live server log.""" + monitor = _qwen4_monitor() + ns = _throttle_ctx(current=84.27 * _GB, hard=121.6 * _GB, monitor=monitor) + actual = Scheduler._qwen4_actual_gathered_pricing( + [SimpleNamespace(_omlx_last_prefill_gathered=False)], True + ) + + Scheduler._record_chunk_transient( + ns, + 2048, + 0, + int(28_164.64 * 1024**2), + request_id="dense-prefix", + loop_label="incident-replay", + kv_len=126_976, + requested_step=2048, + gathered_core=actual, + ) + + tracker = ns._prefill_transient_tracker + assert tracker.flat_overhead_bytes_for(False) > 0 + assert tracker.flat_overhead_bytes_for(True) == 0 + gathered_floor = ns._predicted_chunk_transient( + 32, 142_784, gathered_core=True + ) + assert 84.27 * _GB + gathered_floor < 0.90 * 121.6 * _GB + + def test_non_qwen4_prediction_keeps_existing_measured_rate_behavior(): monitor = _monitor(head_dim=192) tracker = PrefillTransientTracker() From ce191fbcce1349139c37bb985e22b22d2b773126 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B0=A2=E6=B0=B8=E6=A2=81?= <21219102@qq.com> Date: Sun, 6 Sep 2026 11:02:22 +0800 Subject: [PATCH 081/132] fix(scheduler): a throttled prefill chunk must never grow past the tokens left MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The adaptive throttle and its min-chunk floor could return a chunk larger than the caller's requested size: max(min_chunk, min(requested, n_fit)) raises the result back to prefill_min_chunk_tokens whenever a prefill tail is shorter than the floor and memory pressure takes the shrink path. The external-prefill loop slices the token row and the VLM inputs_embeds with the same chunk size, but the embeds always span one row more (the final token is deferred to insert() for the first decode step) and MLX slices silently clamp at the array edge — so an oversized chunk desynchronizes the two, and Qwen4Exp's PLE dies with the off-by-one reshape reported in #3240: [reshape] Cannot reshape array of size 1556480 into shape (1,153,4,2560) _The floor is an admission bound, not a padding requirement. _adaptive_ chunk_size now honors its documented ">= 1, <= requested" contract, and both prefill loops clamp the chunk to the tokens actually left before slicing (which also keeps tokens_processed accurate in the text-chunked loop). Refs #3240 --- omlx/scheduler.py | 23 ++++++++++++++ tests/test_prefill_oom_graceful.py | 26 +++++++++++++++ tests/test_scheduler.py | 51 ++++++++++++++++++++++++++++++ 3 files changed, 100 insertions(+) diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 1bbb6faab5..7224ec8821 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -3623,6 +3623,12 @@ def _do_external_prefill( request_id=request.request_id, gathered_core=gathered_core, ) + # A chunk may never exceed the tokens actually left: the token + # row and the VLM inputs_embeds (one row wider — the +1 final + # token deferred to insert()) are sliced with the same size and + # MLX clamps silently, so an oversized chunk desynchronizes them + # and Qwen4Exp's PLE dies on an off-by-one reshape (#3240). + n_to_process = min(n_to_process, remaining) if getattr(request, "benchmark_trace", False): request.benchmark_prefill_chunks.append(int(n_to_process)) request.benchmark_requested_steps.append(int(prefill_step_size)) @@ -4432,6 +4438,18 @@ def _adaptive_chunk_size( bucket = self._PREFILL_STEP_TIERS[1] # 512 n = max(min_chunk, min(n, bucket)) + # The floor is an admission bound, not a padding requirement: when a + # prefill tail is shorter than min_chunk, both floor above must never + # grow the chunk past what the caller had to work with. Returning + # more than requested breaks the documented ">= 1, <= requested" + # contract, and the external-prefill loop slices the token row and + # the VLM inputs_embeds (which spans the +1 final token the token + # stream defers) with the same chunk size — MLX clamps silently, so + # an oversized chunk desynchronizes the two by exactly the rows left + # on each side and Qwen4Exp's PLE dies on an off-by-one reshape + # (#3240). + n = min(requested, n) + n = self._snap_chunk_size(n, requested) if n < requested and request_id not in self._throttle_notified_requests: @@ -5257,6 +5275,11 @@ def _step_prefill_chunk(self, state: _PrefillState) -> bool: request_id=state.request.request_id, gathered_core=gathered_core, ) + # Same invariant as the external loop (#3240): the throttle may + # shrink but never grow a chunk past the tokens actually left — + # otherwise tokens_processed drifts past the rows actually cached + # (skewed progress and boundary-snapshot totals). + n = min(n, remaining) if getattr(state.request, "benchmark_trace", False): state.request.benchmark_prefill_chunks.append(int(n)) state.request.benchmark_requested_steps.append(int(prefill_step_size)) diff --git a/tests/test_prefill_oom_graceful.py b/tests/test_prefill_oom_graceful.py index e12539b295..ee24dded7c 100644 --- a/tests/test_prefill_oom_graceful.py +++ b/tests/test_prefill_oom_graceful.py @@ -1273,3 +1273,29 @@ def test_speed_priority_guard_passes_full_chunk_that_fits(): ns._fake_current = 10 * _GB ns._prefill_speed_priority = True assert _guard_call(ns, 2048, kv_len=5000) == 2048 + + +def test_adaptive_throttle_tail_below_floor_never_grows_chunk(): + """Regression (#3240): the min-chunk floor must never INFLATE a chunk + beyond what the caller asked for. A prefill tail shorter than + prefill_min_chunk_tokens used to be raised back up to the floor + (max(min_chunk, min(requested, n_fit))), and the external-prefill loop + has no clamp after the throttle — so the chunk sized the token slice and + the VLM inputs_embeds slice differently (embeds always covers the +1 + final token the token stream defers for the first decode step). MLX + slices silently clamp, so the model received e.g. 152 input_ids columns + against 153 embeds rows, and Qwen4Exp's PLE died with the reported + off-by-one: + "[reshape] Cannot reshape array of size 1556480 into shape (1,153,4,2560)". + The throttle's documented contract is ">= 1, <= requested"; the floor is + an admission bound, not a padding requirement. + """ + hard = 40 * _GB + ns = _throttle_ctx( + current=39.5 * _GB, hard=hard, samples_bpt=2 * 1024**2, min_chunk=256 + ) + ns._fake_current = 39.5 * _GB + # Pressure over the target: the shrink path runs and the floor (256) is + # above the tail (152). + n = _call(ns, 152, kv_len=122_000) + assert n <= 152 diff --git a/tests/test_scheduler.py b/tests/test_scheduler.py index 7d91bc943c..0be0d83515 100644 --- a/tests/test_scheduler.py +++ b/tests/test_scheduler.py @@ -6138,6 +6138,57 @@ def test_chunked_prefill_initialization_seeds_cached_text_mrope( model.clear_vlm_position_state.assert_called_once() seed_mrope.assert_called_once_with(model, request) + def test_vlm_external_prefill_never_slices_embeds_longer_than_tokens( + self, mock_tokenizer + ): + """Regression (#3240): an external-prefill chunk must never exceed the + tokens actually left in the input array. + + VLM ``inputs_embeds`` always spans one row wider than the token side + (the final token is deferred to ``insert()`` for the first decode + step), and MLX slices silently clamp at the array edge. So a chunk + inflated past the remaining tail — e.g. the prefill throttle raising + a short tail back to the ``prefill_min_chunk_tokens`` floor — fed the + model 152 input_ids columns against 153 embeds rows and Qwen4Exp's + PLE died with the reported off-by-one: + "[reshape] Cannot reshape array of size 1556480 into shape (1,153,4,2560)". + The floor stub reproduces that inflation and the assertion pins the + invariant at the model boundary. + """ + model = self._make_vlm_model() + scheduler = Scheduler( + model=model, + tokenizer=mock_tokenizer, + config=SchedulerConfig(prefill_step_size=4), + stream=mx.new_stream(mx.cpu), + ) + # Floor-always throttle stubs: mimics the throttle state that + # inflates every chunk to the min-chunk floor. + scheduler._adaptive_chunk_size = lambda requested, **kw: 256 + scheduler._guard_prefill_chunk = lambda n_tokens, **kw: n_tokens + + request = Request( + request_id="vlm-tail-chunk", + prompt="image prompt", + sampling_params=SamplingParams(max_tokens=1), + ) + request.prompt_token_ids = list(range(10)) + request.num_prompt_tokens = 10 + embeds = mx.zeros((1, 10, 4), dtype=mx.float32) + + scheduler._do_external_prefill( + request, + tokens=request.prompt_token_ids, + existing_cache=[], + vlm_embeds=(embeds, {}, 0), + ) + + assert model.call_count > 0 + for model_call in model.call_args_list: + input_ids = model_call.args[0] + inputs_embeds = model_call.kwargs["inputs_embeds"] + assert inputs_embeds.shape[1] == input_ids.shape[1] + class TestBuildStateMachineStopStrings: """Tests for _build_state_machine stop-string tokenization. From d1743d82d5e01cb9ae9742f7715b34ebdcea66ef Mon Sep 17 00:00:00 2001 From: Matthijs van den Bos Date: Sun, 6 Sep 2026 10:36:40 +0200 Subject: [PATCH 082/132] fix(qwen4_exp): avoid double-counting retained prefill buffers --- omlx/engine_pool.py | 3 +++ omlx/prefill_transient_tracker.py | 16 ++++++++++++++- omlx/scheduler.py | 5 +++++ tests/test_engine_pool.py | 1 + tests/test_prefill_oom_graceful.py | 21 +++++++++++++++++++ tests/test_prefill_transient_tracker.py | 27 ++++++++++++++++++++++++- 6 files changed, 71 insertions(+), 2 deletions(-) diff --git a/omlx/engine_pool.py b/omlx/engine_pool.py index f835cf3eba..f9da3d9387 100644 --- a/omlx/engine_pool.py +++ b/omlx/engine_pool.py @@ -2157,6 +2157,9 @@ def _reclaim_on_engine_thread() -> None: return 0 freed = max(0, before - get_phys_footprint()) if freed > 0: + record_reclaim = getattr(scheduler, "_record_prefill_reclaim", None) + if callable(record_reclaim): + record_reclaim(request_id, freed) logger.info( "Reclaimed %s of pooled Metal buffers for prefill request %s " "(no idle model to evict)", diff --git a/omlx/prefill_transient_tracker.py b/omlx/prefill_transient_tracker.py index d897dd43ff..3583be08fb 100644 --- a/omlx/prefill_transient_tracker.py +++ b/omlx/prefill_transient_tracker.py @@ -236,9 +236,23 @@ def flat_overhead_bytes_for(self, gathered_core: bool) -> int: def reclaim_debt_bytes_for(self, gathered_core: bool) -> int: return self._history(gathered_core).reclaim_debt_bytes + def record_external_reclaim(self, request_id: str, reclaimed_bytes: int) -> None: + """Price only observed flat overhead that a cache clear released.""" + if reclaimed_bytes <= 0: + return + for history in (self._dense_history, self._gathered_history): + if history.request_id == request_id: + history.reclaim_debt_bytes = max( + history.reclaim_debt_bytes, + min(history.flat_overhead_bytes, int(reclaimed_bytes)), + ) + def flat_overhead_charge_for(self, gathered_core: bool) -> int: history = self._history(gathered_core) - return max(history.flat_overhead_bytes, history.reclaim_debt_bytes) + # Retained pool growth is already present in the scheduler's current + # physical-footprint reading. Charging it again double-counts it. + # Only the portion actually reclaimed can be reallocated next chunk. + return min(history.flat_overhead_bytes, history.reclaim_debt_bytes) def expansion_limit_for( self, gathered_core: bool, *, request_id: str = "" diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 3a7b462fc8..c23c52df52 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -4837,6 +4837,11 @@ def _bypass_hot_cache_under_pressure(self) -> bool: return False return current >= self._memory_limit_bytes + def _record_prefill_reclaim(self, request_id: str, reclaimed_bytes: int) -> None: + self._prefill_transient_tracker.record_external_reclaim( + request_id, reclaimed_bytes + ) + def _record_chunk_transient( self, n_tokens: int, diff --git a/tests/test_engine_pool.py b/tests/test_engine_pool.py index 4665b15a49..a955e8c09f 100644 --- a/tests/test_engine_pool.py +++ b/tests/test_engine_pool.py @@ -2241,6 +2241,7 @@ def reclaim(): # 45GB -> 25GB reclaim brings 25 + 10 (predicted) under the 40GB cap. assert admitted is True scheduler._reclaim_prefill_headroom.assert_called_once() + scheduler._record_prefill_reclaim.assert_called_once_with("req-1", 20 * gb) pool._unload_engine.assert_not_awaited() @pytest.mark.asyncio diff --git a/tests/test_prefill_oom_graceful.py b/tests/test_prefill_oom_graceful.py index e706ad5c00..60fb2882c1 100644 --- a/tests/test_prefill_oom_graceful.py +++ b/tests/test_prefill_oom_graceful.py @@ -717,6 +717,27 @@ def test_qwen4_mask_dense_chunk_does_not_poison_gathered_admission(): tracker = ns._prefill_transient_tracker assert tracker.flat_overhead_bytes_for(False) > 0 assert tracker.flat_overhead_bytes_for(True) == 0 + + # The 26 GB retained pool is already in current footprint, so the next + # dense chunk pays only its static profile. If a clear really releases + # 12.5 GB, only that released portion becomes a one-shot charge. + dense_retained = ns._predicted_chunk_transient( + 2048, 141_312, gathered_core=False + ) + static_prediction = ( + monitor.estimate_chunk_transient_bytes(2048, 143_360, gathered_core=False) + + monitor.estimate_prompt_kv_bytes(2048) + ) * Scheduler._PREFILL_TRANSIENT_SAFETY + assert dense_retained == pytest.approx(static_prediction) + tracker.record_external_reclaim("dense-prefix", int(12.5 * _GB)) + dense_reallocation = ns._predicted_chunk_transient( + 2048, 141_312, gathered_core=False + ) + assert dense_reallocation == pytest.approx( + static_prediction + tracker.flat_overhead_charge_for(False) + ) + assert tracker.flat_overhead_charge_for(False) <= 12.5 * _GB + gathered_floor = ns._predicted_chunk_transient( 32, 142_784, gathered_core=True ) diff --git a/tests/test_prefill_transient_tracker.py b/tests/test_prefill_transient_tracker.py index 73dac264df..fc297f6c6a 100644 --- a/tests/test_prefill_transient_tracker.py +++ b/tests/test_prefill_transient_tracker.py @@ -240,7 +240,32 @@ def test_fixed_overhead_is_not_scaled_by_token_count(self): request_id="r", ) assert t.flat_overhead_bytes_for(False) == 570 * self.MB - assert t.flat_overhead_charge_for(False) == 570 * self.MB + assert t.flat_overhead_charge_for(False) == 0 + + def test_only_reclaimed_flat_overhead_is_charged_again(self): + t = PrefillTransientTracker("qwen4") + t.observe_flat_overhead( + 2048, + 28_536 * self.MB, + static_bytes=1402 * self.MB, + request_id="r", + ) + + # The retained 27 GB is already included in current footprint. + assert t.flat_overhead_charge_for(False) == 0 + t.record_external_reclaim("r", 12_500 * self.MB) + assert t.flat_overhead_charge_for(False) == 12_500 * self.MB + assert t.flat_overhead_charge_for(True) == 0 + + # The next positive delta repays that one-shot reallocation risk. + t.observe_flat_overhead( + 2048, + 13_902 * self.MB, + static_bytes=1402 * self.MB, + request_id="r", + ) + assert t.flat_overhead_charge_for(False) == 0 + assert t.flat_overhead_bytes_for(False) == 27_134 * self.MB def test_reclaim_debt_tracks_net_release(self): t = PrefillTransientTracker("qwen4") From 14e11f253e9b9961d1d20ec79a86ab16b27d5e9b Mon Sep 17 00:00:00 2001 From: Matthijs van den Bos Date: Sun, 6 Sep 2026 10:48:10 +0200 Subject: [PATCH 083/132] fix(qwen4_exp): keep reclaimed overhead route-local --- omlx/prefill_transient_tracker.py | 18 ++-- omlx/scheduler.py | 107 ++++++++++++------------ tests/test_prefill_oom_graceful.py | 44 ++++++++-- tests/test_prefill_transient_tracker.py | 11 ++- tests/test_qwen4_qsa_decode_gather.py | 12 ++- tests/test_qwen4_qsa_prefill_memory.py | 1 + 6 files changed, 124 insertions(+), 69 deletions(-) diff --git a/omlx/prefill_transient_tracker.py b/omlx/prefill_transient_tracker.py index 3583be08fb..5dc10dced2 100644 --- a/omlx/prefill_transient_tracker.py +++ b/omlx/prefill_transient_tracker.py @@ -236,16 +236,18 @@ def flat_overhead_bytes_for(self, gathered_core: bool) -> int: def reclaim_debt_bytes_for(self, gathered_core: bool) -> int: return self._history(gathered_core).reclaim_debt_bytes - def record_external_reclaim(self, request_id: str, reclaimed_bytes: int) -> None: - """Price only observed flat overhead that a cache clear released.""" + def record_external_reclaim( + self, request_id: str, reclaimed_bytes: int, *, gathered_core: bool + ) -> None: + """Price only route-matched flat overhead that a cache clear released.""" if reclaimed_bytes <= 0: return - for history in (self._dense_history, self._gathered_history): - if history.request_id == request_id: - history.reclaim_debt_bytes = max( - history.reclaim_debt_bytes, - min(history.flat_overhead_bytes, int(reclaimed_bytes)), - ) + history = self._history(gathered_core) + if history.request_id == request_id: + history.reclaim_debt_bytes = max( + history.reclaim_debt_bytes, + min(history.flat_overhead_bytes, int(reclaimed_bytes)), + ) def flat_overhead_charge_for(self, gathered_core: bool) -> int: history = self._history(gathered_core) diff --git a/omlx/scheduler.py b/omlx/scheduler.py index c23c52df52..01c3afe38f 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -3419,6 +3419,11 @@ def _apply_turboquant_kv_convert(self, prompt_cache: list[Any]) -> None: f"cache layers to {bits}-bit{skip_msg}" ) + def _qwen4_prefill_accounting_enabled(self) -> bool: + monitor = getattr(self, "memory_monitor", None) + checker = getattr(monitor, "is_qwen4_gathered_prefill_profile", None) + return callable(checker) and checker() is True + def _qwen4_text_gathered_pricing(self, text_only: bool) -> bool: """True when this engine can price Qwen4 text prefill as gathered QSA. @@ -3426,11 +3431,7 @@ def _qwen4_text_gathered_pricing(self, text_only: bool) -> bool: False. Preflight and prefill then share an argument instead of a mutable flag on the shared monitor. """ - if text_only is not True: - return False - monitor = getattr(self, "memory_monitor", None) - checker = getattr(monitor, "is_qwen4_gathered_prefill_profile", None) - return callable(checker) and checker() is True + return text_only is True and Scheduler._qwen4_prefill_accounting_enabled(self) @staticmethod def _qwen4_actual_gathered_pricing( @@ -3690,20 +3691,21 @@ def _do_external_prefill( extra_kwargs = _advance_vlm_extra(extra_kwargs, n_to_process) _trace_model_ms = (time.perf_counter() - _trace_model_start) * 1000.0 _throttle_post = get_phys_footprint() - actual_gathered_core = Scheduler._qwen4_actual_gathered_pricing( - prompt_cache, gathered_core - ) - if actual_gathered_core != gathered_core: - logger.info( - "Qwen4 prefill pricing route corrected after execution: " - "rid=%s predicted=%s actual=%s query=%d kv_len=%d", - request.request_id, - "gathered" if gathered_core else "mask_dense", - "gathered" if actual_gathered_core else "mask_dense", - n_to_process, - base_size + processed_tokens, + if Scheduler._qwen4_prefill_accounting_enabled(self): + actual_gathered_core = Scheduler._qwen4_actual_gathered_pricing( + prompt_cache, gathered_core ) - gathered_core = actual_gathered_core + if actual_gathered_core != gathered_core: + logger.info( + "Qwen4 prefill pricing route corrected after execution: " + "rid=%s predicted=%s actual=%s query=%d kv_len=%d", + request.request_id, + "gathered" if gathered_core else "mask_dense", + "gathered" if actual_gathered_core else "mask_dense", + n_to_process, + base_size + processed_tokens, + ) + gathered_core = actual_gathered_core self._record_chunk_transient( n_to_process, _throttle_pre, @@ -3969,11 +3971,7 @@ def _predicted_chunk_transient( static += self.memory_monitor.estimate_prompt_kv_bytes(n_tokens) static_per_token = float(static) / n_tokens per_token = static_per_token - qwen4_flat_overhead = bool( - MemoryMonitor is not None - and isinstance(self.memory_monitor, MemoryMonitor) - and self.memory_monitor.is_qwen4_gathered_prefill_profile() - ) + qwen4_flat_overhead = Scheduler._qwen4_prefill_accounting_enabled(self) if tracker is not None: if qwen4_flat_overhead: # Qwen4's profile (#3461) owns every token-scaled term. Raw @@ -4294,11 +4292,7 @@ def _guard_prefill_chunk( ) # The floor fits — pick the largest chunk that still fits under the cap. - qwen4_flat_overhead = bool( - MemoryMonitor is not None - and isinstance(self.memory_monitor, MemoryMonitor) - and self.memory_monitor.is_qwen4_gathered_prefill_profile() - ) + qwen4_flat_overhead = Scheduler._qwen4_prefill_accounting_enabled(self) if qwen4_flat_overhead: n_fit = Scheduler._largest_fitting_prefill_chunk( self, @@ -4443,12 +4437,7 @@ def _adaptive_chunk_size( current = self._current_usage_bytes() min_chunk = max(1, self._prefill_min_chunk_tokens) - monitor = self.memory_monitor - qwen4_flat_overhead = bool( - MemoryMonitor is not None - and isinstance(monitor, MemoryMonitor) - and monitor.is_qwen4_gathered_prefill_profile() - ) + qwen4_flat_overhead = Scheduler._qwen4_prefill_accounting_enabled(self) if qwen4_flat_overhead: expansion_limit = self._prefill_transient_tracker.expansion_limit_for( gathered_core, request_id=request_id @@ -4688,6 +4677,9 @@ def _clear_request_admission_bookkeeping(self, request_id: str) -> None: self._cache_freshness_waits.pop(request_id, None) self._prefix_cache_prepared.discard(request_id) self._throttle_notified_requests.discard(request_id) + routes = getattr(self, "_qwen4_prefill_route_by_request", None) + if routes is not None: + routes.pop(request_id, None) self._clear_memory_admission_blocker(request_id) self._clear_store_cache_admission_blocker(request_id) @@ -4838,9 +4830,13 @@ def _bypass_hot_cache_under_pressure(self) -> bool: return current >= self._memory_limit_bytes def _record_prefill_reclaim(self, request_id: str, reclaimed_bytes: int) -> None: - self._prefill_transient_tracker.record_external_reclaim( - request_id, reclaimed_bytes - ) + if not Scheduler._qwen4_prefill_accounting_enabled(self): + return + route = getattr(self, "_qwen4_prefill_route_by_request", {}).get(request_id) + if route is not None: + self._prefill_transient_tracker.record_external_reclaim( + request_id, reclaimed_bytes, gathered_core=route + ) def _record_chunk_transient( self, @@ -4897,6 +4893,10 @@ def _record_chunk_transient( kv_len + n_tokens, gathered_core=gathered_core, ) + monitor.estimate_prompt_kv_bytes(n_tokens) + routes = getattr(self, "_qwen4_prefill_route_by_request", None) + if routes is None: + routes = self._qwen4_prefill_route_by_request = {} + routes[request_id] = gathered_core self._prefill_transient_tracker.observe_flat_overhead( n_tokens, delta, @@ -5400,9 +5400,10 @@ def _step_prefill_chunk(self, state: _PrefillState) -> bool: # 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). - if state.qwen4_gathered_core is None: + 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 + gathered_core = state.qwen4_gathered_core or False n = self._adaptive_chunk_size( n, request_id=state.request.request_id, @@ -5451,20 +5452,22 @@ def _step_prefill_chunk(self, state: _PrefillState) -> bool: mx.eval([c.state for c in state.cache]) _trace_model_ms = (time.perf_counter() - _trace_model_start) * 1000.0 _throttle_post = get_phys_footprint() - actual_gathered_core = Scheduler._qwen4_actual_gathered_pricing( - state.cache, gathered_core - ) - if actual_gathered_core != gathered_core: - logger.info( - "Qwen4 prefill pricing route corrected after execution: " - "rid=%s predicted=%s actual=%s query=%d kv_len=%d", - state.request.request_id, - "gathered" if gathered_core else "mask_dense", - "gathered" if actual_gathered_core else "mask_dense", - n, - state.base_size + state.tokens_processed, + actual_gathered_core = gathered_core + if qwen4_accounting: + actual_gathered_core = Scheduler._qwen4_actual_gathered_pricing( + state.cache, gathered_core ) - state.qwen4_gathered_core = actual_gathered_core + if actual_gathered_core != gathered_core: + logger.info( + "Qwen4 prefill pricing route corrected after execution: " + "rid=%s predicted=%s actual=%s query=%d kv_len=%d", + state.request.request_id, + "gathered" if gathered_core else "mask_dense", + "gathered" if actual_gathered_core else "mask_dense", + n, + state.base_size + state.tokens_processed, + ) + state.qwen4_gathered_core = actual_gathered_core self._record_chunk_transient( n, _throttle_pre, diff --git a/tests/test_prefill_oom_graceful.py b/tests/test_prefill_oom_graceful.py index 60fb2882c1..a338e61293 100644 --- a/tests/test_prefill_oom_graceful.py +++ b/tests/test_prefill_oom_graceful.py @@ -694,6 +694,17 @@ def test_qwen4_measured_excess_is_flat_not_scaled_to_the_next_chunk(): assert predicted < 20 * _GB / measured_tokens * candidate +@pytest.mark.parametrize( + ("markers", "predicted", "expected"), + [([], True, True), ([True, True], False, True), ([True, False], True, False)], +) +def test_qwen4_actual_route_uses_cache_markers_or_prediction( + markers, predicted, expected +): + cache = [SimpleNamespace(_omlx_last_prefill_gathered=value) for value in markers] + assert Scheduler._qwen4_actual_gathered_pricing(cache, predicted) is expected + + def test_qwen4_mask_dense_chunk_does_not_poison_gathered_admission(): """Replay the 143k false rejection from the live server log.""" monitor = _qwen4_monitor() @@ -729,7 +740,8 @@ def test_qwen4_mask_dense_chunk_does_not_poison_gathered_admission(): + monitor.estimate_prompt_kv_bytes(2048) ) * Scheduler._PREFILL_TRANSIENT_SAFETY assert dense_retained == pytest.approx(static_prediction) - tracker.record_external_reclaim("dense-prefix", int(12.5 * _GB)) + assert ns._qwen4_prefill_route_by_request == {"dense-prefix": False} + Scheduler._record_prefill_reclaim(ns, "dense-prefix", int(12.5 * _GB)) dense_reallocation = ns._predicted_chunk_transient( 2048, 141_312, gathered_core=False ) @@ -756,6 +768,20 @@ def test_non_qwen4_prediction_keeps_existing_measured_rate_behavior(): assert predicted >= 20 * _GB / 1600 * 2048 +def test_qwen4_route_and_reclaim_accounting_are_model_scoped(): + generic = SimpleNamespace( + memory_monitor=_monitor(head_dim=192), + _qwen4_prefill_route_by_request={"r": True}, + _prefill_transient_tracker=MagicMock(), + ) + qwen4 = SimpleNamespace(memory_monitor=_qwen4_monitor()) + + assert not Scheduler._qwen4_prefill_accounting_enabled(generic) + assert Scheduler._qwen4_prefill_accounting_enabled(qwen4) + Scheduler._record_prefill_reclaim(generic, "r", 1024) + generic._prefill_transient_tracker.record_external_reclaim.assert_not_called() + + def test_qwen4_real_chunk_callsite_tracks_deltas_and_expands_one_tier(): monitor = _qwen4_monitor() ns = _throttle_ctx(current=0, hard=240 * _GB, monitor=monitor) @@ -1193,12 +1219,18 @@ def test_record_chunk_transient_keeps_partial_context_sample(): assert tracker.last_delta_bytes == partial_delta -def test_step_prefill_reclaims_before_first_guard(): +@pytest.mark.parametrize( + ("monitor", "expected_gathered", "expected_state_route"), + [(_qwen4_monitor(), True, True), (_monitor(head_dim=192), False, None)], +) +def test_step_prefill_reclaims_before_first_guard( + monitor, expected_gathered, expected_state_route +): events = [] request = SimpleNamespace(request_id="req-prefill") state = _PrefillState( request=request, - cache=[], + cache=[SimpleNamespace(state=None, _omlx_last_prefill_gathered=True)], tokens_remaining=sched_mod.mx.array([[1, 2, 3]]), last_token=[4], tokens_processed=0, @@ -1209,7 +1241,8 @@ def test_step_prefill_reclaims_before_first_guard(): total_length=4, ) ns = SimpleNamespace( - config=SimpleNamespace(prefill_step_size=2, model_name=""), + config=SimpleNamespace(prefill_step_size=2, model_name="qwen4"), + memory_monitor=monitor, _stream="stream", _memory_limit_bytes=0, _glm_dsa_adaptive_prefill=None, @@ -1262,8 +1295,9 @@ def test_step_prefill_reclaims_before_first_guard(): loop_label="chunked_step", kv_len=0, requested_step=2, - gathered_core=False, + gathered_core=expected_gathered, ) + assert state.qwen4_gathered_core is expected_state_route # -------------------------------------------------------------------------- diff --git a/tests/test_prefill_transient_tracker.py b/tests/test_prefill_transient_tracker.py index fc297f6c6a..6f812a9ffd 100644 --- a/tests/test_prefill_transient_tracker.py +++ b/tests/test_prefill_transient_tracker.py @@ -251,9 +251,18 @@ def test_only_reclaimed_flat_overhead_is_charged_again(self): request_id="r", ) + t.observe_flat_overhead( + 2048, + 10_000 * self.MB, + static_bytes=1402 * self.MB, + request_id="r", + gathered_core=True, + ) # The retained 27 GB is already included in current footprint. assert t.flat_overhead_charge_for(False) == 0 - t.record_external_reclaim("r", 12_500 * self.MB) + t.record_external_reclaim( + "r", 12_500 * self.MB, gathered_core=False + ) assert t.flat_overhead_charge_for(False) == 12_500 * self.MB assert t.flat_overhead_charge_for(True) == 0 diff --git a/tests/test_qwen4_qsa_decode_gather.py b/tests/test_qwen4_qsa_decode_gather.py index 2b65845ff2..cd8930c33b 100644 --- a/tests/test_qwen4_qsa_decode_gather.py +++ b/tests/test_qwen4_qsa_decode_gather.py @@ -103,6 +103,8 @@ def tracked_sdpa(queries, keys, values, scale): mx.argmax(expected, axis=-1), ).item() assert fast_cache.offset == reference_cache.offset == 11 + assert fast_cache._omlx_last_prefill_gathered is True + assert reference_cache._omlx_last_prefill_gathered is True for fast_value, reference_value in zip( fast_cache.state, reference_cache.state, @@ -170,7 +172,11 @@ def tracked_decode(self, x, cache, position_ids=None): ) decode_token = mx.array([[12]], dtype=mx.int32) + position_ids = model._position_ids + rope_deltas = model._rope_deltas actual = model(decode_token, cache=fast_cache) + model._position_ids = position_ids + model._rope_deltas = rope_deltas monkeypatch.setattr( language.Qwen4ExpAttention, "_gathered_text_decode_eligible", @@ -186,10 +192,10 @@ def tracked_decode(self, x, cache, position_ids=None): assert mx.allclose( fast_prefix.logits, reference_prefix.logits, - rtol=2e-5, - atol=2e-5, + rtol=2e-4, + atol=2e-4, ).item() - assert mx.allclose(actual.logits, expected.logits, rtol=2e-5, atol=2e-5).item() + assert mx.allclose(actual.logits, expected.logits, rtol=2e-4, atol=2e-4).item() assert mx.array_equal( mx.argmax(actual.logits[:, -1], axis=-1), mx.argmax(expected.logits[:, -1], axis=-1), diff --git a/tests/test_qwen4_qsa_prefill_memory.py b/tests/test_qwen4_qsa_prefill_memory.py index bd6ca16adc..37ab41298a 100644 --- a/tests/test_qwen4_qsa_prefill_memory.py +++ b/tests/test_qwen4_qsa_prefill_memory.py @@ -233,6 +233,7 @@ def boom(*args, **kwargs): mask = calls[0] assert isinstance(mask, mx.array) assert 1 <= mask.ndim <= 4 + assert cache._omlx_last_prefill_gathered is False finally: for mod, fn in sdpa_snap.items(): mod.scaled_dot_product_attention = fn From 9a544e37f22c493fe281e5d1284c3cadaf44dedb Mon Sep 17 00:00:00 2001 From: pedroberaldo87 <134068505+pedroberaldo87@users.noreply.github.com> Date: Sun, 6 Sep 2026 08:37:54 -0300 Subject: [PATCH 084/132] fix: preserve external prefill progress across eviction pauses (#3414) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(scheduler): an eviction pause mid external prefill lost progress and duplicated KV tokens The external prefill loop sizes each chunk through the adaptive throttle, which can raise _PrefillEvictionNeeded AFTER chunks have already entered the cache (prompt_cache is advanced in place). The pause re-queued the request with the remaining_tokens/cached_tokens it started with, so the retry fed the same tokens again on top of the advanced cache. The damage compounds: a duplicated span in the KV, boundary snapshots labelled one block behind what the cache held ("tc=7680 kv=8192", "tc=8192 kv=8704"), and every block stored from there on misaligned — layer 3's KV differed in 2.6 of 2 positions, i.e. it held keys for OTHER tokens. The next request that hit those blocks generated garbage ("NoNo", "DEDEDE", "Sand Sand"). Reproduced through the API in three steps: A stores the prefix, B restores and prefills while throttled, C hits it and generates garbage (2 of 2). It only surfaced with the MTP head enabled, because only then did memory pressure push the throttle far enough to pause a chunk — the head was the witness, not the cause. The pause now commits the progress: cached_tokens += processed and remaining_tokens = what is left. Test: the new one fails without the fix (4 == 8). * fix(prefill): an eviction pause on a COLD prompt keeps its progress too The previous fix committed the pause's progress only when the request had started from a restored prefix cache (existing_cache). A cold prompt builds prompt_cache locally; the pause dropped it with the exception and the retry started again from token zero. Measured 05/09 on GLM-5.3-Flash oQ2e, cold 229,923-token prompt: paused at 206,336 tokens ("needs prefill headroom ... current=111.76GB target=112.48GB"), the eviction reclaimed 1.56 GB, and the request was re-admitted as new (new=229923 kv_exact=0) -- 19 minutes of prefill thrown away, and nothing to stop the same thing at 206k again. The advanced cache now goes onto request.prompt_cache, which is exactly what the retry reads (cache_to_use = request.prompt_cache), with cached_tokens and remaining_tokens at the right point. In the field, on the next 229k run, two pauses at 192k cost 6 seconds and re-admitted only the remaining 36k. Test: test_pause_on_a_cold_prompt_commits_the_progress_too (failed before: prompt_cache was None). --------- Co-authored-by: Pedro Beraldo --- omlx/scheduler.py | 46 ++++++- ...est_scheduler_prefill_eviction_progress.py | 130 ++++++++++++++++++ 2 files changed, 169 insertions(+), 7 deletions(-) create mode 100644 tests/test_scheduler_prefill_eviction_progress.py diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 1bbb6faab5..e32c914f9e 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -3601,13 +3601,45 @@ def _do_external_prefill( # so the hard cap is honored before the chunk-end check. Raises # RuntimeError if the min chunk would exceed the cap — the # #1405 cleanup path catches it and emits an error to the client. - n_to_process = self._adaptive_chunk_size( - n_to_process, - request_id=request.request_id, - loop_label="external", - kv_len=base_size + processed_tokens, - gathered_core=gathered_core, - ) + try: + n_to_process = self._adaptive_chunk_size( + n_to_process, + request_id=request.request_id, + loop_label="external", + kv_len=base_size + processed_tokens, + gathered_core=gathered_core, + ) + except _PrefillEvictionNeeded: + # The eviction pause re-queues the request keeping its + # prompt_cache, which this loop has already advanced in + # place by ``processed_tokens``. Commit that progress, or + # the retry re-feeds the same tokens on top of the advanced + # cache: a duplicated span in the KV, boundary snapshots + # labelled one block behind the cache, and every block + # stored from there on misaligned — the next prefix hit + # generates garbage (GLM-5.3, 02/09, only reachable when the + # MTP head's memory pushed the throttle into a paused chunk). + # + # A COLD prompt has to commit too. The restored-prefix case was + # the one measured in 02/09, so the commit was gated on + # ``existing_cache``; a cold prompt builds ``prompt_cache`` + # locally, the pause dropped it with this exception, and the + # retry started from token zero. Measured 05/09 on GLM-5.3-Flash + # oQ2e: a 229.923-token prompt was paused at 206.336 tokens + # ("needs prefill headroom ... current=111.76GB target=112.48GB"), + # the eviction reclaimed 1,56 GB, and the request was re-admitted + # as ``new=229923 kv_exact=0`` — 19 minutes of prefill thrown + # away, and nothing stops it from happening again at the same + # point. Attaching the advanced cache to the request is what the + # retry path already reads (``cache_to_use = request.prompt_cache``). + if processed_tokens > 0: + if existing_cache is None: + request.prompt_cache = prompt_cache + request.cached_tokens = ( + int(getattr(request, "cached_tokens", 0) or 0) + processed_tokens + ) + request.remaining_tokens = tokens[processed_tokens:] + raise # Pre-chunk safety guard: NEVER submit a chunk whose predicted peak # would breach the prefill safety cap. The Metal command-buffer diff --git a/tests/test_scheduler_prefill_eviction_progress.py b/tests/test_scheduler_prefill_eviction_progress.py new file mode 100644 index 0000000000..b2040fa2cf --- /dev/null +++ b/tests/test_scheduler_prefill_eviction_progress.py @@ -0,0 +1,130 @@ +# SPDX-License-Identifier: Apache-2.0 +"""An eviction pause MID external prefill must not lose the progress made. + +The external prefill loop sizes each chunk through the adaptive throttle, +which may raise ``_PrefillEvictionNeeded`` — including AFTER chunks have +already entered the cache (the ``prompt_cache`` object is advanced in +place). The pause re-queued the request with the ``remaining_tokens`` and +``cached_tokens`` it started with, so on retry the same tokens were fed +again on top of the advanced cache: a DUPLICATED span in the KV, boundary +snapshots labelled one block behind what the cache actually held +(``tc=7680 ... kv=8192``, measured on GLM-5.3-Flash), and every block +stored from there on misaligned — the next request that hit that prefix +generated garbage ("NoNo", "DEDEDE"). It only showed up with the MTP head +enabled, because only then did memory pressure push the throttle far +enough to pause a chunk. +""" +from __future__ import annotations + +from types import SimpleNamespace + +import mlx.core as mx +import pytest +from mlx_lm.models.cache import KVCache + +from omlx.request import Request, SamplingParams +from omlx.scheduler import Scheduler, SchedulerConfig, _PrefillEvictionNeeded + + +class _CountingModel: + """Only pushes positions into a KVCache: the offset is what matters.""" + + def __init__(self): + self.layers = [SimpleNamespace()] + self.args = SimpleNamespace(num_hidden_layers=1) + + def __call__(self, inputs, cache=None, **kwargs): + S = inputs.shape[1] + cache[0].update_and_fetch(mx.zeros((1, 1, S, 4)), mx.zeros((1, 1, S, 4))) + return mx.zeros((1, S, 8)) + + def make_cache(self): + return [KVCache()] + + def parameters(self): + return {} + + +def test_pause_mid_external_prefill_commits_the_progress(mock_tokenizer): + model = _CountingModel() + scheduler = Scheduler( + model=model, tokenizer=mock_tokenizer, config=SchedulerConfig(prefill_step_size=4) + ) + # restored prefix: 4 tokens already in the cache + cache = model.make_cache() + model(mx.zeros((1, 4), dtype=mx.int32), cache=cache) + prompt = list(range(100, 116)) # 16 tokens; 12 to go (the last is the generator's) + request = Request(request_id="req-pause", prompt=prompt, sampling_params=SamplingParams()) + request.prompt_token_ids = prompt + request.num_prompt_tokens = len(prompt) + request.cached_tokens = 4 + request.remaining_tokens = prompt[4:] + request.prompt_cache = cache + scheduler.requests[request.request_id] = request + + calls = {"n": 0} + original = scheduler._adaptive_chunk_size + + def throttle_on_the_second(requested, **kw): + calls["n"] += 1 + if calls["n"] == 2: + raise _PrefillEvictionNeeded( + SimpleNamespace(reason="adaptive_prefill_throttle", request_id=request.request_id) + ) + return original(requested, **kw) + + scheduler._adaptive_chunk_size = throttle_on_the_second + + with pytest.raises(_PrefillEvictionNeeded): + scheduler._do_external_prefill(request, request.remaining_tokens, cache) + + # the cache advanced by ONE chunk (4 tokens) before the pause + assert cache[0].offset == 8 + # and the request has to know it: what is left starts AFTER what went in + assert request.cached_tokens == 8, request.cached_tokens + assert request.remaining_tokens == prompt[8:], request.remaining_tokens + assert request.prompt_cache is cache + + +def test_pause_on_a_cold_prompt_commits_the_progress_too(mock_tokenizer): + """The case the first fix missed: with no restored prefix, the pause restarted at token zero. + + Measured 05/09 on GLM-5.3-Flash oQ2e: a cold 229,923-token prompt was paused at + 206,336 tokens for headroom (111.76 GB against a 112.48 GB target), the eviction + reclaimed 1.56 GB, and the request was re-admitted as new (new=229923, kv_exact=0) + — 19 minutes of prefill thrown away, with nothing preventing the same at 206k again. + The locally built cache has to go onto the request, which is where the retry reads it. + """ + model = _CountingModel() + scheduler = Scheduler( + model=model, tokenizer=mock_tokenizer, config=SchedulerConfig(prefill_step_size=4) + ) + prompt = list(range(100, 116)) + request = Request(request_id="req-cold", prompt=prompt, sampling_params=SamplingParams()) + request.prompt_token_ids = prompt + request.num_prompt_tokens = len(prompt) + request.cached_tokens = 0 + request.remaining_tokens = prompt + request.prompt_cache = None + scheduler.requests[request.request_id] = request + + calls = {"n": 0} + original = scheduler._adaptive_chunk_size + + def throttle_on_third(requested, **kw): + calls["n"] += 1 + if calls["n"] == 3: + raise _PrefillEvictionNeeded( + SimpleNamespace(reason="adaptive_prefill_throttle", request_id=request.request_id) + ) + return original(requested, **kw) + + scheduler._adaptive_chunk_size = throttle_on_third + with pytest.raises(_PrefillEvictionNeeded): + scheduler._do_external_prefill(request, prompt, None) + + # two chunks of 4 went in before the pause; the cache must be ON THE REQUEST + assert request.prompt_cache is not None + assert request.prompt_cache[0].offset == 8 + assert request.cached_tokens == 8, request.cached_tokens + assert request.remaining_tokens == prompt[8:], request.remaining_tokens From 59e497d2a677e6d3b3befd3dd1286ef87b03bda1 Mon Sep 17 00:00:00 2001 From: jundot Date: Sun, 6 Sep 2026 20:40:43 +0900 Subject: [PATCH 085/132] fix: preserve prefill progress on safety-guard eviction (#3414) --- omlx/scheduler.py | 55 ++---- ...est_scheduler_prefill_eviction_progress.py | 168 ++++++++---------- 2 files changed, 85 insertions(+), 138 deletions(-) diff --git a/omlx/scheduler.py b/omlx/scheduler.py index e32c914f9e..14b61f066f 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -3597,10 +3597,6 @@ def _do_external_prefill( n_to_process = min(n_to_process, delta) n_to_process = max(1, n_to_process) - # Adaptive throttle: shrink chunk when entering the caution zone - # so the hard cap is honored before the chunk-end check. Raises - # RuntimeError if the min chunk would exceed the cap — the - # #1405 cleanup path catches it and emits an error to the client. try: n_to_process = self._adaptive_chunk_size( n_to_process, @@ -3609,52 +3605,25 @@ def _do_external_prefill( kv_len=base_size + processed_tokens, gathered_core=gathered_core, ) + # 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, + progress=processed_tokens, + loop_label="external", + request_id=request.request_id, + gathered_core=gathered_core, + ) except _PrefillEvictionNeeded: - # The eviction pause re-queues the request keeping its - # prompt_cache, which this loop has already advanced in - # place by ``processed_tokens``. Commit that progress, or - # the retry re-feeds the same tokens on top of the advanced - # cache: a duplicated span in the KV, boundary snapshots - # labelled one block behind the cache, and every block - # stored from there on misaligned — the next prefix hit - # generates garbage (GLM-5.3, 02/09, only reachable when the - # MTP head's memory pushed the throttle into a paused chunk). - # - # A COLD prompt has to commit too. The restored-prefix case was - # the one measured in 02/09, so the commit was gated on - # ``existing_cache``; a cold prompt builds ``prompt_cache`` - # locally, the pause dropped it with this exception, and the - # retry started from token zero. Measured 05/09 on GLM-5.3-Flash - # oQ2e: a 229.923-token prompt was paused at 206.336 tokens - # ("needs prefill headroom ... current=111.76GB target=112.48GB"), - # the eviction reclaimed 1,56 GB, and the request was re-admitted - # as ``new=229923 kv_exact=0`` — 19 minutes of prefill thrown - # away, and nothing stops it from happening again at the same - # point. Attaching the advanced cache to the request is what the - # retry path already reads (``cache_to_use = request.prompt_cache``). + # Keep token progress aligned with the advanced KV on retry. + # Cold requests must also retain their locally created cache. if processed_tokens > 0: if existing_cache is None: request.prompt_cache = prompt_cache - request.cached_tokens = ( - int(getattr(request, "cached_tokens", 0) or 0) + processed_tokens - ) + request.cached_tokens += processed_tokens request.remaining_tokens = tokens[processed_tokens:] raise - # Pre-chunk safety guard: NEVER submit a chunk whose predicted peak - # would breach the prefill safety cap. The Metal command-buffer - # OOM is an async, uncatchable SIGABRT, so it must be prevented - # before submission — a post-chunk check is too late. Falls back to - # min_chunk after a reclaim; raises gracefully only if even the - # floor can't fit (caught by the #1405 path → requeue/clean error). - n_to_process = self._guard_prefill_chunk( - n_to_process, - kv_len=base_size + processed_tokens, - progress=processed_tokens, - loop_label="external", - request_id=request.request_id, - gathered_core=gathered_core, - ) if getattr(request, "benchmark_trace", False): request.benchmark_prefill_chunks.append(int(n_to_process)) request.benchmark_requested_steps.append(int(prefill_step_size)) diff --git a/tests/test_scheduler_prefill_eviction_progress.py b/tests/test_scheduler_prefill_eviction_progress.py index b2040fa2cf..a8c6c8ba14 100644 --- a/tests/test_scheduler_prefill_eviction_progress.py +++ b/tests/test_scheduler_prefill_eviction_progress.py @@ -1,20 +1,5 @@ # SPDX-License-Identifier: Apache-2.0 -"""An eviction pause MID external prefill must not lose the progress made. - -The external prefill loop sizes each chunk through the adaptive throttle, -which may raise ``_PrefillEvictionNeeded`` — including AFTER chunks have -already entered the cache (the ``prompt_cache`` object is advanced in -place). The pause re-queued the request with the ``remaining_tokens`` and -``cached_tokens`` it started with, so on retry the same tokens were fed -again on top of the advanced cache: a DUPLICATED span in the KV, boundary -snapshots labelled one block behind what the cache actually held -(``tc=7680 ... kv=8192``, measured on GLM-5.3-Flash), and every block -stored from there on misaligned — the next request that hit that prefix -generated garbage ("NoNo", "DEDEDE"). It only showed up with the MTP head -enabled, because only then did memory pressure push the throttle far -enough to pause a chunk. -""" -from __future__ import annotations +"""External prefill preserves KV and token progress across eviction pauses.""" from types import SimpleNamespace @@ -26,17 +11,19 @@ from omlx.scheduler import Scheduler, SchedulerConfig, _PrefillEvictionNeeded -class _CountingModel: - """Only pushes positions into a KVCache: the offset is what matters.""" +class _RecordingModel: + """Store input tokens in KV so retries expose duplication or recomputation.""" def __init__(self): self.layers = [SimpleNamespace()] self.args = SimpleNamespace(num_hidden_layers=1) + self.seen = [] def __call__(self, inputs, cache=None, **kwargs): - S = inputs.shape[1] - cache[0].update_and_fetch(mx.zeros((1, 1, S, 4)), mx.zeros((1, 1, S, 4))) - return mx.zeros((1, S, 8)) + self.seen.extend(inputs[0].tolist()) + values = inputs[:, None, :, None].astype(mx.float32) + cache[0].update_and_fetch(values, values) + return mx.zeros((1, inputs.shape[1], 8)) def make_cache(self): return [KVCache()] @@ -45,86 +32,77 @@ def parameters(self): return {} -def test_pause_mid_external_prefill_commits_the_progress(mock_tokenizer): - model = _CountingModel() +@pytest.mark.parametrize("cached_tokens", [0, 4], ids=["cold", "warm"]) +@pytest.mark.parametrize("pause_after_chunks", [0, 1, 2]) +@pytest.mark.parametrize("pause_count", [1, 2]) +@pytest.mark.parametrize("route", ["adaptive", "guard"]) +def test_external_prefill_resumes_without_replaying_tokens( + mock_tokenizer, monkeypatch, cached_tokens, pause_after_chunks, pause_count, route +): + model = _RecordingModel() scheduler = Scheduler( - model=model, tokenizer=mock_tokenizer, config=SchedulerConfig(prefill_step_size=4) + model=model, + tokenizer=mock_tokenizer, + config=SchedulerConfig(prefill_step_size=4), ) - # restored prefix: 4 tokens already in the cache - cache = model.make_cache() - model(mx.zeros((1, 4), dtype=mx.int32), cache=cache) - prompt = list(range(100, 116)) # 16 tokens; 12 to go (the last is the generator's) - request = Request(request_id="req-pause", prompt=prompt, sampling_params=SamplingParams()) - request.prompt_token_ids = prompt - request.num_prompt_tokens = len(prompt) - request.cached_tokens = 4 - request.remaining_tokens = prompt[4:] - request.prompt_cache = cache - scheduler.requests[request.request_id] = request - - calls = {"n": 0} - original = scheduler._adaptive_chunk_size - - def throttle_on_the_second(requested, **kw): - calls["n"] += 1 - if calls["n"] == 2: - raise _PrefillEvictionNeeded( - SimpleNamespace(reason="adaptive_prefill_throttle", request_id=request.request_id) - ) - return original(requested, **kw) - - scheduler._adaptive_chunk_size = throttle_on_the_second - - with pytest.raises(_PrefillEvictionNeeded): - scheduler._do_external_prefill(request, request.remaining_tokens, cache) - - # the cache advanced by ONE chunk (4 tokens) before the pause - assert cache[0].offset == 8 - # and the request has to know it: what is left starts AFTER what went in - assert request.cached_tokens == 8, request.cached_tokens - assert request.remaining_tokens == prompt[8:], request.remaining_tokens - assert request.prompt_cache is cache - - -def test_pause_on_a_cold_prompt_commits_the_progress_too(mock_tokenizer): - """The case the first fix missed: with no restored prefix, the pause restarted at token zero. - - Measured 05/09 on GLM-5.3-Flash oQ2e: a cold 229,923-token prompt was paused at - 206,336 tokens for headroom (111.76 GB against a 112.48 GB target), the eviction - reclaimed 1.56 GB, and the request was re-admitted as new (new=229923, kv_exact=0) - — 19 minutes of prefill thrown away, with nothing preventing the same at 206k again. - The locally built cache has to go onto the request, which is where the retry reads it. - """ - model = _CountingModel() - scheduler = Scheduler( - model=model, tokenizer=mock_tokenizer, config=SchedulerConfig(prefill_step_size=4) + prompt = list(range(100, 132)) + request = Request( + request_id="req-pause", prompt=prompt, sampling_params=SamplingParams() ) - prompt = list(range(100, 116)) - request = Request(request_id="req-cold", prompt=prompt, sampling_params=SamplingParams()) request.prompt_token_ids = prompt request.num_prompt_tokens = len(prompt) - request.cached_tokens = 0 - request.remaining_tokens = prompt - request.prompt_cache = None + request.cached_tokens = cached_tokens + request.remaining_tokens = prompt[cached_tokens:] + if cached_tokens: + request.prompt_cache = model.make_cache() + model(mx.array(prompt[:cached_tokens])[None], cache=request.prompt_cache) scheduler.requests[request.request_id] = request - calls = {"n": 0} - original = scheduler._adaptive_chunk_size + scheduler._memory_limit_bytes = 80 + scheduler._memory_hard_limit_bytes = 100 + scheduler._memory_abort_limit_bytes = 100 + scheduler._prefill_abort_margin = 0.9 + scheduler._prefill_min_chunk_tokens = 4 + pause_at = cached_tokens + 4 * pause_after_chunks + + def current_usage(): + return 60 if len(model.seen) >= pause_at else 0 + + monkeypatch.setattr(scheduler, "_current_usage_bytes", current_usage) + monkeypatch.setattr(scheduler, "_reclaim_prefill_headroom", current_usage) + # The guard also charges observed peaks, which can exceed the throttle's estimate. + monkeypatch.setattr( + scheduler, + "_predicted_chunk_transient", + lambda *args, **kwargs: 50 if route == "adaptive" else 4, + ) + monkeypatch.setattr(scheduler, "_admission_transient_bound", lambda *a, **kw: 50) - def throttle_on_third(requested, **kw): - calls["n"] += 1 - if calls["n"] == 3: - raise _PrefillEvictionNeeded( - SimpleNamespace(reason="adaptive_prefill_throttle", request_id=request.request_id) + for _ in range(pause_count): + with pytest.raises(_PrefillEvictionNeeded) as exc: + scheduler._do_external_prefill( + request, request.remaining_tokens, request.prompt_cache ) - return original(requested, **kw) - - scheduler._adaptive_chunk_size = throttle_on_third - with pytest.raises(_PrefillEvictionNeeded): - scheduler._do_external_prefill(request, prompt, None) - - # two chunks of 4 went in before the pause; the cache must be ON THE REQUEST - assert request.prompt_cache is not None - assert request.prompt_cache[0].offset == 8 - assert request.cached_tokens == 8, request.cached_tokens - assert request.remaining_tokens == prompt[8:], request.remaining_tokens + expected_reason = ( + "adaptive_prefill_throttle" if route == "adaptive" else "prefill_safety_cap" + ) + assert exc.value.request.reason == expected_reason + assert request.cached_tokens == pause_at + assert request.remaining_tokens == prompt[pause_at:] + if pause_at: + assert request.prompt_cache[0].offset == pause_at + else: + assert request.prompt_cache is None + scheduler._pause_for_prefill_eviction(request, exc.value.request) + assert scheduler.waiting.popleft() is request + pause_at += 4 + + pause_at = len(prompt) + 1 + cache, last_token = scheduler._do_external_prefill( + request, request.remaining_tokens, request.prompt_cache + ) + assert last_token == prompt[-1:] + assert cache[0].offset == len(prompt) - 1 + model(mx.array(last_token)[None], cache=cache) + assert model.seen == prompt + assert cache[0].keys[0, 0, : cache[0].offset, 0].tolist() == prompt From bb02e07cee3ccbcf1eadf72e37b45bd5f718a26c Mon Sep 17 00:00:00 2001 From: YIN WENQING <54882765+saintlits@users.noreply.github.com> Date: Sun, 6 Sep 2026 20:41:42 +0900 Subject: [PATCH 086/132] fix(dflash): handle memory-pressure aborts (#3424) --- omlx/engine/dflash.py | 95 +++++++++++++++++++++++++++++-------- tests/test_dflash_engine.py | 32 ++++++++++++- 2 files changed, 106 insertions(+), 21 deletions(-) diff --git a/omlx/engine/dflash.py b/omlx/engine/dflash.py index a91b3fc7e7..abfac40dd1 100644 --- a/omlx/engine/dflash.py +++ b/omlx/engine/dflash.py @@ -336,6 +336,12 @@ def __init__( self._executor_tokenizer = None self._loaded = False self._active_request = False + # DFlash runs outside Scheduler, so memory-pressure aborts cannot use + # EngineCore's request registry. Keep the stop events for every + # submitted generation instead; the process memory enforcer calls + # abort_all_requests() to signal them at the next DFlash event boundary. + self._stop_events_lock = threading.Lock() + self._active_stop_events: set[threading.Event] = set() self._model_type_str = None self._fallback_engine: BaseEngine | None = None self._in_fallback_mode = False @@ -1286,7 +1292,7 @@ def _run_generate_streaming( for event in event_iter: if stop_event.is_set(): - logger.info("DFlash generation aborted by client") + logger.info("DFlash generation abort requested") break if isinstance(event, TokenEvent): @@ -1390,6 +1396,7 @@ def _run_generate_streaming( loop, ) self._active_request = False + self._unregister_stop_event(stop_event) def _tokenize_prompt(self, prompt: str | list[int]) -> list[int]: """Return prompt IDs without re-tokenizing an already-tokenized prompt.""" @@ -1397,6 +1404,14 @@ def _tokenize_prompt(self, prompt: str | list[int]) -> list[int]: return list(prompt) return list(self._tokenizer_obj.encode(prompt)) + def _register_stop_event(self, stop_event: threading.Event) -> None: + with self._stop_events_lock: + self._active_stop_events.add(stop_event) + + def _unregister_stop_event(self, stop_event: threading.Event) -> None: + with self._stop_events_lock: + self._active_stop_events.discard(stop_event) + async def generate( self, prompt: str | list[int], @@ -1501,7 +1516,7 @@ def _run(): parser_final = None for event in event_iter: if stop_event.is_set(): - logger.info("DFlash generation aborted by client") + logger.info("DFlash generation abort requested") break if isinstance(event, TokenEvent): if first_token_at is None: @@ -1542,9 +1557,15 @@ def _run(): logger.debug(f"event_iter.close() raised: {exc}") self._end_runtime_cache_request(cache_manager) self._active_request = False + self._unregister_stop_event(stop_event) self._active_request = True - future = loop.run_in_executor(get_mlx_executor(), _run) + self._register_stop_event(stop_event) + try: + future = loop.run_in_executor(get_mlx_executor(), _run) + except Exception: + self._unregister_stop_event(stop_event) + raise try: try: ( @@ -1710,23 +1731,28 @@ async def stream_generate( # Models card reads this activity instead of a scheduler snapshot. activity_id = self._begin_activity("generate", detail="generating") self._active_request = True - future = loop.run_in_executor( - get_mlx_executor(), - self._run_generate_streaming, - prompt_tokens, - max_tokens, - temperature, - top_p, - top_k, - min_p, - repetition_penalty, - int(repetition_context_size), - seed, - tools, - queue, - loop, - stop_event, - ) + self._register_stop_event(stop_event) + try: + future = loop.run_in_executor( + get_mlx_executor(), + self._run_generate_streaming, + prompt_tokens, + max_tokens, + temperature, + top_p, + top_k, + min_p, + repetition_penalty, + int(repetition_context_size), + seed, + tools, + queue, + loop, + stop_event, + ) + except Exception: + self._unregister_stop_event(stop_event) + raise total_text = "" total_completion = 0 @@ -1975,9 +2001,38 @@ def has_active_requests(self) -> bool: return True if self._active_request: return True + with self._stop_events_lock: + if self._active_stop_events: + return True with self._active_lock: return self._active_count > 0 + async def abort_all_requests(self) -> int: + """Signal every in-flight DFlash generation to stop. + + The process memory enforcer relies on this method at hard pressure. + DFlash does not use Scheduler request objects, so its per-generation + threading events are the authoritative abort handles. + """ + aborted = 0 + fallback = self._fallback_engine + if fallback is not None: + abort_fallback = getattr(fallback, "abort_all_requests", None) + if callable(abort_fallback): + result = abort_fallback() + if hasattr(result, "__await__"): + result = await result + if isinstance(result, (int, float)): + aborted += max(0, int(result)) + + with self._stop_events_lock: + stop_events = tuple(self._active_stop_events) + for stop_event in stop_events: + if not stop_event.is_set(): + stop_event.set() + aborted += 1 + return aborted + def get_stats(self) -> dict[str, Any]: return { "engine_type": "dflash", diff --git a/tests/test_dflash_engine.py b/tests/test_dflash_engine.py index 83bb512abb..752b1275ac 100644 --- a/tests/test_dflash_engine.py +++ b/tests/test_dflash_engine.py @@ -2,8 +2,9 @@ """Tests for DFlash engine integration.""" import json +import threading from types import SimpleNamespace -from unittest.mock import MagicMock +from unittest.mock import AsyncMock, MagicMock import pytest @@ -1530,6 +1531,35 @@ def test_reset_activity_tracking_clears_phantom_counts(self): assert engine.get_activity_snapshot()["active_requests"] == 0 assert engine.has_active_requests() is False + @pytest.mark.asyncio + async def test_memory_pressure_abort_signals_active_generations(self): + engine = self._engine() + first = threading.Event() + second = threading.Event() + engine._register_stop_event(first) + engine._register_stop_event(second) + + assert engine.has_active_requests() is True + assert await engine.abort_all_requests() == 2 + assert first.is_set() + assert second.is_set() + + # Repeated pressure polls must not count the same request twice. + assert await engine.abort_all_requests() == 0 + + engine._unregister_stop_event(first) + engine._unregister_stop_event(second) + assert engine.has_active_requests() is False + + @pytest.mark.asyncio + async def test_memory_pressure_abort_delegates_to_fallback(self): + engine = self._engine() + engine._fallback_engine = MagicMock() + engine._fallback_engine.abort_all_requests = AsyncMock(return_value=3) + + assert await engine.abort_all_requests() == 3 + engine._fallback_engine.abort_all_requests.assert_awaited_once() + class TestDFlashRuntimeCacheStats: """DFlash adapts its dflash-mlx runtime cache to the scheduler stats From 2f6aa9a2c157b3dc13e0b85caec24ef434ce69b3 Mon Sep 17 00:00:00 2001 From: Aaron Yang <16892776+contrapuntal@users.noreply.github.com> Date: Sun, 6 Sep 2026 04:46:59 -0700 Subject: [PATCH 087/132] fix(scheduler): refuse prefix reuse for unreconstructible cache classes (#3447) Probe model cache classes before paged prefix lookup and refuse layouts without a recognized reconstruction path. Recurse through composite cache members, preserve existing registered/sliceable handling, and retry cache-construction failures rather than memoizing them as safe. This blocks unregistered KV-like caches from silently becoming plain KVCache, including partial hits that bypass the existing post-reconstruction exact-hit check. Registered handler contents remain a separate trust boundary. Completion-time storage is unchanged. Future handler registration must invalidate or safely reject incompatible pre-registration entries. Include the scheduler regressions and realistic cache-construction fixtures, including the existing GDN walkback test. Targeted verification: 1069 passed, 3 deselected. Three MiniMax failures in the CI-style full suite also reproduce on unchanged upstream. Closes #3445. --- omlx/scheduler.py | 101 ++++++++++++++- tests/conftest.py | 12 ++ tests/test_prefix_cache_gdn_split.py | 6 + tests/test_scheduler.py | 177 +++++++++++++++++++++++++++ 4 files changed, 294 insertions(+), 2 deletions(-) diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 14b61f066f..c0bff355f1 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -8189,12 +8189,109 @@ def _should_defer_for_cache_freshness(self, request: Request) -> bool: ) return True + # Legacy class-name aliases explicitly supported by reconstruction. + _EXTRA_RECONSTRUCTIBLE_CACHE_TYPES = frozenset({"SizedArraysCache"}) + + def _prefix_reuse_supports_cache_class(self, class_name: str) -> bool: + """True when ``class_name`` has a recognized reconstruction path. + + Reconstruction dispatches on the stored ``type(cache).__name__`` through + ``CacheTypeRegistry``. Preserve existing handling for registered names + and explicitly supported sliceable classes. Registration is a trust + boundary, not proof that a handler preserves every field: handler-level + round-trip tests are still required. + + An *unregistered* class is the problem. ``detect_cache_type`` falls back + to structural sniffing, so any ``KVCache`` subclass looks like a plain + ``KVCache``, gets ``DefaultCacheHandler`` (``supports_block_slicing = + True``) and is rebuilt as a vanilla ``KVCache`` with its extra state + dropped. Only that case is refused here. + """ + if class_name in _KNOWN_SLICEABLE_CACHE_TYPES: + return True + if class_name in self._EXTRA_RECONSTRUCTIBLE_CACHE_TYPES: + return True + if HAS_CACHE_TYPE_HANDLERS and CacheTypeRegistry is not None: + return class_name in CacheTypeRegistry.list_known_class_names() + # Without the registry nothing beyond the plainly sliceable set can be + # rebuilt, so treat everything else as unsupported. + return False + + def _cache_layer_is_reconstructible(self, layer: Any) -> bool: + """Recursive per-layer form of :meth:`_prefix_reuse_supports_cache_class`.""" + if layer is None: + return True + # Test doubles carry no real cache contract. + if type(layer).__module__.startswith("unittest.mock"): + return True + sub_caches = getattr(layer, "caches", None) + if isinstance(sub_caches, (list, tuple)): + # CacheList itself round-trips, but only if every sub-cache does: + # its handler stores sub-class names and re-dispatches per name. + if not self._prefix_reuse_supports_cache_class(type(layer).__name__): + return False + return all(self._cache_layer_is_reconstructible(sub) for sub in sub_caches) + return self._prefix_reuse_supports_cache_class(type(layer).__name__) + + def _model_has_unreconstructible_cache(self) -> bool: + """True when ``model.make_cache()`` builds cache layers of a class the + paged prefix round trip silently downgrades. + + Unlimited-OCR's ``RingSlidingKVCache`` subclasses ``KVCache`` and is not + in the registry, so it is sniffed as a plain ``KVCache``, rebuilt as one, + and loses ``window_size`` / ``prefill_length`` / ``_ring_pos``. The model + then attends over an unbounded history, which can alter generation. + The pre-existing rotating guard cannot catch it: + it runs only for *exact* prefix hits and inspects the *already + reconstructed* cache, which is a plain ``KVCache`` by then. + + Probed once per scheduler and memoized. A probe that raises is **not** + memoized and refuses reuse for that request, so a transient failure can + never be recorded as "safe" and then silently reused. + """ + cached = getattr(self, "_unreconstructible_cache_model", None) + if cached is not None: + return cached + + try: + layers = make_prompt_cache(self.model) or [] + except Exception as e: + logger.warning( + "Could not probe model cache classes (%s: %s); refusing prefix cache " + "reuse for this request rather than risking a silent downgrade", + type(e).__name__, + e, + ) + logger.debug("Cache probe failure traceback:", exc_info=True) + return True + + result = False + for layer in layers: + if not self._cache_layer_is_reconstructible(layer): + logger.info( + "Prefix cache reuse disabled: model builds %s layers, which " + "have no cache-type handler and would be rebuilt as plain " + "KVCache, dropping their state", + type(layer).__name__, + ) + result = True + break + + self._unreconstructible_cache_model = result + return result + def _prepare_prefix_cache_for_request(self, request: Request) -> None: if request.request_id in self._prefix_cache_prepared: return - # Check prefix cache for cached KV state - if self.block_aware_cache is not None: + # Check prefix cache for cached KV state. Models whose cache layers do + # not survive reconstruction skip the lookup entirely and fall through + # to full prefill below — including on partial hits, which bypass the + # exact-hit guard further down. + if ( + self.block_aware_cache is not None + and not self._model_has_unreconstructible_cache() + ): # Use paged cache block_table, remaining = self.block_aware_cache.fetch_cache( request.request_id, diff --git a/tests/conftest.py b/tests/conftest.py index 8010b0df1f..377acb82dc 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -111,6 +111,18 @@ def parameters(self) -> Dict[str, Any]: """Return model parameters.""" return self._parameters + def make_cache(self) -> list: + """Build the per-layer prompt cache, like a real mlx-lm model. + + The scheduler probes this to decide whether a stored prefix can be + rebuilt faithfully, so the double has to answer it. A plain llama-style + model builds ``KVCache`` layers; tests that need another cache class + override this attribute. + """ + from mlx_lm.models.cache import KVCache + + return [KVCache() for _ in range(self.config.num_hidden_layers)] + @pytest.fixture def mock_tokenizer() -> MockTokenizer: diff --git a/tests/test_prefix_cache_gdn_split.py b/tests/test_prefix_cache_gdn_split.py index c16693e32d..7879ad3964 100644 --- a/tests/test_prefix_cache_gdn_split.py +++ b/tests/test_prefix_cache_gdn_split.py @@ -20,6 +20,11 @@ class _HybridModel: def __init__(self): self.layers = [MagicMock(), MagicMock()] + def make_cache(self): + from mlx_lm.models.cache import ArraysCache, KVCache + + return [KVCache(), ArraysCache(size=2)] + def _hybrid_extracted(token_count: int, recurrent_value: float): return [ @@ -618,6 +623,7 @@ def test_split_exact_prefix_fails_closed_before_placeholder_allocation(tmp_path) def test_scheduler_exact_split_hit_reprefills_only_last_block(): """Exact GDN hits walk back one block before reconstruction (N-1 safety).""" scheduler = Scheduler.__new__(Scheduler) + scheduler.model = _HybridModel() scheduler.config = SchedulerConfig( paged_cache_block_size=BLOCK_SIZE, gdn_ssd_split_enabled=True, diff --git a/tests/test_scheduler.py b/tests/test_scheduler.py index 7d91bc943c..0a215f7e97 100644 --- a/tests/test_scheduler.py +++ b/tests/test_scheduler.py @@ -611,6 +611,183 @@ def test_add_request_exact_cache_hit_rotating_forces_fallback( "req-rotating" ) + def test_partial_hit_refused_when_model_builds_unregistered_cache( + self, mock_model, mock_tokenizer + ): + """A model whose own make_cache() returns an *unregistered* cache class + must not reuse a paged prefix at all — not even a partial one. + + An unregistered ``KVCache`` subclass is sniffed structurally, handed the + default handler and rebuilt as a plain ``KVCache``, silently dropping its + window state (Unlimited-OCR's ``RingSlidingKVCache`` carries + window_size/prefill_length/_ring_pos). The pre-existing rotating guard + only covers *exact* hits and inspects the already-reconstructed cache, + so a partial hit slipped through and corrupted generation. + """ + from omlx.cache.paged_cache import BlockTable + + RingSlidingKVCache = type("RingSlidingKVCache", (), {}) + mock_model.make_cache = lambda: [RingSlidingKVCache()] + + scheduler = Scheduler(model=mock_model, tokenizer=mock_tokenizer) + scheduler.block_aware_cache = MagicMock() + scheduler.paged_cache_manager = MagicMock() + + # Partial hit: 2 of 4 tokens cached, so the exact-hit guard cannot fire. + block_table = BlockTable(request_id="req-ring", block_ids=[7], num_tokens=2) + scheduler.block_aware_cache.fetch_cache.return_value = (block_table, [43, 44]) + # Reconstruction hands back a plain KVCache — the ring class is lost. + scheduler.block_aware_cache.reconstruct_cache.return_value = [MagicMock()] + + request = Request( + request_id="req-ring", + prompt=[41, 42, 43, 44], + sampling_params=SamplingParams(max_tokens=16), + ) + + scheduler.add_request(request) + scheduler._prepare_prefix_cache_for_request(request) + + assert request.cached_tokens == 0 + assert request.remaining_tokens == [41, 42, 43, 44] + assert request.prompt_cache is None + scheduler.block_aware_cache.fetch_cache.assert_not_called() + + def test_plain_kvcache_model_still_uses_prefix_cache( + self, mock_model, mock_tokenizer + ): + """The guard must not disable prefix reuse for ordinary KVCache models.""" + from omlx.cache.paged_cache import BlockTable + + KVCache = type("KVCache", (), {}) + mock_model.make_cache = lambda: [KVCache()] + + scheduler = Scheduler(model=mock_model, tokenizer=mock_tokenizer) + scheduler.block_aware_cache = MagicMock() + scheduler.paged_cache_manager = MagicMock() + + block_table = BlockTable(request_id="req-plain", block_ids=[8], num_tokens=2) + scheduler.block_aware_cache.fetch_cache.return_value = (block_table, [53, 54]) + scheduler.block_aware_cache.reconstruct_cache.return_value = [MagicMock()] + + request = Request( + request_id="req-plain", + prompt=[51, 52, 53, 54], + sampling_params=SamplingParams(max_tokens=16), + ) + + scheduler.add_request(request) + scheduler._prepare_prefix_cache_for_request(request) + + scheduler.block_aware_cache.fetch_cache.assert_called_once() + assert request.cached_tokens == 2 + + @pytest.mark.parametrize( + "cache_class_name", + [ + # Registered: reconstruction re-dispatches on the stored class name + # and the boundary-snapshot path preserves the extra state. + "RotatingKVCache", + "ArraysCache", + "MiniMaxM3KVCache", + # Plainly sliceable, round-trips by block slicing. + "ChunkedKVCache", + "TurboQuantKVCache", + ], + ) + def test_supported_non_plain_cache_models_keep_prefix_cache( + self, mock_model, mock_tokenizer, cache_class_name + ): + """The guard must only refuse classes the round trip cannot rebuild. + + Rotating/arrays/MiniMax layers have registry handlers and chunked and + TurboQuant layers are block-sliceable, so all of them keep prefix reuse. + Refusing them would cost a full re-prefill on every request for no + correctness gain. + """ + from omlx.cache.paged_cache import BlockTable + + mock_model.make_cache = lambda: [type(cache_class_name, (), {})()] + + scheduler = Scheduler(model=mock_model, tokenizer=mock_tokenizer) + scheduler.block_aware_cache = MagicMock() + scheduler.paged_cache_manager = MagicMock() + + block_table = BlockTable( + request_id="req-supported", block_ids=[11], num_tokens=2 + ) + scheduler.block_aware_cache.fetch_cache.return_value = (block_table, [63, 64]) + scheduler.block_aware_cache.reconstruct_cache.return_value = [MagicMock()] + + request = Request( + request_id="req-supported", + prompt=[61, 62, 63, 64], + sampling_params=SamplingParams(max_tokens=16), + ) + + scheduler.add_request(request) + scheduler._prepare_prefix_cache_for_request(request) + + assert scheduler._model_has_unreconstructible_cache() is False + scheduler.block_aware_cache.fetch_cache.assert_called_once() + + def test_cache_list_refused_when_a_sub_cache_is_unregistered( + self, mock_model, mock_tokenizer + ): + """CacheList round-trips per sub-cache, so one unknown sub-cache is fatal.""" + cache_list = type( + "CacheList", + (), + {"caches": (type("KVCache", (), {})(), type("RingSlidingKVCache", (), {})())}, + ) + mock_model.make_cache = lambda: [cache_list()] + + scheduler = Scheduler(model=mock_model, tokenizer=mock_tokenizer) + scheduler.block_aware_cache = MagicMock() + + assert scheduler._model_has_unreconstructible_cache() is True + + def test_cache_list_allowed_when_every_sub_cache_is_supported( + self, mock_model, mock_tokenizer + ): + """A CacheList of known sub-caches keeps prefix reuse.""" + cache_list = type( + "CacheList", + (), + {"caches": (type("KVCache", (), {})(), type("RotatingKVCache", (), {})())}, + ) + mock_model.make_cache = lambda: [cache_list()] + + scheduler = Scheduler(model=mock_model, tokenizer=mock_tokenizer) + scheduler.block_aware_cache = MagicMock() + + assert scheduler._model_has_unreconstructible_cache() is False + + def test_probe_failure_refuses_reuse_and_is_not_memoized( + self, mock_model, mock_tokenizer + ): + """A failed probe must fail closed and stay retryable. + + Memoizing a transient failure as "safe" would restore exactly the silent + downgrade this guard exists to prevent, so the failure path refuses reuse + and records nothing. + """ + + def _boom(): + raise RuntimeError("cannot build cache") + + mock_model.make_cache = _boom + + scheduler = Scheduler(model=mock_model, tokenizer=mock_tokenizer) + scheduler.block_aware_cache = MagicMock() + + assert scheduler._model_has_unreconstructible_cache() is True + assert getattr(scheduler, "_unreconstructible_cache_model", None) is None + + # Once the underlying cause clears, the model is probed again. + mock_model.make_cache = lambda: [type("KVCache", (), {})()] + assert scheduler._model_has_unreconstructible_cache() is False + def test_add_request_under_pressure_skips_hot_cache_preload_and_promotion( self, mock_model, mock_tokenizer ): From 455090aa334d4366442eaba09c5239232cbd09e8 Mon Sep 17 00:00:00 2001 From: jundot Date: Sun, 6 Sep 2026 20:47:45 +0900 Subject: [PATCH 088/132] fix: clean up DFlash cancellations and report memory aborts (#3424) --- omlx/engine/dflash.py | 34 ++++++++----- tests/test_dflash_engine.py | 99 +++++++++++++++++++++++++++++++++++++ 2 files changed, 120 insertions(+), 13 deletions(-) diff --git a/omlx/engine/dflash.py b/omlx/engine/dflash.py index abfac40dd1..8da9bb5f3a 100644 --- a/omlx/engine/dflash.py +++ b/omlx/engine/dflash.py @@ -28,6 +28,7 @@ from ..api.tool_calling import convert_tools_for_template from ..api.utils import clean_special_tokens, detect_and_strip_partial from ..cache.observability import CacheRateTracker +from ..exceptions import PrefillMemoryAbortedError from ..memory_monitor import ( MemoryMonitor, raise_if_prefill_exceeds, @@ -335,7 +336,6 @@ def __init__( self._tokenizer_obj = None self._executor_tokenizer = None self._loaded = False - self._active_request = False # DFlash runs outside Scheduler, so memory-pressure aborts cannot use # EngineCore's request registry. Keep the stop events for every # submitted generation instead; the process memory enforcer calls @@ -1395,8 +1395,6 @@ def _run_generate_streaming( queue.put(("", [], True, {"aborted": stop_event.is_set()})), loop, ) - self._active_request = False - self._unregister_stop_event(stop_event) def _tokenize_prompt(self, prompt: str | list[int]) -> list[int]: """Return prompt IDs without re-tokenizing an already-tokenized prompt.""" @@ -1476,7 +1474,6 @@ async def generate( from ..engine_core import get_mlx_executor - loop = asyncio.get_running_loop() stop_event = threading.Event() # Admin visibility: DFlash bypasses the scheduler, so the Active # Models card reads this activity instead of a scheduler snapshot. @@ -1556,16 +1553,17 @@ def _run(): except Exception as exc: logger.debug(f"event_iter.close() raised: {exc}") self._end_runtime_cache_request(cache_manager) - self._active_request = False - self._unregister_stop_event(stop_event) - self._active_request = True self._register_stop_event(stop_event) try: - future = loop.run_in_executor(get_mlx_executor(), _run) + future = get_mlx_executor().submit(_run) except Exception: self._unregister_stop_event(stop_event) + self._end_activity(activity_id) raise + # Use the executor future: asyncio cancellation can precede worker exit. + future.add_done_callback(lambda _: self._unregister_stop_event(stop_event)) + future = asyncio.wrap_future(future) try: try: ( @@ -1592,6 +1590,11 @@ def _run(): finally: self._end_activity(activity_id) + if stop_event.is_set(): + raise PrefillMemoryAbortedError( + "Request aborted: process memory limit exceeded" + ) + if parser_session is not None: # Parser already converted protocol markers to ... # and stripped channel marker tokens, so just join the visible @@ -1730,11 +1733,9 @@ async def stream_generate( # Admin visibility: DFlash bypasses the scheduler, so the Active # Models card reads this activity instead of a scheduler snapshot. activity_id = self._begin_activity("generate", detail="generating") - self._active_request = True self._register_stop_event(stop_event) try: - future = loop.run_in_executor( - get_mlx_executor(), + future = get_mlx_executor().submit( self._run_generate_streaming, prompt_tokens, max_tokens, @@ -1752,7 +1753,11 @@ async def stream_generate( ) except Exception: self._unregister_stop_event(stop_event) + self._end_activity(activity_id) raise + # Use the executor future: asyncio cancellation can precede worker exit. + future.add_done_callback(lambda _: self._unregister_stop_event(stop_event)) + future = asyncio.wrap_future(future) total_text = "" total_completion = 0 @@ -1762,6 +1767,11 @@ async def stream_generate( while True: new_text, new_tokens, finished, metrics = await queue.get() + if metrics and metrics.get("aborted"): + raise PrefillMemoryAbortedError( + "Request aborted: process memory limit exceeded" + ) + if think_prefix_pending and new_text: new_text = self._think_prefix_text() + new_text think_prefix_pending = False @@ -1999,8 +2009,6 @@ def has_active_requests(self) -> bool: and self._fallback_engine.has_active_requests() ): return True - if self._active_request: - return True with self._stop_events_lock: if self._active_stop_events: return True diff --git a/tests/test_dflash_engine.py b/tests/test_dflash_engine.py index 752b1275ac..eb8a027517 100644 --- a/tests/test_dflash_engine.py +++ b/tests/test_dflash_engine.py @@ -1,8 +1,11 @@ # SPDX-License-Identifier: Apache-2.0 """Tests for DFlash engine integration.""" +import asyncio import json import threading +from concurrent.futures import ThreadPoolExecutor +from contextlib import suppress from types import SimpleNamespace from unittest.mock import AsyncMock, MagicMock @@ -2000,3 +2003,99 @@ def test_empty_generation_is_dropped(self): ) ) assert engine.get_speculation_stats() is None + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streaming", [False, True]) +@pytest.mark.parametrize( + "scenario", ["complete", "abort", "cancel_queued", "cancel_running"] +) +async def test_generation_abort_lifetime(monkeypatch, streaming, scenario): + from dflash_mlx.engine.events import TokenEvent + + from omlx.engine.dflash import DFlashEngine + from omlx.exceptions import PrefillMemoryAbortedError + from omlx.process_memory_enforcer import ProcessMemoryEnforcer + + started = threading.Event() + release = threading.Event() + closed = threading.Event() + engine = DFlashEngine(model_name="test-model", draft_model_path="test-draft") + engine._loaded = True + engine._tokenizer_obj = SimpleNamespace(decode=lambda *args, **kwargs: "hello") + engine._executor_tokenizer = engine._tokenizer_obj + + def events(**kwargs): + def iterate(): + try: + started.set() + assert release.wait(30) + yield TokenEvent(42, 1, 1.0, 1) + finally: + closed.set() + + return iterate(), None, set() + + engine._stream_dflash_events = events + monkeypatch.setattr( + "omlx.engine.dflash.create_streaming_detokenizer", lambda *args, **kwargs: None + ) + + async def generate(): + if streaming: + return [output async for output in engine.stream_generate([1])][-1] + return await engine.generate([1]) + + with ThreadPoolExecutor(max_workers=1) as executor: + monkeypatch.setattr("omlx.engine_core.get_mlx_executor", lambda: executor) + blocker = None + if scenario == "cancel_queued": + blocker = executor.submit(release.wait, 30) + task = asyncio.create_task(generate()) + try: + async with asyncio.timeout(5): + while not engine._active_stop_events: + await asyncio.sleep(0.01) + if blocker is None: + while not started.is_set(): + await asyncio.sleep(0.01) + if scenario.startswith("cancel"): + task.cancel() + # Exercise the real 10-second drain timeout, including its + # cancellation of the asyncio wrapper around executor work. + with pytest.raises(asyncio.CancelledError): + await task + assert engine.has_active_requests() is (blocker is None) + else: + if scenario == "abort": + enforcer = object.__new__(ProcessMemoryEnforcer) + enforcer._engine_pool = SimpleNamespace( + _entries={"test": SimpleNamespace(engine=engine)} + ) + assert ( + await enforcer._abort_loaded_requests_for_memory_emergency() + == 1 + ) + assert ( + await enforcer._abort_loaded_requests_for_memory_emergency() + == 0 + ) + assert engine.has_active_requests() + release.set() + if scenario == "abort": + with pytest.raises(PrefillMemoryAbortedError): + await task + else: + assert (await task).finish_reason == "stop" + finally: + release.set() + if not task.done(): + task.cancel() + with suppress(asyncio.CancelledError): + await task + # A barrier proves that cancelled running work has actually exited. + await asyncio.wrap_future(executor.submit(lambda: None)) + assert not engine.has_active_requests() + assert not engine._active_stop_events + assert closed.is_set() is (blocker is None) + assert engine.get_activity_snapshot()["active_requests"] == 0 From b2cb698ffc5989bca92ac9930f6aad2d9c34040b Mon Sep 17 00:00:00 2001 From: jundot Date: Sun, 6 Sep 2026 20:53:56 +0900 Subject: [PATCH 089/132] fix: skip storage for unsupported cache layouts (#3445) --- omlx/scheduler.py | 67 +++++++------------ tests/test_scheduler.py | 62 ++++++++++------- tests/test_scheduler_prompt_boundary_store.py | 16 ++++- 3 files changed, 77 insertions(+), 68 deletions(-) diff --git a/omlx/scheduler.py b/omlx/scheduler.py index c0bff355f1..58c7052332 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -6380,6 +6380,9 @@ def _on_prefill_boundary_snapshot( ``BatchGenerator`` yet and the uid mapping does not exist — routing through it dropped every snapshot silently (#TBD). """ + if self._model_has_unreconstructible_cache(): + return + block_size = self.config.paged_cache_block_size self._boundary_snapshot_diagnostics.record( "capture_attempt", @@ -6817,6 +6820,9 @@ def record_skip(reason: str) -> None: def _maybe_capture_boundary_snapshot(self, request: Request, uid: int) -> None: """Capture cache snapshot exactly at block boundaries for safe reuse.""" + if self._model_has_unreconstructible_cache(): + return + if self.block_aware_cache is None: return @@ -8193,20 +8199,7 @@ def _should_defer_for_cache_freshness(self, request: Request) -> bool: _EXTRA_RECONSTRUCTIBLE_CACHE_TYPES = frozenset({"SizedArraysCache"}) def _prefix_reuse_supports_cache_class(self, class_name: str) -> bool: - """True when ``class_name`` has a recognized reconstruction path. - - Reconstruction dispatches on the stored ``type(cache).__name__`` through - ``CacheTypeRegistry``. Preserve existing handling for registered names - and explicitly supported sliceable classes. Registration is a trust - boundary, not proof that a handler preserves every field: handler-level - round-trip tests are still required. - - An *unregistered* class is the problem. ``detect_cache_type`` falls back - to structural sniffing, so any ``KVCache`` subclass looks like a plain - ``KVCache``, gets ``DefaultCacheHandler`` (``supports_block_slicing = - True``) and is rebuilt as a vanilla ``KVCache`` with its extra state - dropped. Only that case is refused here. - """ + """Check explicit reconstruction support; structural KV detection is lossy.""" if class_name in _KNOWN_SLICEABLE_CACHE_TYPES: return True if class_name in self._EXTRA_RECONSTRUCTIBLE_CACHE_TYPES: @@ -8221,9 +8214,6 @@ def _cache_layer_is_reconstructible(self, layer: Any) -> bool: """Recursive per-layer form of :meth:`_prefix_reuse_supports_cache_class`.""" if layer is None: return True - # Test doubles carry no real cache contract. - if type(layer).__module__.startswith("unittest.mock"): - return True sub_caches = getattr(layer, "caches", None) if isinstance(sub_caches, (list, tuple)): # CacheList itself round-trips, but only if every sub-cache does: @@ -8234,20 +8224,9 @@ def _cache_layer_is_reconstructible(self, layer: Any) -> bool: return self._prefix_reuse_supports_cache_class(type(layer).__name__) def _model_has_unreconstructible_cache(self) -> bool: - """True when ``model.make_cache()`` builds cache layers of a class the - paged prefix round trip silently downgrades. - - Unlimited-OCR's ``RingSlidingKVCache`` subclasses ``KVCache`` and is not - in the registry, so it is sniffed as a plain ``KVCache``, rebuilt as one, - and loses ``window_size`` / ``prefill_length`` / ``_ring_pos``. The model - then attends over an unbounded history, which can alter generation. - The pre-existing rotating guard cannot catch it: - it runs only for *exact* prefix hits and inspects the *already - reconstructed* cache, which is a plain ``KVCache`` by then. + """Refuse paged storage and reuse for unsupported cache layouts. - Probed once per scheduler and memoized. A probe that raises is **not** - memoized and refuses reuse for that request, so a transient failure can - never be recorded as "safe" and then silently reused. + Memoize successful probes only; retry cache-construction failures. """ cached = getattr(self, "_unreconstructible_cache_model", None) if cached is not None: @@ -8258,7 +8237,7 @@ def _model_has_unreconstructible_cache(self) -> bool: except Exception as e: logger.warning( "Could not probe model cache classes (%s: %s); refusing prefix cache " - "reuse for this request rather than risking a silent downgrade", + "storage and reuse for this request", type(e).__name__, e, ) @@ -8269,9 +8248,7 @@ def _model_has_unreconstructible_cache(self) -> bool: for layer in layers: if not self._cache_layer_is_reconstructible(layer): logger.info( - "Prefix cache reuse disabled: model builds %s layers, which " - "have no cache-type handler and would be rebuilt as plain " - "KVCache, dropping their state", + "Prefix cache storage and reuse disabled: unsupported %s layers", type(layer).__name__, ) result = True @@ -8284,10 +8261,7 @@ def _prepare_prefix_cache_for_request(self, request: Request) -> None: if request.request_id in self._prefix_cache_prepared: return - # Check prefix cache for cached KV state. Models whose cache layers do - # not survive reconstruction skip the lookup entirely and fall through - # to full prefill below — including on partial hits, which bypass the - # exact-hit guard further down. + # Check support before lookup, including partial prefix hits. if ( self.block_aware_cache is not None and not self._model_has_unreconstructible_cache() @@ -11182,9 +11156,15 @@ def _process_batch_responses( raw_cache = getattr(response, "prompt_cache", None) if raw_cache is not None: try: - # SpecPrefill: sparse KV data can't be stored in - # paged cache (hash mismatch with full token IDs). - if request.specprefill_indices is not None: + # Sparse or unsupported layouts cannot round-trip through + # paged storage. Skip tensor extraction as well as writing. + if ( + request.specprefill_indices is not None + or ( + self.block_aware_cache is not None + and self._model_has_unreconstructible_cache() + ) + ): raw_cache = None # For paged cache, extract actual tensor states @@ -11297,7 +11277,10 @@ def _cleanup_finished(self, finished_ids: set[str]) -> None: # prep, no host memcpy, no SSD write. They still take # the block leak-guard branch below so their paged # blocks are released for eviction. - skip_store = getattr(request, "skip_cache_store", False) + skip_store = ( + getattr(request, "skip_cache_store", False) + or self._model_has_unreconstructible_cache() + ) if skip_store or ( hasattr(request, "_extracted_cache") and request._extracted_cache is not None diff --git a/tests/test_scheduler.py b/tests/test_scheduler.py index 0a215f7e97..6350663b6e 100644 --- a/tests/test_scheduler.py +++ b/tests/test_scheduler.py @@ -614,16 +614,7 @@ def test_add_request_exact_cache_hit_rotating_forces_fallback( def test_partial_hit_refused_when_model_builds_unregistered_cache( self, mock_model, mock_tokenizer ): - """A model whose own make_cache() returns an *unregistered* cache class - must not reuse a paged prefix at all — not even a partial one. - - An unregistered ``KVCache`` subclass is sniffed structurally, handed the - default handler and rebuilt as a plain ``KVCache``, silently dropping its - window state (Unlimited-OCR's ``RingSlidingKVCache`` carries - window_size/prefill_length/_ring_pos). The pre-existing rotating guard - only covers *exact* hits and inspects the already-reconstructed cache, - so a partial hit slipped through and corrupted generation. - """ + """Reject unknown cache classes before a partial hit loses their state.""" from omlx.cache.paged_cache import BlockTable RingSlidingKVCache = type("RingSlidingKVCache", (), {}) @@ -698,13 +689,7 @@ def test_plain_kvcache_model_still_uses_prefix_cache( def test_supported_non_plain_cache_models_keep_prefix_cache( self, mock_model, mock_tokenizer, cache_class_name ): - """The guard must only refuse classes the round trip cannot rebuild. - - Rotating/arrays/MiniMax layers have registry handlers and chunked and - TurboQuant layers are block-sliceable, so all of them keep prefix reuse. - Refusing them would cost a full re-prefill on every request for no - correctness gain. - """ + """Known non-plain cache classes must retain prefix reuse.""" from omlx.cache.paged_cache import BlockTable mock_model.make_cache = lambda: [type(cache_class_name, (), {})()] @@ -766,12 +751,7 @@ def test_cache_list_allowed_when_every_sub_cache_is_supported( def test_probe_failure_refuses_reuse_and_is_not_memoized( self, mock_model, mock_tokenizer ): - """A failed probe must fail closed and stay retryable. - - Memoizing a transient failure as "safe" would restore exactly the silent - downgrade this guard exists to prevent, so the failure path refuses reuse - and records nothing. - """ + """Refuse reuse on probe failure and retry after recovery.""" def _boom(): raise RuntimeError("cannot build cache") @@ -6982,3 +6962,39 @@ def test_no_make_cache_defaults_to_0(self, mock_model, mock_tokenizer): model=mock_model, tokenizer=mock_tokenizer, config=SchedulerConfig() ) assert scheduler._decode_eval_kv_cache_interval == 0 + + +@pytest.mark.parametrize("phase", ["prefill", "decode"]) +def test_unsupported_cache_skips_boundary_storage(mock_model, mock_tokenizer, phase): + from mlx_lm.models.cache import KVCache + + class UnknownKVCache(KVCache): + pass + + mock_model.make_cache = lambda: [UnknownKVCache()] + scheduler = Scheduler( + mock_model, mock_tokenizer, SchedulerConfig(paged_cache_block_size=4) + ) + scheduler.block_aware_cache = MagicMock() + scheduler._boundary_snapshot_store = MagicMock() + request = Request("unsupported", [1, 2, 3, 4], SamplingParams()) + scheduler.add_request(request) + with ( + patch.object(scheduler, "_extract_boundary_snapshot") as extract, + patch.object(scheduler, "_prefill_snapshot_value") as materialize, + ): + if phase == "prefill": + scheduler._on_prefill_boundary_snapshot( + request.request_id, mock_model.make_cache(), 4 + ) + else: + scheduler._maybe_capture_boundary_snapshot(request, 0) + extract.assert_not_called() + materialize.assert_not_called() + assert not scheduler._boundary_snapshot_store.mock_calls + assert request.request_id not in scheduler._boundary_cache_snapshots + + +def test_mock_cache_has_no_implicit_reconstruction_support(mock_model, mock_tokenizer): + scheduler = Scheduler(mock_model, mock_tokenizer) + assert not scheduler._cache_layer_is_reconstructible(MagicMock()) diff --git a/tests/test_scheduler_prompt_boundary_store.py b/tests/test_scheduler_prompt_boundary_store.py index d0c2bcff76..5cf608f7cc 100644 --- a/tests/test_scheduler_prompt_boundary_store.py +++ b/tests/test_scheduler_prompt_boundary_store.py @@ -4,6 +4,8 @@ from types import SimpleNamespace from unittest.mock import MagicMock, patch +import pytest + from omlx.request import Request, SamplingParams from omlx.scheduler import Scheduler, SchedulerConfig @@ -245,17 +247,25 @@ def test_cleanup_finished_stores_prompt_boundary_without_extracted_cache( assert kwargs["model_cache_config"] == "boundary-config" +@pytest.mark.parametrize("skip_reason", ["request", "unsupported", "probe_failure"]) +@pytest.mark.parametrize("has_payload", [False, True]) def test_cleanup_finished_skip_cache_store_takes_leak_guard_branch( mock_model, mock_tokenizer, + skip_reason, + has_payload, ): - """A skip_cache_store request must not prep or submit a store, but its + """A skipped store must not prepare a payload, but its blocks still go through the leak-guard release path.""" scheduler = Scheduler( model=mock_model, tokenizer=mock_tokenizer, config=SchedulerConfig(paged_cache_block_size=4), ) + if skip_reason == "unsupported": + mock_model.make_cache = lambda: [type("UnknownKVCache", (), {})()] + elif skip_reason == "probe_failure": + mock_model.make_cache = MagicMock(side_effect=RuntimeError("probe failed")) scheduler.block_aware_cache = MagicMock() scheduler.paged_cache_manager = None @@ -263,12 +273,12 @@ def test_cleanup_finished_skip_cache_store_takes_leak_guard_branch( request_id="req-ctx-probe", prompt="prompt", sampling_params=SamplingParams(), - skip_cache_store=True, + skip_cache_store=skip_reason == "request", ) request.prompt_token_ids = list(range(10)) request.num_prompt_tokens = 10 request.output_token_ids = [100] - request._extracted_cache = ["kv-live"] + request._extracted_cache = ["kv-live"] if has_payload else None scheduler.running[request.request_id] = request scheduler.requests[request.request_id] = request From 4e6eba50744efcec3acf0eeb51e023abc6c47054 Mon Sep 17 00:00:00 2001 From: andyoneal Date: Sun, 6 Sep 2026 07:09:17 -0500 Subject: [PATCH 090/132] fix(ane): clear the per-module state caches when releasing ANE banks (#3340) `release_qwen35_ane_prefill` latches each sliced module and drops its state attributes, then relies on the native model freeing its program and mapped weight blob once the last reference dies. `_compile_pair` and `_compile_gdn` also cache those states per module, in `_omlx_ane_prefill_cache` and `_omlx_ane_gdn_cache`, and the release cleared neither -- so a second reference always survived and the release freed nothing. `engine_pool` brackets the call with `get_phys_footprint()` and a `gc.collect()` to reclaim that memory, which made this a no-op on the one path that exists to hand it back. Cleared unconditionally rather than alongside a live state: an entry left over from an earlier slice is exactly the mapped bank the call is being asked to free, and a subsequent enable recompiles instead of reusing it. A module whose cache holds only such a leftover is not counted in `modules_released`, so the shed marker and counter reset stay tied to modules that were actually serving. No `_COMPILE_LOCK` is needed -- compiles and this release both run on the engine's single-worker MLX executor (`engine_core.py`, `max_workers=1`), so a concurrent compile cannot observe the cache while it is being cleared. The tests hold a weak reference to each native handle and assert it has been collected once the release returns, so dropping this change leaves them failing on that assertion rather than on the cache contents. The caches are also unbounded: an enable at a new chunk width or fraction leaves the previous entry behind. No current path reaches that, since those settings enter the engine runtime signature and changing one reloads the engine, taking the caches with it. Bounding the cache is left for a separate change. Co-authored-by: Claude Opus 5 --- omlx/patches/qwen35_ane_prefill.py | 16 ++++++++-- tests/test_qwen35_ane_prefill.py | 50 ++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 2 deletions(-) diff --git a/omlx/patches/qwen35_ane_prefill.py b/omlx/patches/qwen35_ane_prefill.py index 1031405c4f..2939f9ef5a 100644 --- a/omlx/patches/qwen35_ane_prefill.py +++ b/omlx/patches/qwen35_ane_prefill.py @@ -3562,8 +3562,9 @@ def release_qwen35_ane_prefill(model: Any) -> tuple[int, int]: prefill needs back once the KV cache has grown into the guard's sizing target. Latches every sliced module through the existing per-module failure flags first (so the dispatch sites fall back to stock GPU compute - and never lazily recompile), then drops the state references; the native - models free their programs and mapped blobs when the last reference dies. + and never lazily recompile), then drops the state references and clears the + per-module state caches that hold the same objects; the native models free + their programs and mapped blobs when the last reference dies. Idempotent, and scoped to this engine instance: the next load of the model rebuilds the banks from its settings. @@ -3587,6 +3588,17 @@ def release_qwen35_ane_prefill(model: Any) -> tuple[int, int]: setattr(module, failed_attr, True) setattr(module, state_attr, None) modules_released += 1 + # _compile_pair and _compile_gdn cache their state per module, so + # dropping the attributes above frees nothing while those stay + # populated. Cleared unconditionally rather than alongside a live + # state: an entry left over from an earlier slice is exactly the + # mapped bank this call exists to hand back. No _COMPILE_LOCK needed + # -- compiles and this release both run on the engine's single-worker + # MLX executor, so they are already serialized. + for cache_attr in ("_omlx_ane_prefill_cache", "_omlx_ane_gdn_cache"): + cache = getattr(module, cache_attr, None) + if cache: + cache.clear() if modules_released: # Zero (not delete) the status counters and set the shed marker: # attempted=True/configured=False alone is indistinguishable from a diff --git a/tests/test_qwen35_ane_prefill.py b/tests/test_qwen35_ane_prefill.py index d3f8bd8ee9..9cbbee33c2 100644 --- a/tests/test_qwen35_ane_prefill.py +++ b/tests/test_qwen35_ane_prefill.py @@ -3248,6 +3248,56 @@ def test_release_latches_modules_drops_states_and_zeroes_counters(): assert status["resident_programs"] == 0 +def test_release_clears_the_state_cache_that_pins_the_same_states(): + import gc + model = _ReleasableModel() + mlp_handle = _NativeHandle() + gdn_handle = _NativeHandle() + mlp_ref = weakref.ref(mlp_handle) + gdn_ref = weakref.ref(gdn_handle) + mlp_state = SimpleNamespace(model=mlp_handle) + gdn_state = SimpleNamespace(model=gdn_handle) + model.mlp._omlx_ane_prefill_state = mlp_state + # _compile_pair and _compile_gdn cache the state per module, so this is a + # second reference to everything the release drops. + model.mlp._omlx_ane_prefill_cache = {("mlp-key",): mlp_state} + model.gdn._omlx_ane_gdn_state = gdn_state + model.gdn._omlx_ane_gdn_cache = {("gdn-key",): gdn_state} + + released, _ = ane_patch.release_qwen35_ane_prefill(model) + del mlp_state, gdn_state, mlp_handle, gdn_handle + gc.collect() + + assert released == 2 + # Asserted before the cache contents: left populated, the cache keeps the + # mapped bank alive and the release hands back nothing, and that is the + # failure worth reading when this regresses. + assert mlp_ref() is None + assert gdn_ref() is None + assert model.mlp._omlx_ane_prefill_cache == {} + assert model.gdn._omlx_ane_gdn_cache == {} + + +def test_release_clears_a_stale_state_cache_entry(): + import gc + model = _ReleasableModel() + handle = _NativeHandle() + ref = weakref.ref(handle) + # An entry can outlive its state attribute -- an earlier release, or a + # slice replaced at a different chunk width. + model.mlp._omlx_ane_prefill_cache = {("stale",): SimpleNamespace(model=handle)} + + released, _ = ane_patch.release_qwen35_ane_prefill(model) + del handle + gc.collect() + + # Nothing to latch, so nothing counts as released -- but the bank the entry + # pinned still has to be handed back. + assert released == 0 + assert ref() is None + assert model.mlp._omlx_ane_prefill_cache == {} + + def test_release_is_idempotent_and_noop_without_slices(): model = _ReleasableModel() assert ane_patch.release_qwen35_ane_prefill(model) == (0, 0) From 034ceeec25ec1a9731a007d5ed24bbbbb7ffa130 Mon Sep 17 00:00:00 2001 From: Nikita Aleksandrov Date: Sun, 6 Sep 2026 15:09:29 +0300 Subject: [PATCH 091/132] fix(memory): refresh ANE prefill transient reserve after bank compile (#3364) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Problem #2841: with ANE prefill enabled, the compiled slices hold fixed-shape fp16 I/O surfaces that the first long prompt dirties on top of the KV+SDPA peak. `dcb317fe` priced those surfaces through an `ane_prefill_transient_bytes` term passed to `set_model_info`. That term is snapshotted **at scheduler init**, but on the VLM path the ANE banks are compiled **after** the scheduler is initialized — `VLMBatchedEngine.start()` runs `enable_qwen35_ane_prefill` only after `engine.start()` has constructed the scheduler. The load-time read therefore returns 0 and the reserve never engages. Production capture (v0.6.4, ANE prefill enabled, Qwen3.8-27B-oQ4e-mtp): ``` qwen35_ane_prefill - Warmed 224 ANE procedures in 2.0s at load engine_pool - Loaded model: Qwen3.8-27B-oQ4e-mtp (actual: 28.49GB, local estimate: 16.60GB) scheduler - [guard:external] admission terms: current=32.41GB predicted_transient=3.87GB observed_max_bytes=0.00GB ane_prefill_transient_bytes=0.00GB context_benchmark - ERROR - Not enough memory to prefill even 4,096 tokens on this machine ``` 224 procedures are warm and the banks are resident (~11.9 GB over the GPU-only footprint), yet the admission breakdown prints `ane_prefill_transient_bytes=0.00GB` and the model cannot prefill even 4,096 tokens. This matches the post-`dcb317fe` report on #2841 ("still seeing the abort, disabling ANE prefill fixes it"). The LM path is unaffected (its compile runs before the scheduler is created); the VLM path is the one that loads Qwen multimodal checkpoints. ## Change - **`MemoryMonitor.set_ane_prefill_transient_bytes(value)`**: idempotent setter, clamps negative to 0. - **`BatchedEngine.start()` / `VLMBatchedEngine.start()`**: refresh the reserve immediately after `enable_qwen35_ane_prefill` compiles the banks, computed from the live model dims via the existing `ane_prefill_transient_bytes(model)`. The release rung already zeroes it through `clear_ane_prefill_transient()` (#3103), so the term is non-zero exactly while the banks are resident. ## Verification - New unit test: reserve defaults to 0, the setter raises it, `estimate_prefill_peak_bytes` includes it, clear drops it, negative input clamps. `tests/test_memory_monitor.py` + `tests/test_qwen35_ane_prefill.py`: **216 passed**. Broader: `test_scheduler_prefill_memory_guard.py` + `test_memory_monitor_vlm_config.py` + `test_batched_engine.py`: **104 passed**. - ANE compiles and engages on a source build (224 procedures warmed). With ANE enabled, the long-context benchmark now reaches the bank-release rung and completes 65,536 tokens where the v0.6.4 capture above rejected at 4,096 — the full before/after ladder trace is in the eviction-escalation PR. --- omlx/engine/batched.py | 10 ++++++++++ omlx/engine/vlm.py | 12 ++++++++++++ omlx/memory_monitor.py | 12 ++++++++++++ tests/test_memory_monitor.py | 27 +++++++++++++++++++++++++++ 4 files changed, 61 insertions(+) diff --git a/omlx/engine/batched.py b/omlx/engine/batched.py index 4fc7bfbd1a..37e8b9ea4c 100644 --- a/omlx/engine/batched.py +++ b/omlx/engine/batched.py @@ -580,6 +580,7 @@ def _enable_ane_prefill(): scheduler = self._engine.engine.scheduler if ane_prefill_sequence_length: from ..patches.qwen35_ane_prefill import ( + ane_prefill_transient_bytes, configure_qwen35_ane_prefill_scheduler, ) @@ -587,6 +588,15 @@ def _enable_ane_prefill(): scheduler, ane_prefill_sequence_length, ) + # Price the compiled ANE I/O surfaces explicitly: a later + # _set_model_info_for_monitor() defaults the term to zero + # unless re-derived, and the monitor must hold the real + # reservation while the banks exist. + monitor = getattr(scheduler, "memory_monitor", None) + if monitor is not None: + monitor.set_ane_prefill_transient_bytes( + ane_prefill_transient_bytes(self._model) + ) if self._model_settings is not None: tq_enabled = getattr(self._model_settings, "turboquant_kv_enabled", False) if tq_enabled: diff --git a/omlx/engine/vlm.py b/omlx/engine/vlm.py index a8682b6a44..bfda9f6288 100644 --- a/omlx/engine/vlm.py +++ b/omlx/engine/vlm.py @@ -2129,6 +2129,18 @@ def _enable_ane_prefill(): scheduler, requested_ane_sequence_length, ) + # The scheduler snapshotted model info before these + # banks existed; price the compiled I/O surfaces now so + # admission charges them while the banks are resident. + from ..patches.qwen35_ane_prefill import ( + ane_prefill_transient_bytes, + ) + + monitor = getattr(scheduler, "memory_monitor", None) + if monitor is not None: + monitor.set_ane_prefill_transient_bytes( + ane_prefill_transient_bytes(self._vlm_model) + ) except Exception: logger.warning("Qwen ANE prefill not enabled", exc_info=True) diff --git a/omlx/memory_monitor.py b/omlx/memory_monitor.py index feed9fa25a..4690f66f8e 100644 --- a/omlx/memory_monitor.py +++ b/omlx/memory_monitor.py @@ -426,6 +426,18 @@ def clear_ane_prefill_transient(self) -> None: """ self._ane_prefill_transient_bytes = 0 + def set_ane_prefill_transient_bytes(self, value: int) -> None: + """Refresh the ANE prefill I/O-surface reservation. + + ANE banks compile after the scheduler snapshots model info (the + engine builds them once the scheduler exists), so the load-time + value can read 0 while banks are being created. Engines call this + right after compilation so admission prices the real reservation + while banks exist; bank release clears it via + clear_ane_prefill_transient. + """ + self._ane_prefill_transient_bytes = max(int(value), 0) + def set_model_info( self, num_layers: int, diff --git a/tests/test_memory_monitor.py b/tests/test_memory_monitor.py index 02b16dc6dc..4646f5a762 100644 --- a/tests/test_memory_monitor.py +++ b/tests/test_memory_monitor.py @@ -1131,3 +1131,30 @@ def test_clear_drops_the_reservation_after_a_shed(self): ) monitor.clear_ane_prefill_transient() assert monitor._ane_prefill_transient_bytes == 0 + + def test_setter_refreshes_after_compile_and_clears_after_release(self): + # The banks compile after the scheduler snapshots model info, so the + # load-time reserve reads 0; engines refresh it post-compile, and the + # release rung clears it while the model stays resident. + from omlx.memory_monitor import MemoryMonitor + + monitor = MemoryMonitor(max_kv_cache_memory=None, eviction_enabled=False) + monitor.set_model_info( + num_layers=2, + num_kv_heads=2, + head_dim=64, + dtype_size=2, + ) + assert monitor._ane_prefill_transient_bytes == 0 + reserve = 12 * 1024**3 + base_peak = monitor.estimate_prefill_peak_bytes(32768, 2048) + monitor.set_ane_prefill_transient_bytes(reserve) + assert monitor._ane_prefill_transient_bytes == reserve + assert ( + monitor.estimate_prefill_peak_bytes(32768, 2048) == base_peak + reserve + ) + monitor.clear_ane_prefill_transient() + assert monitor._ane_prefill_transient_bytes == 0 + # Negative input clamps to zero instead of widening headroom. + monitor.set_ane_prefill_transient_bytes(-5) + assert monitor._ane_prefill_transient_bytes == 0 From 40b9f23dd18a9514bf4a62b2bfa803c1d7a3e567 Mon Sep 17 00:00:00 2001 From: Nikita Aleksandrov Date: Sun, 6 Sep 2026 15:09:41 +0300 Subject: [PATCH 092/132] fix(engine_pool): escalate prefill headroom past a no-op first pass (#3365) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Problem #3103 added an ANE-bank-release rung, made *recurring* pressure escalate release-before-reclaim, and raised the retry budget to 2. But a request is marked recurring only when the pooled-buffer reclaim rung actually runs. There is a path where the first eviction callback runs **no rung at all**: the pool's own re-measurement — `max(mx.get_active_memory(), phys_footprint, model_memory)` — reads lower than the scheduler's `_current_usage_bytes()`, sees headroom, and returns having done nothing and marked nothing. The scheduler's tighter reading still shows pressure, so it spends its retry. The second callback is still *not* recurring, so it runs the marginal pooled reclaim — which prefill continuously refutes by refilling MLX's buffer cache — and the budget is exhausted. The durable release rung is never reached. Production capture (v0.6.4, request `4420aa8c`, ANE prefill enabled): ``` scheduler - Request 4420aa8c needs prefill headroom before throttling (current=32.44GB, predicted=1.36GB, target=33.29GB) engine_core - No idle model evicted for request 4420aa8c; scheduler will fall back to throttling scheduler - Request 4420aa8c needs prefill headroom before throttling (current=32.39GB, predicted=2.23GB, target=34.41GB) engine_pool - Reclaimed 2.60GB of pooled Metal buffers for prefill request 4420aa8c (no idle model to evict) ``` Pass 1 ran no rung ("No idle model evicted ... fall back to throttling", with no reclaim line); pass 2 reclaimed; retries exhausted. The request was then rejected at the 2048-token guard — `Not enough memory to prefill even 4,096 tokens` — while the ~12 GB of bank memory sat untouched. ## Change - `_evict_idle_lru_for_prefill` marks the request at **entry**, storing a per-request callback attempt counter in `_prefill_headroom_recurring` (bounded FIFO). `recurring = attempt > 1` is snapshotted so marking inside the current call does not flip it mid-call. A no-op first pass now leaves the request recurring, so the retry escalates to the release rung instead of reclaiming again. The two-retry policy and rung ordering are unchanged. - Adds one stable `[prefill-eviction]` INFO record per callback decision: `request / retry / reason / action / outcome / recurring / mx_active / phys_footprint / model_memory / predicted / target / evicted`, where `action ∈ {already_fit, evict_model, reclaim_pool, release_ane, reject}`. Within a single pass the ladder still runs reclaim→release when reclaim alone is not enough; the record reports the highest rung reached. The decision was previously invisible. ## Verification - New test reproduces the observed sequence exactly: first callback `already_fit` no-op → second releases the ANE banks; asserts reclaim is never attempted, no model is evicted, and both decision records read `action=already_fit retry=1` then `action=release_ane retry=2`. The existing masked-delta test is updated for the extra re-measurement taken by decision logging. `tests/test_engine_pool.py` + `tests/test_prefill_oom_graceful.py`: **191 passed**. Broader: `test_cluster_engine_pool.py` + `test_scheduler_prefill_memory_guard.py` + `test_server_prefill_memory_handler.py`: **65 passed**. - Live (source build, ANE prefill enabled): the decision is now logged and the ladder reaches the release rung under pressure: ``` engine_pool - [prefill-eviction] request=e417db5c retry=1 reason=adaptive_prefill_throttle action=release_ane outcome=retry recurring=False mx_active=16.57GB phys_footprint=20.25GB model_memory=16.60GB predicted=3.39GB target=33.70GB evicted=0 engine_pool - Released ANE prefill banks on 'Qwen3.8-27B-oQ4e-mtp' ... freed 10.29GB ``` With the pressure now recoverable, the 65,536-token context benchmark completes (~397 tok/s) where the v0.6.4 capture above rejected at 4,096 tokens. --- omlx/engine_pool.py | 61 ++++++++++++++++++++++++++---- tests/test_engine_pool.py | 79 +++++++++++++++++++++++++++++++++++++-- 2 files changed, 129 insertions(+), 11 deletions(-) diff --git a/omlx/engine_pool.py b/omlx/engine_pool.py index f835cf3eba..af1b813b63 100644 --- a/omlx/engine_pool.py +++ b/omlx/engine_pool.py @@ -294,8 +294,9 @@ def __init__( # rung can "succeed" marginally on every pass of a long prompt while # the durable rung behind it (ANE bank release) is never reached; a # request coming back for more headroom escalates instead of - # reclaiming again first. Bounded FIFO — request ids are transient. - self._prefill_headroom_recurring: OrderedDict[str, None] = OrderedDict() + # reclaiming again first. Values count callback attempts per request + # (>1 = recurring). Bounded FIFO — request ids are transient. + self._prefill_headroom_recurring: OrderedDict[str, int] = OrderedDict() self._load_seconds_per_gb_ema: float | None = None self._load_time_observations: int = 0 self._lease_release_tasks: set[asyncio.Task[None]] = set() @@ -1980,12 +1981,39 @@ async def _evict_idle_lru_for_prefill( return False evicted_any = False + evicted_count = 0 reclaim_attempted = False ane_release_attempted = False - # Snapshot once per call: "a PREVIOUS pass for this request already - # got a reclaim". Marking inside this call must not flip it. - recurring = request_id in self._prefill_headroom_recurring + reason = str(getattr(eviction_request, "reason", "") or "") async with self._lock: + attempt = self._prefill_headroom_recurring.get(request_id, 0) + 1 + self._prefill_headroom_recurring[request_id] = attempt + while len(self._prefill_headroom_recurring) > 512: + self._prefill_headroom_recurring.popitem(last=False) + # Snapshot once per call: "a PREVIOUS pass for this request + # already ran". Marking at entry must not flip it for THIS call. + recurring = attempt > 1 + + def _log_decision(action: str, outcome: str) -> None: + logger.info( + "[prefill-eviction] request=%s retry=%d reason=%s " + "action=%s outcome=%s recurring=%s mx_active=%.2fGB " + "phys_footprint=%.2fGB model_memory=%.2fGB " + "predicted=%.2fGB target=%.2fGB evicted=%d", + request_id, + attempt, + reason, + action, + outcome, + recurring, + mx.get_active_memory() / 1024**3, + get_phys_footprint() / 1024**3, + self._current_model_memory / 1024**3, + predicted / 1024**3, + target / 1024**3, + evicted_count, + ) + while True: current = max( mx.get_active_memory(), @@ -2000,6 +2028,22 @@ async def _evict_idle_lru_for_prefill( # process-wide and can be masked by concurrent # allocation, but reaching this check with headroom # after an attempt means admission will now succeed. + if ane_release_attempted: + action = "release_ane" + elif reclaim_attempted: + action = "reclaim_pool" + elif evicted_any: + action = "evict_model" + else: + # No rung ran: the pool's own reading already sees + # headroom. The entry mark above keeps this request + # recurring, so when the scheduler's tighter usage + # reading disagrees and sends it back, the ladder + # escalates straight to the ANE-bank release instead + # of spending the remaining retry on the reclaim rung + # a no-op first pass already proved useless. + action = "already_fit" + _log_decision(action, "retry") return evicted_any or reclaim_attempted or ane_release_attempted victim = self._find_lru_prefill_eviction_victim( @@ -2033,9 +2077,6 @@ async def _evict_idle_lru_for_prefill( # requesting engine's own MLX thread, then let the # loop re-measure. reclaim_attempted = True - self._prefill_headroom_recurring[request_id] = None - while len(self._prefill_headroom_recurring) > 512: - self._prefill_headroom_recurring.popitem(last=False) await self._reclaim_pooled_buffers_for_prefill( exclude_model_id, request_id ) @@ -2073,6 +2114,9 @@ async def _evict_idle_lru_for_prefill( format_size(predicted), format_size(target), ) + _log_decision("evict_model", "retry") + else: + _log_decision("reject", "exhausted") return evicted_any logger.info( @@ -2086,6 +2130,7 @@ async def _evict_idle_lru_for_prefill( ) await self._unload_engine(victim) evicted_any = True + evicted_count += 1 @staticmethod def _resolve_engine_core_from_engine(engine: object) -> object | None: diff --git a/tests/test_engine_pool.py b/tests/test_engine_pool.py index 4665b15a49..ea013d221a 100644 --- a/tests/test_engine_pool.py +++ b/tests/test_engine_pool.py @@ -2428,9 +2428,17 @@ async def test_prefill_admits_when_reclaim_delta_is_masked(self): # The helper's before/after reads both see 45GB (another engine # allocates while the reclaim frees, masking the delta as 0), but - # the loop's next reading sees the real 25GB baseline. Exactly four - # reads: loop #1, helper before, helper after, loop #2. + # the loop's next reading sees the real 25GB baseline. Four scripted + # reads: loop #1, helper before, helper after, loop #2; further + # reads (decision logging) stay at the settled 25GB baseline. phys = iter([45 * gb, 45 * gb, 45 * gb, 25 * gb]) + + def _phys(): + try: + return next(phys) + except StopIteration: + return 25 * gb + scheduler = self._reclaim_scheduler(lambda: None) req = PrefillEvictionRequest( request_id="req-1", @@ -2455,7 +2463,7 @@ async def test_prefill_admits_when_reclaim_delta_is_masked(self): patch("omlx.engine_pool.mx.get_active_memory", return_value=0), patch( "omlx.engine_pool.get_phys_footprint", - side_effect=lambda: next(phys), + side_effect=_phys, ), ): admitted = await pool._evict_idle_lru_for_prefill("target", req) @@ -2597,6 +2605,71 @@ def reclaim(): pool._unload_engine.assert_not_awaited() assert pool._entries["busy"].engine is not None + @pytest.mark.asyncio + async def test_noop_first_pass_escalates_second_pass_to_ane_release( + self, caplog + ): + """The observed admission sequence: the first callback's pool-side + re-measurement already sees headroom and runs no rung (the scheduler + retries anyway because its own usage reading is tighter); the second + callback must escalate straight to the ANE bank release instead of + spending the remaining retry on the pooled-buffer reclaim a no-op + first pass already proved useless.""" + gb = 1024**3 + pool = _make_pool(ceiling=0) + + state = {"pressure": 20 * gb, "released": False} + + def _phys(): + return 25 * gb if state["released"] else state["pressure"] + + async def _release_ane(model_id, request_id): + state["released"] = True + return 17 * gb + + req = PrefillEvictionRequest( + request_id="req-1", + model_id="target", + current_bytes=20 * gb, + target_cap_bytes=40 * gb, + predicted_transient_bytes=10 * gb, + requested_tokens=2048, + reason="prefill_safety_cap", + ) + + pool._entries = {"target": self._entry("target", 25 * gb)} + pool._current_model_memory = 15 * gb + pool._unload_engine = AsyncMock() + pool._release_ane_prefill_for_headroom = AsyncMock(side_effect=_release_ane) + pool._reclaim_pooled_buffers_for_prefill = AsyncMock(return_value=0) + + with ( + patch("omlx.engine_pool.mx.get_active_memory", return_value=0), + patch("omlx.engine_pool.get_phys_footprint", side_effect=_phys), + caplog.at_level(logging.INFO, logger="omlx.engine_pool"), + ): + first = await pool._evict_idle_lru_for_prefill("target", req) + # The scheduler's tighter usage reading still sees pressure on + # the retry even though the pool's first reading saw headroom. + state["pressure"] = 45 * gb + second = await pool._evict_idle_lru_for_prefill("target", req) + + assert first is False + assert second is True + pool._reclaim_pooled_buffers_for_prefill.assert_not_awaited() + pool._release_ane_prefill_for_headroom.assert_awaited_once() + pool._unload_engine.assert_not_awaited() + decisions = [ + record.getMessage() + for record in caplog.records + if "[prefill-eviction]" in record.getMessage() + ] + assert len(decisions) == 2 + assert "action=already_fit" in decisions[0] + assert "retry=1" in decisions[0] + assert "action=release_ane" in decisions[1] + assert "retry=2" in decisions[1] + class TestEnginePoolStatus: """Tests for get_status is_loading field.""" From bccb7afcae437f0d586d36f222bf1c9a4f0c956b Mon Sep 17 00:00:00 2001 From: jundot Date: Sun, 6 Sep 2026 21:30:01 +0900 Subject: [PATCH 093/132] refactor: simplify ANE memory handling and fix cache test stub --- omlx/engine/batched.py | 10 ---- omlx/engine_pool.py | 68 +++++++--------------- omlx/memory_monitor.py | 10 +--- omlx/patches/qwen35_ane_prefill.py | 9 +-- tests/test_engine_pool.py | 43 ++++++-------- tests/test_prefix_cache_cachelist_mixed.py | 1 + tests/test_qwen35_ane_prefill.py | 6 +- 7 files changed, 47 insertions(+), 100 deletions(-) diff --git a/omlx/engine/batched.py b/omlx/engine/batched.py index 37e8b9ea4c..4fc7bfbd1a 100644 --- a/omlx/engine/batched.py +++ b/omlx/engine/batched.py @@ -580,7 +580,6 @@ def _enable_ane_prefill(): scheduler = self._engine.engine.scheduler if ane_prefill_sequence_length: from ..patches.qwen35_ane_prefill import ( - ane_prefill_transient_bytes, configure_qwen35_ane_prefill_scheduler, ) @@ -588,15 +587,6 @@ def _enable_ane_prefill(): scheduler, ane_prefill_sequence_length, ) - # Price the compiled ANE I/O surfaces explicitly: a later - # _set_model_info_for_monitor() defaults the term to zero - # unless re-derived, and the monitor must hold the real - # reservation while the banks exist. - monitor = getattr(scheduler, "memory_monitor", None) - if monitor is not None: - monitor.set_ane_prefill_transient_bytes( - ane_prefill_transient_bytes(self._model) - ) if self._model_settings is not None: tq_enabled = getattr(self._model_settings, "turboquant_kv_enabled", False) if tq_enabled: diff --git a/omlx/engine_pool.py b/omlx/engine_pool.py index af1b813b63..9f46a0935c 100644 --- a/omlx/engine_pool.py +++ b/omlx/engine_pool.py @@ -1990,11 +1990,18 @@ async def _evict_idle_lru_for_prefill( self._prefill_headroom_recurring[request_id] = attempt while len(self._prefill_headroom_recurring) > 512: self._prefill_headroom_recurring.popitem(last=False) - # Snapshot once per call: "a PREVIOUS pass for this request - # already ran". Marking at entry must not flip it for THIS call. + # Count no-op calls too so another attempt prioritizes bank release. recurring = attempt > 1 - def _log_decision(action: str, outcome: str) -> None: + def _log_decision(outcome: str) -> None: + if ane_release_attempted: + action = "release_ane" + elif reclaim_attempted: + action = "reclaim_pool" + elif evicted_any: + action = "evict_model" + else: + action = "already_fit" logger.info( "[prefill-eviction] request=%s retry=%d reason=%s " "action=%s outcome=%s recurring=%s mx_active=%.2fGB " @@ -2006,8 +2013,8 @@ def _log_decision(action: str, outcome: str) -> None: action, outcome, recurring, - mx.get_active_memory() / 1024**3, - get_phys_footprint() / 1024**3, + active / 1024**3, + footprint / 1024**3, self._current_model_memory / 1024**3, predicted / 1024**3, target / 1024**3, @@ -2015,52 +2022,20 @@ def _log_decision(action: str, outcome: str) -> None: ) while True: - current = max( - mx.get_active_memory(), - get_phys_footprint(), - self._current_model_memory, - ) + active = mx.get_active_memory() + footprint = get_phys_footprint() + current = max(active, footprint, self._current_model_memory) if current + predicted <= target: - # A model eviction and/or the pooled-buffer reclaim below - # created enough headroom; signal the caller to re-admit. - # reclaim_attempted stands in for "the reclaim freed - # memory": the helper's own footprint delta is - # process-wide and can be masked by concurrent - # allocation, but reaching this check with headroom - # after an attempt means admission will now succeed. - if ane_release_attempted: - action = "release_ane" - elif reclaim_attempted: - action = "reclaim_pool" - elif evicted_any: - action = "evict_model" - else: - # No rung ran: the pool's own reading already sees - # headroom. The entry mark above keeps this request - # recurring, so when the scheduler's tighter usage - # reading disagrees and sends it back, the ladder - # escalates straight to the ANE-bank release instead - # of spending the remaining retry on the reclaim rung - # a no-op first pass already proved useless. - action = "already_fit" - _log_decision(action, "retry") + # Use the same sample for admission and its decision log. + _log_decision("headroom_available") return evicted_any or reclaim_attempted or ane_release_attempted victim = self._find_lru_prefill_eviction_victim( exclude_model_id=exclude_model_id ) if victim is None: - # No idle model left to evict -- the "No idle model - # evicted" case that used to reject outright even when - # tens of GB were reclaimable. Two rungs remain: the - # cheap pooled-buffer reclaim, and shedding the - # requesting model's own ANE prefill banks. Ordering - # matters: prefill continuously refills MLX's buffer - # cache, so on a long prompt the reclaim can "succeed" - # by a marginal few GB on every pass while the durable - # rung is never reached — a request that already had a - # reclaim pass and is back for more headroom escalates - # straight to the bank release instead. + # Reclaim pooled buffers first, unless this request has + # already tried to obtain headroom in a previous callback. if recurring and not ane_release_attempted: ane_release_attempted = True await self._release_ane_prefill_for_headroom( @@ -2114,9 +2089,8 @@ def _log_decision(action: str, outcome: str) -> None: format_size(predicted), format_size(target), ) - _log_decision("evict_model", "retry") - else: - _log_decision("reject", "exhausted") + # The scheduler may still fit a smaller chunk. + _log_decision("insufficient_headroom") return evicted_any logger.info( diff --git a/omlx/memory_monitor.py b/omlx/memory_monitor.py index 4690f66f8e..147abb084c 100644 --- a/omlx/memory_monitor.py +++ b/omlx/memory_monitor.py @@ -427,15 +427,7 @@ def clear_ane_prefill_transient(self) -> None: self._ane_prefill_transient_bytes = 0 def set_ane_prefill_transient_bytes(self, value: int) -> None: - """Refresh the ANE prefill I/O-surface reservation. - - ANE banks compile after the scheduler snapshots model info (the - engine builds them once the scheduler exists), so the load-time - value can read 0 while banks are being created. Engines call this - right after compilation so admission prices the real reservation - while banks exist; bank release clears it via - clear_ane_prefill_transient. - """ + """Refresh the reservation after VLM ANE compilation.""" self._ane_prefill_transient_bytes = max(int(value), 0) def set_model_info( diff --git a/omlx/patches/qwen35_ane_prefill.py b/omlx/patches/qwen35_ane_prefill.py index 2939f9ef5a..8d09a864f8 100644 --- a/omlx/patches/qwen35_ane_prefill.py +++ b/omlx/patches/qwen35_ane_prefill.py @@ -3588,13 +3588,8 @@ def release_qwen35_ane_prefill(model: Any) -> tuple[int, int]: setattr(module, failed_attr, True) setattr(module, state_attr, None) modules_released += 1 - # _compile_pair and _compile_gdn cache their state per module, so - # dropping the attributes above frees nothing while those stay - # populated. Cleared unconditionally rather than alongside a live - # state: an entry left over from an earlier slice is exactly the - # mapped bank this call exists to hand back. No _COMPILE_LOCK needed - # -- compiles and this release both run on the engine's single-worker - # MLX executor, so they are already serialized. + # Clear cached references too, including states no longer attached. + # Loading has finished and the engine step loop is paused for release. for cache_attr in ("_omlx_ane_prefill_cache", "_omlx_ane_gdn_cache"): cache = getattr(module, cache_attr, None) if cache: diff --git a/tests/test_engine_pool.py b/tests/test_engine_pool.py index ea013d221a..08d4ccdc44 100644 --- a/tests/test_engine_pool.py +++ b/tests/test_engine_pool.py @@ -2428,17 +2428,9 @@ async def test_prefill_admits_when_reclaim_delta_is_masked(self): # The helper's before/after reads both see 45GB (another engine # allocates while the reclaim frees, masking the delta as 0), but - # the loop's next reading sees the real 25GB baseline. Four scripted - # reads: loop #1, helper before, helper after, loop #2; further - # reads (decision logging) stay at the settled 25GB baseline. + # the loop's next reading sees the real 25GB baseline. The log uses + # that same sample without taking another measurement. phys = iter([45 * gb, 45 * gb, 45 * gb, 25 * gb]) - - def _phys(): - try: - return next(phys) - except StopIteration: - return 25 * gb - scheduler = self._reclaim_scheduler(lambda: None) req = PrefillEvictionRequest( request_id="req-1", @@ -2463,7 +2455,7 @@ def _phys(): patch("omlx.engine_pool.mx.get_active_memory", return_value=0), patch( "omlx.engine_pool.get_phys_footprint", - side_effect=_phys, + side_effect=lambda: next(phys), ), ): admitted = await pool._evict_idle_lru_for_prefill("target", req) @@ -2606,26 +2598,22 @@ def reclaim(): assert pool._entries["busy"].engine is not None @pytest.mark.asyncio + @pytest.mark.parametrize("released_gb, expected_fit", [(25, True), (35, False)]) async def test_noop_first_pass_escalates_second_pass_to_ane_release( - self, caplog + self, caplog, released_gb, expected_fit ): - """The observed admission sequence: the first callback's pool-side - re-measurement already sees headroom and runs no rung (the scheduler - retries anyway because its own usage reading is tighter); the second - callback must escalate straight to the ANE bank release instead of - spending the remaining retry on the pooled-buffer reclaim a no-op - first pass already proved useless.""" + """A no-op callback still counts toward bank-release escalation.""" gb = 1024**3 pool = _make_pool(ceiling=0) state = {"pressure": 20 * gb, "released": False} def _phys(): - return 25 * gb if state["released"] else state["pressure"] + return released_gb * gb if state["released"] else state["pressure"] async def _release_ane(model_id, request_id): state["released"] = True - return 17 * gb + return (45 - released_gb) * gb req = PrefillEvictionRequest( request_id="req-1", @@ -2649,14 +2637,16 @@ async def _release_ane(model_id, request_id): caplog.at_level(logging.INFO, logger="omlx.engine_pool"), ): first = await pool._evict_idle_lru_for_prefill("target", req) - # The scheduler's tighter usage reading still sees pressure on - # the retry even though the pool's first reading saw headroom. + # Pressure returns after the first callback found enough headroom. state["pressure"] = 45 * gb second = await pool._evict_idle_lru_for_prefill("target", req) assert first is False - assert second is True - pool._reclaim_pooled_buffers_for_prefill.assert_not_awaited() + assert second is expected_fit + if expected_fit: + pool._reclaim_pooled_buffers_for_prefill.assert_not_awaited() + else: + pool._reclaim_pooled_buffers_for_prefill.assert_awaited_once() pool._release_ane_prefill_for_headroom.assert_awaited_once() pool._unload_engine.assert_not_awaited() decisions = [ @@ -2670,6 +2660,11 @@ async def _release_ane(model_id, request_id): assert "action=release_ane" in decisions[1] assert "retry=2" in decisions[1] + outcome = "headroom_available" if expected_fit else "insufficient_headroom" + assert "outcome=headroom_available" in decisions[0] + assert f"outcome={outcome}" in decisions[1] + assert f"phys_footprint={released_gb:.2f}GB" in decisions[1] + class TestEnginePoolStatus: """Tests for get_status is_loading field.""" diff --git a/tests/test_prefix_cache_cachelist_mixed.py b/tests/test_prefix_cache_cachelist_mixed.py index e09efcbbde..42b3469c4a 100644 --- a/tests/test_prefix_cache_cachelist_mixed.py +++ b/tests/test_prefix_cache_cachelist_mixed.py @@ -312,6 +312,7 @@ def test_prefill_snapshot_decoupled_from_live_cache(): block_aware_cache=object(), config=SimpleNamespace(paged_cache_block_size=BLOCK_SIZE), model=SimpleNamespace(), + _model_has_unreconstructible_cache=lambda: False, _cache_list_needs_boundary_snapshot=lambda cache: True, _boundary_cache_snapshots={}, _boundary_snapshot_store=None, diff --git a/tests/test_qwen35_ane_prefill.py b/tests/test_qwen35_ane_prefill.py index 9cbbee33c2..b343fcbedd 100644 --- a/tests/test_qwen35_ane_prefill.py +++ b/tests/test_qwen35_ane_prefill.py @@ -3217,6 +3217,7 @@ class _NativeHandle: def test_release_latches_modules_drops_states_and_zeroes_counters(): import gc + model = _ReleasableModel() handle = _NativeHandle() ref = weakref.ref(handle) @@ -3250,6 +3251,7 @@ def test_release_latches_modules_drops_states_and_zeroes_counters(): def test_release_clears_the_state_cache_that_pins_the_same_states(): import gc + model = _ReleasableModel() mlp_handle = _NativeHandle() gdn_handle = _NativeHandle() @@ -3269,9 +3271,6 @@ def test_release_clears_the_state_cache_that_pins_the_same_states(): gc.collect() assert released == 2 - # Asserted before the cache contents: left populated, the cache keeps the - # mapped bank alive and the release hands back nothing, and that is the - # failure worth reading when this regresses. assert mlp_ref() is None assert gdn_ref() is None assert model.mlp._omlx_ane_prefill_cache == {} @@ -3280,6 +3279,7 @@ def test_release_clears_the_state_cache_that_pins_the_same_states(): def test_release_clears_a_stale_state_cache_entry(): import gc + model = _ReleasableModel() handle = _NativeHandle() ref = weakref.ref(handle) From a0a16857301a39eae8ba9c98577063d2ff47b1b5 Mon Sep 17 00:00:00 2001 From: Matthijs van den Bos Date: Sun, 6 Sep 2026 14:41:49 +0200 Subject: [PATCH 094/132] fix(qwen4_exp): bound masked SDPA256 memory pricing (#3461) Price the head-dim-256 unfused fallback at fp32, route explicit array masks through bounded tiling, and let the Qwen4 profile trust only array-mask-capable bounded routes. Retire stale unfused transient samples when the runtime route flips so EWMA cannot throttle the bounded regime. Keep regression tests standalone and restore patched global state. --- omlx/memory_monitor.py | 52 +++++- omlx/patches/sdpa256_attention.py | 44 +++++- omlx/prefill_transient_tracker.py | 11 +- omlx/scheduler.py | 9 ++ tests/test_memory_monitor.py | 209 +++++++++++++++++++++++++ tests/test_prefill_oom_graceful.py | 65 +++++++- tests/test_qwen4_qsa_prefill_memory.py | 129 +++++++++++++++ tests/test_sdpa256_attention.py | 124 ++++++++++++++- 8 files changed, 624 insertions(+), 19 deletions(-) diff --git a/omlx/memory_monitor.py b/omlx/memory_monitor.py index 147abb084c..5d49351acd 100644 --- a/omlx/memory_monitor.py +++ b/omlx/memory_monitor.py @@ -54,6 +54,18 @@ # dim-less path and matches the fp16/bf16 majority of MLX inference models. _SDPA_FALLBACK_SCORE_DTYPE_SIZE = 2 +# Bytes/elem the unfused head-dim-256 fallback actually materializes on +# Metal: MLX keeps the attention score matrix in fp32 even for bf16/fp16 +# models (measured ~33GiB IOAccelerator spike on a 160k-token VLM prefill at +# head_dim=256). Shared by the sdpa256 route gate +# (patches/sdpa256_attention._tiled_route_required) and the Qwen4 prefill +# profile so the router and the guard price the real fallback identically. +# Kept separate from _SDPA_FALLBACK_SCORE_DTYPE_SIZE: that default covers +# the dim-less generic path where the compute dtype is unknown and the +# fp16/bf16 majority is the better prior; widening it globally would +# re-price unrelated models without evidence. +SDPA256_UNFUSED_SCORE_DTYPE_SIZE = 4 + # Head dims whose multi-token prefill is routed to an O(L) tiled/online-softmax # kernel instead of the unfused O(L^2) score-matrix fallback. Populated at # runtime by the kernel patch that installs the route (see @@ -68,6 +80,7 @@ class _BoundedSDPAPrefillRoute: min_query_len: int min_kv_len: int kv_tile: int + supports_array_mask: bool _SDPA_TILED_PREFILL_HEAD_DIMS: dict[int, tuple[_BoundedSDPAPrefillRoute, ...]] = {} @@ -79,18 +92,20 @@ def register_tiled_prefill_head_dim( min_query_len: int = 2, min_kv_len: int = 8192, kv_tile: int = 1024, + supports_array_mask: bool = False, ) -> None: """Register a bounded long-context route installed for one head dim. Multiple native routes may cover the same head dimension at different - thresholds. Store them independently so combining two registrations can - never invent shape coverage that neither route actually guarantees. + thresholds and mask capabilities. Store them independently so combining + registrations cannot invent coverage no individual route guarantees. """ head_dim = int(head_dim) route = _BoundedSDPAPrefillRoute( min_query_len=max(2, int(min_query_len)), min_kv_len=max(1, int(min_kv_len)), kv_tile=max(1, int(kv_tile)), + supports_array_mask=bool(supports_array_mask), ) routes = _SDPA_TILED_PREFILL_HEAD_DIMS.get(head_dim, ()) if route not in routes: @@ -1299,13 +1314,44 @@ def estimate_prefill_transient_bytes( core_kv = kv_len if gathered_core and kv_len > self.indexer_budget: core_kv = min(kv_len, self.indexer_budget + self.compress_ratio - 1) + + # The head_dim-256 sdpa256 patch keeps long-context prefill O(L): + # consult the same bounded-route registry the generic estimator uses + # (issue #2204 follow-up). Without it this profile always charges the + # dense Q x kv_len matrix, which made the guard shrink VLM chunks to + # crawl speed on 160k-context prefills even though the router forces + # a bounded kernel there. core = estimate_unfused_sdpa_call_bytes( self.num_attention_heads, query_tokens, core_kv, self.head_dim, - self.score_dtype_size, + SDPA256_UNFUSED_SCORE_DTYPE_SIZE, ) + bounded_routes = _SDPA_TILED_PREFILL_HEAD_DIMS.get(self.head_dim, ()) + matching_routes = [ + route + for route in bounded_routes + if route.supports_array_mask + and query_tokens >= route.min_query_len + and core_kv >= route.min_kv_len + ] + if matching_routes: + # Match the generic estimator's O(L) bound: fp32 output plus one + # fp32 score tile (largest registered tile). The core_kv is the + # K width of the real core-attention call, so a gathered QSA call + # whose reduced K is below the route floor stays dense-priced. + kv_tile = max(route.kv_tile for route in matching_routes) + tile_scores = ( + self.num_attention_heads + * query_tokens + * min(kv_tile, core_kv) + * SDPA256_UNFUSED_SCORE_DTYPE_SIZE + ) + output = ( + self.num_attention_heads * query_tokens * self.head_dim * 4 + ) + core = int(output + tile_scores) return indexer + core diff --git a/omlx/patches/sdpa256_attention.py b/omlx/patches/sdpa256_attention.py index 5f2811fd1b..73e1c3fcc4 100644 --- a/omlx/patches/sdpa256_attention.py +++ b/omlx/patches/sdpa256_attention.py @@ -29,7 +29,10 @@ import mlx.core as mx -from omlx.memory_monitor import estimate_unfused_sdpa_call_bytes +from omlx.memory_monitor import ( + SDPA256_UNFUSED_SCORE_DTYPE_SIZE, + estimate_unfused_sdpa_call_bytes, +) logger = logging.getLogger(__name__) @@ -95,6 +98,17 @@ def _parse_force_tiled_env() -> bool | None: return None +def _notify_bounded_route(provider, active: bool) -> None: + """Let the scheduler retire measurements from the previous route.""" + try: + owner = getattr(provider, "__self__", None) + callback = getattr(owner, "_sdpa256_bounded_route_changed", None) + if callable(callback): + callback(active) + except Exception: + logger.debug("sdpa256 route notification failed", exc_info=True) + + def _tiled_route_required(queries, keys) -> bool: """Decide forced-fused vs default for a matched call (True = force). @@ -102,12 +116,13 @@ def _tiled_route_required(queries, keys) -> bool: (issues #2155 / #2204), so force the fused path only when the unfused transient would not fit under the guard ceiling — or when no headroom info is available, keeping the memory-safe #2025 behavior.""" + provider = _HEADROOM_PROVIDER() if _HEADROOM_PROVIDER is not None else None if _FORCE_TILED is not None: if _FORCE_TILED: _note_tiled_route("forced", "forced by OMLX_SDPA256_TILED=1") + _notify_bounded_route(provider, _FORCE_TILED) return _FORCE_TILED try: - provider = _HEADROOM_PROVIDER() if _HEADROOM_PROVIDER is not None else None if provider is None: _note_tiled_route( "no-provider", @@ -122,6 +137,7 @@ def _tiled_route_required(queries, keys) -> bool: "memory ceiling not available (enforcer state not yet " "propagated)", ) + _notify_bounded_route(provider, True) return True batch, n_q, q_len, _ = queries.shape transient = estimate_unfused_sdpa_call_bytes( @@ -129,17 +145,22 @@ def _tiled_route_required(queries, keys) -> bool: q_len, keys.shape[-2], HEAD_DIM, - score_dtype_size=queries.dtype.size, + # The unfused fallback materializes fp32 scores even for bf16 + # inputs (issue #2204 follow-up): pricing it at the query dtype + # halves the predicted matrix and admits OOM spikes at long + # context. Shared with the guard via the memory_monitor constant. + score_dtype_size=SDPA256_UNFUSED_SCORE_DTYPE_SIZE, ) - if transient > headroom: + bounded = transient > headroom + _notify_bounded_route(provider, bounded) + if bounded: _note_tiled_route( "insufficient-headroom", f"unfused transient ~{transient / 2**20:.0f}MiB exceeds live " f"guard headroom ~{headroom / 2**20:.0f}MiB at " f"kv_len={keys.shape[-2]}", ) - return True - return False + return bounded except Exception: _note_tiled_route("probe-error", "guard headroom probe failed") logger.debug("sdpa256 headroom probe failed", exc_info=True) @@ -233,7 +254,15 @@ def _array_tiled_sdpa256(queries, keys, values, scale, mask, sinks=None): def _flash_sdpa256(queries, keys, values, scale, mask, sinks=None): - """Use MLX 0.32.2 native fused SDPA on Metal, portable tiling elsewhere.""" + """Use MLX 0.32.2 native fused SDPA on Metal, portable tiling elsewhere. + + Explicit array masks never take the native fused call: MLX's fused + array-mask support is unproven and may silently fall back to the + unfused fp32 score matrix, which is exactly the O(L^2) spike this patch + exists to bound. The array-tiled implementation already handles bool and + additive masks, so route them there directly.""" + if isinstance(mask, mx.array): + return _array_tiled_sdpa256(queries, keys, values, scale, mask, sinks) native_shape = values.shape[-1] == HEAD_DIM and not ( isinstance(mask, str) and mask == "causal" @@ -297,6 +326,7 @@ def _register_bounded_route(min_kv_len: int) -> bool: min_query_len=_SDPA256_MIN_Q_LEN, min_kv_len=min_kv_len, kv_tile=_KV_TILE, + supports_array_mask=True, ) except Exception: logger.debug("could not register sdpa256 with memory_monitor", exc_info=True) diff --git a/omlx/prefill_transient_tracker.py b/omlx/prefill_transient_tracker.py index f2db08acb9..5b08aab8fc 100644 --- a/omlx/prefill_transient_tracker.py +++ b/omlx/prefill_transient_tracker.py @@ -231,8 +231,15 @@ def recent_reclaim_bytes(self) -> int: """Footprint released since the last positive chunk measurement.""" return self._recent_reclaim_bytes + def reset_history(self, *, gathered_core: bool = False) -> None: + """Drop observations for one execution regime.""" + if gathered_core: + self._gathered_history = _TransientHistory() + else: + self._dense_history = _TransientHistory() + def reset(self) -> None: """Drop all observations (e.g. on model reload or after a long idle).""" - self._dense_history = _TransientHistory() - self._gathered_history = _TransientHistory() + self.reset_history() + self.reset_history(gathered_core=True) self._recent_reclaim_bytes = 0 diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 58c7052332..a7a6d50afa 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -1997,6 +1997,7 @@ def __init__( self._prefill_transient_tracker = PrefillTransientTracker( model_id=_tracker_model_id ) + self._sdpa256_bounded_route_active: bool | None = None # One-shot probe of the GDN/Mamba fixed recurrent-state footprint, # armed by _set_model_info_for_monitor when ArraysCache layers exist # and taken after the first prefill chunk's eval. @@ -4030,6 +4031,14 @@ def _prefill_abort_description(self) -> tuple[int, int, float]: safety_cap = self._prefill_abort_cap() return base_cap, safety_cap, self._prefill_abort_margin + def _sdpa256_bounded_route_changed(self, active: bool) -> None: + """Retire measurements when SDPA256 changes memory regimes.""" + previous = getattr(self, "_sdpa256_bounded_route_active", None) + active = bool(active) + self._sdpa256_bounded_route_active = active + if previous != active and (previous is not None or active): + self._prefill_transient_tracker.reset_history() + def _sdpa256_unfused_headroom(self) -> int: """Live headroom (bytes) for one unfused SDPA transient, under the same target the adaptive prefill throttle enforces (hard ceiling x diff --git a/tests/test_memory_monitor.py b/tests/test_memory_monitor.py index 4646f5a762..6ecd42a6b7 100644 --- a/tests/test_memory_monitor.py +++ b/tests/test_memory_monitor.py @@ -1078,6 +1078,215 @@ def test_non_v4_config_keeps_generic_estimator(self): assert make_prefill_memory_profile(config, compute_dtype_size=2) is None +class TestQwen4ExpPrefillMemoryProfile: + """Qwen4 profile must price the head-dim-256 core through the same + bounded-route registry the generic estimator uses: dense Q x kv_len fp32 + without a registered route, output + one fp32 score tile with one.""" + + @staticmethod + def _profile(): + from omlx.memory_monitor import make_prefill_memory_profile + + config = SimpleNamespace( + model_type="qwen4_exp", + num_hidden_layers=48, + num_attention_heads=24, + num_key_value_heads=2, + head_dim=256, + indexer_n_heads=4, + indexer_head_dim=128, + indexer_budget=2048, + indexer_compress_ratio=4, + full_attention_interval=4, + layer_types=None, + ) + return make_prefill_memory_profile(config, compute_dtype_size=2) + + def _monitor(self, profile): + from omlx.memory_monitor import MemoryMonitor + + monitor = MemoryMonitor(max_kv_cache_memory=None, eviction_enabled=False) + monitor.set_model_info( + num_layers=48, + num_kv_heads=2, + head_dim=256, + dtype_size=2, + num_attention_heads=24, + compute_dtype_size=2, + prefill_memory_profile=profile, + ) + return monitor + + @staticmethod + def _indexer_bytes(query_tokens, kv_len): + pooled = max(kv_len // 4, 1) + return 4 * query_tokens * pooled * 4 + 4 * query_tokens * 128 * 4 + + def test_no_registration_prices_dense_fp32_core(self): + import omlx.memory_monitor as memory_monitor + + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + try: + profile = self._profile() + query_tokens, kv_len = 2048, 160_000 + estimate = profile.estimate_prefill_transient_bytes( + query_tokens, kv_len + ) + # Dense unfused core is priced at the measured fp32 width, not + # the bf16 model compute dtype (issue #2204 follow-up). + assert estimate == self._indexer_bytes(query_tokens, kv_len) + ( + 24 * query_tokens * kv_len * 4 + 24 * query_tokens * 256 * 4 + ) + finally: + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + + def test_causal_only_registration_keeps_array_mask_core_dense(self): + import omlx.memory_monitor as memory_monitor + + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + memory_monitor.register_tiled_prefill_head_dim( + 256, min_query_len=16, min_kv_len=2048, kv_tile=1024 + ) + try: + profile = self._profile() + query_tokens, kv_len = 2048, 4096 + expected = self._indexer_bytes(query_tokens, kv_len) + ( + 24 * query_tokens * kv_len * 4 + 24 * query_tokens * 256 * 4 + ) + assert profile.estimate_prefill_transient_bytes( + query_tokens, kv_len + ) == expected + finally: + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + + def test_matching_registration_prices_output_plus_one_fp32_tile(self): + import omlx.memory_monitor as memory_monitor + + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + memory_monitor.register_tiled_prefill_head_dim( + 256, min_query_len=16, min_kv_len=8192, kv_tile=1024, supports_array_mask=True + ) + try: + profile = self._profile() + query_tokens, kv_len = 2048, 160_000 + estimate = profile.estimate_prefill_transient_bytes( + query_tokens, kv_len + ) + # Indexer charge is retained; the core is fp32 output plus one + # 1024-wide fp32 score tile — no Q x kv_len matrix. + expected = self._indexer_bytes(query_tokens, kv_len) + ( + 24 * query_tokens * 256 * 4 + 24 * query_tokens * 1024 * 4 + ) + assert estimate == expected + dense = self._indexer_bytes(query_tokens, kv_len) + ( + 24 * query_tokens * kv_len * 4 + 24 * query_tokens * 256 * 4 + ) + assert estimate < dense / 10 + finally: + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + + def test_threshold_misses_stay_dense(self): + import omlx.memory_monitor as memory_monitor + + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + memory_monitor.register_tiled_prefill_head_dim( + 256, min_query_len=16, min_kv_len=8192, kv_tile=1024, supports_array_mask=True + ) + try: + profile = self._profile() + dense_small_kv = self._indexer_bytes(2048, 4096) + ( + 24 * 2048 * 4096 * 4 + 24 * 2048 * 256 * 4 + ) + # kv below the route floor -> dense. + assert ( + profile.estimate_prefill_transient_bytes(2048, 4096) + == dense_small_kv + ) + # query below the route floor -> dense. + dense_short_q = self._indexer_bytes(8, 160_000) + ( + 24 * 8 * 160_000 * 4 + 24 * 8 * 256 * 4 + ) + assert ( + profile.estimate_prefill_transient_bytes(8, 160_000) + == dense_short_q + ) + finally: + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + + def test_crossed_registrations_never_invent_coverage(self): + """Two routes whose individual (query, kv) thresholds are not jointly + met must not produce a bounded price (mirror of the generic + estimator's threshold-independence regression).""" + import omlx.memory_monitor as memory_monitor + + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + memory_monitor.register_tiled_prefill_head_dim( + 256, min_query_len=16, min_kv_len=8192, kv_tile=1024, supports_array_mask=True + ) + memory_monitor.register_tiled_prefill_head_dim( + 256, min_query_len=64, min_kv_len=2048, kv_tile=512, supports_array_mask=True + ) + try: + profile = self._profile() + # q=16 / kv=2048 meets one threshold from each route but no + # complete route. + dense = self._indexer_bytes(16, 2048) + ( + 24 * 16 * 2048 * 4 + 24 * 16 * 256 * 4 + ) + assert profile.estimate_prefill_transient_bytes(16, 2048) == dense + # The widest tile among matching routes binds for full matches. + bounded = self._indexer_bytes(64, 8192) + ( + 24 * 64 * 256 * 4 + 24 * 64 * 1024 * 4 + ) + assert profile.estimate_prefill_transient_bytes(64, 8192) == bounded + finally: + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + + def test_gathered_core_below_route_floor_stays_dense(self): + """The route covers the dense core's actual K width. A gathered QSA + core attending ~indexer_budget tokens is below the 8192 route floor + and must not borrow a bounded price registered for the dense path.""" + import omlx.memory_monitor as memory_monitor + + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + memory_monitor.register_tiled_prefill_head_dim( + 256, min_query_len=16, min_kv_len=8192, kv_tile=1024, supports_array_mask=True + ) + try: + profile = self._profile() + query_tokens, kv_len = 2048, 160_000 + core_kv = min(kv_len, 2048 + 4 - 1) + dense = self._indexer_bytes(query_tokens, kv_len) + ( + 24 * query_tokens * core_kv * 4 + 24 * query_tokens * 256 * 4 + ) + assert ( + profile.estimate_prefill_transient_bytes( + query_tokens, kv_len, gathered_core=True + ) + == dense + ) + finally: + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + + def test_bounded_price_reaches_monitor_via_chunk_transient(self): + import omlx.memory_monitor as memory_monitor + + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + memory_monitor.register_tiled_prefill_head_dim( + 256, min_query_len=16, min_kv_len=8192, kv_tile=1024, supports_array_mask=True + ) + try: + profile = self._profile() + monitor = self._monitor(profile) + direct = profile.estimate_prefill_transient_bytes(2048, 160_000) + routed = monitor.estimate_chunk_transient_bytes( + 2048, 160_000, gathered_core=False + ) + assert routed == direct + finally: + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + + class TestAnePrefillTransientReserve: def test_ane_prefill_transient_is_added_to_the_peak(self): # issue #2841: the ANE I/O surfaces are dirtied by the first long diff --git a/tests/test_prefill_oom_graceful.py b/tests/test_prefill_oom_graceful.py index e12539b295..5e893120e0 100644 --- a/tests/test_prefill_oom_graceful.py +++ b/tests/test_prefill_oom_graceful.py @@ -505,6 +505,62 @@ def test_predicted_transient_zero_without_signals(): assert ns._predicted_chunk_transient(4, 1000) == 0.0 +def test_bounded_qwen4_route_drops_unfused_dense_history(): + """A route flip to bounded array-mask SDPA must retire unfused samples.""" + from omlx import memory_monitor + from omlx.memory_monitor import make_prefill_memory_profile + + config = SimpleNamespace( + model_type="qwen4_exp", + num_hidden_layers=48, + num_attention_heads=24, + num_key_value_heads=2, + head_dim=256, + indexer_n_heads=4, + indexer_head_dim=128, + indexer_budget=2048, + indexer_compress_ratio=4, + full_attention_interval=4, + layer_types=None, + ) + profile = make_prefill_memory_profile(config, compute_dtype_size=2) + monitor = MemoryMonitor(max_kv_cache_memory=_GB, eviction_enabled=False) + monitor.set_model_info( + num_layers=48, + num_kv_heads=2, + head_dim=256, + dtype_size=2, + num_attention_heads=24, + prefill_memory_profile=profile, + ) + routes = memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.get(256) + memory_monitor.register_tiled_prefill_head_dim( + 256, + min_query_len=16, + min_kv_len=8192, + kv_tile=1024, + supports_array_mask=True, + ) + try: + tracker = PrefillTransientTracker() + tracker.update(2048, int(25.4 * 1024**2 * 2048)) + ns = _throttle_ctx( + current=0, hard=240 * _GB, samples_bpt=None, monitor=monitor + ) + ns._prefill_transient_tracker = tracker + Scheduler._sdpa256_bounded_route_changed(ns, False) + Scheduler._sdpa256_bounded_route_changed(ns, True) + + predicted = ns._predicted_chunk_transient(2048, 174_000) + stale = 25.4 * 1024**2 * 2048 * Scheduler._PREFILL_TRANSIENT_SAFETY + assert predicted < stale / 8 + finally: + if routes is None: + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + else: + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS[256] = routes + + def test_predicted_transient_drops_dense_ewma_when_qsa_static_is_cheaper(): """A leftover dense last_delta must not refuse gathered QSA static.""" from omlx.memory_monitor import make_prefill_memory_profile @@ -554,11 +610,16 @@ def test_predicted_transient_drops_dense_ewma_when_qsa_static_is_cheaper(): 4096, 233_472, gathered_core=True ) assert next_predicted == pytest.approx(predicted, rel=1e-6) - # Without gathered pricing, that same leftover gulp must still bind. + # Without gathered pricing, the larger of that gulp and dense fp32 static + # pricing must bind. dense_predicted = ns._predicted_chunk_transient( 4096, 233_472, gathered_core=False ) - assert dense_predicted == pytest.approx(dense_poison, rel=1e-3) + dense_static = ( + monitor.estimate_chunk_transient_bytes(4096, 233_472 + 4096) + + monitor.estimate_prompt_kv_bytes(4096) + ) * Scheduler._PREFILL_TRANSIENT_SAFETY + assert dense_predicted == pytest.approx(max(dense_poison, dense_static), rel=1e-3) def test_predicted_transient_keeps_gathered_spike_from_this_request(): diff --git a/tests/test_qwen4_qsa_prefill_memory.py b/tests/test_qwen4_qsa_prefill_memory.py index 1846b64640..bd6ca16adc 100644 --- a/tests/test_qwen4_qsa_prefill_memory.py +++ b/tests/test_qwen4_qsa_prefill_memory.py @@ -1,5 +1,7 @@ """Regression smoke tests for Qwen4 QSA long-prefill memory routing.""" +import importlib +import sys from types import SimpleNamespace import mlx.core as mx @@ -113,3 +115,130 @@ def fake_quantized(self, *args, **kwargs): assert result.shape == queries.shape assert calls == ["quantized"] + + +def test_qwen4_mask_dense_seam_reaches_array_tiled_sdpa256(monkeypatch): + """Production seam: on the official mask_dense path the QSA indexer + builds an explicit array mask; with the sdpa256 patch installed that mask + must reach _array_tiled_sdpa256 (bounded) and never the native fused call + whose array-mask support could silently unfuse into the O(L^2) fp32 + score matrix. Uses a real Qwen4ExpAttention at production head_dim=256 + with gathered attention disabled by non-broadcast MRoPE positions.""" + from omlx import memory_monitor + from omlx.patches import mlx_vlm_qwen4_exp_compat as compat + from omlx.patches import sdpa256_attention as sdpa256 + + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp import TextConfig + from mlx_vlm.models.qwen4_exp.language import QSAKVCache, Qwen4ExpAttention + + cfg = TextConfig( + model_type="qwen4_exp_text", + hidden_size=512, + num_hidden_layers=1, + num_attention_heads=8, + linear_num_value_heads=4, + linear_num_key_heads=2, + linear_key_head_dim=8, + linear_value_head_dim=8, + linear_conv_kernel_dim=3, + num_experts=4, + num_experts_per_tok=2, + shared_expert_intermediate_size=16, + moe_intermediate_size=16, + rms_norm_eps=1e-6, + vocab_size=64, + num_key_value_heads=2, + max_position_embeddings=4096, + hc_count=2, + hc_lowrank=8, + head_dim=256, + layer_types=["full_attention"], + ple_layer_ids=[], + ple_embed_dim=32, + ple_conv_kernel_size=3, + ngram_size=3, + heads_per_ngram=2, + ngram_vocab_size_base=17, + make_ngram_vocab_size_divisible_by=4, + split_ngram_parts=4, + indexer_n_heads=2, + indexer_kv_heads=1, + indexer_head_dim=128, + indexer_budget=16, + indexer_compress_ratio=4, + eos_token_id=1, + rope_parameters={ + "rope_type": "default", + "mrope_section": [2, 1, 1], + "rope_theta": 10_000, + "partial_rotary_factor": 1.0, + }, + ) + attn = Qwen4ExpAttention(cfg) + mx.eval(attn.parameters()) + + # Keep the gathered fast path off so the official mask_dense path runs: + # 3-D MRoPE positions with differing planes fail the gathered text + # eligibility on both this branch (broadcast check) and upstream main + # (2-D-only predicate), unlike the env knob which only exists here. + prefill_len = 64 # > indexer_budget(16): the sparse mask engages + position_ids = mx.stack( + [ + mx.arange(prefill_len, dtype=mx.int32) * (1 + plane) + for plane in range(3) + ] + ).reshape(3, 1, prefill_len) + + # Fresh sdpa256 install with test-sized KV floor. + importlib.import_module("mlx_lm.models.base") + importlib.import_module("mlx_vlm.models.base") + sdpa_snap = { + mod: mod.scaled_dot_product_attention + for name, mod in tuple(sys.modules.items()) + if mod is not None + and name.startswith(("mlx_lm.models.", "mlx_vlm.models.")) + and hasattr(mod, "scaled_dot_product_attention") + } + min_kv_len_snap = sdpa256._SDPA256_MIN_KV_LEN + routes_snap = memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.get(256) + monkeypatch.setattr(sdpa256, "_PATCHED", False, raising=False) + monkeypatch.setattr(sdpa256, "_HEADROOM_PROVIDER", None, raising=False) + monkeypatch.setattr(sdpa256, "_FORCE_TILED", None, raising=False) + assert sdpa256.apply_sdpa256_attention_patch(min_kv_len=32) is True + + calls = [] + + def tiled(queries, keys, values, scale, mask, sinks=None): + calls.append(mask) + return mx.zeros(queries.shape, queries.dtype) + + def boom(*args, **kwargs): + raise AssertionError( + "native fused SDPA must not see the Qwen4 explicit array mask" + ) + + monkeypatch.setattr(sdpa256, "_array_tiled_sdpa256", tiled) + monkeypatch.setattr(sdpa256.mx.fast, "scaled_dot_product_attention", boom) + + try: + mx.random.seed(7) + x = mx.random.normal((1, prefill_len, 512)) + cache = QSAKVCache() + out = attn(x, mask="causal", cache=cache, position_ids=position_ids) + mx.eval(out) + + assert out.shape == (1, prefill_len, 512) + assert len(calls) == 1 + mask = calls[0] + assert isinstance(mask, mx.array) + assert 1 <= mask.ndim <= 4 + finally: + for mod, fn in sdpa_snap.items(): + mod.scaled_dot_product_attention = fn + sdpa256._SDPA256_MIN_KV_LEN = min_kv_len_snap + if routes_snap is None: + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) + else: + memory_monitor._SDPA_TILED_PREFILL_HEAD_DIMS[256] = routes_snap + monkeypatch.setattr(sdpa256, "_PATCHED", False, raising=False) diff --git a/tests/test_sdpa256_attention.py b/tests/test_sdpa256_attention.py index 3fb34e823b..ff6d10e2fe 100644 --- a/tests/test_sdpa256_attention.py +++ b/tests/test_sdpa256_attention.py @@ -109,7 +109,10 @@ def fake_sdpa(q, k, v, **kwargs): @pytest.mark.parametrize("case", ["boolean", "additive", "sinks"]) def test_bounded_path_preserves_array_masks_and_sinks(case): - """Exercise the real MLX 0.32.2 fused call on Metal when available.""" + """Array masks route to the bounded portable path on Metal too (native + fused array-mask support is unproven and may silently unfuse); causal/ + no-mask cases exercise the real MLX 0.32.2 fused call when available. + All cases stay numerically pinned against the reference SDPA.""" from omlx.patches.sdpa256_attention import _flash_sdpa256 q, k, v = _qkv(16, 32, n_q=4, n_kv=2) @@ -131,6 +134,72 @@ def test_bounded_path_preserves_array_masks_and_sinks(case): assert _max_abs(out, ref) < 2e-2 +@pytest.mark.parametrize("mask_kind", ["boolean", "additive"]) +def test_metal_array_masks_never_reach_native_fused(mask_kind, monkeypatch): + """On Metal, an explicit array mask must go straight to the bounded + array-tiled kernel — never to mx.fast.scaled_dot_product_attention with + force_fused=True, whose array-mask handling could silently unfuse into + the O(L^2) fp32 score matrix this patch exists to bound.""" + from omlx.patches import sdpa256_attention as sdpa256 + + calls = [] + + def boom(*args, **kwargs): + raise AssertionError("native fused SDPA must not see an array mask") + + def tiled(q, k, v, scale, mask, sinks=None): + calls.append((mask, sinks)) + return q + + monkeypatch.setattr(sdpa256.mx.metal, "is_available", lambda: True) + monkeypatch.setattr( + sdpa256.mx.fast, "scaled_dot_product_attention", boom + ) + monkeypatch.setattr(sdpa256, "_array_tiled_sdpa256", tiled) + + q, k, v = _qkv(16, 32, n_q=4, n_kv=2) + if mask_kind == "boolean": + mask = mx.arange(32)[None, None, None, :] >= 8 + else: + allowed = mx.arange(32)[None, None, None, :] >= 8 + mask = mx.where(allowed, 0.0, -1e4).astype(mx.float16) + sinks = mx.array([-0.5, 0.0, 0.5, 1.0], dtype=mx.float16) + + out = sdpa256._flash_sdpa256(q, k, v, SCALE_256, mask, sinks) + assert out is q + # Mask and sinks forwarded unchanged to the bounded kernel. + assert len(calls) == 1 + assert calls[0][0] is mask + assert calls[0][1] is sinks + + +@pytest.mark.parametrize("mask", ["causal", None], ids=["causal", "none"]) +def test_metal_causal_and_none_keep_native_fused(mask, monkeypatch): + """The router dtype fix must not push the proven causal/no-mask paths off + the native fused kernel.""" + from omlx.patches import sdpa256_attention as sdpa256 + + calls = [] + + def fake_sdpa(q, k, v, **kwargs): + calls.append(kwargs) + return q + + def tiled(*args, **kwargs): + raise AssertionError("causal/no-mask native shape must stay fused") + + monkeypatch.setattr(sdpa256.mx.metal, "is_available", lambda: True) + monkeypatch.setattr(sdpa256.mx.fast, "scaled_dot_product_attention", fake_sdpa) + monkeypatch.setattr(sdpa256, "_array_tiled_sdpa256", tiled) + + q, k, v = _qkv(16, 32, n_q=4, n_kv=2) + out = sdpa256._flash_sdpa256(q, k, v, SCALE_256, mask) + assert out is q + assert calls == [ + {"scale": SCALE_256, "mask": mask, "sinks": None, "force_fused": True} + ] + + @pytest.mark.parametrize("mask_kind", ["boolean", "additive"]) def test_portable_array_mask_matches_reference(mask_kind, monkeypatch): """CUDA's bounded fallback must preserve both MLX array-mask forms.""" @@ -361,10 +430,14 @@ class _HeadroomOwner: def __init__(self, value): self.value = value + self.route_changes = [] def headroom(self): return self.value + def _sdpa256_bounded_route_changed(self, active): + self.route_changes.append(active) + @pytest.fixture def _sdpa256_provider_reset(monkeypatch): @@ -379,15 +452,20 @@ def _sdpa256_provider_reset(monkeypatch): def test_route_prefers_stock_when_unfused_fits(_sdpa256_provider_reset): sdpa256 = _sdpa256_provider_reset - from omlx.memory_monitor import estimate_unfused_sdpa_call_bytes + from omlx.memory_monitor import ( + SDPA256_UNFUSED_SCORE_DTYPE_SIZE, + estimate_unfused_sdpa_call_bytes, + ) q, k, _ = _qkv(2048, 16384) owner = _HeadroomOwner(1 << 40) # ~1 TB headroom: unfused clearly fits sdpa256.set_unfused_headroom_provider(owner.headroom) assert sdpa256._should_route(q, k, None, "causal", None) is False - # Exactly at the estimated transient the unfused path still fits... - need = estimate_unfused_sdpa_call_bytes(24, 2048, 16384, 256, q.dtype.size) + # Exactly at the fp32-priced transient the unfused path still fits... + need = estimate_unfused_sdpa_call_bytes( + 24, 2048, 16384, 256, SDPA256_UNFUSED_SCORE_DTYPE_SIZE + ) owner.value = need assert sdpa256._should_route(q, k, None, "causal", None) is False # ...one byte short -> forced fused. @@ -397,6 +475,40 @@ def test_route_prefers_stock_when_unfused_fits(_sdpa256_provider_reset): # Negative headroom = no active ceiling -> memory-safe default. owner.value = -1 assert sdpa256._should_route(q, k, None, "causal", None) is True + assert owner.route_changes == [False, False, True, True] + + +def test_route_prices_bf16_fallback_at_fp32(_sdpa256_provider_reset): + """The unfused fallback materializes fp32 scores even for bf16 queries; + pricing at the query dtype (2B) admitted the O(L^2) matrix when only the + bf16-sized transient fit and produced the ~33GiB VLM prefill spike.""" + sdpa256 = _sdpa256_provider_reset + from omlx.memory_monitor import ( + SDPA256_UNFUSED_SCORE_DTYPE_SIZE, + estimate_unfused_sdpa_call_bytes, + ) + + q, k, _ = _qkv(2048, 16384, dtype=mx.bfloat16) + assert q.dtype.size == 2 # the wrongly-cheap price + assert SDPA256_UNFUSED_SCORE_DTYPE_SIZE == 4 # the real materialization + + bf16_price = estimate_unfused_sdpa_call_bytes( + 24, 2048, 16384, 256, q.dtype.size + ) + fp32_price = estimate_unfused_sdpa_call_bytes( + 24, 2048, 16384, 256, SDPA256_UNFUSED_SCORE_DTYPE_SIZE + ) + assert fp32_price > bf16_price + + # Headroom fits the bf16-sized matrix but not the real fp32 one -> the + # router must force the bounded path. + owner = _HeadroomOwner(int((bf16_price + fp32_price) / 2)) + sdpa256.set_unfused_headroom_provider(owner.headroom) + assert sdpa256._should_route(q, k, None, "causal", None) is True + + # Full fp32 headroom restores the faster stock path. + owner.value = fp32_price + assert sdpa256._should_route(q, k, None, "causal", None) is False def test_route_defaults_to_tiled_when_provider_owner_dies(_sdpa256_provider_reset): @@ -463,7 +575,9 @@ def test_force_off_does_not_publish_a_bounded_memory_route(monkeypatch): monkeypatch.setattr(sdpa256, "_FORCE_TILED", None) assert sdpa256._register_bounded_route(8192) is True try: - assert 256 in mm._SDPA_TILED_PREFILL_HEAD_DIMS + routes = mm._SDPA_TILED_PREFILL_HEAD_DIMS[256] + assert len(routes) == 1 + assert routes[0].supports_array_mask is True finally: mm._SDPA_TILED_PREFILL_HEAD_DIMS.pop(256, None) From de57ab77cb81dd12cd43299306721301e9317fd5 Mon Sep 17 00:00:00 2001 From: jundot Date: Sun, 6 Sep 2026 21:48:20 +0900 Subject: [PATCH 095/132] refactor: shorten prefill tail comments --- omlx/scheduler.py | 22 +++------------------- tests/test_prefill_oom_graceful.py | 15 +-------------- tests/test_scheduler.py | 15 +-------------- 3 files changed, 5 insertions(+), 47 deletions(-) diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 3dfb51f75a..71aab21917 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -3625,11 +3625,7 @@ def _do_external_prefill( request.remaining_tokens = tokens[processed_tokens:] raise - # A chunk may never exceed the tokens actually left: the token - # row and the VLM inputs_embeds (one row wider — the +1 final - # token deferred to insert()) are sliced with the same size and - # MLX clamps silently, so an oversized chunk desynchronizes them - # and Qwen4Exp's PLE dies on an off-by-one reshape (#3240). + # Keep token and embedding slices aligned at the final prefill chunk. n_to_process = min(n_to_process, remaining) if getattr(request, "benchmark_trace", False): request.benchmark_prefill_chunks.append(int(n_to_process)) @@ -4448,16 +4444,7 @@ def _adaptive_chunk_size( bucket = self._PREFILL_STEP_TIERS[1] # 512 n = max(min_chunk, min(n, bucket)) - # The floor is an admission bound, not a padding requirement: when a - # prefill tail is shorter than min_chunk, both floor above must never - # grow the chunk past what the caller had to work with. Returning - # more than requested breaks the documented ">= 1, <= requested" - # contract, and the external-prefill loop slices the token row and - # the VLM inputs_embeds (which spans the +1 final token the token - # stream defers) with the same chunk size — MLX clamps silently, so - # an oversized chunk desynchronizes the two by exactly the rows left - # on each side and Qwen4Exp's PLE dies on an off-by-one reshape - # (#3240). + # The minimum chunk must not enlarge a short tail or boundary slice. n = min(requested, n) n = self._snap_chunk_size(n, requested) @@ -5285,10 +5272,7 @@ def _step_prefill_chunk(self, state: _PrefillState) -> bool: request_id=state.request.request_id, gathered_core=gathered_core, ) - # Same invariant as the external loop (#3240): the throttle may - # shrink but never grow a chunk past the tokens actually left — - # otherwise tokens_processed drifts past the rows actually cached - # (skewed progress and boundary-snapshot totals). + # Count only tokens actually passed to the model. n = min(n, remaining) if getattr(state.request, "benchmark_trace", False): state.request.benchmark_prefill_chunks.append(int(n)) diff --git a/tests/test_prefill_oom_graceful.py b/tests/test_prefill_oom_graceful.py index c3423c9706..7157bb6686 100644 --- a/tests/test_prefill_oom_graceful.py +++ b/tests/test_prefill_oom_graceful.py @@ -1337,20 +1337,7 @@ def test_speed_priority_guard_passes_full_chunk_that_fits(): def test_adaptive_throttle_tail_below_floor_never_grows_chunk(): - """Regression (#3240): the min-chunk floor must never INFLATE a chunk - beyond what the caller asked for. A prefill tail shorter than - prefill_min_chunk_tokens used to be raised back up to the floor - (max(min_chunk, min(requested, n_fit))), and the external-prefill loop - has no clamp after the throttle — so the chunk sized the token slice and - the VLM inputs_embeds slice differently (embeds always covers the +1 - final token the token stream defers for the first decode step). MLX - slices silently clamp, so the model received e.g. 152 input_ids columns - against 153 embeds rows, and Qwen4Exp's PLE died with the reported - off-by-one: - "[reshape] Cannot reshape array of size 1556480 into shape (1,153,4,2560)". - The throttle's documented contract is ">= 1, <= requested"; the floor is - an admission bound, not a padding requirement. - """ + """A throttled tail must not grow to the minimum chunk size.""" hard = 40 * _GB ns = _throttle_ctx( current=39.5 * _GB, hard=hard, samples_bpt=2 * 1024**2, min_chunk=256 diff --git a/tests/test_scheduler.py b/tests/test_scheduler.py index 7abbd6fe16..3d87b48543 100644 --- a/tests/test_scheduler.py +++ b/tests/test_scheduler.py @@ -6298,20 +6298,7 @@ def test_chunked_prefill_initialization_seeds_cached_text_mrope( def test_vlm_external_prefill_never_slices_embeds_longer_than_tokens( self, mock_tokenizer ): - """Regression (#3240): an external-prefill chunk must never exceed the - tokens actually left in the input array. - - VLM ``inputs_embeds`` always spans one row wider than the token side - (the final token is deferred to ``insert()`` for the first decode - step), and MLX slices silently clamp at the array edge. So a chunk - inflated past the remaining tail — e.g. the prefill throttle raising - a short tail back to the ``prefill_min_chunk_tokens`` floor — fed the - model 152 input_ids columns against 153 embeds rows and Qwen4Exp's - PLE died with the reported off-by-one: - "[reshape] Cannot reshape array of size 1556480 into shape (1,153,4,2560)". - The floor stub reproduces that inflation and the assertion pins the - invariant at the model boundary. - """ + """An oversized chunk must keep token and embedding slice lengths equal.""" model = self._make_vlm_model() scheduler = Scheduler( model=model, From e69d707359eb2f682beacc1802b7dee5b35b4c02 Mon Sep 17 00:00:00 2001 From: pedroberaldo87 <134068505+pedroberaldo87@users.noreply.github.com> Date: Sun, 6 Sep 2026 09:54:35 -0300 Subject: [PATCH 096/132] fix(mtp): the reconcile re-prefill runs in scheduler-sized chunks, not one forward (#3415) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When the MTP cycle falls back to the plain step, _reconcile_mtp_to_standard rebuilds the cache by re-prefilling the whole history. It did that in a single forward — 13-30k tokens in an agent loop — which both blows memory (the prefill throttle fired only with MTP on) and lands on sparse-attention paths the chunked prefill never takes. Measured on GLM-5.3-Flash oQ2e (2602 tokens): the cache rebuilt in one shot diverges from the chunked one (512) from layer 7 on (38 positions), and at nearly every position from layer 19 on. It now uses the generator's prefill_step_size (512 on the server), so the rebuilt cache matches the prefill the request already had. Test: test_reconcile_re_prefills_in_scheduler_chunks asserts the chunk shapes (512, 512, 276) for a 1300-token history. Co-authored-by: Pedro Beraldo --- omlx/patches/mlx_lm_mtp/batch_generator.py | 17 ++++++++- tests/test_mlx_lm_mtp_patch.py | 44 ++++++++++++++++++++++ 2 files changed, 60 insertions(+), 1 deletion(-) diff --git a/omlx/patches/mlx_lm_mtp/batch_generator.py b/omlx/patches/mlx_lm_mtp/batch_generator.py index 66df1bdb95..5f181a9c83 100644 --- a/omlx/patches/mlx_lm_mtp/batch_generator.py +++ b/omlx/patches/mlx_lm_mtp/batch_generator.py @@ -1296,8 +1296,23 @@ def _reconcile_mtp_to_standard(gen_batch: Any, state: _MtpState) -> bool: procs = _proc_list(gen_batch) _set_singleton_mrope_delta(gen_batch) tok_arr = _ensure_uint32(mx.array(list(tokens))) + # Re-prefill in the scheduler's chunk size, not in one forward: a + # single forward of the whole context (13-30k tokens in an agent + # loop) both blows memory (the prefill throttle fired only with MTP + # on) and lands on sparse-attention paths the chunked prefill never + # takes, so the rebuilt cache diverged from a chunked one from layer + # 7 on (GLM-5.3, prefill_one_vs_chunks.py). Chunked, it matches the + # prefill the request already had. + step = int(getattr(gen_batch, "prefill_step_size", 0) or 0) or 512 + total = int(tok_arr.shape[0]) + logits = None # Inherits the per-engine stream from the enclosing BatchGenerator context. - logits, _, _ = _call_backbone(gen_batch.model, tok_arr[None, :], new_cache) + for start in range(0, total, step): + logits, _, _ = _call_backbone( + gen_batch.model, tok_arr[None, start : start + step], new_cache + ) + if start + step < total: + mx.eval(logits) last_logits = logits[:, -1, :] # (1, vocab) — dist after tokens[-1] if state.queue: diff --git a/tests/test_mlx_lm_mtp_patch.py b/tests/test_mlx_lm_mtp_patch.py index 13d6cc10a7..98c048a158 100644 --- a/tests/test_mlx_lm_mtp_patch.py +++ b/tests/test_mlx_lm_mtp_patch.py @@ -2821,3 +2821,47 @@ def test_recently_active_window(self): assert tracker.recently_active(3.0) # just-finished counts tracker.clear() assert not tracker.recently_active(3.0) + + +class TestReconcileChunked: + def test_reconcile_re_prefills_in_scheduler_chunks(self, monkeypatch): + """The reconcile re-prefill uses the generator's prefill step, never a + single forward over the whole context: memory and sparse-attention + paths differ from the chunked prefill the request already had.""" + from collections import deque + from types import SimpleNamespace + + import mlx.core as mx + import numpy as np + + from omlx.patches.mlx_lm_mtp import batch_generator + + shapes = [] + + class _FakeCache: + def __init__(self): + self.offset = 0 + self._mtp_undo = None + + def fake_backbone(model, inputs, cache, n_confirmed=0): + shapes.append(int(inputs.shape[1])) + cache[0].offset += int(inputs.shape[1]) + arr = np.full((1, int(inputs.shape[1]), 8), -10.0, dtype=np.float32) + arr[0, -1, 5] = 10.0 + return mx.array(arr), None, None + + monkeypatch.setattr(batch_generator, "_rebuild_singleton_cache", lambda m: [_FakeCache()]) + monkeypatch.setattr(batch_generator, "_call_backbone", fake_backbone) + tokens = list(range(1300)) + state = batch_generator._MtpState(uid=1, queue=deque()) + batch = SimpleNamespace( + model=object(), uids=[1], tokens=[tokens], _num_tokens=[len(tokens)], + samplers=[None], fallback_sampler=lambda lp: mx.argmax(lp, axis=-1).astype(mx.uint32), + logits_processors=[], _next_tokens=mx.array([999]), _next_logprobs=[], + _token_context=[], prompt_cache=[object()], _omlx_mtp_state=state, + prefill_step_size=512, + ) + assert batch_generator._reconcile_mtp_to_standard(batch, state) is True + assert shapes == [512, 512, 276], shapes + assert batch.prompt_cache[0].offset == 1300 + assert batch._next_tokens.tolist() == [5] From c40bf72d4c542d77828adf4fc9e39bf83f0081b7 Mon Sep 17 00:00:00 2001 From: jundot Date: Sun, 6 Sep 2026 22:01:10 +0900 Subject: [PATCH 097/132] fix: preserve prefill chunk size during MTP reconcile --- omlx/patches/mlx_lm_mtp/batch_generator.py | 12 ++- tests/test_mlx_lm_mtp_patch.py | 88 +++++++++++++++++++++- 2 files changed, 89 insertions(+), 11 deletions(-) diff --git a/omlx/patches/mlx_lm_mtp/batch_generator.py b/omlx/patches/mlx_lm_mtp/batch_generator.py index 5f181a9c83..5aae748930 100644 --- a/omlx/patches/mlx_lm_mtp/batch_generator.py +++ b/omlx/patches/mlx_lm_mtp/batch_generator.py @@ -271,6 +271,9 @@ def patched_filter(self, keep, *args, **kwargs): def patched_bg_next(self, *args, **kwargs): gen_batch = getattr(self, "_generation_batch", None) if gen_batch is not None: + # Reconcile runs on GenerationBatch, which upstream creates + # without the owning generator's prefill configuration. + gen_batch.prefill_step_size = getattr(self, "prefill_step_size", 512) gen_batch._omlx_mtp_activation_safe = ( _batch_generator_allows_mtp_activation(self) ) @@ -1057,6 +1060,7 @@ def _make_row_batch( next_logprobs = getattr(gen_batch, "_next_logprobs", None) row = SimpleNamespace( model=gen_batch.model, + prefill_step_size=getattr(gen_batch, "prefill_step_size", 512), uids=[gen_batch.uids[idx]], prompt_cache=prompt_cache, tokens=[gen_batch.tokens[idx]], @@ -1296,13 +1300,7 @@ def _reconcile_mtp_to_standard(gen_batch: Any, state: _MtpState) -> bool: procs = _proc_list(gen_batch) _set_singleton_mrope_delta(gen_batch) tok_arr = _ensure_uint32(mx.array(list(tokens))) - # Re-prefill in the scheduler's chunk size, not in one forward: a - # single forward of the whole context (13-30k tokens in an agent - # loop) both blows memory (the prefill throttle fired only with MTP - # on) and lands on sparse-attention paths the chunked prefill never - # takes, so the rebuilt cache diverged from a chunked one from layer - # 7 on (GLM-5.3, prefill_one_vs_chunks.py). Chunked, it matches the - # prefill the request already had. + # Bound each rebuild forward by the owning generator's prefill size. step = int(getattr(gen_batch, "prefill_step_size", 0) or 0) or 512 total = int(tok_arr.shape[0]) logits = None diff --git a/tests/test_mlx_lm_mtp_patch.py b/tests/test_mlx_lm_mtp_patch.py index 98c048a158..bcdd821810 100644 --- a/tests/test_mlx_lm_mtp_patch.py +++ b/tests/test_mlx_lm_mtp_patch.py @@ -2855,13 +2855,93 @@ def fake_backbone(model, inputs, cache, n_confirmed=0): tokens = list(range(1300)) state = batch_generator._MtpState(uid=1, queue=deque()) batch = SimpleNamespace( - model=object(), uids=[1], tokens=[tokens], _num_tokens=[len(tokens)], - samplers=[None], fallback_sampler=lambda lp: mx.argmax(lp, axis=-1).astype(mx.uint32), - logits_processors=[], _next_tokens=mx.array([999]), _next_logprobs=[], - _token_context=[], prompt_cache=[object()], _omlx_mtp_state=state, + model=object(), + uids=[1], + tokens=[tokens], + _num_tokens=[len(tokens)], + samplers=[None], + fallback_sampler=lambda lp: mx.argmax(lp, axis=-1).astype(mx.uint32), + logits_processors=[], + _next_tokens=mx.array([999]), + _next_logprobs=[], + _token_context=[], + prompt_cache=[object()], + _omlx_mtp_state=state, prefill_step_size=512, ) assert batch_generator._reconcile_mtp_to_standard(batch, state) is True assert shapes == [512, 512, 276], shapes assert batch.prompt_cache[0].offset == 1300 assert batch._next_tokens.tolist() == [5] + + @pytest.mark.parametrize("step", [128, 256]) + @pytest.mark.parametrize("queued", [False, True]) + def test_reconcile_inherits_generator_chunk_size(self, step, queued): + from collections import deque + + import mlx.core as mx + from mlx_lm.generate import BatchGenerator + from mlx_lm.models.llama import Model, ModelArgs + + from omlx.patches.mlx_lm_mtp import batch_generator + + class ProbeModel(Model): + def __init__(self): + super().__init__( + ModelArgs( + model_type="llama", + hidden_size=32, + num_hidden_layers=2, + intermediate_size=64, + num_attention_heads=4, + rms_norm_eps=1e-5, + vocab_size=64, + ) + ) + self.reconcile_shapes = [] + + def __call__(self, inputs, cache=None, return_hidden=False): + logits = super().__call__(inputs, cache=cache) + if return_hidden: + self.reconcile_shapes.append(int(inputs.shape[1])) + return logits, None + return logits + + batch_generator.apply() + model = ProbeModel() + generator = BatchGenerator(model, prefill_step_size=step, max_tokens=16) + try: + generator.insert([[i % 64 for i in range(1300)]]) + for _ in range(32): + generator.next() + if generator._generation_batch.uids: + break + batch = generator._generation_batch + assert batch.uids + assert batch.prefill_step_size == step + history = list(batch.tokens[0]) + queue = deque([(7, mx.zeros((64,)), "draft")]) if queued else deque() + state = batch_generator._MtpState(uid=batch.uids[0], queue=queue) + # Exercise the row projection used by multi-row reconciliation too. + row = batch_generator._make_row_batch(batch, 0, state=state) + assert row.prefill_step_size == step + target = row if queued else batch + assert batch_generator._reconcile_mtp_to_standard(target, state) + expected = [step] * (len(history) // step) + if len(history) % step: + expected.append(len(history) % step) + assert model.reconcile_shapes == expected + assert target.tokens[0] == history + + reference = batch_generator._rebuild_singleton_cache(model) + tokens = mx.array(history, dtype=mx.uint32) + for start in range(0, len(history), step): + logits = model(tokens[None, start : start + step], cache=reference) + mx.eval(logits) + for actual, wanted in zip(target.prompt_cache, reference): + for a, b in zip(actual.state, wanted.state): + assert mx.allclose(a, b).item() + expected_token = 7 if queued else mx.argmax(logits[:, -1, :]).item() + assert target._next_tokens.item() == expected_token + finally: + generator.close() From aeb1f68378e13bebccb233be2557d24450383426 Mon Sep 17 00:00:00 2001 From: williamxyl <50697245+williamxie1989@users.noreply.github.com> Date: Sun, 6 Sep 2026 21:22:35 +0800 Subject: [PATCH 098/132] perf: reserve QSA indexer capacity for prefill (#3455) * perf(qwen4_exp): reserve QSA indexer capacity for known prefill lengths The indexer's capacity-backed arrays grew by unconditional doubling, which amortizes correctly when the final length is unknown (decode) but is pure waste for a prefill, which knows it. Measured on a 205k prompt (M-series 128GB, Qwen3.8-Flash-Next-oQ4e-mtp): the chunk that crossed 196,608 tokens reallocated, memset and copied the whole indexer in one step, +12.25GB of phys_footprint in a single chunk (91.40 -> 102.17GB), and left capacity for 393,216 tokens resident on a model whose max_position_embeddings is 262,144. The process enforcer's hard watermark fired moments later at the prefill's finish line and the request died with an empty usage payload. QSAKVCache now accepts a horizon hint (`reserve_index_capacity`) and routes both growth sites (raw arrays and the pooled block bank) through a single `_next_capacity` policy: land on the reservation with the first allocation, then extend in plain index_step increments. With no reservation the policy is `_growth_capacity` unchanged, so decode-only behavior is bit-identical. The scheduler passes the prompt length at the start of both prefill paths. * test(prefill): stub the indexer reservation in the chunk-step harness test_step_prefill_reclaims_before_first_guard drives _step_prefill_chunk with a SimpleNamespace listing exactly the collaborators that function touches, so the reservation call added by the previous commit needs an entry there -- the same reason the neighbouring _record_chunk_transient is a MagicMock. --- .../mlx_vlm/models/qwen4_exp/language.py | 52 ++++++- omlx/scheduler.py | 45 ++++++ tests/test_prefill_oom_graceful.py | 1 + tests/test_qwen4_qsa_reserved_capacity.py | 141 ++++++++++++++++++ 4 files changed, 235 insertions(+), 4 deletions(-) create mode 100644 tests/test_qwen4_qsa_reserved_capacity.py 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 ad752ba471..c9f4290c94 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 @@ -159,8 +159,21 @@ def _init_indexer_cache(self): self._index_position_ids = None self._index_offset = 0 self._index_capacity_managed = True + self._index_reserved_tokens = 0 self._invalidate_pooled_indexer() + def reserve_index_capacity(self, tokens: int) -> None: + """Hint the final sequence length so capacity lands on it once. + + Capacity doubling is the right policy when the final length is unknown + (decode). A prefill knows it up front, and doubling there costs a full + reallocate + memset + copy of the indexer mid-prefill and leaves up to + 2x the needed capacity resident — past ``max_position_embeddings`` for + long prompts. Reservation makes the first grow land exactly on the + stepped horizon and switches later grows back to plain steps. + """ + self._index_reserved_tokens = max(0, int(tokens)) + @property def index_keys(self): if self._index_keys is None: @@ -205,6 +218,30 @@ def _growth_capacity(current: int, needed: int, step: int) -> int: stepped = ((needed + step - 1) // step) * step return max(stepped, 2 * current if current else step) + def _next_capacity( + self, current: int, needed: int, step: int, reserve: Optional[int] = None + ) -> int: + """Single capacity policy shared by the raw arrays and the block bank. + + Without a reservation the horizon is unknown, so doubling amortizes the + copies. With a reservation the horizon is known, so doubling is pure + waste: land on it on the first grow, then extend in plain steps. + + ``reserve`` is expressed in the same units as ``current``/``needed`` + (tokens for the raw arrays, blocks for the pooled bank) and defaults to + the token-denominated reservation. + """ + if reserve is None: + reserve = getattr(self, "_index_reserved_tokens", 0) + if not reserve: + return self._growth_capacity(current, needed, step) + # Known horizon: always grow to at least the reservation, never past it + # by doubling. A restored cache below the horizon (prefix hit) needs the + # same treatment as a fresh one, or it climbs the doubling ladder chunk + # by chunk until it overshoots the prompt twice over. + target = needed if current >= reserve else max(needed, reserve) + return ((target + step - 1) // step) * step + def _ensure_indexer_capacity( self, sample_keys: mx.array, @@ -220,9 +257,14 @@ def _ensure_indexer_capacity( ) if needed <= current: return - capacity = ((needed + self.index_step - 1) // self.index_step) * self.index_step - if current and self._index_capacity_managed: - capacity = max(capacity, 2 * current) + if self._index_capacity_managed: + capacity = self._next_capacity(current, needed, self.index_step) + else: + # The backing buffers belong to a restore/reconstruction caller, so + # only round up to the step; never second-guess its sizing. + capacity = ( + (needed + self.index_step - 1) // self.index_step + ) * self.index_step new_keys = mx.zeros( (sample_keys.shape[0], capacity, sample_keys.shape[-1]), dtype=sample_keys.dtype, @@ -328,10 +370,12 @@ def pooled_indexer_keys( ) if complete_blocks > current_capacity: block_step = max(1, self.index_step // compress_ratio) - capacity = self._growth_capacity( + reserved = getattr(self, "_index_reserved_tokens", 0) + capacity = self._next_capacity( current_capacity, complete_blocks, block_step, + reserve=(reserved // compress_ratio if reserved else 0), ) new_buffer = mx.zeros( (new_pooled.shape[0], capacity, new_pooled.shape[-1]), diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 71aab21917..be41a43349 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -3576,6 +3576,12 @@ def _do_external_prefill( emitted_boundaries: dict[int, int] = {} + # The full prompt length is known here; hand it to the QSA indexer so + # its arrays are sized once instead of doubling mid-prefill. + self._reserve_qsa_index_capacity( + prompt_cache, base_size + int(input_arr.shape[1]) + ) + while input_arr.shape[1] > 0: _trace_chunk_start = time.perf_counter() _trace_processed_before = processed_tokens @@ -4525,6 +4531,38 @@ def _hot_cache_cpu_bytes(self) -> int: logger.debug("Failed to read local hot-cache byte counter") return 0 + def _reserve_qsa_index_capacity(self, cache_list: Any, tokens: int) -> int: + """Tell QSA indexer caches their final length before the first chunk. + + The indexer's capacity-backed arrays grow by doubling, which is correct + when the horizon is unknown (decode) and pure waste when it is known: + a doubling mid-prefill reallocates, memsets and copies the whole + indexer in one chunk (measured +12.25 GB of phys in the chunk that + crossed 196,608 tokens, tripping the enforcer at prefill's finish + line) and leaves up to 2x capacity resident — past + ``max_position_embeddings`` on long prompts. Reserving lands the + allocation on the final stepped size once and switches later grows to + plain steps. Non-QSA caches expose no such method and are skipped. + """ + if not cache_list or tokens <= 0: + return 0 + reserved = 0 + for c in cache_list: + reserve = getattr(c, "reserve_index_capacity", None) + if reserve is None: + continue + try: + reserve(int(tokens)) + reserved += 1 + except Exception: + logger.debug("QSA index capacity reservation failed", exc_info=True) + if reserved: + logger.info( + f"Reserved QSA indexer capacity for {int(tokens)} tokens " + f"across {reserved} caches (no mid-prefill doubling)" + ) + return reserved + def _current_usage_bytes(self, *, refresh_mlx_active: bool = True) -> int: """Current memory usage for scheduler-side guard checks. @@ -5238,6 +5276,13 @@ def _step_prefill_chunk(self, state: _PrefillState) -> bool: if state.tokens_processed == 0: _sync_and_clear_cache(self._stream) + # Known horizon: size the QSA indexer once instead of doubling + # mid-prefill (see _reserve_qsa_index_capacity). + self._reserve_qsa_index_capacity( + state.cache, + state.total_length + or state.base_size + int(state.tokens_remaining.shape[1]), + ) # Clamp to the next block boundary so boundary snapshots fire exactly. if state.boundary_enabled and state.block_size > 0: diff --git a/tests/test_prefill_oom_graceful.py b/tests/test_prefill_oom_graceful.py index 7157bb6686..87965f918e 100644 --- a/tests/test_prefill_oom_graceful.py +++ b/tests/test_prefill_oom_graceful.py @@ -1006,6 +1006,7 @@ def test_step_prefill_reclaims_before_first_guard(): _guard_prefill_chunk=lambda n, **kwargs: events.append("guard") or n, _record_chunk_transient=MagicMock(), _maybe_record_fixed_state_bytes=MagicMock(), + _reserve_qsa_index_capacity=MagicMock(), ) ns.running = {} ns._decode_fairness = True diff --git a/tests/test_qwen4_qsa_reserved_capacity.py b/tests/test_qwen4_qsa_reserved_capacity.py new file mode 100644 index 0000000000..add0dba8d5 --- /dev/null +++ b/tests/test_qwen4_qsa_reserved_capacity.py @@ -0,0 +1,141 @@ +"""Reserved-horizon tests for the Qwen4 QSA indexer capacity policy. + +Regression guard for the measured mid-prefill spike: the indexer used to +double its capacity-backed arrays unconditionally, so a long prefill paid a +full reallocate + memset + copy of the whole indexer at one chunk boundary +(+12.25 GB of phys in the chunk crossing 196,608 tokens) and kept up to 2x +capacity resident, past ``max_position_embeddings``. A prefill knows its final +length, so it now reserves it and doubling is only used when the horizon is +genuinely unknown (decode). +""" + +# SPDX-License-Identifier: Apache-2.0 + +from __future__ import annotations + +import importlib + +import mlx.core as mx + +from omlx.patches import mlx_vlm_qwen4_exp_compat as compat + +compat.apply_mlx_vlm_qwen4_exp_compat_patch() +language = importlib.import_module("mlx_vlm.models.qwen4_exp.language") + +_STEP = 64 # instance override keeps the allocations test-sized + + +def _cache(reserve: int = 0): + cache = language.QSAKVCache() + cache.index_step = _STEP + if reserve: + cache.reserve_index_capacity(reserve) + return cache + + +def _append(cache, start: int, stop: int) -> None: + length = stop - start + raw = mx.arange(1 * stop * 8, dtype=mx.float32).reshape(1, stop, 8) + cache.update_indexer(raw[:, start:stop], mx.arange(start, stop, dtype=mx.int32)[None]) + + +def _capacity(cache) -> int: + return 0 if cache._index_keys is None else int(cache._index_keys.shape[1]) + + +def test_reservation_lands_the_first_allocation_on_the_final_size(): + cache = _cache(reserve=200) + + _append(cache, 0, 8) + + # ceil(200 / 64) * 64 — the whole prompt fits in one allocation. + assert _capacity(cache) == 256 + + +def test_reserved_indexer_never_doubles_past_the_reservation(): + cache = _cache(reserve=200) + + _append(cache, 0, 8) + _append(cache, 8, 200) + assert _capacity(cache) == 256 # no grow while staying inside the horizon + + _append(cache, 200, 257) # decode crossed the reserved horizon + + # A step (256 -> 320), not a doubling (which would be 512). + assert _capacity(cache) == 320 + assert int(cache.index_keys.shape[1]) == 257 # logical view tracks length + + +def test_unreserved_growth_still_doubles(): + cache = _cache() + + _append(cache, 0, 8) + assert _capacity(cache) == _STEP # seed + _append(cache, 8, 65) + assert _capacity(cache) == 128 + _append(cache, 65, 129) + + # Unknown horizon: 128 -> 256 doubling is still the amortizing choice. + assert _capacity(cache) == 256 + + +def test_reservation_preserves_the_prefix_across_the_single_grow(): + cache = _cache(reserve=200) + + _append(cache, 0, 8) + first = mx.array(cache.index_keys[:, :8, :]) + _append(cache, 8, 200) + mx.eval(first, cache.index_keys) + + assert mx.array_equal(first, mx.array(cache.index_keys[:, :8, :])) + + +def test_restored_cache_below_the_reservation_lands_on_it_not_double(): + # A prefix hit restores capacity sized for the cached prefix. The legacy + # policy doubled from there (measured on a warm 212k turn: 2.84 -> 5.59 GB + # in one chunk, capacity for 229,376 tokens on a 212,068-token prompt), and + # kept climbing the ladder whenever the prompt outgrew the doubling. + cache = _cache(reserve=2000) + + capacity = cache._next_capacity(1088, 1089, _STEP) + + assert capacity == 2048 # ceil(2000 / 64) * 64 + assert capacity != 2176 # what doubling from 1088 would have produced + + +def test_next_capacity_policy_table(): + cache = _cache(reserve=200) + + # Tokens, first grow: land on the reservation. + assert cache._next_capacity(0, 8, _STEP) == 256 + # Tokens, past the reservation: plain steps. + assert cache._next_capacity(256, 257, _STEP) == 320 + # Block units (pooled bank): the reservation arrives pre-divided. + assert cache._next_capacity(0, 10, 8, reserve=12) == 16 + assert cache._next_capacity(16, 17, 8, reserve=12) == 24 + # No reservation: unchanged legacy policy. + unreserved = _cache() + assert unreserved._next_capacity(64, 65, _STEP) == 128 + + +def test_scheduler_reservation_skips_non_qsa_caches(): + from omlx.scheduler import Scheduler + + class _Plain: + pass + + class _QSA: + def __init__(self): + self.reserved = 0 + + def reserve_index_capacity(self, tokens): + self.reserved = tokens + + qsa_a, qsa_b = _QSA(), _QSA() + count = Scheduler._reserve_qsa_index_capacity( + object(), [qsa_a, _Plain(), qsa_b], 12345 + ) + + assert count == 2 + assert (qsa_a.reserved, qsa_b.reserved) == (12345, 12345) + assert Scheduler._reserve_qsa_index_capacity(object(), [qsa_a], 0) == 0 From 2393893396610fe3484d9df773973206efafe04b Mon Sep 17 00:00:00 2001 From: jundot Date: Sun, 6 Sep 2026 22:24:05 +0900 Subject: [PATCH 099/132] fix: honor full QSA prefill reservations (#3455) --- docs/TESTING.md | 7 ++ .../mlx_vlm/models/qwen4_exp/language.py | 28 +------ omlx/scheduler.py | 29 ++----- .../test_qwen4_qsa_reservation_integration.py | 82 +++++++++++++++++++ tests/test_qwen4_qsa_reserved_capacity.py | 11 +-- 5 files changed, 102 insertions(+), 55 deletions(-) create mode 100644 docs/TESTING.md create mode 100644 tests/test_qwen4_qsa_reservation_integration.py diff --git a/docs/TESTING.md b/docs/TESTING.md new file mode 100644 index 0000000000..c925ebbb2b --- /dev/null +++ b/docs/TESTING.md @@ -0,0 +1,7 @@ +# QSA reservation tests + +Run `python -m pytest -q tests/test_qwen4_qsa_reservation_integration.py tests/test_qwen4_qsa_reserved_capacity.py` to check QSA capacity reservations. + +The integration tests cover restored-prefix lengths with boundary snapshots enabled and disabled, the first allocation after cache restoration, and prefill/decode output equivalence using a small Qwen4 model. + +Related regression suites are `test_qwen4_qsa_incremental_cache.py`, `test_qwen4_qsa_decode_gather.py`, and `test_prefill_oom_graceful.py`. 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 c9f4290c94..dfeb9127db 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 @@ -163,15 +163,8 @@ def _init_indexer_cache(self): self._invalidate_pooled_indexer() def reserve_index_capacity(self, tokens: int) -> None: - """Hint the final sequence length so capacity lands on it once. - - Capacity doubling is the right policy when the final length is unknown - (decode). A prefill knows it up front, and doubling there costs a full - reallocate + memset + copy of the indexer mid-prefill and leaves up to - 2x the needed capacity resident — past ``max_position_embeddings`` for - long prompts. Reservation makes the first grow land exactly on the - stepped horizon and switches later grows back to plain steps. - """ + """Reserve a stepped prefill horizon; later growth uses plain steps.""" + self._index_reserved_tokens = max(0, int(tokens)) @property @@ -221,24 +214,11 @@ def _growth_capacity(current: int, needed: int, step: int) -> int: def _next_capacity( self, current: int, needed: int, step: int, reserve: Optional[int] = None ) -> int: - """Single capacity policy shared by the raw arrays and the block bank. - - Without a reservation the horizon is unknown, so doubling amortizes the - copies. With a reservation the horizon is known, so doubling is pure - waste: land on it on the first grow, then extend in plain steps. - - ``reserve`` is expressed in the same units as ``current``/``needed`` - (tokens for the raw arrays, blocks for the pooled bank) and defaults to - the token-denominated reservation. - """ + """Use reserved capacity when known, otherwise amortize growth.""" if reserve is None: reserve = getattr(self, "_index_reserved_tokens", 0) if not reserve: return self._growth_capacity(current, needed, step) - # Known horizon: always grow to at least the reservation, never past it - # by doubling. A restored cache below the horizon (prefix hit) needs the - # same treatment as a fresh one, or it climbs the doubling ladder chunk - # by chunk until it overshoots the prompt twice over. target = needed if current >= reserve else max(needed, reserve) return ((target + step - 1) // step) * step @@ -257,7 +237,7 @@ def _ensure_indexer_capacity( ) if needed <= current: return - if self._index_capacity_managed: + if self._index_capacity_managed or self._index_reserved_tokens: capacity = self._next_capacity(current, needed, self.index_step) else: # The backing buffers belong to a restore/reconstruction caller, so diff --git a/omlx/scheduler.py b/omlx/scheduler.py index be41a43349..45ca6d0e56 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -3579,7 +3579,7 @@ def _do_external_prefill( # The full prompt length is known here; hand it to the QSA indexer so # its arrays are sized once instead of doubling mid-prefill. self._reserve_qsa_index_capacity( - prompt_cache, base_size + int(input_arr.shape[1]) + prompt_cache, _cache_base_sizes(prompt_cache) + n_tokens ) while input_arr.shape[1] > 0: @@ -4532,18 +4532,7 @@ def _hot_cache_cpu_bytes(self) -> int: return 0 def _reserve_qsa_index_capacity(self, cache_list: Any, tokens: int) -> int: - """Tell QSA indexer caches their final length before the first chunk. - - The indexer's capacity-backed arrays grow by doubling, which is correct - when the horizon is unknown (decode) and pure waste when it is known: - a doubling mid-prefill reallocates, memsets and copies the whole - indexer in one chunk (measured +12.25 GB of phys in the chunk that - crossed 196,608 tokens, tripping the enforcer at prefill's finish - line) and leaves up to 2x capacity resident — past - ``max_position_embeddings`` on long prompts. Reserving lands the - allocation on the final stepped size once and switches later grows to - plain steps. Non-QSA caches expose no such method and are skipped. - """ + """Reserve the full prompt length on caches that expose the QSA hook.""" if not cache_list or tokens <= 0: return 0 reserved = 0 @@ -4551,15 +4540,12 @@ def _reserve_qsa_index_capacity(self, cache_list: Any, tokens: int) -> int: reserve = getattr(c, "reserve_index_capacity", None) if reserve is None: continue - try: - reserve(int(tokens)) - reserved += 1 - except Exception: - logger.debug("QSA index capacity reservation failed", exc_info=True) + reserve(int(tokens)) + reserved += 1 if reserved: logger.info( f"Reserved QSA indexer capacity for {int(tokens)} tokens " - f"across {reserved} caches (no mid-prefill doubling)" + f"across {reserved} caches" ) return reserved @@ -5280,8 +5266,9 @@ def _step_prefill_chunk(self, state: _PrefillState) -> bool: # mid-prefill (see _reserve_qsa_index_capacity). self._reserve_qsa_index_capacity( state.cache, - state.total_length - or state.base_size + int(state.tokens_remaining.shape[1]), + _cache_base_sizes(state.cache) + + int(state.tokens_remaining.shape[1]) + + len(state.last_token), ) # Clamp to the next block boundary so boundary snapshots fire exactly. diff --git a/tests/test_qwen4_qsa_reservation_integration.py b/tests/test_qwen4_qsa_reservation_integration.py new file mode 100644 index 0000000000..0758c77a9e --- /dev/null +++ b/tests/test_qwen4_qsa_reservation_integration.py @@ -0,0 +1,82 @@ +"""QSA reservation integration tests for restored prefixes and model output.""" + +from types import SimpleNamespace + +import mlx.core as mx +import pytest +from test_qwen4_qsa_reserved_capacity import language + +from omlx.scheduler import Scheduler + + +def test_restored_index_reserves_full_horizon_on_first_growth(): + cache = language.QSAKVCache() + cache.index_step = 64 + cache.state = (None, None, mx.ones((1, 1088, 8)), mx.arange(1088)[None]) + cache.reserve_index_capacity(2000) + cache.update_indexer(mx.ones((1, 1, 8)), mx.array([[1088]])) + mx.eval(cache.index_keys) + assert cache._index_keys.shape[1] == 2048 + assert mx.all(cache.index_keys == 1).item() + + +@pytest.mark.parametrize("snapshots_enabled", [False, True]) +def test_chunked_reservation_includes_restored_prefix(snapshots_enabled): + cache = language.QSAKVCache() + cache.state = ( + mx.zeros((1, 1, 128, 4)), + mx.zeros((1, 1, 128, 4)), + mx.ones((1, 128, 8)), + mx.arange(128)[None], + ) + ns = SimpleNamespace( + model=object(), + config=SimpleNamespace(paged_cache_block_size=64), + block_aware_cache=object() if snapshots_enabled else None, + _stream=mx.default_stream(mx.gpu), + ) + state = Scheduler._begin_prefill( + ns, + SimpleNamespace(cached_tokens=128), + [1] * 129, + [cache, SimpleNamespace(offset=128)], + ) + ns._prefill_step_size_for_progress = lambda *a: 64 + ns._reserve_qsa_index_capacity = ( + lambda caches, tokens: Scheduler._reserve_qsa_index_capacity(ns, caches, tokens) + ) + + def stop(*args): + raise RuntimeError("reservation complete") + + ns._qwen4_text_gathered_pricing = stop + with pytest.raises(RuntimeError, match="reservation complete"): + Scheduler._step_prefill_chunk(ns, state) + assert cache._index_reserved_tokens >= 256 + + +def test_reserved_qsa_prefill_and_decode_match_unreserved_model(): + from mlx_vlm.models.qwen4_exp.language import LanguageModel + from test_mlx_vlm_qwen4_exp_compat import _tiny_config + + mx.random.seed(3455) + config = _tiny_config() + model = LanguageModel(config.text_config, config) + ordinary, reserved = model.make_cache(), model.make_cache() + for cache in ordinary + reserved: + if hasattr(cache, "index_step"): + cache.index_step = 8 + Scheduler._reserve_qsa_index_capacity(object(), reserved, 36) + for start in range(0, 36, 6): + tokens = (mx.arange(start, start + 6) % 60 + 1)[None] + expected = model(tokens, cache=ordinary).logits + actual = model(tokens, cache=reserved).logits + mx.eval(expected, actual) + assert mx.allclose(actual, expected, atol=1e-5, rtol=1e-5).item() + for _ in range(5): + token = mx.argmax(expected[:, -1], axis=-1)[:, None] + assert mx.array_equal(token, mx.argmax(actual[:, -1], axis=-1)[:, None]).item() + expected = model(token, cache=ordinary).logits + actual = model(token, cache=reserved).logits + mx.eval(expected, actual) + assert mx.allclose(actual, expected, atol=1e-5, rtol=1e-5).item() diff --git a/tests/test_qwen4_qsa_reserved_capacity.py b/tests/test_qwen4_qsa_reserved_capacity.py index add0dba8d5..6b14bc0cae 100644 --- a/tests/test_qwen4_qsa_reserved_capacity.py +++ b/tests/test_qwen4_qsa_reserved_capacity.py @@ -1,13 +1,4 @@ -"""Reserved-horizon tests for the Qwen4 QSA indexer capacity policy. - -Regression guard for the measured mid-prefill spike: the indexer used to -double its capacity-backed arrays unconditionally, so a long prefill paid a -full reallocate + memset + copy of the whole indexer at one chunk boundary -(+12.25 GB of phys in the chunk crossing 196,608 tokens) and kept up to 2x -capacity resident, past ``max_position_embeddings``. A prefill knows its final -length, so it now reserves it and doubling is only used when the horizon is -genuinely unknown (decode). -""" +"""QSA capacity reservation and prefix preservation tests.""" # SPDX-License-Identifier: Apache-2.0 From d90d6fcbaa725bb03023f85c339868ab9151a0d6 Mon Sep 17 00:00:00 2001 From: jundot Date: Sun, 6 Sep 2026 22:28:30 +0900 Subject: [PATCH 100/132] fix: account for prefill pool releases and preserve chunk sizing (#3465) --- docs/TESTING.md | 4 + omlx/engine_pool.py | 3 - omlx/prefill_transient_tracker.py | 72 +--- omlx/scheduler.py | 141 +++---- tests/test_engine_pool.py | 1 - tests/test_prefill_oom_graceful.py | 357 ++++++++++-------- tests/test_prefill_transient_tracker.py | 122 +++--- .../test_qwen4_qsa_reservation_integration.py | 6 +- 8 files changed, 328 insertions(+), 378 deletions(-) diff --git a/docs/TESTING.md b/docs/TESTING.md index c925ebbb2b..2769bca031 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -5,3 +5,7 @@ Run `python -m pytest -q tests/test_qwen4_qsa_reservation_integration.py tests/t The integration tests cover restored-prefix lengths with boundary snapshots enabled and disabled, the first allocation after cache restoration, and prefill/decode output equivalence using a small Qwen4 model. Related regression suites are `test_qwen4_qsa_incremental_cache.py`, `test_qwen4_qsa_decode_gather.py`, and `test_prefill_oom_graceful.py`. + +# Prefill memory accounting tests + +Run `python -m pytest -q tests/test_prefill_transient_tracker.py tests/test_prefill_oom_graceful.py` to check retained versus reclaimed overhead, configured chunk sizes, and abort-cap enforcement. The loop tests run a small initialized MLX model with controlled footprint readings through external and chunked prefill; they do not load a checkpoint. diff --git a/omlx/engine_pool.py b/omlx/engine_pool.py index 293cd96678..9f46a0935c 100644 --- a/omlx/engine_pool.py +++ b/omlx/engine_pool.py @@ -2176,9 +2176,6 @@ def _reclaim_on_engine_thread() -> None: return 0 freed = max(0, before - get_phys_footprint()) if freed > 0: - record_reclaim = getattr(scheduler, "_record_prefill_reclaim", None) - if callable(record_reclaim): - record_reclaim(request_id, freed) logger.info( "Reclaimed %s of pooled Metal buffers for prefill request %s " "(no idle model to evict)", diff --git a/omlx/prefill_transient_tracker.py b/omlx/prefill_transient_tracker.py index 5dc10dced2..1a95dba041 100644 --- a/omlx/prefill_transient_tracker.py +++ b/omlx/prefill_transient_tracker.py @@ -1,6 +1,6 @@ # SPDX-License-Identifier: Apache-2.0 """ -Per-scheduler EWMA of bytes-per-prefill-token. +Per-scheduler prefill memory observations. Used by the adaptive prefill throttle in Scheduler: when current memory enters the caution zone (>= hard_cap * safe_zone_ratio), the next chunk @@ -27,18 +27,13 @@ class _TransientHistory: observed_max_bytes: int = 0 flat_overhead_bytes: int = 0 reclaim_debt_bytes: int = 0 - stable_streak: int = 0 - stable_chunk_size: int = 0 - expansion_limit: int = 0 - request_id: str = "" class PrefillTransientTracker: - """EWMA estimator of MLX prefill chunk transient bytes per token. + """Keep separate gathered and dense observations for one loaded model. - Updated post-chunk from `phys_footprint()` deltas. The first chunk - has no measurement yet — callers fall back to a static estimate - (MemoryMonitor.estimate_prefill_peak_bytes) until samples > 0. + Generic models use token-linear EWMA estimates. Qwen4 uses its static + profile plus observed allocator overhead that must return after a pool release. """ _EWMA_ALPHA = 0.3 # weight on the most recent chunk @@ -61,8 +56,6 @@ class PrefillTransientTracker: # observed outlier. _EWMA_OUTLIER_RATIO = 8.0 _FLAT_OVERHEAD_NOISE_BYTES = 64 * 1024**2 - _FLAT_OVERHEAD_STABLE_CHUNKS = 5 - _PREFILL_CHUNK_TIERS = (32, 64, 128, 256, 512, 1024, 2048) def __init__(self, model_id: str = "") -> None: self._model_id = model_id @@ -179,7 +172,6 @@ def observe_flat_overhead( delta_bytes: int, *, static_bytes: int, - request_id: str, gathered_core: bool = False, representative: bool = True, ) -> None: @@ -187,16 +179,8 @@ def observe_flat_overhead( if n_tokens <= 0: return history = self._history(gathered_core) - if history.request_id != request_id: - history.request_id = request_id - history.stable_streak = 0 - history.stable_chunk_size = 0 - history.expansion_limit = 0 - noise = max(self._FLAT_OVERHEAD_NOISE_BYTES, max(0, static_bytes) // 10) if delta_bytes < -noise: - history.stable_streak = 0 - history.stable_chunk_size = 0 history.reclaim_debt_bytes += -delta_bytes return @@ -205,25 +189,7 @@ def observe_flat_overhead( reallocated = min(history.reclaim_debt_bytes, max(0, delta_bytes)) history.reclaim_debt_bytes -= reallocated residual = delta_bytes - reallocated - max(0, static_bytes) - if residual <= noise: - if not representative: - return - if history.stable_chunk_size == n_tokens: - history.stable_streak += 1 - else: - history.stable_chunk_size = n_tokens - history.stable_streak = 1 - if history.stable_streak == self._FLAT_OVERHEAD_STABLE_CHUNKS: - history.flat_overhead_bytes //= 2 - history.expansion_limit = next( - (tier for tier in self._PREFILL_CHUNK_TIERS if tier > n_tokens), - self._PREFILL_CHUNK_TIERS[-1], - ) - return - - history.stable_streak = 0 - history.stable_chunk_size = 0 - if not representative: + if residual <= noise or not representative: return history.flat_overhead_bytes = max(history.flat_overhead_bytes, residual) history.samples += 1 @@ -236,17 +202,19 @@ def flat_overhead_bytes_for(self, gathered_core: bool) -> int: def reclaim_debt_bytes_for(self, gathered_core: bool) -> int: return self._history(gathered_core).reclaim_debt_bytes - def record_external_reclaim( - self, request_id: str, reclaimed_bytes: int, *, gathered_core: bool - ) -> None: - """Price only route-matched flat overhead that a cache clear released.""" + def record_flat_reclaim(self, reclaimed_bytes: int) -> None: + """Record a process-wide pool release against each route's own overhead. + + A cache clear can release buffers from either route, regardless of the + request that triggered it. Each route is bounded by its own observed + overhead; dense observations never increase the gathered prediction. + """ if reclaimed_bytes <= 0: return - history = self._history(gathered_core) - if history.request_id == request_id: - history.reclaim_debt_bytes = max( - history.reclaim_debt_bytes, - min(history.flat_overhead_bytes, int(reclaimed_bytes)), + for history in (self._dense_history, self._gathered_history): + history.reclaim_debt_bytes = min( + history.flat_overhead_bytes, + history.reclaim_debt_bytes + int(reclaimed_bytes), ) def flat_overhead_charge_for(self, gathered_core: bool) -> int: @@ -256,14 +224,6 @@ def flat_overhead_charge_for(self, gathered_core: bool) -> int: # Only the portion actually reclaimed can be reallocated next chunk. return min(history.flat_overhead_bytes, history.reclaim_debt_bytes) - def expansion_limit_for( - self, gathered_core: bool, *, request_id: str = "" - ) -> int: - history = self._history(gathered_core) - if request_id and history.request_id != request_id: - return 0 - return history.expansion_limit - def predict( self, n_tokens: int, diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 3bf0f6773f..3e5a365af8 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -3608,7 +3608,7 @@ def _do_external_prefill( n_to_process = min(prefill_step_size, remaining) if processed_tokens == 0: - _sync_and_clear_cache(self._stream) + Scheduler._clear_cache(self) # Boundary-limited step size if boundary_enabled and block_size > 0: @@ -3733,7 +3733,7 @@ def _do_external_prefill( # reclaim request can never land before its abort escalation # (measured: aborts 0.1GB over the watermark with 3.7GB pooled). if self._consume_pressure_clear(): - _sync_and_clear_cache(self._stream) + Scheduler._clear_cache(self) processed_tokens += n_to_process @@ -3843,11 +3843,11 @@ def _do_external_prefill( extra_kwargs = None model_kwargs = {} prompt_cache = None - _sync_and_clear_cache(self._stream) + Scheduler._clear_cache(self) raise _PrefillAbortedError(abort_uids, processed_tokens) # Reclaim Metal intermediates between prefill chunks. - _sync_and_clear_cache(self._stream) + Scheduler._clear_cache(self) if getattr(request, "benchmark_trace", False): _trace_total_ms = ( time.perf_counter() - _trace_chunk_start @@ -3894,7 +3894,7 @@ def _do_external_prefill( request, prompt_cache, total_tokens ) - _sync_and_clear_cache(self._stream) + Scheduler._clear_cache(self) # Restore _rope_deltas after cached VLM prefill (for decode capture) if vlm_embeds is not None and _saved_rope_deltas is not None: @@ -3951,19 +3951,12 @@ def _do_external_prefill( def _predicted_chunk_transient( self, n_tokens: int, kv_len: int, *, gathered_core: bool = False ) -> float: - """Conservative predicted Metal peak growth for one prefill chunk. - - The per-chunk SDPA/MoE transient scales with ``query_len * kv_len``, so - the per-token cost GROWS with context length. A long-run EWMA average - lags that growth and underestimates the next chunk — the cause of the - Metal command-buffer OOM crash at large kv_len. We therefore take the - MAX of three signals and apply a safety factor: - - the most recently MEASURED per-token growth (last_delta / last_n) - — anchored on reality at the current kv_len regime, - - the long-run EWMA (model-specific constants the static misses), - - the kv_len-aware static estimate (SDPA transient + this chunk's - newly allocated KV). - Returns 0 only when nothing is known (first chunk, no model info). + """Predict additional memory needed for the next prefill chunk. + + Generic models use the largest static, EWMA, or last-chunk estimate, + including recent reclaim. Qwen4 uses its nonlinear static profile + plus observed overhead released from the pool. Retained overhead is + already included in current footprint and must not be charged again. """ if n_tokens <= 0: return 0.0 @@ -3983,9 +3976,8 @@ def _predicted_chunk_transient( qwen4_flat_overhead = Scheduler._qwen4_prefill_accounting_enabled(self) if tracker is not None: if qwen4_flat_overhead: - # Qwen4's profile (#3461) owns every token-scaled term. Raw - # process-footprint growth is pool noise/fixed allocation and - # must not be divided by one chunk then scaled to another. + # Qwen4 models token-scaled work statically. Add measured + # overhead only after the pool releases it for reallocation. return ( static_per_token * n_tokens * self._PREFILL_TRANSIENT_SAFETY + tracker.flat_overhead_charge_for(gathered_core) @@ -4447,13 +4439,6 @@ def _adaptive_chunk_size( current = self._current_usage_bytes() min_chunk = max(1, self._prefill_min_chunk_tokens) qwen4_flat_overhead = Scheduler._qwen4_prefill_accounting_enabled(self) - if qwen4_flat_overhead: - expansion_limit = self._prefill_transient_tracker.expansion_limit_for( - gathered_core, request_id=request_id - ) - if expansion_limit > 0: - requested = min(requested, max(min_chunk, expansion_limit)) - # Conservative per-token peak growth (measured-last / EWMA / static, × # safety) — see _predicted_chunk_transient. Anchored on the most recent # measurement so it tracks growth with kv_len instead of lagging behind @@ -4707,9 +4692,6 @@ def _clear_request_admission_bookkeeping(self, request_id: str) -> None: self._cache_freshness_waits.pop(request_id, None) self._prefix_cache_prepared.discard(request_id) self._throttle_notified_requests.discard(request_id) - routes = getattr(self, "_qwen4_prefill_route_by_request", None) - if routes is not None: - routes.pop(request_id, None) self._clear_memory_admission_blocker(request_id) self._clear_store_cache_admission_blocker(request_id) @@ -4859,14 +4841,17 @@ def _bypass_hot_cache_under_pressure(self) -> bool: return False return current >= self._memory_limit_bytes - def _record_prefill_reclaim(self, request_id: str, reclaimed_bytes: int) -> None: - if not Scheduler._qwen4_prefill_accounting_enabled(self): - return - route = getattr(self, "_qwen4_prefill_route_by_request", {}).get(request_id) - if route is not None: - self._prefill_transient_tracker.record_external_reclaim( - request_id, reclaimed_bytes, gathered_core=route - ) + def _clear_cache(self) -> None: + """Clear the Metal pool and account for Qwen4 buffers that may return.""" + tracker = getattr(self, "_prefill_transient_tracker", None) + track = ( + tracker is not None + and Scheduler._qwen4_prefill_accounting_enabled(self) + ) + before = get_phys_footprint() if track else 0 + _sync_and_clear_cache(self._stream) + if track: + tracker.record_flat_reclaim(max(0, before - get_phys_footprint())) def _record_chunk_transient( self, @@ -4880,30 +4865,13 @@ def _record_chunk_transient( requested_step: int | None = None, gathered_core: bool = False, ) -> None: - """Feed one chunk's measured transient into the EWMA tracker. - - ``kv_len`` is logged, not used: the phys delta this records is far - noisier than it looks — over one 13k prefill on Qwen3.6, 262 chunks of - the SAME 32 tokens produced 5.2MB to 812.4MB (155x), because the delta - largely tracks MLX buffer-pool growth rather than the chunk. Sampling - phys during the chunk reproduces the delta exactly (it is monotonic - within a chunk), and MLX's active high-water is 2x-tight but excludes - the pool, which is real occupancy under set_cache_limit(total). So no - better per-chunk signal was found, and anything sized from this number - has to stay conservative. Keeping kv_len in the log is what made that - analysis possible. - - Negative deltas remain excluded from the per-token EWMA, but their - released footprint is retained until the next positive sample. The - next predictor prices that one-shot reallocation risk without treating - it as a negative per-token cost. - - Under speed priority, only a complete requested step is representative - of the full-size chunks used for admission. A shorter tail or - boundary-alignment chunk must not replace the last full-step sample: - scaling its fixed/pool-heavy delta up to ``prefill_step_size`` can turn - a small residual allocation into a false multi-gigabyte admission - charge. + """Record footprint growth after a completed prefill chunk. + + Qwen4 subtracts static work and records residual allocator overhead + without scaling it by token count. Other models retain token-linear + observations. Negative deltas record released buffers; positive deltas + repay reallocation charges. Partial speed-priority chunks do not + replace representative overhead or full-step measurements. """ delta = post_bytes - pre_bytes monitor = getattr(self, "memory_monitor", None) @@ -4923,15 +4891,10 @@ def _record_chunk_transient( kv_len + n_tokens, gathered_core=gathered_core, ) + monitor.estimate_prompt_kv_bytes(n_tokens) - routes = getattr(self, "_qwen4_prefill_route_by_request", None) - if routes is None: - routes = self._qwen4_prefill_route_by_request = {} - routes[request_id] = gathered_core self._prefill_transient_tracker.observe_flat_overhead( n_tokens, delta, static_bytes=static, - request_id=request_id, gathered_core=gathered_core, representative=representative, ) @@ -5105,7 +5068,7 @@ def _reclaim_prefill_headroom(self) -> int: Returns: ``max(active, phys_footprint)`` after reclaim. """ - _sync_and_clear_cache(self._stream) + Scheduler._clear_cache(self) return self._current_usage_bytes() # ------------------------------------------------------------------ @@ -5414,7 +5377,7 @@ def _step_prefill_chunk(self, state: _PrefillState) -> bool: n = min(prefill_step_size, remaining) if state.tokens_processed == 0: - _sync_and_clear_cache(self._stream) + Scheduler._clear_cache(self) # Known horizon: size the QSA indexer once instead of doubling # mid-prefill (see _reserve_qsa_index_capacity). self._reserve_qsa_index_capacity( @@ -5613,7 +5576,7 @@ def _step_prefill_chunk(self, state: _PrefillState) -> bool: ) if self._should_clear_after_chunk(): - _sync_and_clear_cache(self._stream) + Scheduler._clear_cache(self) chunk_dt = time.perf_counter() - _t_chunk_start if getattr(state.request, "benchmark_trace", False): _ane_sequence = int( @@ -5680,7 +5643,7 @@ def _finalize_chunked_prefill_cache_for_insert( if getattr(request, "cached_tokens", 0) > 0: with mx.stream(self._stream): _materialize_cache_storage(prompt_cache) - _sync_and_clear_cache(self._stream) + Scheduler._clear_cache(self) def _insert_prefilled_request( self, @@ -5821,7 +5784,7 @@ def _advance_chunked_prefills( # Request aborted mid-chunk. Discard state; the abort will # be fully processed by _process_pending_aborts() next step. self._prefill_states.pop(rid, None) - _sync_and_clear_cache(self._stream) + Scheduler._clear_cache(self) continue except _PrefillEvictionNeeded as e: self._pending_prefill_eviction_request = e.request @@ -5841,7 +5804,7 @@ def _advance_chunked_prefills( self.requests.pop(rid, None) self._clear_request_admission_bookkeeping(rid) get_prefill_tracker().remove(rid) - _sync_and_clear_cache(self._stream) + Scheduler._clear_cache(self) rejected.append(_prefill_memory_exception_output(rid, e)) continue except RuntimeError as e: @@ -5855,7 +5818,7 @@ def _advance_chunked_prefills( # Drop Metal cache pool buffers held by the aborted chunk's # forward / mx.eval transients. Without this, enforcer keeps # seeing the burst footprint until the next mx.clear_cache(). - _sync_and_clear_cache(self._stream) + Scheduler._clear_cache(self) # Try a bounded requeue before surfacing the failure: a # memory-pressure prefill gets a fresh, better-throttled # attempt. Only after the retry budget is exhausted (or for @@ -5881,7 +5844,7 @@ def _advance_chunked_prefills( # Prefill complete — emit final boundary snapshot and insert. self._prefill_states.pop(rid, None) self._emit_final_boundary_if_needed(state) - _sync_and_clear_cache(self._stream) + Scheduler._clear_cache(self) # Ensure a BatchGenerator exists (may not if all requests were # previously in chunked prefill with no running decode). @@ -9282,7 +9245,7 @@ def _try_specprefill_scoring(self, request: Request) -> None: prefill_step_size=self.config.prefill_step_size, stream=self._stream, extract_cache_states=self._extract_cache_states, - sync_and_clear_cache=lambda: _sync_and_clear_cache(self._stream), + sync_and_clear_cache=lambda: Scheduler._clear_cache(self), log=logger, ) @@ -9913,7 +9876,7 @@ def fail_all_requests(self) -> list[str]: # state — mx.synchronize() or mx.clear_cache() can throw a C++ # exception that causes SIGABRT if uncaught (#435). try: - _sync_and_clear_cache(self._stream) + Scheduler._clear_cache(self) except Exception as e: logger.warning(f"Metal cache clear failed during error recovery: {e}") # Requests failed mid-prefill leave PrefillProgressTracker entries @@ -10758,7 +10721,7 @@ def _report_sparse_progress(processed: int, total: int) -> None: check_abort=_check_specprefill_abort, report_system_progress=_report_system_progress, report_sparse_progress=_report_sparse_progress, - sync_and_clear_cache=lambda: _sync_and_clear_cache(self._stream), + sync_and_clear_cache=lambda: Scheduler._clear_cache(self), log=logger, extract_cache_states=self._extract_cache_states, # Preserve an ordinary cache hit that already extends @@ -10793,7 +10756,7 @@ def _report_sparse_progress(processed: int, total: int) -> None: cleanup_rope(self.model) request.specprefill_indices = None tracker.remove(request.request_id) - _sync_and_clear_cache(self._stream) + Scheduler._clear_cache(self) self._cleanup_prefill_abort_request(request) continue except Exception as e: @@ -10872,7 +10835,7 @@ def _report_sparse_progress(processed: int, total: int) -> None: try: done = self._step_prefill_chunk(state) except _PrefillAbortedError: - _sync_and_clear_cache(self._stream) + Scheduler._clear_cache(self) self._cleanup_prefill_abort_request(request) continue except _PrefillEvictionNeeded as e: @@ -10898,7 +10861,7 @@ def _report_sparse_progress(processed: int, total: int) -> None: self.requests.pop(request.request_id, None) self._clear_request_admission_bookkeeping(request.request_id) get_prefill_tracker().remove(request.request_id) - _sync_and_clear_cache(self._stream) + Scheduler._clear_cache(self) rejected_outputs.append( _prefill_memory_exception_output(request.request_id, e) ) @@ -10921,7 +10884,7 @@ def _report_sparse_progress(processed: int, total: int) -> None: get_prefill_tracker().remove(request.request_id) # Drop Metal cache pool buffers held by the aborted # first chunk's forward / mx.eval transients. - _sync_and_clear_cache(self._stream) + Scheduler._clear_cache(self) if self._requeue_or_fail_prefill(request, e): continue rejected_outputs.append( @@ -10936,7 +10899,7 @@ def _report_sparse_progress(processed: int, total: int) -> None: if done: self._emit_final_boundary_if_needed(state) - _sync_and_clear_cache(self._stream) + Scheduler._clear_cache(self) get_prefill_tracker().remove(request.request_id) self._insert_prefilled_request(request, state, scheduled) else: @@ -10981,7 +10944,7 @@ def _report_sparse_progress(processed: int, total: int) -> None: self.requests.pop(request.request_id, None) self._clear_request_admission_bookkeeping(request.request_id) get_prefill_tracker().remove(request.request_id) - _sync_and_clear_cache(self._stream) + Scheduler._clear_cache(self) rejected_outputs.append( _prefill_memory_exception_output(request.request_id, e) ) @@ -11003,7 +10966,7 @@ def _report_sparse_progress(processed: int, total: int) -> None: get_prefill_tracker().remove(request.request_id) # Drop Metal cache pool buffers held by the aborted # chunk's forward / mx.eval transients. - _sync_and_clear_cache(self._stream) + Scheduler._clear_cache(self) if self._requeue_or_fail_prefill(request, e): continue rejected_outputs.append( @@ -11979,7 +11942,7 @@ def _recover_from_generation_overflow_error(self) -> None: self._output_parser_sessions.clear() try: - _sync_and_clear_cache(self._stream) + Scheduler._clear_cache(self) except Exception as e: logger.warning( "Metal cache clear failed during generation overflow recovery: %s", @@ -12448,7 +12411,7 @@ def step(self) -> SchedulerOutput: self, "_tokens_since_clear_cache", 0 ) + len(responses) if self._tokens_since_clear_cache >= 1024: - _sync_and_clear_cache(self._stream) + Scheduler._clear_cache(self) self._tokens_since_clear_cache = 0 # Refresh the executor-owned MLX active-memory sample. # The background enforcer reads this cached value @@ -12566,7 +12529,7 @@ def step(self) -> SchedulerOutput: if self._consume_pressure_clear(): should_clear = True if should_clear: - _sync_and_clear_cache(self._stream) + Scheduler._clear_cache(self) # Route preflight cannot call mx.get_active_memory() from the # event-loop thread, so publish a fresh executor-owned sample once # the deferred pool reclaim has completed. diff --git a/tests/test_engine_pool.py b/tests/test_engine_pool.py index cb5de7ddf9..08d4ccdc44 100644 --- a/tests/test_engine_pool.py +++ b/tests/test_engine_pool.py @@ -2241,7 +2241,6 @@ def reclaim(): # 45GB -> 25GB reclaim brings 25 + 10 (predicted) under the 40GB cap. assert admitted is True scheduler._reclaim_prefill_headroom.assert_called_once() - scheduler._record_prefill_reclaim.assert_called_once_with("req-1", 20 * gb) pool._unload_engine.assert_not_awaited() @pytest.mark.asyncio diff --git a/tests/test_prefill_oom_graceful.py b/tests/test_prefill_oom_graceful.py index 36f5c07c1f..01d84ba68c 100644 --- a/tests/test_prefill_oom_graceful.py +++ b/tests/test_prefill_oom_graceful.py @@ -9,8 +9,9 @@ early-return below the soft watermark, min-chunk floor, bucket clamp) - Scheduler._requeue_or_fail_prefill budget behavior + error-type gating -All tests are unit-level: the throttle/requeue logic is exercised on a light -fake object so no model load or GPU is required. +Sizing and requeue cases use lightweight scheduler fixtures. Loop accounting +cases execute a small initialized MLX model with controlled footprint readings; +no downloaded checkpoint is required. """ import logging @@ -18,6 +19,8 @@ from unittest.mock import MagicMock, patch import pytest +from mlx_lm.models.cache import make_prompt_cache +from mlx_lm.models.llama import Model, ModelArgs from omlx import scheduler as sched_mod from omlx.exceptions import PrefillMemoryExceededError @@ -27,7 +30,13 @@ make_prefill_memory_profile, ) from omlx.prefill_transient_tracker import PrefillTransientTracker -from omlx.scheduler import Scheduler, _PrefillEvictionNeeded, _PrefillState +from omlx.request import Request, SamplingParams +from omlx.scheduler import ( + Scheduler, + SchedulerConfig, + _PrefillEvictionNeeded, + _PrefillState, +) _GB = 1024**3 @@ -429,9 +438,7 @@ def test_guard_rejection_logs_admission_terms_breakdown(caplog): with pytest.raises(PrefillMemoryExceededError): _guard_call(ns, 256, kv_len=122_000) - terms_records = [ - r for r in caplog.records if "admission terms" in r.getMessage() - ] + terms_records = [r for r in caplog.records if "admission terms" in r.getMessage()] assert len(terms_records) == 1 msg = terms_records[0].getMessage() assert "current=" in msg @@ -583,9 +590,7 @@ def test_bounded_qwen4_route_drops_unfused_dense_history(): try: tracker = PrefillTransientTracker() tracker.update(2048, int(25.4 * 1024**2 * 2048)) - ns = _throttle_ctx( - current=0, hard=240 * _GB, samples_bpt=None, monitor=monitor - ) + ns = _throttle_ctx(current=0, hard=240 * _GB, samples_bpt=None, monitor=monitor) ns._prefill_transient_tracker = tracker Scheduler._sdpa256_bounded_route_changed(ns, False) Scheduler._sdpa256_bounded_route_changed(ns, True) @@ -631,9 +636,7 @@ def test_predicted_transient_drops_dense_ewma_when_qsa_static_is_cheaper(): tracker.update(4096, int(69.58 * _GB), gathered_core=False) ns = _throttle_ctx(current=0, hard=240 * _GB, samples_bpt=None, monitor=monitor) ns._prefill_transient_tracker = tracker - predicted = ns._predicted_chunk_transient( - 4096, 233_472, gathered_core=True - ) + predicted = ns._predicted_chunk_transient(4096, 233_472, gathered_core=True) dense_poison = 69.58 * _GB * Scheduler._PREFILL_TRANSIENT_SAFETY assert predicted < dense_poison / 8 assert 147 * _GB + predicted < 214 * _GB @@ -645,15 +648,11 @@ def test_predicted_transient_drops_dense_ewma_when_qsa_static_is_cheaper(): int(predicted / Scheduler._PREFILL_TRANSIENT_SAFETY), gathered_core=True, ) - next_predicted = ns._predicted_chunk_transient( - 4096, 233_472, gathered_core=True - ) + next_predicted = ns._predicted_chunk_transient(4096, 233_472, gathered_core=True) assert next_predicted == pytest.approx(predicted, rel=1e-6) # Without gathered pricing, the larger of that gulp and dense fp32 static # pricing must bind. - dense_predicted = ns._predicted_chunk_transient( - 4096, 233_472, gathered_core=False - ) + dense_predicted = ns._predicted_chunk_transient(4096, 233_472, gathered_core=False) dense_static = ( monitor.estimate_chunk_transient_bytes(4096, 233_472 + 4096) + monitor.estimate_prompt_kv_bytes(4096) @@ -673,7 +672,6 @@ def test_qwen4_measured_excess_is_flat_not_scaled_to_the_next_chunk(): measured_tokens, 20 * _GB, static_bytes=measured_static, - request_id="r", gathered_core=True, ) ns = _throttle_ctx(current=0, hard=240 * _GB, monitor=monitor) @@ -683,9 +681,7 @@ def test_qwen4_measured_excess_is_flat_not_scaled_to_the_next_chunk(): candidate_static = monitor.estimate_chunk_transient_bytes( candidate, kv_len + candidate, gathered_core=True ) + monitor.estimate_prompt_kv_bytes(candidate) - predicted = ns._predicted_chunk_transient( - candidate, kv_len, gathered_core=True - ) + predicted = ns._predicted_chunk_transient(candidate, kv_len, gathered_core=True) assert predicted == pytest.approx( candidate_static * Scheduler._PREFILL_TRANSIENT_SAFETY @@ -732,16 +728,13 @@ def test_qwen4_mask_dense_chunk_does_not_poison_gathered_admission(): # The 26 GB retained pool is already in current footprint, so the next # dense chunk pays only its static profile. If a clear really releases # 12.5 GB, only that released portion becomes a one-shot charge. - dense_retained = ns._predicted_chunk_transient( - 2048, 141_312, gathered_core=False - ) + dense_retained = ns._predicted_chunk_transient(2048, 141_312, gathered_core=False) static_prediction = ( monitor.estimate_chunk_transient_bytes(2048, 143_360, gathered_core=False) + monitor.estimate_prompt_kv_bytes(2048) ) * Scheduler._PREFILL_TRANSIENT_SAFETY assert dense_retained == pytest.approx(static_prediction) - assert ns._qwen4_prefill_route_by_request == {"dense-prefix": False} - Scheduler._record_prefill_reclaim(ns, "dense-prefix", int(12.5 * _GB)) + tracker.record_flat_reclaim(int(12.5 * _GB)) dense_reallocation = ns._predicted_chunk_transient( 2048, 141_312, gathered_core=False ) @@ -750,9 +743,7 @@ def test_qwen4_mask_dense_chunk_does_not_poison_gathered_admission(): ) assert tracker.flat_overhead_charge_for(False) <= 12.5 * _GB - gathered_floor = ns._predicted_chunk_transient( - 32, 142_784, gathered_core=True - ) + gathered_floor = ns._predicted_chunk_transient(32, 142_784, gathered_core=True) assert 84.27 * _GB + gathered_floor < 0.90 * 121.6 * _GB @@ -771,132 +762,16 @@ def test_non_qwen4_prediction_keeps_existing_measured_rate_behavior(): def test_qwen4_route_and_reclaim_accounting_are_model_scoped(): generic = SimpleNamespace( memory_monitor=_monitor(head_dim=192), - _qwen4_prefill_route_by_request={"r": True}, _prefill_transient_tracker=MagicMock(), ) qwen4 = SimpleNamespace(memory_monitor=_qwen4_monitor()) assert not Scheduler._qwen4_prefill_accounting_enabled(generic) assert Scheduler._qwen4_prefill_accounting_enabled(qwen4) - Scheduler._record_prefill_reclaim(generic, "r", 1024) - generic._prefill_transient_tracker.record_external_reclaim.assert_not_called() - - -def test_qwen4_real_chunk_callsite_tracks_deltas_and_expands_one_tier(): - monitor = _qwen4_monitor() - ns = _throttle_ctx(current=0, hard=240 * _GB, monitor=monitor) - ns._record_chunk_transient = Scheduler._record_chunk_transient.__get__( - ns, Scheduler - ) - samples = [(100 * _GB, 110 * _GB), (110 * _GB, 109 * _GB)] + [ - (109 * _GB, 109 * _GB) - ] * 5 - for pre, post in samples: - ns._record_chunk_transient( - 512, - pre, - post, - request_id="r", - loop_label="test", - kv_len=180_000, - requested_step=2048, - gathered_core=True, - ) - - tracker = ns._prefill_transient_tracker - assert tracker.flat_overhead_bytes_for(True) > 0 - assert tracker.reclaim_debt_bytes_for(True) == _GB - assert tracker.expansion_limit_for(True, request_id="r") == 1024 - ns._fake_current = 0 - ns.requests = {} - ns.config = SimpleNamespace(model_name="qwen4") - ns._raise_prefill_eviction_if_available = ( - Scheduler._raise_prefill_eviction_if_available.__get__(ns, Scheduler) - ) - assert _call(ns, 2048, kv_len=180_000, gathered_core=True) == 1024 - - -@pytest.mark.parametrize( - ("trace", "expected_limit"), - [ - ( - [ - (160_000, 1024, 8 * _GB), - (166_000, 1024, 0), - (172_000, 1024, 32 * 1024**2), - (178_000, 1024, -32 * 1024**2), - (184_000, 1024, 0), - (190_000, 1024, 0), - ], - 2048, - ), - ( - [ - (350_000, 512, 4 * _GB), - (350_512, 512, 0), - (351_024, 512, 16 * 1024**2), - (351_536, 512, -16 * 1024**2), - (352_048, 512, 0), - (352_560, 512, 0), - ], - 1024, - ), - ], - ids=("160k-190k", "350k"), -) -def test_qwen4_long_context_plateau_replays(trace, expected_limit): - monitor = _qwen4_monitor() - ns = _throttle_ctx(current=0, hard=240 * _GB, monitor=monitor) - for kv_len, n_tokens, delta in trace: - Scheduler._record_chunk_transient( - ns, - n_tokens, - 100 * _GB, - 100 * _GB + delta, - request_id="r", - loop_label="replay", - kv_len=kv_len, - requested_step=2048, - gathered_core=True, - ) - - assert ns._prefill_transient_tracker.expansion_limit_for( - True, request_id="r" - ) == expected_limit - ns._fake_current = 0 - ns.requests = {} - ns.config = SimpleNamespace(model_name="qwen4") - ns._raise_prefill_eviction_if_available = ( - Scheduler._raise_prefill_eviction_if_available.__get__(ns, Scheduler) - ) - assert _call(ns, 2048, kv_len=trace[-1][0], gathered_core=True) == expected_limit - - -def test_qwen4_plateau_never_bypasses_abort_cap(): - monitor = _qwen4_monitor() - ns = _throttle_ctx(current=0, hard=5 * _GB, monitor=monitor, abort=5 * _GB) - ns._prefill_transient_tracker.observe_flat_overhead( - 512, - 6 * _GB, - static_bytes=100 * 1024**2, - request_id="r", - gathered_core=True, - ) - for _ in range(5): - ns._prefill_transient_tracker.observe_flat_overhead( - 512, - 0, - static_bytes=100 * 1024**2, - request_id="r", - gathered_core=True, - ) - ns._fake_current = 0 - - chosen = _guard_call(ns, 2048, kv_len=180_000, gathered_core=True) - predicted = ns._admission_transient_bound( - chosen, 180_000, gathered_core=True - ) - assert predicted <= ns._prefill_abort_cap() + generic._stream = None + with patch.object(sched_mod, "_sync_and_clear_cache"): + Scheduler._clear_cache(generic) + generic._prefill_transient_tracker.record_flat_reclaim.assert_not_called() def test_adaptive_throttle_charges_recently_reclaimed_footprint(): @@ -946,9 +821,7 @@ def test_predicted_transient_does_not_double_count_reclaim_covered_by_raw(): raw_prediction = 11.83 * _GB static_prediction = 4.11 * _GB released = 6.86 * _GB - raw_per_token = raw_prediction / ( - 512 * Scheduler._PREFILL_TRANSIENT_SAFETY - ) + raw_per_token = raw_prediction / (512 * Scheduler._PREFILL_TRANSIENT_SAFETY) monitor = SimpleNamespace( estimate_chunk_transient_bytes=lambda _n, _kv, *, gathered_core=False: ( static_prediction / Scheduler._PREFILL_TRANSIENT_SAFETY @@ -1102,14 +975,10 @@ def test_record_chunk_transient_marks_floor_samples_only(): # First sample is always excluded from the max (seed noise). ns._record_chunk_transient(32, 0, 100, request_id="r", loop_label="unit") # Big chunk: EWMA only, never the max. - ns._record_chunk_transient( - 2048, 0, 3 * 1024**3, request_id="r", loop_label="unit" - ) + ns._record_chunk_transient(2048, 0, 3 * 1024**3, request_id="r", loop_label="unit") assert tracker.observed_max_bytes == 0 # Floor chunk: enters the max. - ns._record_chunk_transient( - 32, 0, 200 * 1024**2, request_id="r", loop_label="unit" - ) + ns._record_chunk_transient(32, 0, 200 * 1024**2, request_id="r", loop_label="unit") assert tracker.observed_max_bytes == 200 * 1024**2 @@ -1152,9 +1021,7 @@ def test_record_chunk_transient_skips_partial_speed_sample(): assert tracker.last_n_tokens == 2048 assert tracker.last_delta_bytes == full_delta predicted = Scheduler._predicted_chunk_transient(ns, 2048, 65_000) - assert predicted == pytest.approx( - full_delta * Scheduler._PREFILL_TRANSIENT_SAFETY - ) + assert predicted == pytest.approx(full_delta * Scheduler._PREFILL_TRANSIENT_SAFETY) def test_record_chunk_transient_keeps_full_speed_spike_as_last_sample(): @@ -1526,14 +1393,11 @@ def test_non_arrays_caches_contribute_zero(self): def test_zero_total_marks_recorded_without_setting(self): ns = self._ns() - ns._maybe_record_fixed_state_bytes( - [type("KVCache", (), {"state": []})()] - ) + ns._maybe_record_fixed_state_bytes([type("KVCache", (), {"state": []})()]) ns.memory_monitor.set_fixed_state_bytes.assert_not_called() assert ns._fixed_state_recorded is True - # -------------------------------------------------------------------------- # Prefill speed priority (never shrink) # -------------------------------------------------------------------------- @@ -1584,6 +1448,167 @@ def test_speed_priority_guard_passes_full_chunk_that_fits(): assert _guard_call(ns, 2048, kv_len=5000) == 2048 +@pytest.mark.parametrize("requested", [2048, 4096, 8192]) +def test_qwen4_stable_prefill_keeps_configured_chunk_size(requested): + ns = _throttle_ctx(current=0, hard=240 * _GB, monitor=_qwen4_monitor()) + ns._fake_current = 0 + for _ in range(12): + assert _call(ns, requested, kv_len=180_000, gathered_core=True) == requested + Scheduler._record_chunk_transient( + ns, + requested, + 50 * _GB, + 50 * _GB, + request_id="r", + loop_label="test", + kv_len=180_000, + requested_step=requested, + gathered_core=True, + ) + + +def test_qwen4_recovers_configured_width_when_headroom_returns(): + ns = _throttle_ctx(current=0, hard=240 * _GB, monitor=_qwen4_monitor()) + ns._fake_current = ns._prefill_abort_cap() - int( + ns._predicted_chunk_transient(512, 180_000, gathered_core=True) + ) + smaller = _call(ns, 4096, kv_len=180_000, gathered_core=True) + assert 32 <= smaller < 4096 + ns._fake_current = 0 + assert _call(ns, 4096, kv_len=180_000, gathered_core=True) == 4096 + + +@pytest.mark.parametrize("route", [False, True]) +def test_qwen4_local_reclaim_updates_next_guard_prediction(route): + ns = _throttle_ctx(current=80 * _GB, hard=100 * _GB, monitor=_qwen4_monitor()) + ns._stream = None + Scheduler._record_chunk_transient( + ns, + 512, + 50 * _GB, + 80 * _GB, + request_id="r", + loop_label="test", + kv_len=180_000, + requested_step=4096, + gathered_core=route, + ) + before = ns._predicted_chunk_transient(512, 180_000, gathered_core=route) + with ( + patch.object(sched_mod, "_sync_and_clear_cache"), + patch.object(sched_mod, "get_phys_footprint", side_effect=[80 * _GB, 50 * _GB]), + ): + Scheduler._clear_cache(ns) + charge = ns._prefill_transient_tracker.flat_overhead_charge_for(route) + assert charge > 0 + assert ns._predicted_chunk_transient( + 512, 180_000, gathered_core=route + ) == pytest.approx(before + charge) + + +@pytest.mark.parametrize("chunked", [False, True]) +def test_prefill_loop_records_pool_release_before_next_chunk(chunked, monkeypatch): + model = Model( + ModelArgs( + model_type="llama", + hidden_size=32, + num_hidden_layers=2, + intermediate_size=64, + num_attention_heads=4, + num_key_value_heads=2, + rms_norm_eps=1e-5, + vocab_size=128, + ) + ) + sched_mod.mx.eval(model.parameters()) + ns = Scheduler( + model, + SimpleNamespace(eos_token_id=2, encode=lambda s: [1]), + SchedulerConfig(prefill_step_size=64, paged_cache_block_size=0), + ) + ns.memory_monitor = _qwen4_monitor() + ns._prefill_min_chunk_tokens = 32 + footprint = [50 * _GB] + original_model = ns.model + + def forward(*args, **kwargs): + footprint[0] += _GB + return original_model(*args, **kwargs) + + ns.model = forward + monkeypatch.setattr(sched_mod, "get_phys_footprint", lambda: footprint[0]) + monkeypatch.setattr( + sched_mod, + "_sync_and_clear_cache", + lambda stream: footprint.__setitem__(0, 50 * _GB), + ) + charges = [] + original_adaptive = ns._adaptive_chunk_size + + def adaptive(n, **kwargs): + charges.append(ns._prefill_transient_tracker.flat_overhead_charge_for(True)) + return original_adaptive(n, **kwargs) + + ns._adaptive_chunk_size = adaptive + prompt = [10] * 193 + req = Request(request_id="loop", prompt=prompt, sampling_params=SamplingParams()) + req.prompt_token_ids = prompt + req.num_prompt_tokens = len(prompt) + if chunked: + state = _PrefillState( + request=req, + cache=make_prompt_cache(model), + tokens_remaining=sched_mod.mx.array(prompt[:-1])[None], + last_token=prompt[-1:], + tokens_processed=0, + base_size=0, + emitted_boundaries={}, + boundary_enabled=False, + block_size=0, + total_length=len(prompt), + ) + while not ns._step_prefill_chunk(state): + pass + else: + ns._do_external_prefill(req, prompt, make_prompt_cache(model)) + assert len(charges) == 3 + assert charges[0] == 0 + assert all(charge > 0 for charge in charges[1:]) + + +@pytest.mark.parametrize("route", [False, True]) +def test_qwen4_reallocation_charge_enforces_abort_cap_until_repaid(route): + ns = _throttle_ctx( + current=80 * _GB, + hard=100 * _GB, + monitor=_qwen4_monitor(), + reclaim_to=80 * _GB, + ) + ns._fake_current = 80 * _GB + tracker = ns._prefill_transient_tracker + tracker.observe_flat_overhead( + 512, + 31 * _GB, + static_bytes=_GB, + gathered_core=route, + ) + tracker.record_flat_reclaim(30 * _GB) + with pytest.raises(PrefillMemoryExceededError): + _guard_call(ns, 512, kv_len=180_000, gathered_core=route) + tracker.observe_flat_overhead( + 512, + 31 * _GB, + static_bytes=_GB, + gathered_core=route, + ) + assert tracker.flat_overhead_charge_for(route) == 0 + chosen = _guard_call(ns, 512, kv_len=180_000, gathered_core=route) + assert 32 <= chosen <= 512 + assert ns._fake_current + ns._predicted_chunk_transient( + chosen, 180_000, gathered_core=route + ) <= ns._prefill_abort_cap() + + def test_adaptive_throttle_tail_below_floor_never_grows_chunk(): """A throttled tail must not grow to the minimum chunk size.""" hard = 40 * _GB diff --git a/tests/test_prefill_transient_tracker.py b/tests/test_prefill_transient_tracker.py index 6f812a9ffd..e4028b922f 100644 --- a/tests/test_prefill_transient_tracker.py +++ b/tests/test_prefill_transient_tracker.py @@ -59,8 +59,21 @@ def test_incident_outlier_rejected_from_ewma(self): # ~/.omlx/logs/server.log 16:08:48-16:09:39 (KB/token), replayed as # (n_tokens=2048, transient_bytes) pairs. baseline_kb_per_token = [ - 1058.0, 1171.0, 1085.0, 1103.0, 1123.1, 1141.3, 991.2, 1131.2, - 1099.3, 1839.3, 1867.3, 1186.5, 1031.4, 1529.5, 1117.5, + 1058.0, + 1171.0, + 1085.0, + 1103.0, + 1123.1, + 1141.3, + 991.2, + 1131.2, + 1099.3, + 1839.3, + 1867.3, + 1186.5, + 1031.4, + 1529.5, + 1117.5, ] for kb in baseline_kb_per_token: t.update(n_tokens=2048, transient_bytes=int(kb * 1024 * 2048)) @@ -237,7 +250,6 @@ def test_fixed_overhead_is_not_scaled_by_token_count(self): 54, 571 * self.MB, static_bytes=self.MB, - request_id="r", ) assert t.flat_overhead_bytes_for(False) == 570 * self.MB assert t.flat_overhead_charge_for(False) == 0 @@ -248,30 +260,25 @@ def test_only_reclaimed_flat_overhead_is_charged_again(self): 2048, 28_536 * self.MB, static_bytes=1402 * self.MB, - request_id="r", ) t.observe_flat_overhead( 2048, 10_000 * self.MB, static_bytes=1402 * self.MB, - request_id="r", gathered_core=True, ) # The retained 27 GB is already included in current footprint. assert t.flat_overhead_charge_for(False) == 0 - t.record_external_reclaim( - "r", 12_500 * self.MB, gathered_core=False - ) + t.record_flat_reclaim(12500 * self.MB) assert t.flat_overhead_charge_for(False) == 12_500 * self.MB - assert t.flat_overhead_charge_for(True) == 0 + assert t.flat_overhead_charge_for(True) == (10_000 - 1402) * self.MB # The next positive delta repays that one-shot reallocation risk. t.observe_flat_overhead( 2048, 13_902 * self.MB, static_bytes=1402 * self.MB, - request_id="r", ) assert t.flat_overhead_charge_for(False) == 0 assert t.flat_overhead_bytes_for(False) == 27_134 * self.MB @@ -279,81 +286,76 @@ def test_only_reclaimed_flat_overhead_is_charged_again(self): def test_reclaim_debt_tracks_net_release(self): t = PrefillTransientTracker("qwen4") t.observe_flat_overhead( - 2048, -600 * self.MB, static_bytes=100 * self.MB, request_id="r" + 2048, + -600 * self.MB, + static_bytes=100 * self.MB, ) t.observe_flat_overhead( - 2048, -400 * self.MB, static_bytes=100 * self.MB, request_id="r" + 2048, + -400 * self.MB, + static_bytes=100 * self.MB, ) assert t.reclaim_debt_bytes_for(False) == 1000 * self.MB t.observe_flat_overhead( - 2048, 250 * self.MB, static_bytes=100 * self.MB, request_id="r" + 2048, + 250 * self.MB, + static_bytes=100 * self.MB, ) assert t.reclaim_debt_bytes_for(False) == 750 * self.MB def test_reallocation_does_not_become_new_flat_overhead(self): t = PrefillTransientTracker("qwen4") t.observe_flat_overhead( - 2048, 4 * 1024 * self.MB, static_bytes=1024 * self.MB, request_id="r" + 2048, + 4 * 1024 * self.MB, + static_bytes=1024 * self.MB, ) t.observe_flat_overhead( - 2048, -16 * 1024 * self.MB, static_bytes=1024 * self.MB, request_id="r" + 2048, + -16 * 1024 * self.MB, + static_bytes=1024 * self.MB, ) t.observe_flat_overhead( - 2048, 17 * 1024 * self.MB, static_bytes=1024 * self.MB, request_id="r" + 2048, + 17 * 1024 * self.MB, + static_bytes=1024 * self.MB, ) assert t.flat_overhead_bytes_for(False) == 3 * 1024 * self.MB assert t.reclaim_debt_bytes_for(False) == 0 - def test_plateau_requires_static_covered_same_width_samples(self): - t = PrefillTransientTracker("qwen4") - static = 1024 * self.MB - t.observe_flat_overhead( - 512, 2 * 1024 * self.MB, static_bytes=static, request_id="r" - ) - for _ in range(4): - t.observe_flat_overhead( - 512, 500 * self.MB, static_bytes=static, request_id="r" - ) - assert t.expansion_limit_for(False) == 0 - t.observe_flat_overhead( - 512, 500 * self.MB, static_bytes=static, request_id="r" - ) - assert t.expansion_limit_for(False) == 1024 - - t.observe_flat_overhead( - 512, -2 * 1024 * self.MB, static_bytes=static, request_id="r" - ) - assert t.expansion_limit_for(False) == 1024 - assert t.reclaim_debt_bytes_for(False) == 2 * 1024 * self.MB - - def test_plateau_expands_to_the_next_fixed_tier(self): - t = PrefillTransientTracker("qwen4") - for _ in range(5): - t.observe_flat_overhead( - 96, 0, static_bytes=100 * self.MB, request_id="r" - ) - assert t.expansion_limit_for(False) == 128 - - def test_plateau_permission_does_not_cross_requests(self): - t = PrefillTransientTracker("qwen4") - for _ in range(5): - t.observe_flat_overhead( - 512, 0, static_bytes=100 * self.MB, request_id="r1" - ) - assert t.expansion_limit_for(False, request_id="r1") == 1024 - assert t.expansion_limit_for(False, request_id="r2") == 0 - t.observe_flat_overhead( - 512, 0, static_bytes=100 * self.MB, request_id="r2" - ) - assert t.expansion_limit_for(False, request_id="r2") == 0 - def test_execution_regimes_are_independent(self): t = PrefillTransientTracker("qwen4") t.observe_flat_overhead( 2048, 500 * self.MB, static_bytes=100 * self.MB, - request_id="r", ) assert t.flat_overhead_bytes_for(False) == 400 * self.MB assert t.flat_overhead_bytes_for(True) == 0 + + +class TestPoolReleaseAccounting: + def test_repeated_releases_accumulate_without_exceeding_observed_overhead(self): + tracker = PrefillTransientTracker() + tracker.observe_flat_overhead(512, 5 * 1024**3, static_bytes=1024**3) + tracker.record_flat_reclaim(1024**3) + tracker.record_flat_reclaim(1024**3) + assert tracker.flat_overhead_charge_for(False) == 2 * 1024**3 + tracker.record_flat_reclaim(10 * 1024**3) + assert tracker.flat_overhead_charge_for(False) == 4 * 1024**3 + assert tracker.flat_overhead_charge_for(True) == 0 + + def test_pool_clear_covers_both_routes_without_sharing_their_overhead(self): + tracker = PrefillTransientTracker() + tracker.observe_flat_overhead(512, 5 * 1024**3, static_bytes=1024**3) + tracker.observe_flat_overhead( + 512, 2 * 1024**3, static_bytes=1024**3, gathered_core=True + ) + tracker.record_flat_reclaim(3 * 1024**3) + assert tracker.flat_overhead_charge_for(False) == 3 * 1024**3 + assert tracker.flat_overhead_charge_for(True) == 1024**3 + tracker.observe_flat_overhead( + 512, 2 * 1024**3, static_bytes=1024**3, gathered_core=True + ) + assert tracker.flat_overhead_charge_for(True) == 0 + assert tracker.flat_overhead_charge_for(False) == 3 * 1024**3 diff --git a/tests/test_qwen4_qsa_reservation_integration.py b/tests/test_qwen4_qsa_reservation_integration.py index 0758c77a9e..24d4e7ef1e 100644 --- a/tests/test_qwen4_qsa_reservation_integration.py +++ b/tests/test_qwen4_qsa_reservation_integration.py @@ -37,7 +37,7 @@ def test_chunked_reservation_includes_restored_prefix(snapshots_enabled): ) state = Scheduler._begin_prefill( ns, - SimpleNamespace(cached_tokens=128), + SimpleNamespace(cached_tokens=128, request_id="reservation"), [1] * 129, [cache, SimpleNamespace(offset=128)], ) @@ -46,10 +46,10 @@ def test_chunked_reservation_includes_restored_prefix(snapshots_enabled): lambda caches, tokens: Scheduler._reserve_qsa_index_capacity(ns, caches, tokens) ) - def stop(*args): + def stop(*args, **kwargs): raise RuntimeError("reservation complete") - ns._qwen4_text_gathered_pricing = stop + ns._adaptive_chunk_size = stop with pytest.raises(RuntimeError, match="reservation complete"): Scheduler._step_prefill_chunk(ns, state) assert cache._index_reserved_tokens >= 256 From 8827f0956f09ef31b1817aac3598b65ffe330e08 Mon Sep 17 00:00:00 2001 From: ivaniguarans Date: Sun, 6 Sep 2026 08:53:56 -0500 Subject: [PATCH 101/132] fix(scheduler): gate cache-freshness deferral on restorable overlap (#3367) An instant follow-up under 4096 prompt tokens skipped the in-flight store_cache deferral and raced the store, re-prefilling every turn (#3102). Replace the prompt-length floor with two per-candidate overlap gates: at least one restorable block must be shared, and the store must not exceed 16x the restorable overlap. --- omlx/scheduler.py | 39 ++++++--- tests/test_scheduler.py | 170 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 198 insertions(+), 11 deletions(-) diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 3e5a365af8..a39e689765 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -8235,13 +8235,23 @@ def _log_prefix_divergence(self, request: Request) -> None: f"{best_p}: stored=...{stored_ctx!r} vs prompt=...{prompt_ctx!r}" ) - # A 4K prompt is the smallest standard benchmark/workload where a missed - # async store is already a multi-second re-prefill. DeepSeek V4 boundary - # snapshots intentionally retain 3584 of 4096 prompt tokens, and their SSD - # write can finish just after the first HTTP response is returned. Include - # this workload class in the non-blocking freshness deferral so an immediate - # repeated turn waits for that relevant store instead of racing it. - _CACHE_FRESHNESS_WAIT_MIN_PROMPT_TOKENS = 4096 + # Whether an in-flight store_cache is worth waiting for is decided by the + # overlap with it, not by the prompt's length. What a wait can save is the + # re-prefill of the restorable overlap (whole blocks of the effective + # paged_cache_block_size -- 256 for KV models, the 2048-token boundary when + # the GDN split is active); what it costs is bounded by the store's own + # duration, which scales with the tokens THAT store copies (~13-20 us/token + # measured on M5 Max, hot cache off) while prefill costs ~0.6-5 ms/token + # across current models and machines. So: never wait when less than one + # block is restorable (nothing a wait could make visible), and never wait on + # a store more than 16x larger than the overlap (a harness side-request + # that shares only the system prompt with a 100K-token turn being stored), + # which keeps the worst-case wait well under the prefill it avoids. A fixed + # prompt floor (8192, then 4096 for the DeepSeek V4 3584-of-4096 boundary + # snapshot, #2471) reproduced the race one notch lower each time: agent + # harnesses firing a 3K follow-up instantly re-prefilled every turn (#3102). + # The 4K boundary-snapshot case still waits under the overlap gates. + _CACHE_FRESHNESS_WAIT_MAX_STORE_TO_OVERLAP = 16 _CACHE_FRESHNESS_WAIT_MIN_COMMON_TOKENS = 8192 _CACHE_FRESHNESS_WAIT_MIN_PROMPT_RATIO = 0.30 _CACHE_FRESHNESS_WAIT_TIMEOUT_S = 4.0 @@ -8267,8 +8277,7 @@ def _find_relevant_inflight_store( return None prompt = request.prompt_token_ids or [] - if len(prompt) < self._CACHE_FRESHNESS_WAIT_MIN_PROMPT_TOKENS: - return None + block = max(1, self.config.paged_cache_block_size) best_rid: str | None = None best_future: concurrent.futures.Future | None = None @@ -8281,6 +8290,18 @@ def _find_relevant_inflight_store( continue common = self._common_prefix_len(prompt, info.tokens) + # Per-candidate: only whole blocks can be restored, and a store far + # larger than the overlap costs more to wait for than it saves. A + # longest-overlap store that fails here must not veto a smaller + # store that passes, so filter before ranking. + restorable = (common // block) * block + if restorable < block: + continue + if ( + len(info.tokens) + > self._CACHE_FRESHNESS_WAIT_MAX_STORE_TO_OVERLAP * restorable + ): + continue if common > best_common: best_rid = rid best_future = future diff --git a/tests/test_scheduler.py b/tests/test_scheduler.py index 3d87b48543..7ba3c64a2a 100644 --- a/tests/test_scheduler.py +++ b/tests/test_scheduler.py @@ -979,13 +979,14 @@ def test_admission_does_not_defer_below_common_and_ratio_thresholds( assert scheduler._should_defer_for_cache_freshness(request) is False assert request.request_id not in scheduler._cache_freshness_waits - def test_admission_does_not_defer_for_short_prompt_even_with_high_ratio( + def test_admission_defers_for_short_prompt_with_restorable_overlap( self, mock_model, mock_tokenizer ): - """Prompts below the freshness minimum should never wait on store_cache.""" + """A sub-4K follow-up waits when whole blocks of the store are reusable (#3102).""" scheduler = Scheduler(model=mock_model, tokenizer=mock_tokenizer) scheduler.block_aware_cache = MagicMock() prompt = list(range(4095)) + scheduler.block_aware_cache.fetch_cache.return_value = (None, prompt) future = MagicMock() future.done.return_value = False @@ -1005,9 +1006,174 @@ def test_admission_does_not_defer_for_short_prompt_even_with_high_ratio( future.result.assert_not_called() scheduler.block_aware_cache.fetch_cache.assert_not_called() + assert scheduler._should_defer_for_cache_freshness(request) is True + assert request.request_id in scheduler._cache_freshness_waits + wait = scheduler._cache_freshness_waits[request.request_id] + assert wait.store_request_id == "req-prev" + assert wait.common_prefix == 3584 + + future.done.return_value = True + assert scheduler._should_defer_for_cache_freshness(request) is False + scheduler._prepare_prefix_cache_for_request(request) + scheduler.block_aware_cache.fetch_cache.assert_called_once() + future.result.assert_not_called() + + def test_admission_defers_for_instant_follow_up_on_gdn_boundary_store( + self, mock_model, mock_tokenizer + ): + """The live #3102 shape: 2875-token turn 2 vs a 2048-token boundary store.""" + scheduler = Scheduler(model=mock_model, tokenizer=mock_tokenizer) + scheduler.block_aware_cache = MagicMock() + scheduler.config.paged_cache_block_size = 2048 + prompt = list(range(2875)) + + future = MagicMock() + future.done.return_value = False + scheduler._inflight_store_futures["req-prev"] = future + scheduler._inflight_store_info["req-prev"] = ( + scheduler_module._InflightStoreInfo(tokens=list(range(2048))) + ) + + request = Request( + request_id="req-next", + prompt=prompt, + sampling_params=SamplingParams(max_tokens=16), + ) + + scheduler.add_request(request) + + assert scheduler._should_defer_for_cache_freshness(request) is True + assert request.request_id in scheduler._cache_freshness_waits + future.result.assert_not_called() + + @pytest.mark.parametrize( + ("block_size", "prompt_len", "store_len", "expected"), + [ + # Less than one 256-token block is restorable: nothing to wait for. + (256, 3000, 200, False), + # A 2000-token overlap never reaches the 2048 GDN boundary block. + (2048, 3000, 2000, False), + # Exactly one full block is restorable: wait. + (256, 300, 256, True), + ], + ) + def test_admission_freshness_gate_requires_one_restorable_block( + self, mock_model, mock_tokenizer, block_size, prompt_len, store_len, expected + ): + scheduler = Scheduler(model=mock_model, tokenizer=mock_tokenizer) + scheduler.block_aware_cache = MagicMock() + scheduler.config.paged_cache_block_size = block_size + prompt = list(range(prompt_len)) + + future = MagicMock() + future.done.return_value = False + scheduler._inflight_store_futures["req-prev"] = future + scheduler._inflight_store_info["req-prev"] = ( + scheduler_module._InflightStoreInfo(tokens=list(range(store_len))) + ) + + request = Request( + request_id="req-next", + prompt=prompt, + sampling_params=SamplingParams(max_tokens=16), + ) + + scheduler.add_request(request) + + assert scheduler._should_defer_for_cache_freshness(request) is expected + assert (request.request_id in scheduler._cache_freshness_waits) is expected + future.result.assert_not_called() + + @pytest.mark.parametrize( + ("prompt_len", "overlap", "store_len", "expected"), + [ + # A side-request sharing one 2048-token block with a 100K-token + # store: the wait would dwarf the prefill it saves. + (2300, 2048, 100_000, False), + # Exactly 16x the restorable overlap still waits ... + (2300, 2048, 16 * 2048, True), + # ... one token past it does not. + (2300, 2048, 16 * 2048 + 1, False), + # Applies above 4K too: a 5K prompt reusing 4096 of a 100K store. + (5000, 4096, 100_000, False), + ], + ) + def test_admission_freshness_gate_bounds_store_size_by_overlap( + self, mock_model, mock_tokenizer, prompt_len, overlap, store_len, expected + ): + scheduler = Scheduler(model=mock_model, tokenizer=mock_tokenizer) + scheduler.block_aware_cache = MagicMock() + stored = list(range(store_len)) + # The prompt diverges from the stored sequence right after `overlap`. + prompt = stored[:overlap] + list(range(10**6, 10**6 + prompt_len - overlap)) + + future = MagicMock() + future.done.return_value = False + scheduler._inflight_store_futures["req-prev"] = future + scheduler._inflight_store_info["req-prev"] = ( + scheduler_module._InflightStoreInfo(tokens=stored) + ) + + request = Request( + request_id="req-next", + prompt=prompt, + sampling_params=SamplingParams(max_tokens=16), + ) + + scheduler.add_request(request) + + assert scheduler._should_defer_for_cache_freshness(request) is expected + assert (request.request_id in scheduler._cache_freshness_waits) is expected + future.result.assert_not_called() + + def test_admission_freshness_gate_filters_candidates_before_ranking( + self, mock_model, mock_tokenizer + ): + """An oversized longest-overlap store must not veto a smaller eligible one.""" + scheduler = Scheduler(model=mock_model, tokenizer=mock_tokenizer) + scheduler.block_aware_cache = MagicMock() + big_store = list(range(100_000)) + prompt = big_store[:2048] + list(range(10**6, 10**6 + 2300 - 2048)) + # Shares the first 1024 tokens with the prompt, then diverges. + small_store = big_store[:1024] + list(range(2 * 10**6, 2 * 10**6 + 2300 - 1024)) + + big_future = MagicMock() + big_future.done.return_value = False + small_future = MagicMock() + small_future.done.return_value = False + scheduler._inflight_store_futures["req-big"] = big_future + scheduler._inflight_store_info["req-big"] = scheduler_module._InflightStoreInfo( + tokens=big_store + ) + scheduler._inflight_store_futures["req-small"] = small_future + scheduler._inflight_store_info["req-small"] = ( + scheduler_module._InflightStoreInfo(tokens=small_store) + ) + + request = Request( + request_id="req-next", + prompt=prompt, + sampling_params=SamplingParams(max_tokens=16), + ) + + scheduler.add_request(request) + + assert scheduler._should_defer_for_cache_freshness(request) is True + wait = scheduler._cache_freshness_waits[request.request_id] + assert wait.store_request_id == "req-small" + assert wait.common_prefix == 1024 + big_future.result.assert_not_called() + small_future.result.assert_not_called() + + # With the only eligible store already visible, nothing is left to wait on. + scheduler._cache_freshness_waits.clear() + small_future.done.return_value = True assert scheduler._should_defer_for_cache_freshness(request) is False assert request.request_id not in scheduler._cache_freshness_waits + def test_scheduler_has_no_prompt_length_freshness_floor(self): + assert not hasattr(Scheduler, "_CACHE_FRESHNESS_WAIT_MIN_PROMPT_TOKENS") + def test_admission_defers_for_immediate_4k_boundary_store( self, mock_model, mock_tokenizer ): From b20f4564886959abc5e633d45c6dca0d426e3f9f Mon Sep 17 00:00:00 2001 From: apcooley Date: Sun, 6 Sep 2026 07:59:56 -0600 Subject: [PATCH 102/132] fix(scheduler): recover boundary-aligned live cache stores (#3288) When every decode-time boundary capture is skipped by the MTP skew guard, the store path raised _BoundaryStoreUnavailable and dropped the recurrent state, so a growing agent context never persisted a reusable prefix and re-prefilled every turn. If the request finishes exactly on a block boundary, verify the live cache leaf offset sits on that boundary and store it instead of giving up. Adds _verify_live_boundary_aligned and store-time recovery in _cleanup_finished, plus tests for the on-boundary (store) and off-boundary (skip) cases. --- omlx/scheduler.py | 113 +++++++++++++++++++++++++++++++++++++++- tests/test_scheduler.py | 71 +++++++++++++++++++++++++ 2 files changed, 183 insertions(+), 1 deletion(-) diff --git a/omlx/scheduler.py b/omlx/scheduler.py index a39e689765..0ccb681307 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -7498,6 +7498,61 @@ def _extract_live_request_cache_for_store( ) return None + def _verify_live_boundary_aligned( + self, request_id: str, uid: int, boundary_tokens: int + ) -> list[dict[str, Any]] | None: + """Return extracted cache state iff the live cache is exactly at a block + boundary, else None. + + Recovery path for the store-time ``_BoundaryStoreUnavailable`` case: when + every decode-time boundary capture was skipped (MTP skew guard) but the + request finished on a block boundary, the live recurrent/rotating state + sits at that boundary and is safe to persist. The leaf cache ``offset`` + must equal the boundary token count exactly — mirroring + ``_extract_boundary_snapshot``'s positional-consistency guard — so we + never label an off-boundary state with a block-boundary count. + """ + if self.batch_generator is None or uid is None or uid < 0: + return None + try: + with self._phase_timer("store_cache_boundary_verify"): + _safe_sync_stream(self._stream) + with mx.stream(self._stream): + result = self.batch_generator.extract_cache([uid]) + if uid not in result: + logger.debug( + "Cannot verify live cache for %s: uid %s not present", + request_id, + uid, + ) + return None + cache_list, _tokens = result[uid] + for c in cache_list: + offset = _first_leaf_cache_offset(c) + if offset is None: + continue + if offset != boundary_tokens: + logger.debug( + "Live cache for %s is off-boundary (offset %d != boundary %d); " + "skipping recovery store", + request_id, + offset, + boundary_tokens, + ) + return None + break + extracted_cache, _ = self._extract_cache_states(cache_list) + if not extracted_cache: + return None + return extracted_cache + except Exception as e: + logger.debug( + "Failed to verify live cache for boundary store %s: %s", + request_id, + e, + ) + return None + def _prepare_prompt_boundary_cache_store( self, request_id: str, @@ -11564,7 +11619,63 @@ def _cleanup_finished(self, finished_ids: set[str]) -> None: # the current decode offset (which # speculative decode can leave off # the emitted count entirely). - raise _BoundaryStoreUnavailable() + # + # Recovery: when every decode-time + # capture was skipped (MTP skew + # guard) but the request itself + # finished on a block boundary, the + # live extracted cache is exactly + # that boundary-aligned snapshot — + # storing it is safe and recovers + # prefix reuse instead of throwing + # away a usable recurrent state. + block_size = ( + self.config.paged_cache_block_size + ) + live_cache = None + if ( + block_size > 0 + and len(cacheable_sequence) + % block_size + == 0 + ): + # Only trust the live state when + # its leaf cache offset actually + # sits on the boundary (emitted + # length alone can be fooled by + # the MTP emit queue). uid_for_store + # may be unset when this request + # carried its own _extracted_cache, + # so resolve it here. + live_uid = ( + self.request_id_to_uid.get( + request_id, -1 + ) + ) + live_cache = ( + self._verify_live_boundary_aligned( + request_id, + live_uid, + len(cacheable_sequence), + ) + ) + if live_cache: + token_sequence_to_store = ( + cacheable_sequence + ) + cache_to_store = live_cache + intermediate_snapshots = None + logger.info( + "Using live boundary-aligned " + "cache for %s: request finished " + "on block boundary " + "(%d/%d tokens)", + request_id, + len(cacheable_sequence), + len(full_token_sequence), + ) + else: + raise _BoundaryStoreUnavailable() if boundary_override is not None: ( token_sequence_to_store, diff --git a/tests/test_scheduler.py b/tests/test_scheduler.py index 7ba3c64a2a..d060d09f5b 100644 --- a/tests/test_scheduler.py +++ b/tests/test_scheduler.py @@ -2990,6 +2990,77 @@ def test_prefix_lookup_observation_explains_reprefill_boundary( "unreused_common_prefix_tokens": 3, } + def test_cleanup_finished_recovery_stores_boundary_aligned_live_cache( + self, mock_model, mock_tokenizer + ): + """Fix A recovery: when every decode-time capture was skipped by the + MTP skew guard but the request finished on a block boundary, the + scheduler stores the verified boundary-aligned live cache instead of + dropping it — preserving prefix-cache reuse on the next turn.""" + config = SchedulerConfig(paged_cache_block_size=4) + scheduler = Scheduler(model=mock_model, tokenizer=mock_tokenizer, config=config) + scheduler.block_aware_cache = MagicMock() + scheduler.paged_cache_manager = None + scheduler._boundary_snapshot_required = True + + request = Request( + request_id="req-recover", + prompt="hello", + sampling_params=SamplingParams(), + ) + request.prompt_token_ids = [1, 2, 3, 4] + request.num_prompt_tokens = 4 + request.output_token_ids = [5, 6, 7, 8] # Total = 8 (2 full blocks) + request._extracted_cache = [{"state": "live-cache"}] + request._model_cache_config = "live-config" + + scheduler.running["req-recover"] = request + scheduler.requests["req-recover"] = request + # Live cache verifies as boundary-aligned (offset == 8 == total). + scheduler._verify_live_boundary_aligned = MagicMock( + return_value=[{"state": "boundary-live-cache"}] + ) + + scheduler._cleanup_finished({"req-recover"}) + + scheduler.block_aware_cache.store_cache.assert_called_once() + args, kwargs = scheduler.block_aware_cache.store_cache.call_args + assert args[0] == "req-recover" + assert args[1] == [1, 2, 3, 4, 5, 6, 7, 8] # full boundary-aligned sequence + + def test_cleanup_finished_recovery_skips_off_boundary_live_cache( + self, mock_model, mock_tokenizer + ): + """Fix A recovery must NOT store when the request finished off a block + boundary — the live recurrent state cannot be labeled with a boundary + token count and would corrupt later prefix hits.""" + config = SchedulerConfig(paged_cache_block_size=4) + scheduler = Scheduler(model=mock_model, tokenizer=mock_tokenizer, config=config) + scheduler.block_aware_cache = MagicMock() + scheduler.paged_cache_manager = None + scheduler._boundary_snapshot_required = True + + request = Request( + request_id="req-off-boundary", + prompt="hello", + sampling_params=SamplingParams(), + ) + request.prompt_token_ids = [1, 2, 3, 4] + request.num_prompt_tokens = 4 + request.output_token_ids = [5, 6, 7] # Total = 7 (not a full block) + request._extracted_cache = [{"state": "live-cache"}] + request._model_cache_config = "live-config" + + scheduler.running["req-off-boundary"] = request + scheduler.requests["req-off-boundary"] = request + + scheduler._cleanup_finished({"req-off-boundary"}) + + scheduler.block_aware_cache.store_cache.assert_not_called() + scheduler.block_aware_cache.clear_request_entry.assert_called_with( + "req-off-boundary" + ) + def test_cleanup_finished_skips_output_tokens_for_reasoning_model( self, mock_model, mock_tokenizer ): From 638f82ec3162413f1421575c10e3e98040053cad Mon Sep 17 00:00:00 2001 From: pedroberaldo87 <134068505+pedroberaldo87@users.noreply.github.com> Date: Sun, 6 Sep 2026 11:02:42 -0300 Subject: [PATCH 103/132] perf: separate affine MoE dispatch thresholds (#3409) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A single 64-route gate turned on both route sorting and the native affine block kernels. Measured on M1 Ultra with real GLM-5.3-Flash expert weights (2-bit, group 64), per layer: sorting pays off from 32 routes, but the block kernels only beat mx.gather_qmm from ~1024 routes (the crossover is at T=128 x 8 experts); between 64 and ~900 routes they cost 2-2.7x. Decode and the MTP verify window live exactly in that band. Split the gate: sort from 32 routes, block kernels from 1024. Server, batch of 8 (B=8, 300 tokens each): 278.5 -> 173.5 ms/step, 28.7 -> 46.1 tok/s. Prefill (chunks >= 512 tokens, >= 4096 routes) stays on the block kernels. Both thresholds are environment-overridable (OMLX_DEEPSEEK_SORT_MIN_ROUTES, OMLX_DEEPSEEK_AFFINE_BLOCK_MIN_ROUTES), like the mxfp4 neighbour: they were tuned on one machine. The two existing block-kernel parity tests now feed 512 tokens x 2 experts = 1024 routes — the smallest count at which the kernels engage — and a new decision test checks the threshold without the Metal kernel present. Co-authored-by: Pedro Beraldo --- omlx/patches/deepseek_v4/switch_layers.py | 28 +++++++++- tests/test_deepseek_v4_patch.py | 45 ++++++++++++++++ tests/test_glm_moe_dsa_patch.py | 63 ++++++++++++++++++++--- 3 files changed, 128 insertions(+), 8 deletions(-) diff --git a/omlx/patches/deepseek_v4/switch_layers.py b/omlx/patches/deepseek_v4/switch_layers.py index 6b1d4c57dd..e6a9ee89a9 100644 --- a/omlx/patches/deepseek_v4/switch_layers.py +++ b/omlx/patches/deepseek_v4/switch_layers.py @@ -21,6 +21,29 @@ _DEEPSEEK_MXFP4_LARGE_BLOCK_BM = 32 _DEEPSEEK_MXFP4_LARGE_BLOCK_VARIANT = 2 _DEEPSEEK_AFFINE_LARGE_BLOCK_MIN_ROUTES = 8192 +# Below this many (token, expert) routes the stock unsorted gather_qmm runs; +# at/above it routes are sorted by expert. Measured on M1 Ultra, GLM-5.3 oQ2e +# (affine 2-bit, g64), one MoE layer, ms per layer: +# T=4: unsorted 1.23 · sorted stock 1.11 · sorted native blocks 2.95 +# T=8: unsorted 2.10 · sorted stock 1.91 · sorted native blocks 5.13 +# T=64: unsorted 12.3 · sorted stock 10.7 · sorted native blocks 15.8 +# T=128: unsorted 24.2 · sorted stock 20.9 · sorted native blocks 19.4 +# Sorting pays from T=4 (32 routes); the affine block kernel only pays past +# ~900 routes, so it has its own floor below. The old single threshold of 64 +# routes sent every 8..110-token window (DFlash block-8 verify, batched +# decode at B>=8) down the block kernel at 2-2.7x the cost. +# Route-count crossovers for the affine (oQ 2/3-bit) MoE path, measured on +# M1 Ultra with real GLM-5.3-Flash expert weights (2-bit, group 64): +# - sorting the routes pays off from 32 routes; +# - the native block kernels only beat mx.gather_qmm from ~1024 routes +# (the crossover sits at T=128 x 8 experts); below it they cost 2-2.7x. +# The single 64-route gate that engaged both at once sat exactly in the +# losing region. Same pattern as _DEEPSEEK_MXFP4_LARGE_BLOCK_MIN_ROUTES below: +# tuned on one machine, overridable per deployment. +_SORT_MIN_ROUTES = int(os.environ.get("OMLX_DEEPSEEK_SORT_MIN_ROUTES", "32")) +_AFFINE_NATIVE_MIN_ROUTES = int( + os.environ.get("OMLX_DEEPSEEK_AFFINE_BLOCK_MIN_ROUTES", "1024") +) # Tuned on M3 Ultra. Set this to 8192 to restore the previous crossover on # other pre-NAX chips; M5 prefill uses the NAX fallback below. _DEEPSEEK_MXFP4_LARGE_BLOCK_MIN_ROUTES = int( @@ -243,6 +266,7 @@ def _can_use_affine_blocks(self, x, sorted_indices: bool, dtype=None) -> bool: sorted_indices and x.ndim == 3 and x.shape[-2] == 1 + and int(x.shape[0]) >= _AFFINE_NATIVE_MIN_ROUTES and dtype in (mx.float16, mx.bfloat16) and self.group_size == 64 and self.bits in (2, 3) @@ -417,7 +441,7 @@ def __call__(self, x, indices, scores=None, weighted_sum=False) -> mx.array: x = mx.expand_dims(x, (-2, -3)) original_dtype = x.dtype - do_sort = indices.size >= 64 + do_sort = indices.size >= _SORT_MIN_ROUTES idx = indices inv_order = None if do_sort: @@ -595,7 +619,7 @@ def __init__( def __call__(self, x, indices) -> mx.array: x = mx.expand_dims(x, (-2, -3)) - do_sort = indices.size >= 64 + do_sort = indices.size >= _SORT_MIN_ROUTES idx = indices inv_order = None if do_sort: diff --git a/tests/test_deepseek_v4_patch.py b/tests/test_deepseek_v4_patch.py index 7659cb3d2c..32e74dafcb 100644 --- a/tests/test_deepseek_v4_patch.py +++ b/tests/test_deepseek_v4_patch.py @@ -2370,3 +2370,48 @@ def test_tile_stays_under_int32_index_limit(self, applied_patch): _, dm = self._reduce_and_ref() assert 64 * 512 * dm._INDEXER_POOL_TILE < 2**31 assert dm._INDEXER_MAX_ELEMS < 2**31 + + +class TestAffineBlockRouteThreshold: + """The affine block kernels must not engage below the measured crossover: + at 64 routes they cost 2-2.7x the plain gather (M1 Ultra, GLM-5.3-Flash + 2-bit experts). The decision is testable without the Metal kernel.""" + + def _linear(self): + from omlx.patches.deepseek_v4 import switch_layers as sl + + import mlx.core as mx + + linear = sl.QuantizedSwitchLinear( + 64, 64, num_experts=2, bias=False, group_size=64, bits=2 + ) + # affine metadata in the activation dtype, as a loaded oQ checkpoint has + linear.scales = linear.scales.astype(mx.bfloat16) + if linear.get("biases") is None: + linear.biases = mx.zeros_like(linear.scales) + linear.biases = linear.biases.astype(mx.bfloat16) + return linear + + def test_affine_blocks_engage_only_from_the_route_threshold(self, monkeypatch): + import mlx.core as mx + + from omlx.patches.deepseek_v4 import switch_layers as sl + + monkeypatch.setattr(sl.glm_fast, "has_symbol", lambda name: True) + linear = self._linear() + below = mx.zeros((sl._AFFINE_NATIVE_MIN_ROUTES - 1, 1, 64), dtype=mx.bfloat16) + at = mx.zeros((sl._AFFINE_NATIVE_MIN_ROUTES, 1, 64), dtype=mx.bfloat16) + assert linear._can_use_affine_blocks(below, sorted_indices=True) is False + assert linear._can_use_affine_blocks(at, sorted_indices=True) is True + # unsorted routes never take the block path, whatever the count + assert linear._can_use_affine_blocks(at, sorted_indices=False) is False + + def test_thresholds_default_to_the_measured_crossovers(self): + from omlx.patches.deepseek_v4 import switch_layers as sl + + assert sl._SORT_MIN_ROUTES == 32 + assert sl._AFFINE_NATIVE_MIN_ROUTES == 1024 + # both are environment-overridable, like the mxfp4 neighbour + src = open(sl.__file__, encoding="utf-8").read() + assert "OMLX_DEEPSEEK_SORT_MIN_ROUTES" in src + assert "OMLX_DEEPSEEK_AFFINE_BLOCK_MIN_ROUTES" in src diff --git a/tests/test_glm_moe_dsa_patch.py b/tests/test_glm_moe_dsa_patch.py index 4d454a92dc..c5d7622081 100644 --- a/tests/test_glm_moe_dsa_patch.py +++ b/tests/test_glm_moe_dsa_patch.py @@ -821,15 +821,18 @@ def single_spy(*args, **kwargs): monkeypatch.setattr(fast, "deepseek_affine_gather_qmm_pair_concat_blocks", pair_spy) monkeypatch.setattr(fast, "deepseek_affine_gather_qmm_blocks", single_spy) - x = mx.random.normal((1, 32, 128), dtype=mx.bfloat16) + # 512 tokens x 2 = 1024 routes: the affine block kernels only engage from + # _AFFINE_NATIVE_MIN_ROUTES (below that the sorted stock gather_qmm is + # faster — measured in switch_layers.py). + x = mx.random.normal((1, 512, 128), dtype=mx.bfloat16) indices = mx.array( - [[[(i + j) % 8 for j in range(2)] for i in range(32)]], + [[[(i + j) % 8 for j in range(2)] for i in range(512)]], dtype=mx.int32, ) y = model(x, indices) mx.eval(y) - assert y.shape == (1, 32, 2, 128) + assert y.shape == (1, 512, 2, 128) assert calls == {"pair": 1, "single": 1} @@ -882,16 +885,19 @@ def single_spy(x, *args, **kwargs): monkeypatch.setattr(fast, "deepseek_affine_gather_qmm_pair_concat_blocks", pair_spy) monkeypatch.setattr(fast, "deepseek_affine_gather_qmm_blocks", single_spy) - x = mx.random.normal((1, 32, 128), dtype=mx.bfloat16) + # 512 tokens x 2 = 1024 routes: the affine block kernels only engage from + # _AFFINE_NATIVE_MIN_ROUTES (below that the sorted stock gather_qmm is + # faster — measured in switch_layers.py). + x = mx.random.normal((1, 512, 128), dtype=mx.bfloat16) indices = mx.array( - [[[(i + j) % 8 for j in range(2)] for i in range(32)]], + [[[(i + j) % 8 for j in range(2)] for i in range(512)]], dtype=mx.int32, ) y = model(x, indices) mx.eval(y) assert y.dtype == mx.bfloat16 - assert y.shape == (1, 32, 2, 128) + assert y.shape == (1, 512, 2, 128) assert calls == { "pair": 1, "single": 1, @@ -1328,3 +1334,48 @@ def test_glm_adaptive_decode_clears_only_on_the_512_step_cadence(): assert bg._steps_counter == 1 assert streams == [] + + +def test_deepseek_switchglu_keeps_small_windows_off_the_block_kernels(monkeypatch): + """8..110-token windows (DFlash block-8 verify, batched decode) used to be + sent down the affine block kernel at 2-2.7x the cost of the sorted stock + gather_qmm (measured on M1 Ultra, GLM-5.3 oQ2e). Below + _AFFINE_NATIVE_MIN_ROUTES the block kernel must stay out.""" + mx = pytest.importorskip("mlx.core") + pytest.importorskip("mlx.nn") + from omlx.custom_kernels.glm_moe_dsa import fast + from omlx.patches.deepseek_v4 import switch_layers as sl + from omlx.patches.deepseek_v4.switch_layers import SwitchGLU + + if not fast.is_native_available() or not fast.has_symbol( + "deepseek_affine_gather_qmm_blocks" + ): + pytest.skip("native affine block kernels unavailable") + + mx.random.seed(23) + model = SwitchGLU(128, 64, 8) + for name in ("gate_proj", "up_proj", "down_proj"): + layer = getattr(model, name).to_quantized(group_size=64, bits=2, mode="affine") + layer.scales = layer.scales.astype(mx.float16) + layer.biases = layer.biases.astype(mx.float16) + setattr(model, name, layer) + + calls = {"single": 0} + orig_single = fast.deepseek_affine_gather_qmm_blocks + + def single_spy(*args, **kwargs): + calls["single"] += 1 + return orig_single(*args, **kwargs) + + monkeypatch.setattr(fast, "deepseek_affine_gather_qmm_blocks", single_spy) + + x = mx.random.normal((1, 8, 128), dtype=mx.float16) # 8 tokens x 8 = 64 routes + indices = mx.array( + [[[(i + j) % 8 for j in range(8)] for i in range(8)]], dtype=mx.int32 + ) + assert indices.size >= sl._SORT_MIN_ROUTES + assert indices.size < sl._AFFINE_NATIVE_MIN_ROUTES + y = model(x, indices) + mx.eval(y) + assert y.shape == (1, 8, 8, 128) + assert calls == {"single": 0} From 163b5273141326148af4a177fe4c4b30cbb6c988 Mon Sep 17 00:00:00 2001 From: ddark-il <44260906+ddark-il@users.noreply.github.com> Date: Sun, 6 Sep 2026 17:03:46 +0300 Subject: [PATCH 104/132] fix: segment oversized M5 sorted gather calls (#3432) The M5 reroute (issue #2267) dropped `sorted_indices` for any sorted rhs gather_qmm call above 32768 rows to dodge the int16 row-offset overflow in the NAX rhs kernel (ml-explore/mlx#3856, fixed upstream by ml-explore/mlx#3922 only after the 0.32.2 release). The unsorted gather path is ~8x slower per MoE layer on M5 Max, so a 4096-token prefill chunk of a top-8 MoE (32768 rows is the cap, 4097+ tokens cross it) or a top-10 MoE (Qwen4-Exp crosses at 3277 tokens) paid far more than the wider chunk saved. The kernel is only wrong because one call exceeds the cap, so keep the flag and issue the call as balanced <=32768-row slices of the already sorted activations/indices, concatenating the partial outputs. Slices stay on the NAX rhs kernel; balanced sizes keep each slice above mlx's `rows / experts >= 4` gate for the batched rhs path. Only the layout the MoE sorted path produces (`[rows, 1, K]` activations with a flat sorted `rhs_indices`) is segmented; other layouts and `K % 64 != 0` keep the existing demotion. benchmarks/bench_m5_sorted_gather_chunk.py reproduces one Qwen4-Exp MoE layer (512 experts, top-10, 2560/640, q4 gs64, fused gate+up) on M5 Max / mlx 0.32.2: chunk rows mode ms/layer tok/s 2048 20480 sorted 24.5 83.6k 4096 40960 unsorted 273.5 15.0k (previous reroute) 4096 40960 segmented 33.2 123.3k 8192 81920 unsorted 552.4 14.8k (previous reroute) 8192 81920 segmented 61.3 133.6k Claude-Session: https://claude.ai/code/session_01FUwVt6F1YHbTLvNvmAGEvU Co-authored-by: Claude Fable 5.1 --- benchmarks/bench_m5_sorted_gather_chunk.py | 135 +++++++++++++++++++++ omlx/patches/m5_gather_qmm.py | 80 ++++++++++-- tests/test_m5_gather_qmm.py | 94 ++++++++++++++ 3 files changed, 298 insertions(+), 11 deletions(-) create mode 100644 benchmarks/bench_m5_sorted_gather_chunk.py diff --git a/benchmarks/bench_m5_sorted_gather_chunk.py b/benchmarks/bench_m5_sorted_gather_chunk.py new file mode 100644 index 0000000000..6dd29f7c77 --- /dev/null +++ b/benchmarks/bench_m5_sorted_gather_chunk.py @@ -0,0 +1,135 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Per-layer MoE prefill cost vs chunk width on M5 (sorted gather_qmm paths). + +Reproduces one routed-expert MoE layer at a configurable geometry (default: +Qwen4-Exp, 512 experts / top-10 / hidden 2560 / inter 640, 4-bit gs64 with +the fused gate+up layout) and times the sorted SwitchGLU path for several +prefill chunk widths under three dispatch modes: + +- ``sorted`` raw ``sorted_indices=True`` (NAX rhs kernel; corrupt past + 32768 rows on mlx <= 0.32.2, timed for reference only) +- ``unsorted`` what the pre-segmenting M5 reroute did past the row cap +- ``segmented`` the oMLX reroute with <=32768-row sorted slices + +Prints ms per layer call and derived tokens/s so the chunk-width policy can +be judged on numbers. Run from a checkout with the reroute installed:: + + python benchmarks/bench_m5_sorted_gather_chunk.py --chunks 2048 4096 8192 +""" + +from __future__ import annotations + +import argparse +import time + +import mlx.core as mx +from mlx_lm.models.switch_layers import _gather_sort, _scatter_unsort + +import omlx.patches.m5_gather_qmm as reroute + + +def _build(experts, hidden, inter, bits, group_size, key): + k1, k2 = mx.random.split(key) + gate_up = mx.random.normal((experts, 2 * inter, hidden), key=k1) * 0.02 + down = mx.random.normal((experts, hidden, inter), key=k2) * 0.02 + gu = mx.quantize(gate_up.astype(mx.bfloat16), group_size=group_size, bits=bits) + dn = mx.quantize(down.astype(mx.bfloat16), group_size=group_size, bits=bits) + mx.eval(*gu, *dn) + return gu, dn + + +def _layer(x, inds, gu, dn, bits, group_size, sorted_flag, gather_qmm): + x5 = mx.expand_dims(x, (-2, -3)) + xs, idx, inv = _gather_sort(x5, inds) + h = gather_qmm( + xs, + *gu, + rhs_indices=idx, + transpose=True, + group_size=group_size, + bits=bits, + sorted_indices=sorted_flag, + ) + g, u = mx.split(h, 2, axis=-1) + a = mx.sigmoid(g) * g * u + y = gather_qmm( + a, + *dn, + rhs_indices=idx, + transpose=True, + group_size=group_size, + bits=bits, + sorted_indices=sorted_flag, + ) + return _scatter_unsort(y, inv, inds.shape).squeeze(-2) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--experts", type=int, default=512) + ap.add_argument("--topk", type=int, default=10) + ap.add_argument("--hidden", type=int, default=2560) + ap.add_argument("--inter", type=int, default=640) + ap.add_argument("--bits", type=int, default=4) + ap.add_argument("--group-size", type=int, default=64) + ap.add_argument("--chunks", type=int, nargs="+", default=[2048, 4096, 8192]) + ap.add_argument("--iters", type=int, default=5) + ap.add_argument("--modes", nargs="+", default=["sorted", "unsorted", "segmented"]) + args = ap.parse_args() + + reroute.apply_m5_gather_qmm_workaround() + raw = reroute._original_gather_qmm or mx.gather_qmm + print( + f"mlx {mx.__version__} device {mx.device_info().get('device_name')} " + f"sorted rhs kernel defective: {reroute._sorted_gather_qmm_defective()}" + ) + gu, dn = _build( + args.experts, + args.hidden, + args.inter, + args.bits, + args.group_size, + mx.random.key(0), + ) + print( + f"geometry: E={args.experts} topk={args.topk} hidden={args.hidden} " + f"inter={args.inter} q{args.bits}/gs{args.group_size}" + ) + print(f"{'chunk':>6} {'rows':>7} {'mode':>10} {'ms/layer':>9} {'tok/s':>10}") + for chunk in args.chunks: + kx, ki = mx.random.split(mx.random.key(chunk)) + x = mx.random.normal((1, chunk, args.hidden), key=kx).astype(mx.bfloat16) + inds = mx.random.randint(0, args.experts, (1, chunk, args.topk), key=ki) + inds = inds.astype(mx.uint32) + mx.eval(x, inds) + for mode in args.modes: + if mode == "sorted": + sorted_flag, gather = True, raw + elif mode == "unsorted": + sorted_flag, gather = False, raw + elif mode == "segmented": + sorted_flag, gather = True, reroute._gather_qmm_rerouted + else: + raise SystemExit(f"unknown mode {mode}") + + def fn(x=x, inds=inds, sorted_flag=sorted_flag, gather=gather): + return _layer( + x, inds, gu, dn, args.bits, args.group_size, sorted_flag, gather + ) + + for _ in range(2): + mx.eval(fn()) + mx.synchronize() + t0 = time.perf_counter() + for _ in range(args.iters): + mx.eval(fn()) + mx.synchronize() + ms = (time.perf_counter() - t0) / args.iters * 1e3 + print( + f"{chunk:>6} {chunk * args.topk:>7} {mode:>10} {ms:>9.2f} " + f"{chunk / ms * 1e3:>10.0f}" + ) + + +if __name__ == "__main__": + main() diff --git a/omlx/patches/m5_gather_qmm.py b/omlx/patches/m5_gather_qmm.py index ea1b3d9cc1..a205345afa 100644 --- a/omlx/patches/m5_gather_qmm.py +++ b/omlx/patches/m5_gather_qmm.py @@ -17,14 +17,28 @@ and the mxfp4 variant carries the same tail bug. - Row offsets: the int16 fix that landed in mlx 0.32.0 still misses this kernel, so sorted row counts above 32768 overflow the row offset - (ml-explore/mlx#3856). Reachable in production: a 4097+ token prefill - chunk of a top-8 MoE crosses the boundary. - -``sorted_indices`` is a pure performance hint, so the wrapper simply -drops it for calls that match a defect condition. The unsorted gather -path guards ``K % 64 == 0`` before entering NAX and falls back to the -verified steel kernels, at some prefill-throughput cost for the -affected shapes only. + (ml-explore/mlx#3856, fixed upstream by ml-explore/mlx#3922 after the + 0.32.2 release). Reachable in production: a 4097+ token prefill chunk + of a top-8 MoE crosses the boundary, and a top-10 MoE (Qwen4-Exp) + crosses it at 3277 tokens. + +``sorted_indices`` is a pure performance hint, so the wrapper can always +fall back to dropping it. The two defects get different treatment: + +- ``K % 64 != 0`` drops the flag: the unsorted gather path guards + ``K % 64 == 0`` before entering NAX and falls back to the verified + steel kernels, at some prefill-throughput cost for the affected + shapes only. +- Row overflow keeps the flag and splits the call instead. The rhs + kernel is only wrong because a *single* call exceeds 32768 rows, so + an oversized call is issued as balanced ``<= 32768``-row slices of + the (already sorted) activations and indices and the partial outputs + are concatenated. Each slice stays on the NAX rhs kernel, which is + what makes wide prefill chunks (4096+ tokens on a top-8/top-10 MoE) + keep their tensor-unit throughput instead of dropping to the + per-row gather kernel. Slices are balanced rather than cut at the + cap so every slice still clears mlx's ``rows / experts >= 4`` gate + for the batched rhs path. The wrapper self-arms: the first matching call runs a tiny canary against an fp32 dequantized reference and only intervenes when the @@ -45,6 +59,11 @@ # ml-explore/mlx#3856: sorted row offsets overflow int16 past this count. _MAX_SORTED_ROWS = 32768 +# Advertises to callers (e.g. the scheduler's prefill-chunk policy) that +# oversized sorted calls are segmented rather than demoted to the unsorted +# kernel, so a wide chunk keeps the NAX rhs path. +SEGMENTS_SORTED_ROWS = True + _original_gather_qmm = None _defective: bool | None = None @@ -83,14 +102,18 @@ def _sorted_gather_qmm_defective() -> bool: if _defective: logger.warning( "sorted gather_qmm corrupts on this machine (canary max err " - "%.3g); rerouting K %% 64 != 0 and >%d-row sorted calls to the " - "unsorted path (issue #2267)", + "%.3g); rerouting K %% 64 != 0 sorted calls to the unsorted " + "path and segmenting >%d-row sorted calls (issue #2267)", err, _MAX_SORTED_ROWS, ) return _defective +def _rhs_indices(args, kwargs): + return args[3] if len(args) > 3 else kwargs.get("rhs_indices") + + def _needs_reroute(x, args, kwargs) -> bool: """True when this call would select the defective NAX rhs kernel.""" if not kwargs.get("sorted_indices"): @@ -99,7 +122,7 @@ def _needs_reroute(x, args, kwargs) -> bool: # rhs_indices, transpose, group_size, bits, mode. sorted_indices is # keyword-only. lhs = args[2] if len(args) > 2 else kwargs.get("lhs_indices") - rhs = args[3] if len(args) > 3 else kwargs.get("rhs_indices") + rhs = _rhs_indices(args, kwargs) transpose = args[4] if len(args) > 4 else kwargs.get("transpose", True) # The rhs kernel is only selected for the rhs-indices-only sorted # path with transposed weights (x @ w.T). @@ -110,8 +133,43 @@ def _needs_reroute(x, args, kwargs) -> bool: return rhs.size * x.shape[-2] > _MAX_SORTED_ROWS +def _segment_bounds(rows: int) -> list[tuple[int, int]]: + """Balanced ``[start, stop)`` slices with at most ``_MAX_SORTED_ROWS`` each.""" + count = -(-rows // _MAX_SORTED_ROWS) + size = -(-rows // count) + return [(start, min(start + size, rows)) for start in range(0, rows, size)] + + +def _segmented_sorted_gather_qmm(x, w, args, kwargs): + """Issue an oversized sorted rhs call as ``<= 32768``-row slices. + + Only the layout the MoE sorted path produces is handled: a 3-D + ``[rows, 1, K]`` activation with a flat sorted ``rhs_indices`` of the + same row count. Anything else returns None and the caller falls back + to dropping ``sorted_indices``. + """ + rhs = _rhs_indices(args, kwargs) + if x.ndim != 3 or x.shape[1] != 1 or rhs.ndim != 1 or rhs.shape[0] != x.shape[0]: + return None + rows = int(x.shape[0]) + outputs = [] + for start, stop in _segment_bounds(rows): + seg_args = list(args) + seg_kwargs = kwargs + if len(args) > 3: + seg_args[3] = rhs[start:stop] + else: + seg_kwargs = dict(kwargs, rhs_indices=rhs[start:stop]) + outputs.append(_original_gather_qmm(x[start:stop], w, *seg_args, **seg_kwargs)) + return mx.concatenate(outputs, axis=0) + + def _gather_qmm_rerouted(x, w, *args, **kwargs): if _needs_reroute(x, args, kwargs) and _sorted_gather_qmm_defective(): + if x.shape[-1] % 64 == 0: + out = _segmented_sorted_gather_qmm(x, w, args, kwargs) + if out is not None: + return out kwargs = dict(kwargs, sorted_indices=False) return _original_gather_qmm(x, w, *args, **kwargs) diff --git a/tests/test_m5_gather_qmm.py b/tests/test_m5_gather_qmm.py index fda82c4338..52289e1c4d 100644 --- a/tests/test_m5_gather_qmm.py +++ b/tests/test_m5_gather_qmm.py @@ -96,6 +96,67 @@ def spy(x, w, *args, **kwargs): assert captured["sorted_indices"] is True +def test_segment_bounds_are_balanced_and_capped(): + cap = patch_mod._MAX_SORTED_ROWS + assert patch_mod._segment_bounds(cap) == [(0, cap)] + bounds = patch_mod._segment_bounds(cap + 1) + assert bounds == [(0, cap // 2 + 1), (cap // 2 + 1, cap + 1)] + rows = 40960 # 4096-token chunk of a top-10 MoE + bounds = patch_mod._segment_bounds(rows) + assert bounds == [(0, 20480), (20480, 40960)] + assert all(stop - start <= cap for start, stop in bounds) + rows = 3 * cap + 5 + bounds = patch_mod._segment_bounds(rows) + assert len(bounds) == 4 + assert bounds[0][0] == 0 and bounds[-1][1] == rows + assert all(b[1] == n[0] for b, n in zip(bounds, bounds[1:])) + sizes = [stop - start for start, stop in bounds] + assert max(sizes) - min(sizes) < len(bounds) + + +def test_wrapper_segments_oversized_sorted_calls(monkeypatch): + """Aligned K past the row cap stays sorted, split into <=32768-row calls.""" + seen = [] + + def spy(x, w, *args, **kwargs): + rhs = args[3] if len(args) > 3 else kwargs["rhs_indices"] + seen.append((int(x.shape[0]), int(rhs.shape[0]), kwargs["sorted_indices"])) + return mx.zeros((x.shape[0], 1, 4), dtype=x.dtype) + + assert apply_m5_gather_qmm_workaround() + monkeypatch.setattr(patch_mod, "_original_gather_qmm", spy) + monkeypatch.setattr(patch_mod, "_defective", True) + + rows = 70000 + x = mx.zeros((rows, 1, 128), dtype=mx.bfloat16) + idx = mx.zeros((rows,), dtype=mx.uint32) + out = mx.gather_qmm(x, x, x, rhs_indices=idx, sorted_indices=True) + assert out.shape == (rows, 1, 4) + assert len(seen) == 3 + assert all(sorted_flag for _, _, sorted_flag in seen) + assert all(n <= patch_mod._MAX_SORTED_ROWS for n, _, _ in seen) + assert all(n == m for n, m, _ in seen) + assert sum(n for n, _, _ in seen) == rows + + # Positional rhs_indices (scales, biases, lhs, rhs) segments the same way. + seen.clear() + out = mx.gather_qmm(x, x, x, x, None, idx, sorted_indices=True) + assert out.shape == (rows, 1, 4) + assert len(seen) == 3 and all(s for _, _, s in seen) + + # Unaligned K cannot use the rhs kernel at all: one unsorted call. + seen.clear() + x96 = mx.zeros((rows, 1, 96), dtype=mx.bfloat16) + mx.gather_qmm(x96, x96, x96, rhs_indices=idx, sorted_indices=True) + assert seen == [(rows, rows, False)] + + # A layout the segmenter does not understand drops the flag instead. + seen.clear() + x2 = mx.zeros((rows // 2, 2, 128), dtype=mx.bfloat16) + mx.gather_qmm(x2, x2, x2, rhs_indices=idx[: rows // 2], sorted_indices=True) + assert seen == [(rows // 2, rows // 2, False)] + + def _kernel_defective_here() -> bool: if not mx.metal.is_available(): return False @@ -142,3 +203,36 @@ def test_reroute_restores_correct_output_on_defective_hardware(): ) err = mx.abs(out.astype(mx.float32) - ref).max().item() assert err < 0.2, f"still corrupt through the reroute: max err {err}" + + +@pytest.mark.skipif( + not _kernel_defective_here(), + reason="sorted gather_qmm NAX kernel is healthy on this machine", +) +def test_segmented_sorted_call_matches_reference_past_row_cap(): + """>32768 sorted rows stay on the NAX rhs kernel and still match fp32.""" + assert apply_m5_gather_qmm_workaround() + + n, e, out_dim, k = patch_mod._MAX_SORTED_ROWS + 4096, 8, 64, 64 + keys = mx.random.split(mx.random.key(3856), 3) + w = mx.random.normal((e, out_dim, k), key=keys[0]).astype(mx.bfloat16) + wq, scales, biases = mx.quantize(w, group_size=64, bits=4) + x = (mx.random.normal((n, 1, k), key=keys[1]) * 0.5).astype(mx.bfloat16) + idx = mx.sort(mx.random.randint(0, e, (n,), key=keys[2]).astype(mx.uint32)) + wd = mx.dequantize(wq, scales, biases, group_size=64, bits=4) + ref = x.astype(mx.float32) @ wd[idx].swapaxes(-1, -2).astype(mx.float32) + + out = mx.gather_qmm( + x, + wq, + scales, + biases, + rhs_indices=idx, + transpose=True, + group_size=64, + bits=4, + sorted_indices=True, + ) + assert out.shape == ref.shape + err = mx.abs(out.astype(mx.float32) - ref).max().item() + assert err < 0.2, f"segmented sorted call is corrupt: max err {err}" From df4e77ab2bf7d5e31097d503984b20a66f5bec87 Mon Sep 17 00:00:00 2001 From: jundot Date: Sun, 6 Sep 2026 23:14:17 +0900 Subject: [PATCH 105/132] fix: preserve reusable prefixes at request completion (#3102, #2384) --- docs/TESTING.md | 4 + omlx/scheduler.py | 209 ++++++-------------- tests/test_scheduler.py | 114 ++++------- tests/test_scheduler_boundary_completion.py | 169 ++++++++++++++++ 4 files changed, 277 insertions(+), 219 deletions(-) create mode 100644 tests/test_scheduler_boundary_completion.py diff --git a/docs/TESTING.md b/docs/TESTING.md index 2769bca031..d6a53d5fdc 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -9,3 +9,7 @@ Related regression suites are `test_qwen4_qsa_incremental_cache.py`, `test_qwen4 # Prefill memory accounting tests Run `python -m pytest -q tests/test_prefill_transient_tracker.py tests/test_prefill_oom_graceful.py` to check retained versus reclaimed overhead, configured chunk sizes, and abort-cap enforcement. The loop tests run a small initialized MLX model with controlled footprint readings through external and chunked prefill; they do not load a checkpoint. + +# Prefix cache completion tests + +Run `python -m pytest -q tests/test_scheduler.py tests/test_scheduler_boundary_completion.py tests/test_prefix_cache_gdn_split.py` to check cache-freshness admission and completed boundary recovery. The completion tests use a small initialized Qwen3.5 hybrid model and the real BatchGenerator, then compare restored-prefix logits with a fresh forward pass. They cover embedded snapshots, GDN sidecars, off-boundary completion, and unknown or inconsistent cache positions. diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 0ccb681307..8a697caa8f 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -6554,15 +6554,10 @@ def _on_prefill_boundary_snapshot( request_id: str, snapshot_cache: list[Any], token_count: int, + *, + source: str = "prefill", ) -> None: - """Record boundary snapshots captured during prefill processing. - - Called from ``_emit_prefill_boundary_snapshot`` at each block - boundary crossed during prefill. Keyed by ``request_id`` rather - than ``uid`` because the request has not been inserted into - ``BatchGenerator`` yet and the uid mapping does not exist — - routing through it dropped every snapshot silently (#TBD). - """ + """Record a prefill boundary or a verified terminal response snapshot.""" if self._model_has_unreconstructible_cache(): return @@ -6572,7 +6567,7 @@ def _on_prefill_boundary_snapshot( request_id=request_id, token_count=token_count, block_size=block_size, - source="prefill", + source=source, ) if self.block_aware_cache is None: self._boundary_snapshot_diagnostics.record( @@ -6581,7 +6576,7 @@ def _on_prefill_boundary_snapshot( request_id=request_id, token_count=token_count, block_size=block_size, - source="prefill", + source=source, ) return @@ -6592,7 +6587,7 @@ def _on_prefill_boundary_snapshot( request_id=request_id, token_count=token_count, block_size=block_size, - source="prefill", + source=source, ) return @@ -6603,7 +6598,7 @@ def _on_prefill_boundary_snapshot( request_id=request_id, token_count=token_count, block_size=block_size, - source="prefill", + source=source, ) return @@ -6618,7 +6613,7 @@ def _on_prefill_boundary_snapshot( request_id=request_id, token_count=token_count, block_size=block_size, - source="prefill", + source=source, ) return @@ -6649,7 +6644,7 @@ def _on_prefill_boundary_snapshot( request_id=request_id, token_count=token_count, block_size=block_size, - source="prefill", + source=source, storage="memory", ) self._boundary_cache_snapshots[request_id][token_count] = ( @@ -6679,11 +6674,12 @@ def _on_prefill_boundary_snapshot( request_id=request_id, token_count=token_count, block_size=block_size, - source="prefill", + source=source, storage=storage, ) logger.debug( - "Captured prefill boundary cache snapshot for %s at %s tokens (%s)", + "Captured %s boundary cache snapshot for %s at %s tokens (%s)", + source, request_id, token_count, storage, @@ -7498,60 +7494,41 @@ def _extract_live_request_cache_for_store( ) return None - def _verify_live_boundary_aligned( - self, request_id: str, uid: int, boundary_tokens: int - ) -> list[dict[str, Any]] | None: - """Return extracted cache state iff the live cache is exactly at a block - boundary, else None. + def _capture_finished_boundary_snapshot( + self, request: Request, cache: list[Any] + ) -> None: + """Preserve a verified terminal boundary after the generator drops its UID.""" + if getattr(request, "skip_cache_store", False): + return + if self._boundary_cache_snapshots.get(request.request_id): + return + token_count = ( + len(request.prompt_token_ids) + if request.needs_think_prefix + else request.num_tokens + ) + block_size = self.config.paged_cache_block_size + if ( + block_size <= 0 + or token_count <= 0 + or token_count % block_size + or not self._detect_boundary_snapshot_need() + ): + return - Recovery path for the store-time ``_BoundaryStoreUnavailable`` case: when - every decode-time boundary capture was skipped (MTP skew guard) but the - request finished on a block boundary, the live recurrent/rotating state - sits at that boundary and is safe to persist. The leaf cache ``offset`` - must equal the boundary token count exactly — mirroring - ``_extract_boundary_snapshot``'s positional-consistency guard — so we - never label an off-boundary state with a block-boundary count. - """ - if self.batch_generator is None or uid is None or uid < 0: - return None - try: - with self._phase_timer("store_cache_boundary_verify"): - _safe_sync_stream(self._stream) - with mx.stream(self._stream): - result = self.batch_generator.extract_cache([uid]) - if uid not in result: - logger.debug( - "Cannot verify live cache for %s: uid %s not present", - request_id, - uid, - ) - return None - cache_list, _tokens = result[uid] - for c in cache_list: - offset = _first_leaf_cache_offset(c) - if offset is None: - continue - if offset != boundary_tokens: - logger.debug( - "Live cache for %s is off-boundary (offset %d != boundary %d); " - "skipping recovery store", - request_id, - offset, - boundary_tokens, - ) - return None - break - extracted_cache, _ = self._extract_cache_states(cache_list) - if not extracted_cache: - return None - return extracted_cache - except Exception as e: - logger.debug( - "Failed to verify live cache for boundary store %s: %s", - request_id, - e, - ) - return None + # Composite caches use their leading token-position leaf; later + # members may count pooled windows instead. Unknown positions cannot + # establish that recurrent state matches the emitted token sequence. + offsets = [ + offset + for layer in cache + if (offset := _first_leaf_cache_offset(layer)) is not None + ] + if not offsets or any(offset != token_count for offset in offsets): + return + self._on_prefill_boundary_snapshot( + request.request_id, cache, token_count, source="completion" + ) def _prepare_prompt_boundary_cache_store( self, @@ -8290,22 +8267,9 @@ def _log_prefix_divergence(self, request: Request) -> None: f"{best_p}: stored=...{stored_ctx!r} vs prompt=...{prompt_ctx!r}" ) - # Whether an in-flight store_cache is worth waiting for is decided by the - # overlap with it, not by the prompt's length. What a wait can save is the - # re-prefill of the restorable overlap (whole blocks of the effective - # paged_cache_block_size -- 256 for KV models, the 2048-token boundary when - # the GDN split is active); what it costs is bounded by the store's own - # duration, which scales with the tokens THAT store copies (~13-20 us/token - # measured on M5 Max, hot cache off) while prefill costs ~0.6-5 ms/token - # across current models and machines. So: never wait when less than one - # block is restorable (nothing a wait could make visible), and never wait on - # a store more than 16x larger than the overlap (a harness side-request - # that shares only the system prompt with a 100K-token turn being stored), - # which keeps the worst-case wait well under the prefill it avoids. A fixed - # prompt floor (8192, then 4096 for the DeepSeek V4 3584-of-4096 boundary - # snapshot, #2471) reproduced the race one notch lower each time: agent - # harnesses firing a 3K follow-up instantly re-prefilled every turn (#3102). - # The 4K boundary-snapshot case still waits under the overlap gates. + # Wait only for reusable blocks. The store/overlap ratio is a heuristic + # limiting waits on large stores that share a small prefix; the timeout + # below still bounds slow storage independently of token counts. _CACHE_FRESHNESS_WAIT_MAX_STORE_TO_OVERLAP = 16 _CACHE_FRESHNESS_WAIT_MIN_COMMON_TOKENS = 8192 _CACHE_FRESHNESS_WAIT_MIN_PROMPT_RATIO = 0.30 @@ -8345,11 +8309,17 @@ def _find_relevant_inflight_store( continue common = self._common_prefix_len(prompt, info.tokens) - # Per-candidate: only whole blocks can be restored, and a store far - # larger than the overlap costs more to wait for than it saves. A - # longest-overlap store that fails here must not veto a smaller - # store that passes, so filter before ranking. + # Filter before ranking so an ineligible larger store cannot + # hide a smaller one whose prefix can actually be reused. restorable = (common // block) * block + if restorable == len(prompt): + # Match exact-hit generation kickoff in prefix preparation: + # GDN sidecars drop the final block; other stateful caches + # cannot trim to N-1 and require a full prefill. + if self._gdn_split_active(): + restorable = max(0, restorable - block) + elif self._detect_boundary_snapshot_need(): + restorable = 0 if restorable < block: continue if ( @@ -11435,6 +11405,9 @@ def _process_batch_responses( if extracted_cache: request._extracted_cache = extracted_cache request._model_cache_config = model_cache_config + self._capture_finished_boundary_snapshot( + request, raw_cache + ) logger.debug( f"Extracted {len(extracted_cache)} layer states " f"for request {request_id}" @@ -11619,63 +11592,7 @@ def _cleanup_finished(self, finished_ids: set[str]) -> None: # the current decode offset (which # speculative decode can leave off # the emitted count entirely). - # - # Recovery: when every decode-time - # capture was skipped (MTP skew - # guard) but the request itself - # finished on a block boundary, the - # live extracted cache is exactly - # that boundary-aligned snapshot — - # storing it is safe and recovers - # prefix reuse instead of throwing - # away a usable recurrent state. - block_size = ( - self.config.paged_cache_block_size - ) - live_cache = None - if ( - block_size > 0 - and len(cacheable_sequence) - % block_size - == 0 - ): - # Only trust the live state when - # its leaf cache offset actually - # sits on the boundary (emitted - # length alone can be fooled by - # the MTP emit queue). uid_for_store - # may be unset when this request - # carried its own _extracted_cache, - # so resolve it here. - live_uid = ( - self.request_id_to_uid.get( - request_id, -1 - ) - ) - live_cache = ( - self._verify_live_boundary_aligned( - request_id, - live_uid, - len(cacheable_sequence), - ) - ) - if live_cache: - token_sequence_to_store = ( - cacheable_sequence - ) - cache_to_store = live_cache - intermediate_snapshots = None - logger.info( - "Using live boundary-aligned " - "cache for %s: request finished " - "on block boundary " - "(%d/%d tokens)", - request_id, - len(cacheable_sequence), - len(full_token_sequence), - ) - else: - raise _BoundaryStoreUnavailable() + raise _BoundaryStoreUnavailable() if boundary_override is not None: ( token_sequence_to_store, diff --git a/tests/test_scheduler.py b/tests/test_scheduler.py index d060d09f5b..e618dd512f 100644 --- a/tests/test_scheduler.py +++ b/tests/test_scheduler.py @@ -1171,8 +1171,47 @@ def test_admission_freshness_gate_filters_candidates_before_ranking( assert scheduler._should_defer_for_cache_freshness(request) is False assert request.request_id not in scheduler._cache_freshness_waits - def test_scheduler_has_no_prompt_length_freshness_floor(self): - assert not hasattr(Scheduler, "_CACHE_FRESHNESS_WAIT_MIN_PROMPT_TOKENS") + @pytest.mark.parametrize( + "split,stateful,prompt_len,store_len,expected", + [ + (True, True, 2048, 2048, False), + (True, True, 4096, 4096, True), + (True, True, 4096, 65536, False), + (True, True, 2600, 2048, True), + (True, True, 2600, 4096, True), + (False, True, 2600, 4096, True), + (False, True, 2048, 2048, False), + (False, False, 2048, 2048, True), + ], + ) + def test_freshness_exact_hit_uses_generation_reusable_overlap( + self, + mock_model, + mock_tokenizer, + split, + stateful, + prompt_len, + store_len, + expected, + ): + scheduler = Scheduler(model=mock_model, tokenizer=mock_tokenizer) + scheduler.config.paged_cache_block_size = 2048 + scheduler.block_aware_cache = MagicMock() + scheduler._gdn_split_active = MagicMock(return_value=split) + scheduler._boundary_snapshot_required = stateful + request = Request( + request_id="next", + prompt=list(range(prompt_len)), + sampling_params=SamplingParams(max_tokens=1), + ) + scheduler.add_request(request) + future = concurrent.futures.Future() + scheduler._inflight_store_futures["previous"] = future + scheduler._inflight_store_info["previous"] = ( + scheduler_module._InflightStoreInfo(tokens=list(range(store_len))) + ) + + assert scheduler._should_defer_for_cache_freshness(request) is expected def test_admission_defers_for_immediate_4k_boundary_store( self, mock_model, mock_tokenizer @@ -2990,77 +3029,6 @@ def test_prefix_lookup_observation_explains_reprefill_boundary( "unreused_common_prefix_tokens": 3, } - def test_cleanup_finished_recovery_stores_boundary_aligned_live_cache( - self, mock_model, mock_tokenizer - ): - """Fix A recovery: when every decode-time capture was skipped by the - MTP skew guard but the request finished on a block boundary, the - scheduler stores the verified boundary-aligned live cache instead of - dropping it — preserving prefix-cache reuse on the next turn.""" - config = SchedulerConfig(paged_cache_block_size=4) - scheduler = Scheduler(model=mock_model, tokenizer=mock_tokenizer, config=config) - scheduler.block_aware_cache = MagicMock() - scheduler.paged_cache_manager = None - scheduler._boundary_snapshot_required = True - - request = Request( - request_id="req-recover", - prompt="hello", - sampling_params=SamplingParams(), - ) - request.prompt_token_ids = [1, 2, 3, 4] - request.num_prompt_tokens = 4 - request.output_token_ids = [5, 6, 7, 8] # Total = 8 (2 full blocks) - request._extracted_cache = [{"state": "live-cache"}] - request._model_cache_config = "live-config" - - scheduler.running["req-recover"] = request - scheduler.requests["req-recover"] = request - # Live cache verifies as boundary-aligned (offset == 8 == total). - scheduler._verify_live_boundary_aligned = MagicMock( - return_value=[{"state": "boundary-live-cache"}] - ) - - scheduler._cleanup_finished({"req-recover"}) - - scheduler.block_aware_cache.store_cache.assert_called_once() - args, kwargs = scheduler.block_aware_cache.store_cache.call_args - assert args[0] == "req-recover" - assert args[1] == [1, 2, 3, 4, 5, 6, 7, 8] # full boundary-aligned sequence - - def test_cleanup_finished_recovery_skips_off_boundary_live_cache( - self, mock_model, mock_tokenizer - ): - """Fix A recovery must NOT store when the request finished off a block - boundary — the live recurrent state cannot be labeled with a boundary - token count and would corrupt later prefix hits.""" - config = SchedulerConfig(paged_cache_block_size=4) - scheduler = Scheduler(model=mock_model, tokenizer=mock_tokenizer, config=config) - scheduler.block_aware_cache = MagicMock() - scheduler.paged_cache_manager = None - scheduler._boundary_snapshot_required = True - - request = Request( - request_id="req-off-boundary", - prompt="hello", - sampling_params=SamplingParams(), - ) - request.prompt_token_ids = [1, 2, 3, 4] - request.num_prompt_tokens = 4 - request.output_token_ids = [5, 6, 7] # Total = 7 (not a full block) - request._extracted_cache = [{"state": "live-cache"}] - request._model_cache_config = "live-config" - - scheduler.running["req-off-boundary"] = request - scheduler.requests["req-off-boundary"] = request - - scheduler._cleanup_finished({"req-off-boundary"}) - - scheduler.block_aware_cache.store_cache.assert_not_called() - scheduler.block_aware_cache.clear_request_entry.assert_called_with( - "req-off-boundary" - ) - def test_cleanup_finished_skips_output_tokens_for_reasoning_model( self, mock_model, mock_tokenizer ): diff --git a/tests/test_scheduler_boundary_completion.py b/tests/test_scheduler_boundary_completion.py new file mode 100644 index 0000000000..de8e2aa74b --- /dev/null +++ b/tests/test_scheduler_boundary_completion.py @@ -0,0 +1,169 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Exercise completed hybrid requests through durable prefix reuse.""" + +from types import SimpleNamespace +from unittest.mock import MagicMock + +import mlx.core as mx +import pytest +from mlx_lm.generate import BatchGenerator +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 + + +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, + ), + ) + ) + + +@pytest.mark.parametrize("split", [False, True]) +@pytest.mark.parametrize("total_tokens", [3, 4, 5]) +def test_completed_hybrid_boundary_reuses_final_response( + mock_tokenizer, tmp_path, split, total_tokens +): + mx.random.seed(7) + model = _tiny_hybrid_model() + scheduler = Scheduler( + model=model, + tokenizer=mock_tokenizer, + config=SchedulerConfig(paged_cache_block_size=4, gdn_ssd_split_enabled=split), + ) + paged = PagedCacheManager( + block_size=4, max_blocks=16, initial_blocks=16, model_name="tiny-qwen" + ) + ssd = PagedSSDCacheManager( + cache_dir=tmp_path / "cache", + max_size_bytes=16 * 1024**2, + expected_model_name="tiny-qwen", + expected_num_layers=2, + expected_block_size=4, + expected_layer_cache_types=["ArraysCache", "KVCache"], + gdn_ssd_split_enabled=split, + ) + boundary = BoundarySnapshotSSDStore(tmp_path / "cache") + prefix = BlockAwarePrefixCache( + model=model, + paged_cache_manager=paged, + paged_ssd_cache_manager=ssd, + gdn_ssd_split_enabled=split, + ) + prefix.set_gdn_checkpoint_loader(boundary.load_file) + scheduler.paged_cache_manager = paged + scheduler.paged_ssd_cache_manager = ssd + scheduler._boundary_snapshot_store = boundary + scheduler.block_aware_cache = prefix + generator = BatchGenerator( + model, + max_tokens=1, + sampler=lambda logits: mx.zeros(logits.shape[:-1], dtype=mx.int32), + stream=scheduler._stream, + ) + scheduler.batch_generator = generator + tokens = list(range(3, 3 + total_tokens - 1)) + request = Request( + request_id="finished", + prompt=tokens, + sampling_params=SamplingParams(max_tokens=1), + ) + scheduler.add_request(request) + scheduler.waiting.clear() + scheduler.running[request.request_id] = request + uid = generator.insert([tokens])[0] + scheduler.request_id_to_uid[request.request_id] = uid + scheduler.uid_to_request_id[uid] = request.request_id + + try: + for _ in range(5): + _, responses = generator.next() + if responses: + break + assert responses[0].finish_reason == "length" + assert responses[0].prompt_cache[-1].offset == total_tokens + assert generator.extract_cache([uid]) == {} + _, finished = scheduler._process_batch_responses(responses) + assert finished == {request.request_id} + scheduler._cleanup_finished(finished) + for future in list(scheduler._inflight_store_futures.values()): + future.result(timeout=10) + scheduler._drain_pending_async_removes() + + extended = tokens + [0, 9, 10] + table, remaining = prefix.fetch_cache("next", extended) + if total_tokens % 4: + assert table is None + assert remaining == extended + else: + assert table is not None and table.num_tokens == total_tokens + restored = prefix.reconstruct_cache(table) + assert restored is not None + assert remaining == [9, 10] + with mx.stream(scheduler._stream): + warm_logits = model(mx.array([remaining]), cache=restored) + cold_logits = model(mx.array([extended]), cache=model.make_cache()) + mx.eval(warm_logits, cold_logits) + assert mx.allclose(warm_logits[:, -1], cold_logits[:, -1], atol=1e-4) + finally: + scheduler.shutdown() + + +@pytest.mark.parametrize( + "offsets,expected", + [([None], False), ([5], False), ([4, 5], False), ([4], True)], +) +def test_completion_boundary_requires_known_consistent_positions( + mock_model, mock_tokenizer, offsets, expected +): + scheduler = Scheduler( + model=mock_model, + tokenizer=mock_tokenizer, + config=SchedulerConfig(paged_cache_block_size=4), + ) + scheduler._boundary_snapshot_required = True + scheduler._on_prefill_boundary_snapshot = MagicMock() + request = Request( + request_id="finished", + prompt=[3, 4, 5], + sampling_params=SamplingParams(max_tokens=1), + ) + request.prompt_token_ids = [3, 4, 5] + request.num_prompt_tokens = 3 + request.output_token_ids = [6] + cache = [ + SimpleNamespace( + caches=[ + SimpleNamespace(offset=offset), + SimpleNamespace(), + ] + ) + for offset in offsets + ] + + scheduler._capture_finished_boundary_snapshot(request, cache) + + assert scheduler._on_prefill_boundary_snapshot.called is expected + scheduler.shutdown() From 2aab2ce3ce2f4254abd0c99a5ff64efb98215d3a Mon Sep 17 00:00:00 2001 From: Jun Kim <64250138+jundot@users.noreply.github.com> Date: Mon, 7 Sep 2026 00:15:35 +1000 Subject: [PATCH 106/132] fix: scope SDPA headroom providers to engine workers (#3333) --- omlx/patches/sdpa256_attention.py | 35 +++++++---- omlx/scheduler.py | 13 ++-- tests/test_qwen4_qsa_prefill_memory.py | 4 +- tests/test_sdpa256_attention.py | 87 +++++++++++++++++++++++--- 4 files changed, 109 insertions(+), 30 deletions(-) diff --git a/omlx/patches/sdpa256_attention.py b/omlx/patches/sdpa256_attention.py index 73e1c3fcc4..35c1e32d03 100644 --- a/omlx/patches/sdpa256_attention.py +++ b/omlx/patches/sdpa256_attention.py @@ -25,6 +25,7 @@ import logging import os +import threading import weakref import mlx.core as mx @@ -54,12 +55,12 @@ _NEG_INF = -1e30 # Live guard-headroom provider for memory-aware routing (issue #2204). -# Registered by Scheduler.__init__ as a bound method returning the bytes left -# under the adaptive-prefill-throttle target (hard ceiling x headroom safety, -# clamped by the abort cap), or a negative value when no ceiling is active. -# Held as a WeakMethod so a torn-down Scheduler auto-unregisters and the route -# falls back to the memory-bounded native fused default. -_HEADROOM_PROVIDER: "weakref.WeakMethod | None" = None +# Scheduler.step registers the active Scheduler on its execution thread. Each +# engine uses its own worker, so thread-local storage keeps concurrent engines +# from replacing one another's provider. The bound method is weakly held so a +# torn-down Scheduler leaves that worker on the memory-bounded native fused +# default. +_HEADROOM_PROVIDER_LOCAL = threading.local() # Backward-compatible override: True = always force fused, False = never force, # None = memory-aware auto. _FORCE_TILED: bool | None = None @@ -82,11 +83,21 @@ def _note_tiled_route(reason: str, detail: str) -> None: def set_unfused_headroom_provider(method) -> None: - """Register a bound method returning the prefill guard's live headroom in - bytes (negative when no ceiling is active). Lets ``_should_route`` prefer - the faster unfused fallback whenever its O(L^2) transient fits.""" - global _HEADROOM_PROVIDER - _HEADROOM_PROVIDER = weakref.WeakMethod(method) + """Bind the active Scheduler's headroom provider to this worker thread.""" + ref = getattr(_HEADROOM_PROVIDER_LOCAL, "ref", None) + current = ref() if ref is not None else None + if ( + current is not None + and current.__self__ is method.__self__ + and current.__func__ is method.__func__ + ): + return + _HEADROOM_PROVIDER_LOCAL.ref = weakref.WeakMethod(method) + + +def _get_unfused_headroom_provider(): + ref = getattr(_HEADROOM_PROVIDER_LOCAL, "ref", None) + return ref() if ref is not None else None def _parse_force_tiled_env() -> bool | None: @@ -116,7 +127,7 @@ def _tiled_route_required(queries, keys) -> bool: (issues #2155 / #2204), so force the fused path only when the unfused transient would not fit under the guard ceiling — or when no headroom info is available, keeping the memory-safe #2025 behavior.""" - provider = _HEADROOM_PROVIDER() if _HEADROOM_PROVIDER is not None else None + provider = _get_unfused_headroom_provider() if _FORCE_TILED is not None: if _FORCE_TILED: _note_tiled_route("forced", "forced by OMLX_SDPA256_TILED=1") diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 8a697caa8f..42c12a4961 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -51,13 +51,13 @@ from .cache.paged_cache import 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 from .exceptions import ( PrefillMemoryExceededError, describe_ceiling_binding, is_cache_corruption_error, ) from .patches.sdpa256_attention import set_unfused_headroom_provider -from .decode_activity import get_decode_activity from .prefill_progress import get_prefill_tracker from .prefill_transient_tracker import PrefillTransientTracker from .request import Request, RequestOutput, RequestStatus, SamplingParams @@ -2004,12 +2004,6 @@ def __init__( # and taken after the first prefill chunk's eval. self._fixed_state_measure_armed: bool = False self._fixed_state_recorded: bool = False - # Let the sdpa256 head_dim-256 prefill route ask for live guard - # headroom so it only forces bounded native SDPA when the faster - # unfused default would not fit (issue #2204). Weakly held; harmless - # when the patch is never applied. - set_unfused_headroom_provider(self._sdpa256_unfused_headroom) - # SpecPrefill: draft model for attention-based sparse prefill self._specprefill_draft_model: Any | None = None self._draft_paged_ssd_cache_manager: Any | None = None @@ -12319,6 +12313,11 @@ def step(self) -> SchedulerOutput: Returns: SchedulerOutput with results of this step """ + # Bind on the thread that runs model forwards. Scheduler construction + # can happen on a shared event-loop thread, while every engine executes + # steps on its own worker. The setter is idempotent for repeated steps. + set_unfused_headroom_provider(self._sdpa256_unfused_headroom) + output = SchedulerOutput() # Publish decode activity for cross-engine prefill fairness (a diff --git a/tests/test_qwen4_qsa_prefill_memory.py b/tests/test_qwen4_qsa_prefill_memory.py index 37ab41298a..46462b8ca9 100644 --- a/tests/test_qwen4_qsa_prefill_memory.py +++ b/tests/test_qwen4_qsa_prefill_memory.py @@ -52,9 +52,11 @@ def test_qsa_cache_is_not_retained_in_boundary_snapshots(cache_cls): def test_bool_mask_uses_tiled_sdpa_and_matches_dense(monkeypatch): + import threading + from omlx.patches import sdpa256_attention as sdpa256 - monkeypatch.setattr(sdpa256, "_HEADROOM_PROVIDER", None) + monkeypatch.setattr(sdpa256, "_HEADROOM_PROVIDER_LOCAL", threading.local()) monkeypatch.setattr(sdpa256, "_FORCE_TILED", None) monkeypatch.setattr(sdpa256, "_SDPA256_MIN_KV_LEN", 64) monkeypatch.setattr(sdpa256, "_Q_TILE", 16) diff --git a/tests/test_sdpa256_attention.py b/tests/test_sdpa256_attention.py index ff6d10e2fe..f4bdcf589b 100644 --- a/tests/test_sdpa256_attention.py +++ b/tests/test_sdpa256_attention.py @@ -441,10 +441,14 @@ def _sdpa256_bounded_route_changed(self, active): @pytest.fixture def _sdpa256_provider_reset(monkeypatch): - """Isolate the module-level provider/override state and restore it.""" + """Isolate the thread-local provider/override state and restore it.""" + import threading + from omlx.patches import sdpa256_attention as sdpa256 - monkeypatch.setattr(sdpa256, "_HEADROOM_PROVIDER", None, raising=False) + monkeypatch.setattr( + sdpa256, "_HEADROOM_PROVIDER_LOCAL", threading.local(), raising=False + ) monkeypatch.setattr(sdpa256, "_FORCE_TILED", None, raising=False) monkeypatch.setattr(sdpa256, "_TILED_ROUTE_LOGGED", set(), raising=False) return sdpa256 @@ -524,6 +528,63 @@ def test_route_defaults_to_tiled_when_provider_owner_dies(_sdpa256_provider_rese assert sdpa256._should_route(q, k, None, "causal", None) is True +def test_provider_binding_is_idempotent_and_replaceable(_sdpa256_provider_reset): + sdpa256 = _sdpa256_provider_reset + first = _HeadroomOwner(1) + second = _HeadroomOwner(2) + + sdpa256.set_unfused_headroom_provider(first.headroom) + first_ref = sdpa256._HEADROOM_PROVIDER_LOCAL.ref + sdpa256.set_unfused_headroom_provider(first.headroom) + assert sdpa256._HEADROOM_PROVIDER_LOCAL.ref is first_ref + + sdpa256.set_unfused_headroom_provider(second.headroom) + provider = sdpa256._get_unfused_headroom_provider() + assert provider is not None + assert provider.__self__ is second + + +def test_worker_provider_survives_other_scheduler_teardown( + _sdpa256_provider_reset, +): + """A later engine must not replace or clear a surviving engine's provider.""" + import concurrent.futures + import gc + + sdpa256 = _sdpa256_provider_reset + q, k, _ = _qkv(2048, 16384) + surviving = _HeadroomOwner(1 << 40) + later = _HeadroomOwner(1) + + def route(worker): + return worker.submit( + sdpa256._should_route, q, k, None, "causal", None + ).result() + + with ( + concurrent.futures.ThreadPoolExecutor(max_workers=1) as first_worker, + concurrent.futures.ThreadPoolExecutor(max_workers=1) as second_worker, + ): + first_worker.submit( + sdpa256.set_unfused_headroom_provider, surviving.headroom + ).result() + second_worker.submit( + sdpa256.set_unfused_headroom_provider, later.headroom + ).result() + + assert route(first_worker) is False + assert route(second_worker) is True + assert surviving.route_changes == [False] + assert later.route_changes == [True] + + del later + gc.collect() + + assert route(first_worker) is False + assert route(second_worker) is True + assert surviving.route_changes == [False, False] + + def test_route_defaults_to_tiled_when_provider_raises(_sdpa256_provider_reset): sdpa256 = _sdpa256_provider_reset @@ -538,6 +599,8 @@ def headroom(self): def test_force_tiled_override(_sdpa256_provider_reset, monkeypatch): + import threading + sdpa256 = _sdpa256_provider_reset q, k, _ = _qkv(2048, 16384) owner = _HeadroomOwner(1 << 40) @@ -545,9 +608,15 @@ def test_force_tiled_override(_sdpa256_provider_reset, monkeypatch): # 1: always tiled even though unfused fits. monkeypatch.setattr(sdpa256, "_FORCE_TILED", True, raising=False) assert sdpa256._should_route(q, k, None, "causal", None) is True + assert owner.route_changes == [True] + monkeypatch.setattr(sdpa256, "_FORCE_TILED", False, raising=False) + assert sdpa256._should_route(q, k, None, "causal", None) is False + assert owner.route_changes == [True, False] # 0: never tiled even without headroom info. monkeypatch.setattr(sdpa256, "_FORCE_TILED", False, raising=False) - monkeypatch.setattr(sdpa256, "_HEADROOM_PROVIDER", None, raising=False) + monkeypatch.setattr( + sdpa256, "_HEADROOM_PROVIDER_LOCAL", threading.local(), raising=False + ) assert sdpa256._should_route(q, k, None, "causal", None) is False @@ -724,10 +793,8 @@ class _Fake: assert "OMLX_SDPA256_TILED=1" in msg -def test_scheduler_init_registers_headroom_provider(_sdpa256_provider_reset): - """Constructing a Scheduler must wire the provider (the production seam: - a rename that silently skips registration would revert #2204 to an - unbounded default).""" +def test_scheduler_step_registers_headroom_provider(_sdpa256_provider_reset): + """Scheduler.step must bind its provider on the model execution thread.""" from unittest.mock import MagicMock from omlx.scheduler import Scheduler, SchedulerConfig @@ -742,9 +809,9 @@ def test_scheduler_init_registers_headroom_provider(_sdpa256_provider_reset): tokenizer=tokenizer, config=SchedulerConfig(paged_cache_block_size=0), ) - ref = sdpa256._HEADROOM_PROVIDER - assert ref is not None - bound = ref() + assert sdpa256._get_unfused_headroom_provider() is None + scheduler.step() + bound = sdpa256._get_unfused_headroom_provider() assert bound is not None assert bound.__self__ is scheduler # Ceiling not propagated yet -> negative sentinel keeps the bounded default. From 8327920452bd4180407f8fd8c4100f0a4dafca67 Mon Sep 17 00:00:00 2001 From: jundot Date: Sun, 6 Sep 2026 23:18:11 +0900 Subject: [PATCH 107/132] fix: remove QSA decode sync and restore MXFP4 dispatch (#3428, #3409) --- omlx/patches/deepseek_v4/switch_layers.py | 39 +++---- omlx/patches/m5_gather_qmm.py | 5 - omlx/patches/mlx_lm_mtp/batch_generator.py | 12 +- .../mlx_vlm/models/qwen4_exp/language.py | 105 +----------------- tests/test_deepseek_v4_patch.py | 64 +++++++++-- tests/test_glm_moe_dsa_patch.py | 13 +-- tests/test_mlx_lm_mtp_patch.py | 8 +- tests/test_qwen4_qsa_decode_gather.py | 32 ++++++ 8 files changed, 119 insertions(+), 159 deletions(-) diff --git a/omlx/patches/deepseek_v4/switch_layers.py b/omlx/patches/deepseek_v4/switch_layers.py index e6a9ee89a9..b987107eda 100644 --- a/omlx/patches/deepseek_v4/switch_layers.py +++ b/omlx/patches/deepseek_v4/switch_layers.py @@ -21,25 +21,8 @@ _DEEPSEEK_MXFP4_LARGE_BLOCK_BM = 32 _DEEPSEEK_MXFP4_LARGE_BLOCK_VARIANT = 2 _DEEPSEEK_AFFINE_LARGE_BLOCK_MIN_ROUTES = 8192 -# Below this many (token, expert) routes the stock unsorted gather_qmm runs; -# at/above it routes are sorted by expert. Measured on M1 Ultra, GLM-5.3 oQ2e -# (affine 2-bit, g64), one MoE layer, ms per layer: -# T=4: unsorted 1.23 · sorted stock 1.11 · sorted native blocks 2.95 -# T=8: unsorted 2.10 · sorted stock 1.91 · sorted native blocks 5.13 -# T=64: unsorted 12.3 · sorted stock 10.7 · sorted native blocks 15.8 -# T=128: unsorted 24.2 · sorted stock 20.9 · sorted native blocks 19.4 -# Sorting pays from T=4 (32 routes); the affine block kernel only pays past -# ~900 routes, so it has its own floor below. The old single threshold of 64 -# routes sent every 8..110-token window (DFlash block-8 verify, batched -# decode at B>=8) down the block kernel at 2-2.7x the cost. -# Route-count crossovers for the affine (oQ 2/3-bit) MoE path, measured on -# M1 Ultra with real GLM-5.3-Flash expert weights (2-bit, group 64): -# - sorting the routes pays off from 32 routes; -# - the native block kernels only beat mx.gather_qmm from ~1024 routes -# (the crossover sits at T=128 x 8 experts); below it they cost 2-2.7x. -# The single 64-route gate that engaged both at once sat exactly in the -# losing region. Same pattern as _DEEPSEEK_MXFP4_LARGE_BLOCK_MIN_ROUTES below: -# tuned on one machine, overridable per deployment. +# Affine 2/3-bit g64 crossovers measured on M1 Ultra. Other formats keep +# their existing 64-route sorting threshold. _SORT_MIN_ROUTES = int(os.environ.get("OMLX_DEEPSEEK_SORT_MIN_ROUTES", "32")) _AFFINE_NATIVE_MIN_ROUTES = int( os.environ.get("OMLX_DEEPSEEK_AFFINE_BLOCK_MIN_ROUTES", "1024") @@ -72,6 +55,18 @@ def _nax_prefers_stock(num_routes: int) -> bool: return num_routes >= _NAX_STOCK_MIN_ROUTES +def _sort_threshold(*projections) -> int: + if all( + isinstance(p, QuantizedSwitchLinear) + and p.mode == "affine" + and p.bits in (2, 3) + and p.group_size == 64 + for p in projections + ): + return _SORT_MIN_ROUTES + return 64 + + def _gather_sort(x, indices): *_, M = indices.shape indices = indices.flatten() @@ -441,7 +436,9 @@ def __call__(self, x, indices, scores=None, weighted_sum=False) -> mx.array: x = mx.expand_dims(x, (-2, -3)) original_dtype = x.dtype - do_sort = indices.size >= _SORT_MIN_ROUTES + do_sort = indices.size >= _sort_threshold( + self.gate_proj, self.up_proj, self.down_proj + ) idx = indices inv_order = None if do_sort: @@ -619,7 +616,7 @@ def __init__( def __call__(self, x, indices) -> mx.array: x = mx.expand_dims(x, (-2, -3)) - do_sort = indices.size >= _SORT_MIN_ROUTES + do_sort = indices.size >= _sort_threshold(self.fc1, self.fc2) idx = indices inv_order = None if do_sort: diff --git a/omlx/patches/m5_gather_qmm.py b/omlx/patches/m5_gather_qmm.py index a205345afa..2ef3cec75a 100644 --- a/omlx/patches/m5_gather_qmm.py +++ b/omlx/patches/m5_gather_qmm.py @@ -59,11 +59,6 @@ # ml-explore/mlx#3856: sorted row offsets overflow int16 past this count. _MAX_SORTED_ROWS = 32768 -# Advertises to callers (e.g. the scheduler's prefill-chunk policy) that -# oversized sorted calls are segmented rather than demoted to the unsorted -# kernel, so a wide chunk keeps the NAX rhs path. -SEGMENTS_SORTED_ROWS = True - _original_gather_qmm = None _defective: bool | None = None diff --git a/omlx/patches/mlx_lm_mtp/batch_generator.py b/omlx/patches/mlx_lm_mtp/batch_generator.py index a6b367f2db..66b99e62b9 100644 --- a/omlx/patches/mlx_lm_mtp/batch_generator.py +++ b/omlx/patches/mlx_lm_mtp/batch_generator.py @@ -3214,13 +3214,13 @@ def _chain_rollback( except Exception as exc: logger.debug("rollback_speculative_cache failed: %s", exc) return False - # The mlx-vlm runtimes stamp ``mtp_partial_rollback`` on the inner - # LanguageModel, but the batch sees oMLX's ``VLMModelAdapter`` wrapper, - # which does not forward it — measured on GLM-5.3 vision: every reject - # raised "cache layer rejects chain rollback" and reconciled (2 tok/s). + # VLM adapters keep the rollback hook on the inner language model. rollback = None - for candidate in (model, getattr(model, "language_model", None), - getattr(model, "_language_model", None)): + for candidate in ( + model, + getattr(model, "language_model", None), + getattr(model, "_language_model", None), + ): rollback = getattr(candidate, "mtp_partial_rollback", None) if callable(rollback): break 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 a7f5bd90a1..60e3d24289 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 @@ -1,9 +1,7 @@ from __future__ import annotations import json -import logging import math -import time import mmap import os import struct @@ -40,9 +38,6 @@ _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]] = [] -_LAST_QSA_PATH_LOG: dict[tuple[str, int, int | None], float] = {} -_QSA_PATH_LOG_MIN_INTERVAL_S = 5.0 -logger = logging.getLogger("omlx.qwen4_qsa") def _broadcast_text_mrope_position_ids( @@ -77,15 +72,7 @@ def _broadcast_text_mrope_position_ids( def _gathered_min_query_tokens() -> int: - """Query rows below which the official mask+SDPA path is faster. - - Measured on an M5 Max at 12k/48k/206k context (Qwen3.8-Flash-Next - geometry, native kernels): the per-row gather of ``token_budget`` K/V - rows costs more than MLX's masked SDPA over the full cache until about - eight query rows, and the official path wins by 1.4-3x for the 1-4 row - windows Lightning MTP issues. Real prefill chunks are far wider. - ``OMLX_QWEN4_GATHERED_MIN_QUERY`` overrides the default of 16. - """ + """Keep narrow Lightning MTP windows on masked SDPA (M5 crossover).""" raw = os.environ.get("OMLX_QWEN4_GATHERED_MIN_QUERY", "").strip() if raw: try: @@ -116,72 +103,6 @@ def _split_text_mrope_positions( return position_ids, position_ids -def _log_qsa_prefill_path( - path: str, - *, - kv_len: int, - query: int, - position_ndim: int | None, -) -> None: - # Consecutive-key dedup alone never fires: a decode loop alternates - # (path, query, ndim) every cycle (ndim 3 <-> None in interleaved - # requests) and kv_len changes on every call. Throttle each distinct - # key to one line per interval instead. - global _LAST_QSA_PATH_LOG - key = (path, query, position_ndim) - now = time.monotonic() - last = _LAST_QSA_PATH_LOG.get(key) - if last is not None and now - last < _QSA_PATH_LOG_MIN_INTERVAL_S: - return - _LAST_QSA_PATH_LOG[key] = now - logger.info( - "qwen4 QSA prefill path=%s query=%d kv_len=%d position_ids.ndim=%s", - path, - query, - kv_len, - position_ndim, - ) - - -def _python_cache_offset(offset: Any) -> int: - """Scalar KV length for logging. Batched offsets use the longest row. - - ``BatchQSAKVCache.offset`` is an ``mx.array`` of per-row lengths. ``int()`` - on that array raises ``[convert] Only length-1 arrays...`` and used to - abort the engine before eligibility could fail closed onto the official - path. Logging still wants one number; the longest row is the conservative - choice for ``kv_len``. - """ - if offset is None: - return 0 - if isinstance(offset, (int, np.integer)): - return int(offset) - shape = getattr(offset, "shape", None) - if shape is None: - try: - return int(offset) - except (TypeError, ValueError): - return 0 - size = 1 - for dim in shape: - size *= int(dim) - if size <= 1: - value = offset.reshape(-1)[0] if size == 1 else offset - return int(value.item()) if hasattr(value, "item") else int(value) - return int(mx.max(offset).item()) - - -def _promote_index_positions_to_3d(positions: mx.array, planes: int) -> mx.array: - if positions.ndim == 3: - if int(positions.shape[0]) != planes: - raise ValueError( - "QSA indexer mRoPE plane count mismatch during cache extend: " - f"{tuple(int(d) for d in positions.shape)} vs planes={planes}" - ) - return positions - return mx.broadcast_to(positions[None], (planes, *positions.shape)) - - @dataclass(frozen=True) class Qwen4ExpMTPRuntime: """Lightning MTP construction decision for the next model load.""" @@ -522,11 +443,7 @@ def pooled_indexer_keys( def _trim_indexer(self, length: int): self._index_offset = min(self._index_offset, max(0, int(length))) - # Pooled blocks strictly below the new complete-block count are built - # from raw keys that trim does not touch, so keep them and only clamp - # the pooled frontier. Lightning MTP trims after every rejected - # draft; a full invalidation re-pooled every block of the context on - # the next call (1.75 ms/layer at 206k tokens). + # Trim leaves completed prefix blocks intact; only re-pool the new tail. if self._pooled_index_keys is not None and self._pooled_index_ratio: self._pooled_index_offset = min( self._pooled_index_offset, @@ -1579,11 +1496,6 @@ def __call__( position_embeddings: Optional[tuple[mx.array, mx.array]] = None, target_verify: bool = False, ) -> mx.array: - query = int(x.shape[1]) if x.ndim == 3 else 0 - kv_len = _python_cache_offset(getattr(cache, "offset", 0)) + query - position_ndim = ( - int(position_ids.ndim) if isinstance(position_ids, mx.array) else None - ) if self._gathered_text_decode_eligible( x, mask, @@ -1603,23 +1515,10 @@ def __call__( target_verify, ): cache._omlx_last_prefill_gathered = True - _log_qsa_prefill_path( - "gathered", - kv_len=kv_len, - query=query, - position_ndim=position_ndim, - ) return self._gathered_text_prefill(x, cache, position_ids) if cache is not None and x.ndim == 3 and x.shape[1] > 1: cache._omlx_last_prefill_gathered = False - if query > 1: - _log_qsa_prefill_path( - "mask_dense", - kv_len=kv_len, - query=query, - position_ndim=position_ndim, - ) qsa_mask = self.indexer( x, cache, diff --git a/tests/test_deepseek_v4_patch.py b/tests/test_deepseek_v4_patch.py index 32e74dafcb..b670c784a6 100644 --- a/tests/test_deepseek_v4_patch.py +++ b/tests/test_deepseek_v4_patch.py @@ -2373,9 +2373,7 @@ def test_tile_stays_under_int32_index_limit(self, applied_patch): class TestAffineBlockRouteThreshold: - """The affine block kernels must not engage below the measured crossover: - at 64 routes they cost 2-2.7x the plain gather (M1 Ultra, GLM-5.3-Flash - 2-bit experts). The decision is testable without the Metal kernel.""" + """Affine blocks require enough routes to amortize their setup cost.""" def _linear(self): from omlx.patches.deepseek_v4 import switch_layers as sl @@ -2411,7 +2409,59 @@ def test_thresholds_default_to_the_measured_crossovers(self): assert sl._SORT_MIN_ROUTES == 32 assert sl._AFFINE_NATIVE_MIN_ROUTES == 1024 - # both are environment-overridable, like the mxfp4 neighbour - src = open(sl.__file__, encoding="utf-8").read() - assert "OMLX_DEEPSEEK_SORT_MIN_ROUTES" in src - assert "OMLX_DEEPSEEK_AFFINE_BLOCK_MIN_ROUTES" in src + + +@pytest.mark.parametrize("family", ["glu", "mlp"]) +@pytest.mark.parametrize( + "mode,bits,group,sort_at_32", + [ + ("affine", 2, 64, True), + ("affine", 4, 64, False), + ("mxfp4", 4, 32, False), + (None, None, None, False), + ], +) +@pytest.mark.parametrize("tokens", [4, 8]) +def test_switch_sorting_preserves_other_formats( + monkeypatch, family, mode, bits, group, sort_at_32, tokens +): + import mlx.core as mx + + from omlx.patches.deepseek_v4 import switch_layers as sl + + mx.random.seed(3409) + if family == "glu": + model = sl.SwitchGLU(128, 64, 8) + names = ("gate_proj", "up_proj", "down_proj") + else: + model = sl.SwitchMLP(128, 64, 8) + names = ("fc1", "fc2") + if mode is not None: + for name in names: + layer = getattr(model, name).to_quantized( + group_size=group, bits=bits, mode=mode + ) + if mode == "affine": + layer.scales = layer.scales.astype(mx.float16) + layer.biases = layer.biases.astype(mx.float16) + setattr(model, name, layer) + + hidden = (mx.random.normal((1, tokens, 128)) * 0.1).astype(mx.float16) + indices = mx.random.randint(0, 8, (1, tokens, 8)).astype(mx.uint32) + calls = [] + original_sort = sl._gather_sort + + def tracked_sort(x, indices): + calls.append(indices.size) + return original_sort(x, indices) + + monkeypatch.setattr(sl, "_gather_sort", tracked_sort) + actual = model(hidden, indices) + mx.eval(actual) + should_sort = tokens == 8 or sort_at_32 + assert calls == ([tokens * 8] if should_sort else []) + + monkeypatch.setattr(sl, "_sort_threshold", lambda *args: 10**9) + expected = model(hidden, indices) + mx.eval(expected) + assert mx.allclose(actual, expected, rtol=1e-2, atol=1e-3).item() diff --git a/tests/test_glm_moe_dsa_patch.py b/tests/test_glm_moe_dsa_patch.py index c5d7622081..e9fa5351df 100644 --- a/tests/test_glm_moe_dsa_patch.py +++ b/tests/test_glm_moe_dsa_patch.py @@ -821,9 +821,7 @@ def single_spy(*args, **kwargs): monkeypatch.setattr(fast, "deepseek_affine_gather_qmm_pair_concat_blocks", pair_spy) monkeypatch.setattr(fast, "deepseek_affine_gather_qmm_blocks", single_spy) - # 512 tokens x 2 = 1024 routes: the affine block kernels only engage from - # _AFFINE_NATIVE_MIN_ROUTES (below that the sorted stock gather_qmm is - # faster — measured in switch_layers.py). + # Reach the 1024-route affine block threshold. x = mx.random.normal((1, 512, 128), dtype=mx.bfloat16) indices = mx.array( [[[(i + j) % 8 for j in range(2)] for i in range(512)]], @@ -885,9 +883,7 @@ def single_spy(x, *args, **kwargs): monkeypatch.setattr(fast, "deepseek_affine_gather_qmm_pair_concat_blocks", pair_spy) monkeypatch.setattr(fast, "deepseek_affine_gather_qmm_blocks", single_spy) - # 512 tokens x 2 = 1024 routes: the affine block kernels only engage from - # _AFFINE_NATIVE_MIN_ROUTES (below that the sorted stock gather_qmm is - # faster — measured in switch_layers.py). + # Reach the 1024-route affine block threshold. x = mx.random.normal((1, 512, 128), dtype=mx.bfloat16) indices = mx.array( [[[(i + j) % 8 for j in range(2)] for i in range(512)]], @@ -1337,10 +1333,7 @@ def test_glm_adaptive_decode_clears_only_on_the_512_step_cadence(): def test_deepseek_switchglu_keeps_small_windows_off_the_block_kernels(monkeypatch): - """8..110-token windows (DFlash block-8 verify, batched decode) used to be - sent down the affine block kernel at 2-2.7x the cost of the sorted stock - gather_qmm (measured on M1 Ultra, GLM-5.3 oQ2e). Below - _AFFINE_NATIVE_MIN_ROUTES the block kernel must stay out.""" + """Small affine windows use stock gather_qmm after sorting.""" mx = pytest.importorskip("mlx.core") pytest.importorskip("mlx.nn") from omlx.custom_kernels.glm_moe_dsa import fast diff --git a/tests/test_mlx_lm_mtp_patch.py b/tests/test_mlx_lm_mtp_patch.py index 66901cd3d5..f082a640d8 100644 --- a/tests/test_mlx_lm_mtp_patch.py +++ b/tests/test_mlx_lm_mtp_patch.py @@ -2948,13 +2948,7 @@ def __call__(self, inputs, cache=None, return_hidden=False): def test_chain_rollback_finds_the_method_behind_the_vlm_adapter(): - """On the server the batch does not see the LanguageModel: it sees - ``VLMModelAdapter``, which does not forward ``mtp_partial_rollback``. The - chain rollback looked only at the wrapper, found nothing, and EVERY reject - fell through to "cache layer rejects chain rollback" plus a reconcile — - measured on a GLM-5.3 vision checkpoint at 2 tok/s with cycles=0. It now - looks at the inner model too. - """ + """Partial rollback reaches the language model through its adapter.""" from omlx.patches.mlx_lm_mtp import batch_generator as bg calls = [] diff --git a/tests/test_qwen4_qsa_decode_gather.py b/tests/test_qwen4_qsa_decode_gather.py index 55f1caed96..972eec06fd 100644 --- a/tests/test_qwen4_qsa_decode_gather.py +++ b/tests/test_qwen4_qsa_decode_gather.py @@ -503,3 +503,35 @@ def test_qwen4_trim_then_decode_matches_official_after_partial_invalidation( expected = attention(token, mask=None, cache=reference_cache) mx.eval(actual, expected) assert mx.array_equal(actual, expected).item() + + +def test_qwen4_batched_decode_does_not_read_gpu_scalars(monkeypatch): + config = _tiny_text_config() + language = _language() + attention = language.Qwen4ExpAttention(config) + cache = language.BatchQSAKVCache([0, 0]) + hidden = mx.random.normal((2, 1, config.hidden_size)) + mx.eval(attention.parameters(), hidden) + + def unexpected_scalar_read(*args, **kwargs): + raise AssertionError("Batched attention must not read GPU scalars") + + with monkeypatch.context() as patch: + patch.setattr(mx.array, "item", unexpected_scalar_read) + for _ in range(3): + positions = mx.broadcast_to(cache.offset[None, :, None], (3, 2, 1)) + mx.eval(attention(hidden, cache=cache, position_ids=positions)) + + assert cache.offset.tolist() == [3, 3] + + +def test_qwen4_prefill_memory_marker_tracks_query_width(): + config = _tiny_text_config() + language = _language() + attention = language.Qwen4ExpAttention(config) + cache = _crossover_cache(config, attention) + + mx.eval(attention(mx.zeros((1, 4, config.hidden_size)), cache=cache)) + assert cache._omlx_last_prefill_gathered is False + mx.eval(attention(mx.zeros((1, 16, config.hidden_size)), cache=cache)) + assert cache._omlx_last_prefill_gathered is True From aa8db73496bd8367989e2862f50b315885b9b91a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 7 Sep 2026 00:22:27 +1000 Subject: [PATCH 108/132] build(deps): bump ddgs from 9.15.0 to 9.16.0 (#3474) Bumps [ddgs](https://github.com/deedy5/ddgs) from 9.15.0 to 9.16.0. - [Release notes](https://github.com/deedy5/ddgs/releases) - [Commits](https://github.com/deedy5/ddgs/compare/v9.15.0...v9.16.0) --- updated-dependencies: - dependency-name: ddgs dependency-version: 9.16.0 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 12d8fdd797..9430104b57 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -99,7 +99,7 @@ dependencies = [ # cutoff (2026-04-23), and the last with the minimal dep tree # (click/primp/lxml only; 9.14.2+ adds fake-useragent and httpx # extras). Bump together with the cutoff. - "ddgs==9.15.0", + "ddgs==9.16.0", "tabulate>=0.9.0", # Resource monitoring "psutil>=5.9.0", From 0ca0953d7dff1e44237994a1e429d5a5f663158e Mon Sep 17 00:00:00 2001 From: Qianhe Chen <54462604+chenqianhe@users.noreply.github.com> Date: Tue, 8 Sep 2026 08:55:01 +0800 Subject: [PATCH 109/132] fix: yield between contended prefill chunks (#3487) --- omlx/scheduler.py | 19 +- tests/test_prefill_fairness_budget.py | 292 ++++++++++++++++++++++++++ 2 files changed, 303 insertions(+), 8 deletions(-) create mode 100644 tests/test_prefill_fairness_budget.py diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 42c12a4961..d22b6af312 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -3842,6 +3842,8 @@ def _do_external_prefill( # Reclaim Metal intermediates between prefill chunks. Scheduler._clear_cache(self) + if vlm_embeds is None: + self._accrue_decode_debt(time.perf_counter() - _trace_chunk_start) if getattr(request, "benchmark_trace", False): _trace_total_ms = ( time.perf_counter() - _trace_chunk_start @@ -5743,12 +5745,12 @@ def _advance_chunked_prefills( scheduled: "list[Request]", rejected: "list[RequestOutput]", ) -> None: - """Process one prefill chunk per in-flight chunked-prefill request. + """Advance in-flight prefills until decode fairness requires a yield. Called at the start of each step() before _schedule_waiting(). Each - call advances every request in self.prefilling by one prefill_step_size - chunk. When a request's prefill completes it is inserted into - BatchGenerator and moved to self.running. + request advances by at most one chunk. Deferred requests precede + already-advanced requests in the next round. Completed prefills are + inserted into BatchGenerator and moved to self.running. Args: scheduled: The step's running list of newly-scheduled requests; @@ -5772,6 +5774,10 @@ def _advance_chunked_prefills( if state is None: continue + if not self._prefill_gate_open(): + still_prefilling.extendleft(reversed(pending_prefills[index:])) + break + try: done = self._step_prefill_chunk(state) except _PrefillAbortedError: @@ -10414,10 +10420,7 @@ def _schedule_waiting( # admissions. This is also the per-step admission budget — # prefills can no longer chain back-to-back inside one step # while decodes wait. - if self._decode_fairness and ( - (self.running and self._decode_time_owed_s > 0.0) - or time.perf_counter() < self._prefill_hold_deadline() - ): + if not self._prefill_gate_open(): break # Store-cache backpressure: when the post-completion pipeline is diff --git a/tests/test_prefill_fairness_budget.py b/tests/test_prefill_fairness_budget.py new file mode 100644 index 0000000000..44450837a7 --- /dev/null +++ b/tests/test_prefill_fairness_budget.py @@ -0,0 +1,292 @@ +"""Regressions for sharing decode time between consecutive prefill forwards.""" + +from itertools import count +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import mlx.core as mx +import pytest + +from omlx.decode_activity import get_decode_activity +from omlx.prefill_progress import get_prefill_tracker +from omlx.request import Request, SamplingParams +from omlx.scheduler import ( + Scheduler, + SchedulerConfig, + _PrefillAbortedError, + _PrefillState, +) + + +@pytest.fixture(autouse=True) +def isolated_activity(): + get_decode_activity().clear() + get_prefill_tracker().clear() + with patch("omlx.scheduler._sync_and_clear_cache"): + yield + get_decode_activity().clear() + get_prefill_tracker().clear() + + +@pytest.fixture +def clock(monkeypatch): + current = SimpleNamespace(now=100.0) + monkeypatch.setattr("omlx.scheduler.time.perf_counter", lambda: current.now) + return current + + +def make_scheduler(**settings) -> Scheduler: + model = MagicMock() + model.layers = [] + tokenizer = MagicMock() + tokenizer.eos_token_id = 2 + config = SchedulerConfig( + **{ + "max_num_seqs": 8, + "prefill_step_size": 4, + "chunked_prefill": True, + "paged_cache_block_size": 0, + **settings, + } + ) + scheduler = Scheduler(model=model, tokenizer=tokenizer, config=config) + batch_generator = MagicMock() + next_uid = count(42) + batch_generator.insert.side_effect = lambda *args, **kwargs: [next(next_uid)] + batch_generator.next_generated.return_value = iter([]) + scheduler.batch_generator = batch_generator + scheduler._current_sampler_params = () + return scheduler + + +def make_request(request_id: str, token_count: int = 20) -> Request: + tokens = list(range(token_count)) + request = Request( + request_id=request_id, + prompt=tokens, + sampling_params=SamplingParams(max_tokens=32), + ) + request.prompt_token_ids = tokens + request.num_prompt_tokens = len(tokens) + request.remaining_tokens = tokens + return request + + +def add_prefill(scheduler: Scheduler, request_id: str) -> Request: + request = make_request(request_id) + scheduler.requests[request_id] = request + scheduler.prefilling.append(request) + scheduler._prefill_states[request_id] = _PrefillState( + request=request, + cache=[], + tokens_remaining=mx.zeros((1, request.num_prompt_tokens - 1), dtype=mx.int32), + last_token=request.prompt_token_ids[-1:], + tokens_processed=0, + base_size=0, + emitted_boundaries={}, + boundary_enabled=False, + block_size=0, + total_length=request.num_prompt_tokens, + sampler=MagicMock(), + sm=MagicMock(), + per_row_lps=[], + ) + return request + + +def prefill_ids(scheduler: Scheduler) -> list[str]: + return [request.request_id for request in scheduler.prefilling] + + +def test_each_forward_rechecks_debt_and_rotates_without_starvation(): + scheduler = make_scheduler() + scheduler.running["decoder"] = make_request("decoder") + request_ids = ["prefill-a", "prefill-b", "prefill-c"] + for request_id in request_ids: + add_prefill(scheduler, request_id) + advanced = [] + + def advance(state): + advanced.append(state.request.request_id) + scheduler._accrue_decode_debt(0.5) + return False + + with patch.object(scheduler, "_step_prefill_chunk", side_effect=advance): + for turn, request_id in enumerate(request_ids * 2): + scheduler._advance_chunked_prefills([], []) + assert advanced == (request_ids * 2)[: turn + 1] + assert prefill_ids(scheduler)[-1] == request_id + assert scheduler._decode_time_owed_s > 0 + scheduler._advance_chunked_prefills([], []) + assert len(advanced) == turn + 1 + scheduler._repay_decode_debt(scheduler._decode_time_owed_s) + + assert prefill_ids(scheduler) == request_ids + + +def test_shared_hold_from_another_prefiller_interrupts_current_loop(clock): + scheduler = make_scheduler() + other_prefiller = make_scheduler() + get_decode_activity().publish("decoding-engine", 1) + for request_id in ("prefill-a", "prefill-b", "prefill-c"): + add_prefill(scheduler, request_id) + advanced = [] + + def advance(state): + advanced.append(state.request.request_id) + other_prefiller._accrue_decode_debt(0.5) + return False + + with patch.object(scheduler, "_step_prefill_chunk", side_effect=advance): + scheduler._advance_chunked_prefills([], []) + assert advanced == ["prefill-a"] + assert scheduler._prefill_hold_until == 0 + assert prefill_ids(scheduler) == ["prefill-b", "prefill-c", "prefill-a"] + scheduler._advance_chunked_prefills([], []) + assert advanced == ["prefill-a"] + clock.now = get_decode_activity().hold_until() + scheduler._advance_chunked_prefills([], []) + + assert advanced == ["prefill-a", "prefill-b"] + assert prefill_ids(scheduler) == ["prefill-c", "prefill-a", "prefill-b"] + + +@pytest.mark.parametrize( + ("decode_fairness", "has_decoder"), [(True, False), (False, True)] +) +def test_uncontended_or_disabled_fairness_keeps_advancing_all_requests( + decode_fairness, has_decoder +): + scheduler = make_scheduler(decode_fairness=decode_fairness) + if has_decoder: + scheduler.running["decoder"] = make_request("decoder") + request_ids = ["prefill-a", "prefill-b", "prefill-c"] + for request_id in request_ids: + add_prefill(scheduler, request_id) + advanced = [] + + def advance(state): + advanced.append(state.request.request_id) + scheduler._accrue_decode_debt(0.5) + return False + + with patch.object(scheduler, "_step_prefill_chunk", side_effect=advance): + scheduler._advance_chunked_prefills([], []) + + assert advanced == request_ids + assert prefill_ids(scheduler) == request_ids + assert scheduler._decode_time_owed_s == 0 + + +def test_completed_request_creates_contention_for_remaining_prefills(): + scheduler = make_scheduler() + completed = add_prefill(scheduler, "completed") + add_prefill(scheduler, "prefill-a") + add_prefill(scheduler, "prefill-b") + scheduled = [] + rejected = [] + advanced = [] + + def advance(state): + advanced.append(state.request.request_id) + scheduler._accrue_decode_debt(0.5) + return state.request is completed + + with patch.object(scheduler, "_step_prefill_chunk", side_effect=advance): + scheduler._advance_chunked_prefills(scheduled, rejected) + + assert advanced == ["completed", "prefill-a"] + assert scheduled == [completed] + assert rejected == [] + assert scheduler.running == {"completed": completed} + assert "completed" not in scheduler._prefill_states + assert prefill_ids(scheduler) == ["prefill-b", "prefill-a"] + + +def test_missing_and_aborted_rows_do_not_discard_waiting_prefills(): + scheduler = make_scheduler() + scheduler.running["decoder"] = make_request("decoder") + scheduler.prefilling.append(make_request("missing")) + add_prefill(scheduler, "aborted") + add_prefill(scheduler, "prefill-a") + add_prefill(scheduler, "prefill-b") + advanced = [] + + def advance(state): + advanced.append(state.request.request_id) + scheduler._accrue_decode_debt(0.5) + if state.request.request_id == "aborted": + raise _PrefillAbortedError([], 4) + return False + + with patch.object(scheduler, "_step_prefill_chunk", side_effect=advance): + scheduler._advance_chunked_prefills([], []) + assert advanced == ["aborted"] + assert prefill_ids(scheduler) == ["prefill-a", "prefill-b"] + assert "aborted" not in scheduler._prefill_states + scheduler._repay_decode_debt(scheduler._decode_time_owed_s) + scheduler._advance_chunked_prefills([], []) + + assert advanced == ["aborted", "prefill-a"] + assert prefill_ids(scheduler) == ["prefill-b", "prefill-a"] + + +def test_inflight_chunk_debt_defers_new_admission_until_decode_runs(): + scheduler = make_scheduler() + scheduler.running["decoder"] = make_request("decoder") + add_prefill(scheduler, "inflight-a") + add_prefill(scheduler, "inflight-b") + waiting = make_request("waiting") + scheduler.add_request(waiting) + events = [] + + def advance(state): + events.append(state.request.request_id) + scheduler._accrue_decode_debt(0.5) + return False + + def decode(): + events.append("decode") + return iter([]) + + scheduler.batch_generator.next_generated.side_effect = decode + with ( + patch.object(scheduler, "_step_prefill_chunk", side_effect=advance), + patch.object(scheduler, "_begin_prefill") as begin, + patch.object(scheduler, "_do_external_prefill") as external, + ): + output = scheduler.step() + + assert events == ["inflight-a", "decode"] + assert list(scheduler.waiting) == [waiting] + assert output.has_work + begin.assert_not_called() + external.assert_not_called() + + +def test_short_external_prefills_share_admission_debt(clock): + scheduler = make_scheduler() + scheduler.running["decoder"] = make_request("decoder") + requests = [make_request(request_id, 3) for request_id in ("short-a", "short-b")] + for request in requests: + scheduler.add_request(request) + forwarded = [] + + def forward(tokens, **kwargs): + forwarded.append(tokens.shape[1]) + clock.now += 0.5 + + scheduler.model.side_effect = forward + with patch("omlx.scheduler.make_prompt_cache", return_value=[]): + scheduled, rejected = scheduler._schedule_waiting() + assert scheduled == [requests[0]] + assert rejected == [] + assert list(scheduler.waiting) == [requests[1]] + assert forwarded == [2] + scheduler._repay_decode_debt(scheduler._decode_time_owed_s) + scheduled, rejected = scheduler._schedule_waiting() + + assert scheduled == [requests[1]] + assert rejected == [] + assert not scheduler.waiting + assert forwarded == [2, 2] From 0b1103b3b413521fc3364df16005b69fa8cf63cf Mon Sep 17 00:00:00 2001 From: Max Freedom Pollard <272618364+MaxFreedomPollard@users.noreply.github.com> Date: Mon, 7 Sep 2026 21:17:06 -0400 Subject: [PATCH 110/132] fix(eval): stop a comma from swallowing the GSM8K answer (#3484) _extract_numeric_answer falls back to the last number in the response when the model does not emit the "#### N" marker. Its fallback pattern -?[\d,]+(?:\.\d+)? also matches a bare comma, because [\d,]+ needs only one character from the class. Any comma after the final digit therefore became the last "number" in the text, and .replace(",", "") turned it into an empty string. "The total is 72 clips, altogether." extracted "" instead of "72", so check_answer returned False on a correct response and the question was scored wrong (parse_error on the external-API path). Anchor the pattern on a digit at both ends: -?\d(?:[\d,]*\d)?(?:\.\d+)?. Thousands separators still match, since they sit between digits. The "####" branch uses the same pattern. All 1,319 gold answers in omlx/eval/data/gsm8k_test.jsonl extract identically before and after, so scoring keys are untouched. --- omlx/eval/gsm8k.py | 11 +++++++++-- tests/test_eval.py | 17 +++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/omlx/eval/gsm8k.py b/omlx/eval/gsm8k.py index 53a882ac43..1a5f9b1137 100644 --- a/omlx/eval/gsm8k.py +++ b/omlx/eval/gsm8k.py @@ -43,16 +43,23 @@ ] +# A number, with optional thousands separators. The digit anchors at both +# ends matter: ``[\d,]+`` alone also matches a bare comma, so punctuation +# after the final digit ("the answer is 18, which is the total") became the +# last "number" in the text and extraction returned an empty string. +_NUMBER_PATTERN = r"-?\d(?:[\d,]*\d)?(?:\.\d+)?" + + def _extract_numeric_answer(text: str) -> str: """Extract the final numeric answer from a GSM8K-style response. Looks for #### pattern first, then falls back to the last number. """ - match = re.search(r"####\s*(-?[\d,]+(?:\.\d+)?)", text) + match = re.search(rf"####\s*({_NUMBER_PATTERN})", text) if match: return match.group(1).replace(",", "") - numbers = re.findall(r"-?[\d,]+(?:\.\d+)?", text) + numbers = re.findall(_NUMBER_PATTERN, text) if numbers: return numbers[-1].replace(",", "") diff --git a/tests/test_eval.py b/tests/test_eval.py index d57a7772e0..32efa9697b 100644 --- a/tests/test_eval.py +++ b/tests/test_eval.py @@ -156,6 +156,23 @@ def test_extract_numeric_answer_fallback(self): assert _extract_numeric_answer("The answer is 42.") == "42" assert _extract_numeric_answer("She has 15 apples and 20 oranges, so 35 total.") == "35" + def test_extract_numeric_answer_trailing_comma_after_last_number(self): + # A bare "," is not a number: punctuation after the final digit must + # not become the extracted answer. + assert _extract_numeric_answer("The total is 72 clips, altogether.") == "72" + assert ( + _extract_numeric_answer("Thus, the answer is 18, which is the total.") + == "18" + ) + assert _extract_numeric_answer("He gave away 8 lollipops,") == "8" + + def test_extract_numeric_answer_keeps_thousands_separator(self): + assert _extract_numeric_answer("The final total is 1,234 dollars.") == "1234" + assert _extract_numeric_answer("That comes to 1,234.50, in the end.") == "1234.50" + + def test_extract_numeric_answer_commas_only(self): + assert _extract_numeric_answer("Well, hmm, no idea,") == "" + def test_extract_numeric_answer_empty(self): assert _extract_numeric_answer("I don't know") == "" assert _extract_numeric_answer("") == "" From 6645b4efab4fafb9b3220a4bf4695f22c69d723b Mon Sep 17 00:00:00 2001 From: ddark-il <44260906+ddark-il@users.noreply.github.com> Date: Tue, 8 Sep 2026 05:32:23 +0300 Subject: [PATCH 111/132] fix(qwen35_prefill): drop the wrong NAX qmm tile variant 6, add a tile benchmark (#3434) `OMLX_QWEN35_QMM_NAX_VARIANT=6` selected a 64x64x64 tile with wm=1, wn=4, i.e. a 16-column per-simdgroup N tile. On M5 Max / mlx 0.32.2 it returns wrong output: max abs error 5-8 against stock `quantized_matmul` at every tested shape, bit width (4/8) and group size, while variants 0-5 agree with stock to within a bf16 ulp. Remove the instantiation and the C++ table entry, validate the env knob in Python (out-of-range or non-numeric values warn once and fall back to variant 0 instead of raising from inside a prefill), and add a hardware test that checks every bundled tile against stock for q4/q8 x gs64/gs128. benchmarks/bench_qwen35_nax_qmm_variants.py times stock vs each bundled tile at Qwen4-Exp GDN/attention projection shapes. Results on M5 Max (mlx 0.32.2, ms per call, lower is better): q8/gs64 T stock v0 v2 v2/stock gdn.in_proj_qkv 8192 18.97 18.14 15.01 0.79 gdn.in_proj_z 8192 10.18 10.25 9.18 0.90 attn.q_proj 8192 19.57 19.38 17.16 0.88 attn.o_proj 8192 10.06 10.17 9.76 0.97 q4/gs64 gdn.in_proj_qkv 8192 8.14 7.99 8.96 1.10 attn.q_proj 8192 17.24 17.11 15.96 0.93 Variant 2 (bm=128) wins 5-20% at 8-bit but is mixed at 4-bit, so the default stays at variant 0 (the stock tile); the knob and the benchmark are there for per-model tuning. Claude-Session: https://claude.ai/code/session_01FUwVt6F1YHbTLvNvmAGEvU Co-authored-by: Claude Fable 5.1 --- benchmarks/bench_qwen35_nax_qmm_variants.py | 122 ++++++++++++++++++ .../qwen35_prefill/csrc/qwen35_prefill.cpp | 6 +- .../qwen35_prefill/csrc/qwen35_qmm_nax.metal | 6 +- omlx/custom_kernels/qwen35_prefill/fast.py | 30 ++++- tests/test_nax.py | 50 +++++++ 5 files changed, 206 insertions(+), 8 deletions(-) create mode 100644 benchmarks/bench_qwen35_nax_qmm_variants.py diff --git a/benchmarks/bench_qwen35_nax_qmm_variants.py b/benchmarks/bench_qwen35_nax_qmm_variants.py new file mode 100644 index 0000000000..25a40d5ff9 --- /dev/null +++ b/benchmarks/bench_qwen35_nax_qmm_variants.py @@ -0,0 +1,122 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Stock vs oMLX NAX qmm tiles for Qwen hybrid-layer projections on M5. + +The Qwen q4/q8 prefill-linear patch routes affine `QuantizedLinear` prefill +matmuls through the bundled `qwen35_q{bits}_affine_qmm_t` op, which on M5 +selects a NAX tile chosen by `OMLX_QWEN35_QMM_NAX_VARIANT` (0 = the tile +stock MLX ships). This benchmark times stock `mx.quantized_matmul` against +each bundled NAX tile variant (``fast.NAX_QMM_VARIANTS``) at the projection shapes of a Qwen4-Exp GDN / +attention layer, so the variant default and the q8 min-token threshold +(`OMLX_QWEN35_Q8_LINEAR_MIN_TOKENS`, 16384) can be set from numbers. + + python benchmarks/bench_qwen35_nax_qmm_variants.py --bits 8 --tokens 2048 8192 +""" + +from __future__ import annotations + +import argparse +import time + +import mlx.core as mx + +from omlx.custom_kernels.qwen35_prefill import fast + +# (name, N, K) — Qwen4-Exp hidden 2560, GDN 48v/16k heads x 128, attn 24q/2kv x 256 +SHAPES = [ + ("gdn.in_proj_qkv", 10240, 2560), + ("gdn.in_proj_z", 6144, 2560), + ("gdn.out_proj", 2560, 6144), + ("attn.q_proj", 12288, 2560), + ("attn.o_proj", 2560, 6144), +] + + +def _time(fn, iters): + for _ in range(2): + mx.eval(fn()) + mx.synchronize() + t0 = time.perf_counter() + for _ in range(iters): + mx.eval(fn()) + mx.synchronize() + return (time.perf_counter() - t0) / iters * 1e3 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--bits", type=int, default=8) + ap.add_argument("--group-size", type=int, default=64) + ap.add_argument("--tokens", type=int, nargs="+", default=[2048, 4096, 8192, 16384]) + ap.add_argument( + "--variants", type=int, nargs="+", default=list(fast.NAX_QMM_VARIANTS) + ) + ap.add_argument("--iters", type=int, default=10) + ap.add_argument("--shapes", nargs="+", default=[s[0] for s in SHAPES]) + args = ap.parse_args() + + if not fast.is_native_available(): + raise SystemExit(f"native extension unavailable: {fast.import_error()}") + native = getattr(fast, f"qwen35_q{args.bits}_affine_qmm_t") + print( + f"mlx {mx.__version__} {mx.device_info().get('device_name')} " + f"nax={fast.is_nax_available()} native_nax_qmm={fast._qmm_use_nax()} " + f"q{args.bits}/gs{args.group_size}" + ) + print( + f"{'shape':>16} {'N':>6} {'K':>5} {'T':>6} {'mode':>10} {'ms':>8} {'GFLOP/s':>9} {'maxerr':>8}" + ) + for name, n, k in SHAPES: + if name not in args.shapes: + continue + w = (mx.random.normal((n, k), key=mx.random.key(n * k)) * 0.02).astype( + mx.bfloat16 + ) + wq, sc, bi = mx.quantize(w, group_size=args.group_size, bits=args.bits) + mx.eval(wq, sc, bi) + for t in args.tokens: + x = mx.random.normal((1, t, k), key=mx.random.key(t)).astype(mx.bfloat16) + mx.eval(x) + flop = 2.0 * t * n * k + + def stock(x=x, wq=wq, sc=sc, bi=bi): + return mx.quantized_matmul( + x, + wq, + sc, + bi, + transpose=True, + group_size=args.group_size, + bits=args.bits, + ) + + ref = stock() + mx.eval(ref) + ms = _time(stock, args.iters) + print( + f"{name:>16} {n:>6} {k:>5} {t:>6} {'stock':>10} {ms:>8.2f} {flop / ms / 1e6:>9.0f} {'-':>8}" + ) + for v in args.variants: + fast.QMM_NAX_VARIANT = v + + def mine(x=x, wq=wq, sc=sc, bi=bi): + return native(x, wq, sc, bi, 8, args.group_size) + + try: + out = mine() + mx.eval(out) + except Exception as exc: # noqa: BLE001 + print( + f"{name:>16} {n:>6} {k:>5} {t:>6} {'nax v' + str(v):>10} {'error':>8} {exc}" + ) + continue + err = ( + mx.abs(out.astype(mx.float32) - ref.astype(mx.float32)).max().item() + ) + ms = _time(mine, args.iters) + print( + f"{name:>16} {n:>6} {k:>5} {t:>6} {'nax v' + str(v):>10} {ms:>8.2f} {flop / ms / 1e6:>9.0f} {err:>8.3g}" + ) + + +if __name__ == "__main__": + main() diff --git a/omlx/custom_kernels/qwen35_prefill/csrc/qwen35_prefill.cpp b/omlx/custom_kernels/qwen35_prefill/csrc/qwen35_prefill.cpp index d871360d0a..5baaf02513 100644 --- a/omlx/custom_kernels/qwen35_prefill/csrc/qwen35_prefill.cpp +++ b/omlx/custom_kernels/qwen35_prefill/csrc/qwen35_prefill.cpp @@ -131,8 +131,10 @@ QwenQAffineNaxVariant qwen_q_affine_nax_variant(int variant) { return {/* bm = */ 64, /* bk = */ 32, /* bn = */ 64, 2, 2}; case 5: return {/* bm = */ 64, /* bk = */ 64, /* bn = */ 64, 4, 1}; - case 6: - return {/* bm = */ 64, /* bk = */ 64, /* bn = */ 64, 1, 4}; + // (64, 64, 64, wm=1, wn=4) was variant 6: a 16-column per-simdgroup N + // tile that returns wrong output on M5 Max / mlx 0.32.2 (max abs err 5-8 + // against stock at every shape and bit width; the other tiles match + // exactly). Rejected rather than kept as an opt-in footgun. default: { std::ostringstream msg; msg << "Unsupported Qwen affine qmm NAX variant " << variant << "."; diff --git a/omlx/custom_kernels/qwen35_prefill/csrc/qwen35_qmm_nax.metal b/omlx/custom_kernels/qwen35_prefill/csrc/qwen35_qmm_nax.metal index 038a0d4763..983f7f8ccc 100644 --- a/omlx/custom_kernels/qwen35_prefill/csrc/qwen35_qmm_nax.metal +++ b/omlx/custom_kernels/qwen35_prefill/csrc/qwen35_qmm_nax.metal @@ -99,11 +99,7 @@ instantiate_qwen35_q_affine_qmm_t_nax( \ bits, group_suffix, float16_t, 64, 64, 64, 4, 1); \ instantiate_qwen35_q_affine_qmm_t_nax( \ - bits, group_suffix, bfloat16_t, 64, 64, 64, 4, 1); \ - instantiate_qwen35_q_affine_qmm_t_nax( \ - bits, group_suffix, float16_t, 64, 64, 64, 1, 4); \ - instantiate_qwen35_q_affine_qmm_t_nax( \ - bits, group_suffix, bfloat16_t, 64, 64, 64, 1, 4) + bits, group_suffix, bfloat16_t, 64, 64, 64, 4, 1) define_qwen35_q_affine_qmm_t_nax(4, 64, ) define_qwen35_q_affine_qmm_t_nax(5, 64, ) diff --git a/omlx/custom_kernels/qwen35_prefill/fast.py b/omlx/custom_kernels/qwen35_prefill/fast.py index 874f070e43..ef06fe4e08 100644 --- a/omlx/custom_kernels/qwen35_prefill/fast.py +++ b/omlx/custom_kernels/qwen35_prefill/fast.py @@ -824,7 +824,35 @@ def qmm_supports_group_size(group_size: int) -> bool: _stock_nax_cache: bool | None = None _qmm_nax_cache: bool | None = None -QMM_NAX_VARIANT = int(os.environ.get("OMLX_QWEN35_QMM_NAX_VARIANT", "0")) +# Bundled NAX tiles (must match qwen_q_affine_nax_variant in qwen35_prefill.cpp): +# 0: 64x64x64 wm2 wn2 (stock MLX tile, default) 1: bm 32 2: bm 128 +# 3: bn 128 4: bk 32 5: wm4 wn1 +# benchmarks/bench_qwen35_nax_qmm_variants.py compares them against stock. +NAX_QMM_VARIANTS = range(6) +_qmm_nax_variant_warned = False + + +def _resolve_qmm_nax_variant() -> int: + global _qmm_nax_variant_warned + raw = os.environ.get("OMLX_QWEN35_QMM_NAX_VARIANT", "0").strip() + try: + variant = int(raw) + except ValueError: + variant = -1 + if variant in NAX_QMM_VARIANTS: + return variant + if not _qmm_nax_variant_warned: + _qmm_nax_variant_warned = True + logger.warning( + "OMLX_QWEN35_QMM_NAX_VARIANT=%r is not a bundled NAX tile " + "(valid: 0-%d); using variant 0", + raw, + NAX_QMM_VARIANTS[-1], + ) + return 0 + + +QMM_NAX_VARIANT = _resolve_qmm_nax_variant() def _nax_available_fallback( diff --git a/tests/test_nax.py b/tests/test_nax.py index 353803ab17..a9975224a9 100644 --- a/tests/test_nax.py +++ b/tests/test_nax.py @@ -136,3 +136,53 @@ def test_ane_hybrid_nax_capability_reports_native_state(monkeypatch): def test_ane_hybrid_nax_capability_is_false_for_older_extension(monkeypatch): monkeypatch.setattr(fast, "_ext", types.SimpleNamespace()) assert fast.qwen35_ane_hybrid_nax_enabled() is False + + +@pytest.mark.parametrize( + ("raw", "expected"), + [("0", 0), ("5", 5), ("6", 0), ("-1", 0), ("junk", 0), (" 2 ", 2)], +) +def test_qmm_nax_variant_env_is_validated(monkeypatch, raw, expected): + monkeypatch.setenv("OMLX_QWEN35_QMM_NAX_VARIANT", raw) + monkeypatch.setattr(fast, "_qmm_nax_variant_warned", False) + assert fast._resolve_qmm_nax_variant() == expected + + +def _nax_qmm_ready() -> bool: + return ( + fast.is_native_available() + and fast.is_nax_available() + and fast.nax_qmm_kernels_built() + and fast._qmm_use_nax() + ) + + +@pytest.mark.skipif(not _nax_qmm_ready(), reason="bundled NAX qmm kernels unavailable") +@pytest.mark.parametrize("bits", [4, 8]) +@pytest.mark.parametrize("group_size", [64, 128]) +@pytest.mark.parametrize("variant", list(fast.NAX_QMM_VARIANTS)) +def test_every_bundled_nax_qmm_tile_matches_stock( + monkeypatch, bits, group_size, variant +): + """Each opt-in tile must reproduce stock MLX (the dropped wn=4 tile did not).""" + import mlx.core as mx + + n, k, t = 640, 512, 320 + keys = mx.random.split(mx.random.key(bits * 100 + variant), 2) + w = (mx.random.normal((n, k), key=keys[0]) * 0.05).astype(mx.bfloat16) + wq, scales, biases = mx.quantize(w, group_size=group_size, bits=bits) + x = mx.random.normal((1, t, k), key=keys[1]).astype(mx.bfloat16) + ref = mx.quantized_matmul( + x, wq, scales, biases, transpose=True, group_size=group_size, bits=bits + ) + monkeypatch.setattr(fast, "QMM_NAX_VARIANT", variant) + native = getattr(fast, f"qwen35_q{bits}_affine_qmm_t") + out = native(x, wq, scales, biases, 8, group_size) + ref32 = ref.astype(mx.float32) + err = mx.abs(out.astype(mx.float32) - ref32).max().item() + scale = mx.abs(ref32).max().item() + # Reduction order costs at most a bf16 ulp or two; the dropped wn=4 tile + # was off by whole units (err ~ scale). + assert err <= 0.02 * scale, ( + f"variant {variant} q{bits}/gs{group_size}: max err {err} (scale {scale})" + ) From 5f62b09f73301b8ba6583f304442c0643e16a6ac Mon Sep 17 00:00:00 2001 From: jundot Date: Tue, 8 Sep 2026 11:36:35 +0900 Subject: [PATCH 112/132] chore: remove standalone NAX tile benchmark --- benchmarks/bench_qwen35_nax_qmm_variants.py | 122 -------------------- omlx/custom_kernels/qwen35_prefill/fast.py | 1 - 2 files changed, 123 deletions(-) delete mode 100644 benchmarks/bench_qwen35_nax_qmm_variants.py diff --git a/benchmarks/bench_qwen35_nax_qmm_variants.py b/benchmarks/bench_qwen35_nax_qmm_variants.py deleted file mode 100644 index 25a40d5ff9..0000000000 --- a/benchmarks/bench_qwen35_nax_qmm_variants.py +++ /dev/null @@ -1,122 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Stock vs oMLX NAX qmm tiles for Qwen hybrid-layer projections on M5. - -The Qwen q4/q8 prefill-linear patch routes affine `QuantizedLinear` prefill -matmuls through the bundled `qwen35_q{bits}_affine_qmm_t` op, which on M5 -selects a NAX tile chosen by `OMLX_QWEN35_QMM_NAX_VARIANT` (0 = the tile -stock MLX ships). This benchmark times stock `mx.quantized_matmul` against -each bundled NAX tile variant (``fast.NAX_QMM_VARIANTS``) at the projection shapes of a Qwen4-Exp GDN / -attention layer, so the variant default and the q8 min-token threshold -(`OMLX_QWEN35_Q8_LINEAR_MIN_TOKENS`, 16384) can be set from numbers. - - python benchmarks/bench_qwen35_nax_qmm_variants.py --bits 8 --tokens 2048 8192 -""" - -from __future__ import annotations - -import argparse -import time - -import mlx.core as mx - -from omlx.custom_kernels.qwen35_prefill import fast - -# (name, N, K) — Qwen4-Exp hidden 2560, GDN 48v/16k heads x 128, attn 24q/2kv x 256 -SHAPES = [ - ("gdn.in_proj_qkv", 10240, 2560), - ("gdn.in_proj_z", 6144, 2560), - ("gdn.out_proj", 2560, 6144), - ("attn.q_proj", 12288, 2560), - ("attn.o_proj", 2560, 6144), -] - - -def _time(fn, iters): - for _ in range(2): - mx.eval(fn()) - mx.synchronize() - t0 = time.perf_counter() - for _ in range(iters): - mx.eval(fn()) - mx.synchronize() - return (time.perf_counter() - t0) / iters * 1e3 - - -def main(): - ap = argparse.ArgumentParser() - ap.add_argument("--bits", type=int, default=8) - ap.add_argument("--group-size", type=int, default=64) - ap.add_argument("--tokens", type=int, nargs="+", default=[2048, 4096, 8192, 16384]) - ap.add_argument( - "--variants", type=int, nargs="+", default=list(fast.NAX_QMM_VARIANTS) - ) - ap.add_argument("--iters", type=int, default=10) - ap.add_argument("--shapes", nargs="+", default=[s[0] for s in SHAPES]) - args = ap.parse_args() - - if not fast.is_native_available(): - raise SystemExit(f"native extension unavailable: {fast.import_error()}") - native = getattr(fast, f"qwen35_q{args.bits}_affine_qmm_t") - print( - f"mlx {mx.__version__} {mx.device_info().get('device_name')} " - f"nax={fast.is_nax_available()} native_nax_qmm={fast._qmm_use_nax()} " - f"q{args.bits}/gs{args.group_size}" - ) - print( - f"{'shape':>16} {'N':>6} {'K':>5} {'T':>6} {'mode':>10} {'ms':>8} {'GFLOP/s':>9} {'maxerr':>8}" - ) - for name, n, k in SHAPES: - if name not in args.shapes: - continue - w = (mx.random.normal((n, k), key=mx.random.key(n * k)) * 0.02).astype( - mx.bfloat16 - ) - wq, sc, bi = mx.quantize(w, group_size=args.group_size, bits=args.bits) - mx.eval(wq, sc, bi) - for t in args.tokens: - x = mx.random.normal((1, t, k), key=mx.random.key(t)).astype(mx.bfloat16) - mx.eval(x) - flop = 2.0 * t * n * k - - def stock(x=x, wq=wq, sc=sc, bi=bi): - return mx.quantized_matmul( - x, - wq, - sc, - bi, - transpose=True, - group_size=args.group_size, - bits=args.bits, - ) - - ref = stock() - mx.eval(ref) - ms = _time(stock, args.iters) - print( - f"{name:>16} {n:>6} {k:>5} {t:>6} {'stock':>10} {ms:>8.2f} {flop / ms / 1e6:>9.0f} {'-':>8}" - ) - for v in args.variants: - fast.QMM_NAX_VARIANT = v - - def mine(x=x, wq=wq, sc=sc, bi=bi): - return native(x, wq, sc, bi, 8, args.group_size) - - try: - out = mine() - mx.eval(out) - except Exception as exc: # noqa: BLE001 - print( - f"{name:>16} {n:>6} {k:>5} {t:>6} {'nax v' + str(v):>10} {'error':>8} {exc}" - ) - continue - err = ( - mx.abs(out.astype(mx.float32) - ref.astype(mx.float32)).max().item() - ) - ms = _time(mine, args.iters) - print( - f"{name:>16} {n:>6} {k:>5} {t:>6} {'nax v' + str(v):>10} {ms:>8.2f} {flop / ms / 1e6:>9.0f} {err:>8.3g}" - ) - - -if __name__ == "__main__": - main() diff --git a/omlx/custom_kernels/qwen35_prefill/fast.py b/omlx/custom_kernels/qwen35_prefill/fast.py index ef06fe4e08..f0b7c80ebf 100644 --- a/omlx/custom_kernels/qwen35_prefill/fast.py +++ b/omlx/custom_kernels/qwen35_prefill/fast.py @@ -827,7 +827,6 @@ def qmm_supports_group_size(group_size: int) -> bool: # Bundled NAX tiles (must match qwen_q_affine_nax_variant in qwen35_prefill.cpp): # 0: 64x64x64 wm2 wn2 (stock MLX tile, default) 1: bm 32 2: bm 128 # 3: bn 128 4: bk 32 5: wm4 wn1 -# benchmarks/bench_qwen35_nax_qmm_variants.py compares them against stock. NAX_QMM_VARIANTS = range(6) _qmm_nax_variant_warned = False From be581eba1f914c011f578881b23eb0af395194f6 Mon Sep 17 00:00:00 2001 From: Anton Bobrik Date: Tue, 8 Sep 2026 06:54:27 +0400 Subject: [PATCH 113/132] perf(qwen4_exp): host-side decode optimizations for Qwen3.8-Flash-Next (#3469) * test: pin MLX_ENABLE_TF32=0 under pytest so fp32 parity tests hold on M5 MLX 0.32.2 runs fp32 GPU matmuls through the M5 tensor unit at TF32 precision by default (128x128 fp32 GPU-vs-CPU max abs error 3.5e-2 with TF32, 1.9e-5 without). Four existing gathered-vs-dense QSA parity tests assert 2e-5 in fp32 and fail on an untouched tree on M5 hardware. tests/conftest.py now pins it off for the test session only; production servers still run with TF32 enabled. * perf(qwen4): route Qwen4ExpRMSNorm through mx.fast.rms_norm Qwen4ExpRMSNorm spelled RMS norm out in MLX ops -- fp32 upcast, optional grouping, y * rsqrt(mean(y^2) + eps) * (1 + w) -- where mx.fast.rms_norm exists. The class is built at 11 sites: the two hyper-connection norms per layer, the attention query/key layernorms, the indexer norms and the PLE layer, so the hand-rolled chain ran a few hundred times per forward. rms_norm takes a 1-D weight, so the grouped case (hc_norm: 10240 in four groups of 2560) cannot hand it the per-group scale; it normalises over the group axis and applies the scale after. The scale stays fp32 either way -- rounding (1 + w) to bf16 costs the full half-ULP bound, ~3.9e-3 relative. Not bitwise: the kernel sums the squares in a different order than mx.mean, so a value occasionally lands on the far side of a bf16 rounding boundary. Measured over 3.1M elements per weight magnitude: 1-8 ppm of elements move, never more than one bf16 ULP, and the rate does not track weight scale. For comparison, running the same row through a 1-row versus a 4-row forward already moves 2.4% of elements by up to 64 ULP, so this sits far below variation the model exhibits between one request and the next -- a bar the new tests assert directly rather than assume. * perf(qwen4): dispatch each decoder layer to the GPU as it is built With one async_eval after the whole forward, the GPU sits idle while Python builds the next ~8.5k-node decode graph and MLX encodes it. Calling mx.async_eval on each decoder layer's output during the layer loop (decode and verify rows only, <= 64 rows) lets the GPU execute layer i while the host builds layer i+1. Scheduling only: outputs are bit-identical, which the ABBA confirms (identical cycle counts and acceptance in every arm). Qwen3.8-Flash-Next-oQ4e-mtp on an M5 Max, interleaved ABBA: serial decode (MTP off): +18..22% tok/s (code 5k 44.6 -> 53.5) Lightning MTP depth 3: -11.5% ms/cycle (44.1 -> 39.1), 65.8 -> 75.9 tok/s at code 5k Disable with OMLX_QWEN4_EAGER_DISPATCH=0. * perf(qwen4): fused hyper-connection kernels for decode and verify rows Qwen4ExpGatedResidual._forward builds ~30 MLX nodes per call and runs 97 times per forward; under Lightning MTP the host-side kernel encoding of that graph, not its GPU time, dominates a verify cycle. Three row-batched Metal kernels replace it for batch*seq <= 16: a per-stream RMS norm (bit-identical to mx.fast.rms_norm), the down and inject projections split over four K-slices with the silu / 2*sigmoid epilogues folded in, and the up projection with the sigmoid gate, stream mix and mean. The affine unpack helpers come from hc_projection; 4/5/6/8-bit gs64 weights are supported, with separate bit widths for the down and inject projections. Results stay within a few bf16 ULP of the canonical path and at least as close to fp32; the path fails closed. Qwen3.8-Flash-Next-oQ4e-mtp on an M5 Max, interleaved pinned-depth ABBA on top of eager dispatch: MTP depth 3 -6.5% ms/cycle (39.2 -> 36.6), 68.7 -> 75.3 tok/s mean over four prompts. Serial decode is GPU-bound after eager dispatch and does not change. Disable with OMLX_QWEN4_HC_FUSED=0. * fix(qwen4_exp): require hidden % 512 for the fused hyper-connection path The fused down projection walks each K-slice (= hidden) in blocks of 32 lanes x 2 packs x 8 values = 512 elements for 4/5-bit weights with no tail handling, but compatible() only asked for a multiple of 256. A hidden size such as 768 (4-bit) or 1280 (5-bit) passed the check and the last block read past the slice: 77 and 88 bf16 ULP off the canonical path on an M5 Max. 6/8-bit weights (block 256) and the shipped checkpoint (hidden 2560) were unaffected. Require hidden % 512 == 0 for every bit width and drop the redundant (hc_count * hidden) % 512 check. Tests: compatible() rejects 768/1280, and the parity sweep now also covers hidden 512 and 1536. * perf(qwen4_exp): handle partial final blocks in the fused hyper-connection kernels Instead of gating the fused path on hidden % 512, let it take any hidden_size that is a multiple of 64 (the quantisation group and the up kernel's grid unit): * norm kernel: PER = ceil(H / 256) with a k < H guard on the loads and the store; * down and inject loops: the main loop stops at SLICE - SLICE % BLOCK and a lane-guarded extra iteration covers the remainder. The unpack helpers read exactly VPT values and VPT * BITS / 8 weight bytes, so no lane touches memory past its slice. The inject loop's separate "safe" last block goes away: hc_qdot_safe is byte-for-byte hc_qdot in the shared header, so the loop shape is now the same as the down loop's. For the shipped geometry (hidden 2560) every tail is zero and the guards fold away: old and new kernels are bit-identical for 4/5/6/8-bit weights at 1, 4 and 16 rows. compatible() also logs once, at INFO, when a Qwen4-Exp model stays on the canonical path because of its layout, so a future checkpoint that misses the fused kernels is visible in the server log rather than just slower. Tests: parity sweep at hidden 512/768/1152/1344/1536 x 4/5/6/8-bit (tails of 64, 128, 256 and 320 elements across the three kernels), norm bit-identity at 768/1152/1344, rejection below 64, and the one-time log. * fix(qwen4_exp): do not log the exact-hybrid projection as a fused-path gap With Lightning MTP off, qwen4_exp.load_weights installs upstream's exact hybrid projection on every eligible hyper-connection (91 of 97 in the shipped checkpoint), and those modules keep their compiled single-token path. compatible() must still step aside for them, but that is a runtime choice, not a checkpoint layout, so the one-time "kernels not used for this model" line no longer fires for it. It still fires for a real combined input_inject_weight layout. * perf(qwen4_exp): run the fused hyper-connection kernels ahead of the exact hybrid projection With Lightning MTP off, qwen4_exp.load_weights flags 91 of the 97 hyper-connections in the shipped checkpoint with upstream's exact hybrid projection and compiles their single-token _forward. compatible() used to step aside for those modules, so in serial decode the fused kernels ran on 6 modules and the other 91 paid a compiled call plus its own kernels each token. Let the fused path take precedence for the rows it covers. _forward is untouched and keeps the hybrid projection for everything else. Serial decode on the M5 Max, interleaved env A/B on this branch (High Power, MTP off, 512 tokens): code 5k 55.2 -> 62.8 tok/s (+13.8%) code 41k 50.6 -> 56.8 tok/s (+12.2%) prose 5.8k 54.9 -> 62.4 tok/s (+13.6%) prose 34k 51.1 -> 57.6 tok/s (+12.8%) MTP verify is unchanged (the hybrid is never installed with MTP on). Serial outputs now match the canonical path to a few bf16 ULP, as the MTP path already did, instead of bit-exactly. --- .../mlx_vlm/models/qwen4_exp/hc_fused.py | 446 ++++++++++++++++++ .../mlx_vlm/models/qwen4_exp/language.py | 39 +- tests/conftest.py | 6 + tests/test_qwen4_eager_dispatch.py | 70 +++ tests/test_qwen4_hc_fused.py | 235 +++++++++ tests/test_qwen4_rms_norm.py | 228 +++++++++ 6 files changed, 1016 insertions(+), 8 deletions(-) create mode 100644 omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/hc_fused.py create mode 100644 tests/test_qwen4_eager_dispatch.py create mode 100644 tests/test_qwen4_hc_fused.py create mode 100644 tests/test_qwen4_rms_norm.py diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/hc_fused.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/hc_fused.py new file mode 100644 index 0000000000..8c6067d177 --- /dev/null +++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/hc_fused.py @@ -0,0 +1,446 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Fused hyper-connection kernels for Qwen4-Exp decode and verify rows. + +``Qwen4ExpGatedResidual._forward`` builds ~30 MLX nodes per call (grouped norm, +three small quantized projections, silu/sigmoid gates, stream mix and mean) and +runs 97 times per forward. On Apple Silicon the host-side kernel encoding of +that graph, not its GPU time, dominates a Lightning MTP verify cycle. Three +row-batched Metal kernels replace it for small row counts: + +* ``N`` -- per-stream RMS norm with the ``1 + weight`` scale (bit-identical to + ``mx.fast.rms_norm``). +* ``D`` -- ``input_mix_weight_down`` (320 rows) and ``block_inject_weight`` + (``hc_count`` rows) projections per token row, split over 4 K-slices, with + the ``silu(mix / hc_count)`` and ``2 * sigmoid(inject / hc_count)`` + epilogues folded in. +* ``U`` -- ``input_mix_weight_up`` per output element, sigmoid, times the + normed stream, mean over streams via simd shuffles. + +Rows live in the grid (``batch * seq <= 16``); within that limit the fused path +runs ahead of upstream's exact hybrid projection and compiled single-token path +(serial decode) as well as the canonical path (MTP verify). The affine unpack +helpers come from :mod:`hc_projection`. Any ``hidden_size`` that is a multiple of 64 is +supported: the norm, down and inject loops guard their partial final blocks +(compiled out for the shipped 2560). Results match the canonical path to a few +bf16 ULP (fp32 is kept through the epilogues); the path fails closed to +``_forward`` on any runtime error and logs once when a model's layout keeps it +on the canonical path. Disable with ``OMLX_QWEN4_HC_FUSED=0``. +""" + +from __future__ import annotations + +import logging +import os + +import mlx.core as mx +import mlx.nn as nn + +from .hc_projection import _HEADER + +logger = logging.getLogger(__name__) + +MAX_ROWS = 16 +_GROUP_SIZE = 64 +_SUPPORTED_BITS = (4, 5, 6, 8) +_DISABLED = os.environ.get("OMLX_QWEN4_HC_FUSED", "1").strip().lower() in { + "0", + "false", + "no", + "off", +} +_KERNELS: dict[str, object] = {} +_RUNTIME_FAILED = False +_FAILURE_LOGGED = False +_INELIGIBLE_LOGGED = False + +_N_SOURCE = r""" + const uint row = threadgroup_position_in_grid.z; + const uint s = threadgroup_position_in_grid.y; + const uint t = thread_index_in_threadgroup; + const uint sg = simdgroup_index_in_threadgroup; + const uint lane = thread_index_in_simdgroup; + threadgroup float part[8]; + constexpr int PER = (H + 255) / 256; + const device T* xp = x + (size_t)row * K + (size_t)s * H; + const device T* wp = w + (size_t)s * H; + device T* op = xn + (size_t)row * K + (size_t)s * H; + float v[PER]; + float ss = 0.0f; + for (int i = 0; i < PER; ++i) { + const int k = t + i * 256; + v[i] = (k < H) ? float(xp[k]) : 0.0f; + ss += v[i] * v[i]; + } + ss = simd_sum(ss); + if (lane == 0) part[sg] = ss; + threadgroup_barrier(mem_flags::mem_threadgroup); + float tot = 0.0f; + for (int i = 0; i < 8; ++i) tot += part[i]; + const float inv = metal::rsqrt(tot / float(H) + eps[0]); + for (int i = 0; i < PER; ++i) { + const int k = t + i * 256; + if (k < H) op[k] = T(v[i] * inv * (1.0f + float(wp[k]))); + } +""" + +_D_SOURCE = r""" + const uint tg = threadgroup_position_in_grid.y; + const uint row = threadgroup_position_in_grid.z; + const uint sg = simdgroup_index_in_threadgroup; + const uint lane = thread_index_in_simdgroup; + constexpr int KS = 4; + constexpr int SLICE = K / KS; + constexpr int GROUPS = K / 64; + threadgroup float part[KS][8]; + const device T* x = xn + (size_t)row * K; + const int rg = int(sg & 1); + const int ks = int(sg >> 1); + if (tg < R / 8) { + constexpr int PF = hc_pack_factor(); + constexpr int BP = hc_bytes_per_pack(); + constexpr int ROW_BYTES = K * BP / PF; + constexpr int PPT = 2; + constexpr int VPT = PF * PPT; + constexpr int BLOCK = VPT * 32; + constexpr int SCALE_STEP = 64 / VPT; + const int out_row = int(tg) * 8 + rg * 4; + const device uint8_t* wp = (const device uint8_t*)down_w + + out_row * ROW_BYTES + ks * (SLICE * BP / PF) + int(lane) * PPT * BP; + const device T* sp = down_s + out_row * GROUPS + ks * (SLICE / 64) + + int(lane) / SCALE_STEP; + const device T* bp = down_b + out_row * GROUPS + ks * (SLICE / 64) + + int(lane) / SCALE_STEP; + const device T* xp = x + ks * SLICE + int(lane) * VPT; + float result[4] = {0.0f}; + float xv[VPT]; + constexpr int TAIL = SLICE % BLOCK; + for (int k = 0; k < SLICE - TAIL; k += BLOCK) { + float sum = hc_load_vector(xp, xv); + for (int r = 0; r < 4; ++r) { + result[r] += hc_qdot( + wp + r * ROW_BYTES, xv, + float(sp[r * GROUPS]), float(bp[r * GROUPS]), sum); + } + wp += BLOCK * BP / PF; + sp += BLOCK / 64; + bp += BLOCK / 64; + xp += BLOCK; + } + // Partial final block: only lanes whose VPT elements lie inside the slice take part. + // The helpers read exactly VPT values and VPT * BITS / 8 weight bytes, so nothing is + // touched past the slice; every lane still joins the simd_sum below. + if (TAIL > 0 && int(lane) * VPT < TAIL) { + float sum = hc_load_vector(xp, xv); + for (int r = 0; r < 4; ++r) { + result[r] += hc_qdot( + wp + r * ROW_BYTES, xv, + float(sp[r * GROUPS]), float(bp[r * GROUPS]), sum); + } + } + for (int r = 0; r < 4; ++r) { + float v = simd_sum(result[r]); + if (lane == 0) part[ks][rg * 4 + r] = v; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg < 2 && lane < 4) { + const int r = int(lane); + float v = part[0][sg * 4 + r] + part[1][sg * 4 + r] + + part[2][sg * 4 + r] + part[3][sg * 4 + r]; + v = v / float(HC); + act[(size_t)row * R + int(tg) * 8 + int(sg) * 4 + r] + = T(v / (1.0f + metal::exp(-v))); + } + return; + } + if (INJ == 0 || rg != 0) return; + { + constexpr int PF = hc_pack_factor(); + constexpr int BP = hc_bytes_per_pack(); + constexpr int ROW_BYTES = K * BP / PF; + constexpr int PPT = 1; + constexpr int VPT = PF; + constexpr int BLOCK = VPT * 32; + constexpr int SCALE_STEP = 64 / VPT; + const device uint8_t* wp = (const device uint8_t*)inject_w + + ks * (SLICE * BP / PF) + int(lane) * BP; + const device T* sp = inject_s + ks * (SLICE / 64) + int(lane) / SCALE_STEP; + const device T* bp = inject_b + ks * (SLICE / 64) + int(lane) / SCALE_STEP; + const device T* xp = x + ks * SLICE + int(lane) * VPT; + float result[HC] = {0.0f}; + float xv[VPT]; + constexpr int TAIL = SLICE % BLOCK; + for (int k = 0; k < SLICE - TAIL; k += BLOCK) { + float sum = hc_load_vector(xp, xv); + for (int r = 0; r < HC; ++r) { + result[r] += hc_qdot( + wp + r * ROW_BYTES, xv, + float(sp[r * GROUPS]), float(bp[r * GROUPS]), sum); + } + wp += BLOCK * BP / PF; + sp += BLOCK / 64; + bp += BLOCK / 64; + xp += BLOCK; + } + if (TAIL > 0 && int(lane) * VPT < TAIL) { + float sum = hc_load_vector(xp, xv); + for (int r = 0; r < HC; ++r) { + result[r] += hc_qdot( + wp + r * ROW_BYTES, xv, + float(sp[r * GROUPS]), float(bp[r * GROUPS]), sum); + } + } + for (int r = 0; r < HC; ++r) { + float v = simd_sum(result[r]); + if (lane == 0) part[ks][r] = v; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg == 0 && lane < HC) { + const int r = int(lane); + float v = part[0][r] + part[1][r] + part[2][r] + part[3][r]; + v = v / float(HC); + inj[(size_t)row * HC + r] = T(2.0f / (1.0f + metal::exp(-v))); + } + } +""" + +_U_SOURCE = r""" + const uint g = threadgroup_position_in_grid.y; + const uint t = thread_index_in_threadgroup; + const int h = int(g) * 64 + int(t >> 2); + const int s = int(t & 3); + const int n = s * H + h; + constexpr int PF = hc_pack_factor(); + constexpr int BP = hc_bytes_per_pack(); + constexpr int ROW_BYTES = R * BP / PF; + constexpr int GROUPS_R = R / 64; + constexpr int CH = 2 * PF; + constexpr int CPG = 64 / CH; + const device uint8_t* w = (const device uint8_t*)up_w + (size_t)n * ROW_BYTES; + const device T* sp = up_s + (size_t)n * GROUPS_R; + const device T* bp = up_b + (size_t)n * GROUPS_R; + float xv[CH]; + for (int r = 0; r < S; ++r) { + const device T* a = act + (size_t)r * R; + float acc = 0.0f; + for (int gq = 0; gq < GROUPS_R; ++gq) { + const float sc = float(sp[gq]); + const float bi = float(bp[gq]); + for (int c = 0; c < CPG; ++c) { + const int e = gq * 64 + c * CH; + float sum = hc_load_vector(a + e, xv); + acc += hc_qdot(w + e * BP / PF, xv, sc, bi, sum); + } + } + float gate = 1.0f / (1.0f + metal::exp(-acc)); + float v = gate * float(xn[(size_t)r * K + n]); + v += simd_shuffle_down(v, 1); + v += simd_shuffle_down(v, 2); + if (s == 0) mixed[(size_t)r * H + h] = T(v / float(HC)); + } +""" + + +def _kernel(name: str, input_names: list[str], output_names: list[str], source: str, header: str = ""): + kernel = _KERNELS.get(name) + if kernel is None: + kernel = mx.fast.metal_kernel( + name=name, + input_names=input_names, + output_names=output_names, + header=header, + source=source, + ensure_row_contiguous=True, + ) + _KERNELS[name] = kernel + return kernel + + +def enabled() -> bool: + return not _DISABLED and not _RUNTIME_FAILED + + +def _quantized_ok(projection) -> bool: + return ( + type(projection) is nn.QuantizedLinear + and getattr(projection, "group_size", None) == _GROUP_SIZE + and getattr(projection, "bits", None) in _SUPPORTED_BITS + and getattr(projection, "mode", "affine") == "affine" + and "bias" not in projection + and isinstance(getattr(projection, "weight", None), mx.array) + and projection.weight.dtype == mx.uint32 + and isinstance(getattr(projection, "scales", None), mx.array) + and isinstance(getattr(projection, "biases", None), mx.array) + and projection.scales.dtype == mx.bfloat16 + and projection.biases.dtype == mx.bfloat16 + ) + + +def _ineligible(reason: str) -> bool: + """Record (once per process) why a model stays on the canonical path, so a future + checkpoint that misses the fused kernels shows up in the log instead of just running slower.""" + global _INELIGIBLE_LOGGED + if not _INELIGIBLE_LOGGED: + _INELIGIBLE_LOGGED = True + logger.info( + "Qwen4 fused hyper-connection kernels not used for this model (%s); " + "the canonical path stays in effect", + reason, + ) + return False + + +def compatible(module, hyper_input) -> bool: + """Whether ``module`` (a Qwen4ExpGatedResidual) can take the fused path for ``hyper_input``.""" + if not enabled(): + return False + if not ( + isinstance(hyper_input, mx.array) + and hyper_input.ndim == 3 + and hyper_input.dtype == mx.bfloat16 + and 1 <= hyper_input.shape[0] * hyper_input.shape[1] <= MAX_ROWS + ): + return False + # With Lightning MTP off, load_weights installs upstream's exact hybrid projection + # (``_omlx_exact_hybrid_projection``) and compiles ``_forward`` for single-token + # decode. The fused path deliberately takes precedence over both: three kernels + # per module against a compiled call plus its own kernels measured +12..14% + # serial tok/s on the M5 Max. ``_forward`` keeps the hybrid for the rows this + # path does not take. + if hasattr(module, "input_inject_weight"): + return _ineligible("combined input projection layout") + hc_count = getattr(module, "hc_count", None) + hidden = getattr(module, "hidden_size", None) + lowrank = getattr(module, "hc_lowrank", None) + if not ( + isinstance(hc_count, int) + and isinstance(hidden, int) + and isinstance(lowrank, int) + and hc_count == 4 + # Every kernel walks the hidden axis in 64-element quantisation groups (the up + # kernel's grid is hidden // 64); the norm, down and inject loops guard their + # partial final blocks, so any multiple of 64 is fine. + and hidden % 64 == 0 + and lowrank % 64 == 0 + and lowrank % 8 == 0 + and hyper_input.shape[2] == hc_count * hidden + ): + return _ineligible( + f"geometry hidden_size={hidden} hc_lowrank={lowrank} hc_count={hc_count}" + ) + norm = getattr(module, "hc_norm", None) + if not ( + norm is not None + and getattr(norm, "group_size", None) == hidden + and isinstance(getattr(norm, "weight", None), mx.array) + and norm.weight.dtype == mx.bfloat16 + and norm.weight.shape == (hc_count * hidden,) + ): + return _ineligible("hc_norm layout") + if not ( + _quantized_ok(getattr(module, "input_mix_weight_down", None)) + and _quantized_ok(getattr(module, "input_mix_weight_up", None)) + ): + return _ineligible( + "projection quantisation (need affine group-size-64 4/5/6/8-bit with bf16 scales)" + ) + if "block_inject_weight" in module and not _quantized_ok(module.block_inject_weight): + return _ineligible("block_inject_weight quantisation") + return mx.default_device() == mx.gpu and mx.metal.is_available() + + +def _eps_array(module) -> mx.array: + eps = getattr(module, "_omlx_hc_fused_eps", None) + if eps is None: + eps = mx.array([float(module.hc_norm.eps)], dtype=mx.float32) + mx.eval(eps) + module._omlx_hc_fused_eps = eps + return eps + + +def fused_forward(module, hyper_input): + """Fused equivalent of ``Qwen4ExpGatedResidual._forward``; ``None`` on runtime failure.""" + global _RUNTIME_FAILED, _FAILURE_LOGGED + try: + hc, hidden, lowrank = module.hc_count, module.hidden_size, module.hc_lowrank + width = hc * hidden + batch, seq, _ = hyper_input.shape + rows = batch * seq + down, up = module.input_mix_weight_down, module.input_mix_weight_up + inject = module.block_inject_weight if "block_inject_weight" in module else None + flat = hyper_input.reshape(rows, width) + dtype = hyper_input.dtype + normed = _kernel( + "omlx_qwen4_hc_fused_norm", ["x", "w", "eps"], ["xn"], _N_SOURCE + )( + inputs=[flat, module.hc_norm.weight, _eps_array(module)], + template=[("T", dtype), ("K", width), ("H", hidden)], + grid=(256, hc, rows), + threadgroup=(256, 1, 1), + output_shapes=[(rows, width)], + output_dtypes=[dtype], + )[0] + if inject is not None: + inject_tensors = (inject.weight, inject.scales, inject.biases) + else: + inject_tensors = (down.weight, down.scales, down.biases) + act, injection = _kernel( + "omlx_qwen4_hc_fused_down", + ["xn", "down_w", "down_s", "down_b", "inject_w", "inject_s", "inject_b"], + ["act", "inj"], + _D_SOURCE, + header=_HEADER, + )( + inputs=[normed, down.weight, down.scales, down.biases, *inject_tensors], + template=[ + ("T", dtype), + ("BITS_D", down.bits), + ("BITS_I", inject.bits if inject is not None else down.bits), + ("K", width), + ("R", lowrank), + ("HC", hc), + ("INJ", 1 if inject is not None else 0), + ], + grid=(32, 8 * (lowrank // 8 + 1), rows), + threadgroup=(32, 8, 1), + output_shapes=[(rows, lowrank), (rows, hc)], + output_dtypes=[dtype, dtype], + ) + mixed = _kernel( + "omlx_qwen4_hc_fused_up", + ["xn", "act", "up_w", "up_s", "up_b"], + ["mixed"], + _U_SOURCE, + header=_HEADER, + )( + inputs=[normed, act, up.weight, up.scales, up.biases], + template=[ + ("T", dtype), + ("BITS_U", up.bits), + ("K", width), + ("R", lowrank), + ("HC", hc), + ("H", hidden), + ("S", rows), + ], + grid=(256, hidden // 64, 1), + threadgroup=(256, 1, 1), + output_shapes=[(rows, hidden)], + output_dtypes=[dtype], + )[0] + mixed = mixed.reshape(batch, seq, hidden) + if inject is None: + return mixed + return mixed, hyper_input, injection.reshape(batch, seq, hc) + except Exception as exc: # noqa: BLE001 - optional native path + _RUNTIME_FAILED = True + if not _FAILURE_LOGGED: + _FAILURE_LOGGED = True + logger.warning( + "Qwen4 fused hyper-connection kernels failed closed; using the " + "canonical path: %s", + exc, + ) + return None + + +__all__ = ["MAX_ROWS", "compatible", "enabled", "fused_forward"] 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 60e3d24289..6f450fced3 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 @@ -32,6 +32,7 @@ contiguous_causal_gathered_qsa_decode, pool_completed_index_keys, ) +from . import hc_fused _PLE_RUNTIME_MODEL_PATH: Path | None = None _PLE_RUNTIME_MODE = "resident" @@ -1009,6 +1010,18 @@ def nbytes(self): return size + self.indexer_nbytes +# Dispatch each decoder layer's graph to the GPU as soon as it is built (decode and +# verify rows only) so the GPU executes layer i while the host builds layer i+1. +# Scheduling only: outputs are bit-identical. Disable with OMLX_QWEN4_EAGER_DISPATCH=0. +_EAGER_DISPATCH = os.environ.get("OMLX_QWEN4_EAGER_DISPATCH", "1").strip().lower() not in { + "0", + "false", + "no", + "off", +} +_EAGER_DISPATCH_MAX_ROWS = 64 + + class Qwen4ExpRMSNorm(nn.Module): """Qwen4 RMSNorm, whose checkpoint weights are centered at zero.""" @@ -1022,14 +1035,14 @@ def __init__(self, dim: int, group_size: int | None = None, eps: float = 1e-6): def __call__(self, x: mx.array) -> mx.array: dtype = x.dtype - y = x.astype(mx.float32) - if self.group_size is not None: - y = y.reshape(*y.shape[:-1], -1, self.group_size) - weight = self.weight.reshape(-1, self.group_size) - else: - weight = self.weight - y = y * mx.rsqrt(mx.mean(mx.square(y), axis=-1, keepdims=True) + self.eps) - y = y * (1.0 + weight.astype(mx.float32)) + scale = 1.0 + self.weight.astype(mx.float32) + if self.group_size is None: + return mx.fast.rms_norm(x, scale, self.eps).astype(dtype) + # rms_norm takes a 1-D weight, so a grouped norm cannot hand it the + # per-group scale; normalise over the group axis and scale afterwards. + # The scale stays fp32 -- rounding (1 + w) to bf16 costs half a ULP. + y = x.astype(mx.float32).reshape(*x.shape[:-1], -1, self.group_size) + y = mx.fast.rms_norm(y, None, self.eps) * scale.reshape(-1, self.group_size) return y.reshape(x.shape).astype(dtype) @@ -1571,6 +1584,10 @@ def __init__(self, config: TextConfig, use_combine: bool = True): ) def __call__(self, hyper_input: mx.array, target_verify: bool = False): + if hc_fused.compatible(self, hyper_input): + fused = hc_fused.fused_forward(self, hyper_input) + if fused is not None: + return fused compiled_forward = getattr(self, "_compiled_forward", None) if ( compiled_forward is not None @@ -2585,6 +2602,12 @@ def __call__( gdn_sink=gdn_sink, target_verify=gdn_sink is not None, ) + if ( + _EAGER_DISPATCH + and hidden_states.shape[0] * hidden_states.shape[1] + <= _EAGER_DISPATCH_MAX_ROWS + ): + mx.async_eval(hidden_states) if hidden_sink is not None and index in capture: hidden_sink.append( self.hyper_connection_mixer( diff --git a/tests/conftest.py b/tests/conftest.py index 377acb82dc..1e5f29b309 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,3 +1,9 @@ +import os + +# MLX 0.32.2 runs fp32 GPU matmuls at TF32 precision on M5-class tensor units; +# the fp32 parity tests assert 2e-5, which TF32 cannot hold. Test session only. +os.environ.setdefault("MLX_ENABLE_TF32", "0") + # SPDX-License-Identifier: Apache-2.0 """ Pytest configuration and fixtures for oMLX tests. diff --git a/tests/test_qwen4_eager_dispatch.py b/tests/test_qwen4_eager_dispatch.py new file mode 100644 index 0000000000..be0ac335dc --- /dev/null +++ b/tests/test_qwen4_eager_dispatch.py @@ -0,0 +1,70 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Per-layer eager dispatch in Qwen4ExpModel: fires for decode/verify rows only and never changes outputs.""" +from __future__ import annotations + +import sys + +import mlx.core as mx +import pytest + +from omlx.patches import mlx_vlm_qwen4_exp_compat as compat + + +@pytest.fixture(autouse=True) +def _vendored_qwen4(): + compat.apply_mlx_vlm_qwen4_exp_compat_patch() +from tests.test_mlx_vlm_qwen4_exp_compat import _tiny_config + + +def _model(): + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp.language import LanguageModel + + config = _tiny_config() + mx.random.seed(1) + model = LanguageModel(config.text_config, config) + mx.eval(model.parameters()) + return model, config + + +def _count_dispatches(monkeypatch, language, rows: int): + calls = [] + real = mx.async_eval + + def spy(*a, **k): + # Count only the decoder-layer loop's dispatches; mlx-lm's gated-delta kernel also async_evals. + if sys._getframe(1).f_code.co_filename == language.__file__: + calls.append(len(a)) + return real(*a, **k) + + monkeypatch.setattr(language.mx, "async_eval", spy) + model, config = _model() + inputs = mx.random.randint(0, config.text_config.vocab_size, (1, rows)) + out = model(inputs) + out = getattr(out, "logits", out) + mx.eval(out) + return len(calls), out + + +@pytest.mark.parametrize("rows,expected", [(1, True), (4, True), (64, True), (65, False), (200, False)]) +def test_dispatches_once_per_layer_for_small_row_counts(monkeypatch, rows, expected): + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp import language + + monkeypatch.setattr(language, "_EAGER_DISPATCH", True) + count, _ = _count_dispatches(monkeypatch, language, rows) + layers = _tiny_config().text_config.num_hidden_layers + assert count == (layers if expected else 0) + + +def test_kill_switch_and_bitwise_equality(monkeypatch): + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp import language + + monkeypatch.setattr(language, "_EAGER_DISPATCH", False) + off_count, off = _count_dispatches(monkeypatch, language, 4) + monkeypatch.setattr(language, "_EAGER_DISPATCH", True) + on_count, on = _count_dispatches(monkeypatch, language, 4) + assert off_count == 0 and on_count > 0 + assert mx.array_equal(on.view(mx.uint32) if on.dtype == mx.float32 else on.view(mx.uint16), + off.view(mx.uint32) if off.dtype == mx.float32 else off.view(mx.uint16)).item() diff --git a/tests/test_qwen4_hc_fused.py b/tests/test_qwen4_hc_fused.py new file mode 100644 index 0000000000..54a6250af2 --- /dev/null +++ b/tests/test_qwen4_hc_fused.py @@ -0,0 +1,235 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Fused hyper-connection kernels: parity with the canonical path, eligibility, kill switch.""" +from __future__ import annotations + +import importlib + +import mlx.core as mx +import mlx.nn as nn +import pytest + +from omlx.patches import mlx_vlm_qwen4_exp_compat as compat + + +@pytest.fixture(autouse=True) +def _vendored_qwen4(): + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + +HC, HIDDEN, LOWRANK = 4, 2560, 320 +WIDTH = HC * HIDDEN + + +def _module(bits: int, use_combine: bool = True, hidden: int = HIDDEN): + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp.language import Qwen4ExpGatedResidual, Qwen4ExpRMSNorm + + width = HC * hidden + module = Qwen4ExpGatedResidual.__new__(Qwen4ExpGatedResidual) + nn.Module.__init__(module) + module.hc_count, module.hidden_size, module.hc_lowrank = HC, hidden, LOWRANK + module.hc_norm = Qwen4ExpRMSNorm(width, group_size=hidden, eps=1e-6) + module.hc_norm.weight = (mx.random.normal((width,)) * 0.05).astype(mx.bfloat16) + module.input_mix_weight_down = nn.QuantizedLinear(width, LOWRANK, bias=False, group_size=64, bits=bits) + module.input_mix_weight_up = nn.QuantizedLinear(LOWRANK, width, bias=False, group_size=64, bits=bits) + if use_combine: + module.block_inject_weight = nn.QuantizedLinear(width, HC, bias=False, group_size=64, bits=bits) + for name in ("input_mix_weight_down", "input_mix_weight_up", "block_inject_weight"): + projection = getattr(module, name, None) + if projection is not None: + # Checkpoint-like statistics: positive scales, small biases. Random-sign scales drive the + # up-projection gate into saturation where any rounding difference flips whole elements. + projection.scales = (mx.abs(mx.random.normal(projection.scales.shape)) * 0.01 + 0.002).astype(mx.bfloat16) + projection.biases = (mx.random.normal(projection.biases.shape) * 0.005).astype(mx.bfloat16) + mx.eval(module.parameters()) + return module + + +def _reference_fp32(module, x): + def dequant(q): + return mx.dequantize(q.weight, q.scales, q.biases, group_size=q.group_size, bits=q.bits).astype(mx.float32) + + normed = module.hc_norm(x).astype(mx.float32) + mix = nn.silu((normed @ dequant(module.input_mix_weight_down).T) / HC) + gate = mx.sigmoid(mix @ dequant(module.input_mix_weight_up).T) + hidden = module.hidden_size + mixed = mx.mean(gate.reshape(*gate.shape[:-1], HC, hidden) * normed.reshape(*normed.shape[:-1], HC, hidden), axis=-2) + if "block_inject_weight" not in module: + return mixed, None + return mixed, 2 * mx.sigmoid((normed @ dequant(module.block_inject_weight).T) / HC) + + +def _ulps(a, b): + a = a.astype(mx.float32) + b = b.astype(mx.float32) + ulp = float(mx.abs(b).max().item()) * 2.0**-7 + diff = mx.abs(a - b) / ulp + return float(diff.max().item()), float(diff.mean().item()) + + +@pytest.mark.skipif(not mx.metal.is_available(), reason="requires Metal") +@pytest.mark.parametrize("bits", [4, 5, 6, 8]) +@pytest.mark.parametrize("rows", [1, 4, 16]) +@pytest.mark.parametrize("use_combine", [True, False]) +def test_fused_matches_canonical_path(bits, rows, use_combine): + mx.random.seed(20260905 + bits * 100 + rows) + _assert_fused_matches_canonical(_module(bits, use_combine), rows, use_combine) + + +# Sizes the checkpoint never has, chosen so every kernel sees a partial final block: +# 768 -> down tail 256 for 4/5-bit; norm and inject loops exact +# 1152 -> down tail 128 (all bits), inject tail 128 (4/5-bit), norm tail 128 +# 1344 -> down tail 320 (4/5) / 64 (6/8), inject tail 64, norm tail 64 +# 512, 1536 -> odd multiples of 512, no tails anywhere +@pytest.mark.skipif(not mx.metal.is_available(), reason="requires Metal") +@pytest.mark.parametrize("bits", [4, 5, 6, 8]) +@pytest.mark.parametrize("hidden", [512, 768, 1152, 1344, 1536]) +def test_fused_matches_canonical_path_at_other_hidden_sizes(hidden, bits): + mx.random.seed(20260906 + hidden + bits) + _assert_fused_matches_canonical(_module(bits, True, hidden=hidden), 16, True) + + +def _assert_fused_matches_canonical(module, rows, use_combine): + from mlx_vlm.models.qwen4_exp import hc_fused + + hidden = module.hidden_size + x = mx.random.normal((1, rows, HC * hidden)).astype(mx.bfloat16) + mx.eval(x) + assert hc_fused.compatible(module, x) + fused = hc_fused.fused_forward(module, x) + assert fused is not None + canonical = module._forward(x) + mx.eval(fused, canonical) + ref_mixed, ref_inject = _reference_fp32(module, x) + if use_combine: + fused_mixed, passthrough, fused_inject = fused + canon_mixed, _, canon_inject = canonical + assert passthrough is x + assert fused_inject.shape == canon_inject.shape == (1, rows, HC) + assert _ulps(fused_inject, canon_inject)[0] <= 4 + assert _ulps(fused_inject, ref_inject)[0] <= 4 + else: + fused_mixed, canon_mixed = fused, canonical + assert fused_mixed.shape == canon_mixed.shape == (1, rows, hidden) + assert fused_mixed.dtype == mx.bfloat16 + max_vs_canon, mean_vs_canon = _ulps(fused_mixed, canon_mixed) + assert max_vs_canon <= 16 and mean_vs_canon <= 0.5 + # Both paths round differently; judge each against fp32. The fused path keeps fp32 through + # the epilogues, so it must stay at least as close to fp32 as the canonical path (with slack). + max_fused, mean_fused = _ulps(fused_mixed, ref_mixed) + max_canon, mean_canon = _ulps(canon_mixed, ref_mixed) + assert max_fused <= max(2 * max_canon, 6) + assert mean_fused <= mean_canon * 1.5 + 0.05 + + +@pytest.mark.skipif(not mx.metal.is_available(), reason="requires Metal") +@pytest.mark.parametrize("hidden", [HIDDEN, 768, 1152, 1344]) +def test_fused_norm_is_bit_identical_to_rms_norm(hidden): + from mlx_vlm.models.qwen4_exp import hc_fused + + mx.random.seed(7) + module = _module(4, hidden=hidden) + width = HC * hidden + x = (mx.random.normal((1, 4, width)) * 3).astype(mx.bfloat16) + flat = x.reshape(4, width) + normed = hc_fused._kernel("omlx_qwen4_hc_fused_norm", ["x", "w", "eps"], ["xn"], hc_fused._N_SOURCE)( + inputs=[flat, module.hc_norm.weight, hc_fused._eps_array(module)], + template=[("T", mx.bfloat16), ("K", width), ("H", hidden)], + grid=(256, HC, 4), + threadgroup=(256, 1, 1), + output_shapes=[(4, width)], + output_dtypes=[mx.bfloat16], + )[0] + expected = module.hc_norm(x).reshape(4, width) + mx.eval(normed, expected) + assert mx.array_equal(normed.view(mx.uint16), expected.view(mx.uint16)).item() + + +@pytest.mark.skipif(not mx.metal.is_available(), reason="requires Metal") +def test_gated_residual_call_routes_through_fused_path(monkeypatch): + from mlx_vlm.models.qwen4_exp import hc_fused + + module = _module(4) + x = mx.random.normal((1, 2, WIDTH)).astype(mx.bfloat16) + calls = [] + original = hc_fused.fused_forward + monkeypatch.setattr(hc_fused, "fused_forward", lambda m, h: calls.append(h.shape) or original(m, h)) + out = module(x) + mx.eval(out) + assert calls == [(1, 2, WIDTH)] + + +@pytest.mark.parametrize("hidden,bits", [(800, 4), (1056, 5)]) +def test_compatible_rejects_hidden_not_multiple_of_64(hidden, bits): + # 64 is the quantisation group and the up kernel's grid unit; nothing below it is handled. + from mlx_vlm.models.qwen4_exp import hc_fused + + module = _module(bits, True, hidden=hidden) + x = mx.random.normal((1, 4, HC * hidden)).astype(mx.bfloat16) + assert not hc_fused.compatible(module, x) + + +def test_ineligible_model_is_logged_once(monkeypatch, caplog): + from mlx_vlm.models.qwen4_exp import hc_fused + + monkeypatch.setattr(hc_fused, "_INELIGIBLE_LOGGED", False) + module = _module(4, True, hidden=800) + x = mx.random.normal((1, 4, HC * 800)).astype(mx.bfloat16) + with caplog.at_level("INFO", logger=hc_fused.logger.name): + assert not hc_fused.compatible(module, x) + assert not hc_fused.compatible(module, x) + # Prefill-sized inputs are expected to skip the fused path and must not log. + monkeypatch.setattr(hc_fused, "_INELIGIBLE_LOGGED", False) + assert not hc_fused.compatible(_module(4), mx.random.normal((1, 64, WIDTH)).astype(mx.bfloat16)) + messages = [r.getMessage() for r in caplog.records if "fused hyper-connection kernels not used" in r.getMessage()] + assert len(messages) == 1 + assert "hidden_size=800" in messages[0] + + +@pytest.mark.skipif(not mx.metal.is_available(), reason="requires Metal") +def test_fused_path_takes_precedence_over_exact_hybrid_projection(monkeypatch): + # With MTP off, load_weights flags modules with upstream's exact hybrid projection and compiles + # their single-token _forward. The fused path must still win for decode rows (+12..14% serial). + from mlx_vlm.models.qwen4_exp import hc_fused + + module = _module(4) + module._omlx_exact_hybrid_projection = True + module._compiled_forward = lambda h: pytest.fail("compiled single-token path must not run") + x = mx.random.normal((1, 1, WIDTH)).astype(mx.bfloat16) + assert hc_fused.compatible(module, x) + calls = [] + original = hc_fused.fused_forward + monkeypatch.setattr(hc_fused, "fused_forward", lambda m, h: calls.append(h.shape) or original(m, h)) + out = module(x) + mx.eval(out) + assert calls == [(1, 1, WIDTH)] + + +def test_compatible_fails_closed(): + from mlx_vlm.models.qwen4_exp import hc_fused + + module = _module(4) + ok = mx.random.normal((1, 4, WIDTH)).astype(mx.bfloat16) + if mx.metal.is_available(): + assert hc_fused.compatible(module, ok) + assert not hc_fused.compatible(module, mx.random.normal((1, 17, WIDTH)).astype(mx.bfloat16)) + assert not hc_fused.compatible(module, mx.random.normal((2, 9, WIDTH)).astype(mx.bfloat16)) + assert not hc_fused.compatible(module, mx.random.normal((1, 4, WIDTH)).astype(mx.float16)) + assert not hc_fused.compatible(module, mx.random.normal((4, WIDTH)).astype(mx.bfloat16)) + module.input_inject_weight = nn.Linear(WIDTH, LOWRANK + HC, bias=False) + assert not hc_fused.compatible(module, ok) + del module.input_inject_weight + module.input_mix_weight_down = nn.Linear(WIDTH, LOWRANK, bias=False) + assert not hc_fused.compatible(module, ok) + + +def test_kill_switch_disables_fused_path(monkeypatch): + monkeypatch.setenv("OMLX_QWEN4_HC_FUSED", "0") + from mlx_vlm.models.qwen4_exp import hc_fused + + reloaded = importlib.reload(hc_fused) + try: + assert not reloaded.enabled() + assert not reloaded.compatible(_module(4), mx.random.normal((1, 4, WIDTH)).astype(mx.bfloat16)) + finally: + monkeypatch.delenv("OMLX_QWEN4_HC_FUSED") + importlib.reload(hc_fused) diff --git a/tests/test_qwen4_rms_norm.py b/tests/test_qwen4_rms_norm.py new file mode 100644 index 0000000000..6bfd319ce2 --- /dev/null +++ b/tests/test_qwen4_rms_norm.py @@ -0,0 +1,228 @@ +# SPDX-License-Identifier: Apache-2.0 +"""``Qwen4ExpRMSNorm`` against the hand-rolled formulation it replaced. + +The module used to spell RMS norm out in MLX ops (fp32 upcast, optional +grouping, ``y * rsqrt(mean(y^2) + eps) * (1 + w)``) where ``mx.fast.rms_norm`` +exists. Routing it through the fast path is a refactor, so these are +characterization tests: ``_reference`` is the old body verbatim, and the module +must keep matching it. + +``rms_norm`` takes a 1-D weight only, so the grouped case cannot hand its +``(groups, group_size)`` weight to the kernel and applies the scale separately. +That scale must stay fp32 -- rounding ``(1 + w)`` to bf16 costs 3.9e-3 relative, +which is half a bf16 ULP of pure avoidable error. +""" + +from __future__ import annotations + +import importlib + +import mlx.core as mx +import pytest + +from omlx.patches import mlx_vlm_qwen4_exp_compat as compat + +compat.apply_mlx_vlm_qwen4_exp_compat_patch() +language = importlib.import_module("mlx_vlm.models.qwen4_exp.language") + +BF16_ULP = 2.0**-7 +FP32_ULP = 2.0**-23 + + +def _reference(x: mx.array, weight: mx.array, eps: float, group_size: int | None): + """The pre-fast-path body, kept verbatim as the thing we must not change.""" + dtype = x.dtype + y = x.astype(mx.float32) + if group_size is not None: + y = y.reshape(*y.shape[:-1], -1, group_size) + weight = weight.reshape(-1, group_size) + y = y * mx.rsqrt(mx.mean(mx.square(y), axis=-1, keepdims=True) + eps) + y = y * (1.0 + weight.astype(mx.float32)) + return y.reshape(x.shape).astype(dtype) + + +def _module(dim: int, group_size: int | None, weight: mx.array): + module = language.Qwen4ExpRMSNorm(dim, group_size=group_size, eps=1e-6) + module.weight = weight + return module + + +# (name, input shape, dim, group_size) -- every geometry the model builds. +_SEEDS = { + (name, scale): 1000 * i + int(scale * 100) + for i, name in enumerate( + [ + "hc_norm_verify", + "hc_norm_decode", + "hc_norm_6rows", + "qk_layernorm", + "qk_layernorm_decode", + "indexer", + "ple_pre_fc", + "gdn_norm_conv", + ] + ) + for scale in (0.0, 0.02, 0.5) +} + +SHAPES = [ + ("hc_norm_verify", (1, 4, 10240), 10240, 2560), + ("hc_norm_decode", (1, 1, 10240), 10240, 2560), + ("hc_norm_6rows", (1, 6, 10240), 10240, 2560), + ("qk_layernorm", (1, 4, 24, 256), 256, None), + ("qk_layernorm_decode", (1, 1, 24, 256), 256, None), + ("indexer", (1, 4, 4, 128), 128, None), + ("ple_pre_fc", (1, 4, 2560), 2560, None), + ("gdn_norm_conv", (1, 4, 2048), 2048, None), +] + + +@pytest.mark.parametrize("name,shape,dim,group_size", SHAPES, ids=[s[0] for s in SHAPES]) +@pytest.mark.parametrize("weight_scale", [0.0, 0.02, 0.5]) +def test_stays_within_one_bf16_ulp_of_the_hand_rolled_formulation( + name, shape, dim, group_size, weight_scale +): + """bf16 is the production dtype; the fast path may move at most one ULP. + + The kernel sums the squares in a different order than ``mx.mean``, so a + handful of values land on the far side of a bf16 rounding boundary. Over + 3.1M elements that is ~2 ppm at any weight magnitude, never above one ULP. + weight_scale 0.02 is the checkpoint's actual magnitude; 0.0 is the + zero-centered init, which makes ``(1 + w)`` a no-op and would hide a + dropped scale, so it is covered but never on its own. + """ + mx.random.seed(_SEEDS[(name, weight_scale)]) + x = (mx.random.normal(shape) * 1.5).astype(mx.bfloat16) + weight = (mx.random.normal((dim,)) * weight_scale).astype(mx.bfloat16) + + got = _module(dim, group_size, weight)(x) + want = _reference(x, weight, 1e-6, group_size) + + assert got.dtype == mx.bfloat16 + assert got.shape == x.shape + delta = mx.abs(got.astype(mx.float32) - want.astype(mx.float32)) + rel = delta / mx.maximum(mx.abs(want.astype(mx.float32)), 1e-30) + assert mx.max(rel).item() <= BF16_ULP, f"{name} moved more than one ULP" + # the rate is an aggregate property -- one element of a 6144-wide decode + # tensor is 163 ppm by construction, so it is asserted in bulk below + assert (delta > 0).sum().item() <= 2, f"{name} moved more than two elements" + + +def test_deviation_is_smaller_than_the_models_own_batching_spread(): + """The bar: MLX already moves this norm's input more than we do. + + Running the same row through a 1-row and a 4-row forward gives different + results from MLX's own matmul path selection. A refactor that stays below + that spread cannot be what makes a generation differ. + """ + mx.random.seed(4242) + x = (mx.random.normal((1, 4, 10240)) * 1.5).astype(mx.bfloat16) + weight = (mx.random.normal((10240,)) * 0.02).astype(mx.bfloat16) + module = _module(10240, 2560, weight) + + ours = mx.abs( + module(x).astype(mx.float32) - _reference(x, weight, 1e-6, 2560).astype(mx.float32) + ) + # the same reference formulation, one row at a time vs all four at once + batched = _reference(x, weight, 1e-6, 2560) + per_row = mx.concatenate( + [_reference(x[:, i : i + 1], weight, 1e-6, 2560) for i in range(x.shape[1])], axis=1 + ) + theirs = mx.abs(batched.astype(mx.float32) - per_row.astype(mx.float32)) + + assert mx.max(ours).item() <= mx.max(theirs).item(), ( + f"our max {mx.max(ours).item():.3e} exceeds the batching spread " + f"{mx.max(theirs).item():.3e}" + ) + + +@pytest.mark.parametrize("name,shape,dim,group_size", SHAPES, ids=[s[0] for s in SHAPES]) +def test_fp32_inputs_stay_within_a_few_ulp(name, shape, dim, group_size): + """fp32 has no bf16 rounding to mask the kernel's different summation order.""" + mx.random.seed(11) + x = (mx.random.normal(shape) * 1.5).astype(mx.float32) + weight = (mx.random.normal((dim,)) * 0.02).astype(mx.float32) + + got = _module(dim, group_size, weight)(x) + want = _reference(x, weight, 1e-6, group_size) + + assert got.dtype == mx.float32 + rel = mx.abs(got - want) / mx.maximum(mx.abs(want), 1e-30) + assert mx.max(rel).item() <= 4 * FP32_ULP + + +def test_the_grouped_scale_is_not_rounded_to_bf16(): + """A bf16 (1 + w) costs ~3.9e-3 relative -- the full half-ULP rounding bound. + + Guards the one shortcut that looks harmless and is not: precomputing the + scale in the weight's own dtype instead of fp32. Round-to-nearest cannot + exceed half a ULP, so this asserts the error saturates that bound rather + than passing it -- which is already ~16000x the fp32 path's ~2 fp32 ULP. + """ + mx.random.seed(5) + weight = (mx.random.normal((10240,)) * 0.02).astype(mx.bfloat16) + exact = 1.0 + weight.astype(mx.float32) + rounded = exact.astype(mx.bfloat16).astype(mx.float32) + worst = mx.max(mx.abs(rounded - exact) / mx.abs(exact)).item() + assert 0.4 * BF16_ULP < worst <= 0.5 * BF16_ULP + + x = (mx.random.normal((1, 4, 10240)) * 1.5).astype(mx.bfloat16) + got = _module(10240, 2560, weight)(x) + naive = ( + mx.fast.rms_norm(x.reshape(1, 4, 4, 2560), None, 1e-6).astype(mx.float32) + * rounded.reshape(-1, 2560) + ).reshape(x.shape).astype(mx.bfloat16) + assert not mx.array_equal(got, naive).item() + + +def test_grouping_is_per_group_not_whole_vector(): + """Four groups of 2560 must each get their own scale; one flat norm differs.""" + mx.random.seed(2) + x = (mx.random.normal((1, 4, 10240)) * 1.5).astype(mx.bfloat16) + # groups with deliberately unequal magnitude, so a whole-vector norm cannot + # coincide with the grouped one + x = mx.concatenate([x[..., :2560] * 8.0, x[..., 2560:]], axis=-1) + weight = (mx.random.normal((10240,)) * 0.02).astype(mx.bfloat16) + + grouped = _module(10240, 2560, weight)(x) + flat = _module(10240, None, weight)(x) + assert not mx.array_equal(grouped, flat).item() + assert mx.array_equal(grouped, _reference(x, weight, 1e-6, 2560)).item() + + +def test_rejects_a_dim_not_divisible_by_group_size(): + with pytest.raises(ValueError, match="divisible"): + language.Qwen4ExpRMSNorm(10240, group_size=3000) + + +def test_weight_stays_a_parameter_and_nothing_else_is_registered(): + """A cached scale filed into the module dict would break checkpoint I/O.""" + module = language.Qwen4ExpRMSNorm(10240, group_size=2560, eps=1e-6) + mx.eval(module(mx.zeros((1, 4, 10240), mx.bfloat16))) + assert list(module.parameters()) == ["weight"] + + +def test_deviation_rate_across_the_whole_geometry_is_a_few_ppm(): + """The rate bound the per-shape tests are too small to carry. + + ~3.1M elements per weight scale. Measured 1-8 ppm and independent of + weight magnitude; 50 ppm leaves an order of magnitude of headroom. + """ + total = moved = 0 + worst = 0.0 + for scale in (0.0, 0.02, 0.5): + for seed in range(12): + for name, shape, dim, group_size in SHAPES: + mx.random.seed(seed * 97 + len(name)) + x = (mx.random.normal(shape) * 1.5).astype(mx.bfloat16) + weight = (mx.random.normal((dim,)) * scale).astype(mx.bfloat16) + got = _module(dim, group_size, weight)(x) + want = _reference(x, weight, 1e-6, group_size) + delta = mx.abs(got.astype(mx.float32) - want.astype(mx.float32)) + total += got.size + moved += (delta > 0).sum().item() + rel = delta / mx.maximum(mx.abs(want.astype(mx.float32)), 1e-30) + worst = max(worst, mx.max(rel).item()) + + assert worst <= BF16_ULP, f"{worst / BF16_ULP:.2f} ULP exceeds one" + assert moved / total <= 50e-6, f"{moved / total * 1e6:.2f} ppm over {total} elements" From 7ee3b748e06b49257da08c66a2739450cd139252 Mon Sep 17 00:00:00 2001 From: jundot Date: Tue, 8 Sep 2026 12:07:41 +0900 Subject: [PATCH 114/132] fix(qwen4_exp): handle lazy fused kernel compilation (#3469) --- .../mlx_vlm/models/qwen4_exp/hc_fused.py | 91 +++++----- tests/test_qwen4_hc_fused.py | 159 +++++++++++++++--- tests/test_qwen4_hc_projection.py | 13 +- 3 files changed, 192 insertions(+), 71 deletions(-) diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/hc_fused.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/hc_fused.py index 8c6067d177..e32f04fc89 100644 --- a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/hc_fused.py +++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/hc_fused.py @@ -1,30 +1,14 @@ # SPDX-License-Identifier: Apache-2.0 -"""Fused hyper-connection kernels for Qwen4-Exp decode and verify rows. +"""Three Metal kernels for small Qwen4 hyper-connection inputs. -``Qwen4ExpGatedResidual._forward`` builds ~30 MLX nodes per call (grouped norm, -three small quantized projections, silu/sigmoid gates, stream mix and mean) and -runs 97 times per forward. On Apple Silicon the host-side kernel encoding of -that graph, not its GPU time, dominates a Lightning MTP verify cycle. Three -row-batched Metal kernels replace it for small row counts: +Fuses per-stream RMS norm, down/inject projections with activation, and the up +projection with stream mixing. Supports at most 16 BF16 rows, four streams, +and affine group-size-64 projections with 4/5/6/8-bit weights. FP32 epilogues +can round differently from the canonical BF16 operations. -* ``N`` -- per-stream RMS norm with the ``1 + weight`` scale (bit-identical to - ``mx.fast.rms_norm``). -* ``D`` -- ``input_mix_weight_down`` (320 rows) and ``block_inject_weight`` - (``hc_count`` rows) projections per token row, split over 4 K-slices, with - the ``silu(mix / hc_count)`` and ``2 * sigmoid(inject / hc_count)`` - epilogues folded in. -* ``U`` -- ``input_mix_weight_up`` per output element, sigmoid, times the - normed stream, mean over streams via simd shuffles. - -Rows live in the grid (``batch * seq <= 16``); within that limit the fused path -runs ahead of upstream's exact hybrid projection and compiled single-token path -(serial decode) as well as the canonical path (MTP verify). The affine unpack -helpers come from :mod:`hc_projection`. Any ``hidden_size`` that is a multiple of 64 is -supported: the norm, down and inject loops guard their partial final blocks -(compiled out for the shipped 2560). Results match the canonical path to a few -bf16 ULP (fp32 is kept through the epilogues); the path fails closed to -``_forward`` on any runtime error and logs once when a model's layout keeps it -on the canonical path. Disable with ``OMLX_QWEN4_HC_FUSED=0``. +Each kernel specialization is evaluated once inside the failure handler to +catch lazy compilation errors. Later calls stay lazy; errors during their +external evaluation propagate to the caller. Disable with OMLX_QWEN4_HC_FUSED=0. """ from __future__ import annotations @@ -49,6 +33,7 @@ "off", } _KERNELS: dict[str, object] = {} +_VALIDATED: set[tuple] = set() _RUNTIME_FAILED = False _FAILURE_LOGGED = False _INELIGIBLE_LOGGED = False @@ -126,9 +111,7 @@ bp += BLOCK / 64; xp += BLOCK; } - // Partial final block: only lanes whose VPT elements lie inside the slice take part. - // The helpers read exactly VPT values and VPT * BITS / 8 weight bytes, so nothing is - // touched past the slice; every lane still joins the simd_sum below. + // Load only lanes inside the tail; all lanes must join simd_sum. if (TAIL > 0 && int(lane) * VPT < TAIL) { float sum = hc_load_vector(xp, xv); for (int r = 0; r < 4; ++r) { @@ -240,7 +223,13 @@ """ -def _kernel(name: str, input_names: list[str], output_names: list[str], source: str, header: str = ""): +def _kernel( + name: str, + input_names: list[str], + output_names: list[str], + source: str, + header: str = "", +): kernel = _KERNELS.get(name) if kernel is None: kernel = mx.fast.metal_kernel( @@ -276,8 +265,7 @@ def _quantized_ok(projection) -> bool: def _ineligible(reason: str) -> bool: - """Record (once per process) why a model stays on the canonical path, so a future - checkpoint that misses the fused kernels shows up in the log instead of just running slower.""" + """Log the first unsupported model layout per process.""" global _INELIGIBLE_LOGGED if not _INELIGIBLE_LOGGED: _INELIGIBLE_LOGGED = True @@ -300,12 +288,6 @@ def compatible(module, hyper_input) -> bool: and 1 <= hyper_input.shape[0] * hyper_input.shape[1] <= MAX_ROWS ): return False - # With Lightning MTP off, load_weights installs upstream's exact hybrid projection - # (``_omlx_exact_hybrid_projection``) and compiles ``_forward`` for single-token - # decode. The fused path deliberately takes precedence over both: three kernels - # per module against a compiled call plus its own kernels measured +12..14% - # serial tok/s on the M5 Max. ``_forward`` keeps the hybrid for the rows this - # path does not take. if hasattr(module, "input_inject_weight"): return _ineligible("combined input projection layout") hc_count = getattr(module, "hc_count", None) @@ -316,12 +298,9 @@ def compatible(module, hyper_input) -> bool: and isinstance(hidden, int) and isinstance(lowrank, int) and hc_count == 4 - # Every kernel walks the hidden axis in 64-element quantisation groups (the up - # kernel's grid is hidden // 64); the norm, down and inject loops guard their - # partial final blocks, so any multiple of 64 is fine. + # The up grid and quantization groups require 64-element alignment. and hidden % 64 == 0 and lowrank % 64 == 0 - and lowrank % 8 == 0 and hyper_input.shape[2] == hc_count * hidden ): return _ineligible( @@ -343,7 +322,9 @@ def compatible(module, hyper_input) -> bool: return _ineligible( "projection quantisation (need affine group-size-64 4/5/6/8-bit with bf16 scales)" ) - if "block_inject_weight" in module and not _quantized_ok(module.block_inject_weight): + if "block_inject_weight" in module and not _quantized_ok( + module.block_inject_weight + ): return _ineligible("block_inject_weight quantisation") return mx.default_device() == mx.gpu and mx.metal.is_available() @@ -358,7 +339,7 @@ def _eps_array(module) -> mx.array: def fused_forward(module, hyper_input): - """Fused equivalent of ``Qwen4ExpGatedResidual._forward``; ``None`` on runtime failure.""" + """Return fused outputs, or None on construction or first-evaluation failure.""" global _RUNTIME_FAILED, _FAILURE_LOGGED try: hc, hidden, lowrank = module.hc_count, module.hidden_size, module.hc_lowrank @@ -378,7 +359,9 @@ def fused_forward(module, hyper_input): threadgroup=(256, 1, 1), output_shapes=[(rows, width)], output_dtypes=[dtype], - )[0] + )[ + 0 + ] if inject is not None: inject_tensors = (inject.weight, inject.scales, inject.biases) else: @@ -426,7 +409,27 @@ def fused_forward(module, hyper_input): threadgroup=(256, 1, 1), output_shapes=[(rows, hidden)], output_dtypes=[dtype], - )[0] + )[ + 0 + ] + signature = ( + dtype, + hc, + hidden, + lowrank, + rows, + down.bits, + up.bits, + inject.bits if inject is not None else None, + ) + if signature not in _VALIDATED: + # Metal compilation is lazy. Validate once, without synchronizing + # subsequent layers or decode steps using the same specialization. + if inject is None: + mx.eval(mixed) + else: + mx.eval(mixed, injection) + _VALIDATED.add(signature) mixed = mixed.reshape(batch, seq, hidden) if inject is None: return mixed diff --git a/tests/test_qwen4_hc_fused.py b/tests/test_qwen4_hc_fused.py index 54a6250af2..789e8a45e0 100644 --- a/tests/test_qwen4_hc_fused.py +++ b/tests/test_qwen4_hc_fused.py @@ -1,8 +1,10 @@ # SPDX-License-Identifier: Apache-2.0 """Fused hyper-connection kernels: parity with the canonical path, eligibility, kill switch.""" + from __future__ import annotations import importlib +from unittest.mock import Mock import mlx.core as mx import mlx.nn as nn @@ -15,6 +17,7 @@ def _vendored_qwen4(): compat.apply_mlx_vlm_qwen4_exp_compat_patch() + HC, HIDDEN, LOWRANK = 4, 2560, 320 WIDTH = HC * HIDDEN @@ -29,30 +32,46 @@ def _module(bits: int, use_combine: bool = True, hidden: int = HIDDEN): module.hc_count, module.hidden_size, module.hc_lowrank = HC, hidden, LOWRANK module.hc_norm = Qwen4ExpRMSNorm(width, group_size=hidden, eps=1e-6) module.hc_norm.weight = (mx.random.normal((width,)) * 0.05).astype(mx.bfloat16) - module.input_mix_weight_down = nn.QuantizedLinear(width, LOWRANK, bias=False, group_size=64, bits=bits) - module.input_mix_weight_up = nn.QuantizedLinear(LOWRANK, width, bias=False, group_size=64, bits=bits) + module.input_mix_weight_down = nn.QuantizedLinear( + width, LOWRANK, bias=False, group_size=64, bits=bits + ) + module.input_mix_weight_up = nn.QuantizedLinear( + LOWRANK, width, bias=False, group_size=64, bits=bits + ) if use_combine: - module.block_inject_weight = nn.QuantizedLinear(width, HC, bias=False, group_size=64, bits=bits) + module.block_inject_weight = nn.QuantizedLinear( + width, HC, bias=False, group_size=64, bits=bits + ) for name in ("input_mix_weight_down", "input_mix_weight_up", "block_inject_weight"): projection = getattr(module, name, None) if projection is not None: # Checkpoint-like statistics: positive scales, small biases. Random-sign scales drive the # up-projection gate into saturation where any rounding difference flips whole elements. - projection.scales = (mx.abs(mx.random.normal(projection.scales.shape)) * 0.01 + 0.002).astype(mx.bfloat16) - projection.biases = (mx.random.normal(projection.biases.shape) * 0.005).astype(mx.bfloat16) + projection.scales = ( + mx.abs(mx.random.normal(projection.scales.shape)) * 0.01 + 0.002 + ).astype(mx.bfloat16) + projection.biases = ( + mx.random.normal(projection.biases.shape) * 0.005 + ).astype(mx.bfloat16) mx.eval(module.parameters()) return module def _reference_fp32(module, x): def dequant(q): - return mx.dequantize(q.weight, q.scales, q.biases, group_size=q.group_size, bits=q.bits).astype(mx.float32) + return mx.dequantize( + q.weight, q.scales, q.biases, group_size=q.group_size, bits=q.bits + ).astype(mx.float32) normed = module.hc_norm(x).astype(mx.float32) mix = nn.silu((normed @ dequant(module.input_mix_weight_down).T) / HC) gate = mx.sigmoid(mix @ dequant(module.input_mix_weight_up).T) hidden = module.hidden_size - mixed = mx.mean(gate.reshape(*gate.shape[:-1], HC, hidden) * normed.reshape(*normed.shape[:-1], HC, hidden), axis=-2) + mixed = mx.mean( + gate.reshape(*gate.shape[:-1], HC, hidden) + * normed.reshape(*normed.shape[:-1], HC, hidden), + axis=-2, + ) if "block_inject_weight" not in module: return mixed, None return mixed, 2 * mx.sigmoid((normed @ dequant(module.block_inject_weight).T) / HC) @@ -131,14 +150,18 @@ def test_fused_norm_is_bit_identical_to_rms_norm(hidden): width = HC * hidden x = (mx.random.normal((1, 4, width)) * 3).astype(mx.bfloat16) flat = x.reshape(4, width) - normed = hc_fused._kernel("omlx_qwen4_hc_fused_norm", ["x", "w", "eps"], ["xn"], hc_fused._N_SOURCE)( + normed = hc_fused._kernel( + "omlx_qwen4_hc_fused_norm", ["x", "w", "eps"], ["xn"], hc_fused._N_SOURCE + )( inputs=[flat, module.hc_norm.weight, hc_fused._eps_array(module)], template=[("T", mx.bfloat16), ("K", width), ("H", hidden)], grid=(256, HC, 4), threadgroup=(256, 1, 1), output_shapes=[(4, width)], output_dtypes=[mx.bfloat16], - )[0] + )[ + 0 + ] expected = module.hc_norm(x).reshape(4, width) mx.eval(normed, expected) assert mx.array_equal(normed.view(mx.uint16), expected.view(mx.uint16)).item() @@ -152,7 +175,9 @@ def test_gated_residual_call_routes_through_fused_path(monkeypatch): x = mx.random.normal((1, 2, WIDTH)).astype(mx.bfloat16) calls = [] original = hc_fused.fused_forward - monkeypatch.setattr(hc_fused, "fused_forward", lambda m, h: calls.append(h.shape) or original(m, h)) + monkeypatch.setattr( + hc_fused, "fused_forward", lambda m, h: calls.append(h.shape) or original(m, h) + ) out = module(x) mx.eval(out) assert calls == [(1, 2, WIDTH)] @@ -179,26 +204,35 @@ def test_ineligible_model_is_logged_once(monkeypatch, caplog): assert not hc_fused.compatible(module, x) # Prefill-sized inputs are expected to skip the fused path and must not log. monkeypatch.setattr(hc_fused, "_INELIGIBLE_LOGGED", False) - assert not hc_fused.compatible(_module(4), mx.random.normal((1, 64, WIDTH)).astype(mx.bfloat16)) - messages = [r.getMessage() for r in caplog.records if "fused hyper-connection kernels not used" in r.getMessage()] + assert not hc_fused.compatible( + _module(4), mx.random.normal((1, 64, WIDTH)).astype(mx.bfloat16) + ) + messages = [ + r.getMessage() + for r in caplog.records + if "fused hyper-connection kernels not used" in r.getMessage() + ] assert len(messages) == 1 assert "hidden_size=800" in messages[0] @pytest.mark.skipif(not mx.metal.is_available(), reason="requires Metal") def test_fused_path_takes_precedence_over_exact_hybrid_projection(monkeypatch): - # With MTP off, load_weights flags modules with upstream's exact hybrid projection and compiles - # their single-token _forward. The fused path must still win for decode rows (+12..14% serial). + # Fused dispatch takes precedence over the compiled hybrid decode path. from mlx_vlm.models.qwen4_exp import hc_fused module = _module(4) module._omlx_exact_hybrid_projection = True - module._compiled_forward = lambda h: pytest.fail("compiled single-token path must not run") + module._compiled_forward = lambda h: pytest.fail( + "compiled single-token path must not run" + ) x = mx.random.normal((1, 1, WIDTH)).astype(mx.bfloat16) assert hc_fused.compatible(module, x) calls = [] original = hc_fused.fused_forward - monkeypatch.setattr(hc_fused, "fused_forward", lambda m, h: calls.append(h.shape) or original(m, h)) + monkeypatch.setattr( + hc_fused, "fused_forward", lambda m, h: calls.append(h.shape) or original(m, h) + ) out = module(x) mx.eval(out) assert calls == [(1, 1, WIDTH)] @@ -211,10 +245,18 @@ def test_compatible_fails_closed(): ok = mx.random.normal((1, 4, WIDTH)).astype(mx.bfloat16) if mx.metal.is_available(): assert hc_fused.compatible(module, ok) - assert not hc_fused.compatible(module, mx.random.normal((1, 17, WIDTH)).astype(mx.bfloat16)) - assert not hc_fused.compatible(module, mx.random.normal((2, 9, WIDTH)).astype(mx.bfloat16)) - assert not hc_fused.compatible(module, mx.random.normal((1, 4, WIDTH)).astype(mx.float16)) - assert not hc_fused.compatible(module, mx.random.normal((4, WIDTH)).astype(mx.bfloat16)) + assert not hc_fused.compatible( + module, mx.random.normal((1, 17, WIDTH)).astype(mx.bfloat16) + ) + assert not hc_fused.compatible( + module, mx.random.normal((2, 9, WIDTH)).astype(mx.bfloat16) + ) + assert not hc_fused.compatible( + module, mx.random.normal((1, 4, WIDTH)).astype(mx.float16) + ) + assert not hc_fused.compatible( + module, mx.random.normal((4, WIDTH)).astype(mx.bfloat16) + ) module.input_inject_weight = nn.Linear(WIDTH, LOWRANK + HC, bias=False) assert not hc_fused.compatible(module, ok) del module.input_inject_weight @@ -229,7 +271,82 @@ def test_kill_switch_disables_fused_path(monkeypatch): reloaded = importlib.reload(hc_fused) try: assert not reloaded.enabled() - assert not reloaded.compatible(_module(4), mx.random.normal((1, 4, WIDTH)).astype(mx.bfloat16)) + assert not reloaded.compatible( + _module(4), mx.random.normal((1, 4, WIDTH)).astype(mx.bfloat16) + ) finally: monkeypatch.delenv("OMLX_QWEN4_HC_FUSED") importlib.reload(hc_fused) + + +@pytest.mark.skipif(not mx.metal.is_available(), reason="requires Metal") +@pytest.mark.parametrize("source_name", ["_N_SOURCE", "_D_SOURCE", "_U_SOURCE"]) +@pytest.mark.parametrize("use_combine", [False, True]) +def test_lazy_compilation_failure_returns_canonical_output( + monkeypatch, caplog, source_name, use_combine +): + from mlx_vlm.models.qwen4_exp import hc_fused + + monkeypatch.setattr(hc_fused, "_KERNELS", {}) + monkeypatch.setattr(hc_fused, "_VALIDATED", set()) + monkeypatch.setattr(hc_fused, "_RUNTIME_FAILED", False) + monkeypatch.setattr(hc_fused, "_FAILURE_LOGGED", False) + monkeypatch.setattr( + hc_fused, + source_name, + getattr(hc_fused, source_name) + "\nintentional_compile_error;\n", + ) + module = _module(4, use_combine, hidden=64) + x = mx.ones((1, 1, HC * 64), dtype=mx.bfloat16) + expected = module._forward(x) + mx.eval(expected) + with caplog.at_level("WARNING", logger=hc_fused.logger.name): + actual = module(x) + mx.eval(actual) + repeated = module(x) + mx.eval(repeated) + assert hc_fused._RUNTIME_FAILED + assert not hc_fused._VALIDATED + assert not hc_fused.enabled() + if not use_combine: + actual, expected, repeated = [actual], [expected], [repeated] + for value, reference, again in zip(actual, expected, repeated): + assert mx.array_equal(value, reference).item() + assert mx.array_equal(again, reference).item() + messages = [r for r in caplog.records if "failed closed" in r.getMessage()] + assert len(messages) == 1 + assert "intentional_compile_error" in messages[0].getMessage() + + +@pytest.mark.skipif(not mx.metal.is_available(), reason="requires Metal") +def test_specializations_validate_once_and_keep_warm_calls_lazy(monkeypatch): + from mlx_vlm.models.qwen4_exp import hc_fused + + monkeypatch.setattr(hc_fused, "_VALIDATED", set()) + # Cover each varying template input, including mixed projection bit widths. + for hidden, rows, down_bits, up_bits, inject_bits in [ + (64, 1, 4, 4, 4), + (64, 4, 4, 4, 4), + (128, 4, 4, 4, 4), + (128, 4, 5, 4, 4), + (128, 4, 5, 6, 4), + (128, 4, 5, 6, 8), + (128, 4, 5, 6, None), + ]: + module = _module(down_bits, inject_bits is not None, hidden=hidden) + module.input_mix_weight_up = _module(up_bits, hidden=hidden).input_mix_weight_up + if inject_bits is not None: + module.block_inject_weight = _module( + inject_bits, hidden=hidden + ).block_inject_weight + hc_fused._eps_array(module) + x = mx.ones((1, rows, HC * hidden), dtype=mx.bfloat16) + mx.eval(x) + with monkeypatch.context() as patch: + evaluate = Mock(wraps=mx.eval) + patch.setattr(mx, "eval", evaluate) + first = module(x) + second = module(x) + assert evaluate.call_count == 1 + mx.eval(first, second) + assert len(hc_fused._VALIDATED) == 7 diff --git a/tests/test_qwen4_hc_projection.py b/tests/test_qwen4_hc_projection.py index 45f07ab33d..fdbcecd31d 100644 --- a/tests/test_qwen4_hc_projection.py +++ b/tests/test_qwen4_hc_projection.py @@ -28,9 +28,7 @@ def _production_module(bits: int): group_size=2560, eps=1e-6, ) - module.hc_norm.weight = ( - mx.random.normal((10240,)) * 0.02 - ).astype(mx.bfloat16) + module.hc_norm.weight = (mx.random.normal((10240,)) * 0.02).astype(mx.bfloat16) module.input_mix_weight_down = nn.QuantizedLinear( 10240, 320, @@ -67,14 +65,17 @@ def _production_module(bits: int): @pytest.mark.parametrize("bits", [4, 5, 6, 8]) @pytest.mark.skipif(not mx.metal.is_available(), reason="requires Metal") -def test_qwen4_exact_hybrid_raw_and_full_outputs_are_bit_exact(bits): +def test_qwen4_exact_hybrid_raw_and_full_outputs_are_bit_exact(bits, monkeypatch): compat.apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp import hc_fused from mlx_vlm.models.qwen4_exp.hc_projection import hybrid_projection from mlx_vlm.models.qwen4_exp.language import ( compile_hyper_connections, fuse_hyper_connection_projections, ) + # Keep this bit-exact test on the hybrid path, below fused dispatch. + monkeypatch.setattr(hc_fused, "_DISABLED", True) mx.random.seed(20260900 + bits) module = _production_module(bits) down = module.input_mix_weight_down @@ -115,9 +116,9 @@ def test_qwen4_exact_hybrid_raw_and_full_outputs_are_bit_exact(bits): @pytest.mark.skipif(not mx.metal.is_available(), reason="requires Metal") def test_qwen4_exact_hybrid_fallbacks_never_enter_native(monkeypatch): compat.apply_mlx_vlm_qwen4_exp_compat_patch() - from mlx_vlm.models.qwen4_exp import hc_projection - from mlx_vlm.models.qwen4_exp import language + from mlx_vlm.models.qwen4_exp import hc_fused, hc_projection, language + monkeypatch.setattr(hc_fused, "_DISABLED", True) mx.random.seed(20261100) module = _production_module(5) assert language.fuse_hyper_connection_projections(module) == 1 From 13ef86fe7be585bb8f6e7e78ed01563339d04315 Mon Sep 17 00:00:00 2001 From: Jonathan Spangler Date: Mon, 7 Sep 2026 20:11:14 -0700 Subject: [PATCH 115/132] feat(cluster): add trusted discovery and pairing foundation (#3155) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(cluster): add v2 node identity module NodeIdentity (uuid4 node_id, scutil-derived friendly_name, schema_version 1) persisted atomically at 0600 to ~/.omlx/cluster/identity.json, with friendly -name collision repair (-2 suffix), rename(), and corruption handling that never silently rotates node_id. Offline unit tests cover persistence, collision, rename, and corrupt-file behavior. * feat(cluster): add v2 DeviceRegistry for paired/discovered devices DeviceRegistry persists paired devices atomically (0600, schema_version 1) to devices.json while discovered-but-unpaired devices stay memory-only. Merge API dedupes on node_id, never downgrades paired trust, and is shaped to accept discovery PeerRecords directly. Fails closed on corruption like ClusterRegistry. Existing ClusterRegistry untouched. * feat(cluster): add v2 PeerRecord + DiscoveryService (mDNS/multicast/manual/tailscale) Layered peer discovery appended to omlx/cluster/discovery.py without touching the existing dns-sd Bonjour code: _omlx._tcp.local. via optional python-zeroconf (absence disables mDNS only), exo-style IPv6 link-local HELLO/WASSUP on ff12::6f6d:6c78/53413 with per-interface joins, nonce-echo self-drop, higher-node_id-initiates-contact, blake2s cluster-hash filter (log-once on mismatch), verification probes against /api/cluster/node_id with node_id-mismatch address drops, RTT-based link classification, and discovered/suspect(6s)/dead(30s) liveness with on_change callbacks. multicast_ok reports whether a foreign HELLO arrived within 5s so the UI can warn about macOS Local Network permission. 30 offline tests; sockets, prober, clock, interfaces, tailscale, and zeroconf all injected. * feat(cluster): wire v2 discovery endpoints and service into server New omlx/cluster/discovery_routes.py with GET /api/cluster/node_id (public, per-IP token-bucket rate limited, 0600 identity only) and GET /api/cluster/devices (admin-gated; {paired, discovered, self} plus multicast_ok/mdns_available signals so the UI can warn about macOS Local Network denial instead of showing silent zeros). discovery_router registered in _register_cluster_routes behind the distributed-inference exposure flag only. Identity + device registry configured at startup; DiscoveryService started/stopped in the server lifespan when the feature is enabled (OMLX_DISCOVERY=0 opts out). zeroconf added as the 'cluster' extra. * test(cluster): cover mDNS announce/failure paths; whitelist v2 test hooks in seams lint * cluster v2: code-based pairing + enrollment bridge (Module B) PairingManager drives the existing fail-closed SSH TOFU primitives (ssh_keys install_authorized_key / add_verified_peer_host_key) instead of the 3-step copy-paste relay: 6-digit code shown on the joiner, 10-minute validity, 3 attempts then 10-minute lockout, blake2s(code+node_id) on the wire, 32-byte cluster_key wrapped under PBKDF2-HMAC-SHA256 (100k iters), JSON-lines audit log, deny + unpair with SSH trust revocation. Endpoints under /api/cluster: pair/request + pair/status (public, pinned by the out-of-band code) and pair/approve + pair/deny + DELETE devices/{node_id} (admin). Wired in server.py alongside the existing cluster routers; legacy relay endpoints kept working and marked advanced/legacy. Module A registry/identity are feature-detected with schema-compatible local fallbacks until that branch lands. * cluster v2: offline pairing tests (loopback, lockout, expiry, unpair, legacy) Two-manager loopback happy path via injected transport; wrong-code 3-strike lockout (correct code refused inside window, code expired after it, attempts reset when a lockout ends inside validity); expiry; deny; unpair revocation (device store + key store + legacy enrolled-nodes + SSH material); key/device store persistence, 0600, fail-closed corruption; Module A registry bridge feature-detection; endpoint error mapping (400/403/404/410/422/423/502/503); legacy 3-step relay route registration + HMAC token non-regression. * cluster: add GET /api/cluster/discovery/health (seam a) Pinned shape from Agent C's fixture: multicast_rx_within_5s, last_multicast_rx_at, mdns_active, transport. DiscoveryService now records a wall-clock timestamp alongside the monotonic hello marker and exposes last_multicast_rx_at / mdns_active / transport_summary(). Admin- gated like /devices; fixture shape matched exactly, no UI changes needed. * cluster: wire pairing onto Module A DeviceRegistry (seam b) - server.py startup: configure identity + device registry BEFORE the pairing manager and pass get_device_registry() as registry=, so pairing approvals persist into the real registry instead of the fallback store. - DeviceRegistryBridge.put_paired: detect mark_paired first and call it with keyword fields. The real DeviceRegistry.mark_paired takes kwargs, and its merge() persists only already-paired devices — routing an approval through merge would have left new peers memory-only. - load_node_identity: Module A ships load_or_create as a module-level function (not a NodeIdentity classmethod); call it with the base_path identity.json so pairing and discovery share one identity. - Tests: bridge driven against the real DeviceRegistry (persistence, unpair); full pairing suite green. * cluster: surface pending pair requests in /api/cluster/devices (seam c) PairingManager.pending_requests() rows are merged into the discovered list with state 'awaiting_approval' (pending state wins for a node that is both discovered and awaiting approval), matching the wizard fixture devices_pending_approval.json. Module A keeps endpoint ownership; the pairing manager is looked up lazily and its absence changes nothing. * cluster: settings-level cluster_name via persisted cluster.json (seam e) ~/.omlx/cluster/cluster.json ({schema_version, cluster_name}, atomic 0600 write) is the settings-level cluster name: server startup feeds it into DiscoveryConfig, and the node_id probe reports it even when the discovery service is disabled. Missing/malformed file falls back to 'omlx' — pre-config behavior unchanged. * cluster-v2 discovery: macOS resilience overhaul + manual peer add Field-diagnosed on the Studio/M5 test pair (macOS 26.5.2, TB5 direct link): - _sync_interfaces now drops vanished interfaces and detects interface renumbering (TB hotplug), re-joining the group under the new ifindex. Previously a stale ifindex silently wedged sends with EHOSTUNREACH forever (observed: 7,085 failures in 9 min, then total silence). - HELLO sends now carry the egress interface as the destination scope id (4-tuple) instead of mutating IPV6_MULTICAST_IF on the shared socket. - WASSUP unicast replies preserve the HELLO source's scope id; without it replies to link-local senders have no route and the handshake could never complete even when multicast flowed. - Background loops run under a supervisor that logs CRITICAL and restarts them on crash, and warns + restarts on unexpected clean exit; the datagram handler is exception-guarded; the loop rebuilds the socket after 3 consecutive all-failed HELLO rounds and clears its join state on exit so a supervised restart starts clean. - Per-interface/per-peer rate-limited failure logging (60s) ends the one-line-per-second-per-interface log spam. - New GET /api/cluster/discovery/health/detail (loop liveness, socket state, joined interfaces, TX error/counters) so 'no peers' is distinguishable from 'discovery dead'. The pinned wizard fixture shape on /discovery/health is untouched. - New POST /api/cluster/devices/manual {ip, port?} — deterministic peer add over the Thunderbolt 10.0.0.x pair (or any IP), verified through the standard HTTP probe path, admin-gated + rate-limited. - /api/cluster/devices self row now reports real local addresses instead of a hardcoded empty list. Tests: 17 new (scoped 4-tuple sends, scope-preserving replies, renumber heal, vanished-if drop, TX rate limiting, fail-round socket reset, socket rebuild liveness, supervised crash restart, health detail, manual-add route incl. 400/503 paths). 62/62 discovery tests pass; 421/421 across discovery+wizard+pairing+exposure scope. * cluster-v2 discovery: backoff socket rebuilds, flag suspected Local Network blocks Follow-up to 5ab14c19 from live field observation on the M5 node: when the wedge is process-level (macOS Local Network permission denial — fresh processes with the same interpreter send/receive fine while the server gets EHOSTUNREACH on every interface), per-second socket rebuilds cannot help and only spam the log (1 warning/sec indefinitely). - Socket rebuilds now back off exponentially (2^n seconds, capped at 60s); the streak warning logs once per streak instead of every round. - After 6 fruitless rebuilds the service logs CRITICAL with actionable guidance (Local Network settings / restart / manual-add fallback) and sets local_network_blocked_suspected, exposed via /api/cluster/discovery/health/detail. Any successful TX round or foreign HELLO RX clears the flag and the backoff schedule. - 88/88 discovery + wizard tests pass. * cluster v2: carry coordinator caps through pair/status; detect TB RDMA in local caps - join_status() (the poll path the joiner UI actually drives) now returns the same coordinator block approve() returns — caps + ssh key — so complete_join persists real capabilities instead of empty caps - local_caps() detects the Thunderbolt RDMA fabric via rdma_ctl status + ibv_devices (fail-safe, macOS-only, injectable runner): thunderbolt flag when rdma_* devices exist, jaccl when RDMA is also enabled — the wizard's RDMA check row and jaccl-vs-ring selection key off these Tests: +3 (join_status caps/key, rdma fabric detection on/off/failing); cluster slice 1561 pass 0 fail * cluster v2: fix rdma device parse (ibv_devices output is whitespace-indented) * cluster v2: non-downgrading device-registry merge A discovery HELLO carries structurally complete but value-empty caps ({chip:'', ram_gb:0.0,...}); DeviceRegistry.merge truthiness-replaced the pairing-exchanged record, so a few seconds after pairing every paired device silently lost its chip/ram/fabric flags and its routable addrs — the wizard then planned with ram_gb=0 and dropped the node. Merge is now field-wise: real values win, backends union, fabric flags sticky-true, addrs union (capped), and records without flags keep their shape. * fix(cluster): paired device rows carry paired=true in /api/cluster/devices Registry rows never carried the flag (only the self record set it), so wizard consumers keyed on device.paired -- the per-Mac memory-contributes role list and the device card's Pair/Paired state -- treated an already paired peer as unpaired: the peer's role row was missing and the card kept offering Pair after a successful pairing. List membership is now reflected on the row itself; UI fixtures already expected this contract. * Rehydrate trusted peer endpoints after reboot * Reconnect paired peers through system Python * Expose and force paired peer probes * Discover Tailscale peers from macOS app * Keep paired discovery heartbeats responsive * Heartbeat verified discovery candidates * fix(cluster): make pairing and SSH enrollment fail closed * test(cluster): keep injected RDMA probes host-independent * fix(cluster): serialize pairing completion and roll back partial trust * fix(cluster): rate-limit public pairing endpoints --------- Co-authored-by: jonathan308 --- omlx/cluster/discovery.py | 1587 ++++++++++++++++++++++- omlx/cluster/discovery_routes.py | 393 ++++++ omlx/cluster/identity.py | 251 ++++ omlx/cluster/pairing.py | 1650 ++++++++++++++++++++++++ omlx/cluster/pairing_routes.py | 184 +++ omlx/cluster/registry.py | 422 +++++- omlx/cluster/routes.py | 26 +- omlx/cluster/system_socket_proxy.py | 218 ++++ omlx/server.py | 113 +- pyproject.toml | 7 + tests/test_cluster_device_registry.py | 289 +++++ tests/test_cluster_discovery_routes.py | 629 +++++++++ tests/test_cluster_identity.py | 133 ++ tests/test_cluster_pairing.py | 1189 +++++++++++++++++ tests/test_cluster_seams.py | 57 +- tests/test_cluster_v2_discovery.py | 1199 +++++++++++++++++ tests/test_system_socket_proxy.py | 87 ++ 17 files changed, 8395 insertions(+), 39 deletions(-) create mode 100644 omlx/cluster/discovery_routes.py create mode 100644 omlx/cluster/identity.py create mode 100644 omlx/cluster/pairing.py create mode 100644 omlx/cluster/pairing_routes.py create mode 100644 omlx/cluster/system_socket_proxy.py create mode 100644 tests/test_cluster_device_registry.py create mode 100644 tests/test_cluster_discovery_routes.py create mode 100644 tests/test_cluster_identity.py create mode 100644 tests/test_cluster_pairing.py create mode 100644 tests/test_cluster_v2_discovery.py create mode 100644 tests/test_system_socket_proxy.py diff --git a/omlx/cluster/discovery.py b/omlx/cluster/discovery.py index 65de3c0fb7..b3656fef3d 100644 --- a/omlx/cluster/discovery.py +++ b/omlx/cluster/discovery.py @@ -181,7 +181,9 @@ def capture_dns_sd(args: Sequence[str], timeout: float) -> DiscoveryOutput: return DiscoveryOutput(raw.decode(errors="replace"), error) -def parse_browse_instances(output: str, service_type: str = "_ssh._tcp.") -> tuple[str, ...]: +def parse_browse_instances( + output: str, service_type: str = "_ssh._tcp." +) -> tuple[str, ...]: """Parse service instance names without trusting their display text.""" instances: list[str] = [] @@ -249,10 +251,7 @@ def resolve(instance: str) -> dict[str, Any] | None: if target is None: return None hostname, port = target - if ( - port != 22 - or _bonjour_host_label(hostname) == local_hostname - ): + if port != 22 or _bonjour_host_label(hostname) == local_hostname: return None return { "name": instance, @@ -305,10 +304,7 @@ def verify_pairing_token(encoded_token: str, *, shared_secret: str) -> bool: except (binascii.Error, json.JSONDecodeError, KeyError, TypeError, ValueError): return False - if ( - not isinstance(expires_at, (int, float)) - or isinstance(expires_at, bool) - ): + if not isinstance(expires_at, (int, float)) or isinstance(expires_at, bool): return False if time.time() > expires_at: @@ -498,3 +494,1576 @@ def _enrich_peer_transports( peer["transport"] = known["transport"] if known else "detecting" peer["link_speed_gbps"] = known["link_speed_gbps"] if known else None peer["rdma_available"] = known["rdma_available"] if known else False + + +# --------------------------------------------------------------------------- +# Cluster v2: PeerRecord + DiscoveryService +# +# Layered peer discovery (see ops/notes/cluster_discovery_onboarding_comparison.md): +# 1. mDNS (_omlx._tcp.local.) via python-zeroconf — optional; absence or any +# mDNS failure disables only mDNS, never the process. +# 2. IPv6 link-local multicast fallback (exo-style): HELLO/WASSUP on +# ff12::6f6d:6c78 udp/53413 with per-interface joins and nonce self-drop. +# 3. Manual peer add (add_manual) for multicast-filtered networks. +# 4. Tailscale opportunistic candidates when the tailscale CLI exists. +# Every announced address is verified against GET /api/cluster/node_id before +# it is trusted; peers never graduate from "discovered" without that probe. +# --------------------------------------------------------------------------- + +import errno # noqa: E402 +import hashlib # noqa: E402 +import http.client # noqa: E402 +import ipaddress # noqa: E402 +import logging # noqa: E402 +import os # noqa: E402 +import platform # noqa: E402 +import struct # noqa: E402 +import sys # noqa: E402 +import threading # noqa: E402 +import urllib.request # noqa: E402 +from collections import deque # noqa: E402 +from contextlib import suppress # noqa: E402 +from dataclasses import dataclass, field # noqa: E402 +from pathlib import Path # noqa: E402 + +from .._version import __version__ as _omlx_version # noqa: E402 + +logger = logging.getLogger(__name__) # noqa: E402 +_probe_diagnostics = threading.local() + +MDNS_SERVICE_TYPE = "_omlx._tcp.local." +MULTICAST_GROUP = "ff12::6f6d:6c78" +MULTICAST_PORT = 53413 +_HELLO_MAGIC = b"OMLX" +_WASSUP_MAGIC = b"OMLXW" +_HELLO_STRUCT = struct.Struct(">4sQQ") # magic, nonce, cluster_hash +_MAX_DATAGRAM = 2048 +_RECENT_NONCES = 64 +_MAX_CANDIDATES = 256 +_MACOS_TAILSCALE_CLI = "/Applications/Tailscale.app/Contents/MacOS/Tailscale" + +# Multicast-join failures we tolerate per-interface (macOS gotcha #3: skip +# interfaces that do not support multicast instead of dying). +_JOIN_IGNORED_ERRNOS = { + errno.EAFNOSUPPORT, + errno.EADDRNOTAVAIL, + errno.ENODEV, + errno.ENXIO, + errno.EINVAL, +} + +# HELLO-send and WASSUP-reply failure logs are rate-limited per interface / +# peer (a down Thunderbolt bridge otherwise spams one line per second per +# interface forever — 7k lines in nine minutes observed in the field). +_TX_FAIL_LOG_INTERVAL = 60.0 +# After this many consecutive HELLO rounds in which every send failed, the +# multicast socket is discarded and rebuilt. macOS gotcha #6: Thunderbolt +# hotplug renumbers interfaces, which wedges a bound socket's per-interface +# multicast state; rebuilding is the only reliable escape. +_TX_FAIL_RESET_ROUNDS = 3 + + +def cluster_hash_u64(cluster_name: str) -> int: + """blake2s(cluster_name)[:8] as a big-endian u64.""" + + digest = hashlib.blake2s(str(cluster_name).encode("utf-8")).digest() + return int.from_bytes(digest[:8], "big") + + +def encode_hello(nonce: int, cluster_hash: int) -> bytes: + return _HELLO_STRUCT.pack(_HELLO_MAGIC, nonce & 0xFFFFFFFFFFFFFFFF, cluster_hash) + + +def decode_hello(data: bytes) -> tuple[int, int] | None: + """Decode a HELLO datagram to (nonce, cluster_hash); ``None`` if invalid.""" + + if len(data) != _HELLO_STRUCT.size: + return None + magic, nonce, cluster_hash = _HELLO_STRUCT.unpack(data) + if magic != _HELLO_MAGIC: + return None + return nonce, cluster_hash + + +def encode_wassup(nonce: int, node_id: str, http_port: int) -> bytes: + payload = json.dumps( + {"nonce": nonce, "node_id": node_id, "http_port": int(http_port)}, + separators=(",", ":"), + ).encode("utf-8") + return _WASSUP_MAGIC + payload + + +def decode_wassup(data: bytes) -> dict[str, Any] | None: + """Decode a WASSUP datagram; ``None`` if invalid.""" + + if not data.startswith(_WASSUP_MAGIC): + return None + try: + payload = json.loads(data[len(_WASSUP_MAGIC) :].decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError): + return None + if not isinstance(payload, dict): + return None + nonce = payload.get("nonce") + node_id = payload.get("node_id") + http_port = payload.get("http_port") + if not isinstance(nonce, int) or not 0 <= nonce < 1 << 64: + return None + if not isinstance(node_id, str) or not node_id or len(node_id) > 255: + return None + if not isinstance(http_port, int) or not 1 <= http_port <= 65535: + return None + return {"nonce": nonce, "node_id": node_id, "http_port": http_port} + + +@dataclass +class PeerCaps: + chip: str = "" + ram_gb: float = 0.0 + backends: list[str] = field(default_factory=list) + thunderbolt: bool = False + jaccl: bool = False + + def to_dict(self) -> dict[str, Any]: + return { + "chip": self.chip, + "ram_gb": self.ram_gb, + "backends": list(self.backends), + "thunderbolt": self.thunderbolt, + "jaccl": self.jaccl, + } + + @classmethod + def from_dict(cls, payload: Any) -> PeerCaps: + if not isinstance(payload, dict): + return cls() + backends = payload.get("backends") + return cls( + chip=str(payload.get("chip") or "")[:128], + ram_gb=float(payload.get("ram_gb") or 0.0), + backends=[str(b) for b in backends][:8] + if isinstance(backends, list) + else [], + thunderbolt=bool(payload.get("thunderbolt")), + jaccl=bool(payload.get("jaccl")), + ) + + +def _rdma_fabric_caps( + caps: PeerCaps, runner: Callable[..., Any] = subprocess.run +) -> None: + """Detect the Thunderbolt RDMA fabric and set ``thunderbolt``/``jaccl``. + + macOS-only, best-effort, never raises: ``rdma_ctl status`` reports + whether RDMA is enabled and ``ibv_devices`` lists the ``rdma_*`` devices, + which exist only on the Thunderbolt fabric. The wizard's RDMA check row + and the JACCL-vs-ring backend choice both key off these flags. + """ + + if sys.platform != "darwin": + return + rdma_ctl = "/usr/bin/rdma_ctl" + ibv_devices = "/usr/bin/ibv_devices" + # A supplied runner is an explicit probe seam (used by offline tests and + # embedders); only the production subprocess runner depends on these paths + # existing on the current host. + if runner is subprocess.run and not ( + os.path.exists(rdma_ctl) and os.path.exists(ibv_devices) + ): + return + try: + status = runner( # noqa: S603 - fixed system executable + [rdma_ctl, "status"], + capture_output=True, + text=True, + timeout=5.0, + check=False, + ) + enabled = ( + status.returncode == 0 + and status.stdout.strip().splitlines() + and status.stdout.strip().splitlines()[0].strip().lower() == "enabled" + ) + devices = runner( # noqa: S603 - fixed system executable + [ibv_devices], capture_output=True, text=True, timeout=5.0, check=False + ) + # Same shape as probe.py's _RDMA_DEVICE_RE: device lines are + # whitespace-indented under a two-row header. + rdma_devs = ( + [ + stripped.split()[0] + for line in devices.stdout.splitlines() + if (stripped := line.strip()).startswith("rdma_") + ] + if devices.returncode == 0 + else [] + ) + caps.thunderbolt = bool(rdma_devs) + caps.jaccl = bool(enabled and rdma_devs) + except (OSError, subprocess.SubprocessError): + pass + + +def local_caps() -> PeerCaps: + """Best-effort local capability snapshot; never raises.""" + + caps = PeerCaps() + try: + if sys.platform == "darwin": + chip = subprocess.run( # noqa: S603 - fixed system executable + ["/usr/sbin/sysctl", "-n", "machdep.cpu.brand_string"], + capture_output=True, + text=True, + timeout=2.0, + check=False, + ) + if chip.returncode == 0: + caps.chip = chip.stdout.strip()[:128] + mem = subprocess.run( # noqa: S603 - fixed system executable + ["/usr/sbin/sysctl", "-n", "hw.memsize"], + capture_output=True, + text=True, + timeout=2.0, + check=False, + ) + if mem.returncode == 0: + caps.ram_gb = round(int(mem.stdout.strip()) / (1 << 30), 1) + else: + caps.chip = platform.machine() + with suppress(OSError, ValueError): + caps.ram_gb = round( + os.sysconf("SC_PAGE_SIZE") + * os.sysconf("SC_PHYS_PAGES") + / (1 << 30), + 1, + ) + except (OSError, subprocess.SubprocessError): + pass + _rdma_fabric_caps(caps) + return caps + + +PeerLink = str # "tb" | "ethernet" | "wifi" | "tailscale" | "unknown" +PeerState = str # "discovered" | "suspect" | "dead" + + +@dataclass +class PeerRecord: + node_id: str + friendly_name: str = "" + version: str = "" + cluster_name: str = "" + caps: PeerCaps = field(default_factory=PeerCaps) + addrs: list[dict[str, str]] = field(default_factory=list) + http_port: int = 0 + paired: bool = False + last_seen: float = 0.0 + link: PeerLink = "unknown" + state: PeerState = "discovered" + + def to_dict(self) -> dict[str, Any]: + return { + "node_id": self.node_id, + "friendly_name": self.friendly_name, + "version": self.version, + "cluster_name": self.cluster_name, + "caps": self.caps.to_dict(), + "addrs": [dict(a) for a in self.addrs], + "http_port": self.http_port, + "paired": self.paired, + "last_seen": self.last_seen, + "link": self.link, + "state": self.state, + } + + +@dataclass +class DiscoveryConfig: + cluster_name: str = "omlx" + http_port: int = 8000 + version: str = _omlx_version + caps: PeerCaps = field(default_factory=local_caps) + hello_interval: float = 1.0 + heartbeat_interval: float = 2.0 + probe_interval: float = 10.0 + probe_timeout: float = 3.0 + suspect_after: float = 6.0 + dead_after: float = 30.0 + multicast_window: float = 5.0 + iface_poll_interval: float = 5.0 + tailscale_interval: float = 30.0 + enable_mdns: bool = True + enable_multicast: bool = True + enable_tailscale: bool = True + + +def default_cluster_config_path(base_path: Path | str | None = None) -> Path: + """On-disk location of the persisted cluster config (cluster.json).""" + + if base_path is not None: + base = Path(base_path) + else: + env_value = os.environ.get("OMLX_BASE_PATH") + base = Path(env_value).expanduser() if env_value else Path.home() / ".omlx" + return base / "cluster" / "cluster.json" + + +def load_cluster_name(base_path: Path | str | None = None) -> str: + """Persisted settings-level cluster name, defaulting to ``"omlx"``. + + Read from ``/cluster/cluster.json`` (``{"cluster_name": ...}``). + A missing or malformed file never fails startup — the default keeps the + pre-config behavior, and nodes only discover each other when the names + (and therefore the cluster hashes) match. + """ + + try: + payload = json.loads( + default_cluster_config_path(base_path).read_text(encoding="utf-8") + ) + except (OSError, ValueError): + return DiscoveryConfig.cluster_name + if not isinstance(payload, dict): + return DiscoveryConfig.cluster_name + name = payload.get("cluster_name") + if isinstance(name, str) and name.strip(): + return name.strip() + return DiscoveryConfig.cluster_name + + +def _default_interface_lister() -> list[str]: + """Names of multicast-capable candidate interfaces (never raises).""" + + names: list[str] = [] + if sys.platform == "darwin": + try: + result = subprocess.run( # noqa: S603 - fixed system executable + ["/sbin/ifconfig", "-l"], + capture_output=True, + text=True, + timeout=2.0, + check=False, + ) + if result.returncode == 0: + names = result.stdout.split() + except (OSError, subprocess.SubprocessError): + names = [] + if not names: + with suppress(OSError): + names = [name for _, name in socket.if_nameindex()] + return [n for n in names if not n.startswith("lo")] + + +def local_addr_dicts() -> list[dict[str, str]]: + """Addresses this node considers its own, for the devices ``self`` row. + + Best-effort and never raises. Thunderbolt bridge addresses (typically + the self-assigned 10.0.0.0/24 pair on a direct link) are included so the + UI can show the direct-link path next to LAN and Tailscale ones. + """ + + addrs: list[dict[str, str]] = [] + if sys.platform == "darwin": + try: + result = subprocess.run( # noqa: S603 - fixed system executable + ["/sbin/ifconfig", "-a"], + capture_output=True, + text=True, + timeout=3.0, + check=False, + ) + except (OSError, subprocess.SubprocessError): + result = None + if result is not None and result.returncode == 0: + current: str | None = None + for line in result.stdout.splitlines(): + header = re.match(r"^([a-z0-9]+): ", line) + if header: + current = header.group(1) + continue + if current is None or current.startswith( + ("lo", "awdl", "llw", "anpi", "ap", "gif", "stf") + ): + continue + match = re.match(r"^\s+inet6?\s+(\S+)", line) + if match is None: + continue + ip = match.group(1) + if_type = "vpn" if current.startswith("utun") else "lan" + if ip.startswith("100."): + if_type = "tailscale" + addrs.append({"ip": ip, "if_type": if_type}) + return addrs[:16] + # Portable fallback: primary IPv4 via the routing table (no traffic is + # actually sent to TEST-NET-1). + with suppress(OSError): + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + try: + sock.connect(("192.0.2.1", 80)) + addrs.append({"ip": sock.getsockname()[0], "if_type": "lan"}) + finally: + sock.close() + return addrs + + +def _http_probe_node_id(ip: str, port: int, timeout: float) -> dict[str, Any] | None: + """GET http://ip:port/api/cluster/node_id; ``None`` on any failure.""" + + host = f"[{ip}]" if ":" in ip else ip + url = f"http://{host}:{port}/api/cluster/node_id" + _probe_diagnostics.value = {"transport": "direct", "error": ""} + try: + with urllib.request.urlopen(url, timeout=timeout) as response: # noqa: S310 - cluster LAN probe of an announced address + payload = json.loads(response.read(65536).decode("utf-8")) + except ValueError as exc: + _probe_diagnostics.value = { + "transport": "direct", + "error": f"invalid response: {exc}", + } + return None + except OSError as direct_exc: + # Some macOS installations deny Homebrew Python outbound access to a + # direct Thunderbolt subnet while Apple's system Python can reach the + # same address. Rank control and JACCL bootstrap already use this + # bounded carrier. Reuse it for persisted-pair reboot recovery so a + # verified 10.0.0.x address does not require another manual seed. + try: + is_tailscale = ipaddress.ip_address(ip) in ipaddress.ip_network( + "100.64.0.0/10" + ) + except ValueError: + is_tailscale = False + if is_tailscale: + _probe_diagnostics.value = { + "transport": "direct", + "error": str(direct_exc), + } + return None + try: + payload = _system_proxy_probe_node_id(ip, port, timeout) + except (OSError, RuntimeError, TimeoutError, ValueError) as proxy_exc: + _probe_diagnostics.value = { + "transport": "system-proxy", + "error": f"direct={direct_exc}; proxy={proxy_exc}", + } + return None + if payload is None: + _probe_diagnostics.value = { + "transport": "system-proxy", + "error": f"direct={direct_exc}; proxy returned no identity", + } + return None + _probe_diagnostics.value = {"transport": "system-proxy", "error": ""} + if not isinstance(payload, dict) or not isinstance(payload.get("node_id"), str): + return None + return payload + + +def _system_proxy_probe_node_id( + ip: str, + port: int, + timeout: float, +) -> dict[str, Any] | None: + """Probe one peer through the bounded macOS system-Python carrier.""" + + from .system_socket_proxy import ( + open_system_tcp_proxy, + should_proxy_control_socket, + ) + + if not should_proxy_control_socket(ip): + return None + proxy = open_system_tcp_proxy(ip, port, timeout=timeout) + try: + host = f"[{ip}]" if ":" in ip else ip + request = ( + "GET /api/cluster/node_id HTTP/1.1\r\n" + f"Host: {host}:{port}\r\n" + "Accept: application/json\r\n" + "Connection: close\r\n\r\n" + ).encode("ascii") + proxy.stream.sendall(request) + response = http.client.HTTPResponse(proxy.stream) + response.begin() + if response.status != 200: + return None + payload = json.loads(response.read(65536).decode("utf-8")) + if response.read(1): + return None + return payload if isinstance(payload, dict) else None + finally: + proxy.close() + + +def _classify_link(ip: str, if_type: str, rtt: float | None) -> PeerLink: + """Best-effort link classification. + + Tailscale is certain (100.64.0.0/10); Thunderbolt vs ethernet vs wifi is + an RTT heuristic over the verified address until interface metadata says + otherwise. + """ + + if if_type == "tailscale": + return "tailscale" + with suppress(ValueError): + if ipaddress.ip_address(ip) in ipaddress.ip_network("100.64.0.0/10"): + return "tailscale" + if rtt is None: + return "unknown" + if rtt < 0.001: + return "tb" + if rtt < 0.010: + return "ethernet" + return "wifi" + + +def _load_zeroconf() -> Any | None: + """Import python-zeroconf if installed; ``None`` disables only mDNS.""" + + try: + import zeroconf + except ImportError: + return None + return zeroconf + + +def _tailscale_executable() -> str | None: + """Return the CLI from PATH or the normal signed macOS app bundle.""" + + discovered = shutil.which("tailscale") + if discovered: + return discovered + candidate = Path( + os.environ.get("OMLX_TAILSCALE_CLI", _MACOS_TAILSCALE_CLI) + ).expanduser() + if ( + sys.platform == "darwin" + and candidate.is_file() + and os.access(candidate, os.X_OK) + ): + return str(candidate) + return None + + +class DiscoveryService: + """Always-on peer discovery for cluster v2. + + All network-touching seams are injectable (``socket_factory``, + ``prober``, ``interface_lister``, ``tailscale_status``, + ``zeroconf_module``) so unit tests run fully offline. + """ + + def __init__( + self, + identity: Any, + registry: Any, + config: DiscoveryConfig | None = None, + *, + socket_factory: Callable[[], Any] | None = None, + prober: Callable[[str, int, float], dict[str, Any] | None] | None = None, + clock: Callable[[], float] = time.monotonic, + interface_lister: Callable[[], list[str]] = _default_interface_lister, + tailscale_status: Callable[[], dict[str, Any] | None] | None = None, + zeroconf_module: Any = "auto", + ) -> None: + self.identity = identity + self.registry = registry + self.config = config or DiscoveryConfig() + self._clock = clock + self._prober = prober or _http_probe_node_id + self._socket_factory = socket_factory or self._open_multicast_socket + self._interface_lister = interface_lister + self._tailscale_status = tailscale_status or self._read_tailscale_status + if zeroconf_module == "auto": + self._zc = _load_zeroconf() if self.config.enable_mdns else None + else: + self._zc = zeroconf_module or None + + self._cluster_hash = cluster_hash_u64(self.config.cluster_name) + self._peers: dict[str, PeerRecord] = {} + # (ip, port) -> {node_id hint, if_type, last_probe, rtt, verified} + self._candidates: dict[tuple[str, int], dict[str, Any]] = {} + self._nonces: deque[int] = deque(maxlen=_RECENT_NONCES) + self._callbacks: list[Callable[[PeerRecord], None]] = [] + self._hash_mismatch_logged = False + self._last_hello_at: float | None = None + self._last_hello_wall: float | None = None + self._lock = threading.RLock() + self._stop = threading.Event() + self._threads: list[threading.Thread] = [] + self._socket: Any | None = None + self._joined: dict[str, int] = {} # ifname -> ifindex + self._tx_fail_logged_at: dict[int, float] = {} # ifindex -> monotonic + self._reply_fail_logged_at: dict[str, float] = {} # peer_ip -> monotonic + self._consecutive_tx_fail_rounds = 0 + self._last_tx_ok_wall: float | None = None + self._last_tx_error: str | None = None + self._needs_socket_reset = False + self._consecutive_socket_resets = 0 + self._last_socket_reset_at = 0.0 + self._local_network_blocked_suspected = False + self._zc_instance: Any | None = None + self._zc_browser: Any | None = None + self._zc_info: Any | None = None + self._rehydrate_paired_candidates() + + # -- public API ---------------------------------------------------------- + + @property + def mdns_available(self) -> bool: + return self._zc is not None + + @property + def multicast_ok(self) -> bool: + """True when a foreign HELLO arrived within the multicast window. + + The UI uses this to warn about macOS Local Network permission + denial: discovery silently finds nothing when the OS blocks us. + """ + + last = self._last_hello_at + return ( + last is not None and (self._clock() - last) < self.config.multicast_window + ) + + @property + def last_multicast_rx_at(self) -> float | None: + """Wall-clock time of the last foreign HELLO, or None if never.""" + + return self._last_hello_wall + + @property + def mdns_active(self) -> bool: + """True when our mDNS service announcement is actually registered.""" + + return self._zc_info is not None + + def transport_summary(self) -> str: + """Active discovery transports, e.g. ``"mdns+multicast"``.""" + + parts: list[str] = [] + if self.mdns_active: + parts.append("mdns") + if self.config.enable_multicast: + parts.append("multicast") + return "+".join(parts) if parts else "none" + + def peers(self) -> list[PeerRecord]: + with self._lock: + return [self._peers[key] for key in sorted(self._peers)] + + def mark_paired(self, node_id: str) -> None: + """Immediately suppress an approved peer from unpaired discovery.""" + + with self._lock: + peer = self._peers.get(node_id) + if peer is not None: + peer.paired = True + + def health(self) -> dict[str, Any]: + """Extended self-diagnostics for the discovery health detail route. + + The base health endpoint only reports inbound multicast state; when + discovery silently dies (a crashed loop thread, a wedged socket, + interfaces renumbered by Thunderbolt hotplug) these fields are how + the UI and field debugging tell those apart from "no peers nearby". + """ + + with self._lock: + threads = {t.name: t.is_alive() for t in self._threads} + joined = sorted(self._joined) + candidate_states = [ + { + "ip": ip, + "port": port, + "node_id": value.get("node_id"), + "if_type": value.get("if_type"), + "verified": bool(value.get("verified", False)), + "last_transport": value.get("last_transport"), + "last_error": str(value.get("last_error") or "")[:1000], + } + for (ip, port), value in sorted(self._candidates.items()) + ] + return { + "multicast_loop_alive": threads.get("omlx-discovery-mcast", False), + "maintenance_loop_alive": threads.get("omlx-discovery-maint", False), + "socket_open": self._socket is not None, + "joined_interfaces": joined, + "last_hello_tx_ok_at": self._last_tx_ok_wall, + "last_hello_tx_error": self._last_tx_error, + "consecutive_tx_fail_rounds": self._consecutive_tx_fail_rounds, + "socket_resets": self._consecutive_socket_resets, + "local_network_blocked_suspected": (self._local_network_blocked_suspected), + "candidates": len(self._candidates), + "candidate_states": candidate_states, + "peers": len(self._peers), + } + + def on_change(self, callback: Callable[[PeerRecord], None]) -> None: + with self._lock: + self._callbacks.append(callback) + + def add_manual(self, ip: str, port: int) -> None: + """Manually added peer candidate; verified via the same probe path.""" + + self._add_candidate(str(ip), int(port), node_id=None, if_type="manual") + # Probe on the next maintenance tick; tests may call probe_now(). + + def _rehydrate_paired_candidates(self) -> None: + """Seed probes from trusted addresses that survived a server restart. + + Discovery announcements are deliberately best-effort on macOS. A peer + that was manually added over a direct Thunderbolt address must remain + reachable when multicast is blocked, so paired registry rows retain the + verified address and HTTP port. Unpaired discoveries are never read here + because the registry keeps them memory-only. + """ + + paired = getattr(self.registry, "paired", None) + if not callable(paired): + return + try: + records = paired() + except Exception: + logger.debug("paired discovery seeds could not be read", exc_info=True) + return + for record in records: + if not isinstance(record, dict): + continue + node_id = record.get("node_id") + # Schema-v1 rows written before endpoint persistence have no port. + # oMLX nodes conventionally share the configured server port (the + # same documented heuristic as Tailscale discovery); a successful + # probe writes the exact value back for subsequent restarts. + port = record.get("http_port") or self.config.http_port + if ( + not isinstance(node_id, str) + or not node_id + or not isinstance(port, int) + or isinstance(port, bool) + or not 1 <= port <= 65535 + ): + continue + for raw_ip in record.get("last_addrs") or (): + if not isinstance(raw_ip, str): + continue + try: + # Scope identifiers are process/interface-local and cannot + # safely survive a reboot. Retain the address itself; a + # routable/manual IPv4 remains the deterministic path. + parsed = ipaddress.ip_address(raw_ip.split("%", 1)[0]) + except ValueError: + continue + # A persisted IPv6 scope identifier cannot be trusted after + # interface renumbering, and link-local IPv6 without a scope is + # not dialable. Multicast can rediscover it with a fresh scope; + # deterministic reboot recovery uses the routable/manual path. + if parsed.version == 6 and parsed.is_link_local: + continue + ip = str(parsed) + self._add_candidate( + ip, + port, + node_id=node_id, + if_type="paired", + ) + + def start(self) -> None: + with self._lock: + if self._threads: + return + self._stop.clear() + if self.config.enable_multicast: + self._spawn(self._multicast_loop, "omlx-discovery-mcast") + self._spawn(self._maintenance_loop, "omlx-discovery-maint") + if self._zc is not None: + try: + self._start_mdns() + except Exception as exc: # mDNS must never kill the process + logger.warning("mDNS announce/browse disabled: %s", exc) + self._zc_instance = None + + def stop(self) -> None: + self._stop.set() + for thread in list(self._threads): + thread.join(timeout=2.0) + self._threads = [] + with suppress(Exception): + if self._socket is not None: + self._socket.close() + self._socket = None + with suppress(Exception): + if self._zc_instance is not None: + if self._zc_info is not None: + self._zc_instance.unregister_service(self._zc_info) + if self._zc_browser is not None: + self._zc_browser.cancel() + self._zc_instance.close() + self._zc_instance = self._zc_browser = self._zc_info = None + + def probe_now(self) -> None: + """Run one probe sweep synchronously (maintenance loop does this).""" + + self._probe_sweep() + + def probe_candidate_now(self, ip: str, port: int) -> None: + """Probe one explicit candidate now, bypassing periodic dedupe.""" + + self._probe_candidate(str(ip), int(port)) + + def tick_liveness(self) -> None: + """Evaluate suspect/dead transitions synchronously (loop does this).""" + + self._liveness_sweep() + + # -- internals ----------------------------------------------------------- + + def _spawn(self, target: Callable[[], None], name: str) -> None: + def _supervised() -> None: + while not self._stop.is_set(): + try: + target() + except BaseException: + if self._stop.is_set(): + return + # A daemon thread dying silently is how discovery goes + # dark without a trace; log loudly and restart instead. + logger.critical( + "discovery thread %s crashed; restarting in 2s", + name, + exc_info=True, + ) + self._stop.wait(2.0) + continue + if self._stop.is_set(): + return + # Clean return without a stop request is also a bug — + # discovery is always-on. Restart rather than going dark. + logger.warning( + "discovery thread %s exited unexpectedly; restarting in 2s", + name, + ) + self._stop.wait(2.0) + + thread = threading.Thread(target=_supervised, name=name, daemon=True) + self._threads.append(thread) + thread.start() + + def _fire_change(self, peer: PeerRecord) -> None: + with self._lock: + callbacks = list(self._callbacks) + for callback in callbacks: + try: + callback(peer) + except Exception: # a UI callback must never kill discovery + logger.exception("discovery on_change callback failed") + + def _open_multicast_socket(self) -> Any: + sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + sock.bind(("::", MULTICAST_PORT)) + sock.settimeout(0.25) + return sock + + def _sync_interfaces(self, sock: Any) -> None: + """Join the multicast group on every multicast-capable interface. + + Thunderbolt bridges appear/disappear with cable state (macOS gotcha + #4), so this is re-run periodically. macOS also *renumbers* + interfaces on Thunderbolt hotplug (gotcha #5): a cached ifindex then + silently points at the wrong interface and every send fails with + EHOSTUNREACH, so stale or renumbered entries are dropped here and + re-joined below. + """ + + try: + names = self._interface_lister() + except Exception: + return + current = set(names) + for name, ifindex in list(self._joined.items()): + if name not in current: + # Interface vanished; its group membership dies with it. + self._joined.pop(name, None) + continue + try: + now_index = socket.if_nametoindex(name) + except OSError: + self._joined.pop(name, None) + continue + if now_index != ifindex: + logger.info( + "interface %s renumbered (%d -> %d); re-joining multicast group", + name, + ifindex, + now_index, + ) + self._joined.pop(name, None) + for name in names: + if name in self._joined: + continue + try: + ifindex = socket.if_nametoindex(name) + except OSError: + continue + membership = socket.inet_pton( + socket.AF_INET6, MULTICAST_GROUP + ) + struct.pack("@I", ifindex) + try: + sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, membership) + except OSError as exc: + if exc.errno not in _JOIN_IGNORED_ERRNOS: + logger.debug("multicast join on %s failed: %s", name, exc) + continue + self._joined[name] = ifindex + + def _multicast_loop(self) -> None: + try: + sock = self._socket_factory() + except OSError as exc: + logger.warning("cluster multicast discovery unavailable: %s", exc) + return + self._socket = sock + last_hello = 0.0 + last_ifaces = 0.0 + last_reset_warn = 0.0 + try: + while not self._stop.is_set(): + if self._needs_socket_reset: + # Exponential backoff: a process-level wedge (e.g. a + # denied macOS Local Network permission) survives socket + # rebuilds, so rebuilding every second just spams the + # log and burns CPU. Back off to at most one rebuild + # per 60s; the first success resets the schedule. + now_mono = time.monotonic() + backoff = min(2.0**self._consecutive_socket_resets, 60.0) + if now_mono - self._last_socket_reset_at < backoff: + self._stop.wait(1.0) + continue + self._needs_socket_reset = False + self._last_socket_reset_at = now_mono + self._consecutive_socket_resets += 1 + with suppress(Exception): + sock.close() + with self._lock: + self._joined.clear() + try: + sock = self._socket_factory() + except OSError as exc: + now_wall = time.monotonic() + if now_wall - last_reset_warn >= 60.0: + last_reset_warn = now_wall + logger.warning( + "multicast socket rebuild failed: %s; retrying", + exc, + ) + self._needs_socket_reset = True + self._stop.wait(1.0) + continue + self._socket = sock + last_ifaces = 0.0 # force an immediate re-join pass + if self._consecutive_socket_resets == 6: + self._local_network_blocked_suspected = True + logger.critical( + "cluster multicast still dead after %d socket " + "rebuilds — on macOS this is usually a denied " + "Local Network permission (System Settings → " + "Privacy & Security → Local Network) or a wedged " + "process (a server restart clears it); peers can " + "always be added manually via POST " + "/api/cluster/devices/manual", + self._consecutive_socket_resets, + ) + now = self._clock() + if now - last_ifaces >= self.config.iface_poll_interval: + self._sync_interfaces(sock) + last_ifaces = now + if now - last_hello >= self.config.hello_interval: + self._send_hello(sock) + last_hello = now + try: + data, addr = sock.recvfrom(_MAX_DATAGRAM) + except TimeoutError: + continue + except OSError: + if self._stop.is_set(): + break + continue + try: + self._handle_datagram(data, addr, sock) + except Exception: + # A malformed datagram or a handler bug must never kill + # the loop (and with it, all discovery). + logger.exception("discovery datagram handler failed") + finally: + with suppress(Exception): + sock.close() + if self._socket is sock: + self._socket = None + with self._lock: + self._joined.clear() + + def _send_hello(self, sock: Any) -> None: + nonce = secrets.randbits(64) + with self._lock: + self._nonces.append(nonce) + payload = encode_hello(nonce, self._cluster_hash) + with self._lock: + joined = list(self._joined.values()) or [0] + any_ok = False + last_error: str | None = None + now = self._clock() + for ifindex in joined: + # Link-scope multicast needs the egress interface in the + # destination's scope id. (The previous design set + # IPV6_MULTICAST_IF on the shared socket per round instead; that + # state goes stale when macOS renumbers interfaces on + # Thunderbolt hotplug and every send then fails EHOSTUNREACH.) + target = ( + (MULTICAST_GROUP, MULTICAST_PORT, 0, ifindex) + if ifindex + else (MULTICAST_GROUP, MULTICAST_PORT) + ) + try: + sock.sendto(payload, target) + any_ok = True + except OSError as exc: + last_error = f"if {ifindex}: {exc}" + if exc.errno not in _JOIN_IGNORED_ERRNOS and ( + now - self._tx_fail_logged_at.get(ifindex, 0.0) + >= _TX_FAIL_LOG_INTERVAL + ): + self._tx_fail_logged_at[ifindex] = now + logger.debug("HELLO send on if %d failed: %s", ifindex, exc) + if any_ok: + self._consecutive_tx_fail_rounds = 0 + self._consecutive_socket_resets = 0 + self._local_network_blocked_suspected = False + self._last_tx_ok_wall = time.time() + self._last_tx_error = None + else: + self._consecutive_tx_fail_rounds += 1 + self._last_tx_error = last_error + if self._consecutive_tx_fail_rounds >= _TX_FAIL_RESET_ROUNDS and any( + joined + ): + if self._consecutive_tx_fail_rounds == _TX_FAIL_RESET_ROUNDS: + # Log once per failure streak; the loop's backoff + # schedule paces the actual rebuilds from here. + logger.warning( + "HELLO sends failed on every joined interface for " + "%d rounds; scheduling multicast socket rebuild", + self._consecutive_tx_fail_rounds, + ) + self._needs_socket_reset = True + + def _handle_datagram(self, data: bytes, addr: Any, sock: Any = None) -> None: + hello = decode_hello(data) + if hello is not None: + self._handle_hello(hello[0], hello[1], addr, sock) + return + wassup = decode_wassup(data) + if wassup is not None: + self._handle_wassup(wassup, addr) + + def _handle_hello( + self, nonce: int, cluster_hash: int, addr: Any, sock: Any = None + ) -> None: + if cluster_hash != self._cluster_hash: + # A foreign oMLX cluster shares the LAN; ignore silently for + # discovery but make the situation diagnosable (once). + if not self._hash_mismatch_logged: + self._hash_mismatch_logged = True + logger.info( + "Ignoring cluster HELLO with a non-matching cluster hash " + "(another oMLX cluster on this LAN?)" + ) + return + with self._lock: + if nonce in self._nonces: + return # nonce-echo self-drop: our own HELLO came back + self._last_hello_at = self._clock() + self._last_hello_wall = time.time() + # Inbound multicast works, so any Local Network permission wedge is + # definitively over. + self._local_network_blocked_suspected = False + if isinstance(addr, tuple): + peer_ip = addr[0] + peer_port = addr[1] + scope_id = addr[3] if len(addr) > 3 else 0 + else: + peer_ip, peer_port, scope_id = str(addr), MULTICAST_PORT, 0 + # Answer unicast so the sender learns our node_id + http_port. A + # link-local HELLO source requires the ingress interface as scope id + # in the reply destination; without it the kernel has no route and + # the handshake silently never completes. + reply = encode_wassup(nonce, self.identity.node_id, self.config.http_port) + target_sock = sock if sock is not None else self._socket + if target_sock is not None: + target = ( + (peer_ip, peer_port, 0, scope_id) if scope_id else (peer_ip, peer_port) + ) + try: + target_sock.sendto(reply, target) + except OSError as exc: + now = self._clock() + if ( + now - self._reply_fail_logged_at.get(peer_ip, 0.0) + >= _TX_FAIL_LOG_INTERVAL + ): + self._reply_fail_logged_at[peer_ip] = now + logger.debug("WASSUP reply to %s failed: %s", peer_ip, exc) + + def _handle_wassup(self, payload: dict[str, Any], addr: Any) -> None: + with self._lock: + if payload["nonce"] not in self._nonces: + return # not an echo of a nonce we issued + node_id = payload["node_id"] + if node_id == self.identity.node_id: + return + peer_ip = addr[0] if isinstance(addr, tuple) else str(addr) + if "%" in peer_ip: + peer_ip = peer_ip.split("%", 1)[0] + now = self._clock() + with self._lock: + peer = self._peers.get(node_id) + is_new = peer is None + if peer is None: + peer = PeerRecord(node_id=node_id) + self._peers[node_id] = peer + peer.http_port = payload["http_port"] + peer.last_seen = now + if peer.state == "dead": + peer.state = "discovered" + if not any(a["ip"] == peer_ip for a in peer.addrs): + peer.addrs.append({"ip": peer_ip, "if_type": "unknown"}) + peer.addrs = peer.addrs[-8:] + self._merge_registry(peer) + self._add_candidate( + peer_ip, payload["http_port"], node_id=node_id, if_type="unknown" + ) + if is_new: + self._fire_change(peer) + # Higher node_id (string compare) initiates contact: the higher node + # probes immediately; the lower node's next periodic probe sweep + # verifies its own candidate entry. + if self.identity.node_id > node_id: + self._probe_candidate(peer_ip, payload["http_port"]) + + def _add_candidate( + self, ip: str, port: int, *, node_id: str | None, if_type: str + ) -> None: + with self._lock: + if len(self._candidates) >= _MAX_CANDIDATES: + return + key = (ip, port) + candidate = self._candidates.get(key) + if candidate is None: + candidate = { + "node_id": node_id, + "if_type": if_type, + # Due immediately even when oMLX starts within the first + # few seconds after boot and the monotonic clock is < the + # normal probe interval. + "last_probe": float("-inf"), + "rtt": None, + "verified": False, + } + self._candidates[key] = candidate + else: + if node_id: + candidate["node_id"] = node_id + if if_type != "unknown": + candidate["if_type"] = if_type + + def _probe_sweep(self) -> None: + now = self._clock() + with self._lock: + due = [ + (ip, port) + for (ip, port), candidate in self._candidates.items() + if now - candidate["last_probe"] + >= ( + self.config.heartbeat_interval + if candidate.get("verified") + else self.config.probe_interval + ) + ] + due.sort( + key=lambda key: ( + not bool(self._candidates[key].get("verified")), + self._candidates[key].get("node_id") is None, + self._candidates[key].get("if_type") != "paired", + ) + ) + for ip, port in due: + self._probe_candidate(ip, port) + + def _probe_candidate(self, ip: str, port: int) -> None: + with self._lock: + candidate = self._candidates.get((ip, port)) + if candidate is None: + return + candidate["last_probe"] = self._clock() + hint = candidate["node_id"] + if_type = candidate["if_type"] + started = self._clock() + _probe_diagnostics.value = None + try: + result = self._prober(ip, port, self.config.probe_timeout) + except Exception as exc: + result = None + diagnostic = { + "transport": "custom", + "error": str(exc), + } + else: + diagnostic = getattr(_probe_diagnostics, "value", None) or { + "transport": "custom", + "error": "" if result is not None else "probe returned no identity", + } + rtt = self._clock() - started + if result is None: + with self._lock: + candidate = self._candidates.get((ip, port)) + if candidate is not None: + candidate["last_transport"] = diagnostic.get("transport") + candidate["last_error"] = diagnostic.get("error") + return + node_id = result.get("node_id") + if hint is not None and node_id != hint: + # Announced address does not answer with the announced node_id — + # drop it (stale DHCP lease, spoofed announcement, etc.). + with self._lock: + self._candidates.pop((ip, port), None) + peer = self._peers.get(hint) + if peer is not None: + peer.addrs = [a for a in peer.addrs if a["ip"] != ip] + return + now = self._clock() + with self._lock: + candidate = self._candidates.get((ip, port)) + if candidate is not None: + candidate["verified"] = True + candidate["rtt"] = rtt + candidate["node_id"] = node_id + candidate["last_transport"] = diagnostic.get("transport") + candidate["last_error"] = "" + peer = self._peers.get(node_id) + is_new = peer is None + if peer is None: + peer = PeerRecord(node_id=node_id) + self._peers[node_id] = peer + peer.version = str(result.get("version") or peer.version) + peer.cluster_name = str(result.get("cluster_name") or peer.cluster_name) + if result.get("friendly_name"): + peer.friendly_name = str(result["friendly_name"]) + peer.http_port = port + peer.last_seen = now + if not any(a["ip"] == ip for a in peer.addrs): + peer.addrs.append({"ip": ip, "if_type": if_type}) + peer.addrs = peer.addrs[-8:] + peer.link = _classify_link(ip, if_type, rtt) + self._merge_registry(peer) + if is_new: + self._fire_change(peer) + + def _merge_registry(self, peer: PeerRecord) -> None: + if self.registry is None: + return + try: + self.registry.merge( + { + "node_id": peer.node_id, + "friendly_name": peer.friendly_name, + "caps": peer.caps.to_dict(), + "addrs": peer.addrs, + "http_port": peer.http_port, + } + ) + with self._lock: + peer.paired = bool(self.registry.is_paired(peer.node_id)) + except Exception: + logger.debug("device registry merge failed", exc_info=True) + + def _liveness_sweep(self) -> None: + now = self._clock() + transitions: list[PeerRecord] = [] + with self._lock: + for peer in self._peers.values(): + silence = now - peer.last_seen + if silence >= self.config.dead_after: + target = "dead" + elif silence >= self.config.suspect_after: + target = "suspect" + else: + target = "discovered" + if peer.state != target: + peer.state = target + transitions.append(peer) + for peer in transitions: + self._fire_change(peer) + + def _maintenance_loop(self) -> None: + last_probe = 0.0 + last_tailscale = 0.0 + sweep_interval = min( + self.config.probe_interval, + self.config.heartbeat_interval, + ) + while not self._stop.is_set(): + now = self._clock() + if now - last_probe >= sweep_interval: + self._probe_sweep() + last_probe = now + self._liveness_sweep() + if ( + self.config.enable_tailscale + and now - last_tailscale >= self.config.tailscale_interval + ): + self._tailscale_sweep() + last_tailscale = now + self._stop.wait(0.5) + + # -- Tailscale (opportunistic, never required) --------------------------- + + @staticmethod + def _read_tailscale_status() -> dict[str, Any] | None: + executable = _tailscale_executable() + if executable is None: + return None + try: + result = subprocess.run( # noqa: S603 - tailscale CLI lookup + [executable, "status", "--json"], + capture_output=True, + text=True, + timeout=5.0, + check=False, + ) + except (OSError, subprocess.SubprocessError): + return None + if result.returncode != 0: + return None + try: + payload = json.loads(result.stdout) + except json.JSONDecodeError: + return None + return payload if isinstance(payload, dict) else None + + def _tailscale_sweep(self) -> None: + try: + status = self._tailscale_status() + except Exception: + return + if not status: + return + peers = status.get("Peer") + if not isinstance(peers, dict): + return + for entry in peers.values(): + if not isinstance(entry, dict): + continue + if entry.get("Online") is False: + continue + ips = entry.get("TailscaleIPs") + if not isinstance(ips, list): + continue + for ip in ips: + if isinstance(ip, str) and ip.startswith("100."): + # Peer's oMLX port is unknown; our own configured port is + # the best heuristic (documented — Tailscale is + # opportunistic, never required). + self._add_candidate( + ip, + self.config.http_port, + node_id=None, + if_type="tailscale", + ) + + # -- mDNS (python-zeroconf, optional) ------------------------------------ + + def _start_mdns(self) -> None: + zc = self._zc + addresses = self._local_addresses() + caps_json = json.dumps(self.config.caps.to_dict(), separators=(",", ":")) + properties = { + "id": self.identity.node_id, + "name": self.identity.friendly_name, + "ver": self.config.version, + "cl": self.config.cluster_name, + "caps": caps_json, + "port": str(self.config.http_port), + } + instance = f"{self.identity.friendly_name}.{MDNS_SERVICE_TYPE}"[:255] + info = zc.ServiceInfo( + MDNS_SERVICE_TYPE, + instance, + addresses=addresses, + port=self.config.http_port, + properties=properties, + ) + self._zc_instance = zc.Zeroconf() + self._zc_info = info + listener = _MdnsListener(self) + self._zc_browser = zc.ServiceBrowser( + self._zc_instance, MDNS_SERVICE_TYPE, listener + ) + self._zc_instance.register_service(info) + + @staticmethod + def _local_addresses() -> list[bytes]: + packed: list[bytes] = [] + with suppress(OSError): + hostname = socket.gethostname() + for family, _, _, _, sockaddr in socket.getaddrinfo(hostname, None): + if family == socket.AF_INET: + packed.append(socket.inet_pton(family, sockaddr[0])) + elif family == socket.AF_INET6 and not sockaddr[0].startswith( + "fe80::1" # skip loopback-ish + ): + packed.append( + socket.inet_pton(family, sockaddr[0].split("%", 1)[0]) + ) + return packed[:8] + + def _handle_mdns_service(self, info: Any) -> None: + """Process one resolved _omlx._tcp service (zeroconf callback path).""" + + try: + props = { + (k.decode("utf-8", "replace") if isinstance(k, bytes) else k): ( + v.decode("utf-8", "replace") if isinstance(v, bytes) else v + ) + for k, v in (info.properties or {}).items() + } + node_id = str(props.get("id") or "") + if not node_id or node_id == self.identity.node_id: + return + cluster = str(props.get("cl") or "") + if cluster != self.config.cluster_name: + if not self._hash_mismatch_logged: + self._hash_mismatch_logged = True + logger.info( + "Ignoring mDNS service for a different oMLX cluster (%r != %r)", + cluster, + self.config.cluster_name, + ) + return + try: + caps = PeerCaps.from_dict(json.loads(props.get("caps") or "{}")) + except json.JSONDecodeError: + caps = PeerCaps() + port = int(getattr(info, "port", 0) or 0) + addresses: list[str] = [] + parsed = getattr(info, "parsed_addresses", None) + if callable(parsed): + addresses = [a for a in parsed() if isinstance(a, str)] + now = self._clock() + with self._lock: + peer = self._peers.get(node_id) + is_new = peer is None + if peer is None: + peer = PeerRecord(node_id=node_id) + self._peers[node_id] = peer + peer.friendly_name = str(props.get("name") or peer.friendly_name) + peer.version = str(props.get("ver") or peer.version) + peer.cluster_name = cluster + peer.caps = caps + if port: + peer.http_port = port + peer.last_seen = now + for ip in addresses: + if not any(a["ip"] == ip for a in peer.addrs): + peer.addrs.append({"ip": ip, "if_type": "mdns"}) + peer.addrs = peer.addrs[-8:] + self._merge_registry(peer) + if port: + for ip in addresses: + self._add_candidate(ip, port, node_id=node_id, if_type="mdns") + if is_new: + self._fire_change(peer) + except Exception: + # mDNS callbacks run on zeroconf threads; nothing here may kill + # the process (macOS gotcha #3). + logger.exception("failed to process mDNS service") + + +class _MdnsListener: + """zeroconf ServiceListener adapter; every callback is exception-safe.""" + + def __init__(self, service: DiscoveryService) -> None: + self._service = service + + def _resolve(self, zc: Any, type_: str, name: str) -> None: + try: + info = zc.get_service_info(type_, name, timeout=3000) + except Exception: + return + if info is not None: + self._service._handle_mdns_service(info) + + # zeroconf >= 0.28 style + def add_service(self, zc: Any, type_: str, name: str) -> None: + self._resolve(zc, type_, name) + + def update_service(self, zc: Any, type_: str, name: str) -> None: + self._resolve(zc, type_, name) + + def remove_service(self, zc: Any, type_: str, name: str) -> None: + pass + + # older zeroconf style + def update_service_callback(self, *args: Any, **kwargs: Any) -> None: + pass + + +_discovery_service_lock = threading.Lock() +_configured_discovery_service: DiscoveryService | None = None + + +def configure_discovery_service( + service: DiscoveryService | None, +) -> DiscoveryService | None: + """Set (or clear) the process-wide discovery service for the endpoints.""" + + global _configured_discovery_service + with _discovery_service_lock: + _configured_discovery_service = service + return _configured_discovery_service + + +def get_discovery_service() -> DiscoveryService: + with _discovery_service_lock: + if _configured_discovery_service is None: + raise RuntimeError("cluster discovery service is not configured") + return _configured_discovery_service + + +def announced_caps() -> dict[str, Any]: + """Return the same best-effort capabilities advertised by discovery.""" + + try: + service = get_discovery_service() + except RuntimeError: + service = None + if service is not None: + try: + caps = service.config.caps.to_dict() + except Exception: # pragma: no cover - defensive + caps = {} + if caps: + return caps + try: + return local_caps().to_dict() + except Exception: # pragma: no cover - defensive + return {} + + +def announced_addrs() -> list[str]: + """Validated local addresses included in an approved pairing record.""" + + return [ + str(address["ip"]) + for address in local_addr_dicts() + if isinstance(address, dict) and address.get("ip") + ][:8] diff --git a/omlx/cluster/discovery_routes.py b/omlx/cluster/discovery_routes.py new file mode 100644 index 0000000000..3f6706d698 --- /dev/null +++ b/omlx/cluster/discovery_routes.py @@ -0,0 +1,393 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Cluster v2 discovery/identity HTTP endpoints. + +``discovery_router`` is mounted WITHOUT ``require_admin`` in +``omlx/server.py`` so peers can probe ``/api/cluster/node_id`` before any +trust exists; it is still gated by the distributed-inference exposure flag +(``require_distributed_inference_enabled``) like the enrollment router. The +probe endpoint is rate-limited per source IP. ``/api/cluster/devices`` +carries the trusted inventory and requires admin like the rest of the +cluster surface. +""" + +from __future__ import annotations + +import asyncio +import ipaddress +import threading +import time +from typing import Any + +from fastapi import APIRouter, Depends, HTTPException, Request + +from .._version import __version__ +from ..admin.auth import require_admin +from .discovery import local_addr_dicts +from .identity import get_node_identity +from .registry import get_device_registry + +discovery_router = APIRouter(prefix="/api/cluster", tags=["cluster-discovery"]) + + +class ProbeRateLimiter: + """Token-bucket rate limiter for the unauthenticated probe endpoint.""" + + def __init__(self, rate_per_second: float = 5.0, burst: int = 10) -> None: + self._rate = float(rate_per_second) + self._burst = int(burst) + self._buckets: dict[str, tuple[float, float]] = {} + self._lock = threading.Lock() + + def allow(self, key: str, now: float | None = None) -> bool: + now = time.monotonic() if now is None else now + with self._lock: + tokens, updated = self._buckets.get(key, (float(self._burst), now)) + tokens = min(float(self._burst), tokens + (now - updated) * self._rate) + if tokens < 1.0: + self._buckets[key] = (tokens, now) + return False + self._buckets[key] = (tokens - 1.0, now) + # Bound the map: drop idle buckets once it grows past 4096 keys. + if len(self._buckets) > 4096: + self._buckets = { + k: v for k, v in self._buckets.items() if now - v[1] < 600.0 + } + return True + + +probe_rate_limiter = ProbeRateLimiter() + + +def discovery_service_or_none(): + from .discovery import get_discovery_service + + try: + return get_discovery_service() + except RuntimeError: + return None + + +def _cluster_name() -> str: + service = discovery_service_or_none() + if service is not None: + return service.config.cluster_name + # Discovery disabled still reports the persisted settings-level name. + from .discovery import load_cluster_name + + return load_cluster_name() + + +@discovery_router.get("/node_id") +async def cluster_node_id_probe(request: Request): + """Public, rate-limited identity probe used by peer verification. + + Deliberately unauthenticated: a discovering node must be able to confirm + an announced address belongs to the announced node_id before any pairing + trust exists. It reveals only the stable node_id, the oMLX version, and + the cluster name — no capabilities, no device inventory. + """ + + client = request.client.host if request.client else "unknown" + if not probe_rate_limiter.allow(client): + raise HTTPException( + status_code=429, + detail="probe rate limit exceeded", + headers={"Retry-After": "1"}, + ) + try: + identity = get_node_identity() + except RuntimeError as exc: + raise HTTPException( + status_code=503, detail="cluster identity is not configured" + ) from exc + return { + "node_id": identity.node_id, + "version": __version__, + "cluster_name": _cluster_name(), + } + + +@discovery_router.get("/discovery/health") +async def cluster_discovery_health(is_admin: bool = Depends(require_admin)): + """Local-network self-test for the wizard's checks row. + + ``multicast_rx_within_5s`` is False when no foreign HELLO arrived in the + last five seconds — on macOS that is how a denied Local Network + permission presents, so the UI pairs it with actionable guidance instead + of a silently empty device list. Shape is pinned by the wizard fixture + (tests/ui/fixtures/cluster_v2/discovery_health_ok.json). + """ + + service = discovery_service_or_none() + if service is None: + return { + "multicast_rx_within_5s": False, + "last_multicast_rx_at": None, + "mdns_active": False, + "transport": "disabled", + } + return { + "multicast_rx_within_5s": bool(service.multicast_ok), + "last_multicast_rx_at": service.last_multicast_rx_at, + "mdns_active": bool(service.mdns_active), + "transport": service.transport_summary(), + } + + +@discovery_router.get("/discovery/health/detail") +async def cluster_discovery_health_detail( + is_admin: bool = Depends(require_admin), +): + """Extended discovery self-diagnostics (loop liveness, TX health). + + Separate route so the pinned wizard fixture shape on + ``/discovery/health`` stays untouched. This is how "no peers nearby" is + distinguished from "discovery loop dead / socket wedged / interface + renumbered underneath us" in the field. + """ + + service = discovery_service_or_none() + if service is None: + raise HTTPException(status_code=503, detail="discovery is disabled") + return service.health() + + +@discovery_router.post("/devices/manual") +async def cluster_add_manual_peer( + request: Request, is_admin: bool = Depends(require_admin) +): + """Manually add a peer by IP — the deterministic path over Thunderbolt. + + Multicast is best-effort on macOS (Local Network permission, interface + renumbering, routers that filter v6 multicast). When two machines share + a direct Thunderbolt link, pointing each node at the other's link + address (typically the 10.0.0.x pair) skips all of that. The candidate + is verified through the same HTTP probe path as multicast-discovered + peers before it is returned as verified. + """ + + service = discovery_service_or_none() + if service is None: + raise HTTPException(status_code=503, detail="discovery is disabled") + client = request.client.host if request.client else "unknown" + if not probe_rate_limiter.allow(client): + raise HTTPException( + status_code=429, + detail="probe rate limit exceeded", + headers={"Retry-After": "1"}, + ) + try: + body = await request.json() + except ValueError as exc: + raise HTTPException(status_code=400, detail="invalid JSON body") from exc + if not isinstance(body, dict): + raise HTTPException(status_code=400, detail="invalid JSON body") + raw_ip = body.get("ip") + try: + ip = str(ipaddress.ip_address(str(raw_ip))) + except ValueError as exc: + raise HTTPException( + status_code=400, detail=f"invalid IP address: {raw_ip!r}" + ) from exc + port = body.get("port", 8000) + if not isinstance(port, int) or isinstance(port, bool) or not (1 <= port <= 65535): + raise HTTPException(status_code=400, detail="invalid port") + service.add_manual(ip, port) + # Probe synchronously (bounded by the configured probe timeout) so the + # caller learns immediately whether the address answers as an oMLX node. + await asyncio.to_thread(service.probe_candidate_now, ip, port) + peer = next( + (p for p in service.peers() if any(a["ip"] == ip for a in p.addrs)), + None, + ) + return { + "ok": True, + "ip": ip, + "port": port, + "verified": peer is not None, + "peer": peer.to_dict() if peer is not None else None, + } + + +def _enrich_paired_row(row: dict[str, Any], record: dict[str, Any] | None) -> None: + """Fill gaps on a paired row from the matching discovery record. + + Pairings completed before capabilities were exchanged persisted empty + ``caps``; the matching registry/service record carries the announced + values. Only fields actually known are merged — nothing is fabricated — + and the persisted row is untouched (the route returns copies). The row + also gains a normalized ``addrs`` list of ``{"ip", "if_type"}`` dicts, + sourced from ``last_addrs`` plus the discovered record, so the UI's + address pickers read paired rows the same way as discovered rows. + """ + + addrs: list[dict[str, str]] = [] + for ip in row.get("last_addrs") or []: + if isinstance(ip, str) and ip and all(a["ip"] != ip for a in addrs): + addrs.append({"ip": ip, "if_type": "paired"}) + if record is not None: + for addr in record.get("addrs") or []: + if not isinstance(addr, dict) or not addr.get("ip"): + continue + existing = next((a for a in addrs if a["ip"] == addr["ip"]), None) + if existing is not None: + # The discovered entry knows the real interface type. + existing["if_type"] = addr.get("if_type") or existing["if_type"] + elif len(addrs) < 16: + addrs.append( + { + "ip": addr["ip"], + "if_type": addr.get("if_type") or "discovered", + } + ) + if addrs: + row["addrs"] = addrs + # Persisted membership is not liveness. Until this process has observed the + # peer, render an amber/suspect shell instead of the old implicit green row. + row.setdefault("http_port", 0) + if record is None: + row["state"] = "suspect" + row["last_seen"] = None + row.setdefault("link", "unknown") + return + caps = row.get("caps") or {} + if not caps.get("ram_gb") or not caps.get("chip"): + known_caps = record.get("caps") or {} + if known_caps.get("ram_gb") or known_caps.get("chip"): + row["caps"] = dict(known_caps) + for key in ("version", "friendly_name"): + if record.get(key): + row[key] = record[key] + state = record.get("state") + row["state"] = state if state in {"discovered", "suspect", "dead"} else "suspect" + last_seen = record.get("last_seen") + row["last_seen"] = ( + float(last_seen) + if isinstance(last_seen, (int, float)) and not isinstance(last_seen, bool) + else None + ) + row["link"] = str(record.get("link") or "unknown") + http_port = record.get("http_port") + if ( + isinstance(http_port, int) + and not isinstance(http_port, bool) + and 1 <= http_port <= 65535 + ): + row["http_port"] = http_port + + +@discovery_router.get("/devices") +async def cluster_devices(is_admin: bool = Depends(require_admin)): + """Cluster device inventory for the wizard UI. + + ``multicast_ok`` is the macOS Local Network permission signal: it is + False when no foreign HELLO was received in the last 5 seconds, which is + how a denied/blocked local-network permission presents. The UI should + surface "check System Settings → Privacy & Security → Local Network" + rather than showing a silently empty device list. + """ + + try: + identity = get_node_identity() + except RuntimeError as exc: + raise HTTPException( + status_code=503, detail="cluster identity is not configured" + ) from exc + + try: + registry = get_device_registry() + except RuntimeError: + registry = None + service = discovery_service_or_none() + + paired: list[dict[str, Any]] = registry.paired() if registry else [] + paired_ids = {row["node_id"] for row in paired} + # Membership in this list IS the paired state, but the registry rows do + # not carry the flag themselves -- the self record below sets it + # explicitly. Without it, wizard consumers keyed on device.paired (the + # per-Mac role list, the card's Pair/Paired state) treat an already + # paired peer as unpaired. + for row in paired: + row["paired"] = True + + # Seam with Module B's enrollment: a paired device that completed SSH + # TOFU enrollment carries its enrolled ssh_target, so the UI probes and + # plans against the enrolled target instead of guessing from probe IPs. + try: + from .enrollment import get_cluster_enrollment + + enrollment = get_cluster_enrollment() + except RuntimeError: + enrollment = None + if enrollment is not None: + enrolled = {node.node_id: node for node in enrollment.list_nodes()} + for row in paired: + node = enrolled.get(row.get("node_id")) + if node is not None: + row["ssh_target"] = node.ssh + observed_records: dict[str, dict[str, Any]] = {} + if registry: + for entry in registry.discovered(): + observed_records[entry["node_id"]] = entry + if service is not None: + for peer in service.peers(): + # Paired peers still belong in the observation map: their live + # state, timestamp, port and interface metadata enrich the durable + # paired shell. They are filtered only from the unpaired list. + observed_records[peer.node_id] = peer.to_dict() + discovered_records = { + node_id: record + for node_id, record in observed_records.items() + if node_id not in paired_ids and not record.get("paired") + } + + # Devices paired before caps were exchanged carry empty caps on disk; + # enrich them from what discovery has actually seen before suppressing + # their node_ids from the discovered list below. + for row in paired: + _enrich_paired_row(row, observed_records.get(row.get("node_id"))) + + # Nothing flips the discovery service's in-memory ``PeerRecord.paired`` + # the moment pairing completes, so a stale (possibly dead) record for a + # now-paired node_id would otherwise render a zombie "Pair" card next + # to the paired row. Paired node_ids never appear as discovered. + for node_id in paired_ids: + discovered_records.pop(node_id, None) + + # Seam with Module B: a posted pair/request must surface in the device + # list as an awaiting_approval row so the wizard renders code entry + + # approve/deny (fixture: tests/ui/.../devices_pending_approval.json). + # Pending state wins over a plain discovered record for the same node. + try: + from .pairing import get_pairing_manager + + pairing_manager = get_pairing_manager() + except RuntimeError: + pairing_manager = None + if pairing_manager is not None: + for pending in pairing_manager.pending_requests(): + row = dict(discovered_records.get(pending["node_id"], {})) + row.update(pending) + row["state"] = "awaiting_approval" + discovered_records[pending["node_id"]] = row + + self_record: dict[str, Any] = { + "node_id": identity.node_id, + "friendly_name": identity.friendly_name, + "version": __version__, + "cluster_name": _cluster_name(), + "caps": service.config.caps.to_dict() if service is not None else {}, + "addrs": local_addr_dicts(), + "http_port": service.config.http_port if service is not None else 0, + "paired": True, + "last_seen": time.time(), + "link": "unknown", + "state": "discovered", + } + return { + "paired": paired, + "discovered": list(discovered_records.values()), + "self": self_record, + "multicast_ok": bool(service.multicast_ok) if service else False, + "mdns_available": bool(service.mdns_available) if service else False, + } diff --git a/omlx/cluster/identity.py b/omlx/cluster/identity.py new file mode 100644 index 0000000000..07178b4353 --- /dev/null +++ b/omlx/cluster/identity.py @@ -0,0 +1,251 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Stable per-node identity for oMLX cluster v2. + +Every node owns a ``NodeIdentity`` persisted at +``~/.omlx/cluster/identity.json`` (mode 0600, atomic write). The ``node_id`` +is an immutable uuid4 string; the ``friendly_name`` is display-only and may +be renamed or collision-repaired without affecting pairing, discovery, or +deployments, which all key on ``node_id``. +""" + +from __future__ import annotations + +import json +import logging +import os +import re +import socket +import subprocess +import sys +import tempfile +import threading +import time +import uuid +from collections.abc import Callable, Iterable +from contextlib import suppress +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +logger = logging.getLogger(__name__) + +IDENTITY_SCHEMA_VERSION = 1 +_MAX_NAME_LENGTH = 63 +_NAME_SANITIZE = re.compile(r"\s+") + + +def default_identity_path() -> Path: + """Default on-disk location, honoring the OMLX_BASE_PATH override.""" + + env_value = os.environ.get("OMLX_BASE_PATH") + base = Path(env_value).expanduser() if env_value else Path.home() / ".omlx" + return base / "cluster" / "identity.json" + + +def _scutil_local_hostname() -> str | None: + """Best-effort macOS LocalHostName; ``None`` off-macOS or on failure.""" + + if sys.platform != "darwin": + return None + try: + result = subprocess.run( # noqa: S603 - fixed system executable + ["/usr/sbin/scutil", "--get", "LocalHostName"], + capture_output=True, + text=True, + timeout=2.0, + check=False, + ) + except (OSError, subprocess.SubprocessError): + return None + if result.returncode != 0: + return None + name = result.stdout.strip() + return name or None + + +def _default_friendly_name() -> str: + for candidate in (_scutil_local_hostname(), socket.gethostname()): + if candidate: + name = _NAME_SANITIZE.sub("-", candidate.strip())[:_MAX_NAME_LENGTH] + if name: + return name + return "omlx-node" + + +def _resolve_collision(name: str, taken: set[str]) -> str: + """Suffix ``-2``, ``-3`` ... until the friendly name is unique.""" + + if name not in taken: + return name + for suffix in range(2, 1000): + candidate = f"{name}-{suffix}" + if candidate not in taken: + return candidate + # Absurdly unlikely; fall back to a random tail rather than loop forever. + return f"{name}-{uuid.uuid4().hex[:6]}" + + +@dataclass +class NodeIdentity: + """A node's stable identity. ``node_id`` never changes once created.""" + + node_id: str + friendly_name: str + created_at: float + schema_version: int = IDENTITY_SCHEMA_VERSION + _path: Path | None = field(default=None, repr=False, compare=False) + load_error: str | None = field(default=None, repr=False, compare=False) + + def to_dict(self) -> dict[str, Any]: + return { + "schema_version": self.schema_version, + "node_id": self.node_id, + "friendly_name": self.friendly_name, + "created_at": self.created_at, + } + + @classmethod + def from_dict(cls, payload: dict[str, Any]) -> NodeIdentity: + if not isinstance(payload, dict): + raise ValueError("cluster identity is malformed") + if payload.get("schema_version") != IDENTITY_SCHEMA_VERSION: + raise ValueError("unsupported cluster identity schema version") + node_id = payload.get("node_id") + friendly_name = payload.get("friendly_name") + created_at = payload.get("created_at") + if not isinstance(node_id, str) or not node_id: + raise ValueError("cluster identity is missing a node_id") + if not isinstance(friendly_name, str) or not friendly_name: + raise ValueError("cluster identity is missing a friendly_name") + if not isinstance(created_at, (int, float)): + raise ValueError("cluster identity is missing created_at") + return cls( + node_id=node_id, + friendly_name=friendly_name, + created_at=float(created_at), + ) + + def rename(self, new_name: str) -> None: + """Update the display name and persist it. ``node_id`` is immutable.""" + + cleaned = _NAME_SANITIZE.sub("-", str(new_name).strip())[:_MAX_NAME_LENGTH] + if not cleaned: + raise ValueError("friendly name must not be empty") + self.friendly_name = cleaned + if self._path is not None: + _atomic_save(self._path, self.to_dict()) + + +def _atomic_save(path: Path, payload: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary = tempfile.mkstemp( + prefix=".identity.", suffix=".tmp", dir=path.parent + ) + try: + os.fchmod(descriptor, 0o600) + with os.fdopen(descriptor, "w", encoding="utf-8") as stream: + json.dump(payload, stream, indent=2, sort_keys=True) + stream.write("\n") + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, path) + os.chmod(path, 0o600) + finally: + with suppress(FileNotFoundError): + os.unlink(temporary) + + +def load_or_create( + path: Path | str | None = None, + *, + taken_names: Iterable[str] = (), + clock: Callable[[], float] = time.time, +) -> NodeIdentity: + """Load the persisted identity, creating and persisting one if absent. + + ``taken_names`` lists friendly names already claimed by other cluster + members; on collision the loaded/created name gains a ``-2`` suffix + (escalating as needed) while ``node_id`` stays untouched. + + A corrupt identity file never rotates ``node_id`` silently: the corrupt + file is left on disk for inspection, a fresh in-memory identity is + returned with ``load_error`` set, and nothing is written. + """ + + identity_path = Path(path) if path is not None else default_identity_path() + taken = {name for name in taken_names} + + identity: NodeIdentity | None = None + load_error: str | None = None + if identity_path.exists(): + try: + payload = json.loads(identity_path.read_text(encoding="utf-8")) + identity = NodeIdentity.from_dict(payload) + except (OSError, json.JSONDecodeError, ValueError) as exc: + load_error = f"could not read cluster identity: {exc}" + logger.warning( + "%s at %s; using a fresh in-memory identity (the corrupt " + "file was left untouched)", + load_error, + identity_path, + ) + + created = identity is None + if identity is None: + identity = NodeIdentity( + node_id=str(uuid.uuid4()), + friendly_name=_default_friendly_name(), + created_at=clock(), + ) + identity._path = identity_path + identity.load_error = load_error + + repaired = _resolve_collision(identity.friendly_name, taken) + collision_repaired = repaired != identity.friendly_name + identity.friendly_name = repaired + + # Persist on first creation or when collision repair changed the name — + # but never overwrite a file we failed to parse. + if load_error is None and (created or collision_repaired): + try: + _atomic_save(identity_path, identity.to_dict()) + except OSError as exc: + identity.load_error = f"could not persist cluster identity: {exc}" + logger.warning("%s", identity.load_error) + return identity + + +_identity_lock = threading.Lock() +_configured_identity: NodeIdentity | None = None + + +def configure_node_identity( + base_path: Path | str | None = None, + *, + taken_names: Iterable[str] = (), +) -> NodeIdentity: + """Configure the process-wide identity used by the discovery endpoints.""" + + global _configured_identity + path = ( + Path(base_path) / "cluster" / "identity.json" if base_path is not None else None + ) + identity = load_or_create(path, taken_names=taken_names) + with _identity_lock: + _configured_identity = identity + return identity + + +def get_node_identity() -> NodeIdentity: + with _identity_lock: + if _configured_identity is None: + raise RuntimeError("cluster node identity is not configured") + return _configured_identity + + +def reset_configured_identity() -> None: + """Test hook: drop the process-wide identity.""" + + global _configured_identity + with _identity_lock: + _configured_identity = None diff --git a/omlx/cluster/pairing.py b/omlx/cluster/pairing.py new file mode 100644 index 0000000000..fa8e383b2c --- /dev/null +++ b/omlx/cluster/pairing.py @@ -0,0 +1,1650 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Code-based cluster pairing and enrollment bridge (cluster v2, Module B). + +Replaces the 3-step copy-paste relay (shared secret + key-exchange tokens in +both directions) with an exo-style flow: + +1. The JOINER shows a 6-digit code (valid 10 minutes). +2. The joiner POSTs ``/api/cluster/pair/request`` to the coordinator carrying + its identity and a salted, slow code verifier bound to the node and SSH + identities — never the code itself. +3. The coordinator dashboard lists the pending request + (``state: "awaiting_approval"``) and the operator types the code shown on + the joiner into ``/api/cluster/pair/approve``. +4. Approval verifies the code-bound identities (3 attempts, then a 10-minute lockout), + generates the 32-byte ``cluster_key``, wraps it under a key derived from + the code with PBKDF2-HMAC-SHA256 (210k iterations), persists the peer as + paired, and drives symmetric, fail-closed SSH enrollment with the + authenticated user key and daemon host key. +5. The joiner polls ``/api/cluster/pair/status/{node_id}`` and unwraps the + cluster key locally with the code only it possesses. + +``DELETE /api/cluster/devices/{node_id}`` unpairs: the device-store entry and +the stored cluster key are removed, any legacy ``enrolled-nodes.json`` entry +is dropped, and the SSH trust installed at approve time is revoked +best-effort. + +Module A (identity + discovery) is built concurrently on another branch. +Every interaction with it is feature-detected: a real ``DeviceRegistry`` / +``NodeIdentity`` is used when importable, otherwise schema-compatible local +fallbacks (same files, same ``schema_version: 1``) keep this module fully +functional and offline-testable. See ``DeviceRegistryBridge`` for the exact +method names looked up on Module A's registry. +""" + +from __future__ import annotations + +import base64 +import binascii +import hashlib +import hmac +import ipaddress +import json +import logging +import os +import platform +import secrets +import socket +import subprocess +import tempfile +import threading +import time +import urllib.request +import uuid +from collections.abc import Callable, Iterable +from contextlib import suppress +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +logger = logging.getLogger(__name__) + +# --- Pairing policy (from ops/notes/omlx_cluster_v2_spec.md, Module B) ------ + +CODE_DIGITS = 6 +CODE_TTL_SECONDS = 10 * 60 +MAX_CODE_ATTEMPTS = 3 +LOCKOUT_SECONDS = 10 * 60 +PBKDF2_ITERATIONS = 210_000 +CLUSTER_KEY_BYTES = 32 +WRAP_KDF = "PBKDF2-HMAC-SHA256" +_WRAP_TAG_DOMAIN = b"omlx-cluster-key-v1" +MAX_PENDING_REQUESTS = 32 + +DEFAULT_BASE_PATH = Path.home() / ".omlx" +IDENTITY_SCHEMA_VERSION = 1 +DEVICE_SCHEMA_VERSION = 1 +KEY_SCHEMA_VERSION = 1 + + +# --- Errors ----------------------------------------------------------------- + + +class PairingError(ValueError): + """Base class for pairing refusals; ``reason`` is machine-readable.""" + + +class PairingRequestError(PairingError): + """A join request payload was malformed or could not be accepted.""" + + +class PairingStateError(PairingError): + """No such pending request / device, or the state transition is invalid.""" + + +class PairingCodeError(PairingError): + """The presented code does not match the pending request's code hash.""" + + +class PairingLockoutError(PairingError): + """Too many wrong codes; approval is locked out until ``retry_after``.""" + + +class PairingExpiredError(PairingError): + """The pending request outlived the 10-minute code validity window.""" + + +class EnrollmentDriveError(PairingError): + """The fail-closed SSH TOFU enrollment step failed after code verify.""" + + +# --- Code + key-wrapping crypto (stdlib only) -------------------------------- + + +def generate_pairing_code() -> str: + """Return a zero-padded 6-digit pairing code shown on the joiner.""" + + return f"{secrets.randbelow(10**CODE_DIGITS):0{CODE_DIGITS}d}" + + +def validate_pairing_code(code: str) -> str: + if not isinstance(code, str) or not code.isdigit() or len(code) != CODE_DIGITS: + raise PairingRequestError(f"pairing code must be {CODE_DIGITS} digits") + return code + + +def pairing_code_hash( + code: str, + node_id: str, + ssh_public_key: str = "", + ssh_host_public_key: str = "", + salt: bytes = b"", +) -> str: + """Slowly derive a verifier bound to the node and both SSH identities.""" + + payload = json.dumps( + { + "node_id": node_id, + "ssh_public_key": ssh_public_key, + "ssh_host_public_key": ssh_host_public_key, + }, + sort_keys=True, + separators=(",", ":"), + ).encode("utf-8") + verifier_salt = bytes(salt) + hashlib.sha256(payload).digest() + return hashlib.pbkdf2_hmac( + "sha256", + code.encode("utf-8"), + verifier_salt, + PBKDF2_ITERATIONS, + dklen=32, + ).hex() + + +def _derive_wrap_key(code: str, salt: bytes, iterations: int) -> bytes: + return hashlib.pbkdf2_hmac( + "sha256", code.encode("utf-8"), salt, iterations, dklen=32 + ) + + +def wrap_cluster_key( + cluster_key: bytes, code: str, *, iterations: int = PBKDF2_ITERATIONS +) -> dict[str, Any]: + """Encrypt ``cluster_key`` under a key derived from the pairing code. + + The derived key is used exactly once, so XOR is a one-time pad here; an + HMAC over the ciphertext detects both tampering and wrong-code unwraps. + """ + + if len(cluster_key) != CLUSTER_KEY_BYTES: + raise PairingError(f"cluster key must be {CLUSTER_KEY_BYTES} bytes") + salt = secrets.token_bytes(16) + wrap_key = _derive_wrap_key(code, salt, iterations) + ciphertext = bytes(a ^ b for a, b in zip(cluster_key, wrap_key)) + tag = hmac.new(wrap_key, _WRAP_TAG_DOMAIN + ciphertext, hashlib.sha256).digest() + return { + "kdf": WRAP_KDF, + "iterations": iterations, + "salt": base64.b64encode(salt).decode(), + "ciphertext": base64.b64encode(ciphertext).decode(), + "tag": base64.b64encode(tag).decode(), + } + + +def unwrap_cluster_key(package: dict[str, Any], code: str) -> bytes: + """Recover the cluster key; a wrong code fails closed with PairingCodeError.""" + + try: + iterations = int(package["iterations"]) + salt = base64.b64decode(package["salt"], validate=True) + ciphertext = base64.b64decode(package["ciphertext"], validate=True) + tag = base64.b64decode(package["tag"], validate=True) + except (KeyError, TypeError, ValueError) as exc: + raise PairingRequestError("malformed wrapped cluster key") from exc + if package.get("kdf") != WRAP_KDF or not 1 <= iterations <= 10_000_000: + raise PairingRequestError("unsupported cluster-key wrap parameters") + wrap_key = _derive_wrap_key(code, salt, iterations) + expected = hmac.new( + wrap_key, _WRAP_TAG_DOMAIN + ciphertext, hashlib.sha256 + ).digest() + if not hmac.compare_digest(tag, expected): + raise PairingCodeError("cluster key unwrap failed (wrong code or tampering)") + if len(ciphertext) != CLUSTER_KEY_BYTES: + raise PairingRequestError("malformed wrapped cluster key") + return bytes(a ^ b for a, b in zip(ciphertext, wrap_key)) + + +def coordinator_identity_tag( + cluster_key: bytes, + coordinator: dict[str, Any], +) -> str: + """Bind the approved coordinator identity to the unwrapped cluster key.""" + + payload = json.dumps( + coordinator, + sort_keys=True, + separators=(",", ":"), + ).encode("utf-8") + return hmac.new( + cluster_key, b"omlx-coordinator-v1\0" + payload, hashlib.sha256 + ).hexdigest() + + +# --- Small persisted stores (same conventions as registry.py/enrollment.py) - + + +def _atomic_write_json(path: Path, payload: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary = tempfile.mkstemp( + prefix=f".{path.stem}.", suffix=".tmp", dir=path.parent + ) + try: + os.fchmod(descriptor, 0o600) + with os.fdopen(descriptor, "w", encoding="utf-8") as stream: + json.dump(payload, stream, indent=2, sort_keys=True) + stream.write("\n") + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, path) + os.chmod(path, 0o600) + finally: + with suppress(FileNotFoundError): + os.unlink(temporary) + + +def _read_json_object(path: Path, schema_version: int, what: str) -> dict[str, Any]: + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + raise PairingError(f"could not read {what}: {exc}") from exc + if not isinstance(payload, dict) or payload.get("schema_version") != schema_version: + raise PairingError(f"unsupported {what} schema") + return payload + + +class PairingAuditLog: + """Append-only JSON-lines audit trail for pairing decisions (0600).""" + + def __init__(self, path: Path) -> None: + self.path = Path(path) + self._lock = threading.Lock() + + def record( + self, event: str, *, node_id: str = "", detail: dict[str, Any] | None = None + ) -> dict[str, Any]: + entry = { + "ts": time.time(), + "event": event, + "node_id": node_id, + "detail": detail or {}, + } + line = json.dumps(entry, sort_keys=True) + with self._lock: + try: + self.path.parent.mkdir(parents=True, exist_ok=True) + fresh = not self.path.exists() + with self.path.open("a", encoding="utf-8") as stream: + stream.write(line + "\n") + if fresh: + os.chmod(self.path, 0o600) + except OSError: + # Auditing must never break a pairing state transition. + logger.exception("could not append to the pairing audit log") + return entry + + +class PairingKeyStore: + """Per-peer cluster keys at ``/cluster/pairing-keys.json`` (0600). + + Written on both sides: the coordinator records the key it issued, the + joiner records the key it unwrapped. Also retains the peer's SSH public + key and addresses so ``unpair`` can revoke exactly what ``approve`` + installed. + """ + + def __init__(self, base_path: Path, *, clock: Callable[[], float] = time.time): + self.base_path = Path(base_path) + self.path = self.base_path / "cluster" / "pairing-keys.json" + self._clock = clock + self._lock = threading.RLock() + self._records: dict[str, dict[str, Any]] = {} + self.load_error: str | None = None + try: + self._load() + except PairingError as exc: + # Fail closed, like ClusterRegistry: trust nothing from a corrupt file. + self._records = {} + self.load_error = str(exc) + + def _load(self) -> None: + if not self.path.exists(): + return + payload = _read_json_object(self.path, KEY_SCHEMA_VERSION, "pairing-key store") + records = payload.get("keys") + if not isinstance(records, dict): + raise PairingError("pairing-key store is malformed") + self._records = {str(k): dict(v) for k, v in records.items()} + + def _save(self) -> None: + _atomic_write_json( + self.path, + {"schema_version": KEY_SCHEMA_VERSION, "keys": self._records}, + ) + + def set(self, node_id: str, record: dict[str, Any]) -> None: + with self._lock: + previous = dict(self._records) + self._records[node_id] = dict(record) + try: + self._save() + except Exception: + self._records = previous + raise + self.load_error = None + + def get(self, node_id: str) -> dict[str, Any] | None: + with self._lock: + record = self._records.get(node_id) + return dict(record) if record is not None else None + + def remove(self, node_id: str) -> dict[str, Any] | None: + with self._lock: + record = self._records.pop(node_id, None) + if record is None: + return None + try: + self._save() + except Exception: + self._records[node_id] = record + raise + return dict(record) + + def list(self) -> dict[str, dict[str, Any]]: + with self._lock: + return {key: dict(value) for key, value in sorted(self._records.items())} + + +class JsonDeviceStore: + """Fallback paired-device store, schema-compatible with Module A. + + Persists to ``/cluster/devices.json`` — the exact file Module A's + ``DeviceRegistry`` owns — using the documented shape: paired devices as + ``{node_id, friendly_name, caps, paired_at, last_addrs, state}`` under + ``schema_version: 1``. Used only when no Module A registry is injected; + when Module A lands, the integrator passes its ``DeviceRegistry`` and this + class is unused (``DeviceRegistryBridge`` adapts it instead). + + Pending (``awaiting_approval``) requests are deliberately NOT written + here: like enrollment.py join keys, they are memory-only so a restart + invalidates half-finished pairings. + """ + + def __init__(self, base_path: Path) -> None: + self.base_path = Path(base_path) + self.path = self.base_path / "cluster" / "devices.json" + self._lock = threading.RLock() + self._devices: dict[str, dict[str, Any]] = {} + self.load_error: str | None = None + try: + self._load() + except PairingError as exc: + self._devices = {} + self.load_error = str(exc) + + def _load(self) -> None: + if not self.path.exists(): + return + payload = _read_json_object(self.path, DEVICE_SCHEMA_VERSION, "device registry") + devices = payload.get("devices") + if not isinstance(devices, list): + raise PairingError("device registry is malformed") + self._devices = { + str(item["node_id"]): dict(item) + for item in devices + if isinstance(item, dict) and "node_id" in item + } + + def _save(self) -> None: + _atomic_write_json( + self.path, + { + "schema_version": DEVICE_SCHEMA_VERSION, + "devices": [self._devices[key] for key in sorted(self._devices)], + }, + ) + + # PairingManager device-store protocol --------------------------------- + + def put_paired(self, record: dict[str, Any]) -> None: + with self._lock: + previous = dict(self._devices) + merged = dict(previous.get(record["node_id"], {})) + merged.update(record) + merged["state"] = "paired" + self._devices[record["node_id"]] = merged + try: + self._save() + except Exception: + self._devices = previous + raise + self.load_error = None + + def get(self, node_id: str) -> dict[str, Any] | None: + with self._lock: + record = self._devices.get(node_id) + return dict(record) if record is not None else None + + def list_paired(self) -> list[dict[str, Any]]: + with self._lock: + return [dict(self._devices[key]) for key in sorted(self._devices)] + + def remove(self, node_id: str) -> bool: + with self._lock: + if node_id not in self._devices: + return False + previous = dict(self._devices) + del self._devices[node_id] + try: + self._save() + except Exception: + self._devices = previous + raise + return True + + +class DeviceRegistryBridge: + """Adapt Module A's ``DeviceRegistry`` to the pairing device-store protocol. + + Module A ships concurrently; its exact merge API is its own deliverable. + Each operation feature-detects the documented candidates in order and + raises a clear error if none exist, so an API drift fails loudly at + integration time rather than silently dropping peers. + + Integration note: the real ``DeviceRegistry.mark_paired`` takes keyword + fields, not a record dict, and its ``merge`` only persists *already + paired* devices — routing a pairing approval through ``merge`` would + leave the new peer memory-only. ``mark_paired`` is therefore detected + first and called with the record's fields. + """ + + _PUT = ("upsert", "merge", "put", "add", "set_paired") + _REMOVE = ("remove", "delete", "unpair", "drop") + _GET = ("get", "device", "find") + _LIST = ("list_paired", "paired", "list", "devices") + + def __init__(self, registry: Any) -> None: + self._registry = registry + + def _call(self, names: Iterable[str], *args: Any) -> Any: + for name in names: + method = getattr(self._registry, name, None) + if callable(method): + return method(*args) + raise PairingStateError( + "DeviceRegistry exposes none of " + + ", ".join(names) + + "; update DeviceRegistryBridge for Module A's API" + ) + + def put_paired(self, record: dict[str, Any]) -> None: + mark_paired = getattr(self._registry, "mark_paired", None) + if callable(mark_paired): + mark_paired( + record["node_id"], + friendly_name=record.get("friendly_name") or None, + caps=record.get("caps") or None, + addrs=record.get("last_addrs") or None, + paired_at=record.get("paired_at"), + ) + return + self._call(self._PUT, record) + + def get(self, node_id: str) -> dict[str, Any] | None: + result = self._call(self._GET, node_id) + return dict(result) if isinstance(result, dict) else None + + def list_paired(self) -> list[dict[str, Any]]: + result = self._call(self._LIST) + if result is None: + return [] + return [dict(item) for item in result] + + def remove(self, node_id: str) -> bool: + return bool(self._call(self._REMOVE, node_id)) + + +def _coerce_device_store(registry: Any, base_path: Path) -> Any: + """Return a device store: injected Module A registry, protocol object, or fallback.""" + + if registry is None: + return JsonDeviceStore(base_path) + if all( + callable(getattr(registry, name, None)) + for name in ("put_paired", "get", "list_paired", "remove") + ): + return registry + return DeviceRegistryBridge(registry) + + +# --- Local identity (Module A bridge) --------------------------------------- + + +def _default_friendly_name() -> str: + if platform.system() == "Darwin": + try: + result = subprocess.run( + ["scutil", "--get", "LocalHostName"], + capture_output=True, + text=True, + check=False, + timeout=5, + ) + name = result.stdout.strip() + if result.returncode == 0 and name: + return name + except (OSError, subprocess.TimeoutExpired): + pass + return socket.gethostname() + + +def _identity_from_dict(payload: dict[str, Any]) -> dict[str, Any]: + return { + "node_id": str(payload["node_id"]), + "friendly_name": str(payload["friendly_name"]), + "created_at": float(payload["created_at"]), + "schema_version": IDENTITY_SCHEMA_VERSION, + } + + +def _fallback_identity(base_path: Path) -> dict[str, Any]: + """``load_or_create`` against the same file Module A's identity.py owns. + + Same path (``~/.omlx/cluster/identity.json``), same schema_version 1, + same 0600 atomic write — when Module A merges it adopts this identity + instead of minting a second node_id. + """ + + path = Path(base_path) / "cluster" / "identity.json" + if path.exists(): + payload = _read_json_object(path, IDENTITY_SCHEMA_VERSION, "cluster identity") + return _identity_from_dict(payload) + identity = { + "node_id": str(uuid.uuid4()), + "friendly_name": _default_friendly_name(), + "created_at": time.time(), + "schema_version": IDENTITY_SCHEMA_VERSION, + } + _atomic_write_json(path, identity) + return identity + + +def load_node_identity(base_path: Path) -> dict[str, Any]: + """Prefer Module A's ``identity.load_or_create``; fall back locally.""" + + try: + from .identity import ( + load_or_create as _load_or_create, # type: ignore[import-not-found] + ) + except ImportError: + return _fallback_identity(base_path) + identity = _load_or_create(base_path / "cluster" / "identity.json") + return { + "node_id": identity.node_id, + "friendly_name": identity.friendly_name, + "created_at": float(getattr(identity, "created_at", time.time())), + "schema_version": getattr(identity, "schema_version", IDENTITY_SCHEMA_VERSION), + } + + +# --- Pending requests (memory-only, like enrollment.py join keys) ------------ + + +@dataclass +class _PendingRequest: + node_id: str + friendly_name: str + caps: dict[str, Any] + code_hash: str + code_salt: bytes + addrs: list[str] + http_port: int | None + ssh_public_key: str | None + ssh_host_public_key: str + created_at: float + expires_at: float + attempts: int = 0 + locked_until: float | None = None + approving: bool = False + + def to_dict(self, now: float) -> dict[str, Any]: + locked = self.locked_until is not None and self.locked_until > now + return { + "node_id": self.node_id, + "friendly_name": self.friendly_name, + "caps": self.caps, + "addrs": list(self.addrs), + "http_port": self.http_port, + "state": "awaiting_approval", + "created_at": self.created_at, + "expires_at": self.expires_at, + "attempts": self.attempts, + "locked": locked, + "locked_until": self.locked_until if locked else None, + "approving": self.approving, + } + + +# --- SSH TOFU enrollment drivers (defaults drive omlx/cluster/ssh_keys.py) --- + + +def default_enrollment_driver(peer: dict[str, Any]) -> dict[str, Any]: + """Drive the existing fail-closed SSH TOFU enrollment for an approved peer. + + Reuses the exact primitives of the legacy 3-step flow instead of + reinventing trust stores: + + * ``ssh_keys.get_or_create_ssh_key`` — the coordinator's dedicated + ``~/.ssh/omlx_cluster`` identity must exist; + * ``ssh_keys.install_authorized_key`` — the joiner's user key (sent in + the join request) is authorized locally so the joiner can be a client; + * ``ssh_keys.pin_enrolled_host_key`` — pin the code-authenticated daemon + host key for each coordinator-observed address, refusing changed hosts. + """ + + from .ssh_keys import ( + get_or_create_ssh_key, + install_authorized_key, + pin_enrolled_host_key, + ) + + key_pair = get_or_create_ssh_key() + result: dict[str, Any] = { + "coordinator_fingerprint": key_pair.fingerprint, + "authorized_key_installed": False, + "host_keys_pinned": [], + } + peer_public_key = normalize_ssh_public_key(peer.get("ssh_public_key") or "") + peer_host_key = normalize_ssh_public_key(peer.get("ssh_host_public_key") or "") + addresses = [str(address) for address in (peer.get("addrs") or []) if address] + if not addresses: + raise EnrollmentDriveError("SSH enrollment requires a verified peer address") + result["authorized_key_installed"] = install_authorized_key( + public_key=peer_public_key + ) + for address in addresses: + target = ssh_host_target(address) + if pin_enrolled_host_key(hostname=target, public_key=peer_host_key): + result["host_keys_pinned"].append(address) + return result + + +def default_revocation_driver(revocation: dict[str, Any]) -> dict[str, Any]: + """Best-effort undo of what ``default_enrollment_driver`` installed. + + The device-store removal (the trust anchor) already happened before this + runs; here we only retract SSH material: the peer's authorized_keys line + and its known_hosts pins. Errors are collected, never raised — a + partially cleaned SSH file must not resurrect a removed device. + """ + + result: dict[str, Any] = {"authorized_key_removed": False, "errors": []} + ssh_dir = Path.home() / ".ssh" + peer_public_key = (revocation.get("peer_public_key") or "").strip() + if peer_public_key: + authorized_keys = ssh_dir / "authorized_keys" + try: + if authorized_keys.exists(): + lines = authorized_keys.read_text(encoding="utf-8").splitlines() + kept = [line for line in lines if line.strip() != peer_public_key] + if len(kept) != len(lines): + authorized_keys.write_text( + "".join(line + "\n" for line in kept), encoding="utf-8" + ) + os.chmod(authorized_keys, 0o600) + result["authorized_key_removed"] = True + except OSError as exc: + result["errors"].append(f"authorized_keys: {exc}") + keygen = "/usr/bin/ssh-keygen" + for address in revocation.get("addrs") or []: + try: + subprocess.run( + [keygen, "-R", address], + capture_output=True, + check=False, + timeout=10, + ) + except (OSError, subprocess.TimeoutExpired) as exc: + result["errors"].append(f"known_hosts {address}: {exc}") + return result + + +def _default_http_post(url: str, payload: dict[str, Any], timeout: float) -> Any: + request = urllib.request.Request( + url, + data=json.dumps(payload).encode("utf-8"), + headers={"Content-Type": "application/json"}, + method="POST", + ) + with urllib.request.urlopen(request, timeout=timeout) as response: + return json.loads(response.read().decode("utf-8")) + + +def _default_http_get(url: str, timeout: float) -> Any: + with urllib.request.urlopen(url, timeout=timeout) as response: + return json.loads(response.read().decode("utf-8")) + + +def _local_ssh_public_key() -> str | None: + """Best-effort local cluster pubkey for the join request (never fatal).""" + + try: + from .ssh_keys import get_or_create_ssh_key + except ImportError: + return None + try: + return get_or_create_ssh_key().public_key + except Exception: + return None + + +def _local_ssh_host_public_key() -> str | None: + """Read the public half of the local SSH daemon host identity.""" + + override = os.environ.get("OMLX_CLUSTER_SSH_HOST_PUBLIC_KEY") + candidates = ( + [Path(override).expanduser()] + if override + else [ + Path("/etc/ssh/ssh_host_ed25519_key.pub"), + Path("/etc/ssh/ssh_host_rsa_key.pub"), + ] + ) + for path in candidates: + try: + return normalize_ssh_public_key(path.read_text(encoding="utf-8").strip()) + except (OSError, PairingRequestError): + continue + return None + + +def normalize_ssh_public_key(public_key: str) -> str: + """Validate and strip an OpenSSH user key to its type and key data.""" + + if not isinstance(public_key, str) or "\n" in public_key or "\r" in public_key: + raise PairingRequestError("join request carries an invalid SSH public key") + parts = public_key.strip().split() + if len(parts) < 2: + raise PairingRequestError("join request carries an invalid SSH public key") + normalized = " ".join(parts[:2]) + try: + from .ssh_keys import ssh_public_key_fingerprint + + ssh_public_key_fingerprint(normalized) + except (ImportError, RuntimeError, ValueError) as exc: + raise PairingRequestError( + "join request carries an invalid SSH public key" + ) from exc + return normalized + + +def ssh_host_target(address: str) -> str: + """Format one validated IP for the existing known_hosts API.""" + + raw = str(address).strip() + if "%" in raw: + raise EnrollmentDriveError( + "SSH enrollment requires an address without an IPv6 scope suffix" + ) + try: + parsed = ipaddress.ip_address(raw) + except ValueError as exc: + raise EnrollmentDriveError( + "SSH enrollment received an invalid address" + ) from exc + return f"[{parsed}]" if parsed.version == 6 else str(parsed) + + +# --- PairingManager ----------------------------------------------------------- + + +class PairingManager: + """Joiner + coordinator sides of code-based pairing. + + Parameters are dependency-injection seams; every default is production + behavior and every test substitutes fakes: + + * ``registry`` — Module A ``DeviceRegistry`` (feature-detected via + :class:`DeviceRegistryBridge`), an object already speaking the + device-store protocol, or ``None`` for the schema-compatible + :class:`JsonDeviceStore` fallback. + * ``enrollment_store`` — the legacy ``ClusterEnrollmentStore``; consulted + on ``unpair`` so CUDA-enrolled entries with the same node_id are + dropped too. Optional. + * ``identity`` — dict with ``node_id``/``friendly_name``; default bridges + to Module A's identity module (or the compatible local file). + * ``enrollment_driver`` / ``revocation_driver`` — SSH TOFU trust + install/retract steps; defaults drive ``omlx/cluster/ssh_keys.py``. + * ``http_post`` / ``http_get`` — joiner-side transport; loopback fakes + in tests, urllib in production. + """ + + def __init__( + self, + registry: Any = None, + enrollment_store: Any = None, + *, + base_path: Path | None = None, + identity: dict[str, Any] | None = None, + key_store: PairingKeyStore | None = None, + caps_provider: Callable[[], dict[str, Any]] | None = None, + address_provider: Callable[[], list[str]] | None = None, + ssh_key_provider: Callable[[], str | None] | None = None, + ssh_host_key_provider: Callable[[], str | None] | None = None, + enrollment_driver: Callable[[dict[str, Any]], Any] | None = None, + revocation_driver: Callable[[dict[str, Any]], Any] | None = None, + http_post: Callable[[str, dict[str, Any], float], Any] | None = None, + http_get: Callable[[str, float], Any] | None = None, + clock: Callable[[], float] = time.time, + audit: PairingAuditLog | Callable[..., Any] | None = None, + ) -> None: + self.base_path = Path(base_path) if base_path is not None else DEFAULT_BASE_PATH + self._identity = ( + dict(identity) + if identity is not None + else load_node_identity(self.base_path) + ) + self._devices = _coerce_device_store(registry, self.base_path) + self._enrollment_store = enrollment_store + self._key_store = ( + key_store + if key_store is not None + else PairingKeyStore(self.base_path, clock=clock) + ) + self._caps_provider = caps_provider + self._address_provider = address_provider + self._ssh_key_provider = ssh_key_provider or _local_ssh_public_key + self._ssh_host_key_provider = ( + ssh_host_key_provider or _local_ssh_host_public_key + ) + self._enrollment_driver = enrollment_driver or default_enrollment_driver + self._revocation_driver = revocation_driver or default_revocation_driver + self._http_post = http_post or _default_http_post + self._http_get = http_get or _default_http_get + self._clock = clock + if audit is None: + audit = PairingAuditLog(self.base_path / "cluster" / "pairing-audit.jsonl") + self._audit = audit + self._lock = threading.RLock() + self._pending: dict[str, _PendingRequest] = {} + self._denied: dict[str, float] = {} + self._local_code: dict[str, Any] | None = None + + # -- helpers ------------------------------------------------------------ + + @property + def node_id(self) -> str: + return self._identity["node_id"] + + @property + def friendly_name(self) -> str: + return self._identity["friendly_name"] + + def local_addrs(self) -> list[str]: + """Validated local IPs included in the peer's approved trust record.""" + + if self._address_provider is None: + return [] + try: + candidates = self._address_provider() + except Exception: + return [] + addresses: list[str] = [] + for candidate in candidates or []: + raw = str(candidate).strip() + try: + ipaddress.ip_address(raw.split("%", 1)[0]) + except ValueError: + continue + normalized = raw + if normalized not in addresses: + addresses.append(normalized) + if len(addresses) >= 8: + break + return addresses + + def local_ssh_material(self) -> dict[str, Any]: + """Complete local trust material the opposite peer must install.""" + + addresses = self.local_addrs() + if not addresses: + raise EnrollmentDriveError( + "SSH enrollment requires a verified local address" + ) + return { + "node_id": self.node_id, + "friendly_name": self.friendly_name, + "caps": self._caps_provider() if self._caps_provider else {}, + "addrs": addresses, + "ssh_public_key": normalize_ssh_public_key(self._ssh_key_provider() or ""), + "ssh_host_public_key": normalize_ssh_public_key( + self._ssh_host_key_provider() or "" + ), + } + + def _record_audit( + self, event: str, *, node_id: str = "", detail: dict[str, Any] | None = None + ) -> None: + record = getattr(self._audit, "record", None) + if callable(record): + record(event, node_id=node_id, detail=detail) + elif callable(self._audit): + self._audit(event, node_id=node_id, detail=detail) + + def _prune_pending(self, now: float, keep: str | None = None) -> None: + expired = [ + node_id + for node_id, pending in self._pending.items() + if pending.expires_at < now and node_id != keep + ] + for node_id in expired: + del self._pending[node_id] + self._record_audit("join_request_expired", node_id=node_id) + self._denied = { + node_id: ts for node_id, ts in self._denied.items() if ts + 3600 > now + } + + # -- joiner side ---------------------------------------------------------- + + def start_join(self) -> dict[str, Any]: + """Generate the 6-digit code the joiner displays; valid 10 minutes.""" + + code = generate_pairing_code() + now = self._clock() + self._local_code = { + "code": code, + "created_at": now, + "expires_at": now + CODE_TTL_SECONDS, + "completing": False, + } + return {"code": code, "expires_at": self._local_code["expires_at"]} + + def build_join_request(self, code: str | None = None) -> dict[str, Any]: + """Assemble the pair/request payload — identity + code hash, no code.""" + + if code is None: + if self._local_code is None: + raise PairingStateError("no join in progress; call start_join first") + if self._local_code["expires_at"] < self._clock(): + raise PairingExpiredError("the displayed pairing code has expired") + code = self._local_code["code"] + validate_pairing_code(code) + caps = self._caps_provider() if self._caps_provider else {} + ssh_public_key = normalize_ssh_public_key(self._ssh_key_provider() or "") + ssh_host_public_key = normalize_ssh_public_key( + self._ssh_host_key_provider() or "" + ) + code_salt = secrets.token_bytes(16) + return { + "node_id": self.node_id, + "friendly_name": self.friendly_name, + "caps": dict(caps), + "code_hash": pairing_code_hash( + code, + self.node_id, + ssh_public_key, + ssh_host_public_key, + code_salt, + ), + "code_salt": base64.b64encode(code_salt).decode("ascii"), + "http_port": None, + "addrs": self.local_addrs(), + "ssh_public_key": ssh_public_key, + "ssh_host_public_key": ssh_host_public_key, + } + + def request_join( + self, + coordinator_addr: str, + code: str | None = None, + *, + timeout: float = 10.0, + ) -> dict[str, Any]: + """POST ``/api/cluster/pair/request`` to the coordinator.""" + + payload = self.build_join_request(code) + url = f"http://{coordinator_addr}/api/cluster/pair/request" + response = self._http_post(url, payload, timeout) + self._record_audit( + "join_requested", + node_id=self.node_id, + detail={"coordinator": coordinator_addr}, + ) + return {"state": "awaiting_approval", "response": response} + + def poll_join( + self, coordinator_addr: str, *, timeout: float = 5.0 + ) -> dict[str, Any]: + """GET the coordinator's view of this node's pairing status.""" + + url = f"http://{coordinator_addr}/api/cluster/pair/status/{self.node_id}" + return self._http_get(url, timeout) + + def complete_join( + self, status: dict[str, Any], code: str | None = None + ) -> dict[str, Any]: + """Unwrap the approved cluster key and persist the coordinator as paired. + + ``status`` is the payload from :meth:`poll_join` (or the loopback + equivalent). Fail-closed: a wrong code or tampered package raises + and nothing is stored. + """ + + if status.get("state") != "approved": + raise PairingStateError( + f"coordinator has not approved this node (state={status.get('state')!r})" + ) + package = status.get("cluster_key_package") + if not isinstance(package, dict): + raise PairingRequestError("approval status is missing the wrapped key") + with self._lock: + local_code = self._local_code + if local_code is None: + raise PairingStateError("no join in progress; call start_join first") + if local_code["expires_at"] < self._clock(): + self._local_code = None + raise PairingExpiredError("the displayed pairing code has expired") + if local_code.get("completing"): + raise PairingStateError("join completion is already in progress") + if code is None: + code = local_code["code"] + local_code["completing"] = True + try: + cluster_key = unwrap_cluster_key(package, code) + except Exception: + with self._lock: + if self._local_code is local_code: + local_code["completing"] = False + raise + coordinator = status.get("coordinator") or {} + coordinator_id = str(coordinator.get("node_id") or "") + if not coordinator_id: + with self._lock: + if self._local_code is local_code: + local_code["completing"] = False + raise PairingRequestError("approval status is missing coordinator identity") + coordinator_peer = { + "node_id": coordinator_id, + "friendly_name": coordinator.get("friendly_name", ""), + "caps": coordinator.get("caps") or {}, + "addrs": list(coordinator.get("addrs") or []), + "ssh_public_key": coordinator.get("ssh_public_key"), + "ssh_host_public_key": coordinator.get("ssh_host_public_key"), + } + observed_tag = str(status.get("coordinator_identity_tag") or "") + try: + expected_tag = coordinator_identity_tag(cluster_key, coordinator_peer) + except Exception: + with self._lock: + if self._local_code is local_code: + local_code["completing"] = False + raise + if not hmac.compare_digest(observed_tag, expected_tag): + with self._lock: + if self._local_code is local_code: + local_code["completing"] = False + raise PairingCodeError("approval status coordinator identity was altered") + enrolled = False + try: + self._enrollment_driver(coordinator_peer) + enrolled = True + except Exception as exc: + self._record_audit( + "join_enrollment_failed", + node_id=coordinator_id, + detail={"error": str(exc)}, + ) + with self._lock: + if self._local_code is local_code: + local_code["completing"] = False + raise EnrollmentDriveError( + f"SSH enrollment failed; coordinator was not paired: {exc}" + ) from exc + paired_at = self._clock() + record = { + "node_id": coordinator_id, + "friendly_name": coordinator.get("friendly_name", ""), + "caps": coordinator.get("caps") or {}, + "paired_at": paired_at, + "last_addrs": coordinator_peer["addrs"], + "state": "paired", + "role": "coordinator", + } + key_record = { + "cluster_key": cluster_key.hex(), + "peer_public_key": coordinator.get("ssh_public_key"), + "addrs": coordinator_peer["addrs"], + "paired_at": paired_at, + "role": "coordinator", + } + key_written = False + try: + with self._lock: + if self._local_code is not local_code or not local_code.get( + "completing" + ): + raise PairingStateError( + "join state changed while completion was in progress" + ) + self._key_store.set(coordinator_id, key_record) + key_written = True + self._devices.put_paired(record) + self._local_code = None + except Exception as exc: + rollback_errors: list[str] = [] + if key_written: + try: + self._key_store.remove(coordinator_id) + except Exception as rollback_exc: + rollback_errors.append(f"pairing key: {rollback_exc}") + if enrolled: + try: + self._revocation_driver( + { + "peer_public_key": coordinator.get("ssh_public_key"), + "addrs": coordinator_peer["addrs"], + } + ) + except Exception as rollback_exc: + rollback_errors.append(f"SSH enrollment: {rollback_exc}") + with self._lock: + if self._local_code is local_code: + local_code["completing"] = False + self._record_audit( + "join_persistence_failed", + node_id=coordinator_id, + detail={"error": str(exc), "rollback_errors": rollback_errors}, + ) + suffix = ( + "; rollback issues: " + "; ".join(rollback_errors) + if rollback_errors + else "" + ) + raise PairingError( + "join state could not be persisted; coordinator was not paired: " + f"{exc}{suffix}" + ) from exc + self._record_audit("join_completed", node_id=coordinator_id) + return record + + # -- coordinator side ----------------------------------------------------- + + def handle_join_request(self, payload: dict[str, Any]) -> dict[str, Any]: + """Register a joiner's pair/request as ``awaiting_approval``. + + The code itself never arrives — only a salted PBKDF2 verifier bound to + the node and both SSH identities — so this endpoint can stay + unauthenticated; the admin's approve step (typing the code shown on the + joiner) is the trust decision. + """ + + if not isinstance(payload, dict): + raise PairingRequestError("join request must be an object") + node_id = str(payload.get("node_id") or "").strip() + friendly_name = str(payload.get("friendly_name") or "").strip() + code_hash = str(payload.get("code_hash") or "").strip() + code_salt_encoded = str(payload.get("code_salt") or "").strip() + caps = payload.get("caps") + addrs = payload.get("addrs") or [] + http_port = payload.get("http_port") + ssh_public_key = payload.get("ssh_public_key") + ssh_host_public_key = payload.get("ssh_host_public_key") + if not node_id or len(node_id) > 255: + raise PairingRequestError("join request is missing a node_id") + if node_id == self.node_id: + raise PairingRequestError("a node cannot join its own cluster") + if not friendly_name or len(friendly_name) > 255: + raise PairingRequestError("join request is missing a friendly_name") + if len(code_hash) != 64 or any(c not in "0123456789abcdef" for c in code_hash): + raise PairingRequestError("join request carries a malformed code_hash") + try: + code_salt = base64.b64decode(code_salt_encoded, validate=True) + except (binascii.Error, ValueError, TypeError) as exc: + raise PairingRequestError( + "join request carries a malformed code_salt" + ) from exc + if len(code_salt) != 16: + raise PairingRequestError("join request carries a malformed code_salt") + if not isinstance(caps, dict): + raise PairingRequestError("join request caps must be an object") + if not isinstance(addrs, list) or not all(isinstance(a, str) for a in addrs): + raise PairingRequestError("join request addrs must be a list of strings") + normalized_addrs: list[str] = [] + for address in addrs: + raw = address.strip() + try: + ipaddress.ip_address(raw.split("%", 1)[0]) + except ValueError as exc: + raise PairingRequestError( + "join request carries an invalid peer address" + ) from exc + if raw not in normalized_addrs: + normalized_addrs.append(raw) + if http_port is not None and not (1 <= int(http_port) <= 65535): + raise PairingRequestError("join request http_port is out of range") + ssh_public_key = normalize_ssh_public_key(ssh_public_key or "") + ssh_host_public_key = normalize_ssh_public_key(ssh_host_public_key or "") + + with self._lock: + now = self._clock() + self._prune_pending(now) + existing = self._pending.get(node_id) + if existing is not None: + same_request = ( + hmac.compare_digest(existing.code_hash, code_hash) + and hmac.compare_digest(existing.code_salt, code_salt) + and existing.ssh_public_key == ssh_public_key + and existing.ssh_host_public_key == ssh_host_public_key + and existing.addrs == normalized_addrs[:8] + ) + if same_request: + return existing.to_dict(now) + raise PairingStateError( + "a different join request is already pending for this node_id" + ) + live = [p for p in self._pending.values() if p.node_id != node_id] + if len(live) >= MAX_PENDING_REQUESTS: + raise PairingRequestError( + "too many pending join requests; approve or deny one first" + ) + request = _PendingRequest( + node_id=node_id, + friendly_name=friendly_name, + caps=dict(caps), + code_hash=code_hash, + code_salt=code_salt, + addrs=normalized_addrs[:8], + http_port=int(http_port) if http_port is not None else None, + ssh_public_key=ssh_public_key, + ssh_host_public_key=ssh_host_public_key, + created_at=now, + expires_at=now + CODE_TTL_SECONDS, + ) + self._pending[node_id] = request + self._denied.pop(node_id, None) + self._record_audit( + "join_request_received", + node_id=node_id, + detail={"friendly_name": friendly_name, "addrs": list(request.addrs)}, + ) + return request.to_dict(self._clock()) + + def pending_requests(self) -> list[dict[str, Any]]: + """Pending requests for the devices list (``state: awaiting_approval``).""" + + with self._lock: + now = self._clock() + self._prune_pending(now) + return [self._pending[key].to_dict(now) for key in sorted(self._pending)] + + def approve(self, node_id: str, code: str) -> dict[str, Any]: + """Verify the displayed code, issue the cluster key, enroll the peer. + + Order is fail-closed: code verify → key wrap → SSH TOFU enrollment → + only then persist the peer as paired. If enrollment driving raises, + the peer is NOT stored; the pending request survives for a retry. + """ + + validate_pairing_code(code) + with self._lock: + now = self._clock() + # Expire *other* pending requests, but keep this one long enough + # to report a precise "expired" instead of a generic "no pending". + self._prune_pending(now, keep=node_id) + pending = self._pending.get(node_id) + if pending is None: + if node_id in self._denied: + raise PairingStateError("this join request was denied") + raise PairingStateError("no pending join request for this node_id") + if pending.expires_at < now: + del self._pending[node_id] + self._record_audit("join_request_expired", node_id=node_id) + raise PairingExpiredError("the pairing code has expired") + if pending.approving: + raise PairingStateError("approval is already in progress") + if pending.locked_until is not None and pending.locked_until > now: + self._record_audit( + "approve_locked_out", + node_id=node_id, + detail={"retry_after": pending.locked_until}, + ) + raise PairingLockoutError( + f"too many wrong codes; locked until {pending.locked_until:.0f}" + ) + if pending.locked_until is not None and pending.locked_until <= now: + # Lockout served: fresh set of attempts, code still valid by TTL. + pending.locked_until = None + pending.attempts = 0 + expected = pairing_code_hash( + code, + node_id, + pending.ssh_public_key or "", + pending.ssh_host_public_key, + pending.code_salt, + ) + if not hmac.compare_digest(expected, pending.code_hash): + pending.attempts += 1 + detail = {"attempts": pending.attempts} + if pending.attempts >= MAX_CODE_ATTEMPTS: + pending.locked_until = now + LOCKOUT_SECONDS + detail["locked_until"] = pending.locked_until + self._record_audit( + "approve_lockout", node_id=node_id, detail=detail + ) + raise PairingLockoutError( + f"too many wrong codes; locked until {pending.locked_until:.0f}" + ) + self._record_audit("approve_wrong_code", node_id=node_id, detail=detail) + raise PairingCodeError( + f"code does not match ({MAX_CODE_ATTEMPTS - pending.attempts} " + "attempts left)" + ) + # Reserve this exact pending request before leaving the manager + # lock for SSH I/O. Deny, unpair, and duplicate approval must not + # race an enrollment that has already passed code verification. + pending.approving = True + + try: + coordinator_material = self.local_ssh_material() + except Exception as exc: + self._record_audit( + "approve_enrollment_failed", + node_id=node_id, + detail={"error": str(exc)}, + ) + with self._lock: + if self._pending.get(node_id) is pending: + pending.approving = False + raise EnrollmentDriveError( + f"SSH enrollment failed; peer was not paired: {exc}" + ) from exc + + cluster_key = secrets.token_bytes(CLUSTER_KEY_BYTES) + package = wrap_cluster_key(cluster_key, code) + coordinator_tag = coordinator_identity_tag( + cluster_key, + coordinator_material, + ) + + peer = { + "node_id": pending.node_id, + "friendly_name": pending.friendly_name, + "caps": pending.caps, + "addrs": list(pending.addrs), + "http_port": pending.http_port, + "ssh_public_key": pending.ssh_public_key, + "ssh_host_public_key": pending.ssh_host_public_key, + } + try: + enrollment = self._enrollment_driver(peer) + except Exception as exc: + self._record_audit( + "approve_enrollment_failed", node_id=node_id, detail={"error": str(exc)} + ) + with self._lock: + if self._pending.get(node_id) is pending: + pending.approving = False + raise EnrollmentDriveError( + f"SSH enrollment failed; peer was not paired: {exc}" + ) from exc + + paired_at = self._clock() + record = { + "node_id": pending.node_id, + "friendly_name": pending.friendly_name, + "caps": pending.caps, + "paired_at": paired_at, + "last_addrs": list(pending.addrs), + "state": "paired", + "role": "peer", + } + key_record = { + "cluster_key": cluster_key.hex(), + # The joiner retrieves this package via pair/status and unwraps it + # with the code; safe to persist (0600) and serve. + "cluster_key_package": package, + "coordinator": coordinator_material, + "coordinator_identity_tag": coordinator_tag, + "peer_public_key": pending.ssh_public_key, + "addrs": list(pending.addrs), + "paired_at": paired_at, + "role": "peer", + } + key_written = False + try: + with self._lock: + if self._pending.get(node_id) is not pending or not pending.approving: + raise PairingStateError( + "join request changed while approval was in progress" + ) + self._key_store.set(pending.node_id, key_record) + key_written = True + self._devices.put_paired(record) + self._pending.pop(node_id, None) + except Exception as exc: + rollback_errors: list[str] = [] + if key_written: + try: + self._key_store.remove(pending.node_id) + except Exception as rollback_exc: + rollback_errors.append(f"pairing key: {rollback_exc}") + try: + self._revocation_driver( + { + "peer_public_key": pending.ssh_public_key, + "addrs": list(pending.addrs), + } + ) + except Exception as rollback_exc: + rollback_errors.append(f"SSH enrollment: {rollback_exc}") + with self._lock: + if self._pending.get(node_id) is pending: + pending.approving = False + detail = {"error": str(exc), "rollback_errors": rollback_errors} + self._record_audit( + "approve_persistence_failed", + node_id=node_id, + detail=detail, + ) + suffix = ( + "; rollback issues: " + "; ".join(rollback_errors) + if rollback_errors + else "" + ) + raise PairingError( + f"pairing state could not be persisted; peer was not paired: " + f"{exc}{suffix}" + ) from exc + self._record_audit( + "approve_success", + node_id=node_id, + detail={"friendly_name": pending.friendly_name}, + ) + return { + "node_id": node_id, + "state": "paired", + "paired_at": paired_at, + "cluster_key_package": package, + "coordinator": coordinator_material, + "coordinator_identity_tag": coordinator_tag, + "enrollment": enrollment, + } + + def deny(self, node_id: str) -> bool: + """Refuse a pending request; the joiner sees ``denied`` on its next poll.""" + + with self._lock: + now = self._clock() + self._prune_pending(now) + pending = self._pending.get(node_id) + if pending is None: + return False + if pending.approving: + raise PairingStateError("approval is already in progress") + self._pending.pop(node_id, None) + self._denied[node_id] = now + self._record_audit("join_request_denied", node_id=node_id) + return True + + def join_status(self, node_id: str) -> dict[str, Any]: + """Coordinator-side status consumed by the joiner's poll loop. + + The wrapped cluster key is safe to serve here: it is encrypted under + a PBKDF2 key derived from the code only the joiner operator can see. + """ + + with self._lock: + now = self._clock() + self._prune_pending(now) + pending = self._pending.get(node_id) + denied = node_id in self._denied + if pending is not None: + return pending.to_dict(now) + key_record = self._key_store.get(node_id) + if key_record is not None: + device = self._devices.get(node_id) or {} + status: dict[str, Any] = { + "node_id": node_id, + "state": "approved", + "paired_at": key_record.get("paired_at"), + # Same coordinator block approve() returns: the joiner + # persists it via complete_join, so caps/ssh key must ride + # here too — the poll path is the only one the UI drives. + "coordinator": key_record.get("coordinator") or {}, + "coordinator_identity_tag": key_record.get("coordinator_identity_tag"), + } + package = key_record.get("cluster_key_package") + if package is not None: + status["cluster_key_package"] = package + if device: + status["friendly_name"] = device.get("friendly_name") + return status + if denied: + return {"node_id": node_id, "state": "denied"} + return {"node_id": node_id, "state": "unknown"} + + def unpair(self, node_id: str) -> dict[str, Any]: + """Remove a paired device and revoke the trust installed at pairing. + + Registry removal is the trust anchor and happens first (fail-closed); + SSH material retraction is best-effort and reported, never raised. + Also drops any legacy ``enrolled-nodes.json`` entry with the same + node_id so both trusted-node inventories stay in step. + """ + + with self._lock: + now = self._clock() + self._prune_pending(now) + pending = self._pending.get(node_id) + if pending is not None and pending.approving: + raise PairingStateError("approval is already in progress") + was_pending = self._pending.pop(node_id, None) is not None + device = self._devices.get(node_id) + removed_device = self._devices.remove(node_id) + key_record = self._key_store.get(node_id) + if key_record is not None: + self._key_store.remove(node_id) + if not (removed_device or key_record or was_pending): + raise PairingStateError("unknown device") + + removed_enrollment = False + if self._enrollment_store is not None: + remove_node = getattr(self._enrollment_store, "remove_node", None) + if callable(remove_node): + with suppress(Exception): + removed_enrollment = bool(remove_node(node_id)) + + revocation: dict[str, Any] = {"authorized_key_removed": False, "errors": []} + material = { + "peer_public_key": (key_record or {}).get("peer_public_key"), + "addrs": (key_record or {}).get("addrs") + or (device or {}).get("last_addrs") + or [], + } + if material["peer_public_key"] or material["addrs"]: + try: + revocation = self._revocation_driver(material) or revocation + except Exception as exc: + revocation["errors"].append(str(exc)) + + self._record_audit( + "device_unpaired", + node_id=node_id, + detail={ + "removed_device": removed_device, + "removed_key": key_record is not None, + "removed_enrollment": removed_enrollment, + "was_pending": was_pending, + }, + ) + return { + "node_id": node_id, + "unpaired": True, + "removed_device": removed_device, + "removed_key": key_record is not None, + "removed_enrollment": removed_enrollment, + "was_pending": was_pending, + "revocation": revocation, + } + + def paired_devices(self) -> list[dict[str, Any]]: + """Persisted paired devices (discovered-but-unpaired never land here).""" + + return self._devices.list_paired() + + def devices_view(self) -> dict[str, Any]: + """Coordinator devices list: paired + awaiting_approval + self.""" + + return { + "paired": self.paired_devices(), + "pending": self.pending_requests(), + "self": { + "node_id": self.node_id, + "friendly_name": self.friendly_name, + "caps": self._caps_provider() if self._caps_provider else {}, + }, + } + + +# --- Configured singleton (mirrors enrollment.py's configure/get pattern) ---- + +_manager_lock = threading.Lock() +_configured_manager: PairingManager | None = None + + +def configure_pairing_manager( + base_path: Path, + *, + registry: Any = None, + enrollment_store: Any = None, + **kwargs: Any, +) -> PairingManager: + """Create the process-wide manager at server startup. + + ``registry`` should be Module A's ``DeviceRegistry`` once that branch is + integrated; until then ``None`` selects the schema-compatible fallback. + """ + + global _configured_manager + with _manager_lock: + _configured_manager = PairingManager( + registry, + enrollment_store, + base_path=base_path, + **kwargs, + ) + return _configured_manager + + +def get_pairing_manager() -> PairingManager: + with _manager_lock: + if _configured_manager is None: + raise RuntimeError("cluster pairing is not configured") + return _configured_manager + + +def reset_pairing_manager() -> None: + """Test hook: drop the configured manager so tests stay isolated.""" + + global _configured_manager + with _manager_lock: + _configured_manager = None diff --git a/omlx/cluster/pairing_routes.py b/omlx/cluster/pairing_routes.py new file mode 100644 index 0000000000..cd40c2d374 --- /dev/null +++ b/omlx/cluster/pairing_routes.py @@ -0,0 +1,184 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Cluster v2 pairing endpoints (Module B). + +Two routers, both under ``/api/cluster`` (the v2 surface; the legacy 3-step +copy-paste endpoints stay untouched under ``/admin/api/cluster`` as +"Advanced (legacy)"): + +* ``pair_router`` — unauthenticated joiner-facing endpoints. The pair request + carries a salted PBKDF2 verifier binding the node and both SSH identities, + and the coordinator binds enrollment to the HTTP source address. The served + cluster key is separately encrypted under a code-derived key, so the admin's + approve step remains the sole trust decision. +* ``pair_admin_router`` — admin-facing approve/deny/unpair. Mounted with + ``Depends(require_admin)`` exactly like the existing cluster router. + +Both are wired in ``omlx/server.py:_register_cluster_routes``. +""" + +from __future__ import annotations + +import asyncio +import ipaddress +from typing import Any + +from fastapi import APIRouter, HTTPException, Request +from pydantic import BaseModel, ConfigDict, Field + +from .discovery_routes import ProbeRateLimiter +from .pairing import ( + CODE_DIGITS, + EnrollmentDriveError, + PairingCodeError, + PairingError, + PairingExpiredError, + PairingLockoutError, + PairingManager, + PairingStateError, + get_pairing_manager, +) + +pair_router = APIRouter(prefix="/api/cluster", tags=["cluster-v2-pairing"]) +pair_admin_router = APIRouter(prefix="/api/cluster", tags=["cluster-v2-pairing-admin"]) + +_get_pairing_manager: Any = get_pairing_manager +pair_request_rate_limiter = ProbeRateLimiter(rate_per_second=0.5, burst=8) +pair_status_rate_limiter = ProbeRateLimiter(rate_per_second=5.0, burst=20) + + +def set_pairing_manager_getter(getter: Any) -> None: + """Inject the server-owned manager without importing ``omlx.server``.""" + + global _get_pairing_manager + _get_pairing_manager = getter + + +def _manager() -> PairingManager: + try: + return _get_pairing_manager() + except RuntimeError as exc: + raise HTTPException(status_code=503, detail=str(exc)) from exc + + +class PairRequestBody(BaseModel): + model_config = ConfigDict(extra="forbid") + + node_id: str = Field(min_length=1, max_length=255) + friendly_name: str = Field(min_length=1, max_length=255) + caps: dict[str, Any] = Field(default_factory=dict) + code_hash: str = Field(pattern=r"^[a-f0-9]{64}$") + code_salt: str = Field(min_length=24, max_length=64) + http_port: int | None = Field(default=None, ge=1, le=65535) + addrs: list[str] = Field(default_factory=list, max_length=8) + ssh_public_key: str = Field(min_length=32, max_length=8192) + ssh_host_public_key: str = Field(min_length=32, max_length=8192) + + +class PairApproveBody(BaseModel): + model_config = ConfigDict(extra="forbid") + + node_id: str = Field(min_length=1, max_length=255) + code: str = Field(pattern=rf"^[0-9]{{{CODE_DIGITS}}}$") + + +class PairDenyBody(BaseModel): + model_config = ConfigDict(extra="forbid") + + node_id: str = Field(min_length=1, max_length=255) + + +def _pairing_http_error(exc: PairingError) -> HTTPException: + if isinstance(exc, PairingLockoutError): + return HTTPException(status_code=423, detail=str(exc)) + if isinstance(exc, PairingExpiredError): + return HTTPException(status_code=410, detail=str(exc)) + if isinstance(exc, PairingCodeError): + return HTTPException(status_code=403, detail=str(exc)) + if isinstance(exc, EnrollmentDriveError): + return HTTPException(status_code=502, detail=str(exc)) + if isinstance(exc, PairingStateError): + return HTTPException(status_code=404, detail=str(exc)) + return HTTPException(status_code=400, detail=str(exc)) + + +@pair_router.post("/pair/request", status_code=202) +async def cluster_pair_request(body: PairRequestBody, request: Request): + """Register a joiner's request as awaiting_approval (code never crosses).""" + + manager = _manager() + payload = body.model_dump() + source = request.client.host if request.client is not None else "" + if not pair_request_rate_limiter.allow(source or "unknown"): + raise HTTPException(status_code=429, detail="pair request rate limit exceeded") + try: + ipaddress.ip_address(source.split("%", 1)[0]) + except ValueError: + payload["addrs"] = [] + else: + # Never enroll an arbitrary address supplied in the public JSON body. + # The HTTP source is the only coordinator-observed endpoint. + payload["addrs"] = [source] + try: + snapshot = await asyncio.to_thread(manager.handle_join_request, payload) + except PairingError as exc: + raise _pairing_http_error(exc) from exc + return snapshot + + +@pair_router.get("/pair/status/{node_id}") +async def cluster_pair_status(node_id: str, request: Request): + """Joiner poll: pending/approved/denied plus the wrapped cluster key.""" + + manager = _manager() + source = request.client.host if request.client is not None else "" + if not pair_status_rate_limiter.allow(source or "unknown"): + raise HTTPException(status_code=429, detail="pair status rate limit exceeded") + if not node_id or len(node_id) > 255: + raise HTTPException(status_code=400, detail="invalid node_id") + return await asyncio.to_thread(manager.join_status, node_id) + + +@pair_admin_router.post("/pair/approve") +async def cluster_pair_approve(body: PairApproveBody): + """Type the code shown on the joiner; verify, issue cluster key, enroll.""" + + manager = _manager() + try: + result = await asyncio.to_thread(manager.approve, body.node_id, body.code) + except PairingError as exc: + raise _pairing_http_error(exc) from exc + try: + from .discovery import get_discovery_service + + get_discovery_service().mark_paired(body.node_id) + except Exception: + # Pairing remains authoritative when discovery is disabled or stopped. + pass + return result + + +@pair_admin_router.post("/pair/deny") +async def cluster_pair_deny(body: PairDenyBody): + """Refuse a pending join request (audit-logged).""" + + manager = _manager() + try: + denied = await asyncio.to_thread(manager.deny, body.node_id) + except PairingError as exc: + raise _pairing_http_error(exc) from exc + if not denied: + raise HTTPException(status_code=404, detail="no pending join request") + return {"ok": True, "node_id": body.node_id, "state": "denied"} + + +@pair_admin_router.delete("/devices/{node_id}") +async def cluster_unpair_device(node_id: str): + """Unpair: drop the registry entry, the cluster key, and SSH trust.""" + + manager = _manager() + if not node_id or len(node_id) > 255: + raise HTTPException(status_code=400, detail="invalid node_id") + try: + return await asyncio.to_thread(manager.unpair, node_id) + except PairingError as exc: + raise _pairing_http_error(exc) from exc diff --git a/omlx/cluster/registry.py b/omlx/cluster/registry.py index 64fe34ee98..ccaf5c9b5d 100644 --- a/omlx/cluster/registry.py +++ b/omlx/cluster/registry.py @@ -58,8 +58,7 @@ def _load(self) -> None: ClusterDeployment.from_dict(item) for item in raw_deployments ] self._deployments = { - _model_key(deployment.model): deployment - for deployment in deployments + _model_key(deployment.model): deployment for deployment in deployments } if len(self._deployments) != len(deployments): raise ValueError("cluster deployment registry has duplicate models") @@ -94,8 +93,7 @@ def _save(self) -> None: def list(self) -> tuple[ClusterDeployment, ...]: with self._lock: return tuple( - deployment - for _, deployment in sorted(self._deployments.items()) + deployment for _, deployment in sorted(self._deployments.items()) ) def get_for_model(self, model: str) -> ClusterDeployment | None: @@ -176,3 +174,419 @@ def get_cluster_registry() -> ClusterRegistry: if _configured_registry is None: raise RuntimeError("cluster registry is not configured") return _configured_registry + + +# --------------------------------------------------------------------------- +# Cluster v2: trusted device inventory (paired nodes) + discovered device cache +# --------------------------------------------------------------------------- + +import time # noqa: E402 + + +def default_devices_path() -> Path: + """Default on-disk location, honoring the OMLX_BASE_PATH override.""" + + env_value = os.environ.get("OMLX_BASE_PATH") + base = Path(env_value).expanduser() if env_value else Path.home() / ".omlx" + return base / "cluster" / "devices.json" + + +class DeviceRegistry: + """Inventory of cluster devices. + + *Paired* devices are trusted and persisted atomically (mode 0600) to + ``devices.json`` (schema_version 1). *Discovered-but-unpaired* devices + are kept in memory only — an untrusted announcer must never gain a + persisted foothold merely by showing up on the LAN. + + The merge API is consumed by both discovery (continuous upserts of + announced metadata) and pairing (marking a node trusted). Merge never + downgrades a paired device back to discovered, and dedupes on + ``node_id``. + """ + + def __init__(self, path: Path | str | None = None) -> None: + self.path = Path(path) if path is not None else default_devices_path() + self._lock = threading.RLock() + self._paired: dict[str, dict[str, Any]] = {} + self._discovered: dict[str, dict[str, Any]] = {} + self.load_error: str | None = None + try: + self._load() + except ValueError as exc: + # Mirror ClusterRegistry: a corrupt optional file must never + # prevent the server from starting. Fail closed, trust nobody. + self._paired = {} + self.load_error = str(exc) + + def _load(self) -> None: + with self._lock: + if not self.path.exists(): + self._paired = {} + return + try: + payload = json.loads(self.path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + raise ValueError( + f"could not read cluster device registry: {exc}" + ) from exc + if not isinstance(payload, dict) or payload.get("schema_version") != 1: + raise ValueError("unsupported cluster device registry schema") + raw_devices = payload.get("devices") + if not isinstance(raw_devices, list): + raise ValueError("cluster device registry is malformed") + devices: dict[str, dict[str, Any]] = {} + for item in raw_devices: + device = self._validate_paired(item) + devices[device["node_id"]] = device + if len(devices) != len(raw_devices): + raise ValueError("cluster device registry has duplicate node_ids") + self._paired = devices + + @staticmethod + def _validate_paired(item: Any) -> dict[str, Any]: + if not isinstance(item, dict): + raise ValueError("cluster device entry is malformed") + node_id = item.get("node_id") + friendly_name = item.get("friendly_name") + paired_at = item.get("paired_at") + if not isinstance(node_id, str) or not node_id: + raise ValueError("cluster device entry is missing a node_id") + if not isinstance(friendly_name, str) or not friendly_name: + raise ValueError("cluster device entry is missing a friendly_name") + if not isinstance(paired_at, (int, float)): + raise ValueError("cluster device entry is missing paired_at") + caps = item.get("caps") + last_addrs = item.get("last_addrs") + device = { + "node_id": node_id, + "friendly_name": friendly_name, + "caps": dict(caps) if isinstance(caps, dict) else {}, + "paired_at": float(paired_at), + "last_addrs": [str(a) for a in last_addrs if isinstance(a, str)][:16] + if isinstance(last_addrs, list) + else [], + } + http_port = item.get("http_port") + if http_port is not None: + if ( + not isinstance(http_port, int) + or isinstance(http_port, bool) + or not 1 <= http_port <= 65535 + ): + raise ValueError("cluster device entry has an invalid HTTP port") + device["http_port"] = http_port + return device + + def _save(self) -> None: + self.path.parent.mkdir(parents=True, exist_ok=True) + payload = { + "schema_version": 1, + "devices": [self._paired[key] for key in sorted(self._paired)], + } + descriptor, temporary = tempfile.mkstemp( + prefix=".devices.", suffix=".tmp", dir=self.path.parent + ) + try: + os.fchmod(descriptor, 0o600) + with os.fdopen(descriptor, "w", encoding="utf-8") as stream: + json.dump(payload, stream, indent=2, sort_keys=True) + stream.write("\n") + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, self.path) + os.chmod(self.path, 0o600) + finally: + with suppress(FileNotFoundError): + os.unlink(temporary) + + # -- merge API (discovery + pairing) ------------------------------------ + + @staticmethod + def _merge_caps( + existing: dict[str, Any], incoming: dict[str, Any] + ) -> dict[str, Any]: + """Field-wise non-downgrading caps merge. + + A discovery HELLO carries a structurally complete but value-empty + caps dict (``{"chip": "", "ram_gb": 0.0, ...}``); a truthiness check + would let it clobber the real capabilities exchanged at pairing. + Only real values win: non-empty chip, non-zero ram_gb, the union of + backends, and sticky-true fabric flags. + """ + + merged = dict(existing) + if incoming.get("chip"): + merged["chip"] = incoming["chip"] + if incoming.get("ram_gb"): + merged["ram_gb"] = incoming["ram_gb"] + backends = incoming.get("backends") + if backends: + merged["backends"] = sorted( + set(existing.get("backends") or []) | set(backends) + ) + for flag in ("thunderbolt", "jaccl"): + # Sticky-true, but never introduce the key out of nowhere — + # records that never had fabric flags keep their shape. + if existing.get(flag) or incoming.get(flag) or flag in existing: + merged[flag] = bool(existing.get(flag)) or bool(incoming.get(flag)) + for key, value in incoming.items(): + if key not in merged and value: + merged[key] = value + return merged + + @staticmethod + def _merge_addrs(existing: list[str], incoming: list[str]) -> list[str]: + """Union, preserving order — a later sparse announcement must not + drop routable addresses the pairing recorded.""" + + merged = list(existing) + for ip in incoming: + if ip not in merged: + merged.append(ip) + return merged[:16] + + def merge( + self, + device: Any, + *, + paired_at: float | None = None, + ) -> dict[str, Any]: + """Upsert announced device metadata, keyed on ``node_id``. + + Accepts any object/dict with ``node_id`` and optional + ``friendly_name``/``caps``/``addrs`` or ``last_addrs`` (a discovery + ``PeerRecord`` works as-is). Updates to an already-paired device are + persisted; updates to an unpaired device stay memory-only. Merges + never downgrade: empty announced fields cannot erase known ones. + """ + + record = self._coerce(device) + node_id = record["node_id"] + with self._lock: + if node_id in self._paired: + merged = self._paired[node_id] + if record.get("friendly_name"): + merged["friendly_name"] = record["friendly_name"] + if record.get("caps"): + merged["caps"] = self._merge_caps( + dict(merged.get("caps") or {}), record["caps"] + ) + if record.get("last_addrs"): + merged["last_addrs"] = self._merge_addrs( + list(merged.get("last_addrs") or []), record["last_addrs"] + ) + if record.get("http_port"): + merged["http_port"] = record["http_port"] + if paired_at is not None: + merged["paired_at"] = float(paired_at) + previous = dict(self._paired) + try: + self._save() + except Exception: + self._paired = previous + raise + self.load_error = None + return dict(merged) + merged = self._discovered.get(node_id, {"node_id": node_id}) + if record.get("friendly_name"): + merged["friendly_name"] = record["friendly_name"] + if record.get("caps"): + merged["caps"] = self._merge_caps( + dict(merged.get("caps") or {}), record["caps"] + ) + if record.get("last_addrs"): + merged["last_addrs"] = self._merge_addrs( + list(merged.get("last_addrs") or []), record["last_addrs"] + ) + if record.get("http_port"): + merged["http_port"] = record["http_port"] + self._discovered[node_id] = merged + return dict(merged) + + @staticmethod + def _coerce(device: Any) -> dict[str, Any]: + if isinstance(device, dict): + record = dict(device) + else: + record = { + "node_id": getattr(device, "node_id", None), + "friendly_name": getattr(device, "friendly_name", None), + "caps": getattr(device, "caps", None), + "http_port": getattr(device, "http_port", None), + } + addrs = getattr(device, "addrs", None) + if addrs is not None: + record["last_addrs"] = [ + a.get("ip") if isinstance(a, dict) else getattr(a, "ip", None) + for a in addrs + ] + node_id = record.get("node_id") + if not isinstance(node_id, str) or not node_id: + raise ValueError("device record is missing a node_id") + if "last_addrs" not in record and isinstance(record.get("addrs"), list): + record["last_addrs"] = [ + a.get("ip") if isinstance(a, dict) else a for a in record["addrs"] + ] + caps = record.get("caps") + if caps is not None and not isinstance(caps, dict): + caps = caps.to_dict() if hasattr(caps, "to_dict") else {} + normalized: dict[str, Any] = {"node_id": node_id} + if isinstance(record.get("friendly_name"), str): + normalized["friendly_name"] = record["friendly_name"] + if isinstance(caps, dict): + normalized["caps"] = dict(caps) + addrs = record.get("last_addrs") + if isinstance(addrs, list): + normalized["last_addrs"] = [str(a) for a in addrs if isinstance(a, str)][ + :16 + ] + http_port = record.get("http_port") + if http_port is not None and http_port != 0 and http_port != "": + if ( + not isinstance(http_port, int) + or isinstance(http_port, bool) + or not 1 <= http_port <= 65535 + ): + raise ValueError("device record has an invalid HTTP port") + normalized["http_port"] = http_port + return normalized + + def mark_paired( + self, + node_id: str, + *, + friendly_name: str | None = None, + caps: dict[str, Any] | None = None, + addrs: list[str] | None = None, + http_port: int | None = None, + paired_at: float | None = None, + ) -> dict[str, Any]: + """Promote a device to trusted/paired and persist it.""" + + with self._lock: + existing = self._paired.get(node_id) or self._discovered.get(node_id, {}) + if http_port is not None and ( + not isinstance(http_port, int) + or isinstance(http_port, bool) + or not 1 <= http_port <= 65535 + ): + raise ValueError("paired device HTTP port is invalid") + device = { + "node_id": node_id, + "friendly_name": friendly_name + or existing.get("friendly_name") + or node_id, + "caps": dict(caps) + if caps is not None + else dict(existing.get("caps") or {}), + "paired_at": float(paired_at if paired_at is not None else time.time()), + "last_addrs": list(addrs) + if addrs is not None + else list(existing.get("last_addrs") or []), + } + effective_port = http_port or existing.get("http_port") + if effective_port: + device["http_port"] = int(effective_port) + previous = dict(self._paired) + self._paired[node_id] = device + self._discovered.pop(node_id, None) + try: + self._save() + except Exception: + self._paired = previous + raise + self.load_error = None + return dict(device) + + def unpair(self, node_id: str) -> bool: + """Revoke trust. The device drops back to memory-only if re-seen.""" + + with self._lock: + if node_id not in self._paired: + return False + previous = dict(self._paired) + device = self._paired.pop(node_id) + try: + self._save() + except Exception: + self._paired = previous + raise + # Keep a memory-only discovered shell so the UI can still show + # the now-untrusted device if it is still announcing. + shell = { + "node_id": node_id, + "friendly_name": device["friendly_name"], + "caps": device["caps"], + "last_addrs": device["last_addrs"], + } + if device.get("http_port"): + shell["http_port"] = device["http_port"] + self._discovered.setdefault( + node_id, + shell, + ) + return True + + # -- reads --------------------------------------------------------------- + + def paired(self) -> list[dict[str, Any]]: + with self._lock: + return [dict(self._paired[key]) for key in sorted(self._paired)] + + def discovered(self) -> list[dict[str, Any]]: + """Unpaired devices (memory-only), excluding paired node_ids.""" + + with self._lock: + return [ + dict(self._discovered[key]) + for key in sorted(self._discovered) + if key not in self._paired + ] + + def get(self, node_id: str) -> dict[str, Any] | None: + with self._lock: + if node_id in self._paired: + return dict(self._paired[node_id]) + found = self._discovered.get(node_id) + return dict(found) if found is not None else None + + def is_paired(self, node_id: str) -> bool: + with self._lock: + return node_id in self._paired + + def to_dict(self) -> dict[str, Any]: + return { + "schema_version": 1, + "paired": self.paired(), + "discovered": self.discovered(), + "load_error": self.load_error, + } + + +_device_registry_lock = threading.Lock() +_configured_device_registry: DeviceRegistry | None = None + + +def configure_device_registry( + path: Path | str | None = None, +) -> DeviceRegistry: + global _configured_device_registry + with _device_registry_lock: + _configured_device_registry = DeviceRegistry(path) + return _configured_device_registry + + +def get_device_registry() -> DeviceRegistry: + with _device_registry_lock: + if _configured_device_registry is None: + raise RuntimeError("cluster device registry is not configured") + return _configured_device_registry + + +def reset_configured_device_registry() -> None: + """Test hook: drop the process-wide device registry.""" + + global _configured_device_registry + with _device_registry_lock: + _configured_device_registry = None diff --git a/omlx/cluster/routes.py b/omlx/cluster/routes.py index 06e59e97b1..ea4419dba5 100644 --- a/omlx/cluster/routes.py +++ b/omlx/cluster/routes.py @@ -1967,7 +1967,12 @@ async def cluster_discover(): @router.post("/pairing-token") async def cluster_pairing_token(request: ClusterPairingTokenRequest): - """Generate a pairing token for QR code exchange.""" + """Generate a pairing token for QR code exchange. + + Advanced (legacy): step 1 of the 3-step copy-paste relay. The cluster v2 + wizard uses POST /api/cluster/pair/request + /pair/approve instead; this + endpoint is kept working unchanged for the legacy flow. + """ from .discovery import generate_pairing_token @@ -1982,7 +1987,11 @@ async def cluster_pairing_token(request: ClusterPairingTokenRequest): async def cluster_verify_pairing_token( request: ClusterPairingTokenVerificationRequest, ): - """Verify a pairing token received via QR code scan.""" + """Verify a pairing token received via QR code scan. + + Advanced (legacy): part of the 3-step copy-paste relay; superseded by the + cluster v2 code-based pairing flow but kept working unchanged. + """ return { "valid": verify_pairing_token( @@ -2232,7 +2241,12 @@ async def cluster_generate_ssh_key( async def cluster_generate_key_exchange_token( request: ClusterKeyExchangeTokenRequest, ): - """Generate a key exchange token for pairing with a peer.""" + """Generate a key exchange token for pairing with a peer. + + Advanced (legacy): step 3 of the copy-paste relay. Cluster v2 pairing + (POST /api/cluster/pair/approve) drives the same SSH TOFU primitives + programmatically; this endpoint remains for the manual flow. + """ from .ssh_keys import generate_key_exchange_for_peer @@ -2252,7 +2266,11 @@ async def cluster_generate_key_exchange_token( @router.post("/ssh-key/exchange") async def cluster_exchange_keys(request: ClusterKeyExchangeRequest): - """Exchange SSH keys with a peer using their exchange token.""" + """Exchange SSH keys with a peer using their exchange token. + + Advanced (legacy): step 3 of the copy-paste relay; kept working unchanged + alongside the cluster v2 code-based pairing flow. + """ from .ssh_keys import exchange_keys_with_peer diff --git a/omlx/cluster/system_socket_proxy.py b/omlx/cluster/system_socket_proxy.py new file mode 100644 index 0000000000..66f90419bd --- /dev/null +++ b/omlx/cluster/system_socket_proxy.py @@ -0,0 +1,218 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Carry one local TCP stream through macOS's system Python when required. + +Some macOS installations deny a Homebrew Python process outbound access to a +direct Thunderbolt subnet while Apple's system Python can use the same address. +A bounded child bridges a loopback socket to that path; the parent retains its +normal socket API and no model data crosses this helper. +""" + +from __future__ import annotations + +import ipaddress +import os +import select +import socket +import subprocess +import sys +import time +from contextlib import suppress +from dataclasses import dataclass +from pathlib import Path + +_DEFAULT_TIMEOUT_SECONDS = 20.0 +_PROXY_PROGRAM = r""" +import socket, sys, threading, time + +def connect(host, port, timeout): + deadline = time.monotonic() + timeout + error = None + while time.monotonic() < deadline: + try: + targets = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM) + except OSError as exc: + error = exc + targets = [] + for family, socktype, protocol, _, sockaddr in targets: + remote = socket.socket(family, socktype, protocol) + try: + remote.settimeout(min(1.0, max(0.05, deadline - time.monotonic()))) + remote.connect(sockaddr) + remote.settimeout(None) + return remote + except OSError as exc: + error = exc + remote.close() + time.sleep(0.05) + raise RuntimeError("could not reach control coordinator: %s" % error) + +def copy(source, target): + try: + while True: + payload = source.recv(65536) + if not payload: + return + target.sendall(payload) + finally: + try: + target.shutdown(socket.SHUT_WR) + except OSError: + pass + +def main(): + host, port, timeout = sys.argv[1], int(sys.argv[2]), float(sys.argv[3]) + listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + try: + listener.bind(("127.0.0.1", 0)) + listener.listen(1) + print("PORT %d" % listener.getsockname()[1], flush=True) + remote = connect(host, port, timeout) + print("READY", flush=True) + local, _ = listener.accept() + finally: + listener.close() + thread = threading.Thread(target=copy, args=(remote, local), daemon=True) + thread.start() + copy(local, remote) + thread.join(timeout=1.0) + local.close() + remote.close() + +if __name__ == "__main__": + try: + main() + except BaseException as exc: + print("oMLX control socket helper failed: %s" % exc, file=sys.stderr, flush=True) + raise +""" + + +def _system_python() -> str | None: + candidate = Path( + os.environ.get("OMLX_CLUSTER_CONTROL_PROXY_PYTHON", "/usr/bin/python3") + ) + if candidate.is_file() and os.access(candidate, os.X_OK): + return str(candidate) + return None + + +def should_proxy_control_socket(host: str) -> bool: + """Whether a non-loopback control socket should use the macOS carrier.""" + + mode = os.environ.get("OMLX_CLUSTER_CONTROL_TRANSPORT", "auto").strip().lower() + if mode not in {"", "auto", "direct", "system-proxy"}: + raise RuntimeError( + "OMLX_CLUSTER_CONTROL_TRANSPORT must be auto, direct, or system-proxy" + ) + if mode == "direct": + return False + if mode == "system-proxy": + if _system_python() is None: + raise RuntimeError("system Python control proxy is unavailable") + return True + try: + loopback = ipaddress.ip_address(host).is_loopback + except ValueError: + loopback = host.strip().lower() in {"localhost", "localhost.local"} + return sys.platform == "darwin" and not loopback and _system_python() is not None + + +@dataclass +class SystemSocketProxy: + """The parent-visible loopback stream and its helper process.""" + + stream: socket.socket + process: subprocess.Popen[bytes] + + def close(self) -> None: + with suppress(OSError): + self.stream.close() + if self.process.poll() is None: + try: + self.process.wait(timeout=1.0) + except subprocess.TimeoutExpired: + self.process.terminate() + try: + self.process.wait(timeout=1.0) + except subprocess.TimeoutExpired: + self.process.kill() + self.process.wait(timeout=1.0) + + +def _helper_error(process: subprocess.Popen[bytes]) -> str: + status = process.poll() + detail = b"" + if status is not None and process.stderr is not None: + detail = process.stderr.read() + text = detail.decode("utf-8", "replace").strip() + suffix = f": {text[-1000:]}" if text else "" + return f"control socket helper stopped (status={status}){suffix}" + + +def _read_line(process: subprocess.Popen[bytes], *, deadline: float) -> bytes: + if process.stdout is None: + raise RuntimeError("control socket helper has no stdout") + while True: + remaining = deadline - time.monotonic() + if remaining <= 0: + raise TimeoutError("control socket helper did not become ready") + ready, _write, _error = select.select([process.stdout], [], [], remaining) + if ready: + line = process.stdout.readline() + if line: + return line.rstrip(b"\r\n") + raise RuntimeError(_helper_error(process)) + if process.poll() is not None: + raise RuntimeError(_helper_error(process)) + + +def open_system_tcp_proxy( + host: str, + port: int, + *, + timeout: float = _DEFAULT_TIMEOUT_SECONDS, +) -> SystemSocketProxy: + """Open a local stream bridged to ``host:port`` by system Python.""" + + if not 1 <= int(port) <= 65535 or timeout <= 0: + raise ValueError("control socket proxy endpoint is invalid") + executable = _system_python() + if executable is None: + raise RuntimeError("system Python control proxy is unavailable") + process = subprocess.Popen( + [executable, "-u", "-c", _PROXY_PROGRAM, host, str(port), str(timeout)], + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + bufsize=0, + ) + stream: socket.socket | None = None + try: + deadline = time.monotonic() + timeout + port_line = _read_line(process, deadline=deadline) + label, separator, value = port_line.partition(b" ") + if label != b"PORT" or not separator or not value.isdigit(): + raise RuntimeError("control socket helper returned an invalid port") + local_port = int(value) + stream = socket.create_connection( + ("127.0.0.1", local_port), + timeout=max(0.05, deadline - time.monotonic()), + ) + if _read_line(process, deadline=deadline) != b"READY": + raise RuntimeError("control socket helper did not reach its coordinator") + return SystemSocketProxy(stream=stream, process=process) + except BaseException: + if stream is not None: + stream.close() + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=1.0) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=1.0) + raise + + +__all__ = ["SystemSocketProxy", "open_system_tcp_proxy", "should_proxy_control_socket"] diff --git a/omlx/server.py b/omlx/server.py index 094291ddf9..856b6cfc96 100644 --- a/omlx/server.py +++ b/omlx/server.py @@ -465,6 +465,48 @@ async def _bonjour_supervisor() -> None: bonjour_task = asyncio.create_task(_bonjour_supervisor()) + # Cluster v2: always-on peer discovery (mDNS + IPv6 multicast fallback + + # manual + Tailscale). Best-effort: discovery failures must never block + # serving. OMLX_DISCOVERY=0 disables it for hostile networks. + discovery_service = None + if ( + distributed_inference_enabled() + and os.environ.get("OMLX_DISCOVERY", "1").strip().lower() + not in {"0", "false", "no", "off"} + ): + try: + from .cluster.discovery import ( + DiscoveryConfig, + DiscoveryService, + configure_discovery_service, + load_cluster_name, + ) + from .cluster.identity import get_node_identity + from .cluster.registry import get_device_registry + + cluster_base = ( + Path(_server_state.global_settings.base_path) + if _server_state.global_settings is not None + else Path.home() / ".omlx" + ) + discovery_service = DiscoveryService( + get_node_identity(), + get_device_registry(), + DiscoveryConfig( + cluster_name=load_cluster_name(cluster_base), + http_port=( + _server_state.global_settings.server.port + if _server_state.global_settings is not None + else 8000 + ) + ), + ) + configure_discovery_service(discovery_service) + await asyncio.to_thread(discovery_service.start) + except Exception as exc: # pragma: no cover - defensive + logger.warning("Cluster discovery service failed to start: %s", exc) + discovery_service = None + # Start process memory enforcer if configured if ( _server_state.global_settings is not None @@ -571,6 +613,14 @@ async def _ttl_check_loop(): await bonjour_task if bonjour_publisher is not None: bonjour_publisher.stop() + if discovery_service is not None: + try: + from .cluster.discovery import configure_discovery_service + + await asyncio.to_thread(discovery_service.stop) + configure_discovery_service(None) + except Exception as exc: # pragma: no cover - defensive + logger.warning("Cluster discovery service failed to stop: %s", exc) if preload_task is not None and not preload_task.done(): # SIGTERM arrived while pinned models were still loading. Cancel the # await; engine_pool.shutdown() below unloads whatever finished. @@ -684,6 +734,32 @@ def _register_cluster_routes() -> None: cluster_join_router, dependencies=[Depends(require_distributed_inference_enabled)], ) + # Cluster v2: /api/cluster/node_id is a deliberately unauthenticated, + # rate-limited probe peers use to verify announced addresses before any + # pairing trust exists; /api/cluster/devices requires admin per-route. + from .cluster.discovery_routes import discovery_router + + app.include_router( + discovery_router, + dependencies=[Depends(require_distributed_inference_enabled)], + ) + # Cluster v2 pairing (Module B): pair/request carries only a salted PBKDF2 + # verifier bound to the node and SSH identities; pair/status returns a + # code-encrypted cluster key only after admin approval. Approve, deny, and + # unpair are admin-only like every other cluster mutation. + from .cluster.pairing_routes import pair_admin_router, pair_router + + app.include_router( + pair_router, + dependencies=[Depends(require_distributed_inference_enabled)], + ) + app.include_router( + pair_admin_router, + dependencies=[ + Depends(require_admin), + Depends(require_distributed_inference_enabled), + ], + ) _cluster_routes_registered = True @@ -1979,15 +2055,48 @@ def init_server( _server_state.engine_pool = EnginePool( scheduler_config=scheduler_config, ) - from .cluster.enrollment import configure_cluster_enrollment + from .cluster.enrollment import configure_cluster_enrollment, get_cluster_enrollment from .cluster.incidents import configure_cluster_incidents - from .cluster.registry import configure_cluster_registry + from .cluster.pairing import configure_pairing_manager + from .cluster.registry import ( + configure_cluster_registry, + configure_device_registry, + get_device_registry, + ) from .cluster.strategy_benchmarks import configure_strategy_benchmark_store _server_state.engine_pool._cluster_registry = configure_cluster_registry(base_path) configure_cluster_enrollment(base_path) configure_cluster_incidents(base_path) configure_strategy_benchmark_store(base_path) + # Cluster v2: stable node identity + trusted device inventory. Best + # effort — a failure here must never block local inference. Configured + # before the pairing manager so pairing approvals persist into the real + # device registry instead of the schema-compatible fallback store. + try: + from .cluster.identity import configure_node_identity + + configure_node_identity(base_path) + configure_device_registry(base_path / "cluster" / "devices.json") + except Exception as exc: # pragma: no cover - defensive + logger.warning("Cluster v2 identity/device stores unavailable: %s", exc) + try: + device_registry = get_device_registry() + except RuntimeError: + device_registry = None + # Cluster v2 pairing manager, bridged onto Module A's DeviceRegistry when + # available (DeviceRegistryBridge adapts the API and fails loudly on + # drift); otherwise the schema-compatible fallback store is used. Resolve + # capabilities lazily because the discovery service starts later. + from .cluster.discovery import announced_addrs, announced_caps + + configure_pairing_manager( + base_path, + registry=device_registry, + enrollment_store=get_cluster_enrollment(), + caps_provider=announced_caps, + address_provider=announced_addrs, + ) # Discover models (use pinned models from settings file) _server_state.engine_pool._settings_manager = _server_state.settings_manager diff --git a/pyproject.toml b/pyproject.toml index 9430104b57..937b2a5330 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -148,6 +148,13 @@ grammar = [ mcp = [ "mcp>=2.0.0,<3", ] +cluster = [ + # mDNS advertise/browse for cluster v2 peer discovery (_omlx._tcp.local.). + # Pure-Python; works in launchd agents. Absence disables mDNS only — the + # IPv6 multicast fallback, manual peer add, and Tailscale paths keep + # working (see omlx/cluster/discovery.py). + "zeroconf>=0.131.0", +] modelscope = [ "modelscope>=1.10.0", ] diff --git a/tests/test_cluster_device_registry.py b/tests/test_cluster_device_registry.py new file mode 100644 index 0000000000..b3e08a80e7 --- /dev/null +++ b/tests/test_cluster_device_registry.py @@ -0,0 +1,289 @@ +# SPDX-License-Identifier: Apache-2.0 + +import stat + +import pytest + +from omlx.cluster.registry import ( + DeviceRegistry, + configure_device_registry, + get_device_registry, + reset_configured_device_registry, +) + + +def _announce(node_id: str, name: str, **extra): + record = { + "node_id": node_id, + "friendly_name": name, + "caps": {"chip": "M3 Ultra", "ram_gb": 96}, + "addrs": [{"ip": "fe80::1", "if_type": "ethernet"}], + } + record.update(extra) + return record + + +def test_discovered_devices_are_memory_only(tmp_path): + path = tmp_path / "devices.json" + registry = DeviceRegistry(path) + + registry.merge(_announce("node-a", "studio-a")) + + assert registry.discovered() == [ + { + "node_id": "node-a", + "friendly_name": "studio-a", + "caps": {"chip": "M3 Ultra", "ram_gb": 96}, + "last_addrs": ["fe80::1"], + } + ] + assert registry.paired() == [] + # Nothing was persisted for an untrusted announcer. + assert not path.exists() + restored = DeviceRegistry(path) + assert restored.discovered() == [] + assert restored.paired() == [] + + +def test_unpaired_http_endpoint_never_gains_a_persisted_foothold(tmp_path): + path = tmp_path / "devices.json" + registry = DeviceRegistry(path) + + registry.merge( + _announce( + "node-a", + "studio-a", + http_port=9123, + addrs=[{"ip": "10.0.0.2", "if_type": "manual"}], + ) + ) + + assert registry.discovered()[0]["http_port"] == 9123 + assert not path.exists() + assert DeviceRegistry(path).discovered() == [] + + +def test_merge_dedupes_on_node_id(tmp_path): + registry = DeviceRegistry(tmp_path / "devices.json") + + registry.merge(_announce("node-a", "studio-a")) + registry.merge(_announce("node-a", "studio-a-renamed", caps={"ram_gb": 128})) + + discovered = registry.discovered() + assert len(discovered) == 1 + assert discovered[0]["friendly_name"] == "studio-a-renamed" + # Non-downgrading merge: the later announcement's real ram_gb wins, and + # the chip it did not carry survives instead of being erased. + assert discovered[0]["caps"] == {"chip": "M3 Ultra", "ram_gb": 128} + + +def test_mark_paired_persists_atomically_with_private_permissions(tmp_path): + path = tmp_path / "devices.json" + registry = DeviceRegistry(path) + registry.merge(_announce("node-a", "studio-a")) + + device = registry.mark_paired("node-a", paired_at=123.0) + + assert device["paired_at"] == 123.0 + assert registry.paired() == [device] + assert registry.discovered() == [] + assert stat.S_IMODE(path.stat().st_mode) == 0o600 + + restored = DeviceRegistry(path) + assert restored.paired() == [device] + assert restored.is_paired("node-a") + + +def test_merge_updates_paired_device_without_losing_trust(tmp_path): + path = tmp_path / "devices.json" + registry = DeviceRegistry(path) + registry.mark_paired("node-a", friendly_name="studio-a", paired_at=1.0) + + registry.merge(_announce("node-a", "studio-a", caps={"chip": "M4"})) + + device = registry.get("node-a") + assert device["caps"] == {"chip": "M4"} + assert device["last_addrs"] == ["fe80::1"] + assert device["paired_at"] == 1.0 + # The update was persisted. + assert DeviceRegistry(path).get("node-a")["caps"] == {"chip": "M4"} + + +def test_verified_http_port_survives_pairing_updates_and_reboot(tmp_path): + path = tmp_path / "devices.json" + registry = DeviceRegistry(path) + registry.merge( + _announce( + "node-a", + "studio-a", + http_port=9123, + addrs=[{"ip": "10.0.0.2", "if_type": "manual"}], + ) + ) + + paired = registry.mark_paired("node-a", paired_at=10.0) + + assert paired["http_port"] == 9123 + assert paired["last_addrs"] == ["10.0.0.2"] + restored = DeviceRegistry(path) + assert restored.get("node-a")["http_port"] == 9123 + + # A later verified endpoint replaces the port without weakening trust. + restored.merge( + { + "node_id": "node-a", + "http_port": 8123, + "addrs": [{"ip": "10.0.0.3", "if_type": "manual"}], + } + ) + after_update = DeviceRegistry(path).get("node-a") + assert after_update["http_port"] == 8123 + assert after_update["last_addrs"] == ["10.0.0.2", "10.0.0.3"] + + +def test_invalid_persisted_http_port_fails_closed(tmp_path): + path = tmp_path / "devices.json" + path.write_text( + '{"schema_version":1,"devices":[{' + '"node_id":"a","friendly_name":"A","paired_at":1,' + '"http_port":70000}]}', + encoding="utf-8", + ) + + registry = DeviceRegistry(path) + + assert registry.paired() == [] + assert "HTTP port" in (registry.load_error or "") + + +def test_merge_never_downgrades_paired_to_discovered(tmp_path): + registry = DeviceRegistry(tmp_path / "devices.json") + registry.mark_paired("node-a", friendly_name="studio-a") + + registry.merge({"node_id": "node-a"}) + + assert registry.is_paired("node-a") + assert registry.discovered() == [] + + +def test_unpair_revokes_and_persists(tmp_path): + path = tmp_path / "devices.json" + registry = DeviceRegistry(path) + registry.mark_paired("node-a", friendly_name="studio-a") + + assert registry.unpair("node-a") is True + assert registry.unpair("node-a") is False + assert registry.paired() == [] + # Device falls back to memory-only discovered so the UI can still show it. + assert registry.discovered()[0]["node_id"] == "node-a" + assert DeviceRegistry(path).paired() == [] + + +def test_corruption_fails_closed_without_blocking_server(tmp_path): + path = tmp_path / "devices.json" + path.write_text("{broken", encoding="utf-8") + + registry = DeviceRegistry(path) + + assert registry.paired() == [] + assert "could not read" in registry.load_error + + +def test_duplicate_node_ids_on_disk_are_rejected(tmp_path): + path = tmp_path / "devices.json" + path.write_text( + '{"schema_version": 1, "devices": [' + '{"node_id": "a", "friendly_name": "x", "paired_at": 1},' + '{"node_id": "a", "friendly_name": "y", "paired_at": 2}]}', + encoding="utf-8", + ) + + registry = DeviceRegistry(path) + + assert registry.paired() == [] + assert "duplicate" in registry.load_error + + +def test_merge_rejects_record_without_node_id(tmp_path): + registry = DeviceRegistry(tmp_path / "devices.json") + with pytest.raises(ValueError, match="node_id"): + registry.merge({"friendly_name": "ghost"}) + + +def test_configure_and_get_process_wide_registry(tmp_path): + reset_configured_device_registry() + try: + registry = configure_device_registry(tmp_path / "devices.json") + assert get_device_registry() is registry + finally: + reset_configured_device_registry() + + +def test_get_device_registry_requires_configuration(): + reset_configured_device_registry() + with pytest.raises(RuntimeError, match="not configured"): + get_device_registry() + + +def test_merge_on_paired_device_never_downgrades_caps_or_addrs(tmp_path): + """A discovery HELLO carries structurally complete but value-empty caps; + merging it over a pairing-exchanged record must not erase real data.""" + registry = DeviceRegistry(tmp_path / "devices.json") + registry.mark_paired( + "node-b", + friendly_name="laptop-b", + caps={"chip": "M5 Max", "ram_gb": 128, "thunderbolt": True, "jaccl": True}, + addrs=["198.51.100.20", "fe80::99"], + ) + + # Sparse announcement: empty caps values, link-local-only addrs. + registry.merge( + { + "node_id": "node-b", + "friendly_name": "", + "caps": { + "chip": "", + "ram_gb": 0.0, + "backends": [], + "thunderbolt": False, + "jaccl": False, + }, + "addrs": [{"ip": "fe80::42", "if_type": "unknown"}], + } + ) + + device = registry.get("node-b") + assert device["caps"] == { + "chip": "M5 Max", + "ram_gb": 128, + "thunderbolt": True, + "jaccl": True, + } + assert device["last_addrs"] == ["198.51.100.20", "fe80::99", "fe80::42"] + + # And the persisted file agrees after a reload. + restored = DeviceRegistry(tmp_path / "devices.json") + assert restored.get("node-b")["caps"]["ram_gb"] == 128 + assert "198.51.100.20" in restored.get("node-b")["last_addrs"] + + +def test_merge_on_discovered_device_also_merges_without_downgrade(tmp_path): + registry = DeviceRegistry(tmp_path / "devices.json") + registry.merge(_announce("node-c", "studio-c")) + registry.merge( + { + "node_id": "node-c", + "caps": { + "chip": "", + "ram_gb": 0.0, + "backends": [], + "thunderbolt": False, + "jaccl": False, + }, + "addrs": [{"ip": "fe80::7", "if_type": "unknown"}], + } + ) + device = registry.get("node-c") + assert device["caps"]["chip"] == "M3 Ultra" + assert device["caps"]["ram_gb"] == 96 + assert device["last_addrs"] == ["fe80::1", "fe80::7"] diff --git a/tests/test_cluster_discovery_routes.py b/tests/test_cluster_discovery_routes.py new file mode 100644 index 0000000000..162bed5a68 --- /dev/null +++ b/tests/test_cluster_discovery_routes.py @@ -0,0 +1,629 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Offline tests for the v2 discovery/identity endpoints.""" + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from omlx.cluster import discovery_routes +from omlx.cluster.discovery import ( + DiscoveryConfig, + DiscoveryService, + PeerCaps, + PeerRecord, + configure_discovery_service, +) +from omlx.cluster.identity import ( + NodeIdentity, + configure_node_identity, + reset_configured_identity, +) +from omlx.cluster.registry import ( + DeviceRegistry, + configure_device_registry, + reset_configured_device_registry, +) + + +@pytest.fixture(autouse=True) +def _configured_stores(tmp_path): + reset_configured_identity() + reset_configured_device_registry() + configure_discovery_service(None) + discovery_routes.probe_rate_limiter._buckets.clear() + identity = configure_node_identity(tmp_path) + registry = configure_device_registry(tmp_path / "devices.json") + # Bypass admin auth for the inventory endpoint in these unit tests; + # admin wiring is exercised by the existing admin auth test suite. + app = FastAPI() + + async def _allow(): + return True + + app.dependency_overrides[discovery_routes.require_admin] = _allow + app.include_router(discovery_routes.discovery_router) + client = TestClient(app) + yield identity, registry, client + reset_configured_identity() + reset_configured_device_registry() + configure_discovery_service(None) + + +def test_node_id_probe_is_public_and_returns_identity(_configured_stores): + identity, _, client = _configured_stores + + response = client.get("/api/cluster/node_id") + + assert response.status_code == 200 + payload = response.json() + assert payload["node_id"] == identity.node_id + assert payload["version"] + assert payload["cluster_name"] == "omlx" # default with no service + # The probe must not leak capabilities or the device inventory. + assert "caps" not in payload + assert "devices" not in payload + + +def test_node_id_probe_is_rate_limited(_configured_stores): + _, _, client = _configured_stores + limiter = discovery_routes.probe_rate_limiter + original = (limiter._rate, limiter._burst) + limiter._rate, limiter._burst = 0.0, 3 + try: + codes = [client.get("/api/cluster/node_id").status_code for _ in range(5)] + finally: + limiter._rate, limiter._burst = original + assert codes[:3] == [200, 200, 200] + assert codes[3:] == [429, 429] + + +def test_devices_returns_inventory_with_multicast_signal(_configured_stores): + identity, registry, client = _configured_stores + registry.mark_paired("peer-1", friendly_name="studio-b", paired_at=10.0) + + response = client.get("/api/cluster/devices") + + assert response.status_code == 200 + payload = response.json() + assert payload["self"]["node_id"] == identity.node_id + assert payload["self"]["paired"] is True + assert payload["paired"][0]["node_id"] == "peer-1" + assert payload["discovered"] == [] + # No discovery service running: multicast_ok must be False so the UI + # shows the Local Network permission guidance instead of silent zeros. + assert payload["multicast_ok"] is False + assert payload["mdns_available"] is False + + +def test_devices_paired_rows_carry_paired_flag(_configured_stores): + """Wizard consumers key on device.paired (the per-Mac role list filters + on it, and the device card's Pair/Paired state derives from it), so + rows in the paired list must carry the flag explicitly -- list + membership alone is not visible to those consumers.""" + _, registry, client = _configured_stores + registry.mark_paired("peer-1", friendly_name="studio-b", paired_at=10.0) + + payload = client.get("/api/cluster/devices").json() + + assert payload["paired"][0]["paired"] is True + + +def test_devices_reflects_live_discovery_service(_configured_stores, tmp_path): + identity, registry, client = _configured_stores + + service = DiscoveryService( + identity, + registry, + DiscoveryConfig(cluster_name="home", http_port=8000), + prober=lambda ip, port, timeout: None, + interface_lister=lambda: [], + zeroconf_module=None, + ) + configure_discovery_service(service) + peer = PeerRecord(node_id="peer-9", friendly_name="nine", http_port=8000) + peer.last_seen = service._clock() + service._peers["peer-9"] = peer + service._last_hello_at = service._clock() + + payload = client.get("/api/cluster/devices").json() + + assert payload["self"]["cluster_name"] == "home" + assert payload["self"]["http_port"] == 8000 + assert payload["multicast_ok"] is True + assert any(d["node_id"] == "peer-9" for d in payload["discovered"]) + # Registry merge happened through the service path? No — direct insertion + # here; the discovered list is sourced from service.peers(). + configure_discovery_service(None) + + +def test_devices_excludes_paired_peers_from_discovered(_configured_stores, tmp_path): + identity, registry, client = _configured_stores + registry.mark_paired("peer-1", friendly_name="studio-b") + + service = DiscoveryService( + identity, + registry, + DiscoveryConfig(), + prober=lambda ip, port, timeout: None, + interface_lister=lambda: [], + zeroconf_module=None, + ) + configure_discovery_service(service) + peer = PeerRecord(node_id="peer-1", friendly_name="studio-b") + peer.paired = True + service._peers["peer-1"] = peer + + payload = client.get("/api/cluster/devices").json() + + assert payload["discovered"] == [] + assert payload["paired"][0]["node_id"] == "peer-1" + configure_discovery_service(None) + + +def test_discovery_health_without_service(_configured_stores): + _, _, client = _configured_stores + + payload = client.get("/api/cluster/discovery/health").json() + + assert payload == { + "multicast_rx_within_5s": False, + "last_multicast_rx_at": None, + "mdns_active": False, + "transport": "disabled", + } + + +def test_discovery_health_reflects_live_service(_configured_stores): + identity, registry, client = _configured_stores + service = DiscoveryService( + identity, + registry, + DiscoveryConfig(cluster_name="home", http_port=8000), + prober=lambda ip, port, timeout: None, + interface_lister=lambda: [], + zeroconf_module=None, + ) + configure_discovery_service(service) + service._last_hello_at = service._clock() + service._last_hello_wall = 1782000002.5 + + payload = client.get("/api/cluster/discovery/health").json() + + assert payload["multicast_rx_within_5s"] is True + assert payload["last_multicast_rx_at"] == 1782000002.5 + assert payload["mdns_active"] is False # zeroconf disabled in tests + assert payload["transport"] == "multicast" + configure_discovery_service(None) + + +def test_devices_merges_pending_pairing_requests(_configured_stores, monkeypatch): + identity, registry, client = _configured_stores + + class _FakePairingManager: + def pending_requests(self): + return [ + { + "node_id": "peer-pending", + "friendly_name": "studio-2", + "caps": {"chip": "M3"}, + "addrs": ["192.168.1.11"], + "http_port": 8000, + "state": "awaiting_approval", + "created_at": 100.0, + "expires_at": 700.0, + "attempts": 0, + "locked": False, + "locked_until": None, + } + ] + + from omlx.cluster import pairing + + monkeypatch.setattr(pairing, "get_pairing_manager", lambda: _FakePairingManager()) + + payload = client.get("/api/cluster/devices").json() + + pending = [d for d in payload["discovered"] if d["node_id"] == "peer-pending"] + assert len(pending) == 1 + assert pending[0]["state"] == "awaiting_approval" + assert pending[0]["friendly_name"] == "studio-2" + + +def test_devices_paired_rows_carry_enrolled_ssh_target(_configured_stores, monkeypatch): + from types import SimpleNamespace + + from omlx.cluster import enrollment + + _, registry, client = _configured_stores + registry.mark_paired("peer-1", friendly_name="studio-b") + enrolled = SimpleNamespace(node_id="peer-1", ssh="omlx@studio-b.local") + fake_store = SimpleNamespace(list_nodes=lambda: (enrolled,)) + monkeypatch.setattr(enrollment, "get_cluster_enrollment", lambda: fake_store) + + payload = client.get("/api/cluster/devices").json() + + assert payload["paired"][0]["ssh_target"] == "omlx@studio-b.local" + + +def test_cluster_name_persisted_config(tmp_path, monkeypatch): + from omlx.cluster.discovery import default_cluster_config_path, load_cluster_name + + assert load_cluster_name(tmp_path) == "omlx" # no file yet + path = default_cluster_config_path(tmp_path) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text('{"cluster_name": "studio-lan"}') + assert load_cluster_name(tmp_path) == "studio-lan" + # Malformed JSON falls back to the default instead of raising. + path.write_text("{not json") + assert load_cluster_name(tmp_path) == "omlx" + + +def test_devices_requires_admin_auth(tmp_path): + # Without the dependency override, an unauthenticated call is rejected. + reset_configured_identity() + configure_node_identity(tmp_path) + app = FastAPI() + app.include_router(discovery_routes.discovery_router) + client = TestClient(app, raise_server_exceptions=False) + try: + response = client.get("/api/cluster/devices") + assert response.status_code in {401, 302, 307} + finally: + reset_configured_identity() + + +def test_node_id_probe_503_without_identity(): + reset_configured_identity() + discovery_routes.probe_rate_limiter._buckets.clear() + app = FastAPI() + app.include_router(discovery_routes.discovery_router) + client = TestClient(app) + try: + response = client.get("/api/cluster/node_id") + assert response.status_code == 503 + finally: + pass # fixture resets on next test + + +# -- manual peer add + health detail ------------------------------------------ + + +def _live_service(registry, prober=None): + service = DiscoveryService( + NodeIdentity(node_id="self-node", friendly_name="self", created_at=1.0), + registry, + DiscoveryConfig(cluster_name="omlx", http_port=8000), + prober=prober or (lambda ip, port, timeout: None), + interface_lister=lambda: [], + zeroconf_module=None, + ) + configure_discovery_service(service) + return service + + +def test_manual_peer_add_verifies_and_returns_peer(_configured_stores): + _, registry, client = _configured_stores + + def prober(ip, port, timeout): + if ip == "10.0.0.2": + return {"node_id": "tb-peer", "friendly_name": "m5-max"} + return None + + service = _live_service(registry, prober) + + response = client.post("/api/cluster/devices/manual", json={"ip": "10.0.0.2"}) + + assert response.status_code == 200 + payload = response.json() + assert payload["ok"] is True + assert payload["verified"] is True + assert payload["peer"]["node_id"] == "tb-peer" + assert payload["peer"]["friendly_name"] == "m5-max" + assert payload["peer"]["addrs"] == [{"ip": "10.0.0.2", "if_type": "manual"}] + service.stop() + + +def test_manual_peer_add_unverified_when_address_silent(_configured_stores): + _, registry, client = _configured_stores + service = _live_service(registry) # prober answers None for everything + + response = client.post( + "/api/cluster/devices/manual", json={"ip": "10.0.0.99", "port": 8000} + ) + + assert response.status_code == 200 + payload = response.json() + assert payload["ok"] is True + assert payload["verified"] is False + assert payload["peer"] is None + service.stop() + + +def test_manual_peer_add_rejects_bad_input(_configured_stores): + _, registry, client = _configured_stores + _live_service(registry) + + assert ( + client.post("/api/cluster/devices/manual", json={"ip": "not-an-ip"}).status_code + == 400 + ) + assert ( + client.post( + "/api/cluster/devices/manual", + json={"ip": "10.0.0.2", "port": 70000}, + ).status_code + == 400 + ) + assert client.post("/api/cluster/devices/manual", json={}).status_code == 400 + + +def test_manual_peer_add_503_when_discovery_disabled(_configured_stores): + _, _, client = _configured_stores # fixture leaves service unset + + response = client.post("/api/cluster/devices/manual", json={"ip": "10.0.0.2"}) + + assert response.status_code == 503 + + +def test_health_detail_reports_loop_state(_configured_stores): + _, registry, client = _configured_stores + _live_service(registry) + + response = client.get("/api/cluster/discovery/health/detail") + + assert response.status_code == 200 + payload = response.json() + assert payload["multicast_loop_alive"] is False # never started + assert payload["maintenance_loop_alive"] is False + assert payload["socket_open"] is False + assert payload["joined_interfaces"] == [] + assert payload["peers"] == 0 + + +def test_health_detail_503_when_discovery_disabled(_configured_stores): + _, _, client = _configured_stores + + assert client.get("/api/cluster/discovery/health/detail").status_code == 503 + + +def test_devices_self_row_lists_local_addresses(_configured_stores): + _, _, client = _configured_stores + + response = client.get("/api/cluster/devices") + + assert response.status_code == 200 + addrs = response.json()["self"]["addrs"] + assert isinstance(addrs, list) + for entry in addrs: + assert set(entry) == {"ip", "if_type"} + + +# -- paired suppression + paired-row enrichment --------------------------------- + + +def test_devices_suppresses_paired_node_with_stale_dead_peer( + _configured_stores, +): + identity, registry, client = _configured_stores + registry.mark_paired("peer-1", friendly_name="studio-b") + + service = DiscoveryService( + identity, + registry, + DiscoveryConfig(), + prober=lambda ip, port, timeout: None, + interface_lister=lambda: [], + zeroconf_module=None, + ) + configure_discovery_service(service) + # Stale in-memory record: the peer went silent before pairing completed, + # so nothing ever flipped PeerRecord.paired on this dead row. + service._peers["peer-1"] = PeerRecord( + node_id="peer-1", friendly_name="studio-b", state="dead" + ) + + payload = client.get("/api/cluster/devices").json() + + assert payload["discovered"] == [] + assert [row["node_id"] for row in payload["paired"]] == ["peer-1"] + configure_discovery_service(None) + + +def test_devices_pending_request_wins_over_stale_discovered_record( + _configured_stores, monkeypatch +): + identity, registry, client = _configured_stores + + service = DiscoveryService( + identity, + registry, + DiscoveryConfig(), + prober=lambda ip, port, timeout: None, + interface_lister=lambda: [], + zeroconf_module=None, + ) + configure_discovery_service(service) + service._peers["peer-pending"] = PeerRecord( + node_id="peer-pending", friendly_name="stale-name", state="dead" + ) + + class _FakePairingManager: + def pending_requests(self): + return [ + { + "node_id": "peer-pending", + "friendly_name": "studio-2", + "caps": {"chip": "M3"}, + "addrs": ["192.168.1.11"], + "http_port": 8000, + "state": "awaiting_approval", + "created_at": 100.0, + "expires_at": 700.0, + "attempts": 0, + "locked": False, + "locked_until": None, + } + ] + + from omlx.cluster import pairing + + monkeypatch.setattr(pairing, "get_pairing_manager", lambda: _FakePairingManager()) + + payload = client.get("/api/cluster/devices").json() + + pending = [d for d in payload["discovered"] if d["node_id"] == "peer-pending"] + assert len(pending) == 1 + assert pending[0]["state"] == "awaiting_approval" + assert pending[0]["friendly_name"] == "studio-2" + configure_discovery_service(None) + + +def test_devices_enriches_paired_row_from_discovery_record(_configured_stores): + identity, registry, client = _configured_stores + # Paired before caps were exchanged: empty caps persisted on disk. + registry.mark_paired( + "peer-1", + friendly_name="studio-b", + caps={}, + addrs=["192.168.1.20"], + paired_at=10.0, + ) + + service = DiscoveryService( + identity, + registry, + DiscoveryConfig(), + prober=lambda ip, port, timeout: None, + interface_lister=lambda: [], + zeroconf_module=None, + ) + configure_discovery_service(service) + peer = PeerRecord( + node_id="peer-1", + friendly_name="studio-b", + version="1.2.3", + caps=PeerCaps( + chip="M3 Max", + ram_gb=96.0, + backends=["jaccl"], + thunderbolt=True, + jaccl=True, + ), + addrs=[ + {"ip": "192.168.1.20", "if_type": "lan"}, + {"ip": "192.168.1.21", "if_type": "tb"}, + ], + http_port=8000, + paired=True, + last_seen=1234.5, + state="dead", + ) + peer.link = "tb" + service._peers["peer-1"] = peer + + payload = client.get("/api/cluster/devices").json() + + assert payload["discovered"] == [] # suppressed, but still enriches + row = payload["paired"][0] + assert row["caps"] == { + "chip": "M3 Max", + "ram_gb": 96.0, + "backends": ["jaccl"], + "thunderbolt": True, + "jaccl": True, + } + assert row["version"] == "1.2.3" + assert row["link"] == "tb" + assert row["state"] == "dead" + assert row["last_seen"] == 1234.5 + assert row["http_port"] == 8000 + # Normalized addrs: last_addrs entries come first with the "paired" + # marker; the discovered record upgrades if_type where the IP matches + # and appends addresses the pairing flow never saw. + assert row["addrs"] == [ + {"ip": "192.168.1.20", "if_type": "lan"}, + {"ip": "192.168.1.21", "if_type": "tb"}, + ] + configure_discovery_service(None) + + +def test_devices_paired_row_normalizes_last_addrs_and_keeps_ssh_target( + _configured_stores, monkeypatch +): + from types import SimpleNamespace + + from omlx.cluster import enrollment + + _, registry, client = _configured_stores + registry.mark_paired( + "peer-1", + friendly_name="studio-b", + caps={"chip": "M4", "ram_gb": 64}, + addrs=["192.168.1.20", "192.168.1.21"], + ) + enrolled = SimpleNamespace(node_id="peer-1", ssh="omlx@studio-b.local") + fake_store = SimpleNamespace(list_nodes=lambda: (enrolled,)) + monkeypatch.setattr(enrollment, "get_cluster_enrollment", lambda: fake_store) + + payload = client.get("/api/cluster/devices").json() + + row = payload["paired"][0] + # No discovery record: caps stay as persisted and nothing is invented. + assert row["caps"] == {"chip": "M4", "ram_gb": 64} + assert row["addrs"] == [ + {"ip": "192.168.1.20", "if_type": "paired"}, + {"ip": "192.168.1.21", "if_type": "paired"}, + ] + assert "version" not in row + assert row["state"] == "suspect" + assert row["last_seen"] is None + assert row["http_port"] == 0 + # The enrollment seam still applies on top of the normalization. + assert row["ssh_target"] == "omlx@studio-b.local" + + +def test_manual_paired_endpoint_persists_and_rehydrates_on_reboot( + _configured_stores, +): + identity, registry, client = _configured_stores + registry.mark_paired("tb-peer", friendly_name="m5-max", paired_at=1.0) + + def prober(ip, port, timeout): + if (ip, port) == ("10.0.0.2", 9123): + return { + "node_id": "tb-peer", + "friendly_name": "m5-max", + "version": "0.6.1", + "cluster_name": "omlx", + } + return None + + service = _live_service(registry, prober) + response = client.post( + "/api/cluster/devices/manual", + json={"ip": "10.0.0.2", "port": 9123}, + ) + + assert response.status_code == 200 + assert response.json()["verified"] is True + persisted = DeviceRegistry(registry.path) + record = persisted.get("tb-peer") + assert record["last_addrs"] == ["10.0.0.2"] + assert record["http_port"] == 9123 + + row = client.get("/api/cluster/devices").json()["paired"][0] + assert row["state"] == "discovered" + assert row["last_seen"] is not None + assert row["http_port"] == 9123 + + rebooted = DiscoveryService( + identity, + persisted, + DiscoveryConfig(cluster_name="omlx", http_port=8000), + prober=prober, + interface_lister=lambda: [], + zeroconf_module=None, + ) + assert ("10.0.0.2", 9123) in rebooted._candidates + assert rebooted._candidates[("10.0.0.2", 9123)]["node_id"] == "tb-peer" + service.stop() diff --git a/tests/test_cluster_identity.py b/tests/test_cluster_identity.py new file mode 100644 index 0000000000..69cba1e28f --- /dev/null +++ b/tests/test_cluster_identity.py @@ -0,0 +1,133 @@ +# SPDX-License-Identifier: Apache-2.0 + +import json +import stat + +import pytest + +from omlx.cluster.identity import ( + NodeIdentity, + configure_node_identity, + get_node_identity, + load_or_create, + reset_configured_identity, +) + + +def test_creates_and_persists_identity_with_private_permissions(tmp_path): + path = tmp_path / "cluster" / "identity.json" + + identity = load_or_create(path) + + assert identity.node_id + assert identity.friendly_name + assert identity.schema_version == 1 + assert identity.created_at > 0 + assert stat.S_IMODE(path.stat().st_mode) == 0o600 + + +def test_load_or_create_is_stable_across_reloads(tmp_path): + path = tmp_path / "identity.json" + + first = load_or_create(path) + second = load_or_create(path) + + assert second.node_id == first.node_id + assert second.friendly_name == first.friendly_name + assert second.created_at == first.created_at + + +def test_collision_repair_suffixes_name_but_keeps_node_id(tmp_path): + path = tmp_path / "identity.json" + identity = load_or_create(path) + original_id = identity.node_id + original_name = identity.friendly_name + + repaired = load_or_create(path, taken_names={original_name}) + + assert repaired.node_id == original_id + assert repaired.friendly_name == f"{original_name}-2" + # Repair is persisted. + assert load_or_create(path).friendly_name == f"{original_name}-2" + + +def test_collision_repair_escalates_past_taken_suffixes(tmp_path): + path = tmp_path / "identity.json" + identity = load_or_create(path) + name = identity.friendly_name + + repaired = load_or_create(path, taken_names={name, f"{name}-2"}) + + assert repaired.friendly_name == f"{name}-3" + + +def test_rename_persists_and_never_touches_node_id(tmp_path): + path = tmp_path / "identity.json" + identity = load_or_create(path) + original_id = identity.node_id + + identity.rename(" My Studio Mac ") + + assert identity.node_id == original_id + assert identity.friendly_name == "My-Studio-Mac" + assert load_or_create(path).friendly_name == "My-Studio-Mac" + + +def test_rename_rejects_empty_name(tmp_path): + identity = load_or_create(tmp_path / "identity.json") + with pytest.raises(ValueError, match="must not be empty"): + identity.rename(" ") + + +def test_corrupt_file_fails_safe_without_rotating_node_id(tmp_path): + path = tmp_path / "identity.json" + path.write_text("{broken", encoding="utf-8") + + identity = load_or_create(path) + + # In-memory identity works, the error is surfaced, and the corrupt file + # is preserved rather than overwritten with a fresh node_id. + assert identity.node_id + assert identity.load_error and "could not read" in identity.load_error + assert path.read_text(encoding="utf-8") == "{broken" + + +def test_wrong_schema_version_is_rejected_as_corrupt(tmp_path): + path = tmp_path / "identity.json" + path.write_text( + json.dumps( + { + "schema_version": 99, + "node_id": "abc", + "friendly_name": "x", + "created_at": 1.0, + } + ), + encoding="utf-8", + ) + + identity = load_or_create(path) + + assert identity.load_error is not None + + +def test_roundtrip_dict(): + identity = NodeIdentity(node_id="n-1", friendly_name="studio", created_at=7.5) + restored = NodeIdentity.from_dict(identity.to_dict()) + assert restored == identity + + +def test_configure_and_get_process_wide_identity(tmp_path): + reset_configured_identity() + try: + identity = configure_node_identity(tmp_path) + assert get_node_identity() is identity + assert (tmp_path / "cluster" / "identity.json").exists() + finally: + reset_configured_identity() + + +def test_get_node_identity_requires_configuration(): + reset_configured_identity() + with pytest.raises(RuntimeError, match="not configured"): + get_node_identity() diff --git a/tests/test_cluster_pairing.py b/tests/test_cluster_pairing.py new file mode 100644 index 0000000000..becd164a4b --- /dev/null +++ b/tests/test_cluster_pairing.py @@ -0,0 +1,1189 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Offline unit tests for cluster v2 pairing (Module B). + +No network, no SSH, no Module A code: enrollment/revocation drivers, SSH key +provider, caps, clocks, and HTTP transport are all fakes. The loopback +happy path wires two real PairingManagers together through their public +joiner/coordinator APIs. +""" + +import base64 +import json +import stat +import threading +from types import SimpleNamespace + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from omlx.cluster import pairing_routes +from omlx.cluster.pairing import ( + CODE_TTL_SECONDS, + LOCKOUT_SECONDS, + MAX_CODE_ATTEMPTS, + PBKDF2_ITERATIONS, + DeviceRegistryBridge, + EnrollmentDriveError, + JsonDeviceStore, + PairingAuditLog, + PairingCodeError, + PairingError, + PairingExpiredError, + PairingKeyStore, + PairingLockoutError, + PairingManager, + PairingRequestError, + PairingStateError, + default_enrollment_driver, + generate_pairing_code, + pairing_code_hash, + unwrap_cluster_key, + wrap_cluster_key, +) + + +class _Clock: + def __init__(self, now: float = 1_000_000.0): + self.now = now + + def __call__(self) -> float: + return self.now + + +class _Audit: + def __init__(self): + self.events = [] + + def __call__(self, event, *, node_id="", detail=None): + self.events.append((event, node_id, detail or {})) + + def names(self): + return [event for event, _, _ in self.events] + + +class _FakeEnrollmentStore: + """Duck-type of the legacy ClusterEnrollmentStore bits pairing uses.""" + + def __init__(self): + self.removed = [] + + def remove_node(self, node_id): + self.removed.append(node_id) + return True + + +class _FakeModuleARegistry: + """Mimics Module A DeviceRegistry method names (upsert/get/remove/list).""" + + def __init__(self): + self.records = {} + + def upsert(self, record): + self.records[record["node_id"]] = dict(record) + + def get(self, node_id): + return self.records.get(node_id) + + def remove(self, node_id): + return self.records.pop(node_id, None) is not None + + def list(self): + return list(self.records.values()) + + +def _test_public_key(node_id: str) -> str: + payload = base64.b64encode(f"key-{node_id}".encode()).decode() + return f"ssh-ed25519 {payload}" + + +def _manager( + tmp_path, + *, + node_id, + name, + clock=None, + audit=None, + registry=None, + enrollment_store=None, + driver_calls=None, + revocation_calls=None, + enrollment_driver=None, + revocation_driver=None, +): + """A PairingManager with every side effect faked or sandboxed.""" + + def driver(peer): + if driver_calls is not None: + driver_calls.append(peer) + return {"ok": True} + + def revocation(material): + if revocation_calls is not None: + revocation_calls.append(material) + return {"authorized_key_removed": True, "errors": []} + + return PairingManager( + registry, + enrollment_store, + base_path=tmp_path / node_id, + identity={ + "node_id": node_id, + "friendly_name": name, + "created_at": 1.0, + "schema_version": 1, + }, + caps_provider=lambda: {"chip": "M4 Max", "ram_gb": 128}, + address_provider=lambda: ["127.0.0.1"], + ssh_key_provider=lambda: _test_public_key(node_id), + ssh_host_key_provider=lambda: _test_public_key(f"host-{node_id}"), + enrollment_driver=enrollment_driver or driver, + revocation_driver=revocation_driver or revocation, + clock=clock or _Clock(), + audit=audit if audit is not None else _Audit(), + ) + + +def _loopback_pair(tmp_path): + """Coordinator + joiner managers joined by an in-process transport.""" + + coordinator_clock, joiner_clock = _Clock(), _Clock() + enrollment_store = _FakeEnrollmentStore() + driver_calls, revocation_calls = [], [] + coordinator = _manager( + tmp_path, + node_id="coord-node", + name="Coordinator", + clock=coordinator_clock, + enrollment_store=enrollment_store, + driver_calls=driver_calls, + revocation_calls=revocation_calls, + ) + joiner = _manager( + tmp_path, + node_id="join-node", + name="Joiner", + clock=joiner_clock, + driver_calls=driver_calls, + ) + + def http_post(url, payload, timeout): + assert url.endswith("/api/cluster/pair/request") + return coordinator.handle_join_request(payload) + + def http_get(url, timeout): + node_id = url.rsplit("/", 1)[1] + return coordinator.join_status(node_id) + + joiner._http_post = http_post + joiner._http_get = http_get + return coordinator, joiner, enrollment_store, driver_calls, revocation_calls + + +# --- Code + wrap crypto ------------------------------------------------------- + + +def test_pairing_code_is_six_digits_with_leading_zeros(): + for _ in range(200): + code = generate_pairing_code() + assert code.isdigit() and len(code) == 6 + + +def test_code_hash_authenticates_node_and_ssh_identities(): + code, node_id = "042517", "node-abc" + user_key = _test_public_key(node_id) + host_key = _test_public_key(f"host-{node_id}") + salt = b"s" * 16 + digest = pairing_code_hash(code, node_id, user_key, host_key, salt) + + assert len(digest) == 64 + assert pairing_code_hash(code, "other", user_key, host_key, salt) != digest + assert ( + pairing_code_hash(code, node_id, _test_public_key("other"), host_key, salt) + != digest + ) + assert ( + pairing_code_hash(code, node_id, user_key, _test_public_key("other"), salt) + != digest + ) + assert pairing_code_hash(code, node_id, user_key, host_key, b"x" * 16) != digest + + +def test_cluster_key_wrap_round_trip_and_wrong_code_fails_closed(): + key = b"\x5a" * 32 + package = wrap_cluster_key(key, "123456") + assert package["kdf"] == "PBKDF2-HMAC-SHA256" + assert package["iterations"] == PBKDF2_ITERATIONS + assert unwrap_cluster_key(package, "123456") == key + with pytest.raises(PairingCodeError): + unwrap_cluster_key(package, "654321") + + +def test_cluster_key_wrap_detects_tampering(): + key = b"\x00" * 32 + package = wrap_cluster_key(key, "123456") + tampered = dict(package) + tampered["ciphertext"] = package["salt"] # same-length valid b64, wrong bytes + with pytest.raises(PairingCodeError): + unwrap_cluster_key(tampered, "123456") + + +def test_wrap_rejects_oversized_iteration_counts(): + package = wrap_cluster_key(b"\x01" * 32, "123456") + package["iterations"] = 10**9 + with pytest.raises(PairingRequestError): + unwrap_cluster_key(package, "123456") + + +# --- Loopback happy path ------------------------------------------------------- + + +def test_two_manager_loopback_happy_path(tmp_path): + coordinator, joiner, enrollment_store, driver_calls, _ = _loopback_pair(tmp_path) + + shown = joiner.start_join() + code = shown["code"] + assert shown["expires_at"] - joiner._clock() == CODE_TTL_SECONDS + + result = joiner.request_join("coordinator.local:8080") + assert result["state"] == "awaiting_approval" + + # Pending request is visible in the coordinator's devices view. + view = coordinator.devices_view() + assert [p["node_id"] for p in view["pending"]] == ["join-node"] + assert view["pending"][0]["state"] == "awaiting_approval" + + # The code never crossed the wire, and the coordinator's snapshot of the + # pending request does not echo even the hash back to the joiner. + assert "code" not in json.dumps(result["response"]) + assert "code_hash" not in result["response"] + + approved = coordinator.approve("join-node", code) + assert approved["state"] == "paired" + assert driver_calls and driver_calls[0]["node_id"] == "join-node" + assert driver_calls[0]["ssh_public_key"] == _test_public_key("join-node") + + # Joiner polls, unwraps, persists: both sides hold the same cluster key. + status = joiner.poll_join("coordinator.local:8080") + assert status["state"] == "approved" + joined = joiner.complete_join(status) + assert joined["node_id"] == "coord-node" + assert [call["node_id"] for call in driver_calls] == [ + "join-node", + "coord-node", + ] + + coord_key = coordinator._key_store.get("join-node")["cluster_key"] + joiner_key = joiner._key_store.get("coord-node")["cluster_key"] + assert coord_key == joiner_key + + assert [d["node_id"] for d in coordinator.paired_devices()] == ["join-node"] + assert [d["node_id"] for d in joiner.paired_devices()] == ["coord-node"] + + events = coordinator._audit.names() + assert "join_request_received" in events + assert "approve_success" in events + assert "join_completed" in joiner._audit.names() + + +def test_request_join_without_start_join_fails(tmp_path): + joiner = _manager(tmp_path, node_id="join-node", name="Joiner") + with pytest.raises(PairingStateError, match="start_join"): + joiner.build_join_request() + + +# --- Wrong-code lockout --------------------------------------------------------- + + +def test_wrong_code_lockout_then_code_dies(tmp_path): + clock = _Clock() + coordinator = _manager( + tmp_path, node_id="coord-node", name="Coordinator", clock=clock + ) + joiner = _manager(tmp_path, node_id="join-node", name="Joiner") + code = joiner.start_join()["code"] + coordinator.handle_join_request(joiner.build_join_request(code)) + + wrong = "000000" if code != "000000" else "000001" + for _attempt in range(1, MAX_CODE_ATTEMPTS): + with pytest.raises(PairingCodeError, match="attempts left"): + coordinator.approve("join-node", wrong) + with pytest.raises(PairingLockoutError, match="locked until"): + coordinator.approve("join-node", wrong) + + # Even the CORRECT code is refused during the lockout window. + with pytest.raises(PairingLockoutError): + coordinator.approve("join-node", code) + assert coordinator._key_store.get("join-node") is None + + # Lockout and code TTL are both 10 minutes from request creation, so by + # the time the lockout is served the code itself has expired — a locked + # request can never become pairable again without a fresh request. + clock.now += LOCKOUT_SECONDS + 1 + with pytest.raises(PairingExpiredError): + coordinator.approve("join-node", code) + + events = coordinator._audit.names() + assert events.count("approve_wrong_code") == MAX_CODE_ATTEMPTS - 1 + assert "approve_lockout" in events + assert "approve_locked_out" in events + + +def test_attempts_reset_after_lockout_within_code_validity(tmp_path): + """If a lockout ends while the code is still valid, attempts reset.""" + + clock = _Clock() + coordinator = _manager( + tmp_path, node_id="coord-node", name="Coordinator", clock=clock + ) + joiner = _manager(tmp_path, node_id="join-node", name="Joiner") + code = joiner.start_join()["code"] + coordinator.handle_join_request(joiner.build_join_request(code)) + + wrong = "000000" if code != "000000" else "000001" + for _ in range(MAX_CODE_ATTEMPTS): + with pytest.raises(PairingError): + coordinator.approve("join-node", wrong) + + # Simulate a short lockout that ended well inside the code's validity. + coordinator._pending["join-node"].locked_until = clock.now - 1 + approved = coordinator.approve("join-node", code) + assert approved["state"] == "paired" + assert coordinator._pending == {} + + +# --- Expiry --------------------------------------------------------------------- + + +def test_expired_request_cannot_be_approved(tmp_path): + clock = _Clock() + coordinator = _manager( + tmp_path, node_id="coord-node", name="Coordinator", clock=clock + ) + joiner = _manager(tmp_path, node_id="join-node", name="Joiner") + code = joiner.start_join()["code"] + coordinator.handle_join_request(joiner.build_join_request(code)) + + clock.now += CODE_TTL_SECONDS + 1 + with pytest.raises(PairingExpiredError): + coordinator.approve("join-node", code) + # Pruned: a second attempt reports "no pending request", not expiry. + with pytest.raises(PairingStateError, match="no pending"): + coordinator.approve("join-node", code) + assert "join_request_expired" in coordinator._audit.names() + + +def test_joiner_side_expired_code_refused(tmp_path): + clock = _Clock() + joiner = _manager(tmp_path, node_id="join-node", name="Joiner", clock=clock) + joiner.start_join() + clock.now += CODE_TTL_SECONDS + 1 + with pytest.raises(PairingExpiredError): + joiner.build_join_request() + + +# --- Deny ----------------------------------------------------------------------- + + +def test_deny_removes_pending_and_is_audited(tmp_path): + coordinator, joiner, *_ = _loopback_pair(tmp_path) + joiner.start_join() + joiner.request_join("coordinator.local:8080") + + assert coordinator.deny("join-node") is True + assert coordinator.deny("join-node") is False + assert coordinator.join_status("join-node")["state"] == "denied" + assert coordinator.devices_view()["pending"] == [] + with pytest.raises(PairingStateError, match="denied"): + coordinator.approve("join-node", "123456") + assert "join_request_denied" in coordinator._audit.names() + + +# --- Unpair revocation ------------------------------------------------------------ + + +def test_unpair_revokes_everything(tmp_path): + coordinator, joiner, enrollment_store, _, revocation_calls = _loopback_pair( + tmp_path + ) + code = joiner.start_join()["code"] + joiner.request_join("coordinator.local:8080") + coordinator.approve("join-node", code) + joiner.complete_join(joiner.poll_join("coordinator.local:8080")) + + result = coordinator.unpair("join-node") + assert result["unpaired"] is True + assert result["removed_device"] is True + assert result["removed_key"] is True + assert result["removed_enrollment"] is True + assert coordinator.paired_devices() == [] + assert coordinator._key_store.get("join-node") is None + assert enrollment_store.removed == ["join-node"] + assert revocation_calls == [ + { + "peer_public_key": _test_public_key("join-node"), + "addrs": ["127.0.0.1"], + } + ] + assert coordinator.join_status("join-node")["state"] == "unknown" + assert "device_unpaired" in coordinator._audit.names() + + # The joiner's own copy is revoked independently. + joiner_result = joiner.unpair("coord-node") + assert joiner_result["removed_key"] is True + assert joiner.paired_devices() == [] + + +def test_unpair_unknown_device_fails_closed(tmp_path): + coordinator = _manager(tmp_path, node_id="coord-node", name="Coordinator") + with pytest.raises(PairingStateError, match="unknown device"): + coordinator.unpair("ghost-node") + + +def test_unpair_also_cancels_a_pending_request(tmp_path): + coordinator, joiner, *_ = _loopback_pair(tmp_path) + joiner.start_join() + joiner.request_join("coordinator.local:8080") + result = coordinator.unpair("join-node") + assert result["was_pending"] is True + assert coordinator.devices_view()["pending"] == [] + + +# --- Fail-closed enrollment driving ----------------------------------------------- + + +def test_enrollment_failure_does_not_pair(tmp_path): + def boom(peer): + raise RuntimeError("refusing changed SSH host key") + + coordinator = _manager(tmp_path, node_id="coord-node", name="Coordinator") + coordinator._enrollment_driver = boom + joiner = _manager(tmp_path, node_id="join-node", name="Joiner") + code = joiner.start_join()["code"] + coordinator.handle_join_request(joiner.build_join_request(code)) + + from omlx.cluster.pairing import EnrollmentDriveError + + with pytest.raises(EnrollmentDriveError, match="not paired"): + coordinator.approve("join-node", code) + assert coordinator.paired_devices() == [] + assert coordinator._key_store.get("join-node") is None + # Pending survives so the operator can fix SSH and retry with the code. + assert [p["node_id"] for p in coordinator.pending_requests()] == ["join-node"] + assert "approve_enrollment_failed" in coordinator._audit.names() + + +def test_approval_reservation_blocks_deny_unpair_and_duplicate_approval(tmp_path): + entered = threading.Event() + release = threading.Event() + + def blocking_enrollment(_peer): + entered.set() + assert release.wait(5), "test did not release enrollment" + return {"ok": True} + + coordinator = _manager( + tmp_path, + node_id="coord-node", + name="Coordinator", + enrollment_driver=blocking_enrollment, + ) + joiner = _manager(tmp_path, node_id="join-node", name="Joiner") + code = joiner.start_join()["code"] + coordinator.handle_join_request(joiner.build_join_request(code)) + result = [] + errors = [] + + def approve(): + try: + result.append(coordinator.approve("join-node", code)) + except Exception as exc: # pragma: no cover - asserted below + errors.append(exc) + + thread = threading.Thread(target=approve) + thread.start() + assert entered.wait(5), "approval never reached enrollment" + + with pytest.raises(PairingStateError, match="already in progress"): + coordinator.approve("join-node", code) + with pytest.raises(PairingStateError, match="already in progress"): + coordinator.deny("join-node") + with pytest.raises(PairingStateError, match="already in progress"): + coordinator.unpair("join-node") + + release.set() + thread.join(5) + assert not thread.is_alive() + assert errors == [] + assert result[0]["state"] == "paired" + assert coordinator._key_store.get("join-node") is not None + + +def test_persistence_failure_revokes_enrollment_and_releases_reservation(tmp_path): + revocations = [] + coordinator = _manager( + tmp_path, + node_id="coord-node", + name="Coordinator", + revocation_calls=revocations, + ) + joiner = _manager(tmp_path, node_id="join-node", name="Joiner") + code = joiner.start_join()["code"] + coordinator.handle_join_request(joiner.build_join_request(code)) + coordinator._key_store.set = lambda *_args, **_kwargs: (_ for _ in ()).throw( + OSError("read-only pairing store") + ) + + with pytest.raises(PairingError, match="could not be persisted"): + coordinator.approve("join-node", code) + + assert coordinator.paired_devices() == [] + assert coordinator._key_store.get("join-node") is None + assert coordinator.pending_requests()[0]["approving"] is False + assert revocations == [ + { + "peer_public_key": _test_public_key("join-node"), + "addrs": ["127.0.0.1"], + } + ] + assert "approve_persistence_failed" in coordinator._audit.names() + + +def test_device_persistence_failure_rolls_back_cluster_key(tmp_path): + revocations = [] + coordinator = _manager( + tmp_path, + node_id="coord-node", + name="Coordinator", + revocation_calls=revocations, + ) + joiner = _manager(tmp_path, node_id="join-node", name="Joiner") + code = joiner.start_join()["code"] + coordinator.handle_join_request(joiner.build_join_request(code)) + coordinator._devices.put_paired = lambda *_args, **_kwargs: (_ for _ in ()).throw( + OSError("read-only device registry") + ) + + with pytest.raises(PairingError, match="could not be persisted"): + coordinator.approve("join-node", code) + + assert coordinator._key_store.get("join-node") is None + assert coordinator.paired_devices() == [] + assert coordinator.pending_requests()[0]["approving"] is False + assert len(revocations) == 1 + + +def test_joiner_enrollment_failure_does_not_persist_coordinator(tmp_path): + coordinator, joiner, *_ = _loopback_pair(tmp_path) + code = joiner.start_join()["code"] + joiner.request_join("coordinator.local:8080") + coordinator.approve("join-node", code) + joiner._enrollment_driver = lambda _peer: (_ for _ in ()).throw( + RuntimeError("host key mismatch") + ) + + with pytest.raises(EnrollmentDriveError, match="coordinator was not paired"): + joiner.complete_join(joiner.poll_join("coordinator.local:8080")) + + assert joiner.paired_devices() == [] + assert joiner._key_store.get("coord-node") is None + assert "join_enrollment_failed" in joiner._audit.names() + + +def test_joiner_persistence_failure_revokes_enrollment_and_keeps_retry_state( + tmp_path, +): + coordinator, joiner, *_ = _loopback_pair(tmp_path) + revocations = [] + joiner._revocation_driver = lambda material: revocations.append(material) or {} + code = joiner.start_join()["code"] + joiner.request_join("coordinator.local:8080") + coordinator.approve("join-node", code) + status = joiner.poll_join("coordinator.local:8080") + joiner._key_store.set = lambda *_args, **_kwargs: (_ for _ in ()).throw( + OSError("read-only pairing store") + ) + + with pytest.raises(PairingError, match="coordinator was not paired"): + joiner.complete_join(status) + + assert joiner.paired_devices() == [] + assert joiner._key_store.get("coord-node") is None + assert joiner._local_code["completing"] is False + assert revocations[-1] == { + "peer_public_key": _test_public_key("coord-node"), + "addrs": ["127.0.0.1"], + } + assert "join_persistence_failed" in joiner._audit.names() + + +def test_join_completion_rejects_an_expired_local_code(tmp_path): + coordinator, joiner, *_ = _loopback_pair(tmp_path) + code = joiner.start_join()["code"] + joiner.request_join("coordinator.local:8080") + coordinator.approve("join-node", code) + status = joiner.poll_join("coordinator.local:8080") + joiner._clock.now += CODE_TTL_SECONDS + 1 + + with pytest.raises(PairingExpiredError, match="expired"): + joiner.complete_join(status) + + assert joiner._local_code is None + assert joiner.paired_devices() == [] + + +def test_approval_requires_coordinator_ssh_material(tmp_path): + coordinator, joiner, *_ = _loopback_pair(tmp_path) + code = joiner.start_join()["code"] + joiner.request_join("coordinator.local:8080") + coordinator._address_provider = lambda: [] + + with pytest.raises(EnrollmentDriveError, match="peer was not paired"): + coordinator.approve("join-node", code) + + assert coordinator.paired_devices() == [] + assert [row["node_id"] for row in coordinator.pending_requests()] == ["join-node"] + + +def test_default_enrollment_requires_key_and_verified_address(monkeypatch): + from omlx.cluster import ssh_keys + + monkeypatch.setattr( + ssh_keys, + "get_or_create_ssh_key", + lambda: SimpleNamespace(fingerprint="SHA256:local"), + ) + with pytest.raises(PairingRequestError, match="SSH public key"): + default_enrollment_driver({"ssh_public_key": None, "addrs": ["127.0.0.1"]}) + with pytest.raises(EnrollmentDriveError, match="verified peer address"): + default_enrollment_driver( + { + "ssh_public_key": _test_public_key("peer"), + "ssh_host_public_key": _test_public_key("host-peer"), + "addrs": [], + } + ) + + +def test_default_enrollment_propagates_host_key_failure(monkeypatch): + from omlx.cluster import ssh_keys + + monkeypatch.setattr( + ssh_keys, + "get_or_create_ssh_key", + lambda: SimpleNamespace(fingerprint="SHA256:local"), + ) + monkeypatch.setattr(ssh_keys, "install_authorized_key", lambda **_kwargs: True) + monkeypatch.setattr( + ssh_keys, + "pin_enrolled_host_key", + lambda **_kwargs: (_ for _ in ()).throw( + RuntimeError("refusing changed SSH host key") + ), + ) + + with pytest.raises(RuntimeError, match="changed SSH host key"): + default_enrollment_driver( + { + "ssh_public_key": _test_public_key("peer"), + "ssh_host_public_key": _test_public_key("host-peer"), + "addrs": ["127.0.0.1"], + } + ) + + +def test_default_enrollment_formats_ipv6_known_host_target(monkeypatch): + from omlx.cluster import ssh_keys + + targets: list[str] = [] + monkeypatch.setattr( + ssh_keys, + "get_or_create_ssh_key", + lambda: SimpleNamespace(fingerprint="SHA256:local"), + ) + monkeypatch.setattr(ssh_keys, "install_authorized_key", lambda **_kwargs: True) + monkeypatch.setattr( + ssh_keys, + "pin_enrolled_host_key", + lambda *, hostname, public_key: targets.append(hostname) or True, + ) + + default_enrollment_driver( + { + "ssh_public_key": _test_public_key("peer"), + "ssh_host_public_key": _test_public_key("host-peer"), + "addrs": ["::1"], + } + ) + + assert targets == ["[::1]"] + + +# --- Input validation ------------------------------------------------------------- + + +def test_join_request_validation(tmp_path): + coordinator = _manager(tmp_path, node_id="coord-node", name="Coordinator") + joiner = _manager(tmp_path, node_id="join-node", name="Joiner") + joiner.start_join() + good = joiner.build_join_request() + + with pytest.raises(PairingRequestError, match="own cluster"): + coordinator.handle_join_request(good | {"node_id": "coord-node"}) + with pytest.raises(PairingRequestError, match="code_hash"): + coordinator.handle_join_request(good | {"code_hash": "zz"}) + with pytest.raises(PairingRequestError, match="code_salt"): + coordinator.handle_join_request(good | {"code_salt": "not-base64"}) + with pytest.raises(PairingRequestError, match="friendly_name"): + coordinator.handle_join_request(good | {"friendly_name": ""}) + with pytest.raises(PairingRequestError, match="caps"): + coordinator.handle_join_request(good | {"caps": ["not", "a", "dict"]}) + with pytest.raises(PairingRequestError, match="SSH public key"): + coordinator.handle_join_request( + good + | { + "ssh_public_key": ( + _test_public_key("join-node") + "\n" + _test_public_key("attacker") + ) + } + ) + with pytest.raises(PairingRequestError, match="http_port"): + coordinator.handle_join_request(good | {"http_port": 70000}) + with pytest.raises(PairingRequestError, match="6 digits"): + coordinator.approve("join-node", "12345") + + +def test_pending_requests_are_memory_only_and_capped(tmp_path): + clock = _Clock() + coordinator = _manager( + tmp_path, node_id="coord-node", name="Coordinator", clock=clock + ) + for index in range(5): + joiner = _manager(tmp_path, node_id=f"join-{index}", name=f"J{index}") + code = joiner.start_join()["code"] + coordinator.handle_join_request(joiner.build_join_request(code)) + assert len(coordinator.pending_requests()) == 5 + # Nothing pending was persisted to devices.json. + store = JsonDeviceStore(tmp_path / "coord-node") + assert store.list_paired() == [] + + +def test_pending_request_is_idempotent_but_cannot_be_overwritten(tmp_path): + coordinator = _manager(tmp_path, node_id="coord-node", name="Coordinator") + joiner = _manager(tmp_path, node_id="join-node", name="Joiner") + joiner.start_join() + request = joiner.build_join_request() + + first = coordinator.handle_join_request(request) + repeated = coordinator.handle_join_request(dict(request)) + assert repeated == first + + with pytest.raises(PairingStateError, match="different join request"): + coordinator.handle_join_request( + request | {"ssh_host_public_key": _test_public_key("attacker-host")} + ) + + +# --- Persistence ------------------------------------------------------------------ + + +def test_key_store_persists_with_private_permissions(tmp_path): + store = PairingKeyStore(tmp_path) + store.set("node-a", {"cluster_key": "ab" * 32, "paired_at": 1.0}) + mode = stat.S_IMODE(store.path.stat().st_mode) + assert mode == 0o600 + + reloaded = PairingKeyStore(tmp_path) + assert reloaded.get("node-a")["cluster_key"] == "ab" * 32 + assert reloaded.remove("node-a") is not None + assert PairingKeyStore(tmp_path).get("node-a") is None + + +def test_key_store_fails_closed_on_corruption(tmp_path): + store = PairingKeyStore(tmp_path) + store.set("node-a", {"cluster_key": "ab" * 32}) + store.path.write_text("{not json") + reloaded = PairingKeyStore(tmp_path) + assert reloaded.get("node-a") is None + assert reloaded.load_error is not None + + +def test_device_store_round_trip_and_permissions(tmp_path): + store = JsonDeviceStore(tmp_path) + store.put_paired( + { + "node_id": "n1", + "friendly_name": "Peer", + "caps": {}, + "paired_at": 1.0, + "last_addrs": ["10.0.0.2"], + } + ) + assert stat.S_IMODE(store.path.stat().st_mode) == 0o600 + payload = json.loads(store.path.read_text()) + assert payload["schema_version"] == 1 + reloaded = JsonDeviceStore(tmp_path) + assert reloaded.get("n1")["state"] == "paired" + assert reloaded.remove("n1") is True + assert reloaded.remove("n1") is False + + +def test_fallback_identity_persists_node_id(tmp_path): + first = pairing_load(tmp_path) + second = pairing_load(tmp_path) + assert first["node_id"] == second["node_id"] + path = tmp_path / "cluster" / "identity.json" + assert stat.S_IMODE(path.stat().st_mode) == 0o600 + assert json.loads(path.read_text())["schema_version"] == 1 + + +def pairing_load(base_path): + from omlx.cluster.pairing import load_node_identity + + return load_node_identity(base_path) + + +def test_audit_log_appends_json_lines(tmp_path): + log = PairingAuditLog(tmp_path / "cluster" / "pairing-audit.jsonl") + log.record("approve_success", node_id="n1") + log.record("device_unpaired", node_id="n1", detail={"removed_key": True}) + lines = log.path.read_text().splitlines() + assert len(lines) == 2 + assert json.loads(lines[1])["event"] == "device_unpaired" + assert stat.S_IMODE(log.path.stat().st_mode) == 0o600 + + +# --- Module A bridge --------------------------------------------------------------- + + +def test_module_a_registry_is_used_via_feature_detection(tmp_path): + registry = _FakeModuleARegistry() + coordinator, joiner, *_ = _loopback_pair(tmp_path) + coordinator_with_a = _manager( + tmp_path, node_id="coord-b", name="CoordB", registry=registry + ) + joiner2 = _manager(tmp_path, node_id="join-b", name="JoinB") + code = joiner2.start_join()["code"] + coordinator_with_a.handle_join_request(joiner2.build_join_request(code)) + coordinator_with_a.approve("join-b", code) + + assert registry.records["join-b"]["state"] == "paired" + assert [d["node_id"] for d in coordinator_with_a.paired_devices()] == ["join-b"] + coordinator_with_a.unpair("join-b") + assert registry.records == {} + + +def test_registry_bridge_reports_api_drift_loudly(): + bridge = DeviceRegistryBridge(object()) + with pytest.raises(PairingStateError, match="DeviceRegistry exposes none of"): + bridge.put_paired({"node_id": "n"}) + + +def test_registry_bridge_against_real_module_a_registry(tmp_path): + """Integration lock: the bridge drives Module A's real DeviceRegistry. + + mark_paired (not merge) must persist the peer as paired — merge would + leave a newly approved device memory-only. + """ + + from omlx.cluster.registry import DeviceRegistry + + registry = DeviceRegistry(tmp_path / "devices.json") + bridge = DeviceRegistryBridge(registry) + bridge.put_paired( + { + "node_id": "peer-real", + "friendly_name": "studio", + "caps": {"chip": "M3"}, + "paired_at": 42.0, + "last_addrs": ["192.168.5.2"], + "state": "paired", + } + ) + + assert registry.is_paired("peer-real") + stored = bridge.get("peer-real") + assert stored["friendly_name"] == "studio" + assert stored["paired_at"] == 42.0 + assert [d["node_id"] for d in bridge.list_paired()] == ["peer-real"] + # Persisted to disk, not memory-only. + reloaded = DeviceRegistry(tmp_path / "devices.json") + assert reloaded.is_paired("peer-real") + assert bridge.remove("peer-real") is True + assert not registry.is_paired("peer-real") + + +# --- HTTP endpoints ----------------------------------------------------------------- + + +def _client(tmp_path): + clock = _Clock() + manager = _manager(tmp_path, node_id="coord-node", name="Coordinator", clock=clock) + pairing_routes.set_pairing_manager_getter(lambda: manager) + app = FastAPI() + app.include_router(pairing_routes.pair_router) + app.include_router(pairing_routes.pair_admin_router) + return TestClient(app), manager, clock + + +@pytest.fixture(autouse=True) +def _restore_manager_getter(): + yield + pairing_routes.set_pairing_manager_getter(None) + + +def test_endpoints_full_flow(tmp_path, monkeypatch): + client, manager, _ = _client(tmp_path) + joiner = _manager(tmp_path, node_id="join-node", name="Joiner") + paired_marks: list[str] = [] + monkeypatch.setattr( + "omlx.cluster.discovery.get_discovery_service", + lambda: SimpleNamespace(mark_paired=paired_marks.append), + ) + code = joiner.start_join()["code"] + payload = joiner.build_join_request(code) + + response = client.post("/api/cluster/pair/request", json=payload) + assert response.status_code == 202 + assert response.json()["state"] == "awaiting_approval" + + # Wrong code → 403, then lockout → 423. + wrong = "000000" if code != "000000" else "000001" + for _ in range(MAX_CODE_ATTEMPTS): + response = client.post( + "/api/cluster/pair/approve", json={"node_id": "join-node", "code": wrong} + ) + assert response.status_code == 423 + response = client.post( + "/api/cluster/pair/approve", json={"node_id": "join-node", "code": code} + ) + assert response.status_code == 423 + + # Re-request after lockout is over; approve succeeds. + manager._pending["join-node"].locked_until = manager._clock() - 1 + response = client.post( + "/api/cluster/pair/approve", json={"node_id": "join-node", "code": code} + ) + assert response.status_code == 200 + assert response.json()["state"] == "paired" + assert paired_marks == ["join-node"] + + status = client.get("/api/cluster/pair/status/join-node").json() + assert status["state"] == "approved" + assert status["coordinator"]["node_id"] == "coord-node" + joined = joiner.complete_join(status, code) + assert joined["node_id"] == "coord-node" + + response = client.delete("/api/cluster/devices/join-node") + assert response.status_code == 200 + assert response.json()["unpaired"] is True + assert client.get("/api/cluster/pair/status/join-node").json()["state"] == "unknown" + + +def test_public_pairing_endpoints_are_rate_limited(tmp_path, monkeypatch): + client, _, _ = _client(tmp_path) + joiner = _manager(tmp_path, node_id="join-node", name="Joiner") + payload = joiner.build_join_request(joiner.start_join()["code"]) + monkeypatch.setattr( + pairing_routes.pair_request_rate_limiter, + "allow", + lambda _client: False, + ) + assert client.post("/api/cluster/pair/request", json=payload).status_code == 429 + + monkeypatch.setattr( + pairing_routes.pair_status_rate_limiter, + "allow", + lambda _client: False, + ) + assert client.get("/api/cluster/pair/status/join-node").status_code == 429 + + +def test_pair_request_binds_enrollment_to_http_source(tmp_path): + captured: list[dict] = [] + + class _CaptureManager: + @staticmethod + def handle_join_request(payload): + captured.append(payload) + return {"state": "awaiting_approval"} + + pairing_routes.set_pairing_manager_getter(lambda: _CaptureManager()) + app = FastAPI() + app.include_router(pairing_routes.pair_router) + client = TestClient(app, client=("198.51.100.23", 50000)) + payload = { + "node_id": "join-node", + "friendly_name": "Joiner", + "caps": {}, + "code_hash": "a" * 64, + "code_salt": base64.b64encode(b"0" * 16).decode(), + "http_port": 8000, + "addrs": ["203.0.113.99"], + "ssh_public_key": _test_public_key("join-node"), + "ssh_host_public_key": _test_public_key("host-join-node"), + } + + response = client.post("/api/cluster/pair/request", json=payload) + + assert response.status_code == 202 + assert captured[0]["addrs"] == ["198.51.100.23"] + + +def test_endpoint_error_mapping(tmp_path): + client, manager, clock = _client(tmp_path) + joiner = _manager(tmp_path, node_id="join-node", name="Joiner") + code = joiner.start_join()["code"] + + # Approve with no pending request → 404. + response = client.post( + "/api/cluster/pair/approve", json={"node_id": "ghost", "code": "123456"} + ) + assert response.status_code == 404 + + client.post("/api/cluster/pair/request", json=joiner.build_join_request(code)) + wrong = "000000" if code != "000000" else "000001" + response = client.post( + "/api/cluster/pair/approve", json={"node_id": "join-node", "code": wrong} + ) + assert response.status_code == 403 + + # Expiry → 410. + clock.now += CODE_TTL_SECONDS + 1 + response = client.post( + "/api/cluster/pair/approve", json={"node_id": "join-node", "code": code} + ) + assert response.status_code == 410 + + # Deny unknown → 404; delete unknown → 404. + assert ( + client.post("/api/cluster/pair/deny", json={"node_id": "ghost"}).status_code + == 404 + ) + assert client.delete("/api/cluster/devices/ghost").status_code == 404 + + +def test_endpoint_deny_flow(tmp_path): + client, manager, _ = _client(tmp_path) + joiner = _manager(tmp_path, node_id="join-node", name="Joiner") + joiner.start_join() + client.post("/api/cluster/pair/request", json=joiner.build_join_request()) + + response = client.post("/api/cluster/pair/deny", json={"node_id": "join-node"}) + assert response.status_code == 200 + assert client.get("/api/cluster/pair/status/join-node").json()["state"] == "denied" + + +def test_request_validation_rejects_bad_payloads(tmp_path): + client, _, _ = _client(tmp_path) + joiner = _manager(tmp_path, node_id="join-node", name="Joiner") + joiner.start_join() + good = joiner.build_join_request() + + assert ( + client.post( + "/api/cluster/pair/request", json=good | {"code_hash": "x"} + ).status_code + == 422 + ) + assert ( + client.post("/api/cluster/pair/request", json=good | {"extra": 1}).status_code + == 422 + ) + assert ( + client.post( + "/api/cluster/pair/approve", json={"node_id": "n", "code": "12345"} + ).status_code + == 422 + ) + assert ( + client.post( + "/api/cluster/pair/request", json=good | {"node_id": "coord-node"} + ).status_code + == 400 + ) + + +def test_unconfigured_manager_returns_503(tmp_path): + pairing_routes.set_pairing_manager_getter( + lambda: (_ for _ in ()).throw(RuntimeError("cluster pairing is not configured")) + ) + app = FastAPI() + app.include_router(pairing_routes.pair_router) + app.include_router(pairing_routes.pair_admin_router) + client = TestClient(app) + assert client.get("/api/cluster/pair/status/x").status_code == 503 + assert client.delete("/api/cluster/devices/x").status_code == 503 + + +# --- Legacy non-regression ---------------------------------------------------------- + + +def test_legacy_pairing_endpoints_still_registered(): + from omlx.cluster import routes + + paths = { + (route.path, tuple(sorted(route.methods))) + for route in routes.router.routes + for methods in [getattr(route, "methods", set())] + if methods + } + expected = { + "/admin/api/cluster/pairing-token", + "/admin/api/cluster/verify-pairing-token", + "/admin/api/cluster/ssh-key", + "/admin/api/cluster/ssh-key/generate", + "/admin/api/cluster/ssh-key/exchange-token", + "/admin/api/cluster/ssh-key/exchange", + "/admin/api/cluster/ssh-key/store-keychain", + "/admin/api/cluster/join-keys", + "/admin/api/cluster/join-status", + } + present = {path for path, _ in paths} + assert expected <= present + + +def test_legacy_pairing_token_flow_still_works(): + from omlx.cluster.discovery import generate_pairing_token, verify_pairing_token + + secret = "x" * 32 + token = generate_pairing_token(shared_secret=secret) + assert verify_pairing_token(token, shared_secret=secret) is True + assert verify_pairing_token(token, shared_secret="y" * 32) is False + + +def test_join_status_carries_coordinator_caps_and_key(tmp_path): + """The poll path is the only one the UI drives: complete_join persists + whatever join_status returns, so the coordinator block must carry the + same caps/ssh key that approve() returns synchronously.""" + + coordinator, joiner, _, _, _ = _loopback_pair(tmp_path) + shown = joiner.start_join() + joiner.request_join("coord:8000") + coordinator.approve("join-node", shown["code"]) + + status = coordinator.join_status("join-node") + assert status["state"] == "approved" + assert status["coordinator"]["caps"] == {"chip": "M4 Max", "ram_gb": 128} + assert status["coordinator"]["ssh_public_key"] == _test_public_key("coord-node") + assert status["coordinator"]["ssh_host_public_key"] == _test_public_key( + "host-coord-node" + ) + + record = joiner.complete_join(status) + assert record["caps"] == {"chip": "M4 Max", "ram_gb": 128} + + +def test_join_status_rejects_substituted_coordinator_identity(tmp_path): + coordinator, joiner, *_ = _loopback_pair(tmp_path) + shown = joiner.start_join() + joiner.request_join("coord:8000") + coordinator.approve("join-node", shown["code"]) + status = coordinator.join_status("join-node") + status["coordinator"] = dict(status["coordinator"]) + status["coordinator"]["ssh_host_public_key"] = _test_public_key("attacker-host") + + with pytest.raises(PairingCodeError, match="identity was altered"): + joiner.complete_join(status) + + assert joiner.paired_devices() == [] diff --git a/tests/test_cluster_seams.py b/tests/test_cluster_seams.py index 2ba902833e..425e1235f0 100644 --- a/tests/test_cluster_seams.py +++ b/tests/test_cluster_seams.py @@ -29,7 +29,8 @@ # Template literals interpolate with ${...}, which may contain calls and nested # parens: /deployments/${encodeURIComponent(id)} _CLUSTER_URL = re.compile( - re.escape(_PREFIX) + r"(?P(?:\$\{[^{}]*(?:\([^)]*\))?[^{}]*\}|[A-Za-z0-9/_\-.])*)" + re.escape(_PREFIX) + + r"(?P(?:\$\{[^{}]*(?:\([^)]*\))?[^{}]*\}|[A-Za-z0-9/_\-.])*)" ) @@ -105,10 +106,13 @@ def test_pairing_token_round_trips(): from omlx.cluster.discovery import generate_pairing_token, verify_pairing_token secret = "correct-horse-battery-staple" - assert verify_pairing_token( - generate_pairing_token(shared_secret=secret), - shared_secret=secret, - ) is True + assert ( + verify_pairing_token( + generate_pairing_token(shared_secret=secret), + shared_secret=secret, + ) + is True + ) def test_pairing_token_rejects_a_tampered_payload(): @@ -230,11 +234,15 @@ def test_no_unreachable_functions_in_the_cluster_package(): # Peer import preflight, exposed ahead of the /autoconfigure handler # that will call it alongside preflight_issues. ("autoconfigure.py", "peer_import_issues"), + # Test hooks that drop process-wide v2 singletons between cases; only + # the test suite calls them (production swaps via configure_*). + ("identity.py", "reset_configured_identity"), + ("registry.py", "reset_configured_device_registry"), + ("pairing.py", "reset_pairing_manager"), + ("pairing_routes.py", "set_pairing_manager_getter"), } - sources = { - path: path.read_text() for path in (_REPO / "omlx").rglob("*.py") - } + sources = {path: path.read_text() for path in (_REPO / "omlx").rglob("*.py")} uncalled = [] for path in sorted(_CLUSTER.glob("*.py")): @@ -429,10 +437,13 @@ def test_key_exchange_rejects_a_tampered_token(): payload["node_id"] = "attacker-mac" forged = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode() - assert ssh_keys.verify_key_exchange_token( - forged, - shared_secret="correct-horse-battery-staple", - ) is None + assert ( + ssh_keys.verify_key_exchange_token( + forged, + shared_secret="correct-horse-battery-staple", + ) + is None + ) def test_key_exchange_rejects_the_wrong_shared_secret(): @@ -447,10 +458,13 @@ def test_key_exchange_rejects_the_wrong_shared_secret(): shared_secret="correct-horse-battery-staple", ) - assert ssh_keys.verify_key_exchange_token( - token, - shared_secret="a-different-shared-secret", - ) is None + assert ( + ssh_keys.verify_key_exchange_token( + token, + shared_secret="a-different-shared-secret", + ) + is None + ) def test_key_exchange_rejects_an_authenticated_ssh_option_target(): @@ -488,7 +502,10 @@ def test_key_exchange_rejects_an_authenticated_ssh_option_target(): ).hexdigest() forged = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode() - assert ssh_keys.verify_key_exchange_token( - forged, - shared_secret=secret, - ) is None + assert ( + ssh_keys.verify_key_exchange_token( + forged, + shared_secret=secret, + ) + is None + ) diff --git a/tests/test_cluster_v2_discovery.py b/tests/test_cluster_v2_discovery.py new file mode 100644 index 0000000000..d8ab555251 --- /dev/null +++ b/tests/test_cluster_v2_discovery.py @@ -0,0 +1,1199 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Offline tests for the v2 discovery service. + +No real multicast, mDNS, or HTTP happens here: sockets, the probe function, +the clock, interface listing, and tailscale status are all injected. +""" + +import errno +import io +import json +import logging +import socket +import struct +import time + +from omlx.cluster.discovery import ( + _TX_FAIL_RESET_ROUNDS, + MULTICAST_GROUP, + MULTICAST_PORT, + DiscoveryConfig, + DiscoveryService, + PeerCaps, + PeerRecord, + _classify_link, + _http_probe_node_id, + _system_proxy_probe_node_id, + _tailscale_executable, + cluster_hash_u64, + decode_hello, + decode_wassup, + encode_hello, + encode_wassup, +) +from omlx.cluster.identity import NodeIdentity +from omlx.cluster.registry import DeviceRegistry + + +class FakeHTTPStream: + def __init__(self, response: bytes) -> None: + self.response = response + self.sent = b"" + + def sendall(self, payload: bytes) -> None: + self.sent += payload + + def makefile(self, *_args, **_kwargs): + return io.BytesIO(self.response) + + +class FakeSystemProxy: + def __init__(self, response: bytes) -> None: + self.stream = FakeHTTPStream(response) + self.closed = False + + def close(self) -> None: + self.closed = True + + +class FakeClock: + def __init__(self, start: float = 1000.0) -> None: + self.now = start + + def __call__(self) -> float: + return self.now + + def advance(self, seconds: float) -> None: + self.now += seconds + + +class FakeSocket: + """Duck-typed stand-in for the UDP multicast socket.""" + + def __init__(self) -> None: + self.sent: list[tuple[bytes, tuple]] = [] + self.inbox: list[tuple[bytes, tuple]] = [] + self.closed = False + self.joined: list[bytes] = [] + self.opts: list[tuple] = [] + + def setsockopt(self, *args): + self.opts.append(args) + if len(args) == 3 and args[1] == socket.IPV6_JOIN_GROUP: + self.joined.append(args[2]) + + def bind(self, addr): + pass + + def settimeout(self, value): + pass + + def sendto(self, data, addr): + self.sent.append((bytes(data), tuple(addr))) + + def recvfrom(self, size): + if not self.inbox: + raise TimeoutError() + return self.inbox.pop(0) + + def close(self): + self.closed = True + + +def _identity(node_id: str, name: str = "node") -> NodeIdentity: + return NodeIdentity(node_id=node_id, friendly_name=name, created_at=1.0) + + +def _service( + node_id: str = "aaaa-node", + *, + clock: FakeClock | None = None, + prober=None, + socket_factory=None, + registry=None, + tailscale_status=None, + zeroconf_module=None, + interface_lister=None, + config: DiscoveryConfig | None = None, +): + clock = clock or FakeClock() + cfg = config or DiscoveryConfig(cluster_name="omlx", http_port=8000) + service = DiscoveryService( + _identity(node_id), + registry + if registry is not None + else DeviceRegistry("/nonexistent/dir/devices.json"), + cfg, + socket_factory=socket_factory, + prober=prober or (lambda ip, port, timeout: None), + clock=clock, + interface_lister=interface_lister or (lambda: ["en0"]), + tailscale_status=tailscale_status, + zeroconf_module=zeroconf_module, + ) + return service, clock + + +# -- codec -------------------------------------------------------------------- + + +def test_hello_codec_roundtrip(): + payload = encode_hello(0xDEADBEEF, cluster_hash_u64("omlx")) + assert decode_hello(payload) == (0xDEADBEEF, cluster_hash_u64("omlx")) + + +def test_hello_codec_rejects_garbage(): + assert decode_hello(b"") is None + assert decode_hello(b"OMLX") is None + assert decode_hello(b"NOPE" + b"\x00" * 16) is None + assert decode_hello(encode_hello(1, 2) + b"extra") is None + + +def test_wassup_codec_roundtrip(): + payload = encode_wassup(7, "node-1", 8000) + assert decode_wassup(payload) == { + "nonce": 7, + "node_id": "node-1", + "http_port": 8000, + } + + +def test_wassup_codec_rejects_garbage(): + assert decode_wassup(b"") is None + assert decode_wassup(b"OMLXW{not json") is None + assert decode_wassup(b"OMLXW" + json.dumps({"nonce": -1}).encode()) is None + assert ( + decode_wassup( + b"OMLXW" + json.dumps({"nonce": 1, "node_id": "x", "http_port": 0}).encode() + ) + is None + ) + + +def test_cluster_hash_is_blake2s_prefix(): + import hashlib + + expected = int.from_bytes(hashlib.blake2s(b"omlx").digest()[:8], "big") + assert cluster_hash_u64("omlx") == expected + assert cluster_hash_u64("omlx") != cluster_hash_u64("other") + + +# -- HELLO handling ----------------------------------------------------------- + + +def test_hello_from_same_cluster_sets_multicast_ok_and_replies_wassup(): + sock = FakeSocket() + service, clock = _service(socket_factory=lambda: sock) + assert service.multicast_ok is False + + service._handle_hello(123, service._cluster_hash, ("fe80::99", 53413), sock) + + assert service.multicast_ok is True + assert len(sock.sent) == 1 + reply = decode_wassup(sock.sent[0][1] and sock.sent[0][0]) + assert reply == { + "nonce": 123, + "node_id": "aaaa-node", + "http_port": 8000, + } + assert sock.sent[0][1] == ("fe80::99", 53413) + + +def test_multicast_ok_expires_after_window(): + service, clock = _service() + service._handle_hello(1, service._cluster_hash, ("fe80::99", 53413), None) + assert service.multicast_ok is True + clock.advance(4.9) + assert service.multicast_ok is True + clock.advance(0.2) + assert service.multicast_ok is False + + +def test_hello_with_foreign_cluster_hash_is_ignored_silently(): + sock = FakeSocket() + service, _ = _service(socket_factory=lambda: sock) + + service._handle_hello( + 1, cluster_hash_u64("someone-else"), ("fe80::99", 53413), sock + ) + + assert sock.sent == [] + assert service.peers() == [] + assert service.multicast_ok is False + + +def test_own_nonce_echo_is_dropped(): + sock = FakeSocket() + service, _ = _service(socket_factory=lambda: sock) + service._nonces.append(555) # simulate a HELLO we sent + + service._handle_hello(555, service._cluster_hash, ("fe80::1", 53413), sock) + + assert sock.sent == [] + assert service.multicast_ok is False + + +# -- WASSUP handling ---------------------------------------------------------- + + +def _announce_nonce(service) -> int: + service._nonces.append(42) + return 42 + + +def test_wassup_creates_peer_and_candidate(): + service, _ = _service("aaaa-node") # lower id than peer + _announce_nonce(service) + + service._handle_wassup( + {"nonce": 42, "node_id": "bbbb-node", "http_port": 8000}, + ("fe80::99", 53413), + ) + + peers = service.peers() + assert [p.node_id for p in peers] == ["bbbb-node"] + assert peers[0].http_port == 8000 + assert peers[0].addrs == [{"ip": "fe80::99", "if_type": "unknown"}] + assert ("fe80::99", 8000) in service._candidates + + +def test_wassup_with_unknown_nonce_is_ignored(): + service, _ = _service() + service._handle_wassup( + {"nonce": 999, "node_id": "bbbb-node", "http_port": 8000}, + ("fe80::99", 53413), + ) + assert service.peers() == [] + + +def test_higher_node_id_probes_immediately_lower_defers(): + calls: list[tuple[str, int]] = [] + + def prober(ip, port, timeout): + calls.append((ip, port)) + return {"node_id": "aaaa-node", "version": "0.6.1", "cluster_name": "omlx"} + + # We are zzzz-node: higher than aaaa-node → we initiate contact. + service, _ = _service("zzzz-node", prober=prober) + _announce_nonce(service) + service._handle_wassup( + {"nonce": 42, "node_id": "aaaa-node", "http_port": 8000}, + ("fe80::99", 53413), + ) + assert calls == [("fe80::99", 8000)] + + # We are aaaa-node: lower → no immediate probe. + calls.clear() + service2, _ = _service("aaaa-node", prober=prober) + _announce_nonce(service2) + service2._handle_wassup( + {"nonce": 42, "node_id": "zzzz-node", "http_port": 8000}, + ("fe80::99", 53413), + ) + assert calls == [] + + +def test_wassup_dedupes_repeated_announcements(): + service, _ = _service("aaaa-node") + _announce_nonce(service) + for _ in range(3): + service._handle_wassup( + {"nonce": 42, "node_id": "bbbb-node", "http_port": 8000}, + ("fe80::99", 53413), + ) + peers = service.peers() + assert len(peers) == 1 + assert peers[0].addrs == [{"ip": "fe80::99", "if_type": "unknown"}] + + +# -- verification probe -------------------------------------------------------- + + +def test_successful_probe_fills_peer_details_and_link(): + service, _ = _service( + "aaaa-node", + prober=lambda ip, port, timeout: { + "node_id": "bbbb-node", + "version": "0.6.1", + "cluster_name": "omlx", + }, + ) + service.add_manual("10.0.0.5", 8000) + service.probe_now() + + peer = service.peers()[0] + assert peer.node_id == "bbbb-node" + assert peer.version == "0.6.1" + assert peer.state == "discovered" + assert peer.link in {"tb", "ethernet", "wifi"} # RTT-classified + + +def test_probe_node_id_mismatch_drops_address(): + service, _ = _service( + "zzzz-node", + prober=lambda ip, port, timeout: { + "node_id": "impostor", + "version": "0.6.1", + "cluster_name": "omlx", + }, + ) + _announce_nonce(service) + service._handle_wassup( + {"nonce": 42, "node_id": "bbbb-node", "http_port": 8000}, + ("fe80::99", 53413), + ) + + # The higher-id immediate probe already ran and found a mismatch. + peer = service.peers()[0] + assert peer.addrs == [] + assert ("fe80::99", 8000) not in service._candidates + + +def test_failed_probe_keeps_candidate_unverified_for_retry(): + clock = FakeClock() + service, _ = _service(clock=clock) # prober default: None (unreachable) + service.add_manual("10.0.0.5", 8000) + service.probe_now() + assert service.peers() == [] + assert ("10.0.0.5", 8000) in service._candidates + assert service._candidates[("10.0.0.5", 8000)]["verified"] is False + + +def test_http_probe_falls_back_to_system_python_carrier(monkeypatch): + from omlx.cluster import discovery + + monkeypatch.setattr( + discovery.urllib.request, + "urlopen", + lambda *_args, **_kwargs: (_ for _ in ()).throw( + OSError("macOS denied direct subnet") + ), + ) + expected = { + "node_id": "peer-node", + "version": "0.6.4.dev1", + "cluster_name": "omlx", + } + calls = [] + monkeypatch.setattr( + discovery, + "_system_proxy_probe_node_id", + lambda ip, port, timeout: calls.append((ip, port, timeout)) or expected, + ) + + assert _http_probe_node_id("10.0.0.1", 8000, 3.0) == expected + assert calls == [("10.0.0.1", 8000, 3.0)] + + +def test_tailscale_probe_failure_does_not_spawn_direct_subnet_proxy(monkeypatch): + from omlx.cluster import discovery + + monkeypatch.setattr( + discovery.urllib.request, + "urlopen", + lambda *_args, **_kwargs: (_ for _ in ()).throw(OSError("connection refused")), + ) + monkeypatch.setattr( + discovery, + "_system_proxy_probe_node_id", + lambda *_args: (_ for _ in ()).throw( + AssertionError("Tailscale must stay on its direct userspace route") + ), + ) + + assert _http_probe_node_id("100.64.0.2", 8000, 3.0) is None + + +def test_system_python_carrier_parses_bounded_node_probe(monkeypatch): + from omlx.cluster import system_socket_proxy + + body = json.dumps( + { + "node_id": "peer-node", + "version": "0.6.4.dev1", + "cluster_name": "omlx", + } + ).encode() + response = ( + b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n" + + f"Content-Length: {len(body)}\r\nConnection: close\r\n\r\n".encode() + + body + ) + proxy = FakeSystemProxy(response) + monkeypatch.setattr( + system_socket_proxy, + "should_proxy_control_socket", + lambda _host: True, + ) + monkeypatch.setattr( + system_socket_proxy, + "open_system_tcp_proxy", + lambda host, port, *, timeout: proxy, + ) + + payload = _system_proxy_probe_node_id("10.0.0.1", 8000, 3.0) + + assert payload is not None and payload["node_id"] == "peer-node" + assert proxy.stream.sent.startswith(b"GET /api/cluster/node_id HTTP/1.1\r\n") + assert proxy.closed is True + + +def test_paired_manual_address_and_port_rehydrate_after_reboot(tmp_path): + path = tmp_path / "devices.json" + registry = DeviceRegistry(path) + registry.mark_paired( + "bbbb-node", + friendly_name="studio-b", + addrs=["10.0.0.5", "fe80::1", "not-an-ip"], + http_port=9123, + paired_at=1.0, + ) + restored = DeviceRegistry(path) + calls = [] + + service, _ = _service( + "aaaa-node", + registry=restored, + prober=lambda ip, port, timeout: ( + calls.append((ip, port)) + or { + "node_id": "bbbb-node", + "friendly_name": "studio-b", + "version": "0.6.1", + "cluster_name": "omlx", + } + ), + ) + + assert ("10.0.0.5", 9123) in service._candidates + assert service._candidates[("10.0.0.5", 9123)]["node_id"] == "bbbb-node" + assert service._candidates[("10.0.0.5", 9123)]["if_type"] == "paired" + assert all(ip != "not-an-ip" for ip, _ in service._candidates) + assert all(ip != "fe80::1" for ip, _ in service._candidates) + + service.probe_now() + + assert calls == [("10.0.0.5", 9123)] + [peer] = service.peers() + assert peer.node_id == "bbbb-node" + assert peer.http_port == 9123 + assert peer.paired is True + assert peer.state == "discovered" + + +def test_legacy_paired_address_rehydrates_on_the_configured_default_port(tmp_path): + registry = DeviceRegistry(tmp_path / "devices.json") + registry.mark_paired( + "bbbb-node", + friendly_name="studio-b", + addrs=["10.0.0.8"], + paired_at=1.0, + ) + + service, _ = _service( + "aaaa-node", + registry=DeviceRegistry(registry.path), + config=DiscoveryConfig(cluster_name="omlx", http_port=8765), + ) + + assert ("10.0.0.8", 8765) in service._candidates + assert service._candidates[("10.0.0.8", 8765)]["node_id"] == "bbbb-node" + + +def test_probe_sweep_respects_interval(): + calls: list[tuple[str, int]] = [] + clock = FakeClock() + service, _ = _service( + clock=clock, + prober=lambda ip, port, timeout: calls.append((ip, port)) or None, + ) + service.add_manual("10.0.0.5", 8000) + service.probe_now() + service.probe_now() # too soon: deduped by probe interval + assert calls == [("10.0.0.5", 8000)] + clock.advance(10.0) + service.probe_now() + assert calls == [("10.0.0.5", 8000)] * 2 + + +def test_verified_candidate_uses_heartbeat_cadence(): + calls: list[tuple[str, int]] = [] + clock = FakeClock() + service, _ = _service( + clock=clock, + prober=lambda ip, port, timeout: ( + calls.append((ip, port)) + or { + "node_id": "peer-node", + "version": "0.6.4.dev1", + "cluster_name": "omlx", + } + ), + ) + service.add_manual("10.0.0.5", 8000) + service.probe_now() + clock.advance(service.config.heartbeat_interval) + service.probe_now() + + assert calls == [("10.0.0.5", 8000)] * 2 + assert service.peers()[0].state == "discovered" + + +def test_explicit_candidate_probe_bypasses_periodic_dedupe(): + calls: list[tuple[str, int]] = [] + service, _ = _service( + prober=lambda ip, port, timeout: calls.append((ip, port)) or None, + ) + service.add_manual("10.0.0.5", 8000) + + service.probe_candidate_now("10.0.0.5", 8000) + service.probe_candidate_now("10.0.0.5", 8000) + + assert calls == [("10.0.0.5", 8000)] * 2 + [state] = service.health()["candidate_states"] + assert state["last_transport"] == "custom" + assert state["last_error"] == "probe returned no identity" + + +# -- liveness ------------------------------------------------------------------- + + +def _verified_peer(service, node_id="bbbb-node"): + _announce_nonce(service) + service._handle_wassup( + {"nonce": 42, "node_id": node_id, "http_port": 8000}, + ("fe80::99", 53413), + ) + return service.peers()[0] + + +def test_liveness_transitions_discovered_suspect_dead(): + clock = FakeClock() + service, _ = _service("aaaa-node", clock=clock) + events: list[tuple[str, str]] = [] + service.on_change(lambda peer: events.append((peer.node_id, peer.state))) + + peer = _verified_peer(service) + assert peer.state == "discovered" + assert ("bbbb-node", "discovered") in events # new-peer event + + clock.advance(6.0) + service.tick_liveness() + assert peer.state == "suspect" + + clock.advance(24.0) + service.tick_liveness() + assert peer.state == "dead" + + clock.advance(3600) + service.tick_liveness() + assert peer.state == "dead" + + states = [state for _, state in events] + assert states == ["discovered", "suspect", "dead"] + + +def test_fresh_sign_of_life_revives_dead_peer(): + clock = FakeClock() + service, _ = _service("aaaa-node", clock=clock) + peer = _verified_peer(service) + clock.advance(60.0) + service.tick_liveness() + assert peer.state == "dead" + + service._nonces.append(43) + service._handle_wassup( + {"nonce": 43, "node_id": "bbbb-node", "http_port": 8000}, + ("fe80::99", 53413), + ) + assert peer.state == "discovered" + + +def test_on_change_callback_failure_does_not_kill_service(): + service, _ = _service("aaaa-node") + service.on_change(lambda peer: 1 / 0) + peer = _verified_peer(service) # must not raise + assert peer.state == "discovered" + + +# -- registry integration ------------------------------------------------------ + + +def test_discovered_peer_merges_into_registry_unpaired(tmp_path): + registry = DeviceRegistry(tmp_path / "devices.json") + service, _ = _service( + "aaaa-node", + registry=registry, + prober=lambda *a: { + "node_id": "bbbb-node", + "version": "0.6.1", + "cluster_name": "omlx", + }, + ) + _verified_peer(service) + + assert registry.discovered()[0]["node_id"] == "bbbb-node" + assert registry.paired() == [] + assert service.peers()[0].paired is False + + registry.mark_paired("bbbb-node", friendly_name="peer") + service._merge_registry(service.peers()[0]) + assert service.peers()[0].paired is True + + +# -- tailscale ------------------------------------------------------------------ + + +def test_tailscale_peers_become_candidates(): + status = { + "Peer": { + "k1": {"TailscaleIPs": ["100.64.0.2", "fe80::1"]}, + "k2": {"TailscaleIPs": ["100.64.0.3"]}, + } + } + service, _ = _service(tailscale_status=lambda: status) + service._tailscale_sweep() + + assert ("100.64.0.2", 8000) in service._candidates + assert ("100.64.0.3", 8000) in service._candidates + assert service._candidates[("100.64.0.2", 8000)]["if_type"] == "tailscale" + # Non-tailscale addresses are not picked up from tailscale status. + assert all(":" not in ip for ip, _ in service._candidates) + + +def test_tailscale_sweep_ignores_offline_peers(): + service, _ = _service( + tailscale_status=lambda: { + "Peer": { + "online": { + "Online": True, + "TailscaleIPs": ["100.64.0.2"], + }, + "offline": { + "Online": False, + "TailscaleIPs": ["100.64.0.3"], + }, + } + } + ) + + service._tailscale_sweep() + + assert ("100.64.0.2", 8000) in service._candidates + assert ("100.64.0.3", 8000) not in service._candidates + + +def test_tailscale_absent_is_a_noop(): + service, _ = _service(tailscale_status=lambda: None) + service._tailscale_sweep() + assert service._candidates == {} + + +def test_macos_tailscale_app_binary_is_a_cli_fallback(tmp_path, monkeypatch): + executable = tmp_path / "Tailscale" + executable.write_text("#!/bin/sh\n") + executable.chmod(0o755) + monkeypatch.setattr("omlx.cluster.discovery.shutil.which", lambda _name: None) + monkeypatch.setattr("omlx.cluster.discovery.sys.platform", "darwin") + monkeypatch.setenv("OMLX_TAILSCALE_CLI", str(executable)) + + assert _tailscale_executable() == str(executable) + + +# -- link classification -------------------------------------------------------- + + +def test_link_classification(): + assert _classify_link("100.64.0.2", "unknown", None) == "tailscale" + assert _classify_link("10.0.0.1", "tailscale", 5.0) == "tailscale" + assert _classify_link("10.0.0.1", "unknown", None) == "unknown" + assert _classify_link("fe80::1", "unknown", 0.0005) == "tb" + assert _classify_link("10.0.0.1", "unknown", 0.005) == "ethernet" + assert _classify_link("10.0.0.1", "unknown", 0.050) == "wifi" + + +# -- mDNS ----------------------------------------------------------------------- + + +def test_zeroconf_absence_disables_only_mdns(): + service, _ = _service(zeroconf_module=None) + assert service.mdns_available is False + # start()/stop() still work with mDNS unavailable (multicast thread is + # given a fake socket so nothing real happens). + sock = FakeSocket() + service._socket_factory = lambda: sock + service.start() + service.stop() + assert sock.closed + + +def test_mdns_service_creates_peer_from_txt(): + service, _ = _service("aaaa-node") + + class FakeInfo: + port = 8000 + properties = { + b"id": b"bbbb-node", + b"name": b"studio-b", + b"ver": b"0.6.1", + b"cl": b"omlx", + b"caps": json.dumps({"chip": "M3 Ultra", "ram_gb": 96}).encode(), + } + + def parsed_addresses(self): + return ["10.0.0.7"] + + service._handle_mdns_service(FakeInfo()) + + peer = service.peers()[0] + assert peer.node_id == "bbbb-node" + assert peer.friendly_name == "studio-b" + assert peer.caps.chip == "M3 Ultra" + assert peer.addrs == [{"ip": "10.0.0.7", "if_type": "mdns"}] + assert ("10.0.0.7", 8000) in service._candidates + + +def test_mdns_foreign_cluster_and_self_are_ignored(): + service, _ = _service("aaaa-node") + + class FakeInfo: + port = 8000 + properties = {b"id": b"bbbb-node", b"cl": b"other-cluster"} + + def parsed_addresses(self): + return ["10.0.0.7"] + + service._handle_mdns_service(FakeInfo()) + assert service.peers() == [] + + class SelfInfo: + port = 8000 + properties = {b"id": b"aaaa-node", b"cl": b"omlx"} + + def parsed_addresses(self): + return ["10.0.0.9"] + + service._handle_mdns_service(SelfInfo()) + assert service.peers() == [] + + +def test_mdns_handler_exception_is_contained(): + service, _ = _service("aaaa-node") + + class BadInfo: + port = 8000 + + @property + def properties(self): + raise RuntimeError("boom") + + service._handle_mdns_service(BadInfo()) # must not raise + assert service.peers() == [] + + +# -- interface joins ------------------------------------------------------------ + + +def test_interface_sync_skips_unsupported_interfaces(): + sock = FakeSocket() + service, _ = _service( + socket_factory=lambda: sock, + # en0 joins fine; gif0 raises EAFNOSUPPORT like loopback-class ifaces + interface_lister=lambda: ["en0", "gif0"], + ) + + real_setsockopt = sock.setsockopt + + def setsockopt(*args): + if len(args) == 3 and args[1] == socket.IPV6_JOIN_GROUP: + ifindex = struct.unpack("@I", args[2][16:])[0] + if socket.if_indextoname(ifindex) == "gif0": + raise OSError(47, "Address family not supported") + real_setsockopt(*args) + + sock.setsockopt = setsockopt + service._sync_interfaces(sock) + + assert "en0" in service._joined + assert "gif0" not in service._joined + + +# -- peer record ---------------------------------------------------------------- + + +def test_peer_record_to_dict_shape(): + record = PeerRecord( + node_id="n1", + friendly_name="studio", + version="0.6.1", + cluster_name="omlx", + caps=PeerCaps( + chip="M3 Ultra", + ram_gb=96.0, + backends=["jaccl"], + thunderbolt=True, + jaccl=True, + ), + addrs=[{"ip": "fe80::1", "if_type": "mdns"}], + http_port=8000, + paired=True, + last_seen=123.0, + link="tb", + state="discovered", + ) + payload = record.to_dict() + assert payload["caps"]["jaccl"] is True + assert payload["link"] == "tb" + assert payload["state"] == "discovered" + json.dumps(payload) # must be JSON-serializable for the API + + +def test_mark_paired_updates_live_discovery_record(): + service, _ = _service() + service._peers["peer-1"] = PeerRecord(node_id="peer-1") + + service.mark_paired("peer-1") + + assert service._peers["peer-1"].paired is True + service.mark_paired("unknown-node") + + +def test_announced_caps_uses_configured_service(): + from omlx.cluster.discovery import announced_caps, configure_discovery_service + + caps = PeerCaps( + chip="M3 Max", + ram_gb=96.0, + backends=["jaccl"], + thunderbolt=True, + jaccl=True, + ) + service, _ = _service(config=DiscoveryConfig(caps=caps)) + configure_discovery_service(service) + try: + assert announced_caps() == caps.to_dict() + finally: + configure_discovery_service(None) + + +# -- mDNS announce path with a fake zeroconf module ----------------------------- + + +class _FakeZeroconfModule: + class ServiceInfo: + def __init__(self, type_, name, addresses, port, properties): + self.type = type_ + self.name = name + self.addresses = addresses + self.port = port + self.properties = properties + + class ServiceBrowser: + def __init__(self, zc, type_, listener): + self.cancelled = False + + def cancel(self): + self.cancelled = True + + class Zeroconf: + def __init__(self): + self.registered = [] + self.closed = False + + def register_service(self, info): + self.registered.append(info) + + def unregister_service(self, info): + self.registered.remove(info) + + def close(self): + self.closed = True + + +def test_mdns_announce_publishes_spec_txt_record(): + service, _ = _service("aaaa-node", zeroconf_module=_FakeZeroconfModule) + service.identity.friendly_name = "studio-a" + + service._start_mdns() + + info = service._zc_instance.registered[0] + assert info.type == "_omlx._tcp.local." + assert info.name.startswith("studio-a._omlx._tcp.local.") + assert info.port == 8000 + assert info.properties["id"] == "aaaa-node" + assert info.properties["name"] == "studio-a" + assert info.properties["cl"] == "omlx" + assert info.properties["ver"] + caps = json.loads(info.properties["caps"]) + assert set(caps) == {"chip", "ram_gb", "backends", "thunderbolt", "jaccl"} + service.stop() + + +def test_mdns_start_failure_disables_mdns_without_killing_service(): + class BoomZeroconf(_FakeZeroconfModule): + class Zeroconf: + def __init__(self): + raise RuntimeError("Local Network permission denied") + + service, _ = _service("aaaa-node", zeroconf_module=BoomZeroconf) + service._socket_factory = FakeSocket + service.start() # must not raise + service.stop() + + +# -- resilience: scoped sends, stale joins, supervision, self-heal ------------ + + +def test_send_hello_uses_scoped_4tuple_per_interface(): + sock = FakeSocket() + service, _ = _service(socket_factory=lambda: sock) + service._joined = {"en5": 20, "en1": 26} + + service._send_hello(sock) + + targets = [addr for _, addr in sock.sent] + assert (MULTICAST_GROUP, MULTICAST_PORT, 0, 20) in targets + assert (MULTICAST_GROUP, MULTICAST_PORT, 0, 26) in targets + # The shared socket's IPV6_MULTICAST_IF must not be mutated per round; + # the scope id in the destination carries the egress interface instead. + assert not any( + len(opt) == 3 and opt[1] == socket.IPV6_MULTICAST_IF for opt in sock.opts + ) + + +def test_send_hello_without_joins_uses_default_route_2tuple(): + sock = FakeSocket() + service, _ = _service(socket_factory=lambda: sock) + + service._send_hello(sock) + + assert sock.sent[0][1] == (MULTICAST_GROUP, MULTICAST_PORT) + + +def test_wassup_reply_preserves_link_local_scope_id(): + sock = FakeSocket() + service, _ = _service(socket_factory=lambda: sock) + + service._handle_hello(42, service._cluster_hash, ("fe80::99", 53413, 0, 20), sock) + + assert len(sock.sent) == 1 + assert sock.sent[0][1] == ("fe80::99", 53413, 0, 20) + + +def test_sync_interfaces_rejoins_after_renumber(monkeypatch): + sock = FakeSocket() + service, _ = _service(interface_lister=lambda: ["en5"]) + state = {"idx": 20} + monkeypatch.setattr(socket, "if_nametoindex", lambda name: state["idx"]) + + service._sync_interfaces(sock) + assert service._joined == {"en5": 20} + assert len(sock.joined) == 1 + + state["idx"] = 21 # Thunderbolt hotplug renumbered the interface + service._sync_interfaces(sock) + assert service._joined == {"en5": 21} + assert len(sock.joined) == 2 # re-joined under the new index + + +def test_sync_interfaces_drops_vanished_interfaces(monkeypatch): + sock = FakeSocket() + names = ["en5", "en1"] + service, _ = _service(interface_lister=lambda: names) + index_of = {"en5": 20, "en1": 26} + monkeypatch.setattr( + socket, + "if_nametoindex", + lambda name: index_of.get(name) or (_ for _ in ()).throw(OSError()), + ) + + service._sync_interfaces(sock) + assert set(service._joined) == {"en5", "en1"} + + names.remove("en5") # cable pulled / bridge torn down + service._sync_interfaces(sock) + assert set(service._joined) == {"en1"} + + +class _FailingSocket(FakeSocket): + """Every send fails the way macOS reports a dead interface.""" + + def sendto(self, data, addr): + raise OSError(errno.EHOSTUNREACH, "No route to host") + + +def test_send_failures_are_rate_limited(caplog): + sock = _FailingSocket() + service, clock = _service(socket_factory=lambda: sock) + service._joined = {"en0": 10} + + with caplog.at_level(logging.DEBUG, logger="omlx.cluster.discovery"): + service._send_hello(sock) + clock.advance(5) + service._send_hello(sock) # inside the 60s window: silent + assert sum("HELLO send on if" in r.getMessage() for r in caplog.records) == 1 + clock.advance(61) + service._send_hello(sock) + assert sum("HELLO send on if" in r.getMessage() for r in caplog.records) == 2 + + +def test_consecutive_failed_rounds_request_socket_reset(): + sock = _FailingSocket() + service, clock = _service(socket_factory=lambda: sock) + service._joined = {"en0": 10} + + for _ in range(_TX_FAIL_RESET_ROUNDS): + service._send_hello(sock) + clock.advance(1) + + assert service._needs_socket_reset is True + assert service._consecutive_tx_fail_rounds >= _TX_FAIL_RESET_ROUNDS + assert service._last_tx_error + + +def test_successful_send_clears_fail_state(): + sock = FakeSocket() + service, _ = _service(socket_factory=lambda: sock) + service._joined = {"en0": 10} + service._consecutive_tx_fail_rounds = 5 + service._last_tx_error = "if 10: boom" + + service._send_hello(sock) + + assert service._consecutive_tx_fail_rounds == 0 + assert service._last_tx_error is None + assert service._last_tx_ok_wall is not None + + +def test_multicast_loop_rebuilds_wedged_socket(): + socks = [FakeSocket(), FakeSocket()] + service, clock = _service(socket_factory=lambda: socks.pop(0)) + service._needs_socket_reset = True + service.config.iface_poll_interval = 0.0 + service.config.hello_interval = 0.0 + + service.start() + try: + deadline = time.time() + 5 + while time.time() < deadline: + if ( + not service._needs_socket_reset + and service._socket is not None + and service._joined + ): + break + time.sleep(0.02) + assert service._needs_socket_reset is False + assert service._socket is not None + assert service._joined # re-joined after the rebuild + health = service.health() + assert health["multicast_loop_alive"] is True + assert health["socket_open"] is True + finally: + service.stop() + + +def test_spawned_thread_restarts_after_crash(): + service, _ = _service() + calls = [] + + def flaky(): + calls.append(1) + if len(calls) == 1: + raise RuntimeError("boom") + service._stop.set() + + service._spawn(flaky, "test-flaky") + deadline = time.time() + 8 + while len(calls) < 2 and time.time() < deadline: + time.sleep(0.05) + service.stop() + + assert len(calls) == 2 # crashed once, supervised restart ran it again + + +def test_health_reports_dead_loops_before_start(): + service, _ = _service() + + health = service.health() + + assert health["multicast_loop_alive"] is False + assert health["maintenance_loop_alive"] is False + assert health["socket_open"] is False + assert health["joined_interfaces"] == [] + assert health["consecutive_tx_fail_rounds"] == 0 + + +def test_blocked_suspicion_flag_lifecycle(): + sock = FakeSocket() + service, _ = _service(socket_factory=lambda: sock) + service._joined = {"en0": 10} + service._local_network_blocked_suspected = True + service._consecutive_socket_resets = 6 + + service._send_hello(sock) # a successful round ends the suspicion + + assert service._local_network_blocked_suspected is False + assert service._consecutive_socket_resets == 0 + + service._local_network_blocked_suspected = True + service._handle_hello(7, service._cluster_hash, ("fe80::99", 53413), sock) + assert service._local_network_blocked_suspected is False + + +def test_rdma_fabric_caps_detects_jaccl_when_enabled_with_devices(): + from omlx.cluster import discovery + + calls = [] + + def runner(args, **kwargs): + calls.append(args[0]) + + class Result: + returncode = 0 + stdout = ( + "enabled\n" + if args[0].endswith("rdma_ctl") + # Real ibv_devices output: two-row header, indented devices. + else " device \t node GUID\n" + " ------ \t----------------\n" + " rdma_en6 \t715a4d3d9c48ac05\n" + " rdma_en1 \t705a4d3d9c48ac05\n" + ) + + return Result() + + caps = discovery.PeerCaps() + discovery._rdma_fabric_caps(caps, runner=runner) + if discovery.sys.platform == "darwin": + assert caps.thunderbolt is True + assert caps.jaccl is True + + +def test_rdma_fabric_caps_stays_false_when_disabled_or_no_devices(): + from omlx.cluster import discovery + + def disabled(args, **kwargs): + class Result: + returncode = 0 + stdout = "disabled\n" if args[0].endswith("rdma_ctl") else "rdma_en6\n" + + return Result() + + caps = discovery.PeerCaps() + discovery._rdma_fabric_caps(caps, runner=disabled) + if discovery.sys.platform == "darwin": + assert caps.thunderbolt is True # fabric exists; RDMA is just off + assert caps.jaccl is False + + def failing(args, **kwargs): + class Result: + returncode = 1 + stdout = "" + + return Result() + + caps = discovery.PeerCaps() + discovery._rdma_fabric_caps(caps, runner=failing) + assert caps.thunderbolt is False + assert caps.jaccl is False diff --git a/tests/test_system_socket_proxy.py b/tests/test_system_socket_proxy.py new file mode 100644 index 0000000000..40d9c37baf --- /dev/null +++ b/tests/test_system_socket_proxy.py @@ -0,0 +1,87 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Tests for the macOS system-Python carrier used by discovery probes.""" + +from __future__ import annotations + +import socket +import threading + +import pytest + +from omlx.cluster.system_socket_proxy import ( + open_system_tcp_proxy, + should_proxy_control_socket, +) + + +def test_system_proxy_bridges_a_loopback_stream(): + listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + listener.bind(("127.0.0.1", 0)) + listener.listen(1) + port = int(listener.getsockname()[1]) + result: dict[str, bytes] = {} + + def server() -> None: + stream, _address = listener.accept() + try: + result["request"] = stream.recv(4) + stream.sendall(b"pong") + finally: + stream.close() + listener.close() + + thread = threading.Thread(target=server) + thread.start() + proxy = open_system_tcp_proxy("127.0.0.1", port, timeout=3) + try: + proxy.stream.sendall(b"ping") + assert proxy.stream.recv(4) == b"pong" + finally: + proxy.close() + thread.join(3) + + assert not thread.is_alive() + assert result == {"request": b"ping"} + + +def test_control_proxy_auto_skips_loopback(monkeypatch): + monkeypatch.delenv("OMLX_CLUSTER_CONTROL_TRANSPORT", raising=False) + assert should_proxy_control_socket("127.0.0.1") is False + assert should_proxy_control_socket("localhost") is False + + +def test_control_proxy_direct_override(monkeypatch): + monkeypatch.setenv("OMLX_CLUSTER_CONTROL_TRANSPORT", "direct") + assert should_proxy_control_socket("10.0.0.1") is False + + +def test_system_proxy_reaches_ipv6_loopback(): + if not socket.has_ipv6: + pytest.skip("IPv6 is unavailable") + listener = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) + try: + listener.bind(("::1", 0)) + except OSError: + listener.close() + pytest.skip("IPv6 loopback is unavailable") + listener.listen(1) + port = int(listener.getsockname()[1]) + + def server() -> None: + stream, _address = listener.accept() + try: + stream.sendall(b"ok") + finally: + stream.close() + listener.close() + + thread = threading.Thread(target=server) + thread.start() + proxy = open_system_tcp_proxy("::1", port, timeout=3) + try: + assert proxy.stream.recv(2) == b"ok" + finally: + proxy.close() + thread.join(3) + assert not thread.is_alive() From 5a2871a17ce56596bb4515b1d1cf6930c7777cbe Mon Sep 17 00:00:00 2001 From: jundot Date: Tue, 8 Sep 2026 12:26:25 +0900 Subject: [PATCH 116/132] fix(cluster): preserve pairing endpoints and check host keys --- omlx/cluster/pairing.py | 22 ++++++++++---- omlx/server.py | 1 + tests/test_cluster_pairing.py | 56 ++++++++++++++++++++++++++++++++++- 3 files changed, 73 insertions(+), 6 deletions(-) diff --git a/omlx/cluster/pairing.py b/omlx/cluster/pairing.py index fa8e383b2c..3cc0ed2a9f 100644 --- a/omlx/cluster/pairing.py +++ b/omlx/cluster/pairing.py @@ -485,6 +485,7 @@ def put_paired(self, record: dict[str, Any]) -> None: caps=record.get("caps") or None, addrs=record.get("last_addrs") or None, paired_at=record.get("paired_at"), + http_port=record.get("http_port"), ) return self._call(self._PUT, record) @@ -658,13 +659,13 @@ def default_enrollment_driver(peer: dict[str, Any]) -> dict[str, Any]: addresses = [str(address) for address in (peer.get("addrs") or []) if address] if not addresses: raise EnrollmentDriveError("SSH enrollment requires a verified peer address") - result["authorized_key_installed"] = install_authorized_key( - public_key=peer_public_key - ) for address in addresses: target = ssh_host_target(address) if pin_enrolled_host_key(hostname=target, public_key=peer_host_key): result["host_keys_pinned"].append(address) + result["authorized_key_installed"] = install_authorized_key( + public_key=peer_public_key + ) return result @@ -828,6 +829,7 @@ def __init__( key_store: PairingKeyStore | None = None, caps_provider: Callable[[], dict[str, Any]] | None = None, address_provider: Callable[[], list[str]] | None = None, + http_port: int = 8000, ssh_key_provider: Callable[[], str | None] | None = None, ssh_host_key_provider: Callable[[], str | None] | None = None, enrollment_driver: Callable[[dict[str, Any]], Any] | None = None, @@ -852,6 +854,7 @@ def __init__( ) self._caps_provider = caps_provider self._address_provider = address_provider + self.http_port = http_port self._ssh_key_provider = ssh_key_provider or _local_ssh_public_key self._ssh_host_key_provider = ( ssh_host_key_provider or _local_ssh_host_public_key @@ -892,9 +895,12 @@ def local_addrs(self) -> list[str]: for candidate in candidates or []: raw = str(candidate).strip() try: - ipaddress.ip_address(raw.split("%", 1)[0]) + parsed = ipaddress.ip_address(raw.split("%", 1)[0]) except ValueError: continue + # The sender's link-local scope is not usable on another Mac. + if parsed.version == 6 and parsed.is_link_local: + continue normalized = raw if normalized not in addresses: addresses.append(normalized) @@ -986,7 +992,7 @@ def build_join_request(self, code: str | None = None) -> dict[str, Any]: code_salt, ), "code_salt": base64.b64encode(code_salt).decode("ascii"), - "http_port": None, + "http_port": self.http_port, "addrs": self.local_addrs(), "ssh_public_key": ssh_public_key, "ssh_host_public_key": ssh_host_public_key, @@ -1106,6 +1112,7 @@ def complete_join( "caps": coordinator.get("caps") or {}, "paired_at": paired_at, "last_addrs": coordinator_peer["addrs"], + "http_port": status.get("coordinator_http_port"), "state": "paired", "role": "coordinator", } @@ -1394,6 +1401,7 @@ def approve(self, node_id: str, code: str) -> dict[str, Any]: "caps": pending.caps, "paired_at": paired_at, "last_addrs": list(pending.addrs), + "http_port": pending.http_port, "state": "paired", "role": "peer", } @@ -1403,6 +1411,8 @@ def approve(self, node_id: str, code: str) -> dict[str, Any]: # with the code; safe to persist (0600) and serve. "cluster_key_package": package, "coordinator": coordinator_material, + # Keep endpoint metadata outside the v1 identity tag for compatibility. + "coordinator_http_port": self.http_port, "coordinator_identity_tag": coordinator_tag, "peer_public_key": pending.ssh_public_key, "addrs": list(pending.addrs), @@ -1465,6 +1475,7 @@ def approve(self, node_id: str, code: str) -> dict[str, Any]: "paired_at": paired_at, "cluster_key_package": package, "coordinator": coordinator_material, + "coordinator_http_port": self.http_port, "coordinator_identity_tag": coordinator_tag, "enrollment": enrollment, } @@ -1510,6 +1521,7 @@ def join_status(self, node_id: str) -> dict[str, Any]: # persists it via complete_join, so caps/ssh key must ride # here too — the poll path is the only one the UI drives. "coordinator": key_record.get("coordinator") or {}, + "coordinator_http_port": key_record.get("coordinator_http_port"), "coordinator_identity_tag": key_record.get("coordinator_identity_tag"), } package = key_record.get("cluster_key_package") diff --git a/omlx/server.py b/omlx/server.py index 856b6cfc96..b7efe31802 100644 --- a/omlx/server.py +++ b/omlx/server.py @@ -2096,6 +2096,7 @@ def init_server( enrollment_store=get_cluster_enrollment(), caps_provider=announced_caps, address_provider=announced_addrs, + http_port=global_settings.server.port if global_settings else 8000, ) # Discover models (use pinned models from settings file) diff --git a/tests/test_cluster_pairing.py b/tests/test_cluster_pairing.py index becd164a4b..8defe799f2 100644 --- a/tests/test_cluster_pairing.py +++ b/tests/test_cluster_pairing.py @@ -673,7 +673,10 @@ def test_default_enrollment_propagates_host_key_failure(monkeypatch): "get_or_create_ssh_key", lambda: SimpleNamespace(fingerprint="SHA256:local"), ) - monkeypatch.setattr(ssh_keys, "install_authorized_key", lambda **_kwargs: True) + installed = [] + monkeypatch.setattr( + ssh_keys, "install_authorized_key", lambda **kwargs: installed.append(kwargs) + ) monkeypatch.setattr( ssh_keys, "pin_enrolled_host_key", @@ -691,6 +694,8 @@ def test_default_enrollment_propagates_host_key_failure(monkeypatch): } ) + assert installed == [] + def test_default_enrollment_formats_ipv6_known_host_target(monkeypatch): from omlx.cluster import ssh_keys @@ -1187,3 +1192,52 @@ def test_join_status_rejects_substituted_coordinator_identity(tmp_path): joiner.complete_join(status) assert joiner.paired_devices() == [] + + +@pytest.mark.parametrize("coord_port,join_port", [(8000, 8000), (9123, 9234)]) +def test_pairing_preserves_ports_for_both_nodes_after_restart( + tmp_path, coord_port, join_port +): + from omlx.cluster.discovery import DiscoveryConfig, DiscoveryService + from omlx.cluster.identity import NodeIdentity + from omlx.cluster.registry import DeviceRegistry + + coord_registry = DeviceRegistry(tmp_path / "coord.json") + join_registry = DeviceRegistry(tmp_path / "join.json") + coordinator = _manager( + tmp_path, node_id="coord", name="Coordinator", registry=coord_registry + ) + joiner = _manager(tmp_path, node_id="join", name="Joiner", registry=join_registry) + coordinator.http_port, joiner.http_port = coord_port, join_port + code = joiner.start_join()["code"] + request = joiner.build_join_request(code) + assert request["http_port"] == join_port + coordinator.handle_join_request(request) + coordinator.approve("join", code) + # Reload the coordinator's key store before the joiner polls approval. + coordinator._key_store = PairingKeyStore(tmp_path / "coord") + joiner.complete_join(coordinator.join_status("join")) + for path, remote_port in [ + (coord_registry.path, join_port), + (join_registry.path, coord_port), + ]: + restored = DeviceRegistry(path) + assert restored.paired()[0]["http_port"] == remote_port + service = DiscoveryService( + NodeIdentity("local", "Local", 1), restored, DiscoveryConfig() + ) + assert ("127.0.0.1", remote_port) in service._candidates + + +def test_sender_local_ipv6_scope_does_not_block_ipv4_enrollment(tmp_path, monkeypatch): + from omlx.cluster import ssh_keys + + manager = _manager(tmp_path, node_id="local", name="Local") + manager._address_provider = lambda: ["fe80::1%en0", "192.168.1.2"] + monkeypatch.setattr(ssh_keys, "_SSH_DIR", tmp_path / "ssh") + monkeypatch.setattr( + ssh_keys, "get_or_create_ssh_key", lambda: SimpleNamespace(fingerprint="local") + ) + result = default_enrollment_driver(manager.local_ssh_material()) + assert result["host_keys_pinned"] == ["192.168.1.2"] + assert result["authorized_key_installed"] From 8041983f4b602ed311c90ba863350a8c3e701215 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Tue, 18 Aug 2026 17:15:34 -0700 Subject: [PATCH 117/132] cluster v2 Module D checkpoint: path_map schema v2 + modelsync + manifest endpoint - deployment.py: path_map field, model_path_for(), schema v2 (v1 decodes to empty map), path_map rides the worker contract, decode_worker_path_map() - registry.py: deployments.json schema v1->v2 in-memory migration, persisted atomically on load, migrated_from reported - planner.py: ShardPlan.path_map passthrough (excluded from plan_hash) - routes.py: path_map on plan/deployment requests, placement signature folds path_map when present, staging honors per-node destinations - launch.py: preflight probes each node at its own path_map path - inference_worker.py: rank resolves its model path from the signed contract - modelsync.py: ModelSyncManager (status/sync, auto|rsync|download), manifest builder + GET /api/cluster/models/{model_id}/manifest, progress events - tests: 32 new offline tests (manifest fixture, path_map, v1 migration, sync decisions with mocked transports) --- omlx/cluster/deployment.py | 131 ++++- omlx/cluster/inference_worker.py | 11 +- omlx/cluster/launch.py | 20 +- omlx/cluster/modelsync.py | 807 +++++++++++++++++++++++++++++++ omlx/cluster/planner.py | 12 +- omlx/cluster/registry.py | 26 +- omlx/cluster/routes.py | 75 ++- omlx/cluster/staging.py | 5 + omlx/server.py | 13 + tests/test_cluster_modelsync.py | 683 ++++++++++++++++++++++++++ 10 files changed, 1734 insertions(+), 49 deletions(-) create mode 100644 omlx/cluster/modelsync.py create mode 100644 tests/test_cluster_modelsync.py diff --git a/omlx/cluster/deployment.py b/omlx/cluster/deployment.py index 8f7f637abc..d9e7e11626 100644 --- a/omlx/cluster/deployment.py +++ b/omlx/cluster/deployment.py @@ -27,6 +27,15 @@ DistributedBackend = Literal["ring", "jaccl", "jaccl-ring"] +# Version 2 adds ``path_map``: an optional per-node absolute model path, so +# nodes no longer need the model at the same absolute path on every Mac. +# Version 1 payloads decode with an empty map, which reproduces the legacy +# shared-path behavior exactly. +DEPLOYMENT_SCHEMA_VERSION = 2 +_SUPPORTED_DEPLOYMENT_SCHEMAS = (1, DEPLOYMENT_SCHEMA_VERSION) +_MAX_PATH_MAP_ENTRIES = 64 +_MAX_MODEL_PATH_BYTES = 4096 + _SSH_TARGET = re.compile( r"^(?:[A-Za-z0-9._-]+@)?(?:[A-Za-z0-9._-]+|\[[0-9A-Fa-f:]+\])$" ) @@ -79,6 +88,44 @@ def _validate_rdma_path(value: Any) -> RDMAPath: raise ValueError("RDMA entries must be a device, a device list, or null") +def validate_model_path_map( + path_map: Any, + node_ids: tuple[str, ...] | None = None, +) -> dict[str, str]: + """Validate an optional per-node model path override map. + + Keys are cluster node IDs; values are absolute paths that exist only on + the node that resolves them, so no existence check happens here. An empty + map is the legacy "same absolute path on every node" behavior. + """ + + if path_map is None: + return {} + if not isinstance(path_map, dict): + raise ValueError("path_map must be an object mapping node IDs to paths") + if len(path_map) > _MAX_PATH_MAP_ENTRIES: + raise ValueError("path_map cannot hold more than 64 nodes") + known = set(node_ids) if node_ids is not None else None + validated: dict[str, str] = {} + for node_id, raw_path in path_map.items(): + if not isinstance(node_id, str) or _NODE_ID.fullmatch(node_id) is None: + raise ValueError(f"invalid path_map node ID: {node_id!r}") + if known is not None and node_id not in known: + raise ValueError(f"path_map names a node outside the deployment: {node_id!r}") + if not isinstance(raw_path, str): + raise ValueError(f"path_map path for {node_id!r} must be a string") + path = raw_path.strip() + if ( + not path + or "\x00" in path + or len(path.encode()) > _MAX_MODEL_PATH_BYTES + or not Path(path).is_absolute() + ): + raise ValueError(f"path_map path for {node_id!r} must be absolute") + validated[node_id] = path + return validated + + @dataclass(frozen=True) class ClusterHost: """One rank in an MLX hostfile.""" @@ -248,6 +295,10 @@ class ClusterDeployment: performance_profiles: tuple[NodePerformanceProfile, ...] = () tensor_parallel_size: int = 1 target_context_tokens: int = 8192 + # node_id → absolute model path on that node. Empty means every node uses + # ``model`` — the pre-v2 same-absolute-path requirement. Entries override + # only the nodes they name; the coordinator path stays the fallback. + path_map: dict[str, str] = field(default_factory=dict) def __post_init__(self) -> None: if _NODE_ID.fullmatch(self.deployment_id) is None: @@ -285,6 +336,14 @@ def __post_init__(self) -> None: raise ValueError("rank 0 must use SSH target 127.0.0.1") if len({host.node_id for host in self.hosts}) != len(self.hosts): raise ValueError("cluster node IDs must be unique") + object.__setattr__( + self, + "path_map", + validate_model_path_map( + self.path_map, + tuple(host.node_id for host in self.hosts), + ), + ) if len(self.plan_hash) != 64 or any( char not in "0123456789abcdef" for char in self.plan_hash ): @@ -340,6 +399,15 @@ def world_size(self) -> int: def distributed_init_backend(self) -> str: return "jaccl" if self.backend.startswith("jaccl") else "ring" + def model_path_for(self, node_id: str) -> str: + """The model directory one rank loads, honouring per-node overrides. + + Nodes absent from ``path_map`` keep the coordinator's shared path, + which is exactly the legacy same-absolute-path behavior. + """ + + return self.path_map.get(node_id, self.model) + def hostfile_dict(self) -> dict[str, Any]: return { "backend": self.backend, @@ -359,7 +427,7 @@ def hostfile_dict(self) -> dict[str, Any]: def to_dict(self) -> dict[str, Any]: return { - "schema_version": 1, + "schema_version": DEPLOYMENT_SCHEMA_VERSION, "deployment_id": self.deployment_id, "model": self.model, "backend": self.backend, @@ -373,11 +441,15 @@ def to_dict(self) -> dict[str, Any]: ], "tensor_parallel_size": self.tensor_parallel_size, "target_context_tokens": self.target_context_tokens, + "path_map": dict(sorted(self.path_map.items())), } @classmethod def from_dict(cls, payload: dict[str, Any]) -> ClusterDeployment: - if not isinstance(payload, dict) or payload.get("schema_version", 1) != 1: + if ( + not isinstance(payload, dict) + or payload.get("schema_version", 1) not in _SUPPORTED_DEPLOYMENT_SCHEMAS + ): raise ValueError("unsupported cluster deployment schema") hosts = payload.get("hosts") assignments = payload.get("assignments") @@ -414,6 +486,9 @@ def from_dict(cls, payload: dict[str, Any]) -> ClusterDeployment: ), tensor_parallel_size=int(payload.get("tensor_parallel_size", 1)), target_context_tokens=int(payload.get("target_context_tokens", 8192)), + # Schema 1 payloads predate per-node paths; they decode to the + # empty map, which is the shared-path behavior they ran with. + path_map=validate_model_path_map(payload.get("path_map")), ) def encode_worker_plan(self) -> str: @@ -421,7 +496,7 @@ def encode_worker_plan(self) -> str: raw = json.dumps( { - "schema_version": 1, + "schema_version": DEPLOYMENT_SCHEMA_VERSION, "plan_hash": self.plan_hash, "assignments": [ assignment.to_dict() for assignment in self.assignments @@ -430,6 +505,7 @@ def encode_worker_plan(self) -> str: profile.to_dict() for profile in self.performance_profiles ], "tensor_parallel_size": self.tensor_parallel_size, + "path_map": dict(sorted(self.path_map.items())), }, sort_keys=True, separators=(",", ":"), @@ -439,15 +515,8 @@ def encode_worker_plan(self) -> str: return base64.urlsafe_b64encode(zlib.compress(raw, level=9)).decode() -def decode_worker_contract( - encoded: str, -) -> tuple[ - str, - tuple[PipelineAssignment, ...], - tuple[NodePerformanceProfile, ...], - int, -]: - """Decode and validate the full worker contract without accepting code.""" +def _decode_worker_payload(encoded: str) -> dict[str, Any]: + """Inflate and validate a worker plan payload without accepting code.""" if not isinstance(encoded, str) or len(encoded) > _MAX_PLAN_BYTES * 2: raise ValueError("encoded pipeline plan is too large") @@ -470,7 +539,10 @@ def decode_worker_contract( payload = json.loads(raw) except (UnicodeDecodeError, json.JSONDecodeError) as exc: raise ValueError("pipeline plan is not valid JSON") from exc - if not isinstance(payload, dict) or payload.get("schema_version") != 1: + if ( + not isinstance(payload, dict) + or payload.get("schema_version") not in _SUPPORTED_DEPLOYMENT_SCHEMAS + ): raise ValueError("unsupported pipeline plan schema") plan_hash = payload.get("plan_hash") assignments = payload.get("assignments") @@ -485,13 +557,28 @@ def decode_worker_contract( char not in "0123456789abcdef" for char in plan_hash ): raise ValueError("pipeline plan hash is invalid") - parsed = tuple(_assignment_from_dict(item) for item in assignments) + return payload + + +def decode_worker_contract( + encoded: str, +) -> tuple[ + str, + tuple[PipelineAssignment, ...], + tuple[NodePerformanceProfile, ...], + int, +]: + """Decode and validate the full worker contract without accepting code.""" + + payload = _decode_worker_payload(encoded) + parsed = tuple(_assignment_from_dict(item) for item in payload["assignments"]) if [item.rank for item in sorted(parsed, key=lambda item: item.rank)] != list( range(len(parsed)) ): raise ValueError("pipeline plan ranks must be contiguous from zero") profiles = tuple( - NodePerformanceProfile.from_dict(item) for item in performance_profiles + NodePerformanceProfile.from_dict(item) + for item in payload.get("performance_profiles", []) ) if profiles and ( len(profiles) != len(parsed) @@ -502,7 +589,19 @@ def decode_worker_contract( tensor_parallel_size = int(payload.get("tensor_parallel_size", 1)) if not 1 <= tensor_parallel_size <= len(parsed): raise ValueError("tensor_parallel_size must be between 1 and the assignment count") - return plan_hash, parsed, profiles, tensor_parallel_size + return payload["plan_hash"], parsed, profiles, tensor_parallel_size + + +def decode_worker_path_map(encoded: str) -> dict[str, str]: + """Per-node model path overrides carried inside the worker contract. + + Schema 1 contracts predate per-node paths and decode to an empty map; + callers then fall back to the shared ``--model`` argument, which is the + legacy behavior those contracts ran with. + """ + + payload = _decode_worker_payload(encoded) + return validate_model_path_map(payload.get("path_map")) def decode_worker_plan(encoded: str) -> tuple[str, tuple[PipelineAssignment, ...]]: diff --git a/omlx/cluster/inference_worker.py b/omlx/cluster/inference_worker.py index bf17ef5618..cbb9224d1e 100644 --- a/omlx/cluster/inference_worker.py +++ b/omlx/cluster/inference_worker.py @@ -20,7 +20,7 @@ from types import SimpleNamespace from typing import Any -from .deployment import decode_worker_contract +from .deployment import decode_worker_contract, decode_worker_path_map from .liveness import PeerWatchdog from .memory_guard import ( admission_budget, @@ -970,6 +970,15 @@ def run_worker(args: argparse.Namespace) -> int: if args.plan_hash != plan_hash: raise RuntimeError("worker plan hash does not match launch contract") + # Cluster v2: a deployment may give each node its own absolute model path. + # The rank's path comes from the signed contract's path_map; nodes without + # an entry keep the shared --model argument, the pre-v2 behavior. + path_map = decode_worker_path_map(args.plan) + if path_map: + rank_model_path = path_map.get(assignments[rank].node_id) + if rank_model_path and rank_model_path != args.model: + args.model = rank_model_path + marker = RuntimeMarker( state_dir=args.state_dir, deployment_id=args.deployment_id, diff --git a/omlx/cluster/launch.py b/omlx/cluster/launch.py index f3be0d47c0..d4e8cc4a6b 100644 --- a/omlx/cluster/launch.py +++ b/omlx/cluster/launch.py @@ -1458,7 +1458,10 @@ def preflight_remote_hosts( script = _PREFLIGHT_SCRIPT local_python_version = platform.python_version() results: list[dict[str, Any]] = [] - local_model_exists = Path(deployment.model).is_dir() + # Cluster v2: each rank validates against its own path_map entry; nodes + # without an entry share the coordinator path, as before v2. + local_model_path = deployment.model_path_for(deployment.hosts[0].node_id) + local_model_exists = Path(local_model_path).is_dir() assignments = sorted(deployment.assignments, key=lambda item: item.rank) if len(assignments) != len(deployment.hosts): raise DistributedLaunchError( @@ -1466,7 +1469,7 @@ def preflight_remote_hosts( ) local_validation = ( validate_staged_model( - deployment.model, + local_model_path, assignments[0].start_layer, assignments[0].end_layer, ) @@ -1513,15 +1516,18 @@ def preflight_remote_hosts( ) continue remote_python = host.python_executable or python_executable - # Send the ~-form: deployment.model is the coordinator's absolute path, - # which names nothing on a peer with a different macOS account. The - # preflight script expanduser()s it in the peer's own home. + # A path_map entry is already absolute on this peer. Without one, send + # the portable ~-form so peers with different macOS accounts resolve + # the model under their own home directory. + remote_model_path = deployment.path_map.get( + host.node_id, home_relative_model_path(deployment.model) + ) remote_command = shlex.join( [ remote_python, "-c", script, - home_relative_model_path(deployment.model), + remote_model_path, str(assignment.start_layer), str(assignment.end_layer), assignment.memory_guard_tier, @@ -1573,7 +1579,7 @@ def preflight_remote_hosts( runtime_warnings = [warning] if warning is not None else [] if versions.get("model-exists") is not True: mismatches.append( - f"model directory is missing on remote host: {deployment.model}" + f"model directory is missing on remote host: {remote_model_path}" ) if local_identity is not None and versions.get("model_identity") != local_identity: mismatches.append( diff --git a/omlx/cluster/modelsync.py b/omlx/cluster/modelsync.py new file mode 100644 index 0000000000..f16f17512e --- /dev/null +++ b/omlx/cluster/modelsync.py @@ -0,0 +1,807 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Model synchronization and per-node model paths for cluster v2. + +Two responsibilities: + +* A bounded, content-describing **manifest** for a locally-known model + (safetensors index hash + file list + total bytes), served to peers over + ``GET /api/cluster/models/{model_id}/manifest`` so a coordinator can answer + "does that node have this model?" without SSHing anywhere. +* A :class:`ModelSyncManager` that compares two manifests and then moves the + model, either over the enrolled SSH channel (``rsync``, resumable via + ``--partial --append-verify``) or as a per-node Hugging Face download of + only the files a shard needs (allow-patterns derived from the weight-map + index — the exo pattern). Progress events are emitted for the UI. + +All transports are injectable so unit tests never open a socket, run rsync, +or touch the Hugging Face hub. +""" + +from __future__ import annotations + +import hashlib +import json +import re +import subprocess +import threading +import time +from collections.abc import Callable, Iterable +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Literal + +from fastapi import APIRouter, HTTPException + +from ..exceptions import ModelNotFoundError +from .staging import ( + index_shards, + model_identity_digest, + shards_for_stage, + sidecar_files, +) + +SyncMethod = Literal["auto", "rsync", "download"] +SyncState = Literal["present", "missing", "partial", "mismatch"] + +#: Above this size ``method="auto"`` prefers a direct rsync over the enrolled +#: SSH channel; at or below it, each node downloads its own shard files. +AUTO_RSYNC_THRESHOLD_BYTES = 20 * 1024**3 + +_MANIFEST_TIMEOUT_SECONDS = 10.0 +_MAX_MODEL_ID_LENGTH = 4096 +_MAX_PROGRESS_EVENTS = 512 + +# ``rsync --info=progress2`` emits lines such as: +# " 1,234,567,890 42% 123.45MB/s 0:01:23" +_PROGRESS2 = re.compile( + r"^\s*(?P[\d,]+)\s+(?P\d+)%\s+" + r"(?P[\d.,]+)\s*(?P[KMGTP]?B)/s\s+" + r"(?P\d+:\d{2}(?::\d{2})?)" +) +_RATE_MULTIPLIERS = { + "B": 1, + "KB": 1000, + "MB": 1000**2, + "GB": 1000**3, + "TB": 1000**4, + "PB": 1000**5, +} + + +class ModelSyncError(RuntimeError): + """A sync operation could not start or finish.""" + + +@dataclass(frozen=True) +class ManifestFile: + """One file in a model directory: name and size, nothing else.""" + + name: str + size_bytes: int + + def to_dict(self) -> dict[str, Any]: + return {"name": self.name, "size_bytes": self.size_bytes} + + @classmethod + def from_dict(cls, payload: dict[str, Any]) -> ManifestFile: + return cls(name=str(payload["name"]), size_bytes=int(payload["size_bytes"])) + + +@dataclass(frozen=True) +class ModelManifest: + """Content description of one model directory, cheap to compute. + + Hashing every weight file would take minutes on a 300 GB model, so the + identity rests on the safetensors weight-map index plus the sidecar + digest staging already uses, with per-file sizes for drift detection. + """ + + model_id: str + path: str + index_sha256: str | None + identity_sha256: str + files: tuple[ManifestFile, ...] + total_bytes: int + source_repo_id: str | None = None + + def to_dict(self) -> dict[str, Any]: + return { + "schema_version": 1, + "model_id": self.model_id, + "path": self.path, + "index_sha256": self.index_sha256, + "identity_sha256": self.identity_sha256, + "files": [item.to_dict() for item in self.files], + "total_bytes": self.total_bytes, + "source_repo_id": self.source_repo_id, + } + + @classmethod + def from_dict(cls, payload: dict[str, Any]) -> ModelManifest: + if not isinstance(payload, dict) or payload.get("schema_version") != 1: + raise ValueError("unsupported model manifest schema") + files = payload.get("files") + if not isinstance(files, list): + raise ValueError("model manifest files must be an array") + return cls( + model_id=str(payload.get("model_id") or ""), + path=str(payload.get("path") or ""), + index_sha256=payload.get("index_sha256"), + identity_sha256=str(payload.get("identity_sha256") or ""), + files=tuple(ManifestFile.from_dict(item) for item in files), + total_bytes=int(payload.get("total_bytes") or 0), + source_repo_id=payload.get("source_repo_id"), + ) + + +@dataclass(frozen=True) +class SyncProgress: + """One progress event for the UI; bytes/s and ETA when measurable.""" + + model_id: str + peer: str + method: str + phase: Literal[ + "checking", "transferring", "verifying", "done", "error" + ] + bytes_done: int = 0 + bytes_total: int = 0 + bytes_per_second: float | None = None + eta_seconds: float | None = None + detail: str = "" + at: float = field(default_factory=time.time) + + def to_dict(self) -> dict[str, Any]: + return { + "model_id": self.model_id, + "peer": self.peer, + "method": self.method, + "phase": self.phase, + "bytes_done": self.bytes_done, + "bytes_total": self.bytes_total, + "bytes_per_second": self.bytes_per_second, + "eta_seconds": self.eta_seconds, + "detail": self.detail, + "at": self.at, + } + + +def build_manifest( + model_path: str | Path, + *, + model_id: str | None = None, + source_repo_id: str | None = None, +) -> ModelManifest: + """Describe a local model directory for peer comparison.""" + + root = Path(model_path).expanduser() + if not root.is_dir(): + raise ValueError(f"model path is not a directory: {root}") + weights = sorted(root.glob("*.safetensors")) + if not weights: + raise ValueError(f"no safetensors weights found in {root}") + + index_path = root / "model.safetensors.index.json" + index_sha256 = ( + hashlib.sha256(index_path.read_bytes()).hexdigest() + if index_path.is_file() + else None + ) + files = [ + ManifestFile(name=path.name, size_bytes=path.stat().st_size) + for path in weights + ] + for name in sidecar_files(root): + path = root / name + files.append(ManifestFile(name=name, size_bytes=path.stat().st_size)) + files.sort(key=lambda item: item.name) + return ModelManifest( + model_id=model_id or root.name, + path=str(root), + index_sha256=index_sha256, + identity_sha256=model_identity_digest(root), + files=tuple(files), + total_bytes=sum(item.size_bytes for item in files), + source_repo_id=source_repo_id, + ) + + +def allow_patterns_for_shard( + model_path: str | Path, + start_layer: int | None = None, + end_layer: int | None = None, +) -> tuple[str, ...]: + """HF ``allow_patterns`` for only the files one shard needs. + + Derived from the weight-map index (or shard headers when no index ships) + via the same layer→file map staging uses: layer-scoped shards for + ``[start_layer, end_layer)`` plus the shared sidecars. With no layer + range, the pattern list covers the whole model. + """ + + shards = index_shards(model_path) + if start_layer is not None and end_layer is not None: + if not 0 <= start_layer < end_layer: + raise ValueError("shard layer range must satisfy 0 <= start < end") + shards = shards_for_stage(shards, start_layer, end_layer) + patterns = {shard.name for shard in shards} + patterns.update(sidecar_files(model_path)) + return tuple(sorted(patterns)) + + +def compare_manifests(local: ModelManifest, peer: ModelManifest | None) -> dict[str, Any]: + """Whether ``peer`` can serve the model ``local`` describes. + + * ``missing`` — the peer answered 404 or is unreachable. + * ``mismatch`` — the peer has a different model (weight-map index hash or + sidecar identity differs). + * ``partial`` — same model, but files are absent or truncated. + * ``present`` — every file is there at the expected size. + """ + + if peer is None: + return { + "state": "missing", + "bytes": 0, + "total_bytes": local.total_bytes, + "missing": [item.name for item in local.files], + } + if ( + local.index_sha256 is not None + and peer.index_sha256 is not None + and local.index_sha256 != peer.index_sha256 + ) or local.identity_sha256 != peer.identity_sha256: + return { + "state": "mismatch", + "bytes": 0, + "total_bytes": local.total_bytes, + "missing": [item.name for item in local.files], + } + peer_sizes = {item.name: item.size_bytes for item in peer.files} + missing = [ + item.name for item in local.files if peer_sizes.get(item.name) != item.size_bytes + ] + matched = sum( + item.size_bytes for item in local.files if item.name not in set(missing) + ) + return { + "state": "partial" if missing else "present", + "bytes": matched, + "total_bytes": local.total_bytes, + "missing": missing, + } + + +def parse_rsync_progress(line: str) -> tuple[int, float, float] | None: + """Parse one ``--info=progress2`` line → (bytes_done, bytes/s, eta_s).""" + + match = _PROGRESS2.match(line.strip()) + if match is None: + return None + done = int(match.group("bytes").replace(",", "")) + rate = float(match.group("rate").replace(",", "")) * _RATE_MULTIPLIERS[ + match.group("unit") + ] + parts = [int(part) for part in match.group("eta").split(":")] + eta = parts[0] * 3600 + parts[1] * 60 + parts[2] if len(parts) == 3 else ( + parts[0] * 60 + parts[1] + ) + return done, rate, float(eta) + + +def build_rsync_argv( + source_dir: str | Path, + ssh_target: str, + destination_dir: str | Path, + *, + ssh_identity: str | Path | None = None, +) -> list[str]: + """A resumable rsync over the enrolled SSH channel. + + ``--partial --append-verify`` resumes interrupted transfers and verifies + the appended bytes, the functional equivalent of ``-P --append-verify`` + without the interactive progress format. + """ + + ssh_command = ["ssh", "-o", "BatchMode=yes"] + if ssh_identity is not None: + ssh_command.extend(["-i", str(ssh_identity)]) + source = str(Path(source_dir).expanduser()).rstrip("/") + "/" + destination = f"{ssh_target}:{destination_dir}" + return [ + "rsync", + "-a", + "--partial", + "--append-verify", + "--info=progress2", + "-e", + " ".join(ssh_command), + source, + destination, + ] + + +def _default_ssh_trust(ssh_target: str) -> bool: + """Whether the dedicated cluster key exists for non-interactive SSH.""" + + del ssh_target # the key is shared; the target itself is probed at launch + return (Path.home() / ".ssh" / "omlx_cluster").is_file() + + +def _default_hf_download( + *, + repo_id: str, + allow_patterns: Iterable[str], + local_dir: str | Path, +) -> None: + try: + from huggingface_hub import snapshot_download + except ImportError as exc: + raise ModelSyncError( + "huggingface_hub is not installed on this node; install it or use " + "method='rsync' to copy the model from the coordinator instead" + ) from exc + snapshot_download( + repo_id=repo_id, + allow_patterns=list(allow_patterns), + local_dir=str(local_dir), + ) + + +def _normalize_peer_url(peer: str) -> str: + peer = peer.strip() + if not peer: + raise ValueError("peer must be a host:port or http(s) URL") + if "://" not in peer: + if ":" not in peer.rsplit("]", 1)[-1]: + raise ValueError( + f"peer {peer!r} has no port; use host:port or a full URL" + ) + peer = f"http://{peer}" + return peer.rstrip("/") + + +class ModelSyncManager: + """Compare and synchronize model files between cluster nodes. + + Every transport is injectable: ``http_fetch`` for peer manifests, + ``ssh_trust`` for the auto-method decision, ``rsync_run`` for the copy, + and ``hf_download`` for per-node downloads. Tests inject fakes; the + defaults are the real thing and are never exercised offline. + """ + + def __init__( + self, + *, + http_fetch: Callable[[str, float], dict[str, Any] | None] | None = None, + ssh_trust: Callable[[str], bool] | None = None, + rsync_run: Callable[..., int] | None = None, + hf_download: Callable[..., None] | None = None, + pool_getter: Callable[[], Any] | None = None, + settings_loader: Callable[[], Any] | None = None, + manifest_timeout: float = _MANIFEST_TIMEOUT_SECONDS, + ) -> None: + self._http_fetch = http_fetch or self._default_http_fetch + self._ssh_trust = ssh_trust or _default_ssh_trust + self._rsync_run = rsync_run or self._default_rsync_run + self._hf_download = hf_download or _default_hf_download + self._pool_getter = pool_getter + self._settings_loader = settings_loader + self._manifest_timeout = manifest_timeout + self._events: list[SyncProgress] = [] + self._lock = threading.Lock() + + # -- model resolution ------------------------------------------------ + + def resolve_local_model_path(self, model_id: str) -> Path: + """Resolve a model ID, repo ID, or path to a local directory.""" + + if not model_id or len(model_id) > _MAX_MODEL_ID_LENGTH or "\x00" in model_id: + raise ModelNotFoundError(model_id or "", []) + candidate = Path(model_id).expanduser() + if candidate.is_dir(): + return candidate.resolve() + pool = self._pool_getter() if self._pool_getter is not None else None + if pool is not None: + status = pool.get_status() + for item in status.get("models", []) if isinstance(status, dict) else []: + if not isinstance(item, dict): + continue + if model_id in {item.get("id"), item.get("source_repo_id"), item.get("model_path")}: + path = Path(str(item["model_path"])).expanduser() + if path.is_dir(): + return path.resolve() + settings = ( + self._settings_loader() if self._settings_loader is not None else None + ) + if settings is not None: + from ..model_discovery import discover_models_from_dirs + + model_dirs = [ + Path(entry).expanduser() + for entry in settings.get_effective_model_dirs() + ] + discovered = discover_models_from_dirs(model_dirs) + for key, entry in discovered.items(): + if model_id in {key, entry.model_id, entry.source_repo_id}: + path = Path(entry.model_path).expanduser() + if path.is_dir(): + return path.resolve() + raise ModelNotFoundError(model_id, []) + + def local_manifest(self, model_id: str) -> ModelManifest: + path = self.resolve_local_model_path(model_id) + source_repo_id = None if Path(model_id).expanduser().is_dir() else model_id + return build_manifest(path, model_id=model_id, source_repo_id=source_repo_id) + + # -- peer manifest ---------------------------------------------------- + + @staticmethod + def _default_http_fetch(url: str, timeout: float) -> dict[str, Any] | None: + import urllib.error + import urllib.request + + request = urllib.request.Request(url, headers={"Accept": "application/json"}) + try: + with urllib.request.urlopen(request, timeout=timeout) as response: + return json.loads(response.read().decode()) + except urllib.error.HTTPError as exc: + if exc.code == 404: + return None + raise ModelSyncError(f"peer manifest request failed: HTTP {exc.code}") from exc + except (OSError, urllib.error.URLError) as exc: + raise ModelSyncError(f"peer is unreachable: {exc}") from exc + + def peer_manifest(self, peer: str, model_id: str) -> ModelManifest | None: + """Fetch a peer's manifest; ``None`` when the model is unknown there.""" + + base = _normalize_peer_url(peer) + payload = self._http_fetch( + f"{base}/api/cluster/models/{model_id}/manifest", + self._manifest_timeout, + ) + if payload is None: + return None + try: + return ModelManifest.from_dict(payload) + except (KeyError, TypeError, ValueError) as exc: + raise ModelSyncError(f"peer returned an invalid manifest: {exc}") from exc + + def status( + self, + peer: str, + model_id: str, + *, + local: ModelManifest | None = None, + ) -> dict[str, Any]: + """{state: present|missing|partial|mismatch, bytes} for a peer.""" + + local = local or self.local_manifest(model_id) + result = compare_manifests(local, self.peer_manifest(peer, model_id)) + result["peer"] = peer + result["model_id"] = model_id + return result + + # -- sync -------------------------------------------------------------- + + def decide_method( + self, + ssh_target: str | None, + total_bytes: int, + ) -> Literal["rsync", "download"]: + """auto = rsync when SSH trust exists AND the model is over 20 GB.""" + + if ssh_target and total_bytes > AUTO_RSYNC_THRESHOLD_BYTES: + if self._ssh_trust(ssh_target): + return "rsync" + return "download" + + def sync( + self, + peer: str, + model_id: str, + method: SyncMethod = "auto", + *, + ssh_target: str | None = None, + destination: str | Path | None = None, + repo_id: str | None = None, + start_layer: int | None = None, + end_layer: int | None = None, + on_progress: Callable[[SyncProgress], None] | None = None, + ) -> dict[str, Any]: + """Bring ``peer`` (or a local destination) to ``present`` for a model. + + ``rsync`` copies the local model directory to ``ssh_target:destination`` + over the enrolled channel. ``download`` fetches only shard-needed files + from the Hugging Face hub into ``destination`` on this node (run the + same call on each node, exo-style). Progress events are emitted to + ``on_progress`` and retained in :attr:`events` for UI polling. + """ + + if method not in {"auto", "rsync", "download"}: + raise ValueError(f"unsupported sync method: {method!r}") + local = self.local_manifest(model_id) + chosen = ( + self.decide_method(ssh_target, local.total_bytes) + if method == "auto" + else method + ) + self._emit(on_progress, local.model_id, peer, chosen, "checking", + bytes_total=local.total_bytes, detail="comparing manifests") + try: + if chosen == "rsync": + result = self._sync_rsync( + local, peer, ssh_target, destination, on_progress + ) + else: + result = self._sync_download( + local, + model_id, + peer, + destination, + repo_id, + start_layer, + end_layer, + on_progress, + ) + except Exception as exc: + self._emit(on_progress, local.model_id, peer, chosen, "error", + bytes_total=local.total_bytes, detail=str(exc)[:500]) + raise + self._emit(on_progress, local.model_id, peer, chosen, "done", + bytes_done=local.total_bytes, bytes_total=local.total_bytes) + return result + + def _sync_rsync( + self, + local: ModelManifest, + peer: str, + ssh_target: str | None, + destination: str | Path | None, + on_progress: Callable[[SyncProgress], None] | None, + ) -> dict[str, Any]: + if not ssh_target: + raise ModelSyncError( + "rsync sync needs ssh_target (the enrolled SSH destination)" + ) + if not self._ssh_trust(ssh_target): + raise ModelSyncError( + f"no enrolled SSH trust for {ssh_target}; pair the nodes first " + "or use method='download'" + ) + # Without an explicit destination the peer keeps the coordinator's + # absolute path — the legacy shared-path layout, still the default + # until a path_map says otherwise. + target_dir = str(destination or local.path) + argv = build_rsync_argv(local.path, ssh_target, target_dir) + + def progress(done: int, rate: float, eta: float) -> None: + self._emit( + on_progress, + local.model_id, + peer, + "rsync", + "transferring", + bytes_done=done, + bytes_total=local.total_bytes, + bytes_per_second=rate, + eta_seconds=eta, + ) + + rc = self._rsync_run(argv, on_line=self._progress_line_parser(progress)) + if rc != 0: + raise ModelSyncError(f"rsync to {ssh_target} exited with status {rc}") + self._emit(on_progress, local.model_id, peer, "rsync", "verifying", + bytes_total=local.total_bytes, detail="verifying peer manifest") + return { + "method": "rsync", + "peer": peer, + "ssh_target": ssh_target, + "destination": target_dir, + "bytes": local.total_bytes, + } + + def _sync_download( + self, + local: ModelManifest, + model_id: str, + peer: str, + destination: str | Path | None, + repo_id: str | None, + start_layer: int | None, + end_layer: int | None, + on_progress: Callable[[SyncProgress], None] | None, + ) -> dict[str, Any]: + repo = repo_id or local.source_repo_id + if not repo or Path(repo).expanduser().is_dir(): + raise ModelSyncError( + "download sync needs the model's Hugging Face repo ID; the " + "local copy has no repository reference, use method='rsync'" + ) + if destination is None: + raise ModelSyncError( + "download sync needs a destination directory on this node" + ) + patterns = allow_patterns_for_shard(local.path, start_layer, end_layer) + self._emit( + on_progress, + local.model_id, + peer, + "download", + "transferring", + bytes_total=local.total_bytes, + detail=f"fetching {len(patterns)} files from {repo}", + ) + self._hf_download( + repo_id=repo, + allow_patterns=patterns, + local_dir=destination, + ) + return { + "method": "download", + "peer": peer, + "repo_id": repo, + "destination": str(destination), + "allow_patterns": list(patterns), + "bytes": local.total_bytes, + } + + # -- progress plumbing --------------------------------------------------- + + @staticmethod + def _progress_line_parser( + progress: Callable[[int, float, float], None], + ) -> Callable[[str], None]: + def parse(line: str) -> None: + parsed = parse_rsync_progress(line) + if parsed is not None: + progress(*parsed) + + return parse + + @staticmethod + def _default_rsync_run(argv: list[str], on_line: Callable[[str], None]) -> int: + process = subprocess.Popen( + argv, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + ) + assert process.stdout is not None + for line in process.stdout: + on_line(line) + return process.wait() + + def _emit( + self, + on_progress: Callable[[SyncProgress], None] | None, + model_id: str, + peer: str, + method: str, + phase: str, + **fields: Any, + ) -> SyncProgress: + event = SyncProgress( + model_id=model_id, + peer=peer, + method=method, + phase=phase, # type: ignore[arg-type] + **fields, + ) + with self._lock: + self._events.append(event) + if len(self._events) > _MAX_PROGRESS_EVENTS: + del self._events[: len(self._events) - _MAX_PROGRESS_EVENTS] + if on_progress is not None: + on_progress(event) + return event + + @property + def events(self) -> tuple[SyncProgress, ...]: + """Bounded recent progress history for UI polling.""" + + with self._lock: + return tuple(self._events) + + +# -- manifest endpoint ------------------------------------------------------ + +manifest_router = APIRouter(prefix="/api/cluster", tags=["cluster-modelsync"]) + +_pool_getter: Callable[[], Any] | None = None +_settings_loader: Callable[[], Any] | None = None + + +def set_modelsync_getters( + engine_pool_getter: Callable[[], Any] | None = None, + settings_loader: Callable[[], Any] | None = None, +) -> None: + """Inject server-owned dependencies without importing ``omlx.server``.""" + + global _pool_getter, _settings_loader + _pool_getter = engine_pool_getter + _settings_loader = settings_loader + + +def _default_settings_loader() -> Any: + from ..settings import GlobalSettings + + return GlobalSettings.load() + + +def _manager() -> ModelSyncManager: + return ModelSyncManager( + pool_getter=_pool_getter, + settings_loader=_settings_loader or _default_settings_loader, + ) + + +def _allowed_model_roots() -> tuple[Path, ...]: + try: + settings = (_settings_loader or _default_settings_loader)() + return tuple( + Path(entry).expanduser().resolve() + for entry in settings.get_effective_model_dirs() + ) + except Exception: # noqa: BLE001 - a broken settings file must not 500 here + return () + + +def _guard_manifest_path(path: Path) -> None: + """Path-typed model IDs stay inside the configured model directories. + + Repo-style IDs are resolved through the engine pool / discovery, which + already only surfaces registered models. A raw path must not let an admin + token enumerate arbitrary directories. + """ + + roots = _allowed_model_roots() + if not roots: + return + if not any(root == path or root in path.parents for root in roots): + raise HTTPException( + status_code=403, + detail="model path is outside the configured model directories", + ) + + +@manifest_router.get("/models/{model_id:path}/manifest") +async def cluster_model_manifest(model_id: str) -> dict[str, Any]: + """Safetensors index hash + file list + total bytes for a local model. + + Peers call this to decide whether they must sync before activation; the + payload is names and sizes only — never weights, never credentials. + """ + + import asyncio + + manager = _manager() + try: + path = manager.resolve_local_model_path(model_id) + except ModelNotFoundError as exc: + raise HTTPException( + status_code=404, detail=f"unknown model: {model_id}" + ) from exc + _guard_manifest_path(path) + try: + manifest = await asyncio.to_thread(build_manifest, path, model_id=model_id) + except ValueError as exc: + raise HTTPException(status_code=404, detail=str(exc)) from exc + return manifest.to_dict() + + +__all__ = [ + "AUTO_RSYNC_THRESHOLD_BYTES", + "ManifestFile", + "ModelManifest", + "ModelSyncError", + "ModelSyncManager", + "SyncProgress", + "allow_patterns_for_shard", + "build_manifest", + "build_rsync_argv", + "compare_manifests", + "manifest_router", + "parse_rsync_progress", + "set_modelsync_getters", +] diff --git a/omlx/cluster/planner.py b/omlx/cluster/planner.py index cdc31edecf..696ba01098 100644 --- a/omlx/cluster/planner.py +++ b/omlx/cluster/planner.py @@ -11,7 +11,7 @@ import threading from collections.abc import Iterator, Sequence from contextlib import contextmanager -from dataclasses import dataclass, replace +from dataclasses import dataclass, field, replace from pathlib import Path from typing import Any @@ -426,6 +426,11 @@ class ShardPlan: # case the per-rank byte reservation is zero, but the operator's requested # runtime limit must still be visible and part of the plan identity. target_context_tokens: int = _DEFAULT_CONTEXT_TOKENS + # node_id → absolute model path on that node (cluster v2). Display and + # staging metadata only: the layer split is path-independent, so the map + # is deliberately excluded from ``plan_hash``. Empty means every node + # loads the shared coordinator path — the legacy behavior. + path_map: dict[str, str] = field(default_factory=dict) @property def max_context_tokens(self) -> int: @@ -458,7 +463,7 @@ def cluster_resident_weight_bytes(self) -> int: return sum(item.planned_weight_bytes for item in self.assignments) def to_dict(self) -> dict[str, Any]: - return { + result = { "plan_version": 1, "plan_hash": self.plan_hash, "strategy": ( @@ -484,6 +489,9 @@ def to_dict(self) -> dict[str, Any]: "tensor_parallel_size": self.tensor_parallel_size, "pipeline_stages": self.pipeline_stages, } + if self.path_map: + result["path_map"] = dict(sorted(self.path_map.items())) + return result def synthetic_model_layout(*, total_weight_bytes: int, layer_count: int) -> ModelLayout: diff --git a/omlx/cluster/registry.py b/omlx/cluster/registry.py index ccaf5c9b5d..baf51f5a58 100644 --- a/omlx/cluster/registry.py +++ b/omlx/cluster/registry.py @@ -13,6 +13,11 @@ from .deployment import ClusterDeployment +# Version 2 persists per-node model paths (``path_map`` on each deployment). +# Version 1 files are migrated in memory on load and rewritten atomically. +REGISTRY_SCHEMA_VERSION = 2 +_SUPPORTED_REGISTRY_SCHEMAS = (1, REGISTRY_SCHEMA_VERSION) + def _model_key(model: str) -> str: path = Path(model).expanduser() @@ -30,6 +35,8 @@ def __init__(self, base_path: Path) -> None: self._lock = threading.RLock() self._deployments: dict[str, ClusterDeployment] = {} self.load_error: str | None = None + #: Set when an on-disk legacy schema was upgraded on load. + self.migrated_from: int | None = None try: self._load() except ValueError as exc: @@ -49,7 +56,9 @@ def _load(self) -> None: raise ValueError( f"could not read cluster deployment registry: {exc}" ) from exc - if not isinstance(payload, dict) or payload.get("schema_version") != 1: + if not isinstance(payload, dict) or payload.get("schema_version") not in ( + _SUPPORTED_REGISTRY_SCHEMAS + ): raise ValueError("unsupported cluster deployment registry schema") raw_deployments = payload.get("deployments") if not isinstance(raw_deployments, list): @@ -62,11 +71,21 @@ def _load(self) -> None: } if len(self._deployments) != len(deployments): raise ValueError("cluster deployment registry has duplicate models") + if payload.get("schema_version") != REGISTRY_SCHEMA_VERSION: + # Legacy files hold no per-node paths; every deployment decoded + # above with an empty path_map, which is the exact behavior the + # file described. Persist the upgrade so the migration happens + # once, but never let an unwritable file block server startup. + self.migrated_from = int(payload.get("schema_version", 1)) + try: + self._save() + except OSError: + pass def _save(self) -> None: self.path.parent.mkdir(parents=True, exist_ok=True) payload = { - "schema_version": 1, + "schema_version": REGISTRY_SCHEMA_VERSION, "deployments": [ deployment.to_dict() for _, deployment in sorted(self._deployments.items()) @@ -152,9 +171,10 @@ def remove(self, deployment_id: str) -> bool: def to_dict(self) -> dict[str, Any]: return { - "schema_version": 1, + "schema_version": REGISTRY_SCHEMA_VERSION, "deployments": [deployment.to_dict() for deployment in self.list()], "load_error": self.load_error, + "migrated_from": self.migrated_from, } diff --git a/omlx/cluster/routes.py b/omlx/cluster/routes.py index ea4419dba5..6952881398 100644 --- a/omlx/cluster/routes.py +++ b/omlx/cluster/routes.py @@ -43,7 +43,12 @@ run_local_collective_smoke, run_local_pipeline_smoke, ) -from .deployment import ClusterDeployment, ClusterHost, validate_ssh_target +from .deployment import ( + ClusterDeployment, + ClusterHost, + validate_model_path_map, + validate_ssh_target, +) from .discovery import ( discover_all_peers, record_peer_transports, @@ -424,6 +429,9 @@ class ClusterPlanRequest(BaseModel): pipeline_microbatch_size: int | None = Field(default=None, gt=0, le=256) tensor_parallel_size: int = Field(default=1, ge=1, le=64) target_context_tokens: int = Field(default=8192, ge=1, le=1_048_576) + # Cluster v2: optional node_id → absolute model path on that node. Empty + # keeps the legacy same-absolute-path-on-every-node behavior. + path_map: dict[str, str] | None = Field(default=None, max_length=64) class ClusterHostRequest(BaseModel): @@ -479,6 +487,9 @@ class ClusterDeploymentRequest(BaseModel): # one dropped the role and the split cap without saying so. Activation is a # GUI workflow: callers must preview and name the placement they approve. approved_placement: str = Field(min_length=16, max_length=64) + # Cluster v2: node_id → absolute model path on that node. Nodes not listed + # load ``model_path`` — the pre-v2 shared-path behavior. + path_map: dict[str, str] | None = Field(default=None, max_length=64) class ClusterPeerProbeRequest(BaseModel): @@ -699,7 +710,14 @@ def _placement_rows(plan: dict[str, Any]) -> list[dict[str, Any]]: def _placement_signature(plan: dict[str, Any]) -> str: """Identity of the plan a user approves, stable across cosmetic re-planning.""" - payload = json.dumps(_placement_rows(plan), sort_keys=True, separators=(",", ":")) + rows: Any = _placement_rows(plan) + # A per-node path override changes what actually runs, so it is part of + # what the user approves. Folded in only when present, keeping signatures + # byte-identical to the legacy format for shared-path deployments. + path_map = plan.get("path_map") + if path_map: + rows = {"rows": rows, "path_map": path_map} + payload = json.dumps(rows, sort_keys=True, separators=(",", ":")) return hashlib.sha256(payload.encode()).hexdigest()[:16] @@ -800,9 +818,13 @@ def _create_cluster_plan(request: ClusterPlanRequest): f"across {len(nodes)} Macs." ) raise PlanningError(detail) + path_map = validate_model_path_map( + request.path_map, + tuple(node.node_id.strip() for node in request.nodes), + ) defaults = execution_profile(request.execution_profile) if request.tensor_parallel_size > 1: - return plan_hybrid( + plan = plan_hybrid( model, nodes, tensor_parallel_size=request.tensor_parallel_size, @@ -812,15 +834,19 @@ def _create_cluster_plan(request: ClusterPlanRequest): ), context_tokens=request.target_context_tokens, ) - return plan_unequal_pipeline( - model, - nodes, - workload_profile=request.execution_profile, - microbatch_size=( - request.pipeline_microbatch_size or defaults.pipeline_microbatch_size - ), - context_tokens=request.target_context_tokens, - ) + else: + plan = plan_unequal_pipeline( + model, + nodes, + workload_profile=request.execution_profile, + microbatch_size=( + request.pipeline_microbatch_size or defaults.pipeline_microbatch_size + ), + context_tokens=request.target_context_tokens, + ) + if path_map: + plan = replace(plan, path_map=path_map) + return plan class ClusterAutoconfigureRequest(BaseModel): @@ -1585,19 +1611,26 @@ def _run_staging_job( portable_model_path = home_relative_model_path(deployment.model) failed_nodes: list[str] = [] for host, assignment in zip(deployment.hosts, assignments): + # Cluster v2: files land at the node's path_map entry when one + # exists. Otherwise preserve the cross-account behavior by + # resolving the portable model path in the remote Mac's home. + explicit_destination = deployment.path_map.get(host.node_id) if _local_ssh_target(host.ssh): - destination_dir = str(model_path) + destination_dir = explicit_destination or str(model_path) + destination_path = Path(destination_dir) present = ( - { - path.name: path.stat().st_size - for path in model_path.iterdir() - if path.is_file() - } - if model_path.is_dir() + { + path.name: path.stat().st_size + for path in destination_path.iterdir() + if path.is_file() + } + if destination_path.is_dir() else {} ) else: - destination_dir = remote_model_dir(host.ssh, portable_model_path) + destination_dir = explicit_destination or remote_model_dir( + host.ssh, portable_model_path + ) present = remote_file_sizes(host.ssh, destination_dir) plan = plan_staging( model_path, @@ -2648,6 +2681,7 @@ def _create_deployment( pipeline_microbatch_size=requested_microbatch, tensor_parallel_size=request.tensor_parallel_size, target_context_tokens=request.target_context_tokens, + path_map=request.path_map, ) plan = _create_cluster_plan(plan_request) execution = _execution_for_request( @@ -2691,6 +2725,7 @@ def _create_deployment( performance_profiles=_request_performance_profiles(request.nodes), tensor_parallel_size=request.tensor_parallel_size, target_context_tokens=request.target_context_tokens, + path_map=validate_model_path_map(request.path_map, tuple(host_ids)), ) return deployment, plan.to_dict() diff --git a/omlx/cluster/staging.py b/omlx/cluster/staging.py index 4c4846c93f..632e93d9f2 100644 --- a/omlx/cluster/staging.py +++ b/omlx/cluster/staging.py @@ -212,6 +212,11 @@ def _model_identity_digest(model_path: str | Path) -> str: return hasher.hexdigest() +# Public name for the digest; the manifest endpoint and peer comparison in +# ``modelsync.py`` share this exact identity definition with staging. +model_identity_digest = _model_identity_digest + + def _indexed_shards(model_path: str | Path) -> tuple[ShardInfo, ...] | None: """Read the full shard map from the index even on a partially staged rank.""" diff --git a/omlx/server.py b/omlx/server.py index b7efe31802..f994498c6c 100644 --- a/omlx/server.py +++ b/omlx/server.py @@ -727,6 +727,19 @@ def _register_cluster_routes() -> None: Depends(require_distributed_inference_enabled), ], ) + # Cluster v2 model-sync manifest: admin-gated like the rest of the + # cluster surface; peers use it to compare model contents before sync. + from .cluster.modelsync import manifest_router as cluster_manifest_router + from .cluster.modelsync import set_modelsync_getters + + set_modelsync_getters(get_engine_pool) + app.include_router( + cluster_manifest_router, + dependencies=[ + Depends(require_admin), + Depends(require_distributed_inference_enabled), + ], + ) # The bootstrap bytes are public but pinned by SHA-256 in an admin-created # command. Claim/source/complete authenticate with one-time enrollment # credentials, not the browser's admin cookie. diff --git a/tests/test_cluster_modelsync.py b/tests/test_cluster_modelsync.py new file mode 100644 index 0000000000..c91d588767 --- /dev/null +++ b/tests/test_cluster_modelsync.py @@ -0,0 +1,683 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Cluster v2 model sync: manifests, path_map resolution, migration, decisions. + +All transports are mocked — no test here opens a socket, runs rsync, or +touches the Hugging Face hub. +""" + +import base64 +import json +import platform +import stat +import struct +import subprocess +import zlib +from pathlib import Path +from types import SimpleNamespace + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from omlx.cluster import modelsync +from omlx.cluster.deployment import ( + ClusterDeployment, + ClusterHost, + decode_worker_contract, + decode_worker_path_map, + validate_model_path_map, +) +from omlx.cluster.modelsync import ( + AUTO_RSYNC_THRESHOLD_BYTES, + ModelSyncError, + ModelSyncManager, + allow_patterns_for_shard, + build_manifest, + build_rsync_argv, + compare_manifests, + parse_rsync_progress, +) +from omlx.cluster.planner import PipelineAssignment, synthetic_model_layout, ShardPlan +from omlx.cluster.registry import ClusterRegistry + + +def _write_shard(directory, name, tensors, payload=b"\x00" * 32): + header = {t: {"dtype": "F16", "shape": [1], "data_offsets": [0, 2]} for t in tensors} + blob = json.dumps(header).encode() + (directory / name).write_bytes(struct.pack(" ClusterDeployment: + return ClusterDeployment( + deployment_id="sync-test", + model=model, + backend="ring", + hosts=( + ClusterHost("local", "127.0.0.1", ("10.0.0.1",)), + ClusterHost("peer", "user@studio.local", ("10.0.0.2",)), + ), + assignments=( + PipelineAssignment("local", 0, 2, 4, 20, 2, 4, 64), + PipelineAssignment("peer", 1, 0, 2, 10, 2, 4, 32), + ), + plan_hash="e" * 64, + path_map=path_map or {}, + ) + + +# -- manifest ----------------------------------------------------------------- + + +def test_build_manifest_on_fixture_model(tmp_path): + root = _model(tmp_path / "model-a") + + manifest = build_manifest(root, model_id="org/model-a") + + assert manifest.model_id == "org/model-a" + assert manifest.index_sha256 is not None + assert len(manifest.index_sha256) == 64 + assert len(manifest.identity_sha256) == 64 + names = [item.name for item in manifest.files] + assert "model-00000.safetensors" in names + assert "model-shared.safetensors" in names + assert "config.json" in names # sidecars travel with the manifest + assert manifest.total_bytes == sum(item.size_bytes for item in manifest.files) + assert manifest.total_bytes > 0 + # Round-trip through the wire format the endpoint serves. + restored = modelsync.ModelManifest.from_dict(manifest.to_dict()) + assert restored == manifest + + +def test_build_manifest_without_index_still_identifies(tmp_path): + root = _model(tmp_path / "model-b", with_index=False) + + manifest = build_manifest(root) + + assert manifest.index_sha256 is None + assert manifest.identity_sha256 + assert manifest.total_bytes > 0 + + +def test_build_manifest_rejects_non_model_dir(tmp_path): + root = tmp_path / "empty" + root.mkdir() + + with pytest.raises(ValueError, match="no safetensors"): + build_manifest(root) + + +@pytest.fixture +def manifest_client(tmp_path, monkeypatch): + """The manifest router mounted bare, backed by fixture model dirs.""" + + models_root = tmp_path / "models" + _model(models_root / "alpha") + settings = SimpleNamespace( + get_effective_model_dirs=lambda: [str(models_root)] + ) + monkeypatch.setattr(modelsync, "_pool_getter", None) + monkeypatch.setattr(modelsync, "_settings_loader", lambda: settings) + app = FastAPI() + app.include_router(modelsync.manifest_router) + return TestClient(app), models_root + + +def test_manifest_endpoint_serves_known_model(manifest_client): + client, models_root = manifest_client + + response = client.get(f"/api/cluster/models/{models_root}/alpha/manifest") + + assert response.status_code == 200 + payload = response.json() + assert payload["schema_version"] == 1 + assert payload["index_sha256"] + assert payload["total_bytes"] > 0 + names = {item["name"] for item in payload["files"]} + assert "model-shared.safetensors" in names + assert "config.json" in names + + +def test_manifest_endpoint_404_for_unknown_model(manifest_client): + client, _ = manifest_client + + response = client.get("/api/cluster/models/no/such-model/manifest") + + assert response.status_code == 404 + + +def test_manifest_endpoint_refuses_paths_outside_model_dirs( + manifest_client, tmp_path +): + client, _ = manifest_client + outside = _model(tmp_path / "elsewhere") + + response = client.get(f"/api/cluster/models/{outside}/manifest") + + assert response.status_code == 403 + + +# -- manifest comparison / status ---------------------------------------------- + + +def test_compare_manifests_states(tmp_path): + root = _model(tmp_path / "source") + local = build_manifest(root) + + assert compare_manifests(local, None)["state"] == "missing" + + present = build_manifest(root) + assert compare_manifests(local, present)["state"] == "present" + assert compare_manifests(local, present)["bytes"] == local.total_bytes + + peer_root = _model(tmp_path / "peer") + (peer_root / "model-00002.safetensors").unlink() + partial = build_manifest(peer_root) + result = compare_manifests(local, partial) + assert result["state"] == "partial" + assert result["missing"] == ["model-00002.safetensors"] + assert result["bytes"] == local.total_bytes - sum( + item.size_bytes for item in local.files if item.name == "model-00002.safetensors" + ) + + (peer_root / "config.json").write_text(json.dumps({"model_type": "other"})) + mismatch = build_manifest(peer_root) + assert compare_manifests(local, mismatch)["state"] == "mismatch" + + +def test_status_uses_peer_manifest_over_http(tmp_path): + root = _model(tmp_path / "source") + manager = ModelSyncManager( + http_fetch=lambda url, timeout: build_manifest(root, model_id="m").to_dict(), + settings_loader=lambda: SimpleNamespace(get_effective_model_dirs=lambda: []), + ) + + result = manager.status("peer.local:8080", str(root)) + + assert result["state"] == "present" + assert result["bytes"] == result["total_bytes"] + + +def test_status_missing_when_peer_lacks_model(tmp_path): + root = _model(tmp_path / "source") + manager = ModelSyncManager(http_fetch=lambda url, timeout: None) + + result = manager.status("peer.local:8080", str(root)) + + assert result["state"] == "missing" + assert result["bytes"] == 0 + + +def test_peer_manifest_requires_a_port(tmp_path): + manager = ModelSyncManager() + + with pytest.raises(ValueError, match="no port"): + manager.peer_manifest("peer.local", "model") + + +# -- path_map resolution -------------------------------------------------------- + + +def test_path_map_resolution_with_fallback(): + deployment = _deployment( + path_map={"peer": "/Volumes/models/studio-copy"}, + ) + + assert deployment.model_path_for("peer") == "/Volumes/models/studio-copy" + # Unlisted nodes keep the shared coordinator path — pre-v2 behavior. + assert deployment.model_path_for("local") == "/models/shared" + # A deployment with no path_map resolves everywhere to the shared path. + legacy = _deployment() + assert legacy.model_path_for("peer") == "/models/shared" + + +def test_path_map_validation(): + with pytest.raises(ValueError, match="absolute"): + _deployment(path_map={"peer": "relative/dir"}) + with pytest.raises(ValueError, match="outside the deployment"): + _deployment(path_map={"stranger": "/models/x"}) + assert validate_model_path_map(None) == {} + assert validate_model_path_map({"a": "/m"}, ("a",)) == {"a": "/m"} + + +def test_deployment_v2_round_trip_preserves_path_map(): + deployment = _deployment(path_map={"peer": "/Volumes/models/copy"}) + + restored = ClusterDeployment.from_dict(deployment.to_dict()) + + assert restored == deployment + assert restored.path_map == {"peer": "/Volumes/models/copy"} + assert deployment.to_dict()["schema_version"] == 2 + + +def test_legacy_v1_deployment_decodes_without_path_map(): + payload = _deployment().to_dict() + payload["schema_version"] = 1 + del payload["path_map"] + + restored = ClusterDeployment.from_dict(payload) + + assert restored.path_map == {} + assert restored.model_path_for("peer") == restored.model + + +def test_path_map_rides_the_worker_contract(): + deployment = _deployment(path_map={"peer": "/Volumes/models/copy"}) + + encoded = deployment.encode_worker_plan() + plan_hash, assignments, profiles, tp = decode_worker_contract(encoded) + + assert plan_hash == deployment.plan_hash + assert assignments == deployment.assignments + assert decode_worker_path_map(encoded) == {"peer": "/Volumes/models/copy"} + + +def test_v1_worker_contract_decodes_to_empty_path_map(): + deployment = _deployment() + raw = json.dumps( + { + "schema_version": 1, + "plan_hash": deployment.plan_hash, + "assignments": [ + assignment.to_dict() for assignment in deployment.assignments + ], + "performance_profiles": [], + "tensor_parallel_size": 1, + }, + sort_keys=True, + separators=(",", ":"), + ).encode() + encoded = base64.urlsafe_b64encode(zlib.compress(raw, level=9)).decode() + + assert decode_worker_path_map(encoded) == {} + plan_hash, assignments = decode_worker_contract(encoded)[:2] + assert plan_hash == deployment.plan_hash + assert len(assignments) == 2 + + +def test_plan_to_dict_carries_path_map_without_changing_hash(): + plan = ShardPlan( + model=synthetic_model_layout(total_weight_bytes=1024, layer_count=4), + assignments=( + PipelineAssignment("local", 0, 2, 4, 20, 2, 4, 64), + PipelineAssignment("peer", 1, 0, 2, 10, 2, 4, 32), + ), + plan_hash="f" * 64, + ) + mapped = ShardPlan( + model=plan.model, + assignments=plan.assignments, + plan_hash=plan.plan_hash, + path_map={"peer": "/Volumes/models/copy"}, + ) + + assert "path_map" not in plan.to_dict() + assert mapped.to_dict()["path_map"] == {"peer": "/Volumes/models/copy"} + # The layer split is path-independent: the map is display/staging + # metadata and must not mint a new plan identity. + assert mapped.plan_hash == plan.plan_hash + + +def test_placement_signature_covers_path_map_only_when_present(): + from omlx.cluster import routes + + plan = ShardPlan( + model=synthetic_model_layout(total_weight_bytes=1024, layer_count=4), + assignments=( + PipelineAssignment("local", 0, 2, 4, 20, 2, 4, 64), + PipelineAssignment("peer", 1, 0, 2, 10, 2, 4, 32), + ), + plan_hash="f" * 64, + ).to_dict() + + legacy = routes._placement_signature(plan) + assert routes._placement_signature(dict(plan)) == legacy + mapped = plan | {"path_map": {"peer": "/Volumes/models/copy"}} + assert routes._placement_signature(mapped) != legacy + + +# -- legacy deployments.json migration ------------------------------------------ + + +def _write_legacy_registry(base: Path, deployment: ClusterDeployment) -> Path: + entry = deployment.to_dict() + entry["schema_version"] = 1 + del entry["path_map"] + path = base / "cluster" / "deployments.json" + path.parent.mkdir(parents=True) + path.write_text( + json.dumps({"schema_version": 1, "deployments": [entry]}, indent=2) + ) + return path + + +def test_legacy_deployments_json_migrates_on_load(tmp_path): + model = tmp_path / "model" + model.mkdir() + deployment = _deployment(str(model)) + path = _write_legacy_registry(tmp_path, deployment) + + registry = ClusterRegistry(tmp_path) + + loaded = registry.get_for_model(str(model)) + assert loaded is not None + assert loaded.path_map == {} + assert loaded.model_path_for("peer") == str(model) + assert registry.migrated_from == 1 + # The upgrade is persisted: the file now carries schema v2 and an + # explicit (empty) path_map, at the same private permissions. + on_disk = json.loads(path.read_text()) + assert on_disk["schema_version"] == 2 + assert on_disk["deployments"][0]["schema_version"] == 2 + assert on_disk["deployments"][0]["path_map"] == {} + assert stat.S_IMODE(path.stat().st_mode) == 0o600 + # A v2 file loads cleanly on the next start, with no migration flagged. + assert ClusterRegistry(tmp_path).migrated_from is None + + +def test_registry_round_trip_preserves_path_map(tmp_path): + model = tmp_path / "model" + model.mkdir() + deployment = _deployment( + str(model), path_map={"peer": "/Volumes/models/copy"} + ) + registry = ClusterRegistry(tmp_path) + + registry.upsert(deployment) + restored = ClusterRegistry(tmp_path).get_for_model(str(model)) + + assert restored is not None + assert restored.path_map == {"peer": "/Volumes/models/copy"} + assert restored.model_path_for("peer") == "/Volumes/models/copy" + + +# -- sync decisions -------------------------------------------------------------- + + +def test_auto_method_prefers_rsync_for_large_models_with_ssh_trust(): + manager = ModelSyncManager(ssh_trust=lambda target: True) + + assert ( + manager.decide_method("user@peer", AUTO_RSYNC_THRESHOLD_BYTES + 1) + == "rsync" + ) + # At or below 20 GiB each node downloads its own shard files instead. + assert ( + manager.decide_method("user@peer", AUTO_RSYNC_THRESHOLD_BYTES) + == "download" + ) + # No enrolled SSH trust: download regardless of size. + untrusted = ModelSyncManager(ssh_trust=lambda target: False) + assert ( + untrusted.decide_method("user@peer", AUTO_RSYNC_THRESHOLD_BYTES * 4) + == "download" + ) + # No SSH target at all: download. + assert manager.decide_method(None, AUTO_RSYNC_THRESHOLD_BYTES * 4) == "download" + + +def test_sync_rsync_invokes_resumable_transport(tmp_path): + root = _model(tmp_path / "source") + runs = [] + + def fake_rsync(argv, on_line): + runs.append(argv) + on_line(" 1,048,576 50% 100.00MB/s 0:00:01") + return 0 + + manager = ModelSyncManager( + ssh_trust=lambda target: True, + rsync_run=fake_rsync, + ) + events = [] + result = manager.sync( + "peer.local:8080", + str(root), + "rsync", + ssh_target="user@peer.local", + destination="/Volumes/models/copy", + on_progress=events.append, + ) + + argv = runs[0] + assert "--partial" in argv and "--append-verify" in argv + assert "BatchMode=yes" in argv[argv.index("-e") + 1] + assert argv[-2].endswith("/") + assert argv[-1] == "user@peer.local:/Volumes/models/copy" + assert result["method"] == "rsync" + transferring = [e for e in events if e.phase == "transferring"] + assert transferring, "rsync progress lines must surface as UI events" + assert transferring[0].bytes_done == 1_048_576 + assert transferring[0].bytes_per_second == pytest.approx(100.0 * 1000**2) + assert transferring[0].eta_seconds == 1.0 + assert events[-1].phase == "done" + # Events are also retained for polling UIs. + assert manager.events[-1].phase == "done" + + +def test_sync_rsync_requires_trust_and_target(tmp_path): + root = _model(tmp_path / "source") + manager = ModelSyncManager(ssh_trust=lambda target: False) + + with pytest.raises(ModelSyncError, match="enrolled SSH trust"): + manager.sync("peer", str(root), "rsync", ssh_target="user@peer") + with pytest.raises(ModelSyncError, match="ssh_target"): + manager.sync("peer", str(root), "rsync", ssh_target=None) + + +def test_sync_download_fetches_only_shard_files(tmp_path): + root = _model(tmp_path / "source") + calls = [] + + def fake_download(*, repo_id, allow_patterns, local_dir): + calls.append((repo_id, tuple(allow_patterns), local_dir)) + + manager = ModelSyncManager(hf_download=fake_download) + destination = tmp_path / "inbound" + + result = manager.sync( + "peer.local:8080", + str(root), + "download", + destination=destination, + repo_id="org/model-a", + start_layer=0, + end_layer=2, + ) + + repo_id, patterns, local_dir = calls[0] + assert repo_id == "org/model-a" + assert Path(local_dir) == destination + # Layers 0-1 live in model-00000; embeddings and sidecars always travel. + assert "model-00000.safetensors" in patterns + assert "model-shared.safetensors" in patterns + assert "config.json" in patterns + assert "model-00002.safetensors" not in patterns, "other stages stay on HF" + assert result["method"] == "download" + assert result["allow_patterns"] == sorted(patterns) + + +def test_sync_download_requires_repo_and_destination(tmp_path): + root = _model(tmp_path / "source") + manager = ModelSyncManager(hf_download=lambda **kw: None) + + with pytest.raises(ModelSyncError, match="repo ID"): + manager.sync("peer", str(root), "download", destination=tmp_path / "x") + with pytest.raises(ModelSyncError, match="destination"): + manager.sync("peer", str(root), "download", repo_id="org/m") + + +def test_sync_failure_emits_error_event(tmp_path): + root = _model(tmp_path / "source") + + def failing_rsync(argv, on_line): + return 23 + + manager = ModelSyncManager( + ssh_trust=lambda target: True, + rsync_run=failing_rsync, + ) + events = [] + + with pytest.raises(ModelSyncError, match="status 23"): + manager.sync( + "peer", str(root), "rsync", + ssh_target="user@peer", on_progress=events.append, + ) + + assert events[-1].phase == "error" + + +def test_sync_auto_selects_rsync_for_large_models(tmp_path): + root = _model(tmp_path / "source") + runs = [] + downloads = [] + manager = ModelSyncManager( + ssh_trust=lambda target: True, + rsync_run=lambda argv, on_line: runs.append(argv) or 0, + hf_download=lambda **kw: downloads.append(kw), + ) + + # The fixture is far below 20 GiB, so auto picks download even with trust. + manager.sync( + "peer", + str(root), + "auto", + ssh_target="user@peer", + destination=tmp_path / "d", + repo_id="org/m", + ) + assert not runs and len(downloads) == 1 + + # Force the decision boundary: a manifest over the threshold picks rsync. + big = ModelSyncManager( + ssh_trust=lambda target: True, + rsync_run=lambda argv, on_line: runs.append(argv) or 0, + ) + import omlx.cluster.modelsync as ms + + original = ms.AUTO_RSYNC_THRESHOLD_BYTES + ms.AUTO_RSYNC_THRESHOLD_BYTES = 1 + try: + big.sync("peer", str(root), "auto", ssh_target="user@peer") + finally: + ms.AUTO_RSYNC_THRESHOLD_BYTES = original + assert len(runs) == 1 + + +# -- rsync helpers ---------------------------------------------------------------- + + +def test_build_rsync_argv_is_resumable_and_noninteractive(): + argv = build_rsync_argv( + "/models/src", "user@peer.local", "/Volumes/models/dst", + ssh_identity="~/.ssh/omlx_cluster", + ) + + assert argv[0] == "rsync" + assert "--partial" in argv + assert "--append-verify" in argv + assert "--info=progress2" in argv + ssh = argv[argv.index("-e") + 1] + assert "BatchMode=yes" in ssh and "omlx_cluster" in ssh + assert argv[-2] == "/models/src/" + assert argv[-1] == "user@peer.local:/Volumes/models/dst" + + +def test_parse_rsync_progress_lines(): + assert parse_rsync_progress(" 1,234,567 42% 123.45MB/s 0:01:23") == ( + 1_234_567, + 123.45 * 1000**2, + 83.0, + ) + assert parse_rsync_progress("100 100% 1.00GB/s 1:02:03")[2] == 3723.0 + assert parse_rsync_progress("sending incremental file list") is None + assert parse_rsync_progress("") is None + + +# -- allow-patterns ------------------------------------------------------------ + + +def test_allow_patterns_cover_whole_model_without_layer_range(tmp_path): + root = _model(tmp_path / "source") + + patterns = allow_patterns_for_shard(root) + + assert "model-00000.safetensors" in patterns + assert "model-00002.safetensors" in patterns + assert "model-shared.safetensors" in patterns + assert "config.json" in patterns + + +def test_allow_patterns_reject_inverted_range(tmp_path): + root = _model(tmp_path / "source") + + with pytest.raises(ValueError, match="0 <= start < end"): + allow_patterns_for_shard(root, 3, 3) + + +# -- launch preflight ------------------------------------------------------------- + + +def test_preflight_uses_per_node_model_paths(monkeypatch): + from omlx.cluster import launch + from omlx.cluster.launch import _local_runtime_versions, preflight_remote_hosts + from omlx.cluster.models import CLUSTER_PROTOCOL_VERSION + + versions = _local_runtime_versions() + calls = [] + + def runner(argv, **kwargs): + calls.append(argv) + return subprocess.CompletedProcess( + argv, + 0, + stdout=json.dumps( + versions + | { + "cluster-protocol": CLUSTER_PROTOCOL_VERSION, + "python": platform.python_version(), + "model-exists": True, + "admission-ceiling-bytes": 1024**4, + } + ), + stderr="", + ) + + deployment = _deployment( + "/nonexistent/shared", + path_map={"peer": "/Volumes/models/studio-copy"}, + ) + result = preflight_remote_hosts( + deployment, + python_executable="/opt/omlx/bin/python", + runner=runner, + ) + + assert len(result) == 2 + assert len(calls) == 1 + # The peer is probed at its own path, not the coordinator's. + assert "/Volumes/models/studio-copy" in calls[0][-1] + assert "/nonexistent/shared" not in calls[0][-1] From 4e2e60d6059d0d7979ccfcb10390defbc89496e9 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Tue, 18 Aug 2026 17:34:10 -0700 Subject: [PATCH 118/132] fix: route rsync through shared cluster SSH policy; fake path_map decoder in worker test harness - modelsync.build_rsync_argv now builds its -e command from ssh_policy.cluster_ssh_options() (seam test compliance: no literal ssh argv outside the shared policy) - test_cluster_inference_worker harness fakes decode_worker_path_map next to decode_worker_contract; the fake plan string is not a real contract --- omlx/cluster/modelsync.py | 12 ++++++++---- tests/test_cluster_inference_worker.py | 7 +++++++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/omlx/cluster/modelsync.py b/omlx/cluster/modelsync.py index f16f17512e..7f99320edb 100644 --- a/omlx/cluster/modelsync.py +++ b/omlx/cluster/modelsync.py @@ -22,6 +22,7 @@ import hashlib import json import re +import shlex import subprocess import threading import time @@ -33,6 +34,7 @@ from fastapi import APIRouter, HTTPException from ..exceptions import ModelNotFoundError +from .ssh_policy import cluster_ssh_options from .staging import ( index_shards, model_identity_digest, @@ -300,12 +302,14 @@ def build_rsync_argv( ``--partial --append-verify`` resumes interrupted transfers and verifies the appended bytes, the functional equivalent of ``-P --append-verify`` - without the interactive progress format. + without the interactive progress format. The SSH transport uses the one + shared non-interactive cluster policy (managed identity, accept-new + host keys, BatchMode) — never a hand-rolled option set. """ - ssh_command = ["ssh", "-o", "BatchMode=yes"] + ssh_argv = ["ssh", *cluster_ssh_options()] if ssh_identity is not None: - ssh_command.extend(["-i", str(ssh_identity)]) + ssh_argv.extend(["-i", str(ssh_identity)]) source = str(Path(source_dir).expanduser()).rstrip("/") + "/" destination = f"{ssh_target}:{destination_dir}" return [ @@ -315,7 +319,7 @@ def build_rsync_argv( "--append-verify", "--info=progress2", "-e", - " ".join(ssh_command), + shlex.join(ssh_argv), source, destination, ] diff --git a/tests/test_cluster_inference_worker.py b/tests/test_cluster_inference_worker.py index 8eb385a2a2..116d424118 100644 --- a/tests/test_cluster_inference_worker.py +++ b/tests/test_cluster_inference_worker.py @@ -637,6 +637,13 @@ def fake_run(host, port, provider): "decode_worker_contract", lambda _plan: ("a" * 64, assignments, (), 1), ) + # The fake plan above is not a real encoded contract, so the path_map + # decoder it feeds must be faked alongside it (empty = legacy behavior). + monkeypatch.setattr( + inference_worker, + "decode_worker_path_map", + lambda _plan: {}, + ) def fake_guard_rank_load(item, *, rank, **kwargs): record["order"].append("guard") From a75eeb3a00b6d3c46ecf30f2cdd0a76cd0462354 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Tue, 18 Aug 2026 17:06:12 -0700 Subject: [PATCH 119/132] planner: RAM-proportional largest-remainder allocator for N-node plans allocate_layers_proportional (exact Fraction arithmetic, min one layer per node, deterministic tie-breaks) plus plan_proportional_pipeline, sharing the assignment/fit/hash tail with plan_unequal_pipeline via _finish_pipeline_plan. The balanced planner's hash payload is byte-identical to before. Routes gain an additive allocation field ('balanced' default) on plan/deployment/replan requests; proportional is pipeline-only. --- omlx/cluster/planner.py | 156 +++++++++++++++++++++++++++++++++++++--- omlx/cluster/routes.py | 6 ++ 2 files changed, 153 insertions(+), 9 deletions(-) diff --git a/omlx/cluster/planner.py b/omlx/cluster/planner.py index 696ba01098..0bafbd9746 100644 --- a/omlx/cluster/planner.py +++ b/omlx/cluster/planner.py @@ -1451,15 +1451,13 @@ def _predict_stage_seconds( return compute_seconds, send_seconds, compute_seconds + send_seconds -def plan_unequal_pipeline( +def _validate_pipeline_request( model: ModelLayout, nodes: Sequence[NodeBudget], - *, - workload_profile: ExecutionProfileName = "balanced", - microbatch_size: int = 1, - context_tokens: int = _DEFAULT_CONTEXT_TOKENS, -) -> ShardPlan: - """Assign contiguous layers in MLX pipeline order across unequal nodes.""" + workload_profile: ExecutionProfileName, + microbatch_size: int, +) -> None: + """The input contract every pipeline planner enforces identically.""" if not nodes: raise ValueError("at least one node is required") @@ -1483,6 +1481,19 @@ def plan_unequal_pipeline( f"replicated fixed weights do not fit node {node.node_id}" ) + +def plan_unequal_pipeline( + model: ModelLayout, + nodes: Sequence[NodeBudget], + *, + workload_profile: ExecutionProfileName = "balanced", + microbatch_size: int = 1, + context_tokens: int = _DEFAULT_CONTEXT_TOKENS, +) -> ShardPlan: + """Assign contiguous layers in MLX pipeline order across unequal nodes.""" + + _validate_pipeline_request(model, nodes, workload_profile, microbatch_size) + # MLX-LM sends activations from the highest rank (early layers) down to # rank zero (late layers / HTTP coordinator), so partition in reverse rank. pipeline_nodes = tuple(sorted(nodes, key=lambda item: item.rank, reverse=True)) @@ -1508,6 +1519,133 @@ def plan_unequal_pipeline( f"fit the supplied per-node budgets: {exc}" ) from exc raise + return _finish_pipeline_plan( + model, + nodes, + pipeline_nodes, + ranges, + workload_profile=workload_profile, + microbatch_size=microbatch_size, + context_tokens=context_tokens, + optimization="performance" if performance_aware else "memory", + ) + + +def allocate_layers_proportional( + layer_count: int, + shares: Sequence[int], +) -> tuple[int, ...]: + """Split ``layer_count`` across nodes proportionally to ``shares``. + + Largest-remainder rounding with a one-layer minimum per node — the + allocation rule exo's placement uses, so a 256 GB + 128 GB pair splits + roughly ⅔–⅓. Fractions are exact (no float drift) and ties break toward + the larger share, then the earlier pipeline position, so the result is + deterministic and reproducible across machines. + """ + + if not isinstance(layer_count, int) or layer_count <= 0: + raise ValueError("layer_count must be a positive integer") + if not shares: + raise ValueError("at least one share is required") + for share in shares: + if not isinstance(share, int) or isinstance(share, bool) or share <= 0: + raise ValueError("shares must be positive integers") + node_count = len(shares) + if node_count > layer_count: + raise PlanningError( + f"{node_count} nodes cannot each receive a layer from " + f"{layer_count} layers" + ) + total = sum(shares) + exact = [Fraction(layer_count * share, total) for share in shares] + counts = [max(1, value.numerator // value.denominator) for value in exact] + remainder = layer_count - sum(counts) + # Σfloor(exact) ≤ layer_count and the one-layer floor adds at most one per + # node that floored to zero, so ``remainder`` is never negative. + assert remainder >= 0 + order = sorted( + range(node_count), + key=lambda index: ( + -(exact[index] - counts[index]), + -shares[index], + index, + ), + ) + for index in order[:remainder]: + counts[index] += 1 + return tuple(counts) + + +def plan_proportional_pipeline( + model: ModelLayout, + nodes: Sequence[NodeBudget], + *, + workload_profile: ExecutionProfileName = "balanced", + microbatch_size: int = 1, + context_tokens: int = _DEFAULT_CONTEXT_TOKENS, +) -> ShardPlan: + """RAM-proportional N-node pipeline plan (largest-remainder, exo-style). + + Layer counts are proportional to each node's usable memory + (``capacity − reserve``), rounded by largest remainder. Unlike the + balanced planner this does not optimize for the bottleneck stage or honor + soft weight targets — it is the predictable "split by RAM" rule operators + expect when generalizing beyond two nodes. Per-node weight ceilings (the + split control) and KV reservations are still enforced: a node whose + proportional share does not fit fails the plan with its name, rather than + being silently rebalanced. + """ + + _validate_pipeline_request(model, nodes, workload_profile, microbatch_size) + + pipeline_nodes = tuple(sorted(nodes, key=lambda item: item.rank, reverse=True)) + counts = allocate_layers_proportional( + len(model.layer_weight_bytes), + [node.usable_bytes for node in pipeline_nodes], + ) + ranges: list[tuple[int, int]] = [] + start = 0 + for count in counts: + ranges.append((start, start + count)) + start += count + for node, (range_start, range_end) in zip(pipeline_nodes, ranges): + layer_weight = sum(model.layer_weight_bytes[range_start:range_end]) + if model.fixed_weight_bytes + layer_weight > node.weight_ceiling_bytes: + raise PlanningError( + f"the RAM-proportional split gives node {node.node_id} " + f"{range_end - range_start} layers " + f"({model.fixed_weight_bytes + layer_weight} bytes with fixed " + f"weights) above its weight ceiling of " + f"{node.weight_ceiling_bytes}; raise that node's split cap or " + "plan with the balanced allocator" + ) + return _finish_pipeline_plan( + model, + nodes, + pipeline_nodes, + tuple(ranges), + workload_profile=workload_profile, + microbatch_size=microbatch_size, + context_tokens=context_tokens, + optimization="ram-proportional", + ) + + +def _finish_pipeline_plan( + model: ModelLayout, + nodes: Sequence[NodeBudget], + pipeline_nodes: Sequence[NodeBudget], + ranges: tuple[tuple[int, int], ...] | list[tuple[int, int]], + *, + workload_profile: ExecutionProfileName, + microbatch_size: int, + context_tokens: int, + optimization: str, +) -> ShardPlan: + """Assignments, per-node fit checks, and the signed hash for a partition.""" + + performance_aware = all(node.performance is not None for node in pipeline_nodes) assignments: list[PipelineAssignment] = [] for node, (start, end) in zip(pipeline_nodes, ranges): layer_weight_bytes = sum(model.layer_weight_bytes[start:end]) @@ -1560,7 +1698,7 @@ def plan_unequal_pipeline( hash_payload = { "model": model.to_dict(), "context_tokens": context_tokens, - "optimization": "performance" if performance_aware else "memory", + "optimization": optimization, "workload_profile": workload_profile, "microbatch_size": microbatch_size, "performance_profiles": [ @@ -1601,7 +1739,7 @@ def plan_unequal_pipeline( model=model, assignments=tuple(assignments), plan_hash=plan_hash, - optimization="performance" if performance_aware else "memory", + optimization=optimization, workload_profile=workload_profile, performance_profiles=tuple( node.performance diff --git a/omlx/cluster/routes.py b/omlx/cluster/routes.py index 6952881398..2c4fbd285a 100644 --- a/omlx/cluster/routes.py +++ b/omlx/cluster/routes.py @@ -89,6 +89,7 @@ ShardPlan, complete_model_layout, plan_hybrid, + plan_proportional_pipeline, plan_unequal_pipeline, remote_model_layout, synthetic_model_layout, @@ -426,6 +427,9 @@ class ClusterPlanRequest(BaseModel): layer_count: int = Field(default=80, gt=0, le=2048) nodes: list[ClusterPlanNodeRequest] = Field(min_length=1, max_length=64) execution_profile: Literal["interactive", "balanced", "throughput"] = "balanced" + # "balanced" runs the bottleneck-minimizing DP planner; "proportional" + # splits layers ∝ usable RAM with largest-remainder rounding (exo-style). + allocation: Literal["balanced", "proportional"] = "balanced" pipeline_microbatch_size: int | None = Field(default=None, gt=0, le=256) tensor_parallel_size: int = Field(default=1, ge=1, le=64) target_context_tokens: int = Field(default=8192, ge=1, le=1_048_576) @@ -472,6 +476,7 @@ class ClusterDeploymentRequest(BaseModel): hosts: list[ClusterHostRequest] = Field(min_length=2, max_length=64) preflight: Literal[True] = True execution_profile: Literal["interactive", "balanced", "throughput"] = "balanced" + allocation: Literal["balanced", "proportional"] = "balanced" auto_tune: bool = True sampling_rank_only: bool = True async_overlap: bool = True @@ -2678,6 +2683,7 @@ def _create_deployment( model_source_python=request.model_source_python, nodes=request.nodes, execution_profile=request.execution_profile, + allocation=request.allocation, pipeline_microbatch_size=requested_microbatch, tensor_parallel_size=request.tensor_parallel_size, target_context_tokens=request.target_context_tokens, From e6803de79060d308c38bb69470314d4766c4ae5d Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Wed, 26 Aug 2026 03:45:38 -0700 Subject: [PATCH 120/132] fix(cluster): preserve proportional allocation routing --- omlx/cluster/planner.py | 1 + omlx/cluster/routes.py | 15 +++++++++++++++ 2 files changed, 16 insertions(+) diff --git a/omlx/cluster/planner.py b/omlx/cluster/planner.py index 0bafbd9746..3a3a96a22f 100644 --- a/omlx/cluster/planner.py +++ b/omlx/cluster/planner.py @@ -12,6 +12,7 @@ from collections.abc import Iterator, Sequence from contextlib import contextmanager from dataclasses import dataclass, field, replace +from fractions import Fraction from pathlib import Path from typing import Any diff --git a/omlx/cluster/routes.py b/omlx/cluster/routes.py index 2c4fbd285a..1f4a395b8d 100644 --- a/omlx/cluster/routes.py +++ b/omlx/cluster/routes.py @@ -829,6 +829,11 @@ def _create_cluster_plan(request: ClusterPlanRequest): ) defaults = execution_profile(request.execution_profile) if request.tensor_parallel_size > 1: + if request.allocation != "balanced": + raise PlanningError( + "RAM-proportional allocation is a pipeline-only rule; tensor " + "parallelism uses the hybrid planner (allocation='balanced')" + ) plan = plan_hybrid( model, nodes, @@ -839,6 +844,16 @@ def _create_cluster_plan(request: ClusterPlanRequest): ), context_tokens=request.target_context_tokens, ) + elif request.allocation == "proportional": + plan = plan_proportional_pipeline( + model, + nodes, + workload_profile=request.execution_profile, + microbatch_size=( + request.pipeline_microbatch_size or defaults.pipeline_microbatch_size + ), + context_tokens=request.target_context_tokens, + ) else: plan = plan_unequal_pipeline( model, From 142c0b3060772ffc426389597064e1ae0230bdb9 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Tue, 18 Aug 2026 17:07:41 -0700 Subject: [PATCH 121/132] =?UTF-8?q?test:=20proportional=20allocator=20?= =?UTF-8?q?=E2=80=94=20ratios,=20min-1,=20tie-breaks,=20ceilings,=20KV=20f?= =?UTF-8?q?it,=20route=20wiring?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/test_cluster_proportional_plan.py | 283 ++++++++++++++++++++++++ 1 file changed, 283 insertions(+) create mode 100644 tests/test_cluster_proportional_plan.py diff --git a/tests/test_cluster_proportional_plan.py b/tests/test_cluster_proportional_plan.py new file mode 100644 index 0000000000..9a2344c054 --- /dev/null +++ b/tests/test_cluster_proportional_plan.py @@ -0,0 +1,283 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Tests for the RAM-proportional largest-remainder N-node allocator.""" + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from omlx.cluster import routes +from omlx.cluster.planner import ( + ModelLayout, + NodeBudget, + PlanningError, + allocate_layers_proportional, + plan_proportional_pipeline, + plan_unequal_pipeline, +) + +GIB = 1024**3 + + +def _client() -> TestClient: + app = FastAPI() + app.include_router(routes.router) + return TestClient(app) + + +# --------------------------------------------------------------------------- +# allocate_layers_proportional +# --------------------------------------------------------------------------- + + +def test_proportional_split_matches_ram_ratio(): + # exo's reference case: 256 GB + 128 GB splits ≈⅔–⅓. + counts = allocate_layers_proportional(80, [256 * GIB, 128 * GIB]) + + assert counts == (53, 27) + assert sum(counts) == 80 + + +def test_proportional_split_three_equal_nodes(): + counts = allocate_layers_proportional(80, [100, 100, 100]) + + # 26.67 each: two nodes round up, ties break toward earlier position. + assert counts == (27, 27, 26) + assert sum(counts) == 80 + + +def test_proportional_split_guarantees_one_layer_per_node(): + counts = allocate_layers_proportional(10, [1000, 1]) + + assert counts == (9, 1) + + +def test_proportional_split_remainder_goes_to_largest_fraction(): + counts = allocate_layers_proportional(4, [1, 1, 1]) + + assert counts == (2, 1, 1) + + +def test_proportional_split_is_deterministic(): + shares = [37, 91, 55, 12] + + assert allocate_layers_proportional(61, shares) == allocate_layers_proportional( + 61, shares + ) + assert sum(allocate_layers_proportional(61, shares)) == 61 + + +def test_proportional_split_rejects_more_nodes_than_layers(): + with pytest.raises(PlanningError, match="cannot each receive a layer"): + allocate_layers_proportional(2, [1, 1, 1]) + + +@pytest.mark.parametrize("layer_count, shares", [(0, [1]), (-3, [1])]) +def test_proportional_split_rejects_nonpositive_layer_count(layer_count, shares): + with pytest.raises(ValueError): + allocate_layers_proportional(layer_count, shares) + + +@pytest.mark.parametrize("shares", [[0], [10, -1], [10, 0]]) +def test_proportional_split_rejects_nonpositive_shares(shares): + with pytest.raises(ValueError, match="positive"): + allocate_layers_proportional(8, shares) + + +# --------------------------------------------------------------------------- +# plan_proportional_pipeline +# --------------------------------------------------------------------------- + + +def _model(layers=(10, 10, 10, 10), **overrides): + return ModelLayout( + source="synthetic", + fixed_weight_bytes=1, + layer_weight_bytes=tuple(layers), + supports_pipeline=True, + **overrides, + ) + + +def _nodes(*specs): + return [ + NodeBudget( + node_id=node_id, + capacity_bytes=capacity, + reserve_bytes=reserve, + rank=rank, + **extra, + ) + for rank, (node_id, capacity, reserve, extra) in enumerate(specs) + ] + + +def test_proportional_plan_two_unequal_nodes(): + # usable 90 vs 50 → 4 layers split 2.57/1.43 → 3/1 after largest remainder. + plan = plan_proportional_pipeline( + _model(), + _nodes(("large", 100, 10, {}), ("small", 60, 10, {})), + ) + + assert plan.optimization == "ram-proportional" + by_rank = {item.rank: item for item in plan.assignments} + # Highest rank owns the earliest layers (MLX pipeline order). + assert (by_rank[1].start_layer, by_rank[1].end_layer) == (0, 1) + assert by_rank[1].node_id == "small" + assert (by_rank[0].start_layer, by_rank[0].end_layer) == (1, 4) + assert by_rank[0].node_id == "large" + # Full, contiguous coverage. + covered = sorted( + (item.start_layer, item.end_layer) for item in plan.assignments + ) + assert covered == [(0, 1), (1, 4)] + + +def test_proportional_plan_three_nodes_covers_every_layer_once(): + plan = plan_proportional_pipeline( + _model(layers=(10,) * 12), + _nodes( + ("a", 200, 10, {}), + ("b", 100, 10, {}), + ("c", 60, 10, {}), + ), + ) + + assert len(plan.assignments) == 3 + covered = sorted( + (item.start_layer, item.end_layer) for item in plan.assignments + ) + assert covered[0][0] == 0 + assert covered[-1][1] == 12 + for previous, following in zip(covered, covered[1:]): + assert previous[1] == following[0] + # Shares 190:90:50 → counts ∝ usable RAM, descending by node size. + counts = { + item.node_id: item.end_layer - item.start_layer + for item in plan.assignments + } + assert counts["a"] > counts["b"] > counts["c"] + assert sum(counts.values()) == 12 + + +def test_proportional_plan_respects_weight_ceiling(): + with pytest.raises(PlanningError, match="small.*split cap|weight ceiling"): + plan_proportional_pipeline( + _model(), + _nodes( + ("large", 100, 10, {}), + ("small", 60, 10, {"max_weight_bytes": 5}), + ), + ) + + +def test_proportional_plan_validates_kv_fit(): + model = _model(kv_bytes_per_token_per_layer=1) + with pytest.raises(PlanningError, match="KV cache"): + plan_proportional_pipeline( + model, + _nodes(("large", 100, 10, {}), ("small", 60, 10, {})), + context_tokens=1_000_000, + ) + + +def test_proportional_plan_hash_is_stable_and_distinct(): + nodes = _nodes(("large", 100, 10, {}), ("small", 60, 10, {})) + + first = plan_proportional_pipeline(_model(), nodes) + second = plan_proportional_pipeline(_model(), nodes) + balanced = plan_unequal_pipeline(_model(), nodes) + + assert first.plan_hash == second.plan_hash + # The allocator is part of plan identity even when the layer ranges agree. + assert first.plan_hash != balanced.plan_hash + + +def test_proportional_plan_single_node_holds_everything(): + plan = plan_proportional_pipeline( + _model(), + _nodes(("only", 100, 10, {})), + ) + + assert len(plan.assignments) == 1 + assert (plan.assignments[0].start_layer, plan.assignments[0].end_layer) == (0, 4) + + +# --------------------------------------------------------------------------- +# Route-level allocation selection +# --------------------------------------------------------------------------- + + +def test_plan_route_runs_proportional_allocator(monkeypatch): + monkeypatch.setattr( + routes, + "inspect_safetensors_layout", + lambda path: _model(layers=(10,) * 12), + ) + + response = _client().post( + "/admin/api/cluster/plan", + json={ + "model_path": "/models/example", + "allocation": "proportional", + "nodes": [ + {"node_id": "a", "capacity_bytes": 200, "reserve_bytes": 10}, + {"node_id": "b", "capacity_bytes": 100, "reserve_bytes": 10}, + {"node_id": "c", "capacity_bytes": 60, "reserve_bytes": 10}, + ], + }, + ) + + assert response.status_code == 200, response.json() + payload = response.json() + assert payload["optimization"] == "ram-proportional" + assert payload["placement_signature"] + counts = { + item["node_id"]: item["layer_count"] for item in payload["assignments"] + } + assert counts["a"] > counts["b"] > counts["c"] + + +def test_plan_route_defaults_to_balanced_allocator(monkeypatch): + monkeypatch.setattr( + routes, + "inspect_safetensors_layout", + lambda path: _model(layers=(10,) * 12), + ) + + response = _client().post( + "/admin/api/cluster/plan", + json={ + "model_path": "/models/example", + "nodes": [ + {"node_id": "a", "capacity_bytes": 200, "reserve_bytes": 10}, + {"node_id": "b", "capacity_bytes": 100, "reserve_bytes": 10}, + ], + }, + ) + + assert response.status_code == 200, response.json() + assert response.json()["optimization"] == "memory" + + +def test_plan_route_rejects_proportional_tensor_parallel(monkeypatch): + monkeypatch.setattr( + routes, + "inspect_safetensors_layout", + lambda path: _model(layers=(10,) * 12), + ) + + response = _client().post( + "/admin/api/cluster/plan", + json={ + "model_path": "/models/example", + "allocation": "proportional", + "tensor_parallel_size": 2, + "nodes": [ + {"node_id": "a", "capacity_bytes": 200, "reserve_bytes": 10}, + {"node_id": "b", "capacity_bytes": 100, "reserve_bytes": 10}, + ], + }, + ) + + assert response.status_code == 400 + assert "pipeline-only" in response.json()["detail"] From 596ed74ba76f7dc66545d2afd97ccfd23fc5ee79 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Tue, 18 Aug 2026 16:57:39 -0700 Subject: [PATCH 122/132] =?UTF-8?q?runtime:=20one-action=20POST=20/admin/a?= =?UTF-8?q?pi/cluster/replan=20(deactivate=E2=86=92re-plan=E2=86=92reload)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Extract the activation pipeline into _activate_and_report so the replan endpoint and the explicit /deployments approval share one code path. The replan endpoint derives nodes/hosts/backend from the current deployment when not posted, renders a signed preview with a placement diff, and on approval runs the quiescence-gated unload (engine-pool prepare_cluster_ reload) whose distributed supervisor teardown is verified before the registry swap and eager reload. --- omlx/cluster/replan.py | 118 ++++++++++++++++++++++ omlx/cluster/routes.py | 218 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 333 insertions(+), 3 deletions(-) create mode 100644 omlx/cluster/replan.py diff --git a/omlx/cluster/replan.py b/omlx/cluster/replan.py new file mode 100644 index 0000000000..45157b72eb --- /dev/null +++ b/omlx/cluster/replan.py @@ -0,0 +1,118 @@ +# SPDX-License-Identifier: Apache-2.0 +"""One-action cluster re-plan: deactivate → re-plan → reload. + +Today a membership or budget change is a manual four-step dance: deactivate +the deployment, rebuild a plan, approve it, then reload the model. This module +is the pure/data half of collapsing that into a single ``POST +/admin/api/cluster/replan`` call (the route handler in +``omlx/cluster/routes.py`` owns the async orchestration): + +- :func:`nodes_from_deployment` / :func:`hosts_from_deployment` derive the + plan inputs for the *next* plan from the *current* approved deployment, so + a replan with no explicit overrides re-plans the same cluster the operator + already trusts. A pairing/membership inventory (the v2 discovery/pairing + modules) can later supply overrides for added or removed nodes; until then + the explicit ``nodes``/``hosts`` request fields are how membership changes + are expressed. +- :func:`summarize_deployment` produces the compact, secret-free description + of what a replan replaced. + +Derivation caveats (documented contract, not bugs): + +- ``max_weight_bytes`` / ``target_weight_bytes`` are operator preferences that + live on the plan *request*, not on the signed assignment, so a derived + replan cannot recover them and resets both to "automatic". Operators moving + the split control must pass explicit ``nodes``. +- KV reservations and per-rank context limits are recomputed by the planner + from ``target_context_tokens``, never copied forward. +""" + +from __future__ import annotations + +from typing import Any + +from .deployment import ClusterDeployment + + +def nodes_from_deployment(deployment: ClusterDeployment) -> list[dict[str, Any]]: + """Rank-ordered node-budget payloads equivalent to this deployment. + + The returned dicts match ``ClusterPlanNodeRequest`` fields. Split-control + preferences (``max_weight_bytes`` / ``target_weight_bytes``) are not + recoverable from a signed plan and are reset to automatic. + """ + + nodes: list[dict[str, Any]] = [] + for assignment in sorted(deployment.assignments, key=lambda item: item.rank): + nodes.append( + { + "node_id": assignment.node_id, + "capacity_bytes": assignment.capacity_bytes, + "reserve_bytes": assignment.reserve_bytes, + "manual_memory_limit": assignment.manual_memory_limit, + "role": assignment.role or "headless", + "memory_guard_tier": assignment.memory_guard_tier, + } + ) + return nodes + + +def hosts_from_deployment(deployment: ClusterDeployment) -> list[dict[str, Any]]: + """Rank-ordered host payloads equivalent to this deployment's hostfile.""" + + hosts: list[dict[str, Any]] = [] + for host in deployment.hosts: + payload: dict[str, Any] = { + "node_id": host.node_id, + "ssh": host.ssh, + "ips": list(host.ips), + "rdma": [ + list(path) if isinstance(path, tuple) else path + for path in host.rdma + ], + } + if host.python_executable: + payload["python_executable"] = host.python_executable + hosts.append(payload) + return hosts + + +def summarize_deployment(deployment: ClusterDeployment) -> dict[str, Any]: + """What a replan is replacing, in the terms the plan view displays.""" + + return { + "deployment_id": deployment.deployment_id, + "model": deployment.model, + "backend": deployment.backend, + "world_size": deployment.world_size, + "plan_hash": deployment.plan_hash, + "target_context_tokens": deployment.target_context_tokens, + "assignments": [ + { + "rank": assignment.rank, + "node_id": assignment.node_id, + "start_layer": assignment.start_layer, + "end_layer": assignment.end_layer, + "planned_weight_bytes": assignment.planned_weight_bytes, + "kv_cache_bytes": assignment.kv_cache_bytes, + } + for assignment in sorted( + deployment.assignments, key=lambda item: item.rank + ) + ], + } + + +def placement_view(deployment: ClusterDeployment) -> dict[str, Any]: + """The ``plan``-shaped assignment list used for placement diffs. + + ``_placement_rows`` in the routes module reads ``plan["assignments"]``; + this rebuilds that shape from a persisted deployment so a replan can diff + the running placement against the proposed one with the exact same code. + """ + + return { + "assignments": [ + assignment.to_dict() for assignment in deployment.assignments + ] + } diff --git a/omlx/cluster/routes.py b/omlx/cluster/routes.py index 1f4a395b8d..7b802254b7 100644 --- a/omlx/cluster/routes.py +++ b/omlx/cluster/routes.py @@ -96,6 +96,12 @@ ) from .probe import collect_cluster_status from .registry import get_cluster_registry +from .replan import ( + hosts_from_deployment, + nodes_from_deployment, + placement_view, + summarize_deployment, +) from .runtime import read_runtime_markers from .staging import ( DEFAULT_REMOTE_PYTHON, @@ -3181,9 +3187,20 @@ async def cluster_deployments(): raise HTTPException(status_code=503, detail=str(exc)) from exc -@router.post("/deployments") -async def activate_cluster_deployment(request: ClusterDeploymentRequest): - """Recompute, preflight, eagerly load, and prove one distributed model.""" +async def _activate_and_report( + request: ClusterDeploymentRequest, +) -> dict[str, Any]: + """Recompute, preflight, eagerly load, and prove one distributed model. + + This is the single activation pipeline behind both ``POST /deployments`` + (explicit approval of a previewed plan) and the approve phase of + ``POST /replan`` (one-action deactivate → re-plan → reload). The + deactivate half of a replan is exactly what this pipeline already does: + ``pool.prepare_cluster_reload`` unloads the resident engine under the + pool lock — quiescence-gated, and for distributed engines the supervisor's + *verified* teardown is the memory barrier — before the registry swap and + the eager reload below. + """ plan_changes: dict[str, Any] = { "changed": False, @@ -3459,6 +3476,201 @@ async def activate_cluster_deployment(request: ClusterDeploymentRequest): } +@router.post("/deployments") +async def activate_cluster_deployment(request: ClusterDeploymentRequest): + """Recompute, preflight, eagerly load, and prove one distributed model.""" + + return await _activate_and_report(request) + + +class ClusterReplanRequest(BaseModel): + """One-action deactivate → re-plan → reload for a clustered model. + + With no ``approved_placement`` this is a dry run: it renders the plan the + one-action call would launch, signed, with a diff against the running + placement. Posting that signature back performs the whole dance at once. + + ``nodes``/``hosts``/``backend`` default to the current deployment's, so a + budget-only or context-only change needs no host details; a membership + change (a node joining or leaving the model) is expressed by posting the + new explicit ``nodes`` + ``hosts`` lists. + """ + + deployment_id: str | None = Field(default=None, max_length=128) + model_path: str | None = Field(default=None, max_length=4096) + model_source: str | None = Field(default=None, max_length=255) + model_source_python: str | None = Field(default=None, max_length=4096) + backend: Literal["ring", "jaccl", "jaccl-ring"] | None = None + nodes: list[ClusterPlanNodeRequest] | None = Field( + default=None, min_length=2, max_length=64 + ) + hosts: list[ClusterHostRequest] | None = Field( + default=None, min_length=2, max_length=64 + ) + execution_profile: Literal["interactive", "balanced", "throughput"] = ( + "balanced" + ) + auto_tune: bool = False + sampling_rank_only: bool = True + async_overlap: bool = True + cache_affinity: bool = True + max_kv_size: int | None = Field(default=None, gt=0) + ring_connections_per_ip: int | None = Field(default=None, ge=1, le=32) + tensor_parallel_size: int = Field(default=1, ge=1, le=64) + target_context_tokens: int = Field(default=8192, ge=1, le=1_048_576) + approved_placement: str | None = Field(default=None, min_length=16, max_length=64) + + +_REPLAN_STEPS = ( + "deactivate (quiescence-gated unload with verified teardown)", + "re-plan (recomputed server-side and pinned by signature)", + "reload (eager distributed load with readiness canary)", +) + + +@router.post("/replan") +async def replan_cluster_deployment(request: ClusterReplanRequest): + """Collapse deactivate → re-plan → reload into one action. + + The engine-pool quiescence gate (``prepare_cluster_reload``) refuses to + interrupt in-flight requests, and the distributed supervisor's verified + teardown is the memory barrier between the old world and the new one: if + teardown cannot be proven, the old registry record stays and the error + says what survived. + """ + + try: + registry = get_cluster_registry() + except RuntimeError as exc: + raise HTTPException(status_code=503, detail=str(exc)) from exc + + current: ClusterDeployment | None = None + if request.deployment_id: + current = await asyncio.to_thread(registry.get, request.deployment_id) + if current is None: + raise HTTPException( + status_code=404, detail="cluster deployment not found" + ) + elif request.model_path: + current = await asyncio.to_thread( + registry.get_for_model, request.model_path + ) + + if current is None and not ( + request.model_path and request.nodes and request.hosts + ): + raise HTTPException( + status_code=400, + detail=( + "replan needs an existing deployment (deployment_id or a " + "model_path with a registered deployment) or an explicit " + "model_path together with nodes and hosts" + ), + ) + + derived: dict[str, bool] = {"nodes": False, "hosts": False, "backend": False} + nodes = request.nodes + if nodes is None: + if current is None: + raise HTTPException(status_code=400, detail="nodes are required") + nodes = [ + ClusterPlanNodeRequest(**payload) + for payload in nodes_from_deployment(current) + ] + derived["nodes"] = True + hosts = request.hosts + if hosts is None: + if current is None: + raise HTTPException(status_code=400, detail="hosts are required") + hosts = [ + ClusterHostRequest(**payload) + for payload in hosts_from_deployment(current) + ] + derived["hosts"] = True + backend = request.backend + if backend is None: + if current is None: + raise HTTPException(status_code=400, detail="backend is required") + backend = current.backend + derived["backend"] = True + try: + _validate_cluster_hosts(hosts) + effective = ClusterDeploymentRequest( + deployment_id=request.deployment_id, + model_path=(request.model_path or (current.model if current else "")), + model_source=request.model_source, + model_source_python=request.model_source_python, + backend=backend, + nodes=nodes, + hosts=hosts, + execution_profile=request.execution_profile, + auto_tune=request.auto_tune, + sampling_rank_only=request.sampling_rank_only, + async_overlap=request.async_overlap, + cache_affinity=request.cache_affinity, + max_kv_size=request.max_kv_size, + ring_connections_per_ip=request.ring_connections_per_ip, + tensor_parallel_size=request.tensor_parallel_size, + target_context_tokens=request.target_context_tokens, + # Not consulted by planning; activation re-checks the real one + # below. Preview callers do not have a signature yet. + approved_placement=request.approved_placement or ("0" * 16), + ) + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + + try: + deployment, plan = await asyncio.to_thread(_create_deployment, effective) + except (OSError, PlanningError, ValueError) as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + + signed_plan = _plan_with_signature(plan) + changes = ( + _plan_changes(placement_view(current), plan) + if current is not None + else None + ) + + if request.approved_placement is None: + return { + "ok": True, + "mode": "preview", + "steps": list(_REPLAN_STEPS), + "derived": derived, + "current": ( + summarize_deployment(current) if current is not None else None + ), + "changes": changes, + "deployment_id": deployment.deployment_id, + "backend": deployment.backend, + "plan": signed_plan, + } + + if request.approved_placement.strip() != signed_plan["placement_signature"]: + raise HTTPException( + status_code=409, + detail=( + "This is not the plan the replan preview showed — the budgets, " + "roles or layer split changed in between. Preview again and " + f"approve what it shows. As posted, this request would place: " + f"{_describe_placement(plan)}." + ), + ) + + result = await _activate_and_report(effective) + return result | { + "mode": "applied", + "replan": { + "steps": list(_REPLAN_STEPS), + "derived": derived, + "previous": ( + summarize_deployment(current) if current is not None else None + ), + "changes": changes, + }, + } + + @router.delete("/deployments/{deployment_id}") async def deactivate_cluster_deployment(deployment_id: str): """Stop the resident cluster, then disable future distributed loads.""" From eb92cf13e6c64c4caa0023284f3b40ac48d1bdc6 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Tue, 18 Aug 2026 17:01:08 -0700 Subject: [PATCH 123/132] =?UTF-8?q?test:=20replan=20endpoint=20=E2=80=94?= =?UTF-8?q?=20preview/apply=20dance,=20busy=20refusal,=20derivation,=20N-n?= =?UTF-8?q?ode=20membership=20change?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/test_cluster_replan.py | 407 +++++++++++++++++++++++++++++++++++ 1 file changed, 407 insertions(+) create mode 100644 tests/test_cluster_replan.py diff --git a/tests/test_cluster_replan.py b/tests/test_cluster_replan.py new file mode 100644 index 0000000000..c149d56037 --- /dev/null +++ b/tests/test_cluster_replan.py @@ -0,0 +1,407 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Tests for the one-action cluster replan endpoint and its derivation helpers. + +Everything is offline: the engine pool, peer liveness, preflight, and model +layout inspection are doubled, and the registry lives in a tmp_path. +""" + +from types import SimpleNamespace + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from omlx.cluster import routes +from omlx.cluster.deployment import ClusterDeployment, ClusterHost +from omlx.cluster.planner import ModelLayout +from omlx.cluster.registry import configure_cluster_registry +from omlx.cluster.replan import ( + hosts_from_deployment, + nodes_from_deployment, + placement_view, + summarize_deployment, +) + +GIB = 1024**3 + + +def _client() -> TestClient: + app = FastAPI() + app.include_router(routes.router) + return TestClient(app) + + +def _layout(path): + return ModelLayout( + source=path, + fixed_weight_bytes=1, + layer_weight_bytes=(10, 10, 10, 10), + supports_pipeline=True, + ) + + +def _install_layout(monkeypatch): + monkeypatch.setattr(routes, "inspect_safetensors_layout", _layout) + monkeypatch.setattr( + routes, + "preflight_remote_hosts", + lambda deployment: [ + {"rank": rank, "node_id": host.node_id} + for rank, host in enumerate(deployment.hosts) + ], + ) + # Route tests establish peer reachability out of band; never let the + # synthetic hosts reach the real SSH liveness probe. + monkeypatch.setattr(routes, "check_peers", lambda *args, **kwargs: ()) + + +def _deployment_payload(model_path, *, capacity_large=100, capacity_small=60): + return { + "model_path": str(model_path), + "backend": "ring", + # The synthetic probe is the real network thing; replan coverage uses + # the memory-only path. + "auto_tune": False, + "nodes": [ + {"node_id": "large", "capacity_bytes": capacity_large, "reserve_bytes": 10}, + {"node_id": "small", "capacity_bytes": capacity_small, "reserve_bytes": 10}, + ], + "hosts": [ + {"node_id": "large", "ssh": "127.0.0.1", "ips": ["192.168.5.1"]}, + {"node_id": "small", "ssh": "studio.local", "ips": ["192.168.5.2"]}, + ], + } + + +def _approval_for(payload): + plan = routes._create_cluster_plan( + routes.ClusterPlanRequest( + model_path=payload["model_path"], + nodes=payload["nodes"], + execution_profile=payload.get("execution_profile", "balanced"), + tensor_parallel_size=payload.get("tensor_parallel_size", 1), + target_context_tokens=payload.get("target_context_tokens", 8192), + ) + ) + return routes._placement_signature(plan.to_dict()) + + +class _ReadyEngine: + def __init__(self, deployment): + self.deployment = deployment + + async def generate(self, *_args, **_kwargs): + return SimpleNamespace(completion_tokens=1) + + def cluster_status(self): + return {"phase": "ready", "ranks": []} + + +class _RecordingPool: + """Engine-pool double that records the reload dance.""" + + def __init__(self, model_path): + self.model_path = str(model_path) + self.model_id = "public-model" + self.entry = SimpleNamespace(engine=None) + self.reloads = 0 + + def resolve_cluster_model_id(self, model_path): + assert model_path == self.model_path + return self.model_id + + def register_cluster_model(self, model_path, *, estimated_size): + assert model_path == self.model_path + assert estimated_size > 0 + return self.model_id, True + + def unregister_cluster_model(self, model_id): + assert model_id == self.model_id + return True + + def get_entry(self, model_id): + assert model_id == self.model_id + return self.entry + + async def prepare_cluster_reload(self, model_id): + assert model_id == self.model_id + self.reloads += 1 + self.entry.engine = None + + async def get_engine(self, model_id): + assert model_id == self.model_id + deployment = routes.get_cluster_registry().get_for_model(self.model_path) + self.entry.engine = _ReadyEngine(deployment) + return self.entry.engine + + +class _BusyPool(_RecordingPool): + def __init__(self, model_path): + super().__init__(model_path) + self.busy = False + + async def prepare_cluster_reload(self, model_id): + if self.busy: + from omlx.exceptions import ModelBusyError + + raise ModelBusyError(self.model_id, "replan the distributed cluster") + await super().prepare_cluster_reload(model_id) + + +@pytest.fixture() +def active_deployment(tmp_path, monkeypatch): + """Activate a two-node ring deployment and return its context.""" + + configure_cluster_registry(tmp_path) + model_path = tmp_path / "models" / "nemotron" + model_path.mkdir(parents=True) + _install_layout(monkeypatch) + pool = _RecordingPool(model_path) + monkeypatch.setattr(routes, "_get_engine_pool", lambda: pool) + + body = _deployment_payload(model_path) + body["approved_placement"] = _approval_for(body) + response = _client().post("/admin/api/cluster/deployments", json=body) + assert response.status_code == 200, response.json() + return SimpleNamespace( + model_path=model_path, + pool=pool, + deployment=response.json()["deployment"], + ) + + +def test_nodes_from_deployment_round_trip(active_deployment): + deployment = ClusterDeployment.from_dict(active_deployment.deployment) + + nodes = nodes_from_deployment(deployment) + + assert [node["node_id"] for node in nodes] == ["large", "small"] + assert nodes[0]["capacity_bytes"] == 100 + assert nodes[0]["reserve_bytes"] == 10 + assert nodes[0]["role"] == "headless" + # Split-control preferences are not recoverable from a signed plan. + assert "max_weight_bytes" not in nodes[0] + assert "target_weight_bytes" not in nodes[0] + + +def test_hosts_from_deployment_round_trip(active_deployment): + deployment = ClusterDeployment.from_dict(active_deployment.deployment) + + hosts = hosts_from_deployment(deployment) + + assert hosts[0]["ssh"] == "127.0.0.1" + assert hosts[1]["ssh"] == "studio.local" + assert hosts[1]["ips"] == ["192.168.5.2"] + + +def test_summarize_and_placement_view(active_deployment): + deployment = ClusterDeployment.from_dict(active_deployment.deployment) + + summary = summarize_deployment(deployment) + assert summary["deployment_id"] == deployment.deployment_id + assert summary["world_size"] == 2 + assert summary["backend"] == "ring" + assert len(summary["assignments"]) == 2 + + # The placement view must feed the same diff machinery a plan dict does. + signature = routes._placement_signature(placement_view(deployment)) + assert len(signature) == 16 + + +def test_replan_preview_derives_current_cluster(active_deployment): + response = _client().post( + "/admin/api/cluster/replan", + json={"deployment_id": active_deployment.deployment["deployment_id"]}, + ) + + assert response.status_code == 200, response.json() + payload = response.json() + assert payload["mode"] == "preview" + assert payload["derived"] == {"nodes": True, "hosts": True, "backend": True} + assert payload["current"]["world_size"] == 2 + assert payload["changes"]["changed"] is False + assert len(payload["steps"]) == 3 + assert payload["plan"]["placement_signature"] + # A preview must not touch the pool at all. + assert active_deployment.pool.reloads == 1 # only the initial activation + + +def test_replan_preview_detects_changed_split(active_deployment): + response = _client().post( + "/admin/api/cluster/replan", + json={ + "deployment_id": active_deployment.deployment["deployment_id"], + "nodes": [ + {"node_id": "large", "capacity_bytes": 100, "reserve_bytes": 10}, + # A bigger reserve on the small node moves layers to the large one. + {"node_id": "small", "capacity_bytes": 60, "reserve_bytes": 40}, + ], + }, + ) + + assert response.status_code == 200, response.json() + payload = response.json() + assert payload["derived"]["nodes"] is False + assert payload["derived"]["hosts"] is True + assert payload["changes"]["changed"] is True + + +def test_replan_applied_runs_full_dance(active_deployment): + preview = _client().post( + "/admin/api/cluster/replan", + json={ + "deployment_id": active_deployment.deployment["deployment_id"], + "target_context_tokens": 16384, + }, + ).json() + + response = _client().post( + "/admin/api/cluster/replan", + json={ + "deployment_id": active_deployment.deployment["deployment_id"], + "target_context_tokens": 16384, + "approved_placement": preview["plan"]["placement_signature"], + }, + ) + + assert response.status_code == 200, response.json() + payload = response.json() + assert payload["mode"] == "applied" + assert payload["readiness"]["canary_passed"] is True + assert payload["replan"]["previous"]["deployment_id"] == ( + active_deployment.deployment["deployment_id"] + ) + # One reload for the initial activation, one for the replan. + assert active_deployment.pool.reloads == 2 + engine = active_deployment.pool.entry.engine + assert engine.deployment.target_context_tokens == 16384 + + +def test_replan_rejects_a_stale_approval(active_deployment): + _client().post( + "/admin/api/cluster/replan", + json={"deployment_id": active_deployment.deployment["deployment_id"]}, + ) + + response = _client().post( + "/admin/api/cluster/replan", + json={ + "deployment_id": active_deployment.deployment["deployment_id"], + "target_context_tokens": 4096, + "approved_placement": "f" * 16, + }, + ) + + assert response.status_code == 409 + assert "not the plan" in response.json()["detail"] + assert active_deployment.pool.reloads == 1 + + +def test_replan_refuses_to_interrupt_active_requests(tmp_path, monkeypatch): + configure_cluster_registry(tmp_path) + model_path = tmp_path / "models" / "nemotron" + model_path.mkdir(parents=True) + _install_layout(monkeypatch) + pool = _BusyPool(model_path) + monkeypatch.setattr(routes, "_get_engine_pool", lambda: pool) + + body = _deployment_payload(model_path) + body["approved_placement"] = _approval_for(body) + response = _client().post("/admin/api/cluster/deployments", json=body) + assert response.status_code == 200, response.json() + deployment_id = response.json()["deployment"]["deployment_id"] + pool.busy = True + + preview = _client().post( + "/admin/api/cluster/replan", json={"deployment_id": deployment_id} + ).json() + response = _client().post( + "/admin/api/cluster/replan", + json={ + "deployment_id": deployment_id, + "approved_placement": preview["plan"]["placement_signature"], + }, + ) + + assert response.status_code == 409 + assert "serving a request" in response.json()["detail"] + # The old deployment must survive a refused replan. + listed = _client().get("/admin/api/cluster/deployments") + assert listed.json()["deployments"][0]["deployment_id"] == deployment_id + + +def test_replan_unknown_deployment_is_404(tmp_path, monkeypatch): + configure_cluster_registry(tmp_path) + _install_layout(monkeypatch) + monkeypatch.setattr( + routes, "_get_engine_pool", lambda: _RecordingPool(tmp_path / "m") + ) + + response = _client().post( + "/admin/api/cluster/replan", json={"deployment_id": "nope"} + ) + + assert response.status_code == 404 + + +def test_replan_without_context_requires_explicit_cluster(tmp_path, monkeypatch): + configure_cluster_registry(tmp_path) + _install_layout(monkeypatch) + monkeypatch.setattr( + routes, "_get_engine_pool", lambda: _RecordingPool(tmp_path / "m") + ) + + response = _client().post( + "/admin/api/cluster/replan", + json={"model_path": "/models/never-deployed"}, + ) + + assert response.status_code == 400 + assert "nodes and hosts" in response.json()["detail"] + + +def test_replan_membership_change_adds_a_node(active_deployment): + """N-node replan: explicit nodes/hosts express the membership change.""" + + model_path = active_deployment.model_path + nodes = [ + {"node_id": "large", "capacity_bytes": 100, "reserve_bytes": 10}, + {"node_id": "small", "capacity_bytes": 60, "reserve_bytes": 10}, + {"node_id": "mini", "capacity_bytes": 50, "reserve_bytes": 10}, + ] + hosts = [ + {"node_id": "large", "ssh": "127.0.0.1", "ips": ["192.168.5.1"]}, + {"node_id": "small", "ssh": "studio.local", "ips": ["192.168.5.2"]}, + {"node_id": "mini", "ssh": "mini.local", "ips": ["192.168.5.3"]}, + ] + preview = _client().post( + "/admin/api/cluster/replan", + json={ + "deployment_id": active_deployment.deployment["deployment_id"], + "nodes": nodes, + "hosts": hosts, + }, + ) + assert preview.status_code == 200, preview.json() + assert preview.json()["plan"]["assignments"][2]["node_id"] == "mini" + + response = _client().post( + "/admin/api/cluster/replan", + json={ + "deployment_id": active_deployment.deployment["deployment_id"], + "nodes": nodes, + "hosts": hosts, + "approved_placement": preview.json()["plan"]["placement_signature"], + }, + ) + + assert response.status_code == 200, response.json() + payload = response.json() + assert payload["deployment"]["world_size"] if "world_size" in payload["deployment"] else True + assert len(payload["deployment"]["assignments"]) == 3 + assert payload["replan"]["previous"]["world_size"] == 2 + ranks = sorted( + (item["rank"], item["node_id"]) + for item in payload["deployment"]["assignments"] + ) + assert ranks == [(0, "large"), (1, "small"), (2, "mini")] From c6a694d21a95a4f06ea080e78c75f3d4ff294036 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Tue, 18 Aug 2026 17:01:34 -0700 Subject: [PATCH 124/132] =?UTF-8?q?test:=20fix=20busy-pool=20replan=20test?= =?UTF-8?q?=20=E2=80=94=20an=20unchanged=20plan=20short-circuits=20the=20r?= =?UTF-8?q?eload?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/test_cluster_replan.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/tests/test_cluster_replan.py b/tests/test_cluster_replan.py index c149d56037..feec43c904 100644 --- a/tests/test_cluster_replan.py +++ b/tests/test_cluster_replan.py @@ -313,12 +313,17 @@ def test_replan_refuses_to_interrupt_active_requests(tmp_path, monkeypatch): pool.busy = True preview = _client().post( - "/admin/api/cluster/replan", json={"deployment_id": deployment_id} + "/admin/api/cluster/replan", + json={ + "deployment_id": deployment_id, + "target_context_tokens": 16384, + }, ).json() response = _client().post( "/admin/api/cluster/replan", json={ "deployment_id": deployment_id, + "target_context_tokens": 16384, "approved_placement": preview["plan"]["placement_signature"], }, ) From a7ad92824035d0b3c6bf346fb36ddfc164c2f901 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Tue, 18 Aug 2026 18:11:00 -0700 Subject: [PATCH 125/132] cluster: thread path_map through the replan endpoint Agent E flagged the seam: ClusterReplanRequest had no path_map and the replan derivation dropped the current deployment's per-node paths, silently reverting a heterogeneous-path cluster to same-path resolution. Add path_map to ClusterReplanRequest, derive it from the current deployment when not posted (tracked in the 'derived' map), and pass it into the effective ClusterDeploymentRequest. Explicit override (including an empty map) wins. Tests updated + carry-forward coverage added. --- omlx/cluster/routes.py | 20 ++++++++++++-- tests/test_cluster_replan.py | 53 +++++++++++++++++++++++++++++++++++- 2 files changed, 70 insertions(+), 3 deletions(-) diff --git a/omlx/cluster/routes.py b/omlx/cluster/routes.py index 7b802254b7..bf49c37cc4 100644 --- a/omlx/cluster/routes.py +++ b/omlx/cluster/routes.py @@ -3493,7 +3493,9 @@ class ClusterReplanRequest(BaseModel): ``nodes``/``hosts``/``backend`` default to the current deployment's, so a budget-only or context-only change needs no host details; a membership change (a node joining or leaving the model) is expressed by posting the - new explicit ``nodes`` + ``hosts`` lists. + new explicit ``nodes`` + ``hosts`` lists. ``path_map`` likewise defaults + to the current deployment's per-node paths so a replan does not silently + revert a heterogeneous-path cluster to same-path resolution. """ deployment_id: str | None = Field(default=None, max_length=128) @@ -3518,6 +3520,7 @@ class ClusterReplanRequest(BaseModel): ring_connections_per_ip: int | None = Field(default=None, ge=1, le=32) tensor_parallel_size: int = Field(default=1, ge=1, le=64) target_context_tokens: int = Field(default=8192, ge=1, le=1_048_576) + path_map: dict[str, str] | None = Field(default=None, max_length=64) approved_placement: str | None = Field(default=None, min_length=16, max_length=64) @@ -3568,7 +3571,12 @@ async def replan_cluster_deployment(request: ClusterReplanRequest): ), ) - derived: dict[str, bool] = {"nodes": False, "hosts": False, "backend": False} + derived: dict[str, bool] = { + "nodes": False, + "hosts": False, + "backend": False, + "path_map": False, + } nodes = request.nodes if nodes is None: if current is None: @@ -3593,6 +3601,13 @@ async def replan_cluster_deployment(request: ClusterReplanRequest): raise HTTPException(status_code=400, detail="backend is required") backend = current.backend derived["backend"] = True + path_map = request.path_map + if path_map is None and current is not None and current.path_map: + # Per-node paths are part of the deployment contract: a replan that + # dropped them would silently revert workers to the coordinator's + # shared path. Carry them forward unless the caller overrides. + path_map = dict(current.path_map) + derived["path_map"] = True try: _validate_cluster_hosts(hosts) effective = ClusterDeploymentRequest( @@ -3612,6 +3627,7 @@ async def replan_cluster_deployment(request: ClusterReplanRequest): ring_connections_per_ip=request.ring_connections_per_ip, tensor_parallel_size=request.tensor_parallel_size, target_context_tokens=request.target_context_tokens, + path_map=path_map, # Not consulted by planning; activation re-checks the real one # below. Preview callers do not have a signature yet. approved_placement=request.approved_placement or ("0" * 16), diff --git a/tests/test_cluster_replan.py b/tests/test_cluster_replan.py index feec43c904..020b20d21d 100644 --- a/tests/test_cluster_replan.py +++ b/tests/test_cluster_replan.py @@ -217,7 +217,12 @@ def test_replan_preview_derives_current_cluster(active_deployment): assert response.status_code == 200, response.json() payload = response.json() assert payload["mode"] == "preview" - assert payload["derived"] == {"nodes": True, "hosts": True, "backend": True} + assert payload["derived"] == { + "nodes": True, + "hosts": True, + "backend": True, + "path_map": False, + } assert payload["current"]["world_size"] == 2 assert payload["changes"]["changed"] is False assert len(payload["steps"]) == 3 @@ -226,6 +231,52 @@ def test_replan_preview_derives_current_cluster(active_deployment): assert active_deployment.pool.reloads == 1 # only the initial activation +def test_replan_carries_path_map_forward(tmp_path, monkeypatch): + """A replan of a per-node-path deployment must not revert to same-path.""" + + configure_cluster_registry(tmp_path) + model_path = tmp_path / "models" / "nemotron" + model_path.mkdir(parents=True) + _install_layout(monkeypatch) + pool = _RecordingPool(model_path) + monkeypatch.setattr(routes, "_get_engine_pool", lambda: pool) + + path_map = { + "large": str(model_path), + "small": "/Volumes/shared/nemotron", + } + body = _deployment_payload(model_path) + body["path_map"] = path_map + plan = routes._create_cluster_plan( + routes.ClusterPlanRequest( + model_path=body["model_path"], + nodes=body["nodes"], + path_map=path_map, + ) + ) + body["approved_placement"] = routes._placement_signature(plan.to_dict()) + response = _client().post("/admin/api/cluster/deployments", json=body) + assert response.status_code == 200, response.json() + deployment_id = response.json()["deployment"]["deployment_id"] + assert response.json()["deployment"]["path_map"] == path_map + + preview = _client().post( + "/admin/api/cluster/replan", json={"deployment_id": deployment_id} + ) + assert preview.status_code == 200, preview.json() + payload = preview.json() + assert payload["derived"]["path_map"] is True + assert payload["plan"]["path_map"] == path_map + + # An explicit override wins over the carried-forward map. + override = _client().post( + "/admin/api/cluster/replan", + json={"deployment_id": deployment_id, "path_map": {}}, + ) + assert override.status_code == 200, override.json() + assert override.json()["derived"]["path_map"] is False + + def test_replan_preview_detects_changed_split(active_deployment): response = _client().post( "/admin/api/cluster/replan", From d9ee5840431a5bd6b44852c8753ebde3120aef77 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Sat, 22 Aug 2026 12:43:04 -0700 Subject: [PATCH 126/132] Preserve measured rank speeds across replans --- omlx/cluster/replan.py | 29 +++++++++++++++++++---------- tests/test_cluster_replan.py | 26 ++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 10 deletions(-) diff --git a/omlx/cluster/replan.py b/omlx/cluster/replan.py index 45157b72eb..c9dca6986a 100644 --- a/omlx/cluster/replan.py +++ b/omlx/cluster/replan.py @@ -25,6 +25,9 @@ the split control must pass explicit ``nodes``. - KV reservations and per-rank context limits are recomputed by the planner from ``target_context_tokens``, never copied forward. +- Signed performance profiles *are* copied forward. Dropping them silently + turns a heterogeneous tensor deployment back into an equal split on every + replan, even when the previous activation already measured both ranks. """ from __future__ import annotations @@ -42,18 +45,24 @@ def nodes_from_deployment(deployment: ClusterDeployment) -> list[dict[str, Any]] recoverable from a signed plan and are reset to automatic. """ + profiles = { + (profile.rank, profile.node_id): profile + for profile in deployment.performance_profiles + } nodes: list[dict[str, Any]] = [] for assignment in sorted(deployment.assignments, key=lambda item: item.rank): - nodes.append( - { - "node_id": assignment.node_id, - "capacity_bytes": assignment.capacity_bytes, - "reserve_bytes": assignment.reserve_bytes, - "manual_memory_limit": assignment.manual_memory_limit, - "role": assignment.role or "headless", - "memory_guard_tier": assignment.memory_guard_tier, - } - ) + payload: dict[str, Any] = { + "node_id": assignment.node_id, + "capacity_bytes": assignment.capacity_bytes, + "reserve_bytes": assignment.reserve_bytes, + "manual_memory_limit": assignment.manual_memory_limit, + "role": assignment.role or "headless", + "memory_guard_tier": assignment.memory_guard_tier, + } + profile = profiles.get((assignment.rank, assignment.node_id)) + if profile is not None: + payload["performance"] = profile.to_dict() + nodes.append(payload) return nodes diff --git a/tests/test_cluster_replan.py b/tests/test_cluster_replan.py index 020b20d21d..3e37934101 100644 --- a/tests/test_cluster_replan.py +++ b/tests/test_cluster_replan.py @@ -5,6 +5,7 @@ layout inspection are doubled, and the registry lives in a tmp_path. """ +from dataclasses import replace from types import SimpleNamespace import pytest @@ -14,6 +15,7 @@ from omlx.cluster import routes from omlx.cluster.deployment import ClusterDeployment, ClusterHost from omlx.cluster.planner import ModelLayout +from omlx.cluster.performance import NodePerformanceProfile from omlx.cluster.registry import configure_cluster_registry from omlx.cluster.replan import ( hosts_from_deployment, @@ -184,6 +186,30 @@ def test_nodes_from_deployment_round_trip(active_deployment): assert "target_weight_bytes" not in nodes[0] +def test_nodes_from_deployment_preserves_signed_performance(active_deployment): + deployment = ClusterDeployment.from_dict(active_deployment.deployment) + profiles = tuple( + NodePerformanceProfile( + node_id=assignment.node_id, + rank=assignment.rank, + decode_weight_bytes_per_second=100.0 - 40.0 * assignment.rank, + prefill_weight_bytes_per_second=90.0 - 30.0 * assignment.rank, + collective_latency_seconds=0.00003, + collective_bandwidth_bytes_per_second=6.2e9, + backend="ring", + measured_at="2026-08-22T00:00:00+00:00", + samples=5, + ) + for assignment in deployment.assignments + ) + deployment = replace(deployment, performance_profiles=profiles) + + nodes = nodes_from_deployment(deployment) + + assert nodes[0]["performance"] == profiles[0].to_dict() + assert nodes[1]["performance"] == profiles[1].to_dict() + + def test_hosts_from_deployment_round_trip(active_deployment): deployment = ClusterDeployment.from_dict(active_deployment.deployment) From 9f490c0ef57a070dcc3a5cce77fc86f32b62f737 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Sat, 22 Aug 2026 22:19:55 -0700 Subject: [PATCH 127/132] Preserve TP topology across cluster replans --- omlx/cluster/routes.py | 22 ++++++++++++++++++---- tests/test_cluster_replan.py | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 4 deletions(-) diff --git a/omlx/cluster/routes.py b/omlx/cluster/routes.py index bf49c37cc4..4e82ee7264 100644 --- a/omlx/cluster/routes.py +++ b/omlx/cluster/routes.py @@ -3518,8 +3518,10 @@ class ClusterReplanRequest(BaseModel): cache_affinity: bool = True max_kv_size: int | None = Field(default=None, gt=0) ring_connections_per_ip: int | None = Field(default=None, ge=1, le=32) - tensor_parallel_size: int = Field(default=1, ge=1, le=64) - target_context_tokens: int = Field(default=8192, ge=1, le=1_048_576) + tensor_parallel_size: int | None = Field(default=None, ge=1, le=64) + target_context_tokens: int | None = Field( + default=None, ge=1, le=1_048_576 + ) path_map: dict[str, str] | None = Field(default=None, max_length=64) approved_placement: str | None = Field(default=None, min_length=16, max_length=64) @@ -3625,8 +3627,20 @@ async def replan_cluster_deployment(request: ClusterReplanRequest): cache_affinity=request.cache_affinity, max_kv_size=request.max_kv_size, ring_connections_per_ip=request.ring_connections_per_ip, - tensor_parallel_size=request.tensor_parallel_size, - target_context_tokens=request.target_context_tokens, + tensor_parallel_size=( + request.tensor_parallel_size + if request.tensor_parallel_size is not None + else current.tensor_parallel_size + if current is not None + else 1 + ), + target_context_tokens=( + request.target_context_tokens + if request.target_context_tokens is not None + else current.target_context_tokens + if current is not None + else 8192 + ), path_map=path_map, # Not consulted by planning; activation re-checks the real one # below. Preview callers do not have a signature yet. diff --git a/tests/test_cluster_replan.py b/tests/test_cluster_replan.py index 3e37934101..cf0539222d 100644 --- a/tests/test_cluster_replan.py +++ b/tests/test_cluster_replan.py @@ -257,6 +257,42 @@ def test_replan_preview_derives_current_cluster(active_deployment): assert active_deployment.pool.reloads == 1 # only the initial activation +def test_replan_inherits_tensor_parallelism_and_context(tmp_path, monkeypatch): + configure_cluster_registry(tmp_path) + model_path = tmp_path / "models" / "nemotron" + model_path.mkdir(parents=True) + _install_layout(monkeypatch) + monkeypatch.setattr( + routes, + "inspect_safetensors_layout", + lambda path: replace( + _layout(path), + tensor_parallel_heads=2, + tensor_parallel_kv_heads=2, + tensor_parallel_divisors=(2,), + supports_tensor_parallel=True, + ), + ) + pool = _RecordingPool(model_path) + monkeypatch.setattr(routes, "_get_engine_pool", lambda: pool) + + body = _deployment_payload(model_path) + body.update(tensor_parallel_size=2, target_context_tokens=32768) + body["approved_placement"] = _approval_for(body) + activation = _client().post("/admin/api/cluster/deployments", json=body) + assert activation.status_code == 200, activation.json() + + deployment_id = activation.json()["deployment"]["deployment_id"] + preview = _client().post( + "/admin/api/cluster/replan", + json={"deployment_id": deployment_id}, + ) + + assert preview.status_code == 200, preview.json() + assert preview.json()["plan"]["tensor_parallel_size"] == 2 + assert preview.json()["plan"]["cluster"]["target_context_tokens"] == 32768 + + def test_replan_carries_path_map_forward(tmp_path, monkeypatch): """A replan of a per-node-path deployment must not revert to same-path.""" From fabe48f4ca8e67a64a4eae23299d3593d35cb822 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Fri, 21 Aug 2026 18:21:01 -0700 Subject: [PATCH 128/132] feat(cluster): recommend tensor on known-fast links in catalogue MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The catalogue tie-break preferred pipeline at equal width because it survives slow links. When the paired registry shows every requested peer reachable over JACCL/Thunderbolt RDMA, tensor parallelism is the better recommendation — it splits per-token compute across the group. - _splits/assess_model/catalogue_for_cluster gain prefer_tensor (default False: API behavior unchanged for unknown links) - catalogue endpoint derives it from the paired device registry: every non-self requested node must be paired with jaccl/thunderbolt caps; unknown or unpaired peers fail closed to pipeline - 4 new tests; 33 catalogue + 1702 cluster/model tests green --- omlx/cluster/catalogue.py | 35 +++++++++-- omlx/cluster/routes.py | 41 ++++++++++++- tests/test_cluster_catalogue.py | 105 ++++++++++++++++++++++++++++++++ 3 files changed, 175 insertions(+), 6 deletions(-) diff --git a/omlx/cluster/catalogue.py b/omlx/cluster/catalogue.py index 4aae39864e..42e513c334 100644 --- a/omlx/cluster/catalogue.py +++ b/omlx/cluster/catalogue.py @@ -175,12 +175,17 @@ def _splits( *, tensor_parallel_ok: bool, pipeline_ok: bool = True, + prefer_tensor: bool = False, ) -> tuple[tuple[int, int], ...]: """Every (tensor_parallel_size, pipeline_stages) this cluster can form. - Ordered fewest-nodes-first, then pipeline before tensor parallelism at - equal width: pipeline loads faster, uses less memory, and survives a - slow link, so it is the better answer when both fit. + Ordered fewest-nodes-first. At equal width the default is pipeline before + tensor parallelism: pipeline loads faster, uses less memory, and survives + a slow link, so it is the better answer when both fit and nothing is + known about the link. ``prefer_tensor`` flips the tie-break for callers + that know every link is fast (JACCL/Thunderbolt): there, splitting each + layer's compute across the group cuts per-token latency, which is what a + user who just cabled two Macs together is after. """ options: list[tuple[int, int]] = [] @@ -196,7 +201,15 @@ def _splits( # weights and then fail at load. continue options.append((tp, used // tp)) - return tuple(sorted(options, key=lambda item: (item[0] * item[1], item[0]))) + return tuple( + sorted( + options, + key=lambda item: ( + item[0] * item[1], + -item[0] if prefer_tensor else item[0], + ), + ) + ) _SHORTFALL_RE = re.compile(r"\bat least (\d+) additional bytes required\b") @@ -340,11 +353,14 @@ def assess_model( tensor_parallel_ok: bool | None = None, pipeline_ok: bool | None = None, workload_profile: str = "balanced", + prefer_tensor: bool = False, ) -> ModelFit: """Whether this model runs here, using the fewest nodes that work. ``tensor_parallel_ok`` defaults to what the layout already determined, so a model mlx-lm cannot shard is never offered a tensor-parallel plan. + ``prefer_tensor`` requests the tensor-parallel split when both strategies + fit at equal width — callers set it when every link is known-fast. """ if tensor_parallel_ok is None: @@ -361,6 +377,7 @@ def assess_model( len(nodes), tensor_parallel_ok=tensor_parallel_ok, pipeline_ok=pipeline_ok, + prefer_tensor=prefer_tensor, ) for tp_size, stages in splits: used = tp_size * stages @@ -508,6 +525,7 @@ def assess_model_path( nodes: Sequence[NodeBudget], *, workload_profile: str = "balanced", + prefer_tensor: bool = False, ) -> ModelFit: """Assess a model directory, reading its real layout and config.""" @@ -536,6 +554,7 @@ def assess_model_path( model_id=root.name, declared_context_tokens=declared, workload_profile=workload_profile, + prefer_tensor=prefer_tensor, ) @@ -544,6 +563,7 @@ def catalogue_for_cluster( nodes: Sequence[NodeBudget], *, workload_profile: str = "balanced", + prefer_tensor: bool = False, ) -> tuple[ModelFit, ...]: """Assess every model, largest first among those that fit. @@ -553,7 +573,12 @@ def catalogue_for_cluster( """ fits = [ - assess_model_path(path, nodes, workload_profile=workload_profile) + assess_model_path( + path, + nodes, + workload_profile=workload_profile, + prefer_tensor=prefer_tensor, + ) for path in model_paths ] runnable = sorted( diff --git a/omlx/cluster/routes.py b/omlx/cluster/routes.py index 4e82ee7264..25ca208a9b 100644 --- a/omlx/cluster/routes.py +++ b/omlx/cluster/routes.py @@ -95,7 +95,8 @@ synthetic_model_layout, ) from .probe import collect_cluster_status -from .registry import get_cluster_registry +from .registry import get_cluster_registry, get_device_registry +from .identity import get_node_identity from .replan import ( hosts_from_deployment, nodes_from_deployment, @@ -3070,11 +3071,45 @@ async def read_host( } +def _requested_links_fast(nodes: list[ClusterPlanNodeRequest]) -> bool: + """Whether every requested peer sits on a fast (JACCL/Thunderbolt) link. + + The catalogue's default tie-break prefers pipeline at equal width because + it survives slow links; when the paired registry shows every requested + peer is reachable over JACCL/Thunderbolt RDMA, tensor parallelism is the + better recommendation — it splits per-token compute across the group. + The coordinator's own row is not in the paired registry, so only + non-self node_ids are consulted. Unknown or unpaired peers fail closed: + pipeline stays the recommendation where tensor would crawl. + """ + + if len(nodes) < 2: + return False + try: + identity = get_node_identity() + registry = get_device_registry() + except RuntimeError: + return False + for node in nodes: + if node.node_id == identity.node_id: + continue + if not registry.is_paired(node.node_id): + return False + record = registry.get(node.node_id) or {} + caps = record.get("caps") + if not isinstance(caps, dict): + return False + if not (caps.get("jaccl") or caps.get("thunderbolt")): + return False + return True + + def _catalogue_for_candidates( candidates: list[ClusterCatalogueModelRequest], nodes: list[NodeBudget], *, workload_profile: str, + prefer_tensor: bool = False, ) -> list[dict[str, Any]]: rows: list[dict[str, Any]] = [] for candidate in candidates: @@ -3097,6 +3132,7 @@ def _catalogue_for_candidates( model_id=candidate.id, declared_context_tokens=candidate.model_context_length, workload_profile=workload_profile, + prefer_tensor=prefer_tensor, ) except (OSError, PlanningError, RuntimeError, ValueError) as exc: fit = ModelFit( @@ -3137,6 +3173,7 @@ async def cluster_catalogue(request: ClusterCatalogueRequest) -> dict[str, Any]: """ nodes = _node_budgets(request.nodes) + prefer_tensor = _requested_links_fast(request.nodes) paths = [Path(item) for item in request.model_paths] if request.model_dir: @@ -3158,6 +3195,7 @@ async def cluster_catalogue(request: ClusterCatalogueRequest) -> dict[str, Any]: request.models, nodes, workload_profile=request.execution_profile, + prefer_tensor=prefer_tensor, ) else: catalogue = await asyncio.to_thread( @@ -3165,6 +3203,7 @@ async def cluster_catalogue(request: ClusterCatalogueRequest) -> dict[str, Any]: paths, nodes, workload_profile=request.execution_profile, + prefer_tensor=prefer_tensor, ) model_rows = [fit.to_dict() for fit in catalogue] runnable = [row for row in model_rows if row["fits"]] diff --git a/tests/test_cluster_catalogue.py b/tests/test_cluster_catalogue.py index a343759c41..3521ebb71c 100644 --- a/tests/test_cluster_catalogue.py +++ b/tests/test_cluster_catalogue.py @@ -394,3 +394,108 @@ def test_the_interface_can_grey_out_an_unsplittable_model(): payload = assess_model(layout, _nodes(128, 128), model_id="m").to_dict() assert payload["splittable"] is False assert payload["fits"] is False + + +# --- Fast-link recommendation ----------------------------------------------- + + +def test_prefer_tensor_flips_the_equal_width_tiebreak(): + # 90 GiB across 2x64 GiB fits both ways; pipeline is the safe default... + def shardable(): + layout = _model(90) + # The synthetic helper declares a single attention head group, which + # no TP degree above 1 divides; give it 8 heads so TP=2 is legal. + object.__setattr__(layout, "tensor_parallel_heads", 8) + object.__setattr__(layout, "tensor_parallel_kv_heads", 8) + object.__setattr__(layout, "tensor_parallel_divisors", (8,)) + return layout + + fit = assess_model(shardable(), _nodes(64, 64), model_id="medium") + assert fit.strategy == "pipeline" + # ...but a caller that knows the link is fast gets the tensor split. + fast = assess_model( + shardable(), _nodes(64, 64), model_id="medium", prefer_tensor=True + ) + assert fast.fits + assert fast.strategy == "tensor" + assert fast.tensor_parallel_size == 2 + assert fast.pipeline_stages == 1 + + +def test_prefer_tensor_still_prefers_fewer_nodes_first(): + # A model that fits one Mac stays single-node even on fast links. + fit = assess_model( + _model(20), _nodes(128, 128), model_id="small", prefer_tensor=True + ) + assert fit.strategy == "single node" + + +def test_prefer_tensor_never_offers_tp_to_an_unshardable_model(): + layout = _model(90) + object.__setattr__(layout, "supports_tensor_parallel", False) + fit = assess_model( + layout, _nodes(64, 64), model_id="m", prefer_tensor=True + ) + assert fit.fits + assert fit.strategy == "pipeline" + + +def test_requested_links_fast(tmp_path): + from omlx.cluster import routes as cluster_routes + from omlx.cluster.identity import ( + configure_node_identity, + reset_configured_identity, + ) + from omlx.cluster.registry import ( + configure_device_registry, + reset_configured_device_registry, + ) + + configure_node_identity(tmp_path / "identity.json") + registry = configure_device_registry(tmp_path / "devices.json") + try: + self_id = cluster_routes.get_node_identity().node_id + + def node(node_id): + return cluster_routes.ClusterPlanNodeRequest( + node_id=node_id, + capacity_bytes=64 * GiB, + role="headless", + memory_guard_tier="balanced", + accelerator="metal", + ) + + # A single-node request has no link to judge. + assert cluster_routes._requested_links_fast([node(self_id)]) is False + + # Unpaired peer: fail closed. + assert ( + cluster_routes._requested_links_fast([node(self_id), node("peer1")]) + is False + ) + + # Paired peer without fast-link caps: fail closed. + registry.mark_paired("peer1", caps={"chip": "M", "ram_gb": 64.0}) + assert ( + cluster_routes._requested_links_fast([node(self_id), node("peer1")]) + is False + ) + + # Paired over JACCL/Thunderbolt: tensor becomes the recommendation. + registry.mark_paired( + "peer2", caps={"jaccl": True, "thunderbolt": True} + ) + assert ( + cluster_routes._requested_links_fast([node(self_id), node("peer2")]) + is True + ) + # One slow peer in a larger pool fails the whole request closed. + assert ( + cluster_routes._requested_links_fast( + [node(self_id), node("peer2"), node("peer1")] + ) + is False + ) + finally: + reset_configured_device_registry() + reset_configured_identity() From b5dcf7bed9255c2be73344199dcf8533e23c4c17 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Fri, 21 Aug 2026 21:08:24 -0700 Subject: [PATCH 129/132] fix(cluster): strip IPv6 zone ids, order routable IPs first in hostfiles MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit macOS announces Thunderbolt interfaces as fe80::…%en10; mlx's address parser cannot read the zone id and ranks died at startup with 'Can't parse address fe80::…%en10:56758'. _validate_ip now strips the zone (machine-local by definition, never valid on the wire) and the hostfile orders routable addresses ahead of link-local fallbacks, so a Mac with configured 10.x Thunderbolt IPs never advertises the ambiguous one first. 3 tests pin the exact failure. --- omlx/cluster/deployment.py | 23 ++++++++++++++++++++++- tests/test_cluster_deployment.py | 27 +++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/omlx/cluster/deployment.py b/omlx/cluster/deployment.py index d9e7e11626..b9447b15fb 100644 --- a/omlx/cluster/deployment.py +++ b/omlx/cluster/deployment.py @@ -63,6 +63,11 @@ def validate_ssh_target(value: str) -> str: def _validate_ip(value: str) -> str: value = value.strip() + # macOS reports Thunderbolt/link-local addresses with a zone id + # (fe80::…%en10). mlx's address parser cannot read the suffix — a rank + # died at startup on exactly that — and a zone only means something on + # the machine that named it, so it never belongs on the wire. + value = value.split("%", 1)[0] try: ipaddress.ip_address(value) except ValueError as exc: @@ -70,6 +75,22 @@ def _validate_ip(value: str) -> str: return value +def _hostfile_ips(host: "ClusterHost") -> list[str]: + """Communication IPs in the order a rank should try them. + + Routable addresses first: a link-local IPv6 without its (machine-local) + zone id is ambiguous, so it can only ever be a fallback. This is what + keeps a Mac that announces fe80:: Thunderbolt addresses alongside its + configured link IPs from advertising the unusable one first. + """ + + def _link_local(ip: str) -> bool: + return ipaddress.ip_address(ip).is_link_local + + routable = [ip for ip in host.ips if not _link_local(ip)] + return routable + [ip for ip in host.ips if _link_local(ip)] + + def _validate_rdma_path(value: Any) -> RDMAPath: if value is None: return None @@ -415,7 +436,7 @@ def hostfile_dict(self) -> dict[str, Any]: "hosts": [ { "ssh": host.ssh, - "ips": list(host.ips), + "ips": _hostfile_ips(host), "rdma": [ list(path) if isinstance(path, tuple) else path for path in host.rdma diff --git a/tests/test_cluster_deployment.py b/tests/test_cluster_deployment.py index 3e39d52887..9b4f32158c 100644 --- a/tests/test_cluster_deployment.py +++ b/tests/test_cluster_deployment.py @@ -433,3 +433,30 @@ def test_a_plan_carrying_an_unknown_role_refuses_to_launch(): with pytest.raises(ValueError, match="unknown node role"): _assignment_from_dict(payload) + + +def test_link_local_zone_ids_are_stripped_from_communication_ips(): + """macOS announces Thunderbolt addresses as fe80::…%en10; mlx's address + parser cannot read the zone and the rank died at startup on it.""" + host = ClusterHost( + "node", "peer.local", ("10.0.0.2", "fe80::23:3ee:ec30:9a92%en10") + ) + assert host.ips == ("10.0.0.2", "fe80::23:3ee:ec30:9a92") + + +def test_hostfile_advertises_routable_addresses_before_link_local(): + from omlx.cluster.deployment import _hostfile_ips + + host = ClusterHost( + "node", + "peer.local", + ("fe80::1%en4", "10.0.0.2", "fe80::2%en5"), + ) + assert _hostfile_ips(host) == ["10.0.0.2", "fe80::1", "fe80::2"] + + +def test_a_link_local_only_host_keeps_its_zone_free_fallback(): + from omlx.cluster.deployment import _hostfile_ips + + host = ClusterHost("node", "peer.local", ("fe80::1%en4",)) + assert _hostfile_ips(host) == ["fe80::1"] From 2a131e23dac8e7e37f8cf2eb003b2eae145ca6e5 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Wed, 26 Aug 2026 03:48:38 -0700 Subject: [PATCH 130/132] fix(cluster): reconcile portable paths and planning lint --- omlx/cluster/catalogue.py | 12 +--- omlx/cluster/deployment.py | 18 ++--- omlx/cluster/inference_worker.py | 49 ++++++------- omlx/cluster/launch.py | 58 +++++++-------- omlx/cluster/modelsync.py | 95 +++++++++++++++++-------- omlx/cluster/planner.py | 79 ++++++++------------ omlx/cluster/registry.py | 4 +- omlx/cluster/replan.py | 11 +-- omlx/cluster/staging.py | 50 ++++--------- tests/test_cluster_catalogue.py | 15 ++-- tests/test_cluster_deployment.py | 5 +- tests/test_cluster_modelsync.py | 48 ++++++------- tests/test_cluster_proportional_plan.py | 15 ++-- tests/test_cluster_replan.py | 51 +++++++------ 14 files changed, 236 insertions(+), 274 deletions(-) diff --git a/omlx/cluster/catalogue.py b/omlx/cluster/catalogue.py index 42e513c334..3507147cad 100644 --- a/omlx/cluster/catalogue.py +++ b/omlx/cluster/catalogue.py @@ -117,9 +117,7 @@ def context_is_limited(self) -> bool: """Does memory, not the model, set the usable context?""" declared = self.declared_context_tokens - return bool( - self.fits and declared and self.max_context_tokens < declared - ) + return bool(self.fits and declared and self.max_context_tokens < declared) def describe(self) -> str: """One line a person can act on.""" @@ -385,9 +383,7 @@ def assess_model( # them, which is where the fast links were placed. Ranks are positional # to the planner and must be contiguous from zero, so a subset — or a # caller's single node that happened to be rank 1 — is renumbered. - subset = [ - replace(node, rank=index) for index, node in enumerate(nodes[:used]) - ] + subset = [replace(node, rank=index) for index, node in enumerate(nodes[:used])] plan, reason = _plan_or_none( layout, subset, @@ -483,9 +479,7 @@ def assess_model( if standalone_node_id: failure_kind = "single_node_only" context = ( - f" at up to {standalone_context:,} tokens" - if standalone_context - else "" + f" at up to {standalone_context:,} tokens" if standalone_context else "" ) last_reason = ( "This model cannot combine Macs because mlx-lm supports neither " diff --git a/omlx/cluster/deployment.py b/omlx/cluster/deployment.py index b9447b15fb..922862415b 100644 --- a/omlx/cluster/deployment.py +++ b/omlx/cluster/deployment.py @@ -75,7 +75,7 @@ def _validate_ip(value: str) -> str: return value -def _hostfile_ips(host: "ClusterHost") -> list[str]: +def _hostfile_ips(host: ClusterHost) -> list[str]: """Communication IPs in the order a rank should try them. Routable addresses first: a link-local IPv6 without its (machine-local) @@ -132,7 +132,9 @@ def validate_model_path_map( if not isinstance(node_id, str) or _NODE_ID.fullmatch(node_id) is None: raise ValueError(f"invalid path_map node ID: {node_id!r}") if known is not None and node_id not in known: - raise ValueError(f"path_map names a node outside the deployment: {node_id!r}") + raise ValueError( + f"path_map names a node outside the deployment: {node_id!r}" + ) if not isinstance(raw_path, str): raise ValueError(f"path_map path for {node_id!r} must be a string") path = raw_path.strip() @@ -340,17 +342,13 @@ def __post_init__(self) -> None: "tensor_parallel_size must be between 1 and the host count" ) if len(self.hosts) % self.tensor_parallel_size != 0: - raise ValueError( - "host count must be divisible by tensor_parallel_size" - ) + raise ValueError("host count must be divisible by tensor_parallel_size") if ( not isinstance(self.target_context_tokens, int) or isinstance(self.target_context_tokens, bool) or not 1 <= self.target_context_tokens <= 1_048_576 ): - raise ValueError( - "target_context_tokens must be between 1 and 1,048,576" - ) + raise ValueError("target_context_tokens must be between 1 and 1,048,576") if len(self.assignments) != len(self.hosts): raise ValueError("host count must match pipeline assignment count") if self.hosts[0].ssh != "127.0.0.1": @@ -609,7 +607,9 @@ def decode_worker_contract( raise ValueError("worker performance profiles do not match the shard plan") tensor_parallel_size = int(payload.get("tensor_parallel_size", 1)) if not 1 <= tensor_parallel_size <= len(parsed): - raise ValueError("tensor_parallel_size must be between 1 and the assignment count") + raise ValueError( + "tensor_parallel_size must be between 1 and the assignment count" + ) return payload["plan_hash"], parsed, profiles, tensor_parallel_size diff --git a/omlx/cluster/inference_worker.py b/omlx/cluster/inference_worker.py index cbb9224d1e..2e3e156bbd 100644 --- a/omlx/cluster/inference_worker.py +++ b/omlx/cluster/inference_worker.py @@ -666,9 +666,9 @@ def _validate_loaded_stage( and start in (None, 0) and end in (None, len(layers)) ) - if ( - not expected_complete_tensor_stage - and (start, end) != (assignment.start_layer, assignment.end_layer) + if not expected_complete_tensor_stage and (start, end) != ( + assignment.start_layer, + assignment.end_layer, ): raise RuntimeError( "loaded model pipeline range does not match the approved plan: " @@ -1112,25 +1112,28 @@ def run_worker(args: argparse.Namespace) -> int: # it is checked again against what the rank actually holds, all the # way through the load. A rank that overruns dies here rather than # taking the Mac with it. - with watch_rank_load( - load_budget, - rank=rank, - node_id=getattr(assignment, "node_id", ""), - on_sample=lambda observed: marker.update( - "loading", - load_stage="loading_weights", - load_memory_bytes=observed, + with ( + watch_rank_load( + load_budget, + rank=rank, + node_id=getattr(assignment, "node_id", ""), + on_sample=lambda observed: marker.update( + "loading", + load_stage="loading_weights", + load_memory_bytes=observed, + ), ), - ), install_progressive_loader( - mlx_server, - progress=lambda progress: marker.update( - "loading", - load_stage=progress.get("phase", "materializing_layers"), - **{ - key: value - for key, value in progress.items() - if key != "phase" - }, + install_progressive_loader( + mlx_server, + progress=lambda progress: marker.update( + "loading", + load_stage=progress.get("phase", "materializing_layers"), + **{ + key: value + for key, value in progress.items() + if key != "phase" + }, + ), ), ): provider.load_default() @@ -1220,9 +1223,7 @@ def run_worker(args: argparse.Namespace) -> int: provider.model, rank=rank, node_id=getattr(assignment, "node_id", ""), - layer_count=( - assignment.end_layer - assignment.start_layer - ), + layer_count=(assignment.end_layer - assignment.start_layer), tensor_parallel_size=assignment.tensor_parallel_size, memory_guard_tier=guard_tier, # The attention peak is set by the prefill chunk, so the diff --git a/omlx/cluster/launch.py b/omlx/cluster/launch.py index d4e8cc4a6b..523ea4ed3f 100644 --- a/omlx/cluster/launch.py +++ b/omlx/cluster/launch.py @@ -227,9 +227,7 @@ def _python_minor(version: str) -> tuple[str, str] | None: return (parts[0], parts[1]) -def _interpreter_parity( - local: str, remote: Any -) -> tuple[str | None, str | None]: +def _interpreter_parity(local: str, remote: Any) -> tuple[str | None, str | None]: """Compare the interpreter two ranks will actually run under (#2695). Returns ``(blocking, warning)``, at most one of which is set. @@ -284,8 +282,7 @@ def _rank_python_module_argv( for rank, executable in enumerate(executables) ) script = ( - f'case "${{MLX_RANK:-}}" in {cases} *) exit 64;; esac; ' - 'exec "$omlx_python" "$@"' + f'case "${{MLX_RANK:-}}" in {cases} *) exit 64;; esac; exec "$omlx_python" "$@"' ) return ["/bin/sh", "-c", script, "omlx-rank-python", "-m", module] @@ -690,7 +687,10 @@ def run_cuda_fabric_probe( raise DistributedLaunchError( f"CUDA fabric probe exited with code {completed.returncode}{suffix}" ) - if len(completed.stdout.encode()) + len(completed.stderr.encode()) > _REMOTE_OUTPUT_LIMIT: + if ( + len(completed.stdout.encode()) + len(completed.stderr.encode()) + > _REMOTE_OUTPUT_LIMIT + ): raise DistributedLaunchError("CUDA fabric probe output exceeded the safe limit") records: list[dict[str, Any]] = [] for line in completed.stdout.splitlines(): @@ -705,7 +705,9 @@ def run_cuda_fabric_probe( raise DistributedLaunchError( "CUDA fabric probe did not return one result from each worker" ) - observed = min(float(record.get("payload_bytes_per_second") or 0) for record in records) + observed = min( + float(record.get("payload_bytes_per_second") or 0) for record in records + ) verified = observed >= minimum_bytes_per_second identity = "\0".join(sorted(host.ssh for host in hosts)).encode() group_id = f"connectx-{hashlib.sha256(identity).hexdigest()[:16]}" @@ -854,8 +856,7 @@ def discover_remote_python_executable( # bare command name (``python3``) needs ``sys.executable`` to become an # absolute path. script = ( - "import os,omlx; print(os.path.expanduser(" - f"{candidate!r}))" + f"import os,omlx; print(os.path.expanduser({candidate!r}))" if candidate.startswith(("~", "/")) else "import sys,omlx; print(sys.executable)" ) @@ -1127,9 +1128,7 @@ def probe_remote_system_host( "ssh_reachable": True, "status": payload, "runtime_compatible": False, - "runtime_mismatches": [ - _RUNTIME_UNVERIFIED if evidence else _RUNTIME_MISSING - ], + "runtime_mismatches": [_RUNTIME_UNVERIFIED if evidence else _RUNTIME_MISSING], # Same keys as the healthy path, so a caller never has to know which # branch produced the result before reading it. "runtime_warnings": [], @@ -1481,9 +1480,7 @@ def preflight_remote_hosts( from .memory_guard import ceiling_breakdown local_admission_ceiling = int( - ceiling_breakdown( - assignments[0].memory_guard_tier - ).get("hard_limit", 0) + ceiling_breakdown(assignments[0].memory_guard_tier).get("hard_limit", 0) ) except Exception as exc: raise DistributedLaunchError( @@ -1581,7 +1578,10 @@ def preflight_remote_hosts( mismatches.append( f"model directory is missing on remote host: {remote_model_path}" ) - if local_identity is not None and versions.get("model_identity") != local_identity: + if ( + local_identity is not None + and versions.get("model_identity") != local_identity + ): mismatches.append( "model identity differs from the coordinator " "(config, tokenizer, processor, or weight index)" @@ -1647,9 +1647,7 @@ def _validate_deployment_admission( 0.0, min( 1.0, - ( - assignment.capacity_bytes - assignment.reserve_bytes - ) + (assignment.capacity_bytes - assignment.reserve_bytes) / assignment.capacity_bytes, ), ) @@ -1945,9 +1943,7 @@ def _terminate(self) -> None: os.killpg(process_group, signal.SIGTERM) if process.poll() is None: with suppress(subprocess.TimeoutExpired): - process.wait( - timeout=max(0.0, deadline - time.monotonic()) - ) + process.wait(timeout=max(0.0, deadline - time.monotonic())) # mlx.launch can exit promptly while a local rank remains blocked # in a Metal/JACCL collective. Waiting only for the launcher left @@ -2110,9 +2106,7 @@ def _reap_remote_ranks(self, *, runner: SSHRunner = subprocess.run) -> None: host.ssh, ) elif action in ("terminated", "killed"): - logger.info( - "reaped remote rank %d on %s (%s)", rank, host.ssh, action - ) + logger.info("reaped remote rank %d on %s (%s)", rank, host.ssh, action) elif action: logger.debug( "remote rank reap for rank %d on %s: %s", @@ -2122,8 +2116,7 @@ def _reap_remote_ranks(self, *, runner: SSHRunner = subprocess.run) -> None: ) else: logger.warning( - "remote rank reap for rank %d on %s returned no report " - "(exit %s)", + "remote rank reap for rank %d on %s returned no report (exit %s)", rank, host.ssh, completed.returncode, @@ -2154,9 +2147,7 @@ def _runtime_failure_reason(self) -> str | None: for rank, host in enumerate(self.deployment.hosts): filename = f"{self.deployment.deployment_id}-rank-{rank}.json" if host.ssh in _LOOPBACK_TARGETS: - marker = read_marker( - Path(self.state_dir).expanduser() / filename - ) + marker = read_marker(Path(self.state_dir).expanduser() / filename) else: remote_root = self.state_dir.rstrip("/") or "." marker, _, _, _ = read_remote_marker( @@ -2169,7 +2160,8 @@ def _runtime_failure_reason(self) -> str | None: marker.get("deployment_id") != self.deployment.deployment_id or marker.get("plan_hash") != self.deployment.plan_hash or marker.get("rank") != rank - or marker.get("phase") not in { + or marker.get("phase") + not in { "failed", "peer_lost", "launcher_lost", @@ -2178,9 +2170,7 @@ def _runtime_failure_reason(self) -> str | None: continue error = marker.get("error") if isinstance(error, str) and error.strip(): - failures.append( - f"rank {rank} ({host.node_id}): {error.strip()}" - ) + failures.append(f"rank {rank} ({host.node_id}): {error.strip()}") return "; ".join(failures)[:_LOG_LINE_LIMIT] or None def _failure_reason(self) -> str | None: diff --git a/omlx/cluster/modelsync.py b/omlx/cluster/modelsync.py index 7f99320edb..1501151e6a 100644 --- a/omlx/cluster/modelsync.py +++ b/omlx/cluster/modelsync.py @@ -143,9 +143,7 @@ class SyncProgress: model_id: str peer: str method: str - phase: Literal[ - "checking", "transferring", "verifying", "done", "error" - ] + phase: Literal["checking", "transferring", "verifying", "done", "error"] bytes_done: int = 0 bytes_total: int = 0 bytes_per_second: float | None = None @@ -190,8 +188,7 @@ def build_manifest( else None ) files = [ - ManifestFile(name=path.name, size_bytes=path.stat().st_size) - for path in weights + ManifestFile(name=path.name, size_bytes=path.stat().st_size) for path in weights ] for name in sidecar_files(root): path = root / name @@ -231,7 +228,9 @@ def allow_patterns_for_shard( return tuple(sorted(patterns)) -def compare_manifests(local: ModelManifest, peer: ModelManifest | None) -> dict[str, Any]: +def compare_manifests( + local: ModelManifest, peer: ModelManifest | None +) -> dict[str, Any]: """Whether ``peer`` can serve the model ``local`` describes. * ``missing`` — the peer answered 404 or is unreachable. @@ -261,7 +260,9 @@ def compare_manifests(local: ModelManifest, peer: ModelManifest | None) -> dict[ } peer_sizes = {item.name: item.size_bytes for item in peer.files} missing = [ - item.name for item in local.files if peer_sizes.get(item.name) != item.size_bytes + item.name + for item in local.files + if peer_sizes.get(item.name) != item.size_bytes ] matched = sum( item.size_bytes for item in local.files if item.name not in set(missing) @@ -281,12 +282,15 @@ def parse_rsync_progress(line: str) -> tuple[int, float, float] | None: if match is None: return None done = int(match.group("bytes").replace(",", "")) - rate = float(match.group("rate").replace(",", "")) * _RATE_MULTIPLIERS[ - match.group("unit") - ] + rate = ( + float(match.group("rate").replace(",", "")) + * _RATE_MULTIPLIERS[match.group("unit")] + ) parts = [int(part) for part in match.group("eta").split(":")] - eta = parts[0] * 3600 + parts[1] * 60 + parts[2] if len(parts) == 3 else ( - parts[0] * 60 + parts[1] + eta = ( + parts[0] * 3600 + parts[1] * 60 + parts[2] + if len(parts) == 3 + else (parts[0] * 60 + parts[1]) ) return done, rate, float(eta) @@ -358,9 +362,7 @@ def _normalize_peer_url(peer: str) -> str: raise ValueError("peer must be a host:port or http(s) URL") if "://" not in peer: if ":" not in peer.rsplit("]", 1)[-1]: - raise ValueError( - f"peer {peer!r} has no port; use host:port or a full URL" - ) + raise ValueError(f"peer {peer!r} has no port; use host:port or a full URL") peer = f"http://{peer}" return peer.rstrip("/") @@ -411,7 +413,11 @@ def resolve_local_model_path(self, model_id: str) -> Path: for item in status.get("models", []) if isinstance(status, dict) else []: if not isinstance(item, dict): continue - if model_id in {item.get("id"), item.get("source_repo_id"), item.get("model_path")}: + if model_id in { + item.get("id"), + item.get("source_repo_id"), + item.get("model_path"), + }: path = Path(str(item["model_path"])).expanduser() if path.is_dir(): return path.resolve() @@ -452,7 +458,9 @@ def _default_http_fetch(url: str, timeout: float) -> dict[str, Any] | None: except urllib.error.HTTPError as exc: if exc.code == 404: return None - raise ModelSyncError(f"peer manifest request failed: HTTP {exc.code}") from exc + raise ModelSyncError( + f"peer manifest request failed: HTTP {exc.code}" + ) from exc except (OSError, urllib.error.URLError) as exc: raise ModelSyncError(f"peer is unreachable: {exc}") from exc @@ -495,9 +503,12 @@ def decide_method( ) -> Literal["rsync", "download"]: """auto = rsync when SSH trust exists AND the model is over 20 GB.""" - if ssh_target and total_bytes > AUTO_RSYNC_THRESHOLD_BYTES: - if self._ssh_trust(ssh_target): - return "rsync" + if ( + ssh_target + and total_bytes > AUTO_RSYNC_THRESHOLD_BYTES + and self._ssh_trust(ssh_target) + ): + return "rsync" return "download" def sync( @@ -530,8 +541,15 @@ def sync( if method == "auto" else method ) - self._emit(on_progress, local.model_id, peer, chosen, "checking", - bytes_total=local.total_bytes, detail="comparing manifests") + self._emit( + on_progress, + local.model_id, + peer, + chosen, + "checking", + bytes_total=local.total_bytes, + detail="comparing manifests", + ) try: if chosen == "rsync": result = self._sync_rsync( @@ -549,11 +567,25 @@ def sync( on_progress, ) except Exception as exc: - self._emit(on_progress, local.model_id, peer, chosen, "error", - bytes_total=local.total_bytes, detail=str(exc)[:500]) + self._emit( + on_progress, + local.model_id, + peer, + chosen, + "error", + bytes_total=local.total_bytes, + detail=str(exc)[:500], + ) raise - self._emit(on_progress, local.model_id, peer, chosen, "done", - bytes_done=local.total_bytes, bytes_total=local.total_bytes) + self._emit( + on_progress, + local.model_id, + peer, + chosen, + "done", + bytes_done=local.total_bytes, + bytes_total=local.total_bytes, + ) return result def _sync_rsync( @@ -595,8 +627,15 @@ def progress(done: int, rate: float, eta: float) -> None: rc = self._rsync_run(argv, on_line=self._progress_line_parser(progress)) if rc != 0: raise ModelSyncError(f"rsync to {ssh_target} exited with status {rc}") - self._emit(on_progress, local.model_id, peer, "rsync", "verifying", - bytes_total=local.total_bytes, detail="verifying peer manifest") + self._emit( + on_progress, + local.model_id, + peer, + "rsync", + "verifying", + bytes_total=local.total_bytes, + detail="verifying peer manifest", + ) return { "method": "rsync", "peer": peer, diff --git a/omlx/cluster/planner.py b/omlx/cluster/planner.py index 3a3a96a22f..31069da1e5 100644 --- a/omlx/cluster/planner.py +++ b/omlx/cluster/planner.py @@ -55,16 +55,13 @@ def normalize_node_role(value: Any) -> str: if value is None: return "" if not isinstance(value, str): - raise ValueError( - f"node role must be a string, got {type(value).__name__}" - ) + raise ValueError(f"node role must be a string, got {type(value).__name__}") text = value.strip().lower() if not text: return "" if text not in ROLES: raise ValueError( - f"unknown node role: {value!r} (expected one of " - f"{', '.join(sorted(ROLES))})" + f"unknown node role: {value!r} (expected one of {', '.join(sorted(ROLES))})" ) return text @@ -214,8 +211,7 @@ def from_dict(cls, payload: dict[str, Any]) -> ModelLayout: payload.get("tensor_parallel_kv_heads", 0) ), tensor_parallel_divisors=tuple( - int(value) - for value in payload.get("tensor_parallel_divisors", ()) + int(value) for value in payload.get("tensor_parallel_divisors", ()) ), kv_bytes_per_token_per_layer=int( payload.get("kv_bytes_per_token_per_layer", 0) @@ -686,9 +682,9 @@ def _tensor_parallel_divisors(config: dict[str, Any]) -> tuple[int, ...]: // max(_config_int(config, "num_attention_heads", 1), 1) ) attn_dim = _config_int(config, "num_attention_heads", 0) * head_dim - mamba_dim = _config_int( - config, "mamba_num_heads", 0 - ) * _config_int(config, "mamba_head_dim", 0) + mamba_dim = _config_int(config, "mamba_num_heads", 0) * _config_int( + config, "mamba_head_dim", 0 + ) shared_dim = _config_int( config, "moe_shared_expert_intermediate_size", @@ -877,11 +873,7 @@ def _kv_bytes_per_token_per_layer(config: dict[str, Any]) -> int: head_dim = _config_int(config, "head_dim", 0) if head_dim <= 0: hidden = _config_int(config, "hidden_size", 0, maximum=1_000_000) - head_dim = ( - hidden // heads - if hidden and heads and hidden % heads == 0 - else 0 - ) + head_dim = hidden // heads if hidden and heads and hidden % heads == 0 else 0 if head_dim > 4096: return 0 if kv_heads <= 0 or head_dim <= 0: @@ -1062,14 +1054,10 @@ def inspect_safetensors_layout(model_path: str | Path) -> ModelLayout: # the runtime model never instantiates them. Counting them as decoder # layers put a stage boundary over weights that do not exist at runtime, # and the last stage failed activation with end_layer beyond the model. - declared_depth = _config_int( - _model_config(root), "num_hidden_layers", 0 - ) + declared_depth = _config_int(_model_config(root), "num_hidden_layers", 0) if declared_depth > 0 and max(layer_sizes) >= declared_depth: trimmed = { - index: size - for index, size in layer_sizes.items() - if index < declared_depth + index: size for index, size in layer_sizes.items() if index < declared_depth } if trimmed: layer_sizes = trimmed @@ -1096,12 +1084,8 @@ def inspect_safetensors_layout(model_path: str | Path) -> ModelLayout: tensor_parallel_divisors=_tensor_parallel_divisors(_model_config(root)), supports_tensor_parallel=_supports_tensor_parallel(_model_config(root)), supports_pipeline=_supports_pipeline(_model_config(root)), - kv_bytes_per_token_per_layer=_kv_bytes_per_token_per_layer( - _model_config(root) - ), - kv_replicated_across_tp=_kv_cache_replicated_across_tp( - _model_config(root) - ), + kv_bytes_per_token_per_layer=_kv_bytes_per_token_per_layer(_model_config(root)), + kv_replicated_across_tp=_kv_cache_replicated_across_tp(_model_config(root)), ) @@ -1339,9 +1323,7 @@ def _partition_layers( start = previous_end for end in range(max(start + 1, minimum_end), maximum_end + 1): layer_bytes = weight_prefix[end] - weight_prefix[start] - resident_layer_bytes = ( - resident_prefix[end] - resident_prefix[start] - ) + resident_layer_bytes = resident_prefix[end] - resident_prefix[start] planned_weight_bytes = fixed_weight_bytes + layer_bytes planned_resident_bytes = fixed_weight_bytes + resident_layer_bytes if planned_weight_bytes > node.weight_ceiling_bytes: @@ -1365,14 +1347,12 @@ def _partition_layers( previous_score[score_offset + 1] + stage_seconds * stage_seconds, max(previous_score[score_offset + 2], utilization), - previous_score[score_offset + 3] - + utilization * utilization, + previous_score[score_offset + 3] + utilization * utilization, ) else: score = ( max(previous_score[score_offset], utilization), - previous_score[score_offset + 1] - + utilization * utilization, + previous_score[score_offset + 1] + utilization * utilization, ) if target_aware: target = node.target_weight_bytes @@ -1395,8 +1375,7 @@ def _partition_layers( final = states.get(layer_count) if final is None: resident_capacity = sum( - max(0, node.usable_bytes - fixed_weight_bytes) - for node in pipeline_nodes + max(0, node.usable_bytes - fixed_weight_bytes) for node in pipeline_nodes ) weight_capacity = sum( max(0, node.weight_ceiling_bytes - fixed_weight_bytes) @@ -1555,8 +1534,7 @@ def allocate_layers_proportional( node_count = len(shares) if node_count > layer_count: raise PlanningError( - f"{node_count} nodes cannot each receive a layer from " - f"{layer_count} layers" + f"{node_count} nodes cannot each receive a layer from {layer_count} layers" ) total = sum(shares) exact = [Fraction(layer_count * share, total) for share in shares] @@ -1717,9 +1695,7 @@ def _finish_pipeline_plan( "reserve_bytes": item.reserve_bytes, "manual_memory_limit": item.manual_memory_limit, "target_weight_bytes": next( - node.target_weight_bytes - for node in nodes - if node.rank == item.rank + node.target_weight_bytes for node in nodes if node.rank == item.rank ), # Part of the plan's identity: the same layers on the same Mac # mean a different deployment depending on whether someone is @@ -1885,9 +1861,7 @@ def _max_context_for_stage( "not known" rather than "unlimited". """ - per_token = _kv_bytes_per_token_for_stage( - model, layer_count, tensor_parallel_size - ) + per_token = _kv_bytes_per_token_for_stage(model, layer_count, tensor_parallel_size) if per_token <= 0: return 0 spare = node.usable_bytes - weight_bytes @@ -2041,7 +2015,11 @@ def plan_hybrid( # them, split within each layer by shard_linear. ordered_nodes = sorted(nodes, key=lambda item: item.rank) stage_groups = [ - tuple(ordered_nodes[stage * tensor_parallel_size : (stage + 1) * tensor_parallel_size]) + tuple( + ordered_nodes[ + stage * tensor_parallel_size : (stage + 1) * tensor_parallel_size + ] + ) for stage in range(pipeline_stages) ] @@ -2160,10 +2138,13 @@ def plan_hybrid( assignments.sort(key=lambda a: a.rank) # Build performance profiles if available - profiles = tuple( - node.performance for node in ordered_nodes - if node.performance is not None - ) if performance_aware else () + profiles = ( + tuple( + node.performance for node in ordered_nodes if node.performance is not None + ) + if performance_aware + else () + ) # Compute plan hash covering all assignment fields hash_payload = { diff --git a/omlx/cluster/registry.py b/omlx/cluster/registry.py index baf51f5a58..33f6fec496 100644 --- a/omlx/cluster/registry.py +++ b/omlx/cluster/registry.py @@ -77,10 +77,8 @@ def _load(self) -> None: # file described. Persist the upgrade so the migration happens # once, but never let an unwritable file block server startup. self.migrated_from = int(payload.get("schema_version", 1)) - try: + with suppress(OSError): self._save() - except OSError: - pass def _save(self) -> None: self.path.parent.mkdir(parents=True, exist_ok=True) diff --git a/omlx/cluster/replan.py b/omlx/cluster/replan.py index c9dca6986a..bd93d8efd6 100644 --- a/omlx/cluster/replan.py +++ b/omlx/cluster/replan.py @@ -76,8 +76,7 @@ def hosts_from_deployment(deployment: ClusterDeployment) -> list[dict[str, Any]] "ssh": host.ssh, "ips": list(host.ips), "rdma": [ - list(path) if isinstance(path, tuple) else path - for path in host.rdma + list(path) if isinstance(path, tuple) else path for path in host.rdma ], } if host.python_executable: @@ -105,9 +104,7 @@ def summarize_deployment(deployment: ClusterDeployment) -> dict[str, Any]: "planned_weight_bytes": assignment.planned_weight_bytes, "kv_cache_bytes": assignment.kv_cache_bytes, } - for assignment in sorted( - deployment.assignments, key=lambda item: item.rank - ) + for assignment in sorted(deployment.assignments, key=lambda item: item.rank) ], } @@ -121,7 +118,5 @@ def placement_view(deployment: ClusterDeployment) -> dict[str, Any]: """ return { - "assignments": [ - assignment.to_dict() for assignment in deployment.assignments - ] + "assignments": [assignment.to_dict() for assignment in deployment.assignments] } diff --git a/omlx/cluster/staging.py b/omlx/cluster/staging.py index 632e93d9f2..2e76ca9470 100644 --- a/omlx/cluster/staging.py +++ b/omlx/cluster/staging.py @@ -162,9 +162,7 @@ def shards_for_stage( wanted = set(range(start_layer, end_layer)) return tuple( - shard - for shard in shards - if (shard.layers & wanted) or shard.has_shared_tensors + shard for shard in shards if (shard.layers & wanted) or shard.has_shared_tensors ) @@ -312,7 +310,9 @@ def validate_staged_model( indexed = _indexed_shards(root) shards = indexed if indexed is not None else index_shards(root) required = shards_for_stage(shards, start_layer, end_layer) - missing = tuple(shard.name for shard in required if not (root / shard.name).is_file()) + missing = tuple( + shard.name for shard in required if not (root / shard.name).is_file() + ) corrupt: list[str] = [] for shard in required: path = root / shard.name @@ -352,10 +352,7 @@ def model_staging_inventory(model_path: str | Path) -> dict[str, Any]: } for shard in shards ], - "sidecars": { - name: (root / name).stat().st_size - for name in sidecars - }, + "sidecars": {name: (root / name).stat().st_size for name in sidecars}, } @@ -571,9 +568,7 @@ def stage_manifest( for plan in plans: present = present_by_node.get(plan.node_id, {}) missing_sidecars = tuple( - name - for name, size in sidecar_sizes.items() - if present.get(name) != size + name for name, size in sidecar_sizes.items() if present.get(name) != size ) missing_sidecar_bytes = sum(sidecar_sizes[name] for name in missing_sidecars) total_missing_bytes += plan.missing_bytes + missing_sidecar_bytes @@ -588,9 +583,7 @@ def stage_manifest( ) return { "sidecars": list(sidecars), - "source_host": ( - "127.0.0.1" if source_is_local else source_host - ), + "source_host": ("127.0.0.1" if source_is_local else source_host), "nodes": nodes, "total_missing_bytes": total_missing_bytes, "ready": all(node["ready"] for node in nodes), @@ -613,9 +606,7 @@ def stage_manifest( "\nos.replace(temporary,final)" ) _REMOTE_DISCARD_SNIPPET = ( - "import os,sys;" - "\ntry: os.unlink(sys.argv[1])" - "\nexcept FileNotFoundError: pass" + "import os,sys;\ntry: os.unlink(sys.argv[1])\nexcept FileNotFoundError: pass" ) @@ -653,8 +644,7 @@ def _finish_remote_staged_file( ) if result.returncode != 0: raise RuntimeError( - f"could not install staged file on {host}: " - f"{result.stderr.strip()[:200]}" + f"could not install staged file on {host}: {result.stderr.strip()[:200]}" ) @@ -750,9 +740,7 @@ def scp_push( f"{str(Path(destination_dir).expanduser()).rstrip('/')}/" f"{_staging_partial_name()}" ) - final_path = ( - f"{str(Path(destination_dir).expanduser()).rstrip('/')}/{filename}" - ) + final_path = f"{str(Path(destination_dir).expanduser()).rstrip('/')}/{filename}" installed = False try: result = subprocess.run( @@ -791,11 +779,7 @@ def _local_file_sizes(model_dir: str | Path) -> dict[str, int]: root = Path(model_dir).expanduser() if not root.is_dir(): return {} - return { - path.name: path.stat().st_size - for path in root.iterdir() - if path.is_file() - } + return {path.name: path.stat().st_size for path in root.iterdir() if path.is_file()} def scp_copy( @@ -878,9 +862,7 @@ def scp_copy( f"could not create model directory on {destination_host}: " f"{mkdir.stderr.strip()[:200]}" ) - temporary_path = ( - f"{destination_dir.rstrip('/')}/{_staging_partial_name()}" - ) + temporary_path = f"{destination_dir.rstrip('/')}/{_staging_partial_name()}" final_path = f"{destination_dir.rstrip('/')}/{filename}" installed = False try: @@ -951,9 +933,7 @@ def stage_files_from_source( source_dir = ( str(Path(model_path).expanduser()) if is_local_host(source_host) - else remote_model_dir( - source_host, home_relative_model_path(str(model_path)) - ) + else remote_model_dir(source_host, home_relative_model_path(str(model_path))) ) destination_dir = destination_dir or source_dir expected = dict(expected_sizes) @@ -968,9 +948,7 @@ def stage_files_from_source( ): raise RuntimeError("staging source returned an unsafe file inventory") if is_local_host(source_host) and not is_local_host(destination_host): - common = tuple( - name for name in expected if name not in set(plan.required) - ) + common = tuple(name for name in expected if name not in set(plan.required)) return stage_remote_files( plan, model_path=model_path, diff --git a/tests/test_cluster_catalogue.py b/tests/test_cluster_catalogue.py index 3521ebb71c..813217309e 100644 --- a/tests/test_cluster_catalogue.py +++ b/tests/test_cluster_catalogue.py @@ -249,9 +249,7 @@ def _node_payload(capacity_gib, node_id="studio"): def test_the_endpoint_needs_somewhere_to_look(): - response = _client().post( - CATALOGUE, json={"nodes": [_node_payload(128)]} - ) + response = _client().post(CATALOGUE, json={"nodes": [_node_payload(128)]}) assert response.status_code == 400 assert "model_paths or model_dir" in response.json()["detail"] @@ -433,9 +431,7 @@ def test_prefer_tensor_still_prefers_fewer_nodes_first(): def test_prefer_tensor_never_offers_tp_to_an_unshardable_model(): layout = _model(90) object.__setattr__(layout, "supports_tensor_parallel", False) - fit = assess_model( - layout, _nodes(64, 64), model_id="m", prefer_tensor=True - ) + fit = assess_model(layout, _nodes(64, 64), model_id="m", prefer_tensor=True) assert fit.fits assert fit.strategy == "pipeline" @@ -482,12 +478,9 @@ def node(node_id): ) # Paired over JACCL/Thunderbolt: tensor becomes the recommendation. - registry.mark_paired( - "peer2", caps={"jaccl": True, "thunderbolt": True} - ) + registry.mark_paired("peer2", caps={"jaccl": True, "thunderbolt": True}) assert ( - cluster_routes._requested_links_fast([node(self_id), node("peer2")]) - is True + cluster_routes._requested_links_fast([node(self_id), node("peer2")]) is True ) # One slow peer in a larger pool fails the whole request closed. assert ( diff --git a/tests/test_cluster_deployment.py b/tests/test_cluster_deployment.py index 9b4f32158c..58d739c32f 100644 --- a/tests/test_cluster_deployment.py +++ b/tests/test_cluster_deployment.py @@ -159,6 +159,7 @@ def test_deployment_round_trip_preserves_tensor_parallel_size(): import base64 import json import zlib + compressed = base64.b64decode(encoded, altchars=b"-_") raw = zlib.decompress(compressed) payload = json.loads(raw) @@ -360,9 +361,7 @@ def test_the_role_survives_the_worker_plan_and_the_registry_file(): ) # The registry writes and reloads this. - restored = ClusterDeployment.from_dict( - json.loads(json.dumps(deployment.to_dict())) - ) + restored = ClusterDeployment.from_dict(json.loads(json.dumps(deployment.to_dict()))) # The rank decodes this. _hash, decoded = decode_worker_plan(deployment.encode_worker_plan()) diff --git a/tests/test_cluster_modelsync.py b/tests/test_cluster_modelsync.py index c91d588767..09751b9f83 100644 --- a/tests/test_cluster_modelsync.py +++ b/tests/test_cluster_modelsync.py @@ -37,12 +37,14 @@ compare_manifests, parse_rsync_progress, ) -from omlx.cluster.planner import PipelineAssignment, synthetic_model_layout, ShardPlan +from omlx.cluster.planner import PipelineAssignment, ShardPlan, synthetic_model_layout from omlx.cluster.registry import ClusterRegistry def _write_shard(directory, name, tensors, payload=b"\x00" * 32): - header = {t: {"dtype": "F16", "shape": [1], "data_offsets": [0, 2]} for t in tensors} + header = { + t: {"dtype": "F16", "shape": [1], "data_offsets": [0, 2]} for t in tensors + } blob = json.dumps(header).encode() (directory / name).write_bytes(struct.pack(" Path: del entry["path_map"] path = base / "cluster" / "deployments.json" path.parent.mkdir(parents=True) - path.write_text( - json.dumps({"schema_version": 1, "deployments": [entry]}, indent=2) - ) + path.write_text(json.dumps({"schema_version": 1, "deployments": [entry]}, indent=2)) return path @@ -400,9 +398,7 @@ def test_legacy_deployments_json_migrates_on_load(tmp_path): def test_registry_round_trip_preserves_path_map(tmp_path): model = tmp_path / "model" model.mkdir() - deployment = _deployment( - str(model), path_map={"peer": "/Volumes/models/copy"} - ) + deployment = _deployment(str(model), path_map={"peer": "/Volumes/models/copy"}) registry = ClusterRegistry(tmp_path) registry.upsert(deployment) @@ -419,15 +415,9 @@ def test_registry_round_trip_preserves_path_map(tmp_path): def test_auto_method_prefers_rsync_for_large_models_with_ssh_trust(): manager = ModelSyncManager(ssh_trust=lambda target: True) - assert ( - manager.decide_method("user@peer", AUTO_RSYNC_THRESHOLD_BYTES + 1) - == "rsync" - ) + assert manager.decide_method("user@peer", AUTO_RSYNC_THRESHOLD_BYTES + 1) == "rsync" # At or below 20 GiB each node downloads its own shard files instead. - assert ( - manager.decide_method("user@peer", AUTO_RSYNC_THRESHOLD_BYTES) - == "download" - ) + assert manager.decide_method("user@peer", AUTO_RSYNC_THRESHOLD_BYTES) == "download" # No enrolled SSH trust: download regardless of size. untrusted = ModelSyncManager(ssh_trust=lambda target: False) assert ( @@ -543,8 +533,11 @@ def failing_rsync(argv, on_line): with pytest.raises(ModelSyncError, match="status 23"): manager.sync( - "peer", str(root), "rsync", - ssh_target="user@peer", on_progress=events.append, + "peer", + str(root), + "rsync", + ssh_target="user@peer", + on_progress=events.append, ) assert events[-1].phase == "error" @@ -592,7 +585,9 @@ def test_sync_auto_selects_rsync_for_large_models(tmp_path): def test_build_rsync_argv_is_resumable_and_noninteractive(): argv = build_rsync_argv( - "/models/src", "user@peer.local", "/Volumes/models/dst", + "/models/src", + "user@peer.local", + "/Volumes/models/dst", ssh_identity="~/.ssh/omlx_cluster", ) @@ -642,7 +637,6 @@ def test_allow_patterns_reject_inverted_range(tmp_path): def test_preflight_uses_per_node_model_paths(monkeypatch): - from omlx.cluster import launch from omlx.cluster.launch import _local_runtime_versions, preflight_remote_hosts from omlx.cluster.models import CLUSTER_PROTOCOL_VERSION diff --git a/tests/test_cluster_proportional_plan.py b/tests/test_cluster_proportional_plan.py index 9a2344c054..3e71f56f59 100644 --- a/tests/test_cluster_proportional_plan.py +++ b/tests/test_cluster_proportional_plan.py @@ -126,9 +126,7 @@ def test_proportional_plan_two_unequal_nodes(): assert (by_rank[0].start_layer, by_rank[0].end_layer) == (1, 4) assert by_rank[0].node_id == "large" # Full, contiguous coverage. - covered = sorted( - (item.start_layer, item.end_layer) for item in plan.assignments - ) + covered = sorted((item.start_layer, item.end_layer) for item in plan.assignments) assert covered == [(0, 1), (1, 4)] @@ -143,17 +141,14 @@ def test_proportional_plan_three_nodes_covers_every_layer_once(): ) assert len(plan.assignments) == 3 - covered = sorted( - (item.start_layer, item.end_layer) for item in plan.assignments - ) + covered = sorted((item.start_layer, item.end_layer) for item in plan.assignments) assert covered[0][0] == 0 assert covered[-1][1] == 12 for previous, following in zip(covered, covered[1:]): assert previous[1] == following[0] # Shares 190:90:50 → counts ∝ usable RAM, descending by node size. counts = { - item.node_id: item.end_layer - item.start_layer - for item in plan.assignments + item.node_id: item.end_layer - item.start_layer for item in plan.assignments } assert counts["a"] > counts["b"] > counts["c"] assert sum(counts.values()) == 12 @@ -231,9 +226,7 @@ def test_plan_route_runs_proportional_allocator(monkeypatch): payload = response.json() assert payload["optimization"] == "ram-proportional" assert payload["placement_signature"] - counts = { - item["node_id"]: item["layer_count"] for item in payload["assignments"] - } + counts = {item["node_id"]: item["layer_count"] for item in payload["assignments"]} assert counts["a"] > counts["b"] > counts["c"] diff --git a/tests/test_cluster_replan.py b/tests/test_cluster_replan.py index cf0539222d..d4f1e387a0 100644 --- a/tests/test_cluster_replan.py +++ b/tests/test_cluster_replan.py @@ -13,9 +13,9 @@ from fastapi.testclient import TestClient from omlx.cluster import routes -from omlx.cluster.deployment import ClusterDeployment, ClusterHost -from omlx.cluster.planner import ModelLayout +from omlx.cluster.deployment import ClusterDeployment from omlx.cluster.performance import NodePerformanceProfile +from omlx.cluster.planner import ModelLayout from omlx.cluster.registry import configure_cluster_registry from omlx.cluster.replan import ( hosts_from_deployment, @@ -360,13 +360,17 @@ def test_replan_preview_detects_changed_split(active_deployment): def test_replan_applied_runs_full_dance(active_deployment): - preview = _client().post( - "/admin/api/cluster/replan", - json={ - "deployment_id": active_deployment.deployment["deployment_id"], - "target_context_tokens": 16384, - }, - ).json() + preview = ( + _client() + .post( + "/admin/api/cluster/replan", + json={ + "deployment_id": active_deployment.deployment["deployment_id"], + "target_context_tokens": 16384, + }, + ) + .json() + ) response = _client().post( "/admin/api/cluster/replan", @@ -381,8 +385,9 @@ def test_replan_applied_runs_full_dance(active_deployment): payload = response.json() assert payload["mode"] == "applied" assert payload["readiness"]["canary_passed"] is True - assert payload["replan"]["previous"]["deployment_id"] == ( - active_deployment.deployment["deployment_id"] + assert ( + payload["replan"]["previous"]["deployment_id"] + == (active_deployment.deployment["deployment_id"]) ) # One reload for the initial activation, one for the replan. assert active_deployment.pool.reloads == 2 @@ -425,13 +430,17 @@ def test_replan_refuses_to_interrupt_active_requests(tmp_path, monkeypatch): deployment_id = response.json()["deployment"]["deployment_id"] pool.busy = True - preview = _client().post( - "/admin/api/cluster/replan", - json={ - "deployment_id": deployment_id, - "target_context_tokens": 16384, - }, - ).json() + preview = ( + _client() + .post( + "/admin/api/cluster/replan", + json={ + "deployment_id": deployment_id, + "target_context_tokens": 16384, + }, + ) + .json() + ) response = _client().post( "/admin/api/cluster/replan", json={ @@ -481,7 +490,6 @@ def test_replan_without_context_requires_explicit_cluster(tmp_path, monkeypatch) def test_replan_membership_change_adds_a_node(active_deployment): """N-node replan: explicit nodes/hosts express the membership change.""" - model_path = active_deployment.model_path nodes = [ {"node_id": "large", "capacity_bytes": 100, "reserve_bytes": 10}, {"node_id": "small", "capacity_bytes": 60, "reserve_bytes": 10}, @@ -515,11 +523,10 @@ def test_replan_membership_change_adds_a_node(active_deployment): assert response.status_code == 200, response.json() payload = response.json() - assert payload["deployment"]["world_size"] if "world_size" in payload["deployment"] else True + assert payload["deployment"].get("world_size", True) assert len(payload["deployment"]["assignments"]) == 3 assert payload["replan"]["previous"]["world_size"] == 2 ranks = sorted( - (item["rank"], item["node_id"]) - for item in payload["deployment"]["assignments"] + (item["rank"], item["node_id"]) for item in payload["deployment"]["assignments"] ) assert ranks == [(0, "large"), (1, "small"), (2, "mini")] From 058912cf892fbe7c2dec05325473d7f39c88dd2e Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Wed, 26 Aug 2026 04:25:33 -0700 Subject: [PATCH 131/132] test(cluster): mark backend-first replan seam explicitly --- omlx/cluster/routes.py | 2 ++ tests/test_cluster_seams.py | 4 +++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/omlx/cluster/routes.py b/omlx/cluster/routes.py index 25ca208a9b..2693e20dcd 100644 --- a/omlx/cluster/routes.py +++ b/omlx/cluster/routes.py @@ -3537,6 +3537,8 @@ class ClusterReplanRequest(BaseModel): revert a heterogeneous-path cluster to same-path resolution. """ + model_config = ConfigDict(extra="forbid") + deployment_id: str | None = Field(default=None, max_length=128) model_path: str | None = Field(default=None, max_length=4096) model_source: str | None = Field(default=None, max_length=255) diff --git a/tests/test_cluster_seams.py b/tests/test_cluster_seams.py index 425e1235f0..59716bb2c6 100644 --- a/tests/test_cluster_seams.py +++ b/tests/test_cluster_seams.py @@ -74,7 +74,9 @@ def test_no_cluster_route_is_unreachable_from_the_dashboard(): both worth knowing about. """ - allowed_without_caller: set[str] = set() + # The backend PR intentionally lands before the Cluster v2 dashboard. The + # UI follow-up will call replan after the deployment contract settles. + allowed_without_caller: set[str] = {"/admin/api/cluster/replan"} unreachable = _registered_routes() - _js_called_paths() - allowed_without_caller assert not unreachable, ( f"cluster routes nothing calls: {sorted(unreachable)} — wire them up or " From 3218bf1dd1cf93333a8b8360c78b6133a56763d6 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Wed, 26 Aug 2026 05:01:03 -0700 Subject: [PATCH 132/132] fix(cluster): protect remote rsync paths from shell interpretation --- omlx/cluster/deployment.py | 2 ++ omlx/cluster/modelsync.py | 15 ++++++++++++++- tests/test_cluster_modelsync.py | 18 ++++++++++++++++++ 3 files changed, 34 insertions(+), 1 deletion(-) diff --git a/omlx/cluster/deployment.py b/omlx/cluster/deployment.py index 922862415b..cb14c0a5f2 100644 --- a/omlx/cluster/deployment.py +++ b/omlx/cluster/deployment.py @@ -141,6 +141,8 @@ def validate_model_path_map( if ( not path or "\x00" in path + or "\n" in path + or "\r" in path or len(path.encode()) > _MAX_MODEL_PATH_BYTES or not Path(path).is_absolute() ): diff --git a/omlx/cluster/modelsync.py b/omlx/cluster/modelsync.py index 1501151e6a..3f71841a9b 100644 --- a/omlx/cluster/modelsync.py +++ b/omlx/cluster/modelsync.py @@ -34,6 +34,7 @@ from fastapi import APIRouter, HTTPException from ..exceptions import ModelNotFoundError +from .deployment import validate_ssh_target from .ssh_policy import cluster_ssh_options from .staging import ( index_shards, @@ -311,11 +312,23 @@ def build_rsync_argv( host keys, BatchMode) — never a hand-rolled option set. """ + ssh_target = validate_ssh_target(ssh_target) + target_dir = str(destination_dir) + if ( + not Path(target_dir).is_absolute() + or "\x00" in target_dir + or "\n" in target_dir + or "\r" in target_dir + ): + raise ValueError("rsync destination must be an absolute single-line path") ssh_argv = ["ssh", *cluster_ssh_options()] if ssh_identity is not None: ssh_argv.extend(["-i", str(ssh_identity)]) source = str(Path(source_dir).expanduser()).rstrip("/") + "/" - destination = f"{ssh_target}:{destination_dir}" + # macOS ships openrsync 2.6.9 without --protect-args/-s. Quote the remote + # path inside the host:path operand so the peer shell receives one literal + # filename while retaining compatibility with the system binary. + destination = f"{ssh_target}:{shlex.quote(target_dir)}" return [ "rsync", "-a", diff --git a/tests/test_cluster_modelsync.py b/tests/test_cluster_modelsync.py index 09751b9f83..b1280562c4 100644 --- a/tests/test_cluster_modelsync.py +++ b/tests/test_cluster_modelsync.py @@ -8,6 +8,7 @@ import base64 import json import platform +import shlex import stat import struct import subprocess @@ -258,6 +259,8 @@ def test_path_map_validation(): _deployment(path_map={"peer": "relative/dir"}) with pytest.raises(ValueError, match="outside the deployment"): _deployment(path_map={"stranger": "/models/x"}) + with pytest.raises(ValueError, match="absolute"): + _deployment(path_map={"peer": "/models/x\nmalformed"}) assert validate_model_path_map(None) == {} assert validate_model_path_map({"a": "/m"}, ("a",)) == {"a": "/m"} @@ -601,6 +604,21 @@ def test_build_rsync_argv_is_resumable_and_noninteractive(): assert argv[-1] == "user@peer.local:/Volumes/models/dst" +def test_build_rsync_argv_protects_remote_paths_and_validates_targets(): + destination = "/Volumes/model copies/$(touch should-not-run)" + argv = build_rsync_argv( + "/models/src", + "user@peer.local", + destination, + ) + + assert argv[-1] == f"user@peer.local:{shlex.quote(destination)}" + with pytest.raises(ValueError, match="SSH target"): + build_rsync_argv("/models/src", "peer;touch-nope", "/models/dst") + with pytest.raises(ValueError, match="single-line"): + build_rsync_argv("/models/src", "peer.local", "/models/dst\nother") + + def test_parse_rsync_progress_lines(): assert parse_rsync_progress(" 1,234,567 42% 123.45MB/s 0:01:23") == ( 1_234_567,