Skip to content

feat(lm): add bounded Qwen3.8 inference and mlx.fast kernel ports - #154

Merged
Brooooooklyn merged 12 commits into
mainfrom
codex/qwen38-flash-next-opt
Sep 17, 2026
Merged

Brooooooklyn merged 12 commits into
mainfrom
codex/qwen38-flash-next-opt

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Adds Qwen3.8-Flash-Next (qwen4_exp) to loadModel() and loadSession() for HF directories and split GGUF checkpoints. Large checkpoints use bounded resident weights and SSD reads for cold experts, preserving the imported quantized codes.

Implementation

  • Port mlx.fast prefill and decode work: expert staging, validated device routes, normalization/GDN/mixer fusions, cached kernel graphs, bounded asynchronous completion, and optional attention output gating. Preserve quantization, rounding and request-state boundaries.

  • Admit fixed projections and expert slots from tensor sizes, RAM and live headroom. Keep bounded reads, system reserves, process-wide wired-limit leases, and partitioned Metal residency sets.

  • Add paged scheduling, continuation, cancellation, opt-in native MTP, and bounded image input using matching auxiliary weights.

  • Move the shared Qwen vision stack into vision/qwen: image processing, encoder/weight loading, prompt expansion, M-RoPE, and the dense/MoE feature cache and memory planner. All three Qwen families import it directly; remove the former family-owned modules and move their numerical regressions with the implementation. Generic image extraction also serves Qianfan OCR through engine/vision.

  • Organize custom Metal shaders into metal/common/ and metal/qwen4/. Share thirteen formerly Qwen4-prefixed operations, quantized preamble builders and the precise-sigmoid helper; keep fixed routing/head geometry and four-stream mixer fusions in the family folder. Preserve arithmetic and dispatch policy, document reuse contracts, and remove two unreferenced tape shader templates.

  • Keep discovery policy in the existing family registry and use one GGUF discovery path for files and directories. Include Qwen4 image capability and first split discovery while preserving other families' loader restrictions. Exclude generated tokenizer asset directories, and key those assets with the shared source identity so same-size/same-mtime checkpoint replacement cannot reuse stale tokenizer/config files.

  • Expose Qwen4 supportsImages() and exact expandedPromptTokenCount() using the same processor/limits as inference. Release empty owners after failed media requests, retain existing usable history, and resolve split GGUF paths with mixed extension casing.

  • Consolidate GDN/shared-expert projections and native BF16 SiLU tables. Remove duplicated hidden-state bookkeeping, unused residency hooks, a test-only shared-prefill FFI, unreachable injection shader variants, obsolete wrappers and one-off logit export. Preserve numerical coverage through production entry points. Copy Metal residency errors before their autorelease pool drains.

  • Generate Qwen4 tokenizer/config assets in the shared writable native GGUF application cache, so read-only checkpoint directories load without sibling writes. Reuse MLX_NATIVE_GGUF_CACHE_DIR, XDG/OS cache selection and temporary-directory fallback; preserve source-identity invalidation and atomic publication.

Family-specific HC, hashed PLE, routed-expert storage and dispatch policy stay in Qwen4. Reusable shaders retain explicit storage and precision contracts in the common module. The existing scheduler, paged cache, stream limits and Metal library cache remain shared. No compatibility aliases, standalone experiment scripts, temporary files or additional research reports are added.

Performance

The 95% target is not achieved. A previous optional configuration measured 2412.472 prefill and 58.078 decode tokens/s: 96.0% / 91.8% of the then-published reference. The refreshed reference's raw fields imply 2510.433 / 64.151 tokens/s; a later four-port candidate measured 2294.530 / 55.364 and did not show a repeatable paired gain. The newest attention-gate port has correctness coverage but no uncontended throughput result. New experimental ports remain off by default; the rejected MoE replay prototype is archived outside the PR.

These are different checkpoints, and the published-rate comparison is not a matched engine/checkpoint/private-prompt comparison. The standard workload was 1024 input / 128 output tokens, two warmups and three measured requests per process. Coding-prompt rates and incomplete BF16/PLE validation are documented separately. This architecture follow-up makes no new performance claim.

The consolidated research report records reference revisions, settings, hashes, retained and rejected ports, measured ranges and validation limits. The original support change advances MLX to 6908f3fd2; the optimization/refactor work does not advance it again.

Validation

  • Reproduced the read-only-source failure through the packaged addon before fixing it. The new regression verifies complete, reusable assets in a separate cache, unchanged source bytes, no sibling writes and no leftover staging directories; source-identity invalidation and shared cache-selection tests pass.
  • Canonical native build and both packaged Metal-library smoke checks passed; both generated declaration copies match. Repeated after the whole-branch review cleanup, along with 47 Metal-library selection tests. The preceding shader audit checked all 45 relocated shader bodies for preserved arithmetic/layout after accounting for renamed helpers, comments and compile-time assertions.
  • Strict all-target Clippy for mlx-core/mlx-sys, workspace TypeScript checking, and formatting/type-aware lint for changed TypeScript sources passed.
  • Release core unit suite after review cleanup: 3577 passed, 122 ignored, with three existing debug-assertion-only checks excluded for release builds. Coverage includes same-size/same-mtime checkpoint replacement, the shared vision stack, Qwen4 kernel parity, split GGUF payloads, repeated sync/stream media failures, and preservation of usable state after cancellation. The residency failure-path ownership fix was inspected and compiled; a driver allocation failure was not forced.
  • Review cleanup: ten selected loader/discovery/registry/session suites passed 150 tests, including exclusion of completed and in-progress GGUF asset directories while retaining the source checkpoint.
  • Batched-prefill reference parity passed with GDN gate pairing and compact gate inputs enabled separately and together, across F32/BF16 SafeTensors/GGUF fixtures and continuation boundaries.
  • After merging main: eleven affected TypeScript suites passed 225 tests, including Qwen4 image/first-split discovery, converted-checkpoint preference, header/config disagreement, and incomplete-scan reporting and recovery.
  • Before the shader-folder refactor, the exact-arithmetic full-checkpoint smoke passed 11 requests covering AR, streaming continuation, native/adaptive MTP, concurrent owners, cancellation recovery, and image continuation/change. Public capability/token-count checks and eight rejected malformed-image owners also passed before valid image requests.
  • The unchanged 63 GiB cap admitted 60 GiB / 345 expert slots with current live headroom. Peak physical footprint was 61.96 GB; all 1365 pages were free after reset and state reservations were zero. This smoke overlapped compilation and is correctness-only.

Evidence and immutable build artifacts are retained outside the repository under ~/Library/Caches/mlx-node/qwen4-reference-gap-20260917/architecture-*; shader-refactor logs are under ~/Library/Caches/mlx-node/metal-layout-20260917/, and whole-branch review validation is under ~/Library/Caches/mlx-node/branch-review-20260917/. No standalone test/benchmark scripts or temporary files are committed.

Paged inference requires macOS Metal. MTP is opt-in; audio, video and image-bearing MTP are unsupported. Full BF16 generation and real-model contexts beyond 2048 tokens remain unvalidated. Remote CI for the new head is separate from local validation.


Note

High Risk
Large new inference path (MoE routing, SSD residency, paged cache, vision/MTP) plus a cross-family vision refactor that touches Qwen3.5 load and prefill behavior.

