Skip to content

Commit 18b617a

Browse files
justinchubyCopilot
andauthored
Add full Jamba GGUF MoE support (#613)
## Summary - implement exact Jamba mixed attention/Mamba-1 execution with multi-token prefill, decode, heterogeneous KV/conv/recurrent state threading, batch reorder, and snapshot replay - add exact dense/routed-MoE scheduling, float32 full-softmax top-k routing without selected-weight renormalization, no-RoPE attention, fused and stacked expert preprocessing, and tied-head handling - import dense and MoE Jamba GGUFs with strict suffix-aware tensor closure and logical shape validation; preserve compatible attention/dense/expert MatMul quantization while dequantizing Mamba/state-sensitive roles - keep released generic ORT GenAI packaging deferred to #605 because its cache schema cannot represent heterogeneous state slots - update generated support documentation from dense-only to the evidence-backed routed-MoE subset ## Validation - `python -m pytest src/mobius/integrations/gguf/ -q --tb=short` — 2608 passed - `python -m pytest tests/build_graph_test.py tests/synthetic_parity_test.py src/mobius/integrations/gguf/_config_mapping_test.py src/mobius/integrations/gguf/_builder_test.py -k 'jamba' -q --tb=short` — 34 passed - `python -m pytest tests/build_graph_test.py tests/cli_test.py src/ -q -k 'not phi4mm and not apply_weights_unknown and not glm_moe_dsa' --tb=short -n auto` — 7096 passed, 52 skipped - initialized `lintrunner` and formatted/linted all changed Python files - generated GGUF support documentation is current - two independent reviews completed; all high-confidence findings fixed The unfiltered broad suite still has the existing `glm_moe_dsa` symbolic-shape inference/checker failure (2 tests), reproduced independently and unrelated to these Jamba paths. ## Upstream evidence Audited llama.cpp at `8d9af256337d1a501250f9bbf4c0859a654bddd6` and current Transformers Jamba. `ai21labs/Jamba-tiny-dev` at `ed303361004ac875426a61675edecf8e9d976882` is the smallest suitable public real-weight follow-up candidate (~637 MB), but this PR makes no real-checkpoint or runtime-generation support claim without that separate evidence. Stacked on #612 (`justinchuby-plamo2-gguf`). --------- Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]>
1 parent 773c965 commit 18b617a

15 files changed

Lines changed: 1042 additions & 83 deletions

‎docs/api/build_from_gguf.md‎

Lines changed: 14 additions & 7 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': 3, 'supported': 56}; importable: 54; quantized import: {'rejected': 12, 'supported': 135}; runtime: {'deferred': 144, 'rejected': 3} |
18+
| Architectures | 147 | graph verdicts: {'deferred': 88, 'rejected': 3, 'supported': 56}; importable: 54; quantized import: {'rejected': 11, 'supported': 136}; 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` |
@@ -411,7 +411,7 @@ before graph construction or durable output.
411411
| `internlm2` | — | model=`internlm2`; tensor=`llama` | not claimed | config=supported; tensor_map=supported; graph=supported; runtime=deferred; quantized_import=rejected | 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. 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. |
412412
| `jais` | — | none (fails before config extraction) | audited-direct-loader-conditional-union | config=deferred; tensor_map=deferred; graph=deferred; runtime=deferred; quantized_import=supported | JAIS combines fused biased QKV, causal ALiBi, 1/head_dim attention scaling, parallel SwiGLU, and converter-baked MuP embedding/output scales. Reusing Falcon or Llama would lose required value transforms. |
413413
| `jais2` | — | none (fails before config extraction) | audited-direct-loader-conditional-union | config=deferred; tensor_map=deferred; graph=deferred; runtime=deferred; quantized_import=supported | JAIS2 is a distinct RoPE, bias-bearing LayerNorm decoder with split Q/K/V and a non-gated ReLU-squared FFN. It is not the ALiBi/SwiGLU JAIS graph and has no exact Mobius tensor recipe. |
414-
| `jamba` | — | model=`jamba`; tensor=`jamba` | 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. |
414+
| `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. |
417417
| `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. |
@@ -559,19 +559,26 @@ independent full-logit and generation parity.
559559
### Second hybrid cohort
560560

561561
`jamba`, `nemotron_h`, and `granitehybrid` have graph-import support for exact
562-
dense subsets only; runtime packaging remains deferred pending independent
562+
pinned subsets. Jamba includes routed MoE layers; Nemotron-H and GraniteHybrid
563+
remain dense-only. Runtime packaging remains deferred pending independent
563564
real-artifact full-logit and stateful-generation parity.
564565

565566
- Schedules come from suffix-exact per-layer metadata. Jamba and GraniteHybrid
566567
use `attention.head_count_kv` (`0` selects Mamba/Mamba2). Nemotron-H combines
567568
that array with per-layer `feed_forward_length` to select exactly one of
568569
Mamba2, attention, or dense ReLU² MLP.
569-
- Jamba requires `ssm.inner_size == 2 * embedding_length`. Nemotron-H rejects
570-
MTP and all MoE files. GraniteHybrid rejects routed-MoE files until 3-D expert
571-
fusion, ordering, and quantized preservation have independent value tests.
570+
- Jamba requires `ssm.inner_size == 2 * embedding_length`, SiLU experts,
571+
Mamba-1 with biased depthwise convolution and bias-free projections, and
572+
softmax-first top-k routing without post-top-k renormalization. Routed layers
573+
are inferred exactly from `ffn_gate_inp`; stacked expert tensors are split in
574+
numeric order. There are no shared experts. Nemotron-H rejects MTP and all MoE
575+
files. GraniteHybrid rejects routed-MoE files until 3-D expert fusion,
576+
ordering, and quantized preservation have independent value tests.
572577
- Every layer must provide exactly its pinned loader tensor family. Missing,
573578
wrong-mixer, partial, auxiliary, scale/input-scale, and out-of-range tensors
574-
are rejected before graph construction. GGUF Mamba decay values are inverted
579+
are rejected before graph construction. Compatible attention, dense-FFN, and
580+
expert MatMul weights may remain quantized; Mamba and other state-sensitive
581+
tensors are dequantized. GGUF Mamba decay values are inverted
575582
from `-exp(A_log)`; convolution and grouped Mamba2 tensors are restored to
576583
graph shapes.
577584
- State inputs and outputs are caller-owned. Mamba1 uses conv

‎src/mobius/_configs/_base.py‎

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2592,6 +2592,9 @@ class JambaConfig(ArchitectureConfig):
25922592
attn_layer_offset: int = 4
25932593
expert_layer_period: int = 2
25942594
expert_layer_offset: int = 1
2595+
# GGUF serializes the resolved schedule through tensor presence rather than
2596+
# preserving the source period/offset pair.
2597+
expert_layer_indices: list[int] | None = None
25952598

25962599
@classmethod
25972600
def from_transformers(cls, config, parent_config=None) -> JambaConfig:
@@ -2601,18 +2604,33 @@ def from_transformers(cls, config, parent_config=None) -> JambaConfig:
26012604
n = base.num_hidden_layers
26022605
attn_period = getattr(config, "attn_layer_period", 8)
26032606
attn_offset = getattr(config, "attn_layer_offset", 4)
2607+
expert_period = getattr(config, "expert_layer_period", 2)
2608+
expert_offset = getattr(config, "expert_layer_offset", 1)
2609+
if attn_period <= 0 or not 0 <= attn_offset < attn_period:
2610+
raise ValueError("Jamba attn_layer_offset must be in [0, attn_layer_period)")
2611+
if expert_period <= 0 or not 0 <= expert_offset < expert_period:
2612+
raise ValueError("Jamba expert_layer_offset must be in [0, expert_layer_period)")
26042613
layer_types = []
26052614
for i in range(n):
2606-
if (i - attn_offset) % attn_period == 0:
2615+
if i % attn_period == attn_offset:
26072616
layer_types.append("full_attention")
26082617
else:
26092618
layer_types.append("mamba")
26102619

26112620
num_experts = getattr(config, "num_experts", 16)
26122621
num_experts_per_tok = getattr(config, "num_experts_per_tok", 2)
2622+
dt_rank = getattr(config, "mamba_dt_rank", "auto")
2623+
if dt_rank == "auto":
2624+
dt_rank = math.ceil(base.hidden_size / 16)
26132625

26142626
# Exclude fields we set explicitly below to avoid duplicate keyword args
2615-
_exclude = {"layer_types", "num_local_experts", "num_experts_per_tok"}
2627+
_exclude = {
2628+
"layer_types",
2629+
"num_local_experts",
2630+
"num_experts_per_tok",
2631+
"norm_topk_prob",
2632+
"rope_type",
2633+
}
26162634
base_fields = {k: v for k, v in _shallow_fields(base).items() if k not in _exclude}
26172635
return cls(
26182636
**base_fields,
@@ -2623,13 +2641,16 @@ def from_transformers(cls, config, parent_config=None) -> JambaConfig:
26232641
mamba_d_state=getattr(config, "mamba_d_state", 16),
26242642
mamba_d_conv=getattr(config, "mamba_d_conv", 4),
26252643
mamba_expand=getattr(config, "mamba_expand", 2),
2626-
mamba_dt_rank=getattr(config, "mamba_dt_rank", 256),
2644+
mamba_dt_rank=int(dt_rank),
26272645
mamba_conv_bias=getattr(config, "mamba_conv_bias", True),
26282646
mamba_proj_bias=getattr(config, "mamba_proj_bias", False),
26292647
attn_layer_period=attn_period,
26302648
attn_layer_offset=attn_offset,
2631-
expert_layer_period=getattr(config, "expert_layer_period", 2),
2632-
expert_layer_offset=getattr(config, "expert_layer_offset", 1),
2649+
expert_layer_period=expert_period,
2650+
expert_layer_offset=expert_offset,
2651+
expert_layer_indices=[i for i in range(n) if i % expert_period == expert_offset],
2652+
norm_topk_prob=False,
2653+
rope_type=None,
26332654
)
26342655

26352656

‎src/mobius/components/_ssm.py‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,60 @@ def _project_ssm_params(self, op, x_db):
188188
c_mat = self.c_layernorm(op, c_mat)
189189
return dt_raw, b_mat, c_mat
190190

191+
def _repeat_for_channels(self, op: OpBuilder, value: ir.Value) -> ir.Value:
192+
# Jamba Mamba-1 shares token-dependent B/C across all expanded channels.
193+
value = op.Unsqueeze(value, [2]) # (B, T, 1, d_state)
194+
value = op.Tile(value, [1, 1, self.d_inner, 1])
195+
return op.Reshape(value, [0, 0, self.d_inner * self.d_state])
196+
197+
def forward(
198+
self,
199+
op: OpBuilder,
200+
x: ir.Value,
201+
ssm_state: ir.Value,
202+
padding_mask: ir.Value | None = None,
203+
):
204+
"""Run the complete multi-token Jamba selective scan."""
205+
dt_raw, b_mat, c_mat = self._project_ssm_params(op, self.x_proj(op, x))
206+
dt = op.Softplus(op.Cast(self.dt_proj(op, dt_raw), to=ir.DataType.FLOAT))
207+
del padding_mask
208+
209+
x_f32 = op.Cast(x, to=ir.DataType.FLOAT)
210+
decay = op.Mul(
211+
op.Unsqueeze(dt, [-1]),
212+
op.Unsqueeze(
213+
op.Neg(op.Exp(op.Cast(self.A_log, to=ir.DataType.FLOAT))),
214+
[0, 1],
215+
),
216+
)
217+
decay = op.Reshape(decay, [0, 0, self.d_inner * self.d_state])
218+
value = op.Mul(dt, x_f32)
219+
internal_state = op.Unsqueeze(
220+
op.Cast(ssm_state, to=ir.DataType.FLOAT),
221+
[-1],
222+
)
223+
output, present_state = op.LinearAttention(
224+
self._repeat_for_channels(op, op.Cast(c_mat, to=ir.DataType.FLOAT)),
225+
self._repeat_for_channels(op, op.Cast(b_mat, to=ir.DataType.FLOAT)),
226+
value,
227+
internal_state,
228+
decay,
229+
scale=1.0,
230+
q_num_heads=self.d_inner,
231+
kv_num_heads=self.d_inner,
232+
update_rule="gated",
233+
_domain="com.microsoft",
234+
_outputs=2,
235+
)
236+
output = op.Add(
237+
output,
238+
op.Mul(x_f32, op.Cast(self.D, to=ir.DataType.FLOAT)),
239+
)
240+
return (
241+
op.CastLike(output, x),
242+
op.CastLike(op.Squeeze(present_state, [-1]), ssm_state),
243+
)
244+
191245

192246
class Mamba2Scan(nn.Module):
193247
"""Multi-head selective scan for Mamba2/SSD architecture.

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

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,15 @@
261261
"stateful ORT generation. Runtime packaging remains deferred until that evidence exists."
262262
)
263263

264+
_JAMBA_RUNTIME_VALIDATION_PENDING = (
265+
"Exact mixed attention/Mamba and dense/routed-MoE schedules, strict tensor closure "
266+
"and shapes, GGUF value transforms, compatible projection quantization, value-checked "
267+
"expert ordering, reduced Transformers parity, and multi-token ORT state threading, "
268+
"reorder, and replay are covered. Generic ORT GenAI runtime packaging remains deferred "
269+
"because its released cache schema cannot represent heterogeneous KV, convolution, and "
270+
"recurrent state slots; tracked by #605."
271+
)
272+
264273
_RWKV_GRAPH_REASONS = {
265274
"rwkv6": (
266275
"RWKV6 carries two F32 states per layer (two token-shift vectors and a per-head "
@@ -1063,8 +1072,7 @@
10631072
"ssm.time_step_rank",
10641073
),
10651074
runtime=Support.DEFERRED,
1066-
quantized_import=Support.REJECTED,
1067-
reason=_RECURRENT_RUNTIME_VALIDATION_PENDING + " " + _NO_QUANTIZED_PROJECTION_REASON,
1075+
reason=_JAMBA_RUNTIME_VALIDATION_PENDING,
10681076
),
10691077
GGUFArchitectureSpec(
10701078
gguf_arch="nemotron_h",

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,7 @@
162162
"gpt2",
163163
"granitemoe",
164164
"hunyuan-dense",
165+
"jamba",
165166
"lfm2",
166167
"llada",
167168
"llada-moe",
@@ -270,7 +271,6 @@ def test_every_float_importable_architecture_has_a_quantized_verdict(self) -> No
270271
"chatglm",
271272
"granitehybrid",
272273
"internlm2",
273-
"jamba",
274274
"lfm2moe",
275275
"mamba",
276276
"mamba2",

0 commit comments

Comments
 (0)