Skip to content

Commit fada98a

Browse files
justinchubyCopilot
andauthored
Add dedicated LFM2MoE GGUF graph support (#606)
## Summary - add a dedicated LFM2MoE model graph with dense-prefix SwiGLU and correction-biased sigmoid-routed experts - reuse LFM2 mixed short-convolution/KV-cache state ABI with exact pinned layer scheduling and tensor closure - add pinned GGUF config extraction, float and explicit-dequantized Q4 import, state rollback/reorder, save/load, weight-alignment, and synthetic parity coverage - advance config/tensor-map/graph verdicts while keeping runtime DEFERRED pending independent real-checkpoint evidence ## Validation - 1,558 GGUF integration/unit tests passed - 22 targeted model/CLI tests passed (1 unrelated selection skipped) - changed-file lintrunner passed - two independent reviews completed; all findings fixed; final review found no issues The repository-wide non-integration run completed 3,345 passing tests with three unrelated existing failures: `granitemoehybrid` synthetic parity and two `glm_moe_dsa` shape-inference checks. No GitHub CI wait requested. --------- Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]>
1 parent ab11232 commit fada98a

17 files changed

Lines changed: 803 additions & 49 deletions

‎docs/api/build_from_gguf.md‎

Lines changed: 2 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': 91, 'rejected': 3, 'supported': 53}; importable: 51; quantized import: {'rejected': 11, 'supported': 136}; runtime: {'deferred': 144, 'rejected': 3} |
18+
| Architectures | 147 | graph verdicts: {'deferred': 90, 'rejected': 3, 'supported': 54}; importable: 52; quantized import: {'rejected': 12, 'supported': 135}; runtime: {'deferred': 144, 'rejected': 3} |
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 exact-copy only with a validated embedded `tokenizer.huggingface.json` |
@@ -418,7 +418,7 @@ before graph construction or durable output.
418418
| `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. |
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. |
421-
| `lfm2moe` | — | none (fails before config extraction) | not claimed | config=deferred; tensor_map=deferred; graph=deferred; runtime=deferred; quantized_import=supported | LFM2MoE has an arbitrary per-layer attention/short-convolution schedule plus a dense-to-sigmoid-routed-MoE transition. Recurrent layers use F32 rolling convolution state with copy-on-write sequence reorder and bounded rollback snapshots, while attention layers use KV cache. The dense LFM2 graph and ordinary KV/static-cache tasks do not own that mixed state or the expert correction-bias semantics. |
421+
| `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. |
422422
| `llada` | — | model=`llada`; tensor=`llama` | not claimed | config=supported; tensor_map=supported; graph=supported; runtime=deferred; quantized_import=supported | Config extraction, suffix-exact tensor closure, masked-diffusion task dispatch, and synthetic full-sequence execution are covered, but no pinned real GGUF has passed independent Hugging Face/llama.cpp masked-step logit parity and deterministic multi-step generation parity. Runtime packaging remains deferred until both exist. |
423423
| `llada-moe` | — | model=`llada`; module=`llada_moe`; tensor=`llama`+`diffusion_fused_qkv`+`moe_qk_norm_extras`+`moe_extras` | not claimed | config=supported; tensor_map=supported; graph=supported; runtime=deferred; quantized_import=supported | Config extraction, suffix-exact tensor closure, masked-diffusion task dispatch, and synthetic full-sequence execution are covered, but no pinned real GGUF has passed independent Hugging Face/llama.cpp masked-step logit parity and deterministic multi-step generation parity. Runtime packaging remains deferred until both exist. |
424424
| `llama` | `mistral` | model=`llama`; tensor=`llama` | not claimed | config=supported; tensor_map=supported; graph=supported; runtime=deferred; quantized_import=supported | Config extraction, exact tensor-name closure, and a full synthetic GGUF graph build are covered, but no representative real-weight GGUF has yet passed ORT parity or generation validation. Runtime packaging remains deferred until that evidence exists. |

‎src/mobius/_configs/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
JambaConfig,
4242
JetMoeConfig,
4343
Lfm2Config,
44+
Lfm2MoeConfig,
4445
Lfm2VlConfig,
4546
LongcatFlashConfig,
4647
Mamba2Config,
@@ -117,6 +118,7 @@
117118
"JambaConfig",
118119
"JetMoeConfig",
119120
"Lfm2Config",
121+
"Lfm2MoeConfig",
120122
"Lfm2VlConfig",
121123
"LongcatFlashConfig",
122124
"Mamba2Config",

‎src/mobius/_configs/_base.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1604,6 +1604,23 @@ def from_transformers(cls, config, parent_config=None) -> Lfm2Config:
16041604
)
16051605

