siann 0.6.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
//! Serving an index that the siann Python package built and saved: [`Index::load`] reads the file
//! `index.save(path)` wrote, and [`Index::search`] returns the same neighbors, in the same order, as the Python
//! package's search on the CPU (`index.search(xq, k, device="cpu")`): the same path for each batch size (the
//! routes measured when the index was built), the same calibrated widths (nprobe, the graph's ef), the same
//! ranking by exact score, ties by row, and the index's own ids.

use std::path::Path;
use std::sync::OnceLock;

use serde_json::Value;

use super::flat::Flat;
use super::graph::{Graph, Rows};
use super::ivf::{Ivf, Options, Stored};
use super::metric::Kind;
use super::npz::Npz;
use super::{Mat, ops};

/// An error loading or searching an index.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Error(String);

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for Error {}

impl From<String> for Error {
    fn from(s: String) -> Self {
        Error(s)
    }
}

impl From<&str> for Error {
    fn from(s: &str) -> Self {
        Error(s.to_string())
    }
}

/// The index file's format, as `siann.Index.save` writes it.
const FORMAT: &str = "siann-index";
/// The latest format version this crate reads.
const FORMAT_VERSION: u64 = 3;
const NEVER: u64 = 1_000_000_000;

/// Each query's k nearest: `ids` and `scores`, row-major (`queries * k`), best first; -1 and the metric's
/// worst score (infinity for a distance, minus infinity for a similarity) where fewer than k were found.
#[derive(Debug, Clone, PartialEq)]
pub struct Neighbors {
    pub ids: Vec<i64>,
    pub scores: Vec<f32>,
    pub k: usize,
}

/// How a search runs: as the index routes its batch size on the CPU (`Auto`), or by one method.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Method {
    /// The path the index measured fastest on the CPU for the batch's size, as the Python package takes it.
    Auto,
    /// Exact search.
    Exact,
    /// The IVF, probing `nprobe` lists (the calibrated number where None), by the scan the index routes the
    /// batch's size to.
    Ivf { nprobe: Option<usize> },
    /// The graph, `ef` candidates wide (the calibrated width where None).
    Graph { ef: Option<usize> },
}

/// The CPU paths of the Python package's routes ("cpu-exact", "cpu-graph", "cpu-query" and "cpu-query-blas",
/// "cpu-split", "cpu-list").
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Route {
    Exact,
    Graph,
    Query,
    Split,
    List,
}

/// The IVF and its graph, where the index has them.
struct Approx {
    ivf: Ivf,
    nprobe: usize,
    graph: Option<(Graph, usize)>,
    routes: Value,
}

/// An index saved by the siann Python package (`index.save(path)`), searched on the CPU.
pub struct Index {
    x: Vec<f32>,
    n: usize,
    d: usize,
    metric: String,
    kernel: Kind,
    ids: Option<Vec<i64>>,
    flat: OnceLock<Flat>,
    approx: Option<Approx>,
    recall: Option<f64>,
}

fn field<'a>(v: &'a Value, key: &str) -> Result<&'a Value, Error> {
    v.get(key)
        .ok_or_else(|| Error(format!("the index file's metadata has no {key}")))
}

impl Index {
    /// Reads an index file that the siann Python package wrote (`index.save(path)`, format version 3 or
    /// earlier). Added vectors are merged and removed ones dropped when Python saves, so the file is searched
    /// as it is.
    pub fn load(path: impl AsRef<Path>) -> Result<Index, Error> {
        let mut z = Npz::open(path.as_ref())?;
        let meta: Value = serde_json::from_str(&z.array("meta")?.text("meta")?)
            .map_err(|e| Error(format!("the index file's metadata is not JSON: {e}")))?;
        if field(&meta, "format")?.as_str() != Some(FORMAT) {
            return Err("not a saved siann index".into());
        }
        let version = field(&meta, "format_version")?.as_u64().unwrap_or(0);
        if version > FORMAT_VERSION {
            return Err(Error(format!(
                "saved in format {version}; this crate reads format {FORMAT_VERSION} and earlier: upgrade it"
            )));
        }
        let x = z.array("x")?;
        let (n, d) = match x.shape[..] {
            [n, d] => (n, d),
            _ => return Err("x is not a matrix".into()),
        };
        let x = x.f32s("x")?;
        let metric = field(&meta, "metric")?
            .as_str()
            .ok_or("metric is not text")?
            .to_string();
        let kernel = Kind::parse(if metric == "cosine" { "ip" } else { &metric })?;
        let ids = if z.has("ids") {
            Some(z.array("ids")?.i64s("ids")?)
        } else {
            None
        };
        let flat = OnceLock::new(); // exact search's copy, made when a search first needs it
        let recall = meta.get("recall").and_then(Value::as_f64);
        let approx = if meta.get("kind").and_then(Value::as_str) == Some("ivf") && n > 0 {
            let ivf_metric = Kind::parse(
                field(&meta, "ivf_metric")?
                    .as_str()
                    .ok_or("ivf_metric is not text")?,
            )?;
            let bytes = meta.get("storage").and_then(Value::as_str) == Some("uint8");
            let centroids = z.array("centroids")?.f32s("centroids")?;
            let assign = z.array("assign")?.i64s("assign")?;
            let stored = if bytes {
                Stored::U8(x.iter().map(|&v| v as u8).collect())
            } else {
                Stored::F32
            };
            let assign_metric = if matches!(ivf_metric, Kind::Ip) {
                Kind::L2
            } else {
                ivf_metric
            };
            let ivf = Ivf::new(
                x.clone(),
                &centroids,
                d,
                ivf_metric,
                assign_metric,
                stored,
                Some(&assign),
            )?;
            let nprobe = field(&meta, "nprobe")?
                .as_u64()
                .ok_or("nprobe is not a number")? as usize;
            let graph = match (meta.get("graph"), z.has("graph")) {
                (Some(g), true) if !g.is_null() => {
                    let links = z.array("graph")?;
                    let degree = *links.shape.get(1).ok_or("graph is not a matrix")?;
                    let links = links.i64s("graph")?;
                    let ef = g
                        .get("ef")
                        .and_then(Value::as_u64)
                        .ok_or("the graph has no calibrated ef")?
                        as usize;
                    let rows = if bytes {
                        Rows::U8(x.iter().map(|&v| v as u8).collect())
                    } else {
                        Rows::F32(x.clone())
                    };
                    Some((Graph::new(&x, d, ivf_metric, rows, &links, degree)?, ef))
                }
                _ => None,
            };
            Some(Approx {
                ivf,
                nprobe,
                graph,
                routes: meta.get("routes").cloned().unwrap_or(Value::Null),
            })
        } else {
            None
        };
        Ok(Index {
            x,
            n,
            d,
            metric,
            kernel,
            ids,
            flat,
            approx,
            recall,
        })
    }

