Modern Apps git

← Modern-Apps.git

ml: pad gemma4 vision tower to 8 positions, tower 1500 -> 677 ms on Pixel

Commit
7b00abd80ee431db12cafcaf36bfb21f385e6a13
Author
vayun-mathur <[email protected]>
When
2026-10-26 05:50 UTC (1 month ago)
Parents
6a15f61

Diff

library/ml/src/main/rust/shaders/softmax.comp
diff --git a/library/ml/src/main/rust/shaders/softmax.comp b/library/ml/src/main/rust/shaders/softmax.compindex 24d8073a93..3da3626366 100644--- a/library/ml/src/main/rust/shaders/softmax.comp+++ b/library/ml/src/main/rust/shaders/softmax.comp@@ -37,6 +37,12 @@ //! //! With `p.kw == 1` one workgroup owns one row and its lanes split the keys, for the few //! long rows a decode step has (whisper's cross-attention is 1,500 keys). See `reduce.glsl`.+//!+//! # Key bound+//!+//! A non-zero `p.kh` normalises only the leading `p.kh` keys of each row and stores zeros past+//! them, for a sequence padded to a multiple of eight positions (Gemma 4's vision tower): the+//! padded keys then add exact zeros in `attn_apply`.  #extension GL_KHR_shader_subgroup_basic : require #extension GL_KHR_shader_subgroup_arithmetic : require@@ -51,19 +57,20 @@ void row_mode() {     uint lane = gl_LocalInvocationID.x;     uint lanes = gl_WorkGroupSize.x;     uint at = p.in0 + row * p.out_w;+    uint keys = p.kh == 0u ? p.out_w : p.kh;     float peak = -65504.0;-    for (uint i = lane; i < p.out_w; i += lanes) {+    for (uint i = lane; i < keys; i += lanes) {         peak = max(peak, float(arena[at + i]));     }     peak = workgroup_max(peak);     float total = 0.0;-    for (uint i = lane; i < p.out_w; i += lanes) {+    for (uint i = lane; i < keys; i += lanes) {         total += exp(float(arena[at + i]) - peak);     }     float inverse = 1.0 / workgroup_sum(total);     uint out_row = p.out_at + row * p.out_w;     for (uint i = lane; i < p.out_w; i += lanes) {-        arena[out_row + i] = float16_t(exp(float(arena[at + i]) - peak) * inverse);+        arena[out_row + i] = i < keys ? float16_t(exp(float(arena[at + i]) - peak) * inverse) : float16_t(0.0);     } } @@ -77,22 +84,26 @@ void main() {         return;     }     uint at = p.in0 + row * p.out_w;+    uint keys = p.kh == 0u ? p.out_w : p.kh;      // The most negative fp16 rather than -inf, matching `maxpool.comp`: every row here     // is non-empty, so the seed is never the answer.     float peak = -65504.0;-    for (uint i = 0u; i < p.out_w; i++) {+    for (uint i = 0u; i < keys; i++) {         peak = max(peak, float(arena[at + i]));     }      float total = 0.0;-    for (uint i = 0u; i < p.out_w; i++) {+    for (uint i = 0u; i < keys; i++) {         total += exp(float(arena[at + i]) - peak);     }     float inverse = 1.0 / total;      uint out_row = p.out_at + row * p.out_w;-    for (uint i = 0u; i < p.out_w; i++) {+    for (uint i = 0u; i < keys; i++) {         arena[out_row + i] = float16_t(exp(float(arena[at + i]) - peak) * inverse);     }+    for (uint i = keys; i < p.out_w; i++) {+        arena[out_row + i] = float16_t(0.0);+    } }
library/ml/src/main/rust/src/nets/gemma4_vision_part1.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_vision_part1.rs b/library/ml/src/main/rust/src/nets/gemma4_vision_part1.rsindex 32fc4404e6..b1bedc969d 100644--- a/library/ml/src/main/rust/src/nets/gemma4_vision_part1.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_vision_part1.rs@@ -1,4 +1,5 @@-/// Plan inputs, in declaration order. `T` is [`Grid::patches`].+/// Plan inputs, in declaration order. `T` is [`padded_positions`] of [`Grid::patches`]; the+/// padded columns are zeros. /// /// | | shape | | /// | :--- | :--- | :--- |@@ -13,6 +14,14 @@ /// All three are built by [`prepare`]. pub const INPUTS: usize = 3; +/// The sequence length the layers run at: the patches rounded up to a multiple of eight, so the+/// int4 GEMMs take their 16-byte load path (`wide_oct` in conv_point_int4.comp). Every op but+/// attention is per position; the padded keys are masked out of each softmax and the padded+/// positions cropped off before the pooling.+pub const fn padded_positions(patches: u32) -> u32 {+    patches.next_multiple_of(8)+}+ /// Build the image pass. pub fn build(weights: &dyn WeightSource, mode: Mode) -> Result<Plan, String> {     let grid = mode.grid();@@ -24,12 +33,13 @@ pub fn build(weights: &dyn WeightSource, mode: Mode) -> Result<Plan, String> {         }     };     let patches = Grid::new(grid.rows, grid.cols)?.patches();+    let padded = padded_positions(patches);     let mut builder = Builder::new(weights);     let b = &mut builder; -    let values = b.input(Shape::new(D_MODEL, 1, patches));-    let positions = b.input(Shape::new(D_MODEL, 1, patches));-    let angles = b.input(Shape::new(HEAD_DIM, 1, patches));+    let values = b.input(Shape::new(D_MODEL, 1, padded));+    let positions = b.input(Shape::new(D_MODEL, 1, padded));+    let angles = b.input(Shape::new(HEAD_DIM, 1, padded));      // The two position tables are gathered on the host and arrive summed, as `positions`.     for at in [COLUMN_POSITIONS, ROW_POSITIONS] {@@ -44,7 +54,10 @@ pub fn build(weights: &dyn WeightSource, mode: Mode) -> Result<Plan, String> {     let mut x = b.add(projected, positions);      for index in 0..stop_after {-        x = layer(b, index, x, angles)?;+        x = layer(b, index, x, angles, patches)?;+    }+    if padded != patches {+        x = b.crop_positions(x, patches);     }      if let Mode::Trace { .. } = mode {@@ -148,7 +161,7 @@ fn dense_point(b: &mut Builder, at: usize, x: Id, out: u32) -> Id { }  /// One encoder layer.-fn layer(b: &mut Builder, index: usize, x: Id, angles: Id) -> Result<Id, String> {+fn layer(b: &mut Builder, index: usize, x: Id, angles: Id, keys: u32) -> Result<Id, String> {     let at = layer_at(index);     let mut next = at;     let plain = |n: &mut usize| {@@ -215,7 +228,7 @@ fn layer(b: &mut Builder, index: usize, x: Id, angles: Id) -> Result<Id, String>     // No scale: the export goes straight from the rotary into the score matmul, and the     // uniform q_norm and k_norm gammas carry it instead. See `SCALE_IS_IN_THE_NORMS`.     let scores = b.attn_scores_prescaled(q, k, HEADS);-    let probs = b.softmax(scores);+    let probs = b.softmax_keys(scores, keys);     let mixed = b.attn_apply(probs, v, HEADS);     let mixed = b.clamp(mixed, clip_mixed);     let attended = point(b, o_proj, mixed, D_MODEL);@@ -343,5 +356,12 @@ pub fn prepare(             }         }     }-    Ok([values, positions, rotary_angles(grid)])+    let padded = padded_positions(grid.patches()) as usize;+    let pad = |values: Vec<f32>| -> Vec<f32> {+        if padded == patches {+            return values;+        }+        values.chunks(patches).flat_map(|row| row.iter().copied().chain(std::iter::repeat_n(0.0, padded - patches))).collect()+    };+    Ok([pad(values), pad(positions), pad(rotary_angles(grid))]) }
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 53022ea0b5..f60e057ef7 100644--- a/library/ml/src/main/rust/src/nets/mod_part6.rs+++ b/library/ml/src/main/rust/src/nets/mod_part6.rs@@ -290,6 +290,31 @@ impl<'a> Builder<'a> {         out     } +    /// [`Builder::softmax`] over only the leading `keys` entries of each row, storing zeros past+    /// them: keys padded onto a sequence then contribute nothing to `attn_apply`.+    pub fn softmax_keys(&mut self, input: Id, keys: u32) -> Id {+        let shape = self.shape_of(input);+        if keys == 0 || keys > shape.w {+            self.fail(format!("a softmax over {keys} keys of {shape:?}"));+        }+        let out = self.tensor(shape);+        let window = if keys == shape.w { 0 } else { keys };+        self.nodes.push(Node::Softmax { input, out, mode: SoftmaxMode::Full, sliding: false, window });+        out+    }++    /// The leading `count` positions of a `[C, H, W]` tensor, as a 1x1 average pool (one+    /// dispatch, exact) rather than `C * H` copies.+    pub fn crop_positions(&mut self, input: Id, count: u32) -> Id {+        let shape = self.shape_of(input);+        if count == 0 || count > shape.w {+            self.fail(format!("the first {count} positions of {shape:?}"));+        }+        let out = self.tensor(Shape::new(shape.c, shape.h, count));+        self.nodes.push(Node::AvgPool { input, out, kernel: (1, 1), stride: (1, 1) });+        out+    }+     /// [`Builder::softmax`] with each query's row truncated at the diagonal.     ///     /// The input must be a square score map `[heads, T, T]`: a causal mask is a statement about
library/ml/src/main/rust/src/nets/reference_part13.rs
diff --git a/library/ml/src/main/rust/src/nets/reference_part13.rs b/library/ml/src/main/rust/src/nets/reference_part13.rsindex 616e034ad2..071eefa878 100644--- a/library/ml/src/main/rust/src/nets/reference_part13.rs+++ b/library/ml/src/main/rust/src/nets/reference_part13.rs@@ -73,6 +73,7 @@ impl Reference {                     }                     continue;                 }+                SoftmaxMode::Full if p.kh != 0 => p.kh.min(p.out_w),                 SoftmaxMode::Full => p.out_w,             };             // A sliding layer's causal row also drops everything more than `p.kh - 1` behind@@ -100,13 +101,11 @@ impl Reference {                 let value = (self.load(p.in0, at + i)? - peak).exp() * inverse;                 self.store(p.out, at + i, value)?;             }-            if mode == SoftmaxMode::Causal {-                // Written rather than left alone: `attn_apply` multiplies the whole row, and the-                // arena is reused, so a stale masked value would contribute something-                // unpredictable.-                for i in keys..p.out_w {-                    self.store(p.out, at + i, 0.0)?;-                }+            // Written rather than left alone (causal and key-bounded rows): `attn_apply`+            // multiplies the whole row, and the arena is reused, so a stale masked value would+            // contribute something unpredictable.+            for i in keys..p.out_w {+                self.store(p.out, at + i, 0.0)?;             }         }         Ok(())
library/ml/src/main/rust/src/vulkan/parity_part12.rs
diff --git a/library/ml/src/main/rust/src/vulkan/parity_part12.rs b/library/ml/src/main/rust/src/vulkan/parity_part12.rsindex bc2cfe8b0c..84edba3f60 100644--- a/library/ml/src/main/rust/src/vulkan/parity_part12.rs+++ b/library/ml/src/main/rust/src/vulkan/parity_part12.rs@@ -31,3 +31,21 @@ fn ragged_tiled_attention_agrees_with_the_reference() {         compare(&format!("ragged apply {heads}/{kv_heads} heads {queries}x{keys}"), plan, source.into_data(), &[&probs, &v]);     } }+#[test]+#[ignore = "needs a Vulkan device"]+fn key_bounded_softmax_and_crop_agree_with_the_reference() {+    // The vision tower's padding: rows over a padded key count normalise only the real keys+    // (per-row and row-mode shaders), and the padded positions are cropped off.+    for (heads, queries, width, keys) in [(3u32, 40u32, 40u32, 37u32), (2, 2, 1504, 1497), (2, 8, 600, 600)] {+        let scores = spread((heads * queries * width) as usize, 0.41);+        let source = Invented::new(0);+        let plan = build(&source, &[Shape::new(heads, queries, width)], |b, ids| {+            let probs = b.softmax_keys(ids[0], keys);+            b.crop_positions(probs, keys)+        });+        compare(&format!("softmax over {keys} of {width} keys, cropped"), plan, source.into_data(), &[&scores]);+        let source = Invented::new(0);+        let plan = build(&source, &[Shape::new(heads, queries, width)], |b, ids| b.softmax_keys(ids[0], keys));+        compare(&format!("softmax over {keys} of {width} keys, zero tail"), plan, source.into_data(), &[&scores]);+    }+}