Skip to content

feat(moe): expert offload for the GLM DSA MoE block (glm_moe_dsa) - #3696

Merged
jundot merged 2 commits into
jundot:mainfrom
beatakouchnir:feat/moe-offload-glm-moe-dsa
Sep 21, 2026
Merged

jundot merged 2 commits into
jundot:mainfrom
beatakouchnir:feat/moe-offload-glm-moe-dsa

Conversation

@beatakouchnir

@beatakouchnir beatakouchnir commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #2595 (expert offload primitive) and #3628 (V4.1 adapter). Closes the GLM half of #986; the ask behind ml-explore/mlx-lm#1438.

Problem

GLM-5.2 and GLM-5.3 (glm_moe_dsa: 78 layers, the first 3 dense, 256 routed experts, top-8, one shared expert) run their routed experts through oMLX's own GLM SwitchGLU, which fuses gate_proj and up_proj into gate_up_proj at load and, on sorted calls, returns the routes already weighted and summed by the native glm_moe_weighted_sum kernel. The common adapter wraps only the stock module, so moe_offload_compat hid the toggle for this family and the docs listed it as unsupported. mlx-community/GLM-5.2-4bit is 409 GiB, so on a 128 GB machine it had no path at all.

Change

  • omlx/patches/glm_moe_dsa/moe_offload.py: an adapter that keeps the module and its kernels. Each projection's parameters are replaced by slot tensors of capacity experts before lazy weights materialize, expert ids are translated to slot ids, and the module's own __call__ runs unchanged on them. Every kernel decision inside it (the sort threshold, the weighted sum, the inverse scatter) is a function of the routes and the slot tensors' shapes, and every use of an index is a gather, so a route computes the same numbers against its slot as against its expert. A miss reads the expert's split gate, up and down slabs from the checkpoint (the layout the checkpoints ship) with positional reads on a bounded pool, the V4.1 adapter's shape, and writes the two halves of the fused row in place. Over-capacity prefill is chunked on expert boundaries like the other adapters; when the caller asked for the weighted sum, it is applied to the reassembled routes the way the model does when the kernel is not used.
  • moe_expert_offload.py: apply_moe_expert_offload dispatches GLM blocks to the adapter and counts them once, so the engines need no change; _is_stock_switch_glu no longer matches the GLM class by name; estimate_offload_admission_bytes stops excluding glm_moe_dsa (its stacked switch_mlp layout is what the generic scan already counts); materialize_offload_state and moe_offload_stats recognize any adapter's cache.
  • moe_offload_compat.py: glm_moe_dsa allowed, reading n_routed_experts and skipping the first_k_dense_replace dense prefix.
  • docs/MoE_Expert_Offload.md: a GLM section with header-only sizing and the measured runs below.

Numerical contract

Unchanged in kind. The test suite asserts bit-exact output against the untouched module on the same routes for decode, for sorted prefill through the native weighted sum at full residency, and for sorted calls that fit the cache (keyed by slot rather than expert, every row still meets its own expert); a rounding-scale bound for over-capacity prefill. The native weighted-sum kernel takes half-precision activations and top-k 6 or 8 only, so the tests feed it bf16 and top-8 as the model does. Without the native kernels (a CI runner) the module returns sorted routes unsummed and the caller applies the scores; the adapter sums on its over-capacity path only under the module's own condition, and the tests run both ways.

Measured

mlx-community/GLM-5.2-4bit (409 GiB estimated, 20 MiB per expert) on an M5 Max 128 GB, internal SSD, loaded through the engine's own sequence (maybe_apply_pre_load_patches, lazy load, wrap, materialize), a 36-token chat prompt, 24 greedy tokens, single runs:

residency experts per layer footprint load cold TTFT decode decode hit rate misses per token
20% 51 86.6 GiB 3.3 s 20.4 s 1.8 tok/s 0.63 213
12.5% 32 58.4 GiB 2.6 s 18.8 s 1.5 tok/s 0.52 275

Header-only admission puts 20% at 105.0 GiB and 25% at 124.3 GiB, so 20% is the largest residency a 128 GB machine admits. Decode is bound by expert reads: 213 misses of 20 MiB per token is 4.2 GiB, and the positional reads move it at about 8 GiB/s (iostat showed 10.8 GB/s at 400 KB per transfer during prefill).

