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};
#[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())
}
}
const FORMAT: &str = "siann-index";
const FORMAT_VERSION: u64 = 3;
const NEVER: u64 = 1_000_000_000;
#[derive(Debug, Clone, PartialEq)]
pub struct Neighbors {
pub ids: Vec<i64>,
pub scores: Vec<f32>,
pub k: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Method {
Auto,
Exact,
Ivf { nprobe: Option<usize> },
Graph { ef: Option<usize> },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Route {
Exact,
Graph,
Query,
Split,
List,
}
struct Approx {
ivf: Ivf,
nprobe: usize,
graph: Option<(Graph, usize)>,
routes: Value,
}
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 {
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(); 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(),
¢roids,
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,
})
}
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 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 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)
}
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)),
}
}
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
}
}