Skip to content

feat(moe): expert offload — stream non-resident experts from the checkpoint - #2595

Merged
jundot merged 15 commits into
jundot:mainfrom
beatakouchnir:feature/moe-expert-streaming
Sep 11, 2026
Merged

jundot merged 15 commits into
jundot:mainfrom
beatakouchnir:feature/moe-expert-streaming

Conversation

@beatakouchnir

Copy link
Copy Markdown
Contributor

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
SwitchGLU modules are replaced before materialize_lazy_state, so
non-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 the
batched engine's own sequence; 585-token prompt, 256 generated, warm cache:

residency memory after gen process peak decode tok/s TTFT per-request hit rate
100% (today's path) 14.20 GB 14.84 GB 122.5 0.30 s —
50% 7.78 GB 8.12 GB 59.4 2.9 s 0.89
25% 4.57 GB 4.85 GB 40.1 9.6 s 0.67
12.5% 2.96 GB 3.24 GB 29.3 18.1 s 0.45

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:

  • Pinning a "hot" expert subset is the design to avoid — measured with
    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.
  • Don't acceptance-test this by diffing outputs across residency
    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 preallocated
    slots 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 — expert
    slabs 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=0
    kill switch.
  • Engine wiring — lazy load gated on the setting; the wrap runs as its own
    MLX-executor step between apply_post_load_transforms and
    materialize_lazy_state (fix(engine): per-engine threads to eliminate cross-engine stream contamination #1304 pattern). With the setting off, the load
    path 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).
  • Settings and admin — ModelSettings fields (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).
  • Tests — 15 fast synthetic tests in the default CI suite (store roundtrips
    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_qmm kernel 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 SwitchGLU
with 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-expert
bias, unknown quantization formats — skips with a logged reason and runs
resident exactly as today. Both checkpoint layouts in the wild are
supported: stacked [E, ...] tensors and the older one-tensor-per-expert
layout that sanitize() stacks at load. End-to-end verified on
gemma-4-26b-a4b-it-4bit (stacked, switch_glu) and
OLMoE-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

@tiagoflino

Copy link
Copy Markdown

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.

  • Hardware: MacBook Pro M5 Pro, 48 GB unified, macOS 26.4
  • Checkpoint: Jundot/gemma-4-26B-A4B-it-oQ4e-mtp (16 GB, oMLX-native oQ4e quant, stacked [E, ...] layout) — straight from a local LM Studio model folder, no downloads, no conversion
  • Setup: load_model(..., lazy=True, strict=False) (the checkpoint bundles an MTP head the plain mlx-lm path doesn't know; dropped for this run since it targets the offload mechanism), then apply_moe_expert_offload(model, path, 0.25) before materialize_lazy_state

Results:

metric offloaded @25% fully resident limit
active memory after 4×96-token gens 5.01 GB 14.65 GB < 55% ✓
peak memory 5.13 GB — < 75% ✓
generations (4 prompts) 4/4 bit-identical — ≤ 1 fork ✓
wrapped layers 30/30 MoE — > 0 ✓
  • Materialized at ~1.8 GB active (model is 16 GB on disk) — the load-peak proof holds: non-resident experts were never materialized
  • misses > 0 and hit rate in range — the cache was actually exercised

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 sanitize()). That suggests the same CheckpointExpertStore serves the oQ-family formats the native-kernel models use — the remaining work is the native-kernel OffloadSwitchGLU wrap, plus the MTP/DSpark interaction during speculative decode (draft+verify doubles the per-step expert fetches).

@beatakouchnir

Copy link
Copy Markdown
Contributor Author

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.

@tiagoflino

Copy link
Copy Markdown

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):

  1. The offloaded switch inherits the chunking from your design, so a DSpark verify window whose expert union exceeds capacity degrades to chunked execution rather than breaking — safe, just slower. The sizing guidance that matters is the one you name: reserve for the window-union (draft_len × top_k distinct experts per layer), which for Flash 0731's DSpark (7 draft tokens × 6 experts) is ~42/layer — inside a 25% residency capacity (64/layer), but that's the number to put in the docs.

  2. Validating on the real mlx-community/DeepSeek-V4-Flash-0731-2.4bit-mixed now (MTP off first; DSpark-on sizing as a measured follow-up, since draft+verify doubles fetch traffic on top of the widening). One detail worth a doc line for >RAM checkpoints: the bare-model load needs strict=False because the 0731 checkpoint bundles mtp.* tensors.

Happy to open the follow-up PR once the live numbers are in.

@fxd0h

fxd0h commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

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:

resid   decode 16-core -> 40-core    ttft 16-core -> 40-core
100%    81 -> 125                    1.0 -> 0.5s
50%     37 -> 60                     24 -> 5.9s
25%     35 -> 43                     31 -> 26s
12.5%   27 -> 32                     52 -> 47s

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.

@jundot

jundot commented Aug 12, 2026

Copy link
Copy Markdown
Owner

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. ExpertCache takes group_size, bits, and mode from gate_proj and reuses them for the other projections. With 4-bit gate/up projections and an 8-bit down projection, gather_qmm fails because the weight and scale shapes no longer match. Each projection needs its own quantization metadata, plus a regression test using mixed bit widths.

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 BatchedEngine. The normal VLMBatchedEngine path does not apply it.

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.

tiagoflino added a commit to tiagoflino/omlx that referenced this pull request Aug 12, 2026
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).
@tiagoflino

