Skip to content

feat(xla): add SSM scan primitive with HF oracle and prefill decision - #3360

Merged
inureyes merged 6 commits into
mainfrom
feature/issue-3337-ssm-scan-primitive
Nov 23, 2026
Merged

inureyes merged 6 commits into
mainfrom
feature/issue-3337-ssm-scan-primitive

Conversation

@inureyes

@inureyes inureyes commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds the selective-scan primitive epic #564 needs before any SSM or hybrid family can run on the OpenXLA/IREE backend, proves one Mamba2 mixer layer against HF Mamba2Mixer.torch_forward in fp32 on local-task and hip, and records the measured prefill-lowering decision in spike/openxla/FINDINGS_ssm.md. Wiring into the generate path is #3339.

  • emitter/ssm.rs: causal depthwise conv1d (prefill, tail, step), selective_scan_step, selective_scan_prefill, and the Mamba2 mixer in prefill and decode form, exactly the API in feat(xla): SSM scan primitive (conv1d + selective scan) with HF oracle #3337. SsmConfig sits next to MoeConfig.
  • emitter/ssm_scan.rs: three prefill forms built from dot_general, pad, slices, select and reduce_window (no scatter, no while). Chunked SSD is the chosen one; the associative and sequential forms stay selectable for the measurements.
  • The scan contractions use a new Builder::dot_general_keep_f32, so the recurrence stays f32 on the f16 path.
  • emit_ssm_probe (model.rs), the dump_ssm_probe_for_execution_check test, ssm_probe.rs (runs the probe through the auxiliary IREE ABI), examples/xla_ssm_probe.rs, spike/openxla/ssm_oracle.py, ssm_gate.sh, and ssm_lowering_measure.py.

Lowering decision

