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
//! float16 values (their bits, `u16`) widened to f32 with the processor's own conversion instruction: `fcvtl` on
//! ARM (every 64-bit ARM processor has it), `vcvtph2ps` (F16C) on x86-64 where the processor has it (every
//! x86-64-v3 processor, which siann's x86-64 wheels require; checked at run time for builds from source). Without
//! either, `elem::widen_half`'s exact bit arithmetic, which takes about as many instructions as a distance does,
//! so that a single query over float16 rows ran at half float32's speed (DBpedia, 1,536 dimensions). Every
//! finite float16 widens to the same f32 by each route (the conversion is exact), which the tests check for all
//! of them. With `blas`, the only module of the crate with `unsafe` code: the instructions, behind `widen`, which
//! checks the lengths first.

use super::elem::widen_half;
use super::metric::{Kind, Metric};

/// Coordinates per chunk of the fused distances, and running sums per row: as `graph::rows_dist`'s
/// `GROUP_LANES`, so that the two sum in the same order.
pub const LANES: usize = 8;

/// The distances from `q` to four float16 rows (each `q.len()` long), converted and summed in one pass, in the
/// order `graph::rows_dist` sums f32 rows (`LANES` running sums per row over the full chunks, by the metric's
/// own operations, then the remaining coordinates, then the sums joined in order), so that each distance is
/// the one `graph::rows_dist` gives over the rows widened. None where the processor has no conversion
/// instruction (the caller widens the rows first instead).
pub fn rows_dist<M: Metric>(q: &[f32], xs: [&[u16]; 4]) -> Option<[f32; 4]> {
    let d = q.len();
    assert!(
        xs.iter().all(|x| x.len() == d),
        "rows_dist: every row must be as long as q"
    );
    let full = d / LANES * LANES;
    let mut acc = simd::rows_acc(M::KIND, &q[..full], xs.map(|x| &x[..full]))?;
    let mut out = [0.0f32; 4];
    for (g, x) in xs.iter().enumerate() {
        for (l, (&a, &b)) in q[full..].iter().zip(&x[full..]).enumerate() {
            acc[g][l] = M::combine(acc[g][l], a, widen_half(b));
        }
        let mut v = acc[g][0];
        for &a in &acc[g][1..] {
            v = M::join(v, a);
        }
        out[g] = v;
    }
    Some(out)
}

/// `src` widened to f32 into `dst` (the same length). `src` must hold finite values (exponent bits below 31), as
/// float16 rows do: the instruction would widen infinity and NaN to themselves, the bit arithmetic not.
pub fn widen(src: &[u16], dst: &mut [f32]) {
    assert_eq!(
        src.len(),
        dst.len(),
        "widen: src and dst must have the same length"
    );
    let done = simd::widen(src, dst);
    for (o, &h) in dst[done..].iter_mut().zip(&src[done..]) {
        *o = widen_half(h);
    }
}

#[cfg(target_arch = "aarch64")]
#[allow(unsafe_code)]
mod simd {
    use super::{Kind, LANES};
    use std::arch::aarch64::{
        float32x4_t, uint16x8_t, vabsq_f32, vaddq_f32, vbslq_f32, vcgtq_f32, vdupq_n_f32,
        vld1q_f32, vld1q_u16, vmulq_f32, vst1q_f32, vsubq_f32,
    };
    use std::arch::asm;

    /// Eight float16 values at `p` as two f32 vectors (lanes 0-3, 4-7).
    ///
    /// # Safety
    /// `p` must point to 8 readable u16.
    #[inline(always)]
    unsafe fn load8(p: *const u16) -> (float32x4_t, float32x4_t) {
        // SAFETY: the caller's: 8 readable u16 at `p`; `fcvtl` and `fcvtl2` only read and write the named
        // vector registers.
        unsafe {
            let h: uint16x8_t = vld1q_u16(p);
            let lo: float32x4_t;
            let hi: float32x4_t;
            asm!(
                "fcvtl {lo:v}.4s, {h:v}.4h",
                "fcvtl2 {hi:v}.4s, {h:v}.8h",
                h = in(vreg) h,
                lo = out(vreg) lo,
                hi = out(vreg) hi,
                options(pure, nomem, nostack),
            );
            (lo, hi)
        }
    }

