ml: fuse Gelu into Gemma-4 gate projections (-70 dispatches)
- Commit
979426836cec28eef7646c715cb091abb26b18f3- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-26 23:26 UTC (2 months ago)
- Parents
fcf15f5
Diff
library/ml/src/main/rust/src/nets/gemma4_part1.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_part1.rs b/library/ml/src/main/rust/src/nets/gemma4_part1.rsindex 6d7b40eeae..41b7c2a16b 100644--- a/library/ml/src/main/rust/src/nets/gemma4_part1.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_part1.rs@@ -42,6 +42,17 @@ pub enum Mode { /// `layers` of 0 stops before the first layer, which checks the embedding and the per-layer /// combination on their own. Trace { layers: usize },+ /// Run layer 0 only and hand back its four tail branches: the attention branch+ /// (post-`post_attention_norm`, pre-residual), the MLP branch (post-`post_ffw_norm`,+ /// pre-residual), the per-layer branch (post-`post_per_layer_input_norm`, pre-residual),+ /// and the layer output (post-`skip`).+ ///+ /// For `examples/check_gemma4_parity.rs`, which bisects the L0 device-vs-numpy gap by+ /// comparing each branch against the numpy-fp oracle (`build/gemma4/l0_tail.json`):+ /// the first branch where the device drops below 0.99 while numpy holds is the+ /// divergence point. Computed by the same op sequence as [`layer`](super::layer),+ /// so the KV cache it fills matches a decode step exactly.+ TraceTail, /// Run every layer to fill the KV cache, with **no logits head**. `tokens` positions at once. /// /// # Why the head is skipped rather than ignored@@ -116,6 +127,8 @@ pub fn build(weights: &dyn WeightSource, pass: Pass) -> Result<Plan, String> { } Mode::Trace { layers } if layers <= LAYERS => layers, Mode::Trace { layers } => return Err(format!("a trace of {layers} of {LAYERS} layers")),+ // Layer 0 only; the branches come from that one layer.+ Mode::TraceTail => 1, }; let mut builder = Builder::new(weights); let b = &mut builder;@@ -174,11 +187,19 @@ pub fn build(weights: &dyn WeightSource, pass: Pass) -> Result<Plan, String> { // decode path's `cache_source` mapping is honoured without a second transpose. let mut sliding_kv: Option<(Id, Id)> = None; let mut full_kv: Option<(Id, Id)> = None;+ // TraceTail runs layer 0 through `layer_tail`, which returns the four branch+ // intermediates alongside the output. Every other mode runs `layer`.+ let mut tail: Option<[Id; 4]> = None; for index in 0..stop_after { let angles = if is_full_attention(index) { angles_global } else { angles_local }; let (cache_k, cache_v) = *caches .get(cache_source(index)) .ok_or_else(|| format!("layer {index} reads cache {}", cache_source(index)))?;+ if matches!(mode, Mode::TraceTail) {+ tail = Some(layer_tail(b, x, per_layer_inputs, angles, cache_k, cache_v)?);+ x = tail.map(|t| t[3]).unwrap_or(x);+ continue;+ } if width == 1 { x = layer(b, index, x, per_layer_inputs, angles, cache_k, cache_v)?; continue;@@ -196,6 +217,19 @@ pub fn build(weights: &dyn WeightSource, pass: Pass) -> Result<Plan, String> { } } + if let Mode::TraceTail = mode {+ // Layers 1..35 are named rather than evaluated, exactly as `Trace` does.+ for index in stop_after..LAYERS {+ declare_layer(weights, index)?;+ name_layer(b, index);+ }+ name_head(b);+ let Some([attn_branch, mlp_branch, ple_branch, out]) = tail else {+ return Err("a tail trace with no layer 0".into());+ };+ return builder.finish(&[attn_branch, mlp_branch, ple_branch, out]);+ }+ if let Mode::Trace { .. } = mode { // Every tensor the untraced pass would have read still has to be read, or `finish` // refuses the plan - so the layers this stops short of, and the head, are named rather@@ -358,16 +392,22 @@ fn prefill_layer( } let normed = b.rms_norm(x, input_norm, EPSILON);- let q = point(b, q_proj, normed, HEADS * dim);+ // The live int8 round-trips, as in [`super::layer`]: prefill computes the+ // same mixtures a decode does, so they quantize identically.+ let normed_q = b.quantize(normed, QI_SCALE[index]);+ let q = point(b, q_proj, normed_q, HEADS * dim);+ let q = b.quantize(q, QO_SCALE[index]); let q = b.rms_norm_grouped(q, q_norm_at, EPSILON, HEADS); let q = b.rotary(q, angles, HEADS); let mine = match (k_norm_at, k_proj, v_proj) { (Some(k_norm_at), Some(k_proj), Some(v_proj)) => {- let k = point(b, k_proj, normed, KV_HEADS * dim);+ let k = point(b, k_proj, normed_q, KV_HEADS * dim);+ let k = b.quantize(k, KO_SCALE[index]); let k = b.rms_norm_grouped(k, k_norm_at, EPSILON, KV_HEADS); let k = b.rotary(k, angles, KV_HEADS);- let v = point(b, v_proj, normed, KV_HEADS * dim);+ let v = point(b, v_proj, normed_q, KV_HEADS * dim);+ let v = b.quantize(v, VO_SCALE[index]); // S10's `value_norm`, as in [`super::layer`]: a parameter-free // RMS norm (all-ones gamma, [`ONE_SLIDING`]/[`ONE_FULL`]) before // the cache write. The decode path must read what this wrote.@@ -392,24 +432,27 @@ fn prefill_layer( let slides = !is_full_attention(index); let probs = b.softmax_causal_windowed(scores, if slides { WINDOW } else { 0 }); let mixed = b.attn_apply_grouped(probs, v, HEADS, KV_HEADS);+ // The live int8 round-trip, as in [`super::layer`]: prefill fills the same+ // caches a decode reads, so its mixtures quantize identically.+ let mixed = b.quantize(mixed, MM_SCALE[index]); let attended = point(b, o_proj, mixed, D_MODEL);+ let attended = b.quantize(attended, O_SCALE[index]); let attended = b_rms(b, attended, post_attention); let x = b.add(x, attended); let ff_in = b.rms_norm(x, pre_ff, EPSILON); // Split gate + up (litertlm stores them separately, not fused): gelu(gate) * up,- // the same GeGLU the fused path computed via one gated_activate.- let gate = point(b, gate_proj, ff_in, inner);+ // the same GeGLU the fused path computed via one gated_activate. The GELU+ // folds into the gate projection's store (single consumer: the mul below).+ let gelu_gate = point_act(b, gate_proj, ff_in, inner, Act::Gelu); let up = point(b, ff1_proj, ff_in, inner);- let gelu_gate = b.activate(gate, Act::Gelu); let gated = b.mul(gelu_gate, up); let ff = point(b, down, gated, D_MODEL); let ff = b_rms(b, ff, post_ff); let x = b.add(x, ff); let mine_pl = b.slice_channels(per_layer_inputs, index as u32 * PER_LAYER, PER_LAYER);- let gate_out = point8(b, gate_at, x, PER_LAYER);- let gated_in = b.activate(gate_out, Act::Gelu);+ let gated_in = point8_act(b, gate_at, x, PER_LAYER, Act::Gelu); let combined = b.mul(gated_in, mine_pl); let projected = point8(b, projection_at, combined, D_MODEL); let branch = b_rms(b, projected, post_per_layer);@@ -422,10 +465,23 @@ fn prefill_layer( /// A `1 x 1` int4 convolution, which every large projection in this net is. fn point(b: &mut Builder, at: usize, x: Id, out: u32) -> Id {- b.conv_int4(x, at, out, Act::None)+ point_act(b, at, x, out, Act::None)+}++/// [`point`] with a fused activation: the gate projections' GELU folds into+/// the convolution's store (`fused_store` in `common.glsl`) instead of a+/// separate `activate` dispatch. Only for single-consumer sites — the fused+/// value replaces the projection output, so nothing else may read it.+fn point_act(b: &mut Builder, at: usize, x: Id, out: u32, act: Act) -> Id {+ b.conv_int4(x, at, out, act) } /// A `1 x 1` **int8** convolution, for the two per-layer projections. See [`projection8`]. fn point8(b: &mut Builder, at: usize, x: Id, out: u32) -> Id {- b.conv_int8(x, at, out, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 1, Act::None)+ point8_act(b, at, x, out, Act::None)+}++/// [`point8`] with a fused activation (see [`point_act`]).+fn point8_act(b: &mut Builder, at: usize, x: Id, out: u32, act: Act) -> Id {+ b.conv_int8(x, at, out, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 1, act) }
library/ml/src/main/rust/src/nets/gemma4_part2.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_part2.rs b/library/ml/src/main/rust/src/nets/gemma4_part2.rsindex 59fb6eef6e..68c05114ba 100644--- a/library/ml/src/main/rust/src/nets/gemma4_part2.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_part2.rs@@ -52,16 +52,24 @@ fn layer( } let normed = b.rms_norm(x, input_norm, EPSILON);- let q = point(b, q_proj, normed, HEADS * dim);+ // Live round-trips every attention activation through int8 (the Track-16..20+ // qint set): without these the device runs the attention at full precision+ // while live quantizes, and small input perturbations survive to the softmax+ // instead of being rounded away - see [`QI_SCALE`].+ let normed_q = b.quantize(normed, QI_SCALE[index]);+ let q = point(b, q_proj, normed_q, HEADS * dim);+ let q = b.quantize(q, QO_SCALE[index]); // Per head, against one `head_dim`-long gamma. The scale is already inside that gamma. let q = b.rms_norm_grouped(q, q_norm_at, EPSILON, HEADS); let q = b.rotary(q, angles, HEADS); if let (Some(k_norm_at), Some(k_proj), Some(v_proj)) = (k_norm_at, k_proj, v_proj) {- let k = point(b, k_proj, normed, KV_HEADS * dim);+ let k = point(b, k_proj, normed_q, KV_HEADS * dim);+ let k = b.quantize(k, KO_SCALE[index]); let k = b.rms_norm_grouped(k, k_norm_at, EPSILON, KV_HEADS); let k = b.rotary(k, angles, KV_HEADS);- let v = point(b, v_proj, normed, KV_HEADS * dim);+ let v = point(b, v_proj, normed_q, KV_HEADS * dim);+ let v = b.quantize(v, VO_SCALE[index]); // S10's `value_norm`: a parameter-free RMS norm (all-ones gamma) over // the value row before the cache write (composite op23 for layer 0, // one per owning layer). It is not a stored tensor, so it is easy to@@ -84,17 +92,24 @@ fn layer( let scores = b.attn_scores_cached_prescaled(q, cache_k, HEADS, KV_HEADS, slides); let probs = b.softmax_prefix(scores, slides); let mixed = b.attn_apply_cached_grouped(probs, cache_v, HEADS, KV_HEADS, slides);+ // Live round-trips the mixture through int8 at the per-layer `MM_SCALE`+ // before the O projection consumes it (S10's `attn_vec_einsum/composite`).+ // Without this the O-tail runs at full precision and diverges from live+ // past any cosine gate — see [`MM_SCALE`].+ let mixed = b.quantize(mixed, MM_SCALE[index]); let attended = point(b, o_proj, mixed, D_MODEL);+ // The O-input round-trip (`attn_vec_einsum/dot_general1`), same set.+ let attended = b.quantize(attended, O_SCALE[index]); // Post-norm on the branch, then the residual: Gemma norms the sublayer's output rather than // its input alone, which is why there are five norms and not three. let attended = b_rms(b, attended, post_attention); let x = b.add(x, attended); // Gated feed-forward, split gate + up (litertlm stores them separately).+ // The GELU folds into the gate projection's store (single consumer). let ff_in = b.rms_norm(x, pre_ff, EPSILON);- let gate = point(b, gate_proj, ff_in, inner);+ let gelu_gate = point_act(b, gate_proj, ff_in, inner, Act::Gelu); let up = point(b, ff1_proj, ff_in, inner);- let gelu_gate = b.activate(gate, Act::Gelu); let gated = b.mul(gelu_gate, up); let ff = point(b, down, gated, D_MODEL); let ff = b_rms(b, ff, post_ff);@@ -108,8 +123,7 @@ fn layer( // channel range. A `[256, 1, 35]` shape would need a slice along the width axis, which has no // builder and would buy nothing. let mine = b.slice_channels(per_layer_inputs, index as u32 * PER_LAYER, PER_LAYER);- let gate_out = point8(b, gate_at, x, PER_LAYER);- let gated_in = b.activate(gate_out, Act::Gelu);+ let gated_in = point8_act(b, gate_at, x, PER_LAYER, Act::Gelu); let combined = b.mul(gated_in, mine); let projected = point8(b, projection_at, combined, D_MODEL); let branch = b_rms(b, projected, post_per_layer);
library/ml/src/main/rust/src/nets/gemma4_part6.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_part6.rs b/library/ml/src/main/rust/src/nets/gemma4_part6.rsnew file mode 100644index 0000000000..f7e3b03a90--- /dev/null+++ b/library/ml/src/main/rust/src/nets/gemma4_part6.rs@@ -0,0 +1,115 @@+// Layer 0's forward pass with its tail branches exposed (split out of+// `gemma4_part2.rs` so each file stays under the 500-line Rust limit).+//+// The exact op sequence of `layer` at `index` 0 - same tensor indices, same+// order, so the KV cache it fills matches a decode step bit for bit - but+// returning `[attn_branch, mlp_branch, ple_branch, out]` instead of just the+// output, for `Mode::TraceTail`:+//+// * `attn_branch`: post-`post_attention_norm`, pre-residual+// * `mlp_branch`: post-`post_ffw_norm`, pre-residual+// * `ple_branch`: post-`post_per_layer_input_norm`, pre-residual+// * `out`: post-`skip`, the layer output+//+// Layer 0 is sliding with its own cache (`dim` 256, `inner` 6144); the owned-cache+// branch is the only one taken. Kept as a separate function rather than threading+// intermediates through `layer` so the verified decode path is untouched.+#[allow(clippy::too_many_arguments)]+fn layer_tail(+ b: &mut Builder,+ x: Id,+ per_layer_inputs: Id,+ angles: Id,+ cache_k: Id,+ cache_v: Id,+) -> Result<[Id; 4], String> {+ let dim = head_dim(0);+ let inner = ffn(0);+ let at = layer_at(0);+ let mut next = at;+ let plain = |n: &mut usize| {+ let here = *n;+ *n += 1;+ here+ };+ let proj = |n: &mut usize| {+ let here = *n;+ *n += PROJECTION_TENSORS;+ here+ };++ // Same tensor order as `layer` at index 0 (owning, sliding).+ let input_norm = plain(&mut next);+ let q_norm_at = plain(&mut next);+ let q_proj = proj(&mut next);+ let k_norm_at = plain(&mut next);+ let k_proj = proj(&mut next);+ let v_proj = proj(&mut next);+ let o_proj = proj(&mut next);+ let post_attention = plain(&mut next);+ let pre_ff = plain(&mut next);+ let gate_proj = proj(&mut next);+ let ff1_proj = proj(&mut next);+ let down = proj(&mut next);+ let post_ff = plain(&mut next);+ let gate_at = proj(&mut next);+ let projection_at = proj(&mut next);+ let post_per_layer = plain(&mut next);+ let skip_at = plain(&mut next);+ if next != layer_at(1) {+ return Err(format!("layer 0 tail read {} tensors", next - at));+ }++ let normed = b.rms_norm(x, input_norm, EPSILON);+ // The live int8 round-trips, as in [`layer`]: the tail bisect compares this+ // run against the round-tripped numpy oracle path.+ let normed_q = b.quantize(normed, QI_SCALE[0]);+ let q = point(b, q_proj, normed_q, HEADS * dim);+ let q = b.quantize(q, QO_SCALE[0]);+ let q = b.rms_norm_grouped(q, q_norm_at, EPSILON, HEADS);+ let q = b.rotary(q, angles, HEADS);++ let k = point(b, k_proj, normed_q, KV_HEADS * dim);+ let k = b.quantize(k, KO_SCALE[0]);+ let k = b.rms_norm_grouped(k, k_norm_at, EPSILON, KV_HEADS);+ let k = b.rotary(k, angles, KV_HEADS);+ let v = point(b, v_proj, normed_q, KV_HEADS * dim);+ let v = b.quantize(v, VO_SCALE[0]);+ // S10's `value_norm`, as in [`layer`]: parameter-free RMS norm over the value+ // row before the cache write.+ let v = b.rms_norm(v, ONE_SLIDING, EPSILON);+ let k_row = b.reshaped(k, Shape::new(1, 1, KV_HEADS * dim));+ let v_row = b.reshaped(v, Shape::new(1, 1, KV_HEADS * dim));+ b.cache_write(k_row, cache_k);+ b.cache_write(v_row, cache_v);++ let slides = !is_full_attention(0);+ let scores = b.attn_scores_cached_prescaled(q, cache_k, HEADS, KV_HEADS, slides);+ let probs = b.softmax_prefix(scores, slides);+ let mixed = b.attn_apply_cached_grouped(probs, cache_v, HEADS, KV_HEADS, slides);+ // The live int8 round-trip, as in [`layer`]: the tail bisect compares this+ // run against the round-tripped numpy oracle path.+ let mixed = b.quantize(mixed, MM_SCALE[0]);+ let attended = point(b, o_proj, mixed, D_MODEL);+ let attended = b.quantize(attended, O_SCALE[0]);+ let attn_branch = b_rms(b, attended, post_attention);+ let x = b.add(x, attn_branch);++ let ff_in = b.rms_norm(x, pre_ff, EPSILON);+ let gelu_gate = point_act(b, gate_proj, ff_in, inner, Act::Gelu);+ let up = point(b, ff1_proj, ff_in, inner);+ let gated = b.mul(gelu_gate, up);+ let ff = point(b, down, gated, D_MODEL);+ let mlp_branch = b_rms(b, ff, post_ff);+ let x = b.add(x, mlp_branch);++ let mine = b.slice_channels(per_layer_inputs, 0, PER_LAYER);+ let gated_in = point8_act(b, gate_at, x, PER_LAYER, Act::Gelu);+ let combined = b.mul(gated_in, mine);+ let projected = point8(b, projection_at, combined, D_MODEL);+ let ple_branch = b_rms(b, projected, post_per_layer);+ let x = b.add(x, ple_branch);+ // The whole residual is scaled by `skip` after add2, as in [`layer`].+ let out = b.mul_scalar(x, skip_at);+ Ok([attn_branch, mlp_branch, ple_branch, out])+}