Overview
Adds Qwen3.8-Flash-Next as qwen4_exp / qwen4_exp_text: new Rust model family with bounded SSD weight residency, paged scheduling, opt-in native MTP, chat/stream/cancel NAPI (Qwen4ExpModel), and auxiliary-checkpoint validation for vision/MTP weights omitted from GGUF. The hybrid scheduler can attach an optional wired memory limit per family during scheduled turns.

Refactors Qwen3.5 dense/MoE vision into a shared vision/qwen module (encoder, processor, prompt expansion, feature cache); dense/MoE loaders and expanded_prompt_token_count call the shared helpers instead of family-local code. Qianfan OCR pulls image bytes via engine/vision::extract_images_from_messages.

Docs/registry: README lists the SSD model row; loader tests register qwen4_exp aliases. Minor fixes: deep_copy keeps zero Metal buffer offset after source drops; gated-delta Metal include path update.

Reviewed by Cursor Bugbot for commit 9856561. Bugbot is set up for automated code reviews on this repo. Configure here.

@coderabbitai

coderabbitai Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: 743aa770-867b-41ca-ba7b-8df6f75ea817

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-17T07:17:37.428610Z 9856561 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@cursor

cursor Bot commented Sep 15, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_ab150b88-d43f-4669-bcbe-3cfd47106e5b)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 51bb619914

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@cursor

cursor Bot commented Sep 16, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_91f463e3-5544-4b82-9491-b9a07fac9b09)

@Brooooooklyn Brooooooklyn changed the title feat(lm): support Qwen3.8-Flash-Next with bounded SSD inference feat(lm): add bounded Qwen3.8 inference and mlx.fast kernel ports Sep 16, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f76ee4bed6

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread packages/lm/src/family-data.ts Resolved
@cursor

cursor Bot commented Sep 16, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_4079c87a-f3e9-464a-80cb-2d0645e5a375)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: cb10e804b9

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread packages/lm/src/family-data.ts Resolved
@cursor

cursor Bot commented Sep 16, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_5f2757c7-bc34-4160-bad3-ffab06cbc318)

@cursor

cursor Bot commented Sep 17, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_9394be73-732c-42d6-8834-dc132ce7161b)

@cursor

cursor Bot commented Sep 17, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_a55ebd60-5818-4fff-aa89-e699dbb3bbb4)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d09c975fe4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@cursor

cursor Bot commented Sep 17, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_fbf062f1-fa01-491a-be2f-7bf59696bfa2)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4dff326afd

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@cursor

cursor Bot commented Sep 17, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_a3a3b6fe-00ec-44fa-865d-2970e9d38cf9)

@cursor

cursor Bot commented Sep 17, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_c8cefd15-62a9-4ffa-973c-e299108cd374)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5d2502c261

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@cursor

cursor Bot commented Sep 17, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_e71edfb1-fe9c-42f0-9642-616b3521a3b5)

@cursor

cursor Bot commented Sep 17, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_1b2d968a-c239-4506-8516-0b219646ccf4)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8f4f322bec

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@cursor

cursor Bot commented Sep 17, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_27ad7aea-60b2-4829-86cd-e44f19e7f106)

@Brooooooklyn
Brooooooklyn merged commit 1787380 into main Sep 17, 2026
8 checks passed
@Brooooooklyn
Brooooooklyn deleted the codex/qwen38-flash-next-opt branch September 17, 2026 09:24
Brooooooklyn added a commit that referenced this pull request Sep 17, 2026
#154 landed overlapping work: Q5_1 import (same math, different
structure) and a family-data-driven GGUF discovery policy replacing
this branch's hardcoded modelType lists. Kept this branch's
words_per_block generalization while adopting main's split_last shape
handling (its new clippy deny forbids the unwrap), moved the qwen3_5_moe
XL policy into ggufDiscovery, and kept mtp in GGUF_COMPANION_NAME plus
the isGgufCompanionName export the CLI and dashboard consume.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
robert-johansson pushed a commit to robert-johansson/mlx-node that referenced this pull request Oct 3, 2026
Upstream's metal-residency overlay (mlx-node#154) defines CMAKE_PROJECT_INCLUDE to
the overlay file when Metal builds and to "" otherwise, intending to clear
a cached include. CMake resolves the empty value to the current directory
and every project() call — MLX's and each FetchContent dependency's — then
fails with "project requested file is a directory". Upstream only builds
on macOS, where the overlay branch always runs; on CUDA/Linux this broke
the whole native build. Drop the define on the non-overlay path (a build
dir that flips Metal→CPU on one host keeps the stale include, which only
touches Metal files). Upstream-PR candidate.
robert-johansson pushed a commit to robert-johansson/mlx-node that referenced this pull request Oct 3, 2026
Upstream mlx-node#138/mlx-node#154 moved every family's inherent impls out of model.rs into
model/{forward,flat_turn,paged_turn,lifecycle,commands,...}.rs and routes
napi calls through ModelCommand<FamilyCommand>. Our per-step surface lived
in the deleted regions, so it is re-homed rather than merged:

- qwen3_5/model/genmlx_surface.rs (new): forward / forwardWithCache bodies
  (bean mlx-2h4l Tier 1); initCaches is upstream's own init_caches_sync.
- qwen3_5_moe/model/genmlx_surface.rs (new): the same plus the Tier-2
  branchable caches (branchCache/branchFrom/forwardBranch/disposeBranch,
  bean mlx-19wy), the flat image prefill (vlmPrefillFlat, beans mlx-ll7n /
  genmlx-52mh) with its rope-shifted continuation helpers, and the vision
  debug tap (vlmVisionFeatures, genmlx-w3og) — adapted to vision::qwen,
  engine::ImageCacheDigest and Stream::generation().
- Family command variants + execute arms in both model/commands.rs
  (BranchSource now lives there); Qwen3 dense gets its three arms back.
- The surviving napi methods send FamilyCommand variants; branch_caches /
  next_branch_id are initialized in the MoE constructor; Qwen3 dense drops
  our generation_stream field for upstream's thread-local Stream::generation.
- layer_cache: Qwen3_5LayerCache::restore and restore_all are production
  code again (the branch fork needs them; upstream test-gated them), and
  upstream's new rewind sites learn our fork-snapshot keys/values fields.
- Dead survivors removed: VisionContinuation + vlm_prepare_vision_continuation
  and the dense draft loaders (flat VLM chat on CUDA is deferred to
  genmlx-7yi2; two-model draft retired in c1ac455); the MoE image-prefix
  bookkeeping fields nothing read any more.
- mlx-sys lib.rs: close our FFI extern block before upstream's (merge union
  had swallowed the brace); genmlx-core: QwenImageProcessor moved to
  vision::qwen::processing; MoE merge-synthesized qkvz prefixes threaded
  into apply_weights_moe_inner and its tests.
- Our two flat-VLM chat integration tests (ignored, env-gated) track
  upstream's ChatConfig.cache_salt and async reset_caches so the test
  target still compiles.

