Repository navigation
feat(xla): thread recurrent state in the shim; Mamba2 generates on xla - #3371
Conversation
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
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
Implementation Review SummaryIntent
Findings Addressed
Remaining Items
Verification
Reproduced on hip: |
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
Security and performance reviewScope: the C/FFI state boundary, buffer lifetimes, cross-request isolation, the test hooks, and the HF JSON tolerance. Fixed (e690800)
Each test fails with its fix reverted. Checked, no change
Left open
Gates: SSM single-seq device tests, |
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
Summary
Epic #564 unit U3.
MLXCEL_BACKEND=xla mlxcel generatenow runs HFMamba2ForCausalLMcheckpoints single-sequence onhipandlocal-task. The C shim andIreeLlamaknew 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
csrc/xla_iree.c):xla_llama_createtakeshas_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 afterreal_len(allocated once, re-zeroed per request), pops KV only whenhas_kv, adopts the state results intosscacheonly when every result is valid, and setsstate_import_pending. The next decode callsdecode_step.state_importonce, askv_importdoes. A recurrent prefill refusesreal_len = 0, and any failed or refused prefill drops the state so decode cannot continue the previous request.xla_llama_state_resetstarts 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.iree.rs, newstate_ffi.rs):RuntimeConfigderives the state layout fromConfig;StateFfiflattens it for the FFI. The layout identity feeds the bundle fingerprint. A recurrent bundle skips the embeddings prefill module (CompiledBundle.prefill_embeddings_vmfbis nowOption).IreeRaggedLlama::loadrefuses recurrent configs.IreeLlamaresets the state instead of running areal_len = 0prefill when the prompt prefix is empty (a one-token prompt).hf_json.rs): HF writes a bareInfinityinto Mamba2'stime_step_limit. The runtime config reader, the EOS lookup and the CLI layer count parsed it strictly, so the CLI failed onmamba2-130mbefore this change. They now share one tolerant parser, which is ungated so thexla-backend-only build uses it too.mamba2config withn_groups > 1whose gated norm spansd_inneris refused with a clear error until the grouping is settled.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
compile_vmfbsskipsprefill_embeddingsfor recurrent configs, and the shim treats that module as optional only whenn_state > 0.@state_importrun is tested intests/xla_ssm_single_seq.rs: prefill then decode agrees across three routes, and a second request on one session matches a fresh session.real_len = 0is refused in the shim for recurrent contexts. Dense contexts keep their existingreal_len = 0seeding (the one-token prompt path), so the dense path is unchanged. The host side resets the state instead.n_groups > 1is refused (check_ssm_norm_grouping).Changes during review
sscache, so the next decode continued the old request. It now drops the state;failed_state_reset_drops_the_previous_statefails without the fix (via a test-support hookxla_test_set_state_zero_failure).sscacheand the decode globals. EveryIreeLlamaprefill entry and every session request entry now calls the newxla_llama_state_dropfirst (no-op without recurrent state).xla_require_kvrefuses the ragged, slot and embeddings entry points whenevern_state > 0, so a future hybrid cannot run a KV-only path silently. A non-Mamba2 config with a bareInfinity/NaNis 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.KV cache modebanner 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:mlxcel generate(CLI)mlxcel generate(CLI)mlxcel generate(CLI)xla_oracle_checkxla_oracle_checkvalidate_arch.sh --single-onlyA 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_hardening6/6,xla_greedy_timing3/3,xla_decode_scalar_reuse4/4,xla_prepared_prefill4/4.llama-3.2-1b-instruct-4bitgreedy ids (40 tokens) are identical before and after.cargo test -p mlxcel-xla --lib512 passed;cargo fmt --checkand clippy-D warnings(mlxcel-xla lib and tests with and withoutiree, root--features xla-iree --all-targets) pass.Follow-up for #3340
Continuous batching and
mlxcel-serverfor recurrent models: lift thexla_require_kvguards on the ragged, slot and embeddings entries, add per-slot state, and remove the recurrent refusal inIreeRaggedLlama::load.Closes #3339