    /// The number of vectors.
    pub fn len(&self) -> usize {
        self.n
    }

    /// Whether the index holds no vectors.
    pub fn is_empty(&self) -> bool {
        self.n == 0
    }

    /// The vectors' dimension.
    pub fn dim(&self) -> usize {
        self.d
    }

    /// The metric: "l2", "l1", "linf", "cosine" or "ip".
    pub fn metric(&self) -> &str {
        &self.metric
    }

    /// "exact" or "ivf" (an IVF, perhaps with a graph), as the index was built.
    pub fn kind(&self) -> &str {
        if self.approx.is_some() {
            "ivf"
        } else {
            "exact"
        }
    }

    /// Whether the index has a graph.
    pub fn has_graph(&self) -> bool {
        self.approx.as_ref().is_some_and(|a| a.graph.is_some())
    }

    /// The recall target the index was calibrated to (None for exact search).
    pub fn recall_target(&self) -> Option<f64> {
        self.recall
    }

    /// The calibrated number of lists each query probes (None for exact search).
    pub fn nprobe(&self) -> Option<usize> {
        self.approx.as_ref().map(|a| a.nprobe)
    }

    /// The graph's calibrated search width on the CPU (None without a graph).
    pub fn ef(&self) -> Option<usize> {
        self.approx
            .as_ref()
            .and_then(|a| a.graph.as_ref().map(|g| g.1))
    }

    /// Each query's k nearest; `queries` holds them row by row (a multiple of `dim()` values). The path is the
    /// one the index routes the batch's size to on the CPU.
    pub fn search(&self, queries: &[f32], k: usize) -> Result<Neighbors, Error> {
        self.search_with(queries, k, Method::Auto)
    }

