Skip to main content

rlx_ir/
quant.rs

1// RLX — versatile ML compiler + runtime.
2// Copyright (C) 2026 Eugene Hauptmann, Nataliya Kosmyna.
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5//! Quantization metadata as graph annotations (plan #57).
6//!
7//! Schemes attach per-tensor via [`QuantMap`] on [`crate::Graph`], not inside
8//! [`crate::Node`], so the common case stays lean.
9//!
10//! # GGUF schemes and backends
11//!
12//! All `Gguf*` variants use two-input `Op::DequantMatMul` (`x`, packed weights).
13//! GPU backends share integer **scheme ids** (0–23) in `dequant_gguf` kernels;
14//! legacy tail: Q4_0 = 19, Q8_0 = 20, Q4_1 = 21, Q5_0 = 22, Q5_1 = 23.
15//!
16//! Per-backend dispatch (GPU dequant, fused GEMV, ANE constexpr, TPU compile-time
17//! bake, env toggles): [`docs/gguf-backend-paths.md`](../../docs/gguf-backend-paths.md).
18
19use crate::NodeId;
20use std::collections::HashMap;
21
22/// How a tensor is quantized. Mirrors the schemes RLX needs for LLM
23/// inference on Apple Silicon: blockwise int8 (GPTQ-style),
24/// blockwise int4 (Q4_K), and per-tensor fp8 (e4m3 / e5m2).
25///
26/// Each variant carries the parameters the dequantizer needs to read
27/// at runtime — scale, zero-point, block size. Where these live in
28/// the actual weight tensor is up to the loader (#56).
29#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
30#[derive(Debug, Clone, Copy, PartialEq)]
31pub enum QuantScheme {
32    /// Symmetric int8 with one scale per `block_size` elements.
33    Int8Block { block_size: u32 },
34    /// Asymmetric int8 with scale + zero-point per `block_size` elements.
35    Int8BlockAsym { block_size: u32 },
36    /// Int4 packed two-per-byte, scale per `block_size` elements
37    /// (Q4_K-ish; matches GGUF block layout).
38    Int4Block { block_size: u32 },
39    /// FP8 e4m3 (no scale; same domain as half).
40    Fp8E4m3,
41    /// FP8 e5m2 (no scale; wider range than e4m3).
42    Fp8E5m2,
43    /// GGUF / llama.cpp Q4_K super-block (256 elements / 144 bytes).
44    /// Packs an f16 super-scale + f16 super-min + 8 sub-block 6-bit
45    /// scales + 8 sub-block 6-bit mins + 128 nibbles. Block layout is
46    /// fixed by the format — there's no `block_size` knob.
47    GgufQ4K,
48    /// GGUF Q5_K (256 / 176 bytes). Adds a 32-byte high-bit plane on
49    /// top of Q4_K.
50    GgufQ5K,
51    /// GGUF Q6_K (256 / 210 bytes). Per-sub-block signed scales,
52    /// no min term.
53    GgufQ6K,
54    /// GGUF Q8_K (256 / 276 bytes). Per-super-block f32 scale plus
55    /// i8 quants and a 32-byte sum-of-blocks table that's only used
56    /// by Q8_K × Q8_K matmul accumulation paths.
57    GgufQ8K,
58    /// GGUF Q2_K (256 / 84 bytes). 2-bit quants with per-sub-block scale/min.
59    GgufQ2K,
60    /// GGUF Q3_K (256 / 110 bytes). 3-bit quants with hmask high bit plane.
61    GgufQ3K,
62    /// GGUF Q4_0 (32 / 18 bytes). Legacy llama.cpp block: f16 scale + signed nibbles (−8..7).
63    GgufQ4_0,
64    /// GGUF Q4_1 (32 / 20 bytes). Legacy block: f16 scale + f16 min + unsigned nibbles (0..15).
65    /// GPU kernel scheme id **21** (shared with Metal/CUDA/ROCm/WGPU).
66    GgufQ4_1,
67    /// GGUF Q5_0 (32 / 22 bytes). Legacy block: f16 scale + 32-bit high plane + signed 5-bit quants.
68    /// GPU kernel scheme id **22**.
69    GgufQ5_0,
70    /// GGUF Q5_1 (32 / 24 bytes). Legacy block: f16 scale + f16 min + high plane + unsigned 5-bit quants.
71    /// GPU kernel scheme id **23**.
72    GgufQ5_1,
73    /// GGUF Q8_0 (32 / 34 bytes). Legacy block: f16 scale + 32×i8 quants.
74    GgufQ8_0,
75    /// NVIDIA FP4 (E2M1) block — fixed 16-element groups, FP8 E4M3 block
76    /// scales, optional f32 global scale on input 3 (legacy `zp` slot).
77    /// Used by FLUX.2 / MLX `nvfp4` checkpoints.
78    Nvfp4Block,
79    /// MLX affine quantization (`nn.quantize` / mlx-lm default): packed
80    /// uint codes + per-group f32 scale and bias. Inputs to
81    /// `DequantMatMul`: `x`, `w_q`, `scales`, `biases` (biases in the
82    /// legacy `zp` slot). Typical `bits=4`, `group_size=64`.
83    MlxAffine { bits: u8, group_size: u32 },
84    /// MLX `mxfp4` mode — E2M1 nibbles × per-group scale (E8M0 or FP8).
85    /// Inputs: `x`, `w_q`, `scales`, unused `zp` (pass ones).
86    MlxMxfp4 { group_size: u32 },
87    /// MLX `mxfp8` mode — FP8 E4M3 codes × per-group scale.
88    MlxMxfp8 { group_size: u32 },
89    /// **MxFp4x2** — two-level residual FP4 (E2M1): `value ≈ s0·q0 + s1·q1`,
90    /// each level an E2M1 nibble plane with its own per-group scale. Roughly
91    /// doubles the effective mantissa of MXFP4 (~3.3 → ~6.7 bits) at 2× storage.
92    /// The low-precision analog of double-word; see [`crate::residual`].
93    MxFp4x2Block { group_size: u32 },
94    // ── GGUF IQ-family (sub-byte LUT-coded) ─────────────────────
95    /// IQ4_NL: 4.5 bpw non-linear. 32-element block (18 bytes).
96    GgufIQ4NL,
97    /// IQ4_XS: 4.25 bpw. 256-element super-block (136 bytes).
98    GgufIQ4XS,
99    /// IQ2_XXS: 2.0625 bpw. 256 / 66.
100    GgufIQ2XXS,
101    /// IQ2_XS: 2.3125 bpw. 256 / 74.
102    GgufIQ2XS,
103    /// IQ2_S: 2.5625 bpw. 256 / 82.
104    GgufIQ2S,
105    /// IQ3_XXS: 3.0625 bpw. 256 / 98.
106    GgufIQ3XXS,
107    /// IQ3_S: 3.4375 bpw. 256 / 110.
108    GgufIQ3S,
109    /// IQ1_S: 1.5625 bpw. 256 / 50.
110    GgufIQ1S,
111    /// IQ1_M: 1.75 bpw. 256 / 56.
112    GgufIQ1M,
113    /// TQ1_0: 1.6875 bpw ternary. 256 / 54.
114    GgufTQ1_0,
115    /// TQ2_0: 2.0625 bpw ternary. 256 / 66.
116    GgufTQ2_0,
117    /// MXFP4: OCP microscaling FP4 with E8M0 scale. 32 / 17.
118    GgufMXFP4,
119    /// NVFP4 GGUF variant: E4M3 scale + E2M1 nibbles. 16 / 9.
120    GgufNVFP4,
121    /// Custom 1-bit format (PrismML `Bonsai-27B`, ggml type 41): one
122    /// f16 group scale + 128 sign bits selecting `±d`. 128 / 18 bytes
123    /// (1.125 bpw). See [`crate`] consumers `rlx_gguf::q1_dequant`.
124    GgufQ1_0,
125    /// PrismML / upstream `Q2_0` (ggml type 42): f16 group scale + 128×2-bit
126    /// codes → `(q−1)·d`. 128 / 34 bytes (2.125 bpw). Used by Ternary Bonsai
127    /// (`prism-ml/Ternary-Bonsai-*-gguf`). See `rlx_gguf::q2_dequant`.
128    GgufQ2_0,
129    /// Fermion five-value ternary (`fermion-fv5` fork, ggml type 43): two f32
130    /// per-row scales `s_lo`/`s_hi` + three 256-bit planes (`bp`,`bn`,`br`)
131    /// → `w = (bp−bn)·(br ? s_hi : s_lo)`, five values `{0, ±s_lo, ±s_hi}`.
132    /// 256 / 104 bytes (3.25 bpw). All Neutrino transformer linears.
133    /// See `rlx_gguf::fv5_dequant`. CPU-only (no GPU kernel — matches the fork).
134    GgufFV5,
135    /// Fermion int8 companion (`fermion-fv5` fork, ggml type 44): one f32
136    /// per-row scale + 256 int8 codes → `w = s·q`. 256 / 260 bytes (8.125 bpw).
137    /// Neutrino's untied int8 `token_embd` / `output` (lm_head).
138    /// See `rlx_gguf::fv5_dequant`.
139    GgufFV5B,
140}
141
142/// Single source of truth for GGUF → GPU `dequant_gguf` scheme ids.
143///
144/// Expanding this macro inside `impl QuantScheme` defines:
145/// - [`QuantScheme::gpu_dequant_scheme_id`]
146/// - [`QuantScheme::from_gpu_dequant_scheme_id`]
147/// - test helper [`QuantScheme::GPU_DEQUANT_SCHEME_ID_PAIRS`]
148///
149/// GPU backends (`gguf_host::gguf_scheme_id` / `scheme_from_id`) must
150/// delegate here — do not re-list variants by hand.
151macro_rules! define_gguf_gpu_dequant_ids {
152    ($(($variant:ident, $id:literal)),+ $(,)?) => {
153        /// Canonical numeric id for the shared on-device GGUF dequant kernel
154        /// (`dequant_gguf` in MSL / CU / WGSL / GLSL).
155        ///
156        /// Generated by `define_gguf_gpu_dequant_ids!` so encode and
157        /// [`Self::from_gpu_dequant_scheme_id`] share one table — backends
158        /// must only call these helpers (no hand-rolled `match` in
159        /// `gguf_host`). Adding a scheme is one macro row + the matching
160        /// kernel branch. Guarded by `gpu_dequant_scheme_id_is_stable`.
161        pub const fn gpu_dequant_scheme_id(self) -> Option<u32> {
162            match self {
163                $(Self::$variant => Some($id),)+
164                _ => None,
165            }
166        }
167
168        /// Inverse of [`Self::gpu_dequant_scheme_id`].
169        pub const fn from_gpu_dequant_scheme_id(id: u32) -> Option<Self> {
170            match id {
171                $($id => Some(Self::$variant),)+
172                _ => None,
173            }
174        }
175
176        /// `(scheme, id)` pairs for tests / docs — keep in sync via the macro.
177        #[cfg(test)]
178        pub(crate) const GPU_DEQUANT_SCHEME_ID_PAIRS: &'static [(Self, u32)] = &[
179            $((Self::$variant, $id),)+
180        ];
181    };
182}
183
184impl QuantScheme {
185    /// Bits per element after packing (×10 for K-quants since they
186    /// have fractional bit budgets — divide by 10 when comparing).
187    pub const fn bits_per_element_x10(self) -> u32 {
188        match self {
189            Self::Int8Block { .. } | Self::Int8BlockAsym { .. } => 80,
190            Self::Int4Block { .. } => 40,
191            Self::Fp8E4m3 | Self::Fp8E5m2 => 80,
192            // GGUF K-quants: header + per-element bits over a 256-element block.
193            Self::GgufQ4K => 45,  // 144 bytes / 256 elems × 8 = 4.5 bpe
194            Self::GgufQ5K => 55,  // 176 / 256 × 8 ≈ 5.5
195            Self::GgufQ6K => 66,  // 210 / 256 × 8 ≈ 6.5625 → 66 (rounded)
196            Self::GgufQ8K => 91,  // 292 / 256 × 8 ≈ 9.125 → 91
197            Self::GgufQ2K => 26,  // 84 / 256 × 8 ≈ 2.625 → 26
198            Self::GgufQ3K => 34,  // 110 / 256 × 8 ≈ 3.4375 → 34
199            Self::GgufQ4_0 => 45, // 18 / 32 × 8 = 4.5 bpe
200            Self::GgufQ4_1 => 50, // 20 / 32 × 8 = 5.0 bpe
201            Self::GgufQ5_0 => 55, // 22 / 32 × 8 = 5.5 bpe
202            Self::GgufQ5_1 => 60, // 24 / 32 × 8 = 6.0 bpe
203            Self::GgufQ8_0 => 85, // 34 / 32 × 8 = 8.5 bpe
204            Self::Nvfp4Block => 40,
205            Self::MlxAffine { bits, .. } => (bits as u32) * 10,
206            Self::MlxMxfp4 { .. } => 40,
207            Self::MlxMxfp8 { .. } => 80,
208            Self::MxFp4x2Block { .. } => 84, // 2× E2M1 nibbles + 2 group scales
209
210            Self::GgufIQ4NL => 45,
211            Self::GgufIQ4XS => 42, // 136/256 × 8 = 4.25
212            Self::GgufIQ2XXS => 20,
213            Self::GgufIQ2XS => 23,
214            Self::GgufIQ2S => 25,
215            Self::GgufIQ3XXS => 30,
216            Self::GgufIQ3S => 34,
217            Self::GgufIQ1S => 15,
218            Self::GgufIQ1M => 17,
219            Self::GgufTQ1_0 => 16, // 54/256 × 8 = 1.6875 → 16
220            Self::GgufTQ2_0 => 20,
221            Self::GgufMXFP4 => 42,
222            Self::GgufNVFP4 => 45,
223            Self::GgufQ1_0 => 11, // 18 bytes / 128 elems × 8 = 1.125 bpe
224            Self::GgufQ2_0 => 21, // 34 bytes / 128 elems × 8 = 2.125 bpe
225            Self::GgufFV5 => 32,  // 104 bytes / 256 elems × 8 = 3.25 bpe
226            Self::GgufFV5B => 81, // 260 bytes / 256 elems × 8 = 8.125 bpe
227        }
228    }
229
230    /// Bits per element after packing (rounded down). Use
231    /// `bits_per_element_x10` for the K-quant fractional values.
232    pub const fn bits_per_element(self) -> u32 {
233        self.bits_per_element_x10() / 10
234    }
235
236    // Table defined once via `define_gguf_gpu_dequant_ids!` above.
237    define_gguf_gpu_dequant_ids! {
238        (GgufQ4K, 0),
239        (GgufQ5K, 1),
240        (GgufQ6K, 2),
241        (GgufQ8K, 3),
242        (GgufQ2K, 4),
243        (GgufQ3K, 5),
244        (GgufIQ4NL, 6),
245        (GgufIQ4XS, 7),
246        (GgufTQ1_0, 8),
247        (GgufTQ2_0, 9),
248        (GgufMXFP4, 10),
249        (GgufNVFP4, 11),
250        (GgufIQ2XXS, 12),
251        (GgufIQ2XS, 13),
252        (GgufIQ2S, 14),
253        (GgufIQ3XXS, 15),
254        (GgufIQ3S, 16),
255        (GgufIQ1S, 17),
256        (GgufIQ1M, 18),
257        (GgufQ4_0, 19),
258        (GgufQ8_0, 20),
259        (GgufQ4_1, 21),
260        (GgufQ5_0, 22),
261        (GgufQ5_1, 23),
262        (GgufQ1_0, 24),
263        (GgufQ2_0, 25),
264        (GgufFV5, 26),
265        (GgufFV5B, 27),
266    }
267
268    /// True if this scheme requires a per-block scale tensor on the side.
269    pub const fn has_scale(self) -> bool {
270        matches!(
271            self,
272            Self::Int8Block { .. }
273                | Self::Int8BlockAsym { .. }
274                | Self::Int4Block { .. }
275                | Self::Nvfp4Block
276                | Self::MlxAffine { .. }
277                | Self::MlxMxfp4 { .. }
278                | Self::MlxMxfp8 { .. }
279                | Self::MxFp4x2Block { .. }
280        )
281    }
282
283    /// True for NVFP4 / MLX mxfp block scales stored as FP8 / E8M0 bytes (not f32).
284    pub const fn scale_is_fp8(self) -> bool {
285        matches!(
286            self,
287            Self::Nvfp4Block | Self::MlxMxfp4 { .. } | Self::MlxMxfp8 { .. }
288        )
289    }
290
291    /// Fixed NVFP4 group size along K (0 for other schemes).
292    pub const fn nvfp4_group_size(self) -> u32 {
293        match self {
294            Self::Nvfp4Block => crate::nvfp4::NVFP4_GROUP_SIZE as u32,
295            _ => 0,
296        }
297    }
298
299    /// For [`Self::MxFp4x2Block`]: `(per-element format, residual levels, group
300    /// size)`; `None` for every other scheme. Ties the scheme to the shared
301    /// residual codec in [`crate::residual`].
302    pub const fn mxfp4x2_config(self) -> Option<(ScaledFormat, u32, u32)> {
303        match self {
304            Self::MxFp4x2Block { group_size } => Some((ScaledFormat::F4E2M1, 2, group_size)),
305            _ => None,
306        }
307    }
308
309    /// True if this scheme requires a per-block zero-point / bias tensor.
310    pub const fn has_zero_point(self) -> bool {
311        matches!(self, Self::Int8BlockAsym { .. } | Self::MlxAffine { .. })
312    }
313
314    /// True for MLX-native affine / mxfp schemes (not GGUF, not legacy int blocks).
315    pub const fn is_mlx(self) -> bool {
316        matches!(
317            self,
318            Self::MlxAffine { .. } | Self::MlxMxfp4 { .. } | Self::MlxMxfp8 { .. }
319        )
320    }
321
322    /// MLX group size along K (0 when not an MLX scheme).
323    pub const fn mlx_group_size(self) -> u32 {
324        match self {
325            Self::MlxAffine { group_size, .. }
326            | Self::MlxMxfp4 { group_size }
327            | Self::MlxMxfp8 { group_size } => group_size,
328            _ => 0,
329        }
330    }
331
332    /// GPU launch args for MLX dequant-matmul kernels: `(kind, bits, group_size)`.
333    ///
334    /// `kind`: 0 = [`Self::MlxAffine`], 1 = [`Self::MlxMxfp4`], 2 = [`Self::MlxMxfp8`].
335    /// `bits` is 0 for mxfp schemes. Returns `None` for non-MLX schemes.
336    pub const fn mlx_gpu_launch(self) -> Option<(u32, u32, u32)> {
337        match self {
338            Self::MlxAffine { bits, group_size } => Some((0, bits as u32, group_size)),
339            Self::MlxMxfp4 { group_size } => Some((1, 0, group_size)),
340            Self::MlxMxfp8 { group_size } => Some((2, 0, group_size)),
341            _ => None,
342        }
343    }
344
345    /// GGUF K-quant block size (256 elements) — meaningless for the
346    /// non-GGUF schemes (returns 0).
347    pub const fn gguf_block_size(self) -> u32 {
348        match self {
349            Self::GgufQ4K
350            | Self::GgufQ5K
351            | Self::GgufQ6K
352            | Self::GgufQ8K
353            | Self::GgufQ2K
354            | Self::GgufQ3K
355            | Self::GgufIQ4XS
356            | Self::GgufIQ2XXS
357            | Self::GgufIQ2XS
358            | Self::GgufIQ2S
359            | Self::GgufIQ3XXS
360            | Self::GgufIQ3S
361            | Self::GgufIQ1S
362            | Self::GgufIQ1M
363            | Self::GgufTQ1_0
364            | Self::GgufTQ2_0
365            | Self::GgufFV5
366            | Self::GgufFV5B => 256,
367            Self::GgufQ4_0
368            | Self::GgufQ4_1
369            | Self::GgufQ5_0
370            | Self::GgufQ5_1
371            | Self::GgufQ8_0
372            | Self::GgufIQ4NL
373            | Self::GgufMXFP4 => 32,
374            Self::GgufNVFP4 => 16,
375            Self::GgufQ1_0 => 128,
376            Self::GgufQ2_0 => 128,
377            _ => 0,
378        }
379    }
380
381    /// Bytes per GGUF super-block. 0 for non-GGUF schemes.
382    pub const fn gguf_block_bytes(self) -> u32 {
383        match self {
384            Self::GgufQ4K => 144, // f16 d + f16 dmin + 12 packed scales + 128 nibbles
385            Self::GgufQ5K => 176, // + 32-byte high-bit plane
386            Self::GgufQ6K => 210, // 128 ql + 64 qh + 16 i8 scales + f16 d
387            Self::GgufQ8K => 292, // f32 d + 256 i8 + 16 i16 bsums = 4 + 256 + 32
388            Self::GgufQ2K => 84,  // f16 d + f16 dmin + 16 scales + 64 qs
389            Self::GgufQ3K => 110, // f16 d + 12 scales + 32 hmask + 64 qs
390            Self::GgufQ4_0 => 18, // f16 d + 16 packed nibbles
391            Self::GgufQ4_1 => 20, // f16 d + f16 min + 16 packed nibbles
392            Self::GgufQ5_0 => 22, // f16 d + 32-bit qh + 16 packed nibbles
393            Self::GgufQ5_1 => 24, // f16 d + f16 min + 32-bit qh + 16 packed nibbles
394            Self::GgufQ8_0 => 34, // f16 d + 32 i8 quants
395            Self::GgufIQ4NL => 18,
396            Self::GgufIQ4XS => 136,
397            Self::GgufIQ2XXS => 66,
398            Self::GgufIQ2XS => 74,
399            Self::GgufIQ2S => 82,
400            Self::GgufIQ3XXS => 98,
401            Self::GgufIQ3S => 110,
402            Self::GgufIQ1S => 50,
403            Self::GgufIQ1M => 56,
404            Self::GgufTQ1_0 => 54,
405            Self::GgufTQ2_0 => 66,
406            Self::GgufMXFP4 => 17,
407            Self::GgufNVFP4 => 9,
408            Self::GgufQ1_0 => 18,  // f16 scale + 128 sign bits
409            Self::GgufQ2_0 => 34,  // Metal fused Q2_0 block (128 elems)
410            Self::GgufFV5 => 104,  // f32 s_lo + f32 s_hi + 3×32B planes (256 elems)
411            Self::GgufFV5B => 260, // f32 s + 256 int8 (256 elems)
412            _ => 0,
413        }
414    }
415
416    /// True for any GGUF-format block scheme. GGUF schemes carry
417    /// their scales / mins / sub-block metadata *inside* the packed
418    /// weight bytes — they don't need separate `scale` / `zp`
419    /// tensors fed alongside as the legacy `Int8Block` paths do.
420    pub const fn is_gguf(self) -> bool {
421        matches!(
422            self,
423            Self::GgufQ4K
424                | Self::GgufQ5K
425                | Self::GgufQ6K
426                | Self::GgufQ8K
427                | Self::GgufQ2K
428                | Self::GgufQ3K
429                | Self::GgufQ4_0
430                | Self::GgufQ4_1
431                | Self::GgufQ5_0
432                | Self::GgufQ5_1
433                | Self::GgufQ8_0
434                | Self::GgufIQ4NL
435                | Self::GgufIQ4XS
436                | Self::GgufIQ2XXS
437                | Self::GgufIQ2XS
438                | Self::GgufIQ2S
439                | Self::GgufIQ3XXS
440                | Self::GgufIQ3S
441                | Self::GgufIQ1S
442                | Self::GgufIQ1M
443                | Self::GgufTQ1_0
444                | Self::GgufTQ2_0
445                | Self::GgufMXFP4
446                | Self::GgufNVFP4
447                | Self::GgufQ1_0
448                | Self::GgufQ2_0
449                | Self::GgufFV5
450                | Self::GgufFV5B
451        )
452    }
453}
454
455impl std::fmt::Display for QuantScheme {
456    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
457        match self {
458            Self::Int8Block { block_size } => write!(f, "int8/{block_size}"),
459            Self::Int8BlockAsym { block_size } => write!(f, "int8a/{block_size}"),
460            Self::Int4Block { block_size } => write!(f, "int4/{block_size}"),
461            Self::Fp8E4m3 => write!(f, "fp8e4m3"),
462            Self::Fp8E5m2 => write!(f, "fp8e5m2"),
463            Self::GgufQ4K => write!(f, "gguf_q4k"),
464            Self::GgufQ5K => write!(f, "gguf_q5k"),
465            Self::GgufQ6K => write!(f, "gguf_q6k"),
466            Self::GgufQ8K => write!(f, "gguf_q8k"),
467            Self::GgufQ2K => write!(f, "gguf_q2k"),
468            Self::GgufQ3K => write!(f, "gguf_q3k"),
469            Self::GgufQ4_0 => write!(f, "gguf_q4_0"),
470            Self::GgufQ4_1 => write!(f, "gguf_q4_1"),
471            Self::GgufQ5_0 => write!(f, "gguf_q5_0"),
472            Self::GgufQ5_1 => write!(f, "gguf_q5_1"),
473            Self::GgufQ8_0 => write!(f, "gguf_q8_0"),
474            Self::Nvfp4Block => write!(f, "nvfp4/16"),
475            Self::MlxAffine { bits, group_size } => {
476                write!(f, "mlx_affine/{bits}/{group_size}")
477            }
478            Self::MlxMxfp4 { group_size } => write!(f, "mlx_mxfp4/{group_size}"),
479            Self::MxFp4x2Block { group_size } => write!(f, "mxfp4x2/{group_size}"),
480            Self::MlxMxfp8 { group_size } => write!(f, "mlx_mxfp8/{group_size}"),
481            Self::GgufIQ4NL => write!(f, "gguf_iq4_nl"),
482            Self::GgufIQ4XS => write!(f, "gguf_iq4_xs"),
483            Self::GgufIQ2XXS => write!(f, "gguf_iq2_xxs"),
484            Self::GgufIQ2XS => write!(f, "gguf_iq2_xs"),
485            Self::GgufIQ2S => write!(f, "gguf_iq2_s"),
486            Self::GgufIQ3XXS => write!(f, "gguf_iq3_xxs"),
487            Self::GgufIQ3S => write!(f, "gguf_iq3_s"),
488            Self::GgufIQ1S => write!(f, "gguf_iq1_s"),
489            Self::GgufIQ1M => write!(f, "gguf_iq1_m"),
490            Self::GgufTQ1_0 => write!(f, "gguf_tq1_0"),
491            Self::GgufTQ2_0 => write!(f, "gguf_tq2_0"),
492            Self::GgufMXFP4 => write!(f, "gguf_mxfp4"),
493            Self::GgufNVFP4 => write!(f, "gguf_nvfp4"),
494            Self::GgufQ1_0 => write!(f, "gguf_q1_0"),
495            Self::GgufQ2_0 => write!(f, "gguf_q2_0"),
496            Self::GgufFV5 => write!(f, "gguf_fv5"),
497            Self::GgufFV5B => write!(f, "gguf_fv5b"),
498        }
499    }
500}
501
502/// Element format for a **native low-precision tensor-core GEMM** operand
503/// (see [`crate::op::Op::ScaledMatMul`]).
504///
505/// Distinct from [`QuantScheme`]: a `QuantScheme` is block-scaled *storage*
506/// that the CPU/GPU decodes to f32 *before* a normal sgemm. A `ScaledFormat`
507/// is the raw element encoding hardware tensor cores consume **directly**, with
508/// f32 accumulation — the whole point of FP8/FP6/FP4 on Hopper / Ada /
509/// Blackwell / CDNA3 / CDNA4. The per-block/per-tensor scale layout is
510/// orthogonal and lives in [`ScaleLayout`].
511///
512/// Operands flow through the graph as `DType::U8` byte buffers (one code per
513/// byte on the CPU oracle; packed on GPU); the format is carried on the op,
514/// not the dtype, so no `DType` variant is needed.
515#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
516#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
517pub enum ScaledFormat {
518    /// OCP FP8 E4M3 — bias 7, no infinities, only `S.1111.111` is NaN.
519    /// Max ±448. Hopper / Ada / Blackwell; weights + forward activations.
520    F8E4M3,
521    /// OCP FP8 E5M2 — bias 15, IEEE-like inf/NaN at max exponent.
522    /// Max ±57344. Wider range — the gradient format.
523    F8E5M2,
524    /// AMD "FNUZ" FP8 E4M3 — bias 8, single NaN at `0x80`, no inf, no −0.
525    /// Max ±240. CDNA3 / MI300.
526    F8E4M3Fnuz,
527    /// AMD "FNUZ" FP8 E5M2 — bias 16, single NaN at `0x80`, no inf, no −0.
528    /// Max ±57344. CDNA3 / MI300.
529    F8E5M2Fnuz,
530    /// MX FP6 E2M3 — bias 1, all 64 codes finite. Max ±7.5. Blackwell / CDNA4.
531    F6E2M3,
532    /// MX FP6 E3M2 — bias 3, all 64 codes finite. Max ±28. Blackwell / CDNA4.
533    F6E3M2,
534    /// FP4 E2M1 — all 16 codes finite. Max ±6. Blackwell / CDNA4.
535    /// Shared by NVFP4 and MXFP4 — the [`ScaleLayout`] tells them apart.
536    F4E2M1,
537    /// Arbitrary sub-byte minifloat parameterized by exponent / mantissa width
538    /// — the `fNeXmY` family (`N = 1 + exp_bits + mant_bits` total bits).
539    ///
540    /// All-finite (no infinities, no NaN, no AMD FNUZ), IEEE-style gradual
541    /// underflow (subnormals when `exp == 0`), sign in bit `exp_bits +
542    /// mant_bits`, one code per byte. The whole code must fit in a byte, so
543    /// `1 + exp_bits + mant_bits <= 8` and `exp_bits >= 1`.
544    ///
545    /// This is a *research / experimental* encoding: it has no hardware
546    /// tensor-core GEMM, so it always runs the decode-and-accumulate path (CPU
547    /// oracle + generic GPU kernel). Build one with [`ScaledFormat::custom`]
548    /// (IEEE bias `2^(exp_bits-1) - 1`) or [`ScaledFormat::custom_with_bias`],
549    /// or parse a name via `"f4e3m0".parse()`.
550    ///
551    /// Example — `f4e3m0` (`exp_bits: 3, mant_bits: 0, bias: 3`): the 16 codes
552    /// are `±0` and `±{0.25, 0.5, 1, 2, 4, 8, 16}` — a signed power-of-two
553    /// (near-logarithmic) 4-bit format.
554    Custom {
555        exp_bits: u8,
556        mant_bits: u8,
557        bias: i8,
558    },
559}
560
561impl ScaledFormat {
562    /// Total bit width of one element code (4, 6, or 8).
563    pub const fn bit_width(self) -> u32 {
564        match self {
565            Self::F8E4M3 | Self::F8E5M2 | Self::F8E4M3Fnuz | Self::F8E5M2Fnuz => 8,
566            Self::F6E2M3 | Self::F6E3M2 => 6,
567            Self::F4E2M1 => 4,
568            Self::Custom {
569                exp_bits,
570                mant_bits,
571                ..
572            } => 1 + exp_bits as u32 + mant_bits as u32,
573        }
574    }
575
576    /// `(exponent_bits, mantissa_bits, exponent_bias)`.
577    pub const fn fields(self) -> (u32, u32, i32) {
578        match self {
579            Self::F8E4M3 => (4, 3, 7),
580            Self::F8E5M2 => (5, 2, 15),
581            Self::F8E4M3Fnuz => (4, 3, 8),
582            Self::F8E5M2Fnuz => (5, 2, 16),
583            Self::F6E2M3 => (2, 3, 1),
584            Self::F6E3M2 => (3, 2, 3),
585            Self::F4E2M1 => (2, 1, 1),
586            Self::Custom {
587                exp_bits,
588                mant_bits,
589                bias,
590            } => (exp_bits as u32, mant_bits as u32, bias as i32),
591        }
592    }
593
594    /// Build an arbitrary all-finite minifloat with `exp_bits` exponent and
595    /// `mant_bits` mantissa bits, using the IEEE-style bias `2^(exp_bits-1) - 1`
596    /// — the convention every named rlx format follows (E4M3 → 7, E5M2 → 15,
597    /// E2M1 → 1, …). The whole code must fit in a byte. `const` — usable in
598    /// `const` contexts and pattern-free construction.
599    ///
600    /// Panics if `exp_bits == 0` or `1 + exp_bits + mant_bits > 8`.
601    ///
602    /// ```
603    /// use rlx_ir::ScaledFormat;
604    /// const F4E3M0: ScaledFormat = ScaledFormat::custom(3, 0);
605    /// assert_eq!(F4E3M0.to_string(), "f4e3m0");
606    /// assert_eq!(F4E3M0.exp_bits(), 3);
607    /// assert_eq!(F4E3M0.mant_bits(), 0);
608    /// // Nearest representable value ("quantize" a single f32):
609    /// assert_eq!(F4E3M0.quantize(1.4), 1.0);
610    /// assert_eq!(F4E3M0.max_finite(), 16.0);
611    /// ```
612    pub const fn custom(exp_bits: u8, mant_bits: u8) -> Self {
613        assert!(exp_bits >= 1, "minifloat needs at least one exponent bit");
614        assert!(
615            1 + exp_bits + mant_bits <= 8,
616            "minifloat code must fit in a byte (1 + exp + mant <= 8)"
617        );
618        let bias = (1i32 << (exp_bits - 1)) - 1;
619        Self::Custom {
620            exp_bits,
621            mant_bits,
622            bias: bias as i8,
623        }
624    }
625
626    /// Like [`custom`](Self::custom) but with an explicit exponent bias
627    /// (for formats that don't use the IEEE `2^(e-1)-1` convention). `const`.
628    pub const fn custom_with_bias(exp_bits: u8, mant_bits: u8, bias: i8) -> Self {
629        assert!(exp_bits >= 1, "minifloat needs at least one exponent bit");
630        assert!(
631            1 + exp_bits + mant_bits <= 8,
632            "minifloat code must fit in a byte (1 + exp + mant <= 8)"
633        );
634        Self::Custom {
635            exp_bits,
636            mant_bits,
637            bias,
638        }
639    }
640
641    /// The seven named hardware element formats, for enumeration / format sweeps.
642    pub const NAMED: [ScaledFormat; 7] = [
643        Self::F8E4M3,
644        Self::F8E5M2,
645        Self::F8E4M3Fnuz,
646        Self::F8E5M2Fnuz,
647        Self::F6E2M3,
648        Self::F6E3M2,
649        Self::F4E2M1,
650    ];
651
652    /// Exponent-field bit count (`X` in `fNeXmY`).
653    pub const fn exp_bits(self) -> u32 {
654        self.fields().0
655    }
656    /// Mantissa-field bit count (`Y` in `fNeXmY`; `0` for a pure power-of-two
657    /// format such as `f4e3m0`).
658    pub const fn mant_bits(self) -> u32 {
659        self.fields().1
660    }
661    /// Exponent bias.
662    pub const fn bias(self) -> i32 {
663        self.fields().2
664    }
665    /// True for a parameterized [`Custom`](Self::Custom) format (no hardware
666    /// tensor core — always runs the decode path).
667    pub const fn is_custom(self) -> bool {
668        matches!(self, Self::Custom { .. })
669    }
670    /// True for one of the seven [`NAMED`](Self::NAMED) hardware formats.
671    pub const fn is_named(self) -> bool {
672        !self.is_custom()
673    }
674
675    /// AMD OCP-FNUZ encoding (single NaN at `0x80`, no inf, no −0).
676    pub const fn is_fnuz(self) -> bool {
677        matches!(self, Self::F8E4M3Fnuz | Self::F8E5M2Fnuz)
678    }
679
680    /// True for IEEE-like formats carrying inf / NaN at the max exponent
681    /// (OCP E5M2 only — E4M3 is finite-with-one-NaN, FP6/FP4 are all-finite).
682    pub const fn has_inf(self) -> bool {
683        matches!(self, Self::F8E5M2)
684    }
685
686    /// Largest finite magnitude representable (used as the amax divisor when
687    /// computing a per-tensor / per-block scale).
688    pub fn max_finite(self) -> f32 {
689        crate::lowp_codec::max_finite(self)
690    }
691
692    /// Decode one packed code to f32 (bit-exact; `±inf` / `NaN` for the formats
693    /// that encode them). Method form of [`crate::lowp_codec::decode`].
694    pub fn decode(self, code: u8) -> f32 {
695        crate::lowp_codec::decode(self, code)
696    }
697
698    /// Encode an f32 to its nearest representable code (round-half-to-even,
699    /// saturating overflow / `±inf` to `±max_finite`, `NaN → 0`). Method form of
700    /// [`crate::lowp_codec::encode`].
701    pub fn encode(self, x: f32) -> u8 {
702        crate::lowp_codec::encode(self, x)
703    }
704
705    /// Round-trip `x` through the format — the nearest value it can represent.
706    /// Handy for eyeballing a format's resolution without building a graph
707    /// (e.g. `ScaledFormat::custom(3, 0).quantize(1.4) == 1.0`).
708    pub fn quantize(self, x: f32) -> f32 {
709        self.decode(self.encode(x))
710    }
711
712    /// Every finite value the format represents, ascending and deduplicated —
713    /// the format's grid. Useful for inspecting a research minifloat, e.g.
714    /// `ScaledFormat::custom(3, 0).representable_values()` yields
715    /// `[-16, -8, -4, -2, -1, -0.5, -0.25, 0, 0.25, 0.5, 1, 2, 4, 8, 16]`.
716    pub fn representable_values(self) -> Vec<f32> {
717        let n = 1u16 << self.bit_width();
718        let mut v: Vec<f32> = (0..n)
719            .map(|c| self.decode(c as u8))
720            .filter(|x| x.is_finite())
721            .collect();
722        v.sort_by(|a, b| a.partial_cmp(b).unwrap());
723        v.dedup();
724        v
725    }
726
727    /// The GPU dispatch word passed to `scaled_lowp_general.cu` (`rlx_decode_lowp`).
728    ///
729    /// For the seven named formats this is a small stable id matching the
730    /// kernel's `switch`: e4m3=0, e5m2=1, e4m3fnuz=2, e5m2fnuz=3, e2m3=4,
731    /// e3m2=5, e2m1=6.
732    ///
733    /// For a [`Custom`](Self::Custom) format there is no fixed id, so this
734    /// returns a **packed field descriptor** with the top bit set as a
735    /// sentinel: `0x8000_0000 | exp_bits | mant_bits<<4 | (bias as u8)<<8`.
736    /// The kernel detects the sentinel bit and decodes generically from the
737    /// unpacked `(exp_bits, mant_bits, bias)` — so a new format needs no kernel
738    /// edit. The named ids stay in `0..=6` (top bit clear), so the existing
739    /// hardware `switch` path is unchanged.
740    pub const fn kernel_id(self) -> u32 {
741        match self {
742            Self::F8E4M3 => 0,
743            Self::F8E5M2 => 1,
744            Self::F8E4M3Fnuz => 2,
745            Self::F8E5M2Fnuz => 3,
746            Self::F6E2M3 => 4,
747            Self::F6E3M2 => 5,
748            Self::F4E2M1 => 6,
749            Self::Custom {
750                exp_bits,
751                mant_bits,
752                bias,
753            } => {
754                0x8000_0000
755                    | (exp_bits as u32 & 0xF)
756                    | ((mant_bits as u32 & 0xF) << 4)
757                    | (((bias as u8) as u32) << 8)
758            }
759        }
760    }
761
762    /// True for the OCP FP8 variants that the native cublasLt / hipBLASLt FP8
763    /// GEMM accepts (per-tensor only). Other formats use the decode fallback.
764    pub const fn is_native_fp8(self) -> bool {
765        matches!(self, Self::F8E4M3 | Self::F8E5M2)
766    }
767}
768
769impl std::fmt::Display for ScaledFormat {
770    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
771        let s = match self {
772            Self::F8E4M3 => "f8e4m3",
773            Self::F8E5M2 => "f8e5m2",
774            Self::F8E4M3Fnuz => "f8e4m3fnuz",
775            Self::F8E5M2Fnuz => "f8e5m2fnuz",
776            Self::F6E2M3 => "f6e2m3",
777            Self::F6E3M2 => "f6e3m2",
778            Self::F4E2M1 => "f4e2m1",
779            // `fNeXmY`, N = 1 + exp + mant. The bias is implied by the width
780            // (IEEE convention) and not rendered; round-trips through `FromStr`.
781            Self::Custom {
782                exp_bits,
783                mant_bits,
784                ..
785            } => {
786                return write!(
787                    f,
788                    "f{}e{}m{}",
789                    1 + exp_bits + mant_bits,
790                    exp_bits,
791                    mant_bits
792                );
793            }
794        };
795        f.write_str(s)
796    }
797}
798
799impl std::str::FromStr for ScaledFormat {
800    type Err = String;
801
802    /// Parse a format name. The seven named formats (`"f8e4m3"`, `"f4e2m1"`,
803    /// the `…fnuz` variants, …) keep their exact hardware semantics (FNUZ,
804    /// inf/NaN); any other `fNeXmY` string becomes an all-finite
805    /// [`Custom`](Self::Custom) with the IEEE bias. `N` must equal `1 + X + Y`
806    /// and the code must fit in a byte (`N <= 8`, `X >= 1`).
807    fn from_str(s: &str) -> Result<Self, Self::Err> {
808        match s {
809            "f8e4m3" => return Ok(Self::F8E4M3),
810            "f8e5m2" => return Ok(Self::F8E5M2),
811            "f8e4m3fnuz" => return Ok(Self::F8E4M3Fnuz),
812            "f8e5m2fnuz" => return Ok(Self::F8E5M2Fnuz),
813            "f6e2m3" => return Ok(Self::F6E2M3),
814            "f6e3m2" => return Ok(Self::F6E3M2),
815            "f4e2m1" => return Ok(Self::F4E2M1),
816            _ => {}
817        }
818        let err = || format!("invalid minifloat format {s:?} (expected e.g. \"f4e3m0\")");
819        let rest = s.strip_prefix('f').ok_or_else(err)?;
820        let (total, rest) = take_leading_u32(rest).ok_or_else(err)?;
821        let rest = rest.strip_prefix('e').ok_or_else(err)?;
822        let (exp, rest) = take_leading_u32(rest).ok_or_else(err)?;
823        let rest = rest.strip_prefix('m').ok_or_else(err)?;
824        let (mant, rest) = take_leading_u32(rest).ok_or_else(err)?;
825        if !rest.is_empty() || exp == 0 || total != 1 + exp + mant || 1 + exp + mant > 8 {
826            return Err(err());
827        }
828        Ok(Self::custom(exp as u8, mant as u8))
829    }
830}
831
832/// Split the leading run of ASCII digits off `s`, returning `(value, tail)`.
833/// `None` if `s` doesn't start with a digit.
834fn take_leading_u32(s: &str) -> Option<(u32, &str)> {
835    let end = s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len());
836    if end == 0 {
837        return None;
838    }
839    Some((s[..end].parse().ok()?, &s[end..]))
840}
841
842/// How scale factors are laid out for an [`crate::op::Op::ScaledMatMul`]
843/// operand. The reconstructed value of element `i` is
844/// `decode(code[i]) * scale(block_of(i))`.
845#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
846#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
847pub enum ScaleLayout {
848    /// One f32 amax scale for the whole operand (classic per-tensor FP8 GEMM).
849    PerTensor,
850    /// OCP microscaling: one power-of-two **E8M0** scale per `block`
851    /// consecutive elements along K (MXFP8 / MXFP6 / MXFP4). Scale tensor
852    /// is `DType::U8` (E8M0 bytes).
853    BlockMxE8M0 { block: u32 },
854    /// NVFP4: one FP8 **E4M3** scale per `group` (16) elements along K, plus
855    /// an optional per-tensor f32 global. Scale tensor is `DType::U8`.
856    Nvfp4 { group: u32 },
857}
858
859impl ScaleLayout {
860    /// OCP microscaling default (32-element blocks).
861    pub const fn mx() -> Self {
862        Self::BlockMxE8M0 { block: 32 }
863    }
864    /// NVFP4 default (16-element groups).
865    pub fn nvfp4() -> Self {
866        Self::Nvfp4 {
867            group: crate::nvfp4::NVFP4_GROUP_SIZE as u32,
868        }
869    }
870    /// Element dtype of the scale tensor for this layout.
871    pub const fn scale_dtype(self) -> crate::DType {
872        match self {
873            Self::PerTensor => crate::DType::F32,
874            Self::BlockMxE8M0 { .. } | Self::Nvfp4 { .. } => crate::DType::U8,
875        }
876    }
877    /// Number of consecutive elements sharing one scale (1 for per-tensor).
878    pub const fn block(self) -> u32 {
879        match self {
880            Self::PerTensor => 1,
881            Self::BlockMxE8M0 { block } => block,
882            Self::Nvfp4 { group } => group,
883        }
884    }
885
886    /// `(scale_mode, block)` for GPU kernels (`scaled_lowp_general.cu`):
887    /// per-tensor=0, block-E8M0=1, NVFP4-E4M3=2.
888    pub const fn mode_block(self) -> (u32, u32) {
889        match self {
890            Self::PerTensor => (0, 1),
891            Self::BlockMxE8M0 { block } => (1, block),
892            Self::Nvfp4 { group } => (2, group),
893        }
894    }
895}
896
897impl std::fmt::Display for ScaleLayout {
898    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
899        match self {
900            Self::PerTensor => write!(f, "per_tensor"),
901            Self::BlockMxE8M0 { block } => write!(f, "mx_e8m0/{block}"),
902            Self::Nvfp4 { group } => write!(f, "nvfp4/{group}"),
903        }
904    }
905}
906
907impl std::str::FromStr for ScaleLayout {
908    type Err = String;
909
910    /// Parse a scale-layout name: `"per_tensor"`, `"mx"` (32-element E8M0
911    /// microscaling), `"nvfp4"` (16-element E4M3), or an explicit block size
912    /// `"mx/<block>"` / `"nvfp4/<group>"`. Mirrors [`Display`](Self) round-trip.
913    fn from_str(s: &str) -> Result<Self, Self::Err> {
914        match s {
915            "per_tensor" | "pertensor" => return Ok(Self::PerTensor),
916            "mx" | "mxfp8" | "block" => return Ok(Self::mx()),
917            "nvfp4" => return Ok(Self::nvfp4()),
918            _ => {}
919        }
920        if let Some(rest) = s.strip_prefix("mx/").or_else(|| s.strip_prefix("mx_e8m0/")) {
921            if let Ok(block) = rest.parse::<u32>() {
922                return Ok(Self::BlockMxE8M0 { block });
923            }
924        }
925        if let Some(rest) = s.strip_prefix("nvfp4/") {
926            if let Ok(group) = rest.parse::<u32>() {
927                return Ok(Self::Nvfp4 { group });
928            }
929        }
930        Err(format!(
931            "unknown scale layout {s:?} (expected \"per_tensor\", \"mx\", \"nvfp4\", or \"mx/<block>\")"
932        ))
933    }
934}
935
936/// Per-graph map of quantized tensors. Lookup is O(1).
937#[derive(Debug, Clone, Default)]
938pub struct QuantMap {
939    map: HashMap<NodeId, QuantScheme>,
940}
941
942impl QuantMap {
943    pub fn new() -> Self {
944        Self::default()
945    }
946    pub fn get(&self, id: NodeId) -> Option<QuantScheme> {
947        self.map.get(&id).copied()
948    }
949    pub fn insert(&mut self, id: NodeId, scheme: QuantScheme) -> Option<QuantScheme> {
950        self.map.insert(id, scheme)
951    }
952    pub fn is_empty(&self) -> bool {
953        self.map.is_empty()
954    }
955    pub fn len(&self) -> usize {
956        self.map.len()
957    }
958    pub fn iter(&self) -> impl Iterator<Item = (&NodeId, &QuantScheme)> {
959        self.map.iter()
960    }
961}
962
963#[cfg(test)]
964mod tests {
965    use super::*;
966
967    #[test]
968    fn scheme_traits() {
969        assert_eq!(
970            QuantScheme::Int4Block { block_size: 32 }.bits_per_element(),
971            4
972        );
973        assert!(QuantScheme::Int8BlockAsym { block_size: 64 }.has_zero_point());
974        assert!(!QuantScheme::Fp8E4m3.has_scale());
975    }
976
977    /// Pins the shared GGUF dequant-kernel ids so they can NEVER drift out
978    /// from under the compiled MSL/CU/WGSL/GLSL `switch (scheme_id)` in any
979    /// backend. Every GPU backend delegates to `gpu_dequant_scheme_id`; if
980    /// someone reorders a variant here this test fails before a mis-decode
981    /// ships. Non-GGUF schemes must report `None`.
982    #[test]
983    fn gpu_dequant_scheme_id_is_stable() {
984        use QuantScheme::*;
985        assert_eq!(QuantScheme::GPU_DEQUANT_SCHEME_ID_PAIRS.len(), 28);
986        for &(scheme, id) in QuantScheme::GPU_DEQUANT_SCHEME_ID_PAIRS {
987            assert_eq!(scheme.gpu_dequant_scheme_id(), Some(id), "{scheme:?}");
988            assert_eq!(
989                QuantScheme::from_gpu_dequant_scheme_id(id),
990                Some(scheme),
991                "id {id}"
992            );
993        }
994        for scheme in [
995            Int8Block { block_size: 32 },
996            Int8BlockAsym { block_size: 32 },
997            Int4Block { block_size: 32 },
998            Fp8E4m3,
999            Fp8E5m2,
1000            Nvfp4Block,
1001            MlxAffine {
1002                bits: 4,
1003                group_size: 64,
1004            },
1005            MlxMxfp4 { group_size: 32 },
1006            MlxMxfp8 { group_size: 32 },
1007        ] {
1008            assert_eq!(scheme.gpu_dequant_scheme_id(), None, "{scheme:?}");
1009        }
1010        assert_eq!(QuantScheme::from_gpu_dequant_scheme_id(999), None);
1011    }
1012
1013    #[test]
1014    fn quant_map_lookup() {
1015        let mut q = QuantMap::new();
1016        let id = NodeId(7);
1017        q.insert(id, QuantScheme::Int8Block { block_size: 32 });
1018        assert_eq!(q.get(id), Some(QuantScheme::Int8Block { block_size: 32 }));
1019        assert_eq!(q.get(NodeId(99)), None);
1020    }
1021
1022    #[test]
1023    fn custom_format_ieee_bias_and_width() {
1024        // IEEE bias 2^(e-1)-1, matching every named format.
1025        assert_eq!(ScaledFormat::custom(3, 0).fields(), (3, 0, 3)); // f4e3m0
1026        assert_eq!(ScaledFormat::custom(4, 3).fields(), (4, 3, 7)); // e4m3 bias
1027        assert_eq!(ScaledFormat::custom(5, 2).fields(), (5, 2, 15)); // e5m2 bias
1028        assert_eq!(ScaledFormat::custom(2, 1).fields(), (2, 1, 1)); // e2m1 bias
1029        assert_eq!(ScaledFormat::custom(3, 0).bit_width(), 4);
1030        assert_eq!(ScaledFormat::custom(3, 4).bit_width(), 8);
1031    }
1032
1033    #[test]
1034    fn custom_format_parse_display_round_trip() {
1035        let f: ScaledFormat = "f4e3m0".parse().unwrap();
1036        assert_eq!(f, ScaledFormat::custom(3, 0));
1037        assert_eq!(f.to_string(), "f4e3m0");
1038        // A few more splits.
1039        assert_eq!(
1040            "f5e2m2".parse::<ScaledFormat>().unwrap().to_string(),
1041            "f5e2m2"
1042        );
1043        assert_eq!(
1044            "f8e3m4".parse::<ScaledFormat>().unwrap().to_string(),
1045            "f8e3m4"
1046        );
1047        // Named formats parse to their exact hardware variants, not Custom.
1048        assert_eq!(
1049            "f8e4m3".parse::<ScaledFormat>().unwrap(),
1050            ScaledFormat::F8E4M3
1051        );
1052        assert_eq!(
1053            "f4e2m1".parse::<ScaledFormat>().unwrap(),
1054            ScaledFormat::F4E2M1
1055        );
1056        assert_eq!(
1057            "f8e5m2fnuz".parse::<ScaledFormat>().unwrap(),
1058            ScaledFormat::F8E5M2Fnuz
1059        );
1060    }
1061
1062    #[test]
1063    fn custom_format_parse_rejects_invalid() {
1064        assert!("f4e3m1".parse::<ScaledFormat>().is_err()); // 1+3+1 != 4
1065        assert!("f9e4m4".parse::<ScaledFormat>().is_err()); // 9 bits > byte
1066        assert!("f1e0m0".parse::<ScaledFormat>().is_err()); // 0 exponent bits
1067        assert!("e3m0".parse::<ScaledFormat>().is_err()); // missing 'f'
1068        assert!("f4e3m0x".parse::<ScaledFormat>().is_err()); // trailing junk
1069        assert!("garbage".parse::<ScaledFormat>().is_err());
1070    }
1071
1072    #[test]
1073    fn custom_gpu_word_is_packed_descriptor() {
1074        // Named formats keep their small ids (top bit clear).
1075        assert_eq!(ScaledFormat::F8E4M3.kernel_id(), 0);
1076        assert_eq!(ScaledFormat::F4E2M1.kernel_id(), 6);
1077        assert!(ScaledFormat::F4E2M1.kernel_id() & 0x8000_0000 == 0);
1078        // Custom packs (exp, mant, bias) with the sentinel bit set.
1079        let w = ScaledFormat::custom(3, 0).kernel_id(); // e=3, m=0, bias=3
1080        assert_eq!(w & 0x8000_0000, 0x8000_0000);
1081        assert_eq!(w & 0xF, 3); // exp_bits
1082        assert_eq!((w >> 4) & 0xF, 0); // mant_bits
1083        assert_eq!((w >> 8) & 0xFF, 3); // bias
1084        // Negative bias round-trips through the u8 reinterpretation.
1085        let wn = ScaledFormat::custom_with_bias(3, 0, -2).kernel_id();
1086        assert_eq!(((wn >> 8) & 0xFF) as u8 as i8, -2);
1087    }
1088
1089    #[test]
1090    fn format_is_const_and_introspectable() {
1091        // Usable in const context.
1092        const F: ScaledFormat = ScaledFormat::custom(3, 0);
1093        assert!(F.is_custom() && !F.is_named());
1094        assert_eq!((F.exp_bits(), F.mant_bits(), F.bias()), (3, 0, 3));
1095        assert!(ScaledFormat::F8E4M3.is_named() && !ScaledFormat::F8E4M3.is_custom());
1096        assert_eq!(ScaledFormat::NAMED.len(), 7);
1097        assert!(ScaledFormat::NAMED.iter().all(|f| f.is_named()));
1098    }
1099
1100    #[test]
1101    fn format_codec_methods_and_quantize() {
1102        // Method forms match the free functions for every named format.
1103        for f in ScaledFormat::NAMED {
1104            for c in 0..(1u16 << f.bit_width()) {
1105                assert_eq!(
1106                    f.decode(c as u8).to_bits(),
1107                    crate::lowp_codec::decode(f, c as u8).to_bits()
1108                );
1109            }
1110        }
1111        let cf = ScaledFormat::custom(3, 0); // f4e3m0 grid: ±{0.25,..,16}, ±0
1112        assert_eq!(cf.quantize(1.4), 1.0);
1113        assert_eq!(cf.quantize(1.6), 2.0);
1114        assert_eq!(cf.quantize(-3.0), -2.0); // nearer 2 than 4 in magnitude
1115        assert_eq!(cf.decode(cf.encode(100.0)), 16.0); // saturates
1116        assert_eq!(cf.decode(cf.encode(f32::INFINITY)), 16.0);
1117    }
1118
1119    #[test]
1120    fn representable_values_grid() {
1121        assert_eq!(
1122            ScaledFormat::custom(3, 0).representable_values(),
1123            vec![
1124                -16.0, -8.0, -4.0, -2.0, -1.0, -0.5, -0.25, 0.0, 0.25, 0.5, 1.0, 2.0, 4.0, 8.0,
1125                16.0
1126            ]
1127        );
1128        // Named formats: the grid size never exceeds the finite code count.
1129        for f in ScaledFormat::NAMED {
1130            let g = f.representable_values();
1131            assert!(!g.is_empty() && g.windows(2).all(|w| w[0] < w[1]));
1132        }
1133    }
1134
1135    #[test]
1136    fn enumerate_all_fnexmy() {
1137        // Every valid fNeXmY: exp >= 1, mant >= 0, 1 + exp + mant <= 8.
1138        let mut all = vec![];
1139        for exp in 1u8..=7 {
1140            for mant in 0u8..=(7 - exp) {
1141                all.push(ScaledFormat::custom(exp, mant));
1142            }
1143        }
1144        assert_eq!(all.len(), 28, "there are exactly 28 fNeXmY formats");
1145        eprintln!(
1146            "{:<8} {:>4} {:>3} {:>3} {:>4} {:>12} {:>12} {:>5}",
1147            "name", "bits", "e", "m", "bias", "max_finite", "min_pos", "vals"
1148        );
1149        for f in &all {
1150            let vals = f.representable_values();
1151            let min_pos = vals.iter().copied().find(|&x| x > 0.0).unwrap();
1152            assert!(f.bit_width() <= 8 && f.exp_bits() >= 1 && !vals.is_empty());
1153            eprintln!(
1154                "{:<8} {:>4} {:>3} {:>3} {:>4} {:>12.3e} {:>12.3e} {:>5}",
1155                f.to_string(),
1156                f.bit_width(),
1157                f.exp_bits(),
1158                f.mant_bits(),
1159                f.bias(),
1160                f.max_finite(),
1161                min_pos,
1162                vals.len()
1163            );
1164        }
1165    }
1166
1167    #[test]
1168    fn scale_layout_parse_round_trip() {
1169        assert_eq!(
1170            "per_tensor".parse::<ScaleLayout>().unwrap(),
1171            ScaleLayout::PerTensor
1172        );
1173        assert_eq!("mx".parse::<ScaleLayout>().unwrap(), ScaleLayout::mx());
1174        assert_eq!(
1175            "nvfp4".parse::<ScaleLayout>().unwrap(),
1176            ScaleLayout::nvfp4()
1177        );
1178        assert_eq!(
1179            "mx/64".parse::<ScaleLayout>().unwrap(),
1180            ScaleLayout::BlockMxE8M0 { block: 64 }
1181        );
1182        assert!("bogus".parse::<ScaleLayout>().is_err());
1183        // Display round-trips through FromStr.
1184        let mx = ScaleLayout::mx();
1185        assert_eq!(mx.to_string().parse::<ScaleLayout>().unwrap(), mx);
1186    }
1187}