cargo check -p mlx-core -p genmlx-core --tests: 0 errors (scratch worktree,
mlx e947e13d8, CUDA sm_120).
Brooooooklyn added a commit that referenced this pull request Oct 22, 2026
…, MTP draft banks, flag purge, device-route MTP verify, draft-side levers, pack stream pool (Phase 3 + Phase 4 + Phase 5 L2) (#297)

> **Ready for review.** Stacked on #294 (`perf/qwen4-sparse-prefill`,
`912eda8c9`, 5 commits over main). Head `c1ac42df3`, rebased onto main
`61a706829` on 2026-10-22, 80 commits over #294. Stack #309: #294 → #297
→ #295, all three ready for review. The timing build is `a706d8058`
(pre-rebase). Later commits changed no mapped-path bits: the unit
digests and D3 6k were rerun on every later head (P5/X/A, P5/Z,
CLEANUP/PART2). Stage III adds L2c (MTP draft bank built at load), #8
(PLE key/value rows four per row-kernel call), #7 (mixer activation K
walk over eight simdgroups, split8) and c2 (a cold prompt runs
layer-major over the streaming pack). Text is unchanged: the same 6k /
16k shas, AR == MTP. The slot residency path now gives the same tokens
as the mapped path (P5-X), which closes the Codex Stage III finding. The
indirect expert prefill runs eagerly (closes Codex pass 2, compile-cache
growth); five MTP draft-bank tests pass on the 7 GB CI runner; the
cleanup drops the finished A/B switches and research-only tests. Stage
II (FINAL4, 2026-10-21) is ahead of llama.cpp b11717 on every decode row
and every warm or 16k prefill row. With c2 the immediate cold 6k request
drops from 11.7-12.4 s to 6.9-7.1 s, at the top of llama.cpp's 6.0-7.0 s
band. FINAL5 (2026-10-22, `a706d8058`) ran 10 timing rows + 1 trace row,
all still loaded-host (foreign GPU 31.4-44.5 % mean; one row 10.6 %).
Stage III cold 6k TTFT: AR 6.92 s (0.87x ; 0.92x, behind), MTP-2 6.92 s
(1.01x ; 0.94x, parity).

## Goal

Qwen3.8 Flash Next must run from SSD streaming on a single 128 GB Mac at
llama.cpp speed or better, with identical text and no experiment flags.

## Design in one picture

```
load:   dense banks -> MTP draft bank (L2c) -> pack stream starts (8 workers, 4 MiB preads, layer order)
cold turn over a streaming pack (c2):
        layer 0: window 1 .. window N   <- the stream reads layer 1, 2, ... meanwhile
        layer 1: window 1 .. window N      each expert bank binds once per prompt
        ...                                tail under 256 rows: its own pass after the group
warm turn / resident pack:  window-major as before (1024-token windows)
decode: mapped banks, R-row exact kernels for MTP-2 verify (#8 PLE rows, #7 split8 mixer)
```

Same windows, kernels and per-window shapes in both orders, so the bits
do not depend on the loop order (D3 group vs window: max_ulp 0).

## Result vs llama.cpp b11717 (Stage III `a706d8058`, addon
`7ac1d006e53b`, FINAL5; Stage II `9cd299141`, FINAL4)

Same machine, page cache evicted before every run (a cold request reads
the whole 73 GiB pack), one process per run, empty `MLX_*` environment,
no addon swap, 0 in-request Metal compiles in all 12 timing runs. Three
requests per process: cold 6k, 16k, warm 6k. Ranges over 2 AR + 3 MTP-2
accepted runs. llama.cpp is not re-run per round: the reference rows are
the stored clean runs of 2026-10-20 and 2026-10-21 on this machine
(`LLAMA-REFERENCE.md`); each ratio gives the 2026-10-21 row first. In
FINAL4 a foreign-load gate (> 300 % foreign CPU or a compiler alive in >
50 % of a request window) re-ran 7 attempts and kept them out of every
number.

FINAL5 (2026-10-22) adds a wired-drop gate per request, a 20 s GPU
sample before launch (idle = every sample < 10 %), and 40 s idle after
the last turn with the process loaded.

Caveat for Stage III: 0 of 10 rows had an idle GPU (foreign GPU mean
31.4-44.5 %, one row 10.6 %); vm pressure normal and thermal nominal on
every sample; 3 load-gate reruns (OrbStack, a foreign rustc, Firefox +
XProtect), each rerun passed all gates.

