Skip to content

feat(xla): thread recurrent state in the shim; Mamba2 generates on xla - #3371

Merged
inureyes merged 5 commits into
mainfrom
feature/issue-3339-mamba2-single-seq-state
Nov 23, 2026
Merged

inureyes merged 5 commits into
mainfrom
feature/issue-3339-mamba2-single-seq-state

Conversation

@inureyes

@inureyes inureyes commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

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 feat(xla): per-slot recurrent state; Mamba2 serves via mlxcel-server #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 feat(xla): add Mamba2 config, mixer schedule and state-threaded graphs #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

Epic #564 unit U3. The C shim and IreeLlama knew only the KV cache, so the state-threaded Mamba2 graphs from #3338 could not run. The shim now takes a generic list of recurrent-state tensors with their own shapes, and the KV cache is optional (no dummy KV for an attention-free model).

- xla_llama_create takes has_kv, n_state, state_ranks, state_dims and state_elems and validates them. Prefill pushes zeroed state inputs (allocated once, re-zeroed per request), skips the KV results when has_kv is 0, 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. A recurrent prefill refuses real_len = 0, and a failed or refused prefill drops the state so decode cannot continue the previous request. xla_llama_state_reset starts from the zero state for an empty prompt prefix. Ragged, slot and embeddings entries refuse a context without KV until #3340.
- RuntimeConfig derives the state layout from Config, runtime_ffi_dimensions flattens it (state_ffi.rs), and the layout feeds the bundle fingerprint. A recurrent bundle skips the embeddings prefill module. The ragged loader refuses recurrent configs. The runtime refuses mamba2 with n_groups > 1 until the gated-norm grouping is settled.
- HF configs with a bare Infinity now parse in the runtime config reader, the EOS lookup and the CLI layer count (the CLI failed on mamba2-130m before). The tolerant parser moves to an ungated hf_json module so the xla-backend-only build has it.
- validate_arch.sh gains --single-only; tests/xla_ssm_single_seq.rs covers the handoff on a synthetic Mamba2.

Validated: AntonV/mamba2-130m-hf greedy ids equal the HF fp32 oracle for 40 tokens on hip (default f16 and f32) and local-task through the CLI and xla_oracle_check, so no f32 pin. Dense llama-3.2-1b ids are unchanged and the dense device gates pass.

Refs #3339
@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
xla_llama_state_reset (the empty-prefix path of a one-token prompt) returned early through XLA_CHECK when preparing the zero state failed, leaving the previous request's sscache in place. A decode after that error continued the previous request, which breaks the invariant the PR states for every failed or refused prefill. The reset now drops the state on failure, so decode refuses until a prefill or reset succeeds.

A test-support hook (xla_test_set_state_zero_failure) forces the zero-state preparation to fail. The new device test failed_state_reset_drops_the_previous_state fails without the fix (the state stays present) and passes with it on hip; the other four xla_ssm_single_seq tests and xla_ragged_hardening (6/6) still pass. Also removes a stray comment left above the SsmPrefillForm re-export.

Refs #3339
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Thread single-sequence recurrent state through the C shim and IreeLlama so Mamba2 generates via MLXCEL_BACKEND=xla mlxcel generate, token-exact against HF fp32, with state reset between requests.

Findings Addressed

  • xla_llama_state_reset returned early when preparing the zero state failed and kept the previous request's sscache, so a decode after that error continued the old request. It now drops the state like a failed prefill. New device test failed_state_reset_drops_the_previous_state (with a test-support failure hook) fails without the fix and passes with it on hip (MEDIUM, e6a03cd)
  • Stray comment above the SsmPrefillForm re-export removed (LOW, e6a03cd)

Remaining Items

  • xla_require_kv refuses only has_kv == 0. A future hybrid (KV plus state) would pass the ragged/slot/embeddings guards without a state contract; refusing n_state > 0 there is the safer condition for feat(xla): per-slot recurrent state; Mamba2 serves via mlxcel-server #3340/feat(xla): Nemotron-H hybrid with dual KV + recurrent state carry #3344. Not reachable today (no hybrid config, IreeRaggedLlama::load refuses recurrent configs, recurrent bundles have no embeddings module) (LOW)
  • The CLI preamble prints KV cache mode: fp16 (applied to 24 of 24 layers) for attention-free Mamba2 on the XLA path; cosmetic (LOW)
  • cargo clippy --features xla-iree,test-utils --all-targets fails on private_interfaces in IreeRaggedLlama prepared-slot methods this PR does not touch; the acceptance command without test-utils passes (LOW, out of scope)

Verification

  • All stated requirements implemented (acceptance items and the five carry-over items checked against the code)
  • No placeholder/mock code remaining
  • Integrated into project code flow (XlaInferenceSession / IreeLlama CLI path)
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass

Reproduced on hip: mlxcel generate -m models/hf/mamba2-130m -p "The capital of France is" -n 40 --temp 0 --no-chat-template prints the 40 oracle ids exactly (default precision). xla_ssm_single_seq 5/5 and xla_ragged_hardening 6/6 on hip; cargo fmt --check and cargo clippy --features xla-iree --all-targets -- -D warnings pass. The cargo clippy --features xla-backend --all-targets failures in src/multimodal/host_preprocessor_molmo_tests.rs and src/worker_failfast.rs reproduce identically on origin/main (ea0b45d), so they are pre-existing.

