Modern Apps git

← Modern-Apps.git

ml: drop supertonic frame padding (not exact; ragged GEMM path covers it)

Commit
f8b39829c6099e0262e830086d6d775bb73db93c
Author
vayun-mathur <[email protected]>
When
2026-10-25 22:08 UTC (1 month ago)
Parents
ffcb437

Diff

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 2b0270c25d..3a5075826a 100644--- a/library/ml/src/main/rust/src/nets/supertonic_sampler.rs+++ b/library/ml/src/main/rust/src/nets/supertonic_sampler.rs@@ -159,10 +159,6 @@ pub const TENSORS: usize = PLAN_TENSORS + 18; /// [`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.-///-/// [`crate::post::supertonic::synthesise`] runs every utterance at a multiple of four frames-/// (see [`crate::post::supertonic::pad_positions`]), so these dispatches take the shader's-/// 16-tap wide-load path rather than its scalar fallback. pub const INT8_CONVS: usize = 2 + BLOCKS * 2 + MAIN_BLOCKS * 7;  /// The rotary `theta`, `[32]`. `rotary_scale * rotary_base ^ (-j / 32)`.
library/ml/src/main/rust/src/post/supertonic.rs
diff --git a/library/ml/src/main/rust/src/post/supertonic.rs b/library/ml/src/main/rust/src/post/supertonic.rsindex 6a673cb368..e5b02257bd 100644--- a/library/ml/src/main/rust/src/post/supertonic.rs+++ b/library/ml/src/main/rust/src/post/supertonic.rs@@ -101,29 +101,17 @@ pub fn time_shifts(weights: Reader, current: u32, total: u32) -> Result<Vec<f32> /// meet at the same angle. It also means the query table and the key table are different tensors /// even though they share `theta`. pub fn rotary_angles(theta: &[f32], positions: u32) -> Result<Vec<f32>, String> {-    rotary_angles_over(theta, positions, positions)-}--/// [`rotary_angles`] with the length and the normaliser split: a table `len` positions wide-/// whose angles are `(position / divisor) * theta`.-///-/// For a padded plan — see [`pad_positions`] — the query table is built at the padded length-/// but normalised by the real one, so the real positions keep the exact angles the unpadded-/// plan used and the padding replicates the edge. The tail is never read (the velocities are-/// sliced back to the real length before the Euler step leaves them anywhere observable),-/// but the divisor is what makes the head bit-identical rather than merely close.-pub fn rotary_angles_over(theta: &[f32], divisor: u32, len: u32) -> Result<Vec<f32>, String> {-    if divisor == 0 || len == 0 {+    if positions == 0 {         return Err("a rotary table over no positions".into());     }     if theta.len() != net::FREQUENCIES as usize {         return Err(format!("{} rotary frequencies, not {}", theta.len(), net::FREQUENCIES));     }-    let width = len as usize;+    let width = positions as usize;     let mut table = vec![0.0f32; 2 * net::FREQUENCIES as usize * width];     for (frequency, &turn) in theta.iter().enumerate() {         for position in 0..width {-            let angle = position as f32 / divisor as f32 * turn;+            let angle = position as f32 / positions as f32 * turn;             table[frequency * width + position] = angle.cos();             table[(net::FREQUENCIES as usize + frequency) * width + position] = angle.sin();         }@@ -131,60 +119,6 @@ pub fn rotary_angles_over(theta: &[f32], divisor: u32, len: u32) -> Result<Vec<f     Ok(table) } -/// The latent length the sampler and the vocoder actually run at: `frames` rounded up to a-/// multiple of four.-///-/// The int8 pointwise shader (`conv_point_int8.comp`) reads sixteen taps and four positions-/// per iteration only when the position count is a multiple of four; at any other length it-/// falls back to scalar loads, which measured ~2.5x slower on the NLLB/whisper encode GEMMs.-/// The sampler runs at 49 frames for the reference sentence, so every one of its 172-/// pointwise dispatches per dual step takes the slow path. Rounding to 52 recovers the fast-/// one for no new kernel and no new op.-///-/// Bit-identical, not approximate, when the padding replicates the edge (see-/// [`replicate_edge`]): the depthwise convolutions are symmetrically edge-padded, so a real-/// position's taps clamp to the same values; everything computed over the tail is sliced off-/// before it is observable. The vocoder needs no replication at all — its convolutions are-/// causal, so real outputs never read the tail.-pub fn pad_positions(frames: u32) -> u32 {-    frames.next_multiple_of(4).max(4)-}--/// Extend a channel-major `[channels, real]` tensor to `[channels, padded]` by replicating-/// its last position.-///-/// The host-side half of [`pad_positions`]: the sampler's latent and query angles arrive at-/// the padded length with the tail filled this way, so the edge-padded depthwise reads the-/// same values the unpadded plan's clamps produced. A zero fill would read as silence past-/// the edge and drift the tail's real outputs; replication is what makes the padding free.-pub fn replicate_edge(-    values: &[f32],-    channels: usize,-    real: usize,-    padded: usize,-) -> Result<Vec<f32>, String> {-    if channels == 0 || real == 0 || padded < real {-        return Err(format!(-            "cannot extend {channels} channels over {real} positions to {padded}"-        ));-    }-    if values.len() != channels * real {-        return Err(format!(-            "{} values are not {channels} channels over {real} positions",-            values.len()-        ));-    }-    let mut out = Vec::with_capacity(channels * padded);-    for channel in 0..channels {-        let row = &values[channel * real..(channel + 1) * real];-        out.extend_from_slice(row);-        if let Some(&edge) = row.last() {-            out.extend(std::iter::repeat_n(edge, padded - real));-        }-    }-    Ok(out)-}- /// The unconditional branch's text input: `text_special_token` at every one of `chars` positions. pub fn unconditional_text(token: &[f32], chars: u32) -> Result<Vec<f32>, String> {     if chars == 0 {
library/ml/src/main/rust/src/post/supertonic_part1.rs
diff --git a/library/ml/src/main/rust/src/post/supertonic_part1.rs b/library/ml/src/main/rust/src/post/supertonic_part1.rsindex ad505f22ea..daae5803d9 100644--- a/library/ml/src/main/rust/src/post/supertonic_part1.rs+++ b/library/ml/src/main/rust/src/post/supertonic_part1.rs@@ -40,13 +40,6 @@ impl Voice { /// noise + text_emb -> latent     the sampler, [`STEPS`] steps of two guidance branches /// latent -> waveform             the vocoder /// ```-///-/// The sampler and the vocoder run at [`pad_positions`]`(frames)` rather than `frames` itself,-/// so the int8 pointwise dispatches take the shader's wide-load path; the waveform is then-/// truncated back to `frames * SAMPLES_PER_FRAME` samples. Bit-identical to running unpadded:-/// the sampler's inputs replicate the edge (which its symmetric padding clamps to anyway),-/// the vocoder is causal (real outputs never read the tail), and the tail is sliced before-/// anything observable. pub fn synthesise(     stages: &mut dyn Stages,     conditioning: &Conditioning,@@ -66,28 +59,14 @@ pub fn synthesise(     with_token.extend_from_slice(&ids);     let log_seconds = stages.duration(&embed_lanes(&with_token), &voice.duration)?;     let frames = duration_net::latent_frames(duration_net::seconds(log_seconds) / SPEED);-    let padded = pad_positions(frames);      let conditioning_text = stages.text(&embed_lanes(&ids), &voice.text)?; -    // Normalised by the real length, built out to the padded one: the real positions-    // keep the exact angles the unpadded plan used and the tail is never read. The key-    // table is over the characters, which are never padded (padding keys would steal-    // softmax mass).-    let query_angles = rotary_angles_over(&conditioning.theta, frames, padded)?;+    let query_angles = rotary_angles(&conditioning.theta, frames)?;     let key_angles = rotary_angles(&conditioning.theta, chars)?;     let unconditional_text = unconditional_text(&conditioning.text_token, chars)?; -    // The noise covers the real frames; the tail replicates the edge so the sampler's-    // edge-padded depthwise reads what the unpadded plan's clamps produced. It stays padded-    // for all sixteen steps — the plan is recorded at the padded shape — and is sliced once,-    // below, before the vocoder.-    let mut latent = replicate_edge(-        &noise(net::LATENT as usize * frames as usize),-        net::LATENT as usize,-        frames as usize,-        padded as usize,-    )?;+    let mut latent = noise(net::LATENT as usize * frames as usize);     for step in 0..STEPS as usize {         let shifts = conditioning             .shifts@@ -108,19 +87,7 @@ pub fn synthesise(         latent = self::step(&latent, &conditional, &unconditional, STEPS)?;     } -    // The vocoder runs padded and its tail is truncated: it is causal, so the real prefix-    // never read the tail and the extra samples are beyond the predicted duration anyway.-    // Truncating the waveform rather than the latent keeps every stage at one shape.-    let waveform = stages.vocoder(&latent, padded)?;-    let samples =-        frames as usize * crate::nets::supertonic_vocoder::SAMPLES_PER_FRAME as usize;-    if waveform.len() < samples {-        return Err(format!(-            "a vocoder pass over {padded} frames returned {} samples, not {samples}",-            waveform.len()-        ));-    }-    Ok(waveform[..samples].to_vec())+    stages.vocoder(&latent, frames) }  /// One Euler step: combine the two guidance branches and advance the latent.
library/ml/src/main/rust/src/post/supertonic_part2.rs
diff --git a/library/ml/src/main/rust/src/post/supertonic_part2.rs b/library/ml/src/main/rust/src/post/supertonic_part2.rsindex 8e4ee30d41..11a87d2431 100644--- a/library/ml/src/main/rust/src/post/supertonic_part2.rs+++ b/library/ml/src/main/rust/src/post/supertonic_part2.rs@@ -172,13 +172,6 @@ mod tests {         vocoded_frames: Vec<u32>,     } -    /// What `synthesise` runs the sampler and the vocoder at: the predicted frames rounded-    /// up for the int8 wide-load path. The stub asserts these padded lengths; the pipeline-    /// test asserts the waveform is truncated back to the real ones.-    fn padded(frames: u32) -> u32 {-        super::pad_positions(frames)-    }-     impl Stages for Recording {         fn duration(&mut self, lanes: &[f32], style: &[f32]) -> Result<f32, String> {             // Two lanes over `chars + 1` positions, the sentence token first.@@ -210,12 +203,12 @@ mod tests {             query_angles: &[f32],             key_angles: &[f32],         ) -> Result<Vec<f32>, String> {-            assert_eq!(latent.len(), net::LATENT as usize * padded(self.frames) as usize);+            assert_eq!(latent.len(), net::LATENT as usize * self.frames as usize);             assert_eq!(text.len(), net::TEXT as usize * self.chars as usize);             assert_eq!(keys.len(), net::STYLE as usize * net::MAIN_BLOCKS * 50);             assert_eq!(style.len(), net::STYLE as usize * 50);             assert_eq!(shifts.len(), net::CHANNELS as usize * net::MAIN_BLOCKS);-            assert_eq!(query_angles.len(), 64 * padded(self.frames) as usize);+            assert_eq!(query_angles.len(), 64 * self.frames as usize);             assert_eq!(key_angles.len(), 64 * self.chars as usize);             self.sampler_calls += 1;             self.latents.push(latent.to_vec());@@ -264,8 +257,6 @@ mod tests {         }          fn vocoder(&mut self, latent: &[f32], frames: u32) -> Result<Vec<f32>, String> {-            // The padded shape in, the padded waveform out; `synthesise` truncates.-            assert_eq!(frames, padded(self.frames));             assert_eq!(latent.len(), net::LATENT as usize * frames as usize);             self.vocoded_frames.push(frames);             Ok(vec![0.5; frames as usize * 3072])@@ -300,49 +291,6 @@ mod tests {         }     } -    #[test]-    fn padding_leaves_short_lengths_alone() {-        assert_eq!(super::pad_positions(1), 4);-        assert_eq!(super::pad_positions(4), 4);-        assert_eq!(super::pad_positions(14), 16);-        assert_eq!(super::pad_positions(49), 52);-        assert_eq!(super::pad_positions(52), 52);-    }--    #[test]-    fn replicating_the_edge_extends_each_channel_with_its_last_value() {-        // Two channels over three positions, extended to five: each row keeps its values-        // and repeats its own edge, not its neighbour's.-        let values = vec![1.0, 2.0, 3.0, 10.0, 20.0, 30.0];-        let got = super::replicate_edge(&values, 2, 3, 5).expect("extends");-        assert_eq!(got, vec![1.0, 2.0, 3.0, 3.0, 3.0, 10.0, 20.0, 30.0, 30.0, 30.0]);-        // Already a multiple of four: a copy, not an error.-        let same = super::replicate_edge(&values, 2, 3, 3).expect("copies");-        assert_eq!(same, values);-        // A short slice, a zero width and a shrinking target are all refused rather-        // than read out of bounds.-        assert!(super::replicate_edge(&values[..5], 2, 3, 5).is_err());-        assert!(super::replicate_edge(&values, 0, 3, 5).is_err());-        assert!(super::replicate_edge(&values, 2, 3, 2).is_err());-    }--    #[test]-    fn a_split_rotary_table_matches_the_whole_one_on_the_real_positions() {-        // The padded query table is normalised by the real length, so its head is the-        // table the unpadded plan used and only the replicated tail differs.-        let theta = vec![0.5; net::FREQUENCIES as usize];-        let whole = super::rotary_angles(&theta, 14).expect("angles");-        let split = super::rotary_angles_over(&theta, 14, 16).expect("angles");-        assert_eq!(split.len(), 64 * 16);-        for channel in 0..64 {-            assert_eq!(-                &split[channel * 16..channel * 16 + 14],-                &whole[channel * 14..(channel + 1) * 14],-                "channel {channel} drifts"-            );-        }-    }-     #[test]     fn the_pipeline_runs_the_four_nets_in_order_at_the_predicted_length() {         // "hello" is five mapped letters, and `<en>` and `</en>` are nine more. At one second the@@ -368,10 +316,8 @@ mod tests {             &|count| vec![0.0; count],         )         .expect("synthesises");-        // Fourteen frames of audio, not sixteen: the sampler and the vocoder ran padded-        // (see the stub's asserts) and `synthesise` truncated the tail.         assert_eq!(samples.len(), 14 * 3072);-        assert_eq!(stages.vocoded_frames, vec![16]);+        assert_eq!(stages.vocoded_frames, vec![14]);         // `synthesise` takes the dual path: 16 `sampler_both` calls, each served by         // the default as two single submits.         assert_eq!(stages.sampler_duals, STEPS as usize);