library:ml: rotary embeddings and a per-channel shift, for the sampler
- Commit
33e5835e64809777e5008302c85ff9d69155bd62- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-28 15:27 UTC (3 months ago)
- Parents
a66bb83
Diff
library/ml/src/main/rust/shaders/add_bcast.comp
diff --git a/library/ml/src/main/rust/shaders/add_bcast.comp b/library/ml/src/main/rust/shaders/add_bcast.compnew file mode 100644index 0000000000..673e4533b5--- /dev/null+++ b/library/ml/src/main/rust/shaders/add_bcast.comp@@ -0,0 +1,32 @@+#version 450+//! `out[c][y][x] = a[c][y][x] + b[c]`, a per-channel shift.+//!+//! Four uses, one per main block of Supertonic's flow-matching sampler. Each block is+//! conditioned on the timestep by a `Linear` from the 64-dimensional time embedding to 512+//! numbers, added to every position: `x = x + W t + b`.+//!+//! # Why the timestep side is not in the plan at all+//!+//! `W t + b` depends only on `current_step` and `total_step`, two scalars, so the host computes+//! all four 512-vectors and passes them in as one `[2048, 1, 1]` tensor that+//! `nets::Builder::slice_channels` cuts up. A sinusoidal embedding and a two-layer MLP for+//! 2,048 numbers is not worth a dispatch, let alone the `Sin` and `Cos` shaders it would need.+//!+//! # The mirror of `mul_bcast.comp`+//!+//! Same indexing, and for the same reason the two operands are separate push constants: the+//! shift is a tensor in its own right rather than a slice of the one being shifted.++#include "common.glsl"++void main() {+ uint index = global_index();+ if (index >= p.count) {+ return;+ }+ uint oc, oy, ox;+ unpack(index, oc, oy, ox);+ float value = float(arena[p.in0 + index]);+ float shift = float(arena[p.in1 + oc]);+ arena[p.out_at + index] = float16_t(value + shift);+}
library/ml/src/main/rust/shaders/rotary.comp
diff --git a/library/ml/src/main/rust/shaders/rotary.comp b/library/ml/src/main/rust/shaders/rotary.compnew file mode 100644index 0000000000..7442a4a7c1--- /dev/null+++ b/library/ml/src/main/rust/shaders/rotary.comp@@ -0,0 +1,60 @@+#version 450+//! Rotary position embedding, the half-split form: `out = x * cos + rotate_half(x) * sin`.+//!+//! Eight uses, on the query and the key of each of the four text cross-attentions in+//! Supertonic's flow-matching sampler.+//!+//! # The split is halves, not pairs+//!+//! There are two conventions and they are not interchangeable. This one splits a head's+//! `head_dim` channels down the middle and pairs channel `j` with channel `j + half`:+//!+//! out[j] = x[j] * cos[j] - x[j + half] * sin[j]+//! out[j + half] = x[j + half] * cos[j] + x[j] * sin[j]+//!+//! The other convention pairs adjacent channels `(2j, 2j + 1)`. Both rotate the same 2-planes+//! by the same angles, so both produce output of exactly the right shape and magnitude, and+//! attention scores computed with one and weights trained for the other are simply wrong. The+//! export's `Slice`s are `[0, 32)` and `[32, 64)` of a 64-wide head, so it is halves.+//!+//! # The angles come from the host+//!+//! `p.in1` is a `[2 * half, 1, W]` table: `cos` in the first `half` channels and `sin` in the+//! rest. It is a function of the position and the frequency alone, so there is nothing to train+//! and nothing to keep in the weights file — and in this export it is not even a function of the+//! absolute position. The angle is `(position / length) * theta[j]`, so a query at the middle of+//! a 60-frame latent and a key at the middle of a 20-character text get the *same* angle. That+//! is what lets an 8-head cross-attention align two sequences of different lengths, and it means+//! the table has to be rebuilt whenever either length changes. See `post::supertonic`.+//!+//! One table serves every head: `p.in_c` is `head_dim` and the frequency index is+//! `(c % head_dim) % half`.++#include "common.glsl"++void main() {+ uint index = global_index();+ if (index >= p.count) {+ return;+ }+ // The tensor is `[C, 1, W]`, so this is (channel, 0, position).+ uint channel, unused_row, position;+ unpack(index, channel, unused_row, position);++ uint head_dim = p.in_c;+ uint half_dim = head_dim / 2u;+ uint within = channel % head_dim;+ uint frequency = within % half_dim;+ // The partner channel is `half_dim` away, in whichever direction stays inside the head.+ bool lower = within < half_dim;+ uint partner = lower ? channel + half_dim : channel - half_dim;++ float angle_cos = float(arena[p.in1 + frequency * p.out_w + position]);+ float angle_sin = float(arena[p.in1 + (half_dim + frequency) * p.out_w + position]);+ float self = float(arena[p.in0 + channel * p.out_w + position]);+ float other = float(arena[p.in0 + partner * p.out_w + position]);++ // The lower half subtracts its partner's sine term; the upper half adds its own.+ float rotated = lower ? -other * angle_sin : other * angle_sin;+ arena[p.out_at + index] = float16_t(self * angle_cos + rotated);+}
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 32d27dcb59..f4cc8818fa 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -176,6 +176,12 @@ pub enum Kind { Add, /// `a * b` where `b` is `C x 1 x 1`. The excite in a squeeze-excite block. MulBroadcast,+ /// `a + b` where `b` is `C x 1 x 1`. A per-channel shift.+ ///+ /// The mirror of [`Kind::MulBroadcast`], and used for one thing: the four timestep+ /// conditioning layers of Supertonic's sampler, whose `Linear` from the time embedding the+ /// host evaluates because it depends on two scalars. See `shaders/add_bcast.comp`.+ AddBroadcast, /// Elementwise `a * b` over two equal shapes. Mul, /// `x * scale + shift`, both scalars. PP-OCRv5's "learnable affine block".@@ -314,6 +320,14 @@ pub enum Kind { /// against 50 style keys that are entirely constant — `tanh(W_key . style_key + b_key)`, /// which the converter folds to one tensor. See `shaders/constant.comp`. Constant,+ /// Rotary position embedding over a `[C, 1, W]` sequence, the **half**-split convention.+ ///+ /// `out[j] = x[j] cos - x[j + half] sin` and `out[j + half] = x[j + half] cos + x[j] sin`,+ /// within each head. The angle table is the second operand rather than a weight: in this+ /// export the angle is `(position / length) * theta`, so it depends on the sequence length+ /// and the host rebuilds it per call. See `shaders/rotary.comp` for why the pairing+ /// convention matters more than it looks.+ Rotary, } /// The push-constant block every shader declares.@@ -593,6 +607,12 @@ enum Node { out: Id, weight: u32, },+ Rotary {+ input: Id,+ angles: Id,+ out: Id,+ heads: u32,+ }, Embed { ids: Id, out: Id,@@ -1227,6 +1247,46 @@ impl<'a> Builder<'a> { out } + /// `a + b` where `b` is `C x 1 x 1`, a per-channel shift. See [`Kind::AddBroadcast`].+ pub fn add_channel(&mut self, a: Id, b: Id) -> Id {+ let (sa, sb) = (self.shape_of(a), self.shape_of(b));+ if sb.c != sa.c || sb.h != 1 || sb.w != 1 {+ self.fail(format!("add_channel of {sa:?} by {sb:?}, which is not Cx1x1"));+ }+ let out = self.tensor(sa);+ self.nodes.push(Node::Binary { kind: Kind::AddBroadcast, a, b, out });+ out+ }++ /// Rotary position embedding over a `[C, 1, W]` sequence. See [`Kind::Rotary`].+ ///+ /// `angles` is `[head_dim, 1, W]`: the cosines in its first `head_dim / 2` channels and the+ /// sines in the rest, one column per position.+ pub fn rotary(&mut self, input: Id, angles: Id, heads: u32) -> Id {+ let (sx, sa) = (self.shape_of(input), self.shape_of(angles));+ if sx.h != 1 || sa.h != 1 {+ self.fail(format!("rotary on {sx:?}: a sequence is [d_model, 1, T]"));+ }+ if heads == 0 || !sx.c.is_multiple_of(heads) {+ self.fail(format!("{} channels do not split into {heads} heads", sx.c));+ }+ let head_dim = sx.c.checked_div(heads.max(1)).unwrap_or(0);+ if head_dim == 0 || !head_dim.is_multiple_of(2) {+ self.fail(format!(+ "rotary over a head of {head_dim}: it rotates 2-planes, so the head must be even"+ ));+ }+ if sa.c != head_dim || sa.w != sx.w {+ self.fail(format!(+ "rotary angles {sa:?} for {sx:?} in {heads} heads: the table is \+ [head_dim, 1, T], cosines then sines"+ ));+ }+ let out = self.tensor(sx);+ self.nodes.push(Node::Rotary { input, angles, out, heads });+ out+ }+ /// A learned tensor copied into the arena, so it can be an operand rather than a kernel. /// /// The only op that reads nothing from the arena. See [`Kind::Constant`] for why it exists@@ -1961,6 +2021,27 @@ impl<'a> Builder<'a> { invocations: so.len(), }); }+ Node::Rotary { input, angles, out, heads } => {+ let so = shape(*out);+ ops.push(Op::Dispatch {+ kind: Kind::Rotary,+ push: Push {+ in0: at(*input)?,+ in1: at(*angles)?,+ out: at(*out)?,+ // The head width, which is what the frequency index wraps on. Not the+ // channel count.+ in_c: so.c / heads.max(&1),+ out_c: so.c,+ out_h: so.h,+ out_w: so.w,+ group: *heads,+ count: so.len(),+ ..Push::default()+ },+ invocations: so.len(),+ });+ } Node::Constant { out, weight } => { let so = shape(*out); ops.push(Op::Dispatch {@@ -2025,6 +2106,7 @@ impl Node { | Node::ConvInt8 { out, .. } | Node::AttnApply { out, .. } | Node::Constant { out, .. }+ | Node::Rotary { out, .. } | Node::Concat { out, .. } => *out, } }@@ -2046,6 +2128,7 @@ impl Node { | Node::ConvInt8 { input, .. } | Node::GlobalAvgPool { input, .. } => vec![*input], Node::Binary { a, b, .. } => vec![*a, *b],+ Node::Rotary { input, angles, .. } => vec![*input, *angles], Node::AttnScores { q: a, k: b, .. } | Node::AttnApply { probs: a, v: b, .. } | Node::AttnScoresRelative { q: a, k: b, .. }@@ -2227,10 +2310,19 @@ pub(crate) mod tests { Kind::Add | Kind::Mul => { vec![(push.in0, written), (push.in1, written)] }+ // Rotary reads a partner channel half a head away, so the whole plane,+ // and the angle table is `head_dim` channels of the same length.+ Kind::Rotary => {+ vec![(push.in0, written), (push.in1, push.in_c * push.out_w)]+ } // The gate is one value per channel, broadcast over H and W. Kind::MulBroadcast => { vec![(push.in0, written), (push.in1, push.in_c)] }+ // As `MulBroadcast`: one shift per channel.+ Kind::AddBroadcast => {+ vec![(push.in0, written), (push.in1, push.out_c)]+ } // Reads no arena at all - it is a copy out of the weights file. Kind::Constant => Vec::new(), // Q and K are each `in_c` channels but of their own lengths, which the
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 60e96f6eb7..225862f82a 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -197,6 +197,8 @@ impl Reference { Kind::AttnApplyRelative => self.attn_apply_relative(push), Kind::Embed => self.embed(push), Kind::Constant => self.constant(push),+ Kind::AddBroadcast => self.add_broadcast(push),+ Kind::Rotary => self.rotary(push), Kind::GatedTanh => self.gated_tanh(push), // The reference interpreter holds its weights as `f32`, so there is no // byte view to unpack: an int8 plan can be built and inspected on the@@ -568,6 +570,45 @@ impl Reference { Ok(()) } + /// `out[c][y][x] = a[c][y][x] + b[c]`, a per-channel shift.+ fn add_broadcast(&mut self, p: &Push) -> Result<(), String> {+ for oc in 0..p.out_c {+ let shift = self.load(p.in1, oc)?;+ for oy in 0..p.out_h {+ for ox in 0..p.out_w {+ let at = nchw(p, oc, oy, ox);+ let value = self.load(p.in0, at)?;+ self.store(p.out, at, value + shift)?;+ }+ }+ }+ Ok(())+ }++ /// Rotary position embedding, the half-split convention. See [`Kind::Rotary`].+ fn rotary(&mut self, p: &Push) -> Result<(), String> {+ let head_dim = p.in_c;+ if head_dim == 0 || !head_dim.is_multiple_of(2) {+ return Err(format!("a rotary head of {head_dim} channels"));+ }+ let half = head_dim / 2;+ for channel in 0..p.out_c {+ let within = channel % head_dim;+ let frequency = within % half;+ let lower = within < half;+ let partner = if lower { channel + half } else { channel - half };+ for position in 0..p.out_w {+ let angle_cos = self.load(p.in1, frequency * p.out_w + position)?;+ let angle_sin = self.load(p.in1, (half + frequency) * p.out_w + position)?;+ let self_value = self.load(p.in0, channel * p.out_w + position)?;+ let other = self.load(p.in0, partner * p.out_w + position)?;+ let rotated = if lower { -other } else { other } * angle_sin;+ self.store(p.out, channel * p.out_w + position, self_value * angle_cos + rotated)?;+ }+ }+ Ok(())+ }+ /// `x < 0 ? alpha * x : x`, elementwise, with `alpha` carried as raw bits. fn leaky_relu(&mut self, p: &Push) -> Result<(), String> { let alpha = f32::from_bits(p.param0_bits);@@ -2177,6 +2218,107 @@ mod tests { close(&got, &[11.0, 22.0, 33.0, 44.0, 55.0, 66.0]); } + #[test]+ fn a_per_channel_shift_broadcasts_over_the_plane() {+ // Two channels of three positions, shifted by 10 and -1. The mirror of the excite+ // multiply, and used for the sampler's timestep conditioning.+ let got = two(+ (Shape::new(2, 1, 3), Shape::new(2, 1, 1)),+ (&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[10.0, -1.0]),+ |b, x, shift| b.add_channel(x, shift),+ );+ close(&got, &[11.0, 12.0, 13.0, 3.0, 4.0, 5.0]);+ }++ #[test]+ fn a_per_channel_shift_refuses_a_full_sequence() {+ // A `[2, 1, 3]` second operand would be a plain `Add`. Taking it here would read only+ // its first column and silently drop the rest.+ let source = Given::new(&[]).expect("no tensors");+ let mut b = Builder::new(&source);+ let x = b.input(Shape::new(2, 1, 3));+ let shift = b.input(Shape::new(2, 1, 3));+ let out = b.add_channel(x, shift);+ let error = b.finish(&[out]).expect_err("a per-position shift");+ assert!(error.contains("not Cx1x1"), "{error}");+ }++ #[test]+ fn rotary_rotates_the_halves_of_each_head() {+ // One head of four channels over two positions, so `half` is 2. At position 0 the angle+ // is 0 and the rotation is the identity; at position 1 it is 90 degrees on both+ // frequencies, which sends `(a, b)` to `(-b, a)` and is unmistakable.+ let quarter = std::f32::consts::FRAC_PI_2;+ let x: Vec<f32> = vec![+ 1.0, 5.0, // channel 0+ 2.0, 6.0, // channel 1+ 3.0, 7.0, // channel 2, the partner of 0+ 4.0, 8.0, // channel 3, the partner of 1+ ];+ // `[head_dim, 1, W]`: two cosines then two sines.+ let angles: Vec<f32> = vec![+ 1.0, quarter.cos(), //+ 1.0, quarter.cos(), //+ 0.0, quarter.sin(), //+ 0.0, quarter.sin(),+ ];+ let got = two(+ (Shape::new(4, 1, 2), Shape::new(4, 1, 2)),+ (&x, &angles),+ |b, x, a| b.rotary(x, a, 1),+ );+ close(+ &got,+ &[+ 1.0, -7.0, // 1*1 - 3*0 ; 5*0 - 7*1+ 2.0, -8.0, //+ 3.0, 5.0, // 3*1 + 1*0 ; 7*0 + 5*1+ 4.0, 6.0,+ ],+ );+ }++ #[test]+ fn rotary_uses_one_angle_table_for_every_head() {+ // Two heads of two channels, one position, a 90-degree turn. Both heads must rotate,+ // and each must pair with its own partner rather than with the next head's channel —+ // a `half` computed on the channel count instead of the head width would pair channel+ // 0 with channel 2, which is head 1.+ let got = two(+ (Shape::new(4, 1, 1), Shape::new(2, 1, 1)),+ (&[1.0, 2.0, 3.0, 4.0], &[0.0, 1.0]),+ |b, x, a| b.rotary(x, a, 2),+ );+ // Head 0 is (1, 2) -> (-2, 1); head 1 is (3, 4) -> (-4, 3).+ close(&got, &[-2.0, 1.0, -4.0, 3.0]);+ }++ #[test]+ fn rotary_refuses_an_odd_head() {+ // It rotates 2-planes, so a head with no middle cannot be split.+ let source = Given::new(&[]).expect("no tensors");+ let mut b = Builder::new(&source);+ let x = b.input(Shape::new(3, 1, 2));+ let angles = b.input(Shape::new(3, 1, 2));+ let out = b.rotary(x, angles, 1);+ let error = b.finish(&[out]).expect_err("an odd head");+ assert!(error.contains("2-planes"), "{error}");+ }++ #[test]+ fn rotary_refuses_an_angle_table_of_the_wrong_width() {+ // The table is `[head_dim, 1, T]`, cosines then sines. A `[head_dim / 2, 1, T]` one —+ // the natural mistake, since there are only `head_dim / 2` frequencies — would read+ // sines out of the tensor that follows it.+ let source = Given::new(&[]).expect("no tensors");+ let mut b = Builder::new(&source);+ let x = b.input(Shape::new(4, 1, 2));+ let angles = b.input(Shape::new(2, 1, 2));+ let out = b.rotary(x, angles, 1);+ let error = b.finish(&[out]).expect_err("half a table");+ assert!(error.contains("cosines then sines"), "{error}");+ }+ #[test] fn a_relative_score_map_adds_a_banded_term_from_its_table() { // Q = K = 1 everywhere over four positions, two channels, one head. The content
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 2a1d98a40e..d28903f4f6 100644--- a/library/ml/src/main/rust/src/vulkan/pipeline.rs+++ b/library/ml/src/main/rust/src/vulkan/pipeline.rs@@ -53,9 +53,11 @@ const CONV_INT8: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/conv_int8.com const FLIP_CHANNELS: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/flip_channels.comp.spv")); const CONSTANT: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/constant.comp.spv"));+const ADD_BCAST: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/add_bcast.comp.spv"));+const ROTARY: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/rotary.comp.spv")); /// Every shader, in the order [`Pipelines::create`] destructures them.-const SPIRV: [&[u8]; 24] = [+const SPIRV: [&[u8]; 26] = [ CONV, CONV_TRANSPOSE, MAXPOOL,@@ -80,6 +82,8 @@ const SPIRV: [&[u8]; 24] = [ CONV_POINT, MUL, CONSTANT,+ ADD_BCAST,+ ROTARY, ]; /// `local_size_x` in `shaders/common.glsl`. A dispatch covers `ceil(invocations / this)`@@ -127,6 +131,8 @@ pub struct Pipelines { conv_point: vk::Pipeline, mul: vk::Pipeline, constant: vk::Pipeline,+ add_bcast: vk::Pipeline,+ rotary: vk::Pipeline, } impl Pipelines {@@ -287,6 +293,8 @@ impl Pipelines { conv_point, mul, constant,+ add_bcast,+ rotary, ] = match <[vk::Pipeline; SPIRV.len()]>::try_from(built) { Ok(all) => all, Err(built) => {@@ -327,6 +335,8 @@ impl Pipelines { conv_point, mul, constant,+ add_bcast,+ rotary, }) } @@ -357,6 +367,8 @@ impl Pipelines { Kind::ConvPoint => self.conv_point, Kind::Mul => self.mul, Kind::Constant => self.constant,+ Kind::AddBroadcast => self.add_bcast,+ Kind::Rotary => self.rotary, } } @@ -389,6 +401,8 @@ impl Pipelines { self.conv_point, self.mul, self.constant,+ self.add_bcast,+ self.rotary, ] { device.destroy_pipeline(pipeline, None); }