Skip to content

Commit 8690dcd

Browse files
justinchubyCopilot
andcommitted
Add GraniteHybrid routed-MoE GGUF support
Import mixed Mamba2/attention GraniteHybrid GGUFs with exact routed and shared expert geometry, strict tensor closure, and fail-closed quantized preservation. Add end-to-end state, parity, persistence, CLI, and malformed-source coverage, and update the GGUF support census. Co-authored-by: Copilot App <[email protected]> Signed-off-by: Justin Chu <[email protected]>
1 parent 356fcdb commit 8690dcd

12 files changed

Lines changed: 822 additions & 68 deletions

‎docs/api/build_from_gguf.md‎

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -396,7 +396,7 @@ before graph construction or durable output.
396396
| `gptneox` | — | none (fails before config extraction) | audited-direct-loader-conditional-union | config=deferred; tensor_map=deferred; graph=deferred; runtime=deferred; quantized_import=supported | GPT-NeoX GGUF requires fused biased QKV, bias-bearing LayerNorm/GELU blocks, partial RoPE, and metadata-selected parallel versus sequential residual topology. Mobius implements only the parallel MHA subset and cannot admit the full loader union. |
397397
| `granite` | — | none (fails before config extraction) | audited-direct-loader-conditional-union | config=deferred; tensor_map=deferred; graph=deferred; runtime=deferred; quantized_import=supported | The granite architecture is a conditional dense-or-MoE union with residual, embedding, attention, and inverse-logit scales, optional biases/RoPE factors, shared experts, and optional deep-stack inputs. It is not the GraniteMoE or GraniteHybrid GGUF contract. |
398398
| `granite_swa` | — | none (fails before config extraction) | audited-direct-loader-conditional-union | config=deferred; tensor_map=deferred; graph=deferred; runtime=deferred; quantized_import=supported | Granite SWA requires attention sinks, a complete interleaved sliding-window schedule, residual/logit scaling, fused routed gate-up experts, and optional fused shared experts/deep-stack injection. Mobius owns neither that cache ABI nor its fused expert sidecars. |
399-
| `granitehybrid` | — | model=`granitemoehybrid`; tensor=`granitehybrid` | 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. |
399+
| `granitehybrid` | — | model=`granitemoehybrid`; tensor=`granitehybrid` | not claimed | config=supported; tensor_map=supported; graph=supported; runtime=deferred; quantized_import=rejected | Exact mixed attention/Mamba2 scheduling, architecture-wide dense or routed MoE feed-forward selection, optional shared experts, Granite scaling, value-preserving float expert fusion, and strict pinned tensor closure are supported. Quantized sources require explicit dequantization because the current graph has no exact packed 3-D expert ABI; use keep_quantized=False. Generic ORT GenAI runtime packaging remains deferred because its released cache schema cannot represent heterogeneous KV, convolution, and recurrent state slots; tracked by onnxruntime/mobius#605. |
400400
| `granitemoe` | — | model=`granitemoe`; tensor=`llama`+`moe_extras` | 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. |
401401
| `graniteswitch` | — | none (fails before config extraction) | audited-direct-loader-conditional-union | config=deferred; tensor_map=deferred; graph=deferred; runtime=deferred; quantized_import=supported | GraniteSwitch repurposes an appended synthetic layer as a token-history-driven adapter router and carries fourteen switched-LoRA tensors per block in addition to decoder KV state. It is not MTP, and Mobius has no switched-LoRA graph, MUL_MAT_ID quantization contract, or package ABI. |
402402
| `grok` | — | none (fails before config extraction) | not claimed | config=deferred; tensor_map=deferred; graph=deferred; runtime=deferred; quantized_import=supported | The pinned Grok graph applies embedding, attention-output, and logit scales; attention, and optional final-logit softcaps; post-attention and post-FFN norms; and a dense-plus-routed expert residual scaled by sqrt(2)/2. Mobius's generic MoE graph has none of that combined topology, so the Hugging Face-style expert names are not evidence that a GGUF alias is safe. |
@@ -556,8 +556,9 @@ independent full-logit and generation parity.
556556
### Second hybrid cohort
557557

