#version 450 //! Root-mean-square normalisation over the **channel** axis, with a per-channel gain. //! //! Sixteen uses, all in Maia3's eight post-norm encoder blocks (`norm1` and `norm2`). //! //! # The difference from `layernorm.comp` //! //! Two lines, both subtractions that are not there: the mean is never computed and never //! removed, and there is no beta. `x / sqrt(mean(x^2) + eps) * gamma` against layer norm's //! `(x - mean) / sqrt(var + eps) * gamma + beta`. That also means one pass over the input //! instead of two, because the sum of squares does not depend on a previously computed mean. //! //! `Kind::RmsNorm` reads a single rank-1 tensor, so unlike `Kind::LayerNorm` the `bias` //! field of the push block is unused. `torch.nn.RMSNorm` with the default //! `elementwise_affine=True` stores exactly this one `weight`, which is why the Maia3 //! checkpoint has `norm1.weight` with no matching `norm1.bias`. //! //! # Layout //! //! Identical to layer norm's: the sequence is `[d_model, 1, T]`, one invocation per //! position, and the reduction strides by `in_h * in_w`. See `nets::Kind::LayerNorm` for //! why the layout is that way round. //! //! # Row mode //! //! With `p.kw == 1` one workgroup owns one (group, position) row and its lanes split the //! group's channels. See `reduce.glsl`. A contiguous, quad-aligned row (one position, as in //! every decode step) takes `quad_row`, four channels per load; its sum of squares adds in a //! different order, so outputs can move by fp32 rounding against the scalar row mode. #extension GL_KHR_shader_subgroup_basic : require #extension GL_KHR_shader_subgroup_arithmetic : require #include "common.glsl" #include "reduce.glsl" /// Binding 0 as fp16 quads, for the contiguous row path. Aliases `arena`; each lane reads and /// writes only its own quads. layout(std430, binding = 0) buffer ArenaQuad { f16vec4 arena_quad[]; }; /// Binding 1 as fp16 quads, for the gains on the contiguous row path. layout(std430, binding = 1) readonly buffer WeightsQuad { f16vec4 weights_quad[]; }; /// Row mode over one contiguous, quad-aligned row (a single position): a lane moves four /// channels per load, so a 1536-wide decode row is six loads a lane per pass instead of 24. /// Latency of those dependent loads, not bandwidth, was most of each 46 us dispatch. void quad_row(uint base, float epsilon, uint per_group) { uint lane = gl_LocalInvocationID.x; uint lanes = gl_WorkGroupSize.x; uint in_q = (p.in0 + base) >> 2u; uint out_q = (p.out_at + base) >> 2u; uint res_q = (p.res + base) >> 2u; uint gain_q = p.weight >> 2u; uint quads = per_group >> 2u; float squares = 0.0; for (uint q = lane; q < quads; q += lanes) { vec4 v = vec4(arena_quad[in_q + q]); squares += v.x * v.x; squares += v.y * v.y; squares += v.z * v.z; squares += v.w * v.w; } float inverse = 1.0 / sqrt(workgroup_sum(squares) / float(per_group) + epsilon); for (uint q = lane; q < quads; q += lanes) { vec4 v = vec4(arena_quad[in_q + q]); vec4 gamma = vec4(weights_quad[gain_q + q]); vec4 normed = vec4(quant_store(v.x * inverse * gamma.x), quant_store(v.y * inverse * gamma.y), quant_store(v.z * inverse * gamma.z), quant_store(v.w * inverse * gamma.w)); if (p.res != 0xFFFFFFFFu) { normed += vec4(arena_quad[res_q + q]); } arena_quad[out_q + q] = f16vec4(normed); } } void row_mode() { uint position = reduce_row(); if (position >= p.count) { return; } uint lane = gl_LocalInvocationID.x; uint lanes = gl_WorkGroupSize.x; uint stride = p.in_h * p.in_w; uint groups = max(p.group, 1u); uint per_group = p.in_c / groups; uint base = (position / stride) * per_group; uint at_pos = position % stride; float epsilon = uintBitsToFloat(p.param1_bits); bool quad = stride == 1u && (per_group & 3u) == 0u && ((p.in0 + base) & 3u) == 0u && ((p.out_at + base) & 3u) == 0u && (p.weight & 3u) == 0u && (p.res == 0xFFFFFFFFu || ((p.res + base) & 3u) == 0u); if (quad) { quad_row(base, epsilon, per_group); return; } float squares = 0.0; for (uint c = lane; c < per_group; c += lanes) { float value = float(arena[p.in0 + (base + c) * stride + at_pos]); squares += value * value; } float inverse = 1.0 / sqrt(workgroup_sum(squares) / float(per_group) + epsilon); for (uint c = lane; c < per_group; c += lanes) { uint at = (base + c) * stride + at_pos; float value = float(arena[p.in0 + at]); float gamma = float(weights[p.weight + c]); float normed = quant_store(value * inverse * gamma); if (p.res != 0xFFFFFFFFu) { normed += float(arena[p.res + at]); } arena[p.out_at + at] = float16_t(normed); } } /// [`tile_mode`] when positions come in aligned quads: a lane loads four adjacent positions at once /// and sixteen lanes split the channels, so a lane makes a sixteenth of a channel walk where the /// scalar tile made a quarter. The sixteen channel groups' sums add in a fixed order. void quad_tile_mode(uint stride) { uint lane = gl_LocalInvocationID.x; uint quad = lane & 3u; uint part = lane >> 2u; uint row = reduce_row() * 16u + quad * 4u; bool live = row < p.count; uint groups = max(p.group, 1u); uint per_group = p.in_c / groups; uint base = (row / stride) * per_group; uint at_pos = row % stride; float epsilon = uintBitsToFloat(p.param1_bits); vec4 squares = vec4(0.0); if (live) { for (uint c = part; c < per_group; c += 16u) { vec4 v = vec4(arena_quad[(p.in0 + (base + c) * stride + at_pos) >> 2u]); squares += v * v; } } vec4 total = squares; uint slot = quad * 4u; for (uint q = 1u; q < 16u; q++) { if (part == q) { reduce_partial[slot] = squares.x; reduce_partial[slot + 1u] = squares.y; reduce_partial[slot + 2u] = squares.z; reduce_partial[slot + 3u] = squares.w; } barrier(); if (part == 0u) { total += vec4(reduce_partial[slot], reduce_partial[slot + 1u], reduce_partial[slot + 2u], reduce_partial[slot + 3u]); } barrier(); } if (part == 0u) { reduce_partial[slot] = total.x; reduce_partial[slot + 1u] = total.y; reduce_partial[slot + 2u] = total.z; reduce_partial[slot + 3u] = total.w; } barrier(); total = vec4(reduce_partial[slot], reduce_partial[slot + 1u], reduce_partial[slot + 2u], reduce_partial[slot + 3u]); if (!live) { return; } vec4 inverse = 1.0 / sqrt(total / float(per_group) + epsilon); for (uint c = part; c < per_group; c += 16u) { uint at = (base + c) * stride + at_pos; vec4 v = vec4(arena_quad[(p.in0 + at) >> 2u]); vec4 scaled = v * inverse * float(weights[p.weight + c]); vec4 normed = vec4(quant_store(scaled.x), quant_store(scaled.y), quant_store(scaled.z), quant_store(scaled.w)); if (p.res != 0xFFFFFFFFu) { normed += vec4(arena_quad[(p.res + at) >> 2u]); } arena_quad[(p.out_at + at) >> 2u] = f16vec4(normed); } } /// Tile mode (`p.kw == 2`): a workgroup owns 16 consecutive rows and each quarter of its lanes a /// quarter of the channels, so 16 adjacent lanes read 16 adjacent positions of one channel - one /// 32-byte load where row mode makes 16 lanes read 16 channels a whole sequence apart. The four /// quarters' sums add in a fixed order through `reduce_partial`, whatever the subgroup size. void tile_mode() { uint stride = p.in_h * p.in_w; if ((stride & 3u) == 0u && (p.in0 & 3u) == 0u && (p.out_at & 3u) == 0u && (p.res == 0xFFFFFFFFu || (p.res & 3u) == 0u)) { quad_tile_mode(stride); return; } uint lane = gl_LocalInvocationID.x; uint slot = lane & 15u; uint quarter = lane >> 4u; uint position = reduce_row() * 16u + slot; bool live = position < p.count; uint groups = max(p.group, 1u); uint per_group = p.in_c / groups; uint base = (position / stride) * per_group; uint at_pos = position % stride; float epsilon = uintBitsToFloat(p.param1_bits); float squares = 0.0; if (live) { for (uint c = quarter; c < per_group; c += 4u) { float value = float(arena[p.in0 + (base + c) * stride + at_pos]); squares += value * value; } } float total = squares; for (uint q = 1u; q < 4u; q++) { if (quarter == q) { reduce_partial[slot] = squares; } barrier(); if (quarter == 0u) { total += reduce_partial[slot]; } barrier(); } if (quarter == 0u) { reduce_partial[slot] = total; } barrier(); total = reduce_partial[slot]; if (!live) { return; } float inverse = 1.0 / sqrt(total / float(per_group) + epsilon); for (uint c = quarter; c < per_group; c += 4u) { uint at = (base + c) * stride + at_pos; float value = float(arena[p.in0 + at]); float gamma = float(weights[p.weight + c]); float normed = quant_store(value * inverse * gamma); if (p.res != 0xFFFFFFFFu) { normed += float(arena[p.res + at]); } arena[p.out_at + at] = float16_t(normed); } } void main() { if (p.kw == 2u) { tile_mode(); return; } if (reduce_row_mode()) { row_mode(); return; } uint position = global_index(); if (position >= p.count) { return; } // `count` is `groups * in_h * in_w`, so an invocation owns one group at one position and // the channel stride is the spatial extent. uint stride = p.in_h * p.in_w; uint groups = max(p.group, 1u); uint per_group = p.in_c / groups; uint group = position / stride; uint at_pos = position % stride; uint base = group * per_group; float epsilon = uintBitsToFloat(p.param1_bits); float squares = 0.0; for (uint c = 0u; c < per_group; c++) { float value = float(arena[p.in0 + (base + c) * stride + at_pos]); squares += value * value; } // Epsilon is inside the square root, matching `torch.nn.RMSNorm`. float inverse = 1.0 / sqrt(squares / float(per_group) + epsilon); for (uint c = 0u; c < per_group; c++) { // Gamma is indexed *within* the group, so a per-head norm re-uses one `head_dim`-long // table across every head rather than needing one per head. uint at = (base + c) * stride + at_pos; float value = float(arena[p.in0 + at]); float gamma = float(weights[p.weight + c]); // A folded int8 round-trip (`quant_store`) applies to the norm output // itself — the `Quantize` this norm's consumer was — before the // residual below: the unfolded graph is `add(res, rmsnorm(quantize))`, // and the add-fold already proved exact, so rounding the norm output // first is too. float normed = quant_store(value * inverse * gamma); // A residual addend folded by `Builder::finish` (see `Push::res`): the // post-norm `add(x, branch)` stores here instead of its own dispatch. // Same contract as the convolution shaders' `fused_store`, minus the // activation and bias they carry and this norm does not. if (p.res != 0xFFFFFFFFu) { normed += float(arena[p.res + at]); } arena[p.out_at + at] = float16_t(normed); } }