Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / library / ml / src / main / rust / shaders / gap.comp
gap.comp65 lines · 2.1 KiBRaw
| 1 | #version 450 |
| 2 | //! Mean over H and W, to `C x 1 x 1`. The squeeze half of a squeeze-excite block. |
| 3 | //! |
| 4 | //! Ten uses, all in the selfie net, and all on a small map: the largest is 128x16x16, so |
| 5 | //! one invocation per *channel* reducing 256 elements serially is the right shape. A |
| 6 | //! tree reduction across a workgroup would be faster per channel and slower overall, |
| 7 | //! because there are only 16 to 128 channels to keep the GPU busy with. |
| 8 | //! |
| 9 | //! ONNX calls this `ReduceMean` with `axes = [2, 3]` and `keepdims = 1`, which is why the |
| 10 | //! output keeps its two trailing unit dimensions and `mul_bcast.comp` can index it by |
| 11 | //! channel alone. |
| 12 | //! |
| 13 | //! # Row mode |
| 14 | //! |
| 15 | //! With `p.kw == 1` one 64-lane workgroup owns one channel and its lanes stride the |
| 16 | //! plane, like `instancenorm.comp`. Selected by the emit arm for large planes; small |
| 17 | //! maps keep one invocation per channel. See `reduce.glsl`. |
| 18 | |
| 19 | #extension GL_KHR_shader_subgroup_basic : require |
| 20 | #extension GL_KHR_shader_subgroup_arithmetic : require |
| 21 | #include "common.glsl" |
| 22 | #include "reduce.glsl" |
| 23 | |
| 24 | void row_mode() { |
| 25 | uint channel = reduce_row(); |
| 26 | if (channel >= p.count) { |
| 27 | return; |
| 28 | } |
| 29 | uint plane = p.in0 + channel * p.in_h * p.in_w; |
| 30 | uint elements = p.in_h * p.in_w; |
| 31 | uint lane = gl_LocalInvocationID.x; |
| 32 | uint lanes = gl_WorkGroupSize.x; |
| 33 | |
| 34 | float total = 0.0; |
| 35 | for (uint i = lane; i < elements; i += lanes) { |
| 36 | total += float(arena[plane + i]); |
| 37 | } |
| 38 | // Every lane reaches the workgroup reduction: `workgroup_sum` barriers, |
| 39 | // which a subset of lanes must never enter alone. |
| 40 | float sum = workgroup_sum(total); |
| 41 | if (lane == 0u) { |
| 42 | arena[p.out_at + channel] = float16_t(sum / float(elements)); |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | void main() { |
| 47 | if (reduce_row_mode()) { |
| 48 | row_mode(); |
| 49 | return; |
| 50 | } |
| 51 | uint channel = global_index(); |
| 52 | if (channel >= p.count) { |
| 53 | return; |
| 54 | } |
| 55 | |
| 56 | uint plane = p.in0 + channel * p.in_h * p.in_w; |
| 57 | uint elements = p.in_h * p.in_w; |
| 58 | |
| 59 | float total = 0.0; |
| 60 | for (uint i = 0u; i < elements; i++) { |
| 61 | total += float(arena[plane + i]); |
| 62 | } |
| 63 | |
| 64 | arena[p.out_at + channel] = float16_t(total / float(elements)); |
| 65 | } |