Modern Apps git

← Modern-Apps.git

ml: rmsnorm tile mode for strided rows, gemma4 prefill RmsNorm 60 -> 31 ms

Commit
f3e2c21fc50e96113de103f413caef0f3100d6ae
Author
vayun-mathur <[email protected]>
When
2026-10-26 19:54 UTC (1 month ago)
Parents
596ec82

Diff

library/ml/src/main/rust/shaders/rmsnorm.comp
diff --git a/library/ml/src/main/rust/shaders/rmsnorm.comp b/library/ml/src/main/rust/shaders/rmsnorm.compindex 4b0d765bc3..08c75f7e33 100644--- a/library/ml/src/main/rust/shaders/rmsnorm.comp+++ b/library/ml/src/main/rust/shaders/rmsnorm.comp@@ -114,7 +114,132 @@ void row_mode() {     } } +/// [`tile_mode`] when positions come in aligned quads: a lane loads four adjacent positions at once+/// and sixteen lanes split the channels, so a lane makes a sixteenth of a channel walk where the+/// scalar tile made a quarter. The sixteen channel groups' sums add in a fixed order.+void quad_tile_mode(uint stride) {+    uint lane = gl_LocalInvocationID.x;+    uint quad = lane & 3u;+    uint part = lane >> 2u;+    uint row = reduce_row() * 16u + quad * 4u;+    bool live = row < p.count;+    uint groups = max(p.group, 1u);+    uint per_group = p.in_c / groups;+    uint base = (row / stride) * per_group;+    uint at_pos = row % stride;+    float epsilon = uintBitsToFloat(p.param1_bits);+    vec4 squares = vec4(0.0);+    if (live) {+        for (uint c = part; c < per_group; c += 16u) {+            vec4 v = vec4(arena_quad[(p.in0 + (base + c) * stride + at_pos) >> 2u]);+            squares += v * v;+        }+    }+    vec4 total = squares;+    uint slot = quad * 4u;+    for (uint q = 1u; q < 16u; q++) {+        if (part == q) {+            reduce_partial[slot] = squares.x;+            reduce_partial[slot + 1u] = squares.y;+            reduce_partial[slot + 2u] = squares.z;+            reduce_partial[slot + 3u] = squares.w;+        }+        barrier();+        if (part == 0u) {+            total += vec4(reduce_partial[slot], reduce_partial[slot + 1u], reduce_partial[slot + 2u],+                          reduce_partial[slot + 3u]);+        }+        barrier();+    }+    if (part == 0u) {+        reduce_partial[slot] = total.x;+        reduce_partial[slot + 1u] = total.y;+        reduce_partial[slot + 2u] = total.z;+        reduce_partial[slot + 3u] = total.w;+    }+    barrier();+    total = vec4(reduce_partial[slot], reduce_partial[slot + 1u], reduce_partial[slot + 2u],+                 reduce_partial[slot + 3u]);+    if (!live) {+        return;+    }+    vec4 inverse = 1.0 / sqrt(total / float(per_group) + epsilon);+    for (uint c = part; c < per_group; c += 16u) {+        uint at = (base + c) * stride + at_pos;+        vec4 v = vec4(arena_quad[(p.in0 + at) >> 2u]);+        vec4 scaled = v * inverse * float(weights[p.weight + c]);+        vec4 normed = vec4(quant_store(scaled.x), quant_store(scaled.y), quant_store(scaled.z),+                           quant_store(scaled.w));+        if (p.res != 0xFFFFFFFFu) {+            normed += vec4(arena_quad[(p.res + at) >> 2u]);+        }+        arena_quad[(p.out_at + at) >> 2u] = f16vec4(normed);+    }+}+/// Tile mode (`p.kw == 2`): a workgroup owns 16 consecutive rows and each quarter of its lanes a+/// quarter of the channels, so 16 adjacent lanes read 16 adjacent positions of one channel - one+/// 32-byte load where row mode makes 16 lanes read 16 channels a whole sequence apart. The four+/// quarters' sums add in a fixed order through `reduce_partial`, whatever the subgroup size.+void tile_mode() {+    uint stride = p.in_h * p.in_w;+    if ((stride & 3u) == 0u && (p.in0 & 3u) == 0u && (p.out_at & 3u) == 0u+        && (p.res == 0xFFFFFFFFu || (p.res & 3u) == 0u)) {+        quad_tile_mode(stride);+        return;+    }+    uint lane = gl_LocalInvocationID.x;+    uint slot = lane & 15u;+    uint quarter = lane >> 4u;+    uint position = reduce_row() * 16u + slot;+    bool live = position < p.count;+    uint groups = max(p.group, 1u);+    uint per_group = p.in_c / groups;+    uint base = (position / stride) * per_group;+    uint at_pos = position % stride;+    float epsilon = uintBitsToFloat(p.param1_bits);+    float squares = 0.0;+    if (live) {+        for (uint c = quarter; c < per_group; c += 4u) {+            float value = float(arena[p.in0 + (base + c) * stride + at_pos]);+            squares += value * value;+        }+    }+    float total = squares;+    for (uint q = 1u; q < 4u; q++) {+        if (quarter == q) {+            reduce_partial[slot] = squares;+        }+        barrier();+        if (quarter == 0u) {+            total += reduce_partial[slot];+        }+        barrier();+    }+    if (quarter == 0u) {+        reduce_partial[slot] = total;+    }+    barrier();+    total = reduce_partial[slot];+    if (!live) {+        return;+    }+    float inverse = 1.0 / sqrt(total / float(per_group) + epsilon);+    for (uint c = quarter; c < per_group; c += 4u) {+        uint at = (base + c) * stride + at_pos;+        float value = float(arena[p.in0 + at]);+        float gamma = float(weights[p.weight + c]);+        float normed = quant_store(value * inverse * gamma);+        if (p.res != 0xFFFFFFFFu) {+            normed += float(arena[p.res + at]);+        }+        arena[p.out_at + at] = float16_t(normed);+    }+} void main() {+    if (p.kw == 2u) {+        tile_mode();+        return;+    }     if (reduce_row_mode()) {         row_mode();         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 7b2a44e48c..7c6fc12fb5 100644--- a/library/ml/src/main/rust/src/nets/mod_part3.rs+++ b/library/ml/src/main/rust/src/nets/mod_part3.rs@@ -98,6 +98,20 @@ fn row_reduce(rows: u32, len: u32) -> (u32, u32) {     } } +/// [`row_reduce`] for an RMS norm over `rows` rows strided `stride` apart: tile mode+/// (`Push::kw` 2, 16 rows a workgroup, see `shaders/rmsnorm.comp`) once 16 adjacent positions+/// exist to share each load.+fn norm_reduce(rows: u32, len: u32, stride: u32) -> (u32, u32) {+    if stride >= NORM_TILE_ROWS && len >= ROW_REDUCE_MIN_LEN {+        (2, rows.div_ceil(NORM_TILE_ROWS) * ROW_REDUCE_LANES)+    } else {+        row_reduce(rows, len)+    }+}++/// Rows one tile-mode workgroup owns. `tile_mode` in `shaders/rmsnorm.comp` hard-codes it.+const NORM_TILE_ROWS: u32 = 16;+ /// [`row_reduce`] for a per-channel plane reduction (instance norm, global average /// pool), whose rows are contiguous planes rather than strided channel gathers. ///
library/ml/src/main/rust/src/nets/mod_part9c.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part9c.rs b/library/ml/src/main/rust/src/nets/mod_part9c.rsindex 9c0cd88afc..caf9763ad4 100644--- a/library/ml/src/main/rust/src/nets/mod_part9c.rs+++ b/library/ml/src/main/rust/src/nets/mod_part9c.rs@@ -116,10 +116,10 @@ impl<'a> Builder<'a> {             }             Node::RmsNorm { input, out, gamma, epsilon, groups, res, quant_scale } => {                 let so = shape(*out);-                // One invocation per group per position, reducing over that group's channels,-                // or one workgroup each when there are few. See `row_reduce`.+                // One invocation per group per position, one workgroup each when there are few,+                // or 16 positions a workgroup when they are strided. See `norm_reduce`.                 let positions = so.h * so.w * groups.max(&1);-                let (kw, invocations) = row_reduce(positions, so.c / groups.max(&1));+                let (kw, invocations) = norm_reduce(positions, so.c / groups.max(&1), so.h * so.w);                 // A folded residual addend, or NO_FUSE. Same contract as the                 // convolution kinds: `fused_store` in the shader adds                 // `arena[res + index]`, and `arena_reads` covers the range.
library/ml/src/main/rust/src/vulkan/parity_part12.rs
diff --git a/library/ml/src/main/rust/src/vulkan/parity_part12.rs b/library/ml/src/main/rust/src/vulkan/parity_part12.rsindex 6bf913e1ff..3ee039b5c0 100644--- a/library/ml/src/main/rust/src/vulkan/parity_part12.rs+++ b/library/ml/src/main/rust/src/vulkan/parity_part12.rs@@ -53,3 +53,23 @@ fn key_bounded_softmax_and_crop_agree_with_the_reference() {         compare(&format!("{keys} positions padded to {width}"), plan, source.into_data(), &[&real]);     } }+#[test]+#[ignore = "needs a Vulkan device"]+fn a_tile_mode_rms_norm_agrees_with_the_reference() {+    // Gemma 4's prefill norms: the hidden state at 208 and a ragged 200 positions (tiles that end+    // past the last row), and the grouped QK-norm at 37 positions, where tiles straddle heads.+    for (channels, groups, positions) in [(1536u32, 1u32, 208u32), (1536, 1, 200), (2048, 8, 37)] {+        let per_group = channels / groups;+        let input: Vec<f32> = spread((channels * positions) as usize, 0.9)+            .iter()+            .enumerate()+            .map(|(i, v)| v * ((i / (per_group * positions) as usize) as f32 + 1.0))+            .collect();+        let given = Given::new(&[(vec![per_group], spread(per_group as usize, 2.5))])+            .expect("the fixture tensors are consistent");+        let plan = ragged_plan(&given, &[Shape::new(channels, 1, positions)], crate::nets::Kind::RmsNorm, |b, ids| {+            b.rms_norm_grouped(ids[0], 0, 1e-6, groups)+        });+        compare(&format!("a tile-mode rms norm, {channels}/{groups} x {positions}"), plan, given.data().to_vec(), &[&input]);+    }+}