Skip to main content

rlx_runtime/
precision.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//! Precision selection for graph execution.
6//!
7//! Each backend can compile a graph at f32 (default — accurate) or f16
8//! (half precision — 2× peak FLOPs and ½ memory bandwidth on supported
9//! hardware). The IR remains dtype-agnostic; the backend decides how to
10//! materialize buffers and pick kernels.
11//!
12//! Mixed precision: f16 inference typically keeps reductions (LayerNorm
13//! mean/var, attention softmax) in f32 to avoid catastrophic accuracy
14//! loss while keeping matmul + element-wise in f16.
15
16/// Numeric precision for graph compilation.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
18pub enum Precision {
19    /// Full single precision. Always supported; accurate; baseline.
20    #[default]
21    F32,
22    /// Half precision (IEEE 754 binary16). Native on Apple Silicon GPU
23    /// and many CPUs (NEON `vfmaq_f16`). 2× FLOPs / 0.5× memory vs F32.
24    /// Reductions are still computed in F32 for numerical stability.
25    F16,
26    /// Brain-float: 8-bit exponent, 7-bit mantissa. Same range as F32,
27    /// less precision. Used in many LLMs. Accelerator-dependent.
28    BF16,
29}
30
31impl Precision {
32    /// Bytes per scalar at this precision.
33    pub fn size_bytes(self) -> usize {
34        match self {
35            Precision::F32 => 4,
36            Precision::F16 | Precision::BF16 => 2,
37        }
38    }
39
40    /// Backward-compatible alias used in older code.
41    pub fn bytes(self) -> usize {
42        self.size_bytes()
43    }
44}
45
46impl std::fmt::Display for Precision {
47    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        match self {
49            Precision::F32 => write!(f, "f32"),
50            Precision::F16 => write!(f, "f16"),
51            Precision::BF16 => write!(f, "bf16"),
52        }
53    }
54}