Files
leleka/crates/cpu-kernels/examples/bench_pinning.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 efd4018a46 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 <noreply@anthropic.com>
2026-10-14 15:32:30 +02:00

163 lines
6.0 KiB
Rust

//! 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<String> = 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::<usize>(),
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<usize> = fast.iter().flat_map(|c| lp(c)).collect();
let fast_first_thread: Vec<usize> = fast.iter().map(|c| lp(c)[0]).collect();
let fast_second_thread: Vec<usize> = fast
.iter()
.flat_map(|c| lp(c).into_iter().skip(1))
.collect();
let slow_all: Vec<usize> = slow.iter().flat_map(|c| lp(c)).collect();
let policies: Vec<(&str, Option<Vec<usize>>)> = 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::<MXFP4>().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<i8> = (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<f64>> = 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<f64> = 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]
);
}
}
}