From b81d700c10da875cd832ef7f79f3a56677aca4e2 Mon Sep 17 00:00:00 2001
From: Mike Wallio
Date: Wed, 4 Nov 2026 09:15:01 -0500
Subject: [PATCH 01/24] docs: document inference features and operational
guidance
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
---
AGENTS.md | 73 ++++
README.fr.md | 1 -
README.ja.md | 1 -
README.ko.md | 5 +-
README.md | 442 +++++++++++++++++++-
README.zh.md | 1 -
benchmarks/README.md | 71 ++++
docs/TESTING.md | 23 +-
docs/custom-kernels.md | 5 +
docs/demos/claude-discovery.cast | 40 ++
docs/experimental/dflash_mlx_integration.md | 5 +-
docs/experimental/qwen35_compiled_mlp.md | 35 ++
docs/experimental/qwen38_mtp_depth_head.md | 49 +++
docs/oQ_Quantization.md | 12 +-
14 files changed, 744 insertions(+), 19 deletions(-)
create mode 100644 AGENTS.md
create mode 100644 benchmarks/README.md
create mode 100644 docs/demos/claude-discovery.cast
create mode 100644 docs/experimental/qwen35_compiled_mlp.md
create mode 100644 docs/experimental/qwen38_mtp_depth_head.md
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 0000000000..1b22e79b59
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,73 @@
+# oMLX agent guide
+
+## Project overview
+
+oMLX is a Python/FastAPI inference server for Apple Silicon Macs. It serves OpenAI-, Anthropic-, and Responses-compatible APIs over MLX models, with continuous batching, multi-model loading, VLM/audio/embedding/reranker engines, MCP tools, and tiered KV caching.
+
+Keep durable shared guidance in this file. Add nested `AGENTS.md` files only for directories with meaningfully different rules, and avoid scoped Copilot instruction files unless they add targeted value beyond these repo-wide rules.
+
+This is a fork maintained by rebasing onto `upstream/main`; its history is intentionally not kept stable. Squashing/rewriting the fork's commits since the `upstream/main` merge-base and force-pushing (`git push --force-with-lease`) is acceptable when cleaning up. Always create a `backup/*` tag before a destructive rewrite, and verify the rewrite changed no code (`git diff HEAD` is empty) before pushing. When regrouping heavily interleaved commits (features scattered among dependency bumps and rebase-cleanup chores), prefer `git reset --soft ` then re-stage per file into logical commits over an interactive reorder; the soft-reset approach keeps the final tree byte-identical and avoids reorder conflicts on shared files such as `pyproject.toml`, `README.md`, and `AGENTS.md`. The regroup pattern that stays byte-identical is a stable file-to-group mapping (image engine/registry/routes + admin Imagine + i18n; audio/video API + VLM; server/admin-chat; upstream-rebase reconciliation; git-pinned deps; Copilot integration). Because `git reset --soft`/mixed reset does NOT scrub the working tree, run the regroup only from a verified-clean checkout of the original tip (`git status` empty and `git rev-parse HEAD^{tree}` equal to the backup tree); a dirty tree left over from diagnostics silently commits stale file content and breaks tree identity. If a run drifts, `git reset --hard ` and re-run rather than patching in place. **Never use `git stash` during a merge** — it can discard `MERGE_HEAD` and break the index, leaving you stranded without merge state or staged conflict resolutions. Pushing requires the `scaryrawr` account: the default git credential helper (gcm-core / a `copilot` host helper) can resolve to a different account and 403; push with `gh auth switch --user scaryrawr` active plus an inline helper override, e.g. `git -c credential.helper= -c 'credential.https://github.com.helper=!gh auth git-credential' push --force-with-lease origin main`, then unset any local `credential.helper` entries you added.
+
+Key areas:
+
+- `omlx/server.py` wires the FastAPI app, route handlers, auth, streaming responses, and server state.
+- `omlx/cli.py`, `omlx/settings.py`, and `omlx/config.py` handle startup, persisted settings, CLI/env/file precedence, and user-visible defaults.
+- `omlx/engine_pool.py` discovers models, selects engine types, tracks loaded engines, and enforces LRU/pinning behavior.
+- `omlx/scheduler.py`, `omlx/engine/`, and `omlx/engine_core.py` own request scheduling and MLX generation.
+- `omlx/utils/model_loading.py` and `omlx/model_discovery.py` handle model loading, tokenizer setup, model classification, and image-manifest discovery. Keep `model_discovery.py`'s image exports aligned with `engine_pool.py`; validate `import omlx.server` after discovery refactors so missing cross-module exports fail fast.
+- `omlx/cache/` owns paged, prefix, hot, SSD, hybrid, vision-feature, and recovery cache behavior. Treat cache serialization and MLX buffer lifetime carefully.
+- `omlx/api/` contains API models, protocol adapters, route helpers, tool calling, thinking parsing, structured output, and SSE formatting.
+- `omlx/adapter/` contains model-family output parsers and Harmony/Gemma-specific adaptation; keep model quirks there instead of in generic server paths.
+- `omlx/admin/` contains the admin HTTP API and utilities; `apps/omlx-web/omlx_web/` owns browser routes, templates, static assets, and i18n files, packaged in the same wheel. Keep web rendering independent of `omlx` imports through `WebUIHost`.
+- `omlx/integrations/`, `omlx/mcp/`, and `omlx/eval/` cover editor/client setup, MCP execution, and evaluation helpers.
+- `packaging/` builds the macOS menubar app bundle and DMG using venvstacks.
+
+## Setup and validation
+
+Use `uv run` for Python tooling and tests. If dependencies are missing, start with `uv sync --dev`. Pin validation commands to Python 3.12 (for example, `UV_PYTHON=python3.12 uv run --python python3.12 pytest ...`): `onnxruntime==1.20.1` does not support CPython 3.14. MLX is pinned to 0.32.4 and xgrammar to 0.2.8; rebuild local custom kernels after MLX upgrades with `OMLX_WITH_CUSTOM_KERNEL=1 uv pip install --python .venv/bin/python --reinstall --no-deps -e .`. Native floating-point QMM wrappers must match MLX's template parameters and global-scale argument, even when global scaling is disabled.
+
+`uv.lock` is intentionally ignored in this repository; dependency pin changes should be tracked in `pyproject.toml` unless a task explicitly changes the lockfile policy.
+
+When bumping git-sourced dependencies, audit `[project].dependencies`, `[project.optional-dependencies]`, and `tool.uv.override-dependencies`; compare the upstream dependency metadata at the new commit (`pyproject.toml`, `requirements.txt`, or equivalent) for changed version constraints that must be mirrored locally; also check mirrors in `packaging/build.py`, `omlx/admin/routes.py` engine metadata, `Formula/omlx.rb`, `tests/test_admin_engine_info.py`, and user-facing install examples such as `README.md`. Some packaging paths intentionally duplicate pins from `pyproject.toml`; if an optional extra pin changes, run targeted validation with that extra enabled (for example `uv sync --dev --extra audio` for `mlx-audio`). For `mlx-lm` bumps, validate the scheduler and MTP BatchGenerator integration against upstream API shape changes such as stop matching (`StopSequenceMatcher` / `stop_matchers` in current pins, replacing older `SequenceStateMachine` / `state_machines`) and `GenerationBatch.Response` fields; keep every MTP response construction routed through `_generation_response`, including unfinished singleton emissions. For `mlx-vlm` bumps, smoke Qwen3.5 dense and MoE VLM generation when available: model loading alone does not exercise oMLX patches whose upstream helper APIs or call signatures may have changed. When native MTP is enabled, include a multi-token verify/rejection cycle and confirm rollback states are returned without cache-rebuild warnings; a one-token smoke does not exercise the dedicated speculative verifier.
+
+- Default fast test run: `uv run pytest`
+- Explicit fast test selection: `uv run pytest -m "not slow and not integration"`
+- Narrow test run: `uv run pytest tests/test_config.py -v`
+- Lint: `uv run ruff check .` is the intended Python lint command, but the current tree may have pre-existing full-repo ruff diagnostics; when a task is not a lint cleanup, prefer `uv run ruff check ` plus focused tests and call out any baseline failures separately. Do not include non-Python files such as `README.md` or `Formula/*.rb` in Ruff path lists; use `git diff --check` for whitespace on mixed-file changes. Ruff's SIM118 suggestion is unsafe for `safetensors.safe_open` handles in this environment; keep `f.keys()` there and add a targeted `# noqa: SIM118` if needed.
+- Type check: `uv run mypy omlx`
+- Format when needed: `uv run black .`
+- macOS app build checks live under `packaging/`; see `packaging/README.md` before running `python build.py`.
+
+`pytest.ini` defaults to verbose tests excluding `slow` and `integration`. Mark tests that require real model files with `@pytest.mark.slow`, and tests that require a live server with `@pytest.mark.integration`.
+
+For manual server smoke tests, remember `omlx serve` persists non-default CLI flags to `~/.omlx/settings.json`. Prefer a disposable base path such as `--base-path "$(mktemp -d /tmp/omlx-smoke.XXXXXX)"` for temporary runs with flags such as `--model-dir`, `--memory-guard`, or `--max-concurrent-requests`; use `--memory-guard aggressive` for light smoke runs rather than disabling the guard with `off`. If the Homebrew service is already running, prefer an isolated temporary server on an alternate port rather than stopping the service unless you specifically need to validate the service instance. Treat a temporary server as a persistent readiness-gated process, not a bounded command: inspect startup output immediately, probe its health or target endpoint as soon as it reports ready, run the dependent smoke request, and then stop it; never wait for the server process to exit or for a completion notification. When `brew services` is slow or hangs, manage the service directly with the user launch agent label/path (`homebrew.mxcl.omlx`, `~/Library/LaunchAgents/homebrew.mxcl.omlx.plist`) via `launchctl list`, `launchctl bootout`, and `launchctl bootstrap`. For unauthenticated smoke servers, unset `OMLX_API_KEY` before launching; if auth is enabled, the generated key is stored under `auth.api_key` in that temporary settings file. Restart any stopped Homebrew service afterward, and verify it on the configured `server.port` from `~/.omlx/settings.json` rather than assuming the default 8000. Query `/v1/models` before smoke requests and use the returned IDs; models stored under nested `owner/model` directories may be served by basename. For Responses API smoke tests, validate nested `.output[].content[].text` in addition to any convenience `.output_text` field. For lightweight image-generation smoke tests with local mlx-vlm models, use the core mlx-vlm dependency and at least two steps because `steps=1` can fail inside backend progress math rather than validating route behavior. For local image-edit smoke tests with large inputs, prefer multipart `/v1/images/edits` uploads (`-F image=@...`, plus `prompt`, `model`, `steps`, `guidance`, and `image_strength` fields) over JSON data URIs to avoid shell/base64 argument-size limits.
+
+## Code conventions
+
+- Keep the Apache 2.0 SPDX header at the top of Python source and test files.
+- Prefer dataclasses for configuration and request/response state where surrounding code already uses them.
+- Keep protocol-specific conversion in `omlx/api/` or `omlx/api/adapters/`; avoid mixing API wire-format logic into scheduler/cache internals.
+- Preserve async boundaries: FastAPI handlers and engine orchestration are async, while MLX generation is isolated through scheduler/engine abstractions.
+- Keep optional dependency behavior explicit. Extras such as `mcp`, `audio`, `grammar`, `image`, `modelscope`, and `paroquant` are intentionally separated; use availability helpers such as `omlx/utils/optional_deps.py` rather than importing heavy optional packages in core paths.
+- For Copilot CLI integration launches, keep `COPILOT_OFFLINE=true` so subagents do not fall back to GitHub-hosted services. The launcher persists the omlx provider into `~/.copilot/providers.json` (honoring `COPILOT_PROVIDERS_CONFIG`): merge into the existing file, clobber only entries whose provider name/id is `omlx`, preserve all foreign providers/models and unknown top-level keys, keep the file `0600`, and back up before rewriting (skip the write when content is unchanged).
+- When adding admin UI i18n keys, update every file under `apps/omlx-web/omlx_web/i18n/*.json` (including `pt-BR.json`) and run focused tests or JSON parsing checks that cover missing locale keys.
+- Admin templates ship with precompiled `apps/omlx-web/omlx_web/static/css/tailwind.css`; if you use new arbitrary Tailwind classes (for example `w-[...]`, `h-[...]`, `z-[...]`, or dynamic responsive grid classes), either rebuild and commit the CSS or prefer local semantic CSS in the template so installed pages do not lose layout.
+- For image generation/edit defaults, keep request-level `steps`/`guidance`/`image_strength` overrides ahead of manifest `default_*` values, and manifest values ahead of `omlx/image_registry.py` family defaults; resolve family defaults through canonical base-model aliases so every supported alias gets the same behavior, and cover changes with focused `tests/test_image_engine.py` cases. Family-level defaults must be backed by mlx-vlm model configuration or manifests rather than subjective manual results.
+- For mlx-vlm image editing, preserve each family’s documented input contract: FLUX.2 and Mage-Flow edit support multi-image requests, while Z-Image and ERNIE-Image require exactly one source image. Current mlx-vlm image families do not support masks. Route `image_strength` through request extras as both `strength` and `image_strength` so Z-Image and ERNIE-Image receive their respective names.
+- For VLM/chat media handling, prefer `omlx/utils/image.py`'s `extract_media_from_messages()` in engine paths so image, audio, and video handling stays aligned; keep `extract_images_from_messages()` as compatibility-only unless a three-value API is specifically required.
+- Keep Pixtral serving preprocessing MLX-resident via `return_tensors="mlx"` while preserving the image processor's default NumPy output for compatibility.
+- For VLM speculative decoding, keep standalone MTP drafter artifacts such as `gemma4_assistant`, `gemma4_unified_assistant`, and `qwen3_5_mtp` out of normal model discovery; they are loaded through parent VLM drafter paths and are not chat-capable models.
+- In SpecPrefill chunk selection, reduce chunk scores in one MLX operation and transfer the score vector once; per-chunk `.item()` calls serialize GPU work. Preserve deterministic Python tie ordering.
+- For model-family patches under `omlx/patches/`, keep changes narrow and covered by focused regression tests. These files mirror upstream behavior and can be brittle across dependency updates.
+- When a model-family patch changes checkpoint sanitization or quantization metadata, test a complete tiny synthetic checkpoint through the real loader with `strict=True`; helper-only conversion tests do not catch config normalization, module replacement, or unexpected/missing binding keys.
+- For affine PLE dequantization, promote mixed floating-point scales and biases to their shared MLX result dtype before calling `mx.dequantize`; its Metal kernel reads both buffers using one scalar type. Keep MXFP scales as `uint8` and preserve the precision of checkpoint metadata.
+- When changing cache, scheduler, streaming, adapters, or tool-call behavior, add focused tests for token accounting, finish reasons, cancellation/disconnect behavior, cache reuse/regression paths, and protocol output shape.
+- Keep streaming `RequestOutput.output_token_ids` empty until the terminal output to avoid quadratic cumulative-list copies; streaming consumers should use `new_token_ids`, while terminal and non-streaming consumers receive the complete token sequence.
+
+## Safety notes
+
+- The project targets Apple Silicon and MLX. Avoid adding torch-heavy dependencies to core paths unless they are guarded by an optional extra.
+- Do not enable Hugging Face `trust_remote_code` by default; tests assert the safer default.
+- Do not swallow MLX, GPU synchronization, cache corruption, model-loading, or settings-persistence errors with broad fallbacks. Surface errors through existing exception types in `omlx/exceptions.py`, route-level HTTP error mapping, or explicit user-facing warnings consistent with nearby code.
+- Do not run slow/integration/model-loading tests unless the task needs them and the environment has the required models or server.
+- Be careful with commands that build the macOS app or DMG; they can be expensive and may write large artifacts under `packaging/build/` and `packaging/dist/`.
diff --git a/README.fr.md b/README.fr.md
index 6d453364e6..596d4bdaca 100644
--- a/README.fr.md
+++ b/README.fr.md
@@ -405,5 +405,4 @@ Les contributions sont les bienvenues ! Voir le [Guide de contribution](docs/CON
- [mlx-vlm](https://github.com/Neywa-Labs/mlx-vlm) — inférence de modèles vision-langage sur Apple Silicon
- [vllm-mlx](https://github.com/waybarrios/vllm-mlx) — oMLX a démarré à partir de vllm-mlx v0.1.0 et a considérablement évolué avec le service multi-modèles, le cache KV à plusieurs niveaux, le support VLM avec cache paginé complet, un panneau d'admin, et une app dans la barre de menus macOS
- [venvstacks](https://venvstacks.lmstudio.ai) — couches d'environnements Python portables pour le bundle de l'app macOS
-- [mlx-embeddings](https://github.com/Blaizzy/mlx-embeddings) — support des modèles d'embedding sur Apple Silicon
- [dflash-mlx](https://github.com/bstnxbt/dflash-mlx) — décodage spéculatif par diffusion par blocs sur Apple Silicon
diff --git a/README.ja.md b/README.ja.md
index 7cb83bbe00..bf0450bdbf 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -402,5 +402,4 @@ apps/omlx-mac/Scripts/build.sh release --rebuild-donor
- [mlx-vlm](https://github.com/Neywa-Labs/mlx-vlm) - Apple Siliconでのビジョン言語モデル推論
- [vllm-mlx](https://github.com/waybarrios/vllm-mlx) - oMLXはvllm-mlx v0.1.0からスタートし、マルチモデルサービング、階層型KVキャッシュ、完全なページドキャッシュ対応のVLM、管理画面、macOSメニューバーアプリへと大きく進化しました
- [venvstacks](https://venvstacks.lmstudio.ai) - macOSアプリバンドルのためのポータブルPython環境レイヤリング
-- [mlx-embeddings](https://github.com/Blaizzy/mlx-embeddings) - Apple Silicon向けエンベディングモデルサポート
- [dflash-mlx](https://github.com/bstnxbt/dflash-mlx) - Apple Siliconでのブロック拡散 speculative decoding
diff --git a/README.ko.md b/README.ko.md
index b116d7b434..4b624904f4 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -310,8 +310,8 @@ mlx-lm에서 사용 가능한 모든 함수 호출 형식, JSON 스키마 검증
| LLM | [mlx-lm](https://github.com/ml-explore/mlx-lm)이 지원하는 모든 모델 |
| VLM | Qwen3.5 시리즈, GLM-4V, Pixtral 및 기타 [mlx-vlm](https://github.com/Neywa-Labs/mlx-vlm) 모델 |
| OCR | DeepSeek-OCR, DOTS-OCR, GLM-OCR |
-| 임베딩 | BERT, BGE-M3, ModernBERT, EmbeddingGemma 2 |
-| 리랭커 | ModernBERT, XLM-RoBERTa |
+| 임베딩 | BERT, BGE-M3, ModernBERT, EmbeddingGemma, EmbeddingGemma 2, Qwen3-Embedding, Qwen3-VL-Embedding, SigLIP (text only) via [mlx-vlm](https://github.com/Blaizzy/mlx-vlm) or native loaders |
+| 리랭커 | ModernBERT, XLM-RoBERTa, Qwen3-Reranker, Qwen3-VL-Reranker |
| Decision | Clef, Clef-Flash, OpenJev, Decision 3.0 (d3, d3-flash, d3-mini, d3-nano, d3-lite, d3-edge) |
## CLI 설정
@@ -446,7 +446,6 @@ apps/omlx-mac/Scripts/build.sh release --rebuild-donor
- [mlx-vlm](https://github.com/Neywa-Labs/mlx-vlm) - Apple Silicon에서의 비전-언어 모델 추론
- [vllm-mlx](https://github.com/waybarrios/vllm-mlx) - oMLX는 vllm-mlx v0.1.0에서 시작하여 멀티 모델 서빙, 계층형 KV 캐시, 페이지드 캐시를 완전 지원하는 VLM, 관리자 패널, macOS 메뉴 바 앱으로 크게 발전했습니다
- [venvstacks](https://venvstacks.lmstudio.ai) - macOS 앱 번들을 위한 포터블 Python 환경 레이어링
-- [mlx-embeddings](https://github.com/Blaizzy/mlx-embeddings) - Apple Silicon을 위한 임베딩 모델 지원
- [dflash-mlx](https://github.com/bstnxbt/dflash-mlx) - Apple Silicon에서의 블록 디퓨전 speculative decoding
- [MTPLX](https://github.com/youssofal/mtplx) - Lightning MTP의 verify-shape Metal 커널은 Youssof Altoukhi의 MTPLX를 기반으로 하며, depth-k 파이프라인도 여기서 영감을 받았습니다
- [mlx-serve](https://github.com/ddalcu/mlx-serve) - Qwen GDN·QSA 커널(하나는 mlx-serve의 mlxfast-challenge 포팅)과 Linux 헬퍼의 expert 커널·MLX CUDA 패치는 mlx-serve의 MIT 라이선스 코드를 바탕으로 수정되었습니다
diff --git a/README.md b/README.md
index b878d719b3..10762cb902 100644
--- a/README.md
+++ b/README.md
@@ -69,6 +69,8 @@ omlx start
# Optional: MCP (Model Context Protocol) support, then restart to load it
/opt/homebrew/opt/omlx/libexec/bin/pip install mcp
omlx restart
+
+# mlx-vlm image generation and editing support is included with oMLX.
```
### From Source
@@ -81,6 +83,10 @@ make install # Editable install with the web UI and native custom
make mcp # Optional: MCP support, restart `omlx serve` to load it
```
+Image generation and editing use the core `mlx-vlm` dependency. The retained
+`image` extra is a no-op compatibility alias; source and released installs do
+not need it.
+
Requires macOS 15.0+ (Sequoia), Python 3.11–3.13, and Apple Silicon (M1/M2/M3/M4/M5).
> **Note on native custom kernels:** GLM-5.2, MiniMax M3, and Qwen3.5 need them.
@@ -100,6 +106,9 @@ Requires macOS 15.0+ (Sequoia), Python 3.11–3.13, and Apple Silicon (M1/M2/M3/
> python -c "from omlx.custom_kernels import native_kernel_status; print(native_kernel_status())"
> ```
+Core installs include text, VLM, embedding, reranker, and mlx-vlm image
+generation/editing support. MCP remains optional via the `mcp` extra.
+
## Quickstart
### macOS App
@@ -123,7 +132,7 @@ omlx restart
omlx serve --model-dir ~/models
```
-The server discovers LLMs, VLMs, embedding models, and rerankers from subdirectories automatically. Any OpenAI-compatible client can connect to `http://localhost:8000/v1`. A built-in chat UI is also available at `http://localhost:8000/admin/chat`.
+The server discovers LLMs, VLMs, embedding models, rerankers, and image model manifests from subdirectories automatically. Any OpenAI-compatible client can connect to `http://localhost:8000/v1`. A built-in chat UI is also available at `http://localhost:8000/admin/chat`.
### Homebrew Service
@@ -148,7 +157,8 @@ Logs are written to two locations:
## Features
-Supports text LLMs, vision-language models (VLM), OCR models, embeddings, and rerankers on Apple Silicon.
+Supports text LLMs, vision-language models (VLM), OCR models, embeddings,
+rerankers, and mlx-vlm image generation/editing models on Apple Silicon.
### Admin Dashboard
@@ -181,7 +191,9 @@ NVIDIA GPUs running [omlx-cuda-helper](apps/omlx-cuda-helper/README.md).
### Vision-Language Models
-Run VLMs with the same continuous batching and tiered KV cache stack as text LLMs. Supports multi-image chat, base64/URL/file image inputs, and tool calling with vision context. MiMo V2.6 checkpoints with bundled sidecars also accept sampled-frame video and 24 kHz audio. Qwen3.5, Qwen3.6 and Qwen3.8 checkpoints (dense and MoE) accept native video input as base64 `video_url` / `input_video` data URIs; video needs OpenCV (`opencv-python-headless`). oQ conversion of official MiMo V2.6 checkpoints preserves image and audio support. OCR models (DeepSeek-OCR, DOTS-OCR, GLM-OCR) are auto-detected with optimized prompts.
+Run VLMs with the same continuous batching and tiered KV cache stack as text LLMs. Supports multi-image chat, base64/URL/file image inputs, and tool calling with vision context. MiMo V2.6 checkpoints with bundled sidecars also accept sampled-frame video and 24 kHz audio. Qwen3.5, Qwen3.6 and Qwen3.8 checkpoints (dense and MoE) accept native video input as base64 `video_url` / `input_video` data URIs; the fork also accepts `input_video: {"data": "", "format": "mp4"}` and inline video file attachments. Video needs OpenCV (`opencv-python-headless`) and cannot be combined with images or audio in one native-video request. Remote video URLs and local file paths are rejected. oQ conversion of official MiMo V2.6 checkpoints preserves image and audio support. OCR models (DeepSeek-OCR, DOTS-OCR, GLM-OCR) are auto-detected with optimized prompts.
+
+Qwen3.8-Flash-Next (`qwen4_exp`) PLE SSD offloading supports dense/raw-FP8, affine, and native MXFP4 embedding shards, including mixed storage layouts. Native MXFP4 uses packed U32 weights and U8 scales (4 bits, group size 32, no biases). The mmap path reads and dequantizes only requested rows, keeping the full PLE table off the GPU without converting the checkpoint.
### Tiered KV Cache (Hot + Cold)
@@ -204,9 +216,20 @@ Handles concurrent requests through mlx-lm's BatchGenerator. Max concurrent requ
Runs smaller context models with Claude Code by reporting the model's real context window to auto-compact instead of scaling token counts, and SSE keep-alive prevents read timeouts during long prefill.
+`omlx launch claude` enables [gateway model discovery](https://code.claude.com/docs/en/llm-gateway-protocol#model-discovery).
+Claude Code's `/model` picker lists visible chat models and exposed profiles with at least 48K context, or an unknown context limit.
+The launcher uses `/claude` as its Anthropic base path.
+That path advertises models with an `omlx-claude/` prefix because Claude Code filters out IDs without `claude` or `anthropic`.
+Messages and token-count requests on that path remove one prefix before normal model and profile resolution.
+The standard `/v1/models` catalog and Claude Desktop configuration stay unchanged.
+Use Claude Code v2.1.257 or later for discovery while nonessential traffic is disabled, as it is by default in the launcher.
+Context and auto-compact overrides remain process-wide, so the launcher uses the smallest known context limit among the initial model, configured tiers, and discoverable chat models.
+If the discovery preflight fails, the launcher warns and caps both overrides at the 48K discovery minimum.
+Models added after launch appear at the next Claude Code startup.
+
### Multi-Model Serving
-Load LLMs, VLMs, embedding models, and rerankers within the same server. Models are managed through a combination of automatic and manual controls:
+Load LLMs, VLMs, embedding models, rerankers, and image models within the same server. Models are managed through a combination of automatic and manual controls:
- **LRU eviction**: Least-recently-used models are evicted automatically when memory runs low.
- **Manual load/unload**: Interactive status badges in the admin panel let you load or unload models on demand.
@@ -246,6 +269,10 @@ Search and download models from HuggingFace directly in the admin dashboard, in
+### Model Upload Tracking
+
+Open **Models > Uploader** to view the upload queue, including jobs started before a page refresh or from another client. Tracking does not require revalidating your HuggingFace token. The queue refreshes automatically while the Uploader tab is open; **Refresh uploads** requests a fresh status without restarting an upload. If refresh fails, the last-known tasks remain visible with a warning. The animated upload indicator shows activity, not a byte percentage; pending jobs wait for the current upload to finish.
+
### Integrations
Set up OpenClaw, OpenCode, Codex, Hermes Agent, Copilot, Pi, Mistral Vibe, and DeepSeek Harness directly from the admin dashboard with a single click. No manual config editing required.
@@ -260,6 +287,120 @@ Set up OpenClaw, OpenCode, Codex, Hermes Agent, Copilot, Pi, Mistral Vibe, and D
Install [Mistral Vibe](https://github.com/mistralai/mistral-vibe) 2.26.0 or newer with `uv tool install mistral-vibe`, then run `omlx launch vibe` to select a local model, or `omlx launch vibe --model `. Vibe's provider, model, API-key reference and context window are configured for that process through its `VIBE_*` environment overrides. Existing `config.toml`, `VIBE_HOME`, tool permissions and cloud configuration are preserved. Pass Vibe arguments after `--`, for example `omlx launch vibe --model -- --resume`.
+#### OpenCode model switching
+
+OpenCode 2 is required. Run `omlx launch opencode` to register available chat
+models in its global configuration. Use `/models` to switch models, or pass `--model ` to
+choose the initial default. Without that flag, oMLX uses the saved OpenCode
+model, the server default, or the first available chat model, in that order.
+
+The launcher updates `opencode.jsonc` if it exists, otherwise `opencode.json`
+under `$XDG_CONFIG_HOME/opencode` or `~/.config/opencode`. It reads comments and
+trailing commas but rewrites the file as plain JSON with two-space indentation.
+The launcher attempts to back up the original file, including comments and
+formatting, before writing. An existing `.jsonc` filename is retained; plain JSON
+is valid JSONC. Other providers and manually configured models are preserved. Models no
+longer reported by oMLX remain in the file; remove them manually if needed. If
+discovery fails, the existing model list is preserved and an explicitly requested
+chat model is added as the default. If no model can be selected, OpenCode uses its
+existing default. The output limit leaves at least one quarter of the context
+window for input. When a refreshed model has no usable context, reasoning, or model-type
+metadata, existing values are preserved because they may be manually
+configured. The launcher warns that those values may be stale and retains
+configured tool capabilities. The config and backup files use Unix mode `0600`
+because they can contain an API key; existing ACLs may grant additional access.
+A malformed config stops the launch without replacing it.
+
+Audio-capable chat models also advertise audio input when oMLX recognizes their
+checkpoint's audio-encoder weights; this does not load the model. Stripped Gemma
+4 checkpoints without audio weights are not advertised as audio-capable.
+When audio detection is inconclusive (including older servers), manually
+configured audio input is preserved. The running server must use the updated
+code to report audio support; updating only the launcher is not sufficient.
+The launcher warns when the server does not expose this metadata.
+
+Changed existing configs receive a timestamped `.bak` file using the same
+best-effort backup-and-write helper as other integrations. If backup creation
+fails, oMLX warns and still writes the config. Concurrent edits are not protected,
+so avoid editing the file while launching. Unchanged configs are not rewritten.
+Symlinked, hard-linked, and non-owned config files are rejected.
+
+The launcher uses `$OPENCODE_CONFIG_DIR` instead of the default directory when
+set. Project, managed, and explicit OpenCode settings can override the global configuration.
+Only the current `providers` format is updated; legacy `provider` settings are
+left untouched and are not migrated.
+
+An already-running OpenCode 2 shared service may initially use a cached catalog;
+its file watcher can refresh the catalog later. Run `opencode reload` after the
+launcher writes the configuration, or pass
+`-- --standalone` to launch a private OpenCode server with the updated config.
+Reload rebuilds every loaded location and cancels pending permissions and forms
+in all projects. The launcher does not reload the shared service automatically.
+An explicitly selected `--server` may not use this local configuration at all.
+
+#### Codex model switching
+
+```bash
+omlx launch codex
+omlx launch codex_app
+# Optionally select the initial model; other models remain available:
+omlx launch codex --model your-model-id
+```
+
+Both integrations refresh a Codex model catalog from oMLX's available chat models,
+so you can switch models with the CLI's `/model` selector or the desktop app's
+model picker instead of selecting just one model before launch. Without `--model`,
+oMLX uses the saved Codex integration model when available, otherwise the
+oMLX default model (including its served alias). If neither is available,
+it falls back to the first chat model returned by the server (favorites first).
+The selected model starts loading in the background before Codex opens; launch
+does not wait for loading to finish. Warm-up request failures produce a warning
+without preventing launch, and normal inference can still load the model on demand.
+
+The catalog preserves served aliases and exposed profiles, includes unloaded
+models that oMLX can load on demand, and records each model's context window and
+text/image input support. Embedding, reranking, audio, and image-generation models
+are excluded when their type is available from the model status endpoint. If
+status is unavailable, the public model listing supplies context limits and input
+support defaults to text-only. Models with native reasoning-effort metadata
+advertise their supported levels. Models without it accept `low`, `medium`, and
+`high` as compatibility values; templates without effort controls ignore these
+values, and existing thinking defaults remain unchanged. This also lets Codex
+Desktop's low-effort background title generator prefer the launch-default model
+instead of loading another checkpoint solely for its effort metadata.
+
+Requires a Codex version supporting
+[`model_catalog_json`](https://developers.openai.com/codex/config-reference/#model_catalog_json).
+The catalog is loaded at startup: relaunch through oMLX after adding or removing
+models, changing aliases, or updating model settings. Restart an already-running
+desktop app to apply the refreshed configuration. The CLI uses process-scoped
+provider/catalog overrides without changing your `config.toml`; the desktop
+integration backs up and updates that file as before. A custom `CODEX_HOME` is
+respected, and oMLX's generated catalogs do not overwrite other catalog files.
+
+#### Copilot CLI model switching
+
+Run `omlx launch copilot` or `omlx launch copilot --model your-model-id`.
+Like Codex, Copilot starts with the saved integration model, the oMLX default,
+or the first available chat model, and its `/model` picker can switch among
+the server's chat models. The launch-time provider registry includes per-model
+context limits, image support and available reasoning-effort levels; relaunch
+to refresh it after model changes. Explicitly selected models start loading in
+the background. When a context limit is unavailable, the registry uses a
+32,768-token fallback; this does not increase a model's actual capacity.
+
+oMLX runs Copilot in offline mode using the Responses API and stores its
+provider in the CLI's `providers.json` (`~/.copilot/providers.json`, or the
+file named by `COPILOT_PROVIDERS_CONFIG`). Relaunches refresh only the
+omlx-owned provider/model entries; providers and models you configured
+yourself are preserved, and the previous file is backed up before rewriting.
+The file is kept at `0600` because it contains the server's bearer token in
+plaintext, and it remains after Copilot exits so later CLI sessions can use
+the models. This requires a Copilot CLI version supporting `providers.json`.
+User-specified global context/reasoning overrides in CLI configuration can still
+take precedence over catalog metadata; the desktop integration clears these
+overrides so limits follow the selected model.
+
### Performance Benchmark
One-click benchmarking from the admin panel. Measures prefill (PP) and text generation (TG) tokens per second, with partial prefix cache hit testing for realistic performance numbers.
@@ -288,6 +429,8 @@ Drop-in replacement for OpenAI and Anthropic APIs. Supports streaming usage stat
| `POST /v1/embeddings` | Text embeddings |
| `POST /v1/rerank` | Document reranking |
| `POST /v1/systemone` | Typed decisions with decision models or chat models (TypeSafe System One) |
+| `POST /v1/images/generations` | Image generation |
+| `POST /v1/images/edits` | Image editing |
| `GET /v1/models` | List available models |
| `POST /v1/audio/transcriptions` | Speech-to-text, including speaker labels when supported |
| `POST /tokenize`, `POST /detokenize` | vLLM-compatible tokenizer API (also under `/v1`); embedding models take `prompt` only |
@@ -349,11 +492,295 @@ Models are auto-detected by type. You can also download models directly from the
| Type | Models |
|------|--------|
| LLM | Any model supported by [mlx-lm](https://github.com/ml-explore/mlx-lm) |
-| VLM | Qwen3.5 Series, GLM-4V, Pixtral, and other [mlx-vlm](https://github.com/Neywa-Labs/mlx-vlm) models |
+| VLM | Qwen3.5 Series, GLM-4V, Pixtral, Nemotron Nano Omni / Super VL / Bolt, and other [mlx-vlm](https://github.com/Neywa-Labs/mlx-vlm) models |
| OCR | DeepSeek-OCR, DOTS-OCR, GLM-OCR |
-| Embedding | BERT, BGE-M3, ModernBERT, EmbeddingGemma 2 |
-| Reranker | ModernBERT, XLM-RoBERTa |
+| Embedding | BERT, BGE-M3, ModernBERT, EmbeddingGemma, EmbeddingGemma 2, Qwen3-Embedding, Qwen3-VL-Embedding, SigLIP (text only) via [mlx-vlm](https://github.com/Blaizzy/mlx-vlm) or native loaders |
+| Reranker | ModernBERT, XLM-RoBERTa, Qwen3-Reranker, Qwen3-VL-Reranker |
| Decision | Clef, Clef-Flash, OpenJev, Decision 3.0 (d3, d3-flash, d3-mini, d3-nano, d3-lite, d3-edge) |
+| Image | mlx-vlm models: Qwen Image 2.1/base/Turbo, FLUX.2 Klein, Mage-Flow, Ming-Image 0.1 Design, ERNIE-Image, Z-Image, Ideogram 4, Bonsai |
+
+Embedding and reranker models load through mlx-vlm; the separate mlx-embeddings dependency is gone. NomicBERT checkpoints are no longer supported. SigLIP serves text embeddings only and rejects image inputs. Qwen3-VL-Embedding rejects inputs longer than 8192 tokens instead of truncating them.
+
+### Flint
+
+RecursiveSI Flint is a text-only MoE model served through native mlx-vlm
+(`model_type: flint`), with reasoning and GLM-style XML tool-call parsing.
+Discovery and integrations report text-only capabilities (`model_type: llm`)
+while retaining `engine_type: vlm` for loading; image, audio, and video inputs
+are not supported.
+oQ supports resident calibration and layer-streamed calibration on the original
+BF16 checkpoint, including routed/shared experts and normalized output-head
+inputs. See [oQ Quantization](docs/oQ_Quantization.md).
+
+### MiniCPM-V 4.7
+
+`MiniCPM-V-4.7-35B-A3B` requires the complete native `minicpmv4_7`
+implementation; it cannot be aliased to MiniCPM 4.6. The paired
+`MiniCPM-V-4.7-35B-A3B-DSpark` checkpoint is a drafter, not an independently
+served chat model. Support uses the existing chat, Anthropic Messages and
+Responses APIs; no audio or image/video generation capability is implied.
+
+The model and torch-free processor come from official **mlx-vlm**, pinned
+to [commit `4319ef2`](https://github.com/Blaizzy/mlx-vlm/commit/4319ef2c837b7226b758c3dd69edda51b7079785)
+(v0.7.10). The former full
+vendored implementation and source-hash installation bridge have been removed.
+This pin requires Python >=3.10, MLX >=0.32.4 and Transformers >=5.14;
+oMLX retains its existing MLX pin and Transformers upper bound.
+
+Small serving hooks in `omlx/patches/minicpm47.py` preserve request-local
+positions, padded-prefill behavior and the existing MiniCPM GDN normalization,
+including the official exact verifier. They also expose processor controls to
+mlx-vlm's signature-based input dispatcher and resolve legacy ViT-merger
+quantization paths through its per-model alias hook. The Qwen MTP constructor
+leaves foreign subclasses, including MiniCPM, responsible for their own heads.
+Vision packing uses the convolution's input dtype and the token embedding's
+floating output dtype, not packed quantized token-table storage.
+`omlx/speculative/minicpm_dspark.py` extends the official
+DSpark drafter with oMLX's proposal-probability/confidence transport and fixed
+paired-helper policy. The model, vision encoder, processor, checkpoint loading
+and speculative cache transactions remain upstream implementations.
+The official target uses normalized top-k routing; `norm_topk_prob=False`
+is not supported.
+
+Run `UV_PYTHON=python3.12 uv run --python python3.12 pytest tests/test_minicpm47.py tests/test_minicpm_pairing.py`
+for isolated, offline CPU compatibility checks. These exercise tiny strict
+HF/canonical/mixed-quantized checkpoints, processor/vision inputs, capture and
+cache rollback, and real oMLX greedy/sampled DSpark generation with cancellation
+and exception cleanup. Existing converted checkpoints and provenance checks
+are preserved; no reconversion or metadata changes are required.
+Tiny fixtures do not establish full-checkpoint or deployed GPU compatibility.
+
+The optional `mm_processor_kwargs` request field controls compression and
+slicing, separately from `chat_template_kwargs`:
+
+```json
+{
+ "mm_processor_kwargs": {
+ "downsample_mode": "4x",
+ "max_slice_nums": 36
+ }
+}
+```
+
+`downsample_mode` accepts `"4x"` or `"16x"`; `max_slice_nums` must be a positive
+integer. These controls can also be stored in per-model settings/profiles.
+In the admin UI, open **Model Settings > MiniCPM Media** to edit them.
+Choose **Default** for compression or clear the slicing limit to remove that
+override. Saving a MiniCPM profile with both controls unset records processor
+defaults explicitly rather than retaining previously applied media overrides.
+Non-null request values override model settings, then checkpoint/processor
+defaults. Omitted controls do not change existing defaults. The same effective
+compression mode is used for preprocessing, canvas positions and encoding.
+Advanced frame stacking (`stack_frames`) is deferred and rejected. Ordinary
+video retains the existing frame limit and can be combined with images.
+
+DSpark is explicitly opt-in through per-model `dflash_enabled: true` and
+`dflash_draft_model` pointing to its existing local paired checkpoint. The
+helper uses the target tokenizer and native sequential Markov proposals,
+proposal probabilities and confidence outputs. Verification is fixed-width,
+with at most eight proposals plus an anchor; confidence is observational, not
+an adaptive controller. Unsupported adaptive modes, sampled batches, stochastic
+XTC, constrained grammar decoding, sparse prefill, context-window truncation
+and private SSD drafter caching fail
+explicitly. Helper activation failures do not silently fall back to ordinary
+generation.
+
+Helper admission also checks source provenance, not just matching dimensions.
+Original Hugging Face local-directory downloads must retain their
+`.cache/huggingface/download/config.json.metadata`. Converted checkpoints
+may declare their source in `config.json`:
+`"omlx_source": {"repo_id": "...", "revision": "..."}`. The reviewed target
+source is `openbmb/MiniCPM-V-4.7-35B-A3B` at
+`4c7623a9326e0f74313bbc7292d852a9e3018a70`, and the helper source is
+`openbmb/MiniCPM-V-4.7-35B-A3B-DSpark` at
+`5facb75c251ffd524524a544c1f5fd97ba0d6c5c`.
+Conversion metadata is an explicit origin declaration, not a cryptographic
+certification of the trained tensors.
+
+DSpark requests re-prefill the complete prompt because ordinary KV prefix
+entries do not contain its target-layer capture history. Base serving without
+DSpark retains normal prefix-cache behavior. MiniCPM vision-feature caching is
+disabled until crop/position-equivalent reuse is proven. Original weights and
+configs are not rewritten; full checkpoint admission and installed-runtime
+validation require a separate memory-safe execution slot.
+
+### Nemotron multimodal models
+
+Support uses the official implementation merged in
+[Blaizzy/mlx-vlm#2528](https://github.com/Blaizzy/mlx-vlm/pull/2528),
+not a vendored architecture. The dependency pin above includes that merge and
+requires MLX 0.32.4, which oMLX already pins.
+
+| Family | Serving inputs | Native Lightning MTP |
+|--------|----------------|----------------------|
+| Nemotron-3 Nano Omni | Text, images, video; audio when the checkpoint includes `sound_config` | Only when native head tensors and configuration are present |
+| Nemotron-3.5 Super VL | Text, images, video | Bundled head; singleton and batched verification |
+| Nemotron-3.5 Bolt | Text, images, video | No bundled head |
+
+These models use the existing chat, Messages, and Responses APIs. Image and
+video inputs must use separate requests; each request accepts one video.
+Native paired-frame processing, odd-frame duplication, and pruning are retained,
+with an oMLX limit of 64 sampled frames. Pruned token IDs and embeddings share
+one retained-position map. API prompt usage reports the original processor token
+count; scheduling and cache positions use the compacted length. Cross-request
+prefix reuse is disabled for pruned video and native MTP because a KV entry alone
+cannot restore their complete media/head history. Audio identities are included
+in cache keys even when clips have identical lengths.
+
+Enable **Lightning MTP**, not an external assistant-drafter setting, for Super VL.
+Each request owns its native full-prompt head initialization. Batched verification
+commits at the earliest mismatch, stop, or token-budget boundary across the
+cohort, using the native recurrent-cache rollback transaction.
+Grammar-constrained and XTC late joins wait for the active native MTP cohort to
+finish; compatible requests still join its batched verification. This preserves
+live media-conditioned caches and queued tokens without text-only replay.
+Native full-prompt MTP requests cannot be requeued under memory pressure; the
+existing abort path applies rather than restarting without their media/head history.
+
+The existing `omlx.oq.quantize_oq_streaming()` Python API and admin oQ/oQe workflow accept floating-point
+sources and the native mixed ModelOpt NVFP4/FP8 source format (including NVIDIA's
+Super VL NVFP4 export). Per-expert global scales are folded before stacking,
+and Bolt's heterogeneous layer geometry is preserved. ModelOpt sensitivity
+measurement streams real source layers even when the full model fits in RAM.
+Existing MLX affine quants are serving inputs, not supported requantization
+sources. Exports remain multimodal: `text_only=True` is rejected before creating
+output. With `preserve_mtp=True`, the native head is exported to an associated
+`mtp/` sidecar using the official splitter's native format: ModelOpt FP8
+projections expand to floating point, while NVFP4 stays packed. The head is not
+oQe-calibrated, converted to the target's oQ recipe, or included in its
+bit-allocation budget. Size estimates count the exported sidecar
+once, including FP8 expansion and FP32 global scales. The official splitter can
+hold the complete head in memory.
+For sources larger than available RAM, oQe automatically streams native decoder
+layers from the original checkpoint for calibration instead of using a lossy
+proxy. Explicit `stream_calibration=True` also selects this path for smaller
+sources; heterogeneous Bolt layers retain their individual geometry and routing.
+Calibration uses the built-in text corpus; vision modules retain the weight-only
+oQ recipe rather than image/audio calibration. `oq_imatrix_report.json` records
+applied statistics and missing entries; this is not a quality claim.
+
+Coverage includes complete tiny native oQ/oQe checkpoint conversion, strict
+reload, mixed-source reconstruction, media alignment, and batched MTP lifecycle
+tests. It is not evidence of full-size checkpoint inference, conversion quality,
+or performance; those require separate model-specific validation.
+
+### Image model discovery and manifests
+
+Image generation and editing use the core mlx-vlm dependency. oMLX asks
+mlx-vlm whether each local diffusion checkpoint supports generation, editing,
+or both. Checkpoint metadata can identify models in renamed directories.
+The fork's alias registry does not restrict which families or tasks can be
+discovered.
+
+Requests override manifest sampling defaults. Otherwise mlx-vlm resolves
+sampling defaults from the loaded model. oMLX does not patch mlx-vlm request
+dataclasses or keep a separate family sampling-default table.
+With `size=auto`, generation uses mlx-vlm's default request size of 512×512;
+editing leaves size selection to the model. Explicit output sizes cannot
+exceed 4,194,304 pixels. Edit inputs use a private OS temporary directory
+per request, removed after inference or after a cancelled worker finishes.
+
+The fork retains `omlx-image-model.json` for explicit family or task
+declarations and per-checkpoint defaults. Add it in a model subdirectory
+to expose an mlx-vlm image model through `/v1/images/generations` or
+`/v1/images/edits`:
+
+```json
+{
+ "backend": "mlx-vlm",
+ "base_model": "flux2-klein-4b",
+ "task": ["generation", "edit"],
+ "model_path": ".",
+ "default_steps": 28,
+ "default_guidance": 3.5,
+ "default_image_strength": 0.4,
+ "estimated_size": 4294967296
+}
+```
+
+`model_path`, defaults, and `estimated_size` are optional. When
+`estimated_size` is omitted, oMLX uses the local `model_path` size when
+available, otherwise a conservative family estimate for memory accounting.
+`quantize` is not a valid image manifest setting because mlx-vlm loads the
+checkpoint's native weight format directly.
+
+Supported `base_model` aliases include FLUX.2 Klein 4B/9B/base/KV variants
+(generation and multi-image edit), Mage-Flow base/aligned/turbo and their edit
+variants, Z-Image and Z-Image Turbo, ERNIE-Image and ERNIE-Image Turbo,
+Ming-Image 0.1 Design (generation only), Ideogram 4 FP8, and Bonsai Ternary.
+The original `Ming-Image-0.1-Design` and quantized variants (such as
+`Ming-Image-0.1-Design-mxfp8`) are discovered without a manifest when placed
+under the model directory. Native sampling defaults are 12 steps and guidance 1.0;
+the output PNG retains its alpha channel. Z-Image
+and ERNIE-Image edit modes require
+exactly one source image; masks are not supported by the current mlx-vlm image
+families.
+
+Qwen Image **2.1 base and 2.1 Turbo** support generation and reference-image
+editing. Local multi-component checkpoints are detected from their 2.1
+pipeline/transformer/VAE configuration, even after renaming the directory;
+a Qwen-looking folder name alone is not sufficient. Older Qwen Image/Edit
+architectures are not included in this support. Explicit manifests can use
+`qwen-image-2.1` or `qwen-image-2.1-turbo`.
+
+The saved Turbo recipe has eight denoising steps and guidance 1.0. Schedule
+precedence is **request `sigmas` > checkpoint `sample_sigmas` > generated
+schedule from `steps`**. Setting only `steps`, including a manifest default,
+does not replace a saved checkpoint grid. Base checkpoints without saved
+grids keep 30 generation steps or 40 editing steps. Finite positive guidance
+overrides remain supported.
+
+Custom sigma grids are an API extension, not an Imagine editor. Supply a
+nonempty, finite, strictly descending JSON array in `(0, 1]`, without terminal
+zero; the scheduler applies the checkpoint's shift settings and appends the
+terminal zero. For multipart edits, encode the `sigmas` form field as a JSON
+array, for example `[1, 0.8, 0.4]`. Each response image includes the backend's
+effective `steps` and `guidance` when available, plus its actual output size.
+Imagine explains saved-grid precedence and displays the actual result steps.
+
+Qwen 2.1 editing conditions on all supplied reference images; the existing
+API/UI upload limits still apply. With automatic size, the backend selects
+the output aspect from the last resized reference. Qwen does not implement
+mask editing, `image_strength`, or an alternative `scheduler` selection;
+explicit unsupported options are rejected rather than ignored.
+
+The Qwen image compatibility patch temporarily backports a local mlx-vlm commit
+`9a200804c81b98fd420d1f8a064a6824cec76f4f`'s saved-grid,
+static-shift, effective-default/result, and nested processor-config fixes.
+It activates for recognized Qwen checkpoints before discovery probes or loading,
+refuses unknown upstream source shapes, and
+does nothing when the complete native fix is present. Remove the backport once
+oMLX's mlx-vlm pin contains the complete fix, retaining registry/API/UI wiring
+and regression tests. Full-checkpoint generation/edit validation and deployment
+are separate from weight-free tests and require a coordinated GPU memory
+budget; no checkpoint conversion or modification is needed.
+
+The source revision above is not yet published in the upstream repository.
+The checked-in hunks contain the exact before/after source and AST fingerprints,
+normalized across Python versions by omitting only empty type-parameter fields.
+Nonempty type parameters and other source changes still affect the fingerprint.
+The hunks can be verified without that local commit. Against a public
+`Blaizzy/mlx-vlm` checkout containing the original backport base
+`4f4634bb813c0298cb1467bed2e957526c71d0b4`, run:
+
+```bash
+uv run --python python3.12 python \
+ omlx/patches/mlx_vlm_qwen_image_compat/generate_backport.py \
+ --source-repo /path/to/mlx-vlm \
+ --verify-from-base
+```
+
+This reconstructs each target from the public base, verifies every hunk's unique
+context and the resulting AST fingerprint, and does not change any files.
+To regenerate the backport, a checkout containing the local source commit is
+required:
+
+```bash
+uv run --python python3.12 python \
+ omlx/patches/mlx_vlm_qwen_image_compat/generate_backport.py \
+ --source-repo /path/to/mlx-vlm \
+ --source-revision 9a200804c81b98fd420d1f8a064a6824cec76f4f
+```
## CLI Configuration
@@ -496,7 +923,6 @@ Contributions are welcome! See [Contributing Guide](docs/CONTRIBUTING.md) for de
- [mlx-vlm](https://github.com/Neywa-Labs/mlx-vlm) - Vision-language model inference on Apple Silicon
- [vllm-mlx](https://github.com/waybarrios/vllm-mlx) - oMLX started from vllm-mlx v0.1.0 and evolved significantly with multi-model serving, tiered KV caching, VLM with full paged cache support, an admin panel, and a macOS menu bar app
- [venvstacks](https://venvstacks.lmstudio.ai) - Portable Python environment layering for the macOS app bundle
-- [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) - Qwen GDN and QSA kernels (one via its mlxfast-challenge port) and the Linux helper's expert kernels and MLX CUDA patches are adapted from its MIT-licensed code
diff --git a/README.zh.md b/README.zh.md
index 03240839fa..27301133e1 100644
--- a/README.zh.md
+++ b/README.zh.md
@@ -411,7 +411,6 @@ apps/omlx-mac/Scripts/build.sh release --rebuild-donor
- [mlx-vlm](https://github.com/Neywa-Labs/mlx-vlm) - Apple Silicon 上的视觉语言模型推理
- [vllm-mlx](https://github.com/waybarrios/vllm-mlx) - oMLX 从 vllm-mlx v0.1.0 起步,经过大幅演进,增加了多模型服务、分层 KV 缓存、完整分页缓存支持的 VLM、管理后台和 macOS 菜单栏应用
- [venvstacks](https://venvstacks.lmstudio.ai) - macOS 应用包的便携 Python 环境分层
-- [mlx-embeddings](https://github.com/Blaizzy/mlx-embeddings) - Apple Silicon 嵌入模型支持
- [dflash-mlx](https://github.com/bstnxbt/dflash-mlx) - Apple Silicon 上的块扩散推测解码 (Block diffusion speculative decoding)
- [MTPLX](https://github.com/youssofal/mtplx) - Lightning MTP 的验证形态 Metal 内核由 Youssof Altoukhi 的 MTPLX 提供支持,同时也启发了 depth-k 流水线设计
- [mlx-serve](https://github.com/ddalcu/mlx-serve) - Qwen 的 GDN 与 QSA 内核(其一来自 mlx-serve 对 mlxfast-challenge 的移植)以及 Linux helper 的 expert 内核与 MLX CUDA 补丁改编自 mlx-serve 的 MIT 开源代码
diff --git a/benchmarks/README.md b/benchmarks/README.md
new file mode 100644
index 0000000000..281d7b258e
--- /dev/null
+++ b/benchmarks/README.md
@@ -0,0 +1,71 @@
+# Qwen verifier benchmark
+
+`bench_qwen_verify_prework.py` compares upstream GDN prework with oMLX's fused
+prework in the real `VLMBatchedEngine` serving path. Native MTP is enabled in
+both arms. This does not measure the speedup from enabling MTP.
+
+Example invocation from the repository root:
+
+```sh
+uv run --python python3.12 python benchmarks/bench_qwen_verify_prework.py \
+ ~/.models/scaryrawr/Qwen3.6-35B-A3B-mxfp4 > qwen-result.json
+```
+
+The default workload has 512 prompt tokens and 128 generated tokens. Each arm
+gets one warmup, followed by three baseline/candidate/candidate/baseline groups.
+The model stays loaded throughout. `--pp 2048` selects a longer prompt.
+`--fixed-depth 1` selects one draft token instead of the default two.
+
+Fixed draft depth is confined to the benchmark process. Adaptive depth can
+change floating-point execution geometry and greedy output tokens, confounding
+an exact kernel comparison. Production retains its adaptive policy.
+
+The JSON includes raw trials, median producer-side decode throughput, complete
+output token IDs, MTP and fused-kernel call counts, MTP head dtypes, runtime
+information, source hashes, and model metadata fingerprints. Weight contents
+are not hashed. Logs go to stderr.
+
+The runner fails on early EOS, unequal outputs, cache hits, inactive MTP,
+inactive treatment, treatment engagement in the baseline, model-file changes,
+or missing telemetry. A failed run is not a performance result. Concurrent GPU
+work and thermal drift can still distort timing.
+
+## Measured scope
+
+On an Apple M4 Max with 128 GB unified memory and MLX 0.32.2, the final paired
+512-token runs produced these medians:
+
+| Model | Upstream prework | Fused prework | Change |
+| --- | ---: | ---: | ---: |
+| Qwen3.6-35B-A3B-mxfp4 | 113.82 tok/s | 118.91 tok/s | +4.47% |
+| Qwen3.8-27B-mxfp4 | 40.97 tok/s | 41.27 tok/s | +0.73% |
+
+Each run generated identical tokens across all arms. Earlier repeated runs
+measured +3.17% for 35B and +1.19% for 27B. The dense-model gain is small.
+A 2048-token 35B run measured 87.48 to 89.06 tok/s, a 1.80% increase.
+These measurements cover singleton, fixed-depth-two MTP decode, not general
+request latency, prefill, or concurrent throughput.
+
+Both MXFP4 trunks retained BF16 MTP heads on disk and after loading. The 27B
+head had 15 tensors, and the 35B head had 20. No model weights were modified.
+
+## Production switch
+
+Fused verifier prework is enabled by default for eligible Qwen3.5-family BF16
+blocks with batch size one and sequence lengths 2 through 9.
+`OMLX_QWEN35_VERIFY_PREWORK=0` selects upstream prework. Qwen4, ordinary decode,
+prefill, masked blocks, and unsupported shapes retain their existing paths.
+
+## Flash Next
+
+`Qwen3.8-Flash-Next-heretic-2-mxfp4` uses `qwen4_exp` and L2 normalization.
+The Qwen3.5 verifier fusion above does not apply to this model.
+
+A separate 512-token prompt and 128-token generation run measured 32.57 tok/s
+without native MTP. A paired run with the Lightning MTP head resident measured
+31.05 tok/s with MTP disabled and 37.66 tok/s with one draft token, a 21.31%
+raw throughput increase. The loaded MTP head contained 32 BF16 tensors.
+
+Outputs were stable within each arm but differed between ordinary and MTP
+decode. These rates therefore do not establish a token-identical speedup.
+They measure existing native MTP, not a new Flash Next optimization.
diff --git a/docs/TESTING.md b/docs/TESTING.md
index e87bcfa53b..0f5d816c2a 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -4,6 +4,21 @@ Server tests live in `tests/` and must not depend on `apps/`: after the full run
Run `node --test` from `apps/omlx-web/tests/` to discover the standalone dashboard script tests. `test_admin_network_auth_ui.py` runs `network_auth_ui_runner.cjs` with backend-generated cases on stdin.
+# Live chat compatibility smoke
+
+Against an isolated server, run
+`OMLX_BASE_URL=http://127.0.0.1:18080 OMLX_TEST_MODEL=Qwen3.5-9B-oQ4e-mtp uv run --python python3.12 pytest tests/integration/test_live_tool_calling.py -m integration`.
+The selected model must appear in `/v1/models`. Cases cover streaming and
+non-streaming tool-call round trips, token usage, chat logprobs and top alternatives,
+and chat-backed decision readouts. Enable native MTP in the isolated model settings
+to exercise multi-token verification too. Keep the server's base path and `HOME`
+isolated so startup cannot overwrite the running service's cluster shim.
+
+Run `uv run --python python3.12 pytest tests/integration/test_responses_tool_merge.py`
+for mocked protocol checks. The Anthropic cases verify that generation and token
+counting share the same tools, thinking, reasoning effort, and multimodal
+processor options, and that template errors remain visible on both endpoints.
+
# Qwen3.5 text-only checkpoint tests
Run `python -m pytest -q tests/test_oq.py -k Qwen35TextCheckpoint` to check
@@ -81,11 +96,15 @@ Run `python -m pytest -q tests/test_engine_teardown.py tests/test_engine_core.py
# Claude launcher tests
-Run `python -m pytest -q tests/test_cli.py tests/test_integrations.py` to check model selection, saved tier precedence, and the final Claude Code environment. Mixed-context cases verify that the selected initial model is passed through `ANTHROPIC_MODEL` and that the process-wide context and auto-compact limits use the smallest known context window across the initial model and configured tiers. Larger models consequently compact at that shared limit; models without reported limits cannot contribute a limit.
+Run `python -m pytest -q tests/test_cli.py tests/test_integrations.py` to check model selection, saved tier precedence, and the final Claude Code environment. Mixed-context cases verify that the selected initial model is passed through `ANTHROPIC_MODEL` and that the process-wide context and auto-compact limits use the smallest known context window across the initial model, configured tiers, and discoverable chat models. Larger models consequently compact at that shared limit; models without reported limits cannot contribute a limit.
+
+Run `UV_PYTHON=python3.12 uv run --python python3.12 pytest tests/test_integrations.py tests/test_cli.py tests/test_v1_models_visibility.py tests/test_server.py` for Claude gateway discovery.
+These tests cover the launch environment, discovery filtering and authentication, unchanged standard model IDs, streaming Messages, token counts, and exposed-profile settings.
+Gateway IDs wrap the served ID with `omlx-claude/`, including the initial model and configured tiers.
# ModernBERT embedding tests
-Run `python -m pytest -q tests/test_modernbert_attention.py tests/test_embedding.py tests/test_mlx_embeddings_compat.py` to check finite padded attention, single-input equivalence, local-window masking, and embedding integration. The attention regression covers fp16, bf16, and fp32 at lengths around the affected SDPA tile boundaries.
+Run `python -m pytest -q tests/test_modernbert_attention.py tests/test_embedding.py` to check finite padded attention, single-input equivalence, local-window masking, and embedding integration. The attention regression covers fp16, bf16, and fp32 at lengths around the affected SDPA tile boundaries.
# GGUF model tests
diff --git a/docs/custom-kernels.md b/docs/custom-kernels.md
index fd278f037a..4668c285f9 100644
--- a/docs/custom-kernels.md
+++ b/docs/custom-kernels.md
@@ -46,6 +46,11 @@ Each package has:
ANE offload is off by default. See [Qwen ANE/GPU prefill](experimental/qwen35_ane_prefill.md).
+The fork's Qwen MXFP4/MXFP8 prefill wrappers are
+`quant_matmul.fast.mxfp4_qmm_t` and `mxfp8_qmm_t`. They share the
+`omlx_quant_matmul_kernels.metallib` library with the affine matmul kernels;
+there is no separate `qwen35_prefill` extension.
+
Some kernels are not in this directory. Small JIT kernels (`mx.fast.metal_kernel`) live next to the model code in `omlx/patches`. They compile at runtime and need no build.
## Build
diff --git a/docs/demos/claude-discovery.cast b/docs/demos/claude-discovery.cast
new file mode 100644
index 0000000000..a5716cb379
--- /dev/null
+++ b/docs/demos/claude-discovery.cast
@@ -0,0 +1,40 @@
+{"version":2,"width":112,"height":42,"timestamp":1793741315,"idle_time_limit":2.0,"title":"Claude Code discovers local oMLX models"}
+[0.024289, "o", "\u001b[2J\u001b[HClaude Code + oMLX: live gateway model discovery\r\n\r\n$ omlx launch claude --port 8001 --model Qwen3.5-9B-oQ4e-mtp\r\n\r\n"]
+[2.223665, "o", "Launching Claude Code with model Qwen3.5-9B-oQ4e-mtp...\r\r\n"]
+[2.223811, "o", "Launching Claude Code with model Qwen3.5-9B-oQ4e-mtp...\r\r\nAuto-compact window: 262,144 tokens\r\r\n"]
+[2.306093, "o", "\u001b7\u001b[r\u001b8\u001b[?25h"]
+[2.34369, "o", "\u001b[?2004h\u001b[?2031h\u001b[?1004h"]
+[2.343952, "o", "\u001b]0;✳ Claude Code\u0007"]
+[2.35575, "o", "\u001b[?1049h\u001b[2J\u001b[H\u001b[?1000h\u001b[?1002h\u001b[?1003h\u001b[?1006h\u001b[?25l\u001b[?25l\u001b[H\r\u001b[1B\u001b[38;2;215;119;87m ▐\u001b[48;2;0;0;0m▛███▛█\u001b[12G\u001b[39m\u001b[49m\u001b[1mClaude Code\u001b[24G\u001b[22m\u001b[38;2;153;153;153mv2.1.311\r\u001b[1B\u001b[38;2;215;119;87m▝▜\u001b[48;2;0;0;0m█████\u001b[49m█▀\u001b[12G\u001b[38;2;153;153;153mQwen3.5-9B-oQ4e-mtp · API Usage Billing\r\u001b[1B\u001b[38;2;215;119;87m ▝▝ ▝▝ \u001b[12G\u001b[38;2;153;153;153m~/project\r\u001b[94C\u001b[34B● high · /effort\r\u001b[1B\u001b[38;2;136;136;136m────────────────────────────────────────────────────────────────────────────────────────────────────────────────\r\u001b[1B\u001b[39m❯ \u001b[7m \r\u001b[1B\u001b[27m\u001b[38;2;136;136;136m────────────────────────────────────────────────────────────────"]
+[2.3559, "o", "────────────────────────────────────────────────\r\u001b[2C\u001b[1B\u001b[38;2;255;193;7m⏵⏵ auto mode on\u001b[38;2;153;153;153m (shift+tab to cycle) · ← for agents\u001b[39m\u001b[42;1H\u001b[40;3H"]
+[2.368043, "o", "\u001b[>0q\u001b[?u\u001b]7501;?\u0007\u001b[c"]
+[5.445684, "o", "\u001b[H\r\u001b[2C\u001b[33B\u001b[38;2;177;185;249m❯ /\u001b[1mmodel\u001b[22m Set the AI \u001b[1mmodel\u001b[22m for Claude Code (currently Qwen3.5-9B-oQ4e-mtp)\r\u001b[2C\u001b[1B\u001b[38;2;153;153;153m /auto-mode-setup Teach auto mode about your environment, plus optional rule tweaks\r\u001b[2C\u001b[1B /code-review Review the current diff or a PR for bugs and cleanups\r\u001b[2C\u001b[1B /update-config Change settings: hooks, permissions, environment variables\r\u001b[2C\u001b[1B /loop Repeat a prompt or command on an interval (e.g. /loop 5m /foo)\u001b[39m\u001b[K\r\u001b[2C\u001b[2B\u001b[38;2;177;185;249m/model\u001b[39m\u001b[7m \r\u001b[38C\u001b[2B\u001b[27m\u001b[K\u001b[42;1H\u001b[40;9H"]
+[6.503581, "o", "\u001b[H\r\u001b[22B\u001b[38;2;177;185;249m▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔\u001b[95G\u001b[38;2;153;153;153m● high · /effort\u001b[38;2;177;185;249m ▔\r\u001b[3C\u001b[1B\u001b[1mSelect model\r\u001b[3C\u001b[1B\u001b[22m\u001b[38;2;153;153;153mSwitch between Claude models. Your pick becomes the default for new sessions. For other/previous model \r\u001b[3C\u001b[1Bnames, specify with --model.\r\u001b[5C\u001b[2B1. \u001b[39mDefault\u001b[18G(recommended)\u001b[45G\u001b[38;2;153;153;153mUse the default model (currently Qwen3.5-9B-oQ4e-mtp)\r\u001b[3C\u001b[1B\u001b[38;2;177;185;249m❯\u001b[6G\u001b[38;2;153;153;153m2. \u001b[38;2;78;186;101momlx-claude/Qwen3.5-9B-oQ4e-mtp\u001b[42G✔\u001b[45G\u001b[38;2;153;153;153mCustom Opus model\r\u001b[5C\u001b[1B3. \u001b[39mFable\u001b[45G\u001b[38;2;153;153;153mFable 5.1 · Most capable for your hardest and longest-running \r\u001b[44C\u001b[1Btasks · $10/$50 per Mtok\r\u001b[5C\u001b[1B4. \u001b[39momlx-claude/Qw"]
+[6.503738, "o", "en3.5-9B-oQ4e-mtp\u001b[45G\u001b[38;2;153;153;153mCustom Sonnet model\r\u001b[5C\u001b[1B5. \u001b[39momlx-claude/Qwen3.5-9B-oQ4e-mtp\u001b[45G\u001b[38;2;153;153;153mCustom Haiku model\r\u001b[2C\u001b[1B\u001b[39m \u001b[38;2;153;153;153m6. \u001b[39mFlint-oQ6e \u001b[38;2;153;153;153mFrom gateway\u001b[39m\u001b[K\r\u001b[2C\u001b[1B \u001b[38;2;153;153;153m7. \u001b[39mQwen3.6-35B-A3B-oQ6e-mtp \u001b[38;2;153;153;153mFrom gateway\u001b[39m\u001b[K\r\u001b[2C\u001b[1B \u001b[38;2;153;153;153m8. \u001b[39mQwen3.8-Flash-Next-oQ4e-mtp \u001b[38;2;153;153;153mF\u001b[47Gom gateway\u001b[39m\u001b[K\r\u001b[2C\u001b[1B \u001b[38;2;153;153;153m9. \u001b[39mgemma-4-12B-it-oQ4e-mtp \u001b[38;2;153;153;153mFrom\u001b[50Ggateway\u001b[39m\u001b[K\r\u001b[2C\u001b[1B \u001b[38;2;153;153;153m10. \u001b[39mgemma-4-26B-A4B-it-oQ6e-mtp \u001b[38;2;153;153;153mFrom gateway\u001b[39m\u001b[K\r\u001b[1B\u001b[K\r\u001b[1B \u001b[38;2;215;119;87m●\u001b[38;2;153;153;153m High effort (default)\u001b[38;2;80;80;80m ←/→ to adjust\r\u001b[1B\u001b[39m\u001b[K\r\u001b[2C\u001b[1B \u001b[38;2;153;153;153mEnter to set as defaul\u001b[27G ·\u001b[30Gs to us\u001b[38G this session only · Esc to cancel\u001b[39m\u001b[42;1H\u001b[29;4H"]
+[11.563579, "o", "\u001b(B\u000f\u001b[?2004h\u001b[?1000h\u001b[?1002h\u001b[?1003h\u001b[?1006h"]
+[11.575157, "o", "\u001b[H\r\u001b[3C\u001b[28B \r\u001b[3C\u001b[1B\u001b[38;2;177;185;249m❯\u001b[10GFable\u001b[39m\u001b[42;1H\u001b[30;4H"]
+[11.881689, "o", "\u001b[H\r\u001b[3C\u001b[29B \u001b[10GFable\r\u001b[3C\u001b[2B\u001b[38;2;177;185;249m❯\u001b[10Gomlx-claude/Qwen3.5-9B-oQ4e-mtp\u001b[39m\u001b[42;1H\u001b[32;4H"]
+[12.191094, "o", "\u001b[H\r\u001b[3C\u001b[31B \u001b[10Gomlx-claude/Qwen3.5-9B-oQ4e-mtp\r\u001b[3C\u001b[1B\u001b[38;2;177;185;249m❯\u001b[10Gomlx-claude/Qwen3.5-9B-oQ4e-mtp\u001b[39m\u001b[42;1H\u001b[33;4H"]
+[12.356264, "o", "\u001b[H\r\u001b[93C\u001b[22B\u001b[38;2;177;185;249m▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔\u001b[39m\u001b[42;1H\u001b[33;4H"]
+[12.495979, "o", "\u001b[H\r\u001b[3C\u001b[32B \u001b[10Gomlx-claude/Qwen3.5-9B-oQ4e-mtp\r\u001b[3C\u001b[1B\u001b[38;2;177;185;249m❯\u001b[10GFlint-oQ6e\u001b[39m\u001b[42;1H\u001b[34;4H"]
+[12.804536, "o", "\u001b[H\r\u001b[3C\u001b[33B \u001b[10GFlint-oQ6e\r\u001b[3C\u001b[1B\u001b[38;2;177;185;249m❯\u001b[10GQwen3.6-35B-A3B-oQ6e-mtp\u001b[39m\u001b[42;1H\u001b[35;4H"]
+[13.11077, "o", "\u001b[H\r\u001b[3C\u001b[34B \u001b[10GQwen3.6-35B-A3B-oQ6e-mtp\r\u001b[3C\u001b[1B\u001b[38;2;177;185;249m❯\u001b[10GQwen3.8-Flash-Next-oQ4e-mtp\u001b[39m\u001b[42;1H\u001b[36;4H"]
+[13.42195, "o", "\u001b[H\r\u001b[3C\u001b[35B \u001b[10GQwen3.8-Flash-Next-oQ4e-mtp\r\u001b[3C\u001b[1B\u001b[38;2;177;185;249m❯\u001b[10Ggemma-4-12B-it-oQ4e-mtp\u001b[39m\u001b[42;1H\u001b[37;4H"]
+[16.758564, "o", "\u001b[H\r\u001b[11C\u001b[2B\u001b[38;2;153;153;153mgemma-4\u001b[20G12B-it-oQ4e-mtp ·\u001b[38GAPI Usage Billing\r\u001b[4B\u001b[48;2;55;55;55m❯\u001b[39m \u001b[38;2;255;255;255m/model\u001b[39m \r\u001b[1B\u001b[49m\u001b[38;2;153;153;153m ⎿ \u001b[39mSet\u001b[10Gmodel\u001b[16Gto\u001b[19G\u001b[38;2;177;185;249mgemma-4-12B-it-oQ4e-mtp\u001b[43G\u001b[39mfor\u001b[47Gthis\u001b[52Gsession\u001b[60Gonly\r\u001b[15B\u001b[K\r\u001b[3C\u001b[1B\u001b[K\r\u001b[3C\u001b[1B\u001b[K\r\u001b[3C\u001b[1B\u001b[K\r\u001b[5C\u001b[2B\u001b[K\r\u001b[5C\u001b[1B\u001b[K\r\u001b[5C\u001b[1B\u001b[K\r\u001b[44C\u001b[1B\u001b[K\r\u001b[5C\u001b[1B\u001b[K\r\u001b[5C\u001b[1B\u001b[K\r\u001b[5C\u001b[1B\u001b[K\r\u001b[5C\u001b[1B\u001b[K\r\u001b[5C\u001b[1B\u001b[K\r\u001b[3C\u001b[1B\u001b[K\r\u001b[5C\u001b[1B \u001b[45G \u001b[95G\u001b[38;2;153;153;153m● high · /effort\r\u001b[1B\u001b[38;2;136;136;136m───────────────────────────────────────────────────────────────────────────────────────────────────────────────"]
+[16.758572, "o", "─\r\u001b[1B\u001b[39m❯ \u001b[7m \u001b[27m\u001b[K\r\u001b[1B\u001b[38;2;136;136;136m────────────────────────────────────────────────────────────────────────────────────────────────────────────────\r\u001b[2C\u001b[1B\u001b[38;2;255;193;7m⏵⏵ auto mode on\u001b[38;2;153;153;153m (shift+\u001b[27Gab\u001b[30Gto cycl\u001b[38G)\u001b[39m\u001b[K\u001b[42;1H\u001b[40;3H"]
+[21.78426, "o", "\u001b(B\u000f\u001b[?2004h\u001b[?1000h\u001b[?1002h\u001b[?1003h\u001b[?1006h"]
+[21.805903, "o", "\u001b[H\r\u001b[2C\u001b[33B\u001b[38;2;177;185;249m❯ /\u001b[1mmodel\u001b[22m Set the AI \u001b[1mmodel\u001b[22m for Claude Code (currently gemma-4-12B-it-oQ4e-mtp)\r\u001b[2C\u001b[1B\u001b[38;2;153;153;153m /auto-mode-setup Teach auto mode about your environment, plus optional rule tweaks\r\u001b[2C\u001b[1B /code-review Review the current diff or a PR for bugs and cleanups\r\u001b[2C\u001b[1B /update-config Change settings: hooks, permissions, environment variables\r\u001b[2C\u001b[1B /loop Repeat a prompt or command on an interval (e.g. /loop 5m /foo)\u001b[39m\u001b[K\r\u001b[2C\u001b[2B\u001b[38;2;177;185;249m/model\u001b[39m\u001b[7m \u001b[27m\u001b[42;1H\u001b[40;9H"]
+[22.863241, "o", "\u001b[H\r\u001b[22B\u001b[38;2;177;185;249m▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔\u001b[95G\u001b[38;2;153;153;153m● high · /effort\u001b[38;2;177;185;249m ▔\r\u001b[3C\u001b[1B\u001b[1mSelect model\r\u001b[3C\u001b[1B\u001b[22m\u001b[38;2;153;153;153mSwitch between Claude models. Your pick becomes the default for new sessions. For other/previous model \r\u001b[3C\u001b[1Bnames, specify with --model.\r\u001b[5C\u001b[2B1. \u001b[39mDefault\u001b[18G(recommended)\u001b[43G\u001b[38;2;153;153;153mUse the default model (currently Qwen3.5-9B-oQ4e-mtp)\r\u001b[5C\u001b[1B2. \u001b[39momlx-claude/Qwen3.5-9B-oQ4e-mtp\u001b[43G\u001b[38;2;153;153;153mCustom Opus model\r\u001b[5C\u001b[1B3. \u001b[39mFable\u001b[43G\u001b[38;2;153;153;153mFable 5.1 · Most capable for your hardest and longest-running tasks\r\u001b[42C\u001b[1B· $10/$50 per Mtok\r\u001b[5C\u001b[1B4. \u001b[39momlx-claude/Qwen3.5-9B-oQ4e-mtp\u001b[43G\u001b[38;2;153;153;153mCustom Sonnet model\r\u001b[5C\u001b["]
+[22.863419, "o", "1B5. \u001b[39momlx-claude/Qwen3.5-9B-oQ4e-mtp\u001b[43G\u001b[38;2;153;153;153mCustom Haiku model\r\u001b[2C\u001b[1B\u001b[39m \u001b[38;2;153;153;153m6. \u001b[39mFlint-oQ6e \u001b[38;2;153;153;153mFrom gateway\u001b[39m\u001b[K\r\u001b[2C\u001b[1B \u001b[38;2;153;153;153m7. \u001b[39mQwen3.6-35B-A3B-oQ6e-mtp \u001b[38;2;153;153;153mFr\u001b[46Gm g\u001b[50Gteway\u001b[39m\u001b[K\r\u001b[2C\u001b[1B \u001b[38;2;153;153;153m8. \u001b[39mQwen3.8-Flash-Next-oQ4e-mtp \u001b[38;2;153;153;153mFrom ga\u001b[51Geway\u001b[39m\u001b[K\r\u001b[2C\u001b[1B \u001b[38;2;177;185;249m❯\u001b[39m \u001b[38;2;153;153;153m9. \u001b[38;2;78;186;101mgemma-4-12B-it-oQ4e-mtp\u001b[39m \u001b[38;2;78;186;101m✔\u001b[39m \u001b[38;2;153;153;153mFrom gateway\u001b[39m\u001b[K\r\u001b[2C\u001b[1B \u001b[38;2;153;153;153m10. \u001b[39mgemma-4-26B-A4B-it-oQ6e-mtp \u001b[38;2;153;153;153mFrom gateway\u001b[39m\u001b[K\r\u001b[1B\u001b[K\r\u001b[1B \u001b[38;2;215;119;87m●\u001b[38;2;153;153;153m High effort (default)\u001b[38;2;80;80;80m ←/→ to adjust\r\u001b[1B\u001b[39m\u001b[K\r\u001b[2C\u001b[1B \u001b[38;2;153;153;153mEnter to set as defaul\u001b[27G ·\u001b[30Gs to us\u001b[38G this session only · Esc to cancel\u001b[39m\u001b[42;1H\u001b[37;4H"]
+[26.762355, "o", "\u001b[H\r\u001b[93C\u001b[22B\u001b[38;2;177;185;249m▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔\u001b[39m\u001b[42;1H\u001b[37;4H"]
+[27.923414, "o", "\u001b(B\u000f\u001b[?2004h\u001b[?1000h\u001b[?1002h\u001b[?1003h\u001b[?1006h"]
+[27.998623, "o", "\u001b[H\r\u001b[9B\u001b[48;2;55;55;55m\u001b[38;2;153;153;153m❯\u001b[39m \u001b[38;2;255;255;255m/model\u001b[39m \r\u001b[1B\u001b[49m\u001b[38;2;153;153;153m ⎿ \u001b[39mKept\u001b[11Gmodel\u001b[17Gas\u001b[20G\u001b[38;2;177;185;249mgemma-4-12B-it-oQ4e-mtp\r\u001b[12B\u001b[39m\u001b[K\r\u001b[3C\u001b[1B\u001b[K\r\u001b[3C\u001b[1B\u001b[K\r\u001b[3C\u001b[1B\u001b[K\r\u001b[5C\u001b[2B\u001b[K\r\u001b[5C\u001b[1B\u001b[K\r\u001b[5C\u001b[1B\u001b[K\r\u001b[42C\u001b[1B\u001b[K\r\u001b[5C\u001b[1B\u001b[K\r\u001b[5C\u001b[1B\u001b[K\r\u001b[5C\u001b[1B\u001b[K\r\u001b[5C\u001b[1B\u001b[K\r\u001b[5C\u001b[1B\u001b[K\r\u001b[3C\u001b[1B\u001b[K\r\u001b[5C\u001b[1B \u001b[43G \u001b[95G\u001b[38;2;153;153;153m● high · /effort\r\u001b[1B\u001b[38;2;136;136;136m────────────────────────────────────────────────────────────────────────────────────────────────────────────────\r\u001b[1B\u001b[39m❯ \u001b[7m \u001b[27m\u001b[K\r\u001b[1B\u001b[38;2;136;136;136m─────────────────────────────────────────────────"]
+[27.998632, "o", "───────────────────────────────────────────────────────────────\r\u001b[2C\u001b[1B\u001b[38;2;255;193;7m⏵⏵ auto mode on\u001b[38;2;153;153;153m (shift+\u001b[27Gab\u001b[30Gto cycl\u001b[38G)\u001b[39m\u001b[K\u001b[42;1H\u001b[40;3H"]
+[28.928952, "o", "\u001b[?1006l\u001b[?1003l\u001b[?1002l\u001b[?1000l"]
+[28.929938, "o", "\u001b[?25h"]
+[28.930186, "o", "\u001b[?1004l\u001b[4m\u001b[>4m\u001b[4m\u001b[?1004l\u001b[?2031l\u001b[?2004l\u001b[
Date: Wed, 4 Nov 2026 09:15:01 -0500
Subject: [PATCH 02/24] chore(deps): pin runtime packages and remove GPL audio
dependencies
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
---
packaging/build.py | 12 +++----
pyproject.toml | 30 +++++++++--------
setup.py | 1 +
tests/test_admin_engine_info.py | 59 +++++++++++++++++++++++++++++++++
tests/test_project_metadata.py | 29 ++++++++++++++++
5 files changed, 110 insertions(+), 21 deletions(-)
create mode 100644 tests/test_admin_engine_info.py
create mode 100644 tests/test_project_metadata.py
diff --git a/packaging/build.py b/packaging/build.py
index 2585b7dd4a..a338f483a1 100644
--- a/packaging/build.py
+++ b/packaging/build.py
@@ -179,12 +179,11 @@ def swap_platform_wheels(
# Remove existing mlx/mlx-metal from site-packages
for item in site_packages.iterdir():
name = item.name.lower()
- if name in ("mlx", "mlx_metal") or name.startswith(
- ("mlx-", "mlx_metal-")
+ if item.is_dir() and (
+ name in ("mlx", "mlx_metal") or name.startswith(("mlx-", "mlx_metal-"))
):
- if item.is_dir():
- shutil.rmtree(item)
- print(f" Removed {item.name}")
+ shutil.rmtree(item)
+ print(f" Removed {item.name}")
# Install downloaded wheels into site-packages
for whl in wheels_tmp.glob("*.whl"):
@@ -410,7 +409,6 @@ def _write_engine_commits(omlx_pkg_dir: Path):
repo_urls = {
"mlx-lm": "https://github.com/ml-explore/mlx-lm",
"mlx-vlm": "https://github.com/Neywa-Labs/mlx-vlm",
- "mlx-embeddings": "https://github.com/Blaizzy/mlx-embeddings",
"mlx-audio": "https://github.com/Neywa-Labs/mlx-audio",
}
@@ -579,7 +577,7 @@ def _create_resolved_toml(version_map: dict[str, str], base_toml: Path) -> Path:
"""
content = base_toml.read_text()
- for full_req, git_url in _parse_git_requirements(base_toml):
+ for full_req, _git_url in _parse_git_requirements(base_toml):
pkg_name = full_req.split("@")[0].strip()
whl = _find_wheel_for_package(pkg_name)
if whl:
diff --git a/pyproject.toml b/pyproject.toml
index 27a1fbc744..7bac8f902e 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -47,8 +47,6 @@ dependencies = [
"mlx-lm @ git+https://github.com/ml-explore/mlx-lm@0d4d3d04f8ab7ce4a51e7209e8615755a48ba94d",
# regex for mlx-lm's Gemma 4 tool parser (uses recursive patterns)
"regex",
- # mlx-embeddings from latest commit (32981fa)
- "mlx-embeddings @ git+https://github.com/Blaizzy/mlx-embeddings@32981fa4e8064ed664b52071789dd18271fe4206",
# mlx-vlm custom processors bypass HF AutoProcessor, so torch is not required
# The mlx-lm pin above includes the NewlineTokenizer registration fix
# required by transformers 5.13+. mlx-vlm requires the 5.14 processor API.
@@ -72,10 +70,11 @@ dependencies = [
"numpy>=1.24.0,<2.4",
"tqdm>=4.66.0",
"pyyaml>=6.0",
+ "json5>=0.12.1,<1",
"itsdangerous>=2.0",
# transformers 5.22.2 refuses to render chat templates with older jinja2.
"jinja2>=3.1.6",
- # mlx-lm 0.31.3 imports rich from mlx_lm.cli_ui for chat/lora entrypoints.
+ # mlx-lm imports rich from mlx_lm.cli_ui for chat/lora entrypoints.
"rich>=13.0.0",
"sentencepiece",
"tiktoken",
@@ -129,6 +128,8 @@ grammar = [
"xgrammar==0.2.8",
"apache-tvm-ffi==0.1.11",
]
+# Kept as a no-op compatibility extra. mlx-vlm image support is part of core.
+image = []
mcp = [
"mcp>=2.0.0,<3",
]
@@ -146,12 +147,10 @@ audio = [
# mlx-audio from commit (1157775, v0.6.5) with tts/stt/sts extras
"mlx-audio[tts,stt,sts] @ git+https://github.com/Neywa-Labs/mlx-audio@1157775c1999654b1ebde41ed03d88108e23f88b",
# Keep dependencies for existing audio models removed from upstream extras.
- "espeakng-loader>=0.2.4",
"librosa==0.11.0",
"misaki>=0.9.4",
"num2words>=0.5.14",
"numba>=0.60.0",
- "phonemizer-fork>=3.3.2",
"pyloudnorm>=0.2.0",
"spacy>=3.8.4",
# WebSocket protocol impl for uvicorn (realtime STT endpoint). Pure
@@ -176,20 +175,22 @@ paroquant = [
bundle = [
"mcp>=2.0.0,<3",
"modelscope>=1.28.0",
- # mlx-audio[tts,stt,sts] transitives:
+ # mlx-audio core deps needed when packaging installs the git wheel --no-deps.
+ "huggingface-hub>=1.0",
+ "tqdm>=4.67.1",
+ # Audio runtime deps bundled for TTS/STT/STS support:
"scipy>=1.11.0",
"librosa>=0.10.0",
- "miniaudio>=1.59",
+ "miniaudio>=1.61",
"numba>=0.59.0",
"pyloudnorm>=0.1.0",
- "sounddevice>=0.4.6",
+ "sounddevice>=0.5.3",
"misaki>=0.9.4",
"num2words>=0.5.14",
"spacy>=3.8.4",
- "phonemizer-fork>=3.3.2",
- "espeakng-loader>=0.2.4",
"webrtcvad>=2.0.10",
"zstandard>=0.23.0",
+ "setuptools<81",
# [audio] extra on top of pyproject's plain mistral-common>=1.10
"mistral-common[audio]>=1.10",
# realtime STT WebSocket endpoint
@@ -228,7 +229,7 @@ Repository = "https://github.com/jundot/omlx"
omlx = "omlx.cli:main"
[tool.setuptools.dynamic]
-version = {attr = "omlx._version.__version__"}
+version = { attr = "omlx._version.__version__" }
[tool.setuptools.packages.find]
# omlx_web ships in the same wheel. Without apps/ the wheel is API-only.
@@ -240,6 +241,7 @@ include = ["omlx*"]
"oq_calibration_data.json",
"oqe_calibration_data.json",
"oqe_refine_calibration_data.json",
+ "MLX_VLM_LICENSE.txt",
]
"omlx.admin" = ["bench_corpora/*"]
"omlx_web" = ["templates/**/*.html", "static/**/*", "i18n/*.json"]
@@ -265,11 +267,11 @@ target-version = ["py311", "py312", "py313"]
[tool.ruff]
line-length = 88
+extend-exclude = ["omlx/patches/*/vendor"]
+
+[tool.ruff.lint]
select = ["E", "F", "W", "I", "N", "UP", "B", "SIM"]
ignore = ["E501", "B905"]
-# Vendored upstream files (mlx-vlm copies under patches) keep their
-# original formatting for pin-bump diffability.
-extend-exclude = ["omlx/patches/*/vendor"]
[tool.mypy]
python_version = "3.11"
diff --git a/setup.py b/setup.py
index b0604cd60f..dbcf809c26 100644
--- a/setup.py
+++ b/setup.py
@@ -50,6 +50,7 @@ def _custom_kernel_build_kwargs() -> dict:
"omlx_quant_matmul_kernels",
sources=[
f"{quant}/affine_qmm.metal",
+ f"{quant}/fp_qmm.metal",
f"{quant}/gather_qmm.metal",
f"{quant}/head_flat_qmm.metal",
f"{quant}/moe_weighted_sum.metal",
diff --git a/tests/test_admin_engine_info.py b/tests/test_admin_engine_info.py
new file mode 100644
index 0000000000..82a41593de
--- /dev/null
+++ b/tests/test_admin_engine_info.py
@@ -0,0 +1,59 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Tests for admin dashboard engine/package metadata."""
+
+from __future__ import annotations
+
+import importlib.metadata
+
+from omlx.admin import routes as admin_routes
+
+
+class _FakeDistribution:
+ version = "9.9.9"
+
+ @staticmethod
+ def read_text(name: str) -> str | None:
+ return None
+
+
+def test_engine_info_reports_mlx_vlm_version(monkeypatch):
+ """Image support should share the mlx-vlm Engine Versions entry."""
+
+ def fake_distribution(pkg_name: str):
+ if pkg_name == "mlx-vlm":
+ return _FakeDistribution()
+ raise importlib.metadata.PackageNotFoundError
+
+ monkeypatch.setattr(importlib.metadata, "distribution", fake_distribution)
+ monkeypatch.setattr(admin_routes, "_load_fallback_commits", lambda packages: {})
+
+ engines = admin_routes._get_engine_info()
+
+ assert engines["mlx-vlm"] == {
+ "name": "mlx-vlm",
+ "version": "9.9.9",
+ "commit": None,
+ "url": None,
+ }
+
+
+def test_parse_commits_uses_pinned_source_repo(tmp_path):
+ """Fallback commit links should point at the pinned package source repo."""
+ pyproject = tmp_path / "pyproject.toml"
+ sha = "71329b8a18f02273279ca766afb66ed0665a97f9"
+ pyproject.write_text(
+ "[project]\n"
+ "dependencies = [\n"
+ f' "mlx-vlm @ git+https://github.com/Blaizzy/mlx-vlm@{sha}",\n'
+ "]\n"
+ )
+ packages = {
+ "mlx-vlm": "https://github.com/Blaizzy/mlx-vlm",
+ }
+
+ commits = admin_routes._parse_commits_from_pyproject(pyproject, packages)
+
+ assert commits["mlx-vlm"] == {
+ "commit": sha,
+ "url": f"https://github.com/Blaizzy/mlx-vlm/commit/{sha}",
+ }
diff --git a/tests/test_project_metadata.py b/tests/test_project_metadata.py
new file mode 100644
index 0000000000..87f7d175eb
--- /dev/null
+++ b/tests/test_project_metadata.py
@@ -0,0 +1,29 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Tests for packaging metadata."""
+
+from __future__ import annotations
+
+import re
+import tomllib
+from pathlib import Path
+
+
+def _dependency_name(requirement: str) -> str:
+ return re.split(r"\s*(?:[<>=!~]=?|@|\[)", requirement.strip(), maxsplit=1)[
+ 0
+ ].lower().replace("_", "-")
+
+
+def test_mlx_vlm_is_core_and_image_extra_is_compatibility_only():
+ pyproject = tomllib.loads(
+ (Path(__file__).resolve().parents[1] / "pyproject.toml").read_text()
+ )
+
+ core_dependencies = {
+ _dependency_name(requirement)
+ for requirement in pyproject["project"]["dependencies"]
+ }
+ image_extra = pyproject["project"]["optional-dependencies"]["image"]
+
+ assert "mlx-vlm" in core_dependencies
+ assert image_extra == []
From 9428818af60fcdd11e4a6f40b9eebfd7583be4c3 Mon Sep 17 00:00:00 2001
From: Mike Wallio
Date: Wed, 4 Nov 2026 09:15:01 -0500
Subject: [PATCH 03/24] perf(quantization): optimize Qwen kernels and extend oQ
model support
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
---
benchmarks/bench_qwen_decode.py | 510 +++++++++++++++++
benchmarks/bench_qwen_verify_prework.py | 265 +++++++++
omlx/admin/oq_manager.py | 4 +-
.../quant_matmul/csrc/affine_qmm.cpp | 245 ++++++++-
.../quant_matmul/csrc/affine_qmm.h | 14 +
.../quant_matmul/csrc/affine_qmm.metal | 2 +
.../quant_matmul/csrc/bindings.cpp | 17 +
.../quant_matmul/csrc/fp_qmm.metal | 76 +++
.../quant_matmul/csrc/moe_staging.cpp | 1 -
omlx/custom_kernels/quant_matmul/fast.py | 46 ++
omlx/oq.py | 250 ++++++++-
omlx/patches/qwen35_compiled_mlp.py | 194 +++++++
omlx/patches/qwen35_gdn_decode.py | 329 +++++++++++
omlx/patches/qwen35_moe_routed_decode.py | 2 +
omlx/patches/qwen35_moe_router.py | 19 +-
omlx/patches/qwen35_q4_mlp.py | 158 ++++--
omlx/patches/qwen35_verify_qmm.py | 320 ++++++++---
scripts/bench.py | 517 ++++++++++++++++++
tests/bench_qwen35_verify_qmm.py | 80 +++
tests/test_bench_qwen_decode.py | 312 +++++++++++
tests/test_bench_qwen_verify_prework.py | 258 +++++++++
tests/test_oq.py | 28 +
tests/test_oq_combine.py | 8 +-
tests/test_qwen35_compiled_mlp.py | 245 +++++++++
tests/test_qwen35_gdn_decode.py | 237 ++++++++
tests/test_qwen35_moe_routed_decode.py | 12 +
tests/test_qwen35_moe_router.py | 94 +++-
tests/test_qwen35_q4_mlp.py | 236 +++++++-
tests/test_qwen35_verify_qmm.py | 171 ++++++
tests/test_scripts_bench.py | 268 +++++++++
30 files changed, 4774 insertions(+), 144 deletions(-)
create mode 100644 benchmarks/bench_qwen_decode.py
create mode 100644 benchmarks/bench_qwen_verify_prework.py
create mode 100644 omlx/custom_kernels/quant_matmul/csrc/fp_qmm.metal
create mode 100644 omlx/patches/qwen35_compiled_mlp.py
create mode 100644 omlx/patches/qwen35_gdn_decode.py
create mode 100755 scripts/bench.py
create mode 100644 tests/bench_qwen35_verify_qmm.py
create mode 100644 tests/test_bench_qwen_decode.py
create mode 100644 tests/test_bench_qwen_verify_prework.py
create mode 100644 tests/test_qwen35_compiled_mlp.py
create mode 100644 tests/test_qwen35_gdn_decode.py
create mode 100644 tests/test_qwen35_verify_qmm.py
create mode 100644 tests/test_scripts_bench.py
diff --git a/benchmarks/bench_qwen_decode.py b/benchmarks/bench_qwen_decode.py
new file mode 100644
index 0000000000..1793b1df8a
--- /dev/null
+++ b/benchmarks/bench_qwen_decode.py
@@ -0,0 +1,510 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Deterministic serving-path decode benchmark for supported Qwen models."""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import hashlib
+import json
+import os
+import platform
+import subprocess
+import sys
+import time
+from collections.abc import Sequence
+from contextlib import redirect_stdout
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from typing import Any
+
+DEFAULT_PROMPT_TEXT = (
+ r"Complete this Python module. Continue with code only and do not stop "
+ r"until the implementation is complete.\n\n"
+)
+SUPPORTED_MODEL_TYPES = frozenset(
+ {"qwen3_5", "qwen3_5_moe", "qwen3_6", "qwen3_8", "qwen4_exp"}
+)
+PROMPT_BUILD_MAX_ATTEMPTS = 16
+MAX_CONFIG_BYTES = 4 * 1024 * 1024
+MODEL_METADATA_NAMES = frozenset(
+ {
+ "config.json",
+ "generation_config.json",
+ "merges.txt",
+ "preprocessor_config.json",
+ "processor_config.json",
+ "special_tokens_map.json",
+ "tokenizer.json",
+ "tokenizer.model",
+ "tokenizer_config.json",
+ "vocab.json",
+ }
+)
+OMLX_CANDIDATE_ENV_PREFIXES = (
+ "OMLX_FA256_",
+ "OMLX_GDN_",
+ "OMLX_M5_",
+ "OMLX_MTP_",
+ "OMLX_QWEN35_",
+ "OMLX_QWEN4_",
+ "OMLX_SDPA256_",
+)
+
+
+@dataclass(frozen=True)
+class Trial:
+ index: int
+ warmup: bool
+ prompt_tokens: int
+ completion_tokens: int
+ cached_tokens: int
+ finish_reason: str | None
+ output_token_ids: tuple[int, ...]
+ output_sha256: str
+ producer_first_s: float | None
+ producer_last_s: float | None
+ producer_duration_s: float | None
+ consumer_duration_s: float
+ generation_tps: float | None
+ end_to_end_tps: float
+ peak_memory_bytes: int
+ errors: tuple[str, ...]
+
+
+class BenchmarkError(RuntimeError):
+ pass
+
+
+def _parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("model")
+ parser.add_argument("--pp", type=int, default=512)
+ parser.add_argument("--gen", type=int, default=128)
+ parser.add_argument("--repeats", type=int, default=3)
+ parser.add_argument("--warmup", type=int, default=1)
+ parser.add_argument("--native-mtp", choices=("off", "on"), required=True)
+ parser.add_argument("--label", required=True)
+ parser.add_argument("--prompt-text", default=DEFAULT_PROMPT_TEXT)
+ args = parser.parse_args(argv)
+ for name in ("pp", "gen", "repeats"):
+ if getattr(args, name) <= 0:
+ parser.error(f"--{name} must be positive")
+ if args.warmup < 0:
+ parser.error("--warmup must be non-negative")
+ return args
+
+
+def _token_digest(token_ids: Sequence[int]) -> str:
+ payload = json.dumps(list(token_ids), separators=(",", ":")).encode()
+ return hashlib.sha256(payload).hexdigest()
+
+
+def _config_model_type(config: dict[str, Any]) -> str:
+ return str(config.get("model_type", "")).replace("-", "_").lower()
+
+
+def _is_model_artifact(path: Path) -> bool:
+ if path.name in MODEL_METADATA_NAMES:
+ return True
+ if path.name.endswith(".safetensors.index.json"):
+ return True
+ if path.suffix in {".safetensors", ".npz"}:
+ return True
+ return any(
+ "mtp" in part.lower() or "sidecar" in part.lower() for part in path.parts
+ )
+
+
+def _model_fingerprint(model: str) -> dict[str, Any]:
+ model_path = Path(model).expanduser().resolve(strict=True)
+ if not model_path.is_dir():
+ raise BenchmarkError(f"model path is not a directory: {model_path}")
+
+ config_path = model_path / "config.json"
+ config_stat = config_path.stat()
+ if config_stat.st_size > MAX_CONFIG_BYTES:
+ raise BenchmarkError(
+ f"config.json is unexpectedly large: {config_stat.st_size} bytes"
+ )
+ config_bytes = config_path.read_bytes()
+ config_stat_after = config_path.stat()
+ if (
+ config_stat_after.st_size != config_stat.st_size
+ or config_stat_after.st_mtime_ns != config_stat.st_mtime_ns
+ ):
+ raise BenchmarkError("config.json changed while fingerprinting")
+ try:
+ config = json.loads(config_bytes)
+ except json.JSONDecodeError as exc:
+ raise BenchmarkError(f"invalid config.json: {exc}") from exc
+ if not isinstance(config, dict):
+ raise BenchmarkError("config.json root must be an object")
+ model_type = _config_model_type(config)
+ if model_type not in SUPPORTED_MODEL_TYPES:
+ supported = ", ".join(sorted(SUPPORTED_MODEL_TYPES))
+ raise BenchmarkError(
+ f"unsupported model_type {model_type!r}; expected one of: {supported}"
+ )
+
+ files = []
+ for path in sorted(model_path.rglob("*")):
+ if not path.is_file():
+ continue
+ relative = path.relative_to(model_path)
+ if not _is_model_artifact(relative):
+ continue
+ stat = path.stat()
+ files.append(
+ {
+ "path": relative.as_posix(),
+ "size": stat.st_size,
+ "mtime_ns": stat.st_mtime_ns,
+ }
+ )
+ if not any(item["path"].endswith(".safetensors") for item in files):
+ raise BenchmarkError(f"model has no safetensors weights: {model_path}")
+
+ fingerprint_payload = {
+ "resolved_path": str(model_path),
+ "model_type": model_type,
+ "config_sha256": hashlib.sha256(config_bytes).hexdigest(),
+ "files": files,
+ }
+ encoded = json.dumps(
+ fingerprint_payload, sort_keys=True, separators=(",", ":")
+ ).encode()
+ return {
+ **fingerprint_payload,
+ "sha256": hashlib.sha256(encoded).hexdigest(),
+ }
+
+
+def _assert_model_unchanged(before: dict[str, Any], after: dict[str, Any]) -> None:
+ if after["sha256"] != before["sha256"]:
+ raise BenchmarkError("model files changed during benchmark")
+
+
+def _candidate_environment() -> dict[str, str]:
+ return {
+ name: value
+ for name, value in sorted(os.environ.items())
+ if name.startswith(OMLX_CANDIDATE_ENV_PREFIXES)
+ }
+
+
+def _source_revision() -> dict[str, Any]:
+ root = Path(__file__).resolve().parents[1]
+ try:
+ revision = subprocess.run(
+ ["git", "rev-parse", "HEAD"],
+ cwd=root,
+ check=True,
+ capture_output=True,
+ text=True,
+ ).stdout.strip()
+ status = subprocess.run(
+ ["git", "status", "--porcelain=v1", "--untracked-files=all"],
+ cwd=root,
+ check=True,
+ capture_output=True,
+ text=True,
+ ).stdout
+ diff = subprocess.run(
+ ["git", "diff", "--no-ext-diff", "--no-textconv", "--binary", "HEAD"],
+ cwd=root,
+ check=True,
+ capture_output=True,
+ ).stdout
+ except (OSError, subprocess.CalledProcessError) as exc:
+ return {"error": f"{type(exc).__name__}: {exc}"}
+ return {
+ "revision": revision,
+ "dirty": bool(status),
+ "status_sha256": hashlib.sha256(status.encode()).hexdigest(),
+ "tracked_diff_sha256": hashlib.sha256(diff).hexdigest(),
+ "runner_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
+ }
+
+
+def _runtime_info(mx: Any) -> dict[str, Any]:
+ from omlx._version import __version__ as omlx_version
+
+ return {
+ "python": platform.python_version(),
+ "platform": platform.platform(),
+ "mlx_version": str(mx.__version__),
+ "omlx_version": omlx_version,
+ "mlx_device": json.loads(json.dumps(mx.device_info(), default=str)),
+ "omlx_environment": _candidate_environment(),
+ "source": _source_revision(),
+ }
+
+
+def _build_prompt(
+ tokenizer: Any,
+ target_tokens: int,
+ prompt_text: str = DEFAULT_PROMPT_TEXT,
+) -> tuple[int, ...]:
+ from omlx.admin.benchmark import BenchmarkContextProfile, _load_bench_corpus
+
+ corpus = _load_bench_corpus(BenchmarkContextProfile.CODE_PYTHON)
+ target_chars = max(target_tokens * 4, 1)
+ for _ in range(PROMPT_BUILD_MAX_ATTEMPTS):
+ repeats = (target_chars + len(corpus) - 1) // len(corpus)
+ body = (corpus * repeats)[:target_chars]
+ token_ids = tuple(int(token) for token in tokenizer.encode(prompt_text + body))
+ if len(token_ids) >= target_tokens:
+ return token_ids[:target_tokens]
+ if not token_ids:
+ raise BenchmarkError("benchmark prompt tokenized to zero tokens")
+ target_chars = max(
+ target_chars + 1,
+ (target_chars * target_tokens + len(token_ids) - 1) // len(token_ids) + 1,
+ )
+ raise BenchmarkError(
+ f"could not build an exact {target_tokens}-token prompt after "
+ f"{PROMPT_BUILD_MAX_ATTEMPTS} attempts"
+ )
+
+
+def _model_settings(native_mtp: bool) -> Any:
+ from omlx.model_settings import ModelSettings
+
+ return ModelSettings(
+ mtp_enabled=native_mtp,
+ vlm_mtp_enabled=False,
+ dflash_enabled=False,
+ specprefill_enabled=False,
+ turboquant_kv_enabled=False,
+ )
+
+
+async def _run_trial(
+ engine: Any,
+ mx: Any,
+ prompt: tuple[int, ...],
+ max_tokens: int,
+ *,
+ index: int,
+ warmup: bool,
+) -> Trial:
+ mx.reset_peak_memory()
+
+ started = time.perf_counter()
+ first_generated_at: float | None = None
+ last_generated_until: float | None = None
+ terminal = None
+ async for output in engine.stream_generate(
+ prompt=list(prompt),
+ max_tokens=max_tokens,
+ temperature=0.0,
+ top_p=1.0,
+ seed=0,
+ skip_cache_store=True,
+ ):
+ if output.generated_at is not None and first_generated_at is None:
+ first_generated_at = float(output.generated_at)
+ if output.generated_until is not None:
+ last_generated_until = float(output.generated_until)
+ terminal = output
+ ended = time.perf_counter()
+
+ peak_memory = int(mx.get_peak_memory())
+ consumer_duration = ended - started
+ if terminal is None:
+ return Trial(
+ index=index,
+ warmup=warmup,
+ prompt_tokens=0,
+ completion_tokens=0,
+ cached_tokens=0,
+ finish_reason=None,
+ output_token_ids=(),
+ output_sha256=_token_digest(()),
+ producer_first_s=first_generated_at,
+ producer_last_s=last_generated_until,
+ producer_duration_s=None,
+ consumer_duration_s=consumer_duration,
+ generation_tps=None,
+ end_to_end_tps=0.0,
+ peak_memory_bytes=peak_memory,
+ errors=("produced no output",),
+ )
+
+ output_ids = tuple(int(token) for token in terminal.tokens)
+ errors = []
+ if not output_ids:
+ errors.append("produced no terminal token IDs")
+ if first_generated_at is None or last_generated_until is None:
+ producer_duration = None
+ errors.append("omitted producer timestamps")
+ else:
+ producer_duration = last_generated_until - first_generated_at
+ if producer_duration <= 0:
+ errors.append("has a non-positive producer duration")
+ if not terminal.finished:
+ errors.append("did not produce a terminal output")
+ if terminal.completion_tokens != max_tokens or len(output_ids) != max_tokens:
+ errors.append(
+ f"ended early: completion_tokens={terminal.completion_tokens}, "
+ f"token_ids={len(output_ids)}, expected={max_tokens}, "
+ f"finish_reason={terminal.finish_reason!r}"
+ )
+ if terminal.cached_tokens:
+ errors.append(f"reported {terminal.cached_tokens} cached prompt tokens")
+
+ generation_tps = None
+ if producer_duration is not None and producer_duration > 0:
+ generation_tps = max(terminal.completion_tokens - 1, 1) / producer_duration
+ return Trial(
+ index=index,
+ warmup=warmup,
+ prompt_tokens=int(terminal.prompt_tokens),
+ completion_tokens=int(terminal.completion_tokens),
+ cached_tokens=int(terminal.cached_tokens),
+ finish_reason=terminal.finish_reason,
+ output_token_ids=output_ids,
+ output_sha256=_token_digest(output_ids),
+ producer_first_s=first_generated_at,
+ producer_last_s=last_generated_until,
+ producer_duration_s=producer_duration,
+ consumer_duration_s=consumer_duration,
+ generation_tps=generation_tps,
+ end_to_end_tps=terminal.completion_tokens / consumer_duration,
+ peak_memory_bytes=peak_memory,
+ errors=tuple(errors),
+ )
+
+
+def _validate_trial(
+ trial: Trial,
+ prompt_tokens: int,
+ expected_output: tuple[int, ...] | None,
+) -> tuple[int, ...]:
+ if trial.errors:
+ raise BenchmarkError(f"trial {trial.index} " + "; ".join(trial.errors))
+ if trial.prompt_tokens != prompt_tokens:
+ raise BenchmarkError(
+ f"trial {trial.index} reported {trial.prompt_tokens} prompt tokens; "
+ f"expected {prompt_tokens}"
+ )
+ if expected_output is not None and trial.output_token_ids != expected_output:
+ raise BenchmarkError(f"trial {trial.index} output differs from the first trial")
+ return trial.output_token_ids
+
+
+async def _benchmark(args: argparse.Namespace) -> dict[str, Any]:
+ result: dict[str, Any] = {
+ "schema_version": 1,
+ "status": "running",
+ "label": args.label,
+ "model": args.model,
+ "native_mtp": args.native_mtp,
+ "config": {
+ "prompt_tokens": args.pp,
+ "generation_tokens": args.gen,
+ "repeats": args.repeats,
+ "warmup": args.warmup,
+ "temperature": 0.0,
+ "seed": 0,
+ "prompt_text": args.prompt_text,
+ "cache_store": False,
+ },
+ "runtime": {
+ "python": platform.python_version(),
+ "platform": platform.platform(),
+ },
+ "trials": [],
+ }
+ engine = None
+ trials: list[Trial] = []
+ fingerprint_before = None
+ try:
+ fingerprint_before = _model_fingerprint(args.model)
+ result["model_type"] = fingerprint_before["model_type"]
+ result["model_fingerprint_before"] = fingerprint_before
+
+ import mlx.core as mx
+
+ from omlx.engine.vlm import VLMBatchedEngine
+ from omlx.scheduler import SchedulerConfig
+
+ result["runtime"] = _runtime_info(mx)
+ engine = VLMBatchedEngine(
+ model_name=args.model,
+ model_settings=_model_settings(args.native_mtp == "on"),
+ scheduler_config=SchedulerConfig(
+ paged_ssd_cache_dir=None,
+ hot_cache_max_size=0,
+ ),
+ )
+ await engine.start()
+ loaded_model_type = str(engine.model_type or "").replace("-", "_").lower()
+ if loaded_model_type != fingerprint_before["model_type"]:
+ raise BenchmarkError(
+ f"loaded model_type {loaded_model_type!r} differs from config "
+ f"{fingerprint_before['model_type']!r}"
+ )
+
+ prompt = _build_prompt(engine.tokenizer, args.pp, args.prompt_text)
+ result["prompt"] = {
+ "token_ids": list(prompt),
+ "sha256": _token_digest(prompt),
+ }
+ expected_output: tuple[int, ...] | None = None
+ for index in range(args.warmup + args.repeats):
+ trial = await _run_trial(
+ engine,
+ mx,
+ prompt,
+ args.gen,
+ index=index,
+ warmup=index < args.warmup,
+ )
+ trials.append(trial)
+ result["trials"] = [asdict(item) for item in trials]
+ expected_output = _validate_trial(trial, args.pp, expected_output)
+ result["status"] = "ok"
+ except Exception as exc:
+ result["status"] = "error"
+ result["error"] = f"{type(exc).__name__}: {exc}"
+ finally:
+ if fingerprint_before is not None:
+ try:
+ fingerprint_after = _model_fingerprint(args.model)
+ result["model_fingerprint_after"] = fingerprint_after
+ _assert_model_unchanged(fingerprint_before, fingerprint_after)
+ except Exception as exc:
+ result["status"] = "error"
+ result["error"] = (
+ f"{result['error']}; post-run fingerprint failed: "
+ f"{type(exc).__name__}: {exc}"
+ if "error" in result
+ else f"post-run fingerprint failed: {type(exc).__name__}: {exc}"
+ )
+ if engine is not None:
+ try:
+ await engine.stop()
+ except Exception as exc:
+ result["status"] = "error"
+ cleanup_error = f"engine cleanup failed: {type(exc).__name__}: {exc}"
+ result["error"] = (
+ f"{result['error']}; {cleanup_error}"
+ if "error" in result
+ else cleanup_error
+ )
+ return result
+
+
+def main(argv: Sequence[str] | None = None) -> int:
+ args = _parse_args(argv)
+ with redirect_stdout(sys.stderr):
+ result = asyncio.run(_benchmark(args))
+ json.dump(result, sys.stdout, separators=(",", ":"))
+ sys.stdout.write("\n")
+ return 0 if result["status"] == "ok" else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/benchmarks/bench_qwen_verify_prework.py b/benchmarks/bench_qwen_verify_prework.py
new file mode 100644
index 0000000000..5c55acfff3
--- /dev/null
+++ b/benchmarks/bench_qwen_verify_prework.py
@@ -0,0 +1,265 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Paired benchmark for the Qwen verifier GDN prework candidate."""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import hashlib
+import json
+import os
+import statistics
+import sys
+from collections.abc import Sequence
+from contextlib import redirect_stdout
+from dataclasses import asdict
+from pathlib import Path
+from typing import Any
+
+ROOT = Path(__file__).resolve().parents[1]
+if str(ROOT) not in sys.path:
+ sys.path.insert(0, str(ROOT))
+
+from benchmarks import bench_qwen_decode as bench # noqa: E402
+
+PROMPT_TEXT = bench.DEFAULT_PROMPT_TEXT
+PREWORK_ENV = "OMLX_QWEN35_VERIFY_PREWORK"
+MISSING = object()
+
+
+def _parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("model")
+ parser.add_argument("--pp", type=int, default=512)
+ parser.add_argument("--gen", type=int, default=128)
+ parser.add_argument("--pairs", type=int, default=3)
+ parser.add_argument("--fixed-depth", type=int, choices=(1, 2), default=2)
+ parser.add_argument("--prompt-text", default=PROMPT_TEXT)
+ args = parser.parse_args(argv)
+ for name in ("pp", "gen", "pairs"):
+ if getattr(args, name) <= 0:
+ parser.error(f"--{name} must be positive")
+ return args
+
+
+def _schedule(pairs: int) -> list[tuple[bool, bool]]:
+ return [(True, False), (True, True)] + [
+ (False, treatment)
+ for _ in range(pairs)
+ for treatment in (False, True, True, False)
+ ]
+
+
+def _head_metadata(head: Any, tree_flatten: Any) -> list[dict[str, Any]]:
+ return [
+ {"name": name, "dtype": str(value.dtype), "shape": list(value.shape)}
+ for name, value in tree_flatten(head.parameters())
+ ]
+
+
+def _validate_engagement(record: dict[str, Any]) -> None:
+ errors = []
+ if record["draft_calls"] <= 0:
+ errors.append("native MTP draft path was not engaged")
+ if record["treatment"] and record["prework_calls"] <= 0:
+ errors.append("prework treatment was not engaged")
+ if not record["treatment"] and record["prework_calls"] != 0:
+ errors.append("prework treatment engaged in the baseline")
+ record["engagement_errors"] = errors
+ if errors:
+ raise bench.BenchmarkError("; ".join(errors))
+
+
+async def _run(args: argparse.Namespace, deps: dict[str, Any] | None = None) -> dict:
+ if deps is None:
+ import mlx.core as mx
+ from mlx.utils import tree_flatten
+
+ from omlx.engine.vlm import VLMBatchedEngine
+ from omlx.patches import qwen35_gdn_prework as prework
+ from omlx.patches.mlx_lm_mtp.batch_generator import _DepthController
+ from omlx.scheduler import SchedulerConfig
+
+ deps = {
+ "mx": mx,
+ "tree_flatten": tree_flatten,
+ "engine_cls": VLMBatchedEngine,
+ "prework": prework,
+ "depth_controller": _DepthController,
+ "scheduler_config": SchedulerConfig,
+ }
+ mx = deps["mx"]
+ controller = deps["depth_controller"]
+ prework = deps["prework"]
+ old_env = os.environ.get(PREWORK_ENV)
+ old_observe = controller.observe
+ old_should_exit = controller.should_exit
+ old_prework = prework.gdn_prework_fused
+ engine = None
+ original_draft = None
+ language_model = None
+ original_depth = MISSING
+ depth_changed = False
+ before = None
+ result = {
+ "schema_version": 1,
+ "status": "running",
+ "model": args.model,
+ "candidate": "qwen35_gdn_prework",
+ "fixed_depth": args.fixed_depth,
+ "config": {"pp": args.pp, "gen": args.gen, "pairs": args.pairs},
+ "trials": [],
+ }
+ prework_calls = 0
+ draft_calls = 0
+
+ def observe_fixed(self, *values, **kwargs):
+ old_observe(self, *values, **kwargs)
+ self.cur = min(self.max_depth, args.fixed_depth)
+
+ def counted_prework(*values, **kwargs):
+ nonlocal prework_calls
+ prework_calls += 1
+ return old_prework(*values, **kwargs)
+
+ try:
+ before = bench._model_fingerprint(args.model)
+ result["model_fingerprint_before"] = before
+ result["runtime"] = bench._runtime_info(mx)
+ result["runner_sha256"] = hashlib.sha256(
+ Path(__file__).read_bytes()
+ ).hexdigest()
+ os.environ[PREWORK_ENV] = "1"
+ controller.observe = observe_fixed
+ controller.should_exit = lambda self: False
+ prework.gdn_prework_fused = counted_prework
+ settings = bench._model_settings(True)
+ settings.mtp_num_draft_tokens = args.fixed_depth
+ engine = deps["engine_cls"](
+ model_name=args.model,
+ model_settings=settings,
+ scheduler_config=deps["scheduler_config"](
+ paged_ssd_cache_dir=None, hot_cache_max_size=0
+ ),
+ )
+ await engine.start()
+ language_model = engine._adapter._language_model
+ original_depth = getattr(language_model, "_omlx_mtp_depth", MISSING)
+ head = (
+ language_model.get_mtp_module()
+ if hasattr(language_model, "get_mtp_module")
+ else getattr(language_model, "mtp", None)
+ )
+ decode_enabled = bool(
+ getattr(language_model, "_omlx_mtp_decode_enabled", False)
+ )
+ if head is None or not decode_enabled:
+ raise bench.BenchmarkError("native MTP did not become ready")
+ language_model._omlx_mtp_depth = args.fixed_depth
+ depth_changed = True
+ head_tensors = _head_metadata(head, deps["tree_flatten"])
+ result["mtp"] = {
+ "decode_enabled": decode_enabled,
+ "head_tensors": head_tensors,
+ "all_bfloat16": bool(head_tensors)
+ and all("bfloat16" in item["dtype"] for item in head_tensors),
+ }
+ if not result["mtp"]["all_bfloat16"]:
+ raise bench.BenchmarkError("MTP head parameters are not all bfloat16")
+ original_draft = engine._adapter.mtp_forward
+
+ def counted_draft(*values, **kwargs):
+ nonlocal draft_calls
+ draft_calls += 1
+ return original_draft(*values, **kwargs)
+
+ engine._adapter.mtp_forward = counted_draft
+ prompt = bench._build_prompt(engine.tokenizer, args.pp, args.prompt_text)
+ result["prompt"] = {
+ "text": args.prompt_text,
+ "token_ids": list(prompt),
+ "sha256": bench._token_digest(prompt),
+ }
+ expected = None
+ for index, (warmup, treatment) in enumerate(_schedule(args.pairs)):
+ os.environ[PREWORK_ENV] = "1" if treatment else "0"
+ mx.random.seed(0)
+ draft_before, prework_before = draft_calls, prework_calls
+ trial = await bench._run_trial(
+ engine, mx, prompt, args.gen, index=index, warmup=warmup
+ )
+ record = asdict(trial)
+ record.update(
+ treatment=treatment,
+ draft_calls=draft_calls - draft_before,
+ prework_calls=prework_calls - prework_before,
+ )
+ result["trials"].append(record)
+ expected = bench._validate_trial(trial, args.pp, expected)
+ _validate_engagement(record)
+ result["outputs_identical"] = (
+ len({record["output_sha256"] for record in result["trials"]}) == 1
+ )
+ result["summary"] = {
+ arm: statistics.median(
+ record["generation_tps"]
+ for record in result["trials"]
+ if not record["warmup"] and record["treatment"] is (arm == "candidate")
+ )
+ for arm in ("baseline", "candidate")
+ }
+ result["status"] = "ok"
+ except Exception as exc:
+ result.update(status="error", error=f"{type(exc).__name__}: {exc}")
+ finally:
+ controller.observe = old_observe
+ controller.should_exit = old_should_exit
+ prework.gdn_prework_fused = old_prework
+ if engine is not None and original_draft is not None:
+ engine._adapter.mtp_forward = original_draft
+ if depth_changed:
+ if original_depth is MISSING:
+ delattr(language_model, "_omlx_mtp_depth")
+ else:
+ language_model._omlx_mtp_depth = original_depth
+ if old_env is None:
+ os.environ.pop(PREWORK_ENV, None)
+ else:
+ os.environ[PREWORK_ENV] = old_env
+ if before is not None:
+ try:
+ after = bench._model_fingerprint(args.model)
+ result["model_fingerprint_after"] = after
+ bench._assert_model_unchanged(before, after)
+ except Exception as exc:
+ result["status"] = "error"
+ fingerprint_error = (
+ f"post-run fingerprint failed: {type(exc).__name__}: {exc}"
+ )
+ result["error"] = (
+ f"{result['error']}; {fingerprint_error}"
+ if "error" in result
+ else fingerprint_error
+ )
+ if engine is not None:
+ try:
+ await engine.stop()
+ except Exception as exc:
+ result["status"] = "error"
+ cleanup = f"engine cleanup failed: {type(exc).__name__}: {exc}"
+ result["error"] = (
+ f"{result['error']}; {cleanup}" if "error" in result else cleanup
+ )
+ return result
+
+
+def main(argv: Sequence[str] | None = None) -> int:
+ args = _parse_args(argv)
+ with redirect_stdout(sys.stderr):
+ result = asyncio.run(_run(args))
+ print(json.dumps(result, separators=(",", ":")))
+ return 0 if result["status"] == "ok" else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/omlx/admin/oq_manager.py b/omlx/admin/oq_manager.py
index 3cf1aea884..9af0fe7dc6 100644
--- a/omlx/admin/oq_manager.py
+++ b/omlx/admin/oq_manager.py
@@ -194,6 +194,7 @@ async def list_quantizable_models(self) -> tuple[list[dict], list[dict]]:
"""Scan all model dirs. Returns (source_models, all_models)."""
def _scan() -> tuple[list[dict], list[dict]]:
+ from ..model_classification import normalize_nemotron_config
from ..model_discovery import (
_is_readable_dir,
_iter_readable_entries,
@@ -251,6 +252,7 @@ def _scan() -> tuple[list[dict], list[dict]]:
try:
with open(path / "config.json") as f:
config = json.load(f)
+ config = normalize_nemotron_config(config)
size = _safetensors_size(path)
if size == 0:
continue
@@ -299,7 +301,7 @@ def _scan() -> tuple[list[dict], list[dict]]:
) or tc.get("num_hidden_layers", 0)
info_full["num_experts"] = config.get(
"num_local_experts", 0
- )
+ ) or tc.get("n_routed_experts", 0)
if is_v41:
info_full["num_layers"] = (
info_full["num_layers"] or tc.get("n_layers", 0)
diff --git a/omlx/custom_kernels/quant_matmul/csrc/affine_qmm.cpp b/omlx/custom_kernels/quant_matmul/csrc/affine_qmm.cpp
index a6e3f788d7..1f93943c31 100644
--- a/omlx/custom_kernels/quant_matmul/csrc/affine_qmm.cpp
+++ b/omlx/custom_kernels/quant_matmul/csrc/affine_qmm.cpp
@@ -65,6 +65,20 @@ bool affine_qmm_packed_shape_matches(int packed_dim, int K, int bits) {
static_cast(packed_dim) * 32 == static_cast(K) * bits;
}
+bool fp_mode_supported(const std::string& mode) {
+ return mode == "mxfp4" || mode == "mxfp8";
+}
+
+int fp_mode_bits(const std::string& mode) {
+ if (mode == "mxfp4") {
+ return 4;
+ }
+ if (mode == "mxfp8") {
+ return 8;
+ }
+ throw std::invalid_argument("Unsupported Qwen floating-point quantization mode.");
+}
+
constexpr const char* kNaxMetallibName = "omlx_quant_matmul_kernels_nax";
// Set to false once loading the NAX metallib (or one of its pipelines) fails
@@ -101,6 +115,16 @@ AffineQmmVariant affine_qmm_variant(int variant) {
}
}
+AffineQmmVariant fp_variant(int variant) {
+ auto config = affine_qmm_variant(variant);
+ if (config.bn > 64) {
+ std::ostringstream msg;
+ msg << "Unsupported Qwen floating-point qmm variant " << variant << ".";
+ throw std::invalid_argument(msg.str());
+ }
+ return config;
+}
+
// Must stay in sync with the instantiations in affine_qmm_nax.metal.
// Variant 0 matches the tile MLX ships for affine_qmm_t_nax. BK stays at or
// below the group size (64): QuantizedBlockLoader rejects larger columns.
@@ -199,8 +223,13 @@ class AffineQmmTPrimitive : public Primitive {
const auto cfg = affine_qmm_variant(variant);
const int K = x.shape(-1);
const int N = weight.shape(0);
+ const int M = K > 0 ? x.size() / K : 0;
+ const bool use_narrow_affine = variant == 8 && group_size == 64 &&
+ x.dtype() == bfloat16 && M >= 2048 && N == 48 &&
+ (bits == 4 || bits == 5);
if (K <= 0 || N <= 0 || x.size() <= 0 || K % group_size != 0 ||
- K % cfg.bk != 0 || N % cfg.bn != 0) {
+ K % (use_narrow_affine ? 64 : cfg.bk) != 0 ||
+ (!use_narrow_affine && N % cfg.bn != 0)) {
return true;
}
if (!affine_qmm_packed_shape_matches(weight.shape(1), K, bits) ||
@@ -234,6 +263,9 @@ class AffineQmmTPrimitive : public Primitive {
const int K = x.shape(-1);
const int N = weight.shape(0);
const int M = x.size() / K;
+ const bool use_narrow_affine = variant_ == 8 && group_size_ == 64 &&
+ x.dtype() == bfloat16 && M >= 2048 && N == 48 &&
+ (bits_ == 4 || bits_ == 5);
auto& compute_encoder = metal::get_command_encoder(s);
auto encode = [&](MTL::ComputePipelineState* kernel,
@@ -256,7 +288,7 @@ class AffineQmmTPrimitive : public Primitive {
compute_encoder.dispatch_threadgroups(grid_dims, group_dims);
};
- if (use_nax_ && nax_qmm_runtime_ok.load(std::memory_order_relaxed)) {
+ if (!use_narrow_affine && use_nax_ && nax_qmm_runtime_ok.load(std::memory_order_relaxed)) {
const auto cfg = affine_qmm_nax_variant(nax_variant_);
std::string kname;
concatenate(
@@ -290,7 +322,9 @@ class AffineQmmTPrimitive : public Primitive {
}
}
- const auto cfg = affine_qmm_variant(variant_);
+ const auto cfg = use_narrow_affine
+ ? AffineQmmVariant{32, 64, 16}
+ : affine_qmm_variant(variant_);
std::string kname;
concatenate(
kname,
@@ -332,6 +366,135 @@ class AffineQmmTPrimitive : public Primitive {
};
+class FpQmmTPrimitive : public Primitive {
+ public:
+ FpQmmTPrimitive(Stream stream, std::string mode, int variant)
+ : Primitive(stream), mode_(std::move(mode)), variant_(variant) {
+ if (!fp_mode_supported(mode_)) {
+ throw std::invalid_argument("Unsupported Qwen floating-point qmm mode.");
+ }
+ (void)fp_variant(variant_);
+ }
+
+ static bool unsupported(
+ const array& x,
+ const array& weight,
+ const array& scales,
+ const std::string& mode,
+ int variant,
+ Stream s) {
+ if (s.device == Device::cpu || !fp_mode_supported(mode)) {
+ return true;
+ }
+ if (x.dtype() != float16 && x.dtype() != bfloat16) {
+ return true;
+ }
+ if (weight.dtype() != uint32 || scales.dtype() != uint8) {
+ return true;
+ }
+ if (x.ndim() < 2 || weight.ndim() != 2 || scales.ndim() != 2) {
+ return true;
+ }
+ if (!row_contiguous(x) || !row_contiguous(weight) ||
+ !row_contiguous(scales)) {
+ return true;
+ }
+
+ const auto cfg = fp_variant(variant);
+ const int bits = fp_mode_bits(mode);
+ const int K = x.shape(-1);
+ const int N = weight.shape(0);
+ const int M = x.size() / K;
+ const bool use_narrow_mxfp4 = mode == "mxfp4" && variant == 8 &&
+ x.dtype() == bfloat16 && M >= 8192 && N == 48;
+ if (K <= 0 || N <= 0 || K % 32 != 0 ||
+ (use_narrow_mxfp4 ? K % 64 != 0 : K % cfg.bk != 0) ||
+ (!use_narrow_mxfp4 && N % cfg.bn != 0)) {
+ return true;
+ }
+ if (!affine_qmm_packed_shape_matches(weight.shape(1), K, bits) ||
+ scales.shape(0) != N || scales.shape(1) != K / 32) {
+ return true;
+ }
+ return false;
+ }
+
+ void eval_cpu(
+ const std::vector& /* inputs */,
+ std::vector& /* outputs */) override {
+ throw std::runtime_error("FpQmmTPrimitive 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& x = inputs[0];
+ const auto& weight = inputs[1];
+ const auto& scales = inputs[2];
+
+ out.set_data(allocator::malloc(out.nbytes()));
+
+ const int K = x.shape(-1);
+ const int N = weight.shape(0);
+ const int M = x.size() / K;
+ const bool use_narrow_mxfp4 = mode_ == "mxfp4" && variant_ == 8 &&
+ x.dtype() == bfloat16 && M >= 8192 && N == 48;
+ const auto cfg = use_narrow_mxfp4
+ ? AffineQmmVariant{
+ /* bm = */ 32, /* bk = */ 64, /* bn = */ 16}
+ : fp_variant(variant_);
+
+ std::string kname;
+ concatenate(
+ kname,
+ "qwen35_",
+ mode_,
+ "_qmm_t_",
+ metal_type_name(x.dtype()),
+ "_bm_",
+ cfg.bm,
+ "_bk_",
+ cfg.bk,
+ "_bn_",
+ cfg.bn);
+
+ auto lib = d.get_library("omlx_quant_matmul_kernels", binary_dir());
+ auto kernel = d.get_kernel(kname, lib);
+ auto& compute_encoder = metal::get_command_encoder(s);
+ compute_encoder.set_compute_pipeline_state(kernel);
+ compute_encoder.set_input_array(weight, 0);
+ compute_encoder.set_input_array(scales, 1);
+ compute_encoder.set_input_array(x, 2);
+ compute_encoder.set_output_array(out, 3);
+ compute_encoder.set_bytes(K, 4);
+ compute_encoder.set_bytes(N, 5);
+ compute_encoder.set_bytes(M, 6);
+
+ MTL::Size grid_dims(
+ (N + cfg.bn - 1) / cfg.bn, (M + cfg.bm - 1) / cfg.bm, 1);
+ MTL::Size group_dims(32, 2, 2);
+ compute_encoder.dispatch_threadgroups(grid_dims, group_dims);
+ }
+
+ DEFINE_NAME(FpQmmTPrimitive)
+ DEFINE_INPUT_OUTPUT_SHAPE()
+ bool is_equivalent(const Primitive& other) const override {
+ const auto& rhs = static_cast(other);
+ return mode_ == rhs.mode_ && variant_ == rhs.variant_;
+ }
+ auto state() const {
+ return std::make_tuple(mode_, variant_);
+ }
+
+ private:
+ std::string mode_;
+ int variant_;
+};
+
} // namespace
bool nax_qmm_kernels_built() {
@@ -516,4 +679,80 @@ array affine_q8_qmm_t(
}
+array fp_qmm_t(
+ const array& x,
+ const array& weight,
+ const array& scales,
+ const std::string& mode,
+ int variant,
+ StreamOrDevice s) {
+ (void)fp_variant(variant);
+ const int bits = fp_mode_bits(mode);
+ if (x.ndim() < 2 || weight.ndim() != 2 || scales.ndim() != 2) {
+ throw std::invalid_argument(
+ "[omlx_quant_matmul.fp_qmm_t] expected x [...,K], packed "
+ "weight, and scales [N,K/32].");
+ }
+
+ const int K = x.shape(-1);
+ const int N = weight.shape(0);
+ if (K <= 0 || N <= 0 || K % 32 != 0 ||
+ !affine_qmm_packed_shape_matches(weight.shape(1), K, bits) ||
+ scales.shape(0) != N || scales.shape(1) != K / 32) {
+ std::ostringstream msg;
+ msg << "[omlx_quant_matmul.qwen35_" << mode
+ << "_qmm_t] incompatible shapes: " << x.shape() << ", "
+ << weight.shape() << ", " << scales.shape() << ".";
+ throw std::invalid_argument(msg.str());
+ }
+ if (x.dtype() != float16 && x.dtype() != bfloat16) {
+ std::ostringstream msg;
+ msg << "[omlx_quant_matmul.qwen35_" << mode
+ << "_qmm_t] expected float16 or bfloat16 input, got " << x.dtype()
+ << ".";
+ throw std::invalid_argument(msg.str());
+ }
+ if (weight.dtype() != uint32 || scales.dtype() != uint8) {
+ std::ostringstream msg;
+ msg << "[omlx_quant_matmul.qwen35_" << mode
+ << "_qmm_t] expected uint32 weight and uint8 scales, got "
+ << weight.dtype() << ", " << scales.dtype() << ".";
+ throw std::invalid_argument(msg.str());
+ }
+
+ auto stream = to_stream(s);
+ if (FpQmmTPrimitive::unsupported(
+ x, weight, scales, mode, variant, stream)) {
+ throw std::invalid_argument(
+ "[omlx_quant_matmul.fp_qmm_t] unsupported shape.");
+ }
+
+ Shape out_shape = x.shape();
+ out_shape.back() = N;
+ std::vector inputs = {x, weight, scales};
+ return array(
+ std::move(out_shape),
+ x.dtype(),
+ std::make_shared(stream, mode, variant),
+ std::move(inputs));
+}
+
+array mxfp4_qmm_t(
+ const array& x,
+ const array& weight,
+ const array& scales,
+ int variant,
+ StreamOrDevice s) {
+ return fp_qmm_t(x, weight, scales, "mxfp4", variant, s);
+}
+
+array mxfp8_qmm_t(
+ const array& x,
+ const array& weight,
+ const array& scales,
+ int variant,
+ StreamOrDevice s) {
+ return fp_qmm_t(x, weight, scales, "mxfp8", variant, s);
+}
+
} // namespace omlx::quant_matmul
diff --git a/omlx/custom_kernels/quant_matmul/csrc/affine_qmm.h b/omlx/custom_kernels/quant_matmul/csrc/affine_qmm.h
index 2976f9fbd3..9fcd1d79f5 100644
--- a/omlx/custom_kernels/quant_matmul/csrc/affine_qmm.h
+++ b/omlx/custom_kernels/quant_matmul/csrc/affine_qmm.h
@@ -71,4 +71,18 @@ mx::array affine_q8_qmm_t(
int group_size = 64,
mx::StreamOrDevice s = {});
+mx::array mxfp4_qmm_t(
+ const mx::array& x,
+ const mx::array& weight,
+ const mx::array& scales,
+ int variant = 8,
+ mx::StreamOrDevice s = {});
+
+mx::array mxfp8_qmm_t(
+ const mx::array& x,
+ const mx::array& weight,
+ const mx::array& scales,
+ int variant = 8,
+ mx::StreamOrDevice s = {});
+
} // namespace omlx::quant_matmul
diff --git a/omlx/custom_kernels/quant_matmul/csrc/affine_qmm.metal b/omlx/custom_kernels/quant_matmul/csrc/affine_qmm.metal
index cdb55ab3d4..742b5eeac2 100644
--- a/omlx/custom_kernels/quant_matmul/csrc/affine_qmm.metal
+++ b/omlx/custom_kernels/quant_matmul/csrc/affine_qmm.metal
@@ -154,6 +154,8 @@ instantiate_qwen35_q_affine_variants(4);
instantiate_qwen35_q_affine_variants(5);
instantiate_qwen35_q_affine_variants(6);
instantiate_qwen35_q_affine_variants(8);
+instantiate_qwen35_q_affine_qmm_t(4, bfloat16_t, 32, 64, 16);
+instantiate_qwen35_q_affine_qmm_t(5, bfloat16_t, 32, 64, 16);
define_qwen35_q_affine_qmm128_t(2)
define_qwen35_q_affine_qmm128_t(4)
diff --git a/omlx/custom_kernels/quant_matmul/csrc/bindings.cpp b/omlx/custom_kernels/quant_matmul/csrc/bindings.cpp
index e2d0c2514d..79f9c342c4 100644
--- a/omlx/custom_kernels/quant_matmul/csrc/bindings.cpp
+++ b/omlx/custom_kernels/quant_matmul/csrc/bindings.cpp
@@ -144,6 +144,7 @@ NB_MODULE(_ext, m) {
m.def(
"nax_qmm_runtime_active",
&omlx::quant_matmul::nax_qmm_runtime_active);
+ m.attr("QMM_HAS_NARROW_AFFINE") = true;
m.def(
"ane_available",
&omlx::quant_matmul::ane_available);
@@ -582,6 +583,22 @@ NB_MODULE(_ext, m) {
"bits"_a,
"group_count"_a,
"stream"_a = nb::none());
+ m.def(
+ "mxfp4_qmm_t",
+ &omlx::quant_matmul::mxfp4_qmm_t,
+ "x"_a,
+ "weight"_a,
+ "scales"_a,
+ "variant"_a = 8,
+ "stream"_a = nb::none());
+ m.def(
+ "mxfp8_qmm_t",
+ &omlx::quant_matmul::mxfp8_qmm_t,
+ "x"_a,
+ "weight"_a,
+ "scales"_a,
+ "variant"_a = 8,
+ "stream"_a = nb::none());
m.def(
"moe_weighted_sum",
&omlx::quant_matmul::moe_weighted_sum,
diff --git a/omlx/custom_kernels/quant_matmul/csrc/fp_qmm.metal b/omlx/custom_kernels/quant_matmul/csrc/fp_qmm.metal
new file mode 100644
index 0000000000..20eb79a568
--- /dev/null
+++ b/omlx/custom_kernels/quant_matmul/csrc/fp_qmm.metal
@@ -0,0 +1,76 @@
+#include "mlx/backend/metal/kernels/utils.h"
+#include "mlx/backend/metal/kernels/steel/gemm/gemm.h"
+#include "mlx/backend/metal/kernels/fp_quantized.h"
+
+#define define_qwen35_fp_qmm_t(mode, bits) \
+ template \
+ [[kernel]] void qwen35_##mode##_qmm_t( \
+ const device uint32_t* w [[buffer(0)]], \
+ const device uint8_t* scales [[buffer(1)]], \
+ const device T* x [[buffer(2)]], \
+ device T* y [[buffer(3)]], \
+ const constant int& K [[buffer(4)]], \
+ const constant int& N [[buffer(5)]], \
+ const constant int& M [[buffer(6)]], \
+ uint3 tid [[threadgroup_position_in_grid]], \
+ uint lid [[thread_index_in_threadgroup]], \
+ uint simd_gid [[simdgroup_index_in_threadgroup]], \
+ uint simd_lid [[thread_index_in_simdgroup]]) { \
+ constexpr int BK_padded = (BK + 16 / sizeof(T)); \
+ \
+ threadgroup T Xs[BM * BK_padded]; \
+ threadgroup T Ws[BN * BK_padded]; \
+ \
+ fp_qmm_t_impl( \
+ w, \
+ scales, \
+ nullptr, \
+ x, \
+ y, \
+ Xs, \
+ Ws, \
+ K, \
+ N, \
+ M, \
+ K, \
+ tid, \
+ lid, \
+ simd_gid, \
+ simd_lid); \
+ }
+
+#define instantiate_qwen35_fp_qmm_t(mode, type, bm, bk, bn) \
+ instantiate_kernel( \
+ "qwen35_" #mode "_qmm_t_" #type "_bm_" #bm "_bk_" #bk "_bn_" #bn, \
+ qwen35_##mode##_qmm_t, \
+ type, \
+ bm, \
+ bk, \
+ bn)
+
+#define instantiate_qwen35_fp_variants(mode) \
+ instantiate_qwen35_fp_qmm_t(mode, float16_t, 32, 32, 32); \
+ instantiate_qwen35_fp_qmm_t(mode, bfloat16_t, 32, 32, 32); \
+ instantiate_qwen35_fp_qmm_t(mode, float16_t, 32, 64, 32); \
+ instantiate_qwen35_fp_qmm_t(mode, bfloat16_t, 32, 64, 32); \
+ instantiate_qwen35_fp_qmm_t(mode, float16_t, 32, 64, 64); \
+ instantiate_qwen35_fp_qmm_t(mode, bfloat16_t, 32, 64, 64); \
+ instantiate_qwen35_fp_qmm_t(mode, float16_t, 64, 64, 64); \
+ instantiate_qwen35_fp_qmm_t(mode, bfloat16_t, 64, 64, 64); \
+ instantiate_qwen35_fp_qmm_t(mode, float16_t, 16, 64, 64); \
+ instantiate_qwen35_fp_qmm_t(mode, bfloat16_t, 16, 64, 64); \
+ instantiate_qwen35_fp_qmm_t(mode, float16_t, 128, 64, 64); \
+ instantiate_qwen35_fp_qmm_t(mode, bfloat16_t, 128, 64, 64); \
+ instantiate_qwen35_fp_qmm_t(mode, float16_t, 128, 64, 32); \
+ instantiate_qwen35_fp_qmm_t(mode, bfloat16_t, 128, 64, 32); \
+ instantiate_qwen35_fp_qmm_t(mode, float16_t, 64, 32, 64); \
+ instantiate_qwen35_fp_qmm_t(mode, bfloat16_t, 64, 32, 64); \
+ instantiate_qwen35_fp_qmm_t(mode, float16_t, 128, 32, 64); \
+ instantiate_qwen35_fp_qmm_t(mode, bfloat16_t, 128, 32, 64)
+
+define_qwen35_fp_qmm_t(mxfp4, 4);
+define_qwen35_fp_qmm_t(mxfp8, 8);
+
+instantiate_qwen35_fp_variants(mxfp4);
+instantiate_qwen35_fp_variants(mxfp8);
+instantiate_qwen35_fp_qmm_t(mxfp4, bfloat16_t, 32, 64, 16);
diff --git a/omlx/custom_kernels/quant_matmul/csrc/moe_staging.cpp b/omlx/custom_kernels/quant_matmul/csrc/moe_staging.cpp
index 82e02b7d33..cdd3373220 100644
--- a/omlx/custom_kernels/quant_matmul/csrc/moe_staging.cpp
+++ b/omlx/custom_kernels/quant_matmul/csrc/moe_staging.cpp
@@ -153,4 +153,3 @@ void register_bindings(nb::module_& parent) {
}
} // namespace omlx::moe_staging
-
diff --git a/omlx/custom_kernels/quant_matmul/fast.py b/omlx/custom_kernels/quant_matmul/fast.py
index 98580b1af7..69deb198d8 100644
--- a/omlx/custom_kernels/quant_matmul/fast.py
+++ b/omlx/custom_kernels/quant_matmul/fast.py
@@ -63,6 +63,9 @@ def share_command_queue(stream) -> int | None:
# presence marks the new ABI. Older builds only carry gs=64 kernels; callers
# must keep gs!=64 layers on stock mlx (see qmm_supports_group_size).
_EXT_HAS_QMM_GROUP_SIZE = _ext is not None and hasattr(_ext, "affine_q2_qmm_t")
+_EXT_HAS_NARROW_AFFINE = bool(
+ _ext is not None and getattr(_ext, "QMM_HAS_NARROW_AFFINE", False)
+)
def _qmm_group_size_kwargs(group_size: int) -> dict:
@@ -81,6 +84,11 @@ def qmm_supports_group_size(group_size: int) -> bool:
return group_size == 64 or _EXT_HAS_QMM_GROUP_SIZE
+def qmm_supports_narrow_affine() -> bool:
+ """True if the extension contains the specialized 48-output qmm kernels."""
+ return _EXT_HAS_NARROW_AFFINE
+
+
_NAX_ARCH_RE = re.compile(r"applegpu_g(\d+)([a-z])")
@@ -743,3 +751,41 @@ def __dir__() -> list[str]:
if _ext is not None:
names.update(dir(_ext))
return sorted(names)
+
+
+def mxfp4_qmm_t(
+ x: mx.array,
+ weight: mx.array,
+ scales: mx.array,
+ variant: int = 8,
+ *,
+ stream=None,
+) -> mx.array:
+ if _ext is not None and hasattr(_ext, "mxfp4_qmm_t"):
+ return _ext.mxfp4_qmm_t(
+ x,
+ weight,
+ scales,
+ variant,
+ **_native_stream_kwargs(stream),
+ )
+ raise RuntimeError("mxfp4_qmm_t native kernel is unavailable")
+
+
+def mxfp8_qmm_t(
+ x: mx.array,
+ weight: mx.array,
+ scales: mx.array,
+ variant: int = 8,
+ *,
+ stream=None,
+) -> mx.array:
+ if _ext is not None and hasattr(_ext, "mxfp8_qmm_t"):
+ return _ext.mxfp8_qmm_t(
+ x,
+ weight,
+ scales,
+ variant,
+ **_native_stream_kwargs(stream),
+ )
+ raise RuntimeError("mxfp8_qmm_t native kernel is unavailable")
diff --git a/omlx/oq.py b/omlx/oq.py
index f8b27cf838..a17acc260d 100644
--- a/omlx/oq.py
+++ b/omlx/oq.py
@@ -13,6 +13,7 @@
import copy
import functools
import hashlib
+import importlib
import inspect
import json
import logging
@@ -59,6 +60,12 @@
except ImportError:
muse_spark_layout = muse_spark_serving = None
+from omlx.model_classification import (
+ NEMOTRON_OMNI_MODEL_TYPES,
+ is_nemotron_modelopt_source,
+ is_nemotron_omni,
+ normalize_nemotron_config,
+)
from omlx.model_discovery import (
D3_DECISION_CONFIG,
DECISION_SIDECAR_FILES,
@@ -673,6 +680,7 @@ def _is_token_embedding_tensor(path: str) -> bool:
".word_embeddings.weight",
".wte.weight",
f"{inkling2_layout.EMBED_PATH}.weight",
+ ".backbone.embeddings.weight",
)
)
@@ -723,16 +731,23 @@ def universal_quant_predicate(
if indexer_override is not None:
return indexer_override
- tc = config.get("text_config", {})
+ tc = config.get("text_config") or config.get("llm_config") or {}
num_layers = config.get("num_hidden_layers") or tc.get("num_hidden_layers", 32)
num_experts = (
config.get("num_local_experts")
or tc.get("num_local_experts")
or config.get("num_experts")
or tc.get("num_experts", 0)
+ or tc.get("n_routed_experts", 0)
or inkling2_layout.n_routed_experts(config)
or 0
)
+ if is_nemotron_omni(config.get("model_type")) and tc.get("block_configs"):
+ layer_index = _extract_layer_index(path)
+ if 0 <= layer_index < len(tc["block_configs"]):
+ num_experts = (
+ tc["block_configs"][layer_index].get("n_routed_experts") or num_experts
+ )
hidden_size = config.get("hidden_size") or tc.get("hidden_size", 0)
is_moe = num_experts > 0
@@ -966,6 +981,7 @@ def _is_vision_tensor(name: str) -> bool:
"visual.merger",
"image_norm",
"temporal_embed",
+ "mlp1.",
)
)
@@ -977,7 +993,7 @@ def _is_audio_tensor(name: str) -> bool:
`embed_audio.*` (the projection from audio output to text hidden size,
which is quantized like `embed_vision.embedding_projection`).
"""
- return "audio_tower" in name
+ return any(part in name for part in ("audio_tower", "sound_encoder", "sound_projection"))
def _is_moe_router(path: str) -> bool:
@@ -2080,7 +2096,9 @@ def validate_gemma4_assistant_pair(
quantization run.
"""
base_type = base_config.get("model_type")
- expected = GEMMA4_ASSISTANT_TYPES.get(base_type)
+ expected = (
+ GEMMA4_ASSISTANT_TYPES.get(base_type) if isinstance(base_type, str) else None
+ )
if expected is None:
raise ValueError(
"Assistant MTP combine requires a gemma4 base model "
@@ -3988,6 +4006,8 @@ def validate_quantizable(config: dict) -> bool:
return False
if "quantization" in config:
return False
+ if is_nemotron_modelopt_source(config):
+ return True
if "quantization_config" in config:
qc = config["quantization_config"]
if isinstance(qc, dict):
@@ -4072,7 +4092,7 @@ def estimate_bpw_and_size(
source = Path(model_path)
config_path = source / "config.json"
with open(config_path) as f:
- config = json.load(f)
+ config = normalize_nemotron_config(json.load(f))
weight_files = _source_weight_files(source)
if not weight_files:
@@ -4144,6 +4164,40 @@ def estimate_bpw_and_size(
config=config,
)
logical = idx.logical_metadata()
+ native_head_bytes = 0
+ native_head_params = 0
+ if preserve_mtp and is_nemotron_omni(config.get("model_type")):
+ modelopt_head = is_nemotron_modelopt_source(config)
+ for name in idx._index:
+ if name.startswith(("mtp.", "language_model.mtp.")) and not name.endswith(
+ (".input_scale", ".k_scale", ".v_scale")
+ ):
+ storage_dtype = idx.source_dtype(name)
+ if modelopt_head:
+ # Mirror the native splitter's FP8 expansion and NVFP4
+ # global-scale promotion without loading head tensors.
+ if name.endswith(".weight_scale"):
+ if idx.source_shape(name + "_2") is None:
+ continue
+ elif name.endswith(".weight_scale_2"):
+ storage_dtype = "F32"
+ elif name.endswith(".weight"):
+ prefix = name.removesuffix(".weight")
+ if (
+ idx.source_shape(prefix + ".weight_scale") is not None
+ and idx.source_shape(prefix + ".weight_scale_2") is None
+ ):
+ storage_dtype = idx.source_dtype(prefix + ".weight_scale")
+ if storage_dtype == "F32":
+ storage_dtype = "BF16"
+ native_head_bytes += math.prod(idx.source_shape(name)) * idx._DTYPE_BYTES[
+ storage_dtype
+ ]
+ native_head_params = sum(
+ math.prod(shape)
+ for name, (shape, _) in logical.items()
+ if name.startswith(("mtp.", "language_model.mtp."))
+ )
# Price on post-sanitize names when a streaming sanitize plan is
# discoverable — the quantization loop itself decides on those names.
@@ -4164,6 +4218,8 @@ def estimate_bpw_and_size(
if _plan:
plan_view = _DiscoveredPlan(_plan, idx)
except Exception as e:
+ if is_nemotron_omni(config.get("model_type")):
+ raise RuntimeError("Nemotron estimate could not resolve native weights") from e
logger.debug("bpw estimate: sanitize-plan discovery unavailable: %s", e)
if plan_view is not None:
@@ -4182,6 +4238,13 @@ def estimate_bpw_and_size(
if planned_logical:
logical = planned_logical
+ if is_nemotron_omni(config.get("model_type")):
+ logical = {
+ name: metadata
+ for name, metadata in logical.items()
+ if not _is_mtp_tensor(name)
+ }
+
def _source_quant_info(name):
if plan_view is not None:
return plan_view.source_quant_info(name)
@@ -4321,6 +4384,11 @@ def _source_quant_info(name):
source_total = sum(sf.stat().st_size for sf in _source_weight_files(source))
streaming_peak = int(source_total * 1.5) + 5 * 1024**3
+ if native_head_bytes:
+ total_output_bytes += native_head_bytes
+ effective_bpw = (effective_bpw * total_params + native_head_bytes * 8) / max(
+ total_params + native_head_params, 1
+ )
return {
"effective_bpw": round(effective_bpw, 2),
@@ -4550,6 +4618,16 @@ def _oqe_calibration_batch_plan(
("top_k_experts", "num_experts_per_tok", "moe_top_k", "top_k"),
default=1,
)
+ if is_nemotron_omni(config.get("model_type")):
+ blocks = (config.get("text_config") or {}).get("block_configs") or []
+ num_experts = max(
+ [num_experts]
+ + [_nested_config_int(block, ("n_routed_experts",)) for block in blocks]
+ )
+ top_k = max(
+ [top_k]
+ + [_nested_config_int(block, ("num_experts_per_tok",)) for block in blocks]
+ )
route_factor = max(1, top_k if num_experts > 0 else 1)
sample_bytes = max(1, int(seq_length) * max(1, hidden_size) * 4 * route_factor)
@@ -4826,6 +4904,7 @@ def _build_model_sanitizer(
from omlx.utils.model_loading import normalize_qwen35_text_config
normalize_qwen35_text_config(config)
+ config = normalize_nemotron_config(config)
if _is_muse_spark(config):
return muse_spark_layout.sanitizer(config, text_only=text_only)
if inkling2_layout.is_inkling2(config):
@@ -4894,6 +4973,12 @@ def _build_model_sanitizer(
)
apply_mlx_vlm_inkling_compat_patch()
+ if model_type == "bailing_moe_v3_vl":
+ from omlx.patches.mlx_vlm_bailing_moe_v3_vl_compat import (
+ apply_mlx_vlm_bailing_moe_v3_vl_compat_patch,
+ )
+
+ apply_mlx_vlm_bailing_moe_v3_vl_compat_patch()
if model_type == "muse_glimmer":
from omlx.patches.mlx_vlm_muse_glimmer_compat import (
apply_mlx_vlm_muse_glimmer_compat_patch,
@@ -5095,6 +5180,10 @@ def __getattr__(self, name):
predicate = getattr(language, "cast_predicate", None)
if predicate is not None:
_vlm_sanitize._omlx_cast_predicate = predicate
+ if is_nemotron_omni(model_type):
+ from mlx_vlm.models.nemotron_h.language import Model as NemotronText
+
+ _vlm_sanitize._omlx_cast_predicate = NemotronText.cast_predicate.fget(None)
logger.info(
f"Using mlx-vlm full sanitize chain for "
@@ -5103,6 +5192,8 @@ def __getattr__(self, name):
)
return _vlm_sanitize
except Exception as e:
+ if is_nemotron_omni(model_type):
+ raise RuntimeError("Native Nemotron sanitizer is unavailable") from e
logger.warning(f"mlx-vlm sanitizer not available for a VLM config: {e}")
try:
@@ -5331,7 +5422,13 @@ def _build_non_quantizable_set(config: dict) -> set:
quantization. Returns empty set if the model class cannot be loaded.
"""
try:
- model_class, model_args_class = _get_classes(config)
+ if is_nemotron_omni(config.get("model_type")):
+ from mlx_vlm.utils import get_model_and_args
+
+ module, _ = get_model_and_args(normalize_nemotron_config(config))
+ model_class, model_args_class = module.Model, module.ModelConfig
+ else:
+ model_class, model_args_class = _get_classes(config)
args = model_args_class.from_dict(config)
model = model_class(args)
@@ -5352,6 +5449,8 @@ def _build_non_quantizable_set(config: dict) -> set:
)
return result
except Exception as e:
+ if is_nemotron_omni(config.get("model_type")):
+ raise RuntimeError("Cannot establish native Nemotron quantization policy") from e
logger.debug(f"Could not build non-quantizable set: {e}")
return set()
@@ -7283,7 +7382,8 @@ def quantize_oq_streaming(
oq_sensitivity_map.json or an explicit sensitivity_model_path
still wins over both. None (default) auto-enables streaming when
the source exceeds the RAM budget. The streamed sourcer supports
- the MiniMax-M3 (minimax_m3_vl) and Qwen4-Exp (qwen4_exp) layouts,
+ MiniMax-M3, Qwen4-Exp, GLM-5.3, Muse Spark, and native Nemotron
+ multimodal layouts,
so the auto rule stays on the RAM-safe proxy for every other
model_type, and an explicit stream_calibration=True on an
unsupported layout raises a ValueError up front instead of
@@ -7346,6 +7446,25 @@ def cb(
config_path = source / "config.json"
with open(config_path) as f:
config = json.load(f)
+ config = normalize_nemotron_config(config)
+ native_nemotron = is_nemotron_omni(config.get("model_type"))
+ native_preserve_mtp = native_nemotron and preserve_mtp
+ if native_nemotron:
+ if text_only:
+ raise ValueError("Native Nemotron supports multimodal quantization exports only")
+ if not validate_quantizable(config):
+ raise ValueError(
+ "Nemotron conversion requires a floating-point or native ModelOpt source, "
+ "not an existing MLX quantization"
+ )
+ if native_preserve_mtp:
+ from .utils.model_loading import _checkpoint_has_mtp_weights
+
+ if not _checkpoint_has_mtp_weights(source):
+ raise ValueError("Preserve MTP requested but this Nemotron source has no head")
+ # The official target deliberately excludes the head. Preserve it
+ # independently in mlx-vlm's native split format, never as target keys.
+ preserve_mtp = False
normalized_model_type = str(config.get("model_type", "")).lower().replace(
"-", "_"
)
@@ -7713,10 +7832,10 @@ def _imatrix_load_path() -> str:
f"calibration sweep ({len(streamed_sensitivity_map)} layers)"
)
sensitivity_map = streamed_sensitivity_map
- elif stream_imatrix:
+ elif stream_imatrix or is_nemotron_modelopt_source(config):
# Streaming calibration is active but the fused sweep never ran
- # (imatrix cache hit). Measure with a standalone streamed pass:
- # still the real weights, still no proxy, no whole-model load.
+ # (imatrix cache hit), or packed ModelOpt modules need real-weight
+ # perturbation. Both use a standalone streamed pass, never a proxy.
logger.info(
f"oQ{oq_level:g}: measuring sensitivity by streaming layers "
"from the source checkpoint (no calibration proxy)"
@@ -7863,6 +7982,8 @@ def _imatrix_load_path() -> str:
f"({e}); the eager fallback would materialize the whole "
"model in BF16"
) from e
+ if native_nemotron:
+ raise RuntimeError("Native Nemotron streaming sanitize discovery failed") from e
if _model_requires_proxy:
raise RuntimeError(
f"oQ{oq_level:g}: streaming sanitize-plan discovery "
@@ -8371,6 +8492,10 @@ def _imatrix_load_path() -> str:
"routed_expert_scales": True,
}
_apply_output_dtype(output_config, dtype)
+ if native_preserve_mtp:
+ from .patches.nemotron_omni_quantization import export_native_mtp
+
+ export_native_mtp(source, output, output_config)
with open(output / "config.json", "w") as f:
json.dump(output_config, f, indent=2, ensure_ascii=False)
if imatrix_report is not None:
@@ -8414,7 +8539,15 @@ def _imatrix_load_path() -> str:
_OQE_MAX_ADAPTIVE_SAMPLES = 1024
_OQE_MIN_EXPERT_COUNT = 16
_OQE_MIN_EXPERT_COUNT_PERCENTILE = 5
-_OQE_SWITCH_LINEAR_CLASSES = {"SwitchLinear", "QuantizedSwitchLinear", "ExpertProj"}
+# Include native NVFP4 expert wrappers with per-tensor/per-expert global scales.
+_OQE_SWITCH_LINEAR_CLASSES = {
+ "SwitchLinear",
+ "QuantizedSwitchLinear",
+ "ExpertProj",
+ "ScaledSwitchLinear",
+ "NVFP4SwitchLinear",
+ "ScaledQuantizedSwitchLinear",
+}
def _is_oqe_switch_module(module) -> bool:
@@ -8743,6 +8876,11 @@ def _find_model_layers(model):
# EmbeddingGemma 2 keeps its text encoder directly on language_model.
embed_fn = model.language_model.embed_tokens
layers = model.language_model.layers
+ elif hasattr(model, "language_model") and hasattr(
+ model.language_model, "backbone"
+ ):
+ embed_fn = model.language_model.backbone.embeddings
+ layers = model.language_model.backbone.layers
elif hasattr(model, "embed_tokens"):
embed_fn = model.embed_tokens
layers = model.layers
@@ -9039,6 +9177,8 @@ def _commit_layer_forward_aux(state, layer_idx: int, aux, fallback=None) -> None
def _forward_layer_result(block, inputs, mask, position_ids, layer_idx=None):
"""Forward pass through a transformer layer, returning output and aux."""
+ if isinstance(position_ids, dict) and position_ids.get("kind") == "nemotron_h_omni":
+ return block(inputs, mask=mask, cache=None), None
if (
isinstance(position_ids, dict)
and position_ids.get("kind") == _FLINT_LAYER_STATE_KIND
@@ -9454,6 +9594,15 @@ def _prepare_layer_inputs(model, layers, calib_data, inputs, *, noncausal=False)
# build their own masks and take no cache.
state = {"kind": _INKLING2_LAYER_STATE_KIND, "blocks": []}
return inputs, [None] * len(layers), state
+ if is_nemotron_omni(model_type):
+ from mlx_vlm.models.base import create_attention_mask as native_attention_mask
+
+ attention_mask = native_attention_mask(inputs, None)
+ return (
+ inputs,
+ [attention_mask if layer.block_type == "*" else None for layer in layers],
+ {"kind": "nemotron_h_omni"},
+ )
gemma4_inputs = _prepare_gemma4_layer_inputs(model, layers, calib_data, inputs)
if gemma4_inputs is not None:
return gemma4_inputs
@@ -9620,7 +9769,9 @@ def _is_capture_module(module) -> bool:
# already-quantized checkpoints (e.g. deriving a recalibrated MTP
# head from an oQ8 model when the bf16 source is gone).
return (
- cls in ("Linear", "QuantizedLinear", "QuantizedProjection")
+ cls in (
+ "Linear", "QuantizedLinear", "QuantizedProjection", "ScaledQuantizedLinear"
+ )
and hasattr(module, "weight")
and getattr(module.weight, "ndim", 0) == 2
)
@@ -10363,7 +10514,13 @@ def _collect_imatrix_from_model(
_STREAM_CALIBRATION_SUPPORTED_MODEL_TYPES = frozenset(
{"minimax_m3_vl", "qwen4_exp", "glm5_next", "muse_spark", "flint"}
| _QWEN3_5_STREAM_MODEL_TYPES
-)
+) | NEMOTRON_OMNI_MODEL_TYPES
+
+
+def _streamed_layer_prefix(config: dict) -> str:
+ if is_nemotron_omni(config.get("model_type")):
+ return "language_model.backbone.layers."
+ return _STREAM_TEXT_LAYER_PREFIX
def _stream_calibration_supported(model_type: str | None) -> bool:
@@ -10391,16 +10548,25 @@ def _streamed_text_args(model_path, config, *, trust_remote_code: bool = False):
from mlx_vlm.models.flint.language import DecoderLayer
return ModelConfig.from_dict(config), DecoderLayer
+ if is_nemotron_omni(config.get("model_type")):
+ from mlx_vlm.models.nemotron_h.config import ModelConfig as TextConfig
+
+ from .patches.nemotron_omni_quantization import streamed_decoder_layer
+
+ return TextConfig.from_dict(config["text_config"]), streamed_decoder_layer
if _stream_source_model_type(config) == "qwen4_exp":
from mlx_vlm.models.qwen4_exp.config import TextConfig
from mlx_vlm.models.qwen4_exp.language import Qwen4ExpDecoderLayer
layer_cls = Qwen4ExpDecoderLayer
elif _stream_source_model_type(config) == "glm5_next":
- from mlx_vlm.models.glm5_next.config import TextConfig
- from mlx_vlm.models.glm5_next.language import Glm5NextDecoderLayer
+ g5_config = importlib.import_module("mlx_vlm.models.glm5_next.config")
+ g5_lang = importlib.import_module("mlx_vlm.models.glm5_next.language")
- layer_cls = Glm5NextDecoderLayer
+ return (
+ g5_config.TextConfig.from_dict(config["text_config"]),
+ g5_lang.Glm5NextDecoderLayer,
+ )
elif _is_muse_spark(config):
# mlx-lm's decoder block; calibration_items maps oQ's tensors to it.
args = muse_spark_layout.calibration_args(config)
@@ -10437,7 +10603,10 @@ def _streamed_source_plan(
return _DiscoveredPlan(plan, lazy_index)
-def _streamed_layer_items(dp: "_DiscoveredPlan", layer_idx: int, skip_key=None) -> list:
+def _streamed_layer_items(
+ dp: "_DiscoveredPlan", layer_idx: int, skip_key=None, *,
+ layer_prefix: str = _STREAM_TEXT_LAYER_PREFIX,
+) -> list:
"""Pop every tensor of one text layer, keyed relative to the bare block.
``skip_key`` (relative-key predicate) filters BEFORE the pop: a skipped
@@ -10446,7 +10615,7 @@ def _streamed_layer_items(dp: "_DiscoveredPlan", layer_idx: int, skip_key=None)
self-sources — popping them first and discarding after would read the
whole table every round and spike process memory by the table's size.
"""
- prefix = f"{_STREAM_TEXT_LAYER_PREFIX}{layer_idx}."
+ prefix = f"{layer_prefix}{layer_idx}."
keys = sorted(k for k in dp if k.startswith(prefix))
if not keys:
raise KeyError(f"no checkpoint tensors for text layer {layer_idx}")
@@ -10526,7 +10695,9 @@ def _iter_streamed_layer_blocks(
else None
)
for layer_idx in range(args.num_hidden_layers):
- items = _streamed_layer_items(dp, layer_idx, skip_key=skip_key)
+ items = _streamed_layer_items(
+ dp, layer_idx, skip_key=skip_key, layer_prefix=_streamed_layer_prefix(config)
+ )
if _is_muse_spark(config):
items = muse_spark_layout.calibration_items(items, layer_idx, config)
block = layer_cls(args, layer_idx)
@@ -10542,7 +10713,8 @@ def _iter_streamed_layer_blocks(
del items
mx.eval(block.parameters())
is_moe = bool(
- getattr(
+ getattr(block, "block_type", None) == "E"
+ or getattr(
block,
"is_moe_layer",
"SparseMoeBlock" in type(getattr(block, "mlp", None)).__name__,
@@ -10559,7 +10731,12 @@ def _iter_streamed_layer_blocks(
def _streamed_embed_weight(source, config: dict):
"""Source the token embedding table (bf16 on disk)."""
dp = _streamed_source_plan(source, config)
- weight = dp.pop(_STREAM_EMBED_KEY)
+ key = (
+ "language_model.backbone.embeddings.weight"
+ if is_nemotron_omni(config.get("model_type"))
+ else _STREAM_EMBED_KEY
+ )
+ weight = dp.pop(key)
mx.eval(weight)
return weight
@@ -10750,6 +10927,17 @@ class _StreamingNoModel:
"""
+def _nemotron_streamed_state(embedded):
+ from mlx_vlm.models.base import create_attention_mask as native_attention_mask
+
+ return {
+ "inputs": embedded,
+ "mask": native_attention_mask(embedded, None),
+ "position_ids": {"kind": "nemotron_h_omni"},
+ "scores": {},
+ }
+
+
def _streamed_glm5_next_state(config: dict, embedded):
"""Streamed counterpart of the glm5_next branch of _prepare_layer_inputs."""
text_config = config.get("text_config") or {}
@@ -10804,6 +10992,9 @@ def _streamed_sensitivity_state(
"position_ids": {"kind": _FLINT_LAYER_STATE_KIND},
"scores": {},
}
+ if is_nemotron_omni(config.get("model_type")):
+ mx.eval(inputs)
+ return _nemotron_streamed_state(inputs)
if _stream_source_model_type(config) == "glm5_next":
inputs, attention_mask = _streamed_glm5_next_state(config, inputs)
mx.eval(inputs)
@@ -10860,7 +11051,9 @@ def _streamed_sensitivity_layer(
bug, and a silently missing score would skew the bit allocation.
"""
layer_masks = state.get("layer_masks")
- if state.get("block_driven_attention_mask"):
+ if is_nemotron_omni(config.get("model_type")):
+ layer_mask = state["mask"] if block.block_type == "*" else None
+ elif state.get("block_driven_attention_mask"):
layer_mask = None if bool(getattr(block, "is_linear", False)) else state["mask"]
elif layer_masks is not None:
layer_mask = layer_masks[layer_idx]
@@ -10967,15 +11160,16 @@ def _collect_streamed_untied_lm_head(source, config, collector, working) -> int:
def _collect_streamed_glm5_next_mtp(
- source, config, collector, calib_data, working, ranges
+ source, config, collector: OQImatrixCollector, calib_data, working, ranges
) -> int:
"""Streamed counterpart of the glm5_next branch of _collect_mtp_head_imatrix."""
- from mlx_vlm.models.glm5_next import language as g5_lang
from mlx_vlm.models.glm5_next.config import TextConfig
from omlx.patches.mlx_vlm_mtp import glm5_next_vlm_runtime
- glm5_next_vlm_runtime.apply()
+ if not glm5_next_vlm_runtime.apply():
+ raise RuntimeError("GLM-5.3 streamed MTP calibration requires the runtime patch")
+ g5_lang = importlib.import_module("mlx_vlm.models.glm5_next.language")
prefix = "language_model.mtp.0."
plan = _streamed_source_plan(source, config, preserve_mtp=True)
head = g5_lang.Glm5NextMTPBlock(TextConfig.from_dict(config["text_config"]))
@@ -11212,6 +11406,10 @@ def embed_rows(weight, lo: int, hi: int):
elif _stream_source_model_type(config) == "flint":
mask = None
position_ids = {"kind": _FLINT_LAYER_STATE_KIND}
+ elif is_nemotron_omni(config.get("model_type")):
+ native_state = _nemotron_streamed_state(embedded[:1])
+ mask = native_state["mask"]
+ position_ids = native_state["position_ids"]
else:
# One causal mask serves every attention layer and micro-batch. Position
# ids keep one row per sample, sliced per micro-batch below.
@@ -11278,7 +11476,7 @@ def embed_rows(weight, lo: int, hi: int):
for layer_idx, block, _is_moe in _iter_streamed_layer_blocks(
source, config, trust_remote_code=trust_remote_code
):
- prefix = f"{_STREAM_TEXT_LAYER_PREFIX}{layer_idx}."
+ prefix = f"{_streamed_layer_prefix(config)}{layer_idx}."
layer_installed = collector.install(block, name_prefix=prefix)
if round_index == 0:
installed += layer_installed
@@ -11299,6 +11497,8 @@ def embed_rows(weight, lo: int, hi: int):
)
if is_qwen4_exp:
layer_mask = q4_layer_masks[layer_idx]
+ elif is_nemotron_omni(config.get("model_type")):
+ layer_mask = mask if block.block_type == "*" else None
elif is_glm5_next:
layer_mask = None if bool(getattr(block, "is_linear", False)) else mask
elif _is_recurrent_layer(block):
diff --git a/omlx/patches/qwen35_compiled_mlp.py b/omlx/patches/qwen35_compiled_mlp.py
new file mode 100644
index 0000000000..4a6fe72a5a
--- /dev/null
+++ b/omlx/patches/qwen35_compiled_mlp.py
@@ -0,0 +1,194 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Compile stateless Qwen3.5-family MLP blocks for decode-shaped calls."""
+
+from __future__ import annotations
+
+import inspect
+import logging
+import os
+from typing import Any, ClassVar
+
+import mlx.core as mx
+import mlx.nn as nn
+from mlx.utils import tree_unflatten
+
+logger = logging.getLogger(__name__)
+
+
+class CompiledMLPBlocks:
+ """Install and configure compiled stateless-MLP wrappers."""
+
+ MAX_COMPILED_TOKENS: ClassVar[int] = 4
+
+ @classmethod
+ def enabled(cls) -> bool:
+ return os.environ.get("OMLX_QWEN35_COMPILED_MLP", "1") != "0"
+
+ @classmethod
+ def _target_policies(cls) -> dict[type, type[CompiledMLPBlock] | None]:
+ from mlx_lm.models.qwen3_next import (
+ Qwen3NextMLP,
+ Qwen3NextSparseMoeBlock,
+ )
+ from mlx_vlm.models.qwen3_5.language import Qwen3_5MLP
+ from mlx_vlm.models.qwen3_5_moe.language import (
+ Qwen3_5MoeMLP,
+ Qwen3_5MoeSparseMoeBlock,
+ )
+
+ parameters = list(inspect.signature(Qwen3NextMLP.__call__).parameters)
+ if parameters != ["self", "x"]:
+ raise RuntimeError(
+ "mlx-lm Qwen3NextMLP.__call__ signature changed "
+ f"({parameters}); update the compiled MLP policy"
+ )
+ for target in (Qwen3_5MLP, Qwen3_5MoeMLP):
+ parameters = list(inspect.signature(target.__call__).parameters)
+ if parameters not in (["self", "x"], ["self", "x", "target_verify"]):
+ raise RuntimeError(
+ f"mlx-vlm {target.__name__}.__call__ signature changed "
+ f"({parameters}); update the compiled MLP policy"
+ )
+ return {
+ Qwen3NextMLP: CompiledMLPBlock,
+ # Whole-MoE compilation is not bit-exact on every Metal GPU.
+ # Keep these blocks and their nested shared experts eager.
+ Qwen3NextSparseMoeBlock: None,
+ Qwen3_5MLP: CompiledTargetVerifyMLPBlock,
+ Qwen3_5MoeMLP: CompiledTargetVerifyMLPBlock,
+ Qwen3_5MoeSparseMoeBlock: None,
+ }
+
+ @classmethod
+ def install(cls, model: Any, *, enabled: bool | None = None) -> int:
+ """Wrap outermost exact-type targets after model loading is complete."""
+
+ if enabled is None:
+ enabled = cls.enabled()
+ if not enabled or not mx.metal.is_available():
+ return 0
+ if not isinstance(model, nn.Module):
+ raise TypeError(
+ "CompiledMLPBlocks.install expects an mlx nn.Module, got "
+ f"{type(model).__name__}"
+ )
+
+ policies = cls._target_policies()
+ wrapper_prefixes = [
+ name + "." if name else ""
+ for name, module in model.named_modules()
+ if isinstance(module, CompiledMLPBlock)
+ ]
+ candidates = {
+ name: module
+ for name, module in model.named_modules()
+ if type(module) in policies
+ and not any(name.startswith(prefix) for prefix in wrapper_prefixes)
+ }
+ outermost = [
+ name
+ for name in candidates
+ if not any(
+ (not other or name.startswith(other + "."))
+ for other in candidates
+ if other != name
+ )
+ ]
+ replacements = []
+ for name in sorted(outermost):
+ wrapper = policies[type(candidates[name])]
+ if wrapper is not None:
+ replacements.append((name, wrapper(candidates[name])))
+ if replacements:
+ if any(
+ isinstance(replacement, CompiledTargetVerifyMLPBlock)
+ for _, replacement in replacements
+ ):
+ _patch_vlm_exact_verifier()
+ model.update_modules(tree_unflatten(replacements))
+ logger.info(
+ "Wrapped %d Qwen MLP blocks for compiled decode dispatch",
+ len(replacements),
+ )
+ return len(replacements)
+
+
+class CompiledMLPBlock(nn.Module):
+ """Wrapper for stateless unary blocks called as ``block(x)``."""
+
+ def __init__(self, inner: nn.Module):
+ super().__init__()
+ self.inner = inner
+ self.train(inner.training)
+ # mx.compile captures the final weight arrays. Install this wrapper
+ # only after all load-time transforms; post-install weight rebinding
+ # is unsupported because it would leave the trace on stale arrays.
+ self._compiled = mx.compile(inner.__call__)
+
+ def routes_compiled(self, x: mx.array) -> bool:
+ return (
+ not self.training
+ and x.ndim == 3
+ and x.shape[0] == 1
+ and x.shape[1] <= CompiledMLPBlocks.MAX_COMPILED_TOKENS
+ and x.dtype in (mx.float16, mx.bfloat16)
+ )
+
+ def dispatch_compiled(self, x: mx.array) -> mx.array:
+ return self._compiled(x)
+
+ def __call__(self, x: mx.array) -> mx.array:
+ if self.routes_compiled(x):
+ return self.dispatch_compiled(x)
+ return self.inner(x)
+
+
+class CompiledTargetVerifyMLPBlock(CompiledMLPBlock):
+ """Wrapper that keeps mlx-vlm speculative verification eager."""
+
+ def __init__(self, inner: nn.Module):
+ super().__init__(inner)
+ self._inner_accepts_target_verify = (
+ "target_verify" in inspect.signature(inner.__call__).parameters
+ )
+
+ def __call__(self, x: mx.array, target_verify: bool = False) -> mx.array:
+ if not target_verify and self.routes_compiled(x):
+ return self.dispatch_compiled(x)
+ if self._inner_accepts_target_verify:
+ return self.inner(x, target_verify)
+ return self.inner(x)
+
+
+def _patch_vlm_exact_verifier() -> None:
+ """Keep current mlx-vlm's exact verifier on the uncompiled inner block."""
+ try:
+ from mlx_vlm.models.qwen3_5 import language as q35
+ except ImportError:
+ return
+
+ verifier = q35.LanguageModel.__call__.__globals__.get(
+ "_EXACT_SPECULATIVE_VERIFIER"
+ )
+ if verifier is None:
+ return
+ verifier_cls = type(verifier)
+ if getattr(verifier_cls, "_omlx_compiled_mlp_unwrap", False):
+ return
+
+ original = verifier_cls._feed_forward
+
+ def feed_forward(self, module, x):
+ if isinstance(module, CompiledTargetVerifyMLPBlock):
+ module = module.inner
+ return original(self, module, x)
+
+ verifier_cls._feed_forward = feed_forward
+ verifier_cls._omlx_compiled_mlp_unwrap = True
+
+
+__all__ = [
+ "CompiledMLPBlock",
+ "CompiledMLPBlocks",
+ "CompiledTargetVerifyMLPBlock",
+]
diff --git a/omlx/patches/qwen35_gdn_decode.py b/omlx/patches/qwen35_gdn_decode.py
new file mode 100644
index 0000000000..caa5581cc7
--- /dev/null
+++ b/omlx/patches/qwen35_gdn_decode.py
@@ -0,0 +1,329 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Fuse Qwen3.5-family decode convolution state handling into one Metal launch."""
+
+from __future__ import annotations
+
+import logging
+import os
+from typing import Any
+
+import mlx.core as mx
+import mlx.nn as nn
+
+logger = logging.getLogger(__name__)
+
+_ENABLED = False
+_LM_PATCHED = False
+_VLM_PATCHED = False
+_KERNEL = None
+
+_SOURCE = r"""
+ uint gid = thread_position_in_grid.x;
+ uint batch = gid / uint(C);
+ uint c = gid - batch * uint(C);
+ uint state_base = batch * 3 * uint(C);
+ uint input_base = batch * uint(C);
+ float s0 = float(state[state_base + c]);
+ float s1 = float(state[state_base + uint(C) + c]);
+ float s2 = float(state[state_base + 2 * uint(C) + c]);
+ float s3 = float(x[input_base + c]);
+ uint weight_base = c * 4;
+ float acc = float(weight[weight_base]) * s0
+ + float(weight[weight_base + 1]) * s1
+ + float(weight[weight_base + 2]) * s2
+ + float(weight[weight_base + 3]) * s3;
+ T y = T(acc);
+ T sigmoid_tail = T(1) / (T(1) + metal::exp(metal::abs(y)));
+ T sigmoid = y < T(0) ? sigmoid_tail : T(1) - sigmoid_tail;
+ output[input_base + c] = y * sigmoid;
+ new_state[state_base + c] = T(s1);
+ new_state[state_base + uint(C) + c] = T(s2);
+ new_state[state_base + 2 * uint(C) + c] = T(s3);
+"""
+
+
+def _kernel():
+ global _KERNEL
+ if _KERNEL is None:
+ _KERNEL = mx.fast.metal_kernel(
+ name="omlx_qwen35_fused_decode_conv",
+ input_names=["state", "x", "weight"],
+ output_names=["new_state", "output"],
+ source=_SOURCE,
+ )
+ return _KERNEL
+
+
+def fused_conv_silu(state, x, weight):
+ """Return bit-exact decode convolution output and shifted state."""
+
+ batch, _, channels = state.shape
+ return _kernel()(
+ inputs=[state, x, weight],
+ template=[("T", state.dtype), ("C", channels)],
+ grid=(batch * channels, 1, 1),
+ threadgroup=(min(channels, 256), 1, 1),
+ output_shapes=[state.shape, (batch, 1, channels)],
+ output_dtypes=[state.dtype, state.dtype],
+ )
+
+
+def try_fused_conv_silu(
+ module: Any,
+ state,
+ x,
+ *,
+ mask=None,
+ lengths=None,
+):
+ """Use the fused path when the call has safe decode geometry."""
+
+ if (
+ not _ENABLED
+ or mask is not None
+ or lengths is not None
+ or x.ndim != 3
+ or x.shape[1] != 1
+ or state is None
+ or state.ndim != 3
+ or state.shape[0] != x.shape[0]
+ or state.shape[1] != 3
+ or state.shape[2] != x.shape[2]
+ or getattr(module, "conv_kernel_size", 0) != 4
+ or module.conv1d.weight.dtype != x.dtype
+ or state.dtype != x.dtype
+ ):
+ return None
+
+ cached = getattr(module, "_omlx_decode_conv_weight", None)
+ cache_key = (id(module.conv1d.weight), x.dtype)
+ if cached is None or cached[0] != cache_key:
+ weight = mx.contiguous(module.conv1d.weight.reshape(x.shape[-1], 4))
+ mx.eval(weight)
+ cached = (cache_key, weight)
+ module._omlx_decode_conv_weight = cached
+ return fused_conv_silu(state, x, cached[1])
+
+
+def _patch_lm() -> bool:
+ global _LM_PATCHED
+ if _LM_PATCHED:
+ return True
+ try:
+ from mlx.nn.layers.distributed import sum_gradients
+ from mlx_lm.models import qwen3_5 as q35
+ from mlx_lm.models.gated_delta import gated_delta_update
+ except ImportError:
+ return False
+
+ cls = q35.GatedDeltaNet
+ if getattr(cls.__call__, "_omlx_fused_decode_conv", False):
+ _LM_PATCHED = True
+ return True
+ # The native-MTP patch owns this method but calls try_fused_conv_silu
+ # directly from its shared chunk helper.
+ if getattr(cls.__call__, "_omlx_mtp_call_marker", False):
+ _LM_PATCHED = True
+ return True
+
+ def call(self, inputs, mask=None, cache=None):
+ batch, seq_len, _ = inputs.shape
+ if self.sharding_group is not None:
+ inputs = sum_gradients(self.sharding_group)(inputs)
+
+ qkv = self.in_proj_qkv(inputs)
+ z = self.in_proj_z(inputs).reshape(
+ batch, seq_len, self.num_v_heads, self.head_v_dim
+ )
+ b = self.in_proj_b(inputs)
+ a = self.in_proj_a(inputs)
+ if cache is not None and cache[0] is not None:
+ conv_state = cache[0]
+ else:
+ conv_state = mx.zeros(
+ (batch, self.conv_kernel_size - 1, self.conv_dim),
+ dtype=inputs.dtype,
+ )
+
+ lengths = cache.lengths if cache is not None else None
+ fused = try_fused_conv_silu(self, conv_state, qkv, mask=mask, lengths=lengths)
+ if fused is not None:
+ new_conv_state, conv_out = fused
+ else:
+ if mask is not None:
+ qkv = mx.where(mask[..., None], qkv, 0)
+ conv_input = mx.concatenate([conv_state, qkv], axis=1)
+ n_keep = self.conv_kernel_size - 1
+ if lengths is not None:
+ ends = mx.clip(lengths, 0, seq_len)
+ positions = (ends[:, None] + mx.arange(n_keep))[..., None]
+ new_conv_state = mx.take_along_axis(conv_input, positions, axis=1)
+ else:
+ new_conv_state = mx.contiguous(conv_input[:, -n_keep:, :])
+ conv_out = nn.silu(self.conv1d(conv_input))
+
+ q, k, v = [
+ tensor.reshape(batch, seq_len, heads, dims)
+ for tensor, heads, dims in zip(
+ mx.split(conv_out, [self.key_dim, 2 * self.key_dim], -1),
+ [self.num_k_heads, self.num_k_heads, self.num_v_heads],
+ [self.head_k_dim, self.head_k_dim, self.head_v_dim],
+ )
+ ]
+ state = cache[1] if cache else None
+ inv_scale = k.shape[-1] ** -0.5
+ q = (inv_scale**2) * mx.fast.rms_norm(q, None, 1e-6)
+ k = inv_scale * mx.fast.rms_norm(k, None, 1e-6)
+ out, state = gated_delta_update(
+ q,
+ k,
+ v,
+ a,
+ b,
+ self.A_log,
+ self.dt_bias,
+ state,
+ mask,
+ use_kernel=not self.training,
+ )
+ if cache is not None:
+ cache[0] = new_conv_state
+ cache[1] = state
+ cache.advance(seq_len)
+ out = self.norm(out, z)
+ out = self.out_proj(out.reshape(batch, seq_len, -1))
+ if self.sharding_group is not None:
+ out = mx.distributed.all_sum(out, group=self.sharding_group)
+ return out
+
+ call._omlx_fused_decode_conv = True
+ call._omlx_original = cls.__call__
+ cls.__call__ = call
+ _LM_PATCHED = True
+ return True
+
+
+def _patch_vlm() -> bool:
+ global _VLM_PATCHED
+ if _VLM_PATCHED:
+ return True
+ try:
+ from mlx_vlm.models.qwen3_5 import language as q35
+ except ImportError:
+ return False
+
+ cls = q35.Qwen3_5GatedDeltaNet
+ if getattr(cls.__call__, "_omlx_fused_decode_conv", False):
+ _VLM_PATCHED = True
+ return True
+ original = cls.__call__
+
+ def call(self, inputs, mask=None, cache=None):
+ if cache is not None and cache.is_speculating:
+ return original(self, inputs, mask=mask, cache=cache)
+ batch, seq_len, _ = inputs.shape
+ mixed_qkv = self.in_proj_qkv(inputs)
+ z = self.in_proj_z(inputs).reshape(batch, seq_len, -1, self.head_v_dim)
+ b = self.in_proj_b(inputs)
+ a = self.in_proj_a(inputs)
+ if cache is not None and cache[0] is not None:
+ conv_state = cache[0]
+ if conv_state.shape[0] != batch:
+ conv_state = mx.zeros(
+ (batch, self.conv_kernel_size - 1, self.conv_dim),
+ dtype=inputs.dtype,
+ )
+ else:
+ conv_state = mx.zeros(
+ (batch, self.conv_kernel_size - 1, self.conv_dim),
+ dtype=inputs.dtype,
+ )
+
+ lengths = getattr(cache, "lengths", None) if cache is not None else None
+ if mask is not None and mask.shape[0] != batch:
+ mask = None
+ fused = try_fused_conv_silu(
+ self, conv_state, mixed_qkv, mask=mask, lengths=lengths
+ )
+ if fused is not None:
+ new_conv_state, conv_out = fused
+ else:
+ if mask is not None:
+ mixed_qkv = mx.where(mask[..., None], mixed_qkv, 0)
+ conv_input = mx.concatenate([conv_state, mixed_qkv], axis=1)
+ n_keep = self.conv_kernel_size - 1
+ if lengths is not None:
+ ends = mx.clip(lengths, 0, seq_len)
+ positions = (ends[:, None] + mx.arange(n_keep))[..., None]
+ new_conv_state = mx.take_along_axis(conv_input, positions, axis=1)
+ else:
+ new_conv_state = mx.contiguous(conv_input[:, -n_keep:, :])
+ if (
+ seq_len == 1
+ and conv_input.shape[1] == self.conv_kernel_size
+ and self.conv1d.weight.dtype in (mx.bfloat16, mx.float16)
+ ):
+ conv_out = nn.silu(self._causal_conv1d_decode(conv_input))
+ else:
+ conv_out = nn.silu(self.conv1d(conv_input))
+
+ q, k, v = [
+ tensor.reshape(batch, seq_len, heads, dims)
+ for tensor, heads, dims in zip(
+ mx.split(conv_out, [self.key_dim, 2 * self.key_dim], -1),
+ [self.num_k_heads, self.num_k_heads, self.num_v_heads],
+ [self.head_k_dim, self.head_k_dim, self.head_v_dim],
+ )
+ ]
+ state = cache[1] if cache else None
+ if state is not None and state.shape[0] != batch:
+ state = None
+ q, k = self._normalize_qk(q, k)
+ out, state = q35.gated_delta_update(
+ q,
+ k,
+ v,
+ a,
+ b,
+ self.A_log,
+ self.dt_bias,
+ state,
+ mask,
+ use_kernel=not self.training,
+ )
+ if cache is not None:
+ cache[0] = new_conv_state
+ cache[1] = state
+ if hasattr(cache, "advance"):
+ cache.advance(seq_len)
+ q35._qwen3_5_advance_lengths_info(cache, seq_len)
+ out = self.norm(out, z)
+ return self.out_proj(out.reshape(batch, seq_len, -1))
+
+ call._omlx_fused_decode_conv = True
+ call._omlx_original = original
+ cls.__call__ = call
+ _VLM_PATCHED = True
+ return True
+
+
+def apply_qwen35_gdn_decode_patch() -> bool:
+ """Install the default-on, opt-out fused decode path."""
+
+ global _ENABLED
+ if os.environ.get("OMLX_QWEN35_GDN_DECODE_FUSION", "1") == "0":
+ return False
+ if not mx.metal.is_available():
+ return False
+ _ENABLED = True
+ applied = _patch_lm() | _patch_vlm()
+ if applied:
+ logger.info("Qwen3.5-family fused GDN decode convolution enabled")
+ return applied
+
+
+__all__ = [
+ "apply_qwen35_gdn_decode_patch",
+ "fused_conv_silu",
+ "try_fused_conv_silu",
+]
diff --git a/omlx/patches/qwen35_moe_routed_decode.py b/omlx/patches/qwen35_moe_routed_decode.py
index aaabbf1cb8..13ba1953bb 100644
--- a/omlx/patches/qwen35_moe_routed_decode.py
+++ b/omlx/patches/qwen35_moe_routed_decode.py
@@ -793,6 +793,7 @@ def routed_decode_plan(block, x) -> _Plan | None:
"""The block's cached plan when ``x`` is one bf16 or fp16 token it can route."""
if (
_DISABLED
+ or not block.norm_topk_prob
or x.dtype not in (mx.bfloat16, mx.float16)
or block.top_k not in TOP_KS
):
@@ -919,6 +920,7 @@ def routed_verify_window(block, x):
if (
_WINDOW_DISABLED
or _DISABLED
+ or not block.norm_topk_prob
or x.ndim != 3
or x.dtype not in (mx.bfloat16, mx.float16)
or block.top_k not in TOP_KS
diff --git a/omlx/patches/qwen35_moe_router.py b/omlx/patches/qwen35_moe_router.py
index 98de0cc5c3..3015285955 100644
--- a/omlx/patches/qwen35_moe_router.py
+++ b/omlx/patches/qwen35_moe_router.py
@@ -708,14 +708,21 @@ def _ensure_vlm_verify_patch() -> None:
@wraps(original)
def verify(self, feed_forward, x):
- if not (
- isinstance(feed_forward, Qwen3_5MoeSparseMoeBlock)
- and x.ndim == 3
- and router_eligible(x, feed_forward.num_experts)
+ if not (isinstance(feed_forward, Qwen3_5MoeSparseMoeBlock) and x.ndim == 3):
+ return original(self, feed_forward, x)
+ if feed_forward.norm_topk_prob and not router_eligible(
+ x, feed_forward.num_experts
):
return original(self, feed_forward, x)
gates = mx.softmax(self._linear(feed_forward.gate, x), axis=-1, precise=True)
- indices, scores = fused_router_topk(gates, feed_forward.top_k)
+ if feed_forward.norm_topk_prob:
+ indices, scores = fused_router_topk(gates, feed_forward.top_k)
+ else:
+ indices = mx.argpartition(gates, kth=-feed_forward.top_k, axis=-1)[
+ ..., -feed_forward.top_k :
+ ]
+ indices = mx.stop_gradient(indices)
+ scores = mx.take_along_axis(gates, indices, axis=-1)
shared = self._feed_forward(feed_forward.shared_expert, x)
shared = mx.sigmoid(self._linear(feed_forward.shared_expert_gate, x)) * shared
routed = self._switch_glu(feed_forward.switch_mlp, x, indices)
@@ -781,7 +788,7 @@ def patched_call(self, x):
vlm_orig = vcls.__call__
def vlm_patched_call(self, x):
- if not router_eligible(x, self.num_experts):
+ if not self.norm_topk_prob or not router_eligible(x, self.num_experts):
return vlm_orig(self, x)
# Children by item: this runs for every MoE layer of every decode step.
gates = mx.softmax(self["gate"](x), axis=-1, precise=True)
diff --git a/omlx/patches/qwen35_q4_mlp.py b/omlx/patches/qwen35_q4_mlp.py
index e238de2743..1beb28d102 100644
--- a/omlx/patches/qwen35_q4_mlp.py
+++ b/omlx/patches/qwen35_q4_mlp.py
@@ -1,11 +1,12 @@
+# SPDX-License-Identifier: Apache-2.0
# ruff: noqa: N806
-"""Qwen3.5/3.6 quantized MLP prefill matmul patch.
+"""Qwen3.5/3.6 quantized prefill matmul patch.
-Replaces eligible affine QuantizedLinear calls inside the Qwen MLP with the
-same affine qmm math through an oMLX native wrapper with a Qwen-friendly tile.
-The tile changes the accumulation order, so outputs match stock MLX to
-rounding (about 1 ulp), not bit for bit. Decode and target-verify paths fall
-through to the original implementation.
+This replaces eligible affine, MXFP4, and MXFP8
+QuantizedLinear calls with the corresponding MLX qmm implementation exposed
+through an oMLX native wrapper using a Qwen-friendly tile. The tile changes
+the accumulation order, so outputs match stock MLX to rounding, not bit for
+bit. Decode and target-verify paths fall through to the original implementation.
"""
from __future__ import annotations
@@ -13,6 +14,7 @@
import importlib
import logging
from collections.abc import Callable
+from functools import wraps
from typing import Any
import mlx.core as mx
@@ -43,12 +45,18 @@
# Native qmm tile variant and the prompt lengths from which it beats stock MLX.
_QMM_VARIANT = 8
_MIN_TOKENS = 2048
+_SUPPORTED_FP_QMM_VARIANTS = frozenset((0, 1, 2, 3, 4, 6, 7, 8, 9))
_Q8_MIN_TOKENS = 16384
# Decode and verify guard, not a profitability floor: the A8 backend applies
# a8_prefill_min_tokens itself, and rows below this never ask it.
_Q8_BACKEND_MIN_ROWS = 64
+def _default_min_tokens() -> int:
+ name = str(mx.device_info().get("device_name", ""))
+ return 128 if name.startswith("Apple M4") else _MIN_TOKENS
+
+
def register_qwen35_lm_gdn_prefill_backend(
backend: (
Callable[
@@ -126,6 +134,17 @@ def _native_qmm_for_bits(bits: int) -> Callable[..., mx.array] | None:
return getattr(fast, name)
+def _native_fp_qmm_for_mode(mode: str) -> Callable[..., mx.array] | None:
+ try:
+ from omlx.custom_kernels.quant_matmul import fast
+ except Exception:
+ return None
+ name = f"{mode}_qmm_t"
+ if mode not in ("mxfp4", "mxfp8") or not fast.has_symbol(name):
+ return None
+ return getattr(fast, name)
+
+
def _qmm_supports_group_size(group_size: int) -> bool:
try:
from omlx.custom_kernels.quant_matmul import fast
@@ -142,6 +161,14 @@ def _native_qmm_has_nax() -> bool:
return fast.nax_qmm_kernels_built()
+def _qmm_supports_narrow_affine() -> bool:
+ try:
+ from omlx.custom_kernels.quant_matmul import fast
+ except Exception:
+ return False
+ return fast.qmm_supports_narrow_affine()
+
+
def _has_native_qmm() -> bool:
return _native_qmm_for_bits(4) is not None
@@ -155,44 +182,81 @@ def _is_supported_affine_linear_shape(
) -> bool:
if not isinstance(linear, nn.QuantizedLinear):
return False
+ if mx.default_device() != mx.gpu:
+ return False
if dtype not in (mx.float16, mx.bfloat16):
return False
if ndim < 2 or seq_len <= 1:
return False
group_size = getattr(linear, "group_size", None)
- if group_size not in (64, 128):
- return False
- if not _qmm_supports_group_size(int(group_size)):
- return False
- if is_nax_available() and (group_size == 128 or not _native_qmm_has_nax()):
- # Stock MLX uses NAX on M5. The custom tile has a NAX kernel only for
- # gs64, and only when the extension was built with an SDK that has it.
- return False
bits = getattr(linear, "bits", None)
- if bits not in _SUPPORTED_QMM_BITS or getattr(linear, "mode", None) != "affine":
- return False
- if _native_qmm_for_bits(int(bits)) is None:
+ mode = getattr(linear, "mode", None)
+ if mode == "affine":
+ if group_size not in (64, 128):
+ return False
+ if not _qmm_supports_group_size(int(group_size)):
+ return False
+ if is_nax_available() and (group_size == 128 or not _native_qmm_has_nax()):
+ # Only gs64 kernels built with a supporting SDK can use NAX.
+ return False
+ if bits not in _SUPPORTED_QMM_BITS or _native_qmm_for_bits(int(bits)) is None:
+ return False
+ elif mode in ("mxfp4", "mxfp8"):
+ expected_bits = 4 if mode == "mxfp4" else 8
+ if (
+ group_size != 32
+ or bits != expected_bits
+ or _native_fp_qmm_for_mode(mode) is None
+ ):
+ return False
+ else:
return False
if "bias" in linear:
return False
weight = getattr(linear, "weight", None)
scales = getattr(linear, "scales", None)
biases = getattr(linear, "biases", None)
- if weight is None or scales is None or biases is None:
+ if weight is None or scales is None:
return False
- if weight.dtype != mx.uint32 or scales.dtype != dtype or biases.dtype != dtype:
+ if weight.dtype != mx.uint32:
return False
- if weight.ndim != 2 or scales.ndim != 2 or biases.ndim != 2:
+ if weight.ndim != 2 or scales.ndim != 2:
return False
if weight.shape[1] * 32 != input_dim * int(bits):
return False
- if input_dim % 64 != 0 or weight.shape[0] % 64 != 0:
- return False
- if scales.shape != biases.shape:
+ narrow_affine = (
+ mode == "affine"
+ and _qmm_supports_narrow_affine()
+ and group_size == 64
+ and bits in (4, 5)
+ and dtype == mx.bfloat16
+ and seq_len >= 2048
+ and weight.shape[0] == 48
+ )
+ narrow_mxfp4 = (
+ mode == "mxfp4"
+ and dtype == mx.bfloat16
+ and seq_len >= 8192
+ and weight.shape[0] == 48
+ )
+ if input_dim % 64 != 0 or (
+ weight.shape[0] % 64 != 0 and not narrow_affine and not narrow_mxfp4
+ ):
return False
+ expected_scale_shape = (weight.shape[0], input_dim // int(group_size))
+ if mode == "affine":
+ return (
+ scales.dtype == dtype
+ and biases is not None
+ and biases.dtype == dtype
+ and biases.ndim == 2
+ and scales.shape == expected_scale_shape
+ and biases.shape == expected_scale_shape
+ )
return (
- scales.shape[0] == weight.shape[0]
- and scales.shape[1] == input_dim // group_size
+ scales.dtype == mx.uint8
+ and biases is None
+ and scales.shape == expected_scale_shape
)
@@ -253,6 +317,34 @@ def _quantized_linear_output_dim(linear: Any) -> int | None:
def _linear_qmm(linear: nn.QuantizedLinear, x: mx.array, variant: int) -> mx.array:
+ mode = getattr(linear, "mode", None)
+ weight = getattr(linear, "weight", None)
+ if (
+ mode == "affine"
+ and weight is not None
+ and weight.shape[0] == 48
+ and x.shape[-2] >= 2048
+ and variant != 8
+ ):
+ return linear(x)
+ if mode in ("mxfp4", "mxfp8"):
+ if (
+ mode == "mxfp4"
+ and weight is not None
+ and weight.shape[0] == 48
+ and x.shape[-2] >= 8192
+ and variant != 8
+ ):
+ return linear(x)
+ qmm = _native_fp_qmm_for_mode(mode)
+ if (
+ qmm is None
+ or variant not in _SUPPORTED_FP_QMM_VARIANTS
+ or not _is_supported_affine_linear(linear, x)
+ ):
+ return linear(x)
+ return qmm(x, linear.weight, linear.scales, variant)
+
bits = getattr(linear, "bits", None)
qmm = _native_qmm_for_bits(int(bits)) if bits is not None else None
if qmm is None:
@@ -279,19 +371,23 @@ def _make_patched_mlp(
min_tokens: int,
q8_min_tokens: int,
):
+ @wraps(orig_call)
def patched(self, x, *args, **kwargs):
# Decode / short-sequence fast path first: this wrapper runs on every
# MLP call of every layer of every decode step, so the common case
# must exit on a single shape check (issue #2132 — per-call gate
# overhead across the qwen35 prefill patches costs ~2% TG).
- if x.ndim < 3 or x.shape[-2] < min_tokens:
+ gate_proj = getattr(self, "gate_proj", None)
+ route_min = _route_min_tokens_for_bits(
+ getattr(gate_proj, "bits", None), min_tokens, q8_min_tokens
+ )
+ if x.ndim < 3 or x.shape[-2] < route_min:
return orig_call(self, x, *args, **kwargs)
target_verify = bool(kwargs.get("target_verify", False))
if args and isinstance(args[0], bool):
target_verify = target_verify or bool(args[0])
if target_verify:
return orig_call(self, x, *args, **kwargs)
- gate_proj = getattr(self, "gate_proj", None)
up_proj = getattr(self, "up_proj", None)
down_proj = getattr(self, "down_proj", None)
gate_dim = _quantized_linear_output_dim(gate_proj)
@@ -350,7 +446,7 @@ def apply_qwen35_q4_mlp_patch() -> bool:
return False
variant = _QMM_VARIANT
- min_tokens = _MIN_TOKENS
+ min_tokens = _default_min_tokens()
q8_min_tokens = _Q8_MIN_TOKENS
patched = False
patched |= _patch_class(
@@ -501,7 +597,7 @@ def apply_qwen35_q4_prefill_linear_patch(model) -> bool:
"""Route the loaded Qwen projections without replacing their forward graph."""
if not _has_native_qmm():
return False
- _VLMQuantizedPrefillLinear._route_min_tokens = _MIN_TOKENS
+ _VLMQuantizedPrefillLinear._route_min_tokens = _default_min_tokens()
_VLMQuantizedPrefillLinear._route_q8_min_tokens = _Q8_MIN_TOKENS
_VLMQuantizedPrefillLinear._route_variant = _QMM_VARIANT
installed = False
@@ -550,7 +646,7 @@ def apply_qwen35_q4_lm_prefill_linear_patch() -> bool:
return False
variant = _QMM_VARIANT
- min_tokens = _MIN_TOKENS
+ min_tokens = _default_min_tokens()
q8_min_tokens = _Q8_MIN_TOKENS
def should_route(linear: Any, x: mx.array) -> bool:
@@ -892,7 +988,7 @@ def apply_muse_glimmer_q4_prefill_patch() -> bool:
return False
variant = _QMM_VARIANT
- min_tokens = _MIN_TOKENS
+ min_tokens = _default_min_tokens()
q8_min_tokens = _Q8_MIN_TOKENS
patched = _patch_class(
diff --git a/omlx/patches/qwen35_verify_qmm.py b/omlx/patches/qwen35_verify_qmm.py
index c73b7a5340..54efb311a6 100644
--- a/omlx/patches/qwen35_verify_qmm.py
+++ b/omlx/patches/qwen35_verify_qmm.py
@@ -1,4 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
+# ruff: noqa: N803, N806, SIM300
#
# Adapted from MTPLX (mtplx/verify_kernels.py)
# Copyright 2026 Youssof Altoukhi
@@ -49,8 +50,8 @@
from the unrouted path (the token is still trunk-verified — the divergence
class is the same as any kernel change).
-Supported: 4-bit and 8-bit affine, group_size in {32, 64, 128}, bf16/fp16
-activations, M in 3..6, K % 64 == 0, N % 4 == 0.
+Supported: 4-bit and 8-bit affine, MXFP4, and MXFP8 with bf16/fp16
+activations and M in 3..6.
The mma path takes 2-, 3-, 4-, 5-, 6- and 8-bit affine, M in 7..24.
It needs K % 256 == 0 and N % 16 == 0. Everything else falls back to stock.
@@ -107,6 +108,55 @@ class is the same as any kernel change).
# On tensor-unit GPUs stock qmm beats sg8 for a single projection below 6 rows.
_SG8_SINGLE_MIN_ROWS_NAX = 6
+_FP_HEADER = r"""
+struct OMLXFP4E2M1 {
+ operator float16_t() {
+ half converted = as_type(ushort((bits & 7) << 9));
+ converted *= 16384.0;
+ return bits & 8 ? -converted : converted;
+ }
+ operator float() {
+ return static_cast(this->operator float16_t());
+ }
+ uint8_t bits;
+};
+
+struct OMLXFP8E4M3 {
+ operator float16_t() {
+ uint16_t value = (bits & 127) << 7;
+ half converted = as_type(value);
+ converted *= 256.0;
+ return bits & 128 ? -converted : converted;
+ }
+ operator float() {
+ return static_cast(this->operator float16_t());
+ }
+ uint8_t bits;
+};
+
+struct OMLXFP8E8M0 {
+ operator float() {
+ uint32_t value = bits == 0
+ ? 0x400000
+ : (static_cast(bits) << 23);
+ return as_type(value);
+ }
+ uint8_t bits;
+};
+
+inline float omlx_fp4_weight(uint8_t value) {
+ return float(*(thread OMLXFP4E2M1*)(&value));
+}
+
+inline float omlx_fp8_weight(uint8_t value) {
+ return float(*(thread OMLXFP8E4M3*)(&value));
+}
+
+inline float omlx_fp_scale(uint8_t value) {
+ return float(*(thread OMLXFP8E8M0*)(&value));
+}
+"""
+
def set_verify_qmm_armed(flag: bool, *, row_exact: bool = False) -> None:
"""Arm/disarm verify-qmm routing (MTP verify forwards only).
@@ -134,15 +184,22 @@ def is_row_exact_armed() -> bool:
# ---------------------------------------------------------------------------
-def _fma_block(m: int, bits: int) -> str:
+def _fma_block(m: int, bits: int, mode: str) -> str:
per = 8 if bits == 4 else 4
mask = "0xFu" if bits == 4 else "0xFFu"
shift = 4 if bits == 4 else 8
lines = [f"for (int ki = 0; ki < {per}; ++ki) {{"]
- for j in range(4):
- lines.append(
- f" float w{j} = float((p{j} >> (ki * {shift})) & {mask}) * s{j} + b{j};"
+ if mode == "affine":
+ weight_expr = (
+ f"float((p{{j}} >> (ki * {shift})) & {mask}) * s{{j}} + b{{j}}"
+ )
+ else:
+ converter = "omlx_fp4_weight" if bits == 4 else "omlx_fp8_weight"
+ weight_expr = (
+ f"{converter}(uint8_t((p{{j}} >> (ki * {shift})) & {mask})) * s{{j}}"
)
+ for j in range(4):
+ lines.append(f" float w{j} = {weight_expr.format(j=j)};")
for j in range(4):
for r in range(m):
lines.append(
@@ -153,10 +210,12 @@ def _fma_block(m: int, bits: int) -> str:
return "\n ".join(lines)
-def _build_msg_kernel(m: int, bits: int, group_size: int, dtype, nsg: int):
+def _build_msg_kernel(
+ m: int, bits: int, group_size: int, mode: str, dtype, nsg: int
+):
import mlx.core as mx
- key = ("msg", m, bits, group_size, dtype, nsg)
+ key = ("msg", m, bits, group_size, mode, dtype, nsg)
if key in _KERNEL_CACHE:
return _KERNEL_CACHE[key]
@@ -172,23 +231,55 @@ def _build_msg_kernel(m: int, bits: int, group_size: int, dtype, nsg: int):
uint32_t p2 = w_q[(n0 + 2) * K_by_p + pack];
uint32_t p3 = w_q[(n0 + 3) * K_by_p + pack];
"""
+ scale_loads = (
+ "\n".join(
+ f" float s{j} = omlx_fp_scale(scales[(n0 + {j}) * K_by_gs + gi]);"
+ for j in range(4)
+ )
+ if mode != "affine"
+ else "\n".join(
+ f" float s{j} = float(scales[(n0 + {j}) * K_by_gs + gi]);"
+ for j in range(4)
+ )
+ )
+ bias_loads = (
+ ""
+ if mode != "affine"
+ else "\n".join(
+ f" float b{j} = float(biases[(n0 + {j}) * K_by_gs + gi]);"
+ for j in range(4)
+ )
+ )
body = f"""
for (int pack = int(lane); pack < K_by_p; pack += 32) {{
{pack_setup}
{xloads}
- float s0 = float(scales[(n0 + 0) * K_by_gs + gi]);
- float s1 = float(scales[(n0 + 1) * K_by_gs + gi]);
- float s2 = float(scales[(n0 + 2) * K_by_gs + gi]);
- float s3 = float(scales[(n0 + 3) * K_by_gs + gi]);
- float b0 = float(biases[(n0 + 0) * K_by_gs + gi]);
- float b1 = float(biases[(n0 + 1) * K_by_gs + gi]);
- float b2 = float(biases[(n0 + 2) * K_by_gs + gi]);
- float b3 = float(biases[(n0 + 3) * K_by_gs + gi]);
+{scale_loads}
+{bias_loads}
_Pragma("unroll")
- {_fma_block(m, 4)}
+ {_fma_block(m, 4, mode)}
}}
"""
else:
+ scale_loads = (
+ "\n".join(
+ f" float s{j} = omlx_fp_scale(scales[(n0 + {j}) * K_by_gs + gi]);"
+ for j in range(4)
+ )
+ if mode != "affine"
+ else "\n".join(
+ f" float s{j} = float(scales[(n0 + {j}) * K_by_gs + gi]);"
+ for j in range(4)
+ )
+ )
+ bias_loads = (
+ ""
+ if mode != "affine"
+ else "\n".join(
+ f" float b{j} = float(biases[(n0 + {j}) * K_by_gs + gi]);"
+ for j in range(4)
+ )
+ )
body = f"""
for (int pair = int(lane); pair < K_by_p; pair += 32) {{
int k_base = pair * 8;
@@ -201,16 +292,10 @@ def _build_msg_kernel(m: int, bits: int, group_size: int, dtype, nsg: int):
uint32_t p1 = w_q[(n0 + 1) * (K / 4) + pair * 2 + wsel];
uint32_t p2 = w_q[(n0 + 2) * (K / 4) + pair * 2 + wsel];
uint32_t p3 = w_q[(n0 + 3) * (K / 4) + pair * 2 + wsel];
- float s0 = float(scales[(n0 + 0) * K_by_gs + gi]);
- float s1 = float(scales[(n0 + 1) * K_by_gs + gi]);
- float s2 = float(scales[(n0 + 2) * K_by_gs + gi]);
- float s3 = float(scales[(n0 + 3) * K_by_gs + gi]);
- float b0 = float(biases[(n0 + 0) * K_by_gs + gi]);
- float b1 = float(biases[(n0 + 1) * K_by_gs + gi]);
- float b2 = float(biases[(n0 + 2) * K_by_gs + gi]);
- float b3 = float(biases[(n0 + 3) * K_by_gs + gi]);
+{scale_loads}
+{bias_loads}
_Pragma("unroll")
- {_fma_block(m, 8)}
+ {_fma_block(m, 8, mode)}
}}
}}
"""
@@ -258,9 +343,10 @@ def _build_msg_kernel(m: int, bits: int, group_size: int, dtype, nsg: int):
dtype_tag = {mx.bfloat16: "bf16", mx.float16: "fp16"}.get(dtype, "unk")
kernel = mx.fast.metal_kernel(
- name=f"omlx_vk_m{m}_q{bits}_nsg{nsg}_gs{group_size}_{dtype_tag}",
+ name=f"omlx_vk_m{m}_{mode}{bits}_nsg{nsg}_gs{group_size}_{dtype_tag}",
input_names=["x", "w_q", "scales", "biases", "K_size", "N_size"],
output_names=["y"],
+ header=_FP_HEADER if mode != "affine" else "",
source=source,
)
_KERNEL_CACHE[key] = kernel
@@ -272,7 +358,7 @@ def _build_msg_kernel(m: int, bits: int, group_size: int, dtype, nsg: int):
# ---------------------------------------------------------------------------
-def _pack_block(m: int, bits: int, sfx: str) -> str:
+def _pack_block(m: int, bits: int, mode: str, sfx: str) -> str:
p = f"pack{sfx}"
lines = [f"int k_base{sfx} = {p} * 8;", f"int gi{sfx} = k_base{sfx} / GS;"]
for r in range(m):
@@ -281,19 +367,35 @@ def _pack_block(m: int, bits: int, sfx: str) -> str:
for j in range(4):
lines.append(f"uint32_t p{sfx}_{j} = w_q[(n0 + {j}) * K_by_p + {p}];")
for j in range(4):
- lines.append(
- f"float s{sfx}_{j} = float(scales[(n0 + {j}) * K_by_gs + gi{sfx}]);"
- f" float b{sfx}_{j} = float(biases[(n0 + {j}) * K_by_gs + gi{sfx}]);"
+ scale = (
+ f"omlx_fp_scale(scales[(n0 + {j}) * K_by_gs + gi{sfx}])"
+ if mode != "affine"
+ else f"float(scales[(n0 + {j}) * K_by_gs + gi{sfx}])"
+ )
+ bias = (
+ ""
+ if mode != "affine"
+ else f" float b{sfx}_{j} = float(biases[(n0 + {j}) * K_by_gs + gi{sfx}]);"
)
+ lines.append(f"float s{sfx}_{j} = {scale};{bias}")
for j in range(4):
block = [
"{",
f" uint32_t packed = p{sfx}_{j};",
f" float s = s{sfx}_{j};",
- f" float b = b{sfx}_{j};",
- " for (int ki = 0; ki < 8; ++ki) {",
- " float wv = float((packed >> (ki * 4)) & 0xFu) * s + b;",
]
+ if mode == "affine":
+ block.append(f" float b = b{sfx}_{j};")
+ block.extend(
+ [
+ " for (int ki = 0; ki < 8; ++ki) {",
+ (
+ " float wv = omlx_fp4_weight(uint8_t((packed >> (ki * 4)) & 0xFu)) * s;"
+ if mode == "mxfp4"
+ else " float wv = float((packed >> (ki * 4)) & 0xFu) * s + b;"
+ ),
+ ]
+ )
for r in range(m):
block.append(
f" acc[{j} * {m} + {r}] += float(v{sfx}_{r}[ki]) * wv;"
@@ -307,21 +409,41 @@ def _pack_block(m: int, bits: int, sfx: str) -> str:
f" uint32_t pb{sfx}_{j} = w_q[(n0 + {j}) * K_by_w + {p} * 2 + 1];"
)
for j in range(4):
- lines.append(
- f"float s{sfx}_{j} = float(scales[(n0 + {j}) * K_by_gs + gi{sfx}]);"
- f" float b{sfx}_{j} = float(biases[(n0 + {j}) * K_by_gs + gi{sfx}]);"
+ scale = (
+ f"omlx_fp_scale(scales[(n0 + {j}) * K_by_gs + gi{sfx}])"
+ if mode != "affine"
+ else f"float(scales[(n0 + {j}) * K_by_gs + gi{sfx}])"
+ )
+ bias = (
+ ""
+ if mode != "affine"
+ else f" float b{sfx}_{j} = float(biases[(n0 + {j}) * K_by_gs + gi{sfx}]);"
)
+ lines.append(f"float s{sfx}_{j} = {scale};{bias}")
for j in range(4):
block = [
"{",
f" uint32_t pa = pa{sfx}_{j};",
f" uint32_t pb = pb{sfx}_{j};",
f" float s = s{sfx}_{j};",
- f" float b = b{sfx}_{j};",
- " for (int ki = 0; ki < 4; ++ki) {",
- " float wa = float((pa >> (ki * 8)) & 0xFFu) * s + b;",
- " float wb = float((pb >> (ki * 8)) & 0xFFu) * s + b;",
]
+ if mode == "affine":
+ block.append(f" float b = b{sfx}_{j};")
+ block.extend(
+ [
+ " for (int ki = 0; ki < 4; ++ki) {",
+ (
+ " float wa = omlx_fp8_weight(uint8_t((pa >> (ki * 8)) & 0xFFu)) * s;"
+ if mode == "mxfp8"
+ else " float wa = float((pa >> (ki * 8)) & 0xFFu) * s + b;"
+ ),
+ (
+ " float wb = omlx_fp8_weight(uint8_t((pb >> (ki * 8)) & 0xFFu)) * s;"
+ if mode == "mxfp8"
+ else " float wb = float((pb >> (ki * 8)) & 0xFFu) * s + b;"
+ ),
+ ]
+ )
for r in range(m):
block.append(
f" acc[{j} * {m} + {r}] += float(v{sfx}_{r}[ki]) * wa;"
@@ -334,17 +456,25 @@ def _pack_block(m: int, bits: int, sfx: str) -> str:
return "\n ".join(lines)
-def _build_ksplit_kernel(m: int, bits: int, group_size: int, dtype, *, k_parts: int):
+def _build_ksplit_kernel(
+ m: int,
+ bits: int,
+ group_size: int,
+ mode: str,
+ dtype,
+ *,
+ k_parts: int,
+):
import mlx.core as mx
- key = ("ksplit", m, bits, group_size, dtype, k_parts)
+ key = ("ksplit", m, bits, group_size, mode, dtype, k_parts)
if key in _KERNEL_CACHE:
return _KERNEL_CACHE[key]
n_acc = 4 * m
loop = f"""
for (int packA = p_start + int(lane); packA < p_end; packA += 32) {{
- {_pack_block(m, bits, "A")}
+ {_pack_block(m, bits, mode, "A")}
}}
"""
@@ -406,9 +536,10 @@ def _build_ksplit_kernel(m: int, bits: int, group_size: int, dtype, *, k_parts:
dtype_tag = {mx.bfloat16: "bf16", mx.float16: "fp16"}.get(dtype, "unk")
kernel = mx.fast.metal_kernel(
- name=f"omlx_vk_ks_m{m}_q{bits}_kp{k_parts}_gs{group_size}_{dtype_tag}",
+ name=f"omlx_vk_ks_m{m}_{mode}{bits}_kp{k_parts}_gs{group_size}_{dtype_tag}",
input_names=["x", "w_q", "scales", "biases", "K_size", "N_size"],
output_names=["y"],
+ header=_FP_HEADER if mode != "affine" else "",
source=source,
)
_KERNEL_CACHE[key] = kernel
@@ -1007,7 +1138,16 @@ def _pad_rows(mx, x2, m: int):
return x2, M
-def vk_qmm(x2, w_q, scales, biases, *, bits: int, group_size: int):
+def vk_qmm(
+ x2,
+ w_q,
+ scales,
+ biases,
+ *,
+ bits: int,
+ group_size: int,
+ mode: str = "affine",
+):
"""Verify-shape qmm: (M, K) x (N, K)^T -> (M, N), M in 2..6.
Rows are padded up to the kernel's M template. split-K for regular
@@ -1022,7 +1162,9 @@ def vk_qmm(x2, w_q, scales, biases, *, bits: int, group_size: int):
if N >= 100000 and N % (4 * _MSG_NSG) == 0:
xm, M0 = _pad_rows(mx, x2, m)
- kernel = _build_msg_kernel(m, bits, group_size, x2.dtype, _MSG_NSG)
+ kernel = _build_msg_kernel(
+ m, bits, group_size, mode, x2.dtype, _MSG_NSG
+ )
cols = 4 * _MSG_NSG
(y,) = kernel(
inputs=[xm, w_q, scales, biases, K, N],
@@ -1038,7 +1180,9 @@ def vk_qmm(x2, w_q, scales, biases, *, bits: int, group_size: int):
m = max(2, min(6, M))
xm, M0 = _pad_rows(mx, x2, m)
k_parts = 2 if N >= 4096 else 4
- kernel = _build_ksplit_kernel(m, bits, group_size, x2.dtype, k_parts=k_parts)
+ kernel = _build_ksplit_kernel(
+ m, bits, group_size, mode, x2.dtype, k_parts=k_parts
+ )
(y,) = kernel(
inputs=[xm, w_q, scales, biases, K, N],
template=[("T", x2.dtype)],
@@ -1050,15 +1194,31 @@ def vk_qmm(x2, w_q, scales, biases, *, bits: int, group_size: int):
return y[:M0, :] if M0 < m else y
-def vk_eligible(M: int, K: int, N: int, bits: int, group_size: int, dtype) -> bool:
+def vk_eligible(
+ M: int,
+ K: int,
+ N: int,
+ bits: int,
+ group_size: int,
+ dtype,
+ mode: str = "affine",
+) -> bool:
import mlx.core as mx
# M >= 3: at M=2 (depth-1 verify) the dispatch overhead eats the GPU win
# AND skipping it keeps depth-1 greedy output bit-identical to the
# unrouted path. Depth >= 2 verifies at M >= 3 where the kernels pay.
- return (
- int(bits) in (4, 8)
+ quantization_supported = (
+ mode == "affine"
+ and int(bits) in (4, 8)
and int(group_size) in (32, 64, 128)
+ ) or (
+ mode in ("mxfp4", "mxfp8")
+ and int(bits) == (4 if mode == "mxfp4" else 8)
+ and int(group_size) == 32
+ )
+ return (
+ quantization_supported
and dtype in (mx.bfloat16, mx.float16)
and 3 <= int(M) <= 6
and int(K) % 64 == 0
@@ -1477,6 +1637,8 @@ def _patch_verify_layer_flush() -> None:
import mlx.core as mx
def _model(self, model, *args, **kwargs):
+ if not _is_armed():
+ return original_model(self, model, *args, **kwargs)
layers = model.layers
_ROUTE_ARMED.next_norm = {
id(layer): nxt.input_layernorm for layer, nxt in zip(layers, layers[1:])
@@ -1572,21 +1734,24 @@ def skinny_eligible(M: int, K: int, N: int, bits: int, group_size: int, dtype) -
return int(M) > _NAX_MMA_MAX_ROWS or mma_eligible(M, K, N, bits, group_size, dtype)
-def _verify_route(rows: int, K: int, N: int, bits: int, group_size: int, dtype):
+def _verify_route(
+ rows: int, K: int, N: int, bits: int, group_size: int, dtype, mode: str = "affine"
+):
"""Kernel an armed verify projection runs ("m1", "m1_mma", "sg8", "skinny",
"mma" or "vk"), or None for the stock qmm."""
- m1 = _m1_route(rows, K, N, bits, group_size, dtype)
- if m1:
- return m1
- if sg8_eligible(rows, K, N, bits, group_size, dtype):
+ if mode == "affine":
+ m1 = _m1_route(rows, K, N, bits, group_size, dtype)
+ if m1:
+ return m1
+ if mode == "affine" and sg8_eligible(rows, K, N, bits, group_size, dtype):
if rows < _SG8_SINGLE_MIN_ROWS_NAX and is_nax_available():
return None
return "sg8"
- if skinny_eligible(rows, K, N, bits, group_size, dtype):
+ if mode == "affine" and skinny_eligible(rows, K, N, bits, group_size, dtype):
return "skinny"
- if mma_eligible(rows, K, N, bits, group_size, dtype):
+ if mode == "affine" and mma_eligible(rows, K, N, bits, group_size, dtype):
return "mma"
- if rows <= 6 and vk_eligible(rows, K, N, bits, group_size, dtype):
+ if rows <= 6 and vk_eligible(rows, K, N, bits, group_size, dtype, mode):
return "vk"
return None
@@ -1614,7 +1779,15 @@ def run_route(layer, x2, route: str, *, sums=None):
return nax_skinny_qmm.skinny_qmm(*args, K, N, bits=layer.bits)
if route == "mma":
return vk_qmm_mma(*args, group_size=layer.group_size, bits=layer.bits)
- return vk_qmm(*args, bits=layer.bits, group_size=layer.group_size)
+ return vk_qmm(
+ x2,
+ layer.weight,
+ layer.scales,
+ layer.biases if layer.biases is not None else layer.scales,
+ bits=layer.bits,
+ group_size=layer.group_size,
+ mode=getattr(layer, "mode", "affine"),
+ )
def takes_verify_route(layer, rows: int, dtype) -> bool:
@@ -1624,11 +1797,22 @@ def takes_verify_route(layer, rows: int, dtype) -> bool:
return False
if is_row_exact_armed():
return True
- if not _is_armed() or getattr(layer, "mode", "affine") != "affine":
+ if not _is_armed():
return False
K = layer.weight.shape[-1] * 32 // layer.bits
N = layer.scales.shape[0]
- return _verify_route(rows, K, N, layer.bits, layer.group_size, dtype) is not None
+ return (
+ _verify_route(
+ rows,
+ K,
+ N,
+ layer.bits,
+ layer.group_size,
+ dtype,
+ getattr(layer, "mode", "affine"),
+ )
+ is not None
+ )
def apply_verify_qmm_patch() -> bool:
@@ -1636,8 +1820,8 @@ def apply_verify_qmm_patch() -> bool:
Strictly gated: only while the MTP verify flag is armed
(``set_verify_qmm_armed``), only rank-3 inputs whose rows (batch x block)
- fall in 3..6 (split-K) or 7..24 (mma), only affine layouts the kernels
- support. Everything else takes the stock path.
+ fall in 3..6 (split-K) or 7..24 (mma), only layouts the kernels support.
+ Everything else takes the stock path.
"""
global _QL_PATCHED
if _QL_PATCHED:
@@ -1660,14 +1844,16 @@ def patched_call(self, x):
if (
not _is_armed()
or x.ndim != 3
- or getattr(self, "mode", "affine") != "affine"
or (x.shape[0] == 1 and x.shape[1] < 2)
):
return orig_call(self, x)
batch, length, K = x.shape
rows = batch * length
N = self.scales.shape[0]
- route = _verify_route(rows, K, N, self.bits, self.group_size, x.dtype)
+ mode = getattr(self, "mode", "affine")
+ route = _verify_route(
+ rows, K, N, self.bits, self.group_size, x.dtype, mode
+ )
if route is None:
return orig_call(self, x)
try:
@@ -1689,7 +1875,7 @@ def patched_call(self, x):
_patch_verify_layer_flush()
_QL_PATCHED = True
logger.info(
- "MTP verify qmm patch applied (rows 2..6 split-K, 7..8 sg8, 9..24 mma%s%s)",
+ "MTP verify qmm patch applied (affine/MXFP split-K, affine sg8/mma%s%s)",
"; NAX: skinny 9..48" if is_nax_available() else "",
"; M1: qmv 2..4, mma 5..16" if m1_verify_qmv.enabled() else "",
)
diff --git a/scripts/bench.py b/scripts/bench.py
new file mode 100755
index 0000000000..943e9b466b
--- /dev/null
+++ b/scripts/bench.py
@@ -0,0 +1,517 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+"""Standalone benchmark script using omlx's native benchmark machinery.
+
+Runs the same single-request and continuous-batching tests as the UI benchmark,
+but directly in Python — no server or HTTP needed. Pass multiple model paths
+to run each in sequence and print a side-by-side comparison table.
+
+Usage
+-----
+ # Single model
+ ~/.venv/bin/python scripts/bench.py ~/models/Bonsai-27B
+
+ # Compare two variants
+ ~/.venv/bin/python scripts/bench.py ~/models/bonsai-27b ~/.cache/huggingface/hub/models--prism-ml--Ternary-Bonsai-27B-mlx-2bit/snapshots/70f75f3ad081ab840a42f3304c02c27e7f89bfb7
+
+ # With batch tests
+ ~/.venv/bin/python scripts/bench.py model-a model-b --pp 1024 4096 --batch 2 4
+
+Metrics (single-request)
+--------------------------
+ pp prompt tokens
+ ttft time-to-first-token (ms)
+ tpot time-per-output-token (ms)
+ gen_tps decode tokens/sec
+ pp_tps prefill tokens/sec
+ mem peak GPU memory
+
+Metrics (batch)
+----------------
+ bs batch size
+ pp_tps aggregate prefill tokens/sec
+ tg_tps aggregate decode tokens/sec
+ ttft average time-to-first-token (ms)
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import sys
+import time
+from collections import defaultdict
+from collections.abc import Sequence
+from dataclasses import dataclass
+from enum import StrEnum
+from pathlib import Path
+from typing import Literal
+
+from omlx.model_settings import ModelSettings
+
+
+class NativeMTPMode(StrEnum):
+ OFF = "off"
+ ON = "on"
+ BOTH = "both"
+
+
+PLEStorage = Literal["resident", "ssd"]
+
+
+class Qwen4PLEMode(StrEnum):
+ RESIDENT = "resident"
+ SSD = "ssd"
+ BOTH = "both"
+
+
+@dataclass(frozen=True)
+class BenchmarkVariant:
+ native_mtp_enabled: bool
+ ple_storage: PLEStorage | None
+ model_settings: ModelSettings
+
+
+@dataclass(frozen=True)
+class BenchmarkCase:
+ model_path: str
+ variant: BenchmarkVariant
+
+
+@dataclass
+class BenchmarkResult:
+ label: str
+ single_results: list[dict[str, object]]
+ batch_results: list[dict[str, object]]
+
+
+def build_parser() -> argparse.ArgumentParser:
+ p = argparse.ArgumentParser(
+ description="omlx native benchmark",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ epilog=__doc__,
+ )
+ p.add_argument("models", nargs="+", help="Path(s) to model directory")
+ p.add_argument(
+ "--pp",
+ metavar="N",
+ type=int,
+ nargs="+",
+ default=[1024, 4096, 8192],
+ help="Prompt token lengths to test (default: 1024 4096 8192)",
+ )
+ p.add_argument(
+ "--gen",
+ metavar="N",
+ type=int,
+ default=128,
+ help="Tokens to generate per request (default: 128)",
+ )
+ p.add_argument(
+ "--batch",
+ metavar="N",
+ type=int,
+ nargs="+",
+ default=[],
+ help="Batch sizes for continuous-batching tests (default: none)",
+ )
+ p.add_argument(
+ "--warmup",
+ metavar="N",
+ type=int,
+ default=1,
+ help="Warmup runs before timing (default: 1)",
+ )
+ p.add_argument(
+ "--native-mtp",
+ type=NativeMTPMode,
+ choices=tuple(NativeMTPMode),
+ default=NativeMTPMode.OFF,
+ help="Native MTP variant(s): off (default), on, or both.",
+ )
+ p.add_argument(
+ "--qwen4-ple",
+ type=Qwen4PLEMode,
+ choices=tuple(Qwen4PLEMode),
+ default=None,
+ help="Qwen4 PLE storage variant(s): resident, ssd, or both.",
+ )
+ return p
+
+
+def _parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
+ return build_parser().parse_args(argv)
+
+
+# ── formatting helpers ────────────────────────────────────────────────────────
+
+def _fmt_mem(peak_bytes: int) -> str:
+ if peak_bytes <= 0:
+ return "—"
+ return f"{peak_bytes / 1e9:.1f}G"
+
+
+def _fmt_metric(value: float | None, decimals: int = 1, width: int = 0) -> str:
+ """Format a metric, rendering unmeasured (None) values as an em dash.
+
+ Timing-derived metrics come back as None when the run could not observe
+ the phase they describe, e.g. an endpoint that never streamed a content
+ delta (omlx/admin/benchmark.py::_compute_single_metrics).
+ """
+ if value is None:
+ return f"{'—':>{width}}"
+ return f"{value:>{width}.{decimals}f}"
+
+
+def _short_name(path: str) -> str:
+ """Return a short display label for a model path."""
+ p = Path(path)
+ name = p.name
+ # HF snapshot paths: …/models--org--name/snapshots/ → org/name
+ parts = p.parts
+ for i, part in enumerate(parts):
+ if part == "snapshots" and i >= 1:
+ repo = parts[i - 1] # models--org--name
+ label = repo.removeprefix("models--").replace("--", "/")
+ return label
+ return name
+
+
+def _benchmark_variants(
+ native_mtp_mode: NativeMTPMode,
+ qwen4_ple_mode: Qwen4PLEMode | None,
+) -> tuple[BenchmarkVariant, ...]:
+ native_mtp_values = (
+ (False, True)
+ if native_mtp_mode is NativeMTPMode.BOTH
+ else (native_mtp_mode is NativeMTPMode.ON,)
+ )
+ ple_values: tuple[PLEStorage | None, ...]
+ if qwen4_ple_mode is Qwen4PLEMode.BOTH:
+ ple_values = ("resident", "ssd")
+ elif qwen4_ple_mode is None:
+ ple_values = (None,)
+ elif qwen4_ple_mode is Qwen4PLEMode.RESIDENT:
+ ple_values = ("resident",)
+ else:
+ ple_values = ("ssd",)
+
+ return tuple(
+ BenchmarkVariant(
+ native_mtp_enabled=native_mtp_enabled,
+ ple_storage=ple_storage,
+ model_settings=ModelSettings(
+ mtp_enabled=native_mtp_enabled,
+ qwen4_ple_ssd_offload=ple_storage == "ssd",
+ ),
+ )
+ for native_mtp_enabled in native_mtp_values
+ for ple_storage in ple_values
+ )
+
+
+def _expand_cases(
+ model_paths: Sequence[str],
+ native_mtp_mode: NativeMTPMode,
+ qwen4_ple_mode: Qwen4PLEMode | None = None,
+) -> list[BenchmarkCase]:
+ return [
+ BenchmarkCase(model_path, variant)
+ for model_path in model_paths
+ for variant in _benchmark_variants(native_mtp_mode, qwen4_ple_mode)
+ ]
+
+
+def _allocate_labels(
+ cases: Sequence[BenchmarkCase], *, include_variant: bool
+) -> list[str]:
+ bases = []
+ for case in cases:
+ parts = []
+ if include_variant:
+ if case.variant.ple_storage is None:
+ parts.append(
+ "native-mtp"
+ if case.variant.native_mtp_enabled
+ else "baseline"
+ )
+ else:
+ native_mtp = "on" if case.variant.native_mtp_enabled else "off"
+ parts.append(f"native-mtp={native_mtp}")
+ if case.variant.ple_storage is not None:
+ parts.append(f"ple={case.variant.ple_storage}")
+ parts.append(_short_name(case.model_path))
+ bases.append(" ".join(parts))
+
+ totals: dict[str, int] = defaultdict(int)
+ for base in bases:
+ totals[base] += 1
+
+ ordinals: dict[str, int] = defaultdict(int)
+ labels: list[str] = []
+ used: set[str] = set()
+ for base in bases:
+ if totals[base] == 1:
+ label = base
+ else:
+ ordinals[base] += 1
+ label = f"{base} #{ordinals[base]}"
+
+ collision_ordinal = 1
+ candidate = label
+ while candidate in used:
+ candidate = f"{label} #{collision_ordinal}"
+ collision_ordinal += 1
+ labels.append(candidate)
+ used.add(candidate)
+ return labels
+
+
+def _truncate_label(label: str, width: int) -> str:
+ return label[:width] if len(label) > width else label
+
+
+def _label_with_ordinal(label: str, width: int, ordinal: int) -> str:
+ suffix = f"#{ordinal}"
+ prefix_width = width - len(suffix)
+ if len(label) <= prefix_width:
+ return f"{label}{suffix}"
+ return f"{label[:prefix_width - 1]}…{suffix}"
+
+
+def _display_labels(labels: Sequence[str], width: int) -> list[str]:
+ if width < 3:
+ raise ValueError("display label width must leave room for an ordinal")
+
+ displays = [_truncate_label(label, width) for label in labels]
+ groups: dict[str, list[int]] = defaultdict(list)
+ for index, display in enumerate(displays):
+ groups[display].append(index)
+
+ for indexes in groups.values():
+ if len(indexes) > 1:
+ for ordinal, index in enumerate(indexes, start=1):
+ displays[index] = _label_with_ordinal(labels[index], width, ordinal)
+
+ while True:
+ collisions: dict[str, list[int]] = defaultdict(list)
+ for index, display in enumerate(displays):
+ collisions[display].append(index)
+ duplicate_groups = [
+ indexes for indexes in collisions.values() if len(indexes) > 1
+ ]
+ if not duplicate_groups:
+ return displays
+ for indexes in duplicate_groups:
+ for index in indexes:
+ displays[index] = _label_with_ordinal(labels[index], width, index + 1)
+
+
+# ── per-model benchmark runner ────────────────────────────────────────────────
+
+async def _bench_model(
+ case: BenchmarkCase,
+ pp_lengths: list[int],
+ gen_tokens: int,
+ batch_sizes: list[int],
+ warmup: int,
+) -> tuple[list[dict], list[dict]]:
+ """Load one model, run all tests, unload. Returns (single_results, batch_results)."""
+ from omlx.admin.benchmark import (
+ _generate_prompt,
+ _run_batch_test,
+ _run_single_test,
+ )
+ from omlx.engine.vlm import VLMBatchedEngine
+
+ print(f"\nLoading {case.model_path} …")
+ t0 = time.perf_counter()
+ engine = VLMBatchedEngine(
+ model_name=case.model_path,
+ model_settings=case.variant.model_settings,
+ )
+ await engine.start()
+ try:
+ print(f"Loaded in {time.perf_counter() - t0:.1f}s")
+
+ tokenizer = engine.tokenizer
+ prompts: dict[int, str] = {
+ pp: _generate_prompt(tokenizer, pp) for pp in sorted(set(pp_lengths))
+ }
+
+ if warmup > 0 and pp_lengths:
+ warmup_pp = min(pp_lengths)
+ print(f"Warming up ({warmup}× pp={warmup_pp}) …")
+ for _ in range(warmup):
+ await _run_single_test(engine, prompts[warmup_pp], gen_tokens, warmup_pp)
+
+ single_results: list[dict[str, object]] = []
+ for pp in sorted(pp_lengths):
+ print(f" pp={pp} gen={gen_tokens} …", end="", flush=True)
+ r = await _run_single_test(engine, prompts[pp], gen_tokens, pp)
+ single_results.append(r)
+ print(
+ f" ttft={_fmt_metric(r['ttft_ms'], 0)}ms "
+ f"{_fmt_metric(r['gen_tps'])} t/s"
+ )
+
+ batch_results: list[dict[str, object]] = []
+ batch_pp = sorted(pp_lengths)[0] if pp_lengths else 1024
+ for bs in sorted(batch_sizes):
+ batch_prompts = [_generate_prompt(tokenizer, batch_pp) for _ in range(bs)]
+ print(f" batch={bs} pp={batch_pp} gen={gen_tokens} …", end="", flush=True)
+ r = await _run_batch_test(engine, batch_prompts, batch_pp, gen_tokens, bs)
+ batch_results.append(r)
+ print(
+ f" pp={_fmt_metric(r['pp_tps'], 0)}/s "
+ f"tg={_fmt_metric(r['tg_tps'], 0)}/s"
+ )
+ return single_results, batch_results
+ finally:
+ await engine.stop()
+
+
+# ── table printers ────────────────────────────────────────────────────────────
+
+def _print_single_comparison(
+ results: Sequence[BenchmarkResult],
+ pp_lengths: list[int],
+) -> None:
+ """Print a side-by-side comparison table for single-request results."""
+ # Column widths: fixed per metric, repeated per model
+ col = 9 # width of one model's metric block
+ n = len(results)
+
+ # Header: model names spanning their columns
+ metrics = ["ttft", "gen_tps", "pp_tps", "mem"]
+ block_w = col * len(metrics) + len(metrics) - 1 # e.g. 4*9+3 = 39
+ labels = _display_labels([result.label for result in results], block_w)
+
+ print()
+ print(" Single-request")
+ # Model name header row
+ name_row = f" {'pp':>6} "
+ for label in labels:
+ name_row += f"{label:^{block_w}} "
+ print(name_row.rstrip())
+
+ # Sub-header: metric names per model
+ sub_row = f" {'':>6} "
+ for _ in labels:
+ sub_row += f"{'ttft':>{col}} {'gen_tps':>{col}} {'pp_tps':>{col}} {'mem':>{col}} "
+ print(sub_row.rstrip())
+
+ sep = "─" * (8 + (block_w + 2) * n)
+ print(" " + sep)
+
+ # Data rows
+ for pp in sorted(pp_lengths):
+ row = f" {pp:>6} "
+ for result in results:
+ model_results = result.single_results
+ r = next((x for x in model_results if x["prompt_tokens"] == pp), None)
+ if r is None:
+ row += f"{'—':>{col}} {'—':>{col}} {'—':>{col}} {'—':>{col}} "
+ else:
+ row += (
+ f"{_fmt_metric(r['ttft_ms'], 0, col - 2)}ms "
+ f"{_fmt_metric(r['gen_tps'], 1, col - 2)}/s "
+ f"{_fmt_metric(r['processing_tps'], 0, col - 2)}/s "
+ f"{_fmt_mem(r['peak_memory_bytes']):>{col}} "
+ )
+ print(row.rstrip())
+
+ print(" " + sep)
+
+
+def _print_batch_comparison(
+ results: Sequence[BenchmarkResult],
+ batch_sizes: list[int],
+) -> None:
+ """Print a side-by-side comparison table for batch results."""
+ col = 9
+ n = len(results)
+ metrics = ["pp_tps", "tg_tps", "ttft"]
+ block_w = col * len(metrics) + len(metrics) - 1
+ labels = _display_labels([result.label for result in results], block_w)
+
+ print()
+ print(" Continuous-batching")
+ name_row = f" {'bs':>4} "
+ for label in labels:
+ name_row += f"{label:^{block_w}} "
+ print(name_row.rstrip())
+
+ sub_row = f" {'':>4} "
+ for _ in labels:
+ sub_row += f"{'pp_tps':>{col}} {'tg_tps':>{col}} {'ttft':>{col}} "
+ print(sub_row.rstrip())
+
+ sep = "─" * (6 + (block_w + 2) * n)
+ print(" " + sep)
+
+ for bs in sorted(batch_sizes):
+ row = f" {bs:>4} "
+ for result in results:
+ model_results = result.batch_results
+ r = next((x for x in model_results if x["batch_size"] == bs), None)
+ if r is None:
+ row += f"{'—':>{col}} {'—':>{col}} {'—':>{col}} "
+ else:
+ row += (
+ f"{_fmt_metric(r['pp_tps'], 0, col - 2)}/s "
+ f"{_fmt_metric(r['tg_tps'], 0, col - 2)}/s "
+ f"{_fmt_metric(r['avg_ttft_ms'], 0, col - 2)}ms "
+ )
+ print(row.rstrip())
+
+ print(" " + sep)
+
+
+# ── main ──────────────────────────────────────────────────────────────────────
+
+async def _run(args: argparse.Namespace) -> None:
+ model_paths = [str(Path(m).expanduser().resolve()) for m in args.models]
+ pp_lengths = sorted(set(args.pp))
+ cases = _expand_cases(model_paths, args.native_mtp, args.qwen4_ple)
+ labels = _allocate_labels(
+ cases,
+ include_variant=args.native_mtp is not NativeMTPMode.OFF,
+ )
+ results: list[BenchmarkResult] = []
+
+ for case, label in zip(cases, labels, strict=True):
+ single, batch = await _bench_model(
+ case, pp_lengths, args.gen, sorted(args.batch), args.warmup
+ )
+ results.append(BenchmarkResult(label, single, batch))
+
+ # ── summary ───────────────────────────────────────────────────────────────
+ print(f"\n{'═' * 60}")
+ print(f" gen_tokens={args.gen}")
+
+ if len(results) == 1:
+ # Single model: original compact table
+ _print_single_comparison(results, pp_lengths)
+ if results[0].batch_results:
+ _print_batch_comparison(results, sorted(args.batch))
+ else:
+ # Multiple models: side-by-side
+ _print_single_comparison(results, pp_lengths)
+ if any(result.batch_results for result in results):
+ _print_batch_comparison(results, sorted(args.batch))
+
+ print()
+
+
+def main() -> None:
+ args = _parse_args()
+ try:
+ asyncio.run(_run(args))
+ except KeyboardInterrupt:
+ print("\nInterrupted.", file=sys.stderr)
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/bench_qwen35_verify_qmm.py b/tests/bench_qwen35_verify_qmm.py
new file mode 100644
index 0000000000..d70328aee4
--- /dev/null
+++ b/tests/bench_qwen35_verify_qmm.py
@@ -0,0 +1,80 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+
+import argparse
+import time
+from functools import partial
+
+import mlx.core as mx
+import mlx.nn as nn
+
+from omlx.patches.qwen35_verify_qmm import vk_qmm
+
+
+def _time_ms(fn, warmup, iterations):
+ for _ in range(warmup):
+ mx.eval(fn())
+ started = time.perf_counter()
+ for _ in range(iterations):
+ mx.eval(fn())
+ return (time.perf_counter() - started) * 1000.0 / iterations
+
+
+def _stock(linear, inputs):
+ return linear(inputs)
+
+
+def _custom(linear, inputs, bits, group_size, mode):
+ return vk_qmm(
+ inputs,
+ linear.weight,
+ linear.scales,
+ linear.biases if linear.biases is not None else linear.scales,
+ bits=bits,
+ group_size=group_size,
+ mode=mode,
+ )
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--rows", type=int, default=4)
+ parser.add_argument("--input-dims", type=int, default=2048)
+ parser.add_argument("--output-dims", type=int, default=16384)
+ parser.add_argument("--iterations", type=int, default=20)
+ parser.add_argument("--warmup", type=int, default=3)
+ args = parser.parse_args()
+
+ inputs = mx.random.normal(
+ (args.rows, args.input_dims), dtype=mx.bfloat16
+ )
+ for mode, bits, group_size in (
+ ("affine", 4, 64),
+ ("mxfp4", 4, 32),
+ ("mxfp8", 8, 32),
+ ):
+ linear = nn.QuantizedLinear.from_linear(
+ nn.Linear(args.input_dims, args.output_dims, bias=False),
+ group_size=group_size,
+ bits=bits,
+ mode=mode,
+ )
+ fallback = partial(_stock, linear, inputs)
+ custom = partial(
+ _custom,
+ linear,
+ inputs,
+ bits,
+ group_size,
+ mode,
+ )
+ fallback_ms = _time_ms(fallback, args.warmup, args.iterations)
+ custom_ms = _time_ms(custom, args.warmup, args.iterations)
+ print(
+ f"{mode}: stock={fallback_ms:.3f}ms custom={custom_ms:.3f}ms "
+ f"speedup={fallback_ms / custom_ms:.2f}x"
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/test_bench_qwen_decode.py b/tests/test_bench_qwen_decode.py
new file mode 100644
index 0000000000..f9ad4e7d04
--- /dev/null
+++ b/tests/test_bench_qwen_decode.py
@@ -0,0 +1,312 @@
+# SPDX-License-Identifier: Apache-2.0
+
+import asyncio
+import importlib.util
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+
+@pytest.fixture
+def benchmark():
+ path = Path(__file__).parents[1] / "benchmarks" / "bench_qwen_decode.py"
+ spec = importlib.util.spec_from_file_location("bench_qwen_decode", path)
+ assert spec and spec.loader
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = module
+ try:
+ spec.loader.exec_module(module)
+ yield module
+ finally:
+ sys.modules.pop(spec.name, None)
+
+
+def test_prompt_is_exact_and_deterministic(benchmark, monkeypatch):
+ monkeypatch.setattr(
+ "omlx.admin.benchmark._load_bench_corpus",
+ lambda _profile: "def solve(value):\n return value + 1\n",
+ )
+
+ class Tokenizer:
+ def encode(self, text):
+ return [ord(char) for char in text]
+
+ first = benchmark._build_prompt(Tokenizer(), 512, "Implement this module.\n")
+ second = benchmark._build_prompt(Tokenizer(), 512, "Implement this module.\n")
+
+ assert isinstance(first, tuple)
+ assert len(first) == 512
+ assert first == second
+ assert benchmark._token_digest(first) == benchmark._token_digest(second)
+
+
+@pytest.mark.parametrize(
+ "model_type",
+ ["qwen3_5", "qwen3_5_moe", "qwen3_6", "qwen3_8", "qwen4_exp"],
+)
+def test_model_fingerprint_accepts_supported_qwen_types(
+ benchmark, tmp_path, model_type
+):
+ (tmp_path / "config.json").write_text(
+ f'{{"model_type": "{model_type}", '
+ f'"text_config": {{"model_type": "{model_type}_text"}}}}'
+ )
+ (tmp_path / "model.safetensors").write_bytes(b"weights")
+
+ fingerprint = benchmark._model_fingerprint(str(tmp_path))
+
+ assert fingerprint["resolved_path"] == str(tmp_path.resolve())
+ assert fingerprint["model_type"] == model_type
+ assert fingerprint["config_sha256"]
+ assert fingerprint["sha256"]
+
+
+def test_model_fingerprint_detects_metadata_drift(benchmark, tmp_path):
+ (tmp_path / "config.json").write_text('{"model_type": "qwen3_5"}')
+ weights = tmp_path / "model.safetensors"
+ weights.write_bytes(b"weights")
+ before = benchmark._model_fingerprint(str(tmp_path))
+
+ weights.write_bytes(b"changed weights")
+ after = benchmark._model_fingerprint(str(tmp_path))
+
+ with pytest.raises(benchmark.BenchmarkError, match="changed"):
+ benchmark._assert_model_unchanged(before, after)
+
+
+def test_model_fingerprint_rejects_unsupported_type_before_loading(benchmark, tmp_path):
+ (tmp_path / "config.json").write_text('{"model_type": "llama"}')
+ (tmp_path / "model.safetensors").write_bytes(b"weights")
+
+ with pytest.raises(benchmark.BenchmarkError, match="unsupported model_type"):
+ benchmark._model_fingerprint(str(tmp_path))
+
+
+def test_candidate_environment_records_flags_not_api_keys(benchmark, monkeypatch):
+ for name in benchmark._candidate_environment():
+ monkeypatch.delenv(name)
+ monkeypatch.setenv("OMLX_QWEN35_GDN_DECODE_FUSION", "0")
+ monkeypatch.setenv("OMLX_API_KEY", "secret")
+
+ environment = benchmark._candidate_environment()
+
+ assert environment == {"OMLX_QWEN35_GDN_DECODE_FUSION": "0"}
+
+
+def test_runtime_info_preserves_device_telemetry_error(benchmark):
+ mlx = SimpleNamespace(
+ __version__="test",
+ device_info=lambda: (_ for _ in ()).throw(RuntimeError("device failed")),
+ )
+
+ with pytest.raises(RuntimeError, match="device failed"):
+ benchmark._runtime_info(mlx)
+
+
+class _FakeMLX:
+ def reset_peak_memory(self):
+ pass
+
+ def get_peak_memory(self):
+ return 1234
+
+
+class _FakeEngine:
+ def __init__(self, outputs):
+ self.outputs = outputs
+
+ async def stream_generate(self, **kwargs):
+ assert kwargs["prompt"] == [10, 11]
+ assert kwargs["skip_cache_store"] is True
+ for output in self.outputs:
+ yield output
+
+
+def _output(**overrides):
+ values = {
+ "tokens": [20, 21, 22],
+ "prompt_tokens": 2,
+ "completion_tokens": 3,
+ "cached_tokens": 0,
+ "finish_reason": "length",
+ "finished": True,
+ "generated_at": 10.0,
+ "generated_until": 10.5,
+ }
+ values.update(overrides)
+ return SimpleNamespace(**values)
+
+
+def test_trial_uses_terminal_ids_and_producer_timestamps(benchmark):
+ trial = asyncio.run(
+ benchmark._run_trial(
+ _FakeEngine([_output()]),
+ _FakeMLX(),
+ (10, 11),
+ 3,
+ index=0,
+ warmup=False,
+ )
+ )
+
+ assert trial.output_token_ids == (20, 21, 22)
+ assert trial.producer_duration_s == 0.5
+ assert trial.generation_tps == 4.0
+ assert trial.errors == ()
+
+
+@pytest.mark.parametrize("method", ["reset_peak_memory", "get_peak_memory"])
+def test_trial_preserves_telemetry_errors(benchmark, method):
+ class BrokenMLX(_FakeMLX):
+ def reset_peak_memory(self):
+ if method == "reset_peak_memory":
+ raise RuntimeError("reset failed")
+
+ def get_peak_memory(self):
+ if method == "get_peak_memory":
+ raise RuntimeError("read failed")
+ return super().get_peak_memory()
+
+ with pytest.raises(RuntimeError, match="failed"):
+ asyncio.run(
+ benchmark._run_trial(
+ _FakeEngine([_output()]),
+ BrokenMLX(),
+ (10, 11),
+ 3,
+ index=0,
+ warmup=False,
+ )
+ )
+
+
+def test_early_eos_trial_is_retained_before_failure(benchmark):
+ trial = asyncio.run(
+ benchmark._run_trial(
+ _FakeEngine([_output(tokens=[20, 21], completion_tokens=2)]),
+ _FakeMLX(),
+ (10, 11),
+ 3,
+ index=0,
+ warmup=False,
+ )
+ )
+
+ assert trial.output_token_ids == (20, 21)
+ assert "ended early" in trial.errors[0]
+ with pytest.raises(benchmark.BenchmarkError, match="ended early"):
+ benchmark._validate_trial(trial, 2, None)
+
+
+def test_repeated_output_mismatch_fails(benchmark):
+ fields = {
+ "warmup": False,
+ "prompt_tokens": 2,
+ "completion_tokens": 3,
+ "cached_tokens": 0,
+ "finish_reason": "length",
+ "producer_first_s": 1,
+ "producer_last_s": 2,
+ "producer_duration_s": 1,
+ "consumer_duration_s": 2,
+ "generation_tps": 2,
+ "end_to_end_tps": 1.5,
+ "peak_memory_bytes": 10,
+ "errors": (),
+ }
+ first = benchmark.Trial(
+ index=0,
+ output_token_ids=(1, 2, 3),
+ output_sha256="a",
+ **fields,
+ )
+ second = benchmark.Trial(
+ index=1,
+ output_token_ids=(1, 2, 4),
+ output_sha256="b",
+ **fields,
+ )
+
+ expected = benchmark._validate_trial(first, 2, None)
+ with pytest.raises(benchmark.BenchmarkError, match="differs"):
+ benchmark._validate_trial(second, 2, expected)
+
+
+def test_model_settings_disable_other_cache_and_speculative_paths(benchmark):
+ settings = benchmark._model_settings(True)
+
+ assert settings.mtp_enabled is True
+ assert settings.vlm_mtp_enabled is False
+ assert settings.dflash_enabled is False
+ assert settings.specprefill_enabled is False
+ assert settings.turboquant_kv_enabled is False
+
+
+def test_vlm_stream_projects_terminal_output_token_ids():
+ from omlx.engine.vlm import VLMBatchedEngine
+
+ engine = VLMBatchedEngine("model")
+ engine._loaded = True
+ engine._vlm_model = SimpleNamespace(config=SimpleNamespace(model_type="qwen3_8"))
+ core = SimpleNamespace()
+
+ async def add_request(**_kwargs):
+ return "request"
+
+ async def stream_outputs(_request_id):
+ yield SimpleNamespace(
+ output_text="a",
+ new_text="a",
+ output_token_ids=[],
+ prompt_tokens=2,
+ completion_tokens=1,
+ finished=False,
+ finish_reason=None,
+ tool_calls=None,
+ logprobs=None,
+ cached_tokens=0,
+ )
+ yield SimpleNamespace(
+ output_text="abc",
+ new_text="bc",
+ output_token_ids=[20, 21, 22],
+ prompt_tokens=2,
+ completion_tokens=3,
+ finished=True,
+ finish_reason="length",
+ tool_calls=None,
+ logprobs=None,
+ cached_tokens=0,
+ )
+
+ async def abort_request(_request_id):
+ raise AssertionError("completed request must not be aborted")
+
+ core.add_request = add_request
+ core.stream_outputs = stream_outputs
+ core.abort_request = abort_request
+ engine._engine = core
+
+ async def collect():
+ return [output async for output in engine.stream_generate([10, 11])]
+
+ outputs = asyncio.run(collect())
+ assert outputs[0].tokens == []
+ assert outputs[-1].tokens == [20, 21, 22]
+
+
+def test_main_keeps_stdout_as_json(benchmark, monkeypatch, capsys):
+ async def fake_benchmark(_args):
+ print("loader noise")
+ return {"status": "error", "trials": [{"errors": ["early EOS"]}]}
+
+ monkeypatch.setattr(benchmark, "_benchmark", fake_benchmark)
+
+ exit_code = benchmark.main(["model", "--native-mtp", "off", "--label", "baseline"])
+
+ captured = capsys.readouterr()
+ assert exit_code == 1
+ assert captured.out == ('{"status":"error","trials":[{"errors":["early EOS"]}]}\n')
+ assert captured.err == "loader noise\n"
diff --git a/tests/test_bench_qwen_verify_prework.py b/tests/test_bench_qwen_verify_prework.py
new file mode 100644
index 0000000000..86ed9ac5c4
--- /dev/null
+++ b/tests/test_bench_qwen_verify_prework.py
@@ -0,0 +1,258 @@
+# SPDX-License-Identifier: Apache-2.0
+
+import asyncio
+import importlib.util
+import os
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+
+@pytest.fixture
+def benchmark():
+ path = Path(__file__).parents[1] / "benchmarks" / "bench_qwen_verify_prework.py"
+ spec = importlib.util.spec_from_file_location("bench_qwen_verify_prework", path)
+ assert spec and spec.loader
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = module
+ try:
+ spec.loader.exec_module(module)
+ yield module
+ finally:
+ sys.modules.pop(spec.name, None)
+
+
+def test_schedule_warms_each_arm_then_runs_abba(benchmark):
+ assert benchmark._schedule(2) == [
+ (True, False),
+ (True, True),
+ (False, False),
+ (False, True),
+ (False, True),
+ (False, False),
+ (False, False),
+ (False, True),
+ (False, True),
+ (False, False),
+ ]
+
+
+def test_default_prompt_preserves_literal_escapes(benchmark):
+ assert benchmark.PROMPT_TEXT == (
+ r"Complete this Python module. Continue with code only and do not stop "
+ r"until the implementation is complete.\n\n"
+ )
+ args = benchmark._parse_args(["model"])
+ assert args.prompt_text == benchmark.PROMPT_TEXT
+ assert args.pp == 512
+ assert args.gen == 128
+ assert args.pairs == 3
+ assert args.fixed_depth == 2
+
+
+@pytest.mark.parametrize("depth", [1, 2])
+def test_fixed_depth_accepts_only_supported_values(benchmark, depth):
+ assert (
+ benchmark._parse_args(["model", "--fixed-depth", str(depth)]).fixed_depth
+ == depth
+ )
+
+ with pytest.raises(SystemExit):
+ benchmark._parse_args(["model", "--fixed-depth", "3"])
+
+
+def test_engagement_rejection_keeps_metadata(benchmark):
+ record = {"treatment": True, "draft_calls": 1, "prework_calls": 0}
+
+ with pytest.raises(benchmark.bench.BenchmarkError, match="prework"):
+ benchmark._validate_engagement(record)
+
+ assert record["engagement_errors"] == ["prework treatment was not engaged"]
+
+
+def test_baseline_cannot_engage_candidate(benchmark):
+ record = {"treatment": False, "draft_calls": 1, "prework_calls": 1}
+ with pytest.raises(benchmark.bench.BenchmarkError, match="baseline"):
+ benchmark._validate_engagement(record)
+
+
+def test_output_drift_is_rejected(benchmark):
+ trial = SimpleNamespace(
+ index=0, errors=(), prompt_tokens=2, output_token_ids=(1, 2)
+ )
+ assert benchmark.bench._validate_trial(trial, 2, None) == (1, 2)
+ trial.output_token_ids = (1, 3)
+ with pytest.raises(benchmark.bench.BenchmarkError, match="differs"):
+ benchmark.bench._validate_trial(trial, 2, (1, 2))
+
+
+@pytest.mark.parametrize("fixed_depth", [1, 2])
+@pytest.mark.parametrize(
+ "failure", [None, "not ready", "trial failed", "fingerprint failed", "stop failed"]
+)
+def test_fixed_depth_and_monkeypatches_restore(
+ benchmark, monkeypatch, fixed_depth, failure
+):
+ monkeypatch.setenv(benchmark.PREWORK_ENV, "original")
+
+ class Controller:
+ def observe(self):
+ self.cur = 1
+
+ def should_exit(self):
+ return True
+
+ original_observe = Controller.observe
+ original_should_exit = Controller.should_exit
+
+ class Prework:
+ @staticmethod
+ def gdn_prework_fused():
+ return None
+
+ original_prework = Prework.gdn_prework_fused
+ head = SimpleNamespace(parameters=lambda: {"weight": SimpleNamespace()})
+ language_model = SimpleNamespace(
+ get_mtp_module=lambda: head,
+ _omlx_mtp_decode_enabled=True,
+ _omlx_mtp_depth=0,
+ )
+ if failure == "not ready":
+ language_model._omlx_mtp_decode_enabled = False
+ del language_model._omlx_mtp_depth
+
+ class Engine:
+ def __init__(self, **kwargs):
+ self.model_settings = kwargs["model_settings"]
+ self._adapter = SimpleNamespace(
+ _language_model=language_model,
+ mtp_forward=lambda: None,
+ )
+ self.tokenizer = object()
+
+ async def start(self):
+ pass
+
+ async def stop(self):
+ self.stopped = True
+ if failure == "stop failed":
+ raise RuntimeError(failure)
+
+ class MX:
+ random = SimpleNamespace(seed=lambda _seed: None)
+
+ monkeypatch.setattr(
+ benchmark.bench, "_model_fingerprint", lambda _model: {"sha256": "x"}
+ )
+ if failure == "fingerprint failed":
+
+ def failed_fingerprint(_model):
+ raise RuntimeError(failure)
+
+ monkeypatch.setattr(benchmark.bench, "_model_fingerprint", failed_fingerprint)
+ monkeypatch.setattr(benchmark.bench, "_runtime_info", lambda _mx: {})
+ monkeypatch.setattr(
+ benchmark.bench, "_model_settings", lambda _enabled: SimpleNamespace()
+ )
+ monkeypatch.setattr(benchmark.bench, "_build_prompt", lambda *_args: (10, 11))
+ monkeypatch.setattr(benchmark.bench, "_token_digest", lambda _ids: "prompt")
+ monkeypatch.setattr(benchmark.bench, "_assert_model_unchanged", lambda *_args: None)
+
+ async def run_trial(*_args, index, warmup):
+ if failure == "trial failed":
+ raise RuntimeError(failure)
+ controller = Controller()
+ controller.max_depth = 4
+ controller.observe()
+ assert controller.cur == fixed_depth
+ assert controller.should_exit() is False
+ Engine.instance._adapter.mtp_forward()
+ if os.environ[benchmark.PREWORK_ENV] == "1":
+ Prework.gdn_prework_fused()
+ return benchmark.bench.Trial(
+ index=index,
+ warmup=warmup,
+ prompt_tokens=2,
+ completion_tokens=2,
+ cached_tokens=0,
+ finish_reason="length",
+ output_token_ids=(1, 2),
+ output_sha256="same",
+ producer_first_s=1.0,
+ producer_last_s=2.0,
+ producer_duration_s=1.0,
+ consumer_duration_s=1.0,
+ generation_tps=1.0,
+ end_to_end_tps=2.0,
+ peak_memory_bytes=1,
+ errors=(),
+ )
+
+ monkeypatch.setattr(benchmark.bench, "_run_trial", run_trial)
+ original_init = Engine.__init__
+
+ def init(self, **kwargs):
+ original_init(self, **kwargs)
+ Engine.instance = self
+
+ Engine.__init__ = init
+ deps = {
+ "mx": MX,
+ "tree_flatten": lambda _params: [
+ ("weight", SimpleNamespace(dtype="bfloat16", shape=(2, 2)))
+ ],
+ "engine_cls": Engine,
+ "prework": Prework,
+ "depth_controller": Controller,
+ "scheduler_config": lambda **kwargs: kwargs,
+ }
+ args = SimpleNamespace(
+ model="model",
+ pp=2,
+ gen=2,
+ pairs=1,
+ fixed_depth=fixed_depth,
+ prompt_text="p",
+ )
+
+ result = asyncio.run(benchmark._run(args, deps))
+
+ assert os.environ[benchmark.PREWORK_ENV] == "original"
+ assert Controller.observe is original_observe
+ assert Controller.should_exit is original_should_exit
+ assert Prework.gdn_prework_fused is original_prework
+ if failure == "not ready":
+ assert not hasattr(language_model, "_omlx_mtp_depth")
+ else:
+ assert language_model._omlx_mtp_depth == 0
+ if failure != "fingerprint failed":
+ assert Engine.instance.stopped
+ if failure:
+ assert result["status"] == "error"
+ expected_error = "did not become ready" if failure == "not ready" else failure
+ assert expected_error in result["error"]
+ return
+
+ assert result["status"] == "ok"
+ assert result["fixed_depth"] == fixed_depth
+ assert Engine.instance.model_settings.mtp_num_draft_tokens == fixed_depth
+ assert result["outputs_identical"] is True
+ assert [record["treatment"] for record in result["trials"]] == [
+ False,
+ True,
+ False,
+ True,
+ True,
+ False,
+ ]
+ assert all(record["draft_calls"] == 1 for record in result["trials"])
+ assert [record["prework_calls"] for record in result["trials"]] == [
+ 0,
+ 1,
+ 0,
+ 1,
+ 1,
+ 0,
+ ]
diff --git a/tests/test_oq.py b/tests/test_oq.py
index 1dd8001ac6..f03eb41e96 100644
--- a/tests/test_oq.py
+++ b/tests/test_oq.py
@@ -8275,6 +8275,34 @@ def test_trunk_and_mtp_imatrix_hooks_execute(self, tmp_path):
@pytest.mark.skipif(not HAS_MLX, reason="MLX not available")
class TestGlm5NextLayerWalk:
+ def test_streamed_decoder_uses_registered_model_classes(self, tmp_path):
+ from dataclasses import asdict
+
+ from omlx.oq import _streamed_text_args
+ from omlx.patches import mlx_vlm_glm5_next_compat
+ 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.config import TextConfig
+ from mlx_vlm.models.glm5_next.language import Glm5NextDecoderLayer
+
+ config = asdict(_tiny_config())
+ (tmp_path / "config.json").write_text(json.dumps(config))
+ args, layer_cls = _streamed_text_args(tmp_path, config)
+
+ assert isinstance(args, TextConfig)
+ assert layer_cls is Glm5NextDecoderLayer
+
+ def test_streamed_mtp_rejects_unavailable_runtime_patch(self, monkeypatch):
+ from omlx.oq import _collect_streamed_glm5_next_mtp
+ from omlx.patches.mlx_vlm_mtp import glm5_next_vlm_runtime
+
+ monkeypatch.setattr(glm5_next_vlm_runtime, "apply", lambda: False)
+ with pytest.raises(RuntimeError, match="requires the runtime patch"):
+ _collect_streamed_glm5_next_mtp(
+ None, {}, OQImatrixCollector(), None, [], []
+ )
+
def test_cache_without_checkpoint_mtp_weights_is_reusable(self, tmp_path):
from omlx.oq import OQImatrixData, _oqe_cache_missing_mtp_entries
diff --git a/tests/test_oq_combine.py b/tests/test_oq_combine.py
index dfa69124f0..4833d2af90 100644
--- a/tests/test_oq_combine.py
+++ b/tests/test_oq_combine.py
@@ -33,6 +33,7 @@
"quantization": {"group_size": 64, "bits": 4},
}
+
ASSISTANT_CONFIG = {
"model_type": "gemma4_assistant",
"backbone_hidden_size": 24,
@@ -41,6 +42,12 @@
}
+@pytest.mark.parametrize("model_type", [None, [], {}, 42])
+def test_assistant_pair_rejects_invalid_base_type(model_type):
+ with pytest.raises(ValueError, match="requires a gemma4 base model"):
+ validate_gemma4_assistant_pair({"model_type": model_type}, ASSISTANT_CONFIG)
+
+
def _write_base_output(tmp_path):
out = tmp_path / "base-oQ4"
out.mkdir()
@@ -680,4 +687,3 @@ def test_import_mtplx_sidecar_rejects_failed_audit(tmp_path):
with pytest.raises(ValueError, match="payload_audit"):
import_mtplx_sidecar(out)
-
diff --git a/tests/test_qwen35_compiled_mlp.py b/tests/test_qwen35_compiled_mlp.py
new file mode 100644
index 0000000000..569a8bcca2
--- /dev/null
+++ b/tests/test_qwen35_compiled_mlp.py
@@ -0,0 +1,245 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Tests for compiled Qwen3.5-family decode MLP dispatch."""
+
+from __future__ import annotations
+
+import mlx.core as mx
+import mlx.nn as nn
+import pytest
+from mlx_lm.models.qwen3_next import (
+ ModelArgs,
+ Qwen3NextMLP,
+ Qwen3NextSparseMoeBlock,
+)
+from mlx_vlm.models.qwen3_5.language import Qwen3_5MLP
+from mlx_vlm.models.qwen3_5_moe.language import Qwen3_5MoeSparseMoeBlock
+
+from omlx.patches.qwen35_compiled_mlp import (
+ CompiledMLPBlock,
+ CompiledMLPBlocks,
+ CompiledTargetVerifyMLPBlock,
+)
+
+
+class _Host(nn.Module):
+ def __init__(self, mlp):
+ super().__init__()
+ self.mlp = mlp
+
+
+def _dense_mlp(cls=Qwen3NextMLP):
+ mx.random.seed(31)
+ mlp = cls(64, 128)
+ mlp.eval()
+ nn.quantize(mlp, group_size=64, bits=4)
+ mx.eval(mlp.parameters())
+ return mlp
+
+
+def _moe_block(cls=Qwen3NextSparseMoeBlock):
+ mx.random.seed(31)
+ args = ModelArgs(
+ model_type="qwen3_next",
+ hidden_size=64,
+ num_hidden_layers=1,
+ intermediate_size=128,
+ num_attention_heads=4,
+ linear_num_value_heads=4,
+ linear_num_key_heads=2,
+ linear_key_head_dim=16,
+ linear_value_head_dim=16,
+ linear_conv_kernel_dim=4,
+ num_experts=8,
+ num_experts_per_tok=2,
+ decoder_sparse_step=1,
+ shared_expert_intermediate_size=128,
+ mlp_only_layers=[],
+ moe_intermediate_size=128,
+ rms_norm_eps=1e-6,
+ vocab_size=128,
+ num_key_value_heads=2,
+ rope_theta=10000.0,
+ partial_rotary_factor=0.25,
+ max_position_embeddings=2048,
+ head_dim=16,
+ )
+ block = cls(args)
+ block.eval()
+ nn.quantize(block.switch_mlp, group_size=64, bits=4)
+ nn.quantize(block.shared_expert, group_size=64, bits=4)
+ mx.eval(block.parameters())
+ return block
+
+
+@pytest.mark.skipif(not mx.metal.is_available(), reason="requires Metal")
+def test_install_is_explicitly_gated_and_idempotent(monkeypatch):
+ host = _Host(_dense_mlp())
+ monkeypatch.setenv("OMLX_QWEN35_COMPILED_MLP", "0")
+ assert CompiledMLPBlocks.install(host) == 0
+ assert not isinstance(host.mlp, CompiledMLPBlock)
+
+ assert CompiledMLPBlocks.install(host, enabled=True) == 1
+ wrapper = host.mlp
+ assert isinstance(wrapper, CompiledMLPBlock)
+ assert CompiledMLPBlocks.install(host, enabled=True) == 0
+ assert host.mlp is wrapper
+ assert CompiledMLPBlocks.install(wrapper, enabled=True) == 0
+ assert not isinstance(wrapper.inner, CompiledMLPBlock)
+
+
+@pytest.mark.skipif(not mx.metal.is_available(), reason="requires Metal")
+def test_dispatch_defaults_on_with_opt_out(monkeypatch):
+ monkeypatch.delenv("OMLX_QWEN35_COMPILED_MLP", raising=False)
+ assert CompiledMLPBlocks.enabled()
+ monkeypatch.setenv("OMLX_QWEN35_COMPILED_MLP", "0")
+ assert not CompiledMLPBlocks.enabled()
+
+
+@pytest.mark.skipif(not mx.metal.is_available(), reason="requires Metal")
+@pytest.mark.parametrize("cls", [Qwen3NextMLP, Qwen3_5MLP])
+def test_prefill_patch_preserves_compiled_decode_policy(monkeypatch, cls):
+ from omlx.patches.qwen35_q4_mlp import _make_patched_mlp
+
+ original = getattr(cls, "_omlx_q4_mlp_original_call", cls.__call__)
+ monkeypatch.setattr(cls, "__call__", _make_patched_mlp(original, 8, 128, 16384))
+ inner = _dense_mlp(cls)
+ host = _Host(inner)
+ x = mx.random.normal((1, 1, 64)).astype(mx.float16)
+ expected = inner(x)
+ assert CompiledMLPBlocks.install(host, enabled=True) == 1
+ actual = host.mlp(x)
+ mx.eval(expected, actual)
+ assert mx.array_equal(actual, expected).item()
+
+
+@pytest.mark.skipif(not mx.metal.is_available(), reason="requires Metal")
+@pytest.mark.parametrize("cls", [Qwen3NextSparseMoeBlock, Qwen3_5MoeSparseMoeBlock])
+def test_eager_sparse_wrapper_does_not_block_dense_compilation(monkeypatch, cls):
+ original = cls.__call__
+
+ def eager(self, x, *args, **kwargs):
+ return original(self, x, *args, **kwargs)
+
+ monkeypatch.setattr(cls, "__call__", eager)
+ sparse = _moe_block(cls)
+ host = _Host(sparse)
+ host.dense = _dense_mlp()
+ assert CompiledMLPBlocks.install(host, enabled=True) == 1
+ assert host.mlp is sparse
+ assert isinstance(host.dense, CompiledMLPBlock)
+
+
+@pytest.mark.skipif(not mx.metal.is_available(), reason="requires Metal")
+@pytest.mark.parametrize("batch,seq", [(1, 1), (1, 4)])
+def test_compiled_quantized_dense_output_is_bit_exact(batch, seq):
+ inner = _dense_mlp()
+ host = _Host(inner)
+ x = mx.random.normal((batch, seq, 64)).astype(mx.float16)
+ expected = inner(x)
+ assert CompiledMLPBlocks.install(host, enabled=True) == 1
+
+ actual = host.mlp(x)
+ mx.eval(expected, actual)
+
+ assert mx.array_equal(actual, expected).item()
+
+
+@pytest.mark.skipif(not mx.metal.is_available(), reason="requires Metal")
+@pytest.mark.parametrize("cls", [Qwen3NextSparseMoeBlock, Qwen3_5MoeSparseMoeBlock])
+@pytest.mark.parametrize("dtype", [mx.float16, mx.bfloat16])
+@pytest.mark.parametrize("batch,seq", [(1, 1), (1, 3), (4, 1), (1, 5)])
+@pytest.mark.parametrize("direct", [False, True])
+def test_quantized_moe_stays_eager_and_bit_exact(
+ cls, dtype, batch, seq, direct, monkeypatch
+):
+ inner = _moe_block(cls)
+ host = _Host(inner)
+ model = inner if direct else host
+ shared_expert = inner.shared_expert
+ x = mx.random.normal((batch, seq, 64)).astype(dtype)
+ expected = inner(x)
+ mx.eval(expected)
+
+ def fail_compile(*args, **kwargs):
+ raise AssertionError("sparse MoE blocks and their children must stay eager")
+
+ monkeypatch.setattr(mx, "compile", fail_compile)
+ assert CompiledMLPBlocks.install(model, enabled=True) == 0
+ assert host.mlp is inner
+ assert host.mlp.shared_expert is shared_expert
+ assert CompiledMLPBlocks.install(model, enabled=True) == 0
+
+ actual = host.mlp(x)
+ mx.eval(actual)
+
+ assert mx.array_equal(actual, expected).item()
+
+
+@pytest.mark.skipif(not mx.metal.is_available(), reason="requires Metal")
+@pytest.mark.parametrize("cls", [Qwen3NextSparseMoeBlock, Qwen3_5MoeSparseMoeBlock])
+def test_mixed_model_compiles_only_dense_blocks(cls):
+ sparse = _moe_block(cls)
+ dense = _dense_mlp()
+ host = _Host(sparse)
+ host.dense = dense
+
+ assert CompiledMLPBlocks.install(host, enabled=True) == 1
+ assert host.mlp is sparse
+ assert not isinstance(host.mlp.shared_expert, CompiledMLPBlock)
+ assert isinstance(host.dense, CompiledMLPBlock)
+ assert host.dense.inner is dense
+ assert CompiledMLPBlocks.install(host, enabled=True) == 0
+
+
+@pytest.mark.skipif(not mx.metal.is_available(), reason="requires Metal")
+def test_batched_decode_prefill_and_target_verify_stay_eager(monkeypatch):
+ inner = _dense_mlp(Qwen3_5MLP)
+ host = _Host(inner)
+ assert CompiledMLPBlocks.install(host, enabled=True) == 1
+ assert isinstance(host.mlp, CompiledTargetVerifyMLPBlock)
+ compiled_calls = 0
+ original_dispatch = host.mlp.dispatch_compiled
+
+ def record(x):
+ nonlocal compiled_calls
+ compiled_calls += 1
+ return original_dispatch(x)
+
+ monkeypatch.setattr(host.mlp, "dispatch_compiled", record)
+ decode = mx.random.normal((1, 1, 64)).astype(mx.float16)
+ batched_decode = mx.random.normal((4, 1, 64)).astype(mx.float16)
+ prefill = mx.random.normal((1, 5, 64)).astype(mx.float16)
+
+ host.mlp(decode)
+ host.mlp(batched_decode)
+ host.mlp(decode, target_verify=True)
+ host.mlp(prefill)
+
+ assert compiled_calls == 1
+
+
+@pytest.mark.skipif(not mx.metal.is_available(), reason="requires Metal")
+def test_exact_verifier_unwraps_compiled_vlm_block(monkeypatch):
+ from mlx_vlm.models.qwen3_5 import language as q35
+
+ verifier = q35.LanguageModel.__call__.__globals__.get(
+ "_EXACT_SPECULATIVE_VERIFIER"
+ )
+ if verifier is None:
+ pytest.skip("mlx-vlm exact verifier not available")
+
+ inner = _dense_mlp(Qwen3_5MLP)
+ host = _Host(inner)
+ x = mx.random.normal((1, 1, 64)).astype(mx.float16)
+ expected = verifier._feed_forward(inner, x)
+
+ assert CompiledMLPBlocks.install(host, enabled=True) == 1
+
+ def fail_compiled_dispatch(_value):
+ raise AssertionError("exact verification must bypass compiled dispatch")
+
+ monkeypatch.setattr(host.mlp, "dispatch_compiled", fail_compiled_dispatch)
+ actual = verifier._feed_forward(host.mlp, x)
+ mx.eval(expected, actual)
+
+ assert mx.array_equal(actual, expected).item()
diff --git a/tests/test_qwen35_gdn_decode.py b/tests/test_qwen35_gdn_decode.py
new file mode 100644
index 0000000000..04bfacafae
--- /dev/null
+++ b/tests/test_qwen35_gdn_decode.py
@@ -0,0 +1,237 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Parity coverage for the fused Qwen3.5-family GDN decode convolution."""
+
+from __future__ import annotations
+
+import mlx.core as mx
+import mlx.nn as nn
+import pytest
+
+from omlx.patches.qwen35_gdn_decode import (
+ apply_qwen35_gdn_decode_patch,
+ fused_conv_silu,
+)
+
+
+@pytest.mark.skipif(not mx.metal.is_available(), reason="requires Metal")
+@pytest.mark.parametrize("batch", [1, 3])
+def test_fused_decode_conv_is_bit_exact(batch):
+ mx.random.seed(23)
+ channels = 256
+ state = (mx.random.normal((batch, 3, channels)) * 0.5).astype(mx.bfloat16)
+ x = (mx.random.normal((batch, 1, channels)) * 0.5).astype(mx.bfloat16)
+ weight = (mx.random.normal((channels, 4)) * 0.2).astype(mx.bfloat16)
+ conv = nn.Conv1d(channels, channels, 4, groups=channels, bias=False)
+ conv.weight = weight[:, :, None]
+
+ conv_input = mx.concatenate([state, x], axis=1)
+ expected_state = mx.contiguous(conv_input[:, -3:, :])
+ expected_output = nn.silu(conv(conv_input))
+ actual_state, actual_output = fused_conv_silu(state, x, weight)
+ mx.eval(expected_state, expected_output, actual_state, actual_output)
+
+ assert mx.array_equal(actual_state, expected_state).item()
+ assert mx.array_equal(actual_output, expected_output).item()
+
+
+def _qwen35_config():
+ from mlx_vlm.models.qwen3_5 import TextConfig
+
+ return TextConfig(
+ model_type="qwen3_5",
+ hidden_size=32,
+ intermediate_size=64,
+ 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_hidden_layers=2,
+ num_attention_heads=4,
+ rms_norm_eps=1e-6,
+ vocab_size=64,
+ num_key_value_heads=2,
+ max_position_embeddings=128,
+ )
+
+
+def _qwen4_config():
+ 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 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"],
+ )
+
+
+def _assert_vlm_gdn_call_matches_upstream(
+ monkeypatch,
+ family,
+ shape,
+ use_mask,
+ conv_kernel_size,
+ cache_metadata=None,
+):
+ from mlx_vlm.models.cache import ArraysCache
+ from mlx_vlm.models.qwen3_5 import language as q35
+
+ import omlx.patches.qwen35_gdn_decode as patch
+
+ if family == "qwen3_5":
+ cls = q35.Qwen3_5GatedDeltaNet
+ config = _qwen35_config()
+ else:
+ 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 import language as qwen4
+
+ cls = qwen4.Qwen4ExpGatedDeltaNet
+ config = _qwen4_config()
+
+ upstream_call = getattr(q35.Qwen3_5GatedDeltaNet.__call__, "_omlx_original", None)
+ if upstream_call is None:
+ upstream_call = q35.Qwen3_5GatedDeltaNet.__call__
+ monkeypatch.setattr(q35.Qwen3_5GatedDeltaNet, "__call__", upstream_call)
+ monkeypatch.setattr(patch, "_VLM_PATCHED", False)
+ monkeypatch.setattr(patch, "_ENABLED", True)
+ assert patch._patch_vlm()
+
+ config.linear_conv_kernel_dim = conv_kernel_size
+ mx.random.seed(31)
+ module = cls(config)
+ module.set_dtype(mx.bfloat16)
+ inputs = mx.random.normal(shape).astype(mx.bfloat16)
+ mask = None
+ if use_mask:
+ mask = mx.array(
+ [[True, False, True] for _ in range(shape[0])],
+ dtype=mx.bool_,
+ )
+
+ reference_cache = ArraysCache(2)
+ patched_cache = ArraysCache(2)
+ if cache_metadata is not None:
+ setattr(reference_cache, cache_metadata, mx.array([1, 2]))
+ setattr(patched_cache, cache_metadata, mx.array([1, 2]))
+ mask = reference_cache.make_mask(shape[1])
+ expected = upstream_call(module, inputs, mask=mask, cache=reference_cache)
+ actual = module(inputs, mask=mask, cache=patched_cache)
+ mx.eval(expected, actual, *reference_cache.state, *patched_cache.state)
+
+ assert mx.array_equal(actual, expected).item()
+ assert mx.array_equal(patched_cache[0], reference_cache[0]).item()
+ assert mx.array_equal(patched_cache[1], reference_cache[1]).item()
+ if cache_metadata is not None:
+ assert getattr(patched_cache, cache_metadata).tolist() == [
+ 1 - shape[1],
+ 2 - shape[1],
+ ]
+
+ next_inputs = mx.random.normal((shape[0], 1, shape[-1])).astype(mx.bfloat16)
+ expected = upstream_call(module, next_inputs, cache=reference_cache)
+ actual = module(next_inputs, cache=patched_cache)
+ mx.eval(expected, actual, *reference_cache.state, *patched_cache.state)
+
+ assert mx.array_equal(actual, expected).item()
+ assert mx.array_equal(patched_cache[0], reference_cache[0]).item()
+ assert mx.array_equal(patched_cache[1], reference_cache[1]).item()
+ if cache_metadata is not None:
+ assert getattr(patched_cache, cache_metadata).tolist() == [
+ -shape[1],
+ 1 - shape[1],
+ ]
+
+
+@pytest.mark.parametrize("family", ["qwen3_5", "qwen4_exp"])
+@pytest.mark.parametrize("conv_kernel_size", [3, 4])
+@pytest.mark.parametrize(
+ ("shape", "use_mask"),
+ [
+ ((1, 1, 32), False),
+ ((1, 3, 32), True),
+ ((2, 3, 32), True),
+ ],
+)
+def test_vlm_gdn_call_matches_current_upstream(
+ monkeypatch, family, shape, use_mask, conv_kernel_size
+):
+ _assert_vlm_gdn_call_matches_upstream(
+ monkeypatch, family, shape, use_mask, conv_kernel_size
+ )
+
+
+@pytest.mark.parametrize("cache_metadata", ["left_padding", "lengths"])
+def test_vlm_gdn_advances_ragged_cache_metadata(monkeypatch, cache_metadata):
+ _assert_vlm_gdn_call_matches_upstream(
+ monkeypatch, "qwen3_5", (2, 3, 32), True, 4, cache_metadata
+ )
+
+
+@pytest.mark.parametrize("length", [1, 3])
+def test_vlm_gdn_preserves_speculative_cache_rollback(monkeypatch, length):
+ from mlx_vlm.models.cache import ArraysCache
+ from mlx_vlm.models.qwen3_5 import language as q35
+ from mlx_vlm.speculative.cache_state import start_speculative_cache
+
+ import omlx.patches.qwen35_gdn_decode as patch
+
+ cls = q35.Qwen3_5GatedDeltaNet
+ original = getattr(cls.__call__, "_omlx_original", cls.__call__)
+ monkeypatch.setattr(cls, "__call__", original)
+ monkeypatch.setattr(patch, "_VLM_PATCHED", False)
+ assert patch._patch_vlm()
+ module = cls(_qwen35_config())
+ module.set_dtype(mx.bfloat16)
+ reference_cache, patched_cache = ArraysCache(2), ArraysCache(2)
+ reference = start_speculative_cache([reference_cache], length)
+ patched = start_speculative_cache([patched_cache], length)
+ inputs = mx.random.normal((1, length, 32)).astype(mx.bfloat16)
+ expected = original(module, inputs, cache=reference_cache)
+ actual = module(inputs, cache=patched_cache)
+ mx.eval(actual, expected)
+ assert mx.array_equal(actual, expected).item()
+ reference.commit([length - 1])
+ patched.commit([length - 1])
+ for actual_state, expected_state in zip(patched_cache.state, reference_cache.state):
+ if expected_state is None:
+ assert actual_state is None
+ else:
+ assert mx.array_equal(actual_state, expected_state).item()
+
+
+def test_patch_installs_for_lm_and_vlm():
+ assert apply_qwen35_gdn_decode_patch()
+ from mlx_lm.models.qwen3_5 import GatedDeltaNet
+ from mlx_vlm.models.qwen3_5.language import Qwen3_5GatedDeltaNet
+
+ assert getattr(GatedDeltaNet.__call__, "_omlx_fused_decode_conv", False) or getattr(
+ GatedDeltaNet.__call__, "_omlx_mtp_call_marker", False
+ )
+ assert getattr(Qwen3_5GatedDeltaNet.__call__, "_omlx_fused_decode_conv", False)
diff --git a/tests/test_qwen35_moe_routed_decode.py b/tests/test_qwen35_moe_routed_decode.py
index 179e32f2d1..85da047c25 100644
--- a/tests/test_qwen35_moe_routed_decode.py
+++ b/tests/test_qwen35_moe_routed_decode.py
@@ -447,6 +447,18 @@ def test_block_without_gate_up_fusion_is_not_routed():
assert routed.routed_decode_plan(block, x) is None
+@pytest.mark.parametrize("batch,length", [(1, 1), (2, 1), (1, 4)])
+def test_non_normalized_routing_rejects_cached_decode_and_window_plans(batch, length):
+ block = _block(1024, 320)
+ x = mx.random.normal((batch, length, 1024)).astype(mx.bfloat16)
+ assert routed.routed_decode_plan(block, x[:1, :1]) is not None
+ block.norm_topk_prob = False
+ assert routed.routed_decode_plan(block, x) is None
+ assert routed.routed_verify_window(block, x) is None
+ expected, actual = _pair(block, x)
+ assert _same_bits(expected, actual)
+
+
def test_kernel_failure_falls_back_once(monkeypatch):
block = _block(1024, 320)
x = mx.random.normal((1, 1, 1024)).astype(mx.bfloat16)
diff --git a/tests/test_qwen35_moe_router.py b/tests/test_qwen35_moe_router.py
index 820319c1ed..f45734d9b6 100644
--- a/tests/test_qwen35_moe_router.py
+++ b/tests/test_qwen35_moe_router.py
@@ -14,12 +14,49 @@
import numpy as np
import pytest
-from omlx.patches.qwen35_moe_router import fused_router_topk, router_eligible
+from omlx.patches.qwen35_moe_router import (
+ apply_qwen35_moe_router_patch,
+ fused_router_topk,
+ router_eligible,
+)
K = 8
NE = 256
+def test_current_vlm_moe_fallback_uses_signature_without_target_verify():
+ """mlx-vlm removed target_verify from its MoE block API in 0.6.16."""
+ from mlx_vlm.models.qwen3_5_moe.config import TextConfig
+ from mlx_vlm.models.qwen3_5_moe.language import Qwen3_5MoeSparseMoeBlock
+
+ config = TextConfig(
+ model_type="qwen3_5_moe_text",
+ hidden_size=8,
+ num_hidden_layers=1,
+ num_attention_heads=1,
+ linear_num_value_heads=1,
+ linear_num_key_heads=1,
+ linear_key_head_dim=4,
+ linear_value_head_dim=4,
+ linear_conv_kernel_dim=4,
+ num_experts=4,
+ num_experts_per_tok=2,
+ shared_expert_intermediate_size=4,
+ moe_intermediate_size=4,
+ rms_norm_eps=1e-6,
+ vocab_size=16,
+ num_key_value_heads=1,
+ max_position_embeddings=32,
+ )
+ block = Qwen3_5MoeSparseMoeBlock(config)
+ assert apply_qwen35_moe_router_patch()
+
+ output = block(mx.zeros((1, 1, 8), dtype=mx.float32))
+ mx.eval(output)
+
+ assert output.shape == (1, 1, 8)
+
+
def _composed(p, top_k=K):
inds = mx.argpartition(p, kth=-top_k, axis=-1)[..., -top_k:]
scores = mx.take_along_axis(p, inds, axis=-1)
@@ -124,6 +161,61 @@ def _composed_combine(routed, scores, shared, gate):
return y + shared
+@pytest.mark.parametrize("length", [1, 4, 9])
+@pytest.mark.parametrize("verify", [False, True])
+def test_non_normalized_vlm_routing_preserves_selected_scores(
+ monkeypatch, length, verify
+):
+ from types import SimpleNamespace
+
+ from mlx_vlm.models.qwen3_5.speculative_verifier import Qwen3_5BatchInvariantForward
+ from mlx_vlm.models.qwen3_5_moe.language import Qwen3_5MoeSparseMoeBlock
+
+ from omlx.patches import qwen35_moe_router as router
+
+ assert router.apply_qwen35_moe_router_patch()
+ block = Qwen3_5MoeSparseMoeBlock(
+ SimpleNamespace(
+ hidden_size=64,
+ moe_intermediate_size=64,
+ shared_expert_intermediate_size=64,
+ num_experts=32,
+ num_experts_per_tok=8,
+ norm_topk_prob=False,
+ )
+ )
+ block.set_dtype(mx.bfloat16)
+ x = mx.random.normal((1, length, 64)).astype(mx.bfloat16)
+ verifier = Qwen3_5BatchInvariantForward()
+ linear = verifier._linear if verify else lambda layer, value: layer(value)
+ gates = mx.softmax(linear(block.gate, x), axis=-1, precise=True)
+ indices = mx.argpartition(gates, kth=-block.top_k, axis=-1)[..., -block.top_k :]
+ scores = mx.take_along_axis(gates, indices, axis=-1)
+ routed = (
+ verifier._switch_glu(block.switch_mlp, x, indices)
+ if verify
+ else block.switch_mlp(x, indices)
+ )
+ shared = (
+ verifier._feed_forward(block.shared_expert, x)
+ if verify
+ else block.shared_expert(x)
+ )
+ shared *= mx.sigmoid(linear(block.shared_expert_gate, x))
+ expected = (routed * scores[..., None]).sum(axis=-2) + shared
+ normalized = (
+ routed * (scores / scores.sum(axis=-1, keepdims=True))[..., None]
+ ).sum(axis=-2) + shared
+ assert not mx.array_equal(expected, normalized).item()
+ monkeypatch.setattr(
+ router,
+ "fused_router_topk",
+ lambda *args: pytest.fail("Normalized router used for norm_topk_prob=False"),
+ )
+ actual = verifier._feed_forward(block, x) if verify else block(x)
+ assert mx.array_equal(actual, expected).item()
+
+
def _same_bits(a, b):
# NaN payloads aside, every element must carry the same BF16 bits.
both_nan = mx.isnan(a) & mx.isnan(b)
diff --git a/tests/test_qwen35_q4_mlp.py b/tests/test_qwen35_q4_mlp.py
index f717ee4baa..8744dfc4ae 100644
--- a/tests/test_qwen35_q4_mlp.py
+++ b/tests/test_qwen35_q4_mlp.py
@@ -1,3 +1,4 @@
+# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import importlib.util
@@ -39,6 +40,15 @@ def _fresh_qwen35_module(monkeypatch):
return module
+def _require_fp_kernel(mode):
+ from omlx.custom_kernels.quant_matmul import fast
+
+ name = f"{mode}_qmm_t"
+ if not fast.has_symbol(name):
+ pytest.skip(f"{name} native kernel unavailable")
+ return fast
+
+
def _quantized_bf16(linear, bits=4):
qlinear = nn.QuantizedLinear.from_linear(
linear, group_size=64, bits=bits, mode="affine"
@@ -49,6 +59,59 @@ def _quantized_bf16(linear, bits=4):
return qlinear
+def _float_quantized_bf16(linear, mode):
+ bits = 4 if mode == "mxfp4" else 8
+ return nn.QuantizedLinear.from_linear(linear, group_size=32, bits=bits, mode=mode)
+
+
+def test_m4_uses_short_prefill_default(monkeypatch):
+ from omlx.patches import qwen35_q4_mlp as patch
+
+ monkeypatch.setattr(
+ patch.mx,
+ "device_info",
+ lambda: {"device_name": "Apple M4 Max"},
+ )
+ assert patch._default_min_tokens() == 128
+ assert patch._route_min_tokens_for_bits(4, 128, 16384) == 128
+ assert patch._route_min_tokens_for_bits(8, 128, 16384) == 16384
+
+
+def test_non_m4_keeps_long_prefill_default(monkeypatch):
+ from omlx.patches import qwen35_q4_mlp as patch
+
+ monkeypatch.setattr(
+ patch.mx,
+ "device_info",
+ lambda: {"device_name": "Apple M3 Ultra"},
+ )
+ assert patch._default_min_tokens() == 2048
+
+
+@pytest.mark.parametrize(
+ "device_name,min_tokens", [("Apple M4 Max", 128), ("Apple M3 Ultra", 2048)]
+)
+def test_mlp_install_uses_hardware_policy_not_removed_env(
+ monkeypatch, device_name, min_tokens
+):
+ from omlx.patches import qwen35_q4_mlp as patch
+
+ monkeypatch.setattr(patch, "_PATCHED", False)
+ monkeypatch.setattr(patch, "_has_native_qmm", lambda: True)
+ monkeypatch.setattr(patch.mx, "device_info", lambda: {"device_name": device_name})
+ monkeypatch.setenv("OMLX_QWEN35_Q4_MLP_MIN_TOKENS", "16")
+ calls = []
+
+ def install(module, name, variant, minimum, q8_minimum):
+ calls.append((module, name, variant, minimum, q8_minimum))
+ return True
+
+ monkeypatch.setattr(patch, "_patch_class", install)
+ assert patch.apply_qwen35_q4_mlp_patch()
+ assert len(calls) == 2
+ assert all(call[2:] == (8, min_tokens, 16384) for call in calls)
+
+
@pytest.mark.parametrize("bits", [4, 5, 6, 8])
def test_qwen35_q_affine_qmm_matches_mlx_quantized_matmul(bits):
fast = _require_qmm_kernels((bits,))
@@ -80,13 +143,109 @@ def test_qwen35_q_affine_qmm_matches_mlx_quantized_matmul(bits):
assert rel <= 0.05
+@pytest.mark.parametrize("mode", ["mxfp4", "mxfp8"])
+@pytest.mark.parametrize("dtype", [mx.float16, mx.bfloat16])
+def test_qwen35_fp_qmm_matches_mlx_quantized_matmul(mode, dtype):
+ fast = _require_fp_kernel(mode)
+ bits = 4 if mode == "mxfp4" else 8
+ x = mx.random.normal((1, 32, 256)).astype(dtype)
+ linear = _float_quantized_bf16(nn.Linear(256, 128, bias=False), mode)
+ ref = linear(x)
+ got = getattr(fast, f"{mode}_qmm_t")(x, linear.weight, linear.scales, 8)
+ mx.eval(ref, got)
+
+ diff = mx.abs(got.astype(mx.float32) - ref.astype(mx.float32))
+ mx.eval(diff)
+ max_abs = float(mx.max(diff).item())
+ rel = float((mx.max(diff) / (mx.max(mx.abs(ref.astype(mx.float32))) + 1e-9)).item())
+ assert linear.bits == bits
+ assert got.dtype == dtype
+ assert max_abs <= 1.0
+ assert rel <= 0.05
+
+
+@pytest.mark.parametrize("mode", ["mxfp4", "mxfp8"])
+def test_qwen35_fp_qmm_rejects_unbuilt_variant(mode):
+ fast = _require_fp_kernel(mode)
+ x = mx.random.normal((1, 32, 256)).astype(mx.bfloat16)
+ linear = _float_quantized_bf16(nn.Linear(256, 128, bias=False), mode)
+
+ with pytest.raises(ValueError, match="floating-point qmm variant 5"):
+ getattr(fast, f"{mode}_qmm_t")(x, linear.weight, linear.scales, 5)
+
+
+def test_qwen35_mxfp4_routes_narrow_long_prefill():
+ from omlx.patches import qwen35_q4_mlp as patch
+
+ fast = _require_fp_kernel("mxfp4")
+ linear = _float_quantized_bf16(nn.Linear(512, 48, bias=False), "mxfp4")
+ x = mx.random.normal((1, 8192, 512)).astype(mx.bfloat16)
+ mx.eval(linear.weight, linear.scales, x)
+ ref = linear(x)
+ got = fast.mxfp4_qmm_t(x, linear.weight, linear.scales, 8)
+ fallback = patch._linear_qmm(linear, x, 0)
+ mx.eval(ref, got, fallback)
+
+ assert patch._is_supported_affine_linear(linear, x)
+ assert not patch._is_supported_affine_linear(linear, x[:, :4096, :])
+ diff = mx.abs(ref.astype(mx.float32) - got.astype(mx.float32))
+ assert mx.max(diff).item() <= 0.02
+ assert (
+ mx.max(mx.abs(ref.astype(mx.float32) - fallback.astype(mx.float32))).item()
+ == 0
+ )
+
+
+@pytest.mark.parametrize("bits", [4, 5])
+def test_qwen35_affine_routes_narrow_long_prefill(bits):
+ from omlx.patches import qwen35_q4_mlp as patch
+
+ fast = _require_qmm_kernels((bits,))
+ linear = _quantized_bf16(nn.Linear(512, 48, bias=False), bits)
+ x = mx.random.normal((1, 2048, 512)).astype(mx.bfloat16)
+ mx.eval(linear.weight, linear.scales, linear.biases, x)
+ ref = linear(x)
+ got = getattr(fast, f"affine_q{bits}_qmm_t")(
+ x,
+ linear.weight,
+ linear.scales,
+ linear.biases,
+ 8,
+ )
+ fallback = patch._linear_qmm(linear, x, 0)
+ mx.eval(ref, got, fallback)
+
+ assert patch._is_supported_affine_linear(linear, x)
+ assert not patch._is_supported_affine_linear(linear, x[:, :1024, :])
+ diff = mx.abs(ref.astype(mx.float32) - got.astype(mx.float32))
+ assert mx.max(diff).item() <= 1.0
+ assert (
+ mx.max(mx.abs(ref.astype(mx.float32) - fallback.astype(mx.float32))).item()
+ == 0
+ )
+
+
+def test_qwen35_affine_narrow_shape_falls_back_with_old_extension(monkeypatch):
+ from omlx.patches import qwen35_q4_mlp as patch
+
+ linear = _quantized_bf16(nn.Linear(512, 48, bias=False), 4)
+ x = mx.random.normal((1, 2048, 512)).astype(mx.bfloat16)
+ monkeypatch.setattr(patch, "_qmm_supports_narrow_affine", lambda: False)
+
+ assert not patch._is_supported_affine_linear(linear, x)
+ ref = linear(x)
+ got = patch._linear_qmm(linear, x, 8)
+ mx.eval(ref, got)
+ assert mx.array_equal(ref, got).item()
+
+
def test_qwen35_q4_mlp_patch_routes_prefill_and_skips_decode(monkeypatch):
fast = _require_q4_kernel()
import mlx_lm.models.qwen3_5 as qwen35
from omlx.patches.qwen35_q4_mlp import apply_qwen35_q4_mlp_patch
- monkeypatch.setattr("omlx.patches.qwen35_q4_mlp._MIN_TOKENS", 16)
+ monkeypatch.setattr("omlx.patches.qwen35_q4_mlp._default_min_tokens", lambda: 16)
mlp = qwen35.MLP(256, 512)
for name in ("gate_proj", "up_proj", "down_proj"):
@@ -116,13 +275,73 @@ def spy(*args, **kwargs):
assert calls["count"] == 0
+def test_qwen35_mxfp4_mlp_patch_routes_prefill_and_skips_decode(monkeypatch):
+ fast = _require_fp_kernel("mxfp4")
+ import mlx_lm.models.qwen3_5 as qwen35
+
+ from omlx.patches.qwen35_q4_mlp import apply_qwen35_q4_mlp_patch
+
+ monkeypatch.setattr("omlx.patches.qwen35_q4_mlp._default_min_tokens", lambda: 16)
+
+ mlp = qwen35.MLP(256, 512)
+ for name in ("gate_proj", "up_proj", "down_proj"):
+ setattr(
+ mlp,
+ name,
+ _float_quantized_bf16(getattr(mlp, name), "mxfp4"),
+ )
+
+ x = mx.random.normal((1, 32, 256)).astype(mx.bfloat16)
+ orig_call = getattr(qwen35.MLP, "_omlx_q4_mlp_original_call", qwen35.MLP.__call__)
+ y_ref = orig_call(mlp, x)
+ mx.eval(y_ref)
+
+ calls = {"count": 0}
+ orig_qmm = fast.mxfp4_qmm_t
+
+ def spy(*args, **kwargs):
+ calls["count"] += 1
+ return orig_qmm(*args, **kwargs)
+
+ monkeypatch.setattr(fast, "mxfp4_qmm_t", spy)
+ assert apply_qwen35_q4_mlp_patch() is True
+ y = mlp(x)
+ mx.eval(y)
+ assert calls["count"] == 3
+ assert mx.max(mx.abs(y.astype(mx.float32) - y_ref.astype(mx.float32))).item() <= 1.0
+
+ calls["count"] = 0
+ y_decode = mlp(x[:, :1, :])
+ mx.eval(y_decode)
+ assert calls["count"] == 0
+
+
+@pytest.mark.parametrize("mode", ["affine", "mxfp4", "mxfp8"])
+def test_qwen35_quantized_qmm_falls_back_on_cpu(mode):
+ from omlx.patches import qwen35_q4_mlp as patch
+
+ linear = nn.Linear(256, 128, bias=False)
+ if mode == "affine":
+ quantized = _quantized_bf16(linear)
+ else:
+ quantized = _float_quantized_bf16(linear, mode)
+ x = mx.random.normal((1, 32, 256)).astype(mx.bfloat16)
+
+ with mx.stream(mx.cpu):
+ expected = quantized(x)
+ actual = patch._linear_qmm(quantized, x, variant=8)
+ mx.eval(expected, actual)
+
+ assert mx.array_equal(actual, expected).item()
+
+
def test_qwen35_mixed_bit_mlp_patch_routes_5_bit_down_proj(monkeypatch):
fast = _require_qmm_kernels((4, 5))
import mlx_lm.models.qwen3_5 as qwen35
from omlx.patches.qwen35_q4_mlp import apply_qwen35_q4_mlp_patch
- monkeypatch.setattr("omlx.patches.qwen35_q4_mlp._MIN_TOKENS", 16)
+ monkeypatch.setattr("omlx.patches.qwen35_q4_mlp._default_min_tokens", lambda: 16)
mlp = qwen35.MLP(256, 512)
mlp.gate_proj = _quantized_bf16(mlp.gate_proj, bits=4)
@@ -252,7 +471,7 @@ class BackendCalledError(Exception):
pass
monkeypatch.setattr(q4patch, "_has_native_qmm", lambda: True)
- monkeypatch.setattr("omlx.patches.qwen35_q4_mlp._MIN_TOKENS", 16)
+ monkeypatch.setattr("omlx.patches.qwen35_q4_mlp._default_min_tokens", lambda: 16)
class FakeGDN:
sharding_group = None
@@ -373,7 +592,7 @@ def test_qwen35_q4_mlp_patch_prechecks_down_proj_before_gate_up(monkeypatch):
from omlx.patches.qwen35_q4_mlp import apply_qwen35_q4_mlp_patch
- monkeypatch.setattr("omlx.patches.qwen35_q4_mlp._MIN_TOKENS", 16)
+ monkeypatch.setattr("omlx.patches.qwen35_q4_mlp._default_min_tokens", lambda: 16)
mlp = qwen35.MLP(256, 512)
mlp.gate_proj = _quantized_bf16(mlp.gate_proj)
@@ -415,7 +634,7 @@ def test_qwen35_q4_prefill_linear_patch_routes_supported_only(monkeypatch):
from omlx.patches.qwen35_q4_mlp import apply_qwen35_q4_prefill_linear_patch
- monkeypatch.setattr("omlx.patches.qwen35_q4_mlp._MIN_TOKENS", 16)
+ monkeypatch.setattr("omlx.patches.qwen35_q4_mlp._default_min_tokens", lambda: 16)
supported = nn.QuantizedLinear(256, 128, bias=False, group_size=64, bits=4)
unsupported = nn.QuantizedLinear(256, 48, bias=False, group_size=64, bits=4)
@@ -458,7 +677,7 @@ def test_qwen35_q4_prefill_linear_patch_offers_packed_projections(monkeypatch):
import omlx.patches.qwen35_q4_mlp as q4patch
from omlx.patches.qwen35_packed_linear import PackedLinear, _pack
- monkeypatch.setattr("omlx.patches.qwen35_q4_mlp._MIN_TOKENS", 16)
+ monkeypatch.setattr("omlx.patches.qwen35_q4_mlp._default_min_tokens", lambda: 16)
source = nn.QuantizedLinear(256, 128, bias=False, group_size=64, bits=4)
source.set_dtype(mx.bfloat16)
routed = mx.ones((1, 32, 128), dtype=mx.bfloat16)
@@ -487,6 +706,7 @@ def test_qwen35_q8_backend_offered_below_a16_floor(monkeypatch):
import omlx.patches.qwen35_q4_mlp as q4patch
+ monkeypatch.setattr(q4patch, "_default_min_tokens", lambda: 2048)
q8 = nn.QuantizedLinear(256, 128, bias=False, group_size=64, bits=8)
q4 = nn.QuantizedLinear(256, 128, bias=False, group_size=64, bits=4)
for linear in (q8, q4):
@@ -537,7 +757,7 @@ def test_qwen35_q4_lm_attention_uses_sdpa_installed_after_the_patch(monkeypatch)
import omlx.patches.qwen35_q4_mlp as q4patch
- monkeypatch.setattr("omlx.patches.qwen35_q4_mlp._MIN_TOKENS", 16)
+ monkeypatch.setattr("omlx.patches.qwen35_q4_mlp._default_min_tokens", lambda: 16)
args = qwen35.TextModelArgs(
model_type="qwen3_5",
@@ -617,7 +837,7 @@ def test_qwen35_q4_lm_prefill_linear_patch_routes_attention_and_gdn(
import omlx.patches.qwen35_q4_mlp as q4patch
- monkeypatch.setattr("omlx.patches.qwen35_q4_mlp._MIN_TOKENS", 16)
+ monkeypatch.setattr("omlx.patches.qwen35_q4_mlp._default_min_tokens", lambda: 16)
args = qwen35.TextModelArgs(
model_type="qwen3_5",
diff --git a/tests/test_qwen35_verify_qmm.py b/tests/test_qwen35_verify_qmm.py
new file mode 100644
index 0000000000..a808fc5071
--- /dev/null
+++ b/tests/test_qwen35_verify_qmm.py
@@ -0,0 +1,171 @@
+# SPDX-License-Identifier: Apache-2.0
+
+import mlx.core as mx
+import mlx.nn as nn
+import pytest
+
+from omlx.patches import qwen35_verify_qmm
+from omlx.patches.qwen35_verify_qmm import (
+ _verify_route,
+ set_verify_qmm_armed,
+ takes_verify_route,
+ vk_eligible,
+ vk_qmm,
+)
+
+
+@pytest.mark.parametrize("mode", ["affine", "mxfp4", "mxfp8"])
+@pytest.mark.parametrize("rows", [3, 6])
+def test_verify_qmm_matches_quantized_linear(mode, rows):
+ bits = 4 if mode != "mxfp8" else 8
+ group_size = 64 if mode == "affine" else 32
+ linear = nn.Linear(256, 128, bias=True)
+ quantized = nn.QuantizedLinear.from_linear(
+ linear,
+ group_size=group_size,
+ bits=bits,
+ mode=mode,
+ )
+ inputs = mx.random.normal((rows, 256), dtype=mx.bfloat16)
+ expected = quantized(inputs)
+ actual = vk_qmm(
+ inputs,
+ quantized.weight,
+ quantized.scales,
+ quantized.biases
+ if quantized.biases is not None
+ else quantized.scales,
+ bits=bits,
+ group_size=group_size,
+ mode=mode,
+ )
+ if "bias" in quantized:
+ actual = actual + quantized.bias
+ mx.eval(expected, actual)
+
+ error = mx.max(
+ mx.abs(expected.astype(mx.float32) - actual.astype(mx.float32))
+ ).item()
+ assert error <= 1.0
+
+
+@pytest.mark.parametrize("mode", ["mxfp4", "mxfp8"])
+def test_verify_run_route_matches_mxfp_quantized_linear(mode):
+ bits = 4 if mode == "mxfp4" else 8
+ quantized = nn.QuantizedLinear.from_linear(
+ nn.Linear(256, 128, bias=False), group_size=32, bits=bits, mode=mode
+ )
+ inputs = mx.random.normal((3, 256), dtype=mx.bfloat16)
+ expected = quantized(inputs)
+ actual = qwen35_verify_qmm.run_route(quantized, inputs, "vk")
+ mx.eval(expected, actual)
+ error = mx.max(
+ mx.abs(expected.astype(mx.float32) - actual.astype(mx.float32))
+ ).item()
+ assert error <= 1.0
+
+
+@pytest.mark.parametrize("mode", ["mxfp4", "mxfp8"])
+def test_verify_qmm_mxfp_lm_head_tile_matches_quantized_linear(mode):
+ bits = 4 if mode == "mxfp4" else 8
+ linear = nn.Linear(64, 100000, bias=False)
+ quantized = nn.QuantizedLinear.from_linear(
+ linear,
+ group_size=32,
+ bits=bits,
+ mode=mode,
+ )
+ inputs = mx.random.normal((3, 64), dtype=mx.bfloat16)
+ expected = quantized(inputs)
+ actual = vk_qmm(
+ inputs,
+ quantized.weight,
+ quantized.scales,
+ quantized.scales,
+ bits=bits,
+ group_size=32,
+ mode=mode,
+ )
+ mx.eval(expected, actual)
+
+ error = mx.max(
+ mx.abs(expected.astype(mx.float32) - actual.astype(mx.float32))
+ ).item()
+ assert error <= 1.0
+
+
+@pytest.mark.parametrize(
+ ("mode", "bits", "group_size", "expected"),
+ [
+ ("affine", 4, 64, True),
+ ("mxfp4", 4, 32, True),
+ ("mxfp8", 8, 32, True),
+ ("mxfp4", 8, 32, False),
+ ("mxfp8", 8, 64, False),
+ ],
+)
+def test_verify_qmm_mode_eligibility(mode, bits, group_size, expected):
+ assert (
+ vk_eligible(
+ 3,
+ 256,
+ 16384,
+ bits,
+ group_size,
+ mx.bfloat16,
+ mode,
+ )
+ is expected
+ )
+
+
+@pytest.mark.parametrize(
+ ("mode", "rows", "expected_route"),
+ [
+ ("affine", 4, "sg8"),
+ ("affine", 16, "mma"),
+ ("mxfp4", 3, "vk"),
+ ("mxfp4", 4, "vk"),
+ ("mxfp8", 4, "vk"),
+ ("mxfp4", 8, None),
+ ("mxfp8", 16, None),
+ ],
+)
+def test_verify_route_prediction_respects_quantization_mode(mode, rows, expected_route):
+ bits = 8 if mode == "mxfp8" else 4
+ group_size = 64 if mode == "affine" else 32
+ linear = nn.QuantizedLinear(1024, 16384, group_size=group_size, bits=bits, mode=mode)
+ assert (
+ _verify_route(rows, 1024, 16384, bits, group_size, mx.bfloat16, mode)
+ == expected_route
+ )
+ from omlx.patches.qwen35_verify_qmm import apply_verify_qmm_patch
+
+ apply_verify_qmm_patch()
+ set_verify_qmm_armed(True)
+ try:
+ assert takes_verify_route(linear, rows, mx.bfloat16) is (
+ expected_route is not None
+ )
+ finally:
+ set_verify_qmm_armed(False)
+
+
+@pytest.mark.parametrize("m1_route", ["m1", "m1_mma"])
+@pytest.mark.parametrize(
+ ("mode", "bits", "group_size"),
+ [("affine", 4, 64), ("mxfp4", 4, 32), ("mxfp8", 8, 32)],
+)
+def test_m1_verify_routes_are_affine_only(monkeypatch, m1_route, mode, bits, group_size):
+ calls = []
+
+ def route(*args):
+ calls.append(args)
+ return m1_route
+
+ monkeypatch.setattr(qwen35_verify_qmm, "_m1_route", route)
+
+ actual = _verify_route(3, 2048, 16384, bits, group_size, mx.float16, mode)
+
+ assert actual == (m1_route if mode == "affine" else "vk")
+ assert len(calls) == (1 if mode == "affine" else 0)
diff --git a/tests/test_scripts_bench.py b/tests/test_scripts_bench.py
new file mode 100644
index 0000000000..6e68568293
--- /dev/null
+++ b/tests/test_scripts_bench.py
@@ -0,0 +1,268 @@
+# SPDX-License-Identifier: Apache-2.0
+
+import asyncio
+import importlib.util
+import sys
+from pathlib import Path
+from types import ModuleType
+
+import pytest
+
+
+@pytest.fixture
+def bench_module():
+ path = Path(__file__).parents[1] / "scripts" / "bench.py"
+ spec = importlib.util.spec_from_file_location("bench_script", path)
+ assert spec and spec.loader
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = module
+ try:
+ spec.loader.exec_module(module)
+ yield module
+ finally:
+ sys.modules.pop(spec.name, None)
+
+
+def test_parser_preserves_legacy_defaults(bench_module):
+ args = bench_module._parse_args(["model-a"])
+
+ assert args.models == ["model-a"]
+ assert args.native_mtp is bench_module.NativeMTPMode.OFF
+ assert args.qwen4_ple is None
+ assert args.pp == [1024, 4096, 8192]
+ assert args.gen == 128
+ assert args.batch == []
+ assert args.warmup == 1
+ assert bench_module._allocate_labels(
+ bench_module._expand_cases(args.models, args.native_mtp),
+ include_variant=False,
+ ) == ["model-a"]
+
+
+@pytest.mark.parametrize(
+ ("value", "expected"),
+ [
+ ("resident", "RESIDENT"),
+ ("ssd", "SSD"),
+ ("both", "BOTH"),
+ ],
+)
+def test_parser_accepts_qwen4_ple_modes(bench_module, value, expected):
+ args = bench_module._parse_args(["model-a", "--qwen4-ple", value])
+
+ assert args.qwen4_ple is getattr(bench_module.Qwen4PLEMode, expected)
+
+
+def test_parser_rejects_invalid_native_mtp_mode(bench_module):
+ with pytest.raises(SystemExit, match="2"):
+ bench_module._parse_args(["model-a", "--native-mtp", "enabled"])
+
+
+def test_legacy_case_expansion_and_labels_are_unchanged(bench_module):
+ cases = bench_module._expand_cases(
+ ["model-a", "model-b"],
+ bench_module.NativeMTPMode.BOTH,
+ )
+
+ assert [
+ (
+ case.model_path,
+ case.variant.native_mtp_enabled,
+ case.variant.ple_storage,
+ )
+ for case in cases
+ ] == [
+ ("model-a", False, None),
+ ("model-a", True, None),
+ ("model-b", False, None),
+ ("model-b", True, None),
+ ]
+ assert [case.variant.model_settings.mtp_enabled for case in cases] == [
+ False,
+ True,
+ False,
+ True,
+ ]
+ assert [
+ case.variant.model_settings.vlm_mtp_enabled for case in cases
+ ] == [False, False, False, False]
+ assert [case.variant.model_settings for case in cases] == [
+ bench_module.ModelSettings(mtp_enabled=False),
+ bench_module.ModelSettings(mtp_enabled=True),
+ bench_module.ModelSettings(mtp_enabled=False),
+ bench_module.ModelSettings(mtp_enabled=True),
+ ]
+ assert bench_module._allocate_labels(cases[:2], include_variant=True) == [
+ "baseline model-a",
+ "native-mtp model-a",
+ ]
+ on_cases = bench_module._expand_cases(
+ ["model-a"], bench_module.NativeMTPMode.ON
+ )
+ assert len(on_cases) == 1
+ assert on_cases[0].variant.model_settings.mtp_enabled is True
+
+
+def test_ple_both_expands_resident_before_ssd_with_native_mtp_off(
+ bench_module,
+):
+ cases = bench_module._expand_cases(
+ ["model-a"],
+ bench_module.NativeMTPMode.OFF,
+ bench_module.Qwen4PLEMode.BOTH,
+ )
+
+ assert [
+ (
+ case.variant.native_mtp_enabled,
+ case.variant.ple_storage,
+ case.variant.model_settings.mtp_enabled,
+ case.variant.model_settings.qwen4_ple_ssd_offload,
+ )
+ for case in cases
+ ] == [
+ (False, "resident", False, False),
+ (False, "ssd", False, True),
+ ]
+ assert bench_module._allocate_labels(
+ cases, include_variant=False
+ ) == ["ple=resident model-a", "ple=ssd model-a"]
+
+
+def test_native_mtp_and_ple_both_expand_in_cartesian_order(bench_module):
+ cases = bench_module._expand_cases(
+ ["model-a"],
+ bench_module.NativeMTPMode.BOTH,
+ bench_module.Qwen4PLEMode.BOTH,
+ )
+
+ assert [
+ (
+ case.variant.native_mtp_enabled,
+ case.variant.ple_storage,
+ case.variant.model_settings.mtp_enabled,
+ case.variant.model_settings.qwen4_ple_ssd_offload,
+ )
+ for case in cases
+ ] == [
+ (False, "resident", False, False),
+ (False, "ssd", False, True),
+ (True, "resident", True, False),
+ (True, "ssd", True, True),
+ ]
+ assert bench_module._allocate_labels(cases, include_variant=True) == [
+ "native-mtp=off ple=resident model-a",
+ "native-mtp=off ple=ssd model-a",
+ "native-mtp=on ple=resident model-a",
+ "native-mtp=on ple=ssd model-a",
+ ]
+
+
+def test_bench_model_passes_case_settings_and_stops_engine(
+ bench_module, monkeypatch
+):
+ benchmark = ModuleType("omlx.admin.benchmark")
+ def generate_prompt(tokenizer, pp):
+ assert tokenizer is not None
+ assert pp == 1
+ return "prompt"
+
+ async def fail_single_test(engine, prompt, max_tokens, pp_len):
+ assert engine is engines[0]
+ assert prompt == "prompt"
+ assert max_tokens == 1
+ assert pp_len == 1
+ raise RuntimeError("test failure")
+
+ async def fail_batch_test(engine, prompts, pp_len, max_tokens, batch_size):
+ raise AssertionError("batch test should not run")
+
+ benchmark._generate_prompt = generate_prompt
+ benchmark._run_single_test = fail_single_test
+ benchmark._run_batch_test = fail_batch_test
+
+ engine_module = ModuleType("omlx.engine.vlm")
+ constructed = []
+ engines = []
+ lifecycle = []
+
+ class FakeEngine:
+ def __init__(self, model_name, model_settings):
+ constructed.append(
+ {
+ "model_name": model_name,
+ "model_settings": model_settings,
+ }
+ )
+ self.tokenizer = object()
+ self.stopped = False
+ engines.append(self)
+
+ async def start(self):
+ lifecycle.append("start")
+
+ async def stop(self):
+ lifecycle.append("stop")
+ self.stopped = True
+
+ engine_module.VLMBatchedEngine = FakeEngine
+ monkeypatch.setitem(sys.modules, "omlx.admin.benchmark", benchmark)
+ monkeypatch.setitem(sys.modules, "omlx.engine.vlm", engine_module)
+ case = bench_module._expand_cases(
+ ["model-a"],
+ bench_module.NativeMTPMode.ON,
+ bench_module.Qwen4PLEMode.SSD,
+ )[0]
+
+ with pytest.raises(RuntimeError, match="test failure"):
+ asyncio.run(bench_module._bench_model(case, [1], 1, [], 0))
+
+ assert constructed == [
+ {
+ "model_name": "model-a",
+ "model_settings": case.variant.model_settings,
+ }
+ ]
+ assert engines[0].stopped
+ assert lifecycle == ["start", "stop"]
+
+
+def test_allocate_labels_adds_stable_ordinals_for_duplicate_logical_labels(
+ bench_module,
+):
+ cases = bench_module._expand_cases(
+ ["/models/duplicate", "/other/duplicate"],
+ bench_module.NativeMTPMode.OFF,
+ )
+
+ assert bench_module._allocate_labels(cases, include_variant=False) == [
+ "duplicate #1",
+ "duplicate #2",
+ ]
+
+
+def test_allocate_labels_handles_names_that_resemble_ordinals(bench_module):
+ cases = bench_module._expand_cases(
+ ["/models/duplicate", "/other/duplicate", "/models/duplicate #1"],
+ bench_module.NativeMTPMode.OFF,
+ )
+
+ labels = bench_module._allocate_labels(cases, include_variant=False)
+
+ assert labels == ["duplicate #1", "duplicate #2", "duplicate #1 #1"]
+ assert len(set(labels)) == len(labels)
+
+
+@pytest.mark.parametrize("width", [39, 29])
+def test_display_labels_remain_unique_after_truncation(bench_module, width):
+ labels = [
+ "native-mtp Qwen3.8-Flash-Next-very-long-model-name-a",
+ "native-mtp Qwen3.8-Flash-Next-very-long-model-name-b",
+ ]
+
+ displays = bench_module._display_labels(labels, width)
+
+ assert len(set(displays)) == len(displays)
+ assert all(len(display) <= width for display in displays)
+ assert displays[0].endswith("#1")
+ assert displays[1].endswith("#2")
From 2bce7287e321280e5ccf789fea265a4fe7060478 Mon Sep 17 00:00:00 2001
From: Mike Wallio
Date: Wed, 4 Nov 2026 09:15:01 -0500
Subject: [PATCH 04/24] feat(inference): add multimodal protocols and native
speculative model support
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
---
omlx/MLX_VLM_LICENSE.txt | 21 +
omlx/adapter/gemma4.py | 6 +-
omlx/api/anthropic_models.py | 12 +
omlx/api/audio_routes.py | 8 +-
omlx/api/decisions.py | 6 +-
omlx/api/markitdown.py | 38 +-
omlx/api/media_inputs.py | 179 ++
omlx/api/media_options.py | 43 +
omlx/api/openai_models.py | 219 ++-
omlx/api/responses_models.py | 2 +
omlx/api/responses_utils.py | 186 +-
omlx/api/utils.py | 42 +-
omlx/engine/tts.py | 3 +
omlx/engine/vlm.py | 740 +++++++-
omlx/models/vlm.py | 187 +-
omlx/patches/arrays_cache_metadata.py | 2 +-
.../bailing_hybrid/bailing_hybrid_model.py | 54 +-
omlx/patches/bailing_hybrid/fp8.py | 95 ++
omlx/patches/deepseek_v4/cache_extras.py | 1 +
omlx/patches/deepseek_v4/chat_template_v4.py | 8 +-
omlx/patches/deepseek_v4/deepseek_v4_model.py | 2 +
omlx/patches/deepseek_v4/dsv4_chat_encoder.py | 208 +++
omlx/patches/deepseek_v4/hyper_connection.py | 2 +
omlx/patches/deepseek_v4/tokenizer_patch.py | 20 +-
omlx/patches/deepseek_v4/utils_patch.py | 1 +
omlx/patches/hybrid_batch_cache.py | 78 +
omlx/patches/minicpm47.py | 299 ++++
omlx/patches/mlx_audio_compat.py | 47 +
omlx/patches/mlx_lm_mtp/batch_generator.py | 157 +-
omlx/patches/mlx_lm_mtp/deepseek_v4_model.py | 3 -
omlx/patches/mlx_lm_mtp/fused_batch.py | 4 +
omlx/patches/mlx_lm_mtp/prompt_priming.py | 28 +-
omlx/patches/mlx_lm_mtp/uniform.py | 146 ++
.../__init__.py | 164 ++
.../vendor/__init__.py | 1 +
.../vendor/mlx_vlm/__init__.py | 1 +
.../vendor/mlx_vlm/models/__init__.py | 1 +
.../models/bailing_moe_v3_vl/__init__.py | 24 +
.../bailing_moe_v3_vl/bailing_moe_v3_vl.py | 167 ++
.../models/bailing_moe_v3_vl/config.py | 176 ++
.../models/bailing_moe_v3_vl/language.py | 651 +++++++
.../processing_bailing_moe_v3_vl.py | 47 +
.../models/bailing_moe_v3_vl/vision.py | 46 +
.../mlx_vlm_inkling_compat/__init__.py | 31 +
.../vendor/mlx_vlm/models/inkling/README.md | 7 +-
.../vendor/mlx_vlm/models/inkling/language.py | 7 +-
.../mlx_vlm_mtp/inkling_vlm_runtime.py | 21 +-
.../mlx_vlm_mtp/qwen35_moe_vlm_runtime.py | 9 +-
.../patches/mlx_vlm_mtp/qwen35_vlm_runtime.py | 27 +-
.../mlx_vlm_muse_glimmer_compat/__init__.py | 65 +
.../vendor/mlx_vlm/models/activations.py | 40 -
.../mlx_vlm/models/muse_glimmer/README.md | 48 -
.../mlx_vlm/models/muse_glimmer/__init__.py | 17 -
.../mlx_vlm/models/muse_glimmer/config.py | 129 --
.../mlx_vlm/models/muse_glimmer/language.py | 313 ----
.../models/muse_glimmer/muse_glimmer.py | 141 --
.../muse_glimmer/processing_muse_glimmer.py | 249 ---
.../mlx_vlm/models/muse_glimmer/vision.py | 313 ----
.../vendor/__init__.py | 7 -
.../mlx_vlm_qwen4_exp_compat/__init__.py | 31 +-
.../mlx_vlm/models/qwen4_exp/language.py | 153 +-
omlx/patches/nemotron_omni.py | 89 +
omlx/patches/nemotron_omni_quantization.py | 125 ++
omlx/patches/specprefill.py | 50 +-
omlx/patches/turboquant_attention.py | 26 +-
omlx/patches/virtual_tensors.py | 2 +
omlx/speculative/dflash/__init__.py | 77 +-
omlx/speculative/dspark_drafter.py | 183 ++
omlx/speculative/minicpm_dspark.py | 190 +++
omlx/speculative/minicpm_pairing.py | 52 +
omlx/utils/image.py | 33 +-
omlx/utils/video.py | 13 +-
.../fixtures/minicpmv4_7_chat_template.jinja | 142 ++
tests/minicpm47_fixtures.py | 213 +++
tests/minicpm47_native_cases.py | 921 ++++++++++
tests/test_anthropic_models.py | 28 +-
tests/test_api_utils.py | 146 +-
tests/test_audio_api.py | 1 +
tests/test_audio_tts.py | 187 ++
tests/test_deepseek_v4_patch.py | 134 +-
tests/test_dspark_drafter.py | 351 ++++
tests/test_gdn_compact_state_lifecycle.py | 68 +
tests/test_gemma4_messages.py | 34 +
tests/test_gemma4_vlm_mtp_runtime.py | 1 +
tests/test_glm_moe_dsa_patch.py | 37 +-
tests/test_inkling_vlm_mtp.py | 5 +-
tests/test_media_options.py | 80 +
tests/test_minicpm47.py | 35 +
tests/test_minicpm_media.py | 653 +++++++
tests/test_minicpm_pairing.py | 52 +
tests/test_mlx_lm_mtp_patch.py | 470 ++++-
.../test_mlx_vlm_bailing_moe_v3_vl_compat.py | 402 +++++
tests/test_mlx_vlm_inkling_compat.py | 67 +
tests/test_mlx_vlm_muse_glimmer_compat.py | 5 +-
tests/test_mlx_vlm_qwen4_exp.py | 21 +
tests/test_mlx_vlm_qwen4_exp_compat.py | 2 +-
tests/test_mlx_vlm_unlimited_ocr_compat.py | 1 -
tests/test_mtp_depth_controller.py | 1 -
tests/test_mtp_prompt_priming.py | 42 +-
tests/test_mtp_xtc_sampling.py | 14 +-
tests/test_nemotron_omni.py | 1513 +++++++++++++++++
tests/test_openai_models.py | 37 +
tests/test_responses.py | 110 ++
tests/test_video.py | 10 +
tests/test_vlm_cohere2_moe_loader.py | 33 +-
tests/test_vlm_engine.py | 295 +++-
tests/test_vlm_model_adapter.py | 3 +
tests/test_vlm_mtp.py | 55 +-
tests/test_vlm_native_mtp.py | 286 ++++
tests/test_vlm_qwen4_exp_loader.py | 124 +-
110 files changed, 11300 insertions(+), 1852 deletions(-)
create mode 100644 omlx/MLX_VLM_LICENSE.txt
create mode 100644 omlx/api/media_inputs.py
create mode 100644 omlx/api/media_options.py
create mode 100644 omlx/patches/bailing_hybrid/fp8.py
create mode 100644 omlx/patches/deepseek_v4/dsv4_chat_encoder.py
create mode 100644 omlx/patches/hybrid_batch_cache.py
create mode 100644 omlx/patches/minicpm47.py
create mode 100644 omlx/patches/mlx_lm_mtp/uniform.py
create mode 100644 omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/__init__.py
create mode 100644 omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/__init__.py
create mode 100644 omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/__init__.py
create mode 100644 omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/models/__init__.py
create mode 100644 omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/models/bailing_moe_v3_vl/__init__.py
create mode 100644 omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/models/bailing_moe_v3_vl/bailing_moe_v3_vl.py
create mode 100644 omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/models/bailing_moe_v3_vl/config.py
create mode 100644 omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/models/bailing_moe_v3_vl/language.py
create mode 100644 omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/models/bailing_moe_v3_vl/processing_bailing_moe_v3_vl.py
create mode 100644 omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/models/bailing_moe_v3_vl/vision.py
delete mode 100644 omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/activations.py
delete mode 100644 omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/muse_glimmer/README.md
delete mode 100644 omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/muse_glimmer/__init__.py
delete mode 100644 omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/muse_glimmer/config.py
delete mode 100644 omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/muse_glimmer/language.py
delete mode 100644 omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/muse_glimmer/muse_glimmer.py
delete mode 100644 omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/muse_glimmer/processing_muse_glimmer.py
delete mode 100644 omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/muse_glimmer/vision.py
delete mode 100644 omlx/patches/mlx_vlm_pixtral_torch_free/vendor/__init__.py
create mode 100644 omlx/patches/nemotron_omni.py
create mode 100644 omlx/patches/nemotron_omni_quantization.py
create mode 100644 omlx/speculative/dspark_drafter.py
create mode 100644 omlx/speculative/minicpm_dspark.py
create mode 100644 omlx/speculative/minicpm_pairing.py
create mode 100644 tests/fixtures/minicpmv4_7_chat_template.jinja
create mode 100644 tests/minicpm47_fixtures.py
create mode 100644 tests/minicpm47_native_cases.py
create mode 100644 tests/test_dspark_drafter.py
create mode 100644 tests/test_gdn_compact_state_lifecycle.py
create mode 100644 tests/test_media_options.py
create mode 100644 tests/test_minicpm47.py
create mode 100644 tests/test_minicpm_media.py
create mode 100644 tests/test_minicpm_pairing.py
create mode 100644 tests/test_mlx_vlm_bailing_moe_v3_vl_compat.py
create mode 100644 tests/test_mlx_vlm_qwen4_exp.py
create mode 100644 tests/test_nemotron_omni.py
create mode 100644 tests/test_vlm_native_mtp.py
diff --git a/omlx/MLX_VLM_LICENSE.txt b/omlx/MLX_VLM_LICENSE.txt
new file mode 100644
index 0000000000..938e89e95e
--- /dev/null
+++ b/omlx/MLX_VLM_LICENSE.txt
@@ -0,0 +1,21 @@
+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.
diff --git a/omlx/adapter/gemma4.py b/omlx/adapter/gemma4.py
index 48a38f8b88..a15fe7c8e4 100644
--- a/omlx/adapter/gemma4.py
+++ b/omlx/adapter/gemma4.py
@@ -119,7 +119,7 @@ def extract_gemma4_messages(
raw: list[dict] = []
for msg in messages:
if hasattr(msg, "model_dump"):
- raw.append(msg.model_dump())
+ raw.append(msg.model_dump(exclude_none=True))
elif isinstance(msg, dict):
raw.append(dict(msg))
else:
@@ -260,13 +260,13 @@ def extract_gemma4_messages(
continue
# All other roles (user, system)
- # Preserve image_url and input_audio parts for VLM processing
+ # Preserve media parts for VLM processing and capability validation.
content = msg.get("content", "")
if isinstance(content, list):
from ..api.utils import _extract_multimodal_content_list
multimodal_parts = _extract_multimodal_content_list(content)
- multimodal_types = {"image_url", "input_audio"}
+ multimodal_types = {"image_url", "video_url", "input_audio", "input_video"}
has_multimodal = any(
p.get("type") in multimodal_types for p in multimodal_parts
)
diff --git a/omlx/api/anthropic_models.py b/omlx/api/anthropic_models.py
index 9dce382fac..8cc47fe424 100644
--- a/omlx/api/anthropic_models.py
+++ b/omlx/api/anthropic_models.py
@@ -12,6 +12,7 @@
from pydantic import BaseModel, ConfigDict, Discriminator, Field, Tag, model_validator
+from omlx.api.media_options import MultimodalProcessorOptions
from omlx.api.shared_models import IDPrefix, generate_id
# =============================================================================
@@ -214,6 +215,13 @@ class ThinkingConfig(BaseModel):
budget_tokens: int | None = None
+class OutputConfig(BaseModel):
+ """Anthropic output controls."""
+
+ effort: Literal["low", "medium", "high", "xhigh", "max"] | None = None
+ format: dict[str, Any] | None = None
+
+
# =============================================================================
# Request
# =============================================================================
@@ -235,8 +243,10 @@ class MessagesRequest(BaseModel):
tools: list[AnthropicTool] | None = None
tool_choice: ToolChoice | dict[str, Any] | None = None
thinking: ThinkingConfig | None = None
+ output_config: OutputConfig | None = None
# Chat template kwargs (e.g. enable_thinking, reasoning_effort)
chat_template_kwargs: dict[str, Any] | None = None
+ mm_processor_kwargs: MultimodalProcessorOptions | None = None
# =============================================================================
@@ -253,6 +263,8 @@ class TokenCountRequest(BaseModel):
tools: list[AnthropicTool] | None = None
tool_choice: ToolChoice | dict[str, Any] | None = None
thinking: ThinkingConfig | None = None
+ output_config: OutputConfig | None = None
+ mm_processor_kwargs: MultimodalProcessorOptions | None = None
class TokenCountResponse(BaseModel):
diff --git a/omlx/api/audio_routes.py b/omlx/api/audio_routes.py
index acae90d032..85640971db 100644
--- a/omlx/api/audio_routes.py
+++ b/omlx/api/audio_routes.py
@@ -1594,7 +1594,7 @@ def _transcode_speech_output(wav_bytes: bytes, response_format: str) -> bytes:
async def create_speech(request: AudioSpeechRequest):
"""OpenAI-compatible text-to-speech endpoint."""
from omlx.engine.tts import TTSEngine
- from omlx.exceptions import ModelNotFoundError
+ from omlx.exceptions import ModelNotFoundError, UnsupportedKokoroLanguageError
if not request.input or not request.input.strip():
raise HTTPException(status_code=400, detail="'input' field must not be empty")
@@ -1629,6 +1629,8 @@ async def create_speech(request: AudioSpeechRequest):
status_code=404,
detail=f"Model '{resolved_model}' not found. Available: {avail}",
) from exc
+ except UnsupportedKokoroLanguageError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
except Exception as exc:
raise HTTPException(status_code=500, detail=str(exc)) from exc
@@ -1658,6 +1660,8 @@ async def create_speech(request: AudioSpeechRequest):
) from exc
except (HTTPException, InvalidRequestError):
raise
+ except UnsupportedKokoroLanguageError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
except Exception as exc:
raise HTTPException(status_code=500, detail=str(exc)) from exc
return StreamingResponse(
@@ -1682,6 +1686,8 @@ async def create_speech(request: AudioSpeechRequest):
)
except (HTTPException, InvalidRequestError):
raise
+ except UnsupportedKokoroLanguageError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
except Exception as exc:
raise HTTPException(status_code=500, detail=str(exc)) from exc
finally:
diff --git a/omlx/api/decisions.py b/omlx/api/decisions.py
index fcb7380c3c..2b7decb5d8 100644
--- a/omlx/api/decisions.py
+++ b/omlx/api/decisions.py
@@ -19,7 +19,7 @@
"""
import asyncio
-from collections.abc import Callable
+from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from typing import Any
@@ -321,7 +321,7 @@ async def decide(
engine: Any,
request: DecisionRequest,
multimodal: bool,
- prepare: Callable[[list[dict]], dict] | None = None,
+ prepare: Callable[[list[dict]], Awaitable[dict]] | None = None,
require_answer: bool = True,
) -> dict:
"""Answer every question with a chat model; returns answers and tokens.
@@ -337,7 +337,7 @@ async def decide(
async def chat(messages, **kwargs):
if prepare is not None:
- kwargs.update(prepare(messages))
+ kwargs.update(await prepare(messages))
return await engine.chat(messages=messages, **kwargs)
async def answer(question):
diff --git a/omlx/api/markitdown.py b/omlx/api/markitdown.py
index ffcb0f8502..ba26df61cc 100644
--- a/omlx/api/markitdown.py
+++ b/omlx/api/markitdown.py
@@ -349,7 +349,10 @@ def preprocess_markitdown_file_parts(
status_code=400,
)
- parsed = parse_file_part(part_dict, max_file_size_mb=max_file_size_mb)
+ parsed = parse_file_part(
+ part_dict,
+ max_file_size_mb=max_file_size_mb,
+ )
markdown = convert_attachment_to_markdown(
parsed,
global_settings=global_settings,
@@ -433,7 +436,10 @@ async def preprocess_markitdown_file_parts_async(
status_code=400,
)
- parsed = parse_file_part(part_dict, max_file_size_mb=max_file_size_mb)
+ parsed = parse_file_part(
+ part_dict,
+ max_file_size_mb=max_file_size_mb,
+ )
markdown = await convert_attachment_to_markdown_async(
parsed,
global_settings=global_settings,
@@ -456,25 +462,43 @@ async def preprocess_markitdown_file_parts_async(
return processed
-def parse_file_part(part: dict[str, Any], *, max_file_size_mb: int) -> MarkItDownFile:
+def parse_file_part(
+ part: dict[str, Any],
+ *,
+ max_file_size_mb: int,
+) -> MarkItDownFile:
file_obj = part.get("file")
if not isinstance(file_obj, dict):
raise MarkItDownRequestError("File content part must include a file object.")
data_value = file_obj.get("file_data") or file_obj.get("data")
+ file_url = file_obj.get("file_url")
+ required_source_message = "File content part requires file.file_data."
+ if file_url:
+ raise MarkItDownRequestError(
+ "File URLs are not supported. Send base64 content in file.file_data.",
+ status_code=400,
+ )
if not data_value and file_obj.get("file_id"):
raise MarkItDownRequestError(
"File content part file_id is not supported. "
"Send base64 content in file.file_data instead.",
status_code=400,
)
- if not isinstance(data_value, str) or not data_value.strip():
+ if not data_value:
+ raise MarkItDownRequestError(
+ required_source_message,
+ status_code=400,
+ )
+ if data_value is not None and (
+ not isinstance(data_value, str) or not data_value.strip()
+ ):
raise MarkItDownRequestError(
- "File content part requires file.file_data.",
+ required_source_message,
status_code=400,
)
- data_uri_mime_type = _mime_type_from_data_uri(data_value)
+ data_uri_mime_type = _mime_type_from_data_uri(data_value or "")
mime_type = (
str(file_obj.get("mime_type") or data_uri_mime_type or "").strip().lower()
)
@@ -492,8 +516,8 @@ def parse_file_part(part: dict[str, Any], *, max_file_size_mb: int) -> MarkItDow
extension = Path(filename).suffix.lower()
_validate_supported_file(filename, mime_type)
- data = _decode_data(data_value)
max_bytes = max_file_size_mb * 1024 * 1024
+ data = _decode_data(data_value)
if len(data) > max_bytes:
raise MarkItDownRequestError(
f"Attached file exceeds the {max_file_size_mb}MB limit: {filename}",
diff --git a/omlx/api/media_inputs.py b/omlx/api/media_inputs.py
new file mode 100644
index 0000000000..909eae13dc
--- /dev/null
+++ b/omlx/api/media_inputs.py
@@ -0,0 +1,179 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Helpers for OpenAI-compatible audio/video file inputs."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+AUDIO_EXTENSIONS = {".wav", ".mp3", ".mpeg", ".mpga", ".m4a", ".webm"}
+VIDEO_EXTENSIONS = {".mp4", ".mov", ".m4v", ".webm", ".avi", ".mkv"}
+
+
+def normalize_media_file_part(part: dict[str, Any]) -> dict[str, Any] | None:
+ """Convert audio/video file parts to internal media content parts.
+
+ Returns ``None`` for document/text files so callers can keep routing those
+ through MarkItDown. Video is an oMLX extension transported via OpenAI file
+ part shapes.
+ """
+ file_obj = _file_object_from_part(part)
+ if file_obj is None:
+ return None
+
+ mime_type = _normalized_mime_type(file_obj)
+ extension = _file_extension(file_obj, mime_type)
+ if mime_type.startswith("audio/"):
+ is_audio = True
+ is_video = False
+ elif mime_type.startswith("video/"):
+ is_audio = False
+ is_video = True
+ else:
+ is_video = extension in VIDEO_EXTENSIONS
+ is_audio = extension in AUDIO_EXTENSIONS and not is_video
+ if not is_audio and not is_video:
+ return None
+
+ data = file_obj.get("file_data") or file_obj.get("data")
+ url = file_obj.get("file_url")
+ if url:
+ raise ValueError(
+ "file_url is not supported for audio/video file parts. "
+ "Send base64 content in file_data."
+ )
+ if file_obj.get("file_id") and not data:
+ raise ValueError(
+ "File IDs for audio/video inputs are not supported. "
+ "Send base64 content in file_data."
+ )
+ if not data:
+ raise ValueError("Audio/video file parts require base64 file_data.")
+
+ filename = str(file_obj.get("filename") or "").strip() or None
+ media_format = extension[1:] if extension else _format_from_mime_type(mime_type)
+ payload: dict[str, Any] = {
+ "format": media_format or ("mp4" if is_video else "wav"),
+ }
+ payload["data"] = data
+ if filename:
+ payload["filename"] = filename
+ if mime_type:
+ payload["mime_type"] = mime_type
+
+ if is_video:
+ return {"type": "input_video", "input_video": payload}
+ return {"type": "input_audio", "input_audio": payload}
+
+
+def normalize_media_file_parts_in_messages(messages: list[Any]) -> list[Any]:
+ """Replace media file parts in Pydantic/dict messages with media parts."""
+ changed_any = False
+ normalized = []
+ for msg in messages:
+ content = (
+ msg.get("content")
+ if isinstance(msg, dict)
+ else getattr(msg, "content", None)
+ )
+ if not isinstance(content, list):
+ normalized.append(msg)
+ continue
+
+ changed = False
+ new_content = []
+ for part in content:
+ part_dict = _part_to_dict(part)
+ media_part = normalize_media_file_part(part_dict)
+ if media_part is not None:
+ new_content.append(media_part)
+ changed = True
+ else:
+ new_content.append(part)
+ if changed:
+ changed_any = True
+ if hasattr(msg, "model_copy"):
+ normalized.append(msg.model_copy(update={"content": new_content}))
+ else:
+ new_msg = dict(msg)
+ new_msg["content"] = new_content
+ normalized.append(new_msg)
+ else:
+ normalized.append(msg)
+
+ return normalized if changed_any else messages
+
+
+def has_audio_video_parts(messages: list[Any]) -> bool:
+ for msg in messages:
+ content = (
+ msg.get("content")
+ if isinstance(msg, dict)
+ else getattr(msg, "content", None)
+ )
+ if not isinstance(content, list):
+ continue
+ for part in content:
+ part_dict = _part_to_dict(part)
+ if part_dict.get("type") in {"input_audio", "input_video", "video"}:
+ return True
+ return False
+
+
+def responses_input_file_to_file_part(part: dict[str, Any]) -> dict[str, Any]:
+ """Convert a Responses ``input_file`` part to Chat-style ``file`` shape."""
+ file_obj = {
+ key: part[key]
+ for key in ("filename", "file_data", "file_id", "file_url", "mime_type")
+ if key in part and part[key] is not None
+ }
+ return {"type": "file", "file": file_obj}
+
+
+def _file_object_from_part(part: dict[str, Any]) -> dict[str, Any] | None:
+ if part.get("type") == "file" and isinstance(part.get("file"), dict):
+ return part["file"]
+ if part.get("type") == "input_file":
+ return responses_input_file_to_file_part(part)["file"]
+ return None
+
+
+def _part_to_dict(part: Any) -> dict[str, Any]:
+ if hasattr(part, "model_dump"):
+ return part.model_dump(exclude_none=True)
+ if hasattr(part, "dict"):
+ return part.dict(exclude_none=True)
+ return part if isinstance(part, dict) else {}
+
+
+def _normalized_mime_type(file_obj: dict[str, Any]) -> str:
+ explicit = str(file_obj.get("mime_type") or "").strip().lower()
+ if explicit:
+ return explicit
+ data = str(file_obj.get("file_data") or file_obj.get("data") or "").strip()
+ if data.startswith("data:"):
+ marker = ";base64,"
+ idx = data.find(marker)
+ if idx >= 0:
+ return data[5:idx].strip().lower()
+ return ""
+
+
+def _file_extension(file_obj: dict[str, Any], mime_type: str) -> str:
+ filename = str(file_obj.get("filename") or "").strip()
+ extension = Path(filename).suffix.lower()
+ if extension:
+ return extension
+ if mime_type.startswith("audio/"):
+ subtype = mime_type.split("/", 1)[1].split(";", 1)[0]
+ return ".mp3" if subtype == "mpeg" else f".{subtype}"
+ if mime_type.startswith("video/"):
+ subtype = mime_type.split("/", 1)[1].split(";", 1)[0]
+ return ".m4v" if subtype == "x-m4v" else f".{subtype}"
+ return ""
+
+
+def _format_from_mime_type(mime_type: str) -> str:
+ if "/" not in mime_type:
+ return ""
+ return mime_type.split("/", 1)[1].split(";", 1)[0]
diff --git a/omlx/api/media_options.py b/omlx/api/media_options.py
new file mode 100644
index 0000000000..af979520fa
--- /dev/null
+++ b/omlx/api/media_options.py
@@ -0,0 +1,43 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Validated request-local multimodal preprocessing controls."""
+
+from typing import Literal
+
+from pydantic import BaseModel, ConfigDict, Field
+
+
+class MultimodalProcessorOptions(BaseModel):
+ """MiniCPM crop controls, separate from chat-template arguments."""
+
+ model_config = ConfigDict(extra="forbid")
+
+ downsample_mode: Literal["4x", "16x"] | None = None
+ max_slice_nums: int | None = Field(default=None, strict=True, ge=1)
+
+
+def merge_mm_processor_kwargs(
+ model_options: dict | None,
+ request_options: MultimodalProcessorOptions | dict | None,
+) -> dict[str, str | int]:
+ model: MultimodalProcessorOptions = MultimodalProcessorOptions.model_validate(
+ model_options or {}
+ )
+ request: MultimodalProcessorOptions = MultimodalProcessorOptions.model_validate(
+ {} if request_options is None else request_options
+ )
+ mode = (
+ request.downsample_mode
+ if request.downsample_mode is not None
+ else model.downsample_mode
+ )
+ slices = (
+ request.max_slice_nums
+ if request.max_slice_nums is not None
+ else model.max_slice_nums
+ )
+ options: dict[str, str | int] = {}
+ if mode is not None:
+ options["downsample_mode"] = mode
+ if slices is not None:
+ options["max_slice_nums"] = slices
+ return options
diff --git a/omlx/api/openai_models.py b/omlx/api/openai_models.py
index 33ff4eb184..1511b3bbe7 100644
--- a/omlx/api/openai_models.py
+++ b/omlx/api/openai_models.py
@@ -11,10 +11,11 @@
"""
import json
-from typing import Annotated, Any, Dict, List, Optional, Union
+from typing import Annotated, Any
from pydantic import AliasChoices, BaseModel, Field, field_validator, model_validator
+from omlx.api.media_options import MultimodalProcessorOptions
from omlx.api.shared_models import (
BaseUsage,
IDPrefix,
@@ -31,7 +32,7 @@ class ImageURL(BaseModel):
"""Base64 data URI for vision model input."""
url: str # "data:image/jpeg;base64,..."
- detail: Optional[str] = "auto" # "low", "high", "auto"
+ detail: str | None = "auto" # "low", "high", "auto"
class InputAudio(BaseModel):
@@ -40,6 +41,35 @@ class InputAudio(BaseModel):
data: str # Base64-encoded audio or data URI
format: str = "wav" # Audio format: wav, mp3, etc.
+ @field_validator("data")
+ @classmethod
+ def validate_data(cls, value: str) -> str:
+ if not value.strip():
+ raise ValueError("data must not be empty")
+ return value
+
+
+class InputVideo(BaseModel):
+ """Video input data for multimodal models (oMLX extension)."""
+
+ data: str # Base64-encoded video or data URI
+ filename: str | None = None
+ mime_type: str | None = None
+ format: str = "mp4"
+
+ @field_validator("data")
+ @classmethod
+ def validate_data(cls, value: str) -> str:
+ if not value.strip():
+ raise ValueError("data must not be empty")
+ return value
+
+
+class InputVideoURL(ImageURL):
+ """MiMo video URL alias, retaining the optional format hint."""
+
+ format: str | None = None
+
class FileContent(BaseModel):
"""File input for attachment preprocessing.
@@ -48,11 +78,12 @@ class FileContent(BaseModel):
``data`` is accepted as an oMLX legacy alias for dashboard clients.
"""
- filename: Optional[str] = None
- mime_type: Optional[str] = None
- file_data: Optional[str] = None
- data: Optional[str] = None
- file_id: Optional[str] = None
+ filename: str | None = None
+ mime_type: str | None = None
+ file_data: str | None = None
+ data: str | None = None
+ file_id: str | None = None
+ file_url: str | None = None
class ContentPart(BaseModel):
@@ -63,17 +94,18 @@ class ContentPart(BaseModel):
- text: Plain text content
- image_url: Image input for vision models
- input_audio: Audio input for multimodal audio models
- - video_url: Video input for supported multimodal models
+ - video_url: MiMo video data URI
+ - input_video: Video input for multimodal video models (oMLX extension)
- file: Document or text input for attachment preprocessing
"""
- type: str # "text", "image_url", "video_url", "input_audio", or "file"
- text: Optional[str] = None
- image_url: Optional[ImageURL] = None
- video_url: Optional[ImageURL] = None
- input_video: Optional[Union[ImageURL, str]] = None
- input_audio: Optional[InputAudio] = None
- file: Optional[FileContent] = None
+ type: str # "text", "image_url", "video_url", "input_audio", "input_video", or "file"
+ text: str | None = None
+ image_url: ImageURL | None = None
+ video_url: ImageURL | None = None
+ input_audio: InputAudio | None = None
+ input_video: InputVideo | InputVideoURL | str | None = None
+ file: FileContent | None = None
# =============================================================================
@@ -93,15 +125,15 @@ class Message(BaseModel):
"""
role: str
- content: Optional[Union[str, List[ContentPart], List[dict]]] = None
+ content: str | list[ContentPart] | list[dict] | None = None
# Reasoning/thinking content from blocks (OpenAI reasoning_content field)
- reasoning_content: Optional[str] = None
+ reasoning_content: str | None = None
# For assistant messages with tool calls
- tool_calls: Optional[List[dict]] = None
+ tool_calls: list[dict] | None = None
# For tool response messages (role="tool")
- tool_call_id: Optional[str] = None
+ tool_call_id: str | None = None
# Participant name, rendered into chat template (e.g. Kimi K2/K2.5 named assistants)
- name: Optional[str] = None
+ name: str | None = None
# Continue from this message instead of starting a new turn (prefill / partial mode)
partial: bool = False
@@ -271,9 +303,9 @@ class ResponseFormatJsonSchema(BaseModel):
"""JSON Schema definition for structured output."""
name: str
- description: Optional[str] = None
+ description: str | None = None
schema_: dict = Field(alias="schema") # JSON Schema specification
- strict: Optional[bool] = False
+ strict: bool | None = False
class Config:
populate_by_name = True
@@ -290,7 +322,7 @@ class ResponseFormat(BaseModel):
"""
type: str = "text" # "text", "json_object", "json_schema"
- json_schema: Optional[ResponseFormatJsonSchema] = None
+ json_schema: ResponseFormatJsonSchema | None = None
class StructuredOutputOptions(BaseModel):
@@ -308,10 +340,10 @@ class StructuredOutputOptions(BaseModel):
model_config = {"populate_by_name": True}
- json_schema: Optional[Union[str, dict]] = Field(None, alias="json")
- regex: Optional[str] = None
- choice: Optional[List[str]] = None
- grammar: Optional[str] = None
+ json_schema: str | dict | None = Field(None, alias="json")
+ regex: str | None = None
+ choice: list[str] | None = None
+ grammar: str | None = None
# =============================================================================
@@ -334,67 +366,68 @@ class ChatCompletionRequest(BaseModel):
"""Request for chat completion."""
model: str
- messages: List[Message]
+ messages: list[Message]
temperature: float | None = None
top_p: float | None = None
top_k: int | None = None
repetition_penalty: float | None = None
- repetition_context_size: Optional[int] = Field(default=None, gt=0)
+ repetition_context_size: int | None = Field(default=None, gt=0)
no_repeat_ngram_size: int | None = Field(default=None, ge=0)
ngram_window: int | None = Field(default=None, ge=0)
# Not in OpenAI's API; vLLM and llama.cpp's server take the same field.
# The model's own stop tokens don't end generation: only max_tokens and the
# request's stop strings do.
ignore_eos: bool = False
- max_tokens: Optional[int] = Field(
+ max_tokens: int | None = Field(
default=None,
gt=0,
validation_alias=AliasChoices("max_tokens", "max_completion_tokens"),
)
stream: bool = False
- stream_options: Optional[StreamOptions] = None
+ stream_options: StreamOptions | None = None
# llama.cpp extension: stream prompt_progress chunks during prefill.
return_progress: bool = False
- stop: Optional[List[str]] = None
+ stop: list[str] | None = None
min_p: float | None = None
xtc_probability: float | None = None
xtc_threshold: float | None = None
presence_penalty: float | None = None
frequency_penalty: float | None = None
# Tool calling
- tools: Optional[List[ToolDefinition]] = None
- tool_choice: Optional[Union[str, dict]] = None # "auto", "none", or specific tool
+ tools: list[ToolDefinition] | None = None
+ tool_choice: str | dict | None = None # "auto", "none", or specific tool
# Structured output
- response_format: Optional[Union[ResponseFormat, dict]] = None
+ response_format: ResponseFormat | dict | None = None
# vLLM-compatible structured output (grammar, regex, choice, json)
- structured_outputs: Optional[Union[StructuredOutputOptions, dict]] = None
+ structured_outputs: StructuredOutputOptions | dict | None = None
# vLLM/OpenAI-compatible grammar alias, normalized to structured_outputs
- guided_grammar: Optional[str] = None
+ guided_grammar: str | None = None
# Chat template kwargs (e.g. enable_thinking, reasoning_effort)
- chat_template_kwargs: Optional[Dict[str, Any]] = None
+ chat_template_kwargs: dict[str, Any] | None = None
+ mm_processor_kwargs: MultimodalProcessorOptions | None = None
# Top-level alias used by OpenAI-compatible clients.
- enable_thinking: Optional[bool] = None
+ enable_thinking: bool | None = None
# OpenAI-compatible reasoning depth; forwarded to the chat template.
# Numbers stay numbers: models like Inkling take a numeric effort
# (0.1-0.99) while Qwen3.8 uses strings ("low".."xhigh") — each chat
# template validates its own vocabulary.
- reasoning_effort: Optional[Union[str, int, float]] = None
+ reasoning_effort: str | int | float | None = None
# Thinking budget (max thinking tokens, None = unlimited)
- thinking_budget: Optional[int] = Field(default=None, ge=0)
+ thinking_budget: int | None = Field(default=None, ge=0)
# System-wide GPU power cap in watts while this request runs. The lower of
# this and the model setting applies.
- gpu_power_limit_w: Optional[int] = Field(default=None, ge=2, le=1000)
+ gpu_power_limit_w: int | None = Field(default=None, ge=2, le=1000)
# SpecPrefill: per-request enable/disable (None = use model setting)
- specprefill: Optional[bool] = None
+ specprefill: bool | None = None
# SpecPrefill: per-request keep percentage (0.1-0.5, None = use model setting)
- specprefill_keep_pct: Optional[float] = None
+ specprefill_keep_pct: float | None = None
# SpecPrefill: per-request threshold override (min tokens to trigger, None = use model setting)
- specprefill_threshold: Optional[int] = None
+ specprefill_threshold: int | None = None
# Seed for reproducible generation (best-effort)
- seed: Optional[int] = None
+ seed: int | None = None
# Per-token log probabilities of the generated tokens
- logprobs: Optional[bool] = None
- top_logprobs: Optional[int] = Field(default=None, ge=0, le=20)
+ logprobs: bool | None = None
+ top_logprobs: int | None = Field(default=None, ge=0, le=20)
@field_validator("stop", mode="before")
@classmethod
@@ -436,9 +469,9 @@ class AssistantMessage(BaseModel):
"""Response message from the assistant."""
role: str = "assistant"
- content: Optional[str] = None
- reasoning_content: Optional[str] = None
- tool_calls: Optional[List[ToolCall]] = None
+ content: str | None = None
+ reasoning_content: str | None = None
+ tool_calls: list[ToolCall] | None = None
class TopLogprob(BaseModel):
@@ -446,19 +479,19 @@ class TopLogprob(BaseModel):
token: str
logprob: float
- bytes: Optional[List[int]] = None
+ bytes: list[int] | None = None
class ChatCompletionTokenLogprob(TopLogprob):
"""Log probability of a generated token and its most likely alternatives."""
- top_logprobs: List[TopLogprob] = Field(default_factory=list)
+ top_logprobs: list[TopLogprob] = Field(default_factory=list)
class ChoiceLogprobs(BaseModel):
"""Log probabilities of the tokens in a choice."""
- content: Optional[List[ChatCompletionTokenLogprob]] = None
+ content: list[ChatCompletionTokenLogprob] | None = None
class ChatCompletionChoice(BaseModel):
@@ -466,15 +499,15 @@ class ChatCompletionChoice(BaseModel):
index: int = 0
message: AssistantMessage
- logprobs: Optional[ChoiceLogprobs] = None
- finish_reason: Optional[str] = "stop"
+ logprobs: ChoiceLogprobs | None = None
+ finish_reason: str | None = "stop"
class PromptTokensDetails(BaseModel):
"""Breakdown of prompt tokens used."""
- cached_tokens: Optional[int] = None
- audio_tokens: Optional[int] = None
+ cached_tokens: int | None = None
+ audio_tokens: int | None = None
class CompletionTokensDetails(BaseModel):
@@ -490,21 +523,21 @@ class Usage(BaseUsage):
When present, timing values are in seconds.
"""
- prompt_tokens_details: Optional[PromptTokensDetails] = None
- completion_tokens_details: Optional[CompletionTokensDetails] = None
+ prompt_tokens_details: PromptTokensDetails | None = None
+ completion_tokens_details: CompletionTokensDetails | None = None
# Timing metrics (oMLX extension, seconds)
- model_load_duration: Optional[float] = None
- time_to_first_token: Optional[float] = None
+ model_load_duration: float | None = None
+ time_to_first_token: float | None = None
# Chat streaming only, measured from stream_chat_completion entry (not HTTP
# endpoint arrival): first nonempty reasoning/content/structured-tool SSE
# delta after all output filters. This may be later than model TTFT for tool
# envelopes; Responses/Completions do not currently populate it.
- time_to_first_visible_token: Optional[float] = None
- total_time: Optional[float] = None
- prompt_eval_duration: Optional[float] = None
- generation_duration: Optional[float] = None
- prompt_tokens_per_second: Optional[float] = None
- generation_tokens_per_second: Optional[float] = None
+ time_to_first_visible_token: float | None = None
+ total_time: float | None = None
+ prompt_eval_duration: float | None = None
+ generation_duration: float | None = None
+ prompt_tokens_per_second: float | None = None
+ generation_tokens_per_second: float | None = None
class ChatCompletionResponse(BaseModel):
@@ -514,7 +547,7 @@ class ChatCompletionResponse(BaseModel):
object: str = "chat.completion"
created: int = Field(default_factory=get_unix_timestamp)
model: str
- choices: List[ChatCompletionChoice]
+ choices: list[ChatCompletionChoice]
usage: Usage = Field(default_factory=Usage)
@@ -527,34 +560,34 @@ class CompletionRequest(BaseModel):
"""Request for text completion."""
model: str
- prompt: Union[str, List[str]]
+ prompt: str | list[str]
temperature: float | None = None
top_p: float | None = None
top_k: int | None = None
repetition_penalty: float | None = None
- repetition_context_size: Optional[int] = Field(default=None, gt=0)
+ repetition_context_size: int | None = Field(default=None, gt=0)
no_repeat_ngram_size: int | None = Field(default=None, ge=0)
ngram_window: int | None = Field(default=None, ge=0)
# Not in OpenAI's API; vLLM and llama.cpp's server take the same field.
# The model's own stop tokens don't end generation: only max_tokens and the
# request's stop strings do.
ignore_eos: bool = False
- max_tokens: Optional[int] = Field(default=None, gt=0)
+ max_tokens: int | None = Field(default=None, gt=0)
stream: bool = False
- stream_options: Optional[StreamOptions] = None
+ stream_options: StreamOptions | None = None
# llama.cpp extension: stream prompt_progress chunks during prefill.
return_progress: bool = False
- stop: Optional[List[str]] = None
+ stop: list[str] | None = None
min_p: float | None = None
xtc_probability: float | None = None
xtc_threshold: float | None = None
presence_penalty: float | None = None
frequency_penalty: float | None = None
# Seed for reproducible generation (best-effort)
- seed: Optional[int] = None
+ seed: int | None = None
# Cap reasoning/thinking tokens (parity with /v1/chat/completions)
- thinking_budget: Optional[int] = Field(default=None, ge=0)
- gpu_power_limit_w: Optional[int] = Field(default=None, ge=2, le=1000)
+ thinking_budget: int | None = Field(default=None, ge=0)
+ gpu_power_limit_w: int | None = Field(default=None, ge=2, le=1000)
@field_validator("stop", mode="before")
@classmethod
@@ -575,7 +608,7 @@ class CompletionChoice(BaseModel):
index: int = 0
text: str
- finish_reason: Optional[str] = "stop"
+ finish_reason: str | None = "stop"
class CompletionResponse(BaseModel):
@@ -585,7 +618,7 @@ class CompletionResponse(BaseModel):
object: str = "text_completion"
created: int = Field(default_factory=get_unix_timestamp)
model: str
- choices: List[CompletionChoice]
+ choices: list[CompletionChoice]
usage: Usage = Field(default_factory=Usage)
@@ -706,7 +739,7 @@ class ModelsResponse(BaseModel):
"""Response for listing models."""
object: str = "list"
- data: List[ModelInfo]
+ data: list[ModelInfo]
# =============================================================================
@@ -726,7 +759,7 @@ class MCPToolInfo(BaseModel):
class MCPToolsResponse(BaseModel):
"""Response for listing MCP tools."""
- tools: List[MCPToolInfo]
+ tools: list[MCPToolInfo]
count: int
@@ -737,13 +770,13 @@ class MCPServerInfo(BaseModel):
state: str
transport: str
tools_count: int
- error: Optional[str] = None
+ error: str | None = None
class MCPServersResponse(BaseModel):
"""Response for listing MCP servers."""
- servers: List[MCPServerInfo]
+ servers: list[MCPServerInfo]
class MCPExecuteRequest(BaseModel):
@@ -759,9 +792,9 @@ class MCPExecuteResponse(BaseModel):
"""Response from executing an MCP tool."""
tool_name: str
- content: Optional[Union[str, list, dict]] = None
+ content: str | list | dict | None = None
is_error: bool = False
- error_message: Optional[str] = None
+ error_message: str | None = None
# =============================================================================
@@ -772,10 +805,10 @@ class MCPExecuteResponse(BaseModel):
class ChatCompletionChunkDelta(BaseModel):
"""Delta content in a streaming chunk."""
- role: Optional[str] = None
- content: Optional[str] = None
- reasoning_content: Optional[str] = None
- tool_calls: Optional[List[dict]] = None
+ role: str | None = None
+ content: str | None = None
+ reasoning_content: str | None = None
+ tool_calls: list[dict] | None = None
class ChatCompletionChunkChoice(BaseModel):
@@ -783,8 +816,8 @@ class ChatCompletionChunkChoice(BaseModel):
index: int = 0
delta: ChatCompletionChunkDelta
- logprobs: Optional[ChoiceLogprobs] = None
- finish_reason: Optional[str] = None
+ logprobs: ChoiceLogprobs | None = None
+ finish_reason: str | None = None
class ChatCompletionChunk(BaseModel):
@@ -794,5 +827,5 @@ class ChatCompletionChunk(BaseModel):
object: str = "chat.completion.chunk"
created: int = Field(default_factory=get_unix_timestamp)
model: str
- choices: List[ChatCompletionChunkChoice]
- usage: Optional[Usage] = None # Present on last chunk when include_usage=true
+ choices: list[ChatCompletionChunkChoice]
+ usage: Usage | None = None # Present on last chunk when include_usage=true
diff --git a/omlx/api/responses_models.py b/omlx/api/responses_models.py
index 69e1c32aa2..74a18ce727 100644
--- a/omlx/api/responses_models.py
+++ b/omlx/api/responses_models.py
@@ -6,6 +6,7 @@
from pydantic import BaseModel, Field, model_serializer, model_validator
+from .media_options import MultimodalProcessorOptions
from .shared_models import IDPrefix, generate_id, get_unix_timestamp
@@ -126,6 +127,7 @@ class ResponsesRequest(BaseModel):
seed: Optional[int] = None
# Chat template kwargs (e.g. enable_thinking, reasoning_effort)
chat_template_kwargs: Optional[Dict[str, Any]] = None
+ mm_processor_kwargs: MultimodalProcessorOptions | None = None
model_config = {"extra": "allow"}
diff --git a/omlx/api/responses_utils.py b/omlx/api/responses_utils.py
index 7b0e7879bb..f9721c5c95 100644
--- a/omlx/api/responses_utils.py
+++ b/omlx/api/responses_utils.py
@@ -7,8 +7,9 @@
import uuid
from collections import OrderedDict
from pathlib import Path
-from typing import Any, Dict, List, Optional, Tuple, Union
+from typing import Any
+from .media_inputs import responses_input_file_to_file_part
from .responses_models import (
InputItem,
InputTokensDetails,
@@ -51,9 +52,9 @@ def _try_parse_json(s: str):
def _extract_tool_output_text(
- output: List[Any],
- image_parts: Optional[List[Dict[str, Any]]],
-) -> Optional[str]:
+ output: list[Any],
+ image_parts: list[dict[str, Any]] | None,
+) -> str | None:
"""Extract text from a multimodal function_call_output list.
Returns None when the list has no recognized content parts so the
@@ -69,7 +70,7 @@ def _extract_tool_output_text(
if not recognized:
return None
- text_parts: List[str] = []
+ text_parts: list[str] = []
for part in output:
if isinstance(part, str):
text_parts.append(part)
@@ -97,8 +98,8 @@ def _extract_tool_output_text(
def _flush_pending_tool_images(
- messages: List[Dict[str, Any]],
- pending_images: List[Dict[str, Any]],
+ messages: list[dict[str, Any]],
+ pending_images: list[dict[str, Any]],
) -> None:
"""Flush tool-output images as a user message after a tool run.
@@ -111,8 +112,8 @@ def _flush_pending_tool_images(
def _flush_pending_tool_calls(
- messages: List[Dict[str, Any]],
- pending: List[Dict[str, Any]],
+ messages: list[dict[str, Any]],
+ pending: list[dict[str, Any]],
min_merge_index: int = 0,
pending_reasoning: str = "",
) -> str:
@@ -140,7 +141,7 @@ def _flush_pending_tool_calls(
if pending_reasoning:
messages[-1]["reasoning_content"] = pending_reasoning
else:
- msg: Dict[str, Any] = {"role": "assistant", "tool_calls": list(pending)}
+ msg: dict[str, Any] = {"role": "assistant", "tool_calls": list(pending)}
if pending_reasoning:
msg["reasoning_content"] = pending_reasoning
messages.append(msg)
@@ -149,11 +150,11 @@ def _flush_pending_tool_calls(
def _consolidate_system_messages(
- messages: List[Dict[str, Any]],
-) -> List[Dict[str, Any]]:
+ messages: list[dict[str, Any]],
+) -> list[dict[str, Any]]:
"""Move all system messages to the front and merge them into one."""
- system_parts: List[str] = []
- non_system: List[Dict[str, Any]] = []
+ system_parts: list[str] = []
+ non_system: list[dict[str, Any]] = []
for msg in messages:
if msg.get("role") == "system":
content = msg.get("content", "")
@@ -168,18 +169,44 @@ def _consolidate_system_messages(
return [{"role": "system", "content": "\n\n".join(system_parts)}] + non_system
+def _normalize_previous_messages(
+ previous_messages: list[dict[str, Any]],
+) -> list[dict[str, Any]]:
+ """Restore template-ready history without mutating caller-owned messages."""
+ normalized = copy.deepcopy(previous_messages)
+ for msg in normalized:
+ if msg.get("partial") is False:
+ msg.pop("partial", None)
+ # Message validation for attachment preprocessing serializes arguments
+ # to OpenAI wire-format JSON strings. Native tool templates (e.g. Qwen)
+ # iterate arguments|items and need the parsed object on replay, both
+ # for the current turn and for previously persisted response state.
+ for call in msg.get("tool_calls") or []:
+ function = call.get("function", {})
+ if "arguments" in function:
+ function["arguments"] = _try_parse_json(function["arguments"])
+ return normalized
+
+
+def normalize_chat_messages_for_response_store(
+ messages: list[dict[str, Any]],
+) -> list[dict[str, Any]]:
+ """Normalize chat messages before persisting Responses conversation state."""
+ return _normalize_previous_messages(messages)
+
+
# =============================================================================
# Input Conversion
# =============================================================================
def convert_responses_input_to_messages(
- input_data: Optional[Union[str, List[InputItem]]],
- instructions: Optional[str] = None,
- previous_messages: Optional[List[Dict[str, Any]]] = None,
+ input_data: str | list[InputItem] | None,
+ instructions: str | None = None,
+ previous_messages: list[dict[str, Any]] | None = None,
consolidate_system_messages: bool = True,
preserve_images: bool = False,
-) -> List[Dict[str, Any]]:
+) -> list[dict[str, Any]]:
"""Convert Responses API input to internal messages format.
Args:
@@ -198,20 +225,20 @@ def convert_responses_input_to_messages(
Returns:
List of message dicts compatible with chat template.
"""
- messages: List[Dict[str, Any]] = []
+ messages: list[dict[str, Any]] = []
# Collect system/developer content to merge into a single system message
# when strict-template compatibility mode is active. In deferred mode,
# top-level instructions still form a leading system message, but input
# system/developer items keep their original position until template
# capability probing decides whether they can be preserved.
- system_parts: List[str] = []
+ system_parts: list[str] = []
if instructions:
system_parts.append(instructions)
# Prepend previous response context
if previous_messages:
- messages.extend(copy.deepcopy(previous_messages))
+ messages.extend(_normalize_previous_messages(previous_messages))
current_message_start = len(messages)
if input_data is None:
@@ -235,12 +262,12 @@ def convert_responses_input_to_messages(
# Process input items
# Track pending tool calls for grouping into a single assistant message
- pending_tool_calls: List[Dict[str, Any]] = []
+ pending_tool_calls: list[dict[str, Any]] = []
# Track reasoning content to attach to the next assistant message
pending_reasoning: str = ""
# Track images extracted from function_call_output lists; flushed as a
# user message once the consecutive tool-output run ends
- pending_tool_images: List[Dict[str, Any]] = []
+ pending_tool_images: list[dict[str, Any]] = []
for item in input_data:
# Resolve effective type: EasyInputMessage has no type field
@@ -272,7 +299,7 @@ def convert_responses_input_to_messages(
# Convert content parts - preserve images for VLM processing
text_parts = []
has_image = False
- converted_parts: List[Dict[str, Any]] = []
+ converted_parts: list[dict[str, Any]] = []
for part in content:
if isinstance(part, dict):
if part.get("type") in ("input_text", "text", "output_text"):
@@ -291,11 +318,36 @@ def convert_responses_input_to_messages(
"detail": detail,
}
)
+ elif part.get("type") == "input_audio":
+ converted_parts.append(
+ {
+ "type": "input_audio",
+ "input_audio": part.get("input_audio", {}),
+ }
+ )
+ elif part.get("type") == "input_file":
+ converted_parts.append(
+ responses_input_file_to_file_part(part)
+ )
+ elif part.get("type") in ("input_video", "video"):
+ converted_parts.append(
+ {
+ "type": "input_video",
+ "input_video": part.get("input_video")
+ or part.get("video", {}),
+ }
+ )
elif isinstance(part, str):
text_parts.append(part)
converted_parts.append({"type": "text", "text": part})
- if has_image and preserve_images:
- # Keep as content list so VLM can extract images
+ has_non_image_structured_part = any(
+ isinstance(p, dict)
+ and p.get("type")
+ not in {"text", "input_text", "output_text", "input_image"}
+ for p in converted_parts
+ )
+ if (has_image and preserve_images) or has_non_image_structured_part:
+ # Keep as content list so media/file preprocessing can run.
content = converted_parts
else:
content = "\n".join(text_parts) if text_parts else ""
@@ -308,7 +360,7 @@ def convert_responses_input_to_messages(
else:
messages.append({"role": "system", "content": content or ""})
else:
- msg_dict: Dict[str, Any] = {"role": role, "content": content or ""}
+ msg_dict: dict[str, Any] = {"role": role, "content": content or ""}
if role == "assistant" and pending_reasoning:
msg_dict["reasoning_content"] = pending_reasoning
pending_reasoning = ""
@@ -416,12 +468,12 @@ def _namespace_wire_name(namespace: str, name: str, taken: set) -> str:
def _convert_function_tool(
- tool: ResponsesTool, name: Optional[str] = None
-) -> Optional[Dict[str, Any]]:
+ tool: ResponsesTool, name: str | None = None
+) -> dict[str, Any] | None:
"""Convert one flat function tool, or None if it is not one."""
if tool.type != "function" or not tool.name:
return None
- func_def: Dict[str, Any] = {"name": name or tool.name}
+ func_def: dict[str, Any] = {"name": name or tool.name}
if tool.description:
func_def["description"] = tool.description
if tool.parameters:
@@ -432,9 +484,9 @@ def _convert_function_tool(
def convert_responses_tools(
- tools: Optional[List[ResponsesTool]],
- aliases: Optional[Dict[str, Tuple[str, str]]] = None,
-) -> Optional[List[Dict[str, Any]]]:
+ tools: list[ResponsesTool] | None,
+ aliases: dict[str, tuple[str, str]] | None = None,
+) -> list[dict[str, Any]] | None:
"""Convert Responses API flat tool format to Chat Completions nested format.
Responses: {"type": "function", "name": "fn", "parameters": {...}}
@@ -479,8 +531,8 @@ def convert_responses_tools(
def split_namespace_tool_name(
name: str,
- aliases: Optional[Dict[str, Tuple[str, str]]] = None,
-) -> Tuple[Optional[str], str]:
+ aliases: dict[str, tuple[str, str]] | None = None,
+) -> tuple[str | None, str]:
"""Restore ``(namespace, name)`` for a call made by wire name.
Flat tools are unaffected: they return ``(None, name)``.
@@ -493,8 +545,8 @@ def split_namespace_tool_name(
def apply_namespace_tool_aliases(
- messages: List[Dict[str, Any]],
- aliases: Dict[str, Tuple[str, str]],
+ messages: list[dict[str, Any]],
+ aliases: dict[str, tuple[str, str]],
) -> None:
"""Map preserved history identities to the current request's tool names."""
wire_names = {identity: wire for wire, identity in aliases.items()}
@@ -516,7 +568,7 @@ def apply_namespace_tool_aliases(
def build_message_output_item(
text: str,
- item_id: Optional[str] = None,
+ item_id: str | None = None,
status: str = "completed",
) -> OutputItem:
"""Build a message-type OutputItem."""
@@ -533,9 +585,9 @@ def build_function_call_output_item(
name: str,
arguments: str,
call_id: str,
- item_id: Optional[str] = None,
+ item_id: str | None = None,
status: str = "completed",
- namespace: Optional[str] = None,
+ namespace: str | None = None,
) -> OutputItem:
"""Build a function_call-type OutputItem."""
return OutputItem(
@@ -551,7 +603,7 @@ def build_function_call_output_item(
def build_reasoning_output_item(
reasoning_text: str,
- item_id: Optional[str] = None,
+ item_id: str | None = None,
status: str = "completed",
) -> OutputItem:
"""Build a reasoning-type OutputItem with full CoT in summary[0].text."""
@@ -618,9 +670,9 @@ class ResponseStore:
def __init__(
self,
max_size: int = MAX_STORED_RESPONSES,
- state_dir: Optional[Union[str, Path]] = None,
+ state_dir: str | Path | None = None,
):
- self._store: OrderedDict[str, Dict[str, Any]] = OrderedDict()
+ self._store: OrderedDict[str, dict[str, Any]] = OrderedDict()
self._max_size = max_size
self._state_dir = Path(state_dir).expanduser().resolve() if state_dir else None
if self._state_dir:
@@ -628,11 +680,11 @@ def __init__(
self._load_persisted_records()
@property
- def state_dir(self) -> Optional[Path]:
+ def state_dir(self) -> Path | None:
"""Resolved directory used for persisted response state."""
return self._state_dir
- def _record_path(self, response_id: str) -> Optional[Path]:
+ def _record_path(self, response_id: str) -> Path | None:
if self._state_dir is None:
return None
return self._state_dir / f"{response_id}.json"
@@ -640,8 +692,8 @@ def _record_path(self, response_id: str) -> Optional[Path]:
def _normalize_record(
self,
response_id: str,
- response_data: Dict[str, Any],
- ) -> Dict[str, Any]:
+ response_data: dict[str, Any],
+ ) -> dict[str, Any]:
if "public_response" in response_data:
record = copy.deepcopy(response_data)
record.setdefault("response_id", response_id)
@@ -674,7 +726,7 @@ def _normalize_record(
"created_at": public_response.get("created_at", 0),
}
- def _persist_record(self, record: Dict[str, Any]) -> None:
+ def _persist_record(self, record: dict[str, Any]) -> None:
path = self._record_path(record["response_id"])
if path is None:
return
@@ -696,7 +748,7 @@ def _evict_oldest(self) -> None:
def _load_persisted_records(self) -> None:
assert self._state_dir is not None
- loaded: List[Dict[str, Any]] = []
+ loaded: list[dict[str, Any]] = []
for path in sorted(self._state_dir.glob("*.json")):
try:
with path.open("r", encoding="utf-8") as f:
@@ -717,7 +769,7 @@ def _load_persisted_records(self) -> None:
self._store[record["response_id"]] = record
self._evict_oldest()
- def put(self, response_id: str, response_data: Dict[str, Any]) -> None:
+ def put(self, response_id: str, response_data: dict[str, Any]) -> None:
"""Store response state, evicting oldest records if needed."""
record = self._normalize_record(response_id, response_data)
if response_id in self._store:
@@ -726,7 +778,7 @@ def put(self, response_id: str, response_data: Dict[str, Any]) -> None:
self._persist_record(record)
self._evict_oldest()
- def get_record(self, response_id: str) -> Optional[Dict[str, Any]]:
+ def get_record(self, response_id: str) -> dict[str, Any] | None:
"""Retrieve a stored response-state record."""
data = self._store.get(response_id)
if data is not None:
@@ -734,21 +786,21 @@ def get_record(self, response_id: str) -> Optional[Dict[str, Any]]:
return copy.deepcopy(data)
return None
- def get(self, response_id: str) -> Optional[Dict[str, Any]]:
+ def get(self, response_id: str) -> dict[str, Any] | None:
"""Retrieve the public response object for a stored record."""
data = self.get_record(response_id)
if data is None:
return None
return data.get("public_response")
- def resolve_chain_messages(self, response_id: str) -> List[Dict[str, Any]]:
+ def resolve_chain_messages(self, response_id: str) -> list[dict[str, Any]]:
"""Resolve the full previous_response_id chain into message history."""
if response_id not in self._store:
raise ResponseStateNotFoundError(f"Response state not found: {response_id}")
- chain: List[Dict[str, Any]] = []
+ chain: list[dict[str, Any]] = []
seen: set[str] = set()
- current_id: Optional[str] = response_id
+ current_id: str | None = response_id
while current_id:
if current_id in seen:
raise ResponseStateCorruptError(
@@ -765,7 +817,7 @@ def resolve_chain_messages(self, response_id: str) -> List[Dict[str, Any]]:
current_id = record.get("previous_response_id")
chain.reverse()
- messages: List[Dict[str, Any]] = []
+ messages: list[dict[str, Any]] = []
for record in chain:
messages.extend(copy.deepcopy(record.get("input_messages", [])))
messages.extend(copy.deepcopy(record.get("output_messages", [])))
@@ -789,8 +841,8 @@ def __len__(self) -> int:
def convert_stored_response_to_messages(
- response_data: Dict[str, Any],
-) -> List[Dict[str, Any]]:
+ response_data: dict[str, Any],
+) -> list[dict[str, Any]]:
"""Convert a stored public response or state record back to messages."""
if "output_messages" in response_data:
return copy.deepcopy(response_data.get("output_messages", []))
@@ -798,11 +850,11 @@ def convert_stored_response_to_messages(
def normalize_response_output_to_messages(
- output_items: List[Dict[str, Any]],
-) -> List[Dict[str, Any]]:
+ output_items: list[dict[str, Any]],
+) -> list[dict[str, Any]]:
"""Convert response output items to assistant/tool-call history messages."""
- messages: List[Dict[str, Any]] = []
- pending_tool_calls: List[Dict[str, Any]] = []
+ messages: list[dict[str, Any]] = []
+ pending_tool_calls: list[dict[str, Any]] = []
pending_reasoning: str = ""
for item in output_items:
@@ -822,7 +874,7 @@ def normalize_response_output_to_messages(
for block in content_blocks:
if block.get("type") == "output_text":
text_parts.append(block.get("text", ""))
- msg_dict: Dict[str, Any] = {
+ msg_dict: dict[str, Any] = {
"role": item.get("role", "assistant"),
"content": "\n".join(text_parts),
}
@@ -854,10 +906,10 @@ def normalize_response_output_to_messages(
def build_response_store_record(
- public_response: Dict[str, Any],
- input_messages: List[Dict[str, Any]],
- output_messages: List[Dict[str, Any]],
-) -> Dict[str, Any]:
+ public_response: dict[str, Any],
+ input_messages: list[dict[str, Any]],
+ output_messages: list[dict[str, Any]],
+) -> dict[str, Any]:
"""Build a persisted response-state record."""
return {
"response_id": public_response.get("id", ""),
diff --git a/omlx/api/utils.py b/omlx/api/utils.py
index 51fc3cab47..5d95453e75 100644
--- a/omlx/api/utils.py
+++ b/omlx/api/utils.py
@@ -6,7 +6,7 @@
import json
import re
-from typing import Any, List
+from typing import Any
from .openai_models import Message
from .thinking import extract_thinking
@@ -222,7 +222,7 @@ def _extract_text_from_content_list(content: list) -> str:
for item in content:
# Convert Pydantic models to dict
if hasattr(item, "model_dump"):
- item = item.model_dump()
+ item = item.model_dump(exclude_none=True)
elif hasattr(item, "dict"):
item = item.dict()
@@ -237,15 +237,15 @@ 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.
+ """Extract text, image, audio, and video parts from a content array.
- Keeps text, image_url, and input_audio items for VLM processing.
+ Keeps text, image_url, input_audio, and input_video items for VLM processing.
Other content types (tool_use, thinking, refusal, etc.) are dropped.
"""
parts = []
for item in content:
if hasattr(item, "model_dump"):
- item = item.model_dump()
+ item = item.model_dump(exclude_none=True)
elif hasattr(item, "dict"):
item = item.dict()
if isinstance(item, dict):
@@ -320,6 +320,24 @@ def _extract_multimodal_content_list(content: list) -> list:
"video_url": {"url": url},
}
)
+ elif item_type == "input_video" and isinstance(video_url_value, dict):
+ parts.append(
+ {"type": "input_video", "input_video": video_url_value}
+ )
+ elif item_type in ("input_video", "video"):
+ # oMLX extension: pass through for engine-side video loading
+ input_video = item.get("input_video") or item.get("video")
+ if input_video is None and item_type == "video":
+ input_video = item
+ if isinstance(input_video, dict) or (
+ isinstance(input_video, str) and input_video.strip()
+ ):
+ parts.append(
+ {
+ "type": "input_video",
+ "input_video": input_video,
+ }
+ )
return parts
@@ -1067,12 +1085,12 @@ def _apply_reasoning_reconstruction(
def extract_text_content(
- messages: List[Message],
+ messages: list[Message],
max_tool_result_tokens: int | None = None,
tokenizer: Any | None = None,
native_reasoning_content: bool = False,
consolidate_system_messages: bool = True,
-) -> List[dict]:
+) -> list[dict]:
"""
Extract text content from OpenAI-format messages.
@@ -1255,12 +1273,12 @@ def extract_text_content(
def extract_multimodal_content(
- messages: List[Message],
+ messages: list[Message],
max_tool_result_tokens: int | None = None,
tokenizer: Any | None = None,
native_reasoning_content: bool = False,
consolidate_system_messages: bool = True,
-) -> List[dict]:
+) -> list[dict]:
"""
Extract content from messages, preserving image_url parts for VLM.
@@ -1406,9 +1424,9 @@ def extract_multimodal_content(
if isinstance(content, str):
processed_messages.append({"role": role, "content": content, **_extra})
elif isinstance(content, list):
- # Preserve image, video, and audio parts for VLM processing.
+ # Preserve image, audio, and video parts for VLM processing.
multimodal_parts = _extract_multimodal_content_list(content)
- multimodal_types = {"image_url", "video_url", "input_audio"}
+ multimodal_types = {"image_url", "video_url", "input_audio", "input_video"}
has_multimodal = any(
p.get("type") in multimodal_types for p in multimodal_parts
)
@@ -1528,7 +1546,7 @@ def extract_harmony_messages(
max_tool_result_tokens: int | None = None,
tokenizer: Any | None = None,
consolidate_system_messages: bool = True,
-) -> List[dict]:
+) -> list[dict]:
"""
Extract messages for Harmony (gpt-oss) models.
diff --git a/omlx/engine/tts.py b/omlx/engine/tts.py
index 10a7def0b9..d85c2ec0d4 100644
--- a/omlx/engine/tts.py
+++ b/omlx/engine/tts.py
@@ -227,6 +227,9 @@ async def start(self) -> None:
model_name = self._model_name
def _load_sync():
+ from ..patches.mlx_audio_compat import ensure_english_kokoro_g2p
+
+ ensure_english_kokoro_g2p()
try:
return _load_model(model_name, strict=True)
except ValueError as exc:
diff --git a/omlx/engine/vlm.py b/omlx/engine/vlm.py
index 6b003be89a..3f84f1274f 100644
--- a/omlx/engine/vlm.py
+++ b/omlx/engine/vlm.py
@@ -34,13 +34,15 @@
import json
import logging
import threading
+import time
from collections.abc import AsyncIterator
from pathlib import Path
-from typing import Any, Dict, List, Optional, Tuple
+from typing import Any
import mlx.core as mx
import numpy as np
+from ..api.media_options import merge_mm_processor_kwargs
from ..api.tool_calling import convert_tools_for_template
from ..api.utils import (
clean_special_tokens,
@@ -49,8 +51,10 @@
)
from ..cache.paged_ssd_cache import numerics_revision_for_model
from ..cache.vision_feature_cache import VisionFeatureSSDCache
-from ..exceptions import InvalidRequestError
+from ..exceptions import InvalidRequestError, ModelUnavailableError
from ..lora_adapters import apply_adapter
+from ..model_classification import is_nemotron_omni
+from ..model_discovery import model_unavailable_reason
from ..model_settings import (
a8_prefill_on,
ane_prefill_backend,
@@ -70,13 +74,15 @@
from ..prefill_helper.manager import PrefillHelperManager
from ..reasoning_effort import apply_chat_template_with_reasoning_effort_fallback
from ..speculative.dflash import attach_drafter, detach_drafter
+from ..utils.generation_config import load_generation_config_token_ids
from ..utils.image import (
+ compute_audio_video_hash,
compute_per_image_hashes,
- extract_images_from_messages,
extract_media_from_messages,
image_hash_prefixes,
)
from ..utils.video import (
+ NATIVE_VIDEO_MAX_FRAMES,
NATIVE_VIDEO_MODEL_TYPES,
attach_native_video_processor,
estimate_native_video_tokens,
@@ -140,11 +146,12 @@ def realtime_voice_capabilities(config: dict) -> dict:
"dots_ocr",
"glm_ocr",
}
+_DEEPSEEK_V4_EOS_TOKEN_IDS = {1, 128803, 128804}
# OCR model types and their default markdown conversion prompts.
# When an OCR model receives a generic user prompt with an image,
# the prompt is automatically adjusted for markdown output.
-OCR_MODEL_PROMPTS: Dict[str, str] = {
+OCR_MODEL_PROMPTS: dict[str, str] = {
"deepseekocr": "Convert the document to markdown.",
"deepseekocr_2": "Convert the document to markdown.",
# baidu/Unlimited-OCR upstream-documented single-page baseline. Multi-page
@@ -159,7 +166,7 @@ def realtime_voice_capabilities(config: dict) -> dict:
# Extra stop sequences for OCR models to prevent degeneration.
# Many OCR models lack proper EOS handling and generate chat-turn
# tokens (<|user|>, <|im_start|>, etc.) indefinitely after the OCR output.
-OCR_EXTRA_STOP_SEQUENCES: List[str] = [
+OCR_EXTRA_STOP_SEQUENCES: list[str] = [
"<|user|>",
"<|im_start|>",
"<|im_end|>",
@@ -179,9 +186,76 @@ def realtime_voice_capabilities(config: dict) -> dict:
DIFFUSION_PREFILL_STEP_SIZE = 2048
+
+def _warmup_bailing_moe_v3_vl(model: Any, token_id: int = 0) -> bool:
+ """Compile Ling VL's KDA prefill and decode graphs before serving."""
+ if getattr(model, "model_type", None) != "bailing_moe_v3_vl":
+ return False
+
+ cache = model.make_cache()
+ prefill = model(mx.full((1, 8), token_id, dtype=mx.int32), cache=cache)
+ mx.eval(prefill)
+ decode = model(mx.array([[token_id]], dtype=mx.int32), cache=cache)
+ mx.eval(decode)
+ return True
+
+
+def _report_native_vlm_mtp_readiness(
+ model_name: str,
+ adapter: Any,
+ *,
+ has_mtp_weights: bool,
+) -> bool:
+ """Log and return whether a loaded VLM can enter native-head MTP decode."""
+ language_model = getattr(adapter, "_language_model", None)
+ get_mtp_module = getattr(language_model, "get_mtp_module", None)
+ mtp_head = (
+ get_mtp_module()
+ if callable(get_mtp_module)
+ else getattr(language_model, "mtp", None)
+ )
+ if getattr(adapter, "_omlx_native_mtp_full_prompt", False):
+ mtp_head = adapter.mtp
+ has_mtp_head = mtp_head is not None
+ decode_enabled = bool(
+ getattr(language_model, "_omlx_mtp_decode_enabled", False)
+ or getattr(adapter, "_omlx_mtp_decode_enabled", False)
+ )
+ adapter_ready = callable(getattr(adapter, "mtp_forward", None))
+ ready = bool(
+ has_mtp_weights and has_mtp_head and decode_enabled and adapter_ready
+ )
+ if ready:
+ if getattr(adapter, "_omlx_native_mtp_full_prompt", False):
+ logger.info(
+ "Native Nemotron MTP ready for %s (media-conditioned prompt history; "
+ "uniform batched draft+verify)",
+ model_name,
+ )
+ return True
+ logger.info(
+ "Native VLM MTP ready for %s (loaded native head; text-only "
+ "requests use mlx-lm BatchGenerator draft+verify; vision requests "
+ "use standard decode)",
+ model_name,
+ )
+ else:
+ logger.warning(
+ "Native VLM MTP requested for %s but readiness gate failed "
+ "(weights=%s, head=%s, decode_flag=%s, adapter=%s); standard "
+ "decode remains active",
+ model_name,
+ has_mtp_weights,
+ has_mtp_head,
+ decode_enabled,
+ adapter_ready,
+ )
+ return ready
+
+
# Per-model OCR generation defaults from official configs.
# Applied automatically when no explicit user override is provided.
-OCR_MODEL_GENERATION_DEFAULTS: Dict[str, Dict[str, Any]] = {
+OCR_MODEL_GENERATION_DEFAULTS: dict[str, dict[str, Any]] = {
"glm_ocr": {
"temperature": 0.0,
"repetition_penalty": 1.1,
@@ -215,6 +289,8 @@ def _read_config_model_type(model_path: str | Path) -> str | None:
except Exception:
return None
model_type = data.get("model_type")
+ if is_nemotron_omni(model_type):
+ return model_type.lower()
return model_type if isinstance(model_type, str) else None
@@ -279,6 +355,47 @@ def _apply_minimax_m3_thinking_mode(
template_kwargs["thinking_mode"] = "disabled"
+def _iter_token_ids(value: Any):
+ if value is None or isinstance(value, bool):
+ return
+ if isinstance(value, int):
+ yield value
+ return
+ if isinstance(value, (list, tuple, set)):
+ for item in value:
+ if isinstance(item, int) and not isinstance(item, bool):
+ yield item
+
+
+def _resolve_vlm_eos_token_ids(
+ model_path: Path,
+ eos_token_id: Any,
+) -> list[int] | int | None:
+ merged: list[int] = []
+ seen: set[int] = set()
+ preserve_sequence = isinstance(eos_token_id, (list, tuple, set)) and not isinstance(
+ eos_token_id,
+ (str, bytes, bytearray),
+ )
+
+ def add(value: Any) -> None:
+ for token_id in _iter_token_ids(value) or ():
+ if token_id not in seen:
+ seen.add(token_id)
+ merged.append(token_id)
+
+ add(eos_token_id)
+ generation_eos = load_generation_config_token_ids(model_path, "eos_token_id")
+ if generation_eos:
+ add(sorted(generation_eos))
+ if _read_config_model_type(model_path) == "deepseek_v4":
+ add(sorted(_DEEPSEEK_V4_EOS_TOKEN_IDS))
+
+ if not merged:
+ return None
+ return merged if preserve_sequence or len(merged) > 1 else merged[0]
+
+
def _attach_vlm_tokenizer_runtime(tokenizer: Any, model_path: Path, eos_token_id: Any):
from mlx_vlm.tokenizer_utils import load_tokenizer
from mlx_vlm.utils import StoppingCriteria
@@ -289,10 +406,11 @@ def _attach_vlm_tokenizer_runtime(tokenizer: Any, model_path: Path, eos_token_id
detokenizer_class = load_tokenizer(model_path, return_tokenizer=False)
tokenizer.detokenizer = detokenizer_class(tokenizer)
- final_eos_token_ids = (
+ final_eos_token_ids = _resolve_vlm_eos_token_ids(
+ model_path,
eos_token_id
or getattr(tokenizer, "eos_token_ids", None)
- or getattr(tokenizer, "eos_token_id", None)
+ or getattr(tokenizer, "eos_token_id", None),
)
tokenizer.stopping_criteria = StoppingCriteria(final_eos_token_ids, tokenizer)
return tokenizer
@@ -315,7 +433,10 @@ def _load_cohere2_moe_text_model(
trust_remote_code=trust_remote_code,
)
- eos_token_id = getattr(getattr(model, "config", None), "eos_token_id", None)
+ eos_token_id = _resolve_vlm_eos_token_ids(
+ model_path,
+ getattr(getattr(model, "config", None), "eos_token_id", None),
+ )
try:
processor = load_processor(
model_path,
@@ -1227,12 +1348,26 @@ def _force_qwen4_exp_sanitize_on_load(model_dir: Path):
yield
return
+ import mlx_vlm.utils as _vu
import safetensors
from ..patches.mlx_vlm_qwen4_exp_compat.ple_load_resources import ple_load_resources
original_safe_open = safetensors.safe_open
+ original_load_safetensors = _vu._load_safetensors
+ target_dir = model_dir.resolve()
is_target_shard = _model_shard_matcher(model_dir)
+ mtp_sidecar = None
+ mtp_loaded = False
+ if model_type == "qwen4_exp" and (model_dir / "mtp" / "config.json").is_file():
+ from ..utils.model_loading import _qwen4_mtp_sidecar_path
+
+ candidate_sidecar = _qwen4_mtp_sidecar_path(model_dir)
+ if candidate_sidecar is not None:
+ from mlx_vlm.models.qwen4_exp.language import get_mtp_runtime
+
+ if get_mtp_runtime().checkpoint_prefix == "mtp/":
+ mtp_sidecar = candidate_sidecar
class _SafeOpenMetadataWrapper:
def __init__(self, inner):
@@ -1261,7 +1396,32 @@ def _patched_safe_open(filename, *args, **kwargs):
return _SafeOpenMetadataWrapper(handle)
return handle
+ def _patched_load_safetensors(path):
+ nonlocal mtp_loaded
+ weights = original_load_safetensors(path)
+ if mtp_sidecar is None or mtp_loaded:
+ return weights
+ try:
+ loaded_path = Path(path).resolve()
+ except TypeError:
+ return weights
+ if loaded_path.parent != target_dir:
+ return weights
+
+ sidecar_weights = {}
+ for sidecar_file in sorted(mtp_sidecar.glob("*.safetensors")):
+ sidecar_weights.update(original_load_safetensors(str(sidecar_file)))
+ weights.update({f"mtp.{key}": value for key, value in sidecar_weights.items()})
+ mtp_loaded = True
+ logger.info(
+ "Loaded %d Qwen4-Exp Lightning MTP tensors from %s",
+ len(sidecar_weights),
+ mtp_sidecar,
+ )
+ return weights
+
safetensors.safe_open = _patched_safe_open
+ _vu._load_safetensors = _patched_load_safetensors
try:
logger.info(
"%s pre-quantization sanitize active for %s",
@@ -1272,6 +1432,7 @@ def _patched_safe_open(filename, *args, **kwargs):
yield
finally:
safetensors.safe_open = original_safe_open
+ _vu._load_safetensors = original_load_safetensors
@contextlib.contextmanager
@@ -1384,7 +1545,7 @@ def _uses_mrope(vlm_model) -> bool:
}
-def _grid_row(image_grid_thw: Any, i: int) -> Optional[List[int]]:
+def _grid_row(image_grid_thw: Any, i: int) -> list[int] | None:
"""Row ``i`` of an ``image_grid_thw`` tensor as ``[t, h, w]``, or None."""
try:
row = [int(v) for v in image_grid_thw[i]]
@@ -1500,8 +1661,12 @@ def _count_image_tokens(
def _smart_resize_tokens(
- h: int, w: int, patch_size: int, merge_size: int,
- min_pixels: int, max_pixels: int,
+ h: int,
+ w: int,
+ patch_size: int,
+ merge_size: int,
+ min_pixels: int,
+ max_pixels: int,
) -> int:
"""Real merged-token count for one image of pixel size (h, w), mirroring
the Qwen image processor's ``smart_resize`` -> grid_thw ->
@@ -1523,10 +1688,10 @@ def _smart_resize_tokens(
beta = math.sqrt(min_pixels / (h * w))
h_bar = math.ceil(h * beta / factor) * factor
w_bar = math.ceil(w * beta / factor) * factor
- return (h_bar // patch_size) * (w_bar // patch_size) // (merge_size ** 2)
+ return (h_bar // patch_size) * (w_bar // patch_size) // (merge_size**2)
-def _read_image_dims(part: dict) -> Optional[tuple]:
+def _read_image_dims(part: dict) -> tuple | None:
"""Best-effort, decode-free ``(width, height)`` for an OpenAI image part.
Handles only ``data:`` base64 URIs. Returns ``None`` for anything else so
@@ -2014,6 +2179,12 @@ async def start(self) -> None:
if self._loaded:
return
+ unavailable_reason = model_unavailable_reason(
+ _read_config_model_type(self._model_name)
+ )
+ if unavailable_reason is not None:
+ raise ModelUnavailableError(self._model_name, unavailable_reason)
+
from mlx_vlm.utils import load as vlm_load
from ..engine_core import AsyncEngineCore, EngineConfig
@@ -2034,6 +2205,8 @@ async def start(self) -> None:
except ValueError:
raise
except Exception as e:
+ if _read_config_model_type(self._model_name) == "minicpmv4_7":
+ raise
logger.debug(f"pre-load patches skipped: {e}")
# Load VLM model on the global MLX executor to avoid blocking the event loop
@@ -2161,6 +2334,11 @@ def _load_vlm_sync():
self._native_video = attach_native_video_processor(
self._processor, self._model_name
)
+ elif self.model_type == "minicpmv4_7" or is_nemotron_omni(self.model_type):
+ self._native_video = (
+ getattr(self._processor, "video_processor", None) is not None
+ )
+ self._vision_cache_enabled = False
if self.model_type == "unlimited-ocr":
from ..utils.tokenizer import (
@@ -2526,6 +2704,62 @@ def _enable_ane_prefill():
# mlx-vlm models now handle per-sequence mx.array offsets natively
# and batched decode is fixed, so no separate mlx-lm decode model needed.
self._adapter = VLMModelAdapter(self._vlm_model)
+ if is_nemotron_omni(self.model_type) and getattr(
+ self._model_settings, "mtp_enabled", False
+ ):
+ from mlx_vlm.speculative.drafters.nemotron_h_mtp.split import (
+ NemotronHMTPSplitter,
+ )
+
+ from ..patches.mlx_lm_mtp import get_mtp_depth
+ from ..utils.model_loading import _checkpoint_has_mtp_weights
+
+ if _checkpoint_has_mtp_weights(self._model_name):
+ from ..patches.nemotron_omni_quantization import native_mtp_sidecar
+
+ source_config = json.loads(
+ (Path(self._model_name) / "config.json").read_text()
+ )
+ sidecar = native_mtp_sidecar(self._model_name, source_config)
+ if sidecar is not None:
+ from mlx_vlm.utils import load_model
+
+ head = await loop.run_in_executor(
+ get_mlx_executor(), load_model, sidecar
+ )
+ else:
+ head = await loop.run_in_executor(
+ get_mlx_executor(),
+ NemotronHMTPSplitter().load,
+ Path(self._model_name),
+ )
+ self._adapter.enable_nemotron_mtp(head, depth=get_mtp_depth())
+
+ warmup_started = time.perf_counter()
+ warmed_up = await loop.run_in_executor(
+ get_mlx_executor(),
+ _warmup_bailing_moe_v3_vl,
+ self._adapter,
+ getattr(self._tokenizer, "bos_token_id", None) or 0,
+ )
+ if warmed_up:
+ logger.info(
+ "Ling VL inference warmup completed in %.2fs",
+ time.perf_counter() - warmup_started,
+ )
+
+ # Native-head MTP uses this same adapter and mlx-lm BatchGenerator;
+ # it is distinct from the external ``vlm_mtp`` assistant drafter.
+ # Report readiness only after strict loading has proven that the head
+ # actually bound to the VLM language model.
+ if getattr(self._model_settings, "mtp_enabled", False):
+ from ..utils.model_loading import _checkpoint_has_mtp_weights
+
+ _report_native_vlm_mtp_readiness(
+ self._model_name,
+ self._adapter,
+ has_mtp_weights=_checkpoint_has_mtp_weights(self._model_name),
+ )
# Create scheduler config
scheduler_config = (
@@ -2634,6 +2868,15 @@ def _enable_ane_prefill():
# Qwen3.5/3.6 verify-width GDN prework -> one fused Metal launch
# (conv+SiLU+split+RMS+scale+conv-state), bit-exact to the chain.
+ try:
+ from ..patches.qwen35_gdn_decode import (
+ apply_qwen35_gdn_decode_patch,
+ )
+
+ apply_qwen35_gdn_decode_patch()
+ except Exception:
+ logger.debug("Qwen fused GDN decode patch not applied", exc_info=True)
+
try:
from ..patches.qwen35_gdn_prework import (
apply_qwen35_gdn_prework_patch,
@@ -2848,6 +3091,13 @@ def _enable_ane_prefill():
apply_qwen35_padded_row_attention_patch()
except Exception:
logger.debug("qwen3_5 padded-row attention patch not applied", exc_info=True)
+
+ try:
+ from ..patches.qwen35_compiled_mlp import CompiledMLPBlocks
+
+ CompiledMLPBlocks.install(self._vlm_model)
+ except Exception:
+ logger.debug("Qwen compiled MLP dispatch not installed", exc_info=True)
scheduler.refresh_ssd_layer_signature()
# SpecPrefill: load draft model and pass to scheduler
@@ -2975,7 +3225,9 @@ def prepare_dflash_target(self) -> Any:
layer captures and rollback here, before the drafter binds.
"""
language_model = self._vlm_model.language_model
- if not hasattr(language_model, "rollback_speculative_cache"):
+ if self.model_type != "minicpmv4_7" and not hasattr(
+ language_model, "rollback_speculative_cache"
+ ):
drafter_target.apply(language_model)
return self._vlm_model
@@ -3064,12 +3316,11 @@ async def stop(self) -> None:
false_attrs=("_grammar_compiler_init_attempted",),
)
- if engine:
- if hasattr(engine, "engine") and engine.engine is not None:
- try:
- cancelled = await _close_engine_core(engine.engine)
- except Exception as e:
- logger.warning(f"Error closing engine: {e}")
+ if engine and hasattr(engine, "engine") and engine.engine is not None:
+ try:
+ cancelled = await _close_engine_core(engine.engine)
+ except Exception as e:
+ logger.warning(f"Error closing engine: {e}")
self._diffusion_cancel_events = set()
self._diffusion_active_requests = 0
self._speech_active = 0
@@ -3257,6 +3508,59 @@ def _format_messages_for_vlm_template(
if not model_type:
raise ValueError("Missing VLM model_type for chat template formatting")
+ if is_nemotron_omni(model_type):
+ formatted_messages = []
+ media_counts = {"image": 0, "audio": 0, "video": 0}
+ for message in messages:
+ formatted = dict(message)
+ content = message.get("content")
+ if isinstance(content, list):
+ parts = []
+ for part in content:
+ kind = part.get("type")
+ if kind in {"image", "image_url", "input_image"}:
+ parts.append({"type": "image"})
+ elif kind in {"video", "video_url", "input_video"}:
+ parts.append({"type": "video"})
+ elif kind in {"audio", "input_audio"}:
+ parts.append({"type": "audio"})
+ elif kind == "text":
+ parts.append({"type": "text", "text": part.get("text", "")})
+ else:
+ raise InvalidRequestError(
+ f"Unsupported Nemotron content type: {kind!r}.",
+ field="messages",
+ )
+ if parts[-1]["type"] in media_counts:
+ media_counts[parts[-1]["type"]] += 1
+ formatted["content"] = parts
+ formatted_messages.append(formatted)
+ missing = []
+ for kind, expected in (
+ ("image", num_images), ("audio", num_audios), ("video", num_videos)
+ ):
+ if media_counts[kind] not in (0, expected):
+ raise InvalidRequestError(
+ f"Nemotron {kind} placeholders do not match the supplied media.",
+ field="messages",
+ )
+ if not media_counts[kind]:
+ missing.extend({"type": kind} for _ in range(expected))
+ if missing:
+ for formatted in reversed(formatted_messages):
+ if formatted.get("role") != "user":
+ continue
+ content = formatted.get("content", "")
+ if isinstance(content, str):
+ content = [{"type": "text", "text": content}]
+ formatted["content"] = missing + content
+ break
+ else:
+ raise InvalidRequestError(
+ "Nemotron media requires a user message.", field="messages"
+ )
+ return formatted_messages, []
+
if model_type == "deepseek_v41":
if num_audios:
raise ValueError("DeepSeek V4.1 supports text and images, not audio")
@@ -3264,6 +3568,55 @@ def _format_messages_for_vlm_template(
return format_messages(messages, num_images)
+ if model_type == "minicpmv4_7":
+ formatted_messages = []
+ explicit_visuals = False
+ for message in messages:
+ formatted = dict(message)
+ content = formatted.get("content")
+ if isinstance(content, list):
+ parts = []
+ for part in content:
+ kind = part.get("type")
+ if kind in {"image", "image_url", "input_image"}:
+ parts.append({"type": "image"})
+ explicit_visuals = True
+ elif kind in {"video", "video_url", "input_video"}:
+ parts.append({"type": "video"})
+ explicit_visuals = True
+ elif kind == "text":
+ parts.append({"type": "text", "text": part.get("text", "")})
+ else:
+ raise InvalidRequestError(
+ f"Unsupported MiniCPM content type: {kind!r}.",
+ field="messages",
+ )
+ if formatted.get("role") == "system" and any(
+ part["type"] != "text" for part in parts
+ ):
+ raise InvalidRequestError(
+ "MiniCPM system messages cannot contain images or videos.",
+ field="messages",
+ )
+ formatted["content"] = parts
+ formatted_messages.append(formatted)
+ if not explicit_visuals and (num_images or num_videos):
+ for formatted in formatted_messages:
+ if formatted.get("role") == "user":
+ content = formatted.get("content")
+ text_parts = (
+ content
+ if isinstance(content, list)
+ else [{"type": "text", "text": content or ""}]
+ )
+ formatted["content"] = [
+ *({"type": "image"} for _ in range(num_images)),
+ *({"type": "video"} for _ in range(num_videos)),
+ *text_parts,
+ ]
+ break
+ return formatted_messages, []
+
image_part_types = {"image", "image_url", "input_image"}
audio_part_types = {"input_audio"}
video_part_types = {"video", "video_url", "input_video"}
@@ -3546,9 +3899,10 @@ def _format_messages_for_vlm_template(
return formatted_messages, image_message_ranges
+
def _compute_vision_features(
self, pixel_values: Any, extra_model_inputs: dict
- ) -> Optional[mx.array]:
+ ) -> mx.array | None:
"""Compute vision features for caching.
Tries multiple strategies based on model architecture:
@@ -3625,7 +3979,10 @@ def _compute_vision_features(
inspect.Parameter.POSITIONAL_OR_KEYWORD,
)
]
- if image_position_ids is not None and len(positional_parameters) >= 2:
+ if (
+ image_position_ids is not None
+ and len(positional_parameters) >= 2
+ ):
return model.encode_image(pixel_values, image_position_ids)
return model.encode_image(pixel_values)
@@ -3680,10 +4037,10 @@ def _encode_missing_vision_features(
self,
pixel_values: Any,
extra_model_inputs: dict,
- cached_per_image: List[Any],
- per_hashes: List[str],
- image_token_count: Optional[int],
- ) -> Optional[mx.array]:
+ cached_per_image: list[Any],
+ per_hashes: list[str],
+ image_token_count: int | None,
+ ) -> mx.array | None:
"""Encode only uncached images and combine with cached ones in order.
Qwen-style towers attend within each image, so a subset encodes
@@ -3770,8 +4127,8 @@ def _encode_missing_vision_features(
def _try_build_cached_vision_inputs(
self,
prompt: str,
- images: List[Any],
- ) -> Optional[Dict[str, Any]]:
+ images: list[Any],
+ ) -> dict[str, Any] | None:
"""Build ``prepare_inputs``-style inputs, preprocessing only cache misses.
Splits the prompt on the vision marker, tokenizes the text chunks, and
@@ -3817,8 +4174,8 @@ def _try_build_cached_vision_inputs(
return None
per_hashes = compute_per_image_hashes(images)
- feats: List[Optional[mx.array]] = []
- grids: List[Optional[List[int]]] = []
+ feats: list[mx.array | None] = []
+ grids: list[list[int] | None] = []
for h in per_hashes:
feat = self._vision_cache.get(h, self._model_name)
grid = self._vision_cache.get_grid(h, self._model_name)
@@ -3877,7 +4234,7 @@ def _try_build_cached_vision_inputs(
grid=miss_grids[k],
)
- token_ids: List[int] = []
+ token_ids: list[int] = []
chunks = prompt.split(marker)
for k, chunk in enumerate(chunks):
if chunk:
@@ -3921,7 +4278,7 @@ def _split_vision_features(
features: mx.array,
num_images: int,
extra_model_inputs: dict,
- ) -> Optional[List[mx.array]]:
+ ) -> list[mx.array] | None:
"""Split batched vision features into per-image tensors for caching.
Returns a list of per-image feature tensors, or None if the model
@@ -4007,7 +4364,7 @@ def _split_vision_features(
return None
@staticmethod
- def _as_int_list(value: Any) -> Optional[List[int]]:
+ def _as_int_list(value: Any) -> list[int] | None:
if value is None:
return None
if hasattr(value, "tolist"):
@@ -4017,7 +4374,7 @@ def _as_int_list(value: Any) -> Optional[List[int]]:
if not isinstance(value, (list, tuple)):
return None
- result: List[int] = []
+ result: list[int] = []
for item in value:
if hasattr(item, "tolist"):
item = item.tolist()
@@ -4032,7 +4389,7 @@ def _as_int_list(value: Any) -> Optional[List[int]]:
return result
@staticmethod
- def _vision_feature_token_count(features: Any) -> Optional[int]:
+ def _vision_feature_token_count(features: Any) -> int | None:
if isinstance(features, (list, tuple)):
total = 0
for feature in features:
@@ -4055,7 +4412,7 @@ def _vision_feature_token_count(features: Any) -> Optional[int]:
def _image_token_count(
self, input_ids: Any, token_id_attr: str = "image_token_id"
- ) -> Optional[int]:
+ ) -> int | None:
config = getattr(self._vlm_model, "config", None)
image_token_id = getattr(config, token_id_attr, None)
if image_token_id is None:
@@ -4068,6 +4425,7 @@ def _image_token_count(
logger.debug("Failed to count VLM image tokens", exc_info=True)
return None
+
def _cached_video_features(
self, video_identity: str, input_ids: Any, extra_model_inputs: dict
) -> mx.array | None:
@@ -4105,7 +4463,7 @@ def _cached_video_features(
return features
def _vision_features_match_image_tokens(
- self, features: Any, image_token_count: Optional[int]
+ self, features: Any, image_token_count: int | None
) -> bool:
if image_token_count is None:
return True
@@ -4133,6 +4491,22 @@ def _language_prompt_kwargs(extra_model_inputs: dict[str, Any]) -> dict[str, Any
if extra_model_inputs.get(key) is not None
}
+ def _mm_processor_kwargs(self, request_options: dict | None) -> dict:
+ options = merge_mm_processor_kwargs(
+ getattr(self._model_settings, "mm_processor_kwargs", None),
+ request_options,
+ )
+ if self.model_type != "minicpmv4_7":
+ if options:
+ raise InvalidRequestError(
+ "mm_processor_kwargs is only supported by MiniCPM-V 4.7.",
+ field="mm_processor_kwargs",
+ )
+ return {}
+ config = self._vlm_model.config
+ options.setdefault("downsample_mode", config.downsample_mode)
+ return options
+
def _prepare_vision_inputs(
self,
messages: list[dict[str, Any]],
@@ -4143,13 +4517,15 @@ def _prepare_vision_inputs(
is_partial: bool | None = None,
videos: list[str] | None = None,
video_hashes: list[str] | None = None,
- ) -> Tuple[
- List[int],
- Optional[mx.array],
- Optional[Dict[str, Any]],
- Optional[str],
+ mm_processor_kwargs: dict | None = None,
+ encode_vision: bool = True,
+ ) -> tuple[
+ list[int],
+ mx.array | None,
+ dict[str, Any] | None,
+ str | None,
int,
- List[Tuple[int, str]],
+ list[tuple[int, str]],
]:
"""
Run the full VLM preprocessing pipeline:
@@ -4200,6 +4576,21 @@ def _prepare_vision_inputs(
"image, audio, or video input.",
field="messages",
)
+ nemotron = is_nemotron_omni(model_type)
+ if (
+ nemotron
+ and num_audios
+ and getattr(self._vlm_model, "sound_encoder", None) is None
+ ):
+ raise InvalidRequestError(
+ "This Nemotron checkpoint has no sound encoder.", field="messages"
+ )
+ processor_options = self._mm_processor_kwargs(mm_processor_kwargs)
+ if model_type == "minicpmv4_7" and num_audios:
+ raise InvalidRequestError(
+ "MiniCPM-V 4.7 supports text, image and video input, not audio.",
+ field="messages",
+ )
if model_type == COHERE2_MOE_MODEL_TYPE and (
num_images > 0 or num_audios > 0
):
@@ -4232,12 +4623,36 @@ def _prepare_vision_inputs(
if feature_extractor is not None
else 16000
)
+ if nemotron:
+ target_sample_rate = self._processor.audio_sampling_rate
if not isinstance(target_sample_rate, (int, float)):
target_sample_rate = 16000
audio = [
_load_audio(a, target_sample_rate) if not isinstance(a, tuple) else a
for a in audio
]
+ if nemotron:
+ normalized_audio = []
+ for item in audio:
+ if isinstance(item, tuple):
+ waveform, sample_rate = item
+ waveform = np.asarray(waveform, dtype=np.float32)
+ if waveform.ndim > 1:
+ waveform = waveform.mean(axis=1)
+ if sample_rate != target_sample_rate:
+ from ..patches.mlx_audio_compat import (
+ ensure_mlx_audio_resample_export,
+ )
+
+ ensure_mlx_audio_resample_export()
+ from mlx_audio.utils import resample_audio
+
+ waveform = resample_audio(
+ waveform, sample_rate, target_sample_rate
+ )
+ item = np.asarray(waveform, dtype=np.float32)
+ normalized_audio.append(item)
+ audio = normalized_audio
# Validate multi-image support
if num_images > 1 and model_type in SINGLE_IMAGE_ONLY_MODELS:
raise ValueError(
@@ -4260,7 +4675,7 @@ def _prepare_vision_inputs(
except Exception as e:
# The upstream formatter has no video placeholders; falling back
# would send frames the prompt never references.
- if num_videos:
+ if num_videos or model_type == "minicpmv4_7":
raise
logger.debug(
"Falling back to mlx-vlm apply_chat_template for VLM formatting: %s",
@@ -4367,7 +4782,7 @@ def _prepare_vision_inputs(
# Images with cached features and grids skip the image processor.
fast_cached_features = None
inputs = None
- if num_audios == 0 and num_videos == 0:
+ if num_audios == 0 and num_videos == 0 and not nemotron:
fast = self._try_build_cached_vision_inputs(prompt, images)
if fast is not None:
fast_cached_features = fast.pop("cached_image_features", None)
@@ -4403,6 +4818,12 @@ def _prepare_vision_inputs(
audio=audio if audio else None,
videos=videos if videos else None,
prompts=prompts,
+ **processor_options,
+ **(
+ {"max_frames": NATIVE_VIDEO_MAX_FRAMES}
+ if num_videos and (model_type == "minicpmv4_7" or nemotron)
+ else {}
+ ),
)
input_ids = inputs["input_ids"]
@@ -4411,8 +4832,8 @@ def _prepare_vision_inputs(
token_ids = input_ids[0].tolist() if input_ids.ndim > 1 else input_ids.tolist()
image_cache_key_start = 0
- image_cache_key_ranges: list[Tuple[int, str]] = []
- if image_message_ranges:
+ image_cache_key_ranges: list[tuple[int, str]] = []
+ if image_message_ranges and model_type != "minicpmv4_7":
try:
image_starts = None
if (
@@ -4474,6 +4895,7 @@ def _prepare_vision_inputs(
if images_consumed > 0
else None
),
+ **processor_options,
prompts=(
[prefix_prompt]
if isinstance(prefix_prompt, str)
@@ -4525,6 +4947,10 @@ def _prepare_vision_inputs(
)
and v is not None
}
+ if not encode_vision:
+ return token_ids, None, None, None, 0, []
+ if model_type == "minicpmv4_7":
+ extra_model_inputs["downsample_mode"] = processor_options["downsample_mode"]
# Check for any multimodal inputs. Most processors expose audio as
# ``input_features``; MiMo's tokenizer produces discrete
@@ -4534,12 +4960,16 @@ def _prepare_vision_inputs(
key in extra_model_inputs
for key in ("input_features", "audio_codes", "sound_clips")
)
- has_video = extra_model_inputs.get("pixel_values_videos") is not None
+ has_video = (
+ bool(num_videos)
+ if model_type == "minicpmv4_7"
+ else extra_model_inputs.get("pixel_values_videos") is not None
+ )
has_multimodal = (
(pixel_values is not None and num_images > 0) or has_audio or has_video
)
- if has_multimodal:
+ if has_multimodal or model_type == "minicpmv4_7":
# Build call kwargs from extra_model_inputs (includes input_features
# for audio, image_grid_thw, etc.)
call_kwargs = dict(extra_model_inputs)
@@ -4549,7 +4979,11 @@ def _prepare_vision_inputs(
# Image-specific: compute hash and try vision feature cache
image_hash = None
image_token_count = None
- if num_images > 0:
+ if model_type == "minicpmv4_7" and has_video:
+ image_hash = self._video_cache_identity(video_hashes or [])
+ if num_images:
+ image_hash = f"{cumulative_hashes[-1]}:{image_hash}"
+ elif num_images > 0:
image_hash = cumulative_hashes[-1]
image_token_count = self._image_token_count(input_ids)
elif has_video:
@@ -4564,14 +4998,19 @@ def _prepare_vision_inputs(
else:
image_cache_key_start = 0
image_hash = self._video_cache_identity(video_hashes or [])
- video_features = self._cached_video_features(
- image_hash, input_ids, extra_model_inputs
+ video_features = (
+ self._cached_video_features(
+ image_hash, input_ids, extra_model_inputs
+ )
+ if model_type != "minicpmv4_7" and not nemotron
+ else None
)
if video_features is not None:
call_kwargs["cached_image_features"] = video_features
if (
num_images > 0
+ and model_type != "minicpmv4_7"
and self._vision_cache is not None
and self._vision_cache_enabled
# Fast path already assembled the combined features.
@@ -4700,9 +5139,22 @@ def _prepare_vision_inputs(
# Pass attention_mask as 'mask' — mlx-vlm models (e.g. Gemma 3)
# expect it as a positional/keyword arg named 'mask'.
try:
- embed_features = self._vlm_model.get_input_embeddings(
- input_ids, pixel_values, mask=attention_mask, **call_kwargs
- )
+ if nemotron:
+ from ..patches.nemotron_omni import prepare_nemotron_prompt
+
+ prepared = prepare_nemotron_prompt(
+ self._vlm_model,
+ input_ids,
+ pixel_values,
+ mask=attention_mask,
+ **call_kwargs,
+ )
+ token_ids = prepared.token_ids[0].tolist()
+ embed_features = prepared
+ else:
+ embed_features = self._vlm_model.get_input_embeddings(
+ input_ids, pixel_values, mask=attention_mask, **call_kwargs
+ )
except TypeError:
# cached_image_features kwarg not supported — disable and retry
if "cached_image_features" in call_kwargs:
@@ -4722,6 +5174,11 @@ def _prepare_vision_inputs(
# Convert InputEmbeddingsFeatures to dict for extra kwargs
extra_kwargs = {}
+ if nemotron and has_video:
+ extra_kwargs["_omlx_pruned_video"] = True
+ extra_kwargs["_omlx_source_prompt_tokens"] = int(
+ prepared.source_token_ids.shape[1]
+ )
if hasattr(embed_features, "to_dict"):
feat_dict = embed_features.to_dict()
for k, v in feat_dict.items():
@@ -4738,6 +5195,13 @@ def _prepare_vision_inputs(
_capture_vlm_position_state(
getattr(self._vlm_model, "language_model", None), extra_kwargs
)
+ if model_type == "minicpmv4_7" and has_multimodal:
+ controls_hash = hashlib.sha256(
+ json.dumps(processor_options, sort_keys=True).encode()
+ ).hexdigest()
+ image_hash = f"minicpm:{controls_hash}:{image_hash}"
+ image_cache_key_start = 0
+ image_cache_key_ranges = [(0, image_hash)]
if model_type in {"mimo_v2", "mimo_v2_flash"} and has_audio:
from ..patches.mimo_v2.audio import audio_cache_key_ranges
@@ -4810,6 +5274,7 @@ def _prepare_vision_inputs(
# Text-only (no images in this message)
return token_ids, None, None, None, 0, []
+
def _apply_chat_template(
self,
messages: list[dict[str, Any]],
@@ -4959,6 +5424,28 @@ def _inject_specprefill_system_end(
except Exception as e:
logger.debug(f"SpecPrefill: system_end calc failed: {e}")
+ def _validate_dspark_request(self, **kwargs) -> None:
+ if getattr(self._dflash_drafter, "kind", None) != "dspark":
+ return
+ if kwargs.get("specprefill"):
+ raise InvalidRequestError(
+ "DSpark requires full target context and cannot use SpecPrefill.",
+ field="specprefill",
+ )
+ if (
+ kwargs.get("xtc_probability", 0.0) > 0.0
+ and kwargs.get("temperature", 1.0) > 0.0
+ ):
+ raise InvalidRequestError(
+ "Sampled DSpark does not support stochastic XTC filtering.",
+ field="xtc_probability",
+ )
+ if kwargs.get("compiled_grammar") is not None:
+ raise InvalidRequestError(
+ "DSpark does not support constrained grammar decoding.",
+ field="structured_outputs",
+ )
+
async def generate(
self,
prompt: str | list[int],
@@ -4974,12 +5461,13 @@ async def generate(
vlm_extra_kwargs: dict[str, Any] | None = None,
vlm_image_hash: str | None = None,
vlm_cache_key_start: int = 0,
- vlm_cache_key_ranges: Optional[List[Tuple[int, str]]] = None,
+ vlm_cache_key_ranges: list[tuple[int, str]] | None = None,
**kwargs,
) -> GenerationOutput:
"""Generate a complete response (non-streaming)."""
if not self._loaded:
await self.start()
+ self._validate_dspark_request(temperature=temperature, **kwargs)
if self.is_diffusion_model:
full_text = ""
@@ -5035,9 +5523,9 @@ async def generate(
stop=stop or [],
ignore_eos=bool(kwargs.get("ignore_eos", False)),
stop_token_ids=extra_stop_ids or None,
- thinking_budget=kwargs.get("thinking_budget", None),
- compiled_grammar=kwargs.get("compiled_grammar", None),
- seed=kwargs.get("seed", None),
+ thinking_budget=kwargs.get("thinking_budget"),
+ compiled_grammar=kwargs.get("compiled_grammar"),
+ seed=kwargs.get("seed"),
stop_skips_reasoning=kwargs.get("stop_skips_reasoning", False),
logits_observer=kwargs.get("logits_observer"),
logprobs=bool(kwargs.get("logprobs", False)),
@@ -5068,6 +5556,7 @@ async def generate(
return GenerationOutput(
text=text,
+ tokens=list(getattr(output, "output_token_ids", [])),
prompt_tokens=output.prompt_tokens,
completion_tokens=output.completion_tokens,
finish_reason=output.finish_reason,
@@ -5092,12 +5581,13 @@ async def stream_generate(
vlm_extra_kwargs: dict[str, Any] | None = None,
vlm_image_hash: str | None = None,
vlm_cache_key_start: int = 0,
- vlm_cache_key_ranges: Optional[List[Tuple[int, str]]] = None,
+ vlm_cache_key_ranges: list[tuple[int, str]] | None = None,
**kwargs,
) -> AsyncIterator[GenerationOutput]:
"""Stream generation token by token."""
if not self._loaded:
await self.start()
+ self._validate_dspark_request(temperature=temperature, **kwargs)
if self.is_diffusion_model:
if (
@@ -5159,9 +5649,9 @@ async def stream_generate(
stop=stop or [],
ignore_eos=bool(kwargs.get("ignore_eos", False)),
stop_token_ids=extra_stop_ids or None,
- thinking_budget=kwargs.get("thinking_budget", None),
- compiled_grammar=kwargs.get("compiled_grammar", None),
- seed=kwargs.get("seed", None),
+ thinking_budget=kwargs.get("thinking_budget"),
+ compiled_grammar=kwargs.get("compiled_grammar"),
+ seed=kwargs.get("seed"),
stop_skips_reasoning=kwargs.get("stop_skips_reasoning", False),
logits_observer=kwargs.get("logits_observer"),
logprobs=bool(kwargs.get("logprobs", False)),
@@ -5202,6 +5692,7 @@ async def stream_generate(
yield GenerationOutput(
text=text,
+ tokens=list(getattr(output, "output_token_ids", [])),
new_text=output.new_text,
prompt_tokens=output.prompt_tokens,
completion_tokens=output.completion_tokens,
@@ -5363,6 +5854,9 @@ async def preflight_chat(
miscalibrates the token count but also bypasses the actual
tool-prompt rendering on the real chat path.
+ MiniCPM instead counts the real packed processor output on the MLX
+ executor, without running its vision encoder.
+
Raises ``PrefillMemoryExceededError`` if the conservative estimate
would exceed the configured memory ceiling. See
``BatchedEngine.preflight_chat`` for the upstream rationale
@@ -5371,11 +5865,15 @@ async def preflight_chat(
"""
if not self._loaded:
await self.start()
+ self._validate_dspark_request(**kwargs)
if self.is_diffusion_model:
- _, _, audio = extract_images_from_messages(messages)
+ has_audio = any(
+ self._count_content_parts(msg.get("content"), {"input_audio"})
+ for msg in messages
+ )
self._validate_diffusion_request(
tools=tools,
- audio=audio if audio else None,
+ audio=[None] if has_audio else None,
stop=kwargs.get("stop"),
kwargs=kwargs,
)
@@ -5383,6 +5881,28 @@ async def preflight_chat(
template_tools = convert_tools_for_template(tools) if tools else None
ct_kwargs = kwargs.get("chat_template_kwargs")
partial = kwargs.get("is_partial")
+ if self.model_type == "minicpmv4_7" or is_nemotron_omni(self.model_type):
+ count = functools.partial(
+ self.count_chat_tokens,
+ messages,
+ template_tools,
+ chat_template_kwargs=ct_kwargs,
+ is_partial=partial,
+ mm_processor_kwargs=kwargs.get("mm_processor_kwargs"),
+ )
+ num_tokens = await asyncio.get_running_loop().run_in_executor(
+ self._engine._mlx_executor, count
+ )
+ 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,
+ )
+ return
# Strip image content-parts BEFORE templating. Modern HF chat
# templates (Qwen2.5-VL, Gemma-Vision, Llama-3.2-Vision) render
# ``image_url`` / ``image`` content parts as literal placeholder
@@ -5458,6 +5978,7 @@ async def preflight_chat(
request_id=request_id,
)
+
async def preflight_completion(
self,
prompt: str,
@@ -5672,21 +6193,30 @@ def _extract_request_media(
model_type = self.model_type or _read_config_model_type(self._model_name)
if model_type in {"mimo_v2", "mimo_v2_flash"}:
media_messages = expand_video_parts(messages)
- if not getattr(self, "_native_video", False):
- text_messages, images, audio = extract_images_from_messages(media_messages)
- return media_messages, text_messages, images, audio, []
-
text_messages, images, audio, videos = extract_media_from_messages(
media_messages
)
+ if videos and not getattr(self, "_native_video", False):
+ raise InvalidRequestError(
+ "Video input is not supported by this model.",
+ field="messages",
+ )
# mlx-vlm's Qwen3-VL embedding path takes the grid of one modality per
# call, so a request that mixes them would silently lose one.
- if videos and (images or audio):
+ if (
+ videos
+ and (images or (audio and not is_nemotron_omni(model_type)))
+ and model_type != "minicpmv4_7"
+ ):
raise InvalidRequestError(
"Video input cannot be combined with image or audio input "
"in the same request.",
field="messages",
)
+ if is_nemotron_omni(model_type) and len(videos) > 1:
+ raise InvalidRequestError(
+ "Nemotron supports one video per request.", field="messages"
+ )
return media_messages, text_messages, images, audio, videos
def _process_chat_messages(
@@ -5694,8 +6224,8 @@ def _process_chat_messages(
messages: list[dict[str, Any]],
tools: list[dict] | None,
kwargs: dict,
- ) -> Tuple[
- str | list[int], Any, dict | None, str | None, int, List[Tuple[int, str]]
+ ) -> tuple[
+ str | list[int], Any, dict | None, str | None, int, list[tuple[int, str]]
]:
"""
Process chat messages, extracting images and preparing VLM inputs.
@@ -5706,20 +6236,27 @@ def _process_chat_messages(
media_messages, text_messages, images, audio, videos = (
self._extract_request_media(messages)
)
- model_type = self.model_type or _read_config_model_type(self._model_name)
-
ct_kwargs = kwargs.pop("chat_template_kwargs", None)
partial = kwargs.pop("is_partial", None)
# The ids below come from mlx-vlm's own render; the prepared prompt only
# covers the checks made before generation.
kwargs.pop("_prepared_prompt", None)
+ processor_options = self._mm_processor_kwargs(
+ kwargs.pop("mm_processor_kwargs", None)
+ )
+ preparation_kwargs = {}
+ if processor_options:
+ preparation_kwargs["mm_processor_kwargs"] = processor_options
+ if "_encode_vision" in kwargs:
+ preparation_kwargs["encode_vision"] = kwargs.pop("_encode_vision")
+ encode_vision = preparation_kwargs.get("encode_vision", True)
# 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.
if images:
vlm_messages = self._apply_ocr_prompt(media_messages)
- elif videos or (audio and model_type in {"mimo_v2", "mimo_v2_flash"}):
+ elif videos or audio:
vlm_messages = media_messages
else:
vlm_messages = text_messages
@@ -5733,9 +6270,12 @@ def _process_chat_messages(
video_files.append(write_video_data_uri(uri))
# Rejects undecodable or degenerate clips with a 400 before
# mlx-vlm samples them.
- native_video_token_count(
- probe_video(video_files[-1][0]), video_processor
- )
+ if self.model_type == "minicpmv4_7" or is_nemotron_omni(self.model_type):
+ probe_video(video_files[-1][0])
+ else:
+ native_video_token_count(
+ probe_video(video_files[-1][0]), video_processor
+ )
video_kwargs = (
{
"videos": [str(path) for path, _ in video_files],
@@ -5759,12 +6299,21 @@ def _process_chat_messages(
tools=template_tools,
is_partial=partial,
**video_kwargs,
+ **preparation_kwargs,
)
finally:
for path, _ in video_files:
path.unlink(missing_ok=True)
- if images or videos:
+ audio_hash = compute_audio_video_hash(audio, [])
+ if audio_hash is not None:
+ image_hash = (
+ f"av:{audio_hash}:{image_hash}" if image_hash else f"av:{audio_hash}"
+ )
+ image_cache_key_start = 0
+ image_cache_key_ranges = []
+
+ if encode_vision and (images or videos):
# Free Metal intermediates from vision encoding.
mx.synchronize()
mx.clear_cache()
@@ -5778,6 +6327,7 @@ def _process_chat_messages(
image_cache_key_ranges,
)
+
def _validate_diffusion_request(
self,
*,
@@ -5941,13 +6491,17 @@ def _process_diffusion_chat_messages(
tools: list[dict] | None,
kwargs: dict[str, Any],
) -> dict[str, Any]:
- text_messages, images, audio = extract_images_from_messages(messages)
+ has_audio = any(
+ self._count_content_parts(msg.get("content"), {"input_audio"})
+ for msg in messages
+ )
self._validate_diffusion_request(
tools=tools,
- audio=audio if audio else None,
+ audio=[None] if has_audio else None,
stop=kwargs.get("stop"),
kwargs=kwargs,
)
+ text_messages, images, _, _ = extract_media_from_messages(messages)
chat_template_kwargs = kwargs.pop("chat_template_kwargs", None)
diffusion_messages = messages if images else text_messages
prompt = self._diffusion_apply_chat_template(
@@ -6193,12 +6747,26 @@ def count_chat_tokens(
tools: list[dict] | None = None,
chat_template_kwargs: dict[str, Any] | None = None,
is_partial: bool | None = None,
+ mm_processor_kwargs: dict | None = None,
) -> int:
- """Count prompt tokens for chat messages (text-only approximation).
+ """Count packed MiniCPM/Nemotron prompts; approximate other VLMs as text.
- For VLM messages with images, this counts only the text tokens.
- Image tokens are added during vision encoding and vary by model.
+ Their preprocessing expands media markers without running the vision
+ encoder. Other families add visual tokens during encoding.
"""
+ processor_options = self._mm_processor_kwargs(mm_processor_kwargs)
+ if self.model_type == "minicpmv4_7" or is_nemotron_omni(self.model_type):
+ token_ids, *_ = self._process_chat_messages(
+ messages,
+ tools,
+ {
+ "chat_template_kwargs": chat_template_kwargs,
+ "is_partial": is_partial,
+ "mm_processor_kwargs": processor_options,
+ "_encode_vision": False,
+ },
+ )
+ return len(token_ids)
_, token_ids = self.prepare_chat_prompt(
messages, tools, chat_template_kwargs, is_partial
)
@@ -6260,6 +6828,8 @@ async def tokenize_chat(
if add_generation_prompt is not None:
ct_kwargs["add_generation_prompt"] = add_generation_prompt
kwargs = {"chat_template_kwargs": ct_kwargs or None, "is_partial": is_partial}
+ if self.model_type == "minicpmv4_7" or is_nemotron_omni(self.model_type):
+ kwargs["_encode_vision"] = False
loop = asyncio.get_running_loop()
token_ids, *_ = await loop.run_in_executor(
self._engine._mlx_executor,
diff --git a/omlx/models/vlm.py b/omlx/models/vlm.py
index ac10773437..85d563f7f7 100644
--- a/omlx/models/vlm.py
+++ b/omlx/models/vlm.py
@@ -20,7 +20,7 @@
"""
import logging
-from typing import Any, Dict, List, Optional
+from typing import Any
import mlx.core as mx
import mlx.nn as nn
@@ -77,6 +77,20 @@ def restore_bonsai_quantized_modules(model: nn.Module) -> int:
return restored
+def rope_delta_to_float(value: Any) -> float:
+ """Normalize optional scalar or batched RoPE state for one request.
+
+ Empty arrays represent no position adjustment and therefore map to zero.
+ """
+ if hasattr(value, "reshape") and hasattr(value, "size"):
+ if value.size == 0:
+ return 0.0
+ value = value.reshape(-1)[0]
+ if hasattr(value, "item"):
+ value = value.item()
+ return float(value)
+
+
class VLMModelAdapter(nn.Module):
"""
Adapter wrapping a VLM's language_model for BatchGenerator compatibility.
@@ -106,16 +120,16 @@ def __init__(self, vlm_model: nn.Module):
self._uses_mrope = self._detect_mrope(vlm_model)
# Pending vision embeddings state (set before prefill, cleared after)
- self._pending_embeds: Optional[mx.array] = None
- self._pending_kwargs: Dict[str, Any] = {}
+ self._pending_embeds: mx.array | None = None
+ self._pending_kwargs: dict[str, Any] = {}
self._embed_offset: int = 0
# Per-request mRoPE state: UID → rope_delta mapping.
# Populated by scheduler after VLM prefill, consumed during decode.
# The _patched_generation_batch_step builds _batch_rope_deltas
# from this dict + current batch UIDs before each step.
- self._uid_rope_deltas: Dict[int, float] = {}
- self._batch_rope_deltas: Optional[mx.array] = None
+ self._uid_rope_deltas: dict[int, float] = {}
+ self._batch_rope_deltas: mx.array | None = 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
@@ -131,10 +145,50 @@ def __init__(self, vlm_model: nn.Module):
# call of the bound step and is cleared by the next bind.
self._qwen4_step_text_positions = False
# Full prompt ids for the next prefill call (see bind_prefill_prompt_ids).
- self._prefill_prompt_ids: Optional[List[int]] = None
+ self._prefill_prompt_ids: list[int] | None = None
+ # Native-head MTP reuses mlx-lm's GenerationBatch. Embeddings-prefilled
+ # rows stay on standard decode because prompt-history priming skips
+ # inputs_embeds forwards.
+ self._native_mtp_disabled_uids: set[int] = set()
+ self._minicpm_speculative_transactions: list[Any] = []
+ self._nemotron_mtp_head = None
+
+ def enable_nemotron_mtp(self, head, *, depth: int) -> None:
+ """Bind official head weights; request state owns every mutable cache."""
+ head.bind(self._vlm_model)
+ self._nemotron_mtp_head = head
+ self._omlx_mtp_decode_enabled = True
+ self._omlx_mtp_chain = True
+ self._omlx_mtp_multi_request = True
+ self._omlx_mtp_depth = depth
+ self._omlx_mtp_depth_fixed = True
+ self._omlx_mtp_head_hidden_normed = True
+ self._omlx_native_mtp_full_prompt = True
+
+ def prime_native_mtp(self, tokens, hidden, bonus):
+ import copy
+
+ head = copy.copy(self._nemotron_mtp_head)
+ head.reset(self._vlm_model)
+ head.prefill_from_target_hidden(
+ tokens, hidden, bonus, lambda logits: mx.argmax(logits, axis=-1), greedy=True
+ )
+ mx.eval([entry.state for entry in head._cache])
+ return head._cache, tokens.shape[1]
+
+ def abort_speculative_forward(self) -> None:
+ """Restore any uncommitted native verify after a failed decode step."""
+ transactions = self._minicpm_speculative_transactions
+ self._minicpm_speculative_transactions = []
+ if transactions:
+ from mlx_vlm.speculative.cache_state import abort_speculative_round
+
+ for transaction in transactions:
+ abort_speculative_round(transaction)
def release_resources(self) -> None:
"""Drop references to VLM-owned MLX arrays before engine teardown reclaim."""
+ self.abort_speculative_forward()
if self._vlm_model is not None:
try:
from ..patches.qwen35_ane_prefill import release_qwen35_ane_prefill
@@ -160,12 +214,16 @@ def release_resources(self) -> None:
self._batch_rope_deltas = None
self._qwen4_text_prefill_positions = False
self._qwen4_step_text_positions = False
+ self._native_mtp_disabled_uids.clear()
+ self._nemotron_mtp_head = None
self._language_model = None
self._vlm_model = None
@property
def mtp(self):
"""Expose an attached Lightning MTP head, when the model provides one."""
+ if self._nemotron_mtp_head is not None:
+ return self._nemotron_mtp_head
language_model = self._language_model
getter = getattr(language_model, "get_mtp_module", None)
if callable(getter):
@@ -180,6 +238,13 @@ def mtp_forward(
return_hidden: bool = False,
logits_keep: int = 0,
):
+ if self._nemotron_mtp_head is not None:
+ head = self._nemotron_mtp_head
+ hidden, next_hidden = head._forward_hidden(
+ head._input_embed(next_token_ids), hidden_states, next_token_ids, mtp_cache
+ )
+ logits = head._lm_head_fn(hidden[:, -logits_keep:] if logits_keep else hidden)
+ return (logits, next_hidden) if return_hidden else logits
return self._language_model.mtp_forward(
hidden_states,
next_token_ids,
@@ -189,6 +254,8 @@ def mtp_forward(
)
def make_mtp_cache(self):
+ if self._nemotron_mtp_head is not None:
+ return self._nemotron_mtp_head.make_cache()
make_cache = getattr(self._language_model, "make_mtp_cache", None)
return make_cache() if callable(make_cache) else []
@@ -200,6 +267,13 @@ def rollback_speculative_cache(self, caches, gdn_states, accepted, block_size):
block_size,
)
+ def speculative_verify_logits(self, inputs, cache, sampler):
+ return self._language_model.speculative_verify_logits(
+ inputs,
+ cache,
+ sampler,
+ )
+
# Runtime family patches use this marker to avoid installing an older,
# model-specific copy of the same adapter plumbing.
_omlx_mtp_adapter_patched = True
@@ -213,7 +287,7 @@ def layers(self):
``layers``, flat ``blocks``. Covers all four mlx-vlm conventions.
"""
lm = self._language_model
- for parent in (getattr(lm, "model", None), lm):
+ for parent in (getattr(lm, "model", None), getattr(lm, "backbone", None), lm):
if parent is None:
continue
for attr in ("layers", "blocks"):
@@ -248,7 +322,7 @@ def args(self):
return self._language_model.args
return self.config
- def make_cache(self) -> List[Any]:
+ def make_cache(self) -> list[Any]:
"""
Create KV cache using the language model's make_cache().
@@ -334,7 +408,7 @@ def restore(source, target):
def set_pending_embeddings(
self,
inputs_embeds: mx.array,
- extra_kwargs: Optional[Dict[str, Any]] = None,
+ extra_kwargs: dict[str, Any] | None = None,
start_offset: int = 0,
) -> None:
"""
@@ -417,6 +491,7 @@ def unregister_rope_delta(self, uid: int) -> None:
"""Remove rope_delta for a finished/aborted UID."""
self._uid_rope_deltas.pop(uid, None)
self._uid_text_positions.discard(uid)
+ self._native_mtp_disabled_uids.discard(uid)
def mark_text_positions(self, uid: int) -> None:
"""Record the scheduler's text-only proof for ``uid`` (see set_step_rope_deltas)."""
@@ -432,6 +507,24 @@ def set_step_rope_deltas(self, deltas: mx.array, uids) -> None:
len(uids) == 1 and uids[0] in self._uid_text_positions
)
+ def set_native_mtp_request_eligible(self, uid: int, eligible: bool) -> None:
+ """Record whether a BatchGenerator row may use native-head MTP.
+
+ The scheduler calls this after ``insert()`` and before the first
+ decode step. Text-only rows are eligible; embeddings-prefilled rows
+ retain the same VLM cache but stay on standard autoregressive decode.
+ """
+ if eligible:
+ self._native_mtp_disabled_uids.discard(uid)
+ else:
+ self._native_mtp_disabled_uids.add(uid)
+
+ def native_mtp_allowed_for_uids(self, uids: list[int]) -> bool:
+ """Return False when any current row was prefixed with embeddings."""
+ if self._nemotron_mtp_head is not None:
+ return True
+ return all(uid not in self._native_mtp_disabled_uids for uid in uids)
+
def set_batch_rope_deltas(self, deltas: mx.array) -> None:
"""Set per-request rope_deltas for the current decode batch.
@@ -454,7 +547,7 @@ def set_text_prefill_rope_delta(self, delta: float) -> None:
self._qwen4_text_prefill_positions = True
self._qwen4_step_text_positions = False
- def _batch_rope_deltas_for_size(self, batch_size: int) -> Optional[mx.array]:
+ def _batch_rope_deltas_for_size(self, batch_size: int) -> mx.array | None:
"""Return rope deltas aligned to the current model input batch size."""
if self._batch_rope_deltas is None:
return None
@@ -531,11 +624,7 @@ 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)
+ return rope_delta_to_float(rd)
@property
def has_pending_embeddings(self) -> bool:
@@ -575,7 +664,7 @@ def ple_gathers_ahead(self) -> bool:
probe = getattr(self._language_model, "ple_gathers_ahead", None)
return bool(probe()) if probe is not None else False
- def bind_prefill_prompt_ids(self, prompt_ids: Optional[List[int]]) -> None:
+ def bind_prefill_prompt_ids(self, prompt_ids: list[int] | None) -> None:
"""Bind the full prompt ids of the request whose prefill call runs next.
Unlimited-OCR fixes its R-SWA or DASH prompt boundary from
@@ -585,7 +674,7 @@ def bind_prefill_prompt_ids(self, prompt_ids: Optional[List[int]]) -> None:
"""
self._prefill_prompt_ids = prompt_ids
- def _set_language_prompt_ids(self, cache: Optional[List[Any]]) -> None:
+ def _set_language_prompt_ids(self, cache: list[Any] | None) -> None:
prompt_ids = self._prefill_prompt_ids
self._prefill_prompt_ids = None
if not hasattr(self._language_model, "_prompt_ids"):
@@ -613,7 +702,7 @@ def _omlx_prefill(self, input_ids, cache=None, next_prefill_tokens=0, **kwargs):
def __call__(
self,
input_ids: mx.array,
- cache: Optional[List[Any]] = None,
+ cache: list[Any] | None = None,
skip_lm_head: bool = False,
**kwargs,
) -> Any:
@@ -648,15 +737,40 @@ def __call__(
return_hidden = bool(kwargs.get("return_hidden", False)) or bool(
kwargs.get("capture_layer_ids")
)
- 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
+ native_prompt_capture = (
+ getattr(self, "_omlx_native_mtp_full_prompt", False) and not return_hidden
+ )
+ if native_prompt_capture:
+ kwargs["return_hidden"] = True
+ minicpm_captures = None
+ minicpm_final_hidden = bool(kwargs.get("return_hidden", False))
+ if self.model_type == "minicpmv4_7" and return_hidden:
+ minicpm_captures = list(kwargs.get("capture_layer_ids") or [])
+ native_captures = set(minicpm_captures)
+ if minicpm_final_hidden:
+ native_captures.add(len(self.layers) - 1)
+ kwargs["capture_layer_ids"] = sorted(native_captures)
+ # Native return_hidden appends normalized hidden; oMLX's MTP head
+ # consumes the final layer's pre-norm capture instead.
+ kwargs["return_hidden"] = False
+ # Scheduler prefill chunks discard their logits. Translate the shared
+ # cache-only contract into the official Qwen model hook.
+ if skip_lm_head and 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)
+ vlm_extra.pop("_omlx_pruned_video", None)
+ if (
+ self.model_type == "minicpmv4_7"
+ and inputs_embeds is None
+ and self._pending_embeds is None
+ and cache is not None
+ and "rope_deltas" not in kwargs
+ ):
+ deltas = self._batch_rope_deltas_for_size(input_ids.shape[0])
+ if deltas is not None:
+ kwargs["rope_deltas"] = deltas.reshape(-1, 1)
if inputs_embeds is not None:
result = self._language_model(
@@ -744,6 +858,27 @@ def __call__(
self._vlm_model._set_position_state(input_ids)
result = self._language_model(input_ids, cache=cache, **kwargs)
+ if self.model_type == "minicpmv4_7" and getattr(result, "gdn_states", None) is not None:
+ self._minicpm_speculative_transactions.append(result.gdn_states)
+ if minicpm_captures is not None:
+ try:
+ by_layer = dict(
+ zip(kwargs["capture_layer_ids"], result.hidden_states, strict=True)
+ )
+ result.hidden_states = [by_layer[layer] for layer in minicpm_captures]
+ if minicpm_final_hidden:
+ result.hidden_states.append(by_layer[len(self.layers) - 1])
+ except BaseException:
+ from mlx_vlm.speculative.cache_state import abort_speculative_round
+
+ abort_speculative_round(result.gdn_states)
+ raise
+ if native_prompt_capture:
+ from ..patches.mlx_lm_mtp import prompt_priming
+
+ prompt_priming.maybe_capture(
+ self, input_ids, result.hidden_states[-1], cache
+ )
if return_hidden and hasattr(result, "logits"):
return result
if hasattr(result, "logits"):
@@ -753,7 +888,7 @@ def __call__(
def _forward_with_embeddings(
self,
input_ids: mx.array,
- cache: Optional[List[Any]] = None,
+ cache: list[Any] | None = None,
**kwargs,
) -> Any:
"""Forward pass with pre-computed vision embeddings (prefill phase)."""
@@ -778,7 +913,7 @@ def _forward_with_embeddings(
return result
- def get_input_embeddings(self, input_ids: mx.array, pixel_values: Optional[mx.array] = None, **kwargs) -> Any:
+ def get_input_embeddings(self, input_ids: mx.array, pixel_values: mx.array | None = None, **kwargs) -> Any:
"""
Compute vision+text merged embeddings.
diff --git a/omlx/patches/arrays_cache_metadata.py b/omlx/patches/arrays_cache_metadata.py
index 45b1f7f8c0..a6a3fe0bb7 100644
--- a/omlx/patches/arrays_cache_metadata.py
+++ b/omlx/patches/arrays_cache_metadata.py
@@ -25,7 +25,7 @@ def apply_arrays_cache_metadata_patch() -> bool:
except ImportError:
return False
- cache_classes = [ArraysCache]
+ cache_classes: list[type] = [ArraysCache]
try:
from mlx_vlm.models.cache import ArraysCache as VLMArraysCache
except ImportError:
diff --git a/omlx/patches/bailing_hybrid/bailing_hybrid_model.py b/omlx/patches/bailing_hybrid/bailing_hybrid_model.py
index 40d462bca0..85ce50306a 100644
--- a/omlx/patches/bailing_hybrid/bailing_hybrid_model.py
+++ b/omlx/patches/bailing_hybrid/bailing_hybrid_model.py
@@ -17,6 +17,7 @@
is_mtp_depth_fixed,
prompt_priming,
)
+from omlx.patches.bailing_hybrid.fp8 import convert_ling_fp8_weights
from .activations import swiglu
from .base import (
@@ -967,7 +968,7 @@ def _sanitize_layers(self, weights, n_layers):
weights[f"{prefix}.attention.embed_q.weight"] = wk
weights[f"{prefix}.attention.unembed_out.weight"] = wv
- return self._convert_fp8_block_weights(weights)
+ return convert_ling_fp8_weights(weights, self.args.quantization_config)
def _dequantize_fp8_block(self, weight_key, weight, scale):
quantization_config = self.args.quantization_config or {}
@@ -1013,55 +1014,8 @@ def _dequantize_fp8_block(self, weight_key, weight, scale):
return weight[..., :out_dim, :in_dim].astype(mx.bfloat16)
def _convert_fp8_block_weights(self, weights):
- """Convert Ling's published FP8 and MXFP4 tensor layouts for MLX.
-
- Published FP8 checkpoints use a float32 ``weight_scale_inv`` grid,
- normally with 128x128 blocks. Metal cannot multiply that layout
- directly. Converting one stacked tensor at a time keeps peak memory
- bounded while preserving the checkpoint's compact runtime footprint.
-
- The mixed FP4 checkpoint stores routed experts as two packed E2M1
- values per int8 byte with one E8M0 scale per 32 logical values. That is
- MLX's native MXFP4 layout, so only reinterpret the packed bytes and
- rename the scale sidecar instead of dequantizing the experts.
- """
- quantization_config = self.args.quantization_config or {}
- scale_keys = [key for key in weights if key.endswith(".weight_scale_inv")]
- for scale_key in scale_keys:
- weight_key = scale_key[: -len("_scale_inv")]
- if weight_key not in weights:
- continue
-
- source_weight = weights[weight_key]
- is_routed_mxfp4 = (
- quantization_config.get("routed_experts_quant_method") == "mxfp4"
- and ".mlp.switch_mlp." in weight_key
- and source_weight.dtype == mx.int8
- )
- if is_routed_mxfp4:
- scale = weights.pop(scale_key)
- packed = weights.pop(weight_key).view(mx.uint32)
- base = weight_key[: -len("weight")]
- weights[weight_key] = packed
- weights[f"{base}scales"] = scale
- mx.eval(packed, scale)
- continue
-
- if source_weight.dtype != mx.uint8:
- continue
-
- weight = self._dequantize_fp8_block(
- weight_key, weights.pop(weight_key), weights.pop(scale_key)
- )
- quantized, scales, biases = mx.quantize(weight, group_size=64, bits=8)
- weights[weight_key] = quantized
- base = weight_key[: -len("weight")]
- weights[f"{base}scales"] = scales
- weights[f"{base}biases"] = biases
- mx.eval(quantized, scales, biases)
- mx.clear_cache()
-
- return weights
+ """Backward-compatible wrapper for Ling's shared FP8 conversion."""
+ return convert_ling_fp8_weights(weights, self.args.quantization_config)
@property
def quant_predicate(self):
diff --git a/omlx/patches/bailing_hybrid/fp8.py b/omlx/patches/bailing_hybrid/fp8.py
new file mode 100644
index 0000000000..4c5802e56a
--- /dev/null
+++ b/omlx/patches/bailing_hybrid/fp8.py
@@ -0,0 +1,95 @@
+# SPDX-License-Identifier: Apache-2.0
+"""MLX conversions for Ling's published FP8 and mixed FP4 checkpoints."""
+
+from __future__ import annotations
+
+from typing import Any
+
+import mlx.core as mx
+
+
+def convert_ling_fp8_weights(
+ weights: dict[str, mx.array],
+ quantization_config: dict[str, Any] | None = None,
+) -> dict[str, mx.array]:
+ """Convert Ling block-FP8 and routed MXFP4 pairs into MLX weight layouts.
+
+ Ling stores standard projections as E4M3 bytes with 128-by-128 inverse
+ scale grids, while routed experts use two E2M1 values per int8 with E8M0
+ scales. MLX natively consumes the latter after reinterpreting packed bytes;
+ its affine 8-bit linears require the former to be restored and requantized.
+ """
+ quantization_config = quantization_config or {}
+ block_size = quantization_config.get("weight_block_size", (128, 128))
+ if not isinstance(block_size, (list, tuple)) or len(block_size) != 2:
+ block_size = (128, 128)
+ block_rows, block_cols = (int(block_size[0]), int(block_size[1]))
+
+ scale_keys = [key for key in weights if key.endswith(".weight_scale_inv")]
+ for scale_key in scale_keys:
+ weight_key = scale_key[: -len("_scale_inv")]
+ if weight_key not in weights:
+ continue
+
+ source_weight = weights[weight_key]
+ is_routed_mxfp4 = (
+ ".mlp.switch_mlp." in weight_key and source_weight.dtype == mx.int8
+ )
+ if is_routed_mxfp4:
+ scale = weights.pop(scale_key)
+ packed = weights.pop(weight_key).view(mx.uint32)
+ base = weight_key[: -len("weight")]
+ weights[weight_key] = packed
+ weights[f"{base}scales"] = scale
+ mx.eval(packed, scale)
+ continue
+
+ if source_weight.dtype != mx.uint8:
+ continue
+
+ scale = weights.pop(scale_key)
+ if scale.dtype == mx.uint8:
+ scale = mx.power(
+ mx.array(2.0, dtype=mx.float32),
+ scale.astype(mx.float32) - 127.0,
+ )
+ else:
+ scale = scale.astype(mx.float32)
+ weight = mx.from_fp8(weights.pop(weight_key), dtype=mx.float32)
+ out_dim, in_dim = weight.shape[-2:]
+ target_out = scale.shape[-2] * block_rows
+ target_in = scale.shape[-1] * block_cols
+ if target_out < out_dim or target_in < in_dim:
+ raise ValueError(
+ f"Invalid FP8 block scale for {weight_key}: weight "
+ f"{weight.shape}, scale {scale.shape}, block {block_size}"
+ )
+
+ pad_out = target_out - out_dim
+ pad_in = target_in - in_dim
+ if pad_out or pad_in:
+ padding = [(0, 0)] * (weight.ndim - 2)
+ padding.extend(((0, pad_out), (0, pad_in)))
+ weight = mx.pad(weight, padding)
+
+ lead = weight.shape[:-2]
+ weight = weight.reshape(
+ *lead,
+ scale.shape[-2],
+ block_rows,
+ scale.shape[-1],
+ block_cols,
+ )
+ weight = weight * scale[..., :, None, :, None]
+ weight = weight.reshape(*lead, target_out, target_in)
+ weight = weight[..., :out_dim, :in_dim].astype(mx.bfloat16)
+
+ quantized, scales, biases = mx.quantize(weight, group_size=64, bits=8)
+ weights[weight_key] = quantized
+ base = weight_key[: -len("weight")]
+ weights[f"{base}scales"] = scales
+ weights[f"{base}biases"] = biases
+ mx.eval(quantized, scales, biases)
+ mx.clear_cache()
+
+ return weights
diff --git a/omlx/patches/deepseek_v4/cache_extras.py b/omlx/patches/deepseek_v4/cache_extras.py
index 86e13afdb1..ef08e6e5fe 100644
--- a/omlx/patches/deepseek_v4/cache_extras.py
+++ b/omlx/patches/deepseek_v4/cache_extras.py
@@ -1,4 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
+# ruff: noqa: E741, I001, N803, N806, SIM300, UP006, UP035
"""PoolingCache + BatchPoolingCache from mlx-lm PR 1192.
These two cache classes are copied 1:1 from
diff --git a/omlx/patches/deepseek_v4/chat_template_v4.py b/omlx/patches/deepseek_v4/chat_template_v4.py
index 3116048cc0..9b54294e93 100644
--- a/omlx/patches/deepseek_v4/chat_template_v4.py
+++ b/omlx/patches/deepseek_v4/chat_template_v4.py
@@ -1,7 +1,7 @@
-# Copyright (c) 2023 DeepSeek
-# SPDX-License-Identifier: MIT
-# ruff: noqa: N806, SIM114, UP006, UP007, UP035, UP045
-"""DeepSeek V4 chat encoding based on the official 0731 reference.
+# Copyright © 2025 Apple Inc.
+# SPDX-License-Identifier: Apache 2.0
+# ruff: noqa: E722, F401, N806, UP006, UP007, UP032, UP035, UP045
+"""DeepSeek V4 DSML chat template (derived from mlx-lm deepseek_v32).
The encoding core is vendored from ``deepseek-ai/DeepSeek-V4-Flash-0731``.
The small adapter at the end exposes mlx-lm's ``apply_chat_template`` API.
diff --git a/omlx/patches/deepseek_v4/deepseek_v4_model.py b/omlx/patches/deepseek_v4/deepseek_v4_model.py
index 769d586c7d..0653d178b7 100644
--- a/omlx/patches/deepseek_v4/deepseek_v4_model.py
+++ b/omlx/patches/deepseek_v4/deepseek_v4_model.py
@@ -1,4 +1,6 @@
# Copyright © 2026 Apple Inc.
+# SPDX-License-Identifier: Apache-2.0
+# ruff: noqa: N803, N806, UP006, UP007, UP035, UP045
import logging
import math
diff --git a/omlx/patches/deepseek_v4/dsv4_chat_encoder.py b/omlx/patches/deepseek_v4/dsv4_chat_encoder.py
new file mode 100644
index 0000000000..beb84c4d81
--- /dev/null
+++ b/omlx/patches/deepseek_v4/dsv4_chat_encoder.py
@@ -0,0 +1,208 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Canonical DeepSeek V4 chat encoder shim.
+
+DSV4 bundles can ship ``encoding/encoding_dsv4.py`` with prompt-rendering
+logic that is stricter than the tokenizer's Jinja template. In particular it
+handles reasoning effort tiers and prior-reasoning stripping. This module
+keeps that behavior scoped to DeepSeek V4 tokenizer loads.
+"""
+
+from __future__ import annotations
+
+import copy
+import importlib.util
+import json
+import logging
+import os
+import sys
+from pathlib import Path
+from typing import Any, cast
+
+logger = logging.getLogger(__name__)
+
+_encoding_cache: dict[str, Any] = {}
+
+
+def _load_encoding_dsv4_module(
+ *,
+ model_path: str | Path | None = None,
+ encoding_dir: str | Path | None = None,
+) -> Any:
+ """Locate and import the DSV4 ``encoding_dsv4.py`` module.
+
+ Lookup order is intentionally narrow and DSV4-specific:
+ 1. explicit ``encoding_dir``;
+ 2. ``DSV4_ENCODING_DIR``;
+ 3. ``{model_path}/encoding``.
+ """
+ candidates: list[Path] = []
+ if encoding_dir is not None:
+ candidates.append(Path(encoding_dir).expanduser())
+ if env_dir := os.environ.get("DSV4_ENCODING_DIR"):
+ candidates.append(Path(env_dir).expanduser())
+ if model_path is not None:
+ candidates.append(Path(model_path).expanduser() / "encoding")
+
+ seen: set[Path] = set()
+ for directory in candidates:
+ if directory in seen:
+ continue
+ seen.add(directory)
+ source = directory / "encoding_dsv4.py"
+ if not source.exists():
+ continue
+ spec = importlib.util.spec_from_file_location("encoding_dsv4", str(source))
+ if spec is None or spec.loader is None:
+ continue
+ module = importlib.util.module_from_spec(spec)
+ sys.modules["encoding_dsv4"] = module
+ spec.loader.exec_module(module)
+ logger.info("Loaded canonical DSV4 chat encoder from %s", source)
+ return module
+
+ raise RuntimeError(
+ "DSV4 canonical chat encoder unavailable: no encoding_dsv4.py found "
+ "via an explicit directory, DSV4_ENCODING_DIR, or {model_path}/encoding."
+ )
+
+
+def _get_encoding(model_path: str | Path | None = None) -> Any:
+ env_dir = os.environ.get("DSV4_ENCODING_DIR")
+ if model_path is not None:
+ key = f"model:{Path(model_path).expanduser().resolve()}"
+ elif env_dir:
+ key = f"env:{Path(env_dir).expanduser().resolve()}"
+ else:
+ key = "default"
+ if key not in _encoding_cache:
+ _encoding_cache[key] = _load_encoding_dsv4_module(model_path=model_path)
+ return _encoding_cache[key]
+
+
+def _resolve_mode_and_effort(
+ enable_thinking: bool | None,
+ reasoning_effort: str | None,
+ thinking_mode: str | None = None,
+) -> tuple[str, str | None]:
+ """Map oMLX/vMLX reasoning kwargs to DSV4 encoder kwargs."""
+ if thinking_mode is not None:
+ if thinking_mode not in {"chat", "thinking"}:
+ raise ValueError(f"Invalid DSV4 thinking_mode: {thinking_mode!r}")
+ if thinking_mode == "chat":
+ return "chat", None
+ if reasoning_effort == "max":
+ return "thinking", "max"
+ effort = "high" if reasoning_effort in {"low", "medium", "high"} else None
+ return "thinking", effort
+
+ if reasoning_effort == "max":
+ return "thinking", "max"
+ if enable_thinking is False:
+ return "chat", None
+ if enable_thinking is True:
+ effort = "high" if reasoning_effort in {"low", "medium", "high"} else None
+ return "thinking", effort
+ if reasoning_effort in {"low", "medium", "high"}:
+ return "thinking", "high"
+ return "chat", None
+
+
+def _normalize_tool_call_arguments(messages: list[dict[str, Any]]) -> None:
+ for msg in messages:
+ for tool_call in msg.get("tool_calls") or []:
+ if not isinstance(tool_call, dict):
+ continue
+ function = tool_call.get("function")
+ if isinstance(function, dict) and isinstance(function.get("arguments"), dict):
+ function["arguments"] = json.dumps(
+ function["arguments"], ensure_ascii=False
+ )
+
+
+def _inject_tools(
+ messages: list[dict[str, Any]], tools: list[dict[str, Any]] | None
+) -> list[dict[str, Any]]:
+ if not tools or not messages:
+ return messages
+
+ if any(m.get("role") == "system" and m.get("tools") for m in messages):
+ return messages
+
+ if messages[0].get("role") == "system":
+ first = dict(messages[0])
+ first["tools"] = tools
+ return [first, *messages[1:]]
+
+ return [{"role": "system", "content": "", "tools": tools}, *messages]
+
+
+def apply_chat_template(
+ messages: list[dict[str, Any]],
+ *,
+ enable_thinking: bool | None = None,
+ reasoning_effort: str | None = None,
+ thinking_mode: str | None = None,
+ drop_earlier_reasoning: bool = True,
+ tools: list[dict[str, Any]] | None = None,
+ add_default_bos_token: bool = True,
+ context: list[dict[str, Any]] | None = None,
+ model_path: str | Path | None = None,
+ **kwargs: Any,
+) -> str:
+ """Render a DSV4 prompt with the bundle's canonical encoder."""
+ if "drop_thinking" in kwargs and "drop_earlier_reasoning" not in kwargs:
+ drop_earlier_reasoning = bool(kwargs.pop("drop_thinking"))
+ kwargs.pop("add_generation_prompt", None)
+ kwargs.pop("continue_final_message", None)
+ kwargs.pop("chat_template", None)
+ kwargs.pop("tokenize", None)
+
+ chat_template_kwargs = kwargs.pop("chat_template_kwargs", None) or {}
+ if enable_thinking is None and "enable_thinking" in chat_template_kwargs:
+ enable_thinking = chat_template_kwargs["enable_thinking"]
+ if reasoning_effort is None and "reasoning_effort" in chat_template_kwargs:
+ reasoning_effort = chat_template_kwargs["reasoning_effort"]
+ if thinking_mode is None and "thinking_mode" in chat_template_kwargs:
+ thinking_mode = chat_template_kwargs["thinking_mode"]
+
+ mode, effort = _resolve_mode_and_effort(
+ enable_thinking, reasoning_effort, thinking_mode
+ )
+ prepared = copy.deepcopy(messages)
+ _normalize_tool_call_arguments(prepared)
+ prepared = _inject_tools(prepared, tools)
+
+ encoder = _get_encoding(model_path)
+ return cast(str, encoder.encode_messages(
+ prepared,
+ thinking_mode=mode,
+ context=context,
+ drop_thinking=drop_earlier_reasoning,
+ add_default_bos_token=add_default_bos_token,
+ reasoning_effort=effort,
+ ))
+
+
+def install_canonical_chat_template(tokenizer: Any, model_path: str | Path) -> bool:
+ """Install the canonical encoder on a DSV4 TokenizerWrapper once."""
+ if getattr(tokenizer, "_omlx_dsv4_chat_template_shim", False):
+ return False
+
+ _get_encoding(model_path)
+ original = getattr(tokenizer, "_chat_template", None)
+
+ def _canonical_template(messages, *args, **kwargs):
+ if args:
+ # mlx-lm calls custom templates with kwargs, but tolerate the
+ # common positional add_generation_prompt value used by HF callers.
+ kwargs.setdefault("add_generation_prompt", args[0])
+ return apply_chat_template(messages, model_path=model_path, **kwargs)
+
+ tokenizer._chat_template = _canonical_template
+ tokenizer.has_chat_template = True
+ tokenizer._omlx_dsv4_chat_template_shim = True
+ tokenizer._omlx_dsv4_chat_template_orig = original
+ logger.info(
+ "Installed canonical DSV4 chat-template shim for %s", model_path
+ )
+ return True
diff --git a/omlx/patches/deepseek_v4/hyper_connection.py b/omlx/patches/deepseek_v4/hyper_connection.py
index 74798202a1..22c549c22a 100644
--- a/omlx/patches/deepseek_v4/hyper_connection.py
+++ b/omlx/patches/deepseek_v4/hyper_connection.py
@@ -1,4 +1,6 @@
# Copyright © 2026 Apple Inc.
+# SPDX-License-Identifier: Apache-2.0
+# ruff: noqa: N806, UP006, UP035
from typing import Tuple
diff --git a/omlx/patches/deepseek_v4/tokenizer_patch.py b/omlx/patches/deepseek_v4/tokenizer_patch.py
index fd8c0d4d21..47f3edf1be 100644
--- a/omlx/patches/deepseek_v4/tokenizer_patch.py
+++ b/omlx/patches/deepseek_v4/tokenizer_patch.py
@@ -214,11 +214,25 @@ def patched_load(
return wrapper
from . import chat_template_v4 as _ct
+ from . import dsv4_chat_encoder as _canonical
from . import tool_parser_v4 as _tp
- # Skip if the published tokenizer_config already wired up V4 by
- # itself — leave whatever the user / publisher chose alone.
- if wrapper._chat_template is None:
+ canonical_installed = False
+ try:
+ canonical_installed = _canonical.install_canonical_chat_template(
+ wrapper, model_path
+ )
+ except Exception as e:
+ logger.warning(
+ "Could not install canonical DSV4 chat-template shim for %s: %s",
+ model_path,
+ e,
+ )
+
+ # Fallback for test fixtures or stripped bundles without the canonical
+ # encoding module. Keep the existing DSML template rather than leaving
+ # DSV4 with a minimal Jinja template that lacks tool grammar.
+ if not canonical_installed and wrapper._chat_template is None:
wrapper._chat_template = _ct.apply_chat_template
wrapper.has_chat_template = True
if wrapper._chat_template is _ct.apply_chat_template:
diff --git a/omlx/patches/deepseek_v4/utils_patch.py b/omlx/patches/deepseek_v4/utils_patch.py
index b8c298098a..4f9b93592f 100644
--- a/omlx/patches/deepseek_v4/utils_patch.py
+++ b/omlx/patches/deepseek_v4/utils_patch.py
@@ -1,4 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
+# ruff: noqa: SIM105
"""Patch ``mlx_lm.utils.load_model`` for DeepSeek V4 support.
Two surgical changes from PR 1192 are applied:
diff --git a/omlx/patches/hybrid_batch_cache.py b/omlx/patches/hybrid_batch_cache.py
new file mode 100644
index 0000000000..b2091dbd71
--- /dev/null
+++ b/omlx/patches/hybrid_batch_cache.py
@@ -0,0 +1,78 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Compatibility fixes for mlx-lm hybrid continuous-batching caches."""
+
+from __future__ import annotations
+
+import logging
+
+logger = logging.getLogger(__name__)
+
+_APPLIED = False
+
+
+def _arrays_mask_is_correct(arrays_cache_cls, mx) -> bool:
+ caches = [arrays_cache_cls(1), arrays_cache_cls(1)]
+ merged = arrays_cache_cls.merge(caches)
+ merged.prepare(lengths=[2, 1])
+ mask = merged.make_mask(2)
+ expected = mx.array([[True, True], [True, False]])
+ return mask is not None and mx.array_equal(mask, expected).item()
+
+
+def _empty_filter_is_correct(batch_kv_cache_cls) -> bool:
+ cache = batch_kv_cache_cls(left_padding=[2, 1])
+ cache.filter([1])
+ return cache._idx == 0 and cache.make_mask(1).shape[-1] == 1
+
+
+def apply_hybrid_batch_cache_fixes() -> bool:
+ """Install self-retiring fixes for mixed-length hybrid batches."""
+
+ global _APPLIED
+ if _APPLIED:
+ return True
+ try:
+ import mlx.core as mx
+ from mlx_lm.models.cache import ArraysCache, BatchKVCache
+ except ImportError:
+ return False
+
+ if not _arrays_mask_is_correct(ArraysCache, mx):
+ original_make_mask = ArraysCache.make_mask
+
+ def make_mask(self, N: int): # noqa: N803 - matches mlx-lm API
+ mask = None
+ if self.left_padding is not None:
+ pos = mx.arange(N)
+ mask = pos >= self.left_padding[:, None]
+ if self.lengths is not None:
+ pos = mx.arange(N)
+ right = pos < self.lengths[:, None]
+ mask = right if mask is None else (mask & right)
+ return mask
+
+ make_mask._omlx_original = original_make_mask
+ make_mask._omlx_hybrid_batch_fix = True
+ ArraysCache.make_mask = make_mask
+ logger.info("Installed ArraysCache mixed-padding mask fix")
+
+ if not _empty_filter_is_correct(BatchKVCache):
+ original_filter = BatchKVCache.filter
+
+ def filter_cache(self, batch_indices):
+ if self.keys is None:
+ self.offset = self.offset[batch_indices]
+ self.left_padding = self.left_padding[batch_indices]
+ return
+ original_filter(self, batch_indices)
+
+ filter_cache._omlx_original = original_filter
+ filter_cache._omlx_hybrid_batch_fix = True
+ BatchKVCache.filter = filter_cache
+ logger.info("Installed empty BatchKVCache filter fix")
+
+ _APPLIED = True
+ return True
+
+
+__all__ = ["apply_hybrid_batch_cache_fixes"]
diff --git a/omlx/patches/minicpm47.py b/omlx/patches/minicpm47.py
new file mode 100644
index 0000000000..855bae00f9
--- /dev/null
+++ b/omlx/patches/minicpm47.py
@@ -0,0 +1,299 @@
+# SPDX-License-Identifier: Apache-2.0
+# Portions adapted from mlx-vlm; see ../MLX_VLM_LICENSE.txt.
+"""MiniCPM serving hooks over the official mlx-vlm model and exact verifier."""
+
+from __future__ import annotations
+
+import threading
+from types import MethodType
+
+import mlx.core as mx
+import numpy as np
+
+_LOCK = threading.Lock()
+_APPLIED = False
+
+
+def validate_target_config(config: dict) -> None:
+ if (config.get("text_config") or {}).get("norm_topk_prob", True) is not True:
+ raise ValueError("MiniCPM-V 4.7 requires normalized top-k routing.")
+
+
+def _normalize_qk(layer, q, k):
+ inv_scale = layer.head_k_dim**-0.5
+ eps = 1e-6 / layer.head_k_dim
+ return (
+ inv_scale**2 * mx.fast.rms_norm(q, None, eps),
+ inv_scale * mx.fast.rms_norm(k, None, eps),
+ )
+
+
+def _get_vision_embedding(self, pixel_values, tgt_sizes, downsample_mode=None):
+ """Use floating compute dtypes rather than packed token-table storage."""
+ from mlx_vlm.models.minicpmv4_6.minicpmv4_6 import _to_mx_array, _to_numpy
+
+ if pixel_values is None:
+ return []
+ vision_dtype = self.vision_tower.embeddings.patch_embedding.weight.dtype
+ embedding = self.language_model.model.embed_tokens
+ output_dtype = embedding(mx.array([0], dtype=mx.int32)).dtype
+ outputs = []
+ for batch_idx, batch_pixels in enumerate(pixel_values):
+ grids = _to_numpy(tgt_sizes[batch_idx]) if tgt_sizes is not None else None
+ grids = (
+ np.asarray(grids, dtype=np.int32)
+ if grids is not None and len(grids)
+ else np.zeros((0, 2), dtype=np.int32)
+ )
+ features = []
+ for image_idx, pixels in enumerate(batch_pixels):
+ pixels = _to_mx_array(pixels, dtype=vision_dtype)
+ if pixels is None or pixels.ndim != 3:
+ continue
+ if pixels.shape[0] == 3:
+ pixels = pixels.transpose(1, 2, 0)
+ pixels = mx.expand_dims(pixels, axis=0)
+ grid = (
+ grids[image_idx]
+ if image_idx < len(grids)
+ else np.array(
+ [1, max(int(pixels.shape[2] // self.config.patch_size), 1)],
+ dtype=np.int32,
+ )
+ )
+ target = mx.array(grid, dtype=mx.int32)[None]
+ hidden = self.vision_tower.embeddings(pixels, tgt_sizes=target)
+ hidden = hidden.astype(vision_dtype)
+ height, width = map(int, grid)
+ use_vit_merger = (downsample_mode or self.config.downsample_mode) != "4x"
+ for index, layer in enumerate(self.vision_tower.encoder.layers):
+ hidden = layer(hidden, attention_mask=None)
+ if use_vit_merger and index == self.config.insert_layer_id:
+ hidden, height, width = self.vit_merger(hidden[0], height, width)
+ hidden = mx.expand_dims(hidden, axis=0)
+ hidden = self.vision_tower.post_layernorm(hidden)[0]
+ merged, _, _ = self.merger(hidden, height, width)
+ features.append(merged.astype(output_dtype))
+ outputs.append(mx.concatenate(features, axis=0) if features else [])
+ return outputs
+
+
+def _prepare_padding(inputs, embeds, positions, mask, cache):
+ from mlx_vlm.models.cache import ArraysCache, BatchKVCache, KVCache
+
+ if bool(mx.all(mask).item()):
+ return inputs, embeds, positions, None
+ valid = mask.astype(mx.bool_)
+ attention = next(
+ (entry for entry in cache if isinstance(entry, BatchKVCache)), None
+ )
+ if isinstance(attention, BatchKVCache):
+ expected = (
+ mx.arange(inputs.shape[1])[None] + attention._idx
+ >= attention.left_padding[:, None]
+ )
+ if bool(mx.all(valid == expected).item()):
+ return inputs, embeds, positions, None
+ lengths = mask.sum(axis=1)
+ if bool(mx.any(lengths == 0).item()):
+ raise ValueError("Every prompt must contain at least one unmasked token")
+ starts = mx.argmax(valid, axis=1)
+ axis = mx.arange(inputs.shape[1])[None]
+ contiguous = (axis >= starts[:, None]) & (axis < (starts + lengths)[:, None])
+ if not bool(mx.all(valid == contiguous).item()):
+ raise ValueError("attention_mask must describe contiguous tokens")
+ if any(not entry.empty() for entry in cache):
+ raise ValueError("Padded cached prefill requires scheduler-prepared windows")
+ if any(type(entry) not in (ArraysCache, KVCache, BatchKVCache) for entry in cache):
+ raise ValueError("Padded prefill requires plain hybrid KV/Arrays caches")
+ padding = (inputs.shape[1] - lengths).tolist()
+ for index, entry in enumerate(cache):
+ if isinstance(entry, ArraysCache):
+ entry.lengths = None
+ entry.left_padding = mx.array(padding)
+ elif type(entry) in (KVCache, BatchKVCache):
+ cache[index] = BatchKVCache(padding)
+ order = mx.argsort(mx.where(valid, axis + inputs.shape[1], axis), axis=1)
+ inputs = mx.take_along_axis(inputs, order, axis=1)
+ positions = mx.take_along_axis(
+ positions, mx.broadcast_to(order[None], positions.shape), axis=2
+ )
+ if embeds is not None:
+ embeds = mx.take_along_axis(
+ embeds, mx.broadcast_to(order[..., None], embeds.shape), axis=1
+ )
+ return inputs, embeds, positions, mx.argsort(order, axis=1)
+
+
+def apply_minicpm47_serving_patch() -> bool:
+ """Keep numerical and request-local serving contracts, not model copies."""
+ global _APPLIED
+ with _LOCK:
+ if _APPLIED:
+ return False
+ from mlx_vlm.models.minicpmv4_7 import (
+ MiniCPMV4_7Processor,
+ language,
+ minicpmv4_7,
+ )
+ from mlx_vlm.models.qwen3_5.speculative_verifier import (
+ Qwen3_5BatchInvariantForward,
+ )
+
+ class MiniCPMForward(Qwen3_5BatchInvariantForward):
+ @staticmethod
+ def _normalize_gated_delta_qk(layer, q, k):
+ return _normalize_qk(layer, q, k)
+
+ def _attention(self, attention, x, mask, *args):
+ if isinstance(mask, mx.array) and mask.ndim == 2:
+ mask = mask[None, None]
+ return super()._attention(attention, x, mask, *args)
+
+ forward = MiniCPMForward()
+
+ def process(
+ self,
+ text=None,
+ images=None,
+ videos=None,
+ downsample_mode=None,
+ max_slice_nums=None,
+ max_num_frames=None,
+ **kwargs,
+ ):
+ # mlx-vlm's generic dispatcher forwards only explicitly named parameters.
+ options = {
+ "downsample_mode": downsample_mode,
+ "max_slice_nums": max_slice_nums,
+ "max_num_frames": max_num_frames,
+ }
+ return self(
+ text=text,
+ images=images,
+ videos=videos,
+ **{key: value for key, value in options.items() if value is not None},
+ **kwargs,
+ )
+
+ MiniCPMV4_7Processor.process = process # type: ignore[attr-defined]
+
+ def quantization_path_aliases(self, path: str) -> tuple[str, ...]:
+ return (f"vision_tower.{path}",) if path.startswith("vit_merger.") else ()
+
+ minicpmv4_7.Model.quantization_path_aliases = quantization_path_aliases # type: ignore[attr-defined]
+ minicpmv4_7.Model.get_vision_embedding = _get_vision_embedding # type: ignore[method-assign]
+
+ class ServingLanguage:
+ requires_explicit_rope_deltas = True
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ for layer in self.layers:
+ if layer.is_linear:
+ layer.linear_attn._normalize_qk = MethodType(
+ _normalize_qk, layer.linear_attn
+ )
+
+ def __call__(
+ self, inputs, inputs_embeds=None, mask=None, cache=None, **kwargs
+ ):
+ batch, length = inputs.shape
+ if mask is None:
+ mask = kwargs.pop("attention_mask", None)
+ if (
+ mask is not None
+ and mask.ndim == 2
+ and (
+ mask.shape != inputs.shape
+ or not bool(mx.all((mask == 0) | (mask == 1)).item())
+ )
+ ):
+ raise ValueError(
+ "attention_mask must contain one binary value per input token"
+ )
+ positions = kwargs.pop("position_ids", None)
+ deltas = kwargs.pop("rope_deltas", None)
+ offset = cache[self.model.fa_idx].offset if cache is not None else 0
+ offsets = mx.array(offset, dtype=mx.int32)
+ if offsets.ndim == 0:
+ offsets = mx.broadcast_to(offsets, (batch,))
+ if offsets.shape != (batch,):
+ raise ValueError("Cache offsets must have one entry per request")
+ if deltas is not None and deltas.shape != (batch, 1):
+ raise ValueError("rope_deltas must have shape [batch, 1]")
+ if positions is None:
+ if deltas is None and bool(mx.any(offsets > 0).item()):
+ raise ValueError(
+ "Cached MiniCPM-V 4.7 decode requires request-local rope_deltas"
+ )
+ positions = offsets[:, None] + mx.arange(length)[None]
+ if mask is not None and mask.ndim == 2:
+ positions = mx.maximum(mx.cumsum(mask, axis=-1) - 1, 0)
+ positions = positions + mx.maximum(offsets[:, None], 0)
+ if deltas is not None:
+ positions = positions + deltas
+ positions = mx.broadcast_to(positions[None], (3, batch, length))
+ elif positions.shape != (3, batch, length):
+ raise ValueError("position_ids must match the current input window")
+ verify = kwargs.pop("speculative_verify", False)
+ restore = None
+ if mask is not None and mask.ndim == 2:
+ if verify and not bool(mx.all(mask).item()):
+ raise ValueError(
+ "Speculative verification cannot accept padded proposals"
+ )
+ if cache is None:
+ cache = self.make_cache()
+ inputs, inputs_embeds, positions, restore = _prepare_padding(
+ inputs, inputs_embeds, positions, mask, cache
+ )
+ if verify or (cache is not None and length == 1):
+ call = forward.verify if verify else forward
+ return call(
+ self,
+ inputs,
+ cache=cache,
+ inputs_embeds=inputs_embeds,
+ position_ids=positions,
+ capture_layer_ids=kwargs.get("capture_layer_ids"),
+ return_hidden=kwargs.get("return_hidden", False),
+ return_shared_kv=kwargs.get("return_shared_kv", False),
+ skip_logits=kwargs.get("skip_logits", False),
+ )
+ output = super().__call__(
+ inputs,
+ inputs_embeds=inputs_embeds,
+ mask=mask,
+ cache=cache,
+ position_ids=positions,
+ rope_deltas=deltas,
+ **kwargs,
+ )
+ if restore is not None:
+
+ def restore_rows(value):
+ return mx.take_along_axis(
+ value,
+ mx.broadcast_to(restore[..., None], value.shape),
+ axis=1,
+ )
+
+ if output.logits is not None:
+ output.logits = restore_rows(output.logits)
+ if output.hidden_states is not None:
+ output.hidden_states = [
+ restore_rows(value) for value in output.hidden_states
+ ]
+ return output
+
+ class LanguageModel(ServingLanguage, language.LanguageModel):
+ pass
+
+ class MoELanguageModel(ServingLanguage, language.MoELanguageModel):
+ pass
+
+ minicpmv4_7.LanguageModel = LanguageModel # type: ignore[misc,assignment]
+ minicpmv4_7.MoELanguageModel = MoELanguageModel # type: ignore[misc,assignment]
+ _APPLIED = True
+ return True
diff --git a/omlx/patches/mlx_audio_compat.py b/omlx/patches/mlx_audio_compat.py
index 60edfd763d..79b6dd4c32 100644
--- a/omlx/patches/mlx_audio_compat.py
+++ b/omlx/patches/mlx_audio_compat.py
@@ -3,8 +3,13 @@
from __future__ import annotations
+import importlib
import logging
+import threading
from functools import wraps
+from typing import NoReturn
+
+from omlx.exceptions import UnsupportedKokoroLanguageError
from transformers import AutoTokenizer
@@ -16,6 +21,48 @@
logger = logging.getLogger(__name__)
_RESAMPLE_EXPORT_CHECKED = False
+_KOKORO_G2P_LOCK = threading.Lock()
+
+
+class _EnglishOnlyEspeakBridge:
+ def EspeakFallback(self, british: bool = False) -> None: # noqa: N802
+ return None
+
+ def EspeakG2P(self, language: str) -> NoReturn: # noqa: N802
+ raise UnsupportedKokoroLanguageError(language)
+
+
+_ENGLISH_ONLY_ESPEAK_BRIDGE = _EnglishOnlyEspeakBridge()
+
+
+def _get_english_only_espeak_bridge() -> _EnglishOnlyEspeakBridge:
+ return _ENGLISH_ONLY_ESPEAK_BRIDGE
+
+
+def ensure_english_kokoro_g2p() -> bool:
+ """Keep English Kokoro on Misaki's built-in G2P without loading eSpeak."""
+ with _KOKORO_G2P_LOCK:
+ try:
+ pipeline = importlib.import_module(
+ "mlx_audio.tts.models.kokoro.pipeline"
+ )
+ except ImportError as exc:
+ raise RuntimeError(
+ "Unable to install the English-only Kokoro G2P compatibility "
+ "bridge for the pinned mlx-audio pipeline"
+ ) from exc
+
+ original = getattr(pipeline, "_get_misaki_espeak", None)
+ if original is _get_english_only_espeak_bridge:
+ return True
+ if not callable(original):
+ raise RuntimeError(
+ "The installed mlx-audio Kokoro pipeline no longer exposes "
+ "_get_misaki_espeak"
+ )
+
+ pipeline._get_misaki_espeak = _get_english_only_espeak_bridge
+ return True
def ensure_qwen3_asr_audio_quantization() -> bool:
diff --git a/omlx/patches/mlx_lm_mtp/batch_generator.py b/omlx/patches/mlx_lm_mtp/batch_generator.py
index fd26b6c09a..2c08e2d785 100644
--- a/omlx/patches/mlx_lm_mtp/batch_generator.py
+++ b/omlx/patches/mlx_lm_mtp/batch_generator.py
@@ -22,6 +22,7 @@
import weakref
from collections import deque
from dataclasses import dataclass, field
+from itertools import islice
from statistics import median
from types import SimpleNamespace
from typing import Any, Deque, Dict, List, Optional, Tuple
@@ -246,6 +247,22 @@ def patched_next(self, *args, **kwargs):
return original_next(self, *args, **kwargs)
def patched_extend(self, batch, *args, **kwargs):
+ if getattr(self.model, "_omlx_native_mtp_full_prompt", False):
+ states = {}
+ for owner in (self, batch):
+ batch_state = getattr(owner, "_omlx_mtp_batch_state", None)
+ if batch_state is not None:
+ states.update(batch_state.states)
+ state = getattr(owner, "_omlx_mtp_state", None)
+ if _mtp_state_valid_for_batch(owner, state):
+ states[state.uid] = state
+ result = original_extend(self, batch, *args, **kwargs)
+ for owner in (self, batch):
+ _drop_mtp_state(owner, "native-extended")
+ _drop_mtp_batch_state(owner, "native-extended")
+ if states:
+ self._omlx_mtp_batch_state = _MtpBatchState(states=states)
+ return result
# Reconcile before adding rows without MTP state so the drained
# batch can feed its last tokens without replaying its history.
if not _reconcile_mtp_batch_to_standard(self):
@@ -298,6 +315,16 @@ def patched_filter(self, keep, *args, **kwargs):
return result
def scoped_next(self, *args, **kwargs):
+ model = getattr(self, "model", None)
+ uids = getattr(self, "uids", ())
+ drafter = _drafter_for(model) if model is not None else None
+ if getattr(drafter, "kind", None) == "dspark" and len(uids) > 1:
+ for idx in range(len(uids)):
+ sampler = _row_value(getattr(self, "samplers", None), idx)
+ if sampler is None:
+ sampler = getattr(self, "fallback_sampler", None)
+ if getattr(sampler, "temp", 0.0) != 0.0:
+ raise ValueError("Batched sampled DSpark is not supported.")
realign_rows = getattr(self, "_omlx_realign_rows", None)
if callable(realign_rows):
realign_rows()
@@ -305,7 +332,12 @@ def scoped_next(self, *args, **kwargs):
model = getattr(self, "model", None)
uids = getattr(self, "uids", ())
with _prompt_priming.decode_scope(model, uids), _drafter_scope(model, uids):
- return patched_next(self, *args, **kwargs)
+ try:
+ return patched_next(self, *args, **kwargs)
+ finally:
+ abort = getattr(type(model), "abort_speculative_forward", None)
+ if callable(abort):
+ abort(model)
GenerationBatch.__init__ = patched_init
GenerationBatch.next = scoped_next
@@ -345,10 +377,24 @@ def patched_bg_next(self, *args, **kwargs):
gen_batch._omlx_mtp_activation_safe = (
_batch_generator_allows_mtp_activation(self)
)
+ native_full_prompt = (
+ getattr(
+ getattr(gen_batch, "model", None),
+ "_omlx_native_mtp_full_prompt",
+ False,
+ )
+ is True
+ )
if (
_generation_batch_has_active_mtp(gen_batch)
- and not _singleton_mtp_handoff_ready(gen_batch)
- and getattr(gen_batch, "_omlx_mtp_batch_state", None) is None
+ and (
+ (native_full_prompt and _native_mtp_admission_blocked(self))
+ or (
+ not native_full_prompt
+ and not _singleton_mtp_handoff_ready(gen_batch)
+ and getattr(gen_batch, "_omlx_mtp_batch_state", None) is None
+ )
+ )
):
old_completion_batch_size = getattr(
self,
@@ -356,7 +402,8 @@ def patched_bg_next(self, *args, **kwargs):
None,
)
had_completion_batch_size = hasattr(self, "completion_batch_size")
- # Drain singleton speculation before admitting a late join.
+ # Drain speculation before an unsafe join; native full-prompt
+ # cohorts retain their media-conditioned caches until finished.
self.completion_batch_size = 0
try:
return original_bg_next(self, *args, **kwargs)
@@ -588,6 +635,27 @@ def _batch_generator_allows_mtp_activation(batch_gen: Any) -> bool:
return False
+def _native_mtp_admission_blocked(batch_gen: Any) -> bool:
+ """Keep MTP-ineligible rows outside an active native cohort."""
+ prompt_batch = batch_gen._prompt_batch
+ if len(prompt_batch) and not _mtp_common_eligible(prompt_batch):
+ return True
+ # Decode runs before admission and can finish any active row, so inspect
+ # the entire next prefill group, not just the currently free decode slots.
+ slots = max(0, batch_gen.prefill_batch_size - len(prompt_batch))
+ for sequence in islice(batch_gen._unprocessed_sequences, slots):
+ candidate = SimpleNamespace(
+ model=batch_gen.model,
+ uids=[sequence[0]],
+ samplers=[sequence[5]],
+ fallback_sampler=batch_gen.sampler,
+ logits_processors=[sequence[6]],
+ )
+ if not _mtp_common_eligible(candidate):
+ return True
+ return False
+
+
def _generation_batch_has_active_mtp(gen_batch: Any) -> bool:
"""True while a generation batch owns Lightning MTP cache state."""
if gen_batch is None:
@@ -607,6 +675,10 @@ def _singleton_mtp_handoff_ready(gen_batch: Any) -> bool:
"""Allow a singleton handoff once at most one committed token is unstreamed."""
if gen_batch is None:
return False
+ if getattr(
+ getattr(gen_batch, "model", None), "_omlx_native_mtp_full_prompt", False
+ ):
+ return False
if getattr(gen_batch, "_omlx_mtp_activation_safe", True):
return False
if getattr(gen_batch, "_omlx_mtp_batch_state", None) is not None:
@@ -642,6 +714,15 @@ def _mtp_common_eligible(gen_batch: Any) -> bool:
uids = getattr(gen_batch, "uids", None)
if uids is None or len(uids) == 0:
return False
+ native_mtp_allowed = getattr(
+ gen_batch.model, "native_mtp_allowed_for_uids", None
+ )
+ if (
+ drafter is None
+ and callable(native_mtp_allowed)
+ and not native_mtp_allowed(list(uids))
+ ):
+ return False
if _has_grammar_processors(gen_batch):
return False
# XTC changes the target distribution but is absent from acceptance math.
@@ -2268,6 +2349,10 @@ def _call_backbone_impl(
MTP head's ``hidden_pre_norm`` is the same array with or without a
capture request.
+ The exact-verifier convenience API returns only the last hidden state.
+ Layer captures use the model's capture-bearing ``return_hidden`` contract,
+ which must retain its architecture-specific verification and rollback.
+
The first three entries:
- mlx-lm path returns the 2-tuple ``(logits, hidden)``; ``gdn_states``
@@ -2293,6 +2378,11 @@ def _call_backbone_impl(
# deepseek_v4 (see _exact_verify_host) run every projection and attention
# row with one-row decode arithmetic, so greedy MTP output equals MTP-off.
exact_verify = bool(n_confirmed and _exact_verify_host(model) is not None)
+ minicpm_verify = bool(
+ n_confirmed and getattr(model, "model_type", None) == "minicpmv4_7"
+ )
+ if minicpm_verify:
+ kwargs["speculative_verify"] = True
_rollback_mod.set_undo_armed(True)
# The affine verify qmm kernel is a Qwen-specific optimization. Keep the
# DeepSeek target on its architecture-native quantized linear path.
@@ -2304,7 +2394,30 @@ def _call_backbone_impl(
)
_set_dspark_target_verify(model, exact_verify)
try:
- result = model(inputs, **kwargs)
+ verify_logits = getattr(model, "speculative_verify_logits", None)
+ language_model = getattr(model, "_language_model", None)
+ # mRoPE adapters bind per-request positions in their forward path.
+ if language_model is not None and (
+ getattr(model, "_uses_mrope", False) is True
+ or not callable(
+ getattr(language_model, "speculative_verify_logits", None)
+ )
+ ):
+ verify_logits = None
+ if (
+ n_confirmed
+ and not minicpm_verify
+ and not capture_layer_ids
+ and callable(verify_logits)
+ ):
+ hidden, _, rollback_state, logits = verify_logits(
+ inputs,
+ cache,
+ lambda value: value,
+ )
+ result = logits, hidden, rollback_state
+ else:
+ result = model(inputs, **kwargs)
finally:
if exact_verify:
_set_dspark_target_verify(model, False)
@@ -3589,6 +3702,8 @@ def _post_init_mtp(gen_batch: Any, *, verify_result=None, priming_offset=None) -
state.mtp_cache, state.hist_offset = primed
state.head_history_primed = True
else:
+ if getattr(gen_batch.model, "_omlx_native_mtp_full_prompt", False):
+ raise RuntimeError("Nemotron MTP activation lost its complete prompt seed")
state.mtp_cache = gen_batch.model.make_mtp_cache()
state.next_main = _ensure_uint32(next_main_tok)
state.queue.append((int(main_tok.tolist()[0]), main_lp, "init"))
@@ -3806,7 +3921,7 @@ def _emit_ragged_responses(
raise _MtpStepFallback(f"ragged emit: row uid={uid} produced no tokens")
state = batch_state.states.get(uid)
row_finished = False
- for token_id, logprobs_1d, source in toks:
+ for position, (token_id, logprobs_1d, source) in enumerate(toks):
if state is not None:
_bump_emit_stat(state, source)
finish_reason: Optional[str] = None
@@ -3817,13 +3932,21 @@ def _emit_ragged_responses(
if gen_batch._matchers[idx].advance(token_id):
finish_reason = "stop"
if finish_reason is not None:
+ terminal_prompt_cache = gen_batch.extract_cache(idx)
+ model = getattr(gen_batch, "model", None)
+ if getattr(model, "_omlx_native_mtp_full_prompt", False) is True:
+ from .uniform import terminal_cache
+
+ terminal_prompt_cache = terminal_cache(
+ gen_batch, idx, token_id, pending=position == len(toks) - 1
+ )
responses.append(
Response(
uid=uid,
token=token_id,
logprobs=logprobs_1d,
finish_reason=finish_reason,
- prompt_cache=gen_batch.extract_cache(idx),
+ prompt_cache=terminal_prompt_cache,
all_tokens=gen_batch.tokens[idx],
)
)
@@ -4574,6 +4697,19 @@ def _run_verify_cycle_chain(
cycle's sync. Emits ``m + 1`` tokens per cycle (m = accepted drafts, plus
bonus on full accept or the verify-position correction on reject).
"""
+ if getattr(gen_batch.model, "_omlx_native_mtp_full_prompt", False):
+ from .uniform import advance_uniform
+
+ replacements = {}
+ advance_uniform(
+ gen_batch,
+ int(state.drafts.shape[0]),
+ [(0, gen_batch, state)],
+ replacements,
+ cache=gen_batch.prompt_cache,
+ )
+ return
+
import time
import mlx.core as mx
@@ -5380,6 +5516,13 @@ def _emit_response(
if finish_reason is not None:
prompt_cache = gen_batch.extract_cache(0)
+ if getattr(gen_batch.model, "_omlx_native_mtp_full_prompt", False):
+ from .uniform import terminal_cache
+
+ state = getattr(gen_batch, "_omlx_mtp_state", None)
+ prompt_cache = terminal_cache(
+ gen_batch, 0, token_id, pending=state is not None and not state.queue
+ )
all_tokens = gen_batch.tokens[0]
response = Response(
uid=gen_batch.uids[0],
diff --git a/omlx/patches/mlx_lm_mtp/deepseek_v4_model.py b/omlx/patches/mlx_lm_mtp/deepseek_v4_model.py
index 4bbe4d7845..c0ee9ec61b 100644
--- a/omlx/patches/mlx_lm_mtp/deepseek_v4_model.py
+++ b/omlx/patches/mlx_lm_mtp/deepseek_v4_model.py
@@ -331,9 +331,6 @@ def __init__(self, config):
if is_dspark:
depth = min(depth, int(config.dspark_block_size))
self._omlx_mtp_head_clone = False
- # DSpark context caches are singleton and committed-only. The
- # existing row-wise extract/merge path does not model them.
- self._omlx_mtp_rowwise_unsupported = True
logger.info(
"DeepSeek speculative backend selected: embedded DSpark "
"(%d stages, draft width %d)",
diff --git a/omlx/patches/mlx_lm_mtp/fused_batch.py b/omlx/patches/mlx_lm_mtp/fused_batch.py
index 5857477d07..348b71d6bd 100644
--- a/omlx/patches/mlx_lm_mtp/fused_batch.py
+++ b/omlx/patches/mlx_lm_mtp/fused_batch.py
@@ -339,6 +339,10 @@ def _verify_rows_together(batch, batch_state, host, indices, replacements):
def _advance_group(batch, depth, rows, replacements, *, cache=None):
+ if getattr(batch.model, "_omlx_native_mtp_full_prompt", False):
+ from .uniform import advance_uniform
+
+ return advance_uniform(batch, depth, rows, replacements, cache=cache)
batch_state = getattr(batch, "_omlx_mtp_batch_state", None)
drafter = bg._drafter_for(batch.model)
use_head_batch = (
diff --git a/omlx/patches/mlx_lm_mtp/prompt_priming.py b/omlx/patches/mlx_lm_mtp/prompt_priming.py
index 60459361e4..0a4b1f26b2 100644
--- a/omlx/patches/mlx_lm_mtp/prompt_priming.py
+++ b/omlx/patches/mlx_lm_mtp/prompt_priming.py
@@ -112,6 +112,8 @@ class _PrimeCtx:
extra_key_token_start: Optional[int] = None
extra_key_ranges: Optional[list[tuple[int, tuple[Any, ...]]]] = None
snapshot_candidate: Any = None
+ native_prompt_tokens: list[Any] | None = None
+ native_prompt_hidden: list[Any] | None = None
@dataclass
@@ -1020,6 +1022,8 @@ def _defer_decode_history(host):
history is the same sequence of committed pairs.
"""
ctx = _find_ctx(host)
+ if isinstance(ctx, _PrimeCtx) and ctx.native_prompt_hidden is not None:
+ return
if (
isinstance(ctx, _PrimeCtx)
and ctx.deferred_pairs is None
@@ -1150,7 +1154,7 @@ def _capture_single(
setattr(host, _PLAN_ATTR, plan)
ctx = None
if ctx is None:
- if seq_len <= 1:
+ if seq_len <= 1 and not getattr(host, "_omlx_native_mtp_full_prompt", False):
# A lone decode step cannot start a prompt timeline.
return
plan = _find_plan(host)
@@ -1170,6 +1174,20 @@ def _capture_single(
return
setattr(host, _CTX_ATTR, ctx)
+ if getattr(host, "_omlx_native_mtp_full_prompt", False) and ctx.deferred_pairs is None:
+ if ctx.native_prompt_hidden is None:
+ if offset_after != seq_len:
+ raise RuntimeError("Native MTP requires complete uncached prompt history")
+ ctx.native_prompt_tokens = []
+ ctx.native_prompt_hidden = []
+ ctx.native_prompt_tokens.append(inputs)
+ ctx.native_prompt_hidden.append(normed)
+ ctx.folded += seq_len
+ ctx.pending_hidden = normed[:, -1:]
+ ctx.expected_offset = offset_after
+ mx.async_eval(normed)
+ return
+
if ctx.pending_hidden is not None:
if seq_len > 1:
pairs_hidden = mx.concatenate([ctx.pending_hidden, normed[:, :-1]], axis=1)
@@ -1288,6 +1306,14 @@ def _take_primed(
offset,
)
return None
+ if ctx.native_prompt_hidden is not None:
+ import mlx.core as mx
+
+ return model.prime_native_mtp(
+ mx.concatenate(ctx.native_prompt_tokens, axis=1),
+ mx.concatenate(ctx.native_prompt_hidden, axis=1),
+ main_tok,
+ )
if ctx.deferred_pairs is not None:
_flush_deferred_history(model, ctx)
try:
diff --git a/omlx/patches/mlx_lm_mtp/uniform.py b/omlx/patches/mlx_lm_mtp/uniform.py
new file mode 100644
index 0000000000..9551f82bee
--- /dev/null
+++ b/omlx/patches/mlx_lm_mtp/uniform.py
@@ -0,0 +1,146 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Common-frontier target sampling for uniform recurrent-cache rollback."""
+
+from __future__ import annotations
+
+from collections import deque
+from collections.abc import Callable, Sequence
+from copy import copy, deepcopy
+from dataclasses import dataclass
+
+
+@dataclass(frozen=True)
+class UniformAcceptance:
+ accepted_drafts: int
+ successors: tuple[int, ...]
+
+
+def sample_uniform_prefix(
+ drafts: Sequence[Sequence[int]],
+ sample_position: Callable[[int], Sequence[int]],
+ stop_position: Callable[[int, Sequence[int]], bool],
+) -> UniformAcceptance:
+ depth = len(drafts[0])
+ for position in range(depth + 1):
+ targets = tuple(sample_position(position))
+ if (
+ position == depth
+ or stop_position(position, targets)
+ or any(target != row[position] for target, row in zip(targets, drafts))
+ ):
+ return UniformAcceptance(position, targets)
+ raise AssertionError("Uniform verification did not reach its frontier")
+
+
+def advance_uniform(batch, depth, rows, replacements, *, cache=None):
+ """Commit one exact native verify at the cohort's common sampled frontier."""
+ import mlx.core as mx
+
+ from . import batch_generator as bg
+
+ whole_batch = cache is not None
+ if cache is None:
+ cache = bg._merge_row_caches([row.prompt_cache for _, row, _ in rows])
+ inputs = mx.stack(
+ [mx.concatenate([state.next_main, state.drafts]) for _, _, state in rows]
+ )
+ logits, hidden, undo, _ = bg._call_backbone_captured(
+ batch.model, inputs, cache, n_confirmed=1
+ )
+ if undo is None:
+ raise RuntimeError("Nemotron verification did not return exact rollback state")
+ drafts = inputs[:, 1:].tolist()
+ distributions = [[] for _ in rows]
+ matchers = [copy(row._matchers[0]) for _, row, _ in rows]
+
+ def sample_position(position):
+ sampled = []
+ for i, (_, row, _) in enumerate(rows):
+ processors = bg._proc_list(row)
+ previous = (
+ row._token_context[0].update_and_fetch(
+ inputs[i, position : position + 1]
+ )
+ if processors is not None
+ else None
+ )
+ value = bg._apply_processors(
+ processors, previous, logits[i : i + 1, position, :]
+ )
+ lp = bg._logprobs(value)
+ distributions[i].append(lp[0])
+ token = bg._resolve_sampler(row)(lp).reshape(-1).tolist()
+ sampled.append(int(token[0]))
+ return sampled
+
+ def stop_position(position, targets):
+ terminal = False
+ for (_, row, _), matcher, token in zip(rows, matchers, targets):
+ stopped = bool(matcher.advance(token))
+ remaining = row.max_tokens[0] - row._num_tokens[0]
+ terminal |= stopped or position + 1 >= remaining
+ return terminal
+
+ decision = sample_uniform_prefix(drafts, sample_position, stop_position)
+ accepted = decision.accepted_drafts
+ # A failed target/head commit fails the cohort. Never publish a queue or
+ # reinterpret partially advanced native state as an ordinary-decode fallback.
+ batch.model.rollback_speculative_cache(cache, undo, accepted, depth + 1)
+ staged = []
+ for i, (_, row, state) in enumerate(rows):
+ next_state = copy(state)
+ next_state.queue = deque()
+ next_state.stats = deepcopy(state.stats)
+ next_state.mtp_cache = bg._clone_mtp_head_cache(state.mtp_cache)
+ bg._mtp_head_trim_to(next_state.mtp_cache, state.hist_offset)
+ committed_ids = drafts[i][:accepted] + [decision.successors[i]]
+ committed = mx.array(committed_ids, dtype=mx.uint32)
+ previous = (
+ row._token_context[0].tokens if bg._proc_list(row) is not None else None
+ )
+ bg._chain_next_drafts(
+ row, next_state, hidden[i : i + 1, : accepted + 1], committed, previous
+ )
+ next_state.next_main = committed[-1:]
+ next_state.stats.cycles += 1
+ next_state.stats.accepts += accepted
+ next_state.stats.rejects += int(accepted < depth)
+ while len(next_state.stats.depth_drafted) < depth:
+ next_state.stats.depth_drafted.append(0)
+ next_state.stats.depth_accepted.append(0)
+ for j in range(depth):
+ next_state.stats.depth_drafted[j] += int(j <= accepted)
+ next_state.stats.depth_accepted[j] += int(j < accepted)
+ for j, token in enumerate(committed_ids):
+ source = (
+ "draft" if j < accepted else "bonus" if accepted == depth else "verify"
+ )
+ next_state.queue.append((token, distributions[i][j], source))
+ staged.append(next_state)
+ mx.eval(
+ [entry.state for entry in cache],
+ [[entry.state for entry in state.mtp_cache] for state in staged],
+ [state.drafts for state in staged],
+ )
+ for row_index, ((index, row, state), next_state) in enumerate(zip(rows, staged)):
+ state.__dict__.update(next_state.__dict__)
+ batch._token_context[index] = row._token_context[0]
+ if not whole_batch:
+ replacements[index] = [entry.extract(row_index) for entry in cache]
+ if whole_batch:
+ batch.prompt_cache = cache
+ bg._clear_rollback(cache)
+ return whole_batch
+
+
+def terminal_cache(batch, row_index, token_id, *, pending):
+ """Return exactly the emitted native prefix without sampling a successor."""
+ import mlx.core as mx
+
+ cache = batch.extract_cache(row_index)
+ if pending:
+ result = batch.model(
+ mx.array([[token_id]], dtype=mx.uint32), cache=cache, return_hidden=True
+ )
+ mx.eval(result.logits, [entry.state for entry in cache])
+ return cache
diff --git a/omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/__init__.py b/omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/__init__.py
new file mode 100644
index 0000000000..260c872635
--- /dev/null
+++ b/omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/__init__.py
@@ -0,0 +1,164 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Ling 3.0 Flash VL compatibility overlay for the pinned mlx-vlm release."""
+
+from __future__ import annotations
+
+import importlib
+import logging
+from copy import deepcopy
+from pathlib import Path
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+SOURCE_COMMIT = "9a89d53fcd698edd6414dd9ea155d6482c721fc8"
+_VENDOR_MLX_VLM = Path(__file__).resolve().parent / "vendor" / "mlx_vlm"
+_APPLIED = False
+
+
+def _prepend_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 in package_path:
+ package_path.remove(path_string)
+ package_path.insert(0, path_string)
+
+
+def apply_mlx_vlm_bailing_moe_v3_vl_compat_patch() -> bool:
+ """Expose oMLX's vendored Ling 3.0 Flash VL model to mlx-vlm."""
+ global _APPLIED
+ if _APPLIED:
+ return False
+
+ try:
+ import mlx_vlm
+ import mlx_vlm.models
+ from mlx_vlm.prompt_utils import MODEL_CONFIG, MessageFormat
+
+ _prepend_package_path(mlx_vlm, _VENDOR_MLX_VLM)
+ _prepend_package_path(mlx_vlm.models, _VENDOR_MLX_VLM / "models")
+ importlib.import_module("mlx_vlm.models.bailing_moe_v3_vl")
+ MODEL_CONFIG.setdefault(
+ "bailing_moe_v3_vl", MessageFormat.LIST_WITH_IMAGE_FIRST
+ )
+ _patch_load_config()
+ _patch_video_prompt_format()
+ except Exception as exc: # noqa: BLE001
+ logger.debug("Ling 3.0 Flash VL mlx-vlm registration failed: %s", exc)
+ return False
+
+ _APPLIED = True
+ logger.info("Ling 3.0 Flash VL mlx-vlm compatibility patch applied")
+ return True
+
+
+def is_applied() -> bool:
+ return _APPLIED
+
+
+def _patch_load_config() -> None:
+ """Retain Ling's native FP8 base plus per-module FP4 overrides."""
+ import mlx_vlm.utils as vlm_utils
+
+ original = vlm_utils.load_config
+ if getattr(original, "_omlx_bailing_moe_v3_vl_compat", False):
+ return
+
+ def patched_load_config(model_path, **kwargs):
+ config = original(model_path, **kwargs)
+ _normalize_ling_quantization(config)
+ return config
+
+ patched_load_config._omlx_bailing_moe_v3_vl_compat = True
+ patched_load_config._omlx_original = original
+ vlm_utils.load_config = patched_load_config
+
+
+def _normalize_ling_quantization(config: Any) -> None:
+ if not isinstance(config, dict) or config.get("model_type") != "bailing_moe_v3_vl":
+ return
+
+ quantization = config.get("quantization")
+ quantization_config = config.get("quantization_config")
+ runtime_quantization = _runtime_quantization(quantization)
+ if runtime_quantization is None:
+ runtime_quantization = _runtime_quantization(quantization_config)
+ if runtime_quantization is None:
+ runtime_quantization = _legacy_ling_quantization(config, quantization_config)
+ if runtime_quantization is None:
+ return
+
+ # mlx-vlm needs ``quantization`` before ModelConfig construction to avoid
+ # collapsing a mixed map into a global mxfp4 default. Mirror the complete
+ # map so ModelConfig's two metadata fields agree through load_model().
+ config["quantization"] = runtime_quantization
+ config["quantization_config"] = deepcopy(runtime_quantization)
+
+
+def _runtime_quantization(metadata: Any) -> dict[str, Any] | None:
+ if not isinstance(metadata, dict):
+ return None
+ if not {"bits", "group_size"}.issubset(metadata):
+ return None
+ return deepcopy(metadata)
+
+
+def _legacy_ling_quantization(
+ config: dict[str, Any], metadata: Any
+) -> dict[str, Any] | None:
+ """Convert only Ling's explicit FP8-plus-routed-MXFP4 declaration."""
+ if not isinstance(metadata, dict) or metadata.get("quant_method") != "fp8":
+ return None
+
+ quantization: dict[str, Any] = {
+ "group_size": int(metadata.get("group_size", 64)),
+ "bits": 8,
+ }
+ for path, spec in metadata.items():
+ if isinstance(spec, dict) and {"bits", "group_size"}.issubset(spec):
+ quantization[path] = deepcopy(spec)
+
+ if metadata.get("routed_experts_quant_method") != "mxfp4":
+ return quantization
+
+ text_config = config.get("text_config")
+ text_config = text_config if isinstance(text_config, dict) else {}
+ first_sparse_layer = int(text_config.get("first_k_dense_replace", 0))
+ num_hidden_layers = int(text_config.get("num_hidden_layers", 0))
+ expert_quantization = {
+ "group_size": int(metadata.get("routed_experts_group_size", 32)),
+ "bits": 4,
+ "mode": "mxfp4",
+ }
+ for layer_index in range(first_sparse_layer, num_hidden_layers):
+ base = f"language_model.model.layers.{layer_index}.mlp.switch_mlp"
+ for projection in ("gate_proj", "up_proj", "down_proj"):
+ quantization.setdefault(f"{base}.{projection}", deepcopy(expert_quantization))
+ return quantization
+
+
+def _patch_video_prompt_format() -> None:
+ """Keep Ling on mlx-vlm's Qwen video-message path."""
+ from mlx_vlm.prompt_utils import MessageFormatter
+
+ original = MessageFormatter.format_message
+ if getattr(original, "_omlx_bailing_moe_v3_vl_compat", False):
+ return
+
+ def patched_format_message(self, *args, **kwargs):
+ if self.model_name == "bailing_moe_v3_vl" and kwargs.get("video"):
+ return self._format_video_message(*args, **kwargs)
+ return original(self, *args, **kwargs)
+
+ patched_format_message._omlx_bailing_moe_v3_vl_compat = True
+ patched_format_message._omlx_original = original
+ MessageFormatter.format_message = patched_format_message
+
+
+__all__ = [
+ "SOURCE_COMMIT",
+ "apply_mlx_vlm_bailing_moe_v3_vl_compat_patch",
+ "is_applied",
+]
diff --git a/omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/__init__.py b/omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/__init__.py
new file mode 100644
index 0000000000..9881313609
--- /dev/null
+++ b/omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/__init__.py
@@ -0,0 +1 @@
+# SPDX-License-Identifier: Apache-2.0
diff --git a/omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/__init__.py b/omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/__init__.py
new file mode 100644
index 0000000000..9881313609
--- /dev/null
+++ b/omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/__init__.py
@@ -0,0 +1 @@
+# SPDX-License-Identifier: Apache-2.0
diff --git a/omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/models/__init__.py b/omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/models/__init__.py
new file mode 100644
index 0000000000..9881313609
--- /dev/null
+++ b/omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/models/__init__.py
@@ -0,0 +1 @@
+# SPDX-License-Identifier: Apache-2.0
diff --git a/omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/models/bailing_moe_v3_vl/__init__.py b/omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/models/bailing_moe_v3_vl/__init__.py
new file mode 100644
index 0000000000..3547d434ab
--- /dev/null
+++ b/omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/models/bailing_moe_v3_vl/__init__.py
@@ -0,0 +1,24 @@
+from ..base import install_auto_processor_patch
+from .bailing_moe_v3_vl import (
+ LanguageModel as LanguageModel,
+)
+from .bailing_moe_v3_vl import (
+ Model as Model,
+)
+from .bailing_moe_v3_vl import (
+ VisionModel as VisionModel,
+)
+from .config import (
+ ModelConfig as ModelConfig,
+)
+from .config import (
+ TextConfig as TextConfig,
+)
+from .config import (
+ VisionConfig as VisionConfig,
+)
+from .processing_bailing_moe_v3_vl import (
+ BailingMoeV3VLProcessor as BailingMoeV3VLProcessor,
+)
+
+install_auto_processor_patch("bailing_moe_v3_vl", BailingMoeV3VLProcessor)
diff --git a/omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/models/bailing_moe_v3_vl/bailing_moe_v3_vl.py b/omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/models/bailing_moe_v3_vl/bailing_moe_v3_vl.py
new file mode 100644
index 0000000000..c055e6c13e
--- /dev/null
+++ b/omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/models/bailing_moe_v3_vl/bailing_moe_v3_vl.py
@@ -0,0 +1,167 @@
+import mlx.core as mx
+import numpy as np
+from mlx import nn
+
+from ..base import InputEmbeddingsFeatures
+from .config import ModelConfig
+from .language import LanguageModel
+from .vision import VisionModel
+
+
+def masked_scatter(final_embedding, mask, features):
+ shape = final_embedding.shape
+ flat = mx.flatten(final_embedding)
+ positions = mx.array(np.where(mx.flatten(mask))[0], mx.uint32)
+ flat[positions] = mx.flatten(features)
+ return flat.reshape(shape)
+
+
+class Model(nn.Module):
+ def __init__(self, config: ModelConfig):
+ super().__init__()
+ self.config = config
+ self.vision_tower = (
+ None if config.skip_vision else VisionModel(config.vision_config)
+ )
+ packed_size = (
+ config.vision_config.hidden_size
+ * config.vision_config.spatial_merge_size**2
+ )
+ self.linear_proj = [
+ nn.Linear(packed_size, config.text_config.hidden_size, bias=True),
+ nn.GELU(),
+ nn.Linear(
+ config.text_config.hidden_size,
+ config.text_config.hidden_size,
+ bias=True,
+ ),
+ ]
+ self.language_model = LanguageModel(config.text_config, config)
+
+ def _project(self, features):
+ for layer in self.linear_proj:
+ features = layer(features)
+ return features
+
+ def get_input_embeddings(
+ self,
+ input_ids: mx.array,
+ pixel_values: mx.array | None = None,
+ **kwargs,
+ ):
+ image_grid_thw = kwargs.get("image_grid_thw")
+ video_grid_thw = kwargs.get("video_grid_thw")
+ mask = kwargs.get("mask")
+ inputs_embeds = self.language_model.model.word_embeddings(input_ids)
+ cached = kwargs.get("cached_image_features")
+ if (
+ pixel_values is None
+ and kwargs.get("pixel_values_videos") is None
+ and cached is None
+ ):
+ if kwargs.get("cache") is not None:
+ return InputEmbeddingsFeatures(inputs_embeds=inputs_embeds)
+ position_ids, rope_deltas = self.language_model.get_rope_index(
+ input_ids, attention_mask=mask
+ )
+ return InputEmbeddingsFeatures(
+ inputs_embeds=inputs_embeds,
+ position_ids=position_ids,
+ rope_deltas=rope_deltas,
+ )
+
+ if cached is not None:
+ features = cached
+ visual_mask = (input_ids == self.config.image_token_index) | (
+ input_ids == self.config.video_token_index
+ )
+ expanded = mx.broadcast_to(visual_mask[..., None], inputs_embeds.shape)
+ if expanded.sum().item() != features.size:
+ raise ValueError(
+ "Cached visual features and visual tokens do not match: "
+ f"tokens={visual_mask.sum().item()}, features={features.shape[0]}"
+ )
+ inputs_embeds = masked_scatter(inputs_embeds, expanded, features)
+ else:
+ if self.vision_tower is None:
+ raise ValueError("bailing_moe_v3_vl was loaded without a vision tower")
+ dtype = self.vision_tower.patch_embed.proj.weight.dtype
+ media = (
+ (
+ pixel_values,
+ image_grid_thw,
+ self.config.image_token_index,
+ "Image",
+ ),
+ (
+ kwargs.get("pixel_values_videos"),
+ video_grid_thw,
+ self.config.video_token_index,
+ "Video",
+ ),
+ )
+ for pixels, grid, token_id, label in media:
+ if pixels is None:
+ continue
+ features, _ = self.vision_tower(pixels.astype(dtype), grid)
+ features = self._project(features)
+ media_mask = input_ids == token_id
+ expanded = mx.broadcast_to(media_mask[..., None], inputs_embeds.shape)
+ if expanded.sum().item() != features.size:
+ raise ValueError(
+ f"{label} features and {label.lower()} tokens do not match: "
+ f"tokens={media_mask.sum().item()}, features={features.shape[0]}"
+ )
+ inputs_embeds = masked_scatter(inputs_embeds, expanded, features)
+
+ visual_mask = (input_ids == self.config.image_token_index) | (
+ input_ids == self.config.video_token_index
+ )
+ position_ids, rope_deltas = self.language_model.get_rope_index(
+ input_ids, image_grid_thw, video_grid_thw, mask
+ )
+ return InputEmbeddingsFeatures(
+ inputs_embeds=inputs_embeds,
+ visual_pos_masks=visual_mask,
+ position_ids=position_ids,
+ rope_deltas=rope_deltas,
+ )
+
+ def __call__(
+ self,
+ input_ids,
+ pixel_values=None,
+ mask=None,
+ cache=None,
+ **kwargs,
+ ):
+ features = self.get_input_embeddings(
+ input_ids, pixel_values, mask=mask, cache=cache, **kwargs
+ )
+ kwargs.update(features.to_dict())
+ kwargs["pixel_values"] = pixel_values
+ return self.language_model(input_ids, mask=mask, cache=cache, **kwargs)
+
+ @property
+ def layers(self):
+ return self.language_model.model.layers
+
+ def sanitize(self, weights):
+ sanitized = {}
+ for key, value in weights.items():
+ if key.startswith("model.visual."):
+ key = "vision_tower." + key[len("model.visual.") :]
+ elif key.startswith("model."):
+ key = "language_model.model." + key[len("model.") :]
+ elif key.startswith("lm_head."):
+ key = "language_model." + key
+ sanitized[key] = value
+ return sanitized
+
+ @property
+ def quant_predicate(self):
+ return self.language_model.quant_predicate
+
+ @property
+ def cast_predicate(self):
+ return self.language_model.cast_predicate
diff --git a/omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/models/bailing_moe_v3_vl/config.py b/omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/models/bailing_moe_v3_vl/config.py
new file mode 100644
index 0000000000..44964f9c31
--- /dev/null
+++ b/omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/models/bailing_moe_v3_vl/config.py
@@ -0,0 +1,176 @@
+import inspect
+from dataclasses import dataclass, field
+from typing import Any, Literal
+
+from ..base import BaseModelConfig
+
+AttentionKind = Literal["kda", "mla"]
+
+
+def _config_kwargs(config_cls, params):
+ return {
+ key: value
+ for key, value in params.items()
+ if key in inspect.signature(config_cls).parameters
+ }
+
+
+@dataclass
+class VisionConfig(BaseModelConfig):
+ model_type: str = "qwen3_moe_vit"
+ depth: int = 27
+ hidden_size: int = 1152
+ hidden_act: str = "gelu_pytorch_tanh"
+ intermediate_size: int = 4304
+ num_heads: int = 16
+ in_channels: int = 3
+ patch_size: int = 16
+ spatial_merge_size: int = 2
+ temporal_patch_size: int = 2
+ out_hidden_size: int = 4096
+ num_position_embeddings: int = 2304
+ initializer_range: float = 0.02
+ disable_merger_proj: bool = True
+ deepstack_visual_indexes: list[int] = field(default_factory=list)
+
+ def __post_init__(self):
+ if self.model_type != "qwen3_moe_vit":
+ raise ValueError(f"Unsupported vision model type: {self.model_type}")
+ if self.spatial_merge_size != 2:
+ raise ValueError("bailing_moe_v3_vl requires fixed 2x2 vision packing")
+
+
+@dataclass
+class TextConfig(BaseModelConfig):
+ model_type: str = "bailing_moe_v3"
+ vocab_size: int = 157184
+ hidden_size: int = 2560
+ intermediate_size: int = 6144
+ num_hidden_layers: int = 42
+ num_attention_heads: int = 32
+ num_key_value_heads: int = 32
+ head_dim: int = 128
+ rms_norm_eps: float = 1e-6
+ max_position_embeddings: int = 131072
+ rope_theta: float = 6000000.0
+ rope_scaling: dict[str, Any] | None = None
+ tie_word_embeddings: bool = False
+ first_k_dense_replace: int = 2
+ num_experts: int = 512
+ num_experts_per_tok: int = 8
+ num_shared_experts: int = 1
+ moe_intermediate_size: int = 768
+ moe_shared_expert_intermediate_size: int = 768
+ n_group: int = 8
+ topk_group: int = 4
+ routed_scaling_factor: float = 2.5
+ norm_topk_prob: bool = True
+ score_function: str = "sigmoid"
+ moe_router_enable_expert_bias: bool = True
+ layer_group_size: int = 6
+ kv_lora_rank: int = 512
+ q_lora_rank: int | None = None
+ qk_nope_head_dim: int = 128
+ qk_rope_head_dim: int = 64
+ v_head_dim: int = 128
+ short_conv_kernel_size: int = 4
+ kda_safe_gate: bool = True
+ kda_lower_bound: float | None = -5.0
+ gated_attention_proj_granularity_type: str = "head_wise"
+ mrope_section: list[int] = field(default_factory=lambda: [8, 12, 12])
+ expert_swiglu_limit_list: list[float] = field(default_factory=list)
+ share_expert_swiglu_limit_list: list[float] = field(default_factory=list)
+ video_start_token: int = 157160
+ layer_plan: tuple[AttentionKind, ...] = field(init=False)
+
+ def __post_init__(self):
+ if self.layer_group_size <= 0:
+ raise ValueError("layer_group_size must be positive")
+ if self.score_function != "sigmoid":
+ raise ValueError("bailing_moe_v3_vl requires sigmoid expert routing")
+ if self.num_shared_experts != 1:
+ raise ValueError("bailing_moe_v3_vl requires exactly one shared expert")
+ if self.gated_attention_proj_granularity_type != "head_wise":
+ raise ValueError("Only head-wise MLA output gating is supported")
+ if sum(self.mrope_section) * 2 != self.qk_rope_head_dim:
+ raise ValueError(
+ "mrope_section must cover half of qk_rope_head_dim "
+ f"({self.mrope_section} for {self.qk_rope_head_dim})"
+ )
+ self.rope_scaling = dict(self.rope_scaling or {})
+ self.rope_scaling.setdefault("type", "default")
+ self.rope_scaling["mrope_section"] = list(self.mrope_section)
+ self.expert_swiglu_limit_list = (
+ list(self.expert_swiglu_limit_list) + [0.0] * self.num_hidden_layers
+ )[: self.num_hidden_layers]
+ self.share_expert_swiglu_limit_list = (
+ list(self.share_expert_swiglu_limit_list) + [0.0] * self.num_hidden_layers
+ )[: self.num_hidden_layers]
+ if any(limit < 0 for limit in self.expert_swiglu_limit_list):
+ raise ValueError("expert_swiglu_limit_list values must be non-negative")
+ if any(limit < 0 for limit in self.share_expert_swiglu_limit_list):
+ raise ValueError(
+ "share_expert_swiglu_limit_list values must be non-negative"
+ )
+ self.layer_plan = tuple(
+ "mla"
+ if (index + 1) % self.layer_group_size == 0
+ or index
+ >= self.num_hidden_layers // self.layer_group_size * self.layer_group_size
+ else "kda"
+ for index in range(self.num_hidden_layers)
+ )
+
+
+@dataclass
+class ModelConfig(BaseModelConfig):
+ text_config: TextConfig
+ vision_config: VisionConfig
+ model_type: str = "bailing_moe_v3_vl"
+ image_token_id: int = 157157
+ video_token_id: int = 156909
+ vision_start_token_id: int = 157158
+ vision_end_token_id: int = 157159
+ video_start_token_id: int = 157160
+ mrope_section: list[int] = field(default_factory=lambda: [8, 12, 12])
+ image_token_index: int | None = None
+ video_token_index: int | None = None
+ skip_vision: bool = False
+ quantization: dict[str, Any] | None = None
+ quantization_config: dict[str, Any] | None = None
+
+ def __post_init__(self):
+ if self.model_type != "bailing_moe_v3_vl":
+ raise ValueError(f"Unsupported model type: {self.model_type}")
+ if self.image_token_index is None:
+ self.image_token_index = self.image_token_id
+ if self.video_token_index is None:
+ self.video_token_index = self.video_token_id
+ self.video_start_token_id = self.text_config.video_start_token
+ self.text_config.mrope_section = list(self.mrope_section)
+ self.text_config.__post_init__()
+ if self.quantization is None:
+ self.quantization = self.quantization_config
+ elif (
+ self.quantization_config is not None
+ and self.quantization_config != self.quantization
+ ):
+ raise ValueError("quantization and quantization_config must agree")
+ self.quantization_config = self.quantization
+
+ @classmethod
+ def from_dict(cls, params):
+ params = dict(params)
+ mrope_section = list(params.get("mrope_section", [8, 12, 12]))
+ text = params.get("text_config")
+ if isinstance(text, dict):
+ text = dict(text)
+ text["mrope_section"] = mrope_section
+ params["text_config"] = TextConfig(**_config_kwargs(TextConfig, text))
+ vision = params.get("vision_config")
+ if isinstance(vision, dict):
+ params["vision_config"] = VisionConfig(
+ **_config_kwargs(VisionConfig, vision)
+ )
+ params["mrope_section"] = mrope_section
+ return cls(**_config_kwargs(cls, params))
diff --git a/omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/models/bailing_moe_v3_vl/language.py b/omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/models/bailing_moe_v3_vl/language.py
new file mode 100644
index 0000000000..b211eaddec
--- /dev/null
+++ b/omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/models/bailing_moe_v3_vl/language.py
@@ -0,0 +1,651 @@
+import re
+from functools import partial
+
+import mlx.core as mx
+from mlx import nn
+
+from omlx.patches.bailing_hybrid.fp8 import convert_ling_fp8_weights
+
+from ..bailing_moe.language import aggregate_expert_outputs, group_expert_select
+from ..base import create_attention_mask, create_ssm_mask, scaled_dot_product_attention
+from ..cache import ArraysCache, BatchKVCache, KVCache
+from ..gated_delta import gated_delta_update
+from ..kimi_k3.language import ShortConv1d
+from ..mla import MultiLinear, latent_length, max_absorbed_queries
+from ..mlp import SwiGLUMLP
+from ..qwen3_vl.language import (
+ LanguageModel as Qwen3VLLanguageModel,
+)
+from ..qwen3_vl.language import (
+ Qwen3VLRotaryEmbedding,
+ apply_multimodal_rotary_pos_emb,
+)
+from ..switch_layers import SwiGLU, SwitchGLU
+from .config import TextConfig
+
+
+@partial(mx.compile, shapeless=True)
+def _clamped_swiglu(x, gate, limit):
+ return mx.clip(nn.silu(gate), a_min=None, a_max=limit) * mx.clip(
+ x, a_min=-limit, a_max=limit
+ )
+
+
+class ClampedSwiGLU(nn.Module):
+ def __init__(self, limit):
+ super().__init__()
+ self.limit = limit
+
+ def __call__(self, x, gate):
+ return _clamped_swiglu(x, gate, self.limit)
+
+
+class DenseMLP(nn.Module):
+ def __init__(self, args: TextConfig, intermediate_size: int, limit: float = 0):
+ super().__init__()
+ self.gate_proj = nn.Linear(args.hidden_size, intermediate_size, bias=False)
+ self.up_proj = nn.Linear(args.hidden_size, intermediate_size, bias=False)
+ self.down_proj = nn.Linear(intermediate_size, args.hidden_size, bias=False)
+ self.activation = ClampedSwiGLU(limit) if limit > 0 else SwiGLU()
+
+ def __call__(self, x):
+ return self.down_proj(self.activation(self.up_proj(x), self.gate_proj(x)))
+
+
+class KDAAttention(nn.Module):
+ def __init__(self, args: TextConfig):
+ super().__init__()
+ self.num_heads = args.num_attention_heads
+ self.head_dim = args.head_dim
+ self.projection_dim = self.num_heads * self.head_dim
+ self.conv_kernel = args.short_conv_kernel_size
+ self.scale = self.head_dim**-0.5
+ self.lower_bound = args.kda_lower_bound if args.kda_safe_gate else None
+
+ hidden = args.hidden_size
+ self.q_proj = nn.Linear(hidden, self.projection_dim, bias=False)
+ self.k_proj = nn.Linear(hidden, self.projection_dim, bias=False)
+ self.v_proj = nn.Linear(hidden, self.projection_dim, bias=False)
+ self.q_conv = ShortConv1d(self.projection_dim, self.conv_kernel)
+ self.k_conv = ShortConv1d(self.projection_dim, self.conv_kernel)
+ self.v_conv = ShortConv1d(self.projection_dim, self.conv_kernel)
+ self.f_proj = nn.Linear(hidden, self.projection_dim, bias=False)
+ self.b_proj = nn.Linear(hidden, self.num_heads, bias=False)
+ self.g_proj = nn.Linear(hidden, self.projection_dim, bias=False)
+ self.A_log = mx.zeros((self.num_heads,))
+ self.dt_bias = mx.zeros((self.projection_dim,))
+ self.o_norm = nn.RMSNorm(self.head_dim, eps=args.rms_norm_eps)
+ self.o_proj = nn.Linear(self.projection_dim, hidden, bias=False)
+
+ def __call__(
+ self,
+ x: mx.array,
+ mask: mx.array | None = None,
+ cache: ArraysCache | None = None,
+ **kwargs,
+ ) -> mx.array:
+ batch, length, _ = x.shape
+ states = [None, None, None, None] if cache is None else list(cache)
+ lengths = None if cache is None else cache.lengths
+ q, states[0] = self.q_conv(self.q_proj(x), states[0], mask, lengths)
+ k, states[1] = self.k_conv(self.k_proj(x), states[1], mask, lengths)
+ v, states[2] = self.v_conv(self.v_proj(x), states[2], mask, lengths)
+
+ q = q.reshape(batch, length, self.num_heads, self.head_dim)
+ k = k.reshape(batch, length, self.num_heads, self.head_dim)
+ v = v.reshape(batch, length, self.num_heads, self.head_dim)
+ eps = 1e-6 / self.head_dim
+ q = (self.scale**2) * mx.fast.rms_norm(q, None, eps)
+ k = self.scale * mx.fast.rms_norm(k, None, eps)
+ gate = self.f_proj(x).reshape(batch, length, self.num_heads, self.head_dim)
+ beta = self.b_proj(x).reshape(batch, length, self.num_heads)
+ out, states[3] = gated_delta_update(
+ q,
+ k,
+ v,
+ gate,
+ beta,
+ self.A_log.reshape(self.num_heads, 1),
+ self.dt_bias.reshape(self.num_heads, self.head_dim),
+ state=states[3],
+ mask=mask,
+ use_kernel=not self.training,
+ lower_bound=self.lower_bound,
+ )
+ if cache is not None:
+ for index, state in enumerate(states):
+ cache[index] = state
+ cache.advance(length)
+ output_gate = mx.sigmoid(self.g_proj(x)).reshape(
+ batch, length, self.num_heads, self.head_dim
+ )
+ out = (self.o_norm(out) * output_gate).reshape(batch, length, -1)
+ return self.o_proj(out)
+
+
+class MLAAttention(nn.Module):
+ def __init__(self, args: TextConfig):
+ super().__init__()
+ self.num_heads = args.num_attention_heads
+ self.qk_nope_head_dim = args.qk_nope_head_dim
+ self.qk_rope_head_dim = args.qk_rope_head_dim
+ self.q_head_dim = self.qk_nope_head_dim + self.qk_rope_head_dim
+ self.v_head_dim = args.v_head_dim
+ self.kv_lora_rank = args.kv_lora_rank
+ self.scale = self.q_head_dim**-0.5
+ hidden = args.hidden_size
+
+ self.q_proj = nn.Linear(hidden, self.num_heads * self.q_head_dim, bias=False)
+ self.kv_a_proj_with_mqa = nn.Linear(
+ hidden, self.kv_lora_rank + self.qk_rope_head_dim, bias=False
+ )
+ self.kv_a_layernorm = nn.RMSNorm(self.kv_lora_rank, eps=args.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.g_proj = nn.Linear(hidden, self.num_heads, bias=False)
+ self.dense = nn.Linear(self.num_heads * self.v_head_dim, hidden, bias=False)
+ self.rotary_emb = Qwen3VLRotaryEmbedding(
+ self.qk_rope_head_dim,
+ max_position_embeddings=args.max_position_embeddings,
+ base=args.rope_theta,
+ rope_scaling=args.rope_scaling,
+ )
+ self._absorbed_dims = (
+ self.kv_lora_rank,
+ self.qk_nope_head_dim,
+ self.v_head_dim,
+ )
+
+ def __call__(
+ self,
+ x: mx.array,
+ mask: mx.array | None = None,
+ cache: KVCache | None = None,
+ position_ids: mx.array | None = None,
+ position_embeddings: tuple[mx.array, mx.array] | None = None,
+ ) -> mx.array:
+ batch, length, _ = x.shape
+ q = self.q_proj(x).reshape(batch, length, self.num_heads, self.q_head_dim)
+ q = q.transpose(0, 2, 1, 3)
+ q_nope, q_pe = mx.split(q, [self.qk_nope_head_dim], axis=-1)
+
+ compressed = self.kv_a_proj_with_mqa(x)
+ compressed, k_pe = mx.split(compressed, [self.kv_lora_rank], axis=-1)
+ kv_latent = mx.expand_dims(self.kv_a_layernorm(compressed), axis=1)
+ k_pe = k_pe.reshape(batch, length, 1, self.qk_rope_head_dim).transpose(
+ 0, 2, 1, 3
+ )
+
+ if position_embeddings is None:
+ if position_ids is None:
+ offset = cache.offset if cache is not None else 0
+ position_ids = mx.arange(offset, offset + length)[None, :]
+ q_pe, k_pe = self.rotary_emb.apply_rotary(
+ q_pe, k_pe, position_ids, unsqueeze_dim=1
+ )
+ else:
+ q_pe, k_pe = apply_multimodal_rotary_pos_emb(
+ q_pe, k_pe, *position_embeddings
+ )
+
+ if cache is not None:
+ kv_latent, k_pe = cache.update_and_fetch(kv_latent, k_pe)
+
+ pe_scores = (q_pe * self.scale) @ k_pe.swapaxes(-1, -2)
+ if mask is not None:
+ pe_scores = mx.where(
+ mask,
+ pe_scores,
+ mx.array(mx.finfo(pe_scores.dtype).min, pe_scores.dtype),
+ )
+
+ absorbed = length == 1 or length <= max_absorbed_queries(
+ *self._absorbed_dims, latent_length(kv_latent)
+ )
+ if absorbed:
+ q_nope = self.embed_q(q_nope)
+ 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_nope, k, v, cache=cache, scale=self.scale, mask=pe_scores
+ )
+ if absorbed:
+ output = self.unembed_out(output)
+ gate = mx.sigmoid(self.g_proj(x)).transpose(0, 2, 1)[..., None]
+ output = output * gate
+ output = output.transpose(0, 2, 1, 3).reshape(batch, length, -1)
+ return self.dense(output)
+
+
+class BailingMoeGate(nn.Module):
+ def __init__(self, args: TextConfig):
+ super().__init__()
+ self.weight = mx.zeros((args.num_experts, args.hidden_size))
+ self.expert_bias = (
+ mx.zeros((args.num_experts,), dtype=mx.float32)
+ if args.moe_router_enable_expert_bias
+ else None
+ )
+ self.top_k = args.num_experts_per_tok
+ self.n_group = args.n_group
+ self.topk_group = args.topk_group
+ self.routed_scaling_factor = args.routed_scaling_factor
+ self.norm_topk_prob = args.norm_topk_prob
+ self.score_function = args.score_function
+
+ def __call__(self, x):
+ return group_expert_select(
+ x @ self.weight.T,
+ self.expert_bias,
+ self.top_k,
+ self.n_group,
+ self.topk_group,
+ self.routed_scaling_factor,
+ self.norm_topk_prob,
+ self.score_function,
+ )
+
+
+class SparseMoE(nn.Module):
+ def __init__(self, args: TextConfig, layer_idx: int):
+ super().__init__()
+ self.gate = BailingMoeGate(args)
+ routed_limit = args.expert_swiglu_limit_list[layer_idx]
+ self.switch_mlp = SwitchGLU(
+ args.hidden_size,
+ args.moe_intermediate_size,
+ args.num_experts,
+ activation=(ClampedSwiGLU(routed_limit) if routed_limit > 0 else SwiGLU()),
+ bias=False,
+ )
+ self.shared_experts = DenseMLP(
+ args,
+ args.moe_shared_expert_intermediate_size,
+ limit=args.share_expert_swiglu_limit_list[layer_idx],
+ )
+
+ def __call__(self, x):
+ indices, scores = self.gate(x)
+ routed = aggregate_expert_outputs(self.switch_mlp(x, indices), scores)
+ return routed + self.shared_experts(x)
+
+
+class DecoderLayer(nn.Module):
+ def __init__(self, args: TextConfig, layer_idx: int):
+ super().__init__()
+ self.kind = args.layer_plan[layer_idx]
+ self.attention = (
+ KDAAttention(args) if self.kind == "kda" else MLAAttention(args)
+ )
+ self.mlp = (
+ SwiGLUMLP(args.hidden_size, args.intermediate_size, bias=False)
+ if layer_idx < args.first_k_dense_replace
+ else SparseMoE(args, layer_idx)
+ )
+ self.input_layernorm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps)
+ self.post_attention_layernorm = nn.RMSNorm(
+ args.hidden_size, eps=args.rms_norm_eps
+ )
+
+ def __call__(self, x, mask=None, cache=None, **kwargs):
+ h = x + self.attention(
+ self.input_layernorm(x), mask=mask, cache=cache, **kwargs
+ )
+ return h + self.mlp(self.post_attention_layernorm(h))
+
+
+class BailingMoeV3Model(nn.Module):
+ def __init__(self, args: TextConfig):
+ super().__init__()
+ self.args = args
+ self.word_embeddings = nn.Embedding(args.vocab_size, args.hidden_size)
+ self.layers = [
+ DecoderLayer(args, index) for index in range(args.num_hidden_layers)
+ ]
+ self.norm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps)
+
+ def __call__(
+ self,
+ inputs,
+ inputs_embeds=None,
+ mask=None,
+ cache=None,
+ position_ids=None,
+ visual_pos_masks=None,
+ deepstack_visual_embeds=None,
+ ):
+ h = self.word_embeddings(inputs) if inputs_embeds is None else inputs_embeds
+ if cache is None:
+ cache = [None] * len(self.layers)
+ kda_index = next(
+ (i for i, kind in enumerate(self.args.layer_plan) if kind == "kda"), None
+ )
+ mla_index = next(
+ (i for i, kind in enumerate(self.args.layer_plan) if kind == "mla"), None
+ )
+ kda_mask = (
+ create_ssm_mask(h, cache[kda_index]) if kda_index is not None else None
+ )
+ mla_mask = (
+ create_attention_mask(h, cache[mla_index], return_array=True)
+ if mla_index is not None
+ else None
+ )
+ if mask is not None:
+ if mask.ndim == 2:
+ kda_mask = mask
+ key_mask = mask.astype(mx.bool_)[:, None, None, :]
+ mla_mask = (
+ key_mask
+ if mla_mask is None
+ else mla_mask.astype(mx.bool_) & key_mask
+ )
+ else:
+ mla_mask = mask
+ position_embeddings = None
+ if (
+ position_ids is not None
+ and mla_index is not None
+ and not self.layers[mla_index].attention.rotary_emb.fused_apply
+ ):
+ position_embeddings = self.layers[mla_index].attention.rotary_emb(
+ h, position_ids
+ )
+ for layer, layer_cache in zip(self.layers, cache):
+ layer_mask = kda_mask if layer.kind == "kda" else mla_mask
+ h = layer(
+ h,
+ mask=layer_mask,
+ cache=layer_cache,
+ position_ids=position_ids,
+ position_embeddings=position_embeddings,
+ )
+ return self.norm(h)
+
+
+class LanguageModel(Qwen3VLLanguageModel):
+ def __init__(self, args: TextConfig, config=None):
+ nn.Module.__init__(self)
+ self.args = args
+ self.config = config
+ self.model_type = args.model_type
+ self.model = BailingMoeV3Model(args)
+ self._rope_deltas = None
+ self._position_ids = None
+ self.lm_head = (
+ None
+ if args.tie_word_embeddings
+ else nn.Linear(args.hidden_size, args.vocab_size, bias=False)
+ )
+
+ def get_rope_index(
+ self,
+ input_ids,
+ image_grid_thw=None,
+ video_grid_thw=None,
+ attention_mask=None,
+ ):
+ video_start = self.config.video_start_token_id
+ vision_start = self.config.vision_start_token_id
+ if video_start != vision_start:
+ input_ids = mx.where(input_ids == video_start, vision_start, input_ids)
+ return super().get_rope_index(
+ input_ids, image_grid_thw, video_grid_thw, attention_mask
+ )
+
+ def __call__(
+ self,
+ inputs,
+ inputs_embeds=None,
+ mask=None,
+ cache=None,
+ **kwargs,
+ ):
+ position_ids = kwargs.pop("position_ids", None)
+ pixel_values = kwargs.pop("pixel_values", None)
+ image_grid_thw = kwargs.pop("image_grid_thw", None)
+ video_grid_thw = kwargs.pop("video_grid_thw", None)
+ rope_deltas = kwargs.pop("rope_deltas", None)
+ if (
+ pixel_values is not None
+ or image_grid_thw is not None
+ or video_grid_thw is not None
+ ):
+ self._rope_deltas = None
+ self._position_ids = None
+ if rope_deltas is not None:
+ self._rope_deltas = rope_deltas
+
+ position_cache = next(
+ (item for item in cache or [] if isinstance(item, (KVCache, BatchKVCache))),
+ None,
+ )
+ cache_offset = 0
+ cache_offset_array = None
+ if position_cache is not None:
+ cache_offset = (
+ position_cache._idx
+ if hasattr(position_cache, "_idx")
+ else position_cache.offset
+ )
+ if (
+ isinstance(position_cache.offset, mx.array)
+ and position_cache.offset.ndim > 0
+ ):
+ cache_offset_array = position_cache.offset
+
+ if (
+ position_ids is not None
+ and cache_offset_array is None
+ and position_ids.shape[-1] > inputs.shape[-1]
+ ):
+ position_ids = position_ids[
+ ..., cache_offset : cache_offset + inputs.shape[-1]
+ ]
+
+ if position_ids is None:
+ if cache_offset == 0 or self._rope_deltas is None:
+ position_ids, new_deltas = self.get_rope_index(
+ inputs,
+ image_grid_thw,
+ video_grid_thw,
+ mask if mask is None or mask.ndim == 2 else None,
+ )
+ self._position_ids = position_ids
+ self._rope_deltas = new_deltas
+ else:
+ batch, length = inputs.shape
+ delta = self._rope_deltas[:batch]
+ position_ids = mx.arange(length).reshape(1, -1)
+ position_ids = mx.broadcast_to(position_ids, (batch, length))
+ position_ids = position_ids + cache_offset + delta
+ if self._position_ids is not None and self._position_ids.ndim == 3:
+ position_ids = mx.broadcast_to(
+ position_ids[None, ...], (3, batch, length)
+ )
+
+ out = self.model(
+ inputs,
+ inputs_embeds=inputs_embeds,
+ mask=mask,
+ cache=cache,
+ position_ids=position_ids,
+ visual_pos_masks=kwargs.get("visual_pos_masks"),
+ deepstack_visual_embeds=kwargs.get("deepstack_visual_embeds"),
+ )
+ logits = (
+ self.model.word_embeddings.as_linear(out)
+ if self.lm_head is None
+ else self.lm_head(out)
+ )
+ from ..base import LanguageModelOutput
+
+ return LanguageModelOutput(logits=logits)
+
+ def make_cache(self):
+ return [
+ ArraysCache(size=4) if kind == "kda" else KVCache()
+ for kind in self.args.layer_plan
+ ]
+
+ def sanitize(self, weights: dict[str, mx.array]) -> dict[str, mx.array]:
+ prefix = "language_model."
+ other = {
+ key: value for key, value in weights.items() if not key.startswith(prefix)
+ }
+ local = {
+ key[len(prefix) :]: value
+ for key, value in weights.items()
+ if key.startswith(prefix)
+ }
+ if self.args.tie_word_embeddings:
+ local.pop("lm_head.weight", None)
+
+ for layer_index, kind in enumerate(self.args.layer_plan):
+ base = f"model.layers.{layer_index}"
+ if layer_index >= self.args.first_k_dense_replace:
+ expert_re = re.compile(
+ rf"^{re.escape(base)}\.mlp\.experts\.(\d+)\."
+ r"(gate_proj|up_proj|down_proj)"
+ r"\.(weight|scales|biases|weight_scale_inv)$"
+ )
+ grouped = {}
+ for key in list(local):
+ match = expert_re.match(key)
+ if match:
+ expert, projection, suffix = match.groups()
+ grouped.setdefault((projection, suffix), {})[int(expert)] = key
+ for (projection, suffix), entries in grouped.items():
+ expected = set(range(self.args.num_experts))
+ found = set(entries)
+ if found != expected:
+ missing = sorted(expected - found)
+ extra = sorted(found - expected)
+ raise ValueError(
+ f"Incomplete expert set for {base} {projection}.{suffix}: "
+ f"missing={missing[:8]}, extra={extra[:8]}"
+ )
+ target = f"{base}.mlp.switch_mlp.{projection}.{suffix}"
+ if target in local:
+ raise ValueError(
+ f"Both stacked and per-expert weights exist: {target}"
+ )
+ local[target] = mx.stack(
+ [
+ local.pop(entries[index])
+ for index in range(self.args.num_experts)
+ ]
+ )
+
+ attention = f"{base}.attention"
+ if kind == "kda":
+ for name in ("q", "k", "v"):
+ source = f"{attention}.{name}_conv1d.weight"
+ target = f"{attention}.{name}_conv.conv.weight"
+ if source in local:
+ if target in local:
+ raise ValueError(
+ f"Both source and sanitized weights exist: {source}"
+ )
+ value = local.pop(source)
+ local[target] = (
+ value.moveaxis(2, 1) if value.ndim == 3 else value
+ )
+ for name in ("A_log", "dt_bias"):
+ key = f"{attention}.{name}"
+ if key in local and local[key].ndim > 1:
+ local[key] = local[key].reshape(-1)
+ else:
+ key = f"{attention}.kv_b_proj.weight"
+ if key in local:
+ targets = (
+ f"{attention}.embed_q.weight",
+ f"{attention}.unembed_out.weight",
+ )
+ if any(target in local for target in targets):
+ raise ValueError(
+ f"Both fused and absorbed MLA weights exist: {attention}"
+ )
+ scale_key = f"{attention}.kv_b_proj.scales"
+ bias_key = f"{attention}.kv_b_proj.biases"
+ quantized = scale_key in local
+ if bias_key in local and not quantized:
+ raise ValueError(f"Missing scales for {attention}.kv_b_proj")
+ value = local.pop(key)
+ bits = group_size = mode = None
+ if quantized:
+ scales = local.pop(scale_key)
+ biases = local.pop(bias_key, None)
+ bits = (value.shape[-1] * 32) // self.args.kv_lora_rank
+ group_size = self.args.kv_lora_rank // scales.shape[-1]
+ if biases is not None:
+ mode = "affine"
+ elif bits == 4:
+ mode = "mxfp4"
+ elif bits == 8:
+ mode = "mxfp8"
+ else:
+ raise ValueError(
+ f"Unsupported bias-free {bits}-bit quantized "
+ f"layout for {attention}.kv_b_proj"
+ )
+ value = mx.dequantize(
+ value,
+ scales,
+ biases,
+ bits=bits,
+ group_size=group_size,
+ mode=mode,
+ )
+ head_width = self.args.qk_nope_head_dim + self.args.v_head_dim
+ value = value.reshape(self.args.num_attention_heads, head_width, -1)
+ embed_q = mx.contiguous(
+ value[:, : self.args.qk_nope_head_dim].swapaxes(-1, -2)
+ )
+ unembed_out = mx.contiguous(value[:, self.args.qk_nope_head_dim :])
+ if quantized:
+ embed_quantized = mx.quantize(
+ embed_q, bits=bits, group_size=group_size, mode=mode
+ )
+ output_quantized = mx.quantize(
+ unembed_out, bits=bits, group_size=group_size, mode=mode
+ )
+ embed_q, embed_scales, *embed_biases = embed_quantized
+ unembed_out, out_scales, *out_biases = output_quantized
+ local[f"{attention}.embed_q.scales"] = embed_scales
+ local[f"{attention}.unembed_out.scales"] = out_scales
+ if embed_biases:
+ local[f"{attention}.embed_q.biases"] = embed_biases[0]
+ if out_biases:
+ local[f"{attention}.unembed_out.biases"] = out_biases[0]
+ local[f"{attention}.embed_q.weight"] = embed_q
+ local[f"{attention}.unembed_out.weight"] = unembed_out
+
+ local = convert_ling_fp8_weights(local)
+ other.update({f"{prefix}{key}": value for key, value in local.items()})
+ return other
+
+ @property
+ def quant_predicate(self):
+ def predicate(path, module):
+ if path.endswith(".gate"):
+ return False
+ if not (hasattr(module, "to_quantized") or isinstance(module, nn.Linear)):
+ return False
+ weight = getattr(module, "weight", None)
+ return weight is None or weight.shape[-1] % 32 == 0
+
+ return predicate
+
+ @property
+ def cast_predicate(self):
+ def predicate(path):
+ return not path.endswith(("A_log", "dt_bias", "expert_bias"))
+
+ return predicate
diff --git a/omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/models/bailing_moe_v3_vl/processing_bailing_moe_v3_vl.py b/omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/models/bailing_moe_v3_vl/processing_bailing_moe_v3_vl.py
new file mode 100644
index 0000000000..5cf3d7ab36
--- /dev/null
+++ b/omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/models/bailing_moe_v3_vl/processing_bailing_moe_v3_vl.py
@@ -0,0 +1,47 @@
+import re
+
+from ..qwen3_vl.processing_qwen3_vl import Qwen3VLProcessor
+
+
+class BailingMoeV3VLProcessor(Qwen3VLProcessor):
+ def __init__(self, image_processor, tokenizer, video_processor=None, **kwargs):
+ super().__init__(image_processor, tokenizer, video_processor, **kwargs)
+ self.video_start_token = (
+ getattr(tokenizer, "video_bos_token", None) or "<|video_start|>"
+ )
+ self.video_end_token = (
+ getattr(tokenizer, "video_eos_token", None) or "<|video_end|>"
+ )
+
+ def _normalize_media_wrappers(self, text):
+ if not isinstance(text, str):
+ return text
+
+ image_wrapper = (
+ self.vision_start_token + self.image_token + self.vision_end_token
+ )
+ text = re.sub(
+ re.escape(image_wrapper) + r"\n?",
+ image_wrapper + "\n",
+ text,
+ )
+
+ video_wrapper = self.video_start_token + self.video_token + self.video_end_token
+ qwen_video_wrapper = (
+ self.video_start_token
+ + self.vision_start_token
+ + self.video_token
+ + self.vision_end_token
+ + self.video_end_token
+ )
+ return text.replace(video_wrapper, qwen_video_wrapper)
+
+ def __call__(self, images=None, text=None, videos=None, **kwargs):
+ if isinstance(text, list):
+ text = [self._normalize_media_wrappers(sample) for sample in text]
+ else:
+ text = self._normalize_media_wrappers(text)
+ return super().__call__(images=images, text=text, videos=videos, **kwargs)
+
+
+__all__ = ["BailingMoeV3VLProcessor"]
diff --git a/omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/models/bailing_moe_v3_vl/vision.py b/omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/models/bailing_moe_v3_vl/vision.py
new file mode 100644
index 0000000000..f24068af1c
--- /dev/null
+++ b/omlx/patches/mlx_vlm_bailing_moe_v3_vl_compat/vendor/mlx_vlm/models/bailing_moe_v3_vl/vision.py
@@ -0,0 +1,46 @@
+import mlx.core as mx
+from mlx import nn
+
+from ..qwen3_vl.vision import (
+ PatchEmbed,
+ Qwen3VLMoEVisionBlock,
+ VisionRotaryEmbedding,
+)
+from ..qwen3_vl.vision import (
+ VisionModel as Qwen3VLVisionModel,
+)
+from .config import VisionConfig
+
+
+class PatchMerger(nn.Module):
+ def __init__(self, config: VisionConfig):
+ super().__init__()
+ self.packed_size = config.hidden_size * config.spatial_merge_size**2
+ self.norm = nn.LayerNorm(config.hidden_size, eps=1e-6)
+
+ def __call__(self, x: mx.array) -> mx.array:
+ return self.norm(x).reshape(-1, self.packed_size)
+
+
+class VisionModel(Qwen3VLVisionModel):
+ def __init__(self, config: VisionConfig):
+ nn.Module.__init__(self)
+ self.config = config
+ self.model_type = config.model_type
+ self.spatial_merge_size = config.spatial_merge_size
+ self.patch_embed = PatchEmbed(
+ patch_size=config.patch_size,
+ temporal_patch_size=config.temporal_patch_size,
+ in_channels=config.in_channels,
+ hidden_size=config.hidden_size,
+ )
+ head_dim = config.hidden_size // config.num_heads
+ self.rotary_pos_emb = VisionRotaryEmbedding(head_dim // 2)
+ self.pos_embed = nn.Embedding(
+ config.num_position_embeddings, config.hidden_size
+ )
+ self.num_grid_per_side = int(config.num_position_embeddings**0.5)
+ self.blocks = [Qwen3VLMoEVisionBlock(config) for _ in range(config.depth)]
+ self.merger = PatchMerger(config)
+ self.deepstack_visual_indexes = []
+ self.deepstack_merger_list = []
diff --git a/omlx/patches/mlx_vlm_inkling_compat/__init__.py b/omlx/patches/mlx_vlm_inkling_compat/__init__.py
index ee5326de17..2a0d73b614 100644
--- a/omlx/patches/mlx_vlm_inkling_compat/__init__.py
+++ b/omlx/patches/mlx_vlm_inkling_compat/__init__.py
@@ -6,6 +6,7 @@
import importlib
import json
import logging
+import sys
from pathlib import Path
from typing import Any
@@ -29,6 +30,7 @@ def apply_mlx_vlm_inkling_compat_patch() -> bool:
try:
_install_vendor_namespace()
_import_vendor_modules()
+ _patch_route_kernel()
import mlx_vlm.prompt_utils as prompt_utils
import mlx_vlm.utils as vlm_utils
@@ -68,11 +70,40 @@ def _append_package_path(package: Any, path: Path) -> None:
def _import_vendor_modules() -> None:
+ import mlx_vlm.models
+
+ module_prefix = f"mlx_vlm.models.{_MODULE_NAME}"
+ for module_name in tuple(sys.modules):
+ if module_name == module_prefix or module_name.startswith(f"{module_prefix}."):
+ del sys.modules[module_name]
+ if hasattr(mlx_vlm.models, _MODULE_NAME):
+ delattr(mlx_vlm.models, _MODULE_NAME)
+ importlib.invalidate_caches()
importlib.import_module("mlx_vlm.models.activations")
importlib.import_module("mlx_vlm.models.mlp")
importlib.import_module(f"mlx_vlm.models.{_MODULE_NAME}")
+def _patch_route_kernel() -> None:
+ import mlx.core as mx
+
+ language = importlib.import_module(f"mlx_vlm.models.{_MODULE_NAME}.language")
+ source = language._ROUTE_SRC
+ old = "const device T* lg = logits + (size_t)n * (R + SH);"
+ if old not in source:
+ return
+ # MLX places small inputs in Metal's constant address space.
+ language._ROUTE_SRC = source.replace(
+ old, "auto lg = logits + (size_t)n * (R + SH);"
+ )
+ language._route_kernel = mx.fast.metal_kernel(
+ name="omlx_inkling_moe_route",
+ input_names=["logits", "corr", "wscale"],
+ output_names=["idx", "wk", "gamma"],
+ source=language._ROUTE_SRC,
+ )
+
+
def _patch_model_remapping(vlm_utils: Any) -> None:
remapping = getattr(vlm_utils, "MODEL_REMAPPING", None)
if isinstance(remapping, dict):
diff --git a/omlx/patches/mlx_vlm_inkling_compat/vendor/mlx_vlm/models/inkling/README.md b/omlx/patches/mlx_vlm_inkling_compat/vendor/mlx_vlm/models/inkling/README.md
index c492ded9a7..6b6110e9a3 100644
--- a/omlx/patches/mlx_vlm_inkling_compat/vendor/mlx_vlm/models/inkling/README.md
+++ b/omlx/patches/mlx_vlm_inkling_compat/vendor/mlx_vlm/models/inkling/README.md
@@ -27,10 +27,9 @@ because oMLX pins transformers <5.13. Audio (dMel) extraction is not
implemented yet (text+vision first).
The sibling shims `../mlp.py`, `../switch_layers.py`, `../activations.py`
-are byte-identical copies from the same PR head; they do not exist at the
-oMLX mlx-vlm pin (`78b96eb`). The `__path__`-append install searches the
-real package first, so a future pin bump that ships any of these upstream
-automatically retires the vendored copy.
+were copied from the original PR head. The current mlx-vlm pin supplies the
+shared modules, while oMLX places only this vendored Inkling package first to
+retain its continuous-batching and mixed-quantization fixes.
Retire this whole package when the mlx-vlm pin advances past PR #1756's
merge (and transformers reaches 5.14+ for the processors).
diff --git a/omlx/patches/mlx_vlm_inkling_compat/vendor/mlx_vlm/models/inkling/language.py b/omlx/patches/mlx_vlm_inkling_compat/vendor/mlx_vlm/models/inkling/language.py
index 833cf93d50..e059cc7c62 100644
--- a/omlx/patches/mlx_vlm_inkling_compat/vendor/mlx_vlm/models/inkling/language.py
+++ b/omlx/patches/mlx_vlm_inkling_compat/vendor/mlx_vlm/models/inkling/language.py
@@ -558,7 +558,6 @@ def __call__(self, x, indices) -> mx.array:
uint lane = thread_position_in_grid.x;
uint n = thread_position_in_grid.y;
if (n >= N) return;
- auto lg = logits + (size_t)n * (R + SH);
float ws = wscale[0];
constexpr int PER = (R + 31) / 32;
float sc[PER];
@@ -568,7 +567,7 @@ def __call__(self, x, indices) -> mx.array:
uint j = lane + (uint)t * 32u;
taken[t] = false;
if (j < R) {
- float l = (float)lg[j];
+ float l = (float)logits[(size_t)n * (R + SH) + j];
tl_[t] = l;
sc[t] = 1.0f / (1.0f + metal::exp(-l)) + (float)corr[j];
} else {
@@ -591,7 +590,9 @@ def __call__(self, x, indices) -> mx.array:
float lp[K + SH];
float m = -INFINITY;
for (uint t = 0; t < K + SH; ++t) {
- float tv = (t < K) ? btl[t] : (float)lg[R + (t - K)];
+ float tv = (t < K)
+ ? btl[t]
+ : (float)logits[(size_t)n * (R + SH) + R + (t - K)];
float a = -tv;
float lad = metal::max(a, 0.0f)
+ metal::log(1.0f + metal::exp(-metal::fabs(a)));
diff --git a/omlx/patches/mlx_vlm_mtp/inkling_vlm_runtime.py b/omlx/patches/mlx_vlm_mtp/inkling_vlm_runtime.py
index be696acd52..4850da5dc5 100644
--- a/omlx/patches/mlx_vlm_mtp/inkling_vlm_runtime.py
+++ b/omlx/patches/mlx_vlm_mtp/inkling_vlm_runtime.py
@@ -265,10 +265,14 @@ def apply() -> bool:
logger.debug(f"inkling language module not importable: {e}")
return False
- _patch_model_config(inkling_pkg)
- _register_mtp_classes(inkling_lang)
- _patch_language_model(inkling_lang)
- _patch_inner_model_capture(inkling_lang)
+ try:
+ _patch_model_config(inkling_pkg)
+ _register_mtp_classes(inkling_lang)
+ _patch_language_model(inkling_lang)
+ _patch_inner_model_capture(inkling_lang)
+ except (AttributeError, ImportError) as e:
+ logger.debug(f"inkling runtime API is incompatible with MTP patch: {e}")
+ return False
# Shared VLMModelAdapter pass-throughs (idempotent).
from .qwen35_vlm_runtime import _patch_vlm_model_adapter
@@ -312,7 +316,11 @@ def patched_from_dict(cls_inner, params):
cls.from_dict = classmethod(patched_from_dict)
cls._omlx_mtp_from_dict_patched = True
- text_cls = inkling_pkg.TextConfig
+ text_cls = getattr(inkling_pkg, "TextConfig", None)
+ if text_cls is None:
+ from mlx_vlm.models.inkling.config import TextConfig
+
+ text_cls = TextConfig
if not getattr(text_cls, "_omlx_mtp_from_dict_patched", False):
original_text_from_dict = text_cls.from_dict.__func__
@@ -435,9 +443,6 @@ def __init__(self, config):
# (vLLM re-prefill equivalent). The generator's
# _mtp_head_trim_to no-ops on CacheList entries (no .offset).
self._omlx_mtp_head_clone = False
- # Row-wise batch MTP threads per-row extract/merge state the
- # multi-block window bookkeeping does not model.
- self._omlx_mtp_rowwise_unsupported = True
# The head normalizes its hidden input per block
# (chain_hidden_post_norm=false) — fold must NOT trunk-norm.
self._omlx_mtp_head_prenorm = True
diff --git a/omlx/patches/mlx_vlm_mtp/qwen35_moe_vlm_runtime.py b/omlx/patches/mlx_vlm_mtp/qwen35_moe_vlm_runtime.py
index ca54ec3c2a..d74ec1ad13 100644
--- a/omlx/patches/mlx_vlm_mtp/qwen35_moe_vlm_runtime.py
+++ b/omlx/patches/mlx_vlm_mtp/qwen35_moe_vlm_runtime.py
@@ -224,6 +224,9 @@ def __init__(self, args, config=None):
from . import is_mtp_attach_enabled
from ..mlx_lm_mtp import is_mtp_active
+ # Subclasses own their MTP wiring, as in the dense Qwen wrapper.
+ if type(self) is not cls:
+ 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
@@ -307,6 +310,11 @@ def __call__(self, inputs, inputs_embeds=None, mask=None, cache=None, **kwargs):
# both of which we need. Caller layers (block drafters) are merged
# with the head's last layer into one capture request.
requested = list(kwargs.pop("capture_layer_ids", None) or [])
+ exact_verify = getattr(self, "speculative_verify_logits", None)
+ if "_EXACT_SPECULATIVE_VERIFIER" in getattr(
+ exact_verify, "__globals__", {}
+ ):
+ kwargs["speculative_verify"] = True
last_layer_idx = len(self.model.layers) - 1
out = original_call(
self,
@@ -315,7 +323,6 @@ def __call__(self, inputs, inputs_embeds=None, mask=None, cache=None, **kwargs):
mask,
cache,
capture_layer_ids=sorted({*requested, last_layer_idx}),
- speculative_verify=True,
**kwargs,
)
from mlx_vlm.models.base import LanguageModelOutput
diff --git a/omlx/patches/mlx_vlm_mtp/qwen35_vlm_runtime.py b/omlx/patches/mlx_vlm_mtp/qwen35_vlm_runtime.py
index 63ee507be5..c8dfd2369f 100644
--- a/omlx/patches/mlx_vlm_mtp/qwen35_vlm_runtime.py
+++ b/omlx/patches/mlx_vlm_mtp/qwen35_vlm_runtime.py
@@ -281,8 +281,8 @@ def _patch_vlm_language_model(q35_lang: Any) -> None:
original_call = cls.__call__
def __init__(self, args, config=None):
- from . import is_mtp_attach_enabled
from ..mlx_lm_mtp import is_mtp_active
+ from . import is_mtp_attach_enabled
if type(self) is not cls:
# Subclasses (e.g. the qwen4_exp vendor LanguageModel, which
@@ -373,6 +373,10 @@ def __call__(self, inputs, inputs_embeds=None, mask=None, cache=None, **kwargs):
# both of which the MTP cycle needs. Caller layers (block drafters)
# are merged with the head's last layer into one capture request.
requested = list(kwargs.pop("capture_layer_ids", None) or [])
+ if "_EXACT_SPECULATIVE_VERIFIER" in getattr(
+ original_call, "__globals__", {}
+ ):
+ kwargs["speculative_verify"] = True
last_layer_idx = len(self.model.layers) - 1
out = original_call(
self,
@@ -381,7 +385,6 @@ def __call__(self, inputs, inputs_embeds=None, mask=None, cache=None, **kwargs):
mask,
cache,
capture_layer_ids=sorted({*requested, last_layer_idx}),
- speculative_verify=True,
**kwargs,
)
from mlx_vlm.models.base import LanguageModelOutput
@@ -445,21 +448,9 @@ def make_mtp_cache(self):
# Inner Qwen3_5Model — prompt-priming capture on prefill/decode forwards.
# ---------------------------------------------------------------------------
+
def _patch_inner_model_capture(q35_lang: Any) -> None:
- """Wrap ``Qwen3_5Model.__call__`` to fold prompt chunks into the MTP head.
-
- The inner model's return value is the trunk-normed hidden for every
- position of the forward — exactly what the head history fold needs — and
- scheduler prefill reaches it via the outer ``LanguageModel.__call__``
- delegate, so this single wrap covers external prefill, chunked prefill
- and the seam decode steps.
-
- Skips: image/recursive calls (``inputs_embeds``), MTP verify and other
- capture forwards (any of ``capture_layer_ids`` / ``hidden_sink`` /
- ``gdn_sink``), unknown extra positional call shapes, and hosts without
- an MTP head (weakref unset). All real gating lives in
- ``prompt_priming.maybe_capture`` and fails safe to unprimed.
- """
+ """Fold Qwen3.5/3.6 VLM prompt chunks into the native MTP head."""
cls = q35_lang.Qwen3_5Model
if getattr(cls, "_omlx_mtp_prime_capture_patched", False):
return
@@ -469,9 +460,7 @@ def _patch_inner_model_capture(q35_lang: Any) -> None:
def __call__(
self, inputs, inputs_embeds=None, mask=None, cache=None, *args, **kwargs
):
- out = original_call(
- self, inputs, inputs_embeds, mask, cache, *args, **kwargs
- )
+ out = original_call(self, inputs, inputs_embeds, mask, cache, *args, **kwargs)
if (
inputs_embeds is None
and cache is not None
diff --git a/omlx/patches/mlx_vlm_muse_glimmer_compat/__init__.py b/omlx/patches/mlx_vlm_muse_glimmer_compat/__init__.py
index a8273fa7e2..7ba03ea285 100644
--- a/omlx/patches/mlx_vlm_muse_glimmer_compat/__init__.py
+++ b/omlx/patches/mlx_vlm_muse_glimmer_compat/__init__.py
@@ -32,6 +32,8 @@ def apply_mlx_vlm_muse_glimmer_compat_patch() -> bool:
import mlx_vlm.prompt_utils as prompt_utils
_register_prompt_format(prompt_utils)
+ _patch_native_model()
+ _patch_dflash_model()
except Exception as exc: # noqa: BLE001
logger.debug("Muse Glimmer mlx-vlm compat patch failed: %s", exc)
return False
@@ -85,4 +87,67 @@ def _register_prompt_format(prompt_utils: Any) -> None:
model_config.setdefault(_MODEL_TYPE, placeholder)
+def _patch_native_model() -> None:
+ from mlx_vlm.models.muse_glimmer.muse_glimmer import Model
+
+ if not hasattr(Model, "encode_image") and hasattr(Model, "_encode_image"):
+ Model.encode_image = Model._encode_image
+
+
+def _patch_dflash_model() -> None:
+ try:
+ from dflash_mlx.models.muse_glimmer import Attention, DecoderLayer
+ from mlx_vlm.models.muse_glimmer.language import (
+ _finish_mlp,
+ _prepare_mlp_input,
+ )
+ from mlx_vlm.models.rope_utils import initialize_rope
+ except ImportError:
+ return
+ if getattr(DecoderLayer, "_omlx_mlx_vlm_parity", False):
+ return
+
+ original_attention_init = Attention.__init__
+
+ def attention_init(self, args, layer_idx):
+ original_attention_init(self, args, layer_idx)
+ theta = (
+ float(args.layer_rope_theta[layer_idx])
+ if self.use_rope
+ else float(args.rope_parameters.get("rope_theta", 500000.0))
+ )
+ self.rope = initialize_rope(
+ self.head_dim,
+ base=theta,
+ traditional=False,
+ scaling_config={"rope_type": "default", "rope_theta": theta},
+ max_position_embeddings=args.max_position_embeddings,
+ implementation="eager",
+ )
+
+ def __call__(self, x, mask=None, cache=None):
+ residual = x
+ attention_output = self.self_attn(
+ self.input_layernorm(x), mask=mask, cache=cache
+ )
+ residual, mlp_input = _prepare_mlp_input(
+ residual,
+ attention_output,
+ self.post_attention_layernorm.weight,
+ self.pre_feedforward_layernorm.weight,
+ self.post_attention_layernorm.eps,
+ self.pre_feedforward_layernorm.eps,
+ )
+ return _finish_mlp(
+ residual,
+ self.mlp(mlp_input),
+ self.post_feedforward_layernorm.weight,
+ self.post_feedforward_layernorm.eps,
+ )
+
+ Attention.__init__ = attention_init
+ DecoderLayer.__call__ = __call__
+ DecoderLayer._omlx_mlx_vlm_parity = True
+
+
__all__ = ["apply_mlx_vlm_muse_glimmer_compat_patch", "is_applied"]
diff --git a/omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/activations.py b/omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/activations.py
deleted file mode 100644
index 13c48d4b69..0000000000
--- a/omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/activations.py
+++ /dev/null
@@ -1,40 +0,0 @@
-from functools import partial
-
-import mlx.core as mx
-import mlx.nn as nn
-
-
-@partial(mx.compile, shapeless=True)
-def swiglu(gate, x):
- return nn.silu(gate) * x
-
-
-def xielu(x, alpha_p, alpha_n, beta, eps):
- alpha_p = nn.softplus(alpha_p)
- alpha_n = beta + nn.softplus(alpha_n)
- return mx.where(
- x > 0,
- alpha_p * mx.square(x) + beta * x,
- (mx.expm1(mx.minimum(x, eps)) - x) * alpha_n + beta * x,
- )
-
-
-class XieLU(nn.Module):
- def __init__(
- self,
- alpha_p_init=0.8,
- alpha_n_init=0.8,
- beta=0.5,
- eps=-1e-6,
- ):
- super().__init__()
- alpha_p_tensor = mx.array(alpha_p_init)
- alpha_n_tensor = mx.array(alpha_n_init - beta)
- self.alpha_p = mx.log(mx.exp(alpha_p_tensor) - 1)
- self.alpha_n = mx.log(mx.exp(alpha_n_tensor) - 1)
-
- self.beta = mx.array(beta)
- self.eps = mx.array(eps)
-
- def __call__(self, x: mx.array) -> mx.array:
- return xielu(x, self.alpha_p, self.alpha_n, self.beta, self.eps)
diff --git a/omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/muse_glimmer/README.md b/omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/muse_glimmer/README.md
deleted file mode 100644
index c58f88dad8..0000000000
--- a/omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/muse_glimmer/README.md
+++ /dev/null
@@ -1,48 +0,0 @@
-# Vendored mlx-vlm muse_glimmer (Meta Muse Glimmer 30B)
-
-Source: Blaizzy/mlx-vlm PR #1838 head (model package + prompt_utils
-registration; includes the CenteredRMSNorm FP32 operation-order fix from
-commits edfb0ef1 + 6242d295), plus upstream #1848 (reasoning config,
-`_prepare_mlp_input`/`_finish_mlp` norm fusions, FP32 `qk_scale_factor`
-math, plain `nn.Embedding` + separate weightless `embed_norm`) synced in
-2026-08-16 (vendor commit 3a82f856). Vendored because these PRs are newer
-than oMLX's mlx-vlm pin (`78b96eb`).
-
-## oMLX deltas against the PR head (marked with `oMLX:` comments)
-
-1. `language.py` — `initialize_rope` is imported from
- `mlx_lm.models.rope_utils` instead of `..rope_utils`: the pinned
- mlx-vlm rope_utils only carries MRoPE machinery. The mlx-lm signature
- matches the upstream call exactly (this is also why upstream's
- `implementation="eager"` is NOT adopted — mlx-lm's initialize_rope
- has no such parameter).
-2. `muse_glimmer.py` — public `encode_image()` alias for `_encode_image`
- so oMLX's vision feature cache can precompute/persist image features
- (`engine/vlm.py::_compute_vision_features` strategy 1).
-
-Upstream #1848 replaced the PR #1839 NormedEmbedding quantization
-workaround with the cleaner design we now carry: `embed_tokens` is a
-plain `nn.Embedding` and `embed_norm` is a separate weightless module, so
-quantizing the embedding can never drop the norm. `quant_predicate` was
-removed along with the wrapper.
-
-`../activations.py` is the same shared shim the inkling vendor carries
-(the pin has no `mlx_vlm.models.activations`); the two copies must stay
-byte-identical since whichever is imported first wins in `sys.modules`.
-
-## Pin-bump checklist
-
-When bumping the mlx-vlm pin past the upstream merge of PR #1838, the
-upstream module wins automatically (vendor path is searched last). Before
-deleting this vendor package, verify upstream carries:
-
-- [ ] the #1848 embed design (`nn.Embedding` + separate `embed_norm`);
- if absent, quantized checkpoints (oQ and community) load with
- silently broken logits (this is what the PR #1839 wrapper guarded)
-- [ ] an `encode_image` public method (or update
- `_compute_vision_features` probing); if absent, the vision feature
- cache silently no-ops for muse_glimmer
-- [ ] `initialize_rope` importable at the new pin (upstream imports it
- from `..rope_utils`, which needs a newer mlx-vlm than `78b96eb`)
-- [ ] `prompt_utils.MODEL_CONFIG["muse_glimmer"]` registered upstream
-- [ ] a real-model smoke test (text + image + quantized load)
diff --git a/omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/muse_glimmer/__init__.py b/omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/muse_glimmer/__init__.py
deleted file mode 100644
index 0bd4d7628b..0000000000
--- a/omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/muse_glimmer/__init__.py
+++ /dev/null
@@ -1,17 +0,0 @@
-from . import processing_muse_glimmer # noqa: F401
-from .config import ModelConfig, TextConfig, VisionConfig
-from .language import LanguageModel
-from .muse_glimmer import Model
-from .processing_muse_glimmer import MuseGlimmerImageProcessor, MuseGlimmerProcessor
-from .vision import VisionModel
-
-__all__ = [
- "LanguageModel",
- "Model",
- "ModelConfig",
- "MuseGlimmerImageProcessor",
- "MuseGlimmerProcessor",
- "TextConfig",
- "VisionConfig",
- "VisionModel",
-]
diff --git a/omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/muse_glimmer/config.py b/omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/muse_glimmer/config.py
deleted file mode 100644
index d609f5b69f..0000000000
--- a/omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/muse_glimmer/config.py
+++ /dev/null
@@ -1,129 +0,0 @@
-import inspect
-from dataclasses import dataclass, field
-from typing import Dict, List, Optional, Union
-
-from ..base import BaseModelConfig
-
-
-def _config_kwargs(config_cls, params):
- return {
- key: value
- for key, value in params.items()
- if key in inspect.signature(config_cls).parameters
- }
-
-
-@dataclass
-class VisionConfig(BaseModelConfig):
- model_type: str = "muse_glimmer_vision"
- patch_size: int = 14
- patch_temporal: int = 2
- merge_size: int = 2
- pos_emb_height: int = 32
- pos_emb_width: int = 32
- hidden_size: int = 1536
- intermediate_size: int = 8960
- num_attention_heads: int = 16
- num_hidden_layers: int = 50
- hidden_act: str = "gelu"
- layer_norm_eps: float = 1e-5
- max_position_embeddings: int = 1024
- rope_parameters: Optional[Dict] = None
- layer_types: Optional[List[str]] = None
-
- def __post_init__(self):
- if self.rope_parameters is None:
- self.rope_parameters = {"rope_theta": 10000.0, "rope_type": "default"}
- if self.layer_types is None:
- self.layer_types = [
- (
- "full_attention"
- if (idx + 1) % 4 == 0 or idx == self.num_hidden_layers - 1
- else "window_attention"
- )
- for idx in range(self.num_hidden_layers)
- ]
-
-
-@dataclass
-class TextConfig(BaseModelConfig):
- model_type: str = "muse_glimmer_text"
- vocab_size: int = 202048
- hidden_size: int = 6656
- intermediate_size: int = 19968
- num_hidden_layers: int = 52
- num_attention_heads: int = 32
- num_key_value_heads: int = 2
- head_dim: int = 128
- hidden_activation: str = "silu"
- max_position_embeddings: int = 131072
- rms_norm_eps: float = 1e-5
- post_norm_eps: float = 1e-8
- attention_bias: bool = False
- attention_dropout: float = 0.0
- sliding_window: int = 2048
- rope_parameters: Optional[Dict] = None
- layer_types: Optional[List[str]] = None
- layer_rope_theta: Optional[List[Union[int, float]]] = None
- qk_scale_factor: float = 3.87
- output_multiplier: float = 0.19611613513818404
- final_logit_softcapping: float = 20.0
- tie_word_embeddings: bool = False
- bos_token_id: Optional[int] = 200000
- eos_token_id: Optional[Union[int, List[int]]] = 200001
- pad_token_id: Optional[int] = None
-
- def __post_init__(self):
- if self.rope_parameters is None:
- self.rope_parameters = {"rope_theta": 500000.0, "rope_type": "default"}
- if self.layer_types is None:
- self.layer_types = [
- (
- "full_attention"
- if (self.num_hidden_layers - 1 - idx) % 4 == 0
- else "sliding_attention"
- )
- for idx in range(self.num_hidden_layers)
- ]
- if self.layer_rope_theta is None:
- theta = self.rope_parameters.get("rope_theta", 500000.0)
- self.layer_rope_theta = [
- 0 if layer_type == "full_attention" else theta
- for layer_type in self.layer_types
- ]
-
-
-@dataclass
-class ModelConfig(BaseModelConfig):
- text_config: TextConfig = field(default_factory=TextConfig)
- vision_config: VisionConfig = field(default_factory=VisionConfig)
- model_type: str = "muse_glimmer"
- image_token_id: int = 200092
- video_token_id: int = 200091
- out_hidden_size: int = 6144
- projector_hidden_size: int = 4096
- projector_hidden_act: str = "gelu"
- eos_token_id: Optional[Union[int, List[int]]] = None
- vocab_size: int = 202048
- thinking_start_token: str = "to=self<|message|>"
- thinking_end_token: str = "<|eom|>"
-
- def __post_init__(self):
- if self.eos_token_id is None:
- self.eos_token_id = self.text_config.eos_token_id
- self.vocab_size = self.text_config.vocab_size
-
- @classmethod
- def from_dict(cls, params):
- params = dict(params)
- text_config = params.get("text_config", {})
- vision_config = params.get("vision_config", {})
- if isinstance(text_config, dict):
- params["text_config"] = TextConfig(
- **_config_kwargs(TextConfig, text_config)
- )
- if isinstance(vision_config, dict):
- params["vision_config"] = VisionConfig(
- **_config_kwargs(VisionConfig, vision_config)
- )
- return cls(**_config_kwargs(cls, params))
diff --git a/omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/muse_glimmer/language.py b/omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/muse_glimmer/language.py
deleted file mode 100644
index 29f7806cf8..0000000000
--- a/omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/muse_glimmer/language.py
+++ /dev/null
@@ -1,313 +0,0 @@
-from typing import Any, Optional
-
-import mlx.core as mx
-import mlx.nn as nn
-
-from ..activations import swiglu
-from ..base import (
- LanguageModelOutput,
- create_attention_mask,
- scaled_dot_product_attention,
-)
-from ..cache import KVCache, RotatingKVCache
-
-# oMLX: the pinned mlx-vlm's rope_utils has no initialize_rope (only MRoPE
-# machinery); source it from mlx-lm, whose signature matches upstream usage.
-from mlx_lm.models.rope_utils import initialize_rope
-
-from .config import TextConfig
-
-
-@mx.compile
-def _centered_rms_norm(x: mx.array, weight: mx.array, eps: float) -> mx.array:
- dtype = x.dtype
- x = x.astype(mx.float32)
- variance = mx.mean(mx.square(x), axis=-1, keepdims=True)
- x = x * mx.rsqrt(variance + eps)
- x = x * (1.0 + weight.astype(mx.float32))
- return x.astype(dtype)
-
-
-@mx.compile
-def _prepare_mlp_input(
- residual: mx.array,
- attention_output: mx.array,
- post_attention_weight: mx.array,
- pre_feedforward_weight: mx.array,
- post_attention_eps: float,
- pre_feedforward_eps: float,
-) -> tuple[mx.array, mx.array]:
- hidden_states = residual + _centered_rms_norm(
- attention_output,
- post_attention_weight,
- post_attention_eps,
- )
- mlp_input = _centered_rms_norm(
- hidden_states,
- pre_feedforward_weight,
- pre_feedforward_eps,
- )
- return hidden_states, mlp_input
-
-
-@mx.compile
-def _finish_mlp(
- residual: mx.array,
- mlp_output: mx.array,
- post_feedforward_weight: mx.array,
- post_feedforward_eps: float,
-) -> mx.array:
- return residual + _centered_rms_norm(
- mlp_output,
- post_feedforward_weight,
- post_feedforward_eps,
- )
-
-
-class RMSNormNoScale(nn.Module):
- def __init__(self, eps: float):
- super().__init__()
- self.eps = eps
-
- def __call__(self, x: mx.array) -> mx.array:
- return mx.fast.rms_norm(x, None, self.eps)
-
-
-class CenteredRMSNorm(nn.Module):
- """RMSNorm whose checkpoint scale is centered at zero (effective scale 1+w)."""
-
- def __init__(self, dim: int, eps: float):
- super().__init__()
- self.weight = mx.zeros((dim,))
- self.eps = eps
-
- def __call__(self, x: mx.array) -> mx.array:
- # Transformers applies the centered scale in FP32 before casting back
- # to the activation dtype. Casting earlier changes BF16 decode choices.
- return _centered_rms_norm(x, self.weight, self.eps)
-
-
-class MLP(nn.Module):
- def __init__(self, args: TextConfig):
- super().__init__()
- self.gate_proj = nn.Linear(args.hidden_size, args.intermediate_size, bias=False)
- self.up_proj = nn.Linear(args.hidden_size, args.intermediate_size, bias=False)
- self.down_proj = nn.Linear(args.intermediate_size, args.hidden_size, bias=False)
-
- def __call__(self, x: mx.array) -> mx.array:
- return self.down_proj(swiglu(self.gate_proj(x), self.up_proj(x)))
-
-
-class Attention(nn.Module):
- def __init__(self, args: TextConfig, layer_idx: int):
- super().__init__()
- self.n_heads = args.num_attention_heads
- self.n_kv_heads = args.num_key_value_heads
- self.head_dim = args.head_dim
- self.scale = self.head_dim**-0.5
- self.qk_scale_factor = args.qk_scale_factor
- self.use_rope = bool(args.layer_rope_theta[layer_idx])
- self.is_sliding = args.layer_types[layer_idx] == "sliding_attention"
-
- dim = args.hidden_size
- self.q_proj = nn.Linear(
- dim, self.n_heads * self.head_dim, bias=args.attention_bias
- )
- self.k_proj = nn.Linear(
- dim, self.n_kv_heads * self.head_dim, bias=args.attention_bias
- )
- self.v_proj = nn.Linear(
- dim, self.n_kv_heads * self.head_dim, bias=args.attention_bias
- )
- self.gate_proj = nn.Linear(dim, self.n_heads * self.head_dim, bias=False)
- self.o_proj = nn.Linear(
- self.n_heads * self.head_dim, dim, bias=args.attention_bias
- )
- self.qk_norm = RMSNormNoScale(args.rms_norm_eps)
-
- theta = (
- float(args.layer_rope_theta[layer_idx])
- if self.use_rope
- else float(args.rope_parameters.get("rope_theta", 500000.0))
- )
- self.rope = initialize_rope(
- self.head_dim,
- base=theta,
- traditional=False,
- scaling_config={"rope_type": "default", "rope_theta": theta},
- max_position_embeddings=args.max_position_embeddings,
- )
-
- def __call__(
- self,
- x: mx.array,
- mask: Optional[mx.array] = None,
- cache: Optional[Any] = None,
- ) -> mx.array:
- batch, length, _ = x.shape
- queries = self.q_proj(x).reshape(batch, length, self.n_heads, self.head_dim)
- keys = self.k_proj(x).reshape(batch, length, self.n_kv_heads, self.head_dim)
- values = self.v_proj(x).reshape(batch, length, self.n_kv_heads, self.head_dim)
-
- queries = self.qk_norm(queries)
- queries = (queries.astype(mx.float32) * self.qk_scale_factor).astype(
- queries.dtype
- )
- queries = queries.transpose(0, 2, 1, 3)
- keys = self.qk_norm(keys).transpose(0, 2, 1, 3)
- values = values.transpose(0, 2, 1, 3)
-
- if self.use_rope:
- offset = cache.offset if cache is not None else 0
- queries = self.rope(queries, offset=offset)
- keys = self.rope(keys, offset=offset)
-
- if cache is not None:
- keys, values = cache.update_and_fetch(keys, values)
-
- output = scaled_dot_product_attention(
- queries,
- keys,
- values,
- cache=cache,
- scale=self.scale,
- mask=mask,
- )
- output = output.transpose(0, 2, 1, 3).reshape(batch, length, -1)
- output = output * mx.sigmoid(self.gate_proj(x))
- return self.o_proj(output)
-
-
-class DecoderLayer(nn.Module):
- def __init__(self, args: TextConfig, layer_idx: int):
- super().__init__()
- self.self_attn = Attention(args, layer_idx)
- self.mlp = MLP(args)
- self.input_layernorm = CenteredRMSNorm(args.hidden_size, args.rms_norm_eps)
- self.post_attention_layernorm = CenteredRMSNorm(
- args.hidden_size, args.post_norm_eps
- )
- self.pre_feedforward_layernorm = CenteredRMSNorm(
- args.hidden_size, args.rms_norm_eps
- )
- self.post_feedforward_layernorm = CenteredRMSNorm(
- args.hidden_size, args.post_norm_eps
- )
- self.is_sliding = args.layer_types[layer_idx] == "sliding_attention"
-
- def __call__(
- self,
- x: mx.array,
- mask: Optional[mx.array] = None,
- cache: Optional[Any] = None,
- ) -> mx.array:
- residual = x
- x = self.self_attn(self.input_layernorm(x), mask=mask, cache=cache)
- residual, mlp_input = _prepare_mlp_input(
- residual,
- x,
- self.post_attention_layernorm.weight,
- self.pre_feedforward_layernorm.weight,
- self.post_attention_layernorm.eps,
- self.pre_feedforward_layernorm.eps,
- )
- return _finish_mlp(
- residual,
- self.mlp(mlp_input),
- self.post_feedforward_layernorm.weight,
- self.post_feedforward_layernorm.eps,
- )
-
-
-class TextModel(nn.Module):
- def __init__(self, args: TextConfig):
- super().__init__()
- self.args = args
- self.embed_tokens = nn.Embedding(args.vocab_size, args.hidden_size)
- self.embed_norm = RMSNormNoScale(args.rms_norm_eps)
- self.layers = [DecoderLayer(args, idx) for idx in range(args.num_hidden_layers)]
- self.norm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps)
- self.layer_types = args.layer_types
- self.sliding_window = args.sliding_window
-
- self.full_attention_idx = self.layer_types.index("full_attention")
- self.sliding_attention_idx = (
- self.layer_types.index("sliding_attention")
- if "sliding_attention" in self.layer_types
- else None
- )
-
- def __call__(
- self,
- inputs: Optional[mx.array],
- cache=None,
- inputs_embeds: Optional[mx.array] = None,
- ) -> mx.array:
- hidden_states = inputs_embeds
- if hidden_states is None:
- hidden_states = self.embed_norm(self.embed_tokens(inputs))
- if cache is None:
- cache = [None] * len(self.layers)
-
- full_mask = create_attention_mask(hidden_states, cache[self.full_attention_idx])
- sliding_mask = None
- if self.sliding_attention_idx is not None:
- sliding_mask = create_attention_mask(
- hidden_states,
- cache[self.sliding_attention_idx],
- window_size=self.sliding_window,
- )
-
- for layer, layer_cache in zip(self.layers, cache):
- mask = sliding_mask if layer.is_sliding else full_mask
- hidden_states = layer(hidden_states, mask=mask, cache=layer_cache)
- return self.norm(hidden_states)
-
-
-class LanguageModel(nn.Module):
- def __init__(self, args: TextConfig):
- super().__init__()
- self.args = args
- self.config = args
- self.model_type = args.model_type
- self.model = TextModel(args)
- self.lm_head = nn.Linear(args.hidden_size, args.vocab_size, bias=False)
- self.final_logit_softcapping = args.final_logit_softcapping
- self.output_multiplier = args.output_multiplier
-
- def __call__(
- self,
- inputs: Optional[mx.array] = None,
- cache=None,
- inputs_embeds: Optional[mx.array] = None,
- **kwargs,
- ) -> LanguageModelOutput:
- if inputs is None:
- inputs = kwargs.get("input_ids")
- hidden_states = self.model(inputs, cache=cache, inputs_embeds=inputs_embeds)
- logits = self.lm_head(hidden_states) * self.output_multiplier
- softcap = self.final_logit_softcapping
- logits = mx.tanh(logits / softcap) * softcap
- return LanguageModelOutput(logits=logits)
-
- @property
- def layers(self):
- return self.model.layers
-
- @property
- def head_dim(self):
- return self.args.head_dim
-
- @property
- def n_kv_heads(self):
- return self.args.num_key_value_heads
-
- def make_cache(self):
- return [
- (
- RotatingKVCache(max_size=self.args.sliding_window)
- if layer.is_sliding
- else KVCache()
- )
- for layer in self.layers
- ]
diff --git a/omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/muse_glimmer/muse_glimmer.py b/omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/muse_glimmer/muse_glimmer.py
deleted file mode 100644
index f94cd1215f..0000000000
--- a/omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/muse_glimmer/muse_glimmer.py
+++ /dev/null
@@ -1,141 +0,0 @@
-from typing import Optional
-
-import mlx.core as mx
-import mlx.nn as nn
-
-from ..base import InputEmbeddingsFeatures
-from .config import ModelConfig
-from .language import LanguageModel, RMSNormNoScale
-from .vision import VisionModel, gelu
-
-
-def masked_scatter(input_tensor: mx.array, mask: mx.array, source: mx.array):
- shape = input_tensor.shape
- flat_input = input_tensor.flatten()
- flat_mask = mask.flatten()
- flat_input[flat_mask] = source.flatten()
- return flat_input.reshape(shape)
-
-
-class VisionAdapter(nn.Module):
- def __init__(self, config: ModelConfig):
- super().__init__()
- self.fc1 = nn.Linear(
- config.out_hidden_size, config.projector_hidden_size, bias=False
- )
- self.fc2 = nn.Linear(
- config.projector_hidden_size, config.projector_hidden_size, bias=False
- )
-
- def __call__(self, x: mx.array) -> mx.array:
- return gelu(self.fc2(gelu(self.fc1(x))))
-
-
-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)
- self.vision_tower = VisionModel(config.vision_config)
- self.vision_adapter = VisionAdapter(config)
- self.vision_projection = nn.Linear(
- config.projector_hidden_size,
- config.text_config.hidden_size,
- bias=False,
- )
- self.perception_emb_norm = RMSNormNoScale(config.text_config.rms_norm_eps)
-
- def _encode_image(self, pixel_values, image_grid_thw=None):
- if image_grid_thw is None:
- raise ValueError(
- "image_grid_thw is required to encode Muse Glimmer images."
- )
- dtype = self.vision_tower.patch_embedder.patch_embedding.weight.dtype
- features = self.vision_tower(pixel_values.astype(dtype), image_grid_thw)
- features = self.vision_adapter(features)
- features = self.vision_projection(features)
- return self.perception_emb_norm(features)
-
- # oMLX: public alias so oMLX's vision feature cache can precompute and
- # persist image features (engine/vlm.py::_compute_vision_features probes
- # for an `encode_image` attribute and replays them at generation time via
- # the `cached_image_features` kwarg of get_input_embeddings).
- def encode_image(self, pixel_values, image_grid_thw=None, **kwargs):
- return self._encode_image(pixel_values, image_grid_thw=image_grid_thw)
-
- def get_input_embeddings(
- self,
- input_ids: Optional[mx.array] = None,
- pixel_values: Optional[mx.array] = None,
- **kwargs,
- ):
- language_model = self.language_model.model
- inputs_embeds = language_model.embed_norm(
- language_model.embed_tokens(input_ids)
- )
- if pixel_values is None:
- pixel_values = kwargs.get("pixel_values_videos")
- if pixel_values is None:
- return InputEmbeddingsFeatures(inputs_embeds=inputs_embeds)
-
- grid_thw = kwargs.get("image_grid_thw")
- if grid_thw is None:
- grid_thw = kwargs.get("video_grid_thw")
- cached = kwargs.get("cached_image_features")
- image_features = (
- cached
- if cached is not None
- else self._encode_image(pixel_values, image_grid_thw=grid_thw)
- ).astype(inputs_embeds.dtype)
-
- token_mask = (input_ids == self.config.image_token_id) | (
- input_ids == self.config.video_token_id
- )
- expanded_mask = mx.broadcast_to(token_mask[..., None], inputs_embeds.shape)
- if int(token_mask.sum().item()) != image_features.shape[0]:
- raise ValueError(
- "Image features and image tokens do not match: "
- f"tokens={int(token_mask.sum().item())}, "
- f"features={image_features.shape[0]}"
- )
- inputs_embeds = masked_scatter(inputs_embeds, expanded_mask, image_features)
- return InputEmbeddingsFeatures(inputs_embeds=inputs_embeds)
-
- def __call__(
- self,
- input_ids: mx.array,
- pixel_values: Optional[mx.array] = None,
- mask: Optional[mx.array] = None,
- cache=None,
- **kwargs,
- ):
- embeddings = self.get_input_embeddings(
- input_ids=input_ids, pixel_values=pixel_values, **kwargs
- )
- return self.language_model(
- input_ids,
- cache=cache,
- inputs_embeds=embeddings.inputs_embeds,
- )
-
- @property
- def layers(self):
- return self.language_model.layers
-
- def make_cache(self):
- return self.language_model.make_cache()
-
- def sanitize(self, weights):
- sanitized = {}
- for key, value in weights.items():
- if "rotary_emb.inv_freq" in key:
- continue
- if key.startswith("model.language_model."):
- key = key.replace("model.language_model.", "language_model.model.", 1)
- elif key.startswith("model."):
- key = key[len("model.") :]
- elif key.startswith("lm_head."):
- key = "language_model." + key
- sanitized[key] = value
- return sanitized
diff --git a/omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/muse_glimmer/processing_muse_glimmer.py b/omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/muse_glimmer/processing_muse_glimmer.py
deleted file mode 100644
index a26a6350d4..0000000000
--- a/omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/muse_glimmer/processing_muse_glimmer.py
+++ /dev/null
@@ -1,249 +0,0 @@
-import itertools
-import json
-import math
-from pathlib import Path
-from typing import List, Optional, Union
-
-import numpy as np
-from PIL import Image
-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
-from .config import ModelConfig
-
-
-def smart_resize(height: int, width: int, patch_size: int, max_tokens: int):
- ideal_h = height / patch_size
- ideal_w = width / patch_size
- ratio = ideal_w / ideal_h if ideal_h > 0 else 1.0
- if ideal_h * ideal_w > max_tokens:
- ideal_h = math.sqrt(max_tokens / ratio)
- ideal_w = ideal_h * ratio
- candidates = set(
- itertools.product(
- (math.floor(ideal_h), math.ceil(ideal_h)),
- (math.floor(ideal_w), math.ceil(ideal_w)),
- )
- )
- candidates = [
- (h, w) for h, w in candidates if h >= 1 and w >= 1 and h * w <= max_tokens
- ]
- if not candidates:
- candidates = [(max(1, round(ideal_h)), max(1, round(ideal_w)))]
- patch_h, patch_w = min(
- candidates, key=lambda grid: abs(grid[0] / grid[1] - height / width)
- )
- return patch_h * patch_size, patch_w * patch_size
-
-
-def _to_pil(image):
- if isinstance(image, (str, Path)):
- image = Image.open(image)
- if isinstance(image, Image.Image):
- return image.convert("RGB")
- array = np.asarray(image)
- if array.ndim == 3 and array.shape[0] in (1, 3, 4):
- array = np.transpose(array, (1, 2, 0))
- if array.dtype != np.uint8:
- if array.max() <= 1.0:
- array = array * 255.0
- array = np.clip(array, 0, 255).astype(np.uint8)
- return Image.fromarray(array).convert("RGB")
-
-
-class MuseGlimmerImageProcessor(ImageProcessingMixin):
- model_input_names = ["pixel_values", "image_grid_thw"]
-
- def __init__(
- self,
- patch_size: int = 14,
- temporal_patch_size: int = 2,
- merge_size: int = 2,
- max_image_tokens: int = 4096,
- image_mean: Optional[List[float]] = None,
- image_std: Optional[List[float]] = None,
- rescale_factor: float = 1 / 255.0,
- **kwargs,
- ):
- self.patch_size = patch_size
- self.temporal_patch_size = temporal_patch_size
- self.merge_size = merge_size
- self.max_image_tokens = max_image_tokens
- self.image_mean = image_mean or [0.5, 0.5, 0.5]
- self.image_std = image_std or [0.5, 0.5, 0.5]
- self.rescale_factor = rescale_factor
-
- def _process_one(self, image):
- image = _to_pil(image)
- width, height = image.size
- resized_h, resized_w = smart_resize(
- height,
- width,
- self.patch_size * self.merge_size,
- self.max_image_tokens,
- )
- image = image.resize((resized_w, resized_h), resample=Image.Resampling.LANCZOS)
- array = np.asarray(image, dtype=np.float32).transpose(2, 0, 1)
- array *= self.rescale_factor
- mean = np.asarray(self.image_mean, dtype=np.float32)[:, None, None]
- std = np.asarray(self.image_std, dtype=np.float32)[:, None, None]
- array = (array - mean) / std
-
- channels = array.shape[0]
- grid_h = resized_h // self.patch_size
- grid_w = resized_w // self.patch_size
- patches = array.reshape(
- channels,
- grid_h,
- self.patch_size,
- grid_w,
- self.patch_size,
- ).transpose(1, 3, 0, 2, 4)
- patches = np.repeat(patches[:, :, None, ...], self.temporal_patch_size, axis=2)
- patches = patches.reshape(
- grid_h * grid_w,
- self.temporal_patch_size * channels * self.patch_size * self.patch_size,
- )
- return patches, [1, grid_h, grid_w]
-
- def __call__(self, images, **kwargs):
- if not isinstance(images, list):
- images = [images]
- processed = [self._process_one(image) for image in images]
- return {
- "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
- ),
- }
-
- def preprocess(self, images, **kwargs):
- return self(images, **kwargs)
-
-
-class MuseGlimmerProcessor(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,
- config=None,
- **kwargs,
- ):
- self.image_token = "<|patch|>"
- self.image_start_token = "<|image_start|>"
- self.image_end_token = "<|image_end|>"
- self.video_token = "<|video|>"
- self.image_token_id = tokenizer.convert_tokens_to_ids(self.image_token)
- super().__init__(
- image_processor, tokenizer, chat_template=chat_template, **kwargs
- )
- self.config = config
-
- def __call__(
- self,
- images=None,
- text: Optional[Union[str, List[str]]] = None,
- **kwargs,
- ):
- image_inputs = {}
- if images is not None:
- image_inputs = self.image_processor(images=images)
-
- if not isinstance(text, list):
- text = [text]
- text = list(text)
- if images is not None:
- grids = image_inputs["image_grid_thw"]
- merge_length = self.image_processor.merge_size**2
- image_idx = 0
- for prompt_idx, prompt in enumerate(text):
- while self.image_token in prompt:
- count = int(np.prod(grids[image_idx]) // merge_length)
- replacement = (
- self.image_start_token
- + "<|image_placeholder|>" * count
- + self.image_end_token
- )
- text[prompt_idx] = text[prompt_idx].replace(
- self.image_token, replacement, 1
- )
- prompt = text[prompt_idx]
- image_idx += 1
- text[prompt_idx] = text[prompt_idx].replace(
- "<|image_placeholder|>", self.image_token
- )
-
- return_tensors = kwargs.pop("return_tensors", None)
- text_inputs = self.tokenizer(text, **kwargs)
- data = to_mlx({**text_inputs, **image_inputs})
- return BatchFeature(data=data, tensor_type=return_tensors)
-
- def batch_decode(self, *args, **kwargs):
- return self.tokenizer.batch_decode(*args, **kwargs)
-
- def decode(self, *args, **kwargs):
- return self.tokenizer.decode(*args, **kwargs)
-
- @property
- def model_input_names(self):
- return list(
- dict.fromkeys(
- self.tokenizer.model_input_names
- + self.image_processor.model_input_names
- )
- )
-
- @classmethod
- def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
- from transformers import AutoTokenizer, PreTrainedConfig
-
- kwargs.pop("use_fast", None)
- kwargs.pop("trust_remote_code", None)
- model_config = kwargs.pop("config", None)
- tokenizer = AutoTokenizer.from_pretrained(
- pretrained_model_name_or_path, **kwargs
- )
- load_chat_template(tokenizer, pretrained_model_name_or_path)
-
- if model_config is None:
- config_dict, _ = PreTrainedConfig.get_config_dict(
- pretrained_model_name_or_path, **kwargs
- )
- model_config = ModelConfig.from_dict(config_dict)
- elif isinstance(model_config, dict):
- model_config = ModelConfig.from_dict(model_config)
-
- config_path = Path(pretrained_model_name_or_path) / "processor_config.json"
- processor_config = (
- json.loads(config_path.read_text()) if config_path.exists() else {}
- )
- image_config = processor_config.get("image_processor", processor_config)
- image_processor = MuseGlimmerImageProcessor(
- patch_size=image_config.get("patch_size", 14),
- temporal_patch_size=image_config.get("temporal_patch_size", 2),
- merge_size=image_config.get("merge_size", 2),
- max_image_tokens=image_config.get("max_image_tokens", 4096),
- image_mean=image_config.get("image_mean", [0.5, 0.5, 0.5]),
- image_std=image_config.get("image_std", [0.5, 0.5, 0.5]),
- rescale_factor=image_config.get("rescale_factor", 1 / 255.0),
- )
- return cls(
- image_processor=image_processor,
- tokenizer=tokenizer,
- chat_template=getattr(tokenizer, "chat_template", None),
- config=model_config,
- )
-
-
-install_auto_processor_patch("muse_glimmer", MuseGlimmerProcessor)
diff --git a/omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/muse_glimmer/vision.py b/omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/muse_glimmer/vision.py
deleted file mode 100644
index 6165fe30a0..0000000000
--- a/omlx/patches/mlx_vlm_muse_glimmer_compat/vendor/mlx_vlm/models/muse_glimmer/vision.py
+++ /dev/null
@@ -1,313 +0,0 @@
-from functools import partial
-from typing import List, Optional, Sequence
-
-import mlx.core as mx
-import mlx.nn as nn
-import numpy as np
-
-from ..base import ensure_fused_sdpa
-from .config import VisionConfig
-
-
-def rotate_half(x: mx.array) -> mx.array:
- half = x.shape[-1] // 2
- return mx.concatenate((-x[..., half:], x[..., :half]), axis=-1)
-
-
-@partial(mx.compile, shapeless=True)
-def _apply_rotary(
- q: mx.array,
- k: mx.array,
- rotated_q: mx.array,
- rotated_k: mx.array,
- cos: mx.array,
- sin: mx.array,
-):
- cos = mx.expand_dims(cos, (0, 2)).astype(mx.float32)
- sin = mx.expand_dims(sin, (0, 2)).astype(mx.float32)
- q_dtype, k_dtype = q.dtype, k.dtype
- q = q.astype(mx.float32)
- k = k.astype(mx.float32)
- rotated_q = rotated_q.astype(mx.float32)
- rotated_k = rotated_k.astype(mx.float32)
- q = (q * cos + rotated_q * sin).astype(q_dtype)
- k = (k * cos + rotated_k * sin).astype(k_dtype)
- return q, k
-
-
-def apply_rotary(q: mx.array, k: mx.array, cos: mx.array, sin: mx.array):
- return _apply_rotary(q, k, rotate_half(q), rotate_half(k), cos, sin)
-
-
-@partial(mx.compile, shapeless=True)
-def gelu(x: mx.array) -> mx.array:
- return nn.gelu(x)
-
-
-def _cu_seqlens(grid: Sequence[Sequence[int]]) -> List[int]:
- lengths: List[int] = []
- for temporal, height, width in grid:
- lengths.extend([int(height) * int(width)] * int(temporal))
- return [0] + np.cumsum(lengths).tolist()
-
-
-def _window_index(
- grid: Sequence[Sequence[int]], window_size: int
-) -> tuple[Optional[mx.array], List[int]]:
- indices = []
- cumulative = [0]
- offset = 0
- for temporal, height, width in grid:
- temporal, height, width = int(temporal), int(height), int(width)
- index = np.arange(temporal * height * width).reshape(temporal, height, width)
- pad_h = (-height) % window_size
- pad_w = (-width) % window_size
- n_h = (height + pad_h) // window_size
- n_w = (width + pad_w) // window_size
- padded = np.pad(
- index,
- ((0, 0), (0, pad_h), (0, pad_w)),
- constant_values=-100,
- )
- padded = padded.reshape(temporal, n_h, window_size, n_w, window_size).transpose(
- 0, 1, 3, 2, 4
- )
- lengths = (padded != -100).sum(axis=(3, 4)).reshape(-1)
- flattened = padded.reshape(-1)
- indices.append(flattened[flattened != -100] + offset)
- for length in lengths:
- cumulative.append(cumulative[-1] + int(length))
- offset += temporal * height * width
-
- cumulative = np.asarray(cumulative, dtype=np.int32)
- keep = np.concatenate(([True], cumulative[1:] != cumulative[:-1]))
- indices = np.concatenate(indices).astype(np.int32, copy=False)
- identity = np.array_equal(indices, np.arange(indices.size, dtype=np.int32))
- window_index = None if identity else mx.array(indices, dtype=mx.int32)
- return window_index, cumulative[keep].tolist()
-
-
-def _position_ids(grid: Sequence[Sequence[int]]) -> mx.array:
- result = []
- for temporal, height, width in grid:
- temporal, height, width = int(temporal), int(height), int(width)
- rows, cols = np.meshgrid(np.arange(height), np.arange(width), indexing="ij")
- # Reference order after flip(-1) + 1 is (width, height), one-indexed.
- coords = np.stack((cols.reshape(-1), rows.reshape(-1)), axis=-1) + 1
- result.append(np.tile(coords, (temporal, 1)))
- return mx.array(np.concatenate(result), dtype=mx.int32)
-
-
-class PatchEmbedder(nn.Module):
- def __init__(self, config: VisionConfig):
- super().__init__()
- patch_dim = config.patch_temporal * 3 * config.patch_size**2
- self.patch_embedding = nn.Linear(patch_dim, config.hidden_size, bias=False)
- self.position_embedding_table = nn.Embedding(
- config.pos_emb_height * config.pos_emb_width, config.hidden_size
- )
- self.num_grid_per_side = config.pos_emb_height
-
- def _position_embeddings(self, grid: Sequence[Sequence[int]]) -> mx.array:
- side = self.num_grid_per_side
- all_indices = [[] for _ in range(4)]
- all_weights = [[] for _ in range(4)]
-
- for temporal, height, width in grid:
- temporal, height, width = int(temporal), int(height), int(width)
- h_grid = (np.arange(height, dtype=np.float32) + 0.5) * (side / height) - 0.5
- w_grid = (np.arange(width, dtype=np.float32) + 0.5) * (side / width) - 0.5
- h0, w0 = (
- np.floor(h_grid).astype(np.int32),
- np.floor(w_grid).astype(np.int32),
- )
- h1, w1 = h0 + 1, w0 + 1
- dh, dw = h_grid - h0, w_grid - w0
- vh0, vh1 = (h0 >= 0) & (h0 < side), (h1 >= 0) & (h1 < side)
- vw0, vw1 = (w0 >= 0) & (w0 < side), (w1 >= 0) & (w1 < side)
- h0, h1 = np.clip(h0, 0, side - 1), np.clip(h1, 0, side - 1)
- w0, w1 = np.clip(w0, 0, side - 1), np.clip(w1, 0, side - 1)
-
- indices = [
- (h0[:, None] * side + w0[None, :]).reshape(-1),
- (h0[:, None] * side + w1[None, :]).reshape(-1),
- (h1[:, None] * side + w0[None, :]).reshape(-1),
- (h1[:, None] * side + w1[None, :]).reshape(-1),
- ]
- weights = [
- (
- (1 - dh)[:, None]
- * (1 - dw)[None, :]
- * (vh0[:, None] & vw0[None, :])
- ).reshape(-1),
- (
- (1 - dh)[:, None] * dw[None, :] * (vh0[:, None] & vw1[None, :])
- ).reshape(-1),
- (
- dh[:, None] * (1 - dw)[None, :] * (vh1[:, None] & vw0[None, :])
- ).reshape(-1),
- (dh[:, None] * dw[None, :] * (vh1[:, None] & vw1[None, :])).reshape(-1),
- ]
- for idx in range(4):
- all_indices[idx].append(np.tile(indices[idx], temporal))
- all_weights[idx].append(np.tile(weights[idx], temporal))
-
- indices = mx.array(
- np.stack([np.concatenate(part) for part in all_indices]),
- dtype=mx.int32,
- )
- weights = mx.array(
- np.stack([np.concatenate(part) for part in all_weights]),
- dtype=mx.float32,
- )
- table = self.position_embedding_table(indices)
- return mx.sum(table * weights[..., None], axis=0)
-
- def __call__(
- self, pixel_values: mx.array, grid: Sequence[Sequence[int]]
- ) -> mx.array:
- embeddings = self.patch_embedding(pixel_values)
- positions = self._position_embeddings(grid).astype(embeddings.dtype)
- return embeddings + positions
-
-
-class VisionAttention(nn.Module):
- def __init__(self, config: VisionConfig):
- super().__init__()
- self.num_heads = config.num_attention_heads
- self.head_dim = config.hidden_size // config.num_attention_heads
- self.scale = self.head_dim**-0.5
- self.q_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=True)
- self.k_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=True)
- self.v_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=True)
- self.proj = nn.Linear(config.hidden_size, config.hidden_size, bias=True)
-
- def __call__(
- self,
- hidden_states: mx.array,
- split_points: List[int],
- cos: mx.array,
- sin: mx.array,
- ) -> mx.array:
- length = hidden_states.shape[0]
- q = self.q_proj(hidden_states).reshape(1, length, self.num_heads, -1)
- k = self.k_proj(hidden_states).reshape(1, length, self.num_heads, -1)
- v = self.v_proj(hidden_states).reshape(1, length, self.num_heads, -1)
- q, k = apply_rotary(q, k, cos, sin)
- q, k, v = (tensor.transpose(0, 2, 1, 3) for tensor in (q, k, v))
-
- if split_points:
- chunks = [mx.split(tensor, split_points, axis=2) for tensor in (q, k, v)]
- output = mx.concatenate(
- [
- ensure_fused_sdpa(q_chunk, k_chunk, v_chunk, self.scale)
- for q_chunk, k_chunk, v_chunk in zip(*chunks)
- ],
- axis=2,
- )
- else:
- output = ensure_fused_sdpa(q, k, v, self.scale)
- output = output.transpose(0, 2, 1, 3).reshape(length, -1)
- return self.proj(output)
-
-
-class VisionMLP(nn.Module):
- def __init__(self, config: VisionConfig):
- super().__init__()
- self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size, bias=True)
- self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size, bias=True)
-
- def __call__(self, x: mx.array) -> mx.array:
- return self.fc2(gelu(self.fc1(x)))
-
-
-class VisionBlock(nn.Module):
- def __init__(self, config: VisionConfig):
- super().__init__()
- self.norm1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
- self.norm2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
- self.attn = VisionAttention(config)
- self.mlp = VisionMLP(config)
-
- def __call__(self, x, split_points, cos, sin):
- x = x + self.attn(self.norm1(x), split_points, cos, sin)
- return x + self.mlp(self.norm2(x))
-
-
-class VisionModel(nn.Module):
- def __init__(self, config: VisionConfig):
- super().__init__()
- self.config = config
- self.patch_embedder = PatchEmbedder(config)
- self.ln_pre = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
- self.layers = [VisionBlock(config) for _ in range(config.num_hidden_layers)]
- self.ln_post = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
-
- head_dim = config.hidden_size // config.num_attention_heads
- spatial_dim = head_dim // 2
- self.rope_theta = float(config.rope_parameters.get("rope_theta", 10000.0))
- self.rope_spatial_dim = spatial_dim
-
- def _rotary(self, position_ids: mx.array):
- inv_freq = 1.0 / (
- self.rope_theta
- ** (
- mx.arange(0, self.rope_spatial_dim, 2, dtype=mx.float32)
- / self.rope_spatial_dim
- )
- )
- width = position_ids[:, 0].astype(mx.float32)
- height = position_ids[:, 1].astype(mx.float32)
- freq_w = width[:, None] * inv_freq[None, :]
- freq_h = height[:, None] * inv_freq[None, :]
- freqs = mx.concatenate((freq_w, freq_h, freq_w, freq_h), axis=-1)
- return mx.cos(freqs), mx.sin(freqs)
-
- def _pixel_shuffle(self, hidden_states: mx.array, grid: Sequence[Sequence[int]]):
- merge = self.config.merge_size
- dim = hidden_states.shape[-1]
- outputs = []
- offset = 0
- for temporal, height, width in grid:
- temporal, height, width = int(temporal), int(height), int(width)
- count = temporal * height * width
- chunk = hidden_states[offset : offset + count]
- chunk = chunk.reshape(temporal, height, width, dim)
- chunk = chunk.reshape(
- temporal,
- height // merge,
- merge,
- width // merge,
- merge,
- dim,
- ).transpose(0, 1, 3, 5, 2, 4)
- outputs.append(chunk.reshape(-1, dim * merge * merge))
- offset += count
- return mx.concatenate(outputs, axis=0)
-
- def __call__(self, pixel_values: mx.array, grid_thw: mx.array) -> mx.array:
- grid = grid_thw.tolist()
- full_split_points = _cu_seqlens(grid)[1:-1]
- window_side = self.config.pos_emb_height
- window_index, window_cu = _window_index(grid, window_side)
- window_split_points = window_cu[1:-1]
-
- hidden_states = self.ln_pre(self.patch_embedder(pixel_values, grid))
- positions = _position_ids(grid)
- if window_index is not None:
- hidden_states = hidden_states[window_index]
- positions = positions[window_index]
- cos, sin = self._rotary(positions)
-
- for idx, block in enumerate(self.layers):
- split_points = (
- full_split_points
- if self.config.layer_types[idx] == "full_attention"
- else window_split_points
- )
- hidden_states = block(hidden_states, split_points, cos, sin)
-
- if window_index is not None:
- hidden_states = hidden_states[mx.argsort(window_index)]
- hidden_states = self.ln_post(hidden_states)
- return self._pixel_shuffle(hidden_states, grid)
diff --git a/omlx/patches/mlx_vlm_pixtral_torch_free/vendor/__init__.py b/omlx/patches/mlx_vlm_pixtral_torch_free/vendor/__init__.py
deleted file mode 100644
index b375cf3b66..0000000000
--- a/omlx/patches/mlx_vlm_pixtral_torch_free/vendor/__init__.py
+++ /dev/null
@@ -1,7 +0,0 @@
-"""Vendored mlx-vlm files from upstream commit e3fec79 (PR #1502).
-
-Source: https://github.com/Blaizzy/mlx-vlm (MIT License,
-Copyright 2025 Prince Canuma). image_processing_pixtral.py is an exact
-copy; the two processing modules carry small omlx-marked adjustments
-(import paths, tokenizer backend kwarg, registration removal).
-"""
diff --git a/omlx/patches/mlx_vlm_qwen4_exp_compat/__init__.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/__init__.py
index b580b92b28..fa1b878b65 100644
--- a/omlx/patches/mlx_vlm_qwen4_exp_compat/__init__.py
+++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/__init__.py
@@ -5,6 +5,7 @@
import importlib
import logging
+import sys
from pathlib import Path
from typing import Any
@@ -37,6 +38,15 @@ def apply_mlx_vlm_qwen4_exp_compat_patch() -> bool:
_append_package_path(mlx_vlm, _VENDOR_MLX_VLM)
_append_package_path(mlx_vlm.models, _VENDOR_MLX_VLM / "models")
+ module_prefix = "mlx_vlm.models.qwen4_exp"
+ for module_name in tuple(sys.modules):
+ if module_name == module_prefix or module_name.startswith(
+ f"{module_prefix}."
+ ):
+ del sys.modules[module_name]
+ if hasattr(mlx_vlm.models, "qwen4_exp"):
+ delattr(mlx_vlm.models, "qwen4_exp")
+ importlib.invalidate_caches()
importlib.import_module("mlx_vlm.models.qwen4_exp")
from mlx_vlm.models.qwen3_5 import language as qwen35_language
@@ -108,16 +118,24 @@ def get_message_json(model_type, *args, **kwargs):
def _ple_prefetch_hook(model):
- hook = getattr(model, "prefetch_ple", None)
- if hook is None:
- hook = getattr(getattr(model, "language_model", None), "prefetch_ple", None)
- return hook
+ language_model = getattr(model, "_language_model", None)
+ if language_model is None:
+ language_model = getattr(model, "language_model", None)
+ if language_model is not None:
+ return getattr(language_model, "prefetch_ple", None)
+ return getattr(model, "prefetch_ple", None)
+
+
+_BASE_PROMPT_LOOP = None
def _prompt_with_ple_lookahead(self, tokens):
"""mlx_lm's PromptProcessingBatch.prompt, telling the model the next chunk before each one."""
from mlx_lm.generate import _right_pad_prompts
+ hook = _ple_prefetch_hook(self.model)
+ if hook is None:
+ return _BASE_PROMPT_LOOP(self, tokens)
if len(self.uids) != len(tokens):
raise ValueError("The batch length doesn't match the number of inputs")
if not tokens:
@@ -134,7 +152,6 @@ def _prompt_with_ple_lookahead(self, tokens):
c.prepare(lengths=lengths, right_padding=padding)
else:
tokens = mx.array(tokens)
- hook = _ple_prefetch_hook(self.model)
while tokens.shape[1] > 0:
n_to_process = min(self.prefill_step_size, tokens.shape[1])
if hook is not None and tokens.shape[1] > n_to_process:
@@ -152,12 +169,16 @@ def _prompt_with_ple_lookahead(self, tokens):
def _patch_prompt_loop() -> None:
"""Install the lookahead loop as the base of the scheduler's prompt wrapper, or as prompt() itself."""
+ global _BASE_PROMPT_LOOP
+
from mlx_lm.generate import PromptProcessingBatch
_prompt_with_ple_lookahead._omlx_ple_lookahead = True
if hasattr(PromptProcessingBatch, "_omlx_base_prompt"):
+ _BASE_PROMPT_LOOP = PromptProcessingBatch._omlx_base_prompt
PromptProcessingBatch._omlx_base_prompt = _prompt_with_ple_lookahead
elif not getattr(PromptProcessingBatch.prompt, "_omlx_ple_lookahead", False):
+ _BASE_PROMPT_LOOP = PromptProcessingBatch.prompt
PromptProcessingBatch.prompt = _prompt_with_ple_lookahead
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 b36a20e999..419a6e15cf 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,3 +1,4 @@
+# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import json
@@ -3374,7 +3375,7 @@ def _ple_require_owner(owner_pid=None):
class _SafeTensorMMap:
- """Read selected dense or affine-packed rows without resident weights."""
+ """Read selected dense or quantized rows without resident weights."""
def __init__(self, path: Path):
_ple_require_owner()
@@ -3434,6 +3435,7 @@ def _rows_np_owned(self, key, rows):
"F16": (np.dtype(" _SafeTensorMMap:
None,
None,
None,
+ None,
)
continue
- if scales_key not in weight_map or biases_key not in weight_map:
+ if scales_key not in weight_map:
raise ValueError(
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"Quantized Qwen4 PLE weight must be U32, got {weight_dtype} "
f"for {weight_key}"
)
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:
+ scales_dtype = scales_reader.tensor_dtype(scales_key)
+ mode = "affine"
+ if biases_key in weight_map:
+ biases_reader = register_reader(biases_key)
+ biases_shape = biases_reader.tensor_shape(biases_key)
+ biases_dtype = biases_reader.tensor_dtype(biases_key)
+ if scales_shape != biases_shape:
+ raise ValueError(
+ f"Invalid affine PLE parameter shapes for {base}: "
+ f"scales={scales_shape}, biases={biases_shape}"
+ )
+ if (
+ scales_dtype not in {"BF16", "F16", "F32"}
+ or biases_dtype not in {"BF16", "F16", "F32"}
+ ):
+ raise TypeError(
+ f"Affine PLE scales and biases must have float dtypes "
+ f"for {base}: scales={scales_dtype}, biases={biases_dtype}"
+ )
+ elif scales_dtype == "U8":
+ mode = "mxfp4"
+ else:
raise ValueError(
- f"Invalid affine PLE parameter shapes for {base}: "
- f"scales={scales_shape}, biases={biases_shape}"
+ f"Incomplete or unsupported PLE tensors for {base}: "
+ f"scales={scales_dtype}, no biases; only native MXFP4 "
+ "supports U8 scales without biases"
)
- if scales_shape[0] != shard_size or scales_shape[1] <= 0:
+ if (
+ len(scales_shape) != 2
+ or scales_shape[0] != shard_size
+ or scales_shape[1] <= 0
+ ):
raise ValueError(
- f"Unexpected affine PLE scale shape for {base}: {scales_shape}"
+ f"Unexpected {mode} 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"Cannot infer {mode} 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"Cannot infer {mode} 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}:
+ if (
+ mode == "mxfp4" and (bits != 4 or group_size != 32)
+ or mode == "affine"
+ and (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"Unsupported {mode} 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"Inconsistent {mode} PLE layout for {base}: "
f"weight={weight_shape}, scales={scales_shape}, dims={dims}"
)
self._shard_specs[shard_index] = (
weight_key,
scales_key,
- biases_key,
+ biases_key if mode == "affine" else None,
bits,
group_size,
+ mode,
)
def _plan(self, host: np.ndarray):
@@ -3758,23 +3790,25 @@ def _plan(self, host: np.ndarray):
local = host - offsets[shard]
touched = [int(index) for index in np.unique(shard)]
specs = [self._shard_specs[index] for index in touched]
- bits, group_size = specs[0][3], specs[0][4]
- families = [0] if bits is None else [0, 1, 2]
+ bits, group_size, mode = specs[0][3:]
+ families = [
+ family for family, key in enumerate(specs[0][:3]) if key is not None
+ ]
dtypes = {
family: self._tensor_readers[specs[0][family]].tensor_dtype(specs[0][family])
for family in families
}
- if any(spec[3:] != (bits, group_size) for spec in specs) or any(
+ if any(spec[3:] != (bits, group_size, mode) for spec in specs) or any(
self._tensor_readers[spec[family]].tensor_dtype(spec[family]) != dtypes[family]
for spec in specs
for family in families
):
return None
- return shard, local, touched, specs, families, dtypes, bits, group_size
+ return shard, local, touched, specs, families, dtypes, bits, group_size, mode
def _assemble(self, host: np.ndarray, plan) -> dict[int, np.ndarray]:
"""Copy every family's rows into one host buffer in index order (runs off the main thread on prefetch)."""
- shard, local, touched, specs, families, _, _, _ = plan
+ shard, local, touched, specs, families, _, _, _, _ = plan
slices = []
for shard_index, spec in zip(touched, specs):
positions = np.flatnonzero(shard == shard_index)
@@ -3841,6 +3875,17 @@ def __call__(self, indices: mx.array) -> mx.array:
raise RuntimeError("SSD-backed Qwen4 PLE embedding is closed")
return self._call_owned(indices)
+ @staticmethod
+ def _dequantize_rows(values, scales, biases, *, group_size, bits, mode):
+ if mode == "affine" and biases is not None and scales.dtype != biases.dtype:
+ # MLX's Metal dequantizer reads scales and biases with one scalar type.
+ dtype = mx.result_type(scales, biases)
+ scales = scales.astype(dtype)
+ biases = biases.astype(dtype)
+ return mx.dequantize(
+ values, scales, biases, group_size=group_size, bits=bits, mode=mode
+ )
+
def _call_owned(self, indices):
shape = indices.shape
host = self._host_indices(indices)
@@ -3856,20 +3901,20 @@ def _call_owned(self, indices):
if plan is None:
return self._gather_per_shard([int(index) for index in host], shape)
buffers = self._assemble(host, plan)
- _, _, touched, _, families, dtypes, bits, group_size = plan
+ _, _, touched, _, families, dtypes, bits, group_size, mode = plan
self.last_touched_shards = tuple(touched)
self.rows_read = int(host.size)
arrays = [_SafeTensorMMap.to_mx(buffers[family], dtypes[family]) for family in families]
self.last_uploads = len(arrays)
values = arrays[0]
if bits is not None:
- values = mx.dequantize(
+ values = self._dequantize_rows(
values,
arrays[1],
- arrays[2],
+ arrays[2] if len(arrays) == 3 else None,
group_size=group_size,
bits=bits,
- mode="affine",
+ mode=mode,
)
# Decode in the checkpoint's scale dtype. bf16 rows times an fp16
# scale promote to fp32.
@@ -3895,23 +3940,27 @@ def _gather_per_shard(self, host_indices: list[int], shape) -> mx.array:
local = [
host_indices[i] - self.shard_offsets[shard_index] for i in positions
]
- weight_key, scales_key, biases_key, bits, group_size = self._shard_specs[
+ weight_key, scales_key, biases_key, bits, group_size, mode = 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
+ assert mode 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(
+ biases = (
+ self._tensor_readers[biases_key].rows(biases_key, local)
+ if biases_key is not None
+ else None
+ )
+ values = self._dequantize_rows(
values,
scales,
biases,
group_size=group_size,
bits=bits,
- mode="affine",
+ mode=mode,
)
values = values.astype(self.weight_scale.dtype) * self.weight_scale
self.rows_read += len(local)
@@ -5098,6 +5147,46 @@ def __call__(self, inputs, inputs_embeds=None, mask=None, cache=None, **kwargs):
if step is not None:
_MTP_ONE_ROW_STEP.reset(step)
+ def speculative_verify_logits(self, inputs: mx.array, cache, sampler):
+ transaction = start_speculative_cache(cache or [], inputs.shape[1])
+ try:
+ output = self(
+ inputs,
+ cache=cache,
+ capture_layer_ids=[],
+ return_hidden=True,
+ return_shared_kv=True,
+ )
+ return (
+ output.hidden_states[0],
+ output.shared_kv_states,
+ transaction,
+ sampler(output.logits),
+ )
+ except BaseException:
+ transaction.abort()
+ raise
+
+ def speculative_verify_hidden(self, inputs: mx.array, cache):
+ transaction = start_speculative_cache(cache or [], inputs.shape[1])
+ try:
+ output = self(
+ inputs,
+ cache=cache,
+ capture_layer_ids=[],
+ return_hidden=True,
+ return_shared_kv=True,
+ skip_logits=True,
+ )
+ return (
+ output.hidden_states[0],
+ output.shared_kv_states,
+ transaction,
+ )
+ except BaseException:
+ transaction.abort()
+ raise
+
def ple_gathers_ahead(self) -> bool:
"""True when an SSD-backed PLE table gathers rows one prefill chunk ahead."""
for layer in self.model.layers:
diff --git a/omlx/patches/nemotron_omni.py b/omlx/patches/nemotron_omni.py
new file mode 100644
index 0000000000..adbdbd9758
--- /dev/null
+++ b/omlx/patches/nemotron_omni.py
@@ -0,0 +1,89 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Native Nemotron media preparation with explicit token/embedding alignment."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import TYPE_CHECKING
+
+import mlx.core as mx
+import numpy as np
+
+if TYPE_CHECKING:
+ from mlx_vlm.models.nemotron_h_nano_omni import Model
+
+
+@dataclass(frozen=True)
+class PreparedNemotronPrompt:
+ source_token_ids: mx.array
+ retained_positions: mx.array
+ token_ids: mx.array
+ inputs_embeds: mx.array
+ attention_mask: mx.array | None
+
+
+class _VideoFeatureCapture:
+ def __init__(self, model: Model):
+ self.model = model
+ self.video_features: mx.array | None = None
+
+ def __getattr__(self, name):
+ return getattr(self.model, name)
+
+ def extract_video_feature(self, pixels):
+ self.video_features = self.model.extract_video_feature(pixels)
+ return self.video_features
+
+
+def prepare_nemotron_prompt(
+ model: Model,
+ input_ids: mx.array,
+ pixel_values: mx.array | None = None,
+ mask: mx.array | None = None,
+ **kwargs,
+) -> PreparedNemotronPrompt:
+ from mlx_vlm.models.nemotron_h_nano_omni.nemotron_h_nano_omni import (
+ Model as NativeModel,
+ )
+ from mlx_vlm.models.nemotron_h_nano_omni.nemotron_h_nano_omni import (
+ compute_retention_mask,
+ )
+
+ has_video = kwargs.get("pixel_values_videos") is not None
+ pruning_rate = kwargs.get("video_pruning_rate", model.video_pruning_rate)
+ if has_video and not 0 <= pruning_rate <= 1:
+ raise ValueError("video_pruning_rate must be between 0 and 1.")
+ view = _VideoFeatureCapture(model)
+ # Let native merging run once, retaining the original pre-cast features.
+ # Apply its pruning decision to both modalities and IDs, not embeddings alone.
+ output = NativeModel.get_input_embeddings(
+ view, # type: ignore[arg-type] # Read-through proxy for the native method.
+ input_ids,
+ pixel_values,
+ mask=mask,
+ **{**kwargs, "video_pruning_rate": 0},
+ )
+ retained = np.arange(input_ids.shape[1])
+ if has_video and pruning_rate > 0:
+ features = view.video_features
+ if features is None:
+ raise RuntimeError(
+ "Native Nemotron preparation returned no video features."
+ )
+ keep = np.ones(input_ids.shape[1], dtype=bool)
+ positions = np.flatnonzero(np.array(input_ids[0] == model.img_context_token_id))
+ keep[positions] = np.array(compute_retention_mask(features, pruning_rate))
+ retained = np.flatnonzero(keep)
+ indices = mx.array(retained, dtype=mx.int32)
+ embeddings = output.inputs_embeds[:, indices]
+ tokens = input_ids[:, indices]
+ attention_mask = None if mask is None else mask[..., indices]
+ if tokens.shape[:2] != embeddings.shape[:2]:
+ raise ValueError("Nemotron prompt tokens and embeddings are not aligned.")
+ return PreparedNemotronPrompt(
+ source_token_ids=input_ids,
+ retained_positions=indices,
+ token_ids=tokens,
+ inputs_embeds=embeddings,
+ attention_mask=attention_mask,
+ )
diff --git a/omlx/patches/nemotron_omni_quantization.py b/omlx/patches/nemotron_omni_quantization.py
new file mode 100644
index 0000000000..281f1b9b32
--- /dev/null
+++ b/omlx/patches/nemotron_omni_quantization.py
@@ -0,0 +1,125 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Native-backed source conversion and associated Nemotron MTP artifacts."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+from pathlib import Path
+
+import mlx.core as mx
+
+from ..model_classification import is_nemotron_modelopt_source
+
+
+def streamed_decoder_layer(args, layer_index):
+ from mlx_vlm.models.nemotron_h.language import NemotronHBlock
+
+ return NemotronHBlock(
+ args.for_layer(layer_index), args.hybrid_override_pattern[layer_index]
+ )
+
+
+def register_source_tensors(index, config: dict) -> int:
+ if not is_nemotron_modelopt_source(config):
+ return 0
+ from mlx_vlm.quantization.checkpoint import _transform_modelopt_nvfp4_weights
+
+ quant = config["quantization_config"]
+ registered = 0
+ for key in list(index._index):
+ if not key.endswith(".weight_scale"):
+ continue
+ prefix = key.removesuffix(".weight_scale")
+ weight_key = prefix + ".weight"
+ if index.source_shape(weight_key) is None:
+ raise ValueError(f"Missing ModelOpt weight for {prefix}")
+ global_key = prefix + ".weight_scale_2"
+ nvfp4 = index.source_shape(global_key) is not None
+ shape = index.source_shape(weight_key)
+ keys = [weight_key, key] + ([global_key] if nvfp4 else [])
+ input_scale = prefix + ".input_scale"
+ if index.source_shape(input_scale) is not None:
+ keys.append(input_scale)
+ if nvfp4:
+ if index.source_dtype(weight_key) != "U8":
+ raise ValueError(f"Invalid ModelOpt NVFP4 weight storage: {weight_key}")
+ shape = (*shape[:-1], shape[-1] * 2)
+ elif index.source_dtype(weight_key) not in {"F8_E4M3", "U8"}:
+ raise ValueError(f"Invalid ModelOpt FP8 weight storage: {weight_key}")
+
+ def materialize(keys=tuple(keys), prefix=prefix, nvfp4=nvfp4):
+ source = {name: index.load_source(name) for name in keys}
+ transformed, _ = _transform_modelopt_nvfp4_weights(source, quant)
+ weight = transformed[prefix + ".weight"]
+ if not nvfp4:
+ return weight
+ dense = mx.dequantize(
+ weight,
+ transformed[prefix + ".scales"],
+ None,
+ group_size=16,
+ bits=4,
+ mode="nvfp4",
+ ).astype(mx.float32)
+ scale = transformed[prefix + ".weight_scale_2"]
+ if scale.ndim:
+ scale = scale.reshape((-1,) + (1,) * (dense.ndim - 1))
+ return (dense * scale).astype(mx.bfloat16)
+
+ index.register_virtual(weight_key, shape, "BF16", materialize, hides=keys)
+ registered += 1
+ for key in index._index:
+ if key.endswith((".k_scale", ".v_scale")):
+ index._hidden.add(key)
+ if (
+ key.endswith(".weight")
+ and index.source_dtype(key) == "U8"
+ and key not in index._virtual
+ ):
+ raise ValueError(f"Unpaired packed ModelOpt weight: {key}")
+ return registered
+
+
+def _parent_digest(config: dict) -> str:
+ return hashlib.sha256(
+ json.dumps(config, sort_keys=True, separators=(",", ":")).encode()
+ ).hexdigest()
+
+
+def native_mtp_sidecar(model_path: str | Path, config: dict) -> Path | None:
+ declaration = config.get("omlx_mtp")
+ if declaration is None:
+ return None
+ if declaration != {"format": "mlx-vlm", "path": "mtp"}:
+ raise ValueError("Invalid native Nemotron MTP sidecar declaration")
+ root = Path(model_path).resolve()
+ sidecar = (root / "mtp").resolve()
+ if sidecar.parent != root:
+ raise ValueError(
+ "Nemotron MTP sidecar must remain inside its parent checkpoint"
+ )
+ head_config = json.loads((sidecar / "config.json").read_text())
+ if head_config.get("model_type") != "nemotron_h_mtp" or head_config.get(
+ "omlx_parent_config_sha256"
+ ) != _parent_digest(config):
+ raise ValueError("Native Nemotron MTP sidecar does not match its parent")
+ if not any(sidecar.glob("*.safetensors")):
+ raise ValueError("Native Nemotron MTP sidecar has no weights")
+ return sidecar
+
+
+def export_native_mtp(source: Path, output: Path, output_config: dict) -> None:
+ from mlx_vlm.speculative.drafters.nemotron_h_mtp.split import NemotronHMTPSplitter
+
+ source_config = json.loads((source / "config.json").read_text())
+ text = source_config.get("text_config") or source_config.get("llm_config") or {}
+ output_config["text_config"]["num_nextn_predict_layers"] = int(
+ text.get("num_nextn_predict_layers", 0)
+ )
+ output_config["omlx_mtp"] = {"format": "mlx-vlm", "path": "mtp"}
+ sidecar = NemotronHMTPSplitter().split(str(source), str(output / "mtp"))
+ config_path = sidecar / "config.json"
+ head_config = json.loads(config_path.read_text())
+ head_config["omlx_parent_config_sha256"] = _parent_digest(output_config)
+ config_path.write_text(json.dumps(head_config, indent=2) + "\n")
diff --git a/omlx/patches/specprefill.py b/omlx/patches/specprefill.py
index f9421d894a..5677bc97e7 100644
--- a/omlx/patches/specprefill.py
+++ b/omlx/patches/specprefill.py
@@ -26,7 +26,8 @@
import inspect
import logging
import math
-from typing import Any, Callable, Dict, List, Optional, Tuple
+from collections.abc import Callable
+from typing import Any
import mlx.core as mx
@@ -167,7 +168,7 @@ def _nemotron_h_extract_queries(attn, x, cache=None, **kwargs):
# ---------------------------------------------------------------------------
-def _find_attention_layers(model) -> List[Tuple[int, Any]]:
+def _find_attention_layers(model) -> list[tuple[int, Any]]:
"""Find all full-attention layers across architectures.
Supports self_attn (standard) and block_type=="*" (Nemotron-H).
@@ -198,7 +199,7 @@ def _set_attn_module(layer, module):
layer.mixer = module
-def _build_layer_to_cache_map(model) -> Dict[int, int]:
+def _build_layer_to_cache_map(model) -> dict[int, int]:
"""Build layer_idx → cache_idx mapping.
Standard models: identity. Nemotron-H: compacted (only M/* layers).
@@ -302,7 +303,7 @@ def _record(entry: Any) -> None:
return max(0, lowest)
-def _linear_output_dims(linear) -> Optional[int]:
+def _linear_output_dims(linear) -> int | None:
"""Best-effort output dimension lookup for Linear / QuantizedLinear layers."""
if linear is None:
return None
@@ -600,10 +601,10 @@ def score_tokens(
temp: float = 0.6,
top_p: float = 0.95,
prefill_step_size: int = 2048,
- query_extractor: Optional[Callable] = None,
- existing_cache: Optional[List[Any]] = None,
- progress_callback: Optional[Callable[[int, int, str], None]] = None,
-) -> Tuple[mx.array, Any]:
+ query_extractor: Callable | None = None,
+ existing_cache: list[Any] | None = None,
+ progress_callback: Callable[[int, int, str], None] | None = None,
+) -> tuple[mx.array, Any]:
"""Score token importance using attention patterns on a draft model.
Pipeline:
@@ -766,6 +767,8 @@ def select_chunks(
sorted mx.array of kept token indices
"""
M = importance.shape[0]
+ if M == 0:
+ return mx.array([], dtype=mx.int32)
if keep_pct >= 1.0:
return mx.arange(M)
@@ -776,11 +779,28 @@ def select_chunks(
)
ranked_end = n_chunks - n_tail_chunks
- chunk_scores = []
- for i in range(ranked_end):
- start = i * chunk_size
- end = min(start + chunk_size, M)
- chunk_scores.append(mx.mean(importance[start:end]).item())
+ ranked_token_count = min(M, ranked_end * chunk_size)
+ full_chunks, remainder = divmod(ranked_token_count, chunk_size)
+ score_parts = []
+ if full_chunks:
+ score_parts.append(
+ mx.mean(
+ importance[: full_chunks * chunk_size].reshape(
+ full_chunks, chunk_size
+ ),
+ axis=1,
+ )
+ )
+ if remainder:
+ score_parts.append(mx.mean(importance[full_chunks * chunk_size :]).reshape(1))
+
+ # Transfer all scores once instead of synchronizing MLX once per chunk.
+ if not score_parts:
+ chunk_scores = []
+ else:
+ chunk_scores = (
+ score_parts[0] if len(score_parts) == 1 else mx.concatenate(score_parts)
+ ).tolist()
budget = max(0, keep_n - n_tail_chunks)
top_chunks = sorted(range(ranked_end), key=lambda i: chunk_scores[i], reverse=True)[
@@ -979,8 +999,8 @@ def sparse_prefill(
cache,
step_size: int = 2048,
position_offset: int = 0,
- progress_callback: Optional[Callable[[int, int], None]] = None,
- kickoff_index: Optional[int] = None,
+ progress_callback: Callable[[int, int], None] | None = None,
+ kickoff_index: int | None = None,
) -> mx.array:
"""Prefill model cache with selected tokens at their original positions.
diff --git a/omlx/patches/turboquant_attention.py b/omlx/patches/turboquant_attention.py
index 9f324875a6..ff58365669 100644
--- a/omlx/patches/turboquant_attention.py
+++ b/omlx/patches/turboquant_attention.py
@@ -20,7 +20,6 @@
import logging
from functools import cache
-from typing import Optional
import mlx.core as mx
from mlx_lm.models.cache import create_causal_mask
@@ -898,12 +897,18 @@ def _patch_vlm_target_verify_attention() -> None:
return
if getattr(q35_lang, "_omlx_tq_target_verify_patched", False):
return
- if getattr(q35_lang, "_qwen3_5_left_padded_attention", None) is None:
+ helper_name = "_target_verify_left_padded_attention"
+ original = getattr(q35_lang, helper_name, None)
+ if original is None:
+ helper_name = "_qwen3_5_left_padded_attention"
+ original = getattr(q35_lang, helper_name, None)
+ if original is None:
return
# The bounded padded-verify kernel returns None for TurboQuant caches
# without calling inward, so keep it inside this wrapper.
- qwen35_verify_attention.apply(q35_lang)
- original = q35_lang._qwen3_5_left_padded_attention
+ if helper_name == "_qwen3_5_left_padded_attention":
+ qwen35_verify_attention.apply(q35_lang)
+ original = getattr(q35_lang, helper_name)
def patched(queries, keys, values, *, cache, scale, mask):
from mlx_vlm.turboquant import TurboQuantKVCache as _TQCache
@@ -941,8 +946,8 @@ def patched(queries, keys, values, *, cache, scale, mask):
dk, dv = real_cache.dequantize(keys_state=keys, values_state=values)
dk = dk.astype(queries.dtype)
dv = dv.astype(queries.dtype)
- L = queries.shape[2]
- prefix_len = dk.shape[-2] - L
+ query_length = queries.shape[2]
+ prefix_len = dk.shape[-2] - query_length
return mx.concatenate(
[
sdpa(
@@ -957,12 +962,13 @@ def patched(queries, keys, values, *, cache, scale, mask):
else None
),
)
- for i in range(L)
+ for i in range(query_length)
],
axis=2,
)
- q35_lang._qwen3_5_left_padded_attention = patched
+ setattr(q35_lang, helper_name, patched)
+ q35_lang._omlx_tq_target_verify_helper = helper_name
q35_lang._omlx_tq_target_verify_original = original
q35_lang._omlx_tq_target_verify_patched = True
@@ -998,8 +1004,8 @@ def patched_sdpa(
values,
cache,
scale: float,
- mask: Optional[mx.array],
- sinks: Optional[mx.array] = None,
+ mask: mx.array | None,
+ sinks: mx.array | None = None,
) -> mx.array:
from mlx_vlm.turboquant import TurboQuantKVCache as _TQCache
diff --git a/omlx/patches/virtual_tensors.py b/omlx/patches/virtual_tensors.py
index 8fba2ffec5..9ab313675c 100644
--- a/omlx/patches/virtual_tensors.py
+++ b/omlx/patches/virtual_tensors.py
@@ -43,6 +43,7 @@ def register_virtual_tensors(index, config) -> int:
from .mlx_vlm_qwen4_exp_compat.virtual_ple import (
register as register_qwen4_exp_ple,
)
+ from .nemotron_omni_quantization import register_source_tensors
# Import errors are deliberately not caught. A registrar that fails to
# load leaves its checkpoint in the layout the quantizer cannot read, so
@@ -53,4 +54,5 @@ def register_virtual_tensors(index, config) -> int:
+ register_qwen4_exp_ple(index, config)
+ register_minimax_nvfp4(index, config)
+ register_inkling2_experts(index, config)
+ + register_source_tensors(index, config)
)
diff --git a/omlx/speculative/dflash/__init__.py b/omlx/speculative/dflash/__init__.py
index 78c9e38901..9b662887bf 100644
--- a/omlx/speculative/dflash/__init__.py
+++ b/omlx/speculative/dflash/__init__.py
@@ -20,7 +20,8 @@
import inspect
import json
import logging
-from typing import Any
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
import mlx.core as mx
import mlx.nn as nn
@@ -37,6 +38,9 @@
_FP16_MAX = 65504.0
+if TYPE_CHECKING:
+ from ..dspark_drafter import DSparkDrafter
+
def resolve_block_size(
model: nn.Module, requested: int | None, max_rows: int | None = None
@@ -163,13 +167,14 @@ def load_dflash_drafter(
target_model: Any,
*,
tokenizer: Any = None,
+ target_path: str | None = None,
block_size: int | None = None,
quant_enabled: bool = False,
quant_bits: int = 4,
quant_group_size: int = 64,
verify_mode: str | None = None,
window_size: int | None = None,
-) -> DFlashDrafter:
+) -> DFlashDrafter | DSparkDrafter:
"""Load a DFlash checkpoint through mlx-vlm and bind it to ``target_model``.
``target_model`` is the mlx-vlm model whose ``language_model`` owns the
@@ -177,7 +182,28 @@ def load_dflash_drafter(
checkpoint's context window.
"""
adaptive = resolve_verify_mode(verify_mode)
- model, kind = load_drafter(path, kind="dflash")
+ is_minicpm = (
+ getattr(getattr(target_model, "config", None), "model_type", None)
+ == "minicpmv4_7"
+ )
+ if is_minicpm:
+ from ..minicpm_dspark import (
+ MiniCPMDSparkDraftModel,
+ load_dspark_model,
+ )
+ from ..minicpm_pairing import validate_model_pair
+
+ if not Path(path).is_dir():
+ raise ValueError("MiniCPM DSpark requires an existing local helper checkpoint.")
+ dspark_class = MiniCPMDSparkDraftModel
+ if not callable(getattr(dspark_class, "propose_block", None)):
+ raise ValueError("Native DSpark proposal support is incomplete.")
+ validate_model_pair(target_path, path)
+ model, kind = load_dspark_model(path), "dflash"
+ if not isinstance(model, dspark_class):
+ raise ValueError("MiniCPM-V 4.7 requires its paired DSpark helper, not DFlash.")
+ else:
+ model, kind = load_drafter(path, kind="dflash")
if kind != "dflash":
raise ValueError(f"{path} resolved to drafter kind {kind!r}, expected 'dflash'")
cast = match_target_dtype(model, target_model)
@@ -193,7 +219,8 @@ def load_dflash_drafter(
)
local = get_model_path(path)
config = json.loads((local / "config.json").read_text())
- apply_partial_rope(model, config)
+ if not is_minicpm:
+ apply_partial_rope(model, config)
mask_path = local / "mask_embedding.pt"
mask_embedding = (
load_mask_embedding(mask_path, int(config["hidden_size"]))
@@ -212,34 +239,44 @@ def load_dflash_drafter(
language_model = getattr(target_model, "language_model", target_model)
block = resolve_block_size(
model,
- block_size,
+ (
+ getattr(model, "dflash_default_block_size", None)
+ if is_minicpm and block_size is None
+ else block_size
+ ),
getattr(language_model, "_omlx_mtp_max_verify_rows", None),
)
mx.eval(model.parameters())
- if qwen35_packed_linear.enabled(target_model):
+ if not is_minicpm and qwen35_packed_linear.enabled(target_model):
packed = qwen35_packed_linear.pack_drafter(model)
logger.info("DFlash drafter packed 4-bit projections: %d layers", packed)
- drafter = DFlashDrafter(
- model,
- block_size=block,
- source_path=path,
- adaptive=adaptive,
- window_size=window_size,
- value_scale=(config.get("dflash_config") or {}).get("attention_value_scale"),
- mask_embedding=mask_embedding,
- )
+ drafter: DFlashDrafter | DSparkDrafter
+ if is_minicpm:
+ from ..dspark_drafter import DSparkDrafter
+
+ drafter = DSparkDrafter(model, block_size=block, source_path=path)
+ else:
+ drafter = DFlashDrafter(
+ model,
+ block_size=block,
+ source_path=path,
+ adaptive=adaptive,
+ window_size=window_size,
+ value_scale=(config.get("dflash_config") or {}).get("attention_value_scale"),
+ mask_embedding=mask_embedding,
+ )
logger.info(
"DFlash drafter loaded: path=%s kind=%s block=%d adaptive=%s target_layers=%s",
path,
drafter.kind,
block,
- drafter.adaptive,
+ adaptive if not is_minicpm else False,
drafter.target_layer_ids,
)
return drafter
-def attach_drafter(language_model: Any, drafter: DFlashDrafter) -> None:
+def attach_drafter(language_model: Any, drafter: DFlashDrafter | DSparkDrafter) -> None:
"""Expose the drafter to Lightning MTP through the language model markers."""
language_model._omlx_drafter = drafter
language_model._omlx_mtp_decode_enabled = True
@@ -250,15 +287,19 @@ def attach_drafter(language_model: Any, drafter: DFlashDrafter) -> None:
language_model._omlx_mtp_chain = True
language_model._omlx_mtp_depth = drafter.depth
language_model._omlx_mtp_head_clone = False
+ if drafter.kind == "dspark":
+ language_model._omlx_mtp_depth_fixed = True
-def detach_drafter(language_model: Any) -> DFlashDrafter | None:
+def detach_drafter(language_model: Any) -> DFlashDrafter | DSparkDrafter | None:
drafter = getattr(language_model, "_omlx_drafter", None)
if drafter is None:
return None
drafter.clear()
language_model._omlx_drafter = None
language_model._omlx_mtp_decode_enabled = False
+ if drafter.kind == "dspark":
+ language_model._omlx_mtp_depth_fixed = False
return drafter
diff --git a/omlx/speculative/dspark_drafter.py b/omlx/speculative/dspark_drafter.py
new file mode 100644
index 0000000000..c1e89fbf92
--- /dev/null
+++ b/omlx/speculative/dspark_drafter.py
@@ -0,0 +1,183 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Native DSpark proposals with request-owned, untruncated context caches."""
+
+from __future__ import annotations
+
+import sys
+import time
+from collections.abc import Iterable, Sequence
+from contextlib import contextmanager
+from dataclasses import dataclass, field
+from typing import Any
+
+import mlx.core as mx
+
+from ..patches.mlx_lm_mtp import batch_generator as bg
+from .dflash.drafter import _concat_captured
+
+
+@dataclass
+class _DSparkRow:
+ cache: list[Any]
+ pending: list[mx.array] = field(default_factory=list)
+ fed: int = 0
+ confidences: mx.array | None = None
+
+
+class DSparkDrafter:
+ """Adapt native proposals to Lightning MTP without replacing their sampler."""
+
+ kind = "dspark"
+ window = sys.maxsize
+
+ def __init__(self, model: Any, *, block_size: int, source_path: str):
+ if not callable(getattr(model, "propose_block", None)):
+ raise ValueError(
+ "DSpark requires the native proposal/probability/confidence contract."
+ )
+ self.model = model
+ self.source_path = source_path
+ self.target_layer_ids = list(model.config.target_layer_ids)
+ self.block_size = block_size
+ self.depth = block_size - 1
+ self._rows: dict[Any, _DSparkRow] = {}
+ self._request_seeds: dict[str, list[mx.array]] = {}
+ self.scope_uids: tuple | None = None
+
+ def _row(self, uid: Any) -> _DSparkRow:
+ if uid not in self._rows:
+ self._rows[uid] = _DSparkRow(cache=self.model.make_cache())
+ return self._rows[uid]
+
+ def seed(self, uid: Any, captured: Sequence[mx.array]) -> None:
+ if captured:
+ self._row(uid).pending.append(_concat_captured(captured))
+
+ def observe(self, uids: Iterable[Any], captured: Sequence[mx.array] | None) -> None:
+ if captured:
+ for index, uid in enumerate(uids):
+ self.seed(uid, [layer[index : index + 1] for layer in captured])
+
+ def prepare_request(
+ self, request_id: str, tokens: Sequence[int], cached: int
+ ) -> int:
+ """DSpark never restores a truncated prefix context."""
+ return 0
+
+ def seed_request(
+ self,
+ request_id: str,
+ captured: Sequence[mx.array],
+ position: int | None = None,
+ ) -> None:
+ """Queue all captures; absolute positions never trim DSpark's history."""
+ if captured:
+ self._request_seeds.setdefault(request_id, []).append(
+ _concat_captured(captured)
+ )
+
+ def bind_uid(self, request_id: str, uid: Any) -> None:
+ seeds = self._request_seeds.pop(request_id, None)
+ if seeds:
+ self._row(uid).pending.extend(seeds)
+
+ def release_request(
+ self, request_id: str, tokens: Sequence[int] | None = None
+ ) -> None:
+ """Release pending captures without retaining context for prefix hits."""
+ self._request_seeds.pop(request_id, None)
+
+ def release(self, uids: Iterable[Any]) -> None:
+ for uid in uids:
+ self._rows.pop(uid, None)
+
+ def reset_rows(self) -> None:
+ self._rows.clear()
+
+ def clear(self) -> None:
+ self.reset_rows()
+ self._request_seeds.clear()
+
+ @contextmanager
+ def decode_scope(self, uids: Iterable[Any]):
+ previous = self.scope_uids
+ self.scope_uids = tuple(uids)
+ try:
+ yield
+ finally:
+ self.scope_uids = previous
+
+ def context_length(self, uid: Any) -> int:
+ row = self._rows.get(uid)
+ return 0 if row is None else row.fed
+
+ def draft(self, jobs: Sequence[tuple]) -> None:
+ stochastic = [
+ gen_batch is not None and not bg._is_greedy(gen_batch)
+ for gen_batch, *_ in jobs
+ ]
+ if any(
+ sampled
+ and (
+ len(jobs) > 1
+ or len(getattr(job[0], "uids", ())) > 1
+ or (self.scope_uids is not None and len(self.scope_uids) > 1)
+ )
+ for job, sampled in zip(jobs, stochastic)
+ ):
+ raise ValueError("Batched sampled DSpark is not supported.")
+ started = time.perf_counter()
+ for job, sampled in zip(jobs, stochastic):
+ gen_batch, state, captured, committed, _prev_buf = job
+ row = self._row(state.uid)
+ if captured:
+ row.pending.append(_concat_captured(captured))
+ if not row.pending:
+ raise RuntimeError(f"DSpark has no target context for uid={state.uid!r}")
+ hidden = (
+ row.pending[0]
+ if len(row.pending) == 1
+ else mx.concatenate(row.pending, axis=1)
+ )
+ sampler = (
+ bg._resolve_draft_sampler(gen_batch, state)
+ if sampled
+ else lambda logits: mx.argmax(logits, axis=-1)
+ )
+ probabilities = (
+ (lambda logprobs, sampler=sampler: mx.exp(
+ bg._accept_lp_for(sampler, logprobs)
+ ))
+ if sampled
+ else None
+ )
+ proposal = self.model.propose_block(
+ committed.reshape(-1)[-1:].astype(mx.int32),
+ hidden,
+ row.cache,
+ self.block_size,
+ sampler,
+ proposal_probs=probabilities,
+ )
+ if proposal.block_size != self.block_size or proposal.tokens.shape != (
+ 1,
+ self.depth,
+ ):
+ raise RuntimeError("Native DSpark returned an inconsistent block width.")
+ if sampled and proposal.proposal_probs is None:
+ raise RuntimeError("Sampled DSpark did not return its proposal law.")
+ state.drafts = proposal.tokens.reshape(-1).astype(mx.uint32)
+ state.draft_lps = []
+ state.draft_accept_lps = (
+ [mx.log(proposal.proposal_probs[0, index]) for index in range(self.depth)]
+ if sampled
+ else []
+ )
+ row.confidences = proposal.confidences
+ row.fed += int(hidden.shape[1])
+ row.pending.clear()
+ mx.async_eval(state.drafts)
+ share = (time.perf_counter() - started) * 1000 / max(1, len(jobs))
+ for _, state, *_ in jobs:
+ if state.stats is not None:
+ state.stats.mtp_head_ms += share
diff --git a/omlx/speculative/minicpm_dspark.py b/omlx/speculative/minicpm_dspark.py
new file mode 100644
index 0000000000..7483943714
--- /dev/null
+++ b/omlx/speculative/minicpm_dspark.py
@@ -0,0 +1,190 @@
+# SPDX-License-Identifier: Apache-2.0
+# Portions adapted from mlx-vlm; see ../MLX_VLM_LICENSE.txt.
+"""Paired MiniCPM DSpark sampling transport over the official drafter."""
+
+from __future__ import annotations
+
+import json
+from contextvars import ContextVar
+from dataclasses import dataclass
+from pathlib import Path
+from types import SimpleNamespace
+
+import mlx.core as mx
+from mlx_vlm.speculative.drafters.dspark import DSparkDraftModel
+from mlx_vlm.speculative.drafters.dspark.config import DSparkConfig
+
+_LOADING = ContextVar("omlx_minicpm_dspark_loading", default=False)
+
+
+@dataclass
+class MiniCPMDSparkConfig(DSparkConfig):
+ target_model_type: str = "minicpmv4_7"
+
+ @classmethod
+ def from_dict(cls, params):
+ params = dict(params)
+ if params.get("target_model_type", "minicpmv4_7") != "minicpmv4_7":
+ raise ValueError("MiniCPM DSpark requires its explicitly paired helper")
+ dflash = dict(params.get("dflash_config") or {})
+ policy = dflash.get(
+ "block_size_policy", params.get("block_size_policy", "fixed")
+ )
+ if policy != "fixed":
+ raise ValueError("MiniCPM DSpark requires fixed-block verification")
+ dflash["block_size_policy"] = "fixed"
+ params["dflash_config"] = dflash
+ return super().from_dict(params)
+
+
+@dataclass(frozen=True)
+class DSparkProposal:
+ tokens: mx.array
+ proposal_probs: mx.array | None
+ confidences: mx.array | None
+ block_size: int
+ sample_from_anchor: bool
+
+
+class MiniCPMDSparkDraftModel(DSparkDraftModel):
+ def validate_target_compatibility(self, target_model):
+ super().validate_target_compatibility(target_model)
+ language = target_model.language_model
+ if language.config.model_type != self.config.target_model_type:
+ raise ValueError("MiniCPM DSpark requires its explicitly paired target")
+ args = language.args
+ if (args.hidden_size, args.num_hidden_layers, args.vocab_size) == (
+ 2048,
+ 40,
+ 248144,
+ ):
+ required = {
+ "target_layer_ids": [3, 11, 19, 27, 35],
+ "num_hidden_layers": 5,
+ "head_dim": 256,
+ "markov_rank": 256,
+ "mask_token_id": 248076,
+ "proposal_length": 15,
+ "enable_confidence_head": True,
+ "sample_from_anchor": True,
+ }
+ if any(
+ getattr(self.config, name) != value for name, value in required.items()
+ ):
+ raise ValueError(
+ "DSpark helper does not match the published MiniCPM pairing"
+ )
+
+ def propose_block(
+ self,
+ last_bonus,
+ hidden,
+ cache,
+ block_size,
+ sampler,
+ token_dtype=mx.int32,
+ *,
+ proposal_probs=None,
+ sampling_key=None,
+ ):
+ if not 1 <= block_size <= self.config.block_size:
+ raise ValueError(
+ "DSpark block_size exceeds the configured verification cap"
+ )
+ anchor = (
+ mx.array([last_bonus], dtype=token_dtype)
+ if isinstance(last_bonus, int)
+ else last_bonus.reshape(-1).astype(token_dtype)
+ )
+ count = block_size - 1
+ if not count:
+ return DSparkProposal(
+ mx.zeros((anchor.size, 0), dtype=token_dtype),
+ (
+ mx.zeros((anchor.size, 0, self.config.vocab_size))
+ if proposal_probs is not None
+ else None
+ ),
+ (
+ mx.zeros((anchor.size, 0))
+ if self.confidence_head is not None
+ else None
+ ),
+ block_size,
+ self.config.sample_from_anchor,
+ )
+ masks = mx.full(
+ (anchor.size, count - int(self.config.sample_from_anchor)),
+ self.config.mask_token_id,
+ dtype=token_dtype,
+ )
+ draft_hidden = self._hidden(
+ mx.concatenate([anchor[:, None], masks], axis=1), hidden, cache
+ )
+ if not self.config.sample_from_anchor:
+ draft_hidden = draft_hidden[:, 1:]
+ logits = self._logits(draft_hidden)
+ tokens, probabilities = [], []
+ previous = anchor
+ keys = (
+ mx.random.split(sampling_key, count) if sampling_key is not None else None
+ )
+ for index in range(count):
+ step = self.markov_head.apply_step_logits(logits[:, index], previous)
+ if proposal_probs is None:
+ previous = sampler(step).reshape(-1)
+ else:
+ logprobs = step.astype(mx.float32)
+ logprobs -= mx.logsumexp(logprobs, axis=-1, keepdims=True)
+ probs = proposal_probs(logprobs)
+ if not isinstance(probs, mx.array) or probs.shape != step.shape:
+ raise ValueError(
+ "DSpark proposal probabilities must match logits shape"
+ )
+ if not bool(
+ mx.all(mx.isfinite(probs) & (probs >= 0)).item()
+ ) or not bool(mx.all(mx.abs(probs.sum(axis=-1) - 1) <= 2e-5).item()):
+ raise ValueError(
+ "DSpark proposal probabilities must be finite and normalized"
+ )
+ probabilities.append(probs[:, None])
+ previous = mx.random.categorical(
+ mx.log(probs), key=keys[index] if keys is not None else None
+ ).reshape(-1)
+ tokens.append(previous[:, None])
+ tokens = mx.concatenate(tokens, axis=1).astype(token_dtype)
+ return DSparkProposal(
+ tokens,
+ mx.concatenate(probabilities, axis=1) if probabilities else None,
+ self.confidence(draft_hidden, anchor, tokens),
+ block_size,
+ self.config.sample_from_anchor,
+ )
+
+
+def load_dspark_model(path: str):
+ """Use upstream's strict loader with a context-local helper class override."""
+ from mlx_vlm import utils
+
+ directory = Path(path)
+ MiniCPMDSparkConfig.from_dict(json.loads((directory / "config.json").read_text()))
+ resolver = utils.get_model_and_args
+ if not getattr(resolver, "_omlx_minicpm_dspark", False):
+
+ def get_model_and_args(*args, **kwargs):
+ if _LOADING.get():
+ return (
+ SimpleNamespace(
+ Model=MiniCPMDSparkDraftModel, ModelConfig=MiniCPMDSparkConfig
+ ),
+ "dspark",
+ )
+ return resolver(*args, **kwargs)
+
+ get_model_and_args._omlx_minicpm_dspark = True # type: ignore[attr-defined]
+ utils.get_model_and_args = get_model_and_args
+ token = _LOADING.set(True)
+ try:
+ return utils.load_model(directory, strict=True)
+ finally:
+ _LOADING.reset(token)
diff --git a/omlx/speculative/minicpm_pairing.py b/omlx/speculative/minicpm_pairing.py
new file mode 100644
index 0000000000..8a1fdb37f9
--- /dev/null
+++ b/omlx/speculative/minicpm_pairing.py
@@ -0,0 +1,52 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Source provenance admission for the published MiniCPM target/helper pair."""
+
+import hashlib
+import json
+from pathlib import Path
+
+TARGET = (
+ "openbmb/MiniCPM-V-4.7-35B-A3B",
+ "4c7623a9326e0f74313bbc7292d852a9e3018a70",
+)
+HELPER = (
+ "openbmb/MiniCPM-V-4.7-35B-A3B-DSpark",
+ "5facb75c251ffd524524a544c1f5fd97ba0d6c5c",
+)
+
+
+def _validate_source(directory: Path, expected: tuple[str, str]) -> None:
+ config_path = directory / "config.json"
+ config_bytes = config_path.read_bytes()
+ config = json.loads(config_bytes)
+ declared = config.get("omlx_source")
+ if declared is not None:
+ if (
+ not isinstance(declared, dict)
+ or (declared.get("repo_id"), declared.get("revision")) != expected
+ ):
+ raise ValueError(f"Checkpoint source does not match {expected[0]}")
+ return
+ metadata = directory / ".cache/huggingface/download/config.json.metadata"
+ if not metadata.is_file():
+ raise ValueError(
+ f"Cannot establish checkpoint source for {expected[0]}. Retain the "
+ "original Hugging Face download metadata, or declare the conversion's "
+ "omlx_source.repo_id and omlx_source.revision in config.json."
+ )
+ lines = metadata.read_text().splitlines()
+ git_blob = b"blob " + str(len(config_bytes)).encode() + b"\0" + config_bytes
+ if (
+ len(lines) < 2
+ or lines[0] != expected[1]
+ or lines[1] != hashlib.sha1(git_blob, usedforsecurity=False).hexdigest()
+ ):
+ raise ValueError(f"Stale or mismatched source metadata for {expected[0]}")
+
+
+def validate_model_pair(target_path: str | None, helper_path: str) -> None:
+ """Check origin metadata before loading helper tensors; shapes are separate."""
+ if target_path is None:
+ raise ValueError("MiniCPM DSpark requires the target checkpoint source path")
+ _validate_source(Path(target_path), TARGET)
+ _validate_source(Path(helper_path), HELPER)
diff --git a/omlx/utils/image.py b/omlx/utils/image.py
index beed52c969..16f8d54228 100644
--- a/omlx/utils/image.py
+++ b/omlx/utils/image.py
@@ -15,7 +15,7 @@
import struct
import threading
from collections import OrderedDict
-from typing import Any, Dict, List, Optional, Tuple
+from typing import Any
from PIL import Image, ImageOps
@@ -326,8 +326,8 @@ def _load_image_bytes(
def extract_images_from_messages(
- messages: List[Dict[str, Any]],
-) -> Tuple[List[Dict[str, Any]], List[Image.Image], List]:
+ messages: list[dict[str, Any]],
+) -> tuple[list[dict[str, Any]], list[Image.Image], list]:
"""Extract images and audio; video parts are rejected.
See :func:`extract_media_from_messages` for models with native video input.
@@ -476,6 +476,12 @@ def _extract_media(
"Video content part is missing video_url.",
field="messages",
)
+ if not url.strip().startswith("data:video/"):
+ raise InvalidRequestError(
+ "Video inputs must be base64 video data URIs. "
+ "Remote URLs and local file paths are not supported.",
+ field="messages",
+ )
videos.append(url)
new_msg = {"role": role, "content": "\n".join(text_parts) if text_parts else ""}
@@ -496,7 +502,24 @@ def _extract_media(
return text_messages, images, audio
-def compute_image_hash(images: List[Image.Image]) -> Optional[str]:
+def compute_audio_video_hash(audio: list[Any], videos: list[Any]) -> str | None:
+ """Hash inline audio and video without changing audio buffer positions."""
+ if not audio and not videos:
+ return None
+ hasher = hashlib.sha256()
+ for label, items in (("audio", audio), ("video", videos)):
+ for item in items:
+ hasher.update(label.encode())
+ if isinstance(item, io.BytesIO):
+ hasher.update(item.getvalue())
+ elif isinstance(item, (bytes, bytearray, memoryview)):
+ hasher.update(bytes(item))
+ else:
+ hasher.update(str(item).encode())
+ return hasher.hexdigest()
+
+
+def compute_image_hash(images: list[Image.Image]) -> str | None:
"""
Compute a SHA256 hash from a list of images for prefix cache deduplication.
@@ -523,7 +546,7 @@ def compute_image_hash(images: List[Image.Image]) -> Optional[str]:
return hasher.hexdigest()
-def compute_per_image_hashes(images: List[Image.Image]) -> List[str]:
+def compute_per_image_hashes(images: list[Image.Image]) -> list[str]:
"""Compute individual SHA256 hashes for each image.
Returns a list of hex-encoded hash strings, one per image.
diff --git a/omlx/utils/video.py b/omlx/utils/video.py
index 903392a649..3ee76065de 100644
--- a/omlx/utils/video.py
+++ b/omlx/utils/video.py
@@ -55,14 +55,21 @@
def _video_url(part: Any) -> str | None:
value = (
- part.get("video_url", part.get("input_video"))
+ part.get("video_url") or part.get("input_video") or part.get("video")
if isinstance(part, dict)
- else getattr(part, "video_url", None)
+ else getattr(part, "video_url", None) or getattr(part, "input_video", None)
)
if isinstance(value, str):
return value
if isinstance(value, dict):
- return value.get("url")
+ if value.get("url"):
+ return value["url"]
+ data = value.get("data") or value.get("file_data")
+ if isinstance(data, str) and data.strip():
+ if data.strip().startswith("data:"):
+ return data.strip()
+ media_format = value.get("format") or "mp4"
+ return f"data:video/{media_format};base64,{data.strip()}"
if value is not None:
return getattr(value, "url", None)
return None
diff --git a/tests/fixtures/minicpmv4_7_chat_template.jinja b/tests/fixtures/minicpmv4_7_chat_template.jinja
new file mode 100644
index 0000000000..0948ab105f
--- /dev/null
+++ b/tests/fixtures/minicpmv4_7_chat_template.jinja
@@ -0,0 +1,142 @@
+{%- macro render_content(content, is_system_content=false) -%}
+ {%- if content is string -%}
+ {{- content -}}
+ {%- elif content is iterable and content is not mapping -%}
+ {%- set ns = namespace(parts=[]) -%}
+ {%- for item in content -%}
+ {%- if 'image' in item or 'image_url' in item or item.type == 'image' -%}
+ {%- if is_system_content -%}
+ {{- raise_exception('System message cannot contain images.') -}}
+ {%- endif -%}
+ {%- set ns.parts = ns.parts + ['<|image_pad|>'] -%}
+ {%- elif 'video' in item or item.type == 'video' -%}
+ {%- if is_system_content -%}
+ {{- raise_exception('System message cannot contain videos.') -}}
+ {%- endif -%}
+ {%- set ns.parts = ns.parts + ['<|video_pad|>'] -%}
+ {%- elif 'text' in item -%}
+ {%- set ns.parts = ns.parts + [item.text] -%}
+ {%- else -%}
+ {{- raise_exception('Unexpected item type in content.') -}}
+ {%- endif -%}
+ {%- endfor -%}
+ {{- ns.parts | join('\n') -}}
+ {%- elif content is none or content is undefined -%}
+ {{- '' -}}
+ {%- else -%}
+ {{- raise_exception('Unexpected content type.') -}}
+ {%- endif -%}
+{%- endmacro -%}
+{%- if not messages %}
+ {{- raise_exception('No messages provided.') }}
+{%- endif %}
+{%- if tools and tools is iterable and tools is not mapping %}
+ {{- '<|im_start|>system\n' }}
+ {{- "# Tools\n\nYou have access to the following functions:\n\n" }}
+ {%- for tool in tools %}
+ {{- "\n" }}
+ {{- tool | tojson }}
+ {%- endfor %}
+ {{- "\n " }}
+ {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n \n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n \n \n \n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n ' }}
+ {%- if messages[0].role == 'system' %}
+ {%- set content = render_content(messages[0].content, true)|trim %}
+ {%- if content %}
+ {{- '\n\n' + content }}
+ {%- endif %}
+ {%- endif %}
+ {{- '<|im_end|>\n' }}
+{%- else %}
+ {%- if messages[0].role == 'system' %}
+ {%- set content = render_content(messages[0].content, true)|trim %}
+ {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}
+ {%- endif %}
+{%- endif %}
+{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
+{%- for message in messages[::-1] %}
+ {%- set index = (messages|length - 1) - loop.index0 %}
+ {%- if ns.multi_step_tool and message.role == "user" %}
+ {%- set content = render_content(message.content)|trim %}
+ {%- if not(content.startswith('') and content.endswith(' ')) %}
+ {%- set ns.multi_step_tool = false %}
+ {%- set ns.last_query_index = index %}
+ {%- endif %}
+ {%- endif %}
+{%- endfor %}
+{%- if ns.multi_step_tool %}
+ {{- raise_exception('No user query found in messages.') }}
+{%- endif %}
+{%- for message in messages %}
+ {%- set content = render_content(message.content)|trim %}
+ {%- if message.role == "system" %}
+ {%- if not loop.first %}
+ {{- raise_exception('System message must be at the beginning.') }}
+ {%- endif %}
+ {%- elif message.role == "user" %}
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
+ {%- elif message.role == "assistant" %}
+ {%- set reasoning_content = '' %}
+ {%- if message.reasoning_content is string %}
+ {%- set reasoning_content = message.reasoning_content %}
+ {%- else %}
+ {%- if ' ' in content %}
+ {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') %}
+ {%- set content = content.split(' ')[-1].lstrip('\n') %}
+ {%- endif %}
+ {%- endif %}
+ {%- set reasoning_content = reasoning_content|trim %}
+ {%- if loop.index0 > ns.last_query_index and reasoning_content %}
+ {{- '<|im_start|>' + message.role + '\n\n' + reasoning_content + '\n \n\n' + content }}
+ {%- else %}
+ {{- '<|im_start|>' + message.role + '\n\n\n \n\n' + content }}
+ {%- endif %}
+ {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
+ {%- for tool_call in message.tool_calls %}
+ {%- if tool_call.function is defined %}
+ {%- set tool_call = tool_call.function %}
+ {%- endif %}
+ {%- if loop.first %}
+ {%- if content|trim %}
+ {{- '\n\n\n\n' }}
+ {%- else %}
+ {{- '\n\n' }}
+ {%- endif %}
+ {%- else %}
+ {{- '\n\n\n' }}
+ {%- endif %}
+ {%- if tool_call.arguments is defined %}
+ {%- for args_name, args_value in tool_call.arguments|items %}
+ {{- '\n' }}
+ {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %}
+ {{- args_value }}
+ {{- '\n \n' }}
+ {%- endfor %}
+ {%- endif %}
+ {{- ' \n ' }}
+ {%- endfor %}
+ {%- endif %}
+ {{- '<|im_end|>\n' }}
+ {%- elif message.role == "tool" %}
+ {%- if loop.previtem and loop.previtem.role != "tool" %}
+ {{- '<|im_start|>user' }}
+ {%- endif %}
+ {{- '\n\n' }}
+ {{- content }}
+ {{- '\n ' }}
+ {%- if not loop.last and loop.nextitem.role != "tool" %}
+ {{- '<|im_end|>\n' }}
+ {%- elif loop.last %}
+ {{- '<|im_end|>\n' }}
+ {%- endif %}
+ {%- else %}
+ {{- raise_exception('Unexpected message role.') }}
+ {%- endif %}
+{%- endfor %}
+{%- if add_generation_prompt %}
+ {{- '<|im_start|>assistant\n' }}
+ {%- if enable_thinking is defined and enable_thinking is false %}
+ {{- '\n\n \n\n' }}
+ {%- else %}
+ {{- '\n' }}
+ {%- endif %}
+{%- endif %}
diff --git a/tests/minicpm47_fixtures.py b/tests/minicpm47_fixtures.py
new file mode 100644
index 0000000000..692b55e054
--- /dev/null
+++ b/tests/minicpm47_fixtures.py
@@ -0,0 +1,213 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Tiny HF-shaped checkpoints and tokenizer for MiniCPM integration tests."""
+
+import json
+import re
+
+import mlx.core as mx
+import numpy as np
+
+
+def tiny_config():
+ return {
+ "model_type": "minicpmv4_7",
+ "architectures": ["MiniCPMV4_7ForConditionalGeneration"],
+ "insert_layer_id": 1,
+ "downsample_mode": "16x",
+ "mrope_mode": "canvas",
+ "image_token_id": 8,
+ "video_token_id": 9,
+ "image_start_id": 10,
+ "image_end_id": 11,
+ "slice_start_id": 12,
+ "slice_end_id": 13,
+ "newline_id": 2,
+ "text_config": {
+ "model_type": "qwen3_5_moe_text",
+ "hidden_size": 16,
+ "num_hidden_layers": 4,
+ "mtp_num_hidden_layers": 1,
+ "num_attention_heads": 2,
+ "num_key_value_heads": 1,
+ "head_dim": 8,
+ "linear_num_value_heads": 2,
+ "linear_num_key_heads": 1,
+ "linear_key_head_dim": 4,
+ "linear_value_head_dim": 4,
+ "linear_conv_kernel_dim": 4,
+ "num_experts": 2,
+ "num_experts_per_tok": 1,
+ "shared_expert_intermediate_size": 8,
+ "moe_intermediate_size": 8,
+ "rms_norm_eps": 1e-6,
+ "vocab_size": 32,
+ "max_position_embeddings": 128,
+ "full_attention_interval": 2,
+ "layer_types": ["linear_attention", "full_attention"] * 2,
+ "rope_parameters": {
+ "rope_type": "default",
+ "mrope_section": [2, 1, 1],
+ "partial_rotary_factor": 1.0,
+ "rope_theta": 10000000,
+ "mrope_interleaved": True,
+ },
+ "tie_word_embeddings": False,
+ },
+ "vision_config": {
+ "model_type": "minicpmv4_7_vision",
+ "hidden_size": 8,
+ "intermediate_size": 12,
+ "num_hidden_layers": 3,
+ "num_attention_heads": 2,
+ "num_channels": 3,
+ "image_size": 8,
+ "patch_size": 2,
+ "hidden_act": "gelu_pytorch_tanh",
+ "layer_norm_eps": 1e-6,
+ },
+ }
+
+
+def hf_weight_fixture():
+ shapes = {
+ "model.language_model.embed_tokens.weight": (32, 16),
+ "model.language_model.norm.weight": (16,),
+ "lm_head.weight": (32, 16),
+ "model.vision_tower.embeddings.patch_embedding.weight": (8, 3, 2, 2),
+ "model.vision_tower.embeddings.patch_embedding.bias": (8,),
+ "model.vision_tower.embeddings.position_embedding.weight": (16, 8),
+ "model.vision_tower.post_layernorm.weight": (8,),
+ "model.vision_tower.post_layernorm.bias": (8,),
+ }
+
+ def linear(prefix, out_dim, in_dim, bias=False):
+ shapes[f"{prefix}.weight"] = (out_dim, in_dim)
+ if bias:
+ shapes[f"{prefix}.bias"] = (out_dim,)
+
+ def norm(prefix, dim, bias=False):
+ shapes[f"{prefix}.weight"] = (dim,)
+ if bias:
+ shapes[f"{prefix}.bias"] = (dim,)
+
+ for layer in range(4):
+ prefix = f"model.language_model.layers.{layer}"
+ norm(f"{prefix}.input_layernorm", 16)
+ norm(f"{prefix}.post_attention_layernorm", 16)
+ if layer % 2 == 0:
+ attn = f"{prefix}.linear_attn"
+ shapes[f"{attn}.conv1d.weight"] = (16, 1, 4)
+ for name, out_dim in (
+ ("in_proj_qkv", 16),
+ ("in_proj_z", 8),
+ ("in_proj_a", 2),
+ ("in_proj_b", 2),
+ ):
+ linear(f"{attn}.{name}", out_dim, 16)
+ linear(f"{attn}.out_proj", 16, 8)
+ shapes[f"{attn}.A_log"] = (2,)
+ shapes[f"{attn}.dt_bias"] = (2,)
+ norm(f"{attn}.norm", 4)
+ else:
+ attn = f"{prefix}.self_attn"
+ for name, out_dim in (("q_proj", 32), ("k_proj", 8), ("v_proj", 8)):
+ linear(f"{attn}.{name}", out_dim, 16)
+ linear(f"{attn}.o_proj", 16, 16)
+ norm(f"{attn}.q_norm", 8)
+ norm(f"{attn}.k_norm", 8)
+ mlp = f"{prefix}.mlp"
+ shapes[f"{mlp}.experts.gate_up_proj"] = (2, 16, 16)
+ shapes[f"{mlp}.experts.down_proj"] = (2, 16, 8)
+ linear(f"{mlp}.gate", 2, 16)
+ linear(f"{mlp}.shared_expert_gate", 1, 16)
+ for name in ("gate_proj", "up_proj"):
+ linear(f"{mlp}.shared_expert.{name}", 8, 16)
+ linear(f"{mlp}.shared_expert.down_proj", 16, 8)
+ for layer in range(3):
+ prefix = f"model.vision_tower.encoder.layers.{layer}"
+ for name in ("layer_norm1", "layer_norm2"):
+ norm(f"{prefix}.{name}", 8, True)
+ for name in ("q_proj", "k_proj", "v_proj", "out_proj"):
+ linear(f"{prefix}.self_attn.{name}", 8, 8, True)
+ linear(f"{prefix}.mlp.fc1", 12, 8, True)
+ linear(f"{prefix}.mlp.fc2", 8, 12, True)
+ prefix = "model.vision_tower.vit_merger"
+ norm(f"{prefix}.layer_norm1", 8, True)
+ norm(f"{prefix}.pre_norm", 32, True)
+ for name in ("q_proj", "k_proj", "v_proj", "out_proj"):
+ linear(f"{prefix}.self_attn.{name}", 8, 8, True)
+ linear(f"{prefix}.linear_1", 48, 32, True)
+ linear(f"{prefix}.linear_2", 8, 48, True)
+ prefix = "model.merger.mlp.0"
+ norm(f"{prefix}.pre_norm", 32, True)
+ linear(f"{prefix}.linear_1", 32, 32, True)
+ linear(f"{prefix}.linear_2", 16, 32, True)
+ result = {}
+ for index, (name, shape) in enumerate(sorted(shapes.items())):
+ values = np.sin(np.arange(np.prod(shape), dtype=np.float32) + index) * 0.03
+ if (
+ "layer_norm" in name
+ or "pre_norm.weight" in name
+ or "post_layernorm.weight" in name
+ or name.endswith("linear_attn.norm.weight")
+ ) and name.endswith(".weight"):
+ values += 1.0
+ result[name] = mx.array(values.reshape(shape))
+ return result
+
+
+class Tokenizer:
+ tokens = {
+ "<|image_pad|>": 10,
+ "<|video_pad|>": 11,
+ "": 12,
+ " ": 13,
+ "": 14,
+ " ": 15,
+ "": 16,
+ " ": 17,
+ "<|im_end|>": 18,
+ "<|endoftext|>": 19,
+ "\n": 20,
+ }
+ pad_token_id = 0
+ unk_token_id = -1
+ eos_token_id = 18
+ eos_token = "<|im_end|>"
+ pad_token = ""
+ chat_template = "local-template"
+ init_kwargs = {}
+
+ def convert_tokens_to_ids(self, token):
+ return self.tokens.get(token, self.unk_token_id)
+
+ def encode(self, text, **kwargs):
+ pattern = "|".join(
+ re.escape(token) for token in sorted(self.tokens, key=len, reverse=True)
+ )
+ return [
+ self.tokens[chunk] if chunk in self.tokens else 100 + ord(chunk)
+ for chunk in re.findall(pattern + r"|[\s\S]", text)
+ ]
+
+ def decode(self, ids, **kwargs):
+ inverse = {value: key for key, value in self.tokens.items()}
+ return "".join(
+ inverse.get(value, chr(value - 100) if value >= 100 else "")
+ for value in ids
+ )
+
+ def batch_decode(self, rows, **kwargs):
+ return [self.decode(row, **kwargs) for row in rows]
+
+ def apply_chat_template(self, messages, **kwargs):
+ output = json.dumps(kwargs.get("tools", [])) + "".join(
+ message["content"] for message in messages
+ )
+ if kwargs.get("add_generation_prompt"):
+ output += (
+ ""
+ if kwargs.get("enable_thinking", True)
+ else "\n\n \n\n"
+ )
+ return self.encode(output) if kwargs.get("tokenize") else output
diff --git a/tests/minicpm47_native_cases.py b/tests/minicpm47_native_cases.py
new file mode 100644
index 0000000000..db29a76783
--- /dev/null
+++ b/tests/minicpm47_native_cases.py
@@ -0,0 +1,921 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Real native/oMLX contracts, collected only by the isolated CPU runner."""
+
+import copy
+import json
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import patch
+
+import mlx.core as mx
+import mlx.nn as nn
+import numpy as np
+import pytest
+from minicpm47_fixtures import Tokenizer, hf_weight_fixture, tiny_config
+from mlx.utils import tree_flatten
+from mlx_vlm.models.cache import ArraysCache, BatchKVCache, KVCache, RotatingKVCache
+from mlx_vlm.models.minicpmv4_7 import Model, ModelConfig
+from PIL import Image
+from transformers.utils.chat_template_utils import render_jinja_template
+
+from omlx.engine.vlm import VLMBatchedEngine
+from omlx.models.vlm import VLMModelAdapter
+from omlx.patches.minicpm47 import apply_minicpm47_serving_patch
+from omlx.patches.mlx_lm_mtp import batch_generator as bg
+from omlx.scheduler import _bind_text_prefill_rope_delta
+from omlx.speculative.dflash import attach_drafter, load_dflash_drafter
+from omlx.speculative.dspark_drafter import DSparkDrafter
+from omlx.speculative.minicpm_dspark import (
+ MiniCPMDSparkConfig,
+ MiniCPMDSparkDraftModel,
+)
+from omlx.speculative.minicpm_pairing import HELPER, TARGET
+from omlx.utils.sampling import make_sampler
+
+
+def model():
+ apply_minicpm47_serving_patch()
+ target = Model(ModelConfig.from_dict(tiny_config()))
+ target.load_weights(list(target.sanitize(hf_weight_fixture()).items()), strict=True)
+ return target
+
+
+@pytest.mark.parametrize(
+ "representation", ["hf", "canonical", "mixed", "mixed-current"]
+)
+def test_complete_checkpoint_through_official_strict_loader(tmp_path, representation):
+ from mlx_vlm.utils import load_model
+
+ target = model()
+ config = tiny_config()
+ if representation == "hf":
+ weights = hf_weight_fixture()
+ else:
+ if representation.startswith("mixed"):
+ config["quantization"] = {"bits": 4, "group_size": 32, "mode": "affine"}
+ overrides = {
+ "merger.mlp.0.linear_1": {
+ "bits": 8,
+ "group_size": 32,
+ "mode": "affine",
+ },
+ "merger.mlp.0.linear_2": {
+ "bits": 4,
+ "group_size": 32,
+ "mode": "affine",
+ },
+ "vit_merger.linear_1": {
+ "bits": 8,
+ "group_size": 32,
+ "mode": "affine",
+ },
+ }
+ config["quantization"].update(
+ {
+ (
+ f"vision_tower.{path}"
+ if path.startswith("vit_merger.") and representation == "mixed"
+ else path
+ ): value
+ for path, value in overrides.items()
+ }
+ )
+ if representation == "mixed-current":
+ config["quantization"]["vision_tower.vit_merger.linear_1"] = {
+ "bits": 4,
+ "group_size": 32,
+ "mode": "affine",
+ }
+ nn.quantize(
+ target,
+ bits=4,
+ group_size=32,
+ class_predicate=lambda path, module: overrides.get(path, False),
+ )
+ weights = {
+ (
+ key.replace("vit_merger.", "vision_tower.vit_merger.", 1)
+ if key.startswith("vit_merger.")
+ else key
+ ): value
+ for key, value in tree_flatten(target.parameters())
+ }
+ sanitized = target.sanitize(weights)
+ repeated = target.sanitize(sanitized)
+ assert sanitized.keys() == repeated.keys()
+ for key in sanitized:
+ np.testing.assert_array_equal(
+ np.array(sanitized[key]), np.array(repeated[key])
+ )
+ (tmp_path / "config.json").write_text(json.dumps(config))
+ mx.save_safetensors(str(tmp_path / "model.safetensors"), weights)
+ loaded = load_model(tmp_path, strict=True, lazy=False)
+ assert json.loads((tmp_path / "config.json").read_text()) == config
+ expected = dict(tree_flatten(target.parameters()))
+ actual = dict(tree_flatten(loaded.parameters()))
+ assert actual.keys() == expected.keys()
+ for key in expected:
+ np.testing.assert_array_equal(np.array(actual[key]), np.array(expected[key]))
+ if representation.startswith("mixed"):
+ assert loaded.merger.mlp[0].linear_1.bits == 8
+ assert loaded.merger.mlp[0].linear_2.bits == 4
+ assert loaded.vit_merger.linear_1.bits == 8
+
+
+def test_qwen_mtp_load_does_not_attach_head_to_following_minicpm(tmp_path, monkeypatch):
+ from mlx_vlm.models.qwen3_5_moe.config import TextConfig
+ from mlx_vlm.models.qwen3_5_moe.language import LanguageModel
+ from mlx_vlm.utils import load_model
+
+ from omlx.patches import mlx_lm_mtp, mlx_vlm_mtp
+
+ model()
+ mlx_vlm_mtp.apply_mlx_vlm_mtp_runtime_patch("qwen3_5_moe")
+ monkeypatch.setattr(mlx_vlm_mtp, "_MTP_ATTACH_ENABLED", True)
+ monkeypatch.setattr(mlx_lm_mtp, "_MTP_ACTIVE", True)
+ config = tiny_config()
+ qwen = LanguageModel(TextConfig.from_dict(config["text_config"]))
+ assert qwen.mtp is not None
+ assert qwen._omlx_mtp_decode_enabled
+
+ (tmp_path / "config.json").write_text(json.dumps(config))
+ mx.save_safetensors(str(tmp_path / "model.safetensors"), hf_weight_fixture())
+ target = load_model(tmp_path, strict=True, lazy=False)
+ assert target.config.text_config.mtp_num_hidden_layers == 1
+ assert not hasattr(target.language_model, "mtp")
+ assert not getattr(target.language_model, "_omlx_mtp_decode_enabled", False)
+ assert mlx_vlm_mtp.is_mtp_attach_enabled()
+ assert mlx_lm_mtp.is_mtp_active()
+ following_qwen = LanguageModel(TextConfig.from_dict(config["text_config"]))
+ assert following_qwen.mtp is not None
+ assert following_qwen._omlx_mtp_decode_enabled
+
+
+def test_hooks_are_family_local_and_preserve_normalization():
+ from mlx_vlm.models.qwen3_5.language import Qwen3_5GatedDeltaNet
+
+ target = model()
+ layer = target.language_model.layers[0].linear_attn
+ assert not apply_minicpm47_serving_patch()
+ q = mx.full((1, 1, 1, layer.head_k_dim), 0.0001)
+ actual_q, actual_k = layer._normalize_qk(q, q)
+ inv_scale = layer.head_k_dim**-0.5
+ eps = 1e-6 / layer.head_k_dim
+ np.testing.assert_allclose(
+ np.array(actual_q), np.array(inv_scale**2 * mx.fast.rms_norm(q, None, eps))
+ )
+ np.testing.assert_allclose(
+ np.array(actual_k), np.array(inv_scale * mx.fast.rms_norm(q, None, eps))
+ )
+ assert Qwen3_5GatedDeltaNet._normalize_qk is not layer._normalize_qk.__func__
+
+
+@pytest.mark.parametrize("side", ["left", "right"])
+def test_padded_prefill_and_continuation_match_unpadded_rows(side):
+ language = model().language_model
+ rows = [[3, 4, 5, 6], [3, 4]]
+ ids = [rows[0], [0, 0, 3, 4] if side == "left" else [3, 4, 0, 0]]
+ mask = [[1] * 4, [0, 0, 1, 1] if side == "left" else [1, 1, 0, 0]]
+ caches = language.make_cache()
+ output = language(
+ mx.array(ids),
+ attention_mask=mx.array(mask),
+ cache=caches,
+ rope_deltas=mx.zeros((2, 1), mx.int32),
+ capture_layer_ids=[0, 3],
+ )
+ continuation = language(
+ mx.array([[5], [5]]), cache=caches, rope_deltas=mx.zeros((2, 1), mx.int32)
+ )
+ for index, row in enumerate(rows):
+ cache = language.make_cache()
+ expected = language(
+ mx.array([row]),
+ cache=cache,
+ capture_layer_ids=[0, 3],
+ rope_deltas=mx.zeros((1, 1), mx.int32),
+ )
+ valid = np.array(mask[index], dtype=bool)
+ np.testing.assert_allclose(
+ np.asarray(output.logits)[index, valid],
+ np.asarray(expected.logits)[0],
+ atol=3e-5,
+ )
+ for layer in range(2):
+ np.testing.assert_allclose(
+ np.asarray(output.hidden_states[layer])[index, valid],
+ np.asarray(expected.hidden_states[layer])[0],
+ atol=3e-5,
+ )
+ next_output = language(
+ mx.array([[5]]), cache=cache, rope_deltas=mx.zeros((1, 1), mx.int32)
+ )
+ np.testing.assert_allclose(
+ np.asarray(continuation.logits)[index],
+ np.asarray(next_output.logits)[0],
+ atol=3e-5,
+ )
+
+
+def test_scheduler_prepared_padding_windows_preserve_cache_and_row_positions():
+ language = model().language_model
+ caches = [
+ (
+ BatchKVCache([0, 2])
+ if isinstance(entry, KVCache)
+ else ArraysCache(len(entry.cache), left_padding=[0, 2])
+ )
+ for entry in language.make_cache()
+ ]
+ language(
+ mx.array([[3, 4], [0, 0]]),
+ attention_mask=mx.array([[1, 1], [0, 0]]),
+ cache=caches,
+ rope_deltas=mx.zeros((2, 1), mx.int32),
+ )
+ output = language(
+ mx.array([[5, 6], [3, 4]]),
+ attention_mask=mx.ones((2, 2), mx.int32),
+ cache=caches,
+ rope_deltas=mx.zeros((2, 1), mx.int32),
+ capture_layer_ids=[3, 0],
+ )
+ continuation = language(
+ mx.array([[5], [5]]), cache=caches, rope_deltas=mx.zeros((2, 1), mx.int32)
+ )
+ for index, row in enumerate([[3, 4, 5, 6], [3, 4]]):
+ cache = language.make_cache()
+ expected = language(
+ mx.array([row]),
+ cache=cache,
+ rope_deltas=mx.zeros((1, 1), mx.int32),
+ capture_layer_ids=[3, 0],
+ )
+ np.testing.assert_allclose(
+ np.asarray(output.logits)[index],
+ np.asarray(expected.logits)[0, -2:],
+ atol=3e-5,
+ )
+ for actual_hidden, expected_hidden in zip(
+ output.hidden_states, expected.hidden_states, strict=True
+ ):
+ np.testing.assert_allclose(
+ np.asarray(actual_hidden)[index],
+ np.asarray(expected_hidden)[0, -2:],
+ atol=3e-5,
+ )
+ expected_next = language(
+ mx.array([[5]]), cache=cache, rope_deltas=mx.zeros((1, 1), mx.int32)
+ )
+ np.testing.assert_allclose(
+ np.asarray(continuation.logits)[index],
+ np.asarray(expected_next.logits)[0],
+ atol=3e-5,
+ )
+
+
+@pytest.mark.parametrize(
+ "mask,verify,error",
+ [
+ ([[1, 1, 1, 1], [0, 2, 1, 1]], False, "binary"),
+ ([[1, 1, 1], [0, 1, 1]], False, "binary"),
+ ([[1, 1, 1, 1], [1, 0, 1, 0]], False, "contiguous"),
+ ([[1, 1, 1, 1], [0, 0, 0, 0]], False, "at least one"),
+ ([[1, 1, 1, 1], [0, 0, 1, 1]], True, "padded proposals"),
+ ],
+)
+def test_invalid_padding_fails_before_cache_mutation(mask, verify, error):
+ language = model().language_model
+ caches = language.make_cache()
+ original = list(caches)
+ with pytest.raises(ValueError, match=error):
+ language(
+ mx.array([[3, 4, 5, 6], [0, 0, 3, 4]]),
+ attention_mask=mx.array(mask),
+ cache=caches,
+ speculative_verify=verify,
+ )
+ assert all(before is after for before, after in zip(original, caches))
+ assert all(entry.empty() for entry in caches)
+ assert all(
+ entry.left_padding is None for entry in caches if isinstance(entry, ArraysCache)
+ )
+
+
+@pytest.mark.parametrize("mode", ["4x", "16x"])
+def test_official_processor_video_controls_and_interleaved_image_order(mode):
+ from mlx_vlm.models.minicpmv4_6.processing_minicpmv4_6 import (
+ MiniCPMVImageProcessor,
+ MiniCPMVVideoProcessor,
+ )
+ from mlx_vlm.models.minicpmv4_7 import MiniCPMV4_7Processor
+ from mlx_vlm.utils import process_inputs
+
+ model()
+ processor = MiniCPMV4_7Processor(
+ image_processor=MiniCPMVImageProcessor(scale_resolution=8, patch_size=2),
+ video_processor=MiniCPMVVideoProcessor(scale_resolution=8, patch_size=2),
+ tokenizer=Tokenizer(),
+ )
+ inputs = process_inputs(
+ processor,
+ prompts=["<|video_pad|>then<|image_pad|>"],
+ images=[Image.new("RGB", (8, 8), "red")],
+ videos=[[Image.new("RGB", (8, 8), "blue") for _ in range(4)]],
+ downsample_mode=mode,
+ max_slice_nums=1,
+ max_num_frames=2,
+ )
+ ids = inputs["input_ids"][0].tolist()
+ count = 4 if mode == "4x" else 1
+ assert ids.count(10) == count
+ assert ids.count(11) == 2 * count
+ assert ids.index(11) < ids.index(10)
+ assert len(inputs["tgt_sizes"][0]) == 3
+ assert inputs["downsample_mode"] == mode
+ assert processor.image_processor.downsample_mode == "16x"
+ assert processor.video_processor.downsample_mode == "16x"
+ assert processor.image_processor.max_slice_nums == 9
+ assert processor.video_processor.max_num_frames == 128
+ config = tiny_config()
+ config.update(
+ image_token_id=10,
+ video_token_id=11,
+ image_start_id=12,
+ image_end_id=13,
+ slice_start_id=14,
+ slice_end_id=15,
+ newline_id=20,
+ )
+ config["text_config"]["vocab_size"] = 512
+ target = Model(ModelConfig.from_dict(config))
+ features = target.get_input_embeddings(
+ mx.array(inputs["input_ids"]),
+ inputs["pixel_values"],
+ tgt_sizes=inputs["tgt_sizes"],
+ downsample_mode=mode,
+ )
+ assert features.inputs_embeds.shape == (1, len(ids), 16)
+ assert features.position_ids.shape == (3, 1, len(ids))
+
+
+def test_paired_dspark_policy_and_probability_errors():
+ helper = MiniCPMDSparkDraftModel(MiniCPMDSparkConfig.from_dict(helper_config()))
+ assert helper.prefer_requested_block_size
+ invalid = helper_config()
+ invalid["dflash_config"]["block_size_policy"] = "adaptive"
+ with pytest.raises(ValueError, match="fixed-block"):
+ MiniCPMDSparkConfig.from_dict(invalid)
+ invalid = helper_config()
+ invalid["target_model_type"] = "qwen3"
+ with pytest.raises(ValueError, match="explicitly paired"):
+ MiniCPMDSparkConfig.from_dict(invalid)
+ target = model()
+ helper.bind(target)
+ hidden = mx.zeros((1, 2, 32))
+ with pytest.raises(ValueError, match="finite and normalized"):
+ helper.propose_block(
+ 4,
+ hidden,
+ helper.make_cache(),
+ 3,
+ lambda logits: logits.argmax(-1),
+ proposal_probs=lambda logprobs: mx.zeros_like(logprobs),
+ )
+
+
+@pytest.mark.parametrize("mode", ["4x", "16x"])
+@pytest.mark.parametrize("dtype", [mx.float32, mx.bfloat16])
+def test_quantized_token_table_preserves_image_and_video_encoding(
+ tmp_path, monkeypatch, mode, dtype
+):
+ from mlx_vlm.utils import load_model
+
+ model()
+ config = tiny_config()
+ config["text_config"]["hidden_size"] = 32
+ target = Model(ModelConfig.from_dict(config))
+ embedding = target.language_model.model.embed_tokens.to_quantized(32, 8)
+ embedding.set_dtype(dtype)
+ target.language_model.model.embed_tokens = embedding
+ reference = copy.deepcopy(target)
+ plain = nn.Embedding(32, 32)
+ plain.weight = mx.dequantize(
+ embedding.weight, embedding.scales, embedding.biases, group_size=32, bits=8
+ )
+ reference.language_model.model.embed_tokens = plain
+ config["quantization"] = {
+ "group_size": 32,
+ "bits": 4,
+ "mode": "affine",
+ "language_model.model.embed_tokens": {
+ "group_size": 32,
+ "bits": 8,
+ "mode": "affine",
+ },
+ }
+ (tmp_path / "config.json").write_text(json.dumps(config))
+ mx.save_safetensors(
+ str(tmp_path / "model.safetensors"), dict(tree_flatten(target.parameters()))
+ )
+ target = load_model(tmp_path, strict=True, lazy=False)
+ assert target.language_model.model.embed_tokens.weight.dtype == mx.uint32
+ embedding_class = type(target.vision_tower.embeddings)
+ original_call = embedding_class.__call__
+ pixel_dtypes = []
+
+ def record_pixels(self, pixels, *args, **kwargs):
+ pixel_dtypes.append(pixels.dtype)
+ return original_call(self, pixels, *args, **kwargs)
+
+ monkeypatch.setattr(embedding_class, "__call__", record_pixels)
+ count = 4 if mode == "4x" else 1
+ ids = mx.array([[3] + [8] * count + [4] + [9] * count + [5]])
+ pixels = mx.arange(192, dtype=mx.float32).reshape(3, 2, 32) / 192 - 0.5
+ inputs = {
+ "pixel_values": [[pixels, -pixels]],
+ "tgt_sizes": [mx.array([[4, 4], [4, 4]])],
+ "downsample_mode": mode,
+ }
+ expected = reference.get_input_embeddings(ids, **inputs)
+ actual = target.get_input_embeddings(ids, **inputs)
+ assert (
+ pixel_dtypes
+ == [target.vision_tower.embeddings.patch_embedding.weight.dtype] * 4
+ )
+ assert actual.inputs_embeds.dtype == dtype
+ assert mx.all(mx.isfinite(actual.inputs_embeds)).item()
+ assert mx.array_equal(actual.inputs_embeds, expected.inputs_embeds).item()
+ np.testing.assert_array_equal(
+ np.asarray(actual.position_ids), np.asarray(expected.position_ids)
+ )
+
+
+def test_real_native_parameter_order_keeps_fused_expert_mates_adjacent():
+ names = [name for name, _ in tree_flatten(model().parameters())]
+ pairs = 0
+ for index, name in enumerate(names):
+ if name.endswith(".switch_mlp.gate_proj.weight"):
+ assert names[index + 1] == name.replace(
+ ".gate_proj.weight", ".up_proj.weight"
+ )
+ pairs += 1
+ assert pairs == 4
+
+
+@pytest.mark.parametrize("mode", ["4x", "16x"])
+@pytest.mark.parametrize("accepted", [0, 1, 2])
+@pytest.mark.parametrize("rotating", [False, True])
+def test_real_omlx_capture_verifier_and_commit(mode, accepted, rotating):
+ target = model()
+ adapter = VLMModelAdapter(target)
+ count = 4 if mode == "4x" else 1
+ ids = mx.array([[3, 10] + [8] * count + [11, 4]])
+ features = target.get_input_embeddings(
+ ids,
+ [[mx.arange(192, dtype=mx.float32).reshape(3, 2, 32) / 192]],
+ tgt_sizes=[mx.array([[4, 4]])],
+ downsample_mode=mode,
+ mm_token_type_ids=(ids == 8).astype(mx.int32),
+ )
+ adapter.set_batch_rope_deltas(features.rope_deltas.reshape(-1))
+
+ def prime():
+ cache = target.language_model.make_cache()
+ if rotating:
+ cache = [
+ (
+ RotatingKVCache(max_size=4, keep=0)
+ if isinstance(entry, KVCache)
+ else entry
+ )
+ for entry in cache
+ ]
+ adapter(
+ ids,
+ cache=cache,
+ inputs_embeds=features.inputs_embeds,
+ vlm_extra_kwargs={
+ "position_ids": features.position_ids,
+ "rope_deltas": features.rope_deltas,
+ },
+ )
+ return cache
+
+ actual_cache, reference_cache = prime(), prime()
+ block = mx.array([[5, 6, 7]])
+ logits, hidden, transaction, captures = bg._call_backbone_captured(
+ adapter, block, actual_cache, n_confirmed=1, capture_layer_ids=[2, 0]
+ )
+ assert transaction is not None
+ expected = [
+ target.language_model(
+ block[:, index : index + 1],
+ cache=reference_cache,
+ rope_deltas=features.rope_deltas,
+ capture_layer_ids=[0, 2, 3],
+ return_hidden=False,
+ )
+ for index in range(3)
+ ]
+ np.testing.assert_allclose(
+ np.array(logits),
+ np.array(mx.concatenate([row.logits for row in expected], 1)),
+ atol=3e-5,
+ )
+ for actual, native_index in zip([*captures, hidden], [1, 0, 2], strict=True):
+ np.testing.assert_allclose(
+ np.array(actual),
+ np.array(
+ mx.concatenate([row.hidden_states[native_index] for row in expected], 1)
+ ),
+ atol=3e-5,
+ )
+ adapter.rollback_speculative_cache(actual_cache, transaction, accepted, 3)
+ replay_cache = prime()
+ for index in range(accepted + 1):
+ adapter(block[:, index : index + 1], cache=replay_cache)
+ token = mx.array([[15]])
+ actual = adapter(token, cache=actual_cache)
+ replay = adapter(token, cache=replay_cache)
+ np.testing.assert_allclose(np.array(actual), np.array(replay), atol=3e-5)
+
+
+def test_real_raw_text_chunks_rebind_zero_delta_after_interleaved_media():
+ target = model()
+ adapter = VLMModelAdapter(target)
+ ids = mx.array([[3, 4, 5, 6, 7]])
+ cache = adapter.make_cache()
+ first = []
+ for start, end in ((0, 2), (2, 5)):
+ adapter.set_batch_rope_deltas(mx.array([-17]))
+ _bind_text_prefill_rope_delta(adapter, 0.0)
+ first.append(adapter(ids[:, start:end], cache=cache))
+ full = target.language_model(ids).logits
+ np.testing.assert_allclose(
+ np.array(mx.concatenate(first, 1)), np.array(full), atol=3e-5
+ )
+ adapter.set_batch_rope_deltas(None)
+ with pytest.raises(ValueError, match="request-local rope_deltas"):
+ adapter(mx.array([[15]]), cache=cache)
+
+
+@pytest.mark.parametrize("rotating", [False, True])
+def test_real_verify_abort_restores_gdn_and_kv_for_next_request(rotating):
+ target = model()
+ adapter = VLMModelAdapter(target)
+ adapter.set_batch_rope_deltas(mx.array([0]))
+
+ def prime():
+ cache = adapter.make_cache()
+ if rotating:
+ cache = [
+ (
+ RotatingKVCache(max_size=4, keep=0)
+ if isinstance(entry, KVCache)
+ else entry
+ )
+ for entry in cache
+ ]
+ adapter(mx.array([[2, 3, 4]]), cache=cache)
+ return cache
+
+ actual_cache, reference_cache = prime(), prime()
+ _, _, transaction, _ = bg._call_backbone_captured(
+ adapter,
+ mx.array([[5, 6, 7]]),
+ actual_cache,
+ n_confirmed=1,
+ capture_layer_ids=[0, 2],
+ )
+ adapter.abort_speculative_forward()
+ adapter.abort_speculative_forward()
+ assert not transaction._active
+ np.testing.assert_allclose(
+ np.array(adapter(mx.array([[15]]), cache=actual_cache)),
+ np.array(adapter(mx.array([[15]]), cache=reference_cache)),
+ atol=3e-5,
+ )
+
+
+@pytest.mark.parametrize("mode", ["4x", "16x"])
+def test_actual_omlx_jinja_processor_encoder_and_tool_parser(mode):
+ from mlx_vlm.models.minicpmv4_6.processing_minicpmv4_6 import MiniCPMVImageProcessor
+ from mlx_vlm.models.minicpmv4_7 import MiniCPMV4_7Processor
+
+ template = (
+ Path(__file__).parent / "fixtures/minicpmv4_7_chat_template.jinja"
+ ).read_text()
+
+ class OfficialTokenizer(Tokenizer):
+ tokens = {
+ **Tokenizer.tokens,
+ "<|image_pad|>": 8,
+ "<|video_pad|>": 9,
+ "": 10,
+ " ": 11,
+ "": 12,
+ " ": 13,
+ "\n": 2,
+ "": 22,
+ " ": 23,
+ }
+ chat_template = template
+
+ def get_vocab(self):
+ return self.tokens
+
+ def apply_chat_template(self, messages, **kwargs):
+ kwargs.pop("tokenize", None)
+ kwargs.pop("chat_template", None)
+ return render_jinja_template(
+ conversations=[messages], chat_template=template, **kwargs
+ )[0][0]
+
+ config = tiny_config()
+ config["text_config"]["vocab_size"] = 512
+ target = Model(ModelConfig.from_dict(config))
+ engine = VLMBatchedEngine(model_name="fixture")
+ engine._vlm_model = target
+ engine._model_type = "minicpmv4_7"
+ engine._processor = MiniCPMV4_7Processor(
+ image_processor=MiniCPMVImageProcessor(scale_resolution=8, patch_size=2),
+ tokenizer=OfficialTokenizer(),
+ )
+ engine._vision_cache = None
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "image"},
+ {"type": "text", "text": "compare"},
+ {"type": "image"},
+ ],
+ }
+ ]
+ prepared = engine._prepare_vision_inputs(
+ messages,
+ [Image.new("RGB", (8, 8)), Image.new("RGB", (8, 8))],
+ mm_processor_kwargs={"downsample_mode": mode, "max_slice_nums": 1},
+ )
+ ids, embeddings, extra = prepared[:3]
+ assert embeddings.shape == (1, len(ids), 16)
+ assert extra["position_ids"].shape == (3, 1, len(ids))
+ assert extra["_captured_rope_deltas"].shape == (1, 1)
+ assert ids.count(8) == (8 if mode == "4x" else 2)
+ tokenizer = engine._processor.tokenizer
+ engine._inject_tool_calling(tokenizer)
+ assert tokenizer.has_tool_calling
+ call = tokenizer.tool_parser(
+ "\n\nvalue\n \n ",
+ [
+ {
+ "type": "function",
+ "function": {
+ "name": "lookup",
+ "parameters": {
+ "type": "object",
+ "properties": {"query": {"type": "string"}},
+ },
+ },
+ }
+ ],
+ )
+ assert call["name"] == "lookup"
+ assert call["arguments"] == {"query": "value"}
+
+
+def helper_config():
+ return {
+ "model_type": "qwen3",
+ "hidden_size": 16,
+ "intermediate_size": 32,
+ "num_hidden_layers": 1,
+ "num_attention_heads": 2,
+ "num_key_value_heads": 2,
+ "head_dim": 8,
+ "vocab_size": 32,
+ "target_model_type": "minicpmv4_7",
+ "dflash_config": {
+ "projector_type": "dspark",
+ "block_size": 3,
+ "block_size_policy": "fixed",
+ "mask_token_id": 31,
+ "target_layer_ids": [0, 1],
+ "num_target_layers": 4,
+ "markov_rank": 4,
+ "enable_confidence_head": True,
+ },
+ }
+
+
+def generation_batch(temperature):
+ from mlx_lm.generate import BatchGenerator
+
+ target = model()
+ adapter = VLMModelAdapter(target)
+ adapter.set_batch_rope_deltas(mx.array([0]))
+ helper = MiniCPMDSparkDraftModel(MiniCPMDSparkConfig.from_dict(helper_config()))
+ helper.bind(target)
+ drafter = DSparkDrafter(helper, block_size=3, source_path="tiny-fixture")
+ attach_drafter(target.language_model, drafter)
+ bg.apply()
+ sampler = make_sampler(temp=temperature, top_k=2 if temperature else 0)
+ cache = adapter.make_cache()
+ prefill = adapter(mx.array([[2, 3, 4]]), cache=cache, capture_layer_ids=[0, 1])
+ drafter.seed_request("fixture", prefill.hidden_states)
+ generator = BatchGenerator(
+ adapter,
+ max_tokens=7,
+ sampler=sampler,
+ stream=mx.new_stream(mx.cpu),
+ )
+ uid = generator.insert([[5]], caches=[cache], all_tokens=[[2, 3, 4, 5]])[0]
+ drafter.bind_uid("fixture", uid)
+ adapter.register_rope_delta(uid, 0.0)
+ adapter.set_native_mtp_request_eligible(uid, False)
+ return target, adapter, helper, drafter, generator, uid
+
+
+@pytest.mark.parametrize("temperature", [0.0, 0.7])
+def test_real_omlx_generation_batch_with_native_dspark(temperature):
+ target, adapter, helper, drafter, generator, uid = generation_batch(temperature)
+ responses = []
+ with (
+ patch.object(helper, "propose_block", wraps=helper.propose_block) as propose,
+ patch.object(
+ adapter,
+ "rollback_speculative_cache",
+ wraps=adapter.rollback_speculative_cache,
+ ) as commit,
+ ):
+ for _ in range(12):
+ _, outputs = generator.next()
+ responses.extend(outputs)
+ if any(output.finish_reason is not None for output in outputs):
+ break
+ assert propose.call_count > 0
+ assert commit.call_count > 0
+ assert len(responses) == 7
+ assert all(output.uid == uid for output in responses)
+ assert responses[-1].finish_reason == "length"
+ assert all(output.finish_reason is None for output in responses[:-1])
+ assert not adapter._minicpm_speculative_transactions
+ if temperature == 0:
+ reference_cache = target.language_model.make_cache()
+ tokens = mx.array([[2, 3, 4, 5]])
+ reference = []
+ for _ in range(7):
+ logits = target.language_model(
+ tokens, cache=reference_cache, rope_deltas=mx.array([[0]])
+ ).logits
+ token = int(mx.argmax(logits[:, -1]).item())
+ reference.append(token)
+ tokens = mx.array([[token]])
+ assert [output.token for output in responses] == reference
+ generator.close()
+ assert not drafter._rows
+
+
+def test_real_generation_sampler_failure_aborts_verify_and_cancellation_releases():
+ _, adapter, _, drafter, generator, uid = generation_batch(0.7)
+ snapshots = []
+ original = bg._call_backbone_captured
+
+ def snapshot_forward(model, inputs, cache, **kwargs):
+ if kwargs.get("n_confirmed") == 1 and inputs.shape[1] > 1:
+ snapshots.append(
+ (
+ cache,
+ [
+ [
+ None if value is None else np.array(value)
+ for value in entry.state
+ ]
+ for entry in cache
+ ],
+ )
+ )
+ return original(model, inputs, cache, **kwargs)
+
+ with (
+ patch.object(bg, "_call_backbone_captured", side_effect=snapshot_forward),
+ patch.object(
+ bg, "_stochastic_verify_tokens", side_effect=RuntimeError("fixture sampler")
+ ),
+ pytest.raises(RuntimeError, match="fixture sampler"),
+ ):
+ for _ in range(12):
+ generator.next()
+ assert not adapter._minicpm_speculative_transactions
+ assert len(snapshots) == 1
+ cache, before = snapshots[0]
+ for entry, expected in zip(cache, before, strict=True):
+ for value, reference in zip(entry.state, expected, strict=True):
+ if reference is None:
+ assert value is None
+ else:
+ np.testing.assert_array_equal(np.array(value), reference)
+ generator.remove([uid])
+ assert uid not in drafter._rows
+ assert not adapter._minicpm_speculative_transactions
+ generator.close()
+
+
+def test_real_omlx_dspark_greedy_batch_with_different_full_histories():
+ target, adapter, helper, drafter, generator, first_uid = generation_batch(0.0)
+ second_cache = adapter.make_cache()
+ prefill = adapter(
+ mx.array([[2, 3, 4, 5, 6]]),
+ cache=second_cache,
+ capture_layer_ids=[0, 1],
+ )
+ drafter.seed_request("second", prefill.hidden_states)
+ second_uid = generator.insert(
+ [[7]], caches=[second_cache], all_tokens=[[2, 3, 4, 5, 6, 7]]
+ )[0]
+ drafter.bind_uid("second", second_uid)
+ adapter.register_rope_delta(second_uid, 0.0)
+ adapter.set_native_mtp_request_eligible(second_uid, False)
+ adapter.set_batch_rope_deltas(mx.array([0, 0]))
+ responses = {first_uid: [], second_uid: []}
+ with (
+ patch.object(helper, "propose_block", wraps=helper.propose_block) as propose,
+ patch.object(drafter, "draft", wraps=drafter.draft) as draft,
+ ):
+ for _ in range(20):
+ _, outputs = generator.next()
+ for output in outputs:
+ responses[output.uid].append(output)
+ if all(
+ row and row[-1].finish_reason is not None for row in responses.values()
+ ):
+ break
+ assert propose.call_count > 1
+ assert any(len(call.args[0]) == 2 for call in draft.call_args_list)
+ for uid, prompt in (
+ (first_uid, [2, 3, 4, 5]),
+ (second_uid, [2, 3, 4, 5, 6, 7]),
+ ):
+ cache = target.language_model.make_cache()
+ tokens = mx.array([prompt])
+ expected = []
+ for _ in range(7):
+ logits = target.language_model(
+ tokens, cache=cache, rope_deltas=mx.array([[0]])
+ ).logits
+ token = int(mx.argmax(logits[:, -1]).item())
+ expected.append(token)
+ tokens = mx.array([[token]])
+ assert [output.token for output in responses[uid]] == expected
+ assert responses[uid][-1].finish_reason == "length"
+ assert not adapter._minicpm_speculative_transactions
+ generator.close()
+ assert not drafter._rows
+
+
+def test_real_helper_strict_load_without_tokenizer_and_native_q_handoff(tmp_path):
+ config = helper_config()
+ helper = MiniCPMDSparkDraftModel(MiniCPMDSparkConfig.from_dict(config))
+ config["omlx_source"] = {"repo_id": HELPER[0], "revision": HELPER[1]}
+ (tmp_path / "config.json").write_text(json.dumps(config))
+ mx.save_safetensors(
+ str(tmp_path / "model.safetensors"),
+ dict(tree_flatten(helper.parameters())),
+ )
+ target = model()
+ engine = VLMBatchedEngine(model_name="tiny-minicpm")
+ engine._vlm_model = target
+ with patch("omlx.engine.vlm.drafter_target.apply") as install:
+ assert engine.prepare_dflash_target() is target
+ install.assert_not_called()
+ target_path = tmp_path / "target"
+ target_path.mkdir()
+ (target_path / "config.json").write_text(
+ json.dumps({"omlx_source": {"repo_id": TARGET[0], "revision": TARGET[1]}})
+ )
+ drafter = load_dflash_drafter(
+ str(tmp_path), target, target_path=str(target_path), block_size=4
+ )
+ assert isinstance(drafter, DSparkDrafter)
+ captures = target.language_model(
+ mx.array([[2, 3, 4]]), capture_layer_ids=[0, 1]
+ ).hidden_states
+ state = SimpleNamespace(uid=7, stats=None)
+ sampler = make_sampler(temp=0.7, top_k=2, top_p=1.0)
+ with (
+ patch.object(bg, "_is_greedy", return_value=False),
+ patch.object(bg, "_resolve_draft_sampler", return_value=sampler),
+ ):
+ mx.random.seed(9)
+ drafter.draft(
+ [(SimpleNamespace(uids=[7]), state, captures, mx.array([4]), None)]
+ )
+ assert state.drafts.shape == (3,)
+ assert len(state.draft_accept_lps) == 3
+ assert drafter._rows[7].confidences.shape == (1, 3)
+ for law in state.draft_accept_lps:
+ assert float(mx.sum(mx.exp(law)).item()) == pytest.approx(1.0, abs=1e-5)
+ assert int(mx.sum(mx.isfinite(law)).item()) == 2
+ drafter.clear()
+ assert drafter.context_length(7) == 0
diff --git a/tests/test_anthropic_models.py b/tests/test_anthropic_models.py
index 8a26660e3e..d1d44227a7 100644
--- a/tests/test_anthropic_models.py
+++ b/tests/test_anthropic_models.py
@@ -6,7 +6,7 @@
including content blocks, tools, and streaming events.
"""
-import json
+
import pytest
from pydantic import ValidationError
@@ -27,10 +27,11 @@
ErrorEvent,
InputJsonDelta,
MessageDeltaEvent,
- MessageStartEvent,
- MessageStopEvent,
MessagesRequest,
MessagesResponse,
+ MessageStartEvent,
+ MessageStopEvent,
+ OutputConfig,
PingEvent,
SystemContent,
TextDelta,
@@ -460,6 +461,16 @@ def test_thinking_default_type(self):
assert config.type == "enabled"
+class TestOutputConfig:
+ """Tests for Anthropic output controls."""
+
+ @pytest.mark.parametrize("effort", ["low", "medium", "high", "xhigh", "max"])
+ def test_effort_levels(self, effort):
+ config = OutputConfig(effort=effort)
+
+ assert config.effort == effort
+
+
class TestMessagesRequest:
"""Tests for MessagesRequest model."""
@@ -534,6 +545,7 @@ def test_request_with_all_parameters(self):
tools=[AnthropicTool(name="test", input_schema={})],
tool_choice=ToolChoice(type="auto"),
thinking=ThinkingConfig(budget_tokens=5000),
+ output_config=OutputConfig(effort="medium"),
)
assert req.model == "claude-3-opus"
@@ -544,6 +556,7 @@ def test_request_with_all_parameters(self):
assert req.top_p == 0.9
assert req.top_k == 40
assert req.metadata == {"user_id": "123"}
+ assert req.output_config.effort == "medium"
def test_request_max_tokens_required(self):
"""Test that max_tokens is required."""
@@ -582,6 +595,15 @@ def test_token_count_request(self):
assert req.model == "claude-3-sonnet"
+ def test_token_count_request_accepts_output_effort(self):
+ req = TokenCountRequest(
+ model="Qwen3.8-Flash-Next",
+ messages=[AnthropicMessage(role="user", content="Hello")],
+ output_config=OutputConfig(effort="low"),
+ )
+
+ assert req.output_config.effort == "low"
+
def test_token_count_response(self):
"""Test creating token count response."""
resp = TokenCountResponse(input_tokens=100)
diff --git a/tests/test_api_utils.py b/tests/test_api_utils.py
index 3ea6e7907a..b81a6e5abc 100644
--- a/tests/test_api_utils.py
+++ b/tests/test_api_utils.py
@@ -38,6 +38,7 @@
map_finish_reason_to_stop_reason,
request_has_cache_control,
)
+from omlx.api.media_inputs import normalize_media_file_parts_in_messages
from omlx.api.openai_models import ContentPart, FunctionCall, Message, ToolCall
from omlx.api.utils import (
SPECIAL_TOKENS_PATTERN,
@@ -63,9 +64,10 @@
class TestReasoningEffortChatTemplateKwargs:
- def test_adds_top_level_reasoning_effort(self):
- assert merge_reasoning_effort_chat_template_kwargs(None, "xhigh") == {
- "reasoning_effort": "xhigh"
+ @pytest.mark.parametrize("effort", ["low", "medium", "xhigh"])
+ def test_adds_top_level_reasoning_effort(self, effort):
+ assert merge_reasoning_effort_chat_template_kwargs(None, effort) == {
+ "reasoning_effort": effort
}
def test_explicit_template_kwarg_wins(self):
@@ -766,6 +768,128 @@ def test_detects_glm5_next(self, key):
assert uses_native_reasoning_content("any-name", **{key: "glm5_next"})
+class TestExtractMultimodalVideoContent:
+ def test_extract_multimodal_normalizes_video_url_alias(self):
+ messages = [
+ Message(
+ role="user",
+ content=[
+ {"type": "text", "text": "Describe this clip"},
+ {
+ "type": "input_video",
+ "input_video": {
+ "url": "https://example.com/clip.mp4",
+ "format": "mp4",
+ },
+ },
+ ],
+ )
+ ]
+
+ result = extract_multimodal_content(messages)
+
+ assert isinstance(result[0]["content"], list)
+ assert result[0]["content"][1] == {
+ "type": "video_url",
+ "video_url": {"url": "https://example.com/clip.mp4"},
+ }
+
+ def test_audio_file_part_normalizes_to_input_audio(self):
+ messages = [
+ Message(
+ role="user",
+ content=[
+ {
+ "type": "file",
+ "file": {
+ "filename": "sound.wav",
+ "mime_type": "audio/wav",
+ "file_data": "data:audio/wav;base64,ZA==",
+ },
+ }
+ ],
+ )
+ ]
+
+ normalized = normalize_media_file_parts_in_messages(messages)
+ content = normalized[0].content
+
+ assert isinstance(content, list)
+ assert content[0]["type"] == "input_audio"
+ assert content[0]["input_audio"]["format"] == "wav"
+
+ def test_audio_webm_mime_overrides_ambiguous_extension(self):
+ messages = [
+ Message(
+ role="user",
+ content=[
+ {
+ "type": "file",
+ "file": {
+ "filename": "recording.webm",
+ "mime_type": "audio/webm",
+ "file_data": "data:audio/webm;base64,ZA==",
+ },
+ }
+ ],
+ )
+ ]
+
+ normalized = normalize_media_file_parts_in_messages(messages)
+ content = normalized[0].content
+
+ assert isinstance(content, list)
+ assert content[0]["type"] == "input_audio"
+ assert content[0]["input_audio"]["mime_type"] == "audio/webm"
+
+ def test_video_file_part_normalizes_to_input_video(self):
+ messages = [
+ Message(
+ role="user",
+ content=[
+ {
+ "type": "file",
+ "file": {
+ "filename": "clip.mp4",
+ "mime_type": "video/mp4",
+ "file_data": "data:video/mp4;base64,ZA==",
+ },
+ }
+ ],
+ )
+ ]
+
+ normalized = normalize_media_file_parts_in_messages(messages)
+ content = normalized[0].content
+
+ assert isinstance(content, list)
+ assert content[0]["type"] == "input_video"
+ assert content[0]["input_video"]["filename"] == "clip.mp4"
+
+ def test_dict_file_part_normalizes_to_input_video(self):
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "file",
+ "file": {
+ "filename": "clip.mp4",
+ "mime_type": "video/mp4",
+ "file_data": "data:video/mp4;base64,ZA==",
+ },
+ }
+ ],
+ }
+ ]
+
+ normalized = normalize_media_file_parts_in_messages(messages)
+ content = normalized[0]["content"]
+
+ assert content[0]["type"] == "input_video"
+ assert content[0]["input_video"]["filename"] == "clip.mp4"
+
+
class TestConvertAnthropicToInternal:
"""Tests for convert_anthropic_to_internal function."""
@@ -3549,6 +3673,15 @@ def test_image_url_missing_url_dropped(self):
)
assert len(parts) == 0
+ def test_input_video_string_form_pass_through(self):
+ """input_video string paths survive multimodal content extraction."""
+ parts = _extract_multimodal_content_list(
+ [
+ {"type": "input_video", "input_video": "/tmp/clip.mp4"},
+ ]
+ )
+ assert parts == [{"type": "video_url", "video_url": {"url": "/tmp/clip.mp4"}}]
+
def test_input_audio_pass_through(self):
"""input_audio parts survive multimodal content extraction."""
parts = _extract_multimodal_content_list(
@@ -3622,6 +3755,13 @@ def test_video_input_is_preserved(self, part_type, value):
"video_url": {"url": "data:video/mp4;base64,AA=="},
}
]
+ def test_input_video_data_is_preserved(self):
+ parts = _extract_multimodal_content_list(
+ [{"type": "input_video", "input_video": {"data": "AA==", "format": "mp4"}}]
+ )
+ assert parts == [
+ {"type": "input_video", "input_video": {"data": "AA==", "format": "mp4"}}
+ ]
# =============================================================================
diff --git a/tests/test_audio_api.py b/tests/test_audio_api.py
index da720947b5..fae1305da0 100644
--- a/tests/test_audio_api.py
+++ b/tests/test_audio_api.py
@@ -49,6 +49,7 @@ def _make_pool(entries: list) -> MagicMock:
pool.check_ttl_expirations = AsyncMock()
pool.shutdown = AsyncMock()
pool.get_model_ids.return_value = [e.model_id for e in entries]
+ pool.get_active_model_aliases.return_value = {}
pool.get_entry.side_effect = lambda mid: next(
(e for e in entries if e.model_id == mid), None
)
diff --git a/tests/test_audio_tts.py b/tests/test_audio_tts.py
index 36ba84ad8b..45dae4d9d3 100644
--- a/tests/test_audio_tts.py
+++ b/tests/test_audio_tts.py
@@ -10,9 +10,12 @@
import asyncio
import base64
+import builtins
import io
+import re
import struct
import threading
+import tomllib
import wave
from concurrent.futures import ThreadPoolExecutor
from types import SimpleNamespace
@@ -44,6 +47,121 @@ def _make_wav_bytes(duration_secs: float = 0.1, sample_rate: int = 22050) -> byt
MAX_WAV_CHUNK_SIZE = 0xFFFFFFFF
+def test_audio_and_bundle_extras_omit_espeak_packages():
+ from pathlib import Path
+
+ pyproject = Path(__file__).resolve().parents[1] / "pyproject.toml"
+ with pyproject.open("rb") as file:
+ extras = tomllib.load(file)["project"]["optional-dependencies"]
+
+ for extra_name in ("audio", "bundle"):
+ package_names = {
+ re.split(r"[\[<>=!~;\s]", requirement, maxsplit=1)[0]
+ .lower()
+ .replace("_", "-")
+ for requirement in extras[extra_name]
+ }
+ assert "phonemizer-fork" not in package_names
+ assert "espeakng-loader" not in package_names
+
+
+def test_english_kokoro_pipeline_uses_g2p_without_gpl_imports(monkeypatch):
+ pipeline = pytest.importorskip("mlx_audio.tts.models.kokoro.pipeline")
+ from omlx.exceptions import UnsupportedKokoroLanguageError
+ from omlx.patches.mlx_audio_compat import ensure_english_kokoro_g2p
+
+ monkeypatch.setattr(pipeline, "_get_misaki_espeak", pipeline._get_misaki_espeak)
+ with ThreadPoolExecutor(max_workers=8) as executor:
+ results = list(executor.map(lambda _: ensure_english_kokoro_g2p(), range(16)))
+ assert all(results)
+
+ g2p_calls = []
+
+ class FakeG2P:
+ def __init__(self, *, trf, british, fallback, unk):
+ g2p_calls.append(
+ {
+ "trf": trf,
+ "british": british,
+ "fallback": fallback,
+ "unk": unk,
+ }
+ )
+
+ monkeypatch.setattr(
+ pipeline,
+ "_get_misaki_en",
+ lambda: SimpleNamespace(G2P=FakeG2P),
+ )
+ original_import = builtins.__import__
+ original_import_module = pipeline.importlib.import_module
+
+ def is_forbidden_import(name):
+ return any(
+ name == package or name.startswith(f"{package}.")
+ for package in ("misaki.espeak", "phonemizer", "espeakng_loader")
+ )
+
+ def reject_gpl_import(name, *args, **kwargs):
+ if is_forbidden_import(name):
+ raise AssertionError(f"unexpected GPL phonemizer import: {name}")
+ return original_import(name, *args, **kwargs)
+
+ def reject_gpl_import_module(name, package=None):
+ if is_forbidden_import(name):
+ raise AssertionError(f"unexpected GPL phonemizer import: {name}")
+ return original_import_module(name, package)
+
+ monkeypatch.setattr(builtins, "__import__", reject_gpl_import)
+ monkeypatch.setattr(pipeline.importlib, "import_module", reject_gpl_import_module)
+
+ for lang_code, british in (("a", False), ("b", True)):
+ pipeline.KokoroPipeline(lang_code, model=False, repo_id="test")
+ assert g2p_calls[-1] == {
+ "trf": False,
+ "british": british,
+ "fallback": None,
+ "unk": "",
+ }
+
+ with pytest.raises(UnsupportedKokoroLanguageError, match="requires eSpeak"):
+ pipeline.KokoroPipeline("e", model=False, repo_id="test")
+
+ monkeypatch.setattr(
+ pipeline, "_get_misaki_ja", lambda: SimpleNamespace(JAG2P=lambda: "ja")
+ )
+ monkeypatch.setattr(
+ pipeline, "_get_misaki_zh", lambda: SimpleNamespace(ZHG2P=lambda: "zh")
+ )
+ assert pipeline.KokoroPipeline("j", model=False, repo_id="test").g2p == "ja"
+ assert pipeline.KokoroPipeline("z", model=False, repo_id="test").g2p == "zh"
+
+
+@pytest.mark.asyncio
+async def test_tts_start_installs_kokoro_bridge_before_loading(monkeypatch):
+ pytest.importorskip("mlx_audio.tts.utils")
+ from omlx.engine.tts import TTSEngine
+ from omlx.patches import mlx_audio_compat
+
+ calls = []
+
+ def install_bridge():
+ calls.append("bridge")
+ return True
+
+ def load_model(model_name, *, strict):
+ calls.append(("load", model_name, strict))
+ return object()
+
+ monkeypatch.setattr(mlx_audio_compat, "ensure_english_kokoro_g2p", install_bridge)
+ monkeypatch.setattr("mlx_audio.tts.utils.load_model", load_model)
+
+ engine = TTSEngine("kokoro")
+ await engine.start()
+
+ assert calls == ["bridge", ("load", "kokoro", True)]
+
+
def _make_mock_tts_engine(wav_bytes: bytes = None) -> MagicMock:
"""Build a mock TTSEngine that returns the given WAV bytes."""
from omlx.engine.tts import TTSEngine
@@ -193,6 +311,30 @@ async def test_non_kokoro_voice_gets_no_inferred_lang_code(self):
assert captured["had_lang_code"] is False
+ @pytest.mark.asyncio
+ async def test_qwen_language_remains_passed_to_model(self):
+ import numpy as np
+
+ captured: dict = {}
+
+ class FakeQwen:
+ sample_rate = 24000
+
+ def generate(
+ self, *, text, verbose=False, voice=None, lang_code=None, **kwargs
+ ):
+ captured.update(voice=voice, lang_code=lang_code)
+ return [SimpleNamespace(audio=np.zeros(100, dtype=np.float32))]
+
+ from omlx.engine.tts import TTSEngine
+
+ engine = TTSEngine("qwen3-tts")
+ engine._model = FakeQwen()
+
+ await engine.synthesize("Bonjour", voice="Vivian", language="French")
+
+ assert captured == {"voice": "Vivian", "lang_code": "French"}
+
class TestTTSPresetVoiceRouting:
"""Qwen3-TTS Base has no preset speakers and raises on any ``voice``."""
@@ -504,6 +646,25 @@ def test_invalid_request_from_model_returns_400(self, server_tts_client, stream)
assert response.status_code == 400
assert "voice cannot be combined" in response.json()["error"]["message"]
+ def test_unsupported_kokoro_language_returns_400(self, server_tts_client):
+ from omlx.exceptions import UnsupportedKokoroLanguageError
+
+ client, mock_pool = server_tts_client
+ mock_pool.get_engine.return_value.synthesize = AsyncMock(
+ side_effect=UnsupportedKokoroLanguageError("es")
+ )
+
+ response = client.post(
+ "/v1/audio/speech",
+ json={"model": "kokoro", "input": "Hola", "language": "es"},
+ )
+
+ assert response.status_code == 400
+ detail = response.json().get("detail") or response.json().get(
+ "error", {}
+ ).get("message", "")
+ assert "Qwen3-TTS" in detail
+
def test_missing_model_field_returns_error(self, server_tts_client):
"""Request without 'model' field returns 4xx."""
client, _ = server_tts_client
@@ -768,6 +929,32 @@ def test_streaming_engine_error_returns_500(self, server_tts_client):
assert response.status_code == 500
assert "audio/wav" not in response.headers.get("content-type", "")
+ def test_streaming_unsupported_kokoro_language_returns_400(
+ self, server_tts_client
+ ):
+ from omlx.exceptions import UnsupportedKokoroLanguageError
+
+ client, mock_pool = server_tts_client
+ mock_pool.get_engine.return_value.synthesize = AsyncMock(
+ side_effect=UnsupportedKokoroLanguageError("es")
+ )
+
+ response = client.post(
+ "/v1/audio/speech",
+ json={
+ "model": "kokoro",
+ "input": "Hola",
+ "language": "es",
+ "stream": True,
+ },
+ )
+
+ assert response.status_code == 400
+ detail = response.json().get("detail") or response.json().get(
+ "error", {}
+ ).get("message", "")
+ assert "Qwen3-TTS" in detail
+
# ---------------------------------------------------------------------------
# LFM3-Audio / LFM3-Omni speech on the VLM engine
diff --git a/tests/test_deepseek_v4_patch.py b/tests/test_deepseek_v4_patch.py
index a527a63a14..ffa7f02b2a 100644
--- a/tests/test_deepseek_v4_patch.py
+++ b/tests/test_deepseek_v4_patch.py
@@ -346,9 +346,10 @@ def from_pretrained(model_path, *args, **kwargs):
def test_fallback_on_max_position_embeddings_error(self, applied_patch):
"""The exact AttributeError that transformers raises when it cannot
recognize deepseek_v4 must trigger a retry with PreTrainedConfig()."""
- import pytest as _pytest
from unittest.mock import patch as mock_patch
+ import pytest as _pytest
+
from omlx.patches.deepseek_v4 import tokenizer_patch
class _FakeUpstream:
@@ -378,9 +379,10 @@ def from_pretrained(model_path, *args, **kwargs):
def test_fallback_on_deepseek_v4_value_error(self, applied_patch):
"""ValueError mentioning deepseek_v4 also triggers fallback."""
- import pytest as _pytest
from unittest.mock import patch as mock_patch
+ import pytest as _pytest
+
from omlx.patches.deepseek_v4 import tokenizer_patch
class _FakeUpstream:
@@ -452,10 +454,10 @@ def test_class_attribute_forwarding(self, applied_patch):
forward to the upstream class so mlx-lm's NewlineTokenizer
registration still works."""
import mlx_lm.tokenizer_utils as tu
- from transformers import AutoTokenizer as upstream_at
+ from transformers import AutoTokenizer as UpstreamAutoTokenizer
# register is an upstream classmethod — wrapped class must expose it.
- assert tu.AutoTokenizer.register is upstream_at.register
+ assert tu.AutoTokenizer.register is UpstreamAutoTokenizer.register
class TestDSMLToolParser:
@@ -1015,6 +1017,130 @@ def test_streamed_tool_call_turn_rerender_is_byte_stable(self, applied_patch):
assert render_through_next_turn.startswith(prev_full_text)
+class TestDSV4CanonicalChatEncoder:
+ """Canonical DSV4 encoder shim — reasoning mode and idempotent install."""
+
+ @pytest.mark.parametrize(
+ ("enable_thinking", "reasoning_effort", "expected"),
+ [
+ (False, None, ("chat", None)),
+ (True, None, ("thinking", None)),
+ (True, "low", ("thinking", "high")),
+ (True, "medium", ("thinking", "high")),
+ (True, "high", ("thinking", "high")),
+ (None, "medium", ("thinking", "high")),
+ (False, "max", ("thinking", "max")),
+ ],
+ )
+ def test_reasoning_kwargs_map_to_canonical_modes(
+ self, enable_thinking, reasoning_effort, expected
+ ):
+ from omlx.patches.deepseek_v4 import dsv4_chat_encoder as enc
+
+ assert (
+ enc._resolve_mode_and_effort(enable_thinking, reasoning_effort)
+ == expected
+ )
+
+ def test_apply_chat_template_passes_canonical_kwargs(self, monkeypatch):
+ from omlx.patches.deepseek_v4 import dsv4_chat_encoder as enc
+
+ class FakeEncoding:
+ def __init__(self):
+ self.calls = []
+
+ def encode_messages(self, messages, **kwargs):
+ self.calls.append({"messages": messages, **kwargs})
+ return (
+ f"{kwargs['thinking_mode']}|"
+ f"{kwargs['reasoning_effort']}|"
+ f"{kwargs['drop_thinking']}"
+ )
+
+ fake = FakeEncoding()
+ monkeypatch.setattr(enc, "_encoding_cache", {})
+ monkeypatch.setattr(
+ enc, "_load_encoding_dsv4_module", lambda **kwargs: fake
+ )
+
+ messages = [
+ {"role": "user", "content": "Weather?"},
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {
+ "type": "function",
+ "function": {
+ "name": "get_weather",
+ "arguments": {"city": "서울"},
+ },
+ }
+ ],
+ },
+ ]
+ tools = [{"type": "function", "function": {"name": "get_weather"}}]
+
+ prompt = enc.apply_chat_template(
+ messages,
+ enable_thinking=True,
+ reasoning_effort="medium",
+ drop_earlier_reasoning=False,
+ tools=tools,
+ model_path="/models/dsv4",
+ )
+
+ assert prompt == "thinking|high|False"
+ call = fake.calls[-1]
+ assert call["messages"][0] == {
+ "role": "system",
+ "content": "",
+ "tools": tools,
+ }
+ arguments = call["messages"][2]["tool_calls"][0]["function"]["arguments"]
+ assert isinstance(arguments, str)
+ assert "서울" in arguments
+ assert call["add_default_bos_token"] is True
+
+ def test_install_canonical_chat_template_is_idempotent(self, monkeypatch):
+ from omlx.patches.deepseek_v4 import dsv4_chat_encoder as enc
+
+ class FakeEncoding:
+ def __init__(self):
+ self.calls = []
+
+ def encode_messages(self, messages, **kwargs):
+ self.calls.append(kwargs)
+ return "canonical"
+
+ class DummyTokenizer:
+ has_chat_template = False
+
+ @staticmethod
+ def _chat_template(*args, **kwargs):
+ return "original"
+
+ fake = FakeEncoding()
+ tokenizer = DummyTokenizer()
+ monkeypatch.setattr(enc, "_encoding_cache", {})
+ monkeypatch.setattr(
+ enc, "_load_encoding_dsv4_module", lambda **kwargs: fake
+ )
+
+ assert enc.install_canonical_chat_template(tokenizer, "/models/dsv4") is True
+ installed = tokenizer._chat_template
+ assert enc.install_canonical_chat_template(tokenizer, "/models/dsv4") is False
+ assert tokenizer._chat_template is installed
+ assert tokenizer._omlx_dsv4_chat_template_orig is DummyTokenizer._chat_template
+ assert tokenizer.has_chat_template is True
+
+ assert tokenizer._chat_template(
+ [{"role": "user", "content": "Hi"}],
+ enable_thinking=False,
+ ) == "canonical"
+ assert fake.calls[-1]["thinking_mode"] == "chat"
+ assert fake.calls[-1]["reasoning_effort"] is None
+
class TestChatTemplateModuleRegistration:
"""sys.modules registration so mlx-lm's importlib path picks up our types."""
diff --git a/tests/test_dspark_drafter.py b/tests/test_dspark_drafter.py
new file mode 100644
index 0000000000..5b8a42755a
--- /dev/null
+++ b/tests/test_dspark_drafter.py
@@ -0,0 +1,351 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Request lifecycle and authoritative native DSpark proposal handoff."""
+
+from types import SimpleNamespace
+from unittest.mock import MagicMock, patch
+
+import mlx.core as mx
+import pytest
+
+from omlx.model_settings import validate_minicpm_speculation
+from omlx.speculative.dspark_drafter import DSparkDrafter
+from omlx.utils.sampling import make_sampler
+
+
+@pytest.fixture(autouse=True)
+def cpu_arrays():
+ previous = mx.default_device()
+ mx.set_default_device(mx.cpu)
+ try:
+ yield
+ finally:
+ mx.set_default_device(previous)
+
+
+class _NativeProposalFixture:
+ config = SimpleNamespace(target_layer_ids=[3, 11])
+
+ def __init__(self):
+ self.calls = []
+
+ def make_cache(self):
+ return [SimpleNamespace(offset=0)]
+
+ def propose_block(
+ self, last_bonus, hidden, cache, block_size, sampler, *, proposal_probs
+ ):
+ self.calls.append((last_bonus, hidden, cache))
+ cache[0].offset += hidden.shape[1]
+ logits = mx.array([[1.0, 3.0, 2.0, -1.0]])
+ lp = logits - mx.logsumexp(logits, axis=-1, keepdims=True)
+ depth = block_size - 1
+ probabilities = (
+ mx.stack([proposal_probs(lp) for _ in range(depth)], axis=1)
+ if proposal_probs is not None
+ else None
+ )
+ return SimpleNamespace(
+ tokens=mx.full((1, depth), 1, dtype=mx.int32),
+ proposal_probs=probabilities,
+ confidences=mx.full((1, depth), 0.75),
+ block_size=block_size,
+ sample_from_anchor=False,
+ )
+
+
+def _state(uid):
+ return SimpleNamespace(uid=uid, stats=SimpleNamespace(mtp_head_ms=0.0))
+
+
+def _captures(length, batch=1):
+ return [
+ mx.full((batch, length, 2), 3.0),
+ mx.full((batch, length, 2), 11.0),
+ ]
+
+
+def test_native_contract_is_required():
+ with pytest.raises(ValueError, match="proposal/probability/confidence"):
+ DSparkDrafter(SimpleNamespace(), block_size=3, source_path="fixture")
+
+
+def test_request_seeds_are_not_truncated_and_only_committed_rows_are_fed():
+ model = _NativeProposalFixture()
+ drafter = DSparkDrafter(model, block_size=3, source_path="fixture")
+ state = _state(7)
+ drafter.seed_request("request", _captures(3000))
+ drafter.bind_uid("request", state.uid)
+ drafter.draft([(None, state, _captures(1), mx.array([42]), None)])
+ assert model.calls[0][0].tolist() == [42]
+ assert model.calls[0][1].shape == (1, 3001, 4)
+ assert model.calls[0][1][0, 0].tolist() == [3.0, 3.0, 11.0, 11.0]
+ assert drafter.context_length(state.uid) == 3001
+ assert state.drafts.tolist() == [1, 1]
+ assert state.draft_accept_lps == []
+ assert drafter._rows[state.uid].confidences.tolist() == [[0.75, 0.75]]
+ drafter.draft([(None, state, _captures(2), mx.array([1, 43]), None)])
+ assert model.calls[1][1].shape == (1, 2, 4)
+ assert model.calls[0][2] is model.calls[1][2]
+ assert drafter.context_length(state.uid) == 3003
+
+
+def test_batched_greedy_rows_keep_independent_context_and_cache():
+ model = _NativeProposalFixture()
+ drafter = DSparkDrafter(model, block_size=3, source_path="fixture")
+ first, second = _state(7), _state(8)
+ drafter.observe([7, 8], _captures(1, batch=2))
+ drafter.draft(
+ [
+ (None, first, _captures(2), mx.array([42]), None),
+ (None, second, _captures(3), mx.array([43]), None),
+ ]
+ )
+ assert model.calls[0][2] is not model.calls[1][2]
+ assert drafter.context_length(7) == 3
+ assert drafter.context_length(8) == 4
+ drafter.release([7])
+ drafter.release([7])
+ assert drafter.context_length(7) == 0
+ assert drafter.context_length(8) == 4
+
+
+def test_sampled_proposal_q_is_native_probability_callback_not_independent_logits():
+ model = _NativeProposalFixture()
+ drafter = DSparkDrafter(model, block_size=3, source_path="fixture")
+ state = _state(7)
+ sampler = make_sampler(temp=0.7, top_k=2, top_p=1.0)
+ with (
+ patch("omlx.speculative.dspark_drafter.bg._is_greedy", return_value=False),
+ patch(
+ "omlx.speculative.dspark_drafter.bg._resolve_draft_sampler",
+ return_value=sampler,
+ ),
+ ):
+ drafter.draft([(object(), state, _captures(2), mx.array([42]), None)])
+ assert len(state.draft_accept_lps) == 2
+ expected = mx.softmax(mx.array([3.0, 2.0]) / 0.7).tolist()
+ for lp in state.draft_accept_lps:
+ actual = mx.exp(lp).tolist()
+ assert actual == pytest.approx([0.0, *expected, 0.0], abs=1e-6)
+
+
+def test_sampled_batches_fail_before_native_cache_mutation():
+ model = _NativeProposalFixture()
+ drafter = DSparkDrafter(model, block_size=3, source_path="fixture")
+ with (
+ patch("omlx.speculative.dspark_drafter.bg._is_greedy", return_value=False),
+ pytest.raises(ValueError, match="Batched sampled"),
+ ):
+ drafter.draft(
+ [
+ (object(), _state(7), _captures(1), mx.array([42]), None),
+ (object(), _state(8), _captures(1), mx.array([43]), None),
+ ]
+ )
+ assert model.calls == []
+ assert drafter._rows == {}
+
+
+def test_sampled_row_initialization_cannot_hide_its_parent_decode_batch():
+ model = _NativeProposalFixture()
+ drafter = DSparkDrafter(model, block_size=3, source_path="fixture")
+ row = SimpleNamespace(uids=[7])
+ with (
+ drafter.decode_scope([7, 8]),
+ patch("omlx.speculative.dspark_drafter.bg._is_greedy", return_value=False),
+ pytest.raises(ValueError, match="Batched sampled"),
+ ):
+ drafter.draft([(row, _state(7), _captures(1), mx.array([42]), None)])
+ assert model.calls == []
+ assert drafter._rows == {}
+
+
+@pytest.mark.parametrize("sampled_row", [0, 1, None])
+def test_decode_batch_admission_rejects_sampling_before_target_realign(sampled_row):
+ from mlx_lm.generate import GenerationBatch
+
+ from omlx.speculative.dspark_drafter import bg
+
+ assert bg.apply()
+ greedy = make_sampler(temp=0.0)
+ sampled = make_sampler(temp=0.7)
+ samplers = [greedy, greedy]
+ if sampled_row is not None:
+ samplers[sampled_row] = sampled
+ else:
+ samplers[1] = None
+ realign = MagicMock()
+ batch = SimpleNamespace(
+ model=SimpleNamespace(
+ _omlx_drafter=DSparkDrafter(
+ _NativeProposalFixture(), block_size=3, source_path="fixture"
+ )
+ ),
+ uids=[7, 8],
+ samplers=samplers,
+ fallback_sampler=sampled,
+ _omlx_realign_rows=realign,
+ )
+ with pytest.raises(ValueError, match="Batched sampled"):
+ GenerationBatch.next(batch)
+ realign.assert_not_called()
+ assert batch.model._omlx_drafter._rows == {}
+
+
+def test_release_before_uid_binding_and_nested_scope_cleanup():
+ drafter = DSparkDrafter(
+ _NativeProposalFixture(), block_size=3, source_path="fixture"
+ )
+ drafter.seed_request("cancelled", _captures(2))
+ drafter.release_request("cancelled")
+ drafter.release_request("cancelled")
+ drafter.bind_uid("cancelled", 7)
+ assert drafter._rows == {}
+ with drafter.decode_scope([7]):
+ assert drafter.scope_uids == (7,)
+ with pytest.raises(RuntimeError, match="cancelled"), drafter.decode_scope([8]):
+ raise RuntimeError("cancelled")
+ assert drafter.scope_uids == (7,)
+ assert drafter.scope_uids is None
+ drafter.seed(7, _captures(2))
+ drafter.seed_request("unbound", _captures(3))
+ drafter.clear()
+ drafter.clear()
+ assert drafter._rows == {}
+ assert drafter._request_seeds == {}
+
+
+def test_scheduler_prefill_positions_and_generator_reset_preserve_unbound_context():
+ from omlx.scheduler import Scheduler
+
+ drafter = DSparkDrafter(
+ _NativeProposalFixture(), block_size=3, source_path="fixture"
+ )
+ scheduler = SimpleNamespace(model=SimpleNamespace(_omlx_drafter=drafter))
+ request = SimpleNamespace(request_id="request", prompt_token_ids=[1, 2, 3, 4])
+ Scheduler._dflash_seed_prefill(
+ scheduler, request, SimpleNamespace(hidden_states=_captures(2)), 0, 0
+ )
+ Scheduler._dflash_seed_prefill(
+ scheduler, request, SimpleNamespace(hidden_states=_captures(1)), 0, 2
+ )
+ drafter.seed(0, _captures(7))
+ drafter.reset_rows()
+ assert drafter._rows == {}
+ drafter.bind_uid(request.request_id, 0)
+ drafter.draft([(None, _state(0), _captures(1), mx.array([42]), None)])
+ assert drafter.context_length(0) == 4
+ drafter.release([0])
+ drafter.release_request(request.request_id, request.prompt_token_ids + [42])
+ assert drafter.prepare_request("next", request.prompt_token_ids, 3) == 0
+ assert not drafter._rows
+ assert not drafter._request_seeds
+
+
+@pytest.mark.parametrize(
+ "override",
+ [
+ {"dflash_draft_model": None},
+ {"dflash_verify_mode": "adaptive"},
+ {"dflash_max_ctx": 1024},
+ {"dflash_draft_window_size": 2048},
+ {"dflash_draft_sink_size": 4},
+ {"dflash_ssd_cache": True},
+ {"mtp_adaptive_max_depth": 4},
+ {"mtp_fixed_depth": 4},
+ {"specprefill_enabled": True},
+ {"guided_grammar_enabled": True},
+ {"mtp_enabled": True},
+ {"vlm_mtp_enabled": True},
+ ],
+)
+def test_enabled_native_path_rejects_unsupported_settings(override):
+ settings = {"dflash_enabled": True, "dflash_draft_model": "/paired/helper"}
+ settings.update(override)
+ with pytest.raises(ValueError):
+ validate_minicpm_speculation(settings, "minicpmv4_7")
+ validate_minicpm_speculation(settings, "qwen3_5")
+
+
+def test_fixed_defaults_and_ordinary_base_serving_are_unchanged():
+ validate_minicpm_speculation({}, "minicpmv4_7")
+ validate_minicpm_speculation(
+ {"dflash_enabled": True, "dflash_draft_model": "/paired/helper"},
+ "minicpmv4_7",
+ )
+
+
+def test_incomplete_native_contract_fails_before_checkpoint_load(tmp_path, monkeypatch):
+ from omlx.speculative import dflash
+ from omlx.speculative import minicpm_dspark as compatibility
+
+ monkeypatch.setattr(compatibility, "MiniCPMDSparkDraftModel", object)
+ target = SimpleNamespace(config=SimpleNamespace(model_type="minicpmv4_7"))
+ with (
+ patch.object(compatibility, "load_dspark_model") as load,
+ pytest.raises(ValueError, match="proposal support is incomplete"),
+ ):
+ dflash.load_dflash_drafter(str(tmp_path), target)
+ load.assert_not_called()
+
+
+def test_native_helper_attachment_uses_fixed_depth_and_detach_releases_state():
+ from omlx.speculative.dflash import attach_drafter, detach_drafter
+
+ drafter = DSparkDrafter(
+ _NativeProposalFixture(), block_size=3, source_path="fixture"
+ )
+ language = SimpleNamespace()
+ attach_drafter(language, drafter)
+ assert language._omlx_mtp_depth == 2
+ assert language._omlx_mtp_depth_fixed
+ drafter.seed_request("request", _captures(2))
+ assert detach_drafter(language) is drafter
+ assert not language._omlx_mtp_decode_enabled
+ assert not language._omlx_mtp_depth_fixed
+ assert drafter._request_seeds == {}
+
+
+def test_dspark_prefill_bypasses_kv_prefix_without_hidden_history():
+ from omlx.request import Request, SamplingParams
+ from omlx.scheduler import Scheduler
+
+ drafter = DSparkDrafter(
+ _NativeProposalFixture(), block_size=3, source_path="fixture"
+ )
+ scheduler = Scheduler.__new__(Scheduler)
+ scheduler.model = SimpleNamespace(_omlx_drafter=drafter)
+ scheduler.block_aware_cache = MagicMock()
+ scheduler._prefix_cache_prepared = set()
+ scheduler._model_has_unreconstructible_cache = lambda: False
+ scheduler._log_prefix_divergence = MagicMock()
+ scheduler._try_specprefill_scoring = MagicMock()
+ request = Request(
+ request_id="request", prompt=[11, 12, 13], sampling_params=SamplingParams()
+ )
+ request.prompt_token_ids = [11, 12, 13]
+ scheduler._prepare_prefix_cache_for_request(request)
+ assert request.remaining_tokens == [11, 12, 13]
+ assert request.cached_tokens == 0
+ scheduler.block_aware_cache.fetch_cache.assert_not_called()
+
+
+def test_sampled_batch_seed_cannot_bypass_gate_with_single_job():
+ model = _NativeProposalFixture()
+ drafter = DSparkDrafter(model, block_size=3, source_path="fixture")
+ with (
+ patch("omlx.speculative.dspark_drafter.bg._is_greedy", return_value=False),
+ pytest.raises(ValueError, match="Batched sampled"),
+ ):
+ drafter.draft(
+ [
+ (
+ SimpleNamespace(uids=[7, 8]),
+ _state(7),
+ _captures(1),
+ mx.array([42]),
+ None,
+ )
+ ]
+ )
+ assert model.calls == []
diff --git a/tests/test_gdn_compact_state_lifecycle.py b/tests/test_gdn_compact_state_lifecycle.py
new file mode 100644
index 0000000000..f53b7c4fdf
--- /dev/null
+++ b/tests/test_gdn_compact_state_lifecycle.py
@@ -0,0 +1,68 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Lock the compact recurrent-state lifecycle used by continuous decode."""
+
+from __future__ import annotations
+
+import mlx.core as mx
+import mlx.nn as nn
+from mlx_lm.generate import GenerationBatch, StopSequences
+from mlx_lm.models.cache import ArraysCache
+
+
+class _CompactStateModel(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.cache_ids: list[int] = []
+ self.state_shapes: list[tuple[int, ...]] = []
+
+ def __call__(self, inputs, cache):
+ recurrent = cache[0]
+ self.cache_ids.append(id(recurrent))
+ for slot, shape in enumerate(((3, 8), (2, 3, 4))):
+ state = recurrent[slot]
+ if state is None:
+ state = mx.zeros((inputs.shape[0], *shape), dtype=mx.float32)
+ state = state + 1
+ recurrent[slot] = state
+ self.state_shapes.append(recurrent[1].shape)
+ logits = mx.zeros((inputs.shape[0], 1, 8))
+ logits[:, :, 1] = 1
+ return logits
+
+
+def test_generation_batch_keeps_gdn_state_compact_between_decode_steps(
+ monkeypatch,
+):
+ """Steady decode must not extract, merge, filter, or scatter GDN state."""
+
+ def unexpected_cache_transition(*_args, **_kwargs):
+ raise AssertionError("steady decode must retain the compact batch cache")
+
+ monkeypatch.setattr(ArraysCache, "extract", unexpected_cache_transition)
+ monkeypatch.setattr(ArraysCache, "filter", unexpected_cache_transition)
+ monkeypatch.setattr(ArraysCache, "merge", unexpected_cache_transition)
+
+ model = _CompactStateModel()
+ cache = ArraysCache(2)
+ batch = GenerationBatch(
+ model=model,
+ uids=[10, 11, 12],
+ inputs=mx.array([1, 1, 1]),
+ prompt_cache=[cache],
+ tokens=[[1], [1], [1]],
+ samplers=[None, None, None],
+ fallback_sampler=lambda logits: mx.argmax(logits, axis=-1),
+ logits_processors=[[], [], []],
+ stop_sequences=[StopSequences() for _ in range(3)],
+ max_tokens=[8, 8, 8],
+ )
+
+ for _ in range(3):
+ batch._step()
+
+ assert model.cache_ids == [id(cache)] * 4
+ assert model.state_shapes == [(3, 2, 3, 4)] * 4
+ assert cache[0].shape == (3, 3, 8)
+ assert cache[1].shape == (3, 2, 3, 4)
+ assert mx.all(cache[0] == 4).item()
+ assert mx.all(cache[1] == 4).item()
diff --git a/tests/test_gemma4_messages.py b/tests/test_gemma4_messages.py
index fa3b7b72ab..e08277e1d7 100644
--- a/tests/test_gemma4_messages.py
+++ b/tests/test_gemma4_messages.py
@@ -59,6 +59,40 @@ def test_mid_system_position_can_be_deferred(self):
{"role": "system", "content": "Tail instruction"},
]
+ def test_input_video_preserved_for_vlm_processing(self):
+ messages = [
+ Message(
+ role="user",
+ content=[
+ {"type": "text", "text": "Describe this clip"},
+ {
+ "type": "input_video",
+ "input_video": {
+ "url": "/tmp/clip.mp4",
+ "format": "mp4",
+ },
+ },
+ ],
+ )
+ ]
+
+ result = extract_gemma4_messages(messages)
+
+ assert result == [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "Describe this clip"},
+ {
+ "type": "video_url",
+ "video_url": {
+ "url": "/tmp/clip.mp4",
+ },
+ },
+ ],
+ }
+ ]
+
def test_tool_result_folded_onto_model_turn(self):
"""Single tool result is attached to the same assistant message as tool_calls."""
messages = [
diff --git a/tests/test_gemma4_vlm_mtp_runtime.py b/tests/test_gemma4_vlm_mtp_runtime.py
index b60e81b831..7c82edf67a 100644
--- a/tests/test_gemma4_vlm_mtp_runtime.py
+++ b/tests/test_gemma4_vlm_mtp_runtime.py
@@ -251,6 +251,7 @@ def test_block_drafter_captures_requested_layers_then_the_last():
plain = lm(tokens, cache=lm.make_cache(), capture_layer_ids=[0, 1])
observed = []
drafter = SimpleNamespace(
+ kind="dflash",
depth=3,
target_layer_ids=[1, 0],
scope_uids=None,
diff --git a/tests/test_glm_moe_dsa_patch.py b/tests/test_glm_moe_dsa_patch.py
index 6b4f0ca1f2..ae38cd0f90 100644
--- a/tests/test_glm_moe_dsa_patch.py
+++ b/tests/test_glm_moe_dsa_patch.py
@@ -259,9 +259,10 @@ def test_glm_adaptive_prefill_config_env_overrides(monkeypatch):
def test_glm_patch_keeps_vendored_helpers_private():
glm_moe_dsa = _load_patched_glm_module()
- from omlx.patches.glm_moe_dsa import deepseek_v32 as vendored_deepseek_v32
from mlx_lm.models import deepseek_v32 as upstream_deepseek_v32
+ from omlx.patches.glm_moe_dsa import deepseek_v32 as vendored_deepseek_v32
+
assert getattr(glm_moe_dsa, "_OMLX_GLM_DSA_OPTIMIZED", False)
assert sys.modules["mlx_lm.models.glm_moe_dsa"] is glm_moe_dsa
assert glm_moe_dsa.DeepseekV32Model is vendored_deepseek_v32.DeepseekV32Model
@@ -397,19 +398,25 @@ def test_glm_native_fused_kernels_match_reference(monkeypatch):
from omlx.patches.glm_moe_dsa.sparse_mla import fused_indexer_scores
- def assert_padded_indexer_scores_match(L, K, offset_view=False):
- B, H, D = 1, 32, 128
+ def assert_padded_indexer_scores_match(q_length, k_length, offset_view=False):
+ batch, heads, dims = 1, 32, 128
if offset_view:
- q_base = mx.random.normal((B, H, L + 2, D), dtype=mx.float16)
- k_base = mx.random.normal((B, 1, K + 2, D), dtype=mx.float16)
- w_base = mx.random.normal((B, L + 2, H), dtype=mx.float16)
- q = q_base[:, :, 1 : L + 1, :]
- k = k_base[:, :, 1 : K + 1, :]
- w = w_base[:, 1 : L + 1, :]
+ q_base = mx.random.normal(
+ (batch, heads, q_length + 2, dims), dtype=mx.float16
+ )
+ k_base = mx.random.normal(
+ (batch, 1, k_length + 2, dims), dtype=mx.float16
+ )
+ w_base = mx.random.normal(
+ (batch, q_length + 2, heads), dtype=mx.float16
+ )
+ q = q_base[:, :, 1 : q_length + 1, :]
+ k = k_base[:, :, 1 : k_length + 1, :]
+ w = w_base[:, 1 : q_length + 1, :]
else:
- q = mx.random.normal((B, H, L, D), dtype=mx.float16)
- k = mx.random.normal((B, 1, K, D), dtype=mx.float16)
- w = mx.random.normal((B, L, H), dtype=mx.float16)
+ q = mx.random.normal((batch, heads, q_length, dims), dtype=mx.float16)
+ k = mx.random.normal((batch, 1, k_length, dims), dtype=mx.float16)
+ w = mx.random.normal((batch, q_length, heads), dtype=mx.float16)
y_native = fused_indexer_scores(q, k, w, causal=True)
head_scores = q @ k.swapaxes(-1, -2)
y_ref = mx.maximum(head_scores, 0)
@@ -418,8 +425,10 @@ def assert_padded_indexer_scores_match(L, K, offset_view=False):
axis=1,
keepdims=True,
)
- q_pos = mx.arange(K - L, K, dtype=mx.uint32).reshape(1, 1, L, 1)
- k_pos = mx.arange(0, K, dtype=mx.uint32).reshape(1, 1, 1, K)
+ q_pos = mx.arange(k_length - q_length, k_length, dtype=mx.uint32).reshape(
+ 1, 1, q_length, 1
+ )
+ k_pos = mx.arange(0, k_length, dtype=mx.uint32).reshape(1, 1, 1, k_length)
y_ref = mx.where(
k_pos <= q_pos,
y_ref,
diff --git a/tests/test_inkling_vlm_mtp.py b/tests/test_inkling_vlm_mtp.py
index 597b69f349..ccfee3b680 100644
--- a/tests/test_inkling_vlm_mtp.py
+++ b/tests/test_inkling_vlm_mtp.py
@@ -128,10 +128,9 @@ def test_config_plumb_and_attach(runtime):
assert model._omlx_mtp_decode_enabled
assert model._omlx_mtp_chain
assert model._omlx_mtp_head_prenorm
- # No per-cycle clone and no row-wise batch path: provisional rows live
- # on the persistent caches and the next fold trims them.
+ # No per-cycle clone: provisional rows live on the persistent caches and
+ # the next fold trims them.
assert model._omlx_mtp_head_clone is False
- assert model._omlx_mtp_rowwise_unsupported is True
assert model._omlx_mtp_depth == 3 # clamped to the shipped block count
assert all(
hasattr(block.transformer_block.self_attn, "qkvr_proj")
diff --git a/tests/test_media_options.py b/tests/test_media_options.py
new file mode 100644
index 0000000000..0a1a9a97bb
--- /dev/null
+++ b/tests/test_media_options.py
@@ -0,0 +1,80 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Shared request and model controls for MiniCPM preprocessing."""
+
+import pytest
+from pydantic import ValidationError
+
+from omlx.api.anthropic_models import MessagesRequest, TokenCountRequest
+from omlx.api.media_options import (
+ MultimodalProcessorOptions,
+ merge_mm_processor_kwargs,
+)
+from omlx.api.openai_models import ChatCompletionRequest
+from omlx.api.responses_models import ResponsesRequest
+from omlx.model_profiles import filter_profile_fields, filter_universal_fields
+from omlx.model_settings import ModelSettings
+
+
+@pytest.mark.parametrize(
+ "request_type,fields",
+ [
+ (ChatCompletionRequest, {"messages": []}),
+ (MessagesRequest, {"messages": [], "max_tokens": 1}),
+ (TokenCountRequest, {"messages": []}),
+ (ResponsesRequest, {"input": "Describe the image."}),
+ ],
+)
+def test_existing_protocols_share_processor_option_validation(request_type, fields):
+ request = request_type(
+ model="mini",
+ mm_processor_kwargs={"downsample_mode": "4x", "max_slice_nums": 9},
+ **fields,
+ )
+ assert request.mm_processor_kwargs == MultimodalProcessorOptions(
+ downsample_mode="4x", max_slice_nums=9
+ )
+ assert request_type(model="mini", **fields).mm_processor_kwargs is None
+
+
+@pytest.mark.parametrize(
+ "options",
+ [
+ {"downsample_mode": "8x"},
+ {"max_slice_nums": 0},
+ {"max_slice_nums": -1},
+ {"max_slice_nums": True},
+ {"max_slice_nums": 1.5},
+ {"max_slice_nums": "9"},
+ {"stack_frames": 1},
+ {"arbitrary": True},
+ ],
+)
+def test_invalid_or_deferred_controls_are_rejected(options):
+ with pytest.raises(ValidationError):
+ MultimodalProcessorOptions.model_validate(options)
+ with pytest.raises(ValidationError):
+ ModelSettings(mm_processor_kwargs=options)
+
+
+def test_request_overrides_model_without_mutation_or_default_changes():
+ model_options = {"downsample_mode": "16x", "max_slice_nums": 9}
+ request_options = MultimodalProcessorOptions(downsample_mode="4x")
+ assert merge_mm_processor_kwargs(model_options, request_options) == {
+ "downsample_mode": "4x",
+ "max_slice_nums": 9,
+ }
+ assert model_options == {"downsample_mode": "16x", "max_slice_nums": 9}
+ assert merge_mm_processor_kwargs(None, None) == {}
+ assert merge_mm_processor_kwargs(model_options, {"max_slice_nums": None}) == (
+ model_options
+ )
+
+
+def test_processor_options_round_trip_only_through_model_profiles():
+ options = {"downsample_mode": "4x", "max_slice_nums": 36}
+ settings = ModelSettings.from_dict({"mm_processor_kwargs": options})
+ assert settings.to_dict()["mm_processor_kwargs"] == options
+ assert settings.mm_processor_kwargs is not options
+ assert filter_profile_fields(settings.to_dict())["mm_processor_kwargs"] == options
+ assert "mm_processor_kwargs" not in filter_universal_fields(settings.to_dict())
+ assert "mm_processor_kwargs" not in ModelSettings().to_dict()
diff --git a/tests/test_minicpm47.py b/tests/test_minicpm47.py
new file mode 100644
index 0000000000..1630682921
--- /dev/null
+++ b/tests/test_minicpm47.py
@@ -0,0 +1,35 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Exercise official MiniCPM models with oMLX serving extensions on CPU."""
+
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+from omlx.patches.minicpm47 import validate_target_config
+
+
+def test_non_normalized_routing_remains_unsupported():
+ validate_target_config({"text_config": {}})
+ with pytest.raises(ValueError, match="normalized top-k"):
+ validate_target_config({"text_config": {"norm_topk_prob": False}})
+
+
+def test_official_minicpm_serving_contracts():
+ script = """
+import mlx.core as mx
+mx.set_default_device(mx.cpu)
+import pytest
+raise SystemExit(pytest.main(['tests/minicpm47_native_cases.py', '-q', '--tb=short']))
+"""
+ result = subprocess.run(
+ [sys.executable, "-c", script],
+ cwd=Path(__file__).parents[1],
+ env={**os.environ, "HF_HUB_OFFLINE": "1"},
+ capture_output=True,
+ text=True,
+ timeout=120,
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
diff --git a/tests/test_minicpm_media.py b/tests/test_minicpm_media.py
new file mode 100644
index 0000000000..6350844cc3
--- /dev/null
+++ b/tests/test_minicpm_media.py
@@ -0,0 +1,653 @@
+# SPDX-License-Identifier: Apache-2.0
+"""MiniCPM request-local media controls and admission plumbing."""
+
+from concurrent.futures import ThreadPoolExecutor
+from threading import get_ident
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import mlx.core as mx
+import pytest
+from fastapi.testclient import TestClient
+from mlx_vlm.models.base import LanguageModelOutput
+from PIL import Image
+
+from omlx.api.media_options import MultimodalProcessorOptions
+from omlx.engine.base import GenerationOutput
+from omlx.engine.vlm import VLMBatchedEngine
+from omlx.exceptions import InvalidRequestError
+from omlx.model_settings import ModelSettings
+from omlx.models.vlm import VLMModelAdapter
+
+
+@pytest.mark.asyncio
+async def test_minicpm_start_propagates_serving_hook_failure_before_tensor_load():
+ engine = VLMBatchedEngine(model_name="minicpm-fixture")
+ with (
+ patch("omlx.engine.vlm._read_config_model_type", return_value="minicpmv4_7"),
+ patch(
+ "omlx.utils.model_loading.maybe_apply_pre_load_patches",
+ side_effect=RuntimeError("MiniCPM serving hook failed"),
+ ),
+ patch("mlx_vlm.utils.load") as loader,
+ ):
+ with pytest.raises(RuntimeError, match="serving hook failed"):
+ await engine.start()
+ loader.assert_not_called()
+
+
+@pytest.fixture(autouse=True)
+def cpu_arrays():
+ previous = mx.default_device()
+ mx.set_default_device(mx.cpu)
+ try:
+ yield
+ finally:
+ mx.set_default_device(previous)
+
+
+@pytest.fixture
+def engine():
+ model = VLMBatchedEngine(
+ model_name="tiny-minicpm",
+ model_settings=ModelSettings(mm_processor_kwargs={"max_slice_nums": 9}),
+ )
+ model._loaded = True
+ model._processor = SimpleNamespace(
+ image_token="<|image_pad|>",
+ image_processor=SimpleNamespace(max_slice_nums=9),
+ apply_chat_template=lambda *args, **kwargs: "<|image_pad|>Describe.",
+ )
+ features = {
+ "inputs_embeds": mx.zeros((1, 4, 2)),
+ "position_ids": mx.ones((3, 1, 4), dtype=mx.int32),
+ "rope_deltas": mx.array([[3]], dtype=mx.int32),
+ }
+ model._vlm_model = SimpleNamespace(
+ config=SimpleNamespace(model_type="minicpmv4_7", downsample_mode="16x"),
+ language_model=SimpleNamespace(),
+ get_input_embeddings=MagicMock(
+ return_value=SimpleNamespace(
+ inputs_embeds=features["inputs_embeds"],
+ to_dict=lambda: dict(features),
+ )
+ ),
+ )
+ model._vision_cache = None
+ model._format_messages_for_vlm_template = MagicMock(
+ return_value=([{"role": "user", "content": "<|image_pad|>Describe."}], [])
+ )
+ return model
+
+
+@pytest.fixture
+def inputs():
+ return {
+ "input_ids": mx.array([[1, 99, 99, 2]]),
+ "pixel_values": mx.zeros((1, 1)),
+ "tgt_sizes": [mx.array([[2, 2]])],
+ "mm_token_type_ids": mx.array([[0, 1, 1, 0]]),
+ }
+
+
+@pytest.mark.parametrize(
+ ("model_type", "needs_hooks"), [("minicpmv4_7", False), ("muse_glimmer", True)]
+)
+def test_drafter_preparation_preserves_native_minicpm_transactions(
+ engine, model_type, needs_hooks
+):
+ engine._vlm_model.config.model_type = model_type
+ with patch("omlx.engine.vlm.drafter_target.apply") as install:
+ assert engine.prepare_dflash_target() is engine._vlm_model
+ if needs_hooks:
+ install.assert_called_once_with(engine._vlm_model.language_model)
+ else:
+ install.assert_not_called()
+
+
+def test_compression_reaches_processor_and_encoder_with_request_local_positions(
+ engine, inputs
+):
+ images = [Image.new("RGB", (4, 4))]
+ with patch("mlx_vlm.utils.prepare_inputs", return_value=inputs) as prepare:
+ result = engine._prepare_vision_inputs(
+ [{"role": "user", "content": "<|image_pad|>Describe."}],
+ images,
+ mm_processor_kwargs={"downsample_mode": "4x", "max_slice_nums": 36},
+ )
+ assert prepare.call_args.kwargs["downsample_mode"] == "4x"
+ assert prepare.call_args.kwargs["max_slice_nums"] == 36
+ kwargs = engine._vlm_model.get_input_embeddings.call_args.kwargs
+ assert kwargs["downsample_mode"] == "4x"
+ assert kwargs["tgt_sizes"] is inputs["tgt_sizes"]
+ assert kwargs["mm_token_type_ids"] is inputs["mm_token_type_ids"]
+ assert result[2]["position_ids"].shape == (3, 1, 4)
+ assert result[2]["_captured_rope_deltas"].tolist() == [[3]]
+ assert result[4] == 0 and result[5] == [(0, result[3])]
+ assert engine._vlm_model.config.downsample_mode == "16x"
+ assert engine._processor.image_processor.max_slice_nums == 9
+ assert engine._model_settings.mm_processor_kwargs == {"max_slice_nums": 9}
+
+
+def test_effective_processor_controls_change_prefix_identity(engine, inputs):
+ images = [Image.new("RGB", (4, 4))]
+ messages = [{"role": "user", "content": "<|image_pad|>Describe."}]
+ with patch("mlx_vlm.utils.prepare_inputs", return_value=inputs):
+ baseline = engine._prepare_vision_inputs(messages, images)
+ compressed = engine._prepare_vision_inputs(
+ messages, images, mm_processor_kwargs={"downsample_mode": "4x"}
+ )
+ sliced = engine._prepare_vision_inputs(
+ messages, images, mm_processor_kwargs={"max_slice_nums": 36}
+ )
+ repeated = engine._prepare_vision_inputs(messages, images)
+ assert len({baseline[3], compressed[3], sliced[3]}) == 3
+ assert repeated[3] == baseline[3]
+
+
+@pytest.mark.parametrize("with_image", [False, True])
+def test_native_combined_video_pixels_use_video_content_identity(
+ engine, inputs, with_image
+):
+ engine._format_messages_for_vlm_template.return_value = (
+ [{"role": "user", "content": "<|video_pad|>Describe."}],
+ [],
+ )
+ images = [Image.new("RGB", (4, 4))] if with_image else []
+ with patch("mlx_vlm.utils.prepare_inputs", return_value=inputs):
+ first = engine._prepare_vision_inputs(
+ [], images, videos=["owned-video"], video_hashes=["first"]
+ )
+ changed = engine._prepare_vision_inputs(
+ [], images, videos=["owned-video"], video_hashes=["second"]
+ )
+ repeated = engine._prepare_vision_inputs(
+ [], images, videos=["owned-video"], video_hashes=["first"]
+ )
+ assert first[1] is not None
+ assert first[3] != changed[3]
+ assert first[3] == repeated[3]
+
+
+def test_unset_slicing_uses_native_image_and_video_defaults(engine):
+ engine._model_settings = ModelSettings()
+ assert engine._mm_processor_kwargs(None) == {"downsample_mode": "16x"}
+ assert engine._mm_processor_kwargs({"max_slice_nums": 1}) == {
+ "downsample_mode": "16x",
+ "max_slice_nums": 1,
+ }
+
+
+def test_pure_text_initializes_native_request_delta_for_cached_decode(engine):
+ engine._format_messages_for_vlm_template.return_value = (
+ [{"role": "user", "content": "Describe."}],
+ [],
+ )
+ engine._processor.apply_chat_template = lambda *args, **kwargs: "Describe."
+ positions = mx.broadcast_to(mx.arange(3)[None, None, :], (3, 1, 3))
+ features = {
+ "inputs_embeds": mx.zeros((1, 3, 2)),
+ "position_ids": positions,
+ "rope_deltas": mx.zeros((1, 1), dtype=mx.int32),
+ }
+ engine._vlm_model.get_input_embeddings.return_value = SimpleNamespace(
+ inputs_embeds=features["inputs_embeds"], to_dict=lambda: dict(features)
+ )
+ inputs = {
+ "input_ids": mx.array([[1, 2, 3]]),
+ "mm_token_type_ids": mx.zeros((1, 3), dtype=mx.int32),
+ }
+ with patch("mlx_vlm.utils.prepare_inputs", return_value=inputs):
+ result = engine._prepare_vision_inputs(
+ [{"role": "user", "content": "Describe."}], []
+ )
+ assert result[0] == [1, 2, 3]
+ assert result[1] is features["inputs_embeds"]
+ assert result[2]["_captured_rope_deltas"].tolist() == [[0]]
+ assert result[2]["position_ids"].tolist() == positions.tolist()
+ assert result[3:] == (None, 0, [])
+ assert engine._vlm_model.get_input_embeddings.call_args.args[1] is None
+
+
+@pytest.mark.parametrize("model_type", ["minicpmv4_7", "qwen3_5_moe"])
+@pytest.mark.parametrize("seq_len", [1, 3])
+def test_decode_and_verify_forward_request_deltas_without_changing_qwen_abi(
+ model_type, seq_len
+):
+ calls = []
+
+ def language(input_ids, **kwargs):
+ calls.append(kwargs)
+ if model_type == "minicpmv4_7":
+ assert kwargs["rope_deltas"].shape == (2, 1)
+ return SimpleNamespace(logits=mx.zeros((2, seq_len, 8)))
+
+ model = SimpleNamespace(
+ language_model=language,
+ config=SimpleNamespace(
+ model_type=model_type,
+ text_config=SimpleNamespace(
+ rope_parameters={"mrope_section": [11, 11, 10]}
+ ),
+ ),
+ )
+ adapter = VLMModelAdapter(model)
+ adapter.set_batch_rope_deltas(mx.array([0, -5]))
+ cache = [SimpleNamespace(offset=mx.array([10, 20]))]
+ adapter(mx.ones((2, seq_len), dtype=mx.int32), cache=cache)
+ if model_type == "minicpmv4_7":
+ assert calls[0]["rope_deltas"].tolist() == [[0], [-5]]
+ else:
+ assert "rope_deltas" not in calls[0]
+ assert calls[0]["position_ids"][0].tolist() == [
+ list(range(10, 10 + seq_len)),
+ list(range(15, 15 + seq_len)),
+ ]
+
+
+@pytest.mark.parametrize("return_hidden", [False, True])
+def test_native_captures_preserve_caller_order_and_pre_norm_final(return_hidden):
+ calls = []
+ transaction = object()
+
+ def language(input_ids, **kwargs):
+ calls.append(kwargs)
+ assert kwargs["return_hidden"] is False
+ return LanguageModelOutput(
+ logits=mx.zeros((1, 2, 8)),
+ hidden_states=[
+ mx.full((1, 2, 4), layer) for layer in kwargs["capture_layer_ids"]
+ ],
+ gdn_states=transaction,
+ )
+
+ language.model = SimpleNamespace(layers=[object() for _ in range(4)])
+ adapter = VLMModelAdapter(
+ SimpleNamespace(
+ language_model=language,
+ config=SimpleNamespace(model_type="minicpmv4_7"),
+ )
+ )
+ result = adapter(
+ mx.array([[1, 2]]),
+ capture_layer_ids=[2, 0],
+ return_hidden=return_hidden,
+ )
+ assert calls[0]["capture_layer_ids"] == ([0, 2, 3] if return_hidden else [0, 2])
+ assert [value[0, 0, 0].item() for value in result.hidden_states] == (
+ [2, 0, 3] if return_hidden else [2, 0]
+ )
+ assert result.gdn_states is transaction
+
+
+def test_minicpm_backbone_uses_capture_bearing_native_exact_verifier():
+ from omlx.patches.mlx_lm_mtp.batch_generator import _call_backbone_captured
+
+ calls = []
+ transaction = object()
+
+ def language(input_ids, **kwargs):
+ calls.append(kwargs)
+ assert kwargs["speculative_verify"] is True
+ assert kwargs["rope_deltas"].tolist() == [[-3]]
+ return LanguageModelOutput(
+ logits=mx.zeros((1, 3, 8)),
+ hidden_states=[
+ mx.full((1, 3, 4), layer) for layer in kwargs["capture_layer_ids"]
+ ],
+ gdn_states=transaction,
+ )
+
+ language.model = SimpleNamespace(layers=[object() for _ in range(4)])
+ language.speculative_verify_logits = MagicMock(
+ side_effect=AssertionError("Convenience verifier loses the capture ABI")
+ )
+ adapter = VLMModelAdapter(
+ SimpleNamespace(
+ language_model=language,
+ config=SimpleNamespace(model_type="minicpmv4_7"),
+ )
+ )
+ adapter.set_batch_rope_deltas(mx.array([-3]))
+ logits, hidden, state, captures = _call_backbone_captured(
+ adapter,
+ mx.array([[1, 2, 3]]),
+ [SimpleNamespace(offset=4)],
+ n_confirmed=1,
+ capture_layer_ids=[2, 0],
+ )
+ assert hidden[0, 0, 0].item() == 3
+ assert [value[0, 0, 0].item() for value in captures] == [2, 0]
+ assert state is transaction
+ assert logits.shape == (1, 3, 8)
+ language.speculative_verify_logits.assert_not_called()
+
+
+def test_token_count_runs_exact_processor_without_vision_forward(engine, inputs):
+ engine._extract_request_media = MagicMock(
+ return_value=(
+ [{"role": "user", "content": "<|image_pad|>Describe."}],
+ [{"role": "user", "content": "Describe."}],
+ [Image.new("RGB", (4, 4))],
+ [],
+ [],
+ )
+ )
+ with patch("mlx_vlm.utils.prepare_inputs", return_value=inputs) as prepare:
+ assert (
+ engine.count_chat_tokens(
+ [{"role": "user", "content": "Describe."}],
+ mm_processor_kwargs={"downsample_mode": "4x"},
+ )
+ == 4
+ )
+ assert prepare.call_args.kwargs["downsample_mode"] == "4x"
+ engine._vlm_model.get_input_embeddings.assert_not_called()
+
+
+@pytest.mark.asyncio
+async def test_preflight_uses_exact_processor_count_on_executor(engine):
+ scheduler = object()
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ engine._engine = SimpleNamespace(
+ _mlx_executor=executor, engine=SimpleNamespace(scheduler=scheduler)
+ )
+ engine.count_chat_tokens = MagicMock(return_value=128)
+ engine._preflight_or_raise_with_eviction = AsyncMock()
+ await engine.preflight_chat(
+ [{"role": "user", "content": "Describe."}],
+ request_id="tiny",
+ mm_processor_kwargs={"downsample_mode": "4x"},
+ )
+ assert engine.count_chat_tokens.call_args.kwargs["mm_processor_kwargs"] == {
+ "downsample_mode": "4x"
+ }
+ engine._preflight_or_raise_with_eviction.assert_awaited_once_with(
+ scheduler, num_prompt_tokens=128, request_id="tiny"
+ )
+
+
+@pytest.mark.asyncio
+async def test_dspark_preflight_rejects_request_local_sparse_prefill(engine):
+ engine._dflash_drafter = SimpleNamespace(kind="dspark")
+ with pytest.raises(InvalidRequestError, match="full target context"):
+ await engine.preflight_chat([], specprefill=True)
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ "options,match",
+ [
+ ({"xtc_probability": 0.5, "temperature": 0.7}, "stochastic XTC"),
+ ({"compiled_grammar": object()}, "constrained grammar"),
+ ],
+)
+async def test_dspark_unsupported_sampling_fails_before_admission(
+ engine, options, match
+):
+ engine._dflash_drafter = SimpleNamespace(kind="dspark")
+ with pytest.raises(InvalidRequestError, match=match):
+ await engine.preflight_chat([], **options)
+ with pytest.raises(InvalidRequestError, match=match):
+ await engine.generate([1], **options)
+ with pytest.raises(InvalidRequestError, match=match):
+ await anext(engine.stream_generate([1], **options))
+
+
+def test_dspark_xtc_is_inactive_for_greedy_and_does_not_gate_base_serving(engine):
+ engine._dflash_drafter = SimpleNamespace(kind="dspark")
+ engine._validate_dspark_request(xtc_probability=0.5, temperature=0.0)
+ engine._dflash_drafter = None
+ engine._validate_dspark_request(
+ xtc_probability=0.5, temperature=0.7, compiled_grammar=object()
+ )
+
+
+def test_audio_is_rejected_before_processor_or_encoder(engine):
+ with (
+ patch("mlx_vlm.utils.prepare_inputs") as prepare,
+ pytest.raises(InvalidRequestError, match="not audio"),
+ ):
+ engine._prepare_vision_inputs([], [], audio=[object()])
+ prepare.assert_not_called()
+ engine._vlm_model.get_input_embeddings.assert_not_called()
+
+
+@pytest.mark.asyncio
+async def test_protocol_merge_rejects_non_minicpm_and_preserves_request_precedence():
+ from omlx import server
+
+ settings = ModelSettings(
+ mm_processor_kwargs={"max_slice_nums": 9, "downsample_mode": "16x"}
+ )
+ request = SimpleNamespace(
+ mm_processor_kwargs=MultimodalProcessorOptions(downsample_mode="4x")
+ )
+ with pytest.raises(InvalidRequestError, match="only supported"):
+ server._request_mm_processor_kwargs(SimpleNamespace(), request, settings)
+ model = SimpleNamespace(model_type="minicpmv4_7")
+ options = server._request_mm_processor_kwargs(model, request, settings)
+ assert options == {"max_slice_nums": 9, "downsample_mode": "4x"}
+ model.count_chat_tokens = MagicMock(return_value=4)
+ count_threads = []
+ model.count_chat_tokens.side_effect = lambda *a, **k: (
+ count_threads.append(get_ident()) or 4
+ )
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ model._engine = SimpleNamespace(_mlx_executor=executor)
+ assert await server._prepare_chat_prompt_for_request(
+ model, [], mm_processor_kwargs=options
+ ) == (4, None)
+ assert count_threads[0] != get_ident()
+ assert model.count_chat_tokens.call_args.kwargs["mm_processor_kwargs"] == options
+
+
+@pytest.mark.asyncio
+async def test_tokenization_avoids_encoder_and_gpu_cleanup(engine, inputs):
+ engine._extract_request_media = MagicMock(
+ return_value=(
+ [{"role": "user", "content": [{"type": "image"}]}],
+ [{"role": "user", "content": ""}],
+ [Image.new("RGB", (4, 4))],
+ [],
+ [],
+ )
+ )
+ with (
+ ThreadPoolExecutor(max_workers=1) as executor,
+ patch("mlx_vlm.utils.prepare_inputs", return_value=inputs),
+ patch("omlx.engine.vlm.mx.synchronize") as synchronize,
+ patch("omlx.engine.vlm.mx.clear_cache") as clear_cache,
+ ):
+ engine._engine = SimpleNamespace(_mlx_executor=executor)
+ assert await engine.tokenize_chat([]) == [1, 99, 99, 2]
+ engine._vlm_model.get_input_embeddings.assert_not_called()
+ synchronize.assert_not_called()
+ clear_cache.assert_not_called()
+
+
+@pytest.fixture
+def protocol_engine(monkeypatch):
+ from omlx import server
+
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ model = MagicMock()
+ model.model_type = "minicpmv4_7"
+ model.tokenizer = None
+ model.is_diffusion_model = False
+ model.supports_request_scoped_abort = False
+ model._engine = SimpleNamespace(_mlx_executor=executor)
+ model.start = AsyncMock()
+ model.preflight_chat = AsyncMock()
+ model.count_chat_tokens.return_value = 4
+ output = GenerationOutput(
+ text="Done.", new_text="Done.", prompt_tokens=4, completion_tokens=1
+ )
+ model.chat = AsyncMock(return_value=output)
+ model.streamed_kwargs = []
+
+ async def stream_chat(**kwargs):
+ model.streamed_kwargs.append(kwargs)
+ yield output
+
+ model.stream_chat = stream_chat
+ pool = MagicMock()
+ pool.preload_pinned_models = AsyncMock()
+ pool.check_ttl_expirations = AsyncMock()
+ pool.shutdown = AsyncMock()
+ pool.get_entry.return_value = SimpleNamespace(
+ config_model_type="minicpmv4_7", preserve_thinking_default=True
+ )
+ state = server.ServerState()
+ state.engine_pool = pool
+ monkeypatch.setattr(server, "_server_state", state)
+ monkeypatch.setattr(
+ server, "get_engine_for_model", AsyncMock(return_value=model)
+ )
+ monkeypatch.setattr(server, "resolve_model_id", lambda name: name)
+ monkeypatch.setattr(server, "validate_context_window", lambda *a, **k: None)
+ monkeypatch.setattr(
+ server,
+ "get_model_settings_for_request",
+ lambda name: ModelSettings(
+ mm_processor_kwargs={"downsample_mode": "16x", "max_slice_nums": 9}
+ ),
+ )
+ monkeypatch.setitem(
+ server.app.dependency_overrides,
+ server.verify_inference_api_key,
+ lambda: True,
+ )
+ yield model
+
+
+@pytest.mark.parametrize("stream", [False, True])
+@pytest.mark.parametrize(
+ "path", ["/v1/chat/completions", "/v1/messages", "/v1/responses"]
+)
+def test_protocols_forward_controls_to_count_admission_and_generation(
+ protocol_engine, path, stream
+):
+ from omlx import server
+
+ body = {
+ "model": "tiny-minicpm",
+ "stream": stream,
+ "mm_processor_kwargs": {"downsample_mode": "4x"},
+ }
+ if path == "/v1/responses":
+ body.update(input="Describe.", store=False)
+ else:
+ body.update(messages=[{"role": "user", "content": "Describe."}], max_tokens=16)
+ with TestClient(server.app, raise_server_exceptions=False) as client:
+ response = client.post(path, json=body)
+ assert response.status_code == 200, response.text
+ expected = {"downsample_mode": "4x", "max_slice_nums": 9}
+ assert (
+ protocol_engine.count_chat_tokens.call_args.kwargs["mm_processor_kwargs"]
+ == expected
+ )
+ assert (
+ protocol_engine.preflight_chat.call_args.kwargs["mm_processor_kwargs"]
+ == expected
+ )
+ generated = (
+ protocol_engine.streamed_kwargs[0]
+ if stream
+ else protocol_engine.chat.call_args.kwargs
+ )
+ assert generated["mm_processor_kwargs"] == expected
+
+
+def test_anthropic_count_endpoint_uses_same_controls(protocol_engine):
+ from omlx import server
+
+ with TestClient(server.app, raise_server_exceptions=False) as client:
+ response = client.post(
+ "/v1/messages/count_tokens",
+ json={
+ "model": "tiny-minicpm",
+ "messages": [{"role": "user", "content": "Describe."}],
+ "mm_processor_kwargs": {"downsample_mode": "4x"},
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert response.json()["input_tokens"] == 4
+ assert protocol_engine.count_chat_tokens.call_args.kwargs[
+ "mm_processor_kwargs"
+ ] == {
+ "downsample_mode": "4x",
+ "max_slice_nums": 9,
+ }
+
+
+def test_formatting_preserves_mixed_visual_order_and_tool_reasoning(engine):
+ del engine._format_messages_for_vlm_template
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "Before"},
+ {"type": "image_url", "image_url": {"url": "ignored"}},
+ {"type": "text", "text": "Between"},
+ {"type": "video_url", "video_url": {"url": "ignored"}},
+ {"type": "text", "text": "After"},
+ ],
+ },
+ {
+ "role": "assistant",
+ "content": "",
+ "reasoning_content": "Think",
+ "tool_calls": [],
+ },
+ {"role": "tool", "content": "Result", "tool_call_id": "call_1"},
+ ]
+ formatted, ranges = engine._format_messages_for_vlm_template(
+ messages, num_images=1, num_videos=1
+ )
+ assert [part["type"] for part in formatted[0]["content"]] == [
+ "text",
+ "image",
+ "text",
+ "video",
+ "text",
+ ]
+ assert formatted[1:] == messages[1:]
+ assert "image_url" in messages[0]["content"][1]
+ assert ranges == []
+
+
+def test_system_visuals_are_rejected_without_formatter_fallback(engine):
+ del engine._format_messages_for_vlm_template
+ with pytest.raises(InvalidRequestError, match="system messages"):
+ engine._prepare_vision_inputs(
+ [{"role": "system", "content": [{"type": "image"}]}],
+ [Image.new("RGB", (4, 4))],
+ )
+
+
+@pytest.mark.parametrize(
+ "content, text_parts",
+ [
+ ("Question", [{"type": "text", "text": "Question"}]),
+ (
+ [{"type": "text", "text": "First"}, {"type": "text", "text": "Second"}],
+ [{"type": "text", "text": "First"}, {"type": "text", "text": "Second"}],
+ ),
+ ],
+)
+def test_direct_engine_visuals_are_inserted_on_user_turn(engine, content, text_parts):
+ del engine._format_messages_for_vlm_template
+ formatted, _ = engine._format_messages_for_vlm_template(
+ [
+ {"role": "system", "content": "System"},
+ {"role": "user", "content": content},
+ ],
+ num_images=2,
+ )
+ assert formatted[0]["content"] == "System"
+ assert formatted[1]["content"] == [
+ {"type": "image"},
+ {"type": "image"},
+ *text_parts,
+ ]
diff --git a/tests/test_minicpm_pairing.py b/tests/test_minicpm_pairing.py
new file mode 100644
index 0000000000..9ebc9c441e
--- /dev/null
+++ b/tests/test_minicpm_pairing.py
@@ -0,0 +1,52 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Source metadata admission is separate from shape/tokenizer compatibility."""
+
+import hashlib
+import json
+
+import pytest
+
+from omlx.speculative.minicpm_pairing import HELPER, TARGET, validate_model_pair
+
+
+def source(directory, identity, *, conversion=False):
+ directory.mkdir()
+ config = {"model_type": "minicpmv4_7"}
+ if conversion:
+ config["omlx_source"] = {"repo_id": identity[0], "revision": identity[1]}
+ data = json.dumps(config).encode()
+ (directory / "config.json").write_bytes(data)
+ if not conversion:
+ metadata = directory / ".cache/huggingface/download"
+ metadata.mkdir(parents=True)
+ blob = b"blob " + str(len(data)).encode() + b"\0" + data
+ digest = hashlib.sha1(blob, usedforsecurity=False).hexdigest()
+ (metadata / "config.json.metadata").write_text(f"{identity[1]}\n{digest}\n0\n")
+ return str(directory)
+
+
+@pytest.mark.parametrize("conversion", [False, True])
+def test_original_and_declared_conversion_pairing(tmp_path, conversion):
+ target = source(tmp_path / "target", TARGET, conversion=conversion)
+ helper = source(tmp_path / "helper", HELPER, conversion=conversion)
+ validate_model_pair(target, helper)
+
+
+def test_missing_or_stale_provenance_is_not_shape_based_admission(tmp_path):
+ target = source(tmp_path / "target", TARGET)
+ helper = source(tmp_path / "helper", HELPER)
+ with pytest.raises(ValueError, match="source path"):
+ validate_model_pair(None, helper)
+ (tmp_path / "helper/config.json").write_text('{"model_type": "qwen3"}')
+ with pytest.raises(ValueError, match="Stale or mismatched"):
+ validate_model_pair(target, helper)
+ (tmp_path / "helper/.cache/huggingface/download/config.json.metadata").unlink()
+ with pytest.raises(ValueError, match="Cannot establish"):
+ validate_model_pair(target, helper)
+
+
+def test_other_source_or_helper_revision_is_rejected(tmp_path):
+ target = source(tmp_path / "target", TARGET, conversion=True)
+ helper = source(tmp_path / "helper", (HELPER[0], "unreviewed"), conversion=True)
+ with pytest.raises(ValueError, match="does not match"):
+ validate_model_pair(target, helper)
diff --git a/tests/test_mlx_lm_mtp_patch.py b/tests/test_mlx_lm_mtp_patch.py
index 4cfb3a1e0c..bc466d2bcf 100644
--- a/tests/test_mlx_lm_mtp_patch.py
+++ b/tests/test_mlx_lm_mtp_patch.py
@@ -2216,6 +2216,168 @@ def __call__(self, inputs, **kwargs):
assert calls[0] == (True, armed)
+class TestBackboneCaptureDispatch:
+ @pytest.mark.parametrize("capture_ids", [None, []])
+ def test_mrope_adapter_verification_keeps_position_binding(self, capture_ids):
+ from mlx_vlm.models.base import LanguageModelOutput
+
+ values = mx.zeros((1, 3, 4))
+ rollback = object()
+ calls = []
+
+ class Target:
+ def speculative_verify_logits(self, *args):
+ pytest.fail("Direct verifier bypassed adapter position binding")
+
+ def __call__(self, inputs, **kwargs):
+ calls.append(kwargs)
+ return LanguageModelOutput(
+ logits=values,
+ hidden_states=[values],
+ gdn_states=rollback,
+ )
+
+ model = _adapter(Target())
+ model._uses_mrope = True
+ model.set_batch_rope_deltas(mx.array([7.0]))
+ cache = [SimpleNamespace(offset=14)]
+ actual = bg._call_backbone_captured(
+ model, mx.array([[1, 2, 3]]), cache, 1, capture_ids
+ )
+
+ assert actual == (values, values, rollback, None)
+ assert len(calls) == 1
+ assert calls[0]["n_confirmed"] == 1
+ assert calls[0]["position_ids"].tolist() == [[[21, 22, 23]]] * 3
+
+ @pytest.mark.parametrize("adapter", [False, True])
+ @pytest.mark.parametrize("n_confirmed", [0, 1])
+ def test_backbone_capture_uses_capture_bearing_verification(
+ self, adapter, n_confirmed
+ ):
+ from mlx_vlm.models.base import LanguageModelOutput
+
+ requested = [61, 5, 33, 19, 47]
+ inputs = mx.array([[1, 2, 3, 4, 5]])
+ logits = mx.zeros((1, 5, 8))
+ hidden = mx.full((1, 5, 4), 63)
+ rollback = object()
+ calls = []
+
+ class Target:
+ def speculative_verify_logits(self, inputs, cache, sampler):
+ return hidden, {}, rollback, sampler(logits)
+
+ def __call__(self, inputs, **kwargs):
+ calls.append(kwargs)
+ return LanguageModelOutput(
+ logits=logits,
+ hidden_states=[
+ mx.full((1, 5, 4), layer)
+ for layer in kwargs["capture_layer_ids"]
+ ]
+ + [hidden],
+ gdn_states=rollback,
+ )
+
+ target = Target()
+ model = _adapter(target) if adapter else target
+ cache = []
+ actual = bg._call_backbone_captured(
+ model, inputs, cache, n_confirmed=n_confirmed, capture_layer_ids=requested
+ )
+ assert actual[0] is logits
+ assert actual[1] is hidden
+ assert actual[2] is rollback
+ assert len(actual[3]) == len(requested)
+ for layer, capture in zip(requested, actual[3]):
+ assert capture.shape == (1, 5, 4)
+ assert mx.all(capture == layer)
+ expected = {
+ "cache": cache,
+ "return_hidden": True,
+ "capture_layer_ids": requested,
+ }
+ if n_confirmed:
+ expected["n_confirmed"] = n_confirmed
+ assert calls == [expected]
+
+ @pytest.mark.parametrize("capture_ids", [None, []])
+ def test_backbone_capture_empty_keeps_exact_convenience_path(self, capture_ids):
+ values = mx.zeros((1, 3, 4))
+ rollback = object()
+ calls = []
+
+ class Target:
+ def speculative_verify_logits(self, inputs, cache, sampler):
+ calls.append(tuple(inputs.shape))
+ return values, {}, rollback, sampler(values)
+
+ def __call__(self, inputs, **kwargs):
+ pytest.fail("Native no-capture verification lost its fast path")
+
+ actual = bg._call_backbone_captured(
+ Target(), mx.array([[1, 2, 3]]), [], 1, capture_ids
+ )
+ assert actual == (values, values, rollback, None)
+ assert calls == [(1, 3)]
+
+ @pytest.mark.parametrize("size", [2, 3])
+ def test_backbone_capture_none_preserves_tuple_outputs(self, size):
+ values = mx.zeros((1, 3, 4))
+ rollback = object() if size == 3 else None
+
+ class Target:
+ def __call__(self, inputs, **kwargs):
+ return (values, values, rollback)[:size]
+
+ actual = bg._call_backbone_captured(
+ Target(), mx.array([[1, 2, 3]]), [], n_confirmed=1
+ )
+ assert actual == (values, values, rollback, None)
+
+ @pytest.mark.parametrize("result_kind", ["tuple2", "tuple3", "short", "error"])
+ def test_backbone_capture_contract_errors_disarm_verification(
+ self, monkeypatch, result_kind
+ ):
+ from mlx_vlm.models.base import LanguageModelOutput
+
+ armed = []
+ monkeypatch.setattr(
+ bg._rollback_mod, "set_undo_armed", lambda value: armed.append(value)
+ )
+ qmm = []
+ monkeypatch.setattr(
+ bg, "_set_verify_qmm_armed", lambda value, **kwargs: qmm.append(value)
+ )
+
+ class Target:
+ def __call__(self, inputs, **kwargs):
+ if result_kind == "error":
+ raise RuntimeError("capture producer failed")
+ if result_kind == "short":
+ return LanguageModelOutput(
+ logits=mx.zeros((1, 3, 8)),
+ hidden_states=[mx.zeros((1, 3, 4))],
+ )
+ return (None,) * (2 if result_kind == "tuple2" else 3)
+
+ error = RuntimeError if result_kind == "error" else TypeError
+ match = (
+ "capture producer failed"
+ if result_kind == "error"
+ else (
+ "0 captures for 2 requested"
+ if result_kind == "short"
+ else "tuple output cannot carry layer captures"
+ )
+ )
+ with pytest.raises(error, match=match):
+ bg._call_backbone_captured(Target(), mx.array([[1, 2, 3]]), [], 1, [0, 2])
+ assert armed == [True, False]
+ assert qmm == [True, False]
+
+
class TestPreLoadPatchDispatch:
def test_dispatch_skips_when_mtp_disabled(self, tmp_path):
config_path = tmp_path / "config.json"
@@ -3665,6 +3827,12 @@ def __call__(
)
+class ExactCapturingCountingModel(CapturingCountingModel):
+ def speculative_verify_logits(self, inputs, cache, sampler):
+ out = self(inputs, cache=cache, return_hidden=True, n_confirmed=1)
+ return out.hidden_states[-1], {}, out.gdn_states, sampler(out.logits)
+
+
class TableDrafter:
"""Block drafter proposing successors, optionally wrong from a position."""
@@ -3725,8 +3893,8 @@ def release(self, uids):
self.released.extend(uids)
-def _drafted_counting_model(depth, wrong_from=None, adaptive=False):
- model = CapturingCountingModel()
+def _drafted_counting_model(depth, wrong_from=None, adaptive=False, exact_verify=False):
+ model = ExactCapturingCountingModel() if exact_verify else CapturingCountingModel()
model._omlx_mtp_depth = depth
model._omlx_drafter = TableDrafter(depth, wrong_from=wrong_from, adaptive=adaptive)
return model
@@ -3739,8 +3907,9 @@ def _verify_widths(model):
@pytest.mark.parametrize("adaptive", [False, True])
@pytest.mark.parametrize("wrong_from", [None, 0, 2])
@pytest.mark.parametrize("late_join", [False, True])
+@pytest.mark.parametrize("exact_verify", [False, True])
def test_block_drafter_matches_standard_and_feeds_committed_context(
- wrong_from, late_join, adaptive
+ wrong_from, late_join, adaptive, exact_verify
):
prompts = [[1, 2], [10, 11, 12], [30, 31]]
limits = [12, 8, 15]
@@ -3748,7 +3917,9 @@ def test_block_drafter_matches_standard_and_feeds_committed_context(
standard._omlx_mtp_decode_enabled = False
expected, _ = generate(standard, prompts, limits, late_join=late_join)
- model = _drafted_counting_model(5, wrong_from=wrong_from, adaptive=adaptive)
+ model = _drafted_counting_model(
+ 5, wrong_from=wrong_from, adaptive=adaptive, exact_verify=exact_verify
+ )
output, terminal = generate(model, prompts, limits, late_join=late_join)
assert output == expected
drafter = model._omlx_drafter
@@ -3762,6 +3933,8 @@ def test_block_drafter_matches_standard_and_feeds_committed_context(
# whose pipelined step also forwards the newest token.
for uid in terminal:
assert drafter.fed[uid] - len(output[uid]) in ((0, 1) if adaptive else (0,))
+ assert len(output[uid]) == limits[uid]
+ assert terminal[uid].finish_reason == "length"
# Finished rows leave the drafter registry.
assert sorted(drafter.released) == sorted(terminal)
@@ -3801,6 +3974,57 @@ def propose(self, limit):
assert drafter.fed[uid] == len(output[uid])
+def test_exact_capture_block_drafter_stop_keeps_survivor_correct():
+ model = _drafted_counting_model(5, exact_verify=True)
+ output, terminal = generate(
+ model, [[1, 2], [10, 11, 12]], [12, 9], stop_tokens=[[6]]
+ )
+ assert output[0] == [3, 4, 5, 6]
+ assert terminal[0].finish_reason == "stop"
+ assert output[1] == list(range(13, 22))
+ assert terminal[1].finish_reason == "length"
+ cache = terminal[0].prompt_cache[0]
+ assert cache.keys[0, 0, : cache.offset, 0].tolist() == [1, 2, 3, 4, 5]
+ for uid in terminal:
+ assert model._omlx_drafter.fed[uid] == len(output[uid])
+
+
+def test_exact_capture_block_drafter_cancellation_releases_context():
+ bg.apply()
+ cache_rollback.apply()
+ model = _drafted_counting_model(5, wrong_from=2, exact_verify=True)
+ gen = BatchGenerator(
+ model, sampler=lambda lp: mx.argmax(lp, -1), prefill_batch_size=3, max_tokens=24
+ )
+ try:
+ uids = gen.insert([[1, 2], [10, 11], [20, 21]])
+ output = {uid: [] for uid in uids}
+ cancelled = None
+ terminal = {}
+ for step in range(60):
+ if step == 3:
+ gen.remove([uids[1]])
+ cancelled = len(output[uids[1]])
+ _, responses = gen.next()
+ for response in responses:
+ assert response.uid not in terminal
+ if cancelled is not None:
+ assert response.uid != uids[1]
+ output[response.uid].append(response.token)
+ if response.finish_reason:
+ terminal[response.uid] = response
+ if len(terminal) == 2:
+ break
+ assert model._omlx_drafter.jobs > 0
+ assert len(output[uids[1]]) == cancelled
+ assert output[uids[0]] == list(range(3, 27))
+ assert output[uids[2]] == list(range(22, 46))
+ assert all(response.finish_reason == "length" for response in terminal.values())
+ assert set(model._omlx_drafter.released) == set(uids)
+ finally:
+ gen.close()
+
+
def test_block_drafter_serves_sampled_rows_with_draft_distribution():
"""A sampled row rides Leviathan acceptance against the drafter's q."""
from omlx.utils.sampling import make_sampler
@@ -4892,6 +5116,244 @@ def _model(family):
raise AssertionError(family)
+def _exact_capture_qwen(family, layers=4, bits=None):
+ from mlx_vlm.models.qwen3_5 import config, language
+ from test_mtp_prompt_priming import TINY_CONFIG
+
+ from omlx.patches.mlx_vlm_mtp import qwen35_vlm_runtime
+
+ qwen35_vlm_runtime.apply()
+ if family == "moe":
+ from mlx_vlm.models.qwen3_5_moe import config, language
+
+ from omlx.patches.mlx_vlm_mtp import qwen35_moe_vlm_runtime
+
+ qwen35_moe_vlm_runtime.apply()
+ args = config.TextConfig.from_dict(
+ dict(
+ TINY_CONFIG,
+ model_type="qwen3_5_moe" if family == "moe" else "qwen3_5",
+ num_hidden_layers=layers,
+ tie_word_embeddings=False,
+ num_experts=4,
+ num_experts_per_tok=2,
+ moe_intermediate_size=64,
+ shared_expert_intermediate_size=64,
+ )
+ )
+ target = language.LanguageModel(
+ args, config.ModelConfig(args, config.VisionConfig(), args.model_type)
+ )
+ if bits is not None:
+ nn.quantize(target, bits=bits, group_size=32)
+ target.set_dtype(mx.bfloat16)
+ mx.eval(target.parameters())
+ return _adapter(target)
+
+
+def _assert_exact_capture_cache(actual, expected, *, atol=0):
+ assert len(actual) == len(expected)
+ for left, right in zip(actual, expected):
+ a, b = tree_flatten(left.state), tree_flatten(right.state)
+ assert [key for key, _ in a] == [key for key, _ in b]
+ for (_, value), (_, reference) in zip(a, b):
+ if isinstance(value, mx.array):
+ assert value.shape == reference.shape
+ assert value.dtype == reference.dtype
+ assert mx.allclose(
+ value, reference, atol=atol, rtol=1e-5 if atol else 0
+ )
+ else:
+ assert value == reference
+ if hasattr(left, "offset"):
+ assert mx.array_equal(mx.array(left.offset), mx.array(right.offset))
+ assert getattr(left, "_speculation", None) is None
+
+
+@pytest.mark.parametrize("family", ["dense", "moe"])
+def test_mrope_mtp_verify_without_drafter_keeps_exact_transaction(family):
+ from mlx_vlm.speculative.cache_state import SpeculativeCacheTransaction
+
+ mx.random.seed(946)
+ model = _exact_capture_qwen(family, bits=4)
+ model._uses_mrope = True
+ model.set_batch_rope_deltas(mx.array([7.0]))
+ cache = model._language_model.make_cache()
+ mx.eval(model(mx.array([[3, 4, 5]]), cache=cache))
+ reference = copy.deepcopy(cache)
+ inputs = mx.array([[6, 7, 8, 9]])
+ result = bg._call_backbone(model, inputs, cache, n_confirmed=1)
+ transaction = result[2]
+ assert isinstance(transaction, SpeculativeCacheTransaction)
+ try:
+ mx.eval(result[0], result[1])
+ assert bg._chain_rollback(model, cache, 0, 3, transaction)
+ committed = bg._call_backbone(
+ model, inputs[:, :1], reference, n_confirmed=1
+ )
+ committed[2].commit(1)
+ _assert_exact_capture_cache(cache, reference, atol=1e-6)
+ next_input = mx.array([[10]])
+ actual = model(next_input, cache=cache)
+ expected = model(next_input, cache=reference)
+ assert mx.allclose(actual, expected, atol=1e-5, rtol=1e-5)
+ assert mx.array_equal(mx.argmax(actual, -1), mx.argmax(expected, -1))
+ finally:
+ transaction.abort()
+
+
+@pytest.mark.parametrize(
+ "family,layers,capture_ids,bits",
+ [
+ ("dense", 64, [61, 5, 33, 19, 47], None),
+ ("dense", 4, [3, 0, 3, 2], None),
+ ("dense", 4, [2, 0], 4),
+ ("moe", 4, [3, 0, 2], None),
+ ],
+)
+def test_exact_capture_matches_verifier_tensors(
+ monkeypatch, family, layers, capture_ids, bits
+):
+ from mlx_vlm.models.qwen3_5 import language
+ from mlx_vlm.speculative.cache_state import SpeculativeCacheTransaction
+
+ mx.random.seed(916)
+ model = _exact_capture_qwen(family, layers, bits)
+ target = model._language_model
+ prefix = mx.array([[3, 4, 5]])
+ inputs = mx.array([[6, 7, 8, 9, 10]])
+ cache = target.make_cache()
+ mx.eval(model(prefix, cache=cache))
+ reference_cache = copy.deepcopy(cache)
+ verifier = language._EXACT_SPECULATIVE_VERIFIER
+ original = verifier._layer
+ reference_layers = {}
+ indices = {id(layer): index for index, layer in enumerate(target.model.layers)}
+
+ def record(layer, *args, **kwargs):
+ out = original(layer, *args, **kwargs)
+ reference_layers[indices[id(layer)]] = out
+ return out
+
+ with monkeypatch.context() as m:
+ m.setattr(verifier, "_layer", record)
+ logits, hidden, transaction = bg._call_backbone(
+ model, inputs, reference_cache, n_confirmed=1
+ )
+ assert isinstance(transaction, SpeculativeCacheTransaction)
+ transaction.commit(inputs.shape[1])
+ assert set(reference_layers) == set(range(layers))
+ verified = []
+ original_verify = verifier.verify
+
+ def verify(*args, **kwargs):
+ verified.append(kwargs["capture_layer_ids"])
+ return original_verify(*args, **kwargs)
+
+ monkeypatch.setattr(verifier, "verify", verify)
+ actual = bg._call_backbone_captured(
+ model, inputs, cache, n_confirmed=1, capture_layer_ids=capture_ids
+ )
+ transaction = actual[2]
+ assert isinstance(transaction, SpeculativeCacheTransaction)
+ try:
+ assert verified == [sorted({*capture_ids, layers - 1})]
+ assert mx.array_equal(actual[0], logits)
+ assert mx.array_equal(actual[1], hidden)
+ assert mx.array_equal(actual[1], reference_layers[layers - 1])
+ assert len(actual[3]) == len(capture_ids)
+ for layer, capture in zip(capture_ids, actual[3]):
+ assert capture.shape == (1, 5, 64)
+ assert mx.array_equal(capture, reference_layers[layer])
+ assert bg._chain_rollback(model, cache, 4, 4, transaction)
+ assert not transaction.active
+ _assert_exact_capture_cache(cache, reference_cache)
+ finally:
+ transaction.abort()
+
+
+@pytest.mark.parametrize("family", ["dense", "moe"])
+def test_exact_capture_prefill_commits_transaction(family):
+ mx.random.seed(935)
+ model = _exact_capture_qwen(family)
+ cache = model._language_model.make_cache()
+ reference = copy.deepcopy(cache)
+ inputs = mx.array([[3, 4, 5]])
+ actual = bg._call_backbone_captured(model, inputs, cache, capture_layer_ids=[2, 0])
+ expected = bg._call_backbone(model, inputs, reference, n_confirmed=1)
+ expected[2].commit(inputs.shape[1])
+ assert actual[2] is None
+ assert mx.array_equal(actual[0], expected[0])
+ assert mx.array_equal(actual[1], expected[1])
+ assert len(actual[3]) == 2
+ _assert_exact_capture_cache(cache, reference)
+
+
+@pytest.mark.parametrize("accepted", [0, 1, 4])
+@pytest.mark.parametrize("bits", [None, 4])
+def test_exact_capture_rollback_matches_native_verifier(accepted, bits):
+ from mlx_vlm.speculative.cache_state import SpeculativeCacheTransaction
+
+ mx.random.seed(927)
+ model = _exact_capture_qwen("dense", bits=bits)
+ cache = model._language_model.make_cache()
+ mx.eval(model(mx.array([[3, 4, 5]]), cache=cache))
+ reference = copy.deepcopy(cache)
+ inputs = mx.array([[6, 7, 8, 9, 10]])
+ result = bg._call_backbone_captured(
+ model, inputs, cache, n_confirmed=1, capture_layer_ids=[2, 0]
+ )
+ transaction = result[2]
+ assert isinstance(transaction, SpeculativeCacheTransaction)
+ try:
+ assert bg._chain_rollback(model, cache, accepted, 4, transaction)
+ assert not transaction.active
+ # The last-hidden-only native verifier is an independent capture-free path.
+ reference_result = bg._call_backbone(model, inputs, reference, n_confirmed=1)
+ reference_result[2].commit(accepted + 1)
+ _assert_exact_capture_cache(cache, reference)
+ next_input = mx.array([[11]])
+ actual_logits = model(next_input, cache=cache)
+ expected_logits = model(next_input, cache=reference)
+ assert mx.array_equal(actual_logits, expected_logits)
+ assert mx.array_equal(
+ mx.argmax(actual_logits, axis=-1), mx.argmax(expected_logits, axis=-1)
+ )
+ _assert_exact_capture_cache(cache, reference)
+ finally:
+ transaction.abort()
+
+
+@pytest.mark.parametrize("accepted", [0, 1, 4])
+def test_exact_capture_rollback_matches_committed_prefix(accepted):
+ mx.random.seed(927)
+ model = _exact_capture_qwen("dense")
+ cache = model._language_model.make_cache()
+ mx.eval(model(mx.array([[3, 4, 5]]), cache=cache))
+ reference = copy.deepcopy(cache)
+ inputs = mx.array([[6, 7, 8, 9, 10]])
+ result = bg._call_backbone_captured(
+ model, inputs, cache, n_confirmed=1, capture_layer_ids=[2, 0]
+ )
+ transaction = result[2]
+ try:
+ assert bg._chain_rollback(model, cache, accepted, 4, transaction)
+ committed = bg._call_backbone(
+ model, inputs[:, : accepted + 1], reference, n_confirmed=1
+ )
+ committed[2].commit(accepted + 1)
+ # Different FP32 window lengths can change reductions at roundoff scale.
+ _assert_exact_capture_cache(cache, reference, atol=1e-6)
+ next_input = mx.array([[11]])
+ actual = model(next_input, cache=cache)
+ expected = model(next_input, cache=reference)
+ assert mx.allclose(actual, expected, atol=1e-6, rtol=1e-5)
+ assert mx.array_equal(mx.argmax(actual, -1), mx.argmax(expected, -1))
+ _assert_exact_capture_cache(cache, reference, atol=1e-6)
+ finally:
+ transaction.abort()
+
+
@pytest.mark.parametrize("family", ["qwen", "qwen_vlm"])
@pytest.mark.parametrize("queued", [False, True])
def test_reconcile_matches_ordinary_prefill_cache_and_next_token(family, queued):
diff --git a/tests/test_mlx_vlm_bailing_moe_v3_vl_compat.py b/tests/test_mlx_vlm_bailing_moe_v3_vl_compat.py
new file mode 100644
index 0000000000..9f26e1e05b
--- /dev/null
+++ b/tests/test_mlx_vlm_bailing_moe_v3_vl_compat.py
@@ -0,0 +1,402 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Regression coverage for the Ling 3.0 Flash VL mlx-vlm overlay."""
+
+from __future__ import annotations
+
+import json
+from dataclasses import asdict
+from types import SimpleNamespace
+from unittest.mock import patch
+
+import pytest
+
+from omlx.model_discovery import detect_model_type
+from omlx.patches import mlx_vlm_bailing_moe_v3_vl_compat as compat
+
+try:
+ import mlx.core as mx
+
+ HAS_MLX = True
+except ImportError:
+ HAS_MLX = False
+
+pytestmark = pytest.mark.skipif(not HAS_MLX, reason="MLX not available")
+
+
+@pytest.fixture(scope="module", autouse=True)
+def _apply_compat_patch():
+ compat.apply_mlx_vlm_bailing_moe_v3_vl_compat_patch()
+ assert compat.is_applied()
+
+
+def _tiny_config(*, layer_plan: tuple[str, ...] = ("kda", "mla")):
+ from mlx_vlm.models import bailing_moe_v3_vl
+
+ text = bailing_moe_v3_vl.TextConfig(
+ vocab_size=64,
+ hidden_size=32,
+ intermediate_size=64,
+ num_hidden_layers=len(layer_plan),
+ num_attention_heads=2,
+ num_key_value_heads=2,
+ head_dim=16,
+ first_k_dense_replace=2,
+ num_experts=4,
+ num_experts_per_tok=2,
+ num_shared_experts=1,
+ moe_intermediate_size=32,
+ moe_shared_expert_intermediate_size=32,
+ n_group=2,
+ topk_group=1,
+ kv_lora_rank=32,
+ qk_nope_head_dim=8,
+ qk_rope_head_dim=8,
+ v_head_dim=8,
+ layer_group_size=2,
+ mrope_section=[2, 1, 1],
+ video_start_token=61,
+ )
+ text.layer_plan = layer_plan
+ vision = bailing_moe_v3_vl.VisionConfig(
+ depth=1,
+ hidden_size=16,
+ intermediate_size=32,
+ num_heads=2,
+ patch_size=2,
+ spatial_merge_size=2,
+ temporal_patch_size=1,
+ num_position_embeddings=16,
+ )
+ return bailing_moe_v3_vl.ModelConfig(
+ text_config=text,
+ vision_config=vision,
+ mrope_section=[2, 1, 1],
+ image_token_id=60,
+ video_token_id=61,
+ vision_start_token_id=62,
+ vision_end_token_id=63,
+ skip_vision=True,
+ )
+
+
+def test_vendor_module_processor_and_prompt_registration(tmp_path):
+ from mlx_vlm.models import bailing_moe_v3_vl
+ from mlx_vlm.prompt_utils import MODEL_CONFIG, MessageFormat, get_message_json
+ from mlx_vlm.utils import get_model_and_args
+ from transformers import AutoProcessor
+
+ module, model_type, *_ = get_model_and_args({"model_type": "bailing_moe_v3_vl"})
+ assert module is bailing_moe_v3_vl
+ assert model_type == "bailing_moe_v3_vl"
+ assert MODEL_CONFIG["bailing_moe_v3_vl"] is MessageFormat.LIST_WITH_IMAGE_FIRST
+ sentinel = object()
+ (tmp_path / "config.json").write_text(json.dumps({"model_type": "bailing_moe_v3_vl"}))
+ with patch.object(
+ bailing_moe_v3_vl.BailingMoeV3VLProcessor,
+ "from_pretrained",
+ return_value=sentinel,
+ ) as load:
+ assert AutoProcessor.from_pretrained(tmp_path) is sentinel
+ load.assert_called_once()
+
+ image = get_message_json(
+ "bailing_moe_v3_vl", "Describe this image.", num_images=1
+ )
+ assert image["content"][0] == {"type": "image"}
+ assert image["content"][1]["type"] == "text"
+ assert image["content"][1]["text"] == "Describe this image."
+ video = get_message_json(
+ "bailing_moe_v3_vl", "Describe this clip.", video=["clip.mp4"]
+ )
+ assert video["content"][0]["type"] == "video"
+ assert video["content"][-1]["type"] == "text"
+ assert video["content"][-1]["text"] == "Describe this clip."
+
+
+def test_processor_normalizes_ling_image_and_video_wrappers():
+ from mlx_vlm.models.bailing_moe_v3_vl import BailingMoeV3VLProcessor
+
+ processor = object.__new__(BailingMoeV3VLProcessor)
+ processor.vision_start_token = "<|vision_start|>"
+ processor.vision_end_token = "<|vision_end|>"
+ processor.video_start_token = "<|video_start|>"
+ processor.video_end_token = "<|video_end|>"
+ processor.image_token = "<|image_pad|>"
+ processor.video_token = "<|video_pad|>"
+
+ assert processor._normalize_media_wrappers(
+ "<|vision_start|><|image_pad|><|vision_end|>Describe."
+ ) == "<|vision_start|><|image_pad|><|vision_end|>\nDescribe."
+ assert processor._normalize_media_wrappers(
+ "<|video_start|><|video_pad|><|video_end|>Describe."
+ ) == (
+ "<|video_start|><|vision_start|><|video_pad|>"
+ "<|vision_end|><|video_end|>Describe."
+ )
+
+
+def test_tiny_config_and_mxfp4_mla_sanitization():
+ from mlx_vlm.models import bailing_moe_v3_vl
+
+ config = _tiny_config(layer_plan=("mla",))
+ config.text_config.qk_nope_head_dim = 32
+ config.text_config.v_head_dim = 32
+ language = bailing_moe_v3_vl.LanguageModel(config.text_config, config)
+ fused = mx.random.uniform(shape=(128, 32))
+ packed, scales = mx.quantize(fused, group_size=32, bits=4, mode="mxfp4")
+ prefix = "language_model.model.layers.0.attention"
+ sanitized = language.sanitize(
+ {
+ f"{prefix}.kv_b_proj.weight": packed,
+ f"{prefix}.kv_b_proj.scales": scales,
+ }
+ )
+
+ assert config.text_config.layer_plan == ("mla",)
+ assert config.text_config.rope_scaling["mrope_section"] == [2, 1, 1]
+ assert f"{prefix}.embed_q.weight" in sanitized
+ assert f"{prefix}.unembed_out.weight" in sanitized
+ assert f"{prefix}.embed_q.biases" not in sanitized
+
+
+def test_mixed_fp4_fp8_quantization_metadata_is_preserved(tmp_path):
+ from mlx_vlm.utils import load_config
+
+ experts = {
+ "group_size": 32,
+ "bits": 4,
+ "mode": "mxfp4",
+ }
+ fp8_attention = {
+ "group_size": 64,
+ "bits": 8,
+ "mode": "mxfp8",
+ }
+ quantization = {
+ "group_size": 64,
+ "bits": 8,
+ "mode": "mxfp8",
+ "language_model.model.layers.2.mlp.switch_mlp.gate_proj": experts,
+ "language_model.model.layers.2.attention.dense": fp8_attention,
+ }
+ (tmp_path / "config.json").write_text(
+ json.dumps(
+ {
+ "model_type": "bailing_moe_v3_vl",
+ "quantization_config": quantization,
+ }
+ )
+ )
+
+ config = load_config(tmp_path)
+
+ assert config["quantization"] == quantization
+ assert config["quantization_config"] == quantization
+ assert (
+ config["quantization"][
+ "language_model.model.layers.2.mlp.switch_mlp.gate_proj"
+ ]["mode"]
+ == "mxfp4"
+ )
+ assert (
+ config["quantization"]["language_model.model.layers.2.attention.dense"][
+ "mode"
+ ]
+ == "mxfp8"
+ )
+
+
+def test_legacy_ling_fp8_metadata_gets_only_explicit_expert_fp4_overrides(tmp_path):
+ from mlx_vlm.utils import load_config
+
+ (tmp_path / "config.json").write_text(
+ json.dumps(
+ {
+ "model_type": "bailing_moe_v3_vl",
+ "text_config": {
+ "first_k_dense_replace": 2,
+ "num_hidden_layers": 4,
+ },
+ "quantization_config": {
+ "quant_method": "fp8",
+ "routed_experts_quant_method": "mxfp4",
+ "routed_experts_group_size": 16,
+ "language_model.model.layers.3.attention.dense": {
+ "group_size": 32,
+ "bits": 8,
+ "mode": "mxfp8",
+ },
+ },
+ }
+ )
+ )
+
+ config = load_config(tmp_path)
+
+ assert config["quantization"]["bits"] == 8
+ assert config["quantization"][
+ "language_model.model.layers.2.mlp.switch_mlp.gate_proj"
+ ] == {"group_size": 16, "bits": 4, "mode": "mxfp4"}
+ assert config["quantization"][
+ "language_model.model.layers.3.attention.dense"
+ ] == {"group_size": 32, "bits": 8, "mode": "mxfp8"}
+
+
+def test_ling_vlm_sanitize_converts_fp8_and_mxfp4_sidecars():
+ from mlx_vlm.models import bailing_moe_v3_vl
+
+ config = _tiny_config(layer_plan=("kda", "kda", "mla"))
+ language = bailing_moe_v3_vl.LanguageModel(config.text_config, config)
+ fp8_weight = "model.layers.0.attention.q_proj.weight"
+ expert_weight = "model.layers.2.mlp.experts"
+ raw_weights = {
+ f"language_model.{fp8_weight}": mx.full((128, 128), 0x38, dtype=mx.uint8),
+ f"language_model.{fp8_weight}_scale_inv": mx.ones(
+ (1, 1), dtype=mx.float32
+ ),
+ }
+ for expert in range(config.text_config.num_experts):
+ key = f"{expert_weight}.{expert}.gate_proj.weight"
+ raw_weights[f"language_model.{key}"] = mx.zeros((1, 32), dtype=mx.int8)
+ raw_weights[f"language_model.{key}_scale_inv"] = mx.full(
+ (1, 2), 127, dtype=mx.uint8
+ )
+
+ converted = language.sanitize(raw_weights)
+ mxfp4_weight = "model.layers.2.mlp.switch_mlp.gate_proj.weight"
+
+ assert f"language_model.{fp8_weight}_scale_inv" not in converted
+ assert f"language_model.{mxfp4_weight}_scale_inv" not in converted
+ assert converted[f"language_model.{fp8_weight}"].dtype == mx.uint32
+ assert f"language_model.{fp8_weight[:-len('weight')]}scales" in converted
+ assert f"language_model.{fp8_weight[:-len('weight')]}biases" in converted
+ assert converted[f"language_model.{mxfp4_weight}"].dtype == mx.uint32
+ assert f"language_model.{mxfp4_weight[:-len('weight')]}scales" in converted
+
+
+def test_ling_fp8_and_mxfp4_checkpoint_loads_strictly(tmp_path):
+ import mlx.nn as nn
+ from mlx.utils import tree_flatten
+ from mlx_vlm.models import bailing_moe_v3_vl
+ from mlx_vlm.utils import load_model
+
+ config = _tiny_config(layer_plan=("kda", "kda", "mla"))
+ text = config.text_config
+ text.hidden_size = 128
+ text.intermediate_size = 128
+ text.num_attention_heads = 2
+ text.num_key_value_heads = 2
+ text.head_dim = 64
+ text.moe_intermediate_size = 64
+ text.moe_shared_expert_intermediate_size = 64
+ source = bailing_moe_v3_vl.Model(config)
+ weights = dict(tree_flatten(source.parameters()))
+
+ fp8_weight = "language_model.model.layers.0.attention.q_proj.weight"
+ weights[fp8_weight] = mx.to_fp8(weights[fp8_weight].astype(mx.float32))
+ weights[f"{fp8_weight}_scale_inv"] = mx.ones((1, 1), dtype=mx.float32)
+
+ expert_base = "language_model.model.layers.2.mlp"
+ for projection in ("gate_proj", "up_proj", "down_proj"):
+ runtime_key = f"{expert_base}.switch_mlp.{projection}.weight"
+ expert_weights = weights.pop(runtime_key)
+ for expert, expert_weight in enumerate(expert_weights):
+ packed, scales = mx.quantize(
+ expert_weight,
+ group_size=32,
+ bits=4,
+ mode="mxfp4",
+ )
+ checkpoint_key = f"{expert_base}.experts.{expert}.{projection}.weight"
+ weights[checkpoint_key] = packed.view(mx.int8)
+ weights[f"{checkpoint_key}_scale_inv"] = scales
+
+ serialized_config = asdict(config)
+ serialized_config.pop("quantization", None)
+ serialized_config["quantization_config"] = {
+ "quant_method": "fp8",
+ "fmt": "e4m3",
+ "weight_block_size": [128, 128],
+ "routed_experts_quant_method": "mxfp4",
+ "routed_experts_group_size": 32,
+ }
+ mx.save_safetensors(str(tmp_path / "model.safetensors"), weights)
+ (tmp_path / "config.json").write_text(json.dumps(serialized_config))
+
+ loaded = load_model(tmp_path, strict=True)
+
+ assert isinstance(
+ loaded.language_model.model.layers[0].attention.q_proj,
+ nn.QuantizedLinear,
+ )
+ for projection in ("gate_proj", "up_proj", "down_proj"):
+ module = getattr(
+ loaded.language_model.model.layers[2].mlp.switch_mlp,
+ projection,
+ )
+ assert module.mode == "mxfp4"
+
+
+def test_tiny_hybrid_kda_mla_forward_and_cache_schedule():
+ from mlx_vlm.models import bailing_moe_v3_vl
+
+ config = _tiny_config()
+ language = bailing_moe_v3_vl.LanguageModel(config.text_config, config)
+ cache = language.make_cache()
+ logits = language(mx.array([[1, 2]]), cache=cache).logits
+ mx.eval(logits)
+
+ assert config.text_config.layer_plan == ("kda", "mla")
+ assert [type(item).__name__ for item in cache] == ["ArraysCache", "KVCache"]
+ assert logits.shape == (1, 2, 64)
+
+
+def test_ling_vl_warmup_compiles_prefill_and_decode_paths():
+ from omlx.engine.vlm import _warmup_bailing_moe_v3_vl
+
+ class FakeAdapter:
+ model_type = "bailing_moe_v3_vl"
+
+ def __init__(self):
+ self.calls = []
+ self.cache = object()
+
+ def make_cache(self):
+ return self.cache
+
+ def __call__(self, tokens, cache):
+ self.calls.append((tokens.shape, cache))
+ return mx.zeros((*tokens.shape, 4))
+
+ adapter = FakeAdapter()
+
+ assert _warmup_bailing_moe_v3_vl(adapter, token_id=7) is True
+ assert adapter.calls == [((1, 8), adapter.cache), ((1, 1), adapter.cache)]
+
+
+def test_ling_vl_warmup_skips_other_model_types():
+ from omlx.engine.vlm import _warmup_bailing_moe_v3_vl
+
+ model = SimpleNamespace(model_type="qwen3_5")
+
+ assert _warmup_bailing_moe_v3_vl(model) is False
+
+
+@pytest.mark.parametrize(
+ ("model_type", "architectures"),
+ [
+ ("bailing_moe_v3_vl", []),
+ ("unknown", ["BailingMoeV3VLForConditionalGeneration"]),
+ ],
+)
+def test_ling_vl_discovery(model_type, architectures, tmp_path):
+ config = {
+ "model_type": model_type,
+ "architectures": architectures,
+ }
+ if model_type == "bailing_moe_v3_vl":
+ config["vision_config"] = {"model_type": "qwen3_moe_vit"}
+ (tmp_path / "config.json").write_text(
+ json.dumps(config)
+ )
+ assert detect_model_type(tmp_path) == "vlm"
diff --git a/tests/test_mlx_vlm_inkling_compat.py b/tests/test_mlx_vlm_inkling_compat.py
index 6b35121836..fd4412a926 100644
--- a/tests/test_mlx_vlm_inkling_compat.py
+++ b/tests/test_mlx_vlm_inkling_compat.py
@@ -10,6 +10,8 @@
from __future__ import annotations
import json
+import subprocess
+import sys
import pytest
@@ -63,6 +65,71 @@ def test_vendor_module_resolves(applied):
assert arch is module
+def test_vendor_registration_replaces_preimported_native_module():
+ result = subprocess.run(
+ [
+ sys.executable,
+ "-c",
+ """
+import importlib
+from pathlib import Path
+
+native = importlib.import_module("mlx_vlm.models.inkling")
+from omlx.patches.mlx_vlm_inkling_compat import (
+ _VENDOR_MLX_VLM,
+ apply_mlx_vlm_inkling_compat_patch,
+)
+
+assert apply_mlx_vlm_inkling_compat_patch()
+vendor = importlib.import_module("mlx_vlm.models.inkling")
+assert vendor is not native
+assert Path(vendor.__file__).is_relative_to(_VENDOR_MLX_VLM)
+config = importlib.import_module("mlx_vlm.models.inkling.config")
+assert callable(config.build_qkvr_fusion_policy)
+assert not apply_mlx_vlm_inkling_compat_patch()
+assert importlib.import_module("mlx_vlm.models.inkling") is vendor
+""",
+ ],
+ capture_output=True,
+ text=True,
+ timeout=30,
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
+
+
+@pytest.mark.parametrize("tokens", [1, 4])
+def test_route_kernel_accepts_constant_address_space(applied, monkeypatch, tokens):
+ import importlib
+
+ from omlx.patches.mlx_vlm_inkling_compat import _patch_route_kernel
+
+ language = importlib.import_module("mlx_vlm.models.inkling.language")
+ source = language._ROUTE_SRC
+ declaration = "const device T* lg = logits + (size_t)n * (R + SH);"
+ if declaration not in source:
+ source = source.replace(
+ "float ws = wscale[0];", declaration + "\n float ws = wscale[0];"
+ )
+ monkeypatch.setattr(language, "_ROUTE_SRC", source)
+ monkeypatch.setattr(language, "_route_kernel", language._route_kernel)
+ _patch_route_kernel()
+ logits = mx.broadcast_to(mx.array([[1.0, 2.0, 3.0, 4.0, 0.0]]), (tokens, 5))
+ indices, weights, shared = language._route_kernel(
+ inputs=[logits, mx.zeros((4,)), mx.array([1.0])],
+ template=[("T", mx.float32), ("N", tokens), ("R", 4), ("SH", 1), ("K", 2), ("I", 16)],
+ grid=(32, tokens, 1),
+ threadgroup=(32, 1, 1),
+ output_shapes=[(tokens, 2), (tokens, 2), (tokens, 16)],
+ output_dtypes=[mx.uint32, mx.float32, mx.float32],
+ )
+ mx.eval(indices, weights, shared)
+ assert indices.tolist() == [[3, 2]] * tokens
+ selected = mx.sigmoid(mx.array([4.0, 3.0, 0.0]))
+ expected = selected / mx.sum(selected)
+ assert mx.allclose(weights, mx.broadcast_to(expected[:2], (tokens, 2))).item()
+ assert mx.allclose(shared, mx.full((tokens, 16), expected[2])).item()
+
+
def _get_model_and_args(vlm_utils, model_type):
config = {"model_type": model_type}
result = vlm_utils.get_model_and_args(config)
diff --git a/tests/test_mlx_vlm_muse_glimmer_compat.py b/tests/test_mlx_vlm_muse_glimmer_compat.py
index 5dabd19e27..34d63ade91 100644
--- a/tests/test_mlx_vlm_muse_glimmer_compat.py
+++ b/tests/test_mlx_vlm_muse_glimmer_compat.py
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
"""Muse Glimmer mlx-vlm compatibility patch tests.
-Covers the vendor install/discovery surface (inkling test pattern), the
+Covers native model discovery, the
model behaviors oMLX depends on (mixed sliding/full cache, NoPE layers,
logit tail, vision-cache encode_image contract), the PR #1839 quantized
embedding-norm preservation, and the real checkpoint's chat template
@@ -81,7 +81,7 @@ def _tiny_config():
)
-def test_vendor_module_resolves(applied):
+def test_native_module_resolves(applied):
import importlib
import mlx_vlm.utils as vlm_utils
@@ -89,6 +89,7 @@ def test_vendor_module_resolves(applied):
module = importlib.import_module("mlx_vlm.models.muse_glimmer")
assert hasattr(module, "Model")
assert hasattr(module, "LanguageModel")
+ assert "omlx/patches" not in str(module.__file__)
result = vlm_utils.get_model_and_args({"model_type": "muse_glimmer"})
assert result[0] is module
diff --git a/tests/test_mlx_vlm_qwen4_exp.py b/tests/test_mlx_vlm_qwen4_exp.py
new file mode 100644
index 0000000000..3fe7781231
--- /dev/null
+++ b/tests/test_mlx_vlm_qwen4_exp.py
@@ -0,0 +1,21 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Compatibility contract for upstream Qwen3.8-Flash-Next support."""
+
+from __future__ import annotations
+
+import importlib
+
+
+def test_qwen4_exp_upstream_module_exports():
+ module = importlib.import_module("mlx_vlm.models.qwen4_exp")
+
+ for name in (
+ "LanguageModel",
+ "Model",
+ "ModelConfig",
+ "Qwen3VLProcessor",
+ "TextConfig",
+ "VisionConfig",
+ "VisionModel",
+ ):
+ assert getattr(module, name) is not None
diff --git a/tests/test_mlx_vlm_qwen4_exp_compat.py b/tests/test_mlx_vlm_qwen4_exp_compat.py
index 52522103fe..e6bbfa1923 100644
--- a/tests/test_mlx_vlm_qwen4_exp_compat.py
+++ b/tests/test_mlx_vlm_qwen4_exp_compat.py
@@ -1824,7 +1824,7 @@ def test_disk_backed_affine_ple_supports_all_oq_bits(tmp_path, bits):
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)
+ assert embedding._shard_specs[0][3:] == (bits, 32, "affine")
embedding.close()
diff --git a/tests/test_mlx_vlm_unlimited_ocr_compat.py b/tests/test_mlx_vlm_unlimited_ocr_compat.py
index e4f23542e6..7a4d4379f9 100644
--- a/tests/test_mlx_vlm_unlimited_ocr_compat.py
+++ b/tests/test_mlx_vlm_unlimited_ocr_compat.py
@@ -20,7 +20,6 @@ def test_unlimited_ocr_compat_uses_upstream_module():
assert Path(unlimited_ocr.__file__).parent == upstream
assert hasattr(unlimited_ocr, "Model")
assert hasattr(unlimited_ocr, "ModelConfig")
- assert hasattr(unlimited_ocr, "RingSlidingKVCache")
def test_unlimited_ocr_model_remapping_resolves_module():
diff --git a/tests/test_mtp_depth_controller.py b/tests/test_mtp_depth_controller.py
index dcbca0d1f5..92422dd7f5 100644
--- a/tests/test_mtp_depth_controller.py
+++ b/tests/test_mtp_depth_controller.py
@@ -490,7 +490,6 @@ def test_std_tax_probe_measures_and_smooths(monkeypatch):
_arm_std_tax_probe,
_record_std_tax_sample,
)
-
# The process-wide prefill tracker may hold another test's prefill.
monkeypatch.setattr(batch_generator, "_prefill_activity_recent", lambda: False)
model = SimpleNamespace()
diff --git a/tests/test_mtp_prompt_priming.py b/tests/test_mtp_prompt_priming.py
index 94666d79d0..19a30e6152 100644
--- a/tests/test_mtp_prompt_priming.py
+++ b/tests/test_mtp_prompt_priming.py
@@ -8,6 +8,7 @@
wiring is exercised by the real-model smoke test.
"""
+import contextlib
import threading
from collections import OrderedDict
from types import SimpleNamespace
@@ -562,10 +563,8 @@ def test_batch_forward_skipped(self, model):
cache = _make_cache(model)
toks = _tokens(12).reshape(2, 6)
# Batched cache shapes differ; just assert no ctx is created.
- try:
+ with contextlib.suppress(Exception):
model(toks, cache=cache)
- except Exception:
- pass
assert prompt_priming.prime_ctx_stats(model) is None
def test_batch_forward_drops_pending_ctx(self, model):
@@ -617,19 +616,19 @@ def test_ctx_lives_on_host_not_cache(self, model):
getattr(c, "_omlx_mtp_prime_ctx", None) is None for c in cache
)
- def test_interleaved_request_restarts_slot(self, model):
- """A second request's prefill on the same model can never continue
- the first request's timeline: its offsets restart at zero, which
- breaks contiguity and restarts the slot."""
+ def test_latest_prefill_owns_the_model_context(self, model):
cache_a = _make_cache(model)
_chunked_prefill(model, cache_a, _tokens(10, seed=23), [10])
assert prompt_priming.prime_ctx_stats(model) == 9
cache_b = _make_cache(model)
_chunked_prefill(model, cache_b, _tokens(6, seed=24), [6])
assert prompt_priming.prime_ctx_stats(model) == 5
- # Request A activating now must not see B's history.
- model(_tokens(1, seed=25)[None, :], cache=cache_a, return_hidden=True)
- assert prompt_priming.take_primed(model, cache_a, _tokens(1, seed=25)) is None
+
+ main_b = _tokens(1, seed=26)
+ model(main_b[None, :], cache=cache_b, return_hidden=True)
+ primed_b = prompt_priming.take_primed(model, cache_b, main_b)
+ assert primed_b is not None
+ assert primed_b[1] == 6
def test_ctx_survives_kv_entry_replacement(self, model):
"""Simulate the TurboQuant convert: swap every KVCache entry for a
@@ -725,6 +724,29 @@ def test_batch_cache_prefill_primes_end_to_end(self, strict_model):
assert mx.allclose(v, rv, rtol=1e-4, atol=1e-4)
+class TestBatchGeneratorCacheOwnership:
+ def test_prompt_batch_keeps_ctx_through_merge_and_extend(self, model):
+ from mlx_lm.generate import PromptProcessingBatch
+
+ from omlx.patches.mlx_lm_mtp import batch_generator
+
+ assert batch_generator.apply()
+
+ source_cache = _make_cache(model)
+ _chunked_prefill(model, source_cache, _tokens(6, seed=36), [6])
+
+ donor = PromptProcessingBatch(
+ model=model,
+ uids=[0],
+ caches=[source_cache],
+ )
+ assert prompt_priming.prime_ctx_stats(model) == 5
+
+ target = PromptProcessingBatch.empty(model, lambda x: mx.argmax(x, axis=-1))
+ target.extend(donor)
+ assert prompt_priming.prime_ctx_stats(model) == 5
+
+
class TestHookFallthrough:
"""``mtp_take_primed`` is registered on the class but answered by only
some builds: the DeepSeek-V4 patch registers it unconditionally and
diff --git a/tests/test_mtp_xtc_sampling.py b/tests/test_mtp_xtc_sampling.py
index dadc46a9a1..ca56809454 100644
--- a/tests/test_mtp_xtc_sampling.py
+++ b/tests/test_mtp_xtc_sampling.py
@@ -42,14 +42,12 @@ def scheduler_probe(monkeypatch):
scheduler.batch_generator = None
observed = []
original = mtp._is_mtp_eligible
- original_batch = mtp._is_mtp_batch_eligible
def observe(batch):
- observed.append((list(batch.uids), original(batch), original_batch(batch)))
+ observed.append((list(batch.uids), original(batch)))
return False
monkeypatch.setattr(mtp, "_is_mtp_eligible", observe)
- monkeypatch.setattr(mtp, "_is_mtp_batch_eligible", lambda batch: False)
try:
yield scheduler, observed
finally:
@@ -92,8 +90,8 @@ def test_reused_generator_follows_request_sampler(scheduler_probe, first, second
else:
pytest.fail("request did not finish")
assert observed
- assert all(rows == [uid] for rows, _, _ in observed)
- assert all(single == (probability == 0.0) for _, single, _ in observed)
+ assert all(rows == [uid] for rows, _ in observed)
+ assert all(single == (probability == 0.0) for _, single in observed)
@pytest.mark.parametrize("xtc_first", [False, True])
@@ -114,13 +112,13 @@ def test_late_join_mixed_batch_and_filter(scheduler_probe, xtc_first):
batch = generator._generation_batch
assert batch.uids == [first, second]
generator.next()
- assert observed[-1] == ([first, second], False, False)
+ assert observed[-1] == ([first, second], False)
assert "XTC" in mtp._ineligibility_reason(batch)
# Removing the XTC row must not leave a sticky generator-wide veto.
remaining = second if xtc_first else first
batch.filter([batch.uids.index(remaining)])
generator.next()
- assert observed[-1] == ([remaining], True, False)
+ assert observed[-1] == ([remaining], True)
def test_greedy_ignores_xtc(scheduler_probe):
@@ -130,7 +128,7 @@ def test_greedy_ignores_xtc(scheduler_probe):
scheduler.batch_generator.next()
if observed:
break
- assert observed[-1] == ([uid], True, False)
+ assert observed[-1] == ([uid], True)
@pytest.mark.parametrize("override", [None, 0.0, 1.0])
diff --git a/tests/test_nemotron_omni.py b/tests/test_nemotron_omni.py
new file mode 100644
index 0000000000..508153fa7a
--- /dev/null
+++ b/tests/test_nemotron_omni.py
@@ -0,0 +1,1513 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Small native Nemotron contracts; no downloaded model weights."""
+
+from __future__ import annotations
+
+import json
+from copy import copy, deepcopy
+from types import SimpleNamespace
+
+import mlx.core as mx
+import numpy as np
+import pytest
+
+from omlx.patches.mlx_lm_mtp.uniform import sample_uniform_prefix
+from omlx.patches.nemotron_omni import prepare_nemotron_prompt
+
+
+def tiny_nemotron_config():
+ return {
+ "model_type": "nemotron_h_omni",
+ "img_context_token_id": 18,
+ "projector_hidden_size": 32,
+ "vit_hidden_size": 16,
+ "ps_version": "v2",
+ "video_pruning_rate": 0.7,
+ "llm_config": {
+ "model_type": "nemotron_h",
+ "vocab_size": 128,
+ "hidden_size": 32,
+ "intermediate_size": 32,
+ "max_position_embeddings": 2048,
+ "num_attention_heads": 4,
+ "num_key_value_heads": 2,
+ "attention_bias": False,
+ "head_dim": 8,
+ "mamba_num_heads": 4,
+ "mamba_head_dim": 16,
+ "mamba_proj_bias": False,
+ "ssm_state_size": 32,
+ "conv_kernel": 4,
+ "n_groups": 1,
+ "use_conv_bias": True,
+ "mlp_bias": False,
+ "layer_norm_epsilon": 1e-5,
+ "use_bias": False,
+ "layers_block_type": ["mamba", "moe", "attention"],
+ "time_step_limit": [0.0, float("inf")],
+ "num_nextn_predict_layers": 1,
+ "mtp_layers_block_type": ["attention", "moe"],
+ "moe_latent_size": 32,
+ "moe_intermediate_size": 32,
+ "moe_shared_expert_intermediate_size": 32,
+ "n_routed_experts": 2,
+ "n_shared_experts": 1,
+ "num_experts_per_tok": 1,
+ "n_group": 1,
+ "topk_group": 1,
+ "norm_topk_prob": True,
+ "routed_scaling_factor": 1.0,
+ },
+ "vision_config": {
+ "hidden_size": 16,
+ "intermediate_size": 32,
+ "num_hidden_layers": 1,
+ "num_attention_heads": 4,
+ "image_size": 32,
+ "patch_size": 16,
+ "max_resolution": 64,
+ "video_temporal_patch_size": 2,
+ "args": {
+ "teachers": [{"name": 0}, {"name": 1}, {"name": 2}],
+ "cls_token_per_teacher": True,
+ "register_multiple": 10,
+ },
+ },
+ }
+
+
+@pytest.fixture
+def native_target():
+ from mlx_vlm.models.nemotron_h_nano_omni import Model, ModelConfig
+
+ mx.random.seed(71)
+ model = Model(ModelConfig.from_dict(tiny_nemotron_config()))
+ model.eval()
+ return model
+
+
+@pytest.mark.parametrize(
+ "limits,stop_first,replace",
+ [
+ ((1, 1), False, False),
+ ((2, 2), False, False),
+ ((3, 9), False, False),
+ ((9, 9), False, False),
+ ((9, 9), True, False),
+ ((9, 9), False, True),
+ ],
+)
+def test_native_mtp_batch_generator_serves_two_unequal_prompts(
+ native_target, monkeypatch, limits, stop_first, replace
+):
+ from mlx_lm.generate import BatchGenerator, StopSequences
+ from mlx_vlm.speculative.drafters.nemotron_h_mtp import Model, ModelConfig
+
+ from omlx import scheduler
+ from omlx.models.vlm import VLMModelAdapter
+ from omlx.patches.mlx_lm_mtp import batch_generator
+
+ assert batch_generator.apply()
+ assert scheduler.BatchGenerator is BatchGenerator
+ head = Model(ModelConfig(text_config=tiny_nemotron_config()["llm_config"]))
+ adapter = VLMModelAdapter(native_target)
+ adapter.enable_nemotron_mtp(head, depth=3)
+ verified_batches = []
+ verify = adapter.speculative_verify_logits
+
+ def observed_verify(inputs, cache, sampler):
+ verified_batches.append(inputs.shape)
+ return verify(inputs, cache, sampler)
+
+ monkeypatch.setattr(adapter, "speculative_verify_logits", observed_verify)
+ generator = BatchGenerator(
+ adapter,
+ max_tokens=9,
+ sampler=lambda lp: mx.argmax(lp, axis=-1),
+ prefill_step_size=2,
+ completion_batch_size=2,
+ )
+ prompts = [[1, 2, 3], [5, 6, 7, 8, 9]]
+ stop = int(
+ mx.argmax(
+ native_target.language_model(mx.array([prompts[0]])).logits[:, -1]
+ ).item()
+ )
+ uids = generator.insert(
+ prompts,
+ max_tokens=list(limits),
+ stop_sequences=(
+ [StopSequences([[stop]]), StopSequences()] if stop_first else None
+ ),
+ )
+ prompt_by_uid = dict(zip(uids, prompts))
+ limit_by_uid = dict(zip(uids, limits))
+ if stop_first:
+ limit_by_uid[uids[0]] = 1
+ outputs = {uid: [] for uid in uids}
+ terminal = {}
+ cancelled = set()
+ try:
+ for _ in range(40):
+ responses = generator.next_generated()
+ if not responses:
+ break
+ for response in responses:
+ assert response.uid not in cancelled
+ outputs[response.uid].append(response.token)
+ if response.finish_reason:
+ terminal[response.uid] = response
+ if replace and len(outputs[uids[0]]) >= 2:
+ generator.remove([uids[0]])
+ cancelled.add(uids[0])
+ joined_prompt = [11, 12, 13, 14]
+ joined_uid = generator.insert([joined_prompt])[0]
+ prompt_by_uid[joined_uid] = joined_prompt
+ limit_by_uid[joined_uid] = 9
+ outputs[joined_uid] = []
+ replace = False
+ finally:
+ generator.close()
+ assert set(terminal) == set(prompt_by_uid) - cancelled
+ if min(limits) >= 9 and not stop_first:
+ assert any(batch == 2 and width == 4 for batch, width in verified_batches)
+ for uid in terminal:
+ prompt = prompt_by_uid[uid]
+ assert len(outputs[uid]) == limit_by_uid[uid]
+ baseline = native_target.language_model.make_cache()
+ expected = []
+ ids = mx.array([prompt])
+ for _ in range(limit_by_uid[uid]):
+ logits = native_target.language_model(ids, cache=baseline).logits[:, -1]
+ token = int(mx.argmax(logits, axis=-1).item())
+ expected.append(token)
+ ids = mx.array([[token]])
+ assert outputs[uid] == expected
+ native_target.language_model(ids, cache=baseline)
+ probe = mx.array([[21]])
+ actual = native_target.language_model(
+ probe, cache=terminal[uid].prompt_cache
+ ).logits
+ expected_logits = native_target.language_model(probe, cache=baseline).logits
+ np.testing.assert_allclose(
+ np.array(actual), np.array(expected_logits), atol=1e-5, rtol=1e-5
+ )
+
+
+@pytest.mark.parametrize("blocker", ["grammar", "xtc"])
+@pytest.mark.parametrize("media", ["text", "image", "video"])
+@pytest.mark.parametrize("active_rows", [1, 2])
+@pytest.mark.parametrize("joined_prompt", [[11], [11, 12, 13]])
+def test_native_mtp_ineligible_late_join_preserves_live_cache(
+ native_target, monkeypatch, blocker, media, active_rows, joined_prompt
+):
+ from mlx_lm.generate import BatchGenerator
+ from mlx_vlm.speculative.drafters.nemotron_h_mtp import Model, ModelConfig
+
+ from omlx import scheduler
+ from omlx.api.grammar import GrammarConstraintProcessor
+ from omlx.models.vlm import VLMModelAdapter
+ from omlx.patches.mlx_lm_mtp import batch_generator
+
+ class FixedTokenGrammar(GrammarConstraintProcessor):
+ def __init__(self):
+ self._pending = False
+ self.accepted = []
+
+ def __call__(self, tokens, logits):
+ self._pending = True
+ return mx.where(mx.arange(logits.shape[-1]) == 12, logits, -mx.inf)
+
+ def accept_token(self, token):
+ self._pending = False
+ self.accepted.append(token)
+
+ class XTCMarkedSampler:
+ """Deterministic sampling with XTC's MTP-ineligibility metadata."""
+
+ temp = 1.0
+ xtc_probability = 0.5
+
+ def __call__(self, logprobs):
+ return mx.argmax(logprobs, axis=-1)
+
+ assert batch_generator.apply()
+ assert scheduler.BatchGenerator is BatchGenerator
+ adapter = VLMModelAdapter(native_target)
+ adapter.enable_nemotron_mtp(
+ Model(ModelConfig(text_config=tiny_nemotron_config()["llm_config"])), depth=3
+ )
+ ids = [1, 2, 3]
+ embeddings = None
+ if media != "text":
+ ids = [1, 18, 3] if media == "image" else [1, 18, 18, 18, 3]
+ kwargs = (
+ {"pixel_values": mx.ones((1, 3, 32, 32))}
+ if media == "image"
+ else {"pixel_values_videos": mx.ones((6, 3, 32, 32))}
+ )
+ prepared = prepare_nemotron_prompt(native_target, mx.array([ids]), **kwargs)
+ ids = prepared.token_ids[0].tolist()
+ embeddings = prepared.inputs_embeds
+ adapter.set_pending_embeddings(embeddings)
+
+ verified_rows = []
+ verify = adapter.speculative_verify_logits
+
+ def observed_verify(inputs, cache, sampler):
+ verified_rows.append(inputs.shape[0])
+ return verify(inputs, cache, sampler)
+
+ monkeypatch.setattr(adapter, "speculative_verify_logits", observed_verify)
+ rebuilds = []
+ rebuild = batch_generator._rebuild_singleton_cache
+
+ def observed_rebuild(model):
+ rebuilds.append(model)
+ return rebuild(model)
+
+ monkeypatch.setattr(batch_generator, "_rebuild_singleton_cache", observed_rebuild)
+ generator = BatchGenerator(
+ adapter,
+ max_tokens=24,
+ prefill_step_size=2,
+ prefill_batch_size=1,
+ completion_batch_size=2,
+ sampler=lambda lp: mx.argmax(lp, axis=-1),
+ )
+ uid = generator.insert([ids])[0]
+ prompts = {uid: ids}
+ outputs = {uid: []}
+ terminal = {}
+ grammar = FixedTokenGrammar()
+ joined = None
+
+ def step():
+ responses = generator.next_generated()
+ for response in responses:
+ if response.uid == joined:
+ assert set(prompts) - {joined} <= set(terminal)
+ outputs[response.uid].append(response.token)
+ if response.finish_reason:
+ assert response.finish_reason == "length"
+ terminal[response.uid] = response.prompt_cache
+ return responses
+
+ try:
+ for _ in range(20):
+ step()
+ if batch_generator._generation_batch_has_active_mtp(
+ generator._generation_batch
+ ):
+ break
+ assert batch_generator._generation_batch_has_active_mtp(
+ generator._generation_batch
+ )
+ if active_rows == 2:
+ peer_prompt = [5, 6, 7, 8, 9]
+ peer = generator.insert([peer_prompt])[0]
+ prompts[peer] = peer_prompt
+ outputs[peer] = []
+ for _ in range(20):
+ step()
+ if 2 in verified_rows:
+ break
+ assert 2 in verified_rows
+ assert not terminal
+ joined = generator.insert(
+ [joined_prompt],
+ logits_processors=[[grammar]] if blocker == "grammar" else None,
+ samplers=[XTCMarkedSampler()] if blocker == "xtc" else None,
+ )[0]
+ prompts[joined] = joined_prompt
+ outputs[joined] = []
+ for _ in range(100):
+ if not step():
+ break
+ finally:
+ generator.close()
+
+ assert set(terminal) == set(prompts)
+ assert not rebuilds
+ assert generator.completion_batch_size == 2
+ if blocker == "grammar":
+ assert grammar.accepted == outputs[joined] == [12] * 24
+ for row_uid, prompt in prompts.items():
+ cache = native_target.language_model.make_cache()
+ kwargs = {"inputs_embeds": embeddings} if row_uid == uid else {}
+ logits = native_target.language_model(
+ mx.array([prompt]), cache=cache, **kwargs
+ ).logits[:, -1]
+ expected = []
+ for _ in range(24):
+ token = (
+ 12
+ if row_uid == joined and blocker == "grammar"
+ else int(mx.argmax(logits, axis=-1).item())
+ )
+ expected.append(token)
+ logits = native_target.language_model(
+ mx.array([[token]]), cache=cache
+ ).logits[:, -1]
+ assert outputs[row_uid] == expected
+ probe = mx.array([[21]])
+ np.testing.assert_allclose(
+ np.array(
+ native_target.language_model(probe, cache=terminal[row_uid]).logits
+ ),
+ np.array(native_target.language_model(probe, cache=cache).logits),
+ atol=1e-5,
+ rtol=1e-5,
+ )
+
+
+def test_cancelling_ineligible_native_late_join_unblocks_compatible_peer(
+ native_target, monkeypatch
+):
+ from mlx_lm.generate import BatchGenerator
+ from mlx_vlm.speculative.drafters.nemotron_h_mtp import Model, ModelConfig
+
+ from omlx import scheduler
+ from omlx.models.vlm import VLMModelAdapter
+ from omlx.patches.mlx_lm_mtp import batch_generator
+ from omlx.utils.sampling import make_sampler
+
+ assert batch_generator.apply()
+ assert scheduler.BatchGenerator is BatchGenerator
+ adapter = VLMModelAdapter(native_target)
+ adapter.enable_nemotron_mtp(
+ Model(ModelConfig(text_config=tiny_nemotron_config()["llm_config"])), depth=3
+ )
+ verified_rows = []
+ verify = adapter.speculative_verify_logits
+
+ def observed_verify(inputs, cache, sampler):
+ verified_rows.append(inputs.shape[0])
+ return verify(inputs, cache, sampler)
+
+ monkeypatch.setattr(adapter, "speculative_verify_logits", observed_verify)
+ generator = BatchGenerator(
+ adapter,
+ max_tokens=24,
+ prefill_step_size=2,
+ prefill_batch_size=1,
+ completion_batch_size=2,
+ sampler=lambda lp: mx.argmax(lp, axis=-1),
+ )
+ host = generator.insert([[1, 2, 3]])[0]
+ try:
+ for _ in range(20):
+ generator.next_generated()
+ if batch_generator._generation_batch_has_active_mtp(
+ generator._generation_batch
+ ):
+ break
+ assert batch_generator._generation_batch_has_active_mtp(
+ generator._generation_batch
+ )
+ cancelled = generator.insert(
+ [[11]], samplers=[make_sampler(temp=1.0, xtc_probability=0.5)]
+ )[0]
+ peer = generator.insert([[5, 6, 7]])[0]
+ assert all(r.uid == host for r in generator.next_generated())
+ assert [s[0] for s in generator._unprocessed_sequences] == [cancelled, peer]
+ generator.remove([cancelled])
+ finished = set()
+ for _ in range(100):
+ responses = generator.next_generated()
+ if not responses:
+ break
+ for response in responses:
+ assert response.uid != cancelled
+ if response.finish_reason:
+ finished.add(response.uid)
+ assert finished == {host, peer}
+ assert 2 in verified_rows
+ assert generator.completion_batch_size == 2
+ finally:
+ generator.close()
+
+
+@pytest.mark.parametrize(
+ "family", ["NemotronH_Nano_Omni_Reasoning_V3", "nemotron_h_omni", "bolt"]
+)
+@pytest.mark.parametrize("calibration", ["basic", "resident", "streamed"])
+@pytest.mark.parametrize("modelopt", [False, True, "fp8_head"])
+def test_complete_tiny_quantization_strict_native_reload(
+ tmp_path, family, calibration, modelopt, monkeypatch
+):
+ from mlx.utils import tree_flatten
+ from mlx_vlm.models.nemotron_h_nano_omni import Model, ModelConfig
+ from mlx_vlm.utils import load_model
+
+ from omlx import oq
+ from omlx.oq import quantize_oq_streaming
+
+ if calibration != "basic" or modelopt:
+ from mlx_lm import tokenizer_utils
+
+ monkeypatch.setattr(tokenizer_utils, "load", lambda *_args: SimpleNamespace())
+ monkeypatch.setattr(
+ oq,
+ "_load_calibration_data",
+ lambda *_args, **_kwargs: mx.array(
+ [[1 + i % 16 for i in range(64)] for _ in range(2)]
+ ),
+ )
+
+ config = tiny_nemotron_config()
+ if family == "bolt":
+ text = config["llm_config"]
+ text["model_type"] = "nemotron_h_puzzle"
+ text["num_nextn_predict_layers"] = 0
+ text["block_configs"] = [
+ {"block_type": "mamba"},
+ {"block_type": "moe", "n_routed_experts": 3},
+ {"block_type": "attention"},
+ ]
+ else:
+ config["model_type"] = family
+ config["eos_token_id"] = 127
+ config["llm_config"].update(
+ hidden_size=128,
+ intermediate_size=128,
+ head_dim=32,
+ moe_latent_size=128,
+ moe_intermediate_size=128,
+ moe_shared_expert_intermediate_size=128,
+ )
+ model = Model(ModelConfig.from_dict(config))
+ model.eval()
+ source = tmp_path / "source"
+ source.mkdir()
+ weights = dict(tree_flatten(model.parameters()))
+ source_references = {}
+ if modelopt:
+ config["quantization_config"] = {
+ "quant_method": "modelopt_mixed",
+ "quant_algo": "MIXED_PRECISION",
+ }
+ prefix = "language_model.backbone.layers.1.mixer"
+ experts = weights.pop(prefix + ".switch_mlp.fc1.weight")
+ for expert, weight in enumerate(experts):
+ packed, scales = mx.quantize(
+ weight.astype(mx.bfloat16), group_size=16, bits=4, mode="nvfp4"
+ )
+ name = f"{prefix}.experts.{expert}.up_proj"
+ global_scale = mx.array(1 + expert, dtype=mx.float32)
+ weights[name + ".weight"] = packed.view(mx.uint8)
+ weights[name + ".weight_scale"] = scales
+ weights[name + ".weight_scale_2"] = global_scale
+ weights[name + ".input_scale"] = mx.array(1.0)
+ source_references[name + ".weight"] = (
+ mx.dequantize(
+ packed, scales, group_size=16, bits=4, mode="nvfp4"
+ ).astype(mx.float32)
+ * global_scale
+ ).astype(mx.bfloat16)
+ fp8_name = "mlp1.layers.1.weight"
+ weights[fp8_name] = mx.full(weights[fp8_name].shape, 0x38, dtype=mx.uint8)
+ weights["mlp1.layers.1.weight_scale"] = mx.array(0.01)
+ weights["mlp1.layers.1.input_scale"] = mx.array(1.0)
+ weights[prefix + ".k_scale"] = mx.array(1.0)
+ source_references[fp8_name] = mx.full(
+ weights[fp8_name].shape, 0.01, dtype=mx.bfloat16
+ )
+ (source / "config.json").write_text(json.dumps(config))
+ preserve_mtp = family == "nemotron_h_omni"
+ if preserve_mtp:
+ from mlx_vlm.speculative.drafters.nemotron_h_mtp import (
+ Model as Head,
+ )
+ from mlx_vlm.speculative.drafters.nemotron_h_mtp import (
+ ModelConfig as HeadConfig,
+ )
+
+ head = Head(HeadConfig(text_config=config["llm_config"]))
+ weights.update(
+ {"mtp." + key: value for key, value in tree_flatten(head.parameters())}
+ )
+ if modelopt:
+ name = "mtp.layers.1.mixer.switch_mlp.fc1"
+ if modelopt == "fp8_head":
+ weights[name + ".weight"] = mx.full(
+ weights[name + ".weight"].shape, 0x38, dtype=mx.uint8
+ )
+ weights[name + ".weight_scale"] = mx.array(0.01)
+ else:
+ packed, scales = mx.quantize(
+ weights[name + ".weight"].astype(mx.bfloat16),
+ group_size=16,
+ bits=4,
+ mode="nvfp4",
+ )
+ weights[name + ".weight"] = packed.view(mx.uint8)
+ weights[name + ".weight_scale"] = scales
+ weights[name + ".weight_scale_2"] = mx.array([1.0, 2.0], dtype=mx.bfloat16)
+ mx.save_safetensors(str(source / "model.safetensors"), weights)
+ if modelopt:
+ index = oq._LazyTensorIndex([source / "model.safetensors"], config=config)
+ for name, expected in source_references.items():
+ np.testing.assert_array_equal(
+ np.array(index[name].astype(mx.float32)),
+ np.array(expected.astype(mx.float32)),
+ )
+ assert not any(
+ name.endswith(
+ (".weight_scale", ".weight_scale_2", ".input_scale", ".k_scale")
+ )
+ for name in index
+ )
+ output = tmp_path / "output"
+ streamed_scores = []
+ measure_streamed = oq._measure_sensitivity_streaming
+
+ def observed_streamed_sensitivity(*args, **kwargs):
+ scores = measure_streamed(*args, **kwargs)
+ streamed_scores.append(scores)
+ return scores
+
+ monkeypatch.setattr(
+ oq, "_measure_sensitivity_streaming", observed_streamed_sensitivity
+ )
+ quantize_oq_streaming(
+ str(source),
+ str(output),
+ 4,
+ sensitivity_map_override=(
+ None if calibration == "streamed" or modelopt else {0: 1, 1: 1, 2: 1}
+ ),
+ preserve_mtp=preserve_mtp,
+ enhanced=calibration != "basic",
+ stream_calibration=calibration == "streamed",
+ imatrix_num_samples=2,
+ imatrix_seq_length=64,
+ )
+ reloaded = load_model(output, lazy=False)
+ if modelopt and calibration != "streamed":
+ assert len(streamed_scores) == 1
+ assert set(streamed_scores[0]) == {0, 1, 2}
+ assert all(
+ np.isfinite(score) and score > 0 for score in streamed_scores[0].values()
+ )
+ output_config = json.loads((output / "config.json").read_text())
+ if calibration != "basic":
+ report = json.loads((output / "oq_imatrix_report.json").read_text())
+ assert not any(
+ name.startswith("language_model.backbone.layers.")
+ for name in report["missing"]
+ ), report["missing"]
+ assert not report["mismatched"]
+ assert output_config["text_config"]["num_hidden_layers"] == 3
+ assert output_config["text_config"]["num_nextn_predict_layers"] == int(preserve_mtp)
+ assert any(
+ key.endswith(".scales") for key, _ in tree_flatten(reloaded.parameters())
+ )
+ result = reloaded.language_model(mx.array([[1, 2, 3]])).logits
+ assert result.shape == (1, 3, 128)
+ assert bool(mx.all(mx.isfinite(result)).item())
+ assert reloaded.language_model.backbone.layers[0].mixer.A_log.dtype == mx.float32
+ embeddings = reloaded.get_input_embeddings(
+ mx.array([[1, 18, 3]]), pixel_values=mx.ones((1, 3, 32, 32))
+ ).inputs_embeds
+ assert embeddings.shape == (1, 3, 128)
+ assert bool(mx.all(mx.isfinite(embeddings)).item())
+ if preserve_mtp:
+ budgeted_shapes = []
+ build_plan = oq._build_quant_plan
+
+ def observed_plan(shapes, *args, **kwargs):
+ budgeted_shapes.extend(shapes)
+ return build_plan(shapes, *args, **kwargs)
+
+ monkeypatch.setattr(oq, "_build_quant_plan", observed_plan)
+ without_head = oq.estimate_bpw_and_size(str(source), 4)
+ with_head = oq.estimate_bpw_and_size(str(source), 4, preserve_mtp=True)
+ head_bytes = sum(
+ value.nbytes
+ for shard in (output / "mtp").glob("*.safetensors")
+ for value in mx.load(str(shard)).values()
+ )
+ assert (
+ with_head["output_size_bytes"] - without_head["output_size_bytes"]
+ == head_bytes
+ )
+ assert budgeted_shapes and not any(
+ oq._is_mtp_tensor(name) for name in budgeted_shapes
+ )
+ if preserve_mtp:
+ from omlx.models.vlm import VLMModelAdapter
+ from omlx.patches.nemotron_omni_quantization import native_mtp_sidecar
+ from omlx.utils.model_loading import _checkpoint_has_mtp_weights
+
+ assert _checkpoint_has_mtp_weights(output)
+ sidecar = native_mtp_sidecar(output, output_config)
+ loaded_head = load_model(sidecar, lazy=False)
+ adapter = VLMModelAdapter(reloaded)
+ adapter.enable_nemotron_mtp(loaded_head, depth=3)
+ prompt = mx.array([[1, 2, 3]])
+ hidden = reloaded.language_model(prompt, return_hidden=True).hidden_states[-1]
+ cache, offset = adapter.prime_native_mtp(prompt, hidden, mx.array([4]))
+ assert offset == 3 and cache[0].offset == 3
+ tampered = {**output_config, "vision_final_layernorm": False}
+ with pytest.raises(ValueError, match="match its parent"):
+ native_mtp_sidecar(output, tampered)
+
+
+@pytest.mark.parametrize(
+ "family",
+ ["nemotron_h_omni", "nemotron_h_nano_omni", "NemotronH_Nano_Omni_Reasoning_V3"],
+)
+def test_native_streamed_calibration_selected_only_when_needed(family):
+ from omlx.oq import _resolve_stream_calibration
+
+ assert _resolve_stream_calibration(None, model_exceeds_ram=True, model_type=family)
+ assert not _resolve_stream_calibration(
+ None, model_exceeds_ram=False, model_type=family
+ )
+ assert not _resolve_stream_calibration(
+ False, model_exceeds_ram=True, model_type=family
+ )
+
+
+@pytest.mark.parametrize("null_overrides", [False, True])
+def test_streamed_bolt_calibration_matches_resident(tmp_path, monkeypatch, null_overrides):
+ from mlx.utils import tree_flatten
+ from mlx_vlm.models.nemotron_h_nano_omni import Model, ModelConfig
+
+ from omlx import oq
+ from omlx.model_classification import normalize_nemotron_config
+
+ config = tiny_nemotron_config()
+ text = config["llm_config"]
+ text.update(
+ model_type="nemotron_h_puzzle",
+ num_nextn_predict_layers=0,
+ hidden_size=128,
+ intermediate_size=128,
+ head_dim=32,
+ moe_latent_size=128,
+ moe_intermediate_size=128,
+ moe_shared_expert_intermediate_size=128,
+ block_configs=[
+ {"block_type": "mamba"},
+ {
+ "block_type": "moe",
+ "n_routed_experts": None if null_overrides else 3,
+ "num_experts_per_tok": None if null_overrides else 2,
+ },
+ {"block_type": "attention"},
+ ],
+ )
+ config = normalize_nemotron_config(config)
+ mx.random.seed(42)
+ model = Model(ModelConfig.from_dict(config))
+ model.eval()
+ weights = {
+ key: value if key.endswith(".A_log") else value.astype(mx.bfloat16)
+ for key, value in tree_flatten(model.parameters())
+ }
+ model.load_weights(list(weights.items()), strict=True)
+ mx.save_safetensors(str(tmp_path / "model.safetensors"), weights)
+ (tmp_path / "config.json").write_text(json.dumps(config))
+ tokens = mx.array([[1 + (i + row) % 32 for i in range(64)] for row in range(2)])
+ monkeypatch.setattr(oq, "_load_calibration_data", lambda *a, **kw: tokens)
+ resident, _ = oq._collect_imatrix_from_model(
+ model,
+ object(),
+ config,
+ calib_dataset=oq._OQE_CALIB_DATASET,
+ num_samples=2,
+ seq_length=64,
+ )
+
+ def reject_full_load(*args, **kwargs):
+ raise AssertionError("streamed calibration must not load the complete model")
+
+ monkeypatch.setattr("mlx_vlm.utils.load_model", reject_full_load)
+ streamed, metadata = oq._collect_imatrix_streaming(
+ tmp_path,
+ object(),
+ config,
+ calib_dataset=oq._OQE_CALIB_DATASET,
+ num_samples=2,
+ seq_length=64,
+ measure_sensitivity=True,
+ sensitivity_oq_level=4,
+ sensitivity_num_samples=2,
+ sensitivity_seq_length=64,
+ )
+ assert streamed.keys() == resident.keys()
+ for key, expected in resident.items():
+ np.testing.assert_array_equal(streamed[key].counts, expected.counts)
+ np.testing.assert_array_equal(streamed[key].in_sum2, expected.in_sum2)
+ reference = oq._measure_sensitivity_from_model(
+ model, object(), config, 4, num_samples=2, seq_length=64
+ )
+ assert metadata["sensitivity_map"] == pytest.approx(reference, abs=1e-6)
+ assert metadata["requires_expert_counts"]
+ plan = oq._oqe_calibration_batch_plan(config, requested_samples=32, seq_length=64)
+ assert plan["top_k"] == (1 if null_overrides else 2)
+ assert plan["num_experts"] == (2 if null_overrides else 3)
+
+
+def test_nemotron_rejects_text_only_before_creating_output(tmp_path):
+ from omlx.oq import quantize_oq_streaming
+
+ source = tmp_path / "source"
+ source.mkdir()
+ (source / "config.json").write_text(json.dumps(tiny_nemotron_config()))
+ output = tmp_path / "output"
+ with pytest.raises(ValueError, match="multimodal"):
+ quantize_oq_streaming(str(source), str(output), 4, text_only=True)
+ assert not output.exists()
+
+
+def test_nemotron_rejects_existing_mlx_quant_before_creating_output(tmp_path):
+ from omlx.oq import quantize_oq_streaming
+
+ source = tmp_path / "source"
+ source.mkdir()
+ config = {**tiny_nemotron_config(), "quantization": {"bits": 4, "group_size": 64}}
+ (source / "config.json").write_text(json.dumps(config))
+ output = tmp_path / "output"
+ with pytest.raises(ValueError, match="existing MLX quantization"):
+ quantize_oq_streaming(str(source), str(output), 4)
+ assert not output.exists()
+
+
+@pytest.mark.parametrize("orphan", [False, True])
+def test_native_modelopt_source_rejects_invalid_packed_storage(tmp_path, orphan):
+ from omlx.oq import _LazyTensorIndex
+
+ config = {
+ **tiny_nemotron_config(),
+ "quantization_config": {
+ "quant_method": "modelopt_mixed",
+ "quant_algo": "MIXED_PRECISION",
+ },
+ }
+ weights = {"language_model.lm_head.weight": mx.ones((128, 16), dtype=mx.uint8)}
+ if not orphan:
+ weights["language_model.lm_head.weight_scale"] = mx.ones(
+ (128, 1), dtype=mx.uint8
+ )
+ path = tmp_path / "model.safetensors"
+ mx.save_safetensors(str(path), weights)
+ with pytest.raises(ValueError, match="Unpaired packed|Invalid ModelOpt FP8 scale"):
+ index = _LazyTensorIndex([path], config=config)
+ index["language_model.lm_head.weight"]
+
+
+@pytest.mark.parametrize(
+ "model_type",
+ [
+ "NemotronH_Nano_Omni_Reasoning_V3",
+ "nemotron_h_nano_omni",
+ "nemotron_h_omni",
+ ],
+)
+def test_native_mtp_admin_capability_requires_configuration_and_real_heads(
+ tmp_path, model_type
+):
+ from omlx.utils.model_loading import lightning_mtp_supported
+
+ config = {**tiny_nemotron_config(), "model_type": model_type}
+ (tmp_path / "config.json").write_text(json.dumps(config))
+ index = tmp_path / "model.safetensors.index.json"
+ index.write_text(
+ json.dumps(
+ {"weight_map": {"language_model.lm_head.weight": "model.safetensors"}}
+ )
+ )
+ assert not lightning_mtp_supported(tmp_path)
+ index.write_text(
+ json.dumps(
+ {"weight_map": {"mtp.layers.0.mixer.q_proj.weight": "model.safetensors"}}
+ )
+ )
+ assert lightning_mtp_supported(tmp_path)
+ config["llm_config"]["num_nextn_predict_layers"] = 0
+ (tmp_path / "config.json").write_text(json.dumps(config))
+ assert not lightning_mtp_supported(tmp_path)
+
+
+@pytest.mark.parametrize("with_audio", [False, True])
+def test_engine_preparation_preserves_compacted_video_and_source_usage(
+ native_target, monkeypatch, with_audio
+):
+ from mlx_vlm import utils
+
+ from omlx.engine.vlm import VLMBatchedEngine
+ from omlx.patches import mlx_audio_compat
+ from omlx.request import Request, SamplingParams
+ from omlx.scheduler import Scheduler
+
+ engine = VLMBatchedEngine("unused")
+ engine._vlm_model = native_target
+ engine._processor = SimpleNamespace(
+ audio_sampling_rate=16000,
+ apply_chat_template=lambda *_args, **_kwargs: "",
+ )
+ engine._tokenizer = engine._processor
+ native_target.sound_context_token_id = 19
+ if with_audio:
+ native_target.sound_encoder = object()
+ monkeypatch.setattr(
+ native_target,
+ "_extract_sound_features",
+ lambda **_kwargs: mx.ones((1, 1, 32)),
+ )
+ monkeypatch.setattr(
+ mlx_audio_compat, "ensure_mlx_audio_resample_export", lambda: None
+ )
+ monkeypatch.setattr(utils, "load_audio", lambda waveform, _rate: waveform)
+ calls = []
+
+ def prepare(_processor, **kwargs):
+ calls.append(kwargs)
+ ids = [1, 18, 18, 18] + ([19] if with_audio else []) + [3]
+ inputs = {
+ "input_ids": mx.array([ids]),
+ "attention_mask": mx.ones((1, len(ids)), dtype=mx.int32),
+ "pixel_values_videos": mx.ones((6, 3, 32, 32)),
+ }
+ if with_audio:
+ inputs["sound_clips"] = kwargs["audio"]
+ return inputs
+
+ monkeypatch.setattr(utils, "prepare_inputs", prepare)
+ audio = [(np.ones((160, 2), dtype=np.float32), 16000)] if with_audio else None
+ ids, embeddings, extra, media_hash, _, ranges = engine._prepare_vision_inputs(
+ [{"role": "user", "content": "Describe this."}],
+ [],
+ audio=audio,
+ videos=["bounded-test-video"],
+ )
+ assert len(ids) == embeddings.shape[1] == 3 + int(with_audio)
+ assert extra["_omlx_source_prompt_tokens"] == 5 + int(with_audio)
+ assert extra["_omlx_pruned_video"]
+ assert calls[0]["max_frames"] == 64
+ if with_audio:
+ assert calls[0]["audio"][0].shape == (160,)
+ assert ranges == [(0, media_hash)]
+ changed_audio = [(np.zeros((160, 2), dtype=np.float32), 16000)]
+ changed = engine._prepare_vision_inputs(
+ [{"role": "user", "content": "Describe this."}],
+ [],
+ audio=changed_audio,
+ videos=["bounded-test-video"],
+ )
+ assert changed[3] != media_hash
+ counted = engine._prepare_vision_inputs(
+ [{"role": "user", "content": "Describe this."}],
+ [],
+ audio=audio,
+ videos=["bounded-test-video"],
+ encode_vision=False,
+ )
+ assert len(counted[0]) == 5 + int(with_audio)
+ assert counted[1] is None
+ request = Request(
+ "video",
+ ids,
+ SamplingParams(),
+ prompt_token_ids=ids,
+ num_prompt_tokens=len(ids),
+ vlm_extra_kwargs=extra,
+ )
+ scheduler = SimpleNamespace(
+ model=engine._vlm_model,
+ _prefix_cache_prepared=set(),
+ block_aware_cache=object(),
+ _model_has_unreconstructible_cache=lambda: False,
+ _log_prefix_divergence=lambda _request: None,
+ _try_specprefill_scoring=lambda _request: None,
+ )
+ Scheduler._prepare_prefix_cache_for_request(scheduler, request)
+ assert request.skip_cache_store
+ assert request.cached_tokens == 0
+ assert request.remaining_tokens == ids
+ assert request.num_prompt_tokens == len(ids)
+ assert request.source_prompt_tokens == 5 + int(with_audio)
+ assert "_omlx_source_prompt_tokens" not in extra
+
+
+@pytest.mark.parametrize("mode", ["greedy", "sampled", "head_failure"])
+def test_native_uniform_commit_uses_common_frontier_atomically(
+ native_target, monkeypatch, mode
+):
+ from mlx_lm.generate import BatchGenerator
+ from mlx_vlm.speculative.drafters.nemotron_h_mtp import Model, ModelConfig
+
+ from omlx import scheduler
+ from omlx.models.vlm import VLMModelAdapter
+ from omlx.patches.mlx_lm_mtp import batch_generator as bg
+
+ assert scheduler.BatchGenerator is BatchGenerator
+ adapter = VLMModelAdapter(native_target)
+ adapter.enable_nemotron_mtp(
+ Model(ModelConfig(text_config=tiny_nemotron_config()["llm_config"])), depth=3
+ )
+
+ class Sampler:
+ temp = 0.7
+
+ def __init__(self, seed):
+ self.seed, self.calls = seed, 0
+
+ def __call__(self, logprobs):
+ key = mx.random.key(self.seed + self.calls)
+ self.calls += 1
+ return mx.random.categorical(logprobs / self.temp, key=key)
+
+ generator = BatchGenerator(
+ adapter,
+ max_tokens=12,
+ completion_batch_size=2,
+ sampler=lambda lp: mx.argmax(lp, axis=-1),
+ )
+ uids = generator.insert([[1, 2, 3], [5, 6, 7, 8]])
+ try:
+ generator.next_generated()
+ generator.next_generated()
+ batch = generator._generation_batch
+ states = batch._omlx_mtp_batch_state.states
+ expected = {}
+ samplers = [Sampler(91), Sampler(103)]
+ if mode == "sampled":
+ batch.samplers = samplers
+ for index, uid in enumerate(uids):
+ state = states[uid]
+ cache = deepcopy(batch.extract_cache(index))
+ sampler = (
+ copy(samplers[index]) if mode == "sampled" else batch.fallback_sampler
+ )
+ ids = state.next_main.reshape(1, 1)
+ tokens = []
+ for _ in range(3):
+ logits = native_target.language_model(ids, cache=cache).logits[:, -1]
+ lp = logits - mx.logsumexp(logits, axis=-1, keepdims=True)
+ token = int(sampler(lp).item())
+ tokens.append(token)
+ ids = mx.array([[token]])
+ expected[uid] = tokens[:2]
+ if index == 1:
+ tokens[1] = (tokens[1] + 1) % 128
+ state.drafts = mx.array(tokens, dtype=mx.uint32)
+ rollback = adapter.rollback_speculative_cache
+ accepted = []
+
+ def observed_rollback(cache, undo, count, width):
+ accepted.append((count, width))
+ return rollback(cache, undo, count, width)
+
+ monkeypatch.setattr(adapter, "rollback_speculative_cache", observed_rollback)
+ if mode == "head_failure":
+ chain = bg._chain_next_drafts
+ calls = []
+ before = {uid: deepcopy(state.stats) for uid, state in states.items()}
+
+ def fail_second(*args, **kwargs):
+ calls.append(1)
+ if len(calls) == 2:
+ raise RuntimeError("injected native head failure")
+ return chain(*args, **kwargs)
+
+ monkeypatch.setattr(bg, "_chain_next_drafts", fail_second)
+ with pytest.raises(RuntimeError, match="injected native head failure"):
+ generator.next_generated()
+ assert all(
+ not state.queue and state.stats == before[uid]
+ for uid, state in states.items()
+ )
+ else:
+ responses = generator.next_generated()
+ for response in responses:
+ assert response.token == expected[response.uid].pop(0)
+ assert all(state.stats.accepts == 1 for state in states.values())
+ if mode == "sampled":
+ assert [sampler.calls for sampler in samplers] == [2, 2]
+ assert accepted == [(1, 4)]
+ finally:
+ generator.close()
+
+
+def test_native_processor_pairs_odd_video_frames_without_model_download(native_target):
+ from mlx_vlm.models.nemotron_h_nano_omni.image_processing_nemotron_h_nano_omni import (
+ NemotronHNanoOmniImageProcessor,
+ )
+ from mlx_vlm.models.nemotron_h_nano_omni.processing_nemotron_h_nano_omni import (
+ NemotronHNanoOmniProcessor,
+ )
+
+ class Tokenizer:
+ image_token_id, video_token_id, audio_token_id = 18, 20, 19
+
+ def __call__(self, texts, **_kwargs):
+ ids = [[1] + [18] * text.count("") + [3] for text in texts]
+ return {"input_ids": ids, "attention_mask": [[1] * len(row) for row in ids]}
+
+ processor = NemotronHNanoOmniProcessor(
+ NemotronHNanoOmniImageProcessor(
+ norm_mean=[0.5] * 3,
+ norm_std=[0.5] * 3,
+ min_num_patches=4,
+ max_num_patches=4,
+ video_target_num_patches=4,
+ ),
+ Tokenizer(),
+ )
+ result = processor(
+ text=["Describe ."], videos=[np.zeros((3, 3, 32, 32), dtype=np.uint8)]
+ )
+ assert int(mx.sum(result["input_ids"] == 18).item()) == 2
+ assert result["pixel_values_videos"].shape == (3, 3, 32, 32)
+ prepared = prepare_nemotron_prompt(
+ native_target,
+ result["input_ids"],
+ pixel_values_videos=result["pixel_values_videos"],
+ )
+ assert prepared.token_ids.shape[1] == prepared.inputs_embeds.shape[1] == 3
+
+
+@pytest.mark.parametrize("video", [False, True])
+def test_media_conditioned_mtp_uses_production_chunked_prompt_capture(
+ native_target, video
+):
+ from mlx_lm.generate import BatchGenerator
+ from mlx_vlm.speculative.drafters.nemotron_h_mtp import Model, ModelConfig
+
+ from omlx import scheduler
+ from omlx.models.vlm import VLMModelAdapter
+
+ assert scheduler.BatchGenerator is BatchGenerator
+ ids = mx.array([[1, 18, 18, 18, 3]]) if video else mx.array([[1, 18, 3]])
+ media = (
+ {"pixel_values_videos": mx.ones((6, 3, 32, 32))}
+ if video
+ else {"pixel_values": mx.ones((1, 3, 32, 32))}
+ )
+ prepared = prepare_nemotron_prompt(native_target, ids, **media)
+ adapter = VLMModelAdapter(native_target)
+ adapter.enable_nemotron_mtp(
+ Model(ModelConfig(text_config=tiny_nemotron_config()["llm_config"])), depth=3
+ )
+ adapter.set_pending_embeddings(prepared.inputs_embeds)
+ generator = BatchGenerator(
+ adapter,
+ max_tokens=7,
+ prefill_step_size=1,
+ sampler=lambda lp: mx.argmax(lp, axis=-1),
+ )
+ generator.insert([prepared.token_ids[0].tolist()])
+ actual = []
+ terminal = None
+ try:
+ for _ in range(20):
+ responses = generator.next_generated()
+ if not responses:
+ break
+ for response in responses:
+ actual.append(response.token)
+ if response.finish_reason:
+ terminal = response.prompt_cache
+ finally:
+ generator.close()
+ cache = native_target.language_model.make_cache()
+ logits = native_target.language_model(
+ prepared.token_ids, inputs_embeds=prepared.inputs_embeds, cache=cache
+ ).logits[:, -1]
+ expected = []
+ for _ in range(7):
+ token = int(mx.argmax(logits, axis=-1).item())
+ expected.append(token)
+ logits = native_target.language_model(mx.array([[token]]), cache=cache).logits[
+ :, -1
+ ]
+ assert actual == expected
+ probe = mx.array([[12]])
+ np.testing.assert_allclose(
+ np.array(native_target.language_model(probe, cache=terminal).logits),
+ np.array(native_target.language_model(probe, cache=cache).logits),
+ atol=1e-5,
+ rtol=1e-5,
+ )
+ assert not adapter.has_pending_embeddings
+
+
+@pytest.mark.parametrize("rate", [0, 0.7, 1])
+@pytest.mark.parametrize("width", [32, 64])
+def test_video_pruning_matches_native_and_preserves_alignment(
+ native_target, rate, width
+):
+ spatial = width // 32
+ ids = mx.array([[1] + [18] * (3 * spatial) + [3]])
+ mask = mx.ones_like(ids)
+ pixels = mx.random.normal((6, 3, 32, width))
+ kwargs = {"pixel_values_videos": pixels, "video_pruning_rate": rate}
+ expected = native_target.get_input_embeddings(ids, **kwargs).inputs_embeds
+ result = prepare_nemotron_prompt(native_target, ids, mask=mask, **kwargs)
+ np.testing.assert_array_equal(np.array(result.inputs_embeds), np.array(expected))
+ np.testing.assert_array_equal(
+ np.array(result.token_ids), np.array(ids[:, result.retained_positions])
+ )
+ assert result.token_ids.shape == result.attention_mask.shape
+ assert result.token_ids.shape[1] == result.inputs_embeds.shape[1]
+ assert result.token_ids[0, 0].item() == 1
+ assert result.token_ids[0, -1].item() == 3
+ assert native_target.video_pruning_rate == 0.7
+
+
+def test_video_preparation_extracts_features_once(native_target, monkeypatch):
+ extract = native_target.extract_video_feature
+ calls = []
+
+ def counted(pixels):
+ calls.append(pixels)
+ return extract(pixels)
+
+ monkeypatch.setattr(native_target, "extract_video_feature", counted)
+ prepare_nemotron_prompt(
+ native_target,
+ mx.array([[1, 18, 18, 18, 3]]),
+ pixel_values_videos=mx.zeros((6, 3, 32, 32)),
+ )
+ assert len(calls) == 1
+
+
+@pytest.mark.parametrize("rate", [-0.1, 1.1, float("nan")])
+def test_video_preparation_rejects_invalid_pruning(native_target, rate):
+ with pytest.raises(ValueError, match="between 0 and 1"):
+ prepare_nemotron_prompt(
+ native_target,
+ mx.array([[1, 18, 3]]),
+ pixel_values_videos=mx.zeros((2, 3, 32, 32)),
+ video_pruning_rate=rate,
+ )
+
+
+@pytest.mark.parametrize("accepted", [0, 1, 3])
+def test_native_batched_uniform_rollback_matches_independent_prefixes(
+ native_target, accepted
+):
+ model = native_target.language_model
+ prompts = [mx.array([[1, 2, 3]]), mx.array([[5, 6, 7, 8, 9]])]
+ ordinary = [model.make_cache() for _ in prompts]
+ rows = [model.make_cache() for _ in prompts]
+ for prompt, baseline, candidate in zip(prompts, ordinary, rows):
+ model(prompt, cache=baseline)
+ model(prompt, cache=candidate)
+ caches = [
+ None if first is None else first.merge([first, second])
+ for first, second in zip(*rows)
+ ]
+ block = mx.array([[4, 5, 6, 7], [10, 11, 12, 13]])
+ hidden, _, states = model.speculative_verify_hidden(block, caches)
+ mx.eval(hidden)
+ assert hidden.shape == (2, 4, 32)
+ model.rollback_speculative_cache(caches, states, accepted, 4)
+ for row, baseline in enumerate(ordinary):
+ for position in range(accepted + 1):
+ model(block[row : row + 1, position : position + 1], cache=baseline)
+ extracted = [None if c is None else c.extract(row) for c in caches]
+ for actual_cache, expected_cache in zip(extracted, baseline):
+ for actual_state, expected_state in zip(
+ actual_cache.state, expected_cache.state
+ ):
+ np.testing.assert_allclose(
+ np.array(actual_state),
+ np.array(expected_state),
+ atol=1e-5,
+ rtol=1e-5,
+ )
+ probe = mx.array([[20 + row]])
+ expected = model(probe, cache=baseline).logits
+ actual = model(probe, cache=extracted).logits
+ np.testing.assert_allclose(
+ np.array(actual), np.array(expected), atol=1e-5, rtol=1e-5
+ )
+
+
+def test_native_rollback_rejects_ragged_acceptance(native_target):
+ model = native_target.language_model
+ with pytest.raises(ValueError, match="uniform acceptance"):
+ model.rollback_speculative_cache([], [], [3, 1], 4)
+
+
+@pytest.mark.parametrize("mismatch", [0, 1, 3])
+def test_uniform_walk_stops_all_rows_at_first_mismatch(mismatch):
+ drafts = [[10, 11, 12], [20, 21, 22]]
+ calls = []
+
+ def sample(position):
+ calls.append(position)
+ if position == 3:
+ return [13, 23]
+ return [
+ drafts[0][position],
+ 99 if position == mismatch else drafts[1][position],
+ ]
+
+ result = sample_uniform_prefix(drafts, sample, lambda *_: False)
+ assert result.accepted_drafts == mismatch
+ assert calls == list(range(mismatch + 1))
+ assert result.successors[0] == 10 + mismatch
+ assert result.successors[1] == (23 if mismatch == 3 else 99)
+
+
+def test_uniform_walk_stop_boundary_does_not_sample_future_positions():
+ calls = []
+
+ def sample(position):
+ calls.append(position)
+ return [10 + position, 20 + position]
+
+ result = sample_uniform_prefix(
+ [[10, 11, 12], [20, 21, 22]], sample, lambda position, _: position == 1
+ )
+ assert result.accepted_drafts == 1
+ assert result.successors == (11, 21)
+ assert calls == [0, 1]
+
+
+def test_native_head_unequal_prompt_caches_merge_and_continue(native_target):
+ from mlx_vlm.speculative.drafters.nemotron_h_mtp import Model, ModelConfig
+
+ prototype = Model(ModelConfig(text_config=tiny_nemotron_config()["llm_config"]))
+ prompts = [mx.array([[1, 2, 3]]), mx.array([[5, 6, 7, 8, 9]])]
+ heads = [deepcopy(prototype) for _ in prompts]
+ hidden_rows = []
+ for head, ids in zip(heads, prompts):
+ hidden = native_target.language_model(ids, return_hidden=True).hidden_states[-1]
+ head.reset(native_target)
+ head.prefill_from_target_hidden(ids, hidden, 7, sampler=None, greedy=True)
+ hidden_rows.append(hidden[:, -1:])
+ merged = [
+ left.merge([left, right])
+ for left, right in zip(heads[0]._cache, heads[1]._cache)
+ ]
+ tokens = mx.array([[10], [11]])
+ hidden = mx.concatenate(hidden_rows, axis=0)
+ actual, _ = prototype._forward_hidden(
+ native_target.language_model.get_input_embeddings(tokens),
+ hidden,
+ tokens,
+ merged,
+ )
+ expected = [
+ head._forward_tokens(tokens[i : i + 1], hidden[i : i + 1], mx.int32)[0]
+ for i, head in enumerate(heads)
+ ]
+ np.testing.assert_allclose(
+ np.array(actual), np.array(mx.concatenate(expected)), atol=1e-5, rtol=1e-5
+ )
+ for index, head in enumerate(heads):
+ for group_cache, row_cache in zip(merged, head._cache):
+ for got, want in zip(group_cache.extract(index).state, row_cache.state):
+ np.testing.assert_allclose(
+ np.array(got), np.array(want), atol=1e-5, rtol=1e-5
+ )
+
+
+def test_pruned_media_full_and_chunked_head_priming_match(native_target):
+ from mlx_vlm.speculative.drafters.nemotron_h_mtp import Model, ModelConfig
+
+ ids = mx.array([[1, 18, 18, 18, 3]])
+ prompt = prepare_nemotron_prompt(
+ native_target, ids, pixel_values_videos=mx.random.normal((6, 3, 32, 32))
+ )
+ language = native_target.language_model
+ full = language(
+ prompt.token_ids, inputs_embeds=prompt.inputs_embeds, return_hidden=True
+ ).hidden_states[-1]
+ cache = language.make_cache()
+ chunks = []
+ for start in range(0, prompt.token_ids.shape[1], 2):
+ output = language(
+ prompt.token_ids[:, start : start + 2],
+ inputs_embeds=prompt.inputs_embeds[:, start : start + 2],
+ cache=cache,
+ return_hidden=True,
+ )
+ chunks.append(output.hidden_states[-1])
+ chunked = mx.concatenate(chunks, axis=1)
+ head = Model(ModelConfig(text_config=tiny_nemotron_config()["llm_config"]))
+ heads = [head, deepcopy(head)]
+ for draft, hidden in zip(heads, [full, chunked]):
+ draft.reset(native_target)
+ draft.prefill_from_target_hidden(
+ prompt.token_ids, hidden, 7, sampler=None, greedy=True
+ )
+ np.testing.assert_allclose(
+ np.array(heads[0]._seed_hidden),
+ np.array(heads[1]._seed_hidden),
+ atol=1e-5,
+ rtol=1e-5,
+ )
+
+
+@pytest.mark.parametrize("enabled", [False, True])
+@pytest.mark.parametrize("phase", ["prefill", "decode"])
+def test_native_full_prompt_mtp_cannot_memory_requeue(enabled, phase):
+ from omlx.request import Request, SamplingParams
+ from omlx.scheduler import Scheduler
+
+ request = Request("native", [1, 2], SamplingParams())
+ scheduler = SimpleNamespace(
+ model=SimpleNamespace(_omlx_native_mtp_full_prompt=enabled),
+ _MAX_MEMORY_REQUEUES=2,
+ _specprefill_active_request_id=None,
+ _prefill_states={"native": object()} if phase == "prefill" else {},
+ request_id_to_uid={"native": 1},
+ )
+ assert Scheduler._memory_requeue_blocker(scheduler, request) == (
+ "native full-prompt MTP" if enabled else None
+ )
+
+
+@pytest.mark.parametrize(
+ "field",
+ [
+ "image_token_id",
+ "video_token_id",
+ "audio_token_id",
+ "img_context_token_id",
+ "video_context_token_id",
+ "sound_context_token_id",
+ ],
+)
+def test_memory_requeue_recognizes_native_media_boundaries(field):
+ from omlx.scheduler import Scheduler
+
+ scheduler = SimpleNamespace(
+ model=SimpleNamespace(
+ _vlm_model=SimpleNamespace(config=SimpleNamespace(**{field: 18}))
+ )
+ )
+ assert Scheduler._media_token_end(scheduler, [1, 18, 18, 3]) == 3
+ assert Scheduler._media_token_end(scheduler, [1, 3]) == 0
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("media_type", ["image_url", "input_audio", "video_url"])
+async def test_native_preflight_counts_processor_expanded_media_tokens(media_type):
+ from concurrent.futures import ThreadPoolExecutor
+ from unittest.mock import AsyncMock, Mock
+
+ from omlx.engine.vlm import VLMBatchedEngine
+
+ engine = VLMBatchedEngine("unused")
+ engine._loaded = True
+ engine._vlm_model = SimpleNamespace(
+ config=SimpleNamespace(model_type="nemotron_h_omni")
+ )
+ engine._processor = SimpleNamespace()
+ engine._tokenizer = SimpleNamespace(encode=lambda _text: [1])
+ engine._apply_chat_template = lambda *_args, **_kwargs: "text only"
+ engine._extract_request_media = lambda messages: ([], messages, [], [], [])
+ engine._process_chat_messages = Mock(
+ return_value=(list(range(501)), None, {}, None, 0, [])
+ )
+ engine._preflight_or_raise_with_eviction = AsyncMock()
+ messages = [{"role": "user", "content": [{"type": media_type}]}]
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ engine._engine = SimpleNamespace(
+ _mlx_executor=executor, engine=SimpleNamespace(scheduler=object())
+ )
+ await engine.preflight_chat(messages, request_id="media")
+ assert (
+ engine._preflight_or_raise_with_eviction.call_args.kwargs["num_prompt_tokens"]
+ == 501
+ )
+ engine._process_chat_messages.assert_called_once()
+ assert engine._process_chat_messages.call_args.args[2]["_encode_vision"] is False
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ "model_type",
+ ["nemotron_h_omni", "nemotron_h_nano_omni", "NemotronH_Nano_Omni_Reasoning_V3"],
+)
+async def test_native_tokenization_does_not_encode_or_prune_media(model_type):
+ from concurrent.futures import ThreadPoolExecutor
+ from unittest.mock import Mock
+
+ from omlx.engine.vlm import VLMBatchedEngine
+
+ engine = VLMBatchedEngine("unused")
+ engine._loaded = True
+ engine._vlm_model = SimpleNamespace(config=SimpleNamespace(model_type=model_type))
+ engine._process_chat_messages = Mock(
+ return_value=([1, 18, 18, 18, 3], None, {}, None, 0, [])
+ )
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ engine._engine = SimpleNamespace(_mlx_executor=executor)
+ tokens = await engine.tokenize_chat([{"role": "user", "content": "media"}])
+ assert tokens == [1, 18, 18, 18, 3]
+ assert engine._process_chat_messages.call_args.args[2]["_encode_vision"] is False
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("sidecar", [False, True])
+async def test_native_head_load_runs_on_mlx_executor(
+ native_target, tmp_path, monkeypatch, sidecar
+):
+ import threading
+
+ from mlx_vlm import utils
+ from mlx_vlm.speculative.drafters.nemotron_h_mtp.split import (
+ NemotronHMTPSplitter,
+ )
+
+ from omlx.engine.vlm import VLMBatchedEngine
+ from omlx.model_settings import ModelSettings
+ from omlx.models.vlm import VLMModelAdapter
+ from omlx.patches import nemotron_omni_quantization
+ from omlx.utils import model_loading
+
+ class HeadEnabledError(Exception):
+ pass
+
+ (tmp_path / "config.json").write_text(json.dumps(tiny_nemotron_config()))
+ mx.eval(native_target.parameters())
+ loop_thread = threading.get_ident()
+ head = object()
+ loads = []
+ expected_path = tmp_path / "head" if sidecar else tmp_path
+
+ def load_head(path):
+ assert threading.get_ident() != loop_thread
+ assert path == expected_path
+ loads.append(path)
+ return head
+
+ def enable_head(self, loaded, depth):
+ assert loaded is head and depth > 0
+ raise HeadEnabledError
+
+ processor = SimpleNamespace(tokenizer=SimpleNamespace(encode=lambda _text: [1]))
+ monkeypatch.setattr(
+ model_loading, "maybe_apply_pre_load_patches", lambda *_a, **_kw: None
+ )
+ monkeypatch.setattr(
+ model_loading,
+ "maybe_load_custom_quantization",
+ lambda *_a, **_kw: (native_target, processor),
+ )
+ monkeypatch.setattr(model_loading, "_checkpoint_has_mtp_weights", lambda _p: True)
+ monkeypatch.setattr(
+ nemotron_omni_quantization,
+ "native_mtp_sidecar",
+ lambda *_a: expected_path if sidecar else None,
+ )
+ monkeypatch.setattr(utils, "load_model", load_head)
+ monkeypatch.setattr(NemotronHMTPSplitter, "load", lambda _self, path: load_head(path))
+ monkeypatch.setattr(VLMModelAdapter, "enable_nemotron_mtp", enable_head)
+ engine = VLMBatchedEngine(
+ str(tmp_path),
+ model_settings=ModelSettings(mtp_enabled=True),
+ )
+ with pytest.raises(HeadEnabledError):
+ await engine.start()
+ assert loads == [expected_path]
diff --git a/tests/test_openai_models.py b/tests/test_openai_models.py
index ccdc35c4a0..b3247ff593 100644
--- a/tests/test_openai_models.py
+++ b/tests/test_openai_models.py
@@ -26,6 +26,8 @@
CompletionResponse,
ContentPart,
FunctionCall,
+ InputAudio,
+ InputVideo,
Message,
ModelInfo,
ModelsResponse,
@@ -76,6 +78,41 @@ def test_file_content_part(self):
assert part.file.filename == "sample.pdf"
assert part.file.file_data.endswith("ZA==")
+ def test_input_video_content_part(self):
+ """Video content parts are accepted as an oMLX extension."""
+ part = ContentPart(
+ type="input_video",
+ input_video={
+ "data": "data:video/mp4;base64,ZA==",
+ "format": "mp4",
+ "filename": "clip.mp4",
+ },
+ )
+
+ assert part.type == "input_video"
+ assert part.input_video.filename == "clip.mp4"
+ assert part.input_video.format == "mp4"
+
+ def test_input_audio_requires_data(self):
+ """input_audio uses the upstream base64 data contract."""
+ with pytest.raises(ValidationError, match="data"):
+ InputAudio()
+ with pytest.raises(ValidationError, match="data must not be empty"):
+ InputAudio(data=" ")
+
+ assert InputAudio(data="abc").data == "abc"
+
+ def test_input_video_requires_data(self):
+ """input_video accepts only inline base64 data."""
+ with pytest.raises(ValidationError, match="data"):
+ InputVideo()
+ with pytest.raises(ValidationError, match="data"):
+ InputVideo(url="https://example.com/clip.mp4")
+ with pytest.raises(ValidationError, match="data must not be empty"):
+ InputVideo(data=" ")
+
+ assert InputVideo(data="abc").data == "abc"
+
class TestMessage:
"""Tests for Message model."""
diff --git a/tests/test_responses.py b/tests/test_responses.py
index 801ec21a81..76a3d6c787 100644
--- a/tests/test_responses.py
+++ b/tests/test_responses.py
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
"""Tests for OpenAI Responses API models and utilities."""
+import copy
import json
import pytest
@@ -27,6 +28,7 @@
convert_responses_tools,
convert_stored_response_to_messages,
format_sse_event,
+ normalize_chat_messages_for_response_store,
normalize_response_output_to_messages,
split_namespace_tool_name,
)
@@ -415,6 +417,60 @@ def test_input_image_dropped_without_preserve_images(self):
messages = convert_responses_input_to_messages(items)
assert messages[0]["content"] == "Reply OK."
+ def test_input_audio_preserved_as_content_list(self):
+ """Responses input_audio parts should be preserved for VLM processing."""
+ items = [
+ InputItem(
+ type="message",
+ role="user",
+ content=[
+ {"type": "input_text", "text": "What is in this recording?"},
+ {
+ "type": "input_audio",
+ "input_audio": {"data": "abc123", "format": "wav"},
+ },
+ ],
+ )
+ ]
+
+ messages = convert_responses_input_to_messages(items)
+ content = messages[0]["content"]
+
+ assert isinstance(content, list)
+ assert content[1] == {
+ "type": "input_audio",
+ "input_audio": {"data": "abc123", "format": "wav"},
+ }
+
+ def test_input_file_preserved_as_file_part(self):
+ """Responses input_file maps to internal file part for preprocessing."""
+ items = [
+ InputItem(
+ type="message",
+ role="user",
+ content=[
+ {"type": "input_text", "text": "Summarize this."},
+ {
+ "type": "input_file",
+ "filename": "notes.txt",
+ "file_data": "data:text/plain;base64,ZA==",
+ },
+ ],
+ )
+ ]
+
+ messages = convert_responses_input_to_messages(items)
+ content = messages[0]["content"]
+
+ assert isinstance(content, list)
+ assert content[1] == {
+ "type": "file",
+ "file": {
+ "filename": "notes.txt",
+ "file_data": "data:text/plain;base64,ZA==",
+ },
+ }
+
def test_text_only_content_parts_flattened(self):
"""Content with only text parts should still be flattened to string."""
items = [
@@ -557,6 +613,60 @@ def test_reasoning_orphan_then_tool_calls_only(self):
IMAGE_URI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUg=="
+class TestResponseHistoryNormalization:
+ @pytest.mark.parametrize("serialized", [False, True])
+ def test_tool_argument_objects_survive_store_and_replay(self, serialized):
+ arguments = {"cmd": "pwd", "options": {"login": False}}
+ messages = [
+ {
+ "role": "assistant",
+ "reasoning_content": "Inspect first.",
+ "partial": False,
+ "tool_calls": [
+ {
+ "id": "call_shell",
+ "type": "function",
+ "function": {
+ "name": "exec_command",
+ "namespace": "functions",
+ "arguments": (
+ json.dumps(arguments) if serialized else arguments
+ ),
+ },
+ }
+ ],
+ },
+ {"role": "tool", "tool_call_id": "call_shell", "content": "/tmp"},
+ ]
+ original = copy.deepcopy(messages)
+ normalized = normalize_chat_messages_for_response_store(messages)
+ replayed = convert_responses_input_to_messages(None, previous_messages=messages)
+ assert normalized == replayed
+ assert normalized[0]["tool_calls"][0]["function"]["arguments"] == arguments
+ assert normalized[0]["tool_calls"][0]["function"]["namespace"] == "functions"
+ assert normalized[0]["reasoning_content"] == "Inspect first."
+ assert "partial" not in normalized[0]
+ assert normalized[1] == original[1]
+ assert messages == original
+ normalized[0]["tool_calls"][0]["function"]["arguments"]["cmd"] = "changed"
+ assert messages == original
+
+ def test_normalization_does_not_replace_malformed_arguments(self):
+ messages = [
+ {
+ "role": "assistant",
+ "tool_calls": [
+ {"function": {"name": "exec_command", "arguments": "{bad json"}}
+ ],
+ }
+ ]
+ assert normalize_chat_messages_for_response_store(messages) == messages
+
+ def test_null_tool_calls_are_preserved(self):
+ messages = [{"role": "assistant", "content": "Done", "tool_calls": None}]
+ assert normalize_chat_messages_for_response_store(messages) == messages
+
+
class TestFunctionCallOutputMultimodal:
"""Images in function_call_output lists route to VLM, not the prompt (#2989)."""
diff --git a/tests/test_video.py b/tests/test_video.py
index 12d21ceced..3d5373e574 100644
--- a/tests/test_video.py
+++ b/tests/test_video.py
@@ -38,6 +38,16 @@ def test_content_part_preserves_video_url():
assert part.video_url.url.startswith("data:video/mp4")
+def test_content_part_preserves_mimo_input_video_url_alias():
+ part = ContentPart(
+ type="input_video",
+ input_video={"url": "data:video/mp4;base64,AAAA"},
+ )
+
+ assert part.input_video is not None
+ assert part.input_video.url == "data:video/mp4;base64,AAAA"
+
+
def test_video_parts_expand_to_images_in_original_order(monkeypatch):
first = Image.new("RGB", (2, 2), "red")
second = Image.new("RGB", (2, 2), "blue")
diff --git a/tests/test_vlm_cohere2_moe_loader.py b/tests/test_vlm_cohere2_moe_loader.py
index 2b47e201d7..a080d53f0e 100644
--- a/tests/test_vlm_cohere2_moe_loader.py
+++ b/tests/test_vlm_cohere2_moe_loader.py
@@ -40,15 +40,22 @@ def test_cohere2_moe_loader_uses_upstream_processor(monkeypatch, tmp_path):
model = SimpleNamespace(config=SimpleNamespace(eos_token_id=[2]))
processor = object()
+ calls = []
monkeypatch.setattr(vlm_utils, "get_model_path", lambda model_name: tmp_path)
monkeypatch.setattr(vlm_utils, "load_model", lambda *a, **k: model)
- monkeypatch.setattr(vlm_utils, "load_processor", lambda *a, **k: processor)
+
+ def load_processor(*args, **kwargs):
+ calls.append(kwargs)
+ return processor
+
+ monkeypatch.setattr(vlm_utils, "load_processor", load_processor)
loaded_model, loaded_processor = _load_cohere2_moe_text_model("cohere")
assert loaded_model is model
assert loaded_processor is processor
+ assert calls[0]["eos_token_ids"] == [2]
def test_cohere2_moe_loader_falls_back_to_tokenizer(monkeypatch, tmp_path):
@@ -88,6 +95,30 @@ def fail_processor(*args, **kwargs):
assert tokenizer.stopping_criteria.eos_token_ids == [7]
+def test_cohere2_moe_loader_merges_generation_config_eos(monkeypatch, tmp_path):
+ import mlx_vlm.utils as vlm_utils
+
+ model = SimpleNamespace(config=SimpleNamespace(eos_token_id=[7]))
+ processor = object()
+ calls = []
+ (tmp_path / "generation_config.json").write_text('{"eos_token_id": [7, 9, 11]}')
+
+ monkeypatch.setattr(vlm_utils, "get_model_path", lambda model_name: tmp_path)
+ monkeypatch.setattr(vlm_utils, "load_model", lambda *a, **k: model)
+
+ def load_processor(*args, **kwargs):
+ calls.append(kwargs)
+ return processor
+
+ monkeypatch.setattr(vlm_utils, "load_processor", load_processor)
+
+ loaded_model, loaded_processor = _load_cohere2_moe_text_model("cohere")
+
+ assert loaded_model is model
+ assert loaded_processor is processor
+ assert calls[0]["eos_token_ids"] == [7, 9, 11]
+
+
def test_cohere2_moe_rejects_image_input():
engine = VLMBatchedEngine("cohere")
engine._vlm_model = SimpleNamespace(
diff --git a/tests/test_vlm_engine.py b/tests/test_vlm_engine.py
index 11b8406619..7dc3acfc60 100644
--- a/tests/test_vlm_engine.py
+++ b/tests/test_vlm_engine.py
@@ -234,6 +234,45 @@ async def stream_outputs(self, request_id):
assert outputs[0].generated_at == 10.0
assert outputs[0].generated_until == 12.0
+ @pytest.mark.asyncio
+ @pytest.mark.skipif(not HAS_MLX, reason="mlx is required")
+ @pytest.mark.parametrize("streaming", [False, True])
+ async def test_generation_preserves_terminal_token_ids(self, streaming):
+ token_ids = [10, 11, 12]
+ terminal = SimpleNamespace(
+ output_text="done",
+ output_token_ids=token_ids,
+ new_text="done",
+ prompt_tokens=1,
+ completion_tokens=3,
+ finished=True,
+ finish_reason="length",
+ tool_calls=None,
+ logprobs=None,
+ cached_tokens=0,
+ first_token_at=None,
+ )
+
+ class TokenCore(FakeStreamingCore):
+ async def stream_outputs(self, request_id):
+ async for partial in super().stream_outputs(request_id):
+ partial.output_token_ids = []
+ yield partial
+ yield terminal
+
+ core = TokenCore()
+ core.generate = AsyncMock(return_value=terminal)
+ engine = _make_loaded_engine(model_type="test-vlm")
+ engine._engine = core
+ if streaming:
+ outputs = [output async for output in engine.stream_generate("hello")]
+ assert outputs[0].tokens == []
+ result = outputs[-1]
+ else:
+ result = await engine.generate("hello")
+ assert result.tokens == token_ids
+ assert result.tokens is not token_ids
+
class TestVLMToolForwarding:
"""Tool schemas must reach scheduler requests on both chat paths."""
@@ -518,9 +557,7 @@ async def test_diffusion_preflight_allows_tools_with_parser(self):
"arguments": "{}",
}
- engine = _make_loaded_engine(
- model_type="diffusion_gemma", tokenizer=tokenizer
- )
+ engine = _make_loaded_engine(model_type="diffusion_gemma", tokenizer=tokenizer)
engine._diffusion_family = "block"
assert engine.supports_tool_calling is True
@@ -538,6 +575,49 @@ def test_diffusion_supports_tool_calling_false_without_parser(self):
engine._diffusion_family = "block"
assert engine.supports_tool_calling is False
+ @pytest.mark.asyncio
+ @pytest.mark.skipif(
+ not HAS_MLX, reason="mlx is required to import VLMBatchedEngine"
+ )
+ async def test_diffusion_preflight_rejects_audio_without_name_error(self):
+ from omlx.exceptions import InvalidRequestError
+
+ engine = _make_loaded_engine(model_type="diffusion_gemma")
+ engine._diffusion_family = "block"
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "hi"},
+ {"type": "input_audio", "input_audio": {"data": "not-base64"}},
+ ],
+ }
+ ]
+
+ with pytest.raises(InvalidRequestError, match="Audio input"):
+ await engine.preflight_chat(messages)
+
+ @pytest.mark.skipif(
+ not HAS_MLX, reason="mlx is required to import VLMBatchedEngine"
+ )
+ def test_process_diffusion_chat_rejects_audio_without_name_error(self):
+ from omlx.exceptions import InvalidRequestError
+
+ engine = _make_loaded_engine(model_type="diffusion_gemma")
+ engine._diffusion_family = "block"
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "hi"},
+ {"type": "input_audio", "input_audio": {"data": "not-base64"}},
+ ],
+ }
+ ]
+ with pytest.raises(InvalidRequestError, match="Audio input"):
+ engine._process_diffusion_chat_messages(messages, tools=None, kwargs={})
+ engine._process_diffusion_chat_messages(messages, tools=None, kwargs={})
+
@pytest.mark.skipif(
not HAS_MLX, reason="mlx is required to import VLMBatchedEngine"
)
@@ -1275,7 +1355,7 @@ def test_deepcopy_no_mutation(self):
class TestProcessChatMessages:
"""Tests for VLMBatchedEngine._process_chat_messages()."""
- @patch("omlx.engine.vlm.extract_images_from_messages")
+ @patch("omlx.engine.vlm.extract_media_from_messages")
def test_mimo_audio_stays_in_its_original_turn(self, mock_extract):
engine = _make_loaded_engine(model_type="mimo_v2")
audio_part = {
@@ -1298,7 +1378,7 @@ def test_mimo_audio_stays_in_its_original_turn(self, mock_extract):
stripped = [dict(message) for message in messages]
stripped[2]["content"] = "First recording"
stripped[4]["content"] = "Second recording"
- mock_extract.return_value = (stripped, [], [object(), object()])
+ mock_extract.return_value = (stripped, [], [object(), object()], [])
formatted = []
def prepare(message_values, images, audio, **kwargs):
@@ -1317,11 +1397,11 @@ def prepare(message_values, images, audio, **kwargs):
assert formatted[4]["content"].count("<|audio_pad|>") == 1
assert formatted[4]["content"].endswith("Second recording")
- @patch("omlx.engine.vlm.extract_images_from_messages")
+ @patch("omlx.engine.vlm.extract_media_from_messages")
def test_text_only_uses_vlm_prepare_path(self, mock_extract):
"""Text-only turns on a VLM model still use _prepare_vision_inputs()."""
text_msgs = [{"role": "user", "content": "Hello"}]
- mock_extract.return_value = (text_msgs, [], [])
+ mock_extract.return_value = (text_msgs, [], [], [])
engine = _make_loaded_engine()
engine._prepare_vision_inputs = MagicMock(
@@ -1378,11 +1458,11 @@ def test_count_chat_tokens_matches_prepared_prompt(self):
assert token_ids == engine._tokenizer.encode(prompt)
assert engine.count_chat_tokens(messages) == len(token_ids)
- @patch("omlx.engine.vlm.extract_images_from_messages")
+ @patch("omlx.engine.vlm.extract_media_from_messages")
def test_text_only_passes_tools_to_prepare_vision(self, mock_extract):
"""Text-only + tools still convert and pass tools through VLM path."""
text_msgs = [{"role": "user", "content": "Hello"}]
- mock_extract.return_value = (text_msgs, [], [])
+ mock_extract.return_value = (text_msgs, [], [], [])
engine = _make_loaded_engine()
engine._prepare_vision_inputs = MagicMock(
@@ -1400,7 +1480,7 @@ def test_text_only_passes_tools_to_prepare_vision(self, mock_extract):
call_kwargs = engine._prepare_vision_inputs.call_args[1]
assert call_kwargs["tools"] == [{"converted": True}]
- @patch("omlx.engine.vlm.extract_images_from_messages")
+ @patch("omlx.engine.vlm.extract_media_from_messages")
@patch("omlx.engine.vlm.expand_video_parts")
def test_mimo_video_uses_on_disk_model_type_when_loaded_config_omits_it(
self, mock_expand_video, mock_extract, tmp_path
@@ -1412,7 +1492,7 @@ def test_mimo_video_uses_on_disk_model_type_when_loaded_config_omits_it(
messages = [{"role": "user", "content": "video"}]
expanded = [{"role": "user", "content": "frames"}]
mock_expand_video.return_value = expanded
- mock_extract.return_value = (expanded, [], [])
+ mock_extract.return_value = (expanded, [], [], [])
engine = _make_loaded_engine(model_type=None, model_name=str(tmp_path))
engine._prepare_vision_inputs = MagicMock(
@@ -1425,7 +1505,7 @@ def test_mimo_video_uses_on_disk_model_type_when_loaded_config_omits_it(
mock_extract.assert_called_once_with(expanded)
@pytest.mark.asyncio
- @patch("omlx.engine.vlm.extract_images_from_messages")
+ @patch("omlx.engine.vlm.extract_media_from_messages")
@patch("omlx.engine.vlm.expand_video_parts")
async def test_mimo_video_preflight_expands_frames_before_validation(
self, mock_expand_video, mock_extract
@@ -1436,7 +1516,7 @@ async def test_mimo_video_preflight_expands_frames_before_validation(
expanded = [{"role": "user", "content": "sampled frames"}]
text_messages = [{"role": "user", "content": "describe"}]
mock_expand_video.return_value = expanded
- mock_extract.return_value = (text_messages, [Image.new("RGB", (4, 4))], [])
+ mock_extract.return_value = (text_messages, [Image.new("RGB", (4, 4))], [], [])
engine = _make_loaded_engine(model_type="mimo_v2_flash")
engine._apply_chat_template = MagicMock(return_value="prompt")
@@ -1456,14 +1536,14 @@ async def test_mimo_video_preflight_expands_frames_before_validation(
mock_expand_video.assert_called_once_with(messages)
mock_extract.assert_called_once_with(expanded)
- @patch("omlx.engine.vlm.extract_images_from_messages")
+ @patch("omlx.engine.vlm.extract_media_from_messages")
def test_image_path_calls_prepare_vision(self, mock_extract):
"""Messages with images → _prepare_vision_inputs() called."""
from PIL import Image
mock_image = Image.new("RGB", (4, 4), "red")
text_msgs = [{"role": "user", "content": "Describe"}]
- mock_extract.return_value = (text_msgs, [mock_image], [])
+ mock_extract.return_value = (text_msgs, [mock_image], [], [])
engine = _make_loaded_engine()
engine._apply_ocr_prompt = MagicMock(return_value=text_msgs)
@@ -1500,14 +1580,14 @@ def test_image_path_calls_prepare_vision(self, mock_extract):
assert image_cache_key_start == 12
assert image_cache_key_ranges == [(12, "hash123")]
- @patch("omlx.engine.vlm.extract_images_from_messages")
+ @patch("omlx.engine.vlm.extract_media_from_messages")
def test_image_path_passes_tools(self, mock_extract):
"""Image + tools → tools converted and passed to _prepare_vision_inputs()."""
from PIL import Image
mock_image = Image.new("RGB", (4, 4), "red")
text_msgs = [{"role": "user", "content": "Describe"}]
- mock_extract.return_value = (text_msgs, [mock_image], [])
+ mock_extract.return_value = (text_msgs, [mock_image], [], [])
engine = _make_loaded_engine()
engine._apply_ocr_prompt = MagicMock(return_value=text_msgs)
@@ -1529,14 +1609,14 @@ def test_image_path_passes_tools(self, mock_extract):
call_kwargs = engine._prepare_vision_inputs.call_args[1]
assert call_kwargs["tools"] == [{"converted": True}]
- @patch("omlx.engine.vlm.extract_images_from_messages")
+ @patch("omlx.engine.vlm.extract_media_from_messages")
def test_image_path_without_tools(self, mock_extract):
"""Image + tools=None → _prepare_vision_inputs(tools=None)."""
from PIL import Image
mock_image = Image.new("RGB", (4, 4), "red")
text_msgs = [{"role": "user", "content": "Describe"}]
- mock_extract.return_value = (text_msgs, [mock_image], [])
+ mock_extract.return_value = (text_msgs, [mock_image], [], [])
engine = _make_loaded_engine()
engine._apply_ocr_prompt = MagicMock(return_value=text_msgs)
@@ -1550,6 +1630,89 @@ def test_image_path_without_tools(self, mock_extract):
call_kwargs = engine._prepare_vision_inputs.call_args[1]
assert call_kwargs["tools"] is None
+ @patch("omlx.engine.vlm.extract_media_from_messages")
+ def test_audio_path_adds_media_cache_key(self, mock_extract):
+ """Audio requests use a media-specific prefix-cache key."""
+ text_msgs = [{"role": "user", "content": "Describe"}]
+ mock_extract.return_value = (text_msgs, [], [b"recording"], [])
+
+ engine = _make_loaded_engine()
+ engine._prepare_vision_inputs = MagicMock(
+ return_value=([1, 2, 3], None, None, None, 0, [])
+ )
+
+ result = engine._process_chat_messages(
+ [{"role": "user", "content": "Describe"}],
+ tools=None,
+ kwargs={},
+ )
+
+ _, _, _, image_hash, image_cache_key_start, image_cache_key_ranges = result
+ assert image_hash is not None
+ assert image_hash.startswith("av:")
+ assert image_cache_key_start == 0
+ assert image_cache_key_ranges == []
+
+ @patch("omlx.engine.vlm.extract_media_from_messages")
+ def test_audio_preserves_explicit_turn_association(self, mock_extract):
+ """Audio-only requests keep structured turns for media placement."""
+ text_msgs = [{"role": "user", "content": "First\nSecond"}]
+ original_messages = [
+ {"role": "user", "content": "First"},
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "Second"},
+ {
+ "type": "input_audio",
+ "input_audio": {"data": "cmVjb3JkaW5n", "format": "wav"},
+ },
+ ],
+ },
+ ]
+ mock_extract.return_value = (text_msgs, [], [b"recording"], [])
+
+ engine = _make_loaded_engine()
+ engine._prepare_vision_inputs = MagicMock(
+ return_value=([1, 2, 3], None, None, None, 0, [])
+ )
+
+ engine._process_chat_messages(original_messages, tools=None, kwargs={})
+
+ assert engine._prepare_vision_inputs.call_args.args[0] is original_messages
+
+ @patch("omlx.engine.vlm.extract_media_from_messages")
+ @patch("omlx.engine.vlm.native_video_token_count")
+ @patch("omlx.engine.vlm.probe_video")
+ @patch("omlx.engine.vlm.write_video_data_uri")
+ def test_video_temp_paths_cleaned_when_prepare_raises(
+ self, mock_write, mock_probe, mock_count, mock_extract, tmp_path
+ ):
+ """Decoded native-video files are cleaned if preprocessing fails."""
+ temp_video = tmp_path / "clip.mp4"
+ temp_video.write_bytes(b"recording")
+ mock_write.return_value = (temp_video, "digest")
+ mock_extract.return_value = (
+ [{"role": "user", "content": "Describe"}],
+ [],
+ [],
+ ["data:video/mp4;base64,cmVjb3JkaW5n"],
+ )
+
+ engine = _make_loaded_engine()
+ engine._native_video = True
+ engine._prepare_vision_inputs = MagicMock(side_effect=RuntimeError("boom"))
+
+ with pytest.raises(RuntimeError, match="boom"):
+ engine._process_chat_messages(
+ [{"role": "user", "content": "Describe"}],
+ tools=None,
+ kwargs={},
+ )
+
+ assert not temp_video.exists()
+
+
# ---------------------------------------------------------------------------
# TestPrepareVisionInputs
# ---------------------------------------------------------------------------
@@ -1893,6 +2056,27 @@ def test_gemma4_renders_formatted_turns_with_tokenizer(self, mock_prepare):
assert {"type": "audio"} in rendered[1]["content"]
assert rendered[3]["content"] == "Again"
+ @pytest.mark.skipif(not HAS_MLX, reason="MLX not available")
+ @patch("mlx_vlm.utils.prepare_inputs")
+ @patch("mlx_vlm.prompt_utils.apply_chat_template")
+ def test_video_passed_to_prepare_inputs(self, mock_vlm_act, mock_prepare):
+ """When video is provided, it is passed as videos= to prepare_inputs."""
+ engine = self._setup_engine_for_vision(model_type="qwen2_5_vl")
+
+ mock_vlm_act.return_value = [{"role": "user", "content": "formatted"}]
+ mock_prepare.return_value = {
+ "input_ids": mx.array([[1, 2, 3]]),
+ "pixel_values": None,
+ }
+
+ messages = [{"role": "user", "content": "Describe this clip"}]
+ videos = ["/tmp/clip.mp4"]
+
+ engine._prepare_vision_inputs(messages, [], videos=videos)
+
+ call_kwargs = mock_prepare.call_args[1]
+ assert call_kwargs.get("videos") == videos
+
# --- per-image vision feature cache -------------------------------
def _vision_cache_engine(self, images, entries_by_index):
@@ -2667,6 +2851,32 @@ def test_audio_and_image_in_same_message(self):
# Image range should be recorded
assert len(image_ranges) == 1
+ def test_format_messages_with_video_parts(self):
+ """Video-bearing messages receive video content entries."""
+ engine = _make_loaded_engine(model_type="qwen3_5")
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "input_video", "input_video": {"url": "/tmp/clip.mp4"}},
+ {"type": "text", "text": "Describe this clip"},
+ ],
+ },
+ ]
+
+ formatted, image_ranges = engine._format_messages_for_vlm_template(
+ messages,
+ num_images=0,
+ num_audios=0,
+ num_videos=1,
+ )
+
+ content = formatted[0]["content"]
+ assert isinstance(content, list)
+ assert content[0]["type"] == "video"
+ assert "video" not in content[0]
+ assert image_ranges == []
+
def test_text_only_messages_with_zero_audio(self):
"""Text-only messages with num_audios=0 should produce string content."""
engine = _make_loaded_engine(model_type="gemma4")
@@ -3292,20 +3502,24 @@ class TestSmartResizeTokens:
@pytest.mark.parametrize(
"w,h,expected",
[
- (512, 512, 256), # exact multiple of patch*merge (32)
- (336, 336, 100), # 336 -> 336 grid 21x21 -> 441//4... rounds via factor
- (510, 680, 336), # non-multiple, rounded to nearest factor
- (100, 100, 64), # below min_pixels -> upscaled to min
+ (512, 512, 256), # exact multiple of patch*merge (32)
+ (336, 336, 100), # 336 -> 336 grid 21x21 -> 441//4... rounds via factor
+ (510, 680, 336), # non-multiple, rounded to nearest factor
+ (100, 100, 64), # below min_pixels -> upscaled to min
(4000, 3000, 11750), # above max_pixels -> downscaled to cap
- (2791, 16, 106), # thin image: branch on raw rounded dims
+ (2791, 16, 106), # thin image: branch on raw rounded dims
],
)
def test_matches_known_grid(self, w, h, expected):
from omlx.engine.vlm import _smart_resize_tokens
got = _smart_resize_tokens(
- h, w, _QWEN_IP.patch_size, _QWEN_IP.merge_size,
- _QWEN_IP.min_pixels, _QWEN_IP.max_pixels,
+ h,
+ w,
+ _QWEN_IP.patch_size,
+ _QWEN_IP.merge_size,
+ _QWEN_IP.min_pixels,
+ _QWEN_IP.max_pixels,
)
assert got == expected
@@ -3326,8 +3540,7 @@ def test_reads_data_uri(self):
def test_http_url_returns_none(self):
from omlx.engine.vlm import _read_image_dims
- part = {"type": "image_url",
- "image_url": {"url": "https://example.com/x.jpg"}}
+ part = {"type": "image_url", "image_url": {"url": "https://example.com/x.jpg"}}
assert _read_image_dims(part) is None
def test_local_path_returns_none_without_opening(self):
@@ -3341,8 +3554,10 @@ def test_local_path_returns_none_without_opening(self):
def test_garbage_returns_none(self):
from omlx.engine.vlm import _read_image_dims
- part = {"type": "image_url",
- "image_url": {"url": "data:image/png;base64,not-base64!!"}}
+ part = {
+ "type": "image_url",
+ "image_url": {"url": "data:image/png;base64,not-base64!!"},
+ }
assert _read_image_dims(part) is None
@@ -3371,11 +3586,18 @@ def test_counts_thin_image_without_undercounting(self):
def test_falls_back_to_upper_bound_for_unreadable(self):
from omlx.engine.vlm import _count_image_tokens_real
- messages = [{"role": "user", "content": [
- {"type": "image_url",
- "image_url": {"url": "https://example.com/x.jpg"}},
- {"type": "text", "text": "hi"},
- ]}]
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "image_url",
+ "image_url": {"url": "https://example.com/x.jpg"},
+ },
+ {"type": "text", "text": "hi"},
+ ],
+ }
+ ]
total = _count_image_tokens_real(messages, _QWEN_PROC, upper_bound=16384)
assert total == 16384
@@ -3384,8 +3606,7 @@ def test_falls_back_when_processor_not_qwen_style(self):
# Processor missing patch/merge/min/max -> never under-count.
messages = [{"role": "user", "content": [_image_part(512, 512)]}]
- total = _count_image_tokens_real(messages, SimpleNamespace(),
- upper_bound=16384)
+ total = _count_image_tokens_real(messages, SimpleNamespace(), upper_bound=16384)
assert total == 16384
def test_no_images_returns_zero(self):
diff --git a/tests/test_vlm_model_adapter.py b/tests/test_vlm_model_adapter.py
index f2e9be36bc..d8903afccc 100644
--- a/tests/test_vlm_model_adapter.py
+++ b/tests/test_vlm_model_adapter.py
@@ -720,6 +720,9 @@ def test_get_last_rope_deltas(self):
vlm.language_model._rope_deltas = mx.array([[-42.0], [-7.0]])
assert adapter.get_last_rope_deltas() == -42.0
+ vlm.language_model._rope_deltas = mx.array([])
+ assert adapter.get_last_rope_deltas() == 0.0
+
vlm.language_model._rope_deltas = None
assert adapter.get_last_rope_deltas() == 0.0
diff --git a/tests/test_vlm_mtp.py b/tests/test_vlm_mtp.py
index b1dc611aed..2f8b052694 100644
--- a/tests/test_vlm_mtp.py
+++ b/tests/test_vlm_mtp.py
@@ -64,12 +64,10 @@ def test_qwen38_block_fp8_rejects_invalid_scale_grid():
)
-def _fake_drafter_model(model_type: str = "gemma4_assistant") -> MagicMock:
+def _fake_drafter_model(model_type: str = "gemma4_assistant") -> SimpleNamespace:
"""Build a stand-in for Gemma4AssistantDraftModel that satisfies the
minimum API used by VLMMTPDrafter."""
- drafter = MagicMock()
- drafter.config = MagicMock(model_type=model_type)
- return drafter
+ return SimpleNamespace(config=SimpleNamespace(model_type=model_type))
def test_load_vlm_mtp_drafter_happy_path():
@@ -549,9 +547,10 @@ def load_weights(self, weights, strict=True):
assert model.received_strict is False
-def test_dense_vlm_runtime_return_hidden_uses_language_model_output_contract():
- """Dense Qwen3.5 VLM MTP verify must satisfy mlx-vlm's output contract."""
+def test_dense_vlm_runtime_return_hidden_uses_exact_verifier(monkeypatch):
+ """Current Qwen VLM MTP verify must use the rollback-aware exact path."""
from mlx_vlm.models.base import LanguageModelOutput
+
from omlx.patches.mlx_vlm_mtp import qwen35_vlm_runtime
logits = mx.zeros((1, 2, 16))
@@ -586,6 +585,11 @@ def __call__(
self.forward_kwargs = kwargs
return FakeStockOutput(kwargs["capture_layer_ids"])
+ monkeypatch.setitem(
+ FakeLanguageModel.__call__.__globals__,
+ "_EXACT_SPECULATIVE_VERIFIER",
+ object(),
+ )
q35_lang = SimpleNamespace(LanguageModel=FakeLanguageModel)
qwen35_vlm_runtime._patch_vlm_language_model(q35_lang)
@@ -607,6 +611,7 @@ def __call__(
assert out.gdn_states is gdn_states
assert out.shared_kv_states == {}
assert model.forward_kwargs["capture_layer_ids"] == [1]
+ assert model.forward_kwargs["speculative_verify"] is True
# A block drafter's layers ride the same forward: requested order first,
# the head's last-layer hidden last.
@@ -1007,10 +1012,10 @@ class TestCallBackbone:
def test_tuple_2_return(self):
"""mlx-lm dense path returns (logits, hidden) 2-tuple."""
- from omlx.patches.mlx_lm_mtp.batch_generator import _call_backbone
-
import mlx.core as mx
+ from omlx.patches.mlx_lm_mtp.batch_generator import _call_backbone
+
logits = mx.zeros((1, 1, 100))
hidden = mx.zeros((1, 1, 64))
@@ -1022,10 +1027,10 @@ def test_tuple_2_return(self):
def test_tuple_3_return(self):
"""mlx-vlm MoE path returns (logits, hidden, gdn_states) 3-tuple."""
- from omlx.patches.mlx_lm_mtp.batch_generator import _call_backbone
-
import mlx.core as mx
+ from omlx.patches.mlx_lm_mtp.batch_generator import _call_backbone
+
logits = mx.zeros((1, 1, 100))
hidden = mx.zeros((1, 1, 64))
gdn = [{"state": "mock"}]
@@ -1038,11 +1043,11 @@ def test_tuple_3_return(self):
def test_language_model_output_return(self):
"""LanguageModelOutput is correctly unpacked."""
- from omlx.patches.mlx_lm_mtp.batch_generator import _call_backbone
-
import mlx.core as mx
from mlx_vlm.models.base import LanguageModelOutput
+ from omlx.patches.mlx_lm_mtp.batch_generator import _call_backbone
+
logits = mx.zeros((1, 1, 100))
hidden = mx.zeros((1, 1, 64))
gdn = [{"state": "mock"}]
@@ -1058,6 +1063,32 @@ def test_language_model_output_return(self):
assert result[1] is hidden
assert result[2] is gdn
+ def test_verify_uses_model_exact_speculative_path(self):
+ import mlx.core as mx
+
+ from omlx.patches.mlx_lm_mtp.batch_generator import _call_backbone
+
+ logits = mx.zeros((1, 3, 100))
+ hidden = mx.zeros((1, 3, 64))
+ rollback_state = object()
+ model = MagicMock()
+ model.speculative_verify_logits.return_value = (
+ hidden,
+ {},
+ rollback_state,
+ logits,
+ )
+ inputs = mx.zeros((1, 3), dtype=mx.uint32)
+ cache = [object()]
+
+ result = _call_backbone(model, inputs, cache, n_confirmed=1)
+
+ assert result[0] is logits
+ assert result[1] is hidden
+ assert result[2] is rollback_state
+ model.speculative_verify_logits.assert_called_once()
+ model.assert_not_called()
+
def test_qwen_external_round_clears_before_replay_and_commits_before_yield(monkeypatch):
from mlx_vlm.speculative.mtp import _MTPVerifyResult
diff --git a/tests/test_vlm_native_mtp.py b/tests/test_vlm_native_mtp.py
new file mode 100644
index 0000000000..ac7f767765
--- /dev/null
+++ b/tests/test_vlm_native_mtp.py
@@ -0,0 +1,286 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Fast wiring tests for native-head MTP through ``VLMBatchedEngine``.
+
+The VLM model and checkpoint index are lightweight stand-ins: no model weights
+are loaded, and no mlx-vlm generation helper is allowed to run.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from types import SimpleNamespace
+
+import pytest
+
+from omlx.engine.vlm import _report_native_vlm_mtp_readiness
+from omlx.models.vlm import VLMModelAdapter
+from omlx.patches.mlx_lm_mtp import batch_generator
+from omlx.scheduler import _record_native_mtp_request_eligibility
+from omlx.utils.model_loading import (
+ _checkpoint_has_mtp_weights,
+ _native_vlm_mtp_eligible,
+)
+
+_TARGET_CONFIG = {
+ "model_type": "qwen3_5",
+ "vision_config": {},
+ "text_config": {"mtp_num_hidden_layers": 1},
+}
+
+
+def _write_checkpoint_index(tmp_path, tensor_keys: list[str]) -> None:
+ weight_map = {key: "model-00001-of-00001.safetensors" for key in tensor_keys}
+ (tmp_path / "model.safetensors.index.json").write_text(
+ json.dumps({"metadata": {}, "weight_map": weight_map})
+ )
+
+
+def _make_adapter() -> VLMModelAdapter:
+ """Build a minimal mlx-vlm-shaped model for adapter state tests."""
+ language_model = SimpleNamespace(
+ args=SimpleNamespace(),
+ model=SimpleNamespace(layers=[]),
+ )
+ vlm_model = SimpleNamespace(
+ config=SimpleNamespace(model_type="qwen3_5"),
+ language_model=language_model,
+ )
+ return VLMModelAdapter(vlm_model)
+
+
+# ---------------------------------------------------------------------------
+# Phase 1: construction-time config/settings/tensor gate
+# ---------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize(
+ ("config", "settings_enabled", "tensor_keys", "expected"),
+ [
+ pytest.param(
+ _TARGET_CONFIG,
+ True,
+ ["language_model.mtp.layers.0.self_attn.q_proj.weight"],
+ True,
+ id="target-positive",
+ ),
+ pytest.param(
+ _TARGET_CONFIG,
+ True,
+ ["language_model.model.embed_tokens.weight"],
+ False,
+ id="head-stripped-negative",
+ ),
+ pytest.param(
+ _TARGET_CONFIG,
+ False,
+ ["language_model.mtp.layers.0.self_attn.q_proj.weight"],
+ False,
+ id="settings-off-negative",
+ ),
+ pytest.param(
+ {
+ "model_type": "qwen3_5",
+ "vision_config": {},
+ "text_config": {},
+ },
+ True,
+ ["language_model.mtp.layers.0.self_attn.q_proj.weight"],
+ False,
+ id="config-heads-missing-negative",
+ ),
+ pytest.param(
+ {"model_type": "llama", "mtp_num_hidden_layers": 1},
+ True,
+ ["language_model.mtp.layers.0.self_attn.q_proj.weight"],
+ False,
+ id="unsupported-family-negative",
+ ),
+ ],
+)
+def test_native_vlm_mtp_eligibility_matrix(
+ tmp_path,
+ config,
+ settings_enabled,
+ tensor_keys,
+ expected,
+):
+ """Native VLM decode requires config, setting, and persisted head tensors."""
+ (tmp_path / "config.json").write_text(json.dumps(config))
+ _write_checkpoint_index(tmp_path, tensor_keys)
+
+ has_mtp_weights = _checkpoint_has_mtp_weights(tmp_path)
+ settings = SimpleNamespace(mtp_enabled=settings_enabled)
+
+ assert (
+ _native_vlm_mtp_eligible(
+ config,
+ config.get("model_type"),
+ settings,
+ has_mtp_weights=has_mtp_weights,
+ )
+ is expected
+ )
+
+
+# ---------------------------------------------------------------------------
+# Phase 2: per-row text/embeddings gate and UID lifecycle
+# ---------------------------------------------------------------------------
+
+
+def test_native_vlm_mtp_per_row_gate_and_uid_cleanup():
+ """Text rows may speculate; vision/mixed batches cannot; retirement cleans up."""
+ adapter = _make_adapter()
+ text_uid = 101
+ vision_uid = 202
+
+ _record_native_mtp_request_eligibility(
+ adapter,
+ text_uid,
+ SimpleNamespace(vlm_inputs_embeds=None),
+ )
+ _record_native_mtp_request_eligibility(
+ adapter,
+ vision_uid,
+ SimpleNamespace(vlm_inputs_embeds=object()),
+ )
+
+ assert adapter.native_mtp_allowed_for_uids([text_uid]) is True
+ assert adapter.native_mtp_allowed_for_uids([vision_uid]) is False
+ assert adapter.native_mtp_allowed_for_uids([text_uid, vision_uid]) is False
+
+ # Exercise BatchGenerator's shared singleton/row-wise eligibility choke
+ # point, not only the adapter's set membership helper.
+ model = SimpleNamespace(
+ mtp=object(),
+ mtp_forward=lambda *_args, **_kwargs: None,
+ _omlx_mtp_decode_enabled=True,
+ native_mtp_allowed_for_uids=adapter.native_mtp_allowed_for_uids,
+ )
+ generation_batch = SimpleNamespace(
+ model=model,
+ uids=[text_uid],
+ logits_processors=[],
+ )
+ assert batch_generator._mtp_common_eligible(generation_batch) is True
+
+ generation_batch.uids = [vision_uid]
+ assert batch_generator._mtp_common_eligible(generation_batch) is False
+
+ generation_batch.uids = [text_uid, vision_uid]
+ assert batch_generator._mtp_common_eligible(generation_batch) is False
+
+ adapter._uid_rope_deltas[vision_uid] = 3.0
+ adapter.unregister_rope_delta(vision_uid)
+ assert vision_uid not in adapter._uid_rope_deltas
+ assert vision_uid not in adapter._native_mtp_disabled_uids
+ assert adapter.native_mtp_allowed_for_uids([vision_uid]) is True
+
+
+# ---------------------------------------------------------------------------
+# Phase 3: strict post-load readiness and fail-soft fallback
+# ---------------------------------------------------------------------------
+
+
+def test_native_vlm_mtp_readiness_logs_ready(caplog):
+ """A bound head, decode marker, adapter method, and tensor index report ready."""
+ adapter = SimpleNamespace(
+ _language_model=SimpleNamespace(
+ mtp=object(),
+ _omlx_mtp_decode_enabled=True,
+ ),
+ mtp_forward=lambda *_args, **_kwargs: None,
+ )
+
+ with caplog.at_level(logging.INFO, logger="omlx.engine.vlm"):
+ ready = _report_native_vlm_mtp_readiness(
+ "/models/qwen3.8-27b-oq6-mtp",
+ adapter,
+ has_mtp_weights=True,
+ )
+
+ assert ready is True
+ assert "Native VLM MTP ready" in caplog.text
+
+
+def test_native_vlm_mtp_readiness_accepts_owner_bound_head(caplog):
+ head = object()
+ adapter = SimpleNamespace(
+ _language_model=SimpleNamespace(
+ get_mtp_module=lambda: head,
+ _omlx_mtp_decode_enabled=True,
+ ),
+ mtp_forward=lambda *_args, **_kwargs: None,
+ )
+
+ with caplog.at_level(logging.INFO, logger="omlx.engine.vlm"):
+ ready = _report_native_vlm_mtp_readiness(
+ "/models/qwen3.8-flash-next-mtp",
+ adapter,
+ has_mtp_weights=True,
+ )
+
+ assert ready is True
+ assert "Native VLM MTP ready" in caplog.text
+
+
+@pytest.mark.parametrize(
+ ("has_head", "has_adapter_bridge"),
+ [(False, True), (True, False)],
+ ids=("missing-loaded-head", "missing-adapter-bridge"),
+)
+def test_native_vlm_mtp_readiness_failure_keeps_standard_decode(
+ caplog,
+ has_head,
+ has_adapter_bridge,
+):
+ """An incomplete strict load warns and remains on GenerationBatch decode."""
+ mtp_head = object() if has_head else None
+ language_model = SimpleNamespace(
+ mtp=mtp_head,
+ _omlx_mtp_decode_enabled=True,
+ )
+ adapter_attrs = {
+ "_language_model": language_model,
+ "mtp": mtp_head,
+ }
+ if has_adapter_bridge:
+ adapter_attrs["mtp_forward"] = lambda *_args, **_kwargs: None
+ adapter = SimpleNamespace(**adapter_attrs)
+
+ with caplog.at_level(logging.WARNING, logger="omlx.engine.vlm"):
+ ready = _report_native_vlm_mtp_readiness(
+ "/models/incomplete-native-mtp",
+ adapter,
+ has_mtp_weights=True,
+ )
+
+ assert ready is False
+ assert "readiness gate failed" in caplog.text
+ assert "standard decode remains active" in caplog.text
+
+ generation_batch = SimpleNamespace(
+ model=adapter,
+ uids=[1],
+ logits_processors=[],
+ )
+ assert batch_generator._mtp_common_eligible(generation_batch) is False
+
+
+def test_incompatible_optional_inkling_patch_does_not_block_qwen(monkeypatch):
+ """An mlx-vlm Inkling API drift must fail closed instead of aborting Qwen load."""
+ from omlx.patches.mlx_vlm_mtp import inkling_vlm_runtime
+
+ monkeypatch.setattr(inkling_vlm_runtime, "_APPLIED", False)
+ monkeypatch.setattr(inkling_vlm_runtime, "apply_sanitize", lambda: True)
+
+ def incompatible_api(_inkling_pkg):
+ raise AttributeError("missing optional Inkling runtime symbol")
+
+ monkeypatch.setattr(
+ inkling_vlm_runtime,
+ "_patch_model_config",
+ incompatible_api,
+ )
+
+ assert inkling_vlm_runtime.apply() is False
diff --git a/tests/test_vlm_qwen4_exp_loader.py b/tests/test_vlm_qwen4_exp_loader.py
index 31545c9b84..1f07ceabb8 100644
--- a/tests/test_vlm_qwen4_exp_loader.py
+++ b/tests/test_vlm_qwen4_exp_loader.py
@@ -11,8 +11,9 @@
pytest.importorskip("mlx.core")
from omlx.engine import vlm as vlm_module
-from omlx.engine.vlm import VLMBatchedEngine
+from omlx.engine.vlm import VLMBatchedEngine, _force_qwen4_exp_sanitize_on_load
from omlx.exceptions import InvalidRequestError
+from omlx.model_settings import ModelSettings
from omlx.utils.model_loading import maybe_apply_pre_load_patches
@@ -117,7 +118,7 @@ def stop_after_load(model_name, **kwargs):
assert captured["lazy"] is expected_lazy
-def test_qwen4_exp_loader_enables_adaptive_depth_three_lightning_mtp(tmp_path):
+def test_qwen4_exp_loader_defaults_to_depth_three_without_sidecar_contract(tmp_path):
(tmp_path / "config.json").write_text(
json.dumps(
{
@@ -156,6 +157,125 @@ def test_qwen4_exp_loader_enables_adaptive_depth_three_lightning_mtp(tmp_path):
assert is_mtp_active() is False
+def test_qwen4_exp_loader_detects_and_loads_standalone_mtp(tmp_path, monkeypatch):
+ (tmp_path / "config.json").write_text(
+ json.dumps(
+ {
+ "model_type": "qwen4_exp",
+ "text_config": {
+ "model_type": "qwen4_exp_text",
+ "mtp_num_hidden_layers": 1,
+ },
+ }
+ ),
+ encoding="utf-8",
+ )
+ parent_weights = tmp_path / "model.safetensors"
+ parent_weights.touch()
+ mtp_dir = tmp_path / "mtp"
+ mtp_dir.mkdir()
+ (mtp_dir / "config.json").write_text(
+ json.dumps({"model_type": "qwen4_exp_mtp", "block_size": 2}),
+ encoding="utf-8",
+ )
+ mtp_weights = mtp_dir / "model.safetensors"
+ mtp_weights.touch()
+
+ import mlx_vlm.utils as vlm_utils
+
+ def fake_load_safetensors(path):
+ if str(path).endswith("/mtp/model.safetensors"):
+ return {"fc_embedding.weight": "mtp-weight"}
+ return {"language_model.lm_head.weight": "parent-weight"}
+
+ monkeypatch.setattr(vlm_utils, "_load_safetensors", fake_load_safetensors)
+ monkeypatch.setattr(
+ "omlx.utils.model_loading._checkpoint_weight_prefix",
+ lambda path, prefixes: (
+ "fc_embedding."
+ if path == mtp_dir and "fc_embedding." in prefixes
+ else None
+ ),
+ )
+ settings = SimpleNamespace(mtp_enabled=True, mtp_adaptive_max_depth=None)
+
+ maybe_apply_pre_load_patches(str(tmp_path), settings, for_vlm=True)
+
+ from mlx_vlm.models.qwen4_exp.language import get_mtp_runtime
+
+ from omlx.patches.mlx_lm_mtp import get_mtp_depth
+
+ assert get_mtp_runtime().checkpoint_prefix == "mtp/"
+ assert get_mtp_depth() == 1
+
+ maybe_apply_pre_load_patches(
+ str(tmp_path),
+ ModelSettings(mtp_enabled=True, mtp_adaptive_max_depth=3),
+ for_vlm=True,
+ )
+ assert get_mtp_depth() == 3
+
+ with _force_qwen4_exp_sanitize_on_load(tmp_path):
+ loaded = vlm_utils._load_safetensors(str(parent_weights))
+
+ assert loaded == {
+ "language_model.lm_head.weight": "parent-weight",
+ "mtp.fc_embedding.weight": "mtp-weight",
+ }
+
+
+@pytest.mark.parametrize(
+ ("sidecar_content", "warning"),
+ [
+ ("{", None),
+ (b"\xff", None),
+ ("[]", "must contain an object"),
+ (
+ json.dumps({"model_type": "qwen4_exp_mtp", "block_size": "2"}),
+ "invalid block_size",
+ ),
+ ],
+)
+def test_qwen4_exp_loader_safely_falls_back_for_invalid_sidecar_contract(
+ tmp_path, caplog, sidecar_content, warning
+):
+ (tmp_path / "config.json").write_text(
+ json.dumps(
+ {
+ "model_type": "qwen4_exp",
+ "text_config": {
+ "model_type": "qwen4_exp_text",
+ "mtp_num_hidden_layers": 1,
+ },
+ }
+ ),
+ encoding="utf-8",
+ )
+ (tmp_path / "model.safetensors.index.json").write_text(
+ json.dumps({"weight_map": {"mtp.fc_hidden.weight": "model.safetensors"}}),
+ encoding="utf-8",
+ )
+ mtp_dir = tmp_path / "mtp"
+ mtp_dir.mkdir()
+ sidecar_config_path = mtp_dir / "config.json"
+ if isinstance(sidecar_content, bytes):
+ sidecar_config_path.write_bytes(sidecar_content)
+ else:
+ sidecar_config_path.write_text(sidecar_content, encoding="utf-8")
+
+ maybe_apply_pre_load_patches(
+ str(tmp_path),
+ ModelSettings(mtp_enabled=True),
+ for_vlm=True,
+ )
+
+ from omlx.patches.mlx_lm_mtp import get_mtp_depth
+
+ assert get_mtp_depth() == 3
+ if warning is not None:
+ assert warning in caplog.text
+
+
def test_qwen4_exp_loader_uses_explicit_ple_ssd_offload_setting(tmp_path):
(tmp_path / "config.json").write_text(
json.dumps({"model_type": "qwen4_exp"}), encoding="utf-8"
From aa88431acf2f92e1a7575cc597711fb5617ef423 Mon Sep 17 00:00:00 2001
From: Mike Wallio
Date: Wed, 4 Nov 2026 09:15:01 -0500
Subject: [PATCH 05/24] feat(image): add generation, editing, and translated
Imagine UI
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
---
apps/omlx-web/omlx_web/i18n/cs.json | 74 +-
apps/omlx-web/omlx_web/i18n/de.json | 74 +-
apps/omlx-web/omlx_web/i18n/en.json | 74 +-
apps/omlx-web/omlx_web/i18n/es.json | 74 +-
apps/omlx-web/omlx_web/i18n/fr.json | 74 +-
apps/omlx-web/omlx_web/i18n/ja.json | 74 +-
apps/omlx-web/omlx_web/i18n/ko.json | 74 +-
apps/omlx-web/omlx_web/i18n/pt-BR.json | 74 +-
apps/omlx-web/omlx_web/i18n/ru.json | 74 +-
apps/omlx-web/omlx_web/i18n/zh-TW.json | 74 +-
apps/omlx-web/omlx_web/i18n/zh.json | 74 +-
apps/omlx-web/omlx_web/templates/imagine.html | 974 ++++++++++++++
omlx/api/image_models.py | 246 ++++
omlx/api/image_routes.py | 1008 ++++++++++++++
omlx/engine/image.py | 648 +++++++++
omlx/image_registry.py | 345 +++++
omlx/patches/mlx_vlm_image_compat/README.md | 13 +
omlx/patches/mlx_vlm_image_compat/__init__.py | 76 ++
.../mlx_vlm_qwen_image_compat/__init__.py | 101 ++
.../mlx_vlm_qwen_image_compat/_backport.py | 811 +++++++++++
.../generate_backport.py | 130 ++
tests/test_admin_imagine.py | 349 +++++
tests/test_image_api.py | 1191 +++++++++++++++++
tests/test_image_engine.py | 563 ++++++++
tests/test_image_models.py | 204 +++
tests/test_image_registry.py | 404 ++++++
tests/test_image_utils.py | 140 +-
tests/test_mlx_vlm_image_compat.py | 453 +++++++
tests/test_qwen_image_compat.py | 425 ++++++
tests/test_qwen_image_source_hash.py | 65 +
30 files changed, 8947 insertions(+), 13 deletions(-)
create mode 100644 apps/omlx-web/omlx_web/templates/imagine.html
create mode 100644 omlx/api/image_models.py
create mode 100644 omlx/api/image_routes.py
create mode 100644 omlx/engine/image.py
create mode 100644 omlx/image_registry.py
create mode 100644 omlx/patches/mlx_vlm_image_compat/README.md
create mode 100644 omlx/patches/mlx_vlm_image_compat/__init__.py
create mode 100644 omlx/patches/mlx_vlm_qwen_image_compat/__init__.py
create mode 100644 omlx/patches/mlx_vlm_qwen_image_compat/_backport.py
create mode 100644 omlx/patches/mlx_vlm_qwen_image_compat/generate_backport.py
create mode 100644 tests/test_admin_imagine.py
create mode 100644 tests/test_image_api.py
create mode 100644 tests/test_image_engine.py
create mode 100644 tests/test_image_models.py
create mode 100644 tests/test_image_registry.py
create mode 100644 tests/test_mlx_vlm_image_compat.py
create mode 100644 tests/test_qwen_image_compat.py
create mode 100644 tests/test_qwen_image_source_hash.py
diff --git a/apps/omlx-web/omlx_web/i18n/cs.json b/apps/omlx-web/omlx_web/i18n/cs.json
index 68c49eae8e..b303ee7ad0 100644
--- a/apps/omlx-web/omlx_web/i18n/cs.json
+++ b/apps/omlx-web/omlx_web/i18n/cs.json
@@ -2464,5 +2464,77 @@
"cluster.cuda_guide.windows_firewall": "In PowerShell as administrator, let this Mac reach the helper.",
"cluster.cuda_guide.windows_run": "Start the helper in PowerShell. It asks this Mac to pair: type the code from its log on this page. If this Mac has more than one address, use the one the PC can reach.",
"cluster.cuda_guide.spark_run": "DGX OS comes with Docker and the NVIDIA Container Toolkit. Start the helper. It appears on this page: press Pair on it and type the code from its log.",
- "cluster.device_card.helper_ready": "{name} can speed up long prompts for models on this Mac."
+ "cluster.device_card.helper_ready": "{name} can speed up long prompts for models on this Mac.",
+ "models.uploader.queue_loading": "Načítání úloh nahrávání...",
+ "models.uploader.queue_error": "Nahrávání nelze aktualizovat. Poslední zobrazený stav může být zastaralý.",
+ "models.uploader.queue_empty": "Žádné úlohy nahrávání. Seznam se aktualizuje automaticky.",
+ "models.uploader.queue_refresh": "Obnovit nahrávání",
+ "models.uploader.queue_activity": "Probíhá nahrávání. Průběh v bajtech není k dispozici.",
+ "modal.model_settings.minicpm_media": "Média MiniCPM",
+ "modal.model_settings.minicpm_downsample_mode": "Vizuální komprese",
+ "modal.model_settings.minicpm_downsample_mode_hint": "16x používá méně vizuálních tokenů; 4x zachovává více detailů. Výchozí volba používá procesor modelu.",
+ "modal.model_settings.minicpm_max_slice_nums": "Maximum obrazových výřezů",
+ "modal.model_settings.minicpm_max_slice_nums_hint": "Nastavte limit dělení obrázku (alespoň 1). Prázdná hodnota použije výchozí nastavení procesoru modelu.",
+ "imagine.welcome_description": "Zadejte pokyn místnímu obrazovému modelu a výsledek si prohlédněte a stáhněte.",
+ "imagine.upload_browse": "Procházet obrázky",
+ "modal.model_settings.moe_expert_offload_resident_25": "25 % v paměti",
+ "modal.model_settings.moe_expert_offload_resident_12_5": "12,5 % v paměti",
+ "imagine.submit.edit": "Upravit obrázek",
+ "imagine.title": "Imagine - Správa oMLX",
+ "imagine.advanced.title": "Pokročilé",
+ "imagine.error.image_too_large": "Obrázek musí být menší než 25 MB",
+ "modal.model_settings.model_type_image": "Obrázek",
+ "imagine.advanced.steps": "Počet kroků",
+ "imagine.checkpoint_schedule_hint": "Uložený plán modelu má přednost před počtem kroků. Plán lze změnit polem sigmas v API.",
+ "imagine.effective_steps": "Skutečný počet kroků",
+ "imagine.results_heading": "Výsledky",
+ "imagine.advanced.seed": "Seed",
+ "imagine.advanced.n": "Počet obrázků",
+ "imagine.upload_heading": "Referenční obrázky",
+ "imagine.brand": "oMLX Imagine",
+ "imagine.api_key_placeholder": "Zadejte API klíč...",
+ "imagine.change_api_key": "Změnit API klíč",
+ "modal.model_settings.moe_expert_offload_resident_75": "75 % v paměti",
+ "imagine.nav.chat": "Chat",
+ "imagine.error.invalid_image_type": "Vyberte soubor s obrázkem",
+ "imagine.nav.imagine": "Imagine",
+ "imagine.image_preview": "Náhled obrázku",
+ "imagine.timeline_model": "Model",
+ "imagine.api_key_prompt": "Pro tvorbu obrázků zadejte API klíč",
+ "imagine.submit.generating": "Generuji...",
+ "imagine.result.download": "Stáhnout",
+ "imagine.advanced.output_format": "Výstupní formát",
+ "imagine.timeline_prompt": "Zadání",
+ "imagine.mode.label": "Režim",
+ "imagine.original_image_alt": "Původní obrázek",
+ "imagine.select_model": "Obrazový model",
+ "imagine.welcome_heading": "Tvořte s oMLX",
+ "imagine.advanced.guidance": "Vedení",
+ "imagine.prompt_label": "Zadání",
+ "imagine.clear_results": "Vymazat výsledky",
+ "modal.model_settings.moe_expert_offload_resident_50": "50 % v paměti",
+ "imagine.advanced.negative_prompt": "Negativní zadání",
+ "imagine.timeline_original": "Originál",
+ "imagine.advanced.size": "Velikost",
+ "imagine.no_models_generation": "Nejsou dostupné žádné modely pro generování",
+ "imagine.heading": "Imagine",
+ "modal.model_settings.dflash_single_stream": "Pouze jeden proud: požadavky se zpracovávají postupně.",
+ "imagine.welcome_privacy": "Veškeré generování obrázků probíhá místně na vašem zařízení.",
+ "imagine.error.incorrect_api_key": "API klíč je nesprávný. Zadejte jej znovu.",
+ "imagine.result_image_alt": "Vygenerovaný obrázek",
+ "imagine.upload_help": "Přetáhněte sem referenční obrázky, vložte je nebo je vyberte.",
+ "imagine.subheading": "Generujte a upravujte obrázky pomocí místních modelů",
+ "imagine.prompt_placeholder": "Popište obrázek, který chcete vytvořit...",
+ "imagine.timeline_edited": "Upravený výsledek",
+ "navbar.tab.imagine": "Imagine",
+ "imagine.no_models_edit": "Nejsou dostupné žádné modely pro úpravy",
+ "imagine.mode.generate": "Vygenerovat",
+ "imagine.result.copy": "Kopírovat datovou URI",
+ "imagine.mode.edit": "Upravit",
+ "imagine.submit.editing": "Upravuji...",
+ "imagine.remove_image": "Odebrat obrázek",
+ "imagine.timeline_generated": "Vygenerovaný výsledek",
+ "imagine.api_key_continue": "Pokračovat",
+ "imagine.submit.generate": "Vygenerovat",
+ "imagine.admin_settings": "Nastavení správy"
}
diff --git a/apps/omlx-web/omlx_web/i18n/de.json b/apps/omlx-web/omlx_web/i18n/de.json
index ca2b495efc..f5d1098832 100644
--- a/apps/omlx-web/omlx_web/i18n/de.json
+++ b/apps/omlx-web/omlx_web/i18n/de.json
@@ -2464,5 +2464,77 @@
"cluster.cuda_guide.windows_firewall": "In PowerShell as administrator, let this Mac reach the helper.",
"cluster.cuda_guide.windows_run": "Start the helper in PowerShell. It asks this Mac to pair: type the code from its log on this page. If this Mac has more than one address, use the one the PC can reach.",
"cluster.cuda_guide.spark_run": "DGX OS comes with Docker and the NVIDIA Container Toolkit. Start the helper. It appears on this page: press Pair on it and type the code from its log.",
- "cluster.device_card.helper_ready": "{name} can speed up long prompts for models on this Mac."
+ "cluster.device_card.helper_ready": "{name} can speed up long prompts for models on this Mac.",
+ "models.uploader.queue_loading": "Upload-Aufgaben werden geladen...",
+ "models.uploader.queue_error": "Uploads konnten nicht aktualisiert werden. Der zuletzt angezeigte Status ist möglicherweise veraltet.",
+ "models.uploader.queue_empty": "Keine Upload-Aufgaben. Diese Liste wird automatisch aktualisiert.",
+ "models.uploader.queue_refresh": "Uploads aktualisieren",
+ "models.uploader.queue_activity": "Upload läuft. Ein Fortschritt auf Byte-Ebene ist nicht verfügbar.",
+ "modal.model_settings.minicpm_media": "MiniCPM-Medien",
+ "modal.model_settings.minicpm_downsample_mode": "Visuelle Komprimierung",
+ "modal.model_settings.minicpm_downsample_mode_hint": "16x verwendet weniger visuelle Tokens; 4x bewahrt mehr Details. Standard verwendet den Modellprozessor.",
+ "modal.model_settings.minicpm_max_slice_nums": "Maximale Bildausschnitte",
+ "modal.model_settings.minicpm_max_slice_nums_hint": "Legen Sie die maximale Anzahl der Bildausschnitte fest (mindestens 1). Leer lassen, um den Standard des Modellprozessors zu verwenden.",
+ "imagine.admin_settings": "Admin-Einstellungen",
+ "imagine.advanced.guidance": "Guidance",
+ "imagine.advanced.n": "Bilder",
+ "imagine.advanced.negative_prompt": "Negativer Prompt",
+ "imagine.advanced.output_format": "Ausgabeformat",
+ "imagine.advanced.seed": "Seed",
+ "imagine.advanced.size": "Größe",
+ "imagine.advanced.steps": "Schritte",
+ "imagine.checkpoint_schedule_hint": "Der im Checkpoint gespeicherte Zeitplan hat Vorrang vor den Schritten. Verwenden Sie das API-Feld sigmas, um den Zeitplan zu ändern.",
+ "imagine.effective_steps": "Tatsächliche Schritte",
+ "imagine.advanced.title": "Erweitert",
+ "imagine.api_key_continue": "Weiter",
+ "imagine.api_key_placeholder": "API-Schlüssel eingeben...",
+ "imagine.api_key_prompt": "Geben Sie Ihren API-Schlüssel ein, um Bilder zu erstellen",
+ "imagine.brand": "oMLX Imagine",
+ "imagine.change_api_key": "API-Schlüssel ändern",
+ "imagine.clear_results": "Ergebnisse löschen",
+ "imagine.error.image_too_large": "Die Bildgröße muss unter 25 MB liegen",
+ "imagine.error.incorrect_api_key": "Der API-Schlüssel ist falsch. Bitte geben Sie ihn erneut ein.",
+ "imagine.error.invalid_image_type": "Bitte wählen Sie eine Bilddatei aus",
+ "imagine.heading": "Imagine",
+ "imagine.image_preview": "Bildvorschau",
+ "imagine.mode.edit": "Bearbeiten",
+ "imagine.mode.generate": "Generieren",
+ "imagine.mode.label": "Modus",
+ "imagine.nav.chat": "Chat",
+ "imagine.nav.imagine": "Imagine",
+ "imagine.no_models_edit": "Keine Modelle zur Bildbearbeitung verfügbar",
+ "imagine.no_models_generation": "Keine Modelle zur Bilderzeugung verfügbar",
+ "imagine.original_image_alt": "Originalbild",
+ "imagine.prompt_label": "Prompt",
+ "imagine.prompt_placeholder": "Beschreiben Sie das gewünschte Bild...",
+ "imagine.remove_image": "Bild entfernen",
+ "imagine.result.copy": "Daten-URI kopieren",
+ "imagine.result.download": "Herunterladen",
+ "imagine.result_image_alt": "Generiertes Bild",
+ "imagine.results_heading": "Ergebnisse",
+ "imagine.select_model": "Bildmodell",
+ "imagine.subheading": "Bilder mit lokalen Bildmodellen generieren und bearbeiten",
+ "imagine.submit.edit": "Bild bearbeiten",
+ "imagine.submit.editing": "Wird bearbeitet...",
+ "imagine.submit.generate": "Generieren",
+ "imagine.submit.generating": "Wird generiert...",
+ "imagine.timeline_edited": "Bearbeitetes Ergebnis",
+ "imagine.timeline_generated": "Generiertes Ergebnis",
+ "imagine.timeline_model": "Modell",
+ "imagine.timeline_original": "Original",
+ "imagine.timeline_prompt": "Prompt",
+ "imagine.title": "Imagine - oMLX Admin",
+ "imagine.upload_browse": "Bilder durchsuchen",
+ "imagine.upload_heading": "Referenzbilder",
+ "imagine.upload_help": "Referenzbilder hier ablegen, einfügen oder auswählen.",
+ "imagine.welcome_description": "Geben Sie einem lokalen Bildmodell einen Prompt, um das Ergebnis anzuzeigen und herunterzuladen.",
+ "imagine.welcome_heading": "Imagine mit oMLX",
+ "imagine.welcome_privacy": "Alle Bilder werden lokal auf Ihrem Gerät generiert.",
+ "modal.model_settings.dflash_single_stream": "Nur ein Stream: Anfragen werden nacheinander verarbeitet.",
+ "modal.model_settings.moe_expert_offload_resident_12_5": "12,5 % resident",
+ "modal.model_settings.moe_expert_offload_resident_25": "25 % resident",
+ "modal.model_settings.moe_expert_offload_resident_50": "50 % resident",
+ "modal.model_settings.moe_expert_offload_resident_75": "75 % resident",
+ "navbar.tab.imagine": "Imagine",
+ "modal.model_settings.model_type_image": "Bild"
}
diff --git a/apps/omlx-web/omlx_web/i18n/en.json b/apps/omlx-web/omlx_web/i18n/en.json
index 2e374abed6..56466574b2 100644
--- a/apps/omlx-web/omlx_web/i18n/en.json
+++ b/apps/omlx-web/omlx_web/i18n/en.json
@@ -2464,5 +2464,77 @@
"cluster.cuda_guide.windows_firewall": "In PowerShell as administrator, let this Mac reach the helper.",
"cluster.cuda_guide.windows_run": "Start the helper in PowerShell. It asks this Mac to pair: type the code from its log on this page. If this Mac has more than one address, use the one the PC can reach.",
"cluster.cuda_guide.spark_run": "DGX OS comes with Docker and the NVIDIA Container Toolkit. Start the helper. It appears on this page: press Pair on it and type the code from its log.",
- "cluster.device_card.helper_ready": "{name} can speed up long prompts for models on this Mac."
+ "cluster.device_card.helper_ready": "{name} can speed up long prompts for models on this Mac.",
+ "models.uploader.queue_loading": "Loading upload tasks...",
+ "models.uploader.queue_error": "Unable to refresh uploads. Last shown status may be out of date.",
+ "models.uploader.queue_empty": "No upload tasks. This list refreshes automatically.",
+ "models.uploader.queue_refresh": "Refresh uploads",
+ "models.uploader.queue_activity": "Upload in progress. Byte-level progress is unavailable.",
+ "modal.model_settings.minicpm_media": "MiniCPM Media",
+ "modal.model_settings.minicpm_downsample_mode": "Visual Compression",
+ "modal.model_settings.minicpm_downsample_mode_hint": "16x uses fewer visual tokens; 4x preserves more detail. Default uses the model processor.",
+ "modal.model_settings.minicpm_max_slice_nums": "Maximum Image Slices",
+ "modal.model_settings.minicpm_max_slice_nums_hint": "Set the image slicing limit (at least 1). Leave empty for the model processor default.",
+ "imagine.admin_settings": "Admin Settings",
+ "imagine.advanced.guidance": "Guidance",
+ "imagine.advanced.n": "Images",
+ "imagine.advanced.negative_prompt": "Negative Prompt",
+ "imagine.advanced.output_format": "Output Format",
+ "imagine.advanced.seed": "Seed",
+ "imagine.advanced.size": "Size",
+ "imagine.advanced.steps": "Steps",
+ "imagine.checkpoint_schedule_hint": "The saved checkpoint schedule overrides Steps. Use the API sigmas field to change the schedule.",
+ "imagine.effective_steps": "Actual steps",
+ "imagine.advanced.title": "Advanced",
+ "imagine.api_key_continue": "Continue",
+ "imagine.api_key_placeholder": "Enter API key...",
+ "imagine.api_key_prompt": "Enter your API key to start creating images",
+ "imagine.brand": "oMLX Imagine",
+ "imagine.change_api_key": "Change API Key",
+ "imagine.clear_results": "Clear Results",
+ "imagine.error.image_too_large": "Image size must be less than 25MB",
+ "imagine.error.incorrect_api_key": "API key is incorrect. Please re-enter your API key.",
+ "imagine.error.invalid_image_type": "Please select an image file",
+ "imagine.heading": "Imagine",
+ "imagine.image_preview": "Image preview",
+ "imagine.mode.edit": "Edit",
+ "imagine.mode.generate": "Generate",
+ "imagine.mode.label": "Mode",
+ "imagine.nav.chat": "Chat",
+ "imagine.nav.imagine": "Imagine",
+ "imagine.no_models_edit": "No edit models available",
+ "imagine.no_models_generation": "No generation models available",
+ "imagine.original_image_alt": "Original image",
+ "imagine.prompt_label": "Prompt",
+ "imagine.prompt_placeholder": "Describe the image you want...",
+ "imagine.remove_image": "Remove image",
+ "imagine.result.copy": "Copy Data URI",
+ "imagine.result.download": "Download",
+ "imagine.result_image_alt": "Generated image",
+ "imagine.results_heading": "Results",
+ "imagine.select_model": "Image Model",
+ "imagine.subheading": "Generate and edit images with local image models",
+ "imagine.submit.edit": "Edit Image",
+ "imagine.submit.editing": "Editing...",
+ "imagine.submit.generate": "Generate",
+ "imagine.submit.generating": "Generating...",
+ "imagine.timeline_edited": "Edited result",
+ "imagine.timeline_generated": "Generated result",
+ "imagine.timeline_model": "Model",
+ "imagine.timeline_original": "Original",
+ "imagine.timeline_prompt": "Prompt",
+ "imagine.title": "Imagine - oMLX Admin",
+ "imagine.upload_browse": "Browse Images",
+ "imagine.upload_heading": "Reference Images",
+ "imagine.upload_help": "Drop reference images here, paste, or browse.",
+ "imagine.welcome_description": "Prompt a local image model, then preview and download the result.",
+ "imagine.welcome_heading": "Imagine with oMLX",
+ "imagine.welcome_privacy": "All image generation runs locally on your device.",
+ "modal.model_settings.dflash_single_stream": "Single-stream only: requests run one at a time.",
+ "modal.model_settings.moe_expert_offload_resident_12_5": "12.5% resident",
+ "modal.model_settings.moe_expert_offload_resident_25": "25% resident",
+ "modal.model_settings.moe_expert_offload_resident_50": "50% resident",
+ "modal.model_settings.moe_expert_offload_resident_75": "75% resident",
+ "navbar.tab.imagine": "Imagine",
+ "modal.model_settings.model_type_image": "Image"
}
diff --git a/apps/omlx-web/omlx_web/i18n/es.json b/apps/omlx-web/omlx_web/i18n/es.json
index 1f348f3017..7b7b164125 100644
--- a/apps/omlx-web/omlx_web/i18n/es.json
+++ b/apps/omlx-web/omlx_web/i18n/es.json
@@ -2464,5 +2464,77 @@
"cluster.cuda_guide.windows_firewall": "In PowerShell as administrator, let this Mac reach the helper.",
"cluster.cuda_guide.windows_run": "Start the helper in PowerShell. It asks this Mac to pair: type the code from its log on this page. If this Mac has more than one address, use the one the PC can reach.",
"cluster.cuda_guide.spark_run": "DGX OS comes with Docker and the NVIDIA Container Toolkit. Start the helper. It appears on this page: press Pair on it and type the code from its log.",
- "cluster.device_card.helper_ready": "{name} can speed up long prompts for models on this Mac."
+ "cluster.device_card.helper_ready": "{name} can speed up long prompts for models on this Mac.",
+ "models.uploader.queue_loading": "Cargando tareas de subida...",
+ "models.uploader.queue_error": "No se pudieron actualizar las subidas. El último estado mostrado puede estar desactualizado.",
+ "models.uploader.queue_empty": "No hay tareas de subida. Esta lista se actualiza automáticamente.",
+ "models.uploader.queue_refresh": "Actualizar subidas",
+ "models.uploader.queue_activity": "Subida en curso. El progreso en bytes no está disponible.",
+ "modal.model_settings.minicpm_media": "Medios MiniCPM",
+ "modal.model_settings.minicpm_downsample_mode": "Compresión visual",
+ "modal.model_settings.minicpm_downsample_mode_hint": "16x usa menos tokens visuales; 4x conserva más detalles. La opción predeterminada usa el procesador del modelo.",
+ "modal.model_settings.minicpm_max_slice_nums": "Máximo de segmentos de imagen",
+ "modal.model_settings.minicpm_max_slice_nums_hint": "Establece el límite de segmentación de imágenes (al menos 1). Déjalo vacío para usar el valor predeterminado del procesador del modelo.",
+ "imagine.welcome_description": "Usa un modelo local de imágenes y descarga el resultado.",
+ "imagine.upload_browse": "Buscar imágenes",
+ "modal.model_settings.moe_expert_offload_resident_25": "25% resident",
+ "modal.model_settings.moe_expert_offload_resident_12_5": "12.5% resident",
+ "imagine.submit.edit": "Editar imagen",
+ "imagine.title": "Imagine - oMLX Admin",
+ "imagine.advanced.title": "Avanzado",
+ "imagine.error.image_too_large": "El tamaño de la imagen debe ser menor a 25MB",
+ "modal.model_settings.model_type_image": "Imagen",
+ "imagine.advanced.steps": "Pasos",
+ "imagine.checkpoint_schedule_hint": "El programa guardado del modelo tiene prioridad sobre los pasos. Cámbialo con el campo sigmas de la API.",
+ "imagine.effective_steps": "Pasos reales",
+ "imagine.results_heading": "Resultados",
+ "imagine.advanced.seed": "Seed",
+ "imagine.advanced.n": "Imágenes",
+ "imagine.upload_heading": "Imágenes de referencia",
+ "imagine.brand": "oMLX Imagine",
+ "imagine.api_key_placeholder": "Ingresa la clave API...",
+ "imagine.change_api_key": "Cambiar Clave API",
+ "modal.model_settings.moe_expert_offload_resident_75": "75% resident",
+ "imagine.nav.chat": "Chat",
+ "imagine.error.invalid_image_type": "Por favor selecciona un archivo de imagen",
+ "imagine.nav.imagine": "Imagine",
+ "imagine.image_preview": "Vista previa de la imagen",
+ "imagine.timeline_model": "Modelo",
+ "imagine.api_key_prompt": "Ingresa tu clave API para comenzar a crear imágenes",
+ "imagine.submit.generating": "Generando...",
+ "imagine.result.download": "Descargar",
+ "imagine.advanced.output_format": "Formato de salida",
+ "imagine.timeline_prompt": "Prompt",
+ "imagine.mode.label": "Modo",
+ "imagine.original_image_alt": "Imagen original",
+ "imagine.select_model": "Modelo de imagen",
+ "imagine.welcome_heading": "Imagine con oMLX",
+ "imagine.advanced.guidance": "Guía",
+ "imagine.prompt_label": "Prompt",
+ "imagine.clear_results": "Limpiar resultados",
+ "modal.model_settings.moe_expert_offload_resident_50": "50% resident",
+ "imagine.advanced.negative_prompt": "Prompt negativo",
+ "imagine.timeline_original": "Original",
+ "imagine.advanced.size": "Tamaño",
+ "imagine.no_models_generation": "No hay modelos de generación disponibles",
+ "imagine.heading": "Imagine",
+ "modal.model_settings.dflash_single_stream": "Single-stream only: requests run one at a time.",
+ "imagine.welcome_privacy": "Toda la generación de imágenes se ejecuta localmente en tu dispositivo.",
+ "imagine.error.incorrect_api_key": "La clave API es incorrecta. Por favor ingrésala nuevamente.",
+ "imagine.result_image_alt": "Imagen generada",
+ "imagine.upload_help": "Arrastra imágenes aquí, pega o explora.",
+ "imagine.subheading": "Genera y edita imágenes con modelos locales",
+ "imagine.prompt_placeholder": "Describe la imagen que quieres...",
+ "imagine.timeline_edited": "Resultado editado",
+ "navbar.tab.imagine": "Imagine",
+ "imagine.no_models_edit": "No hay modelos de edición disponibles",
+ "imagine.mode.generate": "Generar",
+ "imagine.result.copy": "Copiar Data URI",
+ "imagine.mode.edit": "Editar",
+ "imagine.submit.editing": "Editando...",
+ "imagine.remove_image": "Eliminar imagen",
+ "imagine.timeline_generated": "Resultado generado",
+ "imagine.api_key_continue": "Continuar",
+ "imagine.submit.generate": "Generar",
+ "imagine.admin_settings": "Configuración Admin"
}
diff --git a/apps/omlx-web/omlx_web/i18n/fr.json b/apps/omlx-web/omlx_web/i18n/fr.json
index a4550326d0..23d3fed213 100644
--- a/apps/omlx-web/omlx_web/i18n/fr.json
+++ b/apps/omlx-web/omlx_web/i18n/fr.json
@@ -2464,5 +2464,77 @@
"cluster.cuda_guide.windows_firewall": "In PowerShell as administrator, let this Mac reach the helper.",
"cluster.cuda_guide.windows_run": "Start the helper in PowerShell. It asks this Mac to pair: type the code from its log on this page. If this Mac has more than one address, use the one the PC can reach.",
"cluster.cuda_guide.spark_run": "DGX OS comes with Docker and the NVIDIA Container Toolkit. Start the helper. It appears on this page: press Pair on it and type the code from its log.",
- "cluster.device_card.helper_ready": "{name} can speed up long prompts for models on this Mac."
+ "cluster.device_card.helper_ready": "{name} can speed up long prompts for models on this Mac.",
+ "models.uploader.queue_loading": "Chargement des tâches d'envoi...",
+ "models.uploader.queue_error": "Impossible d'actualiser les envois. Le dernier état affiché peut être obsolète.",
+ "models.uploader.queue_empty": "Aucune tâche d'envoi. Cette liste s'actualise automatiquement.",
+ "models.uploader.queue_refresh": "Actualiser les envois",
+ "models.uploader.queue_activity": "Envoi en cours. La progression en octets n'est pas disponible.",
+ "modal.model_settings.minicpm_media": "Médias MiniCPM",
+ "modal.model_settings.minicpm_downsample_mode": "Compression visuelle",
+ "modal.model_settings.minicpm_downsample_mode_hint": "16x utilise moins de jetons visuels ; 4x préserve davantage de détails. L'option par défaut utilise le processeur du modèle.",
+ "modal.model_settings.minicpm_max_slice_nums": "Nombre maximal de découpes d'image",
+ "modal.model_settings.minicpm_max_slice_nums_hint": "Définissez la limite de découpage des images (au moins 1). Laissez vide pour utiliser la valeur par défaut du processeur du modèle.",
+ "imagine.admin_settings": "Paramètres d'administration",
+ "imagine.advanced.guidance": "Guidage",
+ "imagine.advanced.n": "Images",
+ "imagine.advanced.negative_prompt": "Prompt négatif",
+ "imagine.advanced.output_format": "Format de sortie",
+ "imagine.advanced.seed": "Seed",
+ "imagine.advanced.size": "Taille",
+ "imagine.advanced.steps": "Étapes",
+ "imagine.checkpoint_schedule_hint": "Le calendrier enregistré du modèle prime sur les étapes. Utilisez le champ sigmas de l'API pour le modifier.",
+ "imagine.effective_steps": "Étapes réelles",
+ "imagine.advanced.title": "Avancé",
+ "imagine.api_key_continue": "Continuer",
+ "imagine.api_key_placeholder": "Entrez la clé API...",
+ "imagine.api_key_prompt": "Entrez votre clé API pour commencer à créer des images",
+ "imagine.brand": "oMLX Imagine",
+ "imagine.change_api_key": "Modifier la clé API",
+ "imagine.clear_results": "Effacer les résultats",
+ "imagine.error.image_too_large": "La taille de l'image doit être inférieure à 25 Mo",
+ "imagine.error.incorrect_api_key": "La clé API est incorrecte. Veuillez réentrer votre clé API.",
+ "imagine.error.invalid_image_type": "Veuillez sélectionner un fichier image",
+ "imagine.heading": "Imagine",
+ "imagine.image_preview": "Aperçu de l'image",
+ "imagine.mode.edit": "Modifier",
+ "imagine.mode.generate": "Générer",
+ "imagine.mode.label": "Mode",
+ "imagine.nav.chat": "Chat",
+ "imagine.nav.imagine": "Imagine",
+ "imagine.no_models_edit": "Aucun modèle d'édition disponible",
+ "imagine.no_models_generation": "Aucun modèle de génération disponible",
+ "imagine.original_image_alt": "Image originale",
+ "imagine.prompt_label": "Prompt",
+ "imagine.prompt_placeholder": "Décrivez l'image souhaitée...",
+ "imagine.remove_image": "Supprimer l'image",
+ "imagine.result.copy": "Copier le Data URI",
+ "imagine.result.download": "Télécharger",
+ "imagine.result_image_alt": "Image générée",
+ "imagine.results_heading": "Résultats",
+ "imagine.select_model": "Modèle image",
+ "imagine.subheading": "Générez et modifiez des images avec des modèles locaux",
+ "imagine.submit.edit": "Modifier l'image",
+ "imagine.submit.editing": "Modification...",
+ "imagine.submit.generate": "Générer",
+ "imagine.submit.generating": "Génération...",
+ "imagine.timeline_edited": "Résultat modifié",
+ "imagine.timeline_generated": "Résultat généré",
+ "imagine.timeline_model": "Modèle",
+ "imagine.timeline_original": "Original",
+ "imagine.timeline_prompt": "Invite",
+ "imagine.title": "Imagine - oMLX Admin",
+ "imagine.upload_browse": "Parcourir les images",
+ "imagine.upload_heading": "Images de référence",
+ "imagine.upload_help": "Déposez des images ici, collez ou parcourez.",
+ "imagine.welcome_description": "Utilisez un modèle image local, puis prévisualisez et téléchargez le résultat.",
+ "imagine.welcome_heading": "Imagine avec oMLX",
+ "imagine.welcome_privacy": "Toute génération d'image s'exécute localement sur votre appareil.",
+ "modal.model_settings.dflash_single_stream": "Single-stream only: requests run one at a time.",
+ "modal.model_settings.moe_expert_offload_resident_12_5": "12.5% resident",
+ "modal.model_settings.moe_expert_offload_resident_25": "25% resident",
+ "modal.model_settings.moe_expert_offload_resident_50": "50% resident",
+ "modal.model_settings.moe_expert_offload_resident_75": "75% resident",
+ "navbar.tab.imagine": "Imagine",
+ "modal.model_settings.model_type_image": "Image"
}
diff --git a/apps/omlx-web/omlx_web/i18n/ja.json b/apps/omlx-web/omlx_web/i18n/ja.json
index c66e45cbc7..066cfa42aa 100644
--- a/apps/omlx-web/omlx_web/i18n/ja.json
+++ b/apps/omlx-web/omlx_web/i18n/ja.json
@@ -2464,5 +2464,77 @@
"cluster.cuda_guide.windows_firewall": "In PowerShell as administrator, let this Mac reach the helper.",
"cluster.cuda_guide.windows_run": "Start the helper in PowerShell. It asks this Mac to pair: type the code from its log on this page. If this Mac has more than one address, use the one the PC can reach.",
"cluster.cuda_guide.spark_run": "DGX OS comes with Docker and the NVIDIA Container Toolkit. Start the helper. It appears on this page: press Pair on it and type the code from its log.",
- "cluster.device_card.helper_ready": "{name} can speed up long prompts for models on this Mac."
+ "cluster.device_card.helper_ready": "{name} can speed up long prompts for models on this Mac.",
+ "models.uploader.queue_loading": "アップロードタスクを読み込み中...",
+ "models.uploader.queue_error": "アップロード状態を更新できません。最後に表示された状態は古い可能性があります。",
+ "models.uploader.queue_empty": "アップロードタスクはありません。この一覧は自動的に更新されます。",
+ "models.uploader.queue_refresh": "アップロード状態を更新",
+ "models.uploader.queue_activity": "アップロード中です。バイト単位の進行状況は取得できません。",
+ "modal.model_settings.minicpm_media": "MiniCPM メディア",
+ "modal.model_settings.minicpm_downsample_mode": "視覚圧縮",
+ "modal.model_settings.minicpm_downsample_mode_hint": "16x は視覚トークンを削減し、4x はより多くの細部を保持します。デフォルトはモデルのプロセッサ設定を使用します。",
+ "modal.model_settings.minicpm_max_slice_nums": "画像スライス数の上限",
+ "modal.model_settings.minicpm_max_slice_nums_hint": "画像分割の上限を設定します(1 以上)。空欄の場合はモデルのプロセッサのデフォルトを使用します。",
+ "imagine.welcome_description": "ローカル画像モデルにプロンプトを送り、結果をプレビューしてダウンロードします。",
+ "imagine.upload_browse": "画像を選択",
+ "modal.model_settings.moe_expert_offload_resident_25": "25% resident",
+ "modal.model_settings.moe_expert_offload_resident_12_5": "12.5% resident",
+ "imagine.submit.edit": "画像を編集",
+ "imagine.title": "Imagine - oMLX 管理画面",
+ "imagine.advanced.title": "詳細",
+ "imagine.error.image_too_large": "画像サイズは25MB以下にしてください",
+ "modal.model_settings.model_type_image": "画像",
+ "imagine.advanced.steps": "ステップ",
+ "imagine.checkpoint_schedule_hint": "保存されたモデルのスケジュールがステップ数より優先されます。変更するには API の sigmas フィールドを使用してください。",
+ "imagine.effective_steps": "実際のステップ数",
+ "imagine.results_heading": "結果",
+ "imagine.advanced.seed": "Seed",
+ "imagine.advanced.n": "画像数",
+ "imagine.upload_heading": "参照画像",
+ "imagine.brand": "oMLX Imagine",
+ "imagine.api_key_placeholder": "APIキーを入力...",
+ "imagine.change_api_key": "APIキーを変更",
+ "modal.model_settings.moe_expert_offload_resident_75": "75% resident",
+ "imagine.nav.chat": "チャット",
+ "imagine.error.invalid_image_type": "画像ファイルを選択してください",
+ "imagine.nav.imagine": "Imagine",
+ "imagine.image_preview": "画像プレビュー",
+ "imagine.timeline_model": "モデル",
+ "imagine.api_key_prompt": "画像作成を開始するにはAPIキーを入力してください",
+ "imagine.submit.generating": "生成中...",
+ "imagine.result.download": "ダウンロード",
+ "imagine.advanced.output_format": "出力形式",
+ "imagine.timeline_prompt": "プロンプト",
+ "imagine.mode.label": "モード",
+ "imagine.original_image_alt": "元画像",
+ "imagine.select_model": "画像モデル",
+ "imagine.welcome_heading": "oMLXでImagine",
+ "imagine.advanced.guidance": "Guidance",
+ "imagine.prompt_label": "プロンプト",
+ "imagine.clear_results": "結果をクリア",
+ "modal.model_settings.moe_expert_offload_resident_50": "50% resident",
+ "imagine.advanced.negative_prompt": "ネガティブプロンプト",
+ "imagine.timeline_original": "元画像",
+ "imagine.advanced.size": "サイズ",
+ "imagine.no_models_generation": "利用可能な生成モデルがありません",
+ "imagine.heading": "Imagine",
+ "modal.model_settings.dflash_single_stream": "Single-stream only: requests run one at a time.",
+ "imagine.welcome_privacy": "すべての画像生成はローカルデバイス上で実行されます。",
+ "imagine.error.incorrect_api_key": "APIキーが正しくありません。再入力してください。",
+ "imagine.result_image_alt": "生成画像",
+ "imagine.upload_help": "参照画像をドロップ、貼り付け、または選択します。",
+ "imagine.subheading": "ローカル画像モデルで画像を生成・編集します",
+ "imagine.prompt_placeholder": "作成したい画像を説明してください...",
+ "imagine.timeline_edited": "編集結果",
+ "navbar.tab.imagine": "Imagine",
+ "imagine.no_models_edit": "利用可能な編集モデルがありません",
+ "imagine.mode.generate": "生成",
+ "imagine.result.copy": "Data URIをコピー",
+ "imagine.mode.edit": "編集",
+ "imagine.submit.editing": "編集中...",
+ "imagine.remove_image": "画像を削除",
+ "imagine.timeline_generated": "生成結果",
+ "imagine.api_key_continue": "続行",
+ "imagine.submit.generate": "生成",
+ "imagine.admin_settings": "管理設定"
}
diff --git a/apps/omlx-web/omlx_web/i18n/ko.json b/apps/omlx-web/omlx_web/i18n/ko.json
index 44ab7fcf29..4620236d39 100644
--- a/apps/omlx-web/omlx_web/i18n/ko.json
+++ b/apps/omlx-web/omlx_web/i18n/ko.json
@@ -2464,5 +2464,77 @@
"cluster.cuda_guide.windows_firewall": "관리자 권한 PowerShell에서 이 Mac이 헬퍼에 연결할 수 있게 허용합니다.",
"cluster.cuda_guide.windows_run": "PowerShell에서 헬퍼를 시작합니다. 헬퍼가 이 Mac에 페어링을 요청하면 헬퍼 로그의 코드를 이 화면에 입력하세요. 이 Mac의 주소가 여러 개면 PC에서 닿는 주소로 바꾸세요.",
"cluster.cuda_guide.spark_run": "DGX OS에는 Docker와 NVIDIA Container Toolkit이 들어 있습니다. 헬퍼를 시작합니다. 이 화면에 나타나면 Pair를 누르고 헬퍼 로그의 코드를 입력하세요.",
- "cluster.device_card.helper_ready": "{name}에서 이 Mac 모델의 긴 프롬프트를 빠르게 처리할 수 있습니다."
+ "cluster.device_card.helper_ready": "{name}에서 이 Mac 모델의 긴 프롬프트를 빠르게 처리할 수 있습니다.",
+ "models.uploader.queue_loading": "업로드 작업을 불러오는 중...",
+ "models.uploader.queue_error": "업로드 상태를 새로 고칠 수 없습니다. 마지막으로 표시된 상태가 오래되었을 수 있습니다.",
+ "models.uploader.queue_empty": "업로드 작업이 없습니다. 이 목록은 자동으로 새로 고쳐집니다.",
+ "models.uploader.queue_refresh": "업로드 상태 새로 고침",
+ "models.uploader.queue_activity": "업로드 중입니다. 바이트 단위의 진행 상황은 제공되지 않습니다.",
+ "modal.model_settings.minicpm_media": "MiniCPM 미디어",
+ "modal.model_settings.minicpm_downsample_mode": "시각 압축",
+ "modal.model_settings.minicpm_downsample_mode_hint": "16x는 시각 토큰을 줄이고, 4x는 더 많은 세부 정보를 유지합니다. 기본값은 모델 프로세서 설정을 사용합니다.",
+ "modal.model_settings.minicpm_max_slice_nums": "최대 이미지 슬라이스 수",
+ "modal.model_settings.minicpm_max_slice_nums_hint": "이미지 분할 한도를 설정합니다(최소 1). 비워 두면 모델 프로세서의 기본값을 사용합니다.",
+ "imagine.welcome_description": "로컬 이미지 모델에 프롬프트를 보내고 결과를 미리 보고 다운로드하세요.",
+ "imagine.upload_browse": "이미지 선택",
+ "modal.model_settings.moe_expert_offload_resident_25": "25% resident",
+ "modal.model_settings.moe_expert_offload_resident_12_5": "12.5% resident",
+ "imagine.submit.edit": "이미지 편집",
+ "imagine.title": "Imagine - oMLX 관리자",
+ "imagine.advanced.title": "고급",
+ "imagine.error.image_too_large": "이미지 크기는 25MB 이하여야 합니다",
+ "modal.model_settings.model_type_image": "이미지",
+ "imagine.advanced.steps": "스텝",
+ "imagine.checkpoint_schedule_hint": "저장된 모델 스케줄이 스텝 수보다 우선합니다. 변경하려면 API의 sigmas 필드를 사용하세요.",
+ "imagine.effective_steps": "실제 스텝 수",
+ "imagine.results_heading": "결과",
+ "imagine.advanced.seed": "Seed",
+ "imagine.advanced.n": "이미지 수",
+ "imagine.upload_heading": "참조 이미지",
+ "imagine.brand": "oMLX Imagine",
+ "imagine.api_key_placeholder": "API 키 입력...",
+ "imagine.change_api_key": "API 키 변경",
+ "modal.model_settings.moe_expert_offload_resident_75": "75% resident",
+ "imagine.nav.chat": "채팅",
+ "imagine.error.invalid_image_type": "이미지 파일을 선택해주세요",
+ "imagine.nav.imagine": "Imagine",
+ "imagine.image_preview": "이미지 미리보기",
+ "imagine.timeline_model": "모델",
+ "imagine.api_key_prompt": "이미지 생성을 시작하려면 API 키를 입력하세요",
+ "imagine.submit.generating": "생성 중...",
+ "imagine.result.download": "다운로드",
+ "imagine.advanced.output_format": "출력 형식",
+ "imagine.timeline_prompt": "프롬프트",
+ "imagine.mode.label": "모드",
+ "imagine.original_image_alt": "원본 이미지",
+ "imagine.select_model": "이미지 모델",
+ "imagine.welcome_heading": "oMLX로 Imagine",
+ "imagine.advanced.guidance": "Guidance",
+ "imagine.prompt_label": "프롬프트",
+ "imagine.clear_results": "결과 지우기",
+ "modal.model_settings.moe_expert_offload_resident_50": "50% resident",
+ "imagine.advanced.negative_prompt": "네거티브 프롬프트",
+ "imagine.timeline_original": "원본",
+ "imagine.advanced.size": "크기",
+ "imagine.no_models_generation": "사용 가능한 생성 모델 없음",
+ "imagine.heading": "Imagine",
+ "modal.model_settings.dflash_single_stream": "Single-stream only: requests run one at a time.",
+ "imagine.welcome_privacy": "모든 이미지 생성은 로컬 기기에서 실행됩니다.",
+ "imagine.error.incorrect_api_key": "API 키가 올바르지 않습니다. 다시 입력해 주세요.",
+ "imagine.result_image_alt": "생성된 이미지",
+ "imagine.upload_help": "참조 이미지를 드롭하거나 붙여넣거나 선택하세요.",
+ "imagine.subheading": "로컬 이미지 모델로 이미지를 생성하고 편집합니다",
+ "imagine.prompt_placeholder": "원하는 이미지를 설명하세요...",
+ "imagine.timeline_edited": "편집 결과",
+ "navbar.tab.imagine": "Imagine",
+ "imagine.no_models_edit": "사용 가능한 편집 모델 없음",
+ "imagine.mode.generate": "생성",
+ "imagine.result.copy": "Data URI 복사",
+ "imagine.mode.edit": "편집",
+ "imagine.submit.editing": "편집 중...",
+ "imagine.remove_image": "이미지 제거",
+ "imagine.timeline_generated": "생성 결과",
+ "imagine.api_key_continue": "계속",
+ "imagine.submit.generate": "생성",
+ "imagine.admin_settings": "관리자 설정"
}
diff --git a/apps/omlx-web/omlx_web/i18n/pt-BR.json b/apps/omlx-web/omlx_web/i18n/pt-BR.json
index 8486e68351..d5073baa43 100644
--- a/apps/omlx-web/omlx_web/i18n/pt-BR.json
+++ b/apps/omlx-web/omlx_web/i18n/pt-BR.json
@@ -2464,5 +2464,77 @@
"cluster.cuda_guide.windows_firewall": "In PowerShell as administrator, let this Mac reach the helper.",
"cluster.cuda_guide.windows_run": "Start the helper in PowerShell. It asks this Mac to pair: type the code from its log on this page. If this Mac has more than one address, use the one the PC can reach.",
"cluster.cuda_guide.spark_run": "DGX OS comes with Docker and the NVIDIA Container Toolkit. Start the helper. It appears on this page: press Pair on it and type the code from its log.",
- "cluster.device_card.helper_ready": "{name} can speed up long prompts for models on this Mac."
+ "cluster.device_card.helper_ready": "{name} can speed up long prompts for models on this Mac.",
+ "models.uploader.queue_loading": "Carregando tarefas de upload...",
+ "models.uploader.queue_error": "Não foi possível atualizar os uploads. O último status exibido pode estar desatualizado.",
+ "models.uploader.queue_empty": "Nenhuma tarefa de upload. Esta lista é atualizada automaticamente.",
+ "models.uploader.queue_refresh": "Atualizar uploads",
+ "models.uploader.queue_activity": "Upload em andamento. O progresso em bytes não está disponível.",
+ "modal.model_settings.minicpm_media": "Mídia MiniCPM",
+ "modal.model_settings.minicpm_downsample_mode": "Compressão visual",
+ "modal.model_settings.minicpm_downsample_mode_hint": "16x usa menos tokens visuais; 4x preserva mais detalhes. A opção padrão usa o processador do modelo.",
+ "modal.model_settings.minicpm_max_slice_nums": "Máximo de segmentos de imagem",
+ "modal.model_settings.minicpm_max_slice_nums_hint": "Defina o limite de segmentação de imagens (pelo menos 1). Deixe em branco para usar o padrão do processador do modelo.",
+ "imagine.welcome_description": "Use um modelo local de imagem, depois visualize e baixe o resultado.",
+ "imagine.upload_browse": "Procurar imagens",
+ "modal.model_settings.moe_expert_offload_resident_25": "25% resident",
+ "modal.model_settings.moe_expert_offload_resident_12_5": "12.5% resident",
+ "imagine.submit.edit": "Editar imagem",
+ "imagine.title": "Imagine - oMLX Admin",
+ "imagine.advanced.title": "Avançado",
+ "imagine.error.image_too_large": "O tamanho da imagem deve ser menor que 25MB",
+ "modal.model_settings.model_type_image": "Imagem",
+ "imagine.advanced.steps": "Passos",
+ "imagine.checkpoint_schedule_hint": "O cronograma salvo do modelo tem prioridade sobre os passos. Use o campo sigmas da API para alterá-lo.",
+ "imagine.effective_steps": "Passos reais",
+ "imagine.results_heading": "Resultados",
+ "imagine.advanced.seed": "Seed",
+ "imagine.advanced.n": "Imagens",
+ "imagine.upload_heading": "Imagens de referência",
+ "imagine.brand": "oMLX Imagine",
+ "imagine.api_key_placeholder": "Insira a chave de API...",
+ "imagine.change_api_key": "Alterar Chave de API",
+ "modal.model_settings.moe_expert_offload_resident_75": "75% resident",
+ "imagine.nav.chat": "Chat",
+ "imagine.error.invalid_image_type": "Selecione um arquivo de imagem",
+ "imagine.nav.imagine": "Imagine",
+ "imagine.image_preview": "Pré-visualização da imagem",
+ "imagine.timeline_model": "Modelo",
+ "imagine.api_key_prompt": "Insira sua chave de API para começar a criar imagens",
+ "imagine.submit.generating": "Gerando...",
+ "imagine.result.download": "Baixar",
+ "imagine.advanced.output_format": "Formato de saída",
+ "imagine.timeline_prompt": "Prompt",
+ "imagine.mode.label": "Modo",
+ "imagine.original_image_alt": "Imagem original",
+ "imagine.select_model": "Modelo de imagem",
+ "imagine.welcome_heading": "Imagine com oMLX",
+ "imagine.advanced.guidance": "Orientação",
+ "imagine.prompt_label": "Prompt",
+ "imagine.clear_results": "Limpar resultados",
+ "modal.model_settings.moe_expert_offload_resident_50": "50% resident",
+ "imagine.advanced.negative_prompt": "Prompt negativo",
+ "imagine.timeline_original": "Original",
+ "imagine.advanced.size": "Tamanho",
+ "imagine.no_models_generation": "Nenhum modelo de geração disponível",
+ "imagine.heading": "Imagine",
+ "modal.model_settings.dflash_single_stream": "Single-stream only: requests run one at a time.",
+ "imagine.welcome_privacy": "Toda geração de imagens roda localmente no seu dispositivo.",
+ "imagine.error.incorrect_api_key": "A chave de API está incorreta. Insira sua chave de API novamente.",
+ "imagine.result_image_alt": "Imagem gerada",
+ "imagine.upload_help": "Solte imagens aqui, cole ou procure.",
+ "imagine.subheading": "Gere e edite imagens com modelos locais de imagem",
+ "imagine.prompt_placeholder": "Descreva a imagem que você quer...",
+ "imagine.timeline_edited": "Resultado editado",
+ "navbar.tab.imagine": "Imagine",
+ "imagine.no_models_edit": "Nenhum modelo de edição disponível",
+ "imagine.mode.generate": "Gerar",
+ "imagine.result.copy": "Copiar Data URI",
+ "imagine.mode.edit": "Editar",
+ "imagine.submit.editing": "Editando...",
+ "imagine.remove_image": "Remover imagem",
+ "imagine.timeline_generated": "Resultado gerado",
+ "imagine.api_key_continue": "Continuar",
+ "imagine.submit.generate": "Gerar",
+ "imagine.admin_settings": "Configurações de Admin"
}
diff --git a/apps/omlx-web/omlx_web/i18n/ru.json b/apps/omlx-web/omlx_web/i18n/ru.json
index 0925e957eb..85ecc065ac 100644
--- a/apps/omlx-web/omlx_web/i18n/ru.json
+++ b/apps/omlx-web/omlx_web/i18n/ru.json
@@ -2464,5 +2464,77 @@
"cluster.cuda_guide.windows_firewall": "In PowerShell as administrator, let this Mac reach the helper.",
"cluster.cuda_guide.windows_run": "Start the helper in PowerShell. It asks this Mac to pair: type the code from its log on this page. If this Mac has more than one address, use the one the PC can reach.",
"cluster.cuda_guide.spark_run": "DGX OS comes with Docker and the NVIDIA Container Toolkit. Start the helper. It appears on this page: press Pair on it and type the code from its log.",
- "cluster.device_card.helper_ready": "{name} can speed up long prompts for models on this Mac."
+ "cluster.device_card.helper_ready": "{name} can speed up long prompts for models on this Mac.",
+ "models.uploader.queue_loading": "Загрузка списка задач...",
+ "models.uploader.queue_error": "Не удалось обновить состояние загрузок. Последнее показанное состояние может быть устаревшим.",
+ "models.uploader.queue_empty": "Нет задач загрузки. Этот список обновляется автоматически.",
+ "models.uploader.queue_refresh": "Обновить загрузки",
+ "models.uploader.queue_activity": "Идёт загрузка. Сведения о прогрессе в байтах недоступны.",
+ "modal.model_settings.minicpm_media": "Медиа MiniCPM",
+ "modal.model_settings.minicpm_downsample_mode": "Визуальное сжатие",
+ "modal.model_settings.minicpm_downsample_mode_hint": "16x использует меньше визуальных токенов; 4x сохраняет больше деталей. Значение по умолчанию определяется процессором модели.",
+ "modal.model_settings.minicpm_max_slice_nums": "Максимальное число фрагментов изображения",
+ "modal.model_settings.minicpm_max_slice_nums_hint": "Задайте предел разбиения изображения (не менее 1). Оставьте поле пустым для значения по умолчанию процессора модели.",
+ "imagine.welcome_description": "Введите промпт для локальной модели изображений, затем просмотрите и скачайте результат.",
+ "imagine.upload_browse": "Выбрать изображения",
+ "modal.model_settings.moe_expert_offload_resident_25": "25% resident",
+ "modal.model_settings.moe_expert_offload_resident_12_5": "12.5% resident",
+ "imagine.submit.edit": "Редактировать изображение",
+ "imagine.title": "Imagine - oMLX Админ",
+ "imagine.advanced.title": "Дополнительно",
+ "imagine.error.image_too_large": "Размер изображения должен быть меньше 25 МБ",
+ "modal.model_settings.model_type_image": "Изображение",
+ "imagine.advanced.steps": "Шаги",
+ "imagine.checkpoint_schedule_hint": "Сохранённое расписание модели имеет приоритет над числом шагов. Для изменения используйте поле sigmas в API.",
+ "imagine.effective_steps": "Фактические шаги",
+ "imagine.results_heading": "Результаты",
+ "imagine.advanced.seed": "Seed",
+ "imagine.advanced.n": "Изображения",
+ "imagine.upload_heading": "Референсные изображения",
+ "imagine.brand": "oMLX Imagine",
+ "imagine.api_key_placeholder": "Введите API-ключ...",
+ "imagine.change_api_key": "Изменить API-ключ",
+ "modal.model_settings.moe_expert_offload_resident_75": "75% resident",
+ "imagine.nav.chat": "Чат",
+ "imagine.error.invalid_image_type": "Выберите файл изображения",
+ "imagine.nav.imagine": "Imagine",
+ "imagine.image_preview": "Предпросмотр изображения",
+ "imagine.timeline_model": "Модель",
+ "imagine.api_key_prompt": "Введите API-ключ, чтобы начать создавать изображения",
+ "imagine.submit.generating": "Генерация...",
+ "imagine.result.download": "Скачать",
+ "imagine.advanced.output_format": "Формат вывода",
+ "imagine.timeline_prompt": "Промпт",
+ "imagine.mode.label": "Режим",
+ "imagine.original_image_alt": "Исходное изображение",
+ "imagine.select_model": "Модель изображений",
+ "imagine.welcome_heading": "Imagine с oMLX",
+ "imagine.advanced.guidance": "Guidance",
+ "imagine.prompt_label": "Промпт",
+ "imagine.clear_results": "Очистить результаты",
+ "modal.model_settings.moe_expert_offload_resident_50": "50% resident",
+ "imagine.advanced.negative_prompt": "Негативный промпт",
+ "imagine.timeline_original": "Оригинал",
+ "imagine.advanced.size": "Размер",
+ "imagine.no_models_generation": "Нет доступных моделей генерации",
+ "imagine.heading": "Imagine",
+ "modal.model_settings.dflash_single_stream": "Single-stream only: requests run one at a time.",
+ "imagine.welcome_privacy": "Вся генерация изображений выполняется локально на вашем устройстве.",
+ "imagine.error.incorrect_api_key": "API-ключ неверен. Пожалуйста, введите его снова.",
+ "imagine.result_image_alt": "Сгенерированное изображение",
+ "imagine.upload_help": "Перетащите изображения сюда, вставьте или выберите.",
+ "imagine.subheading": "Генерируйте и редактируйте изображения локальными моделями",
+ "imagine.prompt_placeholder": "Опишите нужное изображение...",
+ "imagine.timeline_edited": "Результат редактирования",
+ "navbar.tab.imagine": "Imagine",
+ "imagine.no_models_edit": "Нет доступных моделей редактирования",
+ "imagine.mode.generate": "Генерация",
+ "imagine.result.copy": "Копировать Data URI",
+ "imagine.mode.edit": "Редактирование",
+ "imagine.submit.editing": "Редактирование...",
+ "imagine.remove_image": "Удалить изображение",
+ "imagine.timeline_generated": "Сгенерированный результат",
+ "imagine.api_key_continue": "Продолжить",
+ "imagine.submit.generate": "Генерировать",
+ "imagine.admin_settings": "Настройки админки"
}
diff --git a/apps/omlx-web/omlx_web/i18n/zh-TW.json b/apps/omlx-web/omlx_web/i18n/zh-TW.json
index 00d1d25e84..e80e310eae 100644
--- a/apps/omlx-web/omlx_web/i18n/zh-TW.json
+++ b/apps/omlx-web/omlx_web/i18n/zh-TW.json
@@ -2464,5 +2464,77 @@
"cluster.cuda_guide.windows_firewall": "In PowerShell as administrator, let this Mac reach the helper.",
"cluster.cuda_guide.windows_run": "Start the helper in PowerShell. It asks this Mac to pair: type the code from its log on this page. If this Mac has more than one address, use the one the PC can reach.",
"cluster.cuda_guide.spark_run": "DGX OS comes with Docker and the NVIDIA Container Toolkit. Start the helper. It appears on this page: press Pair on it and type the code from its log.",
- "cluster.device_card.helper_ready": "{name} can speed up long prompts for models on this Mac."
+ "cluster.device_card.helper_ready": "{name} can speed up long prompts for models on this Mac.",
+ "models.uploader.queue_loading": "正在載入上傳工作...",
+ "models.uploader.queue_error": "無法重新整理上傳工作。上次顯示的狀態可能已過時。",
+ "models.uploader.queue_empty": "目前沒有上傳工作。此清單會自動重新整理。",
+ "models.uploader.queue_refresh": "重新整理上傳工作",
+ "models.uploader.queue_activity": "正在上傳。暫不提供位元組層級的進度。",
+ "modal.model_settings.minicpm_media": "MiniCPM 媒體",
+ "modal.model_settings.minicpm_downsample_mode": "視覺壓縮",
+ "modal.model_settings.minicpm_downsample_mode_hint": "16x 使用較少的視覺 token;4x 保留更多細節。預設選項使用模型處理器設定。",
+ "modal.model_settings.minicpm_max_slice_nums": "最大影像切片數",
+ "modal.model_settings.minicpm_max_slice_nums_hint": "設定影像切片上限(至少為 1)。留空則使用模型處理器的預設值。",
+ "imagine.welcome_description": "提示本機圖片模型,然後預覽並下載結果。",
+ "imagine.upload_browse": "選擇圖片",
+ "modal.model_settings.moe_expert_offload_resident_25": "25% resident",
+ "modal.model_settings.moe_expert_offload_resident_12_5": "12.5% resident",
+ "imagine.submit.edit": "編輯圖片",
+ "imagine.title": "Imagine - oMLX 管理後台",
+ "imagine.advanced.title": "進階",
+ "imagine.error.image_too_large": "圖片大小不能超過 25MB",
+ "modal.model_settings.model_type_image": "影像",
+ "imagine.advanced.steps": "步數",
+ "imagine.checkpoint_schedule_hint": "模型儲存的排程優先於步數設定。請使用 API 的 sigmas 欄位變更排程。",
+ "imagine.effective_steps": "實際步數",
+ "imagine.results_heading": "結果",
+ "imagine.advanced.seed": "Seed",
+ "imagine.advanced.n": "圖片數",
+ "imagine.upload_heading": "參考圖片",
+ "imagine.brand": "oMLX Imagine",
+ "imagine.api_key_placeholder": "輸入 API 金鑰...",
+ "imagine.change_api_key": "更換 API 金鑰",
+ "modal.model_settings.moe_expert_offload_resident_75": "75% resident",
+ "imagine.nav.chat": "聊天",
+ "imagine.error.invalid_image_type": "請選擇圖片檔案",
+ "imagine.nav.imagine": "Imagine",
+ "imagine.image_preview": "圖片預覽",
+ "imagine.timeline_model": "模型",
+ "imagine.api_key_prompt": "輸入 API 金鑰以開始建立圖片",
+ "imagine.submit.generating": "生成中...",
+ "imagine.result.download": "下載",
+ "imagine.advanced.output_format": "輸出格式",
+ "imagine.timeline_prompt": "提示詞",
+ "imagine.mode.label": "模式",
+ "imagine.original_image_alt": "原始圖片",
+ "imagine.select_model": "圖片模型",
+ "imagine.welcome_heading": "使用 oMLX Imagine",
+ "imagine.advanced.guidance": "Guidance",
+ "imagine.prompt_label": "提示詞",
+ "imagine.clear_results": "清除結果",
+ "modal.model_settings.moe_expert_offload_resident_50": "50% resident",
+ "imagine.advanced.negative_prompt": "負面提示詞",
+ "imagine.timeline_original": "原圖",
+ "imagine.advanced.size": "尺寸",
+ "imagine.no_models_generation": "暫無可用生成模型",
+ "imagine.heading": "Imagine",
+ "modal.model_settings.dflash_single_stream": "Single-stream only: requests run one at a time.",
+ "imagine.welcome_privacy": "所有圖片生成均在本機設備上執行。",
+ "imagine.error.incorrect_api_key": "API 金鑰不正確,請重新輸入。",
+ "imagine.result_image_alt": "生成的圖片",
+ "imagine.upload_help": "拖放參考圖片、貼上或瀏覽。",
+ "imagine.subheading": "使用本機圖片模型生成和編輯圖片",
+ "imagine.prompt_placeholder": "描述您想要的圖片...",
+ "imagine.timeline_edited": "編輯結果",
+ "navbar.tab.imagine": "Imagine",
+ "imagine.no_models_edit": "暫無可用編輯模型",
+ "imagine.mode.generate": "生成",
+ "imagine.result.copy": "複製 Data URI",
+ "imagine.mode.edit": "編輯",
+ "imagine.submit.editing": "編輯中...",
+ "imagine.remove_image": "移除圖片",
+ "imagine.timeline_generated": "生成結果",
+ "imagine.api_key_continue": "繼續",
+ "imagine.submit.generate": "生成",
+ "imagine.admin_settings": "管理後台"
}
diff --git a/apps/omlx-web/omlx_web/i18n/zh.json b/apps/omlx-web/omlx_web/i18n/zh.json
index 02b871c3ef..1ca53d0391 100644
--- a/apps/omlx-web/omlx_web/i18n/zh.json
+++ b/apps/omlx-web/omlx_web/i18n/zh.json
@@ -2464,5 +2464,77 @@
"cluster.cuda_guide.windows_firewall": "In PowerShell as administrator, let this Mac reach the helper.",
"cluster.cuda_guide.windows_run": "Start the helper in PowerShell. It asks this Mac to pair: type the code from its log on this page. If this Mac has more than one address, use the one the PC can reach.",
"cluster.cuda_guide.spark_run": "DGX OS comes with Docker and the NVIDIA Container Toolkit. Start the helper. It appears on this page: press Pair on it and type the code from its log.",
- "cluster.device_card.helper_ready": "{name} can speed up long prompts for models on this Mac."
+ "cluster.device_card.helper_ready": "{name} can speed up long prompts for models on this Mac.",
+ "models.uploader.queue_loading": "正在加载上传任务...",
+ "models.uploader.queue_error": "无法刷新上传任务。上次显示的状态可能已过时。",
+ "models.uploader.queue_empty": "暂无上传任务。此列表会自动刷新。",
+ "models.uploader.queue_refresh": "刷新上传任务",
+ "models.uploader.queue_activity": "正在上传。暂不提供字节级进度。",
+ "modal.model_settings.minicpm_media": "MiniCPM 媒体",
+ "modal.model_settings.minicpm_downsample_mode": "视觉压缩",
+ "modal.model_settings.minicpm_downsample_mode_hint": "16x 使用更少的视觉 token;4x 保留更多细节。默认选项使用模型处理器设置。",
+ "modal.model_settings.minicpm_max_slice_nums": "最大图像切片数",
+ "modal.model_settings.minicpm_max_slice_nums_hint": "设置图像切片上限(至少为 1)。留空则使用模型处理器的默认值。",
+ "imagine.welcome_description": "提示本地图像模型,然后预览并下载结果。",
+ "imagine.upload_browse": "选择图像",
+ "modal.model_settings.moe_expert_offload_resident_25": "常驻 25%",
+ "modal.model_settings.moe_expert_offload_resident_12_5": "常驻 12.5%",
+ "imagine.submit.edit": "编辑图像",
+ "imagine.title": "Imagine - oMLX 管理后台",
+ "imagine.advanced.title": "高级",
+ "imagine.error.image_too_large": "图像大小不能超过 25MB",
+ "modal.model_settings.model_type_image": "图像",
+ "imagine.advanced.steps": "步数",
+ "imagine.checkpoint_schedule_hint": "模型保存的调度优先于步数设置。请使用 API 的 sigmas 字段更改调度。",
+ "imagine.effective_steps": "实际步数",
+ "imagine.results_heading": "结果",
+ "imagine.advanced.seed": "Seed",
+ "imagine.advanced.n": "图像数",
+ "imagine.upload_heading": "参考图像",
+ "imagine.brand": "oMLX Imagine",
+ "imagine.api_key_placeholder": "输入 API 密钥...",
+ "imagine.change_api_key": "更换 API 密钥",
+ "modal.model_settings.moe_expert_offload_resident_75": "常驻 75%",
+ "imagine.nav.chat": "聊天",
+ "imagine.error.invalid_image_type": "请选择图像文件",
+ "imagine.nav.imagine": "Imagine",
+ "imagine.image_preview": "图片预览",
+ "imagine.timeline_model": "模型",
+ "imagine.api_key_prompt": "输入 API 密钥以开始创建图像",
+ "imagine.submit.generating": "生成中...",
+ "imagine.result.download": "下载",
+ "imagine.advanced.output_format": "输出格式",
+ "imagine.timeline_prompt": "提示词",
+ "imagine.mode.label": "模式",
+ "imagine.original_image_alt": "原始图像",
+ "imagine.select_model": "图像模型",
+ "imagine.welcome_heading": "使用 oMLX Imagine",
+ "imagine.advanced.guidance": "Guidance",
+ "imagine.prompt_label": "提示词",
+ "imagine.clear_results": "清除结果",
+ "modal.model_settings.moe_expert_offload_resident_50": "常驻 50%",
+ "imagine.advanced.negative_prompt": "负面提示词",
+ "imagine.timeline_original": "原图",
+ "imagine.advanced.size": "尺寸",
+ "imagine.no_models_generation": "暂无可用生成模型",
+ "imagine.heading": "Imagine",
+ "modal.model_settings.dflash_single_stream": "仅单流:请求逐个执行。",
+ "imagine.welcome_privacy": "所有图像生成均在本地设备上运行。",
+ "imagine.error.incorrect_api_key": "API 密钥不正确,请重新输入。",
+ "imagine.result_image_alt": "生成的图像",
+ "imagine.upload_help": "拖放参考图像,粘贴或浏览。",
+ "imagine.subheading": "使用本地图像模型生成和编辑图像",
+ "imagine.prompt_placeholder": "描述你想要的图像...",
+ "imagine.timeline_edited": "编辑结果",
+ "navbar.tab.imagine": "Imagine",
+ "imagine.no_models_edit": "暂无可用编辑模型",
+ "imagine.mode.generate": "生成",
+ "imagine.result.copy": "复制 Data URI",
+ "imagine.mode.edit": "编辑",
+ "imagine.submit.editing": "编辑中...",
+ "imagine.remove_image": "移除图像",
+ "imagine.timeline_generated": "生成结果",
+ "imagine.api_key_continue": "继续",
+ "imagine.submit.generate": "生成",
+ "imagine.admin_settings": "管理后台"
}
diff --git a/apps/omlx-web/omlx_web/templates/imagine.html b/apps/omlx-web/omlx_web/templates/imagine.html
new file mode 100644
index 0000000000..9bede2d7c2
--- /dev/null
+++ b/apps/omlx-web/omlx_web/templates/imagine.html
@@ -0,0 +1,974 @@
+{% extends "base.html" %}
+
+{% block title %}{{ t('imagine.title') }}{% endblock %}
+
+{% block head %}
+
+{% endblock %}
+
+{% block content %}
+
+
+
+
+
+
{{ t('login.login.label_api_key') }}
+
{{ t('imagine.api_key_prompt') }}
+
+
+ {{ t('imagine.api_key_continue') }}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+{% endblock %}
+
+{% block scripts %}
+
+{% endblock %}
diff --git a/omlx/api/image_models.py b/omlx/api/image_models.py
new file mode 100644
index 0000000000..1791bc1eaf
--- /dev/null
+++ b/omlx/api/image_models.py
@@ -0,0 +1,246 @@
+# SPDX-License-Identifier: Apache-2.0
+"""
+Pydantic models for OpenAI-compatible Images API.
+
+These models define request and response schemas for:
+- /v1/images/generations
+- /v1/images/edits
+"""
+
+from __future__ import annotations
+
+import math
+from typing import Any, Literal
+
+from pydantic import BaseModel, Field, field_validator, model_validator
+
+from .shared_models import get_unix_timestamp
+
+ImageOutputFormat = Literal["png", "jpeg", "webp"]
+ImageResponseFormat = Literal["b64_json", "url"]
+MAX_IMAGE_OUTPUT_PIXELS = 4 * 1024 * 1024
+
+
+def parse_image_size(size: str | None) -> tuple[int | None, int | None]:
+ """Parse an OpenAI image size string into width and height.
+
+ ``auto`` and ``None`` return ``(None, None)`` so routes can let the image
+ engine or backend model choose defaults.
+ """
+ if size is None:
+ return None, None
+
+ normalized = size.strip().lower()
+ if normalized == "auto":
+ return None, None
+
+ parts = normalized.split("x")
+ if len(parts) != 2:
+ raise ValueError("size must be 'auto' or WIDTHxHEIGHT")
+
+ try:
+ width, height = (int(part.strip()) for part in parts)
+ except ValueError as exc:
+ raise ValueError("size must be 'auto' or WIDTHxHEIGHT") from exc
+
+ if width <= 0 or height <= 0:
+ raise ValueError("size dimensions must be positive")
+ if width * height > MAX_IMAGE_OUTPUT_PIXELS:
+ raise ValueError(f"size area must not exceed {MAX_IMAGE_OUTPUT_PIXELS} pixels")
+ return width, height
+
+
+class ImageURLReference(BaseModel):
+ """URL reference for image edit inputs."""
+
+ url: str
+
+ model_config = {"extra": "allow"}
+
+
+class ImageReference(BaseModel):
+ """Reference to an input image by file id or image URL/data URI."""
+
+ file_id: str | None = None
+ image_url: str | ImageURLReference | None = None
+
+ model_config = {"extra": "allow"}
+
+ @model_validator(mode="after")
+ def validate_single_reference(self) -> ImageReference:
+ """Require exactly one supported image reference shape."""
+ has_file_id = self.file_id is not None
+ has_image_url = self.image_url is not None
+ if has_file_id == has_image_url:
+ raise ValueError(
+ "Image reference must include exactly one of file_id or image_url"
+ )
+ return self
+
+
+class _ImageRequestBase(BaseModel):
+ """Common OpenAI-compatible image request fields."""
+
+ prompt: str
+ model: str
+ n: int = Field(default=1, ge=1, le=10)
+ size: str | None = "auto"
+ quality: str | None = "auto"
+ output_format: ImageOutputFormat = "png"
+ response_format: ImageResponseFormat | None = "b64_json"
+ stream: bool = False
+ partial_images: int | None = None
+ user: str | None = None
+
+ # oMLX/mlx-vlm extension fields passed through by routes when supported.
+ seed: int | None = None
+ steps: int | None = None
+ sigmas: list[float] | None = None
+ guidance: float | None = None
+ negative_prompt: str | None = None
+ scheduler: str | None = None
+ image_strength: float | None = None
+ lora_paths: list[str] | None = None
+ lora_scales: list[float] | None = None
+
+ model_config = {"extra": "allow"}
+
+ @field_validator("prompt")
+ @classmethod
+ def validate_prompt(cls, value: str) -> str:
+ """Require a non-empty prompt while preserving caller whitespace."""
+ if not value.strip():
+ raise ValueError("prompt must not be empty")
+ return value
+
+ @field_validator("sigmas", mode="before")
+ @classmethod
+ def validate_sigmas(cls, value: Any) -> Any:
+ """Input grids contain denoising sigmas, never the terminal zero."""
+ if value is None:
+ return None
+ if (
+ not isinstance(value, list)
+ or not value
+ or any(
+ isinstance(sigma, bool)
+ or not isinstance(sigma, (int, float))
+ or not math.isfinite(sigma)
+ or not 0 < sigma <= 1
+ for sigma in value
+ )
+ or any(left <= right for left, right in zip(value, value[1:]))
+ ):
+ raise ValueError(
+ "sigmas must be a nonempty, finite, strictly descending list "
+ "in (0, 1], without a terminal zero"
+ )
+ return value
+
+ @field_validator("output_format", mode="before")
+ @classmethod
+ def normalize_output_format(cls, value: Any) -> Any:
+ """Normalize and validate route-facing image encoding format."""
+ if isinstance(value, str):
+ value = value.strip().lower()
+ if value not in {"png", "jpeg", "webp"}:
+ raise ValueError("output_format must be one of: png, jpeg, webp")
+ return value
+
+ @field_validator("response_format", mode="before")
+ @classmethod
+ def normalize_response_format(cls, value: Any) -> Any:
+ """Normalize and validate OpenAI image response encoding choices."""
+ if value is None:
+ return value
+ if isinstance(value, str):
+ value = value.strip().lower()
+ if value not in {"b64_json", "url"}:
+ raise ValueError("response_format must be one of: b64_json, url")
+ return value
+
+ def parsed_size(self) -> tuple[int | None, int | None]:
+ """Return ``(width, height)`` parsed from ``size``."""
+ return parse_image_size(self.size)
+
+
+class ImageGenerationRequest(_ImageRequestBase):
+ """Request body for POST /v1/images/generations."""
+
+ background: str | None = "auto"
+ style: str | None = None
+ moderation: str | None = None
+
+
+class ImageEditRequest(_ImageRequestBase):
+ """Request body for POST /v1/images/edits using modern JSON image refs."""
+
+ images: list[ImageReference] = Field(min_length=1)
+ mask: ImageReference | None = None
+ input_fidelity: str | None = None
+
+
+class ImageMultipartEditRequest(_ImageRequestBase):
+ """Parsed multipart edit fields; file uploads are validated by the route."""
+
+ input_fidelity: str | None = None
+
+
+class ImageUsage(BaseModel):
+ """Optional placeholder for image usage accounting."""
+
+ prompt_tokens: int = 0
+ completion_tokens: int = 0
+ total_tokens: int = 0
+ input_tokens: int = 0
+ output_tokens: int = 0
+ image_count: int | None = None
+
+ def model_post_init(self, __context: Any) -> None:
+ """Calculate common token total/aliases when callers provide counts."""
+ if self.total_tokens == 0 and (
+ self.prompt_tokens > 0 or self.completion_tokens > 0
+ ):
+ object.__setattr__(
+ self,
+ "total_tokens",
+ self.prompt_tokens + self.completion_tokens,
+ )
+ if self.input_tokens == 0 and self.prompt_tokens > 0:
+ object.__setattr__(self, "input_tokens", self.prompt_tokens)
+ if self.output_tokens == 0 and self.completion_tokens > 0:
+ object.__setattr__(self, "output_tokens", self.completion_tokens)
+
+
+class ImageData(BaseModel):
+ """A single OpenAI-style image result."""
+
+ b64_json: str
+ revised_prompt: str | None = None
+ size: str | None = None
+ quality: str | None = None
+ output_format: ImageOutputFormat | None = None
+ background: str | None = None
+ steps: int | None = None
+ guidance: float | None = None
+
+ @field_validator("output_format", mode="before")
+ @classmethod
+ def normalize_output_format(cls, value: Any) -> Any:
+ """Normalize optional response image encoding format."""
+ if value is None:
+ return value
+ if isinstance(value, str):
+ value = value.strip().lower()
+ if value not in {"png", "jpeg", "webp"}:
+ raise ValueError("output_format must be one of: png, jpeg, webp")
+ return value
+
+
+class ImageResponse(BaseModel):
+ """Response body for OpenAI-compatible image generation/edit endpoints."""
+
+ created: int = Field(default_factory=get_unix_timestamp)
+ data: list[ImageData]
+ model: str | None = None
+ usage: ImageUsage | None = None
diff --git a/omlx/api/image_routes.py b/omlx/api/image_routes.py
new file mode 100644
index 0000000000..9255816654
--- /dev/null
+++ b/omlx/api/image_routes.py
@@ -0,0 +1,1008 @@
+# SPDX-License-Identifier: Apache-2.0
+"""OpenAI-compatible image generation and edit routes for oMLX."""
+
+from __future__ import annotations
+
+import asyncio
+import base64
+import binascii
+import http.client
+import ipaddress
+import json
+import logging
+import socket
+import ssl
+import tempfile
+import uuid
+from collections.abc import Iterable
+from dataclasses import dataclass
+from io import BytesIO
+from pathlib import Path
+from typing import Any, cast
+from urllib.parse import ParseResult, unquote_to_bytes, urljoin, urlparse, urlunparse
+
+from fastapi import APIRouter, HTTPException, Request, UploadFile
+from PIL import Image, UnidentifiedImageError
+from pydantic import ValidationError
+from starlette.datastructures import UploadFile as StarletteUploadFile
+
+from omlx.utils.optional_deps import require_mlx_vlm_available
+
+from .image_models import (
+ ImageData,
+ ImageEditRequest,
+ ImageGenerationRequest,
+ ImageMultipartEditRequest,
+ ImageReference,
+ ImageResponse,
+ ImageUsage,
+)
+
+logger = logging.getLogger(__name__)
+
+router = APIRouter()
+
+MAX_IMAGE_INPUT_BYTES = 25 * 1024 * 1024
+MAX_IMAGE_INPUT_PIXELS = 64 * 1024 * 1024
+MAX_IMAGE_DOWNLOAD_BYTES = MAX_IMAGE_INPUT_BYTES
+IMAGE_DOWNLOAD_TIMEOUT_SECONDS = 20.0
+IMAGE_DOWNLOAD_CONNECT_TIMEOUT_SECONDS = 5.0
+MAX_IMAGE_REDIRECTS = 3
+
+_IMAGE_SUFFIX_BY_MIME = {
+ "image/png": ".png",
+ "image/jpeg": ".jpg",
+ "image/jpg": ".jpg",
+ "image/webp": ".webp",
+ "image/gif": ".gif",
+}
+_SAFE_ENGINE_KWARG_FIELDS = {
+ "negative_prompt",
+ "scheduler",
+ "image_strength",
+ "sigmas",
+}
+_MULTIPART_FIELD_NAMES = {
+ "prompt",
+ "model",
+ "n",
+ "size",
+ "quality",
+ "output_format",
+ "response_format",
+ "background",
+ "style",
+ "moderation",
+ "user",
+ "stream",
+ "partial_images",
+ "seed",
+ "steps",
+ "sigmas",
+ "guidance",
+ "negative_prompt",
+ "scheduler",
+ "image_strength",
+ "lora_paths",
+ "lora_scales",
+ "input_fidelity",
+}
+_MULTI_VALUE_FIELDS = {"lora_paths", "lora_scales"}
+
+
+@dataclass(frozen=True)
+class _ResolvedHTTPURL:
+ url: str
+ hostname: str
+ port: int
+ resolved_ip: str
+ scheme: str
+
+
+class _PinnedHTTPConnection(http.client.HTTPConnection):
+ def __init__(
+ self,
+ host: str,
+ port: int,
+ resolved_ip: str,
+ connect_timeout: float,
+ read_timeout: float,
+ ) -> None:
+ super().__init__(host=host, port=port, timeout=connect_timeout)
+ self._resolved_ip = resolved_ip
+ self._read_timeout = read_timeout
+
+ def connect(self) -> None:
+ self.sock = socket.create_connection(
+ (self._resolved_ip, self.port),
+ self.timeout,
+ None,
+ )
+ self.sock.settimeout(self._read_timeout)
+
+
+class _PinnedHTTPSConnection(http.client.HTTPSConnection):
+ def __init__(
+ self,
+ host: str,
+ port: int,
+ resolved_ip: str,
+ connect_timeout: float,
+ read_timeout: float,
+ ) -> None:
+ super().__init__(
+ host=host,
+ port=port,
+ timeout=connect_timeout,
+ context=ssl.create_default_context(),
+ )
+ self._resolved_ip = resolved_ip
+ self._read_timeout = read_timeout
+ self._ssl_context = ssl.create_default_context()
+
+ def connect(self) -> None:
+ sock = socket.create_connection(
+ (self._resolved_ip, self.port),
+ self.timeout,
+ None,
+ )
+ self.sock = self._ssl_context.wrap_socket(sock, server_hostname=self.host)
+ self.sock.settimeout(self._read_timeout)
+
+
+def _get_engine_pool():
+ from omlx.server import _server_state
+
+ pool = _server_state.engine_pool
+ if pool is None:
+ raise HTTPException(status_code=503, detail="Server not initialized")
+ return pool
+
+
+def _require_image_dependency() -> None:
+ try:
+ require_mlx_vlm_available()
+ except ImportError as exc:
+ raise HTTPException(status_code=503, detail=str(exc)) from exc
+
+
+def _resolve_model(model_id: str) -> str:
+ from omlx.server import resolve_model_id
+
+ return resolve_model_id(model_id) or model_id
+
+
+def _validation_detail(exc: ValidationError) -> list[dict[str, Any]]:
+ return [
+ dict(error) for error in exc.errors(include_url=False, include_context=False)
+ ]
+
+
+def _normalize_task_names(tasks: object) -> set[str]:
+ if tasks is None:
+ return set()
+ items: Iterable[object]
+ if isinstance(tasks, str):
+ items = [tasks]
+ elif isinstance(tasks, Iterable):
+ items = tasks
+ else:
+ return set()
+
+ normalized: set[str] = set()
+ for item in items:
+ if not isinstance(item, str):
+ continue
+ task = item.strip().lower().replace("_", "-")
+ if task in {"generation", "generate", "text-to-image", "txt2img"}:
+ normalized.add("generation")
+ elif task in {
+ "edit",
+ "editing",
+ "image-to-image",
+ "img2img",
+ "inpaint",
+ "inpainting",
+ }:
+ normalized.add("edit")
+ return normalized
+
+
+def _entry_for_model(pool: Any, model_id: str) -> Any | None:
+ get_entry = getattr(pool, "get_entry", None)
+ if get_entry is None:
+ return None
+ try:
+ return get_entry(model_id)
+ except Exception:
+ return None
+
+
+def _validate_image_entry(entry: Any | None, model_id: str, task: str) -> bool:
+ if entry is None:
+ return False
+
+ model_type = getattr(entry, "model_type", None)
+ engine_type = getattr(entry, "engine_type", None)
+ entry_is_image = model_type == "image" or engine_type == "image"
+ if not entry_is_image:
+ raise HTTPException(
+ status_code=400,
+ detail=f"Model '{model_id}' is not an image model",
+ )
+
+ tasks = _normalize_task_names(getattr(entry, "tasks", None))
+ if tasks and task not in tasks:
+ raise HTTPException(
+ status_code=400,
+ detail=f"Image model '{model_id}' does not support task '{task}'",
+ )
+ return True
+
+
+def _engine_stats(engine: Any) -> dict[str, Any]:
+ get_stats = getattr(engine, "get_stats", None)
+ if get_stats is None:
+ return {}
+ try:
+ stats = get_stats()
+ except Exception:
+ return {}
+ return stats if isinstance(stats, dict) else {}
+
+
+def _validate_image_engine(
+ engine: Any,
+ model_id: str,
+ task: str,
+ *,
+ entry_is_image: bool,
+) -> None:
+ stats = _engine_stats(engine)
+ stats_tasks = _normalize_task_names(stats.get("tasks"))
+ if stats_tasks and task not in stats_tasks:
+ raise HTTPException(
+ status_code=400,
+ detail=f"Image model '{model_id}' does not support task '{task}'",
+ )
+
+ method_name = "generate" if task == "generation" else "edit"
+ has_task_method = callable(getattr(engine, method_name, None))
+ looks_like_image = (
+ entry_is_image or bool(stats_tasks) or stats.get("backend") == "mlx-vlm"
+ )
+ if not looks_like_image or not has_task_method:
+ raise HTTPException(
+ status_code=400,
+ detail=f"Model '{model_id}' is not an image-capable model",
+ )
+
+
+async def _load_image_engine(model: str, task: str) -> tuple[str, Any, Any]:
+ from omlx.exceptions import (
+ EnginePoolError,
+ InsufficientMemoryError,
+ ModelLoadingError,
+ ModelNotFoundError,
+ ModelTooLargeError,
+ )
+
+ pool = _get_engine_pool()
+ resolved_model = _resolve_model(model)
+ entry_is_image = _validate_image_entry(
+ _entry_for_model(pool, resolved_model), resolved_model, task
+ )
+
+ try:
+ engine = await pool.get_engine(resolved_model, _lease=True)
+ except ModelNotFoundError as exc:
+ available = (
+ ", ".join(exc.available_models) if exc.available_models else "(none)"
+ )
+ raise HTTPException(
+ status_code=404,
+ detail=f"Model '{resolved_model}' not found. Available: {available}",
+ ) from exc
+ except (ModelTooLargeError, InsufficientMemoryError) as exc:
+ raise HTTPException(status_code=507, detail=str(exc)) from exc
+ except ModelLoadingError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ except EnginePoolError as exc:
+ raise HTTPException(status_code=500, detail=str(exc)) from exc
+ except Exception as exc:
+ raise HTTPException(status_code=500, detail=str(exc)) from exc
+
+ try:
+ _validate_image_engine(
+ engine,
+ resolved_model,
+ task,
+ entry_is_image=entry_is_image,
+ )
+ except Exception:
+ await pool.release_engine(resolved_model)
+ raise
+ return resolved_model, engine, pool
+
+
+def _safe_suffix(filename: str | None = None, content_type: str | None = None) -> str:
+ if content_type:
+ suffix = _IMAGE_SUFFIX_BY_MIME.get(content_type.split(";")[0].strip().lower())
+ if suffix:
+ return suffix
+ if filename:
+ suffix = Path(filename).suffix.lower()
+ if suffix in {".png", ".jpg", ".jpeg", ".webp", ".gif"}:
+ return suffix
+ return ".png"
+
+
+def _validate_image_bytes(data: bytes) -> None:
+ try:
+ with Image.open(BytesIO(data)) as image:
+ width, height = image.size
+ if width <= 0 or height <= 0 or width * height > MAX_IMAGE_INPUT_PIXELS:
+ raise HTTPException(
+ status_code=413,
+ detail=(
+ "Image dimensions exceed maximum allowed pixels "
+ f"({MAX_IMAGE_INPUT_PIXELS})"
+ ),
+ )
+ image.verify()
+ except (UnidentifiedImageError, OSError) as exc:
+ raise HTTPException(
+ status_code=400, detail="Input is not a valid image"
+ ) from exc
+
+
+def _write_image_bytes(data: bytes, suffix: str, temp_dir: Path) -> str:
+ if len(data) > MAX_IMAGE_INPUT_BYTES:
+ raise HTTPException(
+ status_code=413,
+ detail=f"Image input exceeds maximum allowed size ({MAX_IMAGE_INPUT_BYTES} bytes)",
+ )
+ _validate_image_bytes(data)
+
+ path = temp_dir / f"{uuid.uuid4().hex}{suffix}"
+ with path.open("xb") as handle:
+ handle.write(data)
+ return str(path)
+
+
+async def _read_upload(file: UploadFile | StarletteUploadFile) -> bytes:
+ chunks: list[bytes] = []
+ total = 0
+ while True:
+ chunk = await file.read(1024 * 1024)
+ if not chunk:
+ break
+ total += len(chunk)
+ if total > MAX_IMAGE_INPUT_BYTES:
+ raise HTTPException(
+ status_code=413,
+ detail=(
+ "Image upload exceeds maximum allowed size "
+ f"({MAX_IMAGE_INPUT_BYTES} bytes)"
+ ),
+ )
+ chunks.append(chunk)
+ return b"".join(chunks)
+
+
+def _decode_data_uri(uri: str) -> tuple[bytes, str]:
+ header, separator, payload = uri.partition(",")
+ if not separator or not header.lower().startswith("data:"):
+ raise HTTPException(status_code=400, detail="Invalid image data URI")
+
+ meta = header[5:]
+ media_type = meta.split(";", 1)[0].lower() if meta else "image/png"
+ if media_type and not media_type.startswith("image/"):
+ raise HTTPException(status_code=400, detail="Data URI must contain an image")
+
+ try:
+ if ";base64" in meta.lower():
+ if len(payload) > int(MAX_IMAGE_INPUT_BYTES * 1.5):
+ raise HTTPException(
+ status_code=413,
+ detail=(
+ "Image data URI exceeds maximum allowed size "
+ f"({MAX_IMAGE_INPUT_BYTES} bytes)"
+ ),
+ )
+ data = base64.b64decode(payload, validate=True)
+ else:
+ data = unquote_to_bytes(payload)
+ except (binascii.Error, ValueError) as exc:
+ raise HTTPException(status_code=400, detail="Invalid image data URI") from exc
+
+ return data, _safe_suffix(content_type=media_type)
+
+
+def _is_public_ip(ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
+ mapped = getattr(ip, "ipv4_mapped", None)
+ return mapped.is_global if mapped is not None else ip.is_global
+
+
+def _validate_public_http_url(url: str) -> _ResolvedHTTPURL:
+ """Reject internal/private addresses before server-side image fetches."""
+ try:
+ parsed = urlparse(url)
+ hostname = parsed.hostname
+ port = parsed.port or (443 if parsed.scheme == "https" else 80)
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail="Invalid image_url") from exc
+ if parsed.scheme not in {"http", "https"}:
+ raise HTTPException(
+ status_code=400,
+ detail="image_url must be a data URI or HTTP/HTTPS URL",
+ )
+ if not hostname:
+ raise HTTPException(status_code=400, detail="image_url host is required")
+
+ try:
+ addr_infos = socket.getaddrinfo(
+ hostname,
+ port,
+ type=socket.SOCK_STREAM,
+ )
+ except OSError as exc:
+ raise HTTPException(
+ status_code=400,
+ detail=f"Unable to resolve image_url host: {hostname}",
+ ) from exc
+
+ try:
+ resolved_ips = [
+ ipaddress.ip_address(str(sockaddr[0]).split("%", 1)[0])
+ for *_, sockaddr in addr_infos
+ ]
+ except ValueError as exc:
+ raise HTTPException(
+ status_code=400,
+ detail=f"Unable to resolve image_url host: {hostname}",
+ ) from exc
+ if not resolved_ips or any(not _is_public_ip(ip) for ip in resolved_ips):
+ raise HTTPException(
+ status_code=400,
+ detail="image_url must resolve to a public internet address",
+ )
+ return _ResolvedHTTPURL(
+ url=url,
+ hostname=hostname,
+ port=port,
+ resolved_ip=str(resolved_ips[0]),
+ scheme=parsed.scheme,
+ )
+
+
+def _host_header(parsed: ParseResult) -> str:
+ hostname = parsed.hostname or ""
+ if ":" in hostname and not hostname.startswith("["):
+ hostname = f"[{hostname}]"
+ return hostname if parsed.port is None else f"{hostname}:{parsed.port}"
+
+
+def _request_target(parsed: ParseResult) -> str:
+ return urlunparse(("", "", parsed.path or "/", parsed.params, parsed.query, ""))
+
+
+def _get_pinned_response(
+ resolved: _ResolvedHTTPURL,
+) -> tuple[http.client.HTTPResponse, http.client.HTTPConnection]:
+ parsed = urlparse(resolved.url)
+ if resolved.scheme == "https":
+ connection: http.client.HTTPConnection = _PinnedHTTPSConnection(
+ resolved.hostname,
+ resolved.port,
+ resolved.resolved_ip,
+ IMAGE_DOWNLOAD_CONNECT_TIMEOUT_SECONDS,
+ IMAGE_DOWNLOAD_TIMEOUT_SECONDS,
+ )
+ else:
+ connection = _PinnedHTTPConnection(
+ resolved.hostname,
+ resolved.port,
+ resolved.resolved_ip,
+ IMAGE_DOWNLOAD_CONNECT_TIMEOUT_SECONDS,
+ IMAGE_DOWNLOAD_TIMEOUT_SECONDS,
+ )
+ try:
+ connection.putrequest("GET", _request_target(parsed), skip_host=True)
+ connection.putheader("Host", _host_header(parsed))
+ connection.putheader("Accept", "image/*,*/*;q=0.8")
+ connection.putheader("User-Agent", "omlx-image-fetch/1.0")
+ connection.endheaders()
+ return connection.getresponse(), connection
+ except Exception:
+ connection.close()
+ raise
+
+
+def _download_http_image(url: str) -> tuple[bytes, str]:
+ current_url = url
+ try:
+ for _ in range(MAX_IMAGE_REDIRECTS + 1):
+ resolved = _validate_public_http_url(current_url)
+ response, connection = _get_pinned_response(resolved)
+ if 300 <= response.status < 400:
+ location = response.getheader("location")
+ connection.close()
+ if not location:
+ raise HTTPException(
+ status_code=400,
+ detail="Image download redirect missing Location header",
+ )
+ next_url = urljoin(current_url, location)
+ if (
+ urlparse(current_url).scheme == "https"
+ and urlparse(next_url).scheme != "https"
+ ):
+ raise HTTPException(
+ status_code=400,
+ detail="Image download redirects from HTTPS to HTTP are not allowed",
+ )
+ current_url = next_url
+ continue
+ break
+ else:
+ raise HTTPException(
+ status_code=400,
+ detail=f"Image download exceeded {MAX_IMAGE_REDIRECTS} redirects",
+ )
+
+ try:
+ if response.status >= 400:
+ raise HTTPException(
+ status_code=400,
+ detail=f"Failed to download image: HTTP {response.status}",
+ )
+ content_length = response.getheader("content-length")
+ if content_length is not None:
+ try:
+ length = int(content_length)
+ except ValueError:
+ length = 0
+ if length > MAX_IMAGE_DOWNLOAD_BYTES:
+ raise HTTPException(
+ status_code=413,
+ detail=(
+ "Image download exceeds maximum allowed size "
+ f"({MAX_IMAGE_DOWNLOAD_BYTES} bytes)"
+ ),
+ )
+
+ chunks: list[bytes] = []
+ total = 0
+ while True:
+ chunk = response.read(1024 * 1024)
+ if not chunk:
+ break
+ total += len(chunk)
+ if total > MAX_IMAGE_DOWNLOAD_BYTES:
+ raise HTTPException(
+ status_code=413,
+ detail=(
+ "Image download exceeds maximum allowed size "
+ f"({MAX_IMAGE_DOWNLOAD_BYTES} bytes)"
+ ),
+ )
+ chunks.append(chunk)
+ return (
+ b"".join(chunks),
+ _safe_suffix(
+ filename=urlparse(current_url).path,
+ content_type=response.getheader("content-type"),
+ ),
+ )
+ finally:
+ connection.close()
+ except TimeoutError as exc:
+ raise HTTPException(
+ status_code=504, detail="Timed out downloading image"
+ ) from exc
+ except (OSError, http.client.HTTPException, ssl.SSLError) as exc:
+ raise HTTPException(
+ status_code=400, detail=f"Failed to download image: {exc}"
+ ) from exc
+
+
+async def _image_reference_to_path(reference: ImageReference, temp_dir: Path) -> str:
+ if reference.file_id is not None:
+ raise HTTPException(
+ status_code=400,
+ detail="file_id image references are not supported; no File API store exists",
+ )
+ image_url = reference.image_url
+ if image_url is None:
+ raise HTTPException(status_code=400, detail="image_url is required")
+ url = image_url if isinstance(image_url, str) else image_url.url
+ parsed = urlparse(url)
+
+ if parsed.scheme == "data":
+ data, suffix = _decode_data_uri(url)
+ elif parsed.scheme in {"http", "https"}:
+ data, suffix = await asyncio.to_thread(_download_http_image, url)
+ else:
+ raise HTTPException(
+ status_code=400,
+ detail="image_url must be a data URI or HTTP/HTTPS URL",
+ )
+ return _write_image_bytes(data, suffix, temp_dir)
+
+
+def _reject_unsupported_lora(
+ request: ImageGenerationRequest | ImageEditRequest | ImageMultipartEditRequest,
+) -> None:
+ if request.lora_paths is not None or request.lora_scales is not None:
+ raise HTTPException(
+ status_code=400,
+ detail="Request-level LoRA fields are not supported for image endpoints yet",
+ )
+
+
+def _reject_unsupported_streaming(
+ request: ImageGenerationRequest | ImageEditRequest | ImageMultipartEditRequest,
+) -> None:
+ if request.stream:
+ raise HTTPException(
+ status_code=400,
+ detail="stream is not supported for image endpoints",
+ )
+ if request.partial_images is not None:
+ raise HTTPException(
+ status_code=400,
+ detail="partial_images is not supported for image endpoints",
+ )
+
+
+def _validate_image_size(
+ request: ImageGenerationRequest | ImageEditRequest | ImageMultipartEditRequest,
+) -> None:
+ try:
+ request.parsed_size()
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+
+def _reject_unsupported_response_format(
+ request: ImageGenerationRequest | ImageEditRequest | ImageMultipartEditRequest,
+) -> None:
+ if request.response_format == "url":
+ raise HTTPException(
+ status_code=400,
+ detail="response_format='url' is not supported; use 'b64_json'",
+ )
+
+
+def _request_engine_kwargs(
+ request: ImageGenerationRequest | ImageEditRequest | ImageMultipartEditRequest,
+) -> dict[str, Any]:
+ kwargs: dict[str, Any] = {}
+ for field in _SAFE_ENGINE_KWARG_FIELDS:
+ value = getattr(request, field, None)
+ if value is not None:
+ kwargs[field] = value
+ return kwargs
+
+
+def _seed_for_output(seed: int | None, index: int) -> int | None:
+ if seed is not None:
+ return int(seed) + index
+ return None
+
+
+def _encode_image_b64(image: Any, output_format: str) -> str:
+ if not hasattr(image, "save"):
+ raise HTTPException(
+ status_code=500, detail="Image engine returned no PIL image"
+ )
+
+ pil_image = image
+ image_format = output_format.upper()
+ if image_format == "JPEG":
+ if getattr(pil_image, "mode", None) in {"RGBA", "LA", "P"}:
+ pil_image = pil_image.convert("RGB")
+ elif image_format == "JPG":
+ image_format = "JPEG"
+
+ buffer = BytesIO()
+ try:
+ pil_image.save(buffer, format=image_format)
+ except Exception as exc:
+ raise HTTPException(
+ status_code=500,
+ detail=f"Failed to encode image as {output_format}: {exc}",
+ ) from exc
+ return base64.b64encode(buffer.getvalue()).decode("ascii")
+
+
+def _image_data_from_result(
+ result: Any,
+ request: ImageGenerationRequest | ImageEditRequest | ImageMultipartEditRequest,
+) -> ImageData:
+ image = getattr(result, "image", result)
+ metadata = getattr(result, "metadata", None)
+ metadata = metadata if isinstance(metadata, dict) else {}
+ return ImageData(
+ b64_json=_encode_image_b64(image, request.output_format),
+ revised_prompt=metadata.get("revised_prompt"),
+ size=(
+ f"{image.width}x{image.height}"
+ if hasattr(image, "width") and hasattr(image, "height")
+ else request.size
+ ),
+ quality=request.quality,
+ output_format=request.output_format,
+ background=getattr(request, "background", None),
+ steps=metadata.get("steps"),
+ guidance=metadata.get("guidance"),
+ )
+
+
+async def _run_generation(
+ resolved_model: str,
+ engine: Any,
+ request: ImageGenerationRequest,
+) -> ImageResponse:
+ width, height = request.parsed_size()
+ data: list[ImageData] = []
+ # ImageEngine serializes mlx-vlm/MLX calls for GPU safety, so keep n > 1 sequential.
+ for index in range(request.n):
+ result = await engine.generate(
+ request.prompt,
+ width=width,
+ height=height,
+ seed=_seed_for_output(request.seed, index),
+ steps=request.steps,
+ guidance=request.guidance,
+ output_format=request.output_format,
+ **_request_engine_kwargs(request),
+ )
+ data.append(_image_data_from_result(result, request))
+
+ return ImageResponse(
+ data=data,
+ model=resolved_model,
+ usage=ImageUsage(image_count=len(data)),
+ )
+
+
+async def _run_edit(
+ resolved_model: str,
+ engine: Any,
+ request: ImageEditRequest | ImageMultipartEditRequest,
+ image_paths: list[str],
+ mask_path: str | None,
+) -> ImageResponse:
+ width, height = request.parsed_size()
+ data: list[ImageData] = []
+ # ImageEngine serializes mlx-vlm/MLX calls for GPU safety, so keep n > 1 sequential.
+ for index in range(request.n):
+ result = await engine.edit(
+ request.prompt,
+ image_paths=image_paths,
+ mask_path=mask_path,
+ width=width,
+ height=height,
+ seed=_seed_for_output(request.seed, index),
+ steps=request.steps,
+ guidance=request.guidance,
+ output_format=request.output_format,
+ **_request_engine_kwargs(request),
+ )
+ data.append(_image_data_from_result(result, request))
+
+ return ImageResponse(
+ data=data,
+ model=resolved_model,
+ usage=ImageUsage(image_count=len(data)),
+ )
+
+
+def _is_upload(value: object) -> bool:
+ return isinstance(value, (UploadFile, StarletteUploadFile)) or (
+ hasattr(value, "read") and hasattr(value, "filename")
+ )
+
+
+def _form_values(form: Any, name: str) -> list[Any]:
+ getlist = getattr(form, "getlist", None)
+ if getlist is None:
+ value = form.get(name)
+ return [] if value is None else [value]
+ return list(getlist(name))
+
+
+def _parse_multi_value(values: list[str]) -> list[str]:
+ parsed: list[str] = []
+ for value in values:
+ parsed.extend(part.strip() for part in value.split(",") if part.strip())
+ return parsed
+
+
+def _multipart_request_from_form(form: Any) -> ImageMultipartEditRequest:
+ payload: dict[str, Any] = {}
+ for field in _MULTIPART_FIELD_NAMES:
+ values = [
+ str(value)
+ for value in _form_values(form, field)
+ if not _is_upload(value) and str(value) != ""
+ ]
+ if not values:
+ continue
+ if field in _MULTI_VALUE_FIELDS:
+ payload[field] = _parse_multi_value(values)
+ elif field == "sigmas":
+ try:
+ payload[field] = json.loads(values[-1])
+ except json.JSONDecodeError as exc:
+ raise HTTPException(
+ status_code=422, detail="sigmas must be a JSON array"
+ ) from exc
+ else:
+ payload[field] = values[-1]
+ try:
+ return cast(
+ ImageMultipartEditRequest,
+ ImageMultipartEditRequest.model_validate(payload),
+ )
+ except ValidationError as exc:
+ raise HTTPException(status_code=422, detail=_validation_detail(exc)) from exc
+
+
+async def _upload_to_path(value: object, field_name: str, temp_dir: Path) -> str:
+ if not _is_upload(value):
+ raise HTTPException(
+ status_code=400, detail=f"'{field_name}' must be a file upload"
+ )
+ upload = cast(UploadFile | StarletteUploadFile, value)
+ data = await _read_upload(upload)
+ return _write_image_bytes(
+ data,
+ _safe_suffix(
+ filename=getattr(upload, "filename", None),
+ content_type=getattr(upload, "content_type", None),
+ ),
+ temp_dir,
+ )
+
+
+@router.post("/v1/images/generations", response_model=ImageResponse)
+async def create_image_generation(request: ImageGenerationRequest) -> ImageResponse:
+ """Create images from a prompt using a discovered ImageEngine model."""
+ _reject_unsupported_lora(request)
+ _reject_unsupported_streaming(request)
+ _reject_unsupported_response_format(request)
+ _validate_image_size(request)
+ _require_image_dependency()
+ resolved_model, engine, pool = await _load_image_engine(request.model, "generation")
+ try:
+ return await _run_generation(resolved_model, engine, request)
+ except HTTPException:
+ raise
+ except ImportError as exc:
+ raise HTTPException(status_code=503, detail=str(exc)) from exc
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ except Exception as exc:
+ raise HTTPException(status_code=500, detail=str(exc)) from exc
+ finally:
+ await pool.release_engine(resolved_model)
+
+
+@router.post("/v1/images/edits", response_model=ImageResponse)
+async def create_image_edit(request: Request) -> ImageResponse:
+ """Create edited images from JSON image refs or multipart uploads."""
+ content_type = request.headers.get("content-type", "").split(";", 1)[0].lower()
+ if content_type == "application/json" or content_type.endswith("+json"):
+ return await _create_json_image_edit(request)
+ if content_type == "multipart/form-data":
+ return await _create_multipart_image_edit(request)
+ raise HTTPException(
+ status_code=415,
+ detail="Content-Type must be application/json or multipart/form-data",
+ )
+
+
+async def _create_json_image_edit(request: Request) -> ImageResponse:
+ try:
+ payload = await request.json()
+ edit_request = ImageEditRequest.model_validate(payload)
+ except ValidationError as exc:
+ raise HTTPException(status_code=422, detail=_validation_detail(exc)) from exc
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail="Invalid JSON body") from exc
+ _reject_unsupported_lora(edit_request)
+ _reject_unsupported_streaming(edit_request)
+ _reject_unsupported_response_format(edit_request)
+ if edit_request.mask is not None:
+ raise HTTPException(
+ status_code=400,
+ detail="mask is not supported by mlx-vlm image models",
+ )
+ _validate_image_size(edit_request)
+ _require_image_dependency()
+
+ with tempfile.TemporaryDirectory(prefix="omlx-image-") as temp_dir:
+ image_dir = Path(temp_dir)
+ image_paths: list[str] = []
+ try:
+ for reference in edit_request.images:
+ image_paths.append(await _image_reference_to_path(reference, image_dir))
+ resolved_model, engine, pool = await _load_image_engine(
+ edit_request.model, "edit"
+ )
+ try:
+ return await _run_edit(
+ resolved_model,
+ engine,
+ edit_request,
+ image_paths=image_paths,
+ mask_path=None,
+ )
+ finally:
+ await pool.release_engine(resolved_model)
+ except HTTPException:
+ raise
+ except ImportError as exc:
+ raise HTTPException(status_code=503, detail=str(exc)) from exc
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ except Exception as exc:
+ raise HTTPException(status_code=500, detail=str(exc)) from exc
+
+
+async def _create_multipart_image_edit(request: Request) -> ImageResponse:
+ form = await request.form()
+ edit_request = _multipart_request_from_form(form)
+ _reject_unsupported_lora(edit_request)
+ _reject_unsupported_streaming(edit_request)
+ _reject_unsupported_response_format(edit_request)
+ uploads = _form_values(form, "image") + _form_values(form, "image[]")
+ uploads = [value for value in uploads if _is_upload(value)]
+ if not uploads:
+ raise HTTPException(
+ status_code=400, detail="At least one 'image' upload is required"
+ )
+
+ mask_values = [value for value in _form_values(form, "mask") if _is_upload(value)]
+ if len(mask_values) > 1:
+ raise HTTPException(
+ status_code=400, detail="Only one 'mask' upload is supported"
+ )
+ if mask_values:
+ raise HTTPException(
+ status_code=400,
+ detail="mask is not supported by mlx-vlm image models",
+ )
+ _validate_image_size(edit_request)
+ _require_image_dependency()
+
+ with tempfile.TemporaryDirectory(prefix="omlx-image-") as temp_dir:
+ image_dir = Path(temp_dir)
+ image_paths: list[str] = []
+ try:
+ for upload in uploads:
+ image_paths.append(await _upload_to_path(upload, "image", image_dir))
+ resolved_model, engine, pool = await _load_image_engine(
+ edit_request.model, "edit"
+ )
+ try:
+ return await _run_edit(
+ resolved_model,
+ engine,
+ edit_request,
+ image_paths=image_paths,
+ mask_path=None,
+ )
+ finally:
+ await pool.release_engine(resolved_model)
+ except HTTPException:
+ raise
+ except ImportError as exc:
+ raise HTTPException(status_code=503, detail=str(exc)) from exc
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ except Exception as exc:
+ raise HTTPException(status_code=500, detail=str(exc)) from exc
diff --git a/omlx/engine/image.py b/omlx/engine/image.py
new file mode 100644
index 0000000000..47efe09169
--- /dev/null
+++ b/omlx/engine/image.py
@@ -0,0 +1,648 @@
+# SPDX-License-Identifier: Apache-2.0
+"""mlx-vlm-backed image generation and editing engine for oMLX."""
+
+from __future__ import annotations
+
+import asyncio
+import gc
+import importlib
+import logging
+import math
+from collections.abc import Iterable
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Literal
+
+import mlx.core as mx
+
+from ..engine_core import get_mlx_executor
+from ..image_registry import (
+ get_image_model_reference,
+ get_image_model_spec,
+ normalize_image_alias,
+)
+from ..utils.optional_deps import MLX_VLM_MISSING_MESSAGE
+from .base import BaseNonStreamingEngine
+
+logger = logging.getLogger(__name__)
+
+ImageTask = Literal["generation", "edit"]
+
+
+def _cleanup_mlx_cache() -> None:
+ gc.collect()
+ mx.synchronize()
+ mx.clear_cache()
+
+
+def _clear_mlx_cache() -> None:
+ mx.synchronize()
+ mx.clear_cache()
+
+
+async def _await_image_worker(future: asyncio.Future[Any]) -> Any:
+ cancelled = False
+ while not future.done():
+ try:
+ await asyncio.shield(future)
+ except asyncio.CancelledError:
+ cancelled = True
+ except Exception:
+ if not cancelled:
+ raise
+ if cancelled:
+ error = future.exception()
+ if error is not None:
+ logger.error(
+ "Cancelled image worker failed",
+ exc_info=(type(error), error, error.__traceback__),
+ )
+ raise asyncio.CancelledError
+ return future.result()
+
+
+@dataclass(frozen=True)
+class _ModelKey:
+ task: ImageTask
+ model_reference: str
+
+
+@dataclass(frozen=True)
+class _ImageAPI:
+ load_image_model: Any
+ generate_image: Any
+ ImageGenerationRequest: Any
+ ImageEditRequest: Any
+
+
+@dataclass(slots=True)
+class ImageEngineResult:
+ """A route-friendly image result returned by an mlx-vlm model."""
+
+ image: Any
+ metadata: dict[str, Any] = field(default_factory=dict)
+
+
+def _coerce_int(value: object, field_name: str) -> int | None:
+ if value is None:
+ return None
+ if isinstance(value, bool):
+ raise ValueError(f"Image manifest {field_name} must be an integer")
+ if isinstance(value, int):
+ return value
+ if isinstance(value, float) and value.is_integer():
+ return int(value)
+ if isinstance(value, str) and value.strip().isdigit():
+ return int(value.strip())
+ raise ValueError(f"Image manifest {field_name} must be an integer")
+
+
+def _coerce_float(value: object, field_name: str) -> float | None:
+ if value is None:
+ return None
+ if isinstance(value, bool):
+ raise ValueError(f"Image manifest {field_name} must be a number")
+ if isinstance(value, (int, float)):
+ return float(value)
+ if isinstance(value, str):
+ try:
+ return float(value.strip())
+ except ValueError:
+ pass
+ raise ValueError(f"Image manifest {field_name} must be a number")
+
+
+def _image_api() -> _ImageAPI:
+ """Import mlx-vlm's generic image API after registering oMLX shims."""
+ try:
+ from ..patches.mlx_vlm_image_compat import (
+ apply_mlx_vlm_image_compat_patch,
+ )
+
+ apply_mlx_vlm_image_compat_patch()
+ image = importlib.import_module("mlx_vlm.generate.image")
+ edit_image = importlib.import_module("mlx_vlm.generate.edit_image")
+ except (AttributeError, ImportError) as exc:
+ raise ImportError(MLX_VLM_MISSING_MESSAGE) from exc
+
+ return _ImageAPI(
+ load_image_model=image.load_image_model,
+ generate_image=image.generate_image,
+ ImageGenerationRequest=image.ImageGenerationRequest,
+ ImageEditRequest=edit_image.ImageEditRequest,
+ )
+
+
+class ImageEngine(BaseNonStreamingEngine):
+ """Non-streaming image engine using mlx-vlm model loaders and requests."""
+
+ def __init__(
+ self,
+ model_name: str,
+ *,
+ model_id: str | None = None,
+ model_path: str | None = None,
+ config_model_type: str = "",
+ image_metadata: dict[str, object] | None = None,
+ capabilities: list[str] | None = None,
+ tasks: list[str] | None = None,
+ model_settings: object | None = None,
+ ) -> None:
+ super().__init__()
+ self._model_name = model_name
+ self._model_id = model_id or model_name
+ self._model_path = model_path or model_name
+ self._has_explicit_model_path = model_path is not None
+ self._config_model_type = config_model_type
+ self._image_metadata = dict(image_metadata or {})
+ self._capabilities = list(capabilities or [])
+ self._tasks = self._normalize_tasks(tasks or self._image_metadata.get("tasks"))
+ self._model_settings = model_settings
+ self._models: dict[_ModelKey, Any] = {}
+ self._started = False
+ self._call_lock = asyncio.Lock()
+ self._load_lock = asyncio.Lock()
+
+ @property
+ def model_name(self) -> str:
+ """Get the API/model name associated with this engine."""
+ return self._model_name
+
+ @property
+ def base_model(self) -> str:
+ """Return the manifest's image family alias."""
+ return str(self._image_metadata.get("base_model", "")).strip()
+
+ async def start(self) -> None:
+ """Validate the manifest and load the primary image task."""
+ if self._started:
+ return
+
+ backend = str(self._image_metadata.get("backend", "mlx-vlm")).strip().lower()
+ if backend != "mlx-vlm":
+ raise ValueError(
+ f"Unsupported image backend for {self._model_id}: {backend!r}"
+ )
+ if "quantize" in self._image_metadata:
+ raise ValueError(
+ "Image manifest quantize is not supported by the mlx-vlm image backend"
+ )
+ if not self._tasks:
+ raise ValueError(
+ f"Image model {self._model_id} declares no supported tasks"
+ )
+ if self._is_qwen_image() and (
+ self._image_metadata.get("default_image_strength") is not None
+ ):
+ raise ValueError("Qwen Image 2.1 does not support default_image_strength")
+
+ logger.info(
+ "Starting mlx-vlm image engine: model=%s, base_model=%s, tasks=%s",
+ self._model_id,
+ self.base_model,
+ ",".join(self._tasks),
+ )
+ await self._load_model_for_task(self._primary_task())
+ self._started = True
+
+ def _primary_task(self) -> ImageTask:
+ """Choose the task whose weights are accounted during pool admission."""
+ if "generation" in self._tasks:
+ return "generation"
+ return "edit"
+
+ async def stop(self) -> None:
+ """Drop the loaded image variant and release MLX buffers."""
+ await self._stop(clear_mlx_cache=True)
+
+ async def stop_without_global_cleanup(self) -> None:
+ """Drop this model without synchronizing another active MLX workload."""
+ await self._stop(clear_mlx_cache=False)
+
+ async def _stop(self, *, clear_mlx_cache: bool) -> None:
+ if not self._models and not self._started:
+ return
+
+ async with self._call_lock:
+ logger.info("Stopping image engine: %s", self._model_id)
+ self._models.clear()
+ self._started = False
+ if clear_mlx_cache:
+ loop = asyncio.get_running_loop()
+ await loop.run_in_executor(get_mlx_executor(), _cleanup_mlx_cache)
+ else:
+ gc.collect()
+
+ async def generate(
+ self,
+ prompt: str,
+ width: int | None = None,
+ height: int | None = None,
+ seed: int | None = None,
+ steps: int | None = None,
+ guidance: float | None = None,
+ output_format: str = "png",
+ **kwargs: Any,
+ ) -> ImageEngineResult:
+ """Generate one image through mlx-vlm's generic generation API."""
+ self._ensure_started()
+ self._ensure_task_supported("generation")
+ self._reject_quantize(kwargs)
+ self._validate_qwen_options(kwargs, self._resolve_guidance(guidance))
+
+ activity_id = self._begin_activity(
+ "generating image",
+ detail="Generating image",
+ metadata={"prompt_length": len(prompt), "width": width, "height": height},
+ )
+ try:
+ async with self._call_lock:
+ model_path_override = kwargs.pop("model_path", None)
+ key, model = await self._load_model_for_task(
+ "generation",
+ model_path_override=model_path_override,
+ )
+ api = _image_api()
+ size = {
+ name: int(value)
+ for name, value in (("width", width), ("height", height))
+ if value is not None
+ }
+ request = api.ImageGenerationRequest(
+ prompt=prompt,
+ seed=None if seed is None else int(seed),
+ steps=self._resolve_steps(steps),
+ guidance=self._resolve_guidance(guidance),
+ output_format="png",
+ extra=self._request_extra(kwargs),
+ **size,
+ )
+ raw_result = await self._run_api_call(
+ api.generate_image,
+ model,
+ request,
+ task="generate",
+ )
+ return self._result_from_raw(
+ raw_result,
+ task="generation",
+ output_format=output_format,
+ model_key=key,
+ )
+ finally:
+ await self._finish_activity(activity_id)
+
+ async def edit(
+ self,
+ prompt: str,
+ image_paths: list[str],
+ mask_path: str | None = None,
+ width: int | None = None,
+ height: int | None = None,
+ seed: int | None = None,
+ steps: int | None = None,
+ guidance: float | None = None,
+ output_format: str = "png",
+ **kwargs: Any,
+ ) -> ImageEngineResult:
+ """Edit input images through mlx-vlm's generic edit API."""
+ self._ensure_started()
+ self._ensure_task_supported("edit")
+ self._reject_quantize(kwargs)
+ self._validate_qwen_options(kwargs, self._resolve_guidance(guidance))
+ if not image_paths:
+ raise ValueError("edit requires at least one input image path")
+ if mask_path is not None:
+ raise ValueError("mlx-vlm image models do not support masks")
+ activity_id = self._begin_activity(
+ "editing image",
+ detail="Editing image",
+ metadata={"prompt_length": len(prompt), "width": width, "height": height},
+ )
+ try:
+ async with self._call_lock:
+ model_path_override = kwargs.pop("model_path", None)
+ key, model = await self._load_model_for_task(
+ "edit",
+ model_path_override=model_path_override,
+ )
+ api = _image_api()
+ image_strength = self._resolve_image_strength(
+ kwargs.pop("image_strength", None),
+ )
+ request = api.ImageEditRequest(
+ prompt=prompt,
+ image_paths=tuple(image_paths),
+ seed=None if seed is None else int(seed),
+ steps=self._resolve_steps(steps),
+ width=None if width is None else int(width),
+ height=None if height is None else int(height),
+ guidance=self._resolve_guidance(guidance),
+ output_format="png",
+ extra=self._request_extra(
+ kwargs,
+ image_strength=image_strength,
+ ),
+ )
+ raw_result = await self._run_api_call(
+ api.generate_image,
+ model,
+ request,
+ task="edit",
+ )
+ return self._result_from_raw(
+ raw_result,
+ task="edit",
+ output_format=output_format,
+ model_key=key,
+ input_image_count=len(image_paths),
+ )
+ finally:
+ await self._finish_activity(activity_id)
+
+ def get_stats(self) -> dict[str, Any]:
+ """Get image engine statistics."""
+ return {
+ "model_name": self._model_name,
+ "model_id": self._model_id,
+ "loaded": self._started,
+ "backend": self._image_metadata.get("backend", "mlx-vlm"),
+ "base_model": self.base_model,
+ "tasks": list(self._tasks),
+ "loaded_tasks": sorted({key.task for key in self._models}),
+ }
+
+ @staticmethod
+ def _normalize_tasks(raw_tasks: object) -> list[ImageTask]:
+ if raw_tasks is None:
+ return []
+ items: Iterable[object]
+ if isinstance(raw_tasks, str):
+ items = [raw_tasks]
+ elif isinstance(raw_tasks, Iterable):
+ items = raw_tasks
+ else:
+ raise ValueError(
+ "Image model tasks must be a string or iterable of strings"
+ )
+ normalized: list[ImageTask] = []
+ for item in items:
+ if not isinstance(item, str):
+ raise ValueError("Image model tasks must contain only strings")
+ task = normalize_image_alias(item)
+ if task in {"generation", "generate", "text-to-image", "txt2img"}:
+ normalized.append("generation")
+ elif task in {
+ "edit",
+ "editing",
+ "image-to-image",
+ "img2img",
+ "inpaint",
+ "inpainting",
+ }:
+ normalized.append("edit")
+ else:
+ raise ValueError(f"Unsupported image model task: {item!r}")
+ return sorted(set(normalized), key=("generation", "edit").index)
+
+ def _ensure_started(self) -> None:
+ if not self._started:
+ raise RuntimeError("Engine not started. Call start() first.")
+
+ def _ensure_task_supported(self, task: ImageTask) -> None:
+ if task not in self._tasks:
+ raise ValueError(
+ f"Image model {self._model_id} does not support task {task!r}"
+ )
+
+ def _resolve_model_reference(self, override: object = None) -> str:
+ value = self._image_metadata.get("model_path") if override is None else override
+ root = Path(self._model_path).expanduser()
+ if value is None:
+ if not root.exists() and not self._has_explicit_model_path:
+ # Programmatic callers can construct an engine from a known
+ # mlx-vlm alias without a discovered local model directory.
+ spec = get_image_model_spec(self.base_model)
+ return (
+ get_image_model_reference(spec.base_model)
+ if spec is not None
+ else str(root)
+ )
+ return str(root)
+ if not isinstance(value, str) or not value.strip():
+ field = (
+ "Image manifest model_path"
+ if override is None
+ else "image model_path override"
+ )
+ raise ValueError(f"{field} must be a non-empty string")
+ path = Path(value).expanduser()
+ if not path.is_absolute():
+ candidate = root / path
+ path = candidate if override is None or candidate.exists() else path
+ if override is None and not path.exists():
+ raise ValueError(f"Image manifest model_path does not exist: {path}")
+ return str(path)
+
+ def _model_key(
+ self,
+ task: ImageTask,
+ model_path_override: object = None,
+ ) -> _ModelKey:
+ return _ModelKey(
+ task=task,
+ model_reference=self._resolve_model_reference(model_path_override),
+ )
+
+ def _resolve_steps(self, steps: int | None) -> int | None:
+ if steps is not None:
+ return int(steps)
+ return _coerce_int(self._image_metadata.get("default_steps"), "default_steps")
+
+ def _resolve_guidance(self, guidance: float | None) -> float | None:
+ if guidance is not None:
+ return float(guidance)
+ return _coerce_float(
+ self._image_metadata.get("default_guidance"), "default_guidance"
+ )
+
+ def _resolve_image_strength(self, image_strength: object) -> float | None:
+ if image_strength is not None:
+ return _coerce_float(image_strength, "image_strength")
+ return _coerce_float(
+ self._image_metadata.get("default_image_strength"),
+ "default_image_strength",
+ )
+
+ async def _load_model_for_task(
+ self,
+ task: ImageTask,
+ *,
+ model_path_override: object = None,
+ ) -> tuple[_ModelKey, Any]:
+ key = self._model_key(task, model_path_override)
+ model = self._models.get(key)
+ if model is not None:
+ return key, model
+
+ async with self._load_lock:
+ model = self._models.get(key)
+ if model is not None:
+ return key, model
+
+ if self._models:
+ logger.info(
+ "Unloading previous mlx-vlm image variant before loading: "
+ "model=%s, task=%s",
+ self._model_id,
+ task,
+ )
+ self._models.clear()
+ loop = asyncio.get_running_loop()
+ await loop.run_in_executor(get_mlx_executor(), _cleanup_mlx_cache)
+
+ api = _image_api()
+ loader_task = "generate" if task == "generation" else "edit"
+
+ def load_sync() -> Any:
+ if self._is_qwen_image():
+ from ..patches.mlx_vlm_qwen_image_compat import (
+ apply_qwen_image_compat_patch,
+ )
+
+ apply_qwen_image_compat_patch()
+ return api.load_image_model(key.model_reference, task=loader_task)
+
+ logger.info(
+ "Loading mlx-vlm image model: model=%s, base_model=%s, task=%s, "
+ "model_path=%s",
+ self._model_id,
+ self.base_model,
+ task,
+ key.model_reference,
+ )
+ loop = asyncio.get_running_loop()
+ try:
+ model = await _await_image_worker(
+ loop.run_in_executor(get_mlx_executor(), load_sync)
+ )
+ except ImportError as exc:
+ raise ImportError(MLX_VLM_MISSING_MESSAGE) from exc
+ self._models[key] = model
+ return key, model
+
+ @staticmethod
+ async def _run_api_call(
+ generate_image: Any,
+ model: Any,
+ request: Any,
+ *,
+ task: str,
+ ) -> Any:
+ loop = asyncio.get_running_loop()
+ future = loop.run_in_executor(
+ get_mlx_executor(),
+ lambda: generate_image(model, request, task=task),
+ )
+ return await _await_image_worker(future)
+
+ def _is_qwen_image(self) -> bool:
+ spec = get_image_model_spec(self.base_model)
+ return spec is not None and spec.base_model in {
+ "qwen-image-2-1",
+ "qwen-image-2-1-turbo",
+ }
+
+ def _validate_qwen_options(
+ self, kwargs: dict[str, Any], guidance: float | None
+ ) -> None:
+ if not self._is_qwen_image():
+ if kwargs.get("sigmas") is not None:
+ raise ValueError("sigmas is supported only for Qwen Image 2.1 models")
+ return
+ if kwargs.get("image_strength") is not None:
+ raise ValueError("Qwen Image 2.1 does not support image_strength")
+ if kwargs.get("scheduler") is not None:
+ raise ValueError("Qwen Image 2.1 uses its checkpoint scheduler")
+ if guidance is not None and (not math.isfinite(guidance) or guidance <= 0):
+ raise ValueError("Qwen Image 2.1 guidance must be finite and positive")
+
+ def _request_extra(
+ self,
+ kwargs: dict[str, Any],
+ *,
+ image_strength: float | None = None,
+ ) -> dict[str, Any]:
+ extra = {key: value for key, value in kwargs.items() if value is not None}
+ request_strength = extra.pop("image_strength", None)
+ if image_strength is None and request_strength is not None:
+ image_strength = _coerce_float(request_strength, "image_strength")
+ if image_strength is not None:
+ # Z-Image consumes ``strength`` while ERNIE-Image consumes
+ # ``image_strength``. Other mlx-vlm families safely ignore extras.
+ extra["image_strength"] = image_strength
+ extra["strength"] = image_strength
+ return extra
+
+ @staticmethod
+ def _reject_quantize(kwargs: dict[str, Any]) -> None:
+ if "quantize" in kwargs:
+ raise ValueError(
+ "Image request quantize is not supported by the mlx-vlm image backend"
+ )
+
+ def _result_from_raw(
+ self,
+ raw_result: Any,
+ *,
+ task: ImageTask,
+ output_format: str,
+ model_key: _ModelKey,
+ input_image_count: int | None = None,
+ ) -> ImageEngineResult:
+ raw_metadata = getattr(raw_result, "metadata", {})
+ metadata = dict(raw_metadata) if isinstance(raw_metadata, dict) else {}
+ metadata.update(
+ {
+ "model_id": self._model_id,
+ "model_name": self._model_name,
+ "base_model": self.base_model,
+ "task": task,
+ "output_format": output_format,
+ "model_path": model_key.model_reference,
+ }
+ )
+ if input_image_count is not None:
+ metadata["input_image_count"] = input_image_count
+ for attribute in (
+ "seed",
+ "prompt",
+ "steps",
+ "guidance",
+ "width",
+ "height",
+ "model",
+ "family",
+ "variant",
+ "prompt_tokens",
+ "peak_memory",
+ ):
+ value = getattr(raw_result, attribute, None)
+ if value is not None:
+ metadata[attribute] = value
+ return ImageEngineResult(
+ image=getattr(raw_result, "image", raw_result),
+ metadata=metadata,
+ )
+
+ async def _finish_activity(self, activity_id: str) -> None:
+ self._end_activity(activity_id)
+ loop = asyncio.get_running_loop()
+ await loop.run_in_executor(get_mlx_executor(), _clear_mlx_cache)
+
+ def __repr__(self) -> str:
+ status = "running" if self._started else "stopped"
+ return (
+ f""
+ )
diff --git a/omlx/image_registry.py b/omlx/image_registry.py
new file mode 100644
index 0000000000..8b093e70fc
--- /dev/null
+++ b/omlx/image_registry.py
@@ -0,0 +1,345 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Shared metadata for mlx-vlm-backed image model aliases."""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+from typing import Literal
+
+ImageTask = Literal["generation", "edit"]
+
+IMAGE_UNKNOWN_FALLBACK_SIZE = 24 * 1024**3
+
+
+@dataclass(frozen=True)
+class ImageModelSpec:
+ """Metadata used to identify and constrain a supported image family."""
+
+ base_model: str
+ tasks: tuple[ImageTask, ...]
+ estimated_size: int
+ discovery_aliases: tuple[str, ...]
+ allows_multiple_edit_images: bool = False
+
+
+def normalize_image_alias(value: object) -> str:
+ """Normalize model ids and local-folder aliases without importing mlx-vlm."""
+ if not isinstance(value, str):
+ return ""
+ normalized = value.strip().lower().replace("_", "-").replace(".", "-")
+ normalized = re.sub(r"\s+", "-", normalized)
+ normalized = re.sub(r"-+", "-", normalized).strip("-")
+ if normalized.startswith("flux-2-"):
+ normalized = "flux2-" + normalized[len("flux-2-") :]
+ return normalized
+
+
+def _aliases(*values: str) -> tuple[str, ...]:
+ return tuple(dict.fromkeys(normalize_image_alias(value) for value in values))
+
+
+IMAGE_MODEL_SPECS: tuple[ImageModelSpec, ...] = (
+ ImageModelSpec(
+ base_model="qwen-image-2-1",
+ tasks=("generation", "edit"),
+ estimated_size=IMAGE_UNKNOWN_FALLBACK_SIZE,
+ discovery_aliases=_aliases("qwen-image-2.1", "Qwen/Qwen-Image-2.1"),
+ allows_multiple_edit_images=True,
+ ),
+ ImageModelSpec(
+ base_model="qwen-image-2-1-turbo",
+ tasks=("generation", "edit"),
+ estimated_size=IMAGE_UNKNOWN_FALLBACK_SIZE,
+ discovery_aliases=_aliases("qwen-image-2.1-turbo", "Qwen/Qwen-Image-2.1-Turbo"),
+ allows_multiple_edit_images=True,
+ ),
+ ImageModelSpec(
+ base_model="flux2-klein-4b",
+ tasks=("generation", "edit"),
+ estimated_size=8 * 1024**3,
+ discovery_aliases=_aliases(
+ "flux2-klein-4b",
+ "flux2-klein",
+ "klein-4b",
+ "black-forest-labs/FLUX.2-klein-4B",
+ ),
+ allows_multiple_edit_images=True,
+ ),
+ ImageModelSpec(
+ base_model="flux2-klein-9b",
+ tasks=("generation", "edit"),
+ estimated_size=18 * 1024**3,
+ discovery_aliases=_aliases(
+ "flux2-klein-9b",
+ "klein-9b",
+ "black-forest-labs/FLUX.2-klein-9B",
+ ),
+ allows_multiple_edit_images=True,
+ ),
+ ImageModelSpec(
+ base_model="flux2-klein-base-4b",
+ tasks=("generation", "edit"),
+ estimated_size=8 * 1024**3,
+ discovery_aliases=_aliases(
+ "flux2-klein-base-4b",
+ "flux2-base-4b",
+ "klein-base-4b",
+ "black-forest-labs/FLUX.2-klein-base-4B",
+ ),
+ allows_multiple_edit_images=True,
+ ),
+ ImageModelSpec(
+ base_model="flux2-klein-base-9b",
+ tasks=("generation", "edit"),
+ estimated_size=18 * 1024**3,
+ discovery_aliases=_aliases(
+ "flux2-klein-base-9b",
+ "flux2-base-9b",
+ "klein-base-9b",
+ "black-forest-labs/FLUX.2-klein-base-9B",
+ ),
+ allows_multiple_edit_images=True,
+ ),
+ ImageModelSpec(
+ base_model="flux2-klein-9b-kv",
+ tasks=("generation", "edit"),
+ estimated_size=18 * 1024**3,
+ discovery_aliases=_aliases(
+ "flux2-klein-9b-kv",
+ "klein-9b-kv",
+ "black-forest-labs/FLUX.2-klein-9b-kv",
+ ),
+ allows_multiple_edit_images=True,
+ ),
+ ImageModelSpec(
+ base_model="mage-flow-base",
+ tasks=("generation",),
+ estimated_size=10 * 1024**3,
+ discovery_aliases=_aliases(
+ "mage-flow-base",
+ "mage-flow-4b-base",
+ "microsoft/Mage-Flow-Base",
+ ),
+ ),
+ ImageModelSpec(
+ base_model="mage-flow",
+ tasks=("generation",),
+ estimated_size=10 * 1024**3,
+ discovery_aliases=_aliases(
+ "mage-flow",
+ "mage-flow-aligned",
+ "mage-flow-4b",
+ "mage-flow-4b-aligned",
+ "microsoft/Mage-Flow",
+ ),
+ ),
+ ImageModelSpec(
+ base_model="mage-flow-turbo",
+ tasks=("generation",),
+ estimated_size=10 * 1024**3,
+ discovery_aliases=_aliases(
+ "mage-flow-turbo",
+ "mage-flow-4b-turbo",
+ "microsoft/Mage-Flow-Turbo",
+ ),
+ ),
+ ImageModelSpec(
+ base_model="mage-flow-edit-base",
+ tasks=("edit",),
+ estimated_size=10 * 1024**3,
+ discovery_aliases=_aliases(
+ "mage-flow-edit-base",
+ "mage-flow-edit-4b-base",
+ "microsoft/Mage-Flow-Edit-Base",
+ ),
+ allows_multiple_edit_images=True,
+ ),
+ ImageModelSpec(
+ base_model="mage-flow-edit",
+ tasks=("edit",),
+ estimated_size=10 * 1024**3,
+ discovery_aliases=_aliases(
+ "mage-flow-edit",
+ "mage-flow-edit-aligned",
+ "mage-flow-edit-4b",
+ "mage-flow-edit-4b-aligned",
+ "microsoft/Mage-Flow-Edit",
+ ),
+ allows_multiple_edit_images=True,
+ ),
+ ImageModelSpec(
+ base_model="mage-flow-edit-turbo",
+ tasks=("edit",),
+ estimated_size=10 * 1024**3,
+ discovery_aliases=_aliases(
+ "mage-flow-edit-turbo",
+ "mage-flow-edit-4b-turbo",
+ "microsoft/Mage-Flow-Edit-Turbo",
+ ),
+ allows_multiple_edit_images=True,
+ ),
+ ImageModelSpec(
+ base_model="ming-image-0-1-design",
+ tasks=("generation",),
+ estimated_size=28 * 1024**3,
+ discovery_aliases=_aliases(
+ "ming-image-0.1-design",
+ "ming-image",
+ "inclusionAI/Ming-Image-0.1-Design",
+ ),
+ ),
+ ImageModelSpec(
+ base_model="z-image",
+ tasks=("generation", "edit"),
+ estimated_size=12 * 1024**3,
+ discovery_aliases=_aliases(
+ "z-image",
+ "zimage",
+ "tongyi-mai/Z-Image",
+ ),
+ ),
+ ImageModelSpec(
+ base_model="z-image-turbo",
+ tasks=("generation", "edit"),
+ estimated_size=12 * 1024**3,
+ discovery_aliases=_aliases(
+ "z-image-turbo",
+ "zimage-turbo",
+ "tongyi-mai/Z-Image-Turbo",
+ ),
+ ),
+ ImageModelSpec(
+ base_model="ernie-image",
+ tasks=("generation", "edit"),
+ estimated_size=22 * 1024**3,
+ discovery_aliases=_aliases(
+ "ernie-image",
+ "ernie-image-base",
+ "baidu/ERNIE-Image",
+ ),
+ ),
+ ImageModelSpec(
+ base_model="ernie-image-turbo",
+ tasks=("generation", "edit"),
+ estimated_size=22 * 1024**3,
+ discovery_aliases=_aliases(
+ "ernie-image-turbo",
+ "ernie-turbo",
+ "baidu/ERNIE-Image-Turbo",
+ ),
+ ),
+ ImageModelSpec(
+ base_model="ideogram-4-fp8",
+ tasks=("generation",),
+ estimated_size=28 * 1024**3,
+ discovery_aliases=_aliases(
+ "ideogram-4-fp8",
+ "ideogram4-fp8",
+ "ideogram4",
+ "ideogram-4",
+ "ideogram",
+ "ideogram-ai/ideogram-4-fp8",
+ ),
+ ),
+ ImageModelSpec(
+ base_model="ternary",
+ tasks=("generation",),
+ estimated_size=8 * 1024**3,
+ discovery_aliases=_aliases(
+ "ternary",
+ "bonsai",
+ "bonsai-ternary",
+ "ternary-mlx",
+ "bonsai-ternary-mlx",
+ "2bit",
+ "prism-ml/bonsai-image-ternary-4B-mlx-2bit",
+ ),
+ ),
+)
+
+
+def _build_aliases() -> dict[tuple[ImageTask, str], tuple[str, ...]]:
+ aliases: dict[tuple[ImageTask, str], tuple[str, ...]] = {}
+ for spec in IMAGE_MODEL_SPECS:
+ values = _aliases(spec.base_model, *spec.discovery_aliases)
+ for task in spec.tasks:
+ aliases[(task, spec.base_model)] = values
+ return aliases
+
+
+IMAGE_ENGINE_ALIASES = _build_aliases()
+_SPEC_BY_BASE_MODEL = {spec.base_model: spec for spec in IMAGE_MODEL_SPECS}
+_RUNTIME_MODEL_REFERENCES = {
+ "qwen-image-2-1": "Qwen/Qwen-Image-2.1",
+ "qwen-image-2-1-turbo": "Qwen/Qwen-Image-2.1-Turbo",
+ "ideogram-4-fp8": "ideogram-ai/ideogram-4-fp8",
+ "ming-image-0-1-design": "inclusionAI/Ming-Image-0.1-Design",
+ "z-image": "Tongyi-MAI/Z-Image",
+ "z-image-turbo": "Tongyi-MAI/Z-Image-Turbo",
+}
+
+
+def image_engine_aliases(task: ImageTask, base_model: str) -> tuple[str, ...]:
+ """Return supported aliases for a canonical base model and image task."""
+ return IMAGE_ENGINE_ALIASES.get((task, _canonical_base_model(base_model)), ())
+
+
+def _canonical_base_model(base_model: str) -> str:
+ """Return the registry base model for a user-facing image alias."""
+ normalized = normalize_image_alias(base_model)
+ for (_, canonical), aliases in IMAGE_ENGINE_ALIASES.items():
+ if normalized == canonical or normalized in aliases:
+ return canonical
+ return normalized
+
+
+def get_image_model_spec(base_model: str) -> ImageModelSpec | None:
+ """Return the registered model family for an alias, if it is supported."""
+ return _SPEC_BY_BASE_MODEL.get(_canonical_base_model(base_model))
+
+
+def get_image_model_reference(base_model: str) -> str:
+ """Return the mlx-vlm loader reference for a supported family alias."""
+ canonical = _canonical_base_model(base_model)
+ return _RUNTIME_MODEL_REFERENCES.get(canonical, canonical)
+
+
+def image_edit_accepts_multiple_inputs(base_model: str) -> bool:
+ """Return whether an edit family accepts multiple reference images."""
+ spec = get_image_model_spec(base_model)
+ return bool(spec and spec.allows_multiple_edit_images)
+
+
+IMAGE_DEFAULT_ESTIMATED_SIZES = {
+ alias: spec.estimated_size
+ for spec in IMAGE_MODEL_SPECS
+ for alias in _aliases(spec.base_model, *spec.discovery_aliases)
+}
+
+
+def _matches_image_model_prefix(normalized_name: str, alias: str) -> bool:
+ if normalized_name == alias or normalized_name.startswith(f"{alias}-"):
+ return True
+
+ compact_name = normalized_name.replace("-", "")
+ compact_alias = alias.replace("-", "")
+ return compact_name == compact_alias or compact_name.startswith(compact_alias)
+
+
+def infer_image_model_spec_from_name(name: str) -> ImageModelSpec | None:
+ """Return the supported image spec implied by a local model folder name."""
+ normalized_name = normalize_image_alias(name)
+ candidates = [
+ (len(alias.replace("-", "")), spec, alias)
+ for spec in IMAGE_MODEL_SPECS
+ for alias in spec.discovery_aliases
+ ]
+ for _, spec, alias in sorted(
+ candidates,
+ key=lambda candidate: candidate[0],
+ reverse=True,
+ ):
+ if _matches_image_model_prefix(normalized_name, alias):
+ return spec
+ return None
diff --git a/omlx/patches/mlx_vlm_image_compat/README.md b/omlx/patches/mlx_vlm_image_compat/README.md
new file mode 100644
index 0000000000..5a1f10f5a3
--- /dev/null
+++ b/omlx/patches/mlx_vlm_image_compat/README.md
@@ -0,0 +1,13 @@
+# mlx-vlm image compatibility
+
+oMLX delegates image model detection, per-model sampling defaults and input
+validation to mlx-vlm.
+
+The tokenizer patch forces the native Z-Image tokenizer to load locally with
+`trust_remote_code=False`, preserving oMLX's safe model-loading default.
+
+Local generation loading checks supported checkpoint metadata before folder
+aliases, matching mlx-vlm's capability probe. The pinned loader otherwise
+checks aliases first and can select Qwen for a renamed Mage-Flow checkpoint.
+Remote references and checkpoints without a supported metadata match still
+use the native loader.
diff --git a/omlx/patches/mlx_vlm_image_compat/__init__.py b/omlx/patches/mlx_vlm_image_compat/__init__.py
new file mode 100644
index 0000000000..d149b2a569
--- /dev/null
+++ b/omlx/patches/mlx_vlm_image_compat/__init__.py
@@ -0,0 +1,76 @@
+# SPDX-License-Identifier: Apache-2.0
+
+from __future__ import annotations
+
+import importlib
+import logging
+from functools import wraps
+from pathlib import Path
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+_APPLIED = False
+
+
+def apply_mlx_vlm_image_compat_patch() -> bool:
+ global _APPLIED
+ if _APPLIED:
+ return False
+
+ _patch_z_image_tokenizer_security()
+ _patch_local_generation_model_selection()
+
+ _APPLIED = True
+ logger.info("mlx-vlm image compatibility patch applied")
+ return True
+
+
+def is_applied() -> bool:
+ """Return whether the compatibility layer has been registered."""
+ return _APPLIED
+
+
+def _patch_z_image_tokenizer_security() -> None:
+ """Keep native Z-Image tokenizer loading local and remote-code-free."""
+ pipeline = importlib.import_module("mlx_vlm.models.z_image.pipeline")
+ tokenizer = pipeline.AutoTokenizer
+ if getattr(tokenizer, "_omlx_safe_z_image_tokenizer", False):
+ return
+
+ class SafeAutoTokenizer:
+ _omlx_safe_z_image_tokenizer = True
+
+ @staticmethod
+ def from_pretrained(*args: Any, **kwargs: Any) -> Any:
+ kwargs["local_files_only"] = True
+ kwargs["trust_remote_code"] = False
+ return tokenizer.from_pretrained(*args, **kwargs)
+
+ pipeline.AutoTokenizer = SafeAutoTokenizer
+
+
+def _patch_local_generation_model_selection() -> None:
+ image = importlib.import_module("mlx_vlm.generate.image")
+ original = image.load_image_generation_model
+
+ @wraps(original)
+ def load_image_generation_model(model: str | None, **kwargs: Any) -> Any:
+ if model is not None:
+ root = Path(model).expanduser()
+ if root.exists():
+ for model_type in image._local_image_model_types(str(root)):
+ model_class = image._supported_image_model_class(
+ model_type, str(root)
+ )
+ if model_class is not None:
+ kwargs.pop("force_download", None)
+ kwargs.pop("revision", None)
+ kwargs.setdefault("model_path", root)
+ return model_class.from_model_id(model, **kwargs)
+ return original(model, **kwargs)
+
+ image.load_image_generation_model = load_image_generation_model
+
+
+__all__ = ["apply_mlx_vlm_image_compat_patch", "is_applied"]
diff --git a/omlx/patches/mlx_vlm_qwen_image_compat/__init__.py b/omlx/patches/mlx_vlm_qwen_image_compat/__init__.py
new file mode 100644
index 0000000000..97aeb8f4a8
--- /dev/null
+++ b/omlx/patches/mlx_vlm_qwen_image_compat/__init__.py
@@ -0,0 +1,101 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Exact temporary Qwen Image 2.1 backport, activated before Qwen model load."""
+
+from __future__ import annotations
+
+import importlib
+import logging
+import threading
+from pathlib import Path
+from types import ModuleType
+
+from .generate_backport import SYMBOLS, selected_source, source_hash
+
+logger = logging.getLogger(__name__)
+_APPLIED = False
+_LOCK = threading.Lock()
+
+
+def _prepare_sources(
+ sources: dict[str, str],
+ backports: dict[str, tuple[str, str, tuple[tuple[str, str], ...]]],
+) -> dict[str, str]:
+ states = {
+ name: source_hash(selected_source(source, SYMBOLS.get(name)))
+ for name, source in sources.items()
+ }
+ if all(states[name] == spec[1] for name, spec in backports.items()):
+ return {}
+ unknown = [name for name, spec in backports.items() if states.get(name) != spec[0]]
+ if unknown:
+ raise RuntimeError(
+ "Unsupported or partially fixed mlx-vlm Qwen image source: "
+ + ", ".join(unknown)
+ + ". Update the verified Qwen image compatibility backport."
+ )
+ patched = {}
+ for name, (_, native_hash, edits) in backports.items():
+ source = selected_source(sources[name], SYMBOLS.get(name))
+ for before, after in edits:
+ if source.count(before) != 1:
+ raise RuntimeError(f"Qwen image backport context mismatch: {name}")
+ source = source.replace(before, after, 1)
+ if source_hash(source) != native_hash:
+ raise RuntimeError(f"Qwen image backport result mismatch: {name}")
+ patched[name] = source
+ return patched
+
+
+def _read_source(module: ModuleType) -> str:
+ if module.__file__ is None:
+ raise RuntimeError(f"Qwen image module has no Python source: {module.__name__}")
+ return Path(module.__file__).read_text()
+
+
+def apply_qwen_image_compat_patch() -> bool:
+ """Backport only verified legacy code; complete native fixes are a no-op."""
+ global _APPLIED
+ with _LOCK:
+ if _APPLIED:
+ return False
+ from ._backport import BACKPORTS, SOURCE_REVISION
+
+ modules = {name: importlib.import_module(name) for name in BACKPORTS}
+ patched = _prepare_sources(
+ {name: _read_source(module) for name, module in modules.items()}, BACKPORTS
+ )
+ if not patched:
+ return False
+ package = importlib.import_module("mlx_vlm.models.qwen_image")
+ image = modules["mlx_vlm.generate.image"]
+ edit_image = importlib.import_module("mlx_vlm.generate.edit_image")
+ caches = (
+ getattr(image, "_image_model_class_for_type", None),
+ getattr(edit_image, "_image_edit_model_class_for_type", None),
+ )
+ if not isinstance(getattr(package, "__all__", None), list) or any(
+ not callable(getattr(cache, "cache_clear", None)) for cache in caches
+ ):
+ raise RuntimeError("Unsupported mlx-vlm Qwen image dispatch/cache shape")
+ # Compile every checked source before changing any module.
+ codes = {
+ name: compile(source, f"", "exec")
+ for name, source in patched.items()
+ }
+ for name, code in codes.items():
+ exec(code, modules[name].__dict__)
+
+ config = modules["mlx_vlm.models.qwen_image.config"]
+ model = modules["mlx_vlm.models.qwen_image.model"]
+ for name in package.__all__:
+ if hasattr(model, name):
+ setattr(package, name, getattr(model, name))
+ elif hasattr(config, name):
+ setattr(package, name, getattr(config, name))
+ image._image_model_class_for_type.cache_clear()
+ edit_image._image_edit_model_class_for_type.cache_clear()
+ _APPLIED = True
+ logger.info(
+ "Qwen image compatibility backport applied from %s", SOURCE_REVISION
+ )
+ return True
diff --git a/omlx/patches/mlx_vlm_qwen_image_compat/_backport.py b/omlx/patches/mlx_vlm_qwen_image_compat/_backport.py
new file mode 100644
index 0000000000..724acf2db2
--- /dev/null
+++ b/omlx/patches/mlx_vlm_qwen_image_compat/_backport.py
@@ -0,0 +1,811 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Generated from mlx-vlm; regenerate with generate_backport.py."""
+
+SOURCE_REVISION = "9a200804c81b98fd420d1f8a064a6824cec76f4f"
+BASE_REVISION = "4f4634bb813c0298cb1467bed2e957526c71d0b4"
+BACKPORTS = {'mlx_vlm.models.qwen_image.config': ('f223a1cd7ae83fa66ec090b0ee7512fd06e789512b8d5e3f2ff0d9dea47f2b26',
+ '0099f6d10dcf9506b53d21aebd760c123a2d53ea7412da413d8ae74e0d90255e',
+ (('from __future__ import annotations\n'
+ '\n'
+ 'import json\n'
+ 'from dataclasses import dataclass\n'
+ 'from pathlib import Path\n'
+ '\n'
+ '\n',
+ 'from __future__ import annotations\n'
+ '\n'
+ 'import json\n'
+ 'import math\n'
+ 'from collections.abc import Sequence\n'
+ 'from dataclasses import dataclass, replace\n'
+ 'from numbers import Real\n'
+ 'from pathlib import Path\n'
+ '\n'
+ '\n'),
+ (' uses_reference_kv_cache=True,\n'
+ ' ),\n'
+ '}\n'
+ '\n'
+ '_ALIASES = {\n'
+ ' alias.lower(): variant for variant in '
+ 'VARIANTS.values() for alias in variant.aliases\n',
+ ' uses_reference_kv_cache=True,\n'
+ ' ),\n'
+ '}\n'
+ 'VARIANTS["qwen-image-2.1-turbo"] = replace(\n'
+ ' VARIANTS["qwen-image-2.1"],\n'
+ ' name="qwen-image-2.1-turbo",\n'
+ ' aliases=(\n'
+ ' "qwen-image-2.1-turbo",\n'
+ ' "qwen-image-2_1-turbo",\n'
+ ' "qwen_image_2_1_turbo",\n'
+ ' "Qwen/Qwen-Image-2.1-Turbo",\n'
+ ' ),\n'
+ ' repo_id="Qwen/Qwen-Image-2.1-Turbo",\n'
+ ' local_dir_name="Qwen-Image-2.1-Turbo",\n'
+ ')\n'
+ '\n'
+ '_ALIASES = {\n'
+ ' alias.lower(): variant for variant in '
+ 'VARIANTS.values() for alias in variant.aliases\n'),
+ (' if root.parent.name == "snapshots" and '
+ 'root.parent.parent.name.startswith(\n'
+ ' "models--"\n'
+ ' ):\n'
+ ' name = '
+ 'root.parent.parent.name.removeprefix("models--").replace("--", '
+ '"/")\n'
+ ' if "qwen" in name and "image" in name:\n'
+ ' return VARIANTS["qwen-image-2.1"]\n'
+ '\n'
+ ' transformer_config = root / "transformer" / '
+ '"config.json"\n'
+ ' if transformer_config.exists():\n',
+ ' if root.parent.name == "snapshots" and '
+ 'root.parent.parent.name.startswith(\n'
+ ' "models--"\n'
+ ' ):\n'
+ ' name = (\n'
+ ' '
+ 'root.parent.parent.name.removeprefix("models--").replace("--", '
+ '"/").lower()\n'
+ ' )\n'
+ ' if "qwen" in name and "image" in name:\n'
+ ' return VARIANTS["qwen-image-2.1-turbo" if "turbo" '
+ 'in name else "qwen-image-2.1"]\n'
+ '\n'
+ ' transformer_config = root / "transformer" / '
+ '"config.json"\n'
+ ' if transformer_config.exists():\n'),
+ (' return tuple(VARIANTS)\n'
+ '\n'
+ '\n'
+ 'def validate_dimensions(*, width: int, height: int) -> '
+ 'None:\n'
+ ' for label, value in (("width", width), ("height", '
+ 'height)):\n'
+ ' if value < 256 or value > 2048:\n',
+ ' return tuple(VARIANTS)\n'
+ '\n'
+ '\n'
+ 'def validate_sigmas(sigmas: Sequence[float]) -> '
+ 'tuple[float, ...]:\n'
+ ' if not isinstance(sigmas, Sequence) or not sigmas:\n'
+ ' raise ValueError(\n'
+ ' "sigmas must be a nonempty sequence excluding '
+ 'the terminal zero"\n'
+ ' )\n'
+ ' if any(\n'
+ ' isinstance(value, bool)\n'
+ ' or not isinstance(value, Real)\n'
+ ' or not math.isfinite(value)\n'
+ ' or not 0 < value <= 1\n'
+ ' for value in sigmas\n'
+ ' ):\n'
+ ' raise ValueError("sigmas must contain finite '
+ 'numbers in (0, 1]")\n'
+ ' values = tuple(float(value) for value in sigmas)\n'
+ ' if any(a <= b for a, b in zip(values, values[1:])):\n'
+ ' raise ValueError("sigmas must be strictly '
+ 'decreasing")\n'
+ ' return values\n'
+ '\n'
+ '\n'
+ 'def load_sample_sigmas(model_path: str | Path) -> '
+ 'tuple[float, ...] | None:\n'
+ ' path = Path(model_path) / "model_index.json"\n'
+ ' if not path.exists():\n'
+ ' return None\n'
+ ' config = json.loads(path.read_text())\n'
+ ' if not isinstance(config, dict):\n'
+ ' raise ValueError(f"Expected an object in '
+ '{path}")\n'
+ ' sigmas = config.get("sample_sigmas")\n'
+ ' return None if sigmas is None else '
+ 'validate_sigmas(sigmas)\n'
+ '\n'
+ '\n'
+ 'def resolve_sampling(\n'
+ ' steps: int,\n'
+ ' sigmas: Sequence[float] | None,\n'
+ ' sample_sigmas: tuple[float, ...] | None,\n'
+ ') -> tuple[int, tuple[float, ...] | None]:\n'
+ ' if isinstance(steps, bool) or not isinstance(steps, '
+ 'int) or steps < 1:\n'
+ ' raise ValueError("steps must be a positive '
+ 'integer")\n'
+ ' selected = sample_sigmas if sigmas is None else '
+ 'sigmas\n'
+ ' selected = None if selected is None else '
+ 'validate_sigmas(selected)\n'
+ ' return (steps if selected is None else '
+ 'len(selected)), selected\n'
+ '\n'
+ '\n'
+ 'def validate_guidance(guidance: float) -> None:\n'
+ ' if (\n'
+ ' isinstance(guidance, bool)\n'
+ ' or not isinstance(guidance, Real)\n'
+ ' or not math.isfinite(guidance)\n'
+ ' or guidance <= 0\n'
+ ' ):\n'
+ ' raise ValueError("guidance must be finite and '
+ 'positive")\n'
+ '\n'
+ '\n'
+ 'def validate_dimensions(*, width: int, height: int) -> '
+ 'None:\n'
+ ' for label, value in (("width", width), ("height", '
+ 'height)):\n'
+ ' if value < 256 or value > 2048:\n'))),
+ 'mlx_vlm.models.qwen_image.scheduler': ('2a8e6017536d8c6f5b9252d82fd2949de13e576a49735fa69926f410a12dea3b',
+ '80f6f6976f2ffa5f8b221bc7b28bdd0834ddb645e192649582af593a96a57875',
+ (('"""FlowMatchEuler scheduler for Qwen-Image-2.1 '
+ '(dynamic exponential shift).\n'
+ '\n'
+ 'Mirrors the structure of ``flux2.scheduler`` but uses '
+ "Qwen-Image's linear\n"
+ '``calculate_shift`` (base/max shift over image '
+ 'sequence length) instead of\n',
+ '"""FlowMatchEuler scheduler for Qwen-Image-2.1 and '
+ 'saved sampling grids.\n'
+ '\n'
+ 'Mirrors the structure of ``flux2.scheduler`` but uses '
+ "Qwen-Image's linear\n"
+ '``calculate_shift`` (base/max shift over image '
+ 'sequence length) instead of\n'),
+ ('\n'
+ 'from __future__ import annotations\n'
+ '\n'
+ 'import mlx.core as mx\n'
+ '\n'
+ '\n'
+ 'def calculate_shift(\n',
+ '\n'
+ 'from __future__ import annotations\n'
+ '\n'
+ 'import math\n'
+ 'from collections.abc import Sequence\n'
+ 'from numbers import Real\n'
+ '\n'
+ 'import mlx.core as mx\n'
+ '\n'
+ 'from .config import resolve_sampling\n'
+ '\n'
+ '\n'
+ 'def calculate_shift(\n'),
+ (' max_image_seq_len: int = 8192,\n'
+ ' num_train_timesteps: int = 1000,\n'
+ ' shift_terminal: float | None = 0.02,\n'
+ ' ) -> None:\n'
+ ' sigmas = mx.linspace(\n'
+ ' 1.0, 1.0 / num_inference_steps, '
+ 'num_inference_steps, dtype=mx.float32\n'
+ ' )\n'
+ ' mu = calculate_shift(\n'
+ ' image_seq_len, base_image_seq_len, '
+ 'max_image_seq_len, base_shift, max_shift\n'
+ ' )\n'
+ ' sigmas = mx.exp(mu) / (mx.exp(mu) + (1.0 / '
+ 'sigmas - 1.0))\n'
+ ' # Stretch the shifted schedule before '
+ 'appending the final zero sigma.\n'
+ ' # A one-step schedule has no interval to '
+ 'stretch and starts at pure noise.\n'
+ ' if shift_terminal and num_inference_steps > '
+ '1:\n'
+ ' one_minus_sigmas = 1.0 - sigmas\n'
+ ' scale = one_minus_sigmas[-1] / (1.0 - '
+ 'shift_terminal)\n'
+ ' sigmas = 1.0 - one_minus_sigmas / scale\n'
+ ' self.timesteps = sigmas * num_train_timesteps\n'
+ ' self.sigmas = mx.concatenate(\n'
+ ' [sigmas, mx.zeros((1,), '
+ 'dtype=sigmas.dtype)], axis=0\n',
+ ' max_image_seq_len: int = 8192,\n'
+ ' num_train_timesteps: int = 1000,\n'
+ ' shift_terminal: float | None = 0.02,\n'
+ ' sigmas: Sequence[float] | None = None,\n'
+ ' use_dynamic_shifting: bool = True,\n'
+ ' shift: float = 1.0,\n'
+ ' ) -> None:\n'
+ ' num_inference_steps, sigmas = '
+ 'resolve_sampling(\n'
+ ' num_inference_steps, sigmas, None\n'
+ ' )\n'
+ ' if not isinstance(use_dynamic_shifting, '
+ 'bool):\n'
+ ' raise ValueError("use_dynamic_shifting '
+ 'must be a boolean")\n'
+ ' if (\n'
+ ' isinstance(shift, bool)\n'
+ ' or not isinstance(shift, Real)\n'
+ ' or not math.isfinite(shift)\n'
+ ' or shift <= 0\n'
+ ' ):\n'
+ ' raise ValueError("shift must be finite and '
+ 'positive")\n'
+ ' if shift_terminal is not None and (\n'
+ ' isinstance(shift_terminal, bool)\n'
+ ' or not isinstance(shift_terminal, Real)\n'
+ ' or not math.isfinite(shift_terminal)\n'
+ ' or not 0 <= shift_terminal < 1\n'
+ ' ):\n'
+ ' raise ValueError("shift_terminal must be '
+ 'finite and in [0, 1)")\n'
+ ' sigmas = (\n'
+ ' mx.linspace(\n'
+ ' 1.0, 1.0 / num_inference_steps, '
+ 'num_inference_steps, dtype=mx.float32\n'
+ ' )\n'
+ ' if sigmas is None\n'
+ ' else mx.array(sigmas, dtype=mx.float32)\n'
+ ' )\n'
+ ' if bool(mx.any(sigmas <= 0)) or '
+ 'bool(mx.any(sigmas[:-1] <= sigmas[1:])):\n'
+ ' raise ValueError(\n'
+ ' "sigmas must remain positive and '
+ 'strictly decreasing in float32"\n'
+ ' )\n'
+ ' if use_dynamic_shifting:\n'
+ ' mu = calculate_shift(\n'
+ ' image_seq_len,\n'
+ ' base_image_seq_len,\n'
+ ' max_image_seq_len,\n'
+ ' base_shift,\n'
+ ' max_shift,\n'
+ ' )\n'
+ ' sigmas = mx.exp(mu) / (mx.exp(mu) + (1.0 / '
+ 'sigmas - 1.0))\n'
+ ' elif shift != 1.0:\n'
+ ' sigmas = shift * sigmas / (1.0 + (shift - '
+ '1.0) * sigmas)\n'
+ ' # Stretch the shifted schedule before '
+ 'appending the final zero sigma.\n'
+ ' # A one-step schedule has no interval to '
+ 'stretch and starts at pure noise.\n'
+ ' if shift_terminal and num_inference_steps > '
+ '1:\n'
+ ' if float(sigmas[-1]) == 1.0:\n'
+ ' raise ValueError("Cannot stretch a '
+ 'schedule whose last sigma is 1")\n'
+ ' one_minus_sigmas = 1.0 - sigmas\n'
+ ' scale = one_minus_sigmas[-1] / (1.0 - '
+ 'shift_terminal)\n'
+ ' sigmas = 1.0 - one_minus_sigmas / scale\n'
+ ' if (\n'
+ ' not bool(mx.all(mx.isfinite(sigmas)))\n'
+ ' or bool(mx.any(sigmas <= 0))\n'
+ ' or bool(mx.any(sigmas[:-1] <= '
+ 'sigmas[1:]))\n'
+ ' ):\n'
+ ' raise ValueError("Processed sigmas must be '
+ 'finite, positive and decreasing")\n'
+ ' self.timesteps = sigmas * num_train_timesteps\n'
+ ' self.sigmas = mx.concatenate(\n'
+ ' [sigmas, mx.zeros((1,), '
+ 'dtype=sigmas.dtype)], axis=0\n'))),
+ 'mlx_vlm.models.qwen_image.text_encoder': ('844c0f95932fdb28265f3ce25e17a5300802f5143ec593baf2ddcae0f8891115',
+ 'edfdfe05f14b5c3a9bad9a2ca0cf26c885753ae5732c194e50355d47f001500f',
+ ((' return hidden[:, self.drop_idx :]\n'
+ '\n'
+ ' @property\n'
+ ' def processor(self):\n'
+ ' if self._processor is None:\n'
+ ' config = json.loads(\n'
+ ' (Path(self.processor_dir) / '
+ '"preprocessor_config.json").read_text()\n'
+ ' )\n'
+ ' size = config.get("size", {})\n'
+ ' config["min_pixels"] = '
+ 'config.get("min_pixels") or size.get(\n'
+ ' "shortest_edge", 65536\n'
+ ' )\n',
+ ' return hidden[:, self.drop_idx :]\n'
+ '\n'
+ ' @property\n'
+ ' def processor(self) -> Qwen3VLProcessor:\n'
+ ' if self._processor is None:\n'
+ ' path = Path(self.processor_dir) / '
+ '"preprocessor_config.json"\n'
+ ' if path.exists():\n'
+ ' config = '
+ 'json.loads(path.read_text())\n'
+ ' else:\n'
+ ' path = Path(self.processor_dir) / '
+ '"processor_config.json"\n'
+ ' config = '
+ 'json.loads(path.read_text())\n'
+ ' if not isinstance(config, dict) or '
+ '"image_processor" not in config:\n'
+ ' raise ValueError(f"Missing '
+ 'image_processor configuration in {path}")\n'
+ ' config = config["image_processor"]\n'
+ ' if not isinstance(config, dict):\n'
+ ' raise ValueError(\n'
+ ' f"Expected image processor '
+ 'configuration object in {path}"\n'
+ ' )\n'
+ ' size = config.get("size", {})\n'
+ ' if not isinstance(size, dict):\n'
+ ' raise ValueError(f"Expected image '
+ 'processor size object in {path}")\n'
+ ' config["min_pixels"] = '
+ 'config.get("min_pixels") or size.get(\n'
+ ' "shortest_edge", 65536\n'
+ ' )\n'),)),
+ 'mlx_vlm.models.qwen_image.pipeline': ('10d29a321c9467b571e284c56167e4e666f7441bb66d43c03c1c3649debc6280',
+ '2fb6b85468f0ff8bf58b5f8cdbb2381b788ece4f19a4495b386fed99f75e112b',
+ (('import numpy as np\n'
+ 'from PIL import Image\n'
+ '\n'
+ 'from .config import QwenImageVariant, get_variant\n'
+ 'from .download import download_model, '
+ 'validate_model_layout\n'
+ 'from .kv_cache import QwenImageKVCache\n'
+ 'from .scheduler import '
+ 'FlowMatchEulerDiscreteScheduler\n',
+ 'import numpy as np\n'
+ 'from PIL import Image\n'
+ '\n'
+ 'from .config import (\n'
+ ' QwenImageVariant,\n'
+ ' get_variant,\n'
+ ' load_sample_sigmas,\n'
+ ' resolve_sampling,\n'
+ ' validate_guidance,\n'
+ ')\n'
+ 'from .download import download_model, '
+ 'validate_model_layout\n'
+ 'from .kv_cache import QwenImageKVCache\n'
+ 'from .scheduler import '
+ 'FlowMatchEulerDiscreteScheduler\n'),
+ (' )\n'
+ ' self.latents_std = '
+ 'mx.array(cfg["latents_std"]).reshape(1, self.z_dim, 1, '
+ '1, 1)\n'
+ ' self.quantization_config = '
+ '_read_quant(self.model_path / "transformer")\n'
+ ' scheduler_path = self.model_path / "scheduler" '
+ '/ "scheduler_config.json"\n'
+ ' scheduler_config = (\n'
+ ' json.loads(scheduler_path.read_text()) if '
+ 'scheduler_path.exists() else {}\n'
+ ' )\n'
+ ' self.scheduler_config = {\n'
+ ' key: scheduler_config[key]\n'
+ ' for key in (\n',
+ ' )\n'
+ ' self.latents_std = '
+ 'mx.array(cfg["latents_std"]).reshape(1, self.z_dim, 1, '
+ '1, 1)\n'
+ ' self.quantization_config = '
+ '_read_quant(self.model_path / "transformer")\n'
+ ' self.sample_sigmas = '
+ 'load_sample_sigmas(self.model_path)\n'
+ ' scheduler_path = self.model_path / "scheduler" '
+ '/ "scheduler_config.json"\n'
+ ' scheduler_config = (\n'
+ ' json.loads(scheduler_path.read_text()) if '
+ 'scheduler_path.exists() else {}\n'
+ ' )\n'
+ ' if not isinstance(scheduler_config, dict):\n'
+ ' raise ValueError(f"Expected an object in '
+ '{scheduler_path}")\n'
+ ' for key in (\n'
+ ' "use_beta_sigmas",\n'
+ ' "use_exponential_sigmas",\n'
+ ' "use_karras_sigmas",\n'
+ ' "invert_sigmas",\n'
+ ' "stochastic_sampling",\n'
+ ' ):\n'
+ ' if scheduler_config.get(key, False) is not '
+ 'False:\n'
+ ' raise ValueError(f"Unsupported '
+ 'Qwen-Image scheduler setting: {key}")\n'
+ ' if scheduler_config.get("time_shift_type", '
+ '"exponential") != "exponential":\n'
+ ' raise ValueError("Qwen-Image only supports '
+ 'exponential time shifting")\n'
+ ' self.scheduler_config = {\n'
+ ' key: scheduler_config[key]\n'
+ ' for key in (\n'),
+ (' "max_image_seq_len",\n'
+ ' "num_train_timesteps",\n'
+ ' "shift_terminal",\n'
+ ' )\n'
+ ' if key in scheduler_config\n'
+ ' }\n',
+ ' "max_image_seq_len",\n'
+ ' "num_train_timesteps",\n'
+ ' "shift_terminal",\n'
+ ' "use_dynamic_shifting",\n'
+ ' "shift",\n'
+ ' )\n'
+ ' if key in scheduler_config\n'
+ ' }\n'),
+ (' guidance: float = 1.0,\n'
+ ' negative_prompt: str = " ",\n'
+ ' num_images: int = 1,\n'
+ ' ) -> mx.array:\n'
+ ' """Generate one ``[H, W, 3]`` image, or ``[N, '
+ 'H, W, 3]`` when num_images > 1."""\n'
+ ' emb = '
+ 'self.text_encoder.encode(prompt).astype(mx.bfloat16)\n'
+ ' do_cfg = guidance is not None and guidance > '
+ '1.0\n'
+ ' neg = (\n',
+ ' guidance: float = 1.0,\n'
+ ' negative_prompt: str = " ",\n'
+ ' num_images: int = 1,\n'
+ ' sigmas: Sequence[float] | None = None,\n'
+ ' ) -> mx.array:\n'
+ ' """Generate one ``[H, W, 3]`` image, or ``[N, '
+ 'H, W, 3]`` when num_images > 1."""\n'
+ ' steps, sigmas = resolve_sampling(steps, sigmas, '
+ 'self.sample_sigmas)\n'
+ ' validate_guidance(guidance)\n'
+ ' emb = '
+ 'self.text_encoder.encode(prompt).astype(mx.bfloat16)\n'
+ ' do_cfg = guidance is not None and guidance > '
+ '1.0\n'
+ ' neg = (\n'),
+ (' height=height,\n'
+ ' guidance=guidance,\n'
+ ' num_images=num_images,\n'
+ ' )[..., :3]\n'
+ '\n'
+ ' def edit_array(\n',
+ ' height=height,\n'
+ ' guidance=guidance,\n'
+ ' num_images=num_images,\n'
+ ' sigmas=sigmas,\n'
+ ' )[..., :3]\n'
+ '\n'
+ ' def edit_array(\n'),
+ (' negative_prompt: str = " ",\n'
+ ' output_resolution: int = 1024,\n'
+ ' use_kv_cache: bool = True,\n'
+ ' ) -> mx.array:\n'
+ ' """Edit one or more references; return an [H, '
+ 'W, 4] uint8 RGBA image."""\n'
+ ' if not image_paths:\n'
+ ' raise ValueError("At least one reference '
+ 'image is required")\n'
+ ' if output_resolution < 256:\n',
+ ' negative_prompt: str = " ",\n'
+ ' output_resolution: int = 1024,\n'
+ ' use_kv_cache: bool = True,\n'
+ ' sigmas: Sequence[float] | None = None,\n'
+ ' ) -> mx.array:\n'
+ ' """Edit one or more references; return an [H, '
+ 'W, 4] uint8 RGBA image."""\n'
+ ' steps, sigmas = resolve_sampling(steps, sigmas, '
+ 'self.sample_sigmas)\n'
+ ' validate_guidance(guidance)\n'
+ ' if not image_paths:\n'
+ ' raise ValueError("At least one reference '
+ 'image is required")\n'
+ ' if output_resolution < 256:\n'),
+ (' image_pad_mask=image_pad_mask,\n'
+ ' '
+ 'negative_image_pad_mask=negative_image_pad_mask,\n'
+ ' use_kv_cache=use_kv_cache,\n'
+ ' )\n'
+ '\n'
+ ' def _sample(\n',
+ ' image_pad_mask=image_pad_mask,\n'
+ ' '
+ 'negative_image_pad_mask=negative_image_pad_mask,\n'
+ ' use_kv_cache=use_kv_cache,\n'
+ ' sigmas=sigmas,\n'
+ ' )\n'
+ '\n'
+ ' def _sample(\n'),
+ (' image_pad_mask=None,\n'
+ ' negative_image_pad_mask=None,\n'
+ ' use_kv_cache=False,\n'
+ ' ) -> mx.array:\n'
+ ' z = self.z_dim\n'
+ ' h_lat, w_lat = height // 16, width // 16\n'
+ ' tokens = h_lat * w_lat\n',
+ ' image_pad_mask=None,\n'
+ ' negative_image_pad_mask=None,\n'
+ ' use_kv_cache=False,\n'
+ ' sigmas=None,\n'
+ ' ) -> mx.array:\n'
+ ' steps, sigmas = resolve_sampling(steps, sigmas, '
+ 'self.sample_sigmas)\n'
+ ' z = self.z_dim\n'
+ ' h_lat, w_lat = height // 16, width // 16\n'
+ ' tokens = h_lat * w_lat\n'),
+ (' if neg is not None:\n'
+ ' neg = mx.broadcast_to(neg, (num_images, '
+ '*neg.shape[1:]))\n'
+ ' scheduler = FlowMatchEulerDiscreteScheduler(\n'
+ ' image_seq_len=tokens, '
+ 'num_inference_steps=steps, **self.scheduler_config\n'
+ ' )\n'
+ ' cache = negative_cache = None\n'
+ ' if (\n',
+ ' if neg is not None:\n'
+ ' neg = mx.broadcast_to(neg, (num_images, '
+ '*neg.shape[1:]))\n'
+ ' scheduler = FlowMatchEulerDiscreteScheduler(\n'
+ ' image_seq_len=tokens,\n'
+ ' num_inference_steps=steps,\n'
+ ' sigmas=sigmas,\n'
+ ' **self.scheduler_config,\n'
+ ' )\n'
+ ' cache = negative_cache = None\n'
+ ' if (\n'),
+ (' cache = QwenImageKVCache(num_layers)\n'
+ ' if neg is not None:\n'
+ ' negative_cache = '
+ 'QwenImageKVCache(num_layers)\n'
+ ' for i in range(steps):\n'
+ ' t = scheduler.timesteps[i : i + '
+ '1].astype(latents.dtype) / 1000\n'
+ ' model_input = latents\n'
+ ' edit_kwargs = {}\n',
+ ' cache = QwenImageKVCache(num_layers)\n'
+ ' if neg is not None:\n'
+ ' negative_cache = '
+ 'QwenImageKVCache(num_layers)\n'
+ ' for i in range(len(scheduler.timesteps)):\n'
+ ' t = scheduler.timesteps[i : i + '
+ '1].astype(latents.dtype) / 1000\n'
+ ' model_input = latents\n'
+ ' edit_kwargs = {}\n'))),
+ 'mlx_vlm.models.qwen_image.model': ('c3cc0c52908879d46d577a75787662e0eb30dd8a513a3a8e96b19c7dbd236f1f',
+ 'aa6a434676e00ace2b6fbcb28505aab0b5b67a82ce5c49c94d20e618eea841d7',
+ (('from __future__ import annotations\n'
+ '\n'
+ 'from dataclasses import dataclass\n'
+ 'from pathlib import Path\n'
+ 'from typing import Any, ClassVar\n'
+ '\n',
+ 'from __future__ import annotations\n'
+ '\n'
+ 'from dataclasses import dataclass, field\n'
+ 'from pathlib import Path\n'
+ 'from typing import Any, ClassVar\n'
+ '\n'),
+ (' ImageGenerationRequest,\n'
+ ' ImageGenerationResult,\n'
+ ')\n'
+ 'from mlx_vlm.generate.image_defaults import '
+ 'ImageSamplingDefaults\n'
+ '\n'
+ 'from .config import QwenImageVariant, get_variant, '
+ 'variant_from_local_path\n'
+ 'from .download import validate_model_layout\n'
+ 'from .pipeline import QwenImagePipeline\n'
+ '\n',
+ ' ImageGenerationRequest,\n'
+ ' ImageGenerationResult,\n'
+ ')\n'
+ 'from mlx_vlm.generate.image_defaults import '
+ 'ImageSamplingDefaults, image_metadata_path\n'
+ '\n'
+ 'from .config import (\n'
+ ' QwenImageVariant,\n'
+ ' get_variant,\n'
+ ' load_sample_sigmas,\n'
+ ' resolve_sampling,\n'
+ ' validate_guidance,\n'
+ ' variant_from_local_path,\n'
+ ')\n'
+ 'from .download import validate_model_layout\n'
+ 'from .pipeline import QwenImagePipeline\n'
+ '\n'),
+ (' model_id: str\n'
+ ' family: str = "qwen_image"\n'
+ '\n'
+ ' default_sampling: ClassVar[ImageSamplingDefaults] = '
+ 'ImageSamplingDefaults(30, 1.0)\n'
+ '\n'
+ ' @classmethod\n'
+ ' def resolve_defaults(\n'
+ ' cls, model: str, *, model_path: Path | None = '
+ 'None\n'
+ ' ) -> ImageSamplingDefaults:\n'
+ ' return cls.default_sampling\n'
+ '\n'
+ ' @property\n'
+ ' def variant(self) -> str:\n',
+ ' model_id: str\n'
+ ' family: str = "qwen_image"\n'
+ '\n'
+ ' _default_sampling: ClassVar[ImageSamplingDefaults] = '
+ 'ImageSamplingDefaults(30, 1.0)\n'
+ ' default_sampling: ImageSamplingDefaults = '
+ 'field(init=False)\n'
+ '\n'
+ ' def __post_init__(self) -> None:\n'
+ ' saved = self.pipeline.sample_sigmas\n'
+ ' self.default_sampling = ImageSamplingDefaults(\n'
+ ' self._default_sampling.steps if saved is None '
+ 'else len(saved),\n'
+ ' self._default_sampling.guidance,\n'
+ ' )\n'
+ '\n'
+ ' @classmethod\n'
+ ' def resolve_defaults(\n'
+ ' cls, model: str, *, model_path: Path | None = '
+ 'None\n'
+ ' ) -> ImageSamplingDefaults:\n'
+ ' if model_path is None:\n'
+ ' root = Path(model).expanduser()\n'
+ ' if root.is_dir():\n'
+ ' model_path = root\n'
+ ' else:\n'
+ ' variant = resolve_variant(model)\n'
+ ' if variant.name != '
+ '"qwen-image-2.1-turbo":\n'
+ ' return cls._default_sampling\n'
+ ' model_path = '
+ 'image_metadata_path(variant.repo_id)\n'
+ ' saved = load_sample_sigmas(model_path)\n'
+ ' return ImageSamplingDefaults(\n'
+ ' cls._default_sampling.steps if saved is None '
+ 'else len(saved),\n'
+ ' cls._default_sampling.guidance,\n'
+ ' )\n'
+ '\n'
+ ' @property\n'
+ ' def variant(self) -> str:\n'),
+ (' seed = 0 if request.seed is None else '
+ 'request.seed\n'
+ ' defaults = self.default_sampling\n'
+ ' steps = request.resolve_steps(defaults.steps)\n'
+ ' guidance = '
+ 'request.resolve_guidance(defaults.guidance)\n'
+ ' array = self.pipeline.generate_array(\n'
+ ' request.prompt,\n'
+ ' seed=seed,\n',
+ ' seed = 0 if request.seed is None else '
+ 'request.seed\n'
+ ' defaults = self.default_sampling\n'
+ ' steps = request.resolve_steps(defaults.steps)\n'
+ ' steps, sigmas = resolve_sampling(\n'
+ ' steps, request.extra.get("sigmas"), '
+ 'self.pipeline.sample_sigmas\n'
+ ' )\n'
+ ' guidance = '
+ 'request.resolve_guidance(defaults.guidance)\n'
+ ' validate_guidance(guidance)\n'
+ ' array = self.pipeline.generate_array(\n'
+ ' request.prompt,\n'
+ ' seed=seed,\n'),
+ (' guidance=guidance,\n'
+ ' '
+ 'negative_prompt=request.extra.get("negative_prompt", " '
+ '"),\n'
+ ' num_images=int(request.extra.get("num_images", '
+ '1)),\n'
+ ' )\n'
+ ' metadata = {"model_path": '
+ 'str(self.pipeline.model_path)}\n'
+ ' if self.pipeline.quantization_config:\n',
+ ' guidance=guidance,\n'
+ ' '
+ 'negative_prompt=request.extra.get("negative_prompt", " '
+ '"),\n'
+ ' num_images=int(request.extra.get("num_images", '
+ '1)),\n'
+ ' sigmas=sigmas,\n'
+ ' )\n'
+ ' metadata = {"model_path": '
+ 'str(self.pipeline.model_path)}\n'
+ ' if self.pipeline.quantization_config:\n'),
+ (' is_image_generation_model: ClassVar[bool] = False\n'
+ ' is_image_edit_model: ClassVar[bool] = True\n'
+ '\n'
+ ' default_sampling: ClassVar[ImageSamplingDefaults] = '
+ 'ImageSamplingDefaults(40, 1.0)\n'
+ '\n'
+ ' @classmethod\n'
+ ' def resolve_defaults(\n'
+ ' cls, model: str, *, model_path: Path | None = '
+ 'None\n'
+ ' ) -> ImageSamplingDefaults:\n'
+ ' return cls.default_sampling\n'
+ '\n'
+ ' def edit(self, request: ImageEditRequest) -> '
+ 'ImageGenerationResult:\n'
+ ' seed = 0 if request.seed is None else '
+ 'request.seed\n'
+ ' defaults = self.default_sampling\n'
+ ' steps = request.resolve_steps(defaults.steps)\n'
+ ' guidance = '
+ 'request.resolve_guidance(defaults.guidance)\n'
+ ' array = self.pipeline.edit_array(\n'
+ ' request.prompt,\n'
+ ' request.image_paths,\n',
+ ' is_image_generation_model: ClassVar[bool] = False\n'
+ ' is_image_edit_model: ClassVar[bool] = True\n'
+ '\n'
+ ' _default_sampling: ClassVar[ImageSamplingDefaults] = '
+ 'ImageSamplingDefaults(40, 1.0)\n'
+ '\n'
+ ' def edit(self, request: ImageEditRequest) -> '
+ 'ImageGenerationResult:\n'
+ ' seed = 0 if request.seed is None else '
+ 'request.seed\n'
+ ' defaults = self.default_sampling\n'
+ ' steps = request.resolve_steps(defaults.steps)\n'
+ ' steps, sigmas = resolve_sampling(\n'
+ ' steps, request.extra.get("sigmas"), '
+ 'self.pipeline.sample_sigmas\n'
+ ' )\n'
+ ' guidance = '
+ 'request.resolve_guidance(defaults.guidance)\n'
+ ' validate_guidance(guidance)\n'
+ ' array = self.pipeline.edit_array(\n'
+ ' request.prompt,\n'
+ ' request.image_paths,\n'),
+ (' '
+ 'negative_prompt=request.extra.get("negative_prompt", " '
+ '"),\n'
+ ' '
+ 'output_resolution=request.extra.get("output_resolution", '
+ '1024),\n'
+ ' use_kv_cache=request.extra.get("use_kv_cache", '
+ 'True),\n'
+ ' )\n'
+ ' metadata = {\n'
+ ' "model_path": str(self.pipeline.model_path),\n',
+ ' '
+ 'negative_prompt=request.extra.get("negative_prompt", " '
+ '"),\n'
+ ' '
+ 'output_resolution=request.extra.get("output_resolution", '
+ '1024),\n'
+ ' use_kv_cache=request.extra.get("use_kv_cache", '
+ 'True),\n'
+ ' sigmas=sigmas,\n'
+ ' )\n'
+ ' metadata = {\n'
+ ' "model_path": '
+ 'str(self.pipeline.model_path),\n'))),
+ 'mlx_vlm.generate.image': ('0c49d940b6d575d445d19c930a7b95e90de1291522fe6dcb9724805b7f117701',
+ '0cff132a99b7f740bd8116378514829e6d81d78b5ac54cd84d396d92ca4d0e37',
+ (('def _model_types_from_class_name(class_name: str) -> tuple[str, '
+ '...]:\n'
+ ' tokens = re.findall(r"[A-Z][a-z0-9]*|[A-Z]+(?=[A-Z]|$)", '
+ 'class_name)\n'
+ ' candidates: list[str] = []\n'
+ ' for end in range(1, len(tokens) + 1):\n'
+ ' _add_model_type(candidates, "_".join(tokens[:end]))\n'
+ ' if end > 1:\n',
+ 'def _model_types_from_class_name(class_name: str) -> tuple[str, '
+ '...]:\n'
+ ' tokens = re.findall(r"[A-Z][a-z0-9]*|[A-Z]+(?=[A-Z]|$)", '
+ 'class_name)\n'
+ ' candidates: list[str] = []\n'
+ ' if class_name.startswith("QwenImage21"):\n'
+ ' _add_model_type(candidates, "qwen_image")\n'
+ ' for end in range(1, len(tokens) + 1):\n'
+ ' _add_model_type(candidates, "_".join(tokens[:end]))\n'
+ ' if end > 1:\n'),))}
diff --git a/omlx/patches/mlx_vlm_qwen_image_compat/generate_backport.py b/omlx/patches/mlx_vlm_qwen_image_compat/generate_backport.py
new file mode 100644
index 0000000000..0f15639e27
--- /dev/null
+++ b/omlx/patches/mlx_vlm_qwen_image_compat/generate_backport.py
@@ -0,0 +1,130 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Generate an exact, in-memory Qwen backport from immutable git revisions."""
+
+from __future__ import annotations
+
+import argparse
+import ast
+import difflib
+import hashlib
+import pprint
+import subprocess
+import sys
+from pathlib import Path
+
+BASE_REVISION = "4f4634bb813c0298cb1467bed2e957526c71d0b4"
+MODULES = (
+ "mlx_vlm.models.qwen_image.config",
+ "mlx_vlm.models.qwen_image.scheduler",
+ "mlx_vlm.models.qwen_image.text_encoder",
+ "mlx_vlm.models.qwen_image.pipeline",
+ "mlx_vlm.models.qwen_image.model",
+ "mlx_vlm.generate.image",
+)
+SYMBOLS = {"mlx_vlm.generate.image": "_model_types_from_class_name"}
+
+
+def selected_source(source: str, symbol: str | None) -> str:
+ if symbol is None:
+ return source
+ for node in ast.parse(source).body:
+ if isinstance(node, ast.FunctionDef) and node.name == symbol:
+ result = ast.get_source_segment(source, node)
+ if result is not None:
+ return result
+ raise ValueError(f"Missing upstream symbol: {symbol}")
+
+
+def source_hash(source: str) -> str:
+ tree = ast.parse(source)
+ for node in ast.walk(tree):
+ # Python 3.12 adds empty type_params fields to non-generic definitions.
+ if (
+ isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef))
+ and getattr(node, "type_params", None) == []
+ ):
+ del node.type_params
+ # Python 3.13 omits empty lists by default; retain the older dump format.
+ options = {"show_empty": True} if sys.version_info >= (3, 13) else {}
+ return hashlib.sha256(ast.dump(tree, **options).encode()).hexdigest()
+
+
+def replacements(before: str, after: str) -> tuple[tuple[str, str], ...]:
+ old, new = before.splitlines(keepends=True), after.splitlines(keepends=True)
+ edits = []
+ for group in difflib.SequenceMatcher(a=old, b=new).get_grouped_opcodes(n=3):
+ first, last = group[0], group[-1]
+ left = "".join(old[first[1] : last[2]])
+ right = "".join(new[first[3] : last[4]])
+ if before.count(left) != 1:
+ raise ValueError("Backport hunk must have exactly one source match")
+ edits.append((left, right))
+ return tuple(edits)
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--source-repo", type=Path, required=True)
+ parser.add_argument("--source-revision")
+ parser.add_argument("--verify-from-base", action="store_true")
+ args = parser.parse_args()
+ if args.verify_from_base:
+ from omlx.patches.mlx_vlm_qwen_image_compat import _prepare_sources
+ from omlx.patches.mlx_vlm_qwen_image_compat._backport import BACKPORTS
+
+ sources = {
+ name: subprocess.check_output(
+ [
+ "git",
+ "-C",
+ str(args.source_repo),
+ "show",
+ f"{BASE_REVISION}:{name.replace('.', '/')}.py",
+ ],
+ text=True,
+ )
+ for name in MODULES
+ }
+ patched = _prepare_sources(sources, BACKPORTS)
+ if set(patched) != set(MODULES):
+ raise ValueError("Expected the complete legacy-to-native backport")
+ print(
+ "All backport hunks and target AST fingerprints verified from public base"
+ )
+ return
+ if args.source_revision is None:
+ parser.error("--source-revision is required unless --verify-from-base is used")
+ revision = subprocess.check_output(
+ ["git", "-C", str(args.source_repo), "rev-parse", args.source_revision],
+ text=True,
+ ).strip()
+ backports = {}
+ for name in MODULES:
+ path = name.replace(".", "/") + ".py"
+ sources = [
+ subprocess.check_output(
+ ["git", "-C", str(args.source_repo), "show", f"{ref}:{path}"],
+ text=True,
+ )
+ for ref in (BASE_REVISION, revision)
+ ]
+ before, after = (
+ selected_source(source, SYMBOLS.get(name)) for source in sources
+ )
+ backports[name] = (
+ source_hash(before),
+ source_hash(after),
+ replacements(before, after),
+ )
+ output = Path(__file__).with_name("_backport.py")
+ output.write_text(
+ "# SPDX-License-Identifier: Apache-2.0\n"
+ '"""Generated from mlx-vlm; regenerate with generate_backport.py."""\n\n'
+ f'SOURCE_REVISION = "{revision}"\n'
+ f'BASE_REVISION = "{BASE_REVISION}"\n'
+ f"BACKPORTS = {pprint.pformat(backports, width=100, sort_dicts=False)}\n"
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/test_admin_imagine.py b/tests/test_admin_imagine.py
new file mode 100644
index 0000000000..11868da912
--- /dev/null
+++ b/tests/test_admin_imagine.py
@@ -0,0 +1,349 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Regression tests for the admin Imagine image UI."""
+
+import json
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).parent.parent
+WEB_ROOT = ROOT / "apps" / "omlx-web" / "omlx_web"
+IMAGINE_TEMPLATE = WEB_ROOT / "templates" / "imagine.html"
+CHAT_TEMPLATE = WEB_ROOT / "templates" / "chat.html"
+NAVBAR_TEMPLATE = WEB_ROOT / "templates" / "dashboard" / "_navbar.html"
+ROUTES = WEB_ROOT / "routes.py"
+I18N_DIR = WEB_ROOT / "i18n"
+
+REQUIRED_IMAGINE_KEYS = [
+ "navbar.tab.imagine",
+ "imagine.title",
+ "imagine.brand",
+ "imagine.nav.chat",
+ "imagine.nav.imagine",
+ "imagine.api_key_prompt",
+ "imagine.select_model",
+ "imagine.mode.generate",
+ "imagine.mode.edit",
+ "imagine.prompt_label",
+ "imagine.upload_heading",
+ "imagine.advanced.title",
+ "imagine.advanced.seed",
+ "imagine.advanced.steps",
+ "imagine.checkpoint_schedule_hint",
+ "imagine.effective_steps",
+ "imagine.advanced.guidance",
+ "imagine.advanced.size",
+ "imagine.advanced.n",
+ "imagine.advanced.output_format",
+ "imagine.advanced.negative_prompt",
+ "imagine.submit.generate",
+ "imagine.submit.edit",
+ "imagine.results_heading",
+ "imagine.original_image_alt",
+ "imagine.timeline_model",
+ "imagine.timeline_prompt",
+ "imagine.timeline_original",
+ "imagine.timeline_edited",
+ "imagine.timeline_generated",
+ "imagine.error.incorrect_api_key",
+ "imagine.error.invalid_image_type",
+ "imagine.error.image_too_large",
+]
+
+
+def test_imagine_executes_qwen_recipe_and_request_behavior():
+ node = shutil.which("node")
+ if node is None:
+ pytest.skip("Node.js is required to execute Imagine JavaScript")
+ source = IMAGINE_TEMPLATE.read_text().split("{% block scripts %}", 1)[1]
+ source = source.split("", 1)[0]
+ source = source.replace("{{ api_key | tojson }}", '""')
+ harness = (
+ r"""
+const assert = require('node:assert/strict');
+global.localStorage = {getItem: () => null};
+global.window = {t: key => key};
+"""
+ + source
+ + r"""
+(async () => {
+ const app = imagineApp();
+ app.apiKeySet = true;
+ app.apiKeyInput = 'test';
+ app.mergeStatusMetadata([
+ {id: 'raw', model_alias: 'turbo', model_type: 'image', engine_type: 'image',
+ tasks: ['generation', 'edit'],
+ image_metadata: {uses_checkpoint_sigmas: true, checkpoint_steps: 8}},
+ {id: 'chat', model_type: 'llm', tasks: []},
+ {id: 'collision', model_alias: 'chat', model_type: 'image', tasks: ['edit']}
+ ]);
+ app.currentModel = 'turbo';
+ app.availableModels = [{id: 'turbo'}, {id: 'chat'}];
+ assert.equal(app.currentRecipe().checkpoint_steps, 8);
+ assert.equal(app.modelTypeMap.chat, 'llm');
+ assert.deepEqual(app.modeModels(), [{id: 'turbo'}]);
+ app.prompt = 'a fox';
+ assert.equal(app.commonPayload().steps, undefined);
+ assert.equal(app.commonPayload().guidance, undefined);
+ app.settings.steps = '30';
+ let generation;
+ global.fetch = async (url, options) => {
+ assert.equal(url, '/v1/images/generations');
+ generation = JSON.parse(options.body);
+ return {ok: true, json: async () => ({data: [
+ {b64_json: 'AA==', output_format: 'png', steps: 8, guidance: 1, size: '4x2'}
+ ]})};
+ };
+ await app.submit();
+ assert.equal(generation.steps, 30);
+ assert.equal(generation.sigmas, undefined);
+ assert.equal(app.results[0].images[0].steps, 8);
+ assert.equal(app.results[0].images[0].guidance, 1);
+ app.setMode('edit');
+ app.uploadImages = [
+ {id: 'one', file: new File(['first'], 'first.png'), preview: 'data:first'},
+ {id: 'two', file: new File(['second'], 'second.png'), preview: 'data:second'}
+ ];
+ global.fetch = async (url, options) => {
+ assert.equal(url, '/v1/images/edits');
+ assert.deepEqual(options.body.getAll('image').map(file => file.name),
+ ['first.png', 'second.png']);
+ assert.equal(options.body.get('sigmas'), null);
+ assert.equal(options.body.get('image_strength'), null);
+ assert.equal(options.body.get('mask'), null);
+ return {ok: true, json: async () => ({data: [
+ {b64_json: 'AA==', steps: 8, output_format: 'png'}
+ ]})};
+ };
+ await app.submit();
+ assert.equal(app.results[0].mode, 'edit');
+ assert.equal(app.results[0].originals.length, 2);
+ assert.equal(app.results[0].images[0].steps, 8);
+})().catch(error => {console.error(error); process.exitCode = 1;});
+"""
+ )
+ result = subprocess.run(
+ [node], input=harness, text=True, capture_output=True, timeout=30
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
+
+
+def _imagine_model_selectable(model_type, engine_type=""):
+ """Python equivalent of the imagine.html image model filter."""
+ t = (model_type or "").lower()
+ e = (engine_type or "").lower()
+ return t == "image" or e == "image"
+
+
+def _normalize_tasks(tasks):
+ if not isinstance(tasks, list):
+ return []
+ return [str(task).lower() for task in tasks if task]
+
+
+def _extract_tasks(model):
+ direct_tasks = _normalize_tasks(model.get("tasks"))
+ if direct_tasks:
+ return direct_tasks
+ return _normalize_tasks((model.get("image_metadata") or {}).get("tasks"))
+
+
+def _status_metadata_maps(models):
+ """Python equivalent of the imagine.html /v1/models/status metadata mapping."""
+ model_type_map = {}
+ model_engine_type_map = {}
+ model_task_map = {}
+ for model in models:
+ model_id = model.get("id")
+ if model_id:
+ model_type_map[model_id] = model.get("model_type") or "llm"
+ model_engine_type_map[model_id] = model.get("engine_type") or ""
+ model_task_map[model_id] = _extract_tasks(model)
+ for model in models:
+ model_id = model.get("model_alias")
+ if model_id and model_id not in model_type_map:
+ model_type_map[model_id] = model.get("model_type") or "llm"
+ model_engine_type_map[model_id] = model.get("engine_type") or ""
+ model_task_map[model_id] = _extract_tasks(model)
+ return model_type_map, model_engine_type_map, model_task_map
+
+
+def _supports_task(tasks, task):
+ """Strict task metadata policy approved for the Imagine UI."""
+ return task in (tasks or [])
+
+
+def test_imagine_dropdown_filter_keeps_image_model_types():
+ assert _imagine_model_selectable("image")
+ assert _imagine_model_selectable("llm", engine_type="image")
+
+
+def test_imagine_dropdown_filter_excludes_non_image_model_types():
+ assert not _imagine_model_selectable("llm", engine_type="batched")
+ assert not _imagine_model_selectable("vlm", engine_type="vlm")
+ assert not _imagine_model_selectable("embedding")
+ assert not _imagine_model_selectable("reranker")
+ assert not _imagine_model_selectable("audio_transcription")
+
+
+def test_imagine_task_filter_uses_strict_generation_and_edit_metadata():
+ _, _, task_map = _status_metadata_maps(
+ [
+ {
+ "id": "generate-image",
+ "model_type": "image",
+ "engine_type": "image",
+ "tasks": ["generation"],
+ },
+ {
+ "id": "edit-image",
+ "model_type": "image",
+ "engine_type": "image",
+ "tasks": [],
+ "image_metadata": {"tasks": ["edit"]},
+ },
+ {
+ "id": "unknown-image",
+ "model_type": "image",
+ "engine_type": "image",
+ },
+ ]
+ )
+
+ assert _supports_task(task_map["generate-image"], "generation")
+ assert not _supports_task(task_map["generate-image"], "edit")
+ assert _supports_task(task_map["edit-image"], "edit")
+ assert not _supports_task(task_map["edit-image"], "generation")
+ assert not _supports_task(task_map["unknown-image"], "generation")
+ assert not _supports_task(task_map["unknown-image"], "edit")
+
+
+def test_imagine_status_metadata_maps_active_aliases_without_collisions():
+ model_type_map, engine_type_map, task_map = _status_metadata_maps(
+ [
+ {
+ "id": "chat-model",
+ "model_type": "llm",
+ "engine_type": "batched",
+ },
+ {
+ "id": "raw-image-model",
+ "model_alias": "friendly-image-name",
+ "model_type": "image",
+ "engine_type": "image",
+ "tasks": ["generation"],
+ },
+ {
+ "id": "colliding-image",
+ "model_alias": "chat-model",
+ "model_type": "image",
+ "engine_type": "image",
+ "tasks": ["edit"],
+ },
+ ]
+ )
+
+ assert _imagine_model_selectable(
+ model_type_map["friendly-image-name"],
+ engine_type_map["friendly-image-name"],
+ )
+ assert task_map["friendly-image-name"] == ["generation"]
+ assert model_type_map["chat-model"] == "llm"
+ assert engine_type_map["chat-model"] == "batched"
+
+
+def test_imagine_route_and_nav_are_registered():
+ routes_source = ROUTES.read_text()
+ nav_source = NAVBAR_TEMPLATE.read_text()
+ chat_source = CHAT_TEMPLATE.read_text()
+
+ assert '@router.get("/imagine", response_class=HTMLResponse)' in routes_source
+ assert '"imagine.html"' in routes_source
+ assert "api_key" in routes_source
+ assert 'href="/admin/imagine"' in nav_source
+ assert "navbar.tab.imagine" in nav_source
+ assert 'href="/admin/imagine"' in chat_source
+ assert "navbar.tab.imagine" in chat_source
+
+
+def test_imagine_template_wires_image_endpoints_and_safe_fields():
+ source = IMAGINE_TEMPLATE.read_text()
+
+ assert "fetch('/v1/models'" in source
+ assert "fetch('/v1/models/status'" in source
+ assert "fetch('/v1/images/generations'" in source
+ assert "fetch('/v1/images/edits'" in source
+ assert "response_format: 'b64_json'" in source
+ assert "form.append('image'" in source
+ assert "form.append('mask'" not in source
+ assert "lora_paths" not in source
+ assert "lora_scales" not in source
+ for field in (
+ "seed",
+ "steps",
+ "guidance",
+ "size",
+ "n",
+ "output_format",
+ "negative_prompt",
+ ):
+ assert field in source
+
+
+def test_imagine_template_keeps_results_session_only():
+ source = IMAGINE_TEMPLATE.read_text()
+
+ assert "this.results =" in source
+ assert "localStorage.setItem('omlx_imagine" not in source
+ assert "localStorage.getItem('omlx_imagine" not in source
+
+
+def test_imagine_template_keeps_edit_attempt_timeline_with_originals():
+ source = IMAGINE_TEMPLATE.read_text()
+
+ assert "this.results = [attempt, ...this.results]" in source
+ assert "attempt.originals" in source
+ assert "requestMode === 'edit'" in source
+ assert "mode: requestMode" in source
+ assert "originalSnapshot" in source
+ assert "pendingOriginalPreviews" in source
+ assert "image.preview" in source
+ assert "previewShouldStayAlive" in source
+ assert "clearResults()" in source
+
+
+def test_imagine_template_does_not_depend_on_unbuilt_arbitrary_tailwind_classes():
+ source = IMAGINE_TEMPLATE.read_text()
+
+ assert "imagine-sidebar" in source
+ assert "imagine-edit-comparison" in source
+ assert "imagine-result-grid" in source
+ assert "w-[" not in source
+ assert "min-w-[" not in source
+ assert "max-w-[" not in source
+ assert "h-[" not in source
+ assert "z-[" not in source
+ assert "grid-cols-[" not in source
+ assert "md:grid-cols" not in source
+ assert "xl:grid-cols" not in source
+
+
+def test_imagine_template_refilters_model_on_mode_change():
+ source = IMAGINE_TEMPLATE.read_text()
+
+ assert "setMode(mode)" in source
+ assert "this.ensureValidCurrentModel();" in source
+ assert "modeModels()" in source
+ assert "supportsTask(model.id, task)" in source
+
+
+def test_i18n_imagine_keys_present_in_every_language_file():
+ language_files = list(I18N_DIR.glob("*.json"))
+ assert language_files, "Imagine translations must be packaged"
+ for lang_file in language_files:
+ translations = json.loads(lang_file.read_text())
+ for key in REQUIRED_IMAGINE_KEYS:
+ assert key in translations, f"Missing key '{key}' in {lang_file.name}"
+ assert translations[key], f"Empty value for '{key}' in {lang_file.name}"
diff --git a/tests/test_image_api.py b/tests/test_image_api.py
new file mode 100644
index 0000000000..5a4245402b
--- /dev/null
+++ b/tests/test_image_api.py
@@ -0,0 +1,1191 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Focused tests for OpenAI-compatible image route helpers."""
+
+from __future__ import annotations
+
+import asyncio
+import base64
+import threading
+from io import BytesIO
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+from fastapi import FastAPI, HTTPException
+from fastapi.testclient import TestClient
+from PIL import Image
+
+from omlx.api import image_routes
+
+
+def _png_bytes(color: tuple[int, int, int] = (255, 0, 0)) -> bytes:
+ buffer = BytesIO()
+ Image.new("RGB", (2, 2), color=color).save(buffer, format="PNG")
+ return buffer.getvalue()
+
+
+class FakeImageEngine:
+ def __init__(self, tasks: list[str]) -> None:
+ self._tasks = tasks
+ self.pool: FakePool | None = None
+ self.generate_calls: list[dict] = []
+ self.edit_calls: list[dict] = []
+ self.seen_paths: list[str] = []
+
+ def get_stats(self) -> dict:
+ return {"backend": "mlx-vlm", "tasks": self._tasks}
+
+ async def generate(self, prompt: str, **kwargs):
+ assert self.pool is not None
+ assert self.pool.in_use > 0
+ self.generate_calls.append({"prompt": prompt, **kwargs})
+ return SimpleNamespace(
+ image=Image.new("RGB", (2, 2), color=(0, 255, 0)),
+ metadata={},
+ )
+
+ async def edit(self, prompt: str, image_paths: list[str], **kwargs):
+ assert self.pool is not None
+ assert self.pool.in_use > 0
+ self.edit_calls.append({"prompt": prompt, "image_paths": image_paths, **kwargs})
+ self.seen_paths.extend(image_paths)
+ mask_path = kwargs.get("mask_path")
+ if mask_path is not None:
+ self.seen_paths.append(mask_path)
+ assert all(Path(path).exists() for path in self.seen_paths)
+ return SimpleNamespace(
+ image=Image.new("RGB", (2, 2), color=(0, 0, 255)),
+ metadata={},
+ )
+
+
+class FakePool:
+ def __init__(
+ self,
+ engine: FakeImageEngine,
+ tasks: list[str],
+ *,
+ model_type: str = "image",
+ engine_type: str = "image",
+ ) -> None:
+ self.engine = engine
+ self.engine.pool = self
+ self.get_engine_calls: list[str] = []
+ self.release_engine_calls: list[str] = []
+ self.in_use = 0
+ self.entry = SimpleNamespace(
+ model_type=model_type,
+ engine_type=engine_type,
+ tasks=tasks,
+ image_metadata={"tasks": tasks},
+ )
+
+ def get_entry(self, model_id: str):
+ return self.entry if model_id == "resolved-image-model" else None
+
+ async def get_engine(self, model_id: str, *, _lease: bool = False):
+ assert model_id == "resolved-image-model"
+ assert _lease is True
+ self.get_engine_calls.append(model_id)
+ self.in_use += 1
+ return self.engine
+
+ async def release_engine(self, model_id: str):
+ assert model_id == "resolved-image-model"
+ self.release_engine_calls.append(model_id)
+ self.in_use -= 1
+
+
+@pytest.fixture
+def image_client(monkeypatch):
+ app = FastAPI()
+ app.include_router(image_routes.router)
+
+ monkeypatch.setattr(
+ image_routes, "_resolve_model", lambda model: "resolved-image-model"
+ )
+ monkeypatch.setattr(image_routes, "require_mlx_vlm_available", lambda: None)
+
+ with TestClient(app, raise_server_exceptions=False) as client:
+ yield client
+
+
+def _install_pool(monkeypatch, tasks: list[str]) -> FakeImageEngine:
+ engine = FakeImageEngine(tasks)
+ pool = FakePool(engine, tasks)
+ monkeypatch.setattr(image_routes, "_get_engine_pool", lambda: pool)
+ return engine
+
+
+@pytest.mark.parametrize("task", ["generation", "edit"])
+@pytest.mark.parametrize("seed", [None, 0])
+def test_batch_preserves_optional_seed(image_client, monkeypatch, task, seed):
+ engine = _install_pool(monkeypatch, [task])
+ fields = {"model": "alias", "prompt": "a square", "n": 2}
+ if seed is not None:
+ fields["seed"] = seed
+
+ if task == "generation":
+ response = image_client.post("/v1/images/generations", json=fields)
+ calls = engine.generate_calls
+ else:
+ response = image_client.post(
+ "/v1/images/edits",
+ data=fields,
+ files={"image": ("input.png", _png_bytes(), "image/png")},
+ )
+ calls = engine.edit_calls
+
+ assert response.status_code == 200
+ assert len(response.json()["data"]) == 2
+ assert [call["seed"] for call in calls] == (
+ [None, None] if seed is None else [seed, seed + 1]
+ )
+
+
+def test_generation_forwards_sigmas_and_reports_backend_effective_recipe(
+ image_client, monkeypatch
+):
+ engine = _install_pool(monkeypatch, ["generation"])
+ calls = []
+
+ async def generate(prompt, **kwargs):
+ calls.append(kwargs)
+ return SimpleNamespace(
+ image=Image.new("RGB", (4, 2)),
+ metadata={"steps": 2, "guidance": 1.0, "model_path": "/private/model"},
+ )
+
+ monkeypatch.setattr(engine, "generate", generate)
+ response = image_client.post(
+ "/v1/images/generations",
+ json={
+ "model": "alias",
+ "prompt": "a fox",
+ "steps": 30,
+ "sigmas": [1, 0.5],
+ },
+ )
+ assert response.status_code == 200
+ assert calls[0]["sigmas"] == [1, 0.5]
+ assert calls[0]["steps"] == 30
+ result = response.json()["data"][0]
+ assert result["steps"] == 2
+ assert result["guidance"] == 1.0
+ assert result["size"] == "4x2"
+ assert "model_path" not in result
+
+
+@pytest.mark.parametrize("sigmas", ["[1, 0]", "[]", "invalid"])
+def test_multipart_invalid_sigma_grid_fails_before_loading(
+ image_client, monkeypatch, sigmas
+):
+ engine = _install_pool(monkeypatch, ["edit"])
+ response = image_client.post(
+ "/v1/images/edits",
+ data={"model": "alias", "prompt": "a fox", "sigmas": sigmas},
+ files={"image": ("input.png", _png_bytes(), "image/png")},
+ )
+ assert response.status_code == 422
+ assert engine.pool.get_engine_calls == []
+
+
+def test_multipart_edit_forwards_sigma_grid_and_reference_order(
+ image_client, monkeypatch
+):
+ engine = _install_pool(monkeypatch, ["edit"])
+ response = image_client.post(
+ "/v1/images/edits",
+ data={
+ "model": "alias",
+ "prompt": "combine",
+ "sigmas": "[1, 0.5]",
+ "steps": "30",
+ },
+ files=[
+ ("image", ("first.png", _png_bytes((255, 0, 0)), "image/png")),
+ ("image", ("second.png", _png_bytes((0, 0, 255)), "image/png")),
+ ],
+ )
+ assert response.status_code == 200
+ assert engine.edit_calls[0]["sigmas"] == [1, 0.5]
+ assert len(engine.edit_calls[0]["image_paths"]) == 2
+ assert all(not Path(path).exists() for path in engine.seen_paths)
+ assert engine.pool.in_use == 0
+
+
+async def test_cancelled_edit_keeps_inputs_and_pool_lease_until_worker_exits(
+ monkeypatch, tmp_path
+):
+ from dataclasses import replace
+
+ from omlx.engine.image import ImageEngine, _image_api
+
+ engine = ImageEngine(
+ model_name="image-model",
+ image_metadata={"backend": "mlx-vlm", "base_model": "flux2-klein-4b"},
+ tasks=["edit"],
+ )
+ engine._started = True
+ pool = FakePool(engine, ["edit"])
+ started, finish = threading.Event(), threading.Event()
+ paths = []
+
+ async def loaded(*args, **kwargs):
+ return None, object()
+
+ def worker(model, request, *, task):
+ paths.extend(request.image_paths)
+ started.set()
+ assert finish.wait(5)
+ assert all(Path(path).exists() for path in paths)
+ return SimpleNamespace(image=Image.new("RGB", (2, 2)))
+
+ monkeypatch.setattr(engine, "_load_model_for_task", loaded)
+ api = replace(_image_api(), generate_image=worker)
+ monkeypatch.setattr("omlx.engine.image._image_api", lambda: api)
+ monkeypatch.setattr(image_routes, "_get_engine_pool", lambda: pool)
+ monkeypatch.setattr(
+ image_routes, "_resolve_model", lambda _: "resolved-image-model"
+ )
+
+ async def payload():
+ return {
+ "model": "image-model",
+ "prompt": "change",
+ "images": [
+ {
+ "image_url": "data:image/png;base64,"
+ + base64.b64encode(_png_bytes()).decode()
+ }
+ ],
+ }
+
+ task = asyncio.create_task(
+ image_routes._create_json_image_edit(SimpleNamespace(json=payload))
+ )
+ try:
+ assert await asyncio.to_thread(started.wait, 5)
+ task.cancel()
+ await asyncio.sleep(0)
+ assert not task.done()
+ assert pool.in_use == 1
+ assert all(Path(path).exists() for path in paths)
+ finally:
+ finish.set()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ assert pool.in_use == 0
+ assert all(not Path(path).exists() for path in paths)
+
+
+def test_generation_returns_b64_json_and_increments_seed(image_client, monkeypatch):
+ engine = _install_pool(monkeypatch, ["generation"])
+
+ response = image_client.post(
+ "/v1/images/generations",
+ json={
+ "model": "alias",
+ "prompt": "a green square",
+ "n": 2,
+ "seed": 41,
+ "response_format": "b64_json",
+ "output_format": "png",
+ "style": "vivid",
+ "moderation": "low",
+ "user": "user-123",
+ },
+ )
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["model"] == "resolved-image-model"
+ assert len(body["data"]) == 2
+ assert "url" not in body["data"][0]
+ assert base64.b64decode(body["data"][0]["b64_json"]).startswith(b"\x89PNG")
+ assert [call["seed"] for call in engine.generate_calls] == [41, 42]
+ for ignored_field in (
+ "response_format",
+ "style",
+ "moderation",
+ "user",
+ ):
+ assert ignored_field not in engine.generate_calls[0]
+
+
+def test_generation_preserves_ming_rgba_png(image_client, monkeypatch):
+ engine = _install_pool(monkeypatch, ["generation"])
+
+ async def generate(prompt, **kwargs):
+ return SimpleNamespace(
+ image=Image.new("RGBA", (2, 2), color=(0, 255, 0, 128)),
+ metadata={},
+ )
+
+ monkeypatch.setattr(engine, "generate", generate)
+ response = image_client.post(
+ "/v1/images/generations",
+ json={"model": "alias", "prompt": "transparent green square"},
+ )
+
+ assert response.status_code == 200
+ image_bytes = base64.b64decode(response.json()["data"][0]["b64_json"])
+ with Image.open(BytesIO(image_bytes)) as image:
+ assert image.mode == "RGBA"
+ assert image.getpixel((0, 0)) == (0, 255, 0, 128)
+
+
+def test_generation_rejects_url_response_format_before_engine_pool(
+ image_client, monkeypatch
+):
+ def get_engine_pool():
+ raise AssertionError("engine pool should not be touched")
+
+ monkeypatch.setattr(image_routes, "_get_engine_pool", get_engine_pool)
+
+ response = image_client.post(
+ "/v1/images/generations",
+ json={
+ "model": "alias",
+ "prompt": "a green square",
+ "response_format": "url",
+ },
+ )
+
+ assert response.status_code == 400
+ assert response.json()["detail"] == (
+ "response_format='url' is not supported; use 'b64_json'"
+ )
+
+
+def test_generation_missing_mlx_vlm_returns_503_before_engine_pool(
+ image_client, monkeypatch
+):
+ pool_touched = False
+
+ def missing_mlx_vlm() -> None:
+ raise ImportError(
+ "mlx-vlm image support is unavailable. Reinstall oMLX to restore "
+ "its required mlx-vlm dependency."
+ )
+
+ def get_engine_pool():
+ nonlocal pool_touched
+ pool_touched = True
+ raise AssertionError("engine pool should not be touched")
+
+ monkeypatch.setattr(image_routes, "require_mlx_vlm_available", missing_mlx_vlm)
+ monkeypatch.setattr(image_routes, "_get_engine_pool", get_engine_pool)
+
+ response = image_client.post(
+ "/v1/images/generations",
+ json={"model": "alias", "prompt": "a square"},
+ )
+
+ assert response.status_code == 503
+ assert "mlx-vlm image support is unavailable" in response.json()["detail"]
+ assert pool_touched is False
+
+
+def test_generation_incompatible_mlx_vlm_returns_503_during_inference(
+ image_client, monkeypatch
+):
+ engine = _install_pool(monkeypatch, ["generation"])
+
+ async def fail_generate(prompt: str, **kwargs):
+ raise ImportError(
+ "mlx-vlm image support is unavailable or incompatible. "
+ "Reinstall oMLX to restore its required mlx-vlm dependency."
+ )
+
+ monkeypatch.setattr(engine, "generate", fail_generate)
+
+ response = image_client.post(
+ "/v1/images/generations",
+ json={"model": "alias", "prompt": "a square"},
+ )
+
+ assert response.status_code == 503
+ assert (
+ "mlx-vlm image support is unavailable or incompatible"
+ in response.json()["detail"]
+ )
+ assert engine.pool is not None
+ assert engine.pool.in_use == 0
+ assert engine.pool.release_engine_calls == ["resolved-image-model"]
+
+
+def test_generation_rejects_invalid_size_before_engine_call(image_client, monkeypatch):
+ engine = _install_pool(monkeypatch, ["generation"])
+
+ response = image_client.post(
+ "/v1/images/generations",
+ json={"model": "alias", "prompt": "a square", "size": "wide"},
+ )
+
+ assert response.status_code == 400
+ assert "WIDTHxHEIGHT" in response.json()["detail"]
+ assert engine.generate_calls == []
+
+
+def test_generation_rejects_non_image_model(image_client, monkeypatch):
+ engine = FakeImageEngine(["generation"])
+ pool = FakePool(engine, ["generation"], model_type="llm", engine_type="batched")
+ monkeypatch.setattr(image_routes, "_get_engine_pool", lambda: pool)
+
+ response = image_client.post(
+ "/v1/images/generations",
+ json={"model": "alias", "prompt": "a square"},
+ )
+
+ assert response.status_code == 400
+ assert "not an image model" in response.json()["detail"]
+ assert pool.get_engine_calls == []
+
+
+def test_generation_rejects_wrong_task_model(image_client, monkeypatch):
+ engine = _install_pool(monkeypatch, ["edit"])
+
+ response = image_client.post(
+ "/v1/images/generations",
+ json={"model": "alias", "prompt": "a square"},
+ )
+
+ assert response.status_code == 400
+ assert "does not support task 'generation'" in response.json()["detail"]
+ assert engine.generate_calls == []
+
+
+def test_generation_rejects_request_lora_fields(image_client, monkeypatch):
+ engine = _install_pool(monkeypatch, ["generation"])
+
+ response = image_client.post(
+ "/v1/images/generations",
+ json={
+ "model": "alias",
+ "prompt": "a square",
+ "lora_paths": ["style.safetensors"],
+ },
+ )
+
+ assert response.status_code == 400
+ assert "LoRA" in response.json()["detail"]
+ assert engine.generate_calls == []
+
+
+@pytest.mark.parametrize(
+ "payload,expected_detail",
+ [
+ ({"stream": True}, "stream is not supported"),
+ ({"partial_images": 1}, "partial_images is not supported"),
+ ],
+)
+def test_generation_rejects_unsupported_streaming_fields(
+ image_client, monkeypatch, payload, expected_detail
+):
+ engine = _install_pool(monkeypatch, ["generation"])
+
+ response = image_client.post(
+ "/v1/images/generations",
+ json={"model": "alias", "prompt": "a square", **payload},
+ )
+
+ assert response.status_code == 400
+ assert expected_detail in response.json()["detail"]
+ assert engine.generate_calls == []
+
+
+def test_json_edit_accepts_data_uri_and_cleans_temp_file(image_client, monkeypatch):
+ engine = _install_pool(monkeypatch, ["edit"])
+ data_uri = "data:image/png;base64," + base64.b64encode(_png_bytes()).decode("ascii")
+
+ response = image_client.post(
+ "/v1/images/edits",
+ json={
+ "model": "alias",
+ "prompt": "make it blue",
+ "images": [{"image_url": data_uri}],
+ "n": 1,
+ },
+ )
+
+ assert response.status_code == 200
+ body = response.json()
+ assert len(body["data"]) == 1
+ assert base64.b64decode(body["data"][0]["b64_json"]).startswith(b"\x89PNG")
+ assert len(engine.edit_calls) == 1
+ assert all(not Path(path).exists() for path in engine.seen_paths)
+
+
+def test_json_edit_missing_mlx_vlm_returns_503_before_download_or_engine_pool(
+ image_client, monkeypatch
+):
+ path_conversion_touched = False
+ pool_touched = False
+
+ def missing_mlx_vlm() -> None:
+ raise ImportError(
+ "mlx-vlm image support is unavailable. Reinstall oMLX to restore "
+ "its required mlx-vlm dependency."
+ )
+
+ async def image_reference_to_path(reference, temp_dir):
+ nonlocal path_conversion_touched
+ path_conversion_touched = True
+ raise AssertionError("image refs should not be converted")
+
+ def get_engine_pool():
+ nonlocal pool_touched
+ pool_touched = True
+ raise AssertionError("engine pool should not be touched")
+
+ monkeypatch.setattr(image_routes, "require_mlx_vlm_available", missing_mlx_vlm)
+ monkeypatch.setattr(
+ image_routes, "_image_reference_to_path", image_reference_to_path
+ )
+ monkeypatch.setattr(image_routes, "_get_engine_pool", get_engine_pool)
+
+ response = image_client.post(
+ "/v1/images/edits",
+ json={
+ "model": "alias",
+ "prompt": "edit it",
+ "images": [{"image_url": "https://example.com/input.png"}],
+ },
+ )
+
+ assert response.status_code == 503
+ assert "mlx-vlm image support is unavailable" in response.json()["detail"]
+ assert path_conversion_touched is False
+ assert pool_touched is False
+
+
+def test_json_edit_rejects_mask_before_image_fetch_or_engine_load(
+ image_client, monkeypatch
+):
+ engine = _install_pool(monkeypatch, ["edit"])
+ data_uri = "data:image/png;base64," + base64.b64encode(_png_bytes()).decode("ascii")
+ mask_uri = "data:image/png;base64," + base64.b64encode(
+ _png_bytes((255, 255, 255))
+ ).decode("ascii")
+
+ response = image_client.post(
+ "/v1/images/edits",
+ json={
+ "model": "alias",
+ "prompt": "make it blue",
+ "images": [{"image_url": {"url": data_uri}}],
+ "mask": {"image_url": {"url": mask_uri}},
+ "n": 2,
+ "seed": 7,
+ "size": "2x2",
+ "response_format": "b64_json",
+ "style": "natural",
+ "moderation": "auto",
+ "user": "user-123",
+ },
+ )
+
+ assert response.status_code == 400
+ assert response.json()["detail"] == "mask is not supported by mlx-vlm image models"
+ assert engine.edit_calls == []
+ assert engine.seen_paths == []
+
+
+def test_json_edit_rejects_url_response_format_before_image_fetch(
+ image_client, monkeypatch
+):
+ def image_reference_to_path(_reference, _temp_dir):
+ raise AssertionError("image references should not be resolved")
+
+ def get_engine_pool():
+ raise AssertionError("engine pool should not be touched")
+
+ monkeypatch.setattr(
+ image_routes, "_image_reference_to_path", image_reference_to_path
+ )
+ monkeypatch.setattr(image_routes, "_get_engine_pool", get_engine_pool)
+
+ response = image_client.post(
+ "/v1/images/edits",
+ json={
+ "model": "alias",
+ "prompt": "make it blue",
+ "images": [{"image_url": {"url": "data:image/png;base64,AA=="}}],
+ "response_format": "url",
+ },
+ )
+
+ assert response.status_code == 400
+ assert response.json()["detail"] == (
+ "response_format='url' is not supported; use 'b64_json'"
+ )
+
+
+def test_json_edit_rejects_file_id_refs(image_client, monkeypatch):
+ _install_pool(monkeypatch, ["edit"])
+
+ response = image_client.post(
+ "/v1/images/edits",
+ json={
+ "model": "alias",
+ "prompt": "edit it",
+ "images": [{"file_id": "file-123"}],
+ },
+ )
+
+ assert response.status_code == 400
+ assert "file_id" in response.json()["detail"]
+
+
+def test_json_edit_rejects_unsupported_streaming_fields(image_client, monkeypatch):
+ engine = _install_pool(monkeypatch, ["edit"])
+ data_uri = "data:image/png;base64," + base64.b64encode(_png_bytes()).decode("ascii")
+
+ response = image_client.post(
+ "/v1/images/edits",
+ json={
+ "model": "alias",
+ "prompt": "edit it",
+ "images": [{"image_url": data_uri}],
+ "partial_images": 1,
+ },
+ )
+
+ assert response.status_code == 400
+ assert "partial_images is not supported" in response.json()["detail"]
+ assert engine.edit_calls == []
+
+
+def test_json_edit_rejects_internal_http_image_url(image_client, monkeypatch):
+ _install_pool(monkeypatch, ["edit"])
+
+ response = image_client.post(
+ "/v1/images/edits",
+ json={
+ "model": "alias",
+ "prompt": "edit it",
+ "images": [{"image_url": "http://127.0.0.1:8080/private.png"}],
+ },
+ )
+
+ assert response.status_code == 400
+ assert "public internet address" in response.json()["detail"]
+
+
+def test_http_image_download_rejects_redirect_to_internal_host(monkeypatch):
+ calls: list[str] = []
+
+ def fake_getaddrinfo(host, port, *args, **kwargs):
+ if host == "example.com":
+ return [
+ (
+ image_routes.socket.AF_INET,
+ image_routes.socket.SOCK_STREAM,
+ 0,
+ "",
+ ("93.184.216.34", port),
+ )
+ ]
+ if host == "127.0.0.1":
+ return [
+ (
+ image_routes.socket.AF_INET,
+ image_routes.socket.SOCK_STREAM,
+ 0,
+ "",
+ ("127.0.0.1", port),
+ )
+ ]
+ raise AssertionError(host)
+
+ class RedirectResponse:
+ status = 302
+
+ def getheader(self, name: str):
+ return {"location": "https://127.0.0.1/private.png"}.get(name.lower())
+
+ class FakeConnection:
+ def close(self) -> None:
+ calls.append("closed")
+
+ def fake_get_pinned_response(resolved):
+ calls.append(resolved.url)
+ assert resolved.resolved_ip == "93.184.216.34"
+ return RedirectResponse(), FakeConnection()
+
+ monkeypatch.setattr(image_routes.socket, "getaddrinfo", fake_getaddrinfo)
+ monkeypatch.setattr(image_routes, "_get_pinned_response", fake_get_pinned_response)
+
+ with pytest.raises(HTTPException) as exc_info:
+ image_routes._download_http_image("https://example.com/image.png")
+
+ assert exc_info.value.status_code == 400
+ assert "public internet address" in exc_info.value.detail
+ assert calls == ["https://example.com/image.png", "closed"]
+
+
+def test_http_image_download_uses_pinned_resolved_ip(monkeypatch):
+ calls: list[str] = []
+ png = _png_bytes()
+
+ def fake_getaddrinfo(host, port, *args, **kwargs):
+ calls.append(f"resolve:{host}:{port}")
+ return [
+ (
+ image_routes.socket.AF_INET,
+ image_routes.socket.SOCK_STREAM,
+ 0,
+ "",
+ ("93.184.216.34", port),
+ )
+ ]
+
+ class OKResponse:
+ status = 200
+
+ def __init__(self) -> None:
+ self._chunks = [png, b""]
+
+ def getheader(self, name: str):
+ headers = {"content-type": "image/png", "content-length": str(len(png))}
+ return headers.get(name.lower())
+
+ def read(self, size: int) -> bytes:
+ return self._chunks.pop(0)
+
+ class FakeConnection:
+ def close(self) -> None:
+ calls.append("closed")
+
+ def fake_get_pinned_response(resolved):
+ calls.append(f"connect:{resolved.hostname}:{resolved.resolved_ip}")
+ return OKResponse(), FakeConnection()
+
+ monkeypatch.setattr(image_routes.socket, "getaddrinfo", fake_getaddrinfo)
+ monkeypatch.setattr(image_routes, "_get_pinned_response", fake_get_pinned_response)
+
+ data, suffix = image_routes._download_http_image("https://example.com/image.png")
+
+ assert data == png
+ assert suffix == ".png"
+ assert calls == [
+ "resolve:example.com:443",
+ "connect:example.com:93.184.216.34",
+ "closed",
+ ]
+
+
+@pytest.mark.parametrize(
+ "url_host,ip",
+ [
+ ("127.0.0.1", "127.0.0.1"),
+ ("169.254.169.254", "169.254.169.254"),
+ ("100.64.0.1", "100.64.0.1"),
+ ("[::1]", "::1"),
+ ("mapped.test", "::ffff:10.0.0.1"),
+ ],
+)
+def test_http_image_download_rejects_non_public_addresses(monkeypatch, url_host, ip):
+ def fake_getaddrinfo(resolved_host, port, *args, **kwargs):
+ return [
+ (
+ image_routes.socket.AF_INET,
+ image_routes.socket.SOCK_STREAM,
+ 0,
+ "",
+ (ip, port),
+ )
+ ]
+
+ monkeypatch.setattr(image_routes.socket, "getaddrinfo", fake_getaddrinfo)
+
+ with pytest.raises(HTTPException) as exc_info:
+ image_routes._validate_public_http_url(f"http://{url_host}/image.png")
+
+ assert exc_info.value.status_code == 400
+ assert "public internet address" in exc_info.value.detail
+
+
+@pytest.mark.parametrize(
+ "url",
+ [
+ "http://example.com:bad/image.png",
+ "http://[::1/image.png",
+ ],
+)
+def test_http_image_download_rejects_malformed_urls(url):
+ with pytest.raises(HTTPException) as exc_info:
+ image_routes._validate_public_http_url(url)
+
+ assert exc_info.value.status_code == 400
+ assert "Invalid image_url" in exc_info.value.detail
+
+
+def test_get_pinned_response_closes_connection_on_setup_error(monkeypatch):
+ instances = []
+
+ class FakeConnection:
+ def __init__(self, *args):
+ self.closed = False
+ instances.append(self)
+
+ def putrequest(self, *args, **kwargs):
+ raise OSError("send failed")
+
+ def close(self):
+ self.closed = True
+
+ monkeypatch.setattr(image_routes, "_PinnedHTTPConnection", FakeConnection)
+
+ with pytest.raises(OSError, match="send failed"):
+ image_routes._get_pinned_response(
+ image_routes._ResolvedHTTPURL(
+ url="http://example.com/image.png",
+ hostname="example.com",
+ port=80,
+ resolved_ip="93.184.216.34",
+ scheme="http",
+ )
+ )
+
+ assert instances[0].closed is True
+
+
+@pytest.mark.parametrize("multipart", [False, True])
+@pytest.mark.parametrize("worker_fails", [False, True])
+def test_edits_use_private_request_directories_and_remove_them(
+ image_client, monkeypatch, tmp_path, multipart, worker_fails
+):
+ monkeypatch.chdir(tmp_path)
+ engine = _install_pool(monkeypatch, ["edit"])
+ directories = []
+ original_edit = engine.edit
+
+ async def edit(prompt, image_paths, **kwargs):
+ directories.append(Path(image_paths[0]).parent)
+ assert directories[-1].stat().st_mode & 0o777 == 0o700
+ assert all(Path(path).parent == directories[-1] for path in image_paths)
+ result = await original_edit(prompt, image_paths, **kwargs)
+ if worker_fails:
+ raise ValueError("edit failed")
+ return result
+
+ monkeypatch.setattr(engine, "edit", edit)
+ for _ in range(2):
+ if multipart:
+ response = image_client.post(
+ "/v1/images/edits",
+ data={"model": "alias", "prompt": "edit"},
+ files={"image": ("input.png", _png_bytes(), "image/png")},
+ )
+ else:
+ response = image_client.post(
+ "/v1/images/edits",
+ json={
+ "model": "alias",
+ "prompt": "edit",
+ "images": [
+ {
+ "image_url": "data:image/png;base64,"
+ + base64.b64encode(_png_bytes()).decode("ascii"),
+ }
+ ],
+ },
+ )
+ assert response.status_code == (400 if worker_fails else 200)
+ assert not directories[-1].exists()
+ assert engine.pool.in_use == 0
+ engine.seen_paths.clear()
+
+ assert directories[0] != directories[1]
+ assert not (tmp_path / ".omlx_image_inputs").exists()
+
+
+@pytest.mark.parametrize("endpoint", ["generations", "json-edits", "multipart-edits"])
+@pytest.mark.parametrize("size", ["2049x2048", "wide"])
+def test_invalid_output_size_is_rejected_before_loading(
+ image_client, monkeypatch, endpoint, size
+):
+ engine = _install_pool(monkeypatch, ["generation", "edit"])
+ payload = {"model": "alias", "prompt": "a fox", "size": size}
+ if endpoint == "multipart-edits":
+ response = image_client.post(
+ "/v1/images/edits",
+ data=payload,
+ files={"image": ("input.png", b"not an image", "image/png")},
+ )
+ else:
+ if endpoint == "json-edits":
+ payload["images"] = [{"image_url": "https://example.com/input.png"}]
+ response = image_client.post(
+ (
+ "/v1/images/edits"
+ if endpoint == "json-edits"
+ else "/v1/images/generations"
+ ),
+ json=payload,
+ )
+ assert response.status_code == 400
+ expected_error = "size area" if size == "2049x2048" else "WIDTHxHEIGHT"
+ assert expected_error in response.json()["detail"]
+ assert engine.pool.get_engine_calls == []
+ assert engine.generate_calls == []
+ assert engine.edit_calls == []
+
+
+def test_validate_image_bytes_rejects_excessive_pixels(monkeypatch):
+ monkeypatch.setattr(image_routes, "MAX_IMAGE_INPUT_PIXELS", 1)
+
+ with pytest.raises(HTTPException) as exc_info:
+ image_routes._validate_image_bytes(_png_bytes())
+
+ assert exc_info.value.status_code == 413
+ assert "maximum allowed pixels" in exc_info.value.detail
+
+
+def test_json_edit_rejects_invalid_and_oversized_data_uri(image_client, monkeypatch):
+ _install_pool(monkeypatch, ["edit"])
+
+ invalid_response = image_client.post(
+ "/v1/images/edits",
+ json={
+ "model": "alias",
+ "prompt": "edit it",
+ "images": [{"image_url": "data:image/png;base64,not-valid"}],
+ },
+ )
+
+ assert invalid_response.status_code == 400
+ assert "Invalid image data URI" in invalid_response.json()["detail"]
+
+ monkeypatch.setattr(image_routes, "MAX_IMAGE_INPUT_BYTES", 8)
+ oversized_uri = "data:image/png;base64," + base64.b64encode(_png_bytes()).decode(
+ "ascii"
+ )
+ oversized_response = image_client.post(
+ "/v1/images/edits",
+ json={
+ "model": "alias",
+ "prompt": "edit it",
+ "images": [{"image_url": oversized_uri}],
+ },
+ )
+
+ assert oversized_response.status_code == 413
+ assert "exceeds maximum allowed size" in oversized_response.json()["detail"]
+
+
+def test_multipart_edit_accepts_upload_and_cleans_temp_file(image_client, monkeypatch):
+ engine = _install_pool(monkeypatch, ["edit"])
+
+ response = image_client.post(
+ "/v1/images/edits",
+ data={"model": "alias", "prompt": "edit upload", "seed": "9"},
+ files={"image": ("input.png", _png_bytes(), "image/png")},
+ )
+
+ assert response.status_code == 200
+ assert len(response.json()["data"]) == 1
+ assert engine.edit_calls[0]["seed"] == 9
+ assert all(not Path(path).exists() for path in engine.seen_paths)
+
+
+def test_multipart_edit_missing_mlx_vlm_returns_503_before_file_processing_or_engine_pool(
+ image_client, monkeypatch
+):
+ upload_touched = False
+ pool_touched = False
+
+ def missing_mlx_vlm() -> None:
+ raise ImportError(
+ "mlx-vlm image support is unavailable. Reinstall oMLX to restore "
+ "its required mlx-vlm dependency."
+ )
+
+ async def upload_to_path(value, field_name, temp_dir):
+ nonlocal upload_touched
+ upload_touched = True
+ raise AssertionError("uploads should not be converted")
+
+ def get_engine_pool():
+ nonlocal pool_touched
+ pool_touched = True
+ raise AssertionError("engine pool should not be touched")
+
+ monkeypatch.setattr(image_routes, "require_mlx_vlm_available", missing_mlx_vlm)
+ monkeypatch.setattr(image_routes, "_upload_to_path", upload_to_path)
+ monkeypatch.setattr(image_routes, "_get_engine_pool", get_engine_pool)
+
+ response = image_client.post(
+ "/v1/images/edits",
+ data={"model": "alias", "prompt": "edit upload"},
+ files={"image": ("input.png", _png_bytes(), "image/png")},
+ )
+
+ assert response.status_code == 503
+ assert "mlx-vlm image support is unavailable" in response.json()["detail"]
+ assert upload_touched is False
+ assert pool_touched is False
+
+
+def test_multipart_request_from_form_does_not_inject_placeholder_image():
+ class FakeForm(dict):
+ def getlist(self, name: str):
+ value = self.get(name)
+ if value is None:
+ return []
+ return value if isinstance(value, list) else [value]
+
+ request = image_routes._multipart_request_from_form(
+ FakeForm({"model": "alias", "prompt": "edit upload"})
+ )
+
+ assert not hasattr(request, "images")
+
+
+def test_multipart_edit_rejects_request_lora_fields(image_client, monkeypatch):
+ engine = _install_pool(monkeypatch, ["edit"])
+
+ response = image_client.post(
+ "/v1/images/edits",
+ data={
+ "model": "alias",
+ "prompt": "edit upload",
+ "lora_paths": "style.safetensors",
+ },
+ files={"image": ("input.png", _png_bytes(), "image/png")},
+ )
+
+ assert response.status_code == 400
+ assert "LoRA" in response.json()["detail"]
+ assert engine.edit_calls == []
+
+
+def test_multipart_edit_rejects_unsupported_streaming_fields(image_client, monkeypatch):
+ engine = _install_pool(monkeypatch, ["edit"])
+
+ response = image_client.post(
+ "/v1/images/edits",
+ data={
+ "model": "alias",
+ "prompt": "edit upload",
+ "stream": "true",
+ },
+ files={"image": ("input.png", _png_bytes(), "image/png")},
+ )
+
+ assert response.status_code == 400
+ assert "stream is not supported" in response.json()["detail"]
+ assert engine.edit_calls == []
+
+
+def test_multipart_edit_rejects_mask_before_upload_processing(
+ image_client, monkeypatch
+):
+ engine = _install_pool(monkeypatch, ["edit"])
+
+ response = image_client.post(
+ "/v1/images/edits",
+ data={
+ "model": "alias",
+ "prompt": "edit uploads",
+ "n": "2",
+ "seed": "3",
+ "size": "2x2",
+ "response_format": "b64_json",
+ "style": "vivid",
+ "moderation": "low",
+ "user": "user-123",
+ },
+ files=[
+ ("image[]", ("input-a.png", _png_bytes(), "image/png")),
+ ("image[]", ("input-b.png", _png_bytes((0, 255, 0)), "image/png")),
+ ("mask", ("mask.png", _png_bytes((255, 255, 255)), "image/png")),
+ ],
+ )
+
+ assert response.status_code == 400
+ assert response.json()["detail"] == "mask is not supported by mlx-vlm image models"
+ assert engine.edit_calls == []
+ assert engine.seen_paths == []
+
+
+def test_multipart_edit_rejects_url_response_format_before_upload_processing(
+ image_client, monkeypatch
+):
+ def upload_to_path(_value, _field_name, _temp_dir):
+ raise AssertionError("uploads should not be processed")
+
+ def get_engine_pool():
+ raise AssertionError("engine pool should not be touched")
+
+ monkeypatch.setattr(image_routes, "_upload_to_path", upload_to_path)
+ monkeypatch.setattr(image_routes, "_get_engine_pool", get_engine_pool)
+
+ response = image_client.post(
+ "/v1/images/edits",
+ data={
+ "model": "alias",
+ "prompt": "edit uploads",
+ "response_format": "url",
+ },
+ files={"image": ("input.png", _png_bytes(), "image/png")},
+ )
+
+ assert response.status_code == 400
+ assert response.json()["detail"] == (
+ "response_format='url' is not supported; use 'b64_json'"
+ )
+
+
+def test_multipart_edit_rejects_invalid_and_oversized_upload(image_client, monkeypatch):
+ _install_pool(monkeypatch, ["edit"])
+
+ invalid_response = image_client.post(
+ "/v1/images/edits",
+ data={"model": "alias", "prompt": "edit upload"},
+ files={"image": ("input.png", b"not an image", "image/png")},
+ )
+
+ assert invalid_response.status_code == 400
+ assert "valid image" in invalid_response.json()["detail"]
+
+ monkeypatch.setattr(image_routes, "MAX_IMAGE_INPUT_BYTES", 8)
+ oversized_response = image_client.post(
+ "/v1/images/edits",
+ data={"model": "alias", "prompt": "edit upload"},
+ files={"image": ("input.png", b"x" * 9, "image/png")},
+ )
+
+ assert oversized_response.status_code == 413
+ assert "exceeds maximum allowed size" in oversized_response.json()["detail"]
+
+
+def test_server_image_routes_inherit_api_key_auth(monkeypatch):
+ from omlx import server
+
+ engine = _install_pool(monkeypatch, ["generation"])
+ monkeypatch.setattr(
+ image_routes, "_resolve_model", lambda model: "resolved-image-model"
+ )
+ monkeypatch.setattr(image_routes, "require_mlx_vlm_available", lambda: None)
+ monkeypatch.setattr(server._server_state, "api_key", "secret")
+ monkeypatch.setattr(server._server_state, "global_settings", None)
+ monkeypatch.setattr(server._server_state, "engine_pool", None)
+ monkeypatch.setattr(server._server_state, "process_memory_enforcer", None)
+
+ with TestClient(server.app, raise_server_exceptions=False) as client:
+ unauthorized = client.post(
+ "/v1/images/generations",
+ json={"model": "alias", "prompt": "a square"},
+ )
+ authorized = client.post(
+ "/v1/images/generations",
+ json={"model": "alias", "prompt": "a square"},
+ headers={"Authorization": "Bearer secret"},
+ )
+
+ assert unauthorized.status_code == 401
+ assert authorized.status_code == 200
+ assert len(engine.generate_calls) == 1
diff --git a/tests/test_image_engine.py b/tests/test_image_engine.py
new file mode 100644
index 0000000000..f1c748c1b4
--- /dev/null
+++ b/tests/test_image_engine.py
@@ -0,0 +1,563 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Tests for the mlx-vlm-backed image engine."""
+
+from __future__ import annotations
+
+import asyncio
+import threading
+from dataclasses import dataclass, field
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+import omlx.engine.image as image_module
+from omlx.engine.image import ImageEngine, ImageEngineResult
+from omlx.utils.optional_deps import MLX_VLM_MISSING_MESSAGE
+
+
+class _FakeImageGenerationRequest:
+ def __init__(self, **kwargs: Any) -> None:
+ self.width = self.height = 512
+ self.__dict__.update(kwargs)
+
+
+class _FakeImageEditRequest:
+ def __init__(self, **kwargs: Any) -> None:
+ self.__dict__.update(kwargs)
+
+
+@dataclass
+class _FakeModel:
+ reference: str
+ task: str
+ calls: list[tuple[str, Any]] = field(default_factory=list)
+
+
+class _FakeImageAPI:
+ ImageGenerationRequest = _FakeImageGenerationRequest
+ ImageEditRequest = _FakeImageEditRequest
+
+ def __init__(self) -> None:
+ self.loads: list[tuple[str, str]] = []
+ self.models: list[_FakeModel] = []
+
+ def load_image_model(self, reference: str, *, task: str) -> _FakeModel:
+ self.loads.append((reference, task))
+ model = _FakeModel(reference=reference, task=task)
+ self.models.append(model)
+ return model
+
+ def generate_image(
+ self, model: _FakeModel, request: Any, *, task: str
+ ) -> SimpleNamespace:
+ model.calls.append((task, request))
+ return SimpleNamespace(
+ image={"task": task, "prompt": request.prompt},
+ metadata={"revised_prompt": f"revised: {request.prompt}"},
+ seed=request.seed,
+ steps=request.steps,
+ guidance=request.guidance,
+ width=request.width,
+ height=request.height,
+ model=model.reference,
+ family="fake",
+ variant="fake-variant",
+ )
+
+
+@pytest.fixture
+def fake_mlx_vlm(monkeypatch):
+ api = _FakeImageAPI()
+ cleanup_calls: list[str] = []
+ monkeypatch.setattr(image_module, "_image_api", lambda: api)
+ monkeypatch.setattr(
+ image_module.mx, "synchronize", lambda: cleanup_calls.append("synchronize")
+ )
+ monkeypatch.setattr(
+ image_module.mx, "clear_cache", lambda: cleanup_calls.append("clear_cache")
+ )
+ return SimpleNamespace(api=api, cleanup_calls=cleanup_calls)
+
+
+@pytest.mark.parametrize("task", ["generation", "edit"])
+@pytest.mark.parametrize("seed", [None, 0, 123])
+async def test_requests_preserve_optional_seed(fake_mlx_vlm, task, seed):
+ engine = ImageEngine(model_name="image-model", tasks=[task])
+ await engine.start()
+ kwargs = {} if seed is None else {"seed": seed}
+
+ if task == "generation":
+ await engine.generate("a cat", **kwargs)
+ else:
+ await engine.edit("a cat", image_paths=["input.png"], **kwargs)
+
+ assert fake_mlx_vlm.api.models[-1].calls[-1][1].seed == seed
+
+
+async def test_generate_loads_local_manifest_path_with_request_defaults(
+ fake_mlx_vlm, tmp_path
+):
+ model_root = tmp_path / "flux-model"
+ model_root.mkdir()
+ (model_root / "weights").mkdir()
+ engine = ImageEngine(
+ model_name="api-image-model",
+ model_id="image-model",
+ model_path=str(model_root),
+ image_metadata={
+ "backend": "mlx-vlm",
+ "base_model": "flux2-klein-9b",
+ "model_path": "weights",
+ "default_steps": "7",
+ "default_guidance": "1.5",
+ },
+ tasks=["generation"],
+ )
+
+ await engine.start()
+ result = await engine.generate(
+ "a cat",
+ width=512,
+ height=768,
+ seed=42,
+ output_format="jpeg",
+ negative_prompt="low quality",
+ )
+
+ assert fake_mlx_vlm.api.loads == [
+ (str(model_root / "weights"), "generate"),
+ ]
+ model = fake_mlx_vlm.api.models[0]
+ task, request = model.calls[-1]
+ assert task == "generate"
+ assert request.prompt == "a cat"
+ assert request.seed == 42
+ assert request.width == 512
+ assert request.height == 768
+ assert request.steps == 7
+ assert request.guidance == 1.5
+ assert request.extra == {"negative_prompt": "low quality"}
+
+ assert isinstance(result, ImageEngineResult)
+ assert result.image == {"task": "generate", "prompt": "a cat"}
+ assert result.metadata["output_format"] == "jpeg"
+ assert result.metadata["steps"] == 7
+ assert result.metadata["guidance"] == 1.5
+ assert result.metadata["model_path"] == str(model_root / "weights")
+ assert result.metadata["revised_prompt"] == "revised: a cat"
+
+ await engine.stop()
+ assert engine.get_stats()["loaded"] is False
+ assert "synchronize" in fake_mlx_vlm.cleanup_calls
+ assert "clear_cache" in fake_mlx_vlm.cleanup_calls
+
+
+async def test_stop_can_defer_global_mlx_cleanup(fake_mlx_vlm):
+ engine = ImageEngine(
+ model_name="image-model",
+ image_metadata={"backend": "mlx-vlm", "base_model": "flux2-klein-4b"},
+ tasks=["generation"],
+ )
+ await engine.start()
+
+ await engine.stop_without_global_cleanup()
+
+ assert engine.get_stats()["loaded"] is False
+ assert fake_mlx_vlm.cleanup_calls == []
+
+
+@pytest.mark.parametrize("base_model", ["qwen-image-2.1", "qwen-image-2.1-turbo"])
+async def test_qwen21_generates_edits_and_switches_one_variant(
+ fake_mlx_vlm, base_model
+):
+ engine = ImageEngine(
+ model_name=base_model,
+ image_metadata={"backend": "mlx-vlm", "base_model": base_model},
+ tasks=["generation", "edit"],
+ )
+ await engine.start()
+ generation = await engine.generate("a fox", sigmas=[1, 0.5])
+ assert fake_mlx_vlm.api.models[-1].calls[-1][1].extra == {"sigmas": [1, 0.5]}
+ assert generation.metadata["task"] == "generation"
+ edit = await engine.edit("combine", ["first.png", "second.png"])
+ request = fake_mlx_vlm.api.models[-1].calls[-1][1]
+ assert request.image_paths == ("first.png", "second.png")
+ assert request.steps is None
+ assert "strength" not in request.extra
+ assert edit.metadata["input_image_count"] == 2
+ assert len(engine._models) == 1
+ assert engine.get_stats()["loaded_tasks"] == ["edit"]
+ await engine.stop()
+ assert engine.get_stats()["loaded_tasks"] == []
+
+
+@pytest.mark.parametrize("option", ["image_strength", "scheduler"])
+async def test_qwen21_rejects_unimplemented_explicit_options(fake_mlx_vlm, option):
+ engine = ImageEngine(
+ model_name="qwen",
+ image_metadata={"backend": "mlx-vlm", "base_model": "qwen-image-2.1-turbo"},
+ tasks=["generation", "edit"],
+ )
+ await engine.start()
+ with pytest.raises(ValueError, match=option):
+ await engine.edit("change", ["input.png"], **{option: 0.5})
+ assert fake_mlx_vlm.api.models[0].calls == []
+
+
+@pytest.mark.parametrize("worker_error", [None, ValueError("worker failed")])
+async def test_image_cancellation_drains_worker_before_unlock_and_cleanup(
+ fake_mlx_vlm, monkeypatch, caplog, worker_error
+):
+ engine = ImageEngine(
+ model_name="image-model",
+ image_metadata={"backend": "mlx-vlm", "base_model": "flux2-klein-4b"},
+ tasks=["generation"],
+ )
+ await engine.start()
+ started, finish = threading.Event(), threading.Event()
+
+ def generate(model, request, *, task):
+ started.set()
+ assert finish.wait(5), "test worker was not released"
+ if worker_error is not None:
+ raise worker_error
+ return SimpleNamespace(image="completed")
+
+ monkeypatch.setattr(fake_mlx_vlm.api, "generate_image", generate)
+ task = asyncio.create_task(engine.generate("a fox"))
+ try:
+ assert await asyncio.to_thread(started.wait, 5)
+ task.cancel()
+ await asyncio.sleep(0)
+ assert not task.done()
+ assert engine._call_lock.locked()
+ assert fake_mlx_vlm.cleanup_calls == []
+ finally:
+ finish.set()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ assert not engine._call_lock.locked()
+ assert "clear_cache" in fake_mlx_vlm.cleanup_calls
+ if worker_error is not None:
+ assert "Cancelled image worker failed" in caplog.text
+
+
+@pytest.mark.parametrize(
+ "base_model",
+ [
+ "flux2-klein-4b",
+ "mage-flow-base",
+ "mage-flow",
+ "mage-flow-turbo",
+ "z-image-turbo",
+ "ernie-image-turbo",
+ "ming-image-0.1-design",
+ ],
+)
+async def test_generation_leaves_family_defaults_to_backend(fake_mlx_vlm, base_model):
+ engine = ImageEngine(
+ model_name=base_model,
+ image_metadata={"backend": "mlx-vlm", "base_model": base_model},
+ tasks=["generation"],
+ )
+
+ await engine.start()
+ await engine.generate("a cat")
+
+ _, request = fake_mlx_vlm.api.models[-1].calls[-1]
+ assert request.steps is None
+ assert request.guidance is None
+ assert request.width == request.height == 512
+
+
+async def test_request_defaults_override_manifest_and_family_defaults(fake_mlx_vlm):
+ engine = ImageEngine(
+ model_name="mage",
+ image_metadata={
+ "backend": "mlx-vlm",
+ "base_model": "mage-flow",
+ "default_steps": 7,
+ "default_guidance": 2.0,
+ },
+ tasks=["generation"],
+ )
+
+ await engine.start()
+ await engine.generate("a cat", steps=12, guidance=3.5)
+
+ _, request = fake_mlx_vlm.api.models[-1].calls[-1]
+ assert request.steps == 12
+ assert request.guidance == 3.5
+
+
+async def test_edit_routes_multiple_mage_inputs_and_strength_aliases(fake_mlx_vlm):
+ engine = ImageEngine(
+ model_name="mage-edit",
+ image_metadata={
+ "backend": "mlx-vlm",
+ "base_model": "mage-flow-edit",
+ "default_image_strength": 0.7,
+ },
+ tasks=["edit"],
+ )
+
+ await engine.start()
+ result = await engine.edit(
+ "make it cinematic",
+ image_paths=["input-a.png", "input-b.png"],
+ steps=9,
+ guidance=2.5,
+ seed=123,
+ image_strength=0.55,
+ scheduler="euler",
+ )
+
+ model = fake_mlx_vlm.api.models[-1]
+ task, request = model.calls[-1]
+ assert task == "edit"
+ assert request.image_paths == ("input-a.png", "input-b.png")
+ assert request.seed == 123
+ assert request.steps == 9
+ assert request.guidance == 2.5
+ assert request.extra == {
+ "scheduler": "euler",
+ "image_strength": 0.55,
+ "strength": 0.55,
+ }
+ assert result.metadata["task"] == "edit"
+ assert result.metadata["input_image_count"] == 2
+
+
+@pytest.mark.parametrize("base_model", ["z-image-turbo", "ernie-image-turbo"])
+async def test_edit_leaves_family_defaults_to_backend(fake_mlx_vlm, base_model):
+ engine = ImageEngine(
+ model_name=base_model,
+ image_metadata={"backend": "mlx-vlm", "base_model": base_model},
+ tasks=["edit"],
+ )
+ await engine.start()
+
+ await engine.edit("make it brighter", image_paths=["input.png"])
+
+ _, request = fake_mlx_vlm.api.models[-1].calls[-1]
+ assert request.extra == {}
+ assert request.steps is None
+ assert request.guidance is None
+
+
+async def test_manifest_image_strength_overrides_family_default(fake_mlx_vlm):
+ engine = ImageEngine(
+ model_name="ernie-image",
+ image_metadata={
+ "backend": "mlx-vlm",
+ "base_model": "ernie-image",
+ "default_image_strength": 0.4,
+ },
+ tasks=["edit"],
+ )
+ await engine.start()
+
+ await engine.edit("make it brighter", image_paths=["input.png"])
+
+ _, request = fake_mlx_vlm.api.models[-1].calls[-1]
+ assert request.extra["image_strength"] == 0.4
+ assert request.extra["strength"] == 0.4
+
+
+async def test_all_current_image_families_reject_masks(fake_mlx_vlm):
+ engine = ImageEngine(
+ model_name="flux-edit",
+ image_metadata={"backend": "mlx-vlm", "base_model": "flux2-klein-4b"},
+ tasks=["edit"],
+ )
+ await engine.start()
+
+ with pytest.raises(ValueError, match="do not support masks"):
+ await engine.edit(
+ "remove background",
+ image_paths=["input.png"],
+ mask_path="mask.png",
+ )
+
+
+async def test_dual_task_engine_keeps_one_loaded_variant(fake_mlx_vlm):
+ engine = ImageEngine(
+ model_name="dual-task",
+ image_metadata={"backend": "mlx-vlm", "base_model": "flux2-klein-4b"},
+ tasks=["generation", "edit"],
+ )
+ await engine.start()
+
+ await engine.generate("a cat")
+ assert engine.get_stats()["loaded_tasks"] == ["generation"]
+ assert len(engine._models) == 1
+
+ await engine.edit("make it brighter", image_paths=["input.png"])
+ assert engine.get_stats()["loaded_tasks"] == ["edit"]
+ assert len(engine._models) == 1
+ assert len(fake_mlx_vlm.api.loads) == 2
+
+ await engine.generate("a dog")
+ assert engine.get_stats()["loaded_tasks"] == ["generation"]
+ assert len(engine._models) == 1
+ assert len(fake_mlx_vlm.api.loads) == 3
+
+
+async def test_model_path_override_is_a_distinct_loaded_variant(fake_mlx_vlm, tmp_path):
+ model_root = tmp_path / "models"
+ model_root.mkdir()
+ override = tmp_path / "other-model"
+ override.mkdir()
+ engine = ImageEngine(
+ model_name="flux",
+ model_path=str(model_root),
+ image_metadata={"backend": "mlx-vlm", "base_model": "flux2-klein-4b"},
+ tasks=["generation"],
+ )
+ await engine.start()
+
+ await engine.generate("first")
+ await engine.generate("second", model_path=str(override))
+
+ assert fake_mlx_vlm.api.loads == [
+ (str(model_root), "generate"),
+ (str(override), "generate"),
+ ]
+ assert len(engine._models) == 1
+
+
+@pytest.mark.parametrize(
+ ("base_model", "expected_reference"),
+ [
+ ("mage-flow-aligned", "mage-flow"),
+ ("ideogram4", "ideogram-ai/ideogram-4-fp8"),
+ ("z-image", "Tongyi-MAI/Z-Image"),
+ ("z-image-turbo", "Tongyi-MAI/Z-Image-Turbo"),
+ ("ming-image-0.1-design", "inclusionAI/Ming-Image-0.1-Design"),
+ ],
+)
+async def test_direct_engine_uses_loader_reference_without_a_local_model_path(
+ fake_mlx_vlm, base_model, expected_reference
+):
+ engine = ImageEngine(
+ model_name="public-alias-engine",
+ image_metadata={"backend": "mlx-vlm", "base_model": base_model},
+ tasks=["generation"],
+ )
+ await engine.start()
+
+ await engine.generate("a cat")
+
+ assert fake_mlx_vlm.api.loads == [(expected_reference, "generate")]
+
+
+async def test_manifest_model_path_must_resolve_locally(fake_mlx_vlm, tmp_path):
+ engine = ImageEngine(
+ model_name="flux",
+ model_path=str(tmp_path),
+ image_metadata={
+ "backend": "mlx-vlm",
+ "base_model": "flux2-klein-4b",
+ "model_path": "missing-weights",
+ },
+ tasks=["generation"],
+ )
+ with pytest.raises(ValueError, match="manifest model_path does not exist"):
+ await engine.start()
+ assert fake_mlx_vlm.api.loads == []
+
+
+async def test_quantize_is_rejected_in_manifest_and_request(fake_mlx_vlm):
+ manifest_engine = ImageEngine(
+ model_name="flux",
+ image_metadata={
+ "backend": "mlx-vlm",
+ "base_model": "flux2-klein-4b",
+ "quantize": 4,
+ },
+ tasks=["generation"],
+ )
+ with pytest.raises(ValueError, match="manifest quantize"):
+ await manifest_engine.start()
+
+ engine = ImageEngine(
+ model_name="flux",
+ image_metadata={"backend": "mlx-vlm", "base_model": "flux2-klein-4b"},
+ tasks=["generation"],
+ )
+ await engine.start()
+ with pytest.raises(ValueError, match="request quantize"):
+ await engine.generate("a cat", quantize=4)
+
+
+async def test_start_rejects_unsupported_backend(fake_mlx_vlm):
+ bad_backend = ImageEngine(
+ model_name="unsupported",
+ image_metadata={"backend": "other", "base_model": "flux2-klein-4b"},
+ tasks=["generation"],
+ )
+ with pytest.raises(ValueError, match="Unsupported image backend"):
+ await bad_backend.start()
+
+
+@pytest.mark.parametrize("base_model", ["new-image-family", "mage-flow-turbo"])
+async def test_discovered_tasks_are_not_limited_by_fork_registry(
+ fake_mlx_vlm, tmp_path, base_model
+):
+ engine = ImageEngine(
+ model_name="new-image-family",
+ model_path=str(tmp_path),
+ image_metadata={"backend": "mlx-vlm", "base_model": base_model},
+ tasks=["generation", "edit"],
+ )
+ await engine.start()
+ await engine.generate("a fox")
+ await engine.edit("combine", ["first.png", "second.png"])
+ assert fake_mlx_vlm.api.loads == [
+ (str(tmp_path), "generate"),
+ (str(tmp_path), "edit"),
+ ]
+ request = fake_mlx_vlm.api.models[-1].calls[-1][1]
+ assert request.image_paths == ("first.png", "second.png")
+ assert request.steps is None
+ assert request.guidance is None
+
+
+@pytest.mark.parametrize(
+ ("base_model", "task"),
+ [
+ ("FLUX.2-klein-base-4B", "generation"),
+ ("flux2-klein-9b-kv", "edit"),
+ ("Mage_Flow_Aligned", "generation"),
+ ("Mage_Flow_Edit_Turbo", "edit"),
+ ("Z_Image_Turbo", "generation"),
+ ("ERNIE_Image_Turbo", "edit"),
+ ("Ideogram4", "generation"),
+ ("bonsai-ternary", "generation"),
+ ],
+)
+async def test_start_accepts_supported_aliases(fake_mlx_vlm, base_model, task):
+ engine = ImageEngine(
+ model_name="image-alias",
+ image_metadata={"backend": "mlx-vlm", "base_model": base_model},
+ tasks=[task],
+ )
+ await engine.start()
+ assert engine.get_stats()["loaded_tasks"] == [task]
+
+
+async def test_missing_mlx_vlm_produces_core_dependency_error(monkeypatch):
+ def unavailable_api() -> Any:
+ raise ImportError(MLX_VLM_MISSING_MESSAGE)
+
+ monkeypatch.setattr(image_module, "_image_api", unavailable_api)
+ monkeypatch.setattr(image_module.mx, "synchronize", lambda: None)
+ monkeypatch.setattr(image_module.mx, "clear_cache", lambda: None)
+ engine = ImageEngine(
+ model_name="missing-runtime",
+ image_metadata={"backend": "mlx-vlm", "base_model": "flux2-klein-4b"},
+ tasks=["generation"],
+ )
+ with pytest.raises(ImportError, match="mlx-vlm image support is unavailable"):
+ await engine.start()
diff --git a/tests/test_image_models.py b/tests/test_image_models.py
new file mode 100644
index 0000000000..ed7801835a
--- /dev/null
+++ b/tests/test_image_models.py
@@ -0,0 +1,204 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Tests for OpenAI-compatible image API models."""
+
+import pytest
+from pydantic import ValidationError
+
+from omlx.api.image_models import (
+ ImageData,
+ ImageEditRequest,
+ ImageGenerationRequest,
+ ImageMultipartEditRequest,
+ ImageReference,
+ ImageResponse,
+ ImageURLReference,
+ ImageUsage,
+ parse_image_size,
+)
+
+
+@pytest.mark.parametrize(
+ "sigmas",
+ [
+ [],
+ [1, 0],
+ [1, 1],
+ [0.5, 1],
+ [1.1, 0.5],
+ [True, 0.5],
+ [float("nan")],
+ [float("inf")],
+ "bad",
+ ],
+)
+def test_image_request_rejects_invalid_sigma_grid(sigmas):
+ with pytest.raises(ValidationError, match="sigmas"):
+ ImageGenerationRequest(prompt="a fox", model="qwen-image-2.1", sigmas=sigmas)
+
+
+def test_sigma_grid_can_override_a_different_requested_step_count():
+ request = ImageGenerationRequest(
+ prompt="a fox", model="qwen-image-2.1", steps=30, sigmas=[1, 0.5]
+ )
+ assert request.sigmas == [1, 0.5]
+ assert request.steps == 30
+
+
+def test_generation_request_defaults_and_extensions():
+ request = ImageGenerationRequest(
+ prompt="a watercolor fox",
+ model="image-model",
+ seed=123,
+ steps=12,
+ guidance=3.5,
+ negative_prompt="blurry",
+ scheduler="euler",
+ image_strength=0.4,
+ lora_paths=["style.safetensors"],
+ lora_scales=[0.8],
+ )
+
+ assert request.n == 1
+ assert request.size == "auto"
+ assert request.parsed_size() == (None, None)
+ assert request.response_format == "b64_json"
+ assert request.output_format == "png"
+ assert request.background == "auto"
+ assert request.stream is False
+
+ dumped = request.model_dump(exclude_none=True)
+ assert dumped["negative_prompt"] == "blurry"
+ assert dumped["lora_paths"] == ["style.safetensors"]
+ assert dumped["lora_scales"] == [0.8]
+
+
+@pytest.mark.parametrize("n", [0, 11])
+def test_generation_request_rejects_n_outside_openai_range(n):
+ with pytest.raises(ValidationError):
+ ImageGenerationRequest(prompt="a fox", model="image-model", n=n)
+
+
+def test_generation_request_rejects_empty_prompt():
+ with pytest.raises(ValidationError, match="prompt must not be empty"):
+ ImageGenerationRequest(prompt=" ", model="image-model")
+
+
+def test_output_format_is_normalized_and_validated():
+ request = ImageGenerationRequest(
+ prompt="a fox",
+ model="image-model",
+ output_format="WEBP",
+ )
+
+ assert request.output_format == "webp"
+
+ with pytest.raises(ValidationError, match="output_format"):
+ ImageGenerationRequest(
+ prompt="a fox",
+ model="image-model",
+ output_format="gif",
+ )
+
+
+def test_parse_image_size_helper():
+ assert parse_image_size(None) == (None, None)
+ assert parse_image_size("auto") == (None, None)
+ assert parse_image_size("1024x768") == (1024, 768)
+ assert parse_image_size(" 1536 X 1024 ") == (1536, 1024)
+ assert parse_image_size("2048x2048") == (2048, 2048)
+ assert ImageGenerationRequest(
+ prompt="a fox",
+ model="image-model",
+ size="512x512",
+ ).parsed_size() == (512, 512)
+
+ with pytest.raises(ValueError, match="WIDTHxHEIGHT"):
+ parse_image_size("wide")
+ with pytest.raises(ValueError, match="positive"):
+ parse_image_size("0x512")
+ with pytest.raises(ValueError, match="size area"):
+ parse_image_size("2049x2048")
+
+
+def test_edit_request_accepts_file_id_and_image_url_refs():
+ request = ImageEditRequest(
+ prompt="make it cinematic",
+ model="edit-model",
+ images=[
+ {"file_id": "file-abc123"},
+ {"image_url": {"url": "https://example.test/input.png"}},
+ ],
+ mask={"image_url": "data:image/png;base64,AAAA"},
+ output_format="jpeg",
+ input_fidelity="high",
+ partial_images=2,
+ )
+
+ assert request.images[0].file_id == "file-abc123"
+ assert isinstance(request.images[1].image_url, ImageURLReference)
+ assert request.mask is not None
+ assert request.mask.image_url == "data:image/png;base64,AAAA"
+ assert request.output_format == "jpeg"
+ assert request.input_fidelity == "high"
+ assert request.parsed_size() == (None, None)
+
+ dumped = request.model_dump(mode="json", exclude_none=True)
+ assert dumped["images"][0] == {"file_id": "file-abc123"}
+ assert dumped["images"][1] == {
+ "image_url": {"url": "https://example.test/input.png"}
+ }
+
+
+def test_multipart_edit_request_does_not_require_json_images():
+ request = ImageMultipartEditRequest(
+ prompt="make it cinematic",
+ model="edit-model",
+ seed=7,
+ )
+
+ assert request.prompt == "make it cinematic"
+ assert request.model == "edit-model"
+ assert request.seed == 7
+ assert not hasattr(request, "images")
+
+
+@pytest.mark.parametrize(
+ "payload",
+ [
+ {},
+ {"file_id": "file-abc123", "image_url": "https://example.test/input.png"},
+ ],
+)
+def test_image_reference_requires_exactly_one_shape(payload):
+ with pytest.raises(ValidationError, match="exactly one"):
+ ImageReference(**payload)
+
+
+def test_image_response_serialization_and_usage_placeholder():
+ response = ImageResponse(
+ model="image-model",
+ data=[
+ ImageData(
+ b64_json="aW1hZ2U=",
+ revised_prompt="a better fox",
+ size="1024x1024",
+ quality="high",
+ output_format="PNG",
+ background="transparent",
+ )
+ ],
+ usage=ImageUsage(prompt_tokens=3, completion_tokens=4, image_count=1),
+ )
+
+ assert response.data[0].output_format == "png"
+ assert response.usage is not None
+ assert response.usage.total_tokens == 7
+ assert response.usage.input_tokens == 3
+ assert response.usage.output_tokens == 4
+
+ dumped = response.model_dump(mode="json", exclude_none=True)
+ assert isinstance(dumped["created"], int)
+ assert dumped["data"][0]["b64_json"] == "aW1hZ2U="
+ assert dumped["data"][0]["revised_prompt"] == "a better fox"
+ assert dumped["data"][0]["output_format"] == "png"
+ assert dumped["usage"]["image_count"] == 1
diff --git a/tests/test_image_registry.py b/tests/test_image_registry.py
new file mode 100644
index 0000000000..e06a665e9c
--- /dev/null
+++ b/tests/test_image_registry.py
@@ -0,0 +1,404 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Tests for mlx-vlm image model registry and discovery."""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from omlx.image_registry import (
+ get_image_model_reference,
+ get_image_model_spec,
+ image_edit_accepts_multiple_inputs,
+ infer_image_model_spec_from_name,
+)
+from omlx.model_discovery import (
+ _load_image_manifest,
+ detect_image_tasks,
+ detect_model_type,
+ discover_models,
+ estimate_image_model_size,
+)
+
+TURBO_SIGMAS = [1, 0.978453, 0.95418, 0.926626, 0.89508, 0.845148, 0.704534, 0.414568]
+
+
+def _qwen21_layout(tmp_path, name="renamed-image-model", *, sigmas=None):
+ model_dir = tmp_path / name
+ (model_dir / "tokenizer").mkdir(parents=True)
+ index = {
+ "_class_name": "QwenImage21Pipeline",
+ "_diffusers_version": "0.41.0.dev0",
+ "processor": ["transformers", "Qwen3VLProcessor"],
+ "scheduler": ["diffusers", "FlowMatchEulerDiscreteScheduler"],
+ "text_encoder": ["transformers", "Qwen3VLForConditionalGeneration"],
+ "transformer": ["diffusers", "QwenImage21Transformer2DModel"],
+ "vae": ["diffusers", "AutoencoderKLQwenImage21"],
+ }
+ if sigmas is not None:
+ index["sample_sigmas"] = sigmas
+ (model_dir / "model_index.json").write_text(json.dumps(index))
+ for component in ("transformer", "vae", "text_encoder"):
+ directory = model_dir / component
+ directory.mkdir()
+ (directory / "model.safetensors").write_bytes(b"weights")
+ (directory / "config.json").write_text("{}")
+ (model_dir / "processor").mkdir()
+ (model_dir / "processor" / "tokenizer.json").write_text("{}")
+ (model_dir / "transformer" / "config.json").write_text(
+ json.dumps(
+ {
+ "_class_name": "QwenImage21Transformer2DModel",
+ "attention_head_dim": 128,
+ "num_attention_heads": 32,
+ "num_layers": 32,
+ "in_channels": 64,
+ "out_channels": 64,
+ "patch_size": 1,
+ "causal_condition": True,
+ }
+ )
+ )
+ return model_dir
+
+
+@pytest.mark.parametrize(
+ ("sigmas", "base_model", "steps"),
+ [
+ (None, "qwen-image-2-1", None),
+ (TURBO_SIGMAS, "qwen-image-2-1-turbo", 8),
+ ([1, 0.5], "qwen-image-2-1", 2),
+ ],
+)
+def test_qwen21_intrinsic_discovery_survives_renaming(
+ tmp_path, sigmas, base_model, steps
+):
+ model_dir = _qwen21_layout(tmp_path, sigmas=sigmas)
+ manifest = _load_image_manifest(model_dir)
+ assert manifest is not None
+ assert manifest.base_model == base_model
+ assert manifest.tasks == ["generation", "edit"]
+ assert manifest.metadata.get("default_steps") == steps
+ assert manifest.metadata.get("checkpoint_steps") == steps
+ assert manifest.metadata["uses_checkpoint_sigmas"] is (sigmas is not None)
+ assert detect_model_type(model_dir) == "image"
+ assert image_edit_accepts_multiple_inputs(base_model)
+
+
+@pytest.mark.parametrize(
+ "pipeline", ["QwenImagePipeline", "QwenImageEditPipeline", "OtherPipeline"]
+)
+def test_qwen_folder_name_does_not_override_component_identity(tmp_path, pipeline):
+ model_dir = _qwen21_layout(tmp_path, "Qwen-Image-2.1-Turbo")
+ index_path = model_dir / "model_index.json"
+ index = json.loads(index_path.read_text())
+ index["_class_name"] = pipeline
+ index_path.write_text(json.dumps(index))
+ assert _load_image_manifest(model_dir) is None
+
+
+@pytest.mark.parametrize(
+ "sigmas", [[], [1, 0], [0.5, 1], [True, 0.5], [float("nan")], "bad"]
+)
+def test_qwen21_invalid_saved_grid_is_not_inferred(tmp_path, sigmas):
+ assert _load_image_manifest(_qwen21_layout(tmp_path, sigmas=sigmas)) is None
+
+
+def test_qwen21_explicit_manifest_keeps_effective_recipe_metadata(tmp_path):
+ model_dir = _qwen21_layout(tmp_path, sigmas=TURBO_SIGMAS)
+ (model_dir / "omlx-image-model.json").write_text(
+ json.dumps(
+ {
+ "backend": "mlx-vlm",
+ "base_model": "qwen-image-2.1-turbo",
+ "task": ["generation", "edit"],
+ "model_path": ".",
+ "default_steps": 25,
+ }
+ )
+ )
+ manifest = _load_image_manifest(model_dir)
+ assert manifest is not None
+ assert manifest.metadata["default_steps"] == 25
+ assert manifest.metadata["checkpoint_steps"] == 8
+
+
+def test_qwen21_aliases_and_runtime_identity():
+ for alias in ("qwen-image-2.1-turbo", "Qwen/Qwen-Image-2.1-Turbo"):
+ assert get_image_model_reference(alias) == "Qwen/Qwen-Image-2.1-Turbo"
+ assert get_image_model_spec("qwen-image-edit") is None
+
+
+@pytest.mark.parametrize(
+ ("alias", "base_model", "tasks"),
+ [
+ (
+ "microsoft/Mage-Flow-Base",
+ "mage-flow-base",
+ ("generation",),
+ ),
+ (
+ "Mage-Flow-Aligned",
+ "mage-flow",
+ ("generation",),
+ ),
+ (
+ "Mage-Flow-Turbo",
+ "mage-flow-turbo",
+ ("generation",),
+ ),
+ (
+ "Mage-Flow-Edit-Base",
+ "mage-flow-edit-base",
+ ("edit",),
+ ),
+ (
+ "Mage-Flow-Edit-Aligned",
+ "mage-flow-edit",
+ ("edit",),
+ ),
+ (
+ "Mage-Flow-Edit-Turbo",
+ "mage-flow-edit-turbo",
+ ("edit",),
+ ),
+ ],
+)
+def test_mage_flow_aliases_expose_metadata_hints(alias, base_model, tasks):
+ spec = get_image_model_spec(alias)
+
+ assert spec is not None
+ assert spec.base_model == base_model
+ assert spec.tasks == tasks
+ assert image_edit_accepts_multiple_inputs(alias) is (tasks == ("edit",))
+
+
+@pytest.mark.parametrize(
+ ("name", "base_model", "tasks"),
+ [
+ ("FLUX.2-klein-base-9B", "flux2-klein-base-9b", ("generation", "edit")),
+ ("Z-Image-Turbo", "z-image-turbo", ("generation", "edit")),
+ ("ERNIE-Image", "ernie-image", ("generation", "edit")),
+ ("Ming-Image-0.1-Design-mxfp8", "ming-image-0-1-design", ("generation",)),
+ ("ideogram-4-fp8", "ideogram-4-fp8", ("generation",)),
+ ("bonsai-image-ternary-4B-mlx-2bit", "ternary", ("generation",)),
+ ],
+)
+def test_supported_image_names_infer_registry_specs(name, base_model, tasks):
+ spec = infer_image_model_spec_from_name(name)
+
+ assert spec is not None
+ assert spec.base_model == base_model
+ assert spec.tasks == tasks
+
+
+def test_local_mage_edit_layout_is_discovered_as_mlx_vlm_image(tmp_path):
+ model_dir = tmp_path / "Mage-Flow-Edit-Turbo"
+ _write_mage_checkpoint(model_dir)
+
+ manifest = _load_image_manifest(model_dir)
+
+ assert manifest is not None
+ assert manifest.backend == "mlx-vlm"
+ assert manifest.base_model == "mage-flow-edit-turbo"
+ assert manifest.tasks == ["edit"]
+ assert manifest.metadata["model_path"] == "."
+ assert detect_model_type(model_dir) == "image"
+
+
+@pytest.mark.parametrize(
+ ("folder", "weight_file"),
+ [
+ ("Ming-Image-0.1-Design", "diffusion_pytorch_model.safetensors"),
+ ("Ming-Image-0.1-Design-mxfp8", "model.safetensors"),
+ ],
+)
+def test_local_ming_layout_is_discovered_as_generation_only(
+ tmp_path, folder, weight_file
+):
+ model_dir = tmp_path / folder
+ tokenizer_dir = model_dir / "mllm"
+ tokenizer_dir.mkdir(parents=True)
+ (tokenizer_dir / "tokenizer.json").write_text("{}")
+ (tokenizer_dir / "config.json").write_text(
+ json.dumps({"architectures": ["BailingMMForConditionalGeneration"]})
+ )
+ for component in ("transformer", "vae"):
+ component_dir = model_dir / component
+ component_dir.mkdir()
+ (component_dir / weight_file).write_bytes(b"weights")
+ (component_dir / "config.json").write_text(
+ json.dumps({"_class_name": "DiffusionTransformer"})
+ if component == "transformer"
+ else "{}"
+ )
+
+ manifest = _load_image_manifest(model_dir)
+
+ assert manifest is not None
+ assert manifest.backend == "mlx-vlm"
+ assert manifest.base_model == "ming-image-0-1-design"
+ assert manifest.tasks == ["generation"]
+ assert manifest.metadata["model_path"] == "."
+ assert detect_model_type(model_dir) == "image"
+
+
+@pytest.mark.parametrize(
+ ("name", "tasks"),
+ [
+ ("Mage-Flow", ["generation"]),
+ ("Mage-Flow-Turbo", ["generation"]),
+ ("Mage-Flow-Edit", ["edit"]),
+ ("Mage-Flow-Edit-Turbo", ["edit"]),
+ ],
+)
+def test_mage_flow_text_encoder_tokenizer_layout_is_discovered(tmp_path, name, tasks):
+ """Mage-Flow community checkpoints keep tokenizer files in ``text_encoder/``."""
+ model_dir = tmp_path / name
+ _write_mage_checkpoint(model_dir)
+
+ manifest = _load_image_manifest(model_dir)
+
+ assert manifest is not None
+ assert manifest.backend == "mlx-vlm"
+ assert manifest.tasks == tasks
+ assert manifest.metadata["model_path"] == "."
+ assert detect_model_type(model_dir) == "image"
+
+
+def _write_mage_checkpoint(model_dir):
+ text_encoder = model_dir / "text_encoder"
+ text_encoder.mkdir(parents=True)
+ (text_encoder / "tokenizer.json").write_text("{}")
+ (text_encoder / "tokenizer_config.json").write_text("{}")
+ for component in ("transformer", "vae"):
+ component_dir = model_dir / component
+ component_dir.mkdir()
+ for component in ("transformer", "vae", "text_encoder"):
+ component_dir = model_dir / component
+ (component_dir / "config.json").write_text("{}")
+ (component_dir / "diffusion_pytorch_model.safetensors").write_bytes(b"weights")
+ (model_dir / "model_index.json").write_text('{"_class_name": "MageFlowPipeline"}')
+
+
+@pytest.mark.parametrize(
+ ("variant", "tasks"),
+ [
+ ("mage-flow-turbo", ["generation"]),
+ ("mage-flow-edit-turbo", ["edit"]),
+ ],
+)
+def test_backend_recipe_overrides_folder_name_and_registry_tasks(
+ tmp_path, variant, tasks
+):
+ model_dir = tmp_path / (
+ "Mage-Flow-Edit-Turbo" if tasks == ["generation"] else "Mage-Flow-Turbo"
+ )
+ _write_mage_checkpoint(model_dir)
+ (model_dir / "mlx_mage_flow.json").write_text(json.dumps({"variant": variant}))
+
+ assert detect_image_tasks(model_dir) == tasks
+ model = discover_models(tmp_path)[model_dir.name]
+ assert model.model_type == model.engine_type == "image"
+ assert model.tasks == model.capabilities == tasks
+
+
+def test_renamed_checkpoint_tasks_do_not_require_registry_alias(tmp_path):
+ model_dir = tmp_path / "my-custom-checkpoint"
+ _write_mage_checkpoint(model_dir)
+ (model_dir / "mlx_mage_flow.json").write_text(
+ json.dumps({"variant": "mage-flow-edit-turbo"})
+ )
+ (model_dir / "transformer" / "config.json").write_text(
+ '{"_class_name": "MageFlowTransformer2DModel"}'
+ )
+
+ assert infer_image_model_spec_from_name(model_dir.name) is None
+ model = discover_models(tmp_path)[model_dir.name]
+ assert model.model_type == model.engine_type == "image"
+ assert model.tasks == model.capabilities == ["edit"]
+
+
+def test_qwen_folder_name_does_not_hide_supported_mage_checkpoint(tmp_path):
+ model_dir = tmp_path / "Qwen-Image-2.1-Turbo"
+ _write_mage_checkpoint(model_dir)
+ (model_dir / "mlx_mage_flow.json").write_text(
+ json.dumps({"variant": "mage-flow-edit-turbo"})
+ )
+
+ assert detect_image_tasks(model_dir) == ["edit"]
+ model = discover_models(tmp_path)[model_dir.name]
+ assert model.tasks == model.capabilities == ["edit"]
+ assert model.image_metadata["base_model"] == "MageFlowPipeline"
+
+
+def test_incomplete_named_checkpoint_is_not_discovered(tmp_path):
+ model_dir = tmp_path / "Mage-Flow-Edit-Turbo"
+ _write_mage_checkpoint(model_dir)
+ (model_dir / "text_encoder" / "config.json").unlink()
+ assert detect_image_tasks(model_dir) == []
+ assert model_dir.name not in discover_models(tmp_path)
+
+
+def test_manifest_keeps_quantize_for_clear_engine_validation(tmp_path):
+ model_dir = tmp_path / "flux"
+ model_dir.mkdir()
+ (model_dir / "omlx-image-model.json").write_text(
+ json.dumps(
+ {
+ "backend": "mlx-vlm",
+ "base_model": "flux2-klein-4b",
+ "task": ["generation"],
+ "quantize": 4,
+ }
+ )
+ )
+
+ manifest = _load_image_manifest(model_dir)
+
+ assert manifest is not None
+ assert manifest.metadata["quantize"] == 4
+ assert manifest.backend == "mlx-vlm"
+
+
+def test_unrecognized_vlm_layout_is_not_inferred_as_an_image_model(tmp_path):
+ model_dir = tmp_path / "qwen-vl"
+ model_dir.mkdir()
+ (model_dir / "config.json").write_text(
+ json.dumps(
+ {
+ "model_type": "qwen2_vl",
+ "vision_config": {"hidden_size": 128},
+ "architectures": ["Qwen2VLForConditionalGeneration"],
+ }
+ )
+ )
+ (model_dir / "tokenizer").mkdir()
+ (model_dir / "tokenizer" / "tokenizer.json").write_text("{}")
+ for component in ("transformer", "vae"):
+ component_dir = model_dir / component
+ component_dir.mkdir()
+ (component_dir / "model.safetensors").write_bytes(b"weights")
+
+ assert _load_image_manifest(model_dir) is None
+ assert detect_model_type(model_dir) == "vlm"
+
+
+def test_estimate_uses_unadjusted_family_fallback_without_quantize(tmp_path):
+ model_dir = tmp_path / "z-image"
+ model_dir.mkdir()
+ (model_dir / "omlx-image-model.json").write_text(
+ json.dumps(
+ {
+ "backend": "mlx-vlm",
+ "base_model": "z-image",
+ "task": "generation",
+ "quantize": 4,
+ }
+ )
+ )
+ manifest = _load_image_manifest(model_dir)
+
+ assert manifest is not None
+ assert estimate_image_model_size(model_dir, manifest) == 12 * 1024**3
diff --git a/tests/test_image_utils.py b/tests/test_image_utils.py
index 1a0dbd80f3..955f4dc25e 100644
--- a/tests/test_image_utils.py
+++ b/tests/test_image_utils.py
@@ -13,6 +13,7 @@
from omlx.exceptions import InvalidRequestError
from omlx.utils.image import (
+ compute_audio_video_hash,
compute_image_hash,
compute_per_image_hashes,
extract_images_from_messages,
@@ -98,9 +99,9 @@ def test_rejects_local_file_path(self, tmp_path):
img = _make_test_image(4, 4)
path = tmp_path / "local.png"
img.save(path)
-
with pytest.raises(InvalidRequestError):
load_image(str(path))
+ load_image(str(path))
def test_load_invalid_format_raises(self):
"""Invalid input raises a request error."""
@@ -448,8 +449,133 @@ def test_audio_mixed_with_images(self):
# Text content should be preserved
assert "Describe this image and audio" in text_msgs[0]["content"]
+ def test_input_video_data_uri_is_preserved(self):
+ """Inline video stays in memory until model-specific preprocessing."""
+ video_b64 = base64.b64encode(b"fake mp4 bytes").decode("ascii")
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "input_video",
+ "input_video": {
+ "data": f"data:video/mp4;base64,{video_b64}",
+ "format": "mp4",
+ "filename": "clip.mp4",
+ },
+ },
+ {"type": "text", "text": "Describe this clip"},
+ ],
+ }
+ ]
+
+ text_msgs, images, audio, videos = extract_media_from_messages(messages)
+ assert images == []
+ assert audio == []
+ assert videos == [f"data:video/mp4;base64,{video_b64}"]
+ assert text_msgs[0]["content"] == "Describe this clip"
+
+ def test_input_video_base64_data_is_normalized(self):
+ messages = [{
+ "role": "user",
+ "content": [{
+ "type": "input_video",
+ "input_video": {"data": "cmVjb3JkaW5n", "format": "mp4"},
+ }],
+ }]
+ _, _, _, videos = extract_media_from_messages(messages)
+ assert videos == ["data:video/mp4;base64,cmVjb3JkaW5n"]
+
+ def test_input_video_url_is_rejected(self):
+ """Video inputs must be inline rather than server-fetched."""
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "input_video",
+ "input_video": {
+ "url": "https://example.com/clip.mp4",
+ "format": "mp4",
+ },
+ }
+ ],
+ }
+ ]
+
+ with pytest.raises(InvalidRequestError, match="base64"):
+ extract_media_from_messages(messages)
+
+ def test_input_video_private_url_rejected(self):
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "input_video",
+ "input_video": {
+ "url": "http://127.0.0.1/clip.mp4",
+ "format": "mp4",
+ },
+ }
+ ],
+ }
+ ]
-def test_video_input_is_rejected():
+ with pytest.raises(InvalidRequestError, match="base64"):
+ extract_media_from_messages(messages)
+
+ def test_input_video_string_private_url_rejected(self):
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "input_video",
+ "input_video": "http://127.0.0.1/clip.mp4",
+ }
+ ],
+ }
+ ]
+
+ with pytest.raises(InvalidRequestError, match="base64"):
+ extract_media_from_messages(messages)
+
+ def test_input_video_string_private_url_rejected_after_strip(self):
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "input_video",
+ "input_video": " http://127.0.0.1/clip.mp4 ",
+ }
+ ],
+ }
+ ]
+
+ with pytest.raises(InvalidRequestError, match="base64"):
+ extract_media_from_messages(messages)
+
+ def test_input_video_empty_string_rejected(self):
+ """Empty video parts fail explicitly instead of silently disappearing."""
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "input_video",
+ "input_video": " ",
+ }
+ ],
+ }
+ ]
+
+ with pytest.raises(InvalidRequestError, match="base64"):
+ extract_media_from_messages(messages)
+
+
+def test_compat_image_extraction_rejects_video():
messages = [
{
"role": "user",
@@ -499,6 +625,16 @@ def test_extract_media_rejects_video_part_without_url():
extract_media_from_messages(messages)
+def test_audio_cache_hash_preserves_buffer_position():
+ recording = io.BytesIO(b"recording")
+ recording.seek(3)
+ digest = compute_audio_video_hash([recording], [])
+ assert recording.tell() == 3
+ assert digest == compute_audio_video_hash([io.BytesIO(b"recording")], [])
+ assert digest != compute_audio_video_hash([io.BytesIO(b"different")], [])
+ assert compute_audio_video_hash([], []) is None
+
+
# =============================================================================
# Tests: compute_image_hash
# =============================================================================
diff --git a/tests/test_mlx_vlm_image_compat.py b/tests/test_mlx_vlm_image_compat.py
new file mode 100644
index 0000000000..386e06afec
--- /dev/null
+++ b/tests/test_mlx_vlm_image_compat.py
@@ -0,0 +1,453 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Tests for native mlx-vlm image models and oMLX compatibility."""
+
+from __future__ import annotations
+
+import importlib
+import json
+from dataclasses import dataclass
+from types import SimpleNamespace
+
+import pytest
+
+from omlx.patches.mlx_vlm_image_compat import (
+ apply_mlx_vlm_image_compat_patch,
+)
+
+
+@pytest.mark.parametrize(
+ ("family", "expected_steps", "expected_guidance"),
+ [("mage-flow", 4, 1.0), ("z-image", 9, 0.0), ("ming-image", 12, 1.0)],
+)
+@pytest.mark.parametrize("overrides", ["backend", "manifest", "request"])
+async def test_engine_uses_native_sampling_with_manifest_and_request_precedence(
+ image_apis,
+ monkeypatch,
+ tmp_path,
+ family,
+ expected_steps,
+ expected_guidance,
+ overrides,
+):
+ import mlx.core as mx
+
+ import omlx.engine.image as engine_module
+ from omlx.engine.image import ImageEngine
+
+ image, edit_image = image_apis
+ calls = []
+
+ def generate_array(prompt, **kwargs):
+ calls.append(kwargs)
+ return mx.zeros((2, 2, 3), dtype=mx.uint8)
+
+ pipeline = SimpleNamespace(
+ model_path=tmp_path,
+ generate_array=generate_array,
+ count_prompt_tokens=lambda prompt: 0,
+ quantization_config=None,
+ )
+ if family == "mage-flow":
+ from mlx_vlm.models.mage_flow.config import get_variant
+ from mlx_vlm.models.mage_flow.model import MageFlowImageGenerationModel
+
+ pipeline.variant = get_variant("mage-flow-turbo")
+ model = MageFlowImageGenerationModel(pipeline, "local-model")
+ elif family == "z-image":
+ from mlx_vlm.models.z_image.model import ZImageGenerationModel
+
+ pipeline.config = SimpleNamespace(
+ variant="turbo", default_steps=9, default_guidance=0.0
+ )
+ model = ZImageGenerationModel(pipeline, "local-model")
+ else:
+ from mlx_vlm.models.ming_image.model import MingImageGenerationModel
+
+ pipeline.config = SimpleNamespace(default_steps=12, default_guidance=1.0)
+ model = MingImageGenerationModel(pipeline, "local-model")
+
+ monkeypatch.setattr(
+ engine_module,
+ "_image_api",
+ lambda: SimpleNamespace(
+ load_image_model=lambda *args, **kwargs: model,
+ generate_image=image.generate_image,
+ ImageGenerationRequest=image.ImageGenerationRequest,
+ ImageEditRequest=edit_image.ImageEditRequest,
+ ),
+ )
+ metadata = {"backend": "mlx-vlm", "base_model": family}
+ if overrides != "backend":
+ metadata.update(default_steps=7, default_guidance=0.75)
+ expected_steps, expected_guidance = 7, 0.75
+ request = {}
+ if overrides == "request":
+ request = {"steps": 3, "guidance": 0.5}
+ expected_steps, expected_guidance = 3, 0.5
+ engine = ImageEngine(
+ model_name="local-model",
+ model_path=str(tmp_path),
+ image_metadata=metadata,
+ tasks=["generation"],
+ )
+ await engine.start()
+ try:
+ result = await engine.generate("a fox", **request)
+ assert calls[-1]["steps"] == expected_steps
+ assert calls[-1]["guidance"] == expected_guidance
+ assert calls[-1]["width"] == calls[-1]["height"] == 512
+ assert result.metadata["steps"] == expected_steps
+ assert result.metadata["guidance"] == expected_guidance
+ assert result.image.size == (2, 2)
+ finally:
+ await engine.stop()
+
+
+@pytest.fixture(scope="module")
+def image_apis():
+ pytest.importorskip("mlx_vlm")
+ apply_mlx_vlm_image_compat_patch()
+ image = importlib.import_module("mlx_vlm.generate.image")
+ edit_image = importlib.import_module("mlx_vlm.generate.edit_image")
+
+ return image, edit_image
+
+
+@pytest.mark.parametrize("name", ["Qwen-Image-2.1-Turbo", "custom-checkpoint"])
+def test_native_generation_loader_prefers_supported_checkpoint_metadata(
+ image_apis, monkeypatch, tmp_path, name
+):
+ from mlx_vlm.models.mage_flow.model import MageFlowImageGenerationModel
+
+ image, _ = image_apis
+ root = tmp_path / name
+ for component in ("transformer", "vae", "text_encoder"):
+ directory = root / component
+ directory.mkdir(parents=True)
+ (directory / "config.json").write_text("{}")
+ (directory / "model.safetensors").write_bytes(b"weights")
+ (root / "text_encoder" / "tokenizer.json").write_text("{}")
+ (root / "model_index.json").write_text('{"_class_name":"MageFlowPipeline"}')
+ (root / "mlx_mage_flow.json").write_text('{"variant":"mage-flow-turbo"}')
+ calls = []
+ model = object()
+
+ def from_model_id(cls, model_id, **kwargs):
+ calls.append((model_id, kwargs))
+ return model
+
+ monkeypatch.setattr(
+ MageFlowImageGenerationModel, "from_model_id", classmethod(from_model_id)
+ )
+
+ assert image.is_image_generation_model(str(root))
+ assert image.load_image_model(str(root), task="generate") is model
+ assert calls == [(str(root), {"model_path": root})]
+
+
+@pytest.mark.parametrize(
+ ("alias", "generation_name", "edit_name"),
+ [
+ ("z-image", "ZImageGenerationModel", "ZImageEditModel"),
+ ("ernie-image-turbo", "ErnieImageGenerationModel", "ErnieImageEditModel"),
+ ],
+)
+def test_image_families_register_with_generic_dispatch(
+ image_apis, alias, generation_name, edit_name
+):
+ image, edit_image = image_apis
+
+ generation = image.image_generation_model_class(alias)
+ edit = edit_image.image_edit_model_class(alias)
+
+ assert generation is not None
+ assert edit is not None
+ assert generation.__name__ == generation_name
+ assert edit.__name__ == edit_name
+
+
+def test_z_image_uses_native_mlx_vlm_package(image_apis):
+ import mlx_vlm.models.z_image as z_image
+
+ assert "omlx/patches" not in str(z_image.__file__)
+
+
+@pytest.mark.parametrize("family", ["z-image", "ernie-image"])
+def test_native_single_source_models_reject_multiple_references(image_apis, family):
+ _, edit_image = image_apis
+ if family == "z-image":
+ from mlx_vlm.models.z_image.model import ZImageEditModel
+ from mlx_vlm.models.z_image.pipeline import ZImagePipeline
+
+ pipeline = object.__new__(ZImagePipeline)
+ pipeline.config = SimpleNamespace(
+ variant="turbo", default_steps=9, default_guidance=0.0
+ )
+ model = ZImageEditModel(pipeline, "local-model")
+ else:
+ from mlx_vlm.models.ernie_image.model import ErnieImageEditModel
+
+ model = ErnieImageEditModel(SimpleNamespace(), "local-model")
+ request = edit_image.ImageEditRequest(
+ prompt="combine", image_paths=("first.png", "second.png")
+ )
+ with pytest.raises(ValueError, match="exactly one source image"):
+ edit_image.edit_image(model, request)
+
+
+def test_ernie_image_uses_native_mlx_vlm_package(image_apis):
+ import mlx_vlm.models.ernie_image as ernie_image
+
+ assert "omlx/patches" not in str(ernie_image.__file__)
+
+
+def test_ming_image_registers_generation_only_and_uses_native_package(image_apis):
+ image, edit_image = image_apis
+ from mlx_vlm.models.ming_image.model import MingImageGenerationModel
+
+ assert "omlx/patches" not in str(
+ importlib.import_module("mlx_vlm.models.ming_image").__file__
+ )
+ assert (
+ image.image_generation_model_class("ming-image-0.1-design")
+ is MingImageGenerationModel
+ )
+ assert edit_image.image_edit_model_class("ming-image-0.1-design") is None
+
+ ming = object.__new__(MingImageGenerationModel)
+ ming.pipeline = SimpleNamespace(
+ config=SimpleNamespace(default_steps=12, default_guidance=1.0)
+ )
+ assert ming.default_sampling.steps == 12
+ assert ming.default_sampling.guidance == 1.0
+
+ request = image.ImageGenerationRequest(prompt="a poster")
+ assert request.width == request.height == 512
+ assert request.steps is request.guidance is None
+
+
+def test_unlimited_ocr_uses_native_mlx_vlm_support():
+ import mlx_vlm.models.unlimited_ocr as unlimited_ocr
+ from mlx_vlm.prompt_utils import get_message_json
+ from mlx_vlm.utils import MODEL_REMAPPING, get_model_and_args
+
+ assert "omlx/patches" not in str(unlimited_ocr.__file__)
+ assert MODEL_REMAPPING["unlimited-ocr"] == "unlimited_ocr"
+
+ module, model_type = get_model_and_args(
+ {
+ "model_type": "unlimited-ocr",
+ "architectures": ["UnlimitedOCRForCausalLM"],
+ "vision_config": {},
+ "text_config": {},
+ }
+ )
+ assert module is unlimited_ocr
+ assert model_type == "unlimited_ocr"
+
+ message = get_message_json(
+ "unlimited-ocr",
+ "Multi page parsing.",
+ num_images=3,
+ )
+ assert message == {"role": "user", "content": "Multi page parsing."}
+
+
+def test_z_image_tokenizer_disables_remote_code(image_apis, monkeypatch):
+ import transformers
+ from mlx_vlm.models.z_image import pipeline
+
+ received = {}
+
+ def fake_from_pretrained(*args, **kwargs):
+ received.update(kwargs)
+ return object()
+
+ monkeypatch.setattr(
+ transformers.AutoTokenizer, "from_pretrained", fake_from_pretrained
+ )
+
+ pipeline.AutoTokenizer.from_pretrained(
+ "/tmp/tokenizer",
+ local_files_only=False,
+ trust_remote_code=True,
+ )
+
+ assert received["local_files_only"] is True
+ assert received["trust_remote_code"] is False
+
+
+def test_existing_image_families_provide_native_sampling_defaults(image_apis):
+ from mlx_vlm.models.flux2.model import (
+ Flux2ImageEditModel,
+ Flux2ImageGenerationModel,
+ )
+ from mlx_vlm.models.mage_flow.model import (
+ MageFlowImageEditModel,
+ MageFlowImageGenerationModel,
+ )
+ from mlx_vlm.models.z_image.model import ZImageEditModel, ZImageGenerationModel
+
+ for model_class in (
+ Flux2ImageGenerationModel,
+ Flux2ImageEditModel,
+ MageFlowImageGenerationModel,
+ MageFlowImageEditModel,
+ ZImageGenerationModel,
+ ZImageEditModel,
+ ):
+ assert isinstance(model_class.default_sampling, property)
+
+ z_generation = object.__new__(ZImageGenerationModel)
+ z_generation.pipeline = SimpleNamespace(
+ config=SimpleNamespace(default_steps=9, default_guidance=0.0)
+ )
+ assert z_generation.default_sampling.steps == 9
+ assert z_generation.default_sampling.guidance == 0.0
+
+ z_edit = object.__new__(ZImageEditModel)
+ z_edit.pipeline = SimpleNamespace(
+ config=SimpleNamespace(variant="turbo", default_guidance=0.0)
+ )
+ assert z_edit.default_sampling.steps == 8
+ assert z_edit.default_sampling.guidance == 0.0
+
+
+@pytest.mark.parametrize("alias", ["z-image", "ernie-image-turbo"])
+def test_generic_loader_dispatches_image_families_without_weights(
+ image_apis, alias, monkeypatch
+):
+ image, edit_image = image_apis
+ generation_class = image.image_generation_model_class(alias)
+ edit_class = edit_image.image_edit_model_class(alias)
+ generation_sentinel = object()
+ edit_sentinel = object()
+
+ def fake_generation_load(cls, model, **kwargs):
+ assert model == alias
+ return generation_sentinel
+
+ def fake_edit_load(cls, model, **kwargs):
+ assert model == alias
+ return edit_sentinel
+
+ monkeypatch.setattr(
+ generation_class,
+ "from_model_id",
+ classmethod(fake_generation_load),
+ )
+ monkeypatch.setattr(edit_class, "from_model_id", classmethod(fake_edit_load))
+ monkeypatch.setattr(
+ image, "_resolve_image_model_path", lambda *args, **kwargs: None
+ )
+
+ assert image.load_image_model(alias, task="generate") is generation_sentinel
+ assert image.load_image_model(alias, task="edit") is edit_sentinel
+
+
+def test_generic_api_preserves_native_requests_for_model_default_resolution(image_apis):
+ image, edit_image = image_apis
+
+ @dataclass
+ class GenerationModel:
+ default_steps = 11
+ default_guidance = 2.5
+ default_width = 768
+ default_height = 512
+
+ def generate(self, request):
+ return request
+
+ @dataclass
+ class EditModel:
+ default_steps = 9
+ default_guidance = 1.5
+
+ def edit(self, request):
+ return request
+
+ generation_request = image.ImageGenerationRequest(
+ prompt="a fox",
+ seed=1,
+ )
+ assert generation_request.steps is None
+ assert generation_request.width == 512
+ assert generation_request.height == 512
+ assert generation_request.guidance is None
+ generation_result = image.generate_image(GenerationModel(), generation_request)
+ assert generation_result is generation_request
+ assert generation_result.steps is None
+ assert generation_result.guidance is None
+ assert generation_result.width == 512
+ assert generation_result.height == 512
+
+ edit_request = edit_image.ImageEditRequest(
+ prompt="make it blue",
+ image_paths=("input.png",),
+ seed=1,
+ )
+ assert edit_request.steps is None
+ assert edit_request.guidance is None
+ edit_result = edit_image.edit_image(EditModel(), edit_request)
+ assert edit_result is edit_request
+ assert edit_result.steps is None
+ assert edit_result.guidance is None
+
+
+@pytest.mark.parametrize(
+ ("markers", "expected_model_type"),
+ [
+ (
+ {
+ "layers.0.feed_forward.w1.weight": "weights.safetensors",
+ "context_refiner.0.attention.to_q.weight": "weights.safetensors",
+ "noise_refiner.0.adaLN_modulation.0.weight": "weights.safetensors",
+ },
+ "z_image",
+ ),
+ (
+ {
+ "adaln_modulation.weight": "weights.safetensors",
+ "final_norm.linear.weight": "weights.safetensors",
+ "layers.0.adaLN_sa_ln.weight": "weights.safetensors",
+ },
+ "ernie_image",
+ ),
+ ],
+)
+def test_component_indexes_dispatch_to_image_models(
+ image_apis, markers, expected_model_type, tmp_path
+):
+ image, _ = image_apis
+ transformer = tmp_path / "transformer"
+ transformer.mkdir()
+ (transformer / "model.safetensors.index.json").write_text(
+ json.dumps({"weight_map": markers})
+ )
+
+ assert (
+ image._image_model_type_from_component_indexes(tmp_path) == expected_model_type
+ )
+
+
+def test_ernie_legacy_mlx_checkpoint_layout_is_preserved(image_apis):
+ from mlx_vlm.models.ernie_image.weights import _tensor_layout
+
+ assert _tensor_layout({"mflux_version": "0.1"}) == "mlx_nhwc"
+
+
+def test_ernie_edit_defaults_and_converted_source_metadata(image_apis, tmp_path):
+ from mlx_vlm.models.ernie_image.config import get_variant, variant_from_local_path
+ from mlx_vlm.models.ernie_image.model import ErnieImageEditModel
+
+ turbo = get_variant("ernie-image-turbo")
+ assert turbo.edit_default_guidance == 3.0
+
+ edit = object.__new__(ErnieImageEditModel)
+ edit.pipeline = SimpleNamespace(variant=turbo)
+ assert edit.default_guidance == 3.0
+
+ (tmp_path / "mlx_ernie_image.json").write_text(
+ json.dumps({"source": "baidu/ERNIE-Image-Turbo", "variant": "ernie-image"})
+ )
+ assert variant_from_local_path(tmp_path) is turbo
diff --git a/tests/test_qwen_image_compat.py b/tests/test_qwen_image_compat.py
new file mode 100644
index 0000000000..74f567d8a1
--- /dev/null
+++ b/tests/test_qwen_image_compat.py
@@ -0,0 +1,425 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Weight-free numerical and end-to-end checks of the Qwen image backport."""
+
+from __future__ import annotations
+
+import importlib
+import json
+from dataclasses import replace
+from io import BytesIO
+from types import SimpleNamespace
+
+import mlx.core as mx
+import numpy as np
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from PIL import Image
+
+from omlx.api import image_routes
+from omlx.engine.image import ImageEngine, _image_api
+from omlx.patches import mlx_vlm_qwen_image_compat as compat
+
+SIGMAS = [1, 0.978453, 0.95418, 0.926626, 0.89508, 0.845148, 0.704534, 0.414568]
+
+
+@pytest.fixture(scope="module")
+def qwen():
+ compat.apply_qwen_image_compat_patch()
+ return SimpleNamespace(
+ **{
+ name: importlib.import_module(f"mlx_vlm.models.qwen_image.{name}")
+ for name in ("config", "scheduler", "pipeline", "model", "text_encoder")
+ }
+ )
+
+
+@pytest.fixture
+def checkpoint(tmp_path):
+ configs = {
+ "model_index.json": {
+ "_class_name": "QwenImage21Pipeline",
+ "sample_sigmas": SIGMAS,
+ },
+ "transformer/config.json": {"_class_name": "QwenImage21Transformer2DModel"},
+ "vae/config.json": {
+ "z_dim": 4,
+ "latents_mean": [0] * 4,
+ "latents_std": [1] * 4,
+ },
+ "scheduler/scheduler_config.json": {
+ "use_dynamic_shifting": False,
+ "shift": 1,
+ "shift_terminal": None,
+ "base_image_seq_len": 256,
+ "max_image_seq_len": 8192,
+ "base_shift": 0.5,
+ "max_shift": 0.9,
+ "num_train_timesteps": 1000,
+ },
+ }
+ for relative, data in configs.items():
+ path = tmp_path / relative
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(data))
+ return tmp_path
+
+
+def _tiny_pipeline(qwen, checkpoint, monkeypatch):
+ calls, references = [], []
+ encoder = SimpleNamespace(
+ encode=lambda _: mx.zeros((1, 2, 8)),
+ encode_edit=lambda _, refs: (
+ references.append(len(refs)) or mx.zeros((1, 2, 8)),
+ mx.ones((1, 2), dtype=mx.bool_),
+ ),
+ tokenizer=lambda _: {"input_ids": [1, 2]},
+ )
+ monkeypatch.setattr(qwen.pipeline, "QwenImageTextEncoder", lambda **_: encoder)
+
+ def transformer(*, timestep, img_shape, **kwargs):
+ calls.append((timestep, kwargs))
+ return mx.ones((1, img_shape[1] * img_shape[2], 4), dtype=mx.bfloat16)
+
+ transformer.causal_condition = False
+ vae = SimpleNamespace(
+ encode=lambda pixels: (
+ mx.zeros((1, 4, 1, pixels.shape[-2] // 16, pixels.shape[-1] // 16)),
+ None,
+ ),
+ decode=lambda z: mx.zeros((1, 4, 1, z.shape[-2] * 16, z.shape[-1] * 16)),
+ )
+ pipeline = qwen.pipeline.QwenImagePipeline(
+ variant=qwen.config.get_variant("qwen-image-2.1-turbo"),
+ model_path=checkpoint,
+ text_encoder=None,
+ transformer=transformer,
+ vae=vae,
+ )
+ return pipeline, calls, references
+
+
+@pytest.mark.parametrize("seq_len", [256, 4096, 16384])
+def test_backported_turbo_exact_grid_dtype_timesteps_and_euler(qwen, seq_len):
+ scheduler = qwen.scheduler.FlowMatchEulerDiscreteScheduler(
+ image_seq_len=seq_len,
+ num_inference_steps=30,
+ sigmas=SIGMAS,
+ use_dynamic_shifting=False,
+ shift=1,
+ shift_terminal=None,
+ )
+ expected = np.array([*SIGMAS, 0], dtype=np.float32)
+ np.testing.assert_array_equal(np.array(scheduler.sigmas), expected)
+ np.testing.assert_array_equal(
+ np.array(scheduler.timesteps), expected[:-1] * np.float32(1000)
+ )
+ assert scheduler.sigmas.dtype == mx.float32
+ latent = mx.array([2.0])
+ for step in range(8):
+ latent = scheduler.step(noise=mx.array([1.0]), latents=latent, step_index=step)
+ np.testing.assert_allclose(np.array(latent), [1], atol=1e-7)
+
+
+def test_explicit_sigmas_are_transformed_and_legacy_dynamic_defaults_survive(qwen):
+ cls = qwen.scheduler.FlowMatchEulerDiscreteScheduler
+ grid = cls(
+ image_seq_len=4096,
+ num_inference_steps=30,
+ sigmas=[1, 0.5, 0.2],
+ use_dynamic_shifting=False,
+ shift=2,
+ shift_terminal=None,
+ )
+ np.testing.assert_allclose(np.array(grid.sigmas), [1, 2 / 3, 1 / 3, 0], atol=1e-7)
+ grid = cls(image_seq_len=4096, num_inference_steps=4)
+ source = np.linspace(1, 0.25, 4, dtype=np.float32)
+ mu = qwen.scheduler.calculate_shift(4096)
+ shifted = np.exp(mu) / (np.exp(mu) + (1 / source - 1))
+ expected = 1 - (1 - shifted) / ((1 - shifted[-1]) / 0.98)
+ np.testing.assert_allclose(np.array(grid.sigmas), [*expected, 0], atol=1e-7)
+
+
+@pytest.mark.parametrize("task", ["generation", "edit"])
+@pytest.mark.parametrize("override", [None, [1, 0.6, 0.2]])
+def test_real_wrappers_and_sampler_report_effective_steps(
+ qwen, checkpoint, monkeypatch, task, override
+):
+ pipeline, calls, refs = _tiny_pipeline(qwen, checkpoint, monkeypatch)
+ api = _image_api()
+ cls = (
+ qwen.model.QwenImageGenerationModel
+ if task == "generation"
+ else qwen.model.QwenImageEditModel
+ )
+ instance = cls(pipeline, "tiny-qwen")
+ assert instance.default_sampling.steps == 8
+ request_fields = dict(
+ prompt="a fox",
+ steps=30,
+ width=32,
+ height=32,
+ guidance=1,
+ extra={"sigmas": override, "output_resolution": 256},
+ )
+ if task == "generation":
+ result = instance.generate(api.ImageGenerationRequest(**request_fields))
+ else:
+ paths = []
+ for index in range(2):
+ path = checkpoint / f"reference-{index}.png"
+ Image.new("RGBA", (32, 32), (index * 255, 0, 0, 128)).save(path)
+ paths.append(str(path))
+ result = instance.edit(
+ api.ImageEditRequest(image_paths=paths, **request_fields)
+ )
+ assert refs == [2]
+ assert all(len(kwargs["reference_image_shapes"]) == 2 for _, kwargs in calls)
+ expected = SIGMAS if override is None else override
+ assert result.steps == len(expected) == len(calls)
+ assert result.array.shape == (32, 32, 3 if task == "generation" else 4)
+ assert result.array.dtype == mx.uint8
+ expected_t = (mx.array(expected) * 1000).astype(mx.bfloat16) / 1000
+ np.testing.assert_array_equal(
+ np.array(mx.concatenate([t for t, _ in calls]).astype(mx.float32)),
+ np.array(expected_t.astype(mx.float32)),
+ )
+ calls.clear()
+ pipeline.generate_array("again", width=32, height=32)
+ assert len(calls) == 8
+ assert pipeline.sample_sigmas == tuple(SIGMAS)
+
+
+def test_qwen_engine_routes_execute_saved_recipe_without_weights(
+ qwen, checkpoint, monkeypatch, tmp_path
+):
+ pipeline, calls, references = _tiny_pipeline(qwen, checkpoint, monkeypatch)
+ api = _image_api()
+
+ def load(reference, *, task):
+ assert reference == str(checkpoint)
+ cls = (
+ qwen.model.QwenImageGenerationModel
+ if task == "generate"
+ else qwen.model.QwenImageEditModel
+ )
+ return cls(pipeline, reference)
+
+ api = replace(api, load_image_model=load)
+ monkeypatch.setattr("omlx.engine.image._image_api", lambda: api)
+ engine = ImageEngine(
+ model_name="tiny-qwen",
+ model_path=str(checkpoint),
+ image_metadata={"backend": "mlx-vlm", "base_model": "qwen-image-2.1-turbo"},
+ tasks=["generation", "edit"],
+ )
+ entry = SimpleNamespace(
+ model_type="image", engine_type="image", tasks=["generation", "edit"]
+ )
+
+ class Pool:
+ leases = 0
+
+ def get_entry(self, model_id):
+ return entry
+
+ async def get_engine(self, model_id, *, _lease):
+ assert _lease
+ await engine.start()
+ self.leases += 1
+ return engine
+
+ async def release_engine(self, model_id):
+ self.leases -= 1
+
+ pool = Pool()
+ monkeypatch.setattr(image_routes, "_get_engine_pool", lambda: pool)
+ monkeypatch.setattr(image_routes, "_resolve_model", lambda model: model)
+ app = FastAPI()
+ app.include_router(image_routes.router)
+ with TestClient(app) as client:
+ generation = client.post(
+ "/v1/images/generations",
+ json={
+ "model": "tiny-qwen",
+ "prompt": "a fox",
+ "steps": 30,
+ "size": "32x32",
+ },
+ )
+ assert generation.status_code == 200
+ assert generation.json()["data"][0]["steps"] == 8
+ assert len(calls) == 8
+ calls.clear()
+ buffer = BytesIO()
+ Image.new("RGB", (32, 32), "red").save(buffer, format="PNG")
+ edit = client.post(
+ "/v1/images/edits",
+ data={
+ "model": "tiny-qwen",
+ "prompt": "blue",
+ "steps": "30",
+ "size": "32x32",
+ },
+ files=[
+ ("image", ("one.png", buffer.getvalue(), "image/png")),
+ ("image", ("two.png", buffer.getvalue(), "image/png")),
+ ],
+ )
+ assert edit.status_code == 200
+ assert edit.json()["data"][0]["steps"] == 8
+ assert references == [2]
+ assert len(calls) == 8
+ assert pool.leases == 0
+ assert not list((tmp_path / "inputs").glob("*"))
+
+
+def test_source_gate_fixed_noop_unknown_and_repeated_application(qwen, monkeypatch):
+ from omlx.patches.mlx_vlm_qwen_image_compat._backport import BACKPORTS
+
+ sources = {
+ name: compat._read_source(importlib.import_module(name)) for name in BACKPORTS
+ }
+ fixed = compat._prepare_sources(sources, BACKPORTS)
+ assert compat._prepare_sources(fixed, BACKPORTS) == {}
+ altered = {
+ **sources,
+ next(iter(sources)): "raise RuntimeError('divergent source')\n",
+ }
+ with pytest.raises(RuntimeError, match="Unsupported"):
+ compat._prepare_sources(altered, BACKPORTS)
+ partially_fixed = {**sources, next(iter(fixed)): next(iter(fixed.values()))}
+ with pytest.raises(RuntimeError, match="partially fixed"):
+ compat._prepare_sources(partially_fixed, BACKPORTS)
+ cls = qwen.model.QwenImageGenerationModel
+ assert compat.apply_qwen_image_compat_patch() is False
+ assert qwen.model.QwenImageGenerationModel is cls
+ monkeypatch.setattr(compat, "_APPLIED", False)
+ monkeypatch.setattr(compat, "_read_source", lambda module: fixed[module.__name__])
+ assert compat.apply_qwen_image_compat_patch() is False
+ assert qwen.model.QwenImageGenerationModel is cls
+
+
+@pytest.mark.parametrize("layout", ["legacy", "nested", "both"])
+def test_nested_processor_backport_uses_real_image_preprocessing(
+ qwen, checkpoint, layout
+):
+ from tokenizers import Tokenizer
+ from tokenizers.models import WordLevel
+ from transformers import PreTrainedTokenizerFast
+
+ directory = checkpoint / "processor"
+ directory.mkdir()
+ config = {
+ "patch_size": 16,
+ "merge_size": 2,
+ "temporal_patch_size": 2,
+ "image_mean": [0.5] * 3,
+ "image_std": [0.5] * 3,
+ "size": {"shortest_edge": 65536, "longest_edge": 16777216},
+ }
+ if layout in ("nested", "both"):
+ (directory / "processor_config.json").write_text(
+ json.dumps(
+ {
+ "processor_class": "Qwen3VLProcessor",
+ "image_processor": config,
+ "video_processor": {"patch_size": 99},
+ }
+ )
+ )
+ if layout in ("legacy", "both"):
+ (directory / "preprocessor_config.json").write_text(
+ json.dumps(
+ {
+ **config,
+ "min_pixels": 1024,
+ "max_pixels": 4096,
+ }
+ )
+ )
+ encoder = object.__new__(qwen.text_encoder.QwenImageTextEncoder)
+ encoder.processor_dir = str(directory)
+ encoder._processor = None
+ encoder.tokenizer = PreTrainedTokenizerFast(
+ tokenizer_object=Tokenizer(WordLevel({"[UNK]": 0}, unk_token="[UNK]")),
+ unk_token="[UNK]",
+ )
+ processor = encoder.processor.image_processor
+ assert processor.patch_size == 16
+ assert processor.min_pixels == (65536 if layout == "nested" else 1024)
+ pixels = processor(Image.new("RGB", (32, 32), "white"), return_tensors="np")
+ assert np.isfinite(pixels["pixel_values"]).all()
+
+
+@pytest.mark.parametrize("task", ["generate", "edit"])
+def test_renamed_qwen_checkpoint_uses_real_generic_loader_without_downloads(
+ qwen, checkpoint, monkeypatch, task
+):
+ api = _image_api()
+ download = importlib.import_module("mlx_vlm.models.qwen_image.download")
+ weights = importlib.import_module("mlx_vlm.models.qwen_image.weights")
+ monkeypatch.setattr(
+ download,
+ "snapshot_download",
+ lambda **_: pytest.fail("Local Qwen dispatch must not download a checkpoint"),
+ )
+ for component in ("transformer", "vae", "text_encoder"):
+ directory = checkpoint / component
+ directory.mkdir(exist_ok=True)
+ (directory / "model.safetensors").write_bytes(b"unused")
+ (checkpoint / "text_encoder" / "config.json").write_text("{}")
+ processor = checkpoint / "processor"
+ processor.mkdir()
+ (processor / "tokenizer.json").write_text("{}")
+ pipeline = SimpleNamespace(
+ sample_sigmas=tuple(SIGMAS),
+ model_path=checkpoint,
+ variant=qwen.config.get_variant("qwen-image-2.1-turbo"),
+ )
+ received = []
+
+ def from_pretrained(cls, variant, **kwargs):
+ received.append(kwargs)
+ return pipeline
+
+ monkeypatch.setattr(
+ qwen.pipeline.QwenImagePipeline, "from_pretrained", classmethod(from_pretrained)
+ )
+ # Ensure a class cached before activation cannot redirect to another family.
+ model = api.load_image_model(str(checkpoint), task=task)
+ expected = (
+ qwen.model.QwenImageGenerationModel
+ if task == "generate"
+ else qwen.model.QwenImageEditModel
+ )
+ assert isinstance(model, expected)
+ assert model.pipeline is pipeline
+ assert model.default_sampling.steps == 8
+ assert received[0]["model_path"] == checkpoint
+ assert (
+ download.get_variant("Qwen/Qwen-Image-2.1-Turbo").repo_id
+ == "Qwen/Qwen-Image-2.1-Turbo"
+ )
+ assert (
+ weights.get_variant("Qwen/Qwen-Image-2.1-Turbo").repo_id
+ == "Qwen/Qwen-Image-2.1-Turbo"
+ )
+
+
+@pytest.mark.parametrize("steps", [0, -1, True, "8", 1.5])
+def test_invalid_steps_cannot_hide_behind_checkpoint_recipe(qwen, steps):
+ with pytest.raises(ValueError, match="steps"):
+ qwen.config.resolve_sampling(steps, None, tuple(SIGMAS))
+
+
+@pytest.mark.parametrize("sigmas", [[1e-50], [1, 1 - 1e-10]])
+def test_float32_collapsed_grid_is_rejected(qwen, sigmas):
+ with pytest.raises(ValueError, match="float32"):
+ qwen.scheduler.FlowMatchEulerDiscreteScheduler(
+ image_seq_len=256,
+ num_inference_steps=8,
+ sigmas=sigmas,
+ use_dynamic_shifting=False,
+ shift_terminal=None,
+ )
diff --git a/tests/test_qwen_image_source_hash.py b/tests/test_qwen_image_source_hash.py
new file mode 100644
index 0000000000..46ea3317f6
--- /dev/null
+++ b/tests/test_qwen_image_source_hash.py
@@ -0,0 +1,65 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Portable source fingerprint checks without MLX or model dependencies."""
+
+import ast
+
+import pytest
+
+from omlx.patches.mlx_vlm_qwen_image_compat.generate_backport import source_hash
+
+
+@pytest.mark.parametrize(
+ ("source", "expected"),
+ [
+ (
+ "class Model:\n pass\n",
+ "982ac2b3eb77fb75af373b2638159f4a698e3701e533a1c4d69bfe2f582f03f3",
+ ),
+ (
+ "def load():\n return 1\n",
+ "577391320d95bead4088cf34bd51c4f9c18b81d1572ad1ae17b997a4a861e95b",
+ ),
+ (
+ "async def load():\n return 1\n",
+ "cd3a2dc5966095d9d58947f47478e725957eb3c754cbe75254cb654307677f92",
+ ),
+ ],
+)
+def test_source_fingerprints_are_python_version_independent(
+ source, expected, monkeypatch
+):
+ assert source_hash(source) == expected
+ tree = ast.parse(source)
+ definition = tree.body[0]
+ if "type_params" not in definition._fields:
+ definition._fields = (*definition._fields, "type_params")
+ definition.type_params = []
+ monkeypatch.setattr(ast, "parse", lambda _: tree)
+ assert source_hash(source) == expected
+ definition.type_params = [ast.Name(id="T", ctx=ast.Load())]
+ assert source_hash(source) != expected
+
+
+@pytest.mark.parametrize(
+ ("source", "changed", "expected"),
+ [
+ (
+ "values = []\n",
+ "values = [1]\n",
+ "ab546b0086b83a8aaacb0a6c9033493ed1eb9e07bf8012b77cf9e5be261f2f69",
+ ),
+ (
+ "load = lambda: 1\n",
+ "load = lambda x: 1\n",
+ "0c5ebbca9fd07eb4389ad437f1cd11c603f0f5c332c264c35f8af5528a87bb41",
+ ),
+ (
+ "load()\n",
+ "load(1)\n",
+ "2448683c81365c813b6bdfb70e67090fac996d078ebdf5c9a2fb6317870b1243",
+ ),
+ ],
+)
+def test_source_fingerprints_preserve_empty_fields(source, changed, expected):
+ assert source_hash(source) == expected
+ assert source_hash(changed) != expected
From 4cd9f76e96e959ce578833c9d81ce37f79049f8a Mon Sep 17 00:00:00 2001
From: Mike Wallio
Date: Wed, 4 Nov 2026 09:15:01 -0500
Subject: [PATCH 06/24] feat(embeddings): serve embeddings and rerankers
through mlx-vlm
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
---
apps/omlx-mac/Resources/Localizable.xcstrings | 36 -
.../Sources/AppView/Screens/AboutScreen.swift | 7 -
omlx/api/embedding_utils.py | 6 +-
omlx/engine/embedding.py | 28 +-
omlx/models/embedding.py | 619 ++++-----
omlx/models/mlx_embeddings_compat.py | 207 ---
omlx/models/qwen2_embedding.py | 5 +-
omlx/models/reranker.py | 310 ++---
omlx/models/xlm_roberta.py | 543 --------
omlx/patches/modernbert_attention.py | 34 +-
tests/test_embedding.py | 1230 +++++++----------
tests/test_encoder_quantization.py | 94 ++
tests/test_mlx_embeddings_compat.py | 343 -----
tests/test_modernbert_attention.py | 29 +-
tests/test_reranker_causal_lm.py | 66 +-
...est_reranker_modernbert_attention_patch.py | 142 +-
tests/test_reranker_vl.py | 153 +-
17 files changed, 1328 insertions(+), 2524 deletions(-)
delete mode 100644 omlx/models/mlx_embeddings_compat.py
delete mode 100644 omlx/models/xlm_roberta.py
create mode 100644 tests/test_encoder_quantization.py
delete mode 100644 tests/test_mlx_embeddings_compat.py
diff --git a/apps/omlx-mac/Resources/Localizable.xcstrings b/apps/omlx-mac/Resources/Localizable.xcstrings
index 31830ab8d3..868e0f576f 100644
--- a/apps/omlx-mac/Resources/Localizable.xcstrings
+++ b/apps/omlx-mac/Resources/Localizable.xcstrings
@@ -4564,42 +4564,6 @@
}
}
},
- "about.credits.mlx_embeddings.role" : {
- "comment" : "About screen Credits row: role/description for the mlx-embeddings project",
- "extractionState" : "manual",
- "localizations" : {
- "de" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Embedding- und Reranker-Modelle auf MLX"
- }
- },
- "en" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Embedding + reranker models on MLX"
- }
- },
- "it" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Modelli di embedding + reranker su MLX"
- }
- },
- "ru" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Модели эмбеддингов и реранкеров на MLX"
- }
- },
- "zh-Hans" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "MLX 上的 Embedding + 重排序模型"
- }
- }
- }
- },
"about.credits.mlx_lm.role" : {
"comment" : "About screen Credits row: role/description for the mlx-lm project",
"extractionState" : "manual",
diff --git a/apps/omlx-mac/Sources/AppView/Screens/AboutScreen.swift b/apps/omlx-mac/Sources/AppView/Screens/AboutScreen.swift
index 56e5e5665e..cb8b04ed3b 100644
--- a/apps/omlx-mac/Sources/AppView/Screens/AboutScreen.swift
+++ b/apps/omlx-mac/Sources/AppView/Screens/AboutScreen.swift
@@ -204,13 +204,6 @@ private struct CreditsSection: View {
comment: "About screen Credits row: role/description for the mlx-vlm project"),
url: URL(string: "https://github.com/Neywa-Labs/mlx-vlm")!
),
- Credit(
- name: "mlx-embeddings",
- role: String(localized: "about.credits.mlx_embeddings.role",
- defaultValue: "Embedding + reranker models on MLX",
- comment: "About screen Credits row: role/description for the mlx-embeddings project"),
- url: URL(string: "https://github.com/Blaizzy/mlx-embeddings")!
- ),
Credit(
name: "mlx-audio",
role: String(localized: "about.credits.mlx_audio.role",
diff --git a/omlx/api/embedding_utils.py b/omlx/api/embedding_utils.py
index 0824097e1e..b4332abb8e 100644
--- a/omlx/api/embedding_utils.py
+++ b/omlx/api/embedding_utils.py
@@ -38,7 +38,7 @@ def find_non_finite_embeddings(embeddings: Sequence[Sequence[float]]) -> List[in
Return the indices of embeddings that contain NaN or infinite values.
A model that overflows in its attention mask (see modernbert in
- mlx-embeddings) can hand back NaN vectors for some items of a padded
+ mlx-vlm) can hand back NaN vectors for some items of a padded
batch. Those must not be serialized as a successful response: JSON has
no NaN, so the client would receive ``null``-filled vectors with a 200.
@@ -90,10 +90,10 @@ def count_tokens(processor: Any, texts: List[str]) -> int:
"""
Count total tokens in input texts.
- Handles different tokenizer/processor types from mlx-embeddings.
+ Handles different tokenizer/processor types from mlx-vlm.
Args:
- processor: Tokenizer or processor from mlx-embeddings
+ processor: Tokenizer or processor from mlx-vlm
texts: List of input texts
Returns:
diff --git a/omlx/engine/embedding.py b/omlx/engine/embedding.py
index 11c25eab38..ddf15665b7 100644
--- a/omlx/engine/embedding.py
+++ b/omlx/engine/embedding.py
@@ -3,7 +3,7 @@
Embedding engine for oMLX.
This module provides an engine for generating text embeddings using
-mlx-embeddings. Unlike LLM engines, embedding engines don't support
+mlx-vlm. Unlike LLM engines, embedding engines don't support
streaming or chat completion.
"""
@@ -12,7 +12,7 @@
import logging
import time
from collections.abc import Callable
-from typing import Any, Dict, List, Optional, Union
+from typing import Any
import mlx.core as mx
@@ -24,7 +24,7 @@
logger = logging.getLogger(__name__)
-def _input_length(item: Union[str, Dict[str, str]]) -> int:
+def _input_length(item: str | dict[str, str]) -> int:
"""Approximate token cost of one embedding input, used only to group similar sizes."""
if isinstance(item, str):
return len(item)
@@ -82,7 +82,7 @@ def __init__(
else 32
)
self._batch_size = max(1, int(batch_size))
- self._model: Optional[MLXEmbeddingModel] = None
+ self._model: MLXEmbeddingModel | None = None
self._fairness = ForwardFairnessGate(
f"embed:{model_name}:{id(self):x}", scheduler_config
)
@@ -114,7 +114,7 @@ async def run_tokenizer(self, fn: Callable[[], Any]) -> Any:
return await loop.run_in_executor(get_mlx_executor(), fn)
@property
- def hidden_size(self) -> Optional[int]:
+ def hidden_size(self) -> int | None:
"""Get the embedding dimension."""
return self._model.hidden_size if self._model else None
@@ -154,7 +154,7 @@ async def stop(self) -> None:
async def embed(
self,
- texts: Union[List[str], List[Dict[str, str]]],
+ texts: list[str] | list[dict[str, str]],
max_length: int | None = None,
padding: bool = True,
truncation: bool = True,
@@ -190,7 +190,7 @@ async def embed(
)
try:
loop = asyncio.get_running_loop()
- embeddings: List[List[float]] = []
+ embeddings: list[list[float]] = []
total_tokens = 0
dimensions = 0
@@ -209,12 +209,12 @@ async def embed(
batch = ordered_items[index:index + size]
index += len(batch)
- def _embed_sync(batch=batch):
+ def _embed_sync(batch_inputs=batch):
contended = fairness.wait_turn()
start_ts = time.perf_counter()
try:
return model.embed(
- inputs=batch,
+ inputs=batch_inputs,
max_length=max_length,
padding=padding,
truncation=truncation,
@@ -222,7 +222,9 @@ def _embed_sync(batch=batch):
finally:
mx.synchronize()
fairness.settle(
- time.perf_counter() - start_ts, len(batch), contended
+ time.perf_counter() - start_ts,
+ len(batch_inputs),
+ contended,
)
if fairness.should_clear_cache():
mx.clear_cache()
@@ -240,7 +242,7 @@ def _embed_sync(batch=batch):
)
if len(embeddings) == len(order):
- restored: List[List[float]] = [[]] * len(order)
+ restored: list[list[float]] = [[]] * len(order)
for position, original_index in enumerate(order):
restored[original_index] = embeddings[position]
embeddings = restored
@@ -259,7 +261,7 @@ def _embed_sync(batch=batch):
finally:
self._end_activity(activity_id)
- def get_stats(self) -> Dict[str, Any]:
+ def get_stats(self) -> dict[str, Any]:
"""Get engine statistics."""
return {
"model_name": self._model_name,
@@ -268,7 +270,7 @@ def get_stats(self) -> Dict[str, Any]:
"batch_size": self._batch_size,
}
- def get_model_info(self) -> Dict[str, Any]:
+ def get_model_info(self) -> dict[str, Any]:
"""Get information about the loaded model."""
if self._model is None:
return {"loaded": False, "model_name": self._model_name}
diff --git a/omlx/models/embedding.py b/omlx/models/embedding.py
index 36e9c33cfa..c938ba7b1c 100644
--- a/omlx/models/embedding.py
+++ b/omlx/models/embedding.py
@@ -2,10 +2,9 @@
"""
MLX Embedding Model wrapper.
-This module provides a wrapper around mlx-embeddings for generating
-text embeddings using Apple's MLX framework, with native fallback
-for XLMRoBERTa, BERT, and Qwen2-decoder embedding models, and mlx-vlm
-for embedding models that only mlx-vlm implements.
+This module loads Qwen2-decoder embedding models with a native omlx
+implementation and every other embedding model (including XLM-RoBERTa and
+BERT) through mlx-vlm.
"""
import gc
@@ -15,15 +14,20 @@
import logging
from dataclasses import dataclass
from pathlib import Path
-from typing import Any, Dict, List, Optional, Tuple, Union
+from typing import Any
import mlx.core as mx
+import numpy as np
from mlx.utils import tree_flatten, tree_map
from mlx_vlm.embedding_loader import load_embedding_model
-from mlx_vlm.utils import load_audio, load_config, load_processor
+from mlx_vlm.utils import get_model_path, load_audio, load_config, load_processor
from ..patches.modernbert_attention import patch_modernbert_attention
from ..utils.image import _decode_input_audio_data, load_image, validate_image_data_uri
+from ..utils.model_loading import (
+ ensure_model_code_trusted,
+ normalize_encoder_quantization_config,
+)
from .base_model import (
ENCODER_BATCH_TOKEN_BUDGET,
last_token_pool,
@@ -31,11 +35,6 @@
normalize_embeddings,
token_budget_batches,
)
-from .mlx_embeddings_compat import (
- patch_qwen3_vl_position_ids_recompute,
- patch_qwen3_vl_processor_for_torch_free_image_loading,
- patch_siglip_single_tower_forward,
-)
logger = logging.getLogger(__name__)
@@ -49,20 +48,46 @@
"n_positions",
)
-# Pooling modes whose result depends on the attention mask. CLS reads a fixed
-# position, so it is mask-independent.
-_MASK_AWARE_POOLING_MODES = ("mean", "lasttoken")
-# Context windows from the model cards. EmbeddingGemma 2's config.json only
-# declares the RoPE limit (262144).
-_MLX_VLM_EMBEDDING_CONTEXT = {"embedding_gemma2": 8192}
+
+
+@dataclass(frozen=True)
+class _ChatEmbeddingFamily:
+ """How an mlx-vlm multimodal embedding family formats its inputs."""
+
+ context_length: int
+ """Context window from the model card. config.json only declares RoPE."""
+
+ system_instruction: str | None = None
+ add_generation_prompt: bool = False
+ media_before_text: bool = False
+ template_text: bool = False
+ """Format text-only inputs with the chat template too."""
+
+
+_CHAT_EMBEDDING_FAMILIES = {
+ "embedding_gemma2": _ChatEmbeddingFamily(context_length=8192),
+ "qwen3_vl_embedding": _ChatEmbeddingFamily(
+ context_length=8192,
+ system_instruction="Represent the user's input.",
+ add_generation_prompt=True,
+ media_before_text=True,
+ template_text=True,
+ ),
+}
+
+# The stock Qwen3-VL embedding checkpoints keep the qwen3_vl model_type.
+_EMBEDDING_MODEL_TYPE_OVERRIDES = {"qwen3_vl": "qwen3_vl_embedding"}
+
+# SigLIP's text tower pools the last position, so inputs pad to the full length.
+_PAD_TO_MAX_LENGTH_MODEL_TYPES = frozenset({"siglip"})
@dataclass
class EmbeddingOutput:
"""Output from embedding generation."""
- embeddings: List[List[float]]
+ embeddings: list[list[float]]
"""List of embedding vectors, one per input text."""
total_tokens: int
@@ -76,10 +101,14 @@ class _ChatTemplateEmbeddingInputs:
"""Build text, image, and audio embedding inputs with an mlx-vlm processor."""
def __init__(
- self, processor, max_length: int, audio_max_seconds: Optional[float] = None
+ self,
+ processor,
+ family: _ChatEmbeddingFamily,
+ audio_max_seconds: float | None = None,
):
self._processor = processor
- self._max_length = max_length
+ self.family = family
+ self._max_length = family.context_length
feature_extractor = getattr(processor, "feature_extractor", None)
self._sampling_rate = getattr(feature_extractor, "sampling_rate", 16000)
# The feature extractor cuts audio at its call-time max_length default
@@ -91,25 +120,43 @@ def __init__(
)
def prepare_embedding_inputs(self, inputs, return_tensors: str = "mlx"):
+ family = self.family
conversations = []
for item in inputs:
- content = []
- if item.get("text"):
- content.append({"type": "text", "text": item["text"]})
+ text = (
+ [{"type": "text", "text": item["text"]}] if item.get("text") else []
+ )
+ media = []
if item.get("image"):
- content.append({"type": "image", "url": item["image"]})
+ media.append(
+ {"type": "image", "image": load_image(item["image"], field="image")}
+ )
if item.get("audio"):
# Decoded bytes from embed(); the processor takes the waveform
# as-is and only loads str/Path values itself.
waveform = load_audio(io.BytesIO(item["audio"]), sr=self._sampling_rate)
- content.append({"type": "audio", "audio": waveform})
- conversations.append([{"role": "user", "content": content}])
+ media.append({"type": "audio", "audio": waveform})
+ content = media + text if family.media_before_text else text + media
+ messages = [{"role": "user", "content": content}]
+ if family.system_instruction:
+ messages.insert(
+ 0,
+ {
+ "role": "system",
+ "content": [
+ {"type": "text", "text": family.system_instruction}
+ ],
+ },
+ )
+ conversations.append(messages)
has_audio = any(item.get("audio") for item in inputs)
batch = self._processor.apply_chat_template(
conversations,
tokenize=True,
return_dict=True,
return_tensors=return_tensors,
+ padding=True,
+ add_generation_prompt=family.add_generation_prompt,
**(
{"audio_kwargs": self._audio_kwargs}
if has_audio and self._audio_kwargs
@@ -126,57 +173,15 @@ def prepare_embedding_inputs(self, inputs, return_tensors: str = "mlx"):
return batch
-class _SiglipEmbeddingInputs:
- """Build SigLIP text or image inputs. Each item goes to one tower."""
-
- def __init__(self, processor, text_length: int):
- self.tokenizer = processor.tokenizer
- self._image_processor = processor.image_processor
- self._text_length = text_length
-
- def split_by_modality(self, items: list[dict[str, Any]]) -> list[list[int]]:
- if any(item.get("text") and "image" in item for item in items):
- raise ValueError(
- "SigLIP embeds text and images separately; send each as its own item"
- )
- image_rows = [i for i, item in enumerate(items) if "image" in item]
- text_rows = [i for i, item in enumerate(items) if "image" not in item]
- return [rows for rows in (text_rows, image_rows) if rows]
-
- def prepare_embedding_inputs(self, inputs, return_tensors: str = "mlx"):
- if "image" in inputs[0]:
- images = [
- load_image(item["image"], field="items[].image") for item in inputs
- ]
- pixel_values = self._image_processor(images=images, return_tensors="np")[
- "pixel_values"
- ]
- return {"pixel_values": mx.array(pixel_values)}
- # The text tower pools the last position, so pad to the full length.
- return self.tokenizer(
- [item.get("text", "") for item in inputs],
- padding="max_length",
- truncation=True,
- max_length=self._text_length,
- return_attention_mask=True,
- return_tensors=return_tensors,
- )
-
-
class MLXEmbeddingModel:
"""
- Wrapper around mlx-embeddings for generating text embeddings.
-
- This class provides a unified interface for loading and running
- embedding models using Apple's MLX framework.
+ Unified interface for embedding models on Apple's MLX framework.
Supports:
- - Native XLMRoBERTa embedding (no mlx-embeddings dependency)
- - Native BERT embedding (no mlx-embeddings dependency)
+ - Native XLMRoBERTa and BERT embedding
- Native Qwen2-decoder embedding (last-token + L2; jina-code, gte-Qwen2)
- — mlx-embeddings has no qwen2 module
- - mlx-vlm for EmbeddingGemma 2 (text, image, and audio inputs)
- - mlx-embeddings fallback for other architectures
+ - mlx-vlm for every other embedding family, including EmbeddingGemma 2
+ (text, image, and audio) and Qwen3-VL-Embedding (text and image)
Example:
>>> model = MLXEmbeddingModel("mlx-community/all-MiniLM-L6-v2-4bit")
@@ -189,7 +194,7 @@ def __init__(
model_name: str,
trust_remote_code: bool = False,
audio_enabled: bool = False,
- audio_max_seconds: Optional[float] = None,
+ audio_max_seconds: float | None = None,
):
"""
Initialize the MLX embedding model.
@@ -211,13 +216,14 @@ def __init__(
self.model = None
self.processor = None
self._loaded = False
- self._hidden_size: Optional[int] = None
+ self._hidden_size: int | None = None
self._using_native = False
self._is_compiled = False
self._compiled_embed = None
- self._remap_input_ids_to_inputs = False
- self._pooling_mode: Optional[str] = None
+ self._pad_to_max_length = False
+ self._pooling_mode: str | None = None
self._pooling_source: str = "not resolved"
+ self._pooling_config: dict[str, Any] | None = None
self._media_processor = None
self._supports_audio = False
@@ -271,7 +277,7 @@ def _promote_bf16_to_fp16(self, module: Any) -> None:
("bge-m3", "cls"),
)
- def _pooling_config_path(self, model_path: Path) -> Optional[Path]:
+ def _pooling_config_path(self, model_path: Path) -> Path | None:
"""Locate the Pooling module through ``modules.json``.
sentence-transformers describes its pipeline there; the Pooling module
@@ -298,7 +304,7 @@ def _pooling_config_path(self, model_path: Path) -> Optional[Path]:
return conventional if conventional.is_file() else None
@staticmethod
- def _pooling_mode_from_config(cfg: Dict[str, Any]) -> Optional[str]:
+ def _pooling_mode_from_config(cfg: dict[str, Any]) -> str | None:
"""Read either config dialect.
Recent sentence-transformers releases write a single
@@ -311,6 +317,7 @@ def _pooling_mode_from_config(cfg: Dict[str, Any]) -> Optional[str]:
alias = {
"cls": "cls",
"mean": "mean",
+ "max": "max",
"lasttoken": "lasttoken",
"last_token": "lasttoken",
}
@@ -319,6 +326,7 @@ def _pooling_mode_from_config(cfg: Dict[str, Any]) -> Optional[str]:
return mode
for key, mode in (
("pooling_mode_cls_token", "cls"),
+ ("pooling_mode_max_tokens", "max"),
("pooling_mode_lasttoken", "lasttoken"),
("pooling_mode_mean_tokens", "mean"),
):
@@ -326,7 +334,9 @@ def _pooling_mode_from_config(cfg: Dict[str, Any]) -> Optional[str]:
return mode
return None
- def _resolve_pooling_mode(self) -> Tuple[Optional[str], str]:
+ def _resolve_pooling_mode(
+ self, model_path: Path | None = None
+ ) -> tuple[str | None, str]:
"""Resolve the pooling mode and report where it came from.
Returns ``(mode, source)``. ``source`` is logged at load time so an
@@ -334,15 +344,20 @@ def _resolve_pooling_mode(self) -> Tuple[Optional[str], str]:
the code -- silent pooling changes are exactly what makes retrieval
quality drift unnoticed.
"""
- model_path = Path(self.model_name)
+ if model_path is None:
+ model_path = Path(self.model_name)
+ self._pooling_config = None
cfg_path = self._pooling_config_path(model_path)
if cfg_path is not None:
try:
with open(cfg_path) as fh:
cfg = json.load(fh)
- mode = self._pooling_mode_from_config(cfg)
- if mode:
- return mode, str(cfg_path.relative_to(model_path))
+ if isinstance(cfg, dict):
+ self._pooling_config = cfg
+ mode = self._pooling_mode_from_config(cfg)
+ if mode:
+ return mode, str(cfg_path.relative_to(model_path))
+ return None, str(cfg_path.relative_to(model_path))
except (OSError, ValueError) as e:
logger.debug(f"Could not read pooling config for {self.model_name}: {e}")
@@ -361,9 +376,11 @@ def _resolve_pooling_mode(self) -> Tuple[Optional[str], str]:
def _load_native(self) -> bool:
"""
- Try to load using native omlx implementations (xlm_roberta, bert).
+ Try to load using the native omlx Qwen2-decoder implementation.
- Returns True if native loading succeeded, False otherwise.
+ Returns True if native loading succeeded, False otherwise. Encoder
+ families such as XLM-RoBERTa/BERT are served by mlx-vlm's own MIT
+ implementations, so they are intentionally absent from this table.
"""
from transformers import AutoTokenizer
@@ -376,7 +393,7 @@ def _load_native(self) -> bool:
try:
with open(config_path) as f:
config_dict = json.load(f)
- except (json.JSONDecodeError, IOError):
+ except (json.JSONDecodeError, OSError):
logger.debug("Failed to read config.json, native loading skipped")
return False
@@ -384,16 +401,13 @@ def _load_native(self) -> bool:
arch = architectures[0] if architectures else ""
native_arch_modules = {
- "XLMRobertaModel": "xlm_roberta",
- "BertModel": "xlm_roberta",
- "BertForMaskedLM": "xlm_roberta",
"Qwen2ForCausalLM": "qwen2_embedding",
}
module_name = native_arch_modules.get(arch)
if module_name is None:
logger.debug(
f"Architecture '{arch}' not natively supported for embedding, "
- "trying mlx-embeddings"
+ "trying mlx-vlm"
)
return False
@@ -401,17 +415,17 @@ def _load_native(self) -> bool:
from importlib import import_module
native_module = import_module(f"{__package__}.{module_name}")
- Model = native_module.Model
- ModelArgs = native_module.ModelArgs
+ model_cls = native_module.Model
+ model_args_cls = native_module.ModelArgs
- known_fields = {f.name for f in ModelArgs.__dataclass_fields__.values()}
- model_config = {
- k: v for k, v in config_dict.items() if k in known_fields
+ known_fields = {
+ f.name for f in model_args_cls.__dataclass_fields__.values()
}
+ model_config = {k: v for k, v in config_dict.items() if k in known_fields}
model_config["architectures"] = architectures
- config = ModelArgs(**model_config)
- model_instance = Model(config)
+ config = model_args_cls(**model_config)
+ model_instance = model_cls(config)
weights = {}
weight_files = list(model_path.glob("*.safetensors"))
@@ -453,7 +467,8 @@ def _load_native(self) -> bool:
self._compiled_embed = None
logger.info(
f"Embedding model loaded natively: {self.model_name} "
- f"(arch={arch}, hidden_size={config.hidden_size})"
+ f"(arch={arch}, hidden_size={config.hidden_size}, "
+ f"pooling={self._pooling_mode}, source={self._pooling_source})"
)
return True
@@ -461,118 +476,117 @@ def _load_native(self) -> bool:
logger.debug(f"Native loading failed for {self.model_name}: {e}")
return False
- def _load_mlx_vlm(self) -> bool:
- """Load mlx-vlm-only model types. Errors propagate: no other loader fits."""
- model_path = Path(self.model_name)
- try:
- with open(model_path / "config.json") as fh:
- model_type = json.load(fh).get("model_type")
- except (OSError, ValueError):
- return False
- context_length = _MLX_VLM_EMBEDDING_CONTEXT.get(model_type)
- if context_length is None:
- return False
-
- logger.info(f"Loading embedding model via mlx-vlm: {self.model_name}")
+ def _load_mlx_vlm(self) -> None:
+ """Load any embedding family mlx-vlm implements."""
+ model_path = get_model_path(self.model_name)
+ self._pooling_mode, self._pooling_source = self._resolve_pooling_mode(model_path)
config = load_config(model_path)
+ ensure_model_code_trusted(
+ config,
+ model_path=model_path,
+ trust_remote_code=self.trust_remote_code,
+ )
+ # Checkpoints may spell model types with hyphens (gemma3-text), but
+ # mlx-vlm resolves model modules by underscore names.
+ model_type = str(config.get("model_type", "")).lower().replace("-", "_")
+ model_type = _EMBEDDING_MODEL_TYPE_OVERRIDES.get(model_type, model_type)
+ config["model_type"] = model_type
# The audio tower is resident even for text-only requests, so it loads
# only when the model's embedding_audio_enabled setting asks for it.
+ # mlx-vlm defaults a missing audio_config to {}, which builds the tower.
if not self.audio_enabled:
config["audio_config"] = None
+ normalize_encoder_quantization_config(config)
+ logger.info(f"Loading embedding model via mlx-vlm: {self.model_name}")
model = load_embedding_model(model_path, config=config)
- processor = load_processor(model_path, add_detokenizer=False)
- model.max_input_length = context_length
+ if self._pooling_config is not None:
+ pooling_config = dict(self._pooling_config)
+ # mlx-vlm matches string modes exactly, while omlx accepts aliases.
+ if isinstance(pooling_config.get("pooling_mode"), str) and self._pooling_mode:
+ pooling_config["pooling_mode"] = self._pooling_mode
+ model.pooling_config = pooling_config
+ elif self._pooling_mode:
+ model.pooling_config = {"pooling_mode": self._pooling_mode}
+ patch_modernbert_attention(model)
+ self._promote_bf16_to_fp16(model)
+ processor = load_processor(
+ model_path,
+ add_detokenizer=False,
+ trust_remote_code=self.trust_remote_code,
+ )
self.model = model
- # Text requests use the tokenizer path. The processor's own __call__
- # takes images as its first positional argument.
- self.processor = processor.tokenizer
- self._media_processor = _ChatTemplateEmbeddingInputs(
- processor, context_length, self.audio_max_seconds
- )
+ # Text requests use the tokenizer path. Multimodal processors take
+ # images as their first positional argument.
+ self.processor = getattr(processor, "tokenizer", processor)
+ family = _CHAT_EMBEDDING_FAMILIES.get(model_type)
+ if family is not None:
+ model.max_input_length = family.context_length
+ self._media_processor = _ChatTemplateEmbeddingInputs(
+ processor, family, self.audio_max_seconds
+ )
self._supports_audio = getattr(model, "audio_tower", None) is not None
- self._hidden_size = model.config.text_config.embedding_dim
+ # Encoder checkpoints keep every position inside their learned table
+ # (RoBERTa counts positions from pad_token_id + 1). Absolute position
+ # tables read out of range without an error, so cap the input length.
+ if not hasattr(model, "max_input_length"):
+ max_position_embeddings = getattr(
+ model.config, "max_position_embeddings", None
+ )
+ if isinstance(max_position_embeddings, int):
+ pad_token_id = getattr(model.config, "pad_token_id", None)
+ position_offset = (
+ pad_token_id + 1
+ if isinstance(pad_token_id, int) and model_type != "bert"
+ else 0
+ )
+ model.max_input_length = max_position_embeddings - position_offset
+ self._pad_to_max_length = model_type in _PAD_TO_MAX_LENGTH_MODEL_TYPES
+ if self._pad_to_max_length:
+ model.max_input_length = model.config.text_config.max_position_embeddings
+ self._hidden_size = self._embedding_dimension(model.config)
self._using_native = False
- self._detect_input_key_remapping()
self._is_compiled = self._try_compile()
self._loaded = True
logger.info(
f"Embedding model loaded via mlx-vlm: {self.model_name} "
f"(model_type={model_type}, dimensions={self._hidden_size}, "
- f"compiled={self._is_compiled})"
+ f"compiled={self._is_compiled}, pooling={self._pooling_mode}, "
+ f"source={self._pooling_source})"
)
- return True
+
+ @staticmethod
+ def _embedding_dimension(config: Any) -> int | None:
+ text_config = getattr(config, "text_config", None)
+ for source, attr in (
+ (text_config, "embedding_dim"),
+ (config, "embedding_dim"),
+ (config, "hidden_size"),
+ (text_config, "hidden_size"),
+ ):
+ value = getattr(source, attr, None)
+ if isinstance(value, int):
+ return value
+ return None
def load(self) -> None:
"""Load the model and processor/tokenizer."""
if self._loaded:
return
- # mlx-vlm embedding models pool inside their forward and return
- # float32 text_embeds, so the declared pooling mode is not applied.
- if self._load_mlx_vlm():
- return
-
self._pooling_mode, self._pooling_source = self._resolve_pooling_mode()
- if self._pooling_mode:
- logger.info(
- f"Embedding pooling for {self.model_name}: "
- f"{self._pooling_mode} (source: {self._pooling_source})"
- )
-
- # 1. Try native loading first (xlm_roberta, bert)
if self._load_native():
return
- # 2. Fallback to mlx-embeddings
try:
- patch_qwen3_vl_processor_for_torch_free_image_loading()
- patch_qwen3_vl_position_ids_recompute()
- patch_siglip_single_tower_forward()
- from mlx_embeddings import load
-
- logger.info(f"Loading embedding model via mlx-embeddings: {self.model_name}")
-
- self.model, self.processor = load(
- self.model_name,
- tokenizer_config={"trust_remote_code": self.trust_remote_code},
- )
- patch_modernbert_attention(self.model)
- self._promote_bf16_to_fp16(self.model)
-
- if hasattr(self.model, "config"):
- config = self.model.config
- self._hidden_size = getattr(config, "hidden_size", None)
- if self._hidden_size is None and hasattr(config, "text_config"):
- self._hidden_size = getattr(config.text_config, "hidden_size", None)
- # SiglipProcessor.__call__ takes images as its first positional
- # argument, so text and images get their own input builder.
- if getattr(config, "model_type", None) == "siglip":
- self.processor = _SiglipEmbeddingInputs(
- self.processor, config.text_config.max_position_embeddings
- )
-
- self._using_native = False
- self._detect_input_key_remapping()
- self._is_compiled = self._try_compile()
- self._loaded = True
- logger.info(
- f"Embedding model loaded successfully: {self.model_name} "
- f"(hidden_size={self._hidden_size}, compiled={self._is_compiled})"
- )
-
- except ImportError:
- raise ImportError(
- "mlx-embeddings is required for embedding generation. "
- "Install with: pip install mlx-embeddings"
- )
- except FileNotFoundError:
+ self._load_mlx_vlm()
+ except FileNotFoundError as exc:
raise FileNotFoundError(
f"No safetensors weight files found for '{self.model_name}'. "
f"Embedding models require weights in safetensors format. "
f"If this is a PyTorch model, use an MLX-converted version "
f"(e.g., from mlx-community on HuggingFace)."
- )
+ ) from exc
except Exception as e:
logger.error(f"Failed to load embedding model: {e}")
raise
@@ -589,8 +603,16 @@ def _extract_embeddings_array(self, outputs, attention_mask=None):
# ``mean(axis=1)`` averages pad tokens in, both of which corrupt vectors
# in mixed-length batches while single inputs still look fine. The
# result is L2-normalized like every other path out of this method.
+ # mlx-vlm models pool inside their forward from model.pooling_config,
+ # and some apply dense projections after pooling, so only native
+ # outputs are pooled here.
last_hidden = getattr(outputs, "last_hidden_state", None)
- if self._pooling_mode and last_hidden is not None and last_hidden.ndim == 3:
+ if (
+ self._using_native
+ and self._pooling_mode
+ and last_hidden is not None
+ and last_hidden.ndim == 3
+ ):
if self._pooling_mode == "cls":
return normalize_embeddings(last_hidden[:, 0, :])
if self._pooling_mode == "lasttoken":
@@ -626,9 +648,7 @@ def _extract_embeddings_array(self, outputs, attention_mask=None):
embeddings = mx.mean(embeddings, axis=1)
return embeddings
- def _validate_native_weights(
- self, model_instance, weights: Dict[str, Any]
- ) -> None:
+ def _validate_native_weights(self, model_instance, weights: dict[str, Any]) -> None:
"""Reject native checkpoints with missing or shape-incompatible core weights."""
expected_weights = dict(tree_flatten(model_instance.parameters()))
expected_weight_names = set(expected_weights.keys())
@@ -679,8 +699,8 @@ def _uses_custom_embedding_inputs(self, processor) -> bool:
def _normalize_embedding_inputs(
self,
- inputs: Union[str, Dict[str, str], List[str], List[Dict[str, str]]],
- ) -> List[Dict[str, str]]:
+ inputs: str | dict[str, str] | list[str] | list[dict[str, str]],
+ ) -> list[dict[str, str]]:
"""Normalize embedding inputs into item dicts."""
if not inputs:
return []
@@ -694,7 +714,7 @@ def _normalize_embedding_inputs(
return [dict(item) for item in inputs]
@staticmethod
- def _positive_context_length(value: Any) -> Optional[int]:
+ def _positive_context_length(value: Any) -> int | None:
"""Return a usable positive context length from config/tokenizer metadata."""
if isinstance(value, bool) or not isinstance(value, int):
return None
@@ -703,7 +723,7 @@ def _positive_context_length(value: Any) -> Optional[int]:
return None
@classmethod
- def _get_config_value(cls, config: Any, key: str) -> Optional[int]:
+ def _get_config_value(cls, config: Any, key: str) -> int | None:
if config is None:
return None
if isinstance(config, dict):
@@ -711,7 +731,7 @@ def _get_config_value(cls, config: Any, key: str) -> Optional[int]:
return cls._positive_context_length(getattr(config, key, None))
@classmethod
- def _context_length_from_config(cls, config: Any) -> Optional[int]:
+ def _context_length_from_config(cls, config: Any) -> int | None:
"""Read context length from model config objects or dictionaries."""
for key in _CONTEXT_LENGTH_ATTRS:
value = cls._get_config_value(config, key)
@@ -775,7 +795,7 @@ def effective_max_length(self, max_length: int | None = None) -> int:
def _prepare_embedding_inputs(
self,
processor,
- inputs: Union[List[str], List[Dict[str, str]]],
+ inputs: list[str] | list[dict[str, str]],
max_length: int,
padding: bool,
truncation: bool,
@@ -783,10 +803,8 @@ def _prepare_embedding_inputs(
"""
Prepare inputs for embedding inference.
- Some embedding processors, such as qwen3_vl in mlx-embeddings, expose
- a higher-level embedding API instead of the tokenizer-style
- ``processor(texts, ...)`` path. Reuse that official extension point
- when available to avoid positional-argument mismatches.
+ Chat-template embedding families expose ``prepare_embedding_inputs``.
+ Everything else is a tokenizer.
"""
normalized_inputs = self._normalize_embedding_inputs(inputs)
@@ -804,88 +822,74 @@ def _prepare_embedding_inputs(
f"Embedding model '{self.model_name}' does not support image inputs"
)
- from mlx_embeddings.utils import prepare_inputs
-
- return prepare_inputs(
- processor,
- None,
+ encoded = processor(
[item.get("text", "") for item in normalized_inputs],
- max_length,
- padding,
- truncation,
- None,
+ padding="max_length" if self._pad_to_max_length else padding,
+ truncation=truncation,
+ max_length=max_length,
+ return_attention_mask=True,
+ return_tensors="np",
)
+ if self._pad_to_max_length:
+ encoded = self._pad_to_position_table(encoded, processor, truncation)
+ return {
+ key: mx.array(encoded[key])
+ for key in ("input_ids", "attention_mask", "token_type_ids")
+ if key in encoded
+ }
- def _eager_forward_with_mask(
- self,
- processor,
- normalized_inputs,
- input_texts,
- max_length: int,
- padding: bool,
- truncation: bool,
- ):
- """Eager forward for tokenizer-style processors, keeping the mask.
-
- ``mlx_embeddings.generate`` is ``prepare_inputs`` + ``model(**inputs)``
- and returns only the outputs, dropping the mask it just built. When the
- checkpoint declares a mask-aware pooling mode, run those same two steps
- here so the mask survives into pooling; the compiled path already has
- it. Without this, a right-padded batch pools a pad token whenever
- compile is off or has fallen back. Any preparation failure returns to
- ``generate()`` unchanged, so this can only add a mask, never remove a
- working path.
+ def _pad_to_position_table(
+ self, encoded, processor, truncation: bool
+ ) -> dict[str, np.ndarray]:
+ """Right-pad to the full position table after request truncation.
+
+ SigLIP pools the last position and ignores the attention mask, so its
+ embedding is only correct when padded to the length it was trained on.
"""
- if self._pooling_mode in _MASK_AWARE_POOLING_MODES:
- inputs = None
- try:
- prepared = self._prepare_embedding_inputs(
- processor, normalized_inputs, max_length, padding, truncation
- )
- inputs = dict(prepared)
- except Exception as e:
- # Only input preparation is guarded: a forward error must
- # surface as it does on every other path, not silently rerun.
- logger.warning(
- "masked eager forward unavailable for %s (%s); falling back "
- "to generate() without a mask",
- self.model_name,
- e,
+ target = self.model.max_input_length
+ pad_values = {
+ "input_ids": getattr(processor, "pad_token_id", None) or 0,
+ "attention_mask": 0,
+ "token_type_ids": 0,
+ }
+ padded = {}
+ for key, values in encoded.items():
+ values = np.asarray(values)
+ extra = target - values.shape[-1]
+ if extra < 0:
+ if not truncation:
+ raise ValueError(
+ f"SigLIP input length {values.shape[-1]} exceeds its "
+ f"position table limit of {target} with truncation disabled"
+ )
+ values = values[:, :target]
+ extra = 0
+ if key in pad_values and extra > 0:
+ values = np.pad(
+ values, ((0, 0), (0, extra)), constant_values=pad_values[key]
)
- if inputs is not None:
- outputs = self.model(**self._adapt_model_inputs_for_call(inputs))
- return outputs, inputs.get("attention_mask")
+ padded[key] = values
+ return padded
- from mlx_embeddings import generate
-
- outputs = generate(
- self.model,
- processor,
- input_texts,
- max_length=max_length,
- padding=padding,
- truncation=truncation,
- )
- return outputs, None
+ def _forward(self, inputs: dict[str, Any]):
+ """Run the mlx-vlm model on prepared inputs.
- def _detect_input_key_remapping(self) -> None:
- """Check if the model accepts `inputs` instead of `input_ids` and cache the result."""
+ Qwen3-VL caches rope position ids on the language model and reuses them
+ for any shorter input. Each embedding batch has its own mask, so the
+ cache is cleared on both sides of the call; clearing afterwards also
+ keeps a compile trace from leaving a tracer behind.
+ """
+ language_model = getattr(self.model, "language_model", None)
+ resets_rope = hasattr(language_model, "_position_ids")
+ if resets_rope:
+ language_model._position_ids = None
+ language_model._rope_deltas = None
try:
- params = inspect.signature(self.model.__call__).parameters
- self._remap_input_ids_to_inputs = (
- "input_ids" not in params and "inputs" in params
- )
- except (TypeError, ValueError):
- self._remap_input_ids_to_inputs = False
-
- def _adapt_model_inputs_for_call(
- self, model_inputs: Dict[str, Any]
- ) -> Dict[str, Any]:
- """Rename prepared inputs to match the embedding model call signature."""
- adapted_inputs = dict(model_inputs)
- if self._remap_input_ids_to_inputs and "input_ids" in adapted_inputs:
- adapted_inputs["inputs"] = adapted_inputs.pop("input_ids")
- return adapted_inputs
+ return self.model(**inputs)
+ finally:
+ if resets_rope:
+ language_model._position_ids = None
+ language_model._rope_deltas = None
def _try_compile(self) -> bool:
"""
@@ -896,11 +900,10 @@ def _try_compile(self) -> bool:
for some embedding/reranker models, causing eval() runtime errors.
- We compile a narrower function that returns only the final embedding array.
"""
- base_model = self.model
-
try:
+
def _compiled_embed(inputs):
- outputs = base_model(**self._adapt_model_inputs_for_call(inputs))
+ outputs = self._forward(inputs)
# The mask travels with the request; mask-aware pooling needs it.
return self._extract_embeddings_array(
outputs, inputs.get("attention_mask")
@@ -939,8 +942,7 @@ def close(self) -> None:
return
logger.info(
- "Releasing embedding model resources: %s "
- "(compiled=%s, native=%s)",
+ "Releasing embedding model resources: %s " "(compiled=%s, native=%s)",
self.model_name,
self._is_compiled,
self._using_native,
@@ -956,7 +958,7 @@ def close(self) -> None:
self._hidden_size = None
self._loaded = False
self._using_native = False
- self._remap_input_ids_to_inputs = False
+ self._pad_to_max_length = False
gc.collect()
mx.synchronize()
@@ -965,7 +967,7 @@ def close(self) -> None:
def embed(
self,
- inputs: Union[str, List[str], List[Dict[str, str]]],
+ inputs: str | list[str] | list[dict[str, str]],
max_length: int | None = None,
padding: bool = True,
truncation: bool = True,
@@ -1016,28 +1018,22 @@ def embed(
)
processor = self.processor
- if (has_image_inputs or has_audio_inputs) and self._media_processor is not None:
- processor = self._media_processor
- uses_custom_embedding_inputs = self._uses_custom_embedding_inputs(processor)
- # Unwrap only mlx-embeddings' TokenizerWrapper. transformers tokenizers
- # also have a Rust _tokenizer whose encode() applies tokenizer.json
- # padding and truncation instead of this request's settings.
- if (
- type(processor).__name__ == "TokenizerWrapper"
- and hasattr(processor, "_tokenizer")
- and not uses_custom_embedding_inputs
+ media_processor = self._media_processor
+ if media_processor is not None and (
+ has_image_inputs or has_audio_inputs or media_processor.family.template_text
):
- processor = processor._tokenizer
+ processor = media_processor
+ uses_custom_embedding_inputs = self._uses_custom_embedding_inputs(processor)
- if has_image_inputs and (self._using_native or not uses_custom_embedding_inputs):
+ if has_image_inputs and (
+ self._using_native or not uses_custom_embedding_inputs
+ ):
raise ValueError(
f"Embedding model '{self.model_name}' does not support image inputs"
)
batches = [list(range(len(normalized_inputs)))]
- if isinstance(processor, _SiglipEmbeddingInputs):
- batches = processor.split_by_modality(normalized_inputs)
- elif (
+ if (
not uses_custom_embedding_inputs
and 1 < len(input_texts) == len(normalized_inputs)
and len(input_texts) * max_length > ENCODER_BATCH_TOKEN_BUDGET
@@ -1109,7 +1105,7 @@ def _embed_batch(
input_texts = [item["text"] for item in normalized_inputs if "text" in item]
if self._using_native:
- if hasattr(processor, "__call__"):
+ if callable(processor):
encoded = processor(
input_texts,
padding=padding,
@@ -1167,45 +1163,33 @@ def _embed_batch(
except Exception as e:
logger.warning(
f"compiled embedding path failed for {self.model_name}: {e}; "
- "disabling compile and falling back to eager generate()"
+ "disabling compile and falling back to eager forward()"
)
self._is_compiled = False
self._compiled_embed = None
total_tokens = None
if embeddings_array is None:
- # Both eager paths must carry the prepared mask the compiled
- # path passes: pooling is only correct with it.
- eager_mask = None
- if uses_custom_embedding_inputs:
- inputs = self._prepare_embedding_inputs(
- processor,
- normalized_inputs,
- max_length,
- padding,
- truncation,
- )
- if not isinstance(inputs, dict):
- inputs = dict(inputs)
- outputs = self.model(**self._adapt_model_inputs_for_call(inputs))
- total_tokens = self._count_prepared_tokens(inputs)
- eager_mask = inputs.get("attention_mask")
- else:
- outputs, eager_mask = self._eager_forward_with_mask(
+ inputs = dict(
+ self._prepare_embedding_inputs(
processor,
normalized_inputs,
- input_texts,
max_length,
padding,
truncation,
)
- embeddings_array = self._extract_embeddings_array(outputs, eager_mask)
+ )
+ outputs = self._forward(inputs)
+ total_tokens = self._count_prepared_tokens(inputs)
+ embeddings_array = self._extract_embeddings_array(
+ outputs, inputs.get("attention_mask")
+ )
return embeddings_array, total_tokens
def _count_tokens(
self,
- inputs: Union[List[str], List[Dict[str, str]]],
+ inputs: list[str] | list[dict[str, str]],
max_length: int,
truncation: bool,
) -> int:
@@ -1239,7 +1223,7 @@ def _count_tokens(
return total
- def _count_prepared_tokens(self, prepared_inputs: Dict[str, Any]) -> int:
+ def _count_prepared_tokens(self, prepared_inputs: dict[str, Any]) -> int:
"""Count tokens from prepared model inputs, including multimodal tokens."""
attention_mask = prepared_inputs.get("attention_mask")
if attention_mask is not None:
@@ -1248,7 +1232,12 @@ def _count_prepared_tokens(self, prepared_inputs: Dict[str, Any]) -> int:
except (TypeError, ValueError):
pass
if isinstance(attention_mask, list):
- return int(sum(sum(row) if isinstance(row, list) else row for row in attention_mask))
+ return int(
+ sum(
+ sum(row) if isinstance(row, list) else row
+ for row in attention_mask
+ )
+ )
if hasattr(attention_mask, "tolist"):
values = attention_mask.tolist()
if values and isinstance(values[0], list):
@@ -1271,7 +1260,7 @@ def _count_prepared_tokens(self, prepared_inputs: Dict[str, Any]) -> int:
return 0
@property
- def hidden_size(self) -> Optional[int]:
+ def hidden_size(self) -> int | None:
"""Get the embedding dimension."""
return self._hidden_size
@@ -1304,7 +1293,7 @@ def get_model_info(self) -> dict:
def __repr__(self) -> str:
status = "loaded" if self._loaded else "not loaded"
- impl = "native" if self._using_native else "mlx-embeddings"
+ impl = "native" if self._using_native else "mlx-vlm"
return (
f""
diff --git a/omlx/models/mlx_embeddings_compat.py b/omlx/models/mlx_embeddings_compat.py
deleted file mode 100644
index cf4723b314..0000000000
--- a/omlx/models/mlx_embeddings_compat.py
+++ /dev/null
@@ -1,207 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-"""Compatibility patches for mlx-embeddings."""
-
-import functools
-import logging
-from typing import Any
-
-from ..utils.image import load_image
-
-logger = logging.getLogger(__name__)
-
-_QWEN3_VL_PROCESSOR_PATCHED = False
-
-_QWEN3_VL_POSIDS_PATCHED = False
-
-_SIGLIP_SINGLE_TOWER_PATCHED = False
-
-
-def _flatten_images(images: Any) -> list[Any]:
- """Flatten the per-sample nested image batch transformers hands to processors.
-
- Text-only items contribute empty slots, which must be dropped rather than
- forwarded as zero-length arrays.
- """
- if isinstance(images, (list, tuple)):
- flat: list[Any] = []
- for item in images:
- flat.extend(_flatten_images(item))
- return flat
- return [] if images is None else [images]
-
-
-def _build_contract_compliant_processor(base_cls):
- """Restore the transformers image-processor contract on mlx-vlm's torch-free port.
-
- transformers delegates image loading to ``image_processor.fetch_images`` and
- passes visuals nested per sample. The upstream port overrides ``fetch_images``
- with a non-recursive, file-path-only version, so a data URI reaches
- ``_process_one`` as a numpy string array and a nested batch as a 4-D array,
- both of which fail the ``C, H, W = image.shape`` unpack.
- """
-
- class ContractCompliantImageProcessor(base_cls):
- def fetch_images(self, image_url_or_urls):
- if isinstance(image_url_or_urls, (list, tuple)):
- return [self.fetch_images(item) for item in image_url_or_urls]
- if isinstance(image_url_or_urls, str):
- return load_image(image_url_or_urls, field="image")
- return image_url_or_urls
-
- def __call__(self, images, **kwargs):
- return super().__call__(_flatten_images(images), **kwargs)
-
- return ContractCompliantImageProcessor
-
-
-def _ensure_qwen3_vl_mm_token_ids(processor):
- """Mirror ProcessorMixin multimodal token id fields for manually built processors."""
- defaults = {
- "image_ids": [getattr(processor, "image_token_id", None)],
- "video_ids": [getattr(processor, "video_token_id", None)],
- "audio_ids": [getattr(processor, "audio_token_id", None)],
- }
- for attr_name, value in defaults.items():
- if not hasattr(processor, attr_name):
- setattr(processor, attr_name, value)
- return processor
-
-
-def patch_qwen3_vl_processor_for_torch_free_image_loading() -> None:
- """Keep mlx-embeddings Qwen3-VL loading off HF AutoImageProcessor."""
- global _QWEN3_VL_PROCESSOR_PATCHED
- if _QWEN3_VL_PROCESSOR_PATCHED:
- return
-
- try:
- from mlx_embeddings.models.qwen3_vl import processor as qwen3_vl_processor
- from mlx_vlm.models.qwen3_vl.processing_qwen3_vl import (
- Qwen3VLImageProcessor,
- _qwen_vl_image_kwargs,
- )
- except Exception as exc:
- logger.debug("Qwen3-VL mlx-embeddings compatibility patch skipped: %s", exc)
- _QWEN3_VL_PROCESSOR_PATCHED = True
- return
-
- original_auto_image_processor = getattr(
- qwen3_vl_processor, "AutoImageProcessor", None
- )
- image_processor_cls = _build_contract_compliant_processor(Qwen3VLImageProcessor)
-
- class TorchFreeQwen3VLAutoImageProcessor:
- _omlx_original_auto_image_processor = original_auto_image_processor
-
- @classmethod
- def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
- del cls, kwargs
- image_kwargs = _qwen_vl_image_kwargs(
- pretrained_model_name_or_path,
- default_patch_size=16,
- )
- return image_processor_cls(**image_kwargs)
-
- qwen3_vl_processor.AutoImageProcessor = TorchFreeQwen3VLAutoImageProcessor
-
- processor_cls = getattr(qwen3_vl_processor, "Processor", None)
- original_build_processor = getattr(processor_cls, "_build_processor", None)
- if (
- processor_cls is not None
- and original_build_processor is not None
- and not getattr(original_build_processor, "_omlx_patched", False)
- ):
-
- def build_processor_with_mm_token_ids(tokenizer, image_processor):
- processor = original_build_processor(tokenizer, image_processor)
- return _ensure_qwen3_vl_mm_token_ids(processor)
-
- build_processor_with_mm_token_ids._omlx_patched = True
- processor_cls._build_processor = staticmethod(build_processor_with_mm_token_ids)
-
- _QWEN3_VL_PROCESSOR_PATCHED = True
- logger.debug("Applied torch-free image loader patch for mlx-embeddings Qwen3-VL")
-
-
-def patch_qwen3_vl_position_ids_recompute() -> None:
- """Drop the mlx-embeddings Qwen3-VL position-id cache before each forward.
-
- mlx-embeddings caches position ids on the language model and re-slices
- them for later requests with ``_position_ids[:, :, :seq_len]``. mlx-vlm's
- ``get_rope_index`` now returns 2-D text position ids, so a cached value
- can be 2-D and the 3-D re-slice fails with "Too many indices for array
- with 2 dimensions" (jundot/omlx#3731). A cache that survives across
- single-shot embedding requests also carries stale shapes and is mutated
- inside ``mx.compile`` traces, which leaves a captured tracer behind for
- the next compiled call. Recompute position ids from each request's
- inputs instead of reusing the cache.
- """
- global _QWEN3_VL_POSIDS_PATCHED
- if _QWEN3_VL_POSIDS_PATCHED:
- return
-
- try:
- from mlx_embeddings.models.qwen3_vl import model as qwen3_vl_model
- except Exception as exc:
- logger.debug("Qwen3-VL position-ids recompute patch skipped: %s", exc)
- _QWEN3_VL_POSIDS_PATCHED = True
- return
-
- original = getattr(qwen3_vl_model, "compute_qwen3_vl_hidden_states", None)
- if original is None or getattr(original, "_omlx_patched", False):
- _QWEN3_VL_POSIDS_PATCHED = True
- return
-
- @functools.wraps(original)
- def compute_recomputing_position_ids(*args, **kwargs):
- model = kwargs.get("model", args[0] if args else None)
- language_model = getattr(model, "language_model", None)
- if language_model is not None:
- language_model._position_ids = None
- return original(*args, **kwargs)
-
- compute_recomputing_position_ids._omlx_patched = True
- qwen3_vl_model.compute_qwen3_vl_hidden_states = compute_recomputing_position_ids
- _QWEN3_VL_POSIDS_PATCHED = True
- logger.debug("Applied position-ids recompute patch for mlx-embeddings Qwen3-VL")
-
-
-def patch_siglip_single_tower_forward() -> None:
- """Let the mlx-embeddings SigLIP forward embed text or images alone.
-
- Upstream ``Model.__call__`` always runs both towers, so a call without
- ``pixel_values`` or ``input_ids`` fails on ``None.shape``. A one-modality
- call runs only its tower and is L2-normalized like the two-tower output.
- The text tower runs unmasked: SigLIP pads to ``max_length`` and pools the
- last position, and its reference tokenizers emit no attention mask.
- """
- global _SIGLIP_SINGLE_TOWER_PATCHED
- if _SIGLIP_SINGLE_TOWER_PATCHED:
- return
-
- try:
- from mlx_embeddings.models import siglip
- from mlx_embeddings.models.base import ViTModelOutput, normalize_embeddings
- except Exception as exc:
- logger.debug("SigLIP single-tower patch skipped: %s", exc)
- _SIGLIP_SINGLE_TOWER_PATCHED = True
- return
-
- original = siglip.Model.__call__
- if getattr(original, "_omlx_patched", False):
- _SIGLIP_SINGLE_TOWER_PATCHED = True
- return
-
- @functools.wraps(original)
- def call_single_tower(self, input_ids=None, pixel_values=None, **kwargs):
- if pixel_values is None and input_ids is not None:
- text_embeds = self.get_text_features(input_ids=input_ids)
- return ViTModelOutput(text_embeds=normalize_embeddings(text_embeds))
- if input_ids is None and pixel_values is not None:
- image_embeds = self.get_image_features(pixel_values=pixel_values)
- return ViTModelOutput(image_embeds=normalize_embeddings(image_embeds))
- return original(self, input_ids=input_ids, pixel_values=pixel_values, **kwargs)
-
- call_single_tower._omlx_patched = True
- siglip.Model.__call__ = call_single_tower
- _SIGLIP_SINGLE_TOWER_PATCHED = True
- logger.debug("Applied single-tower forward patch for mlx-embeddings SigLIP")
diff --git a/omlx/models/qwen2_embedding.py b/omlx/models/qwen2_embedding.py
index 218ea337ef..d0aa2a9707 100644
--- a/omlx/models/qwen2_embedding.py
+++ b/omlx/models/qwen2_embedding.py
@@ -4,9 +4,8 @@
Serves Qwen2-decoder embedding models (``architectures=["Qwen2ForCausalLM"]``,
``model_type="qwen2"``) such as ``jinaai/jina-code-embeddings-1.5b`` (causal)
-and ``Alibaba-NLP/gte-Qwen2-1.5B-instruct`` (bidirectional), without depending
-on mlx-embeddings, which has no ``qwen2`` module and raises
-``ValueError("Model type qwen2 not supported.")`` for these checkpoints.
+and ``Alibaba-NLP/gte-Qwen2-1.5B-instruct`` (bidirectional). mlx-vlm's
+embedding loader has no ``qwen2`` remapping for these checkpoints.
These models pool the *last* (mask-aware) token of the final hidden state and
L2-normalize, matching their SentenceTransformers configs
diff --git a/omlx/models/reranker.py b/omlx/models/reranker.py
index eb4385d0c9..9404d7a4fe 100644
--- a/omlx/models/reranker.py
+++ b/omlx/models/reranker.py
@@ -6,9 +6,10 @@
and CausalLM-based reranker models on Apple's MLX framework.
Supports:
-- ModernBertForSequenceClassification (via mlx-embeddings)
-- XLMRobertaForSequenceClassification (omlx native implementation)
+- ModernBertForSequenceClassification (via mlx-vlm)
+- XLMRobertaForSequenceClassification (via mlx-vlm)
- CausalLM-based rerankers (e.g., Qwen3-Reranker) via yes/no logit scoring
+- Qwen3-VL-Reranker (via mlx-vlm)
"""
import gc
@@ -17,9 +18,13 @@
import math
from dataclasses import dataclass
from pathlib import Path
-from typing import Any, Dict, Tuple
+from typing import Any, Tuple
import mlx.core as mx
+from mlx_vlm.encoder_loader import load_encoder_model
+from mlx_vlm.reranker_loader import SEQUENCE_CLASSIFIER_MODEL_REMAPPING, load_reranker
+from mlx_vlm.server.reranking import RerankItem, ensure_chat_template, score_documents
+from mlx_vlm.utils import get_model_path, load_config, load_processor
from ..model_discovery import (
_TOKENIZER_MAX_LENGTH_SENTINEL,
@@ -31,15 +36,33 @@
from ..patches.modernbert_attention import patch_modernbert_attention
from ..patches.qwen3_sliding_window import apply_qwen3_sliding_window_patch
from ..utils.image import load_image
-from .base_model import ENCODER_BATCH_TOKEN_BUDGET, token_budget_batches
-from .mlx_embeddings_compat import (
- patch_qwen3_vl_position_ids_recompute,
- patch_qwen3_vl_processor_for_torch_free_image_loading,
+from ..utils.model_loading import (
+ ensure_model_code_trusted,
+ normalize_encoder_quantization_config,
)
+from .base_model import ENCODER_BATCH_TOKEN_BUDGET, token_budget_batches
logger = logging.getLogger(__name__)
+def _classifier_scores(outputs: Any, is_regression: bool = False) -> mx.array:
+ """Return classifier scores, preserving raw logits for regression heads."""
+ pooled = getattr(outputs, "pooler_output", None)
+ if pooled is not None:
+ return pooled
+ logits = getattr(outputs, "logits", None)
+ if logits is not None:
+ if is_regression:
+ return logits
+ if logits.shape[-1] > 1:
+ return mx.softmax(logits, axis=-1)
+ return mx.sigmoid(logits)
+ raise ValueError(
+ "Model output contains neither pooler_output nor logits. "
+ "Ensure the model is a SequenceClassification model."
+ )
+
+
def _coerce_item_to_text(item: Any) -> str:
"""Reduce a rerank input (str or dict with 'text') to plain text.
@@ -74,8 +97,8 @@ class MLXRerankerModel:
Supports two reranking paradigms:
1. SequenceClassification models (encoder-based):
- - ModernBertForSequenceClassification (via mlx-embeddings)
- - XLMRobertaForSequenceClassification (omlx native implementation)
+ - ModernBertForSequenceClassification (via mlx-vlm)
+ - XLMRobertaForSequenceClassification (via mlx-vlm)
2. CausalLM-based rerankers (decoder-based):
- Qwen3-Reranker and similar models that use yes/no logit scoring
@@ -114,9 +137,11 @@ def __init__(self, model_name: str, trust_remote_code: bool = False):
self.processor = None
self._loaded = False
self._num_labels: int | None = None
+ self._is_regression = False
self._is_causal_lm = False
self._is_jina_reranker = False
self._is_vl_reranker = False
+ self._vl_config: dict[str, Any] | None = None
self._token_true_id: int | None = None
self._token_false_id: int | None = None
self._doc_embed_token_id: int | None = None
@@ -184,132 +209,47 @@ def _detect_jina_v35(self) -> bool:
return True
- def _load_xlm_roberta(self) -> Tuple[Any, Any]:
- """Load XLMRoberta model using omlx native implementation."""
- import mlx.core as mx
- from mlx.utils import tree_unflatten
- from transformers import AutoTokenizer
-
- from .xlm_roberta import Model, ModelArgs
+ def _build_vl_item(self, item: "str | dict[str, Any]") -> RerankItem:
+ """Normalize a rerank input into an mlx-vlm RerankItem.
- model_path = Path(self.model_name)
-
- # Load config
- with open(model_path / "config.json") as f:
- config_dict = json.load(f)
-
- config = ModelArgs(
- **{
- k: v
- for k, v in config_dict.items()
- if k in ModelArgs.__dataclass_fields__
- }
- )
-
- # Create model
- model = Model(config)
-
- # Load weights. Use mx.load (not safetensors.safe_open + get_tensor),
- # which reads safetensors directly into MLX arrays and supports the
- # bfloat16 dtype. safe_open(framework="mlx").get_tensor() routes bf16
- # through numpy, which has no bfloat16 dtype and raises
- # "TypeError: data type 'bfloat16' not understood".
- weights = {}
- weight_files = list(model_path.glob("*.safetensors"))
- for wf in weight_files:
- weights.update(mx.load(str(wf)))
-
- # Sanitize weights (remove "roberta." prefix, etc.)
- weights = model.sanitize(weights)
-
- # Load weights into model
- model.load_weights(list(weights.items()))
- mx.eval(model.parameters())
- # Reranker inference must be deterministic: disable dropout in the
- # native XLM-RoBERTa path just like the native embedding loader does.
- model.train(False)
-
- # Load tokenizer
- tokenizer = AutoTokenizer.from_pretrained(
- str(model_path), trust_remote_code=self.trust_remote_code
- )
-
- return model, tokenizer
-
- def _load_vl_reranker(self) -> Tuple[Any, Any]:
- """Load a multimodal reranker (e.g., Qwen3-VL-Reranker) via mlx-embeddings.
-
- mlx-embeddings exposes a unified `load()` + `model.process()` API that
- handles both embedding and reranking variants of Qwen3-VL. Reranker vs
- embedder is decided by the input dict shape at inference time.
- """
- patch_qwen3_vl_processor_for_torch_free_image_loading()
- patch_qwen3_vl_position_ids_recompute()
- from mlx_embeddings import load as mlx_emb_load
-
- return mlx_emb_load(
- str(self.model_name),
- tokenizer_config={"trust_remote_code": self.trust_remote_code},
- )
-
- def _build_vl_item(self, item: "str | dict[str, Any]") -> Dict[str, Any]:
- """Normalize a rerank input into the mlx-embeddings VL item format.
-
- Accepts either a bare string (text) or a dict with 'text' and/or
- 'image' keys. Request-facing image strings must be base64 data URIs and
- get loaded via omlx's shared image loader.
+ Request-facing image strings must be base64 data URIs. They are decoded
+ here so mlx-vlm never resolves a file path or URL from a request.
"""
if isinstance(item, str):
- return {"text": item}
+ return RerankItem(text=item)
if not isinstance(item, dict):
- return {"text": str(item)}
+ return RerankItem(text=str(item))
- result: Dict[str, Any] = {}
- text = item.get("text")
- if text:
- result["text"] = text
+ text = item.get("text") or None
image_ref = item.get("image")
+ image = None
if image_ref:
- if isinstance(image_ref, str):
- result["image"] = load_image(image_ref, field="image")
- else:
- # Already a PIL image or similar — pass through
- result["image"] = image_ref
- if not result:
+ image = (
+ load_image(image_ref, field="image")
+ if isinstance(image_ref, str)
+ else image_ref
+ )
+ if text is None and image is None:
raise ValueError("VL reranker item must have at least 'text' or 'image'.")
- return result
+ return RerankItem(text=text, image=image)
def _rerank_vl(
self,
query: "str | dict[str, Any]",
documents: "list[str] | list[dict[str, Any]]",
- max_length: int,
instruction: str | None = None,
) -> RerankOutput:
- """Rerank using mlx-embeddings' multimodal model.process() API."""
- query_item = self._build_vl_item(query)
- doc_items = [self._build_vl_item(d) for d in documents]
-
- inputs = {
- "instruction": instruction or self._CAUSAL_LM_DEFAULT_INSTRUCTION,
- "query": query_item,
- "documents": doc_items,
- }
-
- scores = self.model.process(inputs, processor=self.processor)
- mx.eval(scores)
- scores_list = [float(s) for s in scores.tolist()]
- indices = sorted(
- range(len(scores_list)),
- key=lambda i: scores_list[i],
- reverse=True,
- )
-
- return RerankOutput(
- scores=scores_list,
- indices=indices,
- total_tokens=0,
+ """Rerank with mlx-vlm's generative yes/no scoring."""
+ scores, total_tokens = score_documents(
+ self.model,
+ self.processor,
+ self._vl_config,
+ self._build_vl_item(query),
+ [self._build_vl_item(d) for d in documents],
+ instruction or self._CAUSAL_LM_DEFAULT_INSTRUCTION,
)
+ indices = sorted(range(len(scores)), key=lambda i: scores[i], reverse=True)
+ return RerankOutput(scores=scores, indices=indices, total_tokens=total_tokens)
def _load_causal_lm(self) -> Tuple[Any, Any]:
"""Load a CausalLM-based reranker model using mlx-lm."""
@@ -811,8 +751,17 @@ def load(self) -> None:
try:
if arch in MULTIMODAL_RERANKER_ARCHITECTURES:
- # Multimodal reranker (e.g., Qwen3-VL-Reranker) via mlx-embeddings
- self.model, self.processor = self._load_vl_reranker()
+ model_path = get_model_path(self.model_name)
+ self._vl_config = load_config(model_path)
+ ensure_model_code_trusted(
+ self._vl_config,
+ model_path=model_path,
+ trust_remote_code=self.trust_remote_code,
+ )
+ self.model, self.processor = load_reranker(
+ model_path, trust_remote_code=self.trust_remote_code
+ )
+ ensure_chat_template(self.processor, model_path)
self._is_vl_reranker = True
self._num_labels = 1
elif arch == "JinaForRanking":
@@ -825,31 +774,48 @@ def load(self) -> None:
self.model, self.processor = self._load_causal_lm()
self._is_causal_lm = True
self._num_labels = 2 # yes/no
- elif arch == "XLMRobertaForSequenceClassification":
- # Use omlx native implementation
- self.model, self.processor = self._load_xlm_roberta()
- self._num_labels = getattr(self.model.config, "num_labels", None)
else:
- # Use mlx-embeddings for other architectures (ModernBert, etc.)
- patch_qwen3_vl_processor_for_torch_free_image_loading()
- patch_qwen3_vl_position_ids_recompute()
- from mlx_embeddings import load
-
- self.model, self.processor = load(
- self.model_name,
- tokenizer_config={"trust_remote_code": self.trust_remote_code},
+ # Sequence-classification encoders (ModernBERT, XLM-RoBERTa,
+ # BERT) load through mlx-vlm, whose remappings resolve each
+ # model module's SequenceClassificationModel entry point.
+ model_path = get_model_path(self.model_name)
+ config = load_config(model_path)
+ ensure_model_code_trusted(
+ config,
+ model_path=model_path,
+ trust_remote_code=self.trust_remote_code,
)
- # Stock mlx-embeddings masks with -1e9 overflow to -inf in fp16,
- # so a fully padded (short) query produces NaN. The embedding
- # path already applies this finite-mask patch; the reranker's
- # mlx-embeddings branch must do the same (issue #3507).
+ pipeline_config = config.get("pipeline_config")
+ binary_sigmoid = isinstance(pipeline_config, dict) and bool(
+ pipeline_config.get("binary_sigmoid")
+ )
+ self._is_regression = bool(config.get("is_regression"))
+ id2label = config.get("id2label")
+ if self._is_regression or binary_sigmoid:
+ self._num_labels = 1
+ else:
+ self._num_labels = int(
+ config.get("num_labels")
+ or (len(id2label) if isinstance(id2label, dict) else 0)
+ or 1
+ )
+ # The public reranker loader rejects multi-label classifiers.
+ normalize_encoder_quantization_config(config)
+ self.model = load_encoder_model(
+ model_path,
+ model_remapping=SEQUENCE_CLASSIFIER_MODEL_REMAPPING,
+ model_class_name="SequenceClassificationModel",
+ config=config,
+ config_overrides={"num_labels": self._num_labels},
+ )
+ self.processor = load_processor(
+ model_path,
+ add_detokenizer=False,
+ trust_remote_code=self.trust_remote_code,
+ )
+ self.processor = getattr(self.processor, "tokenizer", self.processor)
patch_modernbert_attention(self.model)
- # Get num_labels from model config
- if hasattr(self.model, "config"):
- config = self.model.config
- self._num_labels = getattr(config, "num_labels", None)
-
# Try mx.compile for persistent Metal kernel caching
self._is_compiled = self._try_compile()
@@ -863,8 +829,8 @@ def load(self) -> None:
except ImportError as e:
raise ImportError(
- "mlx-lm, mlx-embeddings, or transformers is required for reranking. "
- "Install with: pip install mlx-lm mlx-embeddings transformers"
+ "mlx-lm, mlx-vlm, or transformers is required for reranking. "
+ "Install with: pip install mlx-lm mlx-vlm transformers"
) from e
except FileNotFoundError:
raise FileNotFoundError(
@@ -886,9 +852,8 @@ def _try_compile(self) -> bool:
- Compile a narrow function that returns logits only.
"""
if self._is_causal_lm or self._is_vl_reranker:
- # CausalLM / VL reranker paths use custom scoring (yes/no logits or
- # mlx-embeddings model.process). VL forward needs pixel_values and
- # lacks pooler_output, so the compile wrapper here wouldn't apply.
+ # CausalLM / VL reranker paths use custom yes/no logit scoring, so
+ # the sequence-classifier compile wrapper does not apply.
logger.info(f"mx.compile skipped for {self.model_name}")
self._compiled_seq_logits = None
return False
@@ -899,15 +864,8 @@ def _try_compile(self) -> bool:
try:
def _compiled_seq_logits(inputs):
- outputs = base_model(**inputs)
- if (
- hasattr(outputs, "pooler_output")
- and outputs.pooler_output is not None
- ):
- return outputs.pooler_output
- raise ValueError(
- "Model output does not contain pooler_output. "
- "Ensure the model is a SequenceClassification model."
+ return _classifier_scores(
+ base_model(**inputs), is_regression=self._is_regression
)
# NOTE: use default compile mode. shapeless=True can fail shape
@@ -940,9 +898,11 @@ def close(self) -> None:
self.processor = None
self._loaded = False
self._num_labels = None
+ self._is_regression = False
self._is_causal_lm = False
self._is_jina_reranker = False
self._is_vl_reranker = False
+ self._vl_config = None
self._token_true_id = None
self._token_false_id = None
self._doc_embed_token_id = None
@@ -1000,14 +960,7 @@ def rerank(
return RerankOutput(scores=[], indices=[], total_tokens=0)
if self._is_vl_reranker:
- effective_max_length = (
- max_length
- if max_length is not None
- else self._DEFAULT_MAX_LENGTH_CAUSAL_LM
- )
- return self._rerank_vl(
- query, documents, effective_max_length, instruction=instruction
- )
+ return self._rerank_vl(query, documents, instruction=instruction)
# Text-only paths: coerce dict inputs down to text so existing
# _rerank_* methods keep their str-only contract.
@@ -1368,20 +1321,9 @@ def _truncate_text(text: str, limit: int) -> str:
total_tokens=total_tokens,
)
- def _seq_classification_tokenizer(self) -> Any:
- """Return the tokenizer behind the SequenceClassification processor."""
- # Unwrap only mlx-embeddings' TokenizerWrapper. transformers
- # tokenizers also have a _tokenizer attribute.
- processor = self.processor
- if type(processor).__name__ == "TokenizerWrapper" and hasattr(
- processor, "_tokenizer"
- ):
- return processor._tokenizer
- return processor
-
def _tokenizer_max_length(self, default: int) -> int:
"""Return the tokenizer's declared input limit, or default."""
- limit = getattr(self._seq_classification_tokenizer(), "model_max_length", None)
+ limit = getattr(self.processor, "model_max_length", None)
# transformers uses int(1e30) when the tokenizer declares no limit.
if isinstance(limit, int) and 0 < limit < _TOKENIZER_MAX_LENGTH_SENTINEL:
return limit
@@ -1406,13 +1348,9 @@ def _seq_classification_logits(
if not callable(self.model):
raise ValueError("SequenceClassification model is not initialized.")
- outputs = self.model(input_ids=input_ids, attention_mask=attention_mask)
- # pooler_output shape: (batch_size, num_labels)
- if hasattr(outputs, "pooler_output") and outputs.pooler_output is not None:
- return outputs.pooler_output
- raise ValueError(
- "Model output does not contain pooler_output. "
- "Ensure the model is a SequenceClassification model."
+ return _classifier_scores(
+ self.model(input_ids=input_ids, attention_mask=attention_mask),
+ is_regression=self._is_regression,
)
def _rerank_seq_classification(
@@ -1422,7 +1360,7 @@ def _rerank_seq_classification(
max_length: int = 512,
) -> RerankOutput:
"""Rerank using SequenceClassification models (encoder-based)."""
- processor = self._seq_classification_tokenizer()
+ processor = self.processor
if not callable(processor):
raise ValueError("SequenceClassification processor is not initialized.")
@@ -1448,7 +1386,7 @@ def _rerank_seq_classification(
# Evaluate per batch so peak memory stays at one batch.
mx.eval(logits)
- # Binary heads already apply sigmoid. Multi-class heads use the
+ # Scores are already activated. Multi-class heads use the
# last column (typically the "relevant" class).
if logits.shape[-1] == 1:
batch_scores = logits.squeeze(-1).tolist()
@@ -1482,7 +1420,7 @@ def _validate_architecture(self) -> None:
"""
config_path = Path(self.model_name) / "config.json"
if not config_path.exists():
- # If no config.json, let mlx-embeddings handle validation
+ # If no config.json, let the loader handle validation
return
try:
diff --git a/omlx/models/xlm_roberta.py b/omlx/models/xlm_roberta.py
deleted file mode 100644
index 66496ae52a..0000000000
--- a/omlx/models/xlm_roberta.py
+++ /dev/null
@@ -1,543 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-"""
-XLM-RoBERTa model implementation for omlx.
-
-This module provides XLM-RoBERTa model with SequenceClassification support
-for reranking tasks. Based on mlx-embeddings implementation with added
-classifier head for ForSequenceClassification architectures.
-
-Supports:
-- XLMRobertaForSequenceClassification (reranking)
-- XLMRobertaModel (embeddings)
-"""
-
-import math
-from dataclasses import dataclass, field
-from typing import Dict, List, Optional
-
-import mlx.core as mx
-import mlx.nn as nn
-
-from .base_model import BaseModelArgs, BaseModelOutput, mean_pooling, normalize_embeddings
-
-
-@dataclass
-class ModelArgs(BaseModelArgs):
- """XLM-RoBERTa model configuration."""
-
- model_type: str = "xlm-roberta"
- hidden_size: int = 768
- num_hidden_layers: int = 12
- intermediate_size: int = 3072
- num_attention_heads: int = 12
- max_position_embeddings: int = 514
- layer_norm_eps: float = 1e-05
- vocab_size: int = 250002
- add_pooling_layer: bool = True
- attention_probs_dropout_prob: float = 0.1
- hidden_dropout_prob: float = 0.1
- type_vocab_size: int = 1
- output_past: bool = True
- pad_token_id: int = 1
- position_embedding_type: str = "absolute"
- pooling_config: Optional[dict] = None
-
- # SequenceClassification specific
- architectures: List[str] = field(default_factory=lambda: ["XLMRobertaModel"])
- num_labels: int = 1
- classifier_dropout: Optional[float] = None
- id2label: Optional[Dict[int, str]] = None
- label2id: Optional[Dict[str, int]] = None
-
- @property
- def is_sequence_classification(self) -> bool:
- """Check if model is for sequence classification."""
- return (
- self.architectures
- and len(self.architectures) > 0
- and "ForSequenceClassification" in self.architectures[0]
- )
-
-
-class XLMRobertaEmbeddings(nn.Module):
- """XLM-RoBERTa embeddings layer."""
-
- def __init__(self, config: ModelArgs):
- super().__init__()
- self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
- self.position_embeddings = nn.Embedding(
- config.max_position_embeddings, config.hidden_size
- )
- self.token_type_embeddings = nn.Embedding(
- config.type_vocab_size, config.hidden_size
- )
- self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
- self.dropout = nn.Dropout(config.hidden_dropout_prob)
- self.padding_idx = config.pad_token_id
- # RoBERTa models number positions after padding_idx. BERT counts from 0.
- self.position_offset = (
- 0 if config.model_type == "bert" else config.pad_token_id + 1
- )
-
- def create_position_ids_from_input_ids(
- self, input_ids, padding_idx, past_key_values_length=0
- ):
- mask = mx.where(input_ids != padding_idx, 1, 0)
- incremental_indices = (mx.cumsum(mask, axis=1) + past_key_values_length) * mask
- return incremental_indices + padding_idx
-
- def __call__(
- self,
- input_ids: mx.array,
- token_type_ids=None,
- position_ids=None,
- inputs_embeds=None,
- past_key_values_length=0,
- ) -> mx.array:
- if input_ids is not None:
- input_shape = input_ids.shape
- else:
- input_shape = inputs_embeds.shape[:-1]
-
- seq_length = input_shape[1]
-
- if position_ids is None:
- if self.position_offset == 0:
- position_ids = mx.broadcast_to(
- mx.arange(
- past_key_values_length, past_key_values_length + seq_length
- ),
- input_shape,
- )
- else:
- position_ids = self.create_position_ids_from_input_ids(
- input_ids, self.padding_idx, past_key_values_length
- )
-
- if token_type_ids is None:
- token_type_ids = mx.zeros(input_shape, dtype=mx.int32)
-
- if inputs_embeds is None:
- inputs_embeds = self.word_embeddings(input_ids)
-
- token_type_embeddings = self.token_type_embeddings(token_type_ids)
-
- embeddings = inputs_embeds + token_type_embeddings
- position_embeddings = self.position_embeddings(position_ids)
- embeddings += position_embeddings
-
- embeddings = self.LayerNorm(embeddings)
- embeddings = self.dropout(embeddings)
- return embeddings
-
-
-class XLMRobertaSelfAttention(nn.Module):
- """XLM-RoBERTa self attention layer."""
-
- def __init__(self, config: ModelArgs):
- super().__init__()
- self.num_attention_heads = config.num_attention_heads
- self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
- self.all_head_size = self.num_attention_heads * self.attention_head_size
-
- self.scale = self.all_head_size**-0.5
-
- self.query = nn.Linear(config.hidden_size, self.all_head_size)
- self.key = nn.Linear(config.hidden_size, self.all_head_size)
- self.value = nn.Linear(config.hidden_size, self.all_head_size)
- self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
-
- def transpose_for_scores(self, x):
- new_x_shape = x.shape[:-1] + (
- self.num_attention_heads,
- self.attention_head_size,
- )
- x = x.reshape(new_x_shape)
- return x.transpose(0, 2, 1, 3)
-
- def __call__(
- self, x: mx.array, attention_mask=None, head_mask=None, output_attentions=False
- ):
- queries, keys, values = self.query(x), self.key(x), self.value(x)
-
- # Prepare the queries, keys and values for the attention computation
- queries = self.transpose_for_scores(queries)
- keys = self.transpose_for_scores(keys)
- values = self.transpose_for_scores(values)
-
- if output_attentions or head_mask is not None:
- attention_scores = queries @ keys.swapaxes(-1, -2)
- attention_scores = attention_scores / math.sqrt(self.attention_head_size)
-
- if attention_mask is not None:
- attention_scores = attention_scores + attention_mask
-
- attention_probs = nn.softmax(
- attention_scores.astype(mx.float32), axis=-1
- ).astype(attention_scores.dtype)
- attention_probs = self.dropout(attention_probs)
-
- if head_mask is not None:
- attention_probs = attention_probs * mx.array(head_mask)
-
- context_layer = attention_probs @ values
- else:
- # The eager path materializes batch x heads x L x L scores, and its
- # looped softmax (L > 4096) corrupts rows past the Metal grid limit.
- mask = (
- attention_mask.astype(queries.dtype)
- if attention_mask is not None
- else None
- )
- context_layer = mx.fast.scaled_dot_product_attention(
- queries,
- keys,
- values,
- scale=1.0 / math.sqrt(self.attention_head_size),
- mask=mask,
- )
-
- context_layer = context_layer.transpose(0, 2, 1, 3)
- new_context_layer_shape = context_layer.shape[:-2] + (self.all_head_size,)
- context_layer = context_layer.reshape(new_context_layer_shape)
-
- outputs = (
- (context_layer, attention_probs) if output_attentions else (context_layer,)
- )
- return outputs
-
-
-class XLMRobertaSelfOutput(nn.Module):
- """XLM-RoBERTa self attention output layer."""
-
- def __init__(self, config: ModelArgs):
- super().__init__()
- self.dense = nn.Linear(config.hidden_size, config.hidden_size)
- self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
- self.dropout = nn.Dropout(config.hidden_dropout_prob)
-
- def __call__(self, hidden_states, input_tensor):
- hidden_states = self.dense(hidden_states)
- hidden_states = self.dropout(hidden_states)
- hidden_states = self.LayerNorm(hidden_states + input_tensor)
- return hidden_states
-
-
-class XLMRobertaAttention(nn.Module):
- """XLM-RoBERTa attention block."""
-
- def __init__(self, config: ModelArgs):
- super().__init__()
- self.self = XLMRobertaSelfAttention(config)
- self.output = XLMRobertaSelfOutput(config)
-
- def __call__(
- self,
- hidden_states,
- attention_mask=None,
- head_mask=None,
- output_attentions=False,
- ):
- self_outputs = self.self(
- hidden_states, attention_mask, head_mask, output_attentions
- )
- attention_output = self.output(self_outputs[0], hidden_states)
- outputs = (attention_output,) + self_outputs[1:]
- return outputs
-
-
-class XLMRobertaIntermediate(nn.Module):
- """XLM-RoBERTa intermediate (FFN first) layer."""
-
- def __init__(self, config: ModelArgs):
- super().__init__()
- self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
-
- def __call__(self, hidden_states):
- hidden_states = self.dense(hidden_states)
- hidden_states = nn.gelu(hidden_states)
- return hidden_states
-
-
-class XLMRobertaOutput(nn.Module):
- """XLM-RoBERTa output (FFN second) layer."""
-
- def __init__(self, config: ModelArgs):
- super().__init__()
- self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
- self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
- self.dropout = nn.Dropout(config.hidden_dropout_prob)
-
- def __call__(self, hidden_states, input_tensor):
- hidden_states = self.dense(hidden_states)
- hidden_states = self.dropout(hidden_states)
- hidden_states = self.LayerNorm(hidden_states + input_tensor)
- return hidden_states
-
-
-class XLMRobertaLayer(nn.Module):
- """XLM-RoBERTa transformer layer."""
-
- def __init__(self, config):
- super().__init__()
- self.attention = XLMRobertaAttention(config)
- self.intermediate = XLMRobertaIntermediate(config)
- self.output = XLMRobertaOutput(config)
-
- def __call__(
- self,
- hidden_states,
- attention_mask=None,
- head_mask=None,
- output_attentions=False,
- ):
- attention_outputs = self.attention(
- hidden_states, attention_mask, head_mask, output_attentions
- )
- attention_output = attention_outputs[0]
- intermediate_output = self.intermediate(attention_output)
- layer_output = self.output(intermediate_output, attention_output)
- outputs = (layer_output,) + attention_outputs[1:]
- return outputs
-
-
-class XLMRobertaEncoder(nn.Module):
- """XLM-RoBERTa encoder (stack of transformer layers)."""
-
- def __init__(self, config: ModelArgs):
- super().__init__()
- self.config = config
- self.layer = [XLMRobertaLayer(config) for _ in range(config.num_hidden_layers)]
-
- def __call__(
- self,
- hidden_states,
- attention_mask=None,
- head_mask=None,
- output_attentions=False,
- output_hidden_states=False,
- ):
- all_hidden_states = () if output_hidden_states else None
- all_attentions = () if output_attentions else None
-
- for i, layer_module in enumerate(self.layer):
- if output_hidden_states:
- all_hidden_states = all_hidden_states + (hidden_states,)
-
- layer_head_mask = head_mask[i] if head_mask is not None else None
-
- layer_outputs = layer_module(
- hidden_states, attention_mask, layer_head_mask, output_attentions
- )
-
- hidden_states = layer_outputs[0]
-
- if output_attentions:
- all_attentions = all_attentions + (layer_outputs[1],)
-
- if output_hidden_states:
- all_hidden_states = all_hidden_states + (hidden_states,)
-
- return tuple(
- v
- for v in [hidden_states, all_hidden_states, all_attentions]
- if v is not None
- )
-
-
-class XLMRobertaPooler(nn.Module):
- """XLM-RoBERTa pooler (CLS token pooling with dense + tanh)."""
-
- def __init__(self, config: ModelArgs):
- super().__init__()
- self.dense = nn.Linear(config.hidden_size, config.hidden_size)
- self.activation = nn.Tanh()
-
- def __call__(self, hidden_states):
- # We "pool" the model by simply taking the hidden state corresponding
- # to the first token.
- first_token_tensor = hidden_states[:, 0]
- pooled_output = self.dense(first_token_tensor)
- pooled_output = self.activation(pooled_output)
- return pooled_output
-
-
-class XLMRobertaClassificationHead(nn.Module):
- """
- Classification head for XLMRobertaForSequenceClassification.
-
- Structure (matching HuggingFace):
- - Take CLS token
- - Dense (hidden_size -> hidden_size)
- - Tanh activation
- - Dropout
- - Out projection (hidden_size -> num_labels)
- """
-
- def __init__(self, config: ModelArgs):
- super().__init__()
- classifier_dropout = (
- config.classifier_dropout
- if config.classifier_dropout is not None
- else config.hidden_dropout_prob
- )
- self.dense = nn.Linear(config.hidden_size, config.hidden_size)
- self.dropout = nn.Dropout(classifier_dropout)
- self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
-
- def __call__(self, features):
- # Take CLS token (first token)
- x = features[:, 0, :]
- x = self.dropout(x)
- x = self.dense(x)
- x = mx.tanh(x)
- x = self.dropout(x)
- x = self.out_proj(x)
- return x
-
-
-class Model(nn.Module):
- """
- XLM-RoBERTa model with optional SequenceClassification head.
-
- Supports both:
- - XLMRobertaModel: Embeddings only
- - XLMRobertaForSequenceClassification: Classification/reranking
- """
-
- def __init__(self, config: ModelArgs):
- super().__init__()
- self.config = config
- self.embeddings = XLMRobertaEmbeddings(config)
- self.encoder = XLMRobertaEncoder(config)
-
- # SequenceClassification uses classifier head instead of pooler
- if config.is_sequence_classification:
- self.num_labels = config.num_labels
- self.classifier = XLMRobertaClassificationHead(config)
- self.pooler = None # Not used for classification
- else:
- self.pooler = XLMRobertaPooler(config) if config.add_pooling_layer else None
-
- @property
- def max_input_length(self) -> int:
- """Longest input whose position ids stay inside the position table."""
- return self.config.max_position_embeddings - self.embeddings.position_offset
-
- def _process_outputs(self, logits: mx.array) -> mx.array:
- """Apply the appropriate activation function to the logits."""
- if self.num_labels == 1:
- # Binary classification with sigmoid
- return mx.sigmoid(logits)
- else:
- # Multi-class classification with softmax
- return mx.softmax(logits, axis=-1)
-
- def get_extended_attention_mask(self, attention_mask, input_shape):
- if attention_mask.ndim == 3:
- extended_attention_mask = attention_mask[:, None, :, :]
- elif attention_mask.ndim == 2:
- extended_attention_mask = attention_mask[:, None, None, :]
- else:
- raise ValueError(
- f"Wrong shape for attention_mask (shape {attention_mask.shape})"
- )
-
- extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
- return extended_attention_mask
-
- def get_head_mask(self, head_mask, num_hidden_layers):
- if head_mask is None:
- return [1] * num_hidden_layers
-
- if isinstance(head_mask, mx.array) and len(head_mask.shape) == 1:
- head_mask = mx.expand_dims(mx.expand_dims(head_mask, axis=0), axis=0)
- head_mask = mx.broadcast_to(head_mask, (num_hidden_layers, -1, -1))
- elif isinstance(head_mask, mx.array) and len(head_mask.shape) == 2:
- head_mask = mx.expand_dims(mx.expand_dims(head_mask, axis=1), axis=-1)
-
- return mx.array(head_mask)
-
- def __call__(
- self,
- input_ids,
- attention_mask=None,
- token_type_ids=None,
- position_ids=None,
- head_mask=None,
- output_attentions=False,
- output_hidden_states=False,
- ):
- input_shape = input_ids.shape
-
- if attention_mask is None:
- attention_mask = mx.ones(input_shape)
- if token_type_ids is None:
- token_type_ids = mx.zeros(input_shape, dtype=mx.int64)
-
- extended_attention_mask = self.get_extended_attention_mask(
- attention_mask, input_shape
- )
- head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
-
- embedding_output = self.embeddings(input_ids, token_type_ids, position_ids)
- encoder_outputs = self.encoder(
- embedding_output,
- extended_attention_mask,
- output_attentions=output_attentions,
- output_hidden_states=output_hidden_states,
- )
- sequence_output = encoder_outputs[0]
-
- # Pooling for embeddings
- pooled_output = (
- self.pooler(sequence_output) if self.pooler is not None else None
- )
-
- # SequenceClassification: apply classifier head
- if hasattr(self, "classifier"):
- logits = self.classifier(sequence_output)
- pooled_output = self._process_outputs(logits)
-
- # Normalized features for embeddings. Honor pooling_config.pooling_mode
- # so models that require CLS pooling (e.g. BAAI bge-m3 dense, which is
- # trained on the [CLS] token — mean pooling significantly degrades it)
- # are served faithfully. Default "mean" preserves prior behavior for all
- # other XLM-RoBERTa / BERT embedding models.
- pooling_mode = (self.config.pooling_config or {}).get("pooling_mode", "mean")
- if pooling_mode == "cls":
- text_embeds = sequence_output[:, 0]
- else:
- text_embeds = mean_pooling(sequence_output, attention_mask)
- text_embeds = normalize_embeddings(text_embeds)
-
- return BaseModelOutput(
- last_hidden_state=sequence_output,
- text_embeds=text_embeds,
- pooler_output=pooled_output,
- hidden_states=encoder_outputs[1:] if len(encoder_outputs) > 1 else None,
- )
-
- def sanitize(self, weights):
- """
- Sanitize weights from HuggingFace checkpoint.
-
- Handles:
- - Removing "roberta." prefix from keys
- - Removing unused position_ids
- """
- sanitized_weights = {}
- for k, v in weights.items():
- if "position_ids" in k:
- # Remove unused position_ids
- continue
-
- # Remove "roberta." prefix if present
- if k.startswith("roberta."):
- new_key = k[len("roberta.") :]
- else:
- new_key = k
-
- sanitized_weights[new_key] = v
-
- return sanitized_weights
diff --git a/omlx/patches/modernbert_attention.py b/omlx/patches/modernbert_attention.py
index 1a02d86378..d9e2a5d5f5 100644
--- a/omlx/patches/modernbert_attention.py
+++ b/omlx/patches/modernbert_attention.py
@@ -1,42 +1,38 @@
# SPDX-License-Identifier: Apache-2.0
-"""Finite ModernBERT attention masks for mlx-embeddings (issue #3507).
+"""Finite ModernBERT attention masks for mlx-vlm (issue #3507).
-Remove after the pinned dependency includes Blaizzy/mlx-embeddings#80.
+mlx-vlm builds the additive mask with -1e9, which becomes -inf in fp16, so a
+fully masked padded query produces NaN.
"""
import logging
import mlx.core as mx
+from mlx_vlm.models.modernbert.modernbert import Model
logger = logging.getLogger(__name__)
+_MASKED = -60000.0
-def _update_attention_mask(self, attention_mask):
+
+def _masks(self, attention_mask, dtype):
"""Preserve padding/window masks without overflowing fp16 SDPA scores."""
batch_size, seq_len = attention_mask.shape
- # Keep the additive mask floating point, including for int32 token masks.
- # -1e9 becomes -inf in fp16; fully masked padded queries then produce NaN.
- # Norm weights retain the compute dtype even when embedding weights are uint32.
- dtype = self.embeddings.norm.weight.dtype
- additive_mask = mx.where(attention_mask == 1, 0.0, -60000.0).astype(dtype)
+ additive = mx.where(attention_mask == 1, 0.0, _MASKED).astype(dtype)
global_mask = mx.broadcast_to(
- additive_mask[:, None, None, :], (batch_size, 1, seq_len, seq_len)
+ additive[:, None, None, :], (batch_size, 1, seq_len, seq_len)
)
positions = mx.arange(seq_len)
in_window = (
- mx.abs(positions[:, None] - positions[None, :])
- <= self.config.local_attention // 2
+ mx.abs(positions[:, None] - positions[None, :]) <= self.local_attention // 2
)
- local_mask = mx.where(in_window[None, None, :, :], global_mask, -60000.0)
- return global_mask, local_mask
+ sliding_mask = mx.where(in_window[None, None, :, :], global_mask, _MASKED)
+ return global_mask, sliding_mask.astype(dtype)
-def patch_modernbert_attention(model):
+def patch_modernbert_attention(model) -> None:
"""Patch the loaded ModernBERT class before compiling its forward pass."""
- if type(model).__module__ != "mlx_embeddings.models.modernbert":
- return
- model_cls = type(model.model)
- if model_cls._update_attention_mask is _update_attention_mask:
+ if not isinstance(model, Model) or Model._masks is _masks:
return
- model_cls._update_attention_mask = _update_attention_mask
+ Model._masks = _masks
logger.info("Applied ModernBERT finite attention mask patch")
diff --git a/tests/test_embedding.py b/tests/test_embedding.py
index 944bdb476a..eda2263fb1 100644
--- a/tests/test_embedding.py
+++ b/tests/test_embedding.py
@@ -6,7 +6,6 @@
import io
import json
import math
-import numpy as np
import struct
import threading
import time
@@ -16,14 +15,15 @@
from unittest.mock import MagicMock, patch
import mlx.core as mx
+import numpy as np
import pytest
from mlx.utils import tree_flatten
-from mlx_embeddings.models.siglip import Model as Siglip
-from mlx_embeddings.models.siglip import ModelArgs as SiglipArgs
-from mlx_embeddings.models.siglip import TextConfig as SiglipTextConfig
-from mlx_embeddings.models.siglip import VisionConfig as SiglipVisionConfig
from mlx_vlm.models.embedding_gemma2 import Model as EmbeddingGemma2
from mlx_vlm.models.embedding_gemma2 import ModelConfig as EmbeddingGemma2Config
+from mlx_vlm.models.siglip import Model as Siglip
+from mlx_vlm.models.siglip.config import ModelConfig as SiglipConfig
+from mlx_vlm.models.siglip.config import TextConfig as SiglipTextConfig
+from mlx_vlm.models.siglip.config import VisionConfig as SiglipVisionConfig
from PIL import Image
from safetensors.numpy import save_file
@@ -450,6 +450,7 @@ class TestExtractEmbeddingsArray:
def test_extract_text_embeds(self):
"""Test extraction from text_embeds field."""
import mlx.core as mx
+
from omlx.models.embedding import MLXEmbeddingModel
model = MLXEmbeddingModel("test-model")
@@ -464,6 +465,7 @@ def test_extract_text_embeds(self):
def test_extract_pooler_output(self):
"""Test extraction from pooler_output when text_embeds is absent."""
import mlx.core as mx
+
from omlx.models.embedding import MLXEmbeddingModel
model = MLXEmbeddingModel("test-model")
@@ -477,6 +479,7 @@ def test_extract_pooler_output(self):
def test_extract_last_hidden_state_mean_pool(self):
"""Test mean pooling fallback from last_hidden_state."""
import mlx.core as mx
+
from omlx.models.embedding import MLXEmbeddingModel
model = MLXEmbeddingModel("test-model")
@@ -500,6 +503,7 @@ def test_extract_raises_when_no_fields(self):
def test_extract_text_embeds_3d_mean_pool(self):
"""Per-token text_embeds (e.g. ModernBERT MaskedLM) should be mean pooled."""
import mlx.core as mx
+
from omlx.models.embedding import MLXEmbeddingModel
model = MLXEmbeddingModel("test-model")
@@ -517,6 +521,7 @@ def test_extract_text_embeds_3d_mean_pool(self):
def test_extract_pooler_output_3d_mean_pool(self):
"""Per-token pooler_output should also be mean pooled to 2D."""
import mlx.core as mx
+
from omlx.models.embedding import MLXEmbeddingModel
model = MLXEmbeddingModel("test-model")
@@ -529,212 +534,149 @@ def test_extract_pooler_output_3d_mean_pool(self):
assert result.shape == (2, 3)
-class TestEmbeddingCompileFallback:
- """Tests for embedding compile path fallback behavior."""
+class _WordTokenizer:
+ """Tokenizer stub that splits words and records each call's kwargs."""
+
+ def __init__(self, model_max_length=None):
+ if model_max_length is not None:
+ self.model_max_length = model_max_length
+ self.calls = []
+
+ def __call__(self, texts, *, padding, truncation, max_length, **kwargs):
+ self.calls.append({"max_length": max_length, "truncation": truncation})
+ rows = [text.split() for text in texts]
+ if truncation:
+ rows = [row[:max_length] for row in rows]
+ width = max(len(row) for row in rows)
+ return {
+ "input_ids": np.array([[1] * width for _ in rows]),
+ "attention_mask": np.array(
+ [[1] * len(row) + [0] * (width - len(row)) for row in rows]
+ ),
+ }
- def test_compiled_path_fallback_on_failure(self):
- """Test that embed() falls back to eager when compiled path raises."""
- import mlx.core as mx
- from omlx.models.embedding import MLXEmbeddingModel
- class StandardTokenizer:
- def encode(self, text, add_special_tokens=True):
- del text, add_special_tokens
- return [1, 2, 3]
+def _text_embeds_model(embeds, config=None):
+ outputs = SimpleNamespace(
+ text_embeds=mx.array(embeds), pooler_output=None, last_hidden_state=None
+ )
+ model = MagicMock(return_value=outputs, spec=["__call__"])
+ model.config = config if config is not None else SimpleNamespace()
+ return model
- class StandardProcessor:
- def __init__(self):
- self._tokenizer = StandardTokenizer()
- model = MLXEmbeddingModel("test-model")
- model._loaded = True
- model._is_compiled = True
- model._compiled_embed = MagicMock(side_effect=RuntimeError("compile fail"))
- model.model = MagicMock()
- model.processor = StandardProcessor()
+def _eager_model(processor, model):
+ wrapper = MLXEmbeddingModel("test-model")
+ wrapper._loaded = True
+ wrapper._is_compiled = False
+ wrapper._compiled_embed = None
+ wrapper.model = model
+ wrapper.processor = processor
+ return wrapper
- # Mock generate to return outputs with text_embeds
- mock_outputs = MagicMock()
- mock_outputs.text_embeds = mx.array([[0.1, 0.2, 0.3]])
- mock_outputs.pooler_output = None
- mock_outputs.last_hidden_state = None
- with patch("mlx_embeddings.generate", return_value=mock_outputs):
- with patch("mlx_embeddings.utils.prepare_inputs"):
- result = model.embed(["test"])
+class TestEmbeddingCompileFallback:
+ """Tests for embedding compile path fallback behavior."""
- assert len(result.embeddings) == 1
- assert result.embeddings[0] == pytest.approx([0.1, 0.2, 0.3], abs=1e-5)
+ def test_compiled_path_fallback_on_failure(self):
+ model = _eager_model(_WordTokenizer(), _text_embeds_model([[0.1, 0.2, 0.3]]))
+ model._is_compiled = True
+ model._compiled_embed = MagicMock(side_effect=RuntimeError("compile fail"))
- def test_is_compiled_false_uses_eager_path(self):
- """Test that embed() uses eager path when _is_compiled is False."""
- import mlx.core as mx
- from omlx.models.embedding import MLXEmbeddingModel
+ result = model.embed(["test"])
- model = MLXEmbeddingModel("test-model")
- model._loaded = True
- model._is_compiled = False
- model._compiled_embed = None
- model.model = MagicMock()
- model.processor = MagicMock(spec=[])
+ assert model._is_compiled is False
+ assert result.embeddings[0] == pytest.approx([0.1, 0.2, 0.3], abs=1e-5)
- mock_outputs = MagicMock(spec=[])
- mock_outputs.text_embeds = mx.array([[0.5, 0.6]])
- mock_outputs.pooler_output = None
- mock_outputs.last_hidden_state = None
+ def test_eager_forward_receives_the_attention_mask(self):
+ model = _eager_model(
+ _WordTokenizer(), _text_embeds_model([[0.5, 0.6], [0.1, 0.2]])
+ )
- with patch("mlx_embeddings.generate", return_value=mock_outputs):
- result = model.embed(["test"])
+ model.embed(["a b c", "d"])
- assert len(result.embeddings) == 1
+ mask = model.model.call_args.kwargs["attention_mask"]
+ assert mask.tolist() == [[1, 1, 1], [1, 0, 0]]
def test_default_max_length_uses_model_config(self):
"""Omitted max_length should use model context metadata, not 512."""
- import mlx.core as mx
- from omlx.models.embedding import MLXEmbeddingModel
-
- model = MLXEmbeddingModel("test-model")
- model._loaded = True
- model._is_compiled = False
- model._compiled_embed = None
- model.model = SimpleNamespace(
- config=SimpleNamespace(max_position_embeddings=40960)
+ tokenizer = _WordTokenizer()
+ model = _eager_model(
+ tokenizer,
+ _text_embeds_model(
+ [[0.5, 0.6]], SimpleNamespace(max_position_embeddings=40960)
+ ),
)
- model.processor = SimpleNamespace()
-
- mock_outputs = MagicMock(spec=[])
- mock_outputs.text_embeds = mx.array([[0.5, 0.6]])
- mock_outputs.pooler_output = None
- mock_outputs.last_hidden_state = None
- with patch("mlx_embeddings.generate", return_value=mock_outputs) as generate:
- model.embed(["test"])
+ model.embed(["test"])
- assert generate.call_args.kwargs["max_length"] == 40960
+ assert tokenizer.calls[-1]["max_length"] == 40960
def test_eager_usage_counts_tokens_left_after_truncation(self):
- """generate() returns no mask, so usage is counted from the text."""
- model = MLXEmbeddingModel("test-model")
- model._loaded = True
- model._is_compiled = False
- model._compiled_embed = None
- model.model = MagicMock()
- model.processor = MagicMock(spec=["encode"])
- model.processor.encode.side_effect = lambda text, add_special_tokens: (
- text.split()
+ model = _eager_model(
+ _WordTokenizer(), _text_embeds_model([[0.5, 0.6], [0.1, 0.2]])
)
- mock_outputs = MagicMock(spec=[])
- mock_outputs.text_embeds = mx.array([[0.5, 0.6], [0.1, 0.2]])
- mock_outputs.pooler_output = None
- mock_outputs.last_hidden_state = None
-
texts = [" ".join(["w"] * 100), "a b c"]
- with patch("mlx_embeddings.generate", return_value=mock_outputs):
- truncated = model.embed(texts, max_length=8)
- full = model.embed(texts, max_length=8, truncation=False)
+ truncated = model.embed(texts, max_length=8)
+ full = model.embed(texts, max_length=8, truncation=False)
assert truncated.total_tokens == 8 + 3
assert full.total_tokens == 100 + 3
def test_default_max_length_uses_tokenizer_config_fallback(self):
"""Tokenizer model_max_length is used when model config lacks a limit."""
- import mlx.core as mx
- from omlx.models.embedding import MLXEmbeddingModel
+ tokenizer = _WordTokenizer(model_max_length=8192)
+ model = _eager_model(tokenizer, _text_embeds_model([[0.5, 0.6]]))
- model = MLXEmbeddingModel("test-model")
- model._loaded = True
- model._is_compiled = False
- model._compiled_embed = None
- model.model = SimpleNamespace(config=SimpleNamespace())
- model.processor = SimpleNamespace(model_max_length=8192)
+ model.embed(["test"])
- mock_outputs = MagicMock(spec=[])
- mock_outputs.text_embeds = mx.array([[0.5, 0.6]])
- mock_outputs.pooler_output = None
- mock_outputs.last_hidden_state = None
-
- with patch("mlx_embeddings.generate", return_value=mock_outputs) as generate:
- model.embed(["test"])
-
- assert generate.call_args.kwargs["max_length"] == 8192
+ assert tokenizer.calls[-1]["max_length"] == 8192
def test_unknown_default_max_length_falls_back_to_512(self):
"""Keep a conservative final fallback when no metadata exists."""
- import mlx.core as mx
- from omlx.models.embedding import MLXEmbeddingModel
-
- model = MLXEmbeddingModel("test-model")
- model._loaded = True
- model._is_compiled = False
- model._compiled_embed = None
- model.model = SimpleNamespace(config=SimpleNamespace())
- model.processor = SimpleNamespace()
-
- mock_outputs = MagicMock(spec=[])
- mock_outputs.text_embeds = mx.array([[0.5, 0.6]])
- mock_outputs.pooler_output = None
- mock_outputs.last_hidden_state = None
+ tokenizer = _WordTokenizer()
+ model = _eager_model(tokenizer, _text_embeds_model([[0.5, 0.6]]))
- with patch("mlx_embeddings.generate", return_value=mock_outputs) as generate:
- model.embed(["test"])
+ model.embed(["test"])
- assert generate.call_args.kwargs["max_length"] == 512
+ assert tokenizer.calls[-1]["max_length"] == 512
def test_explicit_max_length_is_respected(self):
"""Explicit max_length should override metadata."""
- import mlx.core as mx
- from omlx.models.embedding import MLXEmbeddingModel
-
- model = MLXEmbeddingModel("test-model")
- model._loaded = True
- model._is_compiled = False
- model._compiled_embed = None
- model.model = SimpleNamespace(
- config=SimpleNamespace(max_position_embeddings=40960)
+ tokenizer = _WordTokenizer()
+ model = _eager_model(
+ tokenizer,
+ _text_embeds_model(
+ [[0.5, 0.6]], SimpleNamespace(max_position_embeddings=40960)
+ ),
)
- model.processor = SimpleNamespace()
- mock_outputs = MagicMock(spec=[])
- mock_outputs.text_embeds = mx.array([[0.5, 0.6]])
- mock_outputs.pooler_output = None
- mock_outputs.last_hidden_state = None
+ model.embed(["test"], max_length=1024)
- with patch("mlx_embeddings.generate", return_value=mock_outputs) as generate:
- model.embed(["test"], max_length=1024)
-
- assert generate.call_args.kwargs["max_length"] == 1024
+ assert tokenizer.calls[-1]["max_length"] == 1024
def test_max_length_is_capped_at_position_table(self):
"""XLM-R declares 8194 positions but only 8192 inputs fit after the offset."""
- import mlx.core as mx
- from omlx.models.embedding import MLXEmbeddingModel
-
- model = MLXEmbeddingModel("test-model")
- model._loaded = True
- model._is_compiled = False
- model._compiled_embed = None
- model.model = SimpleNamespace(
- config=SimpleNamespace(max_position_embeddings=8194),
- max_input_length=8192,
+ tokenizer = _WordTokenizer()
+ model = _eager_model(
+ tokenizer,
+ _text_embeds_model(
+ [[0.5, 0.6]],
+ SimpleNamespace(max_position_embeddings=8194),
+ ),
)
- model.processor = SimpleNamespace()
-
- mock_outputs = MagicMock(spec=[])
- mock_outputs.text_embeds = mx.array([[0.5, 0.6]])
- mock_outputs.pooler_output = None
- mock_outputs.last_hidden_state = None
+ model.model.max_input_length = 8192
- with patch("mlx_embeddings.generate", return_value=mock_outputs) as generate:
- model.embed(["test"])
- model.embed(["test"], max_length=1024)
+ model.embed(["test"])
+ model.embed(["test"], max_length=1024)
- lengths = [call.kwargs["max_length"] for call in generate.call_args_list]
- assert lengths == [8192, 1024]
+ assert [call["max_length"] for call in tokenizer.calls] == [8192, 1024]
def test_custom_processor_compiled_path_uses_prepare_embedding_inputs(self):
"""Custom embedding processors should use their own prepare API."""
import mlx.core as mx
+
from omlx.models.embedding import MLXEmbeddingModel
model = MLXEmbeddingModel("test-model")
@@ -752,18 +694,16 @@ def test_custom_processor_compiled_path_uses_prepare_embedding_inputs(self):
)
model.processor = processor
- with patch("mlx_embeddings.generate") as mock_generate:
- result = model.embed(["hello world"])
+ result = model.embed(["hello world"])
processor.prepare_embedding_inputs.assert_called_once_with(
[{"text": "hello world"}], return_tensors="mlx"
)
- mock_generate.assert_not_called()
assert result.embeddings[0] == pytest.approx([0.1, 0.2], abs=1e-5)
- def test_custom_processor_eager_path_bypasses_generate(self):
- """Custom embedding processors should bypass mlx_embeddings.generate()."""
+ def test_custom_processor_eager_path_calls_the_model(self):
import mlx.core as mx
+
from omlx.models.embedding import MLXEmbeddingModel
model = MLXEmbeddingModel("test-model")
@@ -786,57 +726,18 @@ def test_custom_processor_eager_path_bypasses_generate(self):
)
model.processor = processor
- with patch("mlx_embeddings.generate") as mock_generate:
- result = model.embed(["hello world"])
+ result = model.embed(["hello world"])
processor.prepare_embedding_inputs.assert_called_once_with(
[{"text": "hello world"}], return_tensors="mlx"
)
- mock_generate.assert_not_called()
model.model.assert_called_once()
assert result.embeddings[0] == pytest.approx([0.3, 0.4, 0.5], abs=1e-5)
- def test_custom_processor_eager_path_remaps_input_ids_for_inputs_signature(self):
- """Models that accept `inputs` instead of `input_ids` should still work."""
- import mlx.core as mx
- from omlx.models.embedding import MLXEmbeddingModel
-
- class InputsOnlyModel:
- def __call__(self, inputs, attention_mask=None):
- assert inputs.tolist() == [[4, 5, 6]]
- assert attention_mask.tolist() == [[1, 1, 1]]
-
- outputs = MagicMock(spec=[])
- outputs.text_embeds = mx.array([[0.7, 0.8, 0.9]])
- outputs.pooler_output = None
- outputs.last_hidden_state = None
- return outputs
-
- model = MLXEmbeddingModel("test-model")
- model._loaded = True
- model._is_compiled = False
- model._compiled_embed = None
- model.model = InputsOnlyModel()
- model._detect_input_key_remapping()
-
- processor = MagicMock(spec=[])
- processor.prepare_embedding_inputs = MagicMock(
- return_value={
- "input_ids": mx.array([[4, 5, 6]]),
- "attention_mask": mx.array([[1, 1, 1]]),
- }
- )
- model.processor = processor
-
- with patch("mlx_embeddings.generate") as mock_generate:
- result = model.embed(["hello world"])
-
- mock_generate.assert_not_called()
- assert result.embeddings[0] == pytest.approx([0.7, 0.8, 0.9], abs=1e-5)
-
def test_custom_processor_receives_valid_image_items_unchanged(self):
"""Custom processors should receive validated data URI strings unchanged."""
import mlx.core as mx
+
from omlx.models.embedding import MLXEmbeddingModel
model = MLXEmbeddingModel("test-model")
@@ -891,6 +792,7 @@ def test_custom_processor_rejects_remote_image_url(self):
def test_custom_processor_counts_image_only_tokens_from_prepared_inputs(self):
"""Image-only custom processor inputs should contribute to usage stats."""
import mlx.core as mx
+
from omlx.models.embedding import MLXEmbeddingModel
model = MLXEmbeddingModel("test-model")
@@ -943,7 +845,6 @@ def test_close_releases_compiled_model_and_processor_resources(self):
model._using_native = False
model._is_compiled = True
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"
@@ -957,7 +858,6 @@ def test_close_releases_compiled_model_and_processor_resources(self):
assert model._hidden_size is None
assert model._using_native is False
assert model._is_compiled is False
- assert model._remap_input_ids_to_inputs is False
mock_mx.synchronize.assert_called_once()
mock_mx.clear_cache.assert_called_once()
assert collect.call_count == 2
@@ -969,19 +869,20 @@ class TestEmbeddingEngine:
def test_engine_lifecycle(self):
"""Test engine start and stop lifecycle."""
import asyncio
+
from omlx.engine.embedding import EmbeddingEngine
engine = EmbeddingEngine("test-model")
# Mock the MLXEmbeddingModel
- with patch("omlx.engine.embedding.MLXEmbeddingModel") as MockModel:
+ with patch("omlx.engine.embedding.MLXEmbeddingModel") as mock_model_cls:
mock_model = MagicMock()
mock_model.hidden_size = 384
- MockModel.return_value = mock_model
+ mock_model_cls.return_value = mock_model
asyncio.run(engine.start())
- MockModel.assert_called_once_with(
+ mock_model_cls.assert_called_once_with(
"test-model",
trust_remote_code=False,
audio_enabled=False,
@@ -996,19 +897,20 @@ def test_engine_lifecycle(self):
def test_engine_embed(self):
"""Test embedding generation through engine."""
import asyncio
+
from omlx.engine.embedding import EmbeddingEngine
from omlx.models.embedding import EmbeddingOutput
engine = EmbeddingEngine("test-model")
- with patch("omlx.engine.embedding.MLXEmbeddingModel") as MockModel:
+ with patch("omlx.engine.embedding.MLXEmbeddingModel") as mock_model_cls:
mock_model = MagicMock()
mock_model.embed.return_value = EmbeddingOutput(
embeddings=[[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]],
total_tokens=10,
dimensions=3,
)
- MockModel.return_value = mock_model
+ mock_model_cls.return_value = mock_model
asyncio.run(engine.start())
result = asyncio.run(engine.embed(["Hello", "World"]))
@@ -1020,6 +922,7 @@ def test_engine_embed(self):
def test_engine_not_started_raises_error(self):
"""Test that embed raises error if engine not started."""
import asyncio
+
from omlx.engine.embedding import EmbeddingEngine
engine = EmbeddingEngine("test-model")
@@ -1133,6 +1036,7 @@ def test_engine_repr(self):
def test_engine_properties(self):
"""Test engine property accessors."""
import asyncio
+
from omlx.engine.embedding import EmbeddingEngine
engine = EmbeddingEngine("test-model")
@@ -1142,11 +1046,11 @@ def test_engine_properties(self):
assert engine.hidden_size is None
# After loading
- with patch("omlx.engine.embedding.MLXEmbeddingModel") as MockModel:
+ with patch("omlx.engine.embedding.MLXEmbeddingModel") as mock_model_cls:
mock_model = MagicMock()
mock_model.processor = MagicMock()
mock_model.hidden_size = 384
- MockModel.return_value = mock_model
+ mock_model_cls.return_value = mock_model
asyncio.run(engine.start())
@@ -1157,15 +1061,17 @@ def test_engine_clears_metal_cache_after_embed(self):
"""Metal cache should be cleared after every embed request (#684)."""
engine = EmbeddingEngine("test-model")
- with patch("omlx.engine.embedding.MLXEmbeddingModel") as MockModel, \
- patch("omlx.engine.embedding.mx") as mock_mx:
+ with (
+ patch("omlx.engine.embedding.MLXEmbeddingModel") as mock_model_cls,
+ patch("omlx.engine.embedding.mx") as mock_mx,
+ ):
mock_model = MagicMock()
mock_model.embed.return_value = EmbeddingOutput(
embeddings=[[0.1, 0.2]],
total_tokens=5,
dimensions=2,
)
- MockModel.return_value = mock_model
+ mock_model_cls.return_value = mock_model
asyncio.run(engine.start())
asyncio.run(engine.embed(["Hello"]))
@@ -1183,15 +1089,17 @@ def test_engine_clears_metal_cache_per_concurrent_request(self):
engine = EmbeddingEngine("test-model")
concurrency = 4
- with patch("omlx.engine.embedding.MLXEmbeddingModel") as MockModel, \
- patch("omlx.engine.embedding.mx") as mock_mx:
+ with (
+ patch("omlx.engine.embedding.MLXEmbeddingModel") as mock_model_cls,
+ patch("omlx.engine.embedding.mx") as mock_mx,
+ ):
mock_model = MagicMock()
mock_model.embed.return_value = EmbeddingOutput(
embeddings=[[0.1, 0.2]],
total_tokens=5,
dimensions=2,
)
- MockModel.return_value = mock_model
+ mock_model_cls.return_value = mock_model
async def run_concurrent():
await engine.start()
@@ -1215,16 +1123,16 @@ def embed_side_effect(inputs, **kwargs):
dimensions=1,
)
- with patch("omlx.engine.embedding.MLXEmbeddingModel") as MockModel, \
- patch("omlx.engine.embedding.mx") as mock_mx:
+ with (
+ patch("omlx.engine.embedding.MLXEmbeddingModel") as mock_model_cls,
+ patch("omlx.engine.embedding.mx") as mock_mx,
+ ):
mock_model = MagicMock()
mock_model.embed.side_effect = embed_side_effect
- MockModel.return_value = mock_model
+ mock_model_cls.return_value = mock_model
asyncio.run(engine.start())
- result = asyncio.run(
- engine.embed([f"text-{i}" for i in range(5)])
- )
+ result = asyncio.run(engine.embed([f"text-{i}" for i in range(5)]))
assert result.embeddings == [[0.0], [1.0], [2.0], [3.0], [4.0]]
assert result.total_tokens == 5
@@ -1254,16 +1162,16 @@ def embed_side_effect(inputs, **kwargs):
dimensions=1,
)
- with patch("omlx.engine.embedding.MLXEmbeddingModel") as MockModel, \
- patch("omlx.engine.embedding.mx"):
+ with (
+ patch("omlx.engine.embedding.MLXEmbeddingModel") as mock_model_cls,
+ patch("omlx.engine.embedding.mx"),
+ ):
mock_model = MagicMock()
mock_model.embed.side_effect = embed_side_effect
- MockModel.return_value = mock_model
+ mock_model_cls.return_value = mock_model
asyncio.run(engine.start())
- result = asyncio.run(
- engine.embed([f"text-{i}" for i in range(5)])
- )
+ result = asyncio.run(engine.embed([f"text-{i}" for i in range(5)]))
assert result.embeddings == [[0.0], [1.0], [2.0], [3.0], [4.0]]
assert observed_batches == [
@@ -1288,11 +1196,13 @@ def embed_side_effect(inputs, **kwargs):
dimensions=1,
)
- with patch("omlx.engine.embedding.MLXEmbeddingModel") as MockModel, \
- patch("omlx.engine.embedding.mx"):
+ with (
+ patch("omlx.engine.embedding.MLXEmbeddingModel") as mock_model_cls,
+ patch("omlx.engine.embedding.mx"),
+ ):
mock_model = MagicMock()
mock_model.embed.side_effect = embed_side_effect
- MockModel.return_value = mock_model
+ mock_model_cls.return_value = mock_model
async def run_concurrent():
await engine.start()
@@ -1334,9 +1244,7 @@ def test_embedding_data_defaults(self):
def test_embedding_response_defaults(self):
"""Test EmbeddingResponse default values."""
response = EmbeddingResponse(
- data=[],
- model="test",
- usage=EmbeddingUsage(prompt_tokens=0, total_tokens=0)
+ data=[], model="test", usage=EmbeddingUsage(prompt_tokens=0, total_tokens=0)
)
assert response.object == "list"
@@ -1366,17 +1274,15 @@ def test_embedding_data_accepts_string_embedding(self):
class TestEmbeddingIntegration:
"""Integration tests requiring actual model loading.
- These tests are marked as slow and require mlx-embeddings to be installed.
+ These tests are marked as slow and require a real model checkpoint.
"""
def test_real_embedding_generation(self):
"""Test embedding generation with a real model.
This test requires a small embedding model to be available.
- Skip if mlx-embeddings is not installed.
"""
import asyncio
- pytest.importorskip("mlx_embeddings")
from omlx.engine.embedding import EmbeddingEngine
@@ -1406,19 +1312,28 @@ def test_real_embedding_generation(self):
pytest.skip(f"Could not load model: {e}")
-class TestNativeEmbeddingLoading:
- """Tests for native embedding model loading (without mlx-embeddings)."""
+class TestEncoderEmbeddingLoading:
+ """XLM-RoBERTa/BERT embedding checkpoints load through mlx-vlm.
+
+ These encoder families used to ship as a vendored copy inside omlx; they
+ now resolve to mlx-vlm's own implementations, so the guarantees that used
+ to live in the vendored module (tokenizer contract, L2-normalized pooled
+ vectors, position-table safety, token-budget batching, weight validation)
+ are asserted against the mlx-vlm path here instead.
+ """
- class MockNativeTokenizer:
- """Minimal tokenizer used only by native-loading tests."""
+ class MockEncoderTokenizer:
+ """Minimal tokenizer used by the encoder-path tests."""
def __init__(self, vocab_size: int = 30522):
self.vocab_size = max(vocab_size, 16)
def encode(self, text: str, add_special_tokens: bool = True):
- tokens = [abs(hash(token)) % (self.vocab_size - 3) + 3 for token in text.split()]
+ tokens = [
+ abs(hash(token)) % (self.vocab_size - 3) + 3 for token in text.split()
+ ]
if add_special_tokens:
- return [101, *tokens, 102]
+ return [1, *tokens, 2]
return tokens
def __call__(
@@ -1428,10 +1343,14 @@ def __call__(
padding=True,
truncation=True,
max_length=512,
+ return_attention_mask=True,
return_tensors="np",
):
- del truncation, return_tensors
- encoded = [self.encode(text, add_special_tokens=True)[:max_length] for text in texts]
+ del truncation, return_attention_mask, return_tensors
+ encoded = [
+ self.encode(text, add_special_tokens=True)[:max_length]
+ for text in texts
+ ]
target_len = max(len(ids) for ids in encoded) if padding and encoded else 0
input_ids = []
attention_mask = []
@@ -1441,443 +1360,173 @@ def __call__(
attention_mask.append([1] * len(ids) + [0] * pad_len)
return {"input_ids": input_ids, "attention_mask": attention_mask}
- def _write_full_native_checkpoint(self, tmp_path, config):
- """Write a complete native checkpoint for a small embedding model."""
- from mlx.utils import tree_flatten
- from omlx.models.xlm_roberta import Model, ModelArgs
- from safetensors.numpy import save_file
-
- model_config = ModelArgs(**config)
- model = Model(model_config)
- weights = {name: np.array(value) for name, value in tree_flatten(model.parameters())}
- save_file(weights, str(tmp_path / "model.safetensors"))
-
- def test_load_native_bert_model(self, tmp_path):
- """Test native loading of BERT embedding model."""
- import sys
- sys.path.insert(0, str(Path(__file__).parent.parent))
- from safetensors.numpy import save_file
-
- # Create minimal BERT model structure
- config = {
- "model_type": "bert",
- "architectures": ["BertModel"],
- "hidden_size": 384,
- "num_hidden_layers": 6,
- "vocab_size": 30522,
- "num_attention_heads": 12,
- "intermediate_size": 1536,
- "max_position_embeddings": 512,
- "hidden_dropout_prob": 0.1,
- "attention_probs_dropout_prob": 0.1,
- "pad_token_id": 0,
- }
- (tmp_path / "config.json").write_text(json.dumps(config))
-
- vocab_size = 30522
- save_file(
- {"embeddings.word_embeddings.weight": np.zeros((1, 1), dtype=np.float32)},
- str(tmp_path / "model.safetensors"),
- )
+ _XLM_ROBERTA_CONFIG = {
+ "model_type": "xlm-roberta",
+ "architectures": ["XLMRobertaModel"],
+ "hidden_size": 32,
+ "num_hidden_layers": 1,
+ "num_attention_heads": 4,
+ "intermediate_size": 64,
+ "vocab_size": 128,
+ "max_position_embeddings": 40,
+ "pad_token_id": 1,
+ }
- from omlx.models.embedding import MLXEmbeddingModel
+ _BERT_CONFIG = {
+ "model_type": "bert",
+ "architectures": ["BertModel"],
+ "hidden_size": 32,
+ "num_hidden_layers": 1,
+ "num_attention_heads": 4,
+ "intermediate_size": 64,
+ "vocab_size": 128,
+ "max_position_embeddings": 64,
+ "pad_token_id": 0,
+ }
- model = MLXEmbeddingModel(str(tmp_path))
- tokenizer = self.MockNativeTokenizer(vocab_size=vocab_size)
- with patch(
- "transformers.AutoTokenizer.from_pretrained",
- return_value=tokenizer,
- ) as mock_from_pretrained, patch(
- "omlx.models.embedding.MLXEmbeddingModel._validate_native_weights",
- return_value=None,
- ) as mock_validate_weights, patch(
- "omlx.models.xlm_roberta.Model.load_weights",
- return_value=None,
- ) as mock_load_weights:
- result = model._load_native()
-
- assert result is True
- assert model._loaded is True
- assert model._using_native is True
- mock_from_pretrained.assert_called()
- mock_validate_weights.assert_called_once()
- assert mock_load_weights.call_args.kwargs["strict"] is False
-
- def test_load_native_xlm_roberta_model(self, tmp_path):
- """Test native loading of XLMRoBERTa embedding model."""
- import sys
- sys.path.insert(0, str(Path(__file__).parent.parent))
+ def _write_checkpoint(self, tmp_path, config):
+ """Write a complete tiny checkpoint for an mlx-vlm encoder family."""
+ from mlx.utils import tree_flatten
from safetensors.numpy import save_file
- config = {
- "model_type": "xlm-roberta",
- "architectures": ["XLMRobertaModel"],
- "hidden_size": 768,
- "num_hidden_layers": 12,
- "vocab_size": 250002,
- "num_attention_heads": 12,
- "intermediate_size": 3072,
- "max_position_embeddings": 514,
- "attention_probs_dropout_prob": 0.1,
- "hidden_dropout_prob": 0.1,
- "pad_token_id": 1,
- }
- (tmp_path / "config.json").write_text(json.dumps(config))
-
- vocab_size = 250002
- save_file(
- {"embeddings.word_embeddings.weight": np.zeros((1, 1), dtype=np.float32)},
- str(tmp_path / "model.safetensors"),
- )
-
- from omlx.models.embedding import MLXEmbeddingModel
-
- model = MLXEmbeddingModel(str(tmp_path))
- tokenizer = self.MockNativeTokenizer(vocab_size=vocab_size)
- with patch(
- "transformers.AutoTokenizer.from_pretrained",
- return_value=tokenizer,
- ) as mock_from_pretrained, patch(
- "omlx.models.embedding.MLXEmbeddingModel._validate_native_weights",
- return_value=None,
- ) as mock_validate_weights, patch(
- "omlx.models.xlm_roberta.Model.load_weights",
- return_value=None,
- ) as mock_load_weights:
- result = model._load_native()
-
- assert result is True
- assert model._loaded is True
- assert model._using_native is True
- mock_from_pretrained.assert_called()
- mock_validate_weights.assert_called_once()
- assert mock_load_weights.call_args.kwargs["strict"] is False
-
- def test_load_native_supports_bfloat16_safetensors(self, tmp_path):
- """Native embedding load must not route bf16 safetensors through NumPy."""
- import mlx.core as mx
-
- config = {
- "model_type": "xlm-roberta",
- "architectures": ["XLMRobertaModel"],
- "hidden_size": 4,
- "num_hidden_layers": 1,
- "vocab_size": 16,
- "num_attention_heads": 1,
- "intermediate_size": 8,
- "max_position_embeddings": 8,
- "attention_probs_dropout_prob": 0.0,
- "hidden_dropout_prob": 0.0,
- "pad_token_id": 1,
- }
- (tmp_path / "config.json").write_text(json.dumps(config))
- mx.save_safetensors(
- str(tmp_path / "model.safetensors"),
- {
- "embeddings.word_embeddings.weight": mx.ones(
- (16, 4), dtype=mx.bfloat16
- )
- },
+ model_type = str(config["model_type"]).replace("-", "_")
+ module = __import__(
+ f"mlx_vlm.models.{model_type}.{model_type}", fromlist=["Model"]
)
-
- from omlx.models.embedding import MLXEmbeddingModel
-
- model = MLXEmbeddingModel(str(tmp_path))
- tokenizer = self.MockNativeTokenizer(vocab_size=config["vocab_size"])
- with patch(
- "transformers.AutoTokenizer.from_pretrained",
- return_value=tokenizer,
- ), patch(
- "omlx.models.embedding.MLXEmbeddingModel._validate_native_weights",
- return_value=None,
- ) as mock_validate_weights, patch(
- "omlx.models.xlm_roberta.Model.load_weights",
- return_value=None,
- ) as mock_load_weights:
- result = model._load_native()
-
- assert result is True
- mock_validate_weights.assert_called_once()
- loaded_weights = dict(mock_load_weights.call_args.args[0])
- assert loaded_weights["embeddings.word_embeddings.weight"].dtype == mx.bfloat16
-
- def test_load_native_rejects_missing_required_weights(self, tmp_path):
- """Native loading must fail when core transformer weights are missing."""
- from safetensors.numpy import save_file
-
- config = {
- "model_type": "bert",
- "architectures": ["BertModel"],
- "hidden_size": 384,
- "num_hidden_layers": 2,
- "vocab_size": 30522,
- "num_attention_heads": 12,
- "intermediate_size": 1536,
- "max_position_embeddings": 512,
- "hidden_dropout_prob": 0.1,
- "attention_probs_dropout_prob": 0.1,
- "pad_token_id": 0,
+ config_cls = __import__(
+ f"mlx_vlm.models.{model_type}.config", fromlist=["ModelConfig"]
+ ).ModelConfig
+ model = module.Model(config_cls.from_dict(config))
+ weights = {
+ name: np.array(value) for name, value in tree_flatten(model.parameters())
}
- (tmp_path / "config.json").write_text(json.dumps(config))
-
- save_file(
- {"embeddings.word_embeddings.weight": np.random.randn(30522, 384).astype(np.float32)},
- str(tmp_path / "model.safetensors"),
- )
+ save_file(weights, str(tmp_path / "model.safetensors"))
+ def _load(self, tmp_path, config):
from omlx.models.embedding import MLXEmbeddingModel
- model = MLXEmbeddingModel(str(tmp_path))
- tokenizer = self.MockNativeTokenizer(vocab_size=30522)
- with patch(
- "transformers.AutoTokenizer.from_pretrained",
- return_value=tokenizer,
- ):
- result = model._load_native()
-
- assert result is False
- assert model._loaded is False
-
- def test_load_native_rejects_shape_mismatches(self, tmp_path):
- """Native loading must fail when a required weight shape is incompatible."""
- from safetensors.numpy import save_file
-
- config = {
- "model_type": "bert",
- "architectures": ["BertModel"],
- "hidden_size": 384,
- "num_hidden_layers": 2,
- "vocab_size": 30522,
- "num_attention_heads": 12,
- "intermediate_size": 1536,
- "max_position_embeddings": 512,
- "hidden_dropout_prob": 0.1,
- "attention_probs_dropout_prob": 0.1,
- "pad_token_id": 0,
- }
(tmp_path / "config.json").write_text(json.dumps(config))
-
- self._write_full_native_checkpoint(tmp_path, config)
-
- from safetensors import safe_open
-
- weights = {}
- with safe_open(tmp_path / "model.safetensors", framework="mlx") as f:
- for key in f.keys():
- weights[key] = np.array(f.get_tensor(key))
-
- weights["embeddings.word_embeddings.weight"] = np.random.randn(30523, 384).astype(
- np.float32
- )
- save_file(weights, str(tmp_path / "model.safetensors"))
-
- from omlx.models.embedding import MLXEmbeddingModel
+ self._write_checkpoint(tmp_path, config)
model = MLXEmbeddingModel(str(tmp_path))
- tokenizer = self.MockNativeTokenizer(vocab_size=30522)
- with patch(
- "transformers.AutoTokenizer.from_pretrained",
- return_value=tokenizer,
- ):
- result = model._load_native()
+ tokenizer = self.MockEncoderTokenizer(config["vocab_size"])
+ with patch("omlx.models.embedding.load_processor", return_value=tokenizer):
+ model.load()
+ return model
- assert result is False
- assert model._loaded is False
+ def test_vendored_encoder_module_is_gone(self):
+ """Nothing may re-add the old vendored encoder implementation."""
+ import importlib.util
- def test_native_embed_tokenizes_with_tokenizer_call(self, tmp_path):
- """transformers tokenizers expose a Rust _tokenizer that must stay unused."""
- config = {
- "model_type": "bert",
- "architectures": ["BertModel"],
- "hidden_size": 32,
- "num_hidden_layers": 1,
- "vocab_size": 128,
- "num_attention_heads": 4,
- "intermediate_size": 64,
- "max_position_embeddings": 64,
- "attention_probs_dropout_prob": 0.0,
- "hidden_dropout_prob": 0.0,
- "pad_token_id": 0,
- }
- (tmp_path / "config.json").write_text(json.dumps(config))
- self._write_full_native_checkpoint(tmp_path, config)
+ import omlx.models.embedding as embedding_module
- from omlx.models.embedding import MLXEmbeddingModel
+ assert importlib.util.find_spec("omlx.models.xlm_roberta") is None
+ assert "xlm_roberta" not in Path(embedding_module.__file__).read_text()
- model = MLXEmbeddingModel(str(tmp_path))
- tokenizer = self.MockNativeTokenizer(vocab_size=config["vocab_size"])
- with patch(
- "transformers.AutoTokenizer.from_pretrained", return_value=tokenizer
- ):
- model.load()
- expected = model.embed(["hello world"]).embeddings
- # Its encode() would apply tokenizer.json padding as real tokens.
- tokenizer._tokenizer = object()
- assert model.embed(["hello world"]).embeddings == expected
+ def test_bert_checkpoint_routes_to_mlx_vlm(self, tmp_path):
+ """BERT resolves through mlx-vlm rather than a removed internal copy."""
+ model = self._load(tmp_path, dict(self._BERT_CONFIG))
- def test_position_ids_follow_bert_and_roberta_numbering(self):
- """BERT positions start at 0; XLM-R positions start after padding_idx."""
- import mlx.core as mx
- from omlx.models.xlm_roberta import Model, ModelArgs
-
- input_ids = mx.array([[5, 6, 7, 8]])
- common = dict(
- hidden_size=8,
- num_hidden_layers=1,
- num_attention_heads=2,
- intermediate_size=16,
- vocab_size=16,
+ assert model._using_native is False
+ assert model._hidden_size == self._BERT_CONFIG["hidden_size"]
+ assert model.model.model_type == "bert"
+
+ def test_xlm_roberta_position_table_caps_input_length(self, tmp_path):
+ """Absolute position tables read out of range silently, so cap inputs."""
+ model = self._load(tmp_path, dict(self._XLM_ROBERTA_CONFIG))
+
+ # RoBERTa numbers positions from pad_token_id + 1, so the top of the
+ # table is unreachable; BERT's whole table stays usable.
+ assert (
+ model.model.max_input_length
+ == self._XLM_ROBERTA_CONFIG["max_position_embeddings"]
+ - self._XLM_ROBERTA_CONFIG["pad_token_id"]
+ - 1
)
- cases = (
- ("bert", 0, 512, [0, 1, 2, 3], 512),
- ("xlm-roberta", 1, 8194, [2, 3, 4, 5], 8192),
+ # An over-long request without an explicit limit must be clamped to the
+ # table instead of reading positions out of range.
+ long_text = " ".join(f"tok{i}" for i in range(400))
+ assert model.embed([long_text], truncation=True).total_tokens <= (
+ model.model.max_input_length
)
- for model_type, pad_token_id, table, positions, max_input in cases:
- model = Model(
- ModelArgs(
- model_type=model_type,
- pad_token_id=pad_token_id,
- max_position_embeddings=table,
- **common,
- )
- )
- model.train(False)
- expected = model.embeddings(input_ids, position_ids=mx.array([positions]))
-
- assert mx.array_equal(model.embeddings(input_ids), expected).item()
- assert model.max_input_length == max_input
- def test_load_native_falls_back_for_unknown_arch(self, tmp_path):
- """Test that native loading returns False for unsupported architectures."""
- import sys
- sys.path.insert(0, str(Path(__file__).parent.parent))
+ def test_bert_position_table_is_fully_usable(self, tmp_path):
+ model = self._load(tmp_path, dict(self._BERT_CONFIG))
- # Create config with unknown embedding architecture
- config = {
- "model_type": "custom-embedding",
- "architectures": ["CustomEmbeddingModel"],
- "hidden_size": 512,
- }
- (tmp_path / "config.json").write_text(json.dumps(config))
-
- from omlx.models.embedding import MLXEmbeddingModel
+ assert (
+ model.model.max_input_length
+ == self._BERT_CONFIG["max_position_embeddings"]
+ )
- model = MLXEmbeddingModel(str(tmp_path))
- result = model._load_native()
- assert result is False
- assert model._loaded is False
+ def test_embed_tokenizes_with_tokenizer_call(self, tmp_path):
+ """transformers tokenizers expose a Rust _tokenizer that must stay unused."""
+ model = self._load(tmp_path, dict(self._BERT_CONFIG))
+ tokenizer = model.processor
+ expected = model.embed(["hello world"]).embeddings
+ # Its encode() would apply tokenizer.json padding as real tokens.
+ tokenizer._tokenizer = object()
+ assert model.embed(["hello world"]).embeddings == expected
def test_embed_produces_normalized_vectors(self, tmp_path):
- """Test that embed produces L2-normalized embedding vectors."""
- import sys, math
- sys.path.insert(0, str(Path(__file__).parent.parent))
+ """embed() returns one L2-normalized vector per input at the model dim."""
+ model = self._load(tmp_path, dict(self._BERT_CONFIG))
+ output = model.embed(["hello world", "a longer sentence with more words"])
- config = {
- "model_type": "bert",
- "architectures": ["BertModel"],
- "hidden_size": 128,
- "num_hidden_layers": 2,
- "vocab_size": 1000,
- "num_attention_heads": 4,
- "intermediate_size": 512,
- "max_position_embeddings": 512,
- "attention_probs_dropout_prob": 0.0,
- "hidden_dropout_prob": 0.0,
- "pad_token_id": 0,
- }
- (tmp_path / "config.json").write_text(json.dumps(config))
- vocab_size = config["vocab_size"]
+ assert len(output.embeddings) == 2
+ for emb in output.embeddings:
+ assert len(emb) == self._BERT_CONFIG["hidden_size"]
+ norm = math.sqrt(sum(x * x for x in emb))
+ assert abs(norm - 1.0) < 1e-3, f"not L2-normalized: norm={norm}"
- self._write_full_native_checkpoint(tmp_path, config)
+ def test_embed_batches_long_inputs_in_input_order(self, tmp_path):
+ """Token-budget batches must match single-input vectors in input order."""
+ config = {**self._BERT_CONFIG, "max_position_embeddings": 256}
+ model = self._load(tmp_path, config)
+ model._is_compiled = False
+ model._compiled_embed = None
+ texts = ["w " * 40, "a b", "x " * 20, "c d e"]
- from omlx.models.embedding import MLXEmbeddingModel
+ singles = [model.embed([text], max_length=64) for text in texts]
- model = MLXEmbeddingModel(str(tmp_path))
- tokenizer = self.MockNativeTokenizer(vocab_size=vocab_size)
- with patch(
- "transformers.AutoTokenizer.from_pretrained",
- return_value=tokenizer,
- ):
- model.load()
- output = model.embed(["hello world"])
+ shapes = []
+ forward = model.model
- # Check normalization
- emb = output.embeddings[0]
- norm = math.sqrt(sum(x * x for x in emb))
- assert abs(norm - 1.0) < 0.01, f"Embedding not normalized: norm={norm}"
+ def recording_forward(**kwargs):
+ shapes.append(kwargs["input_ids"].shape)
+ return forward(**kwargs)
- def test_xlm_roberta_sdpa_attention_matches_eager(self):
- """The fused attention path must match the eager path on padded rows."""
- import mlx.core as mx
- from omlx.models.xlm_roberta import Model, ModelArgs
-
- model = Model(
- ModelArgs(
- hidden_size=32,
- num_hidden_layers=2,
- num_attention_heads=4,
- intermediate_size=64,
- vocab_size=100,
- max_position_embeddings=40,
- )
- )
- model.train(False)
- input_ids = mx.array([[0, 5, 6, 7, 8, 2], [0, 9, 2, 1, 1, 1]])
- attention_mask = mx.array([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0]])
+ model.model = recording_forward
+ with patch("omlx.models.embedding.ENCODER_BATCH_TOKEN_BUDGET", 48):
+ batched = model.embed(texts, max_length=64)
- fused = model(input_ids, attention_mask=attention_mask)
- # output_attentions needs the probabilities, so it keeps the eager path.
- eager = model(input_ids, attention_mask=attention_mask, output_attentions=True)
+ assert len(shapes) == 3
+ assert all(batch * width <= 48 for batch, width in shapes)
+ for got, single in zip(batched.embeddings, singles):
+ assert got == pytest.approx(single.embeddings[0], abs=1e-5)
+ assert batched.total_tokens == sum(single.total_tokens for single in singles)
- assert mx.allclose(
- fused.last_hidden_state, eager.last_hidden_state, atol=1e-5
- ).item()
+ def test_incomplete_checkpoint_fails_the_load(self, tmp_path):
+ """A partial checkpoint must surface as a failed load, not a silently
+ half-loaded encoder (weight validation lives in the loader now)."""
+ from safetensors.numpy import save_file
- def test_embed_batches_long_inputs_in_input_order(self, tmp_path):
- """Token-budget batches must match single-input vectors in input order."""
- config = {
- "model_type": "bert",
- "architectures": ["BertModel"],
- "hidden_size": 32,
- "num_hidden_layers": 1,
- "vocab_size": 128,
- "num_attention_heads": 4,
- "intermediate_size": 64,
- "max_position_embeddings": 128,
- "attention_probs_dropout_prob": 0.0,
- "hidden_dropout_prob": 0.0,
- "pad_token_id": 0,
- }
+ config = dict(self._BERT_CONFIG)
(tmp_path / "config.json").write_text(json.dumps(config))
- self._write_full_native_checkpoint(tmp_path, config)
+ save_file(
+ {"embeddings.word_embeddings.weight": np.zeros((1, 1), dtype=np.float32)},
+ str(tmp_path / "model.safetensors"),
+ )
from omlx.models.embedding import MLXEmbeddingModel
model = MLXEmbeddingModel(str(tmp_path))
- texts = ["w " * 40, "a b", "x " * 20, "c d e"]
with patch(
- "transformers.AutoTokenizer.from_pretrained",
- return_value=self.MockNativeTokenizer(vocab_size=config["vocab_size"]),
+ "omlx.models.embedding.load_processor",
+ return_value=self.MockEncoderTokenizer(config["vocab_size"]),
):
- model.load()
- singles = [model.embed([text], max_length=64) for text in texts]
-
- shapes = []
- forward = model.model
-
- def recording_forward(**kwargs):
- shapes.append(kwargs["input_ids"].shape)
- return forward(**kwargs)
-
- model.model = recording_forward
- with patch("omlx.models.embedding.ENCODER_BATCH_TOKEN_BUDGET", 48):
- batched = model.embed(texts, max_length=64)
-
- assert len(shapes) == 3
- assert all(batch * width <= 48 for batch, width in shapes)
- for got, single in zip(batched.embeddings, singles):
- assert got == pytest.approx(single.embeddings[0], abs=1e-5)
- assert batched.total_tokens == sum(single.total_tokens for single in singles)
+ with pytest.raises(Exception):
+ model.load()
+ assert model._loaded is False
class TestGetEmbeddingMaxLength:
@@ -1954,9 +1603,10 @@ def __call__(
def _write_full_qwen2_checkpoint(self, tmp_path, config):
"""Write a complete native Qwen2 checkpoint from the adapter's own params."""
from mlx.utils import tree_flatten
- from omlx.models.qwen2_embedding import Model, ModelArgs
from safetensors.numpy import save_file
+ from omlx.models.qwen2_embedding import Model, ModelArgs
+
model = Model(ModelArgs(**config))
weights = {
name: np.array(value) for name, value in tree_flatten(model.parameters())
@@ -1979,11 +1629,11 @@ def _load(self, tmp_path):
return model
def test_load_native_qwen2_takes_native_path(self, tmp_path):
- """Qwen2ForCausalLM routes through the native adapter, not mlx-embeddings."""
+ """Qwen2ForCausalLM routes through the native adapter, not mlx-vlm."""
model = self._load(tmp_path)
assert model._using_native is True
assert model._hidden_size == self._CONFIG["hidden_size"]
- # The adapter, not the qwen3/mlx-embeddings fallback.
+ # The adapter, not the qwen3/mlx-vlm fallback.
from omlx.models.qwen2_embedding import Model as Qwen2EmbeddingModel
assert isinstance(model.model, Qwen2EmbeddingModel)
@@ -2008,6 +1658,7 @@ def test_qwen2_last_token_pool_is_mask_aware(self, tmp_path):
would read a pad position under right padding and diverge.
"""
import mlx.core as mx
+
from omlx.models.qwen2_embedding import Model, ModelArgs
mx.random.seed(0)
@@ -2025,9 +1676,9 @@ def test_qwen2_last_token_pool_is_mask_aware(self, tmp_path):
# Mask-aware pooling agrees to float32 noise (~1e-4); a hardcoded
# ``[:, -1]`` pool would read the trailing pad token under right padding
# and diverge by O(0.1+). 1e-3 sits cleanly between the two regimes.
- assert np.max(np.abs(right - left)) < 1e-3, (
- "last-token pool is not mask-aware: left/right padding diverged"
- )
+ assert (
+ np.max(np.abs(right - left)) < 1e-3
+ ), "last-token pool is not mask-aware: left/right padding diverged"
def test_qwen2_is_causal_flag_controls_attention(self, tmp_path):
"""is_causal=False makes attention bidirectional (gte-Qwen2 family).
@@ -2038,6 +1689,7 @@ def test_qwen2_is_causal_flag_controls_attention(self, tmp_path):
distinguishes jina-code (causal) from gte-Qwen2 (``is_causal: false``).
"""
import mlx.core as mx
+
from omlx.models.qwen2_embedding import Model, ModelArgs
base = mx.array([[5, 9, 7, 3]])
@@ -2053,7 +1705,9 @@ def first_token_drift(is_causal):
return float(np.max(np.abs(a - b)))
assert first_token_drift(is_causal=True) < 1e-6, "causal leaked future token"
- assert first_token_drift(is_causal=False) > 1e-3, "bidirectional did not attend forward"
+ assert (
+ first_token_drift(is_causal=False) > 1e-3
+ ), "bidirectional did not attend forward"
class TestDeclaredPoolingMode:
@@ -2151,6 +1805,7 @@ def test_cls_is_normalized(self, tmp_path):
import mlx.core as mx
m = self._model(tmp_path, {"pooling_mode_cls_token": True})
+ m._using_native = True
m._pooling_mode, m._pooling_source = m._resolve_pooling_mode()
hidden = mx.array([[[3.0, 4.0], [0.0, 1.0]]])
out = np.array(m._extract_embeddings_array(
@@ -2237,9 +1892,8 @@ def _call(**kwargs):
def test_eager_batch_is_masked_standard_processor(self, tmp_path):
"""compile off + right-padded batch: the tokenizer path must pool real tokens.
- ``mlx_embeddings.generate`` drops the mask it builds, so this path
- pooled a pad token for every mixed-length batch whenever a compile
- failure sent it here.
+ A compile failure sends mixed-length batches here, so this path must
+ pool with the tokenizer mask too.
"""
import mlx.core as mx
@@ -2340,6 +1994,116 @@ def test_leaves_other_models_untouched(self, tmp_path, name, config):
assert not self._promoted(tmp_path / name, **config)
+class TestMlxVlmEmbeddingLoading:
+ @pytest.mark.parametrize("trust_remote_code", [False, True])
+ def test_hub_id_resolves_before_loading_and_preserves_trust(
+ self, tmp_path, trust_remote_code
+ ):
+ (tmp_path / "config.json").write_text(json.dumps({"model_type": "modernbert"}))
+ loaded = SimpleNamespace(config=SimpleNamespace(hidden_size=4))
+ processor = SimpleNamespace(tokenizer=object())
+ model = MLXEmbeddingModel(
+ "mlx-community/test-embedding", trust_remote_code=trust_remote_code
+ )
+ with (
+ patch("mlx_vlm.utils.snapshot_download", return_value=str(tmp_path)) as hub,
+ patch(
+ "omlx.models.embedding.load_embedding_model", return_value=loaded
+ ) as load_model,
+ patch(
+ "omlx.models.embedding.load_processor", return_value=processor
+ ) as load_processor,
+ patch.object(model, "_try_compile", return_value=False),
+ ):
+ model.load()
+
+ assert hub.call_args.kwargs["repo_id"] == "mlx-community/test-embedding"
+ assert load_model.call_args.args == (tmp_path,)
+ load_processor.assert_called_once_with(
+ tmp_path, add_detokenizer=False, trust_remote_code=trust_remote_code
+ )
+ assert model.processor is processor.tokenizer
+
+ def test_custom_model_code_is_rejected_before_weights_or_processor(self, tmp_path):
+ (tmp_path / "config.json").write_text(
+ json.dumps({"model_type": "modernbert", "model_file": "custom.py"})
+ )
+ model = MLXEmbeddingModel(str(tmp_path))
+ with (
+ patch("omlx.models.embedding.load_embedding_model") as load_model,
+ patch("omlx.models.embedding.load_processor") as load_processor,
+ pytest.raises(ValueError, match="Enable Trust Remote Code"),
+ ):
+ model.load()
+ load_model.assert_not_called()
+ load_processor.assert_not_called()
+
+ @pytest.mark.parametrize("from_hub", [False, True])
+ def test_declared_pooling_config_is_preserved_for_mlx_vlm(
+ self, tmp_path, from_hub
+ ):
+ pooling_config = {
+ "pooling_mode_max_tokens": True,
+ "include_prompt": True,
+ "word_embedding_dimension": 4,
+ }
+ pooling_dir = tmp_path / "1_Pooling"
+ pooling_dir.mkdir()
+ (pooling_dir / "config.json").write_text(json.dumps(pooling_config))
+ (tmp_path / "config.json").write_text(json.dumps({"model_type": "lfm2"}))
+ loaded = SimpleNamespace(config=SimpleNamespace(hidden_size=4))
+ processor = SimpleNamespace(tokenizer=object())
+ model = MLXEmbeddingModel(
+ "mlx-community/test-embedding" if from_hub else str(tmp_path)
+ )
+
+ with (
+ patch("mlx_vlm.utils.snapshot_download", return_value=str(tmp_path)),
+ patch(
+ "omlx.models.embedding.load_embedding_model", return_value=loaded
+ ),
+ patch("omlx.models.embedding.load_processor", return_value=processor),
+ patch.object(model, "_try_compile", return_value=False),
+ ):
+ model.load()
+
+ assert model._pooling_mode == "max"
+ assert loaded.pooling_config == pooling_config
+
+ @pytest.mark.parametrize(
+ ("declared", "expected"),
+ [(" Last_Token ", "lasttoken"), ("CLS", "cls"), ("MAX", "max")],
+ )
+ def test_pooling_mode_alias_is_canonical_for_mlx_vlm(
+ self, tmp_path, declared, expected
+ ):
+ from mlx_vlm.models.pooling import pool_by_config
+
+ pooling_config = {"pooling_mode": declared, "include_prompt": True}
+ pooling_dir = tmp_path / "1_Pooling"
+ pooling_dir.mkdir()
+ (pooling_dir / "config.json").write_text(json.dumps(pooling_config))
+ (tmp_path / "config.json").write_text(json.dumps({"model_type": "lfm2"}))
+ loaded = SimpleNamespace(config=SimpleNamespace(hidden_size=4))
+ processor = SimpleNamespace(tokenizer=object())
+ model = MLXEmbeddingModel(str(tmp_path))
+
+ with (
+ patch(
+ "omlx.models.embedding.load_embedding_model", return_value=loaded
+ ),
+ patch("omlx.models.embedding.load_processor", return_value=processor),
+ patch.object(model, "_try_compile", return_value=False),
+ ):
+ model.load()
+
+ assert model._pooling_mode == expected
+ assert loaded.pooling_config["pooling_mode"] == expected
+ assert loaded.pooling_config["include_prompt"] is True
+ hidden = mx.arange(12, dtype=mx.float32).reshape(1, 3, 4)
+ pool_by_config(hidden, mx.ones((1, 3)), loaded.pooling_config)
+
+
class TestMlxVlmEmbeddingGemma2:
"""EmbeddingGemma 2 loads through mlx-vlm with an image input adapter."""
@@ -2414,7 +2178,9 @@ def _load(self, model_dir, audio_enabled=False, audio_max_seconds=None):
"omlx.models.embedding.load_processor", return_value=processor
) as load_processor:
model.load()
- load_processor.assert_called_once_with(model_dir, add_detokenizer=False)
+ load_processor.assert_called_once_with(
+ model_dir, add_detokenizer=False, trust_remote_code=False
+ )
return model, tokenizer, processor
def test_text_embeddings_match_model_and_clamp_length(self, model_dir):
@@ -2432,6 +2198,31 @@ def test_text_embeddings_match_model_and_clamp_length(self, model_dir):
)
processor.apply_chat_template.assert_not_called()
+ @pytest.mark.parametrize("model_type", ["embedding_gemma2", "Embedding-Gemma2"])
+ def test_text_only_checkpoint_without_audio_config_loads(
+ self, tmp_path, model_type
+ ):
+ config = {k: v for k, v in self._CONFIG.items() if k != "audio_config"}
+ model = EmbeddingGemma2(EmbeddingGemma2Config.from_dict(config))
+ weights = {
+ name: np.array(value) for name, value in tree_flatten(model.parameters())
+ }
+ save_file(weights, str(tmp_path / "model.safetensors"))
+ (tmp_path / "config.json").write_text(
+ json.dumps({**config, "model_type": model_type})
+ )
+
+ loaded, tokenizer, _ = self._load(tmp_path)
+ output = loaded.embed(["one two three"])
+
+ assert loaded.model.audio_tower is None
+ inputs = tokenizer(["one two three"], return_tensors="mlx", max_length=8192)
+ np.testing.assert_allclose(
+ np.array(output.embeddings),
+ np.array(model(**inputs).text_embeds),
+ atol=1e-5,
+ )
+
def test_image_batch_skips_compiled_path(self, model_dir):
model, _, processor = self._load(model_dir)
prepared = {
@@ -2443,18 +2234,12 @@ def test_image_batch_skips_compiled_path(self, model_dir):
output = model.embed([{"text": "a cat", "image": IMAGE_DATA_URI}])
- conversations = processor.apply_chat_template.call_args.args[0]
- assert conversations == [
- [
- {
- "role": "user",
- "content": [
- {"type": "text", "text": "a cat"},
- {"type": "image", "url": IMAGE_DATA_URI},
- ],
- }
- ]
- ]
+ (conversation,) = processor.apply_chat_template.call_args.args[0]
+ assert [message["role"] for message in conversation] == ["user"]
+ text, image = conversation[0]["content"]
+ assert text == {"type": "text", "text": "a cat"}
+ assert image["type"] == "image"
+ assert isinstance(image["image"], Image.Image)
model._compiled_embed.assert_not_called()
expected = model.model(**prepared).text_embeds
np.testing.assert_allclose(
@@ -2552,7 +2337,7 @@ def test_audio_length_not_sent_for_image_batches(self, model_dir):
class TestSiglipEmbedding:
- """SigLIP embeds text and images with separate towers."""
+ """SigLIP embeds text only; its text tower pools the last position."""
class MockTokenizer:
"""Pads to max_length and records the call kwargs."""
@@ -2566,33 +2351,10 @@ def __call__(self, texts, **kwargs):
encoded = [[3 + len(word) % 20 for word in t.split()] + [1] for t in texts]
input_ids = [ids + [0] * (length - len(ids)) for ids in encoded]
mask = [[1] * len(ids) + [0] * (length - len(ids)) for ids in encoded]
- return {"input_ids": mx.array(input_ids), "attention_mask": mx.array(mask)}
-
- class MockProcessor:
- """Like SiglipProcessor, __call__ takes images first."""
-
- def __init__(self, tokenizer):
- self.tokenizer = tokenizer
-
- def __call__(self, images=None, text=None, **kwargs):
- raise AssertionError("text reached the processor's images argument")
-
- @staticmethod
- def image_processor(images, return_tensors):
- pixels = [np.asarray(img, dtype=np.float32) / 127.5 - 1 for img in images]
- return {"pixel_values": np.stack(pixels).transpose(0, 3, 1, 2)}
-
- @staticmethod
- def _image(color):
- return Image.new("RGB", (32, 32), color)
-
- def _uri(self, color):
- buffer = io.BytesIO()
- self._image(color).save(buffer, format="PNG")
- return "data:image/png;base64," + base64.b64encode(buffer.getvalue()).decode()
+ return {"input_ids": np.array(input_ids), "attention_mask": np.array(mask)}
def _load(self, tmp_path):
- args = SiglipArgs(
+ config = SiglipConfig(
text_config=SiglipTextConfig(
vocab_size=32,
max_position_embeddings=8,
@@ -2601,57 +2363,69 @@ def _load(self, tmp_path):
num_attention_heads=2,
num_hidden_layers=1,
),
- vision_config=SiglipVisionConfig(
- image_size=32,
- patch_size=16,
- hidden_size=16,
- intermediate_size=32,
- num_attention_heads=2,
- num_hidden_layers=1,
- ),
+ vision_config=SiglipVisionConfig(),
)
- siglip = Siglip(args)
+ siglip = Siglip(config)
mx.eval(siglip.parameters())
tokenizer = self.MockTokenizer()
model = MLXEmbeddingModel(str(tmp_path))
- with patch(
- "mlx_embeddings.load", return_value=(siglip, self.MockProcessor(tokenizer))
+ with (
+ patch(
+ "omlx.models.embedding.load_config",
+ return_value={"model_type": "siglip"},
+ ),
+ patch("omlx.models.embedding.load_embedding_model", return_value=siglip),
+ patch(
+ "omlx.models.embedding.load_processor",
+ return_value=SimpleNamespace(tokenizer=tokenizer),
+ ),
):
model.load()
return model, siglip, tokenizer
- def test_text_and_image_items_use_their_own_tower(self, tmp_path):
+ def test_text_pads_to_the_position_table_and_counts_real_tokens(self, tmp_path):
model, siglip, tokenizer = self._load(tmp_path)
- texts = ["a red square", "a blue circle"]
- items = [
- {"text": texts[0]},
- {"image": self._uri("red")},
- {"text": texts[1]},
- {"image": self._uri("blue")},
- ]
+ texts = ["a red square", "a blue circle of light"]
- output = model.embed(items)
+ output = model.embed(texts)
assert [(c["padding"], c["max_length"]) for c in tokenizer.calls] == [
("max_length", 8)
]
tokens = tokenizer(texts, max_length=8)
- text = siglip.get_text_features(input_ids=tokens["input_ids"])
- pixels = self.MockProcessor.image_processor(
- [self._image("red"), self._image("blue")], return_tensors="np"
- )["pixel_values"]
- image = siglip.get_image_features(pixel_values=mx.array(pixels))
- text = np.array(text / mx.linalg.norm(text, axis=-1, keepdims=True))
- image = np.array(image / mx.linalg.norm(image, axis=-1, keepdims=True))
+ expected = siglip(mx.array(tokens["input_ids"])).text_embeds
np.testing.assert_allclose(
- np.array(output.embeddings),
- np.stack([text[0], image[0], text[1], image[1]]),
- atol=1e-5,
+ np.array(output.embeddings), np.array(expected), atol=1e-5
)
assert output.total_tokens == int(tokens["attention_mask"].sum())
- def test_text_and_image_in_one_item_is_rejected(self, tmp_path):
+ def test_shorter_limit_truncates_but_still_pads_to_the_table(self, tmp_path):
+ model, siglip, tokenizer = self._load(tmp_path)
+ texts = ["a red", "blue"]
+
+ output = model.embed(texts, max_length=4)
+
+ assert [(c["padding"], c["max_length"]) for c in tokenizer.calls] == [
+ ("max_length", 4)
+ ]
+ full_table = tokenizer(texts, max_length=8)["input_ids"]
+ expected = siglip(mx.array(full_table)).text_embeds
+ np.testing.assert_allclose(
+ np.array(output.embeddings), np.array(expected), atol=1e-5
+ )
+
+ def test_untruncated_input_cannot_exceed_the_position_table(self, tmp_path):
model, _, _ = self._load(tmp_path)
+ model._is_compiled = False
+ model._forward = MagicMock()
- with pytest.raises(ValueError, match="separately"):
- model.embed([{"text": "a red square", "image": self._uri("red")}])
+ with pytest.raises(ValueError, match="position table limit of 8"):
+ model.embed(["one two three four five six seven eight"], truncation=False)
+
+ model._forward.assert_not_called()
+
+ def test_image_inputs_are_rejected(self, tmp_path):
+ model, _, _ = self._load(tmp_path)
+
+ with pytest.raises(ValueError, match="does not support image inputs"):
+ model.embed([{"image": IMAGE_DATA_URI}])
diff --git a/tests/test_encoder_quantization.py b/tests/test_encoder_quantization.py
new file mode 100644
index 0000000000..e7995eed30
--- /dev/null
+++ b/tests/test_encoder_quantization.py
@@ -0,0 +1,94 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Strict-loading regressions for legacy encoder quantization metadata."""
+
+import json
+from types import SimpleNamespace
+from unittest.mock import patch
+
+import mlx.core as mx
+import mlx.nn as nn
+import numpy as np
+import pytest
+from mlx.utils import tree_flatten
+from mlx_vlm.models.modernbert.config import ModelConfig
+from mlx_vlm.models.modernbert.modernbert import Model, SequenceClassificationModel
+
+from omlx.models.embedding import MLXEmbeddingModel
+from omlx.models.reranker import MLXRerankerModel
+from omlx.utils.model_loading import normalize_encoder_quantization_config
+
+
+@pytest.mark.parametrize(
+ ("method", "group_size", "bits", "mode"),
+ [
+ ("compressed-tensors", 32, 4, "affine"),
+ ("mxfp4", 32, 4, "mxfp4"),
+ ("nvfp4", 16, 4, "nvfp4"),
+ ("mxfp8", 32, 8, "mxfp8"),
+ ],
+)
+@pytest.mark.parametrize("nested", [False, True])
+@pytest.mark.parametrize("reranker", [False, True])
+def test_legacy_quantization_metadata_loads_packed_checkpoint(
+ tmp_path, method, group_size, bits, mode, nested, reranker
+):
+ config = {
+ "architectures": [
+ "ModernBertForSequenceClassification" if reranker else "ModernBertModel"
+ ],
+ "model_type": "modernbert",
+ "vocab_size": 64,
+ "hidden_size": 64,
+ "num_hidden_layers": 1,
+ "intermediate_size": 128,
+ "num_attention_heads": 2,
+ }
+ model_class = SequenceClassificationModel if reranker else Model
+ reference = model_class(ModelConfig.from_dict(config))
+ nn.quantize(reference, group_size=group_size, bits=bits, mode=mode)
+ reference.eval()
+ mx.save_safetensors(
+ str(tmp_path / "model.safetensors"), dict(tree_flatten(reference.parameters()))
+ )
+ metadata = {"quantization_config": {"quant_method": method}}
+ config.update({"text_config": metadata} if nested else metadata)
+ (tmp_path / "config.json").write_text(json.dumps(config))
+
+ wrapper = (
+ MLXRerankerModel(str(tmp_path))
+ if reranker
+ else MLXEmbeddingModel(str(tmp_path))
+ )
+ module = "reranker" if reranker else "embedding"
+ with (
+ patch(
+ f"omlx.models.{module}.load_processor",
+ return_value=SimpleNamespace(tokenizer=object()),
+ ),
+ patch.object(wrapper, "_try_compile", return_value=False),
+ ):
+ wrapper.load()
+
+ ids = mx.array([[1, 2, 3]])
+ mask = mx.ones_like(ids)
+ expected = reference(ids, attention_mask=mask)
+ actual = wrapper.model(ids, attention_mask=mask)
+ field = "logits" if reranker else "text_embeds"
+ np.testing.assert_allclose(
+ np.array(getattr(actual, field)),
+ np.array(getattr(expected, field)),
+ atol=1e-5,
+ )
+
+
+@pytest.mark.parametrize("quantization", [None, {"group_size": 64, "bits": 8}])
+def test_existing_quantization_entry_is_authoritative(quantization):
+ config = {
+ "quantization": quantization,
+ "quantization_config": {"quant_method": "mxfp4"},
+ }
+
+ normalize_encoder_quantization_config(config)
+
+ assert config["quantization"] is quantization
+ assert config["quantization_config"] == {"quant_method": "mxfp4"}
diff --git a/tests/test_mlx_embeddings_compat.py b/tests/test_mlx_embeddings_compat.py
deleted file mode 100644
index d4e9217e66..0000000000
--- a/tests/test_mlx_embeddings_compat.py
+++ /dev/null
@@ -1,343 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-"""Tests for mlx-embeddings compatibility patches."""
-
-import importlib.util
-import sys
-import types
-from pathlib import Path
-
-import pytest
-from PIL import Image
-
-from omlx.exceptions import InvalidRequestError
-from omlx.models.mlx_embeddings_compat import (
- _build_contract_compliant_processor,
- _flatten_images,
-)
-
-IMAGE_DATA_URI = (
- "data:image/png;base64,"
- "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/"
- "58BAwAI/AL+26JNFgAAAABJRU5ErkJggg=="
-)
-
-
-def _install_fake_module(monkeypatch, name, module):
- monkeypatch.setitem(sys.modules, name, module)
- return module
-
-
-def test_qwen3_vl_auto_image_processor_uses_mlx_vlm_torch_free_loader(monkeypatch):
- """Qwen3-VL Processor should use mlx-vlm's torch-free image processor."""
- processor_module = types.ModuleType("mlx_embeddings.models.qwen3_vl.processor")
-
- class TorchBoundAutoImageProcessor:
- @classmethod
- def from_pretrained(cls, *args, **kwargs):
- raise RuntimeError("torch/torchvision required")
-
- processor_module.AutoImageProcessor = TorchBoundAutoImageProcessor
-
- qwen3_vl_package = types.ModuleType("mlx_embeddings.models.qwen3_vl")
- qwen3_vl_package.processor = processor_module
-
- _install_fake_module(
- monkeypatch, "mlx_embeddings", types.ModuleType("mlx_embeddings")
- )
- _install_fake_module(
- monkeypatch, "mlx_embeddings.models", types.ModuleType("mlx_embeddings.models")
- )
- _install_fake_module(
- monkeypatch, "mlx_embeddings.models.qwen3_vl", qwen3_vl_package
- )
- _install_fake_module(
- monkeypatch, "mlx_embeddings.models.qwen3_vl.processor", processor_module
- )
-
- mlx_vlm_processing = types.ModuleType("mlx_vlm.models.qwen3_vl.processing_qwen3_vl")
- captured = {}
-
- class TorchFreeImageProcessor:
- def __init__(self, **kwargs):
- captured["kwargs"] = kwargs
-
- def fake_image_kwargs(model_path, default_patch_size=16):
- captured["model_path"] = model_path
- captured["default_patch_size"] = default_patch_size
- return {"patch_size": default_patch_size, "merge_size": 2}
-
- mlx_vlm_processing.Qwen3VLImageProcessor = TorchFreeImageProcessor
- mlx_vlm_processing._qwen_vl_image_kwargs = fake_image_kwargs
-
- _install_fake_module(monkeypatch, "mlx_vlm", types.ModuleType("mlx_vlm"))
- _install_fake_module(
- monkeypatch, "mlx_vlm.models", types.ModuleType("mlx_vlm.models")
- )
- _install_fake_module(
- monkeypatch,
- "mlx_vlm.models.qwen3_vl",
- types.ModuleType("mlx_vlm.models.qwen3_vl"),
- )
- _install_fake_module(
- monkeypatch,
- "mlx_vlm.models.qwen3_vl.processing_qwen3_vl",
- mlx_vlm_processing,
- )
-
- module_path = (
- Path(__file__).resolve().parents[1] / "omlx/models/mlx_embeddings_compat.py"
- )
- spec = importlib.util.spec_from_file_location(
- "omlx.models.mlx_embeddings_compat_under_test", module_path
- )
- mlx_embeddings_compat = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(mlx_embeddings_compat)
-
- monkeypatch.setattr(mlx_embeddings_compat, "_QWEN3_VL_PROCESSOR_PATCHED", False)
-
- mlx_embeddings_compat.patch_qwen3_vl_processor_for_torch_free_image_loading()
-
- image_processor = processor_module.AutoImageProcessor.from_pretrained(
- "/models/Qwen3-VL-Embedding-8B-8bit-mlx",
- trust_remote_code=True,
- local_files_only=True,
- use_fast=False,
- )
-
- assert isinstance(image_processor, TorchFreeImageProcessor)
- assert captured["model_path"] == "/models/Qwen3-VL-Embedding-8B-8bit-mlx"
- assert captured["default_patch_size"] == 16
- assert captured["kwargs"] == {"patch_size": 16, "merge_size": 2}
-
-
-def test_qwen3_vl_build_processor_gets_multimodal_token_id_fields(monkeypatch):
- """Qwen3-VL ProcessorMixin fields should exist when __init__ is bypassed."""
- processor_module = types.ModuleType("mlx_embeddings.models.qwen3_vl.processor")
-
- class TorchBoundAutoImageProcessor:
- @classmethod
- def from_pretrained(cls, *args, **kwargs):
- raise RuntimeError("torch/torchvision required")
-
- class ManuallyBuiltProcessor:
- image_token_id = 151655
- video_token_id = 151656
-
- class MlxEmbeddingsProcessor:
- @staticmethod
- def _build_processor(tokenizer, image_processor):
- del tokenizer, image_processor
- return ManuallyBuiltProcessor()
-
- processor_module.AutoImageProcessor = TorchBoundAutoImageProcessor
- processor_module.Processor = MlxEmbeddingsProcessor
-
- qwen3_vl_package = types.ModuleType("mlx_embeddings.models.qwen3_vl")
- qwen3_vl_package.processor = processor_module
-
- _install_fake_module(
- monkeypatch, "mlx_embeddings", types.ModuleType("mlx_embeddings")
- )
- _install_fake_module(
- monkeypatch, "mlx_embeddings.models", types.ModuleType("mlx_embeddings.models")
- )
- _install_fake_module(
- monkeypatch, "mlx_embeddings.models.qwen3_vl", qwen3_vl_package
- )
- _install_fake_module(
- monkeypatch, "mlx_embeddings.models.qwen3_vl.processor", processor_module
- )
-
- mlx_vlm_processing = types.ModuleType("mlx_vlm.models.qwen3_vl.processing_qwen3_vl")
-
- class TorchFreeImageProcessor:
- pass
-
- mlx_vlm_processing.Qwen3VLImageProcessor = TorchFreeImageProcessor
- mlx_vlm_processing._qwen_vl_image_kwargs = lambda *args, **kwargs: {}
-
- _install_fake_module(monkeypatch, "mlx_vlm", types.ModuleType("mlx_vlm"))
- _install_fake_module(
- monkeypatch, "mlx_vlm.models", types.ModuleType("mlx_vlm.models")
- )
- _install_fake_module(
- monkeypatch,
- "mlx_vlm.models.qwen3_vl",
- types.ModuleType("mlx_vlm.models.qwen3_vl"),
- )
- _install_fake_module(
- monkeypatch,
- "mlx_vlm.models.qwen3_vl.processing_qwen3_vl",
- mlx_vlm_processing,
- )
-
- module_path = (
- Path(__file__).resolve().parents[1] / "omlx/models/mlx_embeddings_compat.py"
- )
- spec = importlib.util.spec_from_file_location(
- "omlx.models.mlx_embeddings_compat_under_test_mm_ids", module_path
- )
- mlx_embeddings_compat = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(mlx_embeddings_compat)
-
- monkeypatch.setattr(mlx_embeddings_compat, "_QWEN3_VL_PROCESSOR_PATCHED", False)
-
- mlx_embeddings_compat.patch_qwen3_vl_processor_for_torch_free_image_loading()
-
- processor = MlxEmbeddingsProcessor._build_processor(object(), object())
-
- assert processor.image_ids == [151655]
- assert processor.video_ids == [151656]
- assert processor.audio_ids == [None]
-
-
-def test_flatten_images_drops_empty_slots_of_a_nested_batch():
- """transformers batches visuals per sample, so text-only items arrive as empty slots."""
- assert _flatten_images([["a"], [], ["b", "c"]]) == ["a", "b", "c"]
- assert _flatten_images([[None], []]) == []
- assert _flatten_images([]) == []
- assert _flatten_images(None) == []
- assert _flatten_images("a") == ["a"]
-
-
-def _load_compat_module_for_posids_test(monkeypatch, model_module):
- """Install a fake mlx_embeddings package and load a fresh compat module over it."""
- qwen3_vl_package = types.ModuleType("mlx_embeddings.models.qwen3_vl")
- qwen3_vl_package.model = model_module
-
- _install_fake_module(
- monkeypatch, "mlx_embeddings", types.ModuleType("mlx_embeddings")
- )
- _install_fake_module(
- monkeypatch, "mlx_embeddings.models", types.ModuleType("mlx_embeddings.models")
- )
- _install_fake_module(
- monkeypatch, "mlx_embeddings.models.qwen3_vl", qwen3_vl_package
- )
-
- module_path = (
- Path(__file__).resolve().parents[1] / "omlx/models/mlx_embeddings_compat.py"
- )
- spec = importlib.util.spec_from_file_location(
- "omlx.models.mlx_embeddings_compat_under_test_posids", module_path
- )
- compat = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(compat)
- monkeypatch.setattr(compat, "_QWEN3_VL_POSIDS_PATCHED", False)
- return compat
-
-
-def _fake_qwen3_vl_model_module(calls):
- """Stand-in for mlx_embeddings.models.qwen3_vl.model reproducing the #3731 crash.
-
- The 3-index re-slice of a cached 2-D position-id array raises the same
- "Too many indices for array with 2 dimensions" as mx.array indexing.
- """
-
- class LanguageModel:
- def __init__(self):
- self._position_ids = None
-
- class Model:
- def __init__(self):
- self.language_model = LanguageModel()
-
- def compute_qwen3_vl_hidden_states(
- model,
- input_ids,
- position_ids=None,
- **kwargs,
- ):
- del kwargs
- if position_ids is None:
- if model.language_model._position_ids is not None:
- position_ids = model.language_model._position_ids[
- :, :, : len(input_ids)
- ]
- else:
- position_ids = "recomputed"
- model.language_model._position_ids = position_ids
- calls.append(position_ids)
- return position_ids
-
- module = types.ModuleType("mlx_embeddings.models.qwen3_vl.model")
- module.Model = Model
- module.compute_qwen3_vl_hidden_states = compute_qwen3_vl_hidden_states
- return module
-
-
-def test_qwen3_vl_posids_patch_recomputes_after_2d_cache(monkeypatch):
- """A cached 2-D position-id array must not be re-sliced as 3-D (#3731)."""
- calls = []
- model_module = _fake_qwen3_vl_model_module(calls)
- compat = _load_compat_module_for_posids_test(monkeypatch, model_module)
-
- compat.patch_qwen3_vl_position_ids_recompute()
- model = model_module.Model()
-
- # First request populates the cache with a 2-D array, as mlx-vlm's
- # get_rope_index now returns for text-only inputs.
- model.language_model._position_ids = [[0, 1, 2]]
- model_module.compute_qwen3_vl_hidden_states(model, [0, 1, 2])
- # The next request previously crashed on the stale 3-D re-slice.
- model_module.compute_qwen3_vl_hidden_states(model, [0, 1])
-
- assert calls == ["recomputed", "recomputed"]
-
-
-def test_qwen3_vl_posids_patch_is_idempotent_and_keeps_explicit_position_ids(
- monkeypatch,
-):
- """The wrapper must survive repeat patching and pass explicit position_ids through."""
- calls = []
- model_module = _fake_qwen3_vl_model_module(calls)
- compat = _load_compat_module_for_posids_test(monkeypatch, model_module)
-
- original = model_module.compute_qwen3_vl_hidden_states
- compat.patch_qwen3_vl_position_ids_recompute()
- first = model_module.compute_qwen3_vl_hidden_states
- compat.patch_qwen3_vl_position_ids_recompute()
-
- assert first is not original
- assert model_module.compute_qwen3_vl_hidden_states is first
-
- model = model_module.Model()
- model_module.compute_qwen3_vl_hidden_states(model, [0, 1], position_ids="explicit")
- assert calls == ["explicit"]
-
-
-def test_contract_compliant_processor_loads_images_before_the_torch_free_port():
- """A data URI must arrive as an image, since the port only knows file paths."""
- seen = {}
-
- class TorchFreeImageProcessor:
- def __call__(self, images, **kwargs):
- seen["images"] = images
- seen["kwargs"] = kwargs
- return {"pixel_values": images}
-
- processor = _build_contract_compliant_processor(TorchFreeImageProcessor)()
-
- fetched = processor.fetch_images([[IMAGE_DATA_URI], []])
- assert isinstance(fetched[0][0], Image.Image)
- assert fetched[1] == []
-
- processor(fetched, do_rescale=True)
- assert len(seen["images"]) == 1
- assert isinstance(seen["images"][0], Image.Image)
- assert seen["kwargs"] == {"do_rescale": True}
-
-
-def test_contract_compliant_processor_keeps_rejecting_non_data_uri_images():
- """Loading stays on omlx's data-URI-only path, so paths and URLs are still refused."""
-
- class TorchFreeImageProcessor:
- def __call__(self, images, **kwargs):
- return images
-
- processor = _build_contract_compliant_processor(TorchFreeImageProcessor)()
-
- with pytest.raises(InvalidRequestError):
- processor.fetch_images(["/etc/passwd"])
- with pytest.raises(InvalidRequestError):
- processor.fetch_images(["https://example.com/cat.png"])
diff --git a/tests/test_modernbert_attention.py b/tests/test_modernbert_attention.py
index 8d28c52662..0ab60896df 100644
--- a/tests/test_modernbert_attention.py
+++ b/tests/test_modernbert_attention.py
@@ -5,12 +5,10 @@
import mlx.core as mx
import pytest
-from mlx_embeddings.models.modernbert import Model, ModelArgs, ModernBertModel
+from mlx_vlm.models.modernbert.config import ModelConfig
+from mlx_vlm.models.modernbert.modernbert import Model
-from omlx.patches.modernbert_attention import (
- _update_attention_mask,
- patch_modernbert_attention,
-)
+from omlx.patches.modernbert_attention import _masks, patch_modernbert_attention
@pytest.mark.parametrize("length", [64, 128, 255, 256, 257, 288])
@@ -19,13 +17,7 @@ def test_padded_attention_is_finite_and_matches_single(length, dtype):
mx.random.seed(3507)
short = 5
mask = mx.array([[1] * short + [0] * (length - short), [1] * length])
- config = SimpleNamespace(
- config=SimpleNamespace(local_attention=128),
- embeddings=SimpleNamespace(
- norm=SimpleNamespace(weight=mx.ones(64, dtype=dtype))
- ),
- )
- masks = _update_attention_mask(config, mask)
+ masks = _masks(SimpleNamespace(local_attention=128), mask, dtype)
q, k, v = [mx.random.normal((2, 1, length, 64)).astype(dtype) for _ in range(3)]
for additive in masks:
output = mx.fast.scaled_dot_product_attention(
@@ -43,13 +35,12 @@ def test_padded_attention_is_finite_and_matches_single(length, dtype):
def test_patch_is_idempotent_and_scoped(monkeypatch):
- original = ModernBertModel._update_attention_mask
- monkeypatch.setattr(ModernBertModel, "_update_attention_mask", original)
- unrelated = SimpleNamespace(model=SimpleNamespace())
- patch_modernbert_attention(unrelated)
- assert ModernBertModel._update_attention_mask is original
+ monkeypatch.setattr(Model, "_masks", Model._masks)
+ original = Model._masks
+ patch_modernbert_attention(SimpleNamespace())
+ assert Model._masks is original
model = Model(
- ModelArgs(
+ ModelConfig(
model_type="modernbert",
vocab_size=128,
hidden_size=64,
@@ -60,4 +51,4 @@ def test_patch_is_idempotent_and_scoped(monkeypatch):
)
patch_modernbert_attention(model)
patch_modernbert_attention(model)
- assert ModernBertModel._update_attention_mask is _update_attention_mask
+ assert Model._masks is _masks
diff --git a/tests/test_reranker_causal_lm.py b/tests/test_reranker_causal_lm.py
index f4f4160540..ef7baa4f69 100644
--- a/tests/test_reranker_causal_lm.py
+++ b/tests/test_reranker_causal_lm.py
@@ -19,44 +19,58 @@
class TestXLMRobertaReranker:
- """Tests for native XLM-RoBERTa sequence-classification rerankers."""
+ """XLM-RoBERTa sequence-classification rerankers served via mlx-vlm."""
+
+ _CONFIG = {
+ "model_type": "xlm-roberta",
+ "architectures": ["XLMRobertaForSequenceClassification"],
+ "hidden_size": 8,
+ "num_hidden_layers": 1,
+ "vocab_size": 16,
+ "num_attention_heads": 2,
+ "intermediate_size": 16,
+ "max_position_embeddings": 16,
+ "pad_token_id": 1,
+ "num_labels": 1,
+ }
@pytest.mark.skipif(not HAS_MLX, reason="MLX not available")
- def test_load_xlm_roberta_switches_to_eval_mode(self, tmp_path):
- """Native reranker load must disable dropout for deterministic scores."""
+ def test_xlm_roberta_routes_to_mlx_vlm_and_scores_deterministically(
+ self, tmp_path
+ ):
+ """The RoBERTa head comes from mlx-vlm, and scoring is deterministic.
+
+ Dropout used to make rerankers non-deterministic when the encoder kept
+ dropout modules; mlx-vlm's encoder builds none, so repeated eager
+ scoring must agree exactly.
+ """
from mlx.utils import tree_flatten
- from omlx.models.xlm_roberta import Model, ModelArgs
+ from mlx_vlm.models.xlm_roberta import ModelConfig, SequenceClassificationModel
- config = {
- "model_type": "xlm-roberta",
- "architectures": ["XLMRobertaForSequenceClassification"],
- "hidden_size": 4,
- "num_hidden_layers": 1,
- "vocab_size": 16,
- "num_attention_heads": 1,
- "intermediate_size": 8,
- "max_position_embeddings": 8,
- "attention_probs_dropout_prob": 0.5,
- "hidden_dropout_prob": 0.5,
- "classifier_dropout": 0.5,
- "pad_token_id": 1,
- "num_labels": 1,
- }
+ config = dict(self._CONFIG)
(tmp_path / "config.json").write_text(json.dumps(config))
- source_model = Model(ModelArgs(**config))
+ source_model = SequenceClassificationModel(ModelConfig.from_dict(config))
mx.save_safetensors(
str(tmp_path / "model.safetensors"),
{name: value for name, value in tree_flatten(source_model.parameters())},
)
loader = MLXRerankerModel(str(tmp_path))
- with patch(
- "transformers.AutoTokenizer.from_pretrained",
- return_value=MagicMock(),
- ):
- loaded_model, _ = loader._load_xlm_roberta()
+ with patch("omlx.models.reranker.load_processor", return_value=MagicMock()):
+ loader.load()
+
+ from mlx_vlm.models.xlm_roberta.xlm_roberta import SequenceClassificationModel
+
+ assert isinstance(loader.model, SequenceClassificationModel)
+ assert loader._num_labels == 1
- assert loaded_model.training is False
+ loader._is_compiled = False
+ loader._compiled_seq_logits = None
+ input_ids = mx.array([[1, 5, 6, 7, 2], [1, 8, 9, 3, 3]])
+ attention_mask = mx.array([[1, 1, 1, 1, 1], [1, 1, 1, 1, 0]])
+ first = loader._seq_classification_logits(input_ids, attention_mask)
+ second = loader._seq_classification_logits(input_ids, attention_mask)
+ assert np.array_equal(np.array(first), np.array(second))
def test_max_length_defaults_to_tokenizer_limit_and_is_capped(self, tmp_path):
"""Encoder rerankers default to the tokenizer limit and never exceed it."""
diff --git a/tests/test_reranker_modernbert_attention_patch.py b/tests/test_reranker_modernbert_attention_patch.py
index b2a6ca1201..ebde4a97e4 100644
--- a/tests/test_reranker_modernbert_attention_patch.py
+++ b/tests/test_reranker_modernbert_attention_patch.py
@@ -1,28 +1,35 @@
# SPDX-License-Identifier: Apache-2.0
"""Regression: a ModernBERT reranker must get the finite attention-mask patch.
-The stock mlx-embeddings mask uses -1e9, which overflows to -inf in fp16 and
-makes fully padded (short) queries produce NaN. omlx already patches this for
-embeddings (issue #3507); the reranker's mlx-embeddings branch must do the same.
+The stock mlx-vlm mask uses -1e9, which overflows to -inf in fp16 and makes
+fully padded (short) queries produce NaN. omlx already patches this for
+embeddings (issue #3507); the reranker's sequence-classification branch must do
+the same.
"""
import json
from types import SimpleNamespace
+from unittest.mock import patch
+
+import mlx.core as mx
+import numpy as np
+import pytest
+from mlx.utils import tree_flatten
+from mlx_vlm.models.modernbert.config import ModelConfig
+from mlx_vlm.models.modernbert.modernbert import SequenceClassificationModel
import omlx.models.reranker as reranker_module
from omlx.models.reranker import MLXRerankerModel
def test_modernbert_reranker_applies_finite_attention_patch(tmp_path, monkeypatch):
- loaded = SimpleNamespace(
- model=SimpleNamespace(),
- config=SimpleNamespace(num_labels=1),
- )
+ loaded = SimpleNamespace()
patched: list = []
monkeypatch.setattr(
reranker_module, "patch_modernbert_attention", lambda m: patched.append(m)
)
- monkeypatch.setattr("mlx_embeddings.load", lambda *a, **k: (loaded, object()))
+ monkeypatch.setattr(reranker_module, "load_encoder_model", lambda *a, **k: loaded)
+ monkeypatch.setattr(reranker_module, "load_processor", lambda *a, **k: object())
model_dir = tmp_path / "modernbert-reranker"
model_dir.mkdir()
@@ -38,3 +45,122 @@ def test_modernbert_reranker_applies_finite_attention_patch(tmp_path, monkeypatc
MLXRerankerModel(str(model_dir)).load()
assert patched == [loaded], "the reranker load path must patch ModernBERT attention"
+
+
+@pytest.mark.parametrize("trust_remote_code", [False, True])
+@pytest.mark.parametrize("num_labels", [1, 2])
+@pytest.mark.parametrize("compiled", [False, True])
+def test_modernbert_checkpoint_preserves_labels_activation_and_trust(
+ tmp_path, trust_remote_code, num_labels, compiled
+):
+ config = {
+ "architectures": ["ModernBertForSequenceClassification"],
+ "model_type": "modernbert",
+ "vocab_size": 32,
+ "hidden_size": 8,
+ "num_hidden_layers": 1,
+ "intermediate_size": 16,
+ "num_attention_heads": 2,
+ "id2label": {str(i): f"LABEL_{i}" for i in range(num_labels)},
+ }
+ (tmp_path / "config.json").write_text(json.dumps(config))
+ reference = SequenceClassificationModel(
+ ModelConfig.from_dict({**config, "num_labels": num_labels})
+ )
+ mx.save_safetensors(
+ str(tmp_path / "model.safetensors"), dict(tree_flatten(reference.parameters()))
+ )
+ processor = object()
+ model = MLXRerankerModel(str(tmp_path), trust_remote_code=trust_remote_code)
+ with patch.object(
+ reranker_module, "load_processor", return_value=processor
+ ) as load:
+ model.load()
+ load.assert_called_once_with(
+ tmp_path, add_detokenizer=False, trust_remote_code=trust_remote_code
+ )
+ assert model.num_labels == num_labels
+ assert model._is_compiled
+ model._is_compiled = compiled
+ ids = mx.array([[1, 2, 3], [4, 5, 0]])
+ mask = mx.array([[1, 1, 1], [1, 1, 0]])
+ logits = reference(ids, attention_mask=mask).logits
+ expected = mx.sigmoid(logits) if num_labels == 1 else mx.softmax(logits, axis=-1)
+ np.testing.assert_allclose(
+ np.array(model._seq_classification_logits(ids, mask)),
+ np.array(expected),
+ atol=1e-6,
+ )
+
+
+@pytest.mark.parametrize(
+ ("flags", "id2label", "expected_labels", "is_regression"),
+ [
+ ({"is_regression": True}, {"0": "LABEL_0", "1": "LABEL_1"}, 1, True),
+ (
+ {"pipeline_config": {"binary_sigmoid": True}},
+ {"0": "LABEL_0", "1": "LABEL_1"},
+ 1,
+ False,
+ ),
+ ({}, None, 1, False),
+ ],
+)
+@pytest.mark.parametrize("compiled", [False, True])
+def test_modernbert_single_output_flags_and_regression_scores(
+ tmp_path, flags, id2label, expected_labels, is_regression, compiled
+):
+ config = {
+ "architectures": ["ModernBertForSequenceClassification"],
+ "model_type": "modernbert",
+ "vocab_size": 32,
+ "hidden_size": 8,
+ "num_hidden_layers": 1,
+ "intermediate_size": 16,
+ "num_attention_heads": 2,
+ "id2label": id2label,
+ **flags,
+ }
+ (tmp_path / "config.json").write_text(json.dumps(config))
+ reference = SequenceClassificationModel(
+ ModelConfig.from_dict({**config, "num_labels": expected_labels})
+ )
+ mx.save_safetensors(
+ str(tmp_path / "model.safetensors"), dict(tree_flatten(reference.parameters()))
+ )
+ with patch.object(reranker_module, "load_processor", return_value=object()):
+ model = MLXRerankerModel(str(tmp_path))
+ model.load()
+
+ assert model.num_labels == expected_labels
+ assert model._is_regression is is_regression
+ model._is_compiled = compiled
+ ids = mx.array([[1, 2, 3]])
+ mask = mx.ones_like(ids)
+ logits = reference(ids, attention_mask=mask).logits
+ expected = logits if is_regression else mx.sigmoid(logits)
+ np.testing.assert_allclose(
+ np.array(model._seq_classification_logits(ids, mask)),
+ np.array(expected),
+ atol=1e-6,
+ )
+
+
+def test_modernbert_custom_model_code_is_rejected_before_loading(tmp_path):
+ (tmp_path / "config.json").write_text(
+ json.dumps(
+ {
+ "architectures": ["ModernBertForSequenceClassification"],
+ "model_type": "modernbert",
+ "model_file": "custom.py",
+ }
+ )
+ )
+ with (
+ patch.object(reranker_module, "load_encoder_model") as load_model,
+ patch.object(reranker_module, "load_processor") as load_processor,
+ pytest.raises(ValueError, match="Enable Trust Remote Code"),
+ ):
+ MLXRerankerModel(str(tmp_path)).load()
+ load_model.assert_not_called()
+ load_processor.assert_not_called()
diff --git a/tests/test_reranker_vl.py b/tests/test_reranker_vl.py
index cb2fd3a057..a3abd5aeb4 100644
--- a/tests/test_reranker_vl.py
+++ b/tests/test_reranker_vl.py
@@ -5,13 +5,7 @@
from unittest.mock import MagicMock, patch
import pytest
-
-try:
- import mlx.core as mx
-
- HAS_MLX = True
-except ImportError:
- HAS_MLX = False
+from mlx_vlm.server.reranking import RerankItem
from omlx.exceptions import InvalidRequestError
from omlx.models.reranker import (
@@ -73,11 +67,11 @@ def test_validate_rejects_vl_without_dir_hint(self, tmp_path):
class TestVLItemBuilder:
def test_str_becomes_text_dict(self, tmp_path):
model = MLXRerankerModel(str(tmp_path))
- assert model._build_vl_item("hello") == {"text": "hello"}
+ assert model._build_vl_item("hello") == RerankItem(text="hello")
def test_dict_text_only(self, tmp_path):
model = MLXRerankerModel(str(tmp_path))
- assert model._build_vl_item({"text": "hi"}) == {"text": "hi"}
+ assert model._build_vl_item({"text": "hi"}) == RerankItem(text="hi")
def test_dict_image_loads_via_load_image(self, tmp_path):
model = MLXRerankerModel(str(tmp_path))
@@ -87,7 +81,7 @@ def test_dict_image_loads_via_load_image(self, tmp_path):
) as mock_load:
result = model._build_vl_item({"image": IMAGE_DATA_URI})
mock_load.assert_called_once_with(IMAGE_DATA_URI, field="image")
- assert result == {"image": fake_img}
+ assert result == RerankItem(image=fake_img)
def test_dict_text_and_image(self, tmp_path):
model = MLXRerankerModel(str(tmp_path))
@@ -97,7 +91,7 @@ def test_dict_text_and_image(self, tmp_path):
) as mock_load:
result = model._build_vl_item({"text": "t", "image": IMAGE_DATA_URI})
mock_load.assert_called_once_with(IMAGE_DATA_URI, field="image")
- assert result == {"text": "t", "image": fake_img}
+ assert result == RerankItem(text="t", image=fake_img)
def test_dict_image_rejects_url(self, tmp_path):
model = MLXRerankerModel(str(tmp_path))
@@ -111,71 +105,98 @@ def test_empty_dict_raises(self, tmp_path):
class TestVLRerankScoring:
- @pytest.mark.skipif(not HAS_MLX, reason="MLX not available")
- def test_rerank_vl_wraps_process_output(self, tmp_path):
- """_rerank_vl sorts model.process() scores into RerankOutput."""
+ @pytest.mark.parametrize("trust_remote_code", [False, True])
+ def test_loader_preserves_remote_code_setting(self, tmp_path, trust_remote_code):
+ tmp_path = tmp_path / "qwen3-vl-reranker"
+ tmp_path.mkdir()
+ config = {
+ "architectures": ["Qwen3VLForConditionalGeneration"],
+ "model_type": "qwen3_vl",
+ }
+ (tmp_path / "config.json").write_text(json.dumps(config))
+ processor = MagicMock()
+ with (
+ patch(
+ "omlx.models.reranker.load_reranker",
+ return_value=(object(), processor),
+ ) as load,
+ patch("omlx.models.reranker.ensure_chat_template"),
+ ):
+ model = MLXRerankerModel(str(tmp_path), trust_remote_code=trust_remote_code)
+ model.load()
+ load.assert_called_once_with(tmp_path, trust_remote_code=trust_remote_code)
+ assert model._vl_config == config
+
+ def test_untrusted_custom_architecture_is_rejected_before_loading(self, tmp_path):
+ tmp_path = tmp_path / "qwen3-vl-reranker"
+ tmp_path.mkdir()
+ (tmp_path / "config.json").write_text(
+ json.dumps(
+ {
+ "architectures": ["Qwen3VLForConditionalGeneration"],
+ "model_type": "qwen3_vl",
+ "model_file": "custom.py",
+ }
+ )
+ )
+ with (
+ patch("omlx.models.reranker.load_reranker") as load,
+ pytest.raises(ValueError, match="Enable Trust Remote Code"),
+ ):
+ MLXRerankerModel(str(tmp_path)).load()
+ load.assert_not_called()
+
+ @staticmethod
+ def _vl_model(tmp_path):
model = MLXRerankerModel(str(tmp_path))
model._is_vl_reranker = True
model._loaded = True
-
- # Mock mlx-embeddings model: process() returns mx.array([0.2, 0.9, 0.5])
- mock_model = MagicMock()
- mock_model.process.return_value = mx.array([0.2, 0.9, 0.5])
- model.model = mock_model
+ model.model = MagicMock()
model.processor = MagicMock()
+ model._vl_config = {"model_type": "qwen3_vl"}
+ return model
- output = model._rerank_vl(
- query="cat",
- documents=["doc a", "doc b", "doc c"],
- max_length=8192,
- )
+ def test_rerank_vl_sorts_mlx_vlm_scores(self, tmp_path):
+ model = self._vl_model(tmp_path)
+ with patch(
+ "omlx.models.reranker.score_documents",
+ return_value=([0.2, 0.9, 0.5], 42),
+ ) as score:
+ output = model._rerank_vl(query="cat", documents=["doc a", "doc b", "doc c"])
assert isinstance(output, RerankOutput)
assert output.scores == pytest.approx([0.2, 0.9, 0.5], rel=1e-5)
- assert output.indices == [1, 2, 0] # sorted descending
- assert output.total_tokens == 0
-
- # process() called with the expected input dict shape
- call_args = mock_model.process.call_args
- inputs = call_args[0][0]
- assert "instruction" in inputs
- assert inputs["query"] == {"text": "cat"}
- assert inputs["documents"] == [
- {"text": "doc a"},
- {"text": "doc b"},
- {"text": "doc c"},
+ assert output.indices == [1, 2, 0]
+ assert output.total_tokens == 42
+ args = score.call_args[0]
+ assert args[:3] == (model.model, model.processor, model._vl_config)
+ assert args[3] == RerankItem(text="cat")
+ assert args[4] == [
+ RerankItem(text="doc a"),
+ RerankItem(text="doc b"),
+ RerankItem(text="doc c"),
]
- assert call_args[1]["processor"] is model.processor
- @pytest.mark.skipif(not HAS_MLX, reason="MLX not available")
def test_rerank_vl_with_image_documents(self, tmp_path):
- """_rerank_vl threads image dicts through _build_vl_item."""
- model = MLXRerankerModel(str(tmp_path))
- model._is_vl_reranker = True
- model._loaded = True
-
- mock_model = MagicMock()
- mock_model.process.return_value = mx.array([0.7, 0.3])
- model.model = mock_model
- model.processor = MagicMock()
-
+ model = self._vl_model(tmp_path)
fake_img = object()
- with patch("omlx.models.reranker.load_image", return_value=fake_img):
+ with (
+ patch("omlx.models.reranker.load_image", return_value=fake_img),
+ patch(
+ "omlx.models.reranker.score_documents", return_value=([0.7, 0.3], 9)
+ ) as score,
+ ):
output = model._rerank_vl(
query={"text": "a dog"},
- documents=[
- {"text": "desc"},
- {"image": IMAGE_DATA_URI},
- ],
- max_length=8192,
+ documents=[{"text": "desc"}, {"image": IMAGE_DATA_URI}],
)
assert output.indices == [0, 1]
- inputs = mock_model.process.call_args[0][0]
- assert inputs["documents"][0] == {"text": "desc"}
- assert inputs["documents"][1] == {"image": fake_img}
+ assert score.call_args[0][4] == [
+ RerankItem(text="desc"),
+ RerankItem(image=fake_img),
+ ]
- @pytest.mark.skipif(not HAS_MLX, reason="MLX not available")
@pytest.mark.parametrize(
("instruction", "expected"),
[
@@ -185,23 +206,19 @@ def test_rerank_vl_with_image_documents(self, tmp_path):
],
)
def test_rerank_forwards_instruction(self, tmp_path, instruction, expected):
- model = MLXRerankerModel(str(tmp_path))
- model._is_vl_reranker = True
- model._loaded = True
- model.model = MagicMock()
- model.model.process.return_value = mx.array([0.5])
- model.processor = MagicMock()
-
- model.rerank("cat", ["doc"], instruction=instruction)
+ model = self._vl_model(tmp_path)
+ with patch(
+ "omlx.models.reranker.score_documents", return_value=([0.5], 3)
+ ) as score:
+ model.rerank("cat", ["doc"], instruction=instruction)
- assert model.model.process.call_args[0][0]["instruction"] == expected
+ assert score.call_args[0][5] == expected
class TestRerankDispatchCoerce:
"""Regression: text-only reranker paths still receive strings even when
callers pass dict inputs (backwards compat for /v1/rerank dict docs)."""
- @pytest.mark.skipif(not HAS_MLX, reason="MLX not available")
def test_causal_lm_path_receives_strings_from_dict_inputs(self, tmp_path):
model = MLXRerankerModel(str(tmp_path))
model._is_causal_lm = True
From 6408f18d38def659d389086acdec399cacaa4d39 Mon Sep 17 00:00:00 2001
From: Mike Wallio
Date: Wed, 4 Nov 2026 09:15:01 -0500
Subject: [PATCH 07/24] feat(integrations): add native client catalogs and
offline Copilot launches
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
---
omlx/api/claude_gateway.py | 22 +
omlx/cli.py | 219 ++++++-
omlx/integrations/base.py | 17 +
omlx/integrations/claude.py | 20 +-
omlx/integrations/codex.py | 302 +++++++---
omlx/integrations/copilot.py | 3 +-
omlx/integrations/opencode.py | 324 +++++++++--
tests/test_cli.py | 742 ++++++++++++++++++++++-
tests/test_integrations.py | 1034 +++++++++++++++++++++++++++------
9 files changed, 2318 insertions(+), 365 deletions(-)
create mode 100644 omlx/api/claude_gateway.py
diff --git a/omlx/api/claude_gateway.py b/omlx/api/claude_gateway.py
new file mode 100644
index 0000000000..57550fb6cc
--- /dev/null
+++ b/omlx/api/claude_gateway.py
@@ -0,0 +1,22 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Claude Code discovery IDs scoped to the Claude gateway endpoints."""
+
+from typing import TypedDict
+
+CLAUDE_GATEWAY_PATH = "/claude"
+_MODEL_PREFIX = "omlx-claude/"
+
+
+class ClaudeGatewayModelInfo(TypedDict):
+ id: str
+ display_name: str
+ max_model_len: int | None
+
+
+def claude_gateway_model_id(model_id: str) -> str:
+ # Claude Code only discovers IDs containing "claude" or "anthropic".
+ return f"{_MODEL_PREFIX}{model_id}"
+
+
+def claude_gateway_served_id(model_id: str) -> str:
+ return model_id.removeprefix(_MODEL_PREFIX)
diff --git a/omlx/cli.py b/omlx/cli.py
index 7542551238..06db88b50f 100644
--- a/omlx/cli.py
+++ b/omlx/cli.py
@@ -476,15 +476,31 @@ def launch_command(args, extra_args: list[str] | None = None):
extra_args are unknown CLI tokens forwarded to the underlying tool binary
(e.g. ``-r`` / ``--resume `` for Claude Code).
"""
+ from urllib.parse import quote
+
import requests
from .integrations import IntegrationContext, get_integration, list_integrations
- from .integrations.base import bracket_host
+ from .integrations.base import IntegrationModel, bracket_host
+ from .integrations.codex import is_codex_chat_model
+ from .model_classification import TEXT_ONLY_CHAT_MODEL_TYPES
from .settings import GlobalSettings
def _optional_str(value) -> str | None:
return value if isinstance(value, str) and value else None
+ def _is_chat_model(info: dict) -> bool:
+ return info.get("model_type") in (None, "llm", "vlm") and info.get(
+ "engine_type"
+ ) not in (
+ "image",
+ "embedding",
+ "reranker",
+ "audio_stt",
+ "audio_tts",
+ "audio_sts",
+ )
+
tool_name = args.tool
if tool_name == "list":
@@ -567,6 +583,13 @@ def _optional_str(value) -> str | None:
resp = requests.get(f"{base_url}/v1/models/status", headers=headers, timeout=5)
if resp.ok:
for m in resp.json().get("models", []):
+ # Older servers report loader type as multimodal capability.
+ if (
+ m.get("model_type") == "vlm"
+ and (m.get("config_model_type") or "").lower().replace("-", "_")
+ in TEXT_ONLY_CHAT_MODEL_TYPES
+ ):
+ m = {**m, "model_type": "llm"}
if m_id := m.get("id"):
models_status_map[m_id] = m
if model_alias := m.get("model_alias"):
@@ -574,10 +597,8 @@ def _optional_str(value) -> str | None:
except Exception:
pass
- # Determine model. Explicit CLI tier flags bypass the picker; otherwise always
- # prompt interactively so the user's selection is honoured. Integrations
- # that resolve models server-side (requires_model_selection=False) skip
- # this block.
+ # These integrations use their native selector with a launch-time catalog.
+ native_model_picker = tool_name in ("codex", "codex_app", "copilot", "opencode")
model = args.model
if not model and not integration.requires_model_selection:
# The integration registers the server's whole model catalog, so
@@ -588,35 +609,113 @@ def _optional_str(value) -> str | None:
_optional_str(getattr(settings.integrations, f"{setting_tool}_model", None))
or ""
)
- if not model and (cli_opus_model or cli_sonnet_model or cli_haiku_model):
- model = cli_sonnet_model or cli_opus_model or cli_haiku_model or ""
- elif not model and integration.requires_model_selection:
- # Fetch available models from server
+ models_info_list = []
+ model_inventory = {}
+ models_discovery_succeeded = False
+ if native_model_picker or (
+ integration.requires_model_selection
+ and not model
+ and not (cli_opus_model or cli_sonnet_model or cli_haiku_model)
+ ):
try:
resp = requests.get(f"{base_url}/v1/models", headers=headers, timeout=5)
resp.raise_for_status()
- data = resp.json()
- models = [
- m["id"]
- for m in data.get("data", [])
- if m.get("model_type") in ("llm", "vlm", None)
- ]
- except Exception:
- models = []
-
- if not models:
- print("No models available. Load a model first.")
+ entries = resp.json()["data"]
+ if not isinstance(entries, list):
+ raise ValueError("model listing is not a list")
+ for entry in entries:
+ model_id = entry["id"]
+ if not isinstance(model_id, str) or not model_id:
+ raise ValueError("invalid model id")
+ info = {**entry, **models_status_map.get(model_id, {}), "id": model_id}
+ model_inventory[model_id] = info
+ if (is_codex_chat_model if native_model_picker else _is_chat_model)(
+ info
+ ):
+ models_info_list.append(info)
+ models_discovery_succeeded = True
+ except (requests.RequestException, ValueError, KeyError, TypeError) as exc:
+ if native_model_picker and (model or tool_name == "opencode"):
+ print(f"Warning: could not list oMLX models: {exc}")
+ if tool_name != "opencode":
+ print(
+ f"Only the requested model will be available in "
+ f"{integration.display_name}."
+ )
+ models_info_list = []
+ model_inventory = {}
+
+ if tool_name == "opencode" and not model and not models_discovery_succeeded:
+ model = _optional_str(
+ getattr(settings.integrations, "opencode_model", None)
+ ) or default_model
+
+ if native_model_picker:
+ if not is_codex_chat_model(
+ {**model_inventory.get(model, {}), **models_status_map.get(model, {})}
+ ):
+ print(
+ f"Cannot launch {integration.display_name} with non-chat model '{model}'."
+ )
sys.exit(1)
-
- if len(models) == 1:
- model = models[0]
+ if tool_name == "opencode" and model:
+ alias = _optional_str(models_status_map.get(model, {}).get("model_alias"))
+ if alias and (
+ not models_discovery_succeeded
+ or any(info["id"] == alias for info in models_info_list)
+ ):
+ model = alias
+ if not model and models_info_list:
+ settings_name = (
+ "codex_model" if tool_name == "codex_app" else f"{tool_name}_model"
+ )
+ saved_model = _optional_str(
+ getattr(settings.integrations, settings_name, None)
+ )
+ available_ids = {info["id"] for info in models_info_list}
+ saved_alias = (
+ _optional_str(
+ models_status_map.get(saved_model or "", {}).get("model_alias")
+ )
+ if tool_name == "opencode"
+ else None
+ )
+ default_alias = _optional_str(
+ models_status_map.get(default_model or "", {}).get("model_alias")
+ )
+ model = next(
+ (
+ candidate
+ for candidate in (
+ saved_model,
+ saved_alias,
+ default_alias,
+ default_model,
+ )
+ if candidate is not None and candidate in available_ids
+ ),
+ models_info_list[0]["id"],
+ )
+ print(
+ f"Using model: {model} "
+ f"(switch models inside {integration.display_name})"
+ )
+ elif not model and (cli_opus_model or cli_sonnet_model or cli_haiku_model):
+ model = cli_sonnet_model or cli_opus_model or cli_haiku_model or ""
+ elif not model and models_info_list:
+ if len(models_info_list) == 1:
+ model = models_info_list[0]["id"]
print(f"Using model: {model}")
else:
- models_info_list = [
- {"id": m_id, **models_status_map.get(m_id, {})} for m_id in models
- ]
model = integration.select_model(models_info_list, integration.display_name)
+ if not model and integration.requires_model_selection:
+ if tool_name == "opencode" and not models_discovery_succeeded:
+ print("No model selected; OpenCode will use its existing configuration.")
+ else:
+ print("No models available. Load a model first.")
+ sys.exit(1)
+
# Check if tool is installed
if not integration.is_installed():
print(f"{integration.display_name} is not installed.")
@@ -635,7 +734,10 @@ def _optional_str(value) -> str | None:
# disabled models, but this central check prevents --model and tier flags
# from bypassing the same restriction.
if tool_name == "claude":
- from .integrations.claude import claude_code_model_disabled_reason
+ from .integrations.claude import (
+ CLAUDE_CODE_MIN_CONTEXT_WINDOW,
+ claude_code_model_disabled_reason,
+ )
models_to_validate = [
("", model),
@@ -668,7 +770,7 @@ def _optional_str(value) -> str | None:
context_window = model_info.get("max_context_window")
if tool_name == "claude":
# Claude's context overrides are process-wide, including tier switches
- # and subagents. Do not advertise more than any configured model allows.
+ # and discovered models. Do not advertise more than any model allows.
context_windows = [
info["max_context_window"]
for model_id in (model, opus_model, sonnet_model, haiku_model)
@@ -676,6 +778,25 @@ def _optional_str(value) -> str | None:
and isinstance(info.get("max_context_window"), int)
and info["max_context_window"] > 0
]
+ from .api.claude_gateway import CLAUDE_GATEWAY_PATH
+
+ try:
+ resp = requests.get(
+ f"{base_url}{CLAUDE_GATEWAY_PATH}/v1/models",
+ headers=headers,
+ timeout=5,
+ )
+ resp.raise_for_status()
+ context_windows.extend(
+ entry["max_model_len"]
+ for entry in resp.json().get("data", [])
+ if isinstance(entry.get("max_model_len"), int)
+ and entry["max_model_len"] > 0
+ )
+ except (requests.RequestException, ValueError) as exc:
+ print(f"Warning: could not read Claude discovery context limits: {exc}")
+ print("Using the 48K discovery minimum as a conservative context limit.")
+ context_windows.append(CLAUDE_CODE_MIN_CONTEXT_WINDOW)
context_window = min(context_windows) if context_windows else None
ctx = IntegrationContext(
host=connect_host,
@@ -691,11 +812,53 @@ def _optional_str(value) -> str | None:
model_type=model_info.get("model_type"),
reasoning=model_info.get("enable_thinking"),
models_status_map=models_status_map,
+ models_discovery_succeeded=models_discovery_succeeded,
+ reasoning_effort_options=tuple(model_info.get("reasoning_effort_options") or ()),
+ reasoning_effort_default=model_info.get("reasoning_effort_default"),
tools_profile=getattr(args, "tools_profile", "coding"),
extra_args=tuple(extra_args or ()),
cross_session=getattr(args, "cross_session", False),
+ models=(
+ tuple(
+ IntegrationModel(
+ id=info["id"],
+ context_window=info.get("max_context_window")
+ or info.get("max_model_len"),
+ model_type=info.get("model_type"),
+ reasoning=info.get("enable_thinking"),
+ reasoning_effort_options=tuple(
+ info.get("reasoning_effort_options") or ()
+ ),
+ reasoning_effort_default=info.get("reasoning_effort_default"),
+ )
+ for info in models_info_list
+ )
+ if native_model_picker
+ else ()
+ ),
)
+ # Only warm a model the user explicitly requested; an auto-selected
+ # default may never be used once the user switches models in the client.
+ if (
+ native_model_picker
+ and args.model
+ and not (model_info.get("loaded") or model_info.get("is_loading"))
+ ):
+ load_model_id = model_info.get("source_model_id") or model_info.get("id") or model
+ try:
+ resp = requests.post(
+ f"{base_url}/v1/models/{quote(load_model_id, safe='')}/load",
+ headers=headers,
+ params={"wait": "false"},
+ timeout=3,
+ )
+ resp.raise_for_status()
+ print(f"Warming up model: {model} (loading in background)")
+ except requests.RequestException as exc:
+ print(f"Warning: could not warm up model '{model}': {exc}")
+ print("Launching anyway; oMLX will load the model on demand.")
+
# Launch
if model:
print(f"Launching {integration.display_name} with model {model}...")
diff --git a/omlx/integrations/base.py b/omlx/integrations/base.py
index 0f52a9ca71..e3e9fdae4d 100644
--- a/omlx/integrations/base.py
+++ b/omlx/integrations/base.py
@@ -1,3 +1,4 @@
+# SPDX-License-Identifier: Apache-2.0
"""Base class for external tool integrations."""
from __future__ import annotations
@@ -25,6 +26,18 @@ def bracket_host(host: str) -> str:
return host
+@dataclass(frozen=True)
+class IntegrationModel:
+ """A discoverable chat model and its per-model capabilities."""
+
+ id: str
+ context_window: int | None = None
+ model_type: str | None = None
+ reasoning: bool | None = None
+ reasoning_effort_options: tuple[str, ...] = ()
+ reasoning_effort_default: str | None = None
+
+
@dataclass(frozen=True)
class IntegrationContext:
"""Resolved launch/configuration inputs for an external tool integration."""
@@ -50,6 +63,10 @@ class IntegrationContext:
# read it instead of fetching the status again themselves; empty for
# direct constructions.
models_status_map: dict[str, dict] = field(default_factory=dict)
+ models: tuple[IntegrationModel, ...] = ()
+ models_discovery_succeeded: bool | None = None
+ reasoning_effort_options: tuple[str, ...] = ()
+ reasoning_effort_default: str | None = None
@property
def base_url(self) -> str:
diff --git a/omlx/integrations/claude.py b/omlx/integrations/claude.py
index 123a2f7b07..3a5b2882e8 100644
--- a/omlx/integrations/claude.py
+++ b/omlx/integrations/claude.py
@@ -1,3 +1,4 @@
+# SPDX-License-Identifier: Apache-2.0
"""Claude Code integration."""
from __future__ import annotations
@@ -6,6 +7,7 @@
import shutil
from pathlib import Path
+from omlx.api.claude_gateway import CLAUDE_GATEWAY_PATH, claude_gateway_model_id
from omlx.integrations.base import Integration, IntegrationContext
from omlx.utils.install import get_cli_command_prefix
@@ -93,7 +95,11 @@ def launch(self, ctx: IntegrationContext) -> None:
raise SystemExit(1)
env = self._scrubbed_env()
- env["ANTHROPIC_BASE_URL"] = ctx.base_url
+ for key in list(env):
+ if key.startswith("CLAUDE_CODE_USE_"):
+ del env[key]
+ env["ANTHROPIC_BASE_URL"] = f"{ctx.base_url}{CLAUDE_GATEWAY_PATH}"
+ env["CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"] = "1"
# Use the actual omlx API key so Claude Code authenticates correctly.
# Fallback to "omlx" only when no API key is configured (open server).
env["ANTHROPIC_AUTH_TOKEN"] = ctx.auth_token
@@ -104,7 +110,7 @@ def launch(self, ctx: IntegrationContext) -> None:
# Large timeout for local model inference (model loading + generation).
env["API_TIMEOUT_MS"] = "3000000"
if ctx.model:
- env["ANTHROPIC_MODEL"] = ctx.model
+ env["ANTHROPIC_MODEL"] = claude_gateway_model_id(ctx.model)
if ctx.cross_session:
# Cross-session messaging (ListAgents/SendMessage) needs telemetry
@@ -137,15 +143,17 @@ def launch(self, ctx: IntegrationContext) -> None:
haiku_model = ctx.haiku_model or ctx.model
if opus_model:
- env["ANTHROPIC_DEFAULT_OPUS_MODEL"] = opus_model
+ env["ANTHROPIC_DEFAULT_OPUS_MODEL"] = claude_gateway_model_id(opus_model)
if sonnet_model:
- env["ANTHROPIC_DEFAULT_SONNET_MODEL"] = sonnet_model
+ env["ANTHROPIC_DEFAULT_SONNET_MODEL"] = claude_gateway_model_id(
+ sonnet_model
+ )
if haiku_model:
- env["ANTHROPIC_DEFAULT_HAIKU_MODEL"] = haiku_model
+ env["ANTHROPIC_DEFAULT_HAIKU_MODEL"] = claude_gateway_model_id(haiku_model)
subagent_model = haiku_model or sonnet_model or opus_model
if subagent_model:
- env["CLAUDE_CODE_SUBAGENT_MODEL"] = subagent_model
+ env["CLAUDE_CODE_SUBAGENT_MODEL"] = claude_gateway_model_id(subagent_model)
if ctx.context_window:
# Claude Code warns at startup when this is outside [100k, 1M].
diff --git a/omlx/integrations/codex.py b/omlx/integrations/codex.py
index 32bcc3e842..99de4f5a8b 100644
--- a/omlx/integrations/codex.py
+++ b/omlx/integrations/codex.py
@@ -15,14 +15,201 @@
import tempfile
import threading
import time
+import tomllib
+from dataclasses import replace
from http.server import BaseHTTPRequestHandler
from pathlib import Path
from socketserver import TCPServer
-from omlx.integrations.base import Integration, IntegrationContext, chat_model_ids
+from omlx.integrations.base import (
+ Integration,
+ IntegrationContext,
+ IntegrationModel,
+ chat_model_ids,
+)
+from omlx.model_classification import EMBEDDING_MODEL_TYPES, is_helper_config_model_type
from omlx.utils.install import get_cli_command_prefix
-CODEX_CONFIG_PATH = Path.home() / ".codex" / "config.toml"
+CODEX_CONFIG_PATH = (
+ Path(os.environ.get("CODEX_HOME", Path.home() / ".codex")) / "config.toml"
+)
+
+_CODEX_INSTRUCTIONS = (
+ "You are a coding agent working in the user's local workspace. "
+ "Follow the user's instructions and applicable AGENTS.md files. "
+ "Inspect the workspace before making focused, maintainable changes. "
+ "Preserve unrelated work, verify changes with relevant tests, and report limitations."
+)
+
+
+def _is_reasoning_model(model_id: str, reasoning: bool | None) -> bool:
+ if reasoning is not None:
+ return reasoning
+ return bool(re.search(r"\b(thinking|o1|o3|r1)\b", model_id.lower()))
+
+
+def is_codex_chat_model(info: dict) -> bool:
+ """Exclude non-chat checkpoints even if the server reports a chat engine."""
+ config_type = info.get("config_model_type") or ""
+ normalized_type = config_type.lower().replace("-", "_")
+ return (
+ info.get("model_type") in (None, "llm", "vlm")
+ and info.get("engine_type") in (None, "batched", "vlm")
+ and not info.get("is_helper")
+ and not info.get("is_hidden")
+ and not info.get("unavailable_reason")
+ and not is_helper_config_model_type(config_type)
+ and normalized_type not in EMBEDDING_MODEL_TYPES
+ )
+
+
+def codex_model_catalog(
+ ctx: IntegrationContext,
+ model_ids: list[str] | None = None,
+ instructions: str = _CODEX_INSTRUCTIONS,
+) -> dict:
+ """Build Codex's ModelInfo catalog, not an OpenAI /v1/models response.
+
+ Keep capabilities conservative: thinking does not imply adjustable effort,
+ reasoning-summary generation, verbosity control, or server-side search.
+ """
+ if model_ids is not None:
+ known_models = {model.id: model for model in ctx.models}
+ models_from_status = []
+ for model_id in model_ids:
+ info = ctx.models_status_map.get(model_id, {})
+ model = known_models.get(model_id) or IntegrationModel(id=model_id)
+ models_from_status.append(
+ replace(
+ model,
+ context_window=info.get("max_context_window", model.context_window),
+ model_type=info.get("model_type", model.model_type),
+ reasoning=info.get("reasoning", model.reasoning),
+ reasoning_effort_options=tuple(
+ level
+ for level in info.get(
+ "reasoning_levels", model.reasoning_effort_options
+ ) or ()
+ if level not in ("off", "on")
+ ),
+ )
+ )
+ ctx = replace(ctx, models=tuple(models_from_status))
+ models = {
+ model.id: model
+ for model in ctx.models
+ if is_codex_chat_model(
+ {"model_type": model.model_type, **ctx.models_status_map.get(model.id, {})}
+ )
+ }
+ if (
+ ctx.model
+ and ctx.model not in models
+ and is_codex_chat_model(
+ {"model_type": ctx.model_type, **ctx.models_status_map.get(ctx.model, {})}
+ )
+ ):
+ models[ctx.model] = IntegrationModel(
+ id=ctx.model,
+ context_window=ctx.context_window,
+ model_type=ctx.model_type,
+ reasoning=ctx.reasoning,
+ reasoning_effort_options=ctx.reasoning_effort_options,
+ reasoning_effort_default=ctx.reasoning_effort_default,
+ )
+ ordered = sorted(models.values(), key=lambda model: model.id != ctx.model)
+ entries = []
+ for priority, model in enumerate(ordered):
+ reasoning = _is_reasoning_model(model.id, model.reasoning)
+ # Keep native effort metadata within Codex's fixed effort enum;
+ # custom template values cannot be sent by its selector.
+ efforts = (
+ [
+ effort
+ for effort in (
+ "none",
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max",
+ "ultra",
+ )
+ if effort in model.reasoning_effort_options
+ ]
+ if model.reasoning is not False
+ else []
+ )
+ default_effort = (
+ "medium" if "medium" in efforts else model.reasoning_effort_default
+ )
+ if efforts:
+ if default_effort not in efforts:
+ default_effort = efforts[0]
+ reasoning_levels = [
+ {"effort": effort, "description": f"Use {effort} reasoning effort"}
+ for effort in efforts
+ ]
+ elif not model.reasoning_effort_options:
+ default_effort = "high" if reasoning else None
+ # Desktop title generation filters fallback models by low effort.
+ # Accepting the value does not imply a template changes its budget.
+ reasoning_levels = [
+ {
+ "effort": effort,
+ "description": (
+ f"Request {effort} effort (ignored by templates "
+ "without effort controls)"
+ ),
+ }
+ for effort in ("low", "medium", "high")
+ ]
+ else:
+ default_effort = "high" if reasoning else None
+ reasoning_levels = (
+ [{"effort": "high", "description": "Use model thinking"}]
+ if reasoning
+ else []
+ )
+ # Status can be unavailable for inference-only API keys. Do not let
+ # Codex's large GPT context default overstate an unknown local limit.
+ context_window = (
+ model.context_window
+ if model.context_window is not None and model.context_window > 0
+ else 32768
+ )
+ entries.append(
+ {
+ "slug": model.id,
+ "display_name": model.id,
+ "description": "Local model served by oMLX",
+ "visibility": "list",
+ "supported_in_api": True,
+ "priority": priority,
+ "base_instructions": instructions,
+ "shell_type": "shell_command",
+ "context_window": context_window,
+ "input_modalities": (
+ ["text", "image"] if model.model_type == "vlm" else ["text"]
+ ),
+ "default_reasoning_level": default_effort,
+ "supported_reasoning_levels": reasoning_levels,
+ "supports_reasoning_summaries": False,
+ "supports_reasoning_summary_parameter": False,
+ "support_verbosity": False,
+ "supports_parallel_tool_calls": False,
+ "supports_search_tool": False,
+ "prefer_websockets": False,
+ "experimental_supported_tools": [],
+ "truncation_policy": {
+ "mode": "tokens",
+ "limit": min(10000, context_window // 4),
+ },
+ }
+ )
+ return {"models": entries}
+
# A slug Codex does not know, so it renders its built-in instructions.
_PROBE_MODEL = "omlx-instructions-probe"
@@ -67,6 +254,9 @@ def _provider_overrides(base_url: str) -> list[tuple[str, str]]:
("model_providers.omlx.name", json.dumps("oMLX")),
("model_providers.omlx.base_url", json.dumps(base_url)),
("model_providers.omlx.env_key", json.dumps("OMLX_API_KEY")),
+ ("model_providers.omlx.wire_api", json.dumps("responses")),
+ ("model_providers.omlx.requires_openai_auth", "false"),
+ ("model_providers.omlx.supports_websockets", "false"),
]
@@ -192,7 +382,11 @@ def codex_instructions(codex_bin: str | None, env: dict[str, str]) -> str:
def resolve_codex_models(ctx: IntegrationContext) -> tuple[list[str], str]:
"""Return the catalog model ids and the model Codex starts with."""
- model_ids = chat_model_ids(ctx)
+ model_ids = [
+ model_id
+ for model_id in chat_model_ids(ctx)
+ if is_codex_chat_model(ctx.models_status_map.get(model_id, {}))
+ ]
if not model_ids:
print("oMLX server reported no chat models. Load a model first.")
sys.exit(1)
@@ -210,54 +404,6 @@ def served_id(model_id: str) -> str:
return model_ids, model
-def codex_model_catalog(
- ctx: IntegrationContext, model_ids: list[str], instructions: str
-) -> dict:
- """Build ``model_catalog_json`` for the oMLX chat models.
-
- Fields not read from the server match Codex's metadata for unknown models.
- """
- entries = []
- for priority, model_id in enumerate(model_ids):
- info = ctx.models_status_map.get(model_id, {})
- # "off" and "on" toggle thinking; they are not effort levels.
- efforts = [
- level
- for level in info.get("reasoning_levels") or ()
- if level not in ("off", "on")
- ]
- entry = {
- "slug": model_id,
- "display_name": model_id,
- "description": "Local model served by oMLX.",
- "visibility": "list",
- "supported_in_api": True,
- "priority": priority,
- "base_instructions": instructions,
- "shell_type": "shell_command",
- # No default level: Codex sends no effort until the user picks one.
- "supported_reasoning_levels": [
- {"effort": effort, "description": f"{effort} reasoning effort"}
- for effort in efforts
- ],
- "support_verbosity": False,
- "apply_patch_tool_type": None,
- "truncation_policy": {"mode": "bytes", "limit": 10_000},
- "experimental_supported_tools": [],
- "include_apps_usage_instructions": False,
- }
- context_window = info.get("max_context_window")
- if isinstance(context_window, int) and context_window > 0:
- entry["context_window"] = context_window
- model_type = info.get("model_type")
- if model_type in ("llm", "vlm"):
- entry["input_modalities"] = (
- ["text", "image"] if model_type == "vlm" else ["text"]
- )
- entries.append(entry)
- return {"models": entries}
-
-
def write_codex_model_catalog(
codex_dir: Path,
tool: str,
@@ -281,21 +427,25 @@ def write_codex_model_catalog(
def write_codex_config(
- config_path: Path, ctx: IntegrationContext, catalog_path: Path
+ config_path: Path, ctx: IntegrationContext, catalog_path: Path | None = None
) -> None:
config_path.parent.mkdir(parents=True, exist_ok=True)
existing_content = ""
if config_path.exists():
# Create backup
- timestamp = int(time.time())
+ timestamp = time.time_ns()
backup = config_path.with_suffix(f".{timestamp}.bak")
- try:
- shutil.copy2(config_path, backup)
- existing_content = config_path.read_text(encoding="utf-8")
- print(f"Backup: {backup}")
- except OSError as e:
- print(f"Warning: could not create backup or read config: {e}")
+ shutil.copy2(config_path, backup)
+ existing_content = config_path.read_text(encoding="utf-8")
+ print(f"Backup: {backup}")
+
+ # Refuse to rewrite invalid TOML, and back up before changing the catalog.
+ tomllib.loads(existing_content)
+ if catalog_path is None:
+ catalog_path = write_codex_model_catalog(
+ config_path.parent, "codex-app", ctx, [ctx.model], _CODEX_INSTRUCTIONS
+ )
# Parse existing config lines to preserve other settings
lines = existing_content.splitlines()
@@ -303,23 +453,32 @@ def write_codex_config(
in_any_section = False
in_omlx_section = False
- # Keys to override at the top level
+ # Model-specific limits and capabilities belong in the catalog so switching
+ # models does not retain the launch model's context or thinking settings.
top_level_overrides = {
- "model": f'"{ctx.model or "select-a-model"}"',
+ "model": json.dumps(ctx.model or "select-a-model", ensure_ascii=False),
"model_provider": '"omlx"',
- "model_catalog_json": json.dumps(str(catalog_path)),
+ "model_catalog_json": json.dumps(str(catalog_path), ensure_ascii=False),
+ }
+ managed_keys = {
+ "model_context_window",
+ "model_auto_compact_token_limit",
+ "model_reasoning_effort",
+ "model_reasoning_summary",
+ "model_supports_reasoning_summaries",
}
-
- # Left by older launches; the catalog now sets effort per model.
- managed_keys = {"model_reasoning_effort"}
seen_keys = set()
for line in lines:
stripped = line.strip()
- if stripped.startswith("[") and stripped.endswith("]"):
+ if stripped.startswith("["):
in_any_section = True
- in_omlx_section = stripped == "[model_providers.omlx]"
+ in_omlx_section = bool(
+ re.fullmatch(
+ r"\[model_providers\.omlx(?:\.[^\]]+)?\]\s*(?:#.*)?", stripped
+ )
+ )
# Handle top-level keys
if not in_any_section and "=" in stripped:
@@ -345,10 +504,15 @@ def write_codex_config(
# Append new oMLX provider section
new_lines.append("\n[model_providers.omlx]")
new_lines.append('name = "oMLX"')
- new_lines.append(f'base_url = "{ctx.openai_base_url}"')
+ new_lines.append(f"base_url = {json.dumps(ctx.openai_base_url)}")
new_lines.append('env_key = "OMLX_API_KEY"')
+ new_lines.append('wire_api = "responses"')
+ new_lines.append("requires_openai_auth = false")
+ new_lines.append("supports_websockets = false")
- config_path.write_text("\n".join(new_lines) + "\n", encoding="utf-8")
+ new_content = "\n".join(new_lines) + "\n"
+ tomllib.loads(new_content)
+ config_path.write_text(new_content, encoding="utf-8")
print(f"Config updated: {config_path}")
diff --git a/omlx/integrations/copilot.py b/omlx/integrations/copilot.py
index 6686deb9f0..3e3bcff390 100644
--- a/omlx/integrations/copilot.py
+++ b/omlx/integrations/copilot.py
@@ -102,7 +102,7 @@ def copilot_provider_config(ctx: IntegrationContext) -> dict:
class CopilotIntegration(Integration):
- """Copilot integration launching via the persistent provider registry."""
+ """Copilot integration launching offline via the persistent provider registry."""
def __init__(self):
super().__init__(
@@ -205,6 +205,7 @@ def launch(self, ctx: IntegrationContext) -> None:
if key.startswith("COPILOT_PROVIDER_") or key == "COPILOT_MODEL":
del env[key]
env["COPILOT_PROVIDERS_CONFIG"] = str(config_path)
+ env["COPILOT_OFFLINE"] = "true"
args = ["copilot", "--model", f"{PROVIDER_NAME}/{model}"]
args.extend(ctx.extra_args)
diff --git a/omlx/integrations/opencode.py b/omlx/integrations/opencode.py
index 7d548084e6..9c3c0b0dc6 100644
--- a/omlx/integrations/opencode.py
+++ b/omlx/integrations/opencode.py
@@ -1,18 +1,220 @@
+# SPDX-License-Identifier: Apache-2.0
"""OpenCode integration."""
from __future__ import annotations
+import json
import os
+import re
+import stat
+import subprocess
+import sys
from pathlib import Path
-from omlx.integrations.base import Integration, IntegrationContext
+import json5
+
+from omlx.integrations.base import (
+ Integration,
+ IntegrationContext,
+ IntegrationModel,
+ backup_then_write,
+)
+from omlx.integrations.codex import is_codex_chat_model
from omlx.utils.install import get_cli_command_prefix
+def _major_version() -> int:
+ try:
+ result = subprocess.run(
+ ["opencode", "--version"],
+ capture_output=True,
+ text=True,
+ timeout=5,
+ check=True,
+ )
+ match = re.search(r"\b(?:v)?(\d+)\.\d+", result.stdout)
+ if match:
+ return int(match.group(1))
+ except (OSError, subprocess.SubprocessError):
+ pass
+ raise RuntimeError("Cannot determine OpenCode version; config was not changed.")
+
+
+def _config_path() -> Path:
+ config_directory = os.environ.get("OPENCODE_CONFIG_DIR")
+ if config_directory is not None:
+ directory = Path(config_directory)
+ else:
+ config_home = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config")
+ directory = config_home / "opencode"
+ jsonc = directory / "opencode.jsonc"
+ return jsonc if jsonc.exists() or jsonc.is_symlink() else directory / "opencode.json"
+
+
+def opencode_provider_config(ctx: IntegrationContext) -> dict:
+ models = {
+ model.id: model
+ for model in ctx.models
+ if is_codex_chat_model(
+ {"model_type": model.model_type, **ctx.models_status_map.get(model.id, {})}
+ )
+ }
+ if (
+ ctx.model
+ and ctx.model not in models
+ and is_codex_chat_model(
+ {"model_type": ctx.model_type, **ctx.models_status_map.get(ctx.model, {})}
+ )
+ ):
+ models[ctx.model] = IntegrationModel(
+ id=ctx.model,
+ context_window=ctx.context_window,
+ model_type=ctx.model_type,
+ reasoning=ctx.reasoning,
+ )
+ entries = {}
+ for model in models.values():
+ inputs = ["text", "image"] if model.model_type == "vlm" else ["text"]
+ if ctx.models_status_map.get(model.id, {}).get("supports_audio_input") is True:
+ inputs.append("audio")
+ entry: dict = {
+ "name": model.id,
+ "capabilities": {"input": inputs, "output": ["text"], "tools": True},
+ }
+ if model.reasoning is not None:
+ entry["capabilities"]["reasoning"] = {"supported": model.reasoning}
+ window = model.context_window
+ max_tokens = ctx.models_status_map.get(model.id, {}).get("max_tokens")
+ if model.id == ctx.model and ctx.max_tokens is not None:
+ max_tokens = ctx.max_tokens
+ if isinstance(window, int) and not isinstance(window, bool) and window > 1:
+ output_limit = window * 3 // 4
+ if isinstance(max_tokens, int) and not isinstance(max_tokens, bool):
+ requested_output = max_tokens if max_tokens > 0 else 2048
+ else:
+ requested_output = 2048
+ entry["limit"] = {
+ "context": window,
+ "output": min(requested_output, output_limit),
+ }
+ elif window is not None:
+ print(
+ f"Warning: context window for {model.id} is unusable; "
+ "preserving any existing OpenCode limits."
+ )
+ entries[model.id] = entry
+ return {
+ "name": "oMLX",
+ "package": "@opencode/ai/providers/openai-compatible",
+ "settings": {"baseURL": ctx.openai_base_url, "apiKey": ctx.auth_token},
+ "models": entries,
+ }
+
+
+def _merge_config(existing: dict, updates: dict) -> dict:
+ merged = existing.copy()
+ for key, value in updates.items():
+ if isinstance(value, dict):
+ previous = existing.get(key, {})
+ if not isinstance(previous, dict):
+ raise ValueError(f"{key} must be an object")
+ merged[key] = _merge_config(previous, value)
+ else:
+ merged[key] = value
+ return merged
+
+
+def _read_config(path: Path) -> str | None:
+ try:
+ entry = path.lstat()
+ except FileNotFoundError:
+ return None
+ if stat.S_ISLNK(entry.st_mode):
+ raise ValueError(f"Refusing to overwrite symlink: {path}")
+ if (
+ not stat.S_ISREG(entry.st_mode)
+ or entry.st_uid != os.geteuid()
+ or entry.st_nlink != 1
+ ):
+ raise ValueError(
+ f"OpenCode config must be an owned, singly linked regular file: {path}"
+ )
+ return path.read_text(encoding="utf-8")
+
+
+def _write_config(path: Path, text: str, original: str | None) -> None:
+ if original is not None:
+ path.chmod(0o600)
+ if original == text:
+ return
+ backup_then_write(path, text, note="OpenCode config", mode=0o600)
+ path.chmod(0o600)
+
+
+def _preserve_model_metadata(
+ existing: dict, provider: dict, ctx: IntegrationContext
+) -> None:
+ providers = existing.get("providers")
+ if not isinstance(providers, dict) or not isinstance(providers.get("omlx"), dict):
+ return
+ old_models = providers["omlx"].get("models")
+ if not isinstance(old_models, dict):
+ return
+ model_types = {model.id: model.model_type for model in ctx.models}
+ if ctx.model and ctx.model not in model_types:
+ model_types[ctx.model] = ctx.model_type
+ for model_id, update in provider["models"].items():
+ old = old_models.get(model_id)
+ if not isinstance(old, dict):
+ continue
+ capabilities = update["capabilities"]
+ previous = old.get("capabilities")
+ retained = []
+ if "limit" not in update and "limit" in old:
+ retained.append("limit")
+ if (
+ "reasoning" not in capabilities
+ and isinstance(previous, dict)
+ and "reasoning" in previous
+ ):
+ retained.append("capabilities.reasoning")
+ if retained:
+ print(
+ f"Warning: no current metadata for {model_id} "
+ f"({', '.join(retained)}); preserving configured values, which may be stale."
+ )
+ if not isinstance(previous, dict):
+ continue
+ if isinstance(previous.get("tools"), bool):
+ capabilities.pop("tools")
+ audio_input = ctx.models_status_map.get(model_id, {}).get("supports_audio_input")
+ if model_types.get(model_id) is not None:
+ if (
+ not isinstance(audio_input, bool)
+ and isinstance(previous.get("input"), list)
+ and "audio" in previous["input"]
+ ):
+ capabilities["input"].append("audio")
+ continue
+ if "input" not in previous:
+ continue
+ inputs = previous["input"]
+ if isinstance(inputs, list) and isinstance(audio_input, bool):
+ capabilities["input"] = [item for item in inputs if item != "audio"]
+ if audio_input:
+ capabilities["input"].append("audio")
+ else:
+ capabilities.pop("input")
+ print(
+ f"Warning: no current model type for {model_id}; "
+ "preserving configured input capabilities, which may be stale."
+ )
+
+
class OpenCodeIntegration(Integration):
- """OpenCode integration that writes ~/.config/opencode/opencode.json."""
+ """Register the oMLX model catalog in OpenCode's global config."""
- CONFIG_PATH = Path.home() / ".config" / "opencode" / "opencode.json"
+ CONFIG_PATH: Path | None = None
def __init__(self):
super().__init__(
@@ -24,59 +226,79 @@ def __init__(self):
)
def get_command(self, ctx: IntegrationContext) -> str:
- return (
- f"{get_cli_command_prefix()} "
- f"launch opencode --model {ctx.model or 'select-a-model'}"
- )
-
- @staticmethod
- def _modalities_for_model(model_type: str | None) -> dict[str, list[str]]:
- """Build OpenCode modality metadata for the selected oMLX model."""
- input_modalities = ["text"]
- if model_type == "vlm":
- input_modalities.append("image")
- return {
- "input": input_modalities,
- "output": ["text"],
- }
+ command = f"{get_cli_command_prefix()} launch opencode"
+ return f"{command} --model {ctx.model}" if ctx.model else command
def configure(self, ctx: IntegrationContext) -> None:
- def updater(config: dict) -> None:
- config.setdefault("provider", {})
- provider_config = {
- "npm": "@ai-sdk/openai-compatible",
- "name": "oMLX",
- "options": {
- "baseURL": ctx.openai_base_url,
- },
- }
- if ctx.api_key:
- provider_config["options"]["apiKey"] = ctx.api_key
- if ctx.model:
- model_entry: dict = {
- "name": ctx.model,
- "modalities": self._modalities_for_model(ctx.model_type),
- }
- if ctx.supports_images:
- model_entry["attachment"] = True
- if ctx.context_window:
- model_entry["limit"] = {
- "context": ctx.context_window,
- "output": ctx.max_tokens or ctx.context_window,
- }
- provider_config["models"] = {ctx.model: model_entry}
- config["provider"]["omlx"] = provider_config
-
- # Set as default model
- if ctx.model:
- config["model"] = f"omlx/{ctx.model}"
-
- self._write_json_config(self.CONFIG_PATH, updater)
+ major = _major_version()
+ if major != 2:
+ raise ValueError(
+ f"Unsupported OpenCode major version {major}; "
+ "OpenCode 2 is required. Config was not changed."
+ )
+ path = self.CONFIG_PATH or _config_path()
+ original = _read_config(path)
+ try:
+ existing = json5.loads(
+ original if original is not None else "{}", allow_duplicate_keys=False
+ )
+ if not isinstance(existing, dict):
+ raise ValueError("config must contain one JSON object")
+ provider = opencode_provider_config(ctx)
+ updates: dict[str, object] = {"providers": {"omlx": provider}}
+ if ctx.model and ctx.model in provider["models"]:
+ updates["model"] = f"omlx/{ctx.model}"
+ _preserve_model_metadata(existing, provider, ctx)
+ updated = json.dumps(
+ _merge_config(existing, updates),
+ indent=2,
+ allow_nan=False,
+ ) + "\n"
+ except ValueError as exc:
+ raise ValueError(
+ f"Cannot update {path}: {exc}. Config was not changed."
+ ) from exc
+ if ctx.models_discovery_succeeded is False:
+ print(
+ "Warning: model discovery failed; preserving existing OpenCode models."
+ )
+ elif ctx.model and ctx.model not in {model.id for model in ctx.models}:
+ print(
+ f"Warning: model '{ctx.model}' was not in the chat catalog; "
+ "registering it with available metadata."
+ )
+ if any(
+ ctx.models_status_map.get(model_id, {}).get("model_type") == "vlm"
+ and "supports_audio_input" not in ctx.models_status_map[model_id]
+ for model_id in provider["models"]
+ ):
+ print(
+ "Warning: the running oMLX server does not report audio-input "
+ "capabilities. Restart it with the updated oMLX code, then run "
+ "'omlx launch opencode' again; updating the launcher alone is not enough."
+ )
+ _write_config(path, updated, original)
+ options = (
+ ctx.extra_args[: ctx.extra_args.index("--")]
+ if "--" in ctx.extra_args
+ else ctx.extra_args
+ )
+ if any(arg == "--server" or arg.startswith("--server=") for arg in options):
+ print(
+ "The selected OpenCode server may not use this local configuration "
+ "or its updated catalog; no server reload was attempted."
+ )
+ elif "--standalone" not in options:
+ print(
+ "OpenCode's running shared service may use a cached catalog. "
+ "Run 'opencode reload' to refresh it, or launch with -- --standalone. "
+ "Reload cancels pending permissions and forms across all loaded projects."
+ )
def launch(self, ctx: IntegrationContext) -> None:
self.configure(ctx)
-
env = self._scrubbed_env()
args = ["opencode", *ctx.extra_args]
-
+ sys.stdout.flush()
+ sys.stderr.flush()
os.execvpe("opencode", args, env)
diff --git a/tests/test_cli.py b/tests/test_cli.py
index a5c54b88e6..bd7ac5ecef 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -16,12 +16,20 @@
from unittest.mock import MagicMock, patch
import pytest
+import requests
from omlx._version import __version__
from omlx.cli import _migrate_saved_network_auth
from omlx.settings import GlobalSettings
+@pytest.fixture
+def empty_gateway_response():
+ response = MagicMock()
+ response.json.return_value = {"data": []}
+ return response
+
+
class TestCLIModule:
"""Tests for CLI module existence and basic functionality."""
@@ -423,6 +431,459 @@ def test_launch_lists_dsh(self):
class TestLaunchCommandFunction:
"""Tests for launch command runtime behavior."""
+ @pytest.fixture(autouse=True)
+ def mock_model_load(self):
+ with patch("requests.post") as post:
+ yield post
+
+ @pytest.mark.parametrize("tool", ["codex", "codex_app", "copilot", "opencode"])
+ @pytest.mark.parametrize(
+ ("requested_model", "saved_model", "default_model", "expected_model"),
+ [
+ (None, None, None, "vision-alias"),
+ (None, None, "text-model", "text-model"),
+ (None, None, "raw-vision-id", "vision-alias"),
+ (None, None, "vision-alias", "vision-alias"),
+ (None, "vision-alias", "text-model", "vision-alias"),
+ (None, "removed-model", "text-model", "text-model"),
+ (None, None, "removed-model", "vision-alias"),
+ (None, None, "hidden-model", "vision-alias"),
+ (None, None, "embedding-model", "vision-alias"),
+ ("text-model", "vision-alias", "vision-alias", "text-model"),
+ ("embedding-model", None, "text-model", None),
+ ("image-model", None, "text-model", None),
+ ("helper-model", None, "text-model", None),
+ ("embeddinggemma", None, "text-model", None),
+ ],
+ )
+ def test_codex_uses_native_picker_with_all_chat_models(
+ self,
+ tool,
+ requested_model,
+ saved_model,
+ default_model,
+ expected_model,
+ mock_model_load,
+ ):
+ from omlx.cli import launch_command
+
+ integration = MagicMock()
+ integration.display_name = "Codex"
+ integration.is_installed.return_value = True
+ health_response = MagicMock()
+ health_response.json.return_value = {"default_model": default_model}
+ status_response = MagicMock()
+ status_response.ok = True
+ status_response.json.return_value = {
+ "models": [
+ {
+ "id": "raw-vision-id",
+ "model_alias": "vision-alias",
+ "model_type": "vlm",
+ "max_context_window": 131072,
+ "enable_thinking": True,
+ "reasoning_effort_options": ["xhigh", "medium", "low"],
+ "reasoning_effort_default": "xhigh",
+ "loaded": False,
+ },
+ {
+ "id": "text-model",
+ "model_type": "llm",
+ "max_context_window": 8192,
+ "enable_thinking": False,
+ "loaded": True,
+ },
+ {"id": "embedding-model", "model_type": "embedding"},
+ {"id": "helper-model", "model_type": "llm", "is_helper": True},
+ {
+ "id": "embeddinggemma",
+ "model_type": "vlm",
+ "config_model_type": "embedding_gemma2",
+ },
+ {"id": "hidden-model", "model_type": "llm", "is_hidden": True},
+ {"id": "audio-model", "model_type": "stt"},
+ {"id": "image-model", "model_type": "llm", "engine_type": "image"},
+ ]
+ }
+ models_response = MagicMock()
+ models_response.json.return_value = {
+ "data": [
+ {"id": "vision-alias"},
+ {"id": "text-model"},
+ {"id": "embedding-model"},
+ {"id": "helper-model"},
+ {"id": "embeddinggemma"},
+ {"id": "audio-model"},
+ {"id": "image-model"},
+ ]
+ }
+ if default_model in ("raw-vision-id", "vision-alias"):
+ models_response.json.return_value["data"][:2] = [
+ {"id": "text-model"},
+ {"id": "vision-alias"},
+ ]
+ settings = SimpleNamespace(
+ server=SimpleNamespace(host="127.0.0.1", port=8000),
+ auth=SimpleNamespace(api_key="saved-key"),
+ integrations=SimpleNamespace(
+ codex_model=saved_model,
+ copilot_model=saved_model,
+ opencode_model=saved_model,
+ ),
+ claude_code=None,
+ )
+ args = argparse.Namespace(
+ tool=tool,
+ host=None,
+ port=None,
+ api_key=None,
+ model=requested_model,
+ )
+ with (
+ patch(
+ "requests.get",
+ side_effect=[health_response, status_response, models_response],
+ ) as get,
+ patch("omlx.integrations.get_integration", return_value=integration),
+ patch("omlx.settings.GlobalSettings.load", return_value=settings),
+ ):
+ if expected_model is None:
+ with pytest.raises(SystemExit) as exc:
+ launch_command(args)
+ assert exc.value.code == 1
+ else:
+ launch_command(args, extra_args=["--example-flag"])
+
+ integration.select_model.assert_not_called()
+ if expected_model is None:
+ integration.launch.assert_not_called()
+ mock_model_load.assert_not_called()
+ return
+ context = integration.launch.call_args.args[0]
+ assert context.model == expected_model
+ assert context.extra_args == ("--example-flag",)
+ catalog = {model.id: model for model in context.models}
+ assert set(catalog) == {"vision-alias", "text-model"}
+ assert catalog["vision-alias"].model_type == "vlm"
+ assert catalog["vision-alias"].context_window == 131072
+ assert catalog["vision-alias"].reasoning is True
+ assert catalog["vision-alias"].reasoning_effort_options == (
+ "xhigh",
+ "medium",
+ "low",
+ )
+ assert catalog["vision-alias"].reasoning_effort_default == "xhigh"
+ if expected_model == "vision-alias":
+ assert context.reasoning_effort_options == ("xhigh", "medium", "low")
+ assert context.reasoning_effort_default == "xhigh"
+ assert catalog["text-model"].context_window == 8192
+ assert catalog["text-model"].reasoning is False
+ assert get.call_args.kwargs["headers"] == {"Authorization": "Bearer saved-key"}
+ # Auto-selected defaults are not warmed; text-model is already loaded.
+ mock_model_load.assert_not_called()
+
+ @pytest.mark.parametrize(
+ ("requested", "saved_model", "default_model", "expected"),
+ [
+ ("requested", None, None, "requested"),
+ (None, "raw-model", None, "served-alias"),
+ (None, None, "raw-model", "served-alias"),
+ (None, None, None, ""),
+ ],
+ )
+ def test_opencode_failed_discovery_preserves_selection_without_inventing_catalog(
+ self, capsys, requested, saved_model, default_model, expected
+ ):
+ import requests
+
+ from omlx.cli import launch_command
+
+ integration = MagicMock()
+ integration.display_name = "OpenCode"
+ integration.is_installed.return_value = True
+ integration.requires_model_selection = True
+ health = MagicMock()
+ health.json.return_value = {"default_model": default_model}
+ status = MagicMock()
+ status.ok = bool(expected)
+ status.json.return_value = {
+ "models": [
+ {"id": "requested", "loaded": True},
+ {
+ "id": "raw-model",
+ "model_alias": "served-alias",
+ "model_type": "llm",
+ "loaded": True,
+ }
+ ]
+ }
+ settings = SimpleNamespace(
+ server=SimpleNamespace(host="127.0.0.1", port=8000),
+ auth=SimpleNamespace(api_key=""),
+ integrations=SimpleNamespace(opencode_model=saved_model),
+ claude_code=None,
+ )
+ args = argparse.Namespace(
+ tool="opencode", host=None, port=None, api_key=None, model=requested
+ )
+ with (
+ patch("requests.get", side_effect=[health, status, requests.Timeout()]),
+ patch("omlx.integrations.get_integration", return_value=integration),
+ patch("omlx.settings.GlobalSettings.load", return_value=settings),
+ ):
+ launch_command(args)
+ context = integration.launch.call_args.args[0]
+ assert context.model == expected
+ assert context.models == ()
+ assert context.models_discovery_succeeded is False
+ assert "could not list oMLX models" in capsys.readouterr().out
+
+ def test_opencode_rejects_non_chat_model_from_inventory_without_status(self):
+ from omlx.cli import launch_command
+
+ integration = MagicMock()
+ integration.display_name = "OpenCode"
+ integration.is_installed.return_value = True
+ health = MagicMock()
+ health.json.return_value = {}
+ status = MagicMock()
+ status.ok = False
+ listing = MagicMock()
+ listing.json.return_value = {
+ "data": [{"id": "embedding-model", "model_type": "embedding"}]
+ }
+ settings = SimpleNamespace(
+ server=SimpleNamespace(host="127.0.0.1", port=8000),
+ auth=SimpleNamespace(api_key=""),
+ claude_code=None,
+ )
+ args = argparse.Namespace(
+ tool="opencode", host=None, port=None, api_key=None, model="embedding-model"
+ )
+ with (
+ patch("requests.get", side_effect=[health, status, listing]),
+ patch("omlx.integrations.get_integration", return_value=integration),
+ patch("omlx.settings.GlobalSettings.load", return_value=settings),
+ pytest.raises(SystemExit) as exc,
+ ):
+ launch_command(args)
+ assert exc.value.code == 1
+ integration.launch.assert_not_called()
+
+ @pytest.mark.parametrize("requested", [True, False])
+ def test_opencode_uses_served_alias_for_raw_model_id(self, requested):
+ from omlx.cli import launch_command
+
+ integration = MagicMock()
+ integration.display_name = "OpenCode"
+ integration.is_installed.return_value = True
+ health = MagicMock()
+ health.json.return_value = {"default_model": "different"}
+ status = MagicMock()
+ status.json.return_value = {
+ "models": [
+ {
+ "id": "raw-model",
+ "model_alias": "served-alias",
+ "model_type": "llm",
+ "loaded": True,
+ }
+ ]
+ }
+ listing = MagicMock()
+ listing.json.return_value = {
+ "data": [{"id": "different"}, {"id": "served-alias"}]
+ }
+ settings = SimpleNamespace(
+ server=SimpleNamespace(host="127.0.0.1", port=8000),
+ auth=SimpleNamespace(api_key=""),
+ integrations=SimpleNamespace(opencode_model="raw-model"),
+ claude_code=None,
+ )
+ args = argparse.Namespace(
+ tool="opencode",
+ host=None,
+ port=None,
+ api_key=None,
+ model="raw-model" if requested else None,
+ )
+ with (
+ patch("requests.get", side_effect=[health, status, listing]),
+ patch("omlx.integrations.get_integration", return_value=integration),
+ patch("omlx.settings.GlobalSettings.load", return_value=settings),
+ ):
+ launch_command(args)
+ assert integration.launch.call_args.args[0].model == "served-alias"
+
+ @pytest.mark.parametrize("tool", ["codex", "codex_app", "copilot"])
+ @pytest.mark.parametrize("load_failure", [None, "http", "timeout"])
+ def test_codex_warms_selected_profile_before_launch(
+ self, tool, load_failure, mock_model_load, capsys
+ ):
+ import requests
+
+ from omlx.cli import launch_command
+
+ integration = MagicMock()
+ integration.display_name = "Codex"
+ integration.is_installed.return_value = True
+ health_response = MagicMock()
+ health_response.json.return_value = {"default_model": "first"}
+ status_response = MagicMock()
+ status_response.json.return_value = {
+ "models": [
+ {
+ "id": "coding-profile",
+ "source_model_id": "raw-model",
+ "model_type": "llm",
+ "loaded": False,
+ }
+ ]
+ }
+ models_response = MagicMock()
+ models_response.json.return_value = {"data": [{"id": "coding-profile"}]}
+ settings = SimpleNamespace(
+ server=SimpleNamespace(host="127.0.0.1", port=8000),
+ auth=SimpleNamespace(api_key="key"),
+ claude_code=None,
+ )
+ if load_failure == "http":
+ mock_model_load.return_value.raise_for_status.side_effect = (
+ requests.HTTPError("warm-up rejected")
+ )
+ elif load_failure == "timeout":
+ mock_model_load.side_effect = requests.Timeout("warm-up timed out")
+ integration.launch.side_effect = (
+ lambda context: mock_model_load.assert_called_once()
+ )
+ args = argparse.Namespace(
+ tool=tool, host=None, port=None, api_key=None, model="coding-profile"
+ )
+ with (
+ patch(
+ "requests.get",
+ side_effect=[health_response, status_response, models_response],
+ ),
+ patch("omlx.integrations.get_integration", return_value=integration),
+ patch("omlx.settings.GlobalSettings.load", return_value=settings),
+ ):
+ launch_command(args)
+
+ mock_model_load.assert_called_once_with(
+ "http://127.0.0.1:8000/v1/models/raw-model/load",
+ headers={"Authorization": "Bearer key"},
+ params={"wait": "false"},
+ timeout=3,
+ )
+ assert integration.launch.call_args.args[0].model == "coding-profile"
+ assert ("Warning: could not warm up" in capsys.readouterr().out) == (
+ load_failure is not None
+ )
+
+ @pytest.mark.parametrize("tool", ["codex", "codex_app", "copilot"])
+ def test_codex_model_listing_failure_keeps_explicit_model(self, tool, capsys):
+ import requests
+
+ from omlx.cli import launch_command
+
+ integration = MagicMock()
+ integration.display_name = "Codex"
+ integration.is_installed.return_value = True
+ health_response = MagicMock()
+ status_response = MagicMock()
+ status_response.ok = False
+ settings = SimpleNamespace(
+ server=SimpleNamespace(host="127.0.0.1", port=8000),
+ auth=SimpleNamespace(api_key=""),
+ claude_code=None,
+ )
+ args = argparse.Namespace(
+ tool=tool, host=None, port=None, api_key=None, model="explicit"
+ )
+ with (
+ patch(
+ "requests.get",
+ side_effect=[
+ health_response,
+ status_response,
+ requests.ConnectionError("offline"),
+ ],
+ ),
+ patch("omlx.integrations.get_integration", return_value=integration),
+ patch("omlx.settings.GlobalSettings.load", return_value=settings),
+ ):
+ launch_command(args)
+ context = integration.launch.call_args.args[0]
+ assert context.model == "explicit"
+ assert context.models == ()
+ integration.select_model.assert_not_called()
+ assert "Only the requested model" in capsys.readouterr().out
+
+ def test_codex_uses_public_context_limit_when_status_unavailable(self):
+ from omlx.cli import launch_command
+
+ integration = MagicMock()
+ integration.is_installed.return_value = True
+ health_response = MagicMock()
+ status_response = MagicMock()
+ status_response.ok = False
+ models_response = MagicMock()
+ models_response.json.return_value = {
+ "data": [{"id": "model", "max_model_len": 16384}]
+ }
+ settings = SimpleNamespace(
+ server=SimpleNamespace(host="127.0.0.1", port=8000),
+ auth=SimpleNamespace(api_key=""),
+ integrations=SimpleNamespace(codex_model=None),
+ claude_code=None,
+ )
+ args = argparse.Namespace(
+ tool="codex", host=None, port=None, api_key=None, model=None
+ )
+ with (
+ patch(
+ "requests.get",
+ side_effect=[health_response, status_response, models_response],
+ ),
+ patch("omlx.integrations.get_integration", return_value=integration),
+ patch("omlx.settings.GlobalSettings.load", return_value=settings),
+ ):
+ launch_command(args)
+ assert integration.launch.call_args.args[0].models[0].context_window == 16384
+ integration.select_model.assert_not_called()
+
+ @pytest.mark.parametrize("tool", ["codex", "codex_app"])
+ def test_codex_without_chat_models_exits(self, tool):
+ from omlx.cli import launch_command
+
+ integration = MagicMock()
+ health_response = MagicMock()
+ status_response = MagicMock()
+ status_response.ok = False
+ models_response = MagicMock()
+ models_response.json.return_value = {"data": []}
+ settings = SimpleNamespace(
+ server=SimpleNamespace(host="127.0.0.1", port=8000),
+ auth=SimpleNamespace(api_key=""),
+ claude_code=None,
+ )
+ args = argparse.Namespace(
+ tool=tool, host=None, port=None, api_key=None, model=None
+ )
+ with (
+ patch(
+ "requests.get",
+ side_effect=[health_response, status_response, models_response],
+ ),
+ patch("omlx.integrations.get_integration", return_value=integration),
+ patch("omlx.settings.GlobalSettings.load", return_value=settings),
+ pytest.raises(SystemExit) as exc,
+ ):
+ launch_command(args)
+ assert exc.value.code == 1
+ integration.launch.assert_not_called()
+ integration.select_model.assert_not_called()
+
def test_launch_command_passes_model_type_to_integration(self):
"""VLM model metadata should be forwarded to integrations."""
from omlx.cli import launch_command
@@ -460,8 +921,14 @@ def test_launch_command_passes_model_type_to_integration(self):
tools_profile="coding",
)
+ models_response = MagicMock()
+ models_response.json.return_value = {"data": [{"id": "qwen2.5-vl"}]}
+
with (
- patch("requests.get", side_effect=[health_response, status_response]),
+ patch(
+ "requests.get",
+ side_effect=[health_response, status_response, models_response],
+ ),
patch("omlx.integrations.get_integration", return_value=integration),
patch("omlx.settings.GlobalSettings.load", return_value=settings),
):
@@ -515,9 +982,13 @@ def test_launch_command_brackets_ipv6_host_in_urls(self):
tools_profile="coding",
)
+ models_response = MagicMock()
+ models_response.json.return_value = {"data": [{"id": "qwen3.5"}]}
+
with (
patch(
- "requests.get", side_effect=[health_response, status_response]
+ "requests.get",
+ side_effect=[health_response, status_response, models_response],
) as mock_get,
patch("omlx.integrations.get_integration", return_value=integration),
patch("omlx.settings.GlobalSettings.load", return_value=settings),
@@ -528,12 +999,15 @@ def test_launch_command_brackets_ipv6_host_in_urls(self):
assert called_urls == [
"http://[::1]:8000/health",
"http://[::1]:8000/v1/models/status",
+ "http://[::1]:8000/v1/models",
]
ctx = integration.launch.call_args.args[0]
assert ctx.host == "::1" # raw host preserved; brackets are URL-only
assert ctx.base_url == "http://[::1]:8000"
- def test_launch_command_passes_cross_session_flag_to_integration(self):
+ def test_launch_command_passes_cross_session_flag_to_integration(
+ self, empty_gateway_response
+ ):
from omlx.cli import launch_command
integration = MagicMock()
@@ -566,7 +1040,10 @@ def test_launch_command_passes_cross_session_flag_to_integration(self):
)
with (
- patch("requests.get", side_effect=[health_response, status_response]),
+ patch(
+ "requests.get",
+ side_effect=[health_response, status_response, empty_gateway_response],
+ ),
patch("omlx.integrations.get_integration", return_value=integration),
patch("omlx.settings.GlobalSettings.load", return_value=settings),
):
@@ -621,10 +1098,16 @@ def test_launch_command_skips_picker_when_integration_registers_catalog(
tools_profile="coding",
)
+ responses = [health_response, status_response]
+ if tool in ("codex_app", "copilot"):
+ models_response = MagicMock()
+ models_response.json.return_value = {
+ "data": [{"id": "Qwen3.8-27B-oQ5e-mtp", "model_type": "vlm"}]
+ }
+ responses.append(models_response)
+
with (
- # Exactly two requests (health + status): the picker's
- # /v1/models call must not happen.
- patch("requests.get", side_effect=[health_response, status_response]),
+ patch("requests.get", side_effect=responses),
patch("omlx.integrations.get_integration", return_value=integration),
patch("omlx.settings.GlobalSettings.load", return_value=settings),
):
@@ -638,6 +1121,7 @@ def test_launch_command_skips_picker_when_integration_registers_catalog(
def test_launch_command_resolves_alias_status_metadata(self):
"""Alias model IDs should keep status metadata from the real model."""
from omlx.cli import launch_command
+ from omlx.integrations.opencode import opencode_provider_config
integration = MagicMock()
integration.display_name = "OpenCode"
@@ -657,6 +1141,7 @@ def test_launch_command_resolves_alias_status_metadata(self):
"max_context_window": 32768,
"max_tokens": 8192,
"enable_thinking": False,
+ "supports_audio_input": True,
}
]
}
@@ -674,8 +1159,14 @@ def test_launch_command_resolves_alias_status_metadata(self):
tools_profile="coding",
)
+ models_response = MagicMock()
+ models_response.json.return_value = {"data": [{"id": "gpt-4o"}]}
+
with (
- patch("requests.get", side_effect=[health_response, status_response]),
+ patch(
+ "requests.get",
+ side_effect=[health_response, status_response, models_response],
+ ),
patch("omlx.integrations.get_integration", return_value=integration),
patch("omlx.settings.GlobalSettings.load", return_value=settings),
):
@@ -687,8 +1178,89 @@ def test_launch_command_resolves_alias_status_metadata(self):
assert ctx.max_tokens == 8192
assert ctx.model_type == "vlm"
assert ctx.reasoning is False
+ assert ctx.models_discovery_succeeded is True
+ assert ctx.models[0].id == "gpt-4o"
+ assert ctx.models[0].model_type == "vlm"
+ assert ctx.models_status_map["gpt-4o"]["supports_audio_input"] is True
+ assert opencode_provider_config(ctx)["models"]["gpt-4o"]["capabilities"][
+ "input"
+ ] == ["text", "image", "audio"]
+
+ @pytest.mark.parametrize("tool", ["opencode", "codex", "copilot"])
+ @pytest.mark.parametrize("model", ["flint-raw", "flint-alias"])
+ @pytest.mark.parametrize("reported_type", ["vlm", "llm"])
+ def test_launch_flint_is_text_only(
+ self, tmp_path, tool, model, reported_type
+ ):
+ from omlx.cli import launch_command
+ from omlx.integrations.opencode import OpenCodeIntegration
+
+ integration = MagicMock()
+ integration.is_installed.return_value = True
+ health_response = MagicMock()
+ health_response.json.return_value = {"default_model": "flint-raw"}
+ status_response = MagicMock()
+ status_response.ok = True
+ status_record = {
+ "id": "flint-raw",
+ "model_alias": "flint-alias",
+ "model_type": reported_type,
+ "config_model_type": "flint",
+ "engine_type": "vlm",
+ "max_context_window": 131072,
+ "max_tokens": 8192,
+ "loaded": True,
+ }
+ status_response.json.return_value = {"models": [status_record]}
+ models_response = MagicMock()
+ models_response.json.return_value = {
+ "data": [{"id": "flint-alias", "model_type": reported_type}]
+ }
+ settings = SimpleNamespace(
+ server=SimpleNamespace(host="127.0.0.1", port=8000),
+ auth=SimpleNamespace(api_key=""),
+ integrations=SimpleNamespace(),
+ claude_code=None,
+ )
+ args = argparse.Namespace(
+ tool=tool, host=None, port=None, api_key=None, model=model
+ )
- def test_launch_command_forwards_extra_args(self):
+ with (
+ patch(
+ "requests.get",
+ side_effect=[health_response, status_response, models_response],
+ ),
+ patch("omlx.integrations.get_integration", return_value=integration),
+ patch("omlx.settings.GlobalSettings.load", return_value=settings),
+ ):
+ launch_command(args)
+
+ context = integration.launch.call_args.args[0]
+ assert context.model_type == "llm"
+ assert context.supports_images is False
+ for model_id in ("flint-raw", "flint-alias"):
+ assert context.models_status_map[model_id]["model_type"] == "llm"
+ assert context.models_status_map[model_id]["engine_type"] == "vlm"
+ assert status_record["model_type"] == reported_type
+ if tool in ("codex", "copilot"):
+ assert len(context.models) == 1
+ assert context.models[0].id == "flint-alias"
+ assert context.models[0].model_type == "llm"
+ else:
+ config_path = tmp_path / "opencode.json"
+ with (
+ patch.object(OpenCodeIntegration, "CONFIG_PATH", config_path),
+ patch("omlx.integrations.opencode._major_version", return_value=2),
+ ):
+ OpenCodeIntegration().configure(context)
+ entry = json.loads(config_path.read_text())["providers"]["omlx"]["models"][
+ context.model
+ ]
+ assert entry["capabilities"]["input"] == ["text"]
+ assert entry["capabilities"]["output"] == ["text"]
+
+ def test_launch_command_forwards_extra_args(self, empty_gateway_response):
"""Unknown CLI tokens (e.g. --resume ) should reach integration.launch."""
from omlx.cli import launch_command
@@ -726,7 +1298,10 @@ def test_launch_command_forwards_extra_args(self):
)
with (
- patch("requests.get", side_effect=[health_response, status_response]),
+ patch(
+ "requests.get",
+ side_effect=[health_response, status_response, empty_gateway_response],
+ ),
patch("omlx.integrations.get_integration", return_value=integration),
patch("omlx.settings.GlobalSettings.load", return_value=settings),
):
@@ -908,7 +1483,9 @@ def test_launch_command_rejects_small_auto_selected_claude_model(self, capsys):
assert "Using model: only-32k" in output
assert "Cannot launch Claude Code with model 'only-32k'" in output
- def test_launch_command_shows_picker_and_keeps_saved_tiers(self):
+ def test_launch_command_shows_picker_and_keeps_saved_tiers(
+ self, empty_gateway_response
+ ):
"""Bare `omlx launch claude` shows the picker for the default model and keeps the saved tier models (#3543)."""
from omlx.cli import launch_command
@@ -958,7 +1535,12 @@ def test_launch_command_shows_picker_and_keeps_saved_tiers(self):
with (
patch(
"requests.get",
- side_effect=[health_response, status_map_response, models_response],
+ side_effect=[
+ health_response,
+ status_map_response,
+ models_response,
+ empty_gateway_response,
+ ],
),
patch("omlx.integrations.get_integration", return_value=integration),
patch("omlx.settings.GlobalSettings.load", return_value=settings),
@@ -973,7 +1555,9 @@ def test_launch_command_shows_picker_and_keeps_saved_tiers(self):
assert ctx.haiku_model == "haiku-local"
assert ctx.api_key == "saved-key"
- def test_launch_command_claude_cli_tiers_override_saved_settings(self):
+ def test_launch_command_claude_cli_tiers_override_saved_settings(
+ self, empty_gateway_response
+ ):
"""Explicit --opus/--sonnet/--haiku should win over saved settings."""
from omlx.cli import launch_command
@@ -1011,7 +1595,10 @@ def test_launch_command_claude_cli_tiers_override_saved_settings(self):
)
with (
- patch("requests.get", side_effect=[health_response, status_response]),
+ patch(
+ "requests.get",
+ side_effect=[health_response, status_response, empty_gateway_response],
+ ),
patch("omlx.integrations.get_integration", return_value=integration),
patch("omlx.settings.GlobalSettings.load", return_value=settings),
):
@@ -1244,7 +1831,10 @@ def test_invalid_embedding_batch_size_is_not_persisted(self, tmp_path):
assert "embedding_batch_size" in result.stdout
assert not (tmp_path / "settings.json").exists()
- def test_network_bind_without_api_key_exits_before_persisting(self, tmp_path):
+ def test_network_bind_without_api_key_exits_before_persisting(
+ self, tmp_path, monkeypatch
+ ):
+ monkeypatch.delenv("OMLX_API_KEY", raising=False)
result = subprocess.run(
[
sys.executable,
@@ -1580,7 +2170,13 @@ def test_serve_has_description(self):
class TestLaunchClaudeTierPrecedence:
def _run(
- self, *, args_model, settings_tiers, cli_tiers=None, picked="picked-model"
+ self,
+ *,
+ args_model,
+ settings_tiers,
+ cli_tiers=None,
+ picked="picked-model",
+ gateway_error=None,
):
from omlx.cli import launch_command
@@ -1616,6 +2212,14 @@ def _run(
for m in status_response.json.return_value["models"]
]
}
+ gateway_response = MagicMock()
+ gateway_response.json.return_value = {"data": []}
+ gateway_response.json.side_effect = gateway_error
+ gateway_result = (
+ gateway_error
+ if isinstance(gateway_error, requests.RequestException)
+ else gateway_response
+ )
settings = SimpleNamespace(
server=SimpleNamespace(host="127.0.0.1", port=8000),
@@ -1637,7 +2241,16 @@ def _run(
with (
patch(
"requests.get",
- side_effect=[health_response, status_response, models_response],
+ side_effect=(
+ [
+ health_response,
+ status_response,
+ models_response,
+ gateway_result,
+ ]
+ if args_model is None and not cli_tiers
+ else [health_response, status_response, gateway_result]
+ ),
),
patch("omlx.integrations.get_integration", return_value=integration),
patch("omlx.settings.GlobalSettings.load", return_value=settings),
@@ -1688,6 +2301,43 @@ def test_without_saved_tiers_the_picked_model_is_used(self):
assert ctx.model == "picked-model"
assert (ctx.opus_model, ctx.sonnet_model, ctx.haiku_model) == (None, None, None)
+ @pytest.mark.parametrize(
+ "gateway_error",
+ [
+ ValueError("Invalid discovery JSON"),
+ requests.Timeout("Discovery timed out"),
+ requests.HTTPError("Discovery unavailable"),
+ ],
+ )
+ def test_failed_discovery_clamps_context_limits(self, capsys, gateway_error):
+ from omlx.integrations.claude import ClaudeCodeIntegration
+
+ context = self._run(
+ args_model="picked-model",
+ settings_tiers={"opus_model": "opus-cfg"},
+ gateway_error=gateway_error,
+ )
+
+ assert context.context_window == 49152
+ output = capsys.readouterr().out
+ assert "could not read Claude discovery context limits" in output
+ assert (
+ "Using the 48K discovery minimum as a conservative context limit." in output
+ )
+
+ with (
+ patch.object(
+ ClaudeCodeIntegration, "_find_claude_binary", return_value="claude"
+ ),
+ patch("omlx.integrations.claude.os.execvpe") as execute,
+ ):
+ ClaudeCodeIntegration().launch(context)
+
+ env = execute.call_args.args[2]
+ assert env["CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"] == "1"
+ assert env["CLAUDE_CODE_MAX_CONTEXT_TOKENS"] == "49152"
+ assert "CLAUDE_CODE_AUTO_COMPACT_WINDOW" not in env
+
@pytest.mark.parametrize(
"windows, expected_window",
[
@@ -1701,8 +2351,9 @@ def test_without_saved_tiers_the_picked_model_is_used(self):
((None, None, None, None), None),
],
)
+ @pytest.mark.parametrize("discovered_window", [None, 49152, 65536])
def test_launch_passes_initial_model_and_shared_context_limit(
- self, windows, expected_window
+ self, windows, expected_window, discovered_window
):
from omlx.cli import launch_command
from omlx.integrations.claude import ClaudeCodeIntegration
@@ -1713,9 +2364,45 @@ def test_launch_passes_initial_model_and_shared_context_limit(
{"id": model_id, "max_context_window": window, "model_type": "llm"}
for model_id, window in zip(model_ids, windows)
]
- responses = [MagicMock(), MagicMock(), MagicMock()]
+ models.extend(
+ [
+ {
+ "id": "discovered-model",
+ "max_context_window": discovered_window,
+ "model_type": "llm",
+ },
+ {"id": "too-small", "max_context_window": 32768, "model_type": "llm"},
+ {"id": "embed", "max_context_window": 1024, "model_type": "embedding"},
+ {
+ "id": "hidden",
+ "max_context_window": 49152,
+ "model_type": "llm",
+ "is_hidden": True,
+ },
+ {
+ "id": "hidden-draft",
+ "max_context_window": 49152,
+ "model_type": "llm",
+ },
+ ]
+ )
+ if discovered_window is not None:
+ expected_window = str(
+ min(int(expected_window), discovered_window)
+ if expected_window is not None
+ else discovered_window
+ )
+ responses = [MagicMock(), MagicMock(), MagicMock(), MagicMock()]
responses[1].json.return_value = {"models": models}
responses[2].json.return_value = {"data": models}
+ responses[3].json.return_value = {
+ "data": [
+ {
+ "id": "omlx-claude/discovered-model",
+ "max_model_len": discovered_window,
+ }
+ ]
+ }
settings = SimpleNamespace(
server=SimpleNamespace(host="127.0.0.1", port=8000),
auth=SimpleNamespace(api_key="saved-key"),
@@ -1729,7 +2416,7 @@ def test_launch_passes_initial_model_and_shared_context_limit(
tool="claude", host=None, port=None, api_key=None, model=None
)
with (
- patch("requests.get", side_effect=responses),
+ patch("requests.get", side_effect=responses) as get,
patch("omlx.settings.GlobalSettings.load", return_value=settings),
patch("omlx.integrations.get_integration", return_value=integration),
patch.object(integration, "is_installed", return_value=True),
@@ -1741,6 +2428,11 @@ def test_launch_passes_initial_model_and_shared_context_limit(
launch_command(args, extra_args=["--resume", "session-id"])
execute.assert_called_once()
+ assert get.call_args.args == ("http://127.0.0.1:8000/claude/v1/models",)
+ assert get.call_args.kwargs == {
+ "headers": {"Authorization": "Bearer saved-key"},
+ "timeout": 5,
+ }
binary, argv, env = execute.call_args.args
assert binary == "claude"
assert argv == [
@@ -1752,11 +2444,11 @@ def test_launch_passes_initial_model_and_shared_context_limit(
"--resume",
"session-id",
]
- assert env["ANTHROPIC_MODEL"] == "picked-model"
- assert env["ANTHROPIC_DEFAULT_OPUS_MODEL"] == "opus-cfg"
- assert env["ANTHROPIC_DEFAULT_SONNET_MODEL"] == "sonnet-cfg"
- assert env["ANTHROPIC_DEFAULT_HAIKU_MODEL"] == "haiku-cfg"
- assert env["CLAUDE_CODE_SUBAGENT_MODEL"] == "haiku-cfg"
+ assert env["ANTHROPIC_MODEL"] == "omlx-claude/picked-model"
+ assert env["ANTHROPIC_DEFAULT_OPUS_MODEL"] == "omlx-claude/opus-cfg"
+ assert env["ANTHROPIC_DEFAULT_SONNET_MODEL"] == "omlx-claude/sonnet-cfg"
+ assert env["ANTHROPIC_DEFAULT_HAIKU_MODEL"] == "omlx-claude/haiku-cfg"
+ assert env["CLAUDE_CODE_SUBAGENT_MODEL"] == "omlx-claude/haiku-cfg"
assert env.get("CLAUDE_CODE_MAX_CONTEXT_TOKENS") == expected_window
diff --git a/tests/test_integrations.py b/tests/test_integrations.py
index f45350b649..fbcfe1a954 100644
--- a/tests/test_integrations.py
+++ b/tests/test_integrations.py
@@ -1,11 +1,14 @@
+# SPDX-License-Identifier: Apache-2.0
"""Tests for the integrations module."""
import json
import os
import plistlib
import shlex
+import subprocess
import sys
import time
+import tomllib
from pathlib import Path
from unittest.mock import MagicMock, patch
@@ -18,7 +21,7 @@
get_integration,
list_integrations,
)
-from omlx.integrations.base import IntegrationContext
+from omlx.integrations.base import IntegrationContext, IntegrationModel
from omlx.integrations.claude import ClaudeCodeIntegration
from omlx.integrations.claude_desktop import (
PROFILE_ID,
@@ -37,6 +40,7 @@
codex_model_catalog,
resolve_codex_models,
write_codex_config,
+ write_codex_model_catalog,
)
from omlx.integrations.codex_app import CodexAppIntegration, find_codex_app_bundle
from omlx.integrations.copilot import CopilotIntegration, copilot_provider_config
@@ -49,7 +53,7 @@
)
from omlx.integrations.hermes import HermesIntegration
from omlx.integrations.openclaw import OpenClawIntegration
-from omlx.integrations.opencode import OpenCodeIntegration
+from omlx.integrations.opencode import OpenCodeIntegration, opencode_provider_config
from omlx.integrations.pi import PiIntegration, _get_agent_dir
from omlx.integrations.vibe import VibeIntegration
@@ -66,6 +70,36 @@ def ctx(**overrides) -> IntegrationContext:
class TestIntegrationRegistry:
+ def test_registry_and_listing_do_not_import_inference_dependencies(self):
+ result = subprocess.run(
+ [
+ sys.executable,
+ "-c",
+ """
+import importlib.abc
+import sys
+from types import SimpleNamespace
+
+class NoInferenceImports(importlib.abc.MetaPathFinder):
+ def find_spec(self, fullname, path=None, target=None):
+ if fullname in ("omlx.model_discovery", "mlx_audio"):
+ raise ImportError(f"Unexpected inference dependency: {fullname}")
+
+sys.meta_path.insert(0, NoInferenceImports())
+from omlx.integrations import list_integrations
+assert {"codex_app", "vibe"} <= {entry.name for entry in list_integrations()}
+from omlx.cli import launch_command
+launch_command(SimpleNamespace(tool="list"))
+""",
+ ],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+ assert result.returncode == 0, result.stderr
+ assert "Available integrations:" in result.stdout
+ assert "codex_app" in result.stdout
+
def test_list_integrations(self):
integrations = list_integrations()
assert len(integrations) == 11
@@ -199,7 +233,10 @@ def test_catalog_uses_served_ids_limits_and_effort_levels(self):
assert {
e["slug"]: [lvl["effort"] for lvl in e["supported_reasoning_levels"]]
for e in entries
- } == {"qwen-vl": [], "dsv41": ["low", "high", "max"]}
+ } == {
+ "qwen-vl": ["low", "medium", "high"],
+ "dsv41": ["low", "high", "max"],
+ }
@pytest.mark.parametrize(
("model", "default", "expected"),
@@ -313,6 +350,9 @@ def fake_execvpe(binary, argv, env):
}
with (
patch("omlx.integrations.codex.write_codex_config") as writer,
+ patch(
+ "omlx.integrations.codex.CODEX_CONFIG_PATH", tmp_path / "config.toml"
+ ),
patch("omlx.integrations.codex.os.environ", base_env),
patch("omlx.integrations.codex.os.execvpe", side_effect=fake_execvpe),
patch("omlx.integrations.codex.shutil.which", return_value="/bin/codex"),
@@ -343,6 +383,244 @@ def fake_execvpe(binary, argv, env):
assert "PYTHONPATH" not in captured["env"]
assert "PYTHONDONTWRITEBYTECODE" not in captured["env"]
writer.assert_not_called()
+ assert not (tmp_path / "config.toml").exists()
+ catalog_arg = next(
+ arg for arg in captured["argv"] if arg.startswith("model_catalog_json=")
+ )
+ catalog = json.loads(Path(json.loads(catalog_arg.split("=", 1)[1])).read_text())
+ assert catalog["models"][0]["slug"] == "qwen3.5"
+
+
+class TestCodexModelCatalog:
+ def test_preserves_ids_and_per_model_capabilities(self):
+ catalog = codex_model_catalog(
+ ctx(
+ model="vision-alias",
+ context_window=999999,
+ reasoning=True,
+ models=(
+ IntegrationModel("small-text", 8192, "llm", False),
+ IntegrationModel("vision-alias", 131072, "vlm", True),
+ IntegrationModel("embedding", 1024, "embedding"),
+ IntegrationModel("audio", 1024, "stt"),
+ ),
+ )
+ )
+ models = catalog["models"]
+ assert [model["slug"] for model in models] == ["vision-alias", "small-text"]
+ assert [model["priority"] for model in models] == [0, 1]
+ assert models[0]["context_window"] == 131072
+ assert models[0]["input_modalities"] == ["text", "image"]
+ assert models[0]["default_reasoning_level"] == "high"
+ assert [
+ level["effort"] for level in models[0]["supported_reasoning_levels"]
+ ] == ["low", "medium", "high"]
+ assert models[1]["context_window"] == 8192
+ assert models[1]["input_modalities"] == ["text"]
+ assert [
+ level["effort"] for level in models[1]["supported_reasoning_levels"]
+ ] == ["low", "medium", "high"]
+ assert models[1]["default_reasoning_level"] is None
+ assert models[1]["truncation_policy"]["limit"] == 2048
+ assert all(model["base_instructions"] for model in models)
+ assert all(not model["prefer_websockets"] for model in models)
+
+ @pytest.mark.parametrize("listed", [True, False])
+ @pytest.mark.parametrize("reasoning", [True, False, None])
+ def test_models_without_native_efforts_advertise_compatibility_levels(
+ self, listed, reasoning
+ ):
+ metadata = {"reasoning": reasoning}
+ model = codex_model_catalog(
+ ctx(
+ model="custom-alias",
+ models=(
+ (IntegrationModel("custom-alias", **metadata),) if listed else ()
+ ),
+ **metadata,
+ )
+ )["models"][0]
+
+ assert [level["effort"] for level in model["supported_reasoning_levels"]] == [
+ "low",
+ "medium",
+ "high",
+ ]
+ assert all(
+ "ignored by templates without effort controls" in level["description"]
+ for level in model["supported_reasoning_levels"]
+ )
+ assert model["default_reasoning_level"] == ("high" if reasoning else None)
+
+ @pytest.mark.parametrize(
+ "selected",
+ ["Qwen3.5-9B-oQ4e-mtp", "Qwen3.8-Flash-Next-oQ4e-mtp"],
+ )
+ def test_desktop_title_fallback_prefers_launch_default_over_other_models(
+ self, selected
+ ):
+ catalog = codex_model_catalog(
+ ctx(
+ model=selected,
+ models=(
+ IntegrationModel(
+ "Qwen3.8-Flash-Next-oQ4e-mtp",
+ reasoning=True,
+ reasoning_effort_options=("low", "medium", "xhigh"),
+ reasoning_effort_default="xhigh",
+ ),
+ IntegrationModel("Qwen3.6-35B-A3B-oQ6e-mtp", reasoning=True),
+ IntegrationModel("Qwen3.5-9B-oQ4e-mtp", reasoning=True),
+ ),
+ )
+ )
+
+ # Codex Desktop filters low-effort candidates before preferring the
+ # catalog default (priority zero), then falls back to the first match.
+ candidates = [
+ model
+ for model in catalog["models"]
+ if any(
+ level["effort"] == "low"
+ for level in model["supported_reasoning_levels"]
+ )
+ ]
+ title_model = next(
+ (model for model in candidates if model["priority"] == 0), candidates[0]
+ )
+ assert title_model["slug"] == selected
+ assert len(catalog["models"]) == 3
+
+ @pytest.mark.parametrize("listed", [True, False])
+ def test_qwen_native_efforts_default_to_medium(self, listed):
+ metadata = {
+ "reasoning": True,
+ "reasoning_effort_options": ("xhigh", "medium", "low"),
+ "reasoning_effort_default": "xhigh",
+ }
+ catalog = codex_model_catalog(
+ ctx(
+ model="custom-alias",
+ models=(IntegrationModel("custom-alias", **metadata),) if listed else (),
+ **metadata,
+ )
+ )
+ model = catalog["models"][0]
+ assert model["default_reasoning_level"] == "medium"
+ assert [level["effort"] for level in model["supported_reasoning_levels"]] == [
+ "low",
+ "medium",
+ "xhigh",
+ ]
+
+ @pytest.mark.parametrize("default,expected", [("low", "low"), ("bogus", "low")])
+ def test_native_default_without_medium_and_unknown_values(self, default, expected):
+ model = codex_model_catalog(
+ ctx(
+ model="alias",
+ reasoning=True,
+ reasoning_effort_options=("low", "ultra", "custom", "low"),
+ reasoning_effort_default=default,
+ )
+ )["models"][0]
+ assert model["default_reasoning_level"] == expected
+ assert [level["effort"] for level in model["supported_reasoning_levels"]] == [
+ "low",
+ "ultra",
+ ]
+
+ def test_disabled_thinking_does_not_advertise_effort(self):
+ model = codex_model_catalog(
+ ctx(
+ model="alias",
+ reasoning=False,
+ reasoning_effort_options=("low", "medium", "xhigh"),
+ reasoning_effort_default="xhigh",
+ )
+ )["models"][0]
+ assert model["supported_reasoning_levels"] == []
+ assert model["default_reasoning_level"] is None
+
+ @pytest.mark.parametrize(
+ "status",
+ [
+ {"model_type": "llm", "is_helper": True},
+ {"model_type": "vlm", "config_model_type": "embedding_gemma2"},
+ {"model_type": "llm", "config_model_type": "qwen3_5_mtp"},
+ {"model_type": "embedding"},
+ {"model_type": "llm", "engine_type": "reranker"},
+ ],
+ )
+ @pytest.mark.parametrize("listed", [False, True])
+ def test_status_excludes_non_chat_models_even_when_selected(self, status, listed):
+ assert codex_model_catalog(
+ ctx(
+ model="alias",
+ models=(IntegrationModel("alias", model_type="vlm"),) if listed else (),
+ models_status_map={"alias": status},
+ )
+ ) == {"models": []}
+
+ def test_explicit_non_chat_model_is_not_added(self):
+ assert codex_model_catalog(ctx(model="embedding", model_type="embedding")) == {
+ "models": []
+ }
+
+ @pytest.mark.parametrize("context_window", [None, 0, -1])
+ def test_unknown_or_invalid_context_uses_fallback(self, context_window):
+ catalog = codex_model_catalog(ctx(model="model", context_window=context_window))
+ assert catalog["models"][0]["context_window"] == 32768
+
+ def test_explicit_model_is_included_when_listing_is_unavailable(self):
+ catalog = codex_model_catalog(ctx(model="deepseek-r1", context_window=65536))
+ assert len(catalog["models"]) == 1
+ model = catalog["models"][0]
+ assert model["slug"] == "deepseek-r1"
+ assert model["context_window"] == 65536
+ assert model["default_reasoning_level"] == "high"
+
+ def test_metadata_overrides_reasoning_name_heuristic(self):
+ catalog = codex_model_catalog(ctx(model="deepseek-r1", reasoning=False))
+ assert [
+ level["effort"]
+ for level in catalog["models"][0]["supported_reasoning_levels"]
+ ] == ["low", "medium", "high"]
+ assert catalog["models"][0]["default_reasoning_level"] is None
+ assert catalog["models"][0]["context_window"] == 32768
+ assert catalog["models"][0]["input_modalities"] == ["text"]
+
+ def test_catalog_overrides_do_not_freeze_model_settings(self, tmp_path):
+ path = tmp_path / "catalog.json"
+ args = codex_config_args(
+ ctx(model="thinking", reasoning=True, context_window=4096), path
+ )
+ assert f"model_catalog_json={json.dumps(str(path))}" in args
+ assert not any(arg.startswith("model_context_window=") for arg in args)
+ assert not any(arg.startswith("model_reasoning_effort=") for arg in args)
+ assert 'model_providers.omlx.wire_api="responses"' in args
+ assert "model_providers.omlx.supports_websockets=false" in args
+
+ def test_catalog_refreshes_without_replacing_other_catalogs(self, tmp_path):
+ config_path = tmp_path / "config.toml"
+ other_catalog = tmp_path / "my-models.json"
+ other_catalog.write_text("user-owned")
+ path = write_codex_model_catalog(
+ config_path.parent, "codex", ctx(model="old"), ["old"], "instructions"
+ )
+ new_path = write_codex_model_catalog(
+ config_path.parent, "codex", ctx(model="new"), ["new"], "instructions"
+ )
+ assert path == new_path
+ assert json.loads(path.read_text())["models"][0]["slug"] == "new"
+ assert other_catalog.read_text() == "user-owned"
+ assert not config_path.exists()
+ assert (
+ write_codex_model_catalog(
+ config_path.parent, "codex", ctx(port=9000, model="other"),
+ ["other"], "instructions",
+ )
+ != path
+ )
class TestCodexConfigWriter:
@@ -369,6 +647,75 @@ def test_writes_provider_config(self, tmp_path):
assert 'base_url = "http://192.168.1.100:9000/v1"' in content
assert 'env_key = "OMLX_API_KEY"' in content
+ def test_writes_catalog_and_clears_global_model_overrides(self, tmp_path):
+ config_path = tmp_path / "config.toml"
+ config_path.write_text(
+ "model_context_window = 999999\n"
+ "model_auto_compact_token_limit = 900000\n"
+ 'model_reasoning_effort = "high"\n'
+ 'model_reasoning_summary = "auto"\n'
+ "model_supports_reasoning_summaries = true\n"
+ 'approval_policy = "on-request"\n'
+ "[model_providers.other]\n"
+ 'name = "Other"\n'
+ )
+ write_codex_config(
+ config_path,
+ ctx(
+ model='model "with quotes"',
+ models=(IntegrationModel('model "with quotes"', 8192, "llm", False),),
+ ),
+ )
+ config = tomllib.loads(config_path.read_text())
+ assert config["model"] == 'model "with quotes"'
+ assert config["approval_policy"] == "on-request"
+ assert config["model_providers"]["other"]["name"] == "Other"
+ assert "model_context_window" not in config
+ assert "model_auto_compact_token_limit" not in config
+ assert "model_reasoning_effort" not in config
+ assert "model_reasoning_summary" not in config
+ assert "model_supports_reasoning_summaries" not in config
+ models = json.loads(Path(config["model_catalog_json"]).read_text())["models"]
+ assert models[0]["context_window"] == 8192
+ assert config["model_providers"]["omlx"]["wire_api"] == "responses"
+ assert config["model_providers"]["omlx"]["supports_websockets"] is False
+
+ def test_backup_failure_does_not_overwrite_config(self, tmp_path):
+ config_path = tmp_path / "config.toml"
+ config_path.write_text('model = "old"\n')
+ with (
+ patch(
+ "omlx.integrations.codex.shutil.copy2", side_effect=OSError("read-only")
+ ),
+ pytest.raises(OSError, match="read-only"),
+ ):
+ write_codex_config(config_path, ctx(model="new"))
+ assert config_path.read_text() == 'model = "old"\n'
+
+ def test_replaces_provider_subtables_and_commented_header(self, tmp_path):
+ config_path = tmp_path / "config.toml"
+ config_path.write_text(
+ "[model_providers.omlx] # old provider\n"
+ 'name = "Old"\n'
+ "[model_providers.omlx.http_headers]\n"
+ 'old_header = "old"\n'
+ "[model_providers.other] # keep\n"
+ 'name = "Other"\n'
+ )
+ write_codex_config(config_path, ctx(model="new"))
+ providers = tomllib.loads(config_path.read_text())["model_providers"]
+ assert providers["omlx"]["name"] == "oMLX"
+ assert "http_headers" not in providers["omlx"]
+ assert providers["other"]["name"] == "Other"
+
+ def test_invalid_config_is_not_overwritten(self, tmp_path):
+ config_path = tmp_path / "config.toml"
+ config_path.write_text('model = "unterminated\n')
+ with pytest.raises(tomllib.TOMLDecodeError):
+ write_codex_config(config_path, ctx(model="new"))
+ assert config_path.read_text() == 'model = "unterminated\n'
+ assert not list(tmp_path.glob("omlx-models-*.json"))
+
def test_creates_backup(self, tmp_path):
config_path = tmp_path / "config.toml"
config_path.write_text('model = "old"')
@@ -597,205 +944,515 @@ def test_type(self):
class TestOpenCodeIntegration:
- def test_get_command(self):
- oc = OpenCodeIntegration()
- cmd = oc.get_command(ctx(port=8000, api_key="key", model="qwen3.5"))
- assert "omlx launch opencode" in cmd
- assert "--model qwen3.5" in cmd
-
- def test_configure_new_file(self, tmp_path):
- oc = OpenCodeIntegration()
- config_path = tmp_path / "opencode" / "opencode.json"
+ @pytest.fixture
+ def opencode_v2(self, tmp_path, monkeypatch):
+ monkeypatch.setattr(
+ OpenCodeIntegration, "CONFIG_PATH", tmp_path / "opencode.json"
+ )
+ monkeypatch.setattr("omlx.integrations.opencode._major_version", lambda: 2)
+ return OpenCodeIntegration()
- with patch.object(OpenCodeIntegration, "CONFIG_PATH", config_path):
- oc.configure(ctx(port=8000, api_key="test-key", model="qwen3.5"))
+ def test_get_command(self):
+ assert "--model qwen" in OpenCodeIntegration().get_command(ctx(model="qwen"))
- assert config_path.exists()
- config = json.loads(config_path.read_text())
- assert (
- config["provider"]["omlx"]["options"]["baseURL"]
- == "http://127.0.0.1:8000/v1"
+ @pytest.mark.parametrize("reported_audio", [None, True, False])
+ def test_warns_when_running_server_lacks_audio_metadata(
+ self, opencode_v2, capsys, reported_audio
+ ):
+ status = {"model_type": "vlm"}
+ if reported_audio is not None:
+ status["supports_audio_input"] = reported_audio
+ context = ctx(
+ model="gemma",
+ models=(IntegrationModel(id="gemma", model_type="vlm"),),
+ models_status_map={"gemma": status},
+ )
+ opencode_v2.configure(context)
+ warning = "updating the launcher alone is not enough"
+ assert (warning in capsys.readouterr().out) is (reported_audio is None)
+
+ @pytest.mark.parametrize("audio_input", [True, False, None, "true"])
+ @pytest.mark.parametrize("listed", [True, False])
+ def test_audio_input_capability(self, audio_input, listed):
+ context = ctx(
+ model="omni",
+ model_type="vlm",
+ models=(IntegrationModel(id="omni", model_type="vlm"),) if listed else (),
+ models_status_map={"omni": {"supports_audio_input": audio_input}},
+ )
+ provider = opencode_provider_config(context)
+ inputs = provider["models"]["omni"]["capabilities"]["input"]
+ assert inputs == ["text", "image"] + (["audio"] if audio_input is True else [])
+ assert provider["models"]["omni"]["capabilities"]["output"] == ["text"]
+
+ @pytest.mark.parametrize("model_type", ["vlm", None])
+ @pytest.mark.parametrize("audio_input", [True, False, None])
+ @pytest.mark.parametrize("previous_audio", [True, False])
+ def test_refresh_audio_input_capability(
+ self, tmp_path, opencode_v2, model_type, audio_input, previous_audio
+ ):
+ path = tmp_path / "opencode.json"
+ old_inputs = ["text", "image"] + (["audio"] if previous_audio else [])
+ models = {"omni": {"capabilities": {"input": old_inputs}}}
+ path.write_text(json.dumps({"providers": {"omlx": {"models": models}}}))
+ context = ctx(
+ model="omni",
+ model_type=model_type,
+ models_status_map={"omni": {"supports_audio_input": audio_input}},
+ )
+ opencode_v2.configure(context)
+ first = path.read_text()
+ opencode_v2.configure(context)
+ assert path.read_text() == first
+ model = json.loads(first)["providers"]["omlx"]["models"]["omni"]
+ expected_audio = previous_audio if audio_input is None else audio_input
+ assert model["capabilities"]["input"] == ["text", "image"] + (
+ ["audio"] if expected_audio else []
)
- assert config["provider"]["omlx"]["npm"] == "@ai-sdk/openai-compatible"
- assert config["provider"]["omlx"]["options"]["apiKey"] == "test-key"
- assert config["provider"]["omlx"]["models"]["qwen3.5"]["name"] == "qwen3.5"
- assert config["provider"]["omlx"]["models"]["qwen3.5"]["modalities"] == {
- "input": ["text"],
- "output": ["text"],
- }
- assert config["model"] == "omlx/qwen3.5"
-
- def test_configure_custom_host(self, tmp_path):
- oc = OpenCodeIntegration()
- config_path = tmp_path / "opencode" / "opencode.json"
- with patch.object(OpenCodeIntegration, "CONFIG_PATH", config_path):
- oc.configure(ctx(port=9000, api_key="key", model="test", host="10.0.0.5"))
- config = json.loads(config_path.read_text())
- assert (
- config["provider"]["omlx"]["options"]["baseURL"]
- == "http://10.0.0.5:9000/v1"
+ def test_v2_catalog_and_preservation(self, tmp_path):
+ path = tmp_path / "opencode.jsonc"
+ original = """{
+ // keep this comment
+ "providers": {
+ "other": {"name": "Other"},
+ "omlx": {
+ "custom": true, // keep provider comment
+ "settings": {"timeout": 100},
+ "models": {"manual": {"name": "Manual"}, "vision": {"custom": 7}},
+ },
+ },
+ "model": "other/model",
+}
+"""
+ path.write_text(original)
+ models = (
+ IntegrationModel(id="text", context_window=32768, model_type="llm"),
+ IntegrationModel(
+ id="vision", context_window=8192, model_type="vlm", reasoning=True
+ ),
+ IntegrationModel(id="embedding", model_type="embedding"),
)
+ context = ctx(
+ model="text",
+ models=models,
+ models_discovery_succeeded=True,
+ models_status_map={"text": {"max_tokens": 2048}},
+ )
+ with (
+ patch.object(OpenCodeIntegration, "CONFIG_PATH", path),
+ patch("omlx.integrations.opencode._major_version", return_value=2),
+ ):
+ OpenCodeIntegration().configure(context)
+ result = path.read_text()
+ OpenCodeIntegration().configure(context)
+ assert path.read_text() == result
+ assert "// keep this comment" not in result
+ assert "// keep provider comment" not in result
+ config = json.loads(result)
+ assert result == json.dumps(config, indent=2) + "\n"
+ provider = config["providers"]["omlx"]
+ assert provider["package"] == "@opencode/ai/providers/openai-compatible"
+ assert provider["settings"] == {
+ "timeout": 100,
+ "baseURL": "http://127.0.0.1:8000/v1",
+ "apiKey": "omlx",
+ }
+ assert config["providers"]["other"] == {"name": "Other"}
+ assert provider["custom"] is True
+ assert set(provider["models"]) == {"manual", "text", "vision"}
+ assert provider["models"]["text"]["limit"] == {"context": 32768, "output": 2048}
+ assert provider["models"]["vision"]["custom"] == 7
+ assert provider["models"]["vision"]["capabilities"]["input"] == [
+ "text",
+ "image",
+ ]
+ assert config["model"] == "omlx/text"
+ backups = list(tmp_path.glob("opencode.*.bak"))
+ assert len(backups) == 1 and backups[0].read_text() == original
+ assert path.stat().st_mode & 0o777 == 0o600
+ assert backups[0].stat().st_mode & 0o777 == 0o600
- def test_configure_preserves_existing(self, tmp_path):
- config_path = tmp_path / "opencode.json"
- existing = {
- "provider": {
- "ollama": {
- "npm": "@ai-sdk/openai-compatible",
- "options": {
- "baseURL": "http://localhost:11434/v1",
- },
+ @pytest.mark.parametrize("native_models", [{}, {"native": {}}])
+ def test_legacy_settings_are_not_modified(
+ self, tmp_path, opencode_v2, native_models
+ ):
+ path = tmp_path / "opencode.json"
+ path.write_text(
+ json.dumps(
+ {
+ "provider": {"omlx": {"models": {"legacy": {}}}},
+ "providers": {"omlx": {"models": native_models}},
}
- },
- "logLevel": "INFO",
+ )
+ )
+ opencode_v2.configure(
+ ctx(
+ model="fresh",
+ models=(IntegrationModel(id="fresh", model_type="llm"),),
+ models_discovery_succeeded=True,
+ )
+ )
+ config = json.loads(path.read_text())
+ assert set(config["providers"]["omlx"]["models"]) == set(native_models) | {
+ "fresh"
}
- config_path.write_text(json.dumps(existing))
+ assert config["provider"]["omlx"]["models"] == {"legacy": {}}
- oc = OpenCodeIntegration()
- with patch.object(OpenCodeIntegration, "CONFIG_PATH", config_path):
- oc.configure(ctx(port=9000, api_key="", model="llama"))
+ @pytest.mark.parametrize(
+ "original",
+ [
+ "invalid {",
+ "[]",
+ '{"providers": []}',
+ '{"providers": {"omlx": {"models": null}}}',
+ '{"providers": {}, "providers": {}}',
+ '{"providers": {"omlx": {}, "omlx": {}}}',
+ '{"x": /* unterminated',
+ '{"x": NaN}',
+ '{"x": Infinity}',
+ ],
+ )
+ def test_invalid_config_is_not_overwritten(self, tmp_path, original):
+ path = tmp_path / "opencode.jsonc"
+ path.write_text(original)
+ with (
+ patch.object(OpenCodeIntegration, "CONFIG_PATH", path),
+ patch("omlx.integrations.opencode._major_version", return_value=2),
+ pytest.raises(ValueError),
+ ):
+ OpenCodeIntegration().configure(ctx(model="test"))
+ assert path.read_text() == original
+ assert not list(tmp_path.glob("opencode.*.bak"))
- config = json.loads(config_path.read_text())
- # Existing provider preserved
- assert "ollama" in config["provider"]
- assert (
- config["provider"]["ollama"]["options"]["baseURL"]
- == "http://localhost:11434/v1"
+ @pytest.mark.parametrize(
+ ("model", "discovered"),
+ [("requested", False), ("requested", True), ("", False)],
+ )
+ def test_refresh_preserves_catalog_and_selects_only_available_default(
+ self, tmp_path, opencode_v2, model, discovered
+ ):
+ path = tmp_path / "opencode.json"
+ path.write_text(
+ '{"model":"omlx/saved", "providers":{"omlx":{"models":{"saved":{}}}}}'
)
- # omlx provider added
- assert "omlx" in config["provider"]
- assert (
- config["provider"]["omlx"]["options"]["baseURL"]
- == "http://127.0.0.1:9000/v1"
+ opencode_v2.configure(ctx(model=model, models_discovery_succeeded=discovered))
+ config = json.loads(path.read_text())
+ assert config["model"] == f"omlx/{model or 'saved'}"
+ assert set(config["providers"]["omlx"]["models"]) == (
+ {"saved", model} if model else {"saved"}
)
- # Other keys preserved
- assert config["logLevel"] == "INFO"
- def test_configure_creates_backup(self, tmp_path):
- config_path = tmp_path / "opencode.json"
- config_path.write_text('{"existing": true}')
-
- oc = OpenCodeIntegration()
- with patch.object(OpenCodeIntegration, "CONFIG_PATH", config_path):
- oc.configure(ctx(port=8000, api_key="", model="test"))
-
- # Check backup was created
- backups = list(tmp_path.glob("opencode.*.bak"))
- assert len(backups) == 1
- backup_content = json.loads(backups[0].read_text())
- assert backup_content == {"existing": True}
-
- def test_configure_handles_invalid_json(self, tmp_path):
- config_path = tmp_path / "opencode.json"
- config_path.write_text("not valid json {{{")
-
- oc = OpenCodeIntegration()
- with patch.object(OpenCodeIntegration, "CONFIG_PATH", config_path):
- oc.configure(ctx(port=8000, api_key="key", model="test"))
-
- # Should create new config despite invalid existing file
- config = json.loads(config_path.read_text())
- assert "omlx" in config["provider"]
-
- def test_configure_with_limits(self, tmp_path):
- oc = OpenCodeIntegration()
- config_path = tmp_path / "opencode" / "opencode.json"
+ @pytest.mark.parametrize(
+ ("window", "max_tokens", "expected_output"),
+ [
+ (32768, None, 2048),
+ (32768, 4096, 4096),
+ (32768, 32768, 24576),
+ (32768, 65536, 24576),
+ (2, None, 1),
+ (3, None, 2),
+ ],
+ )
+ def test_model_output_limit_leaves_room_for_input(
+ self, window, max_tokens, expected_output
+ ):
+ context = ctx(
+ model="test",
+ models=(
+ IntegrationModel(id="test", context_window=window, model_type="llm"),
+ ),
+ max_tokens=max_tokens,
+ )
+ limit = opencode_provider_config(context)["models"]["test"]["limit"]
+ assert limit == {"context": window, "output": expected_output}
+ assert (window - expected_output) * 4 >= window
- with patch.object(OpenCodeIntegration, "CONFIG_PATH", config_path):
- oc.configure(
- ctx(
- port=8000,
- api_key="key",
- model="qwen3.5",
- context_window=32768,
- max_tokens=8192,
- )
+ def test_unusable_context_preserves_existing_limits(
+ self, tmp_path, opencode_v2, capsys
+ ):
+ path = tmp_path / "opencode.json"
+ path.write_text(
+ '{"providers":{"omlx":{"models":{"test":'
+ '{"limit":{"context":100,"output":40}}}}}}'
+ )
+ opencode_v2.configure(
+ ctx(
+ model="test",
+ models=(IntegrationModel(id="test", context_window=1),),
+ models_discovery_succeeded=True,
)
+ )
+ limit = json.loads(path.read_text())["providers"]["omlx"]["models"]["test"][
+ "limit"
+ ]
+ assert limit == {"context": 100, "output": 40}
+ assert "context window for test is unusable" in capsys.readouterr().out
- config = json.loads(config_path.read_text())
- model_config = config["provider"]["omlx"]["models"]["qwen3.5"]
- assert model_config["limit"]["context"] == 32768
- assert model_config["limit"]["output"] == 8192
+ @pytest.mark.parametrize(("previous", "expected"), [(1, True), (False, False)])
+ def test_refresh_preserves_only_boolean_tool_capabilities(
+ self, tmp_path, opencode_v2, previous, expected
+ ):
+ path = tmp_path / "opencode.json"
+ models = {"test": {"capabilities": {"tools": previous}}}
+ path.write_text(json.dumps({"providers": {"omlx": {"models": models}}}))
+ opencode_v2.configure(ctx(model="test", model_type="llm"))
+ tools = json.loads(path.read_text())["providers"]["omlx"]["models"]["test"][
+ "capabilities"
+ ]["tools"]
+ assert tools is expected
- def test_configure_vlm_modalities(self, tmp_path):
- oc = OpenCodeIntegration()
- config_path = tmp_path / "opencode" / "opencode.json"
+ @pytest.mark.parametrize(
+ ("line_break", "escaped"),
+ [("\n", r"\ud83d\ude00"), ("\r\n", r"\ud800"), ("\r", r"\u00e9")],
+ )
+ def test_jsonc_conversion_preserves_values_and_original_backup(
+ self, tmp_path, line_break, escaped
+ ):
+ path = tmp_path / "opencode.jsonc"
+ original = (
+ "{\n// keep header\n"
+ f'"custom": "{escaped}",\n'
+ '"providers":{"omlx":{"models":{"vision":{"capabilities":'
+ '{"input":["text", /* block comment */ // line comment\n'
+ '"image"],"output":["text"]}}}}},\n}\n'
+ ).replace("\n", line_break)
+ path.write_bytes(original.encode())
- with patch.object(OpenCodeIntegration, "CONFIG_PATH", config_path):
- oc.configure(
- ctx(
- port=8000,
- api_key="key",
- model="qwen2.5-vl",
- model_type="vlm",
- )
+ with (
+ patch.object(OpenCodeIntegration, "CONFIG_PATH", path),
+ patch("omlx.integrations.opencode._major_version", return_value=2),
+ ):
+ OpenCodeIntegration().configure(ctx(model="vision", model_type="llm"))
+
+ updated = path.read_bytes().decode()
+ config = json.loads(updated)
+ assert updated == json.dumps(config, indent=2) + "\n"
+ assert next(tmp_path.glob("opencode.*.bak")).read_bytes() == original.encode()
+ assert config["custom"] == json.loads(f'"{escaped}"')
+ assert config["providers"]["omlx"]["models"]["vision"]["capabilities"][
+ "input"
+ ] == ["text"]
+
+ def test_backup_failure_warns_and_writes_config(
+ self, tmp_path, opencode_v2, capsys
+ ):
+ path = tmp_path / "opencode.json"
+ path.write_text('{"original":true}')
+ with patch(
+ "omlx.integrations.base.shutil.copy2", side_effect=OSError("denied")
+ ):
+ opencode_v2.configure(ctx(model="test"))
+ assert json.loads(path.read_text())["original"] is True
+ assert json.loads(path.read_text())["model"] == "omlx/test"
+ assert "Warning: could not create backup: denied" in capsys.readouterr().out
+ assert not list(tmp_path.glob("opencode.*.bak"))
+
+ def test_existing_hardlinked_config_is_not_modified(self, tmp_path, opencode_v2):
+ path = tmp_path / "opencode.json"
+ other = tmp_path / "other.json"
+ path.write_text('{"before": true}')
+ path.chmod(0o644)
+ os.link(path, other)
+ with pytest.raises(ValueError, match="singly linked regular file"):
+ opencode_v2.configure(ctx(model="test"))
+ assert path.samefile(other)
+ assert path.read_text() == '{"before": true}'
+ assert other.stat().st_mode & 0o777 == 0o644
+
+ def test_relaunch_warns_when_metadata_is_unavailable(
+ self, tmp_path, opencode_v2, capsys
+ ):
+ path = tmp_path / "opencode.json"
+ first = ctx(
+ model="test",
+ models=(IntegrationModel(id="test", context_window=32768, reasoning=True),),
+ models_discovery_succeeded=True,
+ )
+ second = ctx(
+ model="test",
+ models=(IntegrationModel(id="test"),),
+ models_discovery_succeeded=True,
+ )
+ opencode_v2.configure(first)
+ capsys.readouterr()
+ opencode_v2.configure(second)
+ model = json.loads(path.read_text())["providers"]["omlx"]["models"]["test"]
+ assert model["limit"] == {"context": 32768, "output": 2048}
+ assert model["capabilities"]["reasoning"] == {"supported": True}
+ warning = capsys.readouterr().out
+ assert "no current metadata for test" in warning
+ assert "limit, capabilities.reasoning" in warning
+ assert "may be stale" in warning
+
+ def test_relaunch_preserves_vision_when_model_type_is_unknown(
+ self, tmp_path, opencode_v2, capsys
+ ):
+ path = tmp_path / "opencode.json"
+ opencode_v2.configure(
+ ctx(
+ model="vision",
+ models=(IntegrationModel(id="vision", model_type="vlm"),),
+ models_discovery_succeeded=True,
)
-
- config = json.loads(config_path.read_text())
- model_config = config["provider"]["omlx"]["models"]["qwen2.5-vl"]
- assert model_config["attachment"] is True
- assert model_config["modalities"] == {
- "input": ["text", "image"],
- "output": ["text"],
- }
-
- def test_configure_with_context_window_only(self, tmp_path):
- oc = OpenCodeIntegration()
- config_path = tmp_path / "opencode" / "opencode.json"
-
- with patch.object(OpenCodeIntegration, "CONFIG_PATH", config_path):
- oc.configure(
- ctx(
- port=8000,
- api_key="key",
- model="qwen3.5",
- context_window=32768,
- )
+ )
+ capsys.readouterr()
+ opencode_v2.configure(
+ ctx(
+ model="vision",
+ models=(IntegrationModel(id="vision"),),
+ models_discovery_succeeded=True,
)
+ )
+ config = json.loads(path.read_text())
+ model = config["providers"]["omlx"]["models"]["vision"]
+ assert model["capabilities"]["input"] == ["text", "image"]
+ assert "model type" in capsys.readouterr().out
+
+ @pytest.mark.parametrize("major", [0, 1, 3, 99])
+ def test_unsupported_version_does_not_change_config(self, tmp_path, major):
+ path = tmp_path / "opencode.json"
+ path.write_text('{"original":true}')
+ with (
+ patch.object(OpenCodeIntegration, "CONFIG_PATH", path),
+ patch("omlx.integrations.opencode._major_version", return_value=major),
+ pytest.raises(ValueError, match="Unsupported OpenCode major version"),
+ ):
+ OpenCodeIntegration().configure(ctx(model="test"))
+ assert path.read_text() == '{"original":true}'
+ assert not list(tmp_path.glob("*.bak"))
- config = json.loads(config_path.read_text())
- model_config = config["provider"]["omlx"]["models"]["qwen3.5"]
- assert model_config["limit"]["context"] == 32768
- assert model_config["limit"]["output"] == 32768
-
- def test_configure_without_limits(self, tmp_path):
- oc = OpenCodeIntegration()
- config_path = tmp_path / "opencode" / "opencode.json"
+ def test_unknown_version_does_not_change_config(self, tmp_path):
+ path = tmp_path / "opencode.json"
+ path.write_text('{"original":true}')
+ with (
+ patch.object(OpenCodeIntegration, "CONFIG_PATH", path),
+ patch(
+ "omlx.integrations.opencode.subprocess.run",
+ side_effect=OSError("missing executable"),
+ ),
+ pytest.raises(RuntimeError, match="Cannot determine OpenCode version"),
+ ):
+ OpenCodeIntegration().configure(ctx(model="test"))
+ assert path.read_text() == '{"original":true}'
+ assert not list(tmp_path.glob("*.bak"))
- with patch.object(OpenCodeIntegration, "CONFIG_PATH", config_path):
- oc.configure(ctx(port=8000, api_key="key", model="qwen3.5"))
+ def test_jsonc_takes_precedence(self, tmp_path, monkeypatch):
+ from omlx.integrations.opencode import _config_path
+
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path))
+ monkeypatch.delenv("OPENCODE_CONFIG_DIR", raising=False)
+ directory = tmp_path / "opencode"
+ directory.mkdir()
+ (directory / "opencode.json").write_text("{}")
+ (directory / "opencode.jsonc").write_text("{}")
+ assert _config_path() == directory / "opencode.jsonc"
+
+ def test_config_directory_override(self, tmp_path, monkeypatch):
+ xdg_config = tmp_path / "xdg"
+ custom = tmp_path / "custom"
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(xdg_config))
+ monkeypatch.setenv("OPENCODE_CONFIG_DIR", str(custom))
+ with (
+ patch.object(OpenCodeIntegration, "CONFIG_PATH", None),
+ patch("omlx.integrations.opencode._major_version", return_value=2),
+ ):
+ OpenCodeIntegration().configure(ctx(model="test"))
+ assert (custom / "opencode.json").exists()
+ assert not (xdg_config / "opencode" / "opencode.json").exists()
+
+ def test_dangling_jsonc_symlink_is_not_skipped(self, tmp_path, monkeypatch):
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path))
+ monkeypatch.delenv("OPENCODE_CONFIG_DIR", raising=False)
+ directory = tmp_path / "opencode"
+ directory.mkdir()
+ jsonc = directory / "opencode.jsonc"
+ jsonc.symlink_to(directory / "missing.jsonc")
+ with (
+ patch.object(OpenCodeIntegration, "CONFIG_PATH", None),
+ patch("omlx.integrations.opencode._major_version", return_value=2),
+ pytest.raises(ValueError, match="Refusing to overwrite symlink"),
+ ):
+ OpenCodeIntegration().configure(ctx(model="test"))
+ assert jsonc.is_symlink()
+ assert not (directory / "opencode.json").exists()
- config = json.loads(config_path.read_text())
- model_config = config["provider"]["omlx"]["models"]["qwen3.5"]
- assert "limit" not in model_config
+ def test_launch_scrubs_python_env(self, opencode_v2):
+ with (
+ patch("omlx.integrations.opencode.os.execvpe") as execvpe,
+ patch.dict(
+ "os.environ",
+ {
+ "PYTHONHOME": "bundle",
+ "PYTHONPATH": "bundle",
+ "PYTHONDONTWRITEBYTECODE": "1",
+ },
+ ),
+ ):
+ opencode_v2.launch(ctx(model="qwen"))
+ binary, argv, env = execvpe.call_args.args
+ assert binary == "opencode"
+ assert argv == ["opencode"]
+ assert "PYTHONHOME" not in env
+ assert "PYTHONPATH" not in env
+ assert "PYTHONDONTWRITEBYTECODE" not in env
- def test_launch_scrubs_python_env(self, tmp_path):
- oc = OpenCodeIntegration()
- config_path = tmp_path / "opencode" / "opencode.json"
- captured = {}
+ def test_launch_flushes_warnings_before_exec(self, tmp_path):
+ result = subprocess.run(
+ [
+ sys.executable,
+ "-c",
+ """
+import os
+from pathlib import Path
+from omlx.integrations.base import IntegrationContext
+import omlx.integrations.opencode as opencode
+
+opencode._major_version = lambda: 2
+opencode.OpenCodeIntegration.CONFIG_PATH = Path(os.environ["TEST_CONFIG"])
+opencode.os.execvpe = lambda *args: os._exit(0)
+context = IntegrationContext(host="127.0.0.1", port=8000, api_key="", model="test")
+opencode.OpenCodeIntegration().launch(context)
+""",
+ ],
+ env={**os.environ, "TEST_CONFIG": str(tmp_path / "opencode.json")},
+ capture_output=True,
+ text=True,
+ check=True,
+ )
+ assert "OpenCode's running shared service" in result.stdout
- def fake_execvpe(binary, argv, env):
- captured["argv"] = argv
- captured["env"] = env
+ def test_reload_warning_describes_shared_service_effects(self, opencode_v2, capsys):
+ opencode_v2.configure(ctx(model="test"))
+ assert "Reload cancels pending permissions and forms" in capsys.readouterr().out
+ opencode_v2.configure(ctx(model="test", extra_args=("--standalone",)))
+ assert "shared service" not in capsys.readouterr().out
- base_env = {
- "PATH": "/usr/bin",
- "PYTHONHOME": "/bundle/python",
- "PYTHONPATH": "/bundle/lib",
- "PYTHONDONTWRITEBYTECODE": "1",
- }
- with (
- patch.object(OpenCodeIntegration, "CONFIG_PATH", config_path),
- patch("omlx.integrations.opencode.os.environ", base_env),
- patch("omlx.integrations.opencode.os.execvpe", side_effect=fake_execvpe),
- ):
- oc.launch(ctx(port=8000, api_key="key", model="qwen3.5"))
+ @pytest.mark.parametrize(
+ "extra_args",
+ [
+ ("--server", "https://example.invalid"),
+ ("--server=https://example.invalid",),
+ ],
+ )
+ def test_explicit_server_warns_without_suggesting_local_reload(
+ self, opencode_v2, capsys, extra_args
+ ):
+ opencode_v2.configure(ctx(model="test", extra_args=extra_args))
+ warning = capsys.readouterr().out
+ assert (
+ "selected OpenCode server may not use this local configuration" in warning
+ )
+ assert "opencode reload" not in warning
+ assert "example.invalid" not in warning
- assert captured["argv"] == ["opencode"]
- assert "PYTHONHOME" not in captured["env"]
- assert "PYTHONPATH" not in captured["env"]
- assert "PYTHONDONTWRITEBYTECODE" not in captured["env"]
+ def test_standalone_after_opencode_separator_does_not_suppress_warning(
+ self, opencode_v2, capsys
+ ):
+ opencode_v2.configure(
+ ctx(model="test", extra_args=("run", "--", "--standalone"))
+ )
+ assert "shared service may use a cached catalog" in capsys.readouterr().out
def test_type(self):
oc = OpenCodeIntegration()
@@ -1659,6 +2316,9 @@ def fake_execvpe(binary, argv, env):
"PYTHONHOME": "/bundle/python",
"PYTHONPATH": "/bundle/lib",
"PYTHONDONTWRITEBYTECODE": "1",
+ "CLAUDE_CODE_USE_BEDROCK": "1",
+ "CLAUDE_CODE_USE_VERTEX": "1",
+ "CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY": "0",
}
with (
patch("omlx.integrations.claude.os.environ", base_env),
@@ -1677,14 +2337,17 @@ def fake_execvpe(binary, argv, env):
)
env = captured["env"]
- assert env["ANTHROPIC_BASE_URL"] == "http://127.0.0.1:8000"
+ assert env["ANTHROPIC_BASE_URL"] == "http://127.0.0.1:8000/claude"
+ assert env["CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"] == "1"
+ assert "CLAUDE_CODE_USE_BEDROCK" not in env
+ assert "CLAUDE_CODE_USE_VERTEX" not in env
assert env["ANTHROPIC_AUTH_TOKEN"] == "secret"
assert env["ANTHROPIC_API_KEY"] == ""
- assert env["ANTHROPIC_MODEL"] == "qwen3.5"
- assert env["ANTHROPIC_DEFAULT_OPUS_MODEL"] == "qwen3.5"
- assert env["ANTHROPIC_DEFAULT_SONNET_MODEL"] == "qwen3.5"
- assert env["ANTHROPIC_DEFAULT_HAIKU_MODEL"] == "qwen3.5"
- assert env["CLAUDE_CODE_SUBAGENT_MODEL"] == "qwen3.5"
+ assert env["ANTHROPIC_MODEL"] == "omlx-claude/qwen3.5"
+ assert env["ANTHROPIC_DEFAULT_OPUS_MODEL"] == "omlx-claude/qwen3.5"
+ assert env["ANTHROPIC_DEFAULT_SONNET_MODEL"] == "omlx-claude/qwen3.5"
+ assert env["ANTHROPIC_DEFAULT_HAIKU_MODEL"] == "omlx-claude/qwen3.5"
+ assert env["CLAUDE_CODE_SUBAGENT_MODEL"] == "omlx-claude/qwen3.5"
assert env["CLAUDE_CODE_AUTO_COMPACT_WINDOW"] == "131072"
assert env["CLAUDE_CODE_MAX_CONTEXT_TOKENS"] == "131072"
assert env["CLAUDE_CODE_AUTO_MODE_SERVER"] == "0"
@@ -2026,10 +2689,10 @@ def fake_execvpe(binary, argv, env):
)
env = captured["env"]
- assert env["ANTHROPIC_DEFAULT_OPUS_MODEL"] == "opus-local"
- assert env["ANTHROPIC_DEFAULT_SONNET_MODEL"] == "sonnet-local"
- assert env["ANTHROPIC_DEFAULT_HAIKU_MODEL"] == "haiku-local"
- assert env["CLAUDE_CODE_SUBAGENT_MODEL"] == "haiku-local"
+ assert env["ANTHROPIC_DEFAULT_OPUS_MODEL"] == "omlx-claude/opus-local"
+ assert env["ANTHROPIC_DEFAULT_SONNET_MODEL"] == "omlx-claude/sonnet-local"
+ assert env["ANTHROPIC_DEFAULT_HAIKU_MODEL"] == "omlx-claude/haiku-local"
+ assert env["CLAUDE_CODE_SUBAGENT_MODEL"] == "omlx-claude/haiku-local"
def test_launch_open_server_uses_omlx_token(self):
cc = ClaudeCodeIntegration()
@@ -2442,6 +3105,7 @@ def fake_exec(file, argv, env):
assert captured["path"] == existing_config
assert "COPILOT_PROVIDER_BASE_URL" not in env
assert "COPILOT_MODEL" not in env
+ assert env["COPILOT_OFFLINE"] == "true"
assert "PYTHONHOME" not in env
assert "PYTHONPATH" not in env
assert "PYTHONDONTWRITEBYTECODE" not in env
From aeab41b4e2d5a2aa47ec1800dc99be3e63bb6ea7 Mon Sep 17 00:00:00 2001
From: Mike Wallio
Date: Wed, 4 Nov 2026 09:22:09 -0500
Subject: [PATCH 08/24] feat(server): add admin controls and typed runtime
lifecycle contracts
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
---
.../oMLXTests/Fixtures/stats-session.json | 6 -
apps/omlx-web/omlx_web/routes.py | 10 +
apps/omlx-web/omlx_web/static/js/dashboard.js | 105 ++-
apps/omlx-web/omlx_web/templates/chat.html | 67 +-
.../dashboard/_modal_model_settings.html | 36 +-
.../omlx_web/templates/dashboard/_models.html | 25 +-
.../omlx_web/templates/dashboard/_navbar.html | 12 +
.../test_admin_model_settings_template.py | 149 +++
.../tests/test_admin_upload_tracking.py | 250 +++++
apps/omlx-web/tests/test_web_ui_contract.py | 13 +-
omlx/admin/benchmark.py | 42 +-
omlx/admin/model_recommender.py | 7 +-
omlx/admin/routes.py | 122 ++-
omlx/cache/paged_cache.py | 142 +--
omlx/engine/__init__.py | 2 +-
omlx/engine/base.py | 75 +-
omlx/engine/batched.py | 58 +-
omlx/engine/decision.py | 6 +-
omlx/engine_core.py | 185 ++--
omlx/engine_pool.py | 385 ++++++--
omlx/exceptions.py | 70 +-
omlx/model_classification.py | 88 ++
omlx/model_discovery.py | 888 +++++++++++++++---
omlx/model_profiles.py | 3 +-
omlx/model_settings.py | 272 +++---
omlx/models/__init__.py | 2 +-
omlx/models/base_model.py | 2 +-
omlx/models/d3.py | 26 +-
omlx/models/decision.py | 7 +-
omlx/output_collector.py | 14 +-
omlx/request.py | 106 ++-
omlx/scheduler.py | 43 +-
omlx/server.py | 489 ++++++++--
omlx/specprefill/planning.py | 8 +-
omlx/specprefill/target.py | 21 +-
omlx/turboquant_kv.py | 17 +-
omlx/utils/model_loading.py | 267 +++++-
omlx/utils/optional_deps.py | 23 +
omlx/utils/safetensors_shards.py | 62 ++
omlx/utils/sampling.py | 6 +-
omlx/utils/tokenizer.py | 29 +
tests/conftest.py | 20 +
tests/integration/test_e2e_streaming.py | 12 +
tests/integration/test_live_tool_calling.py | 311 ++++++
.../integration/test_responses_tool_merge.py | 49 +-
tests/integration/test_server_endpoints.py | 28 +-
tests/test_admin_chat_model_filter.py | 252 +++++
tests/test_admin_profiles_api.py | 181 +++-
tests/test_api_utils.py | 1 -
tests/test_batched_engine.py | 54 +-
tests/test_cluster_deployment.py | 56 +-
tests/test_cluster_performance.py | 28 +-
tests/test_cluster_progressive_loading.py | 35 +-
tests/test_decisions.py | 22 +
tests/test_engine_core.py | 12 +
tests/test_engine_keepalive.py | 2 +-
tests/test_engine_pool.py | 428 ++++++++-
tests/test_engine_preflight.py | 2 +
tests/test_hf_downloader.py | 23 +-
tests/test_hybrid_batch_cache_patch.py | 37 +
tests/test_markitdown_integration.py | 264 ++++++
tests/test_model_discovery.py | 256 ++++-
tests/test_model_loading.py | 30 +
tests/test_model_recommender.py | 25 +
tests/test_model_warmup.py | 226 +++++
tests/test_optional_deps.py | 41 +
tests/test_output_collector.py | 1 +
tests/test_paged_cache.py | 16 +-
tests/test_per_engine_threads.py | 46 +
tests/test_qwen38_modelopt_mixed.py | 9 +
tests/test_qwen4_mxfp4_ple.py | 470 +++++++++
tests/test_reasoning_effort.py | 5 +-
tests/test_reasoning_effort_discovery.py | 117 +++
tests/test_sampling.py | 29 +
tests/test_server.py | 364 ++++++-
tests/test_server_main.py | 2 +
tests/test_settings.py | 13 +-
tests/test_specprefill.py | 8 +
tests/test_specprefill_planning.py | 19 +-
tests/test_specprefill_target.py | 15 +
tests/test_systemone.py | 45 +
tests/test_v1_models_visibility.py | 161 +++-
82 files changed, 6870 insertions(+), 985 deletions(-)
create mode 100644 apps/omlx-web/tests/test_admin_upload_tracking.py
create mode 100644 omlx/model_classification.py
create mode 100644 omlx/utils/optional_deps.py
create mode 100644 omlx/utils/safetensors_shards.py
create mode 100644 tests/integration/test_live_tool_calling.py
create mode 100644 tests/test_admin_chat_model_filter.py
create mode 100644 tests/test_hybrid_batch_cache_patch.py
create mode 100644 tests/test_model_warmup.py
create mode 100644 tests/test_optional_deps.py
create mode 100644 tests/test_qwen4_mxfp4_ple.py
create mode 100644 tests/test_reasoning_effort_discovery.py
diff --git a/apps/omlx-mac/Tests/oMLXTests/Fixtures/stats-session.json b/apps/omlx-mac/Tests/oMLXTests/Fixtures/stats-session.json
index 05cf3e023a..a81a02c5f4 100644
--- a/apps/omlx-mac/Tests/oMLXTests/Fixtures/stats-session.json
+++ b/apps/omlx-mac/Tests/oMLXTests/Fixtures/stats-session.json
@@ -25,12 +25,6 @@
"commit": null,
"url": null
},
- "mlx-embeddings": {
- "name": "mlx-embeddings",
- "version": "0.1.0",
- "commit": null,
- "url": null
- },
"mlx-audio": {
"name": "mlx-audio",
"version": "0.4.3",
diff --git a/apps/omlx-web/omlx_web/routes.py b/apps/omlx-web/omlx_web/routes.py
index 197446989c..4df07d4453 100644
--- a/apps/omlx-web/omlx_web/routes.py
+++ b/apps/omlx-web/omlx_web/routes.py
@@ -164,6 +164,16 @@ async def chat_page(request: Request, is_admin: bool = Depends(require_admin)):
return templates.TemplateResponse(request, "chat.html", {"api_key": api_key or ""})
+@router.get("/imagine", response_class=HTMLResponse)
+async def imagine_page(request: Request, is_admin: bool = Depends(require_admin)):
+ """Render image generation and editing with the host's API key."""
+ _sync_locale()
+ api_key = _host.main_api_key()
+ return templates.TemplateResponse(
+ request, "imagine.html", {"api_key": api_key or ""}
+ )
+
+
@router.get("/static/{path:path}")
async def admin_static(path: str):
"""Serve static files for admin panel (CSS, JS, fonts, logos, etc.)."""
diff --git a/apps/omlx-web/omlx_web/static/js/dashboard.js b/apps/omlx-web/omlx_web/static/js/dashboard.js
index b70220a5dd..741f9c998e 100644
--- a/apps/omlx-web/omlx_web/static/js/dashboard.js
+++ b/apps/omlx-web/omlx_web/static/js/dashboard.js
@@ -655,9 +655,13 @@
uploadAllModels: [],
uploadOqModelsLoaded: false,
uploadTasks: [],
+ uploadTasksLoading: false,
+ uploadTasksLoaded: false,
+ uploadTasksError: '',
uploadError: '',
uploadSuccess: '',
_uploadRefreshTimer: null,
+ _uploadRefreshEnabled: false,
// Upload modal
uploadModalOpen: false,
uploadModalModelPath: '',
@@ -880,6 +884,7 @@
window.addEventListener('popstate', () => {
this.applyTabStateFromUrl();
+ this.refreshUploadTab();
this.settingsScrollToHash();
});
@@ -922,6 +927,7 @@
if (this.modelsTab === 'quantizer') {
loads.push(this.loadOQModels());
}
+ loads.push(this.refreshUploadTab());
if (this.msInitialized && this.msAvailable) {
loads.push(this.loadMSTasks());
}
@@ -936,6 +942,9 @@
['pending', 'loading', 'quantizing', 'saving'].includes(t.status));
if (hasOqActive) this.startOQRefresh();
} else {
+ if (this.mainTab !== 'models' || this.modelsTab !== 'uploader') {
+ this.stopUploadRefresh();
+ }
this.stopHFRefresh();
this.stopMSRefresh();
this.stopOQRefresh();
@@ -1179,10 +1188,7 @@
if (tab === 'quantizer') {
this.loadOQModels();
}
- if (tab === 'uploader') {
- if (!this.uploadOqModelsLoaded) this.loadUploadOqModels();
- this.loadUploadTasks();
- }
+ this.refreshUploadTab();
if (tab === 'downloader' && this.downloaderSource === 'recommended') {
this.loadRecommendations();
}
@@ -1802,6 +1808,11 @@
if (g) out.guided_grammar = g;
continue;
}
+ if (k === 'mm_processor_kwargs') {
+ const options = this.mmProcessorOptions(ms);
+ if (options || ms.is_minicpm_model) out[k] = options || {};
+ continue;
+ }
// Standard field: omit unset values entirely — the server
// treats absent universal keys as "reset to default" when
// the profile is applied (snapshot semantics).
@@ -2238,6 +2249,7 @@
buildModelSettingsState(model, settings) {
const s = settings || {};
const isDiffusion = this.isDiffusionModel(model);
+ const isMiniCPM = model?.config_model_type === 'minicpmv4_7';
const ctKwargEntries = this.buildCtKwargEntries(
s.chat_template_kwargs,
s.forced_ct_kwargs,
@@ -2331,6 +2343,11 @@
qwen35_ane_prefill_cpu_threads: s.qwen35_ane_prefill_cpu_threads ?? 8,
qwen35_ane_prefill_cpu_shared_resource: s.qwen35_ane_prefill_cpu_shared_resource !== false,
specprefill_enabled: s.specprefill_enabled || false,
+ mm_processor_kwargs: {
+ downsample_mode: '',
+ max_slice_nums: null,
+ ...s.mm_processor_kwargs,
+ },
specprefill_draft_model: s.specprefill_draft_model || '',
specprefill_keep_pct: s.specprefill_keep_pct ? String(s.specprefill_keep_pct) : '0.2',
specprefill_threshold: s.specprefill_threshold || null,
@@ -2341,7 +2358,8 @@
dflash_draft_quant_group_size: s.dflash_draft_quant_group_size || 64,
dflash_draft_window_size: s.dflash_draft_window_size ?? null,
dflash_block_size: s.dflash_block_size ?? null,
- dflash_verify_mode: s.dflash_verify_mode || 'adaptive',
+ dflash_verify_mode: s.dflash_verify_mode || (isMiniCPM ? 'dflash' : 'adaptive'),
+ is_minicpm_model: isMiniCPM,
dflash_compatible: model?.dflash_compatible !== false,
dflash_compatibility_reason: model?.dflash_compatibility_reason || '',
mtp_enabled: s.mtp_enabled || false,
@@ -2367,6 +2385,14 @@
};
},
+ mmProcessorOptions(ms = this.modelSettings) {
+ const options = { ...ms.mm_processor_kwargs };
+ for (const key of ['downsample_mode', 'max_slice_nums']) {
+ if (options[key] == null || options[key] === '') delete options[key];
+ }
+ return Object.keys(options).length ? options : null;
+ },
+
moeExpertOffloadResidentInvalid() {
const percent = Number(this.modelSettings.moe_expert_offload_resident_percent);
return (
@@ -3715,8 +3741,9 @@
? parseInt(ms.dflash_block_size)
: null,
dflash_verify_mode: ms.dflash_enabled
- ? (ms.dflash_verify_mode || 'adaptive')
+ ? (ms.dflash_verify_mode || (ms.is_minicpm_model ? 'dflash' : 'adaptive'))
: null,
+ mm_processor_kwargs: this.mmProcessorOptions(ms),
mtp_enabled: !!ms.mtp_enabled,
mtp_adaptive_max_depth: ms.mtp_enabled
? parseInt(ms.mtp_adaptive_max_depth || '3')
@@ -4103,7 +4130,7 @@
this.modelSettings.dflash_draft_quant_group_size = null;
this.modelSettings.dflash_draft_window_size = null;
this.modelSettings.dflash_block_size = null;
- this.modelSettings.dflash_verify_mode = 'adaptive';
+ this.modelSettings.dflash_verify_mode = this.modelSettings.is_minicpm_model ? 'dflash' : 'adaptive';
this.modelSettings.mtp_enabled = false;
this.modelSettings.mtp_adaptive_max_depth = '3';
this.modelSettings.trust_remote_code = false;
@@ -8598,20 +8625,46 @@
}
},
+ async refreshUploadTab() {
+ if (this.mainTab !== 'models' || this.modelsTab !== 'uploader') {
+ this.stopUploadRefresh();
+ return;
+ }
+ this.startUploadRefresh();
+ const loads = [this.loadUploadTasks()];
+ if (!this.uploadOqModelsLoaded) loads.push(this.loadUploadOqModels());
+ await Promise.all(loads);
+ },
+
async loadUploadTasks() {
+ if (this.uploadTasksLoading) return;
+ this.uploadTasksLoading = true;
+ if (this._uploadRefreshTimer !== null) {
+ clearTimeout(this._uploadRefreshTimer);
+ this._uploadRefreshTimer = null;
+ }
try {
const response = await fetch('/admin/api/upload/tasks');
- if (response.ok) {
- const data = await response.json();
- this.uploadTasks = data.tasks || [];
- const hasActive = this.uploadTasks.some(t =>
- ['pending', 'uploading'].includes(t.status));
- if (!hasActive) {
- this.stopUploadRefresh();
- }
+ if (!response.ok) {
+ this.uploadTasksError = `${window.t('models.uploader.queue_error')} (HTTP ${response.status})`;
+ return;
}
+ const data = await response.json();
+ if (!data || !Array.isArray(data.tasks) || !data.tasks.every(task =>
+ task && typeof task.task_id === 'string' &&
+ typeof task.model_name === 'string' &&
+ ['pending', 'uploading', 'completed', 'failed', 'cancelled'].includes(task.status))) {
+ throw new Error('Invalid upload task response');
+ }
+ this.uploadTasks = data.tasks;
+ this.uploadTasksLoaded = true;
+ this.uploadTasksError = '';
} catch (err) {
+ this.uploadTasksError = window.t('models.uploader.queue_error');
console.error('Failed to load upload tasks:', err);
+ } finally {
+ this.uploadTasksLoading = false;
+ if (this._uploadRefreshEnabled) this.startUploadRefresh();
}
},
@@ -8634,15 +8687,25 @@
},
startUploadRefresh() {
- this.stopUploadRefresh();
- this._uploadRefreshTimer = setInterval(() => {
- this.loadUploadTasks();
- }, 2000);
+ if (this.mainTab !== 'models' || this.modelsTab !== 'uploader') {
+ this.stopUploadRefresh();
+ return;
+ }
+ this._uploadRefreshEnabled = true;
+ if (this._uploadRefreshTimer !== null || this.uploadTasksLoading) return;
+ const hasActive = this.uploadTasks.some(task =>
+ ['pending', 'uploading'].includes(task.status));
+ const delay = hasActive && !this.uploadTasksError ? 2000 : 6000;
+ this._uploadRefreshTimer = setTimeout(async () => {
+ this._uploadRefreshTimer = null;
+ await this.loadUploadTasks();
+ }, delay);
},
stopUploadRefresh() {
- if (this._uploadRefreshTimer) {
- clearInterval(this._uploadRefreshTimer);
+ this._uploadRefreshEnabled = false;
+ if (this._uploadRefreshTimer !== null) {
+ clearTimeout(this._uploadRefreshTimer);
this._uploadRefreshTimer = null;
}
},
diff --git a/apps/omlx-web/omlx_web/templates/chat.html b/apps/omlx-web/omlx_web/templates/chat.html
index 326767c35a..24a68cf078 100644
--- a/apps/omlx-web/omlx_web/templates/chat.html
+++ b/apps/omlx-web/omlx_web/templates/chat.html
@@ -1374,7 +1374,12 @@ {{ t('login.login.label_api_key') }}
-
+
+
+
+ {{ t('navbar.tab.imagine') }}
+
@@ -2946,7 +2951,8 @@ {{ t('chat.key
},
// VLM Detection State
- modelTypeMap: {}, // { modelId: "llm"|"vlm"|"embedding"|"reranker" }
+ modelTypeMap: {}, // { modelId: "llm"|"vlm"|"embedding"|"reranker"|"image" }
+ modelEngineTypeMap: {}, // { modelId: "llm"|"vlm"|"embedding"|"reranker"|"image" }
aliasToGateway: {}, // { aliasName: gatewayId } maps alias to directory name
// Session Prompt
@@ -4408,12 +4414,26 @@ {{ t('chat.key
if (!resp.ok) return;
const data = await resp.json();
const map = {};
+ const engineMap = {};
const rtMap = {};
for (const m of (data.models || [])) {
- map[m.id] = m.model_type || 'llm';
- rtMap[m.id] = Boolean(m.realtime_stt);
+ if (m.id) {
+ map[m.id] = m.model_type || 'llm';
+ engineMap[m.id] = m.engine_type || '';
+ rtMap[m.id] = Boolean(m.realtime_stt);
+ }
+ }
+ for (const m of (data.models || [])) {
+ if (m.model_alias && map[m.model_alias] === undefined) {
+ map[m.model_alias] = m.model_type || 'llm';
+ engineMap[m.model_alias] = m.engine_type || '';
+ rtMap[m.model_alias] = Boolean(m.realtime_stt);
+ } else if (m.model_alias) {
+ console.warn(`Ignoring model alias '${m.model_alias}' because it conflicts with another model id`);
+ }
}
this.modelTypeMap = map;
+ this.modelEngineTypeMap = engineMap;
this.realtimeSttMap = rtMap;
this._mirrorAliasModelTypes();
} catch (e) {
@@ -4427,6 +4447,10 @@ {{ t('chat.key
if (t && !this.modelTypeMap[alias]) {
this.modelTypeMap[alias] = t;
}
+ const e = this.modelEngineTypeMap[gatewayId];
+ if (e && !this.modelEngineTypeMap[alias]) {
+ this.modelEngineTypeMap[alias] = e;
+ }
if (this.realtimeSttMap[gatewayId] && !(alias in this.realtimeSttMap)) {
this.realtimeSttMap[alias] = true;
}
@@ -5262,6 +5286,7 @@ {{ t('chat.key
const modelsData = await modelsResponse.json();
const allModels = modelsData.data || [];
+ // Filter out audio/embedding/reranker/image — chat only works with LLM/VLM
// Favorite gateway ids from the admin list; used to sort favorites first
const favoriteIds = new Set(
(this._adminModelsList || []).filter(m => m.is_favorite).map(m => m.id)
@@ -5272,8 +5297,10 @@ {{ t('chat.key
this.availableModels = this.dedupeAvailableModels(
allModels.filter(m => {
const gatewayId = this.aliasToGateway[m.id] || m.id;
- const t = (this.modelTypeMap[gatewayId] || '').toLowerCase();
- return t !== 'audio_tts' && t !== 'audio_sts' && t !== 'embedding' && t !== 'reranker' && t !== 'decision';
+ const t = (this.modelTypeMap[gatewayId] || this.modelTypeMap[m.id] || '').toLowerCase();
+ const e = (this.modelEngineTypeMap[gatewayId] || this.modelEngineTypeMap[m.id] || '').toLowerCase();
+ return t !== 'audio_tts' && t !== 'audio_sts' && t !== 'embedding'
+ && t !== 'reranker' && t !== 'decision' && t !== 'image' && e !== 'image';
}).map(m => ({
id: this.aliasToGateway[m.id] || m.id, // gateway id for API calls
name: m.id, // original name (alias or directory name) for display
@@ -5283,6 +5310,7 @@ {{ t('chat.key
}))
);
+
// Get default model from health endpoint
let defaultModel = null;
if (healthResponse.ok) {
@@ -5695,9 +5723,34 @@ {{ t('chat.key
if (session) session.systemPrompt = '';
},
+ isAvailableModel(modelId) {
+ return this.isModelAvailableOnServer(modelId);
+ },
+
+ fallbackModel(defaultModel = null) {
+ const gatewayDefault = this.resolveGatewayModelId(defaultModel);
+ if (this.isAvailableModel(gatewayDefault)) {
+ return gatewayDefault;
+ }
+ return this.availableModels[0]?.id || null;
+ },
+
+ ensureValidCurrentModel(defaultModel = null) {
+ if (!this.isAvailableModel(this.currentModel)) {
+ this.currentModel = this.fallbackModel(defaultModel);
+ } else {
+ this.currentModel = this.resolveGatewayModelId(this.currentModel);
+ }
+ },
+
async selectModel(modelId) {
- const session = this.getChatSession(this.currentChatId, true);
const gatewayId = this.resolveGatewayModelId(modelId);
+ if (!this.isAvailableModel(gatewayId)) {
+ this.ensureValidCurrentModel();
+ return;
+ }
+
+ const session = this.getChatSession(this.currentChatId, true);
try {
if (session?.model && session.model !== gatewayId) {
this.syncSessionModelSettingsFromUi(session);
diff --git a/apps/omlx-web/omlx_web/templates/dashboard/_modal_model_settings.html b/apps/omlx-web/omlx_web/templates/dashboard/_modal_model_settings.html
index 92919906fe..c31ba2cb1e 100644
--- a/apps/omlx-web/omlx_web/templates/dashboard/_modal_model_settings.html
+++ b/apps/omlx-web/omlx_web/templates/dashboard/_modal_model_settings.html
@@ -47,6 +47,7 @@ {{
{{ t('modal.model_settings.model_type_audio_tts') }}
{{ t('modal.model_settings.model_type_audio_sts') }}
{{ t('modal.model_settings.model_type_decision') }}
+ {{ t('modal.model_settings.model_type_image') }}
@@ -518,6 +520,36 @@ {{ t('m
+
+
+
+
{{ t('modal.model_settings.acceleration_label') }}
@@ -676,9 +708,9 @@ {{
{{ t('modal.model_settings.dflash_verify_mode') }}
- {{ t('modal.model_settings.dflash_verify_adaptive') }}
+ {{ t('modal.model_settings.dflash_verify_adaptive') }}
dflash
- {{ t('modal.model_settings.dflash_verify_off') }}
+ {{ t('modal.model_settings.dflash_verify_off') }}
{{ t('modal.model_settings.dflash_verify_hint') }}
diff --git a/apps/omlx-web/omlx_web/templates/dashboard/_models.html b/apps/omlx-web/omlx_web/templates/dashboard/_models.html
index 08a04e09db..9bfeb4f487 100644
--- a/apps/omlx-web/omlx_web/templates/dashboard/_models.html
+++ b/apps/omlx-web/omlx_web/templates/dashboard/_models.html
@@ -1943,14 +1943,26 @@
-
+
-
+
+
+
+
+
-
+
@@ -490,6 +497,11 @@
{{ t('status.layout.customize') }}
+
+
+ {{ t('navbar.tab.imagine') }}
+
Reasoning Parser" not in modal_html
assert ">SpecPrefill" not in modal_html
@@ -176,6 +178,25 @@ def test_dflash_ui_omits_settings_removed_from_the_admin_api():
assert 'value="ddtree"' not in html
+def test_minicpm_media_controls_are_editable_and_model_specific():
+ html = _model_settings_template()
+ section = _section(
+ html,
+ '',
+ "",
+ )
+ assert 'id="ms-media"' in section
+ assert 'x-model="modelSettings.mm_processor_kwargs.downsample_mode"' in section
+ assert 'x-model.number="modelSettings.mm_processor_kwargs.max_slice_nums"' in section
+ for mode in ("", "4x", "16x"):
+ assert f'' in section
+ assert 'min="1" step="1"' in section
+ assert (
+ "('ms-media', t('modal.model_settings.minicpm_media'), "
+ '"modelSettings.is_minicpm_model")'
+ ) in html
+
+
def test_model_settings_feature_i18n_keys_exist_in_every_locale():
root = Path(__file__).resolve().parents[1]
i18n_dir = root / "omlx_web/i18n"
@@ -222,6 +243,11 @@ def test_model_settings_feature_i18n_keys_exist_in_every_locale():
"modal.model_settings.qwen_ane_tune_test",
"modal.model_settings.qwen_ane_tune_throughput",
"modal.model_settings.qwen_ane_tail_padding",
+ "modal.model_settings.minicpm_media",
+ "modal.model_settings.minicpm_downsample_mode",
+ "modal.model_settings.minicpm_downsample_mode_hint",
+ "modal.model_settings.minicpm_max_slice_nums",
+ "modal.model_settings.minicpm_max_slice_nums_hint",
}
for locale_path in sorted(i18n_dir.glob("*.json")):
@@ -628,6 +654,100 @@ def test_profile_editor_behavior():
return state;
}
+test('MiniCPM uses fixed DSpark defaults without changing other families', async () => {
+ for (const [family, mode] of [['minicpmv4_7', 'dflash'], ['qwen3_5', 'adaptive']]) {
+ let payload;
+ const state = setup(async (url, options) => {
+ assert.equal(options.method, 'PUT');
+ payload = JSON.parse(options.body);
+ return {ok: true, json: async () => ({})};
+ });
+ state.selectedModel = {id: 'model-a', config_model_type: family};
+ const controls = family === 'minicpmv4_7' ? {downsample_mode: '4x', max_slice_nums: 36} : null;
+ state.modelSettings = state.buildModelSettingsState(state.selectedModel, {mm_processor_kwargs: controls});
+ assert.equal(state.modelSettings.dflash_verify_mode, mode);
+ state.modelSettings.dflash_enabled = true;
+ state.modelSettings.dflash_draft_model = '/paired/helper';
+ state.modelSettings.dflash_verify_mode = '';
+ state.loadModels = async () => {};
+ await state.saveModelSettings();
+ assert.equal(payload.dflash_verify_mode, mode);
+ assert.deepEqual(payload.mm_processor_kwargs, controls);
+ state.profileFields = {universal: [], model_specific: ['mm_processor_kwargs']};
+ const profile = JSON.parse(JSON.stringify(state.formValuesForProfile()));
+ assert.deepEqual(profile.mm_processor_kwargs, controls === null ? undefined : controls);
+ const explicit = state.buildModelSettingsState(state.selectedModel, {dflash_verify_mode: 'adaptive'});
+ assert.equal(explicit.dflash_verify_mode, 'adaptive');
+ }
+});
+
+test('MiniCPM media edits save without mutating stored settings', async () => {
+ let payload;
+ const state = setup(async (url, options) => {
+ payload = JSON.parse(options.body);
+ return {ok: true, json: async () => ({})};
+ });
+ state.selectedModel = {id: 'model-a', config_model_type: 'minicpmv4_7'};
+ const stored = {mm_processor_kwargs: {downsample_mode: '4x', max_slice_nums: 36}};
+ state.modelSettings = state.buildModelSettingsState(state.selectedModel, stored);
+ state.loadModels = async () => {};
+ state.profileFields = {universal: [], model_specific: ['mm_processor_kwargs']};
+
+ state.modelSettings.mm_processor_kwargs.downsample_mode = '16x';
+ state.modelSettings.mm_processor_kwargs.max_slice_nums = 3;
+ await state.saveModelSettings();
+ assert.deepEqual(payload.mm_processor_kwargs, {downsample_mode: '16x', max_slice_nums: 3});
+ assert.deepEqual(stored.mm_processor_kwargs, {downsample_mode: '4x', max_slice_nums: 36});
+ const profile = state.formValuesForProfile();
+ assert.deepEqual(JSON.parse(JSON.stringify(profile.mm_processor_kwargs)), payload.mm_processor_kwargs);
+
+ state.modelSettings.mm_processor_kwargs.downsample_mode = '';
+ state.modelSettings.mm_processor_kwargs.max_slice_nums = '';
+ await state.saveModelSettings();
+ assert.equal(payload.mm_processor_kwargs, null);
+ assert.deepEqual(JSON.parse(JSON.stringify(state.formValuesForProfile().mm_processor_kwargs)), {});
+ assert.equal(profile.mm_processor_kwargs.downsample_mode, '16x');
+ assert.equal(profile.mm_processor_kwargs.max_slice_nums, 3);
+
+ state.modelSettings.mm_processor_kwargs.downsample_mode = '4x';
+ await state.saveModelSettings();
+ assert.deepEqual(payload.mm_processor_kwargs, {downsample_mode: '4x'});
+ state.modelSettings.mm_processor_kwargs.downsample_mode = '';
+ state.modelSettings.mm_processor_kwargs.max_slice_nums = 1;
+ await state.saveModelSettings();
+ assert.deepEqual(payload.mm_processor_kwargs, {max_slice_nums: 1});
+});
+
+test('MiniCPM media controls restore applied profiles and preserve defaults', async () => {
+ let saved;
+ const applied = {active_profile_name: 'visual', mm_processor_kwargs: {downsample_mode: '16x', max_slice_nums: 7}};
+ const state = setup(async (url, options) => {
+ if (url.endsWith('/apply')) {
+ return {ok: true, json: async () => ({settings: applied})};
+ }
+ saved = JSON.parse(options.body);
+ return {ok: true, json: async () => ({profile: saved})};
+ });
+ state.selectedModel = {id: 'model-a', config_model_type: 'minicpmv4_7'};
+ state.models = [state.selectedModel];
+ state.profileFields = {universal: [], model_specific: ['mm_processor_kwargs']};
+ state.modelSettings = state.buildModelSettingsState(state.selectedModel, {});
+ assert.equal(state.modelSettings.mm_processor_kwargs.downsample_mode, '');
+ assert.equal(state.modelSettings.mm_processor_kwargs.max_slice_nums, null);
+ assert.deepEqual(JSON.parse(JSON.stringify(state.formValuesForProfile().mm_processor_kwargs)), {});
+ await state.applyProfileToForm({name: 'visual'});
+ assert.equal(state.modelSettings.mm_processor_kwargs.downsample_mode, '16x');
+ assert.equal(state.modelSettings.mm_processor_kwargs.max_slice_nums, 7);
+ state.modelSettings.mm_processor_kwargs.downsample_mode = '4x';
+ state.modelSettings.mm_processor_kwargs.max_slice_nums = 2;
+ state.applyProfileToForm = async () => {};
+ state.newProfile = {display_name: 'Detail', api_name: 'detail'};
+ await state.createProfile();
+ assert.equal(state.profileError, '');
+ assert.deepEqual(saved.settings.mm_processor_kwargs, {downsample_mode: '4x', max_slice_nums: 2});
+ assert.deepEqual(applied.mm_processor_kwargs, {downsample_mode: '16x', max_slice_nums: 7});
+});
+
test('Template apply uses server identity and effective settings', async () => {
const requests = [];
const state = setup(async (url, options) => {
@@ -706,6 +826,35 @@ def test_profile_editor_behavior():
});
});
+test('MiniCPM media edits are compared with the original modal values', async () => {
+ let body;
+ const state = setup(async (url, options) => {
+ body = JSON.parse(options.body);
+ return {ok: true, json: async () => ({})};
+ });
+ state.loadModels = async () => {};
+ state.selectedModel = {id: 'model-a', config_model_type: 'minicpmv4_7'};
+ state.modelSettings = state.buildModelSettingsState(state.selectedModel, {
+ mm_processor_kwargs: {downsample_mode: '4x', max_slice_nums: 36},
+ });
+ state._modelSettingsBaseline = JSON.stringify(state.modelSettings);
+
+ await state.saveModelSettings();
+ assert.deepEqual(body, {mtp_fixed_depth: null});
+
+ state.modelSettings.mm_processor_kwargs.downsample_mode = '16x';
+ await state.saveModelSettings();
+ assert.deepEqual(body, {
+ mm_processor_kwargs: {downsample_mode: '16x', max_slice_nums: 36},
+ mtp_fixed_depth: null,
+ });
+
+ state.modelSettings.mm_processor_kwargs.downsample_mode = '';
+ state.modelSettings.mm_processor_kwargs.max_slice_nums = '';
+ await state.saveModelSettings();
+ assert.deepEqual(body, {mm_processor_kwargs: null, mtp_fixed_depth: null});
+});
+
test('Apply response cannot replace another model editor', async () => {
let resolve;
const state = setup(() => new Promise(r => {resolve=r;}));
diff --git a/apps/omlx-web/tests/test_admin_upload_tracking.py b/apps/omlx-web/tests/test_admin_upload_tracking.py
new file mode 100644
index 0000000000..980c89804e
--- /dev/null
+++ b/apps/omlx-web/tests/test_admin_upload_tracking.py
@@ -0,0 +1,250 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Upload queue discovery and polling regressions without real uploads."""
+
+import json
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parents[1]
+QUEUE_KEYS = (
+ "queue_loading",
+ "queue_error",
+ "queue_empty",
+ "queue_refresh",
+ "queue_activity",
+)
+
+
+def test_upload_tracking_lifecycle():
+ node = shutil.which("node")
+ if node is None:
+ pytest.skip("Node.js is required for dashboard behavior tests")
+ script = r"""
+const fs = require('node:fs');
+const vm = require('node:vm');
+const assert = require('node:assert/strict');
+const source = fs.readFileSync('omlx_web/static/js/dashboard.js', 'utf8');
+const timers = new Map();
+let nextTimer = 1;
+let requests = [];
+let respond = async () => ({ok: true, json: async () => ({tasks: []})});
+const windowEvents = {};
+const browserWindow = {
+ t: key => key,
+ location: {search: '?tab=models&modelsTab=uploader', hash: ''},
+ addEventListener: (name, callback) => {windowEvents[name] = callback;},
+};
+const state = vm.runInNewContext(source + '\n dashboard;', {
+ localStorage: {getItem: () => null},
+ THEME_STORAGE_KEY: 'theme', ENHANCED_READABILITY_KEY: 'readability',
+ window: browserWindow, navigator: {language: 'en'},
+ document: {addEventListener: () => {}}, URLSearchParams,
+ console: {error: () => {}},
+ fetch: async (url, options) => {
+ assert.equal(options, undefined, 'tracking must never mutate uploads');
+ requests.push(url);
+ return respond();
+ },
+ setTimeout: (fn, delay) => {
+ const id = nextTimer++;
+ timers.set(id, {fn, delay});
+ return id;
+ },
+ clearTimeout: id => timers.delete(id),
+})();
+for (const name of [
+ 'loadModels', 'loadHFModels', 'loadHFTasks', 'loadOQTasks',
+ 'startManagerStatusRefresh', 'stopManagerStatusRefresh',
+ 'stopStatsRefresh', 'stopLogRefresh', 'stopHFRefresh',
+ 'stopMSRefresh', 'stopOQRefresh', 'syncTabStateToUrl',
+]) state[name] = () => {};
+let modelLoads = 0;
+state.loadUploadOqModels = () => {modelLoads++;};
+const active = {task_id: 'upload-1', model_name: 'Example-oQ4', status: 'uploading'};
+const queued = {task_id: 'upload-2', model_name: 'Example-oQ6', status: 'pending'};
+const flush = () => new Promise(resolve => setImmediate(resolve));
+const timer = () => {
+ assert.equal(timers.size, 1, 'exactly one refresh timer');
+ return [...timers.values()][0];
+};
+async function tick() {
+ const [id, item] = [...timers.entries()][0];
+ timers.delete(id);
+ await item.fn();
+}
+(async () => {
+ state.mainTab = 'models';
+ state.modelsTab = 'uploader';
+ respond = async () => {
+ assert.equal(state.uploadTasksLoading, true, 'first load is explicit');
+ assert.equal(state.uploadTasksLoaded, false, 'do not show empty before success');
+ return {ok: true, json: async () => ({tasks: [active, queued]})};
+ };
+ await state.handleMainTabChange('models');
+ respond = async () => ({ok: true, json: async () => ({tasks: [active, queued]})});
+ assert.ok(requests.includes('/admin/api/upload/tasks'), 'deep link discovers jobs');
+ assert.equal(modelLoads, 1, 'deep link loads available models too');
+ assert.equal(state.uploadTasks.length, 2);
+ assert.equal(state.uploadTasksLoaded, true);
+ assert.equal(state.uploadTasksLoading, false);
+ assert.equal(state.uploadTokenValidated, false, 'tracking needs no HF validation');
+ assert.equal(timer().delay, 2000);
+
+ state.setModelsTab('uploader');
+ await flush();
+ assert.equal(timer().delay, 2000, 'repeat entry must not duplicate timers');
+ state.startStatsRefresh = () => {};
+ state.startLogRefresh = () => {};
+ state.$nextTick = () => {};
+ for (const tab of ['status', 'logs']) {
+ let finishNavigation;
+ state[tab === 'status' ? 'loadStats' : 'loadLogs'] =
+ () => new Promise(resolve => {finishNavigation = resolve;});
+ state.mainTab = tab;
+ const leaving = state.handleMainTabChange(tab);
+ await flush();
+ state.mainTab = 'models';
+ await state.handleMainTabChange('models');
+ assert.equal(timer().delay, 2000);
+ finishNavigation();
+ await leaving;
+ assert.equal(state._uploadRefreshEnabled, true, 'stale navigation cannot disable tracking');
+ assert.equal(timer().delay, 2000, 'returning before navigation completes keeps polling');
+ }
+ respond = async () => ({ok: true, json: async () => ({
+ tasks: [{...active, status: 'completed'}, {...queued, status: 'failed', error: 'failed'}],
+ })});
+ await tick();
+ assert.equal(state.uploadTasks[0].status, 'completed');
+ assert.equal(state.uploadTasks[1].status, 'failed');
+ assert.equal(timer().delay, 6000, 'terminal jobs switch to idle discovery');
+
+ respond = async () => ({ok: true, json: async () => ({tasks: [queued]})});
+ await tick();
+ assert.equal(timer().delay, 2000, 'idle discovery finds jobs from another client');
+ for (const badResponse of [
+ async () => ({ok: false, status: 503}),
+ async () => {throw new Error('offline');},
+ async () => ({ok: true, json: async () => ({})}),
+ async () => ({ok: true, json: async () => ({tasks: [null]})}),
+ async () => ({ok: true, json: async () => {throw new Error('invalid JSON');}}),
+ ]) {
+ respond = badResponse;
+ await tick();
+ assert.ok(state.uploadTasksError, 'errors must be visible');
+ assert.equal(state.uploadTasks.length, 1, 'keep last-known queue');
+ assert.equal(state.uploadTasksLoading, false);
+ assert.equal(timer().delay, 6000, 'errors retry at the idle cadence');
+ }
+ respond = async () => ({ok: true, json: async () => ({tasks: []})});
+ await state.loadUploadTasks();
+ assert.equal(state.uploadTasksError, '');
+ assert.equal(state.uploadTasksLoaded, true);
+ assert.equal(state.uploadTasks.length, 0);
+ assert.equal(timer().delay, 6000);
+
+ state.setModelsTab('manager');
+ assert.equal(timers.size, 0, 'leaving Uploader stops polling');
+ state.setModelsTab('uploader');
+ await flush();
+ timer();
+ state.mainTab = 'settings';
+ await state.handleMainTabChange('settings');
+ assert.equal(timers.size, 0, 'leaving Models stops polling');
+
+ state.mainTab = 'models';
+ state.modelsTab = 'uploader';
+ let release;
+ respond = () => new Promise(resolve => {release = resolve;});
+ const entering = state.handleMainTabChange('models');
+ await flush();
+ assert.equal(state.uploadTasksLoading, true);
+ const before = requests.length;
+ await state.loadUploadTasks();
+ assert.equal(requests.length, before, 'do not overlap requests');
+ state.setModelsTab('manager');
+ release({ok: true, json: async () => ({tasks: [active]})});
+ await entering;
+ assert.equal(timers.size, 0, 'late response cannot rearm after navigation');
+ assert.equal(state.uploadTasksLoading, false);
+
+ state.modelsTab = 'uploader';
+ state.uploadTasksLoaded = false;
+ state.uploadTasks = [];
+ respond = async () => ({ok: false, status: 401});
+ await state.handleMainTabChange('models');
+ assert.ok(state.uploadTasksError, 'auth failure remains visible');
+ assert.equal(state.uploadTasksLoaded, false, 'initial failure is not an empty success');
+ assert.equal(timer().delay, 6000, 'failures retry at a bounded cadence');
+ state.stopUploadRefresh();
+ assert.equal(timers.size, 0);
+
+ for (const name of [
+ 'applyTheme', 'loadGlobalSettings', 'loadServerInfo',
+ 'loadProfileFields', 'loadPresets', 'checkForUpdate',
+ 'fetchClaudeDesktopStatus', 'startUpdateCheckTimer', 'settingsScrollToHash',
+ 'pollPrefillLending',
+ ]) state[name] = () => {};
+ state.$watch = () => {};
+ respond = async () => ({ok: true, json: async () => ({tasks: [active]})});
+ await state.init();
+ assert.equal(state.modelsTab, 'uploader');
+ timer();
+ browserWindow.location.search = '?tab=models&modelsTab=manager';
+ windowEvents.popstate();
+ assert.equal(timers.size, 0, 'browser history leaving Uploader stops polling');
+ const beforeBack = requests.length;
+ browserWindow.location.search = '?tab=models&modelsTab=uploader';
+ windowEvents.popstate();
+ await flush();
+ assert.equal(requests.length, beforeBack + 1, 'browser history discovers uploads');
+ timer();
+ state.stopUploadRefresh();
+ assert.ok(requests.every(url => url === '/admin/api/upload/tasks'));
+})().catch(error => {console.error(error); process.exitCode = 1;});
+"""
+ result = subprocess.run(
+ [node, "-e", script],
+ cwd=ROOT,
+ capture_output=True,
+ text=True,
+ timeout=30,
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
+
+
+def test_upload_queue_has_explicit_states_and_no_fake_percentage():
+ html = (ROOT / "omlx_web/templates/dashboard/_models.html").read_text()
+ queue = html.split("", 1)[1].split(
+ "", 1
+ )[0]
+ assert 'x-show="uploadTasks.length > 0" x-cloak>' not in queue.split(
+ "' in resp.text
+ assert "Imagine - oMLX Admin" in resp.text
+
def test_language_change_applies_to_next_render(self, web):
client, _ = web
_login(client)
diff --git a/omlx/admin/benchmark.py b/omlx/admin/benchmark.py
index f44ac0860f..f8ed0264cc 100644
--- a/omlx/admin/benchmark.py
+++ b/omlx/admin/benchmark.py
@@ -12,11 +12,12 @@
import re
import time
import uuid
+from contextlib import suppress
from dataclasses import dataclass, field, replace
from enum import StrEnum
from functools import lru_cache
from pathlib import Path
-from typing import Any, Optional
+from typing import Any
from pydantic import BaseModel, field_validator
@@ -127,7 +128,7 @@ class BenchmarkRequest(BaseModel):
# When set, the benchmark runs against a remote OpenAI-compatible
# endpoint instead of a local engine and model_id is the remote
# model name (not validated against the local catalog).
- external: Optional[ExternalEndpointConfig] = None
+ external: ExternalEndpointConfig | None = None
@field_validator("prompt_lengths")
@classmethod
@@ -191,7 +192,7 @@ class BenchmarkRun:
events: list[dict] = field(default_factory=list)
cond: asyncio.Condition = field(default_factory=asyncio.Condition)
terminal: bool = False
- task: Optional[asyncio.Task] = None
+ task: asyncio.Task | None = None
results: list[dict] = field(default_factory=list)
error_message: str = ""
# Acceleration features active when the benchmark started. Results are
@@ -201,9 +202,9 @@ class BenchmarkRun:
# Same snapshot in the upload payload's shape: [{key, label, detail?}].
feature_flags: list[dict] = field(default_factory=list)
# Performance-relevant subset of the model's settings at run start.
- model_settings_snapshot: Optional[dict] = None
+ model_settings_snapshot: dict | None = None
# Host telemetry sampler, running for the duration of the tests.
- sampler: Optional[Any] = None
+ sampler: Any | None = None
# Lifetime footprint high-water mark before the tests began, so the run's
# own peak can be told apart from a larger one set earlier in the process.
lifetime_footprint_at_start: int = 0
@@ -247,9 +248,9 @@ class _FeatureFlagSpec:
legacy: str
key: str
label: str
- detail_attr: Optional[str] = None
- detail_key_fmt: Optional[str] = None
- detail_label_fmt: Optional[str] = None
+ detail_attr: str | None = None
+ detail_key_fmt: str | None = None
+ detail_label_fmt: str | None = None
# `mtp_enabled` is surfaced as "Lightning MTP" everywhere in the UI, so the
@@ -279,7 +280,7 @@ class _FeatureFlagSpec:
)
-def _sample_window(run: "BenchmarkRun", window_start: float) -> Optional[dict]:
+def _sample_window(run: "BenchmarkRun", window_start: float) -> dict | None:
"""Aggregate host telemetry for the interval a single test occupied."""
if run.sampler is None:
return None
@@ -305,7 +306,7 @@ def _detect_experimental_features(model_settings: Any) -> list[str]:
]
-def _format_bits(value: Any) -> Optional[str]:
+def _format_bits(value: Any) -> str | None:
"""Render a bit-width for display, dropping a trailing .0 (4.0 -> "4")."""
try:
number = float(value)
@@ -595,12 +596,12 @@ def _with_benchmark_context(
}
-def get_run(bench_id: str) -> Optional[BenchmarkRun]:
+def get_run(bench_id: str) -> BenchmarkRun | None:
"""Get a benchmark run by ID."""
return _benchmark_runs.get(bench_id)
-def get_active_run() -> Optional[BenchmarkRun]:
+def get_active_run() -> BenchmarkRun | None:
"""Return the currently-running throughput benchmark, if any.
Discovery surface for clients that need to attach to an in-progress
@@ -947,10 +948,8 @@ async def _run_single_test(
)
# Reset peak memory tracking
- try:
+ with suppress(Exception):
mx.reset_peak_memory()
- except Exception:
- pass
start_time = time.perf_counter()
first_token_time = None
@@ -1560,7 +1559,7 @@ def __init__(
@classmethod
def for_engine(
cls, engine: Any, context_profile: BenchmarkContextProfile | str
- ) -> Optional["_ChatBenchmark"]:
+ ) -> "_ChatBenchmark | None":
if callable(getattr(engine, "benchmark_endpoint", None)):
return cls(engine, context_profile)
return None
@@ -1681,7 +1680,7 @@ def _upload_model_name(model_id: str) -> str:
def _upload_model_repo(
model_id: str, entry: Any = None, model_dirs: Any = None
-) -> Optional[str]:
+) -> str | None:
"""Org-qualified repo id to publish alongside the model name (#1808).
Uses the same derivation as the models UI display name: the HF repo id
@@ -2409,7 +2408,6 @@ async def run_benchmark(run: BenchmarkRun, engine_pool: Any) -> None:
await _send_event(run, {"type": "result", "data": result})
-
# Phase 4: Batch tests
# Each request has a unique UUID prefix (no cache hits)
max_batch = max(request.batch_sizes) if request.batch_sizes else 0
@@ -2596,10 +2594,8 @@ async def run_benchmark(run: BenchmarkRun, engine_pool: Any) -> None:
},
)
# Try to unload the model on cancellation
- try:
+ with suppress(Exception):
await engine_pool._unload_engine(request.model_id)
- except Exception:
- pass
except Exception as e:
logger.error(f"Benchmark error: {e}", exc_info=True)
@@ -2613,10 +2609,8 @@ async def run_benchmark(run: BenchmarkRun, engine_pool: Any) -> None:
},
)
# Try to unload the model on error
- try:
+ with suppress(Exception):
await engine_pool._unload_engine(request.model_id)
- except Exception:
- pass
finally:
if chat is not None:
diff --git a/omlx/admin/model_recommender.py b/omlx/admin/model_recommender.py
index d4d6e195c9..1e86eb74c6 100644
--- a/omlx/admin/model_recommender.py
+++ b/omlx/admin/model_recommender.py
@@ -261,7 +261,7 @@ def dense_equivalent_params(family: Family) -> float:
"""Dense size an MoE behaves like, in billions of parameters."""
total = family.total_params / 1e9
active = family.active_params / 1e9
- return total**0.6 * active**0.4
+ return math.pow(total, 0.6) * math.pow(active, 0.4)
def evaluate(
@@ -711,7 +711,10 @@ def _read_json(
follow_redirects=True,
)
hf_raise_for_status(response)
- return response.json()
+ data = response.json()
+ if not isinstance(data, dict):
+ raise ValueError(f"{repo_id}/{filename} must contain a JSON object")
+ return data
def _ngram_table_bytes(
diff --git a/omlx/admin/routes.py b/omlx/admin/routes.py
index faa9f33fb0..62f99d4c6e 100644
--- a/omlx/admin/routes.py
+++ b/omlx/admin/routes.py
@@ -27,7 +27,7 @@
from dataclasses import asdict, is_dataclass
from datetime import UTC, datetime
from pathlib import Path
-from typing import Any, Literal, Optional
+from typing import Any, Literal
import requests
from fastapi import APIRouter, Depends, HTTPException, Request, Response
@@ -43,6 +43,7 @@
from .. import gguf
from .._version import __version__ as _omlx_version
from ..api.markitdown import MARKITDOWN_MODEL_ID, markitdown_model_visible
+from ..api.media_options import MultimodalProcessorOptions
from ..api.openai_models import _coerce_tool_call_arguments
from ..api.utils import _try_parse_json
from ..engine.splash import (
@@ -78,19 +79,19 @@
)
from ..model_settings import (
MAX_LIGHTNING_MTP_DRAFT_TOKENS,
+ MOE_OFFLOAD_MTP_MODEL_TYPES,
ModelSettings,
ane_prefill_backend,
ane_prefill_fraction,
lora_adapter_conflict,
+ merge_chat_template_kwargs,
+ oq_a8_model_supported,
resolve_lora_conflicts,
resolve_qwen35_prefill_conflicts,
resolve_vlm_mtp_conflicts,
validate_ane_prefill,
- validate_moe_expert_offload,
- MOE_OFFLOAD_MTP_MODEL_TYPES,
- merge_chat_template_kwargs,
- oq_a8_model_supported,
validate_kv_compression_settings,
+ validate_moe_expert_offload,
)
from ..oqh.format import is_oqh_checkpoint
from ..patches.deepseek_v4.chat_template_v4 import REASONING_EFFORT_PROMPTS
@@ -441,6 +442,7 @@ class ModelSettingsRequest(BaseModel):
force_sampling: bool | None = None
max_tool_result_tokens: int | None = None
chat_template_kwargs: dict[str, Any] | None = None
+ mm_processor_kwargs: MultimodalProcessorOptions | None = None
forced_ct_kwargs: list[str] | None = None
ttl_seconds: int | None = None
index_cache_freq: int | None = None
@@ -1363,6 +1365,52 @@ def _mtp_compat_for_model(
return True, ""
+def _model_has_mtp_weight_tensors(model_dir) -> bool:
+ """Return True iff the model directory's weight files contain ``mtp.*`` keys.
+
+ Uses ``model.safetensors.index.json`` when present (cheap — only reads
+ the weight_map). Falls back to opening each ``*.safetensors`` and
+ checking its keys when no index is present (single-shard models).
+ Returns False on any error (we treat the model as incompatible rather
+ than risking a confusing load failure mid-inference).
+ """
+ import json
+ from pathlib import Path
+
+ try:
+ from safetensors import safe_open
+ except ImportError:
+ # Library should be installed via mlx-lm deps; if it's not we can't
+ # peek the weights. Stay conservative and assume incompatible.
+ return False
+
+ model_dir = Path(model_dir)
+
+ # Preferred path: read the index file's weight_map (no tensor data loaded).
+ index_path = model_dir / "model.safetensors.index.json"
+ if index_path.exists():
+ try:
+ index = json.loads(index_path.read_text())
+ weight_map = index.get("weight_map", {})
+ return any("mtp." in key for key in weight_map)
+ except Exception:
+ return False
+
+ # Single-shard fallback: enumerate keys via safe_open metadata. We
+ # short-circuit on the first ``mtp.*`` key.
+ from ..utils.safetensors_shards import select_safetensors_weight_files
+
+ for path in select_safetensors_weight_files(model_dir):
+ try:
+ with safe_open(str(path), framework="numpy") as f: # type: ignore[arg-type]
+ for key in f.keys(): # noqa: SIM118 - safe_open exposes keys()
+ if "mtp." in key:
+ return True
+ except Exception:
+ continue
+ return False
+
+
def _apply_log_level_runtime(level: str) -> None:
"""Apply log level change at runtime to all oMLX loggers and handlers."""
level_name = level.upper()
@@ -2684,6 +2732,7 @@ async def list_models(is_admin: bool = Depends(require_admin)):
"model_type": model_info.get("model_type", "llm"),
"config_model_type": model_info.get("config_model_type", ""),
"realtime_voice": bool(model_info.get("realtime_voice")),
+ "unavailable_reason": model_info.get("unavailable_reason"),
# Native context window from the model's config.json — used by
# the context bench UI to hide targets the model cannot reach.
"model_context_length": model_info.get("model_context_length"),
@@ -2696,6 +2745,9 @@ async def list_models(is_admin: bool = Depends(require_admin)):
"source_path": model_info.get("source_path"),
"distributed": model_info.get("distributed", False),
"cluster": model_info.get("cluster"),
+ "capabilities": model_info.get("capabilities", []),
+ "tasks": model_info.get("tasks", []),
+ "image_metadata": model_info.get("image_metadata"),
"last_access": model_info.get("last_access"),
"external_engines": external_engines,
"dflash_compatible": compat_ok,
@@ -3146,6 +3198,7 @@ async def update_model_settings(
"audio_tts",
"audio_sts",
"decision",
+ "image",
}
# Treat empty string as None (auto-detect)
override_value = request.model_type_override or None
@@ -3170,6 +3223,7 @@ async def update_model_settings(
"audio_tts": "audio_tts",
"audio_sts": "audio_sts",
"decision": "decision",
+ "image": "image",
}
if override_value:
entry.model_type = override_value
@@ -3178,11 +3232,20 @@ async def update_model_settings(
# Reset to auto-detected type
from pathlib import Path
- from ..model_discovery import detect_model_type
+ from ..model_discovery import (
+ VLM_NATIVE_TEXT_MODEL_TYPES,
+ detect_model_type,
+ )
detected_type = detect_model_type(Path(entry.model_path))
entry.model_type = detected_type
entry.engine_type = type_to_engine.get(detected_type, "batched")
+ if (
+ detected_type == "llm"
+ and (entry.config_model_type or "").lower().replace("-", "_")
+ in VLM_NATIVE_TEXT_MODEL_TYPES
+ ):
+ entry.engine_type = "vlm"
if "max_context_window" in sent:
current_settings.max_context_window = request.max_context_window
if "max_tokens" in sent:
@@ -3282,6 +3345,13 @@ async def update_model_settings(
current_settings.cache_reasoning_output = request.cache_reasoning_output
if "chat_template_kwargs" in sent:
current_settings.chat_template_kwargs = request.chat_template_kwargs
+ if "mm_processor_kwargs" in sent:
+ if request.mm_processor_kwargs is not None:
+ current_settings.mm_processor_kwargs = (
+ request.mm_processor_kwargs.model_dump(exclude_none=True)
+ )
+ else:
+ current_settings.mm_processor_kwargs = None
if "forced_ct_kwargs" in sent:
current_settings.forced_ct_kwargs = request.forced_ct_kwargs
if "ttl_seconds" in sent:
@@ -3893,7 +3963,10 @@ def _raise_if_alias_conflicts_exposed_profiles(
def _validate_model_settings(entry, settings):
- from ..model_settings import validate_moe_expert_offload
+ from ..model_settings import (
+ validate_minicpm_speculation,
+ validate_moe_expert_offload,
+ )
if settings.get("lora_adapter"):
if getattr(entry, "engine_type", None) not in ("batched", "vlm"):
@@ -3908,6 +3981,15 @@ def _validate_model_settings(entry, settings):
detail=f"A LoRA adapter cannot be combined with {conflict}.",
)
try:
+ validate_minicpm_speculation(
+ settings, getattr(entry, "config_model_type", None)
+ )
+ if settings.get("mm_processor_kwargs") is not None:
+ if getattr(entry, "config_model_type", None) != "minicpmv4_7":
+ raise ValueError(
+ "mm_processor_kwargs is only supported by MiniCPM-V 4.7."
+ )
+ MultimodalProcessorOptions.model_validate(settings["mm_processor_kwargs"])
validate_moe_expert_offload(
settings, model_type=getattr(entry, "config_model_type", None)
)
@@ -4346,6 +4428,8 @@ async def _apply_settings_snapshot(
mgr = _require_settings_manager()
skipped: list[dict] = []
if reset:
+ if _get_engine_pool is None:
+ raise HTTPException(status_code=503, detail="Engine pool not initialized")
cleaned = _get_engine_pool().recommended_sampling_settings(entry)
scope = set(ALL_FIELDS) & set(ModelSettingsRequest.model_fields)
else:
@@ -6654,7 +6738,6 @@ def _get_engine_info() -> dict:
"mlx": "https://github.com/ml-explore/mlx",
"mlx-lm": "https://github.com/ml-explore/mlx-lm",
"mlx-vlm": "https://github.com/Neywa-Labs/mlx-vlm",
- "mlx-embeddings": "https://github.com/Blaizzy/mlx-embeddings",
"mlx-audio": "https://github.com/Neywa-Labs/mlx-audio",
}
@@ -8400,10 +8483,10 @@ async def search_hf_models(
mlx_only: bool = True,
model_format: str | None = None,
# Filtering
- min_params: Optional[int] = None,
- max_params: Optional[int] = None,
- min_size: Optional[int] = None, # bytes
- max_size: Optional[int] = None, # bytes
+ min_params: int | None = None,
+ max_params: int | None = None,
+ min_size: int | None = None, # bytes
+ max_size: int | None = None, # bytes
# Sorting
sort_by_size: bool = False,
sort_ascending: bool = False,
@@ -8522,6 +8605,8 @@ async def list_hf_models(is_admin: bool = Depends(require_admin)):
model_dirs = global_settings.get_effective_model_dirs()
+ from ..model_discovery import _is_model_dir
+
def _add_model(
model_path: Path,
model_name: str,
@@ -8574,7 +8659,7 @@ def _add_adapter(model_path: Path, model_name: str, **kwargs) -> None:
gguf_folders.append((subdir, subdir.name, "local"))
elif is_adapter_dir(subdir):
_add_adapter(subdir, subdir.name)
- elif (subdir / "config.json").exists():
+ elif _is_model_dir(subdir):
# Level 1: direct model folder
_add_model(subdir, subdir.name)
else:
@@ -8612,7 +8697,7 @@ def _add_adapter(model_path: Path, model_name: str, **kwargs) -> None:
_add_adapter(
child, child.name, repo_id=f"{subdir.name}/{child.name}"
)
- elif (child / "config.json").exists():
+ elif _is_model_dir(child):
_add_model(
child, child.name, repo_id=f"{subdir.name}/{child.name}"
)
@@ -8672,11 +8757,9 @@ def _add_adapter(model_path: Path, model_name: str, **kwargs) -> None:
def _is_listed_model_folder(path: Path) -> bool:
"""A folder /api/hf/models lists whole: a checkpoint, GGUF or LoRA adapter."""
- return (
- (path / "config.json").exists()
- or gguf.is_gguf_folder(path)
- or is_adapter_dir(path)
- )
+ from ..model_discovery import _is_model_dir
+
+ return _is_model_dir(path) or gguf.is_gguf_folder(path) or is_adapter_dir(path)
@router.delete("/api/hf/models/{model_name}")
@@ -8692,7 +8775,6 @@ async def delete_hf_model(
raise HTTPException(status_code=503, detail="Server not initialized")
model_dirs = global_settings.get_effective_model_dirs()
-
entry = engine_pool.get_entry(model_name) if engine_pool is not None else None
if entry is not None and entry.model_format == "gguf":
await _delete_gguf_model(entry, model_dirs, engine_pool)
diff --git a/omlx/cache/paged_cache.py b/omlx/cache/paged_cache.py
index dbe225df24..e145dfa2c9 100644
--- a/omlx/cache/paged_cache.py
+++ b/omlx/cache/paged_cache.py
@@ -31,10 +31,10 @@
from collections import OrderedDict
from collections.abc import Callable, Iterable
from dataclasses import dataclass, field
-from typing import Any, Dict, List, NewType, Optional, Tuple
+from typing import Any, NewType
from .interface import CacheManager
-from .stats import BaseCacheStats, PagedCacheStats
+from .stats import PagedCacheStats
logger = logging.getLogger(__name__)
@@ -44,10 +44,10 @@
def resolve_block_extra_keys(
block_end: int,
- extra_keys: Optional[Tuple[Any, ...]] = None,
- extra_key_token_start: Optional[int] = None,
- extra_key_ranges: Optional[List[Tuple[int, Tuple[Any, ...]]]] = None,
-) -> Optional[Tuple[Any, ...]]:
+ extra_keys: tuple[Any, ...] | None = None,
+ extra_key_token_start: int | None = None,
+ extra_key_ranges: list[tuple[int, tuple[Any, ...]]] | None = None,
+) -> tuple[Any, ...] | None:
"""Resolve which cache key salt applies to a block ending at ``block_end``.
``extra_key_ranges`` takes precedence over ``extra_keys`` and is intended
@@ -82,10 +82,10 @@ def resolve_block_extra_keys(
def compute_block_hash(
- parent_hash: Optional[BlockHash],
- token_ids: List[int],
- extra_keys: Optional[Tuple[Any, ...]] = None,
- model_name: Optional[str] = None,
+ parent_hash: BlockHash | None,
+ token_ids: list[int],
+ extra_keys: tuple[Any, ...] | None = None,
+ model_name: str | None = None,
) -> BlockHash:
"""
Compute hash for a block based on its content and parent block.
@@ -154,11 +154,11 @@ class CacheBlock:
block_id: int
ref_count: int = 0
- block_hash: Optional[BlockHash] = None
+ block_hash: BlockHash | None = None
# Doubly linked list pointers for FreeKVCacheBlockQueue
- prev_free_block: Optional["CacheBlock"] = None
- next_free_block: Optional["CacheBlock"] = None
+ prev_free_block: CacheBlock | None = None
+ next_free_block: CacheBlock | None = None
# Special flags
is_null: bool = False
@@ -213,7 +213,7 @@ class FreeKVCacheBlockQueue:
Uses fake head/tail sentinels to simplify edge cases.
"""
- def __init__(self, blocks: List[CacheBlock]) -> None:
+ def __init__(self, blocks: list[CacheBlock]) -> None:
"""
Initialize queue with all blocks as free.
@@ -266,7 +266,7 @@ def popleft(self) -> CacheBlock:
return block
- def popleft_n(self, n: int) -> List[CacheBlock]:
+ def popleft_n(self, n: int) -> list[CacheBlock]:
"""
Pop n blocks from the front.
@@ -344,7 +344,7 @@ def append(self, block: CacheBlock) -> None:
self.num_free_blocks += 1
- def append_n(self, blocks: List[CacheBlock]) -> None:
+ def append_n(self, blocks: list[CacheBlock]) -> None:
"""
Append multiple blocks to the end.
@@ -367,7 +367,7 @@ def append_n(self, blocks: List[CacheBlock]) -> None:
self.num_free_blocks += len(blocks)
- def get_all_free_blocks(self) -> List[CacheBlock]:
+ def get_all_free_blocks(self) -> list[CacheBlock]:
"""Get all free blocks (for testing)."""
result = []
curr = self.fake_head.next_free_block
@@ -390,9 +390,9 @@ class BlockHashToBlockMap:
"""
def __init__(self) -> None:
- self._cache: Dict[BlockHash, CacheBlock | Dict[int, CacheBlock]] = {}
+ self._cache: dict[BlockHash, CacheBlock | dict[int, CacheBlock]] = {}
- def get_block(self, block_hash: BlockHash) -> Optional[CacheBlock]:
+ def get_block(self, block_hash: BlockHash) -> CacheBlock | None:
"""Get any block with the given hash."""
blocks = self._cache.get(block_hash)
if blocks is None:
@@ -416,7 +416,7 @@ def insert(self, block_hash: BlockHash, block: CacheBlock) -> None:
elif isinstance(existing, dict):
existing[block.block_id] = block
- def pop(self, block_hash: BlockHash, block_id: int) -> Optional[CacheBlock]:
+ def pop(self, block_hash: BlockHash, block_id: int) -> CacheBlock | None:
"""Remove and return a specific block from the cache."""
blocks = self._cache.pop(block_hash, None)
if blocks is None:
@@ -463,7 +463,7 @@ class BlockTable:
"""
request_id: str
- block_ids: List[int] = field(default_factory=list)
+ block_ids: list[int] = field(default_factory=list)
num_tokens: int = 0
def add_block(self, block_id: int, num_tokens: int) -> None:
@@ -474,7 +474,7 @@ def add_block(self, block_id: int, num_tokens: int) -> None:
def __len__(self) -> int:
return len(self.block_ids)
- def copy(self, new_request_id: str) -> "BlockTable":
+ def copy(self, new_request_id: str) -> BlockTable:
"""Create a copy with new request ID."""
return BlockTable(
request_id=new_request_id,
@@ -533,7 +533,7 @@ def __init__(
self._current_allocated_count = initial_count
# Create only initial blocks (memory optimization)
- self.blocks: List[CacheBlock] = [
+ self.blocks: list[CacheBlock] = [
CacheBlock(block_id=i) for i in range(initial_count)
]
@@ -544,10 +544,10 @@ def __init__(
self.cached_block_hash_to_block = BlockHashToBlockMap()
# Request to block table mapping
- self.request_tables: Dict[str, BlockTable] = {}
+ self.request_tables: dict[str, BlockTable] = {}
# Allocated blocks (for fast lookup)
- self.allocated_blocks: Dict[int, CacheBlock] = {}
+ self.allocated_blocks: dict[int, CacheBlock] = {}
# Reserve null block (block 0) - never freed
self.null_block = self.free_block_queue.popleft()
@@ -566,7 +566,7 @@ def __init__(
self._lock = threading.RLock()
# paged SSD cache manager for storage (set via set_paged_ssd_cache_manager)
- self._paged_ssd_cache_manager: Optional[Any] = None
+ self._paged_ssd_cache_manager: Any | None = None
# Lifecycle hooks for hash-keyed side indexes (e.g. the prefix index
# in BlockAwarePrefixCache). on_block_hash_dropped fires when a
@@ -578,7 +578,7 @@ def __init__(
# Tail blocks by chain parent (None for a root). A tail is shorter
# than a block, so the grid walk cannot derive its hash.
- self._tail_index: Dict[Optional[BlockHash], "OrderedDict[BlockHash, int]"] = {}
+ self._tail_index: dict[BlockHash | None, OrderedDict[BlockHash, int]] = {}
# Tails shared across conversations, capped apart from ordinary tails.
self._shared_tails: set[BlockHash] = set()
@@ -648,7 +648,7 @@ def _grow_blocks(self, additional_blocks: int) -> int:
# Block Allocation (vLLM style)
# =========================================================================
- def allocate_block(self) -> Optional[CacheBlock]:
+ def allocate_block(self) -> CacheBlock | None:
"""
Allocate a new cache block.
@@ -678,7 +678,7 @@ def allocate_block(self) -> Optional[CacheBlock]:
return block
- def get_new_blocks(self, num_blocks: int) -> List[CacheBlock]:
+ def get_new_blocks(self, num_blocks: int) -> list[CacheBlock]:
"""
Allocate multiple blocks at once (vLLM style).
@@ -881,7 +881,7 @@ def decrement_ref(self, block_id: int) -> bool:
"""Decrement reference count (alias for free_block)."""
return self.free_block(block_id)
- def release_for_eviction(self, block_ids: List[int]) -> int:
+ def release_for_eviction(self, block_ids: list[int]) -> int:
"""
Release blocks for eviction without removing from allocated_blocks.
@@ -914,7 +914,7 @@ def release_for_eviction(self, block_ids: List[int]) -> int:
# Prefix Caching (vLLM chain-hash style)
# =========================================================================
- def get_cached_block(self, block_hash: BlockHash) -> Optional[CacheBlock]:
+ def get_cached_block(self, block_hash: BlockHash) -> CacheBlock | None:
"""
Get a cached block by its hash (vLLM style).
@@ -937,11 +937,11 @@ def get_cached_block(self, block_hash: BlockHash) -> Optional[CacheBlock]:
def cache_full_blocks(
self,
- blocks: List[CacheBlock],
- token_ids: List[int],
+ blocks: list[CacheBlock],
+ token_ids: list[int],
num_cached_blocks: int,
num_full_blocks: int,
- extra_keys: Optional[Tuple[Any, ...]] = None,
+ extra_keys: tuple[Any, ...] | None = None,
) -> None:
"""
Cache full blocks for prefix caching (vLLM style).
@@ -993,11 +993,11 @@ def cache_full_blocks(
def get_computed_blocks(
self,
- token_ids: List[int],
- extra_keys: Optional[Tuple[Any, ...]] = None,
- extra_key_token_start: Optional[int] = None,
- extra_key_ranges: Optional[List[Tuple[int, Tuple[Any, ...]]]] = None,
- ) -> Tuple[List[CacheBlock], int]:
+ token_ids: list[int],
+ extra_keys: tuple[Any, ...] | None = None,
+ extra_key_token_start: int | None = None,
+ extra_key_ranges: list[tuple[int, tuple[Any, ...]]] | None = None,
+ ) -> tuple[list[CacheBlock], int]:
"""
Find cached blocks for a token prefix (vLLM style).
@@ -1088,10 +1088,10 @@ def get_computed_blocks(
def find_cached_block(
self,
- tokens: List[int],
- parent_hash: Optional[BlockHash] = None,
- extra_keys: Optional[Tuple[Any, ...]] = None,
- ) -> Optional[CacheBlock]:
+ tokens: list[int],
+ parent_hash: BlockHash | None = None,
+ extra_keys: tuple[Any, ...] | None = None,
+ ) -> CacheBlock | None:
"""
Find a cached block matching the given tokens using chain hash.
@@ -1123,9 +1123,9 @@ def find_cached_block(
def register_block_hash(
self,
block: CacheBlock,
- tokens: List[int],
- parent_hash: Optional[BlockHash] = None,
- extra_keys: Optional[Tuple[Any, ...]] = None,
+ tokens: list[int],
+ parent_hash: BlockHash | None = None,
+ extra_keys: tuple[Any, ...] | None = None,
) -> None:
"""
Register a block's hash for deduplication using chain hash.
@@ -1149,7 +1149,7 @@ def register_block_hash(
def register_tail_block(
self,
- parent_hash: Optional[BlockHash],
+ parent_hash: BlockHash | None,
tail_hash: BlockHash,
token_count: int,
shared: bool = False,
@@ -1188,7 +1188,7 @@ def is_shared_tail(self, block_hash: Any) -> bool:
return block_hash in self._shared_tails
def seed_tail_blocks(
- self, entries: Iterable[Tuple[Optional[BlockHash], BlockHash, int]]
+ self, entries: Iterable[tuple[BlockHash | None, BlockHash, int]]
) -> int:
"""Rebuild the tail index from persisted block metadata."""
seeded = 0
@@ -1199,13 +1199,13 @@ def seed_tail_blocks(
def _match_tail_block(
self,
- token_ids: List[int],
- parent_hash: Optional[BlockHash],
+ token_ids: list[int],
+ parent_hash: BlockHash | None,
start: int,
- extra_keys: Optional[Tuple[Any, ...]] = None,
- extra_key_token_start: Optional[int] = None,
- extra_key_ranges: Optional[List[Tuple[int, Tuple[Any, ...]]]] = None,
- ) -> Optional[CacheBlock]:
+ extra_keys: tuple[Any, ...] | None = None,
+ extra_key_token_start: int | None = None,
+ extra_key_ranges: list[tuple[int, tuple[Any, ...]]] | None = None,
+ ) -> CacheBlock | None:
"""Find the longest tail block that prefixes ``token_ids[start:]``.
Stale entries are dropped on the way. Called with ``self._lock`` held.
@@ -1262,7 +1262,7 @@ def create_block_table(self, request_id: str) -> BlockTable:
self.request_tables[request_id] = table
return table
- def get_block_table(self, request_id: str) -> Optional[BlockTable]:
+ def get_block_table(self, request_id: str) -> BlockTable | None:
"""Get block table for a request."""
with self._lock:
return self.request_tables.get(request_id)
@@ -1274,7 +1274,7 @@ def get_or_create_block_table(self, request_id: str) -> BlockTable:
self.request_tables[request_id] = BlockTable(request_id=request_id)
return self.request_tables[request_id]
- def detach_block_table(self, request_id: str) -> Optional[BlockTable]:
+ def detach_block_table(self, request_id: str) -> BlockTable | None:
"""Remove a request's block table without freeing its blocks."""
with self._lock:
return self.request_tables.pop(request_id, None)
@@ -1306,11 +1306,11 @@ def add_block_to_table(
def find_shared_prefix(
self,
- tokens: List[int],
- extra_keys: Optional[Tuple[Any, ...]] = None,
- extra_key_token_start: Optional[int] = None,
- extra_key_ranges: Optional[List[Tuple[int, Tuple[Any, ...]]]] = None,
- ) -> Tuple[List[int], List[Optional[BlockHash]], List[int]]:
+ tokens: list[int],
+ extra_keys: tuple[Any, ...] | None = None,
+ extra_key_token_start: int | None = None,
+ extra_key_ranges: list[tuple[int, tuple[Any, ...]]] | None = None,
+ ) -> tuple[list[int], list[BlockHash | None], list[int]]:
"""
Find shared prefix blocks for a token sequence.
@@ -1362,7 +1362,7 @@ def fork_block_table(
def get_blocks_for_generation(
self,
table: BlockTable,
- ) -> Tuple[List[CacheBlock], bool]:
+ ) -> tuple[list[CacheBlock], bool]:
"""
Get blocks for generation, applying COW if needed.
"""
@@ -1391,7 +1391,7 @@ def get_blocks_for_generation(
return blocks, was_copied
- def _cow_copy_block(self, source_block: CacheBlock) -> Optional[CacheBlock]:
+ def _cow_copy_block(self, source_block: CacheBlock) -> CacheBlock | None:
"""
Create a copy of a block for COW.
@@ -1420,7 +1420,7 @@ def _cow_copy_block(self, source_block: CacheBlock) -> Optional[CacheBlock]:
# Legacy allocation methods (for backwards compatibility)
# =========================================================================
- def allocate_blocks_for_tokens(self, num_tokens: int) -> List[CacheBlock]:
+ def allocate_blocks_for_tokens(self, num_tokens: int) -> list[CacheBlock]:
"""Allocate enough blocks to hold num_tokens."""
num_blocks_needed = (num_tokens + self.block_size - 1) // self.block_size
return self.get_new_blocks(num_blocks_needed)
@@ -1455,7 +1455,7 @@ def get_stats(self) -> PagedCacheStats:
self.stats.free_blocks = self.free_block_queue.num_free_blocks
return self.stats
- def get_memory_usage(self) -> Dict[str, Any]:
+ def get_memory_usage(self) -> dict[str, Any]:
"""Get memory usage information."""
with self._lock:
stats = self.get_stats()
@@ -1532,7 +1532,7 @@ def clear(self) -> int:
# SSD Cache Support
# =========================================================================
- def get_evictable_blocks(self, count: int) -> List[CacheBlock]:
+ def get_evictable_blocks(self, count: int) -> list[CacheBlock]:
"""
Get LRU blocks that can be evicted (metadata cleared).
@@ -1681,7 +1681,7 @@ def evict_block_permanently(self, block_id: int) -> bool:
def restore_block(
self,
block_id: int,
- cache_data: List[Tuple[Any, Any]],
+ cache_data: list[tuple[Any, Any]],
) -> bool:
"""
Restore block data from cold storage.
@@ -1710,7 +1710,7 @@ def restore_block(
)
return True
- def get_cold_blocks(self) -> List[CacheBlock]:
+ def get_cold_blocks(self) -> list[CacheBlock]:
"""
Get all blocks that have data on paged SSD.
@@ -1729,7 +1729,7 @@ def cold_block_count(self) -> int:
with self._lock:
return sum(1 for b in self.blocks if b.block_hash is not None and not b.is_null)
- def get_ref_count_distribution(self) -> Dict[int, int]:
+ def get_ref_count_distribution(self) -> dict[int, int]:
"""
Get distribution of blocks by ref_count.
@@ -1738,7 +1738,7 @@ def get_ref_count_distribution(self) -> Dict[int, int]:
Only includes ref_counts that have at least one block.
"""
with self._lock:
- distribution: Dict[int, int] = {}
+ distribution: dict[int, int] = {}
for block in self.allocated_blocks.values():
rc = block.ref_count
distribution[rc] = distribution.get(rc, 0) + 1
@@ -1776,7 +1776,7 @@ def get_ref_count_summary(self) -> str:
# CacheManager ABC Interface Implementation
# =========================================================================
- def fetch(self, key: Any) -> Tuple[Optional[Any], bool]:
+ def fetch(self, key: Any) -> tuple[Any | None, bool]:
"""
Fetch a cached block by its hash.
diff --git a/omlx/engine/__init__.py b/omlx/engine/__init__.py
index 39fc87bf99..84ab07703a 100644
--- a/omlx/engine/__init__.py
+++ b/omlx/engine/__init__.py
@@ -5,7 +5,7 @@
Provides multiple engine implementations:
- BatchedEngine: Continuous batching for multiple concurrent users
- VLMBatchedEngine: Vision-language model engine with image support
-- EmbeddingEngine: Batch embedding generation using mlx-embeddings
+- EmbeddingEngine: Batch embedding generation using mlx-vlm
- RerankerEngine: Document reranking using SequenceClassification models
- DecisionEngine: Typed decisions for /v1/systemone (Clef, OpenJev, Decision 3.0, d1)
diff --git a/omlx/engine/base.py b/omlx/engine/base.py
index d5cd95d229..518aa4f1c0 100644
--- a/omlx/engine/base.py
+++ b/omlx/engine/base.py
@@ -11,8 +11,9 @@
import uuid
from abc import ABC, abstractmethod
from collections import OrderedDict
+from collections.abc import AsyncIterator
from dataclasses import dataclass, field
-from typing import Any, AsyncIterator, Dict, List, Optional
+from typing import Any
import mlx.core as mx
@@ -204,17 +205,17 @@ class GenerationOutput:
"""
text: str
- tokens: List[int] = field(default_factory=list)
+ tokens: list[int] = field(default_factory=list)
prompt_tokens: int = 0
completion_tokens: int = 0
- finish_reason: Optional[str] = "stop"
+ finish_reason: str | None = "stop"
# For streaming
new_text: str = ""
finished: bool = True
# For tool calling (Harmony and other models)
- tool_calls: Optional[List[Dict[str, Any]]] = None
+ tool_calls: list[dict[str, Any]] | None = None
# Per-token logprobs: the new tokens when streaming, all tokens otherwise.
- logprobs: Optional[List[TokenLogprob]] = None
+ logprobs: list[TokenLogprob] | None = None
# Prefix cache stats
cached_tokens: int = 0
# Optional engine-native throughput stats. Diffusion models report
@@ -226,12 +227,12 @@ class GenerationOutput:
diffusion_work_tokens: int = 0
diffusion_canvas_tps: float = 0.0
diffusion_work_tps: float = 0.0
- generated_at: Optional[float] = None
- generated_until: Optional[float] = None
- first_token_at: Optional[float] = None
+ generated_at: float | None = None
+ generated_until: float | None = None
+ first_token_at: float | None = None
# Internal scheduler trace populated only by local benchmark requests.
- benchmark_prefill_chunks: List[int] = field(default_factory=list)
- benchmark_requested_steps: List[int] = field(default_factory=list)
+ benchmark_prefill_chunks: list[int] = field(default_factory=list)
+ benchmark_requested_steps: list[int] = field(default_factory=list)
benchmark_boundary_enabled: bool = False
benchmark_cache_block_size: int = 0
@@ -263,9 +264,9 @@ def supports_logprobs(self) -> bool:
def _generation_prompt_text(
self,
- chat_template_kwargs: Optional[Dict[str, Any]],
- is_partial: Optional[bool],
- ) -> tuple[Optional[str], bool]:
+ chat_template_kwargs: dict[str, Any] | None,
+ is_partial: bool | None,
+ ) -> tuple[str | None, bool]:
"""Return ``(suffix, persists)`` for the template's generation prompt.
``persists`` is True when an assistant turn followed by a user turn still
@@ -278,7 +279,7 @@ def _generation_prompt_text(
cache = self.__dict__.setdefault("_generation_prompt_cache", {})
if key in cache:
return cache[key]
- suffix: Optional[str] = None
+ suffix: str | None = None
persists = False
try:
probe = [{"role": "user", "content": "probe"}]
@@ -325,10 +326,10 @@ def _generation_prompt_text(
def _system_prefix_ids(
self,
- messages: List[Dict[str, Any]],
- tools: Optional[List[Dict[str, Any]]],
- chat_template_kwargs: Optional[Dict[str, Any]],
- ) -> Optional[List[int]]:
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]] | None,
+ chat_template_kwargs: dict[str, Any] | None,
+ ) -> list[int] | None:
"""Return token ids of the leading system block as rendered before any user.
Requests that differ only after it share these tokens. Returns None the
@@ -360,7 +361,7 @@ def _system_prefix_ids(
cache.move_to_end(key)
if cache[key] is not False:
return cache[key]
- ids: Optional[List[int]] = None
+ ids: list[int] | None = None
try:
# Two probe users: the rendered texts agree up to the user content.
a, b = (
@@ -418,7 +419,7 @@ async def generate(
min_p: float = 0.0,
repetition_penalty: float = 1.0,
presence_penalty: float = 0.0,
- stop: Optional[List[str]] = None,
+ stop: list[str] | None = None,
**kwargs,
) -> GenerationOutput:
"""
@@ -450,7 +451,7 @@ async def stream_generate(
min_p: float = 0.0,
repetition_penalty: float = 1.0,
presence_penalty: float = 0.0,
- stop: Optional[List[str]] = None,
+ stop: list[str] | None = None,
**kwargs,
) -> AsyncIterator[GenerationOutput]:
"""
@@ -474,7 +475,7 @@ async def stream_generate(
@abstractmethod
async def chat(
self,
- messages: List[Dict[str, Any]],
+ messages: list[dict[str, Any]],
max_tokens: int = 256,
temperature: float = 0.7,
top_p: float = 0.9,
@@ -482,7 +483,7 @@ async def chat(
min_p: float = 0.0,
repetition_penalty: float = 1.0,
presence_penalty: float = 0.0,
- tools: Optional[List[dict]] = None,
+ tools: list[dict] | None = None,
**kwargs,
) -> GenerationOutput:
"""
@@ -506,7 +507,7 @@ async def chat(
@abstractmethod
async def stream_chat(
self,
- messages: List[Dict[str, Any]],
+ messages: list[dict[str, Any]],
max_tokens: int = 256,
temperature: float = 0.7,
top_p: float = 0.9,
@@ -514,7 +515,7 @@ async def stream_chat(
min_p: float = 0.0,
repetition_penalty: float = 1.0,
presence_penalty: float = 0.0,
- tools: Optional[List[dict]] = None,
+ tools: list[dict] | None = None,
**kwargs,
) -> AsyncIterator[GenerationOutput]:
"""
@@ -537,7 +538,7 @@ async def stream_chat(
@property
@abstractmethod
- def model_type(self) -> Optional[str]:
+ def model_type(self) -> str | None:
"""Get the model type from config.json (e.g., 'gpt_oss', 'llama', 'qwen2').
This can be used to apply model-specific processing.
@@ -580,7 +581,7 @@ def active_request_count(self) -> int:
return 1 if self.has_active_requests() else 0
@abstractmethod
- def get_stats(self) -> Dict[str, Any]:
+ def get_stats(self) -> dict[str, Any]:
"""Get engine statistics.
Returns:
@@ -589,7 +590,7 @@ def get_stats(self) -> Dict[str, Any]:
pass
@abstractmethod
- def get_cache_stats(self) -> Optional[Dict[str, Any]]:
+ def get_cache_stats(self) -> dict[str, Any] | None:
"""Get cache statistics.
Returns:
@@ -600,8 +601,8 @@ def get_cache_stats(self) -> Optional[Dict[str, Any]]:
async def preflight_chat(
self,
messages: list,
- tools: Optional[list] = None,
- request_id: Optional[str] = None,
+ tools: list | None = None,
+ request_id: str | None = None,
**kwargs,
) -> None:
"""Optional prefill-memory preflight check for chat requests.
@@ -617,7 +618,7 @@ async def preflight_chat(
async def preflight_completion(
self,
prompt: str,
- request_id: Optional[str] = None,
+ request_id: str | None = None,
**kwargs,
) -> None:
"""Optional prefill-memory preflight check for completion requests.
@@ -658,7 +659,7 @@ def __init__(self):
super().__init__()
self._active_count = 0
self._active_lock = threading.Lock()
- self._activities: Dict[str, Dict[str, Any]] = {}
+ self._activities: dict[str, dict[str, Any]] = {}
def has_active_requests(self) -> bool:
"""Check if the engine has active in-flight requests."""
@@ -693,8 +694,8 @@ def _reset_activity_tracking(self) -> None:
}
def _sanitize_activity_metadata(
- self, metadata: Dict[str, Any] | None
- ) -> Dict[str, Any]:
+ self, metadata: dict[str, Any] | None
+ ) -> dict[str, Any]:
"""Drop reserved activity keys from caller-provided metadata.
Timing keys are owned by the tracker: _begin_activity sets them and
@@ -713,7 +714,7 @@ def _begin_activity(
kind: str,
detail: str | None = None,
total_items: int | None = None,
- metadata: Dict[str, Any] | None = None,
+ metadata: dict[str, Any] | None = None,
) -> str:
"""Track a non-streaming operation for admin visibility."""
activity_id = str(uuid.uuid4())
@@ -769,7 +770,7 @@ async def _finish_activity(self, activity_id: str) -> None:
lambda: (mx.synchronize(), mx.clear_cache()),
)
- def get_activity_snapshot(self) -> Dict[str, Any]:
+ def get_activity_snapshot(self) -> dict[str, Any]:
"""Return active non-streaming operations for admin display."""
now = time.monotonic()
with self._active_lock:
@@ -820,7 +821,7 @@ async def stop(self) -> None:
pass
@abstractmethod
- def get_stats(self) -> Dict[str, Any]:
+ def get_stats(self) -> dict[str, Any]:
"""Get engine statistics.
Returns:
diff --git a/omlx/engine/batched.py b/omlx/engine/batched.py
index b8e6af05f3..40cb9bcd64 100644
--- a/omlx/engine/batched.py
+++ b/omlx/engine/batched.py
@@ -11,6 +11,7 @@
import functools
import logging
import threading
+import time
from collections.abc import AsyncIterator
from typing import Any
@@ -41,6 +42,22 @@
logger = logging.getLogger(__name__)
+def _warmup_bailing_hybrid(model: Any, token_id: int = 0) -> bool:
+ """Compile Ling's sorted-prefill and decode graphs before serving."""
+ args = getattr(model, "args", None)
+ if getattr(args, "model_type", None) != "bailing_hybrid":
+ return False
+
+ import mlx.core as mx
+
+ cache = model.make_cache()
+ prefill = model(mx.full((1, 8), token_id, dtype=mx.int32), cache=cache)
+ mx.eval(prefill)
+ decode = model(mx.array([[token_id]], dtype=mx.int32), cache=cache)
+ mx.eval(decode)
+ return True
+
+
# Optional Harmony adapter import
try:
from ..adapter.harmony import preprocess_harmony_messages
@@ -537,6 +554,15 @@ def _load_model_sync():
except Exception:
logger.debug("Qwen FA-256 steel patch not applied", exc_info=True)
+ try:
+ from ..patches.qwen35_gdn_decode import (
+ apply_qwen35_gdn_decode_patch,
+ )
+
+ apply_qwen35_gdn_decode_patch()
+ except Exception:
+ logger.debug("Qwen fused GDN decode patch not applied", exc_info=True)
+
# Qwen3.5/3.6 q4 prefill linears -> native qmm tile tuned for long
# batches. Strictly gated in the patch; decode and unsupported linears
# fall through.
@@ -751,6 +777,13 @@ def _enable_ane_prefill():
except Exception:
logger.debug("qwen3_5 ragged decode patch not applied", exc_info=True)
+ try:
+ from ..patches.qwen35_compiled_mlp import CompiledMLPBlocks
+
+ CompiledMLPBlocks.install(self._model)
+ except Exception:
+ logger.debug("Qwen compiled MLP dispatch not installed", exc_info=True)
+
# Create engine config (copy to avoid mutating the shared instance)
scheduler_config = (
copy.copy(self._scheduler_config)
@@ -777,6 +810,19 @@ def _enable_ane_prefill():
config=engine_config,
)
+ warmup_started = time.perf_counter()
+ warmed_up = await loop.run_in_executor(
+ self._engine.engine._mlx_executor,
+ _warmup_bailing_hybrid,
+ self._model,
+ getattr(self._tokenizer, "bos_token_id", None) or 0,
+ )
+ if warmed_up:
+ logger.info(
+ "Ling inference warmup completed in %.2fs",
+ time.perf_counter() - warmup_started,
+ )
+
await self._engine.engine.start()
# TurboQuant KV cache: propagate bits to scheduler
@@ -1238,9 +1284,9 @@ async def generate(
frequency_penalty=kwargs.get("frequency_penalty", 0.0),
stop=stop or [],
ignore_eos=bool(kwargs.get("ignore_eos", False)),
- thinking_budget=kwargs.get("thinking_budget", None),
- compiled_grammar=kwargs.get("compiled_grammar", None),
- seed=kwargs.get("seed", None),
+ thinking_budget=kwargs.get("thinking_budget"),
+ compiled_grammar=kwargs.get("compiled_grammar"),
+ seed=kwargs.get("seed"),
stop_skips_reasoning=kwargs.get("stop_skips_reasoning", False),
logits_observer=kwargs.get("logits_observer"),
logprobs=bool(kwargs.get("logprobs", False)),
@@ -1328,9 +1374,9 @@ async def stream_generate(
frequency_penalty=kwargs.get("frequency_penalty", 0.0),
stop=stop or [],
ignore_eos=bool(kwargs.get("ignore_eos", False)),
- thinking_budget=kwargs.get("thinking_budget", None),
- compiled_grammar=kwargs.get("compiled_grammar", None),
- seed=kwargs.get("seed", None),
+ thinking_budget=kwargs.get("thinking_budget"),
+ compiled_grammar=kwargs.get("compiled_grammar"),
+ seed=kwargs.get("seed"),
stop_skips_reasoning=kwargs.get("stop_skips_reasoning", False),
logits_observer=kwargs.get("logits_observer"),
logprobs=bool(kwargs.get("logprobs", False)),
diff --git a/omlx/engine/decision.py b/omlx/engine/decision.py
index 762e4a86a7..0d6dc21760 100644
--- a/omlx/engine/decision.py
+++ b/omlx/engine/decision.py
@@ -19,7 +19,7 @@
import mlx.core as mx
from ..engine_core import get_mlx_executor
-from ..model_discovery import decision_kind
+from ..model_discovery import DecisionKind, decision_kind
from ..models.clef import ClefModel
from ..models.d1 import D1Model
from ..models.d3 import D3Model
@@ -30,13 +30,13 @@
logger = logging.getLogger(__name__)
-_MODEL_CLASSES = {
+DecisionModel = ClefModel | OpenJevModel | D3Model | D1Model
+_MODEL_CLASSES: dict[DecisionKind, type[DecisionModel]] = {
"clef": ClefModel,
"openjev": OpenJevModel,
"d3": D3Model,
"d1": D1Model,
}
-DecisionModel = ClefModel | OpenJevModel | D3Model | D1Model
class DecisionEngine(BaseNonStreamingEngine):
diff --git a/omlx/engine_core.py b/omlx/engine_core.py
index 30134ef124..afae53d7eb 100644
--- a/omlx/engine_core.py
+++ b/omlx/engine_core.py
@@ -21,18 +21,11 @@
import time
import uuid
import weakref
+from collections.abc import AsyncIterator, Awaitable, Callable
from contextlib import suppress
from dataclasses import dataclass, field
from typing import (
Any,
- AsyncIterator,
- Awaitable,
- Callable,
- Dict,
- List,
- Optional,
- Tuple,
- Union,
)
import mlx.core as mx
@@ -266,6 +259,15 @@ def _final_global_mlx_thread_reclaim() -> None:
clear_thread_streams()
+def _create_mlx_thread_stream() -> Any:
+ """Create the per-engine stream on the MLX executor thread that owns it."""
+ stream = mx.new_stream(mx.default_device())
+ if hasattr(mx, "set_default_stream"):
+ mx.set_default_stream(stream)
+ logger.info("MLX engine thread initialized: stream = %s", stream)
+ return stream
+
+
def get_mlx_executor() -> concurrent.futures.ThreadPoolExecutor:
"""Get or create the global MLX executor (lazy singleton).
@@ -316,10 +318,10 @@ class EngineConfig:
"""Configuration for the engine."""
model_name: str = ""
- scheduler_config: Optional[SchedulerConfig] = None
+ scheduler_config: SchedulerConfig | None = None
step_interval: float = 0.05 # Idle wait timeout; requests wake the loop
stream_interval: int = 1 # Tokens to batch before streaming (1=every token)
- prefill_eviction_callback: Optional[Callable[[Any], Awaitable[bool]]] = None
+ prefill_eviction_callback: Callable[[Any], Awaitable[bool]] | None = None
# Decode burst: run several scheduler.step() calls per run_in_executor
# hand-off instead of one. Each decode token otherwise bounces back to the
# event loop, ping-ponging the GIL with the asyncio loop + uvicorn on the
@@ -366,8 +368,8 @@ def __init__(
self,
model: Any,
tokenizer: Any,
- config: Optional[EngineConfig] = None,
- engine_id: Optional[str] = None,
+ config: EngineConfig | None = None,
+ engine_id: str | None = None,
force_model_ownership: bool = True,
):
"""
@@ -401,14 +403,18 @@ def __init__(
)
self._owns_model = True
+ self._owns_mlx_executor = True
# Per-engine executor with dedicated mx.Stream (#1248).
# Each EngineCore gets its own thread + GPU stream so different
- # models can run scheduler.step() concurrently.
- self._mlx_stream = mx.new_thread_local_stream(mx.default_device())
+ # models can run scheduler.step() concurrently. MLX streams must be
+ # created on the same thread that later uses them; creating this on
+ # the server/main thread and using it from the executor raises
+ # "There is no Stream(gpu, N) in current thread".
self._mlx_executor = concurrent.futures.ThreadPoolExecutor(
max_workers=1,
thread_name_prefix=f"mlx-engine-{self._engine_id[:8]}",
)
+ self._mlx_stream = self._mlx_executor.submit(_create_mlx_thread_stream).result()
# Create scheduler with per-engine stream
scheduler_config = self.config.scheduler_config or SchedulerConfig()
@@ -420,23 +426,23 @@ def __init__(
)
# Output collectors for low-latency streaming (vLLM pattern)
- self._output_collectors: Dict[str, RequestOutputCollector] = {}
- self._stream_states: Dict[str, RequestStreamState] = {}
- self._finished_events: Dict[str, asyncio.Event] = {}
+ self._output_collectors: dict[str, RequestOutputCollector] = {}
+ self._stream_states: dict[str, RequestStreamState] = {}
+ self._finished_events: dict[str, asyncio.Event] = {}
# Finish timestamps for orphan-collector reaping (#1154).
# Normally a consumer drains and removes its own collector, but if the
# client disconnects mid-stream the SSE generator chain is abandoned and
# its cleanup finally only runs at GC time, so the collector lingers and
# the dashboard keeps showing the request as "Generating".
- self._finished_at: Dict[str, float] = {}
+ self._finished_at: dict[str, float] = {}
self._last_reap = 0.0
# Engine state
self._running = False
- self._task: Optional[asyncio.Task] = None
- self._loop: Optional[asyncio.AbstractEventLoop] = None
- self._wake_event: Optional[asyncio.Event] = None
- self._start_time: Optional[float] = None
+ self._task: asyncio.Task | None = None
+ self._loop: asyncio.AbstractEventLoop | None = None
+ self._wake_event: asyncio.Event | None = None
+ self._start_time: float | None = None
self._steps_executed = 0
# Drop transient aliases after ownership moves to the engine/scheduler
@@ -740,23 +746,23 @@ async def _engine_loop(self) -> None:
async def add_request(
self,
- prompt: Union[str, List[int]],
- sampling_params: Optional[SamplingParams] = None,
- request_id: Optional[str] = None,
- images: Optional[List[Any]] = None,
- videos: Optional[List[Any]] = None,
- vlm_inputs_embeds: Optional[Any] = None,
- vlm_extra_kwargs: Optional[Dict[str, Any]] = None,
- vlm_image_hash: Optional[str] = None,
+ prompt: str | list[int],
+ sampling_params: SamplingParams | None = None,
+ request_id: str | None = None,
+ images: list[Any] | None = None,
+ videos: list[Any] | None = None,
+ vlm_inputs_embeds: Any | None = None,
+ vlm_extra_kwargs: dict[str, Any] | None = None,
+ vlm_image_hash: str | None = None,
vlm_cache_key_start: int = 0,
- vlm_cache_key_ranges: Optional[List[Tuple[int, str]]] = None,
- specprefill: Optional[bool] = None,
- specprefill_keep_pct: Optional[float] = None,
- specprefill_threshold: Optional[int] = None,
- specprefill_system_end: Optional[int] = None,
- generation_prompt_text: Optional[str] = None,
+ vlm_cache_key_ranges: list[tuple[int, str]] | None = None,
+ specprefill: bool | None = None,
+ specprefill_keep_pct: float | None = None,
+ specprefill_threshold: int | None = None,
+ specprefill_system_end: int | None = None,
+ generation_prompt_text: str | None = None,
generation_prompt_persists: bool = False,
- system_prefix_ids: Optional[List[int]] = None,
+ system_prefix_ids: list[int] | None = None,
skip_cache_store: bool = False,
preserve_reasoning: bool = False,
benchmark_trace: bool = False,
@@ -1138,7 +1144,7 @@ async def _delayed_cleanup(self, request_id: str, delay: float = 5.0) -> None:
async def stream_outputs(
self,
request_id: str,
- timeout: Optional[float] = None,
+ timeout: float | None = None,
) -> AsyncIterator[RequestOutput]:
"""
Stream outputs for a request with low-latency non-blocking pattern.
@@ -1180,7 +1186,7 @@ async def stream_outputs(
if output.finished:
break
- except asyncio.TimeoutError:
+ except TimeoutError:
logger.warning(f"Timeout waiting for request {request_id}")
break
@@ -1189,9 +1195,9 @@ async def stream_outputs(
async def generate(
self,
- prompt: Union[str, List[int]],
- sampling_params: Optional[SamplingParams] = None,
- request_id: Optional[str] = None,
+ prompt: str | list[int],
+ sampling_params: SamplingParams | None = None,
+ request_id: str | None = None,
**kwargs,
) -> RequestOutput:
"""
@@ -1266,9 +1272,9 @@ async def generate(
def generate_batch_sync(
self,
- prompts: List[Union[str, List[int]]],
- sampling_params: Optional[SamplingParams] = None,
- ) -> List[RequestOutput]:
+ prompts: list[str | list[int]],
+ sampling_params: SamplingParams | None = None,
+ ) -> list[RequestOutput]:
"""
Generate responses synchronously for maximum throughput.
@@ -1283,41 +1289,45 @@ def generate_batch_sync(
Returns:
List of RequestOutput in same order as prompts
"""
- import uuid as uuid_module
-
- from .request import Request
-
if sampling_params is None:
sampling_params = SamplingParams()
- # Add all requests to scheduler
- request_ids = []
- for prompt in prompts:
- request_id = str(uuid_module.uuid4())
- request = Request(
- request_id=request_id,
- prompt=prompt,
- sampling_params=sampling_params,
- )
- self.scheduler.add_request(request)
- request_ids.append(request_id)
+ def _run_batch_sync() -> list[RequestOutput]:
+ import uuid as uuid_module
- # Process until all done - direct scheduler access, no async overhead
- results: Dict[str, RequestOutput] = {}
- while self.scheduler.has_requests():
- output = self.scheduler.step()
- for req_output in output.outputs:
- if req_output.finished:
- results[req_output.request_id] = req_output
+ from .request import Request
- # Cleanup
- for rid in request_ids:
- self.scheduler.remove_finished_request(rid)
+ # Add all requests to scheduler
+ request_ids = []
+ for prompt in prompts:
+ request_id = str(uuid_module.uuid4())
+ request = Request(
+ request_id=request_id,
+ prompt=prompt,
+ sampling_params=sampling_params,
+ )
+ self.scheduler.add_request(request)
+ request_ids.append(request_id)
+
+ # Process until all done - direct scheduler access on the engine's
+ # MLX worker thread, where self._mlx_stream is valid.
+ results: dict[str, RequestOutput] = {}
+ while self.scheduler.has_requests():
+ output = self.scheduler.step()
+ for req_output in output.outputs:
+ if req_output.finished:
+ results[req_output.request_id] = req_output
+
+ # Cleanup
+ for rid in request_ids:
+ self.scheduler.remove_finished_request(rid)
+
+ # Return in original order
+ return [results[rid] for rid in request_ids]
- # Return in original order
- return [results[rid] for rid in request_ids]
+ return self._mlx_executor.submit(_run_batch_sync).result()
- def get_stats(self) -> Dict[str, Any]:
+ def get_stats(self) -> dict[str, Any]:
"""Get engine statistics."""
scheduler_stats = self.scheduler.get_stats()
uptime = time.time() - self._start_time if self._start_time else 0
@@ -1331,7 +1341,7 @@ def get_stats(self) -> Dict[str, Any]:
**scheduler_stats,
}
- def get_cache_stats(self) -> Optional[Dict[str, Any]]:
+ def get_cache_stats(self) -> dict[str, Any] | None:
"""Get prefix cache statistics."""
return self.scheduler.get_cache_stats()
@@ -1466,7 +1476,7 @@ def drain_gpu_errors() -> None:
self.tokenizer = None
self.scheduler = None
- if self._mlx_executor is not None:
+ if self._mlx_executor is not None and self._owns_mlx_executor:
try:
reclaim_future = self._mlx_executor.submit(
_final_engine_thread_reclaim, self._mlx_stream
@@ -1495,17 +1505,16 @@ def drain_gpu_errors() -> None:
# registry before ThreadPoolExecutor lets that worker exit.
self._mlx_executor.shutdown(wait=False)
self._mlx_executor = None
+ elif self._mlx_executor is not None:
+ self._mlx_executor = None
self._closed = True
logger.debug(f"Engine {self._engine_id} closed")
def __del__(self):
"""Cleanup on destruction."""
- try:
+ with suppress(Exception):
self._release_model()
- except Exception:
- # Ignore errors during garbage collection
- pass
@property
def engine_id(self) -> str:
@@ -1528,7 +1537,7 @@ def __init__(
self,
model: Any,
tokenizer: Any,
- config: Optional[EngineConfig] = None,
+ config: EngineConfig | None = None,
):
self.engine = EngineCore(model, tokenizer, config)
# Drop wrapper-local aliases after EngineCore takes ownership.
@@ -1560,9 +1569,9 @@ async def stop(self) -> None:
async def add_request(
self,
- prompt: Union[str, List[int]],
- sampling_params: Optional[SamplingParams] = None,
- request_id: Optional[str] = None,
+ prompt: str | list[int],
+ sampling_params: SamplingParams | None = None,
+ request_id: str | None = None,
**kwargs,
) -> str:
"""Add a request."""
@@ -1607,7 +1616,7 @@ async def abort_all_requests(
async def stream_outputs(
self,
request_id: str,
- timeout: Optional[float] = None,
+ timeout: float | None = None,
) -> AsyncIterator[RequestOutput]:
"""Stream outputs."""
async for output in self.engine.stream_outputs(request_id, timeout):
@@ -1615,8 +1624,8 @@ async def stream_outputs(
async def generate(
self,
- prompt: Union[str, List[int]],
- sampling_params: Optional[SamplingParams] = None,
+ prompt: str | list[int],
+ sampling_params: SamplingParams | None = None,
**kwargs,
) -> RequestOutput:
"""Generate complete response."""
@@ -1626,10 +1635,10 @@ async def generate(
**kwargs,
)
- def get_stats(self) -> Dict[str, Any]:
+ def get_stats(self) -> dict[str, Any]:
"""Get engine stats."""
return self.engine.get_stats()
- def get_cache_stats(self) -> Optional[Dict[str, Any]]:
+ def get_cache_stats(self) -> dict[str, Any] | None:
"""Get prefix cache statistics."""
return self.engine.get_cache_stats()
diff --git a/omlx/engine_pool.py b/omlx/engine_pool.py
index ca46f3a29a..86ecd8b38e 100644
--- a/omlx/engine_pool.py
+++ b/omlx/engine_pool.py
@@ -14,6 +14,7 @@
from __future__ import annotations
import asyncio
+import contextlib
import copy
import gc
import json
@@ -21,13 +22,14 @@
import time
from collections import OrderedDict
from contextlib import asynccontextmanager, suppress
-from dataclasses import dataclass, replace
+from dataclasses import dataclass, field, replace
from pathlib import Path
-from typing import TYPE_CHECKING, Literal
+from typing import TYPE_CHECKING, Protocol, TypeAlias, cast
if TYPE_CHECKING:
from .cluster.deployment import ClusterDeployment
from .cluster.registry import ClusterRegistry
+ from .engine.image import ImageEngine
from .model_settings import ModelSettingsManager
import mlx.core as mx
@@ -69,10 +71,14 @@
)
from .lora_adapters import adapter_info
from .model_discovery import (
+ IMAGE_MANIFEST_NAME,
VLM_NATIVE_TEXT_MODEL_TYPES,
+ EngineType,
+ ModelType,
detect_model_type,
format_size,
is_realtime_stt_model,
+ model_unavailable_reason,
)
from .custom_kernels.quant_matmul import fast as quant_fast
from .model_settings import (
@@ -104,6 +110,7 @@
dflash_draft_for,
lightning_mtp_supported,
)
+from .utils.optional_deps import MLX_VLM_MISSING_MESSAGE, is_mlx_vlm_available
from .utils.proc_memory import get_phys_footprint
logger = logging.getLogger(__name__)
@@ -336,33 +343,40 @@ def _set_decode_cap(scheduler: object, value: int) -> None:
logger.warning("Live decode cap update failed", exc_info=True)
+class ProcessMemoryEnforcerLike(Protocol):
+ max_bytes: int
+
+ def _propagate_memory_limit(self) -> None: ...
+
+
+def _clear_mlx_cache_sync() -> None:
+ mx.synchronize()
+ mx.clear_cache()
+
+
+if TYPE_CHECKING:
+ EngineInstance: TypeAlias = (
+ BaseEngine
+ | EmbeddingEngine
+ | RerankerEngine
+ | DecisionEngine
+ | STTEngine
+ | STSEngine
+ | TTSEngine
+ | ImageEngine
+ )
+else:
+ EngineInstance: TypeAlias = object
+
+
@dataclass
class EngineEntry:
"""Per-model state in the engine pool."""
model_id: str # Directory name (e.g., "llama-3b")
model_path: str # Full path to model directory
- model_type: Literal[
- "llm",
- "vlm",
- "embedding",
- "reranker",
- "audio_stt",
- "audio_tts",
- "audio_sts",
- "decision",
- ] # Model type
- engine_type: Literal[
- "batched",
- "simple",
- "embedding",
- "reranker",
- "vlm",
- "audio_stt",
- "audio_tts",
- "audio_sts",
- "decision",
- ] # Engine type to use
+ model_type: ModelType # Model type
+ engine_type: EngineType # Engine type to use
estimated_size: int # Pre-calculated from safetensors (bytes)
text_only_size: int = 0 # Language-only estimate for VLM checkpoints (0 = n/a)
actual_size: int | None = None # Observed process-memory delta after load settles
@@ -372,6 +386,7 @@ class EngineEntry:
"" # Raw model_type from config.json (e.g., "deepseekocr_2")
)
realtime_voice: bool = False # Its model type and config allow /v1/realtime
+ supports_audio_input: bool | None = None
thinking_default: bool | None = (
None # True if model thinks by default, False if not, None if unknown
)
@@ -384,21 +399,17 @@ class EngineEntry:
model_context_length: int | None = (
None # Declared context length from config.json (None if unknown)
)
+ reasoning_effort_options: list[str] = field(default_factory=list)
+ reasoning_effort_default: str | None = None
source_type: str = "local"
source_repo_id: str | None = None
+ capabilities: list[str] = field(default_factory=list)
+ tasks: list[str] = field(default_factory=list)
+ image_metadata: dict[str, object] | None = None
is_helper: bool = False # Speculative-decoding drafter (dFlash/Assistant/MTP)
model_format: str | None = None # "gguf": served by an external engine only
source_path: str | None = None # The GGUF file a generated folder links to
- engine: (
- BaseEngine
- | EmbeddingEngine
- | RerankerEngine
- | DecisionEngine
- | STTEngine
- | STSEngine
- | TTSEngine
- | None
- ) = None # Loaded engine instance
+ engine: EngineInstance | None = None # Loaded engine instance
last_access: float = 0.0 # Latest load/acquire/release for LRU and TTL
is_loading: bool = False # Prevent concurrent loads
loading_started_at: float | None = None # Timestamp when current load started
@@ -455,17 +466,18 @@ def __init__(
# Splash engines between launch and load completion, which the memory
# guard must count before entry.engine is set.
self._starting_external: dict[str, SplashEngine] = {}
+ self._deferred_mlx_cleanup = False
# Scanned model roots, kept for org-qualified display/upload names.
self._model_dirs: list[Path] = []
# LoRA adapter folders found in the model roots, by adapter id.
self._lora_adapters: dict[str, str] = {}
self._scheduler_config = scheduler_config or SchedulerConfig()
- self._process_memory_enforcer: object | None = None # Set by server
+ self._process_memory_enforcer: ProcessMemoryEnforcerLike | None = None # Set by server
self._get_final_ceiling: object | None = None # Set by server
+ self._settings_manager: ModelSettingsManager | 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
# Requests whose prefill already got a pooled-buffer reclaim pass.
@@ -483,6 +495,7 @@ def __init__(
self._unloading_models: set[str] = set()
self._failed_load_reclaim_tasks: set[asyncio.Task[None]] = set()
self._failed_load_reclaim_task: asyncio.Task[None] | None = None
+ self._engine_unload_tasks: dict[str, asyncio.Task[None]] = {}
self._shutting_down = False
# Last logged forced-offload state per (model_id, kind).
self._offload_warn_state: dict[tuple[str, str], bool] = {}
@@ -1301,6 +1314,7 @@ def add(key: str, value: object) -> None:
# Security/load gates.
add("trust_remote_code", bool(data.get("trust_remote_code", False)))
add("external_engine", data.get("external_engine") or None)
+ add("mm_processor_kwargs", data.get("mm_processor_kwargs") or None)
add("index_cache_freq", normalized_index_cache_freq())
# Embedding audio tower residency is decided at load. The audio length
# only matters while the tower is loaded.
@@ -1599,6 +1613,13 @@ def discover_models(
text_only_size=getattr(info, "text_only_size", 0),
config_model_type=getattr(info, "config_model_type", ""),
realtime_voice=getattr(info, "realtime_voice", False),
+ supports_audio_input=getattr(info, "supports_audio_input", None),
+ reasoning_effort_options=list(
+ getattr(info, "reasoning_effort_options", [])
+ ),
+ reasoning_effort_default=getattr(
+ info, "reasoning_effort_default", None
+ ),
thinking_default=getattr(info, "thinking_default", None),
preserve_thinking_default=getattr(
info, "preserve_thinking_default", None
@@ -1607,6 +1628,9 @@ def discover_models(
model_context_length=getattr(info, "model_context_length", None),
source_type=getattr(info, "source_type", "local"),
source_repo_id=getattr(info, "source_repo_id", None),
+ capabilities=list(getattr(info, "capabilities", [])),
+ tasks=list(getattr(info, "tasks", [])),
+ image_metadata=getattr(info, "image_metadata", None),
is_helper=getattr(info, "is_helper", False),
model_format=getattr(info, "model_format", None),
source_path=getattr(info, "source_path", None),
@@ -1648,7 +1672,7 @@ def lora_adapters(self) -> dict[str, str]:
"""LoRA adapter folders found in the model roots, by adapter id."""
return dict(self._lora_adapters)
- _MODEL_TYPE_TO_ENGINE: dict[str, str] = {
+ _MODEL_TYPE_TO_ENGINE: dict[ModelType, EngineType] = {
"llm": "batched",
"vlm": "vlm",
"embedding": "embedding",
@@ -1657,6 +1681,7 @@ def lora_adapters(self) -> dict[str, str]:
"audio_tts": "audio_tts",
"audio_sts": "audio_sts",
"decision": "decision",
+ "image": "image",
}
@staticmethod
@@ -1664,6 +1689,12 @@ def _entry_is_diffusion_model(entry: EngineEntry) -> bool:
model_type = (entry.config_model_type or "").lower().replace("-", "_")
return model_type == "diffusion_gemma"
+ @staticmethod
+ def _raise_if_entry_unavailable(entry: EngineEntry) -> None:
+ reason = model_unavailable_reason(entry.config_model_type)
+ if reason is not None:
+ raise ModelUnavailableError(entry.model_id, reason)
+
def apply_settings_overrides(
self, settings_manager: ModelSettingsManager
) -> None:
@@ -1676,9 +1707,10 @@ def apply_settings_overrides(
for model_id, entry in self._entries.items():
settings = settings_manager.get_settings(model_id)
if settings.model_type_override:
- entry.model_type = settings.model_type_override
+ model_type_override = cast(ModelType, settings.model_type_override)
+ entry.model_type = model_type_override
entry.engine_type = self._MODEL_TYPE_TO_ENGINE.get(
- settings.model_type_override, "batched"
+ model_type_override, "batched"
)
logger.info(
f"Applied model_type override for {model_id}: "
@@ -1958,8 +1990,17 @@ def _raise_if_model_path_missing_locked(
source = entry.source_path
if (
model_path.exists()
- and (model_path / "config.json").exists()
and (source is None or Path(source).exists())
+ and (
+ (model_path / "config.json").exists()
+ or (
+ entry.engine_type == "image"
+ and (
+ (model_path / IMAGE_MANIFEST_NAME).exists()
+ or entry.image_metadata is not None
+ )
+ )
+ )
):
return
@@ -2011,10 +2052,38 @@ def _case_insensitive_entry_match(self, name: str) -> str | None:
return mid
return None
+ def get_active_model_aliases(
+ self, settings_manager: ModelSettingsManager | None
+ ) -> dict[str, str]:
+ """Return aliases that can resolve unambiguously to discovered models."""
+ if settings_manager is None:
+ return {}
+
+ aliases_by_name: dict[str, list[str]] = {}
+ for model_id, settings in settings_manager.get_all_settings().items():
+ if model_id not in self._entries or not settings.model_alias:
+ continue
+ alias = settings.model_alias.strip()
+ if not alias:
+ continue
+ aliases_by_name.setdefault(alias, []).append(str(model_id))
+
+ active_aliases: dict[str, str] = {}
+ lower_entry_ids = {model_id.lower(): model_id for model_id in self._entries}
+ for alias, model_ids in aliases_by_name.items():
+ if len(model_ids) != 1:
+ continue
+ model_id = model_ids[0]
+ conflicting_entry = lower_entry_ids.get(alias.lower())
+ if conflicting_entry is not None and conflicting_entry != model_id:
+ continue
+ active_aliases[model_id] = alias
+ return active_aliases
+
def resolve_model_id(
self,
model_id_or_alias: str,
- settings_manager,
+ settings_manager: ModelSettingsManager | None,
claude_tier_aliases: dict[str, str] | None = None,
) -> str:
"""Resolve a model alias to its actual model_id (directory name).
@@ -2037,6 +2106,8 @@ def resolve_model_id(
if ci_match is not None:
return ci_match
+ active_aliases = self.get_active_model_aliases(settings_manager)
+
# Cluster deployment IDs are private runtime handles, but older Chat
# sessions and clients may have persisted one before the public model
# ID was returned consistently. Accept an active deployment ID as a
@@ -2053,19 +2124,20 @@ def resolve_model_id(
# return the caller's original value.
pass
- all_settings = None
if settings_manager is not None:
# Exposed profiles resolve to the physical model they overlay
# (handles provider prefixes internally).
- if hasattr(settings_manager, "get_exposed_profile_source_model_id"):
- profile_source = settings_manager.get_exposed_profile_source_model_id(
- model_id_or_alias
- )
- if profile_source is not None:
+ get_profile_source = getattr(
+ settings_manager,
+ "get_exposed_profile_source_model_id",
+ None,
+ )
+ if callable(get_profile_source):
+ profile_source = get_profile_source(model_id_or_alias)
+ if isinstance(profile_source, str) and profile_source:
return profile_source
- all_settings = settings_manager.get_all_settings()
- for mid, ms in all_settings.items():
- if ms.model_alias and ms.model_alias == model_id_or_alias:
+ for mid, alias in active_aliases.items():
+ if alias == model_id_or_alias:
return mid
# Claude Desktop tier aliases are derived at runtime and resolve only
@@ -2083,9 +2155,9 @@ def resolve_model_id(
ci_match = self._case_insensitive_entry_match(stripped)
if ci_match is not None:
return ci_match
- if all_settings is not None:
- for mid, ms in all_settings.items():
- if ms.model_alias and ms.model_alias == stripped:
+ if settings_manager is not None:
+ for mid, alias in active_aliases.items():
+ if alias == stripped:
return mid
if claude_tier_aliases:
tier_target = claude_tier_aliases.get(stripped)
@@ -2128,9 +2200,12 @@ def _entry_is_busy(self, entry: EngineEntry) -> bool:
@staticmethod
def _has_mlx_lm_path(entry: EngineEntry) -> bool:
- """False for text families that only mlx-vlm implements."""
+ """False for families that only mlx-vlm implements."""
model_type = (entry.config_model_type or "").replace("-", "_").lower()
- return model_type not in VLM_NATIVE_TEXT_MODEL_TYPES
+ return (
+ model_type not in VLM_NATIVE_TEXT_MODEL_TYPES
+ and model_type != "minicpmv4_7"
+ )
def _force_lm_replaces_engine(self, model_id: str) -> bool:
"""True when ``get_engine(force_lm=True)`` would reload a resident VLM."""
@@ -2737,14 +2812,7 @@ async def get_engine(
force_lm: bool = False,
_lease: bool = False,
runtime_settings: object | None = None,
- ) -> (
- BaseEngine
- | EmbeddingEngine
- | RerankerEngine
- | STTEngine
- | STSEngine
- | TTSEngine
- ):
+ ) -> EngineInstance:
"""
Get or load engine for the specified model.
@@ -2788,6 +2856,7 @@ async def get_engine(
entry = self._entries.get(model_id)
if not entry:
raise ModelNotFoundError(model_id, list(self._entries.keys()))
+ self._raise_if_entry_unavailable(entry)
if entry.pending_unload_reason:
raise ModelBusyError(model_id, "start work while unload is pending")
expected_signature = self._engine_runtime_signature(
@@ -2866,6 +2935,12 @@ async def get_engine(
self._raise_if_model_path_missing_locked(model_id, entry)
self._raise_if_load_failed(model_id, entry)
+ # mlx-vlm is required by oMLX, but keep this image admission check
+ # explicit so a damaged or incompatible core install fails before
+ # reserving memory or evicting another model.
+ if entry.engine_type == "image" and not is_mlx_vlm_available():
+ raise ModelLoadingError(model_id, MLX_VLM_MISSING_MESSAGE)
+
# Pre-load admission against the memory ceiling from the
# process memory enforcer (min of static and dynamic). Try
# evicting LRU non-pinned models first; if the model still
@@ -3114,6 +3189,7 @@ async def _release_engine_lease(self, model_id: str) -> None:
e.in_use -= 1
e.last_access = time.time()
await self._unload_pending_if_idle_locked(model_id)
+ await self._run_deferred_mlx_cleanup_if_idle()
def _finish_lease_release_task(self, task: asyncio.Task[None]) -> None:
self._lease_release_tasks.discard(task)
@@ -3752,6 +3828,45 @@ def _other_entries_serving(self, model_id: str) -> bool:
return True
return False
+ async def _run_deferred_mlx_cleanup_if_idle(self) -> None:
+ """Run cleanup deferred by an unload once all leased work has drained."""
+ if not self._deferred_mlx_cleanup:
+ return
+ if any(
+ entry.is_loading
+ or entry.in_use > 0
+ or self._entry_has_active_requests(entry)
+ for entry in self._entries.values()
+ if entry.engine is not None or entry.is_loading
+ ):
+ return
+
+ gc.collect()
+ loop = asyncio.get_running_loop()
+ await loop.run_in_executor(get_mlx_executor(), _clear_mlx_cache_sync)
+ self._deferred_mlx_cleanup = False
+ self._wake_process_memory_enforcer()
+
+ def _finish_engine_unload_task(
+ self,
+ model_id: str,
+ task: asyncio.Task[None],
+ ) -> None:
+ if self._engine_unload_tasks.get(model_id) is task:
+ self._engine_unload_tasks.pop(model_id, None)
+ self._unloading_models.discard(model_id)
+ try:
+ task.result()
+ except asyncio.CancelledError:
+ logger.error("Engine unload task was cancelled for '%s'", model_id)
+ except Exception:
+ logger.exception("Engine unload task failed for '%s'", model_id)
+
+ async def _drain_engine_unload_tasks(self) -> None:
+ while self._engine_unload_tasks:
+ tasks = tuple(self._engine_unload_tasks.values())
+ await asyncio.gather(*tasks, return_exceptions=True)
+
async def _unload_engine(self, model_id: str, *, local_only: bool = False) -> None:
if model_id in self._unloading_models:
raise ModelBusyError(model_id, "unload while teardown is in progress")
@@ -3761,18 +3876,23 @@ async def _unload_engine(self, model_id: str, *, local_only: bool = False) -> No
model_id, **({"local_only": True} if local_only else {})
)
)
- cancelled = False
+ self._engine_unload_tasks[model_id] = task
+ task.add_done_callback(
+ lambda completed, mid=model_id: self._finish_engine_unload_task(
+ mid, completed
+ )
+ )
try:
+ await asyncio.shield(task)
+ except asyncio.CancelledError:
while not task.done():
try:
await asyncio.shield(task)
except asyncio.CancelledError:
- cancelled = True
- task.result()
- finally:
- self._unloading_models.discard(model_id)
- if cancelled:
- raise asyncio.CancelledError
+ continue
+ except Exception:
+ break
+ raise
async def _metal_sync_clear_cache(self, model_id: str) -> None:
"""Synchronize and clear the Metal cache during unload."""
@@ -3825,11 +3945,20 @@ async def _stop_and_unload_engine(
)
pre_unload_active = 0 if external else mx.get_active_memory()
pre_unload_footprint = 0 if external else get_phys_footprint()
+ concurrent_activity = (
+ False if external else self._other_entries_serving(model_id)
+ )
try:
- await entry.engine.stop(
- **({"local_only": True} if local_only and distributed else {})
+ concurrent_stop = getattr(
+ entry.engine, "stop_without_global_cleanup", None
)
+ if concurrent_activity and callable(concurrent_stop):
+ await concurrent_stop()
+ else:
+ await entry.engine.stop(
+ **({'local_only': True} if local_only and distributed else {})
+ )
except Exception as e:
if distributed:
# The supervisor raises (DistributedTeardownError) when the
@@ -3894,13 +4023,12 @@ async def _stop_and_unload_engine(
self._wake_process_memory_enforcer()
return
- # Force garbage collection to release memory.
- # Run mx.clear_cache on the global MLX executor to avoid concurrent
- # Metal operations with running engines. See issue #85.
- # Synchronize before clearing to prevent releasing Metal buffers
- # still referenced by in-flight command buffers. See issue #300.
+ # Force garbage collection to release the target engine's references.
+ # A global synchronize/clear-cache must not be queued behind another
+ # active engine: doing so makes an otherwise idle model's unload wait
+ # for that inference to finish. Live memory remains visible to future
+ # admission checks if allocator cache is not immediately reclaimable.
gc.collect()
- await self._metal_sync_clear_cache(model_id)
# RAM Engram tables share MLX buffers with CPU views, so their packed
# bytes are included in both admission and Metal unload settlement.
@@ -3919,7 +4047,26 @@ async def _stop_and_unload_engine(
settle_indeterminate = False
settle_stalled = False
last_freed: int | None = None
- for _settle_round in range(10):
+ active_now = pre_unload_active
+ actual_freed = 0
+ concurrent_activity = self._other_entries_serving(model_id)
+ if concurrent_activity:
+ active_now = mx.get_active_memory()
+ actual_freed = pre_unload_active - active_now
+ settle_indeterminate = True
+ self._deferred_mlx_cleanup = True
+ logger.info(
+ f"Settle for '{model_id}' indeterminate under concurrent "
+ f"activity (freed={format_size(actual_freed)}, "
+ f"need>={format_size(min_expected_freed)}); skipping "
+ f"global MLX cleanup and settle wait"
+ )
+ else:
+ # Run mx.clear_cache on the global MLX executor only while the
+ # pool is otherwise idle. See issues #85 and #300.
+ await self._metal_sync_clear_cache(model_id)
+
+ for _settle_round in range(10 if not settle_indeterminate else 0):
active_now = mx.get_active_memory()
actual_freed = pre_unload_active - active_now
# Metal can release arrays before macOS updates its footprint
@@ -3952,7 +4099,7 @@ async def _stop_and_unload_engine(
f"Settle for '{model_id}' indeterminate under concurrent "
f"activity (freed={format_size(actual_freed)}, "
f"need>={format_size(min_expected_freed)}); skipping "
- f"settle wait"
+ f"further global MLX cleanup and settle wait"
)
break
if (
@@ -4147,6 +4294,7 @@ async def _load_engine(
ModelLoadingError: If model is already being loaded
"""
entry = self._entries[model_id]
+ self._raise_if_entry_unavailable(entry)
if entry.is_loading:
raise ModelLoadingError(model_id)
await self._check_splash_launcher(model_id, runtime_settings)
@@ -4180,6 +4328,16 @@ async def _load_engine(
model_settings = self._effective_deepseek_v41_model_settings(
entry, model_settings
)
+ if entry.config_model_type == "minicpmv4_7" and model_settings is not None:
+ from .model_settings import validate_minicpm_speculation
+
+ validate_minicpm_speculation(
+ model_settings.to_dict(), entry.config_model_type
+ )
+ if model_settings.dflash_enabled and effective_type != "vlm":
+ raise ValueError(
+ "MiniCPM DSpark requires the native batched VLM engine."
+ )
if getattr(model_settings, "qwen35_ane_prefill_enabled", False):
validate_ane_prefill(model_settings.to_dict(), entry.config_model_type)
@@ -4358,6 +4516,26 @@ async def prefill_eviction_callback(
model_name=entry.model_path,
config_model_type=entry.config_model_type,
)
+ elif effective_type == "image":
+ if not is_mlx_vlm_available():
+ raise ModelLoadingError(model_id, MLX_VLM_MISSING_MESSAGE)
+ try:
+ from .engine.image import ImageEngine
+ except ImportError as exc:
+ raise ModelLoadingError(
+ model_id, MLX_VLM_MISSING_MESSAGE
+ ) from exc
+
+ engine = ImageEngine(
+ model_name=entry.model_path,
+ model_id=model_id,
+ model_path=entry.model_path,
+ config_model_type=entry.config_model_type,
+ image_metadata=entry.image_metadata or {},
+ capabilities=list(entry.capabilities),
+ tasks=list(entry.tasks),
+ model_settings=model_settings,
+ )
else:
engine = BatchedEngine(
model_name=entry.model_path,
@@ -4387,15 +4565,13 @@ async def prefill_eviction_callback(
f"(force_lm=True), falling back to VLM engine: "
f"{start_error}"
)
- try:
+ with contextlib.suppress(Exception):
await engine.stop()
- except Exception:
- pass
gc.collect()
loop = asyncio.get_running_loop()
await loop.run_in_executor(
get_mlx_executor(),
- lambda: (mx.synchronize(), mx.clear_cache()),
+ _clear_mlx_cache_sync,
)
engine = VLMBatchedEngine(
@@ -4423,15 +4599,13 @@ async def prefill_eviction_callback(
f"VLM loading failed for {model_id}, "
f"falling back to LLM: {start_error}"
)
- try:
+ with contextlib.suppress(Exception):
await engine.stop()
- except Exception:
- pass
gc.collect()
loop = asyncio.get_running_loop()
await loop.run_in_executor(
get_mlx_executor(),
- lambda: (mx.synchronize(), mx.clear_cache()),
+ _clear_mlx_cache_sync,
)
engine = BatchedEngine(
@@ -4455,6 +4629,22 @@ async def prefill_eviction_callback(
logger.info(
f"Successfully loaded {model_id} as LLM (fallback from VLM)"
)
+ elif entry.engine_type == "image" and isinstance(start_error, ImportError):
+ # ImageEngine imports mlx-vlm lazily during model load.
+ # If the core package went missing after admission, surface
+ # the centralized dependency error instead of raw import.
+ with contextlib.suppress(Exception):
+ await engine.stop()
+ raise ModelLoadingError(
+ model_id, MLX_VLM_MISSING_MESSAGE
+ ) from start_error
+ elif entry.engine_type == "image" and isinstance(start_error, ValueError):
+ # ImageEngine validates the manifest before loading model
+ # weights. Surface unsupported families and stale
+ # quantize settings as ordinary model-load failures.
+ with contextlib.suppress(Exception):
+ await engine.stop()
+ raise ModelLoadingError(model_id, str(start_error)) from start_error
else:
raise
finally:
@@ -4474,7 +4664,7 @@ async def prefill_eviction_callback(
loop = asyncio.get_running_loop()
await loop.run_in_executor(
get_mlx_executor(),
- lambda: (mx.synchronize(), mx.clear_cache()),
+ _clear_mlx_cache_sync,
)
raise ModelLoadingError(
model_id,
@@ -4511,6 +4701,7 @@ def _load_dflash_sync(path: str = drafter_path):
path,
engine.prepare_dflash_target(),
tokenizer=engine.tokenizer,
+ target_path=entry.model_path,
block_size=getattr(model_settings, "dflash_block_size", None),
quant_enabled=bool(
getattr(model_settings, "dflash_draft_quant_enabled", False)
@@ -4535,6 +4726,10 @@ def _load_dflash_sync(path: str = drafter_path):
get_mlx_executor(), _load_dflash_sync
)
except Exception as e:
+ if entry.config_model_type == "minicpmv4_7":
+ await self._unload_engine(model_id)
+ load_completed = False
+ raise
logger.warning(
f"DFlash drafter load raised for {model_id} "
f"(drafter={drafter_id}): {e} -- toggle ignored"
@@ -4659,7 +4854,7 @@ def _load_drafter_sync(path: str = drafter_path):
loop = asyncio.get_running_loop()
await loop.run_in_executor(
get_mlx_executor(),
- lambda: (mx.synchronize(), mx.clear_cache()),
+ _clear_mlx_cache_sync,
)
post_load_memory = max(mx.get_active_memory(), get_phys_footprint())
@@ -4816,6 +5011,7 @@ async def shutdown(self) -> None:
if pending_tasks:
await asyncio.gather(*pending_tasks, return_exceptions=True)
await self._drain_lease_release_tasks()
+ await self._drain_engine_unload_tasks()
async with self._lock:
for model_id in list(self._entries.keys()):
entry = self._entries.get(model_id)
@@ -4865,13 +5061,21 @@ def get_status(self) -> dict:
"engine_type": e.engine_type,
"model_type": e.model_type,
"config_model_type": e.config_model_type,
+ "unavailable_reason": model_unavailable_reason(
+ e.config_model_type
+ ),
"realtime_stt": is_realtime_stt_model(
e.model_type, e.config_model_type
),
# d1 decision checkpoints share lfm3_omni but run on the decision engine.
"realtime_voice": e.engine_type == "vlm" and e.realtime_voice,
+ "supports_audio_input": (
+ e.supports_audio_input if e.engine_type == "vlm" else False
+ ),
"model_context_length": e.model_context_length,
"is_helper": e.is_helper,
+ "reasoning_effort_options": list(e.reasoning_effort_options),
+ "reasoning_effort_default": e.reasoning_effort_default,
"thinking_default": e.thinking_default,
"preserve_thinking_default": e.preserve_thinking_default,
"reasoning_efforts": e.reasoning_efforts,
@@ -4879,6 +5083,9 @@ def get_status(self) -> dict:
"source_repo_id": e.source_repo_id,
"model_format": e.model_format,
"source_path": e.source_path,
+ "capabilities": e.capabilities,
+ "tasks": e.tasks,
+ "image_metadata": e.image_metadata,
"last_access": e.last_access if e.last_access > 0 else None,
}
)
diff --git a/omlx/exceptions.py b/omlx/exceptions.py
index 3b9f0fc89b..5995f171af 100644
--- a/omlx/exceptions.py
+++ b/omlx/exceptions.py
@@ -19,7 +19,7 @@
"""
from collections.abc import Callable
-from typing import Any, Optional, Union
+from typing import Any
# Direction of the memory_guard_tier knob. Spelled out everywhere a message
# names the tier: the admin popup lists Safe first, so "lower the tier" reads
@@ -48,7 +48,7 @@ def describe_ceiling_binding(
tier: str,
current: int,
fmt: Callable[[int], str],
- tail: Optional[Union[str, list[str]]] = None,
+ tail: str | list[str] | None = None,
metal_cap_raw: int = 0,
hot_cache: int = 0,
) -> tuple[str, str]:
@@ -135,7 +135,7 @@ class OMLXError(Exception):
for easy catching of all oMLX-related errors.
"""
- def __init__(self, message: str, details: Optional[dict] = None):
+ def __init__(self, message: str, details: dict | None = None):
super().__init__(message)
self.message = message
self.details = details or {}
@@ -173,9 +173,9 @@ class CacheCorruptionError(CacheError):
def __init__(
self,
message: str,
- request_id: Optional[str] = None,
- block_id: Optional[int] = None,
- details: Optional[dict] = None,
+ request_id: str | None = None,
+ block_id: int | None = None,
+ details: dict | None = None,
):
super().__init__(message, details)
self.request_id = request_id
@@ -193,8 +193,8 @@ class CacheMissError(CacheError):
def __init__(
self,
message: str,
- key: Optional[Any] = None,
- details: Optional[dict] = None,
+ key: Any | None = None,
+ details: dict | None = None,
):
super().__init__(message, details)
self.key = key
@@ -221,9 +221,9 @@ class CacheStorageError(CacheError):
def __init__(
self,
message: str,
- path: Optional[str] = None,
- operation: Optional[str] = None,
- details: Optional[dict] = None,
+ path: str | None = None,
+ operation: str | None = None,
+ details: dict | None = None,
):
super().__init__(message, details)
self.path = path
@@ -252,8 +252,8 @@ class RequestError(SchedulerError):
def __init__(
self,
message: str,
- request_id: Optional[str] = None,
- details: Optional[dict] = None,
+ request_id: str | None = None,
+ details: dict | None = None,
):
super().__init__(message, details)
self.request_id = request_id
@@ -299,7 +299,7 @@ def __init__(
self,
current_depth: int,
max_depth: int,
- details: Optional[dict] = None,
+ details: dict | None = None,
):
super().__init__(
f"Scheduler waiting queue full: {current_depth} >= {max_depth}",
@@ -331,8 +331,8 @@ class ModelLoadError(ModelError):
def __init__(
self,
message: str,
- model_name: Optional[str] = None,
- details: Optional[dict] = None,
+ model_name: str | None = None,
+ details: dict | None = None,
):
super().__init__(message, details)
self.model_name = model_name
@@ -372,13 +372,25 @@ class InvalidRequestError(APIError):
def __init__(
self,
message: str,
- field: Optional[str] = None,
- details: Optional[dict] = None,
+ field: str | None = None,
+ details: dict | None = None,
):
super().__init__(message, details)
self.field = field
+class UnsupportedKokoroLanguageError(InvalidRequestError):
+ """Kokoro's selected language requires the optional eSpeak backend."""
+
+ def __init__(self, language: str):
+ self.language = language
+ super().__init__(
+ f"Kokoro's {language} language path requires eSpeak. "
+ "Use Qwen3-TTS for this language.",
+ field="language",
+ )
+
+
class RateLimitError(APIError):
"""Request was rate limited."""
@@ -407,8 +419,8 @@ class ConfigurationError(OMLXError):
def __init__(
self,
message: str,
- config_key: Optional[str] = None,
- details: Optional[dict] = None,
+ config_key: str | None = None,
+ details: dict | None = None,
):
super().__init__(message, details)
self.config_key = config_key
@@ -436,9 +448,9 @@ class OutOfMemoryError(OMLXMemoryError):
def __init__(
self,
message: str,
- requested_bytes: Optional[int] = None,
- available_bytes: Optional[int] = None,
- details: Optional[dict] = None,
+ requested_bytes: int | None = None,
+ available_bytes: int | None = None,
+ details: dict | None = None,
):
super().__init__(message, details)
self.requested_bytes = requested_bytes
@@ -463,10 +475,10 @@ class PrefillMemoryExceededError(OMLXMemoryError):
def __init__(
self,
message: str,
- request_id: Optional[str] = None,
- estimated_bytes: Optional[int] = None,
- limit_bytes: Optional[int] = None,
- details: Optional[dict] = None,
+ request_id: str | None = None,
+ estimated_bytes: int | None = None,
+ limit_bytes: int | None = None,
+ details: dict | None = None,
):
super().__init__(message, details)
self.request_id = request_id
@@ -520,8 +532,8 @@ def __init__(
model_size: int,
ceiling: int,
*,
- binding: Optional[str] = None,
- advice: Optional[str] = None,
+ binding: str | None = None,
+ advice: str | None = None,
):
self.model_id = model_id
self.model_size = model_size
diff --git a/omlx/model_classification.py b/omlx/model_classification.py
new file mode 100644
index 0000000000..615851822c
--- /dev/null
+++ b/omlx/model_classification.py
@@ -0,0 +1,88 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Lightweight checkpoint classification shared by discovery and integrations."""
+
+TEXT_ONLY_CHAT_MODEL_TYPES = frozenset({"flint"})
+
+NEMOTRON_OMNI_MODEL_TYPES = frozenset(
+ {"nemotron_h_nano_omni", "nemotronh_nano_omni_reasoning_v3", "nemotron_h_omni"}
+)
+
+
+def is_nemotron_omni(model_type: str | None) -> bool:
+ return (
+ isinstance(model_type, str) and model_type.lower() in NEMOTRON_OMNI_MODEL_TYPES
+ )
+
+
+def is_nemotron_modelopt_source(config: dict) -> bool:
+ quant = config.get("quantization_config") or {}
+ if not isinstance(quant, dict) or not is_nemotron_omni(config.get("model_type")):
+ return False
+ return (
+ quant.get("quant_method") in {"modelopt", "modelopt_mixed"}
+ or (
+ quant.get("quant_method") == "fp8"
+ and quant.get("moe_quant_algo") == "NVFP4"
+ )
+ ) and quant.get("quant_algo") in {"NVFP4", "W4A16_NVFP4", "MIXED_PRECISION"}
+
+
+def normalize_nemotron_config(config: dict) -> dict:
+ """Expose native aliases and layer geometry without importing an engine."""
+ if not is_nemotron_omni(config.get("model_type")):
+ return config
+ result = dict(config)
+ result["model_type"] = config["model_type"].lower()
+ text = dict(result.get("text_config") or result.pop("llm_config", None) or {})
+ result.pop("llm_config", None)
+ pattern = (
+ text.get("block_configs")
+ or text.get("hybrid_override_pattern")
+ or text.get("layers_block_type")
+ )
+ if pattern:
+ text["num_hidden_layers"] = len(pattern)
+ if result.get("vision_final_layernorm") is None:
+ result["vision_final_layernorm"] = (
+ int(text.get("num_nextn_predict_layers", 0) or 0) > 0
+ )
+ result["text_config"] = text
+ return result
+
+
+# Known embedding model types served by mlx-vlm or oMLX native loaders
+EMBEDDING_MODEL_TYPES = {
+ "embedding_gemma2",
+ "bert",
+ "xlm-roberta",
+ "xlm_roberta",
+ "modernbert",
+ "siglip",
+ "colqwen2_5",
+ "colqwen2-5",
+}
+
+# Speculative-decoding "helper" checkpoints (dFlash / MTP / assistant drafters)
+# are never meant to be served as standalone chat models. Some declare a
+# distinctive top-level model_type — an ``*_assistant`` (e.g. gemma4_assistant)
+# or ``*_mtp`` (e.g. qwen3_5_mtp) marker — but DFlash draft checkpoints declare
+# a plain model_type (e.g. ``qwen3``) and are only distinguishable by their
+# architecture name (``DFlashDraftModel``) or a drafter-only config block
+# (``dflash_config``). Keep these in sync with the drafter resolution in
+# engine_pool.py (~1498) and the dflash gate in engine/dflash.py when new
+# drafter families are added.
+HELPER_CONFIG_MODEL_TYPE_SUFFIXES = ("_assistant", "_mtp")
+
+
+def is_helper_config_model_type(config_model_type: str | None) -> bool:
+ """True when ``config_model_type`` marks a speculative-decoding drafter.
+
+ These are the raw top-level ``model_type`` values from a checkpoint's
+ config.json (e.g. ``gemma4_assistant``, ``qwen3_5_mtp``). Note this misses
+ DFlash drafts, whose model_type is a plain ``qwen3`` — use
+ :func:`omlx.model_discovery.is_helper_model_config` when the full config dict is available.
+ """
+ if not isinstance(config_model_type, str) or not config_model_type:
+ return False
+ mt = config_model_type.lower()
+ return mt.endswith(HELPER_CONFIG_MODEL_TYPE_SUFFIXES)
diff --git a/omlx/model_discovery.py b/omlx/model_discovery.py
index 62df8ff531..a23edb04f8 100644
--- a/omlx/model_discovery.py
+++ b/omlx/model_discovery.py
@@ -13,39 +13,87 @@
- Audio STT models: Use STTEngine for speech-to-text (Whisper, Qwen3-ASR, ...)
- Audio TTS models: Use TTSEngine for text-to-speech (Qwen3-TTS, Kokoro, ...)
- Decision models: Use DecisionEngine for /v1/systemone (Clef, OpenJev, d3, d1)
+- Image models: Use ImageEngine for mlx-vlm-backed image generation/editing
"""
+import ast
import contextlib
+import importlib
import json
import logging
+import math
import re
import tempfile
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from pathlib import Path
from typing import Literal
from transformers.utils.chat_template_utils import render_jinja_template
from . import gguf
+from .image_registry import (
+ IMAGE_DEFAULT_ESTIMATED_SIZES,
+ IMAGE_UNKNOWN_FALLBACK_SIZE,
+ get_image_model_spec,
+ infer_image_model_spec_from_name,
+ normalize_image_alias,
+)
+from .model_classification import (
+ EMBEDDING_MODEL_TYPES,
+ TEXT_ONLY_CHAT_MODEL_TYPES,
+ is_helper_config_model_type,
+)
+from .utils.safetensors_shards import select_safetensors_weight_files
logger = logging.getLogger(__name__)
ModelType = Literal[
- "llm", "vlm", "embedding", "reranker", "audio_stt", "audio_tts", "audio_sts", "decision"
+ "llm",
+ "vlm",
+ "embedding",
+ "reranker",
+ "audio_stt",
+ "audio_tts",
+ "audio_sts",
+ "image",
+ "decision",
]
EngineType = Literal[
- "batched", "vlm", "embedding", "reranker", "audio_stt", "audio_tts", "audio_sts", "decision"
+ "batched",
+ "vlm",
+ "embedding",
+ "reranker",
+ "audio_stt",
+ "audio_tts",
+ "audio_sts",
+ "image",
+ "decision",
]
DecisionKind = Literal["clef", "openjev", "d3", "d1"]
+IMAGE_MANIFEST_NAME = "omlx-image-model.json"
+
+QWEN4_EXP_MODEL_TYPE = "qwen4_exp"
+QWEN4_EXP_ARCHITECTURE = "Qwen4ExpForConditionalGeneration"
+
+
+def model_unavailable_reason(config_model_type: str | None) -> str | None:
+ """Return a stable serving-policy reason for a known unavailable family."""
+ return None
+
+
# Known VLM (Vision-Language Model) types from mlx-vlm
VLM_MODEL_TYPES = {
+ "nemotron_h_nano_omni",
+ "nemotronh_nano_omni_reasoning_v3",
+ "nemotron_h_omni",
"deepseek_v41",
"qwen2_vl",
"qwen2_5_vl",
"qwen3_vl",
"qwen3_vl_moe",
"qwen3_5_moe",
+ QWEN4_EXP_MODEL_TYPE,
"gemma3",
"gemma4",
"gemma4_unified",
@@ -80,6 +128,7 @@
"inkling_mm_model", # config model_type of Inkling Small checkpoints
# mlx-lm's Inkling 2 module served through the VLM engine adapter.
"inkling2",
+ "bailing_moe_v3_vl",
"muse_glimmer",
"muse_spark",
"glm5_next",
@@ -134,33 +183,10 @@
D3_DECISION_CONFIG,
)
-# Speculative-decoding "helper" checkpoints (dFlash / MTP / assistant drafters)
-# are never meant to be served as standalone chat models. Some declare a
-# distinctive top-level model_type — an ``*_assistant`` (e.g. gemma4_assistant)
-# or ``*_mtp`` (e.g. qwen3_5_mtp) marker — but DFlash draft checkpoints declare
-# a plain model_type (e.g. ``qwen3``) and are only distinguishable by their
-# architecture name (``DFlashDraftModel``) or a drafter-only config block
-# (``dflash_config``). Keep these in sync with the drafter resolution in
-# engine_pool.py when new drafter families are added.
-HELPER_CONFIG_MODEL_TYPE_SUFFIXES = ("_assistant", "_mtp")
_HELPER_ARCH_TOKENS = ("draft", "assistant", "mtp")
_HELPER_CONFIG_KEYS = ("dflash_config",)
-def is_helper_config_model_type(config_model_type: str | None) -> bool:
- """True when ``config_model_type`` marks a speculative-decoding drafter.
-
- These are the raw top-level ``model_type`` values from a checkpoint's
- config.json (e.g. ``gemma4_assistant``, ``qwen3_5_mtp``). Note this misses
- DFlash drafts, whose model_type is a plain ``qwen3`` — use
- :func:`is_helper_model_config` when the full config dict is available.
- """
- if not isinstance(config_model_type, str) or not config_model_type:
- return False
- mt = config_model_type.lower()
- return mt.endswith(HELPER_CONFIG_MODEL_TYPE_SUFFIXES)
-
-
def is_helper_model_config(config: dict) -> bool:
"""True when a parsed config.json marks a speculative-decoding drafter.
@@ -190,10 +216,12 @@ def is_helper_model_config(config: dict) -> bool:
# Known VLM architectures
VLM_ARCHITECTURES = {
+ "MiniCPMV4_7ForConditionalGeneration",
"LlavaForConditionalGeneration",
"LlavaNextForConditionalGeneration",
"Qwen2VLForConditionalGeneration",
"Qwen2_5_VLForConditionalGeneration",
+ QWEN4_EXP_ARCHITECTURE,
"MllamaForConditionalGeneration",
"Gemma3ForConditionalGeneration",
"Gemma4ForConditionalGeneration",
@@ -207,6 +235,7 @@ def is_helper_model_config(config: dict) -> bool:
"LlavaQwen2ForCausalLM", # apple/FastVLM (all sizes)
"UnlimitedOCRForCausalLM", # baidu/Unlimited-OCR
"InklingForConditionalGeneration", # thinkingmachines/Inkling-Small
+ "BailingMoeV3VLForConditionalGeneration", # Ling 3.0 Flash VL
"MuseGlimmerForConditionalGeneration", # meta-models/Muse-Glimmer-30B
"MuseSparkForConditionalGeneration", # meta-models/Muse-Spark-Open-816B-A42B
"Glm5NextForConditionalGeneration", # zai-org/GLM-5.3-Flash
@@ -214,17 +243,6 @@ def is_helper_model_config(config: dict) -> bool:
"Moondream", # vikhyatk/moondream2 (2024 revisions)
}
-# Known embedding model types from mlx-embeddings
-EMBEDDING_MODEL_TYPES = {
- "bert",
- "xlm-roberta",
- "xlm_roberta",
- "modernbert",
- "siglip",
- "colqwen2_5",
- "colqwen2-5",
-}
-
# Model types that have both embedding and LLM variants.
# These require architecture-based disambiguation via EMBEDDING_ARCHITECTURES.
AMBIGUOUS_EMBEDDING_MODEL_TYPES = {
@@ -244,15 +262,14 @@ def is_helper_model_config(config: dict) -> bool:
"ModernBertForMaskedLM",
"Qwen3ForTextEmbedding",
"SiglipModel",
- "SiglipVisionModel",
"SiglipTextModel",
"EmbeddingGemma2Model", # via mlx-vlm; has vision_config, checked before VLM
}
# Supported reranker architectures
SUPPORTED_RERANKER_ARCHITECTURES = {
- "ModernBertForSequenceClassification", # via mlx-embeddings
- "XLMRobertaForSequenceClassification", # omlx native implementation
+ "ModernBertForSequenceClassification", # via mlx-vlm
+ "XLMRobertaForSequenceClassification", # via mlx-vlm
"JinaForRanking", # Jina v3 listwise reranker
}
@@ -275,7 +292,7 @@ def is_helper_model_config(config: dict) -> bool:
# Multimodal (VLM-based) reranker architectures.
# These share an architecture with VLM chat models but are fine-tuned for
-# reranking. Loaded via mlx-embeddings' model.process() API. Distinguished
+# reranking. Scored via mlx-vlm's reranking helpers. Distinguished
# from VLM chat by directory name heuristic.
MULTIMODAL_RERANKER_ARCHITECTURES = {
"Qwen3VLForConditionalGeneration", # Qwen3-VL-Reranker
@@ -294,13 +311,14 @@ def is_helper_model_config(config: dict) -> bool:
}
# All known reranker architectures (for model type detection)
-RERANKER_ARCHITECTURES = SUPPORTED_RERANKER_ARCHITECTURES | UNSUPPORTED_RERANKER_ARCHITECTURES
+RERANKER_ARCHITECTURES = (
+ SUPPORTED_RERANKER_ARCHITECTURES | UNSUPPORTED_RERANKER_ARCHITECTURES
+)
# Unsupported model types — detected and skipped during discovery.
-# Only top-level config fields are checked; nested audio_config/tts_config in
-# multimodal models (e.g., MiniCPM-o) won't trigger this.
-# Note: "whisper" and "qwen3_tts" were previously listed here but are now
-# handled as audio types (audio_stt / audio_tts) — see AUDIO_* sets below.
+# Speculative drafters are intentionally not included here: they must be
+# discoverable as helpers so status endpoints and drafter selectors can expose
+# them, even though a parent model consumes them instead of serving them alone.
# Florence-2 is an encoder-decoder; its decoder cache cannot join a batch.
UNSUPPORTED_ARCHITECTURES: set[str] = {"Florence2ForConditionalGeneration"}
@@ -331,26 +349,27 @@ def _build_audio_detection_sets():
model_type strings that should trigger audio detection.
"""
try:
- from pathlib import Path as _P
-
import mlx_audio as _mla
- _base = _P(_mla.__file__).parent
+ _base = Path(_mla.__file__).parent
def _dir_names(subdir: str) -> set:
d = _base / subdir / "models"
if d.is_dir():
- return {p.name for p in d.iterdir()
- if p.is_dir() and not p.name.startswith("__")}
+ return {
+ p.name
+ for p in d.iterdir()
+ if p.is_dir() and not p.name.startswith("__")
+ }
return set()
# TTS: MODEL_REMAPPING keys + model dir names
- from mlx_audio.tts.utils import MODEL_REMAPPING as _tts_remap
- tts = set(_tts_remap.keys()) | _dir_names("tts")
+ tts_utils = importlib.import_module("mlx_audio.tts.utils")
+ tts = set(tts_utils.MODEL_REMAPPING.keys()) | _dir_names("tts")
# STT: MODEL_REMAPPING keys + model dir names
- from mlx_audio.stt.utils import MODEL_REMAPPING as _stt_remap
- stt = set(_stt_remap.keys()) | _dir_names("stt")
+ stt_utils = importlib.import_module("mlx_audio.stt.utils")
+ stt = set(stt_utils.MODEL_REMAPPING.keys()) | _dir_names("stt")
# STS: model dir names only (no unified utils/remapping)
sts = _dir_names("sts")
@@ -360,8 +379,10 @@ def _dir_names(subdir: str) -> set:
stt -= _LLM_TYPE_COLLISIONS
logger.debug(
- "Audio detection sets loaded from mlx-audio: "
- "STT=%d, TTS=%d, STS=%d", len(stt), len(tts), len(sts),
+ "Audio detection sets loaded from mlx-audio: STT=%d, TTS=%d, STS=%d",
+ len(stt),
+ len(tts),
+ len(sts),
)
return stt, tts, sts
@@ -369,7 +390,15 @@ def _dir_names(subdir: str) -> set:
logger.debug("mlx-audio not available — using static audio detection sets")
# Static fallback so model discovery still works without mlx-audio
_stt = {"whisper", "qwen3_asr", "parakeet", "qwen2_audio"}
- _tts = {"qwen3_tts", "kokoro", "chatterbox", "vibevoice", "vibevoice_streaming", "kugelaudio", "audiodit"}
+ _tts = {
+ "qwen3_tts",
+ "kokoro",
+ "chatterbox",
+ "vibevoice",
+ "vibevoice_streaming",
+ "kugelaudio",
+ "audiodit",
+ }
_sts = {"deepfilternet", "mossformer2_se", "sam_audio", "lfm_audio"}
return _stt, _tts, _sts
@@ -428,18 +457,34 @@ class DiscoveredModel:
model_id: str # Directory name (e.g., "llama-3b")
model_path: str # Full path to model directory
- model_type: ModelType # "llm", "vlm", "embedding", or "reranker"
- engine_type: EngineType # "batched", "vlm", "embedding", or "reranker"
+ # "llm", "vlm", "embedding", "reranker", "audio_*", or "image"
+ model_type: ModelType
+ # "batched", "vlm", "embedding", "reranker", "audio_*", or "image"
+ engine_type: EngineType
estimated_size: int # Estimated memory usage in bytes
text_only_size: int = 0 # Language-only estimate for VLM checkpoints (0 = n/a)
- config_model_type: str = "" # Raw model_type from config.json (e.g., "deepseekocr_2")
realtime_voice: bool = False # Its model type and config allow /v1/realtime
- thinking_default: bool | None = None # True if model thinks by default, False if not, None if unknown
- preserve_thinking_default: bool | None = None # True when template supports preserve_thinking (Qwen 3.6+)
+ supports_audio_input: bool | None = None
+ config_model_type: str = (
+ "" # Raw model_type from config.json (e.g., "deepseekocr_2")
+ )
+ thinking_default: bool | None = (
+ None # True if model thinks by default, False if not, None if unknown
+ )
+ preserve_thinking_default: bool | None = (
+ None # True when template supports preserve_thinking (Qwen 3.6+)
+ )
reasoning_efforts: list[str] | None = None # Template effort levels (None = no effort)
- model_context_length: int | None = None # Declared context length from config.json (None if unknown)
+ model_context_length: int | None = (
+ None # Declared context length from config.json (None if unknown)
+ )
+ reasoning_effort_options: list[str] = field(default_factory=list)
+ reasoning_effort_default: str | None = None
source_type: str = "local" # "local" or "hf_cache"
source_repo_id: str | None = None # HuggingFace repo id for cache-backed models
+ capabilities: list[str] = field(default_factory=list)
+ tasks: list[str] = field(default_factory=list)
+ image_metadata: dict[str, object] | None = None
is_helper: bool = False # Speculative-decoding drafter (dFlash/Assistant/MTP)
model_format: str | None = None # "gguf": served by an external engine only
source_path: str | None = None # The GGUF file a generated folder links to
@@ -454,6 +499,312 @@ class HfCacheEntry:
source_repo_id: str
+@dataclass
+class ImageModelManifest:
+ """Validated mlx-vlm image model manifest."""
+
+ backend: str
+ base_model: str
+ tasks: list[str]
+ metadata: dict[str, object]
+ model_path: str | None = None
+ estimated_size: int | None = None
+
+
+def _normalize_image_tasks(raw_task: object) -> list[str] | None:
+ """Normalize manifest task values to supported image capabilities."""
+ if raw_task is None:
+ return ["generation"]
+
+ raw_tasks: list[object]
+ if isinstance(raw_task, str):
+ raw_tasks = [raw_task]
+ elif isinstance(raw_task, list):
+ raw_tasks = raw_task
+ else:
+ return None
+
+ aliases = {
+ "generation": "generation",
+ "generate": "generation",
+ "text-to-image": "generation",
+ "txt2img": "generation",
+ "edit": "edit",
+ "editing": "edit",
+ "image-to-image": "edit",
+ "img2img": "edit",
+ "inpaint": "edit",
+ "inpainting": "edit",
+ }
+ normalized: set[str] = set()
+ for task in raw_tasks:
+ if not isinstance(task, str):
+ return None
+ key = task.strip().lower().replace("_", "-")
+ capability = aliases.get(key)
+ if capability is None:
+ return None
+ normalized.add(capability)
+
+ order = {"generation": 0, "edit": 1}
+ return sorted(normalized, key=lambda task: order[task])
+
+
+def _normalize_image_base_model(value: object) -> str:
+ return normalize_image_alias(value)
+
+
+def _validate_positive_int(value: object, field_name: str) -> int | None:
+ """Validate a positive integer-ish manifest value."""
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or value <= 0:
+ logger.warning(f"Invalid image manifest {field_name}: {value!r}")
+ return None
+ return int(value)
+
+
+def detect_image_tasks(model_path: Path) -> list[str]:
+ if _infer_qwen_image_metadata(model_path) is not None:
+ from .patches.mlx_vlm_qwen_image_compat import apply_qwen_image_compat_patch
+
+ apply_qwen_image_compat_patch()
+ try:
+ from mlx_vlm.generate.edit_image import is_image_edit_model
+ from mlx_vlm.generate.image import is_image_generation_model
+ except ImportError:
+ return []
+ path = str(model_path)
+ try:
+ tasks = []
+ if is_image_generation_model(path):
+ tasks.append("generation")
+ if is_image_edit_model(path):
+ tasks.append("edit")
+ return tasks
+ except Exception as exc:
+ logger.warning("Could not inspect image model at %s: %s", model_path, exc)
+ return []
+
+
+def _infer_image_manifest(model_path: Path) -> ImageModelManifest | None:
+ tasks = detect_image_tasks(model_path)
+ if not tasks:
+ return None
+ qwen_metadata = _infer_qwen_image_metadata(model_path)
+ spec = (
+ get_image_model_spec(str(qwen_metadata["base_model"]))
+ if qwen_metadata is not None
+ else infer_image_model_spec_from_name(model_path.name)
+ )
+ base_model = spec.base_model if spec is not None else model_path.name
+ if qwen_metadata is None:
+ try:
+ with (model_path / "model_index.json").open() as file:
+ index = json.load(file)
+ except (OSError, json.JSONDecodeError):
+ index = {}
+ qwen_pipeline = isinstance(index, dict) and (
+ str(index.get("_class_name", "")).startswith("QwenImage")
+ or index.get("transformer")
+ == ["diffusers", "QwenImage21Transformer2DModel"]
+ )
+ if qwen_pipeline:
+ return None
+ if spec and spec.base_model.startswith("qwen-image-"):
+ base_model = (
+ str(index.get("_class_name") or "mlx-vlm")
+ if isinstance(index, dict)
+ else "mlx-vlm"
+ )
+
+ metadata: dict[str, object] = {
+ "backend": "mlx-vlm",
+ "base_model": base_model,
+ "model_path": ".",
+ "tasks": tasks,
+ "capabilities": tasks,
+ "inferred": True,
+ }
+ if qwen_metadata is not None:
+ metadata.update(qwen_metadata)
+ return ImageModelManifest(
+ backend="mlx-vlm",
+ base_model=base_model,
+ tasks=tasks,
+ metadata=metadata,
+ model_path=".",
+ )
+
+
+def _infer_qwen_image_metadata(model_path: Path) -> dict[str, object] | None:
+ """Recognize Qwen 2.1 from component identity, including renamed folders."""
+ index_path = model_path / "model_index.json"
+ if not index_path.is_file():
+ return None
+ try:
+ with index_path.open() as file:
+ index = json.load(file)
+ if not isinstance(index, dict) or index.get("_class_name") != "QwenImage21Pipeline":
+ return None
+ with (model_path / "transformer" / "config.json").open() as file:
+ transformer = json.load(file)
+ if (
+ not isinstance(transformer, dict)
+ or transformer.get("_class_name") != "QwenImage21Transformer2DModel"
+ or index.get("transformer") != ["diffusers", "QwenImage21Transformer2DModel"]
+ or index.get("vae") != ["diffusers", "AutoencoderKLQwenImage21"]
+ ):
+ logger.warning("Invalid Qwen Image 2.1 component identity at %s", model_path)
+ return None
+ sigmas = index.get("sample_sigmas")
+ if sigmas is not None and (
+ not isinstance(sigmas, list)
+ or not sigmas
+ or any(
+ isinstance(value, bool)
+ or not isinstance(value, (int, float))
+ or not math.isfinite(value)
+ or not 0 < value <= 1
+ for value in sigmas
+ )
+ or any(left <= right for left, right in zip(sigmas, sigmas[1:]))
+ ):
+ logger.warning("Invalid Qwen Image 2.1 sample_sigmas at %s", index_path)
+ return None
+ except (OSError, json.JSONDecodeError) as exc:
+ logger.warning("Cannot read Qwen Image 2.1 config at %s: %s", model_path, exc)
+ return None
+
+ # Distinguish the official Turbo recipe without relying on a folder name.
+ turbo_sigmas = [1, 0.978453, 0.95418, 0.926626, 0.89508, 0.845148, 0.704534, 0.414568]
+ metadata: dict[str, object] = {
+ "base_model": (
+ "qwen-image-2-1-turbo" if sigmas == turbo_sigmas else "qwen-image-2-1"
+ ),
+ "default_guidance": 1.0,
+ "uses_checkpoint_sigmas": sigmas is not None,
+ }
+ if sigmas is not None:
+ metadata["default_steps"] = len(sigmas)
+ metadata["checkpoint_steps"] = len(sigmas)
+ return metadata
+
+
+def _load_image_manifest(model_path: Path) -> ImageModelManifest | None:
+ """Load and validate an mlx-vlm image manifest, or infer one if absent."""
+ manifest_path = model_path / IMAGE_MANIFEST_NAME
+ if not manifest_path.exists():
+ return _infer_image_manifest(model_path)
+
+ try:
+ with open(manifest_path) as f:
+ manifest = json.load(f)
+ except (json.JSONDecodeError, OSError) as e:
+ logger.warning(f"Invalid image manifest at {manifest_path}: {e}")
+ return None
+
+ if not isinstance(manifest, dict):
+ logger.warning(f"Invalid image manifest at {manifest_path}: expected object")
+ return None
+
+ backend = manifest.get("backend")
+ if not isinstance(backend, str) or backend.strip().lower() != "mlx-vlm":
+ logger.warning(
+ f"Invalid image manifest at {manifest_path}: backend must be 'mlx-vlm'"
+ )
+ return None
+
+ base_model = manifest.get("base_model")
+ if not isinstance(base_model, str) or not base_model.strip():
+ logger.warning(
+ f"Invalid image manifest at {manifest_path}: base_model must be a string"
+ )
+ return None
+
+ tasks = _normalize_image_tasks(manifest.get("task"))
+ if tasks is None:
+ logger.warning(f"Invalid image manifest at {manifest_path}: unsupported task")
+ return None
+
+ model_path_value = manifest.get("model_path")
+ if model_path_value is not None and (
+ not isinstance(model_path_value, str) or not model_path_value.strip()
+ ):
+ logger.warning(
+ f"Invalid image manifest at {manifest_path}: model_path must be a string"
+ )
+ return None
+
+ estimated_size = None
+ if "estimated_size" in manifest:
+ estimated_size = _validate_positive_int(
+ manifest["estimated_size"], "estimated_size"
+ )
+ if estimated_size is None:
+ return None
+
+ default_steps = manifest.get("default_steps")
+ if (
+ default_steps is not None
+ and _validate_positive_int(default_steps, "default_steps") is None
+ ):
+ return None
+
+ default_guidance = manifest.get("default_guidance")
+ if default_guidance is not None and (
+ isinstance(default_guidance, bool)
+ or not isinstance(default_guidance, (int, float))
+ ):
+ logger.warning(f"Invalid image manifest default_guidance: {default_guidance!r}")
+ return None
+
+ default_image_strength = manifest.get("default_image_strength")
+ if default_image_strength is not None and (
+ isinstance(default_image_strength, bool)
+ or not isinstance(default_image_strength, (int, float))
+ ):
+ logger.warning(
+ f"Invalid image manifest default_image_strength: {default_image_strength!r}"
+ )
+ return None
+
+ metadata_keys = (
+ "backend",
+ "base_model",
+ "model_path",
+ "quantize",
+ "default_steps",
+ "default_guidance",
+ "default_image_strength",
+ "estimated_size",
+ )
+ metadata = {key: manifest[key] for key in metadata_keys if key in manifest}
+ metadata["tasks"] = list(tasks)
+ metadata["capabilities"] = list(tasks)
+ metadata["manifest_path"] = str(manifest_path)
+ spec = get_image_model_spec(base_model)
+ if spec is not None and spec.base_model.startswith("qwen-image-2-1"):
+ local_path = Path(model_path_value).expanduser() if model_path_value else model_path
+ if model_path_value and not local_path.is_absolute():
+ local_path = model_path / local_path
+ qwen_metadata = _infer_qwen_image_metadata(local_path)
+ if qwen_metadata is not None:
+ metadata["uses_checkpoint_sigmas"] = qwen_metadata["uses_checkpoint_sigmas"]
+ if "checkpoint_steps" in qwen_metadata:
+ metadata["checkpoint_steps"] = qwen_metadata["checkpoint_steps"]
+ metadata.setdefault("default_steps", qwen_metadata["default_steps"])
+
+ return ImageModelManifest(
+ backend="mlx-vlm",
+ base_model=base_model.strip(),
+ tasks=tasks,
+ metadata=metadata,
+ model_path=(
+ model_path_value.strip() if isinstance(model_path_value, str) else None
+ ),
+ estimated_size=estimated_size,
+ )
+
+
def _is_unsupported_model(model_path: Path) -> bool:
"""
Check if model is an unsupported type that should be skipped during discovery.
@@ -472,17 +823,23 @@ def _is_unsupported_model(model_path: Path) -> bool:
try:
with open(config_path) as f:
config = json.load(f)
- except (json.JSONDecodeError, IOError):
+ except (json.JSONDecodeError, OSError):
return False
- architectures = config.get("architectures", [])
+ architectures = config.get("architectures") or []
+ if isinstance(architectures, str):
+ architectures = [architectures]
+ elif not isinstance(architectures, list | tuple | set):
+ architectures = []
for arch in architectures:
if arch in UNSUPPORTED_ARCHITECTURES:
return True
model_type = config.get("model_type", "")
normalized = model_type.lower().replace("-", "_")
- return normalized in UNSUPPORTED_MODEL_TYPES or model_type in UNSUPPORTED_MODEL_TYPES
+ return (
+ normalized in UNSUPPORTED_MODEL_TYPES or model_type in UNSUPPORTED_MODEL_TYPES
+ )
def _model_name_hint(model_path: Path) -> str:
@@ -503,7 +860,7 @@ def _model_name_hint(model_path: Path) -> str:
def _is_d3_decision_config(path: Path) -> bool:
try:
with open(path) as f:
- return json.load(f).get("format_id") == D3_FORMAT_ID
+ return bool(json.load(f).get("format_id") == D3_FORMAT_ID)
except (OSError, ValueError, AttributeError):
return False
@@ -587,16 +944,14 @@ def _has_sentence_transformers_embedding_pipeline(model_path: Path) -> bool:
try:
with open(modules_path) as f:
modules = json.load(f)
- except (json.JSONDecodeError, IOError):
+ except (json.JSONDecodeError, OSError):
return False
if not isinstance(modules, list):
return False
module_types = {
- module.get("type", "")
- for module in modules
- if isinstance(module, dict)
+ module.get("type", "") for module in modules if isinstance(module, dict)
}
if "sentence_transformers.models.Transformer" not in module_types:
return False
@@ -699,7 +1054,6 @@ def _has_vision_subconfig(config: dict) -> bool:
or bool(config.get("mm_vision_tower"))
)
-
def _architecture_indicates_causal_lm(architectures: list[str]) -> bool:
"""True when ``architectures`` describe a text causal LM (not mlx-audio STS).
@@ -715,15 +1069,16 @@ def detect_model_type(model_path: Path) -> ModelType:
Detect model type from config.json.
Checks:
- 1. architectures field for reranker-specific classes (SequenceClassification)
- 2. CausalLM-based reranker/embedding detection (architecture + directory name)
- 3. sentence-transformers pipeline detection via modules.json
- 4. architectures field for embedding-specific classes
- 5. model_type field against known embedding types (unambiguous only)
- 6. VLM detection via architectures, model_type, or vision sub-config
+ 1. mlx-vlm image manifest (omlx-image-model.json)
+ 2. architectures field for reranker-specific classes (SequenceClassification)
+ 3. CausalLM-based reranker/embedding detection (architecture + directory name)
+ 4. sentence-transformers pipeline detection via modules.json
+ 5. architectures field for embedding-specific classes
+ 6. model_type field against known embedding types (unambiguous only)
+ 7. VLM detection via architectures, model_type, or vision sub-config
presence (``vision_config`` / ``vit_config`` / non-empty
``mm_vision_tower`` — see :func:`_has_vision_subconfig`)
- 7. Audio model detection (STT/TTS/STS)
+ 8. Audio model detection (STT/TTS/STS)
Decision models (see :func:`decision_kind`) are checked first because
their backbones look like ordinary VLM checkpoints.
@@ -733,8 +1088,11 @@ def detect_model_type(model_path: Path) -> ModelType:
Returns:
Model type: "llm", "vlm", "embedding", "reranker", "audio_stt",
- "audio_tts", "audio_sts", or "decision"
+ "audio_tts", "audio_sts", "decision", or "image"
"""
+ if _load_image_manifest(model_path) is not None:
+ return "image"
+
config_path = model_path / "config.json"
if not config_path.exists():
return "llm"
@@ -742,14 +1100,18 @@ def detect_model_type(model_path: Path) -> ModelType:
try:
with open(config_path) as f:
config = json.load(f)
- except (json.JSONDecodeError, IOError):
+ except (json.JSONDecodeError, OSError):
return "llm"
if decision_kind(model_path, config) is not None:
return "decision"
# Check architectures field for reranker first (more specific)
- architectures = config.get("architectures", [])
+ architectures = config.get("architectures") or []
+ if isinstance(architectures, str):
+ architectures = [architectures]
+ elif not isinstance(architectures, list | tuple | set):
+ architectures = []
for arch in architectures:
if arch in RERANKER_ARCHITECTURES:
return "reranker"
@@ -758,26 +1120,32 @@ def detect_model_type(model_path: Path) -> ModelType:
# These use a standard CausalLM architecture but are fine-tuned for reranking
# via yes/no logit scoring. Detected by architecture + model directory name hint.
for arch in architectures:
- if arch in CAUSAL_LM_RERANKER_ARCHITECTURES:
- if _is_causal_lm_reranker(model_path):
- return "reranker"
+ if arch in CAUSAL_LM_RERANKER_ARCHITECTURES and _is_causal_lm_reranker(
+ model_path
+ ):
+ return "reranker"
# Check for CausalLM-based embeddings (e.g., Qwen3-Embedding).
# These use a standard CausalLM architecture but are fine-tuned for embeddings
# and ship without lm_head weights. Detected by architecture + directory name hint.
for arch in architectures:
- if arch in CAUSAL_LM_EMBEDDING_ARCHITECTURES:
- if _is_causal_lm_embedding(model_path):
- return "embedding"
+ if arch in CAUSAL_LM_EMBEDDING_ARCHITECTURES and _is_causal_lm_embedding(
+ model_path
+ ):
+ return "embedding"
# Check for multimodal (VLM-based) rerankers and embeddings.
# Same architecture string as VLM chat models; distinguished by the
# directory name heuristic. Must come before VLM detection below so
# the reranker/embedding hint wins over default VLM classification.
for arch in architectures:
- if arch in MULTIMODAL_RERANKER_ARCHITECTURES and _is_causal_lm_reranker(model_path):
+ if arch in MULTIMODAL_RERANKER_ARCHITECTURES and _is_causal_lm_reranker(
+ model_path
+ ):
return "reranker"
- if arch in MULTIMODAL_EMBEDDING_ARCHITECTURES and _is_causal_lm_embedding(model_path):
+ if arch in MULTIMODAL_EMBEDDING_ARCHITECTURES and _is_causal_lm_embedding(
+ model_path
+ ):
return "embedding"
if _has_sentence_transformers_embedding_pipeline(model_path):
@@ -827,10 +1195,8 @@ def detect_model_type(model_path: Path) -> ModelType:
return "llm"
if normalized_type in VLM_NATIVE_TEXT_MODEL_TYPES:
- logger.info(
- f"{model_type} detected as mlx-vlm native text model"
- )
- return "vlm"
+ logger.info(f"{model_type} detected as mlx-vlm native text model")
+ return "llm" if normalized_type in TEXT_ONLY_CHAT_MODEL_TYPES else "vlm"
# Check for VLM: architectures field
# Some text-only quants (e.g., unsloth/gemma-4-31b-it-MLX-8bit) keep the VLM
@@ -915,7 +1281,10 @@ def detect_model_type(model_path: Path) -> ModelType:
# mlx-audio LFM STS may use an "lfm*" model_type without a known architecture
# string yet. Liquid LFM *text* checkpoints share that prefix — disambiguate
# with CausalLM architecture names (LFM2 / LFM2.5 MoE, future lfm* LMs).
- if normalized_type.startswith("lfm") and normalized_type not in EMBEDDING_MODEL_TYPES:
+ if (
+ normalized_type.startswith("lfm")
+ and normalized_type not in EMBEDDING_MODEL_TYPES
+ ):
if _architecture_indicates_causal_lm(architectures):
return "llm"
return "audio_sts"
@@ -942,6 +1311,52 @@ def _read_chat_template_text(model_path: Path) -> str | None:
return None
+def detect_reasoning_effort_options(model_path: Path) -> tuple[list[str], str | None]:
+ """Read explicit effort enums from Qwen-style template validation guards.
+
+ Thinking alone does not imply adjustable effort. Only advertise literals
+ from a guard on the variable assigned from ``reasoning_effort|default``;
+ templates without this contract retain the conservative thinking control.
+ """
+ try:
+ template = (model_path / "chat_template.jinja").read_text(encoding="utf-8")
+ except OSError:
+ try:
+ config = json.loads(
+ (model_path / "tokenizer_config.json").read_text(encoding="utf-8")
+ )
+ template = config.get("chat_template") if isinstance(config, dict) else None
+ except (OSError, ValueError):
+ return [], None
+ if not isinstance(template, str):
+ return [], None
+ assignment = re.search(
+ r"set\s+(\w+)\s*=\s*reasoning_effort\s*\|\s*default\(\s*(['\"])(\w+)\2\s*\)",
+ template,
+ )
+ if assignment is None:
+ return [], None
+ variable, _, default = assignment.groups()
+ guard = re.search(
+ rf"if\s+{re.escape(variable)}\s+not\s+in\s+(\([^()]+\))",
+ template,
+ )
+ if guard is None:
+ return [], None
+ try:
+ options = ast.literal_eval(guard.group(1))
+ except (SyntaxError, ValueError):
+ return [], None
+ if (
+ not isinstance(options, tuple)
+ or not options
+ or not all(isinstance(option, str) for option in options)
+ or default not in options
+ ):
+ return [], None
+ return list(dict.fromkeys(options)), default
+
+
def detect_thinking_default(
model_path: Path, template_text: str | None = None
) -> bool | None:
@@ -1151,7 +1566,7 @@ def estimate_model_size(model_path: Path) -> int:
total_size = 0
# Primary: safetensors files
- safetensors_files = list(model_path.glob("*.safetensors"))
+ safetensors_files = select_safetensors_weight_files(model_path)
for f in safetensors_files:
total_size += f.stat().st_size
@@ -1178,6 +1593,63 @@ def estimate_model_size(model_path: Path) -> int:
return int(total_size * overhead_factor)
+def _resolve_image_model_path(
+ model_dir: Path, manifest: ImageModelManifest
+) -> Path | None:
+ """Resolve a manifest model_path relative to the image model directory."""
+ if manifest.model_path is None:
+ return None
+
+ local_path = Path(manifest.model_path).expanduser()
+ if not local_path.is_absolute():
+ local_path = model_dir / local_path
+ if local_path.exists():
+ return local_path
+ return None
+
+
+def _sum_file_tree_size(path: Path) -> int:
+ """Best-effort size estimate for a file or directory tree."""
+ if path.is_file():
+ return path.stat().st_size
+
+ total = 0
+ for child in path.rglob("*"):
+ if not child.is_file():
+ continue
+ with contextlib.suppress(OSError):
+ total += child.stat().st_size
+ return total
+
+
+def estimate_image_model_size(model_dir: Path, manifest: ImageModelManifest) -> int:
+ """Estimate image model size without importing or loading mlx-vlm."""
+ if manifest.estimated_size is not None:
+ return manifest.estimated_size
+
+ local_path = _resolve_image_model_path(model_dir, manifest)
+ if local_path is not None:
+ if local_path.is_dir():
+ with contextlib.suppress(ValueError, OSError):
+ return estimate_model_size(local_path)
+
+ with contextlib.suppress(OSError):
+ total_size = _sum_file_tree_size(local_path)
+ if total_size > 0:
+ return int(total_size * 1.05)
+
+ base_model = _normalize_image_base_model(manifest.base_model)
+ fallback_size = IMAGE_DEFAULT_ESTIMATED_SIZES.get(
+ base_model, IMAGE_UNKNOWN_FALLBACK_SIZE
+ )
+ if base_model not in IMAGE_DEFAULT_ESTIMATED_SIZES:
+ logger.warning(
+ "Using conservative image model size fallback for unknown base_model %r",
+ manifest.base_model,
+ )
+ return fallback_size
+
+
# Weight-name prefixes that the text-only (mlx-lm) loaders drop when serving a
# VLM-shaped checkpoint: qwen3_5(_moe) sanitize strips ``vision_tower.*`` and
# ``model.visual.*``; the projector/vision-model spellings cover the other
@@ -1276,8 +1748,11 @@ def _register_adapter(adapters: dict[str, str], path: Path, adapter_id: str) ->
def _is_model_dir(path: Path) -> bool:
- """Check if a directory contains a valid model (has config.json)."""
- return (path / "config.json").exists() and not _is_adapter_dir(path)
+ """Check if a directory contains a valid model manifest or config.json."""
+ return (
+ _load_image_manifest(path) is not None
+ or (path / "config.json").exists()
+ ) and not _is_adapter_dir(path)
_SHARD_FILE_RE = re.compile(r"-(\d+)-of-(\d+)\.safetensors$")
@@ -1425,10 +1900,7 @@ def model_directory_access_error(path: Path) -> str | None:
return f"Model directory is not a directory: {path}"
next(path.iterdir(), None)
except OSError as e:
- return (
- f"Model directory is not readable: {path} "
- f"({type(e).__name__}: {e})"
- )
+ return f"Model directory is not readable: {path} " f"({type(e).__name__}: {e})"
return None
@@ -1443,10 +1915,7 @@ def model_directory_write_error(path: Path, *, create: bool = False) -> str | No
if not path.is_dir():
return f"Model directory is not a directory: {path}"
except OSError as e:
- return (
- f"Model directory is not writable: {path} "
- f"({type(e).__name__}: {e})"
- )
+ return f"Model directory is not writable: {path} " f"({type(e).__name__}: {e})"
access_error = model_directory_access_error(path)
if access_error is not None:
@@ -1461,10 +1930,7 @@ def model_directory_write_error(path: Path, *, create: bool = False) -> str | No
f.write(b"")
f.flush()
except OSError as e:
- return (
- f"Model directory is not writable: {path} "
- f"({type(e).__name__}: {e})"
- )
+ return f"Model directory is not writable: {path} " f"({type(e).__name__}: {e})"
return None
@@ -1504,7 +1970,7 @@ def _decode_hf_cache_model_id(path: Path) -> tuple[str, str] | None:
if not name.startswith("models--"):
return None
- encoded = name[len("models--"):]
+ encoded = name[len("models--") :]
if not encoded:
return None
@@ -1573,7 +2039,9 @@ def _safetensors_has_mlx_metadata(path: Path) -> bool:
logger.debug(f"safetensors import failed while checking {path}: {e}")
return False
- for shard in sorted(path.glob("model*.safetensors")):
+ for shard in select_safetensors_weight_files(path):
+ if not shard.name.startswith("model"):
+ continue
try:
with safe_open(str(shard), framework="numpy") as f:
metadata = f.metadata() or {}
@@ -1653,6 +2121,8 @@ def _is_hf_cache_mlx_compatible(model_dir: Path, source_repo_id: str) -> bool:
"""Heuristic for HF cache entries that can be loaded without conversion."""
if not _is_model_dir(model_dir):
return False
+ if _load_image_manifest(model_dir) is not None:
+ return True
try:
config = json.loads((model_dir / "config.json").read_text())
except (OSError, ValueError):
@@ -1670,8 +2140,14 @@ def _is_hf_cache_mlx_compatible(model_dir: Path, source_repo_id: str) -> bool:
except (OSError, ValueError, TypeError, KeyError) as error:
logger.debug("Invalid K2 cache checkpoint %s: %s", source_repo_id, error)
return False
- if not list(model_dir.glob("model*.safetensors")):
- logger.debug(f"Skipping HF cache model without model*.safetensors: {source_repo_id}")
+ if not [
+ path
+ for path in select_safetensors_weight_files(model_dir)
+ if path.name.startswith("model")
+ ]:
+ logger.debug(
+ f"Skipping HF cache model without model*.safetensors: {source_repo_id}"
+ )
return False
if _is_deepseek_v41_loadable_config(config):
logger.info(
@@ -1727,6 +2203,79 @@ def _gemma4_text_only_prefers_llm_engine(config: dict) -> bool:
return not _has_merged_mtp_head(config)
+def _detect_audio_input(
+ model_dir: Path, config: dict, model_type: ModelType
+) -> bool | None:
+ """Inspect known audio-input weight layouts without loading tensors."""
+ if model_type != "vlm":
+ return False if model_type == "llm" else None
+
+ import safetensors
+
+ family = config.get("model_type")
+ if family == "gemma4" and config.get("audio_config") is None:
+ return False
+ if family == "gemma4_unified" and config.get("audio_config", {}) is None:
+ return False
+ prefixes: tuple[str, ...] = (
+ "audio_tower.", "embed_audio.", "audio_encoder.", "thinker.audio_tower."
+ )
+ if family in ("inkling", "inkling_mm_model"):
+ prefixes += ("audio.",)
+ elif family == "lfm3_audio":
+ prefixes += ("encoder.",)
+ elif family == "minicpmo":
+ if config.get("init_audio") is False:
+ return False
+ prefixes += ("apm.",)
+
+ files = select_safetensors_weight_files(model_dir)
+ sidecar = model_dir / "omnimodal" / "audio_encoder.safetensors"
+ if sidecar.is_file():
+ files.append(sidecar)
+ optiq = config.get("optiq_vision")
+ if (
+ isinstance(optiq, dict)
+ and isinstance(optiq.get("sidecar"), str)
+ and optiq["sidecar"]
+ ):
+ try:
+ sidecar = (model_dir / optiq["sidecar"]).resolve()
+ valid = (
+ sidecar.is_relative_to(model_dir.resolve())
+ and sidecar.suffix == ".safetensors"
+ )
+ except (OSError, RuntimeError) as exc:
+ logger.warning("Cannot resolve audio input sidecar in %s: %s", model_dir, exc)
+ return None
+ if not valid:
+ logger.warning(
+ "Cannot inspect audio input: invalid OptiQ sidecar in %s", model_dir
+ )
+ return None
+ if sidecar not in files:
+ files.append(sidecar)
+ if not files:
+ return None
+
+ incomplete = False
+ for path in files:
+ try:
+ with safetensors.safe_open(str(path), framework="np") as weights:
+ if any(
+ key.removeprefix("model.").startswith(prefixes)
+ for key in weights.keys() # noqa: SIM118
+ ):
+ return True
+ except (OSError, safetensors.SafetensorError) as exc:
+ logger.warning("Cannot inspect audio input weights in %s: %s", path, exc)
+ incomplete = True
+ # These Gemma loaders strip orphaned audio config when its weights are absent.
+ if not incomplete and family in ("gemma4", "gemma4_unified"):
+ return False
+ return None
+
+
def _register_model(
models: dict[str, DiscoveredModel],
model_dir: Path,
@@ -1743,7 +2292,9 @@ def _register_model(
)
return
try:
- if _is_unsupported_model(model_dir):
+ payload_dir = model_dir
+ engine_type: EngineType
+ if _is_unsupported_model(payload_dir):
logger.info(f"Skipping unsupported model: {model_id}")
return
@@ -1759,9 +2310,54 @@ def _register_model(
)
return
- model_type = detect_model_type(model_dir)
+ _config: dict = {}
+ image_manifest = _load_image_manifest(model_dir)
+ if image_manifest is not None:
+ model_type: ModelType = "image"
+ engine_type = "image"
+ estimated_size = estimate_image_model_size(model_dir, image_manifest)
+ config_model_type = image_manifest.backend
+ reasoning_effort_options, reasoning_effort_default = [], None
+ reasoning_efforts = None
+ thinking_default = None
+ preserve_thinking_default = None
+ capabilities = list(image_manifest.tasks)
+ tasks = list(image_manifest.tasks)
+ image_metadata = dict(image_manifest.metadata)
+ model_context_length = None
+ is_helper = False
+ else:
+ model_type = detect_model_type(model_dir)
+ estimated_size = estimate_model_size(model_dir)
+
+ # Read raw config model_type for sub-type detection (e.g., OCR models)
+ # and flag speculative-decoding drafters (dFlash/Assistant/MTP).
+ config_model_type = ""
+ is_helper = False
+ try:
+ with open(payload_dir / "config.json") as f:
+ loaded = json.load(f)
+ if isinstance(loaded, dict):
+ _config = loaded
+ config_model_type = _config.get("model_type", "")
+ is_helper = is_helper_model_config(_config)
+ except (OSError, ValueError):
+ pass
+
+ reasoning_effort_options, reasoning_effort_default = (
+ detect_reasoning_effort_options(payload_dir)
+ )
+ template_text = _read_chat_template_text(payload_dir)
+ thinking_default = detect_thinking_default(payload_dir, template_text)
+ preserve_thinking_default = detect_preserve_thinking(payload_dir, template_text)
+ reasoning_efforts = detect_reasoning_effort(payload_dir, template_text)
+ model_context_length = _read_model_context_length(payload_dir)
+ capabilities = []
+ tasks = []
+ image_metadata = None
+
if model_type == "embedding":
- engine_type: EngineType = "embedding"
+ engine_type = "embedding"
elif model_type == "reranker":
engine_type = "reranker"
elif model_type == "vlm":
@@ -1774,32 +2370,22 @@ def _register_model(
engine_type = "audio_sts"
elif model_type == "decision":
engine_type = "decision"
+ elif model_type == "image":
+ engine_type = "image"
else:
engine_type = "batched"
- estimated_size = estimate_model_size(model_dir)
text_only_size = (
estimate_text_only_model_size(model_dir) if model_type == "vlm" else 0
)
- # Read raw config model_type for sub-type detection (e.g., OCR models)
- # and flag speculative-decoding drafters (dFlash/Assistant/MTP).
- config_model_type = ""
- is_helper = False
- # The routing below reads this even when config.json does not parse.
- _config: dict = {}
- try:
- import json
- with open(model_dir / "config.json") as f:
- loaded = json.load(f)
- if isinstance(loaded, dict):
- _config = loaded
- config_model_type = _config.get("model_type", "")
- is_helper = is_helper_model_config(_config)
- except Exception:
- pass
-
+ if (
+ model_type == "llm"
+ and config_model_type.lower().replace("-", "_")
+ in VLM_NATIVE_TEXT_MODEL_TYPES
+ ):
+ engine_type = "vlm"
# Keep text-only capability metadata when selecting the VLM MTP engine.
- if model_type == "llm" and _gemma4_text_only_wants_vlm_engine(_config):
+ elif model_type == "llm" and _gemma4_text_only_wants_vlm_engine(_config):
engine_type = "vlm"
logger.info(
"%s is text-only Gemma 4 with a merged MTP head; serving it "
@@ -1817,12 +2403,6 @@ def _register_model(
model_id,
)
- template_text = _read_chat_template_text(model_dir)
- thinking_default = detect_thinking_default(model_dir, template_text)
- preserve_thinking_default = detect_preserve_thinking(model_dir, template_text)
- reasoning_efforts = detect_reasoning_effort(model_dir, template_text)
- model_context_length = _read_model_context_length(model_dir)
-
models[model_id] = DiscoveredModel(
model_id=model_id,
model_path=str(model_dir),
@@ -1832,12 +2412,18 @@ def _register_model(
text_only_size=text_only_size,
config_model_type=config_model_type,
realtime_voice=is_realtime_voice_model(config_model_type, _config),
+ supports_audio_input=_detect_audio_input(model_dir, _config, model_type),
+ reasoning_effort_options=reasoning_effort_options,
+ reasoning_effort_default=reasoning_effort_default,
thinking_default=thinking_default,
preserve_thinking_default=preserve_thinking_default,
reasoning_efforts=reasoning_efforts,
model_context_length=model_context_length,
source_type=source_type,
source_repo_id=source_repo_id,
+ capabilities=capabilities,
+ tasks=tasks,
+ image_metadata=image_metadata,
is_helper=is_helper,
)
@@ -2117,10 +2703,9 @@ def discover_models(
# Level 2: organization folder — scan children
has_children = False
for child in _iter_readable_entries(subdir, "model group"):
- if (
- not _is_readable_dir(child, "model group entry")
- or child.name.startswith(".")
- ):
+ if not _is_readable_dir(
+ child, "model group entry"
+ ) or child.name.startswith("."):
continue
if _is_adapter_dir(child):
has_children = True
@@ -2196,8 +2781,9 @@ def discover_models_from_dirs(
def format_size(size_bytes: int) -> str:
"""Format byte size as human-readable string."""
+ size = float(size_bytes)
for unit in ["B", "KB", "MB", "GB", "TB"]:
- if abs(size_bytes) < 1024.0:
- return f"{size_bytes:.2f}{unit}"
- size_bytes /= 1024.0
- return f"{size_bytes:.2f}PB"
+ if abs(size) < 1024.0:
+ return f"{size:.2f}{unit}"
+ size /= 1024.0
+ return f"{size:.2f}PB"
diff --git a/omlx/model_profiles.py b/omlx/model_profiles.py
index 887ffd0d84..a52bf98cd5 100644
--- a/omlx/model_profiles.py
+++ b/omlx/model_profiles.py
@@ -44,6 +44,7 @@
# Model-specific fields — eligible for per-model profiles only (never templates).
MODEL_SPECIFIC_PROFILE_FIELDS = (
+ "mm_processor_kwargs",
"turboquant_kv_enabled",
"turboquant_kv_scheme",
"turboquant_kv_bits",
@@ -266,7 +267,7 @@ def from_dict(cls, data: dict) -> "GlobalTemplate":
def utcnow() -> datetime:
"""Return current UTC time (single-source helper for testability)."""
- return datetime.now(timezone.utc)
+ return datetime.now(timezone.utc) # noqa: UP017
class InvalidProfileNameError(ValueError):
diff --git a/omlx/model_settings.py b/omlx/model_settings.py
index cb5c47fc8b..8310d3ac72 100644
--- a/omlx/model_settings.py
+++ b/omlx/model_settings.py
@@ -12,10 +12,12 @@
import os
import tempfile
import threading
-from dataclasses import dataclass, field, fields
+from collections.abc import Callable
+from dataclasses import dataclass, fields
from pathlib import Path
-from typing import Any, Callable, Dict, Optional
+from typing import Any
+from .api.media_options import MultimodalProcessorOptions
from .model_profiles import (
MODEL_SPECIFIC_PROFILE_FIELDS,
RENAMED_FIELDS,
@@ -25,8 +27,8 @@
normalize_turboquant_kv_bits,
rename_legacy_fields,
slugify_profile_api_name,
- validate_profile_name,
utcnow,
+ validate_profile_name,
)
logger = logging.getLogger(__name__)
@@ -115,6 +117,40 @@ def validate_moe_expert_offload(settings: dict, model_type: str | None = None) -
)
+def validate_minicpm_speculation(settings: dict, model_type: str | None) -> None:
+ if model_type != "minicpmv4_7":
+ return
+ if settings.get("mtp_enabled") or settings.get("vlm_mtp_enabled"):
+ raise ValueError(
+ "MiniCPM-V 4.7 has no embedded MTP head; use its paired DSpark "
+ "helper through dflash_enabled."
+ )
+ if not settings.get("dflash_enabled"):
+ return
+ if not settings.get("dflash_draft_model"):
+ raise ValueError("MiniCPM DSpark requires an explicit local paired helper.")
+ if settings.get("dflash_verify_mode") not in (None, "dflash"):
+ raise ValueError("MiniCPM DSpark supports fixed verification, not adaptive modes.")
+ unsupported = [
+ name
+ for name, default in (
+ ("dflash_max_ctx", None),
+ ("dflash_draft_window_size", None),
+ ("dflash_draft_sink_size", 0),
+ ("dflash_ssd_cache", False),
+ ("mtp_adaptive_max_depth", None),
+ ("mtp_fixed_depth", None),
+ ("specprefill_enabled", False),
+ ("guided_grammar_enabled", False),
+ )
+ if settings.get(name, default) not in (None, default)
+ ]
+ if unsupported:
+ raise ValueError(
+ "MiniCPM DSpark does not support these controls: " + ", ".join(unsupported)
+ )
+
+
def ane_prefill_backend(model_type: str | None) -> str | None:
"""Select the ANE implementation from model metadata."""
model_type = (model_type or "").lower().replace("-", "_")
@@ -326,7 +362,7 @@ class ModelSettings:
forced_ct_kwargs: Keys in chat_template_kwargs that cannot be overridden.
ttl_seconds: Auto-unload after idle seconds (None = no TTL).
model_type_override: "llm", "vlm", "embedding", "reranker", "decision",
- or None (auto-detect).
+ "audio_stt", "audio_tts", "audio_sts", "image", or None (auto-detect).
model_alias: API-visible alternative to the directory name.
index_cache_freq: IndexCache: every Nth layer keeps indexer (DeepSeek DSA
only; GLM-5.2 uses its native checkpoint schedule).
@@ -417,11 +453,10 @@ class ModelSettings:
acceptance; "dflash" and "off" verify the whole block. A stored
"ddtree" from older versions loads as "adaptive".
mtp_enabled: Enable native multi-token prediction (mlx-lm PR 990 / PR 15 monkey-patch).
- When True, BatchGenerator uses MTP draft+verify for singleton decode and
- for multi-row decode batches whose cache positions are aligned. Unaligned
- continuous batches fall back to standard decoding automatically. Compatible
- model_types: qwen3_5*, qwen3_6*, deepseek_v4*. Mutually exclusive with
- dflash_enabled.
+ When True, BatchGenerator uses MTP draft+verify for singleton decode.
+ Multi-row requests use standard batched decoding. Compatible model_types
+ include qwen3_5*, qwen3_6*, deepseek_v4*, GLM-5.2, Gemma 4, Inkling,
+ Nemotron-H, and Step-3.7. Mutually exclusive with dflash_enabled.
vlm_mtp_enabled: Enable VLM MTP speculative decoding via an external assistant
drafter (mlx-vlm 191d7c8+). Target = Gemma4 VLM body, drafter must be a
"gemma4_assistant" model. Mutually exclusive with processor-backed
@@ -438,31 +473,32 @@ class ModelSettings:
"""
# Sampling parameters (None means use global default)
- max_context_window: Optional[int] = None
- max_tokens: Optional[int] = None
- temperature: Optional[float] = None
- top_p: Optional[float] = None
- top_k: Optional[int] = None
- repetition_penalty: Optional[float] = None
- min_p: Optional[float] = None
- presence_penalty: Optional[float] = None
+ max_context_window: int | None = None
+ max_tokens: int | None = None
+ temperature: float | None = None
+ top_p: float | None = None
+ top_k: int | None = None
+ repetition_penalty: float | None = None
+ min_p: float | None = None
+ presence_penalty: float | None = None
force_sampling: bool = False
- max_tool_result_tokens: Optional[int] = None
- chat_template_kwargs: Optional[Dict[str, Any]] = None
- forced_ct_kwargs: Optional[list[str]] = (
+ max_tool_result_tokens: int | None = None
+ chat_template_kwargs: dict[str, Any] | None = None
+ mm_processor_kwargs: dict[str, str | int] | None = None
+ forced_ct_kwargs: list[str] | None = (
None # Keys that cannot be overridden by API requests
)
- ttl_seconds: Optional[int] = None # Auto-unload after idle seconds (None = no TTL)
- model_type_override: Optional[str] = (
- None # "llm", "vlm", "embedding", "reranker", "decision", or None (auto)
+ ttl_seconds: int | None = None # Auto-unload after idle seconds (None = no TTL)
+ model_type_override: str | None = (
+ None # "llm", "vlm", "embedding", "reranker", "decision", "audio_*", "image"
)
- model_alias: Optional[str] = (
+ model_alias: str | None = (
None # API-visible name (alternative to directory name)
)
- index_cache_freq: Optional[int] = (
+ index_cache_freq: int | None = (
None # IndexCache: every Nth layer keeps indexer (DeepSeek DSA only)
)
- enable_thinking: Optional[bool] = (
+ enable_thinking: bool | None = (
None # Explicit toggle for thinking/reasoning mode (None = auto)
)
# Qwen4-Exp only: keep the large PLE N-gram table on SSD and gather rows
@@ -477,30 +513,30 @@ class ModelSettings:
# last window-size tokens; decoder global KV is the encoder-final
# projection already produced by the midpoint CSA2 layer.
# None (never saved) means on; only a saved False turns it off.
- deepseek_v41_ced_prefill_enabled: Optional[bool] = None
+ deepseek_v41_ced_prefill_enabled: bool | None = None
# Prefill Accelerator: the paired Mac (cluster node id) that runs the
# first layers of each prompt chunk, and how many (None picks them from
# measured speed). Applied without reloading the model.
- prefill_helper_node_id: Optional[str] = None
- prefill_helper_layers: Optional[int] = None
+ prefill_helper_node_id: str | None = None
+ prefill_helper_layers: int | None = None
# Recast the checkpoint's bfloat16 leaves (scales, norms, embeddings) to
# float16 after load, so the forward runs on the GPU's native float16 path
# instead of the emulated bfloat16 one. Quantized payloads are untouched.
activation_fp16_enabled: bool = False
- preserve_thinking: Optional[bool] = (
+ preserve_thinking: bool | None = (
None # Keep blocks in historical turns (None = auto, True when template supports it)
)
- cache_reasoning_output: Optional[bool] = (
+ cache_reasoning_output: bool | None = (
None # Cache output for the next turn (None = auto: when history keeps it)
)
thinking_budget_enabled: bool = False
- thinking_budget_tokens: Optional[int] = None
- gpu_power_limit_w: Optional[int] = None
- reasoning_parser: Optional[str] = (
+ thinking_budget_tokens: int | None = None
+ gpu_power_limit_w: int | None = None
+ reasoning_parser: str | None = (
None # xgrammar builtin name: "qwen", "harmony", "llama", etc.
)
guided_grammar_enabled: bool = False
- guided_grammar: Optional[str] = None
+ guided_grammar: str | None = None
# KV cache compression
turboquant_kv_enabled: bool = False
@@ -517,7 +553,7 @@ class ModelSettings:
qwen35_ane_prefill_enabled: bool = False
qwen35_ane_prefill_sequence_length: int = 2048
qwen35_ane_prefill_tail_padding_min_tokens: int = 0
- qwen35_ane_prefill_fraction: Optional[float] = None # Backend default
+ qwen35_ane_prefill_fraction: float | None = None # Backend default
qwen35_ane_prefill_shared_fraction: float = 1.0
qwen35_ane_prefill_fused_down: bool = False
qwen35_ane_prefill_max_layers: int = 64
@@ -545,7 +581,7 @@ class ModelSettings:
# projection costs no extra weight memory and the module's arrays stay
# readable by the decode path.
# None (never saved) means off.
- a8_prefill_enabled: Optional[bool] = None
+ a8_prefill_enabled: bool | None = None
a8_prefill_min_tokens: int = 128
# MoE expert offload (stream non-resident experts from the checkpoint)
@@ -554,22 +590,22 @@ class ModelSettings:
# SpecPrefill (experimental: attention-based sparse prefill for MoE models)
specprefill_enabled: bool = False
- specprefill_draft_model: Optional[str] = (
+ specprefill_draft_model: str | None = (
None # Path to draft model (must share tokenizer)
)
- specprefill_keep_pct: Optional[float] = None # Keep rate (0.1-0.5, default 0.2)
- specprefill_threshold: Optional[int] = None # Min tokens to trigger (default 8192)
+ specprefill_keep_pct: float | None = None # Keep rate (0.1-0.5, default 0.2)
+ specprefill_threshold: int | None = None # Min tokens to trigger (default 8192)
# DFlash (block diffusion speculative decoding)
dflash_enabled: bool = False
- dflash_draft_model: Optional[str] = None # Path/repo for DFlash draft checkpoint
- dflash_draft_quant_enabled: Optional[bool] = None
- dflash_draft_quant_weight_bits: Optional[int] = None # 2, 4, 8
- dflash_draft_quant_group_size: Optional[int] = None # 32, 64, 128
+ dflash_draft_model: str | None = None # Path/repo for DFlash draft checkpoint
+ dflash_draft_quant_enabled: bool | None = None
+ dflash_draft_quant_weight_bits: int | None = None # 2, 4, 8
+ dflash_draft_quant_group_size: int | None = None # 32, 64, 128
# None uses the draft checkpoint's sliding_window.
- dflash_draft_window_size: Optional[int] = None
- dflash_block_size: Optional[int] = None
- dflash_verify_mode: Optional[str] = None # "adaptive" | "dflash" | "off"
+ dflash_draft_window_size: int | None = None
+ dflash_block_size: int | None = None
+ dflash_verify_mode: str | None = None # "adaptive" | "dflash" | "off"
# Lightning MTP uses the embedded head for single and concurrent requests.
# Equal-depth rows share target verification when supported by the backbone;
@@ -577,14 +613,13 @@ class ModelSettings:
# Mutually exclusive with DFlash.
mtp_enabled: bool = False
# Maximum chained MTP draft tokens per verify cycle (speculative depth).
- # Qwen 27B enforces a minimum adaptive ceiling of 4.
- # None = model-specific default (4 for dense Qwen3.5-family on M5, else 3
- # for DeepSeek-V4 and Qwen3.5/3.6). An adaptive controller picks 1..max
- # per sequence from rolling acceptance/latency estimates.
- mtp_adaptive_max_depth: Optional[int] = None
+ # None = model-specific default (including the Qwen MTP sidecar contract);
+ # Qwen 27B keeps an adaptive ceiling of at least 4.
+ # An adaptive controller picks 1..max per sequence.
+ mtp_adaptive_max_depth: int | None = None
# Draft exactly this many tokens every cycle, with no adaptive controller.
# Takes precedence over mtp_adaptive_max_depth; None = adaptive.
- mtp_fixed_depth: Optional[int] = None
+ mtp_fixed_depth: int | None = None
# VLM MTP speculative decoding via external MTP drafter (mlx-vlm f96138e+).
# Supported drafter types: gemma4_assistant (for Gemma 4 VLMs), qwen3_5_mtp
@@ -594,10 +629,10 @@ class ModelSettings:
# processor-backed settings (guided grammar, thinking budget, penalties)
# — see vlm_mtp_processor_conflicts().
vlm_mtp_enabled: bool = False
- vlm_mtp_draft_model: Optional[str] = (
+ vlm_mtp_draft_model: str | None = (
None # Path / model id of the assistant drafter
)
- vlm_mtp_draft_block_size: Optional[int] = (
+ vlm_mtp_draft_block_size: int | None = (
None # Tokens per draft round (None = mlx-vlm default)
)
@@ -613,9 +648,9 @@ class ModelSettings:
# External engine serving this model instead of oMLX's MLX engines
# (omlx/engine/splash.py). None runs the model in-process.
- external_engine: Optional[str] = None
+ external_engine: str | None = None
- # Security: opt-in per model. When True, mlx-lm/mlx-vlm/mlx-embeddings/reranker
+ # Security: opt-in per model. When True, mlx-lm/mlx-vlm/reranker
# loaders are allowed to execute custom Python from the model repository
# (modeling_*.py, tokenization_*.py). Off by default — see issue #926.
trust_remote_code: bool = False
@@ -628,14 +663,18 @@ class ModelSettings:
# the waveform. None keeps the processor default (Gemma 4 audio: 30 s).
# The model's context still bounds it: EmbeddingGemma 2 fits about 327 s
# (8192 tokens at 40 ms each); longer inputs get the token-limit error.
- embedding_audio_max_seconds: Optional[float] = None
+ embedding_audio_max_seconds: float | None = None
# Metadata
- display_name: Optional[str] = None
- description: Optional[str] = None
- active_profile_name: Optional[str] = None # Name of the currently-applied profile
+ display_name: str | None = None
+ description: str | None = None
+ active_profile_name: str | None = None # Name of the currently-applied profile
def __post_init__(self) -> None:
+ if self.mm_processor_kwargs is not None:
+ self.mm_processor_kwargs = MultimodalProcessorOptions.model_validate(
+ self.mm_processor_kwargs
+ ).model_dump(exclude_none=True)
# Profiles retain raw JSON types; engine signatures use repr().
self.turboquant_kv_bits = normalize_turboquant_kv_bits(self.turboquant_kv_bits)
# The ddtree verify mode was removed; stored settings run as adaptive.
@@ -766,9 +805,9 @@ def __init__(self, base_path: Path):
self.profiles_file = self.base_path / "model_profiles.json"
self.templates_file = self.base_path / "global_templates.json"
self._lock = threading.Lock()
- self._settings: Dict[str, ModelSettings] = {}
- self._profiles: Dict[str, Dict[str, Dict[str, Any]]] = {}
- self._templates: Dict[str, Dict[str, Any]] = {}
+ self._settings: dict[str, ModelSettings] = {}
+ self._profiles: dict[str, dict[str, dict[str, Any]]] = {}
+ self._templates: dict[str, dict[str, Any]] = {}
# Ensure base directory exists
self.base_path.mkdir(parents=True, exist_ok=True)
@@ -902,7 +941,7 @@ def _load(self) -> None:
return
try:
- with open(self.settings_file, "r", encoding="utf-8") as f:
+ with open(self.settings_file, encoding="utf-8") as f:
data = json.load(f)
# Check version
@@ -1064,7 +1103,7 @@ def add_initial_settings(self, initial: dict[str, dict[str, Any]]) -> list[str]:
def get_settings_for_request(
self,
model_id: str,
- resolved_model_id: Optional[str] = None,
+ resolved_model_id: str | None = None,
) -> ModelSettings:
"""Get settings for an API-requested model name.
@@ -1141,7 +1180,7 @@ def delete_settings(self, model_id: str) -> bool:
logger.info(f"Deleted settings for model '{model_id}'")
return removed
- def get_default_model_id(self) -> Optional[str]:
+ def get_default_model_id(self) -> str | None:
"""Get the ID of the default model.
Returns:
@@ -1166,7 +1205,7 @@ def get_pinned_model_ids(self) -> list[str]:
if settings.is_pinned
]
- def get_all_settings(self) -> Dict[str, ModelSettings]:
+ def get_all_settings(self) -> dict[str, ModelSettings]:
"""Get a copy of all model settings.
Returns:
@@ -1185,7 +1224,7 @@ def _load_profiles(self) -> None:
self._profiles = {}
return
try:
- with open(self.profiles_file, "r", encoding="utf-8") as f:
+ with open(self.profiles_file, encoding="utf-8") as f:
data = json.load(f)
version = data.get("version", 1)
if version != PROFILES_VERSION:
@@ -1286,14 +1325,14 @@ def _dedupe_profile_api_name(base: str, used: set[str]) -> str:
return candidate
@staticmethod
- def _profile_api_name(profile: Dict[str, Any]) -> str:
+ def _profile_api_name(profile: dict[str, Any]) -> str:
api_name = profile.get("api_name") or profile["name"]
validate_profile_name(api_name)
return api_name
def _allocate_profile_api_name_locked(
self,
- profiles: Dict[str, Dict[str, Any]],
+ profiles: dict[str, dict[str, Any]],
value: str | None,
*,
display_name: str | None,
@@ -1319,7 +1358,7 @@ def _profile_model_id(self, model_id: str, api_name: str) -> str:
return f"{model_id}:{api_name}"
def _display_profile_model_id_locked(
- self, model_id: str, profile: Dict[str, Any]
+ self, model_id: str, profile: dict[str, Any]
) -> str:
"""Advertised form of an exposed profile's model ID.
@@ -1334,7 +1373,7 @@ def _display_profile_model_id_locked(
def _find_exposed_profile_locked(
self, model_id: str
- ) -> Optional[tuple[str, Dict[str, Any]]]:
+ ) -> tuple[str, dict[str, Any]] | None:
for base_model_id, profiles in self._profiles.items():
base = self._settings.get(base_model_id)
alias = base.model_alias if base else None
@@ -1349,7 +1388,7 @@ def _find_exposed_profile_locked(
return None
def _settings_with_profile_locked(
- self, model_id: str, profile: Dict[str, Any]
+ self, model_id: str, profile: dict[str, Any]
) -> ModelSettings:
base = self._settings.get(model_id)
merged = base.to_dict() if base is not None else {}
@@ -1366,7 +1405,7 @@ def _settings_with_profile_locked(
return ModelSettings.from_dict(merged)
def _runtime_settings_with_profile_locked(
- self, model_id: str, profile: Dict[str, Any]
+ self, model_id: str, profile: dict[str, Any]
) -> ModelSettings:
base = self._settings.get(model_id)
merged = base.to_dict() if base is not None else {}
@@ -1376,7 +1415,7 @@ def _runtime_settings_with_profile_locked(
merged, _ = resolve_lora_conflicts(merged)
return ModelSettings.from_dict(merged)
- def get_exposed_profile_source_model_id(self, model_id: str) -> Optional[str]:
+ def get_exposed_profile_source_model_id(self, model_id: str) -> str | None:
"""Return the base model for an exposed profile model ID, if any."""
with self._lock:
candidates = [model_id]
@@ -1391,7 +1430,7 @@ def get_exposed_profile_source_model_id(self, model_id: str) -> Optional[str]:
def get_exposed_profile_runtime_settings_for_request(
self,
model_id: str,
- ) -> Optional[tuple[str, ModelSettings]]:
+ ) -> tuple[str, ModelSettings] | None:
"""Return full runtime settings for an exposed profile request.
Unlike ``get_settings_for_request()``, this includes model-specific
@@ -1443,7 +1482,7 @@ def get_exposed_profile_model_ids(
def _profile_request_ids_locked(
self,
model_id: str,
- profile: Dict[str, Any],
+ profile: dict[str, Any],
) -> set[str]:
base = self._settings.get(model_id)
base_ids = {model_id}
@@ -1455,7 +1494,7 @@ def _profile_request_ids_locked(
def _validate_exposed_profile_ids_available_locked(
self,
model_id: str,
- profile: Dict[str, Any],
+ profile: dict[str, Any],
*,
exclude_profile_name: str | None = None,
reserved_model_ids: set[str] | None = None,
@@ -1514,7 +1553,7 @@ def list_exposed_profile_models(self) -> list[dict]:
return exposed
@staticmethod
- def _has_engine_fields(profile: Dict[str, Any]) -> bool:
+ def _has_engine_fields(profile: dict[str, Any]) -> bool:
"""True when the profile overrides any engine-construction field.
Those fields are ignored by the request-time sampling overlay but are
@@ -1540,7 +1579,7 @@ def list_profiles(self, model_id: str) -> list[dict]:
for p in per_model.values()
]
- def get_profile(self, model_id: str, name: str) -> Optional[dict]:
+ def get_profile(self, model_id: str, name: str) -> dict | None:
with self._lock:
return dict(self._profiles.get(model_id, {}).get(name, {})) or None
@@ -1549,12 +1588,12 @@ def save_profile(
model_id: str,
name: str,
display_name: str,
- description: Optional[str],
- settings: Dict[str, Any],
- source_template: Optional[str] = None,
+ description: str | None,
+ settings: dict[str, Any],
+ source_template: str | None = None,
expose_as_model: bool = False,
- api_name: Optional[str] = None,
- reserved_model_ids: Optional[set[str]] = None,
+ api_name: str | None = None,
+ reserved_model_ids: set[str] | None = None,
) -> dict:
"""Create a new profile. Raises if name is invalid or already exists."""
validate_profile_name(name)
@@ -1598,15 +1637,15 @@ def update_profile(
model_id: str,
name: str,
*,
- new_name: Optional[str] = None,
- display_name: Optional[str] = None,
- description: Optional[str] = None,
- settings: Optional[Dict[str, Any]] = None,
- source_template: Optional[str] = None,
- expose_as_model: Optional[bool] = None,
- api_name: Optional[str] = None,
- reserved_model_ids: Optional[set[str]] = None,
- ) -> Optional[dict]:
+ new_name: str | None = None,
+ display_name: str | None = None,
+ description: str | None = None,
+ settings: dict[str, Any] | None = None,
+ source_template: str | None = None,
+ expose_as_model: bool | None = None,
+ api_name: str | None = None,
+ reserved_model_ids: set[str] | None = None,
+ ) -> dict | None:
"""Update a profile's metadata/settings. Returns updated dict or None if not found."""
with self._lock:
per_model = self._profiles.get(model_id, {})
@@ -1710,8 +1749,8 @@ def apply_profile(
self,
model_id: str,
name: str,
- settings_sanitizer: Optional[Callable[[dict[str, Any]], None]] = None,
- ) -> Optional[ModelSettings]:
+ settings_sanitizer: Callable[[dict[str, Any]], None] | None = None,
+ ) -> ModelSettings | None:
"""Merge profile settings into the model's live settings and persist."""
with self._lock:
per_model = self._profiles.get(model_id, {})
@@ -1847,7 +1886,7 @@ def _load_templates(self) -> None:
self._templates = {}
return
try:
- with open(self.templates_file, "r", encoding="utf-8") as f:
+ with open(self.templates_file, encoding="utf-8") as f:
data = json.load(f)
version = data.get("version", 1)
if version != TEMPLATES_VERSION:
@@ -1890,7 +1929,7 @@ def list_templates(self) -> list[dict]:
with self._lock:
return [dict(t) for t in self._templates.values()]
- def get_template(self, name: str) -> Optional[dict]:
+ def get_template(self, name: str) -> dict | None:
with self._lock:
u = self._templates.get(name)
return dict(u) if u is not None else None
@@ -1899,8 +1938,8 @@ def save_template(
self,
name: str,
display_name: str,
- description: Optional[str],
- settings: Dict[str, Any],
+ description: str | None,
+ settings: dict[str, Any],
) -> dict:
validate_profile_name(name)
filtered = filter_universal_fields(settings or {})
@@ -1923,8 +1962,8 @@ def upsert_template(
self,
name: str,
display_name: str,
- description: Optional[str],
- settings: Dict[str, Any],
+ description: str | None,
+ settings: dict[str, Any],
) -> dict:
"""Create or replace a template with the given settings."""
validate_profile_name(name)
@@ -1948,11 +1987,11 @@ def update_template(
self,
name: str,
*,
- new_name: Optional[str] = None,
- display_name: Optional[str] = None,
- description: Optional[str] = None,
- settings: Optional[Dict[str, Any]] = None,
- ) -> Optional[dict]:
+ new_name: str | None = None,
+ display_name: str | None = None,
+ description: str | None = None,
+ settings: dict[str, Any] | None = None,
+ ) -> dict | None:
with self._lock:
if name not in self._templates:
return None
@@ -2019,7 +2058,7 @@ def forced_ct_keys(settings: "ModelSettings | None") -> set[str]:
"""Chat-template keys a request is not allowed to override."""
if settings is None:
return set()
- return set(settings.forced_ct_kwargs or [])
+ return set(getattr(settings, "forced_ct_kwargs", None) or [])
def merge_chat_template_request_kwargs(
@@ -2037,14 +2076,17 @@ def merge_chat_template_request_kwargs(
forced_keys = forced_ct_keys(settings)
if settings is not None:
- if settings.chat_template_kwargs:
- merged.update(settings.chat_template_kwargs)
+ chat_template_kwargs = getattr(settings, "chat_template_kwargs", None)
+ if chat_template_kwargs:
+ merged.update(chat_template_kwargs)
# Dedicated toggles take precedence over chat_template_kwargs.
- if settings.enable_thinking is not None:
- merged["enable_thinking"] = settings.enable_thinking
+ enable_thinking = getattr(settings, "enable_thinking", None)
+ if enable_thinking is not None:
+ merged["enable_thinking"] = enable_thinking
# preserve_thinking: keep blocks in historical turns (Qwen 3.6+)
- if settings.preserve_thinking is not None:
- merged["preserve_thinking"] = settings.preserve_thinking
+ preserve_thinking = getattr(settings, "preserve_thinking", None)
+ if preserve_thinking is not None:
+ merged["preserve_thinking"] = preserve_thinking
if request_ct_kwargs:
for key, value in request_ct_kwargs.items():
diff --git a/omlx/models/__init__.py b/omlx/models/__init__.py
index f625b8415c..56dbcc51ba 100644
--- a/omlx/models/__init__.py
+++ b/omlx/models/__init__.py
@@ -2,7 +2,7 @@
"""
MLX Model wrappers for oMLX.
-This module provides wrappers around mlx-lm and mlx-embeddings
+This module provides wrappers around mlx-lm and mlx-vlm
for integration with oMLX's model execution system.
"""
diff --git a/omlx/models/base_model.py b/omlx/models/base_model.py
index 5313ffc4cf..7cefa2ace7 100644
--- a/omlx/models/base_model.py
+++ b/omlx/models/base_model.py
@@ -3,7 +3,7 @@
Base model utilities for omlx custom model implementations.
This module provides common utilities for implementing custom models
-that are not yet supported by mlx-embeddings.
+that are not yet supported by mlx-vlm.
"""
from dataclasses import dataclass
diff --git a/omlx/models/d3.py b/omlx/models/d3.py
index 0edb86f24d..5fde55f212 100644
--- a/omlx/models/d3.py
+++ b/omlx/models/d3.py
@@ -207,12 +207,13 @@ def messages(
def chat_text(tokenizer, conversation: list[dict]) -> str:
- return tokenizer.apply_chat_template(
+ text: str = tokenizer.apply_chat_template(
conversation,
tokenize=False,
add_generation_prompt=True,
enable_thinking=False,
)
+ return text
def answer_codes(tokenizer) -> tuple[list[str], list[int]]:
@@ -296,7 +297,8 @@ def sample_indices(total: int, fps: float) -> list[int]:
"""Two frames per second, 4 to 32, spread over the whole video."""
count = int(total / fps * VIDEO_FPS)
count = min(max(count, VIDEO_MIN_FRAMES), VIDEO_MAX_FRAMES, total)
- return np.linspace(0, total - 1, count).round().astype(int).tolist()
+ indices: list[int] = np.linspace(0, total - 1, count).round().astype(int).tolist()
+ return indices
def decode_video(url: str) -> D3Video:
@@ -477,7 +479,12 @@ def load(self) -> None:
"this tokenizer gives"
)
hidden = (backbone.config.get("text_config") or backbone.config)["hidden_size"]
- weight = mx.load(str(path / D3_READOUT_WEIGHTS))["weight"]
+ weights = mx.load(str(path / D3_READOUT_WEIGHTS))
+ if not isinstance(weights, dict):
+ raise ValueError(f"{D3_READOUT_WEIGHTS} must contain named tensors")
+ weight = weights.get("weight")
+ if not isinstance(weight, mx.array):
+ raise ValueError(f"{D3_READOUT_WEIGHTS} is missing its weight tensor")
if tuple(weight.shape) != (MAX_OPTIONS, hidden):
raise ValueError(
f"readout weight has shape {tuple(weight.shape)}, expected "
@@ -659,12 +666,17 @@ def _expand(
def run(self, plan: D3Plan, chunk_size: ChunkSize) -> Generator[int, None, dict]:
"""Encode every question, yielding per layer step, then read out."""
backbone = self.backbone
+ readout = self.readout
+ if readout is None:
+ raise RuntimeError("Decision 3.0 model is not loaded")
image_features = video_features = None
if plan.image_pixels is not None:
+ assert plan.image_grids is not None
image_features = backbone.vision_features(
plan.image_pixels, plan.image_grids
)
if plan.video_pixels is not None:
+ assert plan.video_grids is not None
video_features = backbone.vision_features(
plan.video_pixels, plan.video_grids
)
@@ -690,11 +702,11 @@ def run(self, plan: D3Plan, chunk_size: ChunkSize) -> Generator[int, None, dict]
hidden = yield from backbone.encode(
embeds, mx.array(positions)[:, None, :], chunk_size, self.causal
)
- logits = (hidden.astype(self.readout.dtype) @ self.readout.T).astype(
- mx.float32
- )
+ logits = (hidden.astype(readout.dtype) @ readout.T).astype(mx.float32)
count = len(item.keys)
- probabilities = mx.softmax(logits[:count] / self.temperature).tolist()
+ probabilities: list[float] = np.asarray(
+ mx.softmax(logits[:count] / self.temperature)
+ ).tolist()
answers[item.question_id] = format_answer(item, probabilities)
input_tokens += len(ids)
return {"answers": answers, "input_tokens": input_tokens}
diff --git a/omlx/models/decision.py b/omlx/models/decision.py
index 5e6762c315..c1add601b8 100644
--- a/omlx/models/decision.py
+++ b/omlx/models/decision.py
@@ -235,7 +235,8 @@ def _forward(
return hidden
def embed_tokens(self, ids: np.ndarray) -> mx.array:
- return self._text_model.embed_tokens(mx.array(ids)[None])
+ embeds: mx.array = self._text_model.embed_tokens(mx.array(ids)[None])
+ return embeds
def vision_features(
self, pixel_values: np.ndarray, grid_thw: np.ndarray
@@ -243,6 +244,7 @@ def vision_features(
"""Vision-tower features of images or videos, one row per prompt token."""
tower = self.model.vision_tower
pixels = mx.array(pixel_values).astype(tower.patch_embed.proj.weight.dtype)
+ features: mx.array
features, _ = tower(pixels, mx.array(grid_thw))
return features
@@ -287,7 +289,8 @@ def encode(
mx.eval(hidden)
yield length * end // depth - length * done // depth
done = end
- return self._text_model.norm(hidden[0, -1])
+ normed: mx.array = self._text_model.norm(hidden[0, -1])
+ return normed
def logits(self, hidden: mx.array) -> mx.array:
if isinstance(self._lm_head, nn.Embedding | nn.QuantizedEmbedding):
diff --git a/omlx/output_collector.py b/omlx/output_collector.py
index 0c15ebec77..8bebbcd514 100644
--- a/omlx/output_collector.py
+++ b/omlx/output_collector.py
@@ -8,8 +8,7 @@
"""
import asyncio
-from dataclasses import dataclass, field
-from typing import List, Optional
+from dataclasses import dataclass
from .request import RequestOutput
@@ -46,7 +45,7 @@ def __init__(self, aggregate: bool = True):
aggregate: If True, merge outputs when producer gets ahead.
This prevents buffer explosion under load.
"""
- self.output: Optional[RequestOutput] = None
+ self.output: RequestOutput | None = None
self.ready = asyncio.Event()
self.aggregate = aggregate
self._is_waiting = False
@@ -71,7 +70,7 @@ def put(self, output: RequestOutput) -> None:
self.output = output
self.ready.set()
- def get_nowait(self) -> Optional[RequestOutput]:
+ def get_nowait(self) -> RequestOutput | None:
"""
Get output without blocking.
@@ -132,7 +131,6 @@ def _merge_outputs(
Returns:
Merged RequestOutput
"""
- # Combine new tokens
merged_new_token_ids = existing.new_token_ids + new.new_token_ids
merged_new_text = existing.new_text + new.new_text
@@ -140,8 +138,8 @@ def _merge_outputs(
request_id=new.request_id,
new_token_ids=merged_new_token_ids,
new_text=merged_new_text,
- output_token_ids=new.output_token_ids, # Use latest cumulative
- output_text=new.output_text, # Use latest cumulative
+ output_token_ids=new.output_token_ids,
+ output_text=new.output_text,
finished=new.finished,
finish_reason=new.finish_reason,
prompt_tokens=new.prompt_tokens,
@@ -156,7 +154,7 @@ def _merge_outputs(
if new.generated_until is not None
else existing.generated_until
),
- tool_calls=new.tool_calls, # Preserve tool_calls for Harmony models
+ tool_calls=new.tool_calls,
logprobs=(
(existing.logprobs or []) + (new.logprobs or [])
if existing.logprobs or new.logprobs
diff --git a/omlx/request.py b/omlx/request.py
index fa5f65d25c..573ea7a0ca 100644
--- a/omlx/request.py
+++ b/omlx/request.py
@@ -10,7 +10,7 @@
import enum
import time
from dataclasses import dataclass, field
-from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
+from typing import TYPE_CHECKING, Any, Optional
if TYPE_CHECKING:
from .cache.paged_cache import BlockTable
@@ -98,7 +98,7 @@ def is_finished(status: "RequestStatus") -> bool:
return status > RequestStatus.PREEMPTED
@staticmethod
- def get_finish_reason(status: "RequestStatus") -> Optional[str]:
+ def get_finish_reason(status: "RequestStatus") -> str | None:
"""Get the finish reason string for a finished status."""
if status == RequestStatus.FINISHED_STOPPED:
return "stop"
@@ -131,8 +131,8 @@ class SamplingParams:
ngram_window: int = 0
presence_penalty: float = 0.0
frequency_penalty: float = 0.0
- stop: Optional[List[str]] = None
- stop_token_ids: Optional[List[int]] = None
+ stop: list[str] | None = None
+ stop_token_ids: list[int] | None = None
# Forced-length generation (benchmark use): when True the model's own
# EOS/EOT/generation_config stop tokens do not end generation — only
# max_tokens does. Request-level stop strings / stop_token_ids still
@@ -141,17 +141,17 @@ class SamplingParams:
# Logprobs settings (memory optimization: disabled by default)
logprobs: bool = False # Whether to return logprobs
- top_logprobs: Optional[int] = None # Number of top logprobs (1-20)
+ top_logprobs: int | None = None # Number of top logprobs (1-20)
# Thinking budget (None = unlimited thinking)
- thinking_budget: Optional[int] = None
+ thinking_budget: int | None = None
# Compiled grammar for constrained decoding (xgrammar CompiledGrammar).
# Typed as Any to avoid a hard dependency on xgrammar at import time.
compiled_grammar: Any = None
# Seed for reproducible generation (best-effort, per OpenAI spec)
- seed: Optional[int] = None
+ seed: int | None = None
# Stop strings skip the leading think block. Set by the APIs that return
# reasoning separately; /v1/completions returns it inline.
@@ -181,41 +181,43 @@ class Request:
sampling_params: Parameters for generation
arrival_time: When the request was received
status: Current status of the request
- num_prompt_tokens: Number of tokens in the prompt
+ num_prompt_tokens: Effective prompt length used by the model/cache
+ source_prompt_tokens: Original processor length before media compaction, if any
num_computed_tokens: Number of tokens processed so far
output_token_ids: Generated token ids
output_text: Generated text (decoded)
"""
request_id: str
- prompt: Union[str, List[int]]
+ prompt: str | list[int]
sampling_params: SamplingParams
arrival_time: float = field(default_factory=time.monotonic)
priority: int = 0 # Lower is higher priority
# Set after tokenization
- prompt_token_ids: Optional[List[int]] = None
+ prompt_token_ids: list[int] | None = None
num_prompt_tokens: int = 0
+ source_prompt_tokens: int | None = None
# Generation state
status: RequestStatus = RequestStatus.WAITING
num_computed_tokens: int = 0
- output_token_ids: List[int] = field(default_factory=list)
+ output_token_ids: list[int] = field(default_factory=list)
output_text: str = ""
- generation_started_at: Optional[float] = None
- prefill_started_at: Optional[float] = None
- last_activity_at: Optional[float] = None
+ generation_started_at: float | None = None
+ prefill_started_at: float | None = None
+ last_activity_at: float | None = None
# (time, output tokens) checkpoints for the live decode rate, oldest first.
decode_marks: DecodeMarks = ()
# For BatchGenerator integration
- batch_uid: Optional[int] = None # UID assigned by BatchGenerator
+ batch_uid: int | None = None # UID assigned by BatchGenerator
# Prefix cache fields
- prompt_cache: Optional[List[Any]] = None # Cached KV state from prefix cache
+ prompt_cache: list[Any] | None = None # Cached KV state from prefix cache
cached_tokens: int = 0 # Prefix tokens in KV, including resumed prefill
prefill_resumed_tokens: int = 0 # Locally computed tokens retained after a pause
- remaining_tokens: Optional[List[int]] = None # Tokens still needing processing
+ remaining_tokens: list[int] | None = None # Tokens still needing processing
# Paged cache fields (for BlockAwarePrefixCache)
block_table: Optional["BlockTable"] = None # Block table for paged cache
@@ -230,7 +232,7 @@ class Request:
memory_requeues: int = 0
requeued_output_tokens: int = 0
requeue_reported_cached_tokens: int = 0
- requeue_row_state: Optional[Tuple[Any, List[Any], Any]] = None
+ requeue_row_state: tuple[Any, list[Any], Any] | None = None
# Token index after the last media placeholder. Embeddings are gone by
# then, so the resumed prefix must cover every media token.
requeue_media_end: int = 0
@@ -248,40 +250,40 @@ class Request:
# only for benchmark_trace requests so the benchmark summary can distinguish
# a requested scheduler step from the model calls actually delivered after
# cache-boundary and memory clamps.
- benchmark_prefill_chunks: List[int] = field(default_factory=list)
- benchmark_requested_steps: List[int] = field(default_factory=list)
+ benchmark_prefill_chunks: list[int] = field(default_factory=list)
+ benchmark_requested_steps: list[int] = field(default_factory=list)
benchmark_boundary_enabled: bool = False
benchmark_cache_block_size: int = 0
# MoE expert offload counters when the request was added.
- moe_offload_start: Optional[Dict[str, Any]] = None
+ moe_offload_start: dict[str, Any] | None = None
# Multimodal content (images, video)
- images: Optional[List[Any]] = None
- videos: Optional[List[Any]] = None
+ images: list[Any] | None = None
+ videos: list[Any] | None = None
# VLM (Vision-Language Model) fields
- vlm_inputs_embeds: Optional[Any] = (
+ vlm_inputs_embeds: Any | None = (
None # Pre-computed vision+text embeddings (mx.array)
)
- vlm_extra_kwargs: Optional[Dict[str, Any]] = (
+ vlm_extra_kwargs: dict[str, Any] | None = (
None # Model-specific kwargs (e.g., position_ids)
)
- vlm_image_hash: Optional[str] = None # SHA256 hash of images for prefix cache
+ vlm_image_hash: str | None = None # SHA256 hash of images for prefix cache
vlm_cache_key_start: int = 0 # Token index where image-specific cache keying starts
- vlm_cache_key_ranges: Optional[List[Tuple[int, str]]] = (
+ vlm_cache_key_ranges: list[tuple[int, str]] | None = (
None # [(token_start, cumulative_image_hash)]
)
rope_deltas: float = 0.0 # Per-request mRoPE position delta (set after VLM prefill)
@property
- def vlm_extra_keys_for_cache(self) -> Optional[Tuple[str, ...]]:
+ def vlm_extra_keys_for_cache(self) -> tuple[str, ...] | None:
"""Whole-request image hash wrapped as extra_keys tuple."""
if self.vlm_image_hash:
return (self.vlm_image_hash,)
return None
@property
- def vlm_extra_key_token_start_for_cache(self) -> Optional[int]:
+ def vlm_extra_key_token_start_for_cache(self) -> int | None:
"""Token index where image-specific cache keying begins."""
if self.vlm_image_hash:
return self.vlm_cache_key_start
@@ -290,7 +292,7 @@ def vlm_extra_key_token_start_for_cache(self) -> Optional[int]:
@property
def vlm_extra_key_ranges_for_cache(
self,
- ) -> Optional[List[Tuple[int, Tuple[str, ...]]]]:
+ ) -> list[tuple[int, tuple[str, ...]]] | None:
"""Segmented VLM cache key ranges for per-image-turn keying."""
if not self.vlm_cache_key_ranges:
return None
@@ -299,7 +301,7 @@ def vlm_extra_key_ranges_for_cache(
]
# Metadata
- finish_reason: Optional[str] = None
+ finish_reason: str | None = None
# Reasoning model support (for models with tags)
needs_think_prefix: bool = False # True if prompt ends with token
@@ -312,7 +314,7 @@ def vlm_extra_key_ranges_for_cache(
is_harmony_model: bool = False # True if model uses Harmony format
# SpecPrefill (sparse prefill for MoE models)
- specprefill_indices: Optional[Any] = None # mx.array of selected token indices
+ specprefill_indices: Any | None = None # mx.array of selected token indices
specprefill_total_tokens: int = 0 # Original total token count (M)
specprefill_position_offset: int = 0 # RoPE offset = M - N
specprefill_system_end: int = 0 # Token index where system prompt ends
@@ -323,7 +325,7 @@ def vlm_extra_key_ranges_for_cache(
generation_prompt_persists: bool = False # History keeps the generation prompt
# Rendered leading system block; a shared tail snapshot ends where it does.
- system_prefix_ids: Optional[List[int]] = None
+ system_prefix_ids: list[int] | None = None
system_prefix_end: int = 0 # Token index where the shared system prefix ends
junction_end: int = 0 # Where this prompt branches off a recent stored sequence
@@ -367,7 +369,7 @@ def is_finished(self) -> bool:
"""Check if request has finished."""
return RequestStatus.is_finished(self.status)
- def get_finish_reason(self) -> Optional[str]:
+ def get_finish_reason(self) -> str | None:
"""Get the finish reason if finished."""
if self.finish_reason:
return self.finish_reason
@@ -378,7 +380,7 @@ def append_output_token(self, token_id: int) -> None:
self.output_token_ids.append(token_id)
self.num_computed_tokens += 1
- def set_finished(self, status: RequestStatus, reason: Optional[str] = None) -> None:
+ def set_finished(self, status: RequestStatus, reason: str | None = None) -> None:
"""Mark the request as finished."""
self.status = status
self.finish_reason = reason or RequestStatus.get_finish_reason(status)
@@ -404,9 +406,9 @@ class TokenLogprob:
token_id: int
text: str
- token_bytes: List[int]
+ token_bytes: list[int]
logprob: float
- top: List["TokenLogprob"] = field(default_factory=list)
+ top: list["TokenLogprob"] = field(default_factory=list)
@dataclass
@@ -419,47 +421,47 @@ class RequestOutput:
request_id: str
# New tokens generated in this step
- new_token_ids: List[int] = field(default_factory=list)
+ new_token_ids: list[int] = field(default_factory=list)
new_text: str = ""
- # Cumulative output
- output_token_ids: List[int] = field(default_factory=list)
+ # Cumulative output, materialized on the terminal output.
+ output_token_ids: list[int] = field(default_factory=list)
output_text: str = ""
# Status
finished: bool = False
- finish_reason: Optional[str] = None
+ finish_reason: str | None = None
# Timing
prompt_tokens: int = 0
completion_tokens: int = 0
# Internal producer-side timestamp for the first generated token included in
# this output. Consumers may receive aggregated chunks later than the token
# was actually produced, so benchmark code must not rely only on receive time.
- generated_at: Optional[float] = None
+ generated_at: float | None = None
# Internal producer-side timestamp for the latest generated token included
# in this output. This lets aggregated chunks preserve the decode interval.
- generated_until: Optional[float] = None
+ generated_until: float | None = None
# Timestamp of the very first generated token for this request (perf_counter).
# Set by non-streaming generate() to allow TTFT / prefill-duration estimation.
- first_token_at: Optional[float] = None
+ first_token_at: float | None = None
# Tool calls (for Harmony and other models with tool calling support)
- tool_calls: Optional[List[Dict[str, str]]] = None
+ tool_calls: list[dict[str, str]] | None = None
# One entry per token in new_token_ids when the request asked for logprobs.
- logprobs: Optional[List[TokenLogprob]] = None
+ logprobs: list[TokenLogprob] | None = None
# Prefix cache stats
cached_tokens: int = 0
# Error message (set when engine encounters an unrecoverable error)
- error: Optional[str] = None
+ error: str | None = None
# Structured internal error classification for API-layer mapping.
- error_code: Optional[str] = None
- error_metadata: Optional[Dict[str, Any]] = None
+ error_code: str | None = None
+ error_metadata: dict[str, Any] | None = None
# Internal benchmark instrumentation copied from the originating request.
- benchmark_prefill_chunks: List[int] = field(default_factory=list)
- benchmark_requested_steps: List[int] = field(default_factory=list)
+ benchmark_prefill_chunks: list[int] = field(default_factory=list)
+ benchmark_requested_steps: list[int] = field(default_factory=list)
benchmark_boundary_enabled: bool = False
benchmark_cache_block_size: int = 0
@property
- def usage(self) -> Dict[str, int]:
+ def usage(self) -> dict[str, int]:
"""Return usage statistics compatible with OpenAI API."""
return {
"prompt_tokens": self.prompt_tokens,
diff --git a/omlx/scheduler.py b/omlx/scheduler.py
index 54ad9f0a70..c0794b03db 100644
--- a/omlx/scheduler.py
+++ b/omlx/scheduler.py
@@ -766,6 +766,13 @@ def _register_uid_rows(model, uids, samplers, lps_rows) -> None:
_uid_row_registry.popitem(last=False)
+def _record_native_mtp_request_eligibility(model, uid: int, request) -> None:
+ """Tell an optional VLM adapter whether this UID used embeddings prefill."""
+ setter = getattr(model, "set_native_mtp_request_eligible", None)
+ if callable(setter):
+ setter(uid, getattr(request, "vlm_inputs_embeds", None) is None)
+
+
def _unregister_uid_row(model, uid) -> None:
"""Drop a finished request's row so heavy processors are not pinned
until FIFO eviction; the bounded size stays as the backstop."""
@@ -7802,6 +7809,7 @@ def _insert_prefilled_request(
_register_uid_rows(self.model, uids, [state.sampler], [per_row_lps])
_mtp_priming.bind_uid(self.model, request.request_id, uid)
self._dflash_bind_uid(request.request_id, uid)
+ _record_native_mtp_request_eligibility(self.model, uid, request)
if hasattr(self.model, "register_rope_delta"):
self.model.register_rope_delta(uid, request.rope_deltas)
_mark_text_positions(self.model, request, uid)
@@ -11260,6 +11268,19 @@ def _prepare_prefix_cache_for_request(self, request: Request) -> None:
if request.request_id in self._prefix_cache_prepared:
return
+ if request.vlm_extra_kwargs is not None:
+ source_prompt_tokens = request.vlm_extra_kwargs.pop(
+ "_omlx_source_prompt_tokens", None
+ )
+ if source_prompt_tokens is not None:
+ request.source_prompt_tokens = source_prompt_tokens
+ unpaired_native_history = (
+ getattr(self.model, "_omlx_native_mtp_full_prompt", False) is True
+ or (request.vlm_extra_kwargs or {}).get("_omlx_pruned_video") is True
+ )
+ if unpaired_native_history:
+ request.skip_cache_store = True
+
prefix_hook = getattr(self.model, "minimum_prefill_prefix", None)
minimum_prefix = (
prefix_hook(request.prompt_token_ids) if callable(prefix_hook) else 0
@@ -11271,6 +11292,10 @@ def _prepare_prefix_cache_for_request(self, request: Request) -> None:
if (
self.block_aware_cache is not None
and not self._model_has_unreconstructible_cache()
+ # DSpark needs every target-layer capture, which KV prefix entries
+ # do not contain. Re-prefill rather than silently truncate its context.
+ and getattr(_block_drafter_for(self.model), "kind", None) != "dspark"
+ and not unpaired_native_history
):
# Use paged cache
fetch_started = time.perf_counter()
@@ -14295,6 +14320,7 @@ def _report_sparse_progress(processed: int, total: int) -> None:
uid = uids[0]
_mtp_priming.bind_uid(self.model, request.request_id, uid)
self._dflash_bind_uid(request.request_id, uid)
+ _record_native_mtp_request_eligibility(self.model, uid, request)
self.request_id_to_uid[request.request_id] = uid
self.uid_to_request_id[uid] = request.request_id
now = time.monotonic()
@@ -14518,7 +14544,11 @@ def _process_batch_responses(
logprobs=token_logprobs,
# Only the terminal chunk's cumulative ids are read.
output_token_ids=list(request.output_token_ids) if is_finished else [],
- prompt_tokens=request.num_prompt_tokens,
+ prompt_tokens=(
+ request.source_prompt_tokens
+ if request.source_prompt_tokens is not None
+ else request.num_prompt_tokens
+ ),
completion_tokens=request.num_output_tokens,
generated_at=output_generated_at,
generated_until=output_generated_at,
@@ -15693,6 +15723,8 @@ def _memory_requeue_blocker(self, request: "Request") -> str | None:
return "specprefill"
if _block_drafter_for(self.model) is not None:
return "block drafter"
+ if getattr(self.model, "_omlx_native_mtp_full_prompt", False) is True:
+ return "native full-prompt MTP"
if request_id in self._prefill_states:
return None
uid = self.request_id_to_uid.get(request_id)
@@ -15716,7 +15748,14 @@ def _media_token_end(self, token_ids: list[int]) -> int:
config = getattr(getattr(self.model, "_vlm_model", None), "config", None)
media_ids = {
int(value)
- for name in ("image_token_id", "video_token_id", "audio_token_id")
+ for name in (
+ "image_token_id",
+ "video_token_id",
+ "audio_token_id",
+ "img_context_token_id",
+ "video_context_token_id",
+ "sound_context_token_id",
+ )
if isinstance(value := getattr(config, name, None), int)
}
if not media_ids:
diff --git a/omlx/server.py b/omlx/server.py
index 7eaa60e523..65866adb5c 100644
--- a/omlx/server.py
+++ b/omlx/server.py
@@ -31,6 +31,8 @@
- POST /v1/chat/completions - Chat completions
- POST /v1/messages - Anthropic Messages API
- POST /v1/responses - OpenAI Responses API (Codex compatibility)
+ - POST /v1/images/generations - Image generation
+ - POST /v1/images/edits - Image editing
- GET /v1/models - List available models (with load status)
- GET /health - Health check
- GET /v1/mcp/tools - List MCP tools
@@ -54,8 +56,9 @@
from dataclasses import asdict, dataclass, field
from datetime import UTC, datetime
from enum import Enum
+from functools import partial
from pathlib import Path
-from typing import Optional, Union
+from typing import Optional
import anyio
from fastapi import Depends, FastAPI, HTTPException, Response
@@ -95,6 +98,12 @@
request_has_cache_control,
)
from .api.body_limit import RequestBodySizeLimitMiddleware
+from .api.claude_gateway import (
+ CLAUDE_GATEWAY_PATH,
+ ClaudeGatewayModelInfo,
+ claude_gateway_model_id,
+ claude_gateway_served_id,
+)
from .api.embedding_models import (
EmbeddingData,
EmbeddingRequest,
@@ -118,6 +127,11 @@
request_has_file_parts,
stream_messages_to_markdown_async,
)
+from .api.media_inputs import (
+ has_audio_video_parts,
+ normalize_media_file_parts_in_messages,
+)
+from .api.media_options import merge_mm_processor_kwargs
# Import from new modular API
from .api.openai_models import (
@@ -137,8 +151,8 @@
CompletionTokensDetails,
DetokenizeRequest,
DetokenizeResponse,
+ Message,
ModelInfo,
- ModelsResponse,
PromptTokensDetails,
TokenizeChatRequest,
TokenizeRequest,
@@ -173,6 +187,7 @@
convert_responses_input_to_messages,
convert_responses_tools,
format_sse_event,
+ normalize_chat_messages_for_response_store,
normalize_response_output_to_messages,
split_namespace_tool_name,
)
@@ -195,8 +210,8 @@
)
from .api.tool_calling import (
ToolCallExtraction,
- ToolCallStreamSegment,
ToolCallStreamFilter,
+ ToolCallStreamSegment,
build_json_system_prompt,
convert_tools_for_template,
enrich_tool_params_for_gemma4,
@@ -207,6 +222,7 @@
sanitize_tool_call_markup,
)
from .api.utils import (
+ cache_reasoning_output,
clean_special_tokens,
detect_and_strip_partial,
extract_multimodal_content,
@@ -215,15 +231,14 @@
has_nonleading_system_message,
merge_reasoning_effort_chat_template_kwargs,
prepare_system_messages_for_template,
- cache_reasoning_output,
uses_native_reasoning_content,
)
from .engine import BaseEngine, BatchedEngine, GenerationOutput, VLMBatchedEngine
+from .engine.decision import DecisionEngine
from .engine.distributed import DistributedInferenceError
-from .engine.vlm import MINIMAX_M3_MODEL_TYPES
from .engine.embedding import EmbeddingEngine
from .engine.reranker import RerankerEngine
-from .engine.decision import DecisionEngine
+from .engine.vlm import MINIMAX_M3_MODEL_TYPES
from .engine_pool import (
CLAUDE_DESKTOP_TIER_FAMILY,
EnginePool,
@@ -308,28 +323,29 @@ class ServerState:
to manage and test.
"""
- engine_pool: Optional[EnginePool] = None
- default_model: Optional[str] = None
- mcp_manager: Optional[object] = None
- mcp_executor: Optional[object] = None
+ engine_pool: EnginePool | None = None
+ default_model: str | None = None
+ mcp_manager: object | None = None
+ mcp_executor: object | None = None
sampling: SamplingDefaults = field(default_factory=SamplingDefaults)
- api_key: Optional[str] = None
+ api_key: str | None = None
# Bind address snapshot for security checks. Unlike GlobalSettings.server.host,
# this remains unchanged until the process restarts on the new address.
bind_host: str | None = None
- settings_manager: Optional[object] = None # ModelSettingsManager
- global_settings: Optional[object] = None # GlobalSettings
- hf_downloader: Optional[object] = None # HFDownloader
- ms_downloader: Optional[object] = None # MSDownloader
- process_memory_enforcer: Optional[object] = None # ProcessMemoryEnforcer
- gpu_power_limiter: Optional[gpu_power.GpuPowerLimiter] = None
+ settings_manager: object | None = None # ModelSettingsManager
+ global_settings: object | None = None # GlobalSettings
+ hf_downloader: object | None = None # HFDownloader
+ ms_downloader: object | None = None # MSDownloader
+ process_memory_enforcer: object | None = None # ProcessMemoryEnforcer
+ gpu_power_limiter: gpu_power.GpuPowerLimiter | None = None
responses_store: ResponseStore = field(default_factory=ResponseStore)
- oq_manager: Optional[object] = None # OQManager
- hf_uploader: Optional[object] = None # HFUploader
+ oq_manager: object | None = None # OQManager
+ hf_uploader: object | None = None # HFUploader
# False while the startup pinned-model preload is still running.
# /health returns 503 with status "loading" until it flips to True so
# port watchdogs see liveness instead of a closed port (#2184).
pinned_preload_complete: bool = True
+ model_load_tasks: dict[str, asyncio.Task[None]] = field(default_factory=dict)
# Snapshot at init_server(). Settings may be edited while this process is
# running, but routes, navigation, and Bonjour switch together on restart.
distributed_inference_enabled: bool = False
@@ -775,6 +791,12 @@ async def _ttl_check_loop():
preload_task.cancel()
with suppress(asyncio.CancelledError):
await preload_task
+ model_load_tasks = list(_server_state.model_load_tasks.values())
+ for task in model_load_tasks:
+ task.cancel()
+ if model_load_tasks:
+ await asyncio.gather(*model_load_tasks, return_exceptions=True)
+ _server_state.model_load_tasks.clear()
get_server_metrics().close()
if ttl_task is not None:
ttl_task.cancel()
@@ -816,6 +838,12 @@ async def _ttl_check_loop():
set_mcp_manager_getter(get_mcp_manager)
app.include_router(mcp_router, dependencies=[Depends(verify_inference_api_key)])
+# Keep image routes registered even when the mlx-vlm image runtime is unavailable;
+# handlers return a 503 install hint so OpenAI-compatible paths remain stable.
+from .api.image_routes import router as image_router
+
+app.include_router(image_router, dependencies=[Depends(verify_api_key)])
+
# Include web search routes (chat UI built-in web_search / fetch_url tools)
from .api.websearch_routes import router as websearch_router
from .api.websearch_routes import set_global_settings_getter as _set_websearch_settings
@@ -987,7 +1015,10 @@ def _is_api_route(request: FastAPIRequest) -> bool:
"""
path = request.url.path
- return path.startswith("/v1/") or path in _ROOT_API_ROUTES
+ return (
+ path.startswith(("/v1/", f"{CLAUDE_GATEWAY_PATH}/v1/"))
+ or path in _ROOT_API_ROUTES
+ )
def _openai_error_body(message, status_code: int, param=None, code=None) -> dict:
@@ -1452,7 +1483,7 @@ async def get_engine(
_lease: bool = False,
_leased_out: list | None = None,
_allow_embedding: bool = False,
-) -> Union[BaseEngine, EmbeddingEngine, RerankerEngine, DecisionEngine]:
+) -> BaseEngine | EmbeddingEngine | RerankerEngine | DecisionEngine:
"""
Get engine for the specified model and type.
@@ -2238,9 +2269,16 @@ def _resolve_metric_durations(
generation_tps = float(getattr(output, "generation_tps", 0.0) or 0.0)
if generation_tps > 0:
generation_duration = output.completion_tokens / generation_tps
-
return prefill_duration, generation_duration
+def _active_model_aliases() -> dict[str, str]:
+ """Return aliases that the current engine pool can resolve safely."""
+ pool = _server_state.engine_pool
+ settings_manager = _server_state.settings_manager
+ if pool is None or settings_manager is None:
+ return {}
+ return pool.get_active_model_aliases(settings_manager)
+
def _usage_timing_fields(
prompt_tokens: int,
@@ -2408,38 +2446,59 @@ def get_rerank_max_length(
return None
-def _prepare_chat_prompt_for_request(
+async def _prepare_chat_prompt_for_request(
engine: BaseEngine,
messages: list,
tools: list | None = None,
chat_template_kwargs: dict | None = None,
is_partial: bool | None = None,
+ mm_processor_kwargs: dict | None = None,
) -> tuple[int, tuple[str, list[int]] | None]:
# Subclasses (e.g. distributed) have their own prompt handling.
- if type(engine) in (BatchedEngine, VLMBatchedEngine):
- prepared = engine.prepare_chat_prompt(
- messages, tools, chat_template_kwargs, is_partial
- )
- return len(prepared[1]), prepared
- return (
- engine.count_chat_tokens(
+ if type(engine) is BatchedEngine or (
+ type(engine) is VLMBatchedEngine and engine.model_type != "minicpmv4_7"
+ ):
+ prepared = await asyncio.to_thread(
+ engine.prepare_chat_prompt,
messages,
tools,
- chat_template_kwargs=chat_template_kwargs,
- is_partial=is_partial,
- ),
- None,
+ chat_template_kwargs,
+ is_partial,
+ )
+ return len(prepared[1]), prepared
+ processor_kwargs = (
+ {"mm_processor_kwargs": mm_processor_kwargs} if mm_processor_kwargs else {}
)
+ count_prompt = partial(
+ engine.count_chat_tokens,
+ messages,
+ tools,
+ chat_template_kwargs=chat_template_kwargs,
+ is_partial=is_partial,
+ **processor_kwargs,
+ )
+ if getattr(engine, "model_type", None) == "minicpmv4_7":
+ count = await asyncio.get_running_loop().run_in_executor(
+ engine._engine._mlx_executor, count_prompt
+ )
+ elif isinstance(engine, VLMBatchedEngine):
+ count = await asyncio.to_thread(count_prompt)
+ else:
+ count = count_prompt()
+ return count, None
-async def _prepare_prompt_off_loop(engine: BaseEngine, prepare, *args, **kwargs):
- """Call ``prepare(engine, ...)`` in a worker thread for batched engines.
-
- Encoding a long prompt on the event loop stalls every other stream.
- """
- if type(engine) in (BatchedEngine, VLMBatchedEngine):
- return await asyncio.to_thread(prepare, engine, *args, **kwargs)
- return prepare(engine, *args, **kwargs)
+def _request_mm_processor_kwargs(engine: BaseEngine, request, settings) -> dict:
+ options = merge_mm_processor_kwargs(
+ getattr(settings, "mm_processor_kwargs", None),
+ request.mm_processor_kwargs,
+ )
+ if options and getattr(engine, "model_type", None) != "minicpmv4_7":
+ raise InvalidRequestError(
+ "mm_processor_kwargs is only supported by MiniCPM-V 4.7.",
+ field="mm_processor_kwargs",
+ )
+ return options
class _ContextLengthExceededError(HTTPException):
@@ -2467,6 +2526,37 @@ def validate_context_window(
)
+def _select_default_chat_model(
+ pool: EnginePool,
+ settings_default: str | None,
+) -> tuple[str | None, str | None]:
+ """Select a default model suitable for chat/completions endpoints."""
+ available_models = pool.get_model_ids()
+ if not available_models:
+ return None, None
+
+ if settings_default:
+ entry = pool.get_entry(settings_default)
+ if entry is not None and entry.model_type in {"llm", "vlm"}:
+ return settings_default, None
+ if entry is None:
+ reason = f"Default model '{settings_default}' not found"
+ else:
+ reason = (
+ f"Default model '{settings_default}' is a {entry.model_type} model, "
+ "not a chat-capable model"
+ )
+ else:
+ reason = None
+
+ for model_id in available_models:
+ entry = pool.get_entry(model_id)
+ if entry is not None and entry.model_type in {"llm", "vlm"}:
+ return model_id, reason
+
+ return None, reason
+
+
def init_server(
model_dirs: str | list[str],
scheduler_config=None,
@@ -2675,21 +2765,18 @@ def init_server(
f"No models found in {', '.join(dir_list)}. Add models to serve them."
)
- # Set default model (from settings file, fallback to first model)
- available_models = _server_state.engine_pool.get_model_ids()
- if available_models:
- if settings_default:
- if settings_default in available_models:
- _server_state.default_model = settings_default
- else:
- logger.warning(
- f"Default model '{settings_default}' not found, using first model"
- )
- _server_state.default_model = available_models[0]
+ # Set default model for chat/completions. Discovery can include image,
+ # embedding, and audio models; never make those the implicit chat default.
+ default_model, default_warning = _select_default_chat_model(
+ _server_state.engine_pool,
+ settings_default,
+ )
+ if default_warning is not None:
+ if default_model is not None:
+ logger.warning(f"{default_warning}, using '{default_model}'")
else:
- _server_state.default_model = available_models[0]
- else:
- _server_state.default_model = None
+ logger.warning(f"{default_warning}, and no chat-capable models were found")
+ _server_state.default_model = default_model
# Reset server metrics for fresh start (with all-time persistence)
stats_path = base_path / "stats.json"
@@ -3615,12 +3702,19 @@ def _with_exposed_profile_status(status: dict) -> dict:
async def _preprocess_markitdown_files_for_llm(
request: ChatCompletionRequest,
) -> ChatCompletionRequest:
- if not request_has_file_parts(request.messages):
- return request
+ try:
+ messages = normalize_media_file_parts_in_messages(request.messages)
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+ if not request_has_file_parts(messages):
+ if messages is request.messages:
+ return request
+ return request.model_copy(update={"messages": messages})
try:
messages = await preprocess_markitdown_file_parts_async(
- request.messages,
+ messages,
global_settings=_server_state.global_settings,
engine_pool=_server_state.engine_pool,
settings_manager=_server_state.settings_manager,
@@ -3635,6 +3729,72 @@ async def _preprocess_markitdown_files_for_llm(
return request.model_copy(update={"messages": messages})
+async def _preprocess_response_files_for_llm(
+ messages: list[dict],
+) -> list[dict]:
+ """Convert attachments without round-tripping Responses history through Message."""
+ try:
+ messages = normalize_media_file_parts_in_messages(messages)
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+ document_indices = {
+ index
+ for index, message in enumerate(messages)
+ if isinstance(message.get("content"), list)
+ and any(
+ isinstance(part, dict) and part.get("type") == "file"
+ for part in message["content"]
+ )
+ }
+ if not document_indices:
+ return messages
+
+ # MarkItDown needs roles for historical-file handling, but not tool calls
+ # or other conversation metadata. Only document-bearing content crosses
+ # this adapter; ordinary Codex text/tool requests never construct Message.
+ attachment_messages = [
+ Message(
+ role=message.get("role", "user"),
+ content=message.get("content") if index in document_indices else None,
+ )
+ for index, message in enumerate(messages)
+ ]
+ try:
+ processed = await preprocess_markitdown_file_parts_async(
+ attachment_messages,
+ global_settings=_server_state.global_settings,
+ engine_pool=_server_state.engine_pool,
+ settings_manager=_server_state.settings_manager,
+ get_sampling_params=get_sampling_params,
+ fail_when_disabled=True,
+ allow_missing_historical_files=True,
+ )
+ except MarkItDownRequestError as exc:
+ raise HTTPException(status_code=exc.status_code, detail=exc.detail) from exc
+ except RuntimeError as exc:
+ raise HTTPException(status_code=500, detail=str(exc)) from exc
+
+ result = list(messages)
+ for index in document_indices:
+ # Conversion replaces each file with one text part. Preserve all other
+ # original parts and message fields, including protocol extensions.
+ result[index] = {
+ **messages[index],
+ "content": [
+ (
+ converted.model_dump(exclude_none=True)
+ if isinstance(original, dict) and original.get("type") == "file"
+ else original
+ )
+ for original, converted in zip(
+ messages[index]["content"], processed[index].content, strict=True
+ )
+ ],
+ }
+ return result
+
+
def _build_markitdown_chat_response(
request: ChatCompletionRequest,
markdown: str,
@@ -3786,12 +3946,25 @@ async def _build_markitdown_completion():
@app.get("/v1/models", response_model=None)
async def list_models(_: bool = Depends(verify_inference_api_key)) -> JSONResponse:
"""List all available models with load status."""
+ return await _list_models()
+
+
+@app.get(f"{CLAUDE_GATEWAY_PATH}/v1/models", response_model=None)
+async def list_claude_gateway_models(
+ _: bool = Depends(verify_inference_api_key),
+) -> JSONResponse:
+ """List visible chat models using Claude Code's discovery ID format."""
+ return await _list_models(claude_gateway=True)
+
+
+async def _list_models(*, claude_gateway: bool = False) -> JSONResponse:
models = []
favorite_ids: set[str] = set()
if _server_state.engine_pool is not None:
status = _server_state.engine_pool.get_status()
model_types = {m["id"]: m.get("model_type") for m in status["models"]}
+ active_aliases = _active_model_aliases()
settings_manager = _server_state.settings_manager
hide_helpers = bool(
@@ -3815,12 +3988,10 @@ async def list_models(_: bool = Depends(verify_inference_api_key)) -> JSONRespon
excluded_model_ids: set[str] = set()
for m in status["models"]:
model_id = m["id"]
- display_id = model_id
+ display_id = active_aliases.get(model_id, model_id)
ms = None
if settings_manager:
ms = settings_manager.get_settings(model_id)
- if ms.model_alias:
- display_id = ms.model_alias
# Per-model hide: user-selected, always applied.
is_hidden = ms is not None and ms.is_hidden
# Global helper hide: skip drafters when the toggle is on. A model
@@ -3836,7 +4007,17 @@ async def list_models(_: bool = Depends(verify_inference_api_key)) -> JSONRespon
unservable = m.get("model_format") == "gguf" and bool(
await _server_state.engine_pool.external_engine_problem(model_id, ms)
)
- if is_hidden or is_hidden_helper or unservable:
+ if (
+ is_hidden
+ or is_hidden_helper
+ or unservable
+ or m.get("unavailable_reason")
+ ):
+ excluded_model_ids.add(model_id)
+ continue
+ if claude_gateway and (
+ m.get("model_type") not in ("llm", "vlm") or m.get("is_helper")
+ ):
excluded_model_ids.add(model_id)
continue
if ms is not None and ms.is_favorite:
@@ -3890,6 +4071,8 @@ async def list_models(_: bool = Depends(verify_inference_api_key)) -> JSONRespon
custom_aliases.add(_ms.model_alias)
created_at = datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
for slot_id, tier_model in tier_aliases.items():
+ if claude_gateway and tier_model in excluded_model_ids:
+ continue
if (
slot_id in existing_ids
or slot_id in physical_ids
@@ -3928,8 +4111,10 @@ async def list_models(_: bool = Depends(verify_inference_api_key)) -> JSONRespon
)
existing_ids.add(slot_id)
- if _markitdown_is_visible() and not any(
- m.id == MARKITDOWN_MODEL_ID for m in models
+ if (
+ not claude_gateway
+ and _markitdown_is_visible()
+ and not any(m.id == MARKITDOWN_MODEL_ID for m in models)
):
models.append(
ModelInfo(id=MARKITDOWN_MODEL_ID, owned_by="omlx", model_type="markitdown")
@@ -3939,6 +4124,23 @@ async def list_models(_: bool = Depends(verify_inference_api_key)) -> JSONRespon
if favorite_ids:
models.sort(key=lambda m: m.id not in favorite_ids)
+ if claude_gateway:
+ from .integrations.claude import claude_code_model_disabled_reason
+
+ data: list[ClaudeGatewayModelInfo] = [
+ {
+ "id": claude_gateway_model_id(m.id),
+ "display_name": m.display_name or m.id,
+ "max_model_len": m.max_model_len,
+ }
+ for m in models
+ if claude_code_model_disabled_reason(
+ {"max_context_window": m.max_model_len}
+ )
+ is None
+ ]
+ return JSONResponse(content={"data": data})
+
# Serialize explicitly: FastAPI's jsonable_encoder and the
# ``ModelsResponse`` container both serialize items as the base
# ``ModelInfo`` (dropping the tier metadata), while a route-level
@@ -3966,6 +4168,7 @@ async def list_models_status(_: bool = Depends(verify_api_key)):
status = _with_exposed_profile_status(
_with_markitdown_status(_server_state.engine_pool.get_status())
)
+ active_aliases = _active_model_aliases()
for m in status["models"]:
model_id = m["id"]
if is_markitdown_model(model_id):
@@ -3980,6 +4183,10 @@ async def list_models_status(_: bool = Depends(verify_api_key)):
m["reasoning_levels"] = reasoning_levels(m)
source_model_id = m.get("source_model_id") or model_id
+ # Let clients advertise thinking per model/profile instead of guessing
+ # from a served alias. Explicit template settings win over discovery.
+ m["enable_thinking"] = m.get("thinking_default")
+
# Resolve effective max_tokens: model setting > global default
max_tokens = _server_state.sampling.max_tokens
if _server_state.settings_manager:
@@ -3991,9 +4198,14 @@ async def list_models_status(_: bool = Depends(verify_api_key)):
)
else:
ms = sm.get_settings(source_model_id)
+ if source_model_id == model_id and model_id in active_aliases:
+ m["model_alias"] = active_aliases[model_id]
+ else:
+ m.pop("model_alias", None)
+ m["enable_thinking"] = merge_chat_template_request_kwargs(ms).get(
+ "enable_thinking", m["enable_thinking"]
+ )
base_ms = sm.get_settings(source_model_id)
- if base_ms and base_ms.model_alias and source_model_id == model_id:
- m["model_alias"] = base_ms.model_alias
m["is_favorite"] = base_ms is not None and base_ms.is_favorite
m["is_hidden"] = base_ms is not None and base_ms.is_hidden
if ms and ms.max_tokens is not None:
@@ -4036,9 +4248,20 @@ async def unload_model(model_id: str, _: bool = Depends(verify_api_key)):
return {"status": "ok", "model_id": model_id}
+async def _load_model_in_background(pool: EnginePool, model_id: str) -> None:
+ try:
+ await pool.get_engine(model_id)
+ except Exception:
+ logger.exception("Background model load failed for %s", model_id)
+ else:
+ logger.info("Background model load completed for %s", model_id)
+
+
@app.post("/v1/models/{model_id}/load")
-async def load_model_public(model_id: str, _: bool = Depends(verify_api_key)):
- """Load a discovered model into memory. Blocks until loading completes."""
+async def load_model_public(
+ model_id: str, _: bool = Depends(verify_api_key), wait: bool = True
+):
+ """Load a discovered model; wait=false acknowledges a background load."""
if _server_state.engine_pool is None:
raise HTTPException(status_code=503, detail="Server not initialized")
@@ -4052,6 +4275,23 @@ async def load_model_public(model_id: str, _: bool = Depends(verify_api_key)):
"message": f"Already loaded: {model_id}",
}
+ if not wait:
+ tasks = _server_state.model_load_tasks
+ if model_id not in tasks and not entry.is_loading:
+ task = asyncio.create_task(
+ _load_model_in_background(_server_state.engine_pool, model_id)
+ )
+ tasks[model_id] = task
+ task.add_done_callback(lambda _: tasks.pop(model_id, None))
+ return JSONResponse(
+ status_code=202,
+ content={
+ "status": "loading",
+ "model_id": model_id,
+ "message": f"Loading {model_id}",
+ },
+ )
+
try:
await _server_state.engine_pool.get_engine(model_id)
except ModelNotFoundError as e:
@@ -4523,9 +4763,9 @@ async def _chat_model_decisions(
engine, "supports_multimodal_fallback", False
)
- def _prepare_readout(messages):
+ async def _prepare_readout(messages):
try:
- num_prompt_tokens, prepared = _prepare_chat_prompt_for_request(
+ num_prompt_tokens, prepared = await _prepare_chat_prompt_for_request(
engine,
messages,
chat_template_kwargs=READOUT_TEMPLATE_KWARGS,
@@ -4895,6 +5135,11 @@ def _extract_chat_messages(
),
)
is_vlm = _engine_accepts_images(engine)
+ if has_audio_video_parts(request.messages) and not is_vlm:
+ raise HTTPException(
+ status_code=400,
+ detail="Audio/video inputs require a multimodal VLM model.",
+ )
extractor = getattr(engine, "message_extractor", None)
if extractor is not None:
extractor_kwargs = {}
@@ -5084,6 +5329,7 @@ async def create_chat_completion(
reasoning_parser = ms.reasoning_parser
settings_guided_grammar = _settings_guided_grammar(ms)
merged_ct_kwargs, thinking_budget = _merge_chat_template_kwargs(request, ms)
+ mm_processor_kwargs = _request_mm_processor_kwargs(engine, request, ms)
chat_messages = _extract_chat_messages(
request, engine, resolved_model, max_tool_result_tokens
@@ -5164,13 +5410,13 @@ async def create_chat_completion(
)
# Validate context window before sending to model
try:
- num_prompt_tokens, prepared_prompt = await _prepare_prompt_off_loop(
+ num_prompt_tokens, prepared_prompt = await _prepare_chat_prompt_for_request(
engine,
- _prepare_chat_prompt_for_request,
messages,
tools_for_template,
chat_template_kwargs=merged_ct_kwargs or None,
is_partial=is_partial,
+ mm_processor_kwargs=mm_processor_kwargs,
)
except Exception as e:
if _is_chat_template_error(e):
@@ -5265,6 +5511,8 @@ async def create_chat_completion(
# Add chat template kwargs
if merged_ct_kwargs:
chat_kwargs["chat_template_kwargs"] = merged_ct_kwargs
+ if mm_processor_kwargs:
+ chat_kwargs["mm_processor_kwargs"] = mm_processor_kwargs
# Forward partial-mode decision to the engine explicitly
chat_kwargs["is_partial"] = is_partial
@@ -6613,8 +6861,8 @@ async def stream_chat_completion(
messages: list,
request: ChatCompletionRequest,
model_load_duration: float = 0.0,
- resolved_model: Optional[str] = None,
- response_id: Optional[str] = None,
+ resolved_model: str | None = None,
+ response_id: str | None = None,
**kwargs,
) -> AsyncIterator[str]:
"""Stream chat completion response.
@@ -7335,7 +7583,7 @@ async def stream_anthropic_messages(
engine: BaseEngine,
messages: list,
request: AnthropicMessagesRequest,
- resolved_model: Optional[str] = None,
+ resolved_model: str | None = None,
**kwargs,
) -> AsyncIterator[str]:
"""
@@ -7802,6 +8050,7 @@ class _AnthropicPrompt:
messages: list[dict]
tools: list[dict] | None
chat_template_kwargs: dict
+ mm_processor_kwargs: dict[str, str | int]
is_partial: bool
native_reasoning: bool
thinking_budget: int | None
@@ -7824,8 +8073,12 @@ async def _prepare_anthropic_prompt(
max_tool_result_tokens = ms.max_tool_result_tokens
merged_ct_kwargs = merge_chat_template_request_kwargs(
ms,
- request.chat_template_kwargs,
+ merge_reasoning_effort_chat_template_kwargs(
+ request.chat_template_kwargs,
+ request.output_config.effort if request.output_config is not None else None,
+ ),
)
+ mm_processor_kwargs = _request_mm_processor_kwargs(engine, request, ms)
forced_keys = forced_ct_keys(ms)
_entry = get_engine_pool().get_entry(resolved_model)
@@ -7963,6 +8216,7 @@ async def _prepare_anthropic_prompt(
messages=messages,
tools=internal_tools,
chat_template_kwargs=merged_ct_kwargs,
+ mm_processor_kwargs=mm_processor_kwargs,
is_partial=is_partial,
native_reasoning=native_reasoning,
thinking_budget=thinking_budget,
@@ -7970,16 +8224,17 @@ async def _prepare_anthropic_prompt(
)
-def _count_anthropic_prompt(
+async def _count_anthropic_prompt(
engine: BaseEngine, prompt: _AnthropicPrompt
) -> tuple[int, tuple[str, list[int]] | None]:
try:
- return _prepare_chat_prompt_for_request(
+ return await _prepare_chat_prompt_for_request(
engine,
prompt.messages,
prompt.tools,
chat_template_kwargs=prompt.chat_template_kwargs or None,
is_partial=prompt.is_partial,
+ mm_processor_kwargs=prompt.mm_processor_kwargs,
)
except Exception as e:
if _is_chat_template_error(e):
@@ -7987,6 +8242,19 @@ def _count_anthropic_prompt(
raise
+@app.post(f"{CLAUDE_GATEWAY_PATH}/v1/messages")
+async def create_claude_gateway_message(
+ request: AnthropicMessagesRequest,
+ http_request: FastAPIRequest,
+ _: bool = Depends(verify_inference_api_key),
+):
+ return await create_anthropic_message(
+ request.model_copy(update={"model": claude_gateway_served_id(request.model)}),
+ http_request,
+ _,
+ )
+
+
@app.post("/v1/messages")
async def create_anthropic_message(
request: AnthropicMessagesRequest,
@@ -8037,6 +8305,7 @@ async def create_anthropic_message(
messages = prompt.messages
internal_tools = prompt.tools
merged_ct_kwargs = prompt.chat_template_kwargs
+ mm_processor_kwargs = prompt.mm_processor_kwargs
ms = prompt.model_settings
# Prepare kwargs
@@ -8096,6 +8365,8 @@ async def create_anthropic_message(
# Add chat template kwargs
if merged_ct_kwargs:
chat_kwargs["chat_template_kwargs"] = merged_ct_kwargs
+ if mm_processor_kwargs:
+ chat_kwargs["mm_processor_kwargs"] = mm_processor_kwargs
# Forward partial-mode decision to the engine explicitly
chat_kwargs["is_partial"] = prompt.is_partial
@@ -8107,9 +8378,7 @@ async def create_anthropic_message(
chat_kwargs.update(_cache_store_kwargs(http_request))
# Validate context window before sending to model
- num_prompt_tokens, prepared_prompt = await _prepare_prompt_off_loop(
- engine, _count_anthropic_prompt, prompt
- )
+ num_prompt_tokens, prepared_prompt = await _count_anthropic_prompt(engine, prompt)
validate_context_window(num_prompt_tokens, request.model)
if prepared_prompt is not None:
@@ -8276,6 +8545,17 @@ async def _build_anthropic_message():
raise
+@app.post(f"{CLAUDE_GATEWAY_PATH}/v1/messages/count_tokens")
+async def count_claude_gateway_tokens(
+ request: TokenCountRequest,
+ _: bool = Depends(verify_inference_api_key),
+):
+ return await count_anthropic_tokens(
+ request.model_copy(update={"model": claude_gateway_served_id(request.model)}),
+ _,
+ )
+
+
@app.post("/v1/messages/count_tokens")
async def count_anthropic_tokens(
request: TokenCountRequest,
@@ -8313,11 +8593,11 @@ async def count_anthropic_tokens(
tools=request.tools,
tool_choice=request.tool_choice,
thinking=request.thinking,
+ output_config=request.output_config,
+ mm_processor_kwargs=request.mm_processor_kwargs,
)
prompt = await _prepare_anthropic_prompt(temp_request, engine, resolved_model)
- input_tokens, _ = await _prepare_prompt_off_loop(
- engine, _count_anthropic_prompt, prompt
- )
+ input_tokens, _ = await _count_anthropic_prompt(engine, prompt)
logger.debug(
f"Token count: {input_tokens} tokens for {len(prompt.messages)} messages"
)
@@ -8580,7 +8860,7 @@ async def detokenize(
# =============================================================================
-def _should_store_response(store_flag: Optional[bool]) -> bool:
+def _should_store_response(store_flag: bool | None) -> bool:
"""OpenAI Responses defaults to storing responses unless explicitly disabled."""
return store_flag is not False
@@ -8657,10 +8937,12 @@ async def create_response(
# payloads never reach the prompt (#2989).
preserve_tool_images = _engine_accepts_images(engine)
- current_input_messages = convert_responses_input_to_messages(
- request.input,
- consolidate_system_messages=False,
- preserve_images=preserve_tool_images,
+ current_input_messages = normalize_chat_messages_for_response_store(
+ convert_responses_input_to_messages(
+ request.input,
+ consolidate_system_messages=False,
+ preserve_images=preserve_tool_images,
+ )
)
# Build previous context from previous_response_id
@@ -8683,6 +8965,7 @@ async def create_response(
# can reject reasoning_content, which transformers renders as thinking.
for msg in messages:
msg.pop("reasoning_content", None)
+ messages = await _preprocess_response_files_for_llm(messages)
# Convert tools: flat → nested. namespace_aliases maps each expanded
# namespace member's wire name back for the return path.
@@ -8717,6 +9000,7 @@ async def create_response(
),
)
+ mm_processor_kwargs = _request_mm_processor_kwargs(engine, request, ms)
# Auto-set enable_thinking when a positive thinking budget is active.
# Set it before grammar compilation, which reads the thinking state.
thinking_budget = _resolve_thinking_budget(request, request.model)
@@ -8829,14 +9113,25 @@ async def create_response(
unsupported_mid_system_policy=_unsupported_mid_system_policy(),
)
+ is_vlm = isinstance(engine, VLMBatchedEngine) or getattr(
+ engine,
+ "supports_multimodal_fallback",
+ False,
+ )
+ if has_audio_video_parts(messages) and not is_vlm:
+ raise HTTPException(
+ status_code=400,
+ detail="Audio/video inputs require a multimodal VLM model.",
+ )
+
# Validate context window
try:
- num_prompt_tokens, prepared_prompt = await _prepare_prompt_off_loop(
+ num_prompt_tokens, prepared_prompt = await _prepare_chat_prompt_for_request(
engine,
- _prepare_chat_prompt_for_request,
messages,
tools_for_template,
chat_template_kwargs=merged_ct_kwargs or None,
+ mm_processor_kwargs=mm_processor_kwargs,
)
except Exception as e:
err_name = type(e).__name__.lower()
@@ -8917,6 +9212,8 @@ async def create_response(
chat_kwargs["tools"] = tools_for_template
if merged_ct_kwargs:
chat_kwargs["chat_template_kwargs"] = merged_ct_kwargs
+ if mm_processor_kwargs:
+ chat_kwargs["mm_processor_kwargs"] = mm_processor_kwargs
chat_kwargs["preserve_reasoning"] = cache_reasoning_output(
ms,
@@ -9172,10 +9469,10 @@ async def stream_responses_api(
engine: BaseEngine,
messages: list,
request: ResponsesRequest,
- input_messages: Optional[list[dict]] = None,
+ input_messages: list[dict] | None = None,
store_response: bool = True,
model_load_duration: float = 0.0,
- resolved_model: Optional[str] = None,
+ resolved_model: str | None = None,
response_format=None,
namespace_aliases: Optional[dict] = None,
stream_state: _ResponsesStreamState | None = None,
@@ -9222,8 +9519,8 @@ async def stream_responses_api(
reasoning_closed = False
message_opened = False
next_output_index = 0
- reasoning_output_index: Optional[int] = None # captured when reasoning opens
- msg_output_index: Optional[int] = None # captured when message opens
+ reasoning_output_index: int | None = None # captured when reasoning opens
+ msg_output_index: int | None = None # captured when message opens
# Build initial response object (in_progress, empty output)
initial_response = ResponseObject(
diff --git a/omlx/specprefill/planning.py b/omlx/specprefill/planning.py
index 1bf0d87a97..eb5f47470e 100644
--- a/omlx/specprefill/planning.py
+++ b/omlx/specprefill/planning.py
@@ -19,6 +19,7 @@ class SpecPrefillTargetPlan:
sparse_selected_token_count: int
total_tracker_prefill_count: int
position_offset: int
+ sparse_selected_indices: Sequence[int] | None = None
def plan_specprefill_target(
@@ -35,7 +36,11 @@ def plan_specprefill_target(
# BatchGenerator processes the generation-kickoff token separately.
remove_kickoff_index = generation_kickoff_index in selected_indices
- sparse_selected_token_count = len(selected_indices) - int(remove_kickoff_index)
+ sparse_selected_indices = list(selected_indices)
+ if remove_kickoff_index:
+ sparse_selected_indices.remove(generation_kickoff_index)
+ sparse_selected_indices.sort()
+ sparse_selected_token_count = len(sparse_selected_indices)
return SpecPrefillTargetPlan(
system_token_count=system_token_count,
@@ -48,4 +53,5 @@ def plan_specprefill_target(
system_token_count + sparse_selected_token_count
),
position_offset=position_offset,
+ sparse_selected_indices=sparse_selected_indices,
)
diff --git a/omlx/specprefill/target.py b/omlx/specprefill/target.py
index e82bf758bf..e03946f3aa 100644
--- a/omlx/specprefill/target.py
+++ b/omlx/specprefill/target.py
@@ -48,12 +48,18 @@ def store_exact_prefix(
CheckAbort = Callable[[int], None]
ReportProgress = Callable[[int, int], None]
SyncAndClearCache = Callable[[], None]
+EvalCacheStates = Callable[[list[Any]], None]
# Issue #2177: helper signature mirroring Scheduler._extract_cache_states.
# Returns the per-layer extracted state dicts and an optional ModelCacheConfig.
ExtractCacheStates = Callable[[list[Any]], tuple[list[dict[str, Any]], Any | None]]
PreparePromptCache = Callable[[list[Any]], None]
+def _eval_cache_states(cache_layers: list[Any]) -> None:
+ """Materialize prompt-cache states with MLX's standard cache layout."""
+ mx.eval([cache_layer.state for cache_layer in cache_layers])
+
+
def run_specprefill_target_prefill(
*,
target_model: Any,
@@ -68,6 +74,7 @@ def run_specprefill_target_prefill(
report_sparse_progress: ReportProgress,
sync_and_clear_cache: SyncAndClearCache,
log: logging.Logger,
+ eval_cache_states: EvalCacheStates | None = None,
# Issue #2177: opt-in static system/tool prefix reuse. When the cache,
# tokens, and extraction callback are provided, the first request stores
# the prefetched system state in the tiered cache; later requests restore
@@ -104,6 +111,7 @@ def run_specprefill_target_prefill(
conversation_token_count = plan.conversation_token_count
generation_kickoff_index = plan.generation_kickoff_index
prefill_started_at = time.monotonic()
+ cache_evaluator = eval_cache_states or _eval_cache_states
prompt_cache = (
request.prompt_cache
if request.cached_tokens > 0 and request.prompt_cache is not None
@@ -152,7 +160,7 @@ def run_specprefill_target_prefill(
report_system_progress(system_processed, system_token_count)
with mx.stream(stream):
target_model(sys_arr[:prefill_step_size][None], cache=prompt_cache)
- mx.eval([cache_layer.state for cache_layer in prompt_cache])
+ cache_evaluator(prompt_cache)
# Keep the next chunk view on the target-model stream.
sys_arr = sys_arr[prefill_step_size:]
system_processed += prefill_step_size
@@ -166,7 +174,7 @@ def run_specprefill_target_prefill(
report_system_progress(system_processed, system_token_count)
with mx.stream(stream):
target_model(sys_arr[None], cache=prompt_cache)
- mx.eval([cache_layer.state for cache_layer in prompt_cache])
+ cache_evaluator(prompt_cache)
system_processed += final_system_token_count
check_abort(system_processed)
report_system_progress(system_processed, system_token_count)
@@ -201,9 +209,12 @@ def run_specprefill_target_prefill(
selected = selected_indices
# BatchGenerator processes the generation-kickoff token separately.
if plan.remove_kickoff_index:
- selected_indices_list = selected.tolist()
- selected_indices_list.remove(generation_kickoff_index)
- selected = mx.array(sorted(selected_indices_list))
+ selected_indices_list = plan.sparse_selected_indices
+ if selected_indices_list is None:
+ selected_indices_list = selected.tolist()
+ selected_indices_list.remove(generation_kickoff_index)
+ selected_indices_list.sort()
+ selected = mx.array(selected_indices_list)
with mx.stream(stream):
sparse_prefill(
diff --git a/omlx/turboquant_kv.py b/omlx/turboquant_kv.py
index b9a9bd8a43..17b534fbef 100644
--- a/omlx/turboquant_kv.py
+++ b/omlx/turboquant_kv.py
@@ -11,12 +11,9 @@
import logging
import math
-from typing import List, Optional
import mlx.core as mx
from mlx_lm.models.cache import (
- KVCache,
- _BaseCache,
create_attention_mask,
create_causal_mask,
dynamic_roll,
@@ -31,13 +28,9 @@
_build_codec,
_concat_state,
_QuantizedStateProxy,
- _reserve_state_capacity,
_slice_state,
_slice_state_range,
- _state_length,
- _state_nbytes,
- _validate_bits,
- _write_state,
+ _state_length, # noqa: F401 - re-exported for local attention/cache helpers
turboquant_enabled,
)
@@ -408,7 +401,7 @@ def _has_left_padding(self) -> bool:
self._left_padded = bool(mx.any(self._left_padding).item())
return self._left_padded
- def __init__(self, left_padding: List[int], bits: float = 4.0, seed: int = 0):
+ def __init__(self, left_padding: list[int], bits: float = 4.0, seed: int = 0):
super().__init__(bits=bits, seed=seed)
self.group_size = 0
self.left_padding = mx.array(left_padding)
@@ -579,7 +572,7 @@ def make_mask(
self,
N: int,
return_array: bool = False,
- window_size: Optional[int] = None,
+ window_size: int | None = None,
):
offset = self.offset
if isinstance(offset, int):
@@ -695,7 +688,7 @@ def filter(self, batch_indices):
self._cached_state = None
self._cached_state_offset = -1
- def extend(self, other: "BatchTurboQuantKVCache"):
+ def extend(self, other: BatchTurboQuantKVCache):
if not isinstance(other, BatchTurboQuantKVCache):
raise TypeError(
"BatchTurboQuantKVCache.extend expected BatchTurboQuantKVCache, "
@@ -786,7 +779,7 @@ def extract(self, idx: int) -> TurboQuantKVCache:
return tq
@classmethod
- def merge(cls, caches: List[TurboQuantKVCache]) -> "BatchTurboQuantKVCache":
+ def merge(cls, caches: list[TurboQuantKVCache]) -> BatchTurboQuantKVCache:
for cache in caches:
if not isinstance(cache, TurboQuantKVCache):
raise TypeError(
diff --git a/omlx/utils/model_loading.py b/omlx/utils/model_loading.py
index 886b1b3c12..119adbd673 100644
--- a/omlx/utils/model_loading.py
+++ b/omlx/utils/model_loading.py
@@ -313,6 +313,36 @@ def expand_glm_moe_dsa_fused_quant_keys(cfg: dict) -> dict:
return cfg
+def normalize_encoder_quantization_config(cfg: dict[str, Any]) -> dict[str, Any]:
+ """Translate legacy encoder quantization metadata for mlx-vlm."""
+ if "quantization" in cfg:
+ return cfg
+
+ quantization_config = cfg.get("quantization_config")
+ if quantization_config is None:
+ quantization_config = (cfg.get("text_config") or {}).get("quantization_config")
+ if quantization_config is not None:
+ cfg["quantization_config"] = quantization_config
+ if quantization_config is None:
+ return cfg
+
+ method = quantization_config.get("quant_method")
+ formats = {
+ "compressed-tensors": (32, 4, "affine"),
+ "mxfp4": (32, 4, "mxfp4"),
+ "nvfp4": (16, 4, "nvfp4"),
+ "mxfp8": (32, 8, "mxfp8"),
+ }
+ if method in formats:
+ group_size, bits, mode = formats[method]
+ quantization = {"group_size": group_size, "bits": bits, "mode": mode}
+ cfg["quantization"] = quantization
+ cfg["quantization_config"] = quantization
+ elif method in ("awq", "gptq", "bitnet"):
+ logger.warning("Quantization method %s is not supported for encoders", method)
+ return cfg
+
+
def normalize_qwen35_text_config(cfg: dict) -> dict:
"""Use mlx-lm's Qwen3.5 names for text-only Hugging Face checkpoints."""
model_type = cfg.get("model_type")
@@ -647,6 +677,13 @@ def maybe_apply_pre_load_patches(
apply_qwen35_yarn_patch()
set_context_window(model_name, getattr(model_settings, "max_context_window", None))
+ # Model-independent: mlx-lm hybrid caches must combine left- and
+ # right-padding constraints, and filtering an empty BatchKVCache must not
+ # move its logical offset below zero.
+ from ..patches.hybrid_batch_cache import apply_hybrid_batch_cache_fixes
+
+ apply_hybrid_batch_cache_fixes()
+
config_path = Path(model_name) / "config.json"
if not config_path.exists():
return
@@ -846,6 +883,17 @@ def maybe_apply_pre_load_patches(
model_name,
)
+ if for_vlm and model_type == "bailing_moe_v3_vl":
+ from ..patches.mlx_vlm_bailing_moe_v3_vl_compat import (
+ apply_mlx_vlm_bailing_moe_v3_vl_compat_patch,
+ )
+
+ if apply_mlx_vlm_bailing_moe_v3_vl_compat_patch():
+ logger.info(
+ "Ling 3.0 Flash VL mlx-vlm compatibility patch applied for %s",
+ model_name,
+ )
+
if for_vlm and model_type == "muse_glimmer":
from ..patches.mlx_vlm_muse_glimmer_compat import (
apply_mlx_vlm_muse_glimmer_compat_patch,
@@ -857,6 +905,15 @@ def maybe_apply_pre_load_patches(
model_name,
)
+ if for_vlm and model_type == "minicpmv4_7":
+ from ..patches.minicpm47 import (
+ apply_minicpm47_serving_patch,
+ validate_target_config,
+ )
+
+ validate_target_config(config)
+ apply_minicpm47_serving_patch()
+
if for_vlm and model_type == "qwen4_exp":
from ..patches.mlx_vlm_qwen4_exp_compat import (
apply_mlx_vlm_qwen4_exp_compat_patch,
@@ -871,9 +928,9 @@ def maybe_apply_pre_load_patches(
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:
+ mtp_checkpoint_prefix = _checkpoint_qwen4_mtp_weight_prefix(model_name)
+ mtp_active = mtp_requested and mtp_checkpoint_prefix is not None
+ if mtp_requested and mtp_checkpoint_prefix is None:
logger.warning(
"Qwen4-Exp Lightning MTP was requested for %s, but no embedded "
"MTP tensors were found",
@@ -893,13 +950,14 @@ def maybe_apply_pre_load_patches(
else None
)
fixed = getattr(model_settings, "mtp_fixed_depth", 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.
if fixed:
set_mtp_depth(int(fixed), fixed=True)
else:
- set_mtp_depth(int(depth) if depth else 3)
+ sidecar_depth = _qwen4_mtp_sidecar_draft_depth(model_name)
+ set_mtp_depth(
+ int(depth) if depth is not None
+ else sidecar_depth if sidecar_depth is not None else 3
+ )
if mtp_active and not apply_mlx_lm_mtp_patch():
logger.warning(
"Qwen4-Exp Lightning MTP dispatch patch failed for %s; "
@@ -938,13 +996,6 @@ def maybe_apply_pre_load_patches(
# corrupts the output (garbage tokens). PR 990's sanitize gates the
# shift on "unsanitized conv1d" instead.
#
- # Whether the model actually attaches an MTP head — and therefore
- # whether BatchGenerator runs the MTP draft+verify cycle — is gated
- # by a process-wide flag set just before mlx_lm.load() runs. With
- # mtp_enabled=False the patch is still active so sanitize behaves
- # correctly, but Model.__init__ skips ``self.mtp = MTPModule(args)``;
- # the resulting model is indistinguishable from a stock model that
- # never had MTP heads.
# The batched DFlash drafter rides the Lightning MTP verify path, so its
# patches are installed even when the checkpoint declares no MTP heads.
dflash_batched = dflash_batched_supported(
@@ -963,9 +1014,27 @@ def maybe_apply_pre_load_patches(
# Inkling 2 bundles its DSpark draft as mtp.safetensors.
minimax_dspark = bundled_inkling2_dspark_path(model_name)
if _is_mtp_compatible(config, model_type) or dflash_batched or minimax_dspark:
- mtp_enabled = bool(
+ mtp_requested = bool(
model_settings is not None and getattr(model_settings, "mtp_enabled", False)
)
+ # A VLM config can retain mtp_num_hidden_layers after conversion
+ # stripped the actual head tensors. Keep the construction-time decode
+ # flag off unless both the user toggle and persisted native head agree;
+ # the independent attach flag below still binds real heads when decode
+ # is disabled so strict mlx-vlm loading remains lossless.
+ mtp_enabled = (
+ (
+ bool(mtp_requested and minimax_dspark)
+ or _native_vlm_mtp_eligible(
+ config,
+ model_type,
+ model_settings,
+ has_mtp_weights=bool(has_mtp_weights),
+ )
+ )
+ if for_vlm
+ else mtp_requested
+ )
from ..patches.mlx_lm_mtp import (
apply_mlx_lm_mtp_patch,
set_mtp_active,
@@ -993,8 +1062,14 @@ def maybe_apply_pre_load_patches(
):
# Qwen 27B keeps an adaptive ceiling of at least four tokens.
set_mtp_depth(max(4, int(depth or 4)))
- elif depth:
+ elif depth is not None:
set_mtp_depth(int(depth))
+ elif model_type.startswith(("qwen3_5", "qwen3_6")):
+ sidecar_depth = _qwen35_mtp_sidecar_draft_depth(model_name)
+ set_mtp_depth(
+ sidecar_depth if sidecar_depth is not None
+ else 4 if model_type == "qwen3_5" and _nax_available() else 3
+ )
elif model_type.startswith("nemotron_h"):
# The stock nemotron_h head is depth-1 trained; the adaptive
# controller's exploration costs ~10% throughput vs fixed
@@ -1014,10 +1089,6 @@ def maybe_apply_pre_load_patches(
set_mtp_depth(
int(mtp_cfg.get("num_nextn_predict_layers", 0) or 0) or 3
)
- elif model_type == "qwen3_5" and _nax_available():
- # The M5 packed verify kernels keep a 5-row verify close to
- # a 4-row one on dense Qwen, so depth 4 pays there.
- set_mtp_depth(4)
else:
set_mtp_depth(3)
if mtp_enabled:
@@ -1046,10 +1117,16 @@ def maybe_apply_pre_load_patches(
backend,
model_type,
)
+ elif for_vlm and mtp_requested and not has_mtp_weights:
+ logger.warning(
+ "Native VLM MTP requested for %s but no persisted MTP "
+ "weights were found; standard decode remains active",
+ model_name,
+ )
else:
logger.debug(
"Native MTP patch applied for %s for sanitize correctness "
- "(model has MTP heads but mtp_enabled=False; head not attached)",
+ "(model has MTP heads but native decode is disabled)",
model_name,
)
@@ -1212,7 +1289,7 @@ def _has_mtp_heads(config: dict) -> bool:
return True
if int(config.get("num_nextn_predict_layers", 0) or 0) > 0:
return True
- text_cfg = config.get("text_config") or {}
+ text_cfg = config.get("text_config") or config.get("llm_config") or {}
if int(text_cfg.get("mtp_num_hidden_layers", 0) or 0) > 0:
return True
if int(text_cfg.get("num_nextn_predict_layers", 0) or 0) > 0:
@@ -1315,8 +1392,114 @@ def _checkpoint_weight_prefix(
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)
+ """Return the Qwen4 MTP checkpoint layout supported by the runtime."""
+ embedded_prefix = _checkpoint_weight_prefix(model_path, _MTP_WEIGHT_PREFIXES)
+ if embedded_prefix is not None:
+ return embedded_prefix
+
+ sidecar_path = _qwen4_mtp_sidecar_path(model_path)
+ if sidecar_path is None:
+ return None
+ sidecar_prefix = _checkpoint_weight_prefix(
+ sidecar_path,
+ ("fc_embedding.", "fc_hidden.", "layers."),
+ )
+ return "mtp/" if sidecar_prefix is not None else None
+
+
+def _qwen4_mtp_sidecar_config(
+ model_path: str | Path,
+) -> tuple[Path, dict[str, Any]] | None:
+ """Return the validated standalone Qwen4 Lightning MTP sidecar config."""
+ return _qwen_mtp_sidecar_config(
+ model_path,
+ family="Qwen4",
+ expected_model_type="qwen4_exp_mtp",
+ )
+
+
+def _qwen_mtp_sidecar_config(
+ model_path: str | Path,
+ *,
+ family: str,
+ expected_model_type: str,
+) -> tuple[Path, dict[str, Any]] | None:
+ """Return a validated standalone Qwen MTP sidecar config."""
+ model_path = Path(model_path)
+ sidecar_path = model_path / "mtp"
+ config_path = sidecar_path / "config.json"
+ if not config_path.is_file():
+ return None
+ try:
+ config = json.loads(config_path.read_text(encoding="utf-8"))
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError) as e:
+ logger.debug(
+ "Failed to read %s MTP sidecar config %s: %s",
+ family,
+ config_path,
+ e,
+ )
+ return None
+ if not isinstance(config, dict):
+ logger.warning(
+ "%s MTP sidecar config %s must contain an object",
+ family,
+ config_path,
+ )
+ return None
+ if config.get("model_type") != expected_model_type:
+ return None
+ return sidecar_path, config
+
+
+def _qwen4_mtp_sidecar_path(model_path: str | Path) -> Path | None:
+ """Resolve a standalone Qwen4 Lightning MTP checkpoint directory."""
+ sidecar = _qwen4_mtp_sidecar_config(model_path)
+ return sidecar[0] if sidecar is not None else None
+
+
+def _qwen4_mtp_sidecar_draft_depth(model_path: str | Path) -> int | None:
+ """Map a Qwen4 MTP sidecar's verify block size to native draft depth."""
+ sidecar = _qwen4_mtp_sidecar_config(model_path)
+ return _qwen_mtp_sidecar_draft_depth(sidecar, family="Qwen4")
+
+
+def _qwen35_mtp_sidecar_draft_depth(model_path: str | Path) -> int | None:
+ """Map a Qwen3.5/3.6 MTP sidecar block size to native draft depth."""
+ sidecar = _qwen_mtp_sidecar_config(
+ model_path,
+ family="Qwen3",
+ expected_model_type="qwen3_5_mtp",
+ )
+ return _qwen_mtp_sidecar_draft_depth(sidecar, family="Qwen3")
+
+
+def _qwen_mtp_sidecar_draft_depth(
+ sidecar: tuple[Path, dict[str, Any]] | None,
+ *,
+ family: str,
+) -> int | None:
+ """Map a Qwen sidecar's verify block size to native draft depth."""
+ if sidecar is None:
+ return None
+
+ sidecar_path, config = sidecar
+ config_path = sidecar_path / "config.json"
+ block_size = config.get("block_size")
+ if (
+ isinstance(block_size, bool)
+ or not isinstance(block_size, int)
+ or block_size < 2
+ ):
+ logger.warning(
+ "%s MTP sidecar config %s has invalid block_size=%r; "
+ "using the native default draft depth",
+ family,
+ config_path,
+ block_size,
+ )
+ return None
+ return block_size - 1
def _checkpoint_has_mtp_weights(model_path: str | Path) -> bool:
@@ -1339,6 +1522,17 @@ def _checkpoint_has_mtp_weights(model_path: str | Path) -> bool:
``mtp/model_mtp.safetensors`` sidecar. If neither contains MTP weights,
callers skip attaching the MTP module.
"""
+ from ..model_classification import is_nemotron_omni
+
+ config_path = Path(model_path) / "config.json"
+ if is_nemotron_omni(_config_model_type(model_path)):
+ config = json.loads(config_path.read_text())
+ if config.get("omlx_mtp") is not None:
+ from ..patches.nemotron_omni_quantization import native_mtp_sidecar
+
+ return native_mtp_sidecar(model_path, config) is not None
+ if _checkpoint_qwen4_mtp_weight_prefix(model_path) is not None:
+ return True
prefixes = _MTP_WEIGHT_PREFIXES + _nextn_weight_prefixes(model_path)
if _checkpoint_weight_prefix(model_path, prefixes) is not None:
return True
@@ -1423,6 +1617,27 @@ def _nax_available() -> bool:
return bool(is_nax_available())
+def _native_vlm_mtp_eligible(
+ config: dict,
+ model_type: str | None,
+ model_settings: Any | None,
+ *,
+ has_mtp_weights: bool,
+) -> bool:
+ """True iff a VLM load may enable native-head MTP decode.
+
+ Head attachment is intentionally a separate decision: mlx-vlm must bind
+ persisted ``mtp.*`` tensors even when decode is disabled. This predicate
+ controls only BatchGenerator draft+verify activation.
+ """
+ return bool(
+ model_settings is not None
+ and getattr(model_settings, "mtp_enabled", False)
+ and has_mtp_weights
+ and _is_mtp_compatible(config, model_type)
+ )
+
+
def _is_mtp_compatible(config: dict, model_type: str | None) -> bool:
"""Decide whether the Lightning MTP patch can be applied to this model.
@@ -1436,6 +1651,10 @@ def _is_mtp_compatible(config: dict, model_type: str | None) -> bool:
return False
if not model_type:
return False
+ from ..model_classification import is_nemotron_omni
+
+ if is_nemotron_omni(model_type):
+ return True
return (
model_type.startswith("qwen3_5")
or model_type.startswith("qwen3_6")
diff --git a/omlx/utils/optional_deps.py b/omlx/utils/optional_deps.py
new file mode 100644
index 0000000000..9bc480bee4
--- /dev/null
+++ b/omlx/utils/optional_deps.py
@@ -0,0 +1,23 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Helpers for runtime dependencies with optional feature surfaces."""
+
+from __future__ import annotations
+
+from importlib.util import find_spec
+
+MLX_VLM_PACKAGE = "mlx_vlm"
+MLX_VLM_MISSING_MESSAGE = (
+ "mlx-vlm image support is unavailable or incompatible. Reinstall oMLX to "
+ "restore its required mlx-vlm dependency."
+)
+
+
+def is_mlx_vlm_available() -> bool:
+ """Return whether the required mlx-vlm package can be imported."""
+ return find_spec(MLX_VLM_PACKAGE) is not None
+
+
+def require_mlx_vlm_available() -> None:
+ """Raise a clear error when the core mlx-vlm dependency is unavailable."""
+ if not is_mlx_vlm_available():
+ raise ImportError(MLX_VLM_MISSING_MESSAGE)
diff --git a/omlx/utils/safetensors_shards.py b/omlx/utils/safetensors_shards.py
new file mode 100644
index 0000000000..ba7621229d
--- /dev/null
+++ b/omlx/utils/safetensors_shards.py
@@ -0,0 +1,62 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Helpers for selecting model safetensors shards."""
+
+from __future__ import annotations
+
+import logging
+import re
+from pathlib import Path
+
+logger = logging.getLogger(__name__)
+
+_MODEL_SHARD_RE = re.compile(r"^model-(\d+)-of-(\d+)\.safetensors$")
+
+
+def select_safetensors_weight_files(model_path: Path) -> list[Path]:
+ """Return safetensors files, choosing one complete numbered shard set.
+
+ Some interrupted downloads can leave multiple concurrent
+ ``model-NNNNN-of-MMMMM.safetensors`` sets in the same directory. When a
+ complete numbered set exists, this helper returns only the largest complete
+ set so header scans and size estimates do not mix stale and current shards.
+ Non-numbered single-file checkpoints are returned unchanged.
+ """
+
+ files = sorted(path for path in model_path.glob("*.safetensors") if path.is_file())
+ numbered: dict[int, dict[int, Path]] = {}
+ for path in files:
+ match = _MODEL_SHARD_RE.match(path.name)
+ if match is None:
+ continue
+ index = int(match.group(1))
+ total = int(match.group(2))
+ numbered.setdefault(total, {})[index] = path
+
+ if not numbered:
+ return files
+
+ complete_sets: list[tuple[int, list[Path]]] = []
+ for total, by_index in numbered.items():
+ expected = set(range(1, total + 1))
+ if set(by_index) == expected:
+ complete_sets.append(
+ (total, [by_index[index] for index in sorted(by_index)])
+ )
+
+ if not complete_sets:
+ return files
+
+ total, selected = max(complete_sets, key=lambda item: item[0])
+ selected_names = {path.name for path in selected}
+ if len(numbered) > 1 or any(
+ _MODEL_SHARD_RE.match(path.name) and path.name not in selected_names
+ for path in files
+ ):
+ logger.warning(
+ "Multiple safetensors shard sets found in %s; using complete "
+ "model-*-of-%05d set (%d file(s)) and ignoring stale/incomplete shards",
+ model_path,
+ total,
+ len(selected),
+ )
+ return selected
diff --git a/omlx/utils/sampling.py b/omlx/utils/sampling.py
index 0e40c4a815..ebd9a95942 100644
--- a/omlx/utils/sampling.py
+++ b/omlx/utils/sampling.py
@@ -18,7 +18,7 @@
import functools
import math
-from typing import Callable, List, Optional, Sequence
+from collections.abc import Callable, Sequence
import mlx.core as mx
import numpy as np
@@ -148,7 +148,7 @@ def apply_xtc(
logits: mx.array,
xtc_probability: float,
xtc_threshold: float,
- xtc_special_tokens: List[int],
+ xtc_special_tokens: list[int],
) -> mx.array:
"""XTC sampling — with ``xtc_probability``, mask out all but the lowest
above-threshold token to encourage diversity."""
@@ -218,7 +218,7 @@ def make_sampler(
top_k: int = 0,
xtc_probability: float = 0.0,
xtc_threshold: float = 0.0,
- xtc_special_tokens: Optional[List[int]] = None,
+ xtc_special_tokens: list[int] | None = None,
) -> Callable[[mx.array], mx.array]:
"""Build a sampler callable matching ``mlx_lm.sample_utils.make_sampler``.
diff --git a/omlx/utils/tokenizer.py b/omlx/utils/tokenizer.py
index 4b1da1decf..287d19aee1 100644
--- a/omlx/utils/tokenizer.py
+++ b/omlx/utils/tokenizer.py
@@ -474,6 +474,24 @@ def last_segment(self) -> str:
return segment
+class _DecodeOnlyTokenizerAdapter:
+ """Adapt decode-only tokenizers to mlx-lm's naive detokenizer probe."""
+
+ def __init__(self, tokenizer: Any):
+ self._tokenizer = tokenizer
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._tokenizer, name)
+
+ def decode(self, *args: Any, **kwargs: Any) -> Any:
+ return self._tokenizer.decode(*args, **kwargs)
+
+ def encode(self, text: str, add_special_tokens: bool = False) -> list[int]:
+ if text == "a ,b" and add_special_tokens is False:
+ return []
+ raise AttributeError("decode-only tokenizer does not support encode")
+
+
def create_streaming_detokenizer(
tokenizer: Any,
model_path: str | Path | None = None,
@@ -544,6 +562,17 @@ def create_streaming_detokenizer(
try:
return NaiveStreamingDetokenizer(tokenizer)
+ except AttributeError as exc:
+ if not hasattr(tokenizer, "encode"):
+ try:
+ return NaiveStreamingDetokenizer(_DecodeOnlyTokenizerAdapter(tokenizer))
+ except Exception as adapter_exc:
+ logger.debug(
+ "Failed to create naive streaming detokenizer with "
+ "decode-only tokenizer adapter: %s",
+ adapter_exc,
+ )
+ logger.debug("Failed to create naive streaming detokenizer: %s", exc)
except Exception as exc:
logger.debug("Failed to create naive streaming detokenizer: %s", exc)
diff --git a/tests/conftest.py b/tests/conftest.py
index fe6eded48a..f7da42c76d 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -394,6 +394,26 @@ def write(path: Path, metadata: dict, size: int = 0) -> Path:
return write
+@pytest.fixture
+def write_z_image_checkpoint():
+ pytest.importorskip("mlx_vlm")
+
+ def write(path: Path, weight_size: int = 100) -> Path:
+ (path / "model_index.json").parent.mkdir(parents=True, exist_ok=True)
+ (path / "model_index.json").write_text('{"_class_name": "ZImagePipeline"}')
+ for component in ("transformer", "text_encoder", "vae"):
+ (path / component).mkdir()
+ (path / component / "config.json").write_text("{}")
+ (path / component / "model.safetensors").write_bytes(b"0" * weight_size)
+ (path / "scheduler").mkdir()
+ (path / "scheduler" / "scheduler_config.json").write_text("{}")
+ (path / "tokenizer").mkdir()
+ (path / "tokenizer" / "tokenizer.json").write_text("{}")
+ return path
+
+ return write
+
+
@pytest.fixture
def tmp_cache_dir(tmp_path: Path) -> Path:
"""Provide a temporary cache directory for tests."""
diff --git a/tests/integration/test_e2e_streaming.py b/tests/integration/test_e2e_streaming.py
index 40b48621ba..227ddecac2 100644
--- a/tests/integration/test_e2e_streaming.py
+++ b/tests/integration/test_e2e_streaming.py
@@ -207,6 +207,18 @@ def get_model_ids(self) -> List[str]:
def get_status(self) -> Dict[str, Any]:
return {"models": self._models}
+ def get_active_model_aliases(self, settings_manager) -> Dict[str, str]:
+ if settings_manager is None:
+ return {}
+ aliases: Dict[str, str] = {}
+ for m in self._models:
+ model_id = m["id"]
+ settings = settings_manager.get_settings(model_id)
+ alias = getattr(settings, "model_alias", None)
+ if alias:
+ aliases[model_id] = alias
+ return aliases
+
async def get_engine(self, model_id: str, _lease: bool = False):
return self._engine
diff --git a/tests/integration/test_live_tool_calling.py b/tests/integration/test_live_tool_calling.py
new file mode 100644
index 0000000000..d9b19b71f0
--- /dev/null
+++ b/tests/integration/test_live_tool_calling.py
@@ -0,0 +1,311 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Check live tool turns, SSE, usage, and chat-backed decision readouts.
+
+Run against an isolated server:
+ OMLX_BASE_URL=http://127.0.0.1:18080 OMLX_TEST_MODEL=Qwen3.5-9B-oQ4e-mtp \\
+ uv run --python python3.12 pytest tests/integration/test_live_tool_calling.py -m integration
+
+OMLX_API_KEY is optional. The selected model must be listed by /v1/models.
+"""
+
+import json
+import math
+import os
+
+import httpx
+import pytest
+
+pytestmark = [pytest.mark.integration, pytest.mark.slow]
+
+
+@pytest.fixture
+def live_server():
+ model = os.environ.get("OMLX_TEST_MODEL")
+ if not model:
+ pytest.skip("Set OMLX_TEST_MODEL to a model ID served by the live server")
+ headers = {}
+ if api_key := os.environ.get("OMLX_API_KEY"):
+ headers["Authorization"] = f"Bearer {api_key}"
+ with httpx.Client(
+ base_url=os.environ.get("OMLX_BASE_URL", "http://127.0.0.1:8000"),
+ headers=headers,
+ timeout=180,
+ trust_env=False,
+ ) as client:
+ response = client.get("/v1/models")
+ response.raise_for_status()
+ assert model in {entry["id"] for entry in response.json()["data"]}
+ yield client, model
+
+
+def _completion(client, payload):
+ if not payload["stream"]:
+ response = client.post("/v1/chat/completions", json=payload)
+ response.raise_for_status()
+ return response.json()
+
+ message = {"role": "assistant", "content": "", "tool_calls": []}
+ finish_reason = None
+ usage = None
+ logprobs = []
+ done = False
+ with client.stream("POST", "/v1/chat/completions", json=payload) as response:
+ response.raise_for_status()
+ for line in response.iter_lines():
+ if not line.startswith("data: "):
+ continue
+ data = line.removeprefix("data: ")
+ if data == "[DONE]":
+ done = True
+ break
+ chunk = json.loads(data)
+ assert "error" not in chunk, chunk
+ if chunk.get("usage"):
+ usage = chunk["usage"]
+ for choice in chunk.get("choices", []):
+ assert choice["index"] == 0
+ if choice.get("finish_reason"):
+ finish_reason = choice["finish_reason"]
+ if choice.get("logprobs"):
+ logprobs.extend(choice["logprobs"]["content"] or [])
+ delta = choice["delta"]
+ message["content"] += delta.get("content") or ""
+ for call in delta.get("tool_calls", []):
+ index = call["index"]
+ assert index <= len(message["tool_calls"])
+ if index == len(message["tool_calls"]):
+ message["tool_calls"].append(
+ {
+ "id": "",
+ "type": "function",
+ "function": {"name": "", "arguments": ""},
+ }
+ )
+ target = message["tool_calls"][index]
+ if call.get("id"):
+ assert not target["id"] or target["id"] == call["id"]
+ target["id"] = call["id"]
+ function = call.get("function", {})
+ target["function"]["name"] += function.get("name") or ""
+ target["function"]["arguments"] += function.get("arguments") or ""
+ assert done, "Stream ended without [DONE]"
+ return {
+ "choices": [
+ {
+ "message": message,
+ "finish_reason": finish_reason,
+ "logprobs": {"content": logprobs},
+ }
+ ],
+ "usage": usage,
+ }
+
+
+@pytest.mark.parametrize("stream", [False, True])
+def test_live_chat_logprobs(live_server, stream):
+ client, model = live_server
+ payload = {
+ "model": model,
+ "messages": [{"role": "user", "content": "Reply with only the word hello."}],
+ "temperature": 0,
+ "max_tokens": 16,
+ "chat_template_kwargs": {"enable_thinking": False},
+ "logprobs": True,
+ "top_logprobs": 3,
+ "stream": stream,
+ }
+ if stream:
+ payload["stream_options"] = {"include_usage": True}
+ response = _completion(client, payload)
+ choice = response["choices"][0]
+ assert choice["finish_reason"] == "stop", response
+ assert choice["message"]["content"], response
+ entries = choice["logprobs"]["content"]
+ assert entries, response
+ for entry in entries:
+ assert isinstance(entry["token"], str)
+ assert math.isfinite(entry["logprob"]) and entry["logprob"] <= 0
+ assert all(isinstance(byte, int) and 0 <= byte <= 255 for byte in entry["bytes"])
+ assert len(entry["top_logprobs"]) == 3
+ for alternative in entry["top_logprobs"]:
+ assert math.isfinite(alternative["logprob"])
+ assert alternative["logprob"] <= 0
+ assert response["usage"]["completion_tokens"] > 0
+
+
+@pytest.mark.parametrize("stream", [False, True])
+def test_live_tool_call_round_trip(live_server, stream):
+ client, model = live_server
+ payload = {
+ "model": model,
+ "messages": [
+ {
+ "role": "system",
+ "content": (
+ "Use multiply for arithmetic. After receiving the tool result, "
+ "answer with only the numeric result."
+ ),
+ },
+ {"role": "user", "content": "What is 6 multiplied by 7?"},
+ ],
+ "tools": [
+ {
+ "type": "function",
+ "function": {
+ "name": "multiply",
+ "description": "Multiply two integers.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "a": {"type": "integer"},
+ "b": {"type": "integer"},
+ },
+ "required": ["a", "b"],
+ "additionalProperties": False,
+ },
+ },
+ }
+ ],
+ "tool_choice": "required",
+ "temperature": 0,
+ "max_tokens": 128,
+ "chat_template_kwargs": {"enable_thinking": False},
+ "stream": stream,
+ }
+ if stream:
+ payload["stream_options"] = {"include_usage": True}
+ payload["return_progress"] = True
+ response = _completion(client, payload)
+ choice = response["choices"][0]
+ assert choice["finish_reason"] == "tool_calls", response
+ message = choice["message"]
+ assert len(message["tool_calls"]) == 1, response
+ call = message["tool_calls"][0]
+ assert call["id"]
+ assert call["type"] == "function"
+ assert call["function"]["name"] == "multiply"
+ assert json.loads(call["function"]["arguments"]) == {"a": 6, "b": 7}
+ assert response["usage"]["prompt_tokens"] > 0
+ assert response["usage"]["completion_tokens"] > 0
+ assert response["usage"]["total_tokens"] == (
+ response["usage"]["prompt_tokens"] + response["usage"]["completion_tokens"]
+ )
+
+ payload["messages"].extend(
+ [
+ message,
+ {"role": "tool", "tool_call_id": call["id"], "content": "42"},
+ ]
+ )
+ payload["tool_choice"] = "none"
+ response = _completion(client, payload)
+ choice = response["choices"][0]
+ assert choice["finish_reason"] == "stop", response
+ assert "42" in choice["message"]["content"], response
+ assert not choice["message"].get("tool_calls"), response
+ assert response["usage"]["completion_tokens"] > 0
+
+
+@pytest.mark.parametrize("endpoint", ["/v1/decisions", "/v1/systemone"])
+def test_live_chat_decision_readout(live_server, endpoint):
+ client, model = live_server
+ question = {
+ "type": "choice",
+ "instructions": "What color is the stop sign?",
+ }
+ if endpoint == "/v1/systemone":
+ payload = {
+ "state": "The stop sign is red.",
+ "questions": {
+ "color": {**question, "criteria": {"red": None, "blue": None}}
+ },
+ }
+ else:
+ payload = {
+ "input": "The stop sign is red.",
+ "questions": [{"name": "color", **question, "choices": ["red", "blue"]}],
+ }
+ response = client.post(endpoint, json={"model": model, **payload})
+ response.raise_for_status()
+ body = response.json()
+ if endpoint == "/v1/systemone":
+ answer = body["answers"]["color"]
+ probabilities = list(answer["probabilities"].values())
+ else:
+ (answer,) = body["answers"]
+ assert answer["name"] == "color"
+ probabilities = [entry["probability"] for entry in answer["probabilities"]]
+ assert body["usage"]["input_tokens"] > 0
+ assert body["usage"]["output_tokens"] == 0
+ assert answer["choice"] == "red", body
+ assert len(probabilities) == 2
+ assert all(0 <= probability <= 1 for probability in probabilities)
+ assert sum(probabilities) == pytest.approx(1, abs=0.0002)
+
+
+def test_live_anthropic_tool_call_round_trip(live_server):
+ client, model = live_server
+ payload = {
+ "model": model,
+ "system": (
+ "Use multiply for arithmetic. After receiving the tool result, "
+ "answer with only the numeric result."
+ ),
+ "messages": [{"role": "user", "content": "What is 6 multiplied by 7?"}],
+ "tools": [
+ {
+ "name": "multiply",
+ "description": "Multiply two integers.",
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "a": {"type": "integer"},
+ "b": {"type": "integer"},
+ },
+ "required": ["a", "b"],
+ "additionalProperties": False,
+ },
+ }
+ ],
+ "tool_choice": {"type": "any"},
+ "thinking": {"type": "disabled"},
+ "output_config": {"effort": "low"},
+ "temperature": 0,
+ "max_tokens": 128,
+ }
+ count_response = client.post(
+ "/v1/messages/count_tokens",
+ json={key: value for key, value in payload.items() if key != "max_tokens"},
+ )
+ count_response.raise_for_status()
+ response = client.post("/v1/messages", json=payload)
+ response.raise_for_status()
+ body = response.json()
+ assert body["stop_reason"] == "tool_use", body
+ assert body["usage"]["input_tokens"] == count_response.json()["input_tokens"]
+ assert body["usage"]["output_tokens"] > 0
+ (call,) = [block for block in body["content"] if block["type"] == "tool_use"]
+ assert call["id"]
+ assert call["name"] == "multiply"
+ assert call["input"] == {"a": 6, "b": 7}
+
+ payload["messages"].extend(
+ [
+ {"role": "assistant", "content": body["content"]},
+ {
+ "role": "user",
+ "content": [
+ {"type": "tool_result", "tool_use_id": call["id"], "content": "42"}
+ ],
+ },
+ ]
+ )
+ payload["tool_choice"] = {"type": "none"}
+ response = client.post("/v1/messages", json=payload)
+ response.raise_for_status()
+ body = response.json()
+ assert body["stop_reason"] == "end_turn", body
+ assert any(
+ block["type"] == "text" and "42" in block["text"] for block in body["content"]
+ ), body
+ assert not any(block["type"] == "tool_use" for block in body["content"]), body
diff --git a/tests/integration/test_responses_tool_merge.py b/tests/integration/test_responses_tool_merge.py
index d6b23975de..58e56fdf58 100644
--- a/tests/integration/test_responses_tool_merge.py
+++ b/tests/integration/test_responses_tool_merge.py
@@ -78,7 +78,7 @@ def __init__(self, grammar_compiler=None):
self._model_type = "llama"
self._grammar_compiler = grammar_compiler
self.recorded_chat_kwargs: List[Dict[str, Any]] = []
- self.recorded_count_calls: List[Dict[str, Any]] = []
+ self.recorded_count_calls: list[dict[str, Any]] = []
self.started = False
@property
@@ -121,7 +121,11 @@ def count_chat_tokens(self, messages, tools=None, chat_template_kwargs=None, **k
**kwargs,
}
)
- prompt = self._tokenizer.apply_chat_template(messages, tokenize=False)
+ template_kwargs = dict(chat_template_kwargs or {})
+ template_kwargs["tokenize"] = False
+ if tools:
+ template_kwargs["tools"] = tools
+ prompt = self._tokenizer.apply_chat_template(messages, **template_kwargs)
return len(self._tokenizer.encode(prompt))
async def chat(self, messages, **kwargs) -> MockGenerationOutput:
@@ -472,6 +476,47 @@ def test_count_sees_the_messages_prompt(self, client_with_mcp, engine, thinking)
is (thinking["type"] == "enabled")
)
+ def test_reasoning_effort_reaches_both_prompts(self, client_with_mcp, engine):
+ body = {
+ "model": "test-model",
+ "messages": [{"role": "user", "content": "What's the weather?"}],
+ "output_config": {"effort": "high"},
+ }
+
+ response = client_with_mcp.post("/v1/messages", json={**body, "max_tokens": 16})
+ assert response.status_code == 200
+ response = client_with_mcp.post("/v1/messages/count_tokens", json=body)
+ assert response.status_code == 200
+
+ messages_call, count_call = engine.recorded_count_calls
+ assert count_call == messages_call
+ assert count_call["chat_template_kwargs"]["reasoning_effort"] == "high"
+ assert engine.recorded_chat_kwargs[-1]["chat_template_kwargs"] == (
+ count_call["chat_template_kwargs"]
+ )
+
+ def test_multimodal_options_reach_both_prompts(self, client_with_mcp, engine):
+ from types import SimpleNamespace
+
+ engine._model_type = "minicpmv4_7"
+ engine._engine = SimpleNamespace(_mlx_executor=None)
+ options = {"downsample_mode": "16x", "max_slice_nums": 2}
+ body = {
+ "model": "test-model",
+ "messages": [{"role": "user", "content": "What's the weather?"}],
+ "mm_processor_kwargs": options,
+ }
+
+ response = client_with_mcp.post("/v1/messages", json={**body, "max_tokens": 16})
+ assert response.status_code == 200
+ response = client_with_mcp.post("/v1/messages/count_tokens", json=body)
+ assert response.status_code == 200
+
+ messages_call, count_call = engine.recorded_count_calls
+ assert count_call == messages_call
+ assert count_call["mm_processor_kwargs"] == options
+ assert engine.recorded_chat_kwargs[-1]["mm_processor_kwargs"] == options
+
def test_template_error_is_400_on_both(self, client_with_mcp, engine, monkeypatch):
# count_tokens used to fall back to "role: content" lines here and
# return 200 with a count of a prompt the model never sees.
diff --git a/tests/integration/test_server_endpoints.py b/tests/integration/test_server_endpoints.py
index d84004878b..770ab6e2d4 100644
--- a/tests/integration/test_server_endpoints.py
+++ b/tests/integration/test_server_endpoints.py
@@ -352,6 +352,32 @@ def get_status(self) -> Dict[str, Any]:
"max_model_memory": self.max_model_memory,
}
+ def get_active_model_aliases(self, settings_manager) -> Dict[str, str]:
+ if settings_manager is None:
+ return {}
+ aliases_by_name: Dict[str, List[str]] = {}
+ for m in self._models:
+ model_id = m["id"]
+ settings = settings_manager.get_settings(model_id)
+ alias = getattr(settings, "model_alias", None)
+ if not alias:
+ continue
+ alias = alias.strip()
+ if not alias:
+ continue
+ aliases_by_name.setdefault(alias, []).append(model_id)
+ active: Dict[str, str] = {}
+ lower_ids = {m["id"].lower(): m["id"] for m in self._models}
+ for alias, model_ids in aliases_by_name.items():
+ if len(model_ids) != 1:
+ continue
+ model_id = model_ids[0]
+ conflicting = lower_ids.get(alias.lower())
+ if conflicting is not None and conflicting != model_id:
+ continue
+ active[model_id] = alias
+ return active
+
async def get_engine(
self,
model_id: str,
@@ -1835,7 +1861,7 @@ def test_embeddings_multiple_inputs(self, client, mock_engine_pool):
assert len(data["data"]) == 2
def test_embeddings_use_discovered_context_length(self, client, mock_engine_pool):
- """Embedding requests should not fall back to mlx-embeddings' 512 default."""
+ """Embedding requests should not fall back to a 512-token default."""
mock_engine_pool._models.append(
{"id": "test-embed-model", "loaded": True, "pinned": False, "size": 500000}
)
diff --git a/tests/test_admin_chat_model_filter.py b/tests/test_admin_chat_model_filter.py
new file mode 100644
index 0000000000..c8d1d7e56e
--- /dev/null
+++ b/tests/test_admin_chat_model_filter.py
@@ -0,0 +1,252 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Regression tests for admin chat model dropdown filtering."""
+
+import json
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from omlx.model_settings import ModelSettings
+from omlx.settings import GlobalSettings
+
+CHAT_TEMPLATE = (
+ Path(__file__).parent.parent
+ / "apps"
+ / "omlx-web"
+ / "omlx_web"
+ / "templates"
+ / "chat.html"
+)
+
+
+def _chat_model_selectable(model_type, engine_type=""):
+ """Python equivalent of the chat.html availableModels filter."""
+ t = (model_type or "").lower()
+ e = (engine_type or "").lower()
+ return not (
+ t.startswith("audio_")
+ or t == "embedding"
+ or t == "reranker"
+ or t == "image"
+ or e == "image"
+ )
+
+
+def _status_metadata_maps(models):
+ """Python equivalent of the chat.html /v1/models/status metadata mapping."""
+ model_type_map = {}
+ model_engine_type_map = {}
+ for model in models:
+ model_id = model.get("id")
+ if model_id:
+ model_type_map[model_id] = model.get("model_type") or "llm"
+ model_engine_type_map[model_id] = model.get("engine_type") or ""
+ for model in models:
+ model_id = model.get("model_alias")
+ if model_id and model_id not in model_type_map:
+ model_type_map[model_id] = model.get("model_type") or "llm"
+ model_engine_type_map[model_id] = model.get("engine_type") or ""
+ return model_type_map, model_engine_type_map
+
+
+def test_chat_dropdown_filter_keeps_chat_capable_model_types():
+ """LLM and VLM models should remain selectable in the chat UI."""
+ assert _chat_model_selectable("llm")
+ assert _chat_model_selectable("vlm")
+
+
+def test_chat_dropdown_filter_excludes_non_chat_model_types():
+ """Dedicated non-chat engines should not be offered in the chat UI."""
+ assert not _chat_model_selectable("image")
+ assert not _chat_model_selectable("llm", engine_type="image")
+ assert not _chat_model_selectable("audio_transcription")
+ assert not _chat_model_selectable("audio_speech")
+ assert not _chat_model_selectable("embedding")
+ assert not _chat_model_selectable("reranker")
+
+
+def test_chat_dropdown_filter_excludes_aliased_image_model():
+ """/v1/models aliases should still receive image metadata from status."""
+ model_type_map, engine_type_map = _status_metadata_maps(
+ [
+ {
+ "id": "raw-image-model",
+ "model_alias": "friendly-image-name",
+ "model_type": "llm",
+ "engine_type": "image",
+ },
+ {
+ "id": "raw-vlm-model",
+ "model_alias": "friendly-vlm-name",
+ "model_type": "vlm",
+ "engine_type": "vlm",
+ },
+ ]
+ )
+
+ assert not _chat_model_selectable(
+ model_type_map["friendly-image-name"],
+ engine_type_map["friendly-image-name"],
+ )
+ assert _chat_model_selectable(
+ model_type_map["friendly-vlm-name"],
+ engine_type_map["friendly-vlm-name"],
+ )
+
+
+def test_status_metadata_prefers_model_id_when_alias_collides():
+ """A model alias should not overwrite another model's canonical metadata."""
+ model_type_map, engine_type_map = _status_metadata_maps(
+ [
+ {
+ "id": "chat-model",
+ "model_type": "llm",
+ "engine_type": "batched",
+ },
+ {
+ "id": "raw-image-model",
+ "model_alias": "chat-model",
+ "model_type": "llm",
+ "engine_type": "image",
+ },
+ ]
+ )
+
+ assert _chat_model_selectable(
+ model_type_map["chat-model"],
+ engine_type_map["chat-model"],
+ )
+
+
+@pytest.mark.asyncio
+async def test_models_status_exposes_model_alias_metadata():
+ """/v1/models/status should include aliases for clients listing alias IDs."""
+ from omlx.server import ServerState, list_models_status
+
+ state = ServerState()
+ state.engine_pool = MagicMock()
+ state.engine_pool.get_status.return_value = {
+ "models": [
+ {
+ "id": "raw-image-model",
+ "engine_type": "image",
+ "model_type": "llm",
+ }
+ ]
+ }
+ state.engine_pool.get_active_model_aliases.return_value = {
+ "raw-image-model": "friendly-image-name",
+ }
+ state.settings_manager = MagicMock()
+ state.settings_manager.get_settings.return_value = ModelSettings(
+ model_alias="friendly-image-name"
+ )
+
+ with patch("omlx.server._server_state", state):
+ status = await list_models_status()
+
+ assert status["models"][0]["id"] == "raw-image-model"
+ assert status["models"][0]["model_alias"] == "friendly-image-name"
+ assert status["models"][0]["engine_type"] == "image"
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ ("settings", "discovered_default", "expected"),
+ [
+ (ModelSettings(enable_thinking=False), True, False),
+ (ModelSettings(enable_thinking=True), False, True),
+ (ModelSettings(chat_template_kwargs={"enable_thinking": True}), False, True),
+ (
+ ModelSettings(
+ enable_thinking=False, chat_template_kwargs={"enable_thinking": True}
+ ),
+ True,
+ False,
+ ),
+ (ModelSettings(), True, True),
+ (ModelSettings(), None, None),
+ (None, False, False),
+ ],
+)
+async def test_models_status_exposes_effective_thinking(
+ settings, discovered_default, expected
+):
+ from omlx.server import ServerState, list_models_status
+
+ state = ServerState()
+ state.engine_pool = MagicMock()
+ state.engine_pool.get_status.return_value = {
+ "models": [
+ {"id": "model", "model_type": "llm", "thinking_default": discovered_default}
+ ]
+ }
+ state.engine_pool.get_active_model_aliases.return_value = {}
+ if settings is not None:
+ state.settings_manager = MagicMock()
+ state.settings_manager.get_settings_for_request.return_value = settings
+ state.settings_manager.get_settings.return_value = settings
+ with patch("omlx.server._server_state", state):
+ status = await list_models_status()
+ assert status["models"][0]["enable_thinking"] is expected
+
+
+@pytest.mark.asyncio
+async def test_models_endpoints_omit_inactive_colliding_aliases():
+ """Inactive aliases should not create duplicate /v1/models display IDs."""
+ from omlx.server import ServerState, list_models, list_models_status
+
+ state = ServerState()
+ state.engine_pool = MagicMock()
+ state.engine_pool.get_status.return_value = {
+ "models": [
+ {
+ "id": "chat-model",
+ "engine_type": "batched",
+ "model_type": "llm",
+ },
+ {
+ "id": "raw-image-model",
+ "engine_type": "image",
+ "model_type": "llm",
+ },
+ ]
+ }
+ state.engine_pool.get_active_model_aliases.return_value = {}
+ state.global_settings = GlobalSettings()
+ state.global_settings.integrations.markitdown_expose_model = False
+ state.settings_manager = MagicMock()
+ state.settings_manager.get_settings.side_effect = lambda model_id: ModelSettings(
+ model_alias="chat-model" if model_id == "raw-image-model" else None
+ )
+
+ with patch("omlx.server._server_state", state):
+ models = await list_models()
+ status = await list_models_status()
+
+ data = json.loads(bytes(models.body))["data"]
+ assert [m["id"] for m in data] == ["chat-model", "raw-image-model"]
+ raw_image = next(m for m in status["models"] if m["id"] == "raw-image-model")
+ assert "model_alias" not in raw_image
+
+
+def test_chat_template_uses_status_metadata_for_filtering():
+ """The UI filter should use /v1/models/status model and engine metadata."""
+ source = CHAT_TEMPLATE.read_text()
+
+ assert "modelTypeMap" in source
+ assert "modelEngineTypeMap" in source
+ assert "fetch('/v1/models/status'" in source
+ assert "map[m.id] = m.model_type || 'llm';" in source
+ assert "engineMap[m.id] = m.engine_type || '';" in source
+ assert "map[m.model_alias] === undefined" in source
+ assert source.index("await this.fetchModelTypes();") < source.index(
+ "this.availableModels = this.dedupeAvailableModels("
+ )
+ assert "t !== 'image'" in source
+ assert "e !== 'image'" in source
+ assert "t !== 'embedding'" in source
+ assert "t !== 'reranker'" in source
+ assert "t !== 'audio_tts'" in source
+ assert "t !== 'audio_sts'" in source
diff --git a/tests/test_admin_profiles_api.py b/tests/test_admin_profiles_api.py
index 3b89b48ec7..94ca13c3c9 100644
--- a/tests/test_admin_profiles_api.py
+++ b/tests/test_admin_profiles_api.py
@@ -8,7 +8,7 @@
from types import SimpleNamespace
import pytest
-from fastapi import FastAPI
+from fastapi import FastAPI, HTTPException
from fastapi.testclient import TestClient
from omlx.admin import recipe as settings_recipe
@@ -28,6 +28,7 @@ def __init__(
self.engine_type = engine_type
self.model_type = model_type
self.config_model_type = config_model_type
+ self.model_format = None
self.engine = None
self.is_pinned = False
self.is_loading = False
@@ -84,6 +85,20 @@ class _FakeServerState:
default_model = None
+@pytest.mark.asyncio
+async def test_settings_reset_requires_initialized_engine_pool(client, monkeypatch):
+ _, mgr = client
+ mgr.set_settings("model-a", ModelSettings(temperature=0.3))
+ monkeypatch.setattr(admin_routes, "_get_engine_pool", None)
+
+ with pytest.raises(HTTPException) as error:
+ await admin_routes._apply_settings_snapshot(
+ _FakeEntry("model-a"), "model-a", {}, reset=True
+ )
+ assert error.value.status_code == 503
+ assert mgr.get_settings("model-a").temperature == 0.3
+
+
@pytest.fixture
def client(tmp_path, monkeypatch):
mgr = ModelSettingsManager(tmp_path)
@@ -210,6 +225,123 @@ def test_invalid_kv_profile_does_not_persist(self, client):
assert r.status_code in (400, 422), r.text
assert mgr.list_profiles("model-a") == []
+ def test_minicpm_dspark_settings_use_batched_compatibility(self, client, tmp_path):
+ c, mgr = client
+ helper = tmp_path / "paired-helper"
+ helper.mkdir()
+ (helper / "config.json").write_text(
+ json.dumps(
+ {
+ "model_type": "qwen3",
+ "architectures": ["Qwen3DSparkModel"],
+ "dflash_config": {"projector_type": "dspark"},
+ }
+ )
+ )
+ entry = admin_routes._get_engine_pool().get_entry("model-a")
+ entry.config_model_type = "minicpmv4_7"
+ entry.engine_type = "vlm"
+ entry.model_type = "vlm"
+ response = c.put(
+ "/admin/api/models/model-a/settings",
+ json={
+ "dflash_enabled": True,
+ "dflash_draft_model": str(helper),
+ "dflash_verify_mode": "dflash",
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert mgr.get_settings("model-a").dflash_enabled is True
+ assert admin_routes._dflash_compat_for_model(
+ {
+ "config_model_type": "minicpmv4_7",
+ "engine_type": "vlm",
+ "model_path": entry.model_path,
+ }
+ ) == (True, "")
+
+ def test_processor_controls_reject_other_models_without_saving(self, client):
+ c, mgr = client
+ response = c.post(
+ "/admin/api/models/model-a/profiles",
+ json={
+ "name": "visual",
+ "display_name": "Visual",
+ "settings": {"mm_processor_kwargs": {"downsample_mode": "4x"}},
+ },
+ )
+ assert response.status_code == 400
+ assert "MiniCPM-V 4.7" in response.json()["detail"]
+ assert mgr.list_profiles("model-a") == []
+
+ def test_processor_controls_survive_profile_save_and_apply(self, client):
+ c, mgr = client
+ entry = admin_routes._get_engine_pool().get_entry("model-a")
+ entry.config_model_type = "minicpmv4_7"
+ options = {"downsample_mode": "4x", "max_slice_nums": 36}
+ response = c.post(
+ "/admin/api/models/model-a/profiles",
+ json={
+ "name": "visual",
+ "display_name": "Visual",
+ "settings": {"mm_processor_kwargs": options},
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert response.json()["profile"]["settings"]["mm_processor_kwargs"] == options
+ response = c.post("/admin/api/models/model-a/profiles/visual/apply")
+ assert response.status_code == 200, response.text
+ assert mgr.get_settings("model-a").mm_processor_kwargs == options
+
+ def test_processor_profile_defaults_clear_previous_controls(self, client):
+ c, mgr = client
+ admin_routes._get_engine_pool().get_entry(
+ "model-a"
+ ).config_model_type = "minicpmv4_7"
+ response = c.put(
+ "/admin/api/models/model-a/settings",
+ json={"mm_processor_kwargs": {"downsample_mode": "4x", "max_slice_nums": 36}},
+ )
+ assert response.status_code == 200, response.text
+ response = c.post(
+ "/admin/api/models/model-a/profiles",
+ json={
+ "name": "default-visual",
+ "display_name": "Default Visual",
+ "settings": {"mm_processor_kwargs": {}},
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert response.json()["profile"]["settings"]["mm_processor_kwargs"] == {}
+ response = c.post("/admin/api/models/model-a/profiles/default-visual/apply")
+ assert response.status_code == 200, response.text
+ assert mgr.get_settings("model-a").mm_processor_kwargs == {}
+
+ @pytest.mark.parametrize(
+ "options",
+ [
+ {"stack_frames": 4},
+ {"max_slice_nums": True},
+ {"max_slice_nums": 0},
+ {"max_slice_nums": 1.5},
+ ],
+ )
+ def test_processor_profile_controls_are_validated_before_saving(self, client, options):
+ c, mgr = client
+ admin_routes._get_engine_pool().get_entry(
+ "model-a"
+ ).config_model_type = "minicpmv4_7"
+ response = c.post(
+ "/admin/api/models/model-a/profiles",
+ json={
+ "name": "visual",
+ "display_name": "Visual",
+ "settings": {"mm_processor_kwargs": options},
+ },
+ )
+ assert response.status_code == 422, response.text
+ assert mgr.list_profiles("model-a") == []
+
def test_list_profiles_empty(self, client):
c, _ = client
r = c.get("/admin/api/models/model-a/profiles")
@@ -782,6 +914,53 @@ def test_diffusion_settings_update_sanitizes_unsupported_fields(self, client):
assert settings["mtp_enabled"] is False
assert settings["vlm_mtp_enabled"] is False
+ def test_admin_model_type_override_accepts_image(self, client):
+ c, mgr = client
+ r = c.put("/admin/api/models/model-a/settings", json={
+ "model_type_override": "image",
+ })
+
+ assert r.status_code == 200, r.text
+ assert r.json()["model_type"] == "image"
+ assert r.json()["engine_type"] == "image"
+ assert mgr.get_settings("model-a").model_type_override == "image"
+
+ @pytest.mark.parametrize("override", [None, ""])
+ def test_admin_flint_auto_type_preserves_vlm_engine(
+ self, client, tmp_path, override
+ ):
+ c, mgr = client
+ entry = admin_routes._get_engine_pool().get_entry("model-a")
+ (tmp_path / "config.json").write_text(json.dumps({"model_type": "flint"}))
+ entry.model_path = str(tmp_path)
+ entry.config_model_type = "flint"
+ entry.engine_type = "vlm"
+
+ response = c.put(
+ "/admin/api/models/model-a/settings",
+ json={"model_type_override": override},
+ )
+
+ assert response.status_code == 200, response.text
+ assert response.json()["model_type"] == entry.model_type == "llm"
+ assert response.json()["engine_type"] == entry.engine_type == "vlm"
+ assert mgr.get_settings("model-a").model_type_override is None
+
+ def test_admin_model_type_override_rejects_gguf(self, client):
+ c, mgr = client
+ entry = admin_routes._get_engine_pool().get_entry("model-a")
+ entry.model_format = "gguf"
+
+ response = c.put(
+ "/admin/api/models/model-a/settings",
+ json={"model_type_override": "image"},
+ )
+
+ assert response.status_code == 400, response.text
+ assert "GGUF" in response.json()["detail"]
+ assert entry.model_type == "llm"
+ assert mgr.get_settings("model-a").model_type_override is None
+
class TestActiveProfileDriftClearing:
def test_active_preserved_when_no_drift(self, client):
diff --git a/tests/test_api_utils.py b/tests/test_api_utils.py
index b81a6e5abc..70a22faf9d 100644
--- a/tests/test_api_utils.py
+++ b/tests/test_api_utils.py
@@ -59,7 +59,6 @@
prepare_system_messages_for_template,
uses_native_reasoning_content,
)
-from omlx.exceptions import InvalidRequestError
from omlx.model_settings import ModelSettings, merge_chat_template_request_kwargs
diff --git a/tests/test_batched_engine.py b/tests/test_batched_engine.py
index ed0b72c965..9fd242e68f 100644
--- a/tests/test_batched_engine.py
+++ b/tests/test_batched_engine.py
@@ -15,9 +15,8 @@
import threading
import time
-from abc import ABC
from types import SimpleNamespace
-from typing import Any, Dict, List, Optional
+from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -167,7 +166,7 @@ async def generate(
max_tokens: int = 256,
temperature: float = 0.7,
top_p: float = 0.9,
- stop: Optional[List[str]] = None,
+ stop: list[str] | None = None,
**kwargs,
) -> GenerationOutput:
return GenerationOutput(text="test")
@@ -178,41 +177,41 @@ async def stream_generate(
max_tokens: int = 256,
temperature: float = 0.7,
top_p: float = 0.9,
- stop: Optional[List[str]] = None,
+ stop: list[str] | None = None,
**kwargs,
):
yield GenerationOutput(text="test")
async def chat(
self,
- messages: List[Dict[str, Any]],
+ messages: list[dict[str, Any]],
max_tokens: int = 256,
temperature: float = 0.7,
top_p: float = 0.9,
- tools: Optional[List[dict]] = None,
+ tools: list[dict] | None = None,
**kwargs,
) -> GenerationOutput:
return GenerationOutput(text="test")
async def stream_chat(
self,
- messages: List[Dict[str, Any]],
+ messages: list[dict[str, Any]],
max_tokens: int = 256,
temperature: float = 0.7,
top_p: float = 0.9,
- tools: Optional[List[dict]] = None,
+ tools: list[dict] | None = None,
**kwargs,
):
yield GenerationOutput(text="test")
@property
- def model_type(self) -> Optional[str]:
+ def model_type(self) -> str | None:
return "test"
- def get_stats(self) -> Dict[str, Any]:
+ def get_stats(self) -> dict[str, Any]:
return {}
- def get_cache_stats(self) -> Optional[Dict[str, Any]]:
+ def get_cache_stats(self) -> dict[str, Any] | None:
return None
engine = ConcreteEngine()
@@ -396,6 +395,39 @@ async def test_abort_request_only_reaches_owned_requests(self):
)
+class TestBailingHybridWarmup:
+ def test_compiles_sorted_prefill_and_decode_paths(self):
+ import mlx.core as mx
+
+ from omlx.engine.batched import _warmup_bailing_hybrid
+
+ class FakeModel:
+ args = SimpleNamespace(model_type="bailing_hybrid")
+
+ def __init__(self):
+ self.calls = []
+ self.cache = object()
+
+ def make_cache(self):
+ return self.cache
+
+ def __call__(self, tokens, cache):
+ self.calls.append((tokens.shape, cache))
+ return mx.zeros((*tokens.shape, 4))
+
+ model = FakeModel()
+
+ assert _warmup_bailing_hybrid(model, token_id=7) is True
+ assert model.calls == [((1, 8), model.cache), ((1, 1), model.cache)]
+
+ def test_skips_other_model_types(self):
+ from omlx.engine.batched import _warmup_bailing_hybrid
+
+ model = SimpleNamespace(args=SimpleNamespace(model_type="qwen3"))
+
+ assert _warmup_bailing_hybrid(model) is False
+
+
class TestBatchedEngineStreamingCleanup:
"""Tests for streaming generator cleanup paths."""
diff --git a/tests/test_cluster_deployment.py b/tests/test_cluster_deployment.py
index b43f7d8c63..8706bb04bc 100644
--- a/tests/test_cluster_deployment.py
+++ b/tests/test_cluster_deployment.py
@@ -709,15 +709,33 @@ def test_registry_round_trip_preserves_path_map(tmp_path):
assert restored.model_path_for("peer") == "/Volumes/models/copy"
-def test_preflight_uses_per_node_model_paths(monkeypatch):
- from omlx.cluster.launch import _local_runtime_versions, preflight_remote_hosts
+@pytest.mark.parametrize(
+ ("local_ceiling", "remote_ceiling", "rejected_rank"),
+ [
+ (1024**4, 1024**4, None),
+ (22, 12, None),
+ (21, 12, 0),
+ (22, 11, 1),
+ (1, 12, 0),
+ (22, 1, 1),
+ (0, 12, 0),
+ (22, 0, 1),
+ ],
+)
+def test_preflight_uses_per_node_model_paths(
+ monkeypatch, local_ceiling, remote_ceiling, rejected_rank
+):
+ from omlx.cluster.launch import (
+ DistributedLaunchError,
+ _local_runtime_versions,
+ preflight_remote_hosts,
+ )
from omlx.cluster.models import CLUSTER_PROTOCOL_VERSION
versions = _local_runtime_versions()
calls = []
- # The local rank measures live memory, which other test workers consume.
monkeypatch.setattr(
- memory_guard, "ceiling_breakdown", lambda tier: {"hard_limit": 1024**4}
+ memory_guard, "ceiling_breakdown", lambda tier: {"hard_limit": local_ceiling}
)
def runner(argv, **kwargs):
@@ -731,7 +749,7 @@ def runner(argv, **kwargs):
"cluster-protocol": CLUSTER_PROTOCOL_VERSION,
"python": platform.python_version(),
"model-exists": True,
- "admission-ceiling-bytes": 1024**4,
+ "admission-ceiling-bytes": remote_ceiling,
}
),
stderr="",
@@ -741,13 +759,29 @@ def runner(argv, **kwargs):
"/nonexistent/shared",
path_map={"peer": "/Volumes/models/studio-copy"},
)
- result = preflight_remote_hosts(
- deployment,
- python_executable="/opt/omlx/bin/python",
- runner=runner,
- )
+ if rejected_rank is None:
+ result = preflight_remote_hosts(
+ deployment,
+ python_executable="/opt/omlx/bin/python",
+ runner=runner,
+ )
+ assert len(result) == 2
+ assert [item["admission_ceiling_bytes"] for item in result] == [
+ local_ceiling,
+ remote_ceiling,
+ ]
+ else:
+ node_id = deployment.hosts[rejected_rank].node_id
+ with pytest.raises(
+ DistributedLaunchError,
+ match=rf"no ranks were started.*rank {rejected_rank} \({node_id}\)",
+ ):
+ 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]
diff --git a/tests/test_cluster_performance.py b/tests/test_cluster_performance.py
index 2cee1c449a..866a31b809 100644
--- a/tests/test_cluster_performance.py
+++ b/tests/test_cluster_performance.py
@@ -329,7 +329,31 @@ def size():
return 2
-def test_sampling_rank_optimization_is_capability_gated_and_restored():
+def _make_pipeline_source_inspectable(monkeypatch):
+ from omlx.cluster import runtime_optimizations
+
+ source = """
+def __call__(self, value, cache=None):
+ pipeline_rank = self.pipeline_rank
+ pipeline_size = self.pipeline_size
+ if pipeline_rank != 0:
+ value = mx.distributed.send(value, pipeline_rank - 1)
+ if pipeline_size > 1:
+ value = mx.distributed.all_gather(value)
+ return value
+"""
+ original = runtime_optimizations.inspect.getsource
+
+ def getsource(value):
+ if value is _ValidatedPipeline.__call__:
+ return source
+ return original(value)
+
+ monkeypatch.setattr(runtime_optimizations.inspect, "getsource", getsource)
+
+
+def test_sampling_rank_optimization_is_capability_gated_and_restored(monkeypatch):
+ _make_pipeline_source_inspectable(monkeypatch)
settings = replace(
execution_profile("balanced"),
sampling_rank_only=True,
@@ -428,6 +452,7 @@ def peer_rejects_sampling(group, local):
def test_worker_rank_skips_vocab_projection_when_adapter_declares_contract(
monkeypatch,
):
+ _make_pipeline_source_inspectable(monkeypatch)
class Cache:
state = mx.array([0])
@@ -584,6 +609,7 @@ def test_pipeline_prefill_schedule_has_equal_fill_and_drain_timeline():
def test_staggered_prompt_queues_and_flushes_every_real_chunk(monkeypatch):
+ _make_pipeline_source_inspectable(monkeypatch)
sends = []
gathers = []
async_values = []
diff --git a/tests/test_cluster_progressive_loading.py b/tests/test_cluster_progressive_loading.py
index 315e2acd7a..0deea922ee 100644
--- a/tests/test_cluster_progressive_loading.py
+++ b/tests/test_cluster_progressive_loading.py
@@ -193,7 +193,9 @@ def __call__(self, value):
assert all_sums == [(7, group)]
-def test_native_tensor_strategy_materializes_and_shards_one_layer_at_a_time():
+def test_native_tensor_strategy_materializes_and_shards_one_layer_at_a_time(
+ monkeypatch,
+):
mx = _FakeMX()
calls = []
progress = []
@@ -219,6 +221,14 @@ def shard(self, group):
calls.append(layer.name)
model = Model()
+ monkeypatch.setattr(
+ "omlx.cluster.tensor_strategies.inspect.getsource",
+ lambda _shard: """
+def shard(self, group):
+ for layer in self.model.layers:
+ layer.shard(group)
+""",
+ )
strategy = apply_tensor_strategy(
model,
SimpleNamespace(),
@@ -233,7 +243,7 @@ def shard(self, group):
assert sum(event[0] == "clear" for event in mx.events) == 3
-def test_native_tensor_strategy_skips_read_only_forwarding_layer_property():
+def test_native_tensor_strategy_skips_read_only_forwarding_layer_property(monkeypatch):
"""Qwen3.5 exposes Model.layers as a property over model.layers."""
mx = _FakeMX()
@@ -262,6 +272,14 @@ def shard(self, group):
calls.append(layer.name)
model = Model()
+ monkeypatch.setattr(
+ "omlx.cluster.tensor_strategies.inspect.getsource",
+ lambda _shard: """
+def shard(self, group):
+ for layer in self.layers:
+ layer.shard(group)
+""",
+ )
strategy = apply_tensor_strategy(
model,
SimpleNamespace(),
@@ -273,7 +291,9 @@ def shard(self, group):
assert [layer.name for layer in model.layers] == ["zero", "one"]
-def test_native_tensor_strategy_refuses_fixed_weight_mutation_outside_layer_loop():
+def test_native_tensor_strategy_refuses_fixed_weight_mutation_outside_layer_loop(
+ monkeypatch,
+):
mx = _FakeMX()
class Layer:
@@ -293,6 +313,15 @@ def shard(self, group):
pass
model = Model()
+ monkeypatch.setattr(
+ "omlx.cluster.tensor_strategies.inspect.getsource",
+ lambda _shard: """
+def shard(self, group):
+ self.output = "sharded"
+ for layer in self.layers:
+ layer.shard(group)
+""",
+ )
try:
apply_tensor_strategy(
diff --git a/tests/test_decisions.py b/tests/test_decisions.py
index daa49111a6..eae238bd5a 100644
--- a/tests/test_decisions.py
+++ b/tests/test_decisions.py
@@ -62,6 +62,28 @@ def _run(engine, request, multimodal=False):
return asyncio.run(decisions.decide(engine, request, multimodal))
+@pytest.mark.asyncio
+async def test_each_readout_awaits_preparation_and_forwards_prepared_prompt():
+ engine = _FakeChatEngine(lambda text, letters: [1.0] * len(letters))
+ request = _request(
+ questions=[
+ {"type": "predicate", "name": name, "instructions": "Is this urgent?"}
+ for name in ("first", "second")
+ ]
+ )
+ prepared = []
+
+ async def prepare(messages):
+ await asyncio.sleep(0)
+ prompt = object()
+ prepared.append(prompt)
+ return {"_prepared_prompt": prompt}
+
+ result = await decisions.decide(engine, request, False, prepare=prepare)
+ assert len(result["answers"]) == 2
+ assert [call["_prepared_prompt"] for call in engine.calls] == prepared
+
+
def test_capture_reads_option_logprobs_and_keeps_logits():
capture = decisions.OptionLogitsCapture([[1, 2], [3]])
logits = mx.array([[0.0, 1.0, 1.0, 2.0]])
diff --git a/tests/test_engine_core.py b/tests/test_engine_core.py
index 12aa2849d5..6d5caf4acd 100644
--- a/tests/test_engine_core.py
+++ b/tests/test_engine_core.py
@@ -1553,6 +1553,18 @@ def test_get_mlx_executor_returns_singleton(self):
executor2 = get_mlx_executor()
assert executor1 is executor2
+ def test_global_executor_does_not_rebind_mlx_lm_generation_stream(self):
+ """Initializing cleanup/load work must not leak its worker stream."""
+ import importlib
+
+ from omlx.engine_core import get_mlx_executor
+
+ generate = importlib.import_module("mlx_lm.generate")
+ original = generate.generation_stream
+ get_mlx_executor().submit(lambda: None).result()
+
+ assert generate.generation_stream is original
+
def test_engines_have_per_engine_executors(self, mock_model, mock_tokenizer):
"""Each EngineCore must have its own executor (#1248)."""
with patch("omlx.engine_core.get_registry") as mock_registry:
diff --git a/tests/test_engine_keepalive.py b/tests/test_engine_keepalive.py
index eeb160111d..79c98b37a4 100644
--- a/tests/test_engine_keepalive.py
+++ b/tests/test_engine_keepalive.py
@@ -12,7 +12,7 @@
class _MaskBranchingModel:
"""Forward with a Python `if` on a mask-dependent lazy comparison.
- Mirrors mlx-embeddings qwen3's last_token_pool: with attention_mask=None
+ Mirrors mlx-vlm qwen3_embedding's last_token_pool: with attention_mask=None
the default mask is built from the (static) shape, so it is a tracing
constant and legal to eval; with a traced attention_mask input the same
`if` forces an eval during tracing and mx.compile raises (issue #2447).
diff --git a/tests/test_engine_pool.py b/tests/test_engine_pool.py
index 4ce159ea7e..77881e2e6c 100644
--- a/tests/test_engine_pool.py
+++ b/tests/test_engine_pool.py
@@ -6,7 +6,9 @@
import json
import logging
import shutil
+import sys
import threading
+import types
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
@@ -109,6 +111,41 @@ def test_discover_models(self, small_mock_model_dir):
assert "model-a" in pool.get_model_ids()
assert "model-b" in pool.get_model_ids()
+ @pytest.mark.parametrize("audio", [True, False])
+ def test_discovered_audio_input_is_exposed_without_loading(self, tmp_path, audio):
+ import numpy as np
+ from safetensors.numpy import save_file
+
+ model_dir = tmp_path / "gemma"
+ model_dir.mkdir()
+ (model_dir / "config.json").write_text(
+ json.dumps(
+ {
+ "model_type": "gemma4",
+ "text_config": {"model_type": "gemma4_text", "hidden_size": 16},
+ "vision_config": {"hidden_size": 16},
+ "audio_config": {"hidden_size": 16},
+ }
+ )
+ )
+ key = "audio_tower.layer.weight" if audio else "vision_tower.layer.weight"
+ save_file(
+ {key: np.zeros(1, dtype=np.float32)}, str(model_dir / "model.safetensors")
+ )
+
+ pool = _make_pool()
+ pool.discover_models(str(tmp_path))
+ entry = pool.get_entry("gemma")
+ assert entry is not None
+ assert entry.engine is None
+ assert entry.supports_audio_input is audio
+ status = pool.get_status()["models"][0]
+ assert status["supports_audio_input"] is audio
+ assert status["loaded"] is False
+
+ entry.engine_type = "batched"
+ assert pool.get_status()["models"][0]["supports_audio_input"] is False
+
def test_discover_models_missing_sole_dir(self, tmp_path):
"""A sole unavailable model dir is skipped instead of failing startup."""
pool = _make_pool(ceiling=10 * 1024**3)
@@ -128,6 +165,41 @@ def test_discover_models_with_pinned(self, small_mock_model_dir):
assert entry_b is not None
assert entry_b.is_pinned is False
+ def test_discover_image_model_preserves_metadata_in_status(self, tmp_path):
+ """Image manifest metadata is copied into EngineEntry and status."""
+ model_dir = tmp_path / "flux-schnell"
+ model_dir.mkdir()
+ (model_dir / "omlx-image-model.json").write_text(
+ json.dumps(
+ {
+ "backend": "mlx-vlm",
+ "base_model": "flux2-klein-4b",
+ "task": ["txt2img", "edit"],
+ "estimated_size": 4096,
+ }
+ )
+ )
+
+ pool = _make_pool(ceiling=10 * 1024**3)
+ pool.discover_models(str(tmp_path))
+
+ entry = pool.get_entry("flux-schnell")
+ assert entry is not None
+ assert entry.model_type == "image"
+ assert entry.engine_type == "image"
+ assert entry.config_model_type == "mlx-vlm"
+ assert entry.capabilities == ["generation", "edit"]
+ assert entry.tasks == ["generation", "edit"]
+ assert entry.image_metadata is not None
+ assert entry.image_metadata["base_model"] == "flux2-klein-4b"
+
+ status_model = pool.get_status()["models"][0]
+ assert status_model["model_type"] == "image"
+ assert status_model["engine_type"] == "image"
+ assert status_model["capabilities"] == ["generation", "edit"]
+ assert status_model["tasks"] == ["generation", "edit"]
+ assert status_model["image_metadata"]["backend"] == "mlx-vlm"
+
class TestExposedProfileModelResolution:
"""Tests for exposed profile model IDs that share a physical engine."""
@@ -554,9 +626,28 @@ def test_missing_model_path_removes_unloaded_entry(self, small_mock_model_dir):
with pytest.raises(ModelNotFoundError) as exc_info:
asyncio.run(pool.get_engine("model-a"))
-
assert exc_info.value.model_id == "model-a"
assert pool.get_entry("model-a") is None
+ assert pool.get_entry("model-a") is None
+
+ def test_image_engine_missing_mlx_vlm_raises_model_loading_error(
+ self, tmp_path, write_z_image_checkpoint
+ ):
+ """Image engine load fails fast when mlx-vlm is unavailable."""
+ write_z_image_checkpoint(tmp_path / "Z-Image-Turbo-mxfp8")
+
+ pool = _make_pool(ceiling=10 * 1024**3)
+ pool.discover_models(str(tmp_path))
+
+ with (
+ patch("omlx.engine_pool.is_mlx_vlm_available", return_value=False),
+ pytest.raises(ModelLoadingError) as exc_info,
+ ):
+ asyncio.run(pool.get_engine("Z-Image-Turbo-mxfp8"))
+
+ assert exc_info.value.model_id == "Z-Image-Turbo-mxfp8"
+ msg = str(exc_info.value)
+ assert "mlx-vlm image support is unavailable" in msg
class TestEnginePoolStatus:
@@ -584,6 +675,21 @@ def test_get_status(self, small_mock_model_dir):
assert model_a_status["pinned"] is True
assert model_a_status["loaded"] is False
+ def test_status_includes_template_reasoning_efforts(self, small_mock_model_dir):
+ template = (
+ "{% set resolved_reasoning_effort = reasoning_effort|default('xhigh') %}"
+ "{% if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %}"
+ "{{ raise_exception('Unexpected reasoning effort') }}{% endif %}"
+ )
+ (small_mock_model_dir / "model-a" / "chat_template.jinja").write_text(template)
+ pool = _make_pool(ceiling=10 * 1024**3)
+ pool.discover_models(str(small_mock_model_dir))
+ models = {model["id"]: model for model in pool.get_status()["models"]}
+ assert models["model-a"]["reasoning_effort_options"] == ["xhigh", "medium", "low"]
+ assert models["model-a"]["reasoning_effort_default"] == "xhigh"
+ assert models["model-b"]["reasoning_effort_options"] == []
+ assert models["model-b"]["reasoning_effort_default"] is None
+
def test_get_model_ids(self, small_mock_model_dir):
"""Test get_model_ids returns all model IDs."""
pool = _make_pool(ceiling=10 * 1024**3)
@@ -599,6 +705,16 @@ def test_get_loaded_model_ids_empty(self, small_mock_model_dir):
assert pool.get_loaded_model_ids() == []
+ def test_get_status_includes_is_loading(self, small_mock_model_dir):
+ """Test get_status includes is_loading field."""
+ pool = _make_pool(ceiling=10 * 1024**3)
+ pool.discover_models(str(small_mock_model_dir))
+
+ status = pool.get_status()
+ for model in status["models"]:
+ assert "is_loading" in model
+ assert model["is_loading"] is False
+
class TestEngineEntry:
"""Tests for EngineEntry dataclass."""
@@ -617,6 +733,9 @@ def test_entry_defaults(self):
assert entry.last_access == 0.0
assert entry.is_loading is False
assert entry.is_pinned is False
+ assert entry.capabilities == []
+ assert entry.tasks == []
+ assert entry.image_metadata is None
def test_entry_with_values(self):
"""Test EngineEntry with custom values."""
@@ -1251,6 +1370,121 @@ def test_recommended_sampling_keeps_ocr_defaults(self, tmp_path):
entry.model_type = "embedding"
assert EnginePool.recommended_sampling_settings(entry) == {}
+ def test_image_override_maps_to_image_engine(self, small_mock_model_dir):
+ """Test that image override changes both model and engine type."""
+ pool = _make_pool(ceiling=10 * 1024**3)
+ pool.discover_models(str(small_mock_model_dir))
+
+ from omlx.model_settings import ModelSettings
+
+ settings_manager = MagicMock()
+ settings_manager.get_settings.side_effect = lambda mid: (
+ ModelSettings(model_type_override="image")
+ if mid == "model-a"
+ else ModelSettings()
+ )
+
+ pool.apply_settings_overrides(settings_manager)
+
+ assert pool.get_entry("model-a").model_type == "image"
+ assert pool.get_entry("model-a").engine_type == "image"
+
+
+class TestImageEngineLoading:
+ """Tests for ImageEngine construction."""
+
+ @pytest.mark.asyncio
+ async def test_load_image_engine_passes_manifest_metadata(self, monkeypatch):
+ """ImageEngine is imported lazily and receives discovery metadata."""
+ created_kwargs = {}
+
+ class FakeImageEngine:
+ def __init__(self, **kwargs):
+ created_kwargs.update(kwargs)
+ self.start_calls = 0
+
+ async def start(self):
+ self.start_calls += 1
+ return None
+
+ fake_module = types.ModuleType("omlx.engine.image")
+ fake_module.ImageEngine = FakeImageEngine
+ monkeypatch.setitem(sys.modules, "omlx.engine.image", fake_module)
+ monkeypatch.setattr("omlx.engine_pool.is_mlx_vlm_available", lambda: True)
+ monkeypatch.setattr("omlx.engine_pool.mx.synchronize", lambda: None)
+ monkeypatch.setattr("omlx.engine_pool.mx.clear_cache", lambda: None)
+
+ pool = _make_pool(ceiling=10 * 1024**3)
+ entry = EngineEntry(
+ model_id="flux-schnell",
+ model_path="/models/flux-schnell",
+ model_type="image",
+ engine_type="image",
+ estimated_size=4096,
+ config_model_type="mlx-vlm",
+ capabilities=["generation"],
+ tasks=["generation"],
+ image_metadata={"backend": "mlx-vlm", "base_model": "flux2-klein-4b"},
+ )
+ pool._entries["flux-schnell"] = entry
+
+ await pool._load_engine("flux-schnell")
+
+ assert isinstance(entry.engine, FakeImageEngine)
+ assert entry.engine.start_calls == 1
+ assert pool.current_model_memory == 4096
+ assert created_kwargs["model_name"] == "/models/flux-schnell"
+ assert created_kwargs["model_id"] == "flux-schnell"
+ assert created_kwargs["model_path"] == "/models/flux-schnell"
+ assert created_kwargs["config_model_type"] == "mlx-vlm"
+ assert created_kwargs["image_metadata"] == {
+ "backend": "mlx-vlm",
+ "base_model": "flux2-klein-4b",
+ }
+ assert created_kwargs["capabilities"] == ["generation"]
+ assert created_kwargs["tasks"] == ["generation"]
+
+ @pytest.mark.asyncio
+ async def test_multiple_image_engines_can_remain_loaded(self, monkeypatch):
+ started = []
+
+ class FakeImageEngine:
+ def __init__(self, **kwargs):
+ self.model_id = kwargs["model_id"]
+
+ async def start(self):
+ started.append(self.model_id)
+
+ fake_module = types.ModuleType("omlx.engine.image")
+ fake_module.ImageEngine = FakeImageEngine
+ monkeypatch.setitem(sys.modules, "omlx.engine.image", fake_module)
+ monkeypatch.setattr("omlx.engine_pool.is_mlx_vlm_available", lambda: True)
+ monkeypatch.setattr("omlx.engine_pool.mx.synchronize", lambda: None)
+ monkeypatch.setattr("omlx.engine_pool.mx.clear_cache", lambda: None)
+
+ pool = _make_pool(ceiling=10 * 1024**3)
+ for model_id in ("first-image", "second-image"):
+ pool._entries[model_id] = EngineEntry(
+ model_id=model_id,
+ model_path=f"/models/{model_id}",
+ model_type="image",
+ engine_type="image",
+ estimated_size=4096,
+ capabilities=["generation"],
+ tasks=["generation"],
+ image_metadata={
+ "backend": "mlx-vlm",
+ "base_model": "flux2-klein-4b",
+ },
+ )
+
+ await pool._load_engine("first-image")
+ await pool._load_engine("second-image")
+
+ assert started == ["first-image", "second-image"]
+ assert pool._entries["first-image"].engine is not None
+ assert pool._entries["second-image"].engine is not None
+
class TestVLMFallback:
"""Tests for VLM-to-LLM fallback during engine loading."""
@@ -1390,17 +1624,26 @@ async def test_force_lm_no_fallback_for_non_vlm(self, small_mock_model_dir):
await pool._load_engine("model-a", force_lm=True)
@pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "config_type,model_type", [("glm5_next", "vlm"), ("flint", "llm")]
+ )
async def test_force_lm_keeps_vlm_engine_for_vlm_native_text_model(
- self, small_mock_model_dir
+ self, small_mock_model_dir, config_type, model_type
):
- """glm5_next has no mlx-lm class: force_lm loads the VLM engine directly
+ """Native families have no mlx-lm class: force_lm loads VLM directly
and never unloads a resident VLM engine to retry the LM load (#3959)."""
+ (small_mock_model_dir / "model-a" / "config.json").write_text(
+ json.dumps({"model_type": config_type})
+ )
pool = _make_pool(ceiling=10 * 1024**3)
pool.discover_models(str(small_mock_model_dir))
entry = pool.get_entry("model-a")
- entry.model_type = "vlm"
- entry.engine_type = "vlm"
- entry.config_model_type = "glm5_next"
+ assert entry.model_type == model_type
+ assert entry.engine_type == "vlm"
+ status = next(m for m in pool.get_status()["models"] if m["id"] == "model-a")
+ assert status["model_type"] == model_type
+ assert status["engine_type"] == "vlm"
+ assert status["config_model_type"] == config_type
mock_vlm_engine = MagicMock()
mock_vlm_engine.start = AsyncMock()
@@ -1423,15 +1666,17 @@ async def test_force_lm_keeps_vlm_engine_for_vlm_native_text_model(
assert pool._force_lm_replaces_engine("model-a") is True
@pytest.mark.asyncio
- async def test_vlm_native_text_model_skips_llm_fallback(self, small_mock_model_dir):
- """A glm5_next VLM start failure surfaces as-is instead of an LLM
+ @pytest.mark.parametrize("config_type", ["glm5_next", "flint"])
+ async def test_vlm_native_text_model_skips_llm_fallback(
+ self, small_mock_model_dir, config_type
+ ):
+ """A native VLM start failure surfaces as-is instead of an LLM
fallback error that can never succeed (#3956)."""
+ (small_mock_model_dir / "model-a" / "config.json").write_text(
+ json.dumps({"model_type": config_type})
+ )
pool = _make_pool(ceiling=10 * 1024**3)
pool.discover_models(str(small_mock_model_dir))
- entry = pool.get_entry("model-a")
- entry.model_type = "vlm"
- entry.engine_type = "vlm"
- entry.config_model_type = "glm5_next"
mock_vlm_engine = MagicMock()
mock_vlm_engine.start = AsyncMock(side_effect=RuntimeError("bad expert table"))
@@ -1976,6 +2221,32 @@ async def test_minimax_bundled_dspark_is_charged_and_takes_the_mtp_depth(
assert load.call_args.args[2:] == (3, False)
engine.set_dflash_drafter.assert_called_once_with(load.return_value)
+ @pytest.mark.asyncio
+ async def test_minicpm_dspark_load_failure_unloads_instead_of_falling_back(
+ self, pool_with_mock_engines
+ ):
+ pool = pool_with_mock_engines
+ entry = pool.get_entry("model-a")
+ entry.model_type = "vlm"
+ entry.engine_type = "vlm"
+ entry.config_model_type = "minicpmv4_7"
+ settings = ModelSettings(dflash_enabled=True, dflash_draft_model="/paired/helper")
+ engine = MagicMock()
+ engine.start = AsyncMock()
+ engine.stop = AsyncMock()
+ with (
+ patch("omlx.engine_pool.VLMBatchedEngine", return_value=engine),
+ patch(
+ "omlx.engine_pool.load_dflash_drafter",
+ side_effect=ValueError("paired helper is incompatible"),
+ ),
+ pytest.raises(ModelUnavailableError, match="paired helper is incompatible"),
+ ):
+ await pool._load_engine("model-a", runtime_settings=settings)
+ engine.stop.assert_awaited_once()
+ assert entry.engine is None
+ assert entry.load_failed
+
@pytest.mark.asyncio
async def test_dflash_drafter_failure_reuses_requested_variant_while_leased(
self, pool_with_mock_engines
@@ -2284,11 +2555,11 @@ async def test_embedding_engine_receives_scheduler_config(self, tmp_path):
with patch(
"omlx.engine_pool.EmbeddingEngine",
return_value=mock_engine,
- ) as MockEmbeddingEngine:
+ ) as mock_embedding_engine_cls:
engine = await pool.get_engine("embed-model")
assert engine is mock_engine
- MockEmbeddingEngine.assert_called_once_with(
+ mock_embedding_engine_cls.assert_called_once_with(
model_name=str(model_path),
trust_remote_code=False,
scheduler_config=scheduler_config,
@@ -2317,11 +2588,11 @@ async def test_embedding_engine_receives_fallback_scheduler_config(self, tmp_pat
with patch(
"omlx.engine_pool.EmbeddingEngine",
return_value=mock_engine,
- ) as MockEmbeddingEngine:
+ ) as mock_embedding_engine_cls:
engine = await pool.get_engine("embed-model")
assert engine is mock_engine
- MockEmbeddingEngine.assert_called_once_with(
+ mock_embedding_engine_cls.assert_called_once_with(
model_name=str(model_path),
trust_remote_code=False,
scheduler_config=pool._scheduler_config,
@@ -2790,7 +3061,6 @@ async def test_insufficient_memory_all_pinned(self, tight_memory_pool):
with pytest.raises(InsufficientMemoryError):
await pool.get_engine("model-b")
-
class TestAdmissionSoftTargetEviction:
"""#2319: idle-model eviction starts at the soft watermark, before load.
@@ -2901,7 +3171,6 @@ async def test_pair_under_soft_target_keeps_both_loaded(
assert pool._entries["model-b"].engine is not None
assert pool.loaded_model_count == 2
-
class TestGuardOffBestEffortAdmission:
"""#2290: model-swap eviction must survive disabling the memory guard.
@@ -4077,6 +4346,37 @@ def test_alias_match(self, small_mock_model_dir):
result = pool.resolve_model_id("gpt-4", settings_manager)
assert result == "model-a"
+ def test_alias_conflicting_with_model_id_is_not_active(self, small_mock_model_dir):
+ """Test aliases that collide with model IDs are ignored."""
+ pool = _make_pool(ceiling=10 * 1024**3)
+ pool.discover_models(str(small_mock_model_dir))
+
+ settings_manager = MagicMock()
+ from omlx.model_settings import ModelSettings
+ settings_manager.get_all_settings.return_value = {
+ "model-a": ModelSettings(model_alias="model-b"),
+ "model-b": ModelSettings(),
+ }
+
+ assert pool.get_active_model_aliases(settings_manager) == {}
+ assert pool.resolve_model_id("model-b", settings_manager) == "model-b"
+ assert pool.resolve_model_id("omlx/model-b", settings_manager) == "model-b"
+
+ def test_duplicate_alias_is_not_active(self, small_mock_model_dir):
+ """Test duplicate aliases are ignored instead of resolving arbitrarily."""
+ pool = _make_pool(ceiling=10 * 1024**3)
+ pool.discover_models(str(small_mock_model_dir))
+
+ settings_manager = MagicMock()
+ from omlx.model_settings import ModelSettings
+ settings_manager.get_all_settings.return_value = {
+ "model-a": ModelSettings(model_alias="gpt-4"),
+ "model-b": ModelSettings(model_alias="gpt-4"),
+ }
+
+ assert pool.get_active_model_aliases(settings_manager) == {}
+ assert pool.resolve_model_id("gpt-4", settings_manager) == "gpt-4"
+
def test_no_match_returns_original(self, small_mock_model_dir):
"""Test unresolved name returns original string."""
pool = _make_pool(ceiling=10 * 1024**3)
@@ -4343,6 +4643,75 @@ async def test_settle_keeps_waiting_while_footprint_pending(
# Pre-unload + 10 settle rounds + the emergency reclaim's own check.
assert mock_mx.get_active_memory.call_count == 12
+ @pytest.mark.asyncio
+ async def test_unload_finishes_after_caller_cancellation(
+ self, pool_with_loaded_model
+ ):
+ """Cancellation cannot strand tensors after the entry is detached."""
+ pool = pool_with_loaded_model
+ entry = pool._entries["model-a"]
+ stop_started = asyncio.Event()
+ allow_stop = asyncio.Event()
+
+ async def blocking_stop():
+ stop_started.set()
+ await allow_stop.wait()
+
+ entry.engine.stop.side_effect = blocking_stop
+ active_memory_values = iter([10 * 1024**3, 5 * 1024**3])
+
+ with (
+ patch("omlx.engine_pool.mx") as mock_mx,
+ patch("omlx.engine_pool.get_mlx_executor", return_value=None),
+ ):
+ mock_mx.get_active_memory.side_effect = lambda: next(
+ active_memory_values, 5 * 1024**3
+ )
+ caller = asyncio.create_task(pool._unload_engine("model-a"))
+ await stop_started.wait()
+
+ caller.cancel()
+ await asyncio.sleep(0)
+ assert not caller.done()
+
+ caller.cancel()
+ await asyncio.sleep(0)
+ assert not caller.done()
+
+ allow_stop.set()
+ with pytest.raises(asyncio.CancelledError):
+ await caller
+
+ assert entry.engine is None
+ assert pool._current_model_memory == 0
+ assert pool._engine_unload_tasks == {}
+
+ @pytest.mark.asyncio
+ async def test_unload_failure_does_not_replace_caller_cancellation(
+ self, pool_with_loaded_model
+ ):
+ """A teardown failure is logged without masking caller cancellation."""
+ pool = pool_with_loaded_model
+ unload_started = asyncio.Event()
+ allow_failure = asyncio.Event()
+
+ async def failing_unload(_model_id):
+ unload_started.set()
+ await allow_failure.wait()
+ raise RuntimeError("teardown failed")
+
+ pool._stop_and_unload_engine = failing_unload
+ caller = asyncio.create_task(pool._unload_engine("model-a"))
+ await unload_started.wait()
+
+ caller.cancel()
+ allow_failure.set()
+ with pytest.raises(asyncio.CancelledError):
+ await caller
+ await asyncio.sleep(0)
+ assert pool._engine_unload_tasks == {}
+ assert pool._unloading_models == set()
+
@pytest.mark.asyncio
async def test_settle_takes_multiple_rounds(self, pool_with_loaded_model):
"""Test settle barrier succeeds after multiple rounds of GC."""
@@ -4615,6 +4984,8 @@ async def test_settle_bails_out_under_concurrent_activity(
other_engine = MagicMock()
other_engine.has_active_requests = MagicMock(return_value=True)
pool._entries["model-b"].engine = other_engine
+ target_engine = pool._entries["model-a"].engine
+ target_engine.stop_without_global_cleanup = AsyncMock()
# Global gauge RISES during settle (concurrent prefill/KV growth),
# so freed = pre_unload - active_now is negative every round.
@@ -4641,15 +5012,30 @@ async def record_sleep(duration, *args, **kwargs):
mock_mx.clear_cache = MagicMock()
await pool._unload_engine("model-a")
+ cleanup_counts_during_activity = (
+ mock_mx.synchronize.call_count,
+ mock_mx.clear_cache.call_count,
+ )
+ assert pool._deferred_mlx_cleanup is True
+
+ other_engine.has_active_requests.return_value = False
+ await pool._run_deferred_mlx_cleanup_if_idle()
+ cleanup_counts_after_drain = (
+ mock_mx.synchronize.call_count,
+ mock_mx.clear_cache.call_count,
+ )
assert "indeterminate under concurrent activity" in caplog.text
# No settle-round burn, no timeout warning, no emergency reclaim.
assert sleep_calls.count(0.5) == 0
assert "Settle barrier timed out" not in caplog.text
assert "Emergency reclaim" not in caplog.text
- # Only the initial pre-barrier release cycle touched the executor.
- assert mock_mx.synchronize.call_count == 1
- assert mock_mx.clear_cache.call_count == 1
+ # No global cleanup is queued behind the active inference.
+ target_engine.stop_without_global_cleanup.assert_awaited_once()
+ target_engine.stop.assert_not_awaited()
+ assert cleanup_counts_during_activity == (0, 0)
+ assert cleanup_counts_after_drain == (1, 1)
+ assert pool._deferred_mlx_cleanup is False
# The unload itself still completes and is accounted.
assert pool._entries["model-a"].engine is None
assert pool._current_model_memory == 0
diff --git a/tests/test_engine_preflight.py b/tests/test_engine_preflight.py
index ef33d056ab..a22ec157c1 100644
--- a/tests/test_engine_preflight.py
+++ b/tests/test_engine_preflight.py
@@ -174,6 +174,8 @@ def _build_engine_with_stub_scheduler(engine_cls, scheduler):
engine._model_name = "test-model"
engine._enable_thinking = None
engine._prefill_eviction_callback = None
+ if isinstance(engine, VLMBatchedEngine):
+ engine._dflash_drafter = None
tokenizer = MagicMock()
tokenizer.apply_chat_template = MagicMock(return_value="hello world")
diff --git a/tests/test_hf_downloader.py b/tests/test_hf_downloader.py
index 3ae325a0dd..8f6f969697 100644
--- a/tests/test_hf_downloader.py
+++ b/tests/test_hf_downloader.py
@@ -32,9 +32,9 @@
DownloadStatus,
DownloadTask,
HFDownloader,
+ _calc_safetensors_disk_size,
_DownloadActivity,
_DownloadCancelled,
- _calc_safetensors_disk_size,
_histogram_has_packed_u32,
_is_xet_transport_error,
_SpeedMeter,
@@ -1259,6 +1259,14 @@ def fake_snapshot_download(**kwargs):
class TestHFDownloaderRoutes:
"""Test admin API endpoints for the HF downloader."""
+ def _make_qwen_image_layout(self, model_dir: Path) -> None:
+ """Create a small LM Studio-style Qwen image directory."""
+ for component in ("text_encoder", "tokenizer", "transformer", "vae"):
+ (model_dir / component).mkdir(parents=True, exist_ok=True)
+ (model_dir / "tokenizer" / "tokenizer.json").write_text("{}")
+ for component in ("text_encoder", "transformer", "vae"):
+ (model_dir / component / "0.safetensors").write_bytes(b"x" * 8)
+
@pytest.fixture
def model_dir_with_models(self, tmp_path):
"""Create a model directory with some fake models."""
@@ -1288,6 +1296,14 @@ def model_dir_with_models(self, tmp_path):
(model_apple / "config.json").write_text('{"architectures": ["TestA"]}')
(model_apple / "model.safetensors").write_bytes(b"a" * 256)
+ # LM Studio Qwen image model without config.json
+ self._make_qwen_image_layout(model_dir / "Qwen-Image-Edit-2511-6bit")
+
+ # Nested LM Studio Qwen image model without config.json
+ self._make_qwen_image_layout(
+ model_dir / "mlx-community" / "Qwen-Image-2512-4bit"
+ )
+
# Directory without config.json (should be excluded)
(model_dir / "not-a-model").mkdir()
@@ -1328,9 +1344,9 @@ async def test_recommendations_report_free_space_of_the_model_folder(
assert result["disk"]["free_bytes"] > 0
@pytest.mark.asyncio
- async def test_list_models(self, model_dir_with_models):
+ async def test_list_models(self, model_dir_with_models, monkeypatch):
"""Test the list_hf_models endpoint logic."""
- from omlx.admin.routes import list_hf_models, _get_global_settings
+ from omlx.admin.routes import list_hf_models
nested_model = (
model_dir_with_models / "deepsweet" / "Qwen3.6-27B-MLX-oQ5-FP16"
@@ -1348,6 +1364,7 @@ async def test_list_models(self, model_dir_with_models):
import omlx.admin.routes as routes_module
+ monkeypatch.setattr(routes_module, "_get_engine_pool", lambda: None)
original = routes_module._get_global_settings
routes_module._get_global_settings = lambda: mock_settings
diff --git a/tests/test_hybrid_batch_cache_patch.py b/tests/test_hybrid_batch_cache_patch.py
new file mode 100644
index 0000000000..1fec863731
--- /dev/null
+++ b/tests/test_hybrid_batch_cache_patch.py
@@ -0,0 +1,37 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Regressions for mixed-length hybrid continuous-batching caches."""
+
+from __future__ import annotations
+
+import mlx.core as mx
+from mlx_lm.models.cache import ArraysCache, BatchKVCache
+
+from omlx.patches.hybrid_batch_cache import apply_hybrid_batch_cache_fixes
+
+
+def test_arrays_cache_mask_combines_left_and_right_padding():
+ assert apply_hybrid_batch_cache_fixes()
+ merged = ArraysCache.merge([ArraysCache(1) for _ in range(3)])
+ merged.prepare(lengths=[4, 2, 1])
+ merged.left_padding = mx.array([1, 0, 0])
+
+ mask = merged.make_mask(4)
+
+ expected = mx.array(
+ [
+ [False, True, True, True],
+ [True, True, False, False],
+ [True, False, False, False],
+ ]
+ )
+ assert mx.array_equal(mask, expected).item()
+
+
+def test_empty_batch_kv_filter_preserves_zero_offset():
+ assert apply_hybrid_batch_cache_fixes()
+ cache = BatchKVCache(left_padding=[2, 1])
+
+ cache.filter([1])
+
+ assert cache._idx == 0
+ assert cache.make_mask(1).shape[-1] == 1
diff --git a/tests/test_markitdown_integration.py b/tests/test_markitdown_integration.py
index 1daf5e5048..8cc16ac1eb 100644
--- a/tests/test_markitdown_integration.py
+++ b/tests/test_markitdown_integration.py
@@ -5,6 +5,7 @@
import asyncio
import base64
+import copy
import json
import logging
import sys
@@ -14,6 +15,7 @@
from unittest.mock import patch
import pytest
+from fastapi import HTTPException
from fastapi.testclient import TestClient
from starlette.responses import StreamingResponse
@@ -567,6 +569,23 @@ def test_preprocess_still_rejects_missing_latest_file_part():
)
+def test_parse_file_part_missing_source_requires_file_data():
+ with pytest.raises(
+ MarkItDownRequestError,
+ match=r"file\.file_data",
+ ):
+ parse_file_part(
+ {
+ "type": "file",
+ "file": {
+ "filename": "paper.pdf",
+ "mime_type": "application/pdf",
+ },
+ },
+ max_file_size_mb=10,
+ )
+
+
def test_async_preprocess_allows_missing_historical_file_parts(monkeypatch):
def fake_convert(file: MarkItDownFile, **kwargs) -> str:
raise AssertionError("missing historical files should not be converted")
@@ -646,6 +665,42 @@ async def exercise():
assert "Attached file unavailable: paper.pdf" in (parts[0].text or "")
+def test_server_llm_preprocess_preserves_media_file_parts():
+ state = ServerState()
+ state.engine_pool = _EmptyPool()
+ state.global_settings = GlobalSettings()
+ request = ChatCompletionRequest(
+ model="test-model",
+ messages=[
+ Message(
+ role="user",
+ content=[
+ {
+ "type": "file",
+ "file": {
+ "filename": "clip.mp4",
+ "mime_type": "video/mp4",
+ "file_data": _data_uri(b"video", mime_type="video/mp4"),
+ },
+ },
+ {"type": "text", "text": "Describe it."},
+ ],
+ )
+ ],
+ )
+
+ async def exercise():
+ with patch("omlx.server._server_state", state):
+ return await server_module._preprocess_markitdown_files_for_llm(request)
+
+ processed = asyncio.run(exercise())
+ content = processed.messages[0].content
+
+ assert isinstance(content, list)
+ assert content[0]["type"] == "input_video"
+ assert content[0]["input_video"]["filename"] == "clip.mp4"
+
+
def test_preprocess_file_parts_rejects_when_disabled():
settings = GlobalSettings()
settings.integrations.markitdown_enabled = False
@@ -657,6 +712,215 @@ def test_preprocess_file_parts_rejects_when_disabled():
)
+@pytest.mark.parametrize("with_file", [False, True])
+def test_responses_preprocessing_preserves_tool_argument_objects(
+ monkeypatch, with_file
+):
+ """Codex tool history must still render after Message validation/file conversion."""
+ from jinja2 import Environment
+
+ from omlx.api.responses_models import ResponsesRequest
+ from omlx.api.responses_utils import convert_responses_input_to_messages
+
+ arguments = {"cmd": "pwd", "options": {"login": False}, "paths": ["a", "b"]}
+ request = ResponsesRequest(
+ model="test-model",
+ input=[
+ {"role": "user", "content": "Inspect the workspace."},
+ {
+ "type": "function_call",
+ "call_id": "call_shell",
+ "name": "exec_command",
+ "arguments": json.dumps(arguments),
+ },
+ {"type": "function_call_output", "call_id": "call_shell", "output": "/tmp"},
+ {"role": "user", "content": "Continue."},
+ ],
+ )
+ messages = convert_responses_input_to_messages(request.input)
+ if with_file:
+ messages[-1]["content"] = [_file_part(), {"type": "text", "text": "Continue."}]
+ monkeypatch.setattr(
+ "omlx.api.markitdown.convert_file_to_markdown",
+ lambda *args, **kwargs: "Converted document",
+ )
+ state = ServerState()
+ state.engine_pool = _EmptyPool()
+ state.global_settings = GlobalSettings()
+ with patch("omlx.server._server_state", state):
+ processed = asyncio.run(
+ server_module._preprocess_response_files_for_llm(messages)
+ )
+
+ call = processed[1]["tool_calls"][0]
+ assert call["function"]["arguments"] == arguments
+ assert call["id"] == "call_shell"
+ assert processed[2] == {
+ "role": "tool",
+ "tool_call_id": "call_shell",
+ "content": "/tmp",
+ }
+ assert all("partial" not in message for message in processed)
+ # Qwen's native tool template uses this filter, which raises on JSON strings.
+ rendered = (
+ Environment()
+ .from_string(
+ "{% for name, value in arguments|items %}{{ name }}={{ value }};{% endfor %}"
+ )
+ .render(arguments=call["function"]["arguments"])
+ )
+ assert "cmd=pwd;" in rendered
+ if with_file:
+ assert "Converted document" in str(processed[-1]["content"])
+
+
+def test_responses_without_files_bypass_message_validation():
+ messages = [
+ {
+ "role": "assistant",
+ "channel": "commentary",
+ "tool_calls": [
+ {
+ "id": "call_1",
+ "function": {
+ "name": "exec_command",
+ "namespace": "functions",
+ "arguments": {"cmd": "pwd"},
+ },
+ }
+ ],
+ },
+ {"role": "tool", "tool_call_id": "call_1", "content": "/tmp"},
+ ]
+ original = copy.deepcopy(messages)
+ with patch.object(server_module, "Message") as message_type:
+ processed = asyncio.run(
+ server_module._preprocess_response_files_for_llm(messages)
+ )
+ message_type.model_validate.assert_not_called()
+ message_type.assert_not_called()
+ assert processed is messages
+ assert messages == original
+
+
+@pytest.mark.parametrize("with_document", [False, True])
+@pytest.mark.parametrize("media_kind,extension", [("audio", "wav"), ("video", "mp4")])
+def test_responses_attachments_preserve_unrelated_history_and_content(
+ monkeypatch, with_document, media_kind, extension
+):
+ monkeypatch.setattr(
+ "omlx.api.markitdown.convert_file_to_markdown", lambda *a, **k: "Document"
+ )
+ messages = [
+ {
+ "role": "assistant",
+ "channel": "commentary",
+ "partial": True,
+ "tool_calls": [
+ {
+ "id": "call_1",
+ "function": {
+ "name": "exec_command",
+ "namespace": "functions",
+ "arguments": {"cmd": "pwd"},
+ },
+ }
+ ],
+ },
+ {
+ "role": "user",
+ "metadata": {"keep": True},
+ "content": [
+ _file_part(f"clip.{extension}", mime_type=f"{media_kind}/{extension}"),
+ {"type": "text", "text": "Describe it.", "metadata": {"keep": True}},
+ ],
+ },
+ ]
+ if with_document:
+ messages[-1]["content"].append(_file_part())
+ original = copy.deepcopy(messages)
+ state = ServerState(engine_pool=_EmptyPool(), global_settings=GlobalSettings())
+ with patch("omlx.server._server_state", state):
+ processed = asyncio.run(
+ server_module._preprocess_response_files_for_llm(messages)
+ )
+ assert messages == original
+ assert processed[0] is messages[0]
+ assert processed[1]["metadata"] == original[1]["metadata"]
+ assert processed[1]["content"][0]["type"] == f"input_{media_kind}"
+ assert processed[1]["content"][1] is messages[1]["content"][1]
+ if with_document:
+ assert processed[1]["content"][2]["type"] == "text"
+ assert "Document" in processed[1]["content"][2]["text"]
+
+
+def test_responses_historical_documents_keep_latest_user_position(monkeypatch):
+ monkeypatch.setattr(
+ "omlx.api.markitdown.convert_file_to_markdown",
+ lambda *a, **k: pytest.fail("Historical placeholder must not be converted"),
+ )
+ messages = [
+ {"role": "user", "content": [_file_part(data="")]},
+ {"role": "assistant", "content": "Done."},
+ {"role": "user", "content": "Continue."},
+ ]
+ # _file_part fills empty data by default; simulate a persisted placeholder.
+ messages[0]["content"][0]["file"]["file_data"] = ""
+ state = ServerState(engine_pool=_EmptyPool(), global_settings=GlobalSettings())
+ with patch("omlx.server._server_state", state):
+ processed = asyncio.run(
+ server_module._preprocess_response_files_for_llm(messages)
+ )
+ assert "Attached file unavailable" in processed[0]["content"][0]["text"]
+ assert processed[1] is messages[1]
+ assert processed[2] is messages[2]
+
+
+@pytest.mark.parametrize("disabled", [False, True])
+def test_responses_document_processing_keeps_request_limits(monkeypatch, disabled):
+ monkeypatch.setattr(
+ "omlx.api.markitdown.convert_file_to_markdown", lambda *a, **k: "Document"
+ )
+ messages = [
+ {"role": "user", "content": [_file_part()]},
+ {"role": "assistant", "content": "Done."},
+ {"role": "user", "content": [_file_part()]},
+ ]
+ state = ServerState(engine_pool=_EmptyPool(), global_settings=GlobalSettings())
+ state.global_settings.integrations.markitdown_max_files_per_request = 1
+ state.global_settings.integrations.markitdown_enabled = not disabled
+ with (
+ patch("omlx.server._server_state", state),
+ pytest.raises(HTTPException) as error,
+ ):
+ asyncio.run(server_module._preprocess_response_files_for_llm(messages))
+ assert error.value.status_code == 400
+ assert ("disabled" if disabled else "Too many attached files") in error.value.detail
+
+
+def test_responses_file_url_is_rejected_without_downloading():
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "file",
+ "file": {
+ "filename": "notes.txt",
+ "mime_type": "text/plain",
+ "file_url": "https://example.com/notes.txt",
+ },
+ }
+ ],
+ }
+ ]
+
+ with patch("urllib.request.build_opener") as download:
+ with pytest.raises(HTTPException, match="File URLs are not supported"):
+ asyncio.run(server_module._preprocess_response_files_for_llm(messages))
+ download.assert_not_called()
+
+
def test_xlsx_is_rejected_without_pandas_dependency():
part = {
"type": "file",
diff --git a/tests/test_model_discovery.py b/tests/test_model_discovery.py
index a496dbce2c..40cca59256 100644
--- a/tests/test_model_discovery.py
+++ b/tests/test_model_discovery.py
@@ -11,6 +11,7 @@
from omlx import gguf
from omlx.model_discovery import (
DiscoveredModel,
+ _detect_audio_input,
_is_adapter_dir,
_is_causal_lm_reranker,
_is_helper_checkpoint,
@@ -32,9 +33,158 @@
is_realtime_voice_model,
model_directory_access_error,
model_display_name,
+ model_unavailable_reason,
)
+class TestAudioInputDiscovery:
+ @pytest.mark.parametrize(
+ ("family", "key", "expected"),
+ [
+ ("gemma4", "audio_tower.layer.weight", True),
+ ("gemma4", "model.audio_tower.layer.weight", True),
+ ("gemma4_unified", "model.embed_audio.projection.weight", True),
+ ("qwen3_omni_moe", "thinker.audio_tower.layer.weight", True),
+ ("inkling_mm_model", "model.audio.encoder.weight", True),
+ ("lfm3_audio", "encoder.downsample.weight", True),
+ ("minicpmo", "apm.conv1.weight", True),
+ ("gemma4", "vision_tower.layer.weight", False),
+ ("gemma4", "audio_decoder.layer.weight", False),
+ ("unknown", "vision_tower.layer.weight", None),
+ ],
+ )
+ def test_audio_input_weight_layouts(self, tmp_path, family, key, expected):
+ _write_safetensors(tmp_path / "model.safetensors", {key: ("F32", [1])})
+ config = {"model_type": family, "audio_config": {"hidden_size": 16}}
+ assert _detect_audio_input(tmp_path, config, "vlm") is expected
+
+ @pytest.mark.parametrize(
+ "sidecar", ["omnimodal/audio_encoder.safetensors", "optiq/vision.safetensors"]
+ )
+ def test_audio_input_sidecars(self, tmp_path, sidecar):
+ path = tmp_path / sidecar
+ path.parent.mkdir()
+ _write_safetensors(path, {"audio_encoder.weight": ("F32", [1])})
+ config = {"model_type": "mimo_v2"}
+ if sidecar.startswith("optiq/"):
+ config["optiq_vision"] = {"sidecar": sidecar}
+ assert _detect_audio_input(tmp_path, config, "vlm") is True
+
+ @pytest.mark.parametrize("model_type", ["llm", "audio_stt", "audio_tts", "audio_sts"])
+ def test_audio_input_is_only_detected_for_multimodal_chat(self, tmp_path, model_type):
+ config = {"model_type": "gemma4", "audio_config": {"hidden_size": 16}}
+ expected = False if model_type == "llm" else None
+ assert _detect_audio_input(tmp_path, config, model_type) is expected
+
+ @pytest.mark.parametrize("corrupt", [True, False])
+ def test_missing_or_unreadable_weights_are_unknown(self, tmp_path, caplog, corrupt):
+ if corrupt:
+ (tmp_path / "model.safetensors").write_bytes(b"corrupt")
+ assert _detect_audio_input(
+ tmp_path, {"model_type": "gemma4", "audio_config": {}}, "vlm"
+ ) is None
+ if corrupt:
+ assert "Cannot inspect audio input weights" in caplog.text
+
+ def test_audio_sidecar_must_stay_inside_model(self, tmp_path, caplog):
+ config = {
+ "model_type": "gemma4",
+ "audio_config": {},
+ "optiq_vision": {"sidecar": "../outside.safetensors"},
+ }
+ assert _detect_audio_input(tmp_path, config, "vlm") is None
+ assert "invalid OptiQ sidecar" in caplog.text
+
+ @pytest.mark.parametrize(
+ "config",
+ [
+ {"model_type": "minicpmo", "init_audio": False},
+ {"model_type": "gemma4"},
+ {"model_type": "gemma4", "audio_config": None},
+ {"model_type": "gemma4_unified", "audio_config": None},
+ ],
+ )
+ def test_disabled_audio_is_not_advertised(self, tmp_path, config):
+ _write_safetensors(
+ tmp_path / "model.safetensors", {"audio_tower.weight": ("F32", [1])}
+ )
+ assert _detect_audio_input(tmp_path, config, "vlm") is False
+
+
+class TestImageModelDiscovery:
+ def test_native_flux3_root_config_is_discovered(self, tmp_path):
+ pytest.importorskip("mlx_vlm")
+ model = tmp_path / "native-flux3"
+ model.mkdir()
+ (model / "config.json").write_text(
+ json.dumps(
+ {
+ "model": "flux-3-image-klein",
+ "dit": {
+ "in_channels": {
+ "image": 128,
+ "image_cond": 128,
+ "text": 20480,
+ }
+ },
+ }
+ )
+ )
+ (model / "model.safetensors").write_bytes(b"0" * 100)
+
+ discovered = discover_models(tmp_path)[model.name]
+
+ assert discovered.model_type == discovered.engine_type == "image"
+ assert discovered.capabilities == discovered.tasks == ["generation", "edit"]
+
+ def test_mlx_vlm_image_layout_is_discovered(
+ self, tmp_path, write_z_image_checkpoint
+ ):
+ write_z_image_checkpoint(tmp_path / "custom-folder")
+
+ discovered = discover_models(tmp_path)["custom-folder"]
+
+ assert discovered.model_type == discovered.engine_type == "image"
+ assert discovered.config_model_type == "mlx-vlm"
+ assert discovered.capabilities == discovered.tasks == ["generation", "edit"]
+
+ def test_unrecognized_diffusion_layout_is_not_an_image_model(self, tmp_path):
+ model = tmp_path / "unknown-pipeline"
+ model.mkdir()
+ (model / "model_index.json").write_text('{"_class_name": "UnknownPipeline"}')
+ (model / "transformer").mkdir()
+ (model / "transformer" / "model.safetensors").write_bytes(b"0" * 100)
+
+ assert "unknown-pipeline" not in discover_models(tmp_path)
+
+ def test_diffusion_gemma_stays_on_text_path(self, tmp_path):
+ model = tmp_path / "diffusion-gemma"
+ model.mkdir()
+ (model / "config.json").write_text(
+ json.dumps({"model_type": "diffusion_gemma"})
+ )
+ (model / "model.safetensors").write_bytes(b"0" * 100)
+
+ discovered = discover_models(tmp_path)[model.name]
+
+ assert discovered.model_type != "image"
+ assert discovered.engine_type != "image"
+
+ def test_hf_cache_accepts_image_component_layout(
+ self, tmp_path, write_z_image_checkpoint
+ ):
+ write_z_image_checkpoint(
+ tmp_path / "models--Tongyi-MAI--Z-Image" / "snapshots" / "abc"
+ )
+
+ discovered = discover_models(tmp_path)["Tongyi-MAI--Z-Image"]
+
+ assert discovered.model_type == "image"
+ assert discovered.tasks == ["generation", "edit"]
+ assert discovered.source_type == "hf_cache"
+ assert discovered.source_repo_id == "Tongyi-MAI/Z-Image"
+
+
def _write_safetensors(path, tensors):
"""Write a minimal valid safetensors file: name -> (dtype, shape)."""
dtype_bytes = {"F16": 2, "BF16": 2, "F32": 4, "U32": 4}
@@ -95,6 +245,33 @@ def test_dflash_draft_via_config_block(self):
config = {"model_type": "qwen3", "dflash_config": {"block_size": 16}}
assert is_helper_model_config(config) is True
+ def test_minicpm_dspark_is_helper_not_independent_chat_model(self, tmp_path):
+ config = {
+ "model_type": "qwen3",
+ "architectures": ["Qwen3DSparkModel"],
+ "dflash_config": {
+ "projector_type": "dspark",
+ "target_layer_ids": [3, 11, 19, 27, 35],
+ },
+ }
+ (tmp_path / "config.json").write_text(json.dumps(config))
+ assert is_helper_model_config(config)
+ assert _is_helper_checkpoint(tmp_path)
+
+ def test_minicpm_target_is_not_helper_despite_embedded_mtp_config(self, tmp_path):
+ config = {
+ "model_type": "minicpmv4_7",
+ "architectures": ["MiniCPMV4_7ForConditionalGeneration"],
+ "text_config": {
+ "model_type": "qwen3_5_moe_text",
+ "mtp_num_hidden_layers": 1,
+ },
+ "vision_config": {"model_type": "minicpmv4_7_vision"},
+ }
+ (tmp_path / "config.json").write_text(json.dumps(config))
+ assert not is_helper_model_config(config)
+ assert detect_model_type(tmp_path) == "vlm"
+
def test_assistant_via_model_type(self):
config = {
"model_type": "gemma4_assistant",
@@ -344,6 +521,29 @@ def test_detect_qwen3_vl_without_rerank_or_embed_name_is_vlm(self, tmp_path):
(vlm_dir / "config.json").write_text(json.dumps(config))
assert detect_model_type(vlm_dir) == "vlm"
+ def test_detect_qwen4_exp_official_config_as_vlm(self, tmp_path):
+ config = {
+ "model_type": "qwen4_exp",
+ "architectures": ["Qwen4ExpForConditionalGeneration"],
+ "text_config": {"model_type": "qwen4_exp_text"},
+ "vision_config": {"hidden_size": 1152},
+ }
+ (tmp_path / "config.json").write_text(json.dumps(config))
+
+ assert detect_model_type(tmp_path) == "vlm"
+ assert model_unavailable_reason("qwen4_exp") is None
+
+ def test_qwen4_exp_without_vision_is_available_as_llm(self, tmp_path):
+ config = {
+ "model_type": "qwen4_exp",
+ "architectures": ["Qwen4ExpForConditionalGeneration"],
+ "text_config": {"model_type": "qwen4_exp_text"},
+ }
+ (tmp_path / "config.json").write_text(json.dumps(config))
+
+ assert detect_model_type(tmp_path) == "llm"
+ assert model_unavailable_reason("qwen4_exp") is None
+
def test_missing_config_defaults_to_llm(self, tmp_path):
"""Test that missing config.json defaults to LLM."""
assert detect_model_type(tmp_path) == "llm"
@@ -378,14 +578,20 @@ def test_detect_diffusion_gemma_as_vlm(self, tmp_path):
assert detect_model_type(tmp_path) == "vlm"
@pytest.mark.parametrize(
- "model_type,architecture",
- [("cohere2_moe", "Cohere2MoeForCausalLM"), ("flint", "FlintForCausalLM")],
+ "model_type,architecture,expected_type",
+ [
+ ("cohere2_moe", "Cohere2MoeForCausalLM", "vlm"),
+ ("flint", "FlintForCausalLM", "llm"),
+ ("Flint", "FlintForCausalLM", "llm"),
+ ],
)
- def test_detect_native_text_model_as_vlm(self, tmp_path, model_type, architecture):
- """Text-only families implemented by mlx-vlm route to the VLM engine."""
+ def test_detect_native_text_model(
+ self, tmp_path, model_type, architecture, expected_type
+ ):
+ """Flint's text-only capabilities are independent of its mlx-vlm loader."""
config = {"model_type": model_type, "architectures": [architecture]}
(tmp_path / "config.json").write_text(json.dumps(config))
- assert detect_model_type(tmp_path) == "vlm"
+ assert detect_model_type(tmp_path) == expected_type
def test_detect_text_only_deepseek_v41_as_vlm(self, tmp_path):
"""oQ text-only V4.1 exports drop vision_config but stay on mlx-vlm."""
@@ -788,6 +994,20 @@ def test_transformer_only_modules_json_is_not_embedding(self, tmp_path):
(tmp_path / "modules.json").write_text(json.dumps(modules))
assert detect_model_type(tmp_path) == "llm"
+ def test_detect_embedding_gemma2_without_sentence_transformers_modules(
+ self, tmp_path
+ ):
+ (tmp_path / "config.json").write_text(
+ json.dumps(
+ {
+ "model_type": "embedding_gemma2",
+ "architectures": ["EmbeddingGemma2Model"],
+ "vision_config": {"model_type": "gemma4_vision"},
+ }
+ )
+ )
+ assert detect_model_type(tmp_path) == "embedding"
+
def test_detect_embedding_gemma2_with_vision_config_as_embedding(self, tmp_path):
"""EmbeddingGemma 2 ships a vision_config and sentence-transformers v6 modules."""
config = {
@@ -1911,6 +2131,32 @@ def test_mixed_valid_invalid_dirs(self, tmp_path):
class TestUnsupportedModels:
"""Tests for _is_unsupported_model() — audio models are now supported."""
+ @pytest.mark.parametrize(
+ ("model_type", "architectures"),
+ [
+ ("gemma4_assistant", ["Gemma4AssistantForCausalLM"]),
+ ("gemma4_unified_assistant", ["Gemma4UnifiedAssistantForCausalLM"]),
+ ("qwen3_5_mtp", None),
+ ],
+ )
+ def test_vlm_mtp_helpers_are_discovered(
+ self, tmp_path, model_type, architectures
+ ):
+ """Assistant/MTP checkpoints must reach status and drafter selectors."""
+ model_dir = tmp_path / model_type
+ model_dir.mkdir()
+ config = {"model_type": model_type}
+ if architectures is not None:
+ config["architectures"] = architectures
+ (model_dir / "config.json").write_text(json.dumps(config))
+ (model_dir / "model.safetensors").write_bytes(b"0" * 1000)
+
+ models = discover_models(tmp_path)
+
+ assert _is_unsupported_model(model_dir) is False
+ assert models[model_type].is_helper is True
+ assert models[model_type].config_model_type == model_type
+
def test_whisper_not_unsupported(self, tmp_path):
"""Whisper is now an audio_stt model, not unsupported."""
config = {
diff --git a/tests/test_model_loading.py b/tests/test_model_loading.py
index b2415ab688..02fe26bbf6 100644
--- a/tests/test_model_loading.py
+++ b/tests/test_model_loading.py
@@ -502,6 +502,36 @@ def test_vlm_patches_skipped_when_not_for_vlm(self, tmp_path, monkeypatch):
runtime_mock.assert_not_called()
assert calls == []
+ @pytest.mark.parametrize("model_type", ["minimax_m3", "minimax_m3_vl"])
+ @pytest.mark.parametrize("enabled", [False, True])
+ def test_minimax_bundled_dspark_does_not_require_native_mtp_weights(
+ self, tmp_path, monkeypatch, model_type, enabled
+ ):
+ self._stub_patches(monkeypatch)
+ monkeypatch.setitem(
+ sys.modules, "omlx.patches.mlx_vlm_minimax_m3_compat", MagicMock()
+ )
+ monkeypatch.setitem(
+ sys.modules,
+ "omlx.patches.minimax_m3_dspark",
+ types.SimpleNamespace(bundled_dspark_path=lambda _: tmp_path / "dspark"),
+ )
+ path = _write_config(
+ tmp_path, json.dumps({"model_type": model_type, "text_config": {}})
+ )
+ _write_mtp_index(tmp_path, has_mtp=False)
+
+ maybe_apply_pre_load_patches(
+ path,
+ model_settings=types.SimpleNamespace(mtp_enabled=enabled),
+ for_vlm=True,
+ )
+
+ lm_patch = sys.modules["omlx.patches.mlx_lm_mtp"]
+ lm_patch.set_mtp_active.assert_called_with(enabled)
+ vlm_patch = sys.modules["omlx.patches.mlx_vlm_mtp"]
+ vlm_patch.set_mtp_attach_enabled.assert_called_once_with(False)
+
def test_gemma4_merged_assistant_dispatch(self, tmp_path, monkeypatch):
# Gemma 4 merged-assistant checkpoints (assistant weights under
# language_model.mtp.* + text_config.mtp_assistant_config) route
diff --git a/tests/test_model_recommender.py b/tests/test_model_recommender.py
index 19a19beb82..9cbd744232 100644
--- a/tests/test_model_recommender.py
+++ b/tests/test_model_recommender.py
@@ -98,6 +98,31 @@ def make_family(
CATALOG = [QWEN_27B, GEMMA_31B, QWEN_35B_A3B, FLASH_NEXT, GLM]
+@pytest.mark.parametrize(
+ ("data", "valid"),
+ [
+ ({}, True),
+ ({"model_type": "qwen3_5"}, True),
+ ([], False),
+ ("text", False),
+ (None, False),
+ ],
+)
+def test_hub_json_requires_object(monkeypatch, data, valid):
+ response = SimpleNamespace(json=lambda: data)
+ monkeypatch.setattr(
+ rec,
+ "get_session",
+ lambda: SimpleNamespace(get=lambda *args, **kwargs: response),
+ )
+ monkeypatch.setattr(rec, "hf_raise_for_status", lambda response: None)
+ if valid:
+ assert rec._read_json(None, "Jundot/model", "config.json", "revision") == data
+ else:
+ with pytest.raises(ValueError, match="Jundot/model/config.json.*JSON object"):
+ rec._read_json(None, "Jundot/model", "config.json", "revision")
+
+
def mac(monkeypatch, ram_gib, *, metal_gib=None, tier="balanced", guard=True):
"""MemoryInputs for a Mac whose Metal cap is macOS's default unless given."""
ram = ram_gib * GiB
diff --git a/tests/test_model_warmup.py b/tests/test_model_warmup.py
new file mode 100644
index 0000000000..e5728632af
--- /dev/null
+++ b/tests/test_model_warmup.py
@@ -0,0 +1,226 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Regression tests for nonblocking integration model warm-up."""
+
+import asyncio
+import json
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock
+
+import httpx
+import pytest
+from fastapi import HTTPException
+from fastapi.testclient import TestClient
+
+import omlx.server as server
+from omlx.exceptions import EnginePoolError
+from omlx.server import ServerState, load_model_public
+
+
+@pytest.fixture
+async def state(monkeypatch):
+ pool = MagicMock()
+ pool.get_entry.return_value = SimpleNamespace(engine=None, is_loading=False)
+ pool.get_engine = AsyncMock()
+ state = ServerState(engine_pool=pool)
+ monkeypatch.setattr(server, "_server_state", state)
+ yield state
+ tasks = list(state.model_load_tasks.values())
+ for task in tasks:
+ task.cancel()
+ if tasks:
+ await asyncio.gather(*tasks, return_exceptions=True)
+
+
+@pytest.mark.asyncio
+async def test_background_load_acknowledges_before_completion_and_deduplicates(state):
+ started = asyncio.Event()
+ finish = asyncio.Event()
+
+ async def load(model_id):
+ started.set()
+ await finish.wait()
+ state.engine_pool.get_entry.return_value.engine = object()
+
+ state.engine_pool.get_engine.side_effect = load
+ response = await asyncio.wait_for(load_model_public("model", wait=False), timeout=1)
+ assert response.status_code == 202
+ assert json.loads(response.body) == {
+ "status": "loading",
+ "model_id": "model",
+ "message": "Loading model",
+ }
+ await asyncio.wait_for(started.wait(), timeout=1)
+ task = state.model_load_tasks["model"]
+ assert not task.done()
+
+ repeated = await load_model_public("model", wait=False)
+ assert repeated.status_code == 202
+ assert state.model_load_tasks["model"] is task
+ state.engine_pool.get_engine.assert_awaited_once_with("model")
+
+ finish.set()
+ await task
+ await asyncio.sleep(0)
+ assert state.model_load_tasks == {}
+ assert (await load_model_public("model", wait=False))["status"] == "ok"
+ state.engine_pool.get_engine.assert_awaited_once()
+
+
+@pytest.mark.asyncio
+async def test_waiting_load_retains_blocking_behavior(state):
+ finish = asyncio.Event()
+
+ async def load(model_id):
+ await finish.wait()
+
+ state.engine_pool.get_engine.side_effect = load
+ request = asyncio.create_task(load_model_public("model"))
+ try:
+ await asyncio.sleep(0)
+ assert not request.done()
+ assert state.model_load_tasks == {}
+ finish.set()
+ assert await request == {
+ "status": "ok",
+ "model_id": "model",
+ "message": "Loaded model",
+ }
+ finally:
+ request.cancel()
+ await asyncio.gather(request, return_exceptions=True)
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("wait", [False, True])
+async def test_loaded_model_does_not_schedule_work(state, wait):
+ state.engine_pool.get_entry.return_value.engine = object()
+ assert (await load_model_public("model", wait=wait))["status"] == "ok"
+ assert state.model_load_tasks == {}
+ state.engine_pool.get_engine.assert_not_awaited()
+
+
+@pytest.mark.asyncio
+async def test_http_background_load_returns_while_engine_is_loading(state):
+ started = asyncio.Event()
+ finish = asyncio.Event()
+
+ async def load(model_id):
+ started.set()
+ await finish.wait()
+
+ state.api_key = "secret"
+ state.engine_pool.get_engine.side_effect = load
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=server.app), base_url="http://omlx"
+ ) as client:
+ response = await asyncio.wait_for(
+ client.post(
+ "/v1/models/model/load",
+ params={"wait": "false"},
+ headers={"Authorization": "Bearer secret"},
+ ),
+ timeout=1,
+ )
+ assert response.status_code == 202
+ assert response.json()["model_id"] == "model"
+ assert response.json()["status"] == "loading"
+ await asyncio.wait_for(started.wait(), timeout=1)
+ task = state.model_load_tasks["model"]
+ assert not task.done()
+ finish.set()
+ await task
+
+
+@pytest.mark.asyncio
+async def test_existing_load_does_not_schedule_duplicate(state):
+ state.engine_pool.get_entry.return_value.is_loading = True
+ response = await load_model_public("model", wait=False)
+ assert response.status_code == 202
+ assert state.model_load_tasks == {}
+ state.engine_pool.get_engine.assert_not_awaited()
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("wait", [False, True])
+async def test_missing_model_is_rejected_before_scheduling(state, wait):
+ state.engine_pool.get_entry.return_value = None
+ with pytest.raises(HTTPException) as exc:
+ await load_model_public("missing", wait=wait)
+ assert exc.value.status_code == 404
+ assert state.model_load_tasks == {}
+ state.engine_pool.get_engine.assert_not_awaited()
+
+
+@pytest.mark.asyncio
+async def test_background_failure_is_logged_and_task_can_be_rescheduled(state, caplog):
+ state.engine_pool.get_engine.side_effect = EnginePoolError("load failed")
+ response = await load_model_public("model", wait=False)
+ assert response.status_code == 202
+ await state.model_load_tasks["model"]
+ await asyncio.sleep(0)
+ assert "Background model load failed for model" in caplog.text
+ assert "load failed" in caplog.text
+ assert state.model_load_tasks == {}
+
+ state.engine_pool.get_engine.side_effect = None
+ await load_model_public("model", wait=False)
+ await state.model_load_tasks["model"]
+ await asyncio.sleep(0)
+ assert state.engine_pool.get_engine.await_count == 2
+ assert state.model_load_tasks == {}
+
+
+@pytest.mark.asyncio
+async def test_waiting_load_retains_error_mapping(state):
+ state.engine_pool.get_engine.side_effect = EnginePoolError("load failed")
+ with pytest.raises(HTTPException) as exc:
+ await load_model_public("model")
+ assert exc.value.status_code == 500
+ assert exc.value.detail == "load failed"
+
+
+def test_background_load_requires_management_auth(monkeypatch):
+ monkeypatch.setattr(server, "_server_state", ServerState(api_key="secret"))
+ response = TestClient(server.app).post("/v1/models/model/load?wait=false")
+ assert response.status_code == 401
+
+
+@pytest.mark.asyncio
+async def test_shutdown_cancels_background_load_before_pool_shutdown(
+ state, monkeypatch
+):
+ started = asyncio.Event()
+ cancelled = asyncio.Event()
+
+ async def load(model_id):
+ started.set()
+ try:
+ await asyncio.Event().wait()
+ finally:
+ cancelled.set()
+
+ async def shutdown():
+ assert cancelled.is_set()
+ assert state.model_load_tasks == {}
+
+ state.engine_pool.get_engine.side_effect = load
+ state.engine_pool.preload_pinned_models = AsyncMock()
+ state.engine_pool.shutdown = AsyncMock(side_effect=shutdown)
+ monkeypatch.delenv("OMLX_MCP_CONFIG", raising=False)
+ monkeypatch.setattr(server, "_reset_boundary_snapshots_for_server", lambda: None)
+ monkeypatch.setattr(server, "get_server_metrics", MagicMock())
+ monkeypatch.setattr(
+ "omlx.cluster.launch.reap_orphaned_launches",
+ lambda: {"reaped": [], "failures": []},
+ )
+ monkeypatch.setattr(
+ "omlx.cluster.worker_shim.ensure_cluster_python_shim", lambda: None
+ )
+
+ async with server.lifespan(server.app):
+ await load_model_public("model", wait=False)
+ await asyncio.wait_for(started.wait(), timeout=1)
+ task = state.model_load_tasks["model"]
+
+ assert task.cancelled()
+ state.engine_pool.shutdown.assert_awaited_once()
diff --git a/tests/test_optional_deps.py b/tests/test_optional_deps.py
new file mode 100644
index 0000000000..77d125ba82
--- /dev/null
+++ b/tests/test_optional_deps.py
@@ -0,0 +1,41 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Tests for optional dependency helpers."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from omlx.utils import optional_deps
+
+
+def test_mlx_vlm_availability_uses_find_spec_without_importing(monkeypatch):
+ calls: list[str] = []
+
+ def fake_find_spec(name: str):
+ calls.append(name)
+ return SimpleNamespace()
+
+ monkeypatch.setattr(optional_deps, "find_spec", fake_find_spec)
+
+ assert optional_deps.is_mlx_vlm_available() is True
+ assert calls == ["mlx_vlm"]
+
+
+def test_mlx_vlm_availability_false_when_spec_missing(monkeypatch):
+ monkeypatch.setattr(optional_deps, "find_spec", lambda name: None)
+
+ assert optional_deps.is_mlx_vlm_available() is False
+
+
+def test_require_mlx_vlm_available_raises_core_dependency_error(monkeypatch):
+ monkeypatch.setattr(optional_deps, "find_spec", lambda name: None)
+
+ with pytest.raises(ImportError) as exc_info:
+ optional_deps.require_mlx_vlm_available()
+
+ message = str(exc_info.value)
+ assert "mlx-vlm image support is unavailable" in message
+ assert "required mlx-vlm dependency" in message
+ assert "omlx[image]" not in message
diff --git a/tests/test_output_collector.py b/tests/test_output_collector.py
index 70b66591b0..52d8c99312 100644
--- a/tests/test_output_collector.py
+++ b/tests/test_output_collector.py
@@ -345,6 +345,7 @@ def test_clear_resets_waiting_flag(self):
collector.clear()
assert collector._is_waiting is False
+ assert RequestOutputCollector._waiting_consumers == initial_count
class TestRequestOutputCollectorMergeOutputs:
diff --git a/tests/test_paged_cache.py b/tests/test_paged_cache.py
index a86ba48934..75d214a2e1 100644
--- a/tests/test_paged_cache.py
+++ b/tests/test_paged_cache.py
@@ -6,8 +6,8 @@
architecture, adapted for MLX on Apple Silicon.
"""
-from typing import List
-from unittest.mock import MagicMock, patch
+from typing import get_type_hints
+from unittest.mock import MagicMock
import pytest
@@ -23,6 +23,18 @@
)
+@pytest.mark.parametrize(
+ "method",
+ [
+ PagedCacheManager.register_tail_block,
+ PagedCacheManager.seed_tail_blocks,
+ PagedCacheManager._match_tail_block,
+ ],
+)
+def test_tail_cache_annotations_resolve(method):
+ assert get_type_hints(method)
+
+
class TestComputeBlockHash:
"""Tests for compute_block_hash function."""
diff --git a/tests/test_per_engine_threads.py b/tests/test_per_engine_threads.py
index 8978a7b5f5..24a4eab44d 100644
--- a/tests/test_per_engine_threads.py
+++ b/tests/test_per_engine_threads.py
@@ -1,6 +1,8 @@
+# SPDX-License-Identifier: Apache-2.0
"""Tests for per-engine thread isolation (issue #1248)."""
import concurrent.futures
+import threading
from types import SimpleNamespace
from unittest.mock import MagicMock, call, patch
@@ -250,6 +252,50 @@ def test_engine_passes_stream_to_scheduler(self):
engine.close()
+ def test_engine_stream_created_on_executor_thread(self):
+ """The per-engine MLX stream must be owned by the worker thread.
+
+ MLX thread-local streams created on the caller thread cannot be used
+ from scheduler.step() on the engine executor thread.
+ """
+ mock_model = MagicMock()
+ mock_model.model_type = "test"
+ mock_tokenizer = MagicMock()
+ mock_tokenizer.eos_token_id = 0
+ main_thread_id = threading.get_ident()
+ stream = object()
+ created_on: list[tuple[int, str]] = []
+
+ def create_stream():
+ created_on.append((threading.get_ident(), threading.current_thread().name))
+ return stream
+
+ with (
+ patch("omlx.engine_core.get_registry") as mock_registry,
+ patch(
+ "omlx.engine_core._create_mlx_thread_stream",
+ side_effect=create_stream,
+ ),
+ patch(
+ "omlx.engine_core.share_command_queue",
+ return_value=1,
+ ) as mock_share_queue,
+ patch("omlx.engine_core._final_engine_thread_reclaim"),
+ ):
+ mock_registry.return_value.acquire.return_value = True
+
+ engine = EngineCore(mock_model, mock_tokenizer)
+ try:
+ assert engine._mlx_stream is stream
+ assert engine.scheduler._stream is stream
+ mock_share_queue.assert_called_once_with(stream)
+ assert created_on
+ thread_id, thread_name = created_on[0]
+ assert thread_id != main_thread_id
+ assert thread_name.startswith("mlx-engine-")
+ finally:
+ engine.close()
+
def test_close_reclaims_then_shuts_down_worker(self):
"""MLX 0.32.2 workers shut down normally after final reclaim."""
mock_model = MagicMock()
diff --git a/tests/test_qwen38_modelopt_mixed.py b/tests/test_qwen38_modelopt_mixed.py
index 0bdb631011..5626c0b01d 100644
--- a/tests/test_qwen38_modelopt_mixed.py
+++ b/tests/test_qwen38_modelopt_mixed.py
@@ -64,6 +64,15 @@ def test_config_gate_accepts_validated_unsloth_qwen38_shape():
assert bridge.is_supported_config(_config())
+def test_config_gate_rejects_qwen4_exp():
+ config = _config()
+ config["model_type"] = "qwen4_exp"
+ config["architectures"] = ["Qwen4ExpForConditionalGeneration"]
+ config["text_config"]["model_type"] = "qwen4_exp_text"
+
+ assert not bridge.is_supported_config(config)
+
+
@pytest.mark.parametrize(
("path", "value"),
[
diff --git a/tests/test_qwen4_mxfp4_ple.py b/tests/test_qwen4_mxfp4_ple.py
new file mode 100644
index 0000000000..37ed102844
--- /dev/null
+++ b/tests/test_qwen4_mxfp4_ple.py
@@ -0,0 +1,470 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Native MXFP4 selected-row compatibility for Qwen4 PLE mmap storage."""
+
+from __future__ import annotations
+
+import json
+import struct
+from dataclasses import asdict
+
+import mlx.core as mx
+import mlx.nn as nn
+import pytest
+from mlx.utils import tree_flatten
+
+from omlx.patches import mlx_vlm_qwen4_exp_compat as compat
+from omlx.patches.mlx_vlm_qwen4_exp_compat.ple_load_resources import (
+ ple_load_resources,
+)
+
+SOURCE_PREFIX = "model.language_model.layers.1.ple.ple_embedding.ngram_embedding"
+RUNTIME_PREFIX = "language_model.model.layers.1.ple.ple_embedding.ngram_embedding"
+
+
+@pytest.fixture
+def ple():
+ compat.apply_mlx_vlm_qwen4_exp_compat_patch()
+ from mlx_vlm.models.qwen4_exp import language
+
+ return language
+
+
+def _shard(rows, dims, offset, mode):
+ columns = mx.arange(dims)
+ values = (
+ ((columns % 16).astype(mx.float32) - 8)
+ * mx.power(2.0, columns // 32 - 2)
+ * (mx.arange(offset + 1, offset + rows + 1)[:, None] / 4)
+ )
+ values = mx.where((columns // 32) == 2, 0, values).astype(mx.bfloat16)
+ embedding = nn.Embedding(rows, dims)
+ embedding.weight = values
+ if mode == "dense":
+ return embedding, {"weight": values}
+ embedding = nn.QuantizedEmbedding.from_embedding(
+ embedding, group_size=32, bits=8 if mode == "mxfp8" else 4, mode=mode
+ )
+ tensors = {"weight": embedding.weight, "scales": embedding.scales}
+ if embedding.biases is not None:
+ tensors["biases"] = embedding.biases
+ return embedding, tensors
+
+
+def _checkpoint(
+ path, modes=("mxfp4",) * 3, *, prefix=RUNTIME_PREFIX, spelling="shards"
+):
+ sizes = (4, 4, 3)
+ oracles = []
+ weight_map = {}
+ offset = 0
+ for index, (rows, mode) in enumerate(zip(sizes, modes)):
+ oracle, tensors = _shard(rows, 160, offset, mode)
+ oracles.append(oracle)
+ base = (
+ f"{prefix}.shards.{index}"
+ if spelling == "shards"
+ else f"{prefix}.shard_{index}"
+ )
+ for family, tensor in tensors.items():
+ key = f"{base}.{family}"
+ filename = f"shard-{index}-{family}.safetensors"
+ mx.save_safetensors(str(path / filename), {key: tensor})
+ weight_map[key] = filename
+ offset += rows
+ (path / "model.safetensors.index.json").write_text(
+ json.dumps({"weight_map": weight_map})
+ )
+ return oracles
+
+
+def _expected(oracles, host, shape, scale):
+ table = mx.concatenate(
+ [
+ oracle(mx.arange(oracle.weight.shape[0])).astype(mx.bfloat16)
+ for oracle in oracles
+ ]
+ )
+ return (table[mx.array(host, dtype=mx.int32)] * scale).reshape(*shape, 160)
+
+
+@pytest.mark.parametrize("prefix", [SOURCE_PREFIX, RUNTIME_PREFIX])
+@pytest.mark.parametrize("spelling", ["shards", "shard"])
+def test_native_mxfp4_ple_matches_mlx_embedding(tmp_path, ple, prefix, spelling):
+ oracles = _checkpoint(tmp_path, prefix=prefix, spelling=spelling)
+ with ple_load_resources():
+ embedding = ple.DiskBackedShardedEmbedding(
+ tmp_path, SOURCE_PREFIX, num_embeddings=11, dims=160, num_shards=3
+ )
+ try:
+ host = [10, 0, 4, 3, 8, 4]
+ indices = mx.array(host, dtype=mx.int32).reshape(2, 3)
+ expected = _expected(oracles, host, indices.shape, embedding.weight_scale)
+ actual = embedding(indices)
+ mx.eval(actual, expected)
+ assert mx.array_equal(actual, expected).item()
+ assert embedding.rows_read == len(host)
+ assert embedding.last_uploads == 2
+ assert embedding.last_touched_shards == (0, 1, 2)
+ finally:
+ embedding.close()
+
+
+def test_mxfp4_lookup_and_prefetch_only_process_selected_rows(
+ tmp_path, ple, monkeypatch
+):
+ oracles = _checkpoint(tmp_path)
+ reads = []
+ dequantized_shapes = []
+ original_read = ple._SafeTensorMMap.rows_np
+ original_dequantize = mx.dequantize
+
+ def record_read(reader, key, rows):
+ reads.append((key, len(rows)))
+ return original_read(reader, key, rows)
+
+ def record_dequantize(weight, scales, biases=None, **kwargs):
+ assert kwargs["mode"] == "mxfp4"
+ assert biases is None
+ assert weight.dtype == mx.uint32
+ assert scales.dtype == mx.uint8
+ dequantized_shapes.append((weight.shape, scales.shape))
+ return original_dequantize(weight, scales, biases, **kwargs)
+
+ monkeypatch.setattr(ple._SafeTensorMMap, "rows_np", record_read)
+ with ple_load_resources():
+ embedding = ple.DiskBackedShardedEmbedding(tmp_path, SOURCE_PREFIX, 11, 160, 3)
+ try:
+ assert reads == []
+ assert list(embedding.parameters()) == ["weight_scale"]
+ embedding.weight_scale = mx.array([1.75], dtype=mx.bfloat16)
+ host = [10, 3, 4, 3]
+ indices = mx.array(host).reshape(1, 2, 2)
+ expected = _expected(oracles, host, indices.shape, embedding.weight_scale)
+ mx.eval(expected)
+ monkeypatch.setattr(mx, "dequantize", record_dequantize)
+
+ for prefetch in (False, True, False):
+ reads.clear()
+ if prefetch:
+ embedding.prefetch(indices)
+ actual = embedding(indices)
+ mx.eval(actual)
+ assert mx.array_equal(actual, expected).item()
+ assert embedding.last_prefetch_hit is prefetch
+ assert embedding.last_uploads == 2
+ assert sum(count for _, count in reads) == 2 * len(host)
+ assert {key.rsplit(".", 1)[-1] for key, _ in reads} == {
+ "weight",
+ "scales",
+ }
+ assert dequantized_shapes == [((4, 20), (4, 5))] * 3
+ finally:
+ embedding.close()
+
+
+@pytest.mark.parametrize(
+ "modes",
+ [
+ ("mxfp4", "affine", "dense"),
+ ("affine", "mxfp4", "affine"),
+ ("dense", "mxfp4", "dense"),
+ ],
+)
+def test_mixed_shards_match_native_oracles_exactly(tmp_path, ple, modes):
+ oracles = _checkpoint(tmp_path, modes=modes)
+ (tmp_path / "config.json").write_text(
+ json.dumps(
+ {
+ "quantization": {
+ "group_size": 32,
+ "bits": 4,
+ "mode": "mxfp4",
+ f"{RUNTIME_PREFIX}.shards.0": {"group_size": 32, "bits": 4},
+ f"{RUNTIME_PREFIX}.shards.2": False,
+ }
+ }
+ )
+ )
+ with ple_load_resources():
+ embedding = ple.DiskBackedShardedEmbedding(tmp_path, SOURCE_PREFIX, 11, 160, 3)
+ try:
+ embedding.weight_scale = mx.array([0.75], dtype=mx.bfloat16)
+ host = [10, 0, 4, 3, 8, 4]
+ indices = mx.array(host).reshape(2, 3)
+ expected = _expected(oracles, host, indices.shape, embedding.weight_scale)
+ for prefetch in (False, True):
+ if prefetch:
+ embedding.prefetch(indices)
+ actual = embedding(indices)
+ mx.eval(actual, expected)
+ assert mx.array_equal(actual, expected).item()
+ assert not embedding.last_prefetch_hit
+ assert embedding.rows_read == len(host)
+ assert embedding.last_touched_shards == (0, 1, 2)
+ finally:
+ embedding.close()
+
+
+@pytest.mark.parametrize("host", [[], [0], [3, 4], [7, 8], [10, 10]])
+def test_mxfp4_boundaries_and_empty_ids(tmp_path, ple, host):
+ oracles = _checkpoint(tmp_path)
+ with ple_load_resources():
+ embedding = ple.DiskBackedShardedEmbedding(tmp_path, SOURCE_PREFIX, 11, 160, 3)
+ try:
+ indices = mx.array(host, dtype=mx.int32)
+ actual = embedding(indices)
+ expected = _expected(oracles, host, indices.shape, embedding.weight_scale)
+ mx.eval(actual, expected)
+ assert actual.shape == (len(host), 160)
+ assert mx.array_equal(actual, expected).item()
+ finally:
+ embedding.close()
+
+
+@pytest.mark.parametrize("host", [[-1], [11], [0, 12]])
+def test_mxfp4_out_of_range_rejected_before_row_read(tmp_path, ple, monkeypatch, host):
+ _checkpoint(tmp_path)
+ with ple_load_resources():
+ embedding = ple.DiskBackedShardedEmbedding(tmp_path, SOURCE_PREFIX, 11, 160, 3)
+ try:
+
+ def unexpected_read(*args):
+ pytest.fail("out-of-range lookup read checkpoint rows")
+
+ monkeypatch.setattr(ple._SafeTensorMMap, "rows_np", unexpected_read)
+ for call in (embedding, embedding.prefetch):
+ with pytest.raises(IndexError, match="outside the sharded vocabulary"):
+ call(mx.array(host))
+ finally:
+ embedding.close()
+
+
+@pytest.mark.parametrize(
+ "problem,exception,message",
+ [
+ ("missing_scales", ValueError, "both scales and biases are required"),
+ ("float_scales", ValueError, "Incomplete or unsupported"),
+ ("biases", TypeError, "must have float dtypes"),
+ ("weight_dtype", TypeError, "weight must be U32"),
+ ("scale_rows", ValueError, "Unexpected mxfp4 PLE scale shape"),
+ ("scale_rank", ValueError, "Unexpected mxfp4 PLE scale shape"),
+ ("empty_scales", ValueError, "Unexpected mxfp4 PLE scale shape"),
+ ("group_size", ValueError, "Unsupported mxfp4 PLE layout"),
+ ("packed_width", ValueError, "Cannot infer mxfp4 PLE bits"),
+ ("mxfp8", ValueError, "Unsupported mxfp4 PLE layout"),
+ ("nvfp4", ValueError, "Unsupported mxfp4 PLE layout"),
+ ],
+)
+def test_malformed_or_unsupported_packed_shards_fail_explicitly(
+ tmp_path, ple, problem, exception, message
+):
+ _, tensors = _shard(4, 160, 0, "mxfp4")
+ if problem == "missing_scales":
+ del tensors["scales"]
+ tensors["biases"] = mx.ones((4, 5))
+ elif problem == "float_scales":
+ tensors["scales"] = tensors["scales"].astype(mx.float32)
+ elif problem == "biases":
+ tensors["biases"] = mx.zeros((4, 5))
+ elif problem == "weight_dtype":
+ tensors["weight"] = tensors["weight"].astype(mx.float32)
+ elif problem == "scale_rows":
+ tensors["scales"] = tensors["scales"][:3]
+ elif problem == "scale_rank":
+ tensors["scales"] = tensors["scales"].reshape(-1)
+ elif problem == "empty_scales":
+ tensors["scales"] = mx.zeros((4, 0), dtype=mx.uint8)
+ elif problem == "group_size":
+ tensors["scales"] = mx.ones((4, 10), dtype=mx.uint8)
+ elif problem == "packed_width":
+ tensors["weight"] = tensors["weight"][:, :19]
+ elif problem == "mxfp8":
+ _, tensors = _shard(4, 160, 0, problem)
+ elif problem == "nvfp4":
+ weight, scales = mx.quantize(
+ mx.ones((4, 160)), group_size=16, bits=4, mode="nvfp4"
+ )
+ tensors = {"weight": weight, "scales": scales}
+ base = f"{RUNTIME_PREFIX}.shards.0"
+ tensors = {f"{base}.{key}": value for key, value in tensors.items()}
+ mx.save_safetensors(str(tmp_path / "model.safetensors"), tensors)
+ (tmp_path / "model.safetensors.index.json").write_text(
+ json.dumps({"weight_map": dict.fromkeys(tensors, "model.safetensors")})
+ )
+ with pytest.raises(exception, match=message), ple_load_resources():
+ ple.DiskBackedShardedEmbedding(tmp_path, SOURCE_PREFIX, 4, 160, 1)
+
+
+@pytest.mark.parametrize("dtype", [mx.bfloat16, mx.float16, mx.float32, "fp8"])
+def test_dense_storage_keeps_selected_row_behavior(tmp_path, ple, dtype):
+ values = mx.arange(4 * 160).reshape(4, 160) / 97
+ weight = mx.to_fp8(values) if dtype == "fp8" else values.astype(dtype)
+ key = f"{RUNTIME_PREFIX}.shards.0.weight"
+ path = tmp_path / "model.safetensors"
+ mx.save_safetensors(str(path), {key: weight})
+ if dtype == "fp8":
+ raw = path.read_bytes()
+ size = struct.unpack(" MagicMock:
return pool
+class _DefaultModelPool:
+ def __init__(self, entries: dict[str, EngineEntry]):
+ self._entries = entries
+
+ def get_model_ids(self) -> list[str]:
+ return list(self._entries)
+
+ def get_entry(self, model_id: str) -> EngineEntry | None:
+ return self._entries.get(model_id)
+
+
+def _entry(model_id: str, model_type: str) -> EngineEntry:
+ engine_type = "batched" if model_type == "llm" else model_type
+ return EngineEntry(
+ model_id=model_id,
+ model_path=f"/models/{model_id}",
+ model_type=model_type,
+ engine_type=engine_type,
+ estimated_size=1,
+ )
+
+
+class TestDefaultChatModelSelection:
+ def test_missing_default_skips_image_first_model(self):
+ pool = _DefaultModelPool(
+ {
+ "flux-image": _entry("flux-image", "image"),
+ "qwen-chat": _entry("qwen-chat", "vlm"),
+ "embedding": _entry("embedding", "embedding"),
+ }
+ )
+
+ model_id, reason = _select_default_chat_model(pool, "missing-model")
+
+ assert model_id == "qwen-chat"
+ assert reason == "Default model 'missing-model' not found"
+
+ def test_image_default_falls_back_to_chat_model(self):
+ pool = _DefaultModelPool(
+ {
+ "flux-image": _entry("flux-image", "image"),
+ "llama-chat": _entry("llama-chat", "llm"),
+ }
+ )
+
+ model_id, reason = _select_default_chat_model(pool, "flux-image")
+
+ assert model_id == "llama-chat"
+ assert reason == (
+ "Default model 'flux-image' is a image model, not a chat-capable model"
+ )
+
+ def test_no_chat_capable_models_returns_none(self):
+ pool = _DefaultModelPool(
+ {
+ "flux-image": _entry("flux-image", "image"),
+ "embed": _entry("embed", "embedding"),
+ }
+ )
+
+ model_id, reason = _select_default_chat_model(pool, None)
+
+ assert model_id is None
+ assert reason is None
+
+
class TestBoundarySnapshotLifecycle:
def test_reset_helper_uses_engine_pool_cache_dir(self, tmp_path):
from types import SimpleNamespace
@@ -765,6 +832,45 @@ def test_api_validation_error_openai_format(self, client):
assert "type" in data["error"]
assert "param" in data["error"]
+ @pytest.mark.parametrize("suffix", ["models", "messages", "messages/count_tokens"])
+ def test_claude_gateway_context_error_matches_standard(
+ self, client, monkeypatch, suffix
+ ):
+ error = srv._ContextLengthExceededError(
+ status_code=400,
+ detail="prompt is too long: 100 tokens > 64",
+ )
+ monkeypatch.setattr(srv, "_list_models", AsyncMock(side_effect=error))
+ monkeypatch.setattr(srv, "get_engine_for_model", AsyncMock(side_effect=error))
+ responses = []
+ for prefix in ("", "/claude"):
+ path = f"{prefix}/v1/{suffix}"
+ responses.append(
+ client.get(path)
+ if suffix == "models"
+ else client.post(
+ path,
+ json={
+ "model": "test-model",
+ "max_tokens": 16,
+ "messages": [{"role": "user", "content": "Hello"}],
+ },
+ )
+ )
+
+ assert [response.status_code for response in responses] == [400, 400]
+ assert responses[0].json()["error"]["code"] == "context_length_exceeded"
+ assert responses[1].json() == responses[0].json()
+
+ @pytest.mark.parametrize("suffix", ["messages", "messages/count_tokens"])
+ def test_claude_gateway_validation_error_matches_standard(self, client, suffix):
+ standard = client.post(f"/v1/{suffix}", json={})
+ gateway = client.post(f"/claude/v1/{suffix}", json={})
+
+ assert standard.status_code == gateway.status_code == 422
+ assert "error" in standard.json()
+ assert gateway.json() == standard.json()
+
def test_non_api_route_detail_format(self, client):
"""Test that non-/v1/ routes keep the traditional detail format."""
response = client.get("/nonexistent-page")
@@ -1166,6 +1272,11 @@ def resolve_model_id(self, model_id, settings_manager=None):
def get_entry(self, model_id):
return None
+ def get_active_model_aliases(self, settings_manager):
+ settings = settings_manager.get_settings("qwen-base")
+ alias = settings.model_alias.strip() if settings.model_alias else ""
+ return {"qwen-base": alias} if alias else {}
+
@staticmethod
def _save_exposed_profile(manager, settings):
return manager.save_profile(
@@ -1241,6 +1352,9 @@ async def test_v1_models_status_includes_exposed_profile_capabilities(
assert profile_model["config_model_type"] == "gemma4"
assert profile_model["max_context_window"] == 4096
assert profile_model["max_tokens"] == 1024
+ assert profile_model["enable_thinking"] is True
+ base_model = next(m for m in status["models"] if m["id"] == "qwen-base")
+ assert base_model["enable_thinking"] is None
@pytest.mark.asyncio
async def test_v1_models_status_lists_chat_ui_reasoning_levels(self, manager):
@@ -1409,6 +1523,9 @@ class _FakePool:
def __init__(self, model_ids):
self._model_ids = model_ids
+ def get_active_model_aliases(self, settings_manager):
+ return {}
+
def get_status(self):
return {
"models": [
@@ -1784,7 +1901,8 @@ async def stream_chat(**kwargs):
@pytest.mark.parametrize("subclass", [False, True])
-def test_prepare_chat_prompt_for_request_keeps_other_engine_count_path(subclass):
+@pytest.mark.asyncio
+async def test_prepare_chat_prompt_for_request_keeps_other_engine_count_path(subclass):
class OtherBatchedEngine(BatchedEngine):
pass
@@ -1792,7 +1910,7 @@ class OtherBatchedEngine(BatchedEngine):
engine.count_chat_tokens = MagicMock(return_value=7)
messages = [{"role": "user", "content": "Hello"}]
- assert srv._prepare_chat_prompt_for_request(
+ assert await srv._prepare_chat_prompt_for_request(
engine,
messages,
chat_template_kwargs={"enable_thinking": False},
@@ -1805,7 +1923,8 @@ class OtherBatchedEngine(BatchedEngine):
@pytest.mark.parametrize("stream", [False, True])
@pytest.mark.parametrize(
- "path", ["/v1/chat/completions", "/v1/messages", "/v1/responses"]
+ "path",
+ ["/v1/chat/completions", "/v1/messages", "/claude/v1/messages", "/v1/responses"],
)
def test_chat_routes_reuse_final_prepared_prompt(
monkeypatch, prepared_chat_engine, path, stream
@@ -1824,6 +1943,8 @@ def render(messages, tools=None, **kwargs):
new_text=" Done.",
prompt_tokens=3,
completion_tokens=1,
+ finished=True,
+ finish_reason="stop",
)
engine.chat = AsyncMock(return_value=output)
streamed_kwargs = []
@@ -1851,7 +1972,12 @@ async def stream_chat(**kwargs):
monkeypatch.setitem(
srv.app.dependency_overrides, srv.verify_inference_api_key, lambda: True
)
- body = {"model": "test-model", "stream": stream}
+ body = {
+ "model": (
+ "omlx-claude/test-model" if path == "/claude/v1/messages" else "test-model"
+ ),
+ "stream": stream,
+ }
if path == "/v1/responses":
body.update(input="Hello", store=False)
else:
@@ -1871,7 +1997,8 @@ async def stream_chat(**kwargs):
assert generated["_prepared_prompt"] is prepared
assert generated["_request_id"] == response.headers["x-omlx-request-id"]
assert generated["chat_template_kwargs"]["preserve_thinking"] is True
- if path == "/v1/messages" and stream:
+ assert srv.get_engine_for_model.call_args.args == ("test-model",)
+ if path.endswith("/v1/messages") and stream:
events = [
json.loads(line.removeprefix("data: "))
for line in response.text.splitlines()
@@ -1879,28 +2006,129 @@ async def stream_chat(**kwargs):
]
start = next(event for event in events if event["type"] == "message_start")
assert start["message"]["usage"]["input_tokens"] == len(prepared[1])
+ delta = next(event for event in events if event["type"] == "message_delta")
+ assert delta["delta"]["stop_reason"] == "end_turn"
+ assert events[-1]["type"] == "message_stop"
+
+
+@pytest.mark.parametrize(
+ "model_id", ["owner/chat:fast", "omlx-claude/chat:fast", "Claude-local:fast"]
+)
+@pytest.mark.parametrize("count_tokens", [False, True])
+def test_claude_gateway_preserves_profile_settings(
+ monkeypatch, tmp_path, prepared_chat_engine, model_id, count_tokens
+):
+ source_id, profile_name = model_id.rsplit(":", 1)
+ manager = ModelSettingsManager(base_path=tmp_path)
+ manager.set_settings(source_id, ModelSettings(max_context_window=65536))
+ manager.save_profile(
+ source_id,
+ profile_name,
+ "Fast",
+ None,
+ {"temperature": 0.3, "chat_template_kwargs": {"enable_thinking": False}},
+ expose_as_model=True,
+ )
+ engine = prepared_chat_engine
+ engine.chat = AsyncMock(
+ return_value=GenerationOutput(
+ text="Done.",
+ prompt_tokens=3,
+ completion_tokens=1,
+ finished=True,
+ finish_reason="stop",
+ )
+ )
+ engine.preflight_chat = AsyncMock()
+ pool = MagicMock()
+ pool.get_entry.return_value = None
+ pool.get_active_model_aliases.return_value = {}
+ pool.get_status.return_value = {"models": [{"id": source_id, "model_type": "llm"}]}
+ pool.resolve_model_id.side_effect = (
+ lambda name, settings_manager: settings_manager.get_exposed_profile_source_model_id(
+ name
+ )
+ or name
+ )
+ state = ServerState()
+ state.engine_pool = pool
+ state.settings_manager = manager
+ monkeypatch.setattr(srv, "_server_state", state)
+ acquire = AsyncMock(return_value=engine)
+ monkeypatch.setattr(srv, "get_engine_for_model", acquire)
+ monkeypatch.setitem(
+ srv.app.dependency_overrides, srv.verify_inference_api_key, lambda: True
+ )
+ path = "/claude/v1/messages"
+ if count_tokens:
+ path += "/count_tokens"
+ client = TestClient(app)
+ discovery = client.get("/claude/v1/models?limit=1000")
+ assert discovery.status_code == 200
+ discovered_id = next(
+ entry["id"]
+ for entry in discovery.json()["data"]
+ if entry["display_name"] == model_id
+ )
+ assert discovered_id == f"omlx-claude/{model_id}"
+ response = client.post(
+ path,
+ json={
+ "model": discovered_id,
+ "max_tokens": 16,
+ "messages": [{"role": "user", "content": "Hello"}],
+ },
+ )
-def test_prepare_chat_prompt_for_request_prepares_vlm_prompt():
- engine = VLMBatchedEngine.__new__(VLMBatchedEngine)
+ assert response.status_code == 200, response.text
+ assert acquire.call_args.args == (model_id,)
+ template_kwargs = engine._apply_chat_template.call_args.kwargs[
+ "chat_template_kwargs"
+ ]
+ assert template_kwargs["enable_thinking"] is False
+ if count_tokens:
+ assert response.json() == {"input_tokens": 3}
+ engine.chat.assert_not_called()
+ else:
+ assert engine.chat.call_args.kwargs["temperature"] == 0.3
+ assert response.json()["content"][0]["type"] == "text"
+ assert response.json()["content"][0]["text"] == "Done."
+ assert response.json()["usage"]["input_tokens"] == 3
+ assert response.json()["usage"]["output_tokens"] == 1
+ assert response.json()["stop_reason"] == "end_turn"
+
+
+@pytest.mark.asyncio
+async def test_prepare_chat_prompt_for_request_prepares_vlm_prompt():
+ engine = VLMBatchedEngine(model_name="test-model")
engine.prepare_chat_prompt = MagicMock(return_value=("prompt", [1, 2]))
messages = [{"role": "user", "content": "Hello"}]
- assert srv._prepare_chat_prompt_for_request(engine, messages) == (
+ assert await srv._prepare_chat_prompt_for_request(engine, messages) == (
2,
("prompt", [1, 2]),
)
@pytest.mark.asyncio
-async def test_text_engine_prepares_prompt_off_the_event_loop():
- engine = BatchedEngine(model_name="test-model")
-
- prepare_thread = await srv._prepare_prompt_off_loop(
- engine, lambda engine: threading.get_ident()
+@pytest.mark.parametrize("engine_type", [BatchedEngine, VLMBatchedEngine])
+async def test_batched_engine_prepares_request_prompt_off_the_event_loop(engine_type):
+ engine = engine_type(model_name="test-model")
+ prepare_threads = []
+
+ def prepare(*args):
+ prepare_threads.append(threading.get_ident())
+ return "prompt", [1, 2]
+
+ engine.prepare_chat_prompt = prepare
+ result = await srv._prepare_chat_prompt_for_request(
+ engine, [{"role": "user", "content": "Hello"}]
)
- assert prepare_thread != threading.get_ident()
+ assert result == (2, ("prompt", [1, 2]))
+ assert len(prepare_threads) == 1
+ assert prepare_threads[0] != threading.get_ident()
@pytest.fixture
@@ -2072,3 +2300,111 @@ async def streamed(**kwargs):
else:
generated = (engine.chat if chat else engine.generate).call_args.kwargs
assert generated.get("ignore_eos", False) is bool(ignore_eos)
+
+
+@pytest.mark.parametrize("stream", [False, True])
+def test_responses_tool_result_round_trip_renders_native_arguments(monkeypatch, stream):
+ """The next Codex turn must reach generation, not retry a template HTTP 500."""
+ from jinja2 import Environment
+
+ from omlx.engine.base import GenerationOutput
+
+ template = Environment().from_string(
+ "{% for message in messages %}{{ message.role }}:{{ message.content or '' }}"
+ "{% for call in message.tool_calls or [] %}"
+ "{% for key, value in call.function.arguments|items %}{{ key }}={{ value }};"
+ "{% endfor %}{% endfor %}{% endfor %}"
+ )
+
+ class NativeToolTokenizer:
+ chat_template = "tool_calls"
+
+ def apply_chat_template(self, messages, **kwargs):
+ return template.render(messages=messages)
+
+ def encode(self, text, **kwargs):
+ return [1] * len(text.split())
+
+ engine = MagicMock()
+ engine.tokenizer = NativeToolTokenizer()
+ engine.model_type = "qwen3_5"
+ engine.is_diffusion_model = False
+ engine.supports_multimodal_fallback = False
+ engine.supports_request_scoped_abort = False
+ engine.preflight_chat = AsyncMock()
+ captured_prompts = []
+
+ def count_chat_tokens(messages, *args, **kwargs):
+ rendered = engine.tokenizer.apply_chat_template(messages)
+ captured_prompts.append(rendered)
+ return 16
+
+ engine.count_chat_tokens.side_effect = count_chat_tokens
+ output = GenerationOutput(
+ text="All done.", new_text="All done.", prompt_tokens=16, completion_tokens=2
+ )
+ engine.chat = AsyncMock(return_value=output)
+
+ async def stream_chat(**kwargs):
+ yield output
+
+ engine.stream_chat = stream_chat
+ pool = MagicMock()
+ pool.get_entry.return_value = SimpleNamespace(
+ config_model_type="qwen3_5", preserve_thinking_default=False
+ )
+ monkeypatch.setattr(
+ srv,
+ "_server_state",
+ ServerState(engine_pool=pool, global_settings=GlobalSettings()),
+ )
+ monkeypatch.setattr(srv, "get_engine_for_model", AsyncMock(return_value=engine))
+ monkeypatch.setattr(srv, "resolve_model_id", lambda name: name)
+ monkeypatch.setattr(srv, "validate_context_window", lambda *args, **kwargs: None)
+ monkeypatch.setattr(
+ srv, "get_model_settings_for_request", lambda name: ModelSettings()
+ )
+ monkeypatch.setitem(
+ srv.app.dependency_overrides, srv.verify_inference_api_key, lambda: True
+ )
+ response = TestClient(srv.app).post(
+ "/v1/responses",
+ json={
+ "model": "test-model",
+ "stream": stream,
+ "store": False,
+ "input": [
+ {"role": "user", "content": "Inspect the workspace."},
+ {
+ "type": "function_call",
+ "call_id": "call_shell",
+ "name": "exec_command",
+ "arguments": '{"cmd":"pwd"}',
+ },
+ {
+ "type": "function_call_output",
+ "call_id": "call_shell",
+ "output": "/tmp",
+ },
+ ],
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert captured_prompts and "cmd=pwd;" in captured_prompts[0]
+ if stream:
+ events = [
+ json.loads(line[6:])
+ for line in response.text.splitlines()
+ if line.startswith("data: {")
+ ]
+ assert events[-1]["type"] == "response.completed"
+ final = events[-1]["response"]
+ sequence = [event["sequence_number"] for event in events]
+ assert sequence == sorted(set(sequence))
+ else:
+ final = response.json()
+ assert final["status"] == "completed"
+ assert final["output"][0]["content"][0]["text"] == "All done."
+ assert final["usage"]["input_tokens"] == 16
+ assert final["usage"]["output_tokens"] == 2
+ assert final["usage"]["total_tokens"] == 18
diff --git a/tests/test_server_main.py b/tests/test_server_main.py
index b116ab0d99..eb41ca06e6 100644
--- a/tests/test_server_main.py
+++ b/tests/test_server_main.py
@@ -38,6 +38,7 @@ def module_entry(monkeypatch, tmp_path):
# HOME alone is not enough when a macOS app bootstrap file exists.
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.setenv("OMLX_BASE_PATH", str(tmp_path / "omlx-base"))
+ monkeypatch.delenv("OMLX_API_KEY", raising=False)
reset_settings()
# Reset the middleware stack so init_server's add_middleware works
@@ -203,6 +204,7 @@ def test_module_entry_api_key_setup_end_to_end(tmp_path):
model_dir = tmp_path / "models"
model_dir.mkdir()
env = os.environ.copy()
+ env.pop("OMLX_API_KEY", None)
env["HOME"] = str(tmp_path)
env["OMLX_BASE_PATH"] = str(tmp_path / "base")
diff --git a/tests/test_settings.py b/tests/test_settings.py
index 0116e0a98a..bf6ca43949 100644
--- a/tests/test_settings.py
+++ b/tests/test_settings.py
@@ -1300,8 +1300,9 @@ def test_cli_memory_guard_absent_leaves_saved_state(self, tmp_path):
assert settings.memory.prefill_memory_guard is False
- def test_load_from_file(self):
+ def test_load_from_file(self, monkeypatch):
"""Test loading settings from JSON file."""
+ monkeypatch.delenv("OMLX_API_KEY", raising=False)
with tempfile.TemporaryDirectory() as tmpdir:
# Create settings file
settings_file = Path(tmpdir) / "settings.json"
@@ -1319,8 +1320,9 @@ def test_load_from_file(self):
assert settings.server.port == 9000
assert settings.auth.api_key == "test-key"
- def test_load_from_file_all_sections(self):
+ def test_load_from_file_all_sections(self, monkeypatch):
"""Test loading all settings sections from file."""
+ monkeypatch.delenv("OMLX_API_KEY", raising=False)
with tempfile.TemporaryDirectory() as tmpdir:
settings_file = Path(tmpdir) / "settings.json"
settings_file.write_text(
@@ -2169,8 +2171,10 @@ def test_cli_override_no_cache(self):
assert settings.cache.enabled is False
assert settings.cache.ssd_cache_dir == "/cli/cache"
- def test_save_cli_overrides_preserves_runtime_secrets_and_env(self):
+ def test_save_cli_overrides_preserves_runtime_secrets_and_env(self, monkeypatch):
"""Saving a CLI setting must not serialize transient overrides."""
+ monkeypatch.delenv("OMLX_API_KEY", raising=False)
+ monkeypatch.delenv("OMLX_CACHE_ENABLED", raising=False)
with tempfile.TemporaryDirectory() as tmpdir:
base_path = Path(tmpdir)
stored = GlobalSettings(base_path=base_path)
@@ -2584,8 +2588,9 @@ def test_cli_args_without_expected_attrs(self):
# Other settings should be defaults
assert settings.server.host == "127.0.0.1"
- def test_save_with_unicode_api_key(self):
+ def test_save_with_unicode_api_key(self, monkeypatch):
"""Test saving settings with unicode in values."""
+ monkeypatch.delenv("OMLX_API_KEY", raising=False)
with tempfile.TemporaryDirectory() as tmpdir:
settings = GlobalSettings(base_path=Path(tmpdir))
settings.auth.api_key = "key-with-unicode-\u4e2d\u6587"
diff --git a/tests/test_specprefill.py b/tests/test_specprefill.py
index a3986abc1a..482b29430d 100644
--- a/tests/test_specprefill.py
+++ b/tests/test_specprefill.py
@@ -38,6 +38,14 @@ def test_keep_100_percent(self):
selected = select_chunks(importance, keep_pct=1.0, chunk_size=32)
assert selected.shape[0] == 64
+ def test_empty_importance_returns_empty_indices(self):
+ from omlx.patches.specprefill import select_chunks
+
+ selected = select_chunks(mx.array([]))
+
+ assert selected.shape == (0,)
+ assert selected.dtype == mx.int32
+
def test_sorted_output(self):
from omlx.patches.specprefill import select_chunks
diff --git a/tests/test_specprefill_planning.py b/tests/test_specprefill_planning.py
index 9e635578c5..132274b70a 100644
--- a/tests/test_specprefill_planning.py
+++ b/tests/test_specprefill_planning.py
@@ -15,11 +15,23 @@ def _all_tokens(system_token_count: int, conversation_token_count: int) -> list[
@pytest.mark.parametrize(
- ("selected_indices", "expected_remove", "expected_sparse_count"),
- [([0, 2, 7], True, 2), ([0, 2], False, 2), ([7, 1, 7, 4], True, 3)],
+ (
+ "selected_indices",
+ "expected_remove",
+ "expected_sparse_count",
+ "expected_sparse_indices",
+ ),
+ [
+ ([0, 2, 7], True, 2, [0, 2]),
+ ([0, 2], False, 2, [0, 2]),
+ ([7, 1, 7, 4], True, 3, [1, 4, 7]),
+ ],
)
def test_kickoff_selection_changes_tracker_count_once(
- selected_indices: list[int], expected_remove: bool, expected_sparse_count: int
+ selected_indices: list[int],
+ expected_remove: bool,
+ expected_sparse_count: int,
+ expected_sparse_indices: list[int],
):
plan = plan_specprefill_target(
all_tokens=_all_tokens(system_token_count=3, conversation_token_count=8),
@@ -30,6 +42,7 @@ def test_kickoff_selection_changes_tracker_count_once(
assert plan.remove_kickoff_index is expected_remove
assert plan.sparse_selected_token_count == expected_sparse_count
+ assert list(plan.sparse_selected_indices) == expected_sparse_indices
assert plan.total_tracker_prefill_count == 3 + expected_sparse_count
diff --git a/tests/test_specprefill_target.py b/tests/test_specprefill_target.py
index 952c41132b..83b78bf08a 100644
--- a/tests/test_specprefill_target.py
+++ b/tests/test_specprefill_target.py
@@ -137,6 +137,7 @@ def _run(
abort_error: _AbortError | None = None,
abort_at: int | None = None,
sparse_abort_error: _AbortError | None = None,
+ eval_cache_states: Any | None = None,
exact_prefix_cache: _TieredExactPrefixCache | None = None,
static_prefix_tokens: list[int] | None = None,
promote_static_prefix_to_hot_cache: bool = True,
@@ -255,6 +256,7 @@ def use_stream(selected_stream: Any):
report_sparse_progress=report_sparse_progress,
sync_and_clear_cache=lambda: trace["syncs"].append(stream),
log=logger,
+ eval_cache_states=eval_cache_states,
extract_cache_states=extract_cache_states,
exact_prefix_cache=exact_prefix_cache,
static_prefix_tokens=static_prefix_tokens,
@@ -298,6 +300,19 @@ def test_system_prefill_chunks_reports_checks_abort_and_uses_stream():
assert trace["syncs"] == [trace["stream"]] * 3
+def test_system_prefill_uses_supplied_cache_evaluator():
+ evaluations: list[Any] = []
+ _, _, trace = _run(
+ system_token_count=5,
+ conversation_token_count=8,
+ selected_indices=[0, 2, 6],
+ eval_cache_states=evaluations.append,
+ )
+
+ assert evaluations == [trace["prompt_cache"]] * 2
+ assert trace["evaluations"] == []
+
+
@pytest.mark.parametrize(
("selected_indices", "expected_selected", "keeps_original"),
[
diff --git a/tests/test_systemone.py b/tests/test_systemone.py
index 9ea34de526..66741e254e 100644
--- a/tests/test_systemone.py
+++ b/tests/test_systemone.py
@@ -693,6 +693,51 @@ def tiny_d3(tiny_backbone):
return model
+@pytest.mark.parametrize(
+ ("name", "rows", "error"),
+ [
+ ("weight", d3.MAX_OPTIONS, None),
+ ("other", d3.MAX_OPTIONS, "missing its weight tensor"),
+ ("weight", 1, "readout weight has shape"),
+ ],
+)
+def test_d3_load_validates_readout(tiny_d3, tmp_path, monkeypatch, name, rows, error):
+ token_ids = list(range(len(tiny_d3.codes)))
+ config = {
+ "format_id": d3.D3_FORMAT_ID,
+ "format_version": 1,
+ "codes": tiny_d3.codes,
+ "token_ids": token_ids,
+ }
+ (tmp_path / d3.D3_DECISION_CONFIG).write_text(json.dumps(config))
+ mx.save_safetensors(
+ str(tmp_path / d3.D3_READOUT_WEIGHTS), {name: mx.ones((rows, 64))}
+ )
+ tiny_d3.model_path = str(tmp_path)
+ tiny_d3.readout = None
+ monkeypatch.setattr(tiny_d3.backbone, "load", lambda: None)
+ monkeypatch.setattr(
+ d3, "answer_codes", lambda tokenizer: (tiny_d3.codes, token_ids)
+ )
+ monkeypatch.setattr(d3, "apply_sdpa256_attention_patch", lambda: True)
+
+ if error:
+ with pytest.raises(ValueError, match=error):
+ tiny_d3.load()
+ assert tiny_d3.readout is None
+ else:
+ tiny_d3.load()
+ assert tiny_d3.readout.shape == (d3.MAX_OPTIONS, 64)
+ assert tiny_d3.readout.dtype == mx.float32
+
+
+def test_d3_run_requires_loaded_readout():
+ model = d3.D3Model("unused")
+ plan = d3.D3Plan({}, [], [], [])
+ with pytest.raises(RuntimeError, match="model is not loaded"):
+ next(model.run(plan, lambda: 16))
+
+
def test_d3_encode_matches_full_forward_without_causal_mask(tiny_d3, monkeypatch):
from mlx_vlm.models.qwen3_5 import language
diff --git a/tests/test_v1_models_visibility.py b/tests/test_v1_models_visibility.py
index 3f4533674a..ccb0c58fb9 100644
--- a/tests/test_v1_models_visibility.py
+++ b/tests/test_v1_models_visibility.py
@@ -5,6 +5,7 @@
from unittest.mock import patch
+import pytest
from fastapi.testclient import TestClient
from omlx.integrations.base import IntegrationContext
@@ -23,6 +24,14 @@ def __init__(self, models: list[dict]):
def resolve_model_id(self, model_id_or_alias: str, settings_manager) -> str:
return model_id_or_alias
+ def get_active_model_aliases(self, settings_manager) -> dict[str, str]:
+ aliases: dict[str, str] = {}
+ model_ids = {model["id"] for model in self._models}
+ for model_id, settings in settings_manager.get_all_settings().items():
+ if model_id in model_ids and settings.model_alias:
+ aliases[model_id] = settings.model_alias
+ return aliases
+
def get_status(self) -> dict:
return {
"final_ceiling": 0,
@@ -38,6 +47,7 @@ def _model(model_id: str, config_model_type: str = "llama", **extra) -> dict:
"id": model_id,
"model_path": f"/models/{model_id}",
"config_model_type": config_model_type,
+ "model_type": "llm",
"source_repo_id": None,
**extra,
}
@@ -53,13 +63,13 @@ def _state(models: list[dict], tmp_path, *, hide_helpers: bool = False) -> Serve
return state
-def _list_ids(state) -> list[str]:
+def _list_ids(state, path="/v1/models") -> list[str]:
with (
patch("omlx.server._server_state", state),
patch("omlx.server.get_max_context_window", return_value=None),
):
client = TestClient(app, raise_server_exceptions=False)
- response = client.get("/v1/models")
+ response = client.get(path)
assert response.status_code == 200
return [m["id"] for m in response.json()["data"]]
@@ -118,6 +128,115 @@ def test_public_model_types_support_copilot_discovery(tmp_path):
)
+def test_claude_gateway_discovery_filters_and_preserves_standard_catalog(tmp_path):
+ state = _state(
+ [
+ _model("owner/chat"),
+ _model("small"),
+ _model("hidden"),
+ _model("embed", model_type="embedding"),
+ _model("image", model_type="image"),
+ _model("draft", is_helper=True),
+ _model("unavailable", unavailable_reason="Cannot load model"),
+ ],
+ tmp_path,
+ )
+ state.settings_manager.set_settings(
+ "owner/chat", ModelSettings(model_alias="my-chat", is_favorite=True)
+ )
+ state.settings_manager.set_settings("hidden", ModelSettings(is_hidden=True))
+ state.settings_manager.save_profile(
+ "owner/chat", "fast", "Fast", None, {}, expose_as_model=True
+ )
+ state.settings_manager.save_profile(
+ "embed", "fast", "Fast", None, {}, expose_as_model=True
+ )
+ with (
+ patch("omlx.server._server_state", state),
+ patch(
+ "omlx.server.get_max_context_window",
+ side_effect=lambda name: 32768 if name == "small" else 65536,
+ ),
+ ):
+ client = TestClient(app)
+ standard_before = client.get("/v1/models").json()
+ response = client.get("/claude/v1/models?limit=1000")
+ standard_after = client.get("/v1/models").json()
+
+ assert response.status_code == 200
+ assert response.history == []
+ assert response.json()["data"] == [
+ {
+ "id": "omlx-claude/my-chat",
+ "display_name": "my-chat",
+ "max_model_len": 65536,
+ },
+ {
+ "id": "omlx-claude/my-chat:fast",
+ "display_name": "my-chat:fast",
+ "max_model_len": 65536,
+ },
+ ]
+ assert [m["id"] for m in standard_before["data"]] == [
+ "my-chat",
+ "small",
+ "embed",
+ "image",
+ "draft",
+ "my-chat:fast",
+ "embed:fast",
+ ]
+ assert [m["id"] for m in standard_after["data"]] == [
+ m["id"] for m in standard_before["data"]
+ ]
+ assert all("display_name" not in m for m in standard_after["data"])
+
+
+@pytest.mark.parametrize("context_window", [None, 49152, 65536])
+def test_claude_gateway_discovers_nested_and_already_prefixed_ids(
+ tmp_path, context_window
+):
+ state = _state(
+ [_model("owner/chat"), _model("omlx-claude/chat"), _model("Claude-local")],
+ tmp_path,
+ )
+ with (
+ patch("omlx.server._server_state", state),
+ patch("omlx.server.get_max_context_window", return_value=context_window),
+ ):
+ response = TestClient(app).get("/claude/v1/models?limit=1000")
+
+ assert response.status_code == 200
+ assert [m["id"] for m in response.json()["data"]] == [
+ "omlx-claude/owner/chat",
+ "omlx-claude/omlx-claude/chat",
+ "omlx-claude/Claude-local",
+ ]
+
+
+@pytest.mark.parametrize(
+ "headers",
+ [{}, {"Authorization": "Bearer test-key"}, {"x-api-key": "test-key"}],
+)
+@pytest.mark.parametrize(
+ "path",
+ ["/claude/v1/models", "/claude/v1/messages", "/claude/v1/messages/count_tokens"],
+)
+def test_claude_gateway_uses_inference_auth(tmp_path, headers, path):
+ state = _state([], tmp_path)
+ state.api_key = "test-key"
+ with patch("omlx.server._server_state", state):
+ client = TestClient(app)
+ response = (
+ client.get(path, headers=headers)
+ if path.endswith("/models")
+ else client.post(path, headers=headers, json={})
+ )
+
+ expected_status = 200 if path.endswith("/models") else 422
+ assert response.status_code == (expected_status if headers else 401)
+
+
def test_per_model_hidden_excluded(tmp_path):
state = _state([_model("chat-a"), _model("chat-b")], tmp_path)
state.settings_manager.set_settings("chat-b", ModelSettings(is_hidden=True))
@@ -126,7 +245,8 @@ def test_per_model_hidden_excluded(tmp_path):
assert "chat-b" not in ids
-def test_hidden_source_profile_excluded(tmp_path):
+@pytest.mark.parametrize("path", ["/v1/models", "/claude/v1/models"])
+def test_hidden_source_profile_excluded(tmp_path, path):
state = _state([_model("chat-a")], tmp_path)
state.settings_manager.set_settings("chat-a", ModelSettings(is_hidden=True))
state.settings_manager.save_profile(
@@ -137,7 +257,40 @@ def test_hidden_source_profile_excluded(tmp_path):
{"temperature": 0.1},
expose_as_model=True,
)
- assert _list_ids(state) == []
+ assert _list_ids(state, path) == []
+
+
+def test_claude_gateway_hidden_tier_source_excluded(tmp_path):
+ state = _state([_model("hidden")], tmp_path)
+ state.settings_manager.set_settings("hidden", ModelSettings(is_hidden=True))
+ state.global_settings.claude_code.desktop_enabled = True
+ state.global_settings.claude_code.opus_model = "hidden"
+
+ assert _list_ids(state, "/claude/v1/models") == []
+
+
+def test_unavailable_model_and_profiles_are_excluded(tmp_path):
+ state = _state(
+ [
+ _model("chat-a"),
+ _model(
+ "qwen-next",
+ config_model_type="qwen4_exp",
+ unavailable_reason="QSA continuous batching is unavailable",
+ ),
+ ],
+ tmp_path,
+ )
+ state.settings_manager.save_profile(
+ "qwen-next",
+ "fast",
+ "Fast",
+ None,
+ {"temperature": 0.1},
+ expose_as_model=True,
+ )
+
+ assert _list_ids(state) == ["chat-a"]
def test_hidden_ignored_when_helper_toggle_off(tmp_path):
From af6472a0e14630669ee7310c08bfc98064ffd9f3 Mon Sep 17 00:00:00 2001
From: Mike Wallio
Date: Thu, 5 Nov 2026 14:56:40 -0500
Subject: [PATCH 09/24] feat(chat): add image generation and editing tools
Replace the separate Imagine page with model-aware chat image tools, uploaded and generated image references, translated controls, and production JavaScript regression coverage.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
---
README.md | 22 +-
apps/omlx-web/omlx_web/i18n/cs.json | 58 +-
apps/omlx-web/omlx_web/i18n/de.json | 58 +-
apps/omlx-web/omlx_web/i18n/en.json | 60 +-
apps/omlx-web/omlx_web/i18n/es.json | 58 +-
apps/omlx-web/omlx_web/i18n/fr.json | 60 +-
apps/omlx-web/omlx_web/i18n/ja.json | 58 +-
apps/omlx-web/omlx_web/i18n/ko.json | 58 +-
apps/omlx-web/omlx_web/i18n/pt-BR.json | 58 +-
apps/omlx-web/omlx_web/i18n/ru.json | 58 +-
apps/omlx-web/omlx_web/i18n/zh-TW.json | 58 +-
apps/omlx-web/omlx_web/i18n/zh.json | 58 +-
apps/omlx-web/omlx_web/routes.py | 7 +-
.../omlx_web/static/js/chat-image-tools.js | 267 +++++
apps/omlx-web/omlx_web/templates/chat.html | 218 ++--
.../omlx_web/templates/dashboard/_navbar.html | 12 -
apps/omlx-web/omlx_web/templates/imagine.html | 974 ------------------
apps/omlx-web/tests/chat_image_tools.test.cjs | 700 +++++++++++++
apps/omlx-web/tests/test_chat_image_tools.py | 37 +
apps/omlx-web/tests/test_web_ui_contract.py | 9 +-
omlx/engine_pool.py | 4 +
tests/test_admin_imagine.py | 349 -------
tests/test_engine_pool.py | 22 +
23 files changed, 1222 insertions(+), 2041 deletions(-)
create mode 100644 apps/omlx-web/omlx_web/static/js/chat-image-tools.js
delete mode 100644 apps/omlx-web/omlx_web/templates/imagine.html
create mode 100644 apps/omlx-web/tests/chat_image_tools.test.cjs
create mode 100644 apps/omlx-web/tests/test_chat_image_tools.py
delete mode 100644 tests/test_admin_imagine.py
diff --git a/README.md b/README.md
index 10762cb902..f9d1e6430f 100644
--- a/README.md
+++ b/README.md
@@ -666,6 +666,24 @@ or performance; those require separate model-specific validation.
### Image model discovery and manifests
+Chat at `/admin/chat` includes image tools without a separate image tab.
+Ask which image models are available, request an image, or upload an image
+and ask for an edit. Text-only chat models can use these tools without
+receiving image bytes. Vision models retain their normal image inputs.
+Chat omits image tools when the request model reports no tool-calling support.
+Chat refreshes unavailable tool support before each new prompt, so loaded
+diffusion models can enable image tools without reopening the tab.
+Generated images appear inline with download and reuse controls. Reuse
+inserts an explicit image reference into the composer for a later edit.
+Branching a conversation updates references to copied images for the new chat.
+These references are identifiers, not URLs; references in assistant Markdown
+render as text, while the tool result contains the image preview.
+Images remain in the open conversation only. Saved and exported histories
+strip image bytes, so their references cannot be edited after reload.
+Image inference has a ten-minute browser deadline. Stop prevents later
+tool results and follow-up chat requests, but does not guarantee immediate
+GPU preemption.
+
Image generation and editing use the core mlx-vlm dependency. oMLX asks
mlx-vlm whether each local diffusion checkpoint supports generation, editing,
or both. Checkpoint metadata can identify models in renamed directories.
@@ -730,13 +748,13 @@ does not replace a saved checkpoint grid. Base checkpoints without saved
grids keep 30 generation steps or 40 editing steps. Finite positive guidance
overrides remain supported.
-Custom sigma grids are an API extension, not an Imagine editor. Supply a
+Custom sigma grids are an API extension, not a chat tool option. Supply a
nonempty, finite, strictly descending JSON array in `(0, 1]`, without terminal
zero; the scheduler applies the checkpoint's shift settings and appends the
terminal zero. For multipart edits, encode the `sigmas` form field as a JSON
array, for example `[1, 0.8, 0.4]`. Each response image includes the backend's
effective `steps` and `guidance` when available, plus its actual output size.
-Imagine explains saved-grid precedence and displays the actual result steps.
+Chat tool results include the actual result steps when the backend returns them.
Qwen 2.1 editing conditions on all supplied reference images; the existing
API/UI upload limits still apply. With automatic size, the backend selects
diff --git a/apps/omlx-web/omlx_web/i18n/cs.json b/apps/omlx-web/omlx_web/i18n/cs.json
index b303ee7ad0..693656c18d 100644
--- a/apps/omlx-web/omlx_web/i18n/cs.json
+++ b/apps/omlx-web/omlx_web/i18n/cs.json
@@ -2475,66 +2475,12 @@
"modal.model_settings.minicpm_downsample_mode_hint": "16x používá méně vizuálních tokenů; 4x zachovává více detailů. Výchozí volba používá procesor modelu.",
"modal.model_settings.minicpm_max_slice_nums": "Maximum obrazových výřezů",
"modal.model_settings.minicpm_max_slice_nums_hint": "Nastavte limit dělení obrázku (alespoň 1). Prázdná hodnota použije výchozí nastavení procesoru modelu.",
- "imagine.welcome_description": "Zadejte pokyn místnímu obrazovému modelu a výsledek si prohlédněte a stáhněte.",
- "imagine.upload_browse": "Procházet obrázky",
"modal.model_settings.moe_expert_offload_resident_25": "25 % v paměti",
"modal.model_settings.moe_expert_offload_resident_12_5": "12,5 % v paměti",
- "imagine.submit.edit": "Upravit obrázek",
- "imagine.title": "Imagine - Správa oMLX",
- "imagine.advanced.title": "Pokročilé",
- "imagine.error.image_too_large": "Obrázek musí být menší než 25 MB",
"modal.model_settings.model_type_image": "Obrázek",
- "imagine.advanced.steps": "Počet kroků",
- "imagine.checkpoint_schedule_hint": "Uložený plán modelu má přednost před počtem kroků. Plán lze změnit polem sigmas v API.",
- "imagine.effective_steps": "Skutečný počet kroků",
- "imagine.results_heading": "Výsledky",
- "imagine.advanced.seed": "Seed",
- "imagine.advanced.n": "Počet obrázků",
- "imagine.upload_heading": "Referenční obrázky",
- "imagine.brand": "oMLX Imagine",
- "imagine.api_key_placeholder": "Zadejte API klíč...",
- "imagine.change_api_key": "Změnit API klíč",
"modal.model_settings.moe_expert_offload_resident_75": "75 % v paměti",
- "imagine.nav.chat": "Chat",
- "imagine.error.invalid_image_type": "Vyberte soubor s obrázkem",
- "imagine.nav.imagine": "Imagine",
- "imagine.image_preview": "Náhled obrázku",
- "imagine.timeline_model": "Model",
- "imagine.api_key_prompt": "Pro tvorbu obrázků zadejte API klíč",
- "imagine.submit.generating": "Generuji...",
- "imagine.result.download": "Stáhnout",
- "imagine.advanced.output_format": "Výstupní formát",
- "imagine.timeline_prompt": "Zadání",
- "imagine.mode.label": "Režim",
- "imagine.original_image_alt": "Původní obrázek",
- "imagine.select_model": "Obrazový model",
- "imagine.welcome_heading": "Tvořte s oMLX",
- "imagine.advanced.guidance": "Vedení",
- "imagine.prompt_label": "Zadání",
- "imagine.clear_results": "Vymazat výsledky",
"modal.model_settings.moe_expert_offload_resident_50": "50 % v paměti",
- "imagine.advanced.negative_prompt": "Negativní zadání",
- "imagine.timeline_original": "Originál",
- "imagine.advanced.size": "Velikost",
- "imagine.no_models_generation": "Nejsou dostupné žádné modely pro generování",
- "imagine.heading": "Imagine",
"modal.model_settings.dflash_single_stream": "Pouze jeden proud: požadavky se zpracovávají postupně.",
- "imagine.welcome_privacy": "Veškeré generování obrázků probíhá místně na vašem zařízení.",
- "imagine.error.incorrect_api_key": "API klíč je nesprávný. Zadejte jej znovu.",
- "imagine.result_image_alt": "Vygenerovaný obrázek",
- "imagine.upload_help": "Přetáhněte sem referenční obrázky, vložte je nebo je vyberte.",
- "imagine.subheading": "Generujte a upravujte obrázky pomocí místních modelů",
- "imagine.prompt_placeholder": "Popište obrázek, který chcete vytvořit...",
- "imagine.timeline_edited": "Upravený výsledek",
- "navbar.tab.imagine": "Imagine",
- "imagine.no_models_edit": "Nejsou dostupné žádné modely pro úpravy",
- "imagine.mode.generate": "Vygenerovat",
- "imagine.result.copy": "Kopírovat datovou URI",
- "imagine.mode.edit": "Upravit",
- "imagine.submit.editing": "Upravuji...",
- "imagine.remove_image": "Odebrat obrázek",
- "imagine.timeline_generated": "Vygenerovaný výsledek",
- "imagine.api_key_continue": "Pokračovat",
- "imagine.submit.generate": "Vygenerovat",
- "imagine.admin_settings": "Nastavení správy"
+ "chat.image_download": "Stáhnout",
+ "chat.image_reuse": "Použít pro úpravy"
}
diff --git a/apps/omlx-web/omlx_web/i18n/de.json b/apps/omlx-web/omlx_web/i18n/de.json
index f5d1098832..26c360721d 100644
--- a/apps/omlx-web/omlx_web/i18n/de.json
+++ b/apps/omlx-web/omlx_web/i18n/de.json
@@ -1,4 +1,6 @@
{
+ "chat.image_download": "Herunterladen",
+ "chat.image_reuse": "Zum Bearbeiten verwenden",
"cluster.device.ssh_user": "SSH-Benutzername",
"cluster.device.ssh_user_help": "Geben Sie den Kurznamen des Benutzerkontos auf dem entfernten Computer ein. Lassen Sie das Feld leer, um den bei der Registrierung hinterlegten Benutzernamen oder die SSH-Konfiguration zu verwenden.",
"cluster.device.ssh_user_save": "SSH-Benutzernamen speichern",
@@ -2475,66 +2477,10 @@
"modal.model_settings.minicpm_downsample_mode_hint": "16x verwendet weniger visuelle Tokens; 4x bewahrt mehr Details. Standard verwendet den Modellprozessor.",
"modal.model_settings.minicpm_max_slice_nums": "Maximale Bildausschnitte",
"modal.model_settings.minicpm_max_slice_nums_hint": "Legen Sie die maximale Anzahl der Bildausschnitte fest (mindestens 1). Leer lassen, um den Standard des Modellprozessors zu verwenden.",
- "imagine.admin_settings": "Admin-Einstellungen",
- "imagine.advanced.guidance": "Guidance",
- "imagine.advanced.n": "Bilder",
- "imagine.advanced.negative_prompt": "Negativer Prompt",
- "imagine.advanced.output_format": "Ausgabeformat",
- "imagine.advanced.seed": "Seed",
- "imagine.advanced.size": "Größe",
- "imagine.advanced.steps": "Schritte",
- "imagine.checkpoint_schedule_hint": "Der im Checkpoint gespeicherte Zeitplan hat Vorrang vor den Schritten. Verwenden Sie das API-Feld sigmas, um den Zeitplan zu ändern.",
- "imagine.effective_steps": "Tatsächliche Schritte",
- "imagine.advanced.title": "Erweitert",
- "imagine.api_key_continue": "Weiter",
- "imagine.api_key_placeholder": "API-Schlüssel eingeben...",
- "imagine.api_key_prompt": "Geben Sie Ihren API-Schlüssel ein, um Bilder zu erstellen",
- "imagine.brand": "oMLX Imagine",
- "imagine.change_api_key": "API-Schlüssel ändern",
- "imagine.clear_results": "Ergebnisse löschen",
- "imagine.error.image_too_large": "Die Bildgröße muss unter 25 MB liegen",
- "imagine.error.incorrect_api_key": "Der API-Schlüssel ist falsch. Bitte geben Sie ihn erneut ein.",
- "imagine.error.invalid_image_type": "Bitte wählen Sie eine Bilddatei aus",
- "imagine.heading": "Imagine",
- "imagine.image_preview": "Bildvorschau",
- "imagine.mode.edit": "Bearbeiten",
- "imagine.mode.generate": "Generieren",
- "imagine.mode.label": "Modus",
- "imagine.nav.chat": "Chat",
- "imagine.nav.imagine": "Imagine",
- "imagine.no_models_edit": "Keine Modelle zur Bildbearbeitung verfügbar",
- "imagine.no_models_generation": "Keine Modelle zur Bilderzeugung verfügbar",
- "imagine.original_image_alt": "Originalbild",
- "imagine.prompt_label": "Prompt",
- "imagine.prompt_placeholder": "Beschreiben Sie das gewünschte Bild...",
- "imagine.remove_image": "Bild entfernen",
- "imagine.result.copy": "Daten-URI kopieren",
- "imagine.result.download": "Herunterladen",
- "imagine.result_image_alt": "Generiertes Bild",
- "imagine.results_heading": "Ergebnisse",
- "imagine.select_model": "Bildmodell",
- "imagine.subheading": "Bilder mit lokalen Bildmodellen generieren und bearbeiten",
- "imagine.submit.edit": "Bild bearbeiten",
- "imagine.submit.editing": "Wird bearbeitet...",
- "imagine.submit.generate": "Generieren",
- "imagine.submit.generating": "Wird generiert...",
- "imagine.timeline_edited": "Bearbeitetes Ergebnis",
- "imagine.timeline_generated": "Generiertes Ergebnis",
- "imagine.timeline_model": "Modell",
- "imagine.timeline_original": "Original",
- "imagine.timeline_prompt": "Prompt",
- "imagine.title": "Imagine - oMLX Admin",
- "imagine.upload_browse": "Bilder durchsuchen",
- "imagine.upload_heading": "Referenzbilder",
- "imagine.upload_help": "Referenzbilder hier ablegen, einfügen oder auswählen.",
- "imagine.welcome_description": "Geben Sie einem lokalen Bildmodell einen Prompt, um das Ergebnis anzuzeigen und herunterzuladen.",
- "imagine.welcome_heading": "Imagine mit oMLX",
- "imagine.welcome_privacy": "Alle Bilder werden lokal auf Ihrem Gerät generiert.",
"modal.model_settings.dflash_single_stream": "Nur ein Stream: Anfragen werden nacheinander verarbeitet.",
"modal.model_settings.moe_expert_offload_resident_12_5": "12,5 % resident",
"modal.model_settings.moe_expert_offload_resident_25": "25 % resident",
"modal.model_settings.moe_expert_offload_resident_50": "50 % resident",
"modal.model_settings.moe_expert_offload_resident_75": "75 % resident",
- "navbar.tab.imagine": "Imagine",
"modal.model_settings.model_type_image": "Bild"
}
diff --git a/apps/omlx-web/omlx_web/i18n/en.json b/apps/omlx-web/omlx_web/i18n/en.json
index 56466574b2..1e6007777e 100644
--- a/apps/omlx-web/omlx_web/i18n/en.json
+++ b/apps/omlx-web/omlx_web/i18n/en.json
@@ -2475,66 +2475,12 @@
"modal.model_settings.minicpm_downsample_mode_hint": "16x uses fewer visual tokens; 4x preserves more detail. Default uses the model processor.",
"modal.model_settings.minicpm_max_slice_nums": "Maximum Image Slices",
"modal.model_settings.minicpm_max_slice_nums_hint": "Set the image slicing limit (at least 1). Leave empty for the model processor default.",
- "imagine.admin_settings": "Admin Settings",
- "imagine.advanced.guidance": "Guidance",
- "imagine.advanced.n": "Images",
- "imagine.advanced.negative_prompt": "Negative Prompt",
- "imagine.advanced.output_format": "Output Format",
- "imagine.advanced.seed": "Seed",
- "imagine.advanced.size": "Size",
- "imagine.advanced.steps": "Steps",
- "imagine.checkpoint_schedule_hint": "The saved checkpoint schedule overrides Steps. Use the API sigmas field to change the schedule.",
- "imagine.effective_steps": "Actual steps",
- "imagine.advanced.title": "Advanced",
- "imagine.api_key_continue": "Continue",
- "imagine.api_key_placeholder": "Enter API key...",
- "imagine.api_key_prompt": "Enter your API key to start creating images",
- "imagine.brand": "oMLX Imagine",
- "imagine.change_api_key": "Change API Key",
- "imagine.clear_results": "Clear Results",
- "imagine.error.image_too_large": "Image size must be less than 25MB",
- "imagine.error.incorrect_api_key": "API key is incorrect. Please re-enter your API key.",
- "imagine.error.invalid_image_type": "Please select an image file",
- "imagine.heading": "Imagine",
- "imagine.image_preview": "Image preview",
- "imagine.mode.edit": "Edit",
- "imagine.mode.generate": "Generate",
- "imagine.mode.label": "Mode",
- "imagine.nav.chat": "Chat",
- "imagine.nav.imagine": "Imagine",
- "imagine.no_models_edit": "No edit models available",
- "imagine.no_models_generation": "No generation models available",
- "imagine.original_image_alt": "Original image",
- "imagine.prompt_label": "Prompt",
- "imagine.prompt_placeholder": "Describe the image you want...",
- "imagine.remove_image": "Remove image",
- "imagine.result.copy": "Copy Data URI",
- "imagine.result.download": "Download",
- "imagine.result_image_alt": "Generated image",
- "imagine.results_heading": "Results",
- "imagine.select_model": "Image Model",
- "imagine.subheading": "Generate and edit images with local image models",
- "imagine.submit.edit": "Edit Image",
- "imagine.submit.editing": "Editing...",
- "imagine.submit.generate": "Generate",
- "imagine.submit.generating": "Generating...",
- "imagine.timeline_edited": "Edited result",
- "imagine.timeline_generated": "Generated result",
- "imagine.timeline_model": "Model",
- "imagine.timeline_original": "Original",
- "imagine.timeline_prompt": "Prompt",
- "imagine.title": "Imagine - oMLX Admin",
- "imagine.upload_browse": "Browse Images",
- "imagine.upload_heading": "Reference Images",
- "imagine.upload_help": "Drop reference images here, paste, or browse.",
- "imagine.welcome_description": "Prompt a local image model, then preview and download the result.",
- "imagine.welcome_heading": "Imagine with oMLX",
- "imagine.welcome_privacy": "All image generation runs locally on your device.",
"modal.model_settings.dflash_single_stream": "Single-stream only: requests run one at a time.",
"modal.model_settings.moe_expert_offload_resident_12_5": "12.5% resident",
"modal.model_settings.moe_expert_offload_resident_25": "25% resident",
"modal.model_settings.moe_expert_offload_resident_50": "50% resident",
"modal.model_settings.moe_expert_offload_resident_75": "75% resident",
- "navbar.tab.imagine": "Imagine",
- "modal.model_settings.model_type_image": "Image"
+ "modal.model_settings.model_type_image": "Image",
+ "chat.image_download": "Download",
+ "chat.image_reuse": "Reuse for editing"
}
diff --git a/apps/omlx-web/omlx_web/i18n/es.json b/apps/omlx-web/omlx_web/i18n/es.json
index 7b7b164125..1f98516253 100644
--- a/apps/omlx-web/omlx_web/i18n/es.json
+++ b/apps/omlx-web/omlx_web/i18n/es.json
@@ -2475,66 +2475,12 @@
"modal.model_settings.minicpm_downsample_mode_hint": "16x usa menos tokens visuales; 4x conserva más detalles. La opción predeterminada usa el procesador del modelo.",
"modal.model_settings.minicpm_max_slice_nums": "Máximo de segmentos de imagen",
"modal.model_settings.minicpm_max_slice_nums_hint": "Establece el límite de segmentación de imágenes (al menos 1). Déjalo vacío para usar el valor predeterminado del procesador del modelo.",
- "imagine.welcome_description": "Usa un modelo local de imágenes y descarga el resultado.",
- "imagine.upload_browse": "Buscar imágenes",
"modal.model_settings.moe_expert_offload_resident_25": "25% resident",
"modal.model_settings.moe_expert_offload_resident_12_5": "12.5% resident",
- "imagine.submit.edit": "Editar imagen",
- "imagine.title": "Imagine - oMLX Admin",
- "imagine.advanced.title": "Avanzado",
- "imagine.error.image_too_large": "El tamaño de la imagen debe ser menor a 25MB",
"modal.model_settings.model_type_image": "Imagen",
- "imagine.advanced.steps": "Pasos",
- "imagine.checkpoint_schedule_hint": "El programa guardado del modelo tiene prioridad sobre los pasos. Cámbialo con el campo sigmas de la API.",
- "imagine.effective_steps": "Pasos reales",
- "imagine.results_heading": "Resultados",
- "imagine.advanced.seed": "Seed",
- "imagine.advanced.n": "Imágenes",
- "imagine.upload_heading": "Imágenes de referencia",
- "imagine.brand": "oMLX Imagine",
- "imagine.api_key_placeholder": "Ingresa la clave API...",
- "imagine.change_api_key": "Cambiar Clave API",
"modal.model_settings.moe_expert_offload_resident_75": "75% resident",
- "imagine.nav.chat": "Chat",
- "imagine.error.invalid_image_type": "Por favor selecciona un archivo de imagen",
- "imagine.nav.imagine": "Imagine",
- "imagine.image_preview": "Vista previa de la imagen",
- "imagine.timeline_model": "Modelo",
- "imagine.api_key_prompt": "Ingresa tu clave API para comenzar a crear imágenes",
- "imagine.submit.generating": "Generando...",
- "imagine.result.download": "Descargar",
- "imagine.advanced.output_format": "Formato de salida",
- "imagine.timeline_prompt": "Prompt",
- "imagine.mode.label": "Modo",
- "imagine.original_image_alt": "Imagen original",
- "imagine.select_model": "Modelo de imagen",
- "imagine.welcome_heading": "Imagine con oMLX",
- "imagine.advanced.guidance": "Guía",
- "imagine.prompt_label": "Prompt",
- "imagine.clear_results": "Limpiar resultados",
"modal.model_settings.moe_expert_offload_resident_50": "50% resident",
- "imagine.advanced.negative_prompt": "Prompt negativo",
- "imagine.timeline_original": "Original",
- "imagine.advanced.size": "Tamaño",
- "imagine.no_models_generation": "No hay modelos de generación disponibles",
- "imagine.heading": "Imagine",
"modal.model_settings.dflash_single_stream": "Single-stream only: requests run one at a time.",
- "imagine.welcome_privacy": "Toda la generación de imágenes se ejecuta localmente en tu dispositivo.",
- "imagine.error.incorrect_api_key": "La clave API es incorrecta. Por favor ingrésala nuevamente.",
- "imagine.result_image_alt": "Imagen generada",
- "imagine.upload_help": "Arrastra imágenes aquí, pega o explora.",
- "imagine.subheading": "Genera y edita imágenes con modelos locales",
- "imagine.prompt_placeholder": "Describe la imagen que quieres...",
- "imagine.timeline_edited": "Resultado editado",
- "navbar.tab.imagine": "Imagine",
- "imagine.no_models_edit": "No hay modelos de edición disponibles",
- "imagine.mode.generate": "Generar",
- "imagine.result.copy": "Copiar Data URI",
- "imagine.mode.edit": "Editar",
- "imagine.submit.editing": "Editando...",
- "imagine.remove_image": "Eliminar imagen",
- "imagine.timeline_generated": "Resultado generado",
- "imagine.api_key_continue": "Continuar",
- "imagine.submit.generate": "Generar",
- "imagine.admin_settings": "Configuración Admin"
+ "chat.image_download": "Descargar",
+ "chat.image_reuse": "Reutilizar para editar"
}
diff --git a/apps/omlx-web/omlx_web/i18n/fr.json b/apps/omlx-web/omlx_web/i18n/fr.json
index 23d3fed213..85b996acb8 100644
--- a/apps/omlx-web/omlx_web/i18n/fr.json
+++ b/apps/omlx-web/omlx_web/i18n/fr.json
@@ -2475,66 +2475,12 @@
"modal.model_settings.minicpm_downsample_mode_hint": "16x utilise moins de jetons visuels ; 4x préserve davantage de détails. L'option par défaut utilise le processeur du modèle.",
"modal.model_settings.minicpm_max_slice_nums": "Nombre maximal de découpes d'image",
"modal.model_settings.minicpm_max_slice_nums_hint": "Définissez la limite de découpage des images (au moins 1). Laissez vide pour utiliser la valeur par défaut du processeur du modèle.",
- "imagine.admin_settings": "Paramètres d'administration",
- "imagine.advanced.guidance": "Guidage",
- "imagine.advanced.n": "Images",
- "imagine.advanced.negative_prompt": "Prompt négatif",
- "imagine.advanced.output_format": "Format de sortie",
- "imagine.advanced.seed": "Seed",
- "imagine.advanced.size": "Taille",
- "imagine.advanced.steps": "Étapes",
- "imagine.checkpoint_schedule_hint": "Le calendrier enregistré du modèle prime sur les étapes. Utilisez le champ sigmas de l'API pour le modifier.",
- "imagine.effective_steps": "Étapes réelles",
- "imagine.advanced.title": "Avancé",
- "imagine.api_key_continue": "Continuer",
- "imagine.api_key_placeholder": "Entrez la clé API...",
- "imagine.api_key_prompt": "Entrez votre clé API pour commencer à créer des images",
- "imagine.brand": "oMLX Imagine",
- "imagine.change_api_key": "Modifier la clé API",
- "imagine.clear_results": "Effacer les résultats",
- "imagine.error.image_too_large": "La taille de l'image doit être inférieure à 25 Mo",
- "imagine.error.incorrect_api_key": "La clé API est incorrecte. Veuillez réentrer votre clé API.",
- "imagine.error.invalid_image_type": "Veuillez sélectionner un fichier image",
- "imagine.heading": "Imagine",
- "imagine.image_preview": "Aperçu de l'image",
- "imagine.mode.edit": "Modifier",
- "imagine.mode.generate": "Générer",
- "imagine.mode.label": "Mode",
- "imagine.nav.chat": "Chat",
- "imagine.nav.imagine": "Imagine",
- "imagine.no_models_edit": "Aucun modèle d'édition disponible",
- "imagine.no_models_generation": "Aucun modèle de génération disponible",
- "imagine.original_image_alt": "Image originale",
- "imagine.prompt_label": "Prompt",
- "imagine.prompt_placeholder": "Décrivez l'image souhaitée...",
- "imagine.remove_image": "Supprimer l'image",
- "imagine.result.copy": "Copier le Data URI",
- "imagine.result.download": "Télécharger",
- "imagine.result_image_alt": "Image générée",
- "imagine.results_heading": "Résultats",
- "imagine.select_model": "Modèle image",
- "imagine.subheading": "Générez et modifiez des images avec des modèles locaux",
- "imagine.submit.edit": "Modifier l'image",
- "imagine.submit.editing": "Modification...",
- "imagine.submit.generate": "Générer",
- "imagine.submit.generating": "Génération...",
- "imagine.timeline_edited": "Résultat modifié",
- "imagine.timeline_generated": "Résultat généré",
- "imagine.timeline_model": "Modèle",
- "imagine.timeline_original": "Original",
- "imagine.timeline_prompt": "Invite",
- "imagine.title": "Imagine - oMLX Admin",
- "imagine.upload_browse": "Parcourir les images",
- "imagine.upload_heading": "Images de référence",
- "imagine.upload_help": "Déposez des images ici, collez ou parcourez.",
- "imagine.welcome_description": "Utilisez un modèle image local, puis prévisualisez et téléchargez le résultat.",
- "imagine.welcome_heading": "Imagine avec oMLX",
- "imagine.welcome_privacy": "Toute génération d'image s'exécute localement sur votre appareil.",
"modal.model_settings.dflash_single_stream": "Single-stream only: requests run one at a time.",
"modal.model_settings.moe_expert_offload_resident_12_5": "12.5% resident",
"modal.model_settings.moe_expert_offload_resident_25": "25% resident",
"modal.model_settings.moe_expert_offload_resident_50": "50% resident",
"modal.model_settings.moe_expert_offload_resident_75": "75% resident",
- "navbar.tab.imagine": "Imagine",
- "modal.model_settings.model_type_image": "Image"
+ "modal.model_settings.model_type_image": "Image",
+ "chat.image_download": "Télécharger",
+ "chat.image_reuse": "Réutiliser pour modifier"
}
diff --git a/apps/omlx-web/omlx_web/i18n/ja.json b/apps/omlx-web/omlx_web/i18n/ja.json
index 066cfa42aa..9eef839007 100644
--- a/apps/omlx-web/omlx_web/i18n/ja.json
+++ b/apps/omlx-web/omlx_web/i18n/ja.json
@@ -2475,66 +2475,12 @@
"modal.model_settings.minicpm_downsample_mode_hint": "16x は視覚トークンを削減し、4x はより多くの細部を保持します。デフォルトはモデルのプロセッサ設定を使用します。",
"modal.model_settings.minicpm_max_slice_nums": "画像スライス数の上限",
"modal.model_settings.minicpm_max_slice_nums_hint": "画像分割の上限を設定します(1 以上)。空欄の場合はモデルのプロセッサのデフォルトを使用します。",
- "imagine.welcome_description": "ローカル画像モデルにプロンプトを送り、結果をプレビューしてダウンロードします。",
- "imagine.upload_browse": "画像を選択",
"modal.model_settings.moe_expert_offload_resident_25": "25% resident",
"modal.model_settings.moe_expert_offload_resident_12_5": "12.5% resident",
- "imagine.submit.edit": "画像を編集",
- "imagine.title": "Imagine - oMLX 管理画面",
- "imagine.advanced.title": "詳細",
- "imagine.error.image_too_large": "画像サイズは25MB以下にしてください",
"modal.model_settings.model_type_image": "画像",
- "imagine.advanced.steps": "ステップ",
- "imagine.checkpoint_schedule_hint": "保存されたモデルのスケジュールがステップ数より優先されます。変更するには API の sigmas フィールドを使用してください。",
- "imagine.effective_steps": "実際のステップ数",
- "imagine.results_heading": "結果",
- "imagine.advanced.seed": "Seed",
- "imagine.advanced.n": "画像数",
- "imagine.upload_heading": "参照画像",
- "imagine.brand": "oMLX Imagine",
- "imagine.api_key_placeholder": "APIキーを入力...",
- "imagine.change_api_key": "APIキーを変更",
"modal.model_settings.moe_expert_offload_resident_75": "75% resident",
- "imagine.nav.chat": "チャット",
- "imagine.error.invalid_image_type": "画像ファイルを選択してください",
- "imagine.nav.imagine": "Imagine",
- "imagine.image_preview": "画像プレビュー",
- "imagine.timeline_model": "モデル",
- "imagine.api_key_prompt": "画像作成を開始するにはAPIキーを入力してください",
- "imagine.submit.generating": "生成中...",
- "imagine.result.download": "ダウンロード",
- "imagine.advanced.output_format": "出力形式",
- "imagine.timeline_prompt": "プロンプト",
- "imagine.mode.label": "モード",
- "imagine.original_image_alt": "元画像",
- "imagine.select_model": "画像モデル",
- "imagine.welcome_heading": "oMLXでImagine",
- "imagine.advanced.guidance": "Guidance",
- "imagine.prompt_label": "プロンプト",
- "imagine.clear_results": "結果をクリア",
"modal.model_settings.moe_expert_offload_resident_50": "50% resident",
- "imagine.advanced.negative_prompt": "ネガティブプロンプト",
- "imagine.timeline_original": "元画像",
- "imagine.advanced.size": "サイズ",
- "imagine.no_models_generation": "利用可能な生成モデルがありません",
- "imagine.heading": "Imagine",
"modal.model_settings.dflash_single_stream": "Single-stream only: requests run one at a time.",
- "imagine.welcome_privacy": "すべての画像生成はローカルデバイス上で実行されます。",
- "imagine.error.incorrect_api_key": "APIキーが正しくありません。再入力してください。",
- "imagine.result_image_alt": "生成画像",
- "imagine.upload_help": "参照画像をドロップ、貼り付け、または選択します。",
- "imagine.subheading": "ローカル画像モデルで画像を生成・編集します",
- "imagine.prompt_placeholder": "作成したい画像を説明してください...",
- "imagine.timeline_edited": "編集結果",
- "navbar.tab.imagine": "Imagine",
- "imagine.no_models_edit": "利用可能な編集モデルがありません",
- "imagine.mode.generate": "生成",
- "imagine.result.copy": "Data URIをコピー",
- "imagine.mode.edit": "編集",
- "imagine.submit.editing": "編集中...",
- "imagine.remove_image": "画像を削除",
- "imagine.timeline_generated": "生成結果",
- "imagine.api_key_continue": "続行",
- "imagine.submit.generate": "生成",
- "imagine.admin_settings": "管理設定"
+ "chat.image_download": "ダウンロード",
+ "chat.image_reuse": "編集に再利用"
}
diff --git a/apps/omlx-web/omlx_web/i18n/ko.json b/apps/omlx-web/omlx_web/i18n/ko.json
index 4620236d39..51886d2801 100644
--- a/apps/omlx-web/omlx_web/i18n/ko.json
+++ b/apps/omlx-web/omlx_web/i18n/ko.json
@@ -2475,66 +2475,12 @@
"modal.model_settings.minicpm_downsample_mode_hint": "16x는 시각 토큰을 줄이고, 4x는 더 많은 세부 정보를 유지합니다. 기본값은 모델 프로세서 설정을 사용합니다.",
"modal.model_settings.minicpm_max_slice_nums": "최대 이미지 슬라이스 수",
"modal.model_settings.minicpm_max_slice_nums_hint": "이미지 분할 한도를 설정합니다(최소 1). 비워 두면 모델 프로세서의 기본값을 사용합니다.",
- "imagine.welcome_description": "로컬 이미지 모델에 프롬프트를 보내고 결과를 미리 보고 다운로드하세요.",
- "imagine.upload_browse": "이미지 선택",
"modal.model_settings.moe_expert_offload_resident_25": "25% resident",
"modal.model_settings.moe_expert_offload_resident_12_5": "12.5% resident",
- "imagine.submit.edit": "이미지 편집",
- "imagine.title": "Imagine - oMLX 관리자",
- "imagine.advanced.title": "고급",
- "imagine.error.image_too_large": "이미지 크기는 25MB 이하여야 합니다",
"modal.model_settings.model_type_image": "이미지",
- "imagine.advanced.steps": "스텝",
- "imagine.checkpoint_schedule_hint": "저장된 모델 스케줄이 스텝 수보다 우선합니다. 변경하려면 API의 sigmas 필드를 사용하세요.",
- "imagine.effective_steps": "실제 스텝 수",
- "imagine.results_heading": "결과",
- "imagine.advanced.seed": "Seed",
- "imagine.advanced.n": "이미지 수",
- "imagine.upload_heading": "참조 이미지",
- "imagine.brand": "oMLX Imagine",
- "imagine.api_key_placeholder": "API 키 입력...",
- "imagine.change_api_key": "API 키 변경",
"modal.model_settings.moe_expert_offload_resident_75": "75% resident",
- "imagine.nav.chat": "채팅",
- "imagine.error.invalid_image_type": "이미지 파일을 선택해주세요",
- "imagine.nav.imagine": "Imagine",
- "imagine.image_preview": "이미지 미리보기",
- "imagine.timeline_model": "모델",
- "imagine.api_key_prompt": "이미지 생성을 시작하려면 API 키를 입력하세요",
- "imagine.submit.generating": "생성 중...",
- "imagine.result.download": "다운로드",
- "imagine.advanced.output_format": "출력 형식",
- "imagine.timeline_prompt": "프롬프트",
- "imagine.mode.label": "모드",
- "imagine.original_image_alt": "원본 이미지",
- "imagine.select_model": "이미지 모델",
- "imagine.welcome_heading": "oMLX로 Imagine",
- "imagine.advanced.guidance": "Guidance",
- "imagine.prompt_label": "프롬프트",
- "imagine.clear_results": "결과 지우기",
"modal.model_settings.moe_expert_offload_resident_50": "50% resident",
- "imagine.advanced.negative_prompt": "네거티브 프롬프트",
- "imagine.timeline_original": "원본",
- "imagine.advanced.size": "크기",
- "imagine.no_models_generation": "사용 가능한 생성 모델 없음",
- "imagine.heading": "Imagine",
"modal.model_settings.dflash_single_stream": "Single-stream only: requests run one at a time.",
- "imagine.welcome_privacy": "모든 이미지 생성은 로컬 기기에서 실행됩니다.",
- "imagine.error.incorrect_api_key": "API 키가 올바르지 않습니다. 다시 입력해 주세요.",
- "imagine.result_image_alt": "생성된 이미지",
- "imagine.upload_help": "참조 이미지를 드롭하거나 붙여넣거나 선택하세요.",
- "imagine.subheading": "로컬 이미지 모델로 이미지를 생성하고 편집합니다",
- "imagine.prompt_placeholder": "원하는 이미지를 설명하세요...",
- "imagine.timeline_edited": "편집 결과",
- "navbar.tab.imagine": "Imagine",
- "imagine.no_models_edit": "사용 가능한 편집 모델 없음",
- "imagine.mode.generate": "생성",
- "imagine.result.copy": "Data URI 복사",
- "imagine.mode.edit": "편집",
- "imagine.submit.editing": "편집 중...",
- "imagine.remove_image": "이미지 제거",
- "imagine.timeline_generated": "생성 결과",
- "imagine.api_key_continue": "계속",
- "imagine.submit.generate": "생성",
- "imagine.admin_settings": "관리자 설정"
+ "chat.image_download": "다운로드",
+ "chat.image_reuse": "편집에 재사용"
}
diff --git a/apps/omlx-web/omlx_web/i18n/pt-BR.json b/apps/omlx-web/omlx_web/i18n/pt-BR.json
index d5073baa43..c407ec2975 100644
--- a/apps/omlx-web/omlx_web/i18n/pt-BR.json
+++ b/apps/omlx-web/omlx_web/i18n/pt-BR.json
@@ -2475,66 +2475,12 @@
"modal.model_settings.minicpm_downsample_mode_hint": "16x usa menos tokens visuais; 4x preserva mais detalhes. A opção padrão usa o processador do modelo.",
"modal.model_settings.minicpm_max_slice_nums": "Máximo de segmentos de imagem",
"modal.model_settings.minicpm_max_slice_nums_hint": "Defina o limite de segmentação de imagens (pelo menos 1). Deixe em branco para usar o padrão do processador do modelo.",
- "imagine.welcome_description": "Use um modelo local de imagem, depois visualize e baixe o resultado.",
- "imagine.upload_browse": "Procurar imagens",
"modal.model_settings.moe_expert_offload_resident_25": "25% resident",
"modal.model_settings.moe_expert_offload_resident_12_5": "12.5% resident",
- "imagine.submit.edit": "Editar imagem",
- "imagine.title": "Imagine - oMLX Admin",
- "imagine.advanced.title": "Avançado",
- "imagine.error.image_too_large": "O tamanho da imagem deve ser menor que 25MB",
"modal.model_settings.model_type_image": "Imagem",
- "imagine.advanced.steps": "Passos",
- "imagine.checkpoint_schedule_hint": "O cronograma salvo do modelo tem prioridade sobre os passos. Use o campo sigmas da API para alterá-lo.",
- "imagine.effective_steps": "Passos reais",
- "imagine.results_heading": "Resultados",
- "imagine.advanced.seed": "Seed",
- "imagine.advanced.n": "Imagens",
- "imagine.upload_heading": "Imagens de referência",
- "imagine.brand": "oMLX Imagine",
- "imagine.api_key_placeholder": "Insira a chave de API...",
- "imagine.change_api_key": "Alterar Chave de API",
"modal.model_settings.moe_expert_offload_resident_75": "75% resident",
- "imagine.nav.chat": "Chat",
- "imagine.error.invalid_image_type": "Selecione um arquivo de imagem",
- "imagine.nav.imagine": "Imagine",
- "imagine.image_preview": "Pré-visualização da imagem",
- "imagine.timeline_model": "Modelo",
- "imagine.api_key_prompt": "Insira sua chave de API para começar a criar imagens",
- "imagine.submit.generating": "Gerando...",
- "imagine.result.download": "Baixar",
- "imagine.advanced.output_format": "Formato de saída",
- "imagine.timeline_prompt": "Prompt",
- "imagine.mode.label": "Modo",
- "imagine.original_image_alt": "Imagem original",
- "imagine.select_model": "Modelo de imagem",
- "imagine.welcome_heading": "Imagine com oMLX",
- "imagine.advanced.guidance": "Orientação",
- "imagine.prompt_label": "Prompt",
- "imagine.clear_results": "Limpar resultados",
"modal.model_settings.moe_expert_offload_resident_50": "50% resident",
- "imagine.advanced.negative_prompt": "Prompt negativo",
- "imagine.timeline_original": "Original",
- "imagine.advanced.size": "Tamanho",
- "imagine.no_models_generation": "Nenhum modelo de geração disponível",
- "imagine.heading": "Imagine",
"modal.model_settings.dflash_single_stream": "Single-stream only: requests run one at a time.",
- "imagine.welcome_privacy": "Toda geração de imagens roda localmente no seu dispositivo.",
- "imagine.error.incorrect_api_key": "A chave de API está incorreta. Insira sua chave de API novamente.",
- "imagine.result_image_alt": "Imagem gerada",
- "imagine.upload_help": "Solte imagens aqui, cole ou procure.",
- "imagine.subheading": "Gere e edite imagens com modelos locais de imagem",
- "imagine.prompt_placeholder": "Descreva a imagem que você quer...",
- "imagine.timeline_edited": "Resultado editado",
- "navbar.tab.imagine": "Imagine",
- "imagine.no_models_edit": "Nenhum modelo de edição disponível",
- "imagine.mode.generate": "Gerar",
- "imagine.result.copy": "Copiar Data URI",
- "imagine.mode.edit": "Editar",
- "imagine.submit.editing": "Editando...",
- "imagine.remove_image": "Remover imagem",
- "imagine.timeline_generated": "Resultado gerado",
- "imagine.api_key_continue": "Continuar",
- "imagine.submit.generate": "Gerar",
- "imagine.admin_settings": "Configurações de Admin"
+ "chat.image_download": "Baixar",
+ "chat.image_reuse": "Reutilizar para editar"
}
diff --git a/apps/omlx-web/omlx_web/i18n/ru.json b/apps/omlx-web/omlx_web/i18n/ru.json
index 85ecc065ac..1dc074f4e9 100644
--- a/apps/omlx-web/omlx_web/i18n/ru.json
+++ b/apps/omlx-web/omlx_web/i18n/ru.json
@@ -2475,66 +2475,12 @@
"modal.model_settings.minicpm_downsample_mode_hint": "16x использует меньше визуальных токенов; 4x сохраняет больше деталей. Значение по умолчанию определяется процессором модели.",
"modal.model_settings.minicpm_max_slice_nums": "Максимальное число фрагментов изображения",
"modal.model_settings.minicpm_max_slice_nums_hint": "Задайте предел разбиения изображения (не менее 1). Оставьте поле пустым для значения по умолчанию процессора модели.",
- "imagine.welcome_description": "Введите промпт для локальной модели изображений, затем просмотрите и скачайте результат.",
- "imagine.upload_browse": "Выбрать изображения",
"modal.model_settings.moe_expert_offload_resident_25": "25% resident",
"modal.model_settings.moe_expert_offload_resident_12_5": "12.5% resident",
- "imagine.submit.edit": "Редактировать изображение",
- "imagine.title": "Imagine - oMLX Админ",
- "imagine.advanced.title": "Дополнительно",
- "imagine.error.image_too_large": "Размер изображения должен быть меньше 25 МБ",
"modal.model_settings.model_type_image": "Изображение",
- "imagine.advanced.steps": "Шаги",
- "imagine.checkpoint_schedule_hint": "Сохранённое расписание модели имеет приоритет над числом шагов. Для изменения используйте поле sigmas в API.",
- "imagine.effective_steps": "Фактические шаги",
- "imagine.results_heading": "Результаты",
- "imagine.advanced.seed": "Seed",
- "imagine.advanced.n": "Изображения",
- "imagine.upload_heading": "Референсные изображения",
- "imagine.brand": "oMLX Imagine",
- "imagine.api_key_placeholder": "Введите API-ключ...",
- "imagine.change_api_key": "Изменить API-ключ",
"modal.model_settings.moe_expert_offload_resident_75": "75% resident",
- "imagine.nav.chat": "Чат",
- "imagine.error.invalid_image_type": "Выберите файл изображения",
- "imagine.nav.imagine": "Imagine",
- "imagine.image_preview": "Предпросмотр изображения",
- "imagine.timeline_model": "Модель",
- "imagine.api_key_prompt": "Введите API-ключ, чтобы начать создавать изображения",
- "imagine.submit.generating": "Генерация...",
- "imagine.result.download": "Скачать",
- "imagine.advanced.output_format": "Формат вывода",
- "imagine.timeline_prompt": "Промпт",
- "imagine.mode.label": "Режим",
- "imagine.original_image_alt": "Исходное изображение",
- "imagine.select_model": "Модель изображений",
- "imagine.welcome_heading": "Imagine с oMLX",
- "imagine.advanced.guidance": "Guidance",
- "imagine.prompt_label": "Промпт",
- "imagine.clear_results": "Очистить результаты",
"modal.model_settings.moe_expert_offload_resident_50": "50% resident",
- "imagine.advanced.negative_prompt": "Негативный промпт",
- "imagine.timeline_original": "Оригинал",
- "imagine.advanced.size": "Размер",
- "imagine.no_models_generation": "Нет доступных моделей генерации",
- "imagine.heading": "Imagine",
"modal.model_settings.dflash_single_stream": "Single-stream only: requests run one at a time.",
- "imagine.welcome_privacy": "Вся генерация изображений выполняется локально на вашем устройстве.",
- "imagine.error.incorrect_api_key": "API-ключ неверен. Пожалуйста, введите его снова.",
- "imagine.result_image_alt": "Сгенерированное изображение",
- "imagine.upload_help": "Перетащите изображения сюда, вставьте или выберите.",
- "imagine.subheading": "Генерируйте и редактируйте изображения локальными моделями",
- "imagine.prompt_placeholder": "Опишите нужное изображение...",
- "imagine.timeline_edited": "Результат редактирования",
- "navbar.tab.imagine": "Imagine",
- "imagine.no_models_edit": "Нет доступных моделей редактирования",
- "imagine.mode.generate": "Генерация",
- "imagine.result.copy": "Копировать Data URI",
- "imagine.mode.edit": "Редактирование",
- "imagine.submit.editing": "Редактирование...",
- "imagine.remove_image": "Удалить изображение",
- "imagine.timeline_generated": "Сгенерированный результат",
- "imagine.api_key_continue": "Продолжить",
- "imagine.submit.generate": "Генерировать",
- "imagine.admin_settings": "Настройки админки"
+ "chat.image_download": "Скачать",
+ "chat.image_reuse": "Использовать для редактирования"
}
diff --git a/apps/omlx-web/omlx_web/i18n/zh-TW.json b/apps/omlx-web/omlx_web/i18n/zh-TW.json
index e80e310eae..0bd790531e 100644
--- a/apps/omlx-web/omlx_web/i18n/zh-TW.json
+++ b/apps/omlx-web/omlx_web/i18n/zh-TW.json
@@ -2475,66 +2475,12 @@
"modal.model_settings.minicpm_downsample_mode_hint": "16x 使用較少的視覺 token;4x 保留更多細節。預設選項使用模型處理器設定。",
"modal.model_settings.minicpm_max_slice_nums": "最大影像切片數",
"modal.model_settings.minicpm_max_slice_nums_hint": "設定影像切片上限(至少為 1)。留空則使用模型處理器的預設值。",
- "imagine.welcome_description": "提示本機圖片模型,然後預覽並下載結果。",
- "imagine.upload_browse": "選擇圖片",
"modal.model_settings.moe_expert_offload_resident_25": "25% resident",
"modal.model_settings.moe_expert_offload_resident_12_5": "12.5% resident",
- "imagine.submit.edit": "編輯圖片",
- "imagine.title": "Imagine - oMLX 管理後台",
- "imagine.advanced.title": "進階",
- "imagine.error.image_too_large": "圖片大小不能超過 25MB",
"modal.model_settings.model_type_image": "影像",
- "imagine.advanced.steps": "步數",
- "imagine.checkpoint_schedule_hint": "模型儲存的排程優先於步數設定。請使用 API 的 sigmas 欄位變更排程。",
- "imagine.effective_steps": "實際步數",
- "imagine.results_heading": "結果",
- "imagine.advanced.seed": "Seed",
- "imagine.advanced.n": "圖片數",
- "imagine.upload_heading": "參考圖片",
- "imagine.brand": "oMLX Imagine",
- "imagine.api_key_placeholder": "輸入 API 金鑰...",
- "imagine.change_api_key": "更換 API 金鑰",
"modal.model_settings.moe_expert_offload_resident_75": "75% resident",
- "imagine.nav.chat": "聊天",
- "imagine.error.invalid_image_type": "請選擇圖片檔案",
- "imagine.nav.imagine": "Imagine",
- "imagine.image_preview": "圖片預覽",
- "imagine.timeline_model": "模型",
- "imagine.api_key_prompt": "輸入 API 金鑰以開始建立圖片",
- "imagine.submit.generating": "生成中...",
- "imagine.result.download": "下載",
- "imagine.advanced.output_format": "輸出格式",
- "imagine.timeline_prompt": "提示詞",
- "imagine.mode.label": "模式",
- "imagine.original_image_alt": "原始圖片",
- "imagine.select_model": "圖片模型",
- "imagine.welcome_heading": "使用 oMLX Imagine",
- "imagine.advanced.guidance": "Guidance",
- "imagine.prompt_label": "提示詞",
- "imagine.clear_results": "清除結果",
"modal.model_settings.moe_expert_offload_resident_50": "50% resident",
- "imagine.advanced.negative_prompt": "負面提示詞",
- "imagine.timeline_original": "原圖",
- "imagine.advanced.size": "尺寸",
- "imagine.no_models_generation": "暫無可用生成模型",
- "imagine.heading": "Imagine",
"modal.model_settings.dflash_single_stream": "Single-stream only: requests run one at a time.",
- "imagine.welcome_privacy": "所有圖片生成均在本機設備上執行。",
- "imagine.error.incorrect_api_key": "API 金鑰不正確,請重新輸入。",
- "imagine.result_image_alt": "生成的圖片",
- "imagine.upload_help": "拖放參考圖片、貼上或瀏覽。",
- "imagine.subheading": "使用本機圖片模型生成和編輯圖片",
- "imagine.prompt_placeholder": "描述您想要的圖片...",
- "imagine.timeline_edited": "編輯結果",
- "navbar.tab.imagine": "Imagine",
- "imagine.no_models_edit": "暫無可用編輯模型",
- "imagine.mode.generate": "生成",
- "imagine.result.copy": "複製 Data URI",
- "imagine.mode.edit": "編輯",
- "imagine.submit.editing": "編輯中...",
- "imagine.remove_image": "移除圖片",
- "imagine.timeline_generated": "生成結果",
- "imagine.api_key_continue": "繼續",
- "imagine.submit.generate": "生成",
- "imagine.admin_settings": "管理後台"
+ "chat.image_download": "下載",
+ "chat.image_reuse": "重新用於編輯"
}
diff --git a/apps/omlx-web/omlx_web/i18n/zh.json b/apps/omlx-web/omlx_web/i18n/zh.json
index 1ca53d0391..50c3595188 100644
--- a/apps/omlx-web/omlx_web/i18n/zh.json
+++ b/apps/omlx-web/omlx_web/i18n/zh.json
@@ -2475,66 +2475,12 @@
"modal.model_settings.minicpm_downsample_mode_hint": "16x 使用更少的视觉 token;4x 保留更多细节。默认选项使用模型处理器设置。",
"modal.model_settings.minicpm_max_slice_nums": "最大图像切片数",
"modal.model_settings.minicpm_max_slice_nums_hint": "设置图像切片上限(至少为 1)。留空则使用模型处理器的默认值。",
- "imagine.welcome_description": "提示本地图像模型,然后预览并下载结果。",
- "imagine.upload_browse": "选择图像",
"modal.model_settings.moe_expert_offload_resident_25": "常驻 25%",
"modal.model_settings.moe_expert_offload_resident_12_5": "常驻 12.5%",
- "imagine.submit.edit": "编辑图像",
- "imagine.title": "Imagine - oMLX 管理后台",
- "imagine.advanced.title": "高级",
- "imagine.error.image_too_large": "图像大小不能超过 25MB",
"modal.model_settings.model_type_image": "图像",
- "imagine.advanced.steps": "步数",
- "imagine.checkpoint_schedule_hint": "模型保存的调度优先于步数设置。请使用 API 的 sigmas 字段更改调度。",
- "imagine.effective_steps": "实际步数",
- "imagine.results_heading": "结果",
- "imagine.advanced.seed": "Seed",
- "imagine.advanced.n": "图像数",
- "imagine.upload_heading": "参考图像",
- "imagine.brand": "oMLX Imagine",
- "imagine.api_key_placeholder": "输入 API 密钥...",
- "imagine.change_api_key": "更换 API 密钥",
"modal.model_settings.moe_expert_offload_resident_75": "常驻 75%",
- "imagine.nav.chat": "聊天",
- "imagine.error.invalid_image_type": "请选择图像文件",
- "imagine.nav.imagine": "Imagine",
- "imagine.image_preview": "图片预览",
- "imagine.timeline_model": "模型",
- "imagine.api_key_prompt": "输入 API 密钥以开始创建图像",
- "imagine.submit.generating": "生成中...",
- "imagine.result.download": "下载",
- "imagine.advanced.output_format": "输出格式",
- "imagine.timeline_prompt": "提示词",
- "imagine.mode.label": "模式",
- "imagine.original_image_alt": "原始图像",
- "imagine.select_model": "图像模型",
- "imagine.welcome_heading": "使用 oMLX Imagine",
- "imagine.advanced.guidance": "Guidance",
- "imagine.prompt_label": "提示词",
- "imagine.clear_results": "清除结果",
"modal.model_settings.moe_expert_offload_resident_50": "常驻 50%",
- "imagine.advanced.negative_prompt": "负面提示词",
- "imagine.timeline_original": "原图",
- "imagine.advanced.size": "尺寸",
- "imagine.no_models_generation": "暂无可用生成模型",
- "imagine.heading": "Imagine",
"modal.model_settings.dflash_single_stream": "仅单流:请求逐个执行。",
- "imagine.welcome_privacy": "所有图像生成均在本地设备上运行。",
- "imagine.error.incorrect_api_key": "API 密钥不正确,请重新输入。",
- "imagine.result_image_alt": "生成的图像",
- "imagine.upload_help": "拖放参考图像,粘贴或浏览。",
- "imagine.subheading": "使用本地图像模型生成和编辑图像",
- "imagine.prompt_placeholder": "描述你想要的图像...",
- "imagine.timeline_edited": "编辑结果",
- "navbar.tab.imagine": "Imagine",
- "imagine.no_models_edit": "暂无可用编辑模型",
- "imagine.mode.generate": "生成",
- "imagine.result.copy": "复制 Data URI",
- "imagine.mode.edit": "编辑",
- "imagine.submit.editing": "编辑中...",
- "imagine.remove_image": "移除图像",
- "imagine.timeline_generated": "生成结果",
- "imagine.api_key_continue": "继续",
- "imagine.submit.generate": "生成",
- "imagine.admin_settings": "管理后台"
+ "chat.image_download": "下载",
+ "chat.image_reuse": "重新用于编辑"
}
diff --git a/apps/omlx-web/omlx_web/routes.py b/apps/omlx-web/omlx_web/routes.py
index 4df07d4453..dc07c9baa5 100644
--- a/apps/omlx-web/omlx_web/routes.py
+++ b/apps/omlx-web/omlx_web/routes.py
@@ -166,12 +166,7 @@ async def chat_page(request: Request, is_admin: bool = Depends(require_admin)):
@router.get("/imagine", response_class=HTMLResponse)
async def imagine_page(request: Request, is_admin: bool = Depends(require_admin)):
- """Render image generation and editing with the host's API key."""
- _sync_locale()
- api_key = _host.main_api_key()
- return templates.TemplateResponse(
- request, "imagine.html", {"api_key": api_key or ""}
- )
+ return RedirectResponse(url="/admin/chat", status_code=307)
@router.get("/static/{path:path}")
diff --git a/apps/omlx-web/omlx_web/static/js/chat-image-tools.js b/apps/omlx-web/omlx_web/static/js/chat-image-tools.js
new file mode 100644
index 0000000000..346c299fb5
--- /dev/null
+++ b/apps/omlx-web/omlx_web/static/js/chat-image-tools.js
@@ -0,0 +1,267 @@
+// SPDX-License-Identifier: Apache-2.0
+const ChatImageTools = (() => {
+ const options = {
+ size: { type: 'string', minLength: 1 },
+ seed: { type: 'integer' },
+ steps: { type: 'integer', minimum: 1 },
+ guidance: { type: 'number' },
+ n: { type: 'integer', minimum: 1 },
+ output_format: { type: 'string', enum: ['png', 'jpeg', 'webp'] },
+ negative_prompt: { type: 'string' },
+ };
+ const registry = {
+ list_image_models: {
+ description: 'List available image models, their explicitly supported tasks and defaults. Discover models before generating or editing. Unknown tasks are not supported.',
+ properties: {},
+ required: [],
+ execute: async (_args, scope) => ({
+ content: JSON.stringify({ models: await discover(scope) }), images: [],
+ }),
+ },
+ generate_image: {
+ description: 'Generate images with an available image model. Omit optional parameters to preserve model defaults. Outputs include image_refs for subsequent edits. Never retry inference automatically.',
+ properties: { model: { type: 'string', minLength: 1 }, prompt: { type: 'string', minLength: 1 }, ...options },
+ required: ['model', 'prompt'],
+ execute: (args, scope) => infer(args, scope, false),
+ },
+ edit_image: {
+ description: 'Edit explicit image_refs from this conversation. Sources may be uploads or prior tool images. Never guess a reference, use a URL/path/base64, or edit an unfinished sibling call. Preserves sources and returns fresh images.',
+ properties: {
+ model: { type: 'string', minLength: 1 }, prompt: { type: 'string', minLength: 1 }, ...options,
+ image_refs: { type: 'array', items: { type: 'string', pattern: '^image:' }, minItems: 1 },
+ image_strength: { type: 'number', minimum: 0, maximum: 1 },
+ },
+ required: ['model', 'prompt', 'image_refs'],
+ execute: (args, scope) => infer(args, scope, true),
+ },
+ };
+
+ function owns(name) {
+ return Object.hasOwn(registry, name);
+ }
+
+ function definitions() {
+ return Object.entries(registry).map(([name, entry]) => ({
+ type: 'function',
+ function: {
+ name, description: entry.description,
+ parameters: {
+ type: 'object', properties: entry.properties,
+ required: entry.required, additionalProperties: false,
+ },
+ },
+ }));
+ }
+
+ function reference(chatId, messageId, kind, slot) {
+ return `image:${encodeURIComponent(chatId)}:${encodeURIComponent(messageId)}:${kind}:${slot}`;
+ }
+
+ function renderReference(href) {
+ if (!href.startsWith('image:')) return false;
+ const escaped = href.replace(/&/g, '&').replace(//g, '>');
+ return `${escaped}`;
+ }
+
+ function sources(chatId, messages) {
+ const found = new Map();
+ for (const msg of messages) {
+ if (!msg.id) continue;
+ if (msg.role === 'user' && Array.isArray(msg.content)) {
+ msg.content.forEach((part, slot) => {
+ if (part.type === 'image_url') {
+ found.set(reference(chatId, msg.id, 'upload', slot), part.image_url?.url || '');
+ }
+ });
+ }
+ if (msg.role === 'tool') {
+ const count = msg._images?.length || msg._imagesStripped || 0;
+ for (let slot = 0; slot < count; slot++) {
+ found.set(reference(chatId, msg.id, 'tool', slot), msg._images?.[slot] ?? '');
+ }
+ }
+ }
+ return found;
+ }
+
+ function project(msg, chatId, vision) {
+ if (msg.role === 'user' && Array.isArray(msg.content)) {
+ return msg.content.flatMap((part, slot) => {
+ if (part.type !== 'image_url') return [part];
+ const ref = reference(chatId, msg.id, 'upload', slot);
+ const note = { type: 'text', text: `[Image ${ref}${part.image_url?.url ? '' : ' unavailable after reload'}]` };
+ return vision && part.image_url?.url ? [note, part] : [note];
+ });
+ }
+ if (msg.role === 'tool' && (msg._images?.length || msg._imagesStripped)) {
+ const count = msg._images?.length || msg._imagesStripped;
+ const refs = Array.from({ length: count }, (_, slot) => reference(chatId, msg.id, 'tool', slot));
+ return `${msg.content || ''}\nImage references: ${refs.join(', ')}${msg._images?.length ? '' : ' (unavailable after reload)'}`;
+ }
+ return msg.content;
+ }
+
+ function rebaseReferences(messages, fromChatId, toChatId) {
+ const prefix = `image:${encodeURIComponent(fromChatId)}:`;
+ const refs = new Map([...sources(fromChatId, messages).keys()].map(ref => [
+ ref, `image:${encodeURIComponent(toChatId)}:${ref.slice(prefix.length)}`,
+ ]));
+ const rebase = text => text.replace(
+ /image:[^:\s]+:[^:\s]+:(?:upload|tool):\d+/g,
+ ref => refs.get(ref) || ref,
+ );
+ for (const msg of messages) {
+ for (const field of ['content', 'reasoning_content', '_thinking']) {
+ if (typeof msg[field] === 'string') msg[field] = rebase(msg[field]);
+ }
+ if (Array.isArray(msg.content)) {
+ for (const part of msg.content) {
+ if (part.type === 'text') part.text = rebase(part.text);
+ }
+ }
+ for (const tc of (msg.tool_calls || [])) {
+ tc.function.arguments = rebase(tc.function.arguments);
+ }
+ }
+ }
+
+ async function readJson(url, init, scope) {
+ scope.signal.throwIfAborted();
+ const response = await fetch(url, { ...init, signal: scope.signal });
+ let data;
+ try {
+ data = await response.json();
+ } catch (error) {
+ scope.signal.throwIfAborted();
+ throw new Error(`${url}: ${error.message}`);
+ }
+ scope.signal.throwIfAborted();
+ if (!response.ok) {
+ const detail = data.error?.message || data.detail || `HTTP ${response.status}`;
+ throw new Error(`${url}: ${typeof detail === 'string' ? detail : JSON.stringify(detail)}`);
+ }
+ return data;
+ }
+
+ async function discover(scope) {
+ const [publicData, statusData] = await Promise.all([
+ readJson('/v1/models', { headers: scope.headers }, scope),
+ readJson('/v1/models/status', { headers: scope.headers }, scope),
+ ]);
+ if (!Array.isArray(publicData.data) || !Array.isArray(statusData.models)) {
+ throw new Error('Invalid image model discovery response');
+ }
+ const canonical = new Map();
+ for (const model of statusData.models) {
+ if (typeof model.id === 'string') canonical.set(model.id, model);
+ }
+ const lookup = new Map(canonical);
+ for (const model of canonical.values()) {
+ if (model.model_alias && !lookup.has(model.model_alias)) {
+ lookup.set(model.model_alias, model);
+ }
+ }
+ const result = new Map();
+ for (const publicModel of publicData.data) {
+ const model = lookup.get(publicModel.id);
+ if (!model || (model.model_type !== 'image' && model.engine_type !== 'image')) continue;
+ const metadata = model.image_metadata || {};
+ const tasks = Array.isArray(model.tasks) && model.tasks.length ? model.tasks : metadata.tasks;
+ let entry = result.get(model.id);
+ if (!entry) {
+ const defaults = {};
+ for (const [key, value] of Object.entries(metadata)) {
+ if (key.startsWith('default_')) defaults[key] = value;
+ }
+ entry = {
+ id: model.id,
+ aliases: [],
+ tasks: [...new Set((Array.isArray(tasks) ? tasks : []).filter(task => task === 'generation' || task === 'edit'))],
+ defaults,
+ };
+ result.set(model.id, entry);
+ }
+ if (publicModel.id !== model.id && !entry.aliases.includes(publicModel.id)) entry.aliases.push(publicModel.id);
+ }
+ return [...result.values()];
+ }
+
+ function sourceBlob(ref, scope) {
+ const images = sources(scope.chatId, scope.messages);
+ if (!images.has(ref)) throw new Error(`Image source ${ref} is not in this chat's selected history`);
+ const url = images.get(ref);
+ if (!url) throw new Error(`Image source ${ref} is unavailable after reload or export`);
+ const match = /^data:(image\/[a-zA-Z0-9.+-]+);base64,([A-Za-z0-9+/=\r\n]+)$/.exec(url);
+ if (!match) throw new Error(`Image source ${ref} has no reusable inline image bytes`);
+ let binary;
+ try {
+ binary = atob(match[2]);
+ } catch {
+ throw new Error(`Image source ${ref} contains invalid inline image bytes`);
+ }
+ return new Blob([Uint8Array.from(binary, char => char.charCodeAt(0))], { type: match[1] });
+ }
+
+ async function infer(args, scope, edit) {
+ const body = { model: args.model, prompt: args.prompt, response_format: 'b64_json' };
+ for (const key of Object.keys(options)) {
+ if (args[key] !== undefined) body[key] = args[key];
+ }
+ let init;
+ if (edit) {
+ const form = new FormData();
+ for (const [key, value] of Object.entries(body)) form.append(key, String(value));
+ if (args.image_strength !== undefined) form.append('image_strength', String(args.image_strength));
+ args.image_refs.forEach((ref, index) => form.append('image', sourceBlob(ref, scope), `source-${index}`));
+ init = { method: 'POST', headers: scope.headers, body: form };
+ } else {
+ init = { method: 'POST', headers: { ...scope.headers, 'Content-Type': 'application/json' }, body: JSON.stringify(body) };
+ }
+ const data = await readJson(edit ? '/v1/images/edits' : '/v1/images/generations', init, scope);
+ if (!Array.isArray(data.data) || !data.data.length) throw new Error('Image inference returned no images');
+ const images = data.data.map(item => {
+ if (typeof item.b64_json !== 'string' || !item.b64_json) throw new Error('Image inference returned no inline image bytes');
+ const format = item.output_format || data.output_format || args.output_format || 'png';
+ if (!['png', 'jpeg', 'webp'].includes(format)) throw new Error('Image inference returned an unsupported format');
+ return `data:image/${format};base64,${item.b64_json}`;
+ });
+ const outputs = data.data.map((item, slot) => {
+ const output = { image_ref: reference(scope.chatId, scope.resultMessageId, 'tool', slot) };
+ for (const key of ['revised_prompt', 'steps', 'guidance', 'size', 'seed', 'output_format']) {
+ if (item[key] !== undefined) output[key] = item[key];
+ }
+ return output;
+ });
+ return { content: JSON.stringify({ model: args.model, outputs }), images };
+ }
+
+ async function execute(name, args, scope) {
+ if (!owns(name)) throw new Error(`Unknown image tool ${name}`);
+ const entry = registry[name];
+ if (!args || typeof args !== 'object' || Array.isArray(args)) throw new Error('Image tool arguments must be an object');
+ for (const key of entry.required) {
+ if (args[key] === undefined) throw new Error(`Image tool requires ${key}`);
+ }
+ for (const [key, value] of Object.entries(args)) {
+ if (!Object.hasOwn(entry.properties, key)) throw new Error(`Unsupported image option ${key}`);
+ const rule = entry.properties[key];
+ let valid;
+ if (rule.type === 'array') {
+ valid = Array.isArray(value) && value.length > 0
+ && value.every(ref => typeof ref === 'string' && ref.startsWith('image:'));
+ } else if (rule.type === 'integer') {
+ valid = Number.isInteger(value);
+ } else if (rule.type === 'number') {
+ valid = typeof value === 'number' && Number.isFinite(value);
+ } else {
+ valid = typeof value === 'string' && (!rule.minLength || value.trim().length >= rule.minLength);
+ }
+ if (!valid || (rule.minimum !== undefined && value < rule.minimum)
+ || (rule.maximum !== undefined && value > rule.maximum)
+ || (rule.enum && !rule.enum.includes(value))) throw new Error(`Invalid image option ${key}`);
+ }
+ return entry.execute(args, scope);
+ }
+
+ return { owns, definitions, reference, renderReference, sources, project, rebaseReferences, execute, discover };
+})();
diff --git a/apps/omlx-web/omlx_web/templates/chat.html b/apps/omlx-web/omlx_web/templates/chat.html
index 24a68cf078..d5f8e3a479 100644
--- a/apps/omlx-web/omlx_web/templates/chat.html
+++ b/apps/omlx-web/omlx_web/templates/chat.html
@@ -1375,11 +1375,6 @@ {{ t('login.login.label_api_key') }}
-
-
- {{ t('navbar.tab.imagine') }}
-
@@ -1500,7 +1495,7 @@ {{ t('chat.welcome_heading') }}
-
@@ -1622,7 +1617,7 @@ {{ t('chat.welcome_heading') }}
+ x-html="renderMarkdown(getTextContent(msg.content))">
@@ -497,11 +490,6 @@
{{ t('status.layout.customize') }}
-
-
- {{ t('navbar.tab.imagine') }}
-
- :root {
- --bg-primary: #ffffff;
- --bg-secondary: #f8fafc;
- --bg-tertiary: #f1f5f9;
- --text-primary: #0f172a;
- --text-secondary: #475569;
- --text-tertiary: #64748b;
- --text-muted: #94a3b8;
- --border-faint: #e2e8f0;
- --border-normal: #cbd5e1;
- --btn-primary: #171717;
- --btn-primary-hover: #27272a;
- --btn-primary-text: #ffffff;
- --text-danger: #ef4444;
- --bg-danger-hover: rgba(239, 68, 68, 0.1);
- }
-
- [data-theme="dark"] {
- --bg-primary: #1d1d20;
- --bg-secondary: #252529;
- --bg-tertiary: #2d2d32;
- --text-primary: #efefef;
- --text-secondary: #a1a1aa;
- --text-tertiary: #71717a;
- --text-muted: #52525b;
- --border-faint: #3f3f46;
- --border-normal: #52525b;
- --btn-primary: #e5e5e5;
- --btn-primary-hover: #d4d4d4;
- --btn-primary-text: #18181b;
- --text-danger: #f87171;
- --bg-danger-hover: rgba(239, 68, 68, 0.2);
- }
-
- html,
- body {
- height: 100%;
- overflow: hidden;
- background: var(--bg-primary) !important;
- color: var(--text-primary) !important;
- }
-
- .imagine-shell {
- height: 100vh;
- height: 100dvh;
- background: var(--bg-primary);
- color: var(--text-primary);
- }
-
- .bg-surface { background: var(--bg-primary); }
- .bg-surface-alt { background: var(--bg-secondary); }
- .bg-surface-muted { background: var(--bg-tertiary); }
- .text-fg { color: var(--text-primary); }
- .text-fg-secondary { color: var(--text-secondary); }
- .text-fg-tertiary { color: var(--text-tertiary); }
- .border-line { border-color: var(--border-faint); }
- .border-line-strong { border-color: var(--border-normal); }
-
- .custom-scrollbar::-webkit-scrollbar {
- width: 6px;
- }
-
- .custom-scrollbar::-webkit-scrollbar-track {
- background: transparent;
- }
-
- .custom-scrollbar::-webkit-scrollbar-thumb {
- background: var(--border-normal);
- border-radius: 3px;
- }
-
- .drop-zone.drag-over {
- border-color: var(--btn-primary);
- background: var(--bg-tertiary);
- }
-
- .api-key-modal-card {
- max-width: 400px;
- width: 90%;
- }
-
- .api-key-modal-overlay {
- z-index: 1000;
- }
-
- .imagine-sidebar {
- width: 300px;
- min-width: 300px;
- }
-
- .imagine-brand-logo {
- width: 30px;
- height: 30px;
- }
-
- .imagine-empty-state {
- height: calc(100dvh - 8rem);
- }
-
- .imagine-welcome-logo {
- width: 60px;
- height: 60px;
- }
-
- .imagine-edit-comparison {
- grid-template-columns: minmax(0, 0.9fr) minmax(0, 1.1fr);
- }
-
- .imagine-result-grid {
- grid-template-columns: minmax(0, 1fr);
- }
-
- .imagine-edit-result-grid {
- grid-template-columns: minmax(0, 1fr);
- }
-
- @media (min-width: 768px) {
- .imagine-result-grid {
- grid-template-columns: repeat(2, minmax(0, 1fr));
- }
- }
-
- @media (min-width: 1280px) {
- .imagine-result-grid {
- grid-template-columns: repeat(3, minmax(0, 1fr));
- }
-
- .imagine-edit-result-grid {
- grid-template-columns: repeat(2, minmax(0, 1fr));
- }
- }
-
- @media (max-width: 1023px) {
- .imagine-edit-comparison {
- grid-template-columns: minmax(0, 1fr);
- }
- }
-
- .image-modal {
- position: fixed;
- inset: 0;
- background: rgba(0, 0, 0, 0.9);
- display: flex;
- align-items: center;
- justify-content: center;
- z-index: 9999;
- cursor: zoom-out;
- }
-
- .image-modal img {
- max-width: 90%;
- max-height: 90%;
- object-fit: contain;
- border-radius: 8px;
- box-shadow: 0 4px 24px rgba(0, 0, 0, 0.5);
- }
-
- .image-modal-close {
- position: absolute;
- top: 20px;
- right: 20px;
- width: 40px;
- height: 40px;
- background: rgba(255, 255, 255, 0.1);
- border: none;
- border-radius: 50%;
- color: white;
- cursor: pointer;
- display: flex;
- align-items: center;
- justify-content: center;
- }
-
-{% endblock %}
-
-{% block content %}
-
-
-
-
-
-
{{ t('login.login.label_api_key') }}
-
{{ t('imagine.api_key_prompt') }}
-
-
- {{ t('imagine.api_key_continue') }}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-{% endblock %}
-
-{% block scripts %}
-
-{% endblock %}
diff --git a/apps/omlx-web/tests/chat_image_tools.test.cjs b/apps/omlx-web/tests/chat_image_tools.test.cjs
new file mode 100644
index 0000000000..b25c3b5d0f
--- /dev/null
+++ b/apps/omlx-web/tests/chat_image_tools.test.cjs
@@ -0,0 +1,700 @@
+// SPDX-License-Identifier: Apache-2.0
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const vm = require('node:vm');
+const { test } = require('node:test');
+
+const web = path.join(__dirname, '../omlx_web');
+const template = fs.readFileSync(path.join(web, 'templates/chat.html'), 'utf8');
+const store = new Map([['omlx_chat_api_key', 'test-key']]);
+global.localStorage = {
+ getItem: key => store.get(key) || null,
+ setItem: (key, value) => store.set(key, String(value)),
+ removeItem: key => store.delete(key),
+};
+global.window = { innerWidth: 1200, t: key => key, matchMedia: () => ({ matches: false }) };
+global.document = { getElementById: () => null };
+const markdownOptions = [];
+global.marked = {
+ use: options => markdownOptions.push(options),
+ parse: text => `${text}
`,
+};
+global.DOMPurify = { sanitize: html => html };
+const images = vm.runInThisContext(
+ fs.readFileSync(path.join(web, 'static/js/chat-image-tools.js'), 'utf8') + '\nChatImageTools;'
+);
+const script = template.split('{% block scripts %}')[1].match(/", 1)[0]
- source = source.replace("{{ api_key | tojson }}", '""')
- harness = (
- r"""
-const assert = require('node:assert/strict');
-global.localStorage = {getItem: () => null};
-global.window = {t: key => key};
-"""
- + source
- + r"""
-(async () => {
- const app = imagineApp();
- app.apiKeySet = true;
- app.apiKeyInput = 'test';
- app.mergeStatusMetadata([
- {id: 'raw', model_alias: 'turbo', model_type: 'image', engine_type: 'image',
- tasks: ['generation', 'edit'],
- image_metadata: {uses_checkpoint_sigmas: true, checkpoint_steps: 8}},
- {id: 'chat', model_type: 'llm', tasks: []},
- {id: 'collision', model_alias: 'chat', model_type: 'image', tasks: ['edit']}
- ]);
- app.currentModel = 'turbo';
- app.availableModels = [{id: 'turbo'}, {id: 'chat'}];
- assert.equal(app.currentRecipe().checkpoint_steps, 8);
- assert.equal(app.modelTypeMap.chat, 'llm');
- assert.deepEqual(app.modeModels(), [{id: 'turbo'}]);
- app.prompt = 'a fox';
- assert.equal(app.commonPayload().steps, undefined);
- assert.equal(app.commonPayload().guidance, undefined);
- app.settings.steps = '30';
- let generation;
- global.fetch = async (url, options) => {
- assert.equal(url, '/v1/images/generations');
- generation = JSON.parse(options.body);
- return {ok: true, json: async () => ({data: [
- {b64_json: 'AA==', output_format: 'png', steps: 8, guidance: 1, size: '4x2'}
- ]})};
- };
- await app.submit();
- assert.equal(generation.steps, 30);
- assert.equal(generation.sigmas, undefined);
- assert.equal(app.results[0].images[0].steps, 8);
- assert.equal(app.results[0].images[0].guidance, 1);
- app.setMode('edit');
- app.uploadImages = [
- {id: 'one', file: new File(['first'], 'first.png'), preview: 'data:first'},
- {id: 'two', file: new File(['second'], 'second.png'), preview: 'data:second'}
- ];
- global.fetch = async (url, options) => {
- assert.equal(url, '/v1/images/edits');
- assert.deepEqual(options.body.getAll('image').map(file => file.name),
- ['first.png', 'second.png']);
- assert.equal(options.body.get('sigmas'), null);
- assert.equal(options.body.get('image_strength'), null);
- assert.equal(options.body.get('mask'), null);
- return {ok: true, json: async () => ({data: [
- {b64_json: 'AA==', steps: 8, output_format: 'png'}
- ]})};
- };
- await app.submit();
- assert.equal(app.results[0].mode, 'edit');
- assert.equal(app.results[0].originals.length, 2);
- assert.equal(app.results[0].images[0].steps, 8);
-})().catch(error => {console.error(error); process.exitCode = 1;});
-"""
- )
- result = subprocess.run(
- [node], input=harness, text=True, capture_output=True, timeout=30
- )
- assert result.returncode == 0, result.stdout + result.stderr
-
-
-def _imagine_model_selectable(model_type, engine_type=""):
- """Python equivalent of the imagine.html image model filter."""
- t = (model_type or "").lower()
- e = (engine_type or "").lower()
- return t == "image" or e == "image"
-
-
-def _normalize_tasks(tasks):
- if not isinstance(tasks, list):
- return []
- return [str(task).lower() for task in tasks if task]
-
-
-def _extract_tasks(model):
- direct_tasks = _normalize_tasks(model.get("tasks"))
- if direct_tasks:
- return direct_tasks
- return _normalize_tasks((model.get("image_metadata") or {}).get("tasks"))
-
-
-def _status_metadata_maps(models):
- """Python equivalent of the imagine.html /v1/models/status metadata mapping."""
- model_type_map = {}
- model_engine_type_map = {}
- model_task_map = {}
- for model in models:
- model_id = model.get("id")
- if model_id:
- model_type_map[model_id] = model.get("model_type") or "llm"
- model_engine_type_map[model_id] = model.get("engine_type") or ""
- model_task_map[model_id] = _extract_tasks(model)
- for model in models:
- model_id = model.get("model_alias")
- if model_id and model_id not in model_type_map:
- model_type_map[model_id] = model.get("model_type") or "llm"
- model_engine_type_map[model_id] = model.get("engine_type") or ""
- model_task_map[model_id] = _extract_tasks(model)
- return model_type_map, model_engine_type_map, model_task_map
-
-
-def _supports_task(tasks, task):
- """Strict task metadata policy approved for the Imagine UI."""
- return task in (tasks or [])
-
-
-def test_imagine_dropdown_filter_keeps_image_model_types():
- assert _imagine_model_selectable("image")
- assert _imagine_model_selectable("llm", engine_type="image")
-
-
-def test_imagine_dropdown_filter_excludes_non_image_model_types():
- assert not _imagine_model_selectable("llm", engine_type="batched")
- assert not _imagine_model_selectable("vlm", engine_type="vlm")
- assert not _imagine_model_selectable("embedding")
- assert not _imagine_model_selectable("reranker")
- assert not _imagine_model_selectable("audio_transcription")
-
-
-def test_imagine_task_filter_uses_strict_generation_and_edit_metadata():
- _, _, task_map = _status_metadata_maps(
- [
- {
- "id": "generate-image",
- "model_type": "image",
- "engine_type": "image",
- "tasks": ["generation"],
- },
- {
- "id": "edit-image",
- "model_type": "image",
- "engine_type": "image",
- "tasks": [],
- "image_metadata": {"tasks": ["edit"]},
- },
- {
- "id": "unknown-image",
- "model_type": "image",
- "engine_type": "image",
- },
- ]
- )
-
- assert _supports_task(task_map["generate-image"], "generation")
- assert not _supports_task(task_map["generate-image"], "edit")
- assert _supports_task(task_map["edit-image"], "edit")
- assert not _supports_task(task_map["edit-image"], "generation")
- assert not _supports_task(task_map["unknown-image"], "generation")
- assert not _supports_task(task_map["unknown-image"], "edit")
-
-
-def test_imagine_status_metadata_maps_active_aliases_without_collisions():
- model_type_map, engine_type_map, task_map = _status_metadata_maps(
- [
- {
- "id": "chat-model",
- "model_type": "llm",
- "engine_type": "batched",
- },
- {
- "id": "raw-image-model",
- "model_alias": "friendly-image-name",
- "model_type": "image",
- "engine_type": "image",
- "tasks": ["generation"],
- },
- {
- "id": "colliding-image",
- "model_alias": "chat-model",
- "model_type": "image",
- "engine_type": "image",
- "tasks": ["edit"],
- },
- ]
- )
-
- assert _imagine_model_selectable(
- model_type_map["friendly-image-name"],
- engine_type_map["friendly-image-name"],
- )
- assert task_map["friendly-image-name"] == ["generation"]
- assert model_type_map["chat-model"] == "llm"
- assert engine_type_map["chat-model"] == "batched"
-
-
-def test_imagine_route_and_nav_are_registered():
- routes_source = ROUTES.read_text()
- nav_source = NAVBAR_TEMPLATE.read_text()
- chat_source = CHAT_TEMPLATE.read_text()
-
- assert '@router.get("/imagine", response_class=HTMLResponse)' in routes_source
- assert '"imagine.html"' in routes_source
- assert "api_key" in routes_source
- assert 'href="/admin/imagine"' in nav_source
- assert "navbar.tab.imagine" in nav_source
- assert 'href="/admin/imagine"' in chat_source
- assert "navbar.tab.imagine" in chat_source
-
-
-def test_imagine_template_wires_image_endpoints_and_safe_fields():
- source = IMAGINE_TEMPLATE.read_text()
-
- assert "fetch('/v1/models'" in source
- assert "fetch('/v1/models/status'" in source
- assert "fetch('/v1/images/generations'" in source
- assert "fetch('/v1/images/edits'" in source
- assert "response_format: 'b64_json'" in source
- assert "form.append('image'" in source
- assert "form.append('mask'" not in source
- assert "lora_paths" not in source
- assert "lora_scales" not in source
- for field in (
- "seed",
- "steps",
- "guidance",
- "size",
- "n",
- "output_format",
- "negative_prompt",
- ):
- assert field in source
-
-
-def test_imagine_template_keeps_results_session_only():
- source = IMAGINE_TEMPLATE.read_text()
-
- assert "this.results =" in source
- assert "localStorage.setItem('omlx_imagine" not in source
- assert "localStorage.getItem('omlx_imagine" not in source
-
-
-def test_imagine_template_keeps_edit_attempt_timeline_with_originals():
- source = IMAGINE_TEMPLATE.read_text()
-
- assert "this.results = [attempt, ...this.results]" in source
- assert "attempt.originals" in source
- assert "requestMode === 'edit'" in source
- assert "mode: requestMode" in source
- assert "originalSnapshot" in source
- assert "pendingOriginalPreviews" in source
- assert "image.preview" in source
- assert "previewShouldStayAlive" in source
- assert "clearResults()" in source
-
-
-def test_imagine_template_does_not_depend_on_unbuilt_arbitrary_tailwind_classes():
- source = IMAGINE_TEMPLATE.read_text()
-
- assert "imagine-sidebar" in source
- assert "imagine-edit-comparison" in source
- assert "imagine-result-grid" in source
- assert "w-[" not in source
- assert "min-w-[" not in source
- assert "max-w-[" not in source
- assert "h-[" not in source
- assert "z-[" not in source
- assert "grid-cols-[" not in source
- assert "md:grid-cols" not in source
- assert "xl:grid-cols" not in source
-
-
-def test_imagine_template_refilters_model_on_mode_change():
- source = IMAGINE_TEMPLATE.read_text()
-
- assert "setMode(mode)" in source
- assert "this.ensureValidCurrentModel();" in source
- assert "modeModels()" in source
- assert "supportsTask(model.id, task)" in source
-
-
-def test_i18n_imagine_keys_present_in_every_language_file():
- language_files = list(I18N_DIR.glob("*.json"))
- assert language_files, "Imagine translations must be packaged"
- for lang_file in language_files:
- translations = json.loads(lang_file.read_text())
- for key in REQUIRED_IMAGINE_KEYS:
- assert key in translations, f"Missing key '{key}' in {lang_file.name}"
- assert translations[key], f"Empty value for '{key}' in {lang_file.name}"
diff --git a/tests/test_engine_pool.py b/tests/test_engine_pool.py
index 77881e2e6c..43db6034c9 100644
--- a/tests/test_engine_pool.py
+++ b/tests/test_engine_pool.py
@@ -653,6 +653,28 @@ def test_image_engine_missing_mlx_vlm_raises_model_loading_error(
class TestEnginePoolStatus:
"""Tests for EnginePool status reporting."""
+ @pytest.mark.parametrize(
+ "config_model_type,loaded_tool_support,expected",
+ [
+ ("llama", None, True),
+ ("diffusion_gemma", None, False),
+ ("diffusion_gemma", False, False),
+ ("diffusion_gemma", True, True),
+ ],
+ )
+ def test_status_reports_diffusion_tool_support(
+ self, small_mock_model_dir, config_model_type, loaded_tool_support, expected
+ ):
+ pool = _make_pool()
+ pool.discover_models(str(small_mock_model_dir))
+ entry = pool.get_entry("model-a")
+ entry.config_model_type = config_model_type
+ if loaded_tool_support is not None:
+ entry.engine = SimpleNamespace(supports_tool_calling=loaded_tool_support)
+
+ model = next(m for m in pool.get_status()["models"] if m["id"] == "model-a")
+ assert model["supports_tool_calling"] is expected
+
def test_get_status(self, small_mock_model_dir):
"""Test get_status returns correct information."""
pool = _make_pool(ceiling=10 * 1024**3)
From b002c98b8772e913507222fb1c31720ee7fd1a5e Mon Sep 17 00:00:00 2001
From: Mike Wallio
Date: Thu, 5 Nov 2026 16:04:25 -0500
Subject: [PATCH 10/24] test: simplify duplicated setup and exercise production
behavior
Parametrize repeated cases, replace browser-logic replicas with production JavaScript tests, and scope shared state through fixtures.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
---
apps/omlx-web/tests/chat_image_tools.test.cjs | 192 +++++++
apps/omlx-web/tests/test_admin_auth_ui.py | 245 ++++-----
apps/omlx-web/tests/test_chat_image_upload.py | 181 +------
apps/omlx-web/tests/test_chat_tool_call.py | 502 ++----------------
apps/omlx-web/tests/test_chat_ui_overhaul.py | 83 +--
tests/test_admin_api_key.py | 108 +---
tests/test_anthropic_adapter.py | 54 +-
tests/test_audio_discovery.py | 78 ++-
tests/test_audio_sts.py | 43 +-
tests/test_audio_stt.py | 47 +-
tests/test_cli.py | 251 +++------
tests/test_cluster_interpreter_parity.py | 44 +-
tests/test_cluster_tensor_parallel.py | 46 +-
tests/test_context_window.py | 130 ++---
tests/test_exceptions.py | 112 ++--
tests/test_hf_downloader.py | 77 +--
tests/test_hybrid_cache.py | 53 +-
tests/test_image_utils.py | 62 +--
tests/test_mbpp_extract_code.py | 49 +-
tests/test_mcp_config.py | 64 +--
tests/test_openai_adapter.py | 139 ++---
tests/test_openai_models.py | 103 ++--
tests/test_output_collector.py | 63 +--
tests/test_request.py | 70 +--
tests/test_reranker_vl.py | 53 +-
tests/test_scheduler_chunked_prefill.py | 53 +-
tests/test_shared_models.py | 89 ++--
tests/test_store_cache_gate.py | 38 +-
tests/test_thinking.py | 123 ++---
tests/test_thinking_toggle.py | 14 +-
tests/test_utils_hardware.py | 103 ++--
tests/test_utils_tokenizer.py | 150 +++---
32 files changed, 1118 insertions(+), 2301 deletions(-)
diff --git a/apps/omlx-web/tests/chat_image_tools.test.cjs b/apps/omlx-web/tests/chat_image_tools.test.cjs
index b25c3b5d0f..2e971210a4 100644
--- a/apps/omlx-web/tests/chat_image_tools.test.cjs
+++ b/apps/omlx-web/tests/chat_image_tools.test.cjs
@@ -698,3 +698,195 @@ test('malformed reserved tools never fall through to MCP and API errors retain t
assert.match(result.content, /\/v1\/images\/generations: Model lacks generation/);
assert.equal(requests, 1);
});
+
+for (const [label, content, urls, text] of [
+ ['multiple images', [
+ { type: 'image_url', image_url: { url: png } },
+ { type: 'image_url', image_url: { url: 'data:image/jpeg;base64,bmV3' } },
+ { type: 'text', text: 'What are these?' },
+ ], [png, 'data:image/jpeg;base64,bmV3'], 'What are these?'],
+ ['text only', 'Hello', [], 'Hello'],
+ ['image only', [{ type: 'image_url', image_url: { url: png } }], [png], ''],
+ ['stripped image', [
+ { type: 'image_url', image_url: { url: '' } },
+ { type: 'text', text: 'Old text' },
+ ], [], 'Old text'],
+]) {
+ test(`editing ${label} preserves available images and replaces the text`, async () => {
+ const app = appFixture([{ id: 'original', role: 'user', content }]);
+ app.currentChatId = 'owner';
+ app.messages = app.chatSessions.owner.messages;
+ const streams = [];
+ app.streamResponse = async context => streams.push(context);
+
+ assert.deepEqual(app.getImageUrls(content), urls);
+ assert.equal(app.getTextContent(content), text);
+ const stored = app.messageForStorage(app.messages[0]);
+ assert.deepEqual(app.getImageUrls(stored.content), []);
+ assert.equal(app.getTextContent(stored.content), text);
+ assert.deepEqual(app.getImageUrls(content), urls);
+
+ app.startEdit(0);
+ assert.deepEqual(app.editImages, urls);
+ assert.equal(app.editContent, text);
+ app.editContent = ' New description ';
+ await app.saveEdit(0);
+
+ const edited = app.messages[0];
+ assert.equal(edited.role, 'user');
+ assert.deepEqual(edited.content, urls.length ? [
+ ...urls.map(url => ({ type: 'image_url', image_url: { url } })),
+ { type: 'text', text: 'New description' },
+ ] : 'New description');
+ assert.equal(app.editingIndex, null);
+ assert.deepEqual(app.editImages, []);
+ assert.equal(streams.length, 1);
+ assert.equal(streams[0].chatId, 'owner');
+ });
+}
+
+for (const [value, expected] of [[null, 10], ['bad', 10], [0, 1], [150, 100], [25, 25]]) {
+ test(`tool round limit normalizes ${JSON.stringify(value)} to ${expected}`, () => {
+ assert.equal(appFixture().normalizeMaxToolRounds(value), expected);
+ });
+}
+
+for (const finalAnswer of [true, false]) {
+ test(`the last permitted tool round ${finalAnswer ? 'allows a final answer' : 'blocks another tool execution'}`, async () => {
+ const app = appFixture();
+ app.chatSettings.maxToolRounds = 1;
+ let completions = 0;
+ let executions = 0;
+ global.fetch = async url => {
+ if (url === '/v1/chat/completions') {
+ completions++;
+ return completions === 1 || !finalAnswer
+ ? sse([call('search', { query: 'hello' })]) : sse(null);
+ }
+ assert.equal(url, '/v1/mcp/execute');
+ executions++;
+ return json({ content: 'Search result' });
+ };
+ await app.streamResponse({ chatId: 'owner', model: 'text', systemPrompt: '' });
+ assert.equal(completions, 2);
+ assert.equal(executions, 1);
+ const messages = app.chatSessions.owner.messages;
+ assert.equal(messages.at(-1).content, finalAnswer ? 'Done' : 'chat.error.max_tool_rounds');
+ const chain = app.getApiTurnMessages(messages);
+ assert.equal(chain.find(msg => msg.tool_calls)?._ui, false);
+ assert.equal(chain.find(msg => msg.role === 'tool').tool_call_id, 'search');
+ assert.equal(app.getStreamSession('owner').isStreaming, false);
+ });
+}
+
+test('streamed parallel tool calls assemble fragmented names and arguments before dispatch', async () => {
+ const app = appFixture();
+ const executed = [];
+ let completions = 0;
+ global.fetch = async (url, init) => {
+ if (url === '/v1/chat/completions') {
+ if (completions++) return sse(null);
+ const deltas = [
+ [{ id: 'first', function: { name: 'sea' } }],
+ [{ index: 1, id: 'second', function: { name: 'extract', arguments: '{"urls":' } }],
+ [{ index: 0, function: { name: 'rch', arguments: '{"q":' } }],
+ [{ index: 1, function: { arguments: '["https://example.com"]}' } }],
+ [{ index: 0, function: { arguments: '"hello"}' } }],
+ ];
+ return new Response(deltas.map(tool_calls => `data: ${JSON.stringify({
+ choices: [{ delta: { tool_calls } }],
+ })}\n\n`).join('') + 'data: [DONE]\n\n');
+ }
+ assert.equal(url, '/v1/mcp/execute');
+ executed.push(JSON.parse(init.body));
+ return json({ content: 'Result' });
+ };
+ await app.streamResponse({ chatId: 'owner', model: 'text', systemPrompt: '' });
+ assert.deepEqual(executed, [
+ { tool_name: 'search', arguments: { q: 'hello' } },
+ { tool_name: 'extract', arguments: { urls: ['https://example.com'] } },
+ ]);
+ assert.deepEqual(app.chatSessions.owner.messages.filter(msg => msg.role === 'tool')
+ .map(msg => msg.tool_call_id), ['first', 'second']);
+});
+
+for (const [provider, flag] of [
+ ['brave', 'braveKeySet'], ['searxng', 'searxngUrlSet'],
+ ['ddgs_custom', 'ddgsBackendsSet'], ['ddgs', null], ['duckduckgo', null],
+]) {
+ for (const enabled of [false, true]) {
+ for (const configured of flag ? [false, true] : [true]) {
+ test(`web tools: ${provider}, enabled=${enabled}, configured=${configured}`, () => {
+ const app = appFixture();
+ app.chatSettings.webSearchEnabled = enabled;
+ app.webSearchSettings = { provider };
+
+ if (flag) app.webSearchSettings[flag] = configured;
+
+ app.mcpTools = ['web_search', 'fetch_url', 'other']
+ .map(name => ({ type: 'function', function: { name, description: 'MCP' } }));
+ const active = enabled && configured;
+ assert.equal(app.webSearchToolsActive(), active);
+ assert.equal(app.builtinWebRoute('web_search'), active ? '/v1/web/search' : null);
+ assert.equal(app.builtinWebRoute('fetch_url'), active ? '/v1/web/fetch' : null);
+ assert.equal(app.builtinWebRoute('other'), null);
+ const tools = app.activeTools().filter(tool => !images.owns(tool.function.name));
+ assert.deepEqual(tools.map(tool => tool.function.name), ['web_search', 'fetch_url', 'other']);
+ assert.equal(tools[0].function.description === 'MCP', !active);
+ });
+ }
+ }
+}
+
+for (const [label, turn, activeId, expected] of [
+ ['hidden tool round', [
+ { id: 'round', role: 'assistant', _ui: false, tool_calls: [{}] },
+ { id: 'result', role: 'tool', _ui: false },
+ { id: 'final', role: 'assistant', content: 'Answer' },
+ ], 'final', ['round', 'result', 'final']],
+ ['visible segment boundary', [
+ { id: 'round', role: 'assistant', tool_calls: [{}] },
+ { id: 'result', role: 'tool', _ui: false },
+ { id: 'final', role: 'assistant', content: 'Answer' },
+ ], 'final', ['result', 'final']],
+ ['unfinished tool round', [
+ { id: 'round', role: 'assistant', _ui: false, tool_calls: [{}] },
+ { id: 'result', role: 'tool', _ui: false },
+ ], null, ['round', 'result']],
+]) {
+ test(`variant selection retains the expected ${label} chain`, () => {
+ assert.deepEqual(appFixture().getActiveVariantChain(turn, activeId).map(msg => msg.id), expected);
+ });
+}
+
+test('API message projection omits UI indicators but keeps tool calls and results', () => {
+ const app = appFixture();
+ const toolCalls = [call('search', { q: 'hello' }, 'tc-1')];
+ const messages = [
+ { id: 'user', role: 'user', content: 'Search for X' },
+ { role: 'tool_call', content: 'Searching', _ui: true },
+ { id: 'round', role: 'assistant', content: null, tool_calls: toolCalls, _ui: false },
+ { id: 'result', role: 'tool', tool_call_id: 'tc-1', content: 'Result', _ui: false },
+ { role: 'tool_call', content: 'Failed', _error: true, _ui: true },
+ { id: 'final', role: 'assistant', content: 'Answer' },
+ ];
+ const body = app.buildChatCompletionBody(messages, { chatId: 'owner', model: 'text', systemPrompt: '' });
+
+ assert.deepEqual(body.messages, [
+ { role: 'user', content: 'Search for X' },
+ { role: 'assistant', content: null, tool_calls: toolCalls },
+ { role: 'tool', content: 'Result', tool_call_id: 'tc-1' },
+ { role: 'assistant', content: 'Answer' },
+ ]);
+});
+
+for (const status of [200, 503]) {
+ test(`MCP HTTP ${status} produces a named tool result`, async () => {
+ global.fetch = async () => status === 200
+ ? json({ content: 'Search result' }) : new Response('', { status });
+ const result = await appFixture().executeChatTool(call('search', {}), controllerScope());
+ assert.equal(result.toolName, 'search');
+ assert.equal(result.error, status !== 200);
+ assert.equal(result.content, status === 200 ? 'Search result' : 'Error: search: HTTP 503');
+ });
+}
diff --git a/apps/omlx-web/tests/test_admin_auth_ui.py b/apps/omlx-web/tests/test_admin_auth_ui.py
index c367155625..e9419eeb09 100644
--- a/apps/omlx-web/tests/test_admin_auth_ui.py
+++ b/apps/omlx-web/tests/test_admin_auth_ui.py
@@ -1,161 +1,96 @@
# SPDX-License-Identifier: Apache-2.0
"""Tests for the admin login, dashboard, and chat page handlers."""
-import asyncio
-from unittest.mock import MagicMock, patch
+from unittest.mock import MagicMock
+import pytest
from omlx_web import routes as webui
-import omlx.server # noqa: F401 - wires the web UI host
-import omlx.admin.routes as admin_routes
-
-
-def _mock_global_settings(api_key=None):
- """Create a mock GlobalSettings with the given API key."""
- mock = MagicMock()
- mock.auth.api_key = api_key
- mock.auth.skip_api_key_verification = False
- mock.ui.language = "en"
- return mock
-
-
-def _patch_getter(mock_settings):
- """Replace the module-level _get_global_settings with a lambda returning mock."""
- original = admin_routes._get_global_settings
- admin_routes._get_global_settings = lambda: mock_settings
- return original
-
-
-def _restore_getter(original):
- """Restore the original _get_global_settings."""
- admin_routes._get_global_settings = original
-
-
-class TestLoginPage:
- """Tests for GET /admin login page TemplateResponse signature."""
-
- def test_login_page_uses_new_template_signature(self):
- """login_page should pass request as first arg to TemplateResponse."""
- mock_settings = _mock_global_settings(api_key="test-key")
- original = _patch_getter(mock_settings)
- try:
- mock_request = MagicMock()
- with patch("omlx.admin.routes.verify_session", return_value=False):
- with patch.object(webui, "templates") as mock_templates:
- mock_templates.TemplateResponse.return_value = MagicMock()
- asyncio.run(webui.login_page(request=mock_request))
- mock_templates.TemplateResponse.assert_called_once_with(
- mock_request, "login.html", {"api_key_configured": True}
- )
- finally:
- _restore_getter(original)
-
-
-class TestDashboardPage:
- """Tests for GET /admin/dashboard TemplateResponse signature."""
-
- def test_dashboard_page_uses_new_template_signature(self):
- """dashboard_page should pass request as first arg to TemplateResponse."""
- mock_request = MagicMock()
- with patch.object(webui, "templates") as mock_templates:
- mock_templates.TemplateResponse.return_value = MagicMock()
- asyncio.run(webui.dashboard_page(request=mock_request, is_admin=True))
- mock_templates.TemplateResponse.assert_called_once_with(
- mock_request, "dashboard.html", {}
- )
-
-
-class TestChatPageApiKeyInjection:
- """Tests for GET /admin/chat API key template injection."""
-
- def test_chat_page_passes_api_key_in_context(self):
- """Chat page should include API key in template context."""
- mock_settings = _mock_global_settings(api_key="test-chat-key")
- original = _patch_getter(mock_settings)
- try:
- mock_request = MagicMock()
- with patch.object(webui, "templates") as mock_templates:
- mock_templates.TemplateResponse.return_value = MagicMock()
- asyncio.run(webui.chat_page(request=mock_request, is_admin=True))
- mock_templates.TemplateResponse.assert_called_once_with(
- mock_request,
- "chat.html",
- {"api_key": "test-chat-key"},
- )
- finally:
- _restore_getter(original)
-
- def test_chat_page_passes_empty_when_no_key(self):
- """Chat page should pass empty string when no API key is configured."""
- mock_settings = _mock_global_settings(api_key=None)
- original = _patch_getter(mock_settings)
- try:
- mock_request = MagicMock()
- with patch.object(webui, "templates") as mock_templates:
- mock_templates.TemplateResponse.return_value = MagicMock()
- asyncio.run(webui.chat_page(request=mock_request, is_admin=True))
- call_args = mock_templates.TemplateResponse.call_args
- context = call_args[0][2]
- assert context["api_key"] == ""
- finally:
- _restore_getter(original)
-
- def test_chat_page_passes_empty_when_no_settings(self):
- """Chat page should pass empty string when global settings is None."""
- original = admin_routes._get_global_settings
- admin_routes._get_global_settings = lambda: None
- try:
- mock_request = MagicMock()
- with patch.object(webui, "templates") as mock_templates:
- mock_templates.TemplateResponse.return_value = MagicMock()
- asyncio.run(webui.chat_page(request=mock_request, is_admin=True))
- call_args = mock_templates.TemplateResponse.call_args
- context = call_args[0][2]
- assert context["api_key"] == ""
- finally:
- admin_routes._get_global_settings = original
-
-
-class TestLoginPageSkipAuth:
- """Login page behavior when skip_api_key_verification is enabled."""
-
- def test_login_page_redirects_when_skip_enabled(self):
- """Login page should redirect to dashboard when skip is enabled on localhost."""
- gs = MagicMock()
- gs.auth.skip_api_key_verification = True
- gs.auth.api_key = "test-key"
- gs.ui.language = "en"
- gs.server.host = "127.0.0.1"
- original = _patch_getter(gs)
- try:
- mock_request = MagicMock()
- with patch("omlx.admin.routes.verify_session", return_value=False):
- result = asyncio.run(webui.login_page(request=mock_request))
- assert result.status_code == 302
- assert result.headers["location"] == "/admin/dashboard"
- finally:
- _restore_getter(original)
-
- def test_login_page_does_not_skip_login_on_network_host(self):
- gs = MagicMock()
- gs.auth.skip_api_key_verification = True
- gs.auth.api_key = "test-key"
- gs.ui.language = "en"
- gs.server.host = "0.0.0.0"
- original = _patch_getter(gs)
- rendered = MagicMock()
- try:
- mock_request = MagicMock()
- with (
- patch("omlx.admin.routes.verify_session", return_value=False),
- patch.object(
- webui.templates,
- "TemplateResponse",
- return_value=rendered,
- ),
- ):
- result = asyncio.run(webui.login_page(request=mock_request))
-
- assert result is rendered
- finally:
- _restore_getter(original)
+from omlx.admin import routes as admin_routes
+from omlx.settings import GlobalSettings
+
+
+@pytest.fixture
+def page_host(monkeypatch, tmp_path):
+ settings = GlobalSettings(base_path=tmp_path)
+ settings.auth.api_key = "test-key"
+ settings.server.host = "127.0.0.1"
+ monkeypatch.setattr(admin_routes, "_get_global_settings", lambda: settings)
+ monkeypatch.setattr(admin_routes, "_get_server_state", lambda: None)
+ monkeypatch.setattr(admin_routes, "verify_session", lambda request: False)
+ monkeypatch.setattr(
+ webui,
+ "_host",
+ webui.WebUIHost(
+ version="test",
+ require_admin=admin_routes.require_admin,
+ is_admin=admin_routes.is_admin_request,
+ ui_language=admin_routes.configured_ui_language,
+ main_api_key=admin_routes.configured_api_key,
+ ),
+ )
+ render = MagicMock()
+ monkeypatch.setattr(webui.templates, "TemplateResponse", render)
+ return settings, render
+
+
+async def test_login_page_uses_request_first_template_signature(page_host):
+ _, render = page_host
+ request = MagicMock()
+
+ result = await webui.login_page(request=request)
+
+ assert result is render.return_value
+ render.assert_called_once_with(
+ request, "login.html", {"api_key_configured": True}
+ )
+
+
+async def test_dashboard_page_uses_request_first_template_signature(page_host):
+ _, render = page_host
+ request = MagicMock()
+
+ result = await webui.dashboard_page(request=request, is_admin=True)
+
+ assert result is render.return_value
+ render.assert_called_once_with(request, "dashboard.html", {})
+
+
+@pytest.mark.parametrize(
+ "api_key, settings_available",
+ [("test-chat-key", True), (None, True), (None, False)],
+ ids=["configured-key", "no-key", "no-settings"],
+)
+async def test_chat_page_injects_main_api_key(
+ page_host, monkeypatch, api_key, settings_available
+):
+ settings, render = page_host
+ settings.auth.api_key = api_key
+ if not settings_available:
+ monkeypatch.setattr(admin_routes, "_get_global_settings", lambda: None)
+ request = MagicMock()
+
+ result = await webui.chat_page(request=request, is_admin=True)
+
+ assert result is render.return_value
+ render.assert_called_once_with(request, "chat.html", {"api_key": api_key or ""})
+
+
+@pytest.mark.parametrize("host", ["127.0.0.1", "0.0.0.0"], ids=["loopback", "network"])
+async def test_login_bypass_is_restricted_to_loopback(page_host, host):
+ settings, render = page_host
+ settings.auth.skip_api_key_verification = True
+ settings.server.host = host
+ request = MagicMock()
+
+ result = await webui.login_page(request=request)
+
+ if host == "127.0.0.1":
+ assert result.status_code == 302
+ assert result.headers["location"] == "/admin/dashboard"
+ render.assert_not_called()
+ else:
+ assert result is render.return_value
+ render.assert_called_once_with(
+ request, "login.html", {"api_key_configured": True}
+ )
diff --git a/apps/omlx-web/tests/test_chat_image_upload.py b/apps/omlx-web/tests/test_chat_image_upload.py
index 51c715874f..c0802daa17 100644
--- a/apps/omlx-web/tests/test_chat_image_upload.py
+++ b/apps/omlx-web/tests/test_chat_image_upload.py
@@ -1,15 +1,13 @@
# SPDX-License-Identifier: Apache-2.0
-"""Tests for chat image upload functionality."""
+"""Localization coverage for chat image uploads; behavior runs in the JS suite."""
+
import json
from pathlib import Path
import pytest
-
-I18N_DIR = Path(__file__).parent.parent / "omlx_web" / "i18n"
-
-# Required i18n keys used by chat image upload feature
-REQUIRED_IMAGE_KEYS = [
+I18N_DIR = Path(__file__).parents[1] / "omlx_web" / "i18n"
+REQUIRED_IMAGE_KEYS = {
"chat.upload_image",
"chat.remove_image",
"chat.image_not_available",
@@ -17,170 +15,11 @@
"chat.error.invalid_image_type",
"chat.error.image_too_large",
"chat.error.image_load_failed",
-]
-
-
-class TestChatImageUpload:
- """Test chat image upload feature"""
-
- def test_multimodal_message_format_with_images(self):
- """Content array format for messages with images (OpenAI standard)"""
- content = [
- {"type": "image_url", "image_url": {"url": "data:image/png;base64,abc"}},
- {"type": "image_url", "image_url": {"url": "data:image/jpeg;base64,def"}},
- {"type": "text", "text": "What are these?"},
- ]
- msg = {"role": "user", "content": content}
-
- assert msg["role"] == "user"
- assert isinstance(msg["content"], list)
- images = [p for p in msg["content"] if p["type"] == "image_url"]
- texts = [p for p in msg["content"] if p["type"] == "text"]
- assert len(images) == 2
- assert len(texts) == 1
- assert all(p["image_url"]["url"].startswith("data:image/") for p in images)
-
- def test_multimodal_message_format_text_only(self):
- """Text-only messages use plain string content"""
- msg = {"role": "user", "content": "Hello"}
- assert isinstance(msg["content"], str)
-
- def test_multimodal_message_format_image_only(self):
- """Image-only messages have no text part"""
- content = [
- {"type": "image_url", "image_url": {"url": "data:image/png;base64,abc"}},
- ]
- msg = {"role": "user", "content": content}
- texts = [p for p in msg["content"] if p["type"] == "text"]
- assert len(texts) == 0
-
- def test_localstorage_stripping(self):
- """Stripping base64 from image_url parts for localStorage"""
- content = [
- {"type": "image_url", "image_url": {"url": "data:image/png;base64,LARGE"}},
- {"type": "text", "text": "describe this"},
- ]
- # Simulate the stripping logic from saveCurrentChat()
- stripped = [
- {"type": "image_url", "image_url": {"url": ""}}
- if p["type"] == "image_url"
- else p
- for p in content
- ]
- assert stripped[0]["image_url"]["url"] == ""
- assert stripped[1]["text"] == "describe this"
-
- def test_base64_data_uri_format(self):
- """Valid base64 data URIs for images"""
- valid_uris = [
- "data:image/png;base64,iVBORw0KGgo=",
- "data:image/jpeg;base64,/9j/4AAQSkZJ",
- "data:image/webp;base64,UklGRjg=",
- ]
- for uri in valid_uris:
- assert uri.startswith("data:image/")
- assert ";base64," in uri
-
- @pytest.mark.parametrize(
- "lang_file",
- ["en.json", "ko.json", "zh.json", "zh-TW.json", "ja.json"],
- )
- def test_i18n_image_keys_present(self, lang_file):
- """All image-related i18n keys exist in every language file"""
- with open(I18N_DIR / lang_file) as f:
- translations = json.load(f)
-
- for key in REQUIRED_IMAGE_KEYS:
- assert key in translations, f"Missing key '{key}' in {lang_file}"
- assert translations[key], f"Empty value for '{key}' in {lang_file}"
-
-
-class TestChatEditImagePreservation:
- """Test image preservation when editing messages (PR #268)"""
-
- @staticmethod
- def get_image_urls(content):
- """Simulate getImageUrls() from chat.html"""
- if not isinstance(content, list):
- return []
- return [
- p["image_url"]["url"]
- for p in content
- if p.get("type") == "image_url" and p.get("image_url", {}).get("url")
- ]
-
- @staticmethod
- def get_text_content(content):
- """Simulate getTextContent() from chat.html"""
- if isinstance(content, str):
- return content
- if isinstance(content, list):
- return "\n".join(
- p["text"] for p in content if p.get("type") == "text"
- )
- return ""
-
- @staticmethod
- def build_edit_content(edit_images, new_text):
- """Simulate saveEdit() content reconstruction from chat.html"""
- if edit_images:
- content = []
- for img in edit_images:
- content.append({"type": "image_url", "image_url": {"url": img}})
- content.append({"type": "text", "text": new_text})
- return content
- return new_text
-
- def test_edit_preserves_images(self):
- """Editing a message with images should preserve the images"""
- original = [
- {"type": "image_url", "image_url": {"url": "data:image/png;base64,abc"}},
- {"type": "image_url", "image_url": {"url": "data:image/jpeg;base64,def"}},
- {"type": "text", "text": "What are these?"},
- ]
- edit_images = self.get_image_urls(original)
- edit_text = self.get_text_content(original)
-
- assert edit_images == [
- "data:image/png;base64,abc",
- "data:image/jpeg;base64,def",
- ]
- assert edit_text == "What are these?"
-
- new_content = self.build_edit_content(edit_images, "Describe these images")
- assert isinstance(new_content, list)
- images = [p for p in new_content if p["type"] == "image_url"]
- texts = [p for p in new_content if p["type"] == "text"]
- assert len(images) == 2
- assert len(texts) == 1
- assert texts[0]["text"] == "Describe these images"
-
- def test_edit_text_only_message(self):
- """Editing a text-only message should produce string content"""
- original = "Hello"
- edit_images = self.get_image_urls(original)
- edit_text = self.get_text_content(original)
-
- assert edit_images == []
- assert edit_text == "Hello"
-
- new_content = self.build_edit_content(edit_images, "Hi there")
- assert isinstance(new_content, str)
- assert new_content == "Hi there"
-
- def test_edit_stripped_images_not_preserved(self):
- """Stripped images (empty URL from localStorage) should not be preserved"""
- restored = [
- {"type": "image_url", "image_url": {"url": ""}},
- {"type": "text", "text": "old text"},
- ]
- edit_images = self.get_image_urls(restored)
- assert edit_images == []
-
- new_content = self.build_edit_content(edit_images, "edited text")
- assert isinstance(new_content, str)
- assert new_content == "edited text"
+}
-if __name__ == "__main__":
- pytest.main([__file__, "-v"])
+@pytest.mark.parametrize("locale", sorted(I18N_DIR.glob("*.json")), ids=lambda p: p.stem)
+def test_i18n_image_keys_present(locale):
+ translations = json.loads(locale.read_text(encoding="utf-8"))
+ for key in REQUIRED_IMAGE_KEYS:
+ assert translations.get(key), f"Missing or empty key {key!r} in {locale.name}"
diff --git a/apps/omlx-web/tests/test_chat_tool_call.py b/apps/omlx-web/tests/test_chat_tool_call.py
index 7d5e2ee0ee..e620732d6c 100644
--- a/apps/omlx-web/tests/test_chat_tool_call.py
+++ b/apps/omlx-web/tests/test_chat_tool_call.py
@@ -1,482 +1,50 @@
# SPDX-License-Identifier: Apache-2.0
-"""Tests for chat MCP tool call loop (chat.html streamResponse changes)."""
+"""Template contracts complementing tool-loop behavior in the JS suite."""
-import json
from pathlib import Path
-CHAT_TEMPLATE = Path(__file__).parents[1] / "omlx_web" / "templates" / "chat.html"
-
-
-class TestChatToolCallMessageFiltering:
- """Test the messagesForApi filtering logic (Python equivalent of the JS)."""
-
- @staticmethod
- def build_messages_for_api(messages):
- """Replicate the messagesForApi logic from streamResponse in chat.html."""
- valid_roles = {"user", "assistant", "tool", "system"}
- result = []
- for msg in messages:
- if msg["role"] not in valid_roles:
- continue
- m = {"role": msg["role"], "content": msg.get("content")}
- if msg.get("tool_calls"):
- m["tool_calls"] = msg["tool_calls"]
- if msg.get("tool_call_id"):
- m["tool_call_id"] = msg["tool_call_id"]
- result.append(m)
- return result
-
- def test_filters_tool_call_indicator_messages(self):
- """tool_call role messages must not be sent to the API."""
- messages = [
- {"role": "user", "content": "Who is X?"},
- {"role": "tool_call", "content": "tavily__tavily_search…", "_ui": True},
- {"role": "assistant", "content": "X is...", "tool_calls": None},
- ]
- api_msgs = self.build_messages_for_api(messages)
- roles = [m["role"] for m in api_msgs]
- assert "tool_call" not in roles
- assert roles == ["user", "assistant"]
-
- def test_passes_tool_calls_and_tool_call_id(self):
- """Assistant tool_calls and tool result tool_call_id must be preserved."""
- tc = [{"id": "tc_1", "type": "function", "function": {"name": "t", "arguments": "{}"}}]
- messages = [
- {"role": "user", "content": "Search for X"},
- {"role": "assistant", "content": None, "tool_calls": tc, "_ui": False},
- {"role": "tool", "tool_call_id": "tc_1", "content": "result...", "_ui": False},
- ]
- api_msgs = self.build_messages_for_api(messages)
- assert len(api_msgs) == 3
- assert api_msgs[1]["tool_calls"] == tc
- assert api_msgs[2]["tool_call_id"] == "tc_1"
-
- def test_normal_conversation_unchanged(self):
- """Normal user/assistant conversation with no tools is unaffected."""
- messages = [
- {"role": "user", "content": "Hello"},
- {"role": "assistant", "content": "Hi there"},
- ]
- api_msgs = self.build_messages_for_api(messages)
- assert len(api_msgs) == 2
- assert api_msgs[0] == {"role": "user", "content": "Hello"}
- assert api_msgs[1] == {"role": "assistant", "content": "Hi there"}
-
-
-class TestChatToolCallAccumulation:
- """Test streaming tool_call chunk accumulation (Python equivalent of the JS)."""
-
- @staticmethod
- def accumulate_tool_calls(deltas):
- """Replicate the toolCallsMap accumulation logic from streamResponse."""
- tool_calls_map = {}
- for delta in deltas:
- if not delta.get("tool_calls"):
- continue
- for tc in delta["tool_calls"]:
- i = tc.get("index", 0)
- if i not in tool_calls_map:
- tool_calls_map[i] = {"id": "", "type": "function", "function": {"name": "", "arguments": ""}}
- if tc.get("id"):
- tool_calls_map[i]["id"] = tc["id"]
- if tc.get("function", {}).get("name"):
- tool_calls_map[i]["function"]["name"] += tc["function"]["name"]
- if tc.get("function", {}).get("arguments"):
- tool_calls_map[i]["function"]["arguments"] += tc["function"]["arguments"]
- return list(tool_calls_map.values())
-
- def test_single_tool_call(self):
- """A single tool call split across multiple chunks is assembled correctly."""
- deltas = [
- {"tool_calls": [{"index": 0, "id": "tc_1", "function": {"name": "tavily__tavily_search"}}]},
- {"tool_calls": [{"index": 0, "function": {"arguments": '{"que'}}]},
- {"tool_calls": [{"index": 0, "function": {"arguments": 'ry":"test"}'}}]},
- ]
- result = self.accumulate_tool_calls(deltas)
- assert len(result) == 1
- assert result[0]["id"] == "tc_1"
- assert result[0]["function"]["name"] == "tavily__tavily_search"
- assert json.loads(result[0]["function"]["arguments"]) == {"query": "test"}
-
- def test_multiple_parallel_tool_calls(self):
- """Multiple tool calls with different indices are accumulated separately."""
- deltas = [
- {"tool_calls": [{"index": 0, "id": "tc_1", "function": {"name": "search"}}]},
- {"tool_calls": [{"index": 1, "id": "tc_2", "function": {"name": "extract"}}]},
- {"tool_calls": [{"index": 0, "function": {"arguments": '{"q":"a"}'}}]},
- {"tool_calls": [{"index": 1, "function": {"arguments": '{"urls":["http://x"]}'}}]},
- ]
- result = self.accumulate_tool_calls(deltas)
- assert len(result) == 2
- assert result[0]["function"]["name"] == "search"
- assert result[1]["function"]["name"] == "extract"
- assert json.loads(result[0]["function"]["arguments"]) == {"q": "a"}
- assert json.loads(result[1]["function"]["arguments"]) == {"urls": ["http://x"]}
-
- def test_no_tool_calls(self):
- """Deltas with no tool_calls produce empty list."""
- deltas = [
- {"content": "Hello"},
- {"content": " world"},
- ]
- result = self.accumulate_tool_calls(deltas)
- assert result == []
-
- def test_missing_index_defaults_to_zero(self):
- """A tool_call chunk without an index field defaults to index 0."""
- deltas = [
- {"tool_calls": [{"id": "tc_1", "function": {"name": "t", "arguments": "{}"}}]},
- ]
- result = self.accumulate_tool_calls(deltas)
- assert len(result) == 1
- assert result[0]["id"] == "tc_1"
-
-
-class TestChatToolCallSafety:
- """Test safety guards for the chat tool loop (round limit, abort, errors)."""
-
- MAX_TOOL_ROUNDS = 10
- TOOL_TIMEOUT_MS = 30000
-
- @staticmethod
- def build_round_error_message(max_rounds):
- """Replicate the round-limit error message from streamResponse."""
- return (
- f"Error: Maximum tool call rounds ({max_rounds}) reached. "
- "Increase the limit in Chat settings for longer tool workflows."
- )
-
- @staticmethod
- def normalize_max_tool_rounds(value):
- """Replicate normalizeMaxToolRounds from chat.html."""
- try:
- parsed = int(value)
- except (TypeError, ValueError):
- return 10
- return min(100, max(1, parsed))
-
- @staticmethod
- def should_execute_tool_round(completed_rounds, max_rounds):
- """A newly requested tool round is blocked once the limit is reached."""
- return completed_rounds < max_rounds
-
- @staticmethod
- def build_tool_result(content, error=False, tool_name=None):
- """Replicate the tool execution result format from streamResponse."""
- result = {"content": content, "error": error}
- if tool_name:
- result["toolName"] = tool_name
- return result
-
- @staticmethod
- def build_timeout_error_message(timeout_ms):
- """Replicate the timeout error message from streamResponse."""
- return f"Error: Tool timed out after {timeout_ms / 1000}s"
-
- @staticmethod
- def build_tool_status_error(failed_results):
- """Replicate the toolStatus error format from streamResponse."""
- names = [r["toolName"] for r in failed_results if r.get("error")]
- return f"Failed: {', '.join(names)}" if names else ""
-
- # --- Tool round limit tests ---
-
- def test_round_limit_error_message_format(self):
- """The error identifies the configured limit and where to change it."""
- msg = self.build_round_error_message(self.MAX_TOOL_ROUNDS)
- assert "10" in msg
- assert "Chat settings" in msg
-
- def test_tool_round_below_limit_is_executed(self):
- assert self.should_execute_tool_round(9, self.MAX_TOOL_ROUNDS)
-
- def test_new_tool_round_at_limit_is_blocked(self):
- assert not self.should_execute_tool_round(10, self.MAX_TOOL_ROUNDS)
-
- def test_custom_tool_round_limit_is_honored(self):
- assert self.should_execute_tool_round(24, 25)
- assert not self.should_execute_tool_round(25, 25)
-
- def test_tool_round_limit_is_normalized_to_safe_range(self):
- assert self.normalize_max_tool_rounds(None) == 10
- assert self.normalize_max_tool_rounds("bad") == 10
- assert self.normalize_max_tool_rounds(0) == 1
- assert self.normalize_max_tool_rounds(150) == 100
-
- # --- Tool result format tests ---
-
- def test_success_result_includes_tool_name(self):
- """Successful tool results should have error=False and include toolName."""
- result = self.build_tool_result("search results here", tool_name="tavily_search")
- assert result["error"] is False
- assert result["toolName"] == "tavily_search"
-
- def test_error_result_includes_tool_name(self):
- """Failed tool results should have error=True and include toolName."""
- result = self.build_tool_result("Error: connection refused", error=True, tool_name="tavily_search")
- assert result["error"] is True
- assert result["toolName"] == "tavily_search"
- assert result["content"].startswith("Error:")
-
- def test_timeout_error_message_includes_seconds(self):
- """Timeout error message should show the timeout in seconds."""
- msg = self.build_timeout_error_message(self.TOOL_TIMEOUT_MS)
- assert "30.0s" in msg
-
- def test_http_error_result_format(self):
- """HTTP errors from /v1/mcp/execute should produce error results."""
- result = self.build_tool_result("Error: HTTP 503", error=True, tool_name="broken_tool")
- assert result["error"] is True
- assert "503" in result["content"]
+import pytest
- # --- Error indicator tests ---
-
- def test_tool_status_error_format(self):
- """Tool status error message should list failed tool names."""
- failed_results = [
- {"content": "Error: timeout", "error": True, "toolName": "tavily_search"},
- {"content": "Error: HTTP 503", "error": True, "toolName": "broken_tool"},
- ]
- status = self.build_tool_status_error(failed_results)
- assert "tavily_search" in status
- assert "broken_tool" in status
- assert status.startswith("Failed:")
-
- def test_error_indicators_excluded_from_api(self):
- """Error indicators (role=tool_call) must be filtered from messagesForApi."""
- messages = [
- {"role": "user", "content": "search for X"},
- {"role": "tool_call", "content": "search failed", "_error": True, "_ui": True},
- {"role": "assistant", "content": "Sorry, the search failed."},
- ]
- valid_roles = {"user", "assistant", "tool", "system"}
- api_msgs = [m for m in messages if m["role"] in valid_roles]
- assert len(api_msgs) == 2
- assert all(m["role"] != "tool_call" for m in api_msgs)
-
- # --- Abort guard tests ---
-
- def test_abort_signal_prevents_recursion(self):
- """Simulates the abort guard: if signal is aborted, no recursion should happen."""
- # Replicate the guard logic: if (this.abortController?.signal.aborted) return;
- class FakeSignal:
- def __init__(self, aborted):
- self.aborted = aborted
-
- class FakeController:
- def __init__(self, aborted):
- self.signal = FakeSignal(aborted)
-
- # When aborted, the guard should fire
- controller = FakeController(aborted=True)
- should_recurse = not (controller.signal.aborted)
- assert should_recurse is False
-
- # When not aborted, recursion should proceed
- controller = FakeController(aborted=False)
- should_recurse = not (controller.signal.aborted)
- assert should_recurse is True
-
- def test_abort_guard_with_none_controller(self):
- """If abortController is None, the guard should not crash (optional chaining)."""
- controller = None
- # Replicate JS: this.abortController?.signal.aborted
- aborted = getattr(getattr(controller, "signal", None), "aborted", None)
- # None is falsy, so recursion should proceed
- assert not aborted
-
-
-class TestChatToolRoundSourceContract:
- """Pin the browser implementation's tool-round and timing lifecycle."""
-
- @staticmethod
- def stream_response_source():
- source = CHAT_TEMPLATE.read_text(encoding="utf-8")
- start = source.index("async streamResponse(streamContext = null, depth = 0)")
- end = source.index(" stopStreaming()", start)
- return source[start:end]
-
- def test_limit_is_checked_before_executing_an_extra_tool_round(self):
- stream = self.stream_response_source()
- tool_branch = stream[stream.index("if (toolCalls.length > 0) {") :]
-
- assert tool_branch.index("if (depth >= maxToolRounds)") < tool_branch.index(
- "const results = await Promise.all"
- )
- assert "MAX_TOOL_DEPTH" not in stream
-
- def test_final_answer_is_still_allowed_after_the_last_tool_round(self):
- stream = self.stream_response_source()
-
- assert stream.index("if (toolCalls.length > 0) {") < stream.index(
- "if (depth >= maxToolRounds)"
- )
-
- def test_root_request_owns_timing_and_stream_cleanup(self):
- stream = self.stream_response_source()
-
- assert "context._requestStartedAt = Date.now();" in stream
- assert "Date.now() - context._requestStartedAt" in stream
- assert stream.count("this.resetStreamSession(stream") == 2
- finally_body = stream[stream.rindex("} finally {") :]
- assert finally_body.index("if (depth === 0) {") < finally_body.index(
- "this.resetStreamSession(stream, { preserveFinalContent: true });"
- )
-
- def test_chat_setting_exposes_a_bounded_tool_round_limit(self):
- source = CHAT_TEMPLATE.read_text(encoding="utf-8")
-
- assert "maxToolRounds: 10" in source
- assert 'id="max-tool-rounds"' in source
- assert 'min="1" max="100"' in source
- assert "normalizeMaxToolRounds(value)" in source
-
-
-class TestBuiltinWebToolDispatch:
- """Python equivalent of the built-in web tool gating added to chat.html.
-
- Mirrors webSearchReady / webSearchToolsActive / builtinWebRoute /
- activeTools so the JS contract stays pinned by tests.
- """
-
- ROUTES = {"web_search": "/v1/web/search", "fetch_url": "/v1/web/fetch"}
-
- @staticmethod
- def web_search_ready(settings):
- provider = settings.get("provider", "ddgs")
- if provider == "brave":
- return settings.get("braveKeySet", False)
- if provider == "searxng":
- return settings.get("searxngUrlSet", False)
- if provider == "ddgs_custom":
- return settings.get("ddgsBackendsSet", False)
- return True
-
- def tools_active(self, enabled, settings):
- return enabled and self.web_search_ready(settings)
-
- def builtin_web_route(self, name, enabled, settings):
- if not self.tools_active(enabled, settings):
- return None
- return self.ROUTES.get(name)
-
- def active_tools(self, enabled, settings, builtin_tools, mcp_tools):
- if not self.tools_active(enabled, settings):
- return mcp_tools
- builtin_names = set(self.ROUTES)
- return builtin_tools + [
- t for t in mcp_tools if t["function"]["name"] not in builtin_names
- ]
-
- @staticmethod
- def _tool(name):
- return {"type": "function", "function": {"name": name}}
-
- def test_toggle_off_keeps_mcp_tools_and_routing(self):
- settings = {"provider": "duckduckgo"}
- mcp_tools = [self._tool("web_search"), self._tool("other")]
- assert self.active_tools(False, settings, [self._tool("web_search")], mcp_tools) == mcp_tools
- # An MCP tool named web_search keeps going to /v1/mcp/execute
- assert self.builtin_web_route("web_search", False, settings) is None
-
- def test_toggle_on_builtin_wins_name_collision(self):
- settings = {"provider": "duckduckgo"}
- builtin = [self._tool("web_search"), self._tool("fetch_url")]
- mcp_tools = [self._tool("web_search"), self._tool("other")]
- tools = self.active_tools(True, settings, builtin, mcp_tools)
- names = [t["function"]["name"] for t in tools]
- assert names == ["web_search", "fetch_url", "other"]
-
- def test_builtin_routes_when_active(self):
- settings = {"provider": "duckduckgo"}
- assert self.builtin_web_route("web_search", True, settings) == "/v1/web/search"
- assert self.builtin_web_route("fetch_url", True, settings) == "/v1/web/fetch"
- assert self.builtin_web_route("other", True, settings) is None
-
- def test_brave_without_key_is_inactive(self):
- settings = {"provider": "brave", "braveKeySet": False}
- assert self.tools_active(True, settings) is False
- settings["braveKeySet"] = True
- assert self.tools_active(True, settings) is True
-
- def test_searxng_without_url_is_inactive(self):
- settings = {"provider": "searxng", "searxngUrlSet": False}
- assert self.tools_active(True, settings) is False
- settings["searxngUrlSet"] = True
- assert self.tools_active(True, settings) is True
+CHAT_TEMPLATE = Path(__file__).parents[1] / "omlx_web" / "templates" / "chat.html"
- def test_ddgs_total_and_duckduckgo_need_no_config(self):
- assert self.tools_active(True, {"provider": "ddgs"}) is True
- assert self.tools_active(True, {"provider": "duckduckgo"}) is True
- def test_ddgs_custom_needs_backend_selection(self):
- settings = {"provider": "ddgs_custom", "ddgsBackendsSet": False}
- assert self.tools_active(True, settings) is False
- settings["ddgsBackendsSet"] = True
- assert self.tools_active(True, settings) is True
+@pytest.fixture(scope="module")
+def stream_response_source():
+ source = CHAT_TEMPLATE.read_text(encoding="utf-8")
+ start = source.index("async streamResponse(streamContext = null, depth = 0)")
+ end = source.index(" stopStreaming()", start)
+ return source[start:end]
-class TestToolRoundSegmentChain:
- """Mirror of splitTurnSegments/getActiveVariantChain from chat.html.
+def test_limit_is_checked_before_executing_an_extra_tool_round(stream_response_source):
+ tool_branch = stream_response_source[
+ stream_response_source.index("if (toolCalls.length > 0) {") :
+ ]
+ assert tool_branch.index("if (depth >= maxToolRounds)") < tool_branch.index(
+ "const results = await Promise.all"
+ )
+ assert "MAX_TOOL_DEPTH" not in stream_response_source
- Regression guard for the tool-round visibility bug: intermediate
- assistant tool_calls turns must stay _ui:false. A visible assistant
- message is a variant segment boundary, so a visible tool-round turn
- splits the turn and the active chain sent to the API loses the
- tool_calls turn — the orphan tool message then corrupts chat
- templates (observed as garbage output on DeepSeek-V4).
- """
- @staticmethod
- def split_turn_segments(turn):
- segments, current = [], []
- for m in turn:
- current.append(m)
- if m["role"] == "assistant" and m.get("_ui") is not False:
- segments.append(current)
- current = []
- if current:
- segments.append(current)
- return segments or [turn]
+def test_final_answer_is_still_allowed_after_the_last_tool_round(stream_response_source):
+ assert stream_response_source.index(
+ "if (toolCalls.length > 0) {"
+ ) < stream_response_source.index("if (depth >= maxToolRounds)")
- def active_chain(self, turn, active_id=None):
- segments = self.split_turn_segments(turn)
- if len(segments) <= 1:
- return turn
- if active_id:
- for segment in segments:
- if any(m.get("id") == active_id for m in segment):
- return segment
- return segments[-1]
- def test_hidden_tool_round_keeps_full_chain(self):
- turn = [
- {"id": "t1", "role": "assistant", "tool_calls": [{}],
- "_ui": False, "_toolRound": True},
- {"id": "r1", "role": "tool", "_ui": False},
- {"id": "a1", "role": "assistant", "content": "final"},
- ]
- chain = self.active_chain(turn, active_id="a1")
- assert [m["id"] for m in chain] == ["t1", "r1", "a1"]
+def test_root_request_owns_timing_and_stream_cleanup(stream_response_source):
+ assert "context._requestStartedAt = Date.now();" in stream_response_source
+ assert "Date.now() - context._requestStartedAt" in stream_response_source
+ assert stream_response_source.count("this.resetStreamSession(stream") == 2
+ finally_body = stream_response_source[stream_response_source.rindex("} finally {") :]
+ assert finally_body.index("if (depth === 0) {") < finally_body.index(
+ "this.resetStreamSession(stream, { preserveFinalContent: true });"
+ )
- def test_visible_tool_round_drops_tool_calls_turn(self):
- # Documents the failure mode this guard exists for.
- turn = [
- {"id": "t1", "role": "assistant", "tool_calls": [{}],
- "_toolRound": True},
- {"id": "r1", "role": "tool", "_ui": False},
- {"id": "a1", "role": "assistant", "content": "final"},
- ]
- chain = self.active_chain(turn, active_id="a1")
- assert [m["id"] for m in chain] == ["r1", "a1"]
- def test_mid_loop_last_segment_is_complete_without_final_answer(self):
- # During recursion (final answer not pushed yet) the last segment
- # must still contain the tool_calls turn and its result.
- turn = [
- {"id": "t1", "role": "assistant", "tool_calls": [{}],
- "_ui": False, "_toolRound": True},
- {"id": "r1", "role": "tool", "_ui": False},
- ]
- chain = self.active_chain(turn)
- assert [m["id"] for m in chain] == ["t1", "r1"]
+def test_chat_setting_exposes_a_bounded_tool_round_limit():
+ source = CHAT_TEMPLATE.read_text(encoding="utf-8")
+ assert "maxToolRounds: 10" in source
+ assert 'id="max-tool-rounds"' in source
+ assert 'min="1" max="100"' in source
+ assert "normalizeMaxToolRounds(value)" in source
diff --git a/apps/omlx-web/tests/test_chat_ui_overhaul.py b/apps/omlx-web/tests/test_chat_ui_overhaul.py
index e9b0bb5ce2..c2166146fa 100644
--- a/apps/omlx-web/tests/test_chat_ui_overhaul.py
+++ b/apps/omlx-web/tests/test_chat_ui_overhaul.py
@@ -35,6 +35,25 @@ def _section(source: str, start: str, end: str) -> str:
return source.split(start, 1)[1].split(end, 1)[0]
+def _run_chat(method_names, body):
+ node = shutil.which("node")
+ if not node:
+ pytest.skip("Node.js is required to exercise Chat JavaScript")
+ source = _template()
+ methods = [
+ re.search(
+ r"^( +)(?:async )?" + re.escape(name) + r"\([^\n]*\) \{.*?^\1\},",
+ source,
+ re.M | re.S,
+ ).group()
+ for name in method_names
+ ]
+ script = "const app = {" + "\n".join(methods) + "};\n" + body
+ return json.loads(
+ subprocess.check_output([node, "-e", script], text=True, timeout=30)
+ )
+
+
def test_regeneration_overrides_survive_stream_context():
stream = _section(
_template(),
@@ -234,10 +253,6 @@ def test_right_panel_dialog_breakpoint_matches_the_stylesheet():
def test_regeneration_hides_the_turn_until_the_new_variant_lands():
- node = shutil.which("node")
- if not node:
- pytest.skip("Node.js is required to exercise Chat JavaScript")
- source = _template()
names = [
"findUserIndexForMessage",
"getTurnVariantsAt",
@@ -250,14 +265,7 @@ def test_regeneration_hides_the_turn_until_the_new_variant_lands():
"getStreamSession",
"currentStream",
]
- methods = [
- re.search(
- r"^( +)" + name + r"\([^\n]*\) \{.*?^\1\},", source, re.M | re.S
- ).group()
- for name in names
- ]
- script = (
- "const app = {" + "\n".join(methods) + "};\n" + """
+ result = _run_chat(names, """
app.currentChatId = 'c';
app.messages = [
{id: 'u0', role: 'user'}, {id: 'a0', role: 'assistant'},
@@ -278,7 +286,6 @@ def test_regeneration_hides_the_turn_until_the_new_variant_lands():
console.log(JSON.stringify({during, activeTab, landed, after: visible()}));
"""
)
- result = json.loads(subprocess.check_output([node, "-e", script], text=True))
assert result["during"] == ["u0", "a0", "u1"]
assert result["activeTab"] is False
assert result["landed"] == ["u0", "a0", "u1", "a3"]
@@ -286,10 +293,6 @@ def test_regeneration_hides_the_turn_until_the_new_variant_lands():
def test_profile_picks_where_sampling_values_come_from():
- node = shutil.which("node")
- if not node:
- pytest.skip("Node.js is required to exercise Chat JavaScript")
- source = _template()
names = [
"currentModelInfo",
"thinkingModes",
@@ -301,16 +304,9 @@ def test_profile_picks_where_sampling_values_come_from():
"samplingMode",
"selectProfileOption",
]
- methods = [
- re.search(
- r"^( +)" + name + r"\([^\n]*\) \{.*?^\1\},", source, re.M | re.S
- ).group()
- for name in names
- ]
- script = (
- "const CUSTOM_PROFILE_OPTION = '__custom__';\n"
- "window = {t: key => key};\n"
- "const app = {" + "\n".join(methods) + "};\n" + """
+ result = _run_chat(names, """
+const CUSTOM_PROFILE_OPTION = '__custom__';
+globalThis.window = {t: key => key};
app.currentModel = 'm';
app.aliasToGateway = {};
app._adminModelsList = [{id: 'm', thinking_modes: ['auto'],
@@ -333,7 +329,6 @@ def test_profile_picks_where_sampling_values_come_from():
seeded: app.snapshotGenerationSettings(), active: app.activePromptProfile}));
"""
)
- result = json.loads(subprocess.check_output([node, "-e", script], text=True))
assert result["model"] is None
assert result["writer"] == {"temperature": 1.1}
assert result["custom"] == {"temperature": 0.2}
@@ -343,10 +338,6 @@ def test_profile_picks_where_sampling_values_come_from():
def test_a_new_turn_uses_the_panel_model_and_settings():
- node = shutil.which("node")
- if not node:
- pytest.skip("Node.js is required to exercise Chat JavaScript")
- source = _template()
names = [
"getTurnVariantsAt",
"getActiveVariantForUser",
@@ -354,14 +345,7 @@ def test_a_new_turn_uses_the_panel_model_and_settings():
"resolveApiModel",
"resolveApiGenerationOverrides",
]
- methods = [
- re.search(
- r"^( +)" + name + r"\([^\n]*\) \{.*?^\1\},", source, re.M | re.S
- ).group()
- for name in names
- ]
- script = (
- "const app = {" + "\n".join(methods) + "};\n" + """
+ result = _run_chat(names, """
app.resolveGatewayModelId = id => id;
app.snapshotGenerationSettings = () => ({reasoning_effort: 'max'});
const messages = [
@@ -377,7 +361,6 @@ def test_a_new_turn_uses_the_panel_model_and_settings():
}));
"""
)
- result = json.loads(subprocess.check_output([node, "-e", script], text=True))
assert result == {
"model": "new",
"generation": {"reasoning_effort": "max"},
@@ -386,22 +369,9 @@ def test_a_new_turn_uses_the_panel_model_and_settings():
def test_picking_a_reply_restores_its_sampling_profile():
- node = shutil.which("node")
- if not node:
- pytest.skip("Node.js is required to exercise Chat JavaScript")
- source = _template()
names = ["normalizeProfileName", "samplingFields", "applyVariantPanelSnapshot"]
- methods = [
- re.search(
- r"^( +)(?:async )?" + name + r"\([^\n]*\) \{.*?^\1\},",
- source,
- re.M | re.S,
- ).group()
- for name in names
- ]
- script = (
- "window = {t: key => key};\n"
- "const app = {" + "\n".join(methods) + "};\n" + """
+ result = _run_chat(names, """
+globalThis.window = {t: key => key};
app.variantModelMissing = () => false;
app.resolveGatewayModelId = id => id;
app.applyGenerationSnapshot = () => {};
@@ -424,7 +394,6 @@ def test_picking_a_reply_restores_its_sampling_profile():
})();
"""
)
- result = json.loads(subprocess.check_output([node, "-e", script], text=True))
assert result == {
"custom": None,
"model": "System Default",
diff --git a/tests/test_admin_api_key.py b/tests/test_admin_api_key.py
index cd59e32583..3c36fd0681 100644
--- a/tests/test_admin_api_key.py
+++ b/tests/test_admin_api_key.py
@@ -670,89 +670,39 @@ def test_setup_returns_503_when_settings_are_unavailable(self):
finally:
_restore_getter(original)
- def test_setup_rejects_when_key_already_set(self):
- """Setup should fail if API key is already configured."""
- from fastapi import HTTPException
-
- mock_settings = _mock_global_settings(api_key="existing-key")
- original = _patch_getter(mock_settings)
- try:
- request = admin_routes.SetupApiKeyRequest(
- api_key="newkey", api_key_confirm="newkey"
- )
- with pytest.raises(HTTPException) as exc_info:
- asyncio.run(
- admin_routes.setup_api_key(
- request, MagicMock(), _loopback_http_request()
- )
- )
- assert exc_info.value.status_code == 400
- assert "already configured" in exc_info.value.detail
- finally:
- _restore_getter(original)
-
- def test_setup_rejects_mismatched_keys(self):
- """Setup should fail if api_key and api_key_confirm don't match."""
- from fastapi import HTTPException
-
- mock_settings = _mock_global_settings(api_key=None)
- original = _patch_getter(mock_settings)
- try:
- request = admin_routes.SetupApiKeyRequest(
- api_key="key1", api_key_confirm="key2"
- )
- with pytest.raises(HTTPException) as exc_info:
- asyncio.run(
- admin_routes.setup_api_key(
- request, MagicMock(), _loopback_http_request()
- )
- )
- assert exc_info.value.status_code == 400
- assert "do not match" in exc_info.value.detail
- finally:
- _restore_getter(original)
-
- def test_setup_rejects_short_key(self):
- """Setup should fail if key is too short."""
+ @pytest.mark.parametrize(
+ ("existing_key", "api_key", "confirmation", "detail"),
+ [
+ pytest.param(
+ "existing-key",
+ "newkey",
+ "newkey",
+ "already configured",
+ id="already-set",
+ ),
+ pytest.param(None, "key1", "key2", "do not match", id="mismatched"),
+ pytest.param(None, "abc", "abc", "at least 4", id="too-short"),
+ pytest.param(None, "ab cd", "ab cd", "whitespace", id="whitespace"),
+ ],
+ )
+ def test_setup_rejects_invalid_key(
+ self, monkeypatch, existing_key, api_key, confirmation, detail
+ ):
from fastapi import HTTPException
- mock_settings = _mock_global_settings(api_key=None)
- original = _patch_getter(mock_settings)
- try:
- request = admin_routes.SetupApiKeyRequest(
- api_key="abc", api_key_confirm="abc"
- )
- with pytest.raises(HTTPException) as exc_info:
- asyncio.run(
- admin_routes.setup_api_key(
- request, MagicMock(), _loopback_http_request()
- )
+ mock_settings = _mock_global_settings(api_key=existing_key)
+ monkeypatch.setattr(admin_routes, "_get_global_settings", lambda: mock_settings)
+ request = admin_routes.SetupApiKeyRequest(
+ api_key=api_key, api_key_confirm=confirmation
+ )
+ with pytest.raises(HTTPException) as exc_info:
+ asyncio.run(
+ admin_routes.setup_api_key(
+ request, MagicMock(), _loopback_http_request()
)
- assert exc_info.value.status_code == 400
- assert "at least 4" in exc_info.value.detail
- finally:
- _restore_getter(original)
-
- def test_setup_rejects_whitespace_key(self):
- """Setup should fail if key contains whitespace."""
- from fastapi import HTTPException
-
- mock_settings = _mock_global_settings(api_key=None)
- original = _patch_getter(mock_settings)
- try:
- request = admin_routes.SetupApiKeyRequest(
- api_key="ab cd", api_key_confirm="ab cd"
)
- with pytest.raises(HTTPException) as exc_info:
- asyncio.run(
- admin_routes.setup_api_key(
- request, MagicMock(), _loopback_http_request()
- )
- )
- assert exc_info.value.status_code == 400
- assert "whitespace" in exc_info.value.detail
- finally:
- _restore_getter(original)
+ assert exc_info.value.status_code == 400
+ assert detail in exc_info.value.detail
def test_setup_rejects_non_loopback_configured_bind(self):
"""Initial setup is unavailable once the server is network-facing."""
diff --git a/tests/test_anthropic_adapter.py b/tests/test_anthropic_adapter.py
index 0e8e5b61f6..1cb14b9f86 100644
--- a/tests/test_anthropic_adapter.py
+++ b/tests/test_anthropic_adapter.py
@@ -172,31 +172,18 @@ def test_parse_request_multiple_in_messages_system(self, adapter):
# parse_request Tests - Generation Parameters
# =========================================================================
- def test_parse_request_with_temperature(self, adapter):
- """Test parsing request with temperature."""
+ @pytest.mark.parametrize("temperature", [0.5, 0.0], ids=["nonzero", "zero"])
+ def test_parse_request_with_temperature(self, adapter, temperature):
request = MessagesRequest(
model="claude-3-sonnet",
max_tokens=1024,
messages=[AnthropicMessage(role="user", content="Hello")],
- temperature=0.5,
+ temperature=temperature,
)
internal = adapter.parse_request(request)
- assert internal.temperature == 0.5
-
- def test_parse_request_with_zero_temperature(self, adapter):
- """Test parsing request with zero temperature."""
- request = MessagesRequest(
- model="claude-3-sonnet",
- max_tokens=1024,
- messages=[AnthropicMessage(role="user", content="Hello")],
- temperature=0.0,
- )
-
- internal = adapter.parse_request(request)
-
- assert internal.temperature == 0.0
+ assert internal.temperature == temperature
def test_parse_request_default_temperature(self, adapter):
"""Test parsing request without temperature uses default."""
@@ -516,25 +503,22 @@ def test_create_error_response_default(self, adapter):
assert result["error"]["message"] == "Something went wrong"
assert result["error"]["type"] == "api_error"
- def test_create_error_response_custom_type(self, adapter):
- """Test creating error response with custom type."""
- result = adapter.create_error_response(
- "Invalid request",
- error_type="invalid_request_error",
- )
-
- assert result["error"]["message"] == "Invalid request"
- assert result["error"]["type"] == "invalid_request_error"
-
- def test_create_error_response_authentication(self, adapter):
- """Test creating authentication error response."""
- result = adapter.create_error_response(
- "Invalid API key",
- error_type="authentication_error",
- )
+ @pytest.mark.parametrize(
+ ("message", "error_type"),
+ [
+ pytest.param(
+ "Invalid request", "invalid_request_error", id="invalid-request"
+ ),
+ pytest.param(
+ "Invalid API key", "authentication_error", id="authentication"
+ ),
+ ],
+ )
+ def test_create_error_response_custom_type(self, adapter, message, error_type):
+ result = adapter.create_error_response(message, error_type=error_type)
- assert result["error"]["type"] == "authentication_error"
- assert result["error"]["message"] == "Invalid API key"
+ assert result["error"]["message"] == message
+ assert result["error"]["type"] == error_type
# =========================================================================
# format_error_event Tests
diff --git a/tests/test_audio_discovery.py b/tests/test_audio_discovery.py
index e4ea49fa6b..cc1b9ed273 100644
--- a/tests/test_audio_discovery.py
+++ b/tests/test_audio_discovery.py
@@ -11,6 +11,8 @@
import json
from pathlib import Path
+import pytest
+
from omlx.model_discovery import (
AUDIO_STS_ARCHITECTURES,
AUDIO_STS_MODEL_TYPES,
@@ -496,17 +498,39 @@ def test_sts_architectures_set_contains_expected_entries(self):
class TestDiscoverModelsIncludesSTS:
"""discover_models() must return STS models with correct engine_type."""
- def test_discover_sts_sam_audio_model(self, tmp_path):
- """SAMAudio STS model included in discover_models results."""
- sts_dir = tmp_path / "sam-audio-base"
- _make_model(sts_dir, {
- "model_type": "sam_audio",
- "architectures": ["SAMAudio"],
- })
+ @pytest.mark.parametrize(
+ ("name", "model_type", "architecture"),
+ [
+ pytest.param("sam-audio-base", "sam_audio", "SAMAudio", id="sam-audio"),
+ pytest.param(
+ "DeepFilterNet3",
+ "deepfilternet",
+ "DeepFilterNetModel",
+ id="deepfilternet",
+ ),
+ pytest.param(
+ "mossformer2-se-48k",
+ "mossformer2",
+ "MossFormer2SEModel",
+ id="mossformer2",
+ ),
+ pytest.param(
+ "LFM2.5-Audio-1B",
+ "lfm2_audio",
+ "LFM2AudioModel",
+ id="lfm2-audio",
+ ),
+ ],
+ )
+ def test_discover_sts_model(self, tmp_path, name, model_type, architecture):
+ _make_model(
+ tmp_path / name,
+ {"model_type": model_type, "architectures": [architecture]},
+ )
models = discover_models(tmp_path)
- assert "sam-audio-base" in models
- assert models["sam-audio-base"].model_type == "audio_sts"
+ assert name in models
+ assert models[name].model_type == "audio_sts"
def test_discover_sts_engine_type(self, tmp_path):
"""STS model has engine_type='audio_sts'."""
@@ -517,42 +541,6 @@ def test_discover_sts_engine_type(self, tmp_path):
assert "deepfilternet3" in models
assert models["deepfilternet3"].engine_type == "audio_sts"
- def test_discover_sts_deepfilternet_model(self, tmp_path):
- """DeepFilterNet STS model is discovered correctly."""
- sts_dir = tmp_path / "DeepFilterNet3"
- _make_model(sts_dir, {
- "model_type": "deepfilternet",
- "architectures": ["DeepFilterNetModel"],
- })
-
- models = discover_models(tmp_path)
- assert "DeepFilterNet3" in models
- assert models["DeepFilterNet3"].model_type == "audio_sts"
-
- def test_discover_sts_mossformer2_model(self, tmp_path):
- """MossFormer2 STS model is discovered correctly."""
- sts_dir = tmp_path / "mossformer2-se-48k"
- _make_model(sts_dir, {
- "model_type": "mossformer2",
- "architectures": ["MossFormer2SEModel"],
- })
-
- models = discover_models(tmp_path)
- assert "mossformer2-se-48k" in models
- assert models["mossformer2-se-48k"].model_type == "audio_sts"
-
- def test_discover_lfm2_audio_model(self, tmp_path):
- """LFM2 audio model (via LFM2AudioModel architecture) is discovered as audio_sts."""
- sts_dir = tmp_path / "LFM2.5-Audio-1B"
- _make_model(sts_dir, {
- "model_type": "lfm2_audio",
- "architectures": ["LFM2AudioModel"],
- })
-
- models = discover_models(tmp_path)
- assert "LFM2.5-Audio-1B" in models
- assert models["LFM2.5-Audio-1B"].model_type == "audio_sts"
-
def test_discover_all_audio_types_together(self, tmp_path):
"""STT, TTS, and STS models coexist in the same discovery result."""
_make_model(tmp_path / "llama-3b", {"model_type": "llama"})
diff --git a/tests/test_audio_sts.py b/tests/test_audio_sts.py
index ecaef19eaf..604360e423 100644
--- a/tests/test_audio_sts.py
+++ b/tests/test_audio_sts.py
@@ -273,8 +273,14 @@ def test_engine_error_returns_500(self, server_sts_client):
class TestSTSModelAliasResolution:
"""Verify that STS endpoint resolves model aliases (#489)."""
- def test_process_resolves_alias(self):
- """POST /v1/audio/process with alias resolves to real model ID."""
+ @pytest.mark.parametrize(
+ "requested_model",
+ [
+ pytest.param("denoise", id="alias"),
+ pytest.param("MossFormer2-SE", id="direct-model-id"),
+ ],
+ )
+ def test_process_resolves_model(self, requested_model):
from omlx.server import app
_ensure_audio_routes(app)
@@ -298,38 +304,7 @@ def test_process_resolves_alias(self):
with TestClient(app, raise_server_exceptions=False) as client:
response = client.post(
"/v1/audio/process",
- data={"model": "denoise"},
- files={"file": ("test.wav", TINY_WAV, "audio/wav")},
- )
- assert response.status_code == 200
- mock_pool.get_engine.assert_awaited_once_with("MossFormer2-SE")
-
- def test_process_direct_model_id(self):
- """POST /v1/audio/process with direct model ID works without alias."""
- from omlx.server import app
-
- _ensure_audio_routes(app)
-
- mock_pool = _make_mock_pool(model_id="MossFormer2-SE")
- mock_pool.resolve_model_id = MagicMock(
- return_value="MossFormer2-SE"
- )
-
- with patch("omlx.server._server_state") as mock_state:
- mock_state.engine_pool = mock_pool
- mock_state.global_settings = None
- mock_state.distributed_inference_enabled = False
- mock_state.process_memory_enforcer = None
- mock_state.gpu_power_limiter = None
- mock_state.hf_downloader = None
- mock_state.ms_downloader = None
- mock_state.mcp_manager = None
- mock_state.api_key = None
- mock_state.settings_manager = MagicMock()
- with TestClient(app, raise_server_exceptions=False) as client:
- response = client.post(
- "/v1/audio/process",
- data={"model": "MossFormer2-SE"},
+ data={"model": requested_model},
files={"file": ("test.wav", TINY_WAV, "audio/wav")},
)
assert response.status_code == 200
diff --git a/tests/test_audio_stt.py b/tests/test_audio_stt.py
index 3dd1154b3d..d6dba44b7a 100644
--- a/tests/test_audio_stt.py
+++ b/tests/test_audio_stt.py
@@ -1408,47 +1408,19 @@ async def capture_transcribe(path, **kwargs):
class TestSTTModelAliasResolution:
"""Verify that STT endpoint resolves model aliases (#489)."""
- def test_transcription_resolves_alias(self):
- """POST /v1/audio/transcriptions with alias resolves to real model ID."""
- from omlx.server import app
-
- _ensure_audio_routes(app)
-
- mock_pool = _make_mock_pool(model_id="Qwen3-ASR-1.7B-bf16")
- mock_pool.resolve_model_id = MagicMock(
- return_value="Qwen3-ASR-1.7B-bf16"
- )
-
- with patch("omlx.server._server_state") as mock_state:
- mock_state.engine_pool = mock_pool
- mock_state.global_settings = None
- mock_state.distributed_inference_enabled = False
- mock_state.process_memory_enforcer = None
- mock_state.gpu_power_limiter = None
- mock_state.hf_downloader = None
- mock_state.ms_downloader = None
- mock_state.mcp_manager = None
- mock_state.api_key = None
- mock_state.settings_manager = MagicMock()
- with TestClient(app, raise_server_exceptions=False) as client:
- response = client.post(
- "/v1/audio/transcriptions",
- data={"model": "whisper"},
- files={"file": ("test.wav", TINY_WAV, "audio/wav")},
- )
- assert response.status_code == 200
- mock_pool.get_engine.assert_awaited_once_with(
- "Qwen3-ASR-1.7B-bf16"
- )
-
- def test_transcription_direct_model_id(self):
- """POST /v1/audio/transcriptions with direct model ID works without alias."""
+ @pytest.mark.parametrize(
+ "requested_model",
+ [
+ pytest.param("whisper", id="alias"),
+ pytest.param("Qwen3-ASR-1.7B-bf16", id="direct-model-id"),
+ ],
+ )
+ def test_transcription_resolves_model(self, requested_model):
from omlx.server import app
_ensure_audio_routes(app)
mock_pool = _make_mock_pool(model_id="Qwen3-ASR-1.7B-bf16")
- # resolve_model_id returns the same ID when no alias matches
mock_pool.resolve_model_id = MagicMock(
return_value="Qwen3-ASR-1.7B-bf16"
)
@@ -1467,7 +1439,7 @@ def test_transcription_direct_model_id(self):
with TestClient(app, raise_server_exceptions=False) as client:
response = client.post(
"/v1/audio/transcriptions",
- data={"model": "Qwen3-ASR-1.7B-bf16"},
+ data={"model": requested_model},
files={"file": ("test.wav", TINY_WAV, "audio/wav")},
)
assert response.status_code == 200
@@ -1475,7 +1447,6 @@ def test_transcription_direct_model_id(self):
"Qwen3-ASR-1.7B-bf16"
)
-
# ---------------------------------------------------------------------------
# TestSTTProcessorErrors — actionable errors for MLX STT models (#800)
# ---------------------------------------------------------------------------
diff --git a/tests/test_cli.py b/tests/test_cli.py
index bd7ac5ecef..a5b106c95c 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -225,207 +225,98 @@ def test_no_command_shows_help(self):
class TestServeCommandOptions:
"""Tests for serve command options via help output."""
- def test_serve_has_model_dir_option(self):
- """Test that serve command has --model-dir option."""
+ @pytest.fixture(scope="class")
+ def serve_help(self):
result = subprocess.run(
[sys.executable, "-m", "omlx.cli", "serve", "--help"],
capture_output=True,
text=True,
timeout=10,
)
- assert "--model-dir" in result.stdout
+ assert result.returncode == 0, result.stderr
+ return result.stdout
- def test_serve_has_no_max_memory_options(self):
- """The --max-model-memory and --max-process-memory CLI flags are removed."""
- result = subprocess.run(
- [sys.executable, "-m", "omlx.cli", "serve", "--help"],
- capture_output=True,
- text=True,
- timeout=10,
- )
- assert "--max-model-memory" not in result.stdout
- assert "--max-process-memory" not in result.stdout
-
- def test_serve_has_memory_guard_options(self):
- """Test that serve command exposes memory guard controls."""
- result = subprocess.run(
- [sys.executable, "-m", "omlx.cli", "serve", "--help"],
- capture_output=True,
- text=True,
- timeout=10,
- )
- assert "--memory-guard" in result.stdout
- assert "--memory-guard-gb" in result.stdout
- assert "safe" in result.stdout
- assert "balanced" in result.stdout
- assert "aggressive" in result.stdout
-
- def test_serve_no_model_specific_options(self):
- """Test that serve command does not have model-specific options (managed via admin page)."""
- result = subprocess.run(
- [sys.executable, "-m", "omlx.cli", "serve", "--help"],
- capture_output=True,
- text=True,
- timeout=10,
- )
- # These options are now managed via admin page, not CLI
- assert "--pin" not in result.stdout
- assert "--default-model" not in result.stdout
- assert "--max-tokens" not in result.stdout
- assert "--temperature" not in result.stdout
- assert "--top-p" not in result.stdout
- assert "--top-k" not in result.stdout
- assert "--force-sampling" not in result.stdout
-
- def test_serve_has_host_port_options(self):
- """Test that serve command has --host and --port options."""
- result = subprocess.run(
- [sys.executable, "-m", "omlx.cli", "serve", "--help"],
- capture_output=True,
- text=True,
- timeout=10,
- )
- assert "--host" in result.stdout
- assert "--port" in result.stdout
-
- def test_serve_has_scheduler_options(self):
- """Test that serve command has scheduler options."""
- result = subprocess.run(
- [sys.executable, "-m", "omlx.cli", "serve", "--help"],
- capture_output=True,
- text=True,
- timeout=10,
- )
- 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."""
- result = subprocess.run(
- [sys.executable, "-m", "omlx.cli", "serve", "--help"],
- capture_output=True,
- text=True,
- timeout=10,
- )
- assert "--paged-ssd-cache-dir" in result.stdout
- assert "--paged-ssd-cache-max-size" in result.stdout
- assert "--no-cache" in result.stdout
-
- def test_serve_has_mcp_option(self):
- """Test that serve command has --mcp-config option."""
- result = subprocess.run(
- [sys.executable, "-m", "omlx.cli", "serve", "--help"],
- capture_output=True,
- text=True,
- timeout=10,
- )
- assert "--mcp-config" in result.stdout
-
- def test_serve_has_base_path_option(self):
- """Test that serve command has --base-path option."""
- result = subprocess.run(
- [sys.executable, "-m", "omlx.cli", "serve", "--help"],
- capture_output=True,
- text=True,
- timeout=10,
- )
- assert "--base-path" in result.stdout
+ @pytest.mark.parametrize(
+ "text",
+ [
+ "--model-dir",
+ "--memory-guard",
+ "--memory-guard-gb",
+ "safe",
+ "balanced",
+ "aggressive",
+ "--host",
+ "--port",
+ "--max-concurrent-requests",
+ "--embedding-batch-size",
+ "--max-audio-upload-size",
+ "settings.json",
+ "--paged-ssd-cache-dir",
+ "--paged-ssd-cache-max-size",
+ "--no-cache",
+ "--mcp-config",
+ "--base-path",
+ "--api-key",
+ ],
+ )
+ def test_serve_help_includes(self, serve_help, text):
+ assert text in serve_help
- def test_serve_has_api_key_option(self):
- """Test that serve command has --api-key option."""
- result = subprocess.run(
- [sys.executable, "-m", "omlx.cli", "serve", "--help"],
- capture_output=True,
- text=True,
- timeout=10,
- )
- assert "--api-key" in result.stdout
+ @pytest.mark.parametrize(
+ "text",
+ [
+ "--max-model-memory",
+ "--max-process-memory",
+ "--pin",
+ "--default-model",
+ "--max-tokens",
+ "--temperature",
+ "--top-p",
+ "--top-k",
+ "--force-sampling",
+ "Default: 100MB",
+ ],
+ )
+ def test_serve_help_excludes(self, serve_help, text):
+ assert text not in serve_help
class TestLaunchCommandOptions:
"""Tests for launch command options via help output."""
- def test_launch_has_host_port_options(self):
- """Test that launch command has --host and --port options."""
- result = subprocess.run(
- [sys.executable, "-m", "omlx.cli", "launch", "--help"],
- capture_output=True,
- text=True,
- timeout=10,
- )
- assert result.returncode == 0
- assert "--host" in result.stdout
- assert "--port" in result.stdout
-
- def test_launch_has_model_option(self):
- """Test that launch command has --model option."""
- result = subprocess.run(
- [sys.executable, "-m", "omlx.cli", "launch", "--help"],
- capture_output=True,
- text=True,
- timeout=10,
- )
- assert "--model" in result.stdout
-
- def test_launch_has_claude_tier_options(self):
- """Claude tier options should remain accepted for copied app commands."""
- result = subprocess.run(
- [sys.executable, "-m", "omlx.cli", "launch", "--help"],
- capture_output=True,
- text=True,
- timeout=10,
- )
- assert "--opus" in result.stdout
- assert "--sonnet" in result.stdout
- assert "--haiku" in result.stdout
-
- def test_launch_has_cross_session_option(self):
+ @pytest.fixture(scope="class")
+ def launch_help(self):
result = subprocess.run(
[sys.executable, "-m", "omlx.cli", "launch", "--help"],
capture_output=True,
text=True,
timeout=10,
)
- assert "--cross-session" in result.stdout
+ assert result.returncode == 0, result.stderr
+ return result.stdout
- def test_launch_lists_hermes(self):
- """Test that launch help lists Hermes as an available integration."""
- result = subprocess.run(
- [sys.executable, "-m", "omlx.cli", "launch", "--help"],
- capture_output=True,
- text=True,
- timeout=10,
- )
- assert result.returncode == 0
- assert "hermes" in result.stdout
- assert "Hermes Agent" in result.stdout
-
- def test_launch_lists_codex_app(self):
- """Test that launch help lists the Codex Desktop App target."""
- result = subprocess.run(
- [sys.executable, "-m", "omlx.cli", "launch", "--help"],
- capture_output=True,
- text=True,
- timeout=10,
- )
- assert result.returncode == 0
- assert "codex_app" in result.stdout
- assert "Codex App" in " ".join(result.stdout.split())
+ @pytest.mark.parametrize(
+ "text",
+ [
+ "--host",
+ "--port",
+ "--model",
+ "--opus",
+ "--sonnet",
+ "--haiku",
+ "--cross-session",
+ "hermes",
+ "Hermes Agent",
+ "codex_app",
+ "dsh",
+ ],
+ )
+ def test_launch_help_includes(self, launch_help, text):
+ assert text in launch_help
- def test_launch_lists_dsh(self):
- """Test that launch help lists the DeepSeek Harness target."""
- result = subprocess.run(
- [sys.executable, "-m", "omlx.cli", "launch", "--help"],
- capture_output=True,
- text=True,
- timeout=10,
- )
- assert result.returncode == 0
- assert "dsh" in result.stdout
- assert "DeepSeek Harness" in " ".join(result.stdout.split())
+ @pytest.mark.parametrize("text", ["Codex App", "DeepSeek Harness"])
+ def test_launch_help_includes_wrapped_description(self, launch_help, text):
+ assert text in " ".join(launch_help.split())
class TestLaunchCommandFunction:
diff --git a/tests/test_cluster_interpreter_parity.py b/tests/test_cluster_interpreter_parity.py
index 612f417bcb..49096ccb68 100644
--- a/tests/test_cluster_interpreter_parity.py
+++ b/tests/test_cluster_interpreter_parity.py
@@ -209,38 +209,34 @@ def runner(argv, **_kwargs):
return runner
-def test_preflight_allows_a_different_python_minor_and_records_it(
- monkeypatch, stub_admission
-):
- monkeypatch.setattr(platform, "python_version", lambda: "3.11.9")
-
- results = preflight_remote_hosts(
- _deployment(),
- python_executable=PEER_PYTHON,
- runner=_preflight_runner("3.12.13"),
- )
-
- assert results[0]["runtime_warnings"] == []
- assert results[1]["runtime_warnings"] == [
- "python minor differs: local=3.11.9 remote=3.12.13"
- ]
-
-
-def test_preflight_allows_a_patch_difference_and_records_it(
- monkeypatch, stub_admission
+@pytest.mark.parametrize(
+ ("local_version", "remote_version", "warning"),
+ [
+ pytest.param(
+ "3.11.9", "3.12.13",
+ "python minor differs: local=3.11.9 remote=3.12.13",
+ id="different-minor",
+ ),
+ pytest.param(
+ "3.12.13", "3.12.14",
+ "python patch differs: local=3.12.13 remote=3.12.14",
+ id="different-patch",
+ ),
+ ],
+)
+def test_preflight_allows_python_version_difference_and_records_it(
+ monkeypatch, stub_admission, local_version, remote_version, warning
):
- monkeypatch.setattr(platform, "python_version", lambda: "3.12.13")
+ monkeypatch.setattr(platform, "python_version", lambda: local_version)
results = preflight_remote_hosts(
_deployment(),
python_executable=PEER_PYTHON,
- runner=_preflight_runner("3.12.14"),
+ runner=_preflight_runner(remote_version),
)
assert results[0]["runtime_warnings"] == []
- assert results[1]["runtime_warnings"] == [
- "python patch differs: local=3.12.13 remote=3.12.14"
- ]
+ assert results[1]["runtime_warnings"] == [warning]
def test_preflight_refuses_a_rank_that_reports_no_interpreter(
diff --git a/tests/test_cluster_tensor_parallel.py b/tests/test_cluster_tensor_parallel.py
index a30ec0c1d0..7e0001784e 100644
--- a/tests/test_cluster_tensor_parallel.py
+++ b/tests/test_cluster_tensor_parallel.py
@@ -1,5 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
+import pytest
+
from omlx.cluster.planner import (
ModelLayout,
NodeBudget,
@@ -74,38 +76,19 @@ def test_plan_hybrid_rank_mapping():
assert by_rank[3].tensor_parallel_rank == 1
-def test_plan_hybrid_not_divisible():
- """World size not divisible by TP size should raise PlanningError."""
- model = ModelLayout(
- source="test",
- fixed_weight_bytes=1 * 1024**3,
- layer_weight_bytes=(2 * 1024**3,) * 32,
- tensor_parallel_heads=32,
- )
- nodes = [
- NodeBudget(
- node_id=f"node-{i}",
- capacity_bytes=32 * 1024**3,
- reserve_bytes=2 * 1024**3,
- rank=i,
- )
- for i in range(3)
- ]
-
- try:
- plan_hybrid(model, nodes, tensor_parallel_size=2)
- raise AssertionError("should have raised PlanningError")
- except PlanningError as e:
- assert "not divisible" in str(e)
-
-
-def test_plan_hybrid_heads_not_divisible():
- """TP size that does not divide heads should raise PlanningError."""
+@pytest.mark.parametrize(
+ ("node_count", "heads"),
+ [
+ pytest.param(3, 32, id="world-size-not-divisible"),
+ pytest.param(4, 33, id="heads-not-divisible"),
+ ],
+)
+def test_plan_hybrid_not_divisible(node_count, heads):
model = ModelLayout(
source="test",
fixed_weight_bytes=1 * 1024**3,
layer_weight_bytes=(2 * 1024**3,) * 32,
- tensor_parallel_heads=33, # Not divisible by 2
+ tensor_parallel_heads=heads,
)
nodes = [
NodeBudget(
@@ -114,14 +97,11 @@ def test_plan_hybrid_heads_not_divisible():
reserve_bytes=2 * 1024**3,
rank=i,
)
- for i in range(4)
+ for i in range(node_count)
]
- try:
+ with pytest.raises(PlanningError, match="not divisible"):
plan_hybrid(model, nodes, tensor_parallel_size=2)
- raise AssertionError("should have raised PlanningError")
- except PlanningError as e:
- assert "not divisible" in str(e)
def test_plan_hybrid_single_node():
diff --git a/tests/test_context_window.py b/tests/test_context_window.py
index 4e7ccb758e..54e12bab20 100644
--- a/tests/test_context_window.py
+++ b/tests/test_context_window.py
@@ -41,35 +41,26 @@ def test_returns_global_default(self):
result = get_max_context_window()
assert result == 32768
- def test_model_setting_overrides_global(self):
- """Test model-specific setting takes priority over global."""
+ @pytest.mark.parametrize(
+ ("global_limit", "model_limit", "expected"),
+ [
+ pytest.param(32768, 4096, 4096, id="model-overrides-global"),
+ pytest.param(65536, None, 65536, id="unset-model-falls-back"),
+ ],
+ )
+ def test_model_setting_priority(self, global_limit, model_limit, expected):
from omlx.server import get_max_context_window
- state = self._make_server_state(global_max_ctx=32768)
+ state = self._make_server_state(global_max_ctx=global_limit)
mock_manager = MagicMock()
mock_manager.get_settings_for_request.return_value = ModelSettings(
- max_context_window=4096
+ max_context_window=model_limit
)
state.settings_manager = mock_manager
with patch("omlx.server._server_state", state):
result = get_max_context_window("test-model")
- assert result == 4096
-
- def test_falls_back_to_global_when_model_not_set(self):
- """Test falls back to global when model has no max_context_window."""
- from omlx.server import get_max_context_window
-
- state = self._make_server_state(global_max_ctx=65536)
- mock_manager = MagicMock()
- mock_manager.get_settings_for_request.return_value = ModelSettings(
- max_context_window=None
- )
- state.settings_manager = mock_manager
-
- with patch("omlx.server._server_state", state):
- result = get_max_context_window("test-model")
- assert result == 65536
+ assert result == expected
def test_no_model_id_returns_global(self):
"""Test returns global when model_id is None."""
@@ -102,41 +93,25 @@ def _mount_native_and_policy(
state.engine_pool = mock_pool
return state
- def test_policy_unset_native_wins_unchanged(self):
- """With ``max_context_window_policy`` unset, the model's
- native context length is returned verbatim — existing
- installs see no behavior change after this PR."""
- from omlx.server import get_max_context_window
-
- state = self._mount_native_and_policy(
- native_ctx=262_144, policy_cap=None
- )
- with patch("omlx.server._server_state", state):
- assert get_max_context_window("big-model") == 262_144
-
- def test_policy_set_clamps_native(self):
- """With ``max_context_window_policy=128_000`` and a model that
- natively declares 256 K, the effective cap is the policy."""
- from omlx.server import get_max_context_window
-
- state = self._mount_native_and_policy(
- native_ctx=262_144, policy_cap=128_000
- )
- with patch("omlx.server._server_state", state):
- assert get_max_context_window("big-model") == 128_000, (
- "Policy of 128k must clamp a model that natively declares 256k"
- )
-
- def test_policy_set_native_below_policy_wins(self):
- """When the model's native length is already below the policy,
- the native value wins — policy is a ceiling, not a floor."""
+ @pytest.mark.parametrize(
+ ("native_context", "policy_cap", "expected"),
+ [
+ pytest.param(262_144, None, 262_144, id="policy-unset"),
+ pytest.param(262_144, 128_000, 128_000, id="policy-clamps-native"),
+ pytest.param(32_768, 128_000, 32_768, id="native-below-policy"),
+ pytest.param(None, 16_000, 32_768, id="fallback-not-clamped"),
+ ],
+ )
+ def test_policy_only_caps_native_context(
+ self, native_context, policy_cap, expected
+ ):
from omlx.server import get_max_context_window
state = self._mount_native_and_policy(
- native_ctx=32_768, policy_cap=128_000
+ native_ctx=native_context, policy_cap=policy_cap
)
with patch("omlx.server._server_state", state):
- assert get_max_context_window("small-model") == 32_768
+ assert get_max_context_window("test-model") == expected
def test_per_model_override_escapes_policy(self):
"""A per-model override is the operator's explicit per-model
@@ -158,36 +133,23 @@ def test_per_model_override_escapes_policy(self):
"Per-model override must escape the policy clamp"
)
- def test_policy_does_not_apply_to_fallback_path(self):
- """When the model has no discoverable native context AND no
- per-model override, the fallback default applies — the policy
- is documented as clamping the *native* path only. Existing
- ``settings.json`` files with the historical 32768 fallback
- therefore keep working unchanged even when a policy is later
- added to the install."""
- from omlx.server import get_max_context_window
-
- # native_ctx=None: model config doesn't expose a context length
- state = self._mount_native_and_policy(
- native_ctx=None, policy_cap=16_000
- )
- with patch("omlx.server._server_state", state):
- # Fallback (32768) returned, not the policy (16_000).
- assert get_max_context_window("no-native-model") == 32_768
-
- def test_loaded_engine_plan_lowers_the_limit(self):
+ @pytest.mark.parametrize(
+ ("engine_limit", "expected"),
+ [
+ pytest.param(77_817, 77_817, id="engine-lowers-native-limit"),
+ pytest.param(300_000, 262_144, id="engine-cannot-raise-native-limit"),
+ ],
+ )
+ def test_loaded_engine_plan_caps_the_limit(self, engine_limit, expected):
"""An engine that fits its context to memory (Splash) caps the limit,
so a longer prompt gets the standard overflow error from oMLX."""
from omlx.server import get_max_context_window
state = self._mount_native_and_policy(native_ctx=262_144, policy_cap=None)
engine = state.engine_pool.get_entry.return_value.engine
- engine.max_context_tokens = 77_817
+ engine.max_context_tokens = engine_limit
with patch("omlx.server._server_state", state):
- assert get_max_context_window("splash-model") == 77_817
- engine.max_context_tokens = 300_000
- with patch("omlx.server._server_state", state):
- assert get_max_context_window("splash-model") == 262_144
+ assert get_max_context_window("splash-model") == expected
class TestValidateContextWindow:
@@ -201,23 +163,19 @@ def _make_server_state(self, global_max_ctx=32768):
state.settings_manager = None
return state
- def test_passes_when_under_limit(self):
- """Test no exception when token count is under limit."""
- from omlx.server import validate_context_window
-
- state = self._make_server_state(global_max_ctx=1000)
- with patch("omlx.server._server_state", state):
- # Should not raise
- validate_context_window(500)
-
- def test_passes_at_exact_limit(self):
- """Test no exception when token count equals limit."""
+ @pytest.mark.parametrize(
+ "token_count",
+ [
+ pytest.param(500, id="under-limit"),
+ pytest.param(1000, id="exact-limit"),
+ ],
+ )
+ def test_passes_within_limit(self, token_count):
from omlx.server import validate_context_window
state = self._make_server_state(global_max_ctx=1000)
with patch("omlx.server._server_state", state):
- # Should not raise (equal is OK)
- validate_context_window(1000)
+ validate_context_window(token_count)
def test_raises_when_over_limit(self):
"""Test HTTPException raised when token count exceeds limit."""
diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py
index 9a4fd0635b..f5662d67f0 100644
--- a/tests/test_exceptions.py
+++ b/tests/test_exceptions.py
@@ -316,34 +316,45 @@ def test_mcp_tool_execution_error(self):
class TestIsCacheCorruptionError:
"""Test cases for is_cache_corruption_error helper function."""
- def test_none_type_pattern(self):
- """Test detection of NoneType subscript error."""
- error = TypeError("'NoneType' object is not subscriptable")
- assert is_cache_corruption_error(error) is True
-
- def test_batch_kv_cache_pattern(self):
- """Test detection of BatchKVCache error."""
- error = RuntimeError("BatchKVCache.keys returned None")
- assert is_cache_corruption_error(error) is True
-
- def test_kv_cache_pattern(self):
- """Test detection of KVCache error."""
- error = ValueError("KVCache data is invalid")
- assert is_cache_corruption_error(error) is True
-
- def test_cache_keys_pattern(self):
- """Test detection of cache.keys error."""
- error = AttributeError("cache.keys is not available")
- assert is_cache_corruption_error(error) is True
-
- def test_cache_values_pattern(self):
- """Test detection of cache.values error."""
- error = AttributeError("cache.values returned empty")
- assert is_cache_corruption_error(error) is True
-
- def test_attribute_error_none_attribute(self):
- """Test detection of NoneType attribute access error."""
- error = AttributeError("'NoneType' object has no attribute 'shape'")
+ @pytest.mark.parametrize(
+ "error",
+ [
+ pytest.param(
+ TypeError("'NoneType' object is not subscriptable"),
+ id="none-subscript",
+ ),
+ pytest.param(
+ RuntimeError("BatchKVCache.keys returned None"), id="batch-kv-cache"
+ ),
+ pytest.param(ValueError("KVCache data is invalid"), id="kv-cache"),
+ pytest.param(
+ AttributeError("cache.keys is not available"), id="cache-keys"
+ ),
+ pytest.param(
+ AttributeError("cache.values returned empty"), id="cache-values"
+ ),
+ pytest.param(
+ AttributeError("'NoneType' object has no attribute 'shape'"),
+ id="none-attribute",
+ ),
+ pytest.param(
+ ValueError("Shapes (1,8,256,128) and (1,8,512,128) are not broadcastable"),
+ id="not-broadcastable",
+ ),
+ pytest.param(
+ ValueError(
+ "[broadcast_shapes] Shapes (8,1,625,2674) and (8,8,625,3697) "
+ "cannot be broadcast."
+ ),
+ id="mlx-broadcast-shapes-issue-79",
+ ),
+ pytest.param(
+ ValueError("shape mismatch in cache concatenation"),
+ id="shape-mismatch",
+ ),
+ ],
+ )
+ def test_corruption_patterns(self, error):
assert is_cache_corruption_error(error) is True
def test_none_type_not_iterable_pattern(self):
@@ -358,39 +369,18 @@ def test_none_type_not_iterable_pattern(self):
error = TypeError("'NoneType' object is not iterable")
assert is_cache_corruption_error(error) is True
- def test_value_error_not_broadcastable(self):
- """Test detection of shape broadcast error."""
- error = ValueError(
- "Shapes (1,8,256,128) and (1,8,512,128) are not broadcastable"
- )
- assert is_cache_corruption_error(error) is True
-
- def test_value_error_cannot_be_broadcast(self):
- """Test detection of MLX broadcast_shapes error (Issue #79)."""
- error = ValueError(
- "[broadcast_shapes] Shapes (8,1,625,2674) and (8,8,625,3697) "
- "cannot be broadcast."
- )
- assert is_cache_corruption_error(error) is True
-
- def test_value_error_shape_mismatch(self):
- """Test detection of shape mismatch error."""
- error = ValueError("shape mismatch in cache concatenation")
- assert is_cache_corruption_error(error) is True
-
- def test_non_corruption_error(self):
- """Test that non-corruption errors return False."""
- error = ValueError("Invalid temperature value")
- assert is_cache_corruption_error(error) is False
-
- def test_attribute_error_non_corruption(self):
- """Non-corruption AttributeError should not match."""
- error = AttributeError("'str' object has no attribute 'encode'")
- assert is_cache_corruption_error(error) is False
-
- def test_unrelated_error(self):
- """Test completely unrelated error."""
- error = FileNotFoundError("Model file not found")
+ @pytest.mark.parametrize(
+ "error",
+ [
+ pytest.param(ValueError("Invalid temperature value"), id="invalid-input"),
+ pytest.param(
+ AttributeError("'str' object has no attribute 'encode'"),
+ id="unrelated-attribute",
+ ),
+ pytest.param(FileNotFoundError("Model file not found"), id="missing-model"),
+ ],
+ )
+ def test_non_corruption_errors(self, error):
assert is_cache_corruption_error(error) is False
diff --git a/tests/test_hf_downloader.py b/tests/test_hf_downloader.py
index 8f6f969697..306bf7e17f 100644
--- a/tests/test_hf_downloader.py
+++ b/tests/test_hf_downloader.py
@@ -2591,27 +2591,16 @@ async def test_search_handles_no_safetensors(self):
assert item["params"] is None
@pytest.mark.asyncio
- async def test_search_most_params_sort(self):
- """Test most_params sorting works correctly."""
- small = _make_mock_model("org/small", disk_size_bytes=2_000_000_000, downloads=100)
- large = _make_mock_model("org/large", disk_size_bytes=20_000_000_000, downloads=100)
-
- with patch("omlx.admin.hf_downloader.HfApi") as mock_api_cls:
- mock_api = MagicMock()
- mock_api.list_models.return_value = [small, large]
- mock_api_cls.return_value = mock_api
-
- result = await HFDownloader.search_models(
- query="model", sort="most_params"
- )
-
- # Large should come first
- assert result["models"][0]["repo_id"] == "org/large"
- assert result["models"][1]["repo_id"] == "org/small"
-
- @pytest.mark.asyncio
- async def test_search_least_params_sort(self):
- """Test least_params sorting works correctly."""
+ @pytest.mark.parametrize(
+ ("sort", "expected_order"),
+ [
+ pytest.param("most_params", ["org/large", "org/small"], id="most-params"),
+ pytest.param("least_params", ["org/small", "org/large"], id="least-params"),
+ pytest.param("largest", ["org/large", "org/small"], id="largest"),
+ pytest.param("smallest", ["org/small", "org/large"], id="smallest"),
+ ],
+ )
+ async def test_search_size_and_parameter_sorting(self, sort, expected_order):
small = _make_mock_model("org/small", disk_size_bytes=2_000_000_000, downloads=100)
large = _make_mock_model("org/large", disk_size_bytes=20_000_000_000, downloads=100)
@@ -2620,13 +2609,9 @@ async def test_search_least_params_sort(self):
mock_api.list_models.return_value = [small, large]
mock_api_cls.return_value = mock_api
- result = await HFDownloader.search_models(
- query="model", sort="least_params"
- )
+ result = await HFDownloader.search_models(query="model", sort=sort)
- # Small should come first
- assert result["models"][0]["repo_id"] == "org/small"
- assert result["models"][1]["repo_id"] == "org/large"
+ assert [model["repo_id"] for model in result["models"]] == expected_order
@pytest.mark.asyncio
async def test_search_respects_limit(self):
@@ -2647,44 +2632,6 @@ async def test_search_respects_limit(self):
assert len(result["models"]) == 5
- @pytest.mark.asyncio
- async def test_search_largest_sort(self):
- """Test largest sorting works correctly."""
- small = _make_mock_model("org/small", disk_size_bytes=2_000_000_000, downloads=100)
- large = _make_mock_model("org/large", disk_size_bytes=20_000_000_000, downloads=100)
-
- with patch("omlx.admin.hf_downloader.HfApi") as mock_api_cls:
- mock_api = MagicMock()
- mock_api.list_models.return_value = [small, large]
- mock_api_cls.return_value = mock_api
-
- result = await HFDownloader.search_models(
- query="model", sort="largest"
- )
-
- # Large should come first
- assert result["models"][0]["repo_id"] == "org/large"
- assert result["models"][1]["repo_id"] == "org/small"
-
- @pytest.mark.asyncio
- async def test_search_smallest_sort(self):
- """Test smallest sorting works correctly."""
- small = _make_mock_model("org/small", disk_size_bytes=2_000_000_000, downloads=100)
- large = _make_mock_model("org/large", disk_size_bytes=20_000_000_000, downloads=100)
-
- with patch("omlx.admin.hf_downloader.HfApi") as mock_api_cls:
- mock_api = MagicMock()
- mock_api.list_models.return_value = [small, large]
- mock_api_cls.return_value = mock_api
-
- result = await HFDownloader.search_models(
- query="model", sort="smallest"
- )
-
- # Small should come first
- assert result["models"][0]["repo_id"] == "org/small"
- assert result["models"][1]["repo_id"] == "org/large"
-
@pytest.mark.asyncio
async def test_search_sort_by_size(self):
"""Test sort_by_size parameter works correctly."""
diff --git a/tests/test_hybrid_cache.py b/tests/test_hybrid_cache.py
index fdc0507d78..734c23b584 100644
--- a/tests/test_hybrid_cache.py
+++ b/tests/test_hybrid_cache.py
@@ -165,48 +165,25 @@ def test_hybrid_model_with_rotating(self, prefix_cache):
result = prefix_cache._apply_window_padding(16, config)
assert result == 12
- def test_padding_exceeds_matched(self, prefix_cache):
- """Test when padding blocks exceed matched blocks, returns 0."""
- config = ModelCacheConfig.from_type_list(
- ["KVCache", "RotatingKVCache"]
- )
- config._max_window_size = 1024
-
- # 3 blocks matched, need 4 for padding -> 0
- result = prefix_cache._apply_window_padding(3, config)
- assert result == 0
-
- def test_exact_padding(self, prefix_cache):
- """Test when matched blocks exactly equal padding blocks."""
- config = ModelCacheConfig.from_type_list(
- ["KVCache", "RotatingKVCache"]
- )
- config._max_window_size = 1024
-
- # 4 blocks matched, need 4 for padding -> 0
- result = prefix_cache._apply_window_padding(4, config)
- assert result == 0
-
- def test_window_size_not_multiple_of_block_size(self, prefix_cache):
- """Test with window_size not a multiple of block_size."""
- config = ModelCacheConfig.from_type_list(
- ["KVCache", "RotatingKVCache"]
- )
- config._max_window_size = 1000 # Not a multiple of 256
-
- # ceil(1000/256) = 4 padding blocks
- result = prefix_cache._apply_window_padding(16, config)
- assert result == 12
-
- def test_window_size_zero(self, prefix_cache):
- """Test with window_size=0 returns all blocks."""
+ @pytest.mark.parametrize(
+ ("matched_blocks", "window_size", "expected_blocks"),
+ [
+ pytest.param(3, 1024, 0, id="padding-exceeds-matched"),
+ pytest.param(4, 1024, 0, id="exact-padding"),
+ pytest.param(16, 1000, 12, id="partial-block-rounds-up"),
+ pytest.param(16, 0, 16, id="zero-window"),
+ ],
+ )
+ def test_rotating_window_padding(
+ self, prefix_cache, matched_blocks, window_size, expected_blocks
+ ):
config = ModelCacheConfig.from_type_list(
["KVCache", "RotatingKVCache"]
)
- config._max_window_size = 0
+ config._max_window_size = window_size
- result = prefix_cache._apply_window_padding(16, config)
- assert result == 16
+ result = prefix_cache._apply_window_padding(matched_blocks, config)
+ assert result == expected_blocks
def test_small_block_size(self):
"""Test with small block_size (more padding blocks needed)."""
diff --git a/tests/test_image_utils.py b/tests/test_image_utils.py
index 955f4dc25e..b698a57bc4 100644
--- a/tests/test_image_utils.py
+++ b/tests/test_image_utils.py
@@ -985,53 +985,33 @@ def test_rejects_oversized_encoded_length_early(self, monkeypatch):
with pytest.raises(InvalidRequestError, match="exceeds the maximum allowed limit"):
load_image(uri)
- def test_downscales_oversized_width_preserving_aspect(self, monkeypatch):
- """Wide image exceeding max side length is downscaled preserving aspect ratio."""
- from omlx.utils import image as module
-
- monkeypatch.setattr(module, "get_max_image_side_length", lambda: 1024)
- img = _make_test_image(2048, 1024, "red")
- b64 = _image_to_base64(img)
- uri = f"data:image/png;base64,{b64}"
-
- loaded = load_image(uri)
- assert loaded.size == (1024, 512)
-
- def test_downscales_oversized_height_preserving_aspect(self, monkeypatch):
- """Tall image exceeding max side length is downscaled preserving aspect ratio."""
- from omlx.utils import image as module
-
- monkeypatch.setattr(module, "get_max_image_side_length", lambda: 1024)
- img = _make_test_image(1024, 2048, "green")
- b64 = _image_to_base64(img)
- uri = f"data:image/png;base64,{b64}"
-
- loaded = load_image(uri)
- assert loaded.size == (512, 1024)
-
- def test_preserves_dimensions_within_limit(self, monkeypatch):
- """Images within limits are not resized."""
- from omlx.utils import image as module
-
- monkeypatch.setattr(module, "get_max_image_side_length", lambda: 2048)
- img = _make_test_image(800, 600, "yellow")
- b64 = _image_to_base64(img)
- uri = f"data:image/png;base64,{b64}"
-
- loaded = load_image(uri)
- assert loaded.size == (800, 600)
-
- def test_downscaling_disabled_when_side_limit_zero(self, monkeypatch):
- """Setting max side length to 0 disables downscaling."""
+ @pytest.mark.parametrize(
+ ("size", "color", "max_side", "expected_size"),
+ [
+ pytest.param(
+ (2048, 1024), "red", 1024, (1024, 512), id="wide-preserves-aspect"
+ ),
+ pytest.param(
+ (1024, 2048), "green", 1024, (512, 1024), id="tall-preserves-aspect"
+ ),
+ pytest.param(
+ (800, 600), "yellow", 2048, (800, 600), id="within-limit"
+ ),
+ pytest.param(
+ (3000, 1500), "purple", 0, (3000, 1500), id="downscaling-disabled"
+ ),
+ ],
+ )
+ def test_image_side_limit(self, monkeypatch, size, color, max_side, expected_size):
from omlx.utils import image as module
- monkeypatch.setattr(module, "get_max_image_side_length", lambda: 0)
- img = _make_test_image(3000, 1500, "purple")
+ monkeypatch.setattr(module, "get_max_image_side_length", lambda: max_side)
+ img = _make_test_image(*size, color)
b64 = _image_to_base64(img)
uri = f"data:image/png;base64,{b64}"
loaded = load_image(uri)
- assert loaded.size == (3000, 1500)
+ assert loaded.size == expected_size
def test_decompression_bomb_raises_invalid_request_error(self, monkeypatch):
"""Decompression bombs detected by Pillow raise InvalidRequestError."""
diff --git a/tests/test_mbpp_extract_code.py b/tests/test_mbpp_extract_code.py
index 284f403da4..945487f51f 100644
--- a/tests/test_mbpp_extract_code.py
+++ b/tests/test_mbpp_extract_code.py
@@ -8,6 +8,8 @@
from __future__ import annotations
+import pytest
+
from omlx.eval.mbpp import _extract_code
@@ -54,19 +56,16 @@ def area(r):
# ready
```"""
- result = _extract_code(response)
- assert "import math" in result
- assert "def area(r):" in result
- assert "return math.pi * r ** 2" in result
+ assert _extract_code(response) == (
+ "import math\n\ndef area(r):\n return math.pi * r ** 2\n\n# ready"
+ )
def test_fence_strips_surrounding_whitespace(self):
"""The .strip() inside the regex branch must remove leading/
trailing whitespace inside the fence — the subprocess executor
wants clean source."""
response = "```python\n\n def f():\n return 1\n\n```"
- result = _extract_code(response)
- assert not result.startswith("\n")
- assert not result.endswith("\n")
+ assert _extract_code(response) == "def f():\n return 1"
class TestHeuristicLineScan:
@@ -134,23 +133,19 @@ def test_includes_lines_after_code_start(self):
class TestFallback:
- def test_response_with_no_code_markers_returned_as_is(self):
- """When nothing matches, return the stripped response verbatim.
- This is a degraded but non-crashing fallback — the subprocess
- will surface the syntax error to the grader."""
- response = " I don't know how to solve this. "
- assert _extract_code(response) == "I don't know how to solve this."
-
- def test_empty_response_returns_empty_string(self):
- assert _extract_code("") == ""
-
- def test_whitespace_only_response_returns_empty(self):
- assert _extract_code(" \n\n \t ") == ""
-
- def test_lone_print_statement_falls_through(self):
- """A bare ``print(...)`` line doesn't start with def/class/
- import/from/# so the heuristic doesn't fire — falls back to
- returning the whole response. Documents the limitation."""
- response = "print('hello')"
- # Falls through to the whole-response fallback
- assert _extract_code(response) == "print('hello')"
+ @pytest.mark.parametrize(
+ ("response", "expected"),
+ [
+ pytest.param(
+ " I don't know how to solve this. ",
+ "I don't know how to solve this.",
+ id="no-code-markers",
+ ),
+ pytest.param("", "", id="empty"),
+ pytest.param(" \n\n \t ", "", id="whitespace-only"),
+ pytest.param("print('hello')", "print('hello')", id="bare-print"),
+ ],
+ )
+ def test_returns_stripped_response(self, response, expected):
+ """A bare print is not a code-start marker, so it uses the fallback."""
+ assert _extract_code(response) == expected
diff --git a/tests/test_mcp_config.py b/tests/test_mcp_config.py
index 06dfdde015..af263102b3 100644
--- a/tests/test_mcp_config.py
+++ b/tests/test_mcp_config.py
@@ -183,23 +183,19 @@ def test_custom_max_tool_calls(self):
cfg = validate_config({"max_tool_calls": 5})
assert cfg.max_tool_calls == 5
- def test_max_tool_calls_zero_rejected(self):
+ @pytest.mark.parametrize(
+ "value",
+ [
+ pytest.param(0, id="zero"),
+ pytest.param(-1, id="negative"),
+ pytest.param(3.5, id="non-integer"),
+ ],
+ )
+ def test_invalid_max_tool_calls_rejected(self, value):
with pytest.raises(
ValueError, match="'max_tool_calls' must be a positive integer"
):
- validate_config({"max_tool_calls": 0})
-
- def test_max_tool_calls_negative_rejected(self):
- with pytest.raises(
- ValueError, match="'max_tool_calls' must be a positive integer"
- ):
- validate_config({"max_tool_calls": -1})
-
- def test_max_tool_calls_non_int_rejected(self):
- with pytest.raises(
- ValueError, match="'max_tool_calls' must be a positive integer"
- ):
- validate_config({"max_tool_calls": 3.5})
+ validate_config({"max_tool_calls": value})
def test_max_tool_calls_bool_rejected_in_practice(self):
"""``isinstance(True, int)`` is True in Python, so True passes
@@ -208,31 +204,27 @@ def test_max_tool_calls_bool_rejected_in_practice(self):
cfg = validate_config({"max_tool_calls": True})
assert cfg.max_tool_calls is True # currently accepted; weird but expected
- def test_custom_default_timeout_int(self):
- cfg = validate_config({"default_timeout": 60})
- assert cfg.default_timeout == 60
-
- def test_custom_default_timeout_float(self):
- cfg = validate_config({"default_timeout": 45.5})
- assert cfg.default_timeout == 45.5
-
- def test_default_timeout_zero_rejected(self):
- with pytest.raises(
- ValueError, match="'default_timeout' must be a positive number"
- ):
- validate_config({"default_timeout": 0})
-
- def test_default_timeout_negative_rejected(self):
- with pytest.raises(
- ValueError, match="'default_timeout' must be a positive number"
- ):
- validate_config({"default_timeout": -1.0})
-
- def test_default_timeout_string_rejected(self):
+ @pytest.mark.parametrize(
+ "value",
+ [pytest.param(60, id="integer"), pytest.param(45.5, id="float")],
+ )
+ def test_custom_default_timeout(self, value):
+ cfg = validate_config({"default_timeout": value})
+ assert cfg.default_timeout == value
+
+ @pytest.mark.parametrize(
+ "value",
+ [
+ pytest.param(0, id="zero"),
+ pytest.param(-1.0, id="negative"),
+ pytest.param("30s", id="string"),
+ ],
+ )
+ def test_invalid_default_timeout_rejected(self, value):
with pytest.raises(
ValueError, match="'default_timeout' must be a positive number"
):
- validate_config({"default_timeout": "30s"})
+ validate_config({"default_timeout": value})
# =============================================================================
diff --git a/tests/test_openai_adapter.py b/tests/test_openai_adapter.py
index 75a5a921b8..d3a02a4e8b 100644
--- a/tests/test_openai_adapter.py
+++ b/tests/test_openai_adapter.py
@@ -58,11 +58,11 @@ def test_internal_message_with_optional_fields(self):
assert msg.tool_calls == tool_calls
assert msg.tool_call_id == "call_456"
- def test_internal_message_roles(self):
+ @pytest.mark.parametrize("role", ["user", "assistant", "system", "tool"])
+ def test_internal_message_roles(self, role):
"""Test InternalMessage with different roles."""
- for role in ["user", "assistant", "system", "tool"]:
- msg = InternalMessage(role=role, content=f"Content for {role}")
- assert msg.role == role
+ msg = InternalMessage(role=role, content=f"Content for {role}")
+ assert msg.role == role
# =========================================================================
# InternalRequest Tests
@@ -272,76 +272,38 @@ def test_parse_request_multiple_messages(self, adapter):
assert internal.messages[2].role == "assistant"
assert internal.messages[3].role == "user"
- def test_parse_request_with_temperature(self, adapter):
- """Test parsing request with temperature."""
+ @pytest.mark.parametrize(
+ ("field", "request_fields", "expected"),
+ [
+ pytest.param("temperature", {"temperature": 0.5}, 0.5, id="temperature"),
+ pytest.param(
+ "temperature", {"temperature": 0.0}, 0.0, id="zero-temperature"
+ ),
+ pytest.param("temperature", {}, 1.0, id="default-temperature"),
+ pytest.param("top_p", {"top_p": 0.9}, 0.9, id="top-p"),
+ pytest.param("min_p", {"min_p": 0.1}, 0.1, id="min-p"),
+ pytest.param(
+ "presence_penalty",
+ {"presence_penalty": 0.5},
+ 0.5,
+ id="presence-penalty",
+ ),
+ pytest.param("max_tokens", {"max_tokens": 500}, 500, id="max-tokens"),
+ pytest.param("max_tokens", {}, 2048, id="default-max-tokens"),
+ ],
+ )
+ def test_parse_request_sampling_parameters(
+ self, adapter, field, request_fields, expected
+ ):
request = ChatCompletionRequest(
model="test-model",
messages=[Message(role="user", content="Hello")],
- temperature=0.5,
+ **request_fields,
)
internal = adapter.parse_request(request)
- assert internal.temperature == 0.5
-
- def test_parse_request_with_zero_temperature(self, adapter):
- """Test parsing request with zero temperature."""
- request = ChatCompletionRequest(
- model="test-model",
- messages=[Message(role="user", content="Hello")],
- temperature=0.0,
- )
-
- internal = adapter.parse_request(request)
-
- assert internal.temperature == 0.0
-
- def test_parse_request_default_temperature(self, adapter):
- """Test parsing request without temperature uses default."""
- request = ChatCompletionRequest(
- model="test-model",
- messages=[Message(role="user", content="Hello")],
- )
-
- internal = adapter.parse_request(request)
-
- assert internal.temperature == 1.0
-
- def test_parse_request_with_top_p(self, adapter):
- """Test parsing request with top_p."""
- request = ChatCompletionRequest(
- model="test-model",
- messages=[Message(role="user", content="Hello")],
- top_p=0.9,
- )
-
- internal = adapter.parse_request(request)
-
- assert internal.top_p == 0.9
-
- def test_parse_request_with_min_p(self, adapter):
- """Test parsing request with min_p."""
- request = ChatCompletionRequest(
- model="test-model",
- messages=[Message(role="user", content="Hello")],
- min_p=0.1,
- )
-
- internal = adapter.parse_request(request)
-
- assert internal.min_p == 0.1
-
- def test_parse_request_with_presence_penalty(self, adapter):
- """Test parsing request with presence_penalty."""
- request = ChatCompletionRequest(
- model="test-model",
- messages=[Message(role="user", content="Hello")],
- presence_penalty=0.5,
- )
-
- internal = adapter.parse_request(request)
-
- assert internal.presence_penalty == 0.5
+ assert getattr(internal, field) == expected
def test_parse_request_default_min_p_and_presence_penalty(self, adapter):
"""Test default min_p and presence_penalty values."""
@@ -355,52 +317,17 @@ def test_parse_request_default_min_p_and_presence_penalty(self, adapter):
assert internal.min_p == 0.0
assert internal.presence_penalty == 0.0
- def test_parse_request_with_max_tokens(self, adapter):
- """Test parsing request with max_tokens."""
- request = ChatCompletionRequest(
- model="test-model",
- messages=[Message(role="user", content="Hello")],
- max_tokens=500,
- )
-
- internal = adapter.parse_request(request)
-
- assert internal.max_tokens == 500
-
- def test_parse_request_default_max_tokens(self, adapter):
- """Test parsing request without max_tokens uses default."""
- request = ChatCompletionRequest(
- model="test-model",
- messages=[Message(role="user", content="Hello")],
- )
-
- internal = adapter.parse_request(request)
-
- assert internal.max_tokens == 2048
-
- def test_parse_request_with_stream_true(self, adapter):
- """Test parsing request with stream=True."""
- request = ChatCompletionRequest(
- model="test-model",
- messages=[Message(role="user", content="Hello")],
- stream=True,
- )
-
- internal = adapter.parse_request(request)
-
- assert internal.stream is True
-
- def test_parse_request_with_stream_false(self, adapter):
- """Test parsing request with stream=False."""
+ @pytest.mark.parametrize("stream", [True, False], ids=["stream", "nonstream"])
+ def test_parse_request_stream(self, adapter, stream):
request = ChatCompletionRequest(
model="test-model",
messages=[Message(role="user", content="Hello")],
- stream=False,
+ stream=stream,
)
internal = adapter.parse_request(request)
- assert internal.stream is False
+ assert internal.stream is stream
def test_parse_request_with_stop_list(self, adapter):
"""Test parsing request with stop sequences as list."""
diff --git a/tests/test_openai_models.py b/tests/test_openai_models.py
index b3247ff593..9a1c220fca 100644
--- a/tests/test_openai_models.py
+++ b/tests/test_openai_models.py
@@ -43,19 +43,12 @@
class TestContentPart:
"""Tests for ContentPart model."""
- def test_text_content_part(self):
- """Test creating text content part."""
- part = ContentPart(type="text", text="Hello world")
+ @pytest.mark.parametrize("text", ["Hello world", ""], ids=["nonempty", "empty"])
+ def test_text_content_part(self, text):
+ part = ContentPart(type="text", text=text)
assert part.type == "text"
- assert part.text == "Hello world"
-
- def test_text_content_part_empty_text(self):
- """Test creating text content part with empty text."""
- part = ContentPart(type="text", text="")
-
- assert part.type == "text"
- assert part.text == ""
+ assert part.text == text
def test_content_part_none_text(self):
"""Test creating content part without text."""
@@ -217,11 +210,15 @@ def test_function_call_strips_name_whitespace(self):
assert fc.name == "Bash"
assert fc.arguments == "{}"
- def test_function_call_rejects_non_string_name(self):
+ @pytest.mark.parametrize(
+ "name",
+ [None, 123, {"name": "Bash"}, ["Bash"]],
+ ids=["none", "number", "dict", "list"],
+ )
+ def test_function_call_rejects_non_string_name(self, name):
"""Name normalization must not widen FunctionCall.name beyond str."""
- for name in (None, 123, {"name": "Bash"}, ["Bash"]):
- with pytest.raises(ValidationError):
- FunctionCall(name=name, arguments={})
+ with pytest.raises(ValidationError):
+ FunctionCall(name=name, arguments={})
def test_tool_call(self):
"""Test creating tool call."""
@@ -255,14 +252,10 @@ class TestFunctionCallArgumentsValidation:
must be rejected at the request boundary with a 422-friendly ValueError.
"""
- def test_accepts_empty_string_as_empty_object(self):
- """Some clients send ``""`` — normalize to ``"{}"`` instead of rejecting."""
- fc = FunctionCall(name="f", arguments="")
- assert fc.arguments == "{}"
-
- def test_accepts_whitespace_only_string(self):
- """Whitespace-only input normalizes to ``"{}"`` too."""
- fc = FunctionCall(name="f", arguments=" ")
+ @pytest.mark.parametrize("arguments", ["", " "], ids=["empty", "whitespace"])
+ def test_accepts_empty_arguments_as_empty_object(self, arguments):
+ """Normalize empty client arguments instead of rejecting them."""
+ fc = FunctionCall(name="f", arguments=arguments)
assert fc.arguments == "{}"
def test_accepts_dict_and_serializes(self):
@@ -270,34 +263,21 @@ def test_accepts_dict_and_serializes(self):
fc = FunctionCall(name="f", arguments={"a": 1, "b": "x"})
assert json.loads(fc.arguments) == {"a": 1, "b": "x"}
- def test_rejects_invalid_json(self):
- """Truncated or otherwise malformed JSON must raise."""
- with pytest.raises(ValidationError) as exc:
- FunctionCall(name="f", arguments='{"a": "b')
- msg = str(exc.value)
- assert "valid JSON" in msg
+ @pytest.mark.parametrize(
+ "arguments",
+ ['{"a": "b', "{'a': 1}", "Tokyo"],
+ ids=["truncated-json", "python-repr", "plain-text"],
+ )
+ def test_rejects_invalid_json(self, arguments):
+ with pytest.raises(ValidationError, match="valid JSON"):
+ FunctionCall(name="f", arguments=arguments)
- def test_rejects_python_repr_with_single_quotes(self):
- """``{'a': 1}`` is not valid JSON and must be rejected."""
- with pytest.raises(ValidationError):
- FunctionCall(name="f", arguments="{'a': 1}")
-
- def test_rejects_bare_string(self):
- """``"Tokyo"`` parses as a JSON string, not an object — reject."""
- with pytest.raises(ValidationError) as exc:
- FunctionCall(name="f", arguments='"Tokyo"')
- assert "JSON object" in str(exc.value)
-
- def test_rejects_json_array(self):
- """Arrays are valid JSON but not objects; reject."""
- with pytest.raises(ValidationError) as exc:
- FunctionCall(name="f", arguments="[1, 2, 3]")
- assert "JSON object" in str(exc.value)
-
- def test_rejects_plain_text(self):
- """Plain text that isn't JSON at all — reject."""
- with pytest.raises(ValidationError):
- FunctionCall(name="f", arguments="Tokyo")
+ @pytest.mark.parametrize(
+ "arguments", ['"Tokyo"', "[1, 2, 3]"], ids=["string", "array"]
+ )
+ def test_rejects_non_object_json(self, arguments):
+ with pytest.raises(ValidationError, match="JSON object"):
+ FunctionCall(name="f", arguments=arguments)
def test_rejects_numeric_type(self):
"""Non-string, non-dict types are rejected."""
@@ -342,25 +322,16 @@ def test_dict_arguments_coerced(self):
)
assert json.loads(msg.tool_calls[0]["function"]["arguments"]) == {"a": 1}
- def test_malformed_json_rejected(self):
- with pytest.raises(ValidationError):
- Message(
- role="assistant",
- tool_calls=[{"function": {"name": "f", "arguments": '{"a":'}}],
- )
-
- def test_python_repr_rejected(self):
- with pytest.raises(ValidationError):
- Message(
- role="assistant",
- tool_calls=[{"function": {"name": "f", "arguments": "{'a': 1}"}}],
- )
-
- def test_plain_text_rejected(self):
+ @pytest.mark.parametrize(
+ "arguments",
+ ['{"a":', "{'a': 1}", "Tokyo"],
+ ids=["truncated-json", "python-repr", "plain-text"],
+ )
+ def test_invalid_arguments_rejected(self, arguments):
with pytest.raises(ValidationError):
Message(
role="assistant",
- tool_calls=[{"function": {"name": "f", "arguments": "Tokyo"}}],
+ tool_calls=[{"function": {"name": "f", "arguments": arguments}}],
)
def test_missing_arguments_key_allowed(self):
diff --git a/tests/test_output_collector.py b/tests/test_output_collector.py
index 52d8c99312..4554dc39b9 100644
--- a/tests/test_output_collector.py
+++ b/tests/test_output_collector.py
@@ -53,50 +53,25 @@ def test_custom_values(self):
class TestRequestStreamStateShouldSend:
"""Tests for RequestStreamState.should_send()."""
- def test_should_send_on_finish(self):
- """Test should_send returns True when finished."""
- state = RequestStreamState(stream_interval=10)
- state.sent_tokens = 5
-
- # Should always send on finish regardless of token count
- assert state.should_send(total_tokens=6, finished=True) is True
- assert state.should_send(total_tokens=5, finished=True) is True
-
- def test_should_send_first_token(self):
- """Test should_send returns True for first token."""
- state = RequestStreamState(stream_interval=10)
-
- # First token (sent_tokens == 0) should always send
- assert state.should_send(total_tokens=1, finished=False) is True
-
- def test_should_send_interval_reached(self):
- """Test should_send returns True when interval reached."""
- state = RequestStreamState(stream_interval=5)
- state.sent_tokens = 5
-
- # Not enough tokens accumulated
- assert state.should_send(total_tokens=6, finished=False) is False
- assert state.should_send(total_tokens=9, finished=False) is False
-
- # Exactly at interval
- assert state.should_send(total_tokens=10, finished=False) is True
-
- # Past interval
- assert state.should_send(total_tokens=15, finished=False) is True
-
- def test_should_send_interval_one(self):
- """Test should_send with interval=1 (every token)."""
- state = RequestStreamState(stream_interval=1)
-
- # Should send every token
- state.sent_tokens = 0
- assert state.should_send(total_tokens=1, finished=False) is True
-
- state.sent_tokens = 1
- assert state.should_send(total_tokens=2, finished=False) is True
-
- state.sent_tokens = 5
- assert state.should_send(total_tokens=6, finished=False) is True
+ @pytest.mark.parametrize(
+ ("interval", "sent", "total", "finished", "expected"),
+ [
+ pytest.param(10, 5, 6, True, True, id="finish-with-new-token"),
+ pytest.param(10, 5, 5, True, True, id="finish-without-new-token"),
+ pytest.param(10, 0, 1, False, True, id="first-token"),
+ pytest.param(5, 5, 6, False, False, id="below-interval"),
+ pytest.param(5, 5, 9, False, False, id="just-below-interval"),
+ pytest.param(5, 5, 10, False, True, id="at-interval"),
+ pytest.param(5, 5, 15, False, True, id="past-interval"),
+ pytest.param(1, 0, 1, False, True, id="interval-one-first-token"),
+ pytest.param(1, 1, 2, False, True, id="interval-one-second-token"),
+ pytest.param(1, 5, 6, False, True, id="interval-one-later-token"),
+ ],
+ )
+ def test_should_send(self, interval, sent, total, finished, expected):
+ state = RequestStreamState(stream_interval=interval, sent_tokens=sent)
+
+ assert state.should_send(total_tokens=total, finished=finished) is expected
class TestRequestStreamStateMarkSent:
diff --git a/tests/test_request.py b/tests/test_request.py
index b4dada3636..c495467598 100644
--- a/tests/test_request.py
+++ b/tests/test_request.py
@@ -17,53 +17,31 @@
class TestRequestStatus:
"""Test cases for RequestStatus enum."""
- def test_status_values(self):
- """Test that status enum has expected values."""
- assert RequestStatus.WAITING is not None
- assert RequestStatus.RUNNING is not None
- assert RequestStatus.PREEMPTED is not None
- assert RequestStatus.FINISHED_STOPPED is not None
- assert RequestStatus.FINISHED_LENGTH_CAPPED is not None
- assert RequestStatus.FINISHED_ABORTED is not None
-
- def test_status_ordering(self):
+ @pytest.mark.parametrize(
+ "status",
+ [RequestStatus.WAITING, RequestStatus.RUNNING, RequestStatus.PREEMPTED],
+ ids=lambda status: status.name,
+ )
+ def test_status_ordering(self, status):
"""Test that finished statuses are greater than active statuses."""
- assert RequestStatus.WAITING < RequestStatus.FINISHED_STOPPED
- assert RequestStatus.RUNNING < RequestStatus.FINISHED_STOPPED
- assert RequestStatus.PREEMPTED < RequestStatus.FINISHED_STOPPED
-
- def test_is_finished_active_states(self):
- """Test is_finished returns False for active states."""
- assert RequestStatus.is_finished(RequestStatus.WAITING) is False
- assert RequestStatus.is_finished(RequestStatus.RUNNING) is False
- assert RequestStatus.is_finished(RequestStatus.PREEMPTED) is False
-
- def test_is_finished_finished_states(self):
- """Test is_finished returns True for finished states."""
- assert RequestStatus.is_finished(RequestStatus.FINISHED_STOPPED) is True
- assert RequestStatus.is_finished(RequestStatus.FINISHED_LENGTH_CAPPED) is True
- assert RequestStatus.is_finished(RequestStatus.FINISHED_ABORTED) is True
-
- def test_get_finish_reason_stopped(self):
- """Test get_finish_reason for FINISHED_STOPPED."""
- reason = RequestStatus.get_finish_reason(RequestStatus.FINISHED_STOPPED)
- assert reason == "stop"
-
- def test_get_finish_reason_length_capped(self):
- """Test get_finish_reason for FINISHED_LENGTH_CAPPED."""
- reason = RequestStatus.get_finish_reason(RequestStatus.FINISHED_LENGTH_CAPPED)
- assert reason == "length"
-
- def test_get_finish_reason_aborted(self):
- """Test get_finish_reason for FINISHED_ABORTED."""
- reason = RequestStatus.get_finish_reason(RequestStatus.FINISHED_ABORTED)
- assert reason == "abort"
-
- def test_get_finish_reason_active_states(self):
- """Test get_finish_reason returns None for active states."""
- assert RequestStatus.get_finish_reason(RequestStatus.WAITING) is None
- assert RequestStatus.get_finish_reason(RequestStatus.RUNNING) is None
- assert RequestStatus.get_finish_reason(RequestStatus.PREEMPTED) is None
+ assert status < RequestStatus.FINISHED_STOPPED
+
+ @pytest.mark.parametrize(
+ ("status", "finished", "reason"),
+ [
+ pytest.param(RequestStatus.WAITING, False, None, id="waiting"),
+ pytest.param(RequestStatus.RUNNING, False, None, id="running"),
+ pytest.param(RequestStatus.PREEMPTED, False, None, id="preempted"),
+ pytest.param(RequestStatus.FINISHED_STOPPED, True, "stop", id="stopped"),
+ pytest.param(
+ RequestStatus.FINISHED_LENGTH_CAPPED, True, "length", id="length-capped"
+ ),
+ pytest.param(RequestStatus.FINISHED_ABORTED, True, "abort", id="aborted"),
+ ],
+ )
+ def test_finish_status_and_reason(self, status, finished, reason):
+ assert RequestStatus.is_finished(status) is finished
+ assert RequestStatus.get_finish_reason(status) == reason
class TestSamplingParams:
diff --git a/tests/test_reranker_vl.py b/tests/test_reranker_vl.py
index a3abd5aeb4..38ec90bc3d 100644
--- a/tests/test_reranker_vl.py
+++ b/tests/test_reranker_vl.py
@@ -22,22 +22,18 @@
class TestCoerceItemToText:
- def test_str_passthrough(self):
- assert _coerce_item_to_text("hello") == "hello"
-
- def test_dict_text_extract(self):
- assert _coerce_item_to_text({"text": "hi"}) == "hi"
-
- def test_dict_image_only_returns_empty(self):
- # Text-only paths should not crash when only image is present; they
- # just get an empty string.
- assert _coerce_item_to_text({"image": "https://x/y.jpg"}) == ""
-
- def test_dict_text_and_image_takes_text(self):
- assert _coerce_item_to_text({"text": "t", "image": "i"}) == "t"
-
- def test_non_str_non_dict_stringifies(self):
- assert _coerce_item_to_text(42) == "42"
+ @pytest.mark.parametrize(
+ ("item", "expected"),
+ [
+ pytest.param("hello", "hello", id="string"),
+ pytest.param({"text": "hi"}, "hi", id="text-dict"),
+ pytest.param({"image": "https://x/y.jpg"}, "", id="image-only"),
+ pytest.param({"text": "t", "image": "i"}, "t", id="text-and-image"),
+ pytest.param(42, "42", id="non-string"),
+ ],
+ )
+ def test_coerce_item_to_text(self, item, expected):
+ assert _coerce_item_to_text(item) == expected
class TestVLRerankerValidation:
@@ -73,25 +69,24 @@ def test_dict_text_only(self, tmp_path):
model = MLXRerankerModel(str(tmp_path))
assert model._build_vl_item({"text": "hi"}) == RerankItem(text="hi")
- def test_dict_image_loads_via_load_image(self, tmp_path):
- model = MLXRerankerModel(str(tmp_path))
- fake_img = object()
- with patch(
- "omlx.models.reranker.load_image", return_value=fake_img
- ) as mock_load:
- result = model._build_vl_item({"image": IMAGE_DATA_URI})
- mock_load.assert_called_once_with(IMAGE_DATA_URI, field="image")
- assert result == RerankItem(image=fake_img)
-
- def test_dict_text_and_image(self, tmp_path):
+ @pytest.mark.parametrize(
+ ("item", "text"),
+ [
+ pytest.param({"image": IMAGE_DATA_URI}, None, id="image-only"),
+ pytest.param(
+ {"text": "t", "image": IMAGE_DATA_URI}, "t", id="text-and-image"
+ ),
+ ],
+ )
+ def test_dict_image_loads_via_load_image(self, tmp_path, item, text):
model = MLXRerankerModel(str(tmp_path))
fake_img = object()
with patch(
"omlx.models.reranker.load_image", return_value=fake_img
) as mock_load:
- result = model._build_vl_item({"text": "t", "image": IMAGE_DATA_URI})
+ result = model._build_vl_item(item)
mock_load.assert_called_once_with(IMAGE_DATA_URI, field="image")
- assert result == RerankItem(text="t", image=fake_img)
+ assert result == RerankItem(text=text, image=fake_img)
def test_dict_image_rejects_url(self, tmp_path):
model = MLXRerankerModel(str(tmp_path))
diff --git a/tests/test_scheduler_chunked_prefill.py b/tests/test_scheduler_chunked_prefill.py
index 7253f118cd..8044ab04f8 100644
--- a/tests/test_scheduler_chunked_prefill.py
+++ b/tests/test_scheduler_chunked_prefill.py
@@ -1039,49 +1039,24 @@ def _mock_current(self, sched, current_gb):
"omlx.scheduler.get_phys_footprint", return_value=target
)
- def test_adaptive_throttle_below_soft_watermark_passthrough(self):
- """current < soft watermark → no throttle, full chunk."""
- sched = self._setup_throttle(max_bytes_gb=10, hard_cap_gb=12)
- # soft_watermark = 10 * 0.80 = 8 GB; current 5 GB is below
- a, b = self._mock_current(sched, 5)
- with a, b:
- result = sched._adaptive_chunk_size(
- 2048, request_id="r1", loop_label="external"
- )
- assert result == 2048
-
- def test_adaptive_throttle_tier_1024(self):
- """First quarter of the soft-to-hard band → 1024."""
- sched = self._setup_throttle(max_bytes_gb=10, hard_cap_gb=12)
- # soft_wm = 8 GB, band = 12 - 8 = 4 GB. 10% into band = 8.4 GB.
- a, b = self._mock_current(sched, 8.4)
- with a, b:
- result = sched._adaptive_chunk_size(
- 2048, request_id="r1", loop_label="external"
- )
- assert result == 1024
-
- def test_adaptive_throttle_tier_512(self):
- """50%+ of band → 512."""
- sched = self._setup_throttle(max_bytes_gb=10, hard_cap_gb=12)
- # 60% of band: 8 + 4*0.60 = 10.4 GB
- a, b = self._mock_current(sched, 10.4)
- with a, b:
- result = sched._adaptive_chunk_size(
- 2048, request_id="r1", loop_label="external"
- )
- assert result == 512
-
- def test_adaptive_throttle_requested_smaller_than_tier(self):
- """Requested chunk already smaller than the tier target → pass through."""
+ @pytest.mark.parametrize(
+ "current_gb, requested, expected",
+ [
+ pytest.param(5, 2048, 2048, id="below-soft-watermark"),
+ pytest.param(8.4, 2048, 1024, id="tier-1024"),
+ pytest.param(10.4, 2048, 512, id="tier-512"),
+ pytest.param(10.4, 256, 256, id="requested-smaller-than-tier"),
+ ],
+ )
+ def test_adaptive_throttle_tiers(self, current_gb, requested, expected):
+ """The soft-to-hard pressure band runs from 8 to 12 GiB."""
sched = self._setup_throttle(max_bytes_gb=10, hard_cap_gb=12)
- # 60% of band → tier 512. But requested=256 < 512.
- a, b = self._mock_current(sched, 10.4)
+ a, b = self._mock_current(sched, current_gb)
with a, b:
result = sched._adaptive_chunk_size(
- 256, request_id="r1", loop_label="external"
+ requested, request_id="r1", loop_label="external"
)
- assert result == 256
+ assert result == expected
def test_adaptive_throttle_no_cap_passthrough(self):
"""When hard limit or soft base is unset (=0), no throttle."""
diff --git a/tests/test_shared_models.py b/tests/test_shared_models.py
index 1212ee6ff1..088bdd1a89 100644
--- a/tests/test_shared_models.py
+++ b/tests/test_shared_models.py
@@ -1,41 +1,35 @@
# SPDX-License-Identifier: Apache-2.0
"""Tests for omlx.api.shared_models module."""
+import json
import time
-import uuid
import pytest
+from pydantic import ValidationError
from omlx.api.shared_models import (
+ BaseUsage,
IDPrefix,
generate_id,
get_unix_timestamp,
- BaseUsage,
)
class TestIDPrefix:
"""Test cases for IDPrefix enum."""
- def test_chat_completion_prefix(self):
- """Test CHAT_COMPLETION prefix value."""
- assert IDPrefix.CHAT_COMPLETION.value == "chatcmpl"
-
- def test_completion_prefix(self):
- """Test COMPLETION prefix value."""
- assert IDPrefix.COMPLETION.value == "cmpl"
-
- def test_message_prefix(self):
- """Test MESSAGE prefix value."""
- assert IDPrefix.MESSAGE.value == "msg"
-
- def test_embedding_prefix(self):
- """Test EMBEDDING prefix value."""
- assert IDPrefix.EMBEDDING.value == "emb"
-
- def test_rerank_prefix(self):
- """Test RERANK prefix value."""
- assert IDPrefix.RERANK.value == "rerank"
+ @pytest.mark.parametrize(
+ "prefix, expected",
+ [
+ (IDPrefix.CHAT_COMPLETION, "chatcmpl"),
+ (IDPrefix.COMPLETION, "cmpl"),
+ (IDPrefix.MESSAGE, "msg"),
+ (IDPrefix.EMBEDDING, "emb"),
+ (IDPrefix.RERANK, "rerank"),
+ ],
+ )
+ def test_prefix_value(self, prefix, expected):
+ assert prefix.value == expected
def test_all_prefixes_are_strings(self):
"""Test that all prefixes are strings."""
@@ -52,37 +46,20 @@ def test_prefix_is_str_subclass(self):
class TestGenerateId:
"""Test cases for generate_id function."""
- def test_generate_chat_completion_id(self):
- """Test generating chat completion ID."""
- id_str = generate_id(IDPrefix.CHAT_COMPLETION)
- assert id_str.startswith("chatcmpl-")
- # Default length is 8
- assert len(id_str) == len("chatcmpl-") + 8
-
- def test_generate_completion_id(self):
- """Test generating completion ID."""
- id_str = generate_id(IDPrefix.COMPLETION)
- assert id_str.startswith("cmpl-")
- assert len(id_str) == len("cmpl-") + 8
-
- def test_generate_message_id(self):
- """Test generating message ID (Anthropic style)."""
- id_str = generate_id(IDPrefix.MESSAGE)
- # Anthropic style: msg_<24-char-hex>
- assert id_str.startswith("msg_")
- assert len(id_str) == len("msg_") + 24
-
- def test_generate_embedding_id(self):
- """Test generating embedding ID."""
- id_str = generate_id(IDPrefix.EMBEDDING)
- assert id_str.startswith("emb-")
- assert len(id_str) == len("emb-") + 8
-
- def test_generate_rerank_id(self):
- """Test generating rerank ID."""
- id_str = generate_id(IDPrefix.RERANK)
- assert id_str.startswith("rerank-")
- assert len(id_str) == len("rerank-") + 8
+ @pytest.mark.parametrize(
+ "prefix, expected_prefix, suffix_length",
+ [
+ (IDPrefix.CHAT_COMPLETION, "chatcmpl-", 8),
+ (IDPrefix.COMPLETION, "cmpl-", 8),
+ (IDPrefix.MESSAGE, "msg_", 24),
+ (IDPrefix.EMBEDDING, "emb-", 8),
+ (IDPrefix.RERANK, "rerank-", 8),
+ ],
+ )
+ def test_generate_default_id(self, prefix, expected_prefix, suffix_length):
+ id_str = generate_id(prefix)
+ assert id_str.startswith(expected_prefix)
+ assert len(id_str) == len(expected_prefix) + suffix_length
def test_generate_id_custom_length(self):
"""Test generating ID with custom length."""
@@ -206,8 +183,10 @@ def test_pydantic_model_json(self):
completion_tokens=50,
)
json_str = usage.model_dump_json()
- assert "prompt_tokens" in json_str
- assert "100" in json_str
+ data = json.loads(json_str)
+ assert data["prompt_tokens"] == 100
+ assert data["completion_tokens"] == 50
+ assert data["total_tokens"] == 150
def test_pydantic_validation(self):
"""Test Pydantic validation."""
@@ -216,7 +195,7 @@ def test_pydantic_validation(self):
assert usage.prompt_tokens == 100
# Invalid type should raise error
- with pytest.raises(Exception): # Pydantic ValidationError
+ with pytest.raises(ValidationError):
BaseUsage(prompt_tokens="not_a_number")
def test_large_token_counts(self):
diff --git a/tests/test_store_cache_gate.py b/tests/test_store_cache_gate.py
index 80b306f879..19b4323701 100644
--- a/tests/test_store_cache_gate.py
+++ b/tests/test_store_cache_gate.py
@@ -118,30 +118,20 @@ def _fake_scheduler(self, cap, max_num_seqs=8):
sched._store_cache_gate = _StoreCacheGate(cap=cap)
return sched
- def test_ok_grows_by_one(self):
- sched = self._fake_scheduler(cap=4, max_num_seqs=8)
- Scheduler.adjust_store_cache_cap(sched, "ok")
- assert sched._store_cache_gate.cap == 5
-
- def test_ok_clamps_to_max_num_seqs(self):
- sched = self._fake_scheduler(cap=8, max_num_seqs=8)
- Scheduler.adjust_store_cache_cap(sched, "ok")
- assert sched._store_cache_gate.cap == 8
-
- def test_soft_shrinks_by_one(self):
- sched = self._fake_scheduler(cap=5)
- Scheduler.adjust_store_cache_cap(sched, "soft")
- assert sched._store_cache_gate.cap == 4
-
- def test_hard_shrinks_by_one(self):
- sched = self._fake_scheduler(cap=3)
- Scheduler.adjust_store_cache_cap(sched, "hard")
- assert sched._store_cache_gate.cap == 2
-
- def test_shrink_floor_at_one(self):
- sched = self._fake_scheduler(cap=1)
- Scheduler.adjust_store_cache_cap(sched, "hard")
- assert sched._store_cache_gate.cap == 1
+ @pytest.mark.parametrize(
+ "cap, pressure, expected",
+ [
+ pytest.param(4, "ok", 5, id="ok-grows-by-one"),
+ pytest.param(8, "ok", 8, id="ok-clamps-to-max-num-seqs"),
+ pytest.param(5, "soft", 4, id="soft-shrinks-by-one"),
+ pytest.param(3, "hard", 2, id="hard-shrinks-by-one"),
+ pytest.param(1, "hard", 1, id="shrink-floor-at-one"),
+ ],
+ )
+ def test_pressure_adjusts_cap(self, cap, pressure, expected):
+ sched = self._fake_scheduler(cap=cap, max_num_seqs=8)
+ Scheduler.adjust_store_cache_cap(sched, pressure)
+ assert sched._store_cache_gate.cap == expected
def test_no_op_when_gate_missing(self):
from unittest.mock import MagicMock
diff --git a/tests/test_thinking.py b/tests/test_thinking.py
index b299f331e9..e49d07f18d 100644
--- a/tests/test_thinking.py
+++ b/tests/test_thinking.py
@@ -5,44 +5,60 @@
from omlx.api.thinking import ThinkingParser, extract_thinking
+
class TestExtractThinking:
"""Tests for non-streaming extract_thinking()."""
- def test_basic_separation(self):
- """Standard reasoning answer case."""
- thinking, content = extract_thinking("reasoning Answer")
- assert thinking == "reasoning"
- assert content == "Answer"
-
- def test_minimax_m3_tag_separation(self):
- """MiniMax M3 tags are treated as thinking tags."""
- thinking, content = extract_thinking("reasoning Answer")
- assert thinking == "reasoning"
- assert content == "Answer"
-
- def test_no_thinking(self):
- """No think tags in text."""
- thinking, content = extract_thinking("Just a normal answer")
- assert thinking == ""
- assert content == "Just a normal answer"
-
- def test_empty_text(self):
- """Empty input."""
- thinking, content = extract_thinking("")
- assert thinking == ""
- assert content == ""
-
- def test_empty_think_block(self):
- """Empty block."""
- thinking, content = extract_thinking(" Answer")
- assert thinking == ""
- assert content == "Answer"
-
- def test_think_only(self):
- """Only thinking content, no answer."""
- thinking, content = extract_thinking("reasoning ")
- assert thinking == "reasoning"
- assert content == ""
+ @pytest.mark.parametrize(
+ "text, expected_thinking, expected_content",
+ [
+ pytest.param(
+ "reasoning Answer",
+ "reasoning",
+ "Answer",
+ id="basic-separation",
+ ),
+ pytest.param(
+ "reasoning Answer",
+ "reasoning",
+ "Answer",
+ id="minimax-m3-tags",
+ ),
+ pytest.param(
+ "Just a normal answer", "", "Just a normal answer", id="no-thinking"
+ ),
+ pytest.param("", "", "", id="empty-text"),
+ pytest.param(" Answer", "", "Answer", id="empty-think-block"),
+ pytest.param(
+ "reasoning ", "reasoning", "", id="thinking-only"
+ ),
+ pytest.param(
+ "reasoning contentAnswer",
+ "reasoning content",
+ "Answer",
+ id="scheduler-preopened-tag",
+ ),
+ pytest.param(
+ "thought processvisible answer",
+ "thought process",
+ "visible answer",
+ id="close-tag-only-partial-tail",
+ ),
+ # Issue #1348: short, tag-free tool-turn answers must remain visible.
+ pytest.param(
+ "just the reasoning",
+ "",
+ "just the reasoning",
+ id="tag-free-reasoning-is-content",
+ ),
+ ],
+ )
+ def test_extracts_thinking_and_content(
+ self, text, expected_thinking, expected_content
+ ):
+ thinking, content = extract_thinking(text)
+ assert thinking == expected_thinking
+ assert content == expected_content
def test_multiline_thinking(self):
"""Thinking with newlines."""
@@ -57,17 +73,10 @@ def test_open_tag_no_close_recovers_as_content(self):
"""Model opened ```` but never closed it — non-streaming
path treats the body as content (matching the streaming
recovery in ThinkingParser.finish())."""
- from omlx.api.thinking import extract_thinking
thinking, content = extract_thinking("\nthe whole answer body")
assert thinking == ""
assert content == "the whole answer body"
- def test_partial_no_open_tag(self):
- """Content before without tag (scheduler prefix case)."""
- thinking, content = extract_thinking("reasoning content Answer")
- assert thinking == "reasoning content"
- assert content == "Answer"
-
def test_multiple_think_blocks(self):
"""Multiple think blocks should all be extracted."""
thinking, content = extract_thinking(
@@ -94,26 +103,6 @@ def test_thinking_with_newline_prefix(self):
assert "Let me reason..." in thinking
assert "Final answer." in content
- def test_tag_free_text_always_classified_as_content(self):
- """Tag-free text is content, never thinking. Regression guard for
- issue #1348: in 0.3.9 the Responses API passed
- ``start_in_thinking=True`` here, which misclassified short tool-turn
- answers (no `` ``) as thinking and left ``output_text`` empty.
- Mirrors ``ThinkingParser.finish()`` recovery semantics."""
- thinking, content = extract_thinking("just the reasoning")
- assert thinking == ""
- assert content == "just the reasoning"
-
- def test_close_tag_only_partial_tail_branch(self):
- """Prompt pre-opened ````; model emits ``body answer``
- (no opening tag in output). Partial-tail branch splits correctly."""
- thinking, content = extract_thinking(
- "thought processvisible answer"
- )
- assert thinking == "thought process"
- assert content == "visible answer"
-
-
class TestThinkingParser:
"""Tests for streaming ThinkingParser."""
@@ -234,9 +223,9 @@ def test_angle_bracket_in_thinking(self):
"""Angle brackets inside thinking that are not tags."""
parser = ThinkingParser()
- t1, c1 = parser.feed("if x > 0 then y < 10")
- # The > and < characters should pass through since they don't form valid tags
- assert "x > 0" in t1 or "x > 0" in (t1 + parser._buffer)
+ thinking, content = parser.feed("if x > 0 then y < 10 answer")
+ assert thinking == "if x > 0 then y < 10"
+ assert content == "answer"
def test_recovery_when_no_close_tag_streams_as_content(self):
"""Model opened ```` but never emitted `` ``.
@@ -391,7 +380,7 @@ class TestCleanSpecialTokens:
def test_preserves_think_tags(self):
from omlx.api.utils import clean_special_tokens
result = clean_special_tokens("reasoning Answer")
- assert "reasoning Answer" == result
+ assert result == "reasoning Answer"
def test_removes_special_tokens(self):
from omlx.api.utils import clean_special_tokens
@@ -408,7 +397,7 @@ def test_removes_special_preserves_think(self):
result = clean_special_tokens(
"<|im_start|>reasoning Answer<|im_end|>"
)
- assert "reasoning Answer" == result
+ assert result == "reasoning Answer"
class TestCleanOutputTextBackwardCompat:
diff --git a/tests/test_thinking_toggle.py b/tests/test_thinking_toggle.py
index 62d2cd0c60..f717e1ed13 100644
--- a/tests/test_thinking_toggle.py
+++ b/tests/test_thinking_toggle.py
@@ -1,3 +1,4 @@
+# SPDX-License-Identifier: Apache-2.0
"""Tests for the enable_thinking toggle and detect_thinking_default probe."""
import json
@@ -78,15 +79,10 @@ def test_laguna_template_uses_recommended_serving_default(self, tmp_path):
assert detect_thinking_default(tmp_path) is True
- def test_laguna_without_thinking_template_returns_none(self, tmp_path):
- """A Laguna config alone is not evidence that its template accepts the flag."""
- (tmp_path / "config.json").write_text(json.dumps({"model_type": "laguna"}))
-
- assert detect_thinking_default(tmp_path) is None
-
- def test_non_laguna_config_without_thinking_template_returns_none(self, tmp_path):
- """Reading config metadata must not enable thinking for other models."""
- (tmp_path / "config.json").write_text(json.dumps({"model_type": "llama"}))
+ @pytest.mark.parametrize("model_type", ["laguna", "llama"])
+ def test_config_without_thinking_template_returns_none(self, tmp_path, model_type):
+ """Config metadata alone is not evidence that a template accepts the flag."""
+ (tmp_path / "config.json").write_text(json.dumps({"model_type": model_type}))
assert detect_thinking_default(tmp_path) is None
diff --git a/tests/test_utils_hardware.py b/tests/test_utils_hardware.py
index 769b9f3db3..8766b88bfd 100644
--- a/tests/test_utils_hardware.py
+++ b/tests/test_utils_hardware.py
@@ -161,22 +161,19 @@ def test_falls_back_to_total_memory_without_psutil(self):
class TestIsAppleSilicon:
"""Test cases for is_apple_silicon function."""
- def test_is_apple_silicon_true(self):
- """Test is_apple_silicon returns True on macOS arm64."""
- with patch.object(sys, "platform", "darwin"):
- with patch.object(platform, "machine", return_value="arm64"):
- assert is_apple_silicon() is True
-
- def test_is_apple_silicon_false_wrong_platform(self):
- """Test is_apple_silicon returns False on non-macOS."""
- with patch.object(sys, "platform", "linux"):
- assert is_apple_silicon() is False
-
- def test_is_apple_silicon_false_wrong_arch(self):
- """Test is_apple_silicon returns False on x86_64 macOS."""
- with patch.object(sys, "platform", "darwin"):
- with patch.object(platform, "machine", return_value="x86_64"):
- assert is_apple_silicon() is False
+ @pytest.mark.parametrize(
+ "os_name, architecture, expected",
+ [
+ pytest.param("darwin", "arm64", True, id="apple-silicon"),
+ pytest.param("linux", "arm64", False, id="wrong-platform"),
+ pytest.param("darwin", "x86_64", False, id="wrong-architecture"),
+ ],
+ )
+ def test_is_apple_silicon(self, os_name, architecture, expected):
+ with patch.object(sys, "platform", os_name), patch.object(
+ platform, "machine", return_value=architecture
+ ):
+ assert is_apple_silicon() is expected
class TestIsMlxAvailable:
@@ -187,50 +184,48 @@ def test_is_mlx_available_not_apple_silicon(self):
with patch("omlx.utils.hardware.is_apple_silicon", return_value=False):
assert is_mlx_available() is False
- def test_is_mlx_available_import_error(self):
- """Test is_mlx_available handles import errors."""
- with patch("omlx.utils.hardware.is_apple_silicon", return_value=True):
- with patch.dict("sys.modules", {"mlx.core": None}):
- # Force import to fail
- import builtins
-
- original_import = builtins.__import__
-
- def mock_import(name, *args, **kwargs):
- if name == "mlx.core" or name.startswith("mlx"):
- raise ImportError("No module named mlx")
- return original_import(name, *args, **kwargs)
+ def test_is_mlx_available_without_mlx(self):
+ with patch("omlx.utils.hardware.is_apple_silicon", return_value=True), patch(
+ "omlx.utils.hardware.HAS_MLX", False
+ ):
+ assert is_mlx_available() is False
- with patch.object(builtins, "__import__", mock_import):
- result = is_mlx_available()
- # May return True if mlx is already imported, False if not
- assert isinstance(result, bool)
+ @pytest.mark.parametrize(
+ "array_error, expected",
+ [
+ pytest.param(None, True, id="working-device"),
+ pytest.param(RuntimeError("device unavailable"), False, id="device-error"),
+ ],
+ )
+ def test_is_mlx_available_checks_device(self, array_error, expected):
+ with patch("omlx.utils.hardware.is_apple_silicon", return_value=True), patch(
+ "omlx.utils.hardware.HAS_MLX", True
+ ), patch("omlx.utils.hardware.mx") as mock_mx:
+ mock_mx.array.side_effect = array_error
+ assert is_mlx_available() is expected
+ mock_mx.array.assert_called_once_with([1.0, 2.0, 3.0])
class TestFormatBytesHardware:
"""Test cases for format_bytes function in hardware module."""
- def test_format_bytes_gb(self):
- """Test formatting bytes to GB."""
- assert format_bytes(1024**3) == "1.00 GB"
- assert format_bytes(16 * 1024**3) == "16.00 GB"
- assert format_bytes(48 * 1024**3) == "48.00 GB"
-
- def test_format_bytes_mb(self):
- """Test formatting bytes to MB."""
- assert format_bytes(1024**2) == "1.00 MB"
- assert format_bytes(512 * 1024**2) == "512.00 MB"
-
- def test_format_bytes_kb(self):
- """Test formatting bytes to KB."""
- assert format_bytes(1024) == "1.00 KB"
- assert format_bytes(512 * 1024) == "512.00 KB"
-
- def test_format_bytes_small(self):
- """Test formatting small byte values."""
- assert format_bytes(0) == "0 B"
- assert format_bytes(512) == "512 B"
- assert format_bytes(1023) == "1023 B"
+ @pytest.mark.parametrize(
+ "size, expected",
+ [
+ (1024**3, "1.00 GB"),
+ (16 * 1024**3, "16.00 GB"),
+ (48 * 1024**3, "48.00 GB"),
+ (1024**2, "1.00 MB"),
+ (512 * 1024**2, "512.00 MB"),
+ (1024, "1.00 KB"),
+ (512 * 1024, "512.00 KB"),
+ (0, "0 B"),
+ (512, "512 B"),
+ (1023, "1023 B"),
+ ],
+ )
+ def test_format_bytes(self, size, expected):
+ assert format_bytes(size) == expected
class TestDefaultMemoryBytes:
diff --git a/tests/test_utils_tokenizer.py b/tests/test_utils_tokenizer.py
index 25ef356150..86e3d6041f 100644
--- a/tests/test_utils_tokenizer.py
+++ b/tests/test_utils_tokenizer.py
@@ -3,6 +3,8 @@
import json
+import pytest
+
from omlx.utils.tokenizer import (
apply_qwen3_fix,
create_streaming_detokenizer,
@@ -369,106 +371,74 @@ def test_leaves_canonical_unlimited_tokenizer_untouched(self, tmp_path):
class TestIsHarmonyModel:
"""Test cases for is_harmony_model function."""
- def test_harmony_model_via_config_model_type(self):
- """Test detection via config.model_type == 'gpt_oss'."""
- config = {"model_type": "gpt_oss"}
- assert is_harmony_model("some-model", config) is True
-
- def test_harmony_model_via_name_gpt_oss(self):
- """Test detection via model name containing 'gpt-oss'."""
- assert is_harmony_model("gpt-oss-1.0", None) is True
- assert is_harmony_model("GPT-OSS-v2", None) is True
- assert is_harmony_model("my-gpt-oss-model", None) is True
-
- def test_harmony_model_via_name_gptoss(self):
- """Test detection via model name containing 'gptoss'."""
- assert is_harmony_model("gptoss", None) is True
- assert is_harmony_model("GPTOSS-large", None) is True
- assert is_harmony_model("my-gptoss", None) is True
-
- def test_not_harmony_model(self):
- """Test non-Harmony models return False."""
- assert is_harmony_model("llama-3.1-8b", None) is False
- assert is_harmony_model("qwen2.5-32b", None) is False
- assert is_harmony_model("mistral-7b", None) is False
-
- def test_not_harmony_with_different_model_type(self):
- """Test non-Harmony model type returns False."""
- config = {"model_type": "llama"}
- assert is_harmony_model("some-model", config) is False
-
- def test_harmony_model_empty_name(self):
- """Test with empty model name."""
- assert is_harmony_model("", None) is False
-
- def test_harmony_model_none_config(self):
- """Test with None config."""
- assert is_harmony_model("gpt-oss", None) is True
- assert is_harmony_model("llama", None) is False
-
- def test_harmony_model_empty_config(self):
- """Test with empty config dict."""
- assert is_harmony_model("gpt-oss", {}) is True
- assert is_harmony_model("llama", {}) is False
+ @pytest.mark.parametrize(
+ "name, config, expected",
+ [
+ ("some-model", {"model_type": "gpt_oss"}, True),
+ ("gpt-oss-1.0", None, True),
+ ("GPT-OSS-v2", None, True),
+ ("my-gpt-oss-model", None, True),
+ ("gptoss", None, True),
+ ("GPTOSS-large", None, True),
+ ("my-gptoss", None, True),
+ ("llama-3.1-8b", None, False),
+ ("qwen2.5-32b", None, False),
+ ("mistral-7b", None, False),
+ ("some-model", {"model_type": "llama"}, False),
+ pytest.param("", None, False, id="empty-name"),
+ ("gpt-oss", None, True),
+ ("llama", None, False),
+ ("gpt-oss", {}, True),
+ ("llama", {}, False),
+ ],
+ )
+ def test_detects_harmony_model(self, name, config, expected):
+ assert is_harmony_model(name, config) is expected
class TestIsGemma4Model:
"""Test cases for is_gemma4_model function."""
- def test_gemma4_model_via_config_model_type(self):
- config = {"model_type": "gemma4"}
- assert is_gemma4_model("some-model", config) is True
-
- def test_gemma4_unified_model_via_config_model_type(self):
- config = {"model_type": "gemma4_unified"}
- assert is_gemma4_model("some-model", config) is True
-
- def test_gemma4_model_via_name(self):
- assert is_gemma4_model("google/gemma-4b", None) is True
- assert is_gemma4_model("GEMMA-4-27B", None) is True
- assert is_gemma4_model("my-gemma4-model", None) is True
-
- def test_not_gemma4_model(self):
- assert is_gemma4_model("gemma-3-27b", None) is False
- assert is_gemma4_model("llama-3.1-8b", None) is False
-
- def test_not_gemma4_with_different_model_type(self):
- config = {"model_type": "gemma"}
- assert is_gemma4_model("some-model", config) is False
+ @pytest.mark.parametrize(
+ "name, config, expected",
+ [
+ ("some-model", {"model_type": "gemma4"}, True),
+ ("some-model", {"model_type": "gemma4_unified"}, True),
+ ("google/gemma-4b", None, True),
+ ("GEMMA-4-27B", None, True),
+ ("my-gemma4-model", None, True),
+ ("gemma-3-27b", None, False),
+ ("llama-3.1-8b", None, False),
+ ("some-model", {"model_type": "gemma"}, False),
+ ],
+ )
+ def test_detects_gemma4_model(self, name, config, expected):
+ assert is_gemma4_model(name, config) is expected
class TestIsQwen3Model:
"""Test cases for is_qwen3_model function."""
- def test_qwen3_lowercase(self):
- """Test detection with lowercase 'qwen3'."""
- assert is_qwen3_model("qwen3-8b") is True
- assert is_qwen3_model("my-qwen3-model") is True
- assert is_qwen3_model("qwen3") is True
-
- def test_qwen3_mixed_case(self):
- """Test detection with mixed case 'Qwen3'."""
- assert is_qwen3_model("Qwen3-8B") is True
- assert is_qwen3_model("My-Qwen3-Model") is True
- assert is_qwen3_model("Qwen3") is True
-
- def test_not_qwen3(self):
- """Test non-Qwen3 models return False."""
- assert is_qwen3_model("qwen2.5-32b") is False
- assert is_qwen3_model("Qwen2-7B") is False
- assert is_qwen3_model("llama-3.1") is False
- assert is_qwen3_model("qwen-7b") is False
-
- def test_qwen3_empty_name(self):
- """Test with empty model name."""
- assert is_qwen3_model("") is False
-
- def test_qwen3_partial_match(self):
- """Test that partial matches don't trigger false positives."""
- # 'qwen30' should NOT match as Qwen3
- # However, current implementation will match it since 'qwen3' is in 'qwen30'
- # This test documents the current behavior
- assert is_qwen3_model("qwen30-model") is True # Contains 'qwen3'
+ @pytest.mark.parametrize(
+ "name, expected",
+ [
+ ("qwen3-8b", True),
+ ("my-qwen3-model", True),
+ ("qwen3", True),
+ ("Qwen3-8B", True),
+ ("My-Qwen3-Model", True),
+ ("Qwen3", True),
+ ("qwen2.5-32b", False),
+ ("Qwen2-7B", False),
+ ("llama-3.1", False),
+ ("qwen-7b", False),
+ pytest.param("", False, id="empty-name"),
+ # Preserve the current substring-matching behavior.
+ ("qwen30-model", True),
+ ],
+ )
+ def test_detects_qwen3_model(self, name, expected):
+ assert is_qwen3_model(name) is expected
class TestGetTokenizerConfig:
From 997919b53774a91c3f3c88069e870438ed2b3379 Mon Sep 17 00:00:00 2001
From: Mike Wallio
Date: Thu, 5 Nov 2026 16:29:40 -0500
Subject: [PATCH 11/24] fix(minimax): replace preloaded upstream modules with
vendored models
Clear cached model and parser namespaces before importing the vendored MiniMax implementations, including parent-package bindings and the router source-precision predicate.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
---
.../mlx_vlm_minimax_m3_compat/__init__.py | 21 +++++++
tests/test_mlx_vlm_minimax_m3_compat.py | 61 +++++++++++++++++++
2 files changed, 82 insertions(+)
diff --git a/omlx/patches/mlx_vlm_minimax_m3_compat/__init__.py b/omlx/patches/mlx_vlm_minimax_m3_compat/__init__.py
index 55750086d6..2466061878 100644
--- a/omlx/patches/mlx_vlm_minimax_m3_compat/__init__.py
+++ b/omlx/patches/mlx_vlm_minimax_m3_compat/__init__.py
@@ -13,6 +13,7 @@
import importlib
import inspect
import logging
+import sys
from pathlib import Path
from typing import Any
@@ -81,6 +82,26 @@ def _append_package_path(package: Any, path: Path) -> None:
def _import_vendor_modules() -> None:
+ for package_name in (
+ "mlx_vlm.models.minimax_m3",
+ "mlx_vlm.models.minimax_m3_vl",
+ "mlx_vlm.tools.parsers.minimax_m3",
+ ):
+ package = sys.modules.get(package_name)
+ if package is None or Path(package.__file__).resolve().is_relative_to(
+ _VENDOR_MLX_VLM
+ ):
+ continue
+ # Discovery can import upstream before the vendor search path is installed.
+ for name in tuple(sys.modules):
+ if name == package_name or name.startswith(f"{package_name}."):
+ del sys.modules[name]
+ parent_name, name = package_name.rsplit(".", 1)
+ parent = sys.modules[parent_name]
+ if hasattr(parent, name):
+ delattr(parent, name)
+ importlib.invalidate_caches()
+
# Importing the processor module installs mlx-vlm's AutoProcessor hook for
# minimax_m3_vl via install_auto_processor_patch().
for module_name in (
diff --git a/tests/test_mlx_vlm_minimax_m3_compat.py b/tests/test_mlx_vlm_minimax_m3_compat.py
index 4e8b183c26..44e17cc391 100644
--- a/tests/test_mlx_vlm_minimax_m3_compat.py
+++ b/tests/test_mlx_vlm_minimax_m3_compat.py
@@ -4,6 +4,8 @@
from __future__ import annotations
import json
+import subprocess
+import sys
from types import SimpleNamespace
import pytest
@@ -15,6 +17,65 @@
from omlx.custom_kernels.quant_matmul import fast as quant_fast
+def test_compat_replaces_preimported_upstream_modules():
+ script = """
+import importlib
+from pathlib import Path
+import sys
+import types
+
+import mlx_vlm.models
+import mlx_vlm.tools.parsers
+
+from omlx.patches import mlx_vlm_minimax_m3_compat as compat
+
+module_names = (
+ "mlx_vlm.models.minimax_m3",
+ "mlx_vlm.models.minimax_m3_vl",
+ "mlx_vlm.models.minimax_m3_vl.language",
+ "mlx_vlm.tools.parsers.minimax_m3",
+)
+for name in module_names:
+ module = types.ModuleType(name)
+ module.__file__ = f"/upstream/{name.replace('.', '/')}.py"
+ sys.modules[name] = module
+ parent_name, attr = name.rsplit(".", 1)
+ setattr(sys.modules[parent_name], attr, module)
+
+assert compat.apply_mlx_vlm_minimax_m3_compat_patch()
+assert not compat.apply_mlx_vlm_minimax_m3_compat_patch()
+for name in module_names:
+ module = importlib.import_module(name)
+ assert Path(module.__file__).resolve().is_relative_to(compat._VENDOR_MLX_VLM)
+ parent_name, attr = name.rsplit(".", 1)
+ assert getattr(sys.modules[parent_name], attr) is module
+
+from omlx.oq import _build_model_sanitizer
+
+config = {
+ "model_type": "minimax_m3_vl",
+ "architectures": ["MiniMaxM3ForConditionalGeneration"],
+ "text_config": {
+ "model_type": "minimax_m3",
+ "num_hidden_layers": 1,
+ "n_shared_experts": 1,
+ },
+}
+predicate = _build_model_sanitizer(config)._omlx_cast_predicate
+prefix = "language_model.model.layers.0.block_sparse_moe"
+assert predicate(f"{prefix}.gate.weight") is False
+assert predicate(f"{prefix}.e_score_correction_bias") is False
+assert predicate(f"{prefix}.switch_mlp.gate_proj.weight") is True
+"""
+ result = subprocess.run(
+ [sys.executable, "-c", script],
+ capture_output=True,
+ text=True,
+ timeout=60,
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
+
+
def test_minimax_m3_compat_installs_vendor_modules():
from omlx.patches.mlx_vlm_minimax_m3_compat import (
apply_mlx_vlm_minimax_m3_compat_patch,
From c53fdd12e3b6c41ebb9ebf3f751c0bec629de464 Mon Sep 17 00:00:00 2001
From: Mike Wallio
Date: Thu, 5 Nov 2026 17:06:18 -0500
Subject: [PATCH 12/24] fix(chat): hide empty intermediate tool replies
Omit transcript cards without text or reasoning while retaining paired tool-call turns in API history.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
---
apps/omlx-web/omlx_web/templates/chat.html | 9 +-
apps/omlx-web/tests/chat_image_tools.test.cjs | 91 +++++++++++++++++++
2 files changed, 97 insertions(+), 3 deletions(-)
diff --git a/apps/omlx-web/omlx_web/templates/chat.html b/apps/omlx-web/omlx_web/templates/chat.html
index d5f8e3a479..4e9c1e3df7 100644
--- a/apps/omlx-web/omlx_web/templates/chat.html
+++ b/apps/omlx-web/omlx_web/templates/chat.html
@@ -1615,7 +1615,7 @@ {{ t('chat.welcome_heading') }}
x-html="renderMarkdown(msg._thinking)">
-
@@ -3559,8 +3559,11 @@ {{ t('chat.key
// Tool-round turns and web tool cards are _ui:false for the
// API/variant machinery but still render, following their
// segment's final assistant variant.
- if (msg._toolRound
- || (msg.role === 'tool' && (msg._web || msg._images || msg._imagesStripped))) {
+ if (msg.role === 'assistant' && msg._toolRound) {
+ return (this.getTextContent(msg.content).trim().length > 0
+ || this.hasVisibleThinking(msg._thinking)) && this.isToolFlowVisible(index);
+ }
+ if (msg.role === 'tool' && (msg._web || msg._images || msg._imagesStripped)) {
return this.isToolFlowVisible(index);
}
if (msg._ui === false) return false;
diff --git a/apps/omlx-web/tests/chat_image_tools.test.cjs b/apps/omlx-web/tests/chat_image_tools.test.cjs
index 2e971210a4..ff4a95f58c 100644
--- a/apps/omlx-web/tests/chat_image_tools.test.cjs
+++ b/apps/omlx-web/tests/chat_image_tools.test.cjs
@@ -859,6 +859,97 @@ for (const [label, turn, activeId, expected] of [
});
}
+for (const [label, content, thinking, visible] of [
+ ['null', null, null, false],
+ ['empty', '', '', false],
+ ['whitespace', ' \n\t ', ' \n ', false],
+ ['blank text arrays', [{ type: 'text', text: '' }, { type: 'text', text: '\n ' }], null, false],
+ ['plain text', ' \nEditing the hats.\n ', null, true],
+ ['literal JSON', '{"action":"edit_image","text":"Swap their hats"}', null, true],
+ ['text arrays', [{ type: 'text', text: ' ' }, { type: 'text', text: 'Editing' }], null, true],
+ ['reasoning only', null, 'Checking the source image.', true],
+ ['reasoning with whitespace', '\n', 'Checking the source image.', true],
+ ['reasoning with blank arrays', [{ type: 'text', text: ' \n' }], 'Checking the source image.', true],
+]) {
+ test(`tool-round visibility derives displayable ${label} without changing history`, () => {
+ const app = appFixture();
+
+ const round = {
+ id: 'round', role: 'assistant', content, _thinking: thinking,
+ _toolRound: true, _ui: false, tool_calls: [call('edit_image', {}, 'tc-1')],
+ };
+
+ const messages = [
+ { id: 'user', role: 'user', content: 'Swap their hats', _activeVariantId: 'final' },
+ round,
+ { id: 'result', role: 'tool', content: 'Edited', tool_call_id: 'tc-1', _ui: false, _images: [png] },
+ { id: 'final', role: 'assistant', content: 'Done' },
+ { id: 'other', role: 'assistant', content: 'Other variant' },
+ ];
+
+ app.messages = messages;
+ const before = structuredClone(messages);
+ const apiBefore = app.buildMessagesForApi(messages, '');
+ assert.equal(app.isMessageVisible(round, 1), visible, 'active variant');
+ assert.equal(app.isMessageVisible(messages[2], 2), true, 'image result stays visible');
+ assert.deepEqual(app.buildMessagesForApi(messages, ''), apiBefore);
+ assert.deepEqual(apiBefore.map(msg => msg.role), ['user', 'assistant', 'tool', 'assistant']);
+ assert.deepEqual(apiBefore[1].tool_calls, round.tool_calls);
+ assert.equal(apiBefore[2].tool_call_id, 'tc-1');
+ assert.deepEqual(messages, before, 'visibility never mutates protocol messages');
+
+ messages[0]._activeVariantId = 'other';
+ assert.equal(app.isMessageVisible(round, 1), false, 'inactive variant');
+ assert.equal(app.isMessageVisible(messages[2], 2), false, 'inactive image result');
+
+ app.messages = messages.slice(0, 3);
+ assert.equal(app.isMessageVisible(round, 1), visible, 'unfinished flow');
+ assert.equal(app.isMessageVisible(messages[2], 2), true, 'unfinished image result');
+ });
+}
+
+test('tool-round visibility preserves separate tool cards and ordinary assistants', () => {
+ const app = appFixture();
+ app.messages = [
+ { id: 'user', role: 'user', content: 'Edit' },
+ { role: 'tool', content: null, _ui: false, _web: { query: 'hats' } },
+ { role: 'tool', content: null, _ui: false, _imagesStripped: true },
+ { role: 'tool', content: null, _ui: false },
+ { id: 'final', role: 'assistant', content: null },
+ ];
+ assert.deepEqual(app.messages.map((msg, index) => app.isMessageVisible(msg, index)),
+ [true, true, true, false, true]);
+});
+
+test('tool-round body binding hides blank padding while preserving reasoning and content bytes', () => {
+ const app = appFixture();
+ const roundTemplate = template.split('x-show="msg.role === \'assistant\' && msg._toolRound"')[1]
+ .split('
@@ -2153,6 +2172,16 @@
+
+
+
+
+
+
+
+
@@ -2199,7 +2228,7 @@
-
@@ -2263,12 +2292,6 @@
{{ t('models.detail.cancel') }}
-
-
-
- {{ t('models.detail.lora_info') }}
-
-
diff --git a/apps/omlx-web/tests/test_admin_adapter_ui.py b/apps/omlx-web/tests/test_admin_adapter_ui.py
new file mode 100644
index 0000000000..1df0532e0a
--- /dev/null
+++ b/apps/omlx-web/tests/test_admin_adapter_ui.py
@@ -0,0 +1,95 @@
+# SPDX-License-Identifier: Apache-2.0
+"""LoRA adapter guidance in the downloader and model manager."""
+
+import json
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parents[1]
+WEB = ROOT / "omlx_web"
+CARD_KEYS = ("models.detail.adapter_info", "models.detail.adapter_no_base")
+NOTICE_KEY = "models.manager.adapter_issues_heading"
+
+
+def test_adapter_copy_is_available_in_every_locale():
+ template = (WEB / "templates/dashboard/_models.html").read_text()
+ dashboard = (WEB / "static/js/dashboard.js").read_text()
+ retired_keys = ("is_" + "adapter", "lora_" + "warning")
+
+ for key in (*CARD_KEYS, NOTICE_KEY):
+ assert key in template
+ for key in retired_keys:
+ assert key not in template
+ assert key not in dashboard
+
+ for locale in sorted((WEB / "i18n").glob("*.json")):
+ copy = json.loads(locale.read_text(encoding="utf-8"))
+ for key in CARD_KEYS:
+ assert copy[key].count("{base}") == 1, (locale.name, key)
+ assert copy[NOTICE_KEY], locale.name
+ assert not any(key in entry for key in retired_keys for entry in copy)
+
+
+def test_adapters_can_show_updates_and_report_unavailable_entries():
+ node = shutil.which("node")
+ if node is None:
+ pytest.skip("Node.js is required for dashboard behavior tests")
+ script = r"""
+const fs = require('node:fs');
+const vm = require('node:vm');
+const assert = require('node:assert/strict');
+
+const source = fs.readFileSync('omlx_web/static/js/dashboard.js', 'utf8');
+const issues = [
+ {id: 'same-name', kind: 'base_missing', reason: 'Download the base.',
+ candidates: [], path: '/models/a/same-name'},
+ {id: 'same-name', kind: 'id_collision', reason: 'Rename the folder.',
+ candidates: [], path: '/models/b/same-name'},
+];
+let payload = {models: [], adapter_issues: issues};
+const state = vm.runInNewContext(source + '\n dashboard;', {
+ localStorage: {getItem: () => null},
+ THEME_STORAGE_KEY: 'theme', ENHANCED_READABILITY_KEY: 'readability',
+ window: {t: key => key}, navigator: {language: 'en'}, document: {}, console,
+ fetch: async url => {
+ assert.equal(url, '/admin/api/models');
+ return {ok: true, json: async () => structuredClone(payload)};
+ },
+})();
+
+const repo = 'harness-hub/LFM3-1.7B-pi';
+state.hfModels = [{name: 'LFM3-1.7B-pi', repo_id: repo}];
+state.hfModelDetail = {
+ repo_id: repo, layout: 'safetensors', update_files: ['adapter_model.safetensors'],
+ adapter: {base_repo_id: 'LiquidAI/LFM3-1.7B', rank: 32, local_base_ids: []},
+};
+assert.equal(state.hfShowsUpdate(), true);
+state.hfModelDetail.unsupported_reason = 'Unsupported adapter config.';
+assert.equal(state.hfShowsUpdate(), false);
+
+(async () => {
+ await state.loadModels();
+ assert.deepEqual(state.adapterIssues, issues);
+ const firstIssues = state.adapterIssues;
+ await state.loadModels();
+ assert.equal(state.adapterIssues, firstIssues, 'identical polling must not update the notice');
+
+ payload = {models: []};
+ await state.loadModels();
+ assert.equal(state.adapterIssues.length, 0);
+})().catch(error => {
+ console.error(error);
+ process.exitCode = 1;
+});
+"""
+ result = subprocess.run(
+ [node, "-e", script],
+ cwd=ROOT,
+ capture_output=True,
+ text=True,
+ timeout=30,
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
diff --git a/apps/omlx-web/tests/test_admin_browse_downloaded_badge.py b/apps/omlx-web/tests/test_admin_browse_downloaded_badge.py
index e29482ed41..63e278b6df 100644
--- a/apps/omlx-web/tests/test_admin_browse_downloaded_badge.py
+++ b/apps/omlx-web/tests/test_admin_browse_downloaded_badge.py
@@ -58,12 +58,14 @@ def test_is_model_downloaded_needs_a_finished_local_repo():
})();
state.hfModels = [
{name: 'Qwen3-8B-4bit', repo_id: 'mlx-community/Qwen3-8B-4bit'},
+ {name: 'LFM3-1.7B-pi', repo_id: 'harness-hub/LFM3-1.7B-pi'},
{name: 'local-only', repo_id: null},
];
assert.equal(state.isModelDownloaded('mlx-community/Qwen3-8B-4bit'), true);
assert.equal(state.isModelDownloaded('MLX-Community/qwen3-8b-4bit'), true);
assert.equal(state.isModelDownloaded('someone-else/Qwen3-8B-4bit'), false);
+assert.equal(state.isModelDownloaded('harness-hub/LFM3-1.7B-pi'), true);
assert.equal(state.isModelDownloaded('someone/local-only'), false);
assert.equal(state.isModelDownloaded(undefined), false);
diff --git a/docs/admin-api.md b/docs/admin-api.md
index 83b42a66de..2ae3c73f9a 100644
--- a/docs/admin-api.md
+++ b/docs/admin-api.md
@@ -54,6 +54,7 @@ The same endpoints accept an `X-oMLX-Cache-Store: off` request header. The reque
| Endpoint | Description |
|---|---|
| `GET /admin/api/models` | Discovered models with load state, size, and settings |
+| `PUT /admin/api/adapters/{adapter_id}/base` | Set a base override with `{"base_model_id": ""}` or clear it with `{"base_model_id": null}` |
| `POST /admin/api/models/{model_id}/load`, `.../unload` | Load or unload a model |
| `POST /admin/api/models/{model_id}/requests/{request_id}/abort` | Stop one waiting, prefilling, or generating request and keep the model loaded |
| `POST /admin/api/reload` | Rescan the model directories |
@@ -65,6 +66,14 @@ The same endpoints accept an `X-oMLX-Cache-Store: off` request header. The reque
| `GET`, `POST /admin/api/models/{model_id}/profiles`, `PUT`, `DELETE .../profiles/{name}`, `POST .../profiles/{name}/apply` | Per-model profiles |
| `GET`, `POST /admin/api/profile-templates`, `PUT`, `DELETE .../{name}` | Global profile templates |
+Each row in `GET /admin/api/models` has `adapter: null` for a regular model, or an adapter object with `base_model_id` (string), `rank` (integer), `alpha` (number), and `weight_bytes` (integer).
+
+The same API serves routed-expert LoRA adapters. The supported PEFT `target_parameters` layouts are described in [LoRA adapters](../README.md#lora-adapters). Loading a routed adapter with MoE expert offload or DFlash returns a model-loading error.
+
+The top-level `adapter_issues` array describes adapter folders that could not become model entries. Each issue has `id`, `kind`, `reason`, and `path` strings, and a `candidates` array of model IDs. The issue kinds are `unsupported`, `malformed`, `base_missing`, `base_ambiguous`, `override_invalid`, and `id_collision`.
+
+The base override returns `{"success": true, "id": string, "base_model_id": string or null, "adapter": object or null, "issue": object or null}`. The `adapter` and `issue` objects use the same fields as the list response. The endpoint returns `404` for an unknown adapter, `400` when the requested base is not a candidate, and `409` while the adapter is loaded or loading.
+
`POST /v1/models/{model_id}/load` and `/unload` do the same as the admin load and unload, and accept the main key or a sub key.
### Downloads and uploads
@@ -81,6 +90,8 @@ The same endpoints accept an `X-oMLX-Cache-Store: off` request header. The reque
| `/admin/api/ms/...` | The same for ModelScope |
| `/admin/api/upload/...` | Upload oQ models to Hugging Face |
+The Hugging Face model card includes `adapter: null` or an object with `base_repo_id` (string), `rank` (integer), and `local_base_ids` (array of matching local model IDs). An empty `local_base_ids` array does not block downloads. An unsupported adapter config returns `adapter: null` and an `unsupported_reason` string.
+
### Quantization
| Endpoint | Description |
diff --git a/omlx/admin/hf_downloader.py b/omlx/admin/hf_downloader.py
index 2680b6823e..e0ecbfc059 100644
--- a/omlx/admin/hf_downloader.py
+++ b/omlx/admin/hf_downloader.py
@@ -29,6 +29,7 @@
from typing import Optional
from urllib.parse import urlparse
+import httpx
from huggingface_hub import HfApi, hf_hub_download, snapshot_download
from huggingface_hub._local_folder import read_download_metadata
from huggingface_hub.utils import (
@@ -45,11 +46,17 @@
from .. import gguf
+try:
+ from httpx2 import RequestError as HubRequestError
+except ImportError:
+ HubRequestError = httpx.RequestError
+
logger = logging.getLogger(__name__)
# Timeout for HuggingFace API calls (seconds).
# Prevents server from hanging when HF is unreachable.
_HF_API_TIMEOUT = 10
+_ADAPTER_CONFIG_MAX_BYTES = 1024 * 1024
# Seconds with no disk or wire activity before considering the download
# stalled.
@@ -1586,6 +1593,57 @@ async def search_models(
"hf_token_invalid": token_rejected,
}
+ @staticmethod
+ async def _get_adapter_info(
+ repo_id: str,
+ endpoint: str | None,
+ token: str | None,
+ file_sizes: dict[str, int],
+ ) -> tuple[dict | None, str | None]:
+ from ..exceptions import AdapterError
+ from ..lora_adapter import (
+ ADAPTER_CONFIG_NAME,
+ ADAPTER_WEIGHTS_NAME,
+ parse_adapter_config,
+ )
+
+ filename = ADAPTER_CONFIG_NAME
+ if ADAPTER_WEIGHTS_NAME not in file_sizes:
+ if "adapter_model.bin" in file_sizes:
+ return None, (
+ "The adapter ships adapter_model.bin, and oMLX never loads "
+ f"pickled weights. Re-save it as {ADAPTER_WEIGHTS_NAME}."
+ )
+ return None, (
+ f"{ADAPTER_WEIGHTS_NAME} is missing. Choose a repo that includes it."
+ )
+ if file_sizes[filename] > _ADAPTER_CONFIG_MAX_BYTES:
+ return None, f"{filename} is larger than 1 MiB."
+
+ try:
+ config_path = await asyncio.wait_for(
+ asyncio.to_thread(
+ hf_hub_download,
+ repo_id=repo_id,
+ filename=filename,
+ endpoint=endpoint,
+ token=token,
+ ),
+ timeout=_HF_API_TIMEOUT,
+ )
+ with Path(config_path).open("rb") as handle:
+ raw = handle.read(_ADAPTER_CONFIG_MAX_BYTES + 1)
+ except TimeoutError:
+ return None, f"Could not read {filename}: request timed out."
+ except (HfHubHTTPError, HubRequestError, httpx.RequestError, OSError) as error:
+ return None, f"Could not read {filename}: {error}"
+
+ try:
+ config = parse_adapter_config(raw)
+ except AdapterError as error:
+ return None, str(error)
+ return {"base_repo_id": config.base_ref, "rank": config.rank}, None
+
@staticmethod
async def get_model_info(
repo_id: str, local_dir: Path | None = None, token: str | None = None
@@ -1618,8 +1676,14 @@ async def get_model_info(
)
update_files = await asyncio.to_thread(_update_files, files, local_dir)
- # Detect LoRA/adapter repos (adapter_config.json is peft standard)
- is_adapter = any(f["name"] == "adapter_config.json" for f in files)
+ adapter = None
+ unsupported_reason = _unsupported_repo_reason(info)
+ if unsupported_reason is None:
+ file_sizes = {row["name"]: row["size"] for row in files}
+ if "adapter_config.json" in file_sizes:
+ adapter, unsupported_reason = await HFDownloader._get_adapter_info(
+ repo_id, endpoint, token, file_sizes
+ )
# Params from the dtype histogram (logical count). Size from current
# revision blob bytes — U32 packed quants are not 4 bytes/param (#3401).
@@ -1677,7 +1741,7 @@ async def get_model_info(
"layout": layout,
"update_files": update_files,
"download_all_size": download_all_size or 0,
- "unsupported_reason": _unsupported_repo_reason(info),
+ "unsupported_reason": unsupported_reason,
"tags": list(info.tags) if info.tags else [],
"pipeline_tag": info.pipeline_tag or "",
"params": params,
@@ -1690,7 +1754,7 @@ async def get_model_info(
"updated_at": (
info.last_modified.isoformat() if info.last_modified else ""
),
- "is_adapter": is_adapter,
+ "adapter": adapter,
}
def __init__(
diff --git a/omlx/admin/routes.py b/omlx/admin/routes.py
index 2fb362561c..2f48a00f5d 100644
--- a/omlx/admin/routes.py
+++ b/omlx/admin/routes.py
@@ -591,6 +591,10 @@ def validate_draft_path(cls, value: str | None) -> str | None:
return value or None
+class AdapterBaseRequest(BaseModel):
+ base_model_id: str | None = None
+
+
def _normalize_profile_settings(
value: dict[str, Any] | None, *, universal: bool = False
) -> dict[str, Any] | None:
@@ -2699,7 +2703,7 @@ async def list_models(is_admin: bool = Depends(require_admin)):
"model_path": model_info.get("model_path", ""),
"display_name": _model_display_name(
model_id,
- model_info.get("model_path", ""),
+ None if model_info.get("adapter") else model_info.get("model_path", ""),
model_dirs,
source_repo_id=model_info.get("source_repo_id"),
source_path=model_info.get("source_path"),
@@ -2748,6 +2752,7 @@ async def list_models(is_admin: bool = Depends(require_admin)):
"capabilities": model_info.get("capabilities", []),
"tasks": model_info.get("tasks", []),
"image_metadata": model_info.get("image_metadata"),
+ "adapter": model_info.get("adapter"),
"last_access": model_info.get("last_access"),
"external_engines": external_engines,
"dflash_compatible": compat_ok,
@@ -2770,7 +2775,8 @@ async def list_models(is_admin: bool = Depends(require_admin)):
"is_paroquant": is_paroquant,
"paroquant_reason": paroquant_reason,
"activation_fp16_supported": activation_fp16_supported,
- "prefill_helper_supported": stage_adapter_for(
+ "prefill_helper_supported": model_info.get("adapter") is None
+ and stage_adapter_for(
model_info.get("config_model_type"),
model_info.get("engine_type"),
model_info.get("model_path"),
@@ -2828,7 +2834,94 @@ async def list_models(is_admin: bool = Depends(require_admin)):
}
)
- return {"models": models}
+ return {
+ "models": models,
+ "adapter_issues": [
+ _adapter_issue_row(issue)
+ for issue in getattr(engine_pool, "adapter_issues", ())
+ ],
+ }
+
+
+def _adapter_issue_row(issue) -> dict:
+ return {
+ "id": issue.public_id,
+ "kind": issue.kind.value,
+ "reason": issue.detail,
+ "candidates": list(issue.candidates),
+ "path": str(issue.path),
+ }
+
+
+@router.put("/api/adapters/{adapter_id}/base")
+async def set_adapter_base(
+ adapter_id: str,
+ request: AdapterBaseRequest,
+ is_admin: bool = Depends(require_admin),
+):
+ """Set or clear a local base override for a LoRA adapter."""
+ engine_pool = _get_engine_pool()
+ if engine_pool is None:
+ raise HTTPException(status_code=503, detail="Engine pool not initialized")
+ settings_manager = _require_settings_manager()
+ global_settings = _get_global_settings()
+ if global_settings is None:
+ raise HTTPException(status_code=503, detail="Server not initialized")
+
+ entry = engine_pool.get_entry(adapter_id)
+ adapter = entry.adapter if entry is not None else None
+ issues = [
+ issue for issue in engine_pool.adapter_issues if issue.public_id == adapter_id
+ ]
+ if adapter is None and not issues:
+ raise HTTPException(status_code=404, detail=f"Adapter not found: {adapter_id}")
+
+ base_id = request.base_model_id
+ if base_id is not None and not any(
+ candidate.model_id == base_id
+ for candidate in engine_pool.adapter_base_candidates()
+ ):
+ raise HTTPException(status_code=400, detail=f"Invalid adapter base: {base_id}")
+
+ if (
+ len(issues) > 1
+ or (entry is not None and issues)
+ or any(issue.kind.value == "id_collision" for issue in issues)
+ ):
+ raise HTTPException(
+ status_code=409,
+ detail=f"Adapter id {adapter_id!r} is not unique. Rename the adapter directory.",
+ )
+ if adapter is not None and (entry.engine is not None or entry.is_loading):
+ raise HTTPException(
+ status_code=409,
+ detail=f"Unload adapter {adapter_id!r} before changing its base.",
+ )
+
+ settings_manager.set_adapter_base(adapter_id, base_id)
+ _rediscover_models(
+ engine_pool,
+ global_settings,
+ settings_manager,
+ settings_manager.get_pinned_model_ids(),
+ )
+ entry = engine_pool.get_entry(adapter_id)
+ adapter = entry.adapter if entry is not None else None
+ issues = [
+ issue for issue in engine_pool.adapter_issues if issue.public_id == adapter_id
+ ]
+ logger.info("Set base override for adapter %r to %r", adapter_id, base_id)
+ return {
+ "success": True,
+ "id": adapter_id,
+ "base_model_id": settings_manager.get_adapter_bases().get(adapter_id),
+ "adapter": adapter.as_status() if adapter is not None else None,
+ "issue": (
+ _adapter_issue_row(issues[0])
+ if adapter is None and len(issues) == 1
+ else None
+ ),
+ }
@router.get("/api/models/{model_id}/lora-adapters")
@@ -3062,14 +3155,22 @@ async def import_mtplx(
is_admin: bool = Depends(_require_admin_or_bearer),
):
"""Import an MTPLX side-car MTP head into the model's checkpoint index."""
- from ..oq import import_mtplx_sidecar
-
engine_pool = _get_engine_pool()
if engine_pool is None:
raise HTTPException(status_code=503, detail="Engine pool not initialized")
entry = engine_pool.get_entry(model_id)
if entry is None:
raise HTTPException(status_code=404, detail=f"Model not found: {model_id}")
+ if entry.adapter is not None:
+ raise HTTPException(
+ status_code=400,
+ detail=(
+ "MTPLX import is not supported on an adapter. "
+ f"Import against the base model ID {entry.adapter.base.model_id!r} instead."
+ ),
+ )
+
+ from ..oq import import_mtplx_sidecar
try:
result = await asyncio.to_thread(import_mtplx_sidecar, entry.model_path)
@@ -3125,12 +3226,18 @@ async def update_model_settings(
if entry is None:
raise HTTPException(status_code=404, detail=f"Model not found: {model_id}")
- # Get current settings
- current_settings = settings_manager.get_settings(model_id)
-
# Apply updates — use model_fields_set to distinguish "sent as null"
# (clear to default) from "not sent" (don't touch).
sent = request.model_fields_set
+ if (
+ getattr(entry, "adapter", None) is not None
+ and "prefill_helper_node_id" in sent
+ and request.prefill_helper_node_id
+ ):
+ raise HTTPException(
+ status_code=400, detail="LoRA adapters do not support remote prefill."
+ )
+ current_settings = settings_manager.get_settings(model_id)
kv_scheme = current_settings.turboquant_kv_scheme
kv_bits = current_settings.turboquant_kv_bits
if "turboquant_kv_scheme" in sent:
@@ -3784,7 +3891,7 @@ async def update_model_settings(
if not _oq_a8_kernels_available():
# A8 here reaches only the helper's layers.
helper_fields |= {"a8_prefill_enabled", "a8_prefill_min_tokens"}
- if helper_fields & set(sent):
+ if getattr(entry, "adapter", None) is None and helper_fields & set(sent):
if hasattr(entry.engine, "configure_prefill_helper"):
# Applied to the loaded model in place; no reload.
entry.engine.configure_prefill_helper(current_settings)
@@ -8638,6 +8745,23 @@ async def get_hf_model_info(
local_dir=local_dir,
token=request.headers.get("x-hf-token") or None,
)
+ adapter = result.get("adapter")
+ if adapter is not None:
+ try:
+ engine_pool = _get_engine_pool() if _get_engine_pool else None
+ except HTTPException:
+ engine_pool = None
+ if engine_pool is None:
+ adapter["local_base_ids"] = []
+ else:
+ from ..lora_adapter import match_bases
+
+ adapter["local_base_ids"] = sorted(
+ candidate.model_id
+ for candidate in match_bases(
+ adapter["base_repo_id"], engine_pool.adapter_base_candidates()
+ )
+ )
if _hf_downloader is not None:
result["disk_free"] = await asyncio.to_thread(
_free_disk_bytes, _hf_downloader.model_dir
@@ -8711,7 +8835,7 @@ def _add_model(
)
def _add_adapter(model_path: Path, model_name: str, **kwargs) -> None:
- # Listed so it can be deleted; it is applied from a model's settings.
+ # List adapter files separately from full checkpoints.
count = len(models)
_add_model(model_path, model_name, **kwargs)
if len(models) > count:
@@ -8854,6 +8978,21 @@ async def delete_hf_model(
_refresh_pool_after_delete(model_name, engine_pool, global_settings)
return {"success": True, "message": f"Model '{model_name}' deleted"}
+ from ..model_discovery import _is_adapter_dir
+
+ has_entry = getattr(entry, "model_id", None) == model_name
+ adapter = getattr(entry, "adapter", None) if has_entry else None
+
+ def matches_folder(candidate: Path) -> bool:
+ if not candidate.is_dir() or not _is_listed_model_folder(candidate):
+ return False
+ if adapter is not None:
+ return (
+ _is_adapter_dir(candidate)
+ and candidate.absolute() == adapter.source.path.absolute()
+ )
+ return not has_entry or not _is_adapter_dir(candidate)
+
# Search the discovery directories in flat, HF cache and org-folder layouts
model_path = None
parent_model_dir = None
@@ -8861,7 +9000,7 @@ async def delete_hf_model(
if not model_dir.exists():
continue
candidate = model_dir / model_name
- if candidate.is_dir() and _is_listed_model_folder(candidate):
+ if matches_folder(candidate):
model_path = candidate
parent_model_dir = model_dir
break
@@ -8872,19 +9011,23 @@ async def delete_hf_model(
if hf_resolved is not None:
# The repo dir owns the snapshot symlinks and their blobs, so
# it is removed as one unit.
- if hf_resolved.model_id == model_name and (
- _is_hf_cache_mlx_compatible(
- hf_resolved.snapshot_path, hf_resolved.source_repo_id
+ if (
+ adapter is None
+ and hf_resolved.model_id == model_name
+ and (
+ _is_hf_cache_mlx_compatible(
+ hf_resolved.snapshot_path, hf_resolved.source_repo_id
+ )
+ or gguf.is_gguf_folder(hf_resolved.snapshot_path)
+ or (not has_entry and is_adapter_dir(hf_resolved.snapshot_path))
)
- or gguf.is_gguf_folder(hf_resolved.snapshot_path)
- or is_adapter_dir(hf_resolved.snapshot_path)
):
model_path = subdir
parent_model_dir = model_dir
break
continue
candidate = subdir / model_name
- if candidate.is_dir() and _is_listed_model_folder(candidate):
+ if matches_folder(candidate):
model_path = candidate
parent_model_dir = model_dir
break
@@ -8973,13 +9116,19 @@ def _refresh_pool_after_delete(model_name: str, engine_pool, global_settings) ->
# so they can be reused by another model.
if settings_manager:
settings_manager.delete_settings(model_name)
+ _rediscover_models(engine_pool, global_settings, settings_manager, pinned_models)
+ logger.info("Model pool refreshed after deletion")
+
+
+def _rediscover_models(
+ engine_pool, global_settings, settings_manager, pinned_models
+) -> None:
engine_pool.discover_models(
[str(d) for d in global_settings.get_effective_model_dirs()],
pinned_models,
)
if settings_manager:
engine_pool.apply_settings_overrides(settings_manager)
- logger.info("Model pool refreshed after deletion")
def _unlink_hf_cache_file(link: Path, repo_dir: Path) -> None:
diff --git a/omlx/cache/paged_ssd_cache.py b/omlx/cache/paged_ssd_cache.py
index a15b1fd356..fed6788dca 100644
--- a/omlx/cache/paged_ssd_cache.py
+++ b/omlx/cache/paged_ssd_cache.py
@@ -436,6 +436,11 @@ def numerics_revision_for_model(model: Any) -> str | None:
for module in modules
):
revisions.add("a8-prefill-1")
+ if HAS_MLX:
+ from ..lora_adapter import lora_revision_of
+
+ if lora := lora_revision_of(model):
+ revisions.add(lora)
return ",".join(sorted(revisions)) or None
diff --git a/omlx/cluster/model_inventory.py b/omlx/cluster/model_inventory.py
index ed62467925..2ba91abdf5 100644
--- a/omlx/cluster/model_inventory.py
+++ b/omlx/cluster/model_inventory.py
@@ -96,7 +96,7 @@ def engine_pool_model_inventory(pool: Any) -> list[dict[str, Any]]:
raw_models = status.get("models", []) if isinstance(status, dict) else []
models: list[dict[str, Any]] = []
for item in raw_models:
- if not isinstance(item, dict):
+ if not isinstance(item, dict) or item.get("adapter") is not None:
continue
model_path = item.get("model_path")
model_type = item.get("model_type", "llm")
diff --git a/omlx/engine/batched.py b/omlx/engine/batched.py
index 40cb9bcd64..4883567ab6 100644
--- a/omlx/engine/batched.py
+++ b/omlx/engine/batched.py
@@ -13,7 +13,7 @@
import threading
import time
from collections.abc import AsyncIterator
-from typing import Any
+from typing import TYPE_CHECKING, Any
from ..adapter.output_parser import repair_tool_parser
from ..api.tool_calling import convert_tools_for_template
@@ -39,6 +39,9 @@
_warn_scheduler_unreachable_once,
)
+if TYPE_CHECKING:
+ from ..lora_adapter import AdapterBinding
+
logger = logging.getLogger(__name__)
@@ -98,6 +101,8 @@ def __init__(
enable_thinking: bool | None = None,
model_settings: Any | None = None,
prefill_eviction_callback: Any | None = None,
+ *,
+ lora: "AdapterBinding | None" = None,
):
"""
Initialize the batched engine.
@@ -117,6 +122,7 @@ def __init__(
self._enable_thinking = enable_thinking
self._model_settings = model_settings
self._prefill_eviction_callback = prefill_eviction_callback
+ self._lora = lora
self._model = None
self._tokenizer = None
@@ -373,9 +379,22 @@ def _load_model_sync():
)
loop = asyncio.get_running_loop()
- self._model, self._tokenizer = await loop.run_in_executor(
+ model, tokenizer = await loop.run_in_executor(
get_mlx_executor(), _load_model_sync
)
+ if self._lora is not None:
+ from ..lora_adapter import attach_lora
+
+ wrapped = await loop.run_in_executor(
+ get_mlx_executor(), attach_lora, model, self._lora
+ )
+ logger.info(
+ "Applied LoRA adapter %s to %s (%d modules)",
+ self._lora.source.public_id,
+ self._lora.base.model_id,
+ wrapped,
+ )
+ self._model, self._tokenizer = model, tokenizer
# The scheduler repairs only its deep copy, and API tool parsing reads
# this tokenizer. Repair it here only for MiMo-format templates (#4933).
if is_mimo_tool_template(getattr(self._tokenizer, "chat_template", None)):
@@ -464,7 +483,7 @@ def _load_model_sync():
# After the fp16 recast so the adapter takes the activation dtype, and
# before the fusions and packers that replace the projections.
lora_path = getattr(self._model_settings, "lora_adapter", None)
- if lora_path:
+ if lora_path and self._lora is None:
wrapped = await loop.run_in_executor(
get_mlx_executor(), apply_adapter, self._model, lora_path
)
diff --git a/omlx/engine/vlm.py b/omlx/engine/vlm.py
index 3f84f1274f..4745010612 100644
--- a/omlx/engine/vlm.py
+++ b/omlx/engine/vlm.py
@@ -37,7 +37,7 @@
import time
from collections.abc import AsyncIterator
from pathlib import Path
-from typing import Any
+from typing import TYPE_CHECKING, Any
import mlx.core as mx
import numpy as np
@@ -104,6 +104,9 @@
from .qwen3_omni_realtime import Qwen3OmniVoiceBackend
from .realtime_voice import RealtimeVoiceError, RealtimeVoiceSession
+if TYPE_CHECKING:
+ from ..lora_adapter import AdapterBinding
+
logger = logging.getLogger(__name__)
_VOICE_BACKENDS = {
@@ -1916,6 +1919,8 @@ def __init__(
enable_thinking: bool | None = None,
model_settings: Any | None = None,
prefill_eviction_callback: Any | None = None,
+ *,
+ lora: "AdapterBinding | None" = None,
):
self._model_name = model_name
self._trust_remote_code = trust_remote_code
@@ -1924,6 +1929,7 @@ def __init__(
self._enable_thinking = enable_thinking
self._model_settings = model_settings
self._prefill_eviction_callback = prefill_eviction_callback
+ self._lora = lora
self._vlm_model = None
self._processor = None
@@ -2320,9 +2326,22 @@ def _load_vlm_sync():
return loaded
loop = asyncio.get_running_loop()
- self._vlm_model, self._processor = await loop.run_in_executor(
+ model, processor = await loop.run_in_executor(
get_mlx_executor(), _load_vlm_sync
)
+ if self._lora is not None:
+ from ..lora_adapter import attach_lora
+
+ wrapped = await loop.run_in_executor(
+ get_mlx_executor(), attach_lora, model, self._lora
+ )
+ logger.info(
+ "Applied LoRA adapter %s to %s (%d modules)",
+ self._lora.source.public_id,
+ self._lora.base.model_id,
+ wrapped,
+ )
+ self._vlm_model, self._processor = model, processor
from ..models.vlm import restore_bonsai_quantized_modules
@@ -2463,7 +2482,7 @@ def _load_vlm_sync():
# After the fp16 recast so the adapter takes the activation dtype, and
# before the fusions and packers that replace the projections.
lora_path = getattr(self._model_settings, "lora_adapter", None)
- if lora_path:
+ if lora_path and self._lora is None:
wrapped = await loop.run_in_executor(
get_mlx_executor(), apply_adapter, self._vlm_model, lora_path
)
@@ -2787,7 +2806,11 @@ def _enable_ane_prefill():
await self._engine.engine.start()
scheduler = self._engine.engine.scheduler
- stage_adapter = stage_adapter_for(self.model_type, "vlm", self._model_name)
+ stage_adapter = (
+ stage_adapter_for(self.model_type, "vlm", self._model_name)
+ if self._lora is None
+ else None
+ )
if stage_adapter is not None:
self._prefill_helper = PrefillHelperManager(
model_path=self._model_name,
diff --git a/omlx/engine_pool.py b/omlx/engine_pool.py
index 57fb8e58de..06c6d331b0 100644
--- a/omlx/engine_pool.py
+++ b/omlx/engine_pool.py
@@ -30,6 +30,7 @@
from .cluster.deployment import ClusterDeployment
from .cluster.registry import ClusterRegistry
from .engine.image import ImageEngine
+ from .lora_adapter import AdapterBinding, AdapterIssue, BaseCandidate
from .model_settings import ModelSettingsManager
import mlx.core as mx
@@ -426,6 +427,7 @@ class EngineEntry:
load_failed: bool = False # Sticky until the next discovery refresh
load_failure_message: str | None = None
load_failure_at: float | None = None
+ adapter: AdapterBinding | None = None
class EnginePool:
@@ -461,6 +463,8 @@ def __init__(
are wired up the pool admits unconditionally.
"""
self._entries: dict[str, EngineEntry] = {}
+ self._adapter_issues: tuple[AdapterIssue, ...] = ()
+ self._changed_adapter_ids: set[str] = set()
self._lock = asyncio.Lock()
self._current_model_memory = 0
# Splash engines between launch and load completion, which the memory
@@ -584,6 +588,8 @@ async def _stop_gpu_keep_warm(self) -> None:
def _distributed_deployment_for_entry(
self, entry: EngineEntry
) -> ClusterDeployment | None:
+ if entry.adapter is not None:
+ return None
if entry.engine is not None:
# A newly activated registry record must not retroactively relabel
# an already-loaded local engine. The deployment applies only
@@ -1576,8 +1582,7 @@ def discover_models(
model_dirs: Path or list of paths to directories containing model subdirectories
pinned_models: List of model IDs to pin (never evict)
"""
- from pathlib import Path
-
+ from .lora_adapter import discover_adapters
from .model_discovery import discover_models_from_dirs
if isinstance(model_dirs, str):
@@ -1587,13 +1592,43 @@ def discover_models(
self._model_dirs = dirs
gguf_root = _gguf_model_root()
- adapters: dict[str, str] = {}
- discovered = discover_models_from_dirs(dirs, gguf_root, adapters)
- self._lora_adapters = adapters
+ adapter_paths: dict[str, str] = {}
+ adapter_dirs: list[Path] = []
+ discovered = discover_models_from_dirs(
+ dirs, gguf_root, adapter_paths, adapter_dirs=adapter_dirs
+ )
+ self._lora_adapters = adapter_paths
+ get_bases = getattr(self._settings_manager, "get_adapter_bases", None)
+ adapters = discover_adapters(
+ adapter_dirs, discovered, get_bases() if callable(get_bases) else {}
+ )
+ discovered.update(adapters.entries)
+ previous = {
+ (issue.public_id, issue.kind, issue.detail)
+ for issue in self._adapter_issues
+ }
+ for issue in adapters.issues:
+ key = (issue.public_id, issue.kind, issue.detail)
+ if key not in previous:
+ logger.warning("Adapter '%s': %s", issue.public_id, issue.detail)
+ previous.add(key)
+ self._adapter_issues = adapters.issues
pinned_set = set(pinned_models or [])
+ self._changed_adapter_ids.clear()
+ for issue in adapters.issues:
+ existing = self._entries.get(issue.public_id)
+ if (
+ existing is not None
+ and existing.adapter is None
+ and (existing.engine is not None or existing.is_loading)
+ and Path(existing.model_path).resolve() == issue.path.resolve()
+ and issue.public_id not in discovered
+ ):
+ self._changed_adapter_ids.add(issue.public_id)
for model_id, info in discovered.items():
+ adapter = getattr(info, "adapter", None)
existing = self._entries.get(model_id)
if existing is not None and (
existing.engine is not None or existing.is_loading
@@ -1602,6 +1637,13 @@ def discover_models(
# update the pinned flag. Replacing an in-flight entry would
# orphan the engine the load attaches on completion (#2307).
existing.is_pinned = model_id in pinned_set
+ if (existing.adapter is None) != (adapter is None) or (
+ existing.adapter is not None
+ and adapter is not None
+ and existing.adapter.source.path.resolve()
+ != adapter.source.path.resolve()
+ ):
+ self._changed_adapter_ids.add(model_id)
else:
# New or unloaded model: create fresh entry
self._entries[model_id] = EngineEntry(
@@ -1635,6 +1677,7 @@ def discover_models(
model_format=getattr(info, "model_format", None),
source_path=getattr(info, "source_path", None),
is_pinned=model_id in pinned_set,
+ adapter=adapter,
)
if model_id in pinned_set:
@@ -1672,6 +1715,15 @@ def lora_adapters(self) -> dict[str, str]:
"""LoRA adapter folders found in the model roots, by adapter id."""
return dict(self._lora_adapters)
+ @property
+ def adapter_issues(self) -> tuple[AdapterIssue, ...]:
+ return self._adapter_issues
+
+ def adapter_base_candidates(self) -> tuple[BaseCandidate, ...]:
+ from .lora_adapter import base_candidates
+
+ return base_candidates(self._entries.values())
+
_MODEL_TYPE_TO_ENGINE: dict[ModelType, EngineType] = {
"llm": "batched",
"vlm": "vlm",
@@ -1689,8 +1741,14 @@ def _entry_is_diffusion_model(entry: EngineEntry) -> bool:
model_type = (entry.config_model_type or "").lower().replace("-", "_")
return model_type == "diffusion_gemma"
- @staticmethod
- def _raise_if_entry_unavailable(entry: EngineEntry) -> None:
+ def _raise_if_entry_unavailable(self, entry: EngineEntry) -> None:
+ if entry.model_id in self._changed_adapter_ids:
+ raise ModelLoadingError(
+ entry.model_id,
+ f"Model '{entry.model_id}' changed between a base and a LoRA adapter "
+ "or changed adapter directory. "
+ "Unload it and rediscover models before serving it.",
+ )
reason = model_unavailable_reason(entry.config_model_type)
if reason is not None:
raise ModelUnavailableError(entry.model_id, reason)
@@ -1737,7 +1795,8 @@ def apply_settings_overrides(
@classmethod
def _starts_with_lightning_mtp(cls, entry: EngineEntry) -> bool:
if (
- entry.is_helper
+ entry.adapter is not None
+ or entry.is_helper
or entry.source_type == "cluster"
or entry.model_type not in ("llm", "vlm")
or cls._entry_is_diffusion_model(entry)
@@ -1751,7 +1810,8 @@ def recommended_sampling_settings(cls, entry: EngineEntry) -> dict:
Values come from generation_config.json and family defaults. OCR
defaults replace them, so OCR models keep their request-time values.
- Temporary cluster entries get none.
+ Adapters with a thinking toggle start with thinking off. Temporary
+ cluster entries get none.
"""
if (
entry.is_helper
@@ -1765,6 +1825,8 @@ def recommended_sampling_settings(cls, entry: EngineEntry) -> dict:
return {k: v for k, v in values.items() if k == "temperature"}
ocr = OCR_MODEL_GENERATION_DEFAULTS.get(entry.config_model_type, {})
values.update({k: v for k, v in ocr.items() if k in SAMPLING_SETTING_KEYS})
+ if entry.adapter is not None and entry.thinking_default is not None:
+ values["enable_thinking"] = False
return values
def get_model_ids(self) -> list[str]:
@@ -1827,6 +1889,8 @@ def resolve_cluster_model_id(self, model_path: str) -> str:
)
matches = []
for model_id, entry in self._entries.items():
+ if entry.adapter is not None:
+ continue
entry_path = Path(entry.model_path).expanduser()
entry_key = (
str(entry_path.resolve()) if entry_path.exists() else str(entry_path)
@@ -1870,7 +1934,8 @@ def register_cluster_model(
exact = [
(model_id, entry)
for model_id, entry in self._entries.items()
- if str(Path(entry.model_path).expanduser().resolve()) == candidate_key
+ if entry.adapter is None
+ and str(Path(entry.model_path).expanduser().resolve()) == candidate_key
]
if exact:
model_id, entry = self._select_cluster_path_match(exact)
@@ -2205,6 +2270,7 @@ def _has_mlx_lm_path(entry: EngineEntry) -> bool:
return (
model_type not in VLM_NATIVE_TEXT_MODEL_TYPES
and model_type != "minicpmv4_7"
+ and not (entry.adapter is not None and model_type.startswith("lfm3_"))
)
def _force_lm_replaces_engine(self, model_id: str) -> bool:
@@ -2270,6 +2336,8 @@ def splash_target(
entry = self._entries.get(model_id)
if entry is None:
return None, f"Model '{model_id}' not found"
+ if entry.adapter is not None:
+ return None, f"Splash cannot apply LoRA adapter '{model_id}'"
if entry.engine_type not in ("batched", "vlm"):
return None, "Splash serves language models only"
return resolve_splash_target(
@@ -2365,6 +2433,11 @@ async def _check_splash_launcher(
if callable(get_settings):
settings = get_settings(model_id)
if self.external_engine_id(model_id, settings):
+ entry = self._entries.get(model_id)
+ if entry is not None and entry.adapter is not None:
+ raise ModelLoadingError(
+ model_id, f"Splash cannot apply LoRA adapter '{model_id}'"
+ )
await asyncio.to_thread(
find_splash_binary, get_global_settings().integrations.splash_path
)
@@ -2842,6 +2915,8 @@ async def get_engine(
ModelLoadingError: If model is already being loaded
"""
entry = self._entries.get(model_id)
+ if entry is not None and model_id in self._changed_adapter_ids:
+ self._raise_if_entry_unavailable(entry)
if force_lm and entry is not None and not self._has_mlx_lm_path(entry):
# The VLM engine is the only text engine for these families.
force_lm = False
@@ -3165,6 +3240,8 @@ async def get_engine(
)
loaded = self._entries[model_id]
+ if model_id in self._changed_adapter_ids:
+ self._raise_if_entry_unavailable(loaded)
if ngram_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
@@ -4299,6 +4376,45 @@ async def _load_engine(
raise ModelLoadingError(model_id)
await self._check_splash_launcher(model_id, runtime_settings)
+ 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)
+
+ if entry.adapter is not None:
+ force_lm = force_lm and self._has_mlx_lm_path(entry)
+ registry = self._cluster_registry
+ if entry.source_type == "cluster" or (
+ registry is not None
+ and registry.get_for_model(entry.model_path) is not None
+ ):
+ feature = "distributed cluster inference"
+ elif getattr(model_settings, "prefill_helper_node_id", None):
+ feature = "a remote prefill helper"
+ elif entry.engine_type not in ("batched", "vlm"):
+ feature = f"the {entry.engine_type} engine"
+ elif entry.engine_type == "batched" and not self._has_mlx_lm_path(entry):
+ feature = "the batched language engine for this model family"
+ elif getattr(model_settings, "mtp_enabled", False) or getattr(
+ model_settings, "vlm_mtp_enabled", False
+ ):
+ feature = "multi-token prediction (MTP)"
+ elif getattr(model_settings, "qwen35_ane_prefill_enabled", False):
+ feature = "ANE prefill"
+ elif entry.adapter.source.has_routed_targets and getattr(
+ model_settings, "moe_expert_offload_enabled", False
+ ):
+ feature = "MoE expert offload"
+ elif entry.adapter.source.has_routed_targets and getattr(
+ model_settings, "dflash_enabled", False
+ ):
+ feature = "DFlash"
+ else:
+ feature = None
+ if feature is not None:
+ raise ModelLoadingError(
+ model_id, f"LoRA adapter '{model_id}' cannot run with {feature}"
+ )
+
entry.is_loading = True
entry.loading_started_at = time.monotonic()
self._wake_process_memory_enforcer(active=True)
@@ -4316,10 +4432,6 @@ async def _load_engine(
else:
logger.info(f"Loading model: {model_id}")
- # Retrieve per-model settings for post-load transforms
- 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)
# A status read may have logged a forced offload long before this
# load. Log it again next to the load.
for kind in ("qwen4_ple_ssd_offload", "deepseek_v41_engram_ssd_offload"):
@@ -4506,6 +4618,7 @@ async def prefill_eviction_callback(
scheduler_config=self._scheduler_config,
model_settings=model_settings,
prefill_eviction_callback=prefill_eviction_callback,
+ lora=entry.adapter,
)
elif entry.engine_type == "audio_stt":
engine = STTEngine(model_name=entry.model_path)
@@ -4543,6 +4656,7 @@ async def prefill_eviction_callback(
scheduler_config=self._scheduler_config,
model_settings=model_settings,
prefill_eviction_callback=prefill_eviction_callback,
+ lora=entry.adapter,
)
if isinstance(engine, SplashEngine):
@@ -4580,6 +4694,7 @@ async def prefill_eviction_callback(
scheduler_config=self._scheduler_config,
model_settings=model_settings,
prefill_eviction_callback=prefill_eviction_callback,
+ lora=entry.adapter,
)
try:
await self._start_engine(engine)
@@ -4614,6 +4729,7 @@ async def prefill_eviction_callback(
scheduler_config=self._scheduler_config,
model_settings=model_settings,
prefill_eviction_callback=prefill_eviction_callback,
+ lora=entry.adapter,
)
try:
await self._start_engine(engine)
@@ -5084,6 +5200,7 @@ def get_status(self) -> dict:
"preserve_thinking_default": e.preserve_thinking_default,
"reasoning_efforts": e.reasoning_efforts,
"source_type": e.source_type,
+ "adapter": e.adapter.as_status() if e.adapter else None,
"source_repo_id": e.source_repo_id,
"model_format": e.model_format,
"source_path": e.source_path,
diff --git a/omlx/exceptions.py b/omlx/exceptions.py
index 5995f171af..38afcc1aad 100644
--- a/omlx/exceptions.py
+++ b/omlx/exceptions.py
@@ -19,6 +19,7 @@
"""
from collections.abc import Callable
+from pathlib import Path
from typing import Any
# Direction of the memory_guard_tier knob. Spelled out everywhere a message
@@ -350,6 +351,52 @@ class TokenizerError(ModelError):
pass
+class AdapterError(ModelError):
+ """
+ A LoRA adapter cannot be served.
+
+ Attributes:
+ details["adapter"]: The adapter directory, set whenever adapter_path is given.
+ """
+
+ def __init__(
+ self,
+ message: str,
+ adapter_path: Path | str | None = None,
+ details: dict | None = None,
+ ):
+ merged = dict(details or {})
+ if adapter_path is not None:
+ merged["adapter"] = str(adapter_path)
+ super().__init__(message, merged)
+
+
+class UnsupportedAdapterError(AdapterError):
+ """
+ A valid PEFT adapter that uses a feature oMLX does not apply.
+
+ Attributes:
+ feature: The unsupported PEFT feature, also at details["feature"].
+ """
+
+ def __init__(
+ self,
+ message: str,
+ adapter_path: Path | str | None = None,
+ details: dict | None = None,
+ *,
+ feature: str,
+ ):
+ super().__init__(message, adapter_path, {**(details or {}), "feature": feature})
+ self.feature = feature
+
+
+class AdapterShapeError(AdapterError):
+ """The adapter does not fit the loaded base model, or changed since discovery."""
+
+ pass
+
+
# =============================================================================
# API-related Exceptions
# =============================================================================
diff --git a/omlx/lora_adapter.py b/omlx/lora_adapter.py
new file mode 100644
index 0000000000..f0cf70d0fe
--- /dev/null
+++ b/omlx/lora_adapter.py
@@ -0,0 +1,999 @@
+# SPDX-License-Identifier: Apache-2.0
+"""PEFT LoRA adapters served as extra model entries.
+
+An adapter directory is read from its config and its safetensors header only, bound to
+a local base model, and applied when an engine loads by wrapping the base's linear
+layers in LoraLinear. Parsing and resolution are pure and never touch MLX arrays.
+
+mlx_vlm.trainer and mlx_lm.tuner are not imported: each costs 1 to 2 s.
+omlx.model_discovery is imported for typing only and never imports this module at
+runtime, so the two cannot form an import cycle.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+import enum
+import hashlib
+import json
+import math
+import os
+import re
+from collections.abc import Collection, Iterable, Mapping
+from dataclasses import dataclass
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, BinaryIO, Protocol, TypeGuard
+
+import mlx.core as mx
+import mlx.nn as nn
+
+from .exceptions import AdapterError, AdapterShapeError, UnsupportedAdapterError
+
+if TYPE_CHECKING:
+ from .model_discovery import DiscoveredModel
+
+ADAPTER_CONFIG_NAME = "adapter_config.json"
+ADAPTER_WEIGHTS_NAME = "adapter_model.safetensors"
+_PICKLED_WEIGHTS_NAME = "adapter_model.bin"
+
+_MAX_CONFIG_BYTES = 1 << 20
+_MAX_HEADER_BYTES = 100 << 20
+_DTYPE_BYTES = {"F32": 4, "BF16": 2, "F16": 2}
+_TENSOR_KEY = re.compile(
+ r"base_model\.model\.(?P.+)\.lora_(?P[AB])\.weight"
+)
+_LANGUAGE_PREFIX = r"(?:model\.)?(?:language_model\.(?:model\.)?)?"
+_LAYER_TAIL = re.compile(rf"{_LANGUAGE_PREFIX}(layers\.\d+\..+)")
+_ROUTED_DOWN = re.compile(
+ rf"{_LANGUAGE_PREFIX}layers\.\d+\.(?:mlp\.)?experts\.down_proj"
+)
+_UNSUPPORTED_WHEN_TRUTHY = (
+ "use_dora",
+ "use_qalora",
+ "modules_to_save",
+ "rank_pattern",
+ "alpha_pattern",
+ "layer_replication",
+ "fan_in_fan_out",
+)
+_BASE_MODEL_TYPES = frozenset({"llm", "vlm"})
+_BASE_ENGINE_TYPES = frozenset({"batched", "vlm"})
+_MERGE_FIX = "Merge it with peft merge_and_unload and serve the merged model."
+_CHANGED_AFTER_DISCOVERY = (
+ "The adapter files changed after discovery. Reload the model list."
+)
+
+
+@dataclass(frozen=True)
+class LoraConfig:
+ base_ref: str # adapter_config.base_model_name_or_path. A match key only.
+ rank: int
+ alpha: float
+ rslora: bool
+ target_parameters: tuple[str, ...] = ()
+
+ @property
+ def scale(self) -> float:
+ """alpha / sqrt(rank) when rslora else alpha / rank (PEFT)."""
+ return self.alpha / (math.sqrt(self.rank) if self.rslora else self.rank)
+
+
+@dataclass(frozen=True)
+class LoraModule:
+ """One targeted module, read from the safetensors header only."""
+
+ hf_path: str # "model.language_model.layers.3.mlp.gate_proj"
+ in_features: int # lora_A.weight shape [r, in]
+ out_features: int # lora_B.weight shape [out, r]
+
+
+@dataclass(frozen=True)
+class _RoutedModule(LoraModule):
+ experts: int
+
+ @property
+ def tensor_stem(self) -> str:
+ return self.hf_path.removesuffix(".down_proj")
+
+ @property
+ def runtime_path(self) -> str:
+ if self.tensor_stem.endswith(".mlp.experts"):
+ return self.tensor_stem.removesuffix(".experts") + ".switch_mlp.down_proj"
+ return self.tensor_stem + ".switch_glu.down_proj"
+
+
+@dataclass(frozen=True)
+class AdapterSource:
+ """A structurally valid adapter directory. Not yet bound to a base."""
+
+ public_id: str # directory basename; never contains ":" (profiles own ":")
+ path: Path
+ config: LoraConfig
+ modules: tuple[LoraModule, ...]
+ weights_path: Path
+ weight_bytes: int # file size == resident bytes (tensors stay as shipped)
+ fingerprint: str # sha256(config bytes + weights size + weights mtime_ns)
+
+ @property
+ def has_routed_targets(self) -> bool:
+ return bool(self.config.target_parameters)
+
+
+@dataclass(frozen=True)
+class BaseRef:
+ model_id: str
+ path: Path # physical weights directory of the base
+
+
+@dataclass(frozen=True)
+class AdapterBinding:
+ """Adapter plus resolved base. The only adapter type an engine ever receives.
+
+ There is no Optional base. An unresolved adapter is an AdapterIssue and never
+ becomes an entry, so no engine can see a half-bound adapter.
+ """
+
+ source: AdapterSource
+ base: BaseRef
+ cache_revision: str
+
+ def as_status(self) -> dict[str, Any]:
+ """{"base_model_id", "rank", "alpha", "weight_bytes"} for get_status() rows."""
+ return {
+ "base_model_id": self.base.model_id,
+ "rank": self.source.config.rank,
+ "alpha": self.source.config.alpha,
+ "weight_bytes": self.source.weight_bytes,
+ }
+
+
+def bind_adapter(source: AdapterSource, base: BaseRef) -> AdapterBinding:
+ """The one constructor of AdapterBinding. A pure function with no file reads.
+
+ cache_revision changes with a retrained adapter or a re-bound base path, so stale
+ SSD KV and vision-feature blocks stop matching. An in-place change of the base
+ weights is the exposure plain models already have.
+ """
+ digest = hashlib.sha256(f"{source.fingerprint}|{base.path}".encode()).hexdigest()
+ return AdapterBinding(source, base, f"lora-{digest[:12]}")
+
+
+class IssueKind(enum.Enum):
+ UNSUPPORTED = "unsupported" # valid PEFT, feature we do not apply
+ MALFORMED = "malformed" # unreadable, missing weights, bad tensors or shapes
+ BASE_MISSING = "base_missing"
+ BASE_AMBIGUOUS = "base_ambiguous"
+ OVERRIDE_INVALID = "override_invalid" # persisted override names no usable base
+ ID_COLLISION = "id_collision" # id taken by a real model or an earlier adapter
+
+
+@dataclass(frozen=True)
+class AdapterIssue:
+ """Why an adapter directory is not served. It never becomes an entry."""
+
+ public_id: str
+ path: Path
+ kind: IssueKind
+ detail: str # operator-facing: says what to download, pin or merge
+ candidates: tuple[str, ...] = () # BASE_AMBIGUOUS: the model ids to choose from
+
+
+class ModelLike(Protocol):
+ """The slice of DiscoveredModel and EngineEntry that base matching reads."""
+
+ @property
+ def model_id(self) -> str: ...
+ @property
+ def model_path(self) -> str: ...
+ @property
+ def source_repo_id(self) -> str | None: ...
+ @property
+ def is_helper(self) -> bool: ...
+ @property
+ def model_type(self) -> str: ...
+ @property
+ def engine_type(self) -> str: ...
+ @property
+ def model_format(self) -> str | None: ...
+ @property
+ def adapter(self) -> object | None: ...
+
+
+@dataclass(frozen=True)
+class BaseCandidate:
+ """What resolution needs to know about a local base, nothing more."""
+
+ model_id: str
+ path: Path
+ repo_ids: frozenset[str] # lowercased: source_repo_id and "/" of path
+
+
+@dataclass(frozen=True)
+class AdapterDiscovery:
+ """Derived entries by public id, plus the adapters that could not be served."""
+
+ entries: dict[str, DiscoveredModel]
+ issues: tuple[AdapterIssue, ...]
+
+
+def _clip(value: object, limit: int = 120) -> str:
+ text = repr(value)
+ return text if len(text) <= limit else f"{text[: limit - 3]}..."
+
+
+def _is_int(value: object) -> TypeGuard[int]:
+ """True for an int that is not a bool; JSON true must not pass as a count."""
+ return isinstance(value, int) and not isinstance(value, bool)
+
+
+def _unsupported(feature: str, problem: str | None = None) -> UnsupportedAdapterError:
+ problem = problem or f"The adapter uses {feature}, which oMLX does not apply."
+ return UnsupportedAdapterError(f"{problem} {_MERGE_FIX}", feature=feature)
+
+
+def _alpha_from(value: object) -> float:
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ alpha = math.nan
+ else:
+ try:
+ alpha = float(value)
+ except OverflowError:
+ alpha = math.inf
+ if not math.isfinite(alpha) or alpha <= 0:
+ raise AdapterError(
+ f"{ADAPTER_CONFIG_NAME} needs lora_alpha to be a positive finite number."
+ )
+ return alpha
+
+
+def parse_adapter_config(raw: bytes) -> LoraConfig:
+ """adapter_config.json bytes -> LoraConfig. Shared with the downloader card.
+
+ Raises UnsupportedAdapterError for a valid config oMLX does not apply, and
+ AdapterError for one that is malformed. base_model_name_or_path is a match key
+ only. It is never opened or fetched.
+ """
+ if len(raw) > _MAX_CONFIG_BYTES:
+ raise AdapterError(f"{ADAPTER_CONFIG_NAME} is larger than 1 MiB.")
+ try:
+ document = json.loads(raw)
+ except (ValueError, RecursionError) as error:
+ raise AdapterError(f"{ADAPTER_CONFIG_NAME} is not valid JSON.") from error
+ if not isinstance(document, dict):
+ raise AdapterError(f"{ADAPTER_CONFIG_NAME} must hold a JSON object.")
+
+ peft_type = document.get("peft_type")
+ if not isinstance(peft_type, str):
+ raise AdapterError(f"{ADAPTER_CONFIG_NAME} has no peft_type.")
+ if peft_type != "LORA":
+ raise _unsupported(
+ "peft_type",
+ f"The adapter has peft_type {_clip(peft_type)}, "
+ "and oMLX applies only LORA.",
+ )
+ for key in _UNSUPPORTED_WHEN_TRUTHY:
+ if document.get(key):
+ raise _unsupported(key)
+ if document.get("alora_invocation_tokens") is not None:
+ raise UnsupportedAdapterError(
+ "oMLX does not support aLoRA's token-triggered activation.",
+ feature="alora_invocation_tokens",
+ )
+ if document.get("bias") not in (None, "none"):
+ raise _unsupported("bias")
+
+ initializer = document.get("init_lora_weights", True)
+ if not isinstance(initializer, bool) and initializer not in (
+ "gaussian",
+ "eva",
+ "orthogonal",
+ "mica",
+ "nora",
+ ):
+ raise UnsupportedAdapterError(
+ f"oMLX cannot apply init_lora_weights={_clip(initializer)} "
+ "as a standalone delta on the original base. Use a standard "
+ "LoRA export that does not require changing the base weights.",
+ feature="init_lora_weights",
+ )
+
+ targets = document.get("target_parameters")
+ if targets is None:
+ targets = []
+ if not isinstance(targets, list) or not all(
+ isinstance(path, str) and _ROUTED_DOWN.fullmatch(path) for path in targets
+ ):
+ raise _unsupported("target_parameters")
+ if len(set(targets)) != len(targets):
+ raise AdapterError("target_parameters contains duplicate expert projections.")
+
+ base_ref = document.get("base_model_name_or_path")
+ if not isinstance(base_ref, str) or not base_ref.strip():
+ raise AdapterError(
+ f"{ADAPTER_CONFIG_NAME} needs base_model_name_or_path "
+ "to be a non-empty string."
+ )
+ rank = document.get("r")
+ if not _is_int(rank) or rank <= 0:
+ raise AdapterError(f"{ADAPTER_CONFIG_NAME} needs r to be a positive integer.")
+ return LoraConfig(
+ base_ref=base_ref,
+ rank=rank,
+ alpha=_alpha_from(document.get("lora_alpha")),
+ rslora=bool(document.get("use_rslora")),
+ target_parameters=tuple(targets),
+ )
+
+
+def _read_config(path: Path) -> bytes:
+ try:
+ with path.open("rb") as handle:
+ return handle.read(_MAX_CONFIG_BYTES + 1)
+ except FileNotFoundError as error:
+ raise AdapterError(f"{path.name} is missing.") from error
+ except OSError as error:
+ raise AdapterError(
+ f"Cannot read {path.name}: {error.strerror or error}."
+ ) from error
+
+
+def _read_header(handle: BinaryIO) -> tuple[dict[str, Any], int]:
+ """The safetensors JSON header and the offset where tensor data starts."""
+ prefix = handle.read(8)
+ header_len = int.from_bytes(prefix, "little")
+ if len(prefix) < 8 or header_len > _MAX_HEADER_BYTES:
+ raise AdapterError(
+ f"{ADAPTER_WEIGHTS_NAME} is truncated or has an invalid header. "
+ "Download it again."
+ )
+ raw = handle.read(header_len)
+ if len(raw) < header_len:
+ raise AdapterError(f"{ADAPTER_WEIGHTS_NAME} is truncated. Download it again.")
+ try:
+ header = json.loads(raw)
+ except (ValueError, RecursionError) as error:
+ raise AdapterError(
+ f"{ADAPTER_WEIGHTS_NAME} has an unreadable header."
+ ) from error
+ if not isinstance(header, dict):
+ raise AdapterError(f"{ADAPTER_WEIGHTS_NAME} has an unreadable header.")
+ return header, 8 + header_len
+
+
+def _read_weights_header(path: Path) -> tuple[dict[str, Any], int, int, int]:
+ """(header, data offset, file size, mtime_ns), all from one open handle."""
+ try:
+ with path.open("rb") as handle:
+ stat = os.fstat(handle.fileno())
+ header, data_start = _read_header(handle)
+ except FileNotFoundError as error:
+ if os.path.isfile(path.with_name(_PICKLED_WEIGHTS_NAME)):
+ raise UnsupportedAdapterError(
+ f"The adapter ships {_PICKLED_WEIGHTS_NAME}, and oMLX never loads "
+ f"pickled weights. Re-save it as {ADAPTER_WEIGHTS_NAME}.",
+ feature="weights_format",
+ ) from error
+ raise AdapterError(f"{path.name} is missing.") from error
+ except OSError as error:
+ raise AdapterError(
+ f"Cannot read {path.name}: {error.strerror or error}."
+ ) from error
+ return header, data_start, stat.st_size, stat.st_mtime_ns
+
+
+def _tensor_shape(
+ name: str, entry: object, data_start: int, file_size: int
+) -> tuple[int, ...]:
+ if not isinstance(entry, dict):
+ raise AdapterError(f"Tensor {_clip(name)} has no description.")
+ dtype = entry.get("dtype")
+ if not isinstance(dtype, str) or dtype not in _DTYPE_BYTES:
+ raise AdapterError(
+ f"Tensor {_clip(name)} has dtype {_clip(dtype)}. Use F32, BF16 or F16."
+ )
+ shape = entry.get("shape")
+ offsets = entry.get("data_offsets")
+ if (
+ not isinstance(shape, list)
+ or not all(_is_int(dim) and dim >= 0 for dim in shape)
+ or not isinstance(offsets, list)
+ or len(offsets) != 2
+ or not all(_is_int(offset) for offset in offsets)
+ ):
+ raise AdapterError(f"Tensor {_clip(name)} has a malformed shape or offsets.")
+ begin, end = offsets
+ # A truncated download must fail here, not when the engine loads the weights.
+ if not 0 <= begin <= end or data_start + end > file_size:
+ raise AdapterError(
+ f"Tensor {_clip(name)} reaches past the end of {ADAPTER_WEIGHTS_NAME}. "
+ "Download it again."
+ )
+ if end - begin != _DTYPE_BYTES[dtype] * math.prod(shape):
+ raise AdapterError(
+ f"Tensor {_clip(name)} holds data that does not fit its shape."
+ )
+ return tuple(shape)
+
+
+def _modules_from_header(
+ header: dict[str, Any], data_start: int, file_size: int, config: LoraConfig
+) -> tuple[LoraModule, ...]:
+ halves: dict[str, dict[str, tuple[int, ...]]] = {}
+ for name, entry in header.items():
+ if name == "__metadata__":
+ continue
+ match = _TENSOR_KEY.fullmatch(name)
+ if match is None:
+ raise AdapterError(
+ f"Unexpected tensor {_clip(name)}. "
+ "Only LoRA A and B weights are supported."
+ )
+ shape = _tensor_shape(name, entry, data_start, file_size)
+ halves.setdefault(match["path"], {})[match["half"]] = shape
+
+ routed = {
+ path.removesuffix(".down_proj"): path for path in config.target_parameters
+ }
+ for stem, path in routed.items():
+ if stem not in halves:
+ raise AdapterError(
+ f"Expert projection {_clip(path)} needs lora_A and lora_B."
+ )
+
+ rank = config.rank
+ modules: list[LoraModule] = []
+ for hf_path in sorted(halves):
+ pair = halves[hf_path]
+ if pair.keys() != {"A", "B"}:
+ raise AdapterError(f"Module {_clip(hf_path)} needs both lora_A and lora_B.")
+ shape_a, shape_b = pair["A"], pair["B"]
+ if len(shape_a) != 2 or len(shape_b) != 2:
+ raise AdapterError(f"Module {_clip(hf_path)} needs 2-D LoRA weights.")
+ if hf_path in routed:
+ experts, remainder = divmod(shape_a[0], rank)
+ if not experts or remainder or shape_b[1] != experts * rank:
+ raise AdapterError(
+ f"Expert projection {_clip(routed[hf_path])} needs matching "
+ f"expert counts in lora_A and lora_B at rank {rank}."
+ )
+ modules.append(
+ _RoutedModule(routed[hf_path], shape_a[1], shape_b[0], experts)
+ )
+ continue
+ if _ROUTED_DOWN.fullmatch(hf_path + ".down_proj"):
+ raise AdapterError(
+ f"Expert container {_clip(hf_path)} has no declared target."
+ )
+ if shape_a[0] != rank or shape_b[1] != rank:
+ raise AdapterError(
+ f"Module {_clip(hf_path)} has rank {shape_a[0]} and {shape_b[1]}, "
+ f"but {ADAPTER_CONFIG_NAME} says r={rank}."
+ )
+ modules.append(
+ LoraModule(hf_path, in_features=shape_a[1], out_features=shape_b[0])
+ )
+ if not modules:
+ raise AdapterError(f"{ADAPTER_WEIGHTS_NAME} holds no LoRA weights.")
+ return tuple(modules)
+
+
+def _fingerprint(config_bytes: bytes, weight_bytes: int, mtime_ns: int) -> str:
+ """The identity of an adapter's files. Tensor data is not hashed."""
+ stamp = f"{len(config_bytes)}|{weight_bytes}|{mtime_ns}|".encode()
+ return hashlib.sha256(stamp + config_bytes).hexdigest()
+
+
+def _parse_adapter(adapter_dir: Path) -> AdapterSource:
+ config_bytes = _read_config(adapter_dir / ADAPTER_CONFIG_NAME)
+ config = parse_adapter_config(config_bytes)
+ weights_path = adapter_dir / ADAPTER_WEIGHTS_NAME
+ header, data_start, weight_bytes, mtime_ns = _read_weights_header(weights_path)
+ modules = _modules_from_header(header, data_start, weight_bytes, config)
+ return AdapterSource(
+ public_id=adapter_dir.name,
+ path=adapter_dir,
+ config=config,
+ modules=modules,
+ weights_path=weights_path,
+ weight_bytes=weight_bytes,
+ fingerprint=_fingerprint(config_bytes, weight_bytes, mtime_ns),
+ )
+
+
+def parse_adapter(adapter_dir: Path) -> AdapterSource:
+ """Read the config and the safetensors header. No tensor data, no pickle, no code.
+
+ Raises UnsupportedAdapterError for a PEFT feature or weights format oMLX does not
+ apply, and AdapterError for anything unreadable, missing, truncated or misshapen.
+ """
+ try:
+ return _parse_adapter(adapter_dir)
+ except AdapterError as error:
+ error.details.setdefault("adapter", str(adapter_dir))
+ raise
+
+
+def base_candidates(models: Iterable[ModelLike]) -> tuple[BaseCandidate, ...]:
+ """Chat-capable local bases, in input order.
+
+ A base is model_type llm or vlm on the batched or vlm engine, not a helper, not a
+ GGUF folder (an external engine serves those) and not itself an adapter entry.
+ repo_ids holds the lowercased source_repo_id (when set) and "/" of
+ the model directory, so a base downloaded as owner/name matches an adapter's
+ base_model_name_or_path exactly.
+ """
+ candidates = []
+ for model in models:
+ if (
+ model.model_type not in _BASE_MODEL_TYPES
+ or model.engine_type not in _BASE_ENGINE_TYPES
+ or model.is_helper
+ or model.model_format is not None
+ or model.adapter is not None
+ ):
+ continue
+ path = Path(model.model_path)
+ repo_ids = {f"{path.parent.name}/{path.name}".lower()}
+ if model.source_repo_id:
+ repo_ids.add(model.source_repo_id.lower())
+ candidates.append(BaseCandidate(model.model_id, path, frozenset(repo_ids)))
+ return tuple(candidates)
+
+
+def match_bases(
+ base_ref: str, candidates: Iterable[BaseCandidate]
+) -> tuple[BaseCandidate, ...]:
+ """Exact tier first, family tier second. Shared by resolution and the downloader.
+
+ Exact: candidates whose repo_ids contain base_ref, ignoring case. Any exact hit
+ wins outright.
+ Family: the last path segment of base_ref is the stem, and a candidate's model id
+ must equal it or continue it after a "-" or "_".
+ """
+ candidates = tuple(candidates)
+ wanted = base_ref.lower()
+ exact = tuple(c for c in candidates if wanted in c.repo_ids)
+ if exact:
+ return exact
+ stem = wanted.rsplit("/", 1)[-1]
+ if not stem:
+ return ()
+ # The separator keeps "qwen3.8-27b" from matching "qwen3.8-270b".
+ continuations = (f"{stem}-", f"{stem}_")
+ return tuple(
+ c
+ for c in candidates
+ if c.model_id.lower() == stem or c.model_id.lower().startswith(continuations)
+ )
+
+
+def resolve_adapters(
+ sources: Iterable[AdapterSource | AdapterIssue],
+ candidates: Iterable[BaseCandidate],
+ overrides: Mapping[str, str],
+ taken_ids: Collection[str],
+) -> tuple[tuple[AdapterBinding, ...], tuple[AdapterIssue, ...]]:
+ candidates = tuple(candidates)
+ by_id = {candidate.model_id: candidate for candidate in candidates}
+ reserved: set[str] = set()
+ bindings: list[AdapterBinding] = []
+ issues: list[AdapterIssue] = []
+
+ def reject(
+ source: AdapterSource,
+ kind: IssueKind,
+ detail: str,
+ choices: tuple[str, ...] = (),
+ ) -> None:
+ issues.append(
+ AdapterIssue(source.public_id, source.path, kind, detail, choices)
+ )
+
+ for source in sources:
+ public_id = source.public_id
+ if isinstance(source, AdapterIssue):
+ reserved.add(public_id)
+ continue
+ pin = f"PUT /admin/api/adapters/{public_id}/base"
+ if ":" in public_id:
+ reject(
+ source,
+ IssueKind.ID_COLLISION,
+ f"Adapter id {public_id!r} contains ':', which model profiles use. "
+ "Rename the adapter directory.",
+ )
+ continue
+ if public_id in taken_ids or public_id in reserved:
+ reject(
+ source,
+ IssueKind.ID_COLLISION,
+ f"Adapter id {public_id!r} is already used by a model or an adapter. "
+ "Rename the adapter directory.",
+ )
+ continue
+ reserved.add(public_id)
+
+ pinned = overrides.get(public_id)
+ if pinned is not None:
+ base = by_id.get(pinned)
+ if base is None:
+ reject(
+ source,
+ IssueKind.OVERRIDE_INVALID,
+ f"The pinned base {pinned!r} is not a local chat model. "
+ f"Pin another base or clear the pin with {pin}.",
+ )
+ continue
+ matches: tuple[BaseCandidate, ...] = (base,)
+ else:
+ matches = match_bases(source.config.base_ref, candidates)
+
+ if len(matches) == 1:
+ base = matches[0]
+ bindings.append(bind_adapter(source, BaseRef(base.model_id, base.path)))
+ elif not matches:
+ reject(
+ source,
+ IssueKind.BASE_MISSING,
+ f"No local model matches the base {source.config.base_ref!r}. "
+ f"Download it, or pin a local base with {pin}.",
+ )
+ else:
+ names = tuple(match.model_id for match in matches)
+ reject(
+ source,
+ IssueKind.BASE_AMBIGUOUS,
+ f"Several local models match the base {source.config.base_ref!r}: "
+ f"{', '.join(names)}. Pin one with {pin}.",
+ names,
+ )
+ return tuple(bindings), tuple(issues)
+
+
+def derive_entry(base: DiscoveredModel, binding: AdapterBinding) -> DiscoveredModel:
+ """The model entry an adapter adds, copied from its base.
+
+ model_path stays the base directory, so the physical read sites need no edit. The
+ adapter's weights add to the size estimates. thinking_default becomes False when the
+ base knows it, because an adapter tuned for a harness does not think by default.
+ """
+ weight_bytes = binding.source.weight_bytes
+ return dataclasses.replace(
+ base,
+ model_id=binding.source.public_id,
+ adapter=binding,
+ source_type="local",
+ source_repo_id=None,
+ is_helper=False,
+ estimated_size=base.estimated_size + weight_bytes,
+ text_only_size=base.text_only_size + weight_bytes if base.text_only_size else 0,
+ thinking_default=False if base.thinking_default is not None else None,
+ )
+
+
+def discover_adapters(
+ adapter_dirs: Iterable[Path],
+ discovered: Mapping[str, DiscoveredModel],
+ base_overrides: Mapping[str, str],
+) -> AdapterDiscovery:
+ """Parse each directory, bind it to a discovered base, and derive its entry.
+
+ A directory that cannot be served becomes an issue, never an exception. Parse
+ issues come first, then resolution issues. Entries never override a real model id.
+ """
+ sources: list[AdapterSource | AdapterIssue] = []
+ parse_issues: list[AdapterIssue] = []
+ for adapter_dir in adapter_dirs:
+ try:
+ sources.append(parse_adapter(adapter_dir))
+ except AdapterError as error:
+ kind = (
+ IssueKind.UNSUPPORTED
+ if isinstance(error, UnsupportedAdapterError)
+ else IssueKind.MALFORMED
+ )
+ issue = AdapterIssue(adapter_dir.name, adapter_dir, kind, error.message)
+ parse_issues.append(issue)
+ sources.append(issue)
+
+ bindings, resolve_issues = resolve_adapters(
+ sources, base_candidates(discovered.values()), base_overrides, set(discovered)
+ )
+ bases = {model.model_id: model for model in discovered.values()}
+ entries = {
+ binding.source.public_id: derive_entry(bases[binding.base.model_id], binding)
+ for binding in bindings
+ }
+ return AdapterDiscovery(entries, (*parse_issues, *resolve_issues))
+
+
+class _LoraProjection(nn.Module):
+ def __init__(
+ self,
+ linear: nn.Module,
+ lora_a: mx.array,
+ lora_b: mx.array,
+ scale: float,
+ revision: str,
+ ) -> None:
+ super().__init__()
+ self.linear = linear
+ self.lora_a = lora_a
+ self.lora_b = lora_b
+ self.scale = float(scale)
+ self.revision = revision
+
+
+class LoraLinear(_LoraProjection):
+ """y = linear(x) + (scale * ((x @ lora_a) @ lora_b)).astype(x.dtype)
+
+ The math of mlx_vlm.trainer.peft.lora_layers.LoRALinear.__call__ (mlx_lm.tuner.lora
+ has the same class) without dropout, and without importing either trainer package.
+ lora_a is [in, r] and lora_b is [r, out], kept in the dtype the adapter shipped in.
+ It is not a subclass of nn.QuantizedLinear and exposes no .weight, so code that
+ reads linear attributes directly fails loudly and exact-type-gated patches skip the
+ wrapper. revision is a plain str attribute, not a parameter.
+ """
+
+ def __call__(self, x: mx.array) -> mx.array:
+ y: mx.array = self.linear(x)
+ delta = (x @ self.lora_a) @ self.lora_b
+ return y + (self.scale * delta).astype(x.dtype)
+
+
+class _LoraSwitchLinear(_LoraProjection):
+ def __call__(
+ self, x: mx.array, indices: mx.array, sorted_indices: bool = False
+ ) -> mx.array:
+ y: mx.array = self.linear(x, indices, sorted_indices=sorted_indices)
+ h = mx.gather_mm(
+ x, self.lora_a, rhs_indices=indices, sorted_indices=sorted_indices
+ )
+ delta = mx.gather_mm(
+ h, self.lora_b, rhs_indices=indices, sorted_indices=sorted_indices
+ )
+ return y + (self.scale * delta).astype(y.dtype)
+
+
+@dataclass(frozen=True)
+class _Replacement:
+ hf_path: str
+ parent: Any
+ key: str | int
+ target: nn.Module
+ lora_a: mx.array
+ lora_b: mx.array
+
+
+def _tensor_name(hf_path: str, half: str) -> str:
+ return f"base_model.model.{hf_path}.lora_{half}.weight"
+
+
+def _target_name(hf_path: str, named: Mapping[str, nn.Module], adapter: Path) -> str:
+ """The name under the language root that an adapter's HF module path points at."""
+ match = _LAYER_TAIL.fullmatch(hf_path)
+ if match is None:
+ raise AdapterShapeError(
+ f"{hf_path} is not inside a supported numbered language layer.",
+ adapter,
+ )
+ tail = match.group(1)
+ found = [name for name in (f"model.{tail}", tail) if name in named]
+ if len(found) != 1:
+ problem = "is not in" if not found else "matches two modules of"
+ raise AdapterShapeError(
+ f"{hf_path} {problem} the base model. Check that the adapter was trained "
+ "for this base.",
+ adapter,
+ )
+ return found[0]
+
+
+def _linear_features(name: str, target: nn.Module, adapter: Path) -> tuple[int, int]:
+ """(in_features, out_features) of a Linear or QuantizedLinear.
+
+ Any other module type is an AdapterShapeError. oMLX cannot know how a custom
+ wrapper applies its weights, so it fails closed.
+ """
+ if isinstance(target, nn.QuantizedLinear):
+ # scales.shape[-1] * group_size is exact for every bit width and mode.
+ return target.scales.shape[-1] * target.group_size, target.weight.shape[0]
+ if isinstance(target, nn.Linear):
+ return target.weight.shape[-1], target.weight.shape[0]
+ raise AdapterShapeError(
+ f"Base module {name} is a {type(target).__name__}, not a Linear or "
+ "QuantizedLinear, so oMLX will not wrap it.",
+ adapter,
+ )
+
+
+def _locate(root: Any, name: str) -> tuple[Any, str | int]:
+ """The container holding the module at a dotted name, and its key in it."""
+ *parents, last = name.split(".")
+ node = root
+ for part in parents:
+ node = node[int(part)] if isinstance(node, list) else node[part]
+ return node, int(last) if isinstance(node, list) else last
+
+
+def _plan_replacement(
+ parent: Any,
+ key: str | int,
+ name: str,
+ target: nn.Module,
+ module: LoraModule,
+ weights: Mapping[str, mx.array],
+ source: AdapterSource,
+) -> _Replacement:
+ stem = module.hf_path
+ rank = source.config.rank
+ if isinstance(module, _RoutedModule):
+ from mlx_lm.models import switch_layers as lm
+
+ supported = type(parent) is lm.SwitchGLU and type(target) in (
+ lm.SwitchLinear,
+ lm.QuantizedSwitchLinear,
+ )
+ if not supported and type(parent).__module__ == "mlx_vlm.models.switch_layers":
+ from mlx_vlm.models import switch_layers as vlm
+
+ supported = type(parent) is vlm.SwitchGLU and type(target) in (
+ vlm.SwitchLinear,
+ vlm.QuantizedSwitchLinear,
+ )
+ if not supported or getattr(parent, "oqh_experts", None) is not None:
+ raise AdapterShapeError(
+ f"Base module {name} is not a supported routed expert projection.",
+ source.path,
+ )
+ if target.num_experts != module.experts:
+ raise AdapterShapeError(
+ f"{module.hf_path} has {module.experts} experts, but base module "
+ f"{name} has {target.num_experts}.",
+ source.path,
+ )
+ in_features, out_features = target.input_dims, target.output_dims
+ stem = module.tensor_stem
+ packed_rank = rank * module.experts
+ else:
+ in_features, out_features = _linear_features(name, target, source.path)
+ packed_rank = rank
+ if (in_features, out_features) != (module.in_features, module.out_features):
+ raise AdapterShapeError(
+ f"{module.hf_path} was trained for {module.in_features} inputs and "
+ f"{module.out_features} outputs, but base module {name} has "
+ f"{in_features} and {out_features}. Check that the adapter was trained "
+ "for this base.",
+ source.path,
+ )
+ lora_a = weights.get(_tensor_name(stem, "A"))
+ lora_b = weights.get(_tensor_name(stem, "B"))
+ if (
+ lora_a is None
+ or lora_b is None
+ or tuple(lora_a.shape) != (packed_rank, in_features)
+ or tuple(lora_b.shape) != (out_features, packed_rank)
+ ):
+ raise AdapterShapeError(
+ f"The weights of {module.hf_path} in {ADAPTER_WEIGHTS_NAME} differ from "
+ "the adapter that was discovered. Reload the model list.",
+ source.path,
+ )
+ if isinstance(module, _RoutedModule):
+ a = lora_a.reshape(module.experts, rank, in_features).transpose(0, 2, 1)
+ # PEFT packs B in [out, rank, expert] order, not [out, expert, rank].
+ b = lora_b.reshape(out_features, rank, module.experts).transpose(2, 1, 0)
+ return _Replacement(module.hf_path, parent, key, target, a, b)
+ return _Replacement(module.hf_path, parent, key, target, lora_a.T, lora_b.T)
+
+
+def _install(parent: Any, key: str | int, wrapper: nn.Module) -> None:
+ if isinstance(parent, nn.Module):
+ setattr(parent, str(key), wrapper)
+ else:
+ parent[key] = wrapper
+
+
+def _require_unchanged(source: AdapterSource) -> None:
+ """Refuse an adapter whose files no longer match what discovery fingerprinted.
+
+ cache_revision derives from that fingerprint. Tensors read from replaced files
+ would otherwise be cached under the identity of the files they replaced.
+ """
+ try:
+ config_bytes = _read_config(source.path / ADAPTER_CONFIG_NAME)
+ stat = source.weights_path.stat()
+ except (AdapterError, OSError) as error:
+ raise AdapterShapeError(_CHANGED_AFTER_DISCOVERY, source.path) from error
+ now = _fingerprint(config_bytes, stat.st_size, stat.st_mtime_ns)
+ if now != source.fingerprint:
+ raise AdapterShapeError(_CHANGED_AFTER_DISCOVERY, source.path)
+
+
+def attach_lora(model: Any, binding: AdapterBinding) -> int:
+ """Wrap targeted dense or routed projections in place.
+
+ Runs on the MLX executor right after the loader returns and before every walker
+ (patches, offload, fusion). The weights come from mx.load, which maps the file
+ lazily, and stay in the dtype the adapter shipped in. The language root is
+ model.language_model when present, else model. Each adapter module resolves by its
+ path from "layers.." on, as "model." or "" under that root.
+
+ Just before loading, the adapter's config and weights file are checked against
+ source.fingerprint, so replaced files cannot be stamped with the cache_revision
+ of the files that were discovered. Replace adapter files atomically: a rewrite in
+ place after the load is not detected.
+
+ Everything is validated before anything is installed. An AdapterShapeError (an
+ unresolved, duplicate or unsupported projection,
+ a feature-size mismatch, files changed since discovery, or a model that already
+ carries an adapter) therefore leaves the model unmodified. Returns the number of
+ wrapped modules.
+ """
+ source = binding.source
+ if lora_revision_of(model) is not None:
+ raise AdapterShapeError(
+ "The model already carries a LoRA adapter.", source.path
+ )
+ language_model = getattr(model, "language_model", None)
+ root = model if language_model is None else language_model
+ named = dict(root.named_modules())
+ _require_unchanged(source)
+ weights = mx.load(str(source.weights_path))
+ if not isinstance(weights, dict):
+ raise AdapterError(
+ f"{ADAPTER_WEIGHTS_NAME} did not load as named tensors.", source.path
+ )
+
+ plan: dict[tuple[int, str | int], tuple[_Replacement, _LoraProjection]] = {}
+ for module in source.modules:
+ path = (
+ module.runtime_path if isinstance(module, _RoutedModule) else module.hf_path
+ )
+ name = _target_name(path, named, source.path)
+ parent, key = _locate(root, name)
+ slot = (id(parent), key)
+ if slot in plan:
+ raise AdapterShapeError(
+ f"{plan[slot][0].hf_path} and {module.hf_path} both target "
+ f"base module {name}.",
+ source.path,
+ )
+ replacement = _plan_replacement(
+ parent, key, name, named[name], module, weights, source
+ )
+ wrapper_type = (
+ _LoraSwitchLinear if isinstance(module, _RoutedModule) else LoraLinear
+ )
+ plan[slot] = (
+ replacement,
+ wrapper_type(
+ replacement.target,
+ replacement.lora_a,
+ replacement.lora_b,
+ source.config.scale,
+ binding.cache_revision,
+ ),
+ )
+ _require_unchanged(source)
+ installed = []
+ try:
+ for replacement, wrapper in plan.values():
+ _install(replacement.parent, replacement.key, wrapper)
+ installed.append(replacement)
+ except Exception:
+ for replacement in reversed(installed):
+ _install(replacement.parent, replacement.key, replacement.target)
+ raise
+ return len(plan)
+
+
+def lora_revision_of(model: Any) -> str | None:
+ """The cache_revision stamped on the wrappers under `model`, or None."""
+ modules = getattr(model, "modules", None)
+ if not callable(modules):
+ return None
+ for module in modules():
+ if isinstance(module, _LoraProjection):
+ return module.revision
+ return None
diff --git a/omlx/model_discovery.py b/omlx/model_discovery.py
index a23edb04f8..a62f90c3c7 100644
--- a/omlx/model_discovery.py
+++ b/omlx/model_discovery.py
@@ -26,7 +26,7 @@
import tempfile
from dataclasses import dataclass, field
from pathlib import Path
-from typing import Literal
+from typing import TYPE_CHECKING, Literal
from transformers.utils.chat_template_utils import render_jinja_template
@@ -45,6 +45,9 @@
)
from .utils.safetensors_shards import select_safetensors_weight_files
+if TYPE_CHECKING:
+ from .lora_adapter import AdapterBinding
+
logger = logging.getLogger(__name__)
ModelType = Literal[
@@ -488,6 +491,7 @@ class DiscoveredModel:
is_helper: bool = False # Speculative-decoding drafter (dFlash/Assistant/MTP)
model_format: str | None = None # "gguf": served by an external engine only
source_path: str | None = None # The GGUF file a generated folder links to
+ adapter: "AdapterBinding | None" = None # LoRA adapter served over model_path
@dataclass(frozen=True)
@@ -1736,7 +1740,11 @@ def _is_adapter_dir(path: Path) -> bool:
return (path / "adapter_config.json").exists()
-def _register_adapter(adapters: dict[str, str], path: Path, adapter_id: str) -> None:
+def _register_adapter(
+ adapters: dict[str, str] | None, path: Path, adapter_id: str
+) -> None:
+ if adapters is None:
+ return
if adapter_id in adapters:
logger.warning(
f"Duplicate LoRA adapter id '{adapter_id}' at {path}, "
@@ -2609,6 +2617,8 @@ def discover_models(
model_dir: Path,
gguf_root: Path | None = None,
adapters: dict[str, str] | None = None,
+ *,
+ adapter_dirs: list[Path] | None = None,
) -> dict[str, DiscoveredModel]:
"""
Scan model directory with two-level discovery.
@@ -2638,8 +2648,8 @@ def discover_models(
Args:
model_dir: Path to directory containing model subdirectories
gguf_root: Where GGUF model folders are generated; None skips GGUFs
- adapters: Receives LoRA adapter folders as {adapter_id: path}. They are
- never models: a model's settings apply one on top of its weights.
+ adapters: Maps adapter IDs to paths for per-model settings
+ adapter_dirs: Collects local adapter directories for standalone entries
Returns:
Dictionary mapping model_id to DiscoveredModel
@@ -2663,6 +2673,8 @@ def discover_models(
if _is_adapter_dir(subdir):
_register_adapter(adapters, subdir, subdir.name)
+ if adapter_dirs is not None:
+ adapter_dirs.append(subdir)
elif _register_gguf_folder(models, subdir, gguf_root):
pass
elif _is_model_dir(subdir):
@@ -2710,9 +2722,11 @@ def discover_models(
if _is_adapter_dir(child):
has_children = True
_register_adapter(adapters, child, child.name)
- elif _register_gguf_folder(models, child, gguf_root):
- has_children = True
- elif _skip_splash_package(child):
+ if adapter_dirs is not None:
+ adapter_dirs.append(child)
+ elif _register_gguf_folder(
+ models, child, gguf_root
+ ) or _skip_splash_package(child):
has_children = True
elif _is_model_dir(child):
has_children = True
@@ -2739,6 +2753,8 @@ def discover_models_from_dirs(
model_dirs: list[Path],
gguf_root: Path | None = None,
adapters: dict[str, str] | None = None,
+ *,
+ adapter_dirs: list[Path] | None = None,
) -> dict[str, DiscoveredModel]:
"""
Scan multiple model directories and merge results.
@@ -2748,7 +2764,9 @@ def discover_models_from_dirs(
Args:
model_dirs: List of paths to directories containing model subdirectories
- adapters: Receives LoRA adapter folders, earlier directory first
+ gguf_root: Where GGUF model folders are generated; None skips GGUFs
+ adapters: Maps adapter IDs to paths for per-model settings
+ adapter_dirs: Collects local adapter directories for standalone entries
Returns:
Dictionary mapping model_id to DiscoveredModel
@@ -2762,7 +2780,9 @@ def discover_models_from_dirs(
continue
try:
- discovered = discover_models(model_dir, gguf_root, adapters)
+ discovered = discover_models(
+ model_dir, gguf_root, adapters, adapter_dirs=adapter_dirs
+ )
except ValueError as e:
logger.warning(f"Skipping directory {model_dir}: {e}")
continue
diff --git a/omlx/model_settings.py b/omlx/model_settings.py
index 842abf1046..6f312ad6a0 100644
--- a/omlx/model_settings.py
+++ b/omlx/model_settings.py
@@ -314,6 +314,7 @@ def ced_prefill_on(settings: Any) -> bool:
PROFILES_VERSION = 1
TEMPLATES_VERSION = 1
+ADAPTER_BASES_VERSION = 1
_LEGACY_TURBOQUANT_PROFILE_FIELDS = frozenset(
{"turboquant_kv_enabled", "turboquant_kv_bits"}
)
@@ -638,7 +639,7 @@ class ModelSettings:
# LoRA adapter folder applied on top of the weights at load (PEFT or mlx).
# The adapter is never served on its own; profiles can expose a variant.
- lora_adapter: Optional[str] = None
+ lora_adapter: str | None = None
# Model management flags
is_pinned: bool = False
@@ -804,10 +805,12 @@ def __init__(self, base_path: Path):
self.settings_file = self.base_path / "model_settings.json"
self.profiles_file = self.base_path / "model_profiles.json"
self.templates_file = self.base_path / "global_templates.json"
+ self.adapter_bases_file = self.base_path / "adapter_bases.json"
self._lock = threading.Lock()
self._settings: dict[str, ModelSettings] = {}
self._profiles: dict[str, dict[str, dict[str, Any]]] = {}
self._templates: dict[str, dict[str, Any]] = {}
+ self._adapter_bases: dict[str, str] = {}
# Ensure base directory exists
self.base_path.mkdir(parents=True, exist_ok=True)
@@ -817,6 +820,8 @@ def __init__(self, base_path: Path):
self._load()
self._load_profiles()
self._load_templates()
+ with self._lock:
+ self._load_adapter_bases()
def _repair_profile_references(self) -> None:
"""Detach missing references without changing saved settings or IDs."""
@@ -1155,7 +1160,7 @@ def set_settings(self, model_id: str, settings: ModelSettings) -> None:
self._save()
def delete_settings(self, model_id: str) -> bool:
- """Remove all persisted state for a model (settings + profiles).
+ """Remove a model's settings, profiles, and own adapter base override.
Called when a model is deleted so its alias and other settings are
released and can be reused by another model.
@@ -1176,6 +1181,9 @@ def delete_settings(self, model_id: str) -> bool:
del self._profiles[model_id]
self._save_profiles()
removed = True
+ if model_id in self._adapter_bases:
+ self._set_adapter_base_locked(model_id, None)
+ removed = True
if removed:
logger.info(f"Deleted settings for model '{model_id}'")
return removed
@@ -1311,6 +1319,67 @@ def _save_profiles(self) -> None:
temp_file.unlink(missing_ok=True)
raise
+ def _load_adapter_bases(self) -> None:
+ if not self.adapter_bases_file.exists():
+ return
+ try:
+ with open(self.adapter_bases_file, encoding="utf-8") as f:
+ data = json.load(f)
+ version = data.get("version", 1)
+ if version != ADAPTER_BASES_VERSION:
+ logger.warning(
+ "Adapter bases file version %s differs from current %s",
+ version,
+ ADAPTER_BASES_VERSION,
+ )
+ bases = data.get("adapter_bases", {})
+ if not isinstance(bases, dict) or not all(
+ isinstance(key, str) and isinstance(value, str)
+ for key, value in bases.items()
+ ):
+ raise ValueError("adapter_bases must map adapter IDs to base model IDs")
+ self._adapter_bases = bases
+ except (OSError, ValueError, AttributeError) as e:
+ logger.error(f"Failed to load adapter bases file: {e}")
+ self._adapter_bases = {}
+
+ def _save_adapter_bases(self, bases: dict[str, str]) -> None:
+ data = {"version": ADAPTER_BASES_VERSION, "adapter_bases": bases}
+ temp_file = self.adapter_bases_file.with_name(
+ f"{self.adapter_bases_file.name}.{os.getpid()}.tmp"
+ )
+ try:
+ with open(temp_file, "w", encoding="utf-8") as f:
+ json.dump(data, f, indent=2, ensure_ascii=False)
+ f.flush()
+ os.fsync(f.fileno())
+ temp_file.replace(self.adapter_bases_file)
+ except (OSError, ValueError, TypeError) as e:
+ logger.error(f"Failed to save adapter bases file: {e}")
+ temp_file.unlink(missing_ok=True)
+ raise
+
+ def get_adapter_bases(self) -> dict[str, str]:
+ with self._lock:
+ return self._adapter_bases.copy()
+
+ def set_adapter_base(self, adapter_id: str, base_model_id: str | None) -> None:
+ with self._lock:
+ self._set_adapter_base_locked(adapter_id, base_model_id)
+
+ def _set_adapter_base_locked(
+ self, adapter_id: str, base_model_id: str | None
+ ) -> None:
+ if self._adapter_bases.get(adapter_id) == base_model_id:
+ return
+ bases = self._adapter_bases.copy()
+ if base_model_id is None:
+ del bases[adapter_id]
+ else:
+ bases[adapter_id] = base_model_id
+ self._save_adapter_bases(bases)
+ self._adapter_bases = bases
+
@staticmethod
def _dedupe_profile_api_name(base: str, used: set[str]) -> str:
validate_profile_name(base)
diff --git a/omlx/prefill_helper/routes.py b/omlx/prefill_helper/routes.py
index 1e4b8c9c24..b3cc959fd1 100644
--- a/omlx/prefill_helper/routes.py
+++ b/omlx/prefill_helper/routes.py
@@ -62,6 +62,8 @@ def _saved_settings(model_id: str) -> Any:
def _adapter(entry: Any) -> Any:
+ if getattr(entry, "adapter", None) is not None:
+ return None
return adapter_for_model(
getattr(entry, "config_model_type", None),
getattr(entry, "engine_type", None),
@@ -84,6 +86,8 @@ def prepare_unloaded(entry: Any, settings: Any) -> None:
def helper_status(entry: Any) -> dict | None:
"""The loaded model's helper, else the copy made before it loads."""
+ if getattr(entry, "adapter", None) is not None:
+ return None
manager = getattr(entry.engine, "prefill_helper", None)
if manager is not None:
return manager.status()
@@ -269,6 +273,10 @@ async def model_action(model_id: str, action: str) -> dict:
if action not in ("check", "copy", "retry", "stop"):
raise HTTPException(status_code=404, detail=f"Unknown action: {action}")
entry = _entry(model_id)
+ if getattr(entry, "adapter", None) is not None:
+ raise HTTPException(
+ status_code=400, detail="LoRA adapters do not support remote prefill."
+ )
manager = getattr(entry.engine, "prefill_helper", None)
if manager is not None:
if action != "check":
diff --git a/omlx/server.py b/omlx/server.py
index 2235889aca..ffcc015ec7 100644
--- a/omlx/server.py
+++ b/omlx/server.py
@@ -4008,7 +4008,10 @@ async def _list_models(*, claude_gateway: bool = False) -> JSONResponse:
is_hidden_helper = hide_helpers and (
m.get("is_helper")
or model_id in referenced_drafts
- or m.get("model_path") in referenced_drafts
+ or (
+ m.get("adapter") is None
+ and m.get("model_path") in referenced_drafts
+ )
or (m.get("source_repo_id") in referenced_drafts)
)
# A GGUF no external engine can serve is listed in the admin only.
diff --git a/tests/conftest.py b/tests/conftest.py
index f7da42c76d..5c1e1b6409 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -394,6 +394,68 @@ def write(path: Path, metadata: dict, size: int = 0) -> Path:
return write
+@pytest.fixture
+def write_lora_adapter():
+ """Write a tiny valid PEFT LoRA directory and return it.
+
+ Other test files use this. ``modules`` maps an HF module path to its
+ ``(in_features, out_features)``. ``tensors`` maps full tensor names to arrays and
+ replaces generated tensors of the same name. ``config`` is merged over the
+ generated adapter_config.json.
+ """
+ import json
+ from collections.abc import Mapping
+
+ import numpy as np
+ from safetensors.numpy import save_file
+
+ def write(
+ path: Path,
+ *,
+ base_ref: str = "Qwen/Qwen3.8-27B",
+ rank: int = 4,
+ alpha: float = 8.0,
+ modules: Mapping[str, tuple[int, int]] | None = None,
+ tensors: Mapping[str, np.ndarray] | None = None,
+ config: Mapping[str, Any] | None = None,
+ ) -> Path:
+ if modules is None:
+ modules = {"model.layers.0.mlp.gate_proj": (8, 16)}
+ rng = np.random.default_rng(0)
+ weights = {}
+ for hf_path, (in_features, out_features) in modules.items():
+ prefix = f"base_model.model.{hf_path}"
+ lora_a = rng.standard_normal((rank, in_features)) * 0.1
+ lora_b = rng.standard_normal((out_features, rank)) * 0.1
+ weights[f"{prefix}.lora_A.weight"] = lora_a.astype(np.float32)
+ weights[f"{prefix}.lora_B.weight"] = lora_b.astype(np.float32)
+ weights.update(tensors or {})
+
+ path.mkdir(parents=True, exist_ok=True)
+ document = {
+ "peft_type": "LORA",
+ "r": rank,
+ "lora_alpha": alpha,
+ "base_model_name_or_path": base_ref,
+ "bias": "none",
+ "use_dora": False,
+ "use_rslora": False,
+ "fan_in_fan_out": False,
+ "rank_pattern": {},
+ "alpha_pattern": {},
+ "modules_to_save": None,
+ "target_parameters": None,
+ **(config or {}),
+ }
+ (path / "adapter_config.json").write_text(json.dumps(document))
+ save_file(
+ weights, str(path / "adapter_model.safetensors"), metadata={"format": "pt"}
+ )
+ return path
+
+ return write
+
+
@pytest.fixture
def write_z_image_checkpoint():
pytest.importorskip("mlx_vlm")
diff --git a/tests/test_admin_adapters_api.py b/tests/test_admin_adapters_api.py
new file mode 100644
index 0000000000..95eb3e8f2a
--- /dev/null
+++ b/tests/test_admin_adapters_api.py
@@ -0,0 +1,452 @@
+# SPDX-License-Identifier: Apache-2.0
+from dataclasses import dataclass
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+from fastapi import HTTPException, Request
+
+from omlx.admin import routes
+from omlx.admin.hf_downloader import HFDownloader
+from omlx.lora_adapter import (
+ AdapterBinding,
+ AdapterIssue,
+ BaseCandidate,
+ BaseRef,
+ IssueKind,
+ bind_adapter,
+ parse_adapter,
+)
+
+pytestmark = pytest.mark.asyncio
+
+
+@dataclass
+class Entry:
+ model_id: str
+ model_path: str
+ adapter: AdapterBinding | None = None
+ model_format: str = "mlx"
+ engine: object | None = None
+ is_loading: bool = False
+
+
+class Settings:
+ def __init__(self):
+ self.bases = {}
+ self.deleted = []
+
+ def get_adapter_bases(self):
+ return self.bases.copy()
+
+ def set_adapter_base(self, adapter_id, base_id):
+ if base_id is None:
+ self.bases.pop(adapter_id, None)
+ else:
+ self.bases[adapter_id] = base_id
+
+ def delete_settings(self, model_id):
+ self.deleted.append(model_id)
+ self.bases.pop(model_id, None)
+
+ def get_pinned_model_ids(self):
+ return ["z-base"]
+
+ def get_all_settings(self):
+ return {}
+
+ def list_profiles(self, model_id):
+ return []
+
+
+class Pool:
+ def __init__(self, settings):
+ self.settings = settings
+ self._entries = {}
+ self.adapter_issues = ()
+ self.candidates = ()
+ self.discoveries = []
+ self.applied_overrides = None
+ self.unresolved = None
+
+ def get_entry(self, model_id):
+ return self._entries.get(model_id)
+
+ def get_loaded_model_ids(self):
+ return [
+ entry.model_id
+ for entry in self._entries.values()
+ if entry.engine is not None
+ ]
+
+ def get_status(self):
+ return {
+ "models": [
+ {
+ "id": entry.model_id,
+ "model_path": entry.model_path,
+ "adapter": entry.adapter.as_status() if entry.adapter else None,
+ }
+ for entry in self._entries.values()
+ ]
+ }
+
+ def adapter_base_candidates(self):
+ return self.candidates
+
+ def discover_models(self, dirs, pinned_ids):
+ self.discoveries.append((dirs, pinned_ids))
+ if self.unresolved is None:
+ return
+ source, issue = self.unresolved
+ base_id = self.settings.get_adapter_bases().get(source.public_id)
+ if base_id is None:
+ self._entries.pop(source.public_id, None)
+ self.adapter_issues = (issue,)
+ return
+ base = next(
+ candidate for candidate in self.candidates if candidate.model_id == base_id
+ )
+ self._entries[source.public_id] = Entry(
+ source.public_id,
+ str(base.path),
+ bind_adapter(source, BaseRef(base_id, base.path)),
+ )
+ self.adapter_issues = ()
+
+ def apply_settings_overrides(self, settings):
+ self.applied_overrides = settings.get_adapter_bases()
+
+
+@pytest.fixture
+def admin(monkeypatch, tmp_path):
+ settings = Settings()
+ pool = Pool(settings)
+ roots = [tmp_path]
+ monkeypatch.setattr(routes, "_get_engine_pool", lambda: pool)
+ monkeypatch.setattr(routes, "_get_settings_manager", lambda: settings)
+ monkeypatch.setattr(
+ routes,
+ "_get_global_settings",
+ lambda: SimpleNamespace(get_effective_model_dirs=lambda: roots),
+ )
+ monkeypatch.setattr(routes, "_get_server_state", lambda: None)
+ monkeypatch.setattr(routes, "_hf_downloader", None)
+ return pool, settings, roots
+
+
+@pytest.fixture
+def adapter(admin, tmp_path, write_lora_adapter):
+ pool, _, _ = admin
+ source = parse_adapter(write_lora_adapter(tmp_path / "hub" / "tuned"))
+ pool.candidates = (
+ BaseCandidate("z-base", tmp_path / "z-base", frozenset({"org/base"})),
+ BaseCandidate("a-base", tmp_path / "a-base", frozenset({"org/base"})),
+ BaseCandidate("Base-4bit", tmp_path / "Base-4bit", frozenset()),
+ )
+ base = pool.candidates[0]
+ entry = Entry(
+ "tuned", str(base.path), bind_adapter(source, BaseRef(base.model_id, base.path))
+ )
+ pool._entries[entry.model_id] = entry
+ return entry
+
+
+def ambiguous_issue(path):
+ return AdapterIssue(
+ "tuned", path, IssueKind.BASE_AMBIGUOUS, "Choose a base.", ("a-base", "z-base")
+ )
+
+
+def issue_row(path):
+ return {
+ "id": "tuned",
+ "kind": "base_ambiguous",
+ "reason": "Choose a base.",
+ "candidates": ["a-base", "z-base"],
+ "path": str(path),
+ }
+
+
+async def test_import_mtplx_rejects_adapter_without_invoking_import(
+ adapter, monkeypatch
+):
+ from omlx import oq
+
+ def unexpected_import(model_path):
+ pytest.fail(f"MTPLX importer was called with {model_path}")
+
+ monkeypatch.setattr(oq, "import_mtplx_sidecar", unexpected_import)
+
+ with pytest.raises(HTTPException) as exc:
+ await routes.import_mtplx("tuned", is_admin=True)
+
+ assert exc.value.status_code == 400
+ assert "Import against the base model ID 'z-base' instead." in exc.value.detail
+
+
+def adapter_row(adapter, base_id):
+ return {
+ "base_model_id": base_id,
+ "rank": 4,
+ "alpha": 8.0,
+ "weight_bytes": adapter.source.weights_path.stat().st_size,
+ }
+
+
+async def set_base(base_id, adapter_id="tuned"):
+ return await routes.set_adapter_base(
+ adapter_id, routes.AdapterBaseRequest(base_model_id=base_id), is_admin=True
+ )
+
+
+async def test_list_models_includes_binding_and_all_issues(
+ admin, adapter, tmp_path, monkeypatch
+):
+ pool, _, _ = admin
+ monkeypatch.setattr(routes, "_get_global_settings", lambda: None)
+ monkeypatch.setattr(routes, "stage_adapter_for", lambda *_: object())
+ pool._entries["z-base"] = Entry("z-base", adapter.model_path)
+ paths = [tmp_path / "one" / "tuned", tmp_path / "two" / "tuned"]
+ pool.adapter_issues = tuple(ambiguous_issue(path) for path in paths)
+
+ result = await routes.list_models(is_admin=True)
+
+ rows = {row["id"]: row for row in result["models"]}
+ assert rows["tuned"]["adapter"] == adapter_row(adapter.adapter, "z-base")
+ assert rows["z-base"]["adapter"] is None
+ assert rows["z-base"]["prefill_helper_supported"] is True
+ assert rows["tuned"]["prefill_helper_supported"] is False
+ assert result["adapter_issues"] == [issue_row(path) for path in paths]
+
+
+async def test_adapter_display_name_is_distinct_from_organized_base(
+ admin, adapter, monkeypatch
+):
+ pool, _, roots = admin
+ monkeypatch.setattr(routes, "_get_global_settings", lambda: None)
+ monkeypatch.setattr(routes, "_model_dirs_for_display", lambda _: roots)
+ adapter.model_path = str(roots[0] / "org" / "z-base")
+ pool._entries["z-base"] = Entry("z-base", adapter.model_path)
+
+ result = await routes.list_models(is_admin=True)
+
+ rows = {row["id"]: row for row in result["models"]}
+ assert rows["tuned"]["display_name"] == "tuned"
+ assert rows["z-base"]["display_name"] == "org/z-base"
+ assert rows["tuned"]["model_path"] == rows["z-base"]["model_path"]
+
+
+async def test_admin_rejects_remote_prefill_on_loaded_adapter(admin, adapter):
+ from unittest.mock import Mock
+
+ adapter.engine = Mock()
+ request = routes.ModelSettingsRequest(prefill_helper_node_id="peer")
+ with pytest.raises(HTTPException, match="do not support remote prefill") as caught:
+ await routes.update_model_settings("tuned", request, is_admin=True)
+ assert caught.value.status_code == 400
+ adapter.engine.configure_prefill_helper.assert_not_called()
+
+
+@pytest.mark.parametrize("dependency", ["_get_engine_pool", "_get_settings_manager"])
+async def test_set_base_requires_initialized_services(admin, monkeypatch, dependency):
+ monkeypatch.setattr(routes, dependency, lambda: None)
+ with pytest.raises(HTTPException) as exc:
+ await set_base(None)
+ assert exc.value.status_code == 503
+
+
+async def test_set_base_rejects_unknown_adapter(admin):
+ with pytest.raises(HTTPException) as exc:
+ await set_base("unknown")
+ assert exc.value.status_code == 404
+
+
+@pytest.mark.parametrize("base_id", ["helper", "tuned", "unknown"])
+async def test_set_base_checks_chat_candidates(admin, adapter, base_id):
+ pool, settings, _ = admin
+ pool._entries["helper"] = Entry("helper", adapter.model_path)
+ with pytest.raises(HTTPException) as exc:
+ await set_base(base_id)
+ assert exc.value.status_code == 400
+ assert base_id in exc.value.detail
+ assert settings.get_adapter_bases() == {}
+
+
+@pytest.mark.parametrize("state", ["loaded", "loading"])
+@pytest.mark.parametrize("base_id", ["a-base", None])
+async def test_set_base_cannot_change_active_binding(admin, adapter, state, base_id):
+ pool, settings, _ = admin
+ if state == "loaded":
+ adapter.engine = object()
+ else:
+ adapter.is_loading = True
+ settings.set_adapter_base("tuned", "z-base")
+
+ with pytest.raises(HTTPException) as exc:
+ await set_base(base_id)
+
+ assert exc.value.status_code == 409
+ assert settings.get_adapter_bases() == {"tuned": "z-base"}
+ assert not pool.discoveries
+
+
+@pytest.mark.parametrize("collision", ["bound", "base", "unresolved", "reserved"])
+async def test_set_base_refuses_colliding_ids(admin, adapter, tmp_path, collision):
+ pool, settings, _ = admin
+ source_path = adapter.adapter.source.path
+ other_path = tmp_path / "other" / "tuned"
+ collision_issue = AdapterIssue(
+ "tuned", other_path, IssueKind.ID_COLLISION, "Rename the adapter."
+ )
+ pool.adapter_issues = (collision_issue,)
+ if collision == "base":
+ pool._entries["tuned"] = Entry("tuned", str(tmp_path / "tuned"))
+ elif collision in {"unresolved", "reserved"}:
+ del pool._entries["tuned"]
+ if collision == "unresolved":
+ pool.adapter_issues = (
+ ambiguous_issue(source_path),
+ ambiguous_issue(other_path),
+ )
+
+ with pytest.raises(HTTPException) as exc:
+ await set_base("a-base")
+
+ assert exc.value.status_code == 409
+ assert settings.get_adapter_bases() == {}
+ assert not pool.discoveries
+
+
+@pytest.mark.parametrize("already_bound", [True, False])
+async def test_set_base_pins_then_clears_and_reports_fresh_discovery(
+ admin, adapter, already_bound
+):
+ pool, settings, roots = admin
+ source = adapter.adapter.source
+ issue = ambiguous_issue(source.path)
+ pool.unresolved = (source, issue)
+ if not already_bound:
+ del pool._entries["tuned"]
+ pool.adapter_issues = (issue,)
+
+ assert await set_base("a-base") == {
+ "success": True,
+ "id": "tuned",
+ "base_model_id": "a-base",
+ "adapter": adapter_row(adapter.adapter, "a-base"),
+ "issue": None,
+ }
+ assert settings.get_adapter_bases() == pool.applied_overrides == {"tuned": "a-base"}
+ discovery = ([str(roots[0])], ["z-base"])
+ assert pool.discoveries == [discovery]
+
+ assert await set_base(None) == {
+ "success": True,
+ "id": "tuned",
+ "base_model_id": None,
+ "adapter": None,
+ "issue": issue_row(source.path),
+ }
+ assert settings.get_adapter_bases() == pool.applied_overrides == {}
+ assert pool.discoveries == [discovery, discovery]
+
+
+@pytest.mark.parametrize("pool_state", ["ready", "none", "uninitialized", "plain"])
+async def test_hf_model_info_reports_matching_local_bases(
+ admin, adapter, monkeypatch, pool_state
+):
+ payload = {"adapter": None, "unsupported_reason": None}
+ if pool_state != "plain":
+ payload["adapter"] = {"base_repo_id": "Org/Base", "rank": 4}
+
+ async def get_info(**kwargs):
+ return payload
+
+ monkeypatch.setattr(HFDownloader, "get_model_info", get_info)
+ if pool_state == "none":
+ monkeypatch.setattr(routes, "_get_engine_pool", lambda: None)
+ elif pool_state == "uninitialized":
+
+ def no_pool():
+ raise HTTPException(status_code=503)
+
+ monkeypatch.setattr(routes, "_get_engine_pool", no_pool)
+
+ result = await routes.get_hf_model_info(
+ Request({"type": "http", "headers": []}), repo_id="hub/tuned", is_admin=True
+ )
+ if pool_state == "plain":
+ assert result == {"adapter": None, "unsupported_reason": None}
+ else:
+ assert result["adapter"] == {
+ "base_repo_id": "Org/Base",
+ "rank": 4,
+ "local_base_ids": ["a-base", "z-base"] if pool_state == "ready" else [],
+ }
+
+
+async def test_hf_listing_includes_flat_and_nested_adapters(
+ admin, tmp_path, write_lora_adapter
+):
+ flat = write_lora_adapter(tmp_path / "flat")
+ nested = write_lora_adapter(tmp_path / "hub" / "nested")
+
+ result = await routes.list_hf_models(is_admin=True)
+
+ assert {row["name"]: (row["path"], row["repo_id"]) for row in result["models"]} == {
+ "flat": (str(flat), None),
+ "nested": (str(nested), "hub/nested"),
+ }
+
+
+def write_base(path: Path):
+ path.mkdir(parents=True)
+ (path / "config.json").write_text('{"architectures": ["Qwen2ForCausalLM"]}')
+ (path / "model.safetensors").write_bytes(b"base weights")
+ return path
+
+
+async def test_delete_adapter_keeps_base_and_releases_state(admin, adapter):
+ pool, settings, roots = admin
+ base = write_base(Path(adapter.model_path))
+ path = adapter.adapter.source.path
+ settings.set_adapter_base("tuned", "z-base")
+
+ result = await routes.delete_hf_model("tuned", is_admin=True)
+
+ assert result["success"] is True
+ assert not path.exists()
+ assert (base / "model.safetensors").read_bytes() == b"base weights"
+ assert (base / "config.json").is_file()
+ assert pool.get_entry("tuned") is None
+ assert settings.deleted == ["tuned"]
+ assert settings.get_adapter_bases() == pool.applied_overrides == {}
+ assert pool.discoveries == [([str(roots[0])], ["z-base"])]
+
+
+@pytest.mark.parametrize("delete_adapter", [False, True])
+async def test_delete_same_basename_matches_registered_kind(
+ admin, adapter, tmp_path, write_lora_adapter, delete_adapter
+):
+ pool, _, roots = admin
+ other_root = tmp_path / "other"
+ checkpoint = write_base(other_root / "tuned")
+ path = adapter.adapter.source.path
+ if delete_adapter:
+ duplicate = write_lora_adapter(other_root / "hub" / "tuned")
+ roots.insert(0, other_root)
+ else:
+ pool._entries["tuned"] = Entry("tuned", str(checkpoint))
+ roots.append(other_root)
+
+ result = await routes.delete_hf_model("tuned", is_admin=True)
+
+ assert result["success"] is True
+ if delete_adapter:
+ assert (checkpoint / "model.safetensors").read_bytes() == b"base weights"
+ assert duplicate.is_dir()
+ assert not path.exists()
+ else:
+ assert not checkpoint.exists()
+ assert path.is_dir()
diff --git a/tests/test_batched_engine.py b/tests/test_batched_engine.py
index 8bbeaf4ae8..83ebb41329 100644
--- a/tests/test_batched_engine.py
+++ b/tests/test_batched_engine.py
@@ -25,6 +25,60 @@
from omlx.engine.base import BaseEngine, BaseNonStreamingEngine, GenerationOutput
+@pytest.mark.asyncio
+@pytest.mark.parametrize("case", ["adapter", "base", "invalid"])
+async def test_start_attaches_lora_before_post_load(
+ tmp_path, monkeypatch, write_lora_adapter, case
+):
+ from omlx import lora_adapter
+ from omlx.engine.batched import BatchedEngine
+ from omlx.exceptions import AdapterShapeError
+ from omlx.utils import model_loading
+
+ class PostLoadReachedError(Exception):
+ pass
+
+ source = lora_adapter.parse_adapter(write_lora_adapter(tmp_path / "adapter"))
+ binding = lora_adapter.bind_adapter(source, lora_adapter.BaseRef("base", tmp_path))
+ model, tokenizer = object(), object()
+ calls = []
+
+ def load(*args, **kwargs):
+ calls.append("load")
+ return model, tokenizer
+
+ def attach(loaded, adapter):
+ assert loaded is model and adapter is binding
+ calls.append("attach")
+ if case == "invalid":
+ raise AdapterShapeError("invalid test adapter", source.path)
+ return 1
+
+ def post_load(loaded, settings):
+ assert loaded is model
+ calls.append("post_load")
+ raise PostLoadReachedError
+
+ monkeypatch.setattr(
+ model_loading, "maybe_apply_pre_load_patches", lambda *a, **kw: None
+ )
+ monkeypatch.setattr(model_loading, "maybe_load_custom_quantization", load)
+ monkeypatch.setattr(lora_adapter, "attach_lora", attach)
+ monkeypatch.setattr(model_loading, "apply_post_load_transforms", post_load)
+ engine = BatchedEngine(str(tmp_path), lora=None if case == "base" else binding)
+ if case == "invalid":
+ with pytest.raises(AdapterShapeError, match="invalid test adapter"):
+ await engine.start()
+ assert calls == ["load", "attach"]
+ assert engine.tokenizer is None
+ else:
+ with pytest.raises(PostLoadReachedError):
+ await engine.start()
+ assert calls == (
+ ["load", "post_load"] if case == "base" else ["load", "attach", "post_load"]
+ )
+
+
class FakeStreamingCore:
"""Minimal async engine core for stream cleanup tests."""
diff --git a/tests/test_cluster_engine_pool.py b/tests/test_cluster_engine_pool.py
index a754163af4..659fedee8c 100644
--- a/tests/test_cluster_engine_pool.py
+++ b/tests/test_cluster_engine_pool.py
@@ -8,6 +8,7 @@
from omlx.cluster.deployment import ClusterDeployment, ClusterHost
from omlx.cluster.planner import PipelineAssignment
from omlx.engine_pool import EngineEntry, EnginePool
+from omlx.exceptions import ModelLoadingError
def _deployment(model_path: str) -> ClusterDeployment:
@@ -91,6 +92,34 @@ def test_pool_status_reports_full_and_local_cluster_sizes(tmp_path):
assert model["distributed"] is True
+@pytest.mark.asyncio
+async def test_cluster_path_matches_base_but_never_adapter(
+ tmp_path, write_lora_adapter
+):
+ base = tmp_path / "nemotron"
+ base.mkdir()
+ (base / "config.json").write_text('{"model_type": "llama"}')
+ (base / "model.safetensors").write_bytes(b"0" * 100)
+ write_lora_adapter(tmp_path / "aaa-adapter", base_ref="owner/nemotron")
+ pool = EnginePool()
+ pool.discover_models(str(tmp_path))
+ deployment = _deployment(str(base))
+ pool._cluster_registry = SimpleNamespace(
+ get_for_model=lambda path: deployment if path == str(base) else None
+ )
+
+ assert pool.resolve_cluster_model_id(str(base)) == "nemotron"
+ assert pool.register_cluster_model(str(base), estimated_size=100) == (
+ "nemotron",
+ False,
+ )
+ status = {row["id"]: row for row in pool.get_status()["models"]}
+ assert status["nemotron"]["distributed"] is True
+ assert status["aaa-adapter"]["distributed"] is False
+ with pytest.raises(ModelLoadingError, match="aaa-adapter.*distributed cluster"):
+ await pool.get_engine("aaa-adapter")
+
+
def test_cluster_model_path_resolves_to_public_model_id(tmp_path):
model_path = tmp_path / "nemotron"
model_path.mkdir()
diff --git a/tests/test_cluster_model_inventory.py b/tests/test_cluster_model_inventory.py
index c0cdaba40c..872b749af1 100644
--- a/tests/test_cluster_model_inventory.py
+++ b/tests/test_cluster_model_inventory.py
@@ -118,6 +118,12 @@ def get_status(self):
"model_type": "embedding",
"estimated_size": 2,
},
+ {
+ "id": "tuned",
+ "model_path": "/models/m3",
+ "model_type": "vlm",
+ "adapter": {"base_model_id": "m3"},
+ },
{
"id": "Q-UD-Q4_K_M",
"model_path": "/base/gguf/Q-UD-Q4_K_M-0123",
diff --git a/tests/test_engine_pool.py b/tests/test_engine_pool.py
index 43db6034c9..a518b73dca 100644
--- a/tests/test_engine_pool.py
+++ b/tests/test_engine_pool.py
@@ -31,6 +31,7 @@
ModelUnavailableError,
is_metal_out_of_memory,
)
+from omlx.model_discovery import discover_models
from omlx.model_settings import ModelSettings, ModelSettingsManager
from omlx.patches.mlx_vlm_qwen4_exp_compat.residency import (
Qwen4ExpResidencyEstimate,
@@ -73,6 +74,293 @@ def small_mock_model_dir(tmp_path):
return tmp_path
+@pytest.fixture
+def lora_pool(small_mock_model_dir, write_lora_adapter):
+ adapter = write_lora_adapter(
+ small_mock_model_dir / "harness-hub" / "pi",
+ base_ref="owner/model-a",
+ )
+ pool = _make_pool()
+ pool.discover_models(str(small_mock_model_dir))
+ return pool, adapter
+
+
+def test_adapter_discovery_adds_a_separate_model(lora_pool, small_mock_model_dir):
+ pool, adapter_dir = lora_pool
+ base = pool.get_entry("model-a")
+ adapter = pool.get_entry("pi")
+ weight_bytes = (adapter_dir / "adapter_model.safetensors").stat().st_size
+ assert (
+ adapter.model_path == base.model_path == str(small_mock_model_dir / "model-a")
+ )
+ assert base.adapter is None
+ plain_size = discover_models(small_mock_model_dir)["model-a"].estimated_size
+ assert base.estimated_size == plain_size
+ assert adapter.estimated_size == plain_size + weight_bytes
+ assert adapter.source_type == "local"
+ assert adapter.adapter.source.path == adapter_dir
+ assert {candidate.model_id for candidate in pool.adapter_base_candidates()} == {
+ "model-a",
+ "model-b",
+ }
+ rows = {row["id"]: row for row in pool.get_status()["models"]}
+ assert rows["model-a"]["adapter"] is None
+ assert rows["pi"]["adapter"] == {
+ "base_model_id": "model-a",
+ "rank": 4,
+ "alpha": 8.0,
+ "weight_bytes": weight_bytes,
+ }
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ ("settings", "reason"),
+ [
+ (ModelSettings(moe_expert_offload_enabled=True), "MoE expert offload"),
+ (ModelSettings(dflash_enabled=True), "DFlash"),
+ ],
+)
+async def test_routed_adapter_rejects_bypassing_runtime_modes(
+ small_mock_model_dir, write_lora_adapter, settings, reason
+):
+ import numpy as np
+
+ stem = "model.layers.0.mlp.experts"
+ write_lora_adapter(
+ small_mock_model_dir / "routed",
+ base_ref="owner/model-a",
+ rank=1,
+ modules={},
+ tensors={
+ f"base_model.model.{stem}.lora_A.weight": np.ones((3, 8), np.float32),
+ f"base_model.model.{stem}.lora_B.weight": np.ones((16, 3), np.float32),
+ },
+ config={"target_parameters": [stem + ".down_proj"]},
+ )
+ pool = _make_pool()
+ pool.discover_models(str(small_mock_model_dir))
+ with patch("omlx.engine_pool.BatchedEngine") as engine:
+ with pytest.raises(ModelLoadingError, match=reason):
+ await pool.get_engine("routed", runtime_settings=settings)
+ engine.assert_not_called()
+
+
+def test_missing_adapter_base_is_reported_once(tmp_path, caplog, write_lora_adapter):
+ write_lora_adapter(tmp_path / "pi", base_ref="owner/missing")
+ pool = _make_pool()
+ for _ in range(2):
+ pool.discover_models(str(tmp_path))
+ assert pool.get_model_ids() == []
+ (issue,) = pool.adapter_issues
+ assert (issue.public_id, issue.kind.value) == ("pi", "base_missing")
+ assert "owner/missing" in issue.detail
+ assert sum(issue.detail in record.message for record in caplog.records) == 1
+
+
+@pytest.mark.asyncio
+async def test_override_resolves_ambiguity_without_rebinding_loaded_adapter(
+ lora_pool, small_mock_model_dir
+):
+ pool, _ = lora_pool
+ root = small_mock_model_dir
+ shutil.copytree(root / "model-a", root / "model-a-4bit")
+ manager = ModelSettingsManager(root / "settings")
+ pool._settings_manager = manager
+ pool.discover_models(str(root))
+ assert pool.get_entry("pi") is None
+ (issue,) = pool.adapter_issues
+ assert issue.kind.value == "base_ambiguous"
+ assert set(issue.candidates) == {"model-a", "model-a-4bit"}
+
+ manager.set_adapter_base("pi", "model-a-4bit")
+ pool.discover_models(str(root))
+ assert pool.adapter_issues == ()
+ loaded = MagicMock(start=AsyncMock(), stop=AsyncMock())
+ with patch("omlx.engine_pool.BatchedEngine", return_value=loaded):
+ assert await pool.get_engine("pi") is loaded
+ manager.set_adapter_base("pi", "model-a")
+ pool.discover_models(str(root))
+ assert pool.get_entry("pi").engine is loaded
+ assert pool.get_entry("pi").adapter.base.model_id == "model-a-4bit"
+ assert pool.get_entry("pi").model_path == str(root / "model-a-4bit")
+
+
+@pytest.mark.asyncio
+async def test_rediscovery_does_not_serve_adapter_from_a_replaced_directory(
+ lora_pool, small_mock_model_dir, write_lora_adapter
+):
+ pool, first = lora_pool
+ loaded = MagicMock(start=AsyncMock(), stop=AsyncMock(), scheduler=None, _engine=None)
+ with patch("omlx.engine_pool.BatchedEngine", return_value=loaded):
+ assert await pool.get_engine("pi") is loaded
+ shutil.rmtree(first)
+ second = write_lora_adapter(
+ small_mock_model_dir / "other" / "pi", base_ref="owner/model-b"
+ )
+ pool.discover_models(str(small_mock_model_dir))
+
+ with pytest.raises(ModelLoadingError, match="changed adapter directory"):
+ await pool.get_engine("pi")
+ assert pool.get_entry("pi").engine is loaded
+
+ assert await pool.request_unload("pi", reason="test")
+ pool.discover_models(str(small_mock_model_dir))
+ assert pool.get_entry("pi").adapter.source.path == second
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("final_state", ["valid", "missing_base", "malformed"])
+async def test_rediscovery_does_not_serve_resident_base_under_adapter_id(
+ small_mock_model_dir, write_lora_adapter, final_state
+):
+ root = small_mock_model_dir
+ pool = _make_pool()
+ pool.discover_models(str(root))
+ loaded = MagicMock(start=AsyncMock(), stop=AsyncMock())
+ with patch("omlx.engine_pool.BatchedEngine", return_value=loaded):
+ assert await pool.get_engine("model-b") is loaded
+ shutil.rmtree(root / "model-b")
+ write_lora_adapter(root / "model-b", base_ref="owner/model-a")
+ pool.discover_models(str(root))
+ if final_state == "missing_base":
+ write_lora_adapter(root / "model-b", base_ref="owner/missing")
+ elif final_state == "malformed":
+ (root / "model-b" / "adapter_config.json").write_text("not JSON")
+ pool.discover_models(str(root))
+
+ with pytest.raises(ModelLoadingError, match="changed between a base and a LoRA"):
+ await pool.get_engine("model-b")
+
+
+@pytest.mark.asyncio
+async def test_invalid_adapter_elsewhere_does_not_block_same_name_base(
+ small_mock_model_dir, write_lora_adapter
+):
+ root = small_mock_model_dir
+ pool = _make_pool()
+ pool.discover_models(str(root))
+ loaded = MagicMock(start=AsyncMock(), stop=AsyncMock())
+ with patch("omlx.engine_pool.BatchedEngine", return_value=loaded):
+ assert await pool.get_engine("model-b") is loaded
+ write_lora_adapter(root / "owner" / "model-b", base_ref="owner/missing")
+ pool.discover_models(str(root))
+ assert await pool.get_engine("model-b") is loaded
+
+
+def test_adapter_seeds_thinking_off_but_not_lightning_mtp(
+ lora_pool, small_mock_model_dir, write_lora_adapter
+):
+ pool, _ = lora_pool
+ root = small_mock_model_dir
+ (root / "model-a" / "chat_template.jinja").write_text(
+ "{% if enable_thinking | default(true) %}thinking{% else %}plain{% endif %}"
+ )
+ (root / "model-a" / "config.json").write_text(
+ '{"model_type": "qwen3_5", "mtp_num_hidden_layers": 1}'
+ )
+ (root / "model-a" / "model.safetensors.index.json").write_text(
+ '{"weight_map": {"mtp.fc.weight": "model.safetensors"}}'
+ )
+ write_lora_adapter(root / "pi-no-toggle", base_ref="owner/model-b")
+ pool.discover_models(str(root))
+ assert pool.get_entry("model-a").thinking_default is True
+ assert pool.get_entry("pi-no-toggle").thinking_default is None
+ manager = ModelSettingsManager(root / "settings")
+ pool.apply_settings_overrides(manager)
+
+ saved = ModelSettingsManager(root / "settings")
+ assert saved.get_settings("pi").enable_thinking is False
+ assert saved.get_settings("pi").mtp_enabled is False
+ assert saved.get_settings("pi-no-toggle").enable_thinking is None
+ assert saved.get_settings("model-a").enable_thinking is None
+ assert saved.get_settings("model-a").mtp_enabled is True
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ "force_lm, failed_engine",
+ [(False, None), (True, None), (False, "vlm"), (True, "batched")],
+)
+async def test_adapter_reaches_vlm_and_batched_engines_including_fallbacks(
+ lora_pool, force_lm, failed_engine
+):
+ pool, _ = lora_pool
+ entry = pool.get_entry("pi")
+ entry.engine_type = entry.model_type = "vlm"
+ vlm = MagicMock(start=AsyncMock(), stop=AsyncMock())
+ batched = MagicMock(start=AsyncMock(), stop=AsyncMock())
+ if failed_engine is not None:
+ failed = vlm if failed_engine == "vlm" else batched
+ failed.start.side_effect = ValueError("unsupported checkpoint")
+ with (
+ patch("omlx.engine_pool.VLMBatchedEngine", return_value=vlm) as vlm_cls,
+ patch("omlx.engine_pool.BatchedEngine", return_value=batched) as batched_cls,
+ ):
+ engine = await pool.get_engine("pi", force_lm=force_lm)
+
+ expected = batched if force_lm != (failed_engine is not None) else vlm
+ assert engine is expected
+ constructors = [cls for cls in (vlm_cls, batched_cls) if cls.called]
+ assert len(constructors) == (2 if failed_engine else 1)
+ for cls in constructors:
+ assert cls.call_args.kwargs["lora"] is entry.adapter
+ assert cls.call_args.kwargs["scheduler_config"].model_name == "pi"
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ "settings, reason",
+ [
+ (ModelSettings(external_engine="splash"), "Splash"),
+ (ModelSettings(prefill_helper_node_id="peer"), "prefill helper"),
+ (ModelSettings(mtp_enabled=True), "MTP"),
+ (ModelSettings(vlm_mtp_enabled=True), "MTP"),
+ (ModelSettings(qwen35_ane_prefill_enabled=True), "ANE prefill"),
+ (ModelSettings(model_type_override="embedding"), "embedding engine"),
+ ],
+)
+async def test_adapter_rejects_modes_that_cannot_guarantee_the_delta(
+ lora_pool, small_mock_model_dir, settings, reason
+):
+ pool, _ = lora_pool
+ manager = ModelSettingsManager(small_mock_model_dir / "settings")
+ manager.set_settings("pi", settings)
+ pool._settings_manager = manager
+ pool.apply_settings_overrides(manager)
+
+ with (
+ patch("omlx.engine_pool.find_splash_binary") as launcher,
+ patch("omlx.engine_pool.prepare_prefill_helper") as helper,
+ patch("omlx.engine_pool.BatchedEngine") as batched,
+ patch("omlx.engine_pool.VLMBatchedEngine") as vlm,
+ pytest.raises(ModelLoadingError, match=reason),
+ ):
+ await pool.get_engine("pi")
+ assert pool.get_entry("pi").engine is None
+ for unused in (launcher, helper, batched, vlm):
+ unused.assert_not_called()
+
+
+@pytest.mark.asyncio
+async def test_lfm3_adapter_stays_on_vlm_when_text_engine_is_requested(
+ lora_pool, small_mock_model_dir
+):
+ pool, _ = lora_pool
+ (small_mock_model_dir / "model-a" / "config.json").write_text(
+ '{"model_type": "lfm3"}'
+ )
+ pool.discover_models(str(small_mock_model_dir))
+ vlm = MagicMock(start=AsyncMock(), stop=AsyncMock())
+ with (
+ patch("omlx.engine_pool.VLMBatchedEngine", return_value=vlm) as vlm_cls,
+ patch("omlx.engine_pool.BatchedEngine") as batched_cls,
+ ):
+ assert await pool.get_engine("pi", force_lm=True) is vlm
+ assert vlm_cls.call_args.kwargs["lora"] is pool.get_entry("pi").adapter
+ batched_cls.assert_not_called()
+
+
class TestEnginePoolInit:
"""Tests for EnginePool initialization."""
diff --git a/tests/test_hf_downloader.py b/tests/test_hf_downloader.py
index 306bf7e17f..b3d7530152 100644
--- a/tests/test_hf_downloader.py
+++ b/tests/test_hf_downloader.py
@@ -2959,7 +2959,8 @@ async def test_returns_model_info(self):
assert result["files"][0]["name"] == "model.safetensors"
assert "text-generation" in result["tags"]
assert result["model_card"] == "" # No README available
- assert result["is_adapter"] is False
+ assert result["adapter"] is None
+ assert "is_" + "adapter" not in result
@pytest.mark.asyncio
async def test_u32_size_uses_sibling_blobs_not_histogram(self):
@@ -2997,36 +2998,99 @@ async def test_u32_size_uses_sibling_blobs_not_histogram(self):
assert result["params"] == 25_805_936_206
@pytest.mark.asyncio
- async def test_detects_lora_adapter(self):
- """Verify is_adapter=True when adapter_config.json is in file list."""
- mock_info = MagicMock()
- mock_info.id = "user/lora-adapter"
- mock_info.downloads = 50
- mock_info.likes = 5
- mock_info.tags = ["lora", "mlx"]
- mock_info.pipeline_tag = "text-generation"
- mock_info.created_at = None
- mock_info.last_modified = None
- mock_info.safetensors = None
- mock_info.card_data = None
-
- siblings = []
- for name in ["adapter_config.json", "adapters.safetensors", "config.json"]:
- s = MagicMock()
- s.rfilename = name
- s.size = 1000
- siblings.append(s)
- mock_info.siblings = siblings
+ @pytest.mark.parametrize(
+ ("case", "reason"),
+ [
+ ("valid", None),
+ ("dora", "use_dora"),
+ ("fetch", "Could not read adapter_config.json: proxy unavailable"),
+ ("listed_oversize", "larger than 1 MiB"),
+ ("downloaded_oversize", "larger than 1 MiB"),
+ ("splash", "This is a Splash package"),
+ (
+ "bin_only",
+ "oMLX never loads pickled weights. Re-save it as "
+ "adapter_model.safetensors.",
+ ),
+ (
+ "missing_weights",
+ "adapter_model.safetensors is missing. Choose a repo that includes it.",
+ ),
+ ],
+ )
+ async def test_adapter_config_metadata(self, tmp_path, case, reason):
+ config_path = tmp_path / "adapter_config.json"
+ config = {
+ "peft_type": "LORA",
+ "base_model_name_or_path": "LiquidAI/LFM3-1.7B",
+ "r": 32,
+ "lora_alpha": 64,
+ "use_dora": case == "dora",
+ }
+ config_path.write_text(json.dumps(config), encoding="utf-8")
+ listed_size = config_path.stat().st_size
+ if case == "listed_oversize":
+ listed_size = 1024**2 + 1
+ if case == "downloaded_oversize":
+ with config_path.open("ab") as handle:
+ handle.write(b" " * (1024**2))
+
+ weight_file = {
+ "bin_only": "adapter_model.bin",
+ "missing_weights": "model.safetensors",
+ }.get(case, "adapter_model.safetensors")
+
+ model = SimpleNamespace(
+ id="harness-hub/LFM3-1.7B-pi",
+ downloads=50,
+ likes=5,
+ tags=["lora", "mlx"],
+ pipeline_tag="text-generation",
+ created_at=None,
+ last_modified=None,
+ safetensors=None,
+ card_data=None,
+ library_name="splash" if case == "splash" else "peft",
+ siblings=[
+ SimpleNamespace(rfilename=config_path.name, size=listed_size),
+ SimpleNamespace(rfilename=weight_file, size=1000),
+ ],
+ )
- with patch("omlx.admin.hf_downloader.HfApi") as mock_api_cls, \
- patch("omlx.admin.hf_downloader.hf_hub_download", side_effect=Exception("no readme")):
- mock_api = MagicMock()
- mock_api.model_info.return_value = mock_info
- mock_api_cls.return_value = mock_api
+ def download(*, filename, **kwargs):
+ if filename == "README.md":
+ raise FileNotFoundError(filename)
+ assert filename == config_path.name
+ if case == "fetch":
+ raise hub_httpx.ProxyError("proxy unavailable")
+ return str(config_path)
- result = await HFDownloader.get_model_info("user/lora-adapter")
+ with (
+ patch("omlx.admin.hf_downloader.HfApi") as mock_api_cls,
+ patch(
+ "omlx.admin.hf_downloader.hf_hub_download", side_effect=download
+ ) as mock_download,
+ ):
+ mock_api_cls.return_value.model_info.return_value = model
+ result = await HFDownloader.get_model_info(model.id)
+
+ if reason is None:
+ assert result["adapter"] == {
+ "base_repo_id": "LiquidAI/LFM3-1.7B",
+ "rank": 32,
+ }
+ assert result["unsupported_reason"] is None
+ assert [
+ f["name"] for f in result["files"] if f["required"] and f["preselected"]
+ ] == ["adapter_config.json", "adapter_model.safetensors"]
+ else:
+ assert result["adapter"] is None
+ assert reason in result["unsupported_reason"]
- assert result["is_adapter"] is True
+ if case in {"listed_oversize", "splash", "bin_only", "missing_weights"}:
+ assert [
+ call.kwargs["filename"] for call in mock_download.call_args_list
+ ] == ["README.md"]
@pytest.mark.asyncio
async def test_returns_model_card(self, tmp_path):
diff --git a/tests/test_lora_adapter.py b/tests/test_lora_adapter.py
new file mode 100644
index 0000000000..ca836a3af5
--- /dev/null
+++ b/tests/test_lora_adapter.py
@@ -0,0 +1,2032 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Tests for PEFT LoRA adapter parsing, base resolution, discovery and attach."""
+
+import json
+import math
+import os
+import re
+import struct
+import subprocess
+import sys
+from collections.abc import Callable
+from contextlib import contextmanager
+from dataclasses import dataclass, replace
+from pathlib import Path
+
+import mlx.core as mx
+import mlx.nn as nn
+import numpy as np
+import pytest
+from mlx.utils import tree_flatten
+
+from omlx.exceptions import (
+ AdapterError,
+ AdapterShapeError,
+ ModelError,
+ OMLXError,
+ UnsupportedAdapterError,
+)
+from omlx.lora_adapter import (
+ AdapterSource,
+ BaseCandidate,
+ BaseRef,
+ IssueKind,
+ LoraConfig,
+ LoraLinear,
+ LoraModule,
+ attach_lora,
+ base_candidates,
+ bind_adapter,
+ derive_entry,
+ discover_adapters,
+ lora_revision_of,
+ match_bases,
+ parse_adapter,
+ parse_adapter_config,
+ resolve_adapters,
+)
+from omlx.model_discovery import DiscoveredModel
+
+CONFIG = "adapter_config.json"
+WEIGHTS = "adapter_model.safetensors"
+QWEN = "Qwen/Qwen3.8-27B"
+REPO_ROOT = Path(__file__).resolve().parents[1]
+
+
+@contextmanager
+def malformed():
+ """Expect an AdapterError that is not the valid-but-unsupported subclass."""
+ with pytest.raises(AdapterError) as caught:
+ yield caught
+ assert not isinstance(caught.value, UnsupportedAdapterError)
+
+
+def config_bytes(drop=(), **fields):
+ document = {
+ "peft_type": "LORA",
+ "base_model_name_or_path": QWEN,
+ "r": 32,
+ "lora_alpha": 64,
+ **fields,
+ }
+ for key in drop:
+ del document[key]
+ return json.dumps(document).encode()
+
+
+ITEMSIZE = {"F32": 4, "BF16": 2, "F16": 2}
+HAND_MODULE = "model.layers.0.mlp.gate_proj"
+
+
+def lora_tensors(hf_path, rank, in_features, out_features, dtype="F32"):
+ """Tensor name -> (dtype, shape) for one module's lora_A and lora_B."""
+ prefix = f"base_model.model.{hf_path}"
+ return {
+ f"{prefix}.lora_A.weight": (dtype, (rank, in_features)),
+ f"{prefix}.lora_B.weight": (dtype, (out_features, rank)),
+ }
+
+
+def raw_header(tensors):
+ """A safetensors header with contiguous offsets, and the payload size it needs."""
+ header, offset = {}, 0
+ for name, (dtype, shape) in tensors.items():
+ size = ITEMSIZE[dtype] * math.prod(shape)
+ header[name] = {
+ "dtype": dtype,
+ "shape": list(shape),
+ "data_offsets": [offset, offset + size],
+ }
+ offset += size
+ return header, offset
+
+
+def write_raw_safetensors(path, header, payload=0):
+ """Write a safetensors file by hand. ``header`` is a dict or raw header bytes."""
+ blob = header if isinstance(header, bytes) else json.dumps(header).encode()
+ path.write_bytes(struct.pack("eoi", b, a)
+ for routes, sorted_indices in (
+ (np.array([[2, 0], [1, 2]]), False),
+ (np.array([0, 1, 2, 2]), True),
+ ):
+ x = rng.standard_normal((*routes.shape, 1, width)).astype(np.float32)
+ actual = switch.down_proj(mx.array(x), mx.array(routes), sorted_indices)
+ expected = x @ np.swapaxes(merged[routes], -1, -2)
+ np.testing.assert_allclose(np.array(actual), expected, atol=2e-5, rtol=2e-5)
+ x = mx.array(rng.standard_normal((1, 33, outputs)).astype(np.float32))
+ if layout == "qwen":
+ from omlx.patches.qwen35_moe_routed_decode import _build_plan
+
+ model.eval()
+ assert _build_plan(layer.mlp) is None
+ forward, args = layer.mlp, (x,)
+ else:
+ routes = mx.broadcast_to(mx.array([2, 0]), (1, 33, 2))
+ scores = mx.broadcast_to(mx.array([0.75, 0.25]), routes.shape)
+ forward, args = layer.experts, (x, routes, scores)
+ adapted = np.array(forward(*args))
+ switch.down_proj = original
+ baseline = np.array(forward(*args))
+ assert np.max(np.abs(adapted - baseline)) > 1e-4
+
+
+@pytest.mark.parametrize(
+ ("case", "message"),
+ [
+ ("duplicate", "duplicate expert"),
+ ("missing", "needs lora_A and lora_B"),
+ ("rank", "matching expert counts"),
+ ("experts", "has 4 experts, but"),
+ ],
+)
+def test_invalid_routed_adapter_is_rejected(
+ write_lora_adapter, tmp_path, case, message
+):
+ from mlx_lm.models.switch_layers import SwitchGLU
+
+ stem = "model.layers.0.mlp.experts"
+ target = stem + ".down_proj"
+ path = write_lora_adapter(
+ tmp_path / "routed",
+ rank=2,
+ modules={"model.layers.0.mlp.dense": (8, 8)},
+ config={
+ "target_parameters": [target, target] if case == "duplicate" else [target]
+ },
+ tensors=(
+ {
+ f"base_model.model.{stem}.lora_A.weight": np.ones((8, 64), np.float32),
+ f"base_model.model.{stem}.lora_B.weight": np.ones(
+ (32, 7 if case == "rank" else 8), np.float32
+ ),
+ }
+ if case != "missing"
+ else None
+ ),
+ )
+ if case != "experts":
+ with pytest.raises(AdapterError, match=message):
+ parse_adapter(path)
+ return
+ model, layer = nn.Module(), nn.Module()
+ model.layers = [layer]
+ layer.mlp = nn.Module()
+ dense = layer.mlp.dense = nn.Linear(8, 8)
+ switch = layer.mlp.switch_mlp = SwitchGLU(32, 64, 3)
+ down = switch.down_proj
+ binding = bind_adapter(parse_adapter(path), BaseRef("base", tmp_path))
+ with pytest.raises(AdapterShapeError, match=message):
+ attach_lora(model, binding)
+ assert layer.mlp.dense is dense
+ assert switch.down_proj is down
+ assert lora_revision_of(model) is None
+
+
+def effective_parts(linear, quant):
+ """The weight a Linear or QuantizedLinear applies, and its bias, in float32."""
+ if quant is None:
+ weight = linear.weight
+ else:
+ mode, bits, group_size = quant
+ weight = mx.dequantize(
+ linear.weight,
+ linear.scales,
+ linear.get("biases"),
+ group_size=group_size,
+ bits=bits,
+ mode=mode,
+ )
+ bias = np.array(linear.bias.astype(mx.float32)) if "bias" in linear else None
+ return np.array(weight.astype(mx.float32)), bias
+
+
+def folded_output(x, weight, bias, lora_a, lora_b, scale):
+ """x through W + scale * B @ A, the merged-weight form of the adapter."""
+ merged = weight.astype(np.float64) + scale * (
+ lora_b.astype(np.float64) @ lora_a.astype(np.float64)
+ )
+ out = x.astype(np.float64) @ merged.T
+ return out if bias is None else out + bias
+
+
+def module_types(model):
+ return {name: type(module) for name, module in model.named_modules()}
+
+
+class TestAttachLora:
+ @pytest.fixture(autouse=True)
+ def seed(self):
+ mx.random.seed(7)
+
+ @pytest.mark.parametrize(
+ ("layout_name", "quant"),
+ [
+ ("llm", None),
+ ("vlm", None),
+ ("flat", None),
+ ("llm", ("affine", 4, 32)),
+ ("vlm", ("affine", 4, 32)),
+ ("llm", ("affine", 8, 64)),
+ ("llm", ("mxfp4", 4, 32)),
+ ],
+ ids=["llm", "vlm", "flat", "llm-4bit", "vlm-4bit", "llm-8bit", "llm-mxfp4"],
+ )
+ def test_wrapped_modules_match_the_folded_weights(
+ self, write_lora_adapter, tmp_path, layout_name, quant
+ ):
+ layout = LAYOUTS[layout_name]
+ model = layout.build()
+ if quant is not None:
+ mode, bits, group_size = quant
+ nn.quantize(model, group_size=group_size, bits=bits, mode=mode)
+ mx.eval(model.parameters())
+ adapter, factors = write_adapter(
+ write_lora_adapter, tmp_path / "ad", layout.hf_prefix
+ )
+ layers = layout.layers(model)
+ rng = np.random.default_rng(11)
+ cases = {}
+ for (layer, name), (lora_a, lora_b) in factors.items():
+ weight, bias = effective_parts(getattr(layers[layer].mlp, name), quant)
+ x = rng.standard_normal((3, TARGETS[name][0])).astype(np.float32)
+ without_adapter = x @ weight.T + (0 if bias is None else bias)
+ expected = folded_output(x, weight, bias, lora_a, lora_b, PLAIN_SCALE)
+ cases[layer, name] = (x, without_adapter, expected)
+
+ assert attach_lora(model, bind(adapter)) == len(factors)
+
+ for (layer, name), (x, without_adapter, expected) in cases.items():
+ wrapped = getattr(layers[layer].mlp, name)
+ assert isinstance(wrapped, LoraLinear)
+ assert np.abs(expected - without_adapter).max() > 0.1
+ np.testing.assert_allclose(
+ np.array(wrapped(mx.array(x))), expected, rtol=1e-4, atol=1e-4
+ )
+
+ @pytest.mark.parametrize("layout_name", list(LAYOUTS))
+ def test_model_output_matches_a_model_with_folded_weights(
+ self, write_lora_adapter, tmp_path, layout_name
+ ):
+ layout = LAYOUTS[layout_name]
+ model = layout.build()
+ mx.eval(model.parameters())
+ reference = layout.build()
+ reference.update(model.parameters())
+ adapter, factors = write_adapter(
+ write_lora_adapter, tmp_path / "ad", layout.hf_prefix
+ )
+ for (layer, name), (lora_a, lora_b) in factors.items():
+ linear = getattr(layout.layers(reference)[layer].mlp, name)
+ delta = mx.array(lora_b) @ mx.array(lora_a)
+ linear.weight = linear.weight + PLAIN_SCALE * delta
+ x = mx.random.normal((2, 5, DIMS))
+
+ attach_lora(model, bind(adapter))
+
+ np.testing.assert_allclose(
+ np.array(model(x)), np.array(reference(x)), rtol=1e-4, atol=1e-4
+ )
+
+ def test_rslora_scales_by_alpha_over_sqrt_rank(self, write_lora_adapter, tmp_path):
+ layout = LAYOUTS["llm"]
+ model = layout.build()
+ mx.eval(model.parameters())
+ adapter, factors = write_adapter(
+ write_lora_adapter,
+ tmp_path / "ad",
+ layout.hf_prefix,
+ config={"use_rslora": True},
+ )
+ linear = layout.layers(model)[0].mlp.gate_proj
+ weight, bias = effective_parts(linear, None)
+ lora_a, lora_b = factors[0, "gate_proj"]
+ x = np.random.default_rng(3).standard_normal((3, DIMS)).astype(np.float32)
+ expected = folded_output(x, weight, bias, lora_a, lora_b, RSLORA_SCALE)
+ plain = folded_output(x, weight, bias, lora_a, lora_b, PLAIN_SCALE)
+
+ attach_lora(model, bind(adapter))
+
+ assert np.abs(expected - plain).max() > 0.1
+ np.testing.assert_allclose(
+ np.array(layout.layers(model)[0].mlp.gate_proj(mx.array(x))),
+ expected,
+ rtol=1e-4,
+ atol=1e-4,
+ )
+
+ def test_output_dtype_follows_the_input_dtype(self, write_lora_adapter, tmp_path):
+ layout = LAYOUTS["llm"]
+ model = layout.build()
+ model.set_dtype(mx.bfloat16)
+ mx.eval(model.parameters())
+ adapter, factors = write_adapter(
+ write_lora_adapter, tmp_path / "ad", layout.hf_prefix
+ )
+ weight, bias = effective_parts(layout.layers(model)[0].mlp.gate_proj, None)
+ lora_a, lora_b = factors[0, "gate_proj"]
+ x = mx.array(np.random.default_rng(3).standard_normal((3, DIMS))).astype(
+ mx.bfloat16
+ )
+ expected = folded_output(
+ np.array(x.astype(mx.float32)), weight, bias, lora_a, lora_b, PLAIN_SCALE
+ )
+
+ attach_lora(model, bind(adapter))
+ out = layout.layers(model)[0].mlp.gate_proj(x)
+
+ assert out.dtype == mx.bfloat16
+ np.testing.assert_allclose(
+ np.array(out.astype(mx.float32)), expected, rtol=5e-2, atol=5e-2
+ )
+
+ @pytest.mark.parametrize("dtype", [mx.float32, mx.bfloat16, mx.float16])
+ def test_adapter_weights_keep_the_dtype_they_shipped_in(
+ self, write_lora_adapter, tmp_path, dtype
+ ):
+ layout = LAYOUTS["llm"]
+ model = layout.build()
+ adapter, _ = write_adapter(
+ write_lora_adapter, tmp_path / "ad", layout.hf_prefix, dtype=dtype
+ )
+
+ attach_lora(model, bind(adapter))
+
+ wrapped = layout.layers(model)[0].mlp.gate_proj
+ assert (wrapped.lora_a.dtype, wrapped.lora_b.dtype) == (dtype, dtype)
+
+ def test_the_revision_appears_with_the_adapter(self, write_lora_adapter, tmp_path):
+ layout = LAYOUTS["llm"]
+ model = layout.build()
+ adapter, factors = write_adapter(
+ write_lora_adapter, tmp_path / "ad", layout.hf_prefix
+ )
+ binding = bind(adapter)
+ assert lora_revision_of(model) is None
+
+ wrapped = attach_lora(model, binding)
+
+ assert wrapped == len(factors)
+ assert lora_revision_of(model) == binding.cache_revision
+ assert lora_revision_of(object()) is None
+
+ def test_only_the_language_model_is_wrapped(self, write_lora_adapter, tmp_path):
+ layout = LAYOUTS["vlm"]
+ model = layout.build()
+ adapter, factors = write_adapter(
+ write_lora_adapter, tmp_path / "ad", layout.hf_prefix
+ )
+
+ assert attach_lora(model, bind(adapter)) == len(factors)
+
+ wrapped = [
+ m for m in model.language_model.modules() if isinstance(m, LoraLinear)
+ ]
+ assert len(wrapped) == len(factors)
+ assert not any(isinstance(m, LoraLinear) for m in model.vision_tower.modules())
+
+ def test_wrapped_parameters_are_arrays_only(self, write_lora_adapter, tmp_path):
+ layout = LAYOUTS["llm"]
+ model = layout.build()
+ adapter, _ = write_adapter(
+ write_lora_adapter, tmp_path / "ad", layout.hf_prefix
+ )
+
+ attach_lora(model, bind(adapter))
+
+ assert all(isinstance(v, mx.array) for _, v in tree_flatten(model.parameters()))
+ mx.eval(model.parameters())
+
+
+class TestLoraLinear:
+ def test_computes_the_low_rank_update_in_the_documented_orientation(self):
+ rng = np.random.default_rng(1)
+ lora_a = rng.standard_normal((8, 4)).astype(np.float32)
+ lora_b = rng.standard_normal((4, 16)).astype(np.float32)
+ x = rng.standard_normal((3, 8)).astype(np.float32)
+ linear = nn.Linear(8, 16, bias=False)
+ wrapper = LoraLinear(linear, mx.array(lora_a), mx.array(lora_b), 0.5, "lora-x")
+
+ expected = x @ np.array(linear.weight).T + 0.5 * (x @ lora_a @ lora_b)
+
+ np.testing.assert_allclose(
+ np.array(wrapper(mx.array(x))), expected, rtol=1e-4, atol=1e-4
+ )
+
+ def test_scale_and_revision_are_not_parameters(self):
+ wrapper = LoraLinear(
+ nn.Linear(8, 16), mx.zeros((8, 4)), mx.zeros((4, 16)), 2.0, "lora-x"
+ )
+
+ names = {name for name, _ in tree_flatten(wrapper.parameters())}
+
+ assert names == {"linear.weight", "linear.bias", "lora_a", "lora_b"}
+ assert (wrapper.scale, wrapper.revision) == (2.0, "lora-x")
+
+
+VALID_MODULES = {
+ "model.layers.0.mlp.down_proj": (HIDDEN, DIMS),
+ "model.layers.0.mlp.gate_proj": (DIMS, HIDDEN),
+ "model.layers.1.mlp.down_proj": (HIDDEN, DIMS),
+}
+
+
+def bind_claiming(adapter, modules):
+ """A binding whose source lists ``modules``, whatever the weights file holds."""
+ return bind_adapter(
+ replace(parse_adapter(adapter), modules=tuple(modules)),
+ BaseRef("tiny", Path("/models/tiny")),
+ )
+
+
+def assert_refused(model, binding):
+ """attach_lora must raise AdapterShapeError and leave the model as it was."""
+ x = mx.random.normal((2, DIMS))
+ types_before = module_types(model)
+ output_before = np.array(model(x))
+
+ with pytest.raises(AdapterShapeError) as caught:
+ attach_lora(model, binding)
+
+ assert caught.value.details["adapter"] == str(binding.source.path)
+ assert lora_revision_of(model) is None
+ assert not any(isinstance(m, LoraLinear) for m in model.modules())
+ assert module_types(model) == types_before
+ np.testing.assert_array_equal(np.array(model(x)), output_before)
+ return caught.value
+
+
+def assert_rejected(model, binding, offender):
+ """assert_refused, and the error names ``offender``, the module that fails.
+
+ ``offender`` sorts last in the adapter, so an implementation that installed
+ wrappers while it validated would leave some behind. Returns the error.
+ """
+ assert binding.source.modules[-1].hf_path == offender
+ error = assert_refused(model, binding)
+ assert offender in error.message
+ return error
+
+
+class TestAttachLoraRejections:
+ @pytest.fixture(autouse=True)
+ def seed(self):
+ mx.random.seed(7)
+
+ def adapter(self, write_lora_adapter, tmp_path, extra):
+ modules = {**VALID_MODULES, **extra}
+ return write_lora_adapter(
+ tmp_path / "ad", rank=RANK, alpha=ALPHA, modules=modules
+ )
+
+ def test_feature_size_mismatch(self, write_lora_adapter, tmp_path):
+ bad = "model.layers.1.mlp.gate_proj"
+ trained_inputs = DIMS + 8
+ adapter = self.adapter(
+ write_lora_adapter, tmp_path, {bad: (trained_inputs, HIDDEN)}
+ )
+
+ error = assert_rejected(LlmModel(), bind(adapter), bad)
+
+ assert str(trained_inputs) in error.message
+ assert str(DIMS) in error.message
+ assert "Reload" not in error.message
+
+ def test_unresolved_target(self, write_lora_adapter, tmp_path):
+ bad = "model.layers.5.mlp.gate_proj"
+ adapter = self.adapter(write_lora_adapter, tmp_path, {bad: (DIMS, HIDDEN)})
+
+ assert_rejected(LlmModel(), bind(adapter), bad)
+
+ @pytest.mark.parametrize(
+ "bad",
+ [
+ "model.visual.blocks.0.attn.qkv",
+ "model.vision_tower.encoder.layers.0.mlp.gate_proj",
+ "model.mtp.layers.0.mlp.gate_proj",
+ ],
+ )
+ def test_target_outside_language_layers(self, write_lora_adapter, tmp_path, bad):
+ adapter = write_lora_adapter(
+ tmp_path / "ad",
+ rank=RANK,
+ alpha=ALPHA,
+ modules={
+ "model.layers.0.mlp.down_proj": (HIDDEN, DIMS),
+ bad: (DIMS, HIDDEN),
+ },
+ )
+
+ assert_rejected(LlmModel(), bind(adapter), bad)
+
+ def test_a_module_that_is_not_a_linear(self, write_lora_adapter, tmp_path):
+ bad = "model.layers.1.mlp.gate_proj"
+ model = LlmModel()
+ model.model.layers[1].mlp.gate_proj = OpaqueLinear(
+ nn.Linear(DIMS, HIDDEN, bias=False)
+ )
+ adapter = self.adapter(write_lora_adapter, tmp_path, {bad: (DIMS, HIDDEN)})
+
+ assert_rejected(model, bind(adapter), bad)
+
+ def test_two_adapter_modules_for_one_target(self, write_lora_adapter, tmp_path):
+ modules = {
+ "model.language_model.layers.0.mlp.gate_proj": (DIMS, HIDDEN),
+ "model.layers.0.mlp.down_proj": (HIDDEN, DIMS),
+ "model.layers.0.mlp.gate_proj": (DIMS, HIDDEN),
+ }
+ adapter = write_lora_adapter(
+ tmp_path / "ad", rank=RANK, alpha=ALPHA, modules=modules
+ )
+
+ assert_rejected(LlmModel(), bind(adapter), "model.layers.0.mlp.gate_proj")
+
+ def test_a_target_that_resolves_two_ways(self, write_lora_adapter, tmp_path):
+ bad = "model.layers.0.mlp.gate_proj"
+ adapter = write_lora_adapter(
+ tmp_path / "ad", rank=RANK, alpha=ALPHA, modules={bad: (DIMS, HIDDEN)}
+ )
+
+ assert_rejected(TwoRoots(), bind(adapter), bad)
+
+ def test_a_module_the_weights_do_not_hold(self, write_lora_adapter, tmp_path):
+ ghost = "model.layers.1.mlp.gate_proj"
+ adapter = self.adapter(write_lora_adapter, tmp_path, {})
+ listed = [*parse_adapter(adapter).modules, LoraModule(ghost, DIMS, HIDDEN)]
+
+ error = assert_rejected(LlmModel(), bind_claiming(adapter, listed), ghost)
+
+ assert "Reload" in error.message
+
+ @pytest.mark.parametrize("half", ["A", "B"])
+ def test_a_tensor_that_disagrees_with_the_listed_shape(
+ self, write_lora_adapter, tmp_path, half
+ ):
+ last = "model.layers.1.mlp.down_proj"
+ in_features, out_features = VALID_MODULES[last]
+ reshaped = {"A": (RANK, in_features + 8), "B": (out_features + 8, RANK)}[half]
+ adapter = write_lora_adapter(
+ tmp_path / "ad",
+ rank=RANK,
+ alpha=ALPHA,
+ modules=VALID_MODULES,
+ tensors={
+ f"base_model.model.{last}.lora_{half}.weight": np.zeros(
+ reshaped, np.float32
+ )
+ },
+ )
+ listed = [
+ LoraModule(module.hf_path, *VALID_MODULES[module.hf_path])
+ for module in parse_adapter(adapter).modules
+ ]
+
+ error = assert_rejected(LlmModel(), bind_claiming(adapter, listed), last)
+
+ assert "Reload" in error.message
+
+ @pytest.mark.parametrize(
+ ("first_layers", "second_layers"),
+ [((0, 1), (0, 1)), ((0,), (1,))],
+ ids=["same-targets", "other-targets"],
+ )
+ def test_a_second_adapter_is_rejected_and_the_first_stays(
+ self, write_lora_adapter, tmp_path, first_layers, second_layers
+ ):
+ layout = LAYOUTS["llm"]
+ model = layout.build()
+ first, _ = write_adapter(
+ write_lora_adapter,
+ tmp_path / "first",
+ layout.hf_prefix,
+ layers=first_layers,
+ )
+ second, _ = write_adapter(
+ write_lora_adapter,
+ tmp_path / "second",
+ layout.hf_prefix,
+ config={"lora_alpha": 16.0},
+ layers=second_layers,
+ )
+ first_binding = bind(first)
+ attach_lora(model, first_binding)
+ x = mx.random.normal((2, DIMS))
+ output_before = np.array(model(x))
+
+ with pytest.raises(AdapterShapeError) as caught:
+ attach_lora(model, bind(second))
+
+ assert caught.value.details["adapter"] == str(second)
+ assert lora_revision_of(model) == first_binding.cache_revision
+ np.testing.assert_array_equal(np.array(model(x)), output_before)
+ wrappers = [m for m in model.modules() if isinstance(m, LoraLinear)]
+ assert len(wrappers) == len(TARGETS) * len(first_layers)
+ assert not any(isinstance(w.linear, LoraLinear) for w in wrappers)
+
+
+def retrain_in_place(adapter, write_lora_adapter):
+ """New values of the same shapes. Returns {(layer, name): (A, B)}."""
+ _, factors = write_adapter(
+ write_lora_adapter, adapter, LAYOUTS["llm"].hf_prefix, seed=1000
+ )
+ bump_mtime(adapter)
+ return factors
+
+
+def overwrite_the_weights_with_garbage(adapter, write_lora_adapter):
+ (adapter / WEIGHTS).write_bytes(b"not safetensors")
+
+
+def delete_the_config(adapter, write_lora_adapter):
+ (adapter / CONFIG).unlink()
+
+
+def delete_the_weights(adapter, write_lora_adapter):
+ (adapter / WEIGHTS).unlink()
+
+
+def edit_the_config(adapter, write_lora_adapter):
+ edit_alpha_keeping_the_length(adapter)
+
+
+CHANGES_AFTER_DISCOVERY = {
+ "retrained-weights": retrain_in_place,
+ "config-edited": edit_the_config,
+ "garbage-weights": overwrite_the_weights_with_garbage,
+ "config-deleted": delete_the_config,
+ "weights-deleted": delete_the_weights,
+}
+
+
+class TestAttachLoraAfterTheFilesChanged:
+ """The binding came from files that have since changed on disk."""
+
+ @pytest.fixture(autouse=True)
+ def seed(self):
+ mx.random.seed(7)
+
+ @pytest.mark.parametrize(
+ "change",
+ list(CHANGES_AFTER_DISCOVERY.values()),
+ ids=list(CHANGES_AFTER_DISCOVERY),
+ )
+ def test_the_model_is_left_unmodified(self, write_lora_adapter, tmp_path, change):
+ layout = LAYOUTS["llm"]
+ adapter, _ = write_adapter(
+ write_lora_adapter, tmp_path / "ad", layout.hf_prefix
+ )
+ binding = bind(adapter)
+ change(adapter, write_lora_adapter)
+
+ error = assert_refused(layout.build(), binding)
+
+ assert "Reload the model list" in error.message
+
+ def test_a_reload_attaches_the_replaced_weights(self, write_lora_adapter, tmp_path):
+ layout = LAYOUTS["llm"]
+ adapter, before = write_adapter(
+ write_lora_adapter, tmp_path / "ad", layout.hf_prefix
+ )
+ stale = bind(adapter)
+ after = retrain_in_place(adapter, write_lora_adapter)
+ refreshed = bind(adapter)
+ assert refreshed.source.modules == stale.source.modules
+ assert refreshed.source.weight_bytes == stale.source.weight_bytes
+ model = layout.build()
+ mx.eval(model.parameters())
+ linear = layout.layers(model)[0].mlp.gate_proj
+ weight, bias = effective_parts(linear, None)
+ x = np.random.default_rng(3).standard_normal((3, DIMS)).astype(np.float32)
+ old_a, old_b = before[0, "gate_proj"]
+ new_a, new_b = after[0, "gate_proj"]
+ from_old = folded_output(x, weight, bias, old_a, old_b, PLAIN_SCALE)
+ expected = folded_output(x, weight, bias, new_a, new_b, PLAIN_SCALE)
+
+ attach_lora(model, refreshed)
+
+ assert np.abs(expected - from_old).max() > 0.1
+ np.testing.assert_allclose(
+ np.array(layout.layers(model)[0].mlp.gate_proj(mx.array(x))),
+ expected,
+ rtol=1e-4,
+ atol=1e-4,
+ )
+ assert lora_revision_of(model) == refreshed.cache_revision
+ assert refreshed.cache_revision != stale.cache_revision
+
+
+@pytest.mark.parametrize(
+ ("target", "forbidden"),
+ [
+ ("omlx.model_discovery", ("omlx.lora_adapter",)),
+ (
+ "omlx.lora_adapter",
+ ("omlx.model_discovery", "mlx_vlm.trainer", "mlx_lm.tuner"),
+ ),
+ ],
+)
+def test_import_boundaries(target, forbidden):
+ code = (
+ "import sys\n"
+ f"import {target}\n"
+ f"loaded = sorted(n for n in sys.modules if n.startswith({forbidden!r}))\n"
+ "print(loaded)\n"
+ "sys.exit(bool(loaded))\n"
+ )
+
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True,
+ text=True,
+ cwd=REPO_ROOT,
+ timeout=120,
+ )
+
+ assert result.returncode == 0, result.stdout + result.stderr
diff --git a/tests/test_model_discovery.py b/tests/test_model_discovery.py
index 40cca59256..afcfae8763 100644
--- a/tests/test_model_discovery.py
+++ b/tests/test_model_discovery.py
@@ -1822,6 +1822,22 @@ def test_format_petabytes(self):
class TestAdapterDetection:
"""Tests for LoRA/PEFT adapter detection."""
+ def test_adapter_collector_preserves_discovery_order(
+ self, tmp_path, write_lora_adapter
+ ):
+ first, second = tmp_path / "first", tmp_path / "second"
+ flat = write_lora_adapter(first / "a-flat")
+ nested = write_lora_adapter(first / "b-org" / "nested")
+ duplicate = write_lora_adapter(second / "a-flat")
+ found = []
+
+ assert discover_models(first, adapter_dirs=found) == {}
+ assert found == [flat, nested]
+ found.clear()
+ assert discover_models_from_dirs([first, second], adapter_dirs=found) == {}
+ assert found == [flat, nested, duplicate]
+ assert discover_models_from_dirs([first, second]) == {}
+
def test_adapter_dir_detected(self, tmp_path):
"""Directory with adapter_config.json is detected as adapter."""
(tmp_path / "adapter_config.json").write_text("{}")
diff --git a/tests/test_model_settings.py b/tests/test_model_settings.py
index c7d06c4d97..6897c22008 100644
--- a/tests/test_model_settings.py
+++ b/tests/test_model_settings.py
@@ -20,6 +20,43 @@
)
+def test_adapter_base_overrides_round_trip_and_clear(tmp_path):
+ manager = ModelSettingsManager(tmp_path)
+ manager.set_adapter_base("pi", "base")
+ copy = manager.get_adapter_bases()
+ copy.clear()
+ assert manager.get_adapter_bases() == {"pi": "base"}
+ assert json.loads((tmp_path / "adapter_bases.json").read_text()) == {
+ "version": 1,
+ "adapter_bases": {"pi": "base"},
+ }
+ assert not manager.has_settings("pi")
+
+ reopened = ModelSettingsManager(tmp_path)
+ assert reopened.get_adapter_bases() == {"pi": "base"}
+ reopened.set_adapter_base("pi", None)
+ assert ModelSettingsManager(tmp_path).get_adapter_bases() == {}
+
+
+def test_delete_settings_preserves_overrides_pointing_at_deleted_base(tmp_path):
+ manager = ModelSettingsManager(tmp_path)
+ manager.set_adapter_base("pi", "base")
+ manager.set_adapter_base("hermes", "pi")
+
+ assert not manager.delete_settings("base")
+ assert manager.get_adapter_bases() == {"pi": "base", "hermes": "pi"}
+ assert manager.delete_settings("pi")
+ assert not manager.delete_settings("pi")
+ assert ModelSettingsManager(tmp_path).get_adapter_bases() == {"hermes": "pi"}
+
+
+def test_unreadable_adapter_bases_file_starts_empty(tmp_path, caplog):
+ (tmp_path / "adapter_bases.json").write_text("{")
+
+ assert ModelSettingsManager(tmp_path).get_adapter_bases() == {}
+ assert "Failed to load adapter bases file" in caplog.text
+
+
class TestModelSettings:
"""Tests for ModelSettings dataclass."""
diff --git a/tests/test_paged_ssd_cache.py b/tests/test_paged_ssd_cache.py
index d7055190ea..75af76441a 100644
--- a/tests/test_paged_ssd_cache.py
+++ b/tests/test_paged_ssd_cache.py
@@ -4612,6 +4612,39 @@ def test_revision_follows_the_live_model_modules(self):
)
assert numerics_revision_for_model(nn.Linear(4, 4)) is None
+ def test_revision_tracks_attached_lora(self, tmp_path, write_lora_adapter):
+ from dataclasses import replace
+
+ nn = pytest.importorskip("mlx.nn")
+ from omlx.lora_adapter import BaseRef, attach_lora, bind_adapter, parse_adapter
+
+ source = parse_adapter(write_lora_adapter(tmp_path / "adapter"))
+ binding = bind_adapter(source, BaseRef("base", tmp_path))
+
+ def make_model():
+ model = nn.Module()
+ layer = nn.Module()
+ layer.mlp = nn.Module()
+ layer.mlp.gate_proj = nn.Linear(8, 16, bias=False)
+ model.layers = [layer]
+ return model
+
+ base = make_model()
+ assert numerics_revision_for_model(base) is None
+ base._omlx_fp16_recast = True
+ assert numerics_revision_for_model(base) == "fp16-recast"
+
+ attach_lora(base, binding)
+ assert (
+ numerics_revision_for_model(base) == f"fp16-recast,{binding.cache_revision}"
+ )
+
+ updated = make_model()
+ attach_lora(updated, replace(binding, cache_revision="lora-updated"))
+ assert numerics_revision_for_model(updated) == "lora-updated"
+ updated._omlx_fp16_recast = True
+ assert numerics_revision_for_model(updated) == "fp16-recast,lora-updated"
+
def test_sweep_drops_blocks_from_other_numerics(self, tmp_path: Path):
mgr = self._make_manager(tmp_path, self.REVISION)
mgr._index.add(self._make_meta(block_hash=b"21" * 10, numerics=None))
diff --git a/tests/test_prefill_helper.py b/tests/test_prefill_helper.py
index 86882dc10f..e3d904a7e2 100644
--- a/tests/test_prefill_helper.py
+++ b/tests/test_prefill_helper.py
@@ -1284,6 +1284,37 @@ def test_routes_report_status_forward_actions_and_stop_lending(tmp_path, monkeyp
assert killed[-1] == signal.SIGTERM
+def test_adapter_controls_cannot_access_base_helper_preparation(monkeypatch):
+ calls = []
+ path = "/models/base"
+ prep = SimpleNamespace(
+ status=lambda: {"state": "copying"},
+ cancel=lambda: calls.append("cancel"),
+ )
+ entries = {
+ "base": SimpleNamespace(engine=None, model_path=path, adapter=None),
+ "tuned": SimpleNamespace(engine=None, model_path=path, adapter=object()),
+ }
+ monkeypatch.setattr(
+ helper_routes, "_get_engine_pool", lambda: SimpleNamespace(get_entry=entries.get)
+ )
+ monkeypatch.setattr(helper_routes, "file_prep", lambda _: prep)
+ app = FastAPI()
+ app.include_router(helper_routes.router)
+ client = TestClient(app)
+ url = "/admin/api/prefill-helper/models"
+ assert client.get(f"{url}/base").json() == {"state": "copying"}
+ assert client.post(f"{url}/base/stop").status_code == 200
+ assert calls == ["cancel"]
+ calls.clear()
+ assert client.post(f"{url}/tuned/stop").status_code == 400
+ assert calls == []
+ assert client.get(f"{url}/tuned").json() == {"state": "unloaded"}
+ for action in ("check", "copy", "retry"):
+ assert client.post(f"{url}/tuned/{action}").status_code == 400
+ assert calls == []
+
+
def test_a_mac_helping_another_model_counts_that_memory_as_free(monkeypatch):
info = {
"budget": 100 << 30,
diff --git a/tests/test_v1_models_visibility.py b/tests/test_v1_models_visibility.py
index ccb0c58fb9..543d3ad13d 100644
--- a/tests/test_v1_models_visibility.py
+++ b/tests/test_v1_models_visibility.py
@@ -324,7 +324,12 @@ def test_global_hide_helper_excludes_helper_source_profile(tmp_path):
def test_global_hide_helper_excludes_referenced_draft(tmp_path):
# A plain-LLM draft is a helper only because another model references it.
- models = [_model("chat-a"), _model("draft-llm", config_model_type="llama")]
+ models = [
+ _model("chat-a"),
+ _model("draft-llm", config_model_type="llama"),
+ _model("adapted", adapter={"base_model_id": "draft-llm"}),
+ ]
+ models[-1]["model_path"] = "/models/draft-llm"
state = _state(models, tmp_path, hide_helpers=True)
state.settings_manager.set_settings(
"chat-a", ModelSettings(dflash_draft_model="/models/draft-llm")
@@ -332,6 +337,7 @@ def test_global_hide_helper_excludes_referenced_draft(tmp_path):
ids = _list_ids(state)
assert "chat-a" in ids
assert "draft-llm" not in ids
+ assert "adapted" in ids
def test_referenced_parent_stays_visible(tmp_path):
diff --git a/tests/test_vlm_engine.py b/tests/test_vlm_engine.py
index 7dc3acfc60..e9cf39b5e1 100644
--- a/tests/test_vlm_engine.py
+++ b/tests/test_vlm_engine.py
@@ -85,6 +85,64 @@ def _make_engine(**overrides):
return engine
+@pytest.mark.asyncio
+@pytest.mark.parametrize("case", ["adapter", "base", "invalid"])
+async def test_start_attaches_lora_before_bonsai_restore(
+ tmp_path, monkeypatch, write_lora_adapter, case
+):
+ from omlx import lora_adapter
+ from omlx.exceptions import UnsupportedAdapterError
+ from omlx.models import vlm
+ from omlx.utils import model_loading
+
+ class RestoreReachedError(Exception):
+ pass
+
+ source = lora_adapter.parse_adapter(write_lora_adapter(tmp_path / "adapter"))
+ binding = lora_adapter.bind_adapter(source, lora_adapter.BaseRef("base", tmp_path))
+ model, processor = object(), object()
+ calls = []
+
+ def load(*args, **kwargs):
+ calls.append("load")
+ return model, processor
+
+ def attach(loaded, adapter):
+ assert loaded is model and adapter is binding
+ calls.append("attach")
+ if case == "invalid":
+ raise UnsupportedAdapterError(
+ "unsupported test adapter", source.path, feature="test"
+ )
+ return 1
+
+ def restore(loaded):
+ assert loaded is model
+ calls.append("restore")
+ raise RestoreReachedError
+
+ monkeypatch.setattr(
+ model_loading, "maybe_apply_pre_load_patches", lambda *a, **kw: None
+ )
+ monkeypatch.setattr(model_loading, "maybe_load_custom_quantization", load)
+ monkeypatch.setattr(lora_adapter, "attach_lora", attach)
+ monkeypatch.setattr(vlm, "restore_bonsai_quantized_modules", restore)
+ engine = _make_engine(
+ model_name=str(tmp_path), lora=None if case == "base" else binding
+ )
+ if case == "invalid":
+ with pytest.raises(UnsupportedAdapterError, match="unsupported test adapter"):
+ await engine.start()
+ assert calls == ["load", "attach"]
+ assert engine._processor is None
+ else:
+ with pytest.raises(RestoreReachedError):
+ await engine.start()
+ assert calls == (
+ ["load", "restore"] if case == "base" else ["load", "attach", "restore"]
+ )
+
+
@pytest.mark.asyncio
async def test_start_rejects_unsupported_mtp_offload_before_loading(tmp_path):
from omlx.model_settings import ModelSettings
From f1757f03c3027692cd07b2db4b0e3c8ec448f388 Mon Sep 17 00:00:00 2001
From: Mike Wallio
Date: Fri, 20 Nov 2026 09:48:34 -0500
Subject: [PATCH 21/24] fix(runtime): wire prefill types and quantized cache
capacity
Use the engine entry and model settings contracts for prefill helpers, and import the state capacity helper used by batched TurboQuant caches.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
---
omlx/engine_pool.py | 6 ++++--
omlx/turboquant_kv.py | 1 +
2 files changed, 5 insertions(+), 2 deletions(-)
diff --git a/omlx/engine_pool.py b/omlx/engine_pool.py
index 06c6d331b0..1acb7a8b17 100644
--- a/omlx/engine_pool.py
+++ b/omlx/engine_pool.py
@@ -31,7 +31,7 @@
from .cluster.registry import ClusterRegistry
from .engine.image import ImageEngine
from .lora_adapter import AdapterBinding, AdapterIssue, BaseCandidate
- from .model_settings import ModelSettingsManager
+ from .model_settings import ModelSettings, ModelSettingsManager
import mlx.core as mx
@@ -2580,7 +2580,9 @@ def external_process_memory_bytes(self) -> int:
logger.debug("external process memory read failed", exc_info=True)
return total
- def _start_prefill_helper_early(self, entry: Any, settings: Any) -> bool:
+ def _start_prefill_helper_early(
+ self, entry: EngineEntry, settings: ModelSettings | None
+ ) -> bool:
"""Start the chosen Prefill Accelerator while this Mac loads the model."""
node_id = getattr(settings, "prefill_helper_node_id", None)
model_type = (entry.config_model_type or "").replace("-", "_").lower()
diff --git a/omlx/turboquant_kv.py b/omlx/turboquant_kv.py
index 17b534fbef..a2058f4922 100644
--- a/omlx/turboquant_kv.py
+++ b/omlx/turboquant_kv.py
@@ -28,6 +28,7 @@
_build_codec,
_concat_state,
_QuantizedStateProxy,
+ _reserve_state_capacity,
_slice_state,
_slice_state_range,
_state_length, # noqa: F401 - re-exported for local attention/cache helpers
From b58ced9d03850555af8d63f960b1dfac544e97ad Mon Sep 17 00:00:00 2001
From: Mike Wallio
Date: Fri, 20 Nov 2026 09:48:34 -0500
Subject: [PATCH 22/24] fix(i18n): translate fork controls into Italian
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
---
apps/omlx-web/omlx_web/i18n/it.json | 22 ++++++++++++++++++++++
1 file changed, 22 insertions(+)
diff --git a/apps/omlx-web/omlx_web/i18n/it.json b/apps/omlx-web/omlx_web/i18n/it.json
index 177313159c..539c7d865b 100644
--- a/apps/omlx-web/omlx_web/i18n/it.json
+++ b/apps/omlx-web/omlx_web/i18n/it.json
@@ -1,4 +1,26 @@
{
+ "chat.error.history_storage": "Impossibile salvare o ripristinare la cronologia della chat. Tieni aperta questa scheda e scarica le chat per non perdere il lavoro non salvato. Controlla lo spazio di archiviazione del browser e le altre schede aperte prima di ricaricare.",
+ "chat.image_download": "Scarica",
+ "chat.image_reuse": "Riutilizza per la modifica",
+ "modal.model_settings.dflash_single_stream": "Solo flusso singolo: le richieste vengono eseguite una alla volta.",
+ "modal.model_settings.minicpm_downsample_mode": "Compressione visiva",
+ "modal.model_settings.minicpm_downsample_mode_hint": "16x usa meno token visivi; 4x conserva più dettagli. L'impostazione predefinita usa il processore del modello.",
+ "modal.model_settings.minicpm_max_slice_nums": "Numero massimo di sezioni dell'immagine",
+ "modal.model_settings.minicpm_max_slice_nums_hint": "Imposta il limite di sezioni dell'immagine (almeno 1). Lascia il campo vuoto per usare il valore predefinito del processore del modello.",
+ "modal.model_settings.minicpm_media": "Contenuti multimediali MiniCPM",
+ "modal.model_settings.model_type_image": "Immagine",
+ "modal.model_settings.moe_expert_offload_resident_12_5": "12,5% in memoria",
+ "modal.model_settings.moe_expert_offload_resident_25": "25% in memoria",
+ "modal.model_settings.moe_expert_offload_resident_50": "50% in memoria",
+ "modal.model_settings.moe_expert_offload_resident_75": "75% in memoria",
+ "models.detail.adapter_info": "Adattatore LoRA per {base}. Appare come modello separato se su questo Mac è disponibile un modello di base compatibile.",
+ "models.detail.adapter_no_base": "Adattatore LoRA. Nessun modello di base compatibile è stato scaricato. Scarica {base} o una sua versione quantizzata per usare l'adattatore.",
+ "models.manager.adapter_issues_heading": "Adattatori LoRA non disponibili",
+ "models.uploader.queue_activity": "Caricamento in corso. L'avanzamento in byte non è disponibile.",
+ "models.uploader.queue_empty": "Nessun caricamento in coda. L'elenco si aggiorna automaticamente.",
+ "models.uploader.queue_error": "Impossibile aggiornare i caricamenti. L'ultimo stato mostrato potrebbe non essere aggiornato.",
+ "models.uploader.queue_loading": "Caricamento della coda in corso…",
+ "models.uploader.queue_refresh": "Aggiorna i caricamenti",
"cluster.device.ssh_user": "Nome utente SSH",
"cluster.device.ssh_user_help": "Inserisci il nome breve dell'account sul computer remoto. Lascia vuoto per usare il login registrato o la configurazione SSH.",
"cluster.device.ssh_user_save": "Salva nome utente SSH",
From 839f77b499b5e048ffb567f0f289567d0590b232 Mon Sep 17 00:00:00 2001
From: Mike Wallio
Date: Fri, 20 Nov 2026 16:31:33 -0500
Subject: [PATCH 23/24] Support Inkling 2 Mini checkpoints
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
---
README.md | 6 ++
omlx/adapter/output_parser.py | 2 +-
omlx/api/utils.py | 1 +
omlx/engine/vlm.py | 2 +-
omlx/model_discovery.py | 1 +
omlx/patches/inkling2/loader.py | 49 ++++++++---
omlx/patches/inkling2/loop.py | 98 +++++++++++++++++++++
omlx/patches/inkling2/model.py | 104 ++++++++++++++++++----
omlx/patches/inkling2/vlm.py | 33 ++++++-
tests/test_inkling_vlm_mtp.py | 148 +++++++++++++++++++++++++++++++-
tests/test_output_parser.py | 7 ++
11 files changed, 416 insertions(+), 35 deletions(-)
create mode 100644 omlx/patches/inkling2/loop.py
diff --git a/README.md b/README.md
index 6909722dba..57bb3b2444 100644
--- a/README.md
+++ b/README.md
@@ -536,6 +536,12 @@ Models are auto-detected by type. You can also download models directly from the
Embedding and reranker models load through mlx-vlm; the separate mlx-embeddings dependency is gone. NomicBERT checkpoints are no longer supported. SigLIP serves text embeddings only and rejects image inputs. Qwen3-VL-Embedding rejects inputs longer than 8192 tokens instead of truncating them.
+oMLX serves [Inkling 2 Mini](https://huggingface.co/thinkingmachines/Inkling-2-Mini)
+from the original `inkling2_loop` checkpoint. Keep the checkpoint files together
+in a model directory. Text, image input, and chat tool calls use the native
+checkpoint template and tokenizer. The bundled DSpark draft, audio input, and
+video input are not supported for Mini.
+
### Flint
RecursiveSI Flint is a text-only MoE model served through native mlx-vlm
diff --git a/omlx/adapter/output_parser.py b/omlx/adapter/output_parser.py
index 74c1d872da..d63a84a6a4 100644
--- a/omlx/adapter/output_parser.py
+++ b/omlx/adapter/output_parser.py
@@ -817,7 +817,7 @@ def finalize(self) -> OutputParserFinalizeResult:
)
-_INKLING_MODEL_TYPES = {"inkling", "inkling_mm_model", "inkling2"}
+_INKLING_MODEL_TYPES = {"inkling", "inkling_mm_model", "inkling2", "inkling2_loop"}
_INKLING_MESSAGE_MODEL = "<|message_model|>"
_INKLING_CONTENT_THINKING = "<|content_thinking|>"
_INKLING_CONTENT_TEXT = "<|content_text|>"
diff --git a/omlx/api/utils.py b/omlx/api/utils.py
index 5d95453e75..28a5164495 100644
--- a/omlx/api/utils.py
+++ b/omlx/api/utils.py
@@ -20,6 +20,7 @@
"inkling",
"inkling_mm_model",
"inkling2",
+ "inkling2_loop",
# Muse Glimmer's chat template renders history reasoning_content into
# <|start|>assistant to=self<|message|> blocks.
"muse_glimmer",
diff --git a/omlx/engine/vlm.py b/omlx/engine/vlm.py
index 4745010612..d792d5c1a9 100644
--- a/omlx/engine/vlm.py
+++ b/omlx/engine/vlm.py
@@ -2289,7 +2289,7 @@ def _load_vlm_sync():
getattr(self._model_settings, "a8_prefill_min_tokens", 128)
),
)
- if model_type == "inkling2":
+ if model_type in inkling2_vlm.MODEL_TYPES:
return inkling2_vlm.load(self._model_name)
if model_type == "muse_spark":
return muse_spark_model.load(
diff --git a/omlx/model_discovery.py b/omlx/model_discovery.py
index a62f90c3c7..5d6348bcd0 100644
--- a/omlx/model_discovery.py
+++ b/omlx/model_discovery.py
@@ -131,6 +131,7 @@ def model_unavailable_reason(config_model_type: str | None) -> str | None:
"inkling_mm_model", # config model_type of Inkling Small checkpoints
# mlx-lm's Inkling 2 module served through the VLM engine adapter.
"inkling2",
+ "inkling2_loop",
"bailing_moe_v3_vl",
"muse_glimmer",
"muse_spark",
diff --git a/omlx/patches/inkling2/loader.py b/omlx/patches/inkling2/loader.py
index b40d386409..5b299ab089 100644
--- a/omlx/patches/inkling2/loader.py
+++ b/omlx/patches/inkling2/loader.py
@@ -54,6 +54,7 @@ def sanitize_weights(model, weights: dict) -> tuple[dict, dict]:
out: dict = {}
formats: dict[int, str] = {}
per_layer: dict[int, dict] = {}
+ source_queries: dict[str, mx.array] = {}
for key, value in weights.items():
if key.startswith(_VISUAL_PREFIX):
if has_vision:
@@ -85,24 +86,47 @@ def sanitize_weights(model, weights: dict) -> tuple[dict, dict]:
out["model.final_input.query"] = value.reshape(-1, hidden).astype(
mx.float32
)
+ elif name in (
+ "middle_cycle_cross_pass_queries",
+ "middle_cycle_cross_pass_kv_queries",
+ ):
+ source_queries[name] = value
elif name.startswith("layers."):
_, idx, rest = name.split(".", 2)
per_layer.setdefault(int(idx), {})[rest] = value
+ elif getattr(model.model, "message_query", None) is not None:
+ raise ValueError(f"Unmapped Inkling 2 tensor: {key}")
+
+ if source_queries:
+ hidden = args.hidden_size
+ q_mlp = source_queries["middle_cycle_cross_pass_queries"].reshape(-1, 2, hidden)
+ k_v = source_queries["middle_cycle_cross_pass_kv_queries"].reshape(
+ -1, 2, hidden
+ )
+ out["model.message_query"] = mx.concatenate(
+ [q_mlp[:, :1], k_v, q_mlp[:, 1:]], axis=1
+ ).astype(mx.float32)
for idx, d in per_layer.items():
pre = f"model.layers.{idx}."
+ split_sliding = model.model.layers[idx].attn.split_sliding
if args.is_sliding(idx):
- out[pre + "attn.in_proj.weight"] = mx.concatenate(
- [
- d.pop("attn.wq_du.weight"),
- d.pop("attn.wk_dv.weight"),
- d.pop("attn.wv_dv.weight"),
- d.pop("attn.wr_du.weight"),
- d.pop("attn.gate_attn.weight"),
- d.pop("attn.attn_sink_proj.weight"),
- ],
- axis=0,
- )
+ q = d.pop("attn.wq_du.weight")
+ k_weight = d.pop("attn.wk_dv.weight")
+ v_weight = d.pop("attn.wv_dv.weight")
+ tail = [
+ d.pop("attn.wr_du.weight"),
+ d.pop("attn.gate_attn.weight"),
+ d.pop("attn.attn_sink_proj.weight"),
+ ]
+ if split_sliding:
+ out[pre + "attn.q_proj.weight"] = mx.concatenate([q, *tail], axis=0)
+ out[pre + "attn.k_proj.weight"] = k_weight
+ out[pre + "attn.v_proj.weight"] = v_weight
+ else:
+ out[pre + "attn.in_proj.weight"] = mx.concatenate(
+ [q, k_weight, v_weight, *tail], axis=0
+ )
out[pre + "attn.k_conv"] = d.pop("attn.k_sconv.weight").reshape(-1, k)
out[pre + "attn.v_conv"] = d.pop("attn.v_sconv.weight").reshape(-1, k)
out[pre + "attn_norm.weight"] = d.pop("attn_norm.weight")
@@ -140,6 +164,9 @@ def sanitize_weights(model, weights: dict) -> tuple[dict, dict]:
formats[idx] = _expert_tensors(d, "w13", out, pre)
if _expert_tensors(d, "w2", out, pre) != formats[idx]:
raise ValueError(f"Inkling 2 layer {idx} mixes expert formats")
+ for n in list(d):
+ if n.startswith("controllers."):
+ out[pre + n] = d.pop(n)
if d:
raise ValueError(f"Unmapped Inkling 2 tensors in layer {idx}: {sorted(d)}")
return out, formats
diff --git a/omlx/patches/inkling2/loop.py b/omlx/patches/inkling2/loop.py
new file mode 100644
index 0000000000..ab015db74c
--- /dev/null
+++ b/omlx/patches/inkling2/loop.py
@@ -0,0 +1,98 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Looped Inkling 2 text execution used by Inkling 2 Mini."""
+
+from dataclasses import dataclass
+
+import mlx.core as mx
+
+from .model import Inkling2Layer, Inkling2TextModel, TextArgs, _unit_rms
+
+MODEL_TYPE = "inkling2_loop"
+
+
+@dataclass(frozen=True)
+class LoopPlan:
+ start: int
+ end: int
+ passes: int
+ rank: int
+
+ @classmethod
+ def from_config(cls, config: dict, args: TextArgs):
+ plan = cls(
+ int(config["core_start"]),
+ int(config["core_end"]),
+ int(config["num_passes"]),
+ int(config["gate_rank"]),
+ )
+ block = args.n_layers_per_attn_res_block
+ if (
+ config.get("is_varloop")
+ or not 0 < plan.start < plan.end <= args.num_hidden_layers
+ or plan.start % block
+ or plan.end % block
+ or plan.passes < 1
+ or plan.rank < 1
+ ):
+ raise ValueError(f"Unsupported Inkling 2 loop configuration: {config}")
+ return plan
+
+ def visits(self, num_layers: int):
+ return (
+ range(self.start),
+ *((range(self.start, self.end),) * self.passes),
+ range(self.end, num_layers),
+ )
+
+
+class LoopTextModel(Inkling2TextModel):
+ def __init__(self, args, quant, plan: LoopPlan):
+ self._plan = plan
+ super().__init__(args, quant)
+ self._visits = plan.visits(len(self.layers))
+ self.cache_count = sum(map(len, self._visits))
+ self.message_query = mx.zeros(
+ (plan.end - plan.start, 4, args.hidden_size), dtype=mx.float32
+ )
+
+ def _make_layer(self, args, index, w13, w2):
+ rank = self._plan.rank if self._plan.start <= index < self._plan.end else None
+ return Inkling2Layer(args, index, w13, w2, message_rank=rank)
+
+ def __call__(self, inputs, cache=None, input_embeddings=None, capture=None):
+ if capture:
+ raise ValueError("Inkling 2 Mini does not support speculative decoding.")
+ h = (
+ self.embed_norm(self.embed(inputs))
+ if input_embeddings is None
+ else input_embeddings
+ )
+ if cache is not None and len(cache) != self.cache_count:
+ raise ValueError("Inkling 2 Mini requires one cache per layer visit.")
+ blocks = []
+ index = 0
+ pre_h, pre_blocks = h, blocks
+ for stage, layers in enumerate(self._visits):
+ previous = None
+ if stage == 1:
+ pre_h, pre_blocks = h, list(blocks)
+ elif 1 < stage < len(self._visits) - 1:
+ # Exclude the loop-entry block, which every pass already sees.
+ previous = mx.stack(
+ [*blocks[len(pre_blocks) + 1 :], _unit_rms(h.astype(mx.float32))],
+ axis=-2,
+ )
+ h, blocks = pre_h, list(pre_blocks)
+ for layer in layers:
+ messages = None
+ if previous is not None:
+ query = self.message_query[layer - self._plan.start]
+ scores = (query @ previous.swapaxes(-1, -2)) * (
+ self.args.hidden_size**-0.5
+ )
+ messages = mx.softmax(scores, axis=-1) @ previous
+ entry = cache[index] if cache is not None else None
+ h = self.layers[layer](h, blocks, cache=entry, messages=messages)
+ index += 1
+ x = self.final_input(blocks, _unit_rms(h.astype(mx.float32)))[:, :, 0]
+ return self.norm(x).astype(h.dtype)
diff --git a/omlx/patches/inkling2/model.py b/omlx/patches/inkling2/model.py
index bb20faf4a3..e283e95357 100644
--- a/omlx/patches/inkling2/model.py
+++ b/omlx/patches/inkling2/model.py
@@ -346,9 +346,10 @@ def _dynamic_conv(x, dyn, static_w, state, heads, scale):
class Inkling2Attention(nn.Module):
- def __init__(self, args: TextArgs, layer_idx: int):
+ def __init__(self, args: TextArgs, layer_idx: int, *, split_sliding: bool = False):
super().__init__()
self.sliding = args.is_sliding(layer_idx)
+ self.split_sliding = split_sliding
self.head_dim = args.swa_head_dim if self.sliding else args.head_dim
self.n_heads = (
args.swa_num_attention_heads if self.sliding else args.num_attention_heads
@@ -369,8 +370,14 @@ def __init__(self, args: TextArgs, layer_idx: int):
dr = self.n_heads * self.d_rel
if self.sliding:
# q | k | v | r | gate | sink share one input.
- splits = (dq, self.dkv, self.dkv, dr, dq, self.n_heads)
- self.in_proj = nn.Linear(h, sum(splits), bias=False)
+ if split_sliding:
+ splits = (dq, dr, dq, self.n_heads)
+ self.q_proj = nn.Linear(h, sum(splits), bias=False)
+ self.k_proj = nn.Linear(h, self.dkv, bias=False)
+ self.v_proj = nn.Linear(h, self.dkv, bias=False)
+ else:
+ splits = (dq, self.dkv, self.dkv, dr, dq, self.n_heads)
+ self.in_proj = nn.Linear(h, sum(splits), bias=False)
self.k_conv = mx.zeros((self.dkv, self.conv_k))
self.v_conv = mx.zeros((self.dkv, self.conv_k))
else:
@@ -412,7 +419,11 @@ def project(self, xq, xk, xv, ks, vs, tau):
b, length, _ = xq.shape
dkv = self.dkv
if self.sliding:
- q, k, v, r, gate, sink = mx.split(self.in_proj(xq), self._cuts, axis=-1)
+ if self.split_sliding:
+ q, r, gate, sink = mx.split(self.q_proj(xq), self._cuts, axis=-1)
+ k, v = self.k_proj(xk), self.v_proj(xv)
+ else:
+ q, k, v, r, gate, sink = mx.split(self.in_proj(xq), self._cuts, axis=-1)
k, ks = _static_conv(k, self.k_conv, ks, self._sconv_scale)
v, vs = _static_conv(v, self.v_conv, vs, self._sconv_scale)
else:
@@ -500,8 +511,36 @@ def _cumsum(xs):
_COMPILED_MAX_TOKENS = 16
+class _MessageGate(nn.Module):
+ def __init__(self, hidden: int, rank: int, eps: float):
+ super().__init__()
+ self.down_weight = mx.zeros((rank, 2 * hidden))
+ self.forget_weight = mx.zeros((hidden, rank), dtype=mx.float32)
+ self.gain_weight = mx.zeros((hidden, rank), dtype=mx.float32)
+ self.eps = eps
+
+ def __call__(self, state, message):
+ inputs = mx.concatenate(
+ [_unit_rms(state, self.eps), _unit_rms(message, self.eps)], axis=-1
+ )
+ gate = (inputs.astype(self.down_weight.dtype) @ self.down_weight.T).astype(
+ mx.float32
+ )
+ forget = mx.tanh(gate @ self.forget_weight.T)
+ gain = mx.tanh(gate @ self.gain_weight.T)
+ return (1 - forget) * state + gain * message
+
+
class Inkling2Layer(nn.Module):
- def __init__(self, args: TextArgs, layer_idx: int, w13_spec: dict, w2_spec: dict):
+ def __init__(
+ self,
+ args: TextArgs,
+ layer_idx: int,
+ w13_spec: dict,
+ w2_spec: dict,
+ *,
+ message_rank: int | None = None,
+ ):
super().__init__()
self.layer_idx = layer_idx
self.sliding = args.is_sliding(layer_idx)
@@ -511,7 +550,14 @@ def __init__(self, args: TextArgs, layer_idx: int, w13_spec: dict, w2_spec: dict
if layer_idx > 0:
self.attn_input = AttnResQuery(h, 1 if self.sliding else 3)
self.mlp_input = AttnResQuery(h, 1)
- self.attn = Inkling2Attention(args, layer_idx)
+ self.attn = Inkling2Attention(
+ args, layer_idx, split_sliding=self.sliding and message_rank is not None
+ )
+ if message_rank is not None:
+ self.controllers = {
+ name: _MessageGate(h, message_rank, eps)
+ for name in ("attn", "k", "v", "mlp")
+ }
self.mlp = Inkling2MoE(args, w13_spec, w2_spec)
if self.sliding:
self.attn_norm = nn.RMSNorm(h, eps=eps)
@@ -530,7 +576,7 @@ def __init__(self, args: TextArgs, layer_idx: int, w13_spec: dict, w2_spec: dict
self._pre_compiled = mx.compile(lambda *a: Inkling2Layer._pre(layer, *a))
self._post_compiled = mx.compile(lambda *a: Inkling2Layer._post(layer, *a))
- def _pre(self, h, blocks, ks, vs, tau=None):
+ def _pre(self, h, blocks, ks, vs, tau=None, messages=None):
dtype = h.dtype
h_n = _unit_rms(h.astype(mx.float32))
if self.layer_idx == 0:
@@ -538,19 +584,27 @@ def _pre(self, h, blocks, ks, vs, tau=None):
else:
mixed = self.attn_input(blocks, h_n)
if self.sliding:
- xq = mixed[:, :, 0]
+ xq = xk = xv = mixed[:, :, 0]
else:
xq, xk, xv = mixed[:, :, 0], mixed[:, :, 1], mixed[:, :, 2]
+ if messages is not None:
+ xq = self.controllers["attn"](xq, messages[..., 0, :])
+ xk = self.controllers["k"](xk, messages[..., 1, :])
+ xv = self.controllers["v"](xv, messages[..., 2, :])
if self.sliding:
xq = self.attn_norm(xq).astype(dtype)
- xk = xv = None
+ if self.attn.split_sliding:
+ xk = self.attn_norm(xk).astype(dtype)
+ xv = self.attn_norm(xv).astype(dtype)
+ else:
+ xk = xv = None
else:
xq = self.q_input_norm(xq).astype(dtype)
xk = self.k_input_norm(xk).astype(dtype)
xv = self.v_input_norm(xv).astype(dtype)
return (*self.attn.project(xq, xk, xv, ks, vs, tau), h_n)
- def _post(self, out, gate, h, mlp_blocks, s2, s3):
+ def _post(self, out, gate, h, mlp_blocks, s2, s3, messages=None):
a = self.attn.output(out, gate)
a, s2 = _static_conv(a, self.attn_conv, s2, self._conv_scale)
if self.is_boundary:
@@ -558,11 +612,13 @@ def _post(self, out, gate, h, mlp_blocks, s2, s3):
else:
residual = h.astype(mx.float32) + a.astype(mx.float32)
y = self.mlp_input(mlp_blocks, _unit_rms(residual))[:, :, 0]
+ if messages is not None:
+ y = self.controllers["mlp"](y, messages[..., 3, :])
m = self.mlp(self.mlp_norm(y).astype(h.dtype))
m, s3 = _static_conv(m, self.mlp_conv, s3, self._conv_scale)
return (residual + m.astype(mx.float32)).astype(h.dtype), s2, s3
- def __call__(self, h, blocks, cache=None):
+ def __call__(self, h, blocks, cache=None, *, messages=None):
"""``h``: partial block sum [B, L, H] bf16. ``blocks``: list of unit-RMS
FP32 completed blocks; extended in place at a block boundary."""
b, length, hidden = h.shape
@@ -580,13 +636,18 @@ def __call__(self, h, blocks, cache=None):
pre = self._pre_compiled if compiled else self._pre
post = self._post_compiled if compiled else self._post
pre_args = (h, blocks, states[0], states[1])
- if tau is not None:
+ if messages is not None:
+ pre_args = (*pre_args, tau, messages)
+ elif tau is not None:
pre_args = (*pre_args, tau)
q, k, v, rel, gate, sink, ks, vs, h_n = pre(*pre_args)
out = self.attn.attend(q, k, v, rel, sink, kv)
if self.is_boundary:
blocks.append(h_n)
- h, s2, s3 = post(out, gate, h, blocks, states[2], states[3])
+ post_args = (out, gate, h, blocks, states[2], states[3])
+ if messages is not None:
+ post_args = (*post_args, messages)
+ h, s2, s3 = post(*post_args)
if conv is not None:
windows = (ks, vs, s2, s3)
if 1 < length <= _COMPILED_MAX_TOKENS:
@@ -606,12 +667,15 @@ def __init__(self, args: TextArgs, quant: dict | None = None):
self.embed = nn.Embedding(args.vocab_size, args.hidden_size)
self.embed_norm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps)
self.layers = [
- Inkling2Layer(args, i, *_expert_specs(args, quant, i))
+ self._make_layer(args, i, *_expert_specs(args, quant, i))
for i in range(args.num_hidden_layers)
]
self.final_input = AttnResQuery(args.hidden_size, 1)
self.norm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps)
+ def _make_layer(self, args, index, w13, w2):
+ return Inkling2Layer(args, index, w13, w2)
+
def __call__(self, inputs, cache=None, input_embeddings=None, capture=None):
"""``capture`` maps draft feature ids to fill: ``i`` < num layers is
the partial block sum entering layer ``i``; ``num layers`` is the
@@ -635,12 +699,14 @@ def __call__(self, inputs, cache=None, input_embeddings=None, capture=None):
class Model(nn.Module):
+ _text_model = Inkling2TextModel
+
def __init__(self, args: ModelArgs):
super().__init__()
self.args = args
self.model_type = args.model_type
quant = args.quantization
- self.model = Inkling2TextModel(args.text, quant)
+ self.model = self._text_model(args.text, quant)
self.lm_head = nn.Linear(
args.text.hidden_size, args.text.vocab_size, bias=False
)
@@ -781,7 +847,11 @@ def layers(self):
return self.model.layers
def make_cache(self):
- return [CacheList(KVCache(), ArraysCache(4)) for _ in self.model.layers]
+ return [CacheList(KVCache(), ArraysCache(4)) for _ in range(self._cache_count)]
+
+ @property
+ def _cache_count(self):
+ return len(self.model.layers)
def sanitize(self, weights: dict) -> dict:
out, formats = sanitize_weights(self, weights)
@@ -806,6 +876,8 @@ def predicate(key: str) -> bool:
or key.endswith("router_weight")
or key.endswith("router_bias")
or key.endswith(".global_scale")
+ or key.endswith(".message_query")
+ or key.endswith((".forget_weight", ".gain_weight"))
)
return predicate
diff --git a/omlx/patches/inkling2/vlm.py b/omlx/patches/inkling2/vlm.py
index 3d145e245f..6e47cb89c9 100644
--- a/omlx/patches/inkling2/vlm.py
+++ b/omlx/patches/inkling2/vlm.py
@@ -4,6 +4,7 @@
from __future__ import annotations
+import json
from pathlib import Path
from types import SimpleNamespace
@@ -14,9 +15,12 @@
from . import apply_inkling2_patch
from . import model as inkling2
+from .loop import MODEL_TYPE as LOOP_MODEL_TYPE
+from .loop import LoopPlan, LoopTextModel
from .processing import Inkling2Processor
_MODEL_TYPE = "inkling2"
+MODEL_TYPES = frozenset({_MODEL_TYPE, LOOP_MODEL_TYPE})
_UNSUPPORTED_INPUTS = ("pixel_values_videos", "input_values", "input_features")
_REGISTERED = False
@@ -25,12 +29,13 @@ def _register_mlx_vlm() -> None:
global _REGISTERED
if _REGISTERED:
return
- install_auto_processor_patch(_MODEL_TYPE, Inkling2Processor)
# Without a MODEL_CONFIG entry apply_chat_template drops the image parts.
model_config = getattr(prompt_utils, "MODEL_CONFIG", None)
message_format = getattr(prompt_utils, "MessageFormat", None)
- if isinstance(model_config, dict) and message_format is not None:
- model_config.setdefault(_MODEL_TYPE, message_format.LIST_WITH_IMAGE_FIRST)
+ for model_type in MODEL_TYPES:
+ install_auto_processor_patch(model_type, Inkling2Processor)
+ if isinstance(model_config, dict) and message_format is not None:
+ model_config.setdefault(model_type, message_format.LIST_WITH_IMAGE_FIRST)
_REGISTERED = True
@@ -79,15 +84,35 @@ def get_input_embeddings(self, input_ids=None, pixel_values=None, **kwargs):
return InputEmbeddingsFeatures(inputs_embeds=embeds)
+class LoopModel(Model):
+ def _text_model(self, args, quant):
+ plan = LoopPlan.from_config(self.args.text_config["loop_config"], args)
+ return LoopTextModel(args, quant, plan)
+
+ @property
+ def _cache_count(self):
+ return self.model.cache_count
+
+
+def _model_classes(config):
+ cls = LoopModel if config.get("model_type") == LOOP_MODEL_TYPE else Model
+ return cls, inkling2.ModelArgs
+
+
def load(model_path: str | Path, *, lazy: bool = False):
"""Load an Inkling 2 checkpoint with mlx-lm and its processor."""
apply_inkling2_patch()
_register_mlx_vlm()
path = get_model_path(str(model_path))
+ with (path / "config.json").open() as config_file:
+ is_loop = json.load(config_file).get("model_type") == LOOP_MODEL_TYPE
model, config = load_model(
path,
lazy=lazy,
- get_model_classes=lambda config: (Model, inkling2.ModelArgs),
+ get_model_classes=_model_classes,
+ # Mini's sanitizer installs the mixed expert carriers directly.
+ # Its global ModelOpt declaration describes only one of those formats.
+ model_config={"quantization_config": None} if is_loop else None,
)
model.config = SimpleNamespace(
model_type=model.model_type,
diff --git a/tests/test_inkling_vlm_mtp.py b/tests/test_inkling_vlm_mtp.py
index ccfee3b680..64c860f2ad 100644
--- a/tests/test_inkling_vlm_mtp.py
+++ b/tests/test_inkling_vlm_mtp.py
@@ -522,8 +522,16 @@ def _inkling2_tiny(formats=("mxfp8",) * 6 + ("nvfp4",) * 6, vision=None, **dims)
expert_formats=list(formats),
)
text.update(dims)
- model = inkling2.Model(
- inkling2.ModelArgs(model_type="inkling2", text_config=text, vision_config=vision)
+ cls = inkling2.Model
+ model_type = "inkling2"
+ if "loop_config" in dims:
+ from omlx.patches.inkling2.vlm import LoopModel
+
+ cls, model_type = LoopModel, "inkling2_loop"
+ model = cls(
+ inkling2.ModelArgs(
+ model_type=model_type, text_config=text, vision_config=vision
+ )
)
mx.random.seed(0)
weights = []
@@ -559,6 +567,142 @@ def test_inkling2_incremental_and_chunked_match_full_forward():
assert mx.abs(full[:, 11:] - tail).max().item() < 1e-3
+def test_inkling2_mini_keeps_each_pass_cache_and_reuses_layers():
+ model = _inkling2_tiny(
+ formats=("nvfp4",) * 4 + ("mxfp8",) * 2,
+ n_layers_per_attn_res_block=2,
+ local_layer_ids=[0, 2, 4],
+ loop_config=dict(core_start=2, core_end=4, num_passes=3, gate_rank=8),
+ )
+ ids = mx.random.randint(0, 300, (1, 15))
+ cache = model.make_cache()
+ full = model(ids)[..., :300]
+ model(ids[:, :8], cache=cache)
+ tail = model(ids[:, 8:14], cache=cache)[..., :300]
+ final = model(ids[:, -1:], cache=cache)[..., :300]
+ assert mx.allclose(full[:, 8:], mx.concatenate((tail, final), axis=1), atol=1e-3)
+ assert len(model.layers) == 6
+ assert [entry[0].offset for entry in cache] == [15] * 10
+ # Layer 2 runs three times with different controller inputs.
+ assert not mx.array_equal(cache[2][0].keys, cache[4][0].keys).item()
+ assert not mx.array_equal(cache[4][0].keys, cache[6][0].keys).item()
+
+
+def test_inkling2_mini_loads_original_packed_checkpoint(tmp_path):
+ import json
+ from dataclasses import asdict
+
+ from mlx.utils import tree_flatten
+
+ from omlx.patches.inkling2.vlm import load
+
+ loop = dict(core_start=1, core_end=2, num_passes=3, gate_rank=8)
+ original = _inkling2_tiny(
+ formats=("nvfp4", "nvfp4", "mxfp8"),
+ local_layer_ids=[0, 1, 2],
+ n_layers_per_attn_res_block=1,
+ loop_config=loop,
+ )
+ tensors = dict(tree_flatten(original.parameters()))
+ source = {
+ "embed.weight": tensors["model.embed.weight"],
+ "embed_norm.weight": tensors["model.embed_norm.weight"],
+ "norm.weight": tensors["model.norm.weight"],
+ "unembed.weight": tensors["lm_head.weight"],
+ "attn_res.output_query": tensors["model.final_input.query"],
+ }
+ query = tensors["model.message_query"]
+ source["middle_cycle_cross_pass_queries"] = query[:, [0, 3], :].reshape(-1, 128)
+ source["middle_cycle_cross_pass_kv_queries"] = query[:, 1:3, :].reshape(-1, 128)
+ names = {
+ "attn.k_conv": "attn.k_sconv.weight",
+ "attn.v_conv": "attn.v_sconv.weight",
+ "attn.o_proj.weight": "attn.wo_ud.weight",
+ "attn.q_scale": "attn.q_l2_clip.scale",
+ "attn.r_scale": "attn.rel_l2_clip.scale",
+ "attn.rel_proj": "attn.rel_logits_proj.proj",
+ "attn_conv": "attn_sconv.weight",
+ "mlp_conv": "mlp_sconv.weight",
+ "attn_norm.weight": "attn_norm.weight",
+ "mlp_norm.weight": "mlp_norm.weight",
+ "mlp.router_weight": "mlp.gate.weight",
+ "mlp.router_bias": "mlp.gate.bias",
+ }
+ for i, layer in enumerate(original.layers):
+ prefix = f"layers.{i}."
+ weights = {
+ key.removeprefix(f"model.{prefix}"): value
+ for key, value in tensors.items()
+ if key.startswith(f"model.{prefix}")
+ }
+ source.update({prefix + src: weights[dst] for dst, src in names.items()})
+ if i:
+ source[f"attn_res.attn_queries.{i - 1}"] = weights["attn_input.query"]
+ source[f"attn_res.mlp_queries.{i}"] = weights["mlp_input.query"]
+ for key in weights:
+ if key.startswith("controllers."):
+ source[prefix + key] = weights[key]
+ if layer.attn.split_sliding:
+ q, rel, gate, sink = mx.split(
+ weights["attn.q_proj.weight"], [128, 160, 288]
+ )
+ k, v = weights["attn.k_proj.weight"], weights["attn.v_proj.weight"]
+ else:
+ q, k, v, rel, gate, sink = mx.split(
+ weights["attn.in_proj.weight"], [128, 192, 256, 288, 416]
+ )
+ for part, weight in zip(
+ ("wq_du", "wk_dv", "wv_dv", "wr_du", "gate_attn", "attn_sink_proj"),
+ (q, k, v, rel, gate, sink),
+ ):
+ source[prefix + f"attn.{part}.weight"] = weight
+ for part in ("w13", "w2"):
+ key = f"mlp.experts.{part}"
+ source[prefix + key + "_weight"] = weights[key + ".weight"].view(mx.uint8)
+ source[prefix + key + "_weight_scale"] = weights[key + ".scales"]
+ if key + ".global_scale" in weights:
+ source[prefix + key + "_weight_amax"] = weights[key + ".global_scale"]
+ source[prefix + key + "_weight_outer_scale_denominator"] = mx.array(
+ 2688
+ )
+
+ text = asdict(original.args.text)
+ text.pop("expert_formats") # The source supplies formats through weights.
+ (tmp_path / "config.json").write_text(
+ json.dumps(
+ {
+ "model_type": "inkling2_loop",
+ "text_config": {**text, "loop_config": loop},
+ "eos_token_id": 1,
+ "quantization_config": {
+ "quant_method": "modelopt",
+ "quant_algo": "NVFP4",
+ },
+ }
+ )
+ )
+ from tokenizers import Tokenizer, models
+ from transformers import PreTrainedTokenizerFast
+
+ tokenizer = Tokenizer(models.WordLevel({"[PAD]": 0, "[EOS]": 1, "[UNK]": 2}))
+ PreTrainedTokenizerFast(
+ tokenizer_object=tokenizer,
+ eos_token="[EOS]",
+ pad_token="[PAD]",
+ unk_token="[UNK]",
+ ).save_pretrained(tmp_path)
+ mx.save_safetensors(
+ str(tmp_path / "model.safetensors"),
+ {"model.llm." + key: value for key, value in source.items()},
+ )
+ mx.save_safetensors(str(tmp_path / "mtp.safetensors"), {"unused": mx.zeros(1)})
+ loaded, _ = load(tmp_path)
+ ids = mx.array([[9, 8, 24]])
+ assert mx.allclose(loaded(ids)[..., :300], original(ids)[..., :300], atol=1e-5)
+ assert loaded.layers[1].mlp.experts.w13.mode == "nvfp4"
+ assert loaded.layers[2].mlp.experts.w13.mode == "mxfp8"
+
+
def test_inkling2_verify_rollback_matches_sequential_decode():
model = _inkling2_tiny()
ids = mx.random.randint(0, 300, (1, 30))
diff --git a/tests/test_output_parser.py b/tests/test_output_parser.py
index 7b322d7fab..cc20c44897 100644
--- a/tests/test_output_parser.py
+++ b/tests/test_output_parser.py
@@ -1161,6 +1161,13 @@ def detokenizer(self):
class TestInklingOutputParserSession:
+ def test_mini_uses_channel_parser_with_an_arbitrary_model_name(self):
+ factory = detect_output_parser(
+ "local-checkpoint", InklingTokenizer({}), {"model_type": "inkling2_loop"}
+ )
+ assert factory is not None
+ assert factory.kind == "inkling"
+
def _factory(self, token_map):
tokenizer = InklingTokenizer(token_map)
factory = detect_output_parser(
From 12640990d231b886451795b66553931537aeb8e2 Mon Sep 17 00:00:00 2001
From: Mike Wallio
Date: Fri, 20 Nov 2026 19:50:23 -0500
Subject: [PATCH 24/24] feat(inkling2): add opt-in DSpark for Mini
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
---
README.md | 5 +--
omlx/admin/routes.py | 2 +-
omlx/engine_pool.py | 5 +--
omlx/patches/inkling2/dspark.py | 3 +-
omlx/patches/inkling2/loop.py | 10 ++++--
omlx/utils/model_loading.py | 17 +++++----
tests/test_inkling_vlm_mtp.py | 64 +++++++++++++++++++++++++++++++++
7 files changed, 88 insertions(+), 18 deletions(-)
diff --git a/README.md b/README.md
index 57bb3b2444..28a09d295c 100644
--- a/README.md
+++ b/README.md
@@ -539,8 +539,9 @@ Embedding and reranker models load through mlx-vlm; the separate mlx-embeddings
oMLX serves [Inkling 2 Mini](https://huggingface.co/thinkingmachines/Inkling-2-Mini)
from the original `inkling2_loop` checkpoint. Keep the checkpoint files together
in a model directory. Text, image input, and chat tool calls use the native
-checkpoint template and tokenizer. The bundled DSpark draft, audio input, and
-video input are not supported for Mini.
+checkpoint template and tokenizer. To use the bundled `mtp.safetensors` draft,
+enable **Lightning MTP** in Mini's model settings (`mtp_enabled: true`). It is
+off by default. Audio and video input are not supported for Mini.
### Flint
diff --git a/omlx/admin/routes.py b/omlx/admin/routes.py
index 2f48a00f5d..ab5e64baca 100644
--- a/omlx/admin/routes.py
+++ b/omlx/admin/routes.py
@@ -1325,7 +1325,7 @@ def _mtp_compat_for_model(
if bundled_dspark_path(model_path) is not None:
return True, ""
return False, "MiniMax checkpoint has no bundled dspark/ draft"
- if model_type == "inkling2":
+ if model_type in ("inkling2", "inkling2_loop"):
from ..patches.inkling2.dspark import bundled_inkling2_dspark_path
if bundled_inkling2_dspark_path(model_path) is not None:
diff --git a/omlx/engine_pool.py b/omlx/engine_pool.py
index 1acb7a8b17..ec32fd61d0 100644
--- a/omlx/engine_pool.py
+++ b/omlx/engine_pool.py
@@ -91,6 +91,7 @@
validate_ane_prefill,
)
from .patches.inkling2.dspark import (
+ BUNDLED_DSPARK_MODEL_TYPES,
bundled_inkling2_dspark_path,
load_inkling2_dspark_drafter,
)
@@ -746,7 +747,7 @@ def _entry_runtime_resident_size(
extra += self._dflash_drafter_estimated_bytes(str(dspark_path), None)
elif (
getattr(runtime_settings, "mtp_enabled", False)
- and entry.config_model_type == "inkling2"
+ and entry.config_model_type in BUNDLED_DSPARK_MODEL_TYPES
):
draft = bundled_inkling2_dspark_path(entry.model_path)
if draft is not None:
@@ -4889,7 +4890,7 @@ def _load_dflash_sync(path: str = drafter_path):
if (
model_settings is not None
and getattr(model_settings, "mtp_enabled", False)
- and entry.config_model_type == "inkling2"
+ and entry.config_model_type in BUNDLED_DSPARK_MODEL_TYPES
and hasattr(engine, "prepare_dflash_target")
):
draft_path = bundled_inkling2_dspark_path(entry.model_path)
diff --git a/omlx/patches/inkling2/dspark.py b/omlx/patches/inkling2/dspark.py
index 9f409727b1..4a5dd3ac1d 100644
--- a/omlx/patches/inkling2/dspark.py
+++ b/omlx/patches/inkling2/dspark.py
@@ -25,6 +25,7 @@
logger = logging.getLogger(__name__)
DRAFT_FILENAME = "mtp.safetensors"
+BUNDLED_DSPARK_MODEL_TYPES = frozenset({"inkling2", "inkling2_loop"})
def bundled_inkling2_dspark_path(model_path: str | Path) -> Path | None:
@@ -36,7 +37,7 @@ def bundled_inkling2_dspark_path(model_path: str | Path) -> Path | None:
except (OSError, json.JSONDecodeError):
return None
mtp = config.get("mtp_config") or {}
- if config.get("model_type") != "inkling2" or not mtp or not weights.is_file():
+ if config.get("model_type") not in BUNDLED_DSPARK_MODEL_TYPES or not weights.is_file():
return None
if mtp.get("markov_head_type") != "rnn_hidden":
return None
diff --git a/omlx/patches/inkling2/loop.py b/omlx/patches/inkling2/loop.py
index ab015db74c..1e5c3fa713 100644
--- a/omlx/patches/inkling2/loop.py
+++ b/omlx/patches/inkling2/loop.py
@@ -60,8 +60,6 @@ def _make_layer(self, args, index, w13, w2):
return Inkling2Layer(args, index, w13, w2, message_rank=rank)
def __call__(self, inputs, cache=None, input_embeddings=None, capture=None):
- if capture:
- raise ValueError("Inkling 2 Mini does not support speculative decoding.")
h = (
self.embed_norm(self.embed(inputs))
if input_embeddings is None
@@ -84,6 +82,9 @@ def __call__(self, inputs, cache=None, input_embeddings=None, capture=None):
)
h, blocks = pre_h, list(pre_blocks)
for layer in layers:
+ # The draft indexes execution visits, not physical layers.
+ if capture is not None and index in capture:
+ capture[index] = h
messages = None
if previous is not None:
query = self.message_query[layer - self._plan.start]
@@ -95,4 +96,7 @@ def __call__(self, inputs, cache=None, input_embeddings=None, capture=None):
h = self.layers[layer](h, blocks, cache=entry, messages=messages)
index += 1
x = self.final_input(blocks, _unit_rms(h.astype(mx.float32)))[:, :, 0]
- return self.norm(x).astype(h.dtype)
+ out = self.norm(x).astype(h.dtype)
+ if capture is not None and index in capture:
+ capture[index] = out
+ return out
diff --git a/omlx/utils/model_loading.py b/omlx/utils/model_loading.py
index b6558dce7d..92bf5bd719 100644
--- a/omlx/utils/model_loading.py
+++ b/omlx/utils/model_loading.py
@@ -1001,19 +1001,18 @@ def maybe_apply_pre_load_patches(
dflash_batched = dflash_batched_supported(
model_type, "vlm" if for_vlm else "batched"
) and dflash_batched_requested(model_settings, model_name)
- minimax_dspark = None
+ bundled_dspark = None
if for_vlm and (
model_type in minimax_m3_types or text_model_type in minimax_m3_types
):
from ..patches.minimax_m3_dspark import bundled_dspark_path
- minimax_dspark = bundled_dspark_path(model_name)
- if model_type == "inkling2":
+ bundled_dspark = bundled_dspark_path(model_name)
+ elif for_vlm and model_type in ("inkling2", "inkling2_loop"):
from ..patches.inkling2.dspark import bundled_inkling2_dspark_path
- # Inkling 2 bundles its DSpark draft as mtp.safetensors.
- minimax_dspark = bundled_inkling2_dspark_path(model_name)
- if _is_mtp_compatible(config, model_type) or dflash_batched or minimax_dspark:
+ bundled_dspark = bundled_inkling2_dspark_path(model_name)
+ if _is_mtp_compatible(config, model_type) or dflash_batched or bundled_dspark:
mtp_requested = bool(
model_settings is not None and getattr(model_settings, "mtp_enabled", False)
)
@@ -1024,7 +1023,7 @@ def maybe_apply_pre_load_patches(
# is disabled so strict mlx-vlm loading remains lossless.
mtp_enabled = (
(
- bool(mtp_requested and minimax_dspark)
+ bool(mtp_requested and bundled_dspark)
or _native_vlm_mtp_eligible(
config,
model_type,
@@ -1092,7 +1091,7 @@ def maybe_apply_pre_load_patches(
else:
set_mtp_depth(3)
if mtp_enabled:
- if minimax_dspark is not None:
+ if bundled_dspark is not None:
backend = "bundled DSpark"
elif _has_dspark_heads(config):
backend = "embedded DSpark"
@@ -1688,7 +1687,7 @@ def lightning_mtp_supported(model_path: str | Path) -> bool:
if str(quantization.get("quant_method") or "").lower() == "paroquant":
return False
model_type = config.get("model_type")
- if model_type == "inkling2":
+ if model_type in ("inkling2", "inkling2_loop"):
from ..patches.inkling2.dspark import bundled_inkling2_dspark_path
return bundled_inkling2_dspark_path(model_path) is not None
diff --git a/tests/test_inkling_vlm_mtp.py b/tests/test_inkling_vlm_mtp.py
index 64c860f2ad..f5d7dba394 100644
--- a/tests/test_inkling_vlm_mtp.py
+++ b/tests/test_inkling_vlm_mtp.py
@@ -588,6 +588,70 @@ def test_inkling2_mini_keeps_each_pass_cache_and_reuses_layers():
assert not mx.array_equal(cache[4][0].keys, cache[6][0].keys).item()
+@pytest.mark.parametrize(
+ ("formats", "incremental"),
+ [(("mxfp8",) * 6, True), (("nvfp4",) * 4 + ("mxfp8",) * 2, False)],
+ ids=["mxfp8-single-token", "mixed-chunked"],
+)
+def test_inkling2_mini_dspark_captures_and_rolls_back_every_visit(formats, incremental):
+ model = _inkling2_tiny(
+ formats=formats,
+ n_layers_per_attn_res_block=2,
+ local_layer_ids=[0, 2, 4],
+ loop_config=dict(core_start=2, core_end=4, num_passes=3, gate_rank=8),
+ )
+ ids = mx.random.randint(0, 300, (1, 21))
+ cache, reference = model.make_cache(), model.make_cache()
+ model(ids[:, :12], cache=cache)
+ model(ids[:, :12], cache=reference)
+ verified = model(
+ ids[:, 12:20], cache=cache, return_hidden=True, capture_layer_ids=[1, 5, 7, 10]
+ )
+ assert len(verified.hidden_states) == 5
+ assert not mx.array_equal(verified.hidden_states[1], verified.hidden_states[2]).item()
+ assert mx.array_equal(verified.hidden_states[3], verified.hidden_states[4]).item()
+ assert model.rollback_speculative_cache(cache, None, 3, 8) == 3
+ if incremental:
+ for t in range(12, 16):
+ model(ids[:, t : t + 1], cache=reference)
+ else:
+ # A chunked reference isolates rollback from NVFP4 batch-shape rounding.
+ model(ids[:, 12:16], cache=reference)
+ for visit, (actual, expected) in enumerate(zip(cache, reference)):
+ assert actual[0].offset == expected[0].offset == 16
+ for actual_kv, expected_kv in (
+ (actual[0].keys, expected[0].keys),
+ (actual[0].values, expected[0].values),
+ ):
+ assert mx.allclose(actual_kv[..., :16, :], expected_kv[..., :16, :], atol=1e-4)
+ for slot in range(4):
+ delta = mx.abs(actual[1][slot] - expected[1][slot]).max().item()
+ assert delta < 1e-4, (visit, slot, delta)
+ logits = model(ids[:, 16:17], cache=cache)[..., :300]
+ expected_logits = model(ids[:, 16:17], cache=reference)[..., :300]
+ assert mx.allclose(logits, expected_logits, atol=1e-4)
+
+
+def test_inkling2_mini_lightning_mtp_requires_bundled_draft(tmp_path):
+ import json
+
+ from omlx.model_settings import ModelSettings
+ from omlx.utils.model_loading import lightning_mtp_supported
+
+ (tmp_path / "config.json").write_text(
+ json.dumps(
+ {
+ "model_type": "inkling2_loop",
+ "mtp_config": {"markov_head_type": "rnn_hidden"},
+ }
+ )
+ )
+ assert not lightning_mtp_supported(tmp_path)
+ (tmp_path / "mtp.safetensors").touch()
+ assert lightning_mtp_supported(tmp_path)
+ assert not ModelSettings().mtp_enabled
+
+
def test_inkling2_mini_loads_original_packed_checkpoint(tmp_path):
import json
from dataclasses import asdict