Skip to main content

virtio_accel_tosa_build/quantized/
palette.rs

1//! Explicit constant four-bit lookup indices and binary16 palettes.
2use super::*;
3
4/// Build a projection with immutable four-bit palette indices and FP16 activations.
5///
6/// Indices are row-major `[N,K]`, low nibble first. Each contiguous `group_size`
7/// weights has its own 16-entry binary16 palette: `[N,K/group_size,16]`.
8/// Entries may be arbitrary finite FP16 values (including signed zero); no
9/// clustering, quantization or scaling is performed. Slots are FP16 activations
10/// `[1,M,K]` and FP16 output `[1,M,N]`.
11///
12/// Portable TOSA stores unpacked INT32 indices and uses GATHER. Core ML can
13/// repack these constants into `constexpr_lut_to_dense` at load time. This is
14/// scalar palettization, not linear INT4 or NVFP4. Constants require reload to update.
15pub fn palette4_matmul_fp16(
16    m: usize,
17    n: usize,
18    k: usize,
19    group_size: usize,
20    packed_indices: &[u8],
21    palette_bits: &[u16],
22) -> Result<Vec<u8>, QuantizedBuildError> {
23    if [m, n, k, group_size]
24        .iter()
25        .any(|v| *v == 0 || i32::try_from(*v).is_err())
26        || k % group_size != 0
27    {
28        return Err(QuantizedBuildError::InvalidShape);
29    }
30    let count = n.checked_mul(k).ok_or(QuantizedBuildError::InvalidShape)?;
31    let groups = count / group_size;
32    if count % 2 != 0
33        || packed_indices.len() != count / 2
34        || i32::try_from(groups).is_err()
35        || groups.checked_mul(16) != Some(palette_bits.len())
36    {
37        return Err(QuantizedBuildError::InvalidShape);
38    }
39    if palette_bits.iter().any(|v| v & 0x7c00 == 0x7c00) {
40        return Err(QuantizedBuildError::InvalidScale);
41    }
42    let (m, n, k, group) = (m as i32, n as i32, k as i32, group_size as i32);
43    let d = DType::FP16;
44    let mut g = OwnedGraph::new("palette_weight_projection");
45    tensor(&mut g, "activations", &[1, m, k], d);
46    g.push_input("activations");
47    constant(
48        &mut g,
49        "palette",
50        &[groups as i32, 16, 1],
51        d,
52        palette_bits.iter().flat_map(|v| v.to_le_bytes()).collect(),
53    );
54    constant(
55        &mut g,
56        "indices",
57        &[groups as i32, group],
58        DType::INT32,
59        packed_indices
60            .iter()
61            .flat_map(|v| [i32::from(v & 15), i32::from(v >> 4)])
62            .flat_map(i32::to_le_bytes)
63            .collect(),
64    );
65    tensor(&mut g, "decoded", &[groups as i32, group, 1], d);
66    op(
67        &mut g,
68        OperatorKind::Gather,
69        &["palette", "indices"],
70        "decoded",
71    );
72    reshape(&mut g, "decoded", "matrix", &[1, n, k], d);
73    tensor(&mut g, "transposed", &[1, k, n], d);
74    op(
75        &mut g,
76        OperatorKind::Transpose {
77            perms: [0, 2, 1, 0, 0, 0],
78            rank: 3,
79        },
80        &["matrix"],
81        "transposed",
82    );
83    constant(&mut g, "zero", &[1], d, vec![0, 0]);
84    tensor(&mut g, "output", &[1, m, n], d);
85    op(
86        &mut g,
87        OperatorKind::MatMul,
88        &["activations", "transposed", "zero", "zero"],
89        "output",
90    );
91    g.push_output("output");
92    Ok(g.build(TARGET)?)
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98    #[test]
99    fn palette_indices_and_geometry_are_explicit() {
100        let data = palette4_matmul_fp16(2, 2, 16, 8, &[0x98; 16], &[0x3555; 64]).unwrap();
101        let model = virtio_accel_tosa::parse(&data).unwrap();
102        let a = model.analyze_for(TARGET).unwrap();
103        let indices = a.values().iter().find(|v| v.name() == "indices").unwrap();
104        assert_eq!(
105            &a.serialized_constant(indices.id()).unwrap()[..8],
106            &[8, 0, 0, 0, 9, 0, 0, 0]
107        );
108        assert!(
109            a.conditions()
110                .iter()
111                .all(|c| a.proves_constant_index_bounds(c))
112        );
113        assert!(palette4_matmul_fp16(1, 1, 16, 0, &[0; 8], &[0; 16]).is_err());
114        assert!(palette4_matmul_fp16(1, 1, 16, 3, &[0; 8], &[0; 16]).is_err());
115        assert!(palette4_matmul_fp16(1, 1, 16, 16, &[0; 7], &[0; 16]).is_err());
116        assert!(palette4_matmul_fp16(1, 1, 16, 16, &[0; 8], &[0; 15]).is_err());
117        assert!(palette4_matmul_fp16(1, 1, 16, 16, &[0; 8], &[0x7c00; 16]).is_err());
118    }
119    #[test]
120    fn constant_index_proof_rejects_negative_high_and_runtime_indices() {
121        for (index, runtime, expected) in [
122            (0, false, true),
123            (15, false, true),
124            (-1, false, false),
125            (16, false, false),
126            (0, true, false),
127        ] {
128            let mut g = OwnedGraph::new("bounds");
129            tensor(&mut g, "table", &[1, 16, 1], DType::FP16);
130            g.push_input("table");
131            if runtime {
132                tensor(&mut g, "indices", &[1, 1], DType::INT32);
133                g.push_input("indices");
134            } else {
135                constant(
136                    &mut g,
137                    "indices",
138                    &[1, 1],
139                    DType::INT32,
140                    i32::to_le_bytes(index).to_vec(),
141                );
142            }
143            tensor(&mut g, "out", &[1, 1, 1], DType::FP16);
144            op(&mut g, OperatorKind::Gather, &["table", "indices"], "out");
145            g.push_output("out");
146            let bytes = g.build(TARGET).unwrap();
147            let model = virtio_accel_tosa::parse(&bytes).unwrap();
148            let a = model.analyze_for(TARGET).unwrap();
149            assert_eq!(a.conditions().len(), 1);
150            assert_eq!(a.proves_constant_index_bounds(&a.conditions()[0]), expected);
151        }
152    }
153}