Modern Apps git

← Modern-Apps.git

ml: int8 GEMM split path (2 rows/lane) for small GEMMs, sampler -24%

Commit
07fd683759b59a719bd791d2d6feda85868d984e
Author
vayun-mathur <[email protected]>
When
2026-10-26 00:18 UTC (1 month ago)
Parents
fc8c961

Diff

library/ml/src/main/rust/shaders/conv_point_int8.comp
diff --git a/library/ml/src/main/rust/shaders/conv_point_int8.comp b/library/ml/src/main/rust/shaders/conv_point_int8.compindex 697d7a2e87..6f66caaa0b 100644--- a/library/ml/src/main/rust/shaders/conv_point_int8.comp+++ b/library/ml/src/main/rust/shaders/conv_point_int8.comp@@ -66,7 +66,101 @@ layout(std430, binding = 0) readonly buffer ArenaQuad { /// Channels and positions per invocation. #define BLOCK 4u +/// Channels per invocation on the split path (`p.in1 == 1`).+#define SPLIT 2u++/// The wide path with two channels per invocation instead of four, for GEMMs whose 32 x 32 tiles+/// are too few to fill the GPU (Supertonic's sampler: 512 x 52 is 32 workgroups). Twice the+/// workgroups, each 16 channels x 32 positions. Every output sums the same terms in the same order+/// as the four-row path, so the result is bit-identical. Selected only when `in_c % 16 == 0` and+/// the weights are 16-byte aligned (see `nets`).+void split_rows() {+    uint tile = gl_WorkGroupID.y * gl_NumWorkGroups.x + gl_WorkGroupID.x;+    if (tile >= p.count) {+        return;+    }+    uint positions = p.out_h * p.out_w;+    uint tiles_across = (positions + TILE - 1u) / TILE;+    uint lid = gl_LocalInvocationID.x;+    uint channel_base = (tile / tiles_across) * (TILE / BLOCK * SPLIT) + (lid >> 3u) * SPLIT;+    uint position_base = (tile % tiles_across) * TILE + (lid & 7u) * BLOCK;+    if (position_base >= positions) {+        return;+    }+    uint rows16[SPLIT];+    for (uint i = 0u; i < SPLIT; i++) {+        uint row = min(channel_base + i, p.out_c - 1u);+        rows16[i] = (p.weight + ((row * p.in_c) >> 2u)) >> 2u;+    }+    vec4 sum[SPLIT];+    for (uint i = 0u; i < SPLIT; i++) {+        sum[i] = vec4(0.0);+    }+    if ((positions & 3u) == 0u && (p.in0 & 3u) == 0u) {+        uint quads = positions >> 2u;+        uint quad = (p.in0 + position_base) >> 2u;+        for (uint k = 0u; k < p.in_c; k += 16u) {+            uvec4 w[SPLIT];+            for (uint i = 0u; i < SPLIT; i++) {+                w[i] = weights128[rows16[i] + (k >> 4u)];+            }+            for (uint t = 0u; t < 16u; t++) {+                vec4 x = vec4(arena_quad[quad + (k + t) * quads]);+                for (uint i = 0u; i < SPLIT; i++) {+                    float tap = float(bitfieldExtract(int(w[i][t >> 2u]), int((t & 3u) << 3u), 8));+                    sum[i] += tap * x;+                }+            }+        }+    } else {+        uint first = p.in0 + position_base;+        uint last_quad = (p.in0 + p.in_c * positions - 1u) >> 2u;+        for (uint k = 0u; k < p.in_c; k += 16u) {+            uvec4 w[SPLIT];+            for (uint i = 0u; i < SPLIT; i++) {+                w[i] = weights128[rows16[i] + (k >> 4u)];+            }+            for (uint t = 0u; t < 16u; t++) {+                uint at = first + (k + t) * positions;+                uint q = at >> 2u;+                uint s = at & 3u;+                f16vec4 a = arena_quad[q];+                f16vec4 b = arena_quad[min(q + 1u, last_quad)];+                f16vec4 h = s == 0u ? a+                    : s == 1u ? f16vec4(a.yzw, b.x)+                    : s == 2u ? f16vec4(a.zw, b.xy)+                    : f16vec4(a.w, b.xyz);+                vec4 x = vec4(h);+                for (uint i = 0u; i < SPLIT; i++) {+                    float tap = float(bitfieldExtract(int(w[i][t >> 2u]), int((t & 3u) << 3u), 8));+                    sum[i] += tap * x;+                }+            }+        }+    }+    for (uint i = 0u; i < SPLIT; i++) {+        uint channel = channel_base + i;+        if (channel >= p.out_c) {+            continue;+        }+        float scale = float(weights[p.act_weight + channel]);+        float offset = float(weights[p.bias + channel]);+        for (uint j = 0u; j < BLOCK; j++) {+            if (position_base + j >= positions) {+                continue;+            }+            uint index = channel * positions + position_base + j;+            float value = quant_store(fused_store(sum[i][j] * scale + offset, p.act, channel, index));+            arena[p.out_at + index] = float16_t(value);+        }+    }+}+ void main() {+    if (p.in1 == 1u) {+        split_rows();+        return;+    }     uint tile = gl_WorkGroupID.y * gl_NumWorkGroups.x + gl_WorkGroupID.x;     if (tile >= p.count) {         return;
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 92e79a03ed..3cccc3c5b6 100644--- a/library/ml/src/main/rust/src/nets/mod_part3.rs+++ b/library/ml/src/main/rust/src/nets/mod_part3.rs@@ -11,6 +11,9 @@ const CONV_POINT_TILE: u32 = 16; /// register blocking and covers a larger tile - see its header. **Must equal `TILE` there.** const CONV_POINT_INT8_TILE: u32 = 32; +/// Int8 GEMMs with fewer 32 x 32 tiles than this take `conv_point_int8.comp`'s split path.+const CONV_POINT_INT8_SPLIT_BELOW: u32 = 256;+ /// `TILE` in the tiled modes of `shaders/attn_scores.comp` and `shaders/attn_apply.comp`. /// /// **Must equal `TILE` in both.** Held by `the_attention_tiles_match_their_shaders`.
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 db253e3708..f3e9ec6331 100644--- a/library/ml/src/main/rust/src/nets/mod_part9.rs+++ b/library/ml/src/main/rust/src/nets/mod_part9.rs@@ -70,9 +70,19 @@ impl<'a> Builder<'a> {                     (Quant::Q2K, true, false) => Kind::ConvPointQ2K,                     (Quant::Q2K, false, false) => Kind::ConvQ2K,                 };+                // Too few 32 x 32 tiles to fill the GPU: two channels per invocation instead of+                // four, bit-identical. See `split_rows` in conv_point_int8.comp. On a Pixel 8,+                // splitting everything under 256 tiles took Supertonic's sampler 2199 -> 1521 ms.+                let split = kind == Kind::ConvPointInt8+                    && si.c % 16 == 0+                    && *weight % 4 == 0+                    && int8_tiles < CONV_POINT_INT8_SPLIT_BELOW;                 // Workgroups for the staged kinds, output elements for the untiled one.                 let count = match kind {                     Kind::ConvVecInt8 | Kind::ConvVecInt4 | Kind::ConvVecQ2K => rows,+                    Kind::ConvPointInt8 if split => {+                        so.c.div_ceil(CONV_POINT_INT8_TILE / 2) * positions.div_ceil(CONV_POINT_INT8_TILE)+                    }                     Kind::ConvPointInt8 | Kind::ConvPointInt4 | Kind::ConvPointQ2K => int8_tiles,                     _ => so.len(),                 };@@ -80,6 +90,7 @@ impl<'a> Builder<'a> {                     kind,                     push: Push {                         in0: at(*input)?,+                        in1: u32::from(split),                         out: at(*out)?,                         // A word offset, not an fp16 one: int8 is unpacked through the                         // 32-bit view of the weights buffer.
library/ml/src/main/rust/src/nets/supertonic_sampler_part1.rs
diff --git a/library/ml/src/main/rust/src/nets/supertonic_sampler_part1.rs b/library/ml/src/main/rust/src/nets/supertonic_sampler_part1.rsindex 9dcac590e6..4b8d140828 100644--- a/library/ml/src/main/rust/src/nets/supertonic_sampler_part1.rs+++ b/library/ml/src/main/rust/src/nets/supertonic_sampler_part1.rs@@ -353,8 +353,10 @@ mod tests {         };         for op in &dual.ops[half..] {             match op {-                Op::Dispatch { push, .. } => {-                    for read in [push.in0, push.in1] {+                Op::Dispatch { kind, push, .. } => {+                    // `in1` is a path selector, not an operand, on the int8 GEMM.+                    let in1 = if *kind == Kind::ConvPointInt8 { 0 } else { push.in1 };+                    for read in [push.in0, in1] {                         // `in1` is only meaningful on binary ops; the fused sentinel                         // and the zero default of non-binary pushes are not reads.                         if read == NO_FUSE || (read == 0 && push.in0 != 0) {
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 d23fbc4740..b481626a3a 100644--- a/library/ml/src/main/rust/src/vulkan/parity_part6.rs+++ b/library/ml/src/main/rust/src/vulkan/parity_part6.rs@@ -431,4 +431,41 @@ fn blocked_2x2_transposed_convs_agree_with_the_reference() {     }     assert_eq!(seen, 3);     compare("blocked 2x2 transposed convs", plan, source.into_data(), &[&input]);-}\ No newline at end of file+}++/// `conv_point_int8.comp`'s split path (`in1` = 1, two channels per invocation), which a GEMM+/// with fewer than 128 32 x 32 tiles takes: 40 channels leave the last 16-channel tile part empty,+/// and 52 / 49 positions cover the aligned and the ragged activation loads.+#[test]+#[ignore = "needs a Vulkan device"]+fn a_split_int8_gemm_agrees_with_the_reference() {+    let (out_channels, in_channels) = (40u32, 64u32);+    let kernel: Vec<i8> =+        (0..(out_channels * in_channels) as i32).map(|i| ((i * 37) % 251 - 125) as i8).collect();+    let scales: Vec<f32> = (0..out_channels).map(|c| 0.007_812_5 * (1.0 + (c % 7) as f32)).collect();+    let blob = write_mixed(+        graph::SUPERTONIC_VE,+        &[+            Fixture::I8(vec![out_channels, in_channels, 1, 1], kernel),+            Fixture::F16(vec![out_channels], scales),+            Fixture::F16(vec![out_channels], spread(out_channels as usize, 0.5)),+        ],+    );+    let weights = Weights::parse(&blob, graph::SUPERTONIC_VE).expect("the fixture blob parses");+    for width in [52u32, 49] {+        let input = spread((in_channels * width) as usize, 1.3);+        let mut builder = Builder::new(&weights);+        let first = builder.input(Shape::new(in_channels, 1, width));+        let last = builder.conv_int8(+            first, 0, out_channels, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 1, Act::Gelu,+        );+        let plan = builder.finish(&[last]).expect("the split plan builds");+        assert!(plan.ops.iter().any(|op| matches!(+            op,+            crate::nets::Op::Dispatch { kind: crate::nets::Kind::ConvPointInt8, push, .. }+                if push.in1 == 1+        )));+        let what = format!("a split int8 gemm over {width}");+        compare(&what, plan, weights.data().to_vec(), &[&input]);+    }+}