diff --git a/TECHNICAL_REPORTS/3413-mamba1-falcon-mamba-selective-scan-20261125.en.md b/TECHNICAL_REPORTS/3413-mamba1-falcon-mamba-selective-scan-20261125.en.md new file mode 100644 index 000000000..919d7c3ff --- /dev/null +++ b/TECHNICAL_REPORTS/3413-mamba1-falcon-mamba-selective-scan-20261125.en.md @@ -0,0 +1,77 @@ +# PR #3413: Mamba1 and Falcon-Mamba selective scan + +**Date**: 2026-11-25 + +**Status**: Integrated CUDA acceptance passed; ROCm acceptance passed at the pre-integration source SHA + +## Executive Summary + +This PR adds native OpenXLA/IREE execution for Mamba1 and Falcon-Mamba models. It covers configuration parsing, checkpoint validation, weight ordering, f32 recurrent state, chunk-bounded prefill, batched decode, independent Transformers references, and a registered whole-model decode golden. + +The prefill mixer constructs recurrence operands inside 128-row chunks and applies a log-depth affine prefix scan within each chunk. A 4096-token graph therefore never creates a full `[4096, d_inner, state_size]` tensor, while the carried state remains `[d_inner, state_size]` per layer. + +## Problem Statement + +The existing recurrent path supported Mamba2's grouped state-space layout, but Mamba1 uses a different diagonal recurrence. Each channel has its own decay, input projection, and skip parameter; B and C vary by token; the convolutional history and recurrent state must both survive prefill and batched decode. Falcon-Mamba additionally applies weightless RMS normalization to the B, C, and dt projections. + +A direct row-by-row StableHLO lowering scales graph depth and concatenation count with the prompt capacity. Materializing all recurrence operands before slicing them into chunks also leaves a full `[T,D,N]` value in the graph, which is unacceptable for a 4096-token, 1536-channel, 16-state model. + +## Change Summary + +The configuration layer recognizes `mamba` and `falcon_mamba`, including Hugging Face names and the original state-spaces aliases. Canonical `use_bias` and `use_conv_bias` keys take precedence over `bias` and `conv_bias`. Unsupported LayerNorm configs are rejected, and active block and mixer epsilons must be finite and positive. + +The emitter adds Mamba1 checkpoint names, tensor shapes, state allocation, convolution carry, prefill, and decode. The recurrence is evaluated in f32 even when surrounding values use another dtype. The shared recurrent ABI remains compatible with Mamba2 and Nemotron-H, including compact KV indices, grouped normalization, hybrid layer schedules, and MoE configuration added by the integrated base. + +The Python oracle and Rust model-check harness now cover an official Mamba checkpoint and a seeded synthetic Falcon-Mamba model. The compact registered fixture exercises whole-model Mamba decode and freezes its StableHLO bytes. + +## Technical Decisions + +### Compose affine recurrence pairs in log depth + +Each step is represented as `(a_t, u_t)` for `h_t = a_t * h_(t-1) + u_t`. The inclusive scan composes pairs as `(a_r * a_l, u_r + a_r * u_l)` at doubling offsets. This reduces each bounded block from a linear chain to logarithmic depth while preserving the recurrence order. + +### Construct recurrence operands inside the mixer chunk loop + +The model-specific prefill path first slices `x`, `dt`, B, and C to one chunk. Only then does it broadcast and multiply them into `log_a` and `bx [chunk,D,N]`. The generic scan receives only those bounded values. This producer boundary, rather than post-hoc slicing of full tensors, is what prevents a capacity-sized `[T,D,N]` allocation. + +### Keep recurrent state and sensitive arithmetic in f32 + +Decay, affine composition, state carry, B/C/dt normalization, and readout accumulation use f32. The threaded state shape remains `[layers,d_inner,state_size]`, with convolution history stored separately, so split prefill and one-token decode follow the same numerical contract as whole prefill. + +### Fail closed on unsupported configuration variants + +`rms_norm = false`, non-SiLU activation, malformed dimensions, and non-finite or non-positive active epsilons are rejected before graph construction. Legacy bias aliases are accepted without allowing them to override canonical keys. + +## Validation + +The integrated executable source is `abd1520fd669624cb668bd558b98e332d0955093`, based on the merged PR #3411. `cargo test -p mlxcel-xla --lib -- --test-threads=4` passed 555 tests with 21 ignored. The registered byte-exact golden test passed for Mamba1, Mamba2, and Nemotron-H. Formatting and focused clippy with `-D warnings` passed. The environment-variable documentation checker passed with 396 discovered names, 265 documented names, and 131 allowlisted names; its Python suite passed all 15 tests. + +On NVIDIA GB10, the exact integrated source compiled the capacity-4096 CUDA probe in 5.03 seconds and ran it in 0.319 seconds under `gpu-lock`. Process peak RSS was 203200 KiB. The independent CPU oracle reported maximum absolute differences of `3.651e-7` for output, `1.141e-8` for final recurrent state, and `1.371e-6` for convolution state. The timing log is `/tmp/epic564-plan/3348-cuda-cap4096-integrated-abd1520f-time.log`; the result bundle is `/tmp/issue3348-cap4096-integrated-abd1520f`. These are correctness and compile-footprint observations, not throughput claims. + +The structural capacity probe confirmed that the 4096-token graph has no `[4096,D,N]` tensor. It produced 3,116 StableHLO lines (320 KiB); a direct CPU compile took 10.64 seconds at 228.2 MiB peak RSS and ran in 0.862 seconds. + +On IREE local-task, official `state-spaces/mamba-130m-hf` revision `1e76775f628fbf1350fbe4dbb3d971ba64af25a1` matched an independent Transformers 5.12.1 CPU fp32 reference for whole prefill, split prefill, and decode. The worst maximum absolute difference was `1.488e-4`, with the same argmax. The seeded synthetic `FalconMambaForCausalLM` covered its B/C/dt RMS normalization and matched whole, split, and decode paths with worst maximum absolute difference `3.725e-7` and the same argmax. + +ROCm gfx1151 acceptance was captured at exact source `3a1688f7daaf9bae8bea09997b804e6509357c25`: 551 library tests passed with 21 ignored; local-task and HIP mixer probes covered 12 cases; the real Mamba and synthetic Falcon reference and CLI checks matched 40/40 tokens; B4/N8 batching, cancellation, slot recycling, and four concurrent server requests passed; capacity 4096 compiled; five hybrid tests and Mamba2 regressions passed; and the integrated real Nemotron-H checks passed. All ROCm device work used the ROCm guard. HTTP checks compare rendered text because that API does not expose token IDs, and optimized `test-fast` binaries make no performance claim. The [ROCm acceptance record](https://github.com/lablup/mlxcel/pull/3413#issuecomment-7147199610) contains commands and raw-evidence provenance. + +After that ROCm run, the branch was rebased onto PR #3411. The Mamba1 scan, parser, recurrent emitter, and Python oracle blobs are byte-identical to `3a1688f7`; the integration adds disjoint Nemotron-H MoE paths and the CI allowlist correction. CUDA, full library tests, and registered goldens were rerun on the integrated source. ROCm was not rerun after this source-neutral integration, so the two exact-SHA evidence boundaries remain explicit. + +## Learning Points + +Bounding a consumer is insufficient when the producer already creates a capacity-sized tensor. The safe boundary must begin before broadcasting the token projections into recurrence operands. + +Recurrent model validation needs both numerical references and state-transition coverage. Whole-prefill parity alone cannot detect a wrong carried convolution tail, a stale recycled slot, or a discrepancy between split prefill and decode. + +## Follow-up Actions + +- [x] Validate the integrated capacity-4096 graph on CUDA with an independent oracle. +- [x] Validate real Mamba, synthetic Falcon-Mamba, batching, serving, cancellation, and recurrent regressions on ROCm gfx1151. +- [x] Rebase onto the merged Nemotron-H MoE work without changing Mamba1 numerical-source blobs, then rerun integrated library, golden, lint, and CUDA gates. + +## References + +- Issue #3348 +- Epic #564 +- PR #3413 +- `spike/openxla/FINDINGS_ssm.md` +- [ROCm acceptance record](https://github.com/lablup/mlxcel/pull/3413#issuecomment-7147199610) diff --git a/TECHNICAL_REPORTS/3413-mamba1-falcon-mamba-selective-scan-20261125.ko.md b/TECHNICAL_REPORTS/3413-mamba1-falcon-mamba-selective-scan-20261125.ko.md new file mode 100644 index 000000000..610c927f1 --- /dev/null +++ b/TECHNICAL_REPORTS/3413-mamba1-falcon-mamba-selective-scan-20261125.ko.md @@ -0,0 +1,77 @@ +# PR #3413: Mamba1 및 Falcon-Mamba 선택적 스캔 + +**날짜**: 2026-11-25 + +**상태**: 통합 소스 CUDA 검증 통과, 통합 전 정확한 소스 SHA에서 ROCm 검증 통과 + +## 요약 + +이 PR은 Mamba1과 Falcon-Mamba 모델을 OpenXLA/IREE에서 네이티브로 실행하도록 지원합니다. 설정 파싱, 체크포인트 검증, 가중치 순서, f32 순환 상태, 청크 한정 프리필, 배치 디코드, 독립 Transformers 참조값, 등록된 전체 모델 디코드 골든을 함께 추가합니다. + +프리필 믹서는 128행 청크 안에서만 순환 피연산자를 만들고, 각 청크에는 로그 깊이의 아핀 접두 스캔을 적용합니다. 따라서 4096토큰 그래프에서도 완전한 `[4096, d_inner, state_size]` 텐서를 만들지 않으며, 레이어별 전달 상태는 `[d_inner, state_size]`로 유지됩니다. + +## 문제 정의 + +기존 순환 경로는 Mamba2의 그룹 상태 공간 구조를 지원했지만, Mamba1은 서로 다른 대각 순환식을 사용합니다. 각 채널은 고유한 감쇠, 입력 투영, 스킵 매개변수를 가지며 B와 C는 토큰마다 달라집니다. 합성곱 이력과 순환 상태는 프리필과 배치 디코드 모두에서 보존되어야 합니다. Falcon-Mamba는 B, C, dt 투영에 가중치 없는 RMS 정규화도 적용합니다. + +행을 하나씩 펼치는 StableHLO 구현은 프롬프트 용량에 비례해 그래프 깊이와 연결 연산 수가 증가합니다. 또한 모든 순환 피연산자를 먼저 만든 뒤 청크로 자르면 4096토큰, 1536채널, 상태 크기 16 모델에서 완전한 `[T,D,N]` 값이 그래프에 남습니다. + +## 변경 요약 + +설정 계층은 Hugging Face 필드와 기존 state-spaces 별칭을 모두 사용해 `mamba`와 `falcon_mamba`를 인식합니다. 표준 `use_bias`와 `use_conv_bias`는 `bias`와 `conv_bias`보다 우선합니다. 지원하지 않는 LayerNorm 설정은 거부하며, 실제로 사용하는 블록 및 믹서 엡실론은 유한한 양수여야 합니다. + +이미터에는 Mamba1 체크포인트 이름, 텐서 형상, 상태 할당, 합성곱 상태 전달, 프리필, 디코드를 추가했습니다. 주변 값이 다른 자료형이어도 순환식은 f32로 계산합니다. 공유 순환 ABI는 통합 베이스의 Mamba2와 Nemotron-H 기능인 압축 KV 인덱스, 그룹 정규화, 하이브리드 레이어 일정, MoE 설정과 호환됩니다. + +Python 오라클과 Rust 모델 검사 하네스는 공식 Mamba 체크포인트와 시드가 고정된 합성 Falcon-Mamba 모델을 검증합니다. 작은 등록 픽스처는 전체 모델 Mamba 디코드를 실행하고 StableHLO 바이트를 고정합니다. + +## 기술적 선택 + +### 아핀 순환 쌍을 로그 깊이로 합성 + +각 스텝을 `h_t = a_t * h_(t-1) + u_t`를 나타내는 `(a_t, u_t)`로 표현합니다. 포괄 스캔은 간격을 두 배씩 늘리면서 `(a_r * a_l, u_r + a_r * u_l)`로 쌍을 합성합니다. 순환 순서를 유지하면서 각 한정 블록을 선형 체인에서 로그 깊이로 낮춥니다. + +### 믹서 청크 루프 안에서 순환 피연산자 생성 + +모델 전용 프리필 경로는 먼저 `x`, `dt`, B, C를 한 청크로 자릅니다. 그 뒤에만 브로드캐스트와 곱셈으로 `log_a`와 `bx [chunk,D,N]`를 만듭니다. 범용 스캔은 이 한정된 값만 받습니다. 완전한 텐서를 만든 뒤 자르는 방식이 아니라 이 생산자 경계가 용량 크기의 `[T,D,N]` 할당을 방지합니다. + +### 순환 상태와 민감한 계산을 f32로 유지 + +감쇠, 아핀 합성, 상태 전달, B/C/dt 정규화, 리드아웃 누적은 f32를 사용합니다. 전달 상태 형상은 `[layers,d_inner,state_size]`이고 합성곱 이력은 별도로 저장되므로, 분할 프리필과 단일 토큰 디코드는 전체 프리필과 같은 수치 계약을 따릅니다. + +### 지원하지 않는 설정을 조기에 거부 + +`rms_norm = false`, SiLU가 아닌 활성화, 잘못된 차원, 유한한 양수가 아닌 활성 엡실론은 그래프 생성 전에 거부합니다. 이전 bias 별칭은 허용하되 표준 키를 덮어쓸 수 없습니다. + +## 검증 + +통합 실행 소스는 병합된 PR #3411을 베이스로 한 `abd1520fd669624cb668bd558b98e332d0955093`입니다. `cargo test -p mlxcel-xla --lib -- --test-threads=4`에서 555개가 통과하고 21개가 무시되었습니다. Mamba1, Mamba2, Nemotron-H 등록 골든의 바이트 일치 검사도 통과했습니다. 포맷 검사와 `-D warnings`를 사용한 집중 clippy가 통과했습니다. 환경 변수 문서 검사기는 발견한 396개 중 265개 문서화, 131개 허용 목록으로 통과했고 Python 테스트 15개도 모두 통과했습니다. + +NVIDIA GB10에서 정확한 통합 소스의 용량 4096 CUDA 프로브는 `gpu-lock` 아래에서 5.03초에 컴파일되고 0.319초에 실행되었습니다. 프로세스 최대 RSS는 203200 KiB였습니다. 독립 CPU 오라클 대비 최대 절대 오차는 출력 `3.651e-7`, 최종 순환 상태 `1.141e-8`, 합성곱 상태 `1.371e-6`이었습니다. 시간 로그는 `/tmp/epic564-plan/3348-cuda-cap4096-integrated-abd1520f-time.log`, 결과 묶음은 `/tmp/issue3348-cap4096-integrated-abd1520f`에 있습니다. 이는 정확성과 컴파일 자원 관찰이며 처리량 주장에 해당하지 않습니다. + +구조적 용량 프로브는 4096토큰 그래프에 `[4096,D,N]` 텐서가 없음을 확인했습니다. StableHLO는 3,116행, 320 KiB였으며 직접 CPU 컴파일은 최대 RSS 228.2 MiB에서 10.64초, 실행은 0.862초가 걸렸습니다. + +IREE local-task에서 공식 `state-spaces/mamba-130m-hf` 리비전 `1e76775f628fbf1350fbe4dbb3d971ba64af25a1`은 전체 프리필, 분할 프리필, 디코드 모두에서 독립 Transformers 5.12.1 CPU fp32 참조와 일치했습니다. 최악의 최대 절대 오차는 `1.488e-4`였고 argmax가 같았습니다. 시드가 고정된 합성 `FalconMambaForCausalLM`은 B/C/dt RMS 정규화를 포함했으며 전체, 분할, 디코드에서 최악의 최대 절대 오차 `3.725e-7`과 같은 argmax를 기록했습니다. + +ROCm gfx1151 검증은 정확한 소스 `3a1688f7daaf9bae8bea09997b804e6509357c25`에서 수행되었습니다. 라이브러리 테스트 551개 통과 및 21개 무시, local-task/HIP 믹서 프로브 12개 경우, 실제 Mamba와 합성 Falcon의 참조 및 CLI 40/40 토큰 일치, B4/N8 배치, 취소, 슬롯 재활용, 동시 서버 요청 4개, 용량 4096 컴파일, 하이브리드 테스트 5개, Mamba2 회귀, 실제 Nemotron-H 통합 검증이 통과했습니다. 모든 ROCm 장치 작업은 ROCm 가드를 사용했습니다. HTTP API는 토큰 ID를 노출하지 않으므로 렌더링된 텍스트를 비교했으며, 최적화된 `test-fast` 바이너리는 성능 주장의 근거로 사용하지 않았습니다. [ROCm 검증 기록](https://github.com/lablup/mlxcel/pull/3413#issuecomment-7147199610)에 명령과 원시 증거 출처가 있습니다. + +ROCm 실행 이후 브랜치를 PR #3411 위로 리베이스했습니다. Mamba1 스캔, 파서, 순환 이미터, Python 오라클 blob은 `3a1688f7`과 바이트 단위로 같습니다. 통합으로 추가된 것은 분리된 Nemotron-H MoE 경로와 CI 허용 목록 수정입니다. 통합 소스에서 CUDA, 전체 라이브러리 테스트, 등록 골든을 다시 실행했습니다. ROCm은 이 수치 소스 중립 통합 후 다시 실행하지 않았으므로 두 정확한 SHA의 증거 경계를 명시적으로 구분합니다. + +## 학습 사항 + +소비자만 청크로 제한해서는 생산자가 이미 용량 크기 텐서를 만든 경우를 막을 수 없습니다. 토큰 투영을 순환 피연산자로 브로드캐스트하기 전부터 안전 경계를 적용해야 합니다. + +순환 모델 검증에는 수치 참조와 상태 전이 검증이 모두 필요합니다. 전체 프리필 일치만으로는 잘못 전달된 합성곱 꼬리, 재활용 슬롯의 오래된 상태, 분할 프리필과 디코드의 차이를 탐지할 수 없습니다. + +## 후속 작업 + +- [x] 통합된 용량 4096 그래프를 독립 오라클과 함께 CUDA에서 검증했습니다. +- [x] 실제 Mamba, 합성 Falcon-Mamba, 배치, 서빙, 취소, 순환 회귀를 ROCm gfx1151에서 검증했습니다. +- [x] Mamba1 수치 소스 blob을 바꾸지 않고 병합된 Nemotron-H MoE 작업 위로 리베이스한 뒤 통합 라이브러리, 골든, 린트, CUDA 검증을 다시 실행했습니다. + +## 참고 자료 + +- Issue #3348 +- Epic #564 +- PR #3413 +- `spike/openxla/FINDINGS_ssm.md` +- [ROCm 검증 기록](https://github.com/lablup/mlxcel/pull/3413#issuecomment-7147199610) diff --git a/examples/xla_ssm_model_check.rs b/examples/xla_ssm_model_check.rs index c4493d788..2008402e7 100644 --- a/examples/xla_ssm_model_check.rs +++ b/examples/xla_ssm_model_check.rs @@ -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). diff --git a/examples/xla_ssm_probe.rs b/examples/xla_ssm_probe.rs index c72ce08a6..79a0e1cf9 100644 --- a/examples/xla_ssm_probe.rs +++ b/examples/xla_ssm_probe.rs @@ -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 @@ -134,6 +134,11 @@ fn spec_from_meta(meta: &Value, args: &Args) -> Result { .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")?, @@ -149,6 +154,11 @@ fn spec_from_meta(meta: &Value, args: &Args) -> Result { 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()), diff --git a/scripts/ci/check_env_var_docs.py b/scripts/ci/check_env_var_docs.py index ba8f4a3f4..63c84c7f7 100755 --- a/scripts/ci/check_env_var_docs.py +++ b/scripts/ci/check_env_var_docs.py @@ -153,8 +153,8 @@ ("fixture-authoring: makes a #[cfg(test)] test in " "mlxcel-xla/src/validation.rs rewrite the committed StableHLO goldens", ( "MLXCEL_FREEZE_GOLDENS", + "MLXCEL_FREEZE_MAMBA1", "MLXCEL_FREEZE_MOE", - "MLXCEL_FREEZE_NEMOTRON_H", )), ("fixture-authoring: makes a #[cfg(test)] test in " "mlxcel-xla/src/emitter/nemotron_h_tests.rs rewrite the committed " diff --git a/spike/openxla/FINDINGS_ssm.md b/spike/openxla/FINDINGS_ssm.md index 0e27e39d3..c3e60e1ec 100644 --- a/spike/openxla/FINDINGS_ssm.md +++ b/spike/openxla/FINDINGS_ssm.md @@ -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. diff --git a/spike/openxla/ssm_model_check.py b/spike/openxla/ssm_model_check.py index 1b89d3872..1490746e0 100644 --- a/spike/openxla/ssm_model_check.py +++ b/spike/openxla/ssm_model_check.py @@ -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` @@ -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 @@ -35,36 +38,60 @@ 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) @@ -72,11 +99,11 @@ def build_synthetic(out: Path, seed: int) -> Path: 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(): @@ -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 @@ -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) ) diff --git a/spike/openxla/ssm_oracle.py b/spike/openxla/ssm_oracle.py index f318adc54..1114e5737 100644 --- a/spike/openxla/ssm_oracle.py +++ b/spike/openxla/ssm_oracle.py @@ -1,8 +1,8 @@ -"""HF fp32 oracle for the single-layer Mamba2 mixer probe (issue #3337). +"""HF fp32 oracle for single-layer Mamba2 and Mamba1 mixer probes. -Validates the mlxcel-xla SSM primitives (`emitter/ssm.rs`: causal conv1d, -selective scan, gated norm) against ONE genuine HF `Mamba2Mixer` run through its -slow path `torch_forward` (no `mamba_ssm`, no CUDA kernels), in fp32, with +Validates the mlxcel-xla SSM primitives (`emitter/ssm.rs`: causal conv1d and +selective scan) against a genuine HF `Mamba2Mixer`, `MambaMixer`, or +`FalconMambaMixer` slow path (no custom SSM or CUDA kernels), in fp32, with seeded random weights. Modeled on `moe_oracle.py`, but split into two steps so the XLA side runs through the real IREE shim (`examples/xla_ssm_probe.rs`): @@ -32,12 +32,17 @@ from torch import nn TOL = 5e-5 -PRESETS = { +MAMBA2_PRESETS = { # Small, but with G > 1 and G < H so the group broadcast is exercised. "tiny": dict(hidden_size=32, expand=2, head_dim=16, state_size=16, n_groups=2), # The state-spaces/mamba2-130m mixer dimensions. "mamba2-130m": dict(hidden_size=768, expand=2, head_dim=64, state_size=128, n_groups=1), } +MAMBA1_PRESETS = { + "tiny": dict(hidden_size=16, expand=2, state_size=4, time_step_rank=1), + # state-spaces/mamba-130m-hf. + "mamba1-130m": dict(hidden_size=768, expand=2, state_size=16, time_step_rank=48), +} class StateStub: @@ -72,11 +77,51 @@ def update_recurrent_state(self, state, layer_idx): return state -def build_mixer(preset, conv_kernel, use_bias, seed, hf_chunk, time_step_limit=None): +def build_mixer(kind, preset, conv_kernel, use_bias, seed, hf_chunk, time_step_limit=None): + if kind in ("mamba1", "falcon_mamba"): + if preset not in MAMBA1_PRESETS: + raise ValueError(f"{preset} is not a Mamba1 preset") + if kind == "falcon_mamba": + from transformers import FalconMambaConfig + from transformers.models.falcon_mamba.modeling_falcon_mamba import FalconMambaMixer + + config_cls, mixer_cls = FalconMambaConfig, FalconMambaMixer + else: + from transformers import MambaConfig + from transformers.models.mamba.modeling_mamba import MambaMixer + + config_cls, mixer_cls = MambaConfig, MambaMixer + dims = MAMBA1_PRESETS[preset] + cfg = config_cls( + conv_kernel=conv_kernel, + use_bias=use_bias, + use_conv_bias=True, + num_hidden_layers=1, + **dims, + ) + torch.manual_seed(seed) + # Transformers 5.12.1 initializes Falcon-Mamba's non-persistent RMS + # buffers before registering them. Constructing without initialization + # and then calling the same upstream initializer avoids that ordering + # bug without changing the independent reference implementation. + initialize = kind != "falcon_mamba" + mixer = mixer_cls(cfg, layer_idx=0, initialize_mixer_weights=initialize).float().eval() + if not initialize: + mixer.init_falcon_mamba_weights() + with torch.no_grad(): + mixer.D.copy_(1.0 + 0.5 * torch.randn_like(mixer.D)) + mixer.A_log.add_(0.1 * torch.randn_like(mixer.A_log)) + mixer.dt_proj.bias.add_(0.1 * torch.randn_like(mixer.dt_proj.bias)) + if mixer.conv1d.bias is not None: + mixer.conv1d.bias.copy_(0.1 * torch.randn_like(mixer.conv1d.bias)) + return cfg, mixer + from transformers import Mamba2Config from transformers.models.mamba2.modeling_mamba2 import Mamba2Mixer - dims = PRESETS[preset] + if preset not in MAMBA2_PRESETS: + raise ValueError(f"{preset} is not a Mamba2 preset") + dims = MAMBA2_PRESETS[preset] d_inner = dims["expand"] * dims["hidden_size"] cfg = Mamba2Config( num_heads=d_inner // dims["head_dim"], @@ -102,20 +147,29 @@ def build_mixer(preset, conv_kernel, use_bias, seed, hf_chunk, time_step_limit=N return cfg, mixer -def weights_of(mixer, use_bias): +def weights_of(mixer, use_bias, kind): """The probe's resident weights in `SsmProbeSpec::weight_layout` order.""" out = [("in_proj", mixer.in_proj.weight)] if use_bias: out.append(("in_proj_b", mixer.in_proj.bias)) out.append(("conv_w", mixer.conv1d.weight)) # [C, 1, K] out.append(("conv_b", mixer.conv1d.bias)) - out += [ - ("dt_bias", mixer.dt_bias), - ("a_log", mixer.A_log), - ("d", mixer.D), - ("norm_w", mixer.norm.weight), - ("out_proj", mixer.out_proj.weight), - ] + if kind == "mamba2": + out += [ + ("dt_bias", mixer.dt_bias), + ("a_log", mixer.A_log), + ("d", mixer.D), + ("norm_w", mixer.norm.weight), + ] + else: + out += [ + ("x_proj", mixer.x_proj.weight), + ("dt_proj", mixer.dt_proj.weight), + ("dt_proj_b", mixer.dt_proj.bias), + ("a_log", mixer.A_log), + ("d", mixer.D), + ] + out.append(("out_proj", mixer.out_proj.weight)) if use_bias: out.append(("out_proj_b", mixer.out_proj.bias)) return out @@ -125,15 +179,20 @@ def np32(t): return np.ascontiguousarray(t.detach().cpu().numpy(), dtype=np.float32) +def reference_forward(mixer, rows, cache): + forward = mixer.torch_forward if hasattr(mixer, "torch_forward") else mixer.slow_forward + return forward(rows, cache_params=cache) + + def decode_steps(mixer, rows, h0, conv0): - """HF's own decode branch over `rows [B, L, hidden]`, from `h0 [B,H,P,N]` - and the last K-1 pre-conv inputs `conv0 [B, K-1, C]`.""" + """HF's decode branch over `rows [B,L,hidden]` from recurrent state and + the last K-1 pre-convolution inputs `conv0 [B,K-1,C]`.""" batch, _, channels = conv0.shape window = torch.cat([torch.zeros(batch, 1, channels), conv0], dim=1).transpose(1, 2) stub = StateStub(window.contiguous(), h0.clone(), previous=True) ys = [] for t in range(rows.shape[1]): - ys.append(mixer.torch_forward(rows[:, t : t + 1], cache_params=stub)) + ys.append(reference_forward(mixer, rows[:, t : t + 1], stub)) y = torch.cat(ys, dim=1) if ys else rows.new_zeros(batch, 0, mixer.hidden_size) return y, stub.layers[0].recurrent_states, stub.conv[:, :, 1:].transpose(1, 2) @@ -142,17 +201,31 @@ def emit_inputs(args): os.makedirs(args.emit_inputs, exist_ok=True) hf_chunk = args.hf_chunk or (32 if args.dims == "mamba2-130m" else 256) cfg, mixer = build_mixer( - args.dims, args.conv_kernel, args.use_bias, args.seed, hf_chunk, args.time_step_limit + args.kind, + args.dims, + args.conv_kernel, + args.use_bias, + args.seed, + hf_chunk, + args.time_step_limit, ) - h, p, n = mixer.num_heads, mixer.head_dim, mixer.ssm_state_size - c, k, hidden = mixer.conv_dim, mixer.conv_kernel_size, mixer.hidden_size + mamba1 = args.kind != "mamba2" + if mamba1: + h, p = 1, mixer.intermediate_size + c = mixer.intermediate_size + state_shape = (p, mixer.ssm_state_size) + else: + h, p = mixer.num_heads, mixer.head_dim + c = mixer.conv_dim + state_shape = (h, p, mixer.ssm_state_size) + n, k, hidden = mixer.ssm_state_size, mixer.conv_kernel_size, mixer.hidden_size gen = torch.Generator().manual_seed(args.seed + 1) with torch.no_grad(): if args.mode == "decode": b = args.batch x = torch.randn(b, 1, hidden, generator=gen) - h0 = 0.5 * torch.randn(b, h, p, n, generator=gen) + h0 = 0.5 * torch.randn((b, *state_shape), generator=gen) conv0 = torch.randn(b, k - 1, c, generator=gen) y, h_t, tail = decode_steps(mixer, x, h0, conv0) x, y = x[:, 0], y[:, 0] @@ -163,46 +236,51 @@ def emit_inputs(args): sys.exit(f"--real-len must be in 0..={rows}") x = torch.randn(rows, hidden, generator=gen) if args.init_state: - h0 = 0.5 * torch.randn(h, p, n, generator=gen) + h0 = 0.5 * torch.randn(state_shape, generator=gen) conv0 = torch.randn(k - 1, c, generator=gen) y, h_t, tail = decode_steps(mixer, x[None, :real_len], h0[None], conv0[None]) y, h_t, tail = y[0], h_t[0], tail[0] else: - h0, conv0 = torch.zeros(h, p, n), torch.zeros(k - 1, c) + h0, conv0 = torch.zeros(state_shape), torch.zeros(k - 1, c) if real_len == 0: y, h_t, tail = torch.zeros(0, hidden), h0, conv0 else: stub = StateStub(None, None, previous=False) - y = mixer.torch_forward(x[None, :real_len], cache_params=stub)[0] + y = reference_forward(mixer, x[None, :real_len], stub)[0] h_t = stub.layers[0].recurrent_states[0] tail = stub.conv[0, :, 1:].transpose(0, 1) - for name, tensor in weights_of(mixer, args.use_bias): + for name, tensor in weights_of(mixer, args.use_bias, args.kind): np.save(os.path.join(args.emit_inputs, f"{name}.npy"), np32(tensor)) for name, tensor in [("x", x), ("h0", h0), ("conv0", conv0)]: np.save(os.path.join(args.emit_inputs, f"{name}.npy"), np32(tensor)) for name, tensor in [("expected_y", y), ("expected_h", h_t), ("expected_conv", tail)]: np.save(os.path.join(args.emit_inputs, f"{name}.npy"), np32(tensor)) - lo, hi = cfg.time_step_limit + lo, hi = cfg.time_step_limit if not mamba1 else (0.0, float("inf")) + norm_eps = mixer.rms_eps if args.kind == "falcon_mamba" else cfg.layer_norm_epsilon meta = dict( mode=args.mode, rows=rows, real_len=real_len, dims=args.dims, + family=args.kind, + kind="mamba1" if mamba1 else "mamba2", seed=args.seed, init_state=bool(args.init_state), hidden=hidden, n_heads=h, head_dim=p, state_size=n, - n_groups=mixer.n_groups, + n_groups=1 if mamba1 else mixer.n_groups, conv_kernel=k, use_conv_bias=True, use_bias=bool(args.use_bias), time_step_limit=[float(lo), None if hi == float("inf") else float(hi)], - norm_eps=float(mixer.layer_norm_epsilon), + norm_eps=float(norm_eps), norm_group_size=mixer.intermediate_size, chunk_size=args.chunk_size, + dt_rank=mixer.time_step_rank if mamba1 else 0, + bcdt_norm=args.kind == "falcon_mamba", ) with open(os.path.join(args.emit_inputs, "meta.json"), "w") as fh: json.dump(meta, fh, indent=1) @@ -270,7 +348,12 @@ def main(): ap.add_argument("--real-len", type=int, default=0) ap.add_argument("--capacity", type=int, default=256, help="padded prefill rows") ap.add_argument("--batch", type=int, default=1, help="decode rows") - ap.add_argument("--dims", choices=sorted(PRESETS), default="tiny") + ap.add_argument( + "--kind", choices=["mamba2", "mamba1", "falcon_mamba"], default="mamba2" + ) + ap.add_argument( + "--dims", choices=sorted(MAMBA1_PRESETS.keys() | MAMBA2_PRESETS.keys()), default="tiny" + ) ap.add_argument("--conv-kernel", type=int, default=4) ap.add_argument("--use-bias", action="store_true") ap.add_argument("--init-state", action="store_true") diff --git a/src/lib/mlxcel-xla/assets/mamba-tiny/config.json b/src/lib/mlxcel-xla/assets/mamba-tiny/config.json new file mode 100644 index 000000000..914294b44 --- /dev/null +++ b/src/lib/mlxcel-xla/assets/mamba-tiny/config.json @@ -0,0 +1,14 @@ +{ + "model_type": "mamba", + "hidden_size": 8, + "intermediate_size": 16, + "num_hidden_layers": 1, + "vocab_size": 12, + "state_size": 4, + "time_step_rank": 2, + "conv_kernel": 4, + "use_conv_bias": true, + "use_bias": true, + "tie_word_embeddings": false, + "layer_norm_epsilon": 1e-5 +} diff --git a/src/lib/mlxcel-xla/assets/mamba-tiny/decode.mlir b/src/lib/mlxcel-xla/assets/mamba-tiny/decode.mlir new file mode 100644 index 000000000..81ead9706 --- /dev/null +++ b/src/lib/mlxcel-xla/assets/mamba-tiny/decode.mlir @@ -0,0 +1,133 @@ +module @decode_step { + util.global private mutable @ssm_h : tensor<1x16x4xf32> + util.global private mutable @ssm_conv : tensor<1x3x16xf32> + func.func public @main(%arg0: tensor<12x8xf32> loc("params['embed']"), %arg1: tensor<8xf32> loc("params['final_norm']"), %arg2: tensor<12x8xf32> loc("params['lm_head']"), %arg3: tensor<8xf32> loc("params['layers'][0]['in_ln']"), %arg4: tensor<32x8xf32> loc("params['layers'][0]['ssm.in_proj']"), %arg5: tensor<32xf32> loc("params['layers'][0]['ssm.in_proj_b']"), %arg6: tensor<16x1x4xf32> loc("params['layers'][0]['ssm.conv_w']"), %arg7: tensor<16xf32> loc("params['layers'][0]['ssm.conv_b']"), %arg8: tensor<10x16xf32> loc("params['layers'][0]['ssm.x_proj']"), %arg9: tensor<16x2xf32> loc("params['layers'][0]['ssm.dt_proj']"), %arg10: tensor<16xf32> loc("params['layers'][0]['ssm.dt_proj_b']"), %arg11: tensor<16x4xf32> loc("params['layers'][0]['ssm.a_log']"), %arg12: tensor<16xf32> loc("params['layers'][0]['ssm.d']"), %arg13: tensor<8x16xf32> loc("params['layers'][0]['ssm.out_proj']"), %arg14: tensor<8xf32> loc("params['layers'][0]['ssm.out_proj_b']"), %arg15: i32 loc("token"), %arg16: i32 loc("pos"), %arg17: i32 loc("cache_len")) -> tensor<12xf32> { + %0 = tensor.from_elements %arg15 : tensor + %1 = tensor.from_elements %arg16 : tensor + %2 = tensor.from_elements %arg17 : tensor + %3 = util.global.load @ssm_h : tensor<1x16x4xf32> + %4 = util.global.load @ssm_conv : tensor<1x3x16xf32> + %5 = stablehlo.slice %3 [0:1, 0:16, 0:4] : (tensor<1x16x4xf32>) -> tensor<1x16x4xf32> + %6 = stablehlo.slice %4 [0:1, 0:3, 0:16] : (tensor<1x3x16xf32>) -> tensor<1x3x16xf32> + %7 = stablehlo.constant dense<0x00000000> : tensor + %8 = stablehlo.constant dense<0x3F800000> : tensor + %9 = stablehlo.constant dense<0xFF800000> : tensor + %10 = stablehlo.constant dense<0xF149F2CA> : tensor + %11 = stablehlo.constant dense<0x3727C5AC> : tensor + %12 = stablehlo.constant dense<0x41000000> : tensor + %13 = stablehlo.constant dense<0x7F800000> : tensor + %14 = stablehlo.constant dense<0> : tensor + %15 = stablehlo.constant dense<0> : tensor + %16 = stablehlo.dynamic_slice %arg0, %0, %14, sizes = [1, 8] : (tensor<12x8xf32>, tensor, tensor) -> tensor<1x8xf32> + %17 = stablehlo.reshape %16 : (tensor<1x8xf32>) -> tensor<8xf32> + %18 = stablehlo.multiply %17, %17 : tensor<8xf32> + %19 = stablehlo.reduce(%18 init: %7) applies stablehlo.add across dimensions = [0] : (tensor<8xf32>, tensor) -> tensor + %20 = stablehlo.divide %19, %12 : tensor + %21 = stablehlo.add %20, %11 : tensor + %22 = stablehlo.rsqrt %21 : tensor + %23 = stablehlo.broadcast_in_dim %22, dims = [] : (tensor) -> tensor<8xf32> + %24 = stablehlo.multiply %17, %23 : tensor<8xf32> + %25 = stablehlo.multiply %24, %arg3 : tensor<8xf32> + %26 = stablehlo.reshape %25 : (tensor<8xf32>) -> tensor<1x8xf32> + %27 = stablehlo.dot_general %26, %arg4, contracting_dims = [1] x [1] : (tensor<1x8xf32>, tensor<32x8xf32>) -> tensor<1x32xf32> + %28 = stablehlo.broadcast_in_dim %arg5, dims = [1] : (tensor<32xf32>) -> tensor<1x32xf32> + %29 = stablehlo.add %27, %28 : tensor<1x32xf32> + %30 = stablehlo.slice %29 [0:1, 0:16] : (tensor<1x32xf32>) -> tensor<1x16xf32> + %31 = stablehlo.slice %29 [0:1, 16:32] : (tensor<1x32xf32>) -> tensor<1x16xf32> + %32 = stablehlo.reshape %30 : (tensor<1x16xf32>) -> tensor<1x1x16xf32> + %33 = stablehlo.concatenate %6, %32, dim = 1 : (tensor<1x3x16xf32>, tensor<1x1x16xf32>) -> tensor<1x4x16xf32> + %34 = stablehlo.reshape %arg6 : (tensor<16x1x4xf32>) -> tensor<16x4xf32> + %35 = stablehlo.transpose %34, dims = [1, 0] : (tensor<16x4xf32>) -> tensor<4x16xf32> + %36 = stablehlo.broadcast_in_dim %35, dims = [1, 2] : (tensor<4x16xf32>) -> tensor<1x4x16xf32> + %37 = stablehlo.multiply %33, %36 : tensor<1x4x16xf32> + %38 = stablehlo.constant dense<0x00000000> : tensor + %39 = stablehlo.reduce(%37 init: %38) applies stablehlo.add across dimensions = [1] : (tensor<1x4x16xf32>, tensor) -> tensor<1x16xf32> + %40 = stablehlo.broadcast_in_dim %arg7, dims = [1] : (tensor<16xf32>) -> tensor<1x16xf32> + %41 = stablehlo.add %39, %40 : tensor<1x16xf32> + %42 = stablehlo.slice %33 [0:1, 1:4, 0:16] : (tensor<1x4x16xf32>) -> tensor<1x3x16xf32> + %43 = stablehlo.negate %41 : tensor<1x16xf32> + %44 = stablehlo.exponential %43 : tensor<1x16xf32> + %45 = stablehlo.constant dense<0x3F800000> : tensor + %46 = stablehlo.broadcast_in_dim %45, dims = [] : (tensor) -> tensor<1x16xf32> + %47 = stablehlo.add %46, %44 : tensor<1x16xf32> + %48 = stablehlo.divide %46, %47 : tensor<1x16xf32> + %49 = stablehlo.multiply %41, %48 : tensor<1x16xf32> + %50 = stablehlo.dot_general %49, %arg8, contracting_dims = [1] x [1] : (tensor<1x16xf32>, tensor<10x16xf32>) -> tensor<1x10xf32> + %51 = stablehlo.slice %50 [0:1, 0:2] : (tensor<1x10xf32>) -> tensor<1x2xf32> + %52 = stablehlo.slice %50 [0:1, 2:6] : (tensor<1x10xf32>) -> tensor<1x4xf32> + %53 = stablehlo.slice %50 [0:1, 6:10] : (tensor<1x10xf32>) -> tensor<1x4xf32> + %54 = stablehlo.dot_general %51, %arg9, contracting_dims = [1] x [1] : (tensor<1x2xf32>, tensor<16x2xf32>) -> tensor<1x16xf32> + %55 = stablehlo.broadcast_in_dim %arg10, dims = [1] : (tensor<16xf32>) -> tensor<1x16xf32> + %56 = stablehlo.add %54, %55 : tensor<1x16xf32> + %57 = stablehlo.constant dense<0x00000000> : tensor + %58 = stablehlo.broadcast_in_dim %57, dims = [] : (tensor) -> tensor<1x16xf32> + %59 = stablehlo.maximum %56, %58 : tensor<1x16xf32> + %60 = stablehlo.abs %56 : tensor<1x16xf32> + %61 = stablehlo.negate %60 : tensor<1x16xf32> + %62 = stablehlo.exponential %61 : tensor<1x16xf32> + %63 = stablehlo.log_plus_one %62 : tensor<1x16xf32> + %64 = stablehlo.add %59, %63 : tensor<1x16xf32> + %65 = stablehlo.exponential %arg11 : tensor<16x4xf32> + %66 = stablehlo.negate %65 : tensor<16x4xf32> + %67 = stablehlo.reshape %64 : (tensor<1x16xf32>) -> tensor<1x16x1xf32> + %68 = stablehlo.broadcast_in_dim %67, dims = [0, 1, 2] : (tensor<1x16x1xf32>) -> tensor<1x16x4xf32> + %69 = stablehlo.broadcast_in_dim %66, dims = [1, 2] : (tensor<16x4xf32>) -> tensor<1x16x4xf32> + %70 = stablehlo.multiply %68, %69 : tensor<1x16x4xf32> + %71 = stablehlo.multiply %64, %49 : tensor<1x16xf32> + %72 = stablehlo.reshape %71 : (tensor<1x16xf32>) -> tensor<1x16x1xf32> + %73 = stablehlo.broadcast_in_dim %72, dims = [0, 1, 2] : (tensor<1x16x1xf32>) -> tensor<1x16x4xf32> + %74 = stablehlo.reshape %52 : (tensor<1x4xf32>) -> tensor<1x1x4xf32> + %75 = stablehlo.broadcast_in_dim %74, dims = [0, 1, 2] : (tensor<1x1x4xf32>) -> tensor<1x16x4xf32> + %76 = stablehlo.multiply %73, %75 : tensor<1x16x4xf32> + %77 = stablehlo.exponential %70 : tensor<1x16x4xf32> + %78 = stablehlo.multiply %77, %5 : tensor<1x16x4xf32> + %79 = stablehlo.add %78, %76 : tensor<1x16x4xf32> + %80 = stablehlo.reshape %53 : (tensor<1x4xf32>) -> tensor<1x1x4xf32> + %81 = stablehlo.broadcast_in_dim %80, dims = [0, 1, 2] : (tensor<1x1x4xf32>) -> tensor<1x16x4xf32> + %82 = stablehlo.multiply %79, %81 : tensor<1x16x4xf32> + %83 = stablehlo.constant dense<0x00000000> : tensor + %84 = stablehlo.reduce(%82 init: %83) applies stablehlo.add across dimensions = [2] : (tensor<1x16x4xf32>, tensor) -> tensor<1x16xf32> + %85 = stablehlo.broadcast_in_dim %arg12, dims = [1] : (tensor<16xf32>) -> tensor<1x16xf32> + %86 = stablehlo.multiply %49, %85 : tensor<1x16xf32> + %87 = stablehlo.add %84, %86 : tensor<1x16xf32> + %88 = stablehlo.negate %31 : tensor<1x16xf32> + %89 = stablehlo.exponential %88 : tensor<1x16xf32> + %90 = stablehlo.constant dense<0x3F800000> : tensor + %91 = stablehlo.broadcast_in_dim %90, dims = [] : (tensor) -> tensor<1x16xf32> + %92 = stablehlo.add %91, %89 : tensor<1x16xf32> + %93 = stablehlo.divide %91, %92 : tensor<1x16xf32> + %94 = stablehlo.multiply %31, %93 : tensor<1x16xf32> + %95 = stablehlo.multiply %87, %94 : tensor<1x16xf32> + %96 = stablehlo.dot_general %95, %arg13, contracting_dims = [1] x [1] : (tensor<1x16xf32>, tensor<8x16xf32>) -> tensor<1x8xf32> + %97 = stablehlo.broadcast_in_dim %arg14, dims = [1] : (tensor<8xf32>) -> tensor<1x8xf32> + %98 = stablehlo.add %96, %97 : tensor<1x8xf32> + %99 = stablehlo.reshape %98 : (tensor<1x8xf32>) -> tensor<8xf32> + %100 = stablehlo.add %17, %99 : tensor<8xf32> + %101 = stablehlo.multiply %100, %100 : tensor<8xf32> + %102 = stablehlo.reduce(%101 init: %7) applies stablehlo.add across dimensions = [0] : (tensor<8xf32>, tensor) -> tensor + %103 = stablehlo.divide %102, %12 : tensor + %104 = stablehlo.add %103, %11 : tensor + %105 = stablehlo.rsqrt %104 : tensor + %106 = stablehlo.broadcast_in_dim %105, dims = [] : (tensor) -> tensor<8xf32> + %107 = stablehlo.multiply %100, %106 : tensor<8xf32> + %108 = stablehlo.multiply %107, %arg1 : tensor<8xf32> + %109 = stablehlo.dot_general %108, %arg2, contracting_dims = [0] x [1] : (tensor<8xf32>, tensor<12x8xf32>) -> tensor<12xf32> + %110 = stablehlo.constant dense<0> : tensor + %111 = stablehlo.constant dense<0> : tensor + %112 = stablehlo.reshape %79 : (tensor<1x16x4xf32>) -> tensor<1x16x4xf32> + %113 = stablehlo.reshape %42 : (tensor<1x3x16xf32>) -> tensor<1x3x16xf32> + %114 = stablehlo.dynamic_update_slice %3, %112, %111, %110, %110 : (tensor<1x16x4xf32>, tensor<1x16x4xf32>, tensor, tensor, tensor) -> tensor<1x16x4xf32> + %115 = stablehlo.dynamic_update_slice %4, %113, %111, %110, %110 : (tensor<1x3x16xf32>, tensor<1x3x16xf32>, tensor, tensor, tensor) -> tensor<1x3x16xf32> + util.global.store %114, @ssm_h : tensor<1x16x4xf32> + util.global.store %115, @ssm_conv : tensor<1x3x16xf32> + return %109 : tensor<12xf32> + } + func.func public @state_import(%s0: tensor<1x16x4xf32>, %s1: tensor<1x3x16xf32>) { + util.global.store %s0, @ssm_h : tensor<1x16x4xf32> + util.global.store %s1, @ssm_conv : tensor<1x3x16xf32> + return + } + func.func public @scalar_inputs() { + return + } +} diff --git a/src/lib/mlxcel-xla/src/emitter/config.rs b/src/lib/mlxcel-xla/src/emitter/config.rs index c4cb6c23f..43a6ec880 100644 --- a/src/lib/mlxcel-xla/src/emitter/config.rs +++ b/src/lib/mlxcel-xla/src/emitter/config.rs @@ -42,6 +42,7 @@ //! are rejected rather than mis-emitted. use super::builder::ProjectionLayout; +use super::mamba1_config::mamba1_from_json; use super::recurrent_config::mamba2_from_json; pub use super::recurrent_config::{MixerKind, StateElem, StateTensorSpec}; use crate::hf_json::parse_hf_config_json_tracked; @@ -192,6 +193,10 @@ pub enum WeightScheme { /// HF `Mamba2ForCausalLM` names (`backbone.embeddings`, `backbone.layers.{i}.norm` /// and `.mixer.*`, `backbone.norm_f`, issue #3338). MLX conversions keep them. Mamba2, + /// HF `MambaForCausalLM` / `FalconMambaForCausalLM` names. The outer model + /// names match Mamba2, but the mixer has separate `x_proj` and `dt_proj` + /// tensors and a per-channel `A_log [d_inner, N]` (issue #3348). + Mamba1, /// Nemotron-H hybrid backbone with one mixer or FFN per block. NemotronH, } @@ -283,13 +288,25 @@ pub struct MoeConfig { pub weight_prefix: &'static str, } -/// Selective state-space (Mamba2 SSD) mixer parameters (epic #564, issue #3337). +/// Selective state-space mixer family. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SsmKind { + /// Mamba2's head/group SSD form. + Mamba2, + /// Mamba1's diagonal recurrence. Falcon-Mamba enables weightless RMSNorm + /// on the projected dt, B, and C tensors. + Mamba1 { dt_rank: usize, bcdt_norm: bool }, +} + +/// Selective state-space mixer parameters (epic #564). /// -/// One recurrent mixer layer folds each token into a fixed-size state -/// `h [H, P, N]` (f32) and carries the last `K-1` pre-conv inputs as the conv -/// tail. `emitter/ssm.rs` reads this; parsing it from `config.json` is #3338. +/// One recurrent mixer layer folds each token into a fixed-size f32 state +/// (`h [H,P,N]` for Mamba2, `h [D,N]` for Mamba1) and carries the last `K-1` +/// pre-conv inputs as the conv tail. `emitter/ssm.rs` reads this. #[derive(Clone, Debug, PartialEq)] pub struct SsmConfig { + /// The recurrence and projection layout this config uses. + pub kind: SsmKind, /// H (HF `num_heads`). pub n_heads: usize, /// P (HF `head_dim`); `d_inner = H * P`. @@ -300,7 +317,7 @@ pub struct SsmConfig { pub n_groups: usize, /// K (HF `conv_kernel`). pub conv_kernel: usize, - /// `d_inner + 2 * G * N`. + /// Mamba2: `d_inner + 2 * G * N`; Mamba1: `d_inner`. pub conv_dim: usize, /// HF `use_conv_bias`. pub use_conv_bias: bool, @@ -343,10 +360,14 @@ impl SsmConfig { self.n_heads * self.head_dim } - /// The in_proj output width: `[z: d_inner, xBC: conv_dim, dt: H]`. + /// The input projection width. Mamba2 uses + /// `[z: d_inner, xBC: conv_dim, dt: H]`; Mamba1 uses `[x, z]`. #[must_use] pub fn in_proj_dim(&self) -> usize { - self.d_inner() + self.conv_dim + self.n_heads + match self.kind { + SsmKind::Mamba2 => self.d_inner() + self.conv_dim + self.n_heads, + SsmKind::Mamba1 { .. } => 2 * self.d_inner(), + } } /// Structural checks every emitter entry point relies on. @@ -380,16 +401,38 @@ impl SsmConfig { .n_heads .checked_mul(self.head_dim) .ok_or_else(|| overflow("d_inner = n_heads * head_dim"))?; - let expected = self - .n_groups - .checked_mul(self.state_size) - .and_then(|gn| gn.checked_mul(2)) - .and_then(|bc| bc.checked_add(d_inner)) - .ok_or_else(|| overflow("conv_dim = d_inner + 2*G*N"))?; + let expected = match self.kind { + SsmKind::Mamba2 => { + let expected = self + .n_groups + .checked_mul(self.state_size) + .and_then(|gn| gn.checked_mul(2)) + .and_then(|bc| bc.checked_add(d_inner)) + .ok_or_else(|| overflow("conv_dim = d_inner + 2*G*N"))?; + expected + .checked_add(d_inner) + .and_then(|width| width.checked_add(self.n_heads)) + .ok_or_else(|| overflow("Mamba2 in_proj_dim"))?; + expected + } + SsmKind::Mamba1 { dt_rank, .. } => { + if dt_rank == 0 { + return Err("SsmConfig Mamba1 dt_rank must be positive".into()); + } + d_inner + .checked_mul(2) + .ok_or_else(|| overflow("Mamba1 in_proj_dim = 2*d_inner"))?; + self.state_size + .checked_mul(2) + .and_then(|bc| bc.checked_add(dt_rank)) + .ok_or_else(|| overflow("Mamba1 x_proj_dim = dt_rank + 2*state_size"))?; + d_inner + } + }; if self.conv_dim != expected { return Err(format!( - "SsmConfig.conv_dim={} != d_inner + 2*G*N = {expected}", - self.conv_dim + "SsmConfig.conv_dim={} != the {:?} expected width {expected}", + self.conv_dim, self.kind )); } if !d_inner.is_multiple_of(self.norm_group_size) { @@ -398,10 +441,6 @@ impl SsmConfig { self.norm_group_size )); } - self.conv_dim - .checked_add(d_inner) - .and_then(|width| width.checked_add(self.n_heads)) - .ok_or_else(|| overflow("in_proj_dim"))?; d_inner .checked_mul(self.state_size) .ok_or_else(|| overflow("state H*P*N"))?; @@ -421,9 +460,9 @@ impl SsmConfig { "SsmConfig.time_step_limit {low}..{high} is invalid" )); } - if !self.norm_eps.is_finite() || self.norm_eps < 0.0 { + if !self.norm_eps.is_finite() || self.norm_eps <= 0.0 { return Err(format!( - "SsmConfig.norm_eps={} must be finite and non-negative", + "SsmConfig.norm_eps={} must be finite and positive", self.norm_eps )); } @@ -436,6 +475,7 @@ impl SsmConfig { let (n_heads, head_dim, state_size, n_groups) = (4, 8, 16, 2); let d_inner = n_heads * head_dim; Self { + kind: SsmKind::Mamba2, n_heads, head_dim, state_size, @@ -450,6 +490,30 @@ impl SsmConfig { chunk_size: 8, } } + + /// A small Mamba1 mixer for pure-Rust emitter tests. + #[cfg(test)] + pub(crate) fn tiny_mamba1(bcdt_norm: bool) -> Self { + let (d_inner, state_size) = (16, 4); + Self { + kind: SsmKind::Mamba1 { + dt_rank: 2, + bcdt_norm, + }, + n_heads: 1, + head_dim: d_inner, + state_size, + n_groups: 1, + conv_kernel: 4, + conv_dim: d_inner, + use_conv_bias: true, + use_bias: false, + time_step_limit: (0.0, f32::INFINITY), + norm_eps: if bcdt_norm { 1e-6 } else { 1e-5 }, + norm_group_size: d_inner, + chunk_size: 4, + } + } } /// Static DeepStack schema declared by an architecture. @@ -932,6 +996,9 @@ impl Config { if model_type == Some("mamba2") { return mamba2_from_json(&v, quantization); } + if matches!(model_type, Some("mamba" | "falcon_mamba")) { + return mamba1_from_json(&v, quantization); + } // Only the Mamba2 reader understands the quoted `Infinity`/`NaN` // spelling. Every reader below would see a string where a number was // written, treat an optional field as absent and take its default, so diff --git a/src/lib/mlxcel-xla/src/emitter/mamba1_config.rs b/src/lib/mlxcel-xla/src/emitter/mamba1_config.rs new file mode 100644 index 000000000..a2511257b --- /dev/null +++ b/src/lib/mlxcel-xla/src/emitter/mamba1_config.rs @@ -0,0 +1,171 @@ +// Copyright 2025-2026 Lablup Inc. and Jeongkyu Shin +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Mamba1 and Falcon-Mamba `config.json` parsing (issue #3348). + +use super::config::{ + Config, NormStyle, QuantConfig, RopeScaling, SSM_DEFAULT_CHUNK_SIZE, SsmConfig, SsmKind, + WeightScheme, check_layer_count, +}; +use super::recurrent_config::MixerKind; + +/// Build an attention-free Mamba1 config from either HF's field names or the +/// original state-spaces aliases retained by `*-hf` checkpoints. +pub(super) fn mamba1_from_json( + v: &serde_json::Value, + quantization: Option, +) -> Result { + let model_type = v + .get("model_type") + .and_then(serde_json::Value::as_str) + .unwrap_or("mamba"); + let family = if model_type == "falcon_mamba" { + "falcon_mamba" + } else { + "mamba" + }; + let value = |keys: &[&str]| { + keys.iter() + .find_map(|key| v.get(*key).filter(|value| !value.is_null())) + }; + let usize_key = |keys: &[&str]| -> Result { + value(keys) + .ok_or_else(|| format!("{family} config.json missing integer among {keys:?}"))? + .as_u64() + .and_then(|x| usize::try_from(x).ok()) + .ok_or_else(|| format!("{family} config.json {keys:?} must be a non-negative integer")) + }; + let usize_or = |keys: &[&str], default: usize| -> Result { + match value(keys) { + None => Ok(default), + Some(_) => usize_key(keys), + } + }; + let bool_keys_or = |keys: &[&str], default: bool| -> Result { + match value(keys) { + None => Ok(default), + Some(value) => value + .as_bool() + .ok_or_else(|| format!("{family} config.json {keys:?} must be a boolean")), + } + }; + let bool_or = |key: &str, default: bool| bool_keys_or(&[key], default); + let f32_or = |keys: &[&str], default: f32| -> Result { + match value(keys) { + None => Ok(default), + Some(value) => value + .as_f64() + .map(|x| x as f32) + .ok_or_else(|| format!("{family} config.json {keys:?} must be a number")), + } + }; + + if !bool_or("rms_norm", true)? { + return Err(format!( + "{family} with rms_norm = false (LayerNorm blocks) is not supported" + )); + } + if let Some(act) = value(&["hidden_act"]) + && act.as_str() != Some("silu") + { + return Err(format!( + "{family} hidden_act {act} is not supported (the mixer is silu-gated)" + )); + } + let hidden = usize_key(&["hidden_size", "d_model"])?; + let n_layers = check_layer_count(usize_key(&["num_hidden_layers", "n_layer", "n_layers"])?)?; + let vocab = usize_key(&["vocab_size"])?; + let state_size = usize_key(&["state_size", "d_state"])?; + let conv_kernel = usize_or(&["conv_kernel", "d_conv"], 4)?; + let expand = usize_or(&["expand"], 2)?; + let d_inner = match value(&["intermediate_size", "d_inner"]) { + Some(_) => usize_key(&["intermediate_size", "d_inner"])?, + None => hidden + .checked_mul(expand) + .ok_or_else(|| format!("{family} expand * hidden_size overflows usize"))?, + }; + let dt_rank = match value(&["time_step_rank", "dt_rank"]) { + None => hidden.div_ceil(16), + Some(serde_json::Value::String(text)) if text == "auto" => hidden.div_ceil(16), + Some(serde_json::Value::String(text)) => { + return Err(format!("{family} time_step_rank {text:?} is not supported")); + } + Some(_) => usize_key(&["time_step_rank", "dt_rank"])?, + }; + for (name, value) in [ + ("hidden_size", hidden), + ("num_hidden_layers", n_layers), + ("vocab_size", vocab), + ("intermediate_size", d_inner), + ("state_size", state_size), + ("time_step_rank", dt_rank), + ] { + if value == 0 { + return Err(format!("{family} config.json `{name}` must be positive")); + } + } + let norm_eps = f32_or(&["layer_norm_epsilon", "rms_norm_eps"], 1e-5)?; + let mixer_eps = f32_or(&["mixer_rms_eps"], 1e-6)?; + let bcdt_norm = model_type == "falcon_mamba" || bool_or("use_bcdt_rms", false)?; + if !norm_eps.is_finite() || norm_eps <= 0.0 { + return Err(format!( + "{family} block norm epsilon {norm_eps} must be finite and positive" + )); + } + if bcdt_norm && (!mixer_eps.is_finite() || mixer_eps <= 0.0) { + return Err(format!( + "{family} mixer_rms_eps {mixer_eps} must be finite and positive" + )); + } + let ssm = SsmConfig { + kind: SsmKind::Mamba1 { dt_rank, bcdt_norm }, + // Reuse `n_heads * head_dim` as the common d_inner representation. + n_heads: 1, + head_dim: d_inner, + state_size, + n_groups: 1, + conv_kernel, + conv_dim: d_inner, + // Transformers uses the `use_*` names while the original state-spaces + // configs use `conv_bias` / `bias`. Prefer the canonical HF spellings + // when a converted checkpoint happens to contain both. + use_conv_bias: bool_keys_or(&["use_conv_bias", "conv_bias"], true)?, + use_bias: bool_keys_or(&["use_bias", "bias"], false)?, + time_step_limit: (0.0, f32::INFINITY), + norm_eps: if bcdt_norm { mixer_eps } else { norm_eps }, + norm_group_size: d_inner, + chunk_size: SSM_DEFAULT_CHUNK_SIZE, + }; + ssm.validate()?; + + Ok(Config { + hidden, + inter: 0, + n_layers, + n_q: 0, + n_kv: 0, + head_dim: 0, + eps: norm_eps, + rope_theta: 0.0, + vocab, + rope: RopeScaling::Plain, + tie_word_embeddings: bool_or("tie_word_embeddings", true)?, + quantization, + norm_style: NormStyle::Plain, + weight_scheme: WeightScheme::Mamba1, + ssm: Some(ssm), + layer_mixers: vec![MixerKind::Mamba1; n_layers], + ..Config::llama_3_2_1b() + }) +} diff --git a/src/lib/mlxcel-xla/src/emitter/mod.rs b/src/lib/mlxcel-xla/src/emitter/mod.rs index 2c309628e..e01391727 100644 --- a/src/lib/mlxcel-xla/src/emitter/mod.rs +++ b/src/lib/mlxcel-xla/src/emitter/mod.rs @@ -60,6 +60,7 @@ mod gemma3n_math; mod gemma3n_qmv; mod gemma3n_schema; mod gemma3n_weights; +mod mamba1_config; mod model; mod moe; mod molmo2_config; @@ -80,6 +81,7 @@ mod recurrent_checkpoint; mod recurrent_config; mod rope; mod ssm; +mod ssm_mamba1; mod ssm_scan; #[cfg(test)] mod ssm_tests; @@ -186,7 +188,7 @@ pub(crate) use qwen3_vl::{ pub(crate) use config::{ExpertAct, MoeConfig, MoeScoring, SharedExpertConfig}; // SSM mixer types (issue #3337), consumed by the probe runner and #3338. #[allow(unused_imports)] -pub(crate) use config::{SSM_DEFAULT_CHUNK_SIZE, SsmConfig}; +pub(crate) use config::{SSM_DEFAULT_CHUNK_SIZE, SsmConfig, SsmKind}; // Per-layer mixer schedule and the threaded recurrent-state ABI (issue #3338), // consumed by the IREE runtime (#3339) and the SSM model check. #[allow(unused_imports)] @@ -540,21 +542,11 @@ mod tests { assert_eq!(c.eps, 1e-6); } - /// An unsupported `model_type` and an unsupported `rope_scaling` are each - /// rejected with a clear message rather than mis-emitted. (Untied embeddings and - /// the Gemma / Qwen3 / SmolLM3 / OLMo2/3 families are now accepted; see their + /// An unsupported `rope_scaling` is rejected with a clear message rather + /// than mis-emitted. (Mamba1 and the other supported families have their /// own parse tests.) #[test] fn from_json_rejects_unsupported_configs() { - let mamba = r#"{"model_type":"mamba","tie_word_embeddings":true,"hidden_size":8, - "num_attention_heads":2,"intermediate_size":16,"num_hidden_layers":2, - "num_key_value_heads":1,"rms_norm_eps":1e-6,"rope_theta":1e4,"vocab_size":10}"#; - assert!( - Config::from_json_str(mamba) - .unwrap_err() - .contains("model_type") - ); - // yarn RoPE (e.g. OLMo3 at full size) is not supported yet. let yarn = r#"{"model_type":"qwen2","tie_word_embeddings":true,"hidden_size":8, "num_attention_heads":2,"intermediate_size":16,"num_hidden_layers":2, diff --git a/src/lib/mlxcel-xla/src/emitter/model.rs b/src/lib/mlxcel-xla/src/emitter/model.rs index 42c5d26b9..2bb39ba3a 100644 --- a/src/lib/mlxcel-xla/src/emitter/model.rs +++ b/src/lib/mlxcel-xla/src/emitter/model.rs @@ -35,11 +35,11 @@ use super::builder::{Builder, Precision, ProjectionLayout, Ty, Val, precision_from_env}; use super::config::{ - Config, DeepStackConfig, ExpertAct, MoeScoring, MropeLayout, NormStyle, SsmConfig, + Config, DeepStackConfig, ExpertAct, MoeScoring, MropeLayout, NormStyle, SsmConfig, SsmKind, }; use super::moe::{self, MoeLayerW, MoeSharedW}; use super::rope; -use super::ssm::{self, Mamba2MixerW, SsmLayerState}; +use super::ssm::{self, Mamba1MixerW, Mamba2MixerW, SsmLayerState, SsmMixerW}; use super::ssm_scan::SsmPrefillForm; #[path = "model_recurrent.rs"] @@ -285,9 +285,9 @@ struct LayerW { /// Phi4MM's immutable speech/vision adapter pairs. The request's numeric /// mode gates their deltas per row; the base weights are never mutated. phi4_lora: Option, - /// The Mamba2 mixer of a recurrent layer (issue #3338); `None` on every - /// attention layer. A recurrent layer sets only this and `in_ln`. - ssm: Option, + /// The SSM mixer of a recurrent layer; `None` on every attention layer. A + /// recurrent layer sets only this and `in_ln`. + ssm: Option, } struct MlaLayerW { @@ -3015,7 +3015,7 @@ fn emit_transformer_layer( state: &mut RecurrentLayers, ) -> Val { if c.layer_mixer(li).is_recurrent() { - return recurrent::emit_mamba2_block(b, c, k, lw, li, x, layout, state); + return recurrent::emit_recurrent_block(b, c, k, lw, li, x, layout, state); } if c.layer_mixer(li) == super::config::MixerKind::None { let hn = arch_norm(b, c, k, layout, x, &lw.in_ln, lw.in_ln_bias.as_ref()); @@ -4989,23 +4989,49 @@ pub(crate) fn emit_ssm_probe_with( let in_proj_b = c.use_bias.then(|| arg(vec![c.in_proj_dim()], "in_proj_b")); let conv_w = arg(vec![cd, 1, k], "conv_w"); let conv_b = c.use_conv_bias.then(|| arg(vec![cd], "conv_b")); - let dt_bias = arg(vec![hh], "dt_bias"); - let a_log = arg(vec![hh], "a_log"); - let d = arg(vec![hh], "d"); - let norm_w = arg(vec![di], "norm_w"); - let out_proj = arg(vec![hidden, di], "out_proj"); - let out_proj_b = c.use_bias.then(|| arg(vec![hidden], "out_proj_b")); - let w = Mamba2MixerW { - in_proj, - in_proj_b, - conv_w, - conv_b, - dt_bias, - a_log, - d, - norm_w, - out_proj, - out_proj_b, + let w = match c.kind { + SsmKind::Mamba2 => { + let dt_bias = arg(vec![hh], "dt_bias"); + let a_log = arg(vec![hh], "a_log"); + let d = arg(vec![hh], "d"); + let norm_w = arg(vec![di], "norm_w"); + let out_proj = arg(vec![hidden, di], "out_proj"); + let out_proj_b = c.use_bias.then(|| arg(vec![hidden], "out_proj_b")); + SsmMixerW::Mamba2(Mamba2MixerW { + in_proj, + in_proj_b, + conv_w, + conv_b, + dt_bias, + a_log, + d, + norm_w, + out_proj, + out_proj_b, + }) + } + SsmKind::Mamba1 { dt_rank, .. } => { + let x_proj = arg(vec![dt_rank + 2 * n, di], "x_proj"); + let dt_proj = arg(vec![di, dt_rank], "dt_proj"); + let dt_proj_b = arg(vec![di], "dt_proj_b"); + let a_log = arg(vec![di, n], "a_log"); + let d = arg(vec![di], "d"); + let out_proj = arg(vec![hidden, di], "out_proj"); + let out_proj_b = c.use_bias.then(|| arg(vec![hidden], "out_proj_b")); + SsmMixerW::Mamba1(Mamba1MixerW { + in_proj, + in_proj_b, + conv_w, + conv_b, + x_proj, + dt_proj, + dt_proj_b, + a_log, + d, + out_proj, + out_proj_b, + }) + } }; let x = arg(vec![t, hidden], "x"); @@ -5018,25 +5044,38 @@ pub(crate) fn emit_ssm_probe_with( Ty::scalar("i32"), "ssm.real_len".into(), ); - let h0 = take_arg( - &mut decls, - &mut idx, - Ty::f32(vec![hh, p, n]), - "ssm.h0".into(), - ); + let h_shape = match c.kind { + SsmKind::Mamba2 => vec![hh, p, n], + SsmKind::Mamba1 { .. } => vec![di, n], + }; + let h0 = take_arg(&mut decls, &mut idx, Ty::f32(h_shape), "ssm.h0".into()); let conv0 = take_arg( &mut decls, &mut idx, Ty::f32(vec![k - 1, cd]), "ssm.conv0".into(), ); - ssm::mamba2_mixer_prefill_form(&mut b, c, form, &w, &x, &real_len, &h0, &conv0) + match &w { + SsmMixerW::Mamba2(w) => { + ssm::mamba2_mixer_prefill_form(&mut b, c, form, w, &x, &real_len, &h0, &conv0) + } + SsmMixerW::Mamba1(w) => { + ssm::mamba1_mixer_prefill(&mut b, c, w, &x, &real_len, &h0, &conv0) + } + } } ProbeMode::Decode => { let (h_ty, conv_ty) = ssm::ssm_state_types(c, t); let h = take_arg(&mut decls, &mut idx, h_ty, "ssm.h0".into()); let conv = take_arg(&mut decls, &mut idx, conv_ty, "ssm.conv0".into()); - let (y, st) = ssm::mamba2_mixer_step(&mut b, c, &w, &x, &SsmLayerState { h, conv }); + let (y, st) = match &w { + SsmMixerW::Mamba2(w) => { + ssm::mamba2_mixer_step(&mut b, c, w, &x, &SsmLayerState { h, conv }) + } + SsmMixerW::Mamba1(w) => { + ssm::mamba1_mixer_step(&mut b, c, w, &x, &SsmLayerState { h, conv }) + } + }; (y, st.h, st.conv) } }; diff --git a/src/lib/mlxcel-xla/src/emitter/model_recurrent.rs b/src/lib/mlxcel-xla/src/emitter/model_recurrent.rs index fea091c17..9d59c7ecb 100644 --- a/src/lib/mlxcel-xla/src/emitter/model_recurrent.rs +++ b/src/lib/mlxcel-xla/src/emitter/model_recurrent.rs @@ -12,7 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Recurrent (Mamba2) layers in the shared model graphs (epic #564, #3338). +//! Recurrent Mamba2/Mamba1 layers in the shared model graphs (epic #564, +//! issues #3338 and #3348). //! //! A child of `model`, so it reuses the private weight-argument and layer //! plumbing. The state ABI is the one [`Config::state_tensors`] lists: every @@ -37,8 +38,8 @@ use super::*; /// the prefill row count the prefill mixer masks with. pub(super) struct RecurrentLayers { /// One entry per recurrent layer, indexed by [`Config::state_layer_index`]. - /// Prefill rows are per-sequence (`h [H, P, N]`, `conv [K-1, C]`); the - /// single-sequence decode keeps a batch of one (`[1, H, P, N]`). + /// Prefill rows are per-sequence (`h [H,P,N]` for Mamba2 or `[D,N]` for + /// Mamba1, plus `conv [K-1,C]`); single-sequence decode adds a batch of one. layers: Vec, /// `real_len` of the prefill; `None` in a decode graph. real_len: Option, @@ -66,18 +67,24 @@ impl RecurrentLayers { return Self::none(); }; let [h_all, conv_all] = tensors else { - panic!("a Mamba2 config threads exactly two state tensors"); + panic!("a recurrent config threads exactly two state tensors"); }; - let (hh, p, n) = (ssm.n_heads, ssm.head_dim, ssm.state_size); + let (hh, p, n, d) = (ssm.n_heads, ssm.head_dim, ssm.state_size, ssm.d_inner()); let (k1, cd) = (ssm.conv_kernel - 1, ssm.conv_dim); let unbatched = real_len.is_some(); let layers = (0..c.recurrent_layer_count()) .map(|s| { - let h = b.slice(h_all, &[(s, s + 1), (0, hh), (0, p), (0, n)]); + let h = match ssm.kind { + SsmKind::Mamba2 => b.slice(h_all, &[(s, s + 1), (0, hh), (0, p), (0, n)]), + SsmKind::Mamba1 { .. } => b.slice(h_all, &[(s, s + 1), (0, d), (0, n)]), + }; let conv = b.slice(conv_all, &[(s, s + 1), (0, k1), (0, cd)]); if unbatched { SsmLayerState { - h: b.reshape(&h, vec![hh, p, n]), + h: match ssm.kind { + SsmKind::Mamba2 => b.reshape(&h, vec![hh, p, n]), + SsmKind::Mamba1 { .. } => b.reshape(&h, vec![d, n]), + }, conv: b.reshape(&conv, vec![k1, cd]), } } else { @@ -96,16 +103,26 @@ impl RecurrentLayers { return Self::none(); }; let [h_all, conv_all] = tensors else { - panic!("a Mamba2 config threads exactly two state tensors"); + panic!("a recurrent config threads exactly two state tensors"); }; - let (hh, p, n) = (ssm.n_heads, ssm.head_dim, ssm.state_size); + let (hh, p, n, d) = (ssm.n_heads, ssm.head_dim, ssm.state_size, ssm.d_inner()); let (k1, cd) = (ssm.conv_kernel - 1, ssm.conv_dim); let layers = (0..c.recurrent_layer_count()) .map(|s| { - let h = b.slice(h_all, &[(0, bsz), (s, s + 1), (0, hh), (0, p), (0, n)]); + let h = match ssm.kind { + SsmKind::Mamba2 => { + b.slice(h_all, &[(0, bsz), (s, s + 1), (0, hh), (0, p), (0, n)]) + } + SsmKind::Mamba1 { .. } => { + b.slice(h_all, &[(0, bsz), (s, s + 1), (0, d), (0, n)]) + } + }; let conv = b.slice(conv_all, &[(0, bsz), (s, s + 1), (0, k1), (0, cd)]); SsmLayerState { - h: b.reshape(&h, vec![bsz, hh, p, n]), + h: match ssm.kind { + SsmKind::Mamba2 => b.reshape(&h, vec![bsz, hh, p, n]), + SsmKind::Mamba1 { .. } => b.reshape(&h, vec![bsz, d, n]), + }, conv: b.reshape(&conv, vec![bsz, k1, cd]), } }) @@ -134,8 +151,14 @@ impl RecurrentLayers { conv_shape.extend(&conv_all.ty.shape[2..]); let h = b.reshape(&layer.h, h_shape); let conv = b.reshape(&layer.conv, conv_shape); - h_all = b.dynamic_update_slice(&h_all, &h, &[&zero, &row, &zero, &zero, &zero]); - conv_all = b.dynamic_update_slice(&conv_all, &conv, &[&zero, &row, &zero, &zero]); + let mut h_starts = vec![zero.clone(); h_all.ty.shape.len()]; + h_starts[1] = row.clone(); + let h_starts = h_starts.iter().collect::>(); + h_all = b.dynamic_update_slice(&h_all, &h, &h_starts); + let mut conv_starts = vec![zero.clone(); conv_all.ty.shape.len()]; + conv_starts[1] = row; + let conv_starts = conv_starts.iter().collect::>(); + conv_all = b.dynamic_update_slice(&conv_all, &conv, &conv_starts); } vec![h_all, conv_all] } @@ -158,16 +181,21 @@ impl RecurrentLayers { conv_shape.extend(&conv_all.ty.shape[1..]); let h = b.reshape(&layer.h, h_shape); let conv = b.reshape(&layer.conv, conv_shape); - h_all = b.dynamic_update_slice(&h_all, &h, &[&row, &zero, &zero, &zero]); - conv_all = b.dynamic_update_slice(&conv_all, &conv, &[&row, &zero, &zero]); + let mut h_starts = vec![zero.clone(); h_all.ty.shape.len()]; + h_starts[0] = row.clone(); + let h_starts = h_starts.iter().collect::>(); + h_all = b.dynamic_update_slice(&h_all, &h, &h_starts); + let mut conv_starts = vec![zero.clone(); conv_all.ty.shape.len()]; + conv_starts[0] = row; + let conv_starts = conv_starts.iter().collect::>(); + conv_all = b.dynamic_update_slice(&conv_all, &conv, &conv_starts); } vec![h_all, conv_all] } } -/// Take one Mamba2 layer's weights in the order `push_ssm_layer_specs` -/// (`weights.rs`) lists them: the block norm, in_proj (+ bias), conv1d (+ bias), -/// dt_bias, A_log, D, the gated-norm weight, out_proj (+ bias). Only the block +/// Take one recurrent layer's weights in the exact order +/// `push_ssm_layer_specs` (`weights.rs`) lists for its SSM kind. Only the block /// norm (`in_ln`) and the mixer are set on the returned [`LayerW`]. pub(super) fn take_ssm_layer_weights( b: &mut Builder, @@ -181,7 +209,7 @@ pub(super) fn take_ssm_layer_weights( .as_ref() .expect("a recurrent layer implies an SsmConfig"); let h = c.hidden; - let (di, cd, nh) = (ssm.d_inner(), ssm.conv_dim, ssm.n_heads); + let (di, cd) = (ssm.d_inner(), ssm.conv_dim); let p = |k: &str| format!("params['layers'][{li}]['{k}']"); let in_ln = take_arg(decls, idx, Ty::f32(vec![h]), p("in_ln")); let in_proj = take_weight(b, decls, idx, c, ssm.in_proj_dim(), h, p("ssm.in_proj")); @@ -202,14 +230,64 @@ pub(super) fn take_ssm_layer_weights( let conv_b = ssm .use_conv_bias .then(|| take_arg(decls, idx, Ty::f32(vec![cd]), p("ssm.conv_b"))); - let dt_bias = take_arg(decls, idx, Ty::f32(vec![nh]), p("ssm.dt_bias")); - let a_log = take_arg(decls, idx, Ty::f32(vec![nh]), p("ssm.a_log")); - let d = take_arg(decls, idx, Ty::f32(vec![nh]), p("ssm.d")); - let norm_w = take_arg(decls, idx, Ty::f32(vec![di]), p("ssm.norm_w")); - let out_proj = take_weight(b, decls, idx, c, h, di, p("ssm.out_proj")); - let out_proj_b = ssm - .use_bias - .then(|| take_arg(decls, idx, Ty::f32(vec![h]), p("ssm.out_proj_b"))); + let mixer = match ssm.kind { + SsmKind::Mamba2 => { + let nh = ssm.n_heads; + let dt_bias = take_arg(decls, idx, Ty::f32(vec![nh]), p("ssm.dt_bias")); + let a_log = take_arg(decls, idx, Ty::f32(vec![nh]), p("ssm.a_log")); + let d = take_arg(decls, idx, Ty::f32(vec![nh]), p("ssm.d")); + let norm_w = take_arg(decls, idx, Ty::f32(vec![di]), p("ssm.norm_w")); + SsmMixerW::Mamba2(Mamba2MixerW { + in_proj, + in_proj_b, + conv_w, + conv_b, + dt_bias, + a_log, + d, + norm_w, + out_proj: take_weight(b, decls, idx, c, h, di, p("ssm.out_proj")), + out_proj_b: ssm + .use_bias + .then(|| take_arg(decls, idx, Ty::f32(vec![h]), p("ssm.out_proj_b"))), + }) + } + SsmKind::Mamba1 { dt_rank, .. } => { + let x_proj = take_weight( + b, + decls, + idx, + c, + dt_rank + 2 * ssm.state_size, + di, + p("ssm.x_proj"), + ); + let dt_proj = take_weight(b, decls, idx, c, di, dt_rank, p("ssm.dt_proj")); + let dt_proj_b = take_arg(decls, idx, Ty::f32(vec![di]), p("ssm.dt_proj_b")); + let a_log = take_arg( + decls, + idx, + Ty::f32(vec![di, ssm.state_size]), + p("ssm.a_log"), + ); + let d = take_arg(decls, idx, Ty::f32(vec![di]), p("ssm.d")); + SsmMixerW::Mamba1(Mamba1MixerW { + in_proj, + in_proj_b, + conv_w, + conv_b, + x_proj, + dt_proj, + dt_proj_b, + a_log, + d, + out_proj: take_weight(b, decls, idx, c, h, di, p("ssm.out_proj")), + out_proj_b: ssm + .use_bias + .then(|| take_arg(decls, idx, Ty::f32(vec![h]), p("ssm.out_proj_b"))), + }) + } + }; LayerW { down: None, gate: None, @@ -236,26 +314,15 @@ pub(super) fn take_ssm_layer_weights( up_bias: None, moe: None, phi4_lora: None, - ssm: Some(Mamba2MixerW { - in_proj, - in_proj_b, - conv_w, - conv_b, - dt_bias, - a_log, - d, - norm_w, - out_proj, - out_proj_b, - }), + ssm: Some(mixer), } } -/// One pure Mamba2 block, `x + mixer(norm(x))`, at the rank of `layout`. The -/// layer's state row is read from and written back to `state`. A Mamba2 block -/// has no FFN (`Config::layer_has_ffn` is false), so nothing follows the mixer. +/// One pure Mamba block, `x + mixer(norm(x))`, at the rank of `layout`. The +/// layer's state row is read from and written back to `state`. A Mamba block has +/// no FFN (`Config::layer_has_ffn` is false), so nothing follows the mixer. #[allow(clippy::too_many_arguments)] -pub(super) fn emit_mamba2_block( +pub(super) fn emit_recurrent_block( b: &mut Builder, c: &Config, k: &Consts, @@ -272,11 +339,11 @@ pub(super) fn emit_mamba2_block( let w = lw .ssm .as_ref() - .expect("a recurrent layer takes Mamba2 mixer weights"); + .expect("a recurrent layer takes SSM mixer weights"); let s = c .state_layer_index(li) .expect("a recurrent layer has a state row"); - debug_assert!(!c.layer_has_ffn(li), "a Mamba2 block has no FFN"); + debug_assert!(!c.layer_has_ffn(li), "a Mamba block has no FFN"); let hn = arch_norm(b, c, k, layout, x, &lw.in_ln, None); let mixed = match layout { AttnLayout::Prefill { .. } => { @@ -285,20 +352,32 @@ pub(super) fn emit_mamba2_block( .clone() .expect("the prefill threads real_len to its recurrent layers"); let current = &state.layers[s]; - let (y, h, conv) = - ssm::mamba2_mixer_prefill(b, ssm, w, &hn, &real_len, ¤t.h, ¤t.conv); + let (y, h, conv) = match w { + SsmMixerW::Mamba2(w) => { + ssm::mamba2_mixer_prefill(b, ssm, w, &hn, &real_len, ¤t.h, ¤t.conv) + } + SsmMixerW::Mamba1(w) => { + ssm::mamba1_mixer_prefill(b, ssm, w, &hn, &real_len, ¤t.h, ¤t.conv) + } + }; state.layers[s] = SsmLayerState { h, conv }; y } AttnLayout::Single { .. } => { let row = b.reshape(&hn, vec![1, c.hidden]); - let (y, next) = ssm::mamba2_mixer_step(b, ssm, w, &row, &state.layers[s]); + let (y, next) = match w { + SsmMixerW::Mamba2(w) => ssm::mamba2_mixer_step(b, ssm, w, &row, &state.layers[s]), + SsmMixerW::Mamba1(w) => ssm::mamba1_mixer_step(b, ssm, w, &row, &state.layers[s]), + }; state.layers[s] = next; b.reshape(&y, vec![c.hidden]) } AttnLayout::Ragged { .. } => { // `[B, hidden]` rows, one per slot, each advancing its own state row. - let (y, next) = ssm::mamba2_mixer_step(b, ssm, w, &hn, &state.layers[s]); + let (y, next) = match w { + SsmMixerW::Mamba2(w) => ssm::mamba2_mixer_step(b, ssm, w, &hn, &state.layers[s]), + SsmMixerW::Mamba1(w) => ssm::mamba1_mixer_step(b, ssm, w, &hn, &state.layers[s]), + }; state.layers[s] = next; y } diff --git a/src/lib/mlxcel-xla/src/emitter/nemotron_h_config.rs b/src/lib/mlxcel-xla/src/emitter/nemotron_h_config.rs index cf04e7698..9c04bc526 100644 --- a/src/lib/mlxcel-xla/src/emitter/nemotron_h_config.rs +++ b/src/lib/mlxcel-xla/src/emitter/nemotron_h_config.rs @@ -5,8 +5,8 @@ use super::config::{ Config, DenseMlpActivation, ExpertAct, MixerKind, MoeConfig, MoeScoring, NormStyle, - QuantConfig, RopeScaling, SSM_DEFAULT_CHUNK_SIZE, SharedExpertConfig, SsmConfig, WeightScheme, - check_layer_count, + QuantConfig, RopeScaling, SSM_DEFAULT_CHUNK_SIZE, SharedExpertConfig, SsmConfig, SsmKind, + WeightScheme, check_layer_count, }; use super::recurrent_config::json_f32; use serde_json::Value; @@ -233,6 +233,7 @@ pub(super) fn from_json(v: &Value, quantization: Option) -> Result< None }; let ssm = SsmConfig { + kind: SsmKind::Mamba2, n_heads, head_dim: ssm_head_dim, state_size, diff --git a/src/lib/mlxcel-xla/src/emitter/recurrent_checkpoint.rs b/src/lib/mlxcel-xla/src/emitter/recurrent_checkpoint.rs index 9ca913094..d9fb8a549 100644 --- a/src/lib/mlxcel-xla/src/emitter/recurrent_checkpoint.rs +++ b/src/lib/mlxcel-xla/src/emitter/recurrent_checkpoint.rs @@ -24,7 +24,7 @@ use std::collections::HashMap; use std::io::Read; use std::path::{Path, PathBuf}; -use super::config::{Config, ExpertAct, MoeScoring, QuantConfig, WeightScheme}; +use super::config::{Config, ExpertAct, MoeScoring, QuantConfig, SsmKind, WeightScheme}; use crate::shard_path::index_shard_path; /// Largest safetensors header this check reads (the format caps it at 100 MB). @@ -256,18 +256,25 @@ impl Config { let Some(ssm) = self.ssm.as_ref().filter(|_| self.has_recurrent_state()) else { return Ok(()); }; - if !matches!( - self.weight_scheme, - WeightScheme::Mamba2 | WeightScheme::NemotronH - ) { - return Err("a recurrent config must use the Mamba2 weight scheme".into()); + let scheme_matches_kind = match ssm.kind { + SsmKind::Mamba2 => matches!( + self.weight_scheme, + WeightScheme::Mamba2 | WeightScheme::NemotronH + ), + SsmKind::Mamba1 { .. } => self.weight_scheme == WeightScheme::Mamba1, + }; + if !scheme_matches_kind { + return Err(format!( + "a {:?} recurrent config cannot use the {:?} weight scheme", + ssm.kind, self.weight_scheme + )); } let mut shapes = HashMap::new(); for file in checkpoint_files(model_dir)? { shapes.extend(header_shapes(&file)?); } let quant = self.quantization; - let (h, di, cd, nh) = (self.hidden, ssm.d_inner(), ssm.conv_dim, ssm.n_heads); + let (h, di, cd) = (self.hidden, ssm.d_inner(), ssm.conv_dim); let k = ssm.conv_kernel; let shape = |name: &str| -> Result<&Vec, String> { shapes @@ -323,7 +330,7 @@ impl Config { let in_proj = ssm.in_proj_dim().checked_mul(h); if !matches!((state, in_proj), (Some(state), Some(in_proj)) if state <= in_proj) { return Err(format!( - "mamba2 state H*P*N = {di} * {} exceeds the in_proj weight \ + "SSM state D*N = {di} * {} exceeds the in_proj weight \ [{}, {h}] it is derived from", ssm.state_size, ssm.in_proj_dim() @@ -452,10 +459,30 @@ impl Config { if ssm.use_conv_bias { vector(&format!("{m}conv1d.bias"), cd)?; } - for name in ["dt_bias", "A_log", "D"] { - vector(&format!("{m}{name}"), nh)?; + match ssm.kind { + SsmKind::Mamba2 => { + for name in ["dt_bias", "A_log", "D"] { + vector(&format!("{m}{name}"), ssm.n_heads)?; + } + vector(&format!("{m}norm.weight"), di)?; + } + SsmKind::Mamba1 { dt_rank, .. } => { + proj( + &format!("{m}x_proj.weight"), + dt_rank + 2 * ssm.state_size, + di, + )?; + proj(&format!("{m}dt_proj.weight"), di, dt_rank)?; + vector(&format!("{m}dt_proj.bias"), di)?; + let a_log = format!("{m}A_log"); + expect( + &a_log, + shape(&a_log)?.as_slice() == [di, ssm.state_size], + format!("[{di}, {}]", ssm.state_size), + )?; + vector(&format!("{m}D"), di)?; + } } - vector(&format!("{m}norm.weight"), di)?; } Ok(()) } diff --git a/src/lib/mlxcel-xla/src/emitter/recurrent_config.rs b/src/lib/mlxcel-xla/src/emitter/recurrent_config.rs index 7068bf9fe..397cce3c7 100644 --- a/src/lib/mlxcel-xla/src/emitter/recurrent_config.rs +++ b/src/lib/mlxcel-xla/src/emitter/recurrent_config.rs @@ -17,13 +17,13 @@ //! //! Every attention-only config carries `layer_mixers = [Attention; n_layers]` //! and `ssm = None`, so it has no state tensors, a KV cache, and a FFN on every -//! layer: its graphs are unchanged. A Mamba2 config has no attention layer at -//! all, so it has no KV cache, and threads two f32 state tensors through its +//! layer: its graphs are unchanged. A pure Mamba config has no attention layer +//! at all, so it has no KV cache, and threads two f32 state tensors through its //! graphs in the order [`Config::state_tensors`] lists them. use super::config::{ - Config, NormStyle, QuantConfig, RopeScaling, SSM_DEFAULT_CHUNK_SIZE, SsmConfig, WeightScheme, - check_layer_count, + Config, NormStyle, QuantConfig, RopeScaling, SSM_DEFAULT_CHUNK_SIZE, SsmConfig, SsmKind, + WeightScheme, check_layer_count, }; /// The token mixer of one layer. Later units add more recurrent kinds. @@ -33,6 +33,8 @@ pub enum MixerKind { Attention, /// Mamba2 selective state-space mixer ([`SsmConfig`]). Mamba2, + /// Mamba1 diagonal selective state-space mixer ([`SsmConfig`]). + Mamba1, /// A feed-forward-only block (no token mixer or persistent state). None, } @@ -41,7 +43,7 @@ impl MixerKind { /// Whether the mixer carries recurrent state instead of a KV cache. #[must_use] pub fn is_recurrent(self) -> bool { - matches!(self, MixerKind::Mamba2) + matches!(self, MixerKind::Mamba2 | MixerKind::Mamba1) } /// The HF `model_type` of the family this mixer comes from, for errors. @@ -50,6 +52,7 @@ impl MixerKind { match self { MixerKind::Attention => "attention", MixerKind::Mamba2 => "mamba2", + MixerKind::Mamba1 => "mamba", MixerKind::None => "ffn", } } @@ -81,7 +84,7 @@ impl Config { .unwrap_or(MixerKind::Attention) } - /// Whether layer `li` has a feed-forward sublayer. A pure Mamba2 block is + /// Whether layer `li` has a feed-forward sublayer. A pure Mamba block is /// `norm -> mixer -> residual` with no FFN. #[must_use] pub fn layer_has_ffn(&self, li: usize) -> bool { @@ -142,24 +145,34 @@ impl Config { } /// The threaded state tensors, in graph-argument order. Empty for every - /// attention-only config. Mamba2: `ssm_h [L_ssm, H, P, N]` then - /// `ssm_conv [L_ssm, K-1, conv_dim]`, both f32. + /// attention-only config. Mamba2 uses `ssm_h [L_ssm,H,P,N]`; Mamba1 uses + /// `[L_ssm,D,N]`. Both then carry `ssm_conv [L_ssm,K-1,conv_dim]` in f32. #[must_use] pub fn state_tensors(&self) -> Vec { let layers = self.recurrent_layer_count(); match &self.ssm { - Some(ssm) if layers > 0 => vec![ - StateTensorSpec { - name: "ssm_h", - dims: vec![layers, ssm.n_heads, ssm.head_dim, ssm.state_size], - elem: StateElem::F32, - }, - StateTensorSpec { - name: "ssm_conv", - dims: vec![layers, ssm.conv_kernel - 1, ssm.conv_dim], - elem: StateElem::F32, - }, - ], + Some(ssm) if layers > 0 => { + let h_dims = match ssm.kind { + SsmKind::Mamba2 => { + vec![layers, ssm.n_heads, ssm.head_dim, ssm.state_size] + } + SsmKind::Mamba1 { .. } => { + vec![layers, ssm.d_inner(), ssm.state_size] + } + }; + vec![ + StateTensorSpec { + name: "ssm_h", + dims: h_dims, + elem: StateElem::F32, + }, + StateTensorSpec { + name: "ssm_conv", + dims: vec![layers, ssm.conv_kernel - 1, ssm.conv_dim], + elem: StateElem::F32, + }, + ] + } _ => Vec::new(), } } @@ -350,6 +363,7 @@ pub(super) fn mamba2_from_json( Some(value) => json_f32(value, "layer_norm_epsilon")?, }; let ssm = SsmConfig { + kind: SsmKind::Mamba2, n_heads, head_dim, state_size, diff --git a/src/lib/mlxcel-xla/src/emitter/recurrent_ragged_tests.rs b/src/lib/mlxcel-xla/src/emitter/recurrent_ragged_tests.rs index 709bff20d..eaa6f0cdd 100644 --- a/src/lib/mlxcel-xla/src/emitter/recurrent_ragged_tests.rs +++ b/src/lib/mlxcel-xla/src/emitter/recurrent_ragged_tests.rs @@ -12,9 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! The ragged (continuous-batching) decode for recurrent configs (issue -//! #3340): per-slot `[B, ...dims]` state inputs and results, no KV for an -//! attention-free model. Hybrid coverage is in `nemotron_h_tests`. +//! The ragged (continuous-batching) decode for recurrent configs (issues #3340, +//! #3348): per-slot `[B, ...dims]` state inputs and results, and no KV for an +//! attention-free Mamba1/Mamba2 model. Hybrid coverage is in `nemotron_h_tests`. use super::builder::Precision; use super::config::Config; @@ -29,10 +29,21 @@ const TINY_MAMBA2: &str = r#"{ "hidden_act": "silu", "tie_word_embeddings": true }"#; +const TINY_MAMBA1: &str = r#"{ + "model_type": "mamba", "hidden_size": 8, "intermediate_size": 16, + "num_hidden_layers": 2, "vocab_size": 40, "state_size": 4, + "time_step_rank": 2, "conv_kernel": 4, "use_conv_bias": true, + "use_bias": false, "tie_word_embeddings": true, "layer_norm_epsilon": 1e-5 +}"#; + fn tiny() -> Config { Config::from_json_str(TINY_MAMBA2).expect("tiny mamba2 parses") } +fn tiny_mamba1() -> Config { + Config::from_json_str(TINY_MAMBA1).expect("tiny mamba1 parses") +} + fn main_signature(graph: &str) -> &str { graph .lines() @@ -89,6 +100,22 @@ fn mamba2_ragged_decode_samples_and_emits_at_every_precision() { } } +#[test] +fn mamba1_ragged_decode_threads_per_slot_diagonal_state() { + let graph = emit_decode_ragged(&tiny_mamba1(), 4, false).expect("ragged Mamba1 emits"); + let sig = main_signature(&graph); + assert!(sig.contains("tensor<4x2x16x4xf32> loc(\"ssm_h\")"), "{sig}"); + assert!( + sig.contains("tensor<4x2x3x16xf32> loc(\"ssm_conv\")"), + "{sig}" + ); + assert!( + sig.ends_with("-> (tensor<4x40xf32>, tensor<4x2x16x4xf32>, tensor<4x2x3x16xf32>) {"), + "{sig}" + ); + assert!(!graph.contains("kcache")); +} + /// Each slot's state row is written back at its own layer row with the batch /// axis intact: one write per state tensor per recurrent layer. #[test] diff --git a/src/lib/mlxcel-xla/src/emitter/recurrent_tests.rs b/src/lib/mlxcel-xla/src/emitter/recurrent_tests.rs index cebf10aaf..817a22fd6 100644 --- a/src/lib/mlxcel-xla/src/emitter/recurrent_tests.rs +++ b/src/lib/mlxcel-xla/src/emitter/recurrent_tests.rs @@ -12,12 +12,12 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Mamba2 config, weight order, and state-threaded graph checks (issue #3338). -//! The numeric gate against HF is `spike/openxla/ssm_model_check.py`. +//! Mamba2/Mamba1 config, weight order, and state-threaded graph checks (issues +//! #3338 and #3348). The numeric gates against HF are the OpenXLA SSM oracles. use super::builder::Precision; use super::config::{ - Config, MixerKind, QuantConfig, SsmConfig, StateElem, StateTensorSpec, WeightScheme, + Config, MixerKind, QuantConfig, SsmConfig, SsmKind, StateElem, StateTensorSpec, WeightScheme, }; use super::model::{ emit_decode, emit_decode_batched, emit_decode_with, emit_prefill, emit_prefill_embeddings, @@ -37,10 +37,24 @@ const TINY_MAMBA2: &str = r#"{ "hidden_act": "silu", "tie_word_embeddings": true }"#; +const TINY_MAMBA1: &str = r#"{ + "model_type": "mamba", "hidden_size": 8, "intermediate_size": 16, + "num_hidden_layers": 2, "vocab_size": 40, "state_size": 4, + "time_step_rank": 2, "conv_kernel": 4, "use_conv_bias": true, + "use_bias": false, "tie_word_embeddings": true, "layer_norm_epsilon": 1e-5 +}"#; + fn tiny() -> Config { Config::from_json_str(TINY_MAMBA2).expect("tiny mamba2 parses") } +fn tiny_mamba1() -> Config { + Config::from_json_str(TINY_MAMBA1) + .expect("tiny mamba1 parses") + .with_context_capacity(9) + .expect("small test capacity") +} + fn main_signature(graph: &str) -> &str { graph .lines() @@ -58,6 +72,7 @@ fn assert_lowerable(graph: &str) { fn mamba2_config_parses_ssm_schedule_and_state_abi() { let c = tiny(); let expected = SsmConfig { + kind: SsmKind::Mamba2, n_heads: 4, head_dim: 8, state_size: 16, @@ -100,6 +115,159 @@ fn mamba2_config_parses_ssm_schedule_and_state_abi() { ); } +#[test] +fn mamba1_and_falcon_mamba_parse_diagonal_state_abi() { + for (model_type, bcdt_norm, norm_eps) in [("mamba", false, 1e-5), ("falcon_mamba", true, 1e-6)] + { + let text = TINY_MAMBA1 + .replace( + r#""model_type": "mamba""#, + &format!(r#""model_type": "{model_type}""#), + ) + .replace( + r#""layer_norm_epsilon": 1e-5"#, + r#""layer_norm_epsilon": 1e-5, "mixer_rms_eps": 1e-6"#, + ); + let c = Config::from_json_str(&text).expect("Mamba1 config parses"); + let ssm = c.ssm.as_ref().expect("Mamba1 carries SSM config"); + assert_eq!( + ssm.kind, + SsmKind::Mamba1 { + dt_rank: 2, + bcdt_norm, + } + ); + assert_eq!(ssm.norm_eps, norm_eps); + assert_eq!((ssm.d_inner(), ssm.conv_dim), (16, 16)); + assert_eq!(c.layer_mixers, vec![MixerKind::Mamba1; 2]); + assert_eq!(c.weight_scheme, WeightScheme::Mamba1); + assert!(!c.has_kv_cache()); + assert_eq!( + c.state_tensors(), + vec![ + StateTensorSpec { + name: "ssm_h", + dims: vec![2, 16, 4], + elem: StateElem::F32, + }, + StateTensorSpec { + name: "ssm_conv", + dims: vec![2, 3, 16], + elem: StateElem::F32, + }, + ] + ); + } +} + +#[test] +fn mamba1_legacy_bias_aliases_and_canonical_precedence() { + let aliases = TINY_MAMBA1 + .replace(r#""use_conv_bias": true"#, r#""conv_bias": false"#) + .replace(r#""use_bias": false"#, r#""bias": true"#); + let c = Config::from_json_str(&aliases).expect("legacy Mamba1 aliases parse"); + let ssm = c.ssm.as_ref().expect("Mamba1 carries SSM config"); + assert!(!ssm.use_conv_bias); + assert!(ssm.use_bias); + let names = weight_specs_q(&c, false) + .into_iter() + .map(|spec| spec.tensor_name().to_string()) + .collect::>(); + assert!(!names.iter().any(|name| name.ends_with("conv1d.bias"))); + assert!(names.iter().any(|name| name.ends_with("in_proj.bias"))); + assert!(names.iter().any(|name| name.ends_with("out_proj.bias"))); + + let both = TINY_MAMBA1 + .replace( + r#""use_conv_bias": true"#, + r#""conv_bias": false, "use_conv_bias": true"#, + ) + .replace(r#""use_bias": false"#, r#""bias": true, "use_bias": false"#); + let c = Config::from_json_str(&both).expect("canonical Mamba1 keys take precedence"); + let ssm = c.ssm.as_ref().expect("Mamba1 carries SSM config"); + assert!(ssm.use_conv_bias); + assert!(!ssm.use_bias); +} + +#[test] +fn mamba1_rejects_unsupported_norms_and_nonpositive_epsilons() { + for replacement in [ + r#""layer_norm_epsilon": 1e-5, "rms_norm": false"#, + r#""layer_norm_epsilon": 0"#, + r#""layer_norm_epsilon": -1"#, + ] { + let text = TINY_MAMBA1.replace(r#""layer_norm_epsilon": 1e-5"#, replacement); + let error = Config::from_json_str(&text).expect_err("invalid Mamba1 norm must fail"); + assert!( + error.contains("not supported") || error.contains("finite and positive"), + "{error}" + ); + } + + let falcon = TINY_MAMBA1 + .replace( + r#""model_type": "mamba""#, + r#""model_type": "falcon_mamba""#, + ) + .replace( + r#""layer_norm_epsilon": 1e-5"#, + r#""layer_norm_epsilon": 1e-5, "mixer_rms_eps": 0"#, + ); + let error = Config::from_json_str(&falcon).expect_err("zero Falcon mixer epsilon must fail"); + assert!(error.contains("mixer_rms_eps") && error.contains("finite and positive")); +} + +#[test] +fn mamba1_weight_specs_match_the_hf_mixer_order() { + let c = tiny_mamba1(); + let names = weight_specs_q(&c, false) + .into_iter() + .map(|spec| spec.tensor_name().to_string()) + .collect::>(); + assert_eq!( + &names[..11], + &[ + "backbone.embeddings.weight", + "backbone.norm_f.weight", + "backbone.layers.0.norm.weight", + "backbone.layers.0.mixer.in_proj.weight", + "backbone.layers.0.mixer.conv1d.weight", + "backbone.layers.0.mixer.conv1d.bias", + "backbone.layers.0.mixer.x_proj.weight", + "backbone.layers.0.mixer.dt_proj.weight", + "backbone.layers.0.mixer.dt_proj.bias", + "backbone.layers.0.mixer.A_log", + "backbone.layers.0.mixer.D", + ] + ); + assert_eq!(names[11], "backbone.layers.0.mixer.out_proj.weight"); + assert_eq!(names, graph_weight_tensors(&emit_prefill(&c, false))); + assert_eq!(names, graph_weight_tensors(&emit_decode(&c, false))); +} + +#[test] +fn mamba1_whole_model_graphs_thread_diagonal_state() { + let c = tiny_mamba1(); + let prefill = emit_prefill(&c, false); + assert_lowerable(&prefill); + let sig = main_signature(&prefill); + assert!(sig.contains("tensor<2x16x4xf32> loc(\"ssm_h\")"), "{sig}"); + assert!( + sig.contains("tensor<2x3x16xf32> loc(\"ssm_conv\")"), + "{sig}" + ); + assert!( + sig.ends_with("-> (tensor<40xf32>, tensor<2x16x4xf32>, tensor<2x3x16xf32>) {"), + "{sig}" + ); + let decode = emit_decode(&c, false); + assert_lowerable(&decode); + assert!(decode.contains("util.global private mutable @ssm_h : tensor<2x16x4xf32>")); + assert!(decode.contains( + "func.func public @state_import(%s0: tensor<2x16x4xf32>, %s1: tensor<2x3x16xf32>)" + )); +} + #[test] fn attention_configs_keep_the_kv_cache_and_no_state() { let c = Config::llama_3_2_1b(); @@ -198,6 +366,9 @@ fn tensor_for_loc(li: usize, key: &str) -> String { "ssm.in_proj_b" => format!("{m}in_proj.bias"), "ssm.conv_w" => format!("{m}conv1d.weight"), "ssm.conv_b" => format!("{m}conv1d.bias"), + "ssm.x_proj" => format!("{m}x_proj.weight"), + "ssm.dt_proj" => format!("{m}dt_proj.weight"), + "ssm.dt_proj_b" => format!("{m}dt_proj.bias"), "ssm.dt_bias" => format!("{m}dt_bias"), "ssm.a_log" => format!("{m}A_log"), "ssm.d" => format!("{m}D"), diff --git a/src/lib/mlxcel-xla/src/emitter/ssm.rs b/src/lib/mlxcel-xla/src/emitter/ssm.rs index b780a84ed..5586c8232 100644 --- a/src/lib/mlxcel-xla/src/emitter/ssm.rs +++ b/src/lib/mlxcel-xla/src/emitter/ssm.rs @@ -14,11 +14,12 @@ //! Selective state-space mixer primitives (epic #564, issue #3337). //! -//! A Mamba2 mixer layer is a causal depthwise conv1d followed by a selective -//! scan over a fixed-size f32 state `h [H, P, N]`. Both come in a one-step -//! decode form (with an explicit leading batch axis `B`) and a whole-prompt -//! prefill form over the padded `context_capacity` rows. The reference is HF -//! `Mamba2Mixer.torch_forward`; `spike/openxla/ssm_oracle.py` checks it. +//! A Mamba mixer layer is a causal depthwise conv1d followed by a selective +//! scan over a fixed-size f32 state: Mamba2 uses `h [H,P,N]`, while Mamba1 and +//! Falcon-Mamba use a diagonal `h [D,N]`. Both come in a one-step decode form +//! (with an explicit leading batch axis `B`) and a whole-prompt prefill form +//! over the padded `context_capacity` rows. `spike/openxla/ssm_oracle.py` +//! checks both families against their independent Transformers slow paths. //! //! Prefill invariants: rows `t >= real_len` get `dt = 0`, so their decay is //! `exp(0) = 1` and their input term vanishes; the state passes through them @@ -30,7 +31,11 @@ //! alternatives are recorded in `spike/openxla/FINDINGS_ssm.md`. use super::builder::{Builder, Ty, Val}; -use super::config::SsmConfig; +use super::config::{SsmConfig, SsmKind}; +#[allow(unused_imports)] // Public within the emitter for #3349/#3356 reuse. +pub(crate) use super::ssm_mamba1::{ + Mamba1MixerW, diag_scan_prefill, diag_scan_step, mamba1_mixer_prefill, mamba1_mixer_step, +}; use super::ssm_scan::{SsmPrefillForm, selective_scan_prefill_form}; /// One Mamba2 mixer layer's weights, in the HF checkpoint layout. @@ -53,10 +58,17 @@ pub(crate) struct Mamba2MixerW { pub out_proj_b: Option, } +/// Recurrent mixer weights carried by one model layer. +#[derive(Clone, Debug)] +pub(crate) enum SsmMixerW { + Mamba2(Mamba2MixerW), + Mamba1(Mamba1MixerW), +} + /// One recurrent layer's carried state. #[derive(Clone, Debug)] pub(crate) struct SsmLayerState { - /// `[B, H, P, N]` f32. + /// Mamba2: `[B,H,P,N]`; Mamba1/Falcon-Mamba: `[B,D,N]`. Always f32. pub h: Val, /// `[B, K-1, C]` f32, the last `K-1` pre-conv inputs. pub conv: Val, @@ -85,13 +97,13 @@ fn sigmoid(b: &mut Builder, x: &Val) -> Val { b.divide(&one, &denominator) } -fn silu(b: &mut Builder, x: &Val) -> Val { +pub(super) fn silu(b: &mut Builder, x: &Val) -> Val { let gate = sigmoid(b, x); b.multiply(x, &gate) } /// `softplus(x) = max(x, 0) + log1p(exp(-|x|))`, finite for every input. -fn softplus(b: &mut Builder, x: &Val) -> Val { +pub(super) fn softplus(b: &mut Builder, x: &Val) -> Val { let zero = splat(b, 0.0, &x.ty.shape); let positive = b.maximum(x, &zero); let magnitude = b.abs(x); @@ -122,7 +134,7 @@ pub(super) fn heads_from_groups(b: &mut Builder, v: &Val, n_heads: usize) -> Val } /// Add a `[C]` bias over the last axis. -fn add_last(b: &mut Builder, x: &Val, bias: &Val) -> Val { +pub(super) fn add_last(b: &mut Builder, x: &Val, bias: &Val) -> Val { let last = x.ty.shape.len() - 1; let bias = to_f32(b, bias); let bias = b.broadcast(&bias, &[last], x.ty.shape.clone()); @@ -137,7 +149,7 @@ fn add_last(b: &mut Builder, x: &Val, bias: &Val) -> Val { /// on every precision path: `Builder::convolution` demotes its operands on the /// f16 path, and a mixed-type depthwise convolution does not compile /// (`spike/openxla/FINDINGS_ssm.md`). -fn conv1d_over_left_context( +pub(super) fn conv1d_over_left_context( b: &mut Builder, xp: &Val, w: &Val, @@ -185,7 +197,7 @@ pub(crate) fn conv1d_causal_prefill( } /// The last `K-1` pre-conv rows of `xp [T+K-1, C]` ending at `real_len`. -fn tail_of_left_context(b: &mut Builder, xp: &Val, real_len: &Val, k: usize) -> Val { +pub(super) fn tail_of_left_context(b: &mut Builder, xp: &Val, real_len: &Val, k: usize) -> Val { let channels = xp.ty.shape[1]; let zero = b.const_i32(0); b.dynamic_slice(xp, &[real_len, &zero], vec![k - 1, channels]) @@ -448,8 +460,12 @@ pub(crate) fn mamba2_mixer_step( /// The decode state type for `batch` rows. pub(crate) fn ssm_state_types(c: &SsmConfig, batch: usize) -> (Ty, Ty) { + let h = match c.kind { + SsmKind::Mamba2 => vec![batch, c.n_heads, c.head_dim, c.state_size], + SsmKind::Mamba1 { .. } => vec![batch, c.d_inner(), c.state_size], + }; ( - Ty::f32(vec![batch, c.n_heads, c.head_dim, c.state_size]), + Ty::f32(h), Ty::f32(vec![batch, c.conv_kernel - 1, c.conv_dim]), ) } diff --git a/src/lib/mlxcel-xla/src/emitter/ssm_mamba1.rs b/src/lib/mlxcel-xla/src/emitter/ssm_mamba1.rs new file mode 100644 index 000000000..afa085cf7 --- /dev/null +++ b/src/lib/mlxcel-xla/src/emitter/ssm_mamba1.rs @@ -0,0 +1,347 @@ +// Copyright 2025-2026 Lablup Inc. and Jeongkyu Shin +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Mamba1 diagonal selective scan and mixer (issue #3348). +//! +//! Prefill builds at most `chunk * d_inner * state_size` recurrence operands. +//! It never forms a context-capacity-sized `[T, d_inner, state_size]` value. + +use super::builder::{Builder, Val}; +use super::config::{SsmConfig, SsmKind}; +use super::ssm::{ + SsmLayerState, add_last, conv1d_causal_step, conv1d_over_left_context, silu, softplus, splat, + tail_of_left_context, to_f32, +}; + +/// One Mamba1/Falcon-Mamba mixer layer's weights in HF checkpoint order. +#[derive(Clone, Debug)] +pub(crate) struct Mamba1MixerW { + pub in_proj: Val, + pub in_proj_b: Option, + /// `[D, 1, K]`, the torch depthwise Conv1d layout. + pub conv_w: Val, + pub conv_b: Option, + /// `[dt_rank + 2*N, D]`. + pub x_proj: Val, + /// `[D, dt_rank]` plus the always-present `[D]` bias. + pub dt_proj: Val, + pub dt_proj_b: Val, + /// `[D, N]`. + pub a_log: Val, + /// `[D]`. + pub d: Val, + pub out_proj: Val, + pub out_proj_b: Option, +} + +/// One diagonal recurrence step, entirely in f32: +/// `h' = exp(log_a) * h + bx`. +pub(crate) fn diag_scan_step(b: &mut Builder, log_a: &Val, bx: &Val, h: &Val) -> Val { + debug_assert_eq!(log_a.ty.shape, bx.ty.shape); + debug_assert_eq!(log_a.ty.shape, h.ty.shape); + let log_a = to_f32(b, log_a); + let bx = to_f32(b, bx); + let h = to_f32(b, h); + let decay = b.exponential(&log_a); + let kept = b.multiply(&decay, &h); + b.add(&kept, &bx) +} + +/// Shift `v` down by `by` rows, filling the new prefix with `fill`. +fn shift_rows(b: &mut Builder, v: &Val, by: usize, fill: f32) -> Val { + let rank = v.ty.shape.len(); + let rows = v.ty.shape[0]; + debug_assert!(by < rows); + let mut keep: Vec<(usize, usize)> = v.ty.shape.iter().map(|&size| (0, size)).collect(); + keep[0] = (0, rows - by); + let kept = b.slice(v, &keep); + let fill = b.const_f32(fill); + let mut low = vec![0; rank]; + low[0] = by; + b.pad(&kept, &fill, &low, &vec![0; rank]) +} + +/// Log-depth inclusive prefix scan of the affine recurrence pairs in one +/// bounded block. For `(a_t, u_t)`, composition is +/// `(a_r, u_r) o (a_l, u_l) = (a_r*a_l, u_r + a_r*u_l)`. +fn diag_scan_block( + b: &mut Builder, + log_a: &Val, + bx: &Val, + readout: Option<&Val>, + h0: &Val, +) -> (Val, Val) { + let [rows, d, n] = log_a.ty.shape.as_slice() else { + panic!("diagonal scan block must be [T,D,N]"); + }; + let (rows, d, n) = (*rows, *d, *n); + let full = vec![rows, d, n]; + let log_a = to_f32(b, log_a); + let mut decay = b.exponential(&log_a); + let mut acc = to_f32(b, bx); + let mut step = 1; + while step < rows { + let previous_decay = shift_rows(b, &decay, step, 1.0); + let previous_acc = shift_rows(b, &acc, step, 0.0); + let carried = b.multiply(&decay, &previous_acc); + acc = b.add(&acc, &carried); + decay = b.multiply(&decay, &previous_decay); + step *= 2; + } + let h0 = to_f32(b, h0); + let h0 = b.broadcast(&h0, &[1, 2], full); + let from_h0 = b.multiply(&decay, &h0); + let states = b.add(&from_h0, &acc); + let y = match readout { + Some(readout) => { + let readout = to_f32(b, readout); + let readout = b.reshape(&readout, vec![rows, 1, n]); + let readout = b.broadcast(&readout, &[0, 1, 2], vec![rows, d, n]); + let product = b.multiply(&states, &readout); + let zero = b.const_f32(0.0); + b.reduce_add(&product, 2, &zero) + } + None => b.reshape(&states, vec![rows, d]), + }; + let last = b.slice(&states, &[(rows - 1, rows), (0, d), (0, n)]); + (y, b.reshape(&last, vec![d, n])) +} + +/// Chunked diagonal scan over `log_a, bx [T,D,N]` from `h0 [D,N]`. +/// +/// `readout [T,N]` produces `y[t,d] = sum_n readout[t,n] * h[t,d,n]`. +/// With no readout, `N` must be one and the sole state column is returned. +pub(crate) fn diag_scan_prefill( + b: &mut Builder, + log_a: &Val, + bx: &Val, + readout: Option<&Val>, + h0: &Val, + chunk: usize, +) -> (Val, Val) { + assert!(chunk > 0, "diagonal scan chunk must be positive"); + let [t, d, n] = log_a.ty.shape.as_slice() else { + panic!("diagonal scan log_a must be [T,D,N]"); + }; + let (t, d, n) = (*t, *d, *n); + assert_eq!(bx.ty.shape, vec![t, d, n]); + assert_eq!(h0.ty.shape, vec![d, n]); + if let Some(c) = readout { + assert_eq!(c.ty.shape, vec![t, n]); + } else { + assert_eq!(n, 1, "a diagonal scan without readout requires N == 1"); + } + + let mut h = to_f32(b, h0); + let mut all_y: Option = None; + for begin in (0..t).step_by(chunk) { + let end = (begin + chunk).min(t); + let log_block = b.slice(log_a, &[(begin, end), (0, d), (0, n)]); + let bx_block = b.slice(bx, &[(begin, end), (0, d), (0, n)]); + let read_block = readout.map(|c| b.slice(c, &[(begin, end), (0, n)])); + let (block_y, next) = diag_scan_block(b, &log_block, &bx_block, read_block.as_ref(), &h); + h = next; + all_y = Some(match all_y { + Some(previous) => b.concatenate(&previous, &block_y, 0), + None => block_y, + }); + } + (all_y.expect("the mixer requires a non-empty sequence"), h) +} + +fn kind(c: &SsmConfig) -> (usize, bool) { + match c.kind { + SsmKind::Mamba1 { dt_rank, bcdt_norm } => (dt_rank, bcdt_norm), + SsmKind::Mamba2 => panic!("Mamba1 mixer requires SsmKind::Mamba1"), + } +} + +/// Weightless RMSNorm over the last axis, computed in f32. +fn rms_no_weight(b: &mut Builder, x: &Val, eps: f32) -> Val { + let x = to_f32(b, x); + let axis = x.ty.shape.len() - 1; + let width = x.ty.shape[axis]; + let square = b.multiply(&x, &x); + let zero = b.const_f32(0.0); + let sum = b.reduce_add(&square, axis, &zero); + let denominator = splat(b, width as f32, &sum.ty.shape); + let mean = b.divide(&sum, &denominator); + let epsilon = splat(b, eps, &mean.ty.shape); + let stabilized = b.add(&mean, &epsilon); + let inverse = b.rsqrt(&stabilized); + let dims: Vec = (0..axis).collect(); + let inverse = b.broadcast(&inverse, &dims, x.ty.shape.clone()); + b.multiply(&x, &inverse) +} + +/// Project `x [R,H]` to the pre-conv branch and SiLU gate, both `[R,D]`. +fn in_projection(b: &mut Builder, c: &SsmConfig, w: &Mamba1MixerW, x: &Val) -> (Val, Val) { + let rows = x.ty.shape[0]; + let d = c.d_inner(); + let x = to_f32(b, x); + let projected = b.linear_seq_proj(&x, &w.in_proj); + let projected = match &w.in_proj_b { + Some(bias) => add_last(b, &projected, bias), + None => projected, + }; + let xs = b.slice(&projected, &[(0, rows), (0, d)]); + let z = b.slice(&projected, &[(0, rows), (d, 2 * d)]); + (xs, z) +} + +/// Project activated conv rows into discretized dt and the B/C read vectors. +fn scan_parameters(b: &mut Builder, c: &SsmConfig, w: &Mamba1MixerW, x: &Val) -> (Val, Val, Val) { + let rows = x.ty.shape[0]; + let (rank, normalize) = kind(c); + let n = c.state_size; + let x = to_f32(b, x); + let projected = b.linear_seq_proj(&x, &w.x_proj); + let mut dt = b.slice(&projected, &[(0, rows), (0, rank)]); + let mut bm = b.slice(&projected, &[(0, rows), (rank, rank + n)]); + let mut cm = b.slice(&projected, &[(0, rows), (rank + n, rank + 2 * n)]); + if normalize { + dt = rms_no_weight(b, &dt, c.norm_eps); + bm = rms_no_weight(b, &bm, c.norm_eps); + cm = rms_no_weight(b, &cm, c.norm_eps); + } + let dt = b.linear_seq_proj(&dt, &w.dt_proj); + let dt = add_last(b, &dt, &w.dt_proj_b); + (softplus(b, &dt), bm, cm) +} + +fn decay_rate(b: &mut Builder, a_log: &Val) -> Val { + let a_log = to_f32(b, a_log); + let exponential = b.exponential(&a_log); + b.negate(&exponential) +} + +fn gated_output(b: &mut Builder, w: &Mamba1MixerW, y: &Val, z: &Val) -> Val { + let gate = silu(b, z); + let gated = b.multiply(y, &gate); + let out = b.linear_seq_proj(&gated, &w.out_proj); + match &w.out_proj_b { + Some(bias) => add_last(b, &out, bias), + None => out, + } +} + +/// One Mamba1 mixer layer over a padded prompt. The scan is lowered one bounded +/// chunk at a time, so a capacity of 4096 never creates `[4096,D,N]` operands. +#[allow(clippy::too_many_arguments)] +pub(crate) fn mamba1_mixer_prefill( + b: &mut Builder, + c: &SsmConfig, + w: &Mamba1MixerW, + x: &Val, + real_len: &Val, + h0: &Val, + conv0: &Val, +) -> (Val, Val, Val) { + let t = x.ty.shape[0]; + let (d, n, k) = (c.d_inner(), c.state_size, c.conv_kernel); + let (conv_input, z) = in_projection(b, c, w, x); + let conv0 = to_f32(b, conv0); + let xp = b.concatenate(&conv0, &conv_input, 0); + let conv = conv1d_over_left_context(b, &xp, &w.conv_w, w.conv_b.as_ref(), k); + let tail = tail_of_left_context(b, &xp, real_len, k); + let xs = silu(b, &conv); + let (dt, bm, cm) = scan_parameters(b, c, w, &xs); + let rows = b.iota(t); + let rows = b.broadcast(&rows, &[0], vec![t, d]); + let limit = b.broadcast(real_len, &[], vec![t, d]); + let live = b.compare("LT", &rows, &limit, "SIGNED"); + let zeros = splat(b, 0.0, &[t, d]); + let dt = b.select(&live, &dt, &zeros); + let a = decay_rate(b, &w.a_log); + let d_skip = to_f32(b, &w.d); + + let mut h = to_f32(b, h0); + let mut output: Option = None; + for begin in (0..t).step_by(c.chunk_size) { + let end = (begin + c.chunk_size).min(t); + let rows = end - begin; + let x_block = b.slice(&xs, &[(begin, end), (0, d)]); + let dt_block = b.slice(&dt, &[(begin, end), (0, d)]); + let b_block = b.slice(&bm, &[(begin, end), (0, n)]); + let c_block = b.slice(&cm, &[(begin, end), (0, n)]); + + let dt3 = b.reshape(&dt_block, vec![rows, d, 1]); + let dt3 = b.broadcast(&dt3, &[0, 1, 2], vec![rows, d, n]); + let a3 = b.broadcast(&a, &[1, 2], vec![rows, d, n]); + let log_a = b.multiply(&dt3, &a3); + let dt_x = b.multiply(&dt_block, &x_block); + let dt_x = b.reshape(&dt_x, vec![rows, d, 1]); + let dt_x = b.broadcast(&dt_x, &[0, 1, 2], vec![rows, d, n]); + let b3 = b.reshape(&b_block, vec![rows, 1, n]); + let b3 = b.broadcast(&b3, &[0, 1, 2], vec![rows, d, n]); + let bx = b.multiply(&dt_x, &b3); + let (y, next) = diag_scan_prefill(b, &log_a, &bx, Some(&c_block), &h, rows); + h = next; + let skip = b.broadcast(&d_skip, &[1], vec![rows, d]); + let skip = b.multiply(&skip, &x_block); + let y = b.add(&y, &skip); + output = Some(match output { + Some(previous) => b.concatenate(&previous, &y, 0), + None => y, + }); + } + let y = output.expect("the mixer requires a non-empty sequence"); + (gated_output(b, w, &y, &z), h, tail) +} + +/// One batched Mamba1 decode step. +pub(crate) fn mamba1_mixer_step( + b: &mut Builder, + c: &SsmConfig, + w: &Mamba1MixerW, + x: &Val, + st: &SsmLayerState, +) -> (Val, SsmLayerState) { + let batch = x.ty.shape[0]; + let (d, n) = (c.d_inner(), c.state_size); + let (conv_input, z) = in_projection(b, c, w, x); + let (conv, tail) = conv1d_causal_step( + b, + &conv_input, + &st.conv, + &w.conv_w, + w.conv_b.as_ref(), + c.conv_kernel, + ); + let xs = silu(b, &conv); + let (dt, bm, cm) = scan_parameters(b, c, w, &xs); + let a = decay_rate(b, &w.a_log); + let dt3 = b.reshape(&dt, vec![batch, d, 1]); + let dt3 = b.broadcast(&dt3, &[0, 1, 2], vec![batch, d, n]); + let a3 = b.broadcast(&a, &[1, 2], vec![batch, d, n]); + let log_a = b.multiply(&dt3, &a3); + let dt_x = b.multiply(&dt, &xs); + let dt_x = b.reshape(&dt_x, vec![batch, d, 1]); + let dt_x = b.broadcast(&dt_x, &[0, 1, 2], vec![batch, d, n]); + let b3 = b.reshape(&bm, vec![batch, 1, n]); + let b3 = b.broadcast(&b3, &[0, 1, 2], vec![batch, d, n]); + let bx = b.multiply(&dt_x, &b3); + let h = diag_scan_step(b, &log_a, &bx, &st.h); + let c3 = b.reshape(&cm, vec![batch, 1, n]); + let c3 = b.broadcast(&c3, &[0, 1, 2], vec![batch, d, n]); + let read = b.multiply(&h, &c3); + let zero = b.const_f32(0.0); + let y = b.reduce_add(&read, 2, &zero); + let d_skip = to_f32(b, &w.d); + let d_skip = b.broadcast(&d_skip, &[1], vec![batch, d]); + let skip = b.multiply(&xs, &d_skip); + let y = b.add(&y, &skip); + let out = gated_output(b, w, &y, &z); + (out, SsmLayerState { h, conv: tail }) +} diff --git a/src/lib/mlxcel-xla/src/emitter/ssm_tests.rs b/src/lib/mlxcel-xla/src/emitter/ssm_tests.rs index f0fbc525c..8166cdc3f 100644 --- a/src/lib/mlxcel-xla/src/emitter/ssm_tests.rs +++ b/src/lib/mlxcel-xla/src/emitter/ssm_tests.rs @@ -17,7 +17,7 @@ //! `examples/xla_ssm_probe.rs`. use super::builder::{Builder, Precision, Ty}; -use super::config::SsmConfig; +use super::config::{SsmConfig, SsmKind}; use super::model::{ProbeMode, emit_ssm_probe, emit_ssm_probe_with}; use super::ssm; use super::ssm_scan::SsmPrefillForm; @@ -61,6 +61,18 @@ fn ssm_config_validates_structure() { assert!(bad.validate().unwrap_err().contains("time_step_limit")); } +#[test] +fn mamba1_config_uses_diagonal_projection_widths() { + let c = SsmConfig::tiny_mamba1(false); + c.validate().expect("tiny Mamba1 config is valid"); + assert_eq!(c.d_inner(), 16); + assert_eq!(c.in_proj_dim(), 32); + assert_eq!(c.conv_dim, 16); + let mut bad = c.clone(); + bad.conv_dim += 1; + assert!(bad.validate().unwrap_err().contains("conv_dim")); +} + /// The dims will come from an untrusted config.json (#3338): products that wrap /// must not satisfy the conv_dim equation, and clamps or eps that make every /// state NaN are rejected up front. @@ -78,6 +90,12 @@ fn ssm_config_rejects_overflow_and_non_finite_parameters() { let mut bad = c.clone(); bad.conv_kernel = usize::MAX; assert!(bad.validate().unwrap_err().contains("overflow")); + let mut bad = SsmConfig::tiny_mamba1(false); + bad.kind = super::config::SsmKind::Mamba1 { + dt_rank: usize::MAX, + bcdt_norm: false, + }; + assert!(bad.validate().unwrap_err().contains("x_proj_dim")); for limit in [ (f32::INFINITY, f32::INFINITY), @@ -149,6 +167,94 @@ fn ssm_decode_probe_carries_batched_state() { assert_lowerable(&graph); } +#[test] +fn mamba1_probe_uses_bounded_diagonal_scan_and_state_shapes() { + let c = SsmConfig::tiny_mamba1(false); + let graph = emit_ssm_probe(&c, 8, 9, ProbeMode::Prefill); + let sig = signature(&graph); + for arg in [ + "tensor<32x8xf32> loc(\"ssm.in_proj\")", + "tensor<10x16xf32> loc(\"ssm.x_proj\")", + "tensor<16x2xf32> loc(\"ssm.dt_proj\")", + "tensor<16xf32> loc(\"ssm.dt_proj_b\")", + "tensor<16x4xf32> loc(\"ssm.a_log\")", + "tensor<16x4xf32> loc(\"ssm.h0\")", + "tensor<3x16xf32> loc(\"ssm.conv0\")", + ] { + assert!(sig.contains(arg), "missing {arg} in {sig}"); + } + assert!( + graph.contains("tensor<4x16x4xf32>"), + "the selected chunk must appear" + ); + assert!( + !graph.contains("tensor<9x16x4xf32>"), + "the full capacity-sized diagonal state must never materialize" + ); + assert!(sig.contains("-> (tensor<9x8xf32>, tensor<16x4xf32>, tensor<3x16xf32>)")); + assert_lowerable(&graph); + + let decode = emit_ssm_probe(&c, 8, 3, ProbeMode::Decode); + assert!(signature(&decode).contains("tensor<3x16x4xf32> loc(\"ssm.h0\")")); + assert!( + signature(&decode).contains("-> (tensor<3x8xf32>, tensor<3x16x4xf32>, tensor<3x3x16xf32>)") + ); +} + +#[test] +fn mamba1_capacity_4096_graph_stays_chunk_bounded_and_log_depth() { + let mut c = SsmConfig::tiny_mamba1(false); + c.kind = SsmKind::Mamba1 { + dt_rank: 48, + bcdt_norm: false, + }; + c.head_dim = 1536; + c.state_size = 16; + c.conv_dim = 1536; + c.norm_group_size = 1536; + c.chunk_size = 128; + let graph = emit_ssm_probe(&c, 768, 4096, ProbeMode::Prefill); + assert!(graph.contains("tensor<128x1536x16xf32>")); + assert!(!graph.contains("tensor<4096x1536x16xf32>")); + assert!( + graph.lines().count() < 4_000, + "a row-unrolled scan regressed to {} StableHLO lines", + graph.lines().count() + ); + assert!( + graph.matches("stablehlo.concatenate").count() < 80, + "output assembly must be per chunk, not per row" + ); + assert_lowerable(&graph); +} + +#[test] +fn falcon_mamba_probe_adds_weightless_bcdt_norms() { + let plain = emit_ssm_probe(&SsmConfig::tiny_mamba1(false), 8, 3, ProbeMode::Decode); + let falcon = emit_ssm_probe(&SsmConfig::tiny_mamba1(true), 8, 3, ProbeMode::Decode); + assert_eq!(plain.matches("stablehlo.rsqrt").count(), 0); + assert_eq!(falcon.matches("stablehlo.rsqrt").count(), 3); +} + +#[test] +fn diagonal_scan_returns_each_readout_and_final_state() { + let mut b = Builder::new(); + let log_a = Builder::arg(0, Ty::f32(vec![5, 3, 2])); + let bx = Builder::arg(1, Ty::f32(vec![5, 3, 2])); + let readout = Builder::arg(2, Ty::f32(vec![5, 2])); + let h0 = Builder::arg(3, Ty::f32(vec![3, 2])); + let (y, h) = ssm::diag_scan_prefill(&mut b, &log_a, &bx, Some(&readout), &h0, 2); + assert_eq!(y.ty.shape, vec![5, 3]); + assert_eq!(h.ty.shape, vec![3, 2]); + let step = ssm::diag_scan_step( + &mut b, + &Builder::arg(4, Ty::f32(vec![3, 2])), + &Builder::arg(5, Ty::f32(vec![3, 2])), + &h, + ); + assert_eq!(step.ty.shape, vec![3, 2]); +} + #[test] fn ssm_every_prefill_form_emits_the_same_interface() { let c = SsmConfig::tiny_mamba2(); diff --git a/src/lib/mlxcel-xla/src/ssm_probe.rs b/src/lib/mlxcel-xla/src/ssm_probe.rs index 3ad56c071..c6e6ad3e7 100644 --- a/src/lib/mlxcel-xla/src/ssm_probe.rs +++ b/src/lib/mlxcel-xla/src/ssm_probe.rs @@ -14,11 +14,12 @@ //! Single-layer SSM mixer probe runner (issue #3337). //! -//! Emits one Mamba2 mixer layer ([`crate::emitter::emit_ssm_probe_with`]), -//! compiles it for a device, and runs it through the auxiliary IREE ABI with -//! the mixer weights resident and the activations and state as inputs. The -//! `xla_ssm_probe` example feeds it the inputs `spike/openxla/ssm_oracle.py` -//! wrote and hands the outputs back to the oracle for comparison. +//! Emits one Mamba2, Mamba1, or Falcon-Mamba mixer layer +//! ([`crate::emitter::emit_ssm_probe_with`]), compiles it for a device, and runs +//! it through the auxiliary IREE ABI with the mixer weights resident and the +//! activations and state as inputs. The `xla_ssm_probe` example feeds it the +//! inputs `spike/openxla/ssm_oracle.py` wrote and hands the outputs back to the +//! oracle for comparison. #[cfg(feature = "iree")] use std::process::Command; @@ -33,7 +34,8 @@ use crate::auxiliary::{ AuxiliaryWeightStorage, IreeAuxiliaryModule, }; use crate::emitter::{ - Precision, ProbeMode, SsmConfig, SsmPrefillForm, emit_ssm_probe_with, precision_env_override, + Precision, ProbeMode, SsmConfig, SsmKind, SsmPrefillForm, emit_ssm_probe_with, + precision_env_override, }; #[cfg(feature = "iree")] use crate::iree::{compile_one, iree_compile_bin, target_flags}; @@ -41,6 +43,8 @@ use crate::iree::{compile_one, iree_compile_bin, target_flags}; /// The probe's dimensions and mode, as `ssm_oracle.py` records them. #[derive(Clone, Debug, PartialEq)] pub struct SsmProbeSpec { + /// `mamba2` or `mamba1`. + pub kind: String, pub hidden: usize, pub n_heads: usize, pub head_dim: usize, @@ -53,6 +57,10 @@ pub struct SsmProbeSpec { pub norm_eps: f32, pub norm_group_size: usize, pub chunk_size: usize, + /// Mamba1 low-rank dt projection width (ignored by Mamba2). + pub dt_rank: usize, + /// Falcon-Mamba's weightless RMSNorm on dt, B, and C. + pub bcdt_norm: bool, /// Prefill: the padded capacity `T`. Decode: the batch rows `B`. pub rows: usize, /// `true` for one decode step, `false` for a padded prefill. @@ -74,17 +82,30 @@ impl SsmProbeSpec { if i32::try_from(self.rows).is_err() { return Err(format!("SSM probe rows={} do not fit i32", self.rows)); } - let conv_dim = self + let d_inner = self .n_heads .checked_mul(self.head_dim) - .and_then(|d_inner| { + .ok_or("SSM probe d_inner overflows usize")?; + let (kind, conv_dim) = match self.kind.as_str() { + "mamba2" => ( + SsmKind::Mamba2, self.n_groups - .checked_mul(self.state_size)? - .checked_mul(2)? - .checked_add(d_inner) - }) - .ok_or("SSM probe conv_dim overflows usize")?; + .checked_mul(self.state_size) + .and_then(|gn| gn.checked_mul(2)) + .and_then(|bc| bc.checked_add(d_inner)) + .ok_or("SSM probe conv_dim overflows usize")?, + ), + "mamba1" => ( + SsmKind::Mamba1 { + dt_rank: self.dt_rank, + bcdt_norm: self.bcdt_norm, + }, + d_inner, + ), + other => return Err(format!("unknown SSM probe kind {other:?}")), + }; let config = SsmConfig { + kind, n_heads: self.n_heads, head_dim: self.head_dim, state_size: self.state_size, @@ -114,13 +135,22 @@ impl SsmProbeSpec { if c.use_conv_bias { layout.push(("conv_b", vec![cd])); } - layout.extend([ - ("dt_bias", vec![h]), - ("a_log", vec![h]), - ("d", vec![h]), - ("norm_w", vec![c.d_inner()]), - ("out_proj", vec![self.hidden, c.d_inner()]), - ]); + match c.kind { + SsmKind::Mamba2 => layout.extend([ + ("dt_bias", vec![h]), + ("a_log", vec![h]), + ("d", vec![h]), + ("norm_w", vec![c.d_inner()]), + ]), + SsmKind::Mamba1 { dt_rank, .. } => layout.extend([ + ("x_proj", vec![dt_rank + 2 * c.state_size, c.d_inner()]), + ("dt_proj", vec![c.d_inner(), dt_rank]), + ("dt_proj_b", vec![c.d_inner()]), + ("a_log", vec![c.d_inner(), c.state_size]), + ("d", vec![c.d_inner()]), + ]), + } + layout.push(("out_proj", vec![self.hidden, c.d_inner()])); if c.use_bias { layout.push(("out_proj_b", vec![self.hidden])); } @@ -132,19 +162,18 @@ impl SsmProbeSpec { let c = self.config()?; let (h, p, n) = (c.n_heads, c.head_dim, c.state_size); let tail = c.conv_kernel - 1; - Ok(if self.decode { - [ - vec![self.rows, self.hidden], - vec![self.rows, h, p, n], - vec![self.rows, tail, c.conv_dim], - ] + let h_shape = match (c.kind, self.decode) { + (SsmKind::Mamba2, true) => vec![self.rows, h, p, n], + (SsmKind::Mamba2, false) => vec![h, p, n], + (SsmKind::Mamba1 { .. }, true) => vec![self.rows, c.d_inner(), n], + (SsmKind::Mamba1 { .. }, false) => vec![c.d_inner(), n], + }; + let conv_shape = if self.decode { + vec![self.rows, tail, c.conv_dim] } else { - [ - vec![self.rows, self.hidden], - vec![h, p, n], - vec![tail, c.conv_dim], - ] - }) + vec![tail, c.conv_dim] + }; + Ok([vec![self.rows, self.hidden], h_shape, conv_shape]) } /// The probe's StableHLO text. f32 contractions (the HF fp32 gate) unless @@ -450,6 +479,7 @@ mod tests { fn tiny_spec() -> SsmProbeSpec { SsmProbeSpec { + kind: "mamba2".to_string(), hidden: 16, n_heads: 4, head_dim: 8, @@ -462,6 +492,8 @@ mod tests { norm_eps: 1e-5, norm_group_size: 32, chunk_size: 8, + dt_rank: 0, + bcdt_norm: false, rows: 16, decode: false, form: "chunked".to_string(), diff --git a/src/lib/mlxcel-xla/src/validation.rs b/src/lib/mlxcel-xla/src/validation.rs index 30d77e0f5..1c7e0ab5b 100644 --- a/src/lib/mlxcel-xla/src/validation.rs +++ b/src/lib/mlxcel-xla/src/validation.rs @@ -487,6 +487,22 @@ pub(crate) static OLMOE_TINY: ArchFixture = ArchFixture { ], }; +/// Mamba1 (synthetic tiny): a whole-model decode golden for the diagonal +/// `[D,N]` recurrent state, low-rank dt projection, Mamba1 weight order, linear +/// biases, and untied LM head (issue #3348). Prefill's chunk-bounded recurrence +/// shape is guarded separately by the focused emitter tests; freezing a +/// context-capacity-sized sequential scan would add a disproportionately large +/// asset without covering a distinct model ABI. +pub(crate) static MAMBA_TINY: ArchFixture = ArchFixture { + arch: "mamba-tiny", + config_json: include_str!("../assets/mamba-tiny/config.json"), + graphs: &[GraphFixture { + kind: GraphKind::Decode { sample: false }, + golden_name: "decode.mlir", + golden: include_str!("../assets/mamba-tiny/decode.mlir"), + }], +}; + /// A dense-pack fixture: a small synthetic `config.json` and the frozen decode + /// prefill goldens for a family. `$sample` selects the graph tail the goldens were /// frozen with: `true` returns the on-device argmax token (the issue #499 pack: @@ -593,6 +609,7 @@ pub(crate) static REGISTERED: &[&ArchFixture] = &[ &QWEN2_MOE_TINY, &QWEN3_MOE_TINY, &OLMOE_TINY, + &MAMBA_TINY, ]; /// A golden-less structural fixture (issue #497): a small synthetic `config.json` @@ -964,6 +981,24 @@ mod tests { } } + /// Author the first Mamba1 whole-model golden. This remains opt-in so an + /// ordinary test run never writes the source tree. + #[test] + fn freeze_mamba1_goldens() { + if std::env::var("MLXCEL_FREEZE_MAMBA1").as_deref() != Ok("1") { + return; + } + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("assets/mamba-tiny"); + for (name, mlir) in MAMBA_TINY + .emit_all() + .unwrap_or_else(|e| panic!("mamba-tiny: {e}")) + { + let p = root.join(name); + std::fs::write(&p, mlir).unwrap_or_else(|e| panic!("write {}: {e}", p.display())); + eprintln!("froze {}", p.display()); + } + } + /// Re-freeze the committed goldens for every registered fixture. A no-op unless /// `MLXCEL_FREEZE_GOLDENS=1`; when set it rewrites each `assets//*.mlir` /// from the current emitter output. Run it to refresh goldens after an diff --git a/src/lib/mlxcel-xla/src/weight_names.rs b/src/lib/mlxcel-xla/src/weight_names.rs index 8596c1450..744de1d98 100644 --- a/src/lib/mlxcel-xla/src/weight_names.rs +++ b/src/lib/mlxcel-xla/src/weight_names.rs @@ -206,7 +206,7 @@ pub(crate) fn scheme_names(scheme: WeightScheme) -> SchemeNames { // (`input_layernorm`); its mixer tensors are named by // `weights::push_ssm_layer_specs`. The attention / MLP names are never // emitted for this scheme. - WeightScheme::Mamba2 => SchemeNames { + WeightScheme::Mamba2 | WeightScheme::Mamba1 => SchemeNames { embed: "backbone.embeddings.weight", final_norm: "backbone.norm_f.weight", lm_head: "lm_head.weight", diff --git a/src/lib/mlxcel-xla/src/weights.rs b/src/lib/mlxcel-xla/src/weights.rs index 7776d5ade..f118de327 100644 --- a/src/lib/mlxcel-xla/src/weights.rs +++ b/src/lib/mlxcel-xla/src/weights.rs @@ -215,8 +215,20 @@ fn push_ssm_layer_specs(out: &mut Vec, cfg: &Config, p: &str, quant: if ssm.use_conv_bias { out.push(WeightSpec::Whole(format!("{m}conv1d.bias"))); } - for name in ["dt_bias", "A_log", "D", "norm.weight"] { - out.push(WeightSpec::Whole(format!("{m}{name}"))); + match ssm.kind { + crate::emitter::SsmKind::Mamba2 => { + for name in ["dt_bias", "A_log", "D", "norm.weight"] { + out.push(WeightSpec::Whole(format!("{m}{name}"))); + } + } + crate::emitter::SsmKind::Mamba1 { .. } => { + push_proj(out, format!("{m}x_proj.weight"), quant); + push_proj(out, format!("{m}dt_proj.weight"), quant); + out.push(WeightSpec::Whole(format!("{m}dt_proj.bias"))); + for name in ["A_log", "D"] { + out.push(WeightSpec::Whole(format!("{m}{name}"))); + } + } } push_proj(out, format!("{m}out_proj.weight"), quant); if ssm.use_bias {