Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / library / ml / src / main / rust / shaders / conv_vec_int8.comp

conv_vec_int8.comp168 lines · 8.0 KiBRaw
1#version 450
2//! `conv_point_int8.comp` for a **single position**: a matrix-vector product, not a tiny matrix.
3//!
4//! `out[o] = act(scale[o] * sum_i W[o][i] * x[i] + bias[o])`.
5//!
6//! # Why the tiled shader is the wrong shape here
7//!
8//! `conv_point_int8.comp` tiles `16 x 16` over output channels and positions, so its workgroup
9//! count is `out_c.div_ceil(16) * positions.div_ceil(16)`. At **one** position the second factor is
10//! 1 and the tile is 16 channels by 16 positions of which 15 are padding, so:
11//!
12//! * Of 64 invocations, the 56 whose `local_col` is not 0 compute nothing that is stored. The
13//! workgroup produces 16 outputs where it is built to produce 256.
14//! * Each staging step zero-fills 240 of the 256 `input_tile` slots, and the activation vector is
15//! re-staged once per channel tile — 16 times over for a 256-channel output.
16//!
17//! That is roughly a 16x waste, and it lands on exactly the wrong op. A SMaLL-100 decode step is
18//! *entirely* single-position: 30 projections and the 128,112-class head, 128 times per
19//! translation, with the head alone at 131 million multiply-accumulates. Nothing else in a
20//! translation is close.
21//!
22//! # The shape that fits
23//!
24//! One workgroup per **group of [`ROWS`] output channels**, with the 64 lanes striding along the
25//! input channels:
26//!
27//! ```text
28//! for (k = lane; k < in_c; k += 64) // lane's slice of the activation
29//! x = arena[in0 + k] // read once, into a register
30//! for (r = 0; r < ROWS; r++) // reused by every row
31//! acc[r] += W[channel_base + r][k] * x
32//! ```
33//!
34//! Three things fall out:
35//!
36//! * **Every lane contributes to every output.** No idle lanes and no padding.
37//! * **The weight reads are coalesced.** Lane `l` reads `W[c][k0 + l]`, which is contiguous, and
38//! four adjacent lanes fall in one 32-bit word of the int8 view.
39//! * **The activation is read exactly once per workgroup** and reused from a register across all
40//! `ROWS` rows, rather than staged into shared memory `out_c / 16` times over. That is why there
41//! is no activation tile here: at one position a lane needs only the elements it strides over.
42//!
43//! What it costs is a cross-lane reduction, which the tiled shader does not need because each of
44//! its invocations owns a whole dot product. [`partial`] is the only shared memory, `ROWS * 64`
45//! floats, and lanes `0 .. ROWS` finish the sums. At 2 KB that is an eighth of the 16 KB
46//! `maxComputeSharedMemorySize` the spec guarantees.
47//!
48//! # Precision and the push block
49//!
50//! Identical to `conv_point_int8.comp`, deliberately: `nets::reference` serves all three int8 kinds
51//! from one implementation, so any difference here would be a difference from the oracle. fp32
52//! accumulation, the scale applied to the finished accumulator, then the bias, then the activation.
53//! `p.weight` is a **32-bit word** offset and `p.act_weight` the scale as an fp16 element index,
54//! which is why `Act::PRelu` cannot ride along.
55//!
56//! # Wide loads
57//!
58//! When `in_c % 16 == 0` and the weight and activation bases are 16-byte aligned - every
59//! projection and head here - each lane reads sixteen taps per row with one `uvec4` load and the
60//! matching sixteen activations with four `f16vec4` loads, reused across the rows. The byte-per-lane
61//! loop below it issued one load per tap per row; on a Pixel 8 it streamed NLLB's decode weights at
62//! 15 GB/s, 85% of a step.
63
64// See the tail of `main`, and `conv_vec_int4.comp` which does the same.
65#extension GL_KHR_shader_subgroup_basic : require
66#extension GL_KHR_shader_subgroup_arithmetic : require
67#include "common.glsl"
68
69/// The arena as quads of fp16, for the wide activation loads. Read-only, and never a range this
70/// dispatch writes.
71layout(std430, binding = 0) readonly buffer ArenaQuad {
72 f16vec4 arena_quad[];
73};
74
75/// Output channels per workgroup.
76///
77/// Eight rather than one because a workgroup per output channel would spend 64 lanes on a single
78/// dot product and reduce 64 partials for one number; eight amortises the reduction's barrier over
79/// eight outputs while keeping [`partial`] at 2 KB. It also bounds the register pressure at eight
80/// accumulators, which is what lets the activation stay in a register across the row loop.
81// Output channels one workgroup owns.
82//
83// # Why this is small
84//
85// Eight meant a 1,536-wide projection launched 192 workgroups - about 12k threads, barely over a
86// Mali G715's capacity, so there was nothing queued to run while a workgroup waited on memory.
87// The logits head launches 32,768 and reaches 14.9 GB/s; the per-layer projections reached 3.6.
88// Two gives four times the workgroups for the same weight traffic, at the cost of re-reading the
89// 3 KB activation vector four times more often - which is cache-resident and cheap beside the
90// megabytes of weights each one streams.
91#define ROWS 2u
92
93/// Per-lane partial sums, one row of 64 per output channel.
94shared float partial[ROWS][64];
95
96void main() {
97 // The channel group this workgroup owns. Uniform across the workgroup, so an early return
98 // cannot strand a barrier — every invocation takes the same branch.
99 uint tile = gl_WorkGroupID.y * gl_NumWorkGroups.x + gl_WorkGroupID.x;
100 if (tile >= p.count) {
101 return;
102 }
103 uint channel_base = tile * ROWS;
104 uint lane = gl_LocalInvocationID.x;
105
106 float acc[ROWS];
107 for (uint r = 0u; r < ROWS; r++) {
108 acc[r] = 0.0;
109 }
110 // Rows past the output are accumulated anyway and discarded at the store. Skipping them would
111 // branch inside the hot loop for at most seven channels of the last workgroup.
112 bool wide = (p.in_c & 15u) == 0u && (p.weight & 3u) == 0u && (p.in0 & 3u) == 0u;
113 if (wide) {
114 uint row16[ROWS];
115 for (uint r = 0u; r < ROWS; r++) {
116 uint channel = min(channel_base + r, p.out_c - 1u);
117 row16[r] = (p.weight + ((channel * p.in_c) >> 2u)) >> 2u;
118 }
119 uint quad0 = p.in0 >> 2u;
120 for (uint k = lane * 16u; k < p.in_c; k += 1024u) {
121 vec4 x0 = vec4(arena_quad[quad0 + (k >> 2u)]);
122 vec4 x1 = vec4(arena_quad[quad0 + (k >> 2u) + 1u]);
123 vec4 x2 = vec4(arena_quad[quad0 + (k >> 2u) + 2u]);
124 vec4 x3 = vec4(arena_quad[quad0 + (k >> 2u) + 3u]);
125 for (uint r = 0u; r < ROWS; r++) {
126 uvec4 w = weights128[row16[r] + (k >> 4u)];
127 acc[r] += dot(unpack_int8x4(w.x), x0) + dot(unpack_int8x4(w.y), x1)
128 + dot(unpack_int8x4(w.z), x2) + dot(unpack_int8x4(w.w), x3);
129 }
130 }
131 } else {
132 for (uint k = lane; k < p.in_c; k += 64u) {
133 float x = float(arena[p.in0 + k]);
134 for (uint r = 0u; r < ROWS; r++) {
135 acc[r] += float(int8_at(p.weight, (channel_base + r) * p.in_c + k)) * x;
136 }
137 }
138 }
139 // Reduce within each subgroup in registers, then across the handful a workgroup holds.
140 //
141 // The comment that stood here reasoned a log-step tree would cost six barriers to save 56
142 // adds, so the serial tail was fine. That weighed the wrong things: the cost was never the
143 // adds but the **one** cross-subgroup barrier and the 56 idle lanes behind it, and a
144 // subgroup reduction needs no barrier at all. Measured on a Mali G715, whose subgroup is 16
145 // wide, the per-layer projections reached 3.6 GB/s against the logits head's 14.9 - the head
146 // being the one kernel with enough work per tile to hide this.
147 for (uint r = 0u; r < ROWS; r++) {
148 float summed = subgroupAdd(acc[r]);
149 if (subgroupElect()) {
150 partial[r][gl_SubgroupID] = summed;
151 }
152 }
153 barrier();
154 if (lane >= ROWS) {
155 return;
156 }
157 uint channel = channel_base + lane;
158 if (channel >= p.out_c) {
159 return;
160 }
161 float total = 0.0;
162 for (uint i = 0u; i < gl_NumSubgroups; i++) {
163 total += partial[lane][i];
164 }
165 float scale = float(weights[p.act_weight + channel]);
166 float offset = float(weights[p.bias + channel]);
167 arena[p.out_at + channel] = float16_t(quant_store(fused_store(total * scale + offset, p.act, channel, channel)));
168}