siann 1.0.0

Serve nearest-neighbor indexes built by the siann Python package (exact, IVF, CAGRA graphs) from Rust, on the CPU, with the same results
Documentation
//! The matrix multiply that exact L2 and inner-product search rest on, through a BLAS: on macOS, Apple's Accelerate
//! (part of the operating system, which uses the chip's matrix units, and runs its own threads); elsewhere, with the
//! `openblas` feature, OpenBLAS built single-threaded and linked statically (`build.rs`), called from siann's own
//! threads, so that no BLAS thread pool runs, or spins, beside them. This is the only module of the crate with
//! `unsafe` code: calls into a C library, each behind a safe function that checks every shape and length first.
//! Where no BLAS is linked, `available()` is false and the callers use siann's own kernels.

use super::Result;

#[cfg(any(target_os = "macos", feature = "openblas"))]
#[allow(unsafe_code)]
mod ffi {
    // CBLAS's constants (cblas.h)
    pub const ROW_MAJOR: i32 = 101;
    pub const NO_TRANS: i32 = 111;
    pub const TRANS: i32 = 112;

    #[cfg_attr(target_os = "macos", link(name = "Accelerate", kind = "framework"))]
    unsafe extern "C" {
        #[allow(clippy::too_many_arguments)]
        pub fn cblas_sgemm(
            order: i32,
            trans_a: i32,
            trans_b: i32,
            m: i32,
            n: i32,
            k: i32,
            alpha: f32,
            a: *const f32,
            lda: i32,
            b: *const f32,
            ldb: i32,
            beta: f32,
            c: *mut f32,
            ldc: i32,
        );

        #[allow(clippy::too_many_arguments)]
        pub fn cblas_sgemv(
            order: i32,
            trans: i32,
            m: i32,
            n: i32,
            alpha: f32,
            a: *const f32,
            lda: i32,
            x: *const f32,
            incx: i32,
            beta: f32,
            y: *mut f32,
            incy: i32,
        );
    }
}

/// Whether a BLAS is linked (Accelerate on macOS; OpenBLAS with the `openblas` feature).
pub fn available() -> bool {
    cfg!(any(target_os = "macos", feature = "openblas"))
}

/// Whether the BLAS runs its own threads (Accelerate), so that one call takes a whole tile; OpenBLAS, built
/// single-threaded, is called from siann's threads instead.
pub const THREADED: bool = cfg!(target_os = "macos");

/// `out` (m x n) = `a` (m x d) times `b` (n x d) transposed, all row-major: each query's products with each base
/// vector, as NumPy's `a @ b.T` computes them.
pub fn products(a: &[f32], b: &[f32], d: usize, out: &mut [f32]) -> Result<()> {
    if d == 0 || !a.len().is_multiple_of(d) || !b.len().is_multiple_of(d) {
        return Err("a and b must hold rows of d values".into());
    }
    let (m, n) = (a.len() / d, b.len() / d);
    if out.len() != m * n {
        return Err("out must hold m x n values".into());
    }
    if m == 0 || n == 0 {
        return Ok(());
    }
    let fits = |v: usize| i32::try_from(v).is_ok();
    if !(fits(m) && fits(n) && fits(d)) {
        return Err("a matrix dimension beyond BLAS's 32-bit sizes".into());
    }
    sgemm_nt(a, b, m, n, d, out)
}

#[cfg(any(target_os = "macos", feature = "openblas"))]
#[allow(unsafe_code)]
fn sgemm_nt(a: &[f32], b: &[f32], m: usize, n: usize, d: usize, out: &mut [f32]) -> Result<()> {
    if m == 1 {
        // one query: a matrix-vector product, which BLAS libraries take a faster path for (OpenBLAS's sgemm with
        // one row ran 2.5 times slower than its sgemv on 200,000 x 128)
        // SAFETY: `products` checked that b holds n rows of d values, a (one row) d values and out n, and that n
        // and d fit in i32. Row-major, no transpose, lda = d: reads exactly b's n x d elements and a's d, writes
        // exactly out's n; the slices are borrowed for the call, out exclusively, and no pointer outlives it.
        unsafe {
            ffi::cblas_sgemv(
                ffi::ROW_MAJOR,
                ffi::NO_TRANS,
                n as i32,
                d as i32,
                1.0,
                b.as_ptr(),
                d as i32,
                a.as_ptr(),
                1,
                0.0,
                out.as_mut_ptr(),
                1,
            );
        }
        return Ok(());
    }
    // SAFETY: `products` checked that a holds m rows of d values, b n rows of d, and out m x n, and that m, n
    // and d fit in i32. Row-major with lda = d, ldb = d (b transposed) and ldc = n reads exactly those elements
    // of a and b and writes exactly those of out; the slices are borrowed for the call, out exclusively, and
    // cblas_sgemm keeps no pointer after it returns. OpenBLAS built with USE_LOCKING=1 may be called from several
    // threads at once.
    unsafe {
        ffi::cblas_sgemm(
            ffi::ROW_MAJOR,
            ffi::NO_TRANS,
            ffi::TRANS,
            m as i32,
            n as i32,
            d as i32,
            1.0,
            a.as_ptr(),
            d as i32,
            b.as_ptr(),
            d as i32,
            0.0,
            out.as_mut_ptr(),
            n as i32,
        );
    }
    Ok(())
}

#[cfg(not(any(target_os = "macos", feature = "openblas")))]
fn sgemm_nt(
    _a: &[f32],
    _b: &[f32],
    _m: usize,
    _n: usize,
    _d: usize,
    _out: &mut [f32],
) -> Result<()> {
    Err("no BLAS is linked on this platform".into())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn products_match_plain_loops() {
        if !available() {
            return;
        }
        let (m, n, d) = (7, 13, 5);
        let a: Vec<f32> = (0..m * d).map(|i| ((i * 7 % 11) as f32) - 5.0).collect();
        let b: Vec<f32> = (0..n * d).map(|i| ((i * 3 % 13) as f32) * 0.5).collect();
        let mut out = vec![0.0; m * n];
        products(&a, &b, d, &mut out).unwrap();
        for i in 0..m {
            for j in 0..n {
                let want: f32 = (0..d).map(|t| a[i * d + t] * b[j * d + t]).sum();
                assert!((out[i * n + j] - want).abs() < 1e-4, "{i} {j}");
            }
        }
        // one query: the matrix-vector path
        let mut one = vec![0.0; n];
        products(&a[..d], &b, d, &mut one).unwrap();
        for j in 0..n {
            let want: f32 = (0..d).map(|t| a[t] * b[j * d + t]).sum();
            assert!((one[j] - want).abs() < 1e-4, "{j}");
        }
        assert!(products(&a, &b, 4, &mut out).is_err());
        assert!(products(&a, &b, d, &mut out[..5]).is_err());
    }
}