Modern Apps git

← Modern-Apps.git

library:ml: edge padding, so a border replicates instead of reading zeros

Commit
63d193fb8cd9cfde0d77d01f71b35da25caef056
Author
vayun-mathur <[email protected]>
When
2026-08-28 05:24 UTC (3 months ago)
Parents
f0d8d43

Diff

library/ml/src/main/rust/shaders/common.glsl
diff --git a/library/ml/src/main/rust/shaders/common.glsl b/library/ml/src/main/rust/shaders/common.glslindex 5d73f0793e..6dc952b520 100644--- a/library/ml/src/main/rust/shaders/common.glsl+++ b/library/ml/src/main/rust/shaders/common.glsl@@ -75,6 +75,7 @@ layout(push_constant) uniform Push {     uint dil_w;     uint pad_t;     uint pad_l;+    uint pad_edge;     uint group;     uint act;     uint act_weight;
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 62b4d67af6..53ab6c713b 100644--- a/library/ml/src/main/rust/shaders/conv.comp+++ b/library/ml/src/main/rust/shaders/conv.comp@@ -47,14 +47,19 @@ void main() {         uint plane = p.in0 + (first_in + ic) * p.in_h * p.in_w;         for (uint ky = 0u; ky < p.kh; ky++) {             int iy = int(oy * p.stride_h + ky * p.dil_h) - int(p.pad_t);-            if (iy < 0 || iy >= int(p.in_h)) {+            if (p.pad_edge != 0u) {+                // Replicate the border rather than read zeros. See `Push::pad_edge`.+                iy = clamp(iy, 0, int(p.in_h) - 1);+            } else if (iy < 0 || iy >= int(p.in_h)) {                 continue;             }             uint row = plane + uint(iy) * p.in_w;             uint tap = kernel_at + (ic * p.kh + ky) * p.kw;             for (uint kx = 0u; kx < p.kw; kx++) {                 int ix = int(ox * p.stride_w + kx * p.dil_w) - int(p.pad_l);-                if (ix < 0 || ix >= int(p.in_w)) {+                if (p.pad_edge != 0u) {+                    ix = clamp(ix, 0, int(p.in_w) - 1);+                } else if (ix < 0 || ix >= int(p.in_w)) {                     continue;                 }                 acc += float(arena[row + uint(ix)]) * float(weights[tap + kx]);
library/ml/src/main/rust/src/nets/mod.rs
diff --git a/library/ml/src/main/rust/src/nets/mod.rs b/library/ml/src/main/rust/src/nets/mod.rsindex c61f49fc96..8355faa0ac 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -346,6 +346,14 @@ pub struct Push {     pub pad_t: u32,     /// Padding left of column 0. ONNX's `pads[1]`.     pub pad_l: u32,+    /// Non-zero when the convolution replicates its border instead of reading zeros.+    ///+    /// ONNX spells this as a `Pad` node with `mode=edge` in front of a convolution whose own+    /// `pads` are all zero, which is how Supertonic''s vocoder keeps its length: twelve of them,+    /// 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.+    pub pad_edge: u32,     /// Convolution groups. `group == in_c == out_c` is depthwise.     pub group: u32,     /// [`Act::code`].@@ -501,6 +509,8 @@ enum Node {         /// Resolved offset of [`Act::PRelu`]'s slope, zero otherwise.         act_weight: u32,         transpose: bool,+        /// Replicate the border instead of reading zeros. See [`Push::pad_edge`].+        pad_edge: bool,     },     MaxPool {         input: Id,@@ -632,6 +642,8 @@ pub struct Builder<'a> {     /// One flag per tensor in the file, set when the pass reads it. See     /// [`Builder::finish`], which insists every one was.     read: Vec<bool>,+    /// Whether convolutions replicate their border rather than reading zeros.+    pad_edge: bool, }  /// Arena allocations are aligned to this many fp16 elements, i.e. 16 bytes — the same@@ -649,9 +661,21 @@ impl<'a> Builder<'a> {             pinned: Vec::new(),             error: None,             inputs: Vec::new(),+            pad_edge: false,         }     } +    /// Make every convolution from here on replicate its border instead of reading zeros.+    ///+    /// A builder-level mode rather than an argument on [`Builder::conv`], because a network+    /// either pads this way throughout or not at all: Supertonic''s vocoder puts an ONNX `Pad`+    /// with `mode=edge` in front of all twelve of its convolutions, and threading a flag through+    /// every call site would be noise at each one. See [`Push::pad_edge`] for what goes wrong if+    /// this is missed.+    pub fn edge_padding(&mut self) {+        self.pad_edge = true;+    }+     /// Declare an input of `shape`.     ///     /// Callable more than once, in which case [`Plan::inputs`] lists them in this@@ -741,6 +765,7 @@ impl<'a> Builder<'a> {             act,             act_weight,             transpose: false,+            pad_edge: self.pad_edge,         });         out     }@@ -891,6 +916,7 @@ impl<'a> Builder<'a> {             act,             act_weight,             transpose: true,+            pad_edge: false,         });         out     }@@ -1437,6 +1463,7 @@ impl<'a> Builder<'a> {                 act,                 act_weight,                 transpose,+                pad_edge,             } => {                 let (si, so) = (shape(*input), shape(*out));                 // An ungrouped 1x1 goes to the tiled path. Its geometry is a matrix multiply@@ -1498,6 +1525,7 @@ impl<'a> Builder<'a> {                         dil_w: dilation.1,                         pad_t: pad.0,                         pad_l: pad.1,+                        pad_edge: u32::from(*pad_edge),                         group: *group,                         act: act.code(),                         act_weight: *act_weight,@@ -2149,8 +2177,11 @@ pub(crate) mod tests {     fn the_push_block_has_no_padding() {         // The shaders read it at fixed offsets, so a gap Rust inserted would shift         // every field after it.-        assert_eq!(std::mem::size_of::<Push>(), 25 * 4);+        assert_eq!(std::mem::size_of::<Push>(), 26 * 4);         assert_eq!(std::mem::align_of::<Push>(), 4);+        // Vulkan only guarantees 128 bytes of push constants, so this is the ceiling the+        // block has to stay under however many modes get added to it.+        assert!(std::mem::size_of::<Push>() <= 128, "{}", std::mem::size_of::<Push>());     }      #[test]
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 eb2cdb13a4..2856759eaf 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -272,17 +272,26 @@ impl Reference {                     for ic in 0..in_per_group {                         let plane = (first_in + ic) * p.in_h * p.in_w;                         for ky in 0..p.kh {-                            let Some(iy) = tap(oy * p.stride_h + ky * p.dil_h, p.pad_t, p.in_h)-                            else {-                                continue;+                            let positioned = oy * p.stride_h + ky * p.dil_h;+                            let iy = if p.pad_edge != 0 {+                                tap_edge(positioned, p.pad_t, p.in_h)+                            } else {+                                match tap(positioned, p.pad_t, p.in_h) {+                                    Some(found) => found,+                                    None => continue,+                                }                             };                             let row = plane + iy * p.in_w;                             let tap_at = kernel_at + (ic * p.kh + ky) * p.kw;                             for kx in 0..p.kw {-                                let Some(ix) =-                                    tap(ox * p.stride_w + kx * p.dil_w, p.pad_l, p.in_w)-                                else {-                                    continue;+                                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)+                                } else {+                                    match tap(positioned, p.pad_l, p.in_w) {+                                        Some(found) => found,+                                        None => continue,+                                    }                                 };                                 acc += self.load(p.in0, row + ix)?                                     * self.weight(tap_at, kx)?;@@ -816,6 +825,18 @@ fn tap(positioned: u32, pad: u32, extent: u32) -> Option<u32> {     (coordinate < extent).then_some(coordinate) } +/// As [`tap`], but replicating the border instead of falling off it.+///+/// Always lands, which is the point: an edge-padded convolution has no skipped taps. See+/// [`super::Push::pad_edge`].+fn tap_edge(positioned: u32, pad: u32, extent: u32) -> u32 {+    let last = extent.saturating_sub(1);+    match positioned.checked_sub(pad) {+        Some(coordinate) => coordinate.min(last),+        None => 0,+    }+}+ /// The input coordinate feeding a transposed convolution's output, or `None` when this /// tap does not land on one: `(padded - k)` must be non-negative and a whole number of /// strides.@@ -1847,6 +1868,50 @@ mod tests {         assert!(error.contains("channels 3..5"), "{error}");     } +    #[test]+    fn edge_padding_replicates_the_border_instead_of_reading_zeros() {+        // Four positions, a 3-wide kernel of all ones padded by one each side. With zero padding+        // the two end outputs are short a tap; with edge padding the border value is counted+        // twice. This is the whole difference, and it only shows at the ends — which is why+        // getting it wrong is an audible click at the start and finish of an utterance and+        // nothing anywhere else.+        let values = [1.0f32, 2.0, 3.0, 4.0];+        let weights = &[(vec![1u32, 1, 1, 3], vec![1.0, 1.0, 1.0]), (vec![1], vec![0.0])];+        let zero = one(Shape::new(1, 1, 4), &values, weights, |b, x| {+            b.conv(x, 0, 1, (1, 3), (1, 1), (1, 1), (0, 1, 0, 1), 1, Act::None)+        });+        // 0+1+2, 1+2+3, 2+3+4, 3+4+0+        close(&zero, &[3.0, 6.0, 9.0, 7.0]);++        let edge = one(Shape::new(1, 1, 4), &values, weights, |b, x| {+            b.edge_padding();+            b.conv(x, 0, 1, (1, 3), (1, 1), (1, 1), (0, 1, 0, 1), 1, Act::None)+        });+        // 1+1+2, 1+2+3, 2+3+4, 3+4+4+        close(&edge, &[4.0, 6.0, 9.0, 11.0]);+        // And the interior is identical, which is what makes the failure mode so quiet.+        assert_eq!(zero[1], edge[1]);+        assert_eq!(zero[2], edge[2]);+    }++    #[test]+    fn edge_padding_survives_a_kernel_wider_than_the_input() {+        // The vocoder dilates a 7-tap kernel by up to 4, so a tap can be 12 positions outside a+        // short sequence. Clamping must saturate rather than wrap.+        let values = [5.0f32, 6.0];+        let got = one(+            Shape::new(1, 1, 2),+            &values,+            &[(vec![1u32, 1, 1, 3], vec![1.0, 1.0, 1.0]), (vec![1], vec![0.0])],+            |b, x| {+                b.edge_padding();+                b.conv(x, 0, 1, (1, 3), (1, 1), (4, 4), (0, 4, 0, 4), 1, Act::None)+            },+        );+        // Every tap lands 4 away, so both outputs read only the clamped ends: 5 + x + 6.+        close(&got, &[5.0 + 5.0 + 6.0, 5.0 + 6.0 + 6.0]);+    }+     #[test]     fn an_elementwise_product_multiplies_position_by_position() {         // Distinct from `mul_channel`, which broadcasts `[C, 1, 1]`. Two channels of three