memra_engine/fp8_ffi.rs
1//! FP8-ACT PREFILL (MEMRA_PP_FP8=1): cuBLASLt FP8-E4M3 TN GEMM for the F8-E4M3-origin projections.
2//!
3//! Probe verdict 2026-07-08 (probe/fp8_lt_prefill.cu, JSONL row in research/tune-data): cuBLASLt
4//! FP8 GEMM runs 620-795 TF at the 27B prefill shapes vs 47-72 TF for the qmatvec_gemm_q8_0 class
5//! those weights ride today (46.5% of pp GPU time) — projected ~1.85x pp from the F8-native
6//! layers alone. The weight side is EXACT: the checkpoint's raw e4m3 bytes + per-tensor f32
7//! weight_scale are stashed at load next to the Q8_0 re-encode (`GpuTensor::Quant { fp8 }`,
8//! following the `cutlass` optional-operand precedent). The only new rounding vs today is the
9//! ACTIVATION: f32 -> e4m3 with ONE per-batch scalar scale (amax/448) instead of q8_1's per-32
10//! int8 — finer mantissa lost, coarser scale granularity; the run-gen argmax gate arbitrates.
11//!
12//! Dispatch: `matmul`/`matmul_pre` m>=16 arms ONLY (prefill). Decode (m<16) keeps the Q8_0
13//! dp4a/MMVQ chain bit-for-bit — the spec-exactness law is untouched, and the m=K+1 verify tier
14//! (m<=9) never reaches this path.
15//!
16//! All device work (amax reduce, scale finalize, e4m3 quantize, cublasLtMatmul) runs on the one
17//! `gpu.stream` inside a single C-ABI call (cu/fp8_prefill.cu) — no host sync anywhere: the act
18//! scale is folded with weight_scale into a device scalar fed to the GEMM's B_SCALE_POINTER
19//! (per-token OUTER_VEC B-scales are NOT supported on sm_120 — probed; scalar scales verified
20//! exact there).
21
22use cudarc::driver::{CudaSlice, DevicePtr, DevicePtrMut};
23
24unsafe extern "C" {
25 /// One FP8 prefill GEMM: quantize act f32->e4m3 (per-batch scalar) + cublasLtMatmul TN.
26 /// Returns 0 on success (see cu/fp8_prefill.cu for the error-code bands).
27 fn memra_fp8_pp_gemm(
28 w_e4m3: *const core::ffi::c_void,
29 x_f32: *const f32,
30 xq_e4m3: *mut core::ffi::c_void,
31 scales: *mut f32,
32 y_f32: *mut f32,
33 m: i32,
34 n: i32,
35 k: i32,
36 w_scale: f32,
37 ws: *mut core::ffi::c_void,
38 ws_bytes: usize,
39 stream: *mut core::ffi::c_void,
40 ) -> i32;
41}
42
43/// `MEMRA_PP_FP8=1` gate (default OFF), read once. Gates BOTH the loader stash (model.rs) and the
44/// prefill dispatch — unset means zero VRAM / zero dispatch change.
45pub fn pp_fp8_enabled() -> bool {
46 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
47 *ON.get_or_init(|| {
48 std::env::var("MEMRA_PP_FP8")
49 .map(|v| v == "1")
50 .unwrap_or(false)
51 })
52}
53
54/// F8-E4M3-origin safetensors projections load as RAW e4m3 (QT_F8_E4M3) instead of the Q8_0
55/// re-encode. NEW NUMERIC CONFIG: decode reads the checkpoint's own e4m3 precision (the Q8_0
56/// re-encode was a lossy extra hop) via qmatvec_e4m3_mmvq; prefill (m>=16) rides the cuBLASLt FP8
57/// GEMM on the SAME resident bytes — one weight copy total (frees the ~GBs the MEMRA_PP_FP8 stash
58/// duplicated, no budget cap needed). Superset relationship: with this on, MEMRA_PP_FP8 and its
59/// budget are irrelevant for F8-origin tensors (they never surface as Q8_0, so the stash arm never
60/// fires).
61///
62/// DEFAULT ON since lane/fp8-decode-v1 (2026-08-05); `MEMRA_ST_E4M3=0` is the rollback seam back to
63/// the Q8_0 slab. Flipped on the 27B FP8-ST receipts in `research/fp8dec-20260805/`: decode +2.58pp
64/// with non-overlapping distributions (N=5 interleaved, one binary), 430 MiB freed at a measured
65/// byte ratio of exactly 1.06250 (= theory, so single residency and no duplicate copy), teacher-
66/// forced exactness 2/128 near-tie flips with LOWER NLL on the reference's own tape than the slab
67/// arm scores on it, kernel-check ALL GREEN, run-spec K=1..8 8/8 PASS, serve-st-gate 0 failed.
68///
69/// SCOPE — the flip only reaches the per-tensor scalar-scale class. `find_fp8_native` returns
70/// `blk: Some(grid)` for the block-128 class and `None` for per-row, and the resident arm in
71/// model.rs additionally requires `blk.is_none()`, so both of those classes still take the Q8_0
72/// re-encode. Nothing here changes GGUF: `TensorSource::find_fp8_native` is None for GGUF sources.
73pub fn st_e4m3_enabled() -> bool {
74 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
75 *ON.get_or_init(|| std::env::var("MEMRA_ST_E4M3").as_deref() != Ok("0"))
76}
77
78/// Native residency for the BLOCK-128 e4m3 scale class (`QT_F8_E4M3_BLK`, lane/fp8-blk128-decode
79/// 2026-08-05) — the Qwen-official FP8 class that `st_e4m3_enabled`'s arm deliberately excludes.
80///
81/// SHARES the `MEMRA_ST_E4M3=0` rollback seam rather than adding a second knob, per flags doctrine:
82/// both arms are the same mechanism (checkpoint-native e4m3 residency + in-kernel dequant) applied
83/// to the two scale classes, and one seam that turns ALL native e4m3 residency back into the Q8_0
84/// slab is the behaviour a rollback wants. `MEMRA_ST_E4M3_BLK=0` additionally disables JUST this
85/// class — the narrow seam that isolates the block arm while leaving the (already shipped,
86/// already receipted) per-tensor arm on its default, which is what an A/B of this lane needs.
87pub fn st_e4m3_blk_enabled() -> bool {
88 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
89 *ON.get_or_init(|| {
90 st_e4m3_enabled() && std::env::var("MEMRA_ST_E4M3_BLK").as_deref() != Ok("0")
91 })
92}
93
94/// A block-128 tensor that PASSED every shape precondition for native residency but carried e4m3
95/// NaN codes, so it fell through to the Q8_0 floor. Counted because "0 tensors resident as
96/// F8_E4M3_BLK" is otherwise ambiguous between "not a block-128 checkpoint", "env off", and "the
97/// bytes were ineligible" — three facts demanding three different responses.
98static BLK_NATIVE_NAN_REFUSED: std::sync::atomic::AtomicUsize =
99 std::sync::atomic::AtomicUsize::new(0);
100
101pub fn note_blk_native_nan_refused() {
102 BLK_NATIVE_NAN_REFUSED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
103}
104
105/// Tensors declined by the native block-128 arm's NaN precondition this process.
106pub fn blk_native_nan_refused() -> usize {
107 BLK_NATIVE_NAN_REFUSED.load(std::sync::atomic::Ordering::Relaxed)
108}
109
110/// Resident scratch for the FP8 prefill GEMM (mirrors `CutlassScratch`): the quantized activation
111/// (grown to the largest m*k seen), the 4-float scale block ([0]=amax, [1]=quant mul, [2]=folded
112/// B_SCALE — the GEMM desc holds a POINTER to slot 2, so the buffer must be resident/stable), and
113/// the cuBLASLt workspace (64MB, the probe's size). Single GPU worker => no concurrent use; the
114/// Mutex guards lazy build/grow only (matches moe_cache / cutlass_scratch).
115pub struct Fp8Scratch {
116 pub xq: CudaSlice<u8>,
117 pub scales: CudaSlice<f32>,
118 pub ws: CudaSlice<u8>,
119 cap_xq: usize,
120}
121
122/// cuBLASLt workspace size — same 64MB the probe ran its heuristics with.
123const FP8_WS_BYTES: usize = 64 << 20;
124
125impl crate::Engine {
126 /// FP8 prefill GEMM for a weight carrying the fp8 operand: y[m,out] = x[m,in] @ (e4m3 W)^T
127 /// with the per-batch act scale and per-tensor weight_scale folded in-GEMM. Returns None when
128 /// the env is off or the weight has no fp8 operand (caller falls through to the Q8_0 path).
129 pub fn try_fp8_gemm(
130 &self,
131 w: &crate::model::GpuTensor,
132 x: &CudaSlice<f32>,
133 m: usize,
134 ) -> Result<Option<CudaSlice<f32>>, Box<dyn std::error::Error>> {
135 use crate::model::GpuTensor;
136 // H100 (sm_90) is the first-class FP8 arch: cuBLASLt e4m3 GEMM is native there,
137 // so the Hopper-MMA lane re-admits this path (Phase A5, ARCHITECTURE-H100.md).
138 if crate::portable_mma_gated() {
139 return Ok(None);
140 }
141 // Two e4m3 operand sources, one GEMM:
142 // * QT_F8_E4M3 (MEMRA_ST_E4M3): the RESIDENT decode bytes ARE the raw checkpoint e4m3 —
143 // prefill rides them directly (one copy, no budget). Unconditional: this dtype has no
144 // other prefill GEMM class, so the FP8 path is inherent to the config, not a flag.
145 // * fp8 stash (MEMRA_PP_FP8=1): the Q8_0-decode config's optional duplicate operand.
146 // Block-128 stash operands (blk: Some, Qwen official FP8) are SKIPPED: this GEMM
147 // feeds ONE folded scalar via B_SCALE_POINTER; a block grid through it would apply
148 // scale 1.0 to every tile. The block-scaled GEMM is P1 (probe/fp8_lt_blk_probe.cu
149 // arbitrates cuBLASLt BLK128x128 vs a scale-fold pre-pass on sm_120).
150 let (w_bytes, w_scale, ne) = match w {
151 GpuTensor::Quant {
152 qtype,
153 bytes,
154 scale,
155 ne,
156 ..
157 } if *qtype == crate::QT_F8_E4M3 => (bytes, *scale, ne),
158 GpuTensor::Quant {
159 fp8: Some(f8), ne, ..
160 } if pp_fp8_enabled() && f8.blk.is_none() => (&f8.bytes, f8.scale, ne),
161 _ => return Ok(None),
162 };
163 let (in_f, out_f) = (ne[0] as usize, ne[1] as usize);
164
165 // lazy build / grow the resident scratch to this m*k
166 let need_xq = m * in_f;
167 let mut guard = self.fp8_scratch.lock().unwrap();
168 if guard.is_none() {
169 *guard = Some(Fp8Scratch {
170 xq: self.alloc_u8_uninit(need_xq)?,
171 scales: self.alloc_uninit::<f32>(4)?,
172 ws: self.alloc_u8_uninit(FP8_WS_BYTES)?,
173 cap_xq: need_xq,
174 });
175 }
176 let s = guard.as_mut().unwrap();
177 if need_xq > s.cap_xq {
178 s.xq = self.alloc_u8_uninit(need_xq)?;
179 s.cap_xq = need_xq;
180 }
181
182 let mut y = self.uninit(m * out_f)?; // full-overwrite GEMM output: skip memset
183 let rc = {
184 let stream = self.gpu.stream();
185 // Hold every SyncOnDrop guard across the FFI call (same pattern as cutlass_ffi);
186 // the block scope drops them before `y` is returned.
187 let (w_p, _gw) = w_bytes.device_ptr(&stream);
188 let (x_p, _gx) = x.device_ptr(&stream);
189 let (q_p, _gq) = s.xq.device_ptr_mut(&stream);
190 let (sc_p, _gs) = s.scales.device_ptr_mut(&stream);
191 let (y_p, _gy) = y.device_ptr_mut(&stream);
192 let (ws_p, _gws) = s.ws.device_ptr_mut(&stream);
193 unsafe {
194 memra_fp8_pp_gemm(
195 w_p as *const core::ffi::c_void,
196 x_p as *const f32,
197 q_p as *mut core::ffi::c_void,
198 sc_p as *mut f32,
199 y_p as *mut f32,
200 m as i32,
201 out_f as i32,
202 in_f as i32,
203 w_scale,
204 ws_p as *mut core::ffi::c_void,
205 FP8_WS_BYTES,
206 stream.cu_stream() as *mut core::ffi::c_void,
207 )
208 }
209 };
210 if rc != 0 {
211 return Err(format!(
212 "memra_fp8_pp_gemm rc={rc} (m={m} n={out_f} k={in_f}; 1xxxx=cudaError quant chain, \
213 2xxxx=no cublasLt algo, 3xxxx=matmul status)"
214 )
215 .into());
216 }
217 Ok(Some(y))
218 }
219}
220
221// ============================================================================================
222// P1 option (b) — PER-BLOCK FP8 MMQ prefill (cu/mmq_fp8_blk.cu, lane/fp8-mmq)
223// ============================================================================================
224
225/// `MEMRA_FP8_MMQ=1` gate for the per-block MMQ tile's **STASH** operand source (default OFF;
226/// lane/fp8-mmq 2026-08-04): a SECOND e4m3 copy uploaded next to an already-resident Q8_0 slab,
227/// spending from `MEMRA_PP_FP8_BUDGET_MB`.
228///
229/// This is the third and only exact-AND-fast option from P1-VERDICT.md. cuBLASLt cannot take the
230/// grid at all on sm_120; ARM A's per-tensor fold is fast but diverges at greedy pos 20; ARM B' is
231/// exact but lands on the Q8_0 MMQ. This arm consumes the checkpoint's e4m3 bytes and the
232/// per-[128x128] f32 grid directly, with no re-quantization on either operand's weight side.
233///
234/// STAYS DEFAULT OFF for the stash source, and the reason is the v2 verdict, not inertia: against a
235/// floor whose Q8_0 slab is ALREADY RESIDENT the tile is 0.85-1.09x GEMM-only, so paying a full
236/// duplicate weight copy to reach it is not a win (`lane/fp8-mmq-v2` LANE-VERDICT.jsonl). This
237/// function is ALSO what admits the stash at load (`model.rs`), so it must stay an explicit opt-in:
238/// the native-resident flip below must not silently start duplicating Q8_0 tensors.
239pub fn fp8_mmq_enabled() -> bool {
240 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
241 *ON.get_or_init(|| {
242 std::env::var("MEMRA_FP8_MMQ")
243 .map(|v| v == "1")
244 .unwrap_or(false)
245 })
246}
247
248/// Same tile, **NATIVE-RESIDENT** operand source: a `QT_F8_E4M3_BLK` tensor's own `blk` grid, the
249/// checkpoint's single copy with no slab and no stash. DEFAULT ON since lane/fp8-blk128-decode
250/// (2026-08-05); `MEMRA_FP8_MMQ=0` is the narrow seam back to dequant-per-call.
251///
252/// WHY THE SAME TILE DEFAULTS DIFFERENTLY BY SOURCE — the denominator differs, so the sign does.
253/// With a stash the floor already has its Q8_0 slab resident and the comparison is tile vs tile
254/// (v2: 0.85-1.09x, i.e. not worth a duplicate copy). On the native-resident class the floor must
255/// also CREATE that slab on every prefill call — 27.9 ms/pass of dequant after the vector rewrite,
256/// 14.19 GB of extra weight traffic — so the tile only has to not be 27.9 ms worse than a kernel it
257/// trails by at most ~15% on a subset of shapes. Measured 3-arm interleaved on the 27B block-128
258/// checkpoint (research/fp8blk-20260805/, N=3, one lock hold, one md5-pinned binary):
259/// slab 1540.5 / dequant-per-call 1449.1 / **this tile 1553.3** tok/s, min(C) 1552.4 > max(A) 1541.1
260/// (non-overlapping) = +0.83% pp512 AHEAD of the Q8_0 floor instead of -5.8% behind it.
261///
262/// EXACTNESS, the condition the flip was deferred on (6b741068: "the default flip waits on this
263/// arm's own exactness cells ... rather than inheriting the dequant arm's"). Branch-(b): per-block
264/// f8f6f4 MMA is not the Q8_0 re-encode's arithmetic, so bit-identity is the wrong bar. Measured on
265/// `prime_cache` — the class that actually dispatches this kernel — with a dispatch ledger on every
266/// arm (624 = 208 projections x 3 passes, full coverage) and an A==B bit-identical control proving
267/// the instrument can see zero where zero is: argmax UNCHANGED and the top-10 order identical to the
268/// floor's, rms_rel 2.5e-2 on an rms-2.7155 logit vector, and teacher-forced NLL on the prompt's own
269/// continuation LOWER than the floor's (2.764722 vs 2.787267) on a tape neither arm produced.
270/// `MEMRA_ST_E4M3_BLK=0` / `MEMRA_ST_E4M3=0` also disable this route, by removing the native operand
271/// it consumes — this seam exists for the narrower question (keep native decode residency, revert
272/// only the prefill route).
273pub fn fp8_blk_mmq_native_enabled() -> bool {
274 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
275 *ON.get_or_init(|| std::env::var("MEMRA_FP8_MMQ").as_deref() != Ok("0"))
276}
277
278/// Per-tensor e4m3-NaN verdicts, keyed by the weight's device pointer. The hardware MMA reads
279/// magnitude 0x7F as NaN while the host / ARM B' reference decodes it to 0.0, so a tensor
280/// containing any must NOT ride this kernel. The scan is a full pass over the weight, so it runs
281/// ONCE per tensor (first prefill dispatch) and the verdict is cached — never per-GEMM.
282static FP8_MMQ_NAN_OK: std::sync::Mutex<Option<std::collections::HashMap<u64, bool>>> =
283 std::sync::Mutex::new(None);
284
285impl crate::Engine {
286 /// PER-BLOCK FP8 MMQ prefill GEMM for a weight carrying a block-128 fp8 operand:
287 /// y[m,out] = x[m,in] @ (e4m3 W)^T with each [128x128] weight block scaled by its own f32.
288 /// Returns None when the env is off, the weight has no block-128 fp8 operand, the shape is
289 /// unsupported, or the NaN precondition fails (caller falls through to the Q8_0 floor).
290 pub fn try_fp8_blk_mmq(
291 &self,
292 w: &crate::model::GpuTensor,
293 x: &CudaSlice<f32>,
294 m: usize,
295 ) -> Result<Option<CudaSlice<f32>>, Box<dyn std::error::Error>> {
296 use crate::model::GpuTensor;
297 // Entry counter BEFORE the env gate: a ledger of all zeros is otherwise ambiguous between
298 // "the flag was not seen" and "no prefill GEMM ever reached this hook".
299 FP8_MMQ_ENTRIES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
300 if crate::portable_mma_gated() {
301 FP8_MMQ_GATE_OFF.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
302 return Ok(None);
303 }
304 // TWO OPERAND SOURCES, in this order, EACH WITH ITS OWN DEFAULT (2026-08-05):
305 //
306 // (1) the `fp8` STASH — a SECOND e4m3 copy uploaded alongside a resident Q8_0 slab under
307 // `MEMRA_PP_FP8` / `MEMRA_PP_FP8_BUDGET_MB`. This is what the v1/v2 MMQ lanes measured,
308 // and it stays behind `MEMRA_FP8_MMQ=1` (`fp8_mmq_enabled`): against a floor whose slab
309 // is already resident the tile is 0.85-1.09x, which does not pay for a duplicate copy.
310 //
311 // (2) the `blk` RESIDENCY field on a `QT_F8_E4M3_BLK` tensor (lane/fp8-blk128-decode) —
312 // the checkpoint-native single copy, no slab and no stash. Same bytes, same grid, same
313 // layout contract, so the kernel cannot tell them apart; only the owner differs. This
314 // source is DEFAULT ON (`fp8_blk_mmq_native_enabled`), because its floor must build the
315 // Q8_0 slab every call (27.9 ms/pass) and the tile measured +0.83% pp512 ahead of it
316 // with non-overlapping distributions.
317 //
318 // The gate is therefore checked PER SOURCE, after the operand is known — not once up front.
319 // Checking it before the match would make the native flip also flip the stash, and
320 // `fp8_mmq_enabled` is what admits that stash at LOAD time (model.rs), so a shared gate
321 // would silently start duplicating every Q8_0 tensor with an fp8 sibling.
322 //
323 // Why (1) first: when a stash exists the tensor is ALSO a Q8_0 slab, and the stash is the
324 // operand that arm's budget accounting owns. A `QT_F8_E4M3_BLK` tensor never has a stash
325 // (its residency arm sets `fp8: None`), so the two cases are disjoint in practice and the
326 // order only fixes a hypothetical.
327 let (f8_bytes, f8_scale, blk, ne) = match w {
328 GpuTensor::Quant {
329 fp8: Some(f8), ne, ..
330 } if f8.blk.is_some() => {
331 if !fp8_mmq_enabled() {
332 FP8_MMQ_GATE_OFF.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
333 return Ok(None);
334 }
335 (&f8.bytes, f8.scale, f8.blk.as_ref().unwrap(), ne)
336 }
337 GpuTensor::Quant {
338 bytes, qtype, scale, blk: Some(g), ne, ..
339 } if *qtype == crate::QT_F8_E4M3_BLK => {
340 if !fp8_blk_mmq_native_enabled() {
341 FP8_MMQ_GATE_OFF.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
342 return Ok(None);
343 }
344 (bytes, *scale, g, ne)
345 }
346 // A zero dispatch count is ambiguous on its own: no block operand resident looks
347 // exactly like a shape refusal. Count the no-operand case separately so the receipt
348 // says WHICH, and never per-GEMM-log (this fires on every projection of every layer).
349 _ => {
350 FP8_MMQ_NO_OPERAND.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
351 return Ok(None);
352 }
353 };
354 if ne.len() != 2 {
355 FP8_MMQ_BAD_SHAPE.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
356 return Ok(None);
357 }
358 let (in_f, out_f) = (ne[0] as usize, ne[1] as usize);
359 // in_f % 16: the kernel's 16B tile-copy line. blk grid dims must match the shape — a
360 // mismatch means the operand and the grid came from different tensors; refuse rather than
361 // index a wrong block.
362 if in_f % 16 != 0
363 || blk.rows != out_f.div_ceil(128)
364 || blk.cols != in_f.div_ceil(128)
365 || f8_bytes.len() < out_f * in_f
366 || x.len() < m * in_f
367 {
368 FP8_MMQ_BAD_SHAPE.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
369 return Ok(None);
370 }
371 // The per-tensor scale must be the block class's identity (source.rs sets 1.0 alongside a
372 // grid); anything else would mean a second, unapplied scale factor.
373 if f8_scale != 1.0 {
374 FP8_MMQ_BAD_SCALE.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
375 return Ok(None);
376 }
377
378 // One-time NaN precondition per tensor (cached by device pointer).
379 {
380 let key = {
381 let stream = self.gpu.stream();
382 let (p, _g) = f8_bytes.device_ptr(&stream);
383 p as u64
384 };
385 let mut guard = FP8_MMQ_NAN_OK.lock().unwrap();
386 let map = guard.get_or_insert_with(std::collections::HashMap::new);
387 let ok = match map.get(&key) {
388 Some(v) => *v,
389 None => {
390 let v = self.fp8_blk_nan_count(f8_bytes)? == 0;
391 map.insert(key, v);
392 v
393 }
394 };
395 if !ok {
396 FP8_MMQ_NAN_REFUSED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
397 return Ok(None);
398 }
399 }
400
401 let y = self.qmatvec_mmq_fp8_blk(f8_bytes, &blk.scales, x, m, in_f, out_f)?;
402 FP8_MMQ_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
403 Ok(Some(y))
404 }
405}
406
407/// Dispatch counter for this kernel. A model-level exactness or perf result is only evidence if
408/// the kernel actually RAN — a silently-refused precondition (no block operand made resident, the
409/// stash budget spent before the tensor, a NaN code present) looks exactly like "bit-identical to
410/// the floor" and "no perf change". `MEMRA_FP8_MMQ_STATS=1` prints the count at process exit so
411/// every such run carries its own proof of coverage.
412static FP8_MMQ_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
413
414/// Refusal counters, one per precondition. Without these a `dispatches: 0` receipt says only
415/// "the kernel did not run", which is the same string for "no block operand was ever made
416/// resident" (budget spent / loader arm not taken / not a block-128 checkpoint) and for "the
417/// operand was there but the shape or the NaN scan rejected it". Those demand opposite fixes, so
418/// the receipt has to distinguish them.
419static FP8_MMQ_NO_OPERAND: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
420static FP8_MMQ_BAD_SHAPE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
421static FP8_MMQ_BAD_SCALE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
422static FP8_MMQ_NAN_REFUSED: std::sync::atomic::AtomicUsize =
423 std::sync::atomic::AtomicUsize::new(0);
424static FP8_MMQ_ENTRIES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
425static FP8_MMQ_GATE_OFF: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
426
427/// Number of prefill GEMMs that went through the per-block FP8 MMQ tile so far this process.
428pub fn fp8_mmq_hits() -> usize {
429 FP8_MMQ_HITS.load(std::sync::atomic::Ordering::Relaxed)
430}
431
432/// `entries, gate_off, hits, no_operand, bad_shape, bad_scale, nan_refused` — the full ledger.
433/// `entries` is incremented before any guard, so `entries == 0` means no prefill GEMM reached the
434/// hook at all (a dispatch-wiring fact), while `gate_off == entries` means the flag was not seen.
435pub fn fp8_mmq_ledger() -> (usize, usize, usize, usize, usize, usize, usize) {
436 use std::sync::atomic::Ordering::Relaxed;
437 (
438 FP8_MMQ_ENTRIES.load(Relaxed),
439 FP8_MMQ_GATE_OFF.load(Relaxed),
440 FP8_MMQ_HITS.load(Relaxed),
441 FP8_MMQ_NO_OPERAND.load(Relaxed),
442 FP8_MMQ_BAD_SHAPE.load(Relaxed),
443 FP8_MMQ_BAD_SCALE.load(Relaxed),
444 FP8_MMQ_NAN_REFUSED.load(Relaxed),
445 )
446}
447
448// ============================================================================================
449// ARM B' — device-side block-128 FP8 -> Q8_0 dequant pass (cu/fp8_blk_dequant.cu)
450// ============================================================================================
451
452unsafe extern "C" {
453 /// Q8_0 slab bytes for an `[out_dim x in_dim]` weight (0 = bad dims).
454 fn memra_fp8_blk_q8_0_bytes(out_dim: i32, in_dim: i32) -> usize;
455 /// One device pass: e4m3 codes + block-128 f32 scale grid -> Q8_0 blocks.
456 /// rc: 0 ok, 1 bad dims, else a cudaError_t.
457 fn memra_fp8_blk_dequant_q8_0(
458 f8_weights: *const core::ffi::c_void,
459 blk_scales: *const f32,
460 out_q8: *mut core::ffi::c_void,
461 out_dim: i32,
462 in_dim: i32,
463 stream: *mut core::ffi::c_void,
464 ) -> i32;
465}
466
467/// `MEMRA_FP8_BLK_GPU=1` gate (default OFF; ARM B', lane fp8-gemm-arm 2026-08-03): block-128
468/// FP8 safetensors weights dequant to Q8_0 ON THE GPU at load instead of host-dequant +
469/// host-re-encode. Bit-parity with the CPU path is a kernel-check gate (`fp8-blk-gpu` arm) and
470/// a real-checkpoint argmax gate — the flag exists because the CPU path stays default until
471/// both are green on the 5090.
472pub fn fp8_blk_gpu_enabled() -> bool {
473 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
474 *ON.get_or_init(|| {
475 std::env::var("MEMRA_FP8_BLK_GPU")
476 .map(|v| v == "1")
477 .unwrap_or(false)
478 })
479}
480
481impl crate::Engine {
482 /// Q8_0 slab byte count for an `[out_f, in_f]` block-128 FP8 weight.
483 pub fn fp8_blk_q8_0_bytes(out_f: usize, in_f: usize) -> usize {
484 unsafe { memra_fp8_blk_q8_0_bytes(out_f as i32, in_f as i32) }
485 }
486
487 /// ARM B' load-time pass: upload the raw e4m3 codes + the block-128 scale grid, dequant on
488 /// the GPU, and return the Q8_0 slab (byte-identical to the host re-encode). `f8` is the
489 /// checkpoint's row-major `[out_f x in_f]` codes; `grid` is the row-major
490 /// `[ceil(out_f/128) x ceil(in_f/128)]` f32 scale grid (F8BlockGrid order, verbatim).
491 pub fn fp8_blk_dequant_q8_0(
492 &self,
493 f8: &[u8],
494 grid: &[f32],
495 out_f: usize,
496 in_f: usize,
497 ) -> Result<CudaSlice<u8>, Box<dyn std::error::Error>> {
498 let (rows, cols) = (out_f.div_ceil(128), in_f.div_ceil(128));
499 if f8.len() != out_f * in_f {
500 return Err(format!(
501 "fp8_blk_dequant_q8_0: f8 len {} != out_f*in_f {}",
502 f8.len(),
503 out_f * in_f
504 )
505 .into());
506 }
507 if grid.len() != rows * cols {
508 return Err(format!(
509 "fp8_blk_dequant_q8_0: grid len {} != rows*cols {rows}*{cols}",
510 grid.len()
511 )
512 .into());
513 }
514 let need = Self::fp8_blk_q8_0_bytes(out_f, in_f);
515 if need == 0 {
516 return Err(format!(
517 "fp8_blk_dequant_q8_0: bad dims out_f={out_f} in_f={in_f} (in_f must be %32)"
518 )
519 .into());
520 }
521 let src = self.htod_bytes(f8)?;
522 let scales = self.htod(grid)?;
523 let dst = self.fp8_blk_dequant_q8_0_dev(&src, &scales, out_f, in_f)?;
524 self.gpu.stream().synchronize()?;
525 Ok(dst)
526 }
527
528 /// DEVICE-RESIDENT twin of `fp8_blk_dequant_q8_0` (lane/fp8-blk128-decode): identical kernel,
529 /// identical output bytes, but the e4m3 codes and the scale grid are ALREADY on the device and
530 /// there is no trailing `synchronize`.
531 ///
532 /// Both differences matter to its caller (`try_e4m3_blk_prefill`, per prefill call rather than
533 /// once per load): the host arm's two htods would re-upload a weight that is already resident,
534 /// and its `synchronize` would stall the CUDA owner thread on every prefill projection. Stream
535 /// ordering is sufficient without it — the dequant and the Q8_0 GEMM that consumes `dst` are
536 /// issued to the SAME stream, so the GEMM cannot observe a partially written slab.
537 pub fn fp8_blk_dequant_q8_0_dev(
538 &self,
539 f8: &CudaSlice<u8>,
540 grid: &CudaSlice<f32>,
541 out_f: usize,
542 in_f: usize,
543 ) -> Result<CudaSlice<u8>, Box<dyn std::error::Error>> {
544 let (rows, cols) = (out_f.div_ceil(128), in_f.div_ceil(128));
545 if f8.len() < out_f * in_f {
546 return Err(format!(
547 "fp8_blk_dequant_q8_0_dev: f8 len {} < out_f*in_f {}",
548 f8.len(),
549 out_f * in_f
550 )
551 .into());
552 }
553 if grid.len() < rows * cols {
554 return Err(format!(
555 "fp8_blk_dequant_q8_0_dev: grid len {} < rows*cols {rows}*{cols}",
556 grid.len()
557 )
558 .into());
559 }
560 let need = Self::fp8_blk_q8_0_bytes(out_f, in_f);
561 if need == 0 {
562 return Err(format!(
563 "fp8_blk_dequant_q8_0_dev: bad dims out_f={out_f} in_f={in_f} (in_f must be %32)"
564 )
565 .into());
566 }
567 let mut dst = self.alloc_u8_uninit(need)?;
568 let rc = {
569 let stream = self.gpu.stream();
570 let (s_p, _gs) = f8.device_ptr(&stream);
571 let (g_p, _gg) = grid.device_ptr(&stream);
572 let (d_p, _gd) = dst.device_ptr_mut(&stream);
573 unsafe {
574 memra_fp8_blk_dequant_q8_0(
575 s_p as *const core::ffi::c_void,
576 g_p as *const f32,
577 d_p as *mut core::ffi::c_void,
578 out_f as i32,
579 in_f as i32,
580 stream.cu_stream() as *mut core::ffi::c_void,
581 )
582 }
583 };
584 if rc != 0 {
585 return Err(format!(
586 "memra_fp8_blk_dequant_q8_0 rc={rc} (out_f={out_f} in_f={in_f}; 1=bad dims, \
587 else cudaError_t)"
588 )
589 .into());
590 }
591 Ok(dst)
592 }
593}