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

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

rmsnorm.comp288 lines · 11.5 KiBRaw
1#version 450
2//! Root-mean-square normalisation over the **channel** axis, with a per-channel gain.
3//!
4//! Sixteen uses, all in Maia3's eight post-norm encoder blocks (`norm1` and `norm2`).
5//!
6//! # The difference from `layernorm.comp`
7//!
8//! Two lines, both subtractions that are not there: the mean is never computed and never
9//! removed, and there is no beta. `x / sqrt(mean(x^2) + eps) * gamma` against layer norm's
10//! `(x - mean) / sqrt(var + eps) * gamma + beta`. That also means one pass over the input
11//! instead of two, because the sum of squares does not depend on a previously computed mean.
12//!
13//! `Kind::RmsNorm` reads a single rank-1 tensor, so unlike `Kind::LayerNorm` the `bias`
14//! field of the push block is unused. `torch.nn.RMSNorm` with the default
15//! `elementwise_affine=True` stores exactly this one `weight`, which is why the Maia3
16//! checkpoint has `norm1.weight` with no matching `norm1.bias`.
17//!
18//! # Layout
19//!
20//! Identical to layer norm's: the sequence is `[d_model, 1, T]`, one invocation per
21//! position, and the reduction strides by `in_h * in_w`. See `nets::Kind::LayerNorm` for
22//! why the layout is that way round.
23//!
24//! # Row mode
25//!
26//! With `p.kw == 1` one workgroup owns one (group, position) row and its lanes split the
27//! group's channels. See `reduce.glsl`. A contiguous, quad-aligned row (one position, as in
28//! every decode step) takes `quad_row`, four channels per load; its sum of squares adds in a
29//! different order, so outputs can move by fp32 rounding against the scalar row mode.
30
31#extension GL_KHR_shader_subgroup_basic : require
32#extension GL_KHR_shader_subgroup_arithmetic : require
33#include "common.glsl"
34#include "reduce.glsl"
35
36/// Binding 0 as fp16 quads, for the contiguous row path. Aliases `arena`; each lane reads and
37/// writes only its own quads.
38layout(std430, binding = 0) buffer ArenaQuad {
39 f16vec4 arena_quad[];
40};
41
42/// Binding 1 as fp16 quads, for the gains on the contiguous row path.
43layout(std430, binding = 1) readonly buffer WeightsQuad {
44 f16vec4 weights_quad[];
45};
46
47/// Row mode over one contiguous, quad-aligned row (a single position): a lane moves four
48/// channels per load, so a 1536-wide decode row is six loads a lane per pass instead of 24.
49/// Latency of those dependent loads, not bandwidth, was most of each 46 us dispatch.
50void quad_row(uint base, float epsilon, uint per_group) {
51 uint lane = gl_LocalInvocationID.x;
52 uint lanes = gl_WorkGroupSize.x;
53 uint in_q = (p.in0 + base) >> 2u;
54 uint out_q = (p.out_at + base) >> 2u;
55 uint res_q = (p.res + base) >> 2u;
56 uint gain_q = p.weight >> 2u;
57 uint quads = per_group >> 2u;
58 float squares = 0.0;
59 for (uint q = lane; q < quads; q += lanes) {
60 vec4 v = vec4(arena_quad[in_q + q]);
61 squares += v.x * v.x;
62 squares += v.y * v.y;
63 squares += v.z * v.z;
64 squares += v.w * v.w;
65 }
66 float inverse = 1.0 / sqrt(workgroup_sum(squares) / float(per_group) + epsilon);
67 for (uint q = lane; q < quads; q += lanes) {
68 vec4 v = vec4(arena_quad[in_q + q]);
69 vec4 gamma = vec4(weights_quad[gain_q + q]);
70 vec4 normed = vec4(quant_store(v.x * inverse * gamma.x), quant_store(v.y * inverse * gamma.y),
71 quant_store(v.z * inverse * gamma.z), quant_store(v.w * inverse * gamma.w));
72 if (p.res != 0xFFFFFFFFu) {
73 normed += vec4(arena_quad[res_q + q]);
74 }
75 arena_quad[out_q + q] = f16vec4(normed);
76 }
77}
78
79void row_mode() {
80 uint position = reduce_row();
81 if (position >= p.count) {
82 return;
83 }
84 uint lane = gl_LocalInvocationID.x;
85 uint lanes = gl_WorkGroupSize.x;
86 uint stride = p.in_h * p.in_w;
87 uint groups = max(p.group, 1u);
88 uint per_group = p.in_c / groups;
89 uint base = (position / stride) * per_group;
90 uint at_pos = position % stride;
91 float epsilon = uintBitsToFloat(p.param1_bits);
92 bool quad = stride == 1u && (per_group & 3u) == 0u && ((p.in0 + base) & 3u) == 0u
93 && ((p.out_at + base) & 3u) == 0u && (p.weight & 3u) == 0u
94 && (p.res == 0xFFFFFFFFu || ((p.res + base) & 3u) == 0u);
95 if (quad) {
96 quad_row(base, epsilon, per_group);
97 return;
98 }
99 float squares = 0.0;
100 for (uint c = lane; c < per_group; c += lanes) {
101 float value = float(arena[p.in0 + (base + c) * stride + at_pos]);
102 squares += value * value;
103 }
104 float inverse = 1.0 / sqrt(workgroup_sum(squares) / float(per_group) + epsilon);
105 for (uint c = lane; c < per_group; c += lanes) {
106 uint at = (base + c) * stride + at_pos;
107 float value = float(arena[p.in0 + at]);
108 float gamma = float(weights[p.weight + c]);
109 float normed = quant_store(value * inverse * gamma);
110 if (p.res != 0xFFFFFFFFu) {
111 normed += float(arena[p.res + at]);
112 }
113 arena[p.out_at + at] = float16_t(normed);
114 }
115}
116
117/// [`tile_mode`] when positions come in aligned quads: a lane loads four adjacent positions at once
118/// and sixteen lanes split the channels, so a lane makes a sixteenth of a channel walk where the
119/// scalar tile made a quarter. The sixteen channel groups' sums add in a fixed order.
120void quad_tile_mode(uint stride) {
121 uint lane = gl_LocalInvocationID.x;
122 uint quad = lane & 3u;
123 uint part = lane >> 2u;
124 uint row = reduce_row() * 16u + quad * 4u;
125 bool live = row < p.count;
126 uint groups = max(p.group, 1u);
127 uint per_group = p.in_c / groups;
128 uint base = (row / stride) * per_group;
129 uint at_pos = row % stride;
130 float epsilon = uintBitsToFloat(p.param1_bits);
131 vec4 squares = vec4(0.0);
132 if (live) {
133 for (uint c = part; c < per_group; c += 16u) {
134 vec4 v = vec4(arena_quad[(p.in0 + (base + c) * stride + at_pos) >> 2u]);
135 squares += v * v;
136 }
137 }
138 vec4 total = squares;
139 uint slot = quad * 4u;
140 for (uint q = 1u; q < 16u; q++) {
141 if (part == q) {
142 reduce_partial[slot] = squares.x;
143 reduce_partial[slot + 1u] = squares.y;
144 reduce_partial[slot + 2u] = squares.z;
145 reduce_partial[slot + 3u] = squares.w;
146 }
147 barrier();
148 if (part == 0u) {
149 total += vec4(reduce_partial[slot], reduce_partial[slot + 1u], reduce_partial[slot + 2u],
150 reduce_partial[slot + 3u]);
151 }
152 barrier();
153 }
154 if (part == 0u) {
155 reduce_partial[slot] = total.x;
156 reduce_partial[slot + 1u] = total.y;
157 reduce_partial[slot + 2u] = total.z;
158 reduce_partial[slot + 3u] = total.w;
159 }
160 barrier();
161 total = vec4(reduce_partial[slot], reduce_partial[slot + 1u], reduce_partial[slot + 2u],
162 reduce_partial[slot + 3u]);
163 if (!live) {
164 return;
165 }
166 vec4 inverse = 1.0 / sqrt(total / float(per_group) + epsilon);
167 for (uint c = part; c < per_group; c += 16u) {
168 uint at = (base + c) * stride + at_pos;
169 vec4 v = vec4(arena_quad[(p.in0 + at) >> 2u]);
170 vec4 scaled = v * inverse * float(weights[p.weight + c]);
171 vec4 normed = vec4(quant_store(scaled.x), quant_store(scaled.y), quant_store(scaled.z),
172 quant_store(scaled.w));
173 if (p.res != 0xFFFFFFFFu) {
174 normed += vec4(arena_quad[(p.res + at) >> 2u]);
175 }
176 arena_quad[(p.out_at + at) >> 2u] = f16vec4(normed);
177 }
178}
179/// Tile mode (`p.kw == 2`): a workgroup owns 16 consecutive rows and each quarter of its lanes a
180/// quarter of the channels, so 16 adjacent lanes read 16 adjacent positions of one channel - one
181/// 32-byte load where row mode makes 16 lanes read 16 channels a whole sequence apart. The four
182/// quarters' sums add in a fixed order through `reduce_partial`, whatever the subgroup size.
183void tile_mode() {
184 uint stride = p.in_h * p.in_w;
185 if ((stride & 3u) == 0u && (p.in0 & 3u) == 0u && (p.out_at & 3u) == 0u
186 && (p.res == 0xFFFFFFFFu || (p.res & 3u) == 0u)) {
187 quad_tile_mode(stride);
188 return;
189 }
190 uint lane = gl_LocalInvocationID.x;
191 uint slot = lane & 15u;
192 uint quarter = lane >> 4u;
193 uint position = reduce_row() * 16u + slot;
194 bool live = position < p.count;
195 uint groups = max(p.group, 1u);
196 uint per_group = p.in_c / groups;
197 uint base = (position / stride) * per_group;
198 uint at_pos = position % stride;
199 float epsilon = uintBitsToFloat(p.param1_bits);
200 float squares = 0.0;
201 if (live) {
202 for (uint c = quarter; c < per_group; c += 4u) {
203 float value = float(arena[p.in0 + (base + c) * stride + at_pos]);
204 squares += value * value;
205 }
206 }
207 float total = squares;
208 for (uint q = 1u; q < 4u; q++) {
209 if (quarter == q) {
210 reduce_partial[slot] = squares;
211 }
212 barrier();
213 if (quarter == 0u) {
214 total += reduce_partial[slot];
215 }
216 barrier();
217 }
218 if (quarter == 0u) {
219 reduce_partial[slot] = total;
220 }
221 barrier();
222 total = reduce_partial[slot];
223 if (!live) {
224 return;
225 }
226 float inverse = 1.0 / sqrt(total / float(per_group) + epsilon);
227 for (uint c = quarter; c < per_group; c += 4u) {
228 uint at = (base + c) * stride + at_pos;
229 float value = float(arena[p.in0 + at]);
230 float gamma = float(weights[p.weight + c]);
231 float normed = quant_store(value * inverse * gamma);
232 if (p.res != 0xFFFFFFFFu) {
233 normed += float(arena[p.res + at]);
234 }
235 arena[p.out_at + at] = float16_t(normed);
236 }
237}
238void main() {
239 if (p.kw == 2u) {
240 tile_mode();
241 return;
242 }
243 if (reduce_row_mode()) {
244 row_mode();
245 return;
246 }
247 uint position = global_index();
248 if (position >= p.count) {
249 return;
250 }
251 // `count` is `groups * in_h * in_w`, so an invocation owns one group at one position and
252 // the channel stride is the spatial extent.
253 uint stride = p.in_h * p.in_w;
254 uint groups = max(p.group, 1u);
255 uint per_group = p.in_c / groups;
256 uint group = position / stride;
257 uint at_pos = position % stride;
258 uint base = group * per_group;
259 float epsilon = uintBitsToFloat(p.param1_bits);
260 float squares = 0.0;
261 for (uint c = 0u; c < per_group; c++) {
262 float value = float(arena[p.in0 + (base + c) * stride + at_pos]);
263 squares += value * value;
264 }
265 // Epsilon is inside the square root, matching `torch.nn.RMSNorm`.
266 float inverse = 1.0 / sqrt(squares / float(per_group) + epsilon);
267 for (uint c = 0u; c < per_group; c++) {
268 // Gamma is indexed *within* the group, so a per-head norm re-uses one `head_dim`-long
269 // table across every head rather than needing one per head.
270 uint at = (base + c) * stride + at_pos;
271 float value = float(arena[p.in0 + at]);
272 float gamma = float(weights[p.weight + c]);
273 // A folded int8 round-trip (`quant_store`) applies to the norm output
274 // itself — the `Quantize` this norm's consumer was — before the
275 // residual below: the unfolded graph is `add(res, rmsnorm(quantize))`,
276 // and the add-fold already proved exact, so rounding the norm output
277 // first is too.
278 float normed = quant_store(value * inverse * gamma);
279 // A residual addend folded by `Builder::finish` (see `Push::res`): the
280 // post-norm `add(x, branch)` stores here instead of its own dispatch.
281 // Same contract as the convolution shaders' `fused_store`, minus the
282 // activation and bias they carry and this norm does not.
283 if (p.res != 0xFFFFFFFFu) {
284 normed += float(arena[p.res + at]);
285 }
286 arena[p.out_at + at] = float16_t(normed);
287 }
288}