Skip to content

feat(xla): carry per-slot recurrent state in continuous batching - #3372

Merged
inureyes merged 3 commits into
mainfrom
feature/issue-3340-per-slot-recurrent-state
Nov 24, 2026
Merged

inureyes merged 3 commits into
mainfrom
feature/issue-3340-per-slot-recurrent-state

Conversation

@inureyes

@inureyes inureyes commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

Summary

Epic #564 sub-issue U4. Per-slot recurrent state carry in the continuous-batching engine, so Mamba2 serves through mlxcel-server on the xla backend.

  • Emitter: ragged decode takes and returns one [B, ...dims] tensor per StateTensorSpec entry (ssm_h, ssm_conv). RecurrentLayers::split_rows / join_rows slice and write back rows with dynamic_update_slice. With no KV, RoPE gathers and masks are skipped. Dense ragged MLIR is byte-identical (validation goldens pass). Hybrids are still refused.
  • Shim (xla_iree.c): lazily allocated per-slot sscache_b[] buffers, zeroed on ragged reset and released with the state. xla_store_prefill_slot invalidates the slot, copies KV only when has_kv, copies each state row at slot * row, and sets the slot valid only after every copy succeeds. A failed ragged decode on a stateful model invalidates every slot. New export xla_llama_slot_invalidate. decode_step.state_import is optional in a bundle; the single-sequence path still refuses at import time.
  • Rust (iree.rs): IreeRaggedLlama::load refuses only hybrids. Every slot entry goes through begin_slot_prefill, which validates the slot and invalidates it before any other check, so a refused request leaves no stale state. Embeddings and diagnostics entries still refuse attention-free models via xla_require_kv. Test-support counters report batch state allocations. XlaBatchEngine's Slot, XlaBucketSet and the serve worker need no new fields: the state lives on the device keyed by slot, like the KV.
  • Precision: recurrent configs are pinned to f32 on every device, single-sequence and ragged, like MLA (Config::pins_f32_precision). At the old f16 hip default the single-sequence decode drifts from the HF fp32 oracle after about 16 tokens on some prompts ("In computer science, a linked list is"), so f16 is not token-exact for recurrent models. An explicit MLXCEL_XLA_PRECISION still overrides the pin.
  • gemma3n_audio_config: uses the tolerant HF JSON parser. Server startup on Mamba2 failed before this with parse config JSON: expected value at line 25 (bare Infinity). Non-Mamba2 configs with a bare Infinity/NaN are still refused by the dense and Gemma3n config parsers.
  • Docs: CHANGELOG, docs/supported-models.md, docs/environment-variables.md, mlxcel-xla README, validate_arch.sh help, and a new section in spike/openxla/FINDINGS_ssm.md.

Verification (hip, gfx1151, default precision after the pin)

  • mlxcel generate mamba2-130m, 40 greedy tokens: 5/5 prompts token-exact vs the HF fp32 oracle ("The capital of France is", "In computer science, a linked list is", "Once upon a time, in a small village by the sea,", "The three primary colors are", "Water boils at a temperature of"); xla_oracle_check 5/5.
  • validate_arch.sh --batch 4 --requests 8 --maxcap 24: PASS (structural, token-exact, serve reference-exact; 123.7 vs 75.0 tok/s).
  • xla_batch_bench: B=4 with the 64-token prompt PASS (8/8, was 7/8 at f16; 122.8 tok/s); --cancel 2 PASS; --buckets 256,512 PASS; B=8, 16 requests PASS.
  • mlxcel-server, 4 concurrent temperature-0 /v1/completions: 4/4 equal the CLI (was 3/4 at f16).
  • The pin costs throughput on this model: the serve gate ran at 285.6 tok/s batched at f16.
  • Device tests: xla_ssm_state_carry 5/5, xla_ssm_single_seq 6/6, xla_ragged_hardening 6/6. Each carry fix reverted fails its test (Rust slot invalidation or decode-failure invalidate-all: refused_requests_and_failed_decodes_invalidate_slot_state; the state row copy: 4 tests; the release in reset: state_allocation_counters_show_one_allocation_per_reset).
  • mlxcel-xla lib 520 pass, including the new pin test, which fails without the pin.
  • Dense regression vs main e062a10: ragged_hardening 6/6, greedy_timing 3/3, decode_scalar_reuse 4/4, prepared_prefill 4/4 on both; llama-3.2-1b xla_batch_bench B4 N8 REFERENCE-EXACT PASS both, 64.56 tok/s before and 63.53 tok/s after.
  • cargo fmt --check, cargo clippy --features xla-iree --all-targets -- -D warnings, and mlxcel-xla clippy with and without iree: clean.

