Skip to main content

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/// Resident scratch for the FP8 prefill GEMM (mirrors `CutlassScratch`): the quantized activation
79/// (grown to the largest m*k seen), the 4-float scale block ([0]=amax, [1]=quant mul, [2]=folded
80/// B_SCALE — the GEMM desc holds a POINTER to slot 2, so the buffer must be resident/stable), and
81/// the cuBLASLt workspace (64MB, the probe's size). Single GPU worker => no concurrent use; the
82/// Mutex guards lazy build/grow only (matches moe_cache / cutlass_scratch).
83pub struct Fp8Scratch {
84    pub xq: CudaSlice<u8>,
85    pub scales: CudaSlice<f32>,
86    pub ws: CudaSlice<u8>,
87    cap_xq: usize,
88}
89
90/// cuBLASLt workspace size — same 64MB the probe ran its heuristics with.
91const FP8_WS_BYTES: usize = 64 << 20;
92
93impl crate::Engine {
94    /// FP8 prefill GEMM for a weight carrying the fp8 operand: y[m,out] = x[m,in] @ (e4m3 W)^T
95    /// with the per-batch act scale and per-tensor weight_scale folded in-GEMM. Returns None when
96    /// the env is off or the weight has no fp8 operand (caller falls through to the Q8_0 path).
97    pub fn try_fp8_gemm(
98        &self,
99        w: &crate::model::GpuTensor,
100        x: &CudaSlice<f32>,
101        m: usize,
102    ) -> Result<Option<CudaSlice<f32>>, Box<dyn std::error::Error>> {
103        use crate::model::GpuTensor;
104        // H100 (sm_90) is the first-class FP8 arch: cuBLASLt e4m3 GEMM is native there,
105        // so the Hopper-MMA lane re-admits this path (Phase A5, ARCHITECTURE-H100.md).
106        if crate::portable_mma_gated() {
107            return Ok(None);
108        }
109        // Two e4m3 operand sources, one GEMM:
110        //  * QT_F8_E4M3 (MEMRA_ST_E4M3): the RESIDENT decode bytes ARE the raw checkpoint e4m3 —
111        //    prefill rides them directly (one copy, no budget). Unconditional: this dtype has no
112        //    other prefill GEMM class, so the FP8 path is inherent to the config, not a flag.
113        //  * fp8 stash (MEMRA_PP_FP8=1): the Q8_0-decode config's optional duplicate operand.
114        //    Block-128 stash operands (blk: Some, Qwen official FP8) are SKIPPED: this GEMM
115        //    feeds ONE folded scalar via B_SCALE_POINTER; a block grid through it would apply
116        //    scale 1.0 to every tile. The block-scaled GEMM is P1 (probe/fp8_lt_blk_probe.cu
117        //    arbitrates cuBLASLt BLK128x128 vs a scale-fold pre-pass on sm_120).
118        let (w_bytes, w_scale, ne) = match w {
119            GpuTensor::Quant {
120                qtype,
121                bytes,
122                scale,
123                ne,
124                ..
125            } if *qtype == crate::QT_F8_E4M3 => (bytes, *scale, ne),
126            GpuTensor::Quant {
127                fp8: Some(f8), ne, ..
128            } if pp_fp8_enabled() && f8.blk.is_none() => (&f8.bytes, f8.scale, ne),
129            _ => return Ok(None),
130        };
131        let (in_f, out_f) = (ne[0] as usize, ne[1] as usize);
132
133        // lazy build / grow the resident scratch to this m*k
134        let need_xq = m * in_f;
135        let mut guard = self.fp8_scratch.lock().unwrap();
136        if guard.is_none() {
137            *guard = Some(Fp8Scratch {
138                xq: self.alloc_u8_uninit(need_xq)?,
139                scales: self.alloc_uninit::<f32>(4)?,
140                ws: self.alloc_u8_uninit(FP8_WS_BYTES)?,
141                cap_xq: need_xq,
142            });
143        }
144        let s = guard.as_mut().unwrap();
145        if need_xq > s.cap_xq {
146            s.xq = self.alloc_u8_uninit(need_xq)?;
147            s.cap_xq = need_xq;
148        }
149
150        let mut y = self.uninit(m * out_f)?; // full-overwrite GEMM output: skip memset
151        let rc = {
152            let stream = self.gpu.stream();
153            // Hold every SyncOnDrop guard across the FFI call (same pattern as cutlass_ffi);
154            // the block scope drops them before `y` is returned.
155            let (w_p, _gw) = w_bytes.device_ptr(&stream);
156            let (x_p, _gx) = x.device_ptr(&stream);
157            let (q_p, _gq) = s.xq.device_ptr_mut(&stream);
158            let (sc_p, _gs) = s.scales.device_ptr_mut(&stream);
159            let (y_p, _gy) = y.device_ptr_mut(&stream);
160            let (ws_p, _gws) = s.ws.device_ptr_mut(&stream);
161            unsafe {
162                memra_fp8_pp_gemm(
163                    w_p as *const core::ffi::c_void,
164                    x_p as *const f32,
165                    q_p as *mut core::ffi::c_void,
166                    sc_p as *mut f32,
167                    y_p as *mut f32,
168                    m as i32,
169                    out_f as i32,
170                    in_f as i32,
171                    w_scale,
172                    ws_p as *mut core::ffi::c_void,
173                    FP8_WS_BYTES,
174                    stream.cu_stream() as *mut core::ffi::c_void,
175                )
176            }
177        };
178        if rc != 0 {
179            return Err(format!(
180                "memra_fp8_pp_gemm rc={rc} (m={m} n={out_f} k={in_f}; 1xxxx=cudaError quant chain, \
181                 2xxxx=no cublasLt algo, 3xxxx=matmul status)"
182            )
183            .into());
184        }
185        Ok(Some(y))
186    }
187}
188
189// ============================================================================================
190// P1 option (b) — PER-BLOCK FP8 MMQ prefill (cu/mmq_fp8_blk.cu, lane/fp8-mmq)
191// ============================================================================================
192
193/// `MEMRA_FP8_MMQ=1` gate (default OFF; lane/fp8-mmq 2026-08-04): block-128 FP8 prefill GEMMs run
194/// through memra's OWN per-block MMQ tile instead of falling to the Q8_0 floor.
195///
196/// This is the third and only exact-AND-fast option from P1-VERDICT.md. cuBLASLt cannot take the
197/// grid at all on sm_120; ARM A's per-tensor fold is fast but diverges at greedy pos 20; ARM B' is
198/// exact but lands on the Q8_0 MMQ. This arm consumes the checkpoint's e4m3 bytes and the
199/// per-[128x128] f32 grid directly, with no re-quantization on either operand's weight side.
200///
201/// Default OFF until the model-level battery is green on the target rig — same posture the
202/// W4A8/F8F4 seams shipped with.
203pub fn fp8_mmq_enabled() -> bool {
204    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
205    *ON.get_or_init(|| {
206        std::env::var("MEMRA_FP8_MMQ")
207            .map(|v| v == "1")
208            .unwrap_or(false)
209    })
210}
211
212/// Per-tensor e4m3-NaN verdicts, keyed by the weight's device pointer. The hardware MMA reads
213/// magnitude 0x7F as NaN while the host / ARM B' reference decodes it to 0.0, so a tensor
214/// containing any must NOT ride this kernel. The scan is a full pass over the weight, so it runs
215/// ONCE per tensor (first prefill dispatch) and the verdict is cached — never per-GEMM.
216static FP8_MMQ_NAN_OK: std::sync::Mutex<Option<std::collections::HashMap<u64, bool>>> =
217    std::sync::Mutex::new(None);
218
219impl crate::Engine {
220    /// PER-BLOCK FP8 MMQ prefill GEMM for a weight carrying a block-128 fp8 operand:
221    /// y[m,out] = x[m,in] @ (e4m3 W)^T with each [128x128] weight block scaled by its own f32.
222    /// Returns None when the env is off, the weight has no block-128 fp8 operand, the shape is
223    /// unsupported, or the NaN precondition fails (caller falls through to the Q8_0 floor).
224    pub fn try_fp8_blk_mmq(
225        &self,
226        w: &crate::model::GpuTensor,
227        x: &CudaSlice<f32>,
228        m: usize,
229    ) -> Result<Option<CudaSlice<f32>>, Box<dyn std::error::Error>> {
230        use crate::model::GpuTensor;
231        // Entry counter BEFORE the env gate: a ledger of all zeros is otherwise ambiguous between
232        // "the flag was not seen" and "no prefill GEMM ever reached this hook".
233        FP8_MMQ_ENTRIES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
234        if !fp8_mmq_enabled() || crate::portable_mma_gated() {
235            FP8_MMQ_GATE_OFF.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
236            return Ok(None);
237        }
238        let (f8, ne) = match w {
239            GpuTensor::Quant {
240                fp8: Some(f8), ne, ..
241            } if f8.blk.is_some() => (f8, ne),
242            // A zero dispatch count is ambiguous on its own: no block operand resident looks
243            // exactly like a shape refusal. Count the no-operand case separately so the receipt
244            // says WHICH, and never per-GEMM-log (this fires on every projection of every layer).
245            _ => {
246                FP8_MMQ_NO_OPERAND.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
247                return Ok(None);
248            }
249        };
250        if ne.len() != 2 {
251            FP8_MMQ_BAD_SHAPE.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
252            return Ok(None);
253        }
254        let (in_f, out_f) = (ne[0] as usize, ne[1] as usize);
255        // in_f % 16: the kernel's 16B tile-copy line. blk grid dims must match the shape — a
256        // mismatch means the operand and the grid came from different tensors; refuse rather than
257        // index a wrong block.
258        let blk = f8.blk.as_ref().unwrap();
259        if in_f % 16 != 0
260            || blk.rows != out_f.div_ceil(128)
261            || blk.cols != in_f.div_ceil(128)
262            || f8.bytes.len() < out_f * in_f
263            || x.len() < m * in_f
264        {
265            FP8_MMQ_BAD_SHAPE.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
266            return Ok(None);
267        }
268        // The per-tensor scale must be the block class's identity (source.rs sets 1.0 alongside a
269        // grid); anything else would mean a second, unapplied scale factor.
270        if f8.scale != 1.0 {
271            FP8_MMQ_BAD_SCALE.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
272            return Ok(None);
273        }
274
275        // One-time NaN precondition per tensor (cached by device pointer).
276        {
277            let key = {
278                let stream = self.gpu.stream();
279                let (p, _g) = f8.bytes.device_ptr(&stream);
280                p as u64
281            };
282            let mut guard = FP8_MMQ_NAN_OK.lock().unwrap();
283            let map = guard.get_or_insert_with(std::collections::HashMap::new);
284            let ok = match map.get(&key) {
285                Some(v) => *v,
286                None => {
287                    let v = self.fp8_blk_nan_count(&f8.bytes)? == 0;
288                    map.insert(key, v);
289                    v
290                }
291            };
292            if !ok {
293                FP8_MMQ_NAN_REFUSED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
294                return Ok(None);
295            }
296        }
297
298        let y = self.qmatvec_mmq_fp8_blk(&f8.bytes, &blk.scales, x, m, in_f, out_f)?;
299        FP8_MMQ_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
300        Ok(Some(y))
301    }
302}
303
304/// Dispatch counter for this kernel. A model-level exactness or perf result is only evidence if
305/// the kernel actually RAN — a silently-refused precondition (no block operand made resident, the
306/// stash budget spent before the tensor, a NaN code present) looks exactly like "bit-identical to
307/// the floor" and "no perf change". `MEMRA_FP8_MMQ_STATS=1` prints the count at process exit so
308/// every such run carries its own proof of coverage.
309static FP8_MMQ_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
310
311/// Refusal counters, one per precondition. Without these a `dispatches: 0` receipt says only
312/// "the kernel did not run", which is the same string for "no block operand was ever made
313/// resident" (budget spent / loader arm not taken / not a block-128 checkpoint) and for "the
314/// operand was there but the shape or the NaN scan rejected it". Those demand opposite fixes, so
315/// the receipt has to distinguish them.
316static FP8_MMQ_NO_OPERAND: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
317static FP8_MMQ_BAD_SHAPE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
318static FP8_MMQ_BAD_SCALE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
319static FP8_MMQ_NAN_REFUSED: std::sync::atomic::AtomicUsize =
320    std::sync::atomic::AtomicUsize::new(0);
321static FP8_MMQ_ENTRIES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
322static FP8_MMQ_GATE_OFF: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
323
324/// Number of prefill GEMMs that went through the per-block FP8 MMQ tile so far this process.
325pub fn fp8_mmq_hits() -> usize {
326    FP8_MMQ_HITS.load(std::sync::atomic::Ordering::Relaxed)
327}
328
329/// `entries, gate_off, hits, no_operand, bad_shape, bad_scale, nan_refused` — the full ledger.
330/// `entries` is incremented before any guard, so `entries == 0` means no prefill GEMM reached the
331/// hook at all (a dispatch-wiring fact), while `gate_off == entries` means the flag was not seen.
332pub fn fp8_mmq_ledger() -> (usize, usize, usize, usize, usize, usize, usize) {
333    use std::sync::atomic::Ordering::Relaxed;
334    (
335        FP8_MMQ_ENTRIES.load(Relaxed),
336        FP8_MMQ_GATE_OFF.load(Relaxed),
337        FP8_MMQ_HITS.load(Relaxed),
338        FP8_MMQ_NO_OPERAND.load(Relaxed),
339        FP8_MMQ_BAD_SHAPE.load(Relaxed),
340        FP8_MMQ_BAD_SCALE.load(Relaxed),
341        FP8_MMQ_NAN_REFUSED.load(Relaxed),
342    )
343}
344
345// ============================================================================================
346// ARM B' — device-side block-128 FP8 -> Q8_0 dequant pass (cu/fp8_blk_dequant.cu)
347// ============================================================================================
348
349unsafe extern "C" {
350    /// Q8_0 slab bytes for an `[out_dim x in_dim]` weight (0 = bad dims).
351    fn memra_fp8_blk_q8_0_bytes(out_dim: i32, in_dim: i32) -> usize;
352    /// One device pass: e4m3 codes + block-128 f32 scale grid -> Q8_0 blocks.
353    /// rc: 0 ok, 1 bad dims, else a cudaError_t.
354    fn memra_fp8_blk_dequant_q8_0(
355        f8_weights: *const core::ffi::c_void,
356        blk_scales: *const f32,
357        out_q8: *mut core::ffi::c_void,
358        out_dim: i32,
359        in_dim: i32,
360        stream: *mut core::ffi::c_void,
361    ) -> i32;
362}
363
364/// `MEMRA_FP8_BLK_GPU=1` gate (default OFF; ARM B', lane fp8-gemm-arm 2026-08-03): block-128
365/// FP8 safetensors weights dequant to Q8_0 ON THE GPU at load instead of host-dequant +
366/// host-re-encode. Bit-parity with the CPU path is a kernel-check gate (`fp8-blk-gpu` arm) and
367/// a real-checkpoint argmax gate — the flag exists because the CPU path stays default until
368/// both are green on the 5090.
369pub fn fp8_blk_gpu_enabled() -> bool {
370    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
371    *ON.get_or_init(|| {
372        std::env::var("MEMRA_FP8_BLK_GPU")
373            .map(|v| v == "1")
374            .unwrap_or(false)
375    })
376}
377
378impl crate::Engine {
379    /// Q8_0 slab byte count for an `[out_f, in_f]` block-128 FP8 weight.
380    pub fn fp8_blk_q8_0_bytes(out_f: usize, in_f: usize) -> usize {
381        unsafe { memra_fp8_blk_q8_0_bytes(out_f as i32, in_f as i32) }
382    }
383
384    /// ARM B' load-time pass: upload the raw e4m3 codes + the block-128 scale grid, dequant on
385    /// the GPU, and return the Q8_0 slab (byte-identical to the host re-encode). `f8` is the
386    /// checkpoint's row-major `[out_f x in_f]` codes; `grid` is the row-major
387    /// `[ceil(out_f/128) x ceil(in_f/128)]` f32 scale grid (F8BlockGrid order, verbatim).
388    pub fn fp8_blk_dequant_q8_0(
389        &self,
390        f8: &[u8],
391        grid: &[f32],
392        out_f: usize,
393        in_f: usize,
394    ) -> Result<CudaSlice<u8>, Box<dyn std::error::Error>> {
395        let (rows, cols) = (out_f.div_ceil(128), in_f.div_ceil(128));
396        if f8.len() != out_f * in_f {
397            return Err(format!(
398                "fp8_blk_dequant_q8_0: f8 len {} != out_f*in_f {}",
399                f8.len(),
400                out_f * in_f
401            )
402            .into());
403        }
404        if grid.len() != rows * cols {
405            return Err(format!(
406                "fp8_blk_dequant_q8_0: grid len {} != rows*cols {rows}*{cols}",
407                grid.len()
408            )
409            .into());
410        }
411        let need = Self::fp8_blk_q8_0_bytes(out_f, in_f);
412        if need == 0 {
413            return Err(format!(
414                "fp8_blk_dequant_q8_0: bad dims out_f={out_f} in_f={in_f} (in_f must be %32)"
415            )
416            .into());
417        }
418        let src = self.htod_bytes(f8)?;
419        let scales = self.htod(grid)?;
420        let mut dst = self.alloc_u8_uninit(need)?;
421        let rc = {
422            let stream = self.gpu.stream();
423            let (s_p, _gs) = src.device_ptr(&stream);
424            let (g_p, _gg) = scales.device_ptr(&stream);
425            let (d_p, _gd) = dst.device_ptr_mut(&stream);
426            unsafe {
427                memra_fp8_blk_dequant_q8_0(
428                    s_p as *const core::ffi::c_void,
429                    g_p as *const f32,
430                    d_p as *mut core::ffi::c_void,
431                    out_f as i32,
432                    in_f as i32,
433                    stream.cu_stream() as *mut core::ffi::c_void,
434                )
435            }
436        };
437        if rc != 0 {
438            return Err(format!(
439                "memra_fp8_blk_dequant_q8_0 rc={rc} (out_f={out_f} in_f={in_f}; 1=bad dims, \
440                 else cudaError_t)"
441            )
442            .into());
443        }
444        self.gpu.stream().synchronize()?;
445        Ok(dst)
446    }
447}