Modern Apps git

← Modern-Apps.git

ml: wide uvec4 int4 GEMV, gemma4 decode infer 124 -> 76 ms on Pixel

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

Diff

library/ml/src/main/rust/shaders/conv_vec_int4.comp
diff --git a/library/ml/src/main/rust/shaders/conv_vec_int4.comp b/library/ml/src/main/rust/shaders/conv_vec_int4.compindex f7ba5cce59..eb5f17c263 100644--- a/library/ml/src/main/rust/shaders/conv_vec_int4.comp+++ b/library/ml/src/main/rust/shaders/conv_vec_int4.comp@@ -1,183 +1,113 @@ #version 450 //! `conv_vec_int8.comp` for a **4-bit** kernel with **per-block** scales. //!-//! # What differs from the int8 gemv+//! The scale table is rank 2, `(out_channels, ceil(in_c / I4_BLOCK))`, at `p.act_weight`, so the+//! scale multiplies each block's partial sum rather than the finished accumulator. //!-//! Only where the scale is applied. An int8 kernel has one scale per output row, so it multiplies-//! the finished accumulator once. Four bits cannot hold a row's dynamic range at one scale, so-//! there is one per block of `I4_BLOCK` taps along the contraction axis, and the scale has to-//! reach the product rather than the total.+//! # Lane layout //!-//! The scale table is rank 2, `(out_channels, ceil(in_c / I4_BLOCK))`, at `p.act_weight` - the-//! same push field the int8 shaders use for their per-row scale, since it means the same thing-//! one rank up.-//!-//! # The lane pattern is unchanged, and that costs a fetch-//!-//! Lanes stride by 64 over the contraction axis, which is right for coalescing and wrong for-//! block reuse: at `I4_BLOCK` 32 a lane's block changes on every iteration, so the scale is-//! fetched per tap per row rather than hoisted per block. Fetching it from the fp16 view is a-//! cached read and the alternative - giving each lane a contiguous chunk so its blocks are-//! consecutive - trades that for uncoalesced weight reads, which is the worse end of the deal at-//! these widths. Worth re-measuring if this ever becomes the bottleneck; it is written the simple-//! way deliberately.+//! A workgroup owns [`ROWS`] output channels. Lane `l` owns the row pair `2 * (l % 4)` and+//! `2 * (l % 4) + 1` and the blocks `l / 4, l / 4 + 16, ...`. Every Gemma projection has a block+//! count divisible by 16 (48, 64, 192, 384), so all 64 lanes do the same work; the previous+//! layout (a lane per block, all eight rows) left 16 of 64 lanes idle at `in_c` 1536 and re-read+//! the activations per row. Here one block is two `uvec4` weight loads and eight read-only+//! `f16vec4` activation loads shared by both rows. //! //! # Push fields //! //! As `conv_vec_int8.comp`: `p.weight` is a 32-bit **word** offset, `p.act_weight` the scale //! table, `p.bias` the bias, `p.in_c` the taps, `p.out_c` the output channels and `p.count` the //! workgroup count, one per group of [`ROWS`] channels.--// Reductions happen in registers across a subgroup rather than through shared memory across the-// whole workgroup. See the tail of `main` for why that is worth an extension requirement.-#extension GL_KHR_shader_subgroup_basic : require-#extension GL_KHR_shader_subgroup_arithmetic : require #include "common.glsl" -/// Output channels one workgroup owns.-///-/// Eight, not two. At `I4_BLOCK` 32 a 64-lane workgroup strides 2048 taps, so the-/// loop below runs once for every projection narrower than 2048 — which is 71% of a-/// decode step's bytes — and a wave's whole life is two loads, one dependent ALU-/// burst, a barrier, and exit, with nothing to overlap. Eight rows give the same-/// workgroup eight independent (load, unpack, accumulate) chains per iteration, so-/// iteration N+1's loads issue while iteration N's ALU runs. Measured on the probe-/// harness (`analysis/gemv_probe`, variant H against G); unmeasured on a shipped-/// device, which is why `report_gemv_scaling` exists.-///-/// Eight divides the workgroup count by four against `ROWS` 2. That costs occupancy-/// where the output is narrow — see the table below — and buys the stream where it-/// is wide, which is where the bytes are.-///-/// | `out` | workgroups | vs 448 warp slots | share of decode bytes |-/// | ---: | ---: | :--- | :--- |-/// | 256 | 32 | 0.3x — idle | 1.7%, gate/kv sliding |-/// | 1536 | 192 | 1.7x thin | 29.3%, `down` + projections |-/// | 12288+ | 1536+ | 13.7x+ comfortable | 69%, `gate_up` + head |-///-/// `CONV_VEC_ROWS` in `nets/mod.rs` must equal this: Rust dispatches `out / ROWS`-/// workgroups, and disagreeing leaves channels never written. There is a test holding-/// that (`the_gemv_row_count_matches_both_shaders`).+/// The arena as quads of fp16, for the wide activation loads. Read-only, and never a range this+/// dispatch writes.+layout(std430, binding = 0) readonly buffer ArenaQuad {+    f16vec4 arena_quad[];+};++/// Output channels one workgroup owns. `CONV_VEC_INT4_ROWS` in `nets` must equal this. #define ROWS 8u -/// Per-lane partial sums, one row of 64 per output channel.-///-/// 8 KB at `ROWS` 8, against 16 KB of guaranteed `maxComputeSharedMemorySize`. Half-/// the guarantee, and the reason `ROWS` stops here rather than at 16: doubling again-/// would take the whole budget for the partials alone, before the driver accounts-/// for anything else it stages.-shared float partial[ROWS][64];+shared float partial[2][64];++/// The eight sign-extended nibbles of `bits` dotted with eight activations.+float dot8(uint bits, vec4 lo, vec4 hi) {+    ivec4 v = ivec4(bits);+    vec4 a = vec4((v << ivec4(28, 24, 20, 16)) >> 28);+    vec4 b = vec4((v << ivec4(12, 8, 4, 0)) >> 28);+    return dot(a, lo) + dot(b, hi);+}  void main() {     uint tile = gl_WorkGroupID.y * gl_NumWorkGroups.x + gl_WorkGroupID.x;     if (tile >= p.count) {         return;     }-    uint channel_base = tile * ROWS;     uint lane = gl_LocalInvocationID.x;+    uint channel_base = tile * ROWS;     uint blocks = (p.in_c + I4_BLOCK - 1u) / I4_BLOCK;-    float acc[ROWS];-    for (uint r = 0u; r < ROWS; r++) {-        acc[r] = 0.0;-    }-    // A lane owns whole blocks rather than a stride-64 scatter, so each row's scale is fetched-    // once per 32 taps instead of once per tap.-    //-    // The scatter was the obvious pattern and it made the scale the dominant cost: at-    // `I4_BLOCK` 32 a stride-64 lane lands in a different block on every iteration, so nothing-    // could be reused and the inner loop did two loads per weight - the nibble and its scale.-    // This does 32 nibbles against one scale per row.-    //-    // Coalescing survives the change. A lane reads 32 consecutive nibbles, which is 16 bytes,-    // and neighbouring lanes are 16 bytes apart - so a warp still sweeps one contiguous run.-    for (uint base = lane * I4_BLOCK; base < p.in_c; base += 64u * I4_BLOCK) {-        uint block = base / I4_BLOCK;-        float scale[ROWS];-        for (uint r = 0u; r < ROWS; r++) {-            scale[r] = int4_scale(channel_base + r, block, blocks);+    // Rows past the output read the last row and are dropped at the store.+    uint row0 = min(channel_base + 2u * (lane & 3u), p.out_c - 1u);+    uint row1 = min(channel_base + 2u * (lane & 3u) + 1u, p.out_c - 1u);+    float acc0 = 0.0;+    float acc1 = 0.0;+    bool wide = (p.in_c & 31u) == 0u && (p.weight & 3u) == 0u && (p.in0 & 3u) == 0u;+    if (wide) {+        uint per_row = p.in_c >> 5u;+        uint w0 = (p.weight >> 2u) + row0 * per_row;+        uint w1 = (p.weight >> 2u) + row1 * per_row;+        uint quad0 = p.in0 >> 2u;+        for (uint block = lane >> 2u; block < blocks; block += 16u) {+            uint q = quad0 + block * 8u;+            vec4 x0 = vec4(arena_quad[q]);+            vec4 x1 = vec4(arena_quad[q + 1u]);+            vec4 x2 = vec4(arena_quad[q + 2u]);+            vec4 x3 = vec4(arena_quad[q + 3u]);+            vec4 x4 = vec4(arena_quad[q + 4u]);+            vec4 x5 = vec4(arena_quad[q + 5u]);+            vec4 x6 = vec4(arena_quad[q + 6u]);+            vec4 x7 = vec4(arena_quad[q + 7u]);+            uvec4 a = weights128[w0 + block];+            uvec4 b = weights128[w1 + block];+            float s0 = dot8(a.x, x0, x1) + dot8(a.y, x2, x3) + dot8(a.z, x4, x5) + dot8(a.w, x6, x7);+            float s1 = dot8(b.x, x0, x1) + dot8(b.y, x2, x3) + dot8(b.z, x4, x5) + dot8(b.w, x6, x7);+            acc0 += s0 * int4_scale(row0, block, blocks);+            acc1 += s1 * int4_scale(row1, block, blocks);         }-        uint last = min(base + I4_BLOCK, p.in_c);-        // Eight nibbles a word, unpacked once.-        //-        // `int4_at` loads a whole 32-bit word to extract four bits, so calling it per tap read-        // the same word eight times. The compiler cannot hoist that - the loads are indexed by-        // a loop variable through a storage buffer, so it must assume they may differ. On a-        // desktop the cache hid it; on a phone this is the dominant kernel and the redundancy-        // is eight times the weight traffic it needs.-        //-        // A block is 32 nibbles at a 32-aligned start, so it is exactly four whole words and-        // no nibble straddles the boundary.-        // A whole block in one 16-byte load, when the row lets us.-        //-        // `I4_BLOCK` is 32 nibbles, which is exactly one `uvec4`. Fetching it that way instead of-        // four separate words is four times fewer memory instructions for identical bytes - and-        // on a Tensor G4 that is close to four times the throughput: a gemv reading words-        // reaches 4.7 GB/s where a shader reading `uvec4` reaches 19.6.-        //-        // Only when a row's blocks start 16-byte aligned, which needs `in_c` to be a multiple of-        // 32 since a row begins at `channel * in_c`. Every projection in this model satisfies-        // that; the scalar path below is kept for the ones that will not.-        // `p.weight` counts 32-bit words, so a `uvec4` index is `p.weight / 4` plus the-        // nibble offset over 32. Both divisions must be exact or the load straddles: hence the-        // alignment checks rather than a bare shift.-        bool wide = (p.in_c & 31u) == 0u && (p.weight & 3u) == 0u && (last - base) == I4_BLOCK;-        if (wide) {-            for (uint r = 0u; r < ROWS; r++) {-                uvec4 packed = weights128[p.weight / 4u + ((channel_base + r) * p.in_c + base) / 32u];+    } else {+        // Any `in_c` or alignment: a row starts wherever `channel * in_c` puts it, so a block's+        // nibbles can straddle words; walk word by word and take only what each word holds.+        for (uint block = lane >> 2u; block < blocks; block += 16u) {+            uint base = block * I4_BLOCK;+            uint span = min(base + I4_BLOCK, p.in_c) - base;+            for (uint r = 0u; r < 2u; r++) {+                uint channel = r == 0u ? row0 : row1;+                uint row = channel * p.in_c;                 float total = 0.0;-                for (uint word = 0u; word < 4u; word++) {-                    uint bits = packed[word];-                    for (uint n = 0u; n < 8u; n++) {-                        int code = bitfieldExtract(int(bits), int(n << 2u), 4);-                        total += float(code) * float(arena[p.in0 + base + word * 8u + n]);+                uint taken = 0u;+                while (taken < span) {+                    uint at = row + base + taken;+                    uint word = weights32[p.weight + (at >> 3u)];+                    uint offset = at & 7u;+                    uint run = min(8u - offset, span - taken);+                    for (uint n = 0u; n < run; n++) {+                        int code = bitfieldExtract(int(word), int((offset + n) << 2u), 4);+                        total += float(code) * float(arena[p.in0 + base + taken + n]);                     }+                    taken += run;                 }-                acc[r] += total * scale[r];-            }-            continue;-        }-        for (uint r = 0u; r < ROWS; r++) {-            uint row = (channel_base + r) * p.in_c;-            float total = 0.0;-            uint taken = 0u;-            uint span = last - base;-            // A row starts wherever `channel * in_c` puts it, which is **not** a multiple of-            // eight in general - so a block's nibbles can straddle word boundaries and the first-            // one can sit part-way into a word. Walking word by word and taking only what this-            // word holds is what makes that safe; assuming four aligned words per block passes-            // for even channels and reads the wrong nibbles for odd ones.-            while (taken < span) {-                uint at = row + base + taken;-                uint word = weights32[p.weight + (at >> 3u)];-                uint offset = at & 7u;-                uint run = min(8u - offset, span - taken);-                for (uint n = 0u; n < run; n++) {-                    // Sign-extended from four bits, as `int4_at` does.-                    int code = bitfieldExtract(int(word), int((offset + n) << 2u), 4);-                    total += float(code) * float(arena[p.in0 + base + taken + n]);+                float scaled = total * int4_scale(channel, block, blocks);+                if (r == 0u) {+                    acc0 += scaled;+                } else {+                    acc1 += scaled;                 }-                taken += run;             }-            acc[r] += total * scale[r];-        }-    }-    // Reduce inside each subgroup first, then across the few subgroups a workgroup holds.-    //-    // On a Mali G715 the subgroup is 16 wide, so a 64-lane workgroup is four of them-    // and the barrier below is a real cross-subgroup sync — paid once per output tile,-    // inside every weight kernel of a decode step.-    //-    // `subgroupAdd` does the first 16 in registers with no barrier, leaving-    // `gl_NumSubgroups` values to combine instead of 64.-    //-    // At `ROWS` 8 the tail loop below reads `partial[lane][0..4]`, one row per-    // finishing lane. Lanes 8..63 return after the barrier; only lanes 0..8 store.-    for (uint r = 0u; r < ROWS; r++) {-        float summed = subgroupAdd(acc[r]);-        if (subgroupElect()) {-            partial[r][gl_SubgroupID] = summed;         }     }+    partial[0][lane] = acc0;+    partial[1][lane] = acc1;     barrier();     if (lane >= ROWS) {         return;@@ -186,11 +116,13 @@ void main() {     if (channel >= p.out_c) {         return;     }+    // Row `lane` lives in slot `lane & 1` of the lanes congruent to `lane / 2` mod 4.+    uint pair = lane >> 1u;+    uint slot = lane & 1u;     float total = 0.0;-    for (uint i = 0u; i < gl_NumSubgroups; i++) {-        total += partial[lane][i];+    for (uint i = 0u; i < 16u; i++) {+        total += partial[slot][pair + 4u * i];     }-    // Already scaled inside the loop, so only the bias is left.     float offset = float(weights[p.bias + channel]);     arena[p.out_at + channel] = float16_t(quant_store(fused_store(total + offset, p.act, channel, channel))); }
library/ml/src/main/rust/src/vulkan/parity_part7.rs
diff --git a/library/ml/src/main/rust/src/vulkan/parity_part7.rs b/library/ml/src/main/rust/src/vulkan/parity_part7.rsindex a6df4c44af..2419a32cd6 100644--- a/library/ml/src/main/rust/src/vulkan/parity_part7.rs+++ b/library/ml/src/main/rust/src/vulkan/parity_part7.rs@@ -280,4 +280,39 @@ fn a_ragged_prefill_gemm_agrees_with_the_reference() { fn an_unblocked_prefill_gemm_agrees_with_the_reference() {     // 100 taps is not a whole number of 32-tap blocks: the per-tap scalar path.     int4_gemm_fixture("an unblocked prefill gemm", 40, 100, 9, Act::None);+}+#[test]+#[ignore = "needs a Vulkan device"]+fn a_ragged_wide_int4_gemv_agrees_with_the_reference() {+    // 1056 taps is 33 blocks, so one lane group takes a third pass the others skip; 20 channels+    // leave four rows of the last workgroup to discard. Still the wide (`uvec4`) path.+    let out_channels = 20u32;+    let in_channels = 1056u32;+    let blocks = in_channels.div_ceil(32);+    let kernel: Vec<i8> =+        (0..(out_channels * in_channels) as i32).map(|i| ((i * 5 + i / 3) % 16 - 8) as i8).collect();+    let scales: Vec<f32> =+        (0..out_channels * blocks).map(|i| 0.015_625 * (1.0 + (i % 4) as f32)).collect();+    let blob = write_mixed(+        graph::SUPERTONIC_VE,+        &[+            Fixture::I4(vec![out_channels, in_channels, 1, 1], kernel),+            Fixture::F16(vec![out_channels, blocks], scales),+            Fixture::F16(vec![out_channels], spread(out_channels as usize, 0.9)),+        ],+    );+    let weights = Weights::parse(&blob, graph::SUPERTONIC_VE).expect("the int4 fixture parses");+    let input = spread(in_channels as usize, 0.6);+    let mut builder = Builder::new(&weights);+    let first = builder.input(Shape::new(in_channels, 1, 1));+    let last = builder.conv_int4(first, 0, out_channels, Act::None);+    let plan = builder.finish(&[last]).expect("the ragged gemv fixture plan builds");+    assert!(+        plan.ops.iter().any(|op| matches!(+            op,+            crate::nets::Op::Dispatch { kind: crate::nets::Kind::ConvVecInt4, .. }+        )),+        "a single-position int4 convolution must lower to the gemv shader",+    );+    compare("a ragged wide int4 gemv", plan, weights.data().to_vec(), &[&input]); }\ No newline at end of file