Skip to main content

rlx_tensor/
lowp.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//! Generic low-precision numerics for **emulated mixed-precision training** —
6//! quantize an `f32` to the grid of an arbitrary binary float format
7//! `fXmYeZ` (`X` total bits, `Y` mantissa bits, `Z` exponent bits, 1 sign),
8//! then keep computing in `f32`. This makes training work at *any* precision on
9//! *any* backend (including exotic formats with no hardware kernel — `nvf4`,
10//! `f8`, `bf8`) by round-tripping values through the format's representable set
11//! instead of relying on native half/quarter-precision matmul.
12//!
13//! Pair with a straight-through estimator (quantize on the forward, identity on
14//! the backward) for QAT-style low-precision training — see
15//! [`Func`](crate::Func)'s QAT helpers / the `rlx-tinystories` `--fake-quant`.
16//!
17//! The [`float_format!`] macro generates a marker type per format with a
18//! `const`-parameterized [`FloatFormat`] impl; [`parse_format`] resolves a
19//! runtime spec string (`"nvf4"`, `"f8e4m3"`, `"bf8"`, or generic `"f8m3e4"`).
20
21/// Round `x` to the nearest value representable by a binary float format with a
22/// sign bit, `exp_bits` exponent bits (IEEE bias `2^(exp_bits-1) - 1`) and
23/// `man_bits` explicit mantissa bits, saturating at `±max_normal` (no Inf
24/// produced). Round-to-nearest-**even**; subnormals supported; `0`/NaN pass
25/// through; `±Inf` saturates to `±max_normal`.
26///
27/// The whole grid is emulated in `f32`, so the result is an ordinary `f32` that
28/// happens to be one of the format's representable values.
29#[inline]
30pub fn quantize(x: f32, exp_bits: u32, man_bits: u32, max_normal: f32) -> f32 {
31    if x == 0.0 || x.is_nan() {
32        return x;
33    }
34    let neg = x.is_sign_negative();
35    let ax = x.abs();
36    if ax >= max_normal {
37        return if neg { -max_normal } else { max_normal };
38    }
39    let bias = (1i32 << (exp_bits - 1)) - 1;
40    let emin = 1 - bias; // smallest normal exponent
41    // Exponent of `ax`, floored, clamped up into the subnormal region so the
42    // ULP never shrinks below the format's smallest step.
43    let e = ax.log2().floor() as i32;
44    let e_eff = e.max(emin);
45    // Unit-in-the-last-place at this magnitude.
46    let ulp = exp2i(e_eff - man_bits as i32);
47    let q = round_half_even(ax / ulp) * ulp;
48    let q = q.min(max_normal);
49    if neg { -q } else { q }
50}
51
52/// `2^n` for a (possibly negative) integer exponent, without `powi` overflow
53/// pitfalls at the extremes.
54#[inline]
55fn exp2i(n: i32) -> f32 {
56    // f32 exponent range is [-149, 127]; clamp keeps subnormal ULPs finite.
57    2f32.powi(n.clamp(-149, 127))
58}
59
60/// Round to nearest integer, ties to even (banker's rounding).
61#[inline]
62fn round_half_even(v: f32) -> f32 {
63    let f = v.floor();
64    let diff = v - f;
65    if diff < 0.5 {
66        f
67    } else if diff > 0.5 {
68        f + 1.0
69    } else if (f as i64) & 1 == 0 {
70        f // already even
71    } else {
72        f + 1.0
73    }
74}
75
76/// Quantize every element of `xs` in place to `(exp_bits, man_bits, max_normal)`.
77#[inline]
78pub fn quantize_slice(xs: &mut [f32], exp_bits: u32, man_bits: u32, max_normal: f32) {
79    for x in xs {
80        *x = quantize(*x, exp_bits, man_bits, max_normal);
81    }
82}
83
84/// Quantize `xs` in place with **per-tensor (absmax) scaling** — the standard
85/// microscaling trick (MXFP4 / NVFP4): the largest-magnitude element is mapped
86/// to the format's max, so narrow formats use their full dynamic range instead
87/// of flushing everything below the smallest step to zero. `q = Q(x/s)·s` with
88/// `s = absmax / max_normal`. Essential for ≤6-bit formats (e.g. `nvf4`, whose
89/// smallest nonzero magnitude is 0.5 — without scaling, ~0.02 weights vanish).
90#[inline]
91pub fn quantize_slice_scaled(xs: &mut [f32], exp_bits: u32, man_bits: u32, max_normal: f32) {
92    let absmax = xs.iter().fold(0f32, |a, &x| a.max(x.abs()));
93    if absmax == 0.0 {
94        return;
95    }
96    let scale = absmax / max_normal;
97    for x in xs {
98        *x = quantize(*x / scale, exp_bits, man_bits, max_normal) * scale;
99    }
100}
101
102/// A compile-time-known binary float format.
103pub trait FloatFormat: Copy {
104    /// Exponent bits.
105    const EXP_BITS: u32;
106    /// Explicit mantissa bits.
107    const MAN_BITS: u32;
108    /// Largest finite magnitude (format-specific: e.g. 448 for E4M3, 6 for E2M1).
109    const MAX_NORMAL: f32;
110    /// Canonical spec string (`"f8e4m3"`, `"nvf4"`, …).
111    const NAME: &'static str;
112    /// Total bits (`1 + EXP_BITS + MAN_BITS`).
113    const BITS: u32 = 1 + Self::EXP_BITS + Self::MAN_BITS;
114
115    /// Round `x` to this format's grid.
116    #[inline]
117    fn quantize(x: f32) -> f32 {
118        quantize(x, Self::EXP_BITS, Self::MAN_BITS, Self::MAX_NORMAL)
119    }
120}
121
122/// Generate a marker type + [`FloatFormat`] impl per format, plus a `BUILTIN`
123/// lookup table. `$name = (exp_bits, man_bits, max_normal, "spec")`.
124#[macro_export]
125macro_rules! float_format {
126    ($($(#[$m:meta])* $name:ident = ($exp:expr, $man:expr, $max:expr, $spec:literal);)*) => {
127        $(
128            $(#[$m])*
129            #[derive(Clone, Copy, Debug, Default)]
130            pub struct $name;
131            impl $crate::lowp::FloatFormat for $name {
132                const EXP_BITS: u32 = $exp;
133                const MAN_BITS: u32 = $man;
134                const MAX_NORMAL: f32 = $max;
135                const NAME: &'static str = $spec;
136            }
137        )*
138        /// All built-in formats: `(spec, exp_bits, man_bits, max_normal)`.
139        pub const BUILTIN: &[(&str, u32, u32, f32)] = &[ $(($spec, $exp, $man, $max)),* ];
140    };
141}
142
143float_format! {
144    /// IEEE binary16 (half).
145    F16   = (5, 10, 65504.0,        "f16");
146    /// bfloat16 (truncated f32; 8 exp / 7 man).
147    Bf16  = (8, 7,  3.3895314e38,   "bf16");
148    /// OCP FP8 **E4M3** (max 448) — the common fp8 weight/activation format.
149    F8E4M3 = (4, 3, 448.0,          "f8e4m3");
150    /// OCP FP8 **E5M2** — a.k.a. **bf8** (more range, less mantissa).
151    F8E5M2 = (5, 2, 57344.0,        "bf8");
152    /// **NVFP4** element format (**E2M1**, grid {0,±.5,±1,±1.5,±2,±3,±4,±6}).
153    Nvf4  = (2, 1, 6.0,             "nvf4");
154    /// FP6 E3M2 (a middle ground).
155    F6E3M2 = (3, 2, 28.0,           "f6e3m2");
156}
157
158/// Resolve a runtime precision spec to `(exp_bits, man_bits, max_normal)`.
159///
160/// Accepts a built-in [`BUILTIN`] name / common alias (`"f8"`, `"e4m3"`,
161/// `"e5m2"`, `"fp8"`, …), or a **generic** `fXmYeZ` string — `X` total bits,
162/// `Y` mantissa bits, `Z` exponent bits — e.g. `"f8m3e4"` (== E4M3),
163/// `"f4m1e2"` (== NVFP4). For generic specs `max_normal` uses the IEEE
164/// Inf-reserving convention `(2 − 2^-Y)·2^bias`.
165pub fn parse_format(spec: &str) -> Option<(u32, u32, f32)> {
166    let s = spec.trim().to_ascii_lowercase();
167    for (name, e, m, max) in BUILTIN {
168        if s == *name {
169            return Some((*e, *m, *max));
170        }
171    }
172    match s.as_str() {
173        "fp8" | "f8" | "e4m3" => return Some((4, 3, 448.0)),
174        "e5m2" => return Some((5, 2, 57344.0)),
175        "fp4" | "f4" | "e2m1" => return Some((2, 1, 6.0)),
176        "half" => return Some((5, 10, 65504.0)),
177        _ => {}
178    }
179    // Generic `f{X}m{Y}e{Z}`.
180    let rest = s.strip_prefix('f')?;
181    let (x_str, rest) = rest.split_once('m')?;
182    let (y_str, z_str) = rest.split_once('e')?;
183    let total: u32 = x_str.parse().ok()?;
184    let man: u32 = y_str.parse().ok()?;
185    let exp: u32 = z_str.parse().ok()?;
186    if exp == 0 || 1 + man + exp != total {
187        return None; // sign + exp + man must account for every bit
188    }
189    let bias = (1i32 << (exp - 1)) - 1;
190    let max = (2.0 - exp2i(-(man as i32))) * exp2i(bias);
191    Some((exp, man, max))
192}
193
194#[cfg(test)]
195mod tests {
196    use super::*;
197
198    #[test]
199    fn exact_values_pass_through() {
200        // Powers of two and simple fractions are representable everywhere.
201        for &(e, m, max) in &[(5u32, 10u32, 65504.0f32), (4, 3, 448.0), (2, 1, 6.0)] {
202            for &v in &[0.0, 1.0, -1.0, 0.5, 2.0, -4.0] {
203                assert_eq!(quantize(v, e, m, max), v, "fmt e{e}m{m} v{v}");
204            }
205        }
206    }
207
208    #[test]
209    fn saturates_no_inf() {
210        assert_eq!(quantize(1e30, 4, 3, 448.0), 448.0);
211        assert_eq!(quantize(-1e30, 4, 3, 448.0), -448.0);
212        assert_eq!(quantize(f32::INFINITY, 5, 10, 65504.0), 65504.0);
213        assert_eq!(quantize(100.0, 2, 1, 6.0), 6.0); // nvf4 saturates at 6
214    }
215
216    #[test]
217    fn nvf4_grid_is_exact() {
218        // E2M1 representable magnitudes.
219        for &v in &[0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0] {
220            assert_eq!(quantize(v, 2, 1, 6.0), v, "nvf4 {v}");
221            assert_eq!(quantize(-v, 2, 1, 6.0), -v);
222        }
223        // 5.0 rounds to the nearest of {4,6} → tie → even (4 = 2²·1.0).
224        assert_eq!(quantize(5.0, 2, 1, 6.0), 4.0);
225        // 2.5 → nearest of {2,3}; ulp at e=1 is 1 → RNE(2.5)=2 (even).
226        assert_eq!(quantize(2.5, 2, 1, 6.0), 2.0);
227    }
228
229    #[test]
230    fn rounds_toward_nearest() {
231        // f16 has 10 mantissa bits: 1 + 2^-11 rounds back to 1.0.
232        assert_eq!(quantize(1.0 + 2f32.powi(-11), 5, 10, 65504.0), 1.0);
233        // 1 + 2^-9 is representable (a multiple of 2^-10).
234        assert_eq!(
235            quantize(1.0 + 2f32.powi(-9), 5, 10, 65504.0),
236            1.0 + 2f32.powi(-9)
237        );
238        // f8e4m3 has 3 mantissa bits → step of 1/8 at [1,2): 1.1 → 1.125.
239        assert_eq!(quantize(1.1, 4, 3, 448.0), 1.125);
240    }
241
242    #[test]
243    fn parse_named_and_generic() {
244        assert_eq!(parse_format("nvf4"), Some((2, 1, 6.0)));
245        assert_eq!(parse_format("bf8"), Some((5, 2, 57344.0)));
246        assert_eq!(parse_format("f8e4m3"), Some((4, 3, 448.0)));
247        // Generic fXmYeZ resolves the (exp, man) split (max via IEEE convention).
248        assert_eq!(parse_format("f8m3e4").map(|(e, m, _)| (e, m)), Some((4, 3)));
249        assert_eq!(parse_format("f4m1e2").map(|(e, m, _)| (e, m)), Some((2, 1)));
250        assert_eq!(
251            parse_format("f16m10e5").map(|(e, m, _)| (e, m)),
252            Some((5, 10))
253        );
254        // Bad specs.
255        assert_eq!(parse_format("f8m4e4"), None); // 1+4+4 != 8
256        assert_eq!(parse_format("nonsense"), None);
257    }
258
259    #[test]
260    fn scaled_uses_full_range() {
261        // Small weights (~0.02) under nvf4 *without* scaling all vanish to 0.
262        let mut unscaled = vec![0.02f32, -0.05, 0.1, -0.01];
263        quantize_slice(&mut unscaled, 2, 1, 6.0);
264        assert!(unscaled.iter().all(|&x| x == 0.0), "{unscaled:?}");
265        // *With* per-tensor scaling they survive, and the absmax maps exactly.
266        let mut scaled = vec![0.02f32, -0.05, 0.1, -0.01];
267        quantize_slice_scaled(&mut scaled, 2, 1, 6.0);
268        assert!(scaled.iter().any(|&x| x != 0.0), "{scaled:?}");
269        assert!(
270            (scaled[2] - 0.1).abs() < 1e-6,
271            "absmax preserved: {}",
272            scaled[2]
273        );
274    }
275
276    #[test]
277    fn format_trait_consts() {
278        assert_eq!(Nvf4::BITS, 4);
279        assert_eq!(F8E4M3::BITS, 8);
280        assert_eq!(F16::BITS, 16);
281        assert_eq!(F8E4M3::quantize(1.1), 1.125);
282    }
283}