Skip to content

feat(xla): add Mamba2 config, mixer schedule and state-threaded graphs - #3370

Merged
inureyes merged 6 commits into
mainfrom
feature/issue-3338-mamba2-state-graphs
Nov 23, 2026
Merged

inureyes merged 6 commits into
mainfrom
feature/issue-3338-mamba2-state-graphs

Conversation

@inureyes

@inureyes inureyes commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Summary

Mamba2 (model_type = "mamba2") now parses into a per-layer mixer schedule, declares its backbone.* weights in lock-step with the emitter, and emits prefill and single-sequence decode graphs that thread recurrent state. Dense and MoE graphs are byte-identical. Epic #564, unit U2; the shim and runtime side is #3339.

  • Config gains ssm, layer_mixers, and state_tensors(), has_kv_cache(), state_layer_index(), layer_has_ffn(). Config::from_json cross-checks every SSM dim against the safetensors headers.
  • emit_transformer_layer runs norm -> mixer -> residual for Mamba2 layers. RoPE tables, masks and KV are skipped when there is no attention layer.
  • emit_decode_batched, the ragged decode and every prefill_embeddings* entry now return Result and refuse recurrent configs with an error naming the model type.
  • The f16 prefill conv is now K shifted f32 multiply-adds, which matches the decode step.

