use wide::f32x8;
const BLOCK_SIZE: usize = 64;
#[inline]
pub fn matmul_simd(a: &[f32], b: &[f32], c: &mut [f32], m: usize, k: usize, n: usize) {
debug_assert_eq!(a.len(), m * k, "Matrix A size mismatch");
debug_assert_eq!(b.len(), k * n, "Matrix B size mismatch");
debug_assert_eq!(c.len(), m * n, "Matrix C size mismatch");
c.fill(0.0);
if m * n < 256 || k < 8 {
matmul_scalar(a, b, c, m, k, n);
return;
}
matmul_blocked(a, b, c, m, k, n);
}
#[inline]
pub fn matvec_simd(a: &[f32], x: &[f32], y: &mut [f32], m: usize, n: usize) {
debug_assert_eq!(a.len(), m * n, "Matrix A size mismatch");
debug_assert_eq!(x.len(), n, "Vector x size mismatch");
debug_assert_eq!(y.len(), m, "Vector y size mismatch");
if n < 16 {
matvec_scalar(a, x, y, m, n);
return;
}
for i in 0..m {
let row_start = i * n;
let row = &a[row_start..row_start + n];
y[i] = dot_product_simd(row, x);
}
}
#[inline]
pub fn transpose_simd(a: &[f32], b: &mut [f32], m: usize, n: usize) {
debug_assert_eq!(a.len(), m * n);
debug_assert_eq!(b.len(), m * n);
if m < 8 || n < 8 {
transpose_scalar(a, b, m, n);
return;
}
let block = 8;
for ii in (0..m).step_by(block) {
for jj in (0..n).step_by(block) {
let i_end = (ii + block).min(m);
let j_end = (jj + block).min(n);
for i in ii..i_end {
for j in jj..j_end {
b[j * m + i] = a[i * n + j];
}
}
}
}
}
#[inline]
pub fn outer_product_simd(a: &[f32], b: &[f32], c: &mut [f32]) {
let m = a.len();
let n = b.len();
debug_assert_eq!(c.len(), m * n);
if n < 16 {
for i in 0..m {
for j in 0..n {
c[i * n + j] = a[i] * b[j];
}
}
return;
}
for i in 0..m {
let scalar = a[i];
let scalar_vec = f32x8::splat(scalar);
let row_start = i * n;
let chunks_b = b.chunks_exact(8);
let chunks_c = c[row_start..row_start + n].chunks_exact_mut(8);
let remainder_b = chunks_b.remainder();
let offset = n - remainder_b.len();
for (cb, cc) in chunks_b.zip(chunks_c) {
let vb = load_f32x8(cb);
let result = vb * scalar_vec;
store_f32x8(cc, result);
}
for (j, &bj) in remainder_b.iter().enumerate() {
c[row_start + offset + j] = scalar * bj;
}
}
}
#[inline]
pub fn matadd_simd(a: &[f32], b: &[f32], c: &mut [f32]) {
debug_assert_eq!(a.len(), b.len());
debug_assert_eq!(a.len(), c.len());
let n = a.len();
if n < 16 {
for i in 0..n {
c[i] = a[i] + b[i];
}
return;
}
let chunks_a = a.chunks_exact(8);
let chunks_b = b.chunks_exact(8);
let chunks_c = c.chunks_exact_mut(8);
let remainder_a = chunks_a.remainder();
let remainder_b = chunks_b.remainder();
let offset = n - remainder_a.len();
for ((ca, cb), cc) in chunks_a.zip(chunks_b).zip(chunks_c) {
let va = load_f32x8(ca);
let vb = load_f32x8(cb);
let result = va + vb;
store_f32x8(cc, result);
}
for (i, (&va, &vb)) in remainder_a.iter().zip(remainder_b.iter()).enumerate() {
c[offset + i] = va + vb;
}
}
#[inline]
pub fn matscale_simd(a: &[f32], alpha: f32, b: &mut [f32]) {
debug_assert_eq!(a.len(), b.len());
let n = a.len();
if n < 16 {
for i in 0..n {
b[i] = alpha * a[i];
}
return;
}
let alpha_vec = f32x8::splat(alpha);
let chunks_a = a.chunks_exact(8);
let chunks_b = b.chunks_exact_mut(8);
let remainder_a = chunks_a.remainder();
let offset = n - remainder_a.len();
for (ca, cb) in chunks_a.zip(chunks_b) {
let va = load_f32x8(ca);
let result = va * alpha_vec;
store_f32x8(cb, result);
}
for (i, &va) in remainder_a.iter().enumerate() {
b[offset + i] = alpha * va;
}
}
fn matmul_blocked(a: &[f32], b: &[f32], c: &mut [f32], m: usize, k: usize, n: usize) {
let bk = BLOCK_SIZE.min(k);
let bn = BLOCK_SIZE.min(n);
for kk in (0..k).step_by(bk) {
let k_end = (kk + bk).min(k);
for jj in (0..n).step_by(bn) {
let j_end = (jj + bn).min(n);
for i in 0..m {
let c_row = i * n;
let a_row = i * k;
for kc in kk..k_end {
let a_val = a[a_row + kc];
let a_vec = f32x8::splat(a_val);
let b_row = kc * n;
let mut j = jj;
while j + 8 <= j_end {
let b_chunk = &b[b_row + j..b_row + j + 8];
let c_chunk = &mut c[c_row + j..c_row + j + 8];
let vb = load_f32x8(b_chunk);
let vc = load_f32x8(c_chunk);
let result = a_vec.mul_add(vb, vc);
store_f32x8(c_chunk, result);
j += 8;
}
while j < j_end {
c[c_row + j] += a_val * b[b_row + j];
j += 1;
}
}
}
}
}
}
fn matmul_scalar(a: &[f32], b: &[f32], c: &mut [f32], m: usize, k: usize, n: usize) {
for i in 0..m {
for j in 0..n {
let mut sum = 0.0f32;
for kc in 0..k {
sum += a[i * k + kc] * b[kc * n + j];
}
c[i * n + j] = sum;
}
}
}
fn matvec_scalar(a: &[f32], x: &[f32], y: &mut [f32], m: usize, n: usize) {
for i in 0..m {
let mut sum = 0.0f32;
let row_start = i * n;
for j in 0..n {
sum += a[row_start + j] * x[j];
}
y[i] = sum;
}
}
fn transpose_scalar(a: &[f32], b: &mut [f32], m: usize, n: usize) {
for i in 0..m {
for j in 0..n {
b[j * m + i] = a[i * n + j];
}
}
}
fn dot_product_simd(a: &[f32], b: &[f32]) -> f32 {
let n = a.len();
if n < 16 {
let mut sum = 0.0f32;
for i in 0..n {
sum += a[i] * b[i];
}
return sum;
}
let chunks_a = a.chunks_exact(8);
let chunks_b = b.chunks_exact(8);
let remainder_a = chunks_a.remainder();
let remainder_b = chunks_b.remainder();
let mut acc = f32x8::ZERO;
for (ca, cb) in chunks_a.zip(chunks_b) {
let va = load_f32x8(ca);
let vb = load_f32x8(cb);
acc = va.mul_add(vb, acc);
}
let mut sum = acc.reduce_add();
for (&va, &vb) in remainder_a.iter().zip(remainder_b.iter()) {
sum += va * vb;
}
sum
}
#[inline(always)]
fn load_f32x8(slice: &[f32]) -> f32x8 {
debug_assert!(slice.len() >= 8);
let arr: [f32; 8] = slice[..8].try_into().unwrap();
f32x8::from(arr)
}
#[inline(always)]
fn store_f32x8(slice: &mut [f32], v: f32x8) {
debug_assert!(slice.len() >= 8);
let arr: [f32; 8] = v.into();
slice[..8].copy_from_slice(&arr);
}
#[cfg(test)]
mod tests {
use super::*;
const EPSILON: f32 = 1e-3;
fn approx_eq(a: f32, b: f32) -> bool {
let max_abs = a.abs().max(b.abs());
if max_abs > 1.0 {
(a - b).abs() / max_abs < EPSILON
} else {
(a - b).abs() < EPSILON
}
}
fn matrices_approx_eq(a: &[f32], b: &[f32]) -> bool {
a.len() == b.len() && a.iter().zip(b.iter()).all(|(&x, &y)| approx_eq(x, y))
}
#[test]
fn test_matmul_small() {
let a = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]; let b = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]; let mut c = [0.0f32; 4];
matmul_simd(&a, &b, &mut c, 2, 3, 2);
let expected = [22.0, 28.0, 49.0, 64.0];
assert!(matrices_approx_eq(&c, &expected), "got {:?}", c);
}
#[test]
fn test_matmul_identity() {
let n = 64;
let mut identity = vec![0.0f32; n * n];
for i in 0..n {
identity[i * n + i] = 1.0;
}
let a: Vec<f32> = (0..n * n).map(|i| i as f32).collect();
let mut c = vec![0.0f32; n * n];
matmul_simd(&identity, &a, &mut c, n, n, n);
assert!(matrices_approx_eq(&c, &a));
}
#[test]
fn test_matvec_small() {
let a = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]; let x = [1.0, 2.0, 3.0]; let mut y = [0.0f32; 2];
matvec_simd(&a, &x, &mut y, 2, 3);
let expected = [14.0, 32.0];
assert!(matrices_approx_eq(&y, &expected), "got {:?}", y);
}
#[test]
fn test_matvec_large() {
let m = 64;
let n = 128;
let a: Vec<f32> = (0..m * n).map(|i| (i as f32) * 0.01).collect();
let x: Vec<f32> = (0..n).map(|i| i as f32).collect();
let mut y_simd = vec![0.0f32; m];
let mut y_scalar = vec![0.0f32; m];
matvec_simd(&a, &x, &mut y_simd, m, n);
matvec_scalar(&a, &x, &mut y_scalar, m, n);
assert!(matrices_approx_eq(&y_simd, &y_scalar));
}
#[test]
fn test_transpose_small() {
let a = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]; let mut b = [0.0f32; 6];
transpose_simd(&a, &mut b, 2, 3);
let expected = [1.0, 4.0, 2.0, 5.0, 3.0, 6.0];
assert_eq!(b, expected);
}
#[test]
fn test_transpose_large() {
let m = 32;
let n = 64;
let a: Vec<f32> = (0..m * n).map(|i| i as f32).collect();
let mut b = vec![0.0f32; m * n];
transpose_simd(&a, &mut b, m, n);
for i in 0..m {
for j in 0..n {
assert!(approx_eq(a[i * n + j], b[j * m + i]),
"mismatch at ({}, {})", i, j);
}
}
}
#[test]
fn test_outer_product() {
let a = [1.0, 2.0, 3.0];
let b = [4.0, 5.0];
let mut c = [0.0f32; 6];
outer_product_simd(&a, &b, &mut c);
let expected = [4.0, 5.0, 8.0, 10.0, 12.0, 15.0];
assert!(matrices_approx_eq(&c, &expected));
}
#[test]
fn test_matadd() {
let a = [1.0, 2.0, 3.0, 4.0];
let b = [5.0, 6.0, 7.0, 8.0];
let mut c = [0.0f32; 4];
matadd_simd(&a, &b, &mut c);
assert_eq!(c, [6.0, 8.0, 10.0, 12.0]);
}
#[test]
fn test_matscale() {
let a = [1.0, 2.0, 3.0, 4.0];
let mut b = [0.0f32; 4];
matscale_simd(&a, 2.5, &mut b);
assert!(matrices_approx_eq(&b, &[2.5, 5.0, 7.5, 10.0]));
}
#[test]
fn test_matmul_large() {
let m = 128;
let k = 96;
let n = 64;
let a: Vec<f32> = (0..m * k).map(|i| (i as f32) * 0.001).collect();
let b: Vec<f32> = (0..k * n).map(|i| (i as f32) * 0.001).collect();
let mut c_simd = vec![0.0f32; m * n];
let mut c_scalar = vec![0.0f32; m * n];
matmul_simd(&a, &b, &mut c_simd, m, k, n);
matmul_scalar(&a, &b, &mut c_scalar, m, k, n);
for i in 0..m * n {
assert!((c_simd[i] - c_scalar[i]).abs() < 0.01,
"mismatch at {}: {} vs {}", i, c_simd[i], c_scalar[i]);
}
}
}