A request refused before it reached the shim (an oversized prompt or an empty one, checked in Rust by both IreeLlama and XlaInferenceSession) left the previous request's recurrent state in place, so a following decode or decode_step continued the earlier sequence. Every IreeLlama prefill entry and every session request entry now drops the state first through the new xla_llama_state_drop; a decode then refuses until a prefill or state reset succeeds. Models without recurrent state are unchanged.

The ragged, slot and embeddings shim entries now refuse any context that threads state, not only one without KV, and drop the state on refusal. A future hybrid (KV plus state) would otherwise adopt a new KV next to the previous request's state. Dense contexts are unaffected. The token prefill also drops the state on a null-argument refusal.

Config::from_json_str refuses a document that needed its bare Infinity/NaN quoted unless the Mamba2 reader handles it. The attention readers read optional floats as Option, so a quoted token silently took the field default instead of failing like the strict parse.

Tests: request_refused_in_rust_drops_the_previous_state and kv_only_entry_points_refuse_any_recurrent_state in xla_ssm_single_seq, attention_config_refuses_a_quoted_non_finite_number in the lib; each fails with its fix reverted.

Refs #3339
@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review

Scope: the C/FFI state boundary, buffer lifetimes, cross-request isolation, the test hooks, and the HF JSON tolerance.

Fixed (e690800)

  • MEDIUM, cross-request isolation: a request refused in Rust before it reached the shim (oversized or empty prompt, checked by IreeLlama::prefill_padded/prefill_first and by XlaInferenceSession::prefill/generate_*) left the previous request's state in sscache and the decode globals, so a later decode/decode_step continued the earlier sequence. Every engine prefill entry and every session request entry now calls the new xla_llama_state_drop first. Test: request_refused_in_rust_drops_the_previous_state.
  • LOW, hybrid invariant: xla_require_kv now refuses whenever n_state > 0 (not only has_kv == 0) and drops the state on refusal; dense contexts are unchanged. Test: kv_only_entry_points_refuse_any_recurrent_state (device-free hook under MLXCEL_XLA_TEST_SUPPORT).
  • LOW, config parsing: Config::from_json_str let a quoted bare Infinity/NaN reach the attention readers, which read optional floats as Option and silently took the default. Only the Mamba2 reader understands the quoted spelling, so other model types now refuse such a document. Test: attention_config_refuses_a_quoted_non_finite_number.

Each test fails with its fix reverted.

Checked, no change

  • xla_set_state_contract validates rank before reading state_dims, reads only sum(ranks) entries, and bounds the running byte product against both IREE_DEVICE_SIZE_MAX and SIZE_MAX, so xla_state_elements cannot overflow.
  • Prefill adopts KV and state together only after every result validates; all failure paths go through one cleanup that drops state. Output pops are bounds-checked by IREE and each state result is shape-validated, so a short or mismatched result list fails cleanly.
  • xla_test_set_state_zero_failure and xla_test_state_status are compiled only under MLXCEL_XLA_TEST_SUPPORT (the test-support feature).
  • quote_non_finite_json leaves string contents (including escapes) untouched and runs only when the strict parse fails.

Left open

  • LOW: a decode_step.main invocation that fails mid-step may leave the state globals partly advanced while sscache stays present, so a retried decode in the same request would continue from them. The next request re-imports, so isolation across requests holds. Dense KV has the same pre-existing behavior.

Gates: SSM single-seq device tests, xla_ragged_hardening, xla_greedy_timing, mlxcel-xla lib tests, clippy (lib/tests with and without iree, root xla-iree --all-targets) on gfx1151.

The CHANGELOG entry, the mlxcel-xla README recurrent-state section and FINDINGS_ssm.md now describe the final code: refused or failed requests (including a failed state reset) drop the previous request's state, the KV-only entry points refuse any recurrent state until #3340, pure mamba2 with n_groups > 1 is refused, and a non-Mamba2 config with a bare Infinity or NaN is refused instead of silently defaulted.

mlxcel generate on the XLA backend no longer prints "KV cache mode: fp16 (applied to 24 of 24 layers)" for mamba2, which has no KV cache. The check is a local helper in generate.rs that reads model_type, so the banner for every other model and backend is unchanged. The body of the banner match only gained one indentation level.

Validation: cargo clippy --features xla-iree --all-targets -D warnings clean, mlxcel-xla lib tests 513 passed, check_used_by.py and check_env_var_docs.py OK, and the hip CLI run on mamba2-130m prints the same 40 token ids as the PR body.

Refs #3339
@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 23, 2026
@inureyes
inureyes merged commit e062a10 into main Nov 23, 2026
33 checks passed
@inureyes
inureyes deleted the feature/issue-3339-mamba2-single-seq-state branch November 23, 2026 23:01
@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): single-seq recurrent state in shim; Mamba2 generates on xla

1 participant