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

Modern-Apps.git / library / ml / src / main / rust / shaders / common.glsl

common.glsl430 lines · 18.7 KiBRaw
1// Shared declarations for every compute shader in this runtime.
2//
3// Not a shader itself: `compileShaders` compiles only `*.comp` here, so this is
4// pulled in by `#include` and never compiled alone. glslc resolves the path relative
5// to the including file.
6//
7// # Two bindings, and offsets in push constants
8//
9// There are exactly two storage buffers for the whole runtime:
10//
11// binding 0 the activation arena, read and written
12// binding 1 the weights, read only
13//
14// Every tensor is a *region* of one of those, addressed by an element offset in the
15// push-constant block. So the descriptor set is written once at setup and never
16// rebound, there are no uniform buffers, no dynamic offsets and nothing to keep in
17// sync per layer — `vkCmdPushConstants` before each dispatch is the entire per-layer
18// state. See `nets::Push`, which this block must match field for field.
19//
20// # fp16 storage, fp32 arithmetic
21//
22// Weights and activations are fp16; every accumulator here is `float`. Half the
23// bandwidth and half the memory, without half's 11-bit mantissa accumulating error
24// down a 119-layer net.
25//
26// `shaderFloat16` and `storageBuffer16BitAccess` are both required at device creation.
27// `VK_KHR_shader_float16_int8` is a Vulkan 1.2 promotion, so at the 1.1 floor minSdk 31
28// guarantees it is an extension that may be absent — see `vulkan::context`, which
29// refuses to create a device without it rather than silently producing fp32 code.
30
31#extension GL_EXT_shader_16bit_storage : require
32#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require
33
34// 64 invocations per workgroup: a multiple of every wave width in use (16 on some
35// Mali, 32 on Adreno, 64 on older GCN-derived parts) so no wave is ever half idle.
36layout(local_size_x = 64) in;
37
38layout(std430, binding = 0) buffer Arena {
39 float16_t arena[];
40};
41
42layout(std430, binding = 1) readonly buffer Weights {
43 float16_t weights[];
44};
45// The same buffer as binding 1, viewed as 32-bit words.
46//
47// Int8 weights are unpacked from here four at a time. A byte view would be tidier but needs
48// `VK_KHR_8bit_storage`, an extension on top of the fp16 one this runtime already requires,
49// and every extra requirement narrows the devices that can run at all. 32-bit storage is
50// universal.
51//
52// Aliasing one buffer through two descriptors is allowed, and both are read-only, so there is
53// no write hazard between the views.
54layout(std430, binding = 2) readonly buffer Weights32 {
55 uint weights32[];
56};
57
58// Values that change per step without the command buffer being re-recorded.
59//
60// Push constants below are baked into the recording, so anything that varies between two submits
61// of the *same* recording has to be read from memory. A decode step's key count is the case that
62// matters: it grows by one every token, and re-recording for it cost a `device_wait_idle` and a
63// full re-emit per token.
64//
65// Mirrors `StepParams` in `src/vulkan/run.rs` field for field. `std430` packs a struct of `uint`s
66// with no padding, so neither side has to restate an alignment rule.
67// The same buffer once more, as `uvec4`, for reads wide enough to use the memory system.
68//
69// A gemv fetching one 32-bit word per instruction reaches 4.7 GB/s on a Tensor G4; a shader
70// reading the same bytes 16 at a time reaches 19.6. The bytes and the buffer are identical - only
71// the width of each load differs, and four times the width is very nearly four times the rate.
72//
73// Reads through this view must be 16-byte aligned, which for int4 weights means the element index
74// must be a multiple of 32. Callers check; see `conv_vec_int4.comp`.
75layout(std430, binding = 4) readonly buffer Weights128 {
76 uvec4 weights128[];
77};
78
79layout(std430, binding = 3) readonly buffer Params {
80 // Cache positions already written; a cached-attention op attends over `prefix + 1` keys.
81 uint prefix;
82 // First position a sliding window may attend to. Zero attends from the start.
83 uint window_start;
84} step_params;
85
86layout(push_constant) uniform Push {
87 uint in0;
88 uint in1;
89 uint out_at;
90 uint weight;
91 uint bias;
92 uint in_c;
93 uint in_h;
94 uint in_w;
95 uint out_c;
96 uint out_h;
97 uint out_w;
98 uint kh;
99 uint kw;
100 uint stride_h;
101 uint stride_w;
102 uint dil_h;
103 uint dil_w;
104 uint pad_t;
105 uint pad_l;
106 uint pad_edge;
107 uint group;
108 uint act;
109 uint act_weight;
110 uint param0_bits;
111 uint param1_bits;
112 uint count;
113 // Non-zero when the key range comes from `step_params` rather than from `in_w`/`out_w`,
114 // which then carry only the stride. See `Push::dyn_keys` in `nets/mod.rs`.
115 uint dyn_keys;
116 // Key/value heads, when fewer than `group`. Zero means "as many as `group`", which is
117 // ordinary multi-head attention. See `kv_head_of`.
118 uint kv_heads;
119 // Non-zero when this op's attention slides, so its first key is `window_start`.
120 //
121 // A push constant and not a step parameter, because whether a layer slides is structural -
122 // Gemma 4's layers 0-3 slide and layer 4 does not, for every step of every generation. Baking
123 // it at record time is what lets one `StepParams` serve both: `window_start` is computed once
124 // by the host and the layers that must ignore it do.
125 uint sliding;
126 // Independent rotary sub-blocks per head. 1 is ordinary 1-D RoPE.
127 //
128 // Gemma 4's vision tower uses 2: a 64-wide head is two 32-wide blocks, one rotated by the
129 // patch's row and one by its column, each with its own 16 frequencies. See `rope_axes` in
130 // `nets/mod.rs`.
131 uint rope_axes;
132 // A residual addend folded into this op's store, or all-bits-set for none.
133 //
134 // `Builder::finish` removes a single-consumer `Add` after a convolution by storing
135 // `activate(acc + bias) + arena[res + index]`. All-bits-set because arena offset 0
136 // is a live tensor — the first input is pinned there — so 0 cannot mean "none".
137 uint res;
138 // A per-channel shift folded into this op's store, or all-bits-set for none.
139 //
140 // The `AddBroadcast` half of the same fold: Supertonic's timestep conditioning adds
141 // one value per channel, so the fused store adds `arena[shift + channel]`.
142 uint shift;
143} p;
144
145// Like `activate`, but for a convolution's store: the activated accumulator plus the
146// folded addends `Builder::finish` moved onto it. `p.res` is all-bits-set on every op
147// the fusion did not touch, and all-bits-set reads nothing — see `Push::res`.
148//
149// GLSL has no optional parameters and no function overloading on these types worth using,
150// so this is one function with two sentinel checks rather than a branch at each of the
151// seven call sites. `index` is the output element this invocation stores (the flat index
152// for the untiled shaders, `channel * positions + position` for the tiled and gemv ones);
153// `channel` is its output channel, for the per-channel shift.
154float fused_store(float acc, uint act, uint channel, uint index);
155
156// Keys a cached-attention op attends over, as an inclusive `[first, last]` range.
157//
158// A plain decoder attends `0 ..= prefix`. A sliding-window layer attends
159// `window_start ..= prefix`, which is why this is a range and not a count: Gemma 4 alternates
160// four sliding layers to one global one, and the sliding ones must not see the whole cache.
161//
162// When `p.dyn_keys` is zero the op was built at a fixed length and the range is the whole row,
163// which is every net that does not decode.
164// The first key an attention op may read.
165//
166// `window_start ..= prefix`, which is why this is a range and not a count: Gemma 4 alternates
167// four sliding layers to one global one, and the sliding ones must not see the whole cache.
168//
169// When `p.dyn_keys` is zero the op was built at a fixed length and the range is the whole row,
170// which is every net that does not decode. When it is set but `p.sliding` is not, the op attends
171// the whole prefix - a full-attention layer sharing a submit with sliding ones.
172uint attn_first() {
173 return (p.dyn_keys != 0u && p.sliding != 0u) ? step_params.window_start : 0u;
174}
175
176uint attn_last(uint stride) {
177 return p.dyn_keys != 0u ? min(step_params.prefix, stride - 1u) : stride - 1u;
178}
179
180// The same range for query `q` of a multi-query op (`p.dil_h` queries at positions `prefix + q`,
181// `p.dil_w` the sliding window or 0). Single-query ops (`p.dil_h == 0`) take exactly the
182// decode path above.
183uint attn_first_q(uint q) {
184 if (p.dil_h == 0u) {
185 return attn_first();
186 }
187 uint pos = step_params.prefix + q;
188 return (p.sliding != 0u && p.dil_w != 0u && pos + 1u > p.dil_w) ? pos + 1u - p.dil_w : 0u;
189}
190
191uint attn_last_q(uint stride, uint q) {
192 if (p.dil_h == 0u) {
193 return attn_last(stride);
194 }
195 return min(step_params.prefix + q, stride - 1u);
196}
197
198// The KV head a query head reads from.
199//
200// `p.group` query heads share `p.kv_heads` key/value heads, so head `h` reads KV head
201// `h / (group / kv_heads)`. Gemma 4's text decoder is the extreme case at one KV head for eight
202// query heads; multi-head attention is the other, where the two counts are equal and this is the
203// identity. Zero `kv_heads` means "same as `group`", so every net built before this existed is
204// unaffected.
205uint kv_head_of(uint head) {
206 uint kv = p.kv_heads == 0u ? p.group : p.kv_heads;
207 return head / max(p.group / max(kv, 1u), 1u);
208}
209
210// Channels one position of a KV cache occupies: `kv_heads * head_dim`, not `group * head_dim`.
211uint kv_stride(uint head_dim) {
212 uint kv = p.kv_heads == 0u ? p.group : p.kv_heads;
213 return kv * head_dim;
214}
215
216// `nets::Act`.
217#define ACT_NONE 0u
218#define ACT_RELU 1u
219#define ACT_HARDSWISH 2u
220#define ACT_SIGMOID 3u
221#define ACT_PRELU 4u
222#define ACT_CLIP01 5u
223#define ACT_SWISH 6u
224#define ACT_RELU6 7u
225#define ACT_GELU 8u
226
227// This invocation's output element, across a 2D grid of workgroups.
228//
229// Not `gl_GlobalInvocationID.x`: U^2-Netp's largest layer writes 64x320x320 = 6,553,600
230// elements, which at 64 per workgroup is 102,400 workgroups, and `maxComputeWorkGroupCount`
231// is only guaranteed to be **65,535** per dimension. A 1D dispatch that big is rejected
232// outright on any device at the guaranteed minimum, so `vulkan::run` splits the count
233// across x and y and this flattens it back. `gl_NumWorkGroups` is the actual dispatch
234// extent, so the two cannot disagree.
235//
236// The grid over-covers, so every shader here tests the result against `p.count`.
237uint global_index() {
238 uint group = gl_WorkGroupID.y * gl_NumWorkGroups.x + gl_WorkGroupID.x;
239 return group * gl_WorkGroupSize.x + gl_LocalInvocationID.x;
240}
241
242// The activation fused into a layer's store. Every ReLU, HardSwish, Sigmoid and PReLU in
243// every network here directly follows a convolution, so this is the only place
244// activations happen and there is no standalone activation pass.
245//
246// `channel` is the output channel, needed only by PReLU, whose slope is one value per
247// channel at `p.act_weight` in the weights buffer. Passing it unconditionally costs a
248// register and keeps one signature.
249/// One signed 4-bit value of an int4 tensor, by element index.
250///
251/// Eight nibbles to a 32-bit word, low nibble first, so element `i` is at bit `4 * (i % 8)` of
252/// word `i / 8`. `base` is the tensor's start as a 32-bit word index, as for `int8_at`.
253///
254/// `bitfieldExtract` on a **signed** int sign-extends, which is what makes the stored range
255/// -8..7 rather than 0..15. Reading it unsigned and subtracting would be a different
256/// quantisation and would silently bias every weight.
257int int4_at(uint base, uint index) {
258 uint word = weights32[base + (index >> 3u)];
259 return bitfieldExtract(int(word), int((index & 7u) << 2u), 4);
260}
261
262/// Taps one int4 scale covers. Mirrors `weights::I4_BLOCK`.
263#define I4_BLOCK 32u
264
265/// The per-block scale for output `channel`, block `block`, of a rank-2 `(out, blocks)` table.
266float int4_scale(uint channel, uint block, uint blocks) {
267 return float(weights[p.act_weight + channel * blocks + block]);
268}
269
270/// One signed byte of an int8 tensor, by element index.
271///
272/// `base` is the tensor's start as a 32-bit word index; `index` is the element within it.
273/// `bitfieldExtract` on a *signed* integer sign-extends, which is what turns the byte back into
274/// -128..127 rather than 0..255 — reading it unsigned would make every negative weight large
275/// and positive, which trains-looking output would not reveal.
276int int8_at(uint base, uint index) {
277 uint word = weights32[base + (index >> 2u)];
278 return bitfieldExtract(int(word), int((index & 3u) << 3u), 8);
279}
280
281/// The four signed bytes of one 32-bit word, low byte first, as floats.
282vec4 unpack_int8x4(uint word) {
283 int w = int(word);
284 return vec4(bitfieldExtract(w, 0, 8), bitfieldExtract(w, 8, 8), bitfieldExtract(w, 16, 8),
285 bitfieldExtract(w, 24, 8));
286}
287
288/// Taps one Q2_K superblock covers. Mirrors `weights::Q2K_BLOCK`.
289#define Q2K_BLOCK 256u
290
291/// Bytes one Q2_K superblock occupies. Mirrors `weights::Q2K_BYTES`.
292#define Q2K_BYTES 84u
293
294/// One scale byte of a Q2_K superblock.
295///
296/// `sbo` is the superblock's byte offset in the weights buffer; `half` selects the 128-tap
297/// half (32-byte `qs` chunk) and `scale` the byte within the half's 8 scale bytes. The low
298/// nibble is the lane's `lo`, the high nibble its `hi`.
299uint q2k_scale(uint sbo, uint half_idx, uint scale) {
300 // Scales are the first 16 bytes of the superblock; halves are consumed in order, so
301 // half 1's scales start 8 bytes in.
302 uint at = sbo + half_idx * 8u + scale;
303 // Byte loads go through the 32-bit view: the cheapest aligned read containing `at`.
304 uint word = weights32[at >> 2u];
305 return (word >> ((at & 3u) << 3u)) & 255u;
306}
307
308/// One 2-bit code of a Q2_K superblock.
309///
310/// `tap` is the tap within the 256-tap superblock (0..255). Halves are 128 taps of separate
311/// 32-byte `qs` chunks; within a half, lane-pair `tap / 32` packs 16+16 taps at shift
312/// `2 * ((tap / 16) % 2)`... precisely: even lanes read `qs[..16]` of the half-chunk, odd
313/// lanes `qs[16..]`, both at shift `2 * lane` where `lane = (tap / 32) % 4`.
314uint q2k_code(uint sbo, uint half_idx, uint tap) {
315 uint chunk = sbo + 16u + half_idx * 32u;
316 uint lane = (tap / 32u) % 4u;
317 uint odd = (tap / 16u) % 2u;
318 uint l = tap % 16u;
319 uint at = chunk + odd * 16u + l;
320 uint word = weights32[at >> 2u];
321 uint byte = (word >> ((at & 3u) << 3u)) & 255u;
322 return (byte >> (lane * 2u)) & 3u;
323}
324
325float activate(float x, uint kind, uint channel) {
326 if (kind == ACT_RELU) {
327 return max(x, 0.0);
328 }
329 if (kind == ACT_HARDSWISH) {
330 // ONNX HardSwish at its default alpha = 1/6, beta = 0.5.
331 return x * clamp(x * (1.0 / 6.0) + 0.5, 0.0, 1.0);
332 }
333 if (kind == ACT_SIGMOID) {
334 return 1.0 / (1.0 + exp(-x));
335 }
336 if (kind == ACT_PRELU) {
337 // ONNX PRelu. The branch is on the sign of the accumulator, so it diverges
338 // within a wave; a `mix` on the comparison would too, and this reads as the
339 // definition does.
340 return x < 0.0 ? x * float(weights[p.act_weight + channel]) : x;
341 }
342 if (kind == ACT_CLIP01) {
343 // A normalised ONNX HardSigmoid: its alpha and beta were folded into this
344 // layer's weight and bias by `scripts/ml/ppocr_fold.py`, so what is left is the
345 // clamp. See `nets::Act::Clip01`.
346 return clamp(x, 0.0, 1.0);
347 }
348 if (kind == ACT_SWISH) {
349 // `x * sigmoid(x)`. Not HardSwish's piecewise approximation — the recogniser uses
350 // both, and substituting one for the other is a plausible-looking accuracy loss.
351 return x / (1.0 + exp(-x));
352 }
353 if (kind == ACT_RELU6) {
354 // ONNX `Clip` at `(0, 6)`: MobileNetV2's ReLU6, which every backbone
355 // convolution of MODNet carries. See `nets::Act::Relu6`.
356 return clamp(x, 0.0, 6.0);
357 }
358 if (kind == ACT_GELU) {
359 // The exact GELU, `0.5 x (1 + erf(x / sqrt(2)))`, which is what Supertonic's four nets
360 // spell as an `Erf`.
361 //
362 // The tanh approximation would also have done: the two forms differ by at most 4.7e-4,
363 // and fp16's step there is 2.0e-3. `erf` is used because it matches the export and
364 // because `post::duration::erf` is the same Abramowitz and Stegun 7.1.26 series with the
365 // same coefficients, so the host reference and this are one function rather than two
366 // that happen to agree.
367 float sign = x < 0.0 ? -1.0 : 1.0;
368 float a = abs(x) * 0.70710678;
369 float t = 1.0 / (1.0 + 0.3275911 * a);
370 float poly = t * (0.254829592
371 + t * (-0.284496736
372 + t * (1.421413741
373 + t * (-1.453152027
374 + t * 1.061405429))));
375 float erf = sign * (1.0 - poly * exp(-a * a));
376 return 0.5 * x * (1.0 + erf);
377 }
378 return x;
379}
380
381// Unpack a flat output index into channel, row and column. Every shader here runs one
382// invocation per output element, in NCHW order, so this is the first thing each does.
383void unpack(uint index, out uint c, out uint y, out uint x) {
384 x = index % p.out_w;
385 uint rest = index / p.out_w;
386 y = rest % p.out_h;
387 c = rest / p.out_h;
388}
389
390// Like `activate`, but for a convolution's store: the activated accumulator plus the
391// folded addends `Builder::finish` moved onto it. `p.res` is all-bits-set on every op
392// the fusion did not touch, and all-bits-set reads nothing — see the declaration above.
393//
394// After `unpack` (and so after `activate`) because it calls it: GLSL compiles in order,
395// so the definition has to see the declaration. The seven convolution shaders call this
396// rather than spelling the two sentinel checks each.
397float fused_store(float acc, uint act, uint channel, uint index) {
398 float value = activate(acc, act, channel);
399 if (p.res != 0xFFFFFFFFu) {
400 value += float(arena[p.res + index]);
401 }
402 if (p.shift != 0xFFFFFFFFu) {
403 value += float(arena[p.shift + channel]);
404 }
405 return value;
406}
407
408// The int8 round-trip folded into a producer's store: `quant_store` is the
409// outermost operation, after `fused_store`.
410//
411// `Builder::fuse_quantize` absorbs a single-consumer `Quantize` into the store
412// that produced its input, so the store keeps
413// `quantize(activate(acc + bias) + res + shift)` and the round-trip never
414// becomes a dispatch. `p.param0_bits` carries the scale as raw f32 bits — the
415// same convention as `quantize.comp`'s — and zero bits mean unfused, which is
416// what `Push::default` leaves on every op the fold did not touch.
417//
418// The fused form rounds once (here) where the unfolded pair would round twice
419// (the producer's fp16 store, then the quantize's). That is the same contract
420// as `fused_store`'s own single rounding: the reference implements this form,
421// and parity is against live, not against the unfolded pair.
422float quant_store(float value) {
423 if (p.param0_bits == 0u) {
424 return value;
425 }
426 float scale = uintBitsToFloat(p.param0_bits);
427 float q = floor(value / scale + 0.5);
428 q = clamp(q, -128.0, 127.0);
429 return q * scale;
430}