You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Support for glm_moe_dsa architecture (GLM-5.2 DeepSeek Sparse Attention) #111
GLM-5.2 (z-ai/glm-5.2) uses the glm_moe_dsa architecture (GlmMoeDsaForCausalLM), which combines Mixture-of-Experts with DeepSeek Sparse Attention (DSA). This is distinct from the existing glm4_moe and glm4_moe_lite architectures currently supported in SwiftLM.
Why this matters
GLM-5.2 is a frontier MoE model (~308GB in 3.5bpw MLX format, ~384GB in mxfp4). On a 128GB M5 Max, the model exceeds RAM — making SwiftLM's --stream-experts SSD expert streaming the ideal solution. Only active experts (~40B params per token) need to be in memory, with the rest streamed from NVMe.
Current state
mlx-lm 0.31.3 now supports glm_moe_dsa (merged in commit d711c5f)
transformers v5.11.0 also supports GlmMoeDsa
The MLX 3.5bpw quantized model is available at avlp12/GLM-5.2-Alis-MLX-Dynamic-3.5bpw
SwiftLM's LLMModelFactory.swift supports glm4_moe and glm4_moe_lite but not glm_moe_dsa
What's needed
Add glm_moe_dsa as a supported architecture in LLMModelFactory.swift, mapping to the appropriate Swift MLX model class. The DSA attention pattern differs from standard MHA/GQA — it uses sparse attention with a sliding window + global tokens pattern.
Context
We're building an autonomous agent fleet (Based Agent Systems) that runs GLM-5.2 as the canonical reasoner via OpenRouter. Local MLX inference would eliminate API costs and reduce latency. SwiftLM's SSD expert streaming is the only viable path for running a 308GB MoE model on 128GB RAM.
So the work is a submodule PR plus a bump here, not a change to SwiftLM itself.
There is no Swift class to map to yet. The request reads as "map glm_moe_dsa to the appropriate Swift MLX model class", but no sparse-attention implementation exists in this stack. The closest precedent is DeepseekV4.swift, which handles a DSA-style architecture by discarding the relevant weights:
// Drop compressor/indexer sub-module weights — these implement long-range
// compressed attention and are not yet implemented in this Swift port.
// TODO: implement DeepseekV4Compressor and DeepseekV4Indexer modules.
ifkey.contains(".attn.compressor.")||key.contains(".attn.indexer."){returnfalse}
So glm_moe_dsa needs the indexer built, not wired up. Doing it would also close that TODO, which makes it more attractive than it first looks — one implementation, two architectures.
One correction to the description. The issue says DSA uses "sparse attention with a sliding window + global tokens pattern". As introduced by DeepSeek, DSA is a lightning indexer that scores keys and selects top-k per query — a different mechanism with different kernel requirements. Worth confirming against the mlx-lm implementation (d711c5f) before anyone scopes the port, since it changes what needs writing.
Dependency worth knowing about. SSD expert streaming would not have engaged on this model anyway: MoE detection read only num_local_experts, and GLM MoE configs use n_routed_experts, so --stream-experts was silently dropped and the model was loaded in full. That is #112, fixed in #114. Anyone attempting this port should build on that.
Rough shape of a PR, for whoever picks it up:
Port the DSA attention from mlx-lm into mlx-swift-lm (indexer + top-k selection, the actual work)
GlmMoeDsaConfiguration / GlmMoeDsaModel, reusing the GLM4MoE MoE blocks where they carry over
Registry entry + weight-key sanitisation for the DSA sub-modules
Bump the submodule here
I have not scoped the kernel side, and 308GB at ~40B active per token on 128GB is uncharted for this streaming path — expect that to need its own tuning pass even once the architecture loads. Not something I would promise a timeline on, but the pieces above are what it takes.
Scoped this against the actual mlx-lm implementation, which I'd flagged as a prerequisite in the triage above. Two findings change the shape of the work, one of them substantially.
glm_moe_dsa is not its own architecture. In mlx-lm it is 54 lines, and the model class is a one-liner:
from .deepseek_v32importModelasDSV32ModelclassModel(DSV32Model):
def__init__(self, config: ModelArgs):
super().__init__(config)
Everything else in that file is a config dataclass. So the task is "port DeepSeek V3.2", and GLM-5.2 falls out as a config + registry entry. That also means it closes the DeepseekV4Compressor/DeepseekV4Indexer TODO — one implementation, three architectures.
Most of it already exists in Swift. GLM-5.2's config declares kv_lora_rank: 512, q_lora_rank: 2048, qk_rope_head_dim: 64, topk_method: noaux_tc, n_group/topk_group — all of which DeepseekV3.swift already implements (MLA + grouped expert selection). The genuinely missing piece is the Indexer, which is ~60 lines of Python.
Every primitive it needs is already in mlx-swift: argPartition (Ops.swift:257), plus takeAlong/putAlong, both already used in DeepseekV3.swift:286-291. No new kernels.
The useful detail — DSA is inert below index_topk:
ifk.shape[2] <=self.index_topk:
returnNone
GLM-5.2 ships index_topk: 2048. Below 2048 positions of context the indexer returns None and attention runs fully dense, so a dense-only port is numerically exact up to 2048 tokens and only diverges beyond it (dense rather than top-2048 sparse — degraded quality on long context, not a crash). That makes a staged landing possible:
Stage 1 — DeepseekV32Configuration/Model reusing the V3 MLA and gate, indexer weights sanitised away, registry entries for deepseek_v3_2 and glm_moe_dsa. The model loads and is exact under 2048 tokens. This is what unblocks validating --stream-experts at 308 GB, which is the actual ask here.
Stage 2 — the indexer, which buys correct long context.
What I have not solved, and would not want understated:
Paired cache. V3.2 threads two caches per attention layer (cache[0] main, cache[1] indexer) and couples them via mx.depends to bound graph growth. The hybrid models here (Jamba, FalconH1, NemotronH) index cache[1] for layer state, so there is precedent, but not for this shape.
Absorbed MLA. V3.2 attention uses embed_q/unembed_out on the L == 1 path; no Swift model in this repo implements that. It needs writing, not porting by analogy.
No way to test against real weights. The smallest glm_moe_dsa checkpoint is the 308 GB one. Verification would have to be tiny random-init configs in the style of Gemma4Tests.swift, which validates shape and flow but not numerics against a reference.
Stage 1 is a tractable, self-contained PR. I have not started it — flagging the scope first since it is a good deal smaller than my earlier comment implied, and the staged split is worth agreeing on before anyone writes code.
MoE detection reads n_routed_experts since #114, so --stream-experts engages on this config instead of being silently dropped (the dependency flagged in the triage above).
The exactness boundary, stated precisely. Stage 1 runs dense attention — the DSA indexer is not yet implemented. That is exact, not approximate, while the KV cache is at or under index_topk (2048 for GLM-5.2), because the reference indexer returns no selection in that regime. Past 2048 positions the output diverges: dense where the reference is top-2048 sparse. Long-context quality and speed are what stage 2 buys; it is scoped in #139, including a verification strategy that works without the 308 GB checkpoint.
What has not been verified, plainly: no real weights have been run anywhere in this chain — the smallest glm_moe_dsa checkpoint is 308 GB, beyond what CI or my machine can host. Coverage is tiny random-init models: construction, forward shape/finiteness, config decoding against GLM-5.2's real layout (including rope_theta nested in rope_parameters), weight sanitisation, and an end-to-end check that the SwiftLM binary reaches weight-loading for a glm_moe_dsa config. Tokenizer/chat-template behaviour and the 3.5bpw dynamic-quant layout are untested. And 308 GB at ~40 B active per token on 128 GB is uncharted territory for the streaming path, as noted in the triage — expect that to need its own tuning pass.
@basedagent your setup is the first place this can meet real weights. A report either way — including the failure mode if it falls over — would be genuinely useful, and will feed directly into #139.
One incidental fix worth knowing about: DeepseekV3.sanitize used to drop model.layers.61 by string literal (V3's MTP layer). On GLM-5.2's 78 layers that would have silently deleted a real layer while keeping the actual MTP block; it now filters on numHiddenLayers. If you ever saw inexplicable output from a deep DeepSeek-family variant, that was a candidate cause.
Leaving this open until it has been exercised against real weights; stage 2 is tracked in #139.
Closing as fulfilled — glm_moe_dsa is now fully supported: dense attention landed in #139, and the DSA sparse lightning indexer (stage 2) landed in SharpAI/mlx-swift-lm#61. glm_moe_dsa is registered in LLMModelFactory and covered by tests (including a real-cache regression test for the offset bug found during review). One follow-up not yet done: real-weights end-to-end verification against an actual GLM-5.2 checkpoint (smallest known quant is ~308GB).
Activity
solderzzc commentedon Aug 5, 2026
Triage notes — this is a reasonable request, but it is a fair bit larger than a registry entry, so recording what it actually involves.
Where the registry lives. The architecture map is in the
mlx-swift-lmsubmodule, not this repo:So the work is a submodule PR plus a bump here, not a change to
SwiftLMitself.There is no Swift class to map to yet. The request reads as "map
glm_moe_dsato the appropriate Swift MLX model class", but no sparse-attention implementation exists in this stack. The closest precedent isDeepseekV4.swift, which handles a DSA-style architecture by discarding the relevant weights:So
glm_moe_dsaneeds the indexer built, not wired up. Doing it would also close that TODO, which makes it more attractive than it first looks — one implementation, two architectures.One correction to the description. The issue says DSA uses "sparse attention with a sliding window + global tokens pattern". As introduced by DeepSeek, DSA is a lightning indexer that scores keys and selects top-k per query — a different mechanism with different kernel requirements. Worth confirming against the
mlx-lmimplementation (d711c5f) before anyone scopes the port, since it changes what needs writing.Dependency worth knowing about. SSD expert streaming would not have engaged on this model anyway: MoE detection read only
num_local_experts, and GLM MoE configs usen_routed_experts, so--stream-expertswas silently dropped and the model was loaded in full. That is #112, fixed in #114. Anyone attempting this port should build on that.Rough shape of a PR, for whoever picks it up:
mlx-lmintomlx-swift-lm(indexer + top-k selection, the actual work)GlmMoeDsaConfiguration/GlmMoeDsaModel, reusing theGLM4MoEMoE blocks where they carry overI have not scoped the kernel side, and 308GB at ~40B active per token on 128GB is uncharted for this streaming path — expect that to need its own tuning pass even once the architecture loads. Not something I would promise a timeline on, but the pieces above are what it takes.
solderzzc commentedon Aug 12, 2026
Scoped this against the actual
mlx-lmimplementation, which I'd flagged as a prerequisite in the triage above. Two findings change the shape of the work, one of them substantially.glm_moe_dsais not its own architecture. Inmlx-lmit is 54 lines, and the model class is a one-liner:Everything else in that file is a config dataclass. So the task is "port DeepSeek V3.2", and GLM-5.2 falls out as a config + registry entry. That also means it closes the
DeepseekV4Compressor/DeepseekV4IndexerTODO — one implementation, three architectures.Most of it already exists in Swift. GLM-5.2's config declares
kv_lora_rank: 512,q_lora_rank: 2048,qk_rope_head_dim: 64,topk_method: noaux_tc,n_group/topk_group— all of whichDeepseekV3.swiftalready implements (MLA + grouped expert selection). The genuinely missing piece is theIndexer, which is ~60 lines of Python.Every primitive it needs is already in mlx-swift:
argPartition(Ops.swift:257), plustakeAlong/putAlong, both already used inDeepseekV3.swift:286-291. No new kernels.The useful detail — DSA is inert below
index_topk:GLM-5.2 ships
index_topk: 2048. Below 2048 positions of context the indexer returnsNoneand attention runs fully dense, so a dense-only port is numerically exact up to 2048 tokens and only diverges beyond it (dense rather than top-2048 sparse — degraded quality on long context, not a crash). That makes a staged landing possible:DeepseekV32Configuration/Modelreusing the V3 MLA and gate, indexer weights sanitised away, registry entries fordeepseek_v3_2andglm_moe_dsa. The model loads and is exact under 2048 tokens. This is what unblocks validating--stream-expertsat 308 GB, which is the actual ask here.What I have not solved, and would not want understated:
cache[0]main,cache[1]indexer) and couples them viamx.dependsto bound graph growth. The hybrid models here (Jamba,FalconH1,NemotronH) indexcache[1]for layer state, so there is precedent, but not for this shape.embed_q/unembed_outon theL == 1path; no Swift model in this repo implements that. It needs writing, not porting by analogy.glm_moe_dsacheckpoint is the 308 GB one. Verification would have to be tiny random-init configs in the style ofGemma4Tests.swift, which validates shape and flow but not numerics against a reference.Stage 1 is a tractable, self-contained PR. I have not started it — flagging the scope first since it is a good deal smaller than my earlier comment implied, and the staged split is worth agreeing on before anyone writes code.
feat: load glm_moe_dsa / deepseek_v3_2 with dense attention (stage 1) (…
feat: bump mlx-swift-lm for glm_moe_dsa (GLM-5.2) support
feat: bump mlx-swift-lm for glm_moe_dsa (GLM-5.2) support (#138)
solderzzc commentedon Aug 12, 2026
Stage 1 has landed. As of #138 (submodule at SharpAI/mlx-swift-lm@bfc2462, via SharpAI/mlx-swift-lm#48),
glm_moe_dsaanddeepseek_v3_2are registered architectures: GLM-5.2 constructs, loads, and runs.What you can do now — the thing this issue actually asks for:
MoE detection reads
n_routed_expertssince #114, so--stream-expertsengages on this config instead of being silently dropped (the dependency flagged in the triage above).The exactness boundary, stated precisely. Stage 1 runs dense attention — the DSA indexer is not yet implemented. That is exact, not approximate, while the KV cache is at or under
index_topk(2048 for GLM-5.2), because the reference indexer returns no selection in that regime. Past 2048 positions the output diverges: dense where the reference is top-2048 sparse. Long-context quality and speed are what stage 2 buys; it is scoped in #139, including a verification strategy that works without the 308 GB checkpoint.What has not been verified, plainly: no real weights have been run anywhere in this chain — the smallest
glm_moe_dsacheckpoint is 308 GB, beyond what CI or my machine can host. Coverage is tiny random-init models: construction, forward shape/finiteness, config decoding against GLM-5.2's real layout (includingrope_thetanested inrope_parameters), weight sanitisation, and an end-to-end check that the SwiftLM binary reaches weight-loading for aglm_moe_dsaconfig. Tokenizer/chat-template behaviour and the 3.5bpw dynamic-quant layout are untested. And 308 GB at ~40 B active per token on 128 GB is uncharted territory for the streaming path, as noted in the triage — expect that to need its own tuning pass.@basedagent your setup is the first place this can meet real weights. A report either way — including the failure mode if it falls over — would be genuinely useful, and will feed directly into #139.
One incidental fix worth knowing about:
DeepseekV3.sanitizeused to dropmodel.layers.61by string literal (V3's MTP layer). On GLM-5.2's 78 layers that would have silently deleted a real layer while keeping the actual MTP block; it now filters onnumHiddenLayers. If you ever saw inexplicable output from a deep DeepSeek-family variant, that was a candidate cause.Leaving this open until it has been exercised against real weights; stage 2 is tracked in #139.
fix: make the dependency automation work without a PAT (#140)
fix: pin the vision test's LFM2.5 model to an immutable revision (#141)
fix: name a malformed chat template instead of failing every request (#…
test: cover load-path defect shapes with synthetic checkpoints (#143)
chore: bump mlx-swift-lm to pick up DSA stage 2 (lightning indexer) (#…
solderzzc commentedon Aug 29, 2026
Closing as fulfilled — glm_moe_dsa is now fully supported: dense attention landed in #139, and the DSA sparse lightning indexer (stage 2) landed in SharpAI/mlx-swift-lm#61. glm_moe_dsa is registered in LLMModelFactory and covered by tests (including a real-cache regression test for the offset bug found during review). One follow-up not yet done: real-weights end-to-end verification against an actual GLM-5.2 checkpoint (smallest known quant is ~308GB).