ml: word-per-lane Q2_K decode GEMV (MADLAD 2 s -> 60 ms a token)
- Commit
b1adc26e5c6b4149d46d6676ca0d7579ea81a4e7- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-25 20:50 UTC (1 month ago)
- Parents
1b15559
Diff
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 8a124fc4a5..d6aca5fc45 100644--- a/library/ml/src/main/rust/shaders/conv_vec_q2k.comp+++ b/library/ml/src/main/rust/shaders/conv_vec_q2k.comp@@ -23,6 +23,17 @@ //! `p.in_c` the taps, `p.out_c` the output channels and `p.count` the workgroup count, //! one per group of [`ROWS`] channels. The superblock byte offset of a row's block is //! derived from the two, since rows are contiguous runs of `blocks` superblocks.+//!+//! # Word-per-lane mode+//!+//! When `in_c % 256 == 0` and the activation base is 4-aligned - every MADLAD projection - a lane+//! owns one 32-bit word of a superblock's `qs` rather than a whole superblock. That word holds the+//! 2-bit codes of 16 taps: four bytes, each carrying one code for each of the half's four lanes.+//! Owning whole superblocks left a 1,024-input projection with four of 64 lanes busy, and re-read+//! every activation once per row; on a Pixel 8 that streamed MADLAD's weights at 0.6 GB/s and was+//! 90% of a 2-second token. Here every lane is busy at 1,024 inputs, the sixteen activations are+//! four `f16vec4` loads shared by all the rows, and the affine dequantisation factors out per+//! 4-tap group: `sum((dall*lo*c - dmin*hi) * x) = dall*lo*dot(c, x) - dmin*hi*sum(x)`. // Reductions happen in registers across a subgroup rather than through shared memory across the // whole workgroup. See the tail of `main` for why that is worth an extension requirement.@@ -30,6 +41,11 @@ #extension GL_KHR_shader_subgroup_arithmetic : require #include "common.glsl" +/// The arena as quads of fp16, for the word-per-lane activation loads.+layout(std430, binding = 0) readonly buffer ArenaQuad {+ f16vec4 arena_quad[];+};+ /// Output channels one workgroup owns. /// /// Eight like the int4 gemv, for the same stream reason: a Q2_K superblock is wider than@@ -62,6 +78,50 @@ void main() { for (uint r = 0u; r < ROWS; r++) { acc[r] = 0.0; }+ bool by_word = (p.in_c % Q2K_BLOCK) == 0u && (p.in0 & 3u) == 0u;+ 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) {+ uint block = unit >> 4u;+ uint w = unit & 15u;+ uint half_idx = w >> 3u;+ uint odd = (w >> 2u) & 1u;+ uint quad = w & 3u;+ // Taps `half*128 + q*32 + odd*16 + quad*4 + 0..3` for code lane `q` in 0..3.+ uint first = block * Q2K_BLOCK + half_idx * 128u + odd * 16u + quad * 4u;+ vec4 x[4];+ float xsum[4];+ for (uint q = 0u; q < 4u; q++) {+ x[q] = vec4(arena_quad[(p.in0 + first + q * 32u) >> 2u]);+ xsum[q] = x[q].x + x[q].y + x[q].z + x[q].w;+ }+ for (uint r = 0u; r < ROWS; r++) {+ uint row = min(channel_base + r, p.out_c - 1u);+ uint pair = p.act_weight + row * blocks * 2u + block * 2u;+ float d = float(weights[pair]);+ float m = float(weights[pair + 1u]);+ float dall = d * d;+ float dmin = m * d;+ // The superblock as a word index: 84 bytes is 21 words.+ uint sb = p.weight + (row * blocks + block) * 21u;+ uint codes = weights32[sb + 4u + w];+ // Scale bytes `half*8 + q*2 + odd`: lanes 0,1 in one word, 2,3 in the next.+ 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 c = vec4(float((codes >> shift) & 3u), float((codes >> (shift + 8u)) & 3u),+ float((codes >> (shift + 16u)) & 3u), float((codes >> (shift + 24u)) & 3u));+ total += dall * float(sc & 15u) * dot(c, x[q]) - dmin * float(sc >> 4u) * xsum[q];+ }+ acc[r] += total;+ }+ }+ } else { // A lane owns whole superblocks rather than a stride-64 scatter, so each row's // `(d, dmin)` is fetched once per 256 taps instead of once per tap. //@@ -118,6 +178,7 @@ void main() { acc[r] += total; } }+ } // Reduce inside each subgroup first, then across the few subgroups a workgroup holds. for (uint r = 0u; r < ROWS; r++) { float summed = subgroupAdd(acc[r]);
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 9aee569717..54092e15fe 100644--- a/library/ml/src/main/rust/src/vulkan/parity_part4.rs+++ b/library/ml/src/main/rust/src/vulkan/parity_part4.rs@@ -1,3 +1,41 @@+#[test]+#[ignore = "needs a Vulkan device"]+fn a_q2k_gemv_agrees_with_the_reference() {+ // `conv_vec_q2k.comp` over arbitrary superblock bytes - every scale nibble and code pattern -+ // run once with 1,280 inputs (five superblocks, the word-per-lane path, more units than lanes+ // in the last pass) and once with 300 (not a whole superblock, the per-superblock loop). An+ // odd channel count so the last workgroup's clamped rows must not be stored.+ for (out_channels, in_channels) in [(13u32, 1280u32), (11, 300)] {+ let blocks = in_channels.div_ceil(crate::weights::Q2K_BLOCK);+ let bytes: Vec<u8> = (0..out_channels * blocks * crate::weights::Q2K_BYTES)+ .map(|i| (i.wrapping_mul(2_654_435_761) >> 13) as u8)+ .collect();+ // Small positive `d` and `dmin` so `d*d*q*lo - dmin*d*hi` stays well inside fp16.+ let pairs: Vec<f32> = (0..out_channels * blocks * 2)+ .map(|i| 0.05 + 0.01 * ((i * 7) % 11) as f32)+ .collect();+ let blob = write_mixed(+ graph::SUPERTONIC_VE,+ &[+ Fixture::Q2K(vec![out_channels, in_channels], bytes),+ Fixture::F16(vec![out_channels * blocks * 2], pairs),+ Fixture::F16(vec![out_channels], spread(out_channels as usize, 0.3)),+ ],+ );+ let weights = Weights::parse(&blob, graph::SUPERTONIC_VE).expect("the fixture blob parses");+ let input = spread(in_channels as usize, 0.9);+ let mut builder = Builder::new(&weights);+ let first = builder.input(Shape::new(in_channels, 1, 1));+ let last = builder.conv_q2k(first, 0, out_channels, 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, .. }+ )));+ compare(&format!("a q2k gemv {out_channels}x{in_channels}"), plan, weights.data().to_vec(), &[&input]);+ }+}+ #[test] #[ignore = "needs a Vulkan device"] fn a_wide_gemv_agrees_with_the_reference() {
library/ml/src/main/rust/src/weights_part2.rs
diff --git a/library/ml/src/main/rust/src/weights_part2.rs b/library/ml/src/main/rust/src/weights_part2.rsindex b1cc374e32..79f1412eee 100644--- a/library/ml/src/main/rust/src/weights_part2.rs+++ b/library/ml/src/main/rust/src/weights_part2.rs@@ -376,6 +376,9 @@ pub(crate) enum Fixture { /// are masked rather than clamped, so a fixture that overflows shows up as a wrong number /// rather than a silently saturated one. I4(Vec<u32>, Vec<i8>),+ /// GGUF Q2_K superblocks, raw: [`Q2K_BYTES`] per [`Q2K_BLOCK`] taps of a `[out, taps]` kernel.+ /// The `(d, dmin)` pairs are a separate fp16 tensor, as in a converted file.+ Q2K(Vec<u32>, Vec<u8>), } /// Build a `.maml` blob from a mix of fp16 and int8 tensors, for the fixtures.@@ -432,6 +435,10 @@ pub(crate) fn write_mixed(graph_id: u32, tensors: &[Fixture]) -> Vec<u8> { }) .collect::<Vec<u8>>(), ),+ Fixture::Q2K(dims, bytes) => {+ let elements: u32 = dims.iter().product();+ (dims, DTYPE_Q2K, elements, bytes.clone())+ } }; while !data.len().is_multiple_of(ALIGNMENT as usize) { data.push(0);