Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / library / ml / src / main / rust / shaders / activate.comp
activate.comp34 lines · 1.5 KiBRaw
| 1 | #version 450 |
| 2 | //! An activation on its own, applied elementwise. |
| 3 | //! |
| 4 | //! # Why this exists when every convolution already folds one |
| 5 | //! |
| 6 | //! Folding is right whenever the activation follows the projection that produced the value, which |
| 7 | //! until now was always. A **gated** feed-forward breaks that: one fused projection produces |
| 8 | //! `[gate | up]`, and the activation applies to the gate half only. There is no convolution to |
| 9 | //! fold it into, because the convolution that produced it also produced the half that must stay |
| 10 | //! linear. |
| 11 | //! |
| 12 | //! Gemma 4's MLP is `gelu(gate) * up` over a `[1536, 2 * inner]` projection, which is the case |
| 13 | //! this serves. Splitting the projection in two so each half could fold its own activation would |
| 14 | //! double the number of weight tensors and halve the width of each matmul, which is worse on both |
| 15 | //! counts. |
| 16 | //! |
| 17 | //! # Push fields |
| 18 | //! |
| 19 | //! `p.in0`, `p.out_at` and `p.count` as usual; `p.act` is the [`nets::Act`] code and |
| 20 | //! `p.act_weight` the slope tensor if it is `PRelu`. `p.out_c` and the spatial fields carry the |
| 21 | //! shape only so the channel index can be recovered for a per-channel activation. |
| 22 | |
| 23 | #include "common.glsl" |
| 24 | |
| 25 | void main() { |
| 26 | uint index = global_index(); |
| 27 | if (index >= p.count) { |
| 28 | return; |
| 29 | } |
| 30 | // The channel this element belongs to, for the one activation that is per-channel. |
| 31 | uint spatial = max(p.out_h * p.out_w, 1u); |
| 32 | uint channel = index / spatial; |
| 33 | arena[p.out_at + index] = float16_t(activate(float(arena[p.in0 + index]), p.act, channel)); |
| 34 | } |