use std::path::Path;
use std::sync::{Arc, OnceLock};
use serde_json::Value;
use super::blas;
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::products::{BLAS_FROM, exact_blas};
use super::routes::{Can, Routes};
use super::{Mat, ops};
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
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())
}
}
const FORMAT: &str = "siann-index";
const COARSE_CHUNK: usize = 2048;
const FORMAT_VERSION: u64 = 3;
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Neighbors {
pub ids: Vec<i64>,
pub scores: Vec<f32>,
pub k: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Method {
Auto,
Exact,
Ivf { nprobe: Option<usize> },
Graph { ef: Option<usize> },
Path {
path: SearchPath,
width: Option<usize>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SearchPath {
Exact,
Graph,
Query,
QueryBlas,
Split,
List,
}
impl SearchPath {
pub fn name(self) -> &'static str {
match self {
SearchPath::Exact => "cpu-exact",
SearchPath::Graph => "cpu-graph",
SearchPath::Query => "cpu-query",
SearchPath::QueryBlas => "cpu-query-blas",
SearchPath::Split => "cpu-split",
SearchPath::List => "cpu-list",
}
}
pub fn parse(path: &str) -> Result<SearchPath, Error> {
Ok(match path {
"cpu-exact" => SearchPath::Exact,
"cpu-graph" => SearchPath::Graph,
"cpu-query" => SearchPath::Query,
"cpu-query-blas" => SearchPath::QueryBlas,
"cpu-split" => SearchPath::Split,
"cpu-list" => SearchPath::List,
other => return Err(Error(format!("{other} is not a CPU path"))),
})
}
}
struct Approx {
ivf: Ivf,
centroids: Vec<f32>,
metric: Kind,
bytes: bool,
nprobe: usize,
graph: Option<(Graph, usize)>,
routes: Routes,
}
pub struct Index {
x: Arc<[f32]>,
n: usize,
d: usize,
metric: String,
kernel: Kind,
ids: Option<Vec<i64>>,
flat: OnceLock<Flat>,
norms: OnceLock<Vec<f32>>,
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 {
#[doc(hidden)] pub fn new(x: Vec<f32>, d: usize, metric: &str, ids: Option<Vec<i64>>) -> Result<Index, Error> {
if d == 0 || !x.len().is_multiple_of(d) {
return Err("x must hold rows of d values".into());
}
let n = x.len() / d;
if ids.as_ref().is_some_and(|i| i.len() != n) {
return Err("ids must hold one id per row".into());
}
let kernel = Kind::parse(if metric == "cosine" { "ip" } else { metric })?;
Ok(Index {
x: x.into(),
n,
d,
metric: metric.to_string(),
kernel,
ids,
flat: OnceLock::new(), norms: OnceLock::new(),
approx: None,
recall: None,
})
}
#[doc(hidden)] pub fn set_ivf(
&mut self,
centroids: &[f32],
assign: &[i64],
ivf_metric: &str,
bytes: bool,
nprobe: usize,
) -> Result<(), Error> {
let metric = Kind::parse(ivf_metric)?;
let stored = if bytes {
Stored::U8(self.x.iter().map(|&v| v as u8).collect())
} else {
Stored::F32
};
let assign_metric = if matches!(metric, Kind::Ip) {
Kind::L2
} else {
metric
};
let ivf = Ivf::new(
self.x.to_vec(),
centroids,
self.d,
metric,
assign_metric,
stored,
Some(assign),
)?;
self.approx = Some(Approx {
ivf,
centroids: centroids.to_vec(),
metric,
bytes,
nprobe,
graph: None,
routes: Routes::parse(&Value::Null),
});
Ok(())
}
#[doc(hidden)] pub fn set_graph(
&mut self,
links: &[i64],
degree: usize,
ef: usize,
half: bool,
) -> Result<(), Error> {
let x = Arc::clone(&self.x);
let d = self.d;
let a = self
.approx
.as_mut()
.ok_or("a graph needs the IVF first (set_ivf)")?;
let rows = if a.bytes {
Rows::U8(x.iter().map(|&v| v as u8).collect())
} else if half {
Rows::half(&x).ok_or("float16 rows need every coordinate within float16's range")?
} else {
Rows::F32(Arc::clone(&x))
};
a.graph = Some((Graph::new(&x, d, a.metric, rows, links, degree)?, ef));
Ok(())
}
#[doc(hidden)] pub fn set_routes(&mut self, routes: &Value) {
if let Some(a) = self.approx.as_mut() {
a.routes = Routes::parse(routes);
}
}
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 ids = if z.has("ids") {
Some(z.array("ids")?.i64s("ids")?)
} else {
None
};
let mut index = Index::new(x, d, &metric, ids)?;
index.recall = meta.get("recall").and_then(Value::as_f64);
if meta.get("kind").and_then(Value::as_str) == Some("ivf") && n > 0 {
let ivf_metric = 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 nprobe = field(&meta, "nprobe")?
.as_u64()
.ok_or("nprobe is not a number")? as usize;
index.set_ivf(¢roids, &assign, ivf_metric, bytes, nprobe)?;
if let (Some(g), true) = (meta.get("graph"), z.has("graph"))
&& !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 half = g.get("rows").and_then(Value::as_str) == Some("float16");
index.set_graph(&links, degree, ef, half)?;
}
index.set_routes(meta.get("routes").unwrap_or(&Value::Null));
}
Ok(index)
}
pub fn len(&self) -> usize {
self.n
}
pub fn is_empty(&self) -> bool {
self.n == 0
}
pub fn dim(&self) -> usize {
self.d
}
pub fn metric(&self) -> &str {
&self.metric
}
pub fn kind(&self) -> &str {
if self.approx.is_some() {
"ivf"
} else {
"exact"
}
}
pub fn has_graph(&self) -> bool {
self.approx.as_ref().is_some_and(|a| a.graph.is_some())
}
pub fn recall_target(&self) -> Option<f64> {
self.recall
}
pub fn nprobe(&self) -> Option<usize> {
self.approx.as_ref().map(|a| a.nprobe)
}
pub fn ef(&self) -> Option<usize> {
self.approx
.as_ref()
.and_then(|a| a.graph.as_ref().map(|g| g.1))
}
pub fn paths(&self) -> Vec<SearchPath> {
let mut out = vec![SearchPath::Exact];
if let Some(a) = &self.approx {
out.extend([
SearchPath::Split,
SearchPath::Query,
SearchPath::QueryBlas,
SearchPath::List,
]);
if a.graph.is_some() {
out.push(SearchPath::Graph);
}
}
out
}
pub fn search(&self, queries: &[f32], k: usize) -> Result<Neighbors, Error> {
self.search_with(queries, k, Method::Auto)
}
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 kk = k.min(self.n);
if nq == 0 || kk == 0 {
return self.finish(&[], &[], 0, k).map(|mut f| {
f.ids = vec![-1; nq * k];
f.scores = vec![self.worst(); nq * k];
f
});
}
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, width) = self.path(nq, method)?;
let blas_coarse = matches!(path, SearchPath::QueryBlas | SearchPath::List);
let rows = self.rows_on(&q, kk, path, width, blas_coarse)?;
self.finish(&q, &rows, kk, k)
}
#[doc(hidden)] pub fn rows(
&self,
queries: &[f32],
k: usize,
path: &str,
width: usize,
coarse: &str,
) -> Result<Vec<i64>, Error> {
if self.d == 0 || !queries.len().is_multiple_of(self.d) || k == 0 || k > self.n {
return Err("queries must hold rows of d values, and 0 < k <= len()".into());
}
let route = SearchPath::parse(path)?;
let blas_coarse = match coarse {
"auto" => matches!(route, SearchPath::QueryBlas | SearchPath::List),
"blas" => route != SearchPath::Split,
"rust" => false,
other => {
return Err(Error(format!(
"coarse must be 'auto', 'blas' or 'rust', not {other}"
)));
}
};
self.rows_on(queries, k, route, width, blas_coarse)
}
fn rows_on(
&self,
q: &[f32],
k: usize,
route: SearchPath,
width: usize,
blas_coarse: bool,
) -> Result<Vec<i64>, Error> {
let nq = q.len() / self.d;
let found: Vec<u32> = match route {
SearchPath::Exact => self.exact(q, nq, k)?,
SearchPath::Graph => {
let (g, _) = self
.approx
.as_ref()
.and_then(|a| a.graph.as_ref())
.ok_or("the index has no graph")?;
g.search(q, k, width.max(k))?
}
SearchPath::Query | SearchPath::QueryBlas | SearchPath::Split | SearchPath::List => {
let a = self.approx.as_ref().ok_or("the index has no IVF")?;
let nprobe = width.max(1);
let split = if route == SearchPath::Split { 4 } else { 1 };
let scan = |qs: &[f32], p: Option<Mat<'_, f32>>| -> Result<Vec<u32>, Error> {
Ok(if route == SearchPath::List {
a.ivf.search_list_major(qs, k, nprobe, p)?
} else {
a.ivf.search(
qs,
k,
nprobe,
Options {
split,
gprobe: 0,
threads: 0,
},
p,
)?
})
};
if blas_coarse && blas::available() && matches!(a.metric, Kind::L2 | Kind::Ip) {
let nlist = a.centroids.len() / self.d;
let mut out = Vec::with_capacity(nq * k);
let mut p = vec![0.0f32; COARSE_CHUNK.min(nq) * nlist];
for qs in q.chunks(COARSE_CHUNK * self.d) {
let rows = qs.len() / self.d;
let buf = &mut p[..rows * nlist];
blas::products(qs, &a.centroids, self.d, buf)?;
out.extend(scan(
qs,
Some(Mat {
data: buf,
rows,
cols: nlist,
}),
)?);
}
out
} else {
scan(q, None)?
}
}
};
Ok(found
.iter()
.map(|&i| {
if (i as usize) < self.n {
i64::from(i)
} else {
-1
}
})
.collect())
}
#[doc(hidden)] pub fn finish(
&self,
queries: &[f32],
rows: &[i64],
kk: usize,
k: usize,
) -> Result<Neighbors, Error> {
let nq = queries.len().checked_div(self.d).unwrap_or(0);
if rows.len() != nq * kk || kk > k {
return Err("rows must be (nq, kk), kk at most k".into());
}
if rows.iter().any(|&r| r >= self.n as i64) {
return Err("a row beyond the index".into());
}
let (ids, scores) = if nq == 0 || kk == 0 {
(Vec::new(), Vec::new())
} else {
ops::rank(
Mat {
data: &self.x,
rows: self.n,
cols: self.d,
},
Mat {
data: queries,
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 worst = self.worst();
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)
}
fn worst(&self) -> f32 {
if self.kernel.similarity() {
f32::NEG_INFINITY
} else {
f32::INFINITY
}
}
fn exact(&self, q: &[f32], nq: usize, k: usize) -> Result<Vec<u32>, Error> {
if blas::available() && matches!(self.kernel, Kind::L2 | Kind::Ip) && nq >= BLAS_FROM {
let norms = self.norms.get_or_init(|| {
if matches!(self.kernel, Kind::L2) {
ops::sq_norms(&self.x, self.d)
} else {
vec![0.0; self.n]
}
});
return Ok(exact_blas(&self.x, norms, self.d, q, k)?);
}
Ok(self
.flat
.get_or_init(|| Flat::new(&self.x, self.d, self.kernel))
.search(q, k, 32, true)?)
}
fn path(&self, batch: usize, method: Method) -> Result<(SearchPath, usize), Error> {
let Some(a) = &self.approx else {
return match method {
Method::Auto | Method::Exact => Ok((SearchPath::Exact, 0)),
Method::Path { path, width } => self.given(path, width),
_ => 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((SearchPath::Exact, 0)),
Method::Graph { ef: given } => {
if a.graph.is_none() {
return Err("the index has no graph".into());
}
Ok((SearchPath::Graph, given.unwrap_or(ef)))
}
Method::Ivf { nprobe } => Ok((self.routed(a, batch, true), nprobe.unwrap_or(a.nprobe))),
Method::Auto => {
let r = self.routed(a, batch, false);
Ok((r, if r == SearchPath::Graph { ef } else { a.nprobe }))
}
Method::Path { path, width } => self.given(path, width),
}
}
fn given(&self, path: SearchPath, width: Option<usize>) -> Result<(SearchPath, usize), Error> {
if !self.paths().contains(&path) {
return Err(Error(format!(
"{} is not one of this index's paths",
path.name()
)));
}
let a = self.approx.as_ref();
match path {
SearchPath::Exact if width.is_some() => Err("exact search takes no width".into()),
SearchPath::Exact => Ok((SearchPath::Exact, 0)),
SearchPath::Graph => Ok((
path,
width.unwrap_or_else(|| a.and_then(|a| a.graph.as_ref()).map_or(0, |g| g.1)),
)),
_ => Ok((path, width.unwrap_or_else(|| a.map_or(0, |a| a.nprobe)))),
}
}
fn routed(&self, a: &Approx, batch: usize, ivf_only: bool) -> SearchPath {
let can = Can {
device: Some("cpu"),
approximate: ivf_only,
gpu: false,
graph: a.graph.is_some() && !ivf_only,
graph_gpu: false,
plugin_graph: false,
};
SearchPath::parse(&a.routes.path(batch as u64, &can)).unwrap_or(SearchPath::Query)
}
}