Modern Apps git

← Modern-Apps.git

ml: fuse post-norm residuals into RmsNorm stores (-70 dispatches)

Commit
a6b03f4c43e5d5fa676dc20d447fc086ea428985
Author
vayun-mathur <[email protected]>
When
2026-09-26 23:33 UTC (2 months ago)
Parents
9794268

Diff

library/ml/src/main/rust/shaders/rmsnorm.comp
diff --git a/library/ml/src/main/rust/shaders/rmsnorm.comp b/library/ml/src/main/rust/shaders/rmsnorm.compindex 851759ad8a..5e8c5cfcee 100644--- a/library/ml/src/main/rust/shaders/rmsnorm.comp+++ b/library/ml/src/main/rust/shaders/rmsnorm.comp@@ -44,13 +44,20 @@ void main() {     }     // Epsilon is inside the square root, matching `torch.nn.RMSNorm`.     float inverse = 1.0 / sqrt(squares / float(per_group) + epsilon);-     for (uint c = 0u; c < per_group; c++) {         // Gamma is indexed *within* the group, so a per-head norm re-uses one `head_dim`-long         // table across every head rather than needing one per head.         uint at = (base + c) * stride + at_pos;         float value = float(arena[p.in0 + at]);         float gamma = float(weights[p.weight + c]);-        arena[p.out_at + at] = float16_t(value * inverse * gamma);+        float normed = value * inverse * gamma;+        // A residual addend folded by `Builder::finish` (see `Push::res`): the+        // post-norm `add(x, branch)` stores here instead of its own dispatch.+        // Same contract as the convolution shaders' `fused_store`, minus the+        // activation and bias they carry and this norm does not.+        if (p.res != 0xFFFFFFFFu) {+            normed += float(arena[p.res + at]);+        }+        arena[p.out_at + at] = float16_t(normed);     } }
library/ml/src/main/rust/src/nets/mod_part1.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part1.rs b/library/ml/src/main/rust/src/nets/mod_part1.rsindex 50f5870d93..f173fb9b7d 100644--- a/library/ml/src/main/rust/src/nets/mod_part1.rs+++ b/library/ml/src/main/rust/src/nets/mod_part1.rs@@ -320,6 +320,7 @@ impl Kind {             | Kind::SoftmaxPrefix             | Kind::CacheWrite             | Kind::Softcap+            | Kind::Quantize             | Kind::GatedActivate => {}             Kind::Activate             | Kind::MulScalar@@ -438,16 +439,25 @@ impl Kind {             | Kind::ResizeNearest             | Kind::GlobalAvgPool             | Kind::LayerNorm-            | Kind::RmsNorm             | Kind::Softmax             | Kind::SoftmaxCausal             | Kind::SoftmaxPrefix             | Kind::Affine             | Kind::Softcap+            | Kind::Quantize             | Kind::Activate             | Kind::GatedActivate             | Kind::MulScalar             | Kind::Clamp => one(push.in0, dense),+            // As above, plus a folded residual addend (see `Push::res`): the+            // post-norm `add(x, branch)` the fusion moved into this store.+            Kind::RmsNorm => {+                let mut ranges = vec![(push.in0, dense)];+                if push.res != NO_FUSE {+                    ranges.push((push.res, written));+                }+                Reads::Ranges(ranges)+            }         }     } }
library/ml/src/main/rust/src/nets/mod_part10.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part10.rs b/library/ml/src/main/rust/src/nets/mod_part10.rsindex 0f6b09d7f9..6cb110d5c4 100644--- a/library/ml/src/main/rust/src/nets/mod_part10.rs+++ b/library/ml/src/main/rust/src/nets/mod_part10.rs@@ -27,6 +27,7 @@ impl Node {             | Node::ConcatPositions { out, .. }             | Node::Concat { out, .. } => *out,             | Node::Softcap { out, .. } => *out,+            | Node::Quantize { out, .. } => *out,             | Node::Activate { out, .. }             | Node::GatedActivate { out, .. } => *out,             | Node::MulScalar { out, .. } => *out,@@ -56,9 +57,9 @@ impl Node {             | Node::Resize { input, .. }             | Node::Affine { input, .. }             | Node::LayerNorm { input, .. }-            | Node::RmsNorm { input, .. }             | Node::Softmax { input, .. }             | Node::Softcap { input, .. }+            | Node::Quantize { input, .. }             | Node::GatedActivate { input, .. }             | Node::Activate { input, .. }             | Node::MulScalar { input, .. }@@ -66,6 +67,11 @@ impl Node {             | Node::Embed { ids: input, .. }             | Node::SliceChannels { input, .. }             | Node::GlobalAvgPool { input, .. } => vec![*input],+            Node::RmsNorm { input, res, .. } => {+                let mut reads = vec![*input];+                reads.extend(res.iter().copied());+                reads+            }             Node::Binary { a, b, .. } => vec![*a, *b],             Node::Rotary { input, angles, .. } => vec![*input, *angles],             Node::AttnScores { q: a, k: b, .. }@@ -97,7 +103,10 @@ impl Node { /// binary as its own op. fn producer_of(nodes: &[Node], id: Id) -> Option<usize> {     nodes.iter().position(|node| {-        matches!(node, Node::Conv { .. } | Node::ConvInt8 { .. }) && node.out() == id+        matches!(+            node,+            Node::Conv { .. } | Node::ConvInt8 { .. } | Node::RmsNorm { .. }+        ) && node.out() == id     }) } 
library/ml/src/main/rust/src/nets/mod_part2.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part2.rs b/library/ml/src/main/rust/src/nets/mod_part2.rsindex 5dc5c66bd0..9eeaa79a8f 100644--- a/library/ml/src/main/rust/src/nets/mod_part2.rs+++ b/library/ml/src/main/rust/src/nets/mod_part2.rs@@ -247,6 +247,8 @@ pub(crate) enum Node {         epsilon: f32,         /// Contiguous runs of channels normalised independently. One for a whole-axis norm.         groups: u32,+        /// A residual addend folded into the store. See [`Push::res`].+        res: Option<Id>,     },     AttnScores {         q: Id,@@ -305,6 +307,12 @@ pub(crate) enum Node {         out: Id,         cap: f32,     },+    /// `clamp(round(x / scale), -128, 127) * scale`. See [`Kind::Quantize`].+    Quantize {+        input: Id,+        out: Id,+        scale: f32,+    },     /// An activation on its own. See [`Kind::Activate`].     Activate {         input: Id,
library/ml/src/main/rust/src/nets/mod_part5.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part5.rs b/library/ml/src/main/rust/src/nets/mod_part5.rsindex 46cf87b7b9..b091b97001 100644--- a/library/ml/src/main/rust/src/nets/mod_part5.rs+++ b/library/ml/src/main/rust/src/nets/mod_part5.rs@@ -275,7 +275,7 @@ impl<'a> Builder<'a> {         let per_group = shape.c.checked_div(groups.max(1)).unwrap_or(0);         let gamma = self.weight(weight_index, &[per_group]);         let out = self.tensor(shape);-        self.nodes.push(Node::RmsNorm { input, out, gamma, epsilon, groups });+        self.nodes.push(Node::RmsNorm { input, out, gamma, epsilon, groups, res: None });         out     } 
library/ml/src/main/rust/src/nets/mod_part7.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part7.rs b/library/ml/src/main/rust/src/nets/mod_part7.rsindex 617cafc373..be671e7dc4 100644--- a/library/ml/src/main/rust/src/nets/mod_part7.rs+++ b/library/ml/src/main/rust/src/nets/mod_part7.rs@@ -320,6 +320,10 @@ impl<'a> Builder<'a> {     /// never becomes a dispatch. Same for the timestep `AddBroadcast`: it adds one value per     /// channel, so the store adds `arena[shift + channel]` alongside.     ///+    /// RmsNorm producers fold the same way: a post-norm residual (`add(x, rms(...))`)+    /// stores `norm(input) + residual` directly. Only the `res` half applies (no+    /// activation, no bias, no shift on a norm store).+    ///     /// Runs to fixpoint because the two chain: the residual add's output feeds the timestep     /// shift, so the first iteration folds the add into the convolution and the second folds     /// the shift into the same store. Runs before [`Builder::last_use`] so liveness, the@@ -328,10 +332,10 @@ impl<'a> Builder<'a> {     ///     /// # What can fold, and what cannot     ///-    /// The producer must be a `Conv` or `ConvInt8` node whose output the binary is the only+    /// The producer must be a `Conv`, `ConvInt8` or `RmsNorm` node whose output the binary is the only     /// reader of — counted over node inputs *and* plan outputs, since an output tensor has to     /// survive even when nothing downstream reads it. Anything else (a second reader, a plan-    /// output, a non-convolution producer) keeps the add as its own op, which is always+    /// output, a non-folding producer) keeps the add as its own op, which is always     /// correct and merely one dispatch.     ///     /// Only `Add` and `AddBroadcast` fold. A fused multiply would have to round differently@@ -420,8 +424,11 @@ impl<'a> Builder<'a> {         let Some((i, index, residual, shift, out)) = folded else {             return false;         };-        // The output tensor moves onto the convolution: it stores the sum directly, and+        // The output tensor moves onto the producer: it stores the sum directly, and         // the producer's old output — now unread by anything — is never allocated.+        // A convolution stores `activate(acc + bias) + residual`; an RmsNorm+        // stores `norm(input) + residual` (no activation, no bias, no shift —+        // only the `res` half of the fold applies).         match &mut self.nodes[index] {             Node::Conv { out: conv_out, res, shift: fused_shift, .. } => {                 *conv_out = out;@@ -441,7 +448,16 @@ impl<'a> Builder<'a> {                     *fused_shift = shift;                 }             }-            // `producer_of` only returns convolution nodes, so reaching this means the+            Node::RmsNorm { out: norm_out, res: fused_res, .. } => {+                if shift.is_some() {+                    return false;+                }+                *norm_out = out;+                if residual.is_some() {+                    *fused_res = residual;+                }+            }+            // `producer_of` only returns convolution and norm nodes, so reaching this means the             // predicate and the application disagree — a bug, and folding nothing is the             // safe side of it.             _ => return false,
library/ml/src/main/rust/src/nets/mod_part9.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part9.rs b/library/ml/src/main/rust/src/nets/mod_part9.rsindex 4ed8bc67d4..59414da450 100644--- a/library/ml/src/main/rust/src/nets/mod_part9.rs+++ b/library/ml/src/main/rust/src/nets/mod_part9.rs@@ -378,10 +378,17 @@ impl<'a> Builder<'a> {                     invocations: positions,                 });             }-            Node::RmsNorm { input, out, gamma, epsilon, groups } => {+            Node::RmsNorm { input, out, gamma, epsilon, groups, res } => {                 let so = shape(*out);                 // One invocation per group per position, reducing over that group's channels.                 let positions = so.h * so.w * groups.max(&1);+                // A folded residual addend, or NO_FUSE. Same contract as the+                // convolution kinds: `fused_store` in the shader adds+                // `arena[res + index]`, and `arena_reads` covers the range.+                let res_at = match res {+                    Some(id) => at(*id)?,+                    None => crate::nets::NO_FUSE,+                };                 ops.push(Op::Dispatch {                     kind: Kind::RmsNorm,                     push: Push {@@ -397,6 +404,7 @@ impl<'a> Builder<'a> {                         group: *groups,                         param1_bits: epsilon.to_bits(),                         count: positions,+                        res: res_at,                         ..Push::default()                     },                     invocations: positions,
library/ml/src/main/rust/src/nets/reference_part2.rs
diff --git a/library/ml/src/main/rust/src/nets/reference_part2.rs b/library/ml/src/main/rust/src/nets/reference_part2.rsindex ec4f5b69d1..8da7848b2d 100644--- a/library/ml/src/main/rust/src/nets/reference_part2.rs+++ b/library/ml/src/main/rust/src/nets/reference_part2.rs@@ -286,7 +286,16 @@                 let value = self.load(p.in0, at)?;                 // Gamma is indexed within the group, so every group shares one table.                 let gamma = self.weight(p.weight, c)?;-                self.store(p.out, at, value * inverse * gamma)?;+                let normed = value * inverse * gamma;+                // A residual addend folded by `Builder::finish` (see `Push::res`):+                // the post-norm `add(x, branch)` the fusion moved into this+                // store. Same contract as the convolution stores.+                let folded = if p.res == super::NO_FUSE {+                    normed+                } else {+                    normed + self.load(p.res, at)?+                };+                self.store(p.out, at, folded)?;             }         }         Ok(())