Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions examples/xla_ssm_model_check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,11 @@
// See the License for the specific language governing permissions and
// limitations under the License.

//! Whole-model Mamba2 execution check (issue #3338).
//! Whole-model Mamba-family execution check (issues #3338 and #3348).
//!
//! Loads a Mamba2 checkpoint with the production config reader and weight
//! loader, compiles the state-threaded token prefill for `--device`, and runs
//! Loads a Mamba1, Falcon-Mamba, or Mamba2 checkpoint with the production
//! config reader and weight loader, compiles the state-threaded token prefill
//! for `--device`, and runs
//! `--tokens` twice: once in a single call, and once split at `--split` into
//! two calls that hand the returned state to the second call, then feeds the
//! same tokens one at a time through the decode step (state in module globals).
Expand Down
12 changes: 11 additions & 1 deletion examples/xla_ssm_probe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.

//! Single-layer Mamba2 mixer execution check (issue #3337).
//! Single-layer Mamba2/Mamba1/Falcon-Mamba execution check (issues #3337, #3348).
//!
//! Reads the inputs `spike/openxla/ssm_oracle.py --emit-inputs DIR` wrote,
//! compiles the emitter's SSM probe for `--device`, runs it through the IREE
Expand Down Expand Up @@ -134,6 +134,11 @@ fn spec_from_meta(meta: &Value, args: &Args) -> Result<SsmProbeSpec, String> {
.ok_or("meta.json norm_eps is not a number")? as f32;
let flag = |key: &str| field(meta, key).map(|v| v.as_bool().unwrap_or(false));
Ok(SsmProbeSpec {
kind: meta
.get("kind")
.and_then(Value::as_str)
.unwrap_or("mamba2")
.to_string(),
hidden: usize_field(meta, "hidden")?,
n_heads: usize_field(meta, "n_heads")?,
head_dim: usize_field(meta, "head_dim")?,
Expand All @@ -149,6 +154,11 @@ fn spec_from_meta(meta: &Value, args: &Args) -> Result<SsmProbeSpec, String> {
Some(size) => size,
None => usize_field(meta, "chunk_size")?,
},
dt_rank: meta.get("dt_rank").and_then(Value::as_u64).unwrap_or(0) as usize,
bcdt_norm: meta
.get("bcdt_norm")
.and_then(Value::as_bool)
.unwrap_or(false),
rows: usize_field(meta, "rows")?,
decode: field(meta, "mode")?.as_str() == Some("decode"),
form: args.form.clone().unwrap_or_else(|| "chunked".to_string()),
Expand Down
59 changes: 59 additions & 0 deletions spike/openxla/FINDINGS_ssm.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,3 +209,62 @@ The exact production StableHLO modules emitted at capacity 256 were recompiled u
The server gate used four distinct prompts of 5, 8, 13, and 5 tokens with `--ctx-size 2048 --max-batch-size 4`. It disabled recurrent prefix caching as designed, compiled the 256 and 4096 capacity buckets, and loaded in 10.43 s. All responses finished by the requested length.

The existing chunked SSD lowering therefore needs no CUDA-specific change. This PR changes only the findings record, so it does not require another ROCm gate beyond the already recorded #3339 and #3340 runs.

## Mamba1 diagonal scan (issue #3348)

Mamba1 and Falcon-Mamba use the same f32 diagonal recurrence but do not use
Mamba2's SSD contraction. Prefill is partitioned at `chunk_size = 128` in
production. Each partition materializes at most `[128,D,N]` `log_a` and input
terms and carries only `[D,N]` between partitions, so the 4096-row capacity
never creates a `[4096,D,N]` value. Within a partition, a Hillis-Steele prefix
scan composes affine pairs `(a, u)` as `(a_r*a_l, u_r + a_r*u_l)` in
`ceil(log2(Q))` levels. This replaced an initial per-row unroll that emitted
62,156 lines / 5.35 MiB and did not compile inside a 180 s CPU budget at 4096.

The production-dimension (`D=1536`, `N=16`, `dt_rank=48`) capacity-4096 graph
is 3,116 lines / 320 KiB. Source and emitted-shape inspection find the chunk
shape `[128,1536,16]` and no `[4096,1536,16]` tensor. The structural regression
also caps the graph below 4,000 lines and 80 concatenations, so a per-row scan
or output assembly cannot silently return.

The independent reference is Transformers 5.12.1 on CPU (`torch==2.12.1+cpu`),
calling `MambaMixer.slow_forward` or `FalconMambaMixer.slow_forward` directly
with seeded fp32 weights. The XLA side ran through the real auxiliary ABI and
IREE `local-task` runtime. Tolerance is `5e-5`.

| case | rows / real length | compile s | run s | max-abs y | max-abs h | max-abs conv |
|------|-------------------:|----------:|------:|----------:|----------:|-------------:|
| Mamba1 padded prefill | 9 / 7 | 1.61 | <0.001 | 2.235e-8 | 9.313e-10 | 0 |
| Mamba1 full prefill (same compiled shape) | 9 / 9 | cached | 0.002 | 2.235e-8 | 1.863e-9 | 0 |
| Mamba1 decode, B=3 | 3 / 1 | 0.87 | <0.001 | 2.980e-8 | 5.960e-8 | 0 |
| Falcon-Mamba decode, B=3 | 3 / 1 | 1.01 | <0.001 | 5.960e-8 | 5.960e-8 | 0 |

At the real 130M mixer dimensions and capacity 4096 (`real_len=3584`), direct
`llvm-cpu` compilation completed in 10.64 s at 228.2 MiB peak compiler RSS.
The same graph through the IREE shim compiled in 9.96 s, ran on `local-task` in
0.862 s, and the whole process peaked at 331.1 MiB RSS. Against Transformers'
independent sequential Mamba slow path, max-abs errors were `y=3.427e-7`,
`h=1.246e-8`, and conv tail `0` (tolerance `5e-5`).

Whole-model CPU checks use the official
`state-spaces/mamba-130m-hf` revision
`1e76775f628fbf1350fbe4dbb3d971ba64af25a1` and a seeded two-layer
`FalconMambaForCausalLM` checkpoint. Each check compares whole prefill, split
prefill with carried state, and token-by-token decode against Transformers
5.12.1 fp32. All argmaxes match; the Mamba checkpoint's worst max-abs error is
`2.043e-3`, and Falcon-Mamba's is `4.768e-7` (whole-model tolerance `3e-2`).

Reproduce the padded Mamba1 row (after exporting the pinned IREE environment):

```bash
PY=/home/inureyes/Development/mlxcel/spike/openxla/.venv/bin/python
$PY spike/openxla/ssm_oracle.py --kind mamba1 --dims tiny \
--emit-inputs /tmp/mamba1-prefill --mode prefill --capacity 9 \
--real-len 7 --chunk-size 4
cargo run --features xla-iree --example xla_ssm_probe -- \
--inputs /tmp/mamba1-prefill --device local-task --out /tmp/mamba1-out
$PY spike/openxla/ssm_oracle.py --check /tmp/mamba1-out
```

These are CPU execution results only. The required `hip` probe and whole-model
rows, CLI, server, cancellation, and slot-recycling evidence remain pending.
87 changes: 60 additions & 27 deletions spike/openxla/ssm_model_check.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Whole-model Mamba2 check against HF `Mamba2ForCausalLM` in fp32 (issue #3338).
"""Whole-model Mamba-family check against Transformers in fp32 (issues #3338/#3348).

Runs the mlxcel-xla state-threaded token prefill for a Mamba2 checkpoint
Runs the mlxcel-xla state-threaded token prefill for a Mamba-family checkpoint
through the real IREE shim (`examples/xla_ssm_model_check.rs`, which loads the
checkpoint with the production config reader and weight loader) and compares
the last-token logits with HF's slow path (`torch_forward`, no `mamba_ssm`
Expand All @@ -12,6 +12,9 @@
cargo build --release --features xla-iree --example xla_ssm_model_check
# a seeded two-layer synthetic model (n_groups = 2 < num_heads, biased, untied):
$PY spike/openxla/ssm_model_check.py --synthetic OUT/synthetic --device local-task
# a seeded Falcon-Mamba with weightless B/C/dt RMSNorms:
$PY spike/openxla/ssm_model_check.py --synthetic OUT/falcon --synthetic-kind falcon_mamba \
--device local-task
# a real checkpoint:
scripts/rocm_gpu_guard.sh --hold -- $PY spike/openxla/ssm_model_check.py \
--model models/hf/mamba2-130m --device hip --tokens 200 --capacity 256
Expand All @@ -35,48 +38,72 @@
TOL = 3e-2


def build_synthetic(out: Path, seed: int) -> Path:
"""Save a small seeded Mamba2ForCausalLM with every optional tensor."""
from transformers import Mamba2Config, Mamba2ForCausalLM
def build_synthetic(out: Path, seed: int, kind: str) -> Path:
"""Save a small seeded Mamba-family model with every optional tensor."""
from transformers import (
FalconMambaConfig,
FalconMambaForCausalLM,
Mamba2Config,
Mamba2ForCausalLM,
)

torch.manual_seed(seed)
config = Mamba2Config(
vocab_size=96,
hidden_size=64,
num_hidden_layers=2,
num_heads=8,
head_dim=16,
expand=2,
state_size=16,
n_groups=2,
conv_kernel=4,
use_bias=True,
use_conv_bias=True,
tie_word_embeddings=False,
chunk_size=256,
)
model = Mamba2ForCausalLM(config).float().eval()
if kind == "mamba2":
config = Mamba2Config(
vocab_size=96,
hidden_size=64,
num_hidden_layers=2,
num_heads=8,
head_dim=16,
expand=2,
state_size=16,
n_groups=2,
conv_kernel=4,
use_bias=True,
use_conv_bias=True,
tie_word_embeddings=False,
chunk_size=256,
)
model = Mamba2ForCausalLM(config).float().eval()
else:
config = FalconMambaConfig(
vocab_size=96,
hidden_size=32,
num_hidden_layers=2,
state_size=4,
expand=2,
conv_kernel=4,
time_step_rank=4,
use_bias=True,
use_conv_bias=True,
tie_word_embeddings=False,
# Force Transformers' independent sequential recurrence.
use_associative_scan=False,
)
model = FalconMambaForCausalLM(config).float().eval()
with torch.no_grad():
# The default init leaves dt_bias / D near constant; spread them so a
# mixed-up head order shows up in the logits.
for layer in model.backbone.layers:
mixer = layer.mixer
mixer.dt_bias.uniform_(-3.0, 0.0)
dt_bias = mixer.dt_bias if kind == "mamba2" else mixer.dt_proj.bias
dt_bias.uniform_(-3.0, 0.0)
mixer.D.uniform_(0.5, 1.5)
mixer.A_log.uniform_(0.0, 1.5)
mixer.norm.weight.uniform_(0.5, 1.5)
if kind == "mamba2":
mixer.norm.weight.uniform_(0.5, 1.5)
layer.norm.weight.uniform_(0.5, 1.5)
out.mkdir(parents=True, exist_ok=True)
model.save_pretrained(out, safe_serialization=True)
return out


def hf_logits(model_dir: Path, tokens: list[int]) -> np.ndarray:
from transformers import Mamba2ForCausalLM
from transformers import AutoModelForCausalLM

# safetensors only: a pickled `pytorch_model.bin` in an untrusted
# checkpoint directory must not be unpickled.
model = Mamba2ForCausalLM.from_pretrained(
model = AutoModelForCausalLM.from_pretrained(
model_dir, torch_dtype=torch.float32, use_safetensors=True
).eval()
with torch.no_grad():
Expand Down Expand Up @@ -115,8 +142,14 @@ def compare(name: str, got: np.ndarray, want: np.ndarray) -> dict:
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
src = ap.add_mutually_exclusive_group(required=True)
src.add_argument("--model", help="a Mamba2 checkpoint directory")
src.add_argument("--model", help="a Mamba-family checkpoint directory")
src.add_argument("--synthetic", metavar="DIR", help="build a seeded model here")
ap.add_argument(
"--synthetic-kind",
default="mamba2",
choices=["mamba2", "falcon_mamba"],
help="architecture built by --synthetic (default: mamba2)",
)
ap.add_argument("--device", default="local-task")
ap.add_argument("--precision", default="f32", choices=["f32", "f16", "bf16"])
# `inout` is what the single-sequence runtime (`IreeLlama`) emits and
Expand All @@ -132,7 +165,7 @@ def main() -> int:
args = ap.parse_args()

model_dir = (
build_synthetic(Path(args.synthetic), args.seed)
build_synthetic(Path(args.synthetic), args.seed, args.synthetic_kind)
if args.synthetic
else Path(args.model)
)
Expand Down
Loading
Loading