16061606

1607+
@dataclasses.dataclass
1608+
class Lfm2MoeConfig(CausalLMConfig):
1609+
"""Configuration for LFM2MoE's dense-prefix and routed-expert feed-forwards."""
1610+
1611+
num_dense_layers: int = 2
1612+
use_expert_bias: bool = True
1613+
1614+
@classmethod
1615+
def from_transformers(cls, config, parent_config=None) -> Lfm2MoeConfig:
1616+
base = ArchitectureConfig.from_transformers(config, parent_config)
1617+
return cls(
1618+
**_shallow_fields(base),
1619+
num_dense_layers=getattr(config, "num_dense_layers", 2),
1620+
use_expert_bias=getattr(config, "use_expert_bias", True),
1621+
)
1622+
1623+
16071624
@dataclasses.dataclass
16081625
class Lfm2VlConfig(Lfm2Config):
16091626
"""Configuration for LiquidAI LFM2-VL (SigLIP2 NaFlex + LFM2 decoder).

‎src/mobius/_registry.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
Gemma4AssistantConfig,
3030
Gemma4Config,
3131
Lfm2Config,
32+
Lfm2MoeConfig,
3233
Lfm2VlConfig,
3334
MMSConfig,
3435
MoonshineConfig,
@@ -80,6 +81,7 @@
8081
InternLM2CausalLMModel,
8182
LayerNormCausalLMModel,
8283
Lfm2CausalLMModel,
84+
Lfm2MoECausalLMModel,
8385
Lfm2VlForConditionalGeneration,
8486
LLaDAModel,
8587
LLaDAMoEModel,
@@ -499,6 +501,7 @@ def _detect_fallback_registration(hf_config) -> ModelRegistration | None:
499501
"internlm2": ModelRegistration(InternLM2CausalLMModel),
500502
"llama4_text": ModelRegistration(Llama4CausalLMModel),
501503
"lfm2": ModelRegistration(Lfm2CausalLMModel, config_class=Lfm2Config),
504+
"lfm2_moe": ModelRegistration(Lfm2MoECausalLMModel, config_class=Lfm2MoeConfig),
502505
"dream": ModelRegistration(DreamModel, task="masked-diffusion"),
503506
"Dream": ModelRegistration(DreamModel, task="masked-diffusion"),
504507
"llada": ModelRegistration(LLaDAModel, task="masked-diffusion"),

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

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -322,14 +322,6 @@
322322
"ordinary attention would change the model."
323323
)
324324

325-
_LFM2MOE_GRAPH_REASON = (
326-
"LFM2MoE has an arbitrary per-layer attention/short-convolution schedule plus a "
327-
"dense-to-sigmoid-routed-MoE transition. Recurrent layers use F32 rolling convolution "
328-
"state with copy-on-write sequence reorder and bounded rollback snapshots, while "
329-
"attention layers use KV cache. The dense LFM2 graph and ordinary KV/static-cache "
330-
"tasks do not own that mixed state or the expert correction-bias semantics."
331-
)
332-
333325
_ENCODER_RUNTIME_VALIDATION_PENDING = (
334326
"Config extraction, exact pinned tensor closure, encoder-only task dispatch, and "
335327
"synthetic ORT execution are covered, but no pinned real GGUF artifact has passed "
@@ -1138,11 +1130,22 @@
11381130
),
11391131
GGUFArchitectureSpec(
11401132
gguf_arch="lfm2moe",
1141-
config=Support.DEFERRED,
1142-
tensor_map=Support.DEFERRED,
1143-
graph=Support.DEFERRED,
1133+
model_type="lfm2_moe",
1134+
tensor_map_recipe=("lfm2", "lfm2_moe_extras"),
1135+
config_postprocessor="lfm2moe",
1136+
required_metadata=(
1137+
"attention.head_count_kv",
1138+
"attention.layer_norm_rms_epsilon",
1139+
"rope.freq_base",
1140+
"shortconv.l_cache",
1141+
"expert_count",
1142+
"expert_used_count",
1143+
"expert_feed_forward_length",
1144+
"expert_gating_func",
1145+
),
11441146
runtime=Support.DEFERRED,
1145-
reason=_LFM2MOE_GRAPH_REASON,
1147+
quantized_import=Support.REJECTED,
1148+
reason=_RECURRENT_RUNTIME_VALIDATION_PENDING + " " + _NO_QUANTIZED_PROJECTION_REASON,
11461149
),
11471150
GGUFArchitectureSpec(
11481151
gguf_arch="minimax-01",

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

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@
5757
#: Number of importable architectures. Pinned so that adding support is a
5858
#: deliberate act that also updates the documented support matrix, and so that
5959
#: accidentally losing an architecture is a failure rather than a silence.
60-
_EXPECTED_SUPPORTED_COUNT = 51
60+
_EXPECTED_SUPPORTED_COUNT = 52
6161
_FINAL_CENSUS_CLOSURE = frozenset(
6262
{
6363
"afmoe",
@@ -268,6 +268,7 @@ def test_every_float_importable_architecture_has_a_quantized_verdict(self) -> No
268268
"granitehybrid",
269269
"internlm2",
270270
"jamba",
271+
"lfm2moe",
271272
"mamba",
272273
"mamba2",
273274
"nemotron_h",
@@ -899,14 +900,12 @@ class TestPinnedRemainingHybridCohort:
899900
"deepseek4",
900901
"kimi-k3",
901902
"kimi-linear",
902-
"lfm2moe",
903903
)
904904
_EXPECTED_TENSOR_COUNTS: ClassVar[dict[str, int]] = {
905905
"bailingmoe3": 41,
906906
"deepseek4": 44,
907907
"kimi-k3": 46,
908908
"kimi-linear": 40,
909-
"lfm2moe": 24,
910909
}
911910

912911
@pytest.mark.parametrize("architecture", _ARCHITECTURES)
@@ -954,7 +953,6 @@ def test_no_unpinned_alias_or_config_mutation_is_reachable(
954953
("deepseek4", ("compressed-cache", "rollback", "ordinary KV")),
955954
("kimi-k3", ("matrix state", "latent MoE", "residual banks")),
956955
("kimi-linear", ("convolution histories", "matrix state", "correction-bias")),
957-
("lfm2moe", ("rolling convolution", "reorder", "rollback")),
958956
],
959957
)
960958
def test_state_and_schedule_mismatch_is_explicit(
@@ -965,6 +963,19 @@ def test_state_and_schedule_mismatch_is_explicit(
965963
for term in state_terms:
966964
assert term in reason
967965

966+
def test_lfm2moe_graph_and_import_advance_but_runtime_stays_deferred(self) -> None:
967+
spec = try_get_arch_spec("lfm2moe")
968+
assert spec is not None
969+
assert spec.model_type == "lfm2_moe"
970+
assert spec.config is Support.SUPPORTED
971+
assert spec.tensor_map is Support.SUPPORTED
972+
assert spec.graph is Support.SUPPORTED
973+
assert spec.runtime is Support.DEFERRED
974+
assert spec.quantized_import is Support.REJECTED
975+
assert spec.reason is not None
976+
assert "representative real-weight GGUF" in spec.reason
977+
assert "keep_quantized=False" in spec.reason
978+
968979
def test_hugging_face_deepseek_v4_registration_remains_valid(self) -> None:
969980
assert "deepseek_v4" in _REGISTRATIONS
970981
assert try_get_arch_spec("deepseek4").model_type is None

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

Lines changed: 60 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -906,7 +906,7 @@ def _raise_for_invalid_hybrid_tensor_contract(gguf_model) -> None:
906906
if architecture in {"jamba", "nemotron_h", "granitehybrid"}:
907907
_raise_for_invalid_mamba_hybrid_tensor_contract(gguf_model)
908908
return
909-
if architecture not in {"lfm2", "qwen35", "qwen35moe", "qwen3next"}:
909+
if architecture not in {"lfm2", "lfm2moe", "qwen35", "qwen35moe", "qwen3next"}:
910910
return
911911

912912
metadata = gguf_model.metadata
@@ -934,7 +934,7 @@ def _raise_for_invalid_hybrid_tensor_contract(gguf_model) -> None:
934934
f"{match.group(1)} (block_count={total_layers})"
935935
)
936936

937-
if architecture == "lfm2":
937+
if architecture in {"lfm2", "lfm2moe"}:
938938
required_global = {"token_embd.weight", "token_embd_norm.weight"}
939939
auxiliary = sorted(
940940
name
@@ -946,13 +946,7 @@ def _raise_for_invalid_hybrid_tensor_contract(gguf_model) -> None:
946946
"lfm2 causal-LM import does not support embedding/ColBERT head "
947947
f"tensor(s): {auxiliary}"
948948
)
949-
common_suffixes = {
950-
"attn_norm.weight",
951-
"ffn_norm.weight",
952-
"ffn_gate.weight",
953-
"ffn_up.weight",
954-
"ffn_down.weight",
955-
}
949+
common_suffixes = {"attn_norm.weight", "ffn_norm.weight"}
956950
full_suffixes = {
957951
"attn_q.weight",
958952
"attn_k.weight",
@@ -1019,6 +1013,30 @@ def _raise_for_invalid_hybrid_tensor_contract(gguf_model) -> None:
10191013
required.update(
10201014
full_suffixes if layer_type == "full_attention" else recurrent_suffixes
10211015
)
1016+
if architecture == "lfm2":
1017+
required.update({"ffn_gate.weight", "ffn_up.weight", "ffn_down.weight"})
1018+
elif architecture == "lfm2moe":
1019+
dense_ffn = {"ffn_gate.weight", "ffn_up.weight", "ffn_down.weight"}
1020+
routed_ffn = {
1021+
"ffn_gate_inp.weight",
1022+
"ffn_gate_exps.weight",
1023+
"ffn_up_exps.weight",
1024+
"ffn_down_exps.weight",
1025+
"exp_probs_b.bias",
1026+
}
1027+
dense_layers = int(metadata.get("lfm2moe.leading_dense_block_count", 0))
1028+
if layer < dense_layers:
1029+
required.update(dense_ffn)
1030+
wrong_ffn = sorted(layer_names & routed_ffn)
1031+
else:
1032+
required.update(routed_ffn)
1033+
wrong_ffn = sorted(layer_names & dense_ffn)
1034+
if wrong_ffn:
1035+
raise ValueError(
1036+
f"lfm2moe layer {layer} contains tensor(s) from the wrong "
1037+
f"{'routed' if layer < dense_layers else 'dense'} FFN family: "
1038+
f"{wrong_ffn}"
1039+
)
10221040

10231041
if architecture in {"qwen35moe", "qwen3next"}:
10241042
fused = "ffn_gate_up_exps.weight" in layer_names
@@ -1062,7 +1080,7 @@ def _raise_for_invalid_hybrid_tensor_contract(gguf_model) -> None:
10621080
required.update(
10631081
{"attn_qkv.weight", "attn_gate.weight"} if modern else {"ssm_in.weight"}
10641082
)
1065-
elif architecture != "lfm2":
1083+
elif architecture not in {"lfm2", "lfm2moe"}:
10661084
required.update({"attn_qkv.weight", "attn_gate.weight"})
10671085

10681086
missing = sorted(required - layer_names)
@@ -2070,6 +2088,7 @@ def build_from_gguf(
20702088
)
20712089
if gguf_arch in {
20722090
"lfm2",
2091+
"lfm2moe",
20732092
"qwen35",
20742093
"qwen35moe",
20752094
"qwen3next",
@@ -2753,28 +2772,42 @@ def _normalize_gguf_weights(
27532772
# Fused stacked gate/up experts [num_experts, 2*out, ...] are split
27542773
# before ordinary stacked-expert unpacking. This handles float weights
27552774
# and packed MatMulNBits companions without dropping either half.
2756-
fused_marker = ".mlp.experts.gate_up_proj."
2757-
if fused_marker in key and value.dim() >= 3:
2775+
fused_marker = next(
2776+
(
2777+
marker
2778+
for marker in (
2779+
".mlp.experts.gate_up_proj.",
2780+
".feed_forward.experts.gate_up_proj.",
2781+
)
2782+
if marker in key
2783+
),
2784+
None,
2785+
)
2786+
if fused_marker is not None and value.dim() >= 3:
27582787
prefix, suffix = key.rsplit(fused_marker, 1)
2788+
container = fused_marker.removesuffix(".gate_up_proj.")
27592789
if value.shape[1] % 2:
27602790
raise ValueError(
27612791
f"Fused expert tensor {key!r} has odd gate/up width {value.shape[1]}"
27622792
)
27632793
gate, up = value.chunk(2, dim=1)
27642794
for i in range(value.shape[0]):
2765-
result[f"{prefix}.mlp.experts.{i}.gate_proj.{suffix}"] = gate[i]
2766-
result[f"{prefix}.mlp.experts.{i}.up_proj.{suffix}"] = up[i]
2795+
result[f"{prefix}{container}.{i}.gate_proj.{suffix}"] = gate[i]
2796+
result[f"{prefix}{container}.{i}.up_proj.{suffix}"] = up[i]
27672797
continue
27682798

27692799
# Stacked expert weights [num_experts, out, ...] → per-expert.
27702800
unpacked = False
27712801
for proj in ("gate_proj", "up_proj", "down_proj"):
2772-
marker = f".mlp.experts.{proj}."
2773-
if marker in key and value.dim() >= 3:
2774-
prefix, suffix = key.rsplit(marker, 1)
2775-
for i in range(value.shape[0]):
2776-
result[f"{prefix}.mlp.experts.{i}.{proj}.{suffix}"] = value[i]
2777-
unpacked = True
2802+
for container in (".mlp.experts", ".feed_forward.experts"):
2803+
marker = f"{container}.{proj}."
2804+
if marker in key and value.dim() >= 3:
2805+
prefix, suffix = key.rsplit(marker, 1)
2806+
for i in range(value.shape[0]):
2807+
result[f"{prefix}{container}.{i}.{proj}.{suffix}"] = value[i]
2808+
unpacked = True
2809+
break
2810+
if unpacked:
27782811
break
27792812
if unpacked:
27802813
continue
@@ -3960,8 +3993,12 @@ def _validate_moe_weight_shape(
39603993
if num_experts is None:
39613994
return
39623995
expert_size = getattr(config, "moe_intermediate_size", None) or config.intermediate_size
3963-
if ".mlp.experts." in name:
3964-
projection = name.rsplit(".mlp.experts.", 1)[1].split(".", 1)[0]
3996+
expert_marker = next(
3997+
(marker for marker in (".mlp.experts.", ".feed_forward.experts.") if marker in name),
3998+
None,
3999+
)
4000+
if expert_marker is not None:
4001+
projection = name.rsplit(expert_marker, 1)[1].split(".", 1)[0]
39654002
if projection not in {"gate_proj", "up_proj", "down_proj"}:
39664003
return
39674004
expected = (
@@ -3973,7 +4010,7 @@ def _validate_moe_weight_shape(
39734010
raise ValueError(
39744011
f"Invalid stacked expert shape for {name}: expected {expected}, got {shape}"
39754012
)
3976-
elif name.endswith(".mlp.gate.weight"):
4013+
elif name.endswith((".mlp.gate.weight", ".feed_forward.gate.weight")):
39774014
expected = (num_experts, config.hidden_size)
39784015
if shape != expected:
39794016
raise ValueError(

0 commit comments

Comments
 (0)