    /// Each row's `LANES` running sums over `q` (a multiple of `LANES` long) and the rows (as long), by `kind`'s
    /// operations as `Metric::combine` applies them, lane by lane.
    pub fn rows_acc(kind: Kind, q: &[f32], xs: [&[u16]; 4]) -> Option<[[f32; LANES]; 4]> {
        let n = q.len() / LANES;
        if xs.iter().any(|x| x.len() < n * LANES) {
            return None;
        }
        // one loop per metric, so that the choice is made once
        macro_rules! run {
            ($step:expr) => {{
                // SAFETY: zero vectors; no memory touched.
                let z = unsafe { vdupq_n_f32(0.0) };
                let mut acc = [[z; 2]; 4];
                for c in 0..n {
                    // SAFETY: q holds n * LANES f32 and each row at least as many u16 (checked above), and
                    // c < n, so the loads at c * LANES read 8 values within each; the metric's step is
                    // register arithmetic only.
                    unsafe {
                        let qp = q.as_ptr().add(c * LANES);
                        let (q0, q1) = (vld1q_f32(qp), vld1q_f32(qp.add(4)));
                        for (g, x) in xs.iter().enumerate() {
                            let (x0, x1) = load8(x.as_ptr().add(c * LANES));
                            acc[g][0] = $step(acc[g][0], q0, x0);
                            acc[g][1] = $step(acc[g][1], q1, x1);
                        }
                    }
                }
                let mut out = [[0.0f32; LANES]; 4];
                for (o, a) in out.iter_mut().zip(&acc) {
                    // SAFETY: `o` holds 8 f32: two stores of 4 within it.
                    unsafe {
                        vst1q_f32(o.as_mut_ptr(), a[0]);
                        vst1q_f32(o.as_mut_ptr().add(4), a[1]);
                    }
                }
                Some(out)
            }};
        }
        // each step: register arithmetic only, run inside the loop's unsafe block (NEON being part of every
        // aarch64 target)
        match kind {
            Kind::L2 => run!(|a, q, x| {
                let e = vsubq_f32(q, x);
                vaddq_f32(a, vmulq_f32(e, e))
            }),
            Kind::Ip => run!(|a, q, x| vsubq_f32(a, vmulq_f32(q, x))),
            Kind::L1 => run!(|a, q, x| vaddq_f32(a, vabsq_f32(vsubq_f32(q, x)))),
            Kind::Linf => run!(|a, q, x| {
                let t = vabsq_f32(vsubq_f32(q, x));
                vbslq_f32(vcgtq_f32(t, a), t, a) // `larger`: t where t > a, else a
            }),
        }
    }

    /// The first multiple of 8 values of `src` into `dst`, eight at a time; returns how many.
    pub fn widen(src: &[u16], dst: &mut [f32]) -> usize {
        let (s8, d8) = (src.as_chunks::<8>().0, dst.as_chunks_mut::<8>().0);
        let n = s8.len().min(d8.len()) * 8;
        for (s, d) in s8.iter().zip(d8.iter_mut()) {
            // SAFETY: NEON is part of every aarch64 target Rust supports; `s` holds 8 u16 and `d` 8 f32 (fixed-size
            // arrays), so the load reads and the stores write within them; `fcvtl` and `fcvtl2` only read
            // and write the named vector registers.
            unsafe {
                let h: uint16x8_t = vld1q_u16(s.as_ptr());
                let lo: float32x4_t;
                let hi: float32x4_t;
                asm!(
                    "fcvtl {lo:v}.4s, {h:v}.4h",
                    "fcvtl2 {hi:v}.4s, {h:v}.8h",
                    h = in(vreg) h,
                    lo = out(vreg) lo,
                    hi = out(vreg) hi,
                    options(pure, nomem, nostack),
                );
                vst1q_f32(d.as_mut_ptr(), lo);
                vst1q_f32(d.as_mut_ptr().add(4), hi);
            }
        }
        n
    }
}

#[cfg(target_arch = "x86_64")]
#[allow(unsafe_code)]
mod simd {
    use super::{Kind, LANES};
    use std::arch::x86_64::{
        __m128i, __m256, _CMP_GT_OQ, _mm_loadu_si128, _mm256_add_ps, _mm256_andnot_ps,
        _mm256_blendv_ps, _mm256_cmp_ps, _mm256_cvtph_ps, _mm256_loadu_ps, _mm256_mul_ps,
        _mm256_set1_ps, _mm256_setzero_ps, _mm256_storeu_ps, _mm256_sub_ps,
    };

    /// Each row's `LANES` running sums (one AVX vector) over `q` (a multiple of `LANES` long) and the rows, by
    /// `kind`'s operations as `Metric::combine` applies them; None without F16C.
    pub fn rows_acc(kind: Kind, q: &[f32], xs: [&[u16]; 4]) -> Option<[[f32; LANES]; 4]> {
        if !std::arch::is_x86_feature_detected!("f16c")
            || xs.iter().any(|x| x.len() < q.len() / LANES * LANES)
        {
            return None;
        }
        // SAFETY: the processor has F16C and AVX (F16C implies it), checked above; the lengths too.
        Some(unsafe { rows_acc_f16c(kind, q, xs) })
    }

