library:ml: restore the device parity suite, and check the whole supertonic pipeline
- Commit
2f7b5dce65693baa88a8d1c879820a0aae2b93e6- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-29 22:16 UTC (3 months ago)
- Parents
b07b860
Diff
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 d5511387a9..b32c806db9 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -3397,4 +3397,125 @@ mod tests { // image contains no text, which makes a near-empty map the honest answer. assert_usable_mask("ppocr_det", &plan, weights.data()); }++ /// The whole Supertonic pipeline, on the shipped assets, to a waveform on disk.+ ///+ /// Every parity check in this repo is *per net*: `onnx_parity.py` compares one graph against+ /// onnxruntime, and `vulkan::parity` compares one plan against this interpreter. Nothing+ /// compares the **composition** - four nets, a sixteen-step sampler loop and the marshalling+ /// between them - against anything, and that is where the engine's shipped bugs lived: the+ /// duration predictor's second output, and the vocoder's two missing permutations.+ ///+ /// So this runs `post::supertonic::synthesise` exactly as `bridge.rs` does, with the noise read+ /// from a file so an ONNX driver can be given the same draw, and writes the samples out for it+ /// to correlate against. Driven by `PARITY_DIR`, like `dump_reference_output`.+ #[test]+ #[ignore = "runs all four shipped supertonic nets through the interpreter; minutes"]+ fn dump_supertonic_utterance() {+ let Ok(dir) = std::env::var("SUPERTONIC_DIR") else {+ return;+ };+ let dir = std::path::PathBuf::from(dir);+ let text = std::env::var("SUPERTONIC_TEXT").expect("SUPERTONIC_TEXT");+ let Some(root) = repo_root() else {+ return;+ };+ let assets = root.join("speech/src/main/assets/supertonic");+ let load = |name: &str, id: u32| {+ let bytes = std::fs::read(assets.join(name)).unwrap_or_else(|e| panic!("{name}: {e}"));+ crate::weights::Weights::parse(&bytes, id).unwrap_or_else(|e| panic!("{name}: {e}"))+ };+ use crate::post::supertonic as post;+ use crate::weights::graph;+ let dp = load("supertonic_dp.maml", graph::SUPERTONIC_DP);+ let ttl = load("supertonic_ttl.maml", graph::SUPERTONIC_TTL);+ let ve = load("supertonic_ve.maml", graph::SUPERTONIC_VE);+ let voc = load("supertonic_voc.maml", graph::SUPERTONIC_VOC);+ let indexer = std::fs::read(assets.join("unicode_indexer.bin")).expect("the indexer");+ let style = std::fs::read(assets.join("style_F1.bin")).expect("the voice");+ let voice = post::Voice::read(&style).expect("the voice parses");+ let conditioning = post::Conditioning::read(ve.reader()).expect("the conditioning");++ /// The four nets through the interpreter, rebuilding a plan per shape as `Reshaped` does.+ struct Interpreted<'a> {+ dp: &'a crate::weights::Weights,+ ttl: &'a crate::weights::Weights,+ ve: &'a crate::weights::Weights,+ voc: &'a crate::weights::Weights,+ }+ impl post::Stages for Interpreted<'_> {+ fn duration(&mut self, lanes: &[f32], style: &[f32]) -> Result<f32, String> {+ let chars = (lanes.len() / 2 - 1) as u32;+ let plan = supertonic_duration::build(self.dp, chars)?;+ let out = run_multi(&plan, self.dp.data(), &[lanes, style])?;+ Ok(out[1][0])+ }+ fn text(&mut self, lanes: &[f32], style: &[f32]) -> Result<Vec<f32>, String> {+ let chars = (lanes.len() / 2) as u32;+ let plan = supertonic_text::build(self.ttl, chars)?;+ Ok(run_multi(&plan, self.ttl.data(), &[lanes, style])?.remove(0))+ }+ #[allow(clippy::too_many_arguments)]+ fn sampler(+ &mut self,+ latent: &[f32],+ text: &[f32],+ keys: &[f32],+ style: &[f32],+ shifts: &[f32],+ query_angles: &[f32],+ key_angles: &[f32],+ ) -> Result<Vec<f32>, String> {+ let frames = (latent.len() / 144) as u32;+ let chars = (text.len() / 256) as u32;+ let plan = supertonic_sampler::build(self.ve, frames, chars)?;+ let inputs: &[&[f32]] =+ &[latent, text, keys, style, shifts, query_angles, key_angles];+ Ok(run_multi(&plan, self.ve.data(), inputs)?.remove(0))+ }+ fn vocoder(&mut self, latent: &[f32], frames: u32) -> Result<Vec<f32>, String> {+ let plan = supertonic_vocoder::build(self.voc, frames)?;+ // Statistics of the latent the sampler converged to. A flow model that stayed on+ // the data manifold lands in the same distribution as the export's, even when the+ // trajectory differs; one that drifted off it does not, and that shows here long+ // before it shows in a waveform correlation.+ let n = latent.len() as f64;+ let mean = latent.iter().map(|&v| f64::from(v)).sum::<f64>() / n;+ let var =+ latent.iter().map(|&v| (f64::from(v) - mean).powi(2)).sum::<f64>() / n;+ let absmax = latent.iter().fold(0.0f32, |t, &v| t.max(v.abs()));+ println!(+ "final latent: {} values, absmax {absmax:.4}, mean {mean:.5}, sd {:.5}",+ latent.len(),+ var.sqrt()+ );+ let unpacked = supertonic_vocoder::unpack_latent(latent, frames as usize)?;+ let channelled = run_multi(&plan, self.voc.data(), &[&unpacked])?.remove(0);+ Ok(supertonic_vocoder::interleave(&channelled))+ }+ }++ let raw = std::fs::read(dir.join("noise.f32")).expect("the noise");+ let drawn: Vec<f32> = raw+ .chunks_exact(4)+ .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))+ .collect();+ let mut nets = Interpreted { dp: &dp, ttl: &ttl, ve: &ve, voc: &voc };+ let samples = post::synthesise(&mut nets, &conditioning, &indexer, &voice, &text, &|count| {+ assert_eq!(count, drawn.len(), "the driver drew a latent of a different size");+ drawn.clone()+ })+ .expect("the utterance synthesises");+ println!("supertonic utterance: {} samples", samples.len());+ write(&dir.join("ours.f32"), &samples);+ }++ /// The repo root, or `None` when the assets are not checked out beside this crate.+ fn repo_root() -> Option<std::path::PathBuf> {+ let mut dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));+ while !dir.join("settings.gradle.kts").is_file() {+ dir = dir.parent()?.to_path_buf();+ }+ Some(dir)+ } }
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 669d0165d2..7fbadc8528 100644--- a/library/ml/src/main/rust/src/vulkan/parity.rs+++ b/library/ml/src/main/rust/src/vulkan/parity.rs@@ -849,3 +849,104 @@ fn a_rebuilt_net_agrees_with_the_reference_at_each_shape() { matches(&format!("a net rebuilt at {width}"), &host, &got); } }++/// The shipped Supertonic text encoder and vocoder, on the device against the interpreter.+///+/// The fixtures above are single ops over a handful of channels, and `onnx_parity.py` compares the+/// *interpreter* against onnxruntime. Neither says anything about a real net's depth on a real+/// device: an arena slot reused while a dispatch still reads it, or a barrier missing between two+/// of ninety convolutions, shows up only at that scale and only on hardware.+///+/// Which is what let a broken vocoder ship. Both marshalling steps were missing from `bridge.rs`+/// for a net whose interpreter parity was 0.999.+///+/// The widths are the ones a real utterance produced - 47 characters and 59 latent frames for+/// "Hello, this voice runs entirely on this device." - rather than the round 64 the scripts default+/// to, because a tail that is not a multiple of the workgroup is where indexing goes wrong.+#[test]+#[ignore = "needs a Vulkan device and the shipped supertonic assets"]+fn the_shipped_supertonic_nets_agree_with_the_reference_on_the_device() {+ let Some(root) = repo() else {+ return;+ };+ let read = |name: &str| std::fs::read(root.join("speech/src/main/assets/supertonic").join(name));++ if let Ok(bytes) = read("supertonic_ttl.maml") {+ let weights = Weights::parse(&bytes, graph::SUPERTONIC_TTL).expect("the text encoder parses");+ let chars = 47u32;+ let plan = crate::nets::supertonic_text::build(&weights, chars).expect("the encoder builds");+ // Two lanes of ids and the voice's style, which is what the net's two inputs are.+ let ids: Vec<u32> = (0..chars).map(|i| (i * 173 + 11) % 8322).collect();+ let lanes = embed_lanes(&ids);+ let style = spread(256 * 50, 0.7);+ let host = run_multi(&plan, weights.data(), &[&lanes, &style])+ .expect("the interpreter runs the text encoder");+ let got = on_device(plan, weights.data().to_vec(), &[&lanes, &style]);+ report("the shipped text encoder at 47 characters", &host, &got);+ }++ if let Ok(bytes) = read("supertonic_voc.maml") {+ let weights = Weights::parse(&bytes, graph::SUPERTONIC_VOC).expect("the vocoder parses");+ let frames = 59u32;+ let plan = crate::nets::supertonic_vocoder::build(&weights, frames).expect("it builds");+ // The plan's own input, so this checks the net rather than `unpack_latent`, which is a host+ // permutation with fixtures of its own.+ let latent = spread(24 * 6 * frames as usize, 1.3);+ let host =+ run_multi(&plan, weights.data(), &[&latent]).expect("the interpreter runs the vocoder");+ let got = on_device(plan, weights.data().to_vec(), &[&latent]);+ report("the shipped vocoder at 59 frames", &host, &got);+ }+}++/// Print how far the device is from the interpreter, rather than asserting a threshold.+///+/// [`TOLERANCE`] is calibrated on fixtures a handful of ops deep. These nets are a hundred, so a+/// max element that exceeds it says nothing on its own โ the question is whether the error is a few+/// fp16 ulps spread everywhere, which is drift, or a structure, which is a bug. Correlation and the+/// mean separate the two where a max cannot.+fn report(what: &str, host: &[Vec<f32>], got: &[Vec<f32>]) {+ assert_eq!(got.len(), host.len(), "{what}: output count");+ for (index, (host, got)) in host.iter().zip(got).enumerate() {+ assert_eq!(got.len(), host.len(), "{what}: output {index} length");+ let scale = host.iter().fold(0.0f32, |top, v| top.max(v.abs())).max(1e-3);+ let mut worst = 0.0f32;+ let mut total = 0.0f64;+ let mut over = 0usize;+ for (a, b) in host.iter().zip(got) {+ let error = (a - b).abs();+ worst = worst.max(error);+ total += f64::from(error);+ if error / scale > TOLERANCE {+ over += 1;+ }+ }+ let count = host.len();+ let mean = |v: &[f32]| v.iter().map(|&x| f64::from(x)).sum::<f64>() / count as f64;+ let (hm, gm) = (mean(host), mean(got));+ let mut cov = 0.0f64;+ let (mut hv, mut gv) = (0.0f64, 0.0f64);+ for (a, b) in host.iter().zip(got) {+ let (da, db) = (f64::from(*a) - hm, f64::from(*b) - gm);+ cov += da * db;+ hv += da * da;+ gv += db * db;+ }+ let corr = cov / (hv.sqrt() * gv.sqrt()).max(f64::MIN_POSITIVE);+ println!(+ "{what}: output {index} over {count} values, scale {scale:.4}\n \+ max {worst:.6} mean {:.7} corr {corr:.8} over tolerance {over} ({:.3}%)",+ total / count as f64,+ 100.0 * over as f64 / count as f64,+ );+ }+}++/// The repo root, or `None` when the assets are not checked out beside this crate.+fn repo() -> Option<std::path::PathBuf> {+ let mut dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));+ while !dir.join("settings.gradle.kts").is_file() {+ dir = dir.parent()?.to_path_buf();+ }+ Some(dir)+}
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 a13ea53a61..e8b9097291 100644--- a/library/ml/src/main/rust/src/weights.rs+++ b/library/ml/src/main/rust/src/weights.rs@@ -349,15 +349,30 @@ impl Weights { /// A [`Weights`] that is nothing but a data section, for the device-parity fixtures. ///- /// [`crate::vulkan::run::Net::new`] reads no part of a [`Weights`] except [`data`], because- /// the [`crate::nets::Plan`] it is handed already carries every resolved offset. So a- /// fixture that built its plan against a test [`WeightSource`] can give the device the same- /// blob without assembling a header and a tensor table that nothing would ever read.+ /// [`crate::vulkan::run::Net::new`] reads no part of a [`Weights`] except [`data`] to *record*+ /// the plan, because the [`crate::nets::Plan`] it is handed already carries every resolved+ /// offset. It does read the table to **validate** each op's weight range against it, though โ+ /// see `segment::tensor_end` โ so the table cannot be empty or every op is rejected as reading+ /// outside all zero of the tensors the file describes.+ ///+ /// One tensor spanning the whole blob is what a fixture can honestly assert: its plan was built+ /// against a [`WeightSource`] whose own offsets are already consistent, so the property left to+ /// check on the device is that nothing reads off the end of the data. Assembling a faithful+ /// per-tensor table here would duplicate the fixture's source and check the fixture rather than+ /// the shader. /// /// [`data`]: Weights::data #[cfg(test)] pub(crate) fn from_data(data: Vec<u8>) -> Weights {- let table = Offsets { tensors: Vec::new() };+ let table = Offsets {+ tensors: vec![Tensor {+ rank: 1,+ dims: [(data.len() / 2) as u32, 0, 0, 0],+ offset: 0,+ len: (data.len() / 2) as u32,+ int8: false,+ }],+ }; Weights { graph_id: 0, source_sha256: [0u8; 32], table, data } }