Modern Apps git

← Modern-Apps.git

library:ml: quantise the duration predictor to int8, 1.73 to 1.44 MB

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

Diff

library/ml/src/main/rust/src/nets/supertonic_duration.rs
diff --git a/library/ml/src/main/rust/src/nets/supertonic_duration.rs b/library/ml/src/main/rust/src/nets/supertonic_duration.rsindex 2a1d013abd..b52c089604 100644--- a/library/ml/src/main/rust/src/nets/supertonic_duration.rs+++ b/library/ml/src/main/rust/src/nets/supertonic_duration.rs@@ -101,8 +101,28 @@ const EPSILON: f32 = 1e-5; /// /// The embedding table (1), six blocks of eight (48), two attention layers of eighteen (36), /// `proj_out` (2, the second a synthesised zero bias), the head's first `Gemm` (2), its PReLU-/// slope (1) and its second `Gemm` (2).-pub const TENSORS: usize = 92;+/// slope (1) and its second `Gemm` (2) — 92 at fp16 — plus one per quantised convolution for its+/// scale. See [`INT8_CONVS`].+pub const TENSORS: usize = 92 + INT8_CONVS;++/// Convolutions read as int8 rather than fp16, each carrying a third tensor for its scale.+///+/// Every ungrouped `1 x 1` in the blocks and the attention layers: two per block (`pwconv1` and+/// `pwconv2`) and six per attention layer (q, k, v, the output projection and the two+/// feed-forward projections).+///+/// Three of this net's `1 x 1`s are **not** here, and each for a reason the runtime enforces rather+/// than a judgement call:+///+/// * `proj_out` is strided by the whole sequence, and the tiled int8 shader is stride-1 only.+/// * the head's first `Gemm` carries [`Act::PRelu`], whose per-channel slope wants the same push+///   offset the dequantisation scale occupies — `Builder::conv_int8` refuses it.+/// * the head's second `Gemm` is 128 to 1, so quantising it would save 128 bytes while putting the+///   single value this net exists to produce through a coarser weight.+///+/// That leaves 34% of the parameters quantised. The cap is the embedding table, which is 61% of+/// this net on its own and has no int8 path — `embed.comp` is fp16 only.+pub const INT8_CONVS: usize = BLOCKS * 2 + ATTN_LAYERS * 6;  /// Latent frames for an utterance of `seconds`, which is what the sampler and the vocoder are /// built for.@@ -135,6 +155,18 @@ impl Layers {         index     } +    /// An int8 kernel, its per-output-channel scale, and the bias after that.+    ///+    /// Three rather than two, which is why quantising a convolution shifts every later index. The+    /// order is the one `Builder::conv_int8` reads and `supertonic_fold.py` writes; getting it+    /// wrong puts an fp16 tensor where the kernel should be, and `WeightSource::shaped_words`+    /// refuses that rather than reading it as bytes.+    fn take3(&mut self) -> usize {+        let index = self.next;+        self.next += 3;+        index+    }+     /// A lone tensor: the embedding table, a relative position table, a PReLU slope.     fn take_one(&mut self) -> usize {         let index = self.next;@@ -148,6 +180,11 @@ 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) } +/// [`point`] with an int8 kernel. See [`INT8_CONVS`] for which convolutions get one.+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)+}+ /// The depthwise convolution along the sequence, padded symmetrically so the length holds. fn depthwise(b: &mut Builder, l: &mut Layers, x: Id) -> Id {     let each = (KERNEL - 1) / 2;@@ -193,29 +230,29 @@ pub fn build(weights: &dyn WeightSource, chars: u32) -> Result<Plan, String> {     for _ in 0..BLOCKS {         let along = depthwise(b, l, x);         let normed = b.layer_norm(along, 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, D_MODEL, Act::None);+        let narrowed = point_int8(b, l, widened, D_MODEL, Act::None);         x = b.add(x, narrowed);     }     // The attention encoder is skipped around as a whole, not just per layer.     let convnext = x;      for _ in 0..ATTN_LAYERS {-        let q = point(b, l, x, D_MODEL, Act::None);-        let k = point(b, l, x, D_MODEL, Act::None);-        let v = point(b, l, x, D_MODEL, Act::None);+        let q = point_int8(b, l, x, D_MODEL, Act::None);+        let k = point_int8(b, l, x, D_MODEL, Act::None);+        let v = point_int8(b, l, x, D_MODEL, Act::None);         let scores = b.attn_scores_relative(q, k, HEADS, l.take_one(), OFFSETS);         let probs = b.softmax(scores);         let mixed = b.attn_apply_relative(probs, v, HEADS, l.take_one(), OFFSETS);-        let attended = point(b, l, mixed, D_MODEL, Act::None);+        let attended = point_int8(b, l, mixed, D_MODEL, Act::None);         // Post-norm: the residual is added first and normalised after.         let residual = b.add(x, attended);         x = b.layer_norm(residual, l.take(), EPSILON);          // Both feed-forward convolutions are 1x1 here, so neither has a border.-        let inner = point(b, l, x, INNER, Act::Relu);-        let projected = point(b, l, inner, D_MODEL, Act::None);+        let inner = point_int8(b, l, x, INNER, Act::Relu);+        let projected = point_int8(b, l, inner, D_MODEL, Act::None);         let residual = b.add(x, projected);         x = b.layer_norm(residual, l.take(), EPSILON);     }@@ -276,12 +313,13 @@ mod tests {      #[test]     fn the_tensor_table_matches_the_export() {-        // The export's initializers total 864,706 parameters. Three differences, each derived+        // The export's initializers total 864,706 parameters. Four differences, each derived         // rather than guessed:         //         //   - the six `[1, 64, 1]` layer scales fold into their `pwconv2`:        -384         //   - `proj_out` has no bias in the export, so a zero one is synthesised:  +64         //   - the head PReLU's single shared slope is widened to one per channel: +127+        //   - each quantised convolution gains an `[out]` dequantisation scale:  +3072         //         // `sentence_token` is not a difference: its 64 values move from a standalone tensor         // into the embedding table's last row, so the total is unchanged either way.@@ -292,9 +330,15 @@ mod tests {             .iter()             .map(|(_, dims)| dims.iter().map(|&d| d as u64).product::<u64>())             .sum();-        assert_eq!(total, 864_706 - 384 + 64 + 127);+        // The scales, spelled out per shape so a miscount is visible rather than absorbed:+        // `pwconv1` and both feed-forwards' first stage are `INNER` wide, everything else+        // `D_MODEL`.+        let scales = (BLOCKS as u64) * (INNER + D_MODEL) as u64+            + (ATTN_LAYERS as u64) * (4 * D_MODEL + INNER + D_MODEL) as u64;+        assert_eq!(scales, 3072);+        assert_eq!(total, 864_706 - 384 + 64 + 127 + scales);         // And spelled out, so a reordering that preserved the sum would still be caught.-        assert_eq!(total, 864_513);+        assert_eq!(total, 867_585);     }      #[test]@@ -407,9 +451,11 @@ mod tests {             }         }         // Per block a depthwise and two 1x1s; per attention layer q/k/v/o and two-        // feed-forward 1x1s; then `proj_out` and the head's two `Gemm`s.+        // feed-forward 1x1s; then `proj_out` and the head's two `Gemm`s. All but the depthwise+        // ones, `proj_out` and the head are quantised - see `INT8_CONVS`.         let convolutions = BLOCKS * 3 + ATTN_LAYERS * 6 + 3;-        assert_eq!(counts.get("Conv"), Some(&convolutions), "{counts:?}");+        assert_eq!(counts.get("Conv"), Some(&(convolutions - INT8_CONVS)), "{counts:?}");+        assert_eq!(counts.get("ConvInt8"), Some(&INT8_CONVS), "{counts:?}");         assert_eq!(counts.get("Embed"), Some(&1), "{counts:?}");         assert_eq!(counts.get("AttnScoresRelative"), Some(&ATTN_LAYERS), "{counts:?}");         assert_eq!(counts.get("AttnApplyRelative"), Some(&ATTN_LAYERS), "{counts:?}");@@ -422,7 +468,7 @@ mod tests {         // sentence. A `GlobalAvgPool` here would be the wrong model producing a plausible         // number.         assert_eq!(counts.get("GlobalAvgPool"), None, "{counts:?}");-        assert_eq!(counts.len(), 7, "{counts:?}");+        assert_eq!(counts.len(), 8, "{counts:?}");     }      #[test]
scripts/ml/maml_convert.py
diff --git a/scripts/ml/maml_convert.py b/scripts/ml/maml_convert.pyindex cba2b2b7b2..a55f333b0b 100644--- a/scripts/ml/maml_convert.py+++ b/scripts/ml/maml_convert.py@@ -127,7 +127,7 @@ EXPECTED_DIGEST = {     "ppocr_det": "51b0c9ed871526fa270b4bfa53b393c056db21c58193849fb83d44768f69ef9b",     "ppocr_rec": "8c16a8702aa7a1e7b4d94787d089616ca4bc3d8aaeebb0b0159eabc56af3ba08",     "supertonic_voc": "64e3a3437fa8f889fb679a5e08553ba7392c05a32cd844a0d2340698372a0071",-    "supertonic_dp": "a294dac3e0fa1acf03d5a483b96782190a626c6adbc517969592ec6a888e15cd",+    "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 7dfcf064c0..a4d13f2b5f 100644--- a/scripts/ml/supertonic_fold.py+++ b/scripts/ml/supertonic_fold.py@@ -442,11 +442,15 @@ class Table:             beta,         ) -    def convnext(self, at, channels, inner, dilation):+    def convnext(self, at, channels, inner, dilation, int8=False):         """One ConvNeXt block: depthwise, norm, widening 1x1, narrowing 1x1 with the gamma.          Symmetric padding, `2 * dilation` each side. The vocoder's is causal instead, and that         difference cost real debugging time once already.++        `int8` quantises the two `1 x 1`s and not the depthwise one, which is the only split the+        shaders allow: `conv_int8.comp` zero-pads where this block replicates, and a 5-tap depthwise+        has a border to get wrong where a `1 x 1` has none.         """         each = dilation * 4 // 2         self.conv(@@ -457,25 +461,35 @@ class Table:             group=channels,         )         self.layer_norm(f"{at}.norm.norm")-        self.conv(f"{at}.pwconv1", inner)+        self.conv(f"{at}.pwconv1", inner, int8=int8)         # The block's gamma rides on `pwconv2`, which is a 1x1 and so has no border.-        self.conv(f"{at}.pwconv2", channels, fold_scale=self.at(f"{at}.gamma").reshape(-1))+        self.conv(+            f"{at}.pwconv2",+            channels,+            fold_scale=self.at(f"{at}.gamma").reshape(-1),+            int8=int8,+        ) -    def relative_attention(self, at, layer, channels, inner, head_dim):-        """One post-norm relative-attention layer, in the order the export declares it."""+    def relative_attention(self, at, layer, channels, inner, head_dim, int8=False):+        """One post-norm relative-attention layer, in the order the export declares it.++        `int8` quantises all six convolutions - every one is an ungrouped `1 x 1`. The two relative+        position tables stay fp16: they are read by `attn_scores_relative.comp` rather than by a+        convolution, and there is no int8 path through it.+        """         attn = f"{at}.attn_layers.{layer}"         for projection in ("conv_q", "conv_k", "conv_v"):-            self.conv(f"{attn}.{projection}", channels)+            self.conv(f"{attn}.{projection}", channels, int8=int8)         # `[1, 9, head_dim]` in the export; the Rust reads `[offsets, head_dim]`.         for table_name in ("emb_rel_k", "emb_rel_v"):             relative = self.at(f"{attn}.{table_name}").reshape(9, -1)             if relative.shape[1] != head_dim:                 raise SystemExit(f"{attn}.{table_name} is {list(relative.shape)}, not [9, {head_dim}]")             self.add("RelPos", f"{attn}.{table_name}", f"RelPos t={list(relative.shape)}", relative)-        self.conv(f"{attn}.conv_o", channels)+        self.conv(f"{attn}.conv_o", channels, int8=int8)         self.layer_norm(f"{at}.norm_layers_1.{layer}.norm")-        self.conv(f"{at}.ffn_layers.{layer}.conv_1", inner)-        self.conv(f"{at}.ffn_layers.{layer}.conv_2", channels)+        self.conv(f"{at}.ffn_layers.{layer}.conv_1", inner, int8=int8)+        self.conv(f"{at}.ffn_layers.{layer}.conv_2", channels, int8=int8)         self.layer_norm(f"{at}.norm_layers_2.{layer}.norm")  @@ -502,9 +516,11 @@ def collect_duration(graph):     )      for block in range(DP_BLOCKS):-        table.convnext(f"{DP_PREFIX}.convnext.convnext.{block}", DP_CHANNELS, DP_INNER, 1)+        table.convnext(f"{DP_PREFIX}.convnext.convnext.{block}", DP_CHANNELS, DP_INNER, 1, int8=True)     for layer in range(DP_ATTN_LAYERS):-        table.relative_attention(f"{DP_PREFIX}.attn_encoder", layer, DP_CHANNELS, DP_INNER, 32)+        table.relative_attention(+            f"{DP_PREFIX}.attn_encoder", layer, DP_CHANNELS, DP_INNER, 32, int8=True+        )      # `proj_out` has no bias in the export; the Rust reads a pair for every convolution.     table.conv(f"{DP_PREFIX}.proj_out.net", DP_CHANNELS, synthesise_bias=True)