const LANES: usize = 8;
#[inline(always)]
fn reduce2(x: &[f64], y: &[f64], g: impl Fn(f64, f64) -> f64) -> f64 {
debug_assert_eq!(x.len(), y.len());
let mut acc = [0.0; LANES];
let (xc, xr) = x.as_chunks::<LANES>();
let (yc, yr) = y.as_chunks::<LANES>();
for (a, b) in xc.iter().zip(yc) {
for l in 0..LANES {
acc[l] += g(a[l], b[l]);
}
}
let mut s: f64 = acc.iter().sum();
for (a, b) in xr.iter().zip(yr) {
s += g(*a, *b);
}
s
}
#[inline(always)]
fn madd<const FMA: bool>(a: f64, b: f64, c: f64) -> f64 {
if FMA { a.mul_add(b, c) } else { a * b + c }
}
#[inline]
fn use_fma() -> bool {
#[cfg(target_arch = "x86_64")]
{
std::arch::is_x86_feature_detected!("avx2") && std::arch::is_x86_feature_detected!("fma")
}
#[cfg(not(target_arch = "x86_64"))]
{
false
}
}
macro_rules! dispatch {
($(#[$doc:meta])* fn $name:ident / $fma:ident = $body:ident ($($arg:ident : $ty:ty),*) $(-> $ret:ty)?) => {
$(#[$doc])*
pub(crate) fn $name($($arg: $ty),*) $(-> $ret)? {
#[cfg(target_arch = "x86_64")]
if use_fma() {
return unsafe { $fma($($arg),*) };
}
$body::<false>($($arg),*)
}
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2,fma")]
fn $fma($($arg: $ty),*) $(-> $ret)? {
$body::<true>($($arg),*)
}
};
}
#[inline(always)]
fn dot_k<const FMA: bool>(x: &[f64], y: &[f64]) -> f64 {
debug_assert_eq!(x.len(), y.len());
let mut acc = [0.0; LANES];
let (xc, xr) = x.as_chunks::<LANES>();
let (yc, yr) = y.as_chunks::<LANES>();
for (a, b) in xc.iter().zip(yc) {
for l in 0..LANES {
acc[l] = madd::<FMA>(a[l], b[l], acc[l]);
}
}
let mut s: f64 = acc.iter().sum();
for (a, b) in xr.iter().zip(yr) {
s = madd::<FMA>(*a, *b, s);
}
s
}
#[inline(always)]
fn axpy_k<const FMA: bool>(a: f64, x: &[f64], y: &mut [f64]) {
debug_assert_eq!(x.len(), y.len());
for (yi, xi) in y.iter_mut().zip(x) {
*yi = madd::<FMA>(a, *xi, *yi);
}
}
dispatch! {
fn dot / dot_fma = dot_k(x: &[f64], y: &[f64]) -> f64
}
dispatch! {
fn axpy / axpy_fma = axpy_k(a: f64, x: &[f64], y: &mut [f64])
}
pub(crate) fn scale(a: f64, x: &mut [f64]) {
for xi in x.iter_mut() {
*xi *= a;
}
}
pub(crate) fn nrm2(x: &[f64]) -> f64 {
let s = reduce2(x, x, |a, _| a * a);
if s.is_finite() && s > 1e-280 {
return s.sqrt();
}
if s.is_nan() {
return f64::NAN;
}
if s == 0.0 && x.iter().all(|&v| v == 0.0) {
return 0.0;
}
let amax = x.iter().fold(0.0_f64, |m, v| m.max(v.abs()));
if amax == 0.0 || !amax.is_finite() {
return amax;
}
let s: f64 = x.iter().map(|v| (v / amax) * (v / amax)).sum();
amax * s.sqrt()
}
pub(crate) fn wrms(x: &[f64], w: &[f64]) -> f64 {
debug_assert_eq!(x.len(), w.len());
if x.is_empty() {
return 0.0;
}
let s = reduce2(x, w, |a, b| (a * b) * (a * b));
(s / x.len() as f64).sqrt()
}
const BLOCK: usize = 512;
#[inline(always)]
fn qt_v_k<const FMA: bool>(q: &[f64], n: usize, k: usize, v: &[f64], c: &mut [f64]) -> f64 {
debug_assert!(q.len() >= n * k && v.len() == n && c.len() >= k);
c[..k].fill(0.0);
let mut vv = 0.0;
let mut start = 0;
while start < n {
let end = (start + BLOCK).min(n);
let vb = &v[start..end];
for (j, cj) in c[..k].iter_mut().enumerate() {
*cj += dot_k::<FMA>(&q[j * n + start..j * n + end], vb);
}
vv += dot_k::<FMA>(vb, vb);
start = end;
}
vv
}
#[inline(always)]
fn v_minus_qc_k<const FMA: bool>(
q: &[f64],
n: usize,
k: usize,
c: &[f64],
v: &mut [f64],
mut next: Option<&mut [f64]>,
) -> f64 {
debug_assert!(q.len() >= n * k && v.len() == n && c.len() >= k);
if let Some(nx) = next.as_deref_mut() {
nx[..k].fill(0.0);
}
let mut vv = 0.0;
let mut start = 0;
while start < n {
let end = (start + BLOCK).min(n);
let vb = &mut v[start..end];
for (j, &cj) in c[..k].iter().enumerate() {
axpy_k::<FMA>(-cj, &q[j * n + start..j * n + end], vb);
}
if let Some(nx) = next.as_deref_mut() {
for (j, nj) in nx[..k].iter_mut().enumerate() {
*nj += dot_k::<FMA>(&q[j * n + start..j * n + end], vb);
}
}
vv += dot_k::<FMA>(vb, vb);
start = end;
}
vv
}
#[inline(always)]
fn q_times_k<const FMA: bool>(q: &[f64], n: usize, k: usize, l: &[f64], out: &mut [f64]) {
debug_assert!(q.len() >= n * k && out.len() == n && l.len() >= k);
out.fill(0.0);
let mut start = 0;
while start < n {
let end = (start + BLOCK).min(n);
let ob = &mut out[start..end];
for (j, &lj) in l[..k].iter().enumerate() {
axpy_k::<FMA>(lj, &q[j * n + start..j * n + end], ob);
}
start = end;
}
}
dispatch! {
fn qt_v / qt_v_fma = qt_v_k(q: &[f64], n: usize, k: usize, v: &[f64], c: &mut [f64]) -> f64
}
dispatch! {
fn v_minus_qc / v_minus_qc_fma = v_minus_qc_k(q: &[f64], n: usize, k: usize, c: &[f64], v: &mut [f64], next: Option<&mut [f64]>) -> f64
}
dispatch! {
fn q_times / q_times_fma = q_times_k(q: &[f64], n: usize, k: usize, l: &[f64], out: &mut [f64])
}
pub(crate) fn all_finite(x: &[f64]) -> bool {
x.iter().all(|v| v.is_finite())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn kernels() {
let x = [1.0, -2.0, 3.0];
let mut y = [4.0, 5.0, 6.0];
assert_eq!(dot(&x, &y), 4.0 - 10.0 + 18.0);
axpy(2.0, &x, &mut y);
assert_eq!(y, [6.0, 1.0, 12.0]);
scale(0.5, &mut y);
assert_eq!(y, [3.0, 0.5, 6.0]);
assert!((nrm2(&[3.0, 4.0]) - 5.0).abs() < 1e-15);
assert_eq!(nrm2(&[0.0, 0.0]), 0.0);
assert!((wrms(&[1.0, 2.0], &[2.0, 1.0]) - 2.0).abs() < 1e-15);
}
#[test]
fn nrm2_extreme_scales() {
assert!((nrm2(&[3e200, 4e200]) / 5e200 - 1.0).abs() < 1e-15);
assert!((nrm2(&[3e-200, 4e-200]) / 5e-200 - 1.0).abs() < 1e-15);
assert!(nrm2(&[1.0, f64::NAN]).is_nan());
assert!(
nrm2(&[f64::NAN, f64::NAN]).is_nan(),
"all-NaN must not look like zero"
);
assert!(!all_finite(&[1.0, f64::NAN]));
}
}