Skip to content

Commit 04c6641

Browse files
justinchubyCopilot
andauthored
Add dedicated Kimi Linear GGUF support (#619)
## Summary - implement the pinned Kimi Linear hybrid KDA/NoPE-MLA graph, dense/MoE schedule, and heterogeneous recurrent/KV state ABI - add strict GGUF metadata/tensor closure, layout transforms, compatible quantized MatMul/expert preservation, and malformed-input rejection - add graph, weight, ORT state/replay/reorder/padding, GGUF float/quantized, roundtrip, CLI, and documentation coverage ## Runtime boundary Generic OGA packaging remains deferred to #605 because the released decoder schema cannot represent mixed MLA KV and KDA convolution/matrix states exactly. ## Validation - focused Kimi: 34 passed - full GGUF: 2684 passed - broad non-integration: 7223 passed, 54 skipped - generated GGUF docs check passed - initialized lint completed with only pre-existing Falcon-H1 warnings - two independent reviews completed and findings fixed Stacked on #616 (`justinchuby-minimax-01-gguf`). --------- Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]>
1 parent b30c522 commit 04c6641

24 files changed

Lines changed: 2012 additions & 14 deletions

‎docs/api/build_from_gguf.md‎

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ from mobius import build_from_gguf
1515

1616
| Census | Total | Closure |
1717
|---|---:|---|
18-
| Architectures | 147 | graph verdicts: {'deferred': 87, 'rejected': 2, 'supported': 58}; importable: 56; quantized import: {'rejected': 11, 'supported': 136}; runtime: {'deferred': 144, 'rejected': 2, 'supported': 1} |
18+
| Architectures | 147 | graph verdicts: {'deferred': 86, 'rejected': 2, 'supported': 59}; importable: 57; quantized import: {'rejected': 11, 'supported': 136}; runtime: {'deferred': 144, 'rejected': 2, 'supported': 1} |
1919
| Active stored qtypes | 25 | 24 have an import route; 1 are explicitly deferred with no route |
2020
| Serialized projector strings | 60 | {'graph-importable': 2, 'runtime-supported': 0} |
2121
| Tokenizer pre identifiers | 87 | 56 semantic groups; all default to deferred and become materializable only from a validated embedded `tokenizer.huggingface.json` or an exact pinned source in runtime evidence |
@@ -412,7 +412,7 @@ before graph construction or durable output.
412412
| `jina-bert-v2` | — | none (fails before config extraction) | not claimed | config=deferred; tensor_map=deferred; graph=deferred; runtime=deferred; quantized_import=supported | JinaBERT v2 uses ALiBi, optional full-width Q/K norms, an extra attention norm, and either separate or fused GeGLU inputs. Mobius has no graph with that exact combination. |
413413
| `jina-bert-v3` | — | none (fails before config extraction) | not claimed | config=deferred; tensor_map=deferred; graph=deferred; runtime=deferred; quantized_import=supported | JinaBERT v3 uses RoPE and may alternate dense GELU and routed MoE layers. BertModel has absolute positions and no MoE path. |
414414
| `kimi-k3` | — | none (fails before config extraction) | not claimed | config=deferred; tensor_map=deferred; graph=deferred; runtime=deferred; quantized_import=supported | Kimi-K3 alternates KDA recurrent and NoPE MLA layers and requires convolution plus matrix state, sigmoid routed latent MoE with SiTU experts, optional shared experts, and cross-layer residual banks. Kimi-Linear is not an alias: its gates, expert activation, latent projections, and residual contract differ. Mobius has no exact graph or mixed-state task for either ABI. |
415-
| `kimi-linear` | — | none (fails before config extraction) | not claimed | config=deferred; tensor_map=deferred; graph=deferred; runtime=deferred; quantized_import=supported | Kimi-Linear alternates KDA recurrent and NoPE MLA layers, carrying three rolling convolution histories and a per-head matrix state in addition to attention cache. Its two-stage decay/output gates and sigmoid correction-bias MoE routing are not represented by any Mobius graph or state task; aliasing it to Kimi-K3, Mamba, or ordinary attention would change the model. |
415+
| `kimi-linear` | — | model=`kimi_linear`; tensor=`kimi_linear` | not claimed | config=supported; tensor_map=supported; graph=supported; runtime=deferred; quantized_import=supported | The exact KDA/NoPE-MLA schedule, four-state recurrent ABI, dense/MoE topology, correction-bias routing, pinned metadata, tensor closure, and compatible MatMul/expert quantization are supported. Released generic ORT GenAI cache schemas cannot represent heterogeneous KV plus three convolution histories and a matrix state, and representative real-weight GGUF evidence is pending; package runtime remains tracked by onnxruntime/mobius#605. |
416416
| `laguna` | — | none (fails before config extraction) | audited-direct-loader-conditional-union | config=deferred; tensor_map=deferred; graph=deferred; runtime=deferred; quantized_import=supported | Laguna combines per-head-or-element softplus attention gates, dual-RoPE interleaved sliding-window attention, a dense prefix, and sigmoid correction-biased routed/shared experts. Mobius has no exact graph or iSWA cache contract. |
417417
| `lfm2` | — | model=`lfm2`; tensor=`lfm2` | not claimed | config=supported; tensor_map=supported; graph=supported; runtime=deferred; quantized_import=supported | Config extraction, exact pinned tensor-name closure, GGUF value transforms, and synthetic recurrent-state execution are covered, but no representative real-weight GGUF has yet passed independent full-logit parity and deterministic multi-token stateful ORT generation. Runtime packaging remains deferred until that evidence exists. |
418418
| `lfm2moe` | — | model=`lfm2_moe`; tensor=`lfm2`+`lfm2_moe_extras` | not claimed | config=supported; tensor_map=supported; graph=supported; runtime=deferred; quantized_import=rejected | Config extraction, exact pinned tensor-name closure, GGUF value transforms, and synthetic recurrent-state execution are covered, but no representative real-weight GGUF has yet passed independent full-logit parity and deterministic multi-token stateful ORT generation. Runtime packaging remains deferred until that evidence exists. The mobius graph uses floating Linear modules for this architecture, so no MatMulNBits or BlockQuantizedMatMul target can consume preserved GGUF projection weights. Use keep_quantized=False for explicit float import. |
@@ -615,6 +615,50 @@ attention, dense-MLP, and routed-MoE scheduling. Files with a folded MTP block
615615
still fail before graph construction because no released package contract
616616
represents that auxiliary attention+MoE head.
617617

618+
### Remaining hybrid cohort
619+
620+
`bailingmoe3`, `deepseek4`, and `kimi-k3` are explicitly
621+
deferred before config extraction. Their loader inventories are
622+
suffix-exact in the pinned census, but none has an exact Mobius graph plus state
623+
task. No aliases are accepted.
624+
625+
- BailingMoE3 and Kimi-K3 mix KDA recurrence with MLA. A recurrent
626+
layer carries three Q/K/V convolution histories and a per-head matrix state;
627+
an MLA layer carries attention cache. BailingMoE3 also has gated attention,
628+
correction-biased routed/shared SwiGLU experts, and optional single-layer
629+
NextN storage. Kimi-K3 adds SiTU, latent expert projections, and cross-layer
630+
residual banks.
631+
- Kimi-Linear now has a dedicated graph and task. The importer reconstructs the
632+
exact per-layer KDA/NoPE-MLA schedule from `attention.head_count_kv`, validates
633+
dense-versus-MoE closure, restores `A_log`, convolution, and split MLA K/V-B
634+
layouts, and exposes three convolution histories plus one FP32 recurrent matrix
635+
for each KDA layer. Static cache and generic OGA packaging remain unsupported
636+
because released decoder cache schemas cannot represent that heterogeneous ABI.
637+
- DeepSeek-V4 requires raw sliding-window K, ratio-4 CSA, ratio-128 HCA, and
638+
indexer compressed caches plus persistent compressor and rollback state.
639+
Compression ratios are per-layer and limited to `0`, `4`, or `128`; ratio 4
640+
alone owns indexer-compressor tensors. Hash-routed prefix layers and later
641+
sqrt-softplus/correction-bias layers share neither selection inputs nor cache
642+
behavior. The Mobius Hugging Face model intentionally exports a dense fallback
643+
with ordinary KV state, so it remains valid for `mobius build` but cannot be
644+
used for `general.architecture=deepseek4`.
645+
- LFM2MoE serializes its arbitrary attention/short-convolution schedule as the
646+
complete `attention.head_count_kv` array (`0` means convolution). It switches
647+
from dense SwiGLU to sigmoid, correction-biased, normalized routed experts at
648+
`leading_dense_block_count`. Recurrent state is F32 rolling convolution
649+
history with copy-on-write reorder and bounded rollback snapshots; it is not
650+
ordinary KV or the dense LFM2 task.
651+
- The pinned GGUF closures use separate gate/up/down expert tensors. They do not
652+
contain emitted `.scale` or `.input_scale` sidecars: DeepSeek-V4 and Kimi-K3
653+
converter input scales are consumed while forming MXFP4 expert weights.
654+
Recurrent coefficients, convolution kernels, biases, norms, hash tables, and
655+
residual/compressor sidecars are not mathematically interchangeable with
656+
MatMul weights and must never be silently preserved or dropped.
657+
- Partial NextN/MTP, fused gate-up experts, mixed tied output storage, unknown
658+
mixer tensors, and auxiliary heads remain outside the admitted contract.
659+
Runtime status cannot advance without a pinned real artifact, independent
660+
full-logit parity, and deterministic stateful generation evidence.
661+
618662
### Audio/TTS/codec cohort
619663

620664
The four C09 architectures below were audited against llama.cpp commit

‎src/mobius/_configs/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
GraniteMoeHybridConfig,
4242
JambaConfig,
4343
JetMoeConfig,
44+
KimiLinearConfig,
4445
Lfm2Config,
4546
Lfm2MoeConfig,
4647
Lfm2VlConfig,
@@ -121,6 +122,7 @@
121122
"GraniteMoeHybridConfig",
122123
"JambaConfig",
123124
"JetMoeConfig",
125+
"KimiLinearConfig",
124126
"Lfm2Config",
125127
"Lfm2MoeConfig",
126128
"Lfm2VlConfig",

‎src/mobius/_configs/_base.py‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1503,6 +1503,88 @@ def from_transformers(cls, config, parent_config=None) -> MiniMaxConfig:
15031503
return cls(**fields)
15041504

15051505

1506+
@dataclasses.dataclass
1507+
class KimiLinearConfig(CausalLMConfig):
1508+
"""Exact configuration for Moonshot Kimi Linear models."""
1509+
1510+
@classmethod
1511+
def from_transformers(cls, config, parent_config=None) -> KimiLinearConfig:
1512+
base = ArchitectureConfig.from_transformers(config, parent_config)
1513+
linear = _as_attribute_config(getattr(config, "linear_attn_config", None))
1514+
if linear is None:
1515+
raise ValueError("Kimi Linear requires linear_attn_config")
1516+
1517+
kda_layers = [int(i) for i in getattr(linear, "kda_layers", ())]
1518+
full_layers = [int(i) for i in getattr(linear, "full_attn_layers", ())]
1519+
expected = set(range(1, base.num_hidden_layers + 1))
1520+
if set(kda_layers) & set(full_layers):
1521+
raise ValueError("Kimi Linear KDA and full-attention schedules must not overlap")
1522+
if set(kda_layers) | set(full_layers) != expected:
1523+
raise ValueError(
1524+
"Kimi Linear schedules must exactly partition one-based layer indices "
1525+
f"1..{base.num_hidden_layers}"
1526+
)
1527+
if len(kda_layers) != len(set(kda_layers)) or len(full_layers) != len(
1528+
set(full_layers)
1529+
):
1530+
raise ValueError("Kimi Linear schedules must not contain duplicate layers")
1531+
if not bool(getattr(config, "mla_use_nope", False)):
1532+
raise ValueError("Kimi Linear requires mla_use_nope=true")
1533+
if getattr(config, "q_lora_rank", None) not in (None, 0):
1534+
raise ValueError("Kimi Linear Q-LoRA is not supported by the authoritative graph")
1535+
if int(getattr(config, "num_nextn_predict_layers", 0)):
1536+
raise ValueError("Kimi Linear NextN prediction layers are not supported")
1537+
if int(getattr(config, "moe_layer_freq", 1)) != 1:
1538+
raise ValueError("Kimi Linear requires moe_layer_freq=1")
1539+
if str(getattr(config, "moe_router_activation_func", "")) != "sigmoid":
1540+
raise ValueError("Kimi Linear requires sigmoid expert routing")
1541+
if not bool(getattr(config, "moe_renormalize", False)):
1542+
raise ValueError("Kimi Linear requires selected expert weight renormalization")
1543+
n_group = int(vars(config).get("num_expert_group", 1))
1544+
topk_group = int(vars(config).get("topk_group", 1))
1545+
if n_group != 1 or topk_group != 1:
1546+
raise ValueError(
1547+
"Kimi Linear supports only the pinned single expert-group profile"
1548+
)
1549+
1550+
num_heads = int(vars(linear).get("num_heads", base.num_attention_heads))
1551+
head_dim = int(linear.head_dim)
1552+
if num_heads != base.num_attention_heads:
1553+
raise ValueError("Kimi Linear KDA and MLA head counts must match")
1554+
fields = _shallow_fields(base)
1555+
fields.update(
1556+
model_type="kimi_linear",
1557+
layer_types=[
1558+
"kimi_linear_attention" if i + 1 in set(kda_layers) else "full_attention"
1559+
for i in range(base.num_hidden_layers)
1560+
],
1561+
linear_num_key_heads=num_heads,
1562+
linear_num_value_heads=num_heads,
1563+
linear_key_head_dim=head_dim,
1564+
linear_value_head_dim=head_dim,
1565+
linear_conv_kernel_dim=int(linear.short_conv_kernel_size),
1566+
num_local_experts=int(config.num_experts),
1567+
num_experts_per_tok=int(config.num_experts_per_token),
1568+
n_group=n_group,
1569+
topk_group=topk_group,
1570+
n_shared_experts=int(config.num_shared_experts),
1571+
norm_topk_prob=True,
1572+
scoring_func="sigmoid",
1573+
topk_method="noaux_tc",
1574+
disable_qmoe=True,
1575+
rope_type=None,
1576+
rope_theta=None,
1577+
rope_scaling=None,
1578+
partial_rotary_factor=None,
1579+
)
1580+
result = cls(**fields)
1581+
if result.qk_nope_head_dim is None or result.qk_rope_head_dim is None:
1582+
raise ValueError("Kimi Linear requires both MLA key dimension fields")
1583+
if result.v_head_dim is None or result.kv_lora_rank is None:
1584+
raise ValueError("Kimi Linear requires MLA value dimension and KV-LoRA rank")
1585+
return result
1586+
1587+
15061588
@dataclasses.dataclass
15071589
class EncoderConfig(ArchitectureConfig):
15081590
"""Configuration for encoder-only models (BERT, ViT, etc.)."""

‎src/mobius/_configs/_base_test.py‎

Lines changed: 98 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,104 @@
99

1010
import pytest
1111

12-
from mobius._configs import ArchitectureConfig, MiniMaxConfig, NemotronParseConfig
12+
from mobius._configs import (
13+
ArchitectureConfig,
14+
KimiLinearConfig,
15+
MiniMaxConfig,
16+
NemotronParseConfig,
17+
)
18+
19+
20+
def _kimi_linear_hf_config(**overrides):
21+
values = {
22+
"model_type": "kimi_linear",
23+
"hidden_size": 64,
24+
"intermediate_size": 64,
25+
"num_hidden_layers": 4,
26+
"num_attention_heads": 2,
27+
"num_key_value_heads": 1,
28+
"head_dim": 48,
29+
"vocab_size": 64,
30+
"max_position_embeddings": 64,
31+
"rms_norm_eps": 1e-6,
32+
"hidden_act": "silu",
33+
"tie_word_embeddings": False,
34+
"linear_attn_config": {
35+
"kda_layers": [1, 2, 3],
36+
"full_attn_layers": [4],
37+
"num_heads": 2,
38+
"head_dim": 32,
39+
"short_conv_kernel_size": 4,
40+
},
41+
"mla_use_nope": True,
42+
"q_lora_rank": None,
43+
"qk_nope_head_dim": 32,
44+
"qk_rope_head_dim": 16,
45+
"v_head_dim": 32,
46+
"kv_lora_rank": 32,
47+
"first_k_dense_replace": 1,
48+
"moe_intermediate_size": 32,
49+
"moe_layer_freq": 1,
50+
"moe_renormalize": True,
51+
"moe_router_activation_func": "sigmoid",
52+
"num_experts": 2,
53+
"num_experts_per_token": 1,
54+
"num_expert_group": 1,
55+
"topk_group": 1,
56+
"num_shared_experts": 1,
57+
"num_nextn_predict_layers": 0,
58+
"routed_scaling_factor": 2.446,
59+
}
60+
values.update(overrides)
61+
return types.SimpleNamespace(**values)
62+
63+
64+
def test_kimi_linear_config_extracts_exact_schedule() -> None:
65+
config = KimiLinearConfig.from_transformers(_kimi_linear_hf_config())
66+
67+
assert config.layer_types == [
68+
"kimi_linear_attention",
69+
"kimi_linear_attention",
70+
"kimi_linear_attention",
71+
"full_attention",
72+
]
73+
assert config.linear_key_head_dim == 32
74+
assert config.qk_nope_head_dim == 32
75+
assert config.qk_rope_head_dim == 16
76+
77+
78+
def test_kimi_linear_config_uses_top_level_head_count_when_nested_value_is_absent() -> None:
79+
config = _kimi_linear_hf_config()
80+
del config.linear_attn_config["num_heads"]
81+
82+
extracted = KimiLinearConfig.from_transformers(config)
83+
84+
assert extracted.linear_num_key_heads == config.num_attention_heads
85+
86+
87+
@pytest.mark.parametrize(
88+
("override", "match"),
89+
[
90+
(
91+
{
92+
"linear_attn_config": {
93+
"kda_layers": [1, 2],
94+
"full_attn_layers": [4],
95+
"num_heads": 2,
96+
"head_dim": 32,
97+
"short_conv_kernel_size": 4,
98+
}
99+
},
100+
"exactly partition",
101+
),
102+
({"num_expert_group": 2}, "single expert-group"),
103+
],
104+
)
105+
def test_kimi_linear_config_rejects_non_authoritative_profiles(
106+
override: dict, match: str
107+
) -> None:
108+
with pytest.raises(ValueError, match=match):
109+
KimiLinearConfig.from_transformers(_kimi_linear_hf_config(**override))
13110

14111

15112
def test_minimax_config_extracts_exact_schedule_head_geometry_and_residuals():

‎src/mobius/_registry.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
Gemma3nMultiModalConfig,
3030
Gemma4AssistantConfig,
3131
Gemma4Config,
32+
KimiLinearConfig,
3233
Lfm2Config,
3334
Lfm2MoeConfig,
3435
Lfm2VlConfig,
@@ -82,6 +83,7 @@
8283
HunYuanV1DenseCausalLMModel,
8384
HunYuanVLMoTModel,
8485
InternLM2CausalLMModel,
86+
KimiLinearCausalLMModel,
8587
LayerNormCausalLMModel,
8688
Lfm2CausalLMModel,
8789
Lfm2MoECausalLMModel,
@@ -603,6 +605,11 @@ def _detect_fallback_registration(hf_config) -> ModelRegistration | None:
603605
"granitemoeshared": ModelRegistration(GraniteMoECausalLMModel),
604606
"hunyuan_v1_moe": ModelRegistration(HunYuanMoEV1CausalLMModel),
605607
"jetmoe": ModelRegistration(JetMoeCausalLMModel),
608+
"kimi_linear": ModelRegistration(
609+
KimiLinearCausalLMModel,
610+
task="kimi-linear-text-generation",
611+
config_class=KimiLinearConfig,
612+
),
606613
"minimax": ModelRegistration(MiniMaxCausalLMModel, config_class=MiniMaxConfig),
607614
"MiniMaxText01": ModelRegistration(MiniMaxCausalLMModel, config_class=MiniMaxConfig),
608615
"minimax_text_01": ModelRegistration(MiniMaxCausalLMModel, config_class=MiniMaxConfig),
@@ -1069,6 +1076,7 @@ def _create_default_registry() -> ModelRegistry:
10691076
"dbrx": "databricks/dbrx-instruct",
10701077
"arctic": "Snowflake/snowflake-arctic-instruct",
10711078
"jetmoe": "jetmoe/jetmoe-8b",
1079+
"kimi_linear": "moonshotai/Kimi-Linear-48B-A3B-Instruct",
10721080
"longcat_flash": "yujiepan/longcat-flash-tiny-random",
10731081
"minimax": "MiniMaxAI/MiniMax-Text-01",
10741082
"ernie4_5_moe": "baidu/ERNIE-4.5-21B-A3B-PT",

‎src/mobius/components/__init__.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@
3333
"GatedDeltaNet",
3434
"GatedMLP",
3535
"GatedRMSNorm",
36+
"KimiDeltaAttention",
37+
"KimiMLAAttention",
3638
"Gemma3nAudioEncoder",
3739
"Gemma3nMultimodalEmbedder",
3840
"GlmOcrVisionModel",
@@ -181,6 +183,7 @@
181183
from mobius.components._gemma4_audio import ClippableLinear
182184
from mobius.components._gemma4_audio import Gemma4AudioEncoder as Gemma4AudioEncoder
183185
from mobius.components._glm_ocr_vision import GlmOcrVisionModel
186+
from mobius.components._kimi_linear import KimiDeltaAttention, KimiMLAAttention
184187
from mobius.components._lightning_attention import (
185188
LightningAttention as LightningAttention,
186189
)

0 commit comments

Comments
 (0)