Skip to content

Commit 9bf181f

Browse files
justinchubyCopilot
andcommitted
Fix Kimi Linear rebase integration
Preserve valid KDA convolution state across padded prefills, route native K/V-B tensors through explicit reshape-aware requantization, and register the public Kimi config and coverage policy. Co-authored-by: Copilot App <[email protected]> Signed-off-by: Justin Chu <[email protected]>
1 parent 5d178ef commit 9bf181f

9 files changed

Lines changed: 188 additions & 80 deletions

File tree

‎src/mobius/_registry.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1076,6 +1076,7 @@ def _create_default_registry() -> ModelRegistry:
10761076
"dbrx": "databricks/dbrx-instruct",
10771077
"arctic": "Snowflake/snowflake-arctic-instruct",
10781078
"jetmoe": "jetmoe/jetmoe-8b",
1079+
"kimi_linear": "moonshotai/Kimi-Linear-48B-A3B-Instruct",
10791080
"longcat_flash": "yujiepan/longcat-flash-tiny-random",
10801081
"minimax": "MiniMaxAI/MiniMax-Text-01",
10811082
"ernie4_5_moe": "baidu/ERNIE-4.5-21B-A3B-PT",

‎src/mobius/components/_kimi_linear.py‎

Lines changed: 76 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ def __init__(self, config: ArchitectureConfig, linear_class: type | None = None)
6060
self._head_dim = config.linear_key_head_dim
6161
self._projection_size = self._heads * self._head_dim
6262
kernel = config.linear_conv_kernel_dim
63+
self._conv_history = kernel - 1
6364

6465
self.q_proj = linear_class(config.hidden_size, self._projection_size, bias=False)
6566
self.k_proj = linear_class(config.hidden_size, self._projection_size, bias=False)
@@ -86,9 +87,53 @@ def _project_conv(
8687
convolution: nn.Module,
8788
hidden_states: ir.Value,
8889
state: ir.Value,
90+
current_mask: ir.Value,
8991
):
9092
projected = op.Transpose(projection(op, hidden_states), perm=[0, 2, 1])
91-
value, present = convolution(op, projected, state)
93+
value, _ = convolution(op, projected, state)
94+
95+
# Retain the last valid projected tokens rather than padding positions.
96+
# The prior state contributes enough valid entries to keep TopK fixed-width.
97+
conv_input = op.Concat(state, projected, axis=2)
98+
batch = op.Shape(current_mask, start=0, end=1)
99+
past_valid = op.Expand(
100+
op.CastLike(1, current_mask),
101+
op.Concat(batch, op.Constant(value_ints=[self._conv_history]), axis=0),
102+
)
103+
valid = op.Concat(past_valid, current_mask, axis=1)
104+
positions = op.Range(
105+
op.Constant(value_int=0),
106+
op.Gather(op.Shape(valid), op.Constant(value_int=1), axis=0),
107+
op.Constant(value_int=1),
108+
)
109+
positions = op.Expand(op.Unsqueeze(positions, [0]), op.Shape(valid))
110+
masked_positions = op.Where(
111+
op.Cast(valid, to=ir.DataType.BOOL),
112+
positions,
113+
op.Expand(op.Constant(value_int=-1), op.Shape(valid)),
114+
)
115+
selected, _ = op.TopK(
116+
masked_positions,
117+
op.Constant(value_ints=[self._conv_history]),
118+
axis=1,
119+
largest=1,
120+
sorted=1,
121+
_outputs=2,
122+
)
123+
selected = op.Gather(
124+
selected,
125+
op.Constant(value_ints=list(range(self._conv_history - 1, -1, -1))),
126+
axis=1,
127+
)
128+
selected = op.Expand(
129+
op.Unsqueeze(selected, [1]),
130+
op.Concat(
131+
op.Shape(projected, start=0, end=2),
132+
op.Constant(value_ints=[self._conv_history]),
133+
axis=0,
134+
),
135+
)
136+
present = op.GatherElements(conv_input, selected, axis=2)
92137
return op.Transpose(value, perm=[0, 2, 1]), present
93138

