Skip to content

Commit b30c522

Browse files
justinchubyCopilot
andauthored
Add exact MiniMax-01 GGUF support (#616)
## Summary - add a dedicated MiniMax configuration and exact hybrid Lightning/full-attention graph matching pinned llama.cpp `8d9af256337d1a501250f9bbf4c0859a654bddd6` - add fail-closed GGUF metadata, schedule, tensor-family, shape, and closure validation with exact float and quantized tensor mapping - preserve quantized projection/expert and embedding roles, tied packed embedding/output storage, FP32 router semantics, and heterogeneous recurrent/KV graph state - add synthetic Transformers parity plus ORT prefill/decode, replay, batch reorder, float/quantized import, CLI, and save/reload coverage - update the GGUF support census and pin the public MiniMax reference revision ## Runtime scope Released ORT GenAI packaging remains deferred to #605 because MiniMax requires heterogeneous KV/recurrent state slots plus bounded rollback snapshots that the current package schema cannot faithfully represent. Graph-call state threading, deterministic replay, and batch reorder are covered here. No small public exact checkpoint exists; the approximately 456B public checkpoint is distributed across 413 shards, so real-checkpoint parity and OGA E2E are not locally feasible. ## Validation - `51 passed, 4 skipped` — focused MiniMax config, graph, GGUF closure/import, synthetic parity, weight alignment, Lightning, CLI/roundtrip, and ORT state tests - `7626 passed, 56 skipped` — broad non-integration suite - initialized `lintrunner -a` — clean - generated GGUF documentation and `git diff --check` — clean - GPT-5.6 Sol medium architecture and GGUF reviews completed; all findings resolved, including quantized/tied embedding execution and stale runtime-deferral text Rebased linearly onto merged #615 (`cc80c77db0e8e176a04e66611423399270bcfa63`). --------- Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]> Copilot-Session: aedc6984-fda0-45fc-bddb-a6317953da96
1 parent cc80c77 commit b30c522

18 files changed

Lines changed: 959 additions & 64 deletions

‎docs/api/build_from_gguf.md‎

Lines changed: 7 additions & 4 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': 88, 'rejected': 2, 'supported': 57}; importable: 55; quantized import: {'rejected': 11, 'supported': 136}; runtime: {'deferred': 144, 'rejected': 2, 'supported': 1} |
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} |
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 |
@@ -428,7 +428,7 @@ before graph construction or durable output.
428428
| `mimo2` | — | none (fails before config extraction) | audited-direct-loader-conditional-union | config=deferred; tensor_map=deferred; graph=deferred; runtime=deferred; quantized_import=supported | MiMo2 requires fused-QKV dense MTP blocks, attention sinks, interleaved sliding KV cache, and three chained heads selected by offsets. Mobius permits one head and cannot preserve that state or FP8 converter transform. |
429429
| `minicpm` | — | none (fails before config extraction) | audited-direct-loader-conditional-union | config=deferred; tensor_map=deferred; graph=deferred; runtime=deferred; quantized_import=supported | MiniCPM requires architecture-specific embedding, residual, and logit scales, Q/K permutation, optional long/short RoPE tensors, and a conditional dense-or-MoE loader. The existing MiniCPM graph does not prove this complete GGUF contract. |
430430
| `minicpm3` | — | none (fails before config extraction) | not claimed | config=deferred; tensor_map=deferred; graph=deferred; runtime=deferred; quantized_import=supported | The pinned MiniCPM3 graph uses MLA Q/KV LoRA projections, separate NoPE/RoPE query and key channels, and embedding, residual, and LM-head scales. The current Mobius MiniCPM graph does not represent that exact topology or its scales. |
431-
| `minimax-01` | — | none (fails before config extraction) | not claimed | config=deferred; tensor_map=deferred; graph=deferred; runtime=deferred; quantized_import=supported | The pinned loader schedule is not periodic and its Lightning Attention decay, scaling, residual multipliers, and recurrent rollback semantics are not represented by the current MiniMax graph. |
431+
| `minimax-01` | — | model=`minimax`; tensor=`minimax` | not claimed | config=supported; tensor_map=supported; graph=supported; runtime=deferred; quantized_import=supported | Graph import is exact, but released ORT GenAI packaging cannot represent the heterogeneous KV/recurrent state slots or bounded rollback snapshots; runtime packaging remains tracked by #605. |
432432
| `minimax-m2` | — | none (fails before config extraction) | audited-direct-loader-conditional-union | config=deferred; tensor_map=deferred; graph=deferred; runtime=deferred; quantized_import=supported | MiniMax-M2 uses full-vector Q/K norms, partial RoPE, and all-layer correction-biased routed experts under metadata-selected gating. Mobius has no exact graph or suffix-safe expert import for that topology. |
433433
| `minimax-m3` | — | none (fails before config extraction) | audited-direct-loader-conditional-union | config=deferred; tensor_map=deferred; graph=deferred; runtime=deferred; quantized_import=supported | MiniMax-M3 adds F32 sparse-indexer tensors and a second index-key cache with position/cell maps, block masks, rollback, and reorder semantics alongside main K/V state. Mobius has no MSA cache task or sparse-index operators; dense fallback would change the model. |
434434
| `mistral3` | — | none (fails before config extraction) | exact-direct-loader-conditional-union | config=deferred; tensor_map=deferred; graph=deferred; runtime=deferred; quantized_import=supported | The pinned Mistral3 loader selects dense or routed-expert text blocks from metadata and applies architecture-specific output temperature scaling. A VLM package additionally requires the deferred Pixtral clip sidecar and exact patch/merge/token contract. The existing Hugging Face Mistral3 graph does not cover that conditional GGUF closure. |
@@ -593,8 +593,11 @@ real-artifact full-logit and stateful-generation parity.
593593
- `static_cache=True` and non-hybrid task dispatch are rejected for these mixed
594594
state ABIs.
595595

