Skip to content

feat(qwen4-exp): stream MoE routed-expert weights off the wired/phys budget - #3437

Closed
alytaphoenix wants to merge 2 commits into
jundot:mainfrom
alytaphoenix:pr/qwen4exp-moe-weight-streaming
Closed

alytaphoenix wants to merge 2 commits into
jundot:mainfrom
alytaphoenix:pr/qwen4exp-moe-weight-streaming

Conversation

@alytaphoenix

Copy link
Copy Markdown
Contributor

What

Stream the ~46.87 GB of qwen4_exp routed-expert (switch_mlp) weights off the
wired/phys budget: bind them as mmap-backed, page-aligned arrays over a side-car
artifact next to the checkpoint instead of loading them resident. This lets
Qwen3.8-Flash-Next-MLX-oQ2-MTP load and serve long context on a 64 GB M4 Pro
mini, where the fully-resident path does not fit (backbone ~25.6 GB + experts
~46.9 GB > RAM).

Streaming engages only when the artifact exists next to the checkpoint and
the native extension is available; otherwise it is a clean fully-resident no-op.

Kill switch: OMLX_QWEN4_MOE_STREAM defaults to enabled whenever the
streaming artifact is present on disk; set it to 0 to force the old
fully-resident path.

This is a measured tradeoff, not an unqualified win

Streaming buys the ability to run this model at all on 64 GB, at a real prefill
cost. Live single-request ladder measured (103,019 real prompt tokens,
929.7 s total):

Prompt depth Streaming throughput Non-streaming baseline (comparable depth)
~40k ~178 tok/s ~223 tok/s-class
~76k ~124 tok/s —
~96k ~111 tok/s —

At the top of the tested range this is roughly ~2x slower prefill than the
project's earlier non-streaming baseline (~223 tok/s-class). This corrects an
earlier design-doc framing that overstated the regression as "~15x slower" —
the real number is ~2x, not an order of magnitude.

Real context ceiling: ~121–122k, not the ~200k+ originally projected

