ml: row-parallel norms and softmax for few-row reductions
- Commit
c3d29a411a8dddff77c9c996f8b427116775f98b- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-25 19:47 UTC (1 month ago)
- Parents
483d95e
Diff
library/ml/src/main/rust/examples/profile_net.rs
diff --git a/library/ml/src/main/rust/examples/profile_net.rs b/library/ml/src/main/rust/examples/profile_net.rsnew file mode 100644index 0000000000..0070645392--- /dev/null+++ b/library/ml/src/main/rust/examples/profile_net.rs@@ -0,0 +1,165 @@+//! Per-kind GPU time and per-pass wall time for one model, on whatever device runs it.+//!+//! ```text+//! cargo run --release -p modelrunner --example profile_net -- nllb [path/to/nllb600.maml]+//! adb shell MODELRUNNER_TIMESTAMPS=1 /data/local/tmp/maml/profile_net nllb /data/local/tmp/maml/nllb/nllb600.maml+//! ```+//!+//! Timestamps need `MODELRUNNER_TIMESTAMPS=1`; without it only wall times print. The wall times+//! are with timestamps off unless it is set, so measure the two in separate runs.+use std::collections::BTreeMap;+use std::time::Instant;++use modelrunner::nets::nllb;+use modelrunner::vulkan::context;+use modelrunner::vulkan::reshape::Reshaped;+use modelrunner::vulkan::run::{Net, StepParams};+use modelrunner::weights::{graph, Weights};++/// Source tokens. A longish sentence, so cross-attention costs show.+const SRC_LEN: u32 = 32;++/// Decode steps timed after one warm-up.+const STEPS: u32 = 24;++fn main() {+ let args: Vec<String> = std::env::args().skip(1).collect();+ let model = args.first().map(String::as_str).unwrap_or("nllb");+ let result = match model {+ "nllb" => nllb_profile(args.get(1).map(String::as_str)),+ other => Err(format!("unknown model {other:?}; known: nllb")),+ };+ if let Err(why) = result {+ println!("failed: {why}");+ }+}++fn nllb_profile(path: Option<&str>) -> Result<(), String> {+ let path = path+ .map(str::to_owned)+ .or_else(|| std::env::var("MODELRUNNER_NLLB").ok())+ .ok_or("pass the nllb600.maml path or set MODELRUNNER_NLLB")?;+ let bytes = std::fs::read(&path).map_err(|e| format!("cannot read {path}: {e}"))?;+ let weights = Weights::parse(&bytes, graph::NLLB)?;+ let context = context::shared()?;++ let started = Instant::now();+ let mut net = Reshaped::new(+ context,+ &weights,+ nllb::Mode::Encode { len: SRC_LEN },+ |offsets, mode| nllb::build(offsets, mode),+ )?;+ println!("load {:>8.1} ms (upload + first record)", ms(started));++ // A plausible source: the source-language token, then ordinary pieces, then `</s>`.+ let mut source: Vec<u32> = vec![256_047];+ source.extend((0..SRC_LEN - 2).map(|i| 1_000 + i * 37));+ source.push(2);+ let embedded = nllb::embed_positions(weights.reader(), &source, 0)?;++ let mut encode_ms = Vec::new();+ let mut switch_ms = Vec::new();+ let mut step_ms = Vec::new();+ // Three sentences, so the per-call re-records show up as well as steady-state steps.+ for _ in 0..3 {+ let t = Instant::now();+ net.at(nllb::Mode::Encode { len: SRC_LEN })?.infer_raw(&embedded)?;+ encode_ms.push(ms(t));++ let mut token = 2u32;+ for step in 0..=STEPS {+ let row = nllb::embed_positions(weights.reader(), &[token], step)?;+ let t = Instant::now();+ let at = net.at(nllb::Mode::DecodeStep { src_len: SRC_LEN })?;+ if step == 0 {+ switch_ms.push(ms(t));+ }+ let t = Instant::now();+ at.set_params(StepParams { prefix: step, window_start: 0 })?;+ let out = at.infer_raw(&row)?;+ if step > 0 {+ step_ms.push(ms(t));+ }+ token = greedy(&out).unwrap_or(2).min(nllb::VOCAB - 1);+ }+ }+ println!("encode {} (includes the re-record into Encode after the first)", stats(&encode_ms));+ println!("switch {} (re-record into DecodeStep)", stats(&switch_ms));+ println!("step {}", stats(&step_ms));++ let decode = net.at(nllb::Mode::DecodeStep { src_len: SRC_LEN })?;+ print_kinds("decode step", decode);+ let encode = net.at(nllb::Mode::Encode { len: SRC_LEN })?;+ encode.infer_raw(&embedded)?;+ print_kinds("encode", encode);+ Ok(())+}++/// The token from a greedy plan's `[lo, hi]` output, or the argmax of a logits plan's splits.+fn greedy(out: &[Vec<f32>]) -> Option<u32> {+ if let [pair] = out {+ if let [lo, hi] = pair[..] {+ return Some(hi as u32 * 2048 + lo as u32);+ }+ }+ let mut best: Option<(u32, f32)> = None;+ let mut index = 0u32;+ for split in out {+ for &value in split {+ if best.is_none_or(|(_, top)| value > top) {+ best = Some((index, value));+ }+ index += 1;+ }+ }+ best.map(|(id, _)| id)+}++fn print_kinds(label: &str, net: &Net) {+ let times = match net.op_times() {+ Ok(times) => times,+ Err(why) => {+ println!("{label}: {why}");+ return;+ }+ };+ let mut kinds: BTreeMap<String, (usize, f64)> = BTreeMap::new();+ let (mut total, mut gaps) = (0.0, 0.0);+ for (name, us, gap) in × {+ let kind = name.split(": ").nth(1).unwrap_or(name).to_string();+ let entry = kinds.entry(kind).or_default();+ entry.0 += 1;+ entry.1 += us;+ total += us;+ gaps += gap;+ }+ let mut rows: Vec<_> = kinds.into_iter().collect();+ rows.sort_by(|a, b| b.1 .1.total_cmp(&a.1 .1));+ println!();+ println!("{label}: {} dispatches, {:.2} ms in shaders, {:.2} ms in gaps", times.len(), total / 1e3, gaps / 1e3);+ println!(" {:<22} {:>6} {:>10} {:>10}", "kind", "count", "total ms", "mean us");+ for (kind, (count, us)) in rows {+ println!(" {kind:<22} {count:>6} {:>10.3} {:>10.1}", us / 1e3, us / count as f64);+ }+}++fn ms(since: Instant) -> f64 {+ since.elapsed().as_secs_f64() * 1e3+}++fn stats(values: &[f64]) -> String {+ if values.is_empty() {+ return "n/a".into();+ }+ let mut sorted = values.to_vec();+ sorted.sort_by(f64::total_cmp);+ let mean = sorted.iter().sum::<f64>() / sorted.len() as f64;+ format!(+ "mean {mean:>8.2} ms median {:>8.2} min {:>8.2} max {:>8.2} (n={})",+ sorted[sorted.len() / 2],+ sorted[0],+ sorted[sorted.len() - 1],+ sorted.len()+ )+}
library/ml/src/main/rust/shaders/layernorm.comp
diff --git a/library/ml/src/main/rust/shaders/layernorm.comp b/library/ml/src/main/rust/shaders/layernorm.compindex 7aceb9008d..3f7f2d771e 100644--- a/library/ml/src/main/rust/shaders/layernorm.comp+++ b/library/ml/src/main/rust/shaders/layernorm.comp@@ -23,10 +23,54 @@ //! //! Accumulation is `float` like everywhere else here, and `epsilon` arrives in the push //! block because the recogniser uses 1e-5 for four of these and 1e-6 for the last.+//!+//! # Row mode+//!+//! With `p.kw == 1` one workgroup normalises one position and its lanes split the channels.+//! See `reduce.glsl` for why: a decode step has a single position. +#extension GL_KHR_shader_subgroup_basic : require+#extension GL_KHR_shader_subgroup_arithmetic : require #include "common.glsl"+#include "reduce.glsl"++void row_mode() {+ uint position = reduce_row();+ if (position >= p.count) {+ return;+ }+ uint lane = gl_LocalInvocationID.x;+ uint lanes = gl_WorkGroupSize.x;+ uint stride = p.in_h * p.in_w;+ float epsilon = uintBitsToFloat(p.param1_bits);++ float total = 0.0;+ for (uint c = lane; c < p.in_c; c += lanes) {+ total += float(arena[p.in0 + c * stride + position]);+ }+ float mean = workgroup_sum(total) / float(p.in_c);++ float variance = 0.0;+ for (uint c = lane; c < p.in_c; c += lanes) {+ float centred = float(arena[p.in0 + c * stride + position]) - mean;+ variance += centred * centred;+ }+ float inverse = 1.0 / sqrt(workgroup_sum(variance) / float(p.in_c) + epsilon);++ for (uint c = lane; c < p.in_c; c += lanes) {+ uint at = c * stride + position;+ float centred = float(arena[p.in0 + at]) - mean;+ float gamma = float(weights[p.weight + c]);+ float beta = float(weights[p.bias + c]);+ arena[p.out_at + at] = float16_t(centred * inverse * gamma + beta);+ }+} void main() {+ if (reduce_row_mode()) {+ row_mode();+ return;+ } uint position = global_index(); if (position >= p.count) { return;
library/ml/src/main/rust/shaders/reduce.glsl
diff --git a/library/ml/src/main/rust/shaders/reduce.glsl b/library/ml/src/main/rust/shaders/reduce.glslnew file mode 100644index 0000000000..8b3036609d--- /dev/null+++ b/library/ml/src/main/rust/shaders/reduce.glsl@@ -0,0 +1,68 @@+// Workgroup-wide reductions for the row-parallel mode of the reducing shaders.+//+// Included after `common.glsl` by `layernorm.comp`, `rmsnorm.comp`, `softmax.comp` and+// `softmax_prefix.comp`, each of which must enable `GL_KHR_shader_subgroup_basic` and+// `GL_KHR_shader_subgroup_arithmetic` before its first include - `#extension` has to precede+// every declaration.+//+// # Why a row mode exists+//+// Those shaders were written for one invocation per row, each walking the whole row on its own.+// That is right when there are thousands of rows, and it leaves the GPU nearly idle when there+// are a handful: a decode step normalises **one** position of 1,024 channels, so a single thread+// does 3,072 dependent loads while every other lane on the device waits. On a Pixel 8 that made+// NLLB's 37 layer norms 47% of a decode step at 790 us each, and Gemma's 241 RMS norms 200 ms of+// a 409 ms token.+//+// With `p.kw == 1` a whole 64-lane workgroup owns one row instead: lanes stride the row, reduce+// in registers with a subgroup op, then across the workgroup's subgroups through `reduce_partial`.+// `p.kw` is otherwise unused by these shaders, `p.count` stays the row count, and the work per row+// is unchanged - so the reference interpreter, `Kind::arena_reads` and the barrier schedule need+// no change. `Builder` picks the mode; see `ROW_REDUCE_MAX_ROWS` in `nets`.+//+// Every call is reached by the whole workgroup: the row index is per workgroup, so an early+// `return` on it is uniform, and `p.kw` is a push constant.++// One slot per subgroup. 64 covers a subgroup size of 1, which no device has but costs nothing.+shared float reduce_partial[64];++// The row this workgroup owns in row mode, across the same 2-D grid `global_index` flattens.+uint reduce_row() {+ return gl_WorkGroupID.y * gl_NumWorkGroups.x + gl_WorkGroupID.x;+}++// Whether this dispatch runs one workgroup per row.+bool reduce_row_mode() {+ return p.kw == 1u;+}++// The sum of `value` over every lane of the workgroup, returned to every lane.+float workgroup_sum(float value) {+ float summed = subgroupAdd(value);+ if (subgroupElect()) {+ reduce_partial[gl_SubgroupID] = summed;+ }+ barrier();+ float total = 0.0;+ for (uint i = 0u; i < gl_NumSubgroups; i++) {+ total += reduce_partial[i];+ }+ // The next reduction reuses the slots, so nobody may write them until everyone has read.+ barrier();+ return total;+}++// The maximum of `value` over every lane of the workgroup, returned to every lane.+float workgroup_max(float value) {+ float top = subgroupMax(value);+ if (subgroupElect()) {+ reduce_partial[gl_SubgroupID] = top;+ }+ barrier();+ float peak = reduce_partial[0];+ for (uint i = 1u; i < gl_NumSubgroups; i++) {+ peak = max(peak, reduce_partial[i]);+ }+ barrier();+ return peak;+}
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 9ce9875fb1..814f7ef670 100644--- a/library/ml/src/main/rust/shaders/rmsnorm.comp+++ b/library/ml/src/main/rust/shaders/rmsnorm.comp@@ -20,10 +20,53 @@ //! Identical to layer norm's: the sequence is `[d_model, 1, T]`, one invocation per //! position, and the reduction strides by `in_h * in_w`. See `nets::Kind::LayerNorm` for //! why the layout is that way round.+//!+//! # Row mode+//!+//! With `p.kw == 1` one workgroup owns one (group, position) row and its lanes split the+//! group's channels. See `reduce.glsl`. +#extension GL_KHR_shader_subgroup_basic : require+#extension GL_KHR_shader_subgroup_arithmetic : require #include "common.glsl"+#include "reduce.glsl"++void row_mode() {+ uint position = reduce_row();+ if (position >= p.count) {+ return;+ }+ uint lane = gl_LocalInvocationID.x;+ uint lanes = gl_WorkGroupSize.x;+ uint stride = p.in_h * p.in_w;+ uint groups = max(p.group, 1u);+ uint per_group = p.in_c / groups;+ uint base = (position / stride) * per_group;+ uint at_pos = position % stride;+ float epsilon = uintBitsToFloat(p.param1_bits);+ float squares = 0.0;+ for (uint c = lane; c < per_group; c += lanes) {+ float value = float(arena[p.in0 + (base + c) * stride + at_pos]);+ squares += value * value;+ }+ float inverse = 1.0 / sqrt(workgroup_sum(squares) / float(per_group) + epsilon);+ for (uint c = lane; c < per_group; c += lanes) {+ uint at = (base + c) * stride + at_pos;+ float value = float(arena[p.in0 + at]);+ float gamma = float(weights[p.weight + c]);+ float normed = quant_store(value * inverse * gamma);+ if (p.res != 0xFFFFFFFFu) {+ normed += float(arena[p.res + at]);+ }+ arena[p.out_at + at] = float16_t(normed);+ }+} void main() {+ if (reduce_row_mode()) {+ row_mode();+ return;+ } uint position = global_index(); if (position >= p.count) { return;
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 db0970bbf4..24d8073a93 100644--- a/library/ml/src/main/rust/shaders/softmax.comp+++ b/library/ml/src/main/rust/shaders/softmax.comp@@ -32,10 +32,46 @@ //! Maximum, then sum, then store, re-evaluating `exp` in the third rather than keeping //! the row in registers: `T` is around 80 for a line of text, which is far too large for //! a fixed-size local array and too small for the bandwidth to matter.+//!+//! # Row mode+//!+//! 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`. +#extension GL_KHR_shader_subgroup_basic : require+#extension GL_KHR_shader_subgroup_arithmetic : require #include "common.glsl"+#include "reduce.glsl"++void row_mode() {+ uint row = reduce_row();+ if (row >= p.count) {+ return;+ }+ uint lane = gl_LocalInvocationID.x;+ uint lanes = gl_WorkGroupSize.x;+ uint at = p.in0 + row * p.out_w;+ float peak = -65504.0;+ for (uint i = lane; i < p.out_w; 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) {+ 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);+ }+} void main() {+ if (reduce_row_mode()) {+ row_mode();+ return;+ } uint row = global_index(); if (row >= p.count) { return;
library/ml/src/main/rust/shaders/softmax_prefix.comp
diff --git a/library/ml/src/main/rust/shaders/softmax_prefix.comp b/library/ml/src/main/rust/shaders/softmax_prefix.compindex 7e5b9f3d27..3a8cf432fd 100644--- a/library/ml/src/main/rust/shaders/softmax_prefix.comp+++ b/library/ml/src/main/rust/shaders/softmax_prefix.comp@@ -20,10 +20,49 @@ //! //! The output is written over the same leading span. Entries past it keep whatever they held, //! which is safe precisely because `attn_apply_cached.comp` sums over the same bound.+//!+//! # Row mode+//!+//! With `p.kw == 1` one workgroup owns one row and its lanes split the attended keys. A decode+//! step has one row per head and up to the whole context per row. See `reduce.glsl`. +#extension GL_KHR_shader_subgroup_basic : require+#extension GL_KHR_shader_subgroup_arithmetic : require #include "common.glsl"+#include "reduce.glsl"++void row_mode() {+ uint row = reduce_row();+ if (row >= p.count) {+ return;+ }+ uint lane = gl_LocalInvocationID.x;+ uint lanes = gl_WorkGroupSize.x;+ uint stride = p.out_w;+ uint first = attn_first();+ uint last = attn_last(stride);+ uint at = p.in0 + row * stride;+ float peak = -65504.0;+ for (uint i = first + lane; i <= last; i += lanes) {+ peak = max(peak, float(arena[at + i]));+ }+ peak = workgroup_max(peak);+ float total = 0.0;+ for (uint i = first + lane; i <= last; i += lanes) {+ total += exp(float(arena[at + i]) - peak);+ }+ float inverse = 1.0 / workgroup_sum(total);+ uint out_row = p.out_at + row * stride;+ for (uint i = first + lane; i <= last; i += lanes) {+ arena[out_row + i] = float16_t(exp(float(arena[at + i]) - peak) * inverse);+ }+} void main() {+ if (reduce_row_mode()) {+ row_mode();+ return;+ } uint row = global_index(); if (row >= p.count) { return;
library/ml/src/main/rust/src/nets/mod_part3.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part3.rs b/library/ml/src/main/rust/src/nets/mod_part3.rsindex d3584074aa..3353d14d52 100644--- a/library/ml/src/main/rust/src/nets/mod_part3.rs+++ b/library/ml/src/main/rust/src/nets/mod_part3.rs@@ -34,6 +34,30 @@ const CONV_VEC_INT4_ROWS: u32 = 8; /// `the_q2k_gemv_row_count_matches_its_shader` holds it against the shader. pub(crate) const CONV_VEC_Q2K_ROWS: u32 = 8; +/// Most rows a reducing kind (layer norm, RMS norm, softmax) runs one workgroup per row for.+///+/// Below it a whole workgroup splits each row - see `shaders/reduce.glsl` - because there are+/// too few rows to occupy the device one invocation each: a decode step normalises a single+/// position. Above it the original one-invocation-per-row mode stays, because enough rows fill+/// the device on their own and adjacent invocations then read adjacent positions.+const ROW_REDUCE_MAX_ROWS: u32 = 256;++/// Shortest row worth splitting across a workgroup. Shorter rows leave most lanes idle.+const ROW_REDUCE_MIN_LEN: u32 = 64;++/// Invocations per workgroup: `local_size_x` in `shaders/common.glsl`.+const ROW_REDUCE_LANES: u32 = 64;++/// Whether `rows` rows of `len` elements reduce one workgroup per row, as+/// `(Push::kw, invocations)`.+fn row_reduce(rows: u32, len: u32) -> (u32, u32) {+ if rows <= ROW_REDUCE_MAX_ROWS && len >= ROW_REDUCE_MIN_LEN {+ (1, rows * ROW_REDUCE_LANES)+ } else {+ (0, rows)+ }+}+ #[cfg(test)] fn gemv_rows_of(shader: &str) -> u32 { let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("shaders").join(shader);
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 a4b2a9374e..027124c581 100644--- a/library/ml/src/main/rust/src/nets/mod_part9.rs+++ b/library/ml/src/main/rust/src/nets/mod_part9.rs@@ -361,8 +361,10 @@ impl<'a> Builder<'a> { Node::LayerNorm { input, out, gamma, beta, epsilon } => { let so = shape(*out); // One invocation per position, each reducing over the channels, so the- // dispatch is the spatial extent rather than the element count.+ // dispatch is the spatial extent rather than the element count - or, for a+ // handful of positions, one workgroup each. See `row_reduce`. let positions = so.h * so.w;+ let (kw, invocations) = row_reduce(positions, so.c); ops.push(Op::Dispatch { kind: Kind::LayerNorm, push: Push {@@ -378,9 +380,10 @@ impl<'a> Builder<'a> { out_w: so.w, param1_bits: epsilon.to_bits(), count: positions,+ kw, ..Push::default() },- invocations: positions,+ invocations, }); } Node::InstanceNorm { input, out, epsilon } => {@@ -407,8 +410,10 @@ impl<'a> Builder<'a> { } 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.+ // One invocation per group per position, reducing over that group's channels,+ // or one workgroup each when there are few. See `row_reduce`. let positions = so.h * so.w * groups.max(&1);+ let (kw, invocations) = row_reduce(positions, so.c / groups.max(&1)); // A folded residual addend, or NO_FUSE. Same contract as the // convolution kinds: `fused_store` in the shader adds // `arena[res + index]`, and `arena_reads` covers the range.@@ -433,9 +438,10 @@ impl<'a> Builder<'a> { param1_bits: epsilon.to_bits(), count: positions, res: res_at,+ kw, ..Push::default() },- invocations: positions,+ invocations, }); } Node::AttnScores { q, k, out, heads, kv_heads, scale } => {
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 eeea9e1012..a9340a1b1b 100644--- a/library/ml/src/main/rust/src/nets/mod_part9b.rs+++ b/library/ml/src/main/rust/src/nets/mod_part9b.rs@@ -337,8 +337,14 @@ impl<'a> Builder<'a> { Node::Softmax { input, out, mode, sliding, window } => { let so = shape(*out); // One invocation per row of the last axis, each normalising `out_w`- // contiguous elements, so the dispatch is rows rather than elements.+ // contiguous elements, so the dispatch is rows rather than elements - or one+ // workgroup per row when the rows are few and long. The causal shader has no row+ // mode: it is prefill-only, where rows are plentiful. See `row_reduce`. let rows = so.c * so.h;+ let (kw, invocations) = match mode {+ SoftmaxMode::Causal => (0, rows),+ SoftmaxMode::Full | SoftmaxMode::Prefix => row_reduce(rows, so.w),+ }; ops.push(Op::Dispatch { kind: match mode { SoftmaxMode::Full => Kind::Softmax,@@ -359,9 +365,10 @@ impl<'a> Builder<'a> { sliding: u32::from(*sliding), // Only the causal shader reads it, and only when non-zero. kh: *window,+ kw, ..Push::default() },- invocations: rows,+ invocations, }); } Node::ConcatPositions { parts, out } => {
library/ml/src/main/rust/src/nets/ppocr_rec.rs
diff --git a/library/ml/src/main/rust/src/nets/ppocr_rec.rs b/library/ml/src/main/rust/src/nets/ppocr_rec.rsindex 32aa173b94..cadc227508 100644--- a/library/ml/src/main/rust/src/nets/ppocr_rec.rs+++ b/library/ml/src/main/rust/src/nets/ppocr_rec.rs@@ -414,10 +414,12 @@ mod tests { for op in &plan.ops { if let Op::Dispatch { kind: Kind::LayerNorm, push, invocations } = op { assert_eq!(push.in_c, D_MODEL);- // One invocation per position, not per element: `count` is the spatial- // extent because each reduces a whole column of channels.- assert_eq!(*invocations, WIDTH / 8);+ // One reduction per position, not per element: `count` is the spatial extent+ // because each reduces a whole column of channels. A line is few positions, so+ // each gets a whole workgroup (`row_reduce`), 64 invocations. assert_eq!(push.count, WIDTH / 8);+ assert_eq!(push.kw, 1, "row mode: {push:?}");+ assert_eq!(*invocations, WIDTH / 8 * 64); } } }
library/ml/src/main/rust/src/vulkan/parity_part4.rs
diff --git a/library/ml/src/main/rust/src/vulkan/parity_part4.rs b/library/ml/src/main/rust/src/vulkan/parity_part4.rsindex 7cd3031bfe..18a49296bd 100644--- a/library/ml/src/main/rust/src/vulkan/parity_part4.rs+++ b/library/ml/src/main/rust/src/vulkan/parity_part4.rs@@ -157,6 +157,126 @@ fn layer_norm_over_channels_agrees_with_the_reference() { ); } +/// Build `record`'s plan, require every dispatch of `kind` in it to be in row mode, and return it.+///+/// The row-mode fixtures below are only worth anything if the plan actually chose that mode, and+/// the choice is a threshold in `nets` that can move. This makes a fixture that silently fell back+/// to the per-row shader fail instead of passing for the wrong reason.+fn row_mode_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 mut seen = 0;+ for op in &plan.ops {+ if let crate::nets::Op::Dispatch { kind: k, push, .. } = op {+ if *k == kind {+ assert_eq!(push.kw, 1, "{kind:?} is not in row mode: {push:?}");+ seen += 1;+ }+ }+ }+ assert!(seen > 0, "the plan has no {kind:?}");+ plan+}++#[test]+#[ignore = "needs a Vulkan device"]+fn a_row_mode_layer_norm_agrees_with_the_reference() {+ // A decode step's shape - one position of d_model 1,024 - and a short sentence's, five+ // positions, where the channels a lane reads are a stride apart. 1,024 is not a multiple of+ // the lane count times anything convenient on every device, which is the point: the strided+ // loop must cover every channel exactly once whatever the subgroup size.+ for positions in [1u32, 5] {+ let channels = 1024u32;+ let x = spread((channels * positions) as usize, 0.6);+ let given = Given::new(&[+ (vec![channels], spread(channels as usize, 1.1)),+ (vec![channels], spread(channels as usize, 2.3)),+ ])+ .expect("the fixture tensors are consistent");+ let plan = row_mode_plan(+ &given,+ &[Shape::new(channels, 1, positions)],+ crate::nets::Kind::LayerNorm,+ |b, ids| b.layer_norm(ids[0], 0, 1e-5),+ );+ compare(&format!("row-mode layer norm over {positions}"), plan, given.data().to_vec(), &[&x]);+ }+}++#[test]+#[ignore = "needs a Vulkan device"]+fn a_row_mode_grouped_rms_norm_agrees_with_the_reference() {+ // Gemma 4's QK-norm at decode: eight heads of 256, each its own row and its own workgroup.+ const HEAD_DIM: u32 = 256;+ const HEADS: u32 = 8;+ let channels = HEAD_DIM * HEADS;+ let input: Vec<f32> = (0..channels)+ .map(|i| spread(channels as usize, 0.9)[i as usize] * ((i / HEAD_DIM) as f32 + 1.0))+ .collect();+ let given = Given::new(&[(vec![HEAD_DIM], spread(HEAD_DIM as usize, 2.5))])+ .expect("the fixture tensors are consistent");+ let plan = row_mode_plan(+ &given,+ &[Shape::new(channels, 1, 1)],+ crate::nets::Kind::RmsNorm,+ |b, ids| b.rms_norm_grouped(ids[0], 0, 1e-6, HEADS),+ );+ compare("a row-mode grouped rms norm", plan, given.data().to_vec(), &[&input]);+}++#[test]+#[ignore = "needs a Vulkan device"]+fn a_row_mode_softmax_agrees_with_the_reference() {+ // Whisper's decode cross-attention: a few heads, each one query over 1,500 keys. Large, spread+ // values so the max subtraction matters - a row that skipped it overflows `exp`.+ let (heads, keys) = (8u32, 1500u32);+ let x: Vec<f32> = spread((heads * keys) as usize, 0.3).iter().map(|v| v * 40.0).collect();+ let source = Invented::new(0);+ let plan = row_mode_plan(+ &source,+ &[Shape::new(heads, 1, keys)],+ crate::nets::Kind::Softmax,+ |b, ids| b.softmax(ids[0]),+ );+ compare("a row-mode softmax", plan, source.into_data(), &[&x]);+}++#[test]+#[ignore = "needs a Vulkan device"]+fn a_row_mode_prefix_softmax_agrees_with_the_reference() {+ // A decode plan built at 256 keys, run at several prefixes: the row is mostly stale, and only+ // the leading `prefix + 1` may be read or written. A prefix below and above the lane count, so+ // both the partly idle and the multi-pass cases run.+ let (heads, keys) = (4u32, 256u32);+ let x: Vec<f32> = spread((heads * keys) as usize, 0.7).iter().map(|v| v * 20.0).collect();+ for prefix in [0u32, 40, 200] {+ let source = Invented::new(0);+ let plan = row_mode_plan(+ &source,+ &[Shape::new(heads, 1, keys)],+ crate::nets::Kind::SoftmaxPrefix,+ |b, ids| b.softmax_prefix(ids[0], false),+ );+ let data = source.into_data();+ let host = crate::nets::reference::run_multi_at(&plan, &data, &[&x], prefix, 0)+ .expect("the interpreter runs the plan");+ let got = on_device_at(plan, data, &[&x], prefix);+ // Only the attended span is defined; the rest holds whatever the arena held.+ let live = (prefix + 1) as usize;+ let span = |all: &[Vec<f32>]| -> Vec<Vec<f32>> {+ vec![all[0]+ .chunks_exact(keys as usize)+ .flat_map(|row| row[..live].to_vec())+ .collect()]+ };+ matches(&format!("a row-mode prefix softmax at {prefix}"), &span(&host), &span(&got));+ }+}+ #[test] #[ignore = "needs a Vulkan device"] fn a_two_lane_embedding_agrees_with_the_reference() {