Repository navigation
feat(xla): add SSM scan primitive with HF oracle and prefill decision - #3360
Conversation
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
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
Implementation reviewChecked the chunked SSD against HF Mutation checks against the gate: wrong group mapping and an off-by-one segsum mask fail. Zeroing the chunk-level decay passed every Left as is (LOW): on the f16 path the prefill conv result is f16 while the decode conv is f32. |
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
Security and performance reviewNo CRITICAL or HIGH findings. The IREE shim boundary was already safe: Fixed in cf1bfc0:
Left for #3338:
Validation: mlxcel-xla lib unit gate, clippy |
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
…m-scan-primitive # Conflicts: # CHANGELOG.md
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_forwardin fp32 onlocal-taskandhip, and records the measured prefill-lowering decision inspike/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.SsmConfigsits next toMoeConfig.emitter/ssm_scan.rs: three prefill forms built fromdot_general,pad, slices,selectandreduce_window(no scatter, nowhile). Chunked SSD is the chosen one; the associative and sequential forms stay selectable for the measurements.Builder::dot_general_keep_f32, so the recurrence stays f32 on the f16 path.emit_ssm_probe(model.rs), thedump_ssm_probe_for_execution_checktest,ssm_probe.rs(runs the probe through the auxiliary IREE ABI),examples/xla_ssm_probe.rs,spike/openxla/ssm_oracle.py,ssm_gate.sh, andssm_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 onllvm-cpuandrocmgfx1151, max-absyerror 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 onedot_generalagainst 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
SsmConfigfields and thessm.rsfunction signatures are unchanged from the issue. Additions only:SsmConfig::{d_inner, in_proj_dim, validate}(validate also requiresconv_kernel >= 2),SSM_DEFAULT_CHUNK_SIZE = 128,ssm_state_types, andmamba2_mixer_prefill_form.emit_ssm_probetakes an extrahiddenargument,emit_ssm_probe(c, hidden, t, mode), becauseSsmConfigcarries no model width.mamba2_mixer_prefillusesconv0as the conv's left context and in the tail slice, so a continued prefill is exact andreal_len = 0returnsh0andconv0unchanged.Changes during review
torch_forwardterm 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 everyycheck, and HF's defaulttime_step_limit(0, inf) meant removing the dt clamp was invisible. Added--time-step-limitto 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.SsmConfig::validatecomputes its products with checked arithmetic and rejects non-finite dt limits and a negative or non-finitenorm_eps(MEDIUM: a wrappedH*Pcould satisfy theconv_dimequation in release builds). Zero rows and wrapping widths are rejected before emitting. The example's.npyreader moved intossm_probe.rsas a bounds-checked parser that checks the declared shape and exact data length. Fixed/tmppaths in the README and the measurement script becamemktemp -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, clampreal_lenon the host, and theH*(T/Q)^3cross-chunk carry cost if contexts grow far beyond 4096.Test plan
cargo test --profile test-fast -p mlxcel-xla --lib: 479 passed on the final head, including thessmtests, the new validation tests and the unchanged dense goldens.spike/openxla/ssm_gate.shonlocal-taskandhip: 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), worstyerror 1.4e-6 against tolerance 5e-5. Each case added in review fails under its targeted mutation.spike/openxla/ssm_lowering_measure.pyat 256 and 4096 for chunked Q=64/128/256, associative, sequential.cargo fmt --all -- --check; clippy-D warningson mlxcel-xla (--all-targets, and lib plus tests with--features iree) and on thexla_ssm_probeexample.Closes #3337