Changes during review

  • Review (0807595, orchestrator-required): at the previous f16 default on hip, the single-sequence path was not token-exact against HF fp32 on some prompts ("In computer science, a linked list is" diverged after about 16 tokens), which made the serve gate 7/8 and the server check 3/4 against a drifting reference while the batched path matched the oracle. Recurrent configs are now pinned to f32 on every device, single-sequence and ragged, like MLA; an explicit MLXCEL_XLA_PRECISION still overrides it. recurrent_config_pins_f32_unless_precision_is_explicit fails with the pin removed. All gates were re-run at the new default (numbers below). Cost: the serve gate's batched throughput on mamba2-130m went from 285.6 to 123.7 tok/s. Left (LOW): a single-sequence bundle without decode_step.state_import now fails at the first decode rather than at load; the import stays pending, so stale globals are never used.
  • Security review: no CRITICAL/HIGH/MEDIUM finding and no change. Cross-request isolation was checked for refused admits, torn stores, recycled slots, cancel, disconnect, failed ragged decode, bucket switch and shutdown. Left (LOW): on pinned configs (MLA, recurrent) an unrecognised MLXCEL_XLA_PRECISION keeps f32 silently where dense configs reject it, as MLA already behaved. Pre-existing, outside this PR: any prefill or decode error stops the whole serve worker, and the request popped in a failed pump is dropped.
  • Finalize: no change needed; docs and CHANGELOG already state the f32 default.

Follow-ups

Closes #3340

Mamba2 now serves through mlxcel-server on the xla backend. The ragged decode emitter takes and returns one [B, ...dims] tensor per StateTensorSpec entry and splits and joins rows with dynamic_update_slice, so an attention-free model batches without KV buffers. Hybrids (KV plus recurrent state) stay refused in the emitter and in IreeRaggedLlama::load until #3344.

The IREE shim keeps lazily allocated per-slot state buffers, zeroed on each ragged reset and released with the rest of the state. A slot prefill invalidates the slot first, copies KV only when the model has KV, copies each state row into its slot, and marks the slot valid only after every copy succeeds. A failed ragged decode on a stateful model invalidates every slot. Rust slot entries call a new xla_llama_slot_invalidate before validating, so a refused request also leaves no stale state behind. Embeddings and diagnostics entries still refuse attention-free models.

The Gemma3n audio config probe now uses the tolerant HF JSON parser, so a config with a bare Infinity (Mamba2) no longer fails server startup.

New device tests in tests/xla_ssm_state_carry.rs cover mid-stream admits into recycled slots, half and full batches, torn state stores, refused requests and failed decodes, and one state allocation per reset.
@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 24, 2026
At the f16 hip default the single-sequence Mamba2 decode departs from the HF fp32 oracle after about 16 tokens on some prompts ("In computer science, a linked list is"), while f32 and the batched path match it. That made the serve gate and the server check compare batched output against a drifting reference (7/8 and 3/4 at f16).

`effective_precision` now pins F32 for recurrent configs on every device, as it already did for MLA, for both the single-sequence and the ragged bundles. The decision lives in `Config::pins_f32_precision` and `resolve_pinned_precision_with_override`, so it is unit-tested without the IREE runtime; a recognised explicit `MLXCEL_XLA_PRECISION` still overrides the pin. Docs state that f16 is not token-exact for recurrent models.

