#![doc(
html_logo_url = "https://raw.githubusercontent.com/ChaoticQubit/troupekit/main/assets/brand/logo-mark.svg",
html_favicon_url = "https://raw.githubusercontent.com/ChaoticQubit/troupekit/main/assets/brand/favicon.svg"
)]
mod brute;
mod hnsw;
mod page;
mod quant;
mod rng;
use std::fmt;
pub use brute::BruteForce;
pub use hnsw::Hnsw;
pub const MAX_DIMS: usize = 65_536;
pub const MAX_K: usize = 1_000;
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Neighbor {
pub id: u64,
pub score: f32,
}
impl Neighbor {
pub fn new(id: u64, score: f32) -> Self {
Self { id, score }
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum PageKey {
Header,
Node(u64),
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PageChange {
Put(PageKey, Vec<u8>),
Delete(PageKey),
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Quantization {
#[default]
F32,
F16,
I8,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub struct HnswParams {
m: usize,
ef_construction: usize,
ef_search: usize,
seed: u64,
max_deleted_fraction: f32,
}
impl Default for HnswParams {
fn default() -> Self {
Self { m: 16, ef_construction: 200, ef_search: 64, seed: 0x5452_4B54, max_deleted_fraction: 0.25 }
}
}
impl HnswParams {
pub fn with_m(mut self, m: usize) -> Self {
self.m = m;
self
}
pub fn with_ef_construction(mut self, ef: usize) -> Self {
self.ef_construction = ef;
self
}
pub fn with_ef_search(mut self, ef: usize) -> Self {
self.ef_search = ef;
self
}
pub fn with_seed(mut self, seed: u64) -> Self {
self.seed = seed;
self
}
pub fn with_max_deleted_fraction(mut self, fraction: f32) -> Self {
self.max_deleted_fraction = fraction;
self
}
pub fn m(&self) -> usize {
self.m
}
pub fn ef_construction(&self) -> usize {
self.ef_construction
}
pub fn ef_search(&self) -> usize {
self.ef_search
}
pub fn seed(&self) -> u64 {
self.seed
}
pub fn max_deleted_fraction(&self) -> f32 {
self.max_deleted_fraction
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Default)]
pub enum IndexKind {
#[default]
BruteForce,
Hnsw(HnswParams),
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
pub enum IndexError {
#[error("dimension mismatch: expected {expected}, got {actual}")]
DimensionMismatch { expected: usize, actual: usize },
#[error("invalid input: {0}")]
Invalid(String),
#[error("corrupt page: {0}")]
CorruptPage(String),
#[error("unsupported: {0}")]
Unsupported(&'static str),
}
pub trait VectorIndex: Send + Sync {
fn dims(&self) -> usize;
fn len(&self) -> usize;
fn is_empty(&self) -> bool {
self.len() == 0
}
fn heap_bytes(&self) -> usize;
fn insert(&mut self, id: u64, vector: &[f32]) -> Result<(), IndexError>;
fn remove(&mut self, id: u64) -> bool;
fn search(&self, query: &[f32], k: usize, allow: Option<&dyn Fn(u64) -> bool>) -> Result<Vec<Neighbor>, IndexError>;
fn take_changes(&mut self) -> Vec<PageChange>;
fn restore(&mut self, vectors: &mut dyn Iterator<Item = (u64, Vec<f32>)>, pages: &mut dyn Iterator<Item = (PageKey, Vec<u8>)>) -> Result<(), IndexError>;
}
impl fmt::Debug for dyn VectorIndex {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("VectorIndex").field("dims", &self.dims()).field("len", &self.len()).finish()
}
}
pub fn new_index(kind: &IndexKind, dims: usize, quant: Quantization) -> Result<Box<dyn VectorIndex>, IndexError> {
if dims == 0 || dims > MAX_DIMS {
return Err(IndexError::Invalid(format!("dims must be in 1..={MAX_DIMS}, got {dims}")));
}
match kind {
IndexKind::BruteForce => Ok(Box::new(BruteForce::new(dims, quant))),
IndexKind::Hnsw(params) => {
hnsw::validate_params(params)?;
Ok(Box::new(Hnsw::new(dims, quant, params.clone())))
}
}
}
pub(crate) fn check_vector(dims: usize, v: &[f32]) -> Result<(), IndexError> {
if v.len() != dims {
return Err(IndexError::DimensionMismatch { expected: dims, actual: v.len() });
}
if let Some(i) = v.iter().position(|x| !x.is_finite()) {
return Err(IndexError::Invalid(format!("component {i} is not finite")));
}
Ok(())
}
pub(crate) fn check_k(k: usize) -> Result<(), IndexError> {
if k > MAX_K {
return Err(IndexError::Invalid(format!("k must be at most {MAX_K}, got {k}")));
}
Ok(())
}