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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! Search of a proximity graph on the CPU: each vector linked to `degree` near ones (a CAGRA graph, built on
//! the GPU by mlxvs or cuVS), searched best first from a spread set of entry vectors (as CAGRA starts from
//! many: a graph's clusters need not be linked to each other), keeping the `ef` nearest found so far,
//! as HNSW searches its bottom layer. One thread per query; a query's visited vectors are marked in a
//! per-thread array of epochs, so that nothing is cleared between queries.

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};

/// Lanes of running distances over a row: independent sums the compiler maps onto vector instructions.
const LANES: usize = 16;
/// Batches below this many queries run on a pool of their own, a thread per query up to the cores.
const SMALL_BATCH: usize = 64;
/// Entry vectors every search starts from: the one nearest the mean, and the rest spread evenly through the rows.
const ENTRIES: usize = 256;
/// Rows a node's neighbors span, at most, for the search to touch every cache line of each before computing
/// distances: within a first-level data cache (32-128 KB on current processors). Above it (1,536-dimension
/// float32 rows at 32 links), touching only each row's first line is 1.45 times faster.
const TOUCH_ALL_BYTES: usize = 32 * 1024;
/// The most links per vector a graph may have (CAGRA's are 32 or 64).
pub const MAX_DEGREE: usize = 128;

/// The vectors as the graph's search reads them: rows of f32 (shared, as the serving index's own copy is), of
/// float16 bits (half the memory a search reads; `elem::narrow_half`), or of bytes (SIFT's integer coordinates).
pub enum Rows {
    F32(std::sync::Arc<[f32]>),
    F16(Vec<u16>),
    U8(Vec<u8>),
}

impl Rows {
    /// x's rows as float16, or None where a coordinate is past float16's range (its largest finite value is
    /// 65,504), which the search could not widen back.
    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))
    }
}

/// A distance and a vector, ordered by distance then id (so that ties do not depend on the search's order).
#[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))
    }
}

/// One row's distance to the query, in `LANES` running sums joined at the end.
#[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
}

/// Rows read at once by `rows_dist`: their memory loads in flight together.
const GROUP: usize = 4;
/// Lanes per row in `rows_dist`: GROUP x GROUP_LANES running sums fit in the vector registers.
const GROUP_LANES: usize = 8;

/// Distances from the query to `GROUP` rows, computed in one interleaved pass, so that the rows' loads from
/// memory overlap (a search reads rows scattered through memory, and is limited by fetching them).
#[inline]
fn rows_dist<M: Metric, T: Elem>(q: &[f32], xs: [&[T]; GROUP]) -> [f32; GROUP] {
    // each row's sums a local array of their own, which the compiler keeps in vector registers (sums indexed in
    // one shared array stayed in memory, a lane at a time: 1.75 times slower at 1,536 dimensions)
    #[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! {
    /// Per thread: `GROUP` rows widened to f32, for storages the distance loop cannot widen in registers.
    static WIDE: RefCell<Vec<f32>> = const { RefCell::new(Vec::new()) };
}

/// `rows_dist` for any storage: rows that widen in registers (f32, bytes) directly; float16 rows converted and
/// summed in one pass by the processor's conversion instruction (`half::rows_dist`), or, without one, widened to
/// f32 first, a row at a time (inside the distance loop the compiler loaded the halves one at a time: single
/// queries over float16 rows at 0.38 times float32's speed on DBpedia; widened first, 0.59 times). Every way sums
/// in the same order, so the distances are the same.
#[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! {
    /// Per thread: the epoch of the current query, and each vector's epoch when last visited, a byte (a quarter
    /// of the memory a search writes into at scattered places), cleared every 255 queries.
    static VISITED: RefCell<(u8, Vec<u8>)> = const { RefCell::new((0, Vec::new())) };
}

/// A graph over n vectors of d dimensions: `links` holds each vector's `degree` neighbors in turn.
pub struct Graph {
    pub d: usize,
    n: usize,
    degree: usize,
    metric: Kind,
    rows: Rows,
    links: Vec<u32>,
    /// Where every search starts: the vector nearest the mean, and others spread evenly through the rows.
    entries: Vec<u32>,
}

impl Graph {
    /// From the vectors `x` (n rows of `d`, used to find the entries: the vector nearest their mean and others
    /// spread evenly through them), the rows the
    /// search reads (`rows`: x itself, or the same as bytes), and the links (n x `degree`, each below n, or -1
    /// for none).
    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,
        })
    }

    /// The indices of each query's k nearest found, flattened, nearest first (u32::MAX where fewer were found),
    /// searching with `ef` candidates (at least k): one thread per query.
    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); // on this thread: handing one query to a pool costs a thread's wake-up
        } else if nq < SMALL_BATCH {
            // a pool of its own, as many threads as queries up to the cores: waking rayon's global pool costs
            // more than a 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], // summed as the grouped rows are
            }
        };
        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;
            // candidates to expand, nearest first; the ef nearest found, farthest on top
            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;
                }
                // the unvisited neighbors, then their distances, GROUP rows at a time
                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;
                    }
                }
                // Touch each neighbor's row before computing any distance: ordinary loads, so that the rows'
                // fetches from memory all start now and overlap (a safe stand-in for a prefetch instruction).
                // Where a node's neighbors fit in the first-level cache, every cache line of each row; where
                // they do not, the touched lines would be evicted before they are used, so only each row's
                // first line, the processor's own prefetcher streaming the rest.
                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;
            }
        });
    }
}

/// The entry vectors of a GPU graph search (siann's Metal and Triton searches): `width` vectors spread evenly
/// through the n rows (fewer, each once, where n is smaller), sorted, then -1 to `room` slots. The rows are NumPy's
/// `np.unique(np.linspace(0, n - 1, min(width, n)).astype(np.int32))`, computed as NumPy computes them (float64
/// steps, the last row exactly n - 1), so that the searches start where they always have.
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};

    /// Random finite float16 values (bits), from `seed`.
    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>();
    }
}