    #[target_feature(enable = "f16c,avx")]
    fn rows_acc_f16c(kind: Kind, q: &[f32], xs: [&[u16]; 4]) -> [[f32; LANES]; 4] {
        let n = q.len() / LANES;
        macro_rules! run {
            ($step:expr) => {{
                let mut acc = [_mm256_setzero_ps(); 4];
                for c in 0..n {
                    // SAFETY: q holds n * LANES f32 and each row at least as many u16 (checked by the caller),
                    // and c < n, so the unaligned loads at c * LANES read 8 values within each.
                    unsafe {
                        let qv = _mm256_loadu_ps(q.as_ptr().add(c * LANES));
                        for (g, x) in xs.iter().enumerate() {
                            let h = _mm_loadu_si128(x.as_ptr().add(c * LANES).cast::<__m128i>());
                            acc[g] = $step(acc[g], qv, _mm256_cvtph_ps(h));
                        }
                    }
                }
                let mut out = [[0.0f32; LANES]; 4];
                for (o, a) in out.iter_mut().zip(acc) {
                    // SAFETY: `o` holds 8 f32: one unaligned store of 8 within it.
                    unsafe { _mm256_storeu_ps(o.as_mut_ptr(), a) };
                }
                out
            }};
        }
        let sign = _mm256_set1_ps(-0.0);
        let abs = |v: __m256| _mm256_andnot_ps(sign, v);
        match kind {
            Kind::L2 => run!(|a, q, x| {
                let e = _mm256_sub_ps(q, x);
                _mm256_add_ps(a, _mm256_mul_ps(e, e))
            }),
            Kind::Ip => run!(|a, q, x| _mm256_sub_ps(a, _mm256_mul_ps(q, x))),
            Kind::L1 => run!(|a, q, x| _mm256_add_ps(a, abs(_mm256_sub_ps(q, x)))),
            Kind::Linf => run!(|a, q, x| {
                let t = abs(_mm256_sub_ps(q, x));
                _mm256_blendv_ps(a, t, _mm256_cmp_ps::<_CMP_GT_OQ>(t, a)) // `larger`: t where t > a, else a
            }),
        }
    }

    /// The first multiple of 8 values of `src` into `dst` where the processor has F16C (else none); returns how
    /// many.
    pub fn widen(src: &[u16], dst: &mut [f32]) -> usize {
        if !std::arch::is_x86_feature_detected!("f16c") {
            return 0;
        }
        // SAFETY: the processor has F16C and AVX (F16C implies it), checked just above.
        unsafe { widen_f16c(src, dst) }
    }

    #[target_feature(enable = "f16c,avx")]
    fn widen_f16c(src: &[u16], dst: &mut [f32]) -> usize {
        let (s8, d8) = (src.as_chunks::<8>().0, dst.as_chunks_mut::<8>().0);
        let n = s8.len().min(d8.len()) * 8;
        for (s, d) in s8.iter().zip(d8.iter_mut()) {
            // SAFETY: `s` holds 8 u16 (16 bytes) and `d` 8 f32 (32 bytes), fixed-size arrays, so the
            // unaligned load reads and the unaligned store writes within them.
            unsafe {
                let h = _mm_loadu_si128(s.as_ptr().cast::<__m128i>());
                _mm256_storeu_ps(d.as_mut_ptr(), _mm256_cvtph_ps(h));
            }
        }
        n
    }
}

#[cfg(not(any(target_arch = "aarch64", target_arch = "x86_64")))]
mod simd {
    use super::{Kind, LANES};

    /// No conversion instruction here: none widened.
    pub fn widen(_src: &[u16], _dst: &mut [f32]) -> usize {
        0
    }

    /// No conversion instruction here: None.
    pub fn rows_acc(_kind: Kind, _q: &[f32], _xs: [&[u16]; 4]) -> Option<[[f32; LANES]; 4]> {
        None
    }
}

#[cfg(test)]
mod tests {
    use super::{widen, widen_half};

    #[test]
    fn every_finite_float16_widens_as_the_bit_arithmetic_does() {
        let finite: Vec<u16> = (0..=u16::MAX).filter(|&h| h & 0x7c00 != 0x7c00).collect();
        for len in [finite.len(), 1, 7, 8, 9, 15, 17, 1000] {
            let src = &finite[finite.len() - len..];
            let mut got = vec![0.0f32; len];
            widen(src, &mut got);
            for (&h, &g) in src.iter().zip(&got) {
                assert_eq!(
                    g.to_bits(),
                    widen_half(h).to_bits(),
                    "float16 bits {h:#06x}"
                );
            }
        }
    }

    #[test]
    #[should_panic(expected = "same length")]
    fn lengths_are_checked() {
        widen(&[0; 8], &mut [0.0; 7]);
    }
}