From efd4018a4658a5d80b315e76909a611a30eee377 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 14 Oct 2026 15:32:30 +0200 Subject: [PATCH] feat: add experimental pre-converted activation layout, topology helper and paired benchmarks (STRA-211) Adds two EXPERIMENTAL AVX2 MXFP4 kernels that take the activation as f32 scales plus contiguous int8 quants (q8r, q8r4). q8r is tested bit-identical to the ggml-layout kernel; q8r4 against the stated tolerance. Adds Windows core topology and thread pinning (cpu-sys topology module) and three kernel-level benchmarks that interleave variants and report paired ratios. Findings, recorded in docs/experiments/2026-10-14-cpu-kernel-layout-and-pinning.md: the chip has 2 fast cores and 10 slower ones; the new layout was faster for a single thread (paired median 1.32x, 15 pairs) and inconclusive with many threads; thread pinning did not beat the OS default. The machine was not in a controlled state, so these are not accepted performance results. Co-Authored-By: Claude Sonnet 5.5 --- crates/cpu-kernels/examples/bench_mxfp4.rs | 4 +- crates/cpu-kernels/examples/bench_pinning.rs | 162 ++++++++++++++++++ crates/cpu-kernels/examples/bench_variants.rs | 125 ++++++++++++++ crates/cpu-kernels/tests/mxfp4.rs | 57 ++++++ crates/cpu-sys/csrc/leleka_cpu.h | 4 + crates/cpu-sys/csrc/mxfp4_avx2.c | 66 +++++++ crates/cpu-sys/src/lib.rs | 46 +++++ crates/cpu-sys/src/topology.rs | 159 +++++++++++++++++ ...026-10-14-cpu-kernel-layout-and-pinning.md | 61 +++++++ 9 files changed, 682 insertions(+), 2 deletions(-) create mode 100644 crates/cpu-kernels/examples/bench_pinning.rs create mode 100644 crates/cpu-kernels/examples/bench_variants.rs create mode 100644 crates/cpu-sys/src/topology.rs create mode 100644 docs/experiments/2026-10-14-cpu-kernel-layout-and-pinning.md diff --git a/crates/cpu-kernels/examples/bench_mxfp4.rs b/crates/cpu-kernels/examples/bench_mxfp4.rs index 0ea0af58..1fa75a88 100644 --- a/crates/cpu-kernels/examples/bench_mxfp4.rs +++ b/crates/cpu-kernels/examples/bench_mxfp4.rs @@ -30,14 +30,14 @@ fn main() { (state >> 33) as u32 }; let mut weights = vec![0u8; rows * row_bytes]; - for block in weights.chunks_exact_mut(MXFP4) { + for block in weights.as_chunks_mut::().0.iter_mut() { block[0] = 112 + (next() % 16) as u8; for b in &mut block[1..] { *b = next() as u8; } } let mut act = vec![0u8; BLOCKS_PER_ROW * Q8]; - for block in act.chunks_exact_mut(Q8) { + for block in act.as_chunks_mut::().0.iter_mut() { block[..2].copy_from_slice(&0x2C00u16.to_le_bytes()); // 0.0625 for b in &mut block[2..] { *b = ((next() % 255) as i64 - 127) as i8 as u8; diff --git a/crates/cpu-kernels/examples/bench_pinning.rs b/crates/cpu-kernels/examples/bench_pinning.rs new file mode 100644 index 00000000..b4da349f --- /dev/null +++ b/crates/cpu-kernels/examples/bench_pinning.rs @@ -0,0 +1,162 @@ +//! EXPERIMENT: does thread placement on a hybrid CPU change MXFP4 x Q8 kernel throughput? +//! +//! Kernel-level only, never an inference result. Policies are interleaved inside every repeat in a +//! rotating order and compared as paired ratios against "os" (no pinning), because machine state +//! drifts between runs. Windows only. +//! +//! Run: `cargo run --release -p leleka-cpu-kernels --example bench_pinning -- [MiB] [repeats]` + +use leleka_cpu_sys as sys; +use leleka_cpu_sys::topology::{self, Core}; +use std::time::Instant; + +const BLOCKS_PER_ROW: usize = 90; +const MXFP4: usize = 17; + +fn main() { + let args: Vec = std::env::args().collect(); + let mib: usize = args.get(1).and_then(|s| s.parse().ok()).unwrap_or(768); + let repeats: usize = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(11); + let cores = topology::cores(); + if cores.is_empty() { + println!("no topology on this system; nothing to do"); + return; + } + let max_class = cores.iter().map(|c| c.efficiency_class).max().unwrap(); + let fast: Vec<&Core> = cores + .iter() + .filter(|c| c.efficiency_class == max_class) + .collect(); + let slow: Vec<&Core> = cores + .iter() + .filter(|c| c.efficiency_class != max_class) + .collect(); + println!( + "{} cores: {} fast (class {max_class}, {} logical), {} slow", + cores.len(), + fast.len(), + fast.iter() + .map(|c| c.logical_processors().len()) + .sum::(), + slow.len() + ); + + // Orders of logical processors to hand out to worker t, t = 0, 1, 2, ... + let lp = |c: &Core| c.logical_processors(); + let fast_all: Vec = fast.iter().flat_map(|c| lp(c)).collect(); + let fast_first_thread: Vec = fast.iter().map(|c| lp(c)[0]).collect(); + let fast_second_thread: Vec = fast + .iter() + .flat_map(|c| lp(c).into_iter().skip(1)) + .collect(); + let slow_all: Vec = slow.iter().flat_map(|c| lp(c)).collect(); + let policies: Vec<(&str, Option>)> = vec![ + ("os (no pinning)", None), + ( + "fast first, both SMT, then slow", + Some([fast_all.clone(), slow_all.clone()].concat()), + ), + ( + "fast 1 thread/core, then slow, then SMT siblings", + Some( + [ + fast_first_thread.clone(), + slow_all.clone(), + fast_second_thread.clone(), + ] + .concat(), + ), + ), + ("slow cores only", Some(slow_all.clone())), + ]; + + let row_bytes = BLOCKS_PER_ROW * MXFP4; + let rows = (mib << 20) / row_bytes; + let mut state = 0x1234_5678_9ABC_DEF0u64; + let mut next = move || { + state = state + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407); + (state >> 33) as u32 + }; + let mut weights = vec![0u8; rows * row_bytes]; + for block in weights.as_chunks_mut::().0.iter_mut() { + block[0] = 112 + (next() % 16) as u8; + for b in &mut block[1..] { + *b = next() as u8; + } + } + let ys = vec![0.0625f32; BLOCKS_PER_ROW]; + let yq: Vec = (0..BLOCKS_PER_ROW * 32) + .map(|_| ((next() % 255) as i64 - 127) as i8) + .collect(); + + println!( + "buffer {} MiB; {repeats} interleaved repeats; kernel q8r4 avx2", + weights.len() >> 20 + ); + for threads in [2usize, 4, 6, 8, 10, 12] { + let mut samples: Vec> = vec![Vec::new(); policies.len()]; + for rep in 0..repeats { + for k in 0..policies.len() { + let idx = (k + rep) % policies.len(); + let order = &policies[idx].1; + if order.as_ref().is_some_and(|o| o.len() < threads) { + continue; + } + let start = Instant::now(); + std::thread::scope(|s| { + let per = rows.div_ceil(threads); + for t in 0..threads { + let (w, ys, yq) = (&weights, &ys, &yq); + let pin = order.as_ref().map(|o| 1usize << o[t]); + s.spawn(move || { + if let Some(mask) = pin { + topology::pin_current_thread(mask); + } + let (lo, hi) = (t * per, ((t + 1) * per).min(rows)); + let mut acc = 0f32; + for r in lo..hi { + acc += sys::dot_mxfp4_q8r4_avx2( + &w[r * row_bytes..(r + 1) * row_bytes], + ys, + yq, + ) + .unwrap(); + } + std::hint::black_box(acc); + }); + } + }); + samples[idx].push(weights.len() as f64 / start.elapsed().as_secs_f64() / 1e9); + } + } + println!("-- {threads} threads"); + println!( + "{:<52} median GB/s paired ratio vs os: median [min .. max]", + "policy" + ); + for (i, (name, _)) in policies.iter().enumerate() { + if samples[i].len() < 3 { + println!("{name:<52} (not enough logical processors in this set)"); + continue; + } + let mut s = samples[i].clone(); + s.sort_by(|a, b| a.total_cmp(b)); + let mut ratios: Vec = samples[i] + .iter() + .zip(&samples[0]) + .map(|(a, b)| a / b) + .collect(); + ratios.sort_by(|a, b| a.total_cmp(b)); + println!( + "{:<52} {:>11.1} {:>6.3} [{:.3} .. {:.3}]", + name, + s[s.len() / 2], + ratios[ratios.len() / 2], + ratios[0], + ratios[ratios.len() - 1] + ); + } + } +} diff --git a/crates/cpu-kernels/examples/bench_variants.rs b/crates/cpu-kernels/examples/bench_variants.rs new file mode 100644 index 00000000..91988ebb --- /dev/null +++ b/crates/cpu-kernels/examples/bench_variants.rs @@ -0,0 +1,125 @@ +//! EXPERIMENT: paired comparison of MXFP4 x Q8 kernel variants on identical data. +//! +//! Single-kernel throughput only, never an inference result. Machine state drifts between runs +//! (power, thermals, other load), so variants are interleaved inside every repeat in a rotating order +//! and compared as PAIRED ratios against the first variant, not as absolute numbers from separate runs. +//! +//! Run: `cargo run --release -p leleka-cpu-kernels --example bench_variants -- [MiB] [repeats]` + +use leleka_cpu_sys as sys; +use std::time::Instant; + +const BLOCKS_PER_ROW: usize = 90; +const MXFP4: usize = 17; +const Q8: usize = 34; + +type Kernel<'a> = Box f32 + Sync + 'a>; + +fn main() { + let args: Vec = std::env::args().collect(); + let mib: usize = args.get(1).and_then(|s| s.parse().ok()).unwrap_or(768); + let repeats: usize = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(15); + let row_bytes = BLOCKS_PER_ROW * MXFP4; + let rows = (mib << 20) / row_bytes; + + let mut state = 0x1234_5678_9ABC_DEF0u64; + let mut next = move || { + state = state + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407); + (state >> 33) as u32 + }; + let mut weights = vec![0u8; rows * row_bytes]; + for block in weights.as_chunks_mut::().0.iter_mut() { + block[0] = 112 + (next() % 16) as u8; + for b in &mut block[1..] { + *b = next() as u8; + } + } + let mut act = vec![0u8; BLOCKS_PER_ROW * Q8]; + for block in act.as_chunks_mut::().0.iter_mut() { + block[..2].copy_from_slice(&0x2C00u16.to_le_bytes()); // 0.0625 + for b in &mut block[2..] { + *b = ((next() % 255) as i64 - 127) as i8 as u8; + } + } + let ys = vec![0.0625f32; BLOCKS_PER_ROW]; + let yq: Vec = act + .as_chunks::() + .0 + .iter() + .flat_map(|b| b[2..].iter().map(|v| *v as i8)) + .collect(); + + let kernels: Vec<(&str, Kernel)> = vec![ + ( + "ggml-layout avx2 (baseline)", + Box::new(|r| sys::dot_mxfp4_q8_0_avx2(r, &act).unwrap()), + ), + ( + "q8r avx2, 2 acc", + Box::new(|r| sys::dot_mxfp4_q8r_avx2(r, &ys, &yq).unwrap()), + ), + ( + "q8r4 avx2, 4 acc", + Box::new(|r| sys::dot_mxfp4_q8r4_avx2(r, &ys, &yq).unwrap()), + ), + ( + "ggml-layout avx-vnni", + Box::new(|r| sys::dot_mxfp4_q8_0_avxvnni(r, &act).unwrap()), + ), + ]; + + println!( + "buffer {} MiB = {rows} rows; {repeats} interleaved repeats; ratios are paired against the baseline", + weights.len() >> 20 + ); + for threads in [1usize, 4, 8, 10] { + let mut samples: Vec> = vec![Vec::new(); kernels.len()]; + for rep in 0..repeats { + for k in 0..kernels.len() { + let idx = (k + rep) % kernels.len(); // rotate the order each repeat + let kernel = &kernels[idx].1; + let start = Instant::now(); + std::thread::scope(|s| { + let per = rows.div_ceil(threads); + for t in 0..threads { + let w = &weights; + s.spawn(move || { + let (lo, hi) = (t * per, ((t + 1) * per).min(rows)); + let mut acc = 0f32; + for r in lo..hi { + acc += kernel(&w[r * row_bytes..(r + 1) * row_bytes]); + } + std::hint::black_box(acc); + }); + } + }); + samples[idx].push(weights.len() as f64 / start.elapsed().as_secs_f64() / 1e9); + } + } + println!("-- {threads} thread(s)"); + println!( + "{:<30} median GB/s paired ratio median [min .. max]", + "variant" + ); + for (i, (name, _)) in kernels.iter().enumerate() { + let mut s = samples[i].clone(); + s.sort_by(|a, b| a.total_cmp(b)); + let mut ratios: Vec = samples[i] + .iter() + .zip(&samples[0]) + .map(|(a, b)| a / b) + .collect(); + ratios.sort_by(|a, b| a.total_cmp(b)); + println!( + "{:<30} {:>11.1} {:>6.3} [{:.3} .. {:.3}]", + name, + s[s.len() / 2], + ratios[ratios.len() / 2], + ratios[0], + ratios[ratios.len() - 1] + ); + } + } +} diff --git a/crates/cpu-kernels/tests/mxfp4.rs b/crates/cpu-kernels/tests/mxfp4.rs index cc6119d4..3107b32b 100644 --- a/crates/cpu-kernels/tests/mxfp4.rs +++ b/crates/cpu-kernels/tests/mxfp4.rs @@ -233,6 +233,63 @@ fn unaligned_operands_give_the_same_answer() { } } +/// The EXPERIMENTAL "q8r" activation layout (f32 scales, contiguous int8) must give the same maths as +/// the ggml-layout kernels: `q8r` has the same accumulation structure as the ggml-layout AVX2 kernel, +/// so it must be bit-identical to it; `q8r4` sums in another order, so it must meet the tolerance. +#[cfg(target_arch = "x86_64")] +#[test] +fn experimental_q8r_layout_matches_the_ggml_layout_kernel() { + if !leleka_cpu_sys::avx2_available() { + return; + } + let mut rng = Lcg(0xFACE); + for blocks in BLOCK_COUNTS { + for (name, (x, y)) in [ + ("realistic", realistic(&mut rng, blocks)), + ("raw", raw(&mut rng, blocks)), + ] { + let (ys, yq) = split_q8(&y); + let ggml_layout = leleka_cpu_sys::dot_mxfp4_q8_0_avx2(&x, &y).unwrap(); + let r = leleka_cpu_sys::dot_mxfp4_q8r_avx2(&x, &ys, &yq).unwrap(); + assert_eq!( + r.to_bits(), + ggml_layout.to_bits(), + "q8r {name} blocks {blocks}" + ); + let (expected, abs_sum) = reference(&x, &y); + let r4 = f64::from(leleka_cpu_sys::dot_mxfp4_q8r4_avx2(&x, &ys, &yq).unwrap()); + assert!( + (r4 - expected).abs() <= tolerance(blocks, abs_sum), + "q8r4 {name} blocks {blocks}: got {r4}, expected {expected}" + ); + } + } + // Shape errors. + assert_eq!( + leleka_cpu_sys::dot_mxfp4_q8r_avx2(&[0; 17], &[1.0], &[0; 31]), + Err(KernelError::LengthMismatch) + ); + assert_eq!( + leleka_cpu_sys::dot_mxfp4_q8r4_avx2(&[0; 16], &[1.0], &[0; 32]), + Err(KernelError::LengthMismatch) + ); +} + +/// Split ggml Q8_0 blocks into f32 scales (converted by ggml itself) and contiguous int8 quants. +fn split_q8(y: &[u8]) -> (Vec, Vec) { + let mut scales = Vec::new(); + let mut quants = Vec::new(); + let (blocks, _) = y.as_chunks::(); + for block in blocks { + let mut probe = block.to_vec(); + probe[2..].fill(0); + probe[2] = 1; // one quant of value 1: the dequantized element is exactly the scale + scales.push(oracle::dequantize_q8_0(&probe)[0]); + quants.extend(block[2..].iter().map(|v| *v as i8)); + } + (scales, quants) +} + #[test] fn bad_shapes_are_refused_at_every_level() { for d in levels() { diff --git a/crates/cpu-sys/csrc/leleka_cpu.h b/crates/cpu-sys/csrc/leleka_cpu.h index 42536d75..a4c0d0cf 100644 --- a/crates/cpu-sys/csrc/leleka_cpu.h +++ b/crates/cpu-sys/csrc/leleka_cpu.h @@ -59,6 +59,10 @@ void leleka_mxfp4_q8_0_isums_scalar(const uint8_t *x, const uint8_t *y, size_t n #if defined(__x86_64__) || defined(_M_X64) /* AVX2 level = AVX2 + FMA + F16C. Callers must have verified all three. */ float leleka_dot_mxfp4_q8_0_avx2(const uint8_t *x, const uint8_t *y, size_t nb); +/* EXPERIMENTAL activation layout "q8r": f32 scales ys[nb] (already converted from the half scales) + * and contiguous int8 quants yq[nb * 32]. Same maths as the ggml-layout kernel above. */ +float leleka_dot_mxfp4_q8r_avx2(const uint8_t *x, const float *ys, const int8_t *yq, size_t nb); +float leleka_dot_mxfp4_q8r4_avx2(const uint8_t *x, const float *ys, const int8_t *yq, size_t nb); void leleka_mxfp4_q8_0_isums_avx2(const uint8_t *x, const uint8_t *y, size_t nb, int32_t *out); /* Callers must have verified AVX2, FMA, F16C and AVX-VNNI. */ float leleka_dot_mxfp4_q8_0_avxvnni(const uint8_t *x, const uint8_t *y, size_t nb); diff --git a/crates/cpu-sys/csrc/mxfp4_avx2.c b/crates/cpu-sys/csrc/mxfp4_avx2.c index 68e84eb6..73c42ce1 100644 --- a/crates/cpu-sys/csrc/mxfp4_avx2.c +++ b/crates/cpu-sys/csrc/mxfp4_avx2.c @@ -75,3 +75,69 @@ void leleka_mxfp4_q8_0_isums_avx2(const uint8_t *x, const uint8_t *y, size_t nb, out[ib] = hsum_epi32(block_p32(x + ib * LELEKA_MXFP4_BLOCK_BYTES, y + ib * LELEKA_Q8_0_BLOCK_BYTES, table, low_mask, ones)); } } + +/* ---- Leleka activation layout ("q8r"): scales already converted to f32, quants contiguous. ----- + * The activation row is reused by thousands of weight rows, so converting its half scales once, when + * the row is quantized, removes the per-row-per-block half-to-float work from the hot loop. The scale + * VALUES are the same f32 numbers the ggml layout would convert to, so results match the ggml-layout + * kernel above up to the accumulation structure (identical here: two accumulators, even/odd blocks). */ +static inline __m256i block_p32_r(const uint8_t *x, const int8_t *yq, __m256i table, __m128i low_mask, __m256i ones) { + __m128i bits = _mm_loadu_si128((const __m128i *)(x + 1)); + __m128i lo = _mm_and_si128(bits, low_mask); + __m128i hi = _mm_and_si128(_mm_srli_epi16(bits, 4), low_mask); + __m256i q4 = _mm256_shuffle_epi8(table, _mm256_set_m128i(hi, lo)); + __m256i q8 = _mm256_loadu_si256((const __m256i *)yq); + __m256i p16 = _mm256_maddubs_epi16(_mm256_sign_epi8(q4, q4), _mm256_sign_epi8(q8, q4)); + return _mm256_madd_epi16(p16, ones); +} + +float leleka_dot_mxfp4_q8r_avx2(const uint8_t *x, const float *ys, const int8_t *yq, size_t nb) { + const __m128i table128 = _mm_loadu_si128((const __m128i *)LELEKA_KVALUES_MXFP4); + const __m256i table = _mm256_set_m128i(table128, table128); + const __m128i low_mask = _mm_set1_epi8(0x0F); + const __m256i ones = _mm256_set1_epi16(1); + __m256 acc0 = _mm256_setzero_ps(), acc1 = _mm256_setzero_ps(); + size_t ib = 0; + for (; ib + 2 <= nb; ib += 2) { + const uint8_t *x0 = x + ib * LELEKA_MXFP4_BLOCK_BYTES; + const uint8_t *x1 = x0 + LELEKA_MXFP4_BLOCK_BYTES; + __m256i p0 = block_p32_r(x0, yq + ib * 32, table, low_mask, ones); + __m256i p1 = block_p32_r(x1, yq + ib * 32 + 32, table, low_mask, ones); + acc0 = _mm256_fmadd_ps(_mm256_cvtepi32_ps(p0), _mm256_set1_ps(ys[ib] * leleka_e8m0_half(x0[0])), acc0); + acc1 = _mm256_fmadd_ps(_mm256_cvtepi32_ps(p1), _mm256_set1_ps(ys[ib + 1] * leleka_e8m0_half(x1[0])), acc1); + } + for (; ib < nb; ib++) { + const uint8_t *xb = x + ib * LELEKA_MXFP4_BLOCK_BYTES; + __m256i p = block_p32_r(xb, yq + ib * 32, table, low_mask, ones); + acc0 = _mm256_fmadd_ps(_mm256_cvtepi32_ps(p), _mm256_set1_ps(ys[ib] * leleka_e8m0_half(xb[0])), acc0); + } + return hsum_ps(_mm256_add_ps(acc0, acc1)); +} + +/* Four blocks per iteration with four accumulators: more independent work per loop trip. */ +float leleka_dot_mxfp4_q8r4_avx2(const uint8_t *x, const float *ys, const int8_t *yq, size_t nb) { + const __m128i table128 = _mm_loadu_si128((const __m128i *)LELEKA_KVALUES_MXFP4); + const __m256i table = _mm256_set_m128i(table128, table128); + const __m128i low_mask = _mm_set1_epi8(0x0F); + const __m256i ones = _mm256_set1_epi16(1); + __m256 a0 = _mm256_setzero_ps(), a1 = a0, a2 = a0, a3 = a0; + size_t ib = 0; + for (; ib + 4 <= nb; ib += 4) { + const uint8_t *xb = x + ib * LELEKA_MXFP4_BLOCK_BYTES; + const int8_t *q = yq + ib * 32; + __m256i p0 = block_p32_r(xb, q, table, low_mask, ones); + __m256i p1 = block_p32_r(xb + 17, q + 32, table, low_mask, ones); + __m256i p2 = block_p32_r(xb + 34, q + 64, table, low_mask, ones); + __m256i p3 = block_p32_r(xb + 51, q + 96, table, low_mask, ones); + a0 = _mm256_fmadd_ps(_mm256_cvtepi32_ps(p0), _mm256_set1_ps(ys[ib] * leleka_e8m0_half(xb[0])), a0); + a1 = _mm256_fmadd_ps(_mm256_cvtepi32_ps(p1), _mm256_set1_ps(ys[ib + 1] * leleka_e8m0_half(xb[17])), a1); + a2 = _mm256_fmadd_ps(_mm256_cvtepi32_ps(p2), _mm256_set1_ps(ys[ib + 2] * leleka_e8m0_half(xb[34])), a2); + a3 = _mm256_fmadd_ps(_mm256_cvtepi32_ps(p3), _mm256_set1_ps(ys[ib + 3] * leleka_e8m0_half(xb[51])), a3); + } + for (; ib < nb; ib++) { + const uint8_t *xb = x + ib * LELEKA_MXFP4_BLOCK_BYTES; + __m256i p = block_p32_r(xb, yq + ib * 32, table, low_mask, ones); + a0 = _mm256_fmadd_ps(_mm256_cvtepi32_ps(p), _mm256_set1_ps(ys[ib] * leleka_e8m0_half(xb[0])), a0); + } + return hsum_ps(_mm256_add_ps(_mm256_add_ps(a0, a1), _mm256_add_ps(a2, a3))); +} diff --git a/crates/cpu-sys/src/lib.rs b/crates/cpu-sys/src/lib.rs index fcb6f047..e67d2eed 100644 --- a/crates/cpu-sys/src/lib.rs +++ b/crates/cpu-sys/src/lib.rs @@ -9,6 +9,8 @@ use std::fmt; +pub mod topology; + /// ABI version this crate was written against; compared with the C library at run time. pub const ABI_VERSION: u32 = 2; /// Longest vector the int32 accumulators can hold exactly (`131072 * 128 * 127 < 2^31`). @@ -29,6 +31,20 @@ mod ffi { pub fn leleka_dot_mxfp4_q8_0_avx2(x: *const u8, y: *const u8, nb: usize) -> f32; #[cfg(target_arch = "x86_64")] pub fn leleka_mxfp4_q8_0_isums_avx2(x: *const u8, y: *const u8, nb: usize, out: *mut i32); + #[cfg(target_arch = "x86_64")] + pub fn leleka_dot_mxfp4_q8r_avx2( + x: *const u8, + ys: *const f32, + yq: *const i8, + nb: usize, + ) -> f32; + #[cfg(target_arch = "x86_64")] + pub fn leleka_dot_mxfp4_q8r4_avx2( + x: *const u8, + ys: *const f32, + yq: *const i8, + nb: usize, + ) -> f32; #[cfg(all(target_arch = "x86_64", leleka_avxvnni))] pub fn leleka_dot_mxfp4_q8_0_avxvnni(x: *const u8, y: *const u8, nb: usize) -> f32; #[cfg(all(target_arch = "x86_64", leleka_avxvnni))] @@ -192,6 +208,36 @@ pub fn mxfp4_q8_0_isums_avx2(x: &[u8], y: &[u8], out: &mut [i32]) -> Result<(), Ok(()) } +fn check_q8r(x: &[u8], ys: &[f32], yq: &[i8]) -> Result { + let blocks = ys.len(); + if yq.len() != blocks * BLOCK_ELEMS || x.len() != blocks * MXFP4_BLOCK_BYTES { + return Err(KernelError::LengthMismatch); + } + Ok(blocks) +} + +/// EXPERIMENTAL: AVX2 dot with the "q8r" activation layout (f32 scales, contiguous int8 quants). +#[cfg(target_arch = "x86_64")] +pub fn dot_mxfp4_q8r_avx2(x: &[u8], ys: &[f32], yq: &[i8]) -> Result { + let blocks = check_q8r(x, ys, yq)?; + if !avx2_available() { + return Err(KernelError::Unsupported); + } + // SAFETY: sizes checked; AVX2, FMA and F16C verified just above. + Ok(unsafe { ffi::leleka_dot_mxfp4_q8r_avx2(x.as_ptr(), ys.as_ptr(), yq.as_ptr(), blocks) }) +} + +/// EXPERIMENTAL: as [`dot_mxfp4_q8r_avx2`] with four blocks and four accumulators per iteration. +#[cfg(target_arch = "x86_64")] +pub fn dot_mxfp4_q8r4_avx2(x: &[u8], ys: &[f32], yq: &[i8]) -> Result { + let blocks = check_q8r(x, ys, yq)?; + if !avx2_available() { + return Err(KernelError::Unsupported); + } + // SAFETY: sizes checked; AVX2, FMA and F16C verified just above. + Ok(unsafe { ffi::leleka_dot_mxfp4_q8r4_avx2(x.as_ptr(), ys.as_ptr(), yq.as_ptr(), blocks) }) +} + /// AVX-VNNI level of [`dot_mxfp4_q8_0_scalar`]; equal within float summation order. #[cfg(target_arch = "x86_64")] pub fn dot_mxfp4_q8_0_avxvnni(x: &[u8], y: &[u8]) -> Result { diff --git a/crates/cpu-sys/src/topology.rs b/crates/cpu-sys/src/topology.rs new file mode 100644 index 00000000..16197f72 --- /dev/null +++ b/crates/cpu-sys/src/topology.rs @@ -0,0 +1,159 @@ +//! CPU core types and thread pinning (Windows; other systems report no topology and refuse to pin). +//! +//! Hybrid CPUs mix fast and slow cores, and the OS decides where threads run. A memory-bound kernel +//! can lose a lot on the slow cores or from migration, so the runtime needs to see the topology and +//! be able to choose. Only processor group 0 (at most 64 logical processors) is handled. + +/// One physical core. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Core { + /// Windows efficiency class: a higher number is a faster core type (relative on this machine). + pub efficiency_class: u8, + /// Whether the core runs two hardware threads. + pub smt: bool, + /// Affinity mask of this core's logical processors within group 0. + pub mask: usize, +} + +impl Core { + /// Logical processor indices of this core, lowest first. + pub fn logical_processors(&self) -> Vec { + (0..usize::BITS as usize) + .filter(|bit| self.mask >> bit & 1 == 1) + .collect() + } +} + +#[cfg(windows)] +mod imp { + use super::Core; + + unsafe extern "system" { + fn GetLogicalProcessorInformationEx( + relationship: u32, + buffer: *mut u8, + length: *mut u32, + ) -> i32; + fn GetCurrentThread() -> isize; + fn SetThreadAffinityMask(thread: isize, mask: usize) -> usize; + } + + const RELATION_PROCESSOR_CORE: u32 = 0; + const LTP_PC_SMT: u8 = 1; + + pub fn cores() -> Vec { + let mut length: u32 = 0; + // SAFETY: a null buffer with length 0 asks for the required size. + unsafe { + GetLogicalProcessorInformationEx( + RELATION_PROCESSOR_CORE, + std::ptr::null_mut(), + &mut length, + ) + }; + if length == 0 { + return Vec::new(); + } + let mut buffer = vec![0u8; length as usize]; + // SAFETY: `buffer` holds `length` writable bytes. + let ok = unsafe { + GetLogicalProcessorInformationEx( + RELATION_PROCESSOR_CORE, + buffer.as_mut_ptr(), + &mut length, + ) + }; + if ok == 0 { + return Vec::new(); + } + let mut cores = Vec::new(); + let mut offset = 0usize; + while offset + 32 <= length as usize { + let size = + u32::from_le_bytes(buffer[offset + 4..offset + 8].try_into().unwrap()) as usize; + if size < 48 || offset + size > length as usize { + break; + } + let flags = buffer[offset + 8]; + let efficiency_class = buffer[offset + 9]; + let groups = + u16::from_le_bytes(buffer[offset + 30..offset + 32].try_into().unwrap()) as usize; + let mut mask = 0usize; + for g in 0..groups { + let base = offset + 32 + g * 16; + if base + 10 > offset + size { + break; + } + let group = u16::from_le_bytes(buffer[base + 8..base + 10].try_into().unwrap()); + if group == 0 { + mask |= usize::from_le_bytes(buffer[base..base + 8].try_into().unwrap()); + } + } + if mask != 0 { + cores.push(Core { + efficiency_class, + smt: flags & LTP_PC_SMT != 0, + mask, + }); + } + offset += size; + } + cores + } + + pub fn pin_current_thread(mask: usize) -> bool { + if mask == 0 { + return false; + } + // SAFETY: both functions only act on the calling thread; a zero return means failure. + unsafe { SetThreadAffinityMask(GetCurrentThread(), mask) != 0 } + } +} + +#[cfg(not(windows))] +mod imp { + use super::Core; + + pub fn cores() -> Vec { + Vec::new() + } + + pub fn pin_current_thread(_mask: usize) -> bool { + false + } +} + +/// The physical cores of processor group 0, in the order the OS reports them; empty if unknown. +pub fn cores() -> Vec { + imp::cores() +} + +/// Restrict the calling thread to the logical processors in `mask`; `false` if not possible. +pub fn pin_current_thread(mask: usize) -> bool { + imp::pin_current_thread(mask) +} + +#[cfg(all(test, windows))] +mod tests { + use super::*; + + #[test] + fn topology_is_consistent_and_pinning_works() { + let cores = cores(); + assert!(!cores.is_empty()); + let mut seen = 0usize; + for core in &cores { + assert_eq!( + seen & core.mask, + 0, + "logical processors must not be shared between cores" + ); + seen |= core.mask; + assert_eq!(core.smt, core.logical_processors().len() > 1); + } + // Pin to the first logical processor of the first core, and back to everything. + let first = cores[0].logical_processors()[0]; + assert!(pin_current_thread(1 << first)); + assert!(pin_current_thread(seen)); + } +} diff --git a/docs/experiments/2026-10-14-cpu-kernel-layout-and-pinning.md b/docs/experiments/2026-10-14-cpu-kernel-layout-and-pinning.md new file mode 100644 index 00000000..5e83d3b7 --- /dev/null +++ b/docs/experiments/2026-10-14-cpu-kernel-layout-and-pinning.md @@ -0,0 +1,61 @@ +# CPU kernel experiments: activation layout and thread pinning (STRA-211, STRA-214 input) + +**Status:** exploratory. Kernel-level numbers only. No inference was run, no claim about tokens per second, and the +machine was not in a controlled state, so nothing here is an accepted performance result (charter 4.3/4.4, Gate D). + +## Setup + +- Machine: reference laptop `RHW-WIN-265U-NPU r1` (Core Ultra 7 265U, one DDR5 module). The drift fields of that record + were NOT re-captured for these runs, and the OS was running its normal desktop load (browsers, security agent), so the + record's benchmark pre-conditions are not met. +- Software: Windows 11 build 26100, MSVC 19.50.35717 (`/O2 /arch:AVX2`), Rust 1.99.0, code of commit `164bfa6` plus the + experimental functions in this change. +- Data: 767 MiB of pseudo-random MXFP4 weights (526,344 rows of 90 blocks, the gpt-oss-20b hidden size 2880) and one + Q8_0 activation row. Weight bytes read per second are reported. Free RAM about 7.7 GB. +- Method: variants are interleaved inside every repeat in a rotating order and compared as **paired ratios** against the + first variant, because the absolute speed of the same kernel changed by almost 2x between runs. + +## Core topology (observed) + +12 physical cores: 2 of the faster efficiency class (4 logical threads with SMT) and 10 of the slower class (8 E-cores and +2 low-power E-cores, no SMT). A run with 8 to 10 threads therefore uses mostly the slower cores. + +## Results + +Raw memory read bandwidth, measured twice with a plain C streaming program, was stable: about 36 GB/s at 10 or more +threads (36.3 first, 36.5 second). + +| Run | Kernel | threads 1 / 4 / 8 / 10 (best GB/s) | +| --- | --- | --- | +| first (`bench_mxfp4`, 7 repeats, sequential) | AVX-VNNI ggml layout | 5.2 / 18.2 / 27.5 / 28.1 | +| first | AVX2 ggml layout | 5.5 / 16.5 / 25.8 / 27.7 | +| second (`bench_variants`, 15 interleaved repeats, medians) | AVX2 ggml layout | 5.8 / 12.2 / 12.4 / 13.7 | + +The same AVX2 kernel measured 27.7 GB/s in the first run and 13.7 GB/s in the second at 10 threads, with raw memory +bandwidth unchanged. The cause is unknown (candidates: scheduler placement on the slower cores, power state, background +load). Absolute kernel numbers from these runs must not be quoted. + +Paired ratios against the ggml-layout AVX2 kernel (median [min .. max] of 15 pairs): + +| Variant | 1 thread | 4 threads | 8 threads | 10 threads | +| --- | --- | --- | --- | --- | +| q8r: f32 scales pre-converted, 2 accumulators | 1.255 [0.74 .. 1.39] | 1.135 [0.95 .. 1.26] | 1.088 [1.00 .. 1.49] | 1.035 [0.75 .. 2.99] | +| q8r4: same layout, 4 blocks and 4 accumulators per iteration | 1.316 [1.06 .. 1.41] | 1.130 [0.96 .. 1.28] | 1.127 [0.88 .. 1.38] | 1.061 [0.78 .. 2.88] | +| AVX-VNNI, ggml layout | 1.036 [0.79 .. 1.20] | 1.040 [0.95 .. 1.18] | 1.075 [0.82 .. 1.33] | 1.034 [0.83 .. 2.83] | + +Thread pinning (kernel q8r4, 11 interleaved repeats, ratio against no pinning, medians): pinning the fast cores first, +one thread per fast core first, or the slow cores only gave 0.78 to 1.07 at 2 to 12 threads, with ranges as wide as +0.47 to 1.66. No pinning policy beat the OS default. + +## What can and cannot be said + +- Single thread: the pre-converted layout with four accumulators was faster in all 15 pairs (1.06 to 1.41, median 1.32). + The per-thread kernel is compute-bound, so this is plausible, and it is the only effect that survives the noise. +- Many threads: medians of 1.03 to 1.13 with ranges that include slowdowns; **inconclusive**, and expected, since the + workload is then limited by memory bandwidth. +- Pinning: **no benefit found**; recorded as a negative result for this machine state. +- A proper decision needs the controlled conditions of the reference record: quiet machine, power plan and mode recorded, + soak, repeated pairs, and the drift capture. + +Experimental code: `leleka_dot_mxfp4_q8r_avx2` and `leleka_dot_mxfp4_q8r4_avx2` (tested for bit identity with the ggml-layout +kernel, and for the stated tolerance), `crates/cpu-sys/src/topology.rs`, and the three `bench_*` examples.