| Metric | Stage III (FINAL5), range (mean) | Stage II (FINAL4) | Stage
I (`9a8d1e220`) | llama.cpp AR (`FINAL4-llama-off-1` ;
`FINAL3-llama-off-1`) | llama.cpp MTP-2 (`FINAL4-llama-on-1` ;
`FINAL3-llama-on-2`) | Stage III ratio (2026-10-21 ref ; 2026-10-20 ref)
| Stage II ratio (2026-10-21 ref ; 2026-10-20 ref) |
|---|---|---|---|---|---|---|---|
| Warm 6k prefill, tok/s | AR 1,323.7-1,360.7 (1,342.2); MTP
1,201.8-1,285.0 (1,254.5) | AR 1,197-1,215; MTP 1,231-1,298 | AR
1,112-1,161; MTP 1,116-1,241 | 896 ; 853 | 843 ; 852 | AR **1.50x ;
1.57x**, MTP **1.49x ; 1.47x** | AR **1.35x ; 1.41x**, MTP **1.50x ;
1.48x** |
| 16k prefill, tok/s | AR 1,107.0-1,139.0 (1,123.0); MTP 1,079.6-1,116.9
(1,094.0) | AR 1,086-1,122; MTP 985-1,103 (1,070-1,103 without the
host-event row, see gaps) | AR 909-1,001 (both rows disturbed by foreign
load); MTP 1,088-1,146 | 946 ; 872 | 863 ; 907 | AR **1.19x ; 1.29x**,
MTP **1.27x ; 1.21x** | AR **1.17x ; 1.27x**, MTP **1.22x ; 1.16x** |
| Cold 6k prefill, tok/s | AR 897.5-899.8 (898.6); MTP 897.6-900.0
(899.1) | AR 539-541; MTP 515-521 | AR 473-476; MTP 442-459 | 1,034 ;
975 | 889 ; 955 | AR 0.87x ; 0.92x (behind), MTP 1.01x ; 0.94x (parity)
| AR 0.52x ; 0.55x, MTP 0.58x ; 0.54x |
| AR decode, steady tok/s (cold 6k / 16k / warm 6k) | 48.09-49.55 /
47.42-48.69 / 49.79-50.87 (48.82 / 48.05 / 50.33) | 52.5-55.0 /
51.2-52.3 / 52.5-53.4 | 51.2-51.8 / 44.0-49.7 / 50.4-51.7 | 45.0 / 43.5
/ 43.6 ; 42.0 / 40.7 / 42.6 | – | **1.08x / 1.10x / 1.15x ; 1.16x /
1.18x / 1.18x** (worst run 1.07 / 1.09 / 1.14 ; 1.14 / 1.16 / 1.17) |
**1.19x / 1.19x / 1.21x ; 1.28x / 1.27x / 1.24x** |
| MTP-2 decode, steady tok/s (cold 6k / 16k / warm 6k) | 73.71-74.12 /
70.38-71.61 / 74.72-75.68 (73.97 / 70.95 / 75.28) | 72.7-78.4 /
75.9-76.6 / 77.5-79.8 | 74.0-76.3 / 70.5-74.8 / 73.8-79.0 | – | 72.0 /
67.6 / 68.7 ; 71.7 / 69.4 / 71.5 | 1.03x / 1.05x / **1.10x** ; 1.03x /
1.02x / **1.05x** (worst run 1.02 / 1.04 / 1.09 ; 1.03 / 1.01 / 1.04) |
**1.05x / 1.13x / 1.15x ; 1.05x / 1.10x / 1.10x** (worst run 1.01 / 1.12
/ 1.13) |
| Cost per step, ms (AR step / MTP-2 cycle) | 20.4 / 36.6 | 18.9 / 34.9
| 20.1 / 35.2 | 22.7 ; 23.9 | 39.4 ; 38.6 | AR 1.11x ; 1.17x, MTP 1.08x
; 1.06x | |
| 16k TTFT, per request | AR 16.47-16.94 s (16.70); MTP 16.79-17.37 s
(17.15) | AR 16.7-17.3 s; MTP 17.0-19.1 s | AR 18.7-20.6 s; MTP
16.4-17.2 s | 19.8 ; 21.5 s | 21.7 ; 20.7 s | **1.19x ; 1.29x** /
**1.27x ; 1.21x** faster | **1.17x ; 1.27x** / **1.22x ; 1.16x** faster
|
| Cold 6k TTFT, per request | AR 6.91-6.93 s (6.92); MTP 6.91-6.93 s
(6.92) | AR 11.50-11.54 s; MTP 11.94-12.08 s | AR 13.1-13.2 s; MTP
13.6-14.1 s | 6.01 ; 6.38 s | 7.00 ; 6.51 s | AR 0.87x ; 0.92x (behind),
MTP 1.01x ; 0.94x (parity) | 0.52x ; 0.55x / 0.58x ; 0.54x |
| Warm 6k TTFT, per request | AR 4.57-4.70 s (4.63); MTP 4.84-5.17 s
(4.96) | AR 5.12-5.20 s; MTP 4.79-5.05 s | | 6.94 ; 7.30 s | 7.38 ; 7.30
s | AR **1.50x ; 1.58x**, MTP **1.49x ; 1.47x** | |
| Cold 6k TTFT, request 8 s after load (1 run per arm) | AR 6.94 s; MTP
6.16 s | AR 7.38 s; MTP 8.41 s | not run | 6.01 ; 6.38 s | 7.00 ; 6.51 s
| AR 0.87x ; 0.92x, MTP **1.14x ; 1.06x** (1 run, lighter foreign GPU:
10.6 %) | 0.81x ; 0.86x / 0.83x ; 0.77x |
| Cold 6k TTFT, from load start | AR 9.73-9.94 s (9.83); MTP 9.74-9.89 s
(9.81) | AR 13.7-14.0 s; MTP 14.0-14.3 s | 15.1-15.2 / 15.5-16.1 s |
36.1 ; 34.4 s | 39.1 ; 35.6 s | AR **3.67x ; 3.50x**, MTP **3.98x ;
3.62x** faster | **2.5-2.6x / 2.5-2.8x faster** |
| Peak footprint | AR 10.7-12.1 GiB; MTP 11.3-12.1 GiB (L2c bank in both
arms) | AR 7.9-9.2 GiB; MTP 11.3-11.4 GiB | 7.9-9.2 / 11.4-11.7 GiB |
1.5-1.6 GiB footprint + 78 GiB mmap | 2.4-2.5 GiB + 82 GiB mmap | | |
| 16k + 40 GiB touching hog, MTP-2 | not run in FINAL5 (c2 gates: slots
225, 64/64) | completes 64/64 on the slot fallback (174 slots at 54.6
GiB available; 11.0 tok/s, 39/46 drafts accepted) | 64/64 (218 slots,
14.7 tok/s) | not run | | | |

- Text is identical in every run, AR == MTP (6k `bfb8e8bb3bd0c768`, 16k
`6a63463a98644df6`); none of the Stage II changes moved one token. MTP-2
acceptance 0.823 -> 0.847 (2.656 -> 2.684 tokens per cycle; by position
0.905 / 0.787 at 6k, 0.926 / 0.766 at 16k). FINAL5: the same two shas on
all 30 requests of the 10 rows, MTP 95 / 189 / 160 on every MTP request,
the same acceptance by position.
- Stage III vs llama: ahead on warm 6k and 16k prefill / TTFT in both
arms and on AR decode (1.08-1.18x). MTP-2 decode: cold 6k and 16k parity
(1.03x ; 1.03x and 1.05x ; 1.02x), warm 6k ahead (1.10x ; 1.05x). Cold
6k TTFT: AR behind (6.91-6.93 s = 0.87x ; 0.92x, llama 6.01 ; 6.38 s),
MTP-2 parity (1.01x ; 0.94x).
- Stage II -> Stage III (FINAL4 -> FINAL5): cold 6k TTFT AR -39.9 % /
MTP -42.3 %; warm 6k TTFT AR -10.2 %. AR decode 7-9 % lower (cold 6k
-9.2 %, 16k -7.1 %), MTP-2 16k decode -7.1 %; AR step 18.9 -> 20.4 ms,
MTP cycle 34.9 -> 36.6 ms. Load AR +25.1 %, MTP +34 % (L2c builds the
bank at load). AR peak +2.5-2.9 GiB (the AR arm holds the 2.83 GiB MTP
bank). The decode drop is open (see gaps).
- Stage I -> Stage II under the same protocol: cold 6k TTFT -1.6 s (AR)
/ -1.9 s (MTP), MTP-2 decode +0.3 / +4.3 / +2.3 %, MTP cycle 35.2 ->
34.9 ms, load 2.0 -> 2.3 s (the pack stream starts at load). The AR 16k
and AR decode differences come from foreign load on the Stage I rows,
not from code.
- Wired memory: Stage II 87-91 GiB in a turn, 6-8 GiB within 5-55 s
after exit (all 8 mapped runs). Stage III (FINAL5): 87.6-90.6 GiB in a
turn, 6.7-7.3 GiB 1 s after exit, 6.7-7.4 GiB at turn end + 35 s with
the process loaded (no hold).

## Phase 5 Stage III (`c2e7bba65`, `2fc0426c5`, `ca51f4692`,
`bfa046494`, `a41bf6a7a`, `2e12d1beb`, `3bdca3614`, `8cfc05371`,
`e98d4c733`, `0df94ece6`, `142cff3e0`, `734430a6f`, `299b4defb`,
`071588e44`, `12f7fdb74`, `3c0d8a5a1`)

Headings and commit columns name commits at `3c0d8a5a1`. Result rows
name the measured pre-rebase trees: L2c `313430e52`, #8 `4e7b3608b`, #7
`52611c9d2`, c2 `829f474cf` / `57512c0b9` / `748389987`, T11
`a706d8058`, P5-X `a95cb2492` / `1b90c2e62`, Stage II `9cd299141`, Stage
I `9a8d1e220`.

All timing below is loaded-host (foreign GPU ~40 % mean before launch;
the GPU-idle rule failed on every row, FINAL5 included). Rows marked
REJECT also failed the CPU load gate. Text shas 6k `bfb8e8bb3bd0c768` /
16k `6a63463a98644df6` on every mapped run, AR == MTP, MTP 95 / 189 /
160 on every request.