558558
`jamba`, `nemotron_h`, and `granitehybrid` have graph-import support for exact
559-
pinned subsets. Jamba includes routed MoE layers; Nemotron-H and GraniteHybrid
560-
remain dense-only. Runtime packaging remains deferred pending independent
559+
pinned subsets. All three include their routed-MoE forms; GraniteHybrid selects
560+
dense or routed feed-forward globally and may add one always-active shared
561+
expert on every layer. Runtime packaging remains deferred pending independent
561562
real-artifact full-logit and stateful-generation parity.
562563

563564
- Schedules come from suffix-exact per-layer metadata. Jamba and GraniteHybrid
@@ -568,14 +569,19 @@ real-artifact full-logit and stateful-generation parity.
568569
Mamba-1 with biased depthwise convolution and bias-free projections, and
569570
softmax-first top-k routing without post-top-k renormalization. Routed layers
570571
are inferred exactly from `ffn_gate_inp`; stacked expert tensors are split in
571-
numeric order. There are no shared experts. Nemotron-H rejects MTP and all MoE
572-
files. GraniteHybrid rejects routed-MoE files until 3-D expert fusion,
573-
ordering, and quantized preservation have independent value tests.
572+
numeric order. There are no shared experts. Nemotron-H supports its exact
573+
mixed dense/MoE schedule, correction-biased sigmoid routing, shared expert,
574+
and optional latent projections while rejecting unsupported MTP blocks.
575+
GraniteHybrid uses normalized softmax top-k routing on every layer, fuses
576+
separate GGUF expert gate/up tensors in gate-then-up order, and adds the
577+
optional shared SwiGLU branch.
574578
- Every layer must provide exactly its pinned loader tensor family. Missing,
575579
wrong-mixer, partial, auxiliary, scale/input-scale, and out-of-range tensors
576580
are rejected before graph construction. Compatible attention, dense-FFN, and
577-
expert MatMul weights may remain quantized; Mamba and other state-sensitive
578-
tensors are dequantized. GGUF Mamba decay values are inverted
581+
expert MatMul weights may remain quantized where the graph owns an exact
582+
packed ABI. GraniteHybrid and Nemotron-H quantized sources require explicit
583+
dequantization; neither silently drops or rewrites packed expert semantics.
584+
GGUF Mamba decay values are inverted
579585
from `-exp(A_log)`; convolution and grouped Mamba2 tensors are restored to
580586
graph shapes.
581587
- State inputs and outputs are caller-owned. Mamba1 uses conv

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

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1135,7 +1135,16 @@
11351135
),
11361136
runtime=Support.DEFERRED,
11371137
quantized_import=Support.REJECTED,
1138-
reason=_RECURRENT_RUNTIME_VALIDATION_PENDING + " " + _NO_QUANTIZED_PROJECTION_REASON,
1138+
reason=(
1139+
"Exact mixed attention/Mamba2 scheduling, architecture-wide dense or routed "
1140+
"MoE feed-forward selection, optional shared experts, Granite scaling, "
1141+
"value-preserving float expert fusion, and strict pinned tensor closure are "
1142+
"supported. Quantized sources require explicit dequantization because the "
1143+
"current graph has no exact packed 3-D expert ABI; use keep_quantized=False. "
1144+
"Generic ORT GenAI runtime packaging remains deferred because its released cache "
1145+
"schema cannot represent heterogeneous KV, convolution, and recurrent state "
1146+
"slots; tracked by onnxruntime/mobius#605."
1147+
),
11391148
),
11401149
GGUFArchitectureSpec(
11411150
gguf_arch="bailingmoe3",

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

Lines changed: 195 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1796,13 +1796,30 @@ def _raise_for_invalid_mamba_hybrid_tensor_contract(gguf_model) -> None:
17961796
},
17971797
}
17981798
else:
1799-
common = {
1800-
"attn_norm.weight",
1801-
"ffn_norm.weight",
1802-
"ffn_gate.weight",
1803-
"ffn_up.weight",
1804-
"ffn_down.weight",
1799+
common = {"attn_norm.weight", "ffn_norm.weight"}
1800+
num_experts = int(metadata.get("granitehybrid.expert_count", 0))
1801+
top_k = int(metadata.get("granitehybrid.expert_used_count", 0))
1802+
if bool(num_experts) != bool(top_k):
1803+
raise ValueError(
1804+
"GraniteHybrid expert_count and expert_used_count must both be zero "
1805+
"or both positive"
1806+
)
1807+
dense_ffn = {"ffn_gate.weight", "ffn_up.weight", "ffn_down.weight"}
1808+
routed_ffn = {
1809+
"ffn_gate_inp.weight",
1810+
"ffn_gate_exps.weight",
1811+
"ffn_up_exps.weight",
1812+
"ffn_down_exps.weight",
1813+
}
1814+
shared_ffn = {
1815+
"ffn_gate_shexp.weight",
1816+
"ffn_up_shexp.weight",
1817+
"ffn_down_shexp.weight",
18051818
}
1819+
shared_width = int(metadata.get("granitehybrid.expert_shared_feed_forward_length", 0))
1820+
common |= routed_ffn if num_experts else dense_ffn
1821+
if num_experts and shared_width > 0:
1822+
common |= shared_ffn
18061823
required_by_type = {
18071824
"mamba2": {
18081825
"ssm_in.weight",
@@ -1830,6 +1847,18 @@ def _raise_for_invalid_mamba_hybrid_tensor_contract(gguf_model) -> None:
18301847
"rope_freqs.weight",
18311848
},
18321849
}
1850+
forbidden_ffn = dense_ffn if num_experts else routed_ffn | shared_ffn
1851+
present_forbidden = sorted(
1852+
f"blk.{index}.{suffix}"
1853+
for index in range(layer_count)
1854+
for suffix in forbidden_ffn
1855+
if f"blk.{index}.{suffix}" in actual
1856+
)
1857+
if present_forbidden:
1858+
raise ValueError(
1859+
"GraniteHybrid GGUF mixes dense and routed/shared MoE representations: "
1860+
f"{present_forbidden}"
1861+
)
18331862

18341863
expected = set(required_global)
18351864
allowed = required_global | optional_global
@@ -1855,6 +1884,11 @@ def require_all_or_none(label: str, names: list[str]) -> None:
18551884
"recurrent convolution",
18561885
[f"blk.{index}.ssm_conv1d.bias" for index in recurrent_layers],
18571886
)
1887+
if architecture in {"nemotron_h", "nemotron_h_moe", "granitehybrid"}:
1888+
require_all_or_none(
1889+
"attention output projection",
1890+
[f"blk.{index}.attn_output.bias" for index in attention_layers],
1891+
)
18581892
if architecture == "granitehybrid":
18591893
require_all_or_none(
18601894
"attention Q/K/V projection",
@@ -1864,10 +1898,16 @@ def require_all_or_none(label: str, names: list[str]) -> None:
18641898
for projection in ("q", "k", "v")
18651899
],
18661900
)
1867-
if architecture in {"nemotron_h", "nemotron_h_moe", "granitehybrid"}:
1901+
if architecture == "granitehybrid" and not int(
1902+
metadata.get("granitehybrid.expert_count", 0)
1903+
):
18681904
require_all_or_none(
1869-
"attention output projection",
1870-
[f"blk.{index}.attn_output.bias" for index in attention_layers],
1905+
"dense shared-MLP",
1906+
[
1907+
f"blk.{index}.ffn_{projection}.bias"
1908+
for index in range(layer_count)
1909+
for projection in ("gate", "up", "down")
1910+
],
18711911
)
18721912
if architecture in {"nemotron_h", "nemotron_h_moe"}:
18731913
mlp_layers = [
@@ -1949,9 +1989,7 @@ def require_all_or_none(label: str, names: list[str]) -> None:
19491989
f"unexpected={unexpected}, out_of_range={out_of_range}"
19501990
)
19511991