Validated on hip at the default precision: CLI 5/5 prompts token-exact vs HF fp32, validate_arch serve gate PASS, xla_batch_bench (64-token prompt, cancel, buckets, B=8) all reference-exact, mlxcel-server 4/4 concurrent requests equal the CLI, xla_ssm_state_carry, xla_ssm_single_seq and xla_ragged_hardening pass.

Refs #3340
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Carry Mamba2 recurrent state per slot in the continuous-batching engine so it serves through mlxcel-server with every batched request equal to its single-sequence output.

Findings Addressed

  • At the f16 hip default the single-sequence reference drifts from the HF fp32 oracle, so the serve gate (7/8) and the server check (3/4) compared against a wrong reference. Recurrent configs are now pinned to f32 like MLA, overridable by an explicit MLXCEL_XLA_PRECISION, with a unit test that fails without the pin (HIGH, 0807595)

Remaining Items

  • A single-sequence bundle without decode_step.state_import is now refused at the first decode rather than at load (LOW). The refusal is clear and leaves the import pending, so no decode runs on stale globals.
  • feat(xla): Nemotron-H hybrid with dual KV + recurrent state carry #3344 plans an f16 Nemotron-H run (~8 GB); with the pin, hybrids default to f32 unless MLXCEL_XLA_PRECISION is set (note for that issue).

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass

Re-run at the default precision after the pin, all on hip: CLI 5/5 token-exact vs HF fp32, validate_arch.sh PASS, xla_batch_bench 64-token B=4 8/8 plus cancel, buckets and B=8 PASS, server 4/4 vs CLI, device tests xla_ssm_state_carry 5/5, xla_ssm_single_seq 6/6, xla_ragged_hardening 6/6, fmt and clippy gates clean.

@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review (head 0807595)

No CRITICAL, HIGH or MEDIUM findings; no commits pushed.

Cross-request isolation holds on every path checked. Every Rust slot entry calls begin_slot_prefill (validate, then xla_llama_slot_invalidate) before any other check, and xla_store_prefill_slot clears rg_valid[slot] before the first transfer and sets it only after the last one. A slot prefill always starts from a device-zeroed state_zero and overwrites its whole row, and the ragged decode refuses any active row whose flag is clear. Cancel and disconnect only free the scheduler slot; the stale row is overwritten by the next admit. A failed ragged decode (pre-invoke, invoke, validation or readback) swaps nothing and clears every flag. Buckets each own their sscache_b set. xla_llama_free releases it. Any pump error ends the serve worker after fail_all, so no request runs on top of a failed step.

Bounds: the slot is range-checked before any offset; rg_bsz * row is checked in xla_ensure_batch_state, and the reset that changes rg_bsz also releases the set, so the bound stays valid for later stores. state_desc is written only at create (and copied into buckets), and prefill and decode results are shape-validated against it before a copy or swap.

Resource use: the state set is fixed per bucket at B x row, allocated once per reset, and production resets only at load, so no client can trigger reallocation. Per step the state is threaded device-side (input push, output swap, no host copy); the non-donated arguments cost one device-side state write per step, the same pattern as the KV.

LOW, left as is: with a pinned config (MLA, recurrent), an unrecognised MLXCEL_XLA_PRECISION (for example fp8 or F16) is ignored and F32 is used, while dense configs reject it. This is the safe direction and matches the MLA behaviour before this PR, but an operator typo goes unreported.

Verified on gfx1151 hip: xla_ssm_state_carry 5/5, xla_ragged_hardening 6/6, xla_ssm_single_seq 6/6.

@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 24, 2026
@inureyes
inureyes merged commit fd879f2 into main Nov 24, 2026
33 checks passed
@inureyes
inureyes deleted the feature/issue-3340-per-slot-recurrent-state branch November 24, 2026 01:06
@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): per-slot recurrent state; Mamba2 serves via mlxcel-server

1 participant