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
//! Ranking the products of a BLAS matrix multiply: exact L2 search on the CPU, with the products computed
//! by NumPy's `@` (Accelerate on a Mac) and ranked here.

use rayon::prelude::*;

use super::Result;
use super::kernels::TopK;

/// One IVF list's products for `push_l2_lists`: products (rows x m), norms (m), ids (m), rows.
pub type ListProducts<'a> = (&'a [f32], &'a [f32], &'a [i64], &'a [i64]);

/// The best k of each query's L2 distances, kept across blocks of base vectors: for each block, `push_l2`
/// takes the queries' products with the block's vectors and the vectors' squared norms, and ranks by
/// |x|^2 - 2 q.x (|q|^2 is the same for all of a query's candidates). The queries' rows are split over
/// threads.
pub struct L2TopK {
    tops: Vec<TopK>,
}

impl L2TopK {
    pub fn new(nq: usize, k: usize) -> Result<Self> {
        if k == 0 {
            return Err("need k > 0".into());
        }
        Ok(L2TopK {
            tops: (0..nq).map(|_| TopK::new(k)).collect(),
        })
    }

    /// One block: `p` (nq rows of m), the products of the queries with base vectors `offset` to
    /// `offset + m`; `norms` (m), their squared norms.
    pub fn push_l2(&mut self, p: &[f32], norms: &[f32], offset: usize) -> Result<()> {
        let m = norms.len();
        if m == 0 || p.len() != self.tops.len() * m {
            return Err("prod must be (nq, len(norms))".into());
        }
        self.tops
            .par_iter_mut()
            .zip(p.par_chunks(m))
            .for_each(|(top, row)| {
                for (j, (&pv, &n)) in row.iter().zip(norms).enumerate() {
                    top.push(n - 2.0 * pv, (offset + j) as u32);
                }
            });
        Ok(())
    }

