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
79 changes: 79 additions & 0 deletions TECHNICAL_REPORTS/3128-cuda-mamba1-scan-f32-a-20261116.en.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# Technical Report: PR #3128 - let the graph-exact Mamba1 scan take float32 A with f16 x

**Date**: 2026-11-16
**Status**: Completed (verified on GB10; closes #3125)
**Languages**: Rust, C++ (CUDA JIT source)
**Risk Level**: Medium

---

## Executive Summary

Since #3122, f16 Mamba and Jamba keep the SSM `A` in float32 because f16 cannot hold `-exp(A_log)`. CUDA's graph-exact Mamba1 scan kernel accepted only uniform input dtypes, so f16 Jamba on CUDA fell back to the per-timestep graph scan. This PR lets the CUDA kernel accept f16 `x` with float32 `A` and reproduce the graph scan's rounding for that pair, so f16 Jamba prefill on CUDA takes the kernel again. On GB10 (sm_121) the kernel matches the graph scan bit for bit, and f16 Jamba prefill runs about 2.0x faster than on the graph scan.

---

## 1. Problem Statement

`mamba1_scan_kernel_accepts` required every input to share one dtype. After #3122 an f16 model passes `A` as float32, the predicate declined, and Jamba's prefill ran one graph step per token on CUDA. That path is correct but slow on long prompts. Metal and ROCm use a float-state port whose `A` is already float32, so they were unaffected.

---

## 2. Technical Decisions

### 2.1 Admit exactly one extra dtype mix

`mamba1_graph_exact_dtypes_ok` admits uniform floating inputs, plus f16 `x` (with `delta`, `B`, `C`, `D` also f16) and float32 `A`. Wider rules (any float32 `A`, bf16 `x`) were rejected: each extra pair needs its own rounding proof against the graph. A test pins the rule and fails under both mutations tried (rule widened to any float32 `A`; rule reverted to uniform only). The launcher computes `a_t` with the same rule, so an admitted pair is never re-cast.

### 2.2 Mirror the graph's three rounding steps

For the mixed pair the graph scan computes `astype(exp(multiply(delta, A)), f16)`. MLX promotes `delta` to float32 exactly, multiplies once in float32, runs `exp` on float32, then casts round-to-nearest-even. The new `mamba1_decay<T, TA>` does `static_cast<T>(Exp{}(__fmul_rn(float(dt), a)))`. `__fmul_rn` prevents FMA contraction, and no fast-math or ftz flag is set on either the JIT build or the precompiled ops, so the two paths should agree bit for bit. Uniform inputs take the old `Exp{}(mamba1_mul(dt, a))` path.

### 2.3 `TA` only for the CUDA port

MLX's `cuda_kernel` emits template args as `using` declarations at the top of the kernel body, and the generated source is cached by a name derived from the template args. `TA` is therefore added to the template args only on CUDA. The Metal and ROCm sources and cache keys are unchanged. The uniform CUDA instantiation gets a new name (`..._float16`) and one fresh PTX compile.

### 2.4 Mamba stays on the graph scan

`MambaBlock::forward` on CUDA reads the float-state port and keeps the graph scan on purpose, since switching would change CUDA output. The gain here is Jamba-only. The predicate now admits Mamba's f16 inputs too, and a test pins that, but the Mamba forward path is unchanged.

### 2.5 Shared `A` helpers moved

`ssm_a_f32` and `ssm_a_from_log` move from `mamba.rs` into `models::ssm_a`, since Mamba, Jamba, Mamba2 and the SSD scan all use them. The functions are byte-identical.

---

## 3. Change Summary

| Item | Value |
|---|---|
| Files changed | 14 |
| Lines | +421 / -89 |

- `mlx_cxx_kernels.cpp`: `mamba1_decay`, `TA` template arg on CUDA, `mamba1_graph_exact_dtypes_ok`, test FFI `mamba1_graph_exact_scan_accepts_dtypes`.
- `models::ssm_a`: new home for the `A` helpers.
- `docs/environment-variables.md`: `MLXCEL_MAMBA1_SCAN_KERNEL` row notes the f16/float32 case.
- Tests: dtype-rule test (runs everywhere), CUDA bit-identity test for f16 `x` with float32 `A`, Jamba f16 CUDA bit-identity test, extended mixed-dtype decline test, and parity helpers that take an `a_dtype`.

### Validation

- Metal (M3 Ultra): `mamba1_scan_parity` 7/7, `models::mamba`, `models::jamba`, `models::ssd_scan` pass; clippy, fmt and contract checks pass. The CUDA tests return early here.
- Independent desk check of the CUDA source against MLX's `cuda_kernel` at the pinned commit: no defects found in template-arg emission, `static_assert` placement, intrinsics, cache keys, or the predicate.
- GB10 (sm_121), `--features cuda`: `mamba1_scan` 7 passed (including the f16 `x` + float32 `A` bit-identity test), and `models::jamba models::mamba models::ssd_scan` 56 passed, 3 ignored (including `jamba_f16_cuda_kernel_matches_the_graph_scan_bit_for_bit`). NVRTC compiles the JIT source.
- GB10 prefill A/B, `ai21-jamba-reasoning-3b-4bit` with `MLXCEL_CUDA_F16_NORMALIZE=1`, 2151-token prompt, 3 runs each:

| Scan path | Prefill (tok/s) | Decode (tok/s) |
|---|---|---|
| Kernel | 2071.8 / 2091.5 / 2115.9 | 99.4 / 101.1 / 101.2 |
| Graph scan (`MLXCEL_MAMBA1_SCAN_KERNEL=0`) | 1003.3 / 1012.1 / 1058.1 | 92.3 / 95.1 / 95.8 |

Greedy output (32 tokens) is byte-identical across all six runs and finite.

- The GB10 run also found that `jamba_f16_model_with_an_overflowing_a_log_keeps_finite_logits` (from #3122) aborted a CPU-only lib test run: its MoE fixture reaches MLX's CPU `GatherMM`, which only takes float32. The test now returns early without a GPU backend.

---

## 4. Follow-up Actions

- Not measured: an 8192-token prompt. The 2151-token result already shows the per-timestep graph scan is the bottleneck, and the gap should widen with length.
- Not changed (LOW): the test-only FFI maps unknown dtype codes to float32, and the predicate admits uniform float64 as it did before this PR, though that instantiation would not compile. No model passes float64.
79 changes: 79 additions & 0 deletions TECHNICAL_REPORTS/3128-cuda-mamba1-scan-f32-a-20261116.ko.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# 기술 리포트: PR #3128 - graph-exact Mamba1 scan이 f16 x와 float32 A를 받도록

**작성일**: 2026-11-16
**상태**: 완료 (GB10에서 검증, #3125 해결)
**언어**: Rust, C++ (CUDA JIT 소스)
**위험도**: Medium

---

## 요약

#3122 이후 f16 Mamba와 Jamba는 f16이 `-exp(A_log)`를 담지 못하므로 SSM `A`를 float32로 유지한다. CUDA의 graph-exact Mamba1 scan 커널은 입력 dtype이 모두 같을 때만 받았기 때문에, CUDA에서 f16 Jamba는 timestep마다 도는 graph scan으로 떨어졌다. 이 PR은 CUDA 커널이 f16 `x`와 float32 `A` 조합을 받아 그 조합에서 graph scan과 같은 rounding을 내도록 해서, CUDA의 f16 Jamba prefill이 다시 커널을 탄다. GB10(sm_121)에서 커널은 graph scan과 비트 단위로 같고, f16 Jamba prefill은 graph scan보다 약 2.0배 빠르다.

---

## 1. 문제 정의

`mamba1_scan_kernel_accepts`는 모든 입력이 같은 dtype이어야 했다. #3122 이후 f16 모델은 `A`를 float32로 넘기므로 predicate가 거부했고, CUDA에서 Jamba prefill은 토큰마다 graph step을 하나씩 돌았다. 결과는 맞지만 긴 프롬프트에서 느리다. Metal과 ROCm은 `A`가 원래 float32인 float-state port를 쓰므로 영향이 없었다.

---

## 2. 기술적 선택과 그 이유

### 2.1 조합 하나만 추가로 허용

`mamba1_graph_exact_dtypes_ok`는 균일한 floating 입력과, f16 `x`(`delta`, `B`, `C`, `D`도 f16)에 float32 `A`인 경우만 받는다. 더 넓은 규칙(아무 float32 `A`, bf16 `x`)은 택하지 않았다. 조합마다 graph와 rounding이 같다는 증명이 따로 필요하기 때문이다. 규칙을 고정하는 테스트는 시도한 두 변형(아무 float32 `A` 허용, 균일 입력만 허용으로 되돌림) 모두에서 실패한다. launcher도 같은 규칙으로 `a_t`를 정하므로 허용된 조합이 다시 cast되지 않는다.

### 2.2 graph의 rounding 세 단계를 그대로 재현

혼합 조합에서 graph scan은 `astype(exp(multiply(delta, A)), f16)`을 계산한다. MLX는 `delta`를 float32로 손실 없이 올리고, float32 곱셈을 한 번 하고, float32로 `exp`를 돌린 뒤, round-to-nearest-even으로 cast한다. 새 `mamba1_decay<T, TA>`는 `static_cast<T>(Exp{}(__fmul_rn(float(dt), a)))`를 계산한다. `__fmul_rn`이 FMA contraction을 막고, JIT 빌드와 미리 컴파일된 op 어느 쪽에도 fast-math나 ftz가 없으므로 두 경로는 비트 단위로 같아야 한다. 균일 입력은 기존 `Exp{}(mamba1_mul(dt, a))` 경로를 그대로 쓴다.

### 2.3 `TA`는 CUDA port에만

MLX의 `cuda_kernel`은 template arg를 커널 본문 맨 위에 `using` 선언으로 넣고, 생성된 소스는 template arg로 만든 이름을 키로 캐시한다. 그래서 `TA`는 CUDA에서만 template arg에 넣었다. Metal과 ROCm은 소스와 캐시 키가 바뀌지 않는다. 균일 dtype의 CUDA instantiation은 이름이 새로(`..._float16`) 바뀌어 PTX 컴파일을 한 번 새로 한다.

### 2.4 Mamba는 graph scan 유지

CUDA에서 `MambaBlock::forward`는 float-state port를 보고 일부러 graph scan을 유지한다. 바꾸면 CUDA 출력이 달라지기 때문이다. 그래서 이 PR의 이득은 Jamba에만 해당한다. predicate는 이제 Mamba의 f16 입력도 받고 테스트가 이를 고정하지만, Mamba forward 경로는 바뀌지 않았다.

### 2.5 공용 `A` helper 이동

`ssm_a_f32`와 `ssm_a_from_log`는 Mamba, Jamba, Mamba2, SSD scan이 함께 쓰므로 `mamba.rs`에서 `models::ssm_a`로 옮겼다. 함수 내용은 그대로다.

---

## 3. 변경 요약

| 항목 | 값 |
|---|---|
| 변경 파일 | 14 |
| 라인 | +421 / -89 |

- `mlx_cxx_kernels.cpp`: `mamba1_decay`, CUDA의 `TA` template arg, `mamba1_graph_exact_dtypes_ok`, 테스트용 FFI `mamba1_graph_exact_scan_accepts_dtypes`.
- `models::ssm_a`: `A` helper의 새 위치.
- `docs/environment-variables.md`: `MLXCEL_MAMBA1_SCAN_KERNEL` 행에 f16/float32 경우를 적음.
- 테스트: dtype 규칙 테스트(모든 호스트), f16 `x`와 float32 `A`의 CUDA 비트 일치 테스트, Jamba f16 CUDA 비트 일치 테스트, 혼합 dtype 거부 테스트 확장, `a_dtype`을 받는 parity helper.

### 검증

- Metal(M3 Ultra): `mamba1_scan_parity` 7/7, `models::mamba`, `models::jamba`, `models::ssd_scan` 통과. clippy, fmt, contract check 통과. CUDA 테스트는 여기서 일찍 반환한다.
- 고정된 MLX commit의 `cuda_kernel`에 대해 CUDA 소스를 별도로 코드 검토했다. template arg 생성, `static_assert` 위치, intrinsic, 캐시 키, predicate에서 결함을 찾지 못했다.
- GB10(sm_121), `--features cuda`: `mamba1_scan` 7개 통과(f16 `x` + float32 `A` 비트 일치 테스트 포함), `models::jamba models::mamba models::ssd_scan` 56개 통과, 3개 ignored(`jamba_f16_cuda_kernel_matches_the_graph_scan_bit_for_bit` 포함). NVRTC가 JIT 소스를 컴파일한다.
- GB10 prefill A/B. `ai21-jamba-reasoning-3b-4bit`, `MLXCEL_CUDA_F16_NORMALIZE=1`, 2151 토큰 프롬프트, 경로마다 3회:

| Scan 경로 | Prefill (tok/s) | Decode (tok/s) |
|---|---|---|
| Kernel | 2071.8 / 2091.5 / 2115.9 | 99.4 / 101.1 / 101.2 |
| Graph scan (`MLXCEL_MAMBA1_SCAN_KERNEL=0`) | 1003.3 / 1012.1 / 1058.1 | 92.3 / 95.1 / 95.8 |

greedy 출력(32토큰)은 6회 모두 바이트 단위로 같고 유한하다.

- GB10 실행에서 #3122의 `jamba_f16_model_with_an_overflowing_a_log_keeps_finite_logits`가 CPU 전용 lib 테스트를 중단시킨다는 것도 드러났다. MoE fixture가 float32만 받는 MLX CPU `GatherMM`에 닿기 때문이다. 이제 GPU backend가 없으면 일찍 반환한다.

---

## 4. 후속 조치

- 측정하지 않은 것: 8192 토큰 프롬프트. 2151 토큰 결과로도 timestep마다 도는 graph scan이 병목임이 드러나고, 길이가 늘수록 격차는 커질 것이다.
- 고치지 않은 것(LOW): 테스트 전용 FFI는 모르는 dtype 코드를 float32로 취급한다. predicate는 이 PR 이전처럼 균일 float64를 받는데, 그 instantiation은 컴파일되지 않는다. float64를 넘기는 모델은 없다.
Loading
Loading