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

Filter by extension

Filter by extension

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

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

//! Single-layer Mamba2 mixer execution check (issue #3337).
//! Single-layer Mamba2/Mamba1/Falcon-Mamba execution check (issues #3337, #3348).
//!
//! Reads the inputs `spike/openxla/ssm_oracle.py --emit-inputs DIR` wrote,
//! compiles the emitter's SSM probe for `--device`, runs it through the IREE
Expand Down Expand Up @@ -134,6 +134,11 @@ fn spec_from_meta(meta: &Value, args: &Args) -> Result<SsmProbeSpec, String> {
.ok_or("meta.json norm_eps is not a number")? as f32;
let flag = |key: &str| field(meta, key).map(|v| v.as_bool().unwrap_or(false));
Ok(SsmProbeSpec {
kind: meta
.get("kind")
.and_then(Value::as_str)
.unwrap_or("mamba2")
.to_string(),
hidden: usize_field(meta, "hidden")?,
n_heads: usize_field(meta, "n_heads")?,
head_dim: usize_field(meta, "head_dim")?,
Expand All @@ -149,6 +154,11 @@ fn spec_from_meta(meta: &Value, args: &Args) -> Result<SsmProbeSpec, String> {
Some(size) => size,
None => usize_field(meta, "chunk_size")?,
},
dt_rank: meta.get("dt_rank").and_then(Value::as_u64).unwrap_or(0) as usize,
bcdt_norm: meta
.get("bcdt_norm")
.and_then(Value::as_bool)
.unwrap_or(false),
rows: usize_field(meta, "rows")?,
decode: field(meta, "mode")?.as_str() == Some("decode"),
form: args.form.clone().unwrap_or_else(|| "chunked".to_string()),
Expand Down
2 changes: 1 addition & 1 deletion scripts/ci/check_env_var_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 "
Expand Down
Loading
Loading