Modern Apps git

← Modern-Apps.git

library:ml: windowed average pool, where a map becomes a sequence

Commit
5c15c40e396f60326fe0ef6f92562a06a830b31d
Author
vayun-mathur <[email protected]>
When
2026-08-27 19:01 UTC (3 months ago)
Parents
562a5fe

Diff

library/ml/src/main/rust/shaders/avgpool.comp
diff --git a/library/ml/src/main/rust/shaders/avgpool.comp b/library/ml/src/main/rust/shaders/avgpool.compnew file mode 100644index 0000000000..5881a8c139--- /dev/null+++ b/library/ml/src/main/rust/shaders/avgpool.comp@@ -0,0 +1,56 @@+#version 450+//! Average pooling over an explicit window. One use, in PP-OCRv5 recognition.+//!+//! # What it is for+//!+//! The recogniser's backbone ends at `[480, 3, 80]` and its transformer wants a+//! sequence. One pool with kernel `(3, 2)` and stride `(3, 2)` does both jobs at once:+//! it collapses the remaining three rows to one and halves the width, giving+//! `[480, 1, 40]` — which is `[d_model, 1, T]`, the layout everything downstream reads.+//!+//! So this is not a general-purpose pooling layer that happens to be used once. It is+//! the point at which a feature map becomes a sequence, and the asymmetric kernel is why+//! the shader takes `kh` and `kw` separately rather than one size.+//!+//! # No padding, and an exact divisor+//!+//! `nets::Builder::avg_pool` refuses a window that does not tile its input exactly, so+//! every window is fully inside the map and the divisor is always `kh * kw`. That is+//! what `count_include_pad = 0` means when there is no padding to count, and it is why+//! the bounds tests below can never fire — they are here so that a plan which somehow+//! got past the builder reads in range rather than off the end of the arena.+//!+//! Distinct from `gap.comp`, which reduces *all* of H and W to one value per channel and+//! is the squeeze in a squeeze-excite. That one needs no window at all; this one is+//! nothing but window.++#include "common.glsl"++void main() {+    uint index = global_index();+    if (index >= p.count) {+        return;+    }+    uint oc, oy, ox;+    unpack(index, oc, oy, ox);+    uint plane = p.in0 + oc * p.in_h * p.in_w;+    uint top = oy * p.stride_h;+    uint left = ox * p.stride_w;++    float total = 0.0;+    for (uint ky = 0u; ky < p.kh; ky++) {+        uint iy = top + ky;+        if (iy >= p.in_h) {+            continue;+        }+        uint row = plane + iy * p.in_w;+        for (uint kx = 0u; kx < p.kw; kx++) {+            uint ix = left + kx;+            if (ix >= p.in_w) {+                continue;+            }+            total += float(arena[row + ix]);+        }+    }+    arena[p.out_at + index] = float16_t(total / float(p.kh * p.kw));+}
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 27baafd1bf..f6fb149eaf 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -126,6 +126,14 @@ pub enum Kind {     ConvTranspose,     /// Max pooling.     MaxPool,+    /// Average pooling over an explicit window, floored and unpadded.+    ///+    /// One use: the pool that turns PP-OCRv5 recognition's `[480, 3, 80]` feature map+    /// into the `[480, 1, 40]` sequence its transformer reads, with kernel and stride+    /// both `(3, 2)`. The asymmetric window is the reason this carries `kh`/`kw` rather+    /// than one size, and the reason it is not [`Kind::GlobalAvgPool`] with a flag — that+    /// one reduces all of H and W to a single value and needs no window arithmetic.+    AvgPool,     /// Bilinear resize, `half_pixel` coordinates.     Resize,     /// Nearest-neighbour resize, `asymmetric` coordinates and `floor` rounding.@@ -392,6 +400,12 @@ enum Node {         kernel: (u32, u32),         stride: (u32, u32),     },+    AvgPool {+        input: Id,+        out: Id,+        kernel: (u32, u32),+        stride: (u32, u32),+    },     Resize {         input: Id,         out: Id,@@ -685,6 +699,33 @@ impl<'a> Builder<'a> {         out     } +    /// Average pooling over `kernel` at `stride`, which must tile the input exactly.+    ///+    /// The one use is `(3, 2)` at `(3, 2)` on a `3 x 80` map, so it tiles. Refusing+    /// anything else is deliberate: a window that overhangs makes the divisor a question+    /// — ONNX has `count_include_pad` for it and the two answers differ — and the shader+    /// divides by `kh * kw` unconditionally. A ragged extent would silently scale the+    /// edge of the sequence.+    pub fn avg_pool(&mut self, input: Id, kernel: (u32, u32), stride: (u32, u32)) -> Id {+        let in_shape = self.shape_of(input);+        let (kh, kw) = kernel;+        let out_h = conv_out(in_shape.h, kh, stride.0, 1, 0);+        let out_w = conv_out(in_shape.w, kw, stride.1, 1, 0);+        for (axis, extent, k, s, out) in [+            ('h', in_shape.h, kh, stride.0, out_h),+            ('w', in_shape.w, kw, stride.1, out_w),+        ] {+            if out == 0 || out.saturating_sub(1) * s + k != extent {+                self.fail(format!(+                    "avg_pool of {k} at stride {s} does not tile {extent} along {axis}, so \+                     the divisor would not be the window size"+                ));+            }+        }+        let out = self.tensor(Shape::new(in_shape.c, out_h, out_w));+        self.nodes.push(Node::AvgPool { input, out, kernel, stride });+        out+    }     /// Bilinear resize to `like`'s spatial size, which is how both shipping nets always     /// use it — U^2-Net's `_upsample_like`, and the selfie net's decoder skips.     pub fn resize_like(&mut self, input: Id, like: Id) -> Id {@@ -1017,6 +1058,29 @@ impl<'a> Builder<'a> {                     invocations: so.len(),                 });             }+            Node::AvgPool { input, out, kernel, stride } => {+                let (si, so) = (shape(*input), shape(*out));+                ops.push(Op::Dispatch {+                    kind: Kind::AvgPool,+                    push: Push {+                        in0: at(*input)?,+                        out: at(*out)?,+                        in_c: si.c,+                        in_h: si.h,+                        in_w: si.w,+                        out_c: so.c,+                        out_h: so.h,+                        out_w: so.w,+                        kh: kernel.0,+                        kw: kernel.1,+                        stride_h: stride.0,+                        stride_w: stride.1,+                        count: so.len(),+                        ..Push::default()+                    },+                    invocations: so.len(),+                });+            }             Node::Resize { input, out, nearest } => {                 let (si, so) = (shape(*input), shape(*out));                 ops.push(Op::Dispatch {@@ -1209,6 +1273,7 @@ impl Node {         match self {             Node::Conv { out, .. }             | Node::MaxPool { out, .. }+            | Node::AvgPool { out, .. }             | Node::Resize { out, .. }             | Node::GlobalAvgPool { out, .. }             | Node::Binary { out, .. }@@ -1225,6 +1290,7 @@ impl Node {         match self {             Node::Conv { input, .. }             | Node::MaxPool { input, .. }+            | Node::AvgPool { input, .. }             | Node::Resize { input, .. }             | Node::Affine { input, .. }             | Node::LayerNorm { input, .. }
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 f6c1d0daef..511444ded1 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -172,6 +172,7 @@ impl Reference {                     Kind::Conv => self.conv(push),                     Kind::ConvTranspose => self.conv_transpose(push),                     Kind::MaxPool => self.max_pool(push),+                    Kind::AvgPool => self.avg_pool(push),                     Kind::Resize => self.resize(push),                     Kind::ResizeNearest => self.resize_nearest(push),                     Kind::GlobalAvgPool => self.global_avg_pool(push),@@ -358,6 +359,40 @@ impl Reference {         Ok(())     } +    /// Average pooling over an explicit window, floored and unpadded.+    ///+    /// The divisor is the window size rather than the number of elements actually read,+    /// which is only correct because `Builder::avg_pool` refuses a window that overhangs.+    fn avg_pool(&mut self, p: &Push) -> Result<(), String> {+        let window = p.kh * p.kw;+        if window == 0 {+            return Err("an average pool over an empty window".into());+        }+        for oc in 0..p.out_c {+            let plane = oc * p.in_h * p.in_w;+            for oy in 0..p.out_h {+                for ox in 0..p.out_w {+                    let mut total = 0.0;+                    for ky in 0..p.kh {+                        let iy = oy * p.stride_h + ky;+                        if iy >= p.in_h {+                            continue;+                        }+                        for kx in 0..p.kw {+                            let ix = ox * p.stride_w + kx;+                            if ix >= p.in_w {+                                continue;+                            }+                            total += self.load(p.in0, plane + iy * p.in_w + ix)?;+                        }+                    }+                    self.store(p.out, nchw(p, oc, oy, ox), total / window as f32)?;+                }+            }+        }+        Ok(())+    }+     /// Bilinear resize under the `half_pixel` convention, `src = (dst + 0.5) * in / out - 0.5`.     ///     /// The same formula [`crate::preprocess`] uses for the input resize. That@@ -958,6 +993,60 @@ mod tests {         close(&got, &[6.0, 8.0, 14.0, 16.0]);     } +    #[test]+    fn average_pooling_takes_the_mean_of_each_window() {+        // The same 4x4 as the max-pool fixture above, so the two are directly+        // comparable: 6 against 3.5 for the first window.+        let input: Vec<f32> = (1..=16).map(|v| v as f32).collect();+        let got = one(Shape::new(1, 4, 4), &input, &[], |b, x| {+            b.avg_pool(x, (2, 2), (2, 2))+        });+        close(&got, &[3.5, 5.5, 11.5, 13.5]);+    }++    #[test]+    fn an_asymmetric_pool_window_is_not_transposed() {+        // The recogniser's shape: kernel and stride both (3, 2) on a 3-row map, which+        // collapses the height to one and halves the width. This is the step that turns+        // a feature map into a `[d_model, 1, T]` sequence.+        //+        // Rows are (1,2,3,4), (5,6,7,8), (9,10,11,12), so the left window holds+        // 1,2,5,6,9,10 and the right one 3,4,7,8,11,12. A kernel read as (2, 3) instead+        // would pool 1,2,3,5,6,7 and answer 4 for the first column.+        let input: Vec<f32> = (1..=12).map(|v| v as f32).collect();+        let got = one(Shape::new(1, 3, 4), &input, &[], |b, x| {+            b.avg_pool(x, (3, 2), (3, 2))+        });+        close(&got, &[33.0 / 6.0, 45.0 / 6.0]);+    }++    #[test]+    fn average_pooling_keeps_channels_apart() {+        // Two channels a decade apart, so a pool whose plane stride was wrong folds them+        // together visibly rather than shifting the answer slightly.+        let got = one(+            Shape::new(2, 1, 4),+            &[1.0, 2.0, 3.0, 4.0, 10.0, 20.0, 30.0, 40.0],+            &[],+            |b, x| b.avg_pool(x, (1, 2), (1, 2)),+        );+        close(&got, &[1.5, 3.5, 15.0, 35.0]);+    }++    #[test]+    fn a_pool_window_that_does_not_tile_its_input_is_refused() {+        // 5 wide with a 2-wide window at stride 2 drops the last column, and the shader+        // divides by the window size regardless — so the choice is between a silently+        // dropped column and a silently rescaled edge. Neither is acceptable, so the+        // build fails instead.+        let given = Given::new(&[]).expect("no tensors");+        let mut b = Builder::new(&given);+        let x = b.input(Shape::new(1, 2, 5));+        let pooled = b.avg_pool(x, (2, 2), (2, 2));+        let error = b.finish(&[pooled]).expect_err("a 5-wide input");+        assert!(error.contains("does not tile 5 along w"), "{error}");+    }+     #[test]     fn a_resize_puts_its_samples_at_half_pixel_centres() {         // Two columns to four. The samples land at source x = -0.25, 0.25, 0.75, 1.25,
library/ml/src/main/rust/src/vulkan/pipeline.rs
diff --git a/library/ml/src/main/rust/src/vulkan/pipeline.rs b/library/ml/src/main/rust/src/vulkan/pipeline.rsindex 543d062966..a4c1519db6 100644--- a/library/ml/src/main/rust/src/vulkan/pipeline.rs+++ b/library/ml/src/main/rust/src/vulkan/pipeline.rs@@ -28,6 +28,7 @@ const CONV: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/conv.comp.spv")); const CONV_TRANSPOSE: &[u8] =     include_bytes!(concat!(env!("OUT_DIR"), "/conv_transpose.comp.spv")); const MAXPOOL: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/maxpool.comp.spv"));+const AVGPOOL: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/avgpool.comp.spv")); const RESIZE: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/resize.comp.spv")); const RESIZE_NEAREST: &[u8] =     include_bytes!(concat!(env!("OUT_DIR"), "/resize_nearest.comp.spv"));@@ -41,10 +42,11 @@ const SOFTMAX: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/softmax.comp.sp const ATTN_APPLY: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/attn_apply.comp.spv"));  /// Every shader, in the order [`Pipelines::create`] destructures them.-const SPIRV: [&[u8]; 13] = [+const SPIRV: [&[u8]; 14] = [     CONV,     CONV_TRANSPOSE,     MAXPOOL,+    AVGPOOL,     RESIZE,     RESIZE_NEAREST,     GAP,@@ -81,6 +83,7 @@ pub struct Pipelines {     conv: vk::Pipeline,     conv_transpose: vk::Pipeline,     maxpool: vk::Pipeline,+    avgpool: vk::Pipeline,     resize: vk::Pipeline,     resize_nearest: vk::Pipeline,     gap: vk::Pipeline,@@ -216,6 +219,7 @@ impl Pipelines {             conv,             conv_transpose,             maxpool,+            avgpool,             resize,             resize_nearest,             gap,@@ -245,6 +249,7 @@ impl Pipelines {             conv,             conv_transpose,             maxpool,+            avgpool,             resize,             resize_nearest,             gap,@@ -264,6 +269,7 @@ impl Pipelines {             Kind::Conv => self.conv,             Kind::ConvTranspose => self.conv_transpose,             Kind::MaxPool => self.maxpool,+            Kind::AvgPool => self.avgpool,             Kind::Resize => self.resize,             Kind::ResizeNearest => self.resize_nearest,             Kind::GlobalAvgPool => self.gap,@@ -285,6 +291,7 @@ impl Pipelines {             self.conv,             self.conv_transpose,             self.maxpool,+            self.avgpool,             self.resize,             self.resize_nearest,             self.gap,