Profiling the speculative verification pass (batch_cost, position 900) showed its extra cost is compute in the int8 weight products, not expert bytes: distinct experts per layer rise only from 4 to 9.5 at 9 tokens, while the Q8_0 projections, whose weights every token shares, cost 3.6-4x a single step. Each (row, token) dot redid the MXFP4 decode and scale work. cpu-sys gains multi-activation kernels (portable, AVX2, AVX-VNNI) for MXFP4 and Q8_0 rows: the row is decoded once per 64-block segment and up to 16 activations run over it with exactly the one-token kernel's accumulators and final reduction, so every output is bit for bit the one-token kernel's (tests/multi.rs: every level, 1-16 activations, 13 row lengths). run_region uses them for jobs with two or more activations (speculative batches and prefill chunks); one-token decode keeps its kernel. A new synthetic test checks a 20-token batch at every level against feeding tokens one at a time. Model::set_multi_activation(false) restores the per-token path for paired measurements; Profile counts the expert sets read. batch_cost gains a per-size phase breakdown and an `ab` mode that runs every pass without and with the new kernels back to back and checks the logits are identical. Paired, 9 rounds, real model: identical logits in all 90 paired passes; time ratio with/without 1.01 (1 token), 0.98, 0.92, 0.90, 0.83, 0.81, 0.77, 0.79, 0.76 (2..9 tokens). MEASURED_COST becomes 0.737 + 0.421 n (was 0.30 + 0.631 n). ab_speculation (3 pairs, outputs identical in all 24 runs) gave 1.34 / 1.04 / 0.97 / 0.94, within the pair-to-pair spread of the run before the change; replaying the outputs through the drafter predicts 1.59 / 1.15 / 1.00 / 0.99, so the serving loop loses time the pass-cost model does not see. Prefill also uses the kernels (bit-identical); its speed was not measured. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
218 lines
7.4 KiB
Rust
218 lines
7.4 KiB
Rust
//! EXPERIMENT: paired comparison of the register-tiled and multi-activation MXFP4 kernels with the one-row kernel.
|
|
//!
|
|
//! Two regimes: ACTS=1 (decode: memory-bound, every weight byte used once) and ACTS=8 (prefill: each
|
|
//! weight row is used against 8 activations, so compute matters). Variants are interleaved inside every
|
|
//! repeat in a rotating order and compared as paired ratios against the first variant. Kernel
|
|
//! throughput only, never an inference result.
|
|
//!
|
|
//! Run: `cargo run --release -p leleka-cpu-kernels --example bench_tiles -- [MiB] [repeats] [acts]`
|
|
|
|
use leleka_cpu_sys as sys;
|
|
use std::time::Instant;
|
|
|
|
const BLOCKS_PER_ROW: usize = 90;
|
|
const MXFP4: usize = 17;
|
|
|
|
struct Acts {
|
|
ys: Vec<Vec<f32>>,
|
|
yq: Vec<Vec<i8>>,
|
|
prepared: Vec<sys::PreparedAct>,
|
|
}
|
|
|
|
/// Processes weight rows `lo..hi` against all activations; returns a checksum.
|
|
type Variant<'a> = Box<dyn Fn(&[u8], usize, usize, &Acts) -> f32 + Sync + 'a>;
|
|
|
|
fn one_row_loop(vnni: bool) -> Variant<'static> {
|
|
Box::new(move |w, lo, hi, acts| {
|
|
let mut sum = 0f32;
|
|
for r in lo..hi {
|
|
let row = &w[r * BLOCKS_PER_ROW * MXFP4..(r + 1) * BLOCKS_PER_ROW * MXFP4];
|
|
for a in 0..acts.ys.len() {
|
|
sum += if vnni {
|
|
sys::dot_mxfp4_q8r4_avxvnni(row, &acts.ys[a], &acts.yq[a]).unwrap()
|
|
} else {
|
|
sys::dot_mxfp4_q8r4_avx2(row, &acts.ys[a], &acts.yq[a]).unwrap()
|
|
};
|
|
}
|
|
}
|
|
sum
|
|
})
|
|
}
|
|
|
|
fn multi(vnni: bool) -> Variant<'static> {
|
|
Box::new(move |w, lo, hi, acts| {
|
|
let mut sum = 0f32;
|
|
let rb = BLOCKS_PER_ROW * MXFP4;
|
|
let refs: Vec<sys::Q8rRef> = acts
|
|
.ys
|
|
.iter()
|
|
.zip(&acts.yq)
|
|
.map(|(scales, quants)| sys::Q8rRef { scales, quants })
|
|
.collect();
|
|
let mut out = vec![0f32; refs.len()];
|
|
for r in lo..hi {
|
|
let row = &w[r * rb..(r + 1) * rb];
|
|
for (group, o) in refs
|
|
.chunks(sys::MULTI_MAX)
|
|
.zip(out.chunks_mut(sys::MULTI_MAX))
|
|
{
|
|
if vnni {
|
|
sys::dot_mxfp4_q8r4_multi_avxvnni(row, group, o).unwrap();
|
|
} else {
|
|
sys::dot_mxfp4_q8r4_multi_avx2(row, group, o).unwrap();
|
|
}
|
|
}
|
|
sum += out.iter().sum::<f32>();
|
|
}
|
|
sum
|
|
})
|
|
}
|
|
|
|
fn tiled(vnni: bool, tr: usize, ta: usize) -> Variant<'static> {
|
|
Box::new(move |w, lo, hi, acts| {
|
|
let mut sum = 0f32;
|
|
let na = acts.ys.len();
|
|
let rb = BLOCKS_PER_ROW * MXFP4;
|
|
let mut out = vec![0f32; tr * ta];
|
|
let mut r = lo;
|
|
while r < hi {
|
|
let nr = tr.min(hi - r);
|
|
let rows: Vec<&[u8]> = (0..nr)
|
|
.map(|i| &w[(r + i) * rb..(r + i + 1) * rb])
|
|
.collect();
|
|
let mut a = 0;
|
|
while a < na {
|
|
let nta = ta.min(na - a);
|
|
let views: Vec<sys::ActRef> =
|
|
(a..a + nta).map(|i| acts.prepared[i].view()).collect();
|
|
let o = &mut out[..nr * nta];
|
|
if vnni {
|
|
sys::mxfp4_q8r_tile_avxvnni(&rows, &views, o).unwrap();
|
|
} else {
|
|
sys::mxfp4_q8r_tile_avx2(&rows, &views, o).unwrap();
|
|
}
|
|
sum += o.iter().sum::<f32>();
|
|
a += nta;
|
|
}
|
|
r += nr;
|
|
}
|
|
sum
|
|
})
|
|
}
|
|
|
|
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(9);
|
|
let n_acts: usize = args.get(3).and_then(|s| s.parse().ok()).unwrap_or(1);
|
|
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<Vec<f32>> = (0..n_acts)
|
|
.map(|_| vec![0.0625f32; BLOCKS_PER_ROW])
|
|
.collect();
|
|
let yq: Vec<Vec<i8>> = (0..n_acts)
|
|
.map(|_| {
|
|
(0..BLOCKS_PER_ROW * 32)
|
|
.map(|_| ((next() % 255) as i64 - 127) as i8)
|
|
.collect()
|
|
})
|
|
.collect();
|
|
let prepared = ys
|
|
.iter()
|
|
.zip(&yq)
|
|
.map(|(s, q)| sys::PreparedAct::new(s.clone(), q.clone()).unwrap())
|
|
.collect();
|
|
let acts = Acts { ys, yq, prepared };
|
|
|
|
let vnni = sys::avxvnni_available();
|
|
let mut variants: Vec<(String, Variant)> = vec![(
|
|
format!(
|
|
"one-row q8r4, {} loop over acts",
|
|
if vnni { "vnni" } else { "avx2" }
|
|
),
|
|
one_row_loop(vnni),
|
|
)];
|
|
variants.push((
|
|
"multi-activation q8r4 (bit-identical)".to_owned(),
|
|
multi(vnni),
|
|
));
|
|
for (tr, ta) in [
|
|
(1, 1),
|
|
(2, 1),
|
|
(4, 1),
|
|
(1, 4),
|
|
(2, 2),
|
|
(2, 4),
|
|
(4, 2),
|
|
(4, 4),
|
|
] {
|
|
if ta > n_acts && ta > 1 {
|
|
continue;
|
|
}
|
|
variants.push((format!("tile {tr}x{ta}"), tiled(vnni, tr, ta)));
|
|
}
|
|
|
|
println!(
|
|
"buffer {} MiB = {rows} rows, {n_acts} activation(s); {repeats} interleaved repeats; ratios are paired against the first variant",
|
|
weights.len() >> 20
|
|
);
|
|
for threads in [1usize, 10] {
|
|
let mut samples: Vec<Vec<f64>> = vec![Vec::new(); variants.len()];
|
|
for rep in 0..repeats {
|
|
for k in 0..variants.len() {
|
|
let idx = (k + rep) % variants.len();
|
|
let kernel = &variants[idx].1;
|
|
let start = Instant::now();
|
|
std::thread::scope(|s| {
|
|
let per = rows.div_ceil(threads);
|
|
for t in 0..threads {
|
|
let (w, a) = (&weights, &acts);
|
|
s.spawn(move || {
|
|
let (lo, hi) = (t * per, ((t + 1) * per).min(rows));
|
|
std::hint::black_box(kernel(w, lo, hi, a));
|
|
});
|
|
}
|
|
});
|
|
// weight GB/s read, and block-dot rate (rows x activations x blocks)
|
|
samples[idx].push(weights.len() as f64 / start.elapsed().as_secs_f64() / 1e9);
|
|
}
|
|
}
|
|
println!(
|
|
"-- {threads} thread(s); weight GB/s (each byte used against {n_acts} activation(s))"
|
|
);
|
|
for (i, (name, _)) in variants.iter().enumerate() {
|
|
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!(
|
|
"{:<36} {:>7.1} GB/s ratio {:>6.3} [{:.3} .. {:.3}]",
|
|
name,
|
|
s[s.len() / 2],
|
|
ratios[ratios.len() / 2],
|
|
ratios[0],
|
|
ratios[ratios.len() - 1]
|
|
);
|
|
}
|
|
}
|
|
}
|