Modern Apps git

← Modern-Apps.git

library:ml: quantise the vocoder to int8, 50.7 to 28.7 MB

Commit
b29c6b145e423563f60c401bc18a154d1f9646fd
Author
vayun-mathur <[email protected]>
When
2026-08-29 00:36 UTC (3 months ago)
Parents
b729434

Diff

library/ml/src/main/rust/src/nets/supertonic_text.rs
diff --git a/library/ml/src/main/rust/src/nets/supertonic_text.rs b/library/ml/src/main/rust/src/nets/supertonic_text.rsindex b9ec20937c..7fb5da359a 100644--- a/library/ml/src/main/rust/src/nets/supertonic_text.rs+++ b/library/ml/src/main/rust/src/nets/supertonic_text.rs@@ -118,7 +118,25 @@ const EPSILON: f32 = 1e-5; /// /// The embedding table (1), six blocks of eight (48), four attention layers of eighteen (72), /// two style attentions of seven (14) and the final layer norm (2). The seven are `W_query`,-/// the folded constant keys, `W_value` and `out_fc` โ€” a pair each except the keys.+/// the folded constant keys, `W_value` and `out_fc` - a pair each except the keys.+///+/// # This net stays fp16, and it was measured rather than assumed+///+/// Every other Supertonic net quantises its ungrouped `1 x 1`s to int8. This one was converted the+/// same way and reverted, because the trade is bad at both ends:+///+/// * **It costs the most accuracy of the four.** `onnx_parity.py` against this export: fp16+///   correlates at 0.99900 and int8 at 0.99212, below the 0.999 the other three clear comfortably.+///   The cause is depth, not a bug - a per-tensor round trip of all 66 quantised kernels put every+///   one at ~0.0042 worst-row relative error against the 0.00394 an absmax int8 quantiser can+///   achieve, so no layer is pathological. Twelve sequential stages each losing 0.4% is simply what+///   compounding looks like.+/// * **It saves the least size.** 17.8 MB to 11.1 MB, so 6.6 MB of a 198 MB bundle. The sampler and+///   the vocoder are 178 MB of that 198 and carry the same proportion of quantisable weight.+///+/// Dropping it still leaves the bundle under its target, so there is nothing to buy with the+/// accuracy. Revisit only if a per-channel *activation* scale ever lands, which is what would stop+/// the error compounding. pub const TENSORS: usize = 137;  /// Hands out `.maml` tensor indices in the order the layers appear.
library/ml/src/main/rust/src/nets/supertonic_vocoder.rs
diff --git a/library/ml/src/main/rust/src/nets/supertonic_vocoder.rs b/library/ml/src/main/rust/src/nets/supertonic_vocoder.rsindex 9e0f8de060..07af017e2f 100644--- a/library/ml/src/main/rust/src/nets/supertonic_vocoder.rs+++ b/library/ml/src/main/rust/src/nets/supertonic_vocoder.rs@@ -84,8 +84,36 @@ const EPSILON: f32 = 1e-5; /// Tensors the `.maml` must hold. /// /// `embed` (2), ten blocks of eight, `head/layer1` (2), its PReLU slope (1) and `head/layer2`-/// (2, the second a synthesised zero bias): `2 + 80 + 2 + 1 + 2`.-pub const TENSORS: usize = 87;+/// (2, the second a synthesised zero bias): `2 + 80 + 2 + 1 + 2` โ€” 87 at fp16 โ€” plus one per+/// quantised convolution for its scale. See [`INT8_CONVS`].+pub const TENSORS: usize = 87 + INT8_CONVS;++/// Convolutions read as int8 rather than fp16, each carrying a third tensor for its scale.+///+/// Each block's two `1 x 1`s and `head/layer2`. That is 87% of this net's parameters, and the three+/// exclusions are all forced by the runtime rather than chosen:+///+/// * the ten **depthwise** convolutions along the sequence are grouped and causally padded, and+///   `conv_int8.comp` neither groups a tiled kernel nor replicates a border.+/// * **`embed`** is padded too, and it carries the input's per-channel affine folded in by+///   `supertonic_fold.py`. That fold scales per *input* channel, a range that varies within an+///   output row, which is exactly what a per-output-channel scale cannot absorb.+/// * **`head/layer1`** is padded *and* carries [`Act::PRelu`], whose per-channel slope wants the+///   push offset the dequantisation scale occupies.+///+/// # `head/layer2` is included, and that was checked rather than assumed+///+/// It writes the waveform, so unlike every other layer here its quantisation error reaches the+/// samples with nothing downstream to average it - a reason to expect it to dominate. Measured, it+/// does not: holding it at fp16 moves `onnx_parity.py`'s correlation from 0.99909 to 0.99917 and the+/// worst sample error from 0.0319 to 0.0311, for 1 MB. The error is spread across the twenty block+/// projections instead, which are 83% of the parameters, so there is no cheap subset to give up.+///+/// That makes the accuracy question for this net a single yes-or-no: 21 MB at 0.99909, or fp16 at+/// 0.99999858. The correlation clears the 0.999 bar the conversion was gated on, but it implies+/// roughly -27 dB of error against fp16's -55 dB, and whether that is audible in a vocoder is not+/// something a correlation can answer. A device listening test is the real gate.+pub const INT8_CONVS: usize = BLOCKS * 2 + 1;  /// Hands out `.maml` tensor indices in the order the layers appear. struct Layers {@@ -99,6 +127,15 @@ impl Layers {         index     } +    /// An int8 kernel, its per-output-channel scale, and the bias after that.+    ///+    /// See `supertonic_duration::Layers::take3`; the order is what `Builder::conv_int8` reads.+    fn take3(&mut self) -> usize {+        let index = self.next;+        self.next += 3;+        index+    }+     fn take_one(&mut self) -> usize {         let index = self.next;         self.next += 1;@@ -187,9 +224,9 @@ pub fn build(weights: &dyn WeightSource, frames: u32) -> Result<Plan, String> {             },         );         let normed = b.layer_norm(depthwise, l.take(), EPSILON);-        let widened = point(b, l, normed, INNER, Act::Gelu);+        let widened = point_int8(b, l, normed, INNER, Act::Gelu);         // `pwconv2` carries the block's layer scale, folded in by the converter.-        let narrowed = point(b, l, widened, CHANNELS, Act::None);+        let narrowed = point_int8(b, l, widened, CHANNELS, Act::None);         x = b.add(x, narrowed);     } @@ -203,7 +240,7 @@ pub fn build(weights: &dyn WeightSource, frames: u32) -> Result<Plan, String> {         Along { out: INNER, kernel: 3, dilation: 1, group: 1, act: Act::PRelu(slope) },     );     l.take_one();-    let samples = point(b, l, widened, SAMPLES_PER_POSITION, Act::None);+    let samples = point_int8(b, l, widened, SAMPLES_PER_POSITION, Act::None);      if l.next != TENSORS {         return Err(format!("the forward pass claims {} tensors, not {TENSORS}", l.next));@@ -250,9 +287,11 @@ fn along(b: &mut Builder, l: &mut Layers, x: Id, shape: Along) -> Id {     ) } -/// A `1 x 1` convolution, which the tiled shader serves.-fn point(b: &mut Builder, l: &mut Layers, x: Id, out: u32, act: Act) -> Id {-    b.conv(x, l.take(), out, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 1, act)+/// A `1 x 1` convolution with an int8 kernel, which is every `1 x 1` in this net. See+/// [`INT8_CONVS`], and note there is no fp16 counterpart here because nothing needs one: the+/// convolutions that cannot be quantised are all spatial and go through [`along`].+fn point_int8(b: &mut Builder, l: &mut Layers, x: Id, out: u32, act: Act) -> Id {+    b.conv_int8(x, l.take3(), out, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 1, act) }  #[cfg(test)]@@ -344,9 +383,13 @@ mod tests {             .iter()             .map(|(_, dims)| dims.iter().map(|&d| d as u64).product::<u64>())             .sum();-        assert_eq!(total, 25_333_249 - 2_048 + 2_048 - 1 + 512);+        // Each quantised convolution gains an `[out]` dequantisation scale: `pwconv1` is `INNER`+        // wide, `pwconv2` is `CHANNELS`, and `head/layer2` is its sample count.+        let scales = (BLOCKS as u64) * (INNER + CHANNELS) as u64 + SAMPLES_PER_POSITION as u64;+        assert_eq!(scales, 26_112);+        assert_eq!(total, 25_333_249 - 2_048 + 2_048 - 1 + 512 + scales);         // And spelled out, so a reordering that preserved the sum would still be caught.-        assert_eq!(total, 25_333_760);+        assert_eq!(total, 25_359_872);     }      #[test]@@ -426,13 +469,16 @@ mod tests {                 *counts.entry(super::super::tests::name_of(*kind)).or_insert(0) += 1;             }         }-        // embed, ten depthwise, head/layer1, ten pwconv1, ten pwconv2, head/layer2.-        assert_eq!(counts.get("Conv"), Some(&(1 + BLOCKS + 1 + BLOCKS * 2 + 1)), "{counts:?}");+        // embed, ten depthwise, head/layer1, ten pwconv1, ten pwconv2, head/layer2. The two 1x1s+        // per block and head/layer2 are quantised - see `INT8_CONVS`.+        let convolutions = 1 + BLOCKS + 1 + BLOCKS * 2 + 1;+        assert_eq!(counts.get("Conv"), Some(&(convolutions - INT8_CONVS)), "{counts:?}");+        assert_eq!(counts.get("ConvInt8"), Some(&INT8_CONVS), "{counts:?}");         assert_eq!(counts.get("LayerNorm"), Some(&BLOCKS), "{counts:?}");         assert_eq!(counts.get("Add"), Some(&BLOCKS), "{counts:?}");         // No transposed convolution: the upsample is the output reinterpretation.         assert_eq!(counts.get("ConvTranspose"), None, "{counts:?}");-        assert_eq!(counts.len(), 3, "{counts:?}");+        assert_eq!(counts.len(), 4, "{counts:?}");     }      #[test]
scripts/ml/maml_convert.py
diff --git a/scripts/ml/maml_convert.py b/scripts/ml/maml_convert.pyindex a55f333b0b..48b312bc36 100644--- a/scripts/ml/maml_convert.py+++ b/scripts/ml/maml_convert.py@@ -126,7 +126,7 @@ EXPECTED_DIGEST = {     "mobilefacenet": "40987839aec03378958581deba29ce9fd9dd1ae9aa88d0c7ad04a885a2e2122c",     "ppocr_det": "51b0c9ed871526fa270b4bfa53b393c056db21c58193849fb83d44768f69ef9b",     "ppocr_rec": "8c16a8702aa7a1e7b4d94787d089616ca4bc3d8aaeebb0b0159eabc56af3ba08",-    "supertonic_voc": "64e3a3437fa8f889fb679a5e08553ba7392c05a32cd844a0d2340698372a0071",+    "supertonic_voc": "5282083898554b1fae28de946bfc1a82a11e2acddf3911877f27b1b115c583aa",     "supertonic_dp": "d9a548e1f1ed908a3b0ad27ab543dd7521858f9110b426edb1ed64ba1f1a13e4",     "supertonic_ttl": "92d0fa8ae73d4a8a223c77fb4230e390df580744014a3fcf3211ab72a988c020",     "supertonic_ve": "d76f1fb13eaa9f5a16fed1f97a491d25f75325a36f00535fa3a11a7b16527951",
scripts/ml/supertonic_fold.py
diff --git a/scripts/ml/supertonic_fold.py b/scripts/ml/supertonic_fold.pyindex a4d13f2b5f..72c8e57bea 100644--- a/scripts/ml/supertonic_fold.py+++ b/scripts/ml/supertonic_fold.py@@ -251,8 +251,18 @@ def collect(graph):     layers, tensors = [], []     scales = iter(layer_scales) -    def add(op, name, weight, bias, key):+    def add(op, name, weight, bias, key, int8=False):         first = len(tensors)+        if int8:+            # The three-tensor layout `Builder::conv_int8` reads: kernel, per-output-channel+            # scale, bias. `Table.conv` emits the same thing for the other graphs; this one+            # cannot use it because it walks ONNX nodes rather than named parameters.+            quantised, kernel_scale = maml_convert.quantise_per_channel(weight)+            tensors.append(quantised)+            tensors.append(np.ascontiguousarray(kernel_scale, dtype=np.float32))+            tensors.append(np.ascontiguousarray(bias, dtype=np.float32))+            layers.append(maml_convert.Layer(len(layers), op, name, key, first, 3))+            return         tensors.append(np.ascontiguousarray(weight, dtype=np.float32))         tensors.append(np.ascontiguousarray(bias, dtype=np.float32))         layers.append(maml_convert.Layer(len(layers), op, name, key, first, 2))@@ -298,11 +308,22 @@ def collect(graph):         for attribute in node.attribute:             if attribute.name == "group":                 group = attribute.i+        # The two `1 x 1`s per block and `head/layer2` are read as int8; `embed`, the depthwise+        # convolutions and `head/layer1` cannot be. See `nets::supertonic_vocoder::INT8_CONVS`,+        # which spells out why for each, and must agree with this list.+        int8 = any(+            marker in node.name for marker in ("pwconv1", "pwconv2", "head/layer2")+        )+        if int8 and (group != 1 or tuple(lifted.shape[2:]) != (1, 1)):+            raise SystemExit(+                f"{node.name}: marked int8 but it is g={group} k={list(lifted.shape[2:])};"+                " only an ungrouped 1x1 can be quantised"+            )         key = (-            f"Conv w={list(lifted.shape)} b={list(bias.shape)} g={group}"-            f" pad=edge{note}"+            f"{'ConvInt8' if int8 else 'Conv'} w={list(lifted.shape)} b={list(bias.shape)}"+            f" g={group} pad=edge{note}{' zp=0 dtype=int8' if int8 else ''}"         )-        add("Conv", node.name, lifted, bias, key)+        add("ConvInt8" if int8 else "Conv", node.name, lifted, bias, key, int8=int8)          # The PReLU sits between the two head convolutions, and its slope is one tensor.         if "head/layer1" in node.name: