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

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

conv_vec_q2k.comp265 lines · 12.7 KiBRaw
1#version 450
2//! `conv_vec_int8.comp` for a **GGUF Q2_K** kernel: a matrix-vector product over one position.
3//!
4//! `out[o] = act(sum over superblocks of (d_all*(q*lo) - d_min*hi) * x + bias[o])`.
5//!
6//! # What differs from the int4 gemv
7//!
8//! Only where the values come from. An int4 kernel has one scale per 32-tap block;
9//! Q2_K has a `(d, dmin)` fp16 pair per 256-tap superblock plus a scale byte per
10//! 16-tap lane, and the value is affine rather than scaled. The lane pattern is the
11//! int4 shader's whole-block walk: a lane owns whole 256-tap superblocks so each row's
12//! `(d, dmin)` is fetched once per block instead of once per tap.
13//!
14//! The scale table is rank 1, `(out * blocks * 2,)` flat — `(d, dmin)` pairs in
15//! row-major block order — at `p.act_weight`, the same push field the int8/int4
16//! shaders use for their scales. `p.in_c` is the taps; `blocks` is derived as
17//! `ceil(in_c / 256)`.
18//!
19//! # Push fields
20//!
21//! As `conv_vec_int4.comp`: `p.weight` is a 32-bit **word** offset to the Q2_K payload,
22//! `p.act_weight` the `(d, dmin)` table as an fp16 element index, `p.bias` the bias,
23//! `p.in_c` the taps, `p.out_c` the output channels and `p.count` the workgroup count,
24//! one per group of [`ROWS`] channels. The superblock byte offset of a row's block is
25//! derived from the two, since rows are contiguous runs of `blocks` superblocks.
26//!
27//! # Word-per-lane mode
28//!
29//! When `in_c % 256 == 0` and the activation base is 4-aligned - every MADLAD projection - a lane
30//! owns one 32-bit word of a superblock's `qs` rather than a whole superblock. That word holds the
31//! 2-bit codes of 16 taps: four bytes, each carrying one code for each of the half's four lanes.
32//! Owning whole superblocks left a 1,024-input projection with four of 64 lanes busy, and re-read
33//! every activation once per row; on a Pixel 8 that streamed MADLAD's weights at 0.6 GB/s and was
34//! 90% of a 2-second token. Here every lane is busy at 1,024 inputs, the sixteen activations are
35//! four `f16vec4` loads shared by all the rows, and the affine dequantisation factors out per
36//! 4-tap group: `sum((dall*lo*c - dmin*hi) * x) = dall*lo*dot(c, x) - dmin*hi*sum(x)`.
37
38// Reductions happen in registers across a subgroup rather than through shared memory across the
39// whole workgroup. See the tail of `main` for why that is worth an extension requirement.
40#extension GL_KHR_shader_subgroup_basic : require
41#extension GL_KHR_shader_subgroup_arithmetic : require
42#include "common.glsl"
43
44/// The arena as quads of fp16, for the word-per-lane activation loads.
45layout(std430, binding = 0) readonly buffer ArenaQuad {
46 f16vec4 arena_quad[];
47};
48
49/// The arena as 8 fp16 per element, for the pair-per-lane activation loads.
50layout(std430, binding = 0) readonly buffer ArenaOct {
51 uvec4 arena_oct[];
52};
53
54/// Output channels one workgroup owns.
55///
56/// Eight like the int4 gemv, for the same stream reason: a Q2_K superblock is wider than
57/// an int4 block, so fewer rows per workgroup would leave the same load-ALU overlap on
58/// the table. `CONV_VEC_Q2K_ROWS` in `nets/mod_part3.rs` must equal this: Rust dispatches
59/// `out / ROWS` workgroups, and disagreeing leaves channels never written. There is a test
60/// holding that (`the_q2k_gemv_row_count_matches_its_shader`).
61#define ROWS 8u
62
63/// Taps one Q2_K superblock covers. Mirrors `weights::Q2K_BLOCK`.
64#define Q2K_BLOCK 256u
65
66/// Per-lane partial sums, one row of 64 per output channel.
67///
68/// 8 KB at `ROWS` 8, against 16 KB of guaranteed `maxComputeSharedMemorySize`. Half
69/// the guarantee, and the reason `ROWS` stops here rather than at 16: doubling again
70/// would take the whole budget for the partials alone, before the driver accounts
71/// for anything else it stages.
72shared float partial[ROWS][64];
73
74void main() {
75 uint tile = gl_WorkGroupID.y * gl_NumWorkGroups.x + gl_WorkGroupID.x;
76 if (tile >= p.count) {
77 return;
78 }
79 uint channel_base = tile * ROWS;
80 uint lane = gl_LocalInvocationID.x;
81 uint blocks = (p.in_c + Q2K_BLOCK - 1u) / Q2K_BLOCK;
82 float acc[ROWS];
83 for (uint r = 0u; r < ROWS; r++) {
84 acc[r] = 0.0;
85 }
86 bool by_word = (p.in_c % Q2K_BLOCK) == 0u && (p.in0 & 3u) == 0u;
87 // Pair-per-lane: a lane owns two adjacent `qs` words (32 taps sharing four scale bytes) for
88 // four of the eight rows, so each row's scale words and `(d, dmin)` are fetched once per 32
89 // taps instead of 16, and the activations come in as two 16-byte loads per code lane.
90 bool by_pair = by_word && (p.in0 & 7u) == 0u && (p.act_weight & 1u) == 0u;
91 if (by_pair) {
92 uint row_half = lane >> 5u;
93 uint units = blocks * 8u;
94 float part[4];
95 for (uint r = 0u; r < 4u; r++) {
96 part[r] = 0.0;
97 }
98 for (uint unit = lane & 31u; unit < units; unit += 32u) {
99 uint block = unit >> 3u;
100 uint w = (unit & 7u) << 1u;
101 uint half_idx = w >> 3u;
102 uint odd = (w >> 2u) & 1u;
103 uint first = block * Q2K_BLOCK + half_idx * 128u + odd * 16u + (w & 3u) * 4u;
104 vec4 xa[4];
105 vec4 xb[4];
106 float xsum[4];
107 for (uint q = 0u; q < 4u; q++) {
108 uvec4 raw = arena_oct[(p.in0 + first + q * 32u) >> 3u];
109 xa[q] = vec4(unpackHalf2x16(raw.x), unpackHalf2x16(raw.y));
110 xb[q] = vec4(unpackHalf2x16(raw.z), unpackHalf2x16(raw.w));
111 vec4 s = xa[q] + xb[q];
112 xsum[q] = s.x + s.y + s.z + s.w;
113 }
114 for (uint r = 0u; r < 4u; r++) {
115 uint row = min(channel_base + row_half * 4u + r, p.out_c - 1u);
116 uint idx = row * blocks + block;
117 vec2 dm = unpackHalf2x16(weights32[(p.act_weight >> 1u) + idx]);
118 float dall = dm.x * dm.x;
119 float dmin = dm.y * dm.x;
120 uint sb = p.weight + idx * 21u;
121 uint c0 = weights32[sb + 4u + w];
122 uint c1 = weights32[sb + 5u + w];
123 uint scales_lo = weights32[sb + half_idx * 2u];
124 uint scales_hi = weights32[sb + half_idx * 2u + 1u];
125 float total = 0.0;
126 for (uint q = 0u; q < 4u; q++) {
127 uint word = q < 2u ? scales_lo : scales_hi;
128 uint sc = (word >> ((((q & 1u) << 1u) + odd) << 3u)) & 255u;
129 uint shift = q << 1u;
130 vec4 ca = vec4(float((c0 >> shift) & 3u), float((c0 >> (shift + 8u)) & 3u),
131 float((c0 >> (shift + 16u)) & 3u), float((c0 >> (shift + 24u)) & 3u));
132 vec4 cb = vec4(float((c1 >> shift) & 3u), float((c1 >> (shift + 8u)) & 3u),
133 float((c1 >> (shift + 16u)) & 3u), float((c1 >> (shift + 24u)) & 3u));
134 total += dall * float(sc & 15u) * (dot(ca, xa[q]) + dot(cb, xb[q]))
135 - dmin * float(sc >> 4u) * xsum[q];
136 }
137 part[r] += total;
138 }
139 }
140 for (uint r = 0u; r < ROWS; r++) {
141 acc[r] = (r >> 2u) == row_half ? part[r & 3u] : 0.0;
142 }
143 } else if (by_word) {
144 // 16 `qs` words per superblock, so this many units across the row.
145 uint units = blocks * 16u;
146 for (uint unit = lane; unit < units; unit += 64u) {
147 uint block = unit >> 4u;
148 uint w = unit & 15u;
149 uint half_idx = w >> 3u;
150 uint odd = (w >> 2u) & 1u;
151 uint quad = w & 3u;
152 // Taps `half*128 + q*32 + odd*16 + quad*4 + 0..3` for code lane `q` in 0..3.
153 uint first = block * Q2K_BLOCK + half_idx * 128u + odd * 16u + quad * 4u;
154 vec4 x[4];
155 float xsum[4];
156 for (uint q = 0u; q < 4u; q++) {
157 x[q] = vec4(arena_quad[(p.in0 + first + q * 32u) >> 2u]);
158 xsum[q] = x[q].x + x[q].y + x[q].z + x[q].w;
159 }
160 for (uint r = 0u; r < ROWS; r++) {
161 uint row = min(channel_base + r, p.out_c - 1u);
162 uint pair = p.act_weight + row * blocks * 2u + block * 2u;
163 float d = float(weights[pair]);
164 float m = float(weights[pair + 1u]);
165 float dall = d * d;
166 float dmin = m * d;
167 // The superblock as a word index: 84 bytes is 21 words.
168 uint sb = p.weight + (row * blocks + block) * 21u;
169 uint codes = weights32[sb + 4u + w];
170 // Scale bytes `half*8 + q*2 + odd`: lanes 0,1 in one word, 2,3 in the next.
171 uint scales_lo = weights32[sb + half_idx * 2u];
172 uint scales_hi = weights32[sb + half_idx * 2u + 1u];
173 float total = 0.0;
174 for (uint q = 0u; q < 4u; q++) {
175 uint word = q < 2u ? scales_lo : scales_hi;
176 uint sc = (word >> ((((q & 1u) << 1u) + odd) << 3u)) & 255u;
177 uint shift = q << 1u;
178 vec4 c = vec4(float((codes >> shift) & 3u), float((codes >> (shift + 8u)) & 3u),
179 float((codes >> (shift + 16u)) & 3u), float((codes >> (shift + 24u)) & 3u));
180 total += dall * float(sc & 15u) * dot(c, x[q]) - dmin * float(sc >> 4u) * xsum[q];
181 }
182 acc[r] += total;
183 }
184 }
185 } else {
186 // A lane owns whole superblocks rather than a stride-64 scatter, so each row's
187 // `(d, dmin)` is fetched once per 256 taps instead of once per tap.
188 //
189 // Coalescing survives the change. A lane reads 84 consecutive bytes, and neighbouring
190 // lanes are 84 bytes apart - so a warp still sweeps one contiguous run.
191 for (uint base = lane * Q2K_BLOCK; base < p.in_c; base += 64u * Q2K_BLOCK) {
192 uint block = base / Q2K_BLOCK;
193 float dall[ROWS];
194 float dmin[ROWS];
195 for (uint r = 0u; r < ROWS; r++) {
196 uint pair = p.act_weight + (channel_base + r) * blocks * 2u + block * 2u;
197 float d = float(weights[pair]);
198 float m = float(weights[pair + 1u]);
199 dall[r] = d * d;
200 dmin[r] = m * d;
201 }
202 uint last = min(base + Q2K_BLOCK, p.in_c);
203 for (uint r = 0u; r < ROWS; r++) {
204 // Superblock byte offset of this row's block: rows are contiguous runs of
205 // `blocks` superblocks, 84 bytes each, from the word offset `p.weight`.
206 uint sbo = (p.weight * 4u) + ((channel_base + r) * blocks + block) * 84u;
207 float total = 0.0;
208 uint span = last - base;
209 // The 256 taps are 2 halves of 128; each half is 4 lane-pairs of 16+16 taps
210 // at shifts 0/2/4/6. One scale byte per lane-pair, fetched once per 32 taps.
211 for (uint half_idx = 0u; half_idx < 2u; half_idx++) {
212 for (uint pair = 0u; pair < 4u; pair++) {
213 uint sc = q2k_scale(sbo, half_idx, pair * 2u);
214 uint sc2 = q2k_scale(sbo, half_idx, pair * 2u + 1u);
215 float lo = float(sc & 15u);
216 float hi = float(sc >> 4u);
217 float lo2 = float(sc2 & 15u);
218 float hi2 = float(sc2 >> 4u);
219 for (uint l = 0u; l < 16u; l++) {
220 uint tap = half_idx * 128u + pair * 32u + l;
221 if (tap >= span) {
222 break;
223 }
224 uint code = q2k_code(sbo, half_idx, tap);
225 total += (dall[r] * float(code) * lo - dmin[r] * hi)
226 * float(arena[p.in0 + base + tap]);
227 }
228 for (uint l = 0u; l < 16u; l++) {
229 uint tap = half_idx * 128u + pair * 32u + 16u + l;
230 if (tap >= span) {
231 break;
232 }
233 uint code = q2k_code(sbo, half_idx, tap);
234 total += (dall[r] * float(code) * lo2 - dmin[r] * hi2)
235 * float(arena[p.in0 + base + tap]);
236 }
237 }
238 }
239 acc[r] += total;
240 }
241 }
242 }
243 // Reduce inside each subgroup first, then across the few subgroups a workgroup holds.
244 for (uint r = 0u; r < ROWS; r++) {
245 float summed = subgroupAdd(acc[r]);
246 if (subgroupElect()) {
247 partial[r][gl_SubgroupID] = summed;
248 }
249 }
250 barrier();
251 if (lane >= ROWS) {
252 return;
253 }
254 uint channel = channel_base + lane;
255 if (channel >= p.out_c) {
256 return;
257 }
258 float total = 0.0;
259 for (uint i = 0u; i < gl_NumSubgroups; i++) {
260 total += partial[lane][i];
261 }
262 // Already scaled inside the loop, so only the bias is left.
263 float offset = float(weights[p.bias + channel]);
264 arena[p.out_at + channel] = float16_t(quant_store(fused_store(total + offset, p.act, channel, channel)));
265}