The earlier design doc projected a ~200k+ context ceiling under streaming. That
projection is walked back.
Live testing puts the real ceiling at ~121–122k
tokens
. At that point real chunked-prefill transient memory (not anything
this feature's own accounting touches) hits the hard watermark and the enforcer
gracefully aborts just that one request while keeping the model loaded —
verified clean, not a crash or an eviction.

Production config (decided, now live on the mini): max_context_window: 120000, accepting that requests very near the ~121–122k wall may occasionally
get a graceful per-request abort rather than always succeeding.

Open item

All live testing so far is single-request. No concurrent-traffic run under
streaming has been done yet — flagged as an open item, not a proven gap.

How it works

  • omlx/custom_kernels/qwen4_moe_stream/: native _ext (bytesNoCopy MTLBuffer
    wrap of page-aligned tensors, refcounted deferred munmap), StreamingArtifact
    manifest index + canonical-key parser, weights-list interception, and
    repack.py — the artifact producer / format authority (source dir
    parameterized via --model-dir / OMLX_QWEN4_MODEL_DIR, no hardcoded path).
  • engine/vlm.py: _stream_qwen4_exp_experts_on_load context manager — patches
    Module.load_weights post-sanitize to swap expert values before mx.eval,
    with expect_all hard-fail, a load-time bit-exactness canary, and
    failure-path teardown that closes the mapping and skips the canary/success log
    if the load body raises after the swap.
  • engine_pool.py: streaming-aware resident-size estimate for admission +
    unload-time artifact close.
  • utils/proc_memory.py: name-keyed external-wired provider registry +
    discount_external_wired measurement hygiene.
  • process_memory_enforcer.py: external-wired is observability-only in
    /health, not subtracted from any ceiling (metal_cap per Fix A, dynamic
    ceiling per Fix D); real wired pressure is caught live via vm_stat
    free-bucket depletion.

Provenance

This is a focused resubmit targeting main directly, per @jundot's request
on #3283 to split the remaining wanted changes into focused PRs off current
main. Full review history and discussion for this feature live on
alytaphoenix#2 — this PR is the same feature commit, cherry-picked
cleanly onto current main as a single logical commit (the earlier
deploy-branch prereq-port commit it used to stack on is not needed — main
already independently carries the engine_pool/deployment symbols it
depended on, so it was dropped).

Testing

Full tests/ suite re-run on the rebuilt-onto-main branch: 10664 passed,
150 skipped, 77 deselected
. The only failures (13) are pre-existing and
identical on clean main in this environment — an MLX patch-version pin in
test_mlx0322_compat / test_sdpa256_attention (env has MLX 0.32.0, those
tests expect 0.32.2); none are in files this feature touches, so zero
regressions
vs. the main baseline.

The native-extension tests in tests/test_qwen4_moe_stream.py were run for
real against the built _ext kernel (not skipped)
: 17/17 passed,
including the bit-exact load_weights round-trip, deferred-munmap, and
canonical-key native paths.

🤖 Generated with Claude Code

https://claude.ai/code/session_01FR1CuCS9onnMPzwTTkFU4r

…budget

Bind the ~46.87 GB of qwen4_exp routed-expert (switch_mlp) tensors as
mmap-backed, page-aligned arrays over a side-car artifact next to the
checkpoint instead of loading them resident, so Qwen3.8-Flash-Next-MLX-oQ2-MTP
fits and serves long context on a 64 GB M4 Pro mini.

Components:
- omlx/custom_kernels/qwen4_moe_stream/: native _ext (bytesNoCopy MTLBuffer
  wrap of page-aligned tensors, refcounted deferred munmap), StreamingArtifact
  manifest index + canonical key parser, weights-list interception, and the
  repack.py artifact producer (source-dir parameterized via --model-dir /
  OMLX_QWEN4_MODEL_DIR, no hardcoded home path).
- engine/vlm.py: _stream_qwen4_exp_experts_on_load context manager -- patches
  Module.load_weights POST-sanitize to swap expert values before mx.eval, with
  expect_all hard-fail, a load-time bit-exactness canary, and failure-path
  teardown that closes the mapping and skips the canary/success log if the
  load body raises after the swap.
- engine_pool.py: streaming-aware resident-size estimate for admission and
  unload-time artifact close.
- utils/proc_memory.py: name-keyed external-wired provider registry +
  discount_external_wired measurement hygiene.
- process_memory_enforcer.py: external-wired is observability-only in /health,
  not subtracted from any ceiling (metal_cap Fix A, dynamic ceiling Fix D);
  real wired pressure is caught live via vm_stat free-bucket depletion.
- scheduler.py: wire the provider through the enforcer breakdown.

Kill switch: OMLX_QWEN4_MOE_STREAM=0 forces the fully-resident path. Streaming
engages only when the artifact exists next to the checkpoint and the native
extension is available; otherwise it is a clean resident-load no-op.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FR1CuCS9onnMPzwTTkFU4r
@alytaphoenix
alytaphoenix force-pushed the pr/qwen4exp-moe-weight-streaming branch from 7b47130 to 69974c7 Compare September 7, 2026 18:55
@alytaphoenix

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (1 real conflict in engine_pool.py: main independently added recurring-attempt tracking + structured decision logging to the prefill-eviction loop since this branch was cut — merged both, applying this feature's discount_external_wired() wrapping to the new loop's active sample so the streaming artifact's phantom active-memory doesn't trigger spurious eviction/reclaim against a model that isn't actually short on real memory). Full suite: 10,839 passed, 0 failed, 158 skipped, 77 deselected.

…t-streaming

# Conflicts:
#	omlx/engine_pool.py
#	omlx/process_memory_enforcer.py
#	omlx/scheduler.py
#	omlx/utils/proc_memory.py
@jundot

jundot commented Oct 5, 2026

Copy link
Copy Markdown
Owner

Main now has generic MoE expert offload (#2595). It streams non-resident experts straight from the original checkpoint with a configurable resident fraction, and it works with qwen4_exp including Lightning MTP (#3935). I'd rather build on that path than add a second mechanism that needs a ~47 GB repacked side-car and patches Module.load_weights globally. More context: #2887 (comment)

@jundot jundot closed this Oct 5, 2026
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.

2 participants