Modern Apps git

← Modern-Apps.git

ml: register-blocked 4oc x 8col dense conv, u2netp 7x / modnet 5x on Pixel

Commit
f4ce1c6619711424494ee04be07cd38d506a0ff1
Author
vayun-mathur <[email protected]>
When
2026-10-25 23:19 UTC (1 month ago)
Parents
a8c20e1

Diff

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 d24d614844..47f5eba921 100644--- a/library/ml/src/main/rust/shaders/conv.comp+++ b/library/ml/src/main/rust/shaders/conv.comp@@ -25,8 +25,16 @@ //! tiling bug.  #include "common.glsl"+#include "conv_tiled.glsl"  void main() {+    // The register-blocked tiled path, for nets that opted in with+    // `Builder::spatial_tiling`. The untiled body below is unchanged for+    // everything else — same Kind, same push block, same dispatches.+    if (p.in1 == 1u) {+        tiled_spatial();+        return;+    }     uint index = global_index();     if (index >= p.count) {         return;
library/ml/src/main/rust/shaders/conv_tiled.glsl
diff --git a/library/ml/src/main/rust/shaders/conv_tiled.glsl b/library/ml/src/main/rust/shaders/conv_tiled.glslnew file mode 100644index 0000000000..cf54ff1d26--- /dev/null+++ b/library/ml/src/main/rust/shaders/conv_tiled.glsl@@ -0,0 +1,216 @@+//! A dense (`group == 1`) convolution, register-blocked over channels and columns.+//!+//! Included by `conv.comp`, which branches here when `p.in1 == 1` (see `nets::Push::in1`);+//! the untiled body there stays for every net that never opts in with+//! `Builder::spatial_tiling`, and for grouped convolutions.+//!+//! Each invocation owns [`BLOCK_OC`] output channels by [`BLOCK_X`] adjacent columns of one+//! output row, so every weight read feeds eight columns and every activation read feeds four+//! channels. Invocations run along the row first, so neighbouring lanes read neighbouring+//! activations and the same weights.+//!+//! The scalar untiled path is load-issue bound (~12 GMAC/s on a Pixel 8). Stride-1 3x3,+//! dilated 3x3 and 5x5 kernels over quad-aligned rows read each (channel, kernel row) span+//! once as aligned `f16vec4` quads and run every tap from registers (`dense_rows`, ~120+//! GMAC/s); anything else reads masked scalars. Accumulation order per output is the+//! untiled one - input channels, kernel rows, taps - so the two agree to rounding.++#extension GL_EXT_control_flow_attributes : require++layout(std430, binding = 0) readonly buffer ArenaQuad {+    f16vec4 arena_quad[];+};++/// Output channels per invocation. **Must equal `SPATIAL_BLOCK_OC` in `nets`.**+#define BLOCK_OC 4u++/// Adjacent output columns per invocation. **Must equal `SPATIAL_BLOCK_X` in `nets`.**+#define BLOCK_X 8u++// Eight consecutive arena elements from `at`, through the aligned quads covering them. The+// third quad is read only when `at` is unaligned, so a run ending a buffer reads nothing past it.+void eight_at(uint at, out vec4 lo, out vec4 hi) {+    uint q = at >> 2u;+    uint rem = at & 3u;+    f16vec4 a = arena_quad[q];+    f16vec4 b = arena_quad[q + 1u];+    if (rem == 0u) {+        lo = vec4(a);+        hi = vec4(b);+        return;+    }+    f16vec4 c = arena_quad[q + 2u];+    if (rem == 1u) {+        lo = vec4(a.yzw, b.x);+        hi = vec4(b.yzw, c.x);+    } else if (rem == 2u) {+        lo = vec4(a.zw, b.xy);+        hi = vec4(b.zw, c.xy);+    } else {+        lo = vec4(a.w, b.xyz);+        hi = vec4(b.w, c.xyz);+    }+}++// The eight columns' activations for one tap: input row `row`, first column `ix`.+void columns_at(uint row, int ix, bool interior, out vec4 lo, out vec4 hi) {+    if (interior) {+        eight_at(row + uint(ix), lo, hi);+        return;+    }+    float x[BLOCK_X];+    for (uint j = 0u; j < BLOCK_X; j++) {+        int at = ix + int(j * p.stride_w);+        x[j] = (at >= 0 && at < int(p.in_w)) ? float(arena[row + uint(at)]) : 0.0;+    }+    lo = vec4(x[0], x[1], x[2], x[3]);+    hi = vec4(x[4], x[5], x[6], x[7]);+}++/// Quads in the widest window `dense_rows` loads: 8 columns + a 4-column reach + offset 3.+#define WINDOW_QUADS 4++// Element `e` of a window of quads; constant once `dense_rows` is inlined and unrolled.+#define WIN(e) win[(e) >> 2][(e) & 3]++// Dense stride-1 convolution over rows that all share one quad alignment.+//+// Per (input channel, kernel row) the block's whole input span - 8 columns plus the+// kernel's dilated reach - is read as aligned quads, then every kernel tap reuses it from+// registers. Columns outside the row are zeroed by a per-lane mask computed once, so edge+// blocks take the same branch-free path as interior ones (a per-lane edge branch diverged+// most warps). `rem` (the window start's offset into its quad), `kw` and `dil` are+// literals at every call site, so after inlining every window index is a constant.+void dense_rows(+    const int rem, const int kw, const int dil,+    uint oy, int ix0, uint wrow[BLOCK_OC], inout vec4 lo[BLOCK_OC], inout vec4 hi[BLOCK_OC]+) {+    int quads = (rem + int(BLOCK_X) + (kw - 1) * dil + 3) >> 2;+    uint plane = p.in_h * p.in_w;+    uint taps = p.kh * p.kw;+    int c0 = ix0 - rem;+    bvec4 keep[WINDOW_QUADS];+    [[unroll]] for (int q = 0; q < quads; q++) {+        ivec4 c = ivec4(c0 + 4 * q) + ivec4(0, 1, 2, 3);+        keep[q] = equal(clamp(c, ivec4(0), ivec4(int(p.in_w) - 1)), c);+    }+    int last = int((p.in0 + p.in_c * plane - 1u) >> 2u);+    for (uint ic = 0u; ic < p.in_c; ic++) {+        uint channel = p.in0 + ic * plane;+        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)) {+                continue;+            }+            int first = (int(channel + uint(iy) * p.in_w) + c0) >> 2;+            vec4 win[WINDOW_QUADS];+            [[unroll]] for (int q = 0; q < quads; q++) {+                vec4 v = vec4(arena_quad[clamp(first + q, 0, last)]);+                win[q] = mix(vec4(0.0), v, keep[q]);+            }+            uint tap0 = ic * taps + ky * p.kw;+            [[unroll]] for (int kx = 0; kx < kw; kx++) {+                int e = rem + kx * dil;+                vec4 xl = vec4(WIN(e), WIN(e + 1), WIN(e + 2), WIN(e + 3));+                vec4 xh = vec4(WIN(e + 4), WIN(e + 5), WIN(e + 6), WIN(e + 7));+                [[unroll]] for (uint i = 0u; i < BLOCK_OC; i++) {+                    float w = float(weights[wrow[i] + tap0 + uint(kx)]);+                    lo[i] += w * xl;+                    hi[i] += w * xh;+                }+            }+        }+    }+}++// `dense_rows` for the four alignments of one kernel shape; `rem` is uniform per dispatch.+#define DENSE_ROWS_ANY(KW, DIL) \+    if (rem == 0) dense_rows(0, KW, DIL, oy, ix0, wrow, lo, hi); \+    else if (rem == 1) dense_rows(1, KW, DIL, oy, ix0, wrow, lo, hi); \+    else if (rem == 2) dense_rows(2, KW, DIL, oy, ix0, wrow, lo, hi); \+    else dense_rows(3, KW, DIL, oy, ix0, wrow, lo, hi);++void tiled_spatial() {+    uint x_blocks = (p.out_w + BLOCK_X - 1u) / BLOCK_X;+    uint oc_blocks = (p.out_c + BLOCK_OC - 1u) / BLOCK_OC;+    uint invocation = global_index();+    if (invocation >= oc_blocks * p.out_h * x_blocks) {+        return;+    }+    uint ox0 = (invocation % x_blocks) * BLOCK_X;+    uint rest = invocation / x_blocks;+    uint oy = rest % p.out_h;+    uint channel_base = (rest / p.out_h) * BLOCK_OC;++    // Channels past the last read the last one's weights; never stored.+    uint rows[BLOCK_OC];+    for (uint i = 0u; i < BLOCK_OC; i++) {+        rows[i] = min(channel_base + i, p.out_c - 1u);+    }+    vec4 lo[BLOCK_OC];+    vec4 hi[BLOCK_OC];+    for (uint i = 0u; i < BLOCK_OC; i++) {+        lo[i] = vec4(float(weights[p.bias + rows[i]]));+        hi[i] = lo[i];+    }++    uint taps = p.kh * p.kw;+    uint plane = p.in_h * p.in_w;+    int ix0 = int(ox0 * p.stride_w) - int(p.pad_l);+    bool interior = p.stride_w == 1u && ix0 >= 0+        && ix0 + int(BLOCK_X - 1u + (p.kw - 1u) * p.dil_w) < int(p.in_w);++    uint wrow[BLOCK_OC];+    for (uint i = 0u; i < BLOCK_OC; i++) {+        wrow[i] = p.weight + rows[i] * p.in_c * taps;+    }++    // Every row of the input starts at the same quad offset, so the window alignment+    // `rem` is one value for the whole dispatch.+    bool aligned_rows = p.stride_w == 1u && (p.in_w & 3u) == 0u && (p.in0 & 3u) == 0u;+    int rem = (int(p.in0) + ix0) & 3;+    if (aligned_rows && p.kw == 3u && p.dil_w == 1u) {+        DENSE_ROWS_ANY(3, 1)+    } else if (aligned_rows && p.kw == 3u && p.dil_w == 2u) {+        DENSE_ROWS_ANY(3, 2)+    } else if (aligned_rows && p.kw == 5u && p.dil_w == 1u) {+        DENSE_ROWS_ANY(5, 1)+    } else {+        for (uint ic = 0u; ic < p.in_c; ic++) {+            uint channel = p.in0 + ic * plane;+            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)) {+                    continue;+                }+                uint row = channel + uint(iy) * p.in_w;+                uint tap0 = ic * taps + ky * p.kw;+                for (uint kx = 0u; kx < p.kw; kx++) {+                    vec4 xl, xh;+                    columns_at(row, ix0 + int(kx * p.dil_w), interior, xl, xh);+                    for (uint i = 0u; i < BLOCK_OC; i++) {+                        float w = float(weights[wrow[i] + tap0 + kx]);+                        lo[i] += w * xl;+                        hi[i] += w * xh;+                    }+                }+            }+        }+    }++    uint positions = p.out_h * p.out_w;+    for (uint i = 0u; i < BLOCK_OC; i++) {+        uint channel = channel_base + i;+        if (channel >= p.out_c) {+            continue;+        }+        for (uint j = 0u; j < BLOCK_X; j++) {+            if (ox0 + j >= p.out_w) {+                continue;+            }+            uint index = channel * positions + oy * p.out_w + ox0 + j;+            float value = j < 4u ? lo[i][j] : hi[i][j - 4u];+            arena[p.out_at + index] = float16_t(fused_store(value, p.act, channel, index));+        }+    }+}
library/ml/src/main/rust/src/nets/mobilefacenet.rs
diff --git a/library/ml/src/main/rust/src/nets/mobilefacenet.rs b/library/ml/src/main/rust/src/nets/mobilefacenet.rsindex d5815841dd..043e1ea870 100644--- a/library/ml/src/main/rust/src/nets/mobilefacenet.rs+++ b/library/ml/src/main/rust/src/nets/mobilefacenet.rs@@ -116,6 +116,7 @@ fn transition(b: &mut Builder, l: &mut Layers, x: Id, wide: u32, out: u32) -> Id /// Compile the whole forward pass. pub fn build(weights: &dyn WeightSource) -> Result<Plan, String> {     let mut b = Builder::new(weights);+    b.spatial_tiling();     let mut layers = Layers { next: 0 };     let l = &mut layers;     let input = b.input(Shape::new(3, SIZE, SIZE));
library/ml/src/main/rust/src/nets/mod_part11.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part11.rs b/library/ml/src/main/rust/src/nets/mod_part11.rsindex bb16966795..044ece26ef 100644--- a/library/ml/src/main/rust/src/nets/mod_part11.rs+++ b/library/ml/src/main/rust/src/nets/mod_part11.rs@@ -69,6 +69,31 @@ pub(crate) mod tests {         assert_eq!(tile_of("attn_apply.comp"), ATTN_TILE);     } +    /// The spatial block constants must equal the `conv_tiled.glsl` geometry: Rust+    /// dispatches one invocation per `BLOCK_OC x BLOCK_X` block and the shader owns+    /// that block. A mismatch leaves outputs unwritten, which only the device parity+    /// fixtures would catch.+    #[test]+    fn the_spatial_tiles_match_their_shader() {+        let path =+            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("shaders").join("conv_tiled.glsl");+        let source = std::fs::read_to_string(&path).expect("the tiled conv include reads");+        let define = |name: &str| {+            source+                .lines()+                .find_map(|line| {+                    line.trim_start().strip_prefix("#define ").and_then(|rest| {+                        rest.strip_prefix(name).and_then(|value| {+                            value.trim().trim_end_matches('u').parse::<u32>().ok()+                        })+                    })+                })+                .unwrap_or_else(|| panic!("conv_tiled.glsl declares no {name}"))+        };+        assert_eq!(define("BLOCK_OC"), SPATIAL_BLOCK_OC);+        assert_eq!(define("BLOCK_X"), SPATIAL_BLOCK_X);+    }+     fn tile_of(shader: &str) -> u32 {         let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("shaders").join(shader);         let source = std::fs::read_to_string(&path).expect("the shader reads");
library/ml/src/main/rust/src/nets/mod_part2.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part2.rs b/library/ml/src/main/rust/src/nets/mod_part2.rsindex fb232ea2f8..dcda3e8944 100644--- a/library/ml/src/main/rust/src/nets/mod_part2.rs+++ b/library/ml/src/main/rust/src/nets/mod_part2.rs@@ -478,6 +478,9 @@ pub struct Builder<'a> {     read: Vec<bool>,     /// Whether convolutions replicate their border rather than reading zeros.     pad_edge: bool,+    /// Whether spatial convolutions lower to the register-blocked tiled path.+    /// See [`Builder::spatial_tiling`].+    spatial_tiled: bool, }  /// Arena allocations are aligned to this many fp16 elements, i.e. 16 bytes — the same
library/ml/src/main/rust/src/nets/mod_part3.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part3.rs b/library/ml/src/main/rust/src/nets/mod_part3.rsindex 852abee126..9ece7ecbb6 100644--- a/library/ml/src/main/rust/src/nets/mod_part3.rs+++ b/library/ml/src/main/rust/src/nets/mod_part3.rs@@ -16,21 +16,15 @@ const CONV_POINT_INT8_TILE: u32 = 32; /// **Must equal `TILE` in both.** Held by `the_attention_tiles_match_their_shaders`. const ATTN_TILE: u32 = 32; -/// `TILE_OC` in `shaders/conv_tiled.glsl`: output channels per workgroup.+/// `BLOCK_OC` in `shaders/conv_tiled.glsl`: output channels per invocation. ///-/// **Must equal `TILE_OC` there.** Held by `the_spatial_tiles_match_their_shader`.-const SPATIAL_TILE_OC: u32 = 32;+/// **Must equal `BLOCK_OC` there.** Held by `the_spatial_tiles_match_their_shader`.+const SPATIAL_BLOCK_OC: u32 = 4; -/// `TILE_POS` in `shaders/conv_tiled.glsl`: output positions per workgroup.+/// `BLOCK_X` in `shaders/conv_tiled.glsl`: adjacent output columns per invocation. ///-/// **Must equal `TILE_POS` there.** Held by the same test.-const SPATIAL_TILE_POS: u32 = 32;--/// `BLOCK` in `shaders/conv_tiled.glsl`: output channels and positions each-/// invocation of the tiled spatial path owns.-///-/// **Must equal `BLOCK` there.** Held by the same test.-const SPATIAL_BLOCK: u32 = 4;+/// **Must equal `BLOCK_X` there.** Held by the same test.+const SPATIAL_BLOCK_X: u32 = 8;  /// `ROWS` in `shaders/conv_vec_int8.comp`: output channels per workgroup. ///
library/ml/src/main/rust/src/nets/mod_part4.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part4.rs b/library/ml/src/main/rust/src/nets/mod_part4.rsindex 0e8e0994dc..3f7620fa8d 100644--- a/library/ml/src/main/rust/src/nets/mod_part4.rs+++ b/library/ml/src/main/rust/src/nets/mod_part4.rs@@ -10,9 +10,23 @@ impl<'a> Builder<'a> {             error: None,             inputs: Vec::new(),             pad_edge: false,+            spatial_tiled: false,         }     } +    /// Lower dense spatial convolutions to the register-blocked path from here on.+    ///+    /// A builder-level mode like [`Builder::edge_padding`]: the vision nets set it once+    /// and every `group == 1` convolution lowers to one invocation per 4-channel x+    /// 8-column block (`shaders/conv_tiled.glsl`) instead of one per output element.+    /// Off by default, so nets that never opt in keep the dispatches they have today.+    ///+    /// Only [`Builder::conv`] consults it; [`Builder::conv_raw`] (graph-section+    /// lowering) leaves it off, which is the previous behaviour there.+    pub fn spatial_tiling(&mut self) {+        self.spatial_tiled = true;+    }+     /// 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
library/ml/src/main/rust/src/nets/mod_part9.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part9.rs b/library/ml/src/main/rust/src/nets/mod_part9.rsindex 023490c8f3..446a7c1498 100644--- a/library/ml/src/main/rust/src/nets/mod_part9.rs+++ b/library/ml/src/main/rust/src/nets/mod_part9.rs@@ -188,23 +188,16 @@ impl<'a> Builder<'a> {                     });                     return Ok(());                 }-                // A spatial convolution on the register-blocked tiled path, when the-                // net opted in with `Builder::spatial_tiling`. Same `Kind::Conv` and-                // the same push block the untiled path below writes — only `in1`-                // differs (1, which no untiled dispatch sets) and the invocation-                // count is workgroups rather than output elements. `conv.comp`-                // branches on `in1`, so a net that never opts in keeps the exact-                // dispatches it has today.-                //-                // Any kernel, stride, dilation and group: the tiled shader indexes-                // them all from the push block the way the untiled one does. The-                // exclusions are the ones it cannot share semantics with — a-                // transposed convolution (different weight layout) and edge-                // padding (a Supertonic mode vision never uses).-                if self.spatial_tiled && !*transpose && !*pad_edge {-                    let positions = so.h * so.w;-                    let tiles = so.c.div_ceil(SPATIAL_TILE_OC)-                        * positions.div_ceil(SPATIAL_TILE_POS);+                // A spatial convolution on the register-blocked path, when the net opted+                // in with `Builder::spatial_tiling`. Same `Kind::Conv` and push block as+                // the untiled path below; `in1` = 1 selects the path in `conv.comp` and+                // there is one invocation per 4-channel x 8-column block of a row.+                // Transposed convolutions (different weight layout), edge padding+                // (Supertonic only) and grouped convolutions stay untiled.+                if self.spatial_tiled && !*transpose && !*pad_edge && *group == 1 {+                    let blocks = so.c.div_ceil(SPATIAL_BLOCK_OC)+                        * so.h+                        * so.w.div_ceil(SPATIAL_BLOCK_X);                     ops.push(Op::Dispatch {                         kind: Kind::Conv,                         push: Push {@@ -237,8 +230,7 @@ impl<'a> Builder<'a> {                             shift: Self::fuse_offset(*shift, &at)?,                             ..Push::default()                         },-                        // One workgroup of 64 per tile, as for `Kind::ConvPoint`.-                        invocations: tiles * 64,+                        invocations: blocks,                     });                     return Ok(());                 }
library/ml/src/main/rust/src/nets/modnet.rs
diff --git a/library/ml/src/main/rust/src/nets/modnet.rs b/library/ml/src/main/rust/src/nets/modnet.rsindex 87df8973c8..3950b847d0 100644--- a/library/ml/src/main/rust/src/nets/modnet.rs+++ b/library/ml/src/main/rust/src/nets/modnet.rs@@ -140,6 +140,7 @@ fn ibnorm( /// Compile the whole forward pass. pub fn build(weights: &dyn WeightSource) -> Result<Plan, String> {     let mut b = Builder::new(weights);+    b.spatial_tiling();     let mut layers = Layers { next: 0 };     let l = &mut layers;     let input = b.input(Shape::new(3, SIZE, SIZE));
library/ml/src/main/rust/src/nets/ppocr_det.rs
diff --git a/library/ml/src/main/rust/src/nets/ppocr_det.rs b/library/ml/src/main/rust/src/nets/ppocr_det.rsindex 484b463a43..26813e7fbd 100644--- a/library/ml/src/main/rust/src/nets/ppocr_det.rs+++ b/library/ml/src/main/rust/src/nets/ppocr_det.rs@@ -152,6 +152,7 @@ fn compile(     }      let mut b = Builder::new(weights);+    b.spatial_tiling();     let mut layers = Layers { next: 0 };     let l = &mut layers;     let input = b.input(Shape::new(3, height, width));
library/ml/src/main/rust/src/nets/scrfd.rs
diff --git a/library/ml/src/main/rust/src/nets/scrfd.rs b/library/ml/src/main/rust/src/nets/scrfd.rsindex 9d74cdddd0..c18c8f1554 100644--- a/library/ml/src/main/rust/src/nets/scrfd.rs+++ b/library/ml/src/main/rust/src/nets/scrfd.rs@@ -171,6 +171,7 @@ pub fn build(weights: &dyn WeightSource, height: u32, width: u32) -> Result<Plan     }      let mut b = Builder::new(weights);+    b.spatial_tiling();     let mut layers = Layers { next: 0 };     let l = &mut layers;     let input = b.input(Shape::new(3, height, width));
library/ml/src/main/rust/src/nets/selfie.rs
diff --git a/library/ml/src/main/rust/src/nets/selfie.rs b/library/ml/src/main/rust/src/nets/selfie.rsindex f69f567be3..b801a2435d 100644--- a/library/ml/src/main/rust/src/nets/selfie.rs+++ b/library/ml/src/main/rust/src/nets/selfie.rs@@ -129,6 +129,7 @@ fn final_block(b: &mut Builder, layers: &mut Layers, deep: Id, skip: Id, channel /// Compile the whole forward pass. pub fn build(weights: &dyn WeightSource) -> Result<Plan, String> {     let mut b = Builder::new(weights);+    b.spatial_tiling();     let mut layers = Layers { next: 0 };     let l = &mut layers;     let input = b.input(Shape::new(3, SIZE, SIZE));
library/ml/src/main/rust/src/nets/u2netp.rs
diff --git a/library/ml/src/main/rust/src/nets/u2netp.rs b/library/ml/src/main/rust/src/nets/u2netp.rsindex db90234d3d..6faa35c674 100644--- a/library/ml/src/main/rust/src/nets/u2netp.rs+++ b/library/ml/src/main/rust/src/nets/u2netp.rs@@ -227,6 +227,7 @@ fn rsu4f(b: &mut Builder, layers: &mut Layers, x: Id) -> Id { /// maps — only `d0` is produced. `MlSegmentation.kt` never read the others. pub fn build(weights: &dyn WeightSource) -> Result<Plan, String> {     let mut b = Builder::new(weights);+    b.spatial_tiling();     let mut layers = Layers { next: 0 };     let l = &mut layers; 
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 cf449d62ca..329d316be3 100644--- a/library/ml/src/main/rust/src/vulkan/parity_part6.rs+++ b/library/ml/src/main/rust/src/vulkan/parity_part6.rs@@ -197,3 +197,110 @@ fn a_row_mode_global_avg_pool_agrees_with_the_reference() {         &[&input],     ); }++/// Build `record` with spatial tiling on and require every spatial `Kind::Conv` in the+/// plan to have taken the blocked path (`in1 == 1`), then run it both ways.+fn blocked_conv_agrees(+    what: &str,+    count: usize,+    shapes: &[Shape],+    inputs: &[&[f32]],+    record: impl FnOnce(&mut Builder, &[Id]) -> Id,+) {+    let source = Invented::new(count);+    let plan = build(&source, shapes, |b, ids| {+        b.spatial_tiling();+        record(b, ids)+    });+    let mut seen = 0;+    for op in &plan.ops {+        if let crate::nets::Op::Dispatch { kind: crate::nets::Kind::Conv, push, .. } = op {+            assert_eq!(push.in1, 1, "{what}: a Conv missed the blocked path: {push:?}");+            seen += 1;+        }+    }+    assert!(seen > 0, "{what}: the plan has no Conv");+    compare(what, plan, source.into_data(), inputs);+}++/// Odd input widths put every row at a different quad alignment, so the scalar+/// fallback runs; 6 output channels leave a half-empty channel block and 45 columns+/// leave a partial column block.+#[test]+#[ignore = "needs a Vulkan device"]+fn a_blocked_conv_over_unaligned_rows_agrees_with_the_reference() {+    let input = spread(5 * 29 * 45, 0.3);+    blocked_conv_agrees(+        "a blocked 3x3 over 45-wide rows",+        4,+        &[Shape::new(5, 29, 45)],+        &[&input],+        |b, ids| {+            let x = b.conv(ids[0], 0, 6, (3, 3), (1, 1), (1, 1), (1, 1, 1, 1), 1, Act::Relu);+            b.conv(x, 2, 7, (3, 3), (1, 1), (2, 2), (2, 2, 2, 2), 1, Act::None)+        },+    );+}++/// A U^2-Netp-like layer at a size the interpreter still runs quickly: 24 input+/// channels into 16 at 40x80, with a fused residual onto a second dense 3x3, so most+/// blocks are interior and the fused store indexes through the blocked layout.+#[test]+#[ignore = "needs a Vulkan device"]+fn a_blocked_conv_at_a_real_width_agrees_with_the_reference() {+    let input = spread(24 * 40 * 80, 1.7);+    blocked_conv_agrees(+        "a blocked 3x3 pair at 40x80",+        4,+        &[Shape::new(24, 40, 80)],+        &[&input],+        |b, ids| {+            let x = b.conv(ids[0], 0, 16, (3, 3), (1, 1), (1, 1), (1, 1, 1, 1), 1, Act::Relu);+            let y = b.conv(x, 2, 16, (3, 3), (1, 1), (1, 1), (1, 1, 1, 1), 1, Act::None);+            b.add(x, y)+        },+    );+}++/// Strided dense convolutions on the blocked path at ragged sizes: a stride-2 3x3+/// (scalar gather), a 5x5, and a stride-2 3x3 with the asymmetric stem padding.+#[test]+#[ignore = "needs a Vulkan device"]+fn blocked_strided_convs_agree_with_the_reference() {+    let input = spread(3 * 51 * 67, -0.6);+    blocked_conv_agrees(+        "blocked strided convs",+        6,+        &[Shape::new(3, 51, 67)],+        &[&input],+        |b, ids| {+            let x = b.conv(ids[0], 0, 12, (3, 3), (2, 2), (1, 1), (1, 1, 1, 1), 1, Act::HardSwish);+            let x = b.conv(x, 2, 12, (5, 5), (1, 1), (1, 1), (2, 2, 2, 2), 1, Act::Relu);+            b.conv(x, 4, 12, (3, 3), (2, 2), (1, 1), (0, 0, 1, 1), 1, Act::Relu)+        },+    );+}+/// The aligned-window path at every quad offset and kernel shape it specialises:+/// left pads 0, 3, 1 and 2 put the window start at offsets 0, 1, 3 and 2; then a+/// dilated 3x3, a 5x5 and a stride (2, 1) 3x3. 48 and 64 columns keep the rows quad+/// aligned so these take the window path rather than the scalar fallback.+#[test]+#[ignore = "needs a Vulkan device"]+fn blocked_convs_at_every_window_alignment_agree_with_the_reference() {+    let input = spread(6 * 20 * 48, 0.9);+    blocked_conv_agrees(+        "blocked convs at every window alignment",+        14,+        &[Shape::new(6, 20, 48)],+        &[&input],+        |b, ids| {+            let x = b.conv(ids[0], 0, 8, (3, 3), (1, 1), (1, 1), (1, 0, 1, 2), 1, Act::Relu);+            let x = b.conv(x, 2, 8, (3, 3), (1, 1), (1, 1), (1, 3, 1, 5), 1, Act::None);+            let x = b.conv(x, 4, 8, (3, 3), (1, 1), (1, 1), (1, 1, 1, 1), 1, Act::Relu);+            let x = b.conv(x, 6, 8, (3, 3), (1, 1), (2, 2), (2, 2, 2, 2), 1, Act::Relu);+            let x = b.conv(x, 8, 8, (5, 5), (1, 1), (1, 1), (2, 2, 2, 2), 1, Act::Relu);+            let x = b.conv(x, 10, 8, (3, 3), (2, 1), (1, 1), (1, 1, 1, 1), 1, Act::Relu);+            b.conv(x, 12, 5, (3, 3), (1, 1), (1, 1), (1, 1, 1, 1), 1, Act::Sigmoid)+        },+    );+}