library:ml: int8 weights, dequantised by one per-tensor scale
- Commit
3e931427a842abab54929dccd203b17db6b31475- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-28 02:32 UTC (3 months ago)
- Parents
61e1adb
Diff
library/ml/src/main/rust/shaders/common.glsl
diff --git a/library/ml/src/main/rust/shaders/common.glsl b/library/ml/src/main/rust/shaders/common.glslindex fc0d87d276..faf9e9615f 100644--- a/library/ml/src/main/rust/shaders/common.glsl+++ b/library/ml/src/main/rust/shaders/common.glsl@@ -42,6 +42,18 @@ layout(std430, binding = 0) buffer Arena { layout(std430, binding = 1) readonly buffer Weights { float16_t weights[]; };+// The same buffer as binding 1, viewed as 32-bit words.+//+// Int8 weights are unpacked from here four at a time. A byte view would be tidier but needs+// `VK_KHR_8bit_storage`, an extension on top of the fp16 one this runtime already requires,+// and every extra requirement narrows the devices that can run at all. 32-bit storage is+// universal.+//+// Aliasing one buffer through two descriptors is allowed, and both are read-only, so there is+// no write hazard between the views.+layout(std430, binding = 2) readonly buffer Weights32 {+ uint weights32[];+}; layout(push_constant) uniform Push { uint in0;@@ -103,6 +115,17 @@ uint global_index() { // `channel` is the output channel, needed only by PReLU, whose slope is one value per // channel at `p.act_weight` in the weights buffer. Passing it unconditionally costs a // register and keeps one signature.+/// One signed byte of an int8 tensor, by element index.+///+/// `base` is the tensor's start as a 32-bit word index; `index` is the element within it.+/// `bitfieldExtract` on a *signed* integer sign-extends, which is what turns the byte back into+/// -128..127 rather than 0..255 — reading it unsigned would make every negative weight large+/// and positive, which trains-looking output would not reveal.+int int8_at(uint base, uint index) {+ uint word = weights32[base + (index >> 2u)];+ return bitfieldExtract(int(word), int((index & 3u) << 3u), 8);+}+ float activate(float x, uint kind, uint channel) { if (kind == ACT_RELU) { return max(x, 0.0);
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.compnew file mode 100644index 0000000000..0f5cd109a1--- /dev/null+++ b/library/ml/src/main/rust/shaders/conv_int8.comp@@ -0,0 +1,73 @@+#version 450+//! A convolution whose weights are int8, dequantised by one per-tensor scale.+//!+//! `out[o][y][x] = act(scale * sum(int8_w * in) + bias)`+//!+//! # Why int8 at all+//!+//! Only where the weights dominate a download. SMaLL-100 is 330 million parameters: 660 MB at+//! fp16 and 330 MB here, against the 1.14 GB the ncnn build of the same model shipped. Every+//! other network in this runtime is small enough that fp16 costs nothing worth reclaiming, and+//! they keep using `conv.comp`.+//!+//! # What is quantised and what is not+//!+//! Weights only. The export quantises its activations too, dynamically, per tensor — a+//! `DynamicQuantizeLinear` before every `MatMulInteger`, with a zero point to carry the+//! asymmetry. This does not, and that is both simpler and *more* accurate: activations stay+//! 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`.+//!+//! # 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.+//!+//! `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.++#include "common.glsl"++void main() {+ uint index = global_index();+ if (index >= p.count) {+ return;+ }+ uint oc, oy, ox;+ unpack(index, oc, oy, ox);++ uint per_group = p.in_c / p.group;+ uint group = oc / (p.out_c / p.group);+ uint base = group * per_group;++ float total = 0.0;+ for (uint ic = 0u; ic < per_group; ic++) {+ uint channel = base + ic;+ for (uint ky = 0u; ky < p.kh; ky++) {+ int iy = int(oy * p.stride_h + ky * p.dil_h) - int(p.pad_t);+ if (iy < 0 || iy >= int(p.in_h)) {+ continue;+ }+ for (uint kx = 0u; kx < p.kw; kx++) {+ int ix = int(ox * p.stride_w + kx * p.dil_w) - int(p.pad_l);+ if (ix < 0 || ix >= int(p.in_w)) {+ continue;+ }+ uint at = ((oc * per_group + ic) * p.kh + ky) * p.kw + kx;+ float value =+ float(arena[p.in0 + (channel * p.in_h + uint(iy)) * p.in_w + uint(ix)]);+ total += float(int8_at(p.weight, at)) * value;+ }+ }+ }++ float scale = float(weights[p.act_weight]);+ 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 e3d08c0a85..6cd36498e6 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -243,6 +243,13 @@ pub enum Kind { GatedTanh, /// `out[c] = in[C - 1 - c]`, a channel reversal. VITS''s `Flip` between coupling layers. FlipChannels,+ /// [`Kind::Conv`] with int8 weights and one per-tensor dequantisation scale.+ ///+ /// Only for a network where the weights dominate the download. The scale multiplies the+ /// finished accumulator rather than every tap, so the inner loop costs what fp16 costs;+ /// activations stay fp16, which is simpler than the export''s dynamic quantisation and+ /// strictly more accurate. [`Push::weight`] is a **word** offset here, not an fp16 one.+ ConvInt8, /// `out[c][t] = table[id(t)][c]`, an embedding lookup. /// /// The only op here whose addresses depend on the data. Ids arrive as an ordinary fp16@@ -420,6 +427,12 @@ impl Plan { pub trait WeightSource { /// The fp16 element offset of tensor `index`, which must have shape `dims`. fn shaped(&self, index: usize, dims: &[u32]) -> Result<u32, String>;+ /// The **32-bit word** offset of tensor `index`, for an int8 tensor.+ ///+ /// Int8 weights are read through a `uint` view of the same buffer, four bytes at a time,+ /// so their offsets are word indices rather than fp16 element indices. See+ /// [`crate::weights::Tensor::word_offset`].+ fn shaped_words(&self, index: usize, dims: &[u32]) -> Result<u32, String>; /// How many tensors there are, so a builder can insist it consumed all of them. fn count(&self) -> usize;@@ -429,6 +442,13 @@ impl WeightSource for crate::weights::Weights { fn shaped(&self, index: usize, dims: &[u32]) -> Result<u32, String> { Ok(crate::weights::Weights::shaped(self, index, dims)?.elem_offset()) }+ fn shaped_words(&self, index: usize, dims: &[u32]) -> Result<u32, String> {+ let found = crate::weights::Weights::shaped(self, index, dims)?;+ if !found.int8 {+ return Err(format!("tensor {index} is fp16, but the pass wants int8"));+ }+ Ok(found.word_offset())+ } fn count(&self) -> usize { self.len()@@ -536,6 +556,19 @@ enum Node { out: Id, start: u32, },+ ConvInt8 {+ input: Id,+ out: Id,+ weight: u32,+ scale: u32,+ bias: u32,+ kernel: (u32, u32),+ stride: (u32, u32),+ dilation: (u32, u32),+ pad: (u32, u32),+ group: u32,+ act: Act,+ }, AttnApply { probs: Id, v: Id,@@ -687,6 +720,81 @@ impl<'a> Builder<'a> { out } + /// [`Builder::conv`] with int8 weights and a per-tensor 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.+ ///+ /// `Act::PRelu` is refused: it would need a second weights offset and the push block has+ /// one spare, which the scale is using.+ #[allow(clippy::too_many_arguments)]+ pub fn conv_int8(+ &mut self,+ input: Id,+ weight_index: usize,+ m: u32,+ kernel: (u32, u32),+ stride: (u32, u32),+ dilation: (u32, u32),+ pads: (u32, u32, u32, u32),+ group: u32,+ act: Act,+ ) -> Id {+ let in_shape = self.shape_of(input);+ let (kh, kw) = kernel;+ let splits =+ group != 0 && in_shape.c.is_multiple_of(group) && m.is_multiple_of(group);+ if !splits {+ self.fail(format!(+ "tensor {weight_index}: {} in / {m} out channels do not split into \+ {group} groups",+ in_shape.c+ ));+ }+ if let Act::PRelu(_) = act {+ self.fail(format!(+ "tensor {weight_index}: an int8 convolution cannot carry a PRelu, whose \+ per-channel slope would need the offset the scale occupies"+ ));+ }+ let per_group = in_shape.c.checked_div(group).unwrap_or(0);+ let weight = match self.weights.shaped_words(weight_index, &[m, per_group, kh, kw]) {+ Ok(offset) => {+ if let Some(slot) = self.read.get_mut(weight_index) {+ *slot = true;+ }+ offset+ }+ Err(e) => {+ self.fail(e);+ 0+ }+ };+ let scale = self.weight(weight_index + 1, &[1]);+ let bias = self.weight(weight_index + 2, &[m]);++ let (pad_t, pad_l, pad_b, pad_r) = pads;+ let out_h = conv_out(in_shape.h, kh, stride.0, dilation.0, pad_t + pad_b);+ let out_w = conv_out(in_shape.w, kw, stride.1, dilation.1, pad_l + pad_r);+ let out = self.tensor(Shape::new(m, out_h, out_w));+ self.nodes.push(Node::ConvInt8 {+ input,+ out,+ weight,+ scale,+ bias,+ kernel,+ stride,+ dilation,+ pad: (pad_t, pad_l),+ group,+ act,+ });+ out+ }+ /// Resolve [`Act::PRelu`]'s slope tensor, which is `[channels, 1, 1]` in the ONNX /// exports this reads. fn act_weight(&mut self, act: Act, channels: u32) -> u32 {@@ -1228,6 +1336,54 @@ impl<'a> Builder<'a> { ops: &mut Vec<Op>, ) -> Result<(), String> { match node {+ Node::ConvInt8 {+ input,+ out,+ weight,+ scale,+ bias,+ kernel,+ stride,+ dilation,+ pad,+ group,+ act,+ } => {+ let (si, so) = (shape(*input), shape(*out));+ ops.push(Op::Dispatch {+ kind: Kind::ConvInt8,+ push: Push {+ in0: at(*input)?,+ out: at(*out)?,+ // A word offset, not an fp16 one: int8 is unpacked through the+ // 32-bit view of the weights buffer.+ weight: *weight,+ bias: *bias,+ // The dequantisation scale rides in the field `PRelu` would use,+ // which is why the two cannot be combined.+ act_weight: *scale,+ in_c: si.c,+ in_h: si.h,+ in_w: si.w,+ out_c: so.c,+ out_h: so.h,+ out_w: so.w,+ kh: kernel.0,+ kw: kernel.1,+ stride_h: stride.0,+ stride_w: stride.1,+ dil_h: dilation.0,+ dil_w: dilation.1,+ pad_t: pad.0,+ pad_l: pad.1,+ group: *group,+ act: act.code(),+ count: so.len(),+ ..Push::default()+ },+ invocations: so.len(),+ });+ } Node::Conv { input, out,@@ -1657,6 +1813,7 @@ impl Node { | Node::GatedTanh { out, .. } | Node::FlipChannels { out, .. } | Node::SliceChannels { out, .. }+ | Node::ConvInt8 { out, .. } | Node::AttnApply { out, .. } | Node::Concat { out, .. } => *out, }@@ -1676,6 +1833,7 @@ impl Node { | Node::GatedTanh { input, .. } | Node::FlipChannels { input, .. } | Node::SliceChannels { input, .. }+ | Node::ConvInt8 { input, .. } | Node::GlobalAvgPool { input, .. } => vec![*input], Node::Binary { a, b, .. } => vec![*a, *b], Node::AttnScores { q: a, k: b, .. }@@ -1810,6 +1968,10 @@ pub(crate) mod tests { self.asked.borrow_mut().push((index, dims.to_vec())); Ok(index as u32) }+ fn shaped_words(&self, index: usize, dims: &[u32]) -> Result<u32, String> {+ self.asked.borrow_mut().push((index, dims.to_vec()));+ Ok(index as u32)+ } fn count(&self) -> usize { self.count@@ -1855,6 +2017,8 @@ pub(crate) mod tests { // One id per position, so the read is `out_w` and not `dense` — // `dense` here would be the *table's* row count. Kind::Embed => vec![(push.in0, push.out_w)],+ // As `Conv`: the whole input plane, whatever the kernel touches.+ Kind::ConvInt8 => vec![(push.in0, dense)], // Twice what it writes: the filter half and the gate half. Kind::GatedTanh => vec![(push.in0, written * 2)], _ => vec![(push.in0, dense)],@@ -1958,6 +2122,9 @@ pub(crate) mod tests { fn shaped(&self, index: usize, dims: &[u32]) -> Result<u32, String> { Err(format!("tensor {index} is not {dims:?}")) }+ fn shaped_words(&self, index: usize, dims: &[u32]) -> Result<u32, String> {+ Err(format!("tensor {index} is not {dims:?}"))+ } fn count(&self) -> usize { 2 }
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 2516f21773..a09785ccdf 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -191,6 +191,10 @@ impl Reference { Kind::AttnApplyRelative => self.attn_apply_relative(push), Kind::Embed => self.embed(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::ConvInt8 => Err("int8 convolution has no host reference".into()), Kind::FlipChannels => self.flip_channels(push), }, };@@ -853,6 +857,13 @@ impl Given { } impl WeightSource for Given {+ /// Int8 is not exercised by the host fixtures: the reference interpreter reads its+ /// weights as `f32`, so there is nothing for a byte view to be a view *of*. The int8+ /// path is checked against the export by `scripts/ml/onnx_parity.py` instead.+ fn shaped_words(&self, index: usize, _dims: &[u32]) -> Result<u32, String> {+ Err(format!("tensor {index}: this fixture holds no int8"))+ }+ fn shaped(&self, index: usize, dims: &[u32]) -> Result<u32, String> { let declared: u64 = dims.iter().map(|&d| d as u64).product(); let length = *self@@ -914,6 +925,11 @@ impl Invented { } impl WeightSource for Invented {+ /// As [`Given`]: int8 has nothing to mean here, since this fixture invents `f32`.+ fn shaped_words(&self, index: usize, _dims: &[u32]) -> Result<u32, String> {+ Err(format!("tensor {index}: this fixture invents fp32, not int8"))+ }+ fn shaped(&self, index: usize, dims: &[u32]) -> Result<u32, String> { let mut state = self.state.borrow_mut(); if let Some(Some(offset)) = state.offsets.get(index).copied() {
library/ml/src/main/rust/src/vulkan/pipeline.rs
diff --git a/library/ml/src/main/rust/src/vulkan/pipeline.rs b/library/ml/src/main/rust/src/vulkan/pipeline.rsindex 822286f876..ce61391bdd 100644--- a/library/ml/src/main/rust/src/vulkan/pipeline.rs+++ b/library/ml/src/main/rust/src/vulkan/pipeline.rs@@ -47,11 +47,12 @@ const ATTN_APPLY_RELATIVE: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/attn_apply_relative.comp.spv")); const EMBED: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/embed.comp.spv")); const GATED_TANH: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/gated_tanh.comp.spv"));+const CONV_INT8: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/conv_int8.comp.spv")); const FLIP_CHANNELS: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/flip_channels.comp.spv")); /// Every shader, in the order [`Pipelines::create`] destructures them.-const SPIRV: [&[u8]; 20] = [+const SPIRV: [&[u8]; 21] = [ CONV, CONV_TRANSPOSE, MAXPOOL,@@ -72,6 +73,7 @@ const SPIRV: [&[u8]; 20] = [ EMBED, GATED_TANH, FLIP_CHANNELS,+ CONV_INT8, ]; /// `local_size_x` in `shaders/common.glsl`. A dispatch covers `ceil(invocations / this)`@@ -115,6 +117,7 @@ pub struct Pipelines { embed: vk::Pipeline, gated_tanh: vk::Pipeline, flip_channels: vk::Pipeline,+ conv_int8: vk::Pipeline, } impl Pipelines {@@ -151,6 +154,13 @@ impl Pipelines { .descriptor_type(vk::DescriptorType::STORAGE_BUFFER) .descriptor_count(1) .stage_flags(vk::ShaderStageFlags::COMPUTE),+ // The weights again, viewed as 32-bit words so int8 tensors can be unpacked+ // without `VK_KHR_8bit_storage`. Same buffer as binding 1; see `common.glsl`.+ vk::DescriptorSetLayoutBinding::default()+ .binding(2)+ .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)+ .descriptor_count(1)+ .stage_flags(vk::ShaderStageFlags::COMPUTE), ]; let descriptor_layout = device .create_descriptor_set_layout(@@ -164,7 +174,7 @@ impl Pipelines { let pool_sizes = [vk::DescriptorPoolSize::default() .ty(vk::DescriptorType::STORAGE_BUFFER)- .descriptor_count(2)];+ .descriptor_count(3)]; let descriptor_pool = device .create_descriptor_pool( &vk::DescriptorPoolCreateInfo::default().max_sets(1).pool_sizes(&pool_sizes),@@ -205,6 +215,13 @@ impl Pipelines { .dst_binding(1) .descriptor_type(vk::DescriptorType::STORAGE_BUFFER) .buffer_info(std::slice::from_ref(&weights_info)),+ // Binding 2 is the same buffer as binding 1, viewed as 32-bit words so that int8+ // tensors can be unpacked. Both are read-only, so aliasing them is safe.+ vk::WriteDescriptorSet::default()+ .dst_set(descriptor_set)+ .dst_binding(2)+ .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)+ .buffer_info(std::slice::from_ref(&weights_info)), ]; device.update_descriptor_sets(&writes, &[]); @@ -257,6 +274,7 @@ impl Pipelines { embed, gated_tanh, flip_channels,+ conv_int8, ] = match <[vk::Pipeline; SPIRV.len()]>::try_from(built) { Ok(all) => all, Err(built) => {@@ -293,6 +311,7 @@ impl Pipelines { embed, gated_tanh, flip_channels,+ conv_int8, }) } @@ -319,6 +338,7 @@ impl Pipelines { Kind::Embed => self.embed, Kind::GatedTanh => self.gated_tanh, Kind::FlipChannels => self.flip_channels,+ Kind::ConvInt8 => self.conv_int8, } } @@ -347,6 +367,7 @@ impl Pipelines { self.embed, self.gated_tanh, self.flip_channels,+ self.conv_int8, ] { device.destroy_pipeline(pipeline, None); }
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 79f21fe181..02e3d3c05e 100644--- a/library/ml/src/main/rust/src/weights.rs+++ b/library/ml/src/main/rust/src/weights.rs@@ -22,6 +22,22 @@ const FORMAT_VERSION: u32 = 1; const HEADER_BYTES: usize = 64; const TENSOR_ENTRY_BYTES: usize = 32; const DTYPE_F16: u32 = 0;++/// Signed 8-bit, with a **separate** scale tensor beside it.+///+/// Used only where the weights dominate the download and fp16 would double it: SMaLL-100 is+/// 330 million parameters, which is 660 MB at fp16 and 330 MB here.+///+/// The quantisation is symmetric — zero point 0 — and the scale is per tensor, both read from+/// the export rather than assumed. So a value is `int8 * scale`, and because the scale is one+/// number for the whole tensor it multiplies the *accumulator* once rather than every tap. The+/// scale lives in its own fp16 tensor because a table entry is already 32 bytes with no room+/// for it, and a companion tensor needs no format version bump.+///+/// Activations stay fp16. The export quantises them too, dynamically, per tensor; not doing+/// that is both simpler and strictly more accurate, and it saves nothing to copy since the+/// weights are what take the space.+const DTYPE_I8: u32 = 1; /// Every tensor starts on this boundary, so an offset is a valid fp16 index too. const ALIGNMENT: u32 = 16; @@ -70,6 +86,8 @@ pub struct Tensor { pub offset: u32, /// Elements, not bytes. pub len: u32,+ /// True when the payload is [`DTYPE_I8`] rather than fp16, so one byte per element.+ pub int8: bool, } impl Tensor {@@ -77,6 +95,16 @@ impl Tensor { pub fn elem_offset(&self) -> u32 { self.offset / 2 }++ /// The offset as a 32-bit **word** index, which is how an int8 tensor is addressed.+ ///+ /// Int8 weights are read through a `uint` view of the same buffer and unpacked four at a+ /// time, because a byte view would need `VK_KHR_8bit_storage` — an extension on top of the+ /// fp16 one this runtime already requires, and every extra requirement narrows the fleet.+ /// `ALIGNMENT` is 16, so a tensor always starts on a word boundary.+ pub fn word_offset(&self) -> u32 {+ self.offset / 4+ } } /// A parsed `.maml` file: the tensor table, and the data section to upload.@@ -153,9 +181,11 @@ impl Weights { u32(bytes, at + 16), ]; let dtype = u32(bytes, at + 20);- if dtype != DTYPE_F16 {- return Err(format!("tensor {i} has dtype {dtype}, only fp16 is read"));- }+ let stride = match dtype {+ DTYPE_F16 => 2u64,+ DTYPE_I8 => 1,+ other => return Err(format!("tensor {i} has dtype {other}, expected fp16 or int8")),+ }; let offset = u32(bytes, at + 24); let len = u32(bytes, at + 28); @@ -166,13 +196,13 @@ impl Weights { if !offset.is_multiple_of(ALIGNMENT) { return Err(format!("tensor {i} is at {offset}, not {ALIGNMENT}-aligned")); }- let end = (offset as u64) + (len as u64) * 2;+ let end = (offset as u64) + (len as u64) * stride; if end > data_len as u64 { return Err(format!( "tensor {i} spans {offset}..{end} of a {data_len}-byte data section" )); }- tensors.push(Tensor { rank, dims, offset, len });+ tensors.push(Tensor { rank, dims, offset, len, int8: dtype == DTYPE_I8 }); } Ok(Weights {@@ -294,18 +324,96 @@ mod tests { assert_eq!(weights.len(), 2); assert_eq!( weights.tensor(0).expect("first"),- Tensor { rank: 4, dims: [2, 1, 1, 1], offset: 0, len: 2 }+ Tensor { rank: 4, dims: [2, 1, 1, 1], offset: 0, len: 2, int8: false } ); // Tensor 0 is 4 bytes but the next starts at 16: the alignment the shaders // rely on, and the arithmetic most likely to be got wrong. assert_eq!( weights.tensor(1).expect("second"),- Tensor { rank: 1, dims: [3, 0, 0, 0], offset: 16, len: 3 }+ Tensor { rank: 1, dims: [3, 0, 0, 0], offset: 16, len: 3, int8: false } ); assert_eq!(weights.tensor(1).expect("second").elem_offset(), 8); assert_eq!(weights.data().len(), 16 + 6); } + #[test]+ fn an_int8_tensor_reads_back_with_a_byte_stride_and_a_word_offset() {+ // Hand-built, because `write` above only emits fp16. One int8 tensor of five bytes,+ // then an fp16 scale after it — the layout `Builder::conv_int8` expects.+ let mut table = Vec::new();+ let mut data: Vec<u8> = Vec::new();+ // int8 [5], at offset 0.+ let payload: [i8; 5] = [-128, -1, 0, 1, 127];+ for (dtype, dims, len, bytes) in [+ (DTYPE_I8, [5u32, 0, 0, 0], 5u32, payload.iter().map(|&b| b as u8).collect::<Vec<u8>>()),+ (DTYPE_F16, [1u32, 0, 0, 0], 1u32, f32_to_f16(0.25).to_le_bytes().to_vec()),+ ] {+ 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(&1u32.to_le_bytes());+ for d in dims {+ table.extend_from_slice(&d.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::VITS_ENC.to_le_bytes());+ blob.extend_from_slice(&2u32.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);++ let weights = Weights::parse(&blob, graph::VITS_ENC).expect("parses");+ let quantised = weights.tensor(0).expect("the int8 tensor");+ assert!(quantised.int8);+ assert_eq!(quantised.len, 5);+ // Five elements at one byte each, so the *scale* still lands at 16: the alignment is+ // in bytes, not elements, and an int8 tensor must not be read with an fp16 stride.+ let scale = weights.tensor(1).expect("the scale");+ assert!(!scale.int8);+ assert_eq!(scale.offset, ALIGNMENT);+ // The shader addresses int8 through the 32-bit view, so offset 0 is word 0.+ assert_eq!(quantised.word_offset(), 0);+ assert_eq!(scale.elem_offset(), ALIGNMENT / 2);+ // And the payload survived: a five-byte tensor is not padded to an even length.+ assert_eq!(&weights.data()[0..5], &[0x80, 0xFF, 0x00, 0x01, 0x7F]);+ }++ #[test]+ fn an_unknown_dtype_is_refused() {+ let mut blob = Vec::new();+ blob.extend_from_slice(&MAGIC);+ blob.extend_from_slice(&FORMAT_VERSION.to_le_bytes());+ blob.extend_from_slice(&graph::SELFIE.to_le_bytes());+ blob.extend_from_slice(&1u32.to_le_bytes());+ blob.extend_from_slice(&[0u8; 32]);+ blob.extend_from_slice(&((HEADER_BYTES + TENSOR_ENTRY_BYTES) as u32).to_le_bytes());+ blob.extend_from_slice(&2u32.to_le_bytes());+ blob.extend_from_slice(&[0u8; 8]);+ blob.extend_from_slice(&1u32.to_le_bytes());+ for d in [1u32, 0, 0, 0] {+ blob.extend_from_slice(&d.to_le_bytes());+ }+ // A dtype nothing implements. Refusing beats reading it as whichever stride is+ // nearest and returning plausible rubbish.+ blob.extend_from_slice(&7u32.to_le_bytes());+ blob.extend_from_slice(&0u32.to_le_bytes());+ blob.extend_from_slice(&1u32.to_le_bytes());+ blob.extend_from_slice(&[0u8; 2]);+ let error = Weights::parse(&blob, graph::SELFIE).expect_err("dtype 7");+ assert!(error.contains("dtype 7"), "{error}");+ }+ #[test] fn a_file_for_another_graph_is_refused() { let bytes = write(graph::SELFIE, &[(vec![1], vec![1.0])]);
scripts/ml/maml_convert.py
diff --git a/scripts/ml/maml_convert.py b/scripts/ml/maml_convert.pyindex 09ba269f23..0a57254da3 100644--- a/scripts/ml/maml_convert.py+++ b/scripts/ml/maml_convert.py@@ -81,7 +81,16 @@ MAGIC = b"MAML" FORMAT_VERSION = 1 HEADER_BYTES = 64 TENSOR_ENTRY_BYTES = 32+# Tensor payload types. The container carries the type per tensor, so fp16 and int8 can sit in+# one file and a reader knows the stride without being told. DTYPE_F16 = 0++# Signed 8-bit, symmetric, with a per-tensor scale in the fp16 tensor that follows it.+#+# Only for a network where the weights dominate the download: SMaLL-100 is 330 million+# parameters, 660 MB at fp16 against 330 MB here, and the ncnn build of the same model shipped+# 1.14 GB. Everything else stays fp16, where the saving would not pay for the loss.+DTYPE_I8 = 1 # 16 bytes is the largest scalar/vector alignment the shaders index with, and a # multiple of 2, so an aligned tensor offset is also an aligned fp16 index. ALIGNMENT = 16@@ -602,8 +611,74 @@ def check_graph(model, graph_id_name): raise SystemExit(f"op counts differ: got {only_got}, expected {only_want}") +def quantised_linear(node, held, array, following_bias):+ """An int8 `MatMulInteger` as a `1 x 1` convolution, plus its scale and bias.++ Returns `(tensors, key)` or `None` if this is not one of the shapes we lower.++ # The transpose that would otherwise be silent++ ONNX `MatMul` computes `x @ W`, so its weight is **`[in, out]`**. This runtime indexes a+ kernel as `[out, in, kh, kw]`. SMaLL-100's attention projections are all 1024 x 1024, so a+ missed transpose would produce a tensor of exactly the right shape holding exactly the+ wrong numbers, and the parameter-count check every other net leans on would pass. `fc1` is+ `[1024, 4096]`, which is the one that would fail loudly - so the transpose is asserted+ against a non-square layer in the tests rather than trusted here.++ # What the export carries, and what is dropped++ 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 *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+ take the space.+ """+ if node.op_type != "MatMulInteger" or len(node.input) < 4:+ return None+ weight_name, zero_name = node.input[1], node.input[3]+ if not held(weight_name) or not held(zero_name):+ return None+ weight = array(weight_name)+ 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:+ 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"+ )+ 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:+ 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"+ )++ 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"zp=0 dtype=int8"+ )+ return [kernel, scale.astype(np.float32), bias], key++ def build(layers, tensors, graph_id, onnx_sha256):- """Serialise the tensor table and the fp16 data section."""+ """Serialise the tensor table and the data section.++ A tensor is fp16 unless it arrives as `int8`, in which case its bytes go through+ unchanged and the entry records [`DTYPE_I8`]. Its scale is a separate fp16 tensor that the+ caller has already placed after it.+ """ table = bytearray() data = bytearray() for tensor in tensors:@@ -612,17 +687,23 @@ def build(layers, tensors, graph_id, onnx_sha256): while len(data) % ALIGNMENT: data.append(0) offset = len(data)- half = np.ascontiguousarray(tensor, dtype=np.float32).astype(np.float16)- if not np.isfinite(half).all():- raise SystemExit(- f"a weight of shape {list(tensor.shape)} overflows fp16. "- "Storing this net at half precision needs per-tensor scaling."- )- data.extend(half.tobytes())+ if tensor.dtype == np.int8:+ # Already quantised, so nothing to round: the bytes are the payload.+ dtype = DTYPE_I8+ data.extend(tensor.tobytes())+ else:+ dtype = DTYPE_F16+ half = np.ascontiguousarray(tensor, dtype=np.float32).astype(np.float16)+ if not np.isfinite(half).all():+ raise SystemExit(+ f"a weight of shape {list(tensor.shape)} overflows fp16. "+ "Storing this net at half precision needs per-tensor scaling."+ )+ data.extend(half.tobytes()) dims = list(tensor.shape) + [0] * (4 - tensor.ndim) table.extend(struct.pack("<I", tensor.ndim)) table.extend(struct.pack("<4I", *dims))- table.extend(struct.pack("<III", DTYPE_F16, offset, tensor.size))+ table.extend(struct.pack("<III", dtype, offset, tensor.size)) assert len(table) == len(tensors) * TENSOR_ENTRY_BYTES data_offset = HEADER_BYTES + len(table)