1use anndists::prelude::Distance;
39use memmap2::Mmap;
40use rand::{prelude::*, thread_rng};
41use rayon::prelude::*;
42use serde::{Deserialize, Serialize};
43use std::cmp::{Ordering, Reverse};
44use std::collections::{BinaryHeap, HashSet};
45use std::fs::OpenOptions;
46use std::io::{Read, Seek, SeekFrom, Write};
47use std::marker::PhantomData;
48use thiserror::Error;
49
50mod mmap_dynamic;
51pub use mmap_dynamic::DeleteStats;
52
53const PAD_U32: u32 = u32::MAX;
55
56pub const DISKANN_DEFAULT_MAX_DEGREE: usize = 64;
58pub const DISKANN_DEFAULT_BUILD_BEAM: usize = 128;
59pub const DISKANN_DEFAULT_ALPHA: f32 = 1.2;
60pub const DISKANN_DEFAULT_EXTRA_SEEDS: usize = 1;
62
63const GRAPH_SLACK_FACTOR: f32 = 1.3;
67
68const MAX_OCCLUSION_SIZE: usize = 750;
70
71const MICRO_BATCH_CHUNK_SIZE: usize = 256;
87
88#[derive(Clone, Copy, Debug)]
90pub struct DiskAnnParams {
91 pub max_degree: usize,
92 pub build_beam_width: usize,
93 pub alpha: f32,
94 pub extra_seeds: usize,
96}
97
98impl Default for DiskAnnParams {
99 fn default() -> Self {
100 Self {
101 max_degree: DISKANN_DEFAULT_MAX_DEGREE,
102 build_beam_width: DISKANN_DEFAULT_BUILD_BEAM,
103 alpha: DISKANN_DEFAULT_ALPHA,
104 extra_seeds: DISKANN_DEFAULT_EXTRA_SEEDS,
105 }
106 }
107}
108
109#[derive(Debug, Error)]
111pub enum DiskAnnError {
112 #[error("I/O error: {0}")]
114 Io(#[from] std::io::Error),
115
116 #[error("Serialization error: {0}")]
118 Bincode(#[from] bincode::Error),
119
120 #[error("Index error: {0}")]
122 IndexError(String),
123}
124
125#[derive(Serialize, Deserialize, Debug)]
127struct Metadata {
128 dim: usize,
129 num_vectors: usize,
130 max_degree: usize,
131 medoid_id: u32,
132 vectors_offset: u64,
133 adjacency_offset: u64,
134 elem_size: u8,
135 distance_name: String,
136}
137
138#[derive(Clone, Copy, Debug)]
140pub(crate) struct Candidate {
141 dist: f32,
142 id: u32,
143}
144
145pub(crate) fn graph_search(
148 start_id: u32,
149 beam_width: usize,
150 mut distance: impl FnMut(u32) -> f32,
151 mut neighbors: impl FnMut(u32) -> Vec<u32>,
152) -> Vec<Candidate> {
153 let beam_width = beam_width.max(1);
154 let start = Candidate {
155 dist: distance(start_id),
156 id: start_id,
157 };
158 let mut visited = HashSet::from([start_id]);
159 let mut frontier = BinaryHeap::from([Reverse(start)]);
160 let mut work = BinaryHeap::from([start]);
161
162 while let Some(Reverse(best)) = frontier.peek().copied() {
163 if work.len() >= beam_width && best.dist >= work.peek().unwrap().dist {
164 break;
165 }
166 let Reverse(current) = frontier.pop().unwrap();
167 for neighbor in neighbors(current.id) {
168 if !visited.insert(neighbor) {
169 continue;
170 }
171 let candidate = Candidate {
172 dist: distance(neighbor),
173 id: neighbor,
174 };
175 if work.len() < beam_width {
176 work.push(candidate);
177 frontier.push(Reverse(candidate));
178 } else if candidate.dist < work.peek().unwrap().dist {
179 work.pop();
180 work.push(candidate);
181 frontier.push(Reverse(candidate));
182 }
183 }
184 }
185
186 let mut results = work.into_vec();
187 results.sort_by(|a, b| a.dist.total_cmp(&b.dist));
188 results
189}
190impl PartialEq for Candidate {
191 fn eq(&self, other: &Self) -> bool {
192 self.id == other.id && self.dist.to_bits() == other.dist.to_bits()
193 }
194}
195impl Eq for Candidate {}
196impl PartialOrd for Candidate {
197 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
198 Some(
199 self.dist
200 .total_cmp(&other.dist)
201 .then_with(|| self.id.cmp(&other.id)),
202 )
203 }
204}
205impl Ord for Candidate {
206 fn cmp(&self, other: &Self) -> Ordering {
207 self.partial_cmp(other).unwrap_or(Ordering::Equal)
208 }
209}
210
211#[derive(Clone, Debug)]
215struct FlatVectors<T> {
216 data: Vec<T>,
217 dim: usize,
218 n: usize,
219}
220
221impl<T: Copy> FlatVectors<T> {
222 fn from_vecs(vectors: &[Vec<T>]) -> Result<Self, DiskAnnError> {
223 if vectors.is_empty() {
224 return Err(DiskAnnError::IndexError("No vectors provided".to_string()));
225 }
226 let dim = vectors[0].len();
227 for (i, v) in vectors.iter().enumerate() {
228 if v.len() != dim {
229 return Err(DiskAnnError::IndexError(format!(
230 "Vector {} has dimension {} but expected {}",
231 i,
232 v.len(),
233 dim
234 )));
235 }
236 }
237
238 let n = vectors.len();
239 let mut data = Vec::with_capacity(n * dim);
240 for v in vectors {
241 data.extend_from_slice(v);
242 }
243
244 Ok(Self { data, dim, n })
245 }
246
247 #[inline]
248 fn row(&self, idx: usize) -> &[T] {
249 let start = idx * self.dim;
250 let end = start + self.dim;
251 &self.data[start..end]
252 }
253}
254
255#[derive(Default, Debug)]
266struct OrderedBeam {
267 items: Vec<Candidate>,
268}
269
270impl OrderedBeam {
271 #[inline]
272 fn clear(&mut self) {
273 self.items.clear();
274 }
275
276 #[inline]
277 fn len(&self) -> usize {
278 self.items.len()
279 }
280
281 #[inline]
282 fn is_empty(&self) -> bool {
283 self.items.is_empty()
284 }
285
286 #[inline]
287 fn best(&self) -> Option<Candidate> {
288 self.items.last().copied()
289 }
290
291 #[inline]
292 fn worst(&self) -> Option<Candidate> {
293 self.items.first().copied()
294 }
295
296 #[inline]
297 fn pop_best(&mut self) -> Option<Candidate> {
298 self.items.pop()
299 }
300
301 #[inline]
302 fn reserve(&mut self, cap: usize) {
303 if self.items.capacity() < cap {
304 self.items.reserve(cap - self.items.capacity());
305 }
306 }
307
308 #[inline]
309 fn insert_unbounded(&mut self, cand: Candidate) {
310 let pos = self.items.partition_point(|x| {
311 x.dist > cand.dist || (x.dist.to_bits() == cand.dist.to_bits() && x.id > cand.id)
312 });
313 self.items.insert(pos, cand);
314 }
315
316 #[inline]
317 fn insert_capped(&mut self, cand: Candidate, cap: usize) {
318 if cap == 0 {
319 return;
320 }
321
322 if self.items.len() < cap {
323 self.insert_unbounded(cand);
324 return;
325 }
326
327 let worst = self.items[0];
329 if cand.dist >= worst.dist {
330 return;
331 }
332
333 self.insert_unbounded(cand);
334
335 if self.items.len() > cap {
336 self.items.remove(0);
337 }
338 }
339}
340
341#[derive(Debug)]
345struct BuildScratch {
346 marks: Vec<u32>,
347 epoch: u32,
348
349 visited_ids: Vec<u32>,
350 visited_dists: Vec<f32>,
351
352 frontier: OrderedBeam,
353 work: OrderedBeam,
354
355 seeds: Vec<usize>,
356 candidates: Vec<(u32, f32)>,
357}
358
359impl BuildScratch {
360 fn new(n: usize, beam_width: usize, max_degree: usize, extra_seeds: usize) -> Self {
361 Self {
362 marks: vec![0u32; n],
363 epoch: 1,
364 visited_ids: Vec::with_capacity(beam_width * 4),
365 visited_dists: Vec::with_capacity(beam_width * 4),
366 frontier: {
367 let mut b = OrderedBeam::default();
368 b.reserve(beam_width * 2);
369 b
370 },
371 work: {
372 let mut b = OrderedBeam::default();
373 b.reserve(beam_width * 2);
374 b
375 },
376 seeds: Vec::with_capacity(1 + extra_seeds),
377 candidates: Vec::with_capacity(beam_width * (4 + extra_seeds) + max_degree * 2),
378 }
379 }
380
381 #[inline]
382 fn reset_search(&mut self) {
383 self.epoch = self.epoch.wrapping_add(1);
384 if self.epoch == 0 {
385 self.marks.fill(0);
386 self.epoch = 1;
387 }
388 self.visited_ids.clear();
389 self.visited_dists.clear();
390 self.frontier.clear();
391 self.work.clear();
392 }
393
394 #[inline]
395 fn is_marked(&self, idx: usize) -> bool {
396 self.marks[idx] == self.epoch
397 }
398
399 #[inline]
400 fn mark_with_dist(&mut self, idx: usize, dist: f32) {
401 self.marks[idx] = self.epoch;
402 self.visited_ids.push(idx as u32);
403 self.visited_dists.push(dist);
404 }
405}
406
407#[derive(Debug)]
408struct IncrementalInsertScratch {
409 build: BuildScratch,
410}
411
412impl IncrementalInsertScratch {
413 fn new(n: usize, beam_width: usize, max_degree: usize, extra_seeds: usize) -> Self {
414 Self {
415 build: BuildScratch::new(n, beam_width, max_degree, extra_seeds),
416 }
417 }
418}
419
420pub struct DiskANN<T, D>
422where
423 T: bytemuck::Pod + Copy + Send + Sync + 'static,
424 D: Distance<T> + Send + Sync + Copy + Clone + 'static,
425{
426 pub dim: usize,
428 pub num_vectors: usize,
430 pub max_degree: usize,
432 pub distance_name: String,
434
435 medoid_id: u32,
437 vectors_offset: u64,
439 adjacency_offset: u64,
440
441 mmap: Option<Mmap>,
443
444 dynamic: Option<mmap_dynamic::MmapDynamicDiskANN<T, D>>,
446
447 dist: D,
449
450 _phantom: PhantomData<T>,
452}
453
454impl<T, D> DiskANN<T, D>
457where
458 T: bytemuck::Pod + Copy + Send + Sync + 'static,
459 D: Distance<T> + Send + Sync + Copy + Clone + 'static,
460{
461 fn from_dynamic(dynamic: mmap_dynamic::MmapDynamicDiskANN<T, D>, dist: D) -> Self {
462 Self {
463 dim: dynamic.dim(),
464 num_vectors: dynamic.len(),
465 max_degree: dynamic.max_degree(),
466 distance_name: dynamic.distance_name().to_string(),
467 medoid_id: dynamic.medoid_id(),
468 vectors_offset: 0,
469 adjacency_offset: 0,
470 mmap: None,
471 dynamic: Some(dynamic),
472 dist,
473 _phantom: PhantomData,
474 }
475 }
476
477 pub fn build_index_default(
479 vectors: &[Vec<T>],
480 dist: D,
481 file_path: &str,
482 ) -> Result<Self, DiskAnnError> {
483 Self::build_index(
484 vectors,
485 DISKANN_DEFAULT_MAX_DEGREE,
486 DISKANN_DEFAULT_BUILD_BEAM,
487 DISKANN_DEFAULT_ALPHA,
488 DISKANN_DEFAULT_EXTRA_SEEDS,
489 dist,
490 file_path,
491 )
492 }
493
494 pub fn build_index_with_params(
496 vectors: &[Vec<T>],
497 dist: D,
498 file_path: &str,
499 p: DiskAnnParams,
500 ) -> Result<Self, DiskAnnError> {
501 Self::build_index(
502 vectors,
503 p.max_degree,
504 p.build_beam_width,
505 p.alpha,
506 p.extra_seeds,
507 dist,
508 file_path,
509 )
510 }
511
512 pub fn open_index_with(path: &str, dist: D) -> Result<Self, DiskAnnError> {
514 let mut file = OpenOptions::new().read(true).write(false).open(path)?;
515
516 let mut buf8 = [0u8; 8];
518 file.seek(SeekFrom::Start(0))?;
519 file.read_exact(&mut buf8)?;
520 let md_len = u64::from_le_bytes(buf8);
521
522 let mut md_bytes = vec![0u8; md_len as usize];
524 file.read_exact(&mut md_bytes)?;
525 let metadata: Metadata = bincode::deserialize(&md_bytes)?;
526
527 let mmap = unsafe { memmap2::Mmap::map(&file)? };
528
529 let want = std::mem::size_of::<T>() as u8;
531 if metadata.elem_size != want {
532 return Err(DiskAnnError::IndexError(format!(
533 "element size mismatch: file has {}B, T is {}B",
534 metadata.elem_size, want
535 )));
536 }
537
538 let expected = std::any::type_name::<D>();
540 if metadata.distance_name != expected {
541 eprintln!(
542 "Warning: index recorded distance `{}` but you opened with `{}`",
543 metadata.distance_name, expected
544 );
545 }
546
547 Ok(Self {
548 dim: metadata.dim,
549 num_vectors: metadata.num_vectors,
550 max_degree: metadata.max_degree,
551 distance_name: metadata.distance_name,
552 medoid_id: metadata.medoid_id,
553 vectors_offset: metadata.vectors_offset,
554 adjacency_offset: metadata.adjacency_offset,
555 mmap: Some(mmap),
556 dynamic: None,
557 dist,
558 _phantom: PhantomData,
559 })
560 }
561
562 pub fn begin_updates(
566 index: &Self,
567 capacity: usize,
568 alpha: f32,
569 path: &str,
570 ) -> Result<Self, DiskAnnError> {
571 if index.dynamic.is_some() {
572 return Err(DiskAnnError::IndexError(
573 "source index is already dynamic".into(),
574 ));
575 }
576 let dynamic =
577 mmap_dynamic::MmapDynamicDiskANN::create_from_static(index, capacity, alpha, path)?;
578 Ok(Self::from_dynamic(dynamic, index.dist))
579 }
580
581 pub fn is_updating(&self) -> bool {
583 self.dynamic.is_some()
584 }
585
586 pub fn capacity(&self) -> usize {
588 self.dynamic
589 .as_ref()
590 .map_or(self.num_vectors, |dynamic| dynamic.capacity())
591 }
592
593 pub fn insert(&mut self, vector: Vec<T>, beam: usize) -> Result<u32, DiskAnnError> {
595 let dynamic = self
596 .dynamic
597 .as_mut()
598 .ok_or_else(|| DiskAnnError::IndexError("begin_updates must be called first".into()))?;
599 let id = dynamic.insert(vector, beam)?;
600 self.num_vectors = dynamic.len();
601 Ok(id)
602 }
603
604 pub fn insert_batch(
606 &mut self,
607 vectors: Vec<Vec<T>>,
608 beam: usize,
609 ) -> Result<Vec<u32>, DiskAnnError> {
610 let dynamic = self
611 .dynamic
612 .as_mut()
613 .ok_or_else(|| DiskAnnError::IndexError("begin_updates must be called first".into()))?;
614 let ids = dynamic.insert_batch(vectors, beam)?;
615 self.num_vectors = dynamic.len();
616 Ok(ids)
617 }
618
619 pub fn delete(
621 &mut self,
622 id: u32,
623 repair_beam: usize,
624 repair_degree: usize,
625 ) -> Result<Option<DeleteStats>, DiskAnnError> {
626 let mut stats = self.delete_batch(&[id], repair_beam, repair_degree)?;
627 Ok(stats.pop())
628 }
629
630 pub fn delete_batch(
632 &mut self,
633 ids: &[u32],
634 repair_beam: usize,
635 repair_degree: usize,
636 ) -> Result<Vec<DeleteStats>, DiskAnnError> {
637 let dynamic = self
638 .dynamic
639 .as_mut()
640 .ok_or_else(|| DiskAnnError::IndexError("begin_updates must be called first".into()))?;
641 let stats = dynamic.delete_batch(ids, repair_beam, repair_degree);
642 self.num_vectors = dynamic.len();
643 Ok(stats)
644 }
645
646 pub fn flush(&self) -> Result<(), DiskAnnError> {
648 if let Some(dynamic) = &self.dynamic {
649 dynamic.flush()?;
650 }
651 Ok(())
652 }
653
654 pub fn commit_updates_to_static(
660 self,
661 path: &str,
662 ) -> Result<(Self, Vec<Option<u32>>), DiskAnnError> {
663 let dynamic = self.dynamic.as_ref().ok_or_else(|| {
664 DiskAnnError::IndexError("commit requires a dynamic update session".into())
665 })?;
666 let (vectors, graph, medoid_id, id_map) = dynamic.static_snapshot();
667 let work_path = dynamic.work_path().to_path_buf();
668 if vectors.is_empty() {
669 return Err(DiskAnnError::IndexError(
670 "cannot commit an empty static index".into(),
671 ));
672 }
673 let temporary = format!("{path}.static-commit-{}", std::process::id());
674 let dist = self.dist;
675 let result = write_static_graph(
676 &vectors,
677 &graph,
678 self.max_degree,
679 medoid_id,
680 &self.distance_name,
681 &temporary,
682 );
683 drop(self);
684 result?;
685 std::fs::rename(&temporary, path)?;
686 if work_path != std::path::Path::new(path) {
687 let _ = std::fs::remove_file(work_path);
688 }
689 Ok((Self::open_index_with(path, dist)?, id_map))
690 }
691}
692
693fn write_static_graph<T: bytemuck::Pod>(
694 vectors: &[Vec<T>],
695 graph: &[Vec<u32>],
696 max_degree: usize,
697 medoid_id: u32,
698 distance_name: &str,
699 path: &str,
700) -> Result<(), DiskAnnError> {
701 let dim = vectors[0].len();
702 if vectors.iter().any(|vector| vector.len() != dim) || graph.len() != vectors.len() {
703 return Err(DiskAnnError::IndexError(
704 "invalid static snapshot dimensions".into(),
705 ));
706 }
707 let vectors_offset = 1024 * 1024u64;
708 let adjacency_offset = vectors_offset + (vectors.len() * dim * std::mem::size_of::<T>()) as u64;
709 let mut file = OpenOptions::new()
710 .create(true)
711 .truncate(true)
712 .read(true)
713 .write(true)
714 .open(path)?;
715 file.seek(SeekFrom::Start(vectors_offset))?;
716 for vector in vectors {
717 file.write_all(bytemuck::cast_slice(vector))?;
718 }
719 file.seek(SeekFrom::Start(adjacency_offset))?;
720 for neighbors in graph {
721 let mut row = neighbors
722 .iter()
723 .copied()
724 .take(max_degree)
725 .collect::<Vec<_>>();
726 row.resize(max_degree, PAD_U32);
727 file.write_all(bytemuck::cast_slice(&row))?;
728 }
729 let metadata = Metadata {
730 dim,
731 num_vectors: vectors.len(),
732 max_degree,
733 medoid_id,
734 vectors_offset,
735 adjacency_offset,
736 elem_size: std::mem::size_of::<T>() as u8,
737 distance_name: distance_name.to_owned(),
738 };
739 let bytes = bincode::serialize(&metadata)?;
740 file.seek(SeekFrom::Start(0))?;
741 file.write_all(&(bytes.len() as u64).to_le_bytes())?;
742 file.write_all(&bytes)?;
743 file.sync_all()?;
744 Ok(())
745}
746
747impl<T, D> DiskANN<T, D>
749where
750 T: bytemuck::Pod + Copy + Send + Sync + 'static,
751 D: Distance<T> + Default + Send + Sync + Copy + Clone + 'static,
752{
753 pub fn build_index_default_metric(
755 vectors: &[Vec<T>],
756 file_path: &str,
757 ) -> Result<Self, DiskAnnError> {
758 Self::build_index_default(vectors, D::default(), file_path)
759 }
760
761 pub fn open_index_default_metric(path: &str) -> Result<Self, DiskAnnError> {
763 Self::open_index_with(path, D::default())
764 }
765}
766
767impl<T, D> DiskANN<T, D>
768where
769 T: bytemuck::Pod + Copy + Send + Sync + 'static,
770 D: Distance<T> + Send + Sync + Copy + Clone + 'static,
771{
772 pub fn build_index(
783 vectors: &[Vec<T>],
784 max_degree: usize,
785 build_beam_width: usize,
786 alpha: f32,
787 extra_seeds: usize,
788 dist: D,
789 file_path: &str,
790 ) -> Result<Self, DiskAnnError> {
791 let flat = FlatVectors::from_vecs(vectors)?;
792
793 let num_vectors = flat.n;
794 let dim = flat.dim;
795
796 let mut file = OpenOptions::new()
797 .create(true)
798 .write(true)
799 .read(true)
800 .truncate(true)
801 .open(file_path)?;
802
803 let vectors_offset = 1024 * 1024;
805 assert_eq!(
806 (vectors_offset as usize) % std::mem::align_of::<T>(),
807 0,
808 "vectors_offset must be aligned for T"
809 );
810
811 let elem_sz = std::mem::size_of::<T>() as u64;
812 let total_vector_bytes = (num_vectors as u64) * (dim as u64) * elem_sz;
813
814 file.seek(SeekFrom::Start(vectors_offset as u64))?;
816 file.write_all(bytemuck::cast_slice::<T, u8>(&flat.data))?;
817
818 let medoid_id = calculate_medoid(&flat, dist);
820
821 let adjacency_offset = vectors_offset as u64 + total_vector_bytes;
823 let graph = build_vamana_graph(
824 &flat,
825 max_degree,
826 build_beam_width,
827 alpha,
828 extra_seeds,
829 dist,
830 medoid_id as u32,
831 );
832
833 file.seek(SeekFrom::Start(adjacency_offset))?;
835 for neighbors in &graph {
836 let mut padded = neighbors.clone();
837 padded.resize(max_degree, PAD_U32);
838 let bytes = bytemuck::cast_slice::<u32, u8>(&padded);
839 file.write_all(bytes)?;
840 }
841
842 let metadata = Metadata {
844 dim,
845 num_vectors,
846 max_degree,
847 medoid_id: medoid_id as u32,
848 vectors_offset: vectors_offset as u64,
849 adjacency_offset,
850 elem_size: std::mem::size_of::<T>() as u8,
851 distance_name: std::any::type_name::<D>().to_string(),
852 };
853
854 let md_bytes = bincode::serialize(&metadata)?;
855 file.seek(SeekFrom::Start(0))?;
856 let md_len = md_bytes.len() as u64;
857 file.write_all(&md_len.to_le_bytes())?;
858 file.write_all(&md_bytes)?;
859 file.sync_all()?;
860
861 let mmap = unsafe { memmap2::Mmap::map(&file)? };
863
864 Ok(Self {
865 dim,
866 num_vectors,
867 max_degree,
868 distance_name: metadata.distance_name,
869 medoid_id: metadata.medoid_id,
870 vectors_offset: metadata.vectors_offset,
871 adjacency_offset: metadata.adjacency_offset,
872 mmap: Some(mmap),
873 dynamic: None,
874 dist,
875 _phantom: PhantomData,
876 })
877 }
878
879 pub fn search_with_dists(&self, query: &[T], k: usize, beam_width: usize) -> Vec<(u32, f32)> {
882 if let Some(dynamic) = &self.dynamic {
883 return dynamic.search_with_dists(query, k, beam_width);
884 }
885 assert_eq!(
886 query.len(),
887 self.dim,
888 "Query dim {} != index dim {}",
889 query.len(),
890 self.dim
891 );
892
893 let mut results = graph_search(
894 self.medoid_id,
895 beam_width,
896 |id| self.distance_to(query, id as usize),
897 |id| {
898 self.get_neighbors(id)
899 .iter()
900 .copied()
901 .filter(|neighbor| *neighbor != PAD_U32)
902 .collect()
903 },
904 );
905 results.truncate(k);
906 results.into_iter().map(|c| (c.id, c.dist)).collect()
907 }
908
909 pub fn search(&self, query: &[T], k: usize, beam_width: usize) -> Vec<u32> {
911 self.search_with_dists(query, k, beam_width)
912 .into_iter()
913 .map(|(id, _dist)| id)
914 .collect()
915 }
916
917 fn get_neighbors(&self, node_id: u32) -> &[u32] {
919 let offset = self.adjacency_offset + (node_id as u64 * self.max_degree as u64 * 4);
920 let start = offset as usize;
921 let end = start + (self.max_degree * 4);
922 let bytes = &self.mmap.as_ref().expect("static mmap missing")[start..end];
923 bytemuck::cast_slice(bytes)
924 }
925
926 fn distance_to(&self, query: &[T], idx: usize) -> f32 {
928 let elem_sz = std::mem::size_of::<T>();
929 let offset = self.vectors_offset + (idx as u64 * self.dim as u64 * elem_sz as u64);
930 let start = offset as usize;
931 let end = start + (self.dim * elem_sz);
932 let bytes = &self.mmap.as_ref().expect("static mmap missing")[start..end];
933 let vector: &[T] = bytemuck::cast_slice(bytes);
934 self.dist.eval(query, vector)
935 }
936
937 pub fn get_vector(&self, idx: usize) -> Vec<T> {
939 if let Some(dynamic) = &self.dynamic {
940 return dynamic.get_vector(idx);
941 }
942 let elem_sz = std::mem::size_of::<T>();
943 let offset = self.vectors_offset + (idx as u64 * self.dim as u64 * elem_sz as u64);
944 let start = offset as usize;
945 let end = start + (self.dim * elem_sz);
946 let bytes = &self.mmap.as_ref().expect("static mmap missing")[start..end];
947 let vector: &[T] = bytemuck::cast_slice(bytes);
948 vector.to_vec()
949 }
950}
951
952fn calculate_medoid<T, D>(vectors: &FlatVectors<T>, dist: D) -> usize
954where
955 T: bytemuck::Pod + Copy + Send + Sync,
956 D: Distance<T> + Copy + Sync,
957{
958 let n = vectors.n;
959 let k = 8.min(n);
960 let mut rng = thread_rng();
961 let pivots: Vec<usize> = (0..k).map(|_| rng.gen_range(0..n)).collect();
962
963 let (best_idx, _best_score) = (0..n)
964 .into_par_iter()
965 .map(|i| {
966 let vi = vectors.row(i);
967 let score: f32 = pivots.iter().map(|&p| dist.eval(vi, vectors.row(p))).sum();
968 (i, score)
969 })
970 .reduce(|| (0usize, f32::MAX), |a, b| if a.1 <= b.1 { a } else { b });
971
972 best_idx
973}
974
975fn dedup_keep_best_by_id_in_place(cands: &mut Vec<(u32, f32)>) {
976 if cands.is_empty() {
977 return;
978 }
979
980 cands.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.total_cmp(&b.1)));
981
982 let mut write = 0usize;
983 for read in 0..cands.len() {
984 if write == 0 || cands[read].0 != cands[write - 1].0 {
985 cands[write] = cands[read];
986 write += 1;
987 }
988 }
989 cands.truncate(write);
990}
991
992fn merge_chunk_updates_into_graph_reuse<T, D>(
999 graph: &mut [Vec<u32>],
1000 chunk_nodes: &[usize],
1001 chunk_pruned: &[Vec<u32>],
1002 vectors: &FlatVectors<T>,
1003 max_degree: usize,
1004 slack_limit: usize,
1005 alpha: f32,
1006 dist: D,
1007 merge: &mut MergeScratch,
1008) where
1009 T: bytemuck::Pod + Copy + Send + Sync,
1010 D: Distance<T> + Copy + Sync,
1011{
1012 merge.reset();
1013
1014 for &u in chunk_nodes {
1016 merge.mark_affected(u);
1017 }
1018
1019 let mut total_incoming = 0usize;
1021
1022 for (local_idx, &u) in chunk_nodes.iter().enumerate() {
1023 for &dst in &chunk_pruned[local_idx] {
1024 let dst_usize = dst as usize;
1025 if dst_usize == u {
1026 continue;
1027 }
1028
1029 merge.mark_affected(dst_usize);
1030 merge.incoming_counts[dst_usize] += 1;
1031 total_incoming += 1;
1032 }
1033 }
1034
1035 merge.affected_nodes.sort_unstable();
1037
1038 let mut running = 0usize;
1039 for &u in &merge.affected_nodes {
1040 merge.incoming_offsets[u] = running;
1041 running += merge.incoming_counts[u];
1042 merge.incoming_offsets[u + 1] = running;
1043 }
1044
1045 merge.incoming_flat.resize(total_incoming, PAD_U32);
1046
1047 for &u in &merge.affected_nodes {
1049 merge.incoming_write[u] = merge.incoming_offsets[u];
1050 }
1051
1052 for (local_idx, &u) in chunk_nodes.iter().enumerate() {
1054 for &dst in &chunk_pruned[local_idx] {
1055 let dst_usize = dst as usize;
1056 if dst_usize == u {
1057 continue;
1058 }
1059
1060 let pos = merge.incoming_write[dst_usize];
1061 merge.incoming_flat[pos] = u as u32;
1062 merge.incoming_write[dst_usize] += 1;
1063 }
1064 }
1065
1066 for (local_idx, &u) in chunk_nodes.iter().enumerate() {
1068 graph[u] = chunk_pruned[local_idx].clone();
1069 }
1070
1071 let affected = merge.affected_nodes.clone();
1074
1075 let updated_pairs: Vec<(usize, Vec<u32>)> = affected
1076 .into_par_iter()
1077 .map(|u| {
1078 let start = merge.incoming_offsets[u];
1079 let end = merge.incoming_offsets[u + 1];
1080
1081 let mut ids: Vec<u32> = Vec::with_capacity(graph[u].len() + (end - start));
1082
1083 ids.extend_from_slice(&graph[u]);
1085
1086 if start < end {
1088 ids.extend_from_slice(&merge.incoming_flat[start..end]);
1089 }
1090
1091 ids.retain(|&id| id != PAD_U32 && id as usize != u);
1093
1094 ids.sort_unstable();
1096 ids.dedup();
1097
1098 if ids.is_empty() {
1099 return (u, Vec::new());
1100 }
1101
1102 if ids.len() <= slack_limit {
1104 return (u, ids);
1105 }
1106
1107 let mut pool = Vec::<(u32, f32)>::with_capacity(ids.len());
1109 for id in ids {
1110 let d = dist.eval(vectors.row(u), vectors.row(id as usize));
1111 pool.push((id, d));
1112 }
1113
1114 let pruned = prune_neighbors(u, &pool, vectors, max_degree, alpha, dist);
1115 (u, pruned)
1116 })
1117 .collect();
1118
1119 for (u, neigh) in updated_pairs {
1120 graph[u] = neigh;
1121 }
1122
1123 for &u in &merge.affected_nodes {
1125 merge.incoming_counts[u] = 0;
1126 merge.incoming_offsets[u + 1] = 0;
1127 }
1128}
1129
1130#[derive(Debug)]
1140struct MergeScratch {
1141 incoming_counts: Vec<usize>,
1142 incoming_offsets: Vec<usize>,
1143 incoming_write: Vec<usize>,
1144 incoming_flat: Vec<u32>,
1145
1146 affected_marks: Vec<u32>,
1147 affected_epoch: u32,
1148 affected_nodes: Vec<usize>,
1149}
1150
1151impl MergeScratch {
1152 fn new(n: usize) -> Self {
1153 Self {
1154 incoming_counts: vec![0usize; n],
1155 incoming_offsets: vec![0usize; n + 1],
1156 incoming_write: vec![0usize; n],
1157 incoming_flat: Vec::new(),
1158 affected_marks: vec![0u32; n],
1159 affected_epoch: 1,
1160 affected_nodes: Vec::new(),
1161 }
1162 }
1163
1164 #[inline]
1165 fn reset(&mut self) {
1166 self.affected_epoch = self.affected_epoch.wrapping_add(1);
1167 if self.affected_epoch == 0 {
1168 self.affected_marks.fill(0);
1169 self.affected_epoch = 1;
1170 }
1171 self.affected_nodes.clear();
1172 self.incoming_flat.clear();
1173 }
1174
1175 #[inline]
1176 fn mark_affected(&mut self, u: usize) {
1177 if self.affected_marks[u] != self.affected_epoch {
1178 self.affected_marks[u] = self.affected_epoch;
1179 self.affected_nodes.push(u);
1180 self.incoming_counts[u] = 0;
1181 }
1182 }
1183}
1184
1185fn build_vamana_graph<T, D>(
1188 vectors: &FlatVectors<T>,
1189 max_degree: usize,
1190 build_beam_width: usize,
1191 alpha: f32,
1192 extra_seeds: usize,
1193 dist: D,
1194 medoid_id: u32,
1195) -> Vec<Vec<u32>>
1196where
1197 T: bytemuck::Pod + Copy + Send + Sync,
1198 D: Distance<T> + Copy + Sync,
1199{
1200 let n = vectors.n;
1201 let mut graph = vec![Vec::<u32>::new(); n];
1202 {
1204 let mut rng = thread_rng();
1205 let target = max_degree.min(n.saturating_sub(1));
1206
1207 for i in 0..n {
1208 let mut s = HashSet::with_capacity(target);
1209 while s.len() < target {
1210 let nb = rng.gen_range(0..n);
1211 if nb != i {
1212 s.insert(nb as u32);
1213 }
1214 }
1215 graph[i] = s.into_iter().collect();
1216 }
1217 }
1218
1219 let mut rng = thread_rng();
1220 let slack_limit = ((GRAPH_SLACK_FACTOR * max_degree as f32).ceil() as usize).max(max_degree);
1221
1222 let mut merge_scratch = MergeScratch::new(n);
1224
1225 let mut order: Vec<usize> = (0..n).collect();
1226 order.shuffle(&mut rng);
1227
1228 for chunk in order.chunks(MICRO_BATCH_CHUNK_SIZE) {
1229 let snapshot = &graph;
1230 let chunk_results: Vec<(usize, Vec<u32>)> = chunk
1232 .par_iter()
1233 .map_init(
1234 || IncrementalInsertScratch::new(n, build_beam_width, max_degree, extra_seeds),
1235 |scratch, &u| {
1236 let bs = &mut scratch.build;
1237 bs.candidates.clear();
1238
1239 for &nb in &snapshot[u] {
1241 let d = dist.eval(vectors.row(u), vectors.row(nb as usize));
1242 bs.candidates.push((nb, d));
1243 }
1244
1245 bs.seeds.clear();
1247 bs.seeds.push(medoid_id as usize);
1248
1249 let mut local_rng = thread_rng();
1250 while bs.seeds.len() < 1 + extra_seeds {
1251 let s = local_rng.gen_range(0..n);
1252 if !bs.seeds.contains(&s) {
1253 bs.seeds.push(s);
1254 }
1255 }
1256
1257 let seeds_len = bs.seeds.len();
1258 for si in 0..seeds_len {
1259 let start = bs.seeds[si];
1260
1261 greedy_search_visited_collect(
1262 vectors.row(u),
1263 vectors,
1264 snapshot,
1265 start,
1266 build_beam_width,
1267 dist,
1268 bs,
1269 );
1270
1271 for i in 0..bs.visited_ids.len() {
1272 bs.candidates.push((bs.visited_ids[i], bs.visited_dists[i]));
1273 }
1274 }
1275
1276 dedup_keep_best_by_id_in_place(&mut bs.candidates);
1277
1278 let pruned =
1279 prune_neighbors(u, &bs.candidates, vectors, max_degree, alpha, dist);
1280
1281 (u, pruned)
1282 },
1283 )
1284 .collect();
1285
1286 let mut chunk_nodes = Vec::<usize>::with_capacity(chunk_results.len());
1287 let mut chunk_pruned = Vec::<Vec<u32>>::with_capacity(chunk_results.len());
1288
1289 for (u, pruned) in chunk_results {
1290 chunk_nodes.push(u);
1291 chunk_pruned.push(pruned);
1292 }
1293 merge_chunk_updates_into_graph_reuse(
1295 &mut graph,
1296 &chunk_nodes,
1297 &chunk_pruned,
1298 vectors,
1299 max_degree,
1300 slack_limit,
1301 alpha,
1302 dist,
1303 &mut merge_scratch,
1304 );
1305 }
1306
1307 graph
1309 .into_par_iter()
1310 .enumerate()
1311 .map(|(u, neigh)| {
1312 if neigh.len() <= max_degree {
1313 return neigh;
1314 }
1315
1316 let mut ids = neigh;
1317 ids.sort_unstable();
1318 ids.dedup();
1319
1320 let pool: Vec<(u32, f32)> = ids
1321 .into_iter()
1322 .filter(|&id| id as usize != u)
1323 .map(|id| (id, dist.eval(vectors.row(u), vectors.row(id as usize))))
1324 .collect();
1325
1326 prune_neighbors(u, &pool, vectors, max_degree, alpha, dist)
1327 })
1328 .collect()
1329}
1330
1331fn greedy_search_visited_collect<T, D>(
1337 query: &[T],
1338 vectors: &FlatVectors<T>,
1339 graph: &[Vec<u32>],
1340 start_id: usize,
1341 beam_width: usize,
1342 dist: D,
1343 scratch: &mut BuildScratch,
1344) where
1345 T: bytemuck::Pod + Copy + Send + Sync,
1346 D: Distance<T> + Copy,
1347{
1348 scratch.reset_search();
1349
1350 let start_dist = dist.eval(query, vectors.row(start_id));
1351 let start = Candidate {
1352 dist: start_dist,
1353 id: start_id as u32,
1354 };
1355
1356 scratch.frontier.insert_unbounded(start);
1357 scratch.work.insert_capped(start, beam_width);
1358 scratch.mark_with_dist(start_id, start_dist);
1359
1360 while !scratch.frontier.is_empty() {
1361 let best = scratch.frontier.best().unwrap();
1362 if scratch.work.len() >= beam_width {
1363 if let Some(worst) = scratch.work.worst() {
1364 if best.dist >= worst.dist {
1365 break;
1366 }
1367 }
1368 }
1369
1370 let cur = scratch.frontier.pop_best().unwrap();
1371
1372 for &nb in &graph[cur.id as usize] {
1373 let nb_usize = nb as usize;
1374 if scratch.is_marked(nb_usize) {
1375 continue;
1376 }
1377
1378 let d = dist.eval(query, vectors.row(nb_usize));
1379 scratch.mark_with_dist(nb_usize, d);
1380
1381 let cand = Candidate { dist: d, id: nb };
1382
1383 if scratch.work.len() < beam_width {
1384 scratch.work.insert_unbounded(cand);
1385 scratch.frontier.insert_unbounded(cand);
1386 } else if let Some(worst) = scratch.work.worst() {
1387 if d < worst.dist {
1388 scratch.work.insert_capped(cand, beam_width);
1389 scratch.frontier.insert_unbounded(cand);
1390 }
1391 }
1392 }
1393 }
1394}
1395
1396fn prune_neighbors<T, D>(
1398 node_id: usize,
1399 candidates: &[(u32, f32)],
1400 vectors: &FlatVectors<T>,
1401 max_degree: usize,
1402 alpha: f32,
1403 dist: D,
1404) -> Vec<u32>
1405where
1406 T: bytemuck::Pod + Copy + Send + Sync,
1407 D: Distance<T> + Copy,
1408{
1409 if candidates.is_empty() || max_degree == 0 {
1410 return Vec::new();
1411 }
1412
1413 let mut sorted = candidates.to_vec();
1415 sorted.sort_by(|a, b| a.1.total_cmp(&b.1));
1416 sorted.truncate(MAX_OCCLUSION_SIZE);
1417
1418 let mut uniq = Vec::<(u32, f32)>::with_capacity(sorted.len());
1420 let mut seen = HashSet::with_capacity(sorted.len());
1421 for &(cand_id, cand_dist) in &sorted {
1422 if cand_id as usize == node_id || !seen.insert(cand_id) {
1423 continue;
1424 }
1425 uniq.push((cand_id, cand_dist));
1426 }
1427
1428 if uniq.is_empty() {
1429 return Vec::new();
1430 }
1431
1432 let mut pruned = Vec::<u32>::with_capacity(max_degree);
1433 let mut occlude_factors = vec![0.0f32; uniq.len()];
1434 let target_alpha = alpha.max(1.0);
1435 let increment = target_alpha.min(1.2);
1436 let mut current_alpha = 1.0f32;
1437
1438 loop {
1439 for i in 0..uniq.len() {
1440 if pruned.len() >= max_degree {
1441 return pruned;
1442 }
1443 if occlude_factors[i] > current_alpha {
1444 continue;
1445 }
1446
1447 let (selected_id, _) = uniq[i];
1448 occlude_factors[i] = f32::MAX;
1449 pruned.push(selected_id);
1450
1451 for j in (i + 1)..uniq.len() {
1452 if occlude_factors[j] > target_alpha {
1453 continue;
1454 }
1455
1456 let (candidate_id, candidate_dist) = uniq[j];
1457 let pair_dist = dist.eval(
1458 vectors.row(candidate_id as usize),
1459 vectors.row(selected_id as usize),
1460 );
1461 let factor = if pair_dist == 0.0 {
1462 f32::MAX
1463 } else {
1464 candidate_dist / pair_dist
1465 };
1466 occlude_factors[j] = occlude_factors[j].max(factor);
1467 }
1468 }
1469
1470 if current_alpha >= target_alpha {
1471 break;
1472 }
1473 current_alpha = (current_alpha * increment).min(target_alpha);
1474 }
1475
1476 pruned
1477}
1478
1479#[cfg(test)]
1480mod tests {
1481 use super::*;
1482 use anndists::dist::{DistCosine, DistJaccard, DistL2};
1483 use rand::{Rng, SeedableRng, rngs::StdRng};
1484 use std::fs;
1485
1486 fn euclid(a: &[f32], b: &[f32]) -> f32 {
1487 a.iter()
1488 .zip(b)
1489 .map(|(x, y)| (x - y) * (x - y))
1490 .sum::<f32>()
1491 .sqrt()
1492 }
1493
1494 fn exact_recall<T, D>(
1495 index: &DiskANN<T, D>,
1496 vectors: &[Vec<T>],
1497 queries: &[Vec<T>],
1498 dist: D,
1499 k: usize,
1500 beam: usize,
1501 ) -> f32
1502 where
1503 T: bytemuck::Pod + Copy + Send + Sync + 'static,
1504 D: Distance<T> + Send + Sync + Copy + Clone + 'static,
1505 {
1506 let mut hits = 0usize;
1507 for query in queries {
1508 let mut truth: Vec<(usize, f32)> = vectors
1509 .iter()
1510 .enumerate()
1511 .map(|(id, vector)| (id, dist.eval(query, vector)))
1512 .collect();
1513 truth.sort_by(|a, b| a.1.total_cmp(&b.1));
1514 let truth: HashSet<u32> = truth.into_iter().take(k).map(|(id, _)| id as u32).collect();
1515
1516 hits += index
1517 .search(query, k, beam)
1518 .into_iter()
1519 .filter(|id| truth.contains(id))
1520 .count();
1521 }
1522 hits as f32 / (queries.len() * k) as f32
1523 }
1524
1525 fn quality_params() -> DiskAnnParams {
1526 DiskAnnParams {
1527 max_degree: 32,
1528 build_beam_width: 128,
1529 alpha: 1.2,
1530 extra_seeds: 1,
1531 }
1532 }
1533
1534 #[test]
1535 fn test_small_index_l2() {
1536 let path = "test_small_l2.db";
1537 let _ = fs::remove_file(path);
1538
1539 let vectors = vec![
1540 vec![0.0, 0.0],
1541 vec![1.0, 0.0],
1542 vec![0.0, 1.0],
1543 vec![1.0, 1.0],
1544 vec![0.5, 0.5],
1545 ];
1546
1547 let index = DiskANN::<f32, DistL2>::build_index_default(&vectors, DistL2, path).unwrap();
1548
1549 let q = vec![0.1, 0.1];
1550 let nns = index.search(&q, 3, 8);
1551 assert_eq!(nns.len(), 3);
1552
1553 let v = index.get_vector(nns[0] as usize);
1554 assert!(euclid(&q, &v) < 1.0);
1555
1556 let _ = fs::remove_file(path);
1557 }
1558
1559 #[test]
1560 fn update_session_commits_as_ordinary_static_index() {
1561 let static_path = "test_update_commit_static.db";
1562 let work_path = "test_update_commit_work.db";
1563 let _ = fs::remove_file(static_path);
1564 let _ = fs::remove_file(work_path);
1565 let vectors = (0..200)
1566 .map(|id| vec![id as f32, (id % 11) as f32])
1567 .collect::<Vec<_>>();
1568 let static_index = DiskANN::build_index_default(&vectors, DistL2, static_path).unwrap();
1569 let mut update = DiskANN::begin_updates(&static_index, 220, 1.2, work_path).unwrap();
1570 assert!(update.is_updating());
1571 assert!(update.delete(40, 64, 2).unwrap().is_some());
1572 let replacement = vec![40.25, 7.0];
1573 update.insert(replacement.clone(), 128).unwrap();
1574 drop(static_index);
1575
1576 let (committed, id_map) = update.commit_updates_to_static(static_path).unwrap();
1577 assert_eq!(id_map.len(), 220);
1578 assert!(!committed.is_updating());
1579 assert_eq!(committed.num_vectors, 200);
1580 assert_eq!(committed.search(&replacement, 1, 128).len(), 1);
1581 drop(committed);
1582
1583 let reopened = DiskANN::<f32, DistL2>::open_index_with(static_path, DistL2).unwrap();
1584 assert!(!reopened.is_updating());
1585 assert_eq!(reopened.num_vectors, 200);
1586 assert_eq!(reopened.search(&replacement, 1, 128).len(), 1);
1587 let _ = fs::remove_file(static_path);
1588 let _ = fs::remove_file(work_path);
1589 }
1590
1591 #[test]
1592 fn test_cosine() {
1593 let path = "test_cosine.db";
1594 let _ = fs::remove_file(path);
1595
1596 let vectors = vec![
1597 vec![1.0, 0.0, 0.0],
1598 vec![0.0, 1.0, 0.0],
1599 vec![0.0, 0.0, 1.0],
1600 vec![1.0, 1.0, 0.0],
1601 vec![1.0, 0.0, 1.0],
1602 ];
1603
1604 let index =
1605 DiskANN::<f32, DistCosine>::build_index_default(&vectors, DistCosine, path).unwrap();
1606
1607 let q = vec![2.0, 0.0, 0.0];
1608 let nns = index.search(&q, 2, 8);
1609 assert_eq!(nns.len(), 2);
1610
1611 let v = index.get_vector(nns[0] as usize);
1612 let dot = v.iter().zip(&q).map(|(a, b)| a * b).sum::<f32>();
1613 let n1 = v.iter().map(|x| x * x).sum::<f32>().sqrt();
1614 let n2 = q.iter().map(|x| x * x).sum::<f32>().sqrt();
1615 let cos = dot / (n1 * n2);
1616 assert!(cos > 0.7);
1617
1618 let _ = fs::remove_file(path);
1619 }
1620
1621 #[test]
1622 fn test_persistence_and_open() {
1623 let path = "test_persist.db";
1624 let _ = fs::remove_file(path);
1625
1626 let vectors = vec![
1627 vec![0.0, 0.0],
1628 vec![1.0, 0.0],
1629 vec![0.0, 1.0],
1630 vec![1.0, 1.0],
1631 ];
1632
1633 {
1634 let _idx = DiskANN::<f32, DistL2>::build_index_default(&vectors, DistL2, path).unwrap();
1635 }
1636
1637 let idx2 = DiskANN::<f32, DistL2>::open_index_default_metric(path).unwrap();
1638 assert_eq!(idx2.num_vectors, 4);
1639 assert_eq!(idx2.dim, 2);
1640
1641 let q = vec![0.9, 0.9];
1642 let res = idx2.search(&q, 2, 8);
1643 assert_eq!(res[0], 3);
1644
1645 let _ = fs::remove_file(path);
1646 }
1647
1648 #[test]
1649 fn test_grid_connectivity() {
1650 let path = "test_grid.db";
1651 let _ = fs::remove_file(path);
1652
1653 let mut vectors = Vec::new();
1654 for i in 0..5 {
1655 for j in 0..5 {
1656 vectors.push(vec![i as f32, j as f32]);
1657 }
1658 }
1659
1660 let index = DiskANN::<f32, DistL2>::build_index_with_params(
1661 &vectors,
1662 DistL2,
1663 path,
1664 DiskAnnParams {
1665 max_degree: 4,
1666 build_beam_width: 64,
1667 alpha: 1.5,
1668 extra_seeds: DISKANN_DEFAULT_EXTRA_SEEDS,
1669 },
1670 )
1671 .unwrap();
1672
1673 for target in 0..vectors.len() {
1674 let q = &vectors[target];
1675 let nns = index.search(q, 10, 32);
1676 if !nns.contains(&(target as u32)) {
1677 let v = index.get_vector(nns[0] as usize);
1678 assert!(euclid(q, &v) < 2.0);
1679 }
1680 for &nb in nns.iter().take(5) {
1681 let v = index.get_vector(nb as usize);
1682 assert!(euclid(q, &v) < 5.0);
1683 }
1684 }
1685
1686 let _ = fs::remove_file(path);
1687 }
1688
1689 #[test]
1690 fn test_medium_random() {
1691 let path = "test_medium.db";
1692 let _ = fs::remove_file(path);
1693
1694 let n = 200usize;
1695 let d = 32usize;
1696 let mut rng = rand::thread_rng();
1697 let vectors: Vec<Vec<f32>> = (0..n)
1698 .map(|_| (0..d).map(|_| rng.r#gen::<f32>()).collect())
1699 .collect();
1700
1701 let index = DiskANN::<f32, DistL2>::build_index_with_params(
1702 &vectors,
1703 DistL2,
1704 path,
1705 DiskAnnParams {
1706 max_degree: 32,
1707 build_beam_width: 128,
1708 alpha: 1.2,
1709 extra_seeds: DISKANN_DEFAULT_EXTRA_SEEDS,
1710 },
1711 )
1712 .unwrap();
1713
1714 let q: Vec<f32> = (0..d).map(|_| rng.r#gen::<f32>()).collect();
1715 let res = index.search(&q, 10, 64);
1716 assert_eq!(res.len(), 10);
1717
1718 let dists: Vec<f32> = res
1719 .iter()
1720 .map(|&id| {
1721 let v = index.get_vector(id as usize);
1722 euclid(&q, &v)
1723 })
1724 .collect();
1725 let mut sorted = dists.clone();
1726 sorted.sort_by(|a, b| a.total_cmp(b));
1727 assert_eq!(dists, sorted);
1728
1729 let _ = fs::remove_file(path);
1730 }
1731
1732 #[test]
1733 fn test_regular_l2_recall() {
1734 let path = "test_regular_l2_recall.db";
1735 let _ = fs::remove_file(path);
1736 let mut rng = StdRng::seed_from_u64(11);
1737 let vectors: Vec<Vec<f32>> = (0..500)
1738 .map(|_| (0..24).map(|_| rng.r#gen::<f32>()).collect())
1739 .collect();
1740 let queries: Vec<Vec<f32>> = (0..40)
1741 .map(|_| (0..24).map(|_| rng.r#gen::<f32>()).collect())
1742 .collect();
1743
1744 let index =
1745 DiskANN::build_index_with_params(&vectors, DistL2, path, quality_params()).unwrap();
1746 let recall = exact_recall(&index, &vectors, &queries, DistL2, 10, 256);
1747 assert!(recall >= 0.95, "regular L2 recall was {recall}");
1748 let _ = fs::remove_file(path);
1749 }
1750
1751 #[test]
1752 fn test_clustered_l2_recall() {
1753 let path = "test_clustered_l2_recall.db";
1754 let _ = fs::remove_file(path);
1755 let mut rng = StdRng::seed_from_u64(23);
1756 let dim = 24usize;
1757 let clusters = 12usize;
1758 let mut vectors = Vec::with_capacity(clusters * 50);
1759 let mut queries = Vec::with_capacity(clusters * 3);
1760
1761 for cluster in 0..clusters {
1762 let mut center = vec![0.0f32; dim];
1763 center[cluster] = 40.0;
1764 center[(cluster + 7) % dim] = -25.0;
1765 for _ in 0..50 {
1766 vectors.push(
1767 center
1768 .iter()
1769 .map(|value| value + rng.gen_range(-0.4f32..0.4f32))
1770 .collect(),
1771 );
1772 }
1773 for _ in 0..3 {
1774 queries.push(
1775 center
1776 .iter()
1777 .map(|value| value + rng.gen_range(-0.4f32..0.4f32))
1778 .collect(),
1779 );
1780 }
1781 }
1782
1783 let index =
1784 DiskANN::build_index_with_params(&vectors, DistL2, path, quality_params()).unwrap();
1785 let recall = exact_recall(&index, &vectors, &queries, DistL2, 10, 256);
1786 assert!(recall >= 0.95, "clustered L2 recall was {recall}");
1787 let _ = fs::remove_file(path);
1788 }
1789
1790 #[test]
1791 fn test_cosine_recall() {
1792 let path = "test_cosine_recall.db";
1793 let _ = fs::remove_file(path);
1794 let mut rng = StdRng::seed_from_u64(37);
1795 let vectors: Vec<Vec<f32>> = (0..500)
1796 .map(|_| (0..32).map(|_| rng.gen_range(-1.0f32..1.0f32)).collect())
1797 .collect();
1798 let queries: Vec<Vec<f32>> = (0..40)
1799 .map(|_| (0..32).map(|_| rng.gen_range(-1.0f32..1.0f32)).collect())
1800 .collect();
1801
1802 let index =
1803 DiskANN::build_index_with_params(&vectors, DistCosine, path, quality_params()).unwrap();
1804 let recall = exact_recall(&index, &vectors, &queries, DistCosine, 10, 256);
1805 assert!(recall >= 0.95, "cosine recall was {recall}");
1806 let _ = fs::remove_file(path);
1807 }
1808
1809 #[test]
1810 fn test_jaccard_recall() {
1811 let path = "test_jaccard_recall.db";
1812 let _ = fs::remove_file(path);
1813 let mut rng = StdRng::seed_from_u64(41);
1814 let vectors: Vec<Vec<u32>> = (0..400)
1815 .map(|_| (0..32).map(|_| rng.gen_range(0u32..8u32)).collect())
1816 .collect();
1817 let queries: Vec<Vec<u32>> = (0..40)
1818 .map(|_| (0..32).map(|_| rng.gen_range(0u32..8u32)).collect())
1819 .collect();
1820
1821 let index = DiskANN::build_index_with_params(&vectors, DistJaccard, path, quality_params())
1822 .unwrap();
1823 let recall = exact_recall(&index, &vectors, &queries, DistJaccard, 10, 256);
1824 assert!(recall >= 0.95, "Jaccard recall was {recall}");
1825 let _ = fs::remove_file(path);
1826 }
1827}