Copy link
Copy Markdown

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:

  • ExpertCache.meta[name] = (group_size, bits, mode) per projection; qmm/qmm_native read the projection's own metadata
  • the native block path requires all projections to share one qualifying combo — mixed formats fall back to gather_qmm (same contract as the stock all() check on native_kinds)
  • regression test: synthetic DS4 with 3-bit gate/up + 8-bit down affine — wraps, per-projection metadata asserted, decode and sorted prefill bit-exact vs the resident twin (CI-runnable, no checkpoint download)

On the other two items — VLMBatchedEngine dispatch and EnginePool admission — those are engine-wiring scope; happy to help either way:

  • we have the Gemma 4 oQ4e checkpoint locally (VLM-detected, same one from the docs), so we can exercise the VLMBatchedEngine path as a test bed if useful
  • for EnginePool, the "offloaded footprint" estimate is exactly what our live runs measure (18.1 GB active vs 92.8 GB on disk at 15% residency on a 48 GB box), so we can validate the admission threshold change against real numbers

Let us know what's most useful — otherwise the follow-up PR is ready for review whenever #2595 settles.

@tiagoflino

Copy link
Copy Markdown

Update: the follow-up PR is now open in the upstream repo (carrying this PR's commits in the same branch, so the complete feature lands in one place — will rebase to drop the duplicates once #2595 merges):

#2616

The mixed-bit fix mentioned above is included there with its regression test.

@beatakouchnir

Copy link
Copy Markdown
Contributor Author

@jundot thank you for the review — all three are addressed, one commit per item.

Mixed-bit projections (bd49b7d): confirmed. ExpertCache took group_size/bits/mode from gate_proj and applied them to all three projections. It now keeps the triple per projection and passes the right one 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.

Gemma 4 VLM dispatch (da21860): right again — discovery matched with type(obj) is SwitchGLU against mlx-lm's class, but mlx-vlm defines its own SwitchGLU, so the VLM engine (the default for Gemma 4 checkpoints) never wrapped anything. Matching is now by class name plus the attribute contract, and VLMBatchedEngine got the same lazy-load → wrap → materialize sequence and gate/up-fusion skip as BatchedEngine. Two tests: a fast one that wraps a SwitchGLU-named class that isn't mlx-lm's (bit-exact output), and a slow live one that loads gemma-4-26b-a4b-it-4bit through mlx_vlm.utils.load and requires wrapped layers, finite logits, and cache traffic through the wrapped forward.

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 {gate,up,down}_proj tensors under any container name, or per-expert .experts.<n>. names) and subtracts the non-resident share. Any failure falls back to the full size, so admission never gets more permissive by accident. Covered by a unit test over a real checkpoint (named switch_mlp, so the matching is shape-based rather than tied to one container name) plus a pool test where a model over the ceiling admits with offload enabled and still refuses without it.