    /// A group of IVF lists, each given as its products with the queries `rows` (distinct within a list),
    /// its vectors' squared norms and their ids in the base. The lists are ranked in parallel, each into its
    /// own best k per query, which are then merged into the queries' best k.
    pub fn push_l2_lists(&mut self, lists: &[ListProducts<'_>]) -> Result<()> {
        let nq = self.tops.len();
        for &(p, nm, id, rs) in lists {
            if id.len() != nm.len()
                || p.len() != rs.len() * nm.len()
                || rs.iter().any(|&r| r < 0 || r as usize >= nq)
            {
                return Err("each prod must be (len(rows), m), ids (m,), rows in range".into());
            }
        }
        let k = self.tops.first().map_or(1, |t| t.dist.len());
        let parts: Vec<Vec<(usize, TopK)>> = lists
            .par_iter()
            .map(|&(p, nm, id, rs)| {
                let m = nm.len();
                if m == 0 {
                    return Vec::new();
                }
                rs.iter()
                    .zip(p.chunks_exact(m))
                    .map(|(&r, row)| {
                        let mut t = TopK::new(k);
                        for ((&pv, &nv), &i) in row.iter().zip(nm).zip(id) {
                            t.push(nv - 2.0 * pv, i as u32);
                        }
                        (r as usize, t)
                    })
                    .collect()
            })
            .collect();
        for (r, t) in parts.iter().flatten() {
            for (&v, &i) in t.dist.iter().zip(&t.idx) {
                self.tops[*r].push(v, i);
            }
        }
        Ok(())
    }

    /// The indices of each query's k nearest, flattened, nearest first.
    pub fn result(&self) -> Vec<u32> {
        self.tops
            .iter()
            .flat_map(|t| t.idx.iter().copied())
            .collect()
    }
}

/// The batch size from which exact L2 and inner product go through the BLAS (`crate::blas`), where one is linked;
/// below it, siann's own kernel. On an M3 Max, SIFT1M, the kernel ran 1.25 times Accelerate at one query, the two
/// level at 10, Accelerate 2.6-3.2 times the kernel from 100; on 4 Linux ARM CPUs, siann's OpenBLAS led the kernel
/// at every batch size, 1.9 times at one query (benchmarks/cpu_blas.py).
pub const BLAS_FROM: usize = if cfg!(target_os = "macos") { 10 } else { 1 };

/// The query tile and base block exact search through BLAS takes for `nq` queries: up to 512 queries, and a block
/// of about 2^22 products (16 MB), rounded down to a power of two. Products of 4-8 million values were fast on SIFT
/// and GloVe; smaller ones pay per-call overhead, larger ones fall out of cache (BENCHMARKS.md).
pub fn default_tiles(nq: usize) -> (usize, usize) {
    let qtile = nq.clamp(1, 512);
    let target = (1usize << 22) / qtile;
    (qtile, 1usize << (usize::BITS - 1 - target.leading_zeros()))
}

/// Exact L2 by the products of a BLAS matrix multiply (`crate::blas`), ranked by |x|^2 - 2 q.x: for each tile of
/// queries and block of the base, one multiply, then the top-k update. `norms` are the base vectors' squared norms
/// (zeros for inner product, ranked by -q.x). The indices of each query's k nearest, flattened, nearest first.
/// A BLAS that runs its own threads (Accelerate) takes each block in turn, the ranking spread over the queries; a
/// single-threaded one (siann's OpenBLAS) is called from siann's threads, each taking blocks of the base (at least
/// four per thread) and keeping its own best k, merged at the end: the same results either way, since equal
/// distances are kept by index whatever the order.
pub fn exact_blas(x: &[f32], norms: &[f32], d: usize, q: &[f32], k: usize) -> Result<Vec<u32>> {
    if d == 0 || x.len() != norms.len() * d || !q.len().is_multiple_of(d) {
        return Err("x must be (n, d), norms (n,), q rows of d".into());
    }
    let (n, nq) = (norms.len(), q.len() / d);
    let (qtile, block) = default_tiles(nq);
    let mut out = Vec::with_capacity(nq * k);
    if crate::blas::THREADED {
        let mut p = vec![0.0f32; qtile * block.min(n.max(1))];
        for s in (0..nq).step_by(qtile) {
            let qs = &q[s * d..(s + qtile).min(nq) * d];
            let rows = qs.len() / d;
            let mut top = L2TopK::new(rows, k)?;
            for b in (0..n).step_by(block) {
                let e = (b + block).min(n);
                let buf = &mut p[..rows * (e - b)];
                crate::blas::products(qs, &x[b * d..e * d], d, buf)?;
                top.push_l2(buf, &norms[b..e], b)?;
            }
            out.extend(top.result());
        }
        return Ok(out);
    }
    let threads = rayon::current_num_threads().max(1);
    let block = block.min(n.div_ceil(4 * threads)).max(1);
    for s in (0..nq).step_by(qtile) {
        let qs = &q[s * d..(s + qtile).min(nq) * d];
        let rows = qs.len() / d;
        let starts: Vec<usize> = (0..n).step_by(block).collect();
        // each of rayon's jobs keeps one products buffer and one best-k per query across the blocks it takes
        let fresh = || {
            (
                Vec::<f32>::new(),
                (0..rows).map(|_| TopK::new(k)).collect::<Vec<TopK>>(),
            )
        };
        let tops = starts
            .par_iter()
            .try_fold(
                fresh,
                |(mut p, mut tops), &b| -> Result<(Vec<f32>, Vec<TopK>)> {
                    let e = (b + block).min(n);
                    p.resize(rows * (e - b), 0.0);
                    crate::blas::products(qs, &x[b * d..e * d], d, &mut p)?;
                    for (top, row) in tops.iter_mut().zip(p.chunks(e - b)) {
                        for (j, (&pv, &nv)) in row.iter().zip(&norms[b..e]).enumerate() {
                            top.push(nv - 2.0 * pv, (b + j) as u32);
                        }
                    }
                    Ok((p, tops))
                },
            )
            .map(|r| r.map(|(_, tops)| tops))
            .try_reduce(
                || (0..rows).map(|_| TopK::new(k)).collect(),
                |mut a, b| {
                    for (ta, tb) in a.iter_mut().zip(b) {
                        for (&v, &i) in tb.dist.iter().zip(&tb.idx) {
                            if i != u32::MAX {
                                ta.push(v, i);
                            }
                        }
                    }
                    Ok(a)
                },
            )?;
        out.extend(tops.iter().flat_map(|t| t.idx.iter().copied()));
    }
    Ok(out)
}