Skip to main content

virtio_accel_tosa_build/quantized/
integer.rs

1//! Constant, symmetric integer weights with explicit FP16 dequantization.
2use super::*;
3
4/// Build an FP16 projection with immutable, symmetric signed four-bit weights.
5///
6/// `packed_weights` is row-major `[N,K]`, low nibble first, two's-complement `[-8,7]`.
7/// N*K must be even; the packed byte slice must have exactly N*K/2 bytes.
8/// `scale_bits` contains positive finite binary16 scales `[N,K/group_size]`.
9/// Each weight is converted to FP16 then multiplied by its group's scale before
10/// MATMUL. Slots are 0: FP16 activations `[1,M,K]`, 1: FP16 output `[1,M,N]`.
11///
12/// TOSA 1.0 has no INT4-to-float CAST. The portable artifact therefore serializes
13/// these exact values as INT8 constants, using one byte per weight. OpenVINO and Core ML can
14/// losslessly repack them to native compressed constants at load time. This is not a TOSA
15/// INT4 tensor or NVFP4; no automatic quantization of floating weights occurs.
16/// Changing weights or scales requires rebuilding and reloading the program.
17pub fn int4_matmul_fp16(
18    m: usize,
19    n: usize,
20    k: usize,
21    group_size: usize,
22    packed_weights: &[u8],
23    scale_bits: &[u16],
24) -> Result<Vec<u8>, QuantizedBuildError> {
25    let elements = validate(m, n, k, group_size, scale_bits)?;
26    if elements % 2 != 0 || packed_weights.len() != elements / 2 {
27        return Err(QuantizedBuildError::InvalidShape);
28    }
29    let weights = packed_weights
30        .iter()
31        .flat_map(|byte| [byte & 15, byte >> 4].map(|v| ((v as i8) << 4) >> 4))
32        .collect::<Vec<_>>();
33    build(m, n, k, group_size, &weights, scale_bits)
34}
35
36/// As [`int4_matmul_fp16`], with signed eight-bit constant weights `[N,K]`.
37/// Values are represented exactly; the backend may losslessly use narrower
38/// storage when all values fit. This is W8A16, not integer-profile INT8 MATMUL.
39pub fn int8_matmul_fp16(
40    m: usize,
41    n: usize,
42    k: usize,
43    group_size: usize,
44    weights: &[i8],
45    scale_bits: &[u16],
46) -> Result<Vec<u8>, QuantizedBuildError> {
47    let elements = validate(m, n, k, group_size, scale_bits)?;
48    if weights.len() != elements {
49        return Err(QuantizedBuildError::InvalidShape);
50    }
51    build(m, n, k, group_size, weights, scale_bits)
52}
53
54fn validate(
55    m: usize,
56    n: usize,
57    k: usize,
58    group: usize,
59    scales: &[u16],
60) -> Result<usize, QuantizedBuildError> {
61    if m == 0
62        || n == 0
63        || k == 0
64        || group == 0
65        || k % group != 0
66        || [m, n, k, group].iter().any(|v| i32::try_from(*v).is_err())
67    {
68        return Err(QuantizedBuildError::InvalidShape);
69    }
70    let elements = n.checked_mul(k).ok_or(QuantizedBuildError::InvalidShape)?;
71    if scales.len() != elements / group {
72        return Err(QuantizedBuildError::InvalidShape);
73    }
74    if scales
75        .iter()
76        .any(|b| *b == 0 || b & 0x8000 != 0 || b & 0x7c00 == 0x7c00)
77    {
78        return Err(QuantizedBuildError::InvalidScale);
79    }
80    Ok(elements)
81}
82
83fn build(
84    m: usize,
85    n: usize,
86    k: usize,
87    group: usize,
88    weights: &[i8],
89    scales: &[u16],
90) -> Result<Vec<u8>, QuantizedBuildError> {
91    let (m, n, k, group) = (m as i32, n as i32, k as i32, group as i32);
92    let d = DType::FP16;
93    let mut g = OwnedGraph::new("integer_weight_projection");
94    tensor(&mut g, "activations", &[1, m, k], d);
95    g.push_input("activations");
96    constant(
97        &mut g,
98        "weights",
99        &[n, k / group, group],
100        DType::INT8,
101        weights.iter().map(|v| *v as u8).collect(),
102    );
103    tensor(&mut g, "decoded", &[n, k / group, group], d);
104    op(&mut g, OperatorKind::Cast, &["weights"], "decoded");
105    constant(
106        &mut g,
107        "scales",
108        &[n, k / group, 1],
109        d,
110        scales.iter().flat_map(|v| v.to_le_bytes()).collect(),
111    );
112    constant(&mut g, "shift", &[1], DType::INT8, vec![0]);
113    tensor(&mut g, "scaled", &[n, k / group, group], d);
114    op(
115        &mut g,
116        OperatorKind::Mul,
117        &["decoded", "scales", "shift"],
118        "scaled",
119    );
120    reshape(&mut g, "scaled", "matrix", &[1, n, k], d);
121    tensor(&mut g, "transposed", &[1, k, n], d);
122    op(
123        &mut g,
124        OperatorKind::Transpose {
125            perms: [0, 2, 1, 0, 0, 0],
126            rank: 3,
127        },
128        &["matrix"],
129        "transposed",
130    );
131    constant(&mut g, "zero", &[1], d, vec![0, 0]);
132    tensor(&mut g, "output", &[1, m, n], d);
133    op(
134        &mut g,
135        OperatorKind::MatMul,
136        &["activations", "transposed", "zero", "zero"],
137        "output",
138    );
139    g.push_output("output");
140    Ok(g.build(TARGET)?)
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146    #[test]
147    fn signed_nibbles_and_groups_are_explicit_portable_operations() {
148        let packed = [0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe];
149        let bytes = int4_matmul_fp16(2, 2, 8, 4, &packed, &[0x3800; 4]).unwrap();
150        let model = virtio_accel_tosa::parse(&bytes).unwrap();
151        let a = model.analyze_for(TARGET).unwrap();
152        assert!(a.conditions().is_empty());
153        let weights = a.values().iter().find(|v| v.name() == "weights").unwrap();
154        assert_eq!(
155            a.serialized_constant(weights.id()).unwrap(),
156            &[
157                0, 1, 2, 3, 4, 5, 6, 7, 248, 249, 250, 251, 252, 253, 254, 255
158            ]
159        );
160        assert_eq!(a.block_inputs(a.blocks()[0].id()).len(), 1);
161        let w8 = int8_matmul_fp16(1, 1, 4, 4, &[-128, -8, 7, 127], &[0x3c00]).unwrap();
162        virtio_accel_tosa::parse(&w8)
163            .unwrap()
164            .analyze_for(TARGET)
165            .unwrap();
166    }
167    #[test]
168    fn malformed_weight_geometry_and_scales_are_rejected() {
169        for (m, n, k, g) in [
170            (0, 1, 2, 2),
171            (1, 0, 2, 2),
172            (1, 1, 0, 2),
173            (1, 1, 2, 0),
174            (1, 1, 2, 3),
175            (1, usize::MAX, 2, 2),
176        ] {
177            assert!(int4_matmul_fp16(m, n, k, g, &[0], &[0x3c00]).is_err());
178        }
179        assert!(int4_matmul_fp16(1, 1, 2, 2, &[], &[0x3c00]).is_err());
180        assert!(int8_matmul_fp16(1, 1, 2, 2, &[1], &[0x3c00]).is_err());
181        assert!(int4_matmul_fp16(1, 1, 2, 2, &[0], &[]).is_err());
182        for scale in [0, 0x8000, 0xbc00, 0x7c00, 0xfc00, 0x7e00] {
183            assert!(int4_matmul_fp16(1, 1, 2, 2, &[0], &[scale]).is_err());
184        }
185    }
186}