I also merged main to clear the conflict with the distributed-cluster admission changes (70be6bf). One deliberate interaction: the offload discount only applies when deployment is None — a rank-zero shard's planned size shouldn't be reduced by whole-checkpoint expert bytes.

Fast suites pass (test_moe_expert_offload, test_engine_pool, test_batched_engine, test_vlm_engine), and the slow live acceptance tests were re-run against the real checkpoint after the merge.

@beatakouchnir

Copy link
Copy Markdown
Contributor Author

@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 qparams with a 4/8-bit bit-exact regression test), da21860 (VLM dispatch), c81366c (EnginePool admission) — and the branch is conflict-free and re-validated as of today. #2616's copy of this branch predates those commits, so it carries an alternative mixed-bit implementation (af3d3e5) and none of the VLM or admission work; as it stands it wouldn't satisfy the review above.

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 gather_qmm) composes cleanly with per-projection qparams, so the rebase should be mechanical.

The DSpark window-union number (~42/layer for 7×6) and the strict=False note on the 0731 checkpoint's mtp.* tensors are both worth a doc line — happy to fold them in here if jundot prefers docs to travel with the mechanism, otherwise they fit naturally in #2616. And a real-number check of the admission estimate on your 48 GB box would be genuinely useful.

@tiagoflino

Copy link
Copy Markdown

Two updates:

Rebase done. #2616 now carries the review-fixed branch (bd49b7d per-projection qparams, da21860 VLM dispatch, c81366c admission) plus our DS4/GLM delta — our alternative mixed-bit implementation was dropped in favor of the canonical qparams, and the native-path constraint (all projections share one qualifying combo, else fall back to gather_qmm) is implemented on top of it. 197 tests pass (base + VLM + pool + DS4 + our optimizations). When #2595 merges we'll rebase again to drop the duplicates and #2616 becomes the pure DS4/GLM delta.

Admission estimate vs real measurements (DeepSeek-V4-Flash-0731-2.4bit-mixed, 92.8 GB on disk, M5 Pro 48 GB):

residency estimate_offload_admission_bytes measured active (mx.get_active_memory)
15% 19.9 GB 18.1 GB (peak 18.3)
40% 41.3 GB 37.5 GB (peak 38.7)

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 strict=False note on the 0731 checkpoint's mtp.* tensors into #2616's docs — just say which side you'd rather carry them.

@beatakouchnir

Copy link
Copy Markdown
Contributor Author

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:

  • The estimate is now derived from the same structural rules apply_moe_expert_offload enforces, so it cannot promise savings the wrapper won't deliver: a container counts only when all three {gate,up,down}_proj projections are present with quantization scales in a supported layout. Renamed layouts (w1/w2/w3) and unquantized checkpoints match nothing and discount nothing — your 4,000→1,750-byte repro now returns the full size.
  • Per-layer savings honor the runtime's minimum-eight capacity floor (max(8, min(E, round(E·fraction)))), so small fractions no longer under-report the resident share.

Regression tests cover the w1/w2/w3 repro shape, an unquantized checkpoint, and a floor-binding fraction (0.05 on 32 experts → 75% max savings, not 95%).

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.

@fxd0h

fxd0h commented Aug 16, 2026

Copy link
Copy Markdown
Contributor

rebased the branch onto 0.6.0 since main moved under it and the PR went conflicting. result is on my fork: fxd0h/omlx branch feature/moe-expert-streaming-0.6.0 — @beatakouchnir cherry-pick it or give me push on your fork and i update the PR branch directly.

