Skip to main content

virtio_accel_tosa_build/
quantized.rs

1//! Explicit packed storage graphs. NVFP4 is expressed using released TOSA operations,
2//! not mislabeled as INT4 or assigned a new TOSA dtype. The host receives packed bytes;
3//! decoding and scaling occur in the submitted graph. Native compilers may materialize
4//! wider intermediate weights: this API makes no compressed-residency or throughput promise.
5use crate::{BuildError, OperatorKind, OwnedGraph, OwnedOperator, OwnedShape, OwnedTensor};
6use alloc::{vec, vec::Vec};
7use virtio_accel_tosa::{DType, ExtensionSet, Level, ProfileSet, Target, Version};
8
9mod integer;
10mod palette;
11pub use integer::{int4_matmul_fp16, int8_matmul_fp16};
12pub use palette::palette4_matmul_fp16;
13
14pub const TARGET: Target = Target::new(
15    Version::TOSA_1_0,
16    ProfileSet::FLOATING_POINT.union(ProfileSet::INTEGER),
17    Level::Level8K,
18    ExtensionSet::NONE,
19);
20
21#[derive(Debug)]
22pub enum QuantizedBuildError {
23    InvalidShape,
24    InvalidScale,
25    Graph(BuildError),
26}
27impl From<BuildError> for QuantizedBuildError {
28    fn from(e: BuildError) -> Self {
29        Self::Graph(e)
30    }
31}
32impl core::fmt::Display for QuantizedBuildError {
33    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
34        write!(f, "{self:?}")
35    }
36}
37impl core::error::Error for QuantizedBuildError {}
38
39fn tensor(g: &mut OwnedGraph<'_>, name: &str, shape: &[i32], dtype: DType) {
40    g.push_tensor(OwnedTensor::new(name, shape.to_vec(), dtype));
41}
42fn op(g: &mut OwnedGraph<'_>, kind: OperatorKind, ins: &[&str], out: &str) {
43    g.push_operator(OwnedOperator::new(
44        kind,
45        ins.iter().map(|s| (*s).into()).collect(),
46        vec![out.into()],
47    ));
48}
49fn constant(g: &mut OwnedGraph<'_>, name: &str, shape: &[i32], dtype: DType, bytes: Vec<u8>) {
50    g.push_tensor(OwnedTensor::constant(name, shape.to_vec(), dtype, bytes));
51    op(g, OperatorKind::Const, &[], name);
52}
53fn reshape(g: &mut OwnedGraph<'_>, input: &str, out: &str, shape: &[i32], dtype: DType) {
54    let sn = alloc::format!("{out}_shape");
55    g.push_shape(OwnedShape::new(
56        &sn,
57        shape.iter().map(|x| i64::from(*x)).collect(),
58    ));
59    op(g, OperatorKind::ConstShape, &[], &sn);
60    tensor(g, out, shape, dtype);
61    op(g, OperatorKind::Reshape, &[input, &sn], out);
62}
63fn lookup(
64    g: &mut OwnedGraph<'_>,
65    input: &str,
66    prefix: &str,
67    count: i32,
68    table: &[f32],
69    width: i32,
70    dtype: DType,
71) {
72    let cast = alloc::format!("{prefix}_signed");
73    let idx = alloc::format!("{prefix}_index");
74    let lut = alloc::format!("{prefix}_lut");
75    let result = alloc::format!("{prefix}_decoded");
76    tensor(g, &cast, &[1, count], DType::INT32);
77    op(g, OperatorKind::Cast, &[input], &cast);
78    tensor(g, &idx, &[1, count], DType::INT32);
79    op(g, OperatorKind::Add, &[&cast, "offset"], &idx);
80    constant(
81        g,
82        &lut,
83        &[1, 256, width],
84        dtype,
85        if dtype == DType::FP32 {
86            table.iter().flat_map(|x| x.to_le_bytes()).collect()
87        } else {
88            table
89                .iter()
90                .flat_map(|x| exact_f16(*x).to_le_bytes())
91                .collect()
92        },
93    );
94    tensor(g, &result, &[1, count, width], dtype);
95    op(g, OperatorKind::Gather, &[&lut, &idx], &result);
96}
97/// Build `output = activations @ decoded_weights.T * tensor_scale`.
98///
99/// Slots: 0 FP32 activations [1, M, K]; 1 packed E2M1 bytes [1, N*K/2];
100/// 2 E4M3 block scales [1, N*K/16]; 3 FP32 output [1, M, N].
101/// Byte buffers use INT8 solely as a bit-preserving storage carrier. Low nibble is
102/// the first K element; each row has K/16 scales. Weights and scales remain runtime
103/// inputs, so changing a block does not require rebuilding the program.
104/// Scaling order matches Kore's projection: multiply E2M1 by its block scale,
105/// accumulate the FP32 matrix product, then apply the separate FP32 tensor scale.
106pub fn nvfp4_matmul(
107    m: usize,
108    n: usize,
109    k: usize,
110    tensor_scale: f32,
111) -> Result<Vec<u8>, QuantizedBuildError> {
112    if !tensor_scale.is_finite() || tensor_scale <= 0.0 {
113        return Err(QuantizedBuildError::InvalidScale);
114    }
115    build_nvfp4(m, n, k, DType::FP32, tensor_scale.to_le_bytes().to_vec())
116}
117/// FP16 activation, accumulation-result, output, and tensor-scale variant. The
118/// scale is supplied as IEEE binary16 bits so no implicit host rounding is involved.
119/// As in TOSA FP16 MATMUL, accumulation has the specified wider accumulator and
120/// the result rounds to FP16 before the final FP16 scaling operation.
121pub fn nvfp4_matmul_fp16(
122    m: usize,
123    n: usize,
124    k: usize,
125    tensor_scale_bits: u16,
126) -> Result<Vec<u8>, QuantizedBuildError> {
127    if tensor_scale_bits == 0
128        || tensor_scale_bits & 0x8000 != 0
129        || tensor_scale_bits & 0x7c00 == 0x7c00
130    {
131        return Err(QuantizedBuildError::InvalidScale);
132    }
133    build_nvfp4(
134        m,
135        n,
136        k,
137        DType::FP16,
138        tensor_scale_bits.to_le_bytes().to_vec(),
139    )
140}
141// Only used for the E2M1 and E4M3 decode tables, all of whose finite values are
142// exactly representable as normal binary16 values. No general float quantizer.
143fn exact_f16(x: f32) -> u16 {
144    let b = x.to_bits();
145    let sign = ((b >> 16) & 0x8000) as u16;
146    if b & 0x7fff_ffff == 0 {
147        return sign;
148    }
149    if x.is_nan() {
150        return sign | 0x7e00;
151    }
152    sign | ((((b >> 23) & 255) - 112) as u16) << 10 | ((b >> 13) & 1023) as u16
153}
154fn build_nvfp4(
155    m: usize,
156    n: usize,
157    k: usize,
158    dtype: DType,
159    scale: Vec<u8>,
160) -> Result<Vec<u8>, QuantizedBuildError> {
161    if m == 0 || n == 0 || k == 0 || k % 16 != 0 {
162        return Err(QuantizedBuildError::InvalidShape);
163    }
164    let elements = n.checked_mul(k).ok_or(QuantizedBuildError::InvalidShape)?;
165    let dim = |x| i32::try_from(x).map_err(|_| QuantizedBuildError::InvalidShape);
166    let (m, n, k, packed, groups) = (
167        dim(m)?,
168        dim(n)?,
169        dim(k)?,
170        dim(elements / 2)?,
171        dim(elements / 16)?,
172    );
173    let mut g = OwnedGraph::new("nvfp4_projection");
174    tensor(&mut g, "activations", &[1, m, k], dtype);
175    tensor(&mut g, "weights", &[1, packed], DType::INT8);
176    tensor(&mut g, "scales", &[1, groups], DType::INT8);
177    for input in ["activations", "weights", "scales"] {
178        g.push_input(input);
179    }
180    constant(
181        &mut g,
182        "offset",
183        &[1, 1],
184        DType::INT32,
185        128i32.to_le_bytes().to_vec(),
186    );
187    let e2m1 = [
188        0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0,
189    ];
190    let low = (0..256)
191        .map(|i| e2m1[((i as u8).wrapping_add(128) & 15) as usize])
192        .collect::<Vec<_>>();
193    let high = (0..256)
194        .map(|i| e2m1[((i as u8).wrapping_add(128) >> 4) as usize])
195        .collect::<Vec<_>>();
196    let scales = (0..256)
197        .map(|i| virtio_accel_tosa::fp8e4m3_to_f32((i as u8).wrapping_add(128)))
198        .collect::<Vec<_>>();
199    // Separate scalar lookups also avoid an OpenVINO 2026.4 CPU Gather issue with
200    // two-column tables. The native regression tests exercise all 256 packed bytes.
201    lookup(&mut g, "weights", "lo", packed, &low, 1, dtype);
202    lookup(&mut g, "weights", "hi", packed, &high, 1, dtype);
203    tensor(&mut g, "w_decoded", &[1, packed, 2], dtype);
204    op(
205        &mut g,
206        OperatorKind::Concat { axis: 2 },
207        &["lo_decoded", "hi_decoded"],
208        "w_decoded",
209    );
210    lookup(&mut g, "scales", "s", groups, &scales, 1, dtype);
211    reshape(&mut g, "w_decoded", "blocks", &[n, k / 16, 16], dtype);
212    reshape(&mut g, "s_decoded", "block_scales", &[n, k / 16, 1], dtype);
213    constant(&mut g, "shift", &[1], DType::INT8, vec![0]);
214    tensor(&mut g, "scaled_blocks", &[n, k / 16, 16], dtype);
215    op(
216        &mut g,
217        OperatorKind::Mul,
218        &["blocks", "block_scales", "shift"],
219        "scaled_blocks",
220    );
221    reshape(&mut g, "scaled_blocks", "matrix", &[1, n, k], dtype);
222    tensor(&mut g, "transposed", &[1, k, n], dtype);
223    op(
224        &mut g,
225        OperatorKind::Transpose {
226            perms: [0, 2, 1, 0, 0, 0],
227            rank: 3,
228        },
229        &["matrix"],
230        "transposed",
231    );
232    constant(
233        &mut g,
234        "zero",
235        &[1],
236        dtype,
237        vec![0; if dtype == DType::FP32 { 4 } else { 2 }],
238    );
239    tensor(&mut g, "product", &[1, m, n], dtype);
240    op(
241        &mut g,
242        OperatorKind::MatMul,
243        &["activations", "transposed", "zero", "zero"],
244        "product",
245    );
246    constant(&mut g, "tensor_scale", &[1, 1, 1], dtype, scale);
247    tensor(&mut g, "output", &[1, m, n], dtype);
248    op(
249        &mut g,
250        OperatorKind::Mul,
251        &["product", "tensor_scale", "shift"],
252        "output",
253    );
254    g.push_output("output");
255    Ok(g.build(TARGET)?)
256}
257#[cfg(test)]
258mod tests {
259    use super::*;
260    #[test]
261    fn graph_is_released_tosa_with_proven_lookup_bounds() {
262        let bytes = nvfp4_matmul(2, 3, 32, 0.25).unwrap();
263        let model = virtio_accel_tosa::parse(&bytes).unwrap();
264        let a = model.analyze_for(TARGET).unwrap();
265        assert_eq!(a.conditions().len(), 3);
266        assert!(
267            a.conditions()
268                .iter()
269                .all(|c| a.proves_byte_lookup_bounds(c))
270        );
271    }
272    #[test]
273    fn invalid_geometry_and_scale_are_rejected() {
274        for (m, n, k) in [(0, 1, 16), (1, 0, 16), (1, 1, 15), (1, usize::MAX, 16)] {
275            assert!(nvfp4_matmul(m, n, k, 1.0).is_err());
276        }
277        for s in [0.0, -1.0, f32::NAN, f32::INFINITY] {
278            assert!(nvfp4_matmul(1, 1, 16, s).is_err());
279        }
280        for bits in [0, 0x8000, 0xbc00, 0x7c00, 0x7e00] {
281            assert!(nvfp4_matmul_fp16(1, 1, 16, bits).is_err());
282        }
283        let bytes = nvfp4_matmul_fp16(2, 3, 32, 0x3400).unwrap();
284        let model = virtio_accel_tosa::parse(&bytes).unwrap();
285        let a = model.analyze_for(TARGET).unwrap();
286        assert!(
287            a.conditions()
288                .iter()
289                .all(|c| a.proves_byte_lookup_bounds(c))
290        );
291    }
292
293    #[test]
294    fn lookup_proof_rejects_wrong_offsets_unbounded_sources_and_small_tables() {
295        for (offset, source_type, table_size, expected) in [
296            (128, DType::INT8, 256, true),
297            (127, DType::INT8, 256, false),
298            (129, DType::INT8, 256, false),
299            (128, DType::INT32, 256, false),
300            (128, DType::INT8, 255, false),
301        ] {
302            let mut g = OwnedGraph::new("lookup_proof");
303            tensor(&mut g, "source", &[1, 8], source_type);
304            g.push_input("source");
305            tensor(&mut g, "wide", &[1, 8], DType::INT32);
306            op(
307                &mut g,
308                if source_type == DType::INT8 {
309                    OperatorKind::Cast
310                } else {
311                    OperatorKind::Identity
312                },
313                &["source"],
314                "wide",
315            );
316            constant(
317                &mut g,
318                "offset",
319                &[1, 1],
320                DType::INT32,
321                i32::to_le_bytes(offset).to_vec(),
322            );
323            tensor(&mut g, "indices", &[1, 8], DType::INT32);
324            op(&mut g, OperatorKind::Add, &["offset", "wide"], "indices");
325            tensor(&mut g, "table", &[1, table_size, 1], DType::FP32);
326            g.push_input("table");
327            tensor(&mut g, "result", &[1, 8, 1], DType::FP32);
328            op(
329                &mut g,
330                OperatorKind::Gather,
331                &["table", "indices"],
332                "result",
333            );
334            g.push_output("result");
335            let bytes = g.build(TARGET).unwrap();
336            let model = virtio_accel_tosa::parse(&bytes).unwrap();
337            let a = model.analyze_for(TARGET).unwrap();
338            assert_eq!(a.conditions().len(), 1);
339            assert_eq!(
340                a.proves_byte_lookup_bounds(&a.conditions()[0]),
341                expected,
342                "offset={offset}, source={source_type:?}, table_size={table_size}"
343            );
344        }
345    }
346}