ml: Q2_K gemv two words per lane, MADLAD step 59.8 -> 52.7 ms on Pixel
- Commit
9ecc46591cf47070c2c1e30d93056c23859b9545- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-26 03:16 UTC (1 month ago)
- Parents
cabd584
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.rsindex fdd232145e..d4e3ceb0a0 100644--- a/library/ml/src/main/rust/examples/profile_net.rs+++ b/library/ml/src/main/rust/examples/profile_net.rs@@ -10,7 +10,7 @@ use std::collections::BTreeMap; use std::time::Instant; -use modelrunner::nets::{madlad, madlad_part1, nllb, whisper};+use modelrunner::nets::{madlad, madlad_part1, nllb, whisper, Op, Plan}; use modelrunner::vulkan::context; use modelrunner::vulkan::reshape::Reshaped; use modelrunner::vulkan::run::{Net, StepParams};@@ -276,11 +276,14 @@ fn madlad_profile(path: Option<&str>) -> Result<(), String> { println!("step {}", stats(&step_ms)); println!("ids {ids:?}"); + let (planner, offsets) = net.planner(); let decode = net.at(madlad::Mode::DecodeStep { src_len: SRC_LEN })?; print_kinds("decode step", decode);+ print_shapes("decode step", decode, &planner(&offsets, madlad::Mode::DecodeStep { src_len: SRC_LEN })?); let encode = net.at(madlad::Mode::Encode { len: SRC_LEN })?; encode.infer_raw_many(&[&embedded, &enc_bias])?; print_kinds("encode", encode);+ print_shapes("encode", encode, &planner(&offsets, madlad::Mode::Encode { len: SRC_LEN })?); Ok(()) } @@ -332,6 +335,35 @@ fn print_kinds(label: &str, net: &Net) { } } +/// GPU time per (kind, in_c, out_c, positions) when `MODELRUNNER_SHAPES` is set.+fn print_shapes(label: &str, net: &Net, plan: &Plan) {+ if std::env::var("MODELRUNNER_SHAPES").is_err() {+ return;+ }+ let Ok(times) = net.op_times() else { return };+ let pushes: Vec<_> = plan+ .ops+ .iter()+ .filter_map(|op| match op {+ Op::Dispatch { kind, push, .. } => Some((*kind, *push)),+ _ => None,+ })+ .collect();+ let mut shapes: BTreeMap<String, (usize, f64)> = BTreeMap::new();+ for ((_, us, _), (kind, push)) in times.iter().zip(&pushes) {+ let key = format!("{kind:?} {}->{} x{} in1={}", push.in_c, push.out_c, push.out_h * push.out_w, push.in1);+ let entry = shapes.entry(key).or_default();+ entry.0 += 1;+ entry.1 += us;+ }+ let mut rows: Vec<_> = shapes.into_iter().collect();+ rows.sort_by(|a, b| b.1 .1.total_cmp(&a.1 .1));+ println!("{label} by shape:");+ for (key, (count, us)) in rows.into_iter().take(16) {+ println!(" {key:<44} {count:>5} {:>10.3} ms {:>9.1} us", us / 1e3, us / count as f64);+ }+}+ fn ms(since: Instant) -> f64 { since.elapsed().as_secs_f64() * 1e3 }
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 d6aca5fc45..731eb24dd4 100644--- a/library/ml/src/main/rust/shaders/conv_vec_q2k.comp+++ b/library/ml/src/main/rust/shaders/conv_vec_q2k.comp@@ -46,6 +46,11 @@ layout(std430, binding = 0) readonly buffer ArenaQuad { f16vec4 arena_quad[]; }; +/// The arena as 8 fp16 per element, for the pair-per-lane activation loads.+layout(std430, binding = 0) readonly buffer ArenaOct {+ uvec4 arena_oct[];+};+ /// Output channels one workgroup owns. /// /// Eight like the int4 gemv, for the same stream reason: a Q2_K superblock is wider than@@ -79,7 +84,63 @@ void main() { acc[r] = 0.0; } bool by_word = (p.in_c % Q2K_BLOCK) == 0u && (p.in0 & 3u) == 0u;- if (by_word) {+ // Pair-per-lane: a lane owns two adjacent `qs` words (32 taps sharing four scale bytes) for+ // four of the eight rows, so each row's scale words and `(d, dmin)` are fetched once per 32+ // taps instead of 16, and the activations come in as two 16-byte loads per code lane.+ bool by_pair = by_word && (p.in0 & 7u) == 0u && (p.act_weight & 1u) == 0u;+ if (by_pair) {+ uint row_half = lane >> 5u;+ uint units = blocks * 8u;+ float part[4];+ for (uint r = 0u; r < 4u; r++) {+ part[r] = 0.0;+ }+ for (uint unit = lane & 31u; unit < units; unit += 32u) {+ uint block = unit >> 3u;+ uint w = (unit & 7u) << 1u;+ uint half_idx = w >> 3u;+ uint odd = (w >> 2u) & 1u;+ uint first = block * Q2K_BLOCK + half_idx * 128u + odd * 16u + (w & 3u) * 4u;+ vec4 xa[4];+ vec4 xb[4];+ float xsum[4];+ for (uint q = 0u; q < 4u; q++) {+ uvec4 raw = arena_oct[(p.in0 + first + q * 32u) >> 3u];+ xa[q] = vec4(unpackHalf2x16(raw.x), unpackHalf2x16(raw.y));+ xb[q] = vec4(unpackHalf2x16(raw.z), unpackHalf2x16(raw.w));+ vec4 s = xa[q] + xb[q];+ xsum[q] = s.x + s.y + s.z + s.w;+ }+ for (uint r = 0u; r < 4u; r++) {+ uint row = min(channel_base + row_half * 4u + r, p.out_c - 1u);+ uint idx = row * blocks + block;+ vec2 dm = unpackHalf2x16(weights32[(p.act_weight >> 1u) + idx]);+ float dall = dm.x * dm.x;+ float dmin = dm.y * dm.x;+ uint sb = p.weight + idx * 21u;+ uint c0 = weights32[sb + 4u + w];+ uint c1 = weights32[sb + 5u + w];+ uint scales_lo = weights32[sb + half_idx * 2u];+ uint scales_hi = weights32[sb + half_idx * 2u + 1u];+ float total = 0.0;+ for (uint q = 0u; q < 4u; q++) {+ uint word = q < 2u ? scales_lo : scales_hi;+ uint sc = (word >> ((((q & 1u) << 1u) + odd) << 3u)) & 255u;+ uint shift = q << 1u;+ vec4 ca = vec4(float((c0 >> shift) & 3u), float((c0 >> (shift + 8u)) & 3u),+ float((c0 >> (shift + 16u)) & 3u), float((c0 >> (shift + 24u)) & 3u));+ vec4 cb = vec4(float((c1 >> shift) & 3u), float((c1 >> (shift + 8u)) & 3u),+ float((c1 >> (shift + 16u)) & 3u), float((c1 >> (shift + 24u)) & 3u));+ total += dall * float(sc & 15u) * (dot(ca, xa[q]) + dot(cb, xb[q]))+ - dmin * float(sc >> 4u) * xsum[q];+ }+ part[r] += total;+ }+ }+ for (uint r = 0u; r < ROWS; r++) {+ acc[r] = (r >> 2u) == row_half ? part[r & 3u] : 0.0;+ }+ } else if (by_word) { // 16 `qs` words per superblock, so this many units across the row. uint units = blocks * 16u; for (uint unit = lane; unit < units; unit += 64u) {
library/ml/src/main/rust/src/vulkan/parity_part6.rs
diff --git a/library/ml/src/main/rust/src/vulkan/parity_part6.rs b/library/ml/src/main/rust/src/vulkan/parity_part6.rsindex 6b59c9e6c6..76bbfcbb2d 100644--- a/library/ml/src/main/rust/src/vulkan/parity_part6.rs+++ b/library/ml/src/main/rust/src/vulkan/parity_part6.rs@@ -448,3 +448,36 @@ fn strided_window_convs_agree_with_the_reference() { ); } }++/// The Q2_K gemv's pair-per-lane path (8-aligned input, even scale table) at MADLAD's input widths,+/// ragged row groups, several units per lane at 8192.+#[test]+#[ignore = "needs a Vulkan device"]+fn q2k_gemv_pairs_agree_with_the_reference() {+ for (out_c, in_c) in [(44u32, 1024u32), (13, 2048), (9, 8192)] {+ let blocks = in_c / crate::weights::Q2K_BLOCK;+ let bytes: Vec<u8> =+ (0..out_c * blocks * crate::weights::Q2K_BYTES).map(|i| (i.wrapping_mul(2_246_822_519) >> 7) as u8).collect();+ let pairs: Vec<f32> = (0..out_c * blocks * 2).map(|i| 0.05 + 0.01 * ((i * 5) % 9) as f32).collect();+ let blob = write_mixed(+ graph::SUPERTONIC_VE,+ &[+ Fixture::Q2K(vec![out_c, in_c], bytes),+ Fixture::F16(vec![out_c * blocks * 2], pairs),+ Fixture::F16(vec![out_c], spread(out_c as usize, 0.2)),+ ],+ );+ let weights = Weights::parse(&blob, graph::SUPERTONIC_VE).expect("the fixture blob parses");+ let input = spread(in_c as usize, 0.8);+ let mut builder = Builder::new(&weights);+ let first = builder.input(Shape::new(in_c, 1, 1));+ let last = builder.conv_q2k(first, 0, out_c, Act::None);+ let plan = builder.finish(&[last]).expect("the q2k gemv plan builds");+ assert!(plan.ops.iter().any(|op| matches!(+ op,+ crate::nets::Op::Dispatch { kind: crate::nets::Kind::ConvVecQ2K, push, .. }+ if push.in0 % 8 == 0 && push.act_weight % 2 == 0+ )));+ compare(&format!("a q2k gemv {out_c}x{in_c}"), plan, weights.data().to_vec(), &[&input]);+ }+}