Skip to content

feat(moe): stream qwen4_exp routed experts from the SSD - #2912

Merged
inureyes merged 7 commits into
mainfrom
feature/issue-2882-expert-streaming-arena
Nov 9, 2026
Merged

inureyes merged 7 commits into
mainfrom
feature/issue-2882-expert-streaming-arena

Conversation

@inureyes

@inureyes inureyes commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

Lets qwen4_exp run 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|0 overrides, MLXCEL_EXPERT_ARENA_BYTES sizes 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_qmm on 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 under auto) 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 = 512 tensor 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-stream writes the contiguous file (hash-checked, used automatically), an [Expert arena: ...] line and mlxcel_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)

  • Greedy output on five prompts (256 tokens) is byte-identical to resident at 24 GB and 8 GB arenas; a 3286-token prompt through default prefill chunking matches too (it stops after 16 tokens).
  • Logit traces after 4608 context tokens in one forward match row for row at forward widths 32 and 1, at printed logit precision.
  • Unit tests cover the slot map, LRU, batching, decision rule, hostile checkpoints, and the contiguous writer's bit-for-bit round trip. qwen4_exp tests, clippy, fmt, and make verify-env-var-docs pass.

Not verified

  • A Mac with less memory than the checkpoint, with no swap-outs and the external PLE table: none available. Forced small arenas on 512 GB are only a stand-in.
  • Paired five-run medians (arena sizes, contiguous file, 4K prefill): not run while a sibling job shared the host.
  • The contiguous file on the real checkpoint: unit test only, to avoid writing 41 GB into the shared model tree.

Not implemented: read-ahead, the warm-start usage profile, and choosing the prefill chunk size by available memory. Batched decode with streaming is untested.

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
@inureyes inureyes added type:enhancement New features, capabilities, or significant additions type:performance Performance improvements priority:medium Medium priority area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) platform:macos macOS (Apple Silicon) specific modelsize:xlarge 4-bit checkpoint > 100GB; exceeds a 128GB dev box, needs bigger hardware arch:moe Sparse mixture-of-experts decoder status:review Under review labels Nov 9, 2026
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
@inureyes

inureyes commented Nov 9, 2026

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Stream qwen4_exp routed experts from the SSD through a resident slot arena with exact numerics on Metal.

Findings Addressed

  • Sorted prefill batches could leave the resident kernel band, since MLX computes B / E over the slot tensor (HIGH)
  • pending was overwritten by hit-only windows, and buffers could be freed under a queued command (MEDIUM)
  • --surgery silently skipped streamed experts (MEDIUM)
  • Preflight understated arenas below the 64-slot minimum (MEDIUM)
  • Contiguous file was not tied to shard identity or size (MEDIUM)
  • Active stats kept dropped models alive and reported them (MEDIUM)

Remaining Items

  • Numeric parity of rebalanced batches on the real model, not re-run in review (HIGH)
  • Prefill chunk size by available memory (design item 7) is not implemented and not listed as deferred (MEDIUM)
  • Small-Mac run and paired five-run medians, as the PR body states (acceptance)
  • Merge conflicts with main in docs/supported-models.md and src/models/qwen4_exp.rs (blocks merge)

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass (models::qwen4_exp::stream, clippy)

…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 inureyes added status:done Completed and removed status:review Under review labels Nov 9, 2026
@inureyes
inureyes marked this pull request as ready for review November 9, 2026 19:35
@inureyes
inureyes merged commit 897852d into main Nov 9, 2026
13 checks passed
@inureyes
inureyes deleted the feature/issue-2882-expert-streaming-arena branch November 9, 2026 19:36
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
@inureyes inureyes added this to the 0.9 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

arch:moe Sparse mixture-of-experts decoder area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) modelsize:xlarge 4-bit checkpoint > 100GB; exceeds a 128GB dev box, needs bigger hardware platform:macos macOS (Apple Silicon) specific priority:medium Medium priority status:done Completed type:enhancement New features, capabilities, or significant additions type:performance Performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(moe): SSD expert streaming arena for MoE checkpoints larger than unified memory

1 participant