- service: BATCH n lets it see each product's successor and expand the next weights on a thread while the device runs the current one; buckets up to 4096; OpenVINO CACHE_DIR compile cache - client: batched expert products, layout sized by batch, default batch 2048 - cpu-sys/cpu-kernels: AVX2 F16C f16_to_f32 kernel, exact for every half bit pattern - npu-worker: memory admission before an NPU prefill (falls back to the CPU when RAM is short) Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
400 lines
14 KiB
Rust
400 lines
14 KiB
Rust
//! The attention helpers: the AVX2 level against the portable one and against f64 references, for
|
|
//! groups of heads that share the keys and values.
|
|
|
|
use leleka_cpu_sys as sys;
|
|
|
|
struct Rng(u64);
|
|
|
|
impl Rng {
|
|
fn next(&mut self) -> u64 {
|
|
self.0 ^= self.0 << 13;
|
|
self.0 ^= self.0 >> 7;
|
|
self.0 ^= self.0 << 17;
|
|
self.0
|
|
}
|
|
fn f32(&mut self, spread: f32) -> f32 {
|
|
((self.next() >> 40) as f32 / (1u64 << 24) as f32 - 0.5) * 2.0 * spread
|
|
}
|
|
}
|
|
|
|
/// (heads, head width, stride, positions): odd widths, strides wider than the head, blocks that do not
|
|
/// divide the position count, and the empty case.
|
|
const SHAPES: [(usize, usize, usize, usize); 9] = [
|
|
(8, 64, 512, 37),
|
|
(1, 64, 64, 5),
|
|
(8, 64, 512, 16),
|
|
(8, 64, 512, 17),
|
|
(3, 8, 8, 1),
|
|
(2, 13, 20, 9),
|
|
(4, 100, 128, 33),
|
|
(2, 1, 1, 4),
|
|
(8, 64, 512, 0),
|
|
];
|
|
|
|
#[test]
|
|
fn scores_match_an_f64_reference_for_groups_of_heads() {
|
|
let mut rng = Rng(11);
|
|
for (heads, hd, stride, n) in SHAPES {
|
|
let q: Vec<f32> = (0..heads * hd).map(|_| rng.f32(2.0)).collect();
|
|
let extent = if n == 0 { 0 } else { (n - 1) * stride + hd };
|
|
let keys: Vec<f32> = (0..extent).map(|_| rng.f32(2.0)).collect();
|
|
let mut out_s = vec![0f32; heads * n];
|
|
sys::attn_scores_scalar(&q, heads, &keys, stride, n, 0.125, &mut out_s).unwrap();
|
|
let mut out_v = out_s.clone();
|
|
if sys::avx2_available() {
|
|
out_v.fill(f32::NAN);
|
|
sys::attn_scores_avx2(&q, heads, &keys, stride, n, 0.125, &mut out_v).unwrap();
|
|
}
|
|
for g in 0..heads {
|
|
for i in 0..n {
|
|
let terms: Vec<f64> = (0..hd)
|
|
.map(|j| f64::from(q[g * hd + j]) * f64::from(keys[i * stride + j]))
|
|
.collect();
|
|
let exact = terms.iter().sum::<f64>() * 0.125;
|
|
let mag = terms.iter().map(|t| t.abs()).sum::<f64>() * 0.125;
|
|
let tol = mag * (hd as f64 + 8.0) * 2f64.powi(-23);
|
|
assert!(
|
|
(f64::from(out_s[g * n + i]) - exact).abs() <= tol,
|
|
"scalar {heads}x{hd} head {g} #{i}"
|
|
);
|
|
assert!(
|
|
(f64::from(out_v[g * n + i]) - exact).abs() <= tol,
|
|
"avx2 {heads}x{hd} head {g} #{i}"
|
|
);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn weighted_sums_match_an_f64_reference_for_groups_of_heads() {
|
|
let mut rng = Rng(23);
|
|
for (heads, hd, stride, n) in SHAPES {
|
|
let weights: Vec<f32> = (0..heads * n).map(|_| rng.f32(1.0).abs()).collect();
|
|
let extent = if n == 0 { 0 } else { (n - 1) * stride + hd };
|
|
let values: Vec<f32> = (0..extent).map(|_| rng.f32(3.0)).collect();
|
|
let mut out_s = vec![7f32; heads * hd];
|
|
sys::attn_weighted_sum_scalar(&weights, heads, n, &values, stride, &mut out_s).unwrap();
|
|
let mut out_v = out_s.clone();
|
|
if sys::avx2_available() {
|
|
out_v.fill(f32::NAN);
|
|
sys::attn_weighted_sum_avx2(&weights, heads, n, &values, stride, &mut out_v).unwrap();
|
|
}
|
|
for g in 0..heads {
|
|
for j in 0..hd {
|
|
let terms: Vec<f64> = (0..n)
|
|
.map(|i| f64::from(weights[g * n + i]) * f64::from(values[i * stride + j]))
|
|
.collect();
|
|
let exact: f64 = terms.iter().sum();
|
|
let mag: f64 = terms.iter().map(|t| t.abs()).sum();
|
|
let tol = mag * (n as f64 + 8.0) * 2f64.powi(-23);
|
|
assert!(
|
|
(f64::from(out_s[g * hd + j]) - exact).abs() <= tol,
|
|
"scalar {heads}x{hd} head {g} col {j}"
|
|
);
|
|
assert!(
|
|
(f64::from(out_v[g * hd + j]) - exact).abs() <= tol,
|
|
"avx2 {heads}x{hd} head {g} col {j}"
|
|
);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn the_vector_exp_is_accurate_and_flushes_deep_underflow_to_zero() {
|
|
if !sys::avx2_available() {
|
|
return;
|
|
}
|
|
let mut rng = Rng(5);
|
|
let mut inputs: Vec<f32> = (0..20_000).map(|_| rng.f32(20.0) - 10.0).collect();
|
|
inputs.extend([
|
|
0.0,
|
|
-0.0,
|
|
1e-8,
|
|
-1e-8,
|
|
88.0,
|
|
-86.9,
|
|
-87.5,
|
|
-200.0,
|
|
f32::NEG_INFINITY,
|
|
0.5,
|
|
-0.5,
|
|
1.0,
|
|
]);
|
|
inputs.truncate(inputs.len() / 8 * 8 + 3); // a ragged tail
|
|
let max = 3.0f32;
|
|
let mut vec_out = inputs.clone();
|
|
let mut scalar_out = inputs.clone();
|
|
let sv = sys::exp_shift_sum_avx2(&mut vec_out, max).unwrap();
|
|
let ss = sys::exp_shift_sum_scalar(&mut scalar_out, max).unwrap();
|
|
for (i, x) in inputs.iter().enumerate() {
|
|
// the kernel subtracts in f32, so the argument it exponentiates is the f32 difference
|
|
let exact = f64::from(*x - max).exp();
|
|
let got = f64::from(vec_out[i]);
|
|
if *x - max < -87.0 {
|
|
assert!(
|
|
vec_out[i] == 0.0 || (got - exact).abs() <= exact * 3e-7 + 1e-37,
|
|
"{x}: {got} vs {exact}"
|
|
);
|
|
} else {
|
|
assert!((got - exact).abs() <= exact * 3e-7, "{x}: {got} vs {exact}");
|
|
}
|
|
}
|
|
assert!((f64::from(sv) - f64::from(ss)).abs() <= f64::from(ss) * 1e-4);
|
|
}
|
|
|
|
#[test]
|
|
fn bad_shapes_are_refused_before_any_read() {
|
|
let q = [1.0f32; 16]; // two heads of width 8
|
|
let keys = [0.0f32; 20];
|
|
let mut out = [0.0f32; 6];
|
|
let check = |name: &str, result: Result<(), sys::KernelError>| {
|
|
assert_eq!(result, Err(sys::KernelError::LengthMismatch), "{name}");
|
|
};
|
|
// three positions at stride 8 need 8 * 2 + 8 = 24 floats
|
|
check(
|
|
"keys too short",
|
|
sys::attn_scores_scalar(&q, 2, &keys, 8, 3, 1.0, &mut out),
|
|
);
|
|
check(
|
|
"output too short",
|
|
sys::attn_scores_scalar(&q, 2, &keys, 8, 2, 1.0, &mut out[..3]),
|
|
);
|
|
check(
|
|
"no heads",
|
|
sys::attn_scores_scalar(&q, 0, &keys, 8, 2, 1.0, &mut out),
|
|
);
|
|
check(
|
|
"heads do not divide q",
|
|
sys::attn_scores_scalar(&q, 3, &keys, 8, 2, 1.0, &mut out),
|
|
);
|
|
check(
|
|
"empty q",
|
|
sys::attn_scores_scalar(&[], 1, &keys, 8, 2, 1.0, &mut out),
|
|
);
|
|
check(
|
|
"stride overflow",
|
|
sys::attn_scores_scalar(&q, 2, &keys, usize::MAX, 3, 1.0, &mut out),
|
|
);
|
|
let mut o = [0.0f32; 16];
|
|
check(
|
|
"weights too short",
|
|
sys::attn_weighted_sum_scalar(&[1.0; 5], 2, 3, &keys, 4, &mut o),
|
|
);
|
|
check(
|
|
"values too short",
|
|
sys::attn_weighted_sum_scalar(&[1.0; 6], 2, 3, &keys[..10], 8, &mut o),
|
|
);
|
|
check(
|
|
"no heads",
|
|
sys::attn_weighted_sum_scalar(&[1.0; 6], 0, 3, &keys, 4, &mut o),
|
|
);
|
|
if sys::avx2_available() {
|
|
check(
|
|
"avx2 keys too short",
|
|
sys::attn_scores_avx2(&q, 2, &keys, 8, 3, 1.0, &mut out),
|
|
);
|
|
check(
|
|
"avx2 values too short",
|
|
sys::attn_weighted_sum_avx2(&[1.0; 6], 2, 3, &keys[..10], 8, &mut o),
|
|
);
|
|
}
|
|
}
|
|
|
|
/// Round `values` to half precision and return the bit patterns and the decoded values.
|
|
fn to_half(values: &[f32]) -> (Vec<u16>, Vec<f32>) {
|
|
let mut bits = vec![0u16; values.len()];
|
|
sys::f32_to_f16_slice_scalar(values, &mut bits).unwrap();
|
|
let decoded = bits.iter().map(|b| sys::simd::f16_to_f32(*b)).collect();
|
|
(bits, decoded)
|
|
}
|
|
|
|
#[test]
|
|
fn half_precision_keys_and_values_match_f64_references_on_the_decoded_values() {
|
|
let mut rng = Rng(31);
|
|
for (heads, hd, stride, n) in SHAPES {
|
|
let q: Vec<f32> = (0..heads * hd).map(|_| rng.f32(2.0)).collect();
|
|
let extent = if n == 0 { 0 } else { (n - 1) * stride + hd };
|
|
let (keys16, keys) = to_half(&(0..extent).map(|_| rng.f32(2.0)).collect::<Vec<_>>());
|
|
let (values16, values) = to_half(&(0..extent).map(|_| rng.f32(3.0)).collect::<Vec<_>>());
|
|
let weights: Vec<f32> = (0..heads * n).map(|_| rng.f32(1.0).abs()).collect();
|
|
|
|
let mut scores_s = vec![0f32; heads * n];
|
|
sys::attn_scores_f16_scalar(&q, heads, &keys16, stride, n, 0.125, &mut scores_s).unwrap();
|
|
let mut scores_v = scores_s.clone();
|
|
let mut sums_s = vec![0f32; heads * hd];
|
|
sys::attn_weighted_sum_f16_scalar(&weights, heads, n, &values16, stride, &mut sums_s)
|
|
.unwrap();
|
|
let mut sums_v = sums_s.clone();
|
|
if sys::avx2_available() {
|
|
scores_v.fill(f32::NAN);
|
|
sums_v.fill(f32::NAN);
|
|
sys::attn_scores_f16_avx2(&q, heads, &keys16, stride, n, 0.125, &mut scores_v).unwrap();
|
|
sys::attn_weighted_sum_f16_avx2(&weights, heads, n, &values16, stride, &mut sums_v)
|
|
.unwrap();
|
|
}
|
|
for g in 0..heads {
|
|
for i in 0..n {
|
|
let terms: Vec<f64> = (0..hd)
|
|
.map(|j| f64::from(q[g * hd + j]) * f64::from(keys[i * stride + j]))
|
|
.collect();
|
|
let exact = terms.iter().sum::<f64>() * 0.125;
|
|
let tol = terms.iter().map(|t| t.abs()).sum::<f64>()
|
|
* 0.125
|
|
* (hd as f64 + 8.0)
|
|
* 2f64.powi(-23);
|
|
for got in [scores_s[g * n + i], scores_v[g * n + i]] {
|
|
assert!(
|
|
(f64::from(got) - exact).abs() <= tol,
|
|
"scores {heads}x{hd} head {g} #{i}"
|
|
);
|
|
}
|
|
}
|
|
for j in 0..hd {
|
|
let terms: Vec<f64> = (0..n)
|
|
.map(|i| f64::from(weights[g * n + i]) * f64::from(values[i * stride + j]))
|
|
.collect();
|
|
let exact: f64 = terms.iter().sum();
|
|
let tol =
|
|
terms.iter().map(|t| t.abs()).sum::<f64>() * (n as f64 + 8.0) * 2f64.powi(-23);
|
|
for got in [sums_s[g * hd + j], sums_v[g * hd + j]] {
|
|
assert!(
|
|
(f64::from(got) - exact).abs() <= tol,
|
|
"sums {heads}x{hd} head {g} col {j}"
|
|
);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn the_vector_half_conversion_is_bit_identical_to_the_portable_one() {
|
|
if !sys::avx2_available() {
|
|
return;
|
|
}
|
|
let mut rng = Rng(77);
|
|
for len in [0usize, 1, 7, 8, 9, 63, 64, 65, 1000] {
|
|
let mut src: Vec<f32> = (0..len)
|
|
.map(|_| f32::from_bits(rng.next() as u32))
|
|
.collect();
|
|
src.iter_mut().for_each(|v| {
|
|
if v.is_nan() {
|
|
*v = 0.5; // NaN payloads are not part of the contract
|
|
}
|
|
});
|
|
let (mut a, mut b) = (vec![0u16; len], vec![0u16; len]);
|
|
sys::f32_to_f16_slice_scalar(&src, &mut a).unwrap();
|
|
sys::f32_to_f16_slice_avx2(&src, &mut b).unwrap();
|
|
assert_eq!(a, b, "length {len}");
|
|
}
|
|
let mut short = [0u16; 3];
|
|
assert_eq!(
|
|
sys::f32_to_f16_slice_scalar(&[1.0; 4], &mut short),
|
|
Err(sys::KernelError::LengthMismatch)
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn half_precision_kernels_refuse_short_buffers() {
|
|
let q = [1.0f32; 16];
|
|
let keys = [0u16; 20];
|
|
let mut out = [0.0f32; 6];
|
|
assert_eq!(
|
|
sys::attn_scores_f16_scalar(&q, 2, &keys, 8, 3, 1.0, &mut out),
|
|
Err(sys::KernelError::LengthMismatch)
|
|
);
|
|
let mut o = [0.0f32; 16];
|
|
assert_eq!(
|
|
sys::attn_weighted_sum_f16_scalar(&[1.0; 6], 2, 3, &keys[..10], 8, &mut o),
|
|
Err(sys::KernelError::LengthMismatch)
|
|
);
|
|
if sys::avx2_available() {
|
|
assert_eq!(
|
|
sys::attn_scores_f16_avx2(&q, 2, &keys, 8, 3, 1.0, &mut out),
|
|
Err(sys::KernelError::LengthMismatch)
|
|
);
|
|
assert_eq!(
|
|
sys::attn_weighted_sum_f16_avx2(&[1.0; 6], 2, 3, &keys[..10], 8, &mut o),
|
|
Err(sys::KernelError::LengthMismatch)
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn the_expert_activation_matches_an_f64_reference_including_extremes() {
|
|
let mut rng = Rng(101);
|
|
let (alpha, limit) = (1.702f32, 7.0f32);
|
|
for len in [0usize, 1, 7, 8, 9, 100, 2880] {
|
|
let mut gate: Vec<f32> = (0..len).map(|_| rng.f32(12.0)).collect();
|
|
let mut up: Vec<f32> = (0..len).map(|_| rng.f32(12.0)).collect();
|
|
// extremes: far beyond the clamps in both directions and at the clamp edges
|
|
for (i, g) in [-200.0f32, 200.0, -7.0, 7.0, 0.0, -0.0, 50.0, -50.0]
|
|
.iter()
|
|
.enumerate()
|
|
{
|
|
if i < len {
|
|
gate[i] = *g;
|
|
up[i] = if i % 2 == 0 { 100.0 } else { -100.0 };
|
|
}
|
|
}
|
|
let mut s = vec![0f32; len];
|
|
sys::swiglu_oai_scalar(&gate, &up, alpha, limit, &mut s).unwrap();
|
|
let mut v = s.clone();
|
|
if sys::avx2_available() {
|
|
v.fill(f32::NAN);
|
|
sys::swiglu_oai_avx2(&gate, &up, alpha, limit, &mut v).unwrap();
|
|
}
|
|
for i in 0..len {
|
|
let x = f64::from(gate[i]).min(f64::from(limit));
|
|
let y = f64::from(up[i]).clamp(-f64::from(limit), f64::from(limit));
|
|
let exact = x / (1.0 + (-f64::from(alpha) * x).exp()) * (1.0 + y);
|
|
for (name, got) in [("scalar", s[i]), ("avx2", v[i])] {
|
|
let err = (f64::from(got) - exact).abs();
|
|
assert!(
|
|
err <= 3e-6 * exact.abs() + 1e-30,
|
|
"{name} len {len} #{i}: gate {} up {}: {got} vs {exact}",
|
|
gate[i],
|
|
up[i]
|
|
);
|
|
}
|
|
}
|
|
}
|
|
let mut out = [0f32; 3];
|
|
assert_eq!(
|
|
sys::swiglu_oai_scalar(&[1.0; 3], &[1.0; 2], alpha, limit, &mut out),
|
|
Err(sys::KernelError::LengthMismatch)
|
|
);
|
|
assert_eq!(
|
|
sys::swiglu_oai_scalar(&[1.0; 3], &[1.0; 3], alpha, limit, &mut out[..2]),
|
|
Err(sys::KernelError::LengthMismatch)
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn the_vector_half_to_float_conversion_is_exact_for_every_bit_pattern() {
|
|
if !sys::avx2_available() {
|
|
return;
|
|
}
|
|
// every half, padded so the vector body and the scalar tail both run
|
|
let all: Vec<u16> = (0..=u16::MAX).collect();
|
|
for len in [65_536usize, 65_531, 7, 8, 9, 0] {
|
|
let src = &all[..len];
|
|
let (mut a, mut b) = (vec![0f32; len], vec![0f32; len]);
|
|
sys::f16_to_f32_slice_scalar(src, &mut a).unwrap();
|
|
sys::f16_to_f32_slice_avx2(src, &mut b).unwrap();
|
|
for (i, (x, y)) in a.iter().zip(&b).enumerate() {
|
|
// NaN payloads are not part of the contract
|
|
assert!(
|
|
x.to_bits() == y.to_bits() || (x.is_nan() && y.is_nan()),
|
|
"half {i:#06x}: {x} vs {y}"
|
|
);
|
|
}
|
|
}
|
|
assert_eq!(
|
|
sys::f16_to_f32_slice_avx2(&[0u16; 3], &mut [0f32; 2]),
|
|
Err(sys::KernelError::LengthMismatch)
|
|
);
|
|
}
|