library:ml: quantise the sampler to int8, 127.6 to 64.5 MB
- Commit
baa012aa68adf8f461698489e592babb38a9a118- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-29 00:42 UTC (3 months ago)
- Parents
b29c6b1
Diff
.gitignore
diff --git a/.gitignore b/.gitignoreindex 15d626557c..c5d68d672e 100644--- a/.gitignore+++ b/.gitignore@@ -65,11 +65,11 @@ health/src/main/assets/staging.db # every listing image twice. Remove this ignore if you ever want # `validate<Variant>ScreenshotTest` to act as UI regression testing. **/src/screenshotTest*/reference/-# Supertonic 3's TTS bundle - 189 MiB of fp16 .maml plus its codepoint table and ten voice+# Supertonic 3's TTS bundle - 107 MiB of mostly-int8 .maml plus its codepoint table and ten voice # styles. Rebuild byte for byte with `python scripts/ml/fetch_supertonic.py`, which pins the # upstream revision and every ONNX SHA-256. Ignored for the same reason as the two above: it is # the largest asset in the tree, it is derived rather than authored, and committing it would put-# it in history permanently - including the fp16 blobs that an int8 conversion would supersede.+# it in history permanently. # # Consequence worth knowing: a fresh checkout builds a :speech APK with **no voices**, and the # TTS engine then advertises no languages (SupertonicBundle.isPresent is false) rather than
SUPPLY_CHAIN_RISKS.md
diff --git a/SUPPLY_CHAIN_RISKS.md b/SUPPLY_CHAIN_RISKS.mdindex 5a06577058..c8bdcf3d30 100644--- a/SUPPLY_CHAIN_RISKS.md+++ b/SUPPLY_CHAIN_RISKS.md@@ -55,7 +55,9 @@ These servers provide data/functionality that is NOT intrinsically tied to a sin Two things about this one are unlike every other model here. **Its licence is use-restricted**: Supertonic 3 is **OpenRAIL**, the first such licence in this tree - everything else is Apache-2.0, MIT, ODbL or InsightFace's non-commercial research terms. And because it is bundled rather than downloaded, the restriction ships in the APK rather than being fetched by a user who went looking for it. It is a **build-host** dependency and no runtime dependency at all: upstream is **`Supertone/supertonic-3`** on HuggingFace, pinned to revision `3cadd1ee` with all four ONNX SHA-256s in `scripts/ml/fetch_supertonic.py`, which fetches it and drives both converters. The ONNX is not vendored - it is 398 MB against the 189 MiB of fp16 `.maml` it becomes, and nothing reads it at run time. The `.maml` are not committed either, for the reason `/.gitignore` gives, so `fetch_supertonic.py` is the only record of where the weights came from and the only way to rebuild them. - Two independent checks guard a bad rebuild, and they fail for different reasons: the pinned file SHA-256s catch a re-export or a truncated download, and each converter's layer-table digest in `maml_convert.EXPECTED_DIGEST` catches an export whose *structure* moved - which is what would make the hardcoded Rust forward passes read the right shapes holding the wrong numbers. Neither checks the numbers; `scripts/ml/onnx_parity.py` does, and at the pinned revision all four nets correlate with onnxruntime above 0.999.+ Two independent checks guard a bad rebuild, and they fail for different reasons: the pinned file SHA-256s catch a re-export or a truncated download, and each converter's layer-table digest in `maml_convert.EXPECTED_DIGEST` catches an export whose *structure* moved - which is what would make the hardcoded Rust forward passes read the right shapes holding the wrong numbers. Neither checks the numbers; `scripts/ml/onnx_parity.py` does, and its correlations against onnxruntime are recorded in the README beside the assets.++ The bundle is **107 MiB**, not the 198 MB the fp32 export folds to at fp16: every ungrouped `1 x 1` convolution in the sampler, the vocoder and the duration predictor is stored as int8 with one fp16 scale per output channel. That is 92% of the sampler's parameters and 87% of the vocoder's. The text encoder stays fp16 - quantising it cost more correlation than the other three combined and saved 6.6 MB of 198, so it was measured and reverted. With Whisper's 74.3 MiB, `:speech` ships 181.9 MiB of assets. The language coverage is a deliberate regression as well as a gain: 42 languages became 31. TTS was **lost** for Chinese, Hebrew, Thai, Bengali, Telugu, Malayalam, Marathi, Urdu, Serbian, Norwegian, Catalan, Georgian, Kurdish, Luxembourgish, Nepali and Swahili, and **gained** for Estonian, Croatian, Lithuanian, Latvian and Slovenian. The dropped languages are absent from the engine's advertised voice list, so a user is never offered one that would be silent.
library/ml/src/main/rust/src/nets/supertonic_sampler.rs
diff --git a/library/ml/src/main/rust/src/nets/supertonic_sampler.rs b/library/ml/src/main/rust/src/nets/supertonic_sampler.rsindex 99ec44b7c7..27301c4693 100644--- a/library/ml/src/main/rust/src/nets/supertonic_sampler.rs+++ b/library/ml/src/main/rust/src/nets/supertonic_sampler.rs@@ -138,13 +138,29 @@ pub const FREQUENCIES: u32 = 32; /// The guidance scale the export bakes in: `v = 4 * conditional - 3 * unconditional`. pub const GUIDANCE: f32 = 4.0; -/// Tensors the plan itself reads: `proj_in`, 28 ConvNeXt blocks of eight, four main blocks'-/// conditioning, and `proj_out`.-pub const PLAN_TENSORS: usize = 2 + BLOCKS * 8 + MAIN_BLOCKS * 18 + 2;+/// Tensors the plan itself reads: `proj_in`, 28 ConvNeXt blocks, four main blocks' conditioning,+/// and `proj_out`.+///+/// Ten per block rather than eight, and 25 per main block rather than 18, because every ungrouped+/// `1 x 1` here is int8 and carries a scale beside its kernel. See [`INT8_CONVS`].+pub const PLAN_TENSORS: usize = 3 + BLOCKS * 10 + MAIN_BLOCKS * 25 + 3; /// Tensors the `.maml` must hold: the plan's, then the host's eighteen. pub const TENSORS: usize = PLAN_TENSORS + 18; +/// Convolutions read as int8 rather than fp16, each carrying a third tensor for its scale.+///+/// **Every `1 x 1` in this net**: both projections, both `1 x 1`s of all 28 ConvNeXt blocks, and all+/// seven attention projections of each main block. Only the 28 depthwise convolutions stay fp16,+/// because they are grouped and edge-padded and `conv_int8.comp` is neither.+///+/// That is 92% of 63.8 million parameters, and it is why the tiled int8 shader had to exist before+/// any of this: `Node::ConvInt8` would otherwise lower to the untiled `conv_int8.comp`, and+/// [`crate::post::supertonic::synthesise`] runs this net `2 * STEPS` = 32 times per utterance. The+/// benchmark in `vulkan::parity` is what closed that off - the tiled int8 path measured at 0.98x of+/// the fp16 tiled one, so quantising costs no time here.+pub const INT8_CONVS: usize = 2 + BLOCKS * 2 + MAIN_BLOCKS * 7;+ /// The rotary `theta`, `[32]`. `rotary_scale * rotary_base ^ (-j / 32)`. pub const HOST_THETA: usize = PLAN_TENSORS; @@ -183,11 +199,20 @@ impl Layers { self.next += 2; 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+ } } -/// A `1 x 1` convolution, which every projection here is.+/// A `1 x 1` convolution with an int8 kernel, which is every `1 x 1` here. See [`INT8_CONVS`]. 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)+ b.conv_int8(x, l.take3(), out, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 1, act) } /// One ConvNeXt block: depthwise, layer norm, widening 1x1 with a GELU, narrowing 1x1, residual.@@ -380,10 +405,13 @@ mod tests { .sum(); let projection = |a: u64, b: u64| a * b + a;- let block = 2_560 + 512 + 512 + 512 + 1_048_576 + 2_048 + 1_048_576 + 512;- let text_attention = projection(512, 512) * 2 + projection(512, 256) * 2 + 1_024;+ // A quantised projection carries a third tensor: the per-output-channel scale, which is+ // the same length as the bias. Every `1 x 1` here is one - see `INT8_CONVS`.+ let quantised = |a: u64, b: u64| projection(a, b) + a;+ let block = 2_560 + 512 + 512 + 512 + quantised(2_048, 512) + quantised(512, 2_048);+ let text_attention = quantised(512, 512) * 2 + quantised(512, 256) * 2 + 1_024; let style_attention =- projection(256, 512) + projection(256, 256) + projection(512, 256) + 1_024;+ quantised(256, 512) + quantised(256, 256) + quantised(512, 256) + 1_024; let host = 32 + 32 + projection(256, 64) + projection(64, 256)@@ -393,14 +421,16 @@ mod tests { + 12_800 * 2 * MAIN_BLOCKS as u64; assert_eq!( total,- projection(512, 144)+ quantised(512, 144) + block * BLOCKS as u64 + (text_attention + style_attention) * MAIN_BLOCKS as u64- + projection(144, 512)+ + quantised(144, 512) + host );- // And spelled out, so a reordering that preserved the sum would still be caught.- assert_eq!(total, 63_813_392);+ // And spelled out, so a reordering that preserved the sum would still be caught. The 84,624+ // above the fp16 total is the scales.+ assert_eq!(total, 63_813_392 + 84_624);+ assert_eq!(total, 63_898_016); } #[test]@@ -536,9 +566,11 @@ mod tests { } } // Three per ConvNeXt block, four per text attention (query, key, value, output),- // three per style attention, plus the two projections.+ // three per style attention, plus the two projections. Everything but the 28 depthwise+ // convolutions is quantised - see `INT8_CONVS`. let convolutions = BLOCKS * 3 + MAIN_BLOCKS * (4 + 3) + 2;- 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("Rotary"), Some(&(MAIN_BLOCKS * 2)), "{counts:?}"); assert_eq!(counts.get("AttnScores"), Some(&(MAIN_BLOCKS * 2)), "{counts:?}"); assert_eq!(counts.get("AttnApply"), Some(&(MAIN_BLOCKS * 2)), "{counts:?}");@@ -549,7 +581,7 @@ mod tests { // No relative attention here: the positions are rotary. assert_eq!(counts.get("AttnScoresRelative"), None, "{counts:?}"); assert_eq!(counts.get("Embed"), None, "{counts:?}");- assert_eq!(counts.len(), 8, "{counts:?}");+ assert_eq!(counts.len(), 9, "{counts:?}"); } #[test]
scripts/ml/maml_convert.py
diff --git a/scripts/ml/maml_convert.py b/scripts/ml/maml_convert.pyindex 48b312bc36..eb79854bc2 100644--- a/scripts/ml/maml_convert.py+++ b/scripts/ml/maml_convert.py@@ -129,7 +129,7 @@ EXPECTED_DIGEST = { "supertonic_voc": "5282083898554b1fae28de946bfc1a82a11e2acddf3911877f27b1b115c583aa", "supertonic_dp": "d9a548e1f1ed908a3b0ad27ab543dd7521858f9110b426edb1ed64ba1f1a13e4", "supertonic_ttl": "92d0fa8ae73d4a8a223c77fb4230e390df580744014a3fcf3211ab72a988c020",- "supertonic_ve": "d76f1fb13eaa9f5a16fed1f97a491d25f75325a36f00535fa3a11a7b16527951",+ "supertonic_ve": "48ab5789e8839507ff93e099dc0f61940f25da9ba6201651784f6e68598199e2", } # Graphs that are one **module** of a larger export, keyed by the node-name prefix that
scripts/ml/supertonic_fold.py
diff --git a/scripts/ml/supertonic_fold.py b/scripts/ml/supertonic_fold.pyindex 72c8e57bea..46f5653af2 100644--- a/scripts/ml/supertonic_fold.py+++ b/scripts/ml/supertonic_fold.py@@ -384,6 +384,18 @@ class Table: maml_convert.Layer(len(self.layers), op, name, key, first, len(values)) ) + def quantised_conv(self, name, key, weight, bias):+ """Add a convolution whose kernel is quantised, from arrays already in hand.++ The int8 half of [`conv`], factored out because the sampler's attention projections come+ from `MatMul` weights rather than a named `.weight` - they are transposed, and the query has+ a scale folded in - so they cannot go through `conv` but must emit the identical+ three-tensor layout. Two copies of that layout would be two chances to order the scale and+ the bias differently, and they are the same length, so nothing downstream would notice.+ """+ quantised, kernel_scale = maml_convert.quantise_per_channel(weight)+ self.add("ConvInt8", name, f"{key} zp=0 dtype=int8", quantised, kernel_scale, bias)+ def conv(self, name, out_channels, fold_scale=None, synthesise_bias=False, pads=(0, 0, 0, 0), kernel=(1, 1), group=1, transpose=False, scale=None, int8=False):@@ -681,13 +693,12 @@ def collect_sampler(graph): return matmul_weights(graph, held, prefix)[name] def linear(at, prefix, name, out_channels):- """One `MatMul` plus its bias, as a 1x1 convolution. The weight is `[in, out]`."""+ """One `MatMul` plus its bias, as a quantised 1x1 convolution. The weight is `[in, out]`.""" weight = matmul(prefix, name).T bias = table.at(f"{at}.{name}.linear.bias") if weight.shape[0] != out_channels: raise SystemExit(f"{at}.{name} is {list(weight.shape)}, not [{out_channels}, in]")- table.add(- "Conv",+ table.quantised_conv( f"{at}.{name}", f"Conv w={[*weight.shape, 1, 1]} b={list(bias.shape)} k={[1, 1]}" f" p={[0, 0, 0, 0]} g=1 pad=edge transposed",@@ -705,8 +716,7 @@ def collect_sampler(graph): scale = np.sqrt(out_channels / heads) / 16.0 weight = matmul(prefix, "W_query").T * scale bias = table.at(f"{at}.W_query.linear.bias") * scale- table.add(- "Conv",+ table.quantised_conv( f"{at}.W_query", f"Conv w={[*weight.shape, 1, 1]} b={list(bias.shape)} k={[1, 1]}" f" p={[0, 0, 0, 0]} g=1 pad=edge transposed scaled={scale:.6f}",@@ -714,8 +724,7 @@ def collect_sampler(graph): bias, ) - table.conv(f"{VE_PREFIX}.proj_in.net", VE_CHANNELS, synthesise_bias=True)-+ table.conv(f"{VE_PREFIX}.proj_in.net", VE_CHANNELS, synthesise_bias=True, int8=True) for block in range(VE_MAIN_BLOCKS): base = block * 6 for layer, dilation in enumerate(VE_LEADING):@@ -724,10 +733,11 @@ def collect_sampler(graph): VE_CHANNELS, VE_INNER, dilation,+ int8=True, ) # `main_blocks.{base + 1}` is the timestep `Linear`, evaluated on the host. table.convnext(- f"{VE_PREFIX}.main_blocks.{base + 2}.convnext.0", VE_CHANNELS, VE_INNER, 1+ f"{VE_PREFIX}.main_blocks.{base + 2}.convnext.0", VE_CHANNELS, VE_INNER, 1, int8=True ) at = f"{VE_PREFIX}.main_blocks.{base + 3}.attn"@@ -739,7 +749,7 @@ def collect_sampler(graph): table.layer_norm(f"{VE_PREFIX}.main_blocks.{base + 3}.norm.norm") table.convnext(- f"{VE_PREFIX}.main_blocks.{base + 4}.convnext.0", VE_CHANNELS, VE_INNER, 1+ f"{VE_PREFIX}.main_blocks.{base + 4}.convnext.0", VE_CHANNELS, VE_INNER, 1, int8=True ) at = f"{VE_PREFIX}.main_blocks.{base + 5}.attention"@@ -750,9 +760,10 @@ def collect_sampler(graph): table.layer_norm(f"{VE_PREFIX}.main_blocks.{base + 5}.norm.norm") for layer in range(VE_TRAILING):- table.convnext(f"{VE_PREFIX}.last_convnext.convnext.{layer}", VE_CHANNELS, VE_INNER, 1)-- table.conv(f"{VE_PREFIX}.proj_out.net", VE_LATENT, synthesise_bias=True)+ table.convnext(+ f"{VE_PREFIX}.last_convnext.convnext.{layer}", VE_CHANNELS, VE_INNER, 1, int8=True+ )+ table.conv(f"{VE_PREFIX}.proj_out.net", VE_LATENT, synthesise_bias=True, int8=True) # Everything from here is read on the host. `nets::Builder::host_tensor` names each, so an # accidentally unread weight is still an error.
speech/src/main/assets/supertonic/README.md
diff --git a/speech/src/main/assets/supertonic/README.md b/speech/src/main/assets/supertonic/README.mdindex ec25daac6f..38fb68785b 100644--- a/speech/src/main/assets/supertonic/README.md+++ b/speech/src/main/assets/supertonic/README.md@@ -22,15 +22,27 @@ producing a net that reads the right shapes holding the wrong numbers. | `unicode_indexer.bin` | 65,536 `int16`, one per BMP codepoint; the whole front end | | `style_F1.bin` … `style_M5.bin` | ten voices, ~25 KB each; two style tensors, not a model | -At fp16 the four nets come to 189 MiB, which with Whisper's 74 MiB puts `:speech`'s assets at-263 MiB. Quantising the ungrouped `1 x 1` convolutions to int8 would take the four nets to ~100 MiB;-`Builder::conv_int8` and `conv_point_int8.comp` exist for it, but no net has been switched over yet.+At int8 the four nets come to 107.6 MiB, which with Whisper's 74.3 MiB puts `:speech`'s assets at+181.9 MiB — 190.7 MB, under the 200 MB target. Every ungrouped `1 x 1` convolution is quantised in+the sampler, the vocoder and the duration predictor; the text encoder stays fp16 on measurement, and+each net's `INT8_CONVS` doc says exactly what is excluded and why.++`onnx_parity.py` against this revision, fp16 and int8 side by side, correlation with onnxruntime:++| net | fp16 | int8 | size |+| :--- | ---: | ---: | ---: |+| `supertonic_dp` | 0.99999975 | 0.99999250 | 1.73 → 1.44 MB |+| `supertonic_ttl` | 0.99900006 | *not quantised* | 17.77 MB |+| `supertonic_voc` | 0.99999858 | 0.99909061 | 50.67 → 28.70 MB |+| `supertonic_ve` | 0.99999981 | 0.99996750 | 127.64 → 64.48 MB |++**The vocoder is the one to listen to first.** 0.99909 clears the 0.999 bar the conversion was gated+on, but it implies roughly −27 dB of error against fp16's −55 dB, and no correlation can say whether+that is audible. Holding it at fp16 costs 21 MB and still fits the target. Verified by `library/ml/src/main/rust/tests/assets.rs`, which builds all four forward passes against these files and checks the codepoint table and every style is the size the runtime assumes. Those tests **skip** when the bundle is absent, so they pass on a fresh checkout and fail on a wrong one.-The numbers are checked separately by `scripts/ml/onnx_parity.py`; at the pinned revision all four-nets correlate with onnxruntime above 0.999, the vocoder better than its own fp16 bar. ## Uncompressed, and it has to stay that way