Skip to content

Commit aec175f

Browse files
justinchubyCopilot
andauthored
Add dedicated Kimi-K3 GGUF support (#621)
## Summary - add a dedicated Kimi-K3 config, model, and heterogeneous-state task with exact KDA/NoPE gated-MLA scheduling, AttnRes mixing, SiTU latent MoE, shared experts, and an untied output head - import pinned llama.cpp `kimi-k3` GGUF metadata and tensors with strict metadata/tensor/shape/storage closure and malformed-input rejection - preserve lossless quantization routes under #609: separate rank-3 MLA projections fail closed unless explicitly dequantized, while fused Q4_0 KV-B is split by exact packed-row reordering across weights, scales, and zero-points - preserve valid KDA convolution history across padding, validate kernel/state/task contracts, and cover replay, reorder, float/quantized import, roundtrip, CLI, and negative paths - keep generic OGA runtime packaging truthfully deferred under #605 because released cache schemas cannot represent the heterogeneous state ABI ## Reconstruction Reconstructed after #619 was admin squash-merged. The PR contains only the four-commit Kimi-K3 delta and review follow-ups on live-main base `04b7e3f6f2d9de5d5741aafb8fa6375a18eee693`. This preserves #611 graph-driven ORT GenAI decoder configs, #618 ORT GenAI end-to-end CI, #624 generic decoder config migration, and the Kimi Linear, MiniMax, runtime, and fail-closed quantization changes already on main. `git range-diff` reports all four replayed commits as patch-identical (`=`). ## Validation - Kimi-K3 model and GGUF tests: 30 passed - focused builder/build-graph Kimi-K3 checks: 4 passed, 1900 deselected - affected generic ORT config/runtime/E2E tests: 250 passed - affected OGA metadata tests: 94 passed, 1 skipped - broad non-integration suite: 7765 passed, 56 skipped, 1 subtest passed - repository lintrunner passed - final GPT-5.6 Sol medium review reported no findings ## Real-checkpoint note The pinned `yujiepan/kimi-k3-tiny-random@a5c86ee03f07f7b141508b0108304a1447fbb345` checkpoint was assessed, but macOS cannot run its required `fla-core` kernels and its selective compressed-tensors MXFP4 expert representation is unsupported by the generic HF loader. That format fails explicitly rather than producing an incorrectly quantized graph. --------- Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]>
1 parent 04b7e3f commit aec175f

23 files changed

Lines changed: 2635 additions & 35 deletions

‎docs/api/build_from_gguf.md‎

Lines changed: 10 additions & 8 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': 86, 'rejected': 2, 'supported': 59}; importable: 57; quantized import: {'rejected': 11, 'supported': 136}; runtime: {'deferred': 144, 'rejected': 2, 'supported': 1} |
18+
| Architectures | 147 | graph verdicts: {'deferred': 85, 'rejected': 2, 'supported': 60}; importable: 58; 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 |
@@ -414,7 +414,7 @@ before graph construction or durable output.
414414
| `jamba` | — | model=`jamba`; tensor=`jamba` | not claimed | config=supported; tensor_map=supported; graph=supported; runtime=deferred; quantized_import=supported | Exact mixed attention/Mamba and dense/routed-MoE schedules, strict tensor closure and shapes, GGUF value transforms, compatible projection quantization, value-checked expert ordering, reduced Transformers parity, and multi-token ORT state threading, reorder, and replay are covered. Generic ORT GenAI runtime packaging remains deferred because its released cache schema cannot represent heterogeneous KV, convolution, and recurrent state slots; tracked by #605. |
415415
| `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. |
416416
| `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. |
417-
| `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. |
417+
| `kimi-k3` | — | model=`kimi_k3`; tensor=`kimi_k3` | not claimed | config=supported; tensor_map=supported; graph=supported; runtime=deferred; quantized_import=supported | The exact KDA/NoPE gated-MLA schedule, four-state recurrent ABI, attention-residual banks, Stable LatentMoE routing, SiTU activation, strict metadata/tensor closure, and compatible projection quantization are supported. Released generic ORT GenAI cache schemas cannot represent the heterogeneous KV plus convolution/matrix state ABI; tracked by onnxruntime/mobius#605. |
418418
| `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. |
419419
| `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. |
420420
| `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. |
@@ -620,17 +620,19 @@ represents that auxiliary attention+MoE head.
620620

621621
### Remaining hybrid cohort
622622

623-
`bailingmoe3`, `deepseek4`, and `kimi-k3` are explicitly
623+
`bailingmoe3` and `deepseek4` are explicitly
624624
deferred before config extraction. Their loader inventories are
625625
suffix-exact in the pinned census, but none has an exact Mobius graph plus state
626626
task. No aliases are accepted.
627627

628-
- BailingMoE3 and Kimi-K3 mix KDA recurrence with MLA. A recurrent
629-
layer carries three Q/K/V convolution histories and a per-head matrix state;
630-
an MLA layer carries attention cache. BailingMoE3 also has gated attention,
628+
- BailingMoE3 mixes KDA recurrence with MLA, gated attention,
631629
correction-biased routed/shared SwiGLU experts, and optional single-layer
632-
NextN storage. Kimi-K3 adds SiTU, latent expert projections, and cross-layer
633-
residual banks.
630+
NextN storage. Its exact graph and state task remain deferred.
631+
- Kimi-K3 now has a dedicated text graph and task. It preserves Q-LoRA gated
632+
NoPE MLA, lower-bounded KDA decay with full-rank output gates, cross-layer
633+
attention residuals, and Stable LatentMoE with SiTU. Each recurrent layer
634+
carries three Q/K/V convolution histories and one FP32 matrix state; static
635+
cache and generic OGA packaging remain deferred under #605.
634636
- Kimi-Linear now has a dedicated graph and task. The importer reconstructs the
635637
exact per-layer KDA/NoPE-MLA schedule from `attention.head_count_kv`, validates
636638
dense-versus-MoE closure, restores `A_log`, convolution, and split MLA K/V-B

‎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+
KimiK3Config,
4445
KimiLinearConfig,
4546
Lfm2Config,
4647
Lfm2MoeConfig,
@@ -122,6 +123,7 @@
122123
"GraniteMoeHybridConfig",
123124
"JambaConfig",
124125
"JetMoeConfig",
126+
"KimiK3Config",
125127
"KimiLinearConfig",
126128
"Lfm2Config",
127129
"Lfm2MoeConfig",

‎src/mobius/_configs/_base.py‎

Lines changed: 148 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -422,6 +422,8 @@ class ArchitectureConfig(BaseModelConfig):
422422
linear_value_head_dim: int | None = None
423423
linear_num_key_heads: int | None = None
424424
linear_num_value_heads: int | None = None
425+
linear_gate_lower_bound: float | None = None
426+
linear_use_full_rank_gate: bool = False
425427

426428
# Double-gated short-convolution config (LFM2-style hybrid layers).
427429
short_conv_kernel: int = 3
@@ -504,6 +506,14 @@ class ArchitectureConfig(BaseModelConfig):
504506
qk_rope_head_dim: int | None = None
505507
v_head_dim: int | None = None
506508
rope_interleave: bool = False
509+
mla_use_output_gate: bool = False
510+
511+
# Kimi-K3 attention-residual and latent-expert configuration.
512+
attn_res_block_size: int | None = None
513+
routed_expert_hidden_size: int | None = None
514+
latent_moe_use_norm: bool = False
515+
activation_situ_beta: float = 1.0
516+
activation_situ_linear_beta: float | None = None
507517

508518
# DeepSeek-V4 compressed sparse attention / Hyper-Connections.
509519
o_groups: int = 1
@@ -1549,8 +1559,11 @@ def from_transformers(cls, config, parent_config=None) -> KimiLinearConfig:
15491559

15501560
num_heads = int(vars(linear).get("num_heads", base.num_attention_heads))
15511561
head_dim = int(linear.head_dim)
1562+
conv_kernel = int(linear.short_conv_kernel_size)
15521563
if num_heads != base.num_attention_heads:
15531564
raise ValueError("Kimi Linear KDA and MLA head counts must match")
1565+
if conv_kernel < 2:
1566+
raise ValueError("Kimi Linear short_conv_kernel_size must be at least 2")
15541567
fields = _shallow_fields(base)
15551568
fields.update(
15561569
model_type="kimi_linear",
@@ -1562,7 +1575,7 @@ def from_transformers(cls, config, parent_config=None) -> KimiLinearConfig:
15621575
linear_num_value_heads=num_heads,
15631576
linear_key_head_dim=head_dim,
15641577
linear_value_head_dim=head_dim,
1565-
linear_conv_kernel_dim=int(linear.short_conv_kernel_size),
1578+
linear_conv_kernel_dim=conv_kernel,
15661579
num_local_experts=int(config.num_experts),
15671580
num_experts_per_tok=int(config.num_experts_per_token),
15681581
n_group=n_group,
@@ -1585,6 +1598,140 @@ def from_transformers(cls, config, parent_config=None) -> KimiLinearConfig:
15851598
return result
15861599

15871600

1601+
@dataclasses.dataclass
1602+
class KimiK3Config(CausalLMConfig):
1603+
"""Text-decoder configuration extracted from the composite Kimi-K3 config."""
1604+
1605+
@classmethod
1606+
def from_transformers(cls, config, parent_config=None) -> KimiK3Config:
1607+
parent = parent_config or config
1608+
text = _as_attribute_config(getattr(config, "text_config", None)) or config
1609+
base = ArchitectureConfig.from_transformers(text, parent)
1610+
if (
1611+
base.quantization is not None
1612+
and base.quantization.quant_method == "compressed-tensors"
1613+
):
1614+
raise NotImplementedError(
1615+
"Kimi-K3 compressed-tensors checkpoints use selective MXFP4 routed "
1616+
"experts, which are not representable by the generic quantized-linear "
1617+
"loader. Use a GGUF checkpoint or an unquantized state dict."
1618+
)
1619+
linear = _as_attribute_config(getattr(text, "linear_attn_config", None))
1620+
if linear is None:
1621+
raise ValueError("Kimi-K3 requires text_config.linear_attn_config")
1622+
1623+
kda_layers = [int(i) for i in getattr(linear, "kda_layers", ())]
1624+
full_layers = [int(i) for i in getattr(linear, "full_attn_layers", ())]
1625+
expected = set(range(1, base.num_hidden_layers + 1))
1626+
if (
1627+
set(kda_layers) & set(full_layers)
1628+
or set(kda_layers) | set(full_layers) != expected
1629+
or len(kda_layers) != len(set(kda_layers))
1630+
or len(full_layers) != len(set(full_layers))
1631+
):
1632+
raise ValueError(
1633+
"Kimi-K3 KDA and MLA schedules must uniquely partition one-based "
1634+
f"layer indices 1..{base.num_hidden_layers}"
1635+
)
1636+
if not bool(getattr(text, "mla_use_nope", False)):
1637+
raise ValueError("Kimi-K3 requires mla_use_nope=true")
1638+
if not bool(getattr(text, "mla_use_output_gate", False)):
1639+
raise ValueError("Kimi-K3 requires mla_use_output_gate=true")
1640+
if not bool(getattr(linear, "use_full_rank_gate", False)):
1641+
raise ValueError("Kimi-K3 requires a full-rank KDA output gate")
1642+
raw_lower_bound = float(getattr(linear, "gate_lower_bound", 0.0))
1643+
if raw_lower_bound >= 0.0:
1644+
raise ValueError("Kimi-K3 gate_lower_bound must be negative")
1645+
if int(getattr(text, "first_k_dense_replace", 0)) != 1:
1646+
raise ValueError("Kimi-K3 requires exactly one leading dense layer")
1647+
if int(getattr(text, "num_shared_experts", 0)) != 2:
1648+
raise ValueError("Kimi-K3 requires exactly two shared experts")
1649+
if str(getattr(text, "hidden_act", "")) != "situ":
1650+
raise ValueError("Kimi-K3 requires SiTU expert activation")
1651+
if not math.isclose(float(getattr(text, "activation_situ_beta", 0.0)), 4.0):
1652+
raise ValueError("Kimi-K3 requires activation_situ_beta=4")
1653+
if not math.isclose(float(getattr(text, "activation_situ_linear_beta", 0.0)), 25.0):
1654+
raise ValueError("Kimi-K3 requires activation_situ_linear_beta=25")
1655+
if not bool(getattr(text, "latent_moe_use_norm", False)):
1656+
raise ValueError("Kimi-K3 requires latent MoE RMS normalization")
1657+
if getattr(text, "routed_expert_hidden_size", None) is None:
1658+
raise ValueError("Kimi-K3 requires routed_expert_hidden_size")
1659+
if getattr(text, "q_lora_rank", None) in (None, 0):
1660+
raise ValueError("Kimi-K3 requires Q-LoRA")
1661+
if bool(getattr(text, "tie_word_embeddings", False)):
1662+
raise ValueError("Kimi-K3 requires an untied LM head")
1663+
if str(getattr(text, "moe_router_activation_func", "")) != "sigmoid":
1664+
raise ValueError("Kimi-K3 requires sigmoid expert routing")
1665+
if not bool(getattr(text, "moe_renormalize", False)):
1666+
raise ValueError("Kimi-K3 requires selected expert weight renormalization")
1667+
if int(getattr(text, "moe_layer_freq", 1)) != 1:
1668+
raise ValueError("Kimi-K3 requires MoE in every layer after layer zero")
1669+
if str(getattr(text, "topk_method", "")) != "noaux_tc":
1670+
raise ValueError("Kimi-K3 requires correction-bias noaux_tc routing")
1671+
if (
1672+
int(getattr(text, "num_expert_group", 1)) != 1
1673+
or int(getattr(text, "topk_group", 1)) != 1
1674+
):
1675+
raise ValueError("Kimi-K3 requires the released single expert-group profile")
1676+
if int(getattr(text, "num_nextn_predict_layers", 0)):
1677+
raise ValueError("Kimi-K3 NextN prediction layers are not supported")
1678+
if int(getattr(text, "attn_res_block_size", 0)) <= 0:
1679+
raise ValueError("Kimi-K3 requires a positive attn_res_block_size")
1680+
1681+
num_heads = int(vars(linear).get("num_heads", base.num_attention_heads))
1682+
conv_kernel = int(linear.short_conv_kernel_size)
1683+
if num_heads != base.num_attention_heads:
1684+
raise ValueError("Kimi-K3 KDA and MLA head counts must match")
1685+
if conv_kernel < 2:
1686+
raise ValueError("Kimi-K3 short_conv_kernel_size must be at least 2")
1687+
fields = _shallow_fields(base)
1688+
fields.update(
1689+
model_type="kimi_k3",
1690+
layer_types=[
1691+
"kimi_k3_attention" if i + 1 in set(kda_layers) else "full_attention"
1692+
for i in range(base.num_hidden_layers)
1693+
],
1694+
linear_num_key_heads=num_heads,
1695+
linear_num_value_heads=num_heads,
1696+
linear_key_head_dim=int(linear.head_dim),
1697+
linear_value_head_dim=int(linear.head_dim),
1698+
linear_conv_kernel_dim=conv_kernel,
1699+
linear_gate_lower_bound=-raw_lower_bound,
1700+
linear_use_full_rank_gate=True,
1701+
mla_use_output_gate=True,
1702+
attn_res_block_size=int(text.attn_res_block_size),
1703+
routed_expert_hidden_size=int(text.routed_expert_hidden_size),
1704+
latent_moe_use_norm=True,
1705+
activation_situ_beta=float(text.activation_situ_beta),
1706+
activation_situ_linear_beta=float(text.activation_situ_linear_beta),
1707+
num_local_experts=int(text.num_experts),
1708+
num_experts_per_tok=int(text.num_experts_per_token),
1709+
n_group=int(getattr(text, "num_expert_group", 1)),
1710+
topk_group=int(getattr(text, "topk_group", 1)),
1711+
n_shared_experts=2,
1712+
norm_topk_prob=True,
1713+
scoring_func="sigmoid",
1714+
topk_method="noaux_tc",
1715+
disable_qmoe=True,
1716+
rope_type=None,
1717+
rope_theta=None,
1718+
rope_scaling=None,
1719+
partial_rotary_factor=None,
1720+
tie_word_embeddings=False,
1721+
)
1722+
result = cls(**fields)
1723+
required = (
1724+
result.q_lora_rank,
1725+
result.kv_lora_rank,
1726+
result.qk_nope_head_dim,
1727+
result.qk_rope_head_dim,
1728+
result.v_head_dim,
1729+
)
1730+
if any(value is None for value in required):
1731+
raise ValueError("Kimi-K3 requires complete Q-LoRA and MLA dimensions")
1732+
return result
1733+
1734+
15881735
@dataclasses.dataclass
15891736
class EncoderConfig(ArchitectureConfig):
15901737
"""Configuration for encoder-only models (BERT, ViT, etc.)."""

‎src/mobius/_configs/_base_test.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,14 @@ def test_kimi_linear_config_uses_top_level_head_count_when_nested_value_is_absen
8484
assert extracted.linear_num_key_heads == config.num_attention_heads
8585

8686

87+
def test_kimi_linear_config_rejects_empty_convolution_history() -> None:
88+
config = _kimi_linear_hf_config()
89+
config.linear_attn_config["short_conv_kernel_size"] = 1
90+
91+
with pytest.raises(ValueError, match="at least 2"):
92+
KimiLinearConfig.from_transformers(config)
93+
94+
8795
@pytest.mark.parametrize(
8896
("override", "match"),
8997
[

‎src/mobius/_registry.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
Gemma3nMultiModalConfig,
3030
Gemma4AssistantConfig,
3131
Gemma4Config,
32+
KimiK3Config,
3233
KimiLinearConfig,
3334
Lfm2Config,
3435
Lfm2MoeConfig,
@@ -83,6 +84,7 @@
8384
HunYuanV1DenseCausalLMModel,
8485
HunYuanVLMoTModel,
8586
InternLM2CausalLMModel,
87+
KimiK3CausalLMModel,
8688
KimiLinearCausalLMModel,
8789
LayerNormCausalLMModel,
8890
Lfm2CausalLMModel,
@@ -610,6 +612,11 @@ def _detect_fallback_registration(hf_config) -> ModelRegistration | None:
610612
task="kimi-linear-text-generation",
611613
config_class=KimiLinearConfig,
612614
),
615+
"kimi_k3": ModelRegistration(
616+
KimiK3CausalLMModel,
617+
task="kimi-k3-text-generation",
618+
config_class=KimiK3Config,
619+
),
613620
"minimax": ModelRegistration(MiniMaxCausalLMModel, config_class=MiniMaxConfig),
614621
"MiniMaxText01": ModelRegistration(MiniMaxCausalLMModel, config_class=MiniMaxConfig),
615622
"minimax_text_01": ModelRegistration(MiniMaxCausalLMModel, config_class=MiniMaxConfig),
@@ -1017,6 +1024,7 @@ def _create_default_registry() -> ModelRegistry:
10171024

10181025
# --- CausalLM (architecture-specific) ---
10191026
"falcon": "tiiuae/falcon-7b",
1027+
"falcon_h1": "tiiuae/Falcon-H1-Tiny-90M-Base",
10201028
"bloom": "bigscience/bloom-560m",
10211029
"gemma": "google/gemma-2b",
10221030
"gemma2": "google/gemma-2-2b",
@@ -1084,6 +1092,10 @@ def _create_default_registry() -> ModelRegistry:
10841092
"glm4_moe": "zai-org/GLM-4.5-Air",
10851093
"granitemoehybrid": "ibm-granite/granite-4.0-tiny-preview",
10861094
"granitemoeshared": "ibm-research/moe-7b-1b-active-shared-experts",
1095+
"kimi_k3": "yujiepan/kimi-k3-tiny-random",
1096+
"lfm2_moe": "LiquidAI/LFM2-8B-A1B",
1097+
"MiniMaxText01": "MiniMaxAI/MiniMax-Text-01",
1098+
"minimax_text_01": "MiniMaxAI/MiniMax-Text-01",
10871099
"qwen3_omni_moe": "Qwen/Qwen3-Omni-30B-A3B-Instruct",
10881100
"qwen3_vl_moe": "Qwen/Qwen3-VL-30B-A3B-Instruct",
10891101

0 commit comments

Comments
 (0)