Repository navigation
feat(xla): add Mamba2 config, mixer schedule and state-threaded graphs - #3370
Conversation
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
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
Implementation Review SummaryIntent
Findings Addressed (e17b087)
Remaining Items
f16Rounding every Verification
|
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
Security and performance reviewTrust boundary: an untrusted model directory (
Checked, no change needed: the MLX Verification: |
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
#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
Summary
Mamba2 (
model_type = "mamba2") now parses into a per-layer mixer schedule, declares itsbackbone.*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.Configgainsssm,layer_mixers, andstate_tensors(),has_kv_cache(),state_layer_index(),layer_has_ffn().Config::from_jsoncross-checks every SSM dim against the safetensors headers.emit_transformer_layerrunsnorm -> mixer -> residualfor Mamba2 layers. RoPE tables, masks and KV are skipped when there is no attention layer.emit_decode_batched, the ragged decode and everyprefill_embeddings*entry now returnResultand refuse recurrent configs with an error naming the model type.State ABI (for #3339 / #3340)
The ABI is the one in the issue. Prefill takes
ssm_h [L,H,P,N]and thenssm_conv [L,K-1,conv_dim](both f32) afterreal_len, and returns them after the logits. There are nokcache/vcacheresults. Decode keeps@ssm_h/@ssm_convglobals seeded by@state_import(%s0, %s1).@mainkeepstoken,posandcache_lenbut reads only the token.@kcache,@vcacheand@kv_importare 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
tie_word_embeddingsnow follows the HFMamba2Configdefault (false) whenconfig.jsonomits it, and the cross-check then requireslm_head.weight(MEDIUM: a checkpoint with its own head would silently have used the embeddings). The model check now defaults to theInOutlayout thatIreeLlama::loaduses (--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 thenn.Linearinputs and weights to f16 reproduces 0.44 max-abs,in_projalone 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.num_hidden_layersis capped at 1024 at parse time in both the Mamba2 and dense parsers, becauselayer_mixerswas allocated from it before any check. Every safetensors header entry must be backed by exactlyshape * dtypebytes inside the file (before, a few-KB file could declare any dims and get graphs compiled at them). The per-layer stateH*P*Nmay not exceed the layer'sin_projelement count. Shard names go throughindex_shard_path, moved toshard_path.rsso the emitter builds withoutiree. The Python check loads safetensors only and reads.npywithallow_pickle=False.Test plan
spike/openxla/ssm_model_check.py(withexamples/xla_ssm_model_check.rs) compares the last-token logits with HFMamba2ForCausalLMfp32. 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.n_groups2, 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.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 warningswith no features, withiree, and for the example.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