The same 20% configuration with misses served by the common store's memmap fetches measured 646 s to first token and 0.09 tok/s (iostat: 0.4 GB/s at 47 KB per transfer, the compute thread faulting 16 KiB pages), with identical output. That is the reason this adapter reads positionally rather than reusing the common store's fetch, and it is the same gap #3589 closes for the common adapter.

Continuations were coherent and identical between the cold and warm runs at each residency. Between residencies the two texts forked at one marginal token (a capitalization), the documented behavior of over-capacity prefill under a different chunking.

omlx serve end to end on the same machine (balanced memory guard, which puts the dynamic ceiling at 102.5 GB): the checkpoint is discovered from the HF cache; at 20% the request is refused with 507 because the 105.0 GB estimate does not fit that ceiling (the aggressive tier, or raising iogpu.wired_limit_mb, would admit it); at 12.5% it is admitted at a 76.9 GB estimate (57.6 GB actual), the engine loads in 3.7 s with 75 layers wrapped and gate/up fusion skipped, and two 24-token chat completions took 35.7 s and 34.0 s including prefill.

Tests

tests/test_glm_moe_dsa_offload.py (26, fused and split modules, the sorted cases with and without the native kernels so the shape contract holds on a runner that has none; the with-kernels cases skip where they are not built): wrap replaces the module and keeps only slot-sized tensors off the parameter tree; decode bit-exact at 25%; sorted prefill bit-exact at full residency with and without the weighted sum; sorted call within capacity bit-exact through the weighted sum; over-capacity prefill within 2e-2 with every distinct expert installed once and the read accounting matching; LRU eviction and counters; an uncovered checkpoint is skipped; kill switch; the common entry point dispatches and the shared walkers see the layer; the admission estimate discounts the experts. tests/test_moe_offload_compat.py: glm_moe_dsa in the header-only supported layouts with the dense prefix skipped, and a missing routed layer rejected by name.

pytest tests/test_glm_moe_dsa_offload.py tests/test_moe_expert_offload.py tests/test_moe_offload_compat.py tests/test_engine_pool.py tests/test_admin_api_key.py tests/test_model_settings.py tests/test_deepseek_v41_moe_offload.py tests/test_admin_model_settings_template.py -m "not slow": 466 passed. ruff clean on the changed files; the new files are black-formatted, existing files were not reformatted.

Not in this PR

GLM-5.3-Flash (glm5_next, the mlx-vlm path) stays unsupported: different module, and the Vontra checkpoint's heterogeneous per-expert quantization (#3380) is a loader problem before it is an offload one.

🤖 Generated with Claude Code

@williamxie1989

Copy link
Copy Markdown
Contributor

Heads-up: #3720 builds on this PR (cherry-picked) to extend the same pattern to the DeepSeek V4 / glm5_next SwitchGLU family (native block/pair kernels, split gate/up). If this merges first, #3720 rebases down to just its adapter + tests.

@jundot

jundot commented Sep 21, 2026

Copy link
Copy Markdown
Owner

The dedicated adapter makes sense for GLM's fused projections and weighted-sum kernels. I checked it on current main with the conflicts resolved, but found two runtime issues.

A valid per-expert checkpoint passes compatibility and receives an admission discount, yet the actual GLM loader produces a model that the adapter wraps at zero layers because resolve_view() only accepts stacked tensors. Please make eligibility, adapter reads, and admission agree, with a loader-level regression for both layouts.

_SlabReader.close() also has no caller. Ten wrap/release cycles leaked ten file descriptors even after garbage collection. Current main already provides positional reads through CheckpointExpertStore; please reuse that ownership where possible and verify that repeated load/unload returns the descriptor count to baseline.

beatakouchnir and others added 2 commits September 21, 2026 01:21
GLM-5.2 and GLM-5.3 (glm_moe_dsa: 78 layers, 256 routed experts, top-8)
run their experts through oMLX's own GLM SwitchGLU, which fuses gate/up at
load and sums sorted routes through the native glm_moe_weighted_sum kernel,
so the common adapter could not wrap them and the compat layer hid the
toggle. The 409 GiB 4-bit checkpoint therefore had no path onto a 128 GB
machine.