State ABI (for #3339 / #3340)

The ABI is the one in the issue. Prefill takes ssm_h [L,H,P,N] and then ssm_conv [L,K-1,conv_dim] (both f32) after real_len, and returns them after the logits. There are no kcache/vcache results. Decode keeps @ssm_h/@ssm_conv globals seeded by @state_import(%s0, %s1). @main keeps token, pos and cache_len but reads only the token. @kcache, @vcache and @kv_import are absent. Two loader details also apply: an MLX [C,K,1] conv weight is uploaded as [C,1,K] (same bytes), and packed/native quant is disabled for SSM configs.

Changes during review

  • Review (e17b087): tie_word_embeddings now follows the HF Mamba2Config default (false) when config.json omits it, and the cross-check then requires lm_head.weight (MEDIUM: a checkpoint with its own head would silently have used the embeddings). The model check now defaults to the InOut layout that IreeLlama::load uses (--layout inout|outin); numbers are unchanged. A checked multiply in the packed-width test of the cross-check (LOW). The f16 drift was traced inside HF's own forward: rounding only the nn.Linear inputs and weights to f16 reproduces 0.44 max-abs, in_proj alone 0.385; the scan, norm and residual stream are f32 in the graph. Notes for feat(xla): single-seq recurrent state in shim; Mamba2 generates on xla #3339 are posted on that issue.
  • Security review (d9cb7b8): num_hidden_layers is capped at 1024 at parse time in both the Mamba2 and dense parsers, because layer_mixers was allocated from it before any check. Every safetensors header entry must be backed by exactly shape * dtype bytes inside the file (before, a few-KB file could declare any dims and get graphs compiled at them). The per-layer state H*P*N may not exceed the layer's in_proj element count. Shard names go through index_shard_path, moved to shard_path.rs so the emitter builds without iree. The Python check loads safetensors only and reads .npy with allow_pickle=False.
  • Finalize (08ed5b3): CHANGELOG states the final behavior, FINDINGS and README updated, a direct test of the shard-name rule. Reverting the header-span check and the layer cap each makes its test fail.

Test plan

spike/openxla/ssm_model_check.py (with examples/xla_ssm_model_check.rs) compares the last-token logits with HF Mamba2ForCausalLM fp32. It checks three paths: the whole prompt, the prompt split in two state-carrying prefill calls, and token-by-token decode. Tolerance is 3e-2.

  • Synthetic model (2 layers, n_groups 2, biased, untied): max-abs 1.8e-6 on local-task and hip, argmax equal.
  • AntonV/mamba2-130m-hf @ 05e8773f, 200 tokens over two chunks: max-abs 2.0e-4 on local-task and 3.9e-4 on hip, argmax equal. At f16 the drift is 0.45 with the top 5 unchanged; this is recorded but not gated.
  • Prefill and decode compile in 1.6 to 2.6 s on both llvm-cpu and rocm gfx1151, at capacities 256 and 4096 (FINDINGS_ssm.md).
  • cargo test --profile test-fast -p mlxcel-xla --lib (506 passed on the final head), validate_arch.sh --structural-only, cargo fmt --all -- --check, and clippy -D warnings with no features, with iree, and for the example.
  • The feat(xla): SSM scan primitive (conv1d + selective scan) with HF oracle #3337 probe gate (spike/openxla/ssm_gate.sh, 11 cases) re-run on local-task and hip on the merged head after the prefill conv became f32 shifted multiply-adds: SSM GATE: PASS.

Closes #3338

The OpenXLA emitter rejected mamba2 and assumed every layer is attention with a KV cache. Epic #564 needs Mamba2 prefill and decode graphs that thread recurrent state through the ABI #3339 implements in the shim.

- Config: model_type mamba2 parses into SsmConfig plus a per-layer MixerKind schedule; state_tensors() lists ssm_h [L,H,P,N] and ssm_conv [L,K-1,conv_dim] (f32), has_kv_cache() is false for attention-free configs. Bare Infinity and {"__float__": "Infinity"} limits parse. Config::from_json cross-checks every SSM dim against the safetensors headers.
- Weights: WeightScheme::Mamba2 names and weight_specs in take_ssm_layer_weights order; the loader maps MLX [C,K,1] conv weights to [C,1,K].
- Graphs: emit_transformer_layer runs norm -> Mamba2 mixer -> residual for recurrent layers. Prefill takes the state after real_len and returns it after the logits; the decode keeps it in @ssm_h/@ssm_conv globals seeded by @state_import, with no KV cache, RoPE table or @kv_import. Batched, ragged and embeddings-input entries return Err for recurrent configs.
- The f16 prefill conv is now K shifted f32 multiply-adds, matching the decode step.
- spike/openxla/ssm_model_check.py with examples/xla_ssm_model_check.rs checks whole, split and token-by-token decode logits against HF fp32.

Validation: unit gate (498 passed), validate_arch.sh --structural-only, fmt and clippy (no features, iree, example). mamba2-130m max-abs 3.9e-4 and synthetic 1.8e-6 on local-task and hip, argmax equal.

Closes #3338
@inureyes inureyes added status:review Under review type:enhancement New features, capabilities, or significant additions priority:high High priority area:architecture Architecture and code structure changes area:inference Generation, sampling, decoding (incl. speculative, DRY) labels Nov 23, 2026
A Mamba2 config.json that omitted tie_word_embeddings was read as tied, while HF Mamba2Config defaults to false. On a checkpoint that ships lm_head.weight the emitter would silently reuse the embeddings as the head. The reader now follows the HF default, so the head is read from lm_head.weight and the checkpoint cross-check refuses a checkpoint without one.

The cross-check compared an MLX-packed projection width with an unchecked `i * 32` on a header dim. A crafted dim such as 2^59 + 2 wrapped to the expected width and passed; the multiply is now checked.

The SSM model check loaded the checkpoint in the config's OutIn layout, but IreeLlama, the single-sequence runtime #3339 drives, always emits and uploads InOut. The check (Rust runner, example and spike script) now takes `--layout inout|outin`, defaulting to inout, so the oracle covers the layout the runtime uses.

FINDINGS_ssm.md records the f16 analysis: rounding every projection to f16 inside HF's fp32 forward reproduces the 0.44 drift (in_proj alone 0.39), so nothing besides projection rounding contributes. Both config fixes have regression tests in recurrent_tests that fail without them. Refs #3338
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Mamba2 config, per-layer mixer schedule, weight specs, and state-threaded prefill / single-sequence decode graphs that match HF fp32, with dense graphs byte-identical (#3338, epic #564 U2).

Findings Addressed (e17b087)

  • tie_word_embeddings defaulted to true when omitted, while HF Mamba2Config defaults to false; a checkpoint with its own lm_head.weight would silently get the embeddings as head. Now follows HF; the cross-check then requires lm_head.weight. Regression test fails without the fix. (MEDIUM)
  • The checkpoint cross-check multiplied a header dim by 32 unchecked; a crafted dim 2^59 + 2 wrapped to the expected 4-bit width and passed. Now checked; test fails without the fix. (LOW)
  • The model check ran the config's OutIn layout, but IreeLlama (the path feat(xla): single-seq recurrent state in shim; Mamba2 generates on xla #3339 drives) always uses InOut. The runner now takes --layout, default inout. Re-run at InOut: synthetic 1.8e-6, mamba2-130m 2.0e-4 (local-task) and 3.9e-4 (hip), argmax equal; f16 on hip fails the gate as expected (0.44), so the runner does fail on a bad result. (MEDIUM)

Remaining Items

  • HF's torch path and the MLX loader normalize the gated output over all of d_inner; the original mamba_ssm kernel (and HF's CUDA path) normalizes per group when n_groups > 1. Irrelevant for mamba2-130m (n_groups = 1); verify before enabling an n_groups > 1 checkpoint such as Codestral Mamba. (MEDIUM, follows the issue's spec)
  • For feat(xla): single-seq recurrent state in shim; Mamba2 generates on xla #3339: compile_vmfbs emits prefill_embeddings for every dense config and now gets Err for Mamba2, so it must skip that entry for recurrent configs. The decode @state_import handoff is only compiled here, never executed (the auxiliary module cannot call it); feat(xla): single-seq recurrent state in shim; Mamba2 generates on xla #3339's gate 1 is its first execution. (note)
  • rms_norm = false is refused although HF ignores the flag. Conservative. (LOW)

f16

Rounding every nn.Linear input and weight to f16 inside HF's own fp32 forward reproduces the drift: 0.44 overall, 0.39 from in_proj alone (0.40 even with the dt columns kept f32). Norms, softplus, the D skip and the residual stream are already f32 in the graph, so nothing else contributes. hip defaults to f16 (default_precision, used by effective_precision), which is what #3339's token-exact gate will run at. In the simulation, 40 greedy tokens on five prompts match fp32, so the risk is low but not zero; pinning f32 for recurrent configs the way MLA does is the fallback.

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow (deferred to feat(xla): single-seq recurrent state in shim; Mamba2 generates on xla #3339 by the issue)
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass (lib 499 passed, fmt, clippy with and without iree, example clippy)

The recurrent checkpoint cross-check is meant to make the checkpoint the upper bound on what an untrusted config.json can request, but several paths let a hostile model directory get past it or around it.

- Cap num_hidden_layers at 1024 at parse time, for Mamba2 and dense configs. The new layer_mixers vector is sized by it before any checkpoint is read, so an absurd count was a host allocation of that many bytes.
- Require every safetensors header entry to be backed by exactly product(shape) * dtype bytes inside the file's data section, as the loader's SafeTensors::deserialize does. A header alone previously vouched for any dims, so a few-KB file passed the check, and compile_ssm_model_graphs (which never loads weights) emitted and compiled graphs at those dims.
- Bound the per-layer ssm_h state (H*P*N) by the layer's in_proj elements. H*P and G*N were each checked, but their product was not, so a narrow-hidden checkpoint of a few MB could ask for gigabytes of state.
- Resolve index shard names through the loader's index_shard_path rule (moved to a shared shard_path module so the emitter builds without iree). The local check let "..", "/" and NUL-bearing names through, and deduplicated shards with a quadratic Vec::contains.
- ssm_model_check.py loads HF weights with use_safetensors=True and the runner's .npy outputs with allow_pickle=False.

Each fix has a unit test that fails without it. cargo test -p mlxcel-xla --lib, and clippy -D warnings with and without iree and on the xla-iree example, pass.

Refs #3338
@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review

Trust boundary: an untrusted model directory (config.json, safetensors headers, index). Fixed in d9cb7b8, each with a unit test that fails without it:

  • MEDIUM: num_hidden_layers sized the new layer_mixers vector (dense and Mamba2 parse paths) before any checkpoint check, so an absurd count was a host allocation of that size. Now capped at 1024 at parse time.
  • MEDIUM: the cross-check read declared shapes from safetensors headers without checking them against the file's data section, so a few-KB file vouched for any dims. compile_ssm_model_graphs never loads weights, so it emitted and compiled at those dims. Every header entry must now span exactly product(shape) * dtype bytes within the file.
  • MEDIUM: H*P and G*N were each bounded by tensor shapes, but the per-layer ssm_h state H*P*N was not, so a narrow-hidden checkpoint could request gigabytes of state. The state is now bounded by the layer's in_proj element count (any real Mamba2 has N <= 2 * hidden).
  • LOW: index shard names used a local check that let .., / and NUL through (reads failed on directories, so nothing leaked) and deduplicated with a quadratic Vec::contains. They now go through index_shard_path, moved to a shared shard_path module, with a set.
  • LOW: ssm_model_check.py now uses use_safetensors=True and np.load(..., allow_pickle=False).

Checked, no change needed: the MLX [C,K,1] to [C,1,K] conv reinterpretation keeps the element product, and SafeTensors::deserialize enforces byte length. load_host_weights is pub(crate) and goes through the loader's shard resolution. Token ids and prompt length are checked on the host. Cached artifacts use the private cache_dir helpers, and --compile-times writes only to the directory the caller names. The Python runner has no trust_remote_code, and its subprocess arguments are a list. Graph emission is O(layers) and independent of capacity. Host work in the runner is O(capacity + state).

Verification: cargo test -p mlxcel-xla --lib (505 pass). Clippy -D warnings passes with and without iree and on the xla-iree example. ssm_model_check.py passes on local-task for the synthetic model and mamba2-130m (max-abs 1.5e-4, argmax match).

The CHANGELOG entry, FINDINGS_ssm.md and the spike README now describe the final behavior: tie_word_embeddings follows the HF default (untied), num_hidden_layers is capped at 1024 for dense configs too, each safetensors header entry must be backed by its shape * dtype bytes inside the file, index shard names must be plain file names, and the per-layer state H*P*N is bounded by the in_proj element count. The README also names the --layout default.

Two module comments in lib.rs had drifted onto the wrong mods (the shard_path note sat above local_task, the ssm_probe note above ssm_model_check) and are moved back. shard_path.rs gains a direct unit test of the plain-file-name rule, including the NUL and empty cases the checkpoint tests did not reach.

Validation: cargo test -p mlxcel-xla --lib (506 passed), clippy -D warnings with and without iree and on the xla_ssm_model_check example, scripts/ci/check_used_by.py and check_env_var_docs.py pass. Temporarily disabling the header-span check or the layer cap made checkpoint_cross_check_refuses_headers_larger_than_their_data and config_parse_refuses_an_unbounded_layer_count fail; both reverts were discarded.

Refs #3338
@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 23, 2026
@inureyes
inureyes merged commit ea0b45d into main Nov 23, 2026
33 checks passed
@inureyes
inureyes deleted the feature/issue-3338-mamba2-state-graphs branch November 23, 2026 20:29
inureyes added a commit that referenced this pull request Nov 23, 2026
#3371)

## Summary

Epic #564 unit U3. `MLXCEL_BACKEND=xla mlxcel generate` now runs HF `Mamba2ForCausalLM` checkpoints single-sequence on `hip` and `local-task`. The C shim and `IreeLlama` knew only the KV cache, so the state-threaded graphs from #3338 could not run. The shim now takes a generic list of recurrent-state tensors, and the KV cache is optional (an attention-free model carries no dummy KV).

Checkpoint used for validation: `AntonV/mamba2-130m-hf` @ `05e8773f` (`models/hf/mamba2-130m`).

## Changes

- **C shim (`csrc/xla_iree.c`)**: `xla_llama_create` takes `has_kv, n_state, state_ranks, state_dims, state_elems` (elem code 0 = f32, up to 8 tensors of rank up to 8) and validates them. Prefill pushes zeroed state inputs after `real_len` (allocated once, re-zeroed per request), pops KV only when `has_kv`, adopts the state results into `sscache` only when every result is valid, and sets `state_import_pending`. The next decode calls `decode_step.state_import` once, as `kv_import` does. A recurrent prefill refuses `real_len = 0`, and any failed or refused prefill drops the state so decode cannot continue the previous request. `xla_llama_state_reset` starts a request from the zero state. The ragged, slot and embeddings entries refuse a context without KV (`xla_require_kv`) until #3340.
- **Rust runtime (`iree.rs`, new `state_ffi.rs`)**: `RuntimeConfig` derives the state layout from `Config`; `StateFfi` flattens it for the FFI. The layout identity feeds the bundle fingerprint. A recurrent bundle skips the embeddings prefill module (`CompiledBundle.prefill_embeddings_vmfb` is now `Option`). `IreeRaggedLlama::load` refuses recurrent configs. `IreeLlama` resets the state instead of running a `real_len = 0` prefill when the prompt prefix is empty (a one-token prompt).
- **Config parsing (new `hf_json.rs`)**: HF writes a bare `Infinity` into Mamba2's `time_step_limit`. The runtime config reader, the EOS lookup and the CLI layer count parsed it strictly, so the CLI failed on `mamba2-130m` before this change. They now share one tolerant parser, which is ungated so the `xla-backend`-only build uses it too.
- **Refusal**: a `mamba2` config with `n_groups > 1` whose gated norm spans `d_inner` is refused with a clear error until the grouping is settled.
- **Tooling and docs**: `scripts/xla/validate_arch.sh --single-only` (structural pre-gate plus the token-exact gate, no serve gate). README section on the state ABI, `docs/supported-models.md`, `spike/openxla/FINDINGS_ssm.md`, CHANGELOG.

## Carry-over items from the issue comment

1. `compile_vmfbs` skips `prefill_embeddings` for recurrent configs, and the shim treats that module as optional only when `n_state > 0`.
2. The first real `@state_import` run is tested in `tests/xla_ssm_single_seq.rs`: prefill then decode agrees across three routes, and a second request on one session matches a fresh session.
3. `real_len = 0` is refused in the shim for recurrent contexts. Dense contexts keep their existing `real_len = 0` seeding (the one-token prompt path), so the dense path is unchanged. The host side resets the state instead.
4. Precision: gated at the hip default (f16) and it is token-exact, so recurrent configs are **not** pinned to f32. f32 on hip was also run and matches.
5. `n_groups > 1` is refused (`check_ssm_norm_grouping`).

## Changes during review

- Review (e6a03cd): a failed state reset (the zero-state preparation for a one-token prompt) returned early and kept the previous request's `sscache`, so the next decode continued the old request. It now drops the state; `failed_state_reset_drops_the_previous_state` fails without the fix (via a test-support hook `xla_test_set_state_zero_failure`).
- Security review (e690800): a request refused in Rust before reaching the shim (prompt over capacity, empty prompt) left the previous request's state live in `sscache` and the decode globals. Every `IreeLlama` prefill entry and every session request entry now calls the new `xla_llama_state_drop` first (no-op without recurrent state). `xla_require_kv` refuses the ragged, slot and embeddings entry points whenever `n_state > 0`, so a future hybrid cannot run a KV-only path silently. A non-Mamba2 config with a bare `Infinity`/`NaN` is refused instead of reaching optional-float readers that would silently default it (the tolerant parse had been on main since #3370). Each new test fails with its fix reverted. Left: a decode that fails partway may leave the state globals partly advanced for a retry within the same request; the next request is isolated, and dense KV behaves the same.
- Finalize (25eeb40): CHANGELOG, README and FINDINGS state the final behavior; the CLI no longer prints a `KV cache mode` banner for Mamba2 on the XLA path. The 40 ids were re-checked on hip after the change.

## Validation

HF fp32 oracle (`oracle_continuation.py`), "The capital of France is", 40 greedy tokens:

```
247 2846 273 253 5112 952 13 285 253 5347 273 253 5112 4687 15 733 310 253 5347 273 253 4687 273 6181 13 285 253 5347 273 253 4687 273 6181 15 187 187 510 5347 273 253
```

| route | device | precision | result |
|-------|--------|-----------|--------|
| `mlxcel generate` (CLI) | hip | f16 (default) | 40/40 |
| `mlxcel generate` (CLI) | hip | f32 | 40/40 |
| `mlxcel generate` (CLI) | local-task | f32 (default) | 40/40 |
| `xla_oracle_check` | hip | default | 40/40 |
| `xla_oracle_check` | local-task | default | 40/40 |
| `validate_arch.sh --single-only` | hip | default | PASS |

A one-token prompt ("The", 10 tokens), which takes the state-reset path, also equals its HF oracle (`1246 3688 7033 281 247 1332 323 253 3275 273`).

`tests/xla_ssm_single_seq.rs` (synthetic Mamba2, 4 tests) passes on hip and local-task. A mutation that feeds the previous request's state into prefill fails 3 of the 4 tests.

Dense regression on hip: `xla_ragged_hardening` 6/6, `xla_greedy_timing` 3/3, `xla_decode_scalar_reuse` 4/4, `xla_prepared_prefill` 4/4. `llama-3.2-1b-instruct-4bit` greedy ids (40 tokens) are identical before and after. `cargo test -p mlxcel-xla --lib` 512 passed; `cargo fmt --check` and clippy `-D warnings` (mlxcel-xla lib and tests with and without `iree`, root `--features xla-iree --all-targets`) pass.

## Follow-up for #3340

Continuous batching and `mlxcel-server` for recurrent models: lift the `xla_require_kv` guards on the ragged, slot and embeddings entries, add per-slot state, and remove the recurrent refusal in `IreeRaggedLlama::load`.

Closes #3339
@inureyes inureyes added this to the 0.9 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:architecture Architecture and code structure changes area:inference Generation, sampling, decoding (incl. speculative, DRY) priority:high High priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(xla): Mamba2 config, mixer schedule, weights, state-threaded graphs

1 participant