Modern Apps git

← Modern-Apps.git

ml: row-mode InstanceNorm/GlobalAvgPool emit + fixtures

Commit
758a8e725e110570827b491f7843cc3d40e12284
Author
vayun-mathur <[email protected]>
When
2026-10-25 21:52 UTC (1 month ago)
Parents
f3563c2

Diff

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 933c3f6aeb..852abee126 100644--- a/library/ml/src/main/rust/src/nets/mod_part3.rs+++ b/library/ml/src/main/rust/src/nets/mod_part3.rs@@ -16,6 +16,22 @@ 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.+///+/// **Must equal `TILE_OC` there.** Held by `the_spatial_tiles_match_their_shader`.+const SPATIAL_TILE_OC: u32 = 32;++/// `TILE_POS` in `shaders/conv_tiled.glsl`: output positions per workgroup.+///+/// **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;+ /// `ROWS` in `shaders/conv_vec_int8.comp`: output channels per workgroup. /// /// That shader is dispatched one workgroup per group of this many channels, so [`Builder::emit`]@@ -69,6 +85,23 @@ fn row_reduce(rows: u32, len: u32) -> (u32, u32) {     } } +/// [`row_reduce`] for a per-channel plane reduction (instance norm, global average+/// pool), whose rows are contiguous planes rather than strided channel gathers.+///+/// The threshold differs from [`row_reduce`]: a plane reduction's serial cost grows+/// with the plane, not the row count, so planes of at least [`ROW_REDUCE_MIN_LEN`]+/// elements go row mode however many channels there are — MODNet's 16-channel+/// 128x128 planes (16 ms each serially) are the case that motivated this. `count`+/// stays the channel count either way, so the reference interpreter and+/// `Kind::arena_reads` need no change.+fn row_reduce_plane(channels: u32, plane: u32) -> (u32, u32) {+    if plane >= ROW_REDUCE_MIN_LEN {+        (1, channels * ROW_REDUCE_LANES)+    } else {+        (0, channels)+    }+}+ /// Rows at least this long reduce one workgroup per row however many there are - for a softmax. /// /// A softmax row is contiguous, so lanes splitting it read consecutive elements and the row mode
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 57626264aa..64f05f7e85 100644--- a/library/ml/src/main/rust/src/nets/mod_part9.rs+++ b/library/ml/src/main/rust/src/nets/mod_part9.rs@@ -185,7 +185,61 @@ impl<'a> Builder<'a> {                             shift: Self::fuse_offset(*shift, &at)?,                             ..Push::default()                         },-                        // 64 invocations a workgroup, so this asks for exactly `tiles` of them.+                    // 64 invocations a workgroup, so this asks for exactly `tiles` of them.+                        invocations: tiles * 64,+                    });+                    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);+                    ops.push(Op::Dispatch {+                        kind: Kind::Conv,+                        push: Push {+                            in0: at(*input)?,+                            // The tiled selector. See `Push::in1`.+                            in1: 1,+                            out: at(*out)?,+                            weight: *weight,+                            bias: *bias,+                            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,+                            dil_h: dilation.0,+                            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,+                            count: so.len(),+                            res: Self::fuse_offset(*res, &at)?,+                            shift: Self::fuse_offset(*shift, &at)?,+                            ..Push::default()+                        },+                        // One workgroup of 64 per tile, as for `Kind::ConvPoint`.                         invocations: tiles * 64,                     });                     return Ok(());@@ -290,6 +344,10 @@ impl<'a> Builder<'a> {             }             Node::GlobalAvgPool { input, out } => {                 let (si, so) = (shape(*input), shape(*out));+                // One invocation per channel, each reducing over its own plane, so+                // the dispatch is the channel count — or, for large planes, one+                // workgroup each. See `row_reduce_plane`.+                let (kw, invocations) = row_reduce_plane(si.c, si.h * si.w);                 ops.push(Op::Dispatch {                     kind: Kind::GlobalAvgPool,                     push: Push {@@ -302,9 +360,10 @@ impl<'a> Builder<'a> {                         out_h: 1,                         out_w: 1,                         count: so.len(),+                        kw,                         ..Push::default()                     },-                    invocations: so.len(),+                    invocations,                 });             }             Node::Binary { kind, a, b, out } => {@@ -392,7 +451,9 @@ impl<'a> Builder<'a> {             Node::InstanceNorm { input, out, epsilon } => {                 let so = shape(*out);                 // One invocation per channel, each reducing over its own plane, so-                // the dispatch is the channel count rather than the element count.+                // the dispatch is the channel count rather than the element count —+                // or, for large planes, one workgroup each. See `row_reduce_plane`.+                let (kw, invocations) = row_reduce_plane(so.c, so.h * so.w);                 ops.push(Op::Dispatch {                     kind: Kind::InstanceNorm,                     push: Push {@@ -406,9 +467,10 @@ impl<'a> Builder<'a> {                         out_w: so.w,                         param1_bits: epsilon.to_bits(),                         count: so.c,+                        kw,                         ..Push::default()                     },-                    invocations: so.c,+                    invocations,                 });             }             Node::RmsNorm { input, out, gamma, epsilon, groups, res, quant_scale } => {
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 0cc844e97f..cf449d62ca 100644--- a/library/ml/src/main/rust/src/vulkan/parity_part6.rs+++ b/library/ml/src/main/rust/src/vulkan/parity_part6.rs@@ -1 +1,199 @@ // Device parity fixtures (vision and Supertonic work). See `parity.rs` for the helpers.++// Tiled spatial convolutions (`shaders/conv_tiled.glsl` via `Builder::spatial_tiling`).+//+// Each fixture builds a one- or two-op plan with tiling opted in and requires the+// device to agree with the host interpreter, which serves `Kind::Conv` from the+// untiled `conv` — so these compare the two shader paths against each other through+// the same oracle. Sizes are small enough for the debug interpreter but ragged+// against the 32x32 tile on purpose: channels, positions and rows that are not+// multiples of the tile are where the clamping and masking go wrong.+//+// Real-size coverage comes from `profile_vision` checksums on the Pixel (the bar+// requires end-to-end outputs unchanged there); a whole 320x320 map through the+// debug interpreter is hours, not a fixture.++/// A dense 3x3 at stride 1 with ragged channels and positions: 24 channels is three+/// quarters of a channel tile, 36x36 is 1296 positions with a 16 tail.+#[test]+#[ignore = "needs a Vulkan device"]+fn a_tiled_dense_conv_agrees_with_the_reference() {+    let input = spread(8 * 36 * 36, 0.0);+    agrees_invented(+        "a tiled dense 3x3",+        2,+        &[Shape::new(8, 36, 36)],+        &[&input],+        |b, ids| {+            b.spatial_tiling();+            b.conv(ids[0], 0, 24, (3, 3), (1, 1), (1, 1), (1, 1, 1, 1), 1, Act::Relu)+        },+    );+}++/// A strided 3x3 with the selfie stem's asymmetric padding: nothing above or left,+// one below and right. Symmetric padding gives the same output size and a mask+// shifted half a pixel, so the asymmetry is the thing under test.+#[test]+#[ignore = "needs a Vulkan device"]+fn a_tiled_strided_conv_keeps_its_asymmetric_padding() {+    let input = spread(8 * 32 * 32, 1.0);+    agrees_invented(+        "a tiled strided 3x3 with asymmetric pads",+        2,+        &[Shape::new(8, 32, 32)],+        &[&input],+        |b, ids| {+            b.spatial_tiling();+            b.conv(ids[0], 0, 16, (3, 3), (2, 2), (1, 1), (0, 0, 1, 1), 1, Act::Relu)+        },+    );+}++/// Depthwise 3x3s at strides 1 and 2, the SCRFD/MobileFaceNet shape: one group per+/// channel, so the kernel is `[channels, 1, 3, 3]` and each output channel must see+/// exactly one input channel.+#[test]+#[ignore = "needs a Vulkan device"]+fn tiled_depthwise_convs_agree_with_the_reference() {+    let input = spread(16 * 24 * 24, 2.0);+    agrees_invented(+        "tiled depthwise 3x3s",+        4,+        &[Shape::new(16, 24, 24)],+        &[&input],+        |b, ids| {+            b.spatial_tiling();+            let x = b.conv(ids[0], 0, 16, (3, 3), (1, 1), (1, 1), (1, 1, 1, 1), 16, Act::Relu);+            b.conv(x, 2, 16, (3, 3), (2, 2), (1, 1), (1, 1, 1, 1), 16, Act::Relu)+        },+    );+}++/// A dilated 3x3 (U^2-Netp's RSU bottoms) and a dense 5x5 (MODNet's branch heads),+/// both with ragged extents: 30x30 is 900 positions with a 4 tail.+#[test]+#[ignore = "needs a Vulkan device"]+fn tiled_dilated_and_5x5_convs_agree_with_the_reference() {+    let input = spread(12 * 30 * 30, 3.0);+    agrees_invented(+        "tiled dilated 3x3 and dense 5x5",+        4,+        &[Shape::new(12, 30, 30)],+        &[&input],+        |b, ids| {+            b.spatial_tiling();+            let x = b.conv(ids[0], 0, 12, (3, 3), (1, 1), (2, 2), (2, 2, 2, 2), 1, Act::Relu);+            b.conv(x, 2, 12, (5, 5), (1, 1), (1, 1), (2, 2, 2, 2), 1, Act::Relu)+        },+    );+}++/// A grouped 3x3 that is neither dense nor depthwise (two channels per group, the+/// MobileFaceNet stem shape), with a fused PReLU: the slope read is per channel,+// so a row-indexing error lands two layers on one slope's value.+#[test]+#[ignore = "needs a Vulkan device"]+fn a_tiled_grouped_conv_with_prelu_agrees_with_the_reference() {+    let input = spread(8 * 20 * 20, 4.0);+    agrees_invented(+        "a tiled grouped 3x3 with PReLU",+        3,+        &[Shape::new(8, 20, 20)],+        &[&input],+        |b, ids| {+            b.spatial_tiling();+            // Weight at 0, bias at 1, slope at 2: `conv` reads the bias after the+            // weight, and the slope index rides the activation.+            b.conv(ids[0], 0, 8, (3, 3), (1, 1), (1, 1), (1, 1, 1, 1), 4, Act::PRelu(2))+        },+    );+}++/// A tiled convolution whose consumer is a residual add: `Builder::finish` folds+/// the add into the tiled store via `res`, so this exercises the fused addend at+/// the tiled block's flat index rather than only the plain store.+#[test]+#[ignore = "needs a Vulkan device"]+fn a_tiled_conv_with_a_fused_residual_agrees_with_the_reference() {+    let input = spread(8 * 24 * 24, 5.0);+    agrees_invented(+        "a tiled 3x3 with a fused residual",+        2,+        &[Shape::new(8, 24, 24)],+        &[&input],+        |b, ids| {+            b.spatial_tiling();+            let projected =+                b.conv(ids[0], 0, 8, (3, 3), (1, 1), (1, 1), (1, 1, 1, 1), 1, Act::None);+            b.add(ids[0], projected)+        },+    );+}++/// A row-mode instance norm at a MODNet-like shape: 32 channels of 128x128.+/// Planes this large must take the workgroup-per-channel path (`row_reduce_plane`+/// selects it at 64+ elements); the fixture asserts the plan chose it, then+/// requires the device to agree with the reference.+#[test]+#[ignore = "needs a Vulkan device"]+fn a_row_mode_instance_norm_agrees_with_the_reference() {+    let input = spread(32 * 128 * 128, 0.7);+    let source = Invented::new(0);+    let plan = row_mode_plan(+        &source,+        &[Shape::new(32, 128, 128)],+        crate::nets::Kind::InstanceNorm,+        |b, ids| b.instance_norm(ids[0], 1e-5),+    );+    compare(+        "a row-mode instance norm, 32 channels of 128x128",+        plan,+        source.into_data(),+        &[&input],+    );+}++/// A row-mode instance norm at a ragged shape: 13 channels of 37x41, so neither+/// the channel count nor the plane is a multiple of anything convenient. Lanes+/// stride the plane, so partial workgroups and tail elements are the thing under+/// test.+#[test]+#[ignore = "needs a Vulkan device"]+fn a_ragged_row_mode_instance_norm_agrees_with_the_reference() {+    let input = spread(13 * 37 * 41, -0.4);+    let source = Invented::new(0);+    let plan = row_mode_plan(+        &source,+        &[Shape::new(13, 37, 41)],+        crate::nets::Kind::InstanceNorm,+        |b, ids| b.instance_norm(ids[0], 1e-5),+    );+    compare(+        "a ragged row-mode instance norm, 13 channels of 37x41",+        plan,+        source.into_data(),+        &[&input],+    );+}++/// A row-mode global average pool at a real size: the plan must choose the+/// workgroup-per-channel path and the device must agree with the reference.+#[test]+#[ignore = "needs a Vulkan device"]+fn a_row_mode_global_avg_pool_agrees_with_the_reference() {+    let input = spread(128 * 16 * 16, 1.3);+    let source = Invented::new(0);+    let plan = row_mode_plan(+        &source,+        &[Shape::new(128, 16, 16)],+        crate::nets::Kind::GlobalAvgPool,+        |b, ids| b.global_avg_pool(ids[0]),+    );+    compare(+        "a row-mode global average pool, 128 channels of 16x16",+        plan,+        source.into_data(),+        &[&input],+    );+}