    /// Each query's k nearest by `method`.
    pub fn search_with(
        &self,
        queries: &[f32],
        k: usize,
        method: Method,
    ) -> Result<Neighbors, Error> {
        if k == 0 {
            return Err("k must be positive".into());
        }
        if self.d == 0 || !queries.len().is_multiple_of(self.d) {
            return Err(Error(format!(
                "queries must hold a multiple of {} values",
                self.d
            )));
        }
        if queries.iter().any(|v| !v.is_finite()) {
            return Err("the queries hold infinity or NaN".into());
        }
        let nq = queries.len() / self.d;
        let worst = if self.kernel.similarity() {
            f32::NEG_INFINITY
        } else {
            f32::INFINITY
        };
        let kk = k.min(self.n);
        if nq == 0 || kk == 0 {
            return Ok(Neighbors {
                ids: vec![-1; nq * k],
                scores: vec![worst; nq * k],
                k,
            });
        }
        let q = if self.metric == "cosine" {
            let (v, zeros) = ops::normalize(queries, self.d);
            if zeros > 0 {
                return Err(Error(format!(
                    "cosine is undefined for a zero vector, and the queries hold {zeros}"
                )));
            }
            v
        } else {
            queries.to_vec()
        };
        let (path, nprobe, ef) = self.path(nq, method)?;
        let found: Vec<u32> = match path {
            Route::Exact => self
                .flat
                .get_or_init(|| Flat::new(&self.x, self.d, self.kernel))
                .search(&q, kk, 32, true)?,
            Route::Graph => {
                let (g, _) = self
                    .approx
                    .as_ref()
                    .and_then(|a| a.graph.as_ref())
                    .ok_or("the index has no graph")?;
                g.search(&q, kk, ef.max(kk))?
            }
            Route::Query | Route::Split => {
                let a = self.approx.as_ref().ok_or("the index has no IVF")?;
                let split = if path == Route::Split { 4 } else { 1 };
                a.ivf.search(
                    &q,
                    kk,
                    nprobe,
                    Options {
                        split,
                        gprobe: 0,
                        threads: 0,
                    },
                    None,
                )?
            }
            Route::List => {
                let a = self.approx.as_ref().ok_or("the index has no IVF")?;
                a.ivf.search_list_major(&q, kk, nprobe, None)?
            }
        };
        let rows: Vec<i64> = found
            .iter()
            .map(|&i| {
                if (i as usize) < self.n {
                    i64::from(i)
                } else {
                    -1
                }
            })
            .collect();
        let (ids, scores) = ops::rank(
            Mat {
                data: &self.x,
                rows: self.n,
                cols: self.d,
            },
            Mat {
                data: &q,
                rows: nq,
                cols: self.d,
            },
            Mat {
                data: &rows,
                rows: nq,
                cols: kk,
            },
            self.kernel,
        )?;
        let ids: Vec<i64> = match &self.ids {
            Some(own) => ids
                .iter()
                .map(|&i| if i >= 0 { own[i as usize] } else { -1 })
                .collect(),
            None => ids,
        };
        if kk == k {
            return Ok(Neighbors { ids, scores, k });
        }
        let mut out = Neighbors {
            ids: Vec::with_capacity(nq * k),
            scores: Vec::with_capacity(nq * k),
            k,
        };
        for r in 0..nq {
            out.ids.extend_from_slice(&ids[r * kk..(r + 1) * kk]);
            out.ids.extend(std::iter::repeat_n(-1, k - kk));
            out.scores.extend_from_slice(&scores[r * kk..(r + 1) * kk]);
            out.scores.extend(std::iter::repeat_n(worst, k - kk));
        }
        Ok(out)
    }

    /// The path, nprobe and ef a batch of `batch` queries takes by `method`.
    fn path(&self, batch: usize, method: Method) -> Result<(Route, usize, usize), Error> {
        let Some(a) = &self.approx else {
            return match method {
                Method::Auto | Method::Exact => Ok((Route::Exact, 0, 0)),
                _ => Err("an exact index has no IVF or graph".into()),
            };
        };
        let ef = a.graph.as_ref().map_or(0, |g| g.1);
        match method {
            Method::Exact => Ok((Route::Exact, 0, 0)),
            Method::Graph { ef: given } => {
                if a.graph.is_none() {
                    return Err("the index has no graph".into());
                }
                Ok((Route::Graph, 0, given.unwrap_or(ef)))
            }
            Method::Ivf { nprobe } => {
                Ok((self.routed(a, batch, true), nprobe.unwrap_or(a.nprobe), ef))
            }
            Method::Auto => Ok((self.routed(a, batch, false), a.nprobe, ef)),
        }
    }

    /// The CPU path Python's `Index._ivf_path(batch, "cpu")` takes: the first CPU path of the measured table's
    /// entry for the batch size, or else the thresholds. ``ivf_only``: the IVF's paths only (as with
    /// `search(..., nprobe=)`).
    fn routed(&self, a: &Approx, batch: usize, ivf_only: bool) -> Route {
        let r = &a.routes;
        let has_graph = a.graph.is_some();
        let named = |p: &str| -> Option<Route> {
            match p {
                "cpu-exact" if !ivf_only => Some(Route::Exact),
                "cpu-graph" if has_graph && !ivf_only => Some(Route::Graph),
                "cpu-query" | "cpu-query-blas" => Some(Route::Query),
                "cpu-split" => Some(Route::Split),
                "cpu-list" => Some(Route::List),
                _ => None,
            }
        };
        if let Some(table) = r
            .get("table")
            .and_then(Value::as_array)
            .filter(|t| !t.is_empty())
        {
            let mut entry = table[0].get(1);
            for e in table {
                if e.get(0).and_then(Value::as_u64).unwrap_or(0) as usize > batch {
                    break;
                }
                entry = e.get(1);
            }
            if let Some(paths) = entry.and_then(Value::as_array) {
                for p in paths.iter().filter_map(Value::as_str) {
                    if let Some(path) = named(p) {
                        return path;
                    }
                }
            }
        } else {
            if !ivf_only
                && batch as u64 >= r.get("exact_from").and_then(Value::as_u64).unwrap_or(NEVER)
            {
                return Route::Exact;
            }
            if batch == 1
                && let Some(path) = r.get("single").and_then(Value::as_str).and_then(named)
            {
                return path;
            }
        }
        let t = |key: &str, default: u64| {
            r.get(key).and_then(Value::as_u64).unwrap_or(default) as usize
        };
        if has_graph && !ivf_only && batch < t("cpu_ivf_from", 1) {
            return Route::Graph;
        }
        if batch == 1 {
            return Route::Split;
        }
        if batch >= t("cpu_list_from", NEVER) {
            return Route::List;
        }
        Route::Query
    }
}