| Commit | What | Measured effect (run tag) |
|---|---|---|
| L2c `c2e7bba65` | The Q8 MTP draft bank (2.83 GiB) is built at load,
after the dense banks and before the pack stream. No turn builds
anything. A declined build warns and the load goes on. | MTP request 8 s
after load: 6k TTFT 8.41 -> 7.32 s, request SSD 5.77 -> 1.07 GiB. MTP
immediate: 11.94-12.08 -> 11.62 s, request SSD 77.2 -> 72.5 GiB (FINAL4
MTP rows -> `L2C-after-d8-on-1`, `L2C-after-on-1`, both loadcheck OK).
Cost: with the aux attached the AR arm also holds the 2.83 GiB bank and
reads 4.7 GiB more at load (+0.5-1.0 s load). |
| #8 `2fc0426c5` | A prefill window projects PLE key and value through
the exact row kernel in 4-row groups (256 calls per 1024-token window)
instead of one M=1 gather GEMV per token. MTP verify projects all rows'
PLE in one call. | 16k TTFT AR 17.50 -> 17.08 s (last interleaved pair),
MTP 17.68-17.95 -> 17.40-17.47 s; warm 6k TTFT AR 4.97 -> 4.57 s, MTP
4.86 -> 4.60 s (`PLEHC-*`, see the table below). Bit-identical: probe
B-8 0 differing values; 2 new bitwise tests. |
| #7 `ca51f4692` | The decode mixer activation (HC down, Q8 320 x 10240)
runs eight simdgroups per output. Each stores its block terms; simdgroup
0 adds all 40 in the old order. The partial-sum form is not exact and is
not used. | MTP-2 decode 70.65 -> 71.51 tok/s, cycle 38.15 -> 37.71 ms
(ranges do not overlap). AR decode 49.17 -> 49.39 tok/s: ranges overlap,
not measurable (`PLEHC-*`). Kernel alone: 12.21 / 18.25 -> 10.37 / 11.79
us at 1 / 3 rows (probe B-7, 0 differing values). |
| c2 engine `bfa046494` | The scheduler can give a cold turn one
whole-prompt prefill step (per-family hook, default off). A K/V write
entry takes chunks anywhere above a recorded floor; the strict suffix
entry stays. Row fetch: 32 readers (was 4), pending limit 1 << 20 (was 1
<< 16). | Enables c2; no timing on its own. |
| c2 qwen4 `a41bf6a7a` | A turn that opens over a streaming mapped pack
prefills as one group: every 1024-token window at layer 0, then at layer
1, and so on. A trip between sweeps evaluates the group first, then
leaves the mapped path. | Immediate cold 6k AR 12.43 / 16.03 -> 6.98 /
7.05 s, MTP 11.73 / 11.94 -> 7.09 / 6.89 s (`C2G-G1*`, `C2G-G1b*`).
Rebased head: AR 6.93 s, MTP 6.94 / 6.90 s (`C2INT-*`). See the c2
table. |
| c2 tests `2e12d1beb` | New unit tests in tests.rs (8), weights.rs (2),
scheduler.rs, hybrid_scheduler.rs and paged_kv_cache_adapter.rs; 2
real-model tests (T10 group == window at a time, T11 forced trip), D3
goes through the group path, docs. `draft_history_appends_in_place` now
synchronizes after each eval (it failed 25 of 500 runs on a loaded host,
0 of 500 after). | D3 cold 6k / 16k as one group: 256 / 256,
group-vs-window max_ulp 0. T10 6k: 221 arrays byte-equal (`C2INT` d3 /
t10 logs). |
| T11 `3bdca3614` | The forced-trip test no longer compares a slot run's
text with the mapped reference (a slot run's text follows its slot count
and resident expert set). It keeps the structural asserts on the switch
and reruns the prompt on the same decoder, now on slots, printing both
texts. | Passes at slots 454 and 461. The two trees `6d86a6ad8` and
`748389987` give the same tripped text and the same plain-slot text at
454 slots, so #8 / #7 do not change the bits after a trip
(`P5/C2/T11X`). P5-X below makes slot text equal to the mapped text. |

Op trace (`FINAL5-trace-on-1`, MTP-2, traced addon `7709d2ec79eb`, not a
timing row): PLE GatherQMM count 0 at `a706d8058` (104 at `234f4bdd1`);
expert-bank GatherQMM 663. The 2560x2560 dense-decode kernels are not
attributed to a projection.

### c2: immediate cold 6k request (every cold request reads the whole 73
GiB pack)

| Arm | before (`313430e52` addon) | after (`85874b357` addon) | rebased
head (`748389987` addon) | llama.cpp b11717 reference (2026-10-21 ;
2026-10-20) |
|---|---|---|---|---|
| AR, req0 TTFT | 12.43 s (REJECT) / 16.03 s (REJECT) | **6.98 / 7.05
s** (both OK) | **6.93 s** (OK) | 6.01 s (`FINAL4-llama-off-1`) ; 6.38 s
(`FINAL3-llama-off-1`) |
| MTP-2, req0 TTFT | 11.73 s (OK) / 11.94 s (REJECT) | **7.09 s**
(REJECT) / **6.89 s** (OK) | **6.94 / 6.90 s** (rows REJECT, req0
passed) | 7.00 s (`FINAL4-llama-on-1`) ; 6.51 s (`FINAL3-llama-on-2`) |
| Speed vs llama (llama TTFT / ours) | AR 0.48x ; 0.51x (12.43 s row) |
AR 0.85-0.86x ; 0.90-0.91x; MTP 0.99-1.02x ; 0.92-0.94x | AR 0.87x ;
0.92x; MTP 1.01x ; 0.94x | |
| From load start (load + req0 TTFT) | AR 16.0 s; MTP 14.6 s (12.43 /
11.73 s rows) | AR 10.2 s; MTP 9.8-10.7 s | AR 10.0 s; MTP 9.8-9.9 s |
AR 36.1 ; 34.4 s, MTP 39.1 ; 35.6 s (FINAL4 table) |
| Request SSD | 71.5-72.4 GiB | 71.9-72.3 GiB | 72.3 GiB | 0.87 GiB
(llama reads the 78-82 GiB GGUF at load) |

- From load start we lead: AR 3.4-3.6x, MTP-2 3.3-4.0x faster than the
llama rows. FINAL5: AR 9.73-9.94 s = 3.67x ; 3.50x, MTP-2 9.74-9.89 s =
3.98x ; 3.62x.
- Per request we are at the top of llama's band: MTP-2 at parity, AR
8-15 % behind, on a loaded host.
- Other cold cases, after arm (`C2G-G2*`, `C2G-G8*`): request 3 s after
load AR 5.95 / 6.63 s (before 8.81 s; all three REJECT); request 8 s
after load AR 7.37 -> 6.96 s, MTP 7.00 -> 6.87 s; cold 16k as the first
request 16.92 s vs llama 19.82 ; 21.52 s (1.17x ; 1.27x faster).
- GATES held: G1 bar 8.0 s met by 0.95-1.02 s; wired back to 6.6-7.8 GiB
after exit on every row; load 2.81-3.56 s inside the before range.

