Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / library / ml / src / main / rust / shaders / gated_activate.comp
gated_activate.comp39 lines · 2.0 KiBRaw
| 1 | #version 450 |
| 2 | //! `activate(gate) * up` over a fused `[gate | up]` projection, in one dispatch. |
| 3 | //! |
| 4 | //! # Why this is its own shader |
| 5 | //! |
| 6 | //! A gated feed-forward was four dispatches: two `SliceChannels` copies to split the projection, |
| 7 | //! an `Activate` on the gate half, and a `Mul` against the up half. Three of those move data |
| 8 | //! only to hand it to the next one. |
| 9 | //! |
| 10 | //! That is cheap on a desktop and is not on a phone. A Gemma 4 decode step is 1,094 dispatches |
| 11 | //! of which only 245 carry weights; the rest are elementwise work over a few kilobytes, and each |
| 12 | //! costs far more in dispatch and barrier overhead than in arithmetic. Two gated feed-forwards |
| 13 | //! per layer across 35 layers is 210 dispatches spent on something expressible as one. |
| 14 | //! |
| 15 | //! The slices disappear entirely: the halves are contiguous, so this reads both directly by |
| 16 | //! offset instead of copying each into scratch first. |
| 17 | //! |
| 18 | //! # Push fields |
| 19 | //! |
| 20 | //! `p.in0` is the `[2 * inner, 1, T]` projection and `p.out_at` the `[inner, 1, T]` result. |
| 21 | //! `p.count` is the output's element count. `p.in_c` is `inner`, the distance from a gate element |
| 22 | //! to its up partner. `p.act` is the [`nets::Act`] code and `p.act_weight` the slope tensor when |
| 23 | //! it is `PRelu`. `p.out_h` and `p.out_w` give the spatial size, so a per-channel activation can |
| 24 | //! recover its channel. |
| 25 | #include "common.glsl" |
| 26 | void main() { |
| 27 | uint index = global_index(); |
| 28 | if (index >= p.count) { |
| 29 | return; |
| 30 | } |
| 31 | // Both halves come from one tensor, so the up element is a fixed stride from the gate one. |
| 32 | // `p.in_c` is that stride in elements, which is `inner * spatial` - the whole gate half - |
| 33 | // rather than `inner`, because the layout is channel-major and T may exceed one. |
| 34 | uint spatial = max(p.out_h * p.out_w, 1u); |
| 35 | uint channel = index / spatial; |
| 36 | float gate = float(arena[p.in0 + index]); |
| 37 | float up = float(arena[p.in0 + p.in_c + index]); |
| 38 | arena[p.out_at + index] = float16_t(activate(gate, p.act, channel) * up); |
| 39 | } |