library:ml: LayerNorm over channels, and Swish
- Commit
22c9706737814febcd476bffc35a1b031f0f26ce- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-27 17:42 UTC (3 months ago)
- Parents
23217d2
Diff
library/ml/src/main/rust/shaders/affine.comp
diff --git a/library/ml/src/main/rust/shaders/affine.comp b/library/ml/src/main/rust/shaders/affine.compindex 53098a748d..072ddb4506 100644--- a/library/ml/src/main/rust/shaders/affine.comp+++ b/library/ml/src/main/rust/shaders/affine.comp@@ -30,7 +30,7 @@ void main() { if (index >= p.count) { return; }- float scale = uintBitsToFloat(p.scale_bits);- float shift = uintBitsToFloat(p.shift_bits);+ float scale = uintBitsToFloat(p.param0_bits);+ float shift = uintBitsToFloat(p.param1_bits); arena[p.out_at + index] = float16_t(float(arena[p.in0 + index]) * scale + shift); }
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 8b69baa010..bc2f11e5a8 100644--- a/library/ml/src/main/rust/shaders/common.glsl+++ b/library/ml/src/main/rust/shaders/common.glsl@@ -66,8 +66,8 @@ layout(push_constant) uniform Push { uint group; uint act; uint act_weight;- uint scale_bits;- uint shift_bits;+ uint param0_bits;+ uint param1_bits; uint count; } p; @@ -78,6 +78,7 @@ layout(push_constant) uniform Push { #define ACT_SIGMOID 3u #define ACT_PRELU 4u #define ACT_CLIP01 5u+#define ACT_SWISH 6u // This invocation's output element, across a 2D grid of workgroups. //@@ -124,6 +125,11 @@ float activate(float x, uint kind, uint channel) { // clamp. See `nets::Act::Clip01`. return clamp(x, 0.0, 1.0); }+ if (kind == ACT_SWISH) {+ // `x * sigmoid(x)`. Not HardSwish's piecewise approximation — the recogniser uses+ // both, and substituting one for the other is a plausible-looking accuracy loss.+ return x / (1.0 + exp(-x));+ } return x; }
library/ml/src/main/rust/shaders/layernorm.comp
diff --git a/library/ml/src/main/rust/shaders/layernorm.comp b/library/ml/src/main/rust/shaders/layernorm.compnew file mode 100644index 0000000000..7aceb9008d--- /dev/null+++ b/library/ml/src/main/rust/shaders/layernorm.comp@@ -0,0 +1,61 @@+#version 450+//! Layer normalisation over the **channel** axis, with a per-channel affine.+//!+//! Five uses, all in PP-OCRv5 recognition's two transformer blocks.+//!+//! # One invocation per position, reducing over channels+//!+//! This runtime keeps a transformer's sequence as `[d_model, 1, T]` — features in+//! channels, the sequence along the width — because that is the layout the CNN backbone+//! in front of it already produces, and because splitting `d_model` into attention heads+//! is then free: `[120, 1, T]` read as `[8, 15, T]` is the same bytes in the same order.+//! See `nets::Kind::LayerNorm` for the whole argument.+//!+//! The consequence here is that the reduction is strided: `d_model` loads `in_h * in_w`+//! apart. At `d_model` 120 that is 120 loads per position, and there are `T` positions —+//! a few thousand loads for the whole layer. A contiguous layout would make this pass+//! faster and cost two `Permute`s per attention, which is the wrong trade.+//!+//! # Two passes, not Welford+//!+//! Mean then variance, reading the input twice. `d_model` is 120, so both passes sit in+//! cache; a single-pass algorithm would save bandwidth that is not being spent.+//!+//! Accumulation is `float` like everywhere else here, and `epsilon` arrives in the push+//! block because the recogniser uses 1e-5 for four of these and 1e-6 for the last.++#include "common.glsl"++void main() {+ uint position = global_index();+ if (position >= p.count) {+ return;+ }+ // `count` is `in_h * in_w`, so `position` walks the spatial extent and the channel+ // stride is that same extent.+ uint stride = p.in_h * p.in_w;+ float epsilon = uintBitsToFloat(p.param1_bits);++ float total = 0.0;+ for (uint c = 0u; c < p.in_c; c++) {+ total += float(arena[p.in0 + c * stride + position]);+ }+ float mean = total / float(p.in_c);++ float variance = 0.0;+ for (uint c = 0u; c < p.in_c; c++) {+ float centred = float(arena[p.in0 + c * stride + position]) - mean;+ variance += centred * centred;+ }+ // Biased variance, dividing by N rather than N-1, which is what every framework's+ // layer norm does at inference.+ float inverse = 1.0 / sqrt(variance / float(p.in_c) + epsilon);++ for (uint c = 0u; c < p.in_c; c++) {+ uint at = c * stride + position;+ float centred = float(arena[p.in0 + at]) - mean;+ float gamma = float(weights[p.weight + c]);+ float beta = float(weights[p.bias + c]);+ arena[p.out_at + at] = float16_t(centred * inverse * gamma + beta);+ }+}
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 129a2a3582..486dd20935 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -96,6 +96,11 @@ pub enum Act { /// runtime needs one parameterless clamp rather than an activation carrying two /// floats through the push block. Clip01,+ /// `x / (1 + exp(-x))`, i.e. ONNX `Sigmoid` multiplied by its own input.+ ///+ /// 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, } impl Act {@@ -107,6 +112,7 @@ impl Act { Act::Sigmoid => 3, Act::PRelu(_) => 4, Act::Clip01 => 5,+ Act::Swish => 6, } } }@@ -141,8 +147,30 @@ pub enum Kind { /// activation, so unlike everything else constant in that export they cannot be /// folded into the preceding convolution's weight — and pushing them into the /// *following* one needs `b' += shift * sum(W)` per output row, which is only valid- /// when the tensor feeds nothing but convolutions. 24 uses in detection.+ /// when the tensor feeds nothing but convolutions. 24 uses in detection, of which 23+ /// do fold, leaving one. Affine,+ /// Layer normalisation **over the channel axis**, with a per-channel affine.+ ///+ /// # Why over channels+ ///+ /// PP-OCRv5's recogniser is a CNN feeding a small transformer — `d_model` 120, 8+ /// heads, two blocks — and this runtime keeps its sequences in the layout the CNN+ /// already produces: `[d_model, 1, T]`, features in channels and the sequence along+ /// the width. Two things fall out of that and neither is an accident:+ ///+ /// * **Every linear projection is a 1x1 convolution.** All five feed-forward `Gemm`s+ /// and all six attention projections are already expressible, so they need no new+ /// pipeline.+ /// * **Splitting `d_model` into heads is free.** `[120, 1, T]` read as `[8, 15, T]`+ /// is the same bytes in the same order, so there is no `Permute` and no `Reshape`+ /// anywhere in the attention — the attention pipelines take the head count in+ /// [`Push::group`] and index accordingly.+ ///+ /// The cost is that the reduction here is strided rather than contiguous. At+ /// `d_model` 120 that is 120 loads a stride apart per position, which is nothing+ /// against what a contiguous layout would cost in permutes.+ LayerNorm, } /// The push-constant block every shader declares.@@ -203,9 +231,9 @@ pub struct Push { /// /// `f32` bits rather than an `f32` field so [`Push`] stays all-`u32` and /// `push_bytes` can keep treating it as a plain byte block with no padding.- pub scale_bits: u32,- /// [`Kind::Affine`]'s addend, as raw bits.- pub shift_bits: u32,+ pub param0_bits: u32,+ /// [`Kind::Affine`]'s addend, or [`Kind::LayerNorm`]'s epsilon.+ pub param1_bits: u32, /// Output elements, so an over-dispatched workgroup can bail. pub count: u32, }@@ -362,6 +390,13 @@ enum Node { scale: f32, shift: f32, },+ LayerNorm {+ input: Id,+ out: Id,+ gamma: u32,+ beta: u32,+ epsilon: f32,+ }, } /// Records a forward pass, then packs and resolves it.@@ -691,6 +726,19 @@ impl<'a> Builder<'a> { out } + /// Layer normalisation over the channel axis, with a per-channel affine.+ ///+ /// `weight_index` is the gamma tensor's position in the `.vkml` table; beta follows+ /// it, the way a convolution's bias follows its weight.+ pub fn layer_norm(&mut self, input: Id, weight_index: usize, epsilon: f32) -> Id {+ let shape = self.shape_of(input);+ let gamma = self.weight(weight_index, &[shape.c]);+ let beta = self.weight(weight_index + 1, &[shape.c]);+ let out = self.tensor(shape);+ self.nodes.push(Node::LayerNorm { input, out, gamma, beta, epsilon });+ out+ }+ /// Pack the arena and resolve every offset, with `outputs` as the result tensors. pub fn finish(mut self, outputs: &[Id]) -> Result<Plan, String> { self.pinned.extend_from_slice(outputs);@@ -951,14 +999,39 @@ impl<'a> Builder<'a> { out_c: so.c, out_h: so.h, out_w: so.w,- scale_bits: scale.to_bits(),- shift_bits: shift.to_bits(),+ param0_bits: scale.to_bits(),+ param1_bits: shift.to_bits(), count: so.len(), ..Push::default() }, invocations: so.len(), }); }+ Node::LayerNorm { input, out, gamma, beta, epsilon } => {+ let so = shape(*out);+ // One invocation per position, each reducing over the channels, so the+ // dispatch is the spatial extent rather than the element count.+ let positions = so.h * so.w;+ ops.push(Op::Dispatch {+ kind: Kind::LayerNorm,+ push: Push {+ in0: at(*input)?,+ out: at(*out)?,+ weight: *gamma,+ bias: *beta,+ in_c: so.c,+ in_h: so.h,+ in_w: so.w,+ out_c: so.c,+ out_h: so.h,+ out_w: so.w,+ param1_bits: epsilon.to_bits(),+ count: positions,+ ..Push::default()+ },+ invocations: positions,+ });+ } } Ok(()) }@@ -973,6 +1046,7 @@ impl Node { | Node::GlobalAvgPool { out, .. } | Node::Binary { out, .. } | Node::Affine { out, .. }+ | Node::LayerNorm { out, .. } | Node::Concat { out, .. } => *out, } }@@ -983,6 +1057,7 @@ impl Node { | Node::MaxPool { input, .. } | Node::Resize { input, .. } | Node::Affine { input, .. }+ | Node::LayerNorm { input, .. } | Node::GlobalAvgPool { input, .. } => vec![*input], Node::Binary { a, b, .. } => vec![*a, *b], Node::Concat { parts, .. } => parts.clone(),
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 a538e42b7a..47e6eb4ea4 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -57,6 +57,8 @@ mod act { pub const PRELU: u32 = 4; /// `clamp(x, 0, 1)`, a normalised `HardSigmoid`. pub const CLIP01: u32 = 5;+ /// `x * sigmoid(x)`.+ pub const SWISH: u32 = 6; } /// The fused activation, mirroring `activate` in `common.glsl`.@@ -76,6 +78,7 @@ fn activate(x: f32, kind: u32, slope: f32) -> f32 { } } act::CLIP01 => x.clamp(0.0, 1.0),+ act::SWISH => x / (1.0 + (-x).exp()), _ => x, } }@@ -175,6 +178,7 @@ impl Reference { Kind::Add => self.add(push), Kind::MulBroadcast => self.mul_broadcast(push), Kind::Affine => self.affine(push),+ Kind::LayerNorm => self.layer_norm(push), }, }; result.map_err(|e| format!("step {step} ({op:?}): {e}"))?;@@ -418,8 +422,8 @@ impl Reference { /// `out = in * scale + shift`, both scalars carried as raw bits in the push block. fn affine(&mut self, p: &Push) -> Result<(), String> {- let scale = f32::from_bits(p.scale_bits);- let shift = f32::from_bits(p.shift_bits);+ let scale = f32::from_bits(p.param0_bits);+ let shift = f32::from_bits(p.param1_bits); for i in 0..p.count { let value = self.load(p.in0, i)?; self.store(p.out, i, value * scale + shift)?;@@ -427,6 +431,42 @@ impl Reference { Ok(()) } + /// Layer normalisation over the channel axis, per spatial position.+ ///+ /// Biased variance, dividing by `C` rather than `C - 1`, which is what every+ /// framework does at inference. `count` is the spatial extent rather than the element+ /// count, because one invocation handles a whole column of channels.+ fn layer_norm(&mut self, p: &Push) -> Result<(), String> {+ if p.in_c == 0 {+ return Err("a layer norm over zero channels".into());+ }+ let stride = p.in_h * p.in_w;+ let epsilon = f32::from_bits(p.param1_bits);+ for position in 0..p.count {+ let mut total = 0.0;+ for c in 0..p.in_c {+ total += self.load(p.in0, c * stride + position)?;+ }+ let mean = total / p.in_c as f32;++ let mut variance = 0.0;+ for c in 0..p.in_c {+ let centred = self.load(p.in0, c * stride + position)? - mean;+ variance += centred * centred;+ }+ let inverse = 1.0 / (variance / p.in_c as f32 + epsilon).sqrt();++ for c in 0..p.in_c {+ let at = c * stride + position;+ let centred = self.load(p.in0, at)? - mean;+ let gamma = self.weight(p.weight, c)?;+ let beta = self.weight(p.bias, c)?;+ self.store(p.out, at, centred * inverse * gamma + beta)?;+ }+ }+ Ok(())+ }+ /// Elementwise sum of two equal shapes. fn add(&mut self, p: &Push) -> Result<(), String> { for i in 0..p.count {@@ -1039,6 +1079,90 @@ mod tests { } } + #[test]+ fn swish_is_x_times_sigmoid_x_and_not_hard_swish() {+ // The recogniser uses both, so the piecewise approximation must not be+ // substituted here. They differ most around |x| = 1..3.+ let inputs = [-3.0f32, -1.0, 0.0, 1.0, 3.0];+ let got = one(+ Shape::new(1, 1, 5),+ &inputs,+ &[(vec![1, 1, 1, 1], vec![1.0]), (vec![1], vec![0.0])],+ |b, x| b.conv_same(x, 0, 1, 1, 1, Act::Swish),+ );+ let want: Vec<f32> = inputs.iter().map(|&x| x / (1.0 + (-x).exp())).collect();+ close(&got, &want);+ // And it really is a different function from HardSwish at x = 1.+ let hard = 1.0 * (1.0 / 6.0 + 0.5);+ assert!((got[3] - hard).abs() > 0.05, "swish {} vs hardswish {hard}", got[3]);+ }++ #[test]+ fn layer_norm_standardises_a_column_of_channels() {+ // Four channels at one position: mean 2.5, biased variance 1.25.+ let got = one(+ Shape::new(4, 1, 1),+ &[1.0, 2.0, 3.0, 4.0],+ &[(vec![4], vec![1.0; 4]), (vec![4], vec![0.0; 4])],+ |b, x| b.layer_norm(x, 0, 1e-5),+ );+ let sd = 1.25f32.sqrt();+ close(&got, &[-1.5 / sd, -0.5 / sd, 0.5 / sd, 1.5 / sd]);+ }++ #[test]+ fn layer_norm_applies_its_affine_per_channel() {+ // A gamma and beta that differ per channel, so a shader broadcasting one value+ // over the column would be visible.+ let got = one(+ Shape::new(4, 1, 1),+ &[1.0, 2.0, 3.0, 4.0],+ &[+ (vec![4], vec![1.0, 2.0, 3.0, 4.0]),+ (vec![4], vec![10.0, 20.0, 30.0, 40.0]),+ ],+ |b, x| b.layer_norm(x, 0, 1e-5),+ );+ let sd = 1.25f32.sqrt();+ let normalised = [-1.5 / sd, -0.5 / sd, 0.5 / sd, 1.5 / sd];+ let want: Vec<f32> = (0..4)+ .map(|i| normalised[i] * (i as f32 + 1.0) + (i as f32 + 1.0) * 10.0)+ .collect();+ close(&got, &want);+ }++ #[test]+ fn layer_norm_treats_each_position_independently() {+ // Two positions with very different scales. Both standardise to the same pair, so+ // a reduction that spanned the whole tensor instead of one column would not.+ //+ // Layout is `[c, 1, T]` channel-major, so this is columns (1, 2) and (3, 10).+ let got = one(+ Shape::new(2, 1, 2),+ &[1.0, 3.0, 2.0, 10.0],+ &[(vec![2], vec![1.0, 1.0]), (vec![2], vec![0.0, 0.0])],+ |b, x| b.layer_norm(x, 0, 1e-5),+ );+ // Two channels always standardise to -1 and +1 regardless of their spread.+ close(&got, &[-1.0, -1.0, 1.0, 1.0]);+ }++ #[test]+ fn layer_norm_epsilon_comes_from_the_push_block() {+ // The recogniser uses 1e-5 for four of its five and 1e-6 for the last, so the+ // value has to travel per op. A constant column makes it the only thing that+ // stops a division by zero.+ let got = one(+ Shape::new(2, 1, 1),+ &[5.0, 5.0],+ &[(vec![2], vec![1.0, 1.0]), (vec![2], vec![0.0, 0.0])],+ |b, x| b.layer_norm(x, 0, 1e-5),+ );+ // Zero variance, so both come out at beta rather than as NaN.+ close(&got, &[0.0, 0.0]);+ assert!(got.iter().all(|v| v.is_finite()), "{got:?}");+ }+ #[test] fn relu_clamps_at_zero_without_touching_positives() { let got = one(
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 93c19787c9..c510f9664d 100644--- a/library/ml/src/main/rust/src/vulkan/pipeline.rs+++ b/library/ml/src/main/rust/src/vulkan/pipeline.rs@@ -35,6 +35,7 @@ const GAP: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/gap.comp.spv")); const ADD: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/add.comp.spv")); const MUL_BCAST: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/mul_bcast.comp.spv")); const AFFINE: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/affine.comp.spv"));+const LAYERNORM: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/layernorm.comp.spv")); /// `local_size_x` in `shaders/common.glsl`. A dispatch covers `ceil(invocations / this)` /// workgroups, and each shader bails on the over-dispatched tail.@@ -66,6 +67,7 @@ pub struct Pipelines { add: vk::Pipeline, mul_bcast: vk::Pipeline, affine: vk::Pipeline,+ layernorm: vk::Pipeline, } impl Pipelines {@@ -184,6 +186,7 @@ impl Pipelines { ADD, MUL_BCAST, AFFINE,+ LAYERNORM, ] { match compute_pipeline(device, layout, spirv) { Ok(pipeline) => built.push(pipeline),@@ -195,11 +198,21 @@ impl Pipelines { } } }- let [conv, conv_transpose, maxpool, resize, resize_nearest, gap, add, mul_bcast, affine] =- match built.as_slice() {- [a, b, c, d, e, f, g, h, i] => [*a, *b, *c, *d, *e, *f, *g, *h, *i],- _ => return Err("wrong pipeline count".into()),- };+ let [+ conv,+ conv_transpose,+ maxpool,+ resize,+ resize_nearest,+ gap,+ add,+ mul_bcast,+ affine,+ layernorm,+ ] = match built.as_slice() {+ [a, b, c, d, e, f, g, h, i, j] => [*a, *b, *c, *d, *e, *f, *g, *h, *i, *j],+ _ => return Err("wrong pipeline count".into()),+ }; cleanup.disarm(); Ok(Pipelines {@@ -216,6 +229,7 @@ impl Pipelines { add, mul_bcast, affine,+ layernorm, }) } @@ -231,6 +245,7 @@ impl Pipelines { Kind::Add => self.add, Kind::MulBroadcast => self.mul_bcast, Kind::Affine => self.affine,+ Kind::LayerNorm => self.layernorm, } } @@ -248,6 +263,7 @@ impl Pipelines { self.add, self.mul_bcast, self.affine,+ self.layernorm, ] { device.destroy_pipeline(pipeline, None); }