Chunked SSD, chunk_size = 128. Measured on the mamba2-130m mixer dimensions at 256 and 4096 rows: 157 StableHLO ops and 33 dispatches at both capacities, compile under 1 s on llvm-cpu and rocm gfx1151, max-abs y error 6.7e-6 (local-task) and 6.0e-6 (hip). Q=128 has the smallest transient at 4096 (242 MiB). The associative scan is correct but needs 9.2 GiB of transient at 4096; the sequential unroll has 783 dispatches at 256 and does not compile within 1200 s at 4096 on either target. The cross-chunk carry is one dot_general against the chunk-level decay matrix (HF's form) instead of the unrolled sequence the issue suggested, so nothing is unrolled.

Contract notes for #3338 / #3339

  • The SsmConfig fields and the ssm.rs function signatures are unchanged from the issue. Additions only: SsmConfig::{d_inner, in_proj_dim, validate} (validate also requires conv_kernel >= 2), SSM_DEFAULT_CHUNK_SIZE = 128, ssm_state_types, and mamba2_mixer_prefill_form.
  • emit_ssm_probe takes an extra hidden argument, emit_ssm_probe(c, hidden, t, mode), because SsmConfig carries no model width.
  • mamba2_mixer_prefill uses conv0 as the conv's left context and in the tail slice, so a continued prefill is exact and real_len = 0 returns h0 and conv0 unchanged.

Changes during review

  • Review (2283ee0): no defect in the math (checked against HF torch_forward term by term, G>1 included), but two gate gaps. No case carried a nonzero state across more than two chunks, so zeroing the chunk-level decay matrix passed every y check, and HF's default time_step_limit (0, inf) meant removing the dt clamp was invisible. Added --time-step-limit to the oracle and the multi-chunk and clamp cases above. A remaining LOW: on the f16 path the prefill conv rounds to f16 while the decode conv accumulates in f32 (a mixed-type depthwise conv does not compile); recorded in FINDINGS with the fix if feat(xla): Mamba2 config, mixer schedule, weights, state-threaded graphs #3338 needs it.
  • Security review (cf1bfc0): SsmConfig::validate computes its products with checked arithmetic and rejects non-finite dt limits and a negative or non-finite norm_eps (MEDIUM: a wrapped H*P could satisfy the conv_dim equation in release builds). Zero rows and wrapping widths are rejected before emitting. The example's .npy reader moved into ssm_probe.rs as a bounds-checked parser that checks the declared shape and exact data length. Fixed /tmp paths in the README and the measurement script became mktemp -d. The FFI boundary already rechecked every buffer length against its shape. Left for feat(xla): Mamba2 config, mixer schedule, weights, state-threaded graphs #3338 (posted there): cross-check config dims against tensor shapes, clamp real_len on the host, and the H*(T/Q)^3 cross-chunk carry cost if contexts grow far beyond 4096.
  • Finalize (ad14be9): CHANGELOG entry; the two test-only dump variables added to the env-var checker's allowlist.

Test plan

  • cargo test --profile test-fast -p mlxcel-xla --lib: 479 passed on the final head, including the ssm tests, the new validation tests and the unchanged dense goldens.
  • spike/openxla/ssm_gate.sh on local-task and hip: 11 cases per device pass on the final head (decode B=1, B=3 with biases, B=2 with a dt clamp; prefill real_len 100, 256, 2, 0; real_len 0 and 77 from a carried state; real_len 200 at chunk 64 from a carried state; real_len 100 with a dt clamp), worst y error 1.4e-6 against tolerance 5e-5. Each case added in review fails under its targeted mutation.
  • spike/openxla/ssm_lowering_measure.py at 256 and 4096 for chunked Q=64/128/256, associative, sequential.
  • cargo fmt --all -- --check; clippy -D warnings on mlxcel-xla (--all-targets, and lib plus tests with --features iree) and on the xla_ssm_probe example.

Closes #3337

Epic #564 needs a recurrent mixing primitive before any SSM or hybrid family can run on the OpenXLA/IREE backend. The prefill scan was the open lowering question: the builder has no while op and IREE-CUDA rejects scatter.

emitter/ssm.rs adds the causal depthwise conv1d (prefill, tail, step), the selective-scan step, and the full Mamba2 mixer in prefill and decode form, with SsmConfig next to MoeConfig. emitter/ssm_scan.rs holds the prefill forms: chunked SSD (chosen, chunk 128), a log-depth associative scan, and a sequential unroll, all from dot_general, pad, slices, select and reduce_window. Scan contractions use a new Builder::dot_general_keep_f32, so the recurrence stays f32 on the f16 path. The prefill mixer takes conv0 as the conv's left context, so real_len 0 returns h0 and conv0 unchanged.

emit_ssm_probe (model.rs) emits one mixer layer; ssm_probe.rs runs it through the auxiliary IREE ABI; examples/xla_ssm_probe.rs and spike/openxla/ssm_oracle.py compare it against HF Mamba2Mixer.torch_forward in fp32. spike/openxla/FINDINGS_ssm.md records the measurements behind the decision.

Validation: ssm_gate.sh passes all 8 cases on local-task and hip (max-abs y below 1e-6); chunked SSD at 4096 rows compiles in under 1 s on llvm-cpu and rocm with 157 ops and 33 dispatches, error 6.7e-6. mlxcel-xla lib tests, dense goldens, fmt and clippy pass.

Refs #3337
@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
The gate had no case where the inter-chunk decay reaches y: with a zero h0 and at most two chunks the state entering each chunk needs no decay, and the one carried-state case fit in a single chunk. Zeroing the chunk-level decay matrix left every y within 1e-6 and was caught only through h_T. HF's default time_step_limit is (0, inf), so the dt clamp in discretize_dt was never executed either.

ssm_oracle.py gains --time-step-limit LO HI, and ssm_gate.sh adds three cases: a carried-state prefill of 200 rows at chunk 64, and prefill and decode with dt clamped to [0.01, 0.05] (padded rows still at dt = 0). All pass on local-task and hip within 1.4e-6; with the chunk decay zeroed the multi-chunk case fails with y off by 1.05, and with the clamp removed both clamp cases fail by about 2e-2.

FINDINGS_ssm.md records the new rows, the dispatch range, and that a f32-result prefill conv (convolution_f32_accumulate) is rejected by iree-compile for the depthwise mixed-type case. Fixes a stale count in a test comment.

Refs #3337
@inureyes

Copy link
Copy Markdown
Member Author

Implementation review

Checked the chunked SSD against HF Mamba2Mixer.torch_forward: discretization, the segsum built from non-positive sums only (no exp of positive values), repeat_interleave group mapping, D skip, gated norm order, and the chunk-level dot_general carry. It is the same math as HF's inter-chunk recurrence. Padding, real_len = 0, real_len < K-1 and carried-state continuation are correct. dot_general_keep_f32, abs and log_plus_one are additive, and the full mlxcel-xla lib suite including the dense goldens passes.

Mutation checks against the gate: wrong group mapping and an off-by-one segsum mask fail. Zeroing the chunk-level decay passed every y check and was caught only by h_T, and the dt clamp was never executed. 2283ee0 adds a 4-chunk carried-state case and dt-clamp prefill and decode cases. All 11 cases pass on local-task and hip, and each new case fails under its mutation.

Left as is (LOW): on the f16 path the prefill conv result is f16 while the decode conv is f32. convolution_f32_accumulate does not compile in IREE for this depthwise mixed-type conv, so the note in FINDINGS_ssm.md points at a K-tap f32 multiply-add if #3338 needs it.

SsmConfig::validate now computes d_inner, conv_dim, in_proj_dim, the H*P*N state and the (K-1)*conv_dim tail with checked arithmetic. In release builds a wrapped H*P could satisfy the conv_dim equation with absurd dims, which matters once #3338 reads these from config.json. It also rejects a +inf dt floor, a -inf dt ceiling, and a negative or non-finite norm_eps, which make every state NaN.

The probe spec rejects zero rows or hidden (the chunked scan divided by zero) and rows past i32, and computes conv_dim and expected buffer lengths with checked products; emit_ssm_probe_with asserts the same instead of hitting the divide. The FFI layer already re-validated lengths, so no out-of-bounds read was reachable.

The .npy reader moves from the example into ssm_probe as parse_npy_f32 with bounds-checked header parsing, a checked element count and an exact data length, so a truncated file is an error rather than a slice panic. The example now requires each input's .npy shape to match the probe's declared shape, rejects real_len above rows or past i32, and errors on a malformed time_step_limit or norm_eps instead of indexing or defaulting to infinity. The probe module builds under cfg(test) so these checks run in the plain unit gate. The README and measurement docstring use a mktemp -d directory instead of fixed /tmp paths.

Validated with the mlxcel-xla lib unit gate, clippy -D warnings with and without iree and on the example, and the SSM gate on local-task and hip.

Refs #3337
@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review

No CRITICAL or HIGH findings. The IREE shim boundary was already safe: IreeAuxiliaryModule::load and invoke recheck every buffer length against its shape with checked arithmetic, so a short buffer could not reach the FFI. The scripts load .npy with numpy's default allow_pickle=False, build the HF mixer locally (no trust_remote_code, no hub download), and pass subprocess arguments as lists.

Fixed in cf1bfc0:

  • MEDIUM: SsmConfig::validate used unchecked products, so in release a wrapped H*P could satisfy the conv_dim equation with absurd dims. It now checks d_inner, conv_dim, in_proj_dim, H*P*N and (K-1)*conv_dim, and rejects a +inf dt floor, a -inf dt ceiling, and a negative or non-finite norm_eps.
  • LOW: zero rows reached t.div_ceil(0) in the chunked scan. The probe spec returns an error for zero rows or hidden and for rows past i32, and the emitter asserts with a clear message.
  • LOW: the example's .npy reader could panic on a truncated header and ignored the file's shape. It is now parse_npy_f32 in the library with bounds-checked parsing and an exact data length, and the example requires each input's shape to match the probe's declared shape. real_len above rows, a short time_step_limit and a non-numeric norm_eps are errors instead of a panic or a silent infinity.
  • LOW: the README used fixed /tmp/ssm* paths, where a planted link would redirect the fixed-name .npy writes. It now uses mktemp -d.

Left for #3338:

  • Cross-check every config dim against the checkpoint tensor shapes, which is the real upper bound on them, and clamp real_len to [0, capacity] on the host.
  • MEDIUM, performance at long context: reduce_window_prefix_add lowers as a full-width window, so exp_segsum costs O(L^2) per row. Intra-chunk that is T*H*Q^2 adds (about 2x the y_diag contraction at Q=128, P=64), and the inter-chunk carry is H*(T/Q)^3 adds on an [H, nc+1, nc+1] tensor. That is negligible at 4096 (nc=32) but overtakes the intra-chunk work near T=185k and needs about 6 GiB per intermediate at T=1M. If feat(xla): Mamba2 config, mixer schedule, weights, state-threaded graphs #3338 targets long contexts, the carry needs a bounded form (a prefix sum over chunk totals, or a scan over chunks), measured against HF on hip.

Validation: mlxcel-xla lib unit gate, clippy -D warnings with and without iree and on the example, and ssm_gate.sh on local-task and hip.

Add an Unreleased entry for the SSM scan primitive and Mamba2 probe, noting it is not reachable from generate until #3339. Allowlist MLXCEL_SSM_MODE and MLXCEL_SSM_T, which only the opt-in ignored dump_ssm_probe_for_execution_check test reads, so check_env_var_docs.py passes.

Validation: check_env_var_docs.py OK, check_used_by.py OK, cargo fmt --check clean, clippy -D warnings clean on mlxcel-xla lib/tests with and without iree and on the xla_ssm_probe example, mlxcel-xla lib tests 479 passed.

Refs #3337
@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 23, 2026
@inureyes
inureyes merged commit 39d7bbf into main Nov 23, 2026
63 of 65 checks passed
@inureyes
inureyes deleted the feature/issue-3337-ssm-scan-primitive branch November 23, 2026 18:44
@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): SSM scan primitive (conv1d + selective scan) with HF oracle

1 participant