ml: tiled attention for long ragged maps, gemma4 vision tower 2147 -> 1520 ms
- Commit
d792df9b8aed50c526d1a0904c92e7dd50eb289d- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-26 05:02 UTC (1 month ago)
- Parents
23c9ff3
Diff
library/ml/src/main/rust/examples/check_gemma4_audio_parity.rs
diff --git a/library/ml/src/main/rust/examples/check_gemma4_audio_parity.rs b/library/ml/src/main/rust/examples/check_gemma4_audio_parity.rsindex 6b76d3c121..fe918df22f 100644--- a/library/ml/src/main/rust/examples/check_gemma4_audio_parity.rs+++ b/library/ml/src/main/rust/examples/check_gemma4_audio_parity.rs@@ -43,6 +43,8 @@ use modelrunner::logmel::{self, LogMel}; use modelrunner::nets::gemma4_audio as audio; use modelrunner::vulkan::context; use modelrunner::vulkan::reshape::Reshaped;+#[path = "common/gemma4_tower_time.rs"]+mod tower_time; use modelrunner::weights::{graph, Weights}; /// The bar every probe must clear against the int4 control.@@ -179,12 +181,30 @@ fn against(got: &[f32], clip: &str, label: &str, golden: &str) -> (String, f64, } } +/// `--time N`: the clip pass at `seconds` of synthetic audio, built once and run `N` times.+fn time_clip(context: &Arc<context::Context>, weights: &Weights, seconds: f64, repeats: usize) -> Result<(), String> {+ let real = ((seconds * 16_000.0) as usize).min(audio::MAX_SAMPLES);+ let (mel, frames) = mel_for(real)?;+ let input = audio::prepare(&mel, frames)?;+ let mode = audio::Mode::Clip { frames };+ println!();+ println!("=== {seconds} s: {frames} frames, T {}", audio::tokens(frames));+ let tick = std::time::Instant::now();+ let mut net = Reshaped::new(Arc::clone(context), weights, mode, |offsets, mode| audio::build(offsets, mode))?;+ println!("clip net built in {:.0} ms", tick.elapsed().as_secs_f64() * 1000.0);+ tower_time::time_runs(&mut net, mode, &[&input], repeats)+}+ fn main() { let mut args = std::env::args().skip(1); let (Some(model), Some(path)) = (args.next().map(PathBuf::from), args.next()) else {- println!("usage: check_gemma4_audio_parity <gemma4_audio.maml> <audio_golden.json>");+ println!("usage: check_gemma4_audio_parity <gemma4_audio.maml> <audio_golden.json> [--time N]"); return; };+ let repeats = match (args.next().as_deref(), args.next()) {+ (Some("--time"), n) => Some(n.and_then(|n| n.parse().ok()).unwrap_or(3)),+ _ => None,+ }; let bytes = match std::fs::read(&model) { Ok(bytes) => bytes, Err(why) => return println!("cannot read {}: {why}", model.display()),@@ -204,6 +224,14 @@ fn main() { Ok(context) => context, Err(why) => return println!("no Vulkan device: {why}"), };+ if let Some(repeats) = repeats {+ for seconds in [5.0, 30.0] {+ if let Err(why) = time_clip(&context, &weights, seconds, repeats) {+ println!("timing {seconds} s failed: {why}");+ }+ }+ return;+ } let mut worst = (1.0_f64, String::new()); let mut any_control = false;
library/ml/src/main/rust/examples/check_gemma4_vision_parity.rs
diff --git a/library/ml/src/main/rust/examples/check_gemma4_vision_parity.rs b/library/ml/src/main/rust/examples/check_gemma4_vision_parity.rsindex 9cb476f219..74c17092bc 100644--- a/library/ml/src/main/rust/examples/check_gemma4_vision_parity.rs+++ b/library/ml/src/main/rust/examples/check_gemma4_vision_parity.rs@@ -36,6 +36,8 @@ use std::sync::Arc; use modelrunner::nets::gemma4_vision as vision; use modelrunner::vulkan::context; use modelrunner::vulkan::reshape::Reshaped;+#[path = "common/gemma4_tower_time.rs"]+mod tower_time; use modelrunner::weights::{graph, Weights}; /// A reproducible byte for pixel `(y, x)`, channel `(0, 1, 2)` = `(r, g, b)`.@@ -74,9 +76,13 @@ fn synthetic_image(grid: vision::Grid) -> Vec<i32> { fn main() { let mut args = std::env::args().skip(1); let (Some(model), Some(golden)) = (args.next().map(PathBuf::from), args.next()) else {- println!("usage: check_gemma4_vision_parity <vision.maml> <vision_golden.json>");+ println!("usage: check_gemma4_vision_parity <vision.maml> <vision_golden.json> [--time N]"); return; };+ let repeats = match (args.next().as_deref(), args.next()) {+ (Some("--time"), n) => Some(n.and_then(|n| n.parse().ok()).unwrap_or(3)),+ _ => None,+ }; let bytes = match std::fs::read(&model) { Ok(bytes) => bytes, Err(why) => return println!("cannot read {}: {why}", model.display()),@@ -119,6 +125,20 @@ fn main() { Ok(inputs) => inputs, Err(why) => return println!("the host preprocessing failed: {why}"), };+ if let Some(repeats) = repeats {+ let mode = vision::Mode::Image(grid);+ let tick = std::time::Instant::now();+ let built = Reshaped::new(Arc::clone(&context), &weights, mode, |offsets, mode| vision::build(offsets, mode));+ let mut net = match built {+ Ok(net) => net,+ Err(why) => return println!("the image net does not build: {why}"),+ };+ println!("image net built in {:.0} ms", tick.elapsed().as_secs_f64() * 1000.0);+ if let Err(why) = tower_time::time_runs(&mut net, mode, &[&inputs[0], &inputs[1], &inputs[2]], repeats) {+ println!("timing failed: {why}");+ }+ return;+ } // Bisect first: a whole-tower disagreement is much easier to read once the layers below it // have been placed.
library/ml/src/main/rust/examples/common/gemma4_tower_time.rs
diff --git a/library/ml/src/main/rust/examples/common/gemma4_tower_time.rs b/library/ml/src/main/rust/examples/common/gemma4_tower_time.rsnew file mode 100644index 0000000000..f03aa529a5--- /dev/null+++ b/library/ml/src/main/rust/examples/common/gemma4_tower_time.rs@@ -0,0 +1,61 @@+//! Shared by the Gemma 4 tower parity examples: `--time N` builds the net once, runs it `N`+//! times and prints wall time per run plus, with `MODELRUNNER_TIMESTAMPS=1`, a per-kind table.++use modelrunner::vulkan::reshape::Reshaped;+use std::time::Instant;++/// Build-free timing of an already-built net: one warm-up run, then `repeats` timed ones.+pub fn time_runs<S: Copy + PartialEq>(+ net: &mut Reshaped<S>,+ mode: S,+ inputs: &[&[f32]],+ repeats: usize,+) -> Result<(), String> {+ let mut walls = Vec::with_capacity(repeats);+ for pass in 0..=repeats {+ let tick = Instant::now();+ net.at(mode)?.infer_raw_many(inputs)?;+ let ms = tick.elapsed().as_secs_f64() * 1000.0;+ println!("run {pass}: {ms:.1} ms{}", if pass == 0 { " (first)" } else { "" });+ if pass > 0 {+ walls.push(ms);+ }+ }+ walls.sort_by(f64::total_cmp);+ if let Some(median) = walls.get(walls.len() / 2) {+ println!("median of {} warm runs: {median:.1} ms", walls.len());+ }+ if modelrunner::knobs::is_set("timestamps") {+ print_kinds(&net.at(mode)?.op_times()?);+ }+ Ok(())+}++/// Per-kind GPU table for one submit, plus its ten hottest dispatches.+fn print_kinds(report: &[(String, f64, f64)]) {+ let mut per_kind: Vec<(String, usize, f64)> = Vec::new();+ let (mut total, mut gaps) = (0.0, 0.0);+ for (label, us, gap) in report {+ total += us;+ gaps += gap;+ let kind = label.split(':').nth(1).unwrap_or("?").trim().to_string();+ match per_kind.iter_mut().find(|(k, _, _)| *k == kind) {+ Some((_, n, t)) => {+ *n += 1;+ *t += us;+ }+ None => per_kind.push((kind, 1, *us)),+ }+ }+ per_kind.sort_by(|a, b| b.2.total_cmp(&a.2));+ println!("{} dispatches, {:.1} ms timestamped, {:.1} ms gaps", report.len(), total / 1000.0, gaps / 1000.0);+ println!("{:>6} {:>10} {:>10} kind", "count", "total-ms", "mean-us");+ for (kind, n, us) in &per_kind {+ println!("{n:>6} {:>10.1} {:>10.1} {kind}", us / 1000.0, us / *n as f64);+ }+ let mut hottest: Vec<&(String, f64, f64)> = report.iter().collect();+ hottest.sort_by(|a, b| b.1.total_cmp(&a.1));+ for (label, us, _) in hottest.into_iter().take(10) {+ println!(" {us:>9.1} us {label}");+ }+}
library/ml/src/main/rust/shaders/attn_apply.comp
diff --git a/library/ml/src/main/rust/shaders/attn_apply.comp b/library/ml/src/main/rust/shaders/attn_apply.compindex cdb2c13af0..126cd7be5c 100644--- a/library/ml/src/main/rust/shaders/attn_apply.comp+++ b/library/ml/src/main/rust/shaders/attn_apply.comp@@ -47,6 +47,33 @@ layout(std430, binding = 0) readonly buffer ArenaQuad { #define TILE 32u #define BLOCK 4u +/// The tiled mode for key counts or bases that are not multiples of four (`p.kw == 2`): the same+/// four channels by four queries per invocation through scalar loads. Edge channels and queries+/// are clamped on load and dropped on store.+void ragged(uint channel_base, uint query_base, uint queries, uint keys, uint head_dim) {+ uint head = channel_base / head_dim;+ uvec4 v_row;+ uvec4 s_row;+ for (uint i = 0u; i < BLOCK; i++) {+ uint channel = min(channel_base + i, p.out_c - 1u);+ v_row[i] = p.in1 + (kv_head_of(head) * head_dim + channel % head_dim) * keys;+ uint query = min(query_base + i, queries - 1u);+ s_row[i] = p.in0 + (head * queries + query) * keys;+ }+ mat4 acc = mat4(0.0);+ for (uint j = 0u; j < keys; j++) {+ vec4 v = vec4(float(arena[v_row.x + j]), float(arena[v_row.y + j]), float(arena[v_row.z + j]), float(arena[v_row.w + j]));+ vec4 s = vec4(float(arena[s_row.x + j]), float(arena[s_row.y + j]), float(arena[s_row.z + j]), float(arena[s_row.w + j]));+ // Column `q` of `acc` is query `q`: `acc[q][c] += v[c] * s[q]`.+ acc += outerProduct(v, s);+ }+ for (uint i = 0u; i < BLOCK && channel_base + i < p.out_c; i++) {+ for (uint j = 0u; j < BLOCK && query_base + j < queries; j++) {+ arena[p.out_at + (channel_base + i) * queries + query_base + j] = float16_t(acc[j][i]);+ }+ }+}+ void tiled() { uint tile = gl_WorkGroupID.y * gl_NumWorkGroups.x + gl_WorkGroupID.x; if (tile >= p.count) {@@ -62,6 +89,10 @@ void tiled() { if (channel_base >= p.out_c || query_base >= queries) { return; }+ if (p.kw == 2u) {+ ragged(channel_base, query_base, queries, keys, head_dim);+ return;+ } // `head_dim` is a multiple of four, so a block of four channels never spans two heads. uint head = channel_base / head_dim; uint quads = keys >> 2u;@@ -108,7 +139,7 @@ void tiled() { } void main() {- if (p.kw == 1u) {+ if (p.kw != 0u) { tiled(); return; }
library/ml/src/main/rust/shaders/attn_scores.comp
diff --git a/library/ml/src/main/rust/shaders/attn_scores.comp b/library/ml/src/main/rust/shaders/attn_scores.compindex 470d847afe..3f265f42d7 100644--- a/library/ml/src/main/rust/shaders/attn_scores.comp+++ b/library/ml/src/main/rust/shaders/attn_scores.comp@@ -58,6 +58,32 @@ layout(std430, binding = 0) readonly buffer ArenaQuad { #define TILE 32u +/// The tiled mode for lengths or bases that are not multiples of four (`p.kw == 2`): the same+/// 4 x 4 block per invocation through scalar loads, edge queries and keys clamped on load and+/// dropped on store. The per-element shader re-read a whole `head_dim` column pair per score;+/// with the apply's, a Gemma vision tower (594 patches) spent 1.05 s of an image there on a Pixel 8.+void ragged(uint queries, uint keys, uint head_dim, uint head, uint query_base, uint key_base) {+ uint q_at = p.in0 + head * head_dim * queries;+ uint k_at = p.in1 + kv_head_of(head) * head_dim * keys;+ uvec4 qi = min(uvec4(query_base) + uvec4(0u, 1u, 2u, 3u), uvec4(queries - 1u));+ uvec4 kj = min(uvec4(key_base) + uvec4(0u, 1u, 2u, 3u), uvec4(keys - 1u));+ mat4 acc = mat4(0.0);+ for (uint d = 0u; d < head_dim; d++) {+ uint qd = q_at + d * queries;+ uint kd = k_at + d * keys;+ vec4 q = vec4(float(arena[qd + qi.x]), float(arena[qd + qi.y]), float(arena[qd + qi.z]), float(arena[qd + qi.w]));+ vec4 k = vec4(float(arena[kd + kj.x]), float(arena[kd + kj.y]), float(arena[kd + kj.z]), float(arena[kd + kj.w]));+ acc += outerProduct(q, k);+ }+ float scale = uintBitsToFloat(p.param0_bits);+ for (uint j = 0u; j < 4u && key_base + j < keys; j++) {+ for (uint i = 0u; i < 4u && query_base + i < queries; i++) {+ uint at = (head * queries + query_base + i) * keys + key_base + j;+ arena[p.out_at + at] = float16_t(acc[j][i] * scale);+ }+ }+}+ void tiled() { uint tile = gl_WorkGroupID.y * gl_NumWorkGroups.x + gl_WorkGroupID.x; if (tile >= p.count) {@@ -76,6 +102,10 @@ void tiled() { if (query_base >= queries || key_base >= keys) { return; }+ if (p.kw == 2u) {+ ragged(queries, keys, head_dim, head, query_base, key_base);+ return;+ } // Both lengths are multiples of four, so a quad is wholly inside its sequence. uint q_quad = (p.in0 + head * head_dim * queries + query_base) >> 2u; uint k_quad = (p.in1 + kv_head_of(head) * head_dim * keys + key_base) >> 2u;@@ -98,7 +128,7 @@ void tiled() { } void main() {- if (p.kw == 1u) {+ if (p.kw != 0u) { tiled(); return; }
library/ml/src/main/rust/src/nets/mod_part9c.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part9c.rs b/library/ml/src/main/rust/src/nets/mod_part9c.rsindex 6995895eaa..9c0cd88afc 100644--- a/library/ml/src/main/rust/src/nets/mod_part9c.rs+++ b/library/ml/src/main/rust/src/nets/mod_part9c.rs@@ -161,8 +161,17 @@ impl<'a> Builder<'a> { && in0 % 4 == 0 && in1 % 4 == 0; let tiles = so.c * so.h.div_ceil(ATTN_TILE) * so.w.div_ceil(ATTN_TILE);- let (kw, count, invocations) =- if tiled { (1, tiles, tiles * 64) } else { (0, so.len(), so.len()) };+ // Otherwise the same blocking through scalar loads (`kw` 2), e.g. a vision tower's+ // 594 patches. Long maps only: the shorter ragged ones (NLLB sources, OCR lines,+ // TinyCLIP's 197 tokens) keep the per-element shader and so their exact outputs.+ let ragged = !tiled && so.h >= 256 && so.w >= 256;+ let (kw, count, invocations) = if tiled {+ (1, tiles, tiles * 64)+ } else if ragged {+ (2, tiles, tiles * 64)+ } else {+ (0, so.len(), so.len())+ }; ops.push(Op::Dispatch { kind: Kind::AttnScores, push: Push {
library/ml/src/main/rust/src/nets/mod_part9d.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part9d.rs b/library/ml/src/main/rust/src/nets/mod_part9d.rsindex 203351d0e2..752a04b77b 100644--- a/library/ml/src/main/rust/src/nets/mod_part9d.rs+++ b/library/ml/src/main/rust/src/nets/mod_part9d.rs@@ -20,8 +20,16 @@ impl<'a> Builder<'a> { && in0 % 4 == 0 && in1 % 4 == 0; let tiles = so.c.div_ceil(ATTN_TILE) * so.w.div_ceil(ATTN_TILE);- let (kw, count, invocations) =- if tiled { (1, tiles, tiles * 64) } else { (0, so.len(), so.len()) };+ // Otherwise the same blocking through scalar loads (`kw` 2) when the key count or a+ // base is not a multiple of four. Long maps only, as for the scores.+ let ragged = !tiled && so.w >= 256 && sv.w >= 256 && head_dim % 4 == 0;+ let (kw, count, invocations) = if tiled {+ (1, tiles, tiles * 64)+ } else if ragged {+ (2, tiles, tiles * 64)+ } else {+ (0, so.len(), so.len())+ }; ops.push(Op::Dispatch { kind: Kind::AttnApply, push: Push {
library/ml/src/main/rust/src/vulkan/parity.rs
diff --git a/library/ml/src/main/rust/src/vulkan/parity.rs b/library/ml/src/main/rust/src/vulkan/parity.rsindex ec187d7f8b..e7f76408b0 100644--- a/library/ml/src/main/rust/src/vulkan/parity.rs+++ b/library/ml/src/main/rust/src/vulkan/parity.rs@@ -446,4 +446,5 @@ include!("parity_part6.rs"); include!("parity_part10.rs"); include!("parity_part7.rs"); include!("parity_part8.rs");-include!("parity_part11.rs");\ No newline at end of file+include!("parity_part11.rs");+include!("parity_part12.rs");\ No newline at end of file
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.rsnew file mode 100644index 0000000000..bc2cfe8b0c--- /dev/null+++ b/library/ml/src/main/rust/src/vulkan/parity_part12.rs@@ -0,0 +1,33 @@+/// Build `record`'s plan and require every dispatch of `kind` to take the ragged tiled mode.+fn ragged_plan(source: &dyn WeightSource, shapes: &[Shape], kind: crate::nets::Kind, record: impl FnOnce(&mut Builder, &[Id]) -> Id) -> Plan {+ let plan = build(source, shapes, record);+ let ragged = plan.ops.iter().filter(|op| matches!(op, crate::nets::Op::Dispatch { kind: k, push, .. } if *k == kind && push.kw == 2)).count();+ assert!(ragged > 0, "no {kind:?} took the ragged tiled mode");+ plan+}++#[test]+#[ignore = "needs a Vulkan device"]+fn ragged_tiled_attention_agrees_with_the_reference() {+ // Lengths that are not multiples of four and at least 256 (the Gemma vision tower runs 594+ // patches), partial 32-wide tiles, queries != keys, and a grouped case.+ for (heads, kv_heads, head_dim, queries, keys) in [(2u32, 2u32, 8u32, 258u32, 261u32), (4, 2, 12, 262, 257), (2, 1, 64, 278, 278)] {+ let q = spread((heads * head_dim * queries) as usize, 0.31);+ let k = spread((kv_heads * head_dim * keys) as usize, -0.23);+ let source = Invented::new(0);+ let shapes = [Shape::new(heads * head_dim, 1, queries), Shape::new(kv_heads * head_dim, 1, keys)];+ let plan = ragged_plan(&source, &shapes, crate::nets::Kind::AttnScores, |b, ids| {+ b.attn_scores_grouped_prescaled(ids[0], ids[1], heads, kv_heads)+ });+ compare(&format!("ragged scores {heads}/{kv_heads} heads {queries}x{keys}"), plan, source.into_data(), &[&q, &k]);++ let probs = spread((heads * queries * keys) as usize, 0.17);+ let v = spread((kv_heads * head_dim * keys) as usize, 0.53);+ let source = Invented::new(0);+ let shapes = [Shape::new(heads, queries, keys), Shape::new(kv_heads * head_dim, 1, keys)];+ let plan = ragged_plan(&source, &shapes, crate::nets::Kind::AttnApply, |b, ids| {+ b.attn_apply_grouped(ids[0], ids[1], heads, kv_heads)+ });+ compare(&format!("ragged apply {heads}/{kv_heads} heads {queries}x{keys}"), plan, source.into_data(), &[&probs, &v]);+ }+}