94139
def forward(
@@ -108,17 +153,32 @@ def forward(
108153
op.Constant(value_ints=[9223372036854775807]),
109154
op.Constant(value_ints=[1]),
110155
)
111-
current_mask = op.Unsqueeze(op.CastLike(current_mask, hidden_states), [-1])
112-
masked_hidden_states = op.Mul(hidden_states, current_mask)
156+
current_mask_3d = op.Unsqueeze(op.CastLike(current_mask, hidden_states), [-1])
157+
masked_hidden_states = op.Mul(hidden_states, current_mask_3d)
113158

114159
q, present_q = self._project_conv(
115-
op, self.q_proj, self.q_conv1d, masked_hidden_states, q_conv_state
160+
op,
161+
self.q_proj,
162+
self.q_conv1d,
163+
masked_hidden_states,
164+
q_conv_state,
165+
current_mask,
116166
)
117167
k, present_k = self._project_conv(
118-
op, self.k_proj, self.k_conv1d, masked_hidden_states, k_conv_state
168+
op,
169+
self.k_proj,
170+
self.k_conv1d,
171+
masked_hidden_states,
172+
k_conv_state,
173+
current_mask,
119174
)
120175
v, present_v = self._project_conv(
121-
op, self.v_proj, self.v_conv1d, masked_hidden_states, v_conv_state
176+
op,
177+
self.v_proj,
178+
self.v_conv1d,
179+
masked_hidden_states,
180+
v_conv_state,
181+
current_mask,
122182
)
123183

124184
shape = [0, 0, self._heads, self._head_dim]
@@ -142,11 +202,9 @@ def forward(
142202
a = op.Neg(op.Exp(op.Cast(self.A_log, to=ir.DataType.FLOAT)))
143203
decay = op.Reshape(decay, [0, 0, self._heads, self._head_dim])
144204
decay = op.Reshape(op.Mul(decay, a), [0, 0, self._projection_size])
145-
decay = op.Mul(decay, current_mask)
146-
beta = op.Sigmoid(
147-
op.Cast(self.b_proj(op, masked_hidden_states), to=ir.DataType.FLOAT)
148-
)
149-
beta = op.Mul(beta, current_mask)
205+
decay = op.Mul(decay, current_mask_3d)
206+
beta = op.Sigmoid(op.Cast(self.b_proj(op, masked_hidden_states), to=ir.DataType.FLOAT))
207+
beta = op.Mul(beta, current_mask_3d)
150208

151209
output, present_recurrent = op.LinearAttention(
152210
q,
@@ -170,7 +228,7 @@ def forward(
170228
op.Reshape(output, [0, 0, self._projection_size]),
171229
hidden_states,
172230
)
173-
output = op.Mul(output, current_mask)
231+
output = op.Mul(output, current_mask_3d)
174232
output = self.o_proj(op, output)
175233
return output, (present_q, present_k, present_v, present_recurrent)
176234

@@ -187,21 +245,15 @@ def __init__(self, config: ArchitectureConfig, linear_class: type | None = None)
187245
self._qk_dim = self._nope + self._extra
188246
self._value_dim = config.v_head_dim
189247
self._kv_rank = config.kv_lora_rank
190-
self.q_proj = linear_class(
191-
config.hidden_size, self._heads * self._qk_dim, bias=False
192-
)
248+
self.q_proj = linear_class(config.hidden_size, self._heads * self._qk_dim, bias=False)
193249
self.kv_a_proj_with_mqa = linear_class(
194250
config.hidden_size, self._kv_rank + self._extra, bias=False
195251
)
196252
self.kv_a_layernorm = RMSNorm(self._kv_rank, eps=config.rms_norm_eps)
197253
# llama.cpp serializes these as separate MatMul roles. Keeping them
198254
# separate preserves quantized GGUF weights without a lossy fuse/split.
199-
self.k_b_proj = linear_class(
200-
self._kv_rank, self._heads * self._nope, bias=False
201-
)
202-
self.v_b_proj = linear_class(
203-
self._kv_rank, self._heads * self._value_dim, bias=False
204-
)
255+
self.k_b_proj = linear_class(self._kv_rank, self._heads * self._nope, bias=False)
256+
self.v_b_proj = linear_class(self._kv_rank, self._heads * self._value_dim, bias=False)
205257
self.o_proj = linear_class(
206258
self._heads * self._value_dim, config.hidden_size, bias=False
207259
)
@@ -213,22 +265,16 @@ def forward(
213265
attention_bias: ir.Value,
214266
past_key_value: tuple[ir.Value, ir.Value],
215267
):
216-
query = op.Reshape(
217-
self.q_proj(op, hidden_states), [0, 0, self._heads, self._qk_dim]
218-
)
268+
query = op.Reshape(self.q_proj(op, hidden_states), [0, 0, self._heads, self._qk_dim])
219269
compressed, key_extra = op.Split(
220270
self.kv_a_proj_with_mqa(op, hidden_states),
221271
[self._kv_rank, self._extra],
222272
axis=-1,
223273
_outputs=2,
224274
)
225275
compressed = self.kv_a_layernorm(op, compressed)
226-
key_nope = op.Reshape(
227-
self.k_b_proj(op, compressed), [0, 0, self._heads, self._nope]
228-
)
229-
value = op.Reshape(
230-
self.v_b_proj(op, compressed), [0, 0, self._heads, self._value_dim]
231-
)
276+
key_nope = op.Reshape(self.k_b_proj(op, compressed), [0, 0, self._heads, self._nope])
277+
value = op.Reshape(self.v_b_proj(op, compressed), [0, 0, self._heads, self._value_dim])
232278
key_extra = op.Expand(
233279
op.Reshape(key_extra, [0, 0, 1, self._extra]),
234280
[1, 1, self._heads, 1],

‎src/mobius/integrations/gguf/_arch_registry_test.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,7 @@
163163
"granitemoe",
164164
"hunyuan-dense",
165165
"jamba",
166+
"kimi-linear",
166167
"lfm2",
167168
"llada",
168169
"llada-moe",

‎src/mobius/integrations/gguf/_builder.py‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4947,9 +4947,10 @@ def _load_quantized_state_dict(
49474947
np_shape,
49484948
quantized_stems,
49494949
)
4950-
if gguf_arch == "kimi-linear" and module_hf_name.endswith(
4950+
is_kimi_reshaped_projection = gguf_arch == "kimi-linear" and module_hf_name.endswith(
49514951
(".k_b_proj.weight", ".v_b_proj.weight")
4952-
):
4952+
)
4953+
if is_kimi_reshaped_projection:
49534954
# These tensors are rank-3 in GGUF. They target one flattened
49544955
# projection rather than an expert-major collection.
49554956
affine_targets = []
@@ -4995,6 +4996,13 @@ def _load_quantized_state_dict(
49954996
)
49964997
if explicitly_dequantized and quant_spec.dequantize is Support.SUPPORTED:
49974998
route = QuantImportRoute.DEQUANTIZE_FLOAT
4999+
if is_kimi_reshaped_projection and route is QuantImportRoute.NATIVE_BYTES:
5000+
if quant_spec.dequantize is not Support.SUPPORTED:
5001+
raise ValueError(
5002+
f"Cannot reshape native {quant_spec.name} tensor {hf_name}: "
5003+
"the stored format has no supported dequantization route."
5004+
)
5005+
route = QuantImportRoute.DEQUANTIZE_REQUANTIZE
49985006
if route is QuantImportRoute.REJECTED:
49995007
raise ValueError(
50005008
f"Cannot import GGUF tensor {gguf_name} mapped to {hf_name} "
@@ -5199,9 +5207,7 @@ def _load_quantized_state_dict(
51995207
data_section_offset,
52005208
tensors_by_name[gguf_name],
52015209
)
5202-
elif gguf_arch == "kimi-linear" and hf_name.endswith(
5203-
(".k_b_proj.weight", ".v_b_proj.weight")
5204-
):
5210+
elif is_kimi_reshaped_projection:
52055211
values = gguf_model.dequantize_raw_tensor(raw, qtype, np_shape)
52065212
if hf_name.endswith(".k_b_proj.weight"):
52075213
values = values.transpose(0, 2, 1).reshape(

‎src/mobius/integrations/gguf/_builder_test.py‎

Lines changed: 84 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1406,6 +1406,7 @@ def _write_kimi_linear_gguf(
14061406
path: Path,
14071407
*,
14081408
quantized: bool,
1409+
native_quantized: bool = False,
14091410
omit: str | None = None,
14101411
extra: str | None = None,
14111412
malformed_shape: str | None = None,
@@ -1471,26 +1472,28 @@ def add_float(name: str, shape: tuple[int, ...]) -> None:
14711472
values.fill(1.0)
14721473
writer.add_tensor(name, values)
14731474

1474-
def add_q4(name: str, shape: tuple[int, ...]) -> None:
1475+
def add_quantized(name: str, shape: tuple[int, ...]) -> None:
14751476
if name == omit:
14761477
return
14771478
shape = shape_for(name, shape)
14781479
assert shape[-1] % 32 == 0
14791480
raw = np.zeros((*shape[:-1], shape[-1] // 32 * 18), dtype=np.uint8)
1480-
for index in np.ndindex(shape[:-1]):
1481-
for block in range(shape[-1] // 32):
1482-
offset = block * 18
1483-
raw[(*index, slice(offset, offset + 2))] = np.array(
1484-
[rng.uniform(0.01, 0.05)], dtype=np.float16
1485-
).view(np.uint8)
1486-
raw[(*index, slice(offset + 2, offset + 18))] = rng.integers(
1487-
0, 256, 16, dtype=np.uint8
1488-
)
1489-
writer.add_tensor(name, raw, raw_dtype=GGMLQuantizationType.Q4_0)
1481+
qtype = GGMLQuantizationType.IQ4_NL if native_quantized else GGMLQuantizationType.Q4_0
1482+
if not native_quantized:
1483+
for index in np.ndindex(shape[:-1]):
1484+
for block in range(shape[-1] // 32):
1485+
offset = block * 18
1486+
raw[(*index, slice(offset, offset + 2))] = np.array(
1487+
[rng.uniform(0.01, 0.05)], dtype=np.float16
1488+
).view(np.uint8)
1489+
raw[(*index, slice(offset + 2, offset + 18))] = rng.integers(
1490+
0, 256, 16, dtype=np.uint8
1491+
)
1492+
writer.add_tensor(name, raw, raw_dtype=qtype)
14901493

14911494
add_float("token_embd.weight", (vocab, hidden))
14921495
add_float("output_norm.weight", (hidden,))
1493-
projection = add_q4 if quantized else add_float
1496+
projection = add_quantized if quantized else add_float
14941497
projection("output.weight", (vocab, hidden))
14951498
projection_width = heads * kda_dim
14961499

@@ -5915,6 +5918,22 @@ def test_quantized_source_preserves_only_matmul_roles(self, tmp_path: Path) -> N
59155918
for name in quantized_inputs
59165919
)
59175920

5921+
def test_native_quantized_mla_projections_requantize_after_reshape(
5922+
self, tmp_path: Path
5923+
) -> None:
5924+
from mobius.integrations.gguf import build_from_gguf
5925+
5926+
path = tmp_path / "kimi-linear-iq4-nl.gguf"
5927+
_write_kimi_linear_gguf(path, quantized=True, native_quantized=True)
5928+
model = build_from_gguf(path, keep_quantized=True)["model"]
5929+
quantized_inputs = {
5930+
node.inputs[1].name
5931+
for node in model.graph
5932+
if node.op_type == "MatMulNBits" and len(node.inputs) > 1
5933+
}
5934+
assert any(name.endswith("k_b_proj.weight") for name in quantized_inputs)
5935+
assert any(name.endswith("v_b_proj.weight") for name in quantized_inputs)
5936+
59185937
def test_left_padding_does_not_change_valid_logits_or_states(self, tmp_path: Path) -> None:
59195938
from mobius._testing.ort_inference import OnnxModelSession
59205939
from mobius.integrations.gguf import build_from_gguf
@@ -5943,6 +5962,59 @@ def test_left_padding_does_not_change_valid_logits_or_states(self, tmp_path: Pat
59435962
finally:
59445963
session.close()
59455964

5965+
def test_right_padding_preserves_state_for_cached_decode(self, tmp_path: Path) -> None:
5966+
from mobius._testing.ort_inference import OnnxModelSession
5967+
from mobius.integrations.gguf import build_from_gguf
5968+
5969+
path = tmp_path / "kimi-linear-right-padding.gguf"
5970+
_write_kimi_linear_gguf(path, quantized=False)
5971+
session = OnnxModelSession(build_from_gguf(path)["model"])
5972+
try:
5973+
unpadded = session.run(self._inputs(np.asarray([[7, 8]], np.int64)))
5974+
padded = session.run(
5975+
self._inputs(
5976+
np.asarray([[7, 8, 0, 0]], np.int64),
5977+
attention_mask=np.asarray([[1, 1, 0, 0]], np.int64),
5978+
)
5979+
)
5980+
for suffix in (
5981+
"q_conv_state",
5982+
"k_conv_state",
5983+
"v_conv_state",
5984+
"recurrent_state",
5985+
):
5986+
np.testing.assert_allclose(
5987+
padded[f"present.0.{suffix}"],
5988+
unpadded[f"present.0.{suffix}"],
5989+
rtol=1e-5,
5990+
atol=1e-5,
5991+
)
5992+
5993+
unpadded_states = {
5994+
name.replace("present.", "past_key_values."): value
5995+
for name, value in unpadded.items()
5996+
if name.startswith("present.")
5997+
}
5998+
padded_states = {
5999+
name.replace("present.", "past_key_values."): value
6000+
for name, value in padded.items()
6001+
if name.startswith("present.")
6002+
}
6003+
token = np.asarray([[9]], np.int64)
6004+
expected = session.run(self._inputs(token, unpadded_states))
6005+
actual = session.run(
6006+
self._inputs(
6007+
token,
6008+
padded_states,
6009+
attention_mask=np.asarray([[1, 1, 0, 0, 1]], np.int64),
6010+
)
6011+
)
6012+
np.testing.assert_allclose(
6013+
actual["logits"], expected["logits"], rtol=1e-5, atol=1e-5
6014+
)
6015+
finally:
6016+
session.close()
6017+
59466018
def test_static_cache_is_rejected(self, tmp_path: Path) -> None:
59476019
from mobius.integrations.gguf import build_from_gguf
59486020

0 commit comments

Comments
 (0)