### #8 + #7: one interleaved A/B (`PLEHC-*`, before `313430e52` addon,
after `52611c9d2` addon, loadcheck-OK rows only)

| Mode | Metric | before mean (n) | after mean (n) | after - before |
before range | after range |
|---|---|---|---|---|---|---|
| AR | 16k TTFT s | 18.09 (3) | 17.28 (2) | -0.82 | 17.50-18.98 |
17.08-17.47 |
| AR | 16k prefill tok/s | 1,037.8 (3) | 1,085.7 (2) | +47.9 |
988.3-1,071.8 | 1,073.7-1,097.7 |
| AR | warm 6k TTFT s | 4.97 (3) | 4.57 (2) | -0.40 | 4.68-5.18 |
4.53-4.61 |
| AR | decode tok/s (mean req0-2) | 49.17 (3) | 49.39 (2) | +0.22
(overlap) | 48.96-49.54 | 49.05-49.73 |
| MTP-2 | 16k TTFT s | 17.81 (2) | 17.44 (2) | -0.38 | 17.68-17.95 |
17.40-17.47 |
| MTP-2 | 16k prefill tok/s | 1,052.9 (2) | 1,075.5 (2) | +22.6 |
1,045.1-1,060.7 | 1,073.3-1,077.6 |
| MTP-2 | warm 6k TTFT s | 4.86 (2) | 4.60 (2) | -0.26 | 4.71-5.00 |
4.58-4.63 |
| MTP-2 | decode tok/s (mean req0-2) | 70.65 (2) | 71.51 (2) | +0.86 |
70.38-70.93 | 71.44-71.58 |
| MTP-2 | ms per cycle | 38.15 (2) | 37.71 (2) | -0.45 | 38.00-38.30 |
37.67-37.75 |

- The AR 16k mean includes a slow before row (18.98 s); the last
interleaved pair is -0.41 s. Per PLE window that is -19.7 ms (MTP) /
-21.7 ms (AR) over 19 windows.
- At the rebased head (`C2INT-after-off-1`, loadcheck OK): AR 16k TTFT
17.30 s, 16k prefill 1,083.8 tok/s, decode 48.24 tok/s, all within 2.3 %
of the better parent. The two MTP rows at the head are REJECT (foreign
compiles): 16k TTFT 18.14 / 19.15 s, decode 67.45 / 71.31 tok/s; not
counted.
- The decode tok/s here is the mean of each request's decode rate, not
the steady rate of the Stage II table.

### P5-X: slot path == mapped path bits

| Commit | What |
|---|---|
| `8cfc05371` test | `slot_groups_match_the_whole_window_bit_for_bit`:
slot groups on capacity-row banks vs the whole 512 bank, bf16 value for
value. T11 asserts tripped == plain == reference. |
| `e98d4c733` fix | `ExpertKernel::for_window` picks the kernel class
once per window; every slot group uses it. Hosts keep shape guards and a
1..=65536 row range. |
| `0df94ece6` fix | `route_sort` takes 1..=65536 rows (was 256..), so a
Tiles group of any size runs `prefill_indirect`. |

Root cause: a slot run splits a window's experts into groups of
`capacity` (454, 461, ...). The kernel class was chosen per group from
its rows and the bank's rows, so a remainder group under 4 rows per slot
fell from NAX tiles to QMV (gemv / gather_qmv). QMV sums K over 32 lanes
with `simd_sum`; NAX accumulates K in BK steps in `matmul2d`; the bits
differ. The mapped path runs one indirect call over all 512 experts. The
remainder set follows the slot count, so the slot text did too.

```
ExpertKernel::for_window(rows, 512)   // rows = window tokens x 10; 512 = model experts, not bank rows
  256 <= rows <= 65536 && rows / 512 >= 4  -> Tiles   NAX prefill_indirect, every group
  rows > 80                                -> Gather  sorted rows, gather_qmv (right_sorted = false)
  else                                     -> Rows    expert_rows gemv
```

Mapped windows keep their class (<= 80 Rows, 81-2047 Gather, >= 2048
Tiles before and after).

| Check | Result |
|---|---|
| `slot_groups_match_the_whole_window_bit_for_bit`, 21 splits (windows
1024 / 2000 / 200 / 75 / 20 tokens; capacities 454, 461 and one per
remainder band) | 13 differ before the fix, 0 after |
| Whole-bank FNV digests, old tree vs new tree | unchanged:
`61699f30731fef84`, `945858c1ffd5b137`, `42e2d760d60b10cd`,
`dcf1e56baefe4fb0`, `de18448f7e14176a` |
| D3 cold 6k / 16k, mapped 512 | 256 / 256, max_ulp 0 |
| T11 6k | tripped == plain == reference `[22916, 310, 635, ...]` at
slots 427 / 420 / 277 |
| T10 6k | 221 arrays byte-equal |
| Scoped `models::qwen4_exp` | 242 pass / 0 fail / 11 ignored |
| `cargo clippy -p mlx-core --all-targets`, `cargo fmt --check` | clean
|

- Real-model rows ran on the pre-rebase trees (`a95cb2492`; T11 at 277
slots on `81ea6f965`). The rebase is 3 x `=` in range-diff with an empty
qwen4 / mlx-sys diff. D3 6k, the unit gates and the digests were rerun
on the rebased P5-X head and on every later head.
- Timing: interleaved T11, old vs new binary on the same loaded host,
plain slot prefill new / old = 1.23x then 0.91x: NOISE. No mapped window
changed kernel class. No further slot-mode timing (P5-Y stopped, see
gaps).
- Codex Stage III finding (slot path bits): closed by `e98d4c733` +
`0df94ece6`; the Codex thread is resolved with the commits.

### Compile cache and CI fixes (`142cff3e0`, `734430a6f`)

