library:ml: int8 weights carry a scale per output column, as the export does
- Commit
a20b79c1efcba58e345d71fec18039de1c83ca24- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-28 19:41 UTC (3 months ago)
- Parents
fcd7be5
Diff
library/ml/src/main/rust/shaders/conv_int8.comp
diff --git a/library/ml/src/main/rust/shaders/conv_int8.comp b/library/ml/src/main/rust/shaders/conv_int8.compindex 0f5cd109a1..f404ece019 100644--- a/library/ml/src/main/rust/shaders/conv_int8.comp+++ b/library/ml/src/main/rust/shaders/conv_int8.comp@@ -1,7 +1,7 @@ #version 450-//! A convolution whose weights are int8, dequantised by one per-tensor scale.+//! A convolution whose weights are int8, dequantised by one scale per output channel. //!-//! `out[o][y][x] = act(scale * sum(int8_w * in) + bias)`+//! `out[o][y][x] = act(scale[o] * sum(int8_w * in) + bias[o])` //! //! # Why int8 at all //!@@ -18,19 +18,21 @@ //! fp16 in the arena, so the only error introduced is the weights'. It costs nothing, because //! the weights are what take the space. //!-//! Read from the export rather than assumed: the weight zero point is a scalar **0**, so the-//! quantisation is symmetric and a value is just `int8 * scale`.+//! Read from the export rather than assumed: the weight zero points are per-column vectors and+//! every entry of every one of them is **0**, so the quantisation is symmetric and a value is+//! just `int8 * scale`. //! //! # The scale multiplies once //!-//! Because the scale is one number for the whole tensor, it applies to the finished-//! accumulator rather than to every tap — so the inner loop is an integer-to-float convert and-//! a multiply-add, exactly as many operations as the fp16 version. A per-channel scale would-//! also work this way; a per-tap one would not, which is why the rank was checked.+//! One scale per output column, which is what onnxruntime's dynamic quantiser emits — not the+//! per-tensor scalar this was first written for. Either way it applies to the finished+//! accumulator rather than to every tap, so the inner loop is an integer-to-float convert and a+//! multiply-add, exactly as many operations as the fp16 version. A per-tap scale would not work+//! this way, which is why the rank is checked. //!-//! `p.act_weight` holds the scale's own offset in the weights buffer, as an fp16 element index.-//! `p.weight` holds the int8 tensor's offset as a **32-bit word** index, because that is the-//! view it is unpacked through.+//! `p.act_weight` holds the scale tensor's offset in the weights buffer, as an fp16 element index;+//! output channel `oc` reads its own entry. `p.weight` holds the int8 tensor's offset as a+//! **32-bit word** index, because that is the view it is unpacked through. #include "common.glsl" @@ -67,7 +69,7 @@ void main() { } } - float scale = float(weights[p.act_weight]);+ float scale = float(weights[p.act_weight + oc]); float biased = total * scale + float(weights[p.bias + oc]); arena[p.out_at + index] = float16_t(activate(biased, p.act, oc)); }
library/ml/src/main/rust/src/nets/mod.rs
diff --git a/library/ml/src/main/rust/src/nets/mod.rs b/library/ml/src/main/rust/src/nets/mod.rsindex fb8142eafe..027fc83c1e 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -869,12 +869,25 @@ impl<'a> Builder<'a> { out } - /// [`Builder::conv`] with int8 weights and a per-tensor dequantisation scale.+ /// [`Builder::conv`] with int8 weights and a per-output-channel dequantisation scale. ///- /// Three tensors rather than two: the int8 kernel at `weight_index`, a one-element fp16- /// scale after it, and the fp16 bias after that. The scale is its own tensor because a- /// `.maml` table entry is already full at 32 bytes, and a companion tensor needs no- /// format version bump.+ /// Three tensors rather than two: the int8 kernel at `weight_index`, an `[m]` fp16 scale+ /// after it, and the fp16 bias after that. The scale is its own tensor because a `.maml`+ /// table entry is already full at 32 bytes, and a companion tensor needs no format version+ /// bump.+ ///+ /// # Per channel, not per tensor+ ///+ /// Read off `encoder_model_quantized.onnx` rather than assumed, and the opposite of what this+ /// was first written for: onnxruntime's dynamic quantiser emits **one scale per output+ /// column**, so a `[1024, 4096]` `MatMul` carries a `[4096]` scale. All 72 weight+ /// `MatMulInteger`s in the SMaLL-100 encoder are that shape. The zero points are per-column+ /// vectors too, but every one of them is zero, so the quantisation is symmetric and a value+ /// is still just `int8 * scale`.+ ///+ /// It costs nothing over a scalar: the scale multiplies the finished accumulator either way,+ /// so the inner loop is the same integer-to-float convert and multiply-add the fp16 path does.+ /// A per-*tap* scale would not work this way, which is why the rank is checked. /// /// `Act::PRelu` is refused: it would need a second weights offset and the push block has /// one spare, which the scale is using.@@ -921,7 +934,7 @@ impl<'a> Builder<'a> { 0 } };- let scale = self.weight(weight_index + 1, &[1]);+ let scale = self.weight(weight_index + 1, &[m]); let bias = self.weight(weight_index + 2, &[m]); let (pad_t, pad_l, pad_b, pad_r) = pads;
library/ml/src/main/rust/src/nets/reference.rs
diff --git a/library/ml/src/main/rust/src/nets/reference.rs b/library/ml/src/main/rust/src/nets/reference.rsindex c56a01e263..3bc103e49d 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -132,6 +132,13 @@ pub struct Reference { /// The weights blob, decoded once. Decoding per multiply-accumulate would be /// exact too, and slow enough to make a whole-net run untestable. weights: Vec<f32>,+ /// The same blob undecoded, for the one op whose weights are not fp16.+ ///+ /// [`Kind::ConvInt8`] reads its kernel a byte at a time through what the shader sees as a+ /// `uint` view of the weights buffer. Keeping the bytes as well as the decoded floats costs a+ /// third more memory in a test-only interpreter and is what lets an int8 net be checked on the+ /// host at all — without it the only oracle for 605 MB of quantised weights would be a phone.+ bytes: Vec<u8>, } impl Reference {@@ -154,8 +161,11 @@ impl Reference { }) .collect::<Result<Vec<f32>, String>>()?; - let mut reference =- Reference { arena: vec![0.0; plan.arena_elems as usize], weights: decoded };+ let mut reference = Reference {+ arena: vec![0.0; plan.arena_elems as usize],+ weights: decoded,+ bytes: weights.to_vec(),+ }; for (binding, values) in plan.inputs.iter().zip(inputs) { if values.len() != binding.shape.len() as usize { return Err(format!(@@ -200,11 +210,8 @@ impl Reference { Kind::AddBroadcast => self.add_broadcast(push), Kind::Rotary => self.rotary(push), Kind::GatedTanh => self.gated_tanh(push),- // The reference interpreter holds its weights as `f32`, so there is no- // byte view to unpack: an int8 plan can be built and inspected on the- // host but not run. `scripts/ml/onnx_parity.py` checks it on a device. Kind::ConvPoint => self.conv_point(push),- Kind::ConvInt8 => Err("int8 convolution has no host reference".into()),+ Kind::ConvInt8 => self.conv_int8(push), Kind::FlipChannels => self.flip_channels(push), }, };@@ -308,6 +315,69 @@ impl Reference { Ok(()) } + /// [`Reference::conv`] with int8 weights and a per-output-channel scale.+ ///+ /// Deliberately a separate function rather than a flag on `conv`: the accumulation is over+ /// integers scaled once at the end, and the padding is zero rather than edge — `Node::ConvInt8`+ /// carries no `pad_edge`, so there is nothing to branch on. Keeping them apart means the fp16+ /// path, which five shipping nets run on, is not touched by anything int8 needs.+ fn conv_int8(&mut self, p: &Push) -> Result<(), String> {+ let (in_per_group, out_per_group) = groups(p)?;+ for oc in 0..p.out_c {+ let first_in = (oc / out_per_group) * in_per_group;+ let kernel_at = oc * in_per_group * p.kh * p.kw;+ // One per output column, unlike the fp16 path's single `act_weight` slot.+ let scale = self.weight(p.act_weight, oc)?;+ for oy in 0..p.out_h {+ for ox in 0..p.out_w {+ let mut acc = 0.0f32;+ for ic in 0..in_per_group {+ let plane = (first_in + ic) * p.in_h * p.in_w;+ for ky in 0..p.kh {+ let positioned = oy * p.stride_h + ky * p.dil_h;+ let iy = match tap(positioned, p.pad_t, p.in_h) {+ Some(found) => found,+ None => continue,+ };+ let row = plane + iy * p.in_w;+ let tap_at = kernel_at + (ic * p.kh + ky) * p.kw;+ for kx in 0..p.kw {+ let positioned = ox * p.stride_w + kx * p.dil_w;+ let ix = match tap(positioned, p.pad_l, p.in_w) {+ Some(found) => found,+ None => continue,+ };+ acc += self.load(p.in0, row + ix)?+ * f32::from(self.int8(p.weight, tap_at + kx)?);+ }+ }+ }+ let biased = acc * scale + self.weight(p.bias, oc)?;+ // PRelu is refused at build time for int8, so the slope is never read.+ self.store(p.out, nchw(p, oc, oy, ox), activate(biased, p.act, 0.0))?;+ }+ }+ }+ Ok(())+ }++ /// Element `index` of the int8 tensor whose **32-bit word** offset is `word`.+ ///+ /// The shader reads these through a `uint` alias of the weights buffer and unpacks four bytes+ /// at a time, because a byte view would need `VK_KHR_8bit_storage` on top of the fp16+ /// extension this runtime already requires. Here the same address arithmetic is done on the+ /// undecoded blob, so the two agree by construction rather than by coincidence.+ fn int8(&self, word: u32, index: u32) -> Result<i8, String> {+ let at = (word as usize)+ .checked_mul(4)+ .and_then(|base| base.checked_add(index as usize))+ .ok_or("an int8 weight offset overflowed")?;+ self.bytes+ .get(at)+ .map(|&byte| byte as i8)+ .ok_or_else(|| format!("int8 weight byte {at} of {}", self.bytes.len()))+ }+ /// The PReLU slope for output channel `c`, or zero when the activation is not PReLU. fn slope(&self, p: &Push, c: u32) -> Result<f32, String> { if p.act == act::PRELU {@@ -1124,6 +1194,60 @@ mod tests { run(&plan, given.data(), input).expect("the fixture plan runs") } + #[test]+ fn an_int8_convolution_dequantises_per_output_channel() {+ // Two output channels over three input channels, 1x1 — the shape every SMaLL-100 linear+ // reduces to. The two channels get *different* scales, which is the whole point: a+ // per-tensor scale would give channel 1 four times its correct magnitude here and still+ // produce a plausible-looking tensor of the right shape.+ //+ // Values chosen to be exact in fp16 so the expectation can be written out longhand and any+ // disagreement is arithmetic rather than rounding.+ let kernel: Vec<i8> = vec![1, 2, 3, 4, -5, 6];+ let scales = vec![0.25f32, 1.0];+ let biases = vec![1.0f32, -1.0];+ let blob = crate::weights::write_mixed(+ crate::weights::graph::SUPERTONIC_VE,+ &[+ crate::weights::Fixture::I8(vec![2, 3, 1, 1], kernel.clone()),+ crate::weights::Fixture::F16(vec![2], scales.clone()),+ crate::weights::Fixture::F16(vec![2], biases.clone()),+ ],+ );+ let weights = crate::weights::Weights::parse(&blob, crate::weights::graph::SUPERTONIC_VE)+ .expect("the fixture blob parses");++ // Three channels, two positions: [c0: 1, 2] [c1: 4, 8] [c2: 0.5, -1]+ let input = vec![1.0f32, 2.0, 4.0, 8.0, 0.5, -1.0];+ let mut builder = Builder::new(&weights);+ let first = builder.input(Shape::new(3, 1, 2));+ let last = builder.conv_int8(+ first,+ 0,+ 2,+ (1, 1),+ (1, 1),+ (1, 1),+ (0, 0, 0, 0),+ 1,+ Act::None,+ );+ let plan = builder.finish(&[last]).expect("the int8 fixture plan builds");+ let got = run(&plan, weights.data(), &input).expect("the int8 fixture plan runs");++ let mut want = Vec::new();+ for oc in 0..2usize {+ for x in 0..2usize {+ let mut acc = 0.0f32;+ for ic in 0..3usize {+ acc += f32::from(kernel[oc * 3 + ic]) * input[ic * 2 + x];+ }+ want.push(acc * scales[oc] + biases[oc]);+ }+ }+ assert_eq!(got, want, "int8 conv: got {got:?}, want {want:?}");+ }+ /// [`one`], for the ops whose two operands are different shapes. /// /// Attention cannot be checked with one tensor used twice: `Q . K^T` is symmetric
library/ml/src/main/rust/src/vulkan/parity.rs
diff --git a/library/ml/src/main/rust/src/vulkan/parity.rs b/library/ml/src/main/rust/src/vulkan/parity.rsindex 4d0972c7a0..888ab2450f 100644--- a/library/ml/src/main/rust/src/vulkan/parity.rs+++ b/library/ml/src/main/rust/src/vulkan/parity.rs@@ -31,7 +31,7 @@ use std::sync::{Arc, OnceLock}; use crate::nets::reference::{run_multi, Given, Invented}; use crate::nets::{embed_lanes, Act, Builder, Id, Plan, Shape, WeightSource}; use crate::preprocess::RESCALE_ONLY;-use crate::weights::Weights;+use crate::weights::{graph, write_mixed, Fixture, Weights}; use super::context::{self, Context}; use super::run::Net;@@ -290,6 +290,51 @@ fn a_two_lane_embedding_agrees_with_the_reference() { ); } +#[test]+#[ignore = "needs a Vulkan device"]+fn an_int8_convolution_agrees_with_the_reference() {+ // The only op whose weights are not fp16, so the only one where the shader and the interpreter+ // address the weights buffer differently: 32-bit words unpacked to bytes on one side, a byte+ // index into the undecoded blob on the other. Four output channels with four *different*+ // scales, because a shader that read `scale[0]` for every channel — which is what this op did+ // before the export turned out to be quantised per column — still returns the right shape and+ // three wrong channels.+ let out_channels = 4u32;+ let in_channels = 3u32;+ let width = 5u32;+ let kernel: Vec<i8> = (0..(out_channels * in_channels) as i32)+ .map(|i| ((i * 7) % 61 - 30) as i8)+ .collect();+ let scales: Vec<f32> = vec![0.25, 0.5, 0.0625, 1.0];+ let biases: Vec<f32> = vec![0.5, -0.25, 1.0, 0.0];+ let blob = write_mixed(+ graph::SUPERTONIC_VE,+ &[+ Fixture::I8(vec![out_channels, in_channels, 1, 1], kernel),+ Fixture::F16(vec![out_channels], scales),+ Fixture::F16(vec![out_channels], biases),+ ],+ );+ let weights = Weights::parse(&blob, graph::SUPERTONIC_VE).expect("the fixture blob parses");+ let input = spread((in_channels * width) as usize, 0.3);++ let mut builder = Builder::new(&weights);+ let first = builder.input(Shape::new(in_channels, 1, width));+ let last = builder.conv_int8(+ first,+ 0,+ out_channels,+ (1, 1),+ (1, 1),+ (1, 1),+ (0, 0, 0, 0),+ 1,+ Act::Relu,+ );+ let plan = builder.finish(&[last]).expect("the int8 fixture plan builds");+ compare("an int8 convolution", plan, weights.data().to_vec(), &[&input]);+}+ #[test] #[ignore = "needs a Vulkan device"] fn a_rebuilt_net_agrees_with_the_reference_at_each_shape() {
library/ml/src/main/rust/src/weights.rs
diff --git a/library/ml/src/main/rust/src/weights.rs b/library/ml/src/main/rust/src/weights.rsindex 3e9849a1f4..5e0eceee92 100644--- a/library/ml/src/main/rust/src/weights.rs+++ b/library/ml/src/main/rust/src/weights.rs@@ -321,6 +321,83 @@ impl Weights { } } +/// One tensor for [`write_mixed`]: fp16 values, or the int8 payload of a quantised kernel.+#[cfg(test)]+pub(crate) enum Fixture {+ /// fp16, the format every tensor but a quantised kernel is in.+ F16(Vec<u32>, Vec<f32>),+ /// int8, addressed by the shaders as a 32-bit word offset. See [`Tensor::word_offset`].+ I8(Vec<u32>, Vec<i8>),+}++/// Build a `.maml` blob from a mix of fp16 and int8 tensors, for the fixtures.+///+/// The `write` helper in this module's tests emits fp16 only, and an int8 convolution needs a table+/// where one tensor is int8 and the two after it — its per-channel scale and its bias — are not.+/// Shared rather than hand-rolled per test because the 16-byte alignment and the resulting word+/// offsets are precisely what a second copy would get subtly wrong, and a wrong offset here reads a+/// neighbouring tensor at the right shape.+#[cfg(test)]+pub(crate) fn write_mixed(graph_id: u32, tensors: &[Fixture]) -> Vec<u8> {+ fn f32_to_f16(v: f32) -> u16 {+ let bits = v.to_bits();+ let sign = ((bits >> 16) & 0x8000) as u16;+ let exponent = ((bits >> 23) & 0xFF) as i32 - 127 + 15;+ let mantissa = bits & 0x007F_FFFF;+ if exponent >= 0x1F {+ return sign | 0x7C00;+ }+ if exponent <= 0 {+ return sign;+ }+ sign | ((exponent as u16) << 10) | ((mantissa >> 13) as u16)+ }++ let mut table = Vec::new();+ let mut data: Vec<u8> = Vec::new();+ for tensor in tensors {+ let (dims, dtype, len, bytes) = match tensor {+ Fixture::F16(dims, values) => (+ dims,+ DTYPE_F16,+ values.len() as u32,+ values.iter().flat_map(|&v| f32_to_f16(v).to_le_bytes()).collect::<Vec<u8>>(),+ ),+ Fixture::I8(dims, values) => (+ dims,+ DTYPE_I8,+ values.len() as u32,+ values.iter().map(|&v| v as u8).collect::<Vec<u8>>(),+ ),+ };+ while !data.len().is_multiple_of(ALIGNMENT as usize) {+ data.push(0);+ }+ let offset = data.len() as u32;+ data.extend_from_slice(&bytes);+ table.extend_from_slice(&(dims.len() as u32).to_le_bytes());+ for slot in 0..4 {+ table.extend_from_slice(&dims.get(slot).copied().unwrap_or(0).to_le_bytes());+ }+ table.extend_from_slice(&dtype.to_le_bytes());+ table.extend_from_slice(&offset.to_le_bytes());+ table.extend_from_slice(&len.to_le_bytes());+ }++ let mut blob = Vec::new();+ blob.extend_from_slice(&MAGIC);+ blob.extend_from_slice(&FORMAT_VERSION.to_le_bytes());+ blob.extend_from_slice(&graph_id.to_le_bytes());+ blob.extend_from_slice(&(tensors.len() as u32).to_le_bytes());+ blob.extend_from_slice(&[0u8; 32]);+ blob.extend_from_slice(&((HEADER_BYTES + table.len()) as u32).to_le_bytes());+ blob.extend_from_slice(&(data.len() as u32).to_le_bytes());+ blob.extend_from_slice(&[0u8; 8]);+ blob.extend_from_slice(&table);+ blob.extend_from_slice(&data);+ blob+}+ fn u32(bytes: &[u8], at: usize) -> u32 { u32::from_le_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]]) }
scripts/ml/maml_convert.py
diff --git a/scripts/ml/maml_convert.py b/scripts/ml/maml_convert.pyindex c62c1d491e..31b3dda258 100644--- a/scripts/ml/maml_convert.py+++ b/scripts/ml/maml_convert.py@@ -637,9 +637,13 @@ def quantised_linear(node, held, array, following_bias): Read from `casawolice/small100-onnx` rather than assumed: - * The weight zero point is a **scalar 0**, so the quantisation is symmetric and a value is- `int8 * scale`. A non-zero one is refused rather than ignored.- * The weight scale is a **scalar**, so it multiplies the accumulator once.+ * The weight zero point is a **per-column vector and every entry is 0**, so the quantisation+ is symmetric and a value is `int8 * scale`. A non-zero one is refused rather than ignored.+ * The weight scale is **per output column** - a `[1024, 4096]` weight carries a `[4096]`+ scale. It still multiplies the finished accumulator rather than every tap, so+ `conv_int8.comp` costs the same as the fp16 path; it just indexes the scale by output+ channel. A scalar is accepted too, broadcast to one per column, so a per-tensor quantiser+ also converts. * The *activation* scale and zero point come from a `DynamicQuantizeLinear` at runtime. Both are dropped: activations stay fp16 here, which is simpler than reproducing dynamic quantisation and strictly more accurate, and costs nothing because the weights are what@@ -654,27 +658,30 @@ def quantised_linear(node, held, array, following_bias): if weight.dtype != np.int8 or weight.ndim != 2: return None zero = np.array(array(zero_name)).flatten()- if zero.size != 1 or int(zero[0]) != 0:+ if np.any(zero != 0): raise SystemExit(- f"{node.output[0]}: weight zero point {zero.tolist()} is not 0, so the "- "quantisation is not symmetric and `conv_int8.comp` would be wrong"+ f"{node.output[0]}: weight zero point {zero[zero != 0][:4].tolist()} is not 0, so "+ "the quantisation is not symmetric and `conv_int8.comp` would be wrong" ) scale_name = weight_name.removesuffix("_quantized") + "_scale" if not held(scale_name): raise SystemExit(f"{node.output[0]}: no {scale_name} beside its weight") scale = np.array(array(scale_name)).flatten()- if scale.size != 1:+ inputs, outputs = weight.shape+ if scale.size == 1:+ # A per-tensor quantiser. Broadcast rather than special-case it, so the `.maml` layout is+ # the same either way and the shader has one path.+ scale = np.repeat(scale, outputs)+ if scale.size != outputs: raise SystemExit(- f"{node.output[0]}: a {scale.size}-element scale; `conv_int8.comp` applies one "- "number to the whole accumulator, so a per-channel scale needs a shader change"+ f"{node.output[0]}: a {scale.size}-element scale for {outputs} output columns; "+ "`conv_int8.comp` reads one per output channel" )-- inputs, outputs = weight.shape # `[in, out]` to `[out, in, 1, 1]`. kernel = np.ascontiguousarray(weight.T).reshape(outputs, inputs, 1, 1) bias = following_bias(node, outputs) key = (- f"MatMulInteger w={list(kernel.shape)} scale=1 b={[outputs]} "+ f"MatMulInteger w={list(kernel.shape)} scale={[outputs]} b={[outputs]} " f"zp=0 dtype=int8" ) return [kernel, scale.astype(np.float32), bias], key