596-
`minimax-01` remains deferred before config extraction because its pinned
597-
Lightning schedule and decay/scaling semantics do not match the current graph.
596+
`minimax-01` graph import supports its exact pinned Lightning schedule,
597+
decay/scaling semantics, recurrent state, and mixed full-attention cache.
598+
Runtime packaging remains deferred because the released schema cannot represent
599+
that heterogeneous state ABI or bounded rollback snapshots; this is tracked by
600+
[`onnxruntime/mobius#605`](https://github.com/onnxruntime/mobius/issues/605).
598601
PLaMo2 has a dedicated alternating Mamba1/attention graph and strict GGUF
599602
tensor closure. Its mixed per-layer recurrent/KV runtime package remains
600603
deferred to [`onnxruntime/mobius#605`](https://github.com/onnxruntime/mobius/issues/605).

‎src/mobius/_configs/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@
4747
LongcatFlashConfig,
4848
Mamba2Config,
4949
MambaConfig,
50+
MiniMaxConfig,
5051
MllamaConfig,
5152
MMSConfig,
5253
MoonshineConfig,
@@ -127,6 +128,7 @@
127128
"Mamba2Config",
128129
"MambaConfig",
129130
"MllamaConfig",
131+
"MiniMaxConfig",
130132
"MMSConfig",
131133
"MoonshineConfig",
132134
"MuseGlimmerConfig",

‎src/mobius/_configs/_base.py‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -486,6 +486,16 @@ class ArchitectureConfig(BaseModelConfig):
486486
topk_method: str = "greedy"
487487
first_k_dense_replace: int = 0
488488
n_shared_experts: int | None = None
489+
disable_qmoe: bool = False
490+
491+
# MiniMax-01 hybrid attention and normalized-residual scaling.
492+
lightning_norm_eps: float | None = None
493+
full_attn_alpha_factor: float = 1.0
494+
full_attn_beta_factor: float = 1.0
495+
linear_attn_alpha_factor: float = 1.0
496+
linear_attn_beta_factor: float = 1.0
497+
mlp_alpha_factor: float = 1.0
498+
mlp_beta_factor: float = 1.0
489499

490500
# Multi-head Latent Attention (MLA) config — DeepSeek-V2/V3
491501
q_lora_rank: int | None = None
@@ -1435,6 +1445,64 @@ class CausalLMConfig(ArchitectureConfig):
14351445
"""
14361446

14371447

1448+
@dataclasses.dataclass
1449+
class MiniMaxConfig(CausalLMConfig):
1450+
"""Exact configuration for MiniMax-Text-01 and MiniMax-M1 backbones."""
1451+
1452+
@classmethod
1453+
def from_transformers(cls, config, parent_config=None) -> MiniMaxConfig:
1454+
base = ArchitectureConfig.from_transformers(config, parent_config)
1455+
raw_schedule = getattr(config, "attn_type_list", None)
1456+
if raw_schedule is None:
1457+
raise ValueError("MiniMax-01 config requires an explicit attn_type_list")
1458+
if len(raw_schedule) != base.num_hidden_layers:
1459+
raise ValueError(
1460+
"MiniMax-01 attn_type_list must contain exactly "
1461+
f"{base.num_hidden_layers} entries, got {len(raw_schedule)}"
1462+
)
1463+
if any(value not in (0, 1, False, True) for value in raw_schedule):
1464+
raise ValueError("MiniMax-01 attn_type_list entries must be 0 or 1")
1465+
if not bool(getattr(config, "postnorm", True)):
1466+
raise ValueError("MiniMax-01 requires postnorm=true")
1467+
if int(getattr(config, "shared_intermediate_size", 0) or 0):
1468+
raise ValueError(
1469+
"MiniMax-01 shared experts are not supported by the pinned GGUF architecture"
1470+
)
1471+
1472+
beta_names = (
1473+
"layernorm_full_attention_beta",
1474+
"layernorm_linear_attention_beta",
1475+
"layernorm_mlp_beta",
1476+
)
1477+
betas = {name: float(getattr(config, name, 1.0)) for name in beta_names}
1478+
if any(not math.isclose(value, 1.0) for value in betas.values()):
1479+
raise ValueError(f"MiniMax-01 beta residual factors must all equal 1.0: {betas}")
1480+
1481+
fields = _shallow_fields(base)
1482+
fields.update(
1483+
model_type="minimax",
1484+
layer_types=[
1485+
"full_attention" if int(value) == 1 else "lightning_attention"
1486+
for value in raw_schedule
1487+
],
1488+
hidden_act="silu",
1489+
norm_topk_prob=True,
1490+
disable_qmoe=True,
1491+
lightning_norm_eps=float(getattr(config, "lightning_norm_eps", 1e-6)),
1492+
full_attn_alpha_factor=float(
1493+
getattr(config, "layernorm_full_attention_alpha", 1.0)
1494+
),
1495+
full_attn_beta_factor=betas["layernorm_full_attention_beta"],
1496+
linear_attn_alpha_factor=float(
1497+
getattr(config, "layernorm_linear_attention_alpha", 1.0)
1498+
),
1499+
linear_attn_beta_factor=betas["layernorm_linear_attention_beta"],
1500+
mlp_alpha_factor=float(getattr(config, "layernorm_mlp_alpha", 1.0)),
1501+
mlp_beta_factor=betas["layernorm_mlp_beta"],
1502+
)
1503+
return cls(**fields)
1504+
1505+
14381506
@dataclasses.dataclass
14391507
class EncoderConfig(ArchitectureConfig):
14401508
"""Configuration for encoder-only models (BERT, ViT, etc.)."""

‎src/mobius/_configs/_base_test.py‎

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,48 @@
77

88
import types
99

10-
from mobius._configs import ArchitectureConfig, NemotronParseConfig
10+
import pytest
11+
12+
from mobius._configs import ArchitectureConfig, MiniMaxConfig, NemotronParseConfig
13+
14+
15+
def test_minimax_config_extracts_exact_schedule_head_geometry_and_residuals():
16+
config = types.SimpleNamespace(
17+
model_type="MiniMaxText01",
18+
hidden_size=48,
19+
intermediate_size=32,
20+
num_hidden_layers=2,
21+
num_attention_heads=4,
22+
num_key_value_heads=2,
23+
head_dim=16,
24+
rotary_dim=8,
25+
rope_theta=10_000_000.0,
26+
vocab_size=64,
27+
attn_type_list=[0, 1],
28+
num_local_experts=2,
29+
num_experts_per_tok=1,
30+
rms_norm_eps=1e-5,
31+
postnorm=True,
32+
shared_intermediate_size=0,
33+
layernorm_full_attention_alpha=3.5,
34+
layernorm_full_attention_beta=1.0,
35+
layernorm_linear_attention_alpha=3.5,
36+
layernorm_linear_attention_beta=1.0,
37+
layernorm_mlp_alpha=3.5,
38+
layernorm_mlp_beta=1.0,
39+
)
40+
41+
extracted = MiniMaxConfig.from_transformers(config)
42+
43+
assert extracted.model_type == "minimax"
44+
assert extracted.head_dim == 16
45+
assert extracted.partial_rotary_factor == pytest.approx(0.5)
46+
assert extracted.layer_types == ["lightning_attention", "full_attention"]
47+
assert extracted.lightning_norm_eps == pytest.approx(1e-6)
48+
assert extracted.full_attn_alpha_factor == pytest.approx(3.5)
49+
assert extracted.linear_attn_alpha_factor == pytest.approx(3.5)
50+
assert extracted.mlp_alpha_factor == pytest.approx(3.5)
51+
assert extracted.disable_qmoe
1152

1253

1354
def test_nemotron_parse_maps_raw_mbart_decoder_attention_heads():

‎src/mobius/_registry.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
Lfm2Config,
3333
Lfm2MoeConfig,
3434
Lfm2VlConfig,
35+
MiniMaxConfig,
3536
MMSConfig,
3637
MoonshineConfig,
3738
MuseGlimmerConfig,
@@ -602,7 +603,9 @@ def _detect_fallback_registration(hf_config) -> ModelRegistration | None:
602603
"granitemoeshared": ModelRegistration(GraniteMoECausalLMModel),
603604
"hunyuan_v1_moe": ModelRegistration(HunYuanMoEV1CausalLMModel),
604605
"jetmoe": ModelRegistration(JetMoeCausalLMModel),
605-
"minimax": ModelRegistration(MiniMaxCausalLMModel),
606+
"minimax": ModelRegistration(MiniMaxCausalLMModel, config_class=MiniMaxConfig),
607+
"MiniMaxText01": ModelRegistration(MiniMaxCausalLMModel, config_class=MiniMaxConfig),
608+
"minimax_text_01": ModelRegistration(MiniMaxCausalLMModel, config_class=MiniMaxConfig),
606609
"mixtral": ModelRegistration(MoECausalLMModel),
607610
"olmoe": ModelRegistration(MoECausalLMModel),
608611
"phimoe": ModelRegistration(Phi3MoECausalLMModel),

‎src/mobius/components/_lightning_attention.py‎

Lines changed: 43 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -59,31 +59,38 @@ class LightningAttention(nn.Module):
5959
layer_idx: Zero-based layer index, used to compute slope_rate.
6060
"""
6161

62-
def __init__(self, config: ArchitectureConfig, layer_idx: int):
62+
def __init__(
63+
self,
64+
config: ArchitectureConfig,
65+
layer_idx: int,
66+
linear_class: type | None = None,
67+
):
6368
super().__init__()
69+
linear_class = linear_class or Linear
6470
self.num_heads = config.num_attention_heads
65-
self.head_dim = config.hidden_size // config.num_attention_heads
71+
self.head_dim = config.head_dim
6672
self.hidden_size = config.hidden_size
6773
self._dtype = config.dtype
6874

6975
# Fused QKV projection — SiLU applied to all 3*H*d_k before split
70-
self.qkv_proj = Linear(
76+
self.qkv_proj = linear_class(
7177
config.hidden_size,
7278
self.num_heads * self.head_dim * 3,
7379
bias=False,
7480
)
75-
self.out_proj = Linear(
81+
self.o_proj = linear_class(
7682
self.num_heads * self.head_dim,
7783
config.hidden_size,
7884
bias=False,
7985
)
8086
# output_gate: sigmoid gate applied to the normalized attention output
81-
self.output_gate = Linear(
87+
self.output_gate = linear_class(
8288
config.hidden_size,
8389
self.num_heads * self.head_dim,
8490
bias=False,
8591
)
86-
self.norm = RMSNorm(self.num_heads * self.head_dim, eps=config.rms_norm_eps)
92+
norm_eps = config.lightning_norm_eps or config.rms_norm_eps
93+
self.norm = RMSNorm(self.num_heads * self.head_dim, eps=norm_eps)
8794

8895
# Per-head log-space decay values (negative, so exp < 1)
8996
# HF: slope_rate[h] = base^(h+1) * factor
@@ -97,6 +104,7 @@ def forward(
97104
op: OpBuilder,
98105
hidden_states: ir.Value,
99106
recurrent_state: ir.Value,
107+
attention_mask: ir.Value | None = None,
100108
):
101109
"""Lightning Attention forward.
102110
@@ -117,14 +125,28 @@ def forward(
117125
qkv = self.qkv_proj(op, hidden_states)
118126
qkv = op.Swish(qkv)
119127

120-
# Split into Q, K, V: each (B, T, num_heads * head_dim)
121-
head_total = self.num_heads * self.head_dim
128+
# MiniMax stores Q/K/V adjacent within each head:
129+
# (B, T, H * 3D) -> (B, T, H, 3D) -> three (B, T, H, D) tensors.
130+
qkv = op.Reshape(qkv, [0, 0, self.num_heads, 3 * self.head_dim])
122131
query, key, value = op.Split(
123132
qkv,
124-
op.Constant(value_ints=[head_total, head_total, head_total]),
133+
op.Constant(value_ints=[self.head_dim, self.head_dim, self.head_dim]),
125134
axis=-1,
126135
_outputs=3,
127136
)
137+
query = op.Reshape(query, [0, 0, -1])
138+
key = op.Reshape(key, [0, 0, -1])
139+
value = op.Reshape(value, [0, 0, -1])
140+
if attention_mask is not None:
141+
# Only newly processed tokens contribute to the recurrent state.
142+
current_mask = op.Slice(
143+
attention_mask,
144+
op.Neg(seq_dim),
145+
op.Constant(value_ints=[9223372036854775807]),
146+
op.Constant(value_ints=[1]),
147+
)
148+
current_mask = op.Unsqueeze(op.CastLike(current_mask, value), [2])
149+
value = op.Mul(value, current_mask)
128150

129151
# Static decay tensor: (B, T, num_heads) with constant per-head values.
130152
# Each decay[h] = -slope_rate[h] in log-space → exp(decay[h]) < 1.
@@ -144,8 +166,6 @@ def forward(
144166
decay = op.Expand(decay_1, expand_to) # (B, T, num_heads)
145167

146168
# LinearAttention "gated": S_t = exp(g_t) * S_{t-1} + k_t ⊗ v_t
147-
# scale = 1/sqrt(head_dim) for proper scaling
148-
scale = 1.0 / math.sqrt(self.head_dim)
149169
attn_out, new_state = op.LinearAttention(
150170
query,
151171
key,
@@ -155,7 +175,7 @@ def forward(
155175
update_rule="gated",
156176
q_num_heads=self.num_heads,
157177
kv_num_heads=self.num_heads,
158-
scale=scale,
178+
scale=1.0,
159179
_domain=DOMAIN,
160180
_outputs=2,
161181
)
@@ -166,16 +186,22 @@ def forward(
166186
gate = op.Sigmoid(self.output_gate(op, hidden_states))
167187
attn_out = op.Mul(gate, attn_out)
168188

169-
output = self.out_proj(op, attn_out)
189+
output = self.o_proj(op, attn_out)
170190
return output, new_state
171191

172192

173193
def _compute_decay_log(layer_idx: int, num_layers: int, num_heads: int) -> list[float]:
174194
"""Compute per-head log-space decay values for Lightning Attention.
175195
176196
Returns negative values so that exp(decay[h]) = exp(-slope_rate[h]) < 1.
177-
Matches HF ``MiniMaxLightningAttention.get_slope_rate()``.
197+
Matches the pinned llama.cpp MiniMax-01 slope calculation.
178198
"""
179-
base = 1.0 / (2.0 ** (8.0 / num_heads))
180-
factor = 1.0 - layer_idx / (num_layers - 1.0 + 1e-5) + 1e-5
181-
return [-(base ** (h + 1)) * factor for h in range(num_heads)]
199+
if num_layers <= 1:
200+
raise ValueError("MiniMax Lightning Attention requires at least two layers")
201+
202+
if num_heads <= 0:
203+
raise ValueError("MiniMax Lightning Attention requires at least one head")
204+
start = 2.0 ** (-(2.0 ** -(math.log2(num_heads) - 3.0)))
205+
slopes = [start ** (head + 1) for head in range(num_heads)]
206+
factor = 1.0 - layer_idx / (num_layers - 1.0) + 1e-5
207+
return [-slope * factor for slope in slopes]
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# Copyright (c) Microsoft Corporation.
2+
# Licensed under the MIT License.
3+
4+
from __future__ import annotations
5+
6+
import math
7+
8+
import pytest
9+
10+
from mobius.components._lightning_attention import _compute_decay_log
11+
12+
13+
def test_minimax_decay_matches_pinned_64_head_formula():
14+
actual = _compute_decay_log(layer_idx=7, num_layers=80, num_heads=64)
15+
factor = 1.0 - 7.0 / 79.0 + 1e-5
16+
expected = [-(2.0 ** (-(head + 1) / 8.0)) * factor for head in range(64)]
17+
18+
assert actual == pytest.approx(expected)
19+
20+
21+
def test_minimax_decay_supports_non_power_of_two_head_counts():
22+
actual = _compute_decay_log(layer_idx=0, num_layers=2, num_heads=6)
23+
start = 2.0 ** (-(2.0 ** -(math.log2(6) - 3.0)))
24+
expected = [-(start ** (head + 1)) * 1.00001 for head in range(6)]
25+
26+
assert actual == pytest.approx(expected)

‎src/mobius/components/_moe.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -429,7 +429,11 @@ def __init__(
429429
assert config.num_experts_per_tok is not None
430430
self.num_experts = config.num_local_experts
431431
self.top_k = config.num_experts_per_tok
432-
self._qmoe_quantization = _supported_qmoe_quantization(config.quantization)
432+
self._qmoe_quantization = (
433+
None
434+
if getattr(config, "disable_qmoe", False)
435+
else _supported_qmoe_quantization(config.quantization)
436+
)
433437
# Clipped-SwiGLU attributes (QMoE's ``activation_alpha``/``activation_beta``/
434438
# ``swiglu_limit``). Left ``None`` by default so existing callers get a
435439
# byte-identical QMoE call (the attributes are simply omitted, even though

0 commit comments

Comments
 (0)