use rayon::prelude::*;
use std::cell::RefCell;
use std::cmp::Ordering;
use std::collections::BinaryHeap;
use super::Result;
use super::elem::Elem;
use super::ivf::split_pool;
use super::metric::{Kind, Metric, with_metric};
const LANES: usize = 16;
const SMALL_BATCH: usize = 64;
const ENTRIES: usize = 256;
const TOUCH_ALL_BYTES: usize = 32 * 1024;
pub const MAX_DEGREE: usize = 128;
pub enum Rows {
F32(std::sync::Arc<[f32]>),
F16(Vec<u16>),
U8(Vec<u8>),
}
impl Rows {
pub fn half(x: &[f32]) -> Option<Rows> {
let h: Vec<u16> = x.iter().map(|&v| super::elem::narrow_half(v)).collect();
h.iter()
.all(|&b| b & 0x7c00 != 0x7c00)
.then_some(Rows::F16(h))
}
}
#[derive(Clone, Copy, PartialEq)]
struct Near(f32, u32);
impl Eq for Near {}
impl PartialOrd for Near {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Near {
fn cmp(&self, other: &Self) -> Ordering {
self.0.total_cmp(&other.0).then(self.1.cmp(&other.1))
}
}
#[inline]
fn row_dist<M: Metric, T: Elem>(q: &[f32], x: &[T]) -> f32 {
let mut acc = [0.0f32; LANES];
let (q16, q_rest) = q.as_chunks::<LANES>();
let (x16, x_rest) = x.as_chunks::<LANES>();
for (qs, xs) in q16.iter().zip(x16) {
for l in 0..LANES {
acc[l] = M::combine(acc[l], qs[l], T::lane(xs[l]));
}
}
for (l, (&a, &b)) in q_rest.iter().zip(x_rest).enumerate() {
acc[l] = M::combine(acc[l], a, T::lane(b));
}
let mut out = acc[0];
for &v in &acc[1..] {
out = M::join(out, v);
}
out
}
const GROUP: usize = 4;
const GROUP_LANES: usize = 8;
#[inline]
fn rows_dist<M: Metric, T: Elem>(q: &[f32], xs: [&[T]; GROUP]) -> [f32; GROUP] {
#[inline(always)]
fn step<M: Metric, T: Elem>(
acc: &mut [f32; GROUP_LANES],
qs: &[f32; GROUP_LANES],
xs: &[T; GROUP_LANES],
) {
for l in 0..GROUP_LANES {
acc[l] = M::combine(acc[l], qs[l], T::lane(xs[l]));
}
}
let (q8, q_rest) = q.as_chunks::<GROUP_LANES>();
let rows = xs.map(|x| x.as_chunks::<GROUP_LANES>());
let (mut a0, mut a1, mut a2, mut a3) = (
[0.0f32; GROUP_LANES],
[0.0f32; GROUP_LANES],
[0.0f32; GROUP_LANES],
[0.0f32; GROUP_LANES],
);
for ((((qs, x0), x1), x2), x3) in q8
.iter()
.zip(rows[0].0)
.zip(rows[1].0)
.zip(rows[2].0)
.zip(rows[3].0)
{
step::<M, T>(&mut a0, qs, x0);
step::<M, T>(&mut a1, qs, x1);
step::<M, T>(&mut a2, qs, x2);
step::<M, T>(&mut a3, qs, x3);
}
let mut acc = [a0, a1, a2, a3];
let mut out = [0.0f32; GROUP];
for (g, (_, rest)) in rows.iter().enumerate() {
for (l, (&a, &b)) in q_rest.iter().zip(rest.iter()).enumerate() {
acc[g][l] = M::combine(acc[g][l], a, T::lane(b));
}
let mut v = acc[g][0];
for &a in &acc[g][1..] {
v = M::join(v, a);
}
out[g] = v;
}
out
}
thread_local! {
static WIDE: RefCell<Vec<f32>> = const { RefCell::new(Vec::new()) };
}
#[inline]
fn group_dist<M: Metric, T: Elem>(q: &[f32], xs: [&[T]; GROUP]) -> [f32; GROUP] {
if T::DIRECT {
return rows_dist::<M, T>(q, xs);
}
if let Some(d) = T::fused_rows_dist::<M>(q, xs) {
return d;
}
WIDE.with(|w| {
let mut w = w.borrow_mut();
let d = q.len();
w.resize(GROUP * d, 0.0);
for (out, x) in w.chunks_exact_mut(d.max(1)).zip(xs) {
T::widen_into(x, out);
}
let r = |g: usize| &w[g * d..(g + 1) * d];
rows_dist::<M, f32>(q, [r(0), r(1), r(2), r(3)])
})
}
thread_local! {
static VISITED: RefCell<(u8, Vec<u8>)> = const { RefCell::new((0, Vec::new())) };
}
pub struct Graph {
pub d: usize,
n: usize,
degree: usize,
metric: Kind,
rows: Rows,
links: Vec<u32>,
entries: Vec<u32>,
}
impl Graph {
pub fn new(
x: &[f32],
d: usize,
metric: Kind,
rows: Rows,
links: &[i64],
degree: usize,
) -> Result<Self> {
let n = x.len() / d;
if n == 0 || degree == 0 || degree > MAX_DEGREE || links.len() != n * degree {
return Err(format!(
"links must be (n, degree), n > 0, degree at most {MAX_DEGREE}"
));
}
if links.iter().any(|&l| l < -1 || l >= n as i64) {
return Err("each link must be -1 or a row of x".into());
}
match &rows {
Rows::F32(v) if v.len() != x.len() => {
return Err("rows must have the shape of x".into());
}
Rows::U8(v) if v.len() != x.len() => return Err("rows must have the shape of x".into()),
Rows::F16(v) if v.len() != x.len() => {
return Err("rows must have the shape of x".into());
}
Rows::F16(v) if v.iter().any(|&b| b & 0x7c00 == 0x7c00) => {
return Err("float16 rows must be finite".into());
}
Rows::U8(v) if v.iter().zip(x).any(|(&b, &f)| f32::from(b) != f) => {
return Err("byte rows need x's coordinates to be integers from 0 to 255".into());
}
_ => {}
}
let mut mean = vec![0.0f64; d];
for row in x.chunks_exact(d) {
for (m, &v) in mean.iter_mut().zip(row) {
*m += f64::from(v);
}
}
let mean: Vec<f32> = mean.iter().map(|&m| (m / n as f64) as f32).collect();
let entry = x
.par_chunks(d)
.enumerate()
.map(|(i, row)| Near(row_dist::<super::metric::L2, f32>(&mean, row), i as u32))
.min()
.map_or(0, |b| b.1);
let step = n.div_ceil(ENTRIES - 1).max(1);
let mut entries: Vec<u32> = std::iter::once(entry)
.chain((0..n).step_by(step).map(|i| i as u32))
.collect();
entries.sort_unstable();
entries.dedup();
Ok(Graph {
d,
n,
degree,
metric,
rows,
links: links
.iter()
.map(|&l| if l < 0 { u32::MAX } else { l as u32 })
.collect(),
entries,
})
}
pub fn search(&self, xq: &[f32], k: usize, ef: usize) -> Result<Vec<u32>> {
if k == 0 || ef < k {
return Err("need k > 0 and ef >= k".into());
}
let nq = xq.len() / self.d;
let mut out = vec![u32::MAX; nq * k];
let one = |o: &mut [u32], q: &[f32]| {
with_metric!(self.metric, M => match &self.rows {
Rows::F32(r) => self.one::<M, f32>(r, q, k, ef, o),
Rows::U8(r) => self.one::<M, u8>(r, q, k, ef, o),
Rows::F16(r) => self.one::<M, u16>(r, q, k, ef, o),
})
};
let batch = |out: &mut [u32]| {
out.par_chunks_mut(k)
.zip(xq.par_chunks(self.d))
.for_each(|(o, q)| one(o, q))
};
if nq == 1 {
one(&mut out, xq); } else if nq < SMALL_BATCH {
split_pool(nq.min(rayon::current_num_threads()))?.install(|| batch(&mut out));
} else {
batch(&mut out);
}
Ok(out)
}
fn one<M: Metric, T: Elem>(&self, rows: &[T], q: &[f32], k: usize, ef: usize, out: &mut [u32]) {
let d = self.d;
let q8 = if M::INTEGER {
T::integer_query(q)
} else {
None
};
let dist = |i: u32| -> f32 {
let x = &rows[i as usize * d..(i as usize + 1) * d];
match &q8 {
Some(q8) => T::int_dist::<M>(q8, x) as f32,
None => group_dist::<M, T>(q, [x; GROUP])[0], }
};
VISITED.with(|v| {
let (epoch, seen) = &mut *v.borrow_mut();
if seen.len() < self.n {
seen.resize(self.n, 0);
}
*epoch = epoch.wrapping_add(1);
if *epoch == 0 {
seen.fill(0);
*epoch = 1;
}
let epoch = *epoch;
let mut todo: BinaryHeap<std::cmp::Reverse<Near>> = BinaryHeap::new();
let (mut ids, mut dists) = ([0u32; MAX_DEGREE], [0.0f32; MAX_DEGREE]);
let mut best: BinaryHeap<Near> = BinaryHeap::with_capacity(ef + 1);
let entry_dists: Vec<f32> = if q8.is_none() {
let row = |i: u32| &rows[i as usize * d..(i as usize + 1) * d];
self.entries
.chunks(GROUP)
.flat_map(|g| {
let pick = |j: usize| row(g[j.min(g.len() - 1)]);
group_dist::<M, T>(q, [pick(0), pick(1), pick(2), pick(3)])
.into_iter()
.take(g.len())
})
.collect()
} else {
self.entries.iter().map(|&e| dist(e)).collect()
};
for (&e, &de) in self.entries.iter().zip(&entry_dists) {
let start = Near(de, e);
seen[e as usize] = epoch;
if best.len() < ef || start < *best.peek().unwrap() {
todo.push(std::cmp::Reverse(start));
best.push(start);
if best.len() > ef {
best.pop();
}
}
}
while let Some(std::cmp::Reverse(c)) = todo.pop() {
if best.len() >= ef && c > *best.peek().unwrap() {
break;
}
let mut m = 0;
for &nb in &self.links[c.1 as usize * self.degree..(c.1 as usize + 1) * self.degree]
{
if nb != u32::MAX && seen[nb as usize] != epoch {
seen[nb as usize] = epoch;
ids[m] = nb;
m += 1;
}
}
let line = (64 / std::mem::size_of::<T>()).max(1);
let step = if self.degree * d * std::mem::size_of::<T>() <= TOUCH_ALL_BYTES {
line
} else {
d.max(1)
};
let mut touched = 0.0f32;
for &nb in &ids[..m] {
let row = &rows[nb as usize * d..(nb as usize + 1) * d];
for v in row.iter().step_by(step) {
touched += T::lane(*v);
}
}
std::hint::black_box(touched);
let mut j = 0;
if q8.is_none() {
let row = |i: u32| &rows[i as usize * d..(i as usize + 1) * d];
while j + GROUP <= m {
let g = group_dist::<M, T>(
q,
[
row(ids[j]),
row(ids[j + 1]),
row(ids[j + 2]),
row(ids[j + 3]),
],
);
dists[j..j + GROUP].copy_from_slice(&g);
j += GROUP;
}
}
for k in j..m {
dists[k] = dist(ids[k]);
}
for (&nb, &dv) in ids[..m].iter().zip(&dists[..m]) {
let cand = Near(dv, nb);
if best.len() < ef || cand < *best.peek().unwrap() {
todo.push(std::cmp::Reverse(cand));
best.push(cand);
if best.len() > ef {
best.pop();
}
}
}
}
let found = best.into_sorted_vec();
for (o, c) in out.iter_mut().zip(found.iter().take(k)) {
*o = c.1;
}
});
}
}
pub fn spread_entries(n: usize, width: usize, room: usize) -> Result<Vec<i32>> {
let num = width.min(n);
if num > room {
return Err(format!("room for {room} entries, but {num} are spread"));
}
let mut out = vec![-1i32; room];
if num == 0 {
return Ok(out);
}
let delta = (n - 1) as f64;
let mut rows: Vec<i32> = (0..num)
.map(|i| {
let y = if num > 1 {
let div = (num - 1) as f64;
let step = delta / div;
if step == 0.0 {
(i as f64 / div) * delta
} else {
i as f64 * step
}
} else {
i as f64 * delta
};
y as i32
})
.collect();
if num > 1 {
rows[num - 1] = (n - 1) as i32;
}
rows.sort_unstable();
rows.dedup();
out[..rows.len()].copy_from_slice(&rows);
Ok(out)
}
#[cfg(test)]
mod tests {
use super::{GROUP, rows_dist};
use crate::elem::widen_half;
use crate::metric::{Ip, L1, L2, Linf, Metric};
fn halves(n: usize, seed: u64) -> Vec<u16> {
let mut state = seed;
let mut out = Vec::with_capacity(n);
while out.len() < n {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
let h = (state >> 48) as u16;
if h & 0x7c00 != 0x7c00 {
out.push(h);
}
}
out
}
fn check<M: Metric>() {
for d in [1, 5, 8, 13, 64, 100, 128, 1536] {
let q: Vec<f32> = halves(d, 7).into_iter().map(widen_half).collect();
let rows: Vec<Vec<u16>> = (0..GROUP as u64).map(|g| halves(d, 11 + g)).collect();
let wide: Vec<Vec<f32>> = rows
.iter()
.map(|r| r.iter().map(|&h| widen_half(h)).collect())
.collect();
let want = rows_dist::<M, f32>(&q, [&wide[0], &wide[1], &wide[2], &wide[3]]);
if let Some(got) =
crate::half::rows_dist::<M>(&q, [&rows[0], &rows[1], &rows[2], &rows[3]])
{
for (g, w) in got.iter().zip(&want) {
assert_eq!(g.to_bits(), w.to_bits(), "d {d}: {g} against {w}");
}
}
}
}
#[test]
fn fused_float16_distances_are_the_f32_distances_over_the_rows_widened() {
check::<L2>();
check::<Ip>();
check::<L1>();
check::<Linf>();
}
}