Modern Apps git

← Modern-Apps.git

library:ml: an exact GELU activation and an elementwise product

Commit
97f99a1cf2f4257f6477c3fe7a4635d7676f995f
Author
vayun-mathur <[email protected]>
When
2026-08-28 04:37 UTC (3 months ago)
Parents
6ca5234

Diff

library/ml/src/main/rust/shaders/common.glsl
diff --git a/library/ml/src/main/rust/shaders/common.glsl b/library/ml/src/main/rust/shaders/common.glslindex faf9e9615f..5d73f0793e 100644--- a/library/ml/src/main/rust/shaders/common.glsl+++ b/library/ml/src/main/rust/shaders/common.glsl@@ -92,6 +92,7 @@ layout(push_constant) uniform Push { #define ACT_CLIP01 5u #define ACT_SWISH 6u #define ACT_TANH 7u+#define ACT_GELU 8u  // This invocation's output element, across a 2D grid of workgroups. //@@ -154,6 +155,26 @@ float activate(float x, uint kind, uint channel) {         // both, and substituting one for the other is a plausible-looking accuracy loss.         return x / (1.0 + exp(-x));     }+    if (kind == ACT_GELU) {+        // The exact GELU, `0.5 x (1 + erf(x / sqrt(2)))`, which is what Supertonic's four nets+        // spell as an `Erf`.+        //+        // The tanh approximation would also have done: the two forms differ by at most 4.7e-4,+        // and fp16's step there is 2.0e-3. `erf` is used because it matches the export and+        // because `post::duration::erf` is the same Abramowitz and Stegun 7.1.26 series with the+        // same coefficients, so the host reference and this are one function rather than two+        // that happen to agree.+        float sign = x < 0.0 ? -1.0 : 1.0;+        float a = abs(x) * 0.70710678;+        float t = 1.0 / (1.0 + 0.3275911 * a);+        float poly = t * (0.254829592+            + t * (-0.284496736+            + t * (1.421413741+            + t * (-1.453152027+            + t * 1.061405429))));+        float erf = sign * (1.0 - poly * exp(-a * a));+        return 0.5 * x * (1.0 + erf);+    }     if (kind == ACT_TANH) {         // The last thing Piper's vocoder does, which is what bounds the waveform to         // -1..1. GLSL's `tanh` is a built-in; writing it as two exponentials would
library/ml/src/main/rust/shaders/mul.comp
diff --git a/library/ml/src/main/rust/shaders/mul.comp b/library/ml/src/main/rust/shaders/mul.compnew file mode 100644index 0000000000..9483a6ee7e--- /dev/null+++ b/library/ml/src/main/rust/shaders/mul.comp@@ -0,0 +1,22 @@+#version 450+//! Elementwise product of two equally-shaped tensors.+//!+//! Distinct from `mul_channel`, which broadcasts a `[C, 1, 1]` tensor over height and width for+//! a squeeze-excite block. This one needs both operands to be the same shape, which is what+//! Supertonic's four nets want: 241 `Mul` nodes in its flow-matching sampler alone, gating and+//! scaling whole activations rather than whole channels.+//!+//! Not fused into the producing convolution, for the same reason `add.comp` is not: both+//! operands are read elsewhere too, so a fused form would need a second input binding and a+//! flag on the convolution shader to save one pass over data already in cache.++#include "common.glsl"++void main() {+    uint index = global_index();+    if (index >= p.count) {+        return;+    }+    float product = float(arena[p.in0 + index]) * float(arena[p.in1 + index]);+    arena[p.out_at + index] = float16_t(product);+}
library/ml/src/main/rust/src/nets/mod.rs
diff --git a/library/ml/src/main/rust/src/nets/mod.rs b/library/ml/src/main/rust/src/nets/mod.rsindex 45cd819938..c61f49fc96 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -105,6 +105,18 @@ pub enum Act {     /// Seven uses in PP-OCRv5 recognition, where the export spells it out as     /// `Mul(x, Sigmoid(x))`; the fold recognises that the way it recognises HardSwish.     Swish,+    /// The **exact** GELU, `0.5 x (1 + erf(x / sqrt(2)))`.+    ///+    /// 44 uses across Supertonic's four networks, where the export spells it as an `Erf`.+    ///+    /// The tanh approximation would also have done: measured, the two forms differ by at most+    /// 4.7e-4 (at `x = 2.699`), and fp16's step there is 2.0e-3, so the difference is four+    /// times finer than the arena can represent. `erf` is used anyway for two reasons that are+    /// about agreement rather than accuracy โ€” it is what the export computes, and+    /// [`crate::post::duration::erf`] already implements the same Abramowitz and Stegun 7.1.26+    /// series for the CPU duration predictor, so the host reference and the shader are the same+    /// function by construction rather than by coincidence. The cost is comparable either way.+    Gelu,     /// `tanh(x)`.     ///     /// One use: the last thing Piper's HiFi-GAN vocoder does, which is what bounds its@@ -124,6 +136,7 @@ impl Act {             Act::Clip01 => 5,             Act::Swish => 6,             Act::Tanh => 7,+            Act::Gelu => 8,         }     } }@@ -160,6 +173,8 @@ pub enum Kind {     Add,     /// `a * b` where `b` is `C x 1 x 1`. The excite in a squeeze-excite block.     MulBroadcast,+    /// Elementwise `a * b` over two equal shapes.+    Mul,     /// `x * scale + shift`, both scalars. PP-OCRv5's "learnable affine block".     ///     /// One pass over the data for two multiplies. It exists because these sit *after* an@@ -991,6 +1006,21 @@ impl<'a> Builder<'a> {         out     } +    /// Elementwise `a * b`. Shapes must match; see [`Builder::mul_channel`] for the+    /// broadcasting form.+    ///+    /// 241 uses in Supertonic's flow-matching sampler alone, gating and scaling whole+    /// activations rather than whole channels.+    pub fn mul(&mut self, a: Id, b: Id) -> Id {+        let (sa, sb) = (self.shape_of(a), self.shape_of(b));+        if sa != sb {+            self.fail(format!("mul of {sa:?} and {sb:?}"));+        }+        let out = self.tensor(sa);+        self.nodes.push(Node::Binary { kind: Kind::Mul, a, b, out });+        out+    }+     /// `a * b` with `b` broadcast over H and W โ€” the excite half of a squeeze-excite     /// block, where `b` came from [`Builder::global_avg_pool`].     pub fn mul_channel(&mut self, a: Id, b: Id) -> Id {@@ -2060,7 +2090,9 @@ pub(crate) mod tests {                     // what they write. Every output here is dense.                     let written = push.out_c * push.out_h * push.out_w;                     let reads = match kind {-                        Kind::Add => vec![(push.in0, written), (push.in1, written)],+                        Kind::Add | Kind::Mul => {+                            vec![(push.in0, written), (push.in1, written)]+                        }                         // The gate is one value per channel, broadcast over H and W.                         Kind::MulBroadcast => {                             vec![(push.in0, written), (push.in1, push.in_c)]
library/ml/src/main/rust/src/nets/reference.rs
diff --git a/library/ml/src/main/rust/src/nets/reference.rs b/library/ml/src/main/rust/src/nets/reference.rsindex e3a760300a..eb2cdb13a4 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -61,6 +61,8 @@ mod act {     pub const SWISH: u32 = 6;     /// `tanh(x)`.     pub const TANH: u32 = 7;+    /// The exact GELU. See `super::super::Act::Gelu`.+    pub const GELU: u32 = 8; }  /// The fused activation, mirroring `activate` in `common.glsl`.@@ -82,6 +84,9 @@ fn activate(x: f32, kind: u32, slope: f32) -> f32 {         act::CLIP01 => x.clamp(0.0, 1.0),         act::SWISH => x / (1.0 + (-x).exp()),         act::TANH => x.tanh(),+        // The exact GELU. crate::post::duration::erf is the same A&S 7.1.26 series the+        // shader uses, so the two agree well inside fp16.+        act::GELU => 0.5 * x * (1.0 + crate::post::duration::erf(x * std::f32::consts::FRAC_1_SQRT_2)),         _ => x,     } }@@ -181,6 +186,7 @@ impl Reference {                     Kind::GlobalAvgPool => self.global_avg_pool(push),                     Kind::Add => self.add(push),                     Kind::MulBroadcast => self.mul_broadcast(push),+                    Kind::Mul => self.mul(push),                     Kind::Affine => self.affine(push),                     Kind::LayerNorm => self.layer_norm(push),                     Kind::AttnScores => self.attn_scores(push),@@ -747,6 +753,15 @@ impl Reference {         Ok(())     } +    /// `out = a * b`, elementwise over two equal shapes.+    fn mul(&mut self, p: &Push) -> Result<(), String> {+        for i in 0..p.count {+            let product = self.load(p.in0, i)? * self.load(p.in1, i)?;+            self.store(p.out, i, product)?;+        }+        Ok(())+    }+     /// `out[c][y][x] = a[c][y][x] * b[c]`, the excite half of a squeeze-excite block.     fn mul_broadcast(&mut self, p: &Push) -> Result<(), String> {         for oc in 0..p.out_c {@@ -1832,6 +1847,62 @@ mod tests {         assert!(error.contains("channels 3..5"), "{error}");     } +    #[test]+    fn an_elementwise_product_multiplies_position_by_position() {+        // Distinct from `mul_channel`, which broadcasts `[C, 1, 1]`. Two channels of three+        // positions, with values chosen so a broadcast would give a different answer: if this+        // took only channel 0 of `b` it would produce 2, 6, 12 in the second row.+        let got = two(+            (Shape::new(2, 1, 3), Shape::new(2, 1, 3)),+            (&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2.0, 3.0, 4.0, 5.0, 6.0, 7.0]),+            |b, a, c| b.mul(a, c),+        );+        close(&got, &[2.0, 6.0, 12.0, 20.0, 30.0, 42.0]);+    }++    #[test]+    fn an_elementwise_product_of_mismatched_shapes_is_refused() {+        let given = Given::new(&[]).expect("no tensors");+        let mut b = Builder::new(&given);+        let a = b.input(Shape::new(2, 1, 3));+        let c = b.tensor(Shape::new(2, 1, 4));+        let out = b.mul(a, c);+        let error = b.finish(&[out]).expect_err("mismatched shapes");+        assert!(error.contains("mul of"), "{error}");+    }++    #[test]+    fn gelu_matches_the_exact_erf_form() {+        // Pinned against the exact `0.5 x (1 + erf(x / sqrt(2)))`, which is what the export+        // computes. The tanh approximation would also pass at this tolerance - measured, the two+        // forms differ by at most 4.7e-4 against fp16's 2.0e-3 step - so this test does not+        // distinguish them, and the doc on `Act::Gelu` says why `erf` is used anyway. What it+        // does pin is that the activation is a GELU at all, symmetric about the right place, and+        // saturating to the identity and to zero at the tails.+        let xs = [-6.0f32, -2.0, -1.0, 0.0, 0.5, 1.0, 2.0, 6.0];+        // A 1x1 convolution with weight 1 and bias 0 is the identity, so this measures the+        // activation alone. It also routes through `ConvPoint`, so the tiled path carries it.+        let got = one(+            Shape::new(1, 1, xs.len() as u32),+            &xs,+            &[(vec![1, 1, 1, 1], vec![1.0]), (vec![1], vec![0.0])],+            |b, x| b.conv(x, 0, 1, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 1, Act::Gelu),+        );+        let want = [+            -0.0000000f32,+            -0.04550027,+            -0.15865526,+            0.0,+            0.34573123,+            0.8413447,+            1.9544997,+            6.0,+        ];+        for (i, (&g, &w)) in got.iter().zip(&want).enumerate() {+            assert!((g - w).abs() < 2e-3, "at x={}: {g} not {w}", xs[i]);+        }+    }+     #[test]     fn an_embedding_gathers_the_row_each_id_names() {         // Four symbols of three channels, looked up in an order that is neither ascending
library/ml/src/main/rust/src/post/duration.rs
diff --git a/library/ml/src/main/rust/src/post/duration.rs b/library/ml/src/main/rust/src/post/duration.rsindex 89fe803541..0944e74286 100644--- a/library/ml/src/main/rust/src/post/duration.rs+++ b/library/ml/src/main/rust/src/post/duration.rs@@ -84,7 +84,7 @@ fn tensor(weights: &Weights, index: usize, dims: &[u32]) -> Result<Vec<f32>, Str /// Rust has no `erf`, and the export's GELU is the exact one rather than the tanh /// approximation, so approximating the *activation* would be a different function. This /// approximates `erf` itself instead, well below fp16's resolution.-fn erf(x: f32) -> f32 {+pub(crate) fn erf(x: f32) -> f32 {     const A: [f32; 5] = [0.254_829_6, -0.284_496_74, 1.421_413_7, -1.453_152, 1.061_405_4];     const P: f32 = 0.327_591_1;     let sign = if x < 0.0 { -1.0 } else { 1.0 };@@ -357,11 +357,13 @@ mod tests {     }      #[test]-    fn gelu_is_the_exact_one_and_not_the_tanh_approximation() {-        // They differ by about 0.003 near x = 2, which is above fp16's resolution there.+    fn gelu_matches_the_exact_erf_form() {+        // The tanh approximation differs by at most 4.7e-4, which is below fp16's 2.0e-3 step+        // there โ€” so this is about matching the export rather than about the approximation being+        // unusable. See `nets::Act::Gelu`, which carries the same note for the shader.         assert!((gelu(0.0) - 0.0).abs() < 1e-6);-        assert!((gelu(1.0) - 0.8413447) < 1e-5);-        assert!((gelu(-1.0) + 0.15865526) < 1e-5);+        assert!((gelu(1.0) - 0.8413447).abs() < 1e-5);+        assert!((gelu(-1.0) + 0.15865526).abs() < 1e-5);         // Large inputs pass through, large negatives vanish.         assert!((gelu(6.0) - 6.0).abs() < 1e-4);         assert!(gelu(-6.0).abs() < 1e-6);
library/ml/src/main/rust/src/vulkan/pipeline.rs
diff --git a/library/ml/src/main/rust/src/vulkan/pipeline.rs b/library/ml/src/main/rust/src/vulkan/pipeline.rsindex 5fdcaee509..acccc59b57 100644--- a/library/ml/src/main/rust/src/vulkan/pipeline.rs+++ b/library/ml/src/main/rust/src/vulkan/pipeline.rs@@ -47,13 +47,14 @@ const ATTN_APPLY_RELATIVE: &[u8] =     include_bytes!(concat!(env!("OUT_DIR"), "/attn_apply_relative.comp.spv")); const EMBED: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/embed.comp.spv")); const GATED_TANH: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/gated_tanh.comp.spv"));+const MUL: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/mul.comp.spv")); const CONV_POINT: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/conv_point.comp.spv")); const CONV_INT8: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/conv_int8.comp.spv")); const FLIP_CHANNELS: &[u8] =     include_bytes!(concat!(env!("OUT_DIR"), "/flip_channels.comp.spv"));  /// Every shader, in the order [`Pipelines::create`] destructures them.-const SPIRV: [&[u8]; 22] = [+const SPIRV: [&[u8]; 23] = [     CONV,     CONV_TRANSPOSE,     MAXPOOL,@@ -76,6 +77,7 @@ const SPIRV: [&[u8]; 22] = [     FLIP_CHANNELS,     CONV_INT8,     CONV_POINT,+    MUL, ];  /// `local_size_x` in `shaders/common.glsl`. A dispatch covers `ceil(invocations / this)`@@ -121,6 +123,7 @@ pub struct Pipelines {     flip_channels: vk::Pipeline,     conv_int8: vk::Pipeline,     conv_point: vk::Pipeline,+    mul: vk::Pipeline, }  impl Pipelines {@@ -279,6 +282,7 @@ impl Pipelines {             flip_channels,             conv_int8,             conv_point,+            mul,         ] = match <[vk::Pipeline; SPIRV.len()]>::try_from(built) {             Ok(all) => all,             Err(built) => {@@ -317,6 +321,7 @@ impl Pipelines {             flip_channels,             conv_int8,             conv_point,+            mul,         })     } @@ -345,6 +350,7 @@ impl Pipelines {             Kind::FlipChannels => self.flip_channels,             Kind::ConvInt8 => self.conv_int8,             Kind::ConvPoint => self.conv_point,+            Kind::Mul => self.mul,         }     } @@ -375,6 +381,7 @@ impl Pipelines {             self.flip_channels,             self.conv_int8,             self.conv_point,+            self.mul,         ] {             device.destroy_pipeline(pipeline, None);         }