ml: supertonic sampler at frames padded to x4, exact via pad_edge clamp
- Commit
30ddf657f3d68d0df64c1cc0cc34bd4b88dd5d46- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-25 23:53 UTC (1 month ago)
- Parents
8fba5de
Diff
library/ml/src/main/rust/examples/profile_supertonic.rs
diff --git a/library/ml/src/main/rust/examples/profile_supertonic.rs b/library/ml/src/main/rust/examples/profile_supertonic.rsindex 6322cccc66..2619b2d484 100644--- a/library/ml/src/main/rust/examples/profile_supertonic.rs+++ b/library/ml/src/main/rust/examples/profile_supertonic.rs@@ -51,7 +51,7 @@ fn text_plan(offsets: &Offsets, chars: u32) -> Result<Plan, String> { } fn sampler_plan(offsets: &Offsets, shape: (u32, u32)) -> Result<Plan, String> {- supertonic_sampler::build_dual(offsets, shape.0, shape.1)+ supertonic_sampler::build_dual_padded(offsets, shape.0, shape.1) } fn vocoder_plan(offsets: &Offsets, frames: u32) -> Result<Plan, String> {@@ -217,6 +217,9 @@ impl supertonic::Stages for Timed { self.reshape_ms += each; self.reshape_sampler_ms += each; let running = Instant::now();+ let latent = supertonic_sampler::pad_frames(latent, frames)?;+ let query_angles = supertonic_sampler::pad_frames(query_angles, frames)?;+ let (latent, query_angles) = (latent.as_slice(), query_angles.as_slice()); let out = net.infer_raw_many(&[ latent, conditional_text,@@ -242,7 +245,10 @@ impl supertonic::Stages for Timed { <[Vec<f32>; 2]>::try_from(out).map_err(|other| { format!("the dual sampler returned {} tensors, not two", other.len()) })?;- Ok([conditional, unconditional])+ Ok([+ supertonic_sampler::unpad_frames(&conditional, frames)?,+ supertonic_sampler::unpad_frames(&unconditional, frames)?,+ ]) } fn vocoder(&mut self, latent: &[f32], frames: u32) -> Result<Vec<f32>, String> {
library/ml/src/main/rust/shaders/conv.comp
diff --git a/library/ml/src/main/rust/shaders/conv.comp b/library/ml/src/main/rust/shaders/conv.compindex a8f76fe7d9..7c03933441 100644--- a/library/ml/src/main/rust/shaders/conv.comp+++ b/library/ml/src/main/rust/shaders/conv.comp@@ -70,7 +70,7 @@ void main() { for (uint kx = 0u; kx < p.kw; kx++) { int ix = int(ox * p.stride_w + kx * p.dil_w) - int(p.pad_l); if (p.pad_edge != 0u) {- ix = clamp(ix, 0, int(p.in_w) - 1);+ ix = clamp(ix, 0, int(p.in_w) - int(p.pad_edge)); } else if (ix < 0 || ix >= int(p.in_w)) { continue; }
library/ml/src/main/rust/src/bridge_part1.rs
diff --git a/library/ml/src/main/rust/src/bridge_part1.rs b/library/ml/src/main/rust/src/bridge_part1.rsindex 912db571ea..c5363e1de9 100644--- a/library/ml/src/main/rust/src/bridge_part1.rs+++ b/library/ml/src/main/rust/src/bridge_part1.rs@@ -213,7 +213,7 @@ fn text_plan(offsets: &Offsets, chars: u32) -> Result<Plan, String> { } fn sampler_plan(offsets: &Offsets, shape: (u32, u32)) -> Result<Plan, String> {- supertonic_sampler::build_dual(offsets, shape.0, shape.1)+ supertonic_sampler::build_dual_padded(offsets, shape.0, shape.1) } fn vocoder_plan(offsets: &Offsets, frames: u32) -> Result<Plan, String> {@@ -367,6 +367,11 @@ impl supertonic::Stages for SupertonicNets<'_> { self.timing.reshape += reshaping.elapsed().as_secs_f64() * 1000.0; let running = std::time::Instant::now(); self.timing.sampler_calls += 1;+ // The plan runs at `padded_frames` (see `build_dual_padded`), so the latent and the+ // query angles go in widened and the velocities come back cut to `frames`.+ let latent = supertonic_sampler::pad_frames(latent, frames)?;+ let query_angles = supertonic_sampler::pad_frames(query_angles, frames)?;+ let (latent, query_angles) = (latent.as_slice(), query_angles.as_slice()); // Fourteen inputs: the conditional seven, then the unconditional seven โ the // order `build_dual` declares them in. Two outputs, the two velocities. let out = net.infer_raw_many(&[@@ -390,7 +395,10 @@ impl supertonic::Stages for SupertonicNets<'_> { <[Vec<f32>; 2]>::try_from(out).map_err(|other| { format!("the dual sampler returned {} tensors, not two", other.len()) })?;- Ok([conditional, unconditional])+ Ok([+ supertonic_sampler::unpad_frames(&conditional, frames)?,+ supertonic_sampler::unpad_frames(&unconditional, frames)?,+ ]) } fn vocoder(&mut self, latent: &[f32], frames: u32) -> Result<Vec<f32>, String> {
library/ml/src/main/rust/src/nets/mod_part1.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part1.rs b/library/ml/src/main/rust/src/nets/mod_part1.rsindex 4c46c74353..4c2e6811eb 100644--- a/library/ml/src/main/rust/src/nets/mod_part1.rs+++ b/library/ml/src/main/rust/src/nets/mod_part1.rs@@ -62,6 +62,8 @@ pub struct Push { /// one before every convolution. Zero padding there would corrupt up to twelve positions at /// each END of an utterance and leave the middle correct - an audible click at the start and /// finish of every sentence.+ ///+ /// `conv.comp` clamps columns at `in_w - pad_edge`, so values above 1 ignore a padded tail. pub pad_edge: u32, /// Convolution groups. `group == in_c == out_c` is depthwise. pub group: u32,
library/ml/src/main/rust/src/nets/reference_part1.rs
diff --git a/library/ml/src/main/rust/src/nets/reference_part1.rs b/library/ml/src/main/rust/src/nets/reference_part1.rsindex 2b0966dd19..272893267c 100644--- a/library/ml/src/main/rust/src/nets/reference_part1.rs+++ b/library/ml/src/main/rust/src/nets/reference_part1.rs@@ -177,7 +177,7 @@ impl Reference { for kx in 0..p.kw { let positioned = ox * p.stride_w + kx * p.dil_w; let ix = if p.pad_edge != 0 {- tap_edge(positioned, p.pad_l, p.in_w)+ tap_edge(positioned, p.pad_l, p.in_w + 1 - p.pad_edge) } else { match tap(positioned, p.pad_l, p.in_w) { Some(found) => found,
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 3a5075826a..63aa02b7b0 100644--- a/library/ml/src/main/rust/src/nets/supertonic_sampler.rs+++ b/library/ml/src/main/rust/src/nets/supertonic_sampler.rs@@ -81,7 +81,7 @@ //! at 0.29 from `main_blocks.11` on. A per-stage comparison found it in one run, which is much //! faster than reasoning about a 1004-node graph. -use super::{Act, Builder, Id, Plan, Shape, WeightSource, NO_FUSE};+use super::{Act, Builder, Id, Kind, Op, Plan, Shape, WeightSource, NO_FUSE}; /// Latent channels in and out. `ldim * chunk_compress_factor`, and the vocoder's `PACKED`. pub const LATENT: u32 = 144;@@ -420,4 +420,5 @@ fn branch_host_tensors(b: &mut Builder) { b.host_tensor(HOST_KEYS_UNCONDITIONAL, &[STYLE * MAIN_BLOCKS as u32, STYLE_TOKENS]); } -include!("supertonic_sampler_part1.rs");\ No newline at end of file+include!("supertonic_sampler_part1.rs");+include!("supertonic_sampler_part2.rs");\ No newline at end of file
library/ml/src/main/rust/src/nets/supertonic_sampler_part2.rs
diff --git a/library/ml/src/main/rust/src/nets/supertonic_sampler_part2.rs b/library/ml/src/main/rust/src/nets/supertonic_sampler_part2.rsnew file mode 100644index 0000000000..51b17d00ff--- /dev/null+++ b/library/ml/src/main/rust/src/nets/supertonic_sampler_part2.rs@@ -0,0 +1,105 @@+/// Frames [`build_dual_padded`] runs at: `frames` rounded up to a multiple of four.+///+/// `conv_point_int8.comp` reads activations a quad at a time only when the width is a multiple+/// of four; at a ragged width each row costs two loads, and the sampler's 172 int8 GEMMs per+/// step ran ~1.6x slower on a Pixel 8.+pub fn padded_frames(frames: u32) -> u32 {+ frames.next_multiple_of(4)+}++/// [`build_dual`] at [`padded_frames`]`(frames)`, exact on the first `frames` positions.+///+/// The depthwise convolutions are the only ops here that mix positions โ both attentions take+/// the frames as queries only, layer norm is over channels โ so each one clamps its right edge+/// at `frames - 1` rather than at the padded width (`Push::pad_edge` = 1 + tail, read by+/// `conv.comp`). Real positions then never read the tail, whatever it holds. Inputs and outputs+/// are at the padded width: [`pad_frames`] the latent and query angles in, [`unpad_frames`]+/// the velocities out.+pub fn build_dual_padded(+ weights: &dyn WeightSource,+ frames: u32,+ chars: u32,+) -> Result<Plan, String> {+ let padded = padded_frames(frames);+ let mut plan = build_dual(weights, padded, chars)?;+ let edge = 1 + padded - frames;+ for op in &mut plan.ops {+ if let Op::Dispatch { kind: Kind::Conv, push, .. } = op {+ if push.group == CHANNELS && push.in_w == padded {+ push.pad_edge = edge;+ }+ }+ }+ Ok(plan)+}++/// A channel-major `[channels, frames]` tensor widened to [`padded_frames`] with a zero tail.+pub fn pad_frames(values: &[f32], frames: u32) -> Result<Vec<f32>, String> {+ let (real, padded) = (frames as usize, padded_frames(frames) as usize);+ if real == 0 || values.is_empty() || !values.len().is_multiple_of(real) {+ return Err(format!("{} values are not whole rows of {real} frames", values.len()));+ }+ let mut out = vec![0.0; values.len() / real * padded];+ for (row, chunk) in values.chunks_exact(real).enumerate() {+ out[row * padded..row * padded + real].copy_from_slice(chunk);+ }+ Ok(out)+}++/// The first `frames` positions of each row of a [`padded_frames`]-wide tensor.+pub fn unpad_frames(values: &[f32], frames: u32) -> Result<Vec<f32>, String> {+ let (real, padded) = (frames as usize, padded_frames(frames) as usize);+ if real == 0 || values.is_empty() || !values.len().is_multiple_of(padded) {+ return Err(format!("{} values are not whole rows of {padded} frames", values.len()));+ }+ Ok(values.chunks_exact(padded).flat_map(|row| &row[..real]).copied().collect())+}++#[cfg(test)]+mod padded_tests {+ use super::super::tests::Shapes;+ use super::super::{Kind, Op};+ use super::*;++ #[test]+ fn frames_round_up_to_a_multiple_of_four() {+ assert_eq!(padded_frames(1), 4);+ assert_eq!(padded_frames(49), 52);+ assert_eq!(padded_frames(52), 52);+ }++ #[test]+ fn the_padded_plan_runs_wide_and_clamps_every_depthwise_at_the_real_edge() {+ let (frames, chars) = (49, 24);+ let plan = build_dual_padded(&Shapes::new(TENSORS), frames, chars).expect("builds");+ assert_eq!(plan.inputs[0].shape, Shape::new(LATENT, 1, 52));+ assert_eq!(plan.inputs[5].shape, Shape::new(2 * FREQUENCIES, 1, 52));+ assert_eq!(plan.outputs.len(), 2);+ let edges: Vec<u32> = plan+ .ops+ .iter()+ .filter_map(|op| match op {+ Op::Dispatch { kind: Kind::Conv, push, .. } => Some(push.pad_edge),+ _ => None,+ })+ .collect();+ assert_eq!(edges, vec![4; 2 * BLOCKS]);+ }++ #[test]+ fn an_aligned_length_is_the_plain_dual_plan() {+ let padded = build_dual_padded(&Shapes::new(TENSORS), 52, 24).expect("builds");+ let plain = build_dual(&Shapes::new(TENSORS), 52, 24).expect("builds");+ assert_eq!(padded.ops, plain.ops);+ }++ #[test]+ fn padding_and_unpadding_round_trip() {+ let values: Vec<f32> = (0..6).map(|v| v as f32).collect();+ let wide = pad_frames(&values, 3).expect("pads");+ assert_eq!(wide, vec![0.0, 1.0, 2.0, 0.0, 3.0, 4.0, 5.0, 0.0]);+ assert_eq!(unpad_frames(&wide, 3).expect("unpads"), values);+ assert!(pad_frames(&values[..5], 3).is_err());+ assert!(unpad_frames(&values, 3).is_err());+ }+}
library/ml/src/main/rust/src/vulkan/parity_part6.rs
diff --git a/library/ml/src/main/rust/src/vulkan/parity_part6.rs b/library/ml/src/main/rust/src/vulkan/parity_part6.rsindex a209bfc8f3..d2d1f17519 100644--- a/library/ml/src/main/rust/src/vulkan/parity_part6.rs+++ b/library/ml/src/main/rust/src/vulkan/parity_part6.rs@@ -305,6 +305,45 @@ fn blocked_convs_at_every_window_alignment_agree_with_the_reference() { ); } +/// The Supertonic sampler's padded plan: a dilated depthwise (1, 7) with edge padding over 52+/// columns, `pad_edge` = 4 so columns clamp at the real width of 49. The tail holds garbage,+/// and the first 49 columns must match the plain 49-wide plan exactly on the interpreter, and+/// the device must match the interpreter.+#[test]+#[ignore = "needs a Vulkan device"]+fn an_edge_clamp_short_of_the_width_ignores_the_padded_tail() {+ let (channels, real, padded) = (16usize, 49usize, 52usize);+ let given = Given::new(&[+ (vec![channels as u32, 1, 1, 7], spread(channels * 7, 0.4)),+ (vec![channels as u32], spread(channels, 1.7)),+ ])+ .expect("the fixture tensors are consistent");+ let data = given.data().to_vec();+ let at = |width: usize| {+ build(&given, &[Shape::new(channels as u32, 1, width as u32)], |b, ids| {+ b.edge_padding();+ let c = channels as u32;+ b.conv(ids[0], 0, c, (1, 7), (1, 1), (1, 4), (0, 12, 0, 12), c, Act::None)+ })+ };+ let narrow_input = spread(channels * real, 2.2);+ let mut wide_input = vec![37.0f32; channels * padded];+ for (row, chunk) in narrow_input.chunks_exact(real).enumerate() {+ wide_input[row * padded..row * padded + real].copy_from_slice(chunk);+ }+ let mut wide = at(padded);+ for op in &mut wide.ops {+ if let crate::nets::Op::Dispatch { kind: crate::nets::Kind::Conv, push, .. } = op {+ push.pad_edge = 1 + (padded - real) as u32;+ }+ }+ let narrow = run_multi(&at(real), &data, &[&narrow_input]).expect("the interpreter runs");+ let host = run_multi(&wide, &data, &[&wide_input]).expect("the interpreter runs");+ let cut: Vec<f32> = host[0].chunks_exact(padded).flat_map(|row| &row[..real]).copied().collect();+ assert_eq!(cut, narrow[0], "the real columns read the padded tail");+ compare("an edge clamp short of the width", wide, data, &[&wide_input]);+}+ /// Count the plan's `Kind::Conv` dispatches by `in1` selector (untiled, dense, depthwise). fn conv_selectors(plan: &crate::nets::Plan) -> [usize; 3] { let mut seen = [0; 3];