two findings beyond the mechanical rebase, both fixed there:

  1. a linear rebase silently drops the deployment is None guard around the admission discount, because it lives in merge commit 70be6bf4 and not in any replayed commit. without it a distributed shards planned size gets discounted by whole-checkpoint expert bytes and an over-ceiling cluster load admits with no eviction. restored byte-identical to the pre-rebase tip.
  2. test_moe_offload_admits_oversized_moe fails since 94985ef: the estimator now requires all three projections quantized and floors capacity at 8 experts, but the fixture still wrote a lone gate_proj.weight with 4 experts. fixed with a 32-expert quantized container (2400 expert bytes, saves 1800, admits under the 1500 ceiling).

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.

@fxd0h

fxd0h commented Aug 16, 2026

Copy link
Copy Markdown
Contributor

third find, this one live on our fleet: with offload enabled the VLM path dies on the first request with RuntimeError: There is no Stream(gpu, 1) in current thread. the caches slot maps and resident slots live on plain attributes, so materialize_lazy_state never reaches them and they stay bound to the loader threads stream. fix on the same branch (821d84f): materialize_offload_state walks the wrapped layers and evals map + resident slots on the executor that ran the apply, wired into both engines. regression test rebuilds the loader/inference thread split. with it a 24GB M5 Pro serves gemma-4-26B at 10.1GB resident (fraction 0.5) instead of 16GB — first time the feature runs end to end on the vision path for us.

@jundot

jundot commented Aug 16, 2026

Copy link
Copy Markdown
Owner

Thanks — 94985ef fixes the original w1/w2/w3 repro and the minimum-eight capacity floor. I also verified the VLM state-materialization fix in 821d84f1: the current PR head reproduces There is no Stream(gpu, 1) in current thread on the first Gemma 4 request, while the rebased candidate wraps all 30 layers and completes the same request successfully.

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 gate_proj.weight was estimated at 972,736 bytes from a 1,000,000-byte full size, even though apply_moe_expert_offload() rejected the layer and wrapped zero modules. Please validate the full required field set for every expert before applying a discount.

The PR head is still 94985ef and conflicting; bce55e50, 68090c9c, and 821d84f1 are currently only on the rebased fork branch. Once those are carried over and the per-expert admission case is covered, this base PR should be close to mergeable. The DS4, prefetch, and pinning work can remain separate in #2616.

@beatakouchnir
beatakouchnir force-pushed the feature/moe-expert-streaming branch from 94985ef to 5309c8a Compare August 16, 2026 15:14
beatakouchnir added a commit to beatakouchnir/omlx that referenced this pull request Aug 16, 2026
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>
beatakouchnir added a commit to beatakouchnir/omlx that referenced this pull request Aug 16, 2026
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>
beatakouchnir added a commit to beatakouchnir/omlx that referenced this pull request Aug 16, 2026
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>
@beatakouchnir

Copy link
Copy Markdown
Contributor Author

@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 deployment is None guard and the VLM materialization fix are both carried. The engine-pool fixture was my miss: I had run the offload suite with the estimator change but not the pool suite. Both run together now.

@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 ruleapply_moe_expert_offload() enforces. Your repro (1 complete + 31 gate-only experts) is a regression test returning the full size, with a fully-complete control asserting the discount and capacity floor.

Suites on the new head: offload + engine-pool 153 passed, settings template 8 passed. Agreed on scope — DS4, prefetch, and pinning stay in #2616.

@beatakouchnir
beatakouchnir force-pushed the feature/moe-expert-streaming branch from 5309c8a to 01ee86d Compare August 19, 2026 06:35
beatakouchnir and others added 13 commits September 10, 2026 22:38
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
@beatakouchnir
beatakouchnir force-pushed the feature/moe-expert-streaming branch from 9b48119 to a410ea3 Compare September 11, 2026 05:39
@jundot

jundot commented Sep 11, 2026

Copy link
Copy Markdown
Owner

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.

@jundot
jundot merged commit 6df0d8d into jundot:main Sep 11, 2026
3 checks passed
@beatakouchnir

Copy link
Copy Markdown
Contributor Author

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.

kaushikvira pushed a commit to kaushikvira/omlx that referenced this pull request Sep 12, 2026
* 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>
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.

Add Flash-MoE-style SSD-backed expert streaming for large MoE models

5 participants