- omlx/patches/glm_moe_dsa/moe_offload.py: the module and its kernels are
  kept; each projection's parameters are replaced by resident slots before
  lazy weights materialize, expert ids are translated to slot ids, and the
  module's own forward runs unchanged on them (every kernel decision is a
  function of the routes and the slot tensors' shapes, every index use a
  gather). Misses read the split gate/up/down slabs the checkpoints ship
  with positional reads on a bounded pool, as the V4.1 adapter does, and
  write the two halves of the fused row in place. Over-capacity prefill is
  chunked on expert boundaries like the other adapters.
- moe_expert_offload: apply_moe_expert_offload dispatches GLM blocks to the
  adapter and counts them once; the admission estimate no longer excludes
  glm_moe_dsa (its stacked switch_mlp layout is the generic one); the
  materialize/stats walkers recognize any offload cache.
- moe_offload_compat: glm_moe_dsa allowed, with n_routed_experts and the
  first_k_dense_replace dense prefix.
- docs: a GLM section with sizing from the headers and the measured runs.

Tests: bit-exact against the resident module for decode, sorted prefill
through the native weighted sum at full residency, and sorted calls that
fit the cache; rounding-bounded over-capacity prefill; LRU eviction and
counters; skipped when the checkpoint does not cover; kill switch; the
common entry point dispatching; the admission estimate; compat with the
dense prefix skipped and a missing routed layer rejected.

Measured, mlx-community/GLM-5.2-4bit on an M5 Max 128 GB, 36-token prompt,
24 greedy tokens: 20% residency (51 experts per layer) 86.6 GiB footprint,
3.3 s load, 20.4 s cold TTFT, 1.8 tok/s at a 0.63 decode hit rate; 12.5%
58.4 GiB, 18.8 s, 1.5 tok/s at 0.52. The same 20% run through the common
store's memmap fetches: 646 s TTFT and 0.09 tok/s (16 KiB page faults at
0.4 GB/s), which is why the adapter reads positionally.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…int layouts

The adapter validated and read only stacked expert tensors, while
eligibility and admission also accepted the per-expert layout the loader
stacks at load, so such a checkpoint passed compatibility, received an
admission discount, and then wrapped zero layers. The adapter's private
reader also opened its own shard descriptors and nothing closed them.

Misses now read through CheckpointExpertStore's plans on the shared reader
pool, so the store owns the descriptors, and the view resolves either
layout as the common adapter does (the per-expert one verified expert by
expert). The GLM adapter tests run every case over both layouts and check
that ten wrap/release cycles return the descriptor count to baseline; a
loader-level regression builds a tiny glm_moe_dsa model through the real
loader in both layouts and asserts eligibility, the wrapped layer count,
unchanged output and the admission discount agree.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@beatakouchnir
beatakouchnir force-pushed the feat/moe-offload-glm-moe-dsa branch from 0fabbd5 to a6cf245 Compare September 21, 2026 08:32
@beatakouchnir

Copy link
Copy Markdown
Contributor Author

Both confirmed and fixed in a6cf245 (rebased on current main).

Per-expert layout: resolve_view now resolves either layout the way the common adapter does, with the per-expert one verified expert by expert, so eligibility, the adapter's reads and admission agree. A loader-level regression
(test_glm_loader_paths_match_offload_admission) builds a tiny glm_moe_dsa model through the real loader in both layouts and asserts compatibility, the wrapped layer count, unchanged output and the admission discount.

Descriptors: _SlabReader is gone. Misses read through CheckpointExpertStore's plans on the shared reader pool, so the store owns the descriptors; the adapter only keeps its 512 MiB in-flight bound on top of the pool's window. The GLM suite now runs every case over both layouts, and a new test checks that ten wrap/fetch/release cycles return the open-descriptor count to baseline.

@jundot jundot left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I verified both checkpoint layouts through the GLM loader: the expected layers are wrapped, outputs match, and admission savings agree. Repeated wrap/fetch/release cycles return file descriptors to baseline, and the native weighted-sum and fallback paths pass. I also reproduced and verified a small fix for the serial-reader setting, which I'll apply immediately after merging. LGTM.

@jundot
jundot merged commit 7f7dc33 into jundot:main Sep 21, 2026
3 checks passed
jundot added a commit that referenced this pull request Sep 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants