Modern Apps git

← Modern-Apps.git

ml: fold 170 Quantize dispatches into producer stores

Commit
f4af0eafabbb8f39d7df2db383f86fae11aae1d0
Author
vayun-mathur <[email protected]>
When
2026-09-29 15:21 UTC (2 months ago)
Parents
7a9b40c

Diff

library/ml/src/main/rust/shaders/attn_apply_cached.comp
diff --git a/library/ml/src/main/rust/shaders/attn_apply_cached.comp b/library/ml/src/main/rust/shaders/attn_apply_cached.compindex e00c397ff3..4b8e839458 100644--- a/library/ml/src/main/rust/shaders/attn_apply_cached.comp+++ b/library/ml/src/main/rust/shaders/attn_apply_cached.comp@@ -61,5 +61,7 @@ void main() {     for (uint j = attn_first(); j <= attn_last(stride); j++) {         total += float(arena[row + j]) * float(arena[value + j * vstride]);     }-    arena[p.out_at + channel] = float16_t(total);+    // A folded int8 round-trip: the attention mixture's `Quantize` (live's+    // `Mm` round-trip at `MM_SCALE`) stores here instead of its own dispatch.+    arena[p.out_at + channel] = float16_t(quant_store(total)); }
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 2406a1a285..50f31e645c 100644--- a/library/ml/src/main/rust/shaders/common.glsl+++ b/library/ml/src/main/rust/shaders/common.glsl@@ -373,3 +373,27 @@ float fused_store(float acc, uint act, uint channel, uint index) {     }     return value; }++// The int8 round-trip folded into a producer's store: `quant_store` is the+// outermost operation, after `fused_store`.+//+// `Builder::fuse_quantize` absorbs a single-consumer `Quantize` into the store+// that produced its input, so the store keeps+// `quantize(activate(acc + bias) + res + shift)` and the round-trip never+// becomes a dispatch. `p.param0_bits` carries the scale as raw f32 bits — the+// same convention as `quantize.comp`'s — and zero bits mean unfused, which is+// what `Push::default` leaves on every op the fold did not touch.+//+// The fused form rounds once (here) where the unfolded pair would round twice+// (the producer's fp16 store, then the quantize's). That is the same contract+// as `fused_store`'s own single rounding: the reference implements this form,+// and parity is against live, not against the unfolded pair.+float quant_store(float value) {+    if (p.param0_bits == 0u) {+        return value;+    }+    float scale = uintBitsToFloat(p.param0_bits);+    float q = floor(value / scale + 0.5);+    q = clamp(q, -128.0, 127.0);+    return q * scale;+}
library/ml/src/main/rust/shaders/conv_int8.comp
diff --git a/library/ml/src/main/rust/shaders/conv_int8.comp b/library/ml/src/main/rust/shaders/conv_int8.compindex c34e7b753c..d7f85b1ff9 100644--- a/library/ml/src/main/rust/shaders/conv_int8.comp+++ b/library/ml/src/main/rust/shaders/conv_int8.comp@@ -71,5 +71,5 @@ void main() {      float scale = float(weights[p.act_weight + oc]);     float biased = total * scale + float(weights[p.bias + oc]);-    arena[p.out_at + index] = float16_t(fused_store(biased, p.act, oc, index));+    arena[p.out_at + index] = float16_t(quant_store(fused_store(biased, p.act, oc, index))); }
library/ml/src/main/rust/shaders/conv_point_int4.comp
diff --git a/library/ml/src/main/rust/shaders/conv_point_int4.comp b/library/ml/src/main/rust/shaders/conv_point_int4.compindex dac1acdbd2..fb2956baf2 100644--- a/library/ml/src/main/rust/shaders/conv_point_int4.comp+++ b/library/ml/src/main/rust/shaders/conv_point_int4.comp@@ -86,7 +86,7 @@ void main() {             }             // Already scaled in the staging above, so only the bias is left.             uint index = channel * positions + position;-            float value = fused_store(acc[i][j] + offset, p.act, channel, index);+            float value = quant_store(fused_store(acc[i][j] + offset, p.act, channel, index));             arena[p.out_at + index] = float16_t(value);         }     }
library/ml/src/main/rust/shaders/conv_point_int8.comp
diff --git a/library/ml/src/main/rust/shaders/conv_point_int8.comp b/library/ml/src/main/rust/shaders/conv_point_int8.compindex 1b332db0bd..8b9be95ff7 100644--- a/library/ml/src/main/rust/shaders/conv_point_int8.comp+++ b/library/ml/src/main/rust/shaders/conv_point_int8.comp@@ -107,7 +107,7 @@ void main() {                 continue;             }             uint index = channel * positions + position;-            float value = fused_store(acc[i][j] * scale + offset, p.act, channel, index);+            float value = quant_store(fused_store(acc[i][j] * scale + offset, p.act, channel, index));             arena[p.out_at + index] = float16_t(value);         }     }
library/ml/src/main/rust/shaders/conv_point_q2k.comp
diff --git a/library/ml/src/main/rust/shaders/conv_point_q2k.comp b/library/ml/src/main/rust/shaders/conv_point_q2k.compindex 96526e29fc..c988c07d89 100644--- a/library/ml/src/main/rust/shaders/conv_point_q2k.comp+++ b/library/ml/src/main/rust/shaders/conv_point_q2k.comp@@ -124,7 +124,7 @@ void main() {                 continue;             }             uint index = channel * positions + position;-            float value = fused_store(acc[i][j] + offset, p.act, channel, index);+            float value = quant_store(fused_store(acc[i][j] + offset, p.act, channel, index));             arena[p.out_at + index] = float16_t(value);         }     }
library/ml/src/main/rust/shaders/conv_q2k.comp
diff --git a/library/ml/src/main/rust/shaders/conv_q2k.comp b/library/ml/src/main/rust/shaders/conv_q2k.compindex 7cc7dd7e45..029b340e90 100644--- a/library/ml/src/main/rust/shaders/conv_q2k.comp+++ b/library/ml/src/main/rust/shaders/conv_q2k.comp@@ -71,5 +71,5 @@ void main() {         }     }     float offset = float(weights[p.bias + channel]);-    arena[p.out_at + index] = float16_t(fused_store(total + offset, p.act, channel, index));+    arena[p.out_at + index] = float16_t(quant_store(fused_store(total + offset, p.act, channel, index))); }
library/ml/src/main/rust/shaders/conv_vec_int4.comp
diff --git a/library/ml/src/main/rust/shaders/conv_vec_int4.comp b/library/ml/src/main/rust/shaders/conv_vec_int4.compindex 4987b4e221..f7ba5cce59 100644--- a/library/ml/src/main/rust/shaders/conv_vec_int4.comp+++ b/library/ml/src/main/rust/shaders/conv_vec_int4.comp@@ -192,5 +192,5 @@ void main() {     }     // Already scaled inside the loop, so only the bias is left.     float offset = float(weights[p.bias + channel]);-    arena[p.out_at + channel] = float16_t(fused_store(total + offset, p.act, channel, channel));+    arena[p.out_at + channel] = float16_t(quant_store(fused_store(total + offset, p.act, channel, channel))); }
library/ml/src/main/rust/shaders/conv_vec_int8.comp
diff --git a/library/ml/src/main/rust/shaders/conv_vec_int8.comp b/library/ml/src/main/rust/shaders/conv_vec_int8.compindex 531e2873e9..a1989314de 100644--- a/library/ml/src/main/rust/shaders/conv_vec_int8.comp+++ b/library/ml/src/main/rust/shaders/conv_vec_int8.comp@@ -129,5 +129,5 @@ void main() {     }     float scale = float(weights[p.act_weight + channel]);     float offset = float(weights[p.bias + channel]);-    arena[p.out_at + channel] = float16_t(fused_store(total * scale + offset, p.act, channel, channel));+    arena[p.out_at + channel] = float16_t(quant_store(fused_store(total * scale + offset, p.act, channel, channel))); }
library/ml/src/main/rust/shaders/conv_vec_q2k.comp
diff --git a/library/ml/src/main/rust/shaders/conv_vec_q2k.comp b/library/ml/src/main/rust/shaders/conv_vec_q2k.compindex f3addee279..8a124fc4a5 100644--- a/library/ml/src/main/rust/shaders/conv_vec_q2k.comp+++ b/library/ml/src/main/rust/shaders/conv_vec_q2k.comp@@ -139,5 +139,5 @@ void main() {     }     // Already scaled inside the loop, so only the bias is left.     float offset = float(weights[p.bias + channel]);-    arena[p.out_at + channel] = float16_t(fused_store(total + offset, p.act, channel, channel));+    arena[p.out_at + channel] = float16_t(quant_store(fused_store(total + offset, p.act, channel, channel))); }
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 5e8c5cfcee..9ce9875fb1 100644--- a/library/ml/src/main/rust/shaders/rmsnorm.comp+++ b/library/ml/src/main/rust/shaders/rmsnorm.comp@@ -50,7 +50,12 @@ void main() {         uint at = (base + c) * stride + at_pos;         float value = float(arena[p.in0 + at]);         float gamma = float(weights[p.weight + c]);-        float normed = value * inverse * gamma;+        // A folded int8 round-trip (`quant_store`) applies to the norm output+        // itself — the `Quantize` this norm's consumer was — before the+        // residual below: the unfolded graph is `add(res, rmsnorm(quantize))`,+        // and the add-fold already proved exact, so rounding the norm output+        // first is too.+        float normed = quant_store(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
library/ml/src/main/rust/src/bridge_part11.rs
diff --git a/library/ml/src/main/rust/src/bridge_part11.rs b/library/ml/src/main/rust/src/bridge_part11.rsindex 35bf2db382..699cacc44e 100644--- a/library/ml/src/main/rust/src/bridge_part11.rs+++ b/library/ml/src/main/rust/src/bridge_part11.rs@@ -4,7 +4,7 @@ // `createGemma4` / `encodeGemma4` JNI entry points with their builder. // // Same module scope via `bridge.rs` (`include!`), so item order is-// irrelevant � e.g. `CHUNK` here is read by `prefill` in part6.+// irrelevant — e.g. `CHUNK` here is read by `prefill` in part6.  /// Host `combine`: projection + grouped-norm + scaled add over rows the /// caller already gathered. Mirrors `gemma4_part4::combine` exactly (which
library/ml/src/main/rust/src/nets/gemma4_part3.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_part3.rs b/library/ml/src/main/rust/src/nets/gemma4_part3.rsindex 0fd04b6de5..743fbe714f 100644--- a/library/ml/src/main/rust/src/nets/gemma4_part3.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_part3.rs@@ -159,7 +159,9 @@ mod tests {     fn every_layer_gates_its_feed_forward_twice() {         // Two gates a layer, both split (litertlm stores gate and up separately,         // not fused): the MLP's `gelu(gate) * up` and the per-layer input's-        // `gelu(x @ gate) * per_layer[layer]`. Each is an `Activate` plus a `Mul`.+        // `gelu(x @ gate) * per_layer[layer]`. The GELU folds into the gate+        // projection's store (`point_act`, so no `Activate` dispatch survives);+        // each gate is a fused conv store plus a `Mul`.         let plan = build(&Shapes::new(TENSORS), Mode::DecodeStep.at(TEST_CONTEXT)).expect("builds");         let count = |want: Kind| {             plan.ops@@ -167,7 +169,7 @@ mod tests {                 .filter(|op| matches!(op, Op::Dispatch { kind, .. } if *kind == want))                 .count()         };-        assert_eq!(count(Kind::Activate), LAYERS * 2, "two gelu gates per layer");+        assert_eq!(count(Kind::Activate), 0, "the gelu folds into the gate store");         assert_eq!(count(Kind::Mul), LAYERS * 2, "two gated products per layer");         // The whole residual is scaled by `skip` after add2, one scalar multiply         // a layer (`_maybe_apply_skip_scale/mul` in the portable graph).@@ -176,13 +178,11 @@ mod tests {         assert_eq!(count(Kind::Softcap), 0, "softcapping moved to the host with the head");         // The live int8 round-trips of the attention path (S10's qint set):         // qi + qo + mm + o on every layer, plus ko + vo where a layer owns-        // its cache - 15 * 6 + 20 * 4. (The `o` grid matches live exactly-        // only at full-scale O tables: the /4-rescaled build flipped codes.)-        assert_eq!(-            count(Kind::Quantize),-            OWNS_CACHE_LAYERS * 6 + (LAYERS - OWNS_CACHE_LAYERS) * 4,-            "one Mm round-trip per layer"-        );+        // its cache - 15 * 6 + 20 * 4. Every one folds into its producer's+        // store (`fuse_quantize`, Phase 1 of the 10-tok/s plan), so no+        // `Quantize` dispatch survives: 1076 ops become 906.+        assert_eq!(count(Kind::Quantize), 0, "every round-trip folds into its producer");+        assert_eq!(plan.ops.len(), 906, "1076 - 170 fused quantizes");     }      #[test]
library/ml/src/main/rust/src/nets/madlad_extra.rs
diff --git a/library/ml/src/main/rust/src/nets/madlad_extra.rs b/library/ml/src/main/rust/src/nets/madlad_extra.rsindex 4dea28e361..d4f5228274 100644--- a/library/ml/src/main/rust/src/nets/madlad_extra.rs+++ b/library/ml/src/main/rust/src/nets/madlad_extra.rs@@ -1,7 +1,7 @@ #[cfg(test)] mod tests {     use super::super::tests::{assert_no_aliasing, Shapes};-    use super::super::{Kind, Op};+    use super::super::{Kind, Op, Plan, Shape};     use super::super::madlad::*;     use super::super::madlad_part1::{relative_bucket, split_of}; 
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 ebab3177c0..aba659f985 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -466,4 +466,5 @@ include!("mod_part9.rs"); include!("mod_part9b.rs"); include!("mod_part10.rs"); include!("mod_part11.rs");-include!("mod_part12.rs");\ No newline at end of file+include!("mod_part12.rs");+include!("mod_part13.rs");\ No newline at end of file
library/ml/src/main/rust/src/nets/mod_part12.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part12.rs b/library/ml/src/main/rust/src/nets/mod_part12.rsindex 16a248d2bc..02305c2619 100644--- a/library/ml/src/main/rust/src/nets/mod_part12.rs+++ b/library/ml/src/main/rust/src/nets/mod_part12.rs@@ -130,4 +130,217 @@         }         bytes[52..56].copy_from_slice(&(data_len as u32).to_le_bytes());         bytes-    }\ No newline at end of file+    }++    /// The fallback flag parses without touching the environment.+    ///+    /// `quant_fold_on` takes the raw setting value so this test pins the+    /// default-on contract with no `set_var`: fusion is the shipping path,+    /// and only an explicit opt-out disables it.+    #[test]+    fn the_quantize_fold_is_on_unless_explicitly_disabled() {+        use crate::nets::quant_fold_on;+        assert!(quant_fold_on(None));+        assert!(quant_fold_on(Some("1".into())));+        assert!(quant_fold_on(Some("yes".into())));+        assert!(!quant_fold_on(Some("0".into())));+        assert!(!quant_fold_on(Some("off".into())));+        assert!(!quant_fold_on(Some("false".into())));+    }++    /// A single-consumer quantize folds into its producing convolution.+    ///+    /// `conv_int8 -> quantize`: one convolution dispatch carrying the scale in+    /// `param0_bits`, and no `Quantize` op. The fused convolution writes the+    /// quantize's own output tensor.+    #[test]+    fn a_single_consumer_quantize_folds_into_the_producing_store() {+        use crate::nets::Kind;+        use crate::nets::tests::Shapes;+        let source = Shapes::new(4);+        let mut builder = Builder::new(&source);+        let x = builder.input(Shape::new(4, 1, 4));+        let projected = builder.conv_int8(x, 0, 4, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 1, Act::None);+        let out = builder.quantize(projected, 0.5);+        // Tensor 3 is the file's spare: `finish` refuses an unread tensor.+        builder.host_tensor(3, &[1]);+        let plan = builder.finish(&[out]).expect("builds");+        assert!(+            plan.ops.iter().all(|op| !matches!(op, Op::Dispatch { kind: Kind::Quantize, .. })),+            "the quantize should have folded: {:?}",+            plan.ops+        );+        let fused = plan+            .ops+            .iter()+            .filter_map(|op| match op {+                Op::Dispatch { push, .. } if push.param0_bits != 0 => Some(push),+                _ => None,+            })+            .collect::<Vec<_>>();+        assert_eq!(fused.len(), 1, "exactly one quant-fused store: {fused:?}");+        assert_eq!(fused[0].out, plan.outputs[0].at);+        assert_eq!(f32::from_bits(fused[0].param0_bits), 0.5);+    }++    /// A quantize whose input has a second reader stays its own dispatch.+    ///+    /// Folding it would leave the other reader with no writer: the producer's+    /// old output tensor is never allocated once the fold moves the rounding.+    #[test]+    fn a_shared_convolution_output_keeps_its_quantize() {+        use crate::nets::Kind;+        use crate::nets::tests::Shapes;+        let source = Shapes::new(5);+        let mut builder = Builder::new(&source);+        let x = builder.input(Shape::new(4, 1, 4));+        let projected = builder.conv_int8(x, 0, 4, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 1, Act::None);+        let rounded = builder.quantize(projected, 0.5);+        // A second reader of the convolution's output: the folded store would orphan it.+        let mixed = builder.mul(rounded, projected);+        builder.host_tensor(3, &[1]);+        builder.host_tensor(4, &[1]);+        let plan = builder.finish(&[mixed]).expect("builds");+        assert_eq!(+            plan.ops.iter().filter(|op| matches!(op, Op::Dispatch { kind: Kind::Quantize, .. })).count(),+            1,+            "the shared quantize must survive: {:?}",+            plan.ops+        );+    }++    /// A quantize held as a plan output stays its own dispatch.+    ///+    /// Nothing downstream reads the producer's output, but the host does — via+    /// the quantize, which folding would remove.+    #[test]+    fn a_quantize_that_is_a_plan_output_keeps_its_dispatch() {+        use crate::nets::Kind;+        use crate::nets::tests::Shapes;+        let source = Shapes::new(5);+        let mut builder = Builder::new(&source);+        let x = builder.input(Shape::new(4, 1, 4));+        let projected = builder.conv_int8(x, 0, 4, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 1, Act::None);+        let rounded = builder.quantize(projected, 0.5);+        builder.host_tensor(3, &[1]);+        builder.host_tensor(4, &[1]);+        let plan = builder.finish(&[projected, rounded]).expect("builds");+        assert_eq!(+            plan.ops.iter().filter(|op| matches!(op, Op::Dispatch { kind: Kind::Quantize, .. })).count(),+            1,+            "the output quantize must survive: {:?}",+            plan.ops+        );+    }++    /// A chained `quantize(quantize(x))` folds only the inner one.+    ///+    /// The outer scale would otherwise be dropped: the producer carries one+    /// `quant_scale`, so the second fold finds it occupied and stops.+    #[test]+    fn a_chained_quantize_folds_once_and_keeps_the_outer() {+        use crate::nets::Kind;+        use crate::nets::tests::Shapes;+        let source = Shapes::new(4);+        let mut builder = Builder::new(&source);+        let x = builder.input(Shape::new(4, 1, 4));+        let projected = builder.conv_int8(x, 0, 4, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 1, Act::None);+        let inner = builder.quantize(projected, 0.5);+        let out = builder.quantize(inner, 0.25);+        builder.host_tensor(3, &[1]);+        let plan = builder.finish(&[out]).expect("builds");+        assert_eq!(+            plan.ops.iter().filter(|op| matches!(op, Op::Dispatch { kind: Kind::Quantize, .. })).count(),+            1,+            "the outer quantize must survive: {:?}",+            plan.ops+        );+    }++    /// A quantize after a norm folds into the norm's store.+    ///+    /// The QI shape: `rms_norm -> quantize`, one dispatch carrying the scale.+    #[test]+    fn a_quantize_after_a_norm_folds_into_the_norm_store() {+        use crate::nets::Kind;+        use crate::nets::tests::Shapes;+        let source = Shapes::new(2);+        let mut builder = Builder::new(&source);+        let x = builder.input(Shape::new(4, 1, 4));+        let normed = builder.rms_norm(x, 0, 1e-6);+        let out = builder.quantize(normed, 0.25);+        builder.host_tensor(1, &[1]);+        let plan = builder.finish(&[out]).expect("builds");+        assert!(+            plan.ops.iter().all(|op| !matches!(op, Op::Dispatch { kind: Kind::Quantize, .. })),+            "the norm-fed quantize should have folded: {:?}",+            plan.ops+        );+        let fused = plan+            .ops+            .iter()+            .filter_map(|op| match op {+                Op::Dispatch { kind: Kind::RmsNorm, push, .. } => Some(push),+                _ => None,+            })+            .collect::<Vec<_>>();+        assert_eq!(fused.len(), 1, "one norm: {fused:?}");+        assert_eq!(f32::from_bits(fused[0].param0_bits), 0.25);+    }++    /// A fused quantize store computes what the unfolded pair computes.+    ///+    /// The reference serves fused pushes from the same arms as unfolded ones,+    /// so this runs a folded `rms_norm -> quantize` plan (one dispatch) over+    /// a real weights file and checks the outputs against hand-computed+    /// norm-then-round-trip values. The fused form rounds once where the+    /// unfolded pair would round twice, so this asserts close agreement+    /// (well inside half an int8 step), not bit-identity. Bit-identity+    /// against live is the parity harness's job.+    #[test]+    fn a_fused_quantize_store_matches_its_unfolded_numbers() {+        use crate::nets::reference;+        // Two tensors: the norm gamma and the file's spare. Built directly —+        // `Offsets` has no public constructor — by parsing a hand-made `.maml`+        // header, which also exercises the real `WeightSource` path.+        let header = maml_header(&[+            (&[4], crate::weights::DTYPE_F16),+            (&[1], crate::weights::DTYPE_F16),+        ]);+        let parsed = crate::weights::Weights::parse(&header, crate::weights::graph::SELFIE)+            .expect("the hand-made header parses");+        let table = parsed.offsets();+        let mut builder = Builder::new(&table);+        let x = builder.input(Shape::new(4, 1, 4));+        let normed = builder.rms_norm(x, 0, 1e-6);+        let out = builder.quantize(normed, 0.25);+        builder.host_tensor(1, &[1]);+        let plan = builder.finish(&[out]).expect("builds");+        // Gamma all ones. Inputs exactly representable in fp16, so the upload+        // round-trips losslessly and the hand computation below is in f64.+        let half = |v: f32| crate::preprocess::f32_to_f16(v).to_le_bytes();+        let mut blob = vec![0u8; 16];+        for e in 0..4 {+            blob[e * 2..e * 2 + 2].copy_from_slice(&half(1.0));+        }+        // Channel-major `[c, 1, w]`: channel c holds `x_values[c] + position`.+        let x_values = [0.5f64, 1.5, -2.0, 3.0];+        let input: Vec<f32> =+            x_values.iter().flat_map(|&c| (0..4).map(move |p| (c + p as f64 * 0.5) as f32)).collect();+        let outputs = reference::run_multi(&plan, &blob, &[&input]).expect("runs");+        assert_eq!(outputs.len(), 1);+        assert_eq!(outputs[0].len(), 16);+        for (c, &base) in x_values.iter().enumerate() {+            for p in 0..4 {+                let column: Vec<f64> =+                    x_values.iter().map(|&cc| cc + p as f64 * 0.5).collect();+                let mean_sq = column.iter().map(|v| v * v).sum::<f64>() / 4.0;+                let normed = (base + p as f64 * 0.5) / (mean_sq + 1e-6).sqrt();+                let q = ((normed / 0.25 + 0.5).floor()).clamp(-128.0, 127.0);+                let want = q * 0.25;+                let got = outputs[0][c * 4 + p] as f64;+                assert!((got - want).abs() < 0.06, "channel {c} position {p}: got {got}, want {want}");+            }+        }+    }+
library/ml/src/main/rust/src/nets/mod_part13.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part13.rs b/library/ml/src/main/rust/src/nets/mod_part13.rsnew file mode 100644index 0000000000..d5c21e7e8c--- /dev/null+++ b/library/ml/src/main/rust/src/nets/mod_part13.rs@@ -0,0 +1,140 @@+/// Fold single-consumer `Quantize` nodes into their producing store.+///+/// A Gemma decode step spends 170 dispatches on int8 round-trips (`quantize.comp`):+/// the attention path runs at live's rounded precision, so every projection output+/// is `clamp(round(x / scale), -128, 127) * scale` before its consumer reads it.+/// Each is elementwise over a tensor that already sits in cache, so the producing+/// convolution, norm or cached apply stores `quantize(value)` directly — via+/// `quant_store` in `common.glsl`, fed by [`Push::param0_bits`] — and the+/// `Quantize` node never becomes a dispatch.+///+/// The fold direction mirrors [`Builder::fuse_elementwise`](super::Builder::fuse_elementwise):+/// the consumer is absorbed into the producer's store, never materialising anything+/// new. And like that fold it runs to fixpoint before liveness, so the arena+/// packing sees the folded graph.+///+/// # What can fold, and what cannot+///+/// The producer must be a `ConvInt8` (which covers the int4, int8 and Q2_K+/// lowerings — all three emit through that node), `RmsNorm` or `AttnApplyCached`+/// node whose output the quantize is the only reader of, counted over node inputs+/// *and* plan outputs. Anything else keeps its `Quantize` as its own op.+///+/// `Node::Conv` (fp16) is deliberately not a producer: no `Quantize` input in+/// Gemma is an fp16 convolution's output, so including it would need quant hooks+/// in shaders with no consumer. A producer that already carries a fused scale+/// (a chained `quantize(quantize(x))`, which no net builds) keeps the outer one+/// rather than dropping a rounding.+///+/// Only `Quantize` folds. A fused multiply would round differently (see the+/// elementwise fold), and a quantize is already the outermost operation of the+/// store it joins: `quantize(activate(acc + bias) + res + shift)`, which is+/// exactly `quantize(add(conv, res))` — the add-fold was already exact, so+/// applying the round-trip to its sum is too.+///+/// # Fallback+///+/// Gated by [`quant_fold_on`]: `MODELRUNNER_QUANT_FOLD=0` (or+/// `debug.modelrunner.quant_fold=0` on Android) restores the discrete+/// `Quantize` dispatches. See [`crate::knobs`].+impl<'a> Builder<'a> {+    /// Fold every foldable `Quantize` into its producer's store.+    fn fuse_quantize(&mut self, outputs: &[Id]) {+        loop {+            if !self.fuse_one_quantize(outputs) {+                return;+            }+        }+    }++    /// One fold, or `false` when no quantize qualifies.+    fn fuse_one_quantize(&mut self, outputs: &[Id]) -> bool {+        let folded = (0..self.nodes.len()).find_map(|i| {+            // The quantize's input, its scale, and its own output, which the+            // rounded value moves onto. All `Copy`, so the borrow ends here.+            let (produced, scale, out) = match &self.nodes[i] {+                Node::Quantize { input, out, scale } => (*input, *scale, *out),+                _ => return None,+            };+            // A self-quantize would fold into a store that reads the tensor it+            // no longer writes. Refused rather than reasoned about: no net+            // builds one.+            if produced == out {+                return None;+            }+            // Elementwise means shape-preserving: a mismatch is a bug elsewhere,+            // and folding it would silently change the tensor the producer writes.+            if self.shape_of(produced) != self.shape_of(out) {+                return None;+            }+            // The producer's index. `None` for anything that is not a+            // quant-fusable store, or one that already carries a scale.+            let index = quant_producer_of(&self.nodes, produced)?;+            // The producer's output must reach exactly this quantize: a second+            // reader, or the plan holding it as an output, keeps the quantize+            // unfolded. Same rule as the elementwise fold.+            let single = self.nodes.iter().enumerate()+                .filter(|(j, _)| *j != index && *j != i)+                .all(|(_, node)| !node.inputs().contains(&produced))+                && !outputs.contains(&produced);+            single.then_some((i, index, scale, out))+        });+        let Some((i, index, scale, out)) = folded else {+            return false;+        };+        // The output tensor moves onto the producer: it stores the rounded value+        // directly, and the producer's old output — now unread by anything — is+        // never allocated.+        match &mut self.nodes[index] {+            Node::ConvInt8 { out: conv_out, quant_scale, .. } => {+                *conv_out = out;+                *quant_scale = Some(scale);+            }+            Node::RmsNorm { out: norm_out, quant_scale, .. } => {+                *norm_out = out;+                *quant_scale = Some(scale);+            }+            Node::AttnApplyCached { out: apply_out, quant_scale, .. } => {+                *apply_out = out;+                *quant_scale = Some(scale);+            }+            // `quant_producer_of` only returns those three, so reaching this+            // means the predicate and the application disagree — a bug, and+            // folding nothing is the safe side of it.+            _ => return false,+        }+        self.nodes.remove(i);+        true+    }+}++/// The node that wrote `id`, if it is one this fold can absorb a quantize into.+///+/// `ConvInt8` covers all three quantised lowerings (int8, int4, Q2_K emit+/// through it); `RmsNorm` covers the QI/QO/KO/VO/O sites whose consumer is a+/// norm; `AttnApplyCached` covers the MM site. A producer that already carries+/// a scale is excluded: folding a second one would drop a rounding.+fn quant_producer_of(nodes: &[Node], id: Id) -> Option<usize> {+    nodes.iter().position(|node| {+        let (out, free) = match node {+            Node::ConvInt8 { out, quant_scale, .. } => (*out, quant_scale.is_none()),+            Node::RmsNorm { out, quant_scale, .. } => (*out, quant_scale.is_none()),+            Node::AttnApplyCached { out, quant_scale, .. } => (*out, quant_scale.is_none()),+            _ => return false,+        };+        free && out == id+    })+}++/// Whether the quantize fold runs, from the `quant_fold` debug setting.+///+/// On by default: fusion is the shipping path, and the flag exists as the+/// per-phase fallback the plan requires, not as an experiment. Only an+/// explicit opt-out (`0`, `off` or `false`) disables it; anything else —+/// including unset — folds.+pub(crate) fn quant_fold_on(value: Option<String>) -> bool {+    match value.as_deref() {+        Some("0") | Some("off") | Some("false") => false,+        _ => true,+    }+}
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 1d99fbeba8..73ab21c5cc 100644--- a/library/ml/src/main/rust/src/nets/mod_part2.rs+++ b/library/ml/src/main/rust/src/nets/mod_part2.rs@@ -249,6 +249,14 @@ pub(crate) enum Node {         groups: u32,         /// A residual addend folded into the store. See [`Push::res`].         res: Option<Id>,+        /// An int8 round-trip scale folded into the store, or `None` for none.+        ///+        /// [`Builder::quantize`]'s consumer is this norm: the store keeps+        /// `quantize(norm(input))` and the `Quantize` node never becomes a+        /// dispatch. The scale rides [`Push::param0_bits`], which no norm+        /// otherwise reads; bits of zero mean unfused. See `quant_store` in+        /// `shaders/common.glsl`.+        quant_scale: Option<f32>,     },     AttnScores {         q: Id,@@ -285,6 +293,12 @@ pub(crate) enum Node {         dynamic: bool,         /// Whether this layer's window applies. See [`Push::sliding`].         sliding: bool,+        /// An int8 round-trip scale folded into the store, or `None` for none.+        ///+        /// As on [`Node::RmsNorm::quant_scale`]: the attention mixture's+        /// `Quantize` folds into this cached apply, which stores+        /// `quantize(mixed)` directly.+        quant_scale: Option<f32>,     },     Softmax {         input: Id,@@ -390,6 +404,12 @@ pub(crate) enum Node {         res: Option<Id>,         /// A per-channel shift folded into the store. See [`Push::shift`].         shift: Option<Id>,+        /// An int8 round-trip scale folded into the store, or `None` for none.+        ///+        /// As on [`Node::RmsNorm::quant_scale`]: a `Quantize` whose input this+        /// convolution produced folds into the store, which keeps+        /// `quantize(activate(acc + bias))` and never dispatches it.+        quant_scale: Option<f32>,     },     AttnApply {         probs: Id,
library/ml/src/main/rust/src/nets/mod_part4.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part4.rs b/library/ml/src/main/rust/src/nets/mod_part4.rsindex 48584b44e2..0e8e0994dc 100644--- a/library/ml/src/main/rust/src/nets/mod_part4.rs+++ b/library/ml/src/main/rust/src/nets/mod_part4.rs@@ -389,6 +389,7 @@ impl<'a> Builder<'a> {             quant,             res: None,             shift: None,+            quant_scale: None,         });         out     }
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 b091b97001..62d205bba0 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, res: None });+        self.nodes.push(Node::RmsNorm { input, out, gamma, epsilon, groups, res: None, quant_scale: None });         out     } 
library/ml/src/main/rust/src/nets/mod_part6.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part6.rs b/library/ml/src/main/rust/src/nets/mod_part6.rsindex e74373983d..3f4a01bf56 100644--- a/library/ml/src/main/rust/src/nets/mod_part6.rs+++ b/library/ml/src/main/rust/src/nets/mod_part6.rs@@ -53,7 +53,7 @@ impl<'a> Builder<'a> {         // that, so taking the width from the cache would silently produce a shorter tensor.         let head_dim = sc.w.checked_div(kv_heads.max(1)).unwrap_or(0);         let out = self.tensor(Shape::new(heads * head_dim, 1, 1));-        self.nodes.push(Node::AttnApplyCached { probs, cache, out, heads, kv_heads, dynamic, sliding });+        self.nodes.push(Node::AttnApplyCached { probs, cache, out, heads, kv_heads, dynamic, sliding, quant_scale: 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 be671e7dc4..e5af59407d 100644--- a/library/ml/src/main/rust/src/nets/mod_part7.rs+++ b/library/ml/src/main/rust/src/nets/mod_part7.rs@@ -228,6 +228,12 @@ impl<'a> Builder<'a> {         }          self.fuse_elementwise(outputs);+        // The quantize fold second: it removes no addends, so it enables no+        // further elementwise fold, and running it after keeps the existing+        // fusion's behaviour first. Gated by the phase fallback flag.+        if quant_fold_on(crate::knobs::get("quant_fold")) {+            self.fuse_quantize(outputs);+        }          let plan = self.emit_all(outputs)?;         Ok(Recorded {
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 59414da450..9fa40f35bb 100644--- a/library/ml/src/main/rust/src/nets/mod_part9.rs+++ b/library/ml/src/main/rust/src/nets/mod_part9.rs@@ -22,6 +22,7 @@ impl<'a> Builder<'a> {                 quant,                 res,                 shift,+                quant_scale,             } => {                 let (si, so) = (shape(*input), shape(*out));                 // The same test `Node::Conv` applies below, less the two cases that cannot arise@@ -109,6 +110,10 @@ impl<'a> Builder<'a> {                         count,                         res: Self::fuse_offset(*res, &at)?,                         shift: Self::fuse_offset(*shift, &at)?,+                        // A folded int8 round-trip scale, or zero for none. `param0_bits`+                        // is free on the quantised convolutions (their dequantisation+                        // scale rides `act_weight`); `quant_store` in the shader reads it.+                        param0_bits: quant_scale.map_or(0, f32::to_bits),                         ..Push::default()                     },                     // One workgroup of 64 per unit for the staged shaders; one invocation per@@ -378,7 +383,7 @@ impl<'a> Builder<'a> {                     invocations: positions,                 });             }-            Node::RmsNorm { input, out, gamma, epsilon, groups, res } => {+            Node::RmsNorm { input, out, gamma, epsilon, groups, res, quant_scale } => {                 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);@@ -402,6 +407,7 @@ impl<'a> Builder<'a> {                         out_h: so.h,                         out_w: so.w,                         group: *groups,+                        param0_bits: quant_scale.map_or(0, f32::to_bits),                         param1_bits: epsilon.to_bits(),                         count: positions,                         res: res_at,
library/ml/src/main/rust/src/nets/mod_part9b.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part9b.rs b/library/ml/src/main/rust/src/nets/mod_part9b.rsindex e4077e62dc..eeea9e1012 100644--- a/library/ml/src/main/rust/src/nets/mod_part9b.rs+++ b/library/ml/src/main/rust/src/nets/mod_part9b.rs@@ -7,7 +7,7 @@ impl<'a> Builder<'a> {         ops: &mut Vec<Op>,     ) -> Result<(), String> {         match node {-            Node::AttnApplyCached { probs, cache, out, heads, kv_heads, dynamic, sliding } => {+            Node::AttnApplyCached { probs, cache, out, heads, kv_heads, dynamic, sliding, quant_scale } => {                 let (sc, so) = (shape(*cache), shape(*out));                 ops.push(Op::Dispatch {                     kind: Kind::AttnApplyCached,@@ -30,6 +30,10 @@ impl<'a> Builder<'a> {                         dyn_keys: u32::from(*dynamic),                         kv_heads: *kv_heads,                         sliding: u32::from(*sliding),+                        // A folded int8 round-trip scale, or zero for none. Free on+                        // this kind (it carries no other scalar); `quant_store`+                        // in the shader reads it.+                        param0_bits: quant_scale.map_or(0, f32::to_bits),                         ..Push::default()                     },                     invocations: so.len(),
library/ml/src/main/rust/src/nets/nllb_extra.rs
diff --git a/library/ml/src/main/rust/src/nets/nllb_extra.rs b/library/ml/src/main/rust/src/nets/nllb_extra.rsindex a150f6cc9d..d0e5c1a9e7 100644--- a/library/ml/src/main/rust/src/nets/nllb_extra.rs+++ b/library/ml/src/main/rust/src/nets/nllb_extra.rs@@ -1,7 +1,7 @@ #[cfg(test)] mod tests {     use super::super::tests::{assert_no_aliasing, Shapes};-    use super::super::{Kind, Op};+    use super::super::{Kind, Op, Plan, Shape};     use super::super::nllb::*;      /// A short sentence: a language token, six pieces and `</s>`.
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 5847046cde..a4fb828239 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -163,11 +163,9 @@ pub struct Reference {     window_start: u32, } -impl Reference { include!("reference_part1.rs"); include!("reference_part2.rs"); include!("reference_part3.rs");-} include!("reference_part4.rs"); #[cfg(test)] mod tests {
library/ml/src/main/rust/src/nets/reference_part1.rs
diff --git a/library/ml/src/main/rust/src/nets/reference_part1.rs b/library/ml/src/main/rust/src/nets/reference_part1.rsindex ccbc3e6c81..9fa8d56a24 100644--- a/library/ml/src/main/rust/src/nets/reference_part1.rs+++ b/library/ml/src/main/rust/src/nets/reference_part1.rs@@ -1,3 +1,4 @@+impl Reference {     fn new(plan: &Plan, weights: &[u8], inputs: &[&[f32]]) -> Result<Reference, String> {         if inputs.len() != plan.inputs.len() {             return Err(format!(@@ -189,7 +190,7 @@                     let index = nchw(p, oc, oy, ox);                     let folded =                         activate(acc, p.act, slope) + self.fused_res(p, index)? + shift;-                    self.store(p.out, index, folded)?;+                    self.store(p.out, index, self.fused_quant(p, folded)?)?;                 }             }         }@@ -239,7 +240,7 @@                     // PRelu is refused at build time for int8, so the slope is never read.                     let folded =                         activate(biased, p.act, 0.0) + self.fused_res(p, index)? + shift;-                    self.store(p.out, index, folded)?;+                    self.store(p.out, index, self.fused_quant(p, folded)?)?;                 }             }         }@@ -271,7 +272,7 @@                 let index = oc * positions + position;                 let folded =                     activate(biased, p.act, 0.0) + self.fused_res(p, index)? + shift;-                self.store(p.out, index, folded)?;+                self.store(p.out, index, self.fused_quant(p, folded)?)?;             }         }         Ok(())@@ -314,14 +315,14 @@                     let q = f32::from((qb >> (lane * 2)) & 3);                     let dm = self.weight(p.act_weight, (oc * blocks + block) * 2)?;                     let dn = self.weight(p.act_weight, (oc * blocks + block) * 2 + 1)?;-                    acc += self.load(p.in0, k * positions + position)?+                acc += self.load(p.in0, k * positions + position)?                         * (dm * dm * q * lo - dn * dm * hi);                 }                 let biased = acc + self.weight(p.bias, oc)?;                 let index = oc * positions + position;                 let folded =                     activate(biased, p.act, 0.0) + self.fused_res(p, index)? + shift;-                self.store(p.out, index, folded)?;+                self.store(p.out, index, self.fused_quant(p, folded)?)?;             }         }         Ok(())@@ -426,7 +427,7 @@                                 }                             }                         }-                        self.store(p.out, nchw(p, oc, oy, ox), activate(acc, p.act, slope))?;+                        self.store(p.out, nchw(p, oc, oy, ox), self.fused_quant(p, activate(acc, p.act, slope))?)?;                     }                 }             }@@ -460,7 +461,7 @@                     let index = nchw(p, oc, oy, ox);                     let folded =                         activate(acc, p.act, slope) + self.fused_res(p, index)? + shift;-                    self.store(p.out, index, folded)?;+                    self.store(p.out, index, self.fused_quant(p, folded)?)?;                 }             }         }@@ -495,4 +496,5 @@             }         }         Ok(())-    }\ No newline at end of file+    }+}
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 da51ef221c..dc1d135971 100644--- a/library/ml/src/main/rust/src/nets/reference_part2.rs+++ b/library/ml/src/main/rust/src/nets/reference_part2.rs@@ -1,3 +1,4 @@+impl Reference {      /// Average pooling over an explicit window, floored and unpadded.     ///@@ -119,7 +120,7 @@                 let index = channel * positions + position;                 let folded =                     activate(total + bias, p.act, 0.0) + self.fused_res(p, index)? + shift;-                self.store(p.out, index, folded)?;+                self.store(p.out, index, self.fused_quant(p, folded)?)?;             }         }         Ok(())@@ -307,7 +308,10 @@                 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)?;-                let normed = value * inverse * gamma;+                // A folded int8 round-trip applies to the norm output itself,+                // before the residual below — mirroring `quant_store` in+                // `rmsnorm.comp`, which rounds before adding `p.res`.+                let normed = self.fused_quant(p, 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.@@ -357,6 +361,25 @@         }     } +    /// A folded int8 round-trip scale applied to the stored value, or the value+    /// unchanged when the op stores unfolded.+    ///+    /// Mirrors `quant_store` in `shaders/common.glsl`: the outermost store+    /// operation, after the activation and the folded addends. `param0_bits`+    /// of zero is the unfused default every push carries unless the+    /// quantize fold set a scale. Same arithmetic as [`Self::quantize`].+    fn fused_quant(&self, p: &Push, value: f32) -> Result<f32, String> {+        if p.param0_bits == 0 {+            return Ok(value);+        }+        let scale = f32::from_bits(p.param0_bits);+        if !(scale > 0.0) {+            return Err(format!("a fused quantize of {scale}"));+        }+        let q = ((value / scale + 0.5).floor()).clamp(-128.0, 127.0);+        Ok(q * scale)+    }+     /// `S[h][i][j] = scale * sum_d Q[h][d][i] * K[h][d][j]`.     ///     /// Q and K are `[d_model, 1, T]`; the output is `[heads, T, T]`. A head is a run of@@ -468,4 +491,5 @@             }         }         Ok(())-    }\ No newline at end of file+    }+}
library/ml/src/main/rust/src/nets/reference_part3.rs
diff --git a/library/ml/src/main/rust/src/nets/reference_part3.rs b/library/ml/src/main/rust/src/nets/reference_part3.rsindex 0812297e12..b672ebd4b9 100644--- a/library/ml/src/main/rust/src/nets/reference_part3.rs+++ b/library/ml/src/main/rust/src/nets/reference_part3.rs@@ -1,3 +1,4 @@+impl Reference {      /// Keys an op attends over, as an inclusive `[first, last]` range.     ///@@ -207,7 +208,7 @@                 total += self.load(p.in0, row + key)?                     * self.load(p.in1, value + key * vstride)?;             }-            self.store(p.out, nchw(p, channel, 0, 0), total)?;+            self.store(p.out, nchw(p, channel, 0, 0), self.fused_quant(p, total)?)?;         }         Ok(())     }@@ -372,4 +373,5 @@             }         }         Ok(())-    }\ No newline at end of file+    }+}
library/ml/src/main/rust/src/weights_part7.rs
diff --git a/library/ml/src/main/rust/src/weights_part7.rs b/library/ml/src/main/rust/src/weights_part7.rsindex 5c764145db..f2d187a3fc 100644--- a/library/ml/src/main/rust/src/weights_part7.rs+++ b/library/ml/src/main/rust/src/weights_part7.rs@@ -184,12 +184,18 @@ impl Graph {                     quant,                     res,                     shift,+                    quant_scale,                 } => {                     if res.is_some() || shift.is_some() {                         return Err(format!(                             "emitter: node {i} carries a fused addend; emit before fusion"                         ));                     }+                    if quant_scale.is_some() {+                        return Err(format!(+                            "emitter: node {i} carries a fused quantize; emit before fusion"+                        ));+                    }                     if matches!(act, Act::PRelu(_)) {                         return Err(format!("emitter: node {i} is a PReLU"));                     }