340 lines
11 KiB
Rust
340 lines
11 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;
|
|
|
|
#[path = "attention/kernel_checks.rs"]
|
|
mod kernel_checks;
|
|
use kernel_checks::*;
|
|
|
|
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),
|
|
];
|
|
|
|
/// Heads, head width, stride and positions of one shape.
|
|
#[derive(Clone, Copy)]
|
|
struct Shape {
|
|
heads: usize,
|
|
hd: usize,
|
|
stride: usize,
|
|
n: usize,
|
|
}
|
|
|
|
impl Shape {
|
|
fn new(heads: usize, hd: usize, stride: usize, n: usize) -> Self {
|
|
Shape {
|
|
heads,
|
|
hd,
|
|
stride,
|
|
n,
|
|
}
|
|
}
|
|
|
|
fn parts(self) -> (usize, usize, usize, usize) {
|
|
(self.heads, self.hd, self.stride, self.n)
|
|
}
|
|
|
|
fn extent(self) -> usize {
|
|
if self.n == 0 {
|
|
0
|
|
} else {
|
|
(self.n - 1) * self.stride + self.hd
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn scores_match_an_f64_reference_for_groups_of_heads() {
|
|
let mut rng = Rng(11);
|
|
for (heads, hd, stride, n) in SHAPES {
|
|
let shape = Shape::new(heads, hd, stride, n);
|
|
let q: Vec<f32> = (0..heads * hd).map(|_| rng.f32(2.0)).collect();
|
|
let keys: Vec<f32> = (0..shape.extent()).map(|_| rng.f32(2.0)).collect();
|
|
let mut out_s = vec![0f32; heads * n];
|
|
sys::attn_scores_scalar(&q, &keys, score_spec(heads, n, stride, 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, &keys, score_spec(heads, n, stride, 0.125), &mut out_v)
|
|
.unwrap();
|
|
}
|
|
check_scores(shape, &q, &keys, [&out_s, &out_v]);
|
|
}
|
|
}
|
|
|
|
/// The scalar and AVX2 scores against the f64 reference.
|
|
fn check_scores(shape: Shape, q: &[f32], keys: &[f32], [out_s, out_v]: [&[f32]; 2]) {
|
|
let (heads, hd, stride, n) = shape.parts();
|
|
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 shape = Shape::new(heads, hd, stride, n);
|
|
let weights: Vec<f32> = (0..heads * n).map(|_| rng.f32(1.0).abs()).collect();
|
|
let values: Vec<f32> = (0..shape.extent()).map(|_| rng.f32(3.0)).collect();
|
|
let mut out_s = vec![7f32; heads * hd];
|
|
sys::attn_weighted_sum_scalar(&weights, &values, attn_shape(heads, n, 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,
|
|
&values,
|
|
attn_shape(heads, n, stride),
|
|
&mut out_v,
|
|
)
|
|
.unwrap();
|
|
}
|
|
check_weighted_sums(shape, &weights, &values, [&out_s, &out_v]);
|
|
}
|
|
}
|
|
|
|
/// The scalar and AVX2 weighted sums against the f64 reference.
|
|
fn check_weighted_sums(shape: Shape, weights: &[f32], values: &[f32], [out_s, out_v]: [&[f32]; 2]) {
|
|
let (heads, hd, stride, n) = shape.parts();
|
|
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}"
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Inputs of the vector exp: random values, special values and a ragged tail.
|
|
fn exp_inputs(rng: &mut Rng) -> Vec<f32> {
|
|
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
|
|
inputs
|
|
}
|
|
|
|
#[test]
|
|
fn the_vector_exp_is_accurate_and_flushes_deep_underflow_to_zero() {
|
|
if !sys::avx2_available() {
|
|
return;
|
|
}
|
|
let mut rng = Rng(5);
|
|
let inputs = exp_inputs(&mut rng);
|
|
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];
|
|
refuse_score_shapes(&q, &keys);
|
|
refuse_weighted_sum_shapes(&keys);
|
|
}
|
|
|
|
#[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 shape = Shape::new(heads, hd, stride, n);
|
|
let extent = shape.extent();
|
|
let q: Vec<f32> = (0..heads * hd).map(|_| rng.f32(2.0)).collect();
|
|
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 scores = half_scores(shape, &q, &keys16);
|
|
let sums = half_sums(shape, &weights, &values16);
|
|
check_f16_scores(shape, &q, &keys, [&scores[0], &scores[1]]);
|
|
check_f16_sums(shape, &weights, &values, [&sums[0], &sums[1]]);
|
|
}
|
|
}
|
|
|
|
#[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, &keys, score_spec(2, 3, 8, 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], &keys[..10], attn_shape(2, 3, 8), &mut o),
|
|
Err(sys::KernelError::LengthMismatch)
|
|
);
|
|
if sys::avx2_available() {
|
|
assert_eq!(
|
|
sys::attn_scores_f16_avx2(&q, &keys, score_spec(2, 3, 8, 1.0), &mut out),
|
|
Err(sys::KernelError::LengthMismatch)
|
|
);
|
|
assert_eq!(
|
|
sys::attn_weighted_sum_f16_avx2(&[1.0; 6], &keys[..10], attn_shape(2, 3, 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 (gate, up) = swiglu_inputs(&mut rng, len);
|
|
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();
|
|
}
|
|
check_swiglu(len, [&gate, &up], [&s, &v], (alpha, limit));
|
|
}
|
|
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)
|
|
);
|
|
}
|