- **Codex pass 2 (medium): compile-cache growth.**
`qwen4_indirect_prefill` ran through `mlx::core::compile`, which keeps
one trace per input shape and never evicts. Each trace holds its own
copy of the two kernel sources, ~309 KB (estimated from the measured
148,980 B header). P5-X sends the slot remainder groups to this path
too, so one 32k prompt at 454 slots makes 542 keys instead of 271
(Codex's harness, reproduced), and 814 after 4 prompts. The wrapper and
the base growth come from main (#154); the doubling is ours.
- **Fix `142cff3e0`:** the indirect expert prefill runs eagerly. Its
graph is two custom kernels with nothing to fuse, so the bits are the
same by construction (an earlier eager arm was also exact at D3 6k /
16k). 1 file, +3 / -7. Unit digests unchanged, scoped 242 / 0 / 11, D3
6k 256 / 256, max_ulp 0. The Codex bot found nothing on the fixed head.
- Out of scope: the dense prefill wrapper on main
(`qwen4_dense_prefill_dispatch`) has the same growth, one key per
distinct window length. Left for a separate item.
- **CI `734430a6f`:** five MTP draft-bank tests failed on the 7 GB
macos-26-arm64 runner. The fixture load asks for the fixed 4 GiB
first-request working reserve (`WORKING_BYTES`), not for its few-KB
bank; the runner had 2.7 GiB free. Production degrades as designed (warn
and load on). Test-only fix: fixture helpers pass an always-yes
admission; the decline calls pass one that panics, so the decline still
comes before any host admission. On a simulated 7 GB host: old tests 0 /
5 with the CI message, new 5 / 5, scoped 242 / 0 / 11. CI green on
`e3503adc0` (this commit before the final rebase).

### Cleanup (`299b4defb`, `071588e44`, `12f7fdb74`, `3c0d8a5a1`)

- The four decoder A/B switches (`batch_prefill`, `window_carry`,
`async_prefill`, `batch_rotary`) are gone with their losing arms. The
prefill oracles now compare against `step()`; the rotary test is
bit-exact against per-row `rope`.
- `fold_rows` is gone, with the research-only tests (row-batched GPU
time, forced-stream acceptance, two fold-cost timings).
- D3 is cut to the greedy expected-argmax gate:
`real_model_greedy_argmax_matches_expected`. Env vars renamed: `D3_*` /
`T10_CASE` -> `QWEN4_EXP_REAL_STEPS` / `_CASES` / `_EXPECTED` / `_OUT`
(documented in `docs/qwen38-flash-next.md`).
- Phase labels, mutation codes, dates and shas are stripped from
comments. Docs corrected: 73 GiB pack, 32 readers, cache paths.
- Gates (on `4455353de`, this stack before the final rebase; the rebase
diff is the openai bump only): scoped 239 / 0 / 9. The delta from 242 /
0 / 11: 2 passing tests removed, 1 moved to ignored (release
microbenchmark), 3 ignored research tests removed. Clippy, fmt and
typecheck clean; unit digests unchanged; D3 6k `EXPECTED OK: 256
positions`, mapped 512.

## Phase 4 Stage II + Phase 5 L2 + v3 pack policy (`e00bb6e3f`,
`f6a35ca4c`, `9f52a1c3d`, `29bff1850`, `67fe0f15c`, `32e7a3faa`,
`5a7c5fdea`, `c003150d0`)

| Step | Change |
|---|---|
| M3 `e00bb6e3f` | A draft pass submits the attention hyper-connection
rows and their injection gate as soon as they exist, so the GPU starts
while the host builds the rest of the pass. Same graph and kernels.
Propose wall at 6k 4.86-5.17 -> 4.75-4.80 ms. |
| C5 `f6a35ca4c` | The draft K/V history is a capacity buffer written in
place instead of six full-history concatenations per MTP cycle (12 MiB
each at 6k). Cache clones share the buffer and keep their own row
counts. Draft GPU per cycle 6k 4.21 -> 4.04 ms, 16k 4.54 -> 4.14 ms. |
| L2 `9f52a1c3d` | Stream pool: eight workers read the whole pack with 4
MiB buffered preads in layer order (12.3 GiB/s over the evicted pack;
the old depth-3 walker did 9.3), kernel read-ahead off, one `mincore`
per file to skip resident chunks. The stream starts at load after the
dense banks and at any turn over a pack that is not fully resident; it
yields to the model's row reads and stops within one chunk on the switch
to slots or on unload. Cold 6k TTFT -1.6..-1.9 s; a request 8 s after
load reaches 7.4 s. |
| L3 `29bff1850` | The draft head normalizes the target hidden per
hyper-connection stream (as the target's own `hc_norm` and llama.cpp's
MTP graph do) instead of one RMS over the joined streams (mlx-vlm's
drafter). Teacher-forced on llama.cpp's committed text it reproduces
llama's per-position acceptance (0.914, 0.817); f32 head / router, f16
draft K/V and a zero first row moved nothing. Draft side only: verify
path and committed text unchanged. |
| B1 `67fe0f15c` | Test only: fixture GGUF loads in unit tests resolve
to a fresh temp root instead of
`~/Library/Caches/mlx-node/qwen4-packed`, so `cargo test` no longer
sweeps the developer's real cache; a regression test with a fake HOME
proves it. Codex: approve. |
| v3 policy `32e7a3faa` `5a7c5fdea` | Pack identity no longer includes
`st_dev`, so a volume renumber keeps the 73 GiB pack. The manifest
records the canonical path and the mount point of every source file. A
pack is removed only on proof: its source is present with another
fingerprint, or a source file is gone from a volume that is mounted. An
unmounted or unreadable source keeps the pack. A real-model load after
the change reused all 144 files and matched the shas. |
| manifest fix `c003150d0` | Codex S2 (medium): a truncated `.manifest`
read as a fingerprint change and deleted a healthy pack. The manifest
ends with an `end=<hex file count>` record and is written to
`.manifest.tmp` then renamed; a manifest without a valid end record is
incomplete and keeps its pack; the load heals the opened pack's manifest
and no other. 4 mutations red, module tests 223/0, real-model load
reused the pack and healed its manifest with the shas unchanged. |

## Phase 4 Stage I: MTP-2 cycle (`fffd47666`, `98861f447`, `f765187d9`)

Warm 6k MTP-2 cycle 50.6 -> 37.8 ms in the quiet A/B (-25 %); traced
cycle 33.1 ms = draft 2.5 + 2.3 + verify 28.0 + accept/commit 0.3.

| Step | Change |
|---|---|
| A1 `98861f447` | On the mapped pack the verify pass keeps its routes
on the device: one route tape joined into the final eval and one
readback replace 48 per-layer GPU-to-host waits; the tripwire is told
after the route commit. Slot mode keeps the host routes. Real-model
test: 32 three-row verifies match the AR step bit for bit. |
| M1 `f765187d9` | The MTP gate_up draft bank keeps its scales and
biases as f32 copies, so `gather_qmm` no longer casts 2 x 52.4 M values
on every draft; the f16 layout stays where the f32 one does not fit the
mapped charge or the slot allowance. |
| v2 retire `fffd47666` | Legacy `.mlx-qwen4-packed-v2-<64 lowercase
hex>` directories are removed at load once idle for 1 h and their
`budget` lock is free. |

## What Phase 3 adds

| Step | Change |
|---|---|
| M5 | Mapped-or-slots chosen at load from live memory (wired +
compressor + anonymous), byte budget exported; thrash tripwire (SSD
reads > 2x mapped bytes, or 8 slow passes); decoded-row LRU
byte-bounded; no "free memory" advice, no override flag |
| M6 | A tripped turn leaves the mapped path at that pass and finishes
on slots (13 min -> 50 s under a 40 GiB hog); gate maps while live
non-reclaimable <= 42.85 GiB; slot fallback sized after the compressed +
swapped debt |
| D3 | Same-process teacher-forced A/B of every fusion/schedule flag:
none beats the noise band; decode is weight-stream bound; 21 flags and
their kernels deleted |
| S3-S6 | MTP verify runs the R draft rows layer by layer with shared
weight reads; Q8 g32 draft expert bank for the MTP head; draft prefill
merged into the first draft pass; 16k MTP admission counts only KV pages
|
| K16 | Prefill QSA kernel serves two GQA heads per K/V read (-14 %,
bit-identical) |
| INT2 | Integration; fixes the S3 regression that sent prefill through
the row-exact R <= 4 wrappers (1.58 M single-row GEMV dispatches per 6k
prompt -> 9.5 k) |
| C1 | Flag purge: 89 `MLX_QWEN4_*` names, the runtime flag module, the
residency selection knobs and the v2 per-expert chunk cache are gone;
one code path |
| Review fixes | Slot sizing keeps room for MTP draft banks
(`163a0f9c1`, `6698e47b6`) |

## How to verify

Cleanup head = `4455353de` (`3c0d8a5a1` before the final rebase).

| Check | Command or test | Result at |
|---|---|---|
| Scoped unit tests | `cargo test -p mlx-core --lib models::qwen4_exp` |
248 run / 239 pass / 0 fail / 9 ignored (cleanup head) |
| | `cargo test -p mlx-core --lib engine::scheduler` /
`engine::hybrid_scheduler` / `transformer::paged_kv_cache_adapter` |
26/26, 51/51, 174 run / 170 pass / 4 ignored (`a706d8058`) |
| Bitwise tests (`--exact`) |
`ple_projection_row_kernel_matches_gather_and_single_rows_bit_for_bit`,
`ple_window_runs_four_rows_per_row_kernel_call_bit_for_bit`,
`mixer_act_split_keeps_the_one_simdgroup_chain_bit_for_bit`,
`row_batched_decode_kernels_match_single_row_calls_bit_for_bit`,
`a_group_of_windows_matches_one_window_at_a_time_bit_for_bit` | each 1
passed (P5-X); in the scoped run on every later head |
| Slot == mapped (`--exact`) |
`slot_groups_match_the_whole_window_bit_for_bit` | 21 / 21 splits equal
(13 differed before the fix); 5 whole-bank digests unchanged (P5-X,
P5-Z, cleanup head) |
| Kernel class rule (`--exact`) |
`expert_kernel_follows_the_window_not_the_bank` | ok (P5-X, P5-Z,
cleanup head) |
| Lint | `cargo clippy -p mlx-core --all-targets`, `cargo fmt --check`,
`yarn typecheck`, `vp fmt --check docs/qwen38-flash-next.md` | clean
(cleanup head) |
| Real model, exactness (ignored tests; `QWEN4_EXP_REAL_MODEL`,
`QWEN4_EXP_REAL_INPUTS`, `QWEN4_EXP_REAL_CASES`,
`QWEN4_EXP_REAL_EXPECTED`; page cache evicted first) |
`real_model_greedy_argmax_matches_expected` | cold 6k `EXPECTED OK: 256
positions`, mapped 512 (cleanup head, P5-Z); cold 6k / 16k as one group
256 / 256, max_ulp 0 (`a706d8058`, P5-X) |
| Real model, group vs windows |
`real_model_group_matches_window_at_a_time_on_a_cold_pack` | 221 arrays
byte-equal (`a706d8058`, P5-X) |
| Real model, trip |
`real_model_forced_trip_between_sweeps_switches_after_the_frontier_eval`
| asserts tripped == plain == reference, plus commit -> frontier -> trip
-> switch order, store off the mapped path, stream gone, fallback index
0, history == prompt; passes at slots 427 / 420 / 277 (P5-X trees) |
| Real model, text | R0 benchmark, cold 6k + 16k + warm 6k, 256 tokens,
AR and MTP-2 | shas `bfb8e8bb3bd0c768` / `6a63463a98644df6` on every
request, AR == MTP, MTP 95 / 189 / 160 (`a706d8058`) |
| FINAL5 measurement | `FINAL5/driver.sh` + `FINAL5/trace.sh` (research
dir), R0 benchmark, page cache evicted per run | 10/10 timing rows + 1
trace row; the same 6k / 16k sha on all 30 requests (`rows-all.txt`), AR
== MTP; mapped/512 on every row; wired-drop gate 10/10 (largest fall 4.3
GiB); MTP c/d/a 95/189/160 on every MTP request (`a706d8058`) |

## Known gaps and open items

- **FINAL5 still loaded-host.** 0 of 10 rows had an idle GPU (foreign
GPU mean 31.4-44.5 %, one row 10.6 %). Interleaved A/B deltas hold;
absolute rows carry the caveat. The trace row is above (op trace).
- **Decode below Stage II.** AR decode 7-9 % and MTP-2 16k decode 7.1 %
below Stage II on every Stage III loaded-host row since `313430e52`.
Cause not separated: the L2c bank in the AR arm vs foreign GPU load. The
interleaved Stage II vs Stage III A/B (P5-Y) was stopped at the user's
request after 5 rows, with no analysis.
- **Cold 6k per request, AR, behind.** 6.91-6.93 s vs llama 6.01 ; 6.38
s = 0.87x ; 0.92x (FINAL5, loaded host). MTP-2 is at parity (1.01x ;
0.94x). From load start: AR 3.67x ; 3.50x, MTP-2 3.98x ; 3.62x faster.
- **#7 on AR.** The AR gain (target -0.5 ms per step) is below the
noise; only the MTP-2 decode delta separates.
- **c2 follow-ups, accepted and not coded:** SF2 (the row queue's
`take()` scans under the lock; late rows 995-1,698 per cold 6k request;
trace the wait first), SF3 (no cadence trace; the 3-layer submit cadence
stays), SF4 after-trip half (the 1024-row window is not re-sized after a
switch; every growing byte is still admitted; tight host untested), SF5
native-state half (a failed group's lazy tail costs the next request GPU
time, not bits).
- **Slot-mode prefill timing.** Not measured on a quiet host with the
window kernel class rule. The only pair (T11, loaded host) is NOISE.
- **Dense prefill compile cache (out of scope).** The dense prefill
wrapper on main (`qwen4_dense_prefill_dispatch`) keeps one compile trace
per distinct window length, the same growth as the indirect one fixed
here. Left for a separate item.
- **MLX fork item.** The Synchronizer's `retain_inputs` keeps an eval's
output buffers until its completion handler runs, so `append_draft_kv`
can copy instead of writing in place. It is a copy, never a wrong value.
- **First launch after a kernel change** pays in-request Metal compiles
once (AR 1.07 s + 0.07 s, MTP 24 compiles in the first process per
mode); 0 from the second process on.
- **MTP 16k prefill spread.** Slow MTP 16k rows trace to a host event:
40-55 GiB of wired memory released and re-taken within 1-3 s
mid-prefill, GPU to ~18 %. FINAL5's wired-drop gate passed 10/10
(largest fall 4.3 GiB); no host-event row this time.
- **Busy posture.** Above ~43 GiB of live non-reclaimable memory from
other apps the load picks the slot path, which is ~5x slower (11-15
tok/s MTP-2 decode); it completes, it does not crash or thrash. c2 hog
row (40 GiB hog, 16k, MTP-2): slots 225, 64 / 64 tokens.
- Pre-existing: kquant golden gate fails on the g17s/g17d/g17g NAX
routes at the base pin (identical bits on the source and prebuilt
builds).

## Submodule

`crates/mlx-sys/mlx` -> fork branch `fn-d1` (`e68b9ba77`: two patches on
`bcad39304`). `mlx-prebuilt.json` pins the matching prebuilt release
`mlx-prebuilt-e68b9ba778fc-6d601cad`; golden gates are digest-identical
between the source and prebuilt builds. Stage III does not move the pin;
#7's kernel is a new
`crates/mlx-sys/src/metal/qwen4/mixer_act_decode.metal.inc`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant