Files
leleka/crates/cpu-sys/tests/attention/kernel_checks.rs
T

227 lines
7.1 KiB
Rust

//! The shape-refusal, half-precision and activation helpers of the attention tests.
use super::*;
pub(super) fn attn_shape(heads: usize, n: usize, stride: usize) -> sys::AttnShape {
sys::AttnShape { heads, n, stride }
}
pub(super) fn score_spec(heads: usize, n: usize, stride: usize, scale: f32) -> sys::ScoreSpec {
sys::ScoreSpec {
shape: attn_shape(heads, n, stride),
scale,
}
}
pub(super) fn expect_mismatch(name: &str, result: Result<(), sys::KernelError>) {
assert_eq!(result, Err(sys::KernelError::LengthMismatch), "{name}");
}
pub(super) fn refuse_score_shapes(q: &[f32; 16], keys: &[f32; 20]) {
let mut out = [0.0f32; 6];
let check = expect_mismatch;
// three positions at stride 8 need 8 * 2 + 8 = 24 floats
check(
"keys too short",
sys::attn_scores_scalar(q, keys, score_spec(2, 3, 8, 1.0), &mut out),
);
check(
"output too short",
sys::attn_scores_scalar(q, keys, score_spec(2, 2, 8, 1.0), &mut out[..3]),
);
check(
"no heads",
sys::attn_scores_scalar(q, keys, score_spec(0, 2, 8, 1.0), &mut out),
);
check(
"heads do not divide q",
sys::attn_scores_scalar(q, keys, score_spec(3, 2, 8, 1.0), &mut out),
);
check(
"empty q",
sys::attn_scores_scalar(&[], keys, score_spec(1, 2, 8, 1.0), &mut out),
);
check(
"stride overflow",
sys::attn_scores_scalar(q, keys, score_spec(2, 3, usize::MAX, 1.0), &mut out),
);
refuse_avx2_score_shape(q, keys);
}
pub(super) fn refuse_avx2_score_shape(q: &[f32; 16], keys: &[f32; 20]) {
let mut out = [0.0f32; 6];
let check = expect_mismatch;
if sys::avx2_available() {
check(
"avx2 keys too short",
sys::attn_scores_avx2(q, keys, score_spec(2, 3, 8, 1.0), &mut out),
);
}
}
pub(super) fn refuse_weighted_sum_shapes(keys: &[f32; 20]) {
let mut o = [0.0f32; 16];
let check = expect_mismatch;
check(
"weights too short",
sys::attn_weighted_sum_scalar(&[1.0; 5], keys, attn_shape(2, 3, 4), &mut o),
);
check(
"values too short",
sys::attn_weighted_sum_scalar(&[1.0; 6], &keys[..10], attn_shape(2, 3, 8), &mut o),
);
check(
"no heads",
sys::attn_weighted_sum_scalar(&[1.0; 6], keys, attn_shape(0, 3, 4), &mut o),
);
if sys::avx2_available() {
check(
"avx2 values too short",
sys::attn_weighted_sum_avx2(&[1.0; 6], &keys[..10], attn_shape(2, 3, 8), &mut o),
);
}
}
/// Round `values` to half precision and return the bit patterns and the decoded values.
pub(super) 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)
}
/// The scalar and (when available) AVX2 half-precision scores.
pub(super) fn half_scores(shape: Shape, q: &[f32], keys16: &[u16]) -> [Vec<f32>; 2] {
let (heads, _hd, stride, n) = shape.parts();
let mut scores_s = vec![0f32; heads * n];
sys::attn_scores_f16_scalar(
q,
keys16,
score_spec(heads, n, stride, 0.125),
&mut scores_s,
)
.unwrap();
let mut scores_v = scores_s.clone();
if sys::avx2_available() {
scores_v.fill(f32::NAN);
sys::attn_scores_f16_avx2(
q,
keys16,
score_spec(heads, n, stride, 0.125),
&mut scores_v,
)
.unwrap();
}
[scores_s, scores_v]
}
/// The scalar and (when available) AVX2 half-precision weighted sums.
pub(super) fn half_sums(shape: Shape, weights: &[f32], values16: &[u16]) -> [Vec<f32>; 2] {
let (heads, hd, stride, n) = shape.parts();
let mut sums_s = vec![0f32; heads * hd];
sys::attn_weighted_sum_f16_scalar(weights, values16, attn_shape(heads, n, stride), &mut sums_s)
.unwrap();
let mut sums_v = sums_s.clone();
if sys::avx2_available() {
sums_v.fill(f32::NAN);
sys::attn_weighted_sum_f16_avx2(
weights,
values16,
attn_shape(heads, n, stride),
&mut sums_v,
)
.unwrap();
}
[sums_s, sums_v]
}
pub(super) fn check_f16_scores(
shape: Shape,
q: &[f32],
keys: &[f32],
[scores_s, scores_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 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}"
);
}
}
}
}
pub(super) fn check_f16_sums(
shape: Shape,
weights: &[f32],
values: &[f32],
[sums_s, sums_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 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}"
);
}
}
}
}
/// Gate and up vectors with extremes at the front: far beyond the clamps and at the clamp edges.
pub(super) fn swiglu_inputs(rng: &mut Rng, len: usize) -> (Vec<f32>, Vec<f32>) {
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();
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 };
}
}
(gate, up)
}
pub(super) fn check_swiglu(
len: usize,
[gate, up]: [&[f32]; 2],
[s, v]: [&[f32]; 2],
(alpha, limit): (f32, f32),
) {
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]
);
}
}
}