1952-
if architecture not in {"jamba", "nemotron_h", "nemotron_h_moe"} or not hasattr(
1953-
gguf_model, "tensor_items_raw"
1954-
):
1992+
if not hasattr(gguf_model, "tensor_items_raw"):
19551993
return
19561994

19571995
shapes = {
@@ -1961,6 +1999,9 @@ def require_all_or_none(label: str, names: list[str]) -> None:
19611999
if architecture in {"nemotron_h", "nemotron_h_moe"}:
19622000
_validate_nemotron_h_tensor_shapes(gguf_model, layer_types, actual)
19632001
return
2002+
if architecture == "granitehybrid":
2003+
_validate_granitehybrid_tensor_shapes(gguf_model, layer_types, actual)
2004+
return
19642005

19652006
hidden = int(metadata["jamba.embedding_length"])
19662007
intermediate = int(metadata["jamba.feed_forward_length"])
@@ -2198,6 +2239,148 @@ def _validate_nemotron_h_tensor_shapes(gguf_model, layer_types, actual: set[str]
21982239
raise ValueError(f"Invalid Nemotron-H GGUF tensor shape(s): {malformed}")
21992240

22002241

2242+
def _validate_granitehybrid_tensor_shapes(gguf_model, layer_types, actual: set[str]) -> None:
2243+
"""Validate logical GraniteHybrid tensor shapes before graph construction."""
2244+
metadata = gguf_model.metadata
2245+
arch = gguf_model.architecture
2246+
shapes = {
2247+
name: tuple(int(dimension) for dimension in shape)
2248+
for name, _raw, _qtype, shape in gguf_model.tensor_items_raw()
2249+
}
2250+
hidden = int(metadata[f"{arch}.embedding_length"])
2251+
vocab = int(metadata.get(f"{arch}.vocab_size", 0))
2252+
if not vocab:
2253+
vocab = len(metadata.get("tokenizer.ggml.tokens", ()))
2254+
heads_raw = metadata[f"{arch}.attention.head_count"]
2255+
heads_by_layer = (
2256+
[int(value) for value in heads_raw]
2257+
if isinstance(heads_raw, (list, tuple, np.ndarray))
2258+
else [int(heads_raw)] * len(layer_types)
2259+
)
2260+
kv_by_layer = [int(value) for value in metadata[f"{arch}.attention.head_count_kv"]]
2261+
attention_heads = next(
2262+
(
2263+
heads_by_layer[index]
2264+
for index, kind in enumerate(layer_types)
2265+
if kind == "full_attention"
2266+
),
2267+
0,
2268+
)
2269+
head_dim = int(
2270+
metadata.get(
2271+
f"{arch}.attention.key_length",
2272+
hidden // attention_heads if attention_heads else 0,
2273+
)
2274+
)
2275+
state = int(metadata[f"{arch}.ssm.state_size"])
2276+
inner = int(metadata[f"{arch}.ssm.inner_size"])
2277+
groups = int(metadata[f"{arch}.ssm.group_count"])
2278+
ssm_heads = int(metadata[f"{arch}.ssm.time_step_rank"])
2279+
conv = int(metadata[f"{arch}.ssm.conv_kernel"])
2280+
expert_count = int(metadata.get(f"{arch}.expert_count", 0))
2281+
expert_width = int(metadata[f"{arch}.feed_forward_length"])
2282+
shared_width = int(metadata.get(f"{arch}.expert_shared_feed_forward_length", 0))
2283+
2284+
expected: dict[str, tuple[int, ...]] = {
2285+
"token_embd.weight": (vocab, hidden),
2286+
"output_norm.weight": (hidden,),
2287+
}
2288+
if "output.weight" in actual:
2289+
expected["output.weight"] = (vocab, hidden)
2290+
for layer, layer_type in enumerate(layer_types):
2291+
prefix = f"blk.{layer}."
2292+
expected[prefix + "attn_norm.weight"] = (hidden,)
2293+
expected[prefix + "ffn_norm.weight"] = (hidden,)
2294+
if layer_type == "mamba2":
2295+
conv_width = inner + 2 * groups * state
2296+
expected.update(
2297+
{
2298+
prefix + "ssm_in.weight": (
2299+
2 * inner + 2 * groups * state + ssm_heads,
2300+
hidden,
2301+
),
2302+
prefix + "ssm_conv1d.weight": (conv_width, conv),
2303+
prefix + "ssm_dt.bias": (ssm_heads,),
2304+
prefix + "ssm_a": (ssm_heads, 1),
2305+
prefix + "ssm_d": (ssm_heads, 1),
2306+
prefix + "ssm_norm.weight": (groups, inner // groups),
2307+
prefix + "ssm_out.weight": (hidden, inner),
2308+
}
2309+
)
2310+
if prefix + "ssm_conv1d.bias" in actual:
2311+
expected[prefix + "ssm_conv1d.bias"] = (conv_width,)
2312+
else:
2313+
heads = heads_by_layer[layer]
2314+
kv_heads = kv_by_layer[layer]
2315+
expected.update(
2316+
{
2317+
prefix + "attn_q.weight": (heads * head_dim, hidden),
2318+
prefix + "attn_q.bias": (heads * head_dim,),
2319+
prefix + "attn_k.weight": (kv_heads * head_dim, hidden),
2320+
prefix + "attn_k.bias": (kv_heads * head_dim,),
2321+
prefix + "attn_v.weight": (kv_heads * head_dim, hidden),
2322+
prefix + "attn_v.bias": (kv_heads * head_dim,),
2323+
prefix + "attn_output.weight": (hidden, heads * head_dim),
2324+
}
2325+
)
2326+
if prefix + "attn_output.bias" in actual:
2327+
expected[prefix + "attn_output.bias"] = (hidden,)
2328+
2329+
if expert_count:
2330+
expected.update(
2331+
{
2332+
prefix + "ffn_gate_inp.weight": (expert_count, hidden),
2333+
prefix + "ffn_gate_exps.weight": (
2334+
expert_count,
2335+
expert_width,
2336+
hidden,
2337+
),
2338+
prefix + "ffn_up_exps.weight": (
2339+
expert_count,
2340+
expert_width,
2341+
hidden,
2342+
),
2343+
prefix + "ffn_down_exps.weight": (
2344+
expert_count,
2345+
hidden,
2346+
expert_width,
2347+
),
2348+
}
2349+
)
2350+
if shared_width:
2351+
expected.update(
2352+
{
2353+
prefix + "ffn_gate_shexp.weight": (shared_width, hidden),
2354+
prefix + "ffn_up_shexp.weight": (shared_width, hidden),
2355+
prefix + "ffn_down_shexp.weight": (hidden, shared_width),
2356+
}
2357+
)
2358+
else:
2359+
expected.update(
2360+
{
2361+
prefix + "ffn_gate.weight": (expert_width, hidden),
2362+
prefix + "ffn_up.weight": (expert_width, hidden),
2363+
prefix + "ffn_down.weight": (hidden, expert_width),
2364+
}
2365+
)
2366+
for projection, size in (
2367+
("gate", expert_width),
2368+
("up", expert_width),
2369+
("down", hidden),
2370+
):
2371+
name = prefix + f"ffn_{projection}.bias"
2372+
if name in actual:
2373+
expected[name] = (size,)
2374+
2375+
malformed = sorted(
2376+
f"{name}: expected {expected_shape}, got {shapes[name]}"
2377+
for name, expected_shape in expected.items()
2378+
if name in shapes and shapes[name] != expected_shape
2379+
)
2380+
if malformed:
2381+
raise ValueError(f"Invalid GraniteHybrid GGUF tensor shape(s): {malformed}")
2382+
2383+
22012384
def _raise_for_invalid_t5_tensor_contract(gguf_model) -> None:
22022385
"""Validate the pinned T5/T5-encoder tensor closure and logical shapes."""
22032386
from mobius.integrations.gguf._quant_registry import float_storage_type_ids

0 commit comments

Comments
 (0)