ml: Q2_K GEMM 4-way tap split for long-K low-tile shapes, encode -12% GPU
- Commit
a9e97cff98c55a02509b8b2a32f9bb1327c79dfa- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-26 03:36 UTC (1 month ago)
- Parents
80f2c62
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 d4e3ceb0a0..2f81ebd32b 100644--- a/library/ml/src/main/rust/examples/profile_net.rs+++ b/library/ml/src/main/rust/examples/profile_net.rs@@ -242,6 +242,10 @@ fn madlad_profile(path: Option<&str>) -> Result<(), String> { let out = net.at(madlad::Mode::Encode { len: SRC_LEN })?.infer_raw_many(&[&embedded, &enc_bias])?; encode_ms.push(ms(t)); let encoded = out.into_iter().next().ok_or("the encoder returned nothing")?;+ if round == 0 {+ let sum: f64 = encoded.iter().map(|&v| f64::from(v)).sum();+ println!("encoded checksum {sum:.6}");+ } let mut token = 0u32; for step in 0..STEPS {
library/ml/src/main/rust/shaders/conv_point_q2k.comp
diff --git a/library/ml/src/main/rust/shaders/conv_point_q2k.comp b/library/ml/src/main/rust/shaders/conv_point_q2k.compindex 8d9e51cf69..330e3bf81f 100644--- a/library/ml/src/main/rust/shaders/conv_point_q2k.comp+++ b/library/ml/src/main/rust/shaders/conv_point_q2k.comp@@ -39,17 +39,27 @@ layout(std430, binding = 0) readonly buffer ArenaQuad { /// Channels and positions per invocation. #define BLOCK 4u +/// Partial sums from the K-split's other slices, combined by slice 0 in slice order.+shared float partial[64][BLOCK * BLOCK];+ void main() { uint tile = gl_WorkGroupID.y * gl_NumWorkGroups.x + gl_WorkGroupID.x; if (tile >= p.count) { return; }+ // `p.in1` = s > 0 (word path only): the workgroup's lanes split into 2^s slices, each summing+ // a contiguous 1/2^s of the taps for a (32 >> s) x 32 tile, so a GEMM with few tiles (MADLAD's+ // 8192 -> 1024 at 32 positions is 32) runs 2^s times the workgroups at the same loads per MAC.+ uint split = p.in1;+ uint slice_lanes = 64u >> split; uint positions = p.out_h * p.out_w; uint tiles_across = (positions + TILE - 1u) / TILE; uint lid = gl_LocalInvocationID.x;- uint channel_base = (tile / tiles_across) * TILE + (lid >> 3u) * BLOCK;+ uint slice = lid / slice_lanes;+ uint channel_base = (tile / tiles_across) * (TILE >> split) + ((lid % slice_lanes) >> 3u) * BLOCK; uint position_base = (tile % tiles_across) * TILE + (lid & 7u) * BLOCK;- if (position_base >= positions) {+ bool busy = position_base < positions;+ if (!busy && split == 0u) { return; } uint blocks = (p.in_c + Q2K_BLOCK - 1u) / Q2K_BLOCK;@@ -77,7 +87,11 @@ void main() { for (uint i = 0u; i < BLOCK; i++) { sum[i] = vec4(0.0); }- for (uint unit = 0u; unit < blocks * 16u; unit++) {+ bool pair_word = (p.act_weight & 1u) == 0u;+ uint units = (blocks * 16u) >> split;+ uint unit0 = busy ? slice * units : 0u;+ uint unit_end = busy ? unit0 + units : 0u;+ for (uint unit = unit0; unit < unit_end; unit++) { uint block = unit >> 4u; uint w = unit & 15u; uint half_idx = w >> 3u;@@ -94,9 +108,14 @@ void main() { scales[i][0] = weights32[sb + half_idx * 2u]; scales[i][1] = weights32[sb + half_idx * 2u + 1u]; uint pair = p.act_weight + (rows[i] * blocks + block) * 2u;- float d = float(weights[pair]);- dall[i] = d * d;- dmin[i] = float(weights[pair + 1u]) * d;+ vec2 dm;+ if (pair_word) {+ dm = unpackHalf2x16(weights32[pair >> 1u]);+ } else {+ dm = vec2(float(weights[pair]), float(weights[pair + 1u]));+ }+ dall[i] = dm.x * dm.x;+ dmin[i] = dm.y * dm.x; } for (uint q = 0u; q < 4u; q++) { // Taps `first + q*32 + 0..3`, four positions each.@@ -117,6 +136,26 @@ void main() { } } }+ if (split > 0u) {+ if (slice > 0u) {+ for (uint i = 0u; i < BLOCK; i++) {+ for (uint j = 0u; j < BLOCK; j++) {+ partial[lid][i * BLOCK + j] = sum[i][j];+ }+ }+ }+ barrier();+ if (slice > 0u || !busy) {+ return;+ }+ for (uint k = 1u; k < (1u << split); k++) {+ for (uint i = 0u; i < BLOCK; i++) {+ for (uint j = 0u; j < BLOCK; j++) {+ sum[i][j] += partial[lid + k * slice_lanes][i * BLOCK + j];+ }+ }+ }+ } for (uint i = 0u; i < BLOCK; i++) { for (uint j = 0u; j < BLOCK; j++) { acc[i][j] = sum[i][j];
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 17abc43d4b..a4b27542ee 100644--- a/library/ml/src/main/rust/src/nets/mod_part9.rs+++ b/library/ml/src/main/rust/src/nets/mod_part9.rs@@ -1,3 +1,7 @@+/// Q2_K GEMMs over at least 2048 taps with fewer 32 x 32 tiles than this split their taps across+/// four lane slices. See `q2k_split` in [`Builder::emit`] and conv_point_q2k.comp.+const Q2K_SPLIT_BELOW: u32 = 64;+ impl<'a> Builder<'a> { fn emit( &self,@@ -115,6 +119,20 @@ impl<'a> Builder<'a> { && (si.c / *group) % 16 == 0 && *weight % 4 == 0 && input_at % 4 == 0;+ // Too few Q2_K tiles to fill the GPU and a long tap loop: split the taps across 4+ // lane slices of a workgroup (`in1` = 2 in conv_point_q2k.comp). Word path only; at+ // 1024 taps the shorter loop no longer pays for the combine.+ let q2k_split = if kind == Kind::ConvPointQ2K+ && si.c % 256 == 0+ && si.c >= 2048+ && positions % 4 == 0+ && input_at % 4 == 0+ && int8_tiles < Q2K_SPLIT_BELOW+ {+ 2+ } else {+ 0+ }; // Workgroups for the staged kinds, output elements for the untiled one. let count = match kind { Kind::ConvVecInt8 | Kind::ConvVecInt4 | Kind::ConvVecQ2K => rows,@@ -122,14 +140,19 @@ impl<'a> Builder<'a> { so.c.div_ceil(CONV_POINT_INT8_TILE / 2) * positions.div_ceil(CONV_POINT_INT8_TILE) } Kind::ConvPointInt4 if int4_wide => so.c.div_ceil(CONV_POINT_INT8_TILE) * positions.div_ceil(64),- Kind::ConvPointInt8 | Kind::ConvPointInt4 | Kind::ConvPointQ2K => int8_tiles,+ Kind::ConvPointQ2K => {+ so.c.div_ceil(CONV_POINT_INT8_TILE >> q2k_split) * positions.div_ceil(CONV_POINT_INT8_TILE)+ }+ Kind::ConvPointInt8 | Kind::ConvPointInt4 => int8_tiles, _ => so.len(), }; ops.push(Op::Dispatch { kind, push: Push { in0: input_at,- in1: if row_gemm || grouped_vec {+ in1: if kind == Kind::ConvPointQ2K {+ q2k_split+ } else if row_gemm || grouped_vec { 2 } else if widened { 3 + u32::from(split)
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 1441d0689f..ec187d7f8b 100644--- a/library/ml/src/main/rust/src/vulkan/parity.rs+++ b/library/ml/src/main/rust/src/vulkan/parity.rs@@ -445,4 +445,5 @@ include!("parity_part5.rs"); include!("parity_part6.rs"); include!("parity_part10.rs"); include!("parity_part7.rs");-include!("parity_part8.rs");\ No newline at end of file+include!("parity_part8.rs");+include!("parity_part11.rs");\ No newline at end of file
library/ml/src/main/rust/src/vulkan/parity_part11.rs
diff --git a/library/ml/src/main/rust/src/vulkan/parity_part11.rs b/library/ml/src/main/rust/src/vulkan/parity_part11.rsnew file mode 100644index 0000000000..421d8e7d5b--- /dev/null+++ b/library/ml/src/main/rust/src/vulkan/parity_part11.rs@@ -0,0 +1,39 @@+// Device parity fixtures (kernels-d: Q2_K GEMM and vision). See `parity.rs` for the helpers.++/// The Q2_K GEMM over the word path with 4 lane slices summing the taps (`in1` 2) and unsplit:+/// ragged channel tiles, a 36-position map (a partial position tile whose idle lanes must still+/// reach the slice barrier), 8192 taps like MADLAD's FFN output projection, and shapes just past+/// the split's limits (64+ tiles, under 2048 taps).+#[test]+#[ignore = "needs a Vulkan device"]+fn q2k_gemm_tap_splits_agree_with_the_reference() {+ for (out_c, in_c, width, in1) in+ [(44u32, 8192u32, 32u32, 2u32), (52, 2048, 36, 2), (2050, 2048, 4, 0), (40, 1024, 36, 0)]+ {+ 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_654_435_761) >> 9) as u8)+ .collect();+ let pairs: Vec<f32> = (0..out_c * blocks * 2).map(|i| 0.04 + 0.01 * ((i * 3) % 7) 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.7)),+ ],+ );+ let weights = Weights::parse(&blob, graph::SUPERTONIC_VE).expect("the fixture blob parses");+ let input = spread((in_c * width) as usize, 0.35);+ let mut builder = Builder::new(&weights);+ let first = builder.input(Shape::new(in_c, 1, width));+ let last = builder.conv_q2k(first, 0, out_c, Act::Relu);+ let plan = builder.finish(&[last]).expect("the q2k gemm plan builds");+ assert!(plan.ops.iter().any(|op| matches!(+ op,+ crate::nets::Op::Dispatch { kind: crate::nets::Kind::ConvPointQ2K, push, .. } if push.in1 == in1+ )));+ let what = format!("a q2k gemm {out_c}x{in_c} over {width}, split {in1}");+ compare(&what, plan, weights.data().to_vec(), &[&input]);+ }+}