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

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

softcap.comp32 lines · 1.3 KiBRaw
1#version 450
2//! `y = tanh(x / cap) * cap`, Gemma's `final_logit_softcapping`.
3//!
4//! # Why an op and not an activation
5//!
6//! It carries a float. The activation path threads a `uint` code and, for `PRelu`, a tensor
7//! index; a parameter would mean either a new push field on every convolution or overloading
8//! `param0_bits`, which several kinds already use for something else. This runs **once** over the
9//! logits at the end of a forward pass, not per layer, so a dedicated dispatch costs one pipeline
10//! and no complexity anywhere else.
11//!
12//! # Why it cannot be folded away
13//!
14//! It is not a scale: `tanh` saturates. Dropping it changes which token wins whenever a logit
15//! exceeds the cap, which is exactly the confident predictions - so a greedy decode diverges from
16//! the reference on the tokens it is most sure about, and only on those.
17//!
18//! # Push fields
19//!
20//! `p.in0` is the input, `p.out_at` the output, `p.param0_bits` the cap as raw f32 bits, and
21//! `p.count` the element count. Shapes are irrelevant: this is elementwise.
22
23#include "common.glsl"
24
25void main() {
26 uint index = global_index();
27 if (index >= p.count) {
28 return;
29 }
30 float cap = uintBitsToFloat(p.param0_bits);
31 arena[p.out_at + index] = float16_t(tanh(float(arena[p.in0 + index]) / cap) * cap);
32}