Repository navigation
feat(moe): expert offload — stream non-resident experts from the checkpoint - #2595
Conversation
|
Independent validation: M5 Pro 48 GB + oMLX-native oQ4e checkpoint — acceptance passes Ran the acceptance contract on different hardware and a different quantization format than the PR's own test set — passes cleanly.
Results:
The relevant bit for the DeepSeek-V4 / GLM-5.2 follow-up: the store handled oMLX's native oQ4e stacked layout out of the box (a checkpoint that never passed through mlx-lm's |
|
Thank you for running this, @tiagoflino! The oQ4e result is new information — I hadn't tested any oMLX-native quant, so the store handling a never-sanitized stacked layout was untested until your run. It de-risks the native-kernel follow-up. One sharpening: verify runs the drafted window through the full stack in one forward, so each layer needs the union of the window's experts resident at once — batch-like working-set widening, not just extra fetch traffic — which is worth accounting for in cache sizing. |
|
Thanks — and agreed on the verify working-set point. Two notes from the follow-up side (the DS4/GLM native-kernel extension built on this mechanism):
Happy to open the follow-up PR once the live numbers are in. |
|
ran it on two machines, 24gb m5 pro (16-core gpu, macos 27) and 128gb m5 max (40-core gpu, macos 26.5), gemma-4-26b-a4b-it-4bit. memory matches your table exactly on both, and greedy is 3/4 identical to resident at 0.25 on both (one fork on the canberra prompt, the one your test allows). the thing worth adding from two very different boxes: the cost is io-bound, not compute. the max has 2.5x the gpu cores (40 vs 16). at 100% residency that only turns into 1.54x decode (81 -> 125 tok/s, memory-bw bound past that, and the 125 matches your resident number). but it collapses as you drop residency: so 2.5x the cores is only 1.2x at 25%, and ttft barely moves. at low residency both boxes just hit the ssd floor. misses go 30k (50%) -> 155k (25%) -> 361k (12.5%) on this prompt, thats what decode and ttft track, not the gpu. more gpu doesnt buy you out of low-residency latency. two follow-ons maybe worth a doc line. ttft scales with prompt length, yours is 585 tok at 9.6s @25%, this is ~1.8k tok at 26-31s @25% on the same hardware class, longer prefill routes through more experts. so long-context pays most of the cost up front. decode stays fine (35-43 tok/s @25%), its prefill thats expensive. also works with response_format. served it at 0.25 (rss 4.5gb so actually streaming, not resident) plus a strict json_schema through xgrammar, valid schema-conforming output, GrammarCompiler active in the log. so a 26b doing constrained json in ~4.5gb as a batching server, which the standalone streaming engines dont give you. full per-residency json below if useful. |
|
Thanks for running the extra hardware checks. They show that the basic offload path works on the checkpoints tested and that the memory savings are real. I still hit a mixed-quantization crash. The default server path also needs coverage. The Gemma 4 checkpoint in the docs is detected as a VLM, but this PR only installs offload in EnginePool still checks the full checkpoint size as well. That means a model over the memory ceiling is rejected before offload has a chance to reduce its resident footprint. Before merge, please add tests for those three paths: mixed-bit projections, normal Gemma 4 VLM dispatch, and EnginePool admission when the full checkpoint is over the limit but the offloaded model should fit. |
Addresses the review item on jundot#2595: ExpertCache took group_size/bits/mode from gate_proj and reused them for every projection, so a GLU with mixed bit widths (e.g. 3-bit gate/up + 8-bit down) crashed gather_qmm on a packed-shape mismatch. - ExpertCache.meta[name] = (group, bits, mode) per projection - qmm/qmm_native read the projection's own metadata - native_kind requires ALL projections to share one qualifying combo (mixed formats -> gather_qmm fallback, same contract as the stock all()-check on native_kinds) - regression test: synthetic DS4 with 3-bit gate/up + 8-bit down affine wraps, metadata per projection asserted, decode + sorted prefill bit-exact vs resident twin Suite: 21 passed (15 base + 6 DS4, incl. the new mixed-bit test).
|
Thanks for the thorough review @jundot — the mixed-bit point is a real one, and it bites our follow-up too, so we picked it up there. We're stacking a follow-up PR (beatakouchnir#1) on #2595 that adds DeepSeek V4 / GLM-5.2 coverage to the same store. To keep this PR's scope tight we moved the mixed-bit fix into the follow-up, with the regression test you asked for:
On the other two items — VLMBatchedEngine dispatch and EnginePool admission — those are engine-wiring scope; happy to help either way:
Let us know what's most useful — otherwise the follow-up PR is ready for review whenever #2595 settles. |
|
@jundot thank you for the review — all three are addressed, one commit per item. Mixed-bit projections (bd49b7d): confirmed. Gemma 4 VLM dispatch (da21860): right again — discovery matched with EnginePool admission (c81366c): when offload is enabled for the model, admission now uses an offload-adjusted estimate — a safetensors header scan totals expert bytes (stacked 3-D I also merged main to clear the conflict with the distributed-cluster admission changes (70be6bf). One deliberate interaction: the offload discount only applies when Fast suites pass ( |
|
@tiagoflino saw #2616 — thanks for keeping the attribution clear and stating the rebase intent up front. One thing to flag so the two threads don't diverge: the three review items above are already fixed in this PR — bd49b7d (mixed-bit, per-projection Given that, the clean sequencing seems to be: this PR merges as the reviewed foundation, and #2616 becomes the DS4/GLM delta — which is the part that genuinely needs its own review. You don't have to wait for the merge to get there: rebasing #2616 onto this branch now drops the duplicates and the divergent mixed-bit fix. The native-path constraint you described (all projections must share one qualifying combo, else fall back to The DSpark window-union number (~42/layer for 7×6) and the |
|
Two updates: Rebase done. #2616 now carries the review-fixed branch (bd49b7d per-projection Admission estimate vs real measurements (DeepSeek-V4-Flash-0731-2.4bit-mixed, 92.8 GB on disk, M5 Pro 48 GB):
The estimate runs ~10% above measured at both points — a healthy conservative margin (the measurement excludes some lazy allocations), and the model admits on this box at both fractions. Note the measured numbers include the KV/pooling caches for a short context; long-context runs would close part of the gap. Also happy to fold the DSpark window-union (~42 experts/layer for a 7×6 verify) and the |
|
Following up on the admission-estimator finding from #2616 (comment) — that code is from this PR (c81366c, carried unchanged into #2616), so the fix belongs here. Pushed in 94985ef:
Regression tests cover the Separating the DS4/GLM compatibility work from the prefetch/pinning changes sounds right to me as well — it keeps this base PR reviewable on its own terms. |
|
rebased the branch onto 0.6.0 since main moved under it and the PR went conflicting. result is on my fork: two findings beyond the mechanical rebase, both fixed there:
local run on the rebased branch: test_engine_pool 130 passed, offload suites 39 passed, settings template 8 passed. @jundot with your three items addressed and this, ready for re-review. |
|
third find, this one live on our fleet: with offload enabled the VLM path dies on the first request with |
|
Thanks — One admission edge remains. For per-expert layouts, the estimator unions field names and expert IDs independently. A checkpoint with one complete expert and 31 experts containing only The PR head is still |
94985ef to
5309c8a
Compare
ExpertCache took group_size/bits/mode from gate_proj and applied them to all three projections, decoding garbage from mixed-bit checkpoints (e.g. oQ profiles quantizing down_proj at 8-bit over 4-bit gate/up). Keep the metadata per projection and pass the right triple to each gather_qmm. Regression test quantizes gate/up at 4-bit and down at 8-bit and requires bit-exact decode and prefill against the resident module. Reported-by: @jundot (jundot#2595 review) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Discovery matched modules with 'type(obj) is SwitchGLU' against mlx-lm's class, but mlx-vlm defines its own SwitchGLU — so Gemma 4 checkpoints, which default to the VLM engine, silently never offloaded. Match by class name plus the attribute contract instead (same for QuantizedSwitchLinear), and give VLMBatchedEngine the same lazy-load -> wrap -> materialize sequence and gate/up-fusion skip that BatchedEngine runs. Tests: a fast regression wraps a SwitchGLU-named class that is not mlx-lm's and requires bit-exact output, and a slow live test loads Gemma 4 through mlx_vlm.utils.load and requires wrapped layers, finite logits, and cache traffic through the wrapped forward. Reported-by: @jundot (jundot#2595 review) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Admission compared the full checkpoint size against the memory ceiling,
so the over-ceiling MoE models expert offload exists for were rejected
before the feature could run. When offload is enabled for the model,
estimate_offload_admission_bytes() header-scans the checkpoint for expert
tensors — stacked 3-D {gate,up,down}_proj under any container name, or
per-expert '.experts.<n>.' — and subtracts the non-resident share; any
failure falls back to the plain size, so admission never gets more
permissive by accident.
Tests: estimator unit test over a real checkpoint (switch_mlp-named, so
matching is proven shape-based, plus the missing-path fallback), and a
pool test where a model over the ceiling admits with offload enabled and
still refuses without it.
Reported-by: @jundot (jundot#2595 review)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
|
@fxd0h, thank you — I've adopted your branch as the PR head and force-pushed; your commits keep their authorship, so no fork access needed. The @jundot, the per-expert admission edge is fixed in 5309c8a6: field completeness is tracked per expert, and a container discounts only when every expert has all three quantized projections — the same rule Suites on the new head: offload + engine-pool 153 passed, settings template 8 passed. Agreed on scope — DS4, prefetch, and pinning stay in #2616. |
5309c8a to
01ee86d
Compare
moe_expert_offload_enabled (default off) and moe_expert_offload_resident_fraction (default 0.25, validated to (0, 1] at construction) on ModelSettings, with the full plumbing: model-specific profile allowlist, admin API request/apply/reset paths, dashboard toggle with residency selector (en locale keys; other locales fall back to English), and the engine-pool runtime signature so toggling triggers a reload — fraction participates only while the feature is enabled, per the signature's dependent-field convention. When offload wraps any layers the engine now skips gate/up fusion explicitly with a log line: fusion concatenates stock SwitchGLU weights in RAM, which cannot apply to experts that were never materialized. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The live test (slow-marked, skipped unless the checkpoint is cached) loads gemma-4-26b-a4b-it-4bit through the engine's lazy-wrap-materialize sequence at 25% residency and requires: peak memory well under the resident model's size (proof non-resident experts never materialized), sane hit rates, and greedy generations matching the fully resident model — allowing at most one paraphrase-level rounding fork across four prompts per the documented numerical contract. Passes in ~35 s with both arms in one process. docs/MoE_Expert_Offload.md follows the benchmark-first house style: measured memory/throughput table across residencies (14.2 -> 3.0 GB, 122 -> 29 tok/s decode), enablement, supported-model matrix and skip semantics, why pinned-expert subsets are the design to avoid (measured), and the behavioral acceptance methodology including why cross-capacity output diffing is invalid. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…onestly The coverage gate validated names and shapes but not storage dtype tags, so a checkpoint field in an unrecognized quantization format would pass coverage and then KeyError at the first cache miss mid-generation. Validate dtypes at coverage time so the failure mode stays 'runs resident', with a regression test that rewrites a safetensors header tag in place. Docs and scope language corrected from 'covers every family' to what is actually established: type-targeted across ~40 SwitchGLU families, end-to-end verified on gemma-4-26b-a4b-it-4bit, fail-safe skip for anything unmatched. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The second-family live check surfaced the gap: older mlx-community conversions store one tensor per expert under the GLU's parent (model.layers.N.mlp.experts.E.gate_proj.weight), which mlx-lm's sanitize() stacks at load — so the stacked names the store looked for never exist in those files and every layer skipped. The store view now detects the naming scheme per layer (stacked slab reads, or whole-tensor reads for per-expert layouts) behind the same ExpertCache interface, and coverage verifies every expert's tensors individually in the per-expert scheme. Layouts that also rename projections (Mixtral w1/w2/w3) still skip gracefully. Verified live on OLMoE-1B-7B-0125-Instruct-4bit: 16 layers wrapped, 3.89 GB -> 1.17 GB at 25% residency, greedy generations bit-identical to resident. Byte accounting now derives from module metadata, making it layout-agnostic. Two new fast tests cover the per-expert path: bit-exact forward through a per-expert checkpoint, and a skip when any single expert's tensor is missing. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
ExpertCache took group_size/bits/mode from gate_proj and applied them to all three projections, decoding garbage from mixed-bit checkpoints (e.g. oQ profiles quantizing down_proj at 8-bit over 4-bit gate/up). Keep the metadata per projection and pass the right triple to each gather_qmm. Regression test quantizes gate/up at 4-bit and down at 8-bit and requires bit-exact decode and prefill against the resident module. Reported-by: @jundot (jundot#2595 review) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Discovery matched modules with 'type(obj) is SwitchGLU' against mlx-lm's class, but mlx-vlm defines its own SwitchGLU — so Gemma 4 checkpoints, which default to the VLM engine, silently never offloaded. Match by class name plus the attribute contract instead (same for QuantizedSwitchLinear), and give VLMBatchedEngine the same lazy-load -> wrap -> materialize sequence and gate/up-fusion skip that BatchedEngine runs. Tests: a fast regression wraps a SwitchGLU-named class that is not mlx-lm's and requires bit-exact output, and a slow live test loads Gemma 4 through mlx_vlm.utils.load and requires wrapped layers, finite logits, and cache traffic through the wrapped forward. Reported-by: @jundot (jundot#2595 review) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Admission compared the full checkpoint size against the memory ceiling,
so the over-ceiling MoE models expert offload exists for were rejected
before the feature could run. When offload is enabled for the model,
estimate_offload_admission_bytes() header-scans the checkpoint for expert
tensors — stacked 3-D {gate,up,down}_proj under any container name, or
per-expert '.experts.<n>.' — and subtracts the non-resident share; any
failure falls back to the plain size, so admission never gets more
permissive by accident.
Tests: estimator unit test over a real checkpoint (switch_mlp-named, so
matching is proven shape-based, plus the missing-path fallback), and a
pool test where a model over the ceiling admits with offload enabled and
still refuses without it.
Reported-by: @jundot (jundot#2595 review)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…nors capacity floor The estimator discounted any .experts.<n>. tensor, including layouts the wrapper rejects (Mixtral-style w1/w2/w3 wrapped zero layers yet admission assumed savings), and ignored the minimum-eight capacity floor, so tiny fractions under-reported the resident share. It now derives from the same structural rules apply_moe_expert_offload enforces: a container counts only with all three quantized projections present in a supported layout, and per-layer savings use capacity = max(8, min(E, round(E*fraction))). Regressions cover the reported w1/w2/w3 repro, unquantized checkpoints, and a floor-binding fraction.
…sion is local-loads only the deployment-is-None guard around the admission discount lived in merge commit 70be6bf4, not in any replayed commit, so rebasing onto 0.6.0 silently discarded it. without it a distributed shard's planned size gets discounted by whole-checkpoint expert bytes and an over-ceiling cluster load admits with no eviction. region restored byte-identical to the pre-rebase tip, admission_kind placement included.
94985ef tightened estimate_offload_admission_bytes to count only containers with all three projections quantized (weight and scales) and floored capacity at 8 experts, but this fixture still wrote a lone gate_proj.weight with 4 experts, so the estimator saved nothing and the test failed on its own branch. the container is now 32 experts with all six tensors: 2400 expert bytes at 25% residency keeps 8 and saves 1800, the 2000-byte model admits under the 1500 ceiling, and the disabled path still refuses.
…quest dies the caches slot maps and resident slots live on plain object attributes, so materialize_lazy_state's module walk never reaches them. left lazy they stay bound to the loader thread's stream and the first inference request dies with RuntimeError: There is no Stream(gpu, N) in current thread. reproduced live on a 24GB M5 Pro the moment the VLM path ran with offload enabled; with the fix the same box serves gemma-4-26B at 10.1GB resident (fraction 0.5) instead of 16GB, warning-free xgrammar included. materialize_offload_state walks the model like moe_offload_stats does, collects every cache's map and resident slots, and evaluates them on the same executor that ran the apply. wired into both engines right after apply_moe_expert_offload. the regression test rebuilds the exact loader-thread/inference-thread split.
The estimator unioned field names and expert ids independently, so one complete expert vouched for a container full of incomplete ones: a checkpoint with one complete expert and 31 gate-only experts was estimated at 972,736 bytes of 1,000,000 while apply_moe_expert_offload() wrapped zero modules. Field completeness is now tracked per expert and a container discounts only when every expert carries all three quantized projections — the same rule the wrapper enforces. Regressions cover the reported repro and a fully-complete control with the capacity floor.
The expert-offload settings surface added three modal.model_settings.moe_expert_offload* keys to en.json but not the other locales, breaking the locale key-set parity test (test_locale_key_sets_identical). Add them to all eight locales with the English string as an untranslated placeholder, matching the existing convention (≈40% of es.json keys already carry the English value pending translation). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ERWSeTnvoPjsvxTYDYpqJv
9b48119 to
a410ea3
Compare
|
Thanks for implementing this. The lazy-load replacement keeps non-resident experts out of memory, and I verified the Gemma offload path locally. I'll add the DeepSeek V4.1 and Qwen3.8-Flash-Next support I've tested in a follow-up, along with the settings wiring, memory accounting fixes, and MTP exclusion. I'll also show the experimental toggle only for supported model types with compatible checkpoint layouts. Merging this first, then applying the follow-up. |
|
Thank you, @jundot! Happy to help with the Flash-Next / DeepSeek-V4.1 follow-up if that would be useful: I've been running large MoEs with expert offload on a 128 GB Mac (Qwen3.5-397B-A17B end-to-end, decode bit-identical to resident; Qwen3.8-Flash-Next in progress), so the checkpoint-layout gating and MTP exclusion you mention are right in what I've been working on. |
* feat(moe): expert offload runtime — stream non-resident experts from the checkpoint Adds omlx/patches/moe_expert_offload.py: replace stock SwitchGLU instances with an LRU expert cache (contiguous resident slots, fetch-on-miss) whose store is the model's own safetensors shards, read as mmap slab slices — no converted copy of the checkpoint, no write path. Applied pre-materialize so non-resident experts are never loaded; routing is computed exactly as shipped, so accuracy is preserved by construction at a latency cost. Numerical contract, measured against the pinned mlx-lm: decode and unsorted/chunked prefill bit-identical at any residency; sorted prefill bit-identical at real model geometry (the kernel is presentation-invariant there); chunked-below-sort-threshold cases bounded by the ~4e-3 sorted-vs-unsorted kernel difference. Test suite encodes exactly that policy (12 fast synthetic tests + 3 slow real-geometry tests). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(moe): wire expert offload into the batched engine load path When moe_expert_offload_enabled is set on model settings, load lazily and run apply_moe_expert_offload as an MLX-executor step between apply_post_load_transforms and materialize_lazy_state — the stock modules are dropped while still lazy, so non-resident experts never materialize. With the setting off (default), the load path is byte-for-byte unchanged. Hub repo ids resolve to the local snapshot via huggingface_hub with allow_patterns=['*.safetensors'] and local_files_only=True: never a download, and tolerant of mlx-lm-style partial caches (a patternless local lookup demands the repo's full file list and fails on them). Verified on gemma-4-26b-a4b-it-4bit at 25% residency through this exact sequence: 30 layers wrapped, load peak 4.69 GB vs 14.28 GB eager (the full expert set is never held), post-generation active 4.57 GB vs 14.20, hit rate 0.771, and greedy generations bit-identical to the resident model on both test prompts. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(moe): settings and admin surface for expert offload moe_expert_offload_enabled (default off) and moe_expert_offload_resident_fraction (default 0.25, validated to (0, 1] at construction) on ModelSettings, with the full plumbing: model-specific profile allowlist, admin API request/apply/reset paths, dashboard toggle with residency selector (en locale keys; other locales fall back to English), and the engine-pool runtime signature so toggling triggers a reload — fraction participates only while the feature is enabled, per the signature's dependent-field convention. When offload wraps any layers the engine now skips gate/up fusion explicitly with a log line: fusion concatenates stock SwitchGLU weights in RAM, which cannot apply to experts that were never materialized. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(moe): live acceptance test + feature docs for expert offload The live test (slow-marked, skipped unless the checkpoint is cached) loads gemma-4-26b-a4b-it-4bit through the engine's lazy-wrap-materialize sequence at 25% residency and requires: peak memory well under the resident model's size (proof non-resident experts never materialized), sane hit rates, and greedy generations matching the fully resident model — allowing at most one paraphrase-level rounding fork across four prompts per the documented numerical contract. Passes in ~35 s with both arms in one process. docs/MoE_Expert_Offload.md follows the benchmark-first house style: measured memory/throughput table across residencies (14.2 -> 3.0 GB, 122 -> 29 tok/s decode), enablement, supported-model matrix and skip semantics, why pinned-expert subsets are the design to avoid (measured), and the behavioral acceptance methodology including why cross-capacity output diffing is invalid. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(moe): skip layers whose checkpoint dtype is unknown; scope docs honestly The coverage gate validated names and shapes but not storage dtype tags, so a checkpoint field in an unrecognized quantization format would pass coverage and then KeyError at the first cache miss mid-generation. Validate dtypes at coverage time so the failure mode stays 'runs resident', with a regression test that rewrites a safetensors header tag in place. Docs and scope language corrected from 'covers every family' to what is actually established: type-targeted across ~40 SwitchGLU families, end-to-end verified on gemma-4-26b-a4b-it-4bit, fail-safe skip for anything unmatched. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(moe): support per-expert checkpoint layouts (OLMoE/Qwen2-MoE style) The second-family live check surfaced the gap: older mlx-community conversions store one tensor per expert under the GLU's parent (model.layers.N.mlp.experts.E.gate_proj.weight), which mlx-lm's sanitize() stacks at load — so the stacked names the store looked for never exist in those files and every layer skipped. The store view now detects the naming scheme per layer (stacked slab reads, or whole-tensor reads for per-expert layouts) behind the same ExpertCache interface, and coverage verifies every expert's tensors individually in the per-expert scheme. Layouts that also rename projections (Mixtral w1/w2/w3) still skip gracefully. Verified live on OLMoE-1B-7B-0125-Instruct-4bit: 16 layers wrapped, 3.89 GB -> 1.17 GB at 25% residency, greedy generations bit-identical to resident. Byte accounting now derives from module metadata, making it layout-agnostic. Two new fast tests cover the per-expert path: bit-exact forward through a per-expert checkpoint, and a skip when any single expert's tensor is missing. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(moe-offload): per-projection quant params in expert cache ExpertCache took group_size/bits/mode from gate_proj and applied them to all three projections, decoding garbage from mixed-bit checkpoints (e.g. oQ profiles quantizing down_proj at 8-bit over 4-bit gate/up). Keep the metadata per projection and pass the right triple to each gather_qmm. Regression test quantizes gate/up at 4-bit and down at 8-bit and requires bit-exact decode and prefill against the resident module. Reported-by: @jundot (jundot#2595 review) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(moe-offload): wrap mlx-vlm SwitchGLU and wire the VLM engine Discovery matched modules with 'type(obj) is SwitchGLU' against mlx-lm's class, but mlx-vlm defines its own SwitchGLU — so Gemma 4 checkpoints, which default to the VLM engine, silently never offloaded. Match by class name plus the attribute contract instead (same for QuantizedSwitchLinear), and give VLMBatchedEngine the same lazy-load -> wrap -> materialize sequence and gate/up-fusion skip that BatchedEngine runs. Tests: a fast regression wraps a SwitchGLU-named class that is not mlx-lm's and requires bit-exact output, and a slow live test loads Gemma 4 through mlx_vlm.utils.load and requires wrapped layers, finite logits, and cache traffic through the wrapped forward. Reported-by: @jundot (jundot#2595 review) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(engine-pool): admit oversized MoE models by offload-adjusted size Admission compared the full checkpoint size against the memory ceiling, so the over-ceiling MoE models expert offload exists for were rejected before the feature could run. When offload is enabled for the model, estimate_offload_admission_bytes() header-scans the checkpoint for expert tensors — stacked 3-D {gate,up,down}_proj under any container name, or per-expert '.experts.<n>.' — and subtracts the non-resident share; any failure falls back to the plain size, so admission never gets more permissive by accident. Tests: estimator unit test over a real checkpoint (switch_mlp-named, so matching is proven shape-based, plus the missing-path fallback), and a pool test where a model over the ceiling admits with offload enabled and still refuses without it. Reported-by: @jundot (jundot#2595 review) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(moe-offload): admission estimate counts only wrappable layers, honors capacity floor The estimator discounted any .experts.<n>. tensor, including layouts the wrapper rejects (Mixtral-style w1/w2/w3 wrapped zero layers yet admission assumed savings), and ignored the minimum-eight capacity floor, so tiny fractions under-reported the resident share. It now derives from the same structural rules apply_moe_expert_offload enforces: a container counts only with all three quantized projections present in a supported layout, and per-layer savings use capacity = max(8, min(E, round(E*fraction))). Regressions cover the reported w1/w2/w3 repro, unquantized checkpoints, and a floor-binding fraction. * restore the merge resolution the linear rebase dropped: offload admission is local-loads only the deployment-is-None guard around the admission discount lived in merge commit 70be6bf4, not in any replayed commit, so rebasing onto 0.6.0 silently discarded it. without it a distributed shard's planned size gets discounted by whole-checkpoint expert bytes and an over-ceiling cluster load admits with no eviction. region restored byte-identical to the pre-rebase tip, admission_kind placement included. * fix the engine-pool offload fixture the estimator update left behind 94985ef tightened estimate_offload_admission_bytes to count only containers with all three projections quantized (weight and scales) and floored capacity at 8 experts, but this fixture still wrote a lone gate_proj.weight with 4 experts, so the estimator saved nothing and the test failed on its own branch. the container is now 32 experts with all six tensors: 2400 expert bytes at 25% residency keeps 8 and saves 1800, the 2000-byte model admits under the 1500 ceiling, and the disabled path still refuses. * materialize offload cache state on the loader stream, or the first request dies the caches slot maps and resident slots live on plain object attributes, so materialize_lazy_state's module walk never reaches them. left lazy they stay bound to the loader thread's stream and the first inference request dies with RuntimeError: There is no Stream(gpu, N) in current thread. reproduced live on a 24GB M5 Pro the moment the VLM path ran with offload enabled; with the fix the same box serves gemma-4-26B at 10.1GB resident (fraction 0.5) instead of 16GB, warning-free xgrammar included. materialize_offload_state walks the model like moe_offload_stats does, collects every cache's map and resident slots, and evaluates them on the same executor that ran the apply. wired into both engines right after apply_moe_expert_offload. the regression test rebuilds the exact loader-thread/inference-thread split. * fix(moe-offload): per-expert admission requires every expert complete The estimator unioned field names and expert ids independently, so one complete expert vouched for a container full of incomplete ones: a checkpoint with one complete expert and 31 gate-only experts was estimated at 972,736 bytes of 1,000,000 while apply_moe_expert_offload() wrapped zero modules. Field completeness is now tracked per expert and a container discounts only when every expert carries all three quantized projections — the same rule the wrapper enforces. Regressions cover the reported repro and a fully-complete control with the capacity floor. * fix(i18n): add moe_expert_offload keys to non-English locales The expert-offload settings surface added three modal.model_settings.moe_expert_offload* keys to en.json but not the other locales, breaking the locale key-set parity test (test_locale_key_sets_identical). Add them to all eight locales with the English string as an untranslated placeholder, matching the existing convention (≈40% of es.json keys already carry the English value pending translation). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ERWSeTnvoPjsvxTYDYpqJv --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> Co-authored-by: Mariano Abad <weimaraner@gmail.com>
Closes #986.
MoE models leave most of their parameters idle on any given token. This PR
keeps a configurable fraction of each layer's experts resident in a fixed
slot cache and streams the rest from the checkpoint's own safetensors on
demand — mmap slab reads, no converted copy of the model, no write path.
Routing is computed exactly as shipped: a cache miss changes when an
expert's weights are read, never which expert runs, so accuracy is
preserved by construction and the entire cost is latency.
The key mechanism: with the feature enabled the load stays lazy, and stock
SwitchGLUmodules are replaced beforematerialize_lazy_state, sonon-resident experts are never materialized at any point in the process's
life — which is what lets a model larger than physical memory load at all.
Measured
gemma-4-26b-a4b-it-4bit(30 MoE layers × 128 experts), loaded through thebatched engine's own sequence; 585-token prompt, 256 generated, warm cache:
Peak is the load-transient proof: the full expert set is never held. Greedy
generations at 25% residency are bit-identical to the fully resident
model on the acceptance-test prompts.
Behind the design sits a measurement study I ran on my own implementation of
this technique (full record):
labeled accuracy is flat down to 12% residency (≤0.6pp gsm8k spread across a
4× capacity range; 1.5pp ifeval across 5.3×), and at matched memory (~7.4 GB)
2-bit quantization keeps 0.115 ifeval where 50%-resident offload keeps
0.869. I also cross-validated the pending mlx-lm implementation of the same
family (ml-explore/mlx-lm#1588) with the same method: 57/60 generations
bit-identical, paired-entropy verdict clean, labeled gsm8k at n=200
statistically indistinguishable (McNemar p = 0.61). Two implementations,
same result: the fetch-on-miss family is behaviorally safe.
Two design notes from that record, encoded in the docs page:
usage-calibrated pins, zeroing the non-pinned half costs ~91% of gsm8k
accuracy, because multi-step generation compounds per-token errors.
Fetch-on-miss keeps the computation exact and pays in latency.
settings. Capacity changes gather/reduction order, so greedy outputs can
fork at marginal tokens mid-generation while being semantically exact —
deterministic at any fixed setting, never at token 0. The valid comparison
is behavioral (labeled accuracy at n, or paired entropy), which is what the
test suite does.
What's in the PR
omlx/patches/moe_expert_offload.py—ExpertCache(fixed preallocatedslots per layer, LRU, in-place slot overwrite so eviction causes no
alloc/free churn against the pinned buffer pool),
OffloadSwitchGLU(mirrors the stock sort/kernel decisions; chunks any prefill whose expert
working set exceeds capacity, with per-chunk eval to bound the transient),
CheckpointExpertStore(safetensors header parse + mmap reads — expertslabs of stacked tensors, or whole tensors for per-expert layouts; bf16
travels as uint16), fail-safe discovery (every layer verified
against the checkpoint — quantized projections, tensor names, shapes —
and skipped with a logged reason otherwise),
OMLX_MOE_EXPERT_OFFLOAD=0kill switch.
MLX-executor step between
apply_post_load_transformsandmaterialize_lazy_state(fix(engine): per-engine threads to eliminate cross-engine stream contamination #1304 pattern). With the setting off, the loadpath is unchanged. When offload wraps layers, Qwen gate/up fusion is
skipped with a logged reason (it concatenates stock expert weights in RAM,
which cannot apply to experts that were never materialized).
ModelSettingsfields (fraction validated to (0, 1]at construction), model-specific profile allowlist, admin API
request/apply/reset, dashboard toggle with a residency selector, and the
engine-pool runtime signature so toggling reloads (fraction participates
only while enabled, per the dependent-field convention).
incl. bf16 and multi-shard, wrap + forward bit-exactness at partial
residency in both checkpoint layouts, batch invariance, chunking, every
skip path including unknown storage dtypes and a per-expert layout with a
missing expert, kill switch,
idempotency), 3 slow real-geometry tests (sorted-path bit-exactness at
gemma dimensions), and a slow live acceptance test that loads the real
checkpoint offloaded and resident and requires matching generations and a
fractional memory peak (skips unless the checkpoint is cached).
docs/MoE_Expert_Offload.md— benchmark-first feature doc.Numerical contract
Measured against the pinned mlx-lm: decode and unsorted prefill are
bit-identical to the stock path at any residency; the sorted prefill kernel
is presentation-invariant at real model dimensions, so full-residency
prefill is bit-identical too; a prefill chunked below the sort threshold
differs only by the ~4e-3 sorted-vs-unsorted
gather_qmmkernel rounding.The tests assert exactly this — bit-exactness where the kernel path is
identical, a rounding-bounded tolerance where it legitimately is not.
Scope and follow-ups
Targets every family whose MoE layers use upstream mlx-lm
SwitchGLUwith quantized experts (~40 model files — Qwen3.5/3.6 MoE, Gemma MoE,
Mixtral, Llama-4, Kimi, OLMoE, gpt-oss, …): the wrap is type-based, and
every layer is verified against the checkpoint before wrapping (quantized
projections, tensor names, shapes, known storage dtypes), so a family that
does not match — renamed projections (Mixtral's
w1/w2/w3), per-expertbias, unknown quantization formats — skips with a logged reason and runsresident exactly as today. Both checkpoint layouts in the wild are
supported: stacked
[E, ...]tensors and the older one-tensor-per-expertlayout that
sanitize()stacks at load. End-to-end verified ongemma-4-26b-a4b-it-4bit(stacked,switch_glu) andOLMoE-1B-7B-0125-Instruct-4bit(per-expert,switch_mlp; 16 layers,3.89 GB → 1.17 GB, generations bit-identical); the live acceptance test
takes any cached MoE checkpoint, and I'm happy to run it against specific
families reviewers care about. DeepSeek-V4 and GLM-5.2 use oMLX's native switch kernels — a
planned follow-up on the same store, once the mechanism has settled here.
The native macOS app is unaffected (its settings DTOs are optional-field
and ignore unknown keys) and the setting stays editable from the web
dashboard it links to; a native toggle on the app's model-settings screen
is a small follow-up I'm glad to do if wanted.
v1 fetches synchronously on miss, so TTFT at low residency is the pain
point; prefill's full expert-access schedule is computable before any fetch
(run the router over the prompt — no prediction needed), and decode prefetch
has measured LRU→optimal headroom of +17pp hit rate, so an async prefetch
follow-up has a clear, quantified path.
🤖 Generated with Claude Code