Repository navigation
feat(moe): stream qwen4_exp routed experts from the SSD - #2912
Merged
Merged
Conversation
Checkpoints larger than unified memory cannot run today because every routed expert stays resident. Add a per-layer slot arena for Qwen3.8-Flash-Next on Metal: the host evaluates the router's top-k, reads missing experts into least recently used slots with unbuffered reads, and runs the gather on slot indices. Slots are page-aligned host memory wrapped as MLX arrays without a copy, and a load fails if MLX copies instead. The sorted prefill path reproduces the resident sort and cuts oversized windows only between experts, and it follows the resident kernel choice rather than the slot count. Cutting by token rows changed the kernel batching and broke exactness. Streaming engages under auto only when routed experts exceed 60% of the Metal working set, and sizes the arena from available memory. Also adds the prepare-expert-stream contiguous writer, an arena stats line and metrics, the preflight accounting, and a warning for an MTP drafter below 96 GB. Validated on a 512 GB M3 Ultra: greedy output on five prompts and logit traces after 4608 context tokens match the resident path at 24 GB and 8 GB arenas. Decode at a forced 100% hit rate costs about 15 ms per token; a run on a smaller Mac and the paired benchmarks are still outstanding. Refs #2882
MLX chooses the sorted gathered matmul and its tile height from rows / tensor experts per call. A batch on a slot tensor could fall outside the resident band, so a resident-sorted prefill window took another kernel. Batches are now planned to land in that band: largest expert first into the lightest batch, whole experts only, with a one-time warning when the band cannot be met. Other fixes: an output is no longer forgotten while it may still read a slot, and dropping a layer waits for its last reader before freeing the buffers. The contiguous file is tied to each shard's size and mtime and rejected when truncated. Active stats no longer keep a dropped model alive. Preflight counts the clamped slot allocation. --surgery cannot silently skip streamed experts: forced streaming errors and auto loads resident. Validated with the stream unit tests and clippy. The real model was not re-run, so numeric parity of the rebalanced batches is unconfirmed. Refs #2882
Member
Author
Implementation Review SummaryIntent
Findings Addressed
Remaining Items
Verification
|
…pert-streaming-arena # Conflicts: # docs/supported-models.md # src/models/qwen4_exp.rs
The CLI prints the arena line after the model is gone, and the weak handle added in review made it disappear. A dropped stream now leaves its final counters for the stats line. Refs #2882
A checkpoint directory can come from anyone, and ExpertSource::open runs on every qwen4_exp load on macOS and in the memory preflight, so a bad checkpoint must produce an Err rather than a panic, abort, or out-of-bounds access. The plane table now requires row size to equal shape times element size, keeps offsets inside the shard, refuses duplicate alias keys and impossible layer or expert counts, and proves the byte totals fit. Shards and the contiguous files resolve through the #2881 containment helpers, and headers use its bounded reader. A contiguous manifest must describe every layer exactly. write_contiguous_file unlinks existing files and creates new ones, so a planted symlink is not written through and a running reader keeps its inode; failed runs remove the partial file. Under auto, a layout whose arena is not whole pages or has fewer slots than num_experts_per_tok falls back to the resident path. Unit tests cover each refusal. The expert stream module tests, clippy, and fmt pass. Refs #2882
The expert streaming feature (MLXCEL_EXPERT_STREAM, MLXCEL_EXPERT_ARENA_BYTES, prepare-expert-stream, arena metrics) had no CHANGELOG entry. Add one under Unreleased. The environment variable and supported-models text already match the final code, so they are unchanged. Validation: cargo test --lib --features metal,accelerate qwen4_exp (199 passed), cargo clippy --lib --tests --features metal,accelerate -- -D warnings, cargo fmt --check, make verify-env-var-docs all pass. Refs #2882
inureyes
marked this pull request as ready for review
November 9, 2026 19:35
inureyes
added a commit
that referenced
this pull request
Nov 10, 2026
## Summary Records the timing and memory measurements that #2908, #2906, #2912, #2909, #2911 and #2918 deferred to a quiet host, in `docs/benchmark_results/qwen4-exp-deferred-measurements-m3ultra-2026-11-10.md` (Mac Studio M3 Ultra, 512 GB, `main` @ `60a3270c`). - Native MTP (#2880, #2917): 1.30x / 1.10x / 1.76x (code / prose / enumeration) for the OptiQ 2-bit target with the bf16 split head, 1.38x / 1.00x / 1.74x for the 4-bit target with its embedded head. - SSD expert streaming (#2882): decode 42.8 tok/s resident, 23.0 at a 24 GB arena (89.8% hit), 18.3 at 8 GB (74.9% hit). Router sync costs 8.0 s per run at both sizes, more than the I/O wait. Output identical across arms. - External PLE (#2881): 31 GB less resident (78.5 to 47.3 GB), same TTFT at 4K and 32K, identical output in every mode. - Prompt-cache second turn (#2885): 0.51 to 0.60 s cached vs 15.1 s (16K) and 28.6 to 28.9 s (32K) after a reset, byte-identical in 10/10 repetitions. - macOS memory soak (#2883): 0 compressions and 0 swap-outs in every setting. A 512 GB host cannot show the eviction the issue targets. ## Script changes - `scripts/bench_speculative.sh`: new `flashnext` and `flashnext4` pairings. - `scripts/macos_memory_soak.sh`: send the `model` field (every request got HTTP 400 without it), and default `--out` gets a `-wire-weights` suffix under `--wire-weights` so it no longer overwrites the plain run. ## Not covered A Mac with less memory than the checkpoint, the `prepare-expert-stream` contiguous file, and streaming combined with the external PLE table. Refs #2880, #2881, #2882, #2883, #2885, #2917
This was referenced Nov 10, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Lets
qwen4_exprun with its routed experts on the SSD: a slot arena per layer, filled on demand, with everything else resident. Off by default unless routed experts exceed 60% of the Metal working set (MLXCEL_EXPERT_STREAM=1|0overrides,MLXCEL_EXPERT_ARENA_BYTESsizes it). A 512 GB machine does not stream unless asked.Closes #2882
How it works
Each layer evaluates the router's top-k to the host once, reads misses into LRU victims the window cannot evict, and runs
gather_qmmon slot indices. Slot tensors are page-aligned host allocations wrapped as MLX arrays without a copy, and a load fails (or falls back to resident underauto) if that is not possible. A slot is rewritten only after every command that reads it has finished.The sorted prefill path reproduces the resident sort, keeps each expert's rows in one batch, and plans batches so MLX picks the kernel and tile the resident
E = 512tensor would get. Splitting by token rows made an 8 GB arena diverge from resident output on all five test prompts. If a window cannot be planned that way, a one-time warning says its low bits may differ; it did not fire in any run below.Sync cost at a 100% hit rate (host had a sibling job running, see
docs/benchmark_results/expert-streaming-sync-cost-m3ultra-2026-11-10.md): resident 42.0 tok/s, forced per-layer sync 25.6 tok/s, about 15.3 ms per token. The mode engages only where the alternative is not running, so the MLX-graph approach stays; a custom Metal handshake remains a possible follow-up.Also:
mlxcel prepare-expert-streamwrites the contiguous file (hash-checked, used automatically), an[Expert arena: ...]line andmlxcel_expert_arena_*metrics, preflight accounting, a warning for an MTP drafter below 96 GB, and validation that refuses malformed or out-of-directory checkpoints.Validation (final commit, forced streaming on a 512 GB M3 Ultra)
qwen4_exptests, clippy, fmt, andmake verify-env-var-docspass.Not verified
Not implemented: read-ahead, the warm-start usage profile, and choosing the prefill chunk size by available memory. Batched decode with streaming is untested.