Skip to content

Support for glm_moe_dsa architecture (GLM-5.2 DeepSeek Sparse Attention) #111

Closed

Description

@basedagent

Request

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.

Activity

  1. solderzzc commented on Aug 5, 2026

    @solderzzc
    Member

    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-lm submodule, not this repo:

    mlx-swift-lm/Libraries/MLXLLM/LLMModelFactory.swift:56-58
        "glm4":           create(GLM4Configuration.self, GLM4Model.init),
        "glm4_moe":       create(GLM4MoEConfiguration.self, GLM4MoEModel.init),
        "glm4_moe_lite":  create(GLM4MoELiteConfiguration.self, GLM4MoELiteModel.init),
    

    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.
    if key.contains(".attn.compressor.") || key.contains(".attn.indexer.") { return false }

    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:

    1. Port the DSA attention from mlx-lm into mlx-swift-lm (indexer + top-k selection, the actual work)
    2. GlmMoeDsaConfiguration / GlmMoeDsaModel, reusing the GLM4MoE MoE blocks where they carry over
    3. Registry entry + weight-key sanitisation for the DSA sub-modules
    4. 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.

  2. solderzzc commented on Aug 12, 2026

    @solderzzc
    Member

    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_v32 import Model as DSV32Model
    
    class Model(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:

    if k.shape[2] <= self.index_topk:
        return None

    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:

    1. 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.
    2. 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.

  3. solderzzc commented on Aug 12, 2026

    @solderzzc
    Member

    Stage 1 has landed. As of #138 (submodule at SharpAI/mlx-swift-lm@bfc2462, via SharpAI/mlx-swift-lm#48), glm_moe_dsa and deepseek_v3_2 are registered architectures: GLM-5.2 constructs, loads, and runs.

    What you can do now — the thing this issue actually asks for:

    SwiftLM --model avlp12/GLM-5.2-Alis-MLX-Dynamic-3.5bpw --stream-experts
    

    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.

  4. solderzzc commented on Aug 29, 2026

    @solderzzc
    Member

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions