Skip to content

Commit bfc2462

Browse files
solderzzcAegis AI Assistantclaude
authored
feat: load glm_moe_dsa / deepseek_v3_2 with dense attention (stage 1) (#48)
* test: cover the all-KV-shared assistant and its chunked prefill The MTP unit tests built their assistant from a config with num_kv_shared_layers: 0, which no shipped assistant checkpoint uses — real ones are entirely KV-shared and carry no K/V projections at all. So the existing tests exercised a model that cannot occur in practice, and dual-model MTP aborting on any chunk-prefilled prompt (#46) passed straight through them. Adds a matching config (every layer shared) and two tests: - a plain forward must reach the trunk, asserted by comparing logits against the trunk directly rather than merely surviving the call - MTPTokenIterator with prefillStepSize squeezed to 2, which forces the chunked prefill path with a 5-token prompt The second is the regression proper. prepare() only forwards a chunk when the prompt exceeds prefillStepSize; below it the model is never called, which is why a 512-token threshold hid the bug behind every short test prompt. Lowering the threshold reproduces it without a multi-gigabyte model pair — the smallest real one is 7.1 GB, more than GitHub's 10 GB per-repo cache budget can host alongside the existing modalities. Verified red-green: with the delegation in Gemma4AssistantModel.callAsFunction removed, both abort with the production error Layer 0 is a KV-shared layer but received no sharedKV Note that a regression here surfaces as a crashed test run rather than a failed assertion, since the guard is a fatalError. Full suite: 98 tests, 16 suites, all passing. Co-Authored-By: Claude Opus 5 <[email protected]> * feat: load glm_moe_dsa / deepseek_v3_2 with dense attention (stage 1) GLM-5.2 uses `glm_moe_dsa`, which in mlx-lm is 54 lines whose model class is a bare `class Model(DSV32Model)` — it is DeepSeek V3.2, not its own architecture. V3.2 in turn is V3 plus DeepSeek Sparse Attention: a lightning indexer scores cached keys and attention is restricted to the top `index_topk`. The V3 half of that already exists in this repo, so both model types map to one new Swift model built on the V3 stack. The indexer is not implemented here. That is not an approximation below `index_topk`, because the reference returns no selection at all until the cache is longer than it: if k.shape[2] <= self.index_topk: return None GLM-5.2 ships index_topk 2048, so output is exact for the first 2048 positions and diverges past them — dense instead of top-2048 sparse, a long-context quality question rather than a failure. Implementing the indexer is stage 2 and also closes the DeepseekV4Compressor/Indexer TODO. Config decoding differs from V3 in one way worth noting: GLM-5.2 carries no top-level rope_theta, nesting it in `rope_parameters` (mlx-lm unpacks this in __post_init__). Both layouts are accepted. `rope_type: "default"` is deliberately not forwarded as rope_scaling — a non-nil dict there sends the V3 stack looking for yarn fields the config does not have. Also generalises a trap in DeepseekV3.sanitize, which dropped `model.layers.61` as a string literal. That number is just numHiddenLayers — V3 has 61 layers and its MTP block sits at index 61 — but GLM-5.2 has 78, so the literal deleted a real layer while keeping the actual MTP block. It now filters on `layerIdx >= numHiddenLayers`, identical for V3 and correct for any depth. Covered both ways: a 78-layer model keeps layer 61 and drops 78, a 61-layer model still drops 61. Verified red-green — under the old literal the GLM case fails on both counts. Tests are tiny random-init configs in the style of the Gemma 4 suite; they establish shape, flow and weight handling, not numerics against a reference. Nothing here is validated against real weights: the smallest glm_moe_dsa checkpoint is 308 GB. Full suite: 104 tests, 17 suites, passing. Refs SharpAI/SwiftLM#111 Co-Authored-By: Claude Opus 5 <[email protected]> --------- Co-authored-by: Aegis AI Assistant <[email protected]> Co-authored-by: Claude Opus 5 <[email protected]>
1 parent b1b348e commit bfc2462

4 files changed

Lines changed: 406 additions & 1 deletion

File tree

‎Libraries/MLXLLM/LLMModelFactory.swift‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,11 @@ public enum LLMTypeRegistry {
5050
"openelm": create(OpenElmConfiguration.self, OpenELMModel.init),
5151
"internlm2": create(InternLM2Configuration.self, InternLM2Model.init),
5252
"deepseek_v3": create(DeepseekV3Configuration.self, DeepseekV3Model.init),
53+
// DeepSeek Sparse Attention. GLM-5.2 (`glm_moe_dsa`) is the same architecture —
54+
// in mlx-lm its model class is a bare subclass of the V3.2 one — so it maps to
55+
// the same Swift model rather than getting a parallel implementation.
56+
"deepseek_v3_2": create(DeepseekV32Configuration.self, DeepseekV32Model.init),
57+
"glm_moe_dsa": create(DeepseekV32Configuration.self, DeepseekV32Model.init),
5358
"deepseek_v4": create(DeepseekV4Configuration.self, DeepseekV4Model.init),
5459
"granite": create(GraniteConfiguration.self, GraniteModel.init),
5560
"granitemoehybrid": create(

‎Libraries/MLXLLM/Models/DeepseekV3.swift‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -437,6 +437,18 @@ public class DeepseekV3Model: Module, LLMModel, KVCacheDimensionProvider, LoRAMo
437437
return lmHead(out)
438438
}
439439

440+
/// Multi-token-prediction layers sit past the main stack and have no module to load
441+
/// into. DeepSeek-V3 has 61 of them and its MTP block is `model.layers.61`, which is
442+
/// why this used to be a literal string — but that number is just `numHiddenLayers`,
443+
/// and hardcoding it silently deletes a real layer in any architecture reusing this
444+
/// stack with a different depth (GLM-5.2 has 78, so `layers.61` is load-bearing).
445+
func isMultiTokenPredictionLayer(_ key: String) -> Bool {
446+
guard key.starts(with: "model.layers.") else { return false }
447+
let parts = key.split(separator: ".")
448+
guard parts.count >= 3, let layerIdx = Int(parts[2]) else { return false }
449+
return layerIdx >= args.numHiddenLayers
450+
}
451+
440452
public func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] {
441453
var newWeights = weights
442454

@@ -480,7 +492,7 @@ public class DeepseekV3Model: Module, LLMModel, KVCacheDimensionProvider, LoRAMo
480492
}
481493

482494
return newWeights.filter { key, _ in
483-
!key.starts(with: "model.layers.61") && !key.contains("rotary_emb.inv_freq")
495+
!isMultiTokenPredictionLayer(key) && !key.contains("rotary_emb.inv_freq")
484496
}
485497
}
486498

Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,225 @@
1+
// Copyright © 2025 Apple Inc.
2+
3+
// port of https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/models/deepseek_v32.py
4+
// and https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/models/glm_moe_dsa.py
5+
//
6+
// DeepSeek V3.2 is V3 plus DeepSeek Sparse Attention (DSA): a "lightning indexer"
7+
// scores every cached key against the query and attention is restricted to the
8+
// top `index_topk` of them. GLM-5.2 (`glm_moe_dsa`) is the same architecture — in
9+
// mlx-lm its model class is a bare `class Model(DSV32Model)` over a differently
10+
// shaped config — so both land here.
11+
//
12+
// STAGE 1: the indexer is not implemented; its weights are dropped and attention
13+
// runs dense. This is not an approximation below `index_topk` — the reference
14+
// indexer returns no selection at all until the cache is longer than that:
15+
//
16+
// if k.shape[2] <= self.index_topk:
17+
// return None
18+
//
19+
// GLM-5.2 ships `index_topk: 2048`, so output is exact for the first 2048
20+
// positions of context and diverges beyond them (dense rather than top-2048
21+
// sparse — a quality question on long context, not a failure). Implementing the
22+
// indexer is stage 2 and also closes the DeepseekV4Compressor/Indexer TODO.
23+
24+
import Foundation
25+
import MLX
26+
import MLXLMCommon
27+
import MLXNN
28+
29+
public struct DeepseekV32Configuration: Codable, Sendable {
30+
var vocabSize: Int
31+
var hiddenSize: Int
32+
var intermediateSize: Int
33+
var moeIntermediateSize: Int
34+
var numHiddenLayers: Int
35+
var numAttentionHeads: Int
36+
var numKeyValueHeads: Int
37+
var nSharedExperts: Int?
38+
var nRoutedExperts: Int?
39+
var routedScalingFactor: Float
40+
var kvLoraRank: Int
41+
var qLoraRank: Int
42+
var qkRopeHeadDim: Int
43+
var vHeadDim: Int
44+
var qkNopeHeadDim: Int
45+
var normTopkProb: Bool
46+
var nGroup: Int?
47+
var topkGroup: Int?
48+
var numExpertsPerTok: Int?
49+
var moeLayerFreq: Int
50+
var firstKDenseReplace: Int
51+
var maxPositionEmbeddings: Int
52+
var rmsNormEps: Float
53+
var ropeTheta: Float
54+
var ropeScaling: [String: StringOrNumber]?
55+
/// Kept as a stored property so the synthesised `Encodable` conformance has
56+
/// somewhere to put the key; `ropeTheta`/`ropeScaling` above are what the model
57+
/// actually reads.
58+
var ropeParameters: [String: StringOrNumber]?
59+
var attentionBias: Bool
60+
61+
// DSA-specific. Retained for stage 2 and to document what is being dropped.
62+
var indexTopk: Int
63+
var indexNHeads: Int
64+
var indexHeadDim: Int
65+
var numNextnPredictLayers: Int
66+
67+
enum CodingKeys: String, CodingKey {
68+
case vocabSize = "vocab_size"
69+
case hiddenSize = "hidden_size"
70+
case intermediateSize = "intermediate_size"
71+
case moeIntermediateSize = "moe_intermediate_size"
72+
case numHiddenLayers = "num_hidden_layers"
73+
case numAttentionHeads = "num_attention_heads"
74+
case numKeyValueHeads = "num_key_value_heads"
75+
case nSharedExperts = "n_shared_experts"
76+
case nRoutedExperts = "n_routed_experts"
77+
case routedScalingFactor = "routed_scaling_factor"
78+
case kvLoraRank = "kv_lora_rank"
79+
case qLoraRank = "q_lora_rank"
80+
case qkRopeHeadDim = "qk_rope_head_dim"
81+
case vHeadDim = "v_head_dim"
82+
case qkNopeHeadDim = "qk_nope_head_dim"
83+
case normTopkProb = "norm_topk_prob"
84+
case nGroup = "n_group"
85+
case topkGroup = "topk_group"
86+
case numExpertsPerTok = "num_experts_per_tok"
87+
case moeLayerFreq = "moe_layer_freq"
88+
case firstKDenseReplace = "first_k_dense_replace"
89+
case maxPositionEmbeddings = "max_position_embeddings"
90+
case rmsNormEps = "rms_norm_eps"
91+
case ropeTheta = "rope_theta"
92+
case ropeScaling = "rope_scaling"
93+
case ropeParameters = "rope_parameters"
94+
case attentionBias = "attention_bias"
95+
case indexTopk = "index_topk"
96+
case indexNHeads = "index_n_heads"
97+
case indexHeadDim = "index_head_dim"
98+
case numNextnPredictLayers = "num_nextn_predict_layers"
99+
}
100+
101+
public init(from decoder: Decoder) throws {
102+
let c = try decoder.container(keyedBy: CodingKeys.self)
103+
104+
vocabSize = try c.decode(Int.self, forKey: .vocabSize)
105+
hiddenSize = try c.decode(Int.self, forKey: .hiddenSize)
106+
intermediateSize = try c.decode(Int.self, forKey: .intermediateSize)
107+
moeIntermediateSize = try c.decode(Int.self, forKey: .moeIntermediateSize)
108+
numHiddenLayers = try c.decode(Int.self, forKey: .numHiddenLayers)
109+
numAttentionHeads = try c.decode(Int.self, forKey: .numAttentionHeads)
110+
numKeyValueHeads = try c.decode(Int.self, forKey: .numKeyValueHeads)
111+
nSharedExperts = try c.decodeIfPresent(Int.self, forKey: .nSharedExperts)
112+
nRoutedExperts = try c.decodeIfPresent(Int.self, forKey: .nRoutedExperts)
113+
routedScalingFactor = try c.decode(Float.self, forKey: .routedScalingFactor)
114+
kvLoraRank = try c.decode(Int.self, forKey: .kvLoraRank)
115+
qLoraRank = try c.decode(Int.self, forKey: .qLoraRank)
116+
qkRopeHeadDim = try c.decode(Int.self, forKey: .qkRopeHeadDim)
117+
vHeadDim = try c.decode(Int.self, forKey: .vHeadDim)
118+
qkNopeHeadDim = try c.decode(Int.self, forKey: .qkNopeHeadDim)
119+
normTopkProb = try c.decodeIfPresent(Bool.self, forKey: .normTopkProb) ?? true
120+
nGroup = try c.decodeIfPresent(Int.self, forKey: .nGroup)
121+
topkGroup = try c.decodeIfPresent(Int.self, forKey: .topkGroup)
122+
numExpertsPerTok = try c.decodeIfPresent(Int.self, forKey: .numExpertsPerTok)
123+
moeLayerFreq = try c.decodeIfPresent(Int.self, forKey: .moeLayerFreq) ?? 1
124+
firstKDenseReplace = try c.decodeIfPresent(Int.self, forKey: .firstKDenseReplace) ?? 0
125+
maxPositionEmbeddings =
126+
try c.decodeIfPresent(Int.self, forKey: .maxPositionEmbeddings) ?? 2048
127+
rmsNormEps = try c.decode(Float.self, forKey: .rmsNormEps)
128+
attentionBias = try c.decodeIfPresent(Bool.self, forKey: .attentionBias) ?? false
129+
130+
indexTopk = try c.decodeIfPresent(Int.self, forKey: .indexTopk) ?? 2048
131+
indexNHeads = try c.decodeIfPresent(Int.self, forKey: .indexNHeads) ?? 0
132+
indexHeadDim = try c.decodeIfPresent(Int.self, forKey: .indexHeadDim) ?? 0
133+
numNextnPredictLayers =
134+
try c.decodeIfPresent(Int.self, forKey: .numNextnPredictLayers) ?? 0
135+
136+
// GLM-5.2 carries no top-level `rope_theta`/`rope_scaling`; both live inside a
137+
// `rope_parameters` dict, which mlx-lm unpacks in ModelArgs.__post_init__.
138+
// DeepSeek's own V3.2 configs keep the flat layout, so accept either.
139+
let ropeParameters = try c.decodeIfPresent(
140+
[String: StringOrNumber].self, forKey: .ropeParameters)
141+
self.ropeParameters = ropeParameters
142+
143+
if let flat = try c.decodeIfPresent(Float.self, forKey: .ropeTheta) {
144+
ropeTheta = flat
145+
} else if case .float(let theta) = ropeParameters?["rope_theta"] {
146+
ropeTheta = theta
147+
} else if case .int(let theta) = ropeParameters?["rope_theta"] {
148+
ropeTheta = Float(theta)
149+
} else {
150+
throw DecodingError.keyNotFound(
151+
CodingKeys.ropeTheta,
152+
.init(
153+
codingPath: decoder.codingPath,
154+
debugDescription:
155+
"no rope_theta at the top level or inside rope_parameters"))
156+
}
157+
158+
if let flat = try c.decodeIfPresent([String: StringOrNumber].self, forKey: .ropeScaling) {
159+
ropeScaling = flat
160+
} else if let ropeParameters,
161+
case .string(let type)? = ropeParameters["rope_type"], type != "default"
162+
{
163+
// Only forward rope_parameters as scaling when it actually describes a
164+
// scheme; "default" means plain RoPE and a non-nil dict here would make
165+
// the V3 stack look for yarn fields that are not there.
166+
ropeScaling = ropeParameters
167+
} else {
168+
ropeScaling = nil
169+
}
170+
}
171+
172+
/// The V3.2 base stack is V3: same MLA projections, same grouped `noaux_tc` gate,
173+
/// same MoE block. Only the indexer is new, and stage 1 does not build it — so the
174+
/// model is constructed straight from the equivalent V3 configuration.
175+
var v3Configuration: DeepseekV3Configuration {
176+
DeepseekV3Configuration(
177+
vocabSize: vocabSize,
178+
hiddenSize: hiddenSize,
179+
intermediateSize: intermediateSize,
180+
moeIntermediateSize: moeIntermediateSize,
181+
numHiddenLayers: numHiddenLayers,
182+
numAttentionHeads: numAttentionHeads,
183+
numKeyValueHeads: numKeyValueHeads,
184+
nSharedExperts: nSharedExperts,
185+
nRoutedExperts: nRoutedExperts,
186+
routedScalingFactor: routedScalingFactor,
187+
kvLoraRank: kvLoraRank,
188+
qLoraRank: qLoraRank,
189+
qkRopeHeadDim: qkRopeHeadDim,
190+
vHeadDim: vHeadDim,
191+
qkNopeHeadDim: qkNopeHeadDim,
192+
normTopkProb: normTopkProb,
193+
nGroup: nGroup,
194+
topkGroup: topkGroup,
195+
numExpertsPerTok: numExpertsPerTok,
196+
moeLayerFreq: moeLayerFreq,
197+
firstKDenseReplace: firstKDenseReplace,
198+
maxPositionEmbeddings: maxPositionEmbeddings,
199+
rmsNormEps: rmsNormEps,
200+
ropeTheta: ropeTheta,
201+
ropeScaling: ropeScaling,
202+
attentionBias: attentionBias
203+
)
204+
}
205+
}
206+
207+
public class DeepseekV32Model: DeepseekV3Model {
208+
let dsaArgs: DeepseekV32Configuration
209+
210+
init(_ args: DeepseekV32Configuration) {
211+
self.dsaArgs = args
212+
super.init(args.v3Configuration)
213+
}
214+
215+
override public func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] {
216+
// Drop the lightning-indexer sub-module. Stage 1 has no module to load these
217+
// into, and leaving them in surfaces as an unexpected-key failure rather than
218+
// anything diagnostic. Mirrors what DeepseekV4 does for the same weights.
219+
// TODO: implement the Indexer and stop dropping these (stage 2).
220+
let withoutIndexer = weights.filter { key, _ in
221+
!key.contains(".indexer.") && !key.contains(".attn.compressor.")
222+
}
223+
return super.sanitize(weights: withoutIndexer)
224+
}
225+
}

0 commit comments

Comments
 (0)