1use std::collections::BTreeMap;
4use std::fs::{self, File};
5use std::io::{BufReader, BufWriter, Write};
6use std::path::Path;
7
8use ndarray::{s, Array1, Array2, Axis};
9use serde::{Deserialize, Serialize};
10
11use crate::codec::ResidualCodec;
12use crate::error::{Error, Result};
13use crate::kmeans::{compute_kmeans, ComputeKmeansConfig};
14use crate::utils::{quantile, quantiles};
15
16fn compress_and_residuals_cpu(
18 embeddings: &Array2<f32>,
19 codec: &ResidualCodec,
20) -> (Array1<usize>, Array2<f32>) {
21 use rayon::prelude::*;
22
23 let codes = codec.compress_into_codes_cpu(embeddings);
25 let mut residuals = embeddings.clone();
26
27 let centroids = &codec.centroids;
28 residuals
29 .axis_iter_mut(Axis(0))
30 .into_par_iter()
31 .zip(codes.as_slice().unwrap().par_iter())
32 .for_each(|(mut row, &code)| {
33 let centroid = centroids.row(code);
34 row.iter_mut()
35 .zip(centroid.iter())
36 .for_each(|(r, c)| *r -= c);
37 });
38
39 (codes, residuals)
40}
41
42#[derive(Debug, Clone, Serialize, Deserialize)]
44pub struct IndexConfig {
45 pub nbits: usize,
47 pub batch_size: usize,
49 pub seed: Option<u64>,
51 #[serde(default = "default_kmeans_niters")]
53 pub kmeans_niters: usize,
54 #[serde(default = "default_max_points_per_centroid")]
56 pub max_points_per_centroid: usize,
57 #[serde(default)]
60 pub n_samples_kmeans: Option<usize>,
61 #[serde(default = "default_start_from_scratch")]
65 pub start_from_scratch: usize,
66 #[serde(default)]
69 pub force_cpu: bool,
70}
71
72fn default_start_from_scratch() -> usize {
73 999
74}
75
76fn default_kmeans_niters() -> usize {
77 4
78}
79
80fn default_max_points_per_centroid() -> usize {
81 256
82}
83
84impl Default for IndexConfig {
85 fn default() -> Self {
86 Self {
87 nbits: 4,
88 batch_size: 50_000,
89 seed: Some(42),
90 kmeans_niters: 4,
91 max_points_per_centroid: 256,
92 n_samples_kmeans: None,
93 start_from_scratch: 999,
94 force_cpu: false,
95 }
96 }
97}
98
99#[derive(Debug, Clone, Serialize, Deserialize)]
101pub struct Metadata {
102 pub num_chunks: usize,
104 pub nbits: usize,
106 pub num_partitions: usize,
108 pub num_embeddings: usize,
110 pub avg_doclen: f64,
112 #[serde(default)]
114 pub num_documents: usize,
115 #[serde(default)]
118 pub next_plaid_compatible: bool,
119}
120
121impl Metadata {
122 pub fn load_from_path(index_path: &Path) -> Result<Self> {
124 let metadata_path = index_path.join("metadata.json");
125 let mut metadata: Metadata = serde_json::from_reader(BufReader::new(
126 File::open(&metadata_path)
127 .map_err(|e| Error::IndexLoad(format!("Failed to open metadata: {}", e)))?,
128 ))?;
129
130 if metadata.num_documents == 0 {
132 let mut total_docs = 0usize;
133 for chunk_idx in 0..metadata.num_chunks {
134 let doclens_path = index_path.join(format!("doclens.{}.json", chunk_idx));
135 if let Ok(file) = File::open(&doclens_path) {
136 if let Ok(chunk_doclens) =
137 serde_json::from_reader::<_, Vec<i64>>(BufReader::new(file))
138 {
139 total_docs += chunk_doclens.len();
140 }
141 }
142 }
143 metadata.num_documents = total_docs;
144 }
145
146 Ok(metadata)
147 }
148}
149
150#[derive(Debug, Clone, Serialize, Deserialize)]
152pub struct ChunkMetadata {
153 pub num_documents: usize,
154 pub num_embeddings: usize,
155 #[serde(default)]
156 pub embedding_offset: usize,
157}
158
159pub fn create_index_files(
181 embeddings: &[Array2<f32>],
182 centroids: Array2<f32>,
183 index_path: &str,
184 config: &IndexConfig,
185) -> Result<Metadata> {
186 let index_dir = Path::new(index_path);
187 fs::create_dir_all(index_dir)?;
188
189 let num_documents = embeddings.len();
190 let embedding_dim = centroids.ncols();
191 let num_centroids = centroids.nrows();
192
193 if num_documents == 0 {
194 return Err(Error::IndexCreation("No documents provided".into()));
195 }
196
197 let total_embeddings: usize = embeddings.iter().map(|e| e.nrows()).sum();
199 let avg_doclen = total_embeddings as f64 / num_documents as f64;
200
201 let sample_count = ((16.0 * (120.0 * num_documents as f64).sqrt()) as usize)
203 .min(num_documents)
204 .max(1);
205
206 let mut rng = if let Some(seed) = config.seed {
207 use rand::SeedableRng;
208 rand_chacha::ChaCha8Rng::seed_from_u64(seed)
209 } else {
210 use rand::SeedableRng;
211 rand_chacha::ChaCha8Rng::from_entropy()
212 };
213
214 use rand::seq::SliceRandom;
215 let mut indices: Vec<usize> = (0..num_documents).collect();
216 indices.shuffle(&mut rng);
217 let sample_indices: Vec<usize> = indices.into_iter().take(sample_count).collect();
218
219 let heldout_size = (0.05 * total_embeddings as f64).min(50000.0) as usize;
221 let mut heldout_embeddings: Vec<f32> = Vec::with_capacity(heldout_size * embedding_dim);
222 let mut collected = 0;
223
224 for &idx in sample_indices.iter().rev() {
225 if collected >= heldout_size {
226 break;
227 }
228 let emb = &embeddings[idx];
229 let take = (heldout_size - collected).min(emb.nrows());
230 for row in emb.axis_iter(Axis(0)).take(take) {
231 heldout_embeddings.extend(row.iter());
232 }
233 collected += take;
234 }
235
236 let heldout = Array2::from_shape_vec((collected, embedding_dim), heldout_embeddings)
237 .map_err(|e| Error::IndexCreation(format!("Failed to create heldout array: {}", e)))?;
238
239 let avg_residual = Array1::zeros(embedding_dim);
241 let initial_codec =
242 ResidualCodec::new(config.nbits, centroids.clone(), avg_residual, None, None)?;
243
244 let heldout_codes = if config.force_cpu {
247 initial_codec.compress_into_codes_cpu(&heldout)
248 } else {
249 initial_codec.compress_into_codes(&heldout)
250 };
251
252 let mut residuals = heldout.clone();
254 for i in 0..heldout.nrows() {
255 let centroid = initial_codec.centroids.row(heldout_codes[i]);
256 for j in 0..embedding_dim {
257 residuals[[i, j]] -= centroid[j];
258 }
259 }
260
261 let distances: Array1<f32> = residuals
263 .axis_iter(Axis(0))
264 .map(|row| row.dot(&row).sqrt())
265 .collect();
266 #[allow(unused_variables)]
267 let cluster_threshold = quantile(&distances, 0.75);
268
269 let avg_res_per_dim: Array1<f32> = residuals
271 .axis_iter(Axis(1))
272 .map(|col| col.iter().map(|x| x.abs()).sum::<f32>() / col.len() as f32)
273 .collect();
274
275 let n_options = 1 << config.nbits;
277 let quantile_values: Vec<f64> = (1..n_options)
278 .map(|i| i as f64 / n_options as f64)
279 .collect();
280 let weight_quantile_values: Vec<f64> = (0..n_options)
281 .map(|i| (i as f64 + 0.5) / n_options as f64)
282 .collect();
283
284 let flat_residuals: Array1<f32> = residuals.iter().copied().collect();
286 let bucket_cutoffs = Array1::from_vec(quantiles(&flat_residuals, &quantile_values));
287 let bucket_weights = Array1::from_vec(quantiles(&flat_residuals, &weight_quantile_values));
288
289 let codec = ResidualCodec::new(
290 config.nbits,
291 centroids.clone(),
292 avg_res_per_dim.clone(),
293 Some(bucket_cutoffs.clone()),
294 Some(bucket_weights.clone()),
295 )?;
296
297 use ndarray_npy::WriteNpyExt;
299
300 let centroids_path = index_dir.join("centroids.npy");
301 codec
302 .centroids_view()
303 .to_owned()
304 .write_npy(File::create(¢roids_path)?)?;
305
306 let cutoffs_path = index_dir.join("bucket_cutoffs.npy");
307 bucket_cutoffs.write_npy(File::create(&cutoffs_path)?)?;
308
309 let weights_path = index_dir.join("bucket_weights.npy");
310 bucket_weights.write_npy(File::create(&weights_path)?)?;
311
312 let avg_res_path = index_dir.join("avg_residual.npy");
313 avg_res_per_dim.write_npy(File::create(&avg_res_path)?)?;
314
315 let threshold_path = index_dir.join("cluster_threshold.npy");
316 Array1::from_vec(vec![cluster_threshold]).write_npy(File::create(&threshold_path)?)?;
317
318 let n_chunks = (num_documents as f64 / config.batch_size as f64).ceil() as usize;
320
321 let plan_path = index_dir.join("plan.json");
323 let plan = serde_json::json!({
324 "nbits": config.nbits,
325 "num_chunks": n_chunks,
326 });
327 let mut plan_file = File::create(&plan_path)?;
328 writeln!(plan_file, "{}", serde_json::to_string_pretty(&plan)?)?;
329
330 let mut all_codes: Vec<usize> = Vec::with_capacity(total_embeddings);
331 let mut doc_lengths: Vec<i64> = Vec::with_capacity(num_documents);
332
333 for chunk_idx in 0..n_chunks {
334 let start = chunk_idx * config.batch_size;
335 let end = (start + config.batch_size).min(num_documents);
336 let chunk_docs = &embeddings[start..end];
337
338 let chunk_doclens: Vec<i64> = chunk_docs.iter().map(|d| d.nrows() as i64).collect();
340 let total_tokens: usize = chunk_doclens.iter().sum::<i64>() as usize;
341
342 let mut batch_embeddings = Array2::<f32>::zeros((total_tokens, embedding_dim));
344 let mut offset = 0;
345 for doc in chunk_docs {
346 let n = doc.nrows();
347 batch_embeddings
348 .slice_mut(s![offset..offset + n, ..])
349 .assign(doc);
350 offset += n;
351 }
352
353 let (batch_codes, batch_residuals) = {
356 #[cfg(feature = "cuda")]
357 {
358 if !config.force_cpu {
359 if let Some(ctx) = crate::cuda::get_global_context() {
360 match crate::cuda::compress_and_residuals_cuda_batched(
361 ctx,
362 &batch_embeddings.view(),
363 &codec.centroids_view(),
364 None,
365 ) {
366 Ok(result) => result,
367 Err(e) => {
368 eprintln!(
369 "[next-plaid] CUDA compress_and_residuals failed: {}, falling back to CPU",
370 e
371 );
372 compress_and_residuals_cpu(&batch_embeddings, &codec)
373 }
374 }
375 } else {
376 compress_and_residuals_cpu(&batch_embeddings, &codec)
377 }
378 } else {
379 compress_and_residuals_cpu(&batch_embeddings, &codec)
380 }
381 }
382 #[cfg(not(feature = "cuda"))]
383 {
384 compress_and_residuals_cpu(&batch_embeddings, &codec)
385 }
386 };
387
388 let batch_packed = codec.quantize_residuals(&batch_residuals)?;
390
391 for &len in &chunk_doclens {
393 doc_lengths.push(len);
394 }
395 all_codes.extend(batch_codes.iter().copied());
396
397 let chunk_meta = ChunkMetadata {
399 num_documents: end - start,
400 num_embeddings: batch_codes.len(),
401 embedding_offset: 0, };
403
404 let chunk_meta_path = index_dir.join(format!("{}.metadata.json", chunk_idx));
405 serde_json::to_writer_pretty(BufWriter::new(File::create(&chunk_meta_path)?), &chunk_meta)?;
406
407 let doclens_path = index_dir.join(format!("doclens.{}.json", chunk_idx));
409 serde_json::to_writer(BufWriter::new(File::create(&doclens_path)?), &chunk_doclens)?;
410
411 let chunk_codes_arr: Array1<i64> = batch_codes.iter().map(|&x| x as i64).collect();
413 let codes_path = index_dir.join(format!("{}.codes.npy", chunk_idx));
414 chunk_codes_arr.write_npy(File::create(&codes_path)?)?;
415
416 let residuals_path = index_dir.join(format!("{}.residuals.npy", chunk_idx));
418 batch_packed.write_npy(File::create(&residuals_path)?)?;
419 }
420
421 let mut current_offset = 0usize;
423 for chunk_idx in 0..n_chunks {
424 let chunk_meta_path = index_dir.join(format!("{}.metadata.json", chunk_idx));
425 let mut meta: serde_json::Value =
426 serde_json::from_reader(BufReader::new(File::open(&chunk_meta_path)?))?;
427
428 if let Some(obj) = meta.as_object_mut() {
429 obj.insert("embedding_offset".to_string(), current_offset.into());
430 let num_emb = obj["num_embeddings"].as_u64().unwrap_or(0) as usize;
431 current_offset += num_emb;
432 }
433
434 serde_json::to_writer_pretty(BufWriter::new(File::create(&chunk_meta_path)?), &meta)?;
435 }
436
437 let mut code_to_docs: BTreeMap<usize, Vec<i64>> = BTreeMap::new();
439 let mut emb_idx = 0;
440
441 for (doc_id, &len) in doc_lengths.iter().enumerate() {
442 for _ in 0..len {
443 let code = all_codes[emb_idx];
444 code_to_docs.entry(code).or_default().push(doc_id as i64);
445 emb_idx += 1;
446 }
447 }
448
449 let mut ivf_data: Vec<i64> = Vec::new();
451 let mut ivf_lengths: Vec<i32> = vec![0; num_centroids];
452
453 for (centroid_id, ivf_len) in ivf_lengths.iter_mut().enumerate() {
454 if let Some(docs) = code_to_docs.get(¢roid_id) {
455 let mut unique_docs: Vec<i64> = docs.clone();
456 unique_docs.sort_unstable();
457 unique_docs.dedup();
458 *ivf_len = unique_docs.len() as i32;
459 ivf_data.extend(unique_docs);
460 }
461 }
462
463 let ivf = Array1::from_vec(ivf_data);
464 let ivf_lengths = Array1::from_vec(ivf_lengths);
465
466 let ivf_path = index_dir.join("ivf.npy");
467 ivf.write_npy(File::create(&ivf_path)?)?;
468
469 let ivf_lengths_path = index_dir.join("ivf_lengths.npy");
470 ivf_lengths.write_npy(File::create(&ivf_lengths_path)?)?;
471
472 let metadata = Metadata {
474 num_chunks: n_chunks,
475 nbits: config.nbits,
476 num_partitions: num_centroids,
477 num_embeddings: total_embeddings,
478 avg_doclen,
479 num_documents,
480 next_plaid_compatible: true, };
482
483 let metadata_path = index_dir.join("metadata.json");
484 serde_json::to_writer_pretty(BufWriter::new(File::create(&metadata_path)?), &metadata)?;
485
486 Ok(metadata)
487}
488
489pub fn create_index_with_kmeans_files(
504 embeddings: &[Array2<f32>],
505 index_path: &str,
506 config: &IndexConfig,
507) -> Result<Metadata> {
508 if embeddings.is_empty() {
509 return Err(Error::IndexCreation("No documents provided".into()));
510 }
511
512 #[cfg(feature = "cuda")]
515 if !config.force_cpu {
516 let _ = crate::cuda::get_global_context();
517 }
518
519 let kmeans_config = ComputeKmeansConfig {
521 kmeans_niters: config.kmeans_niters,
522 max_points_per_centroid: config.max_points_per_centroid,
523 seed: config.seed.unwrap_or(42),
524 n_samples_kmeans: config.n_samples_kmeans,
525 num_partitions: None, force_cpu: config.force_cpu,
527 };
528
529 let centroids = compute_kmeans(embeddings, &kmeans_config)?;
531
532 let metadata = create_index_files(embeddings, centroids, index_path, config)?;
534
535 if embeddings.len() <= config.start_from_scratch {
537 let index_dir = std::path::Path::new(index_path);
538 crate::update::save_embeddings_npy(index_dir, embeddings)?;
539 }
540
541 Ok(metadata)
542}
543pub struct MmapIndex {
567 pub path: String,
569 pub metadata: Metadata,
571 pub codec: ResidualCodec,
573 pub ivf: Array1<i64>,
575 pub ivf_lengths: Array1<i32>,
577 pub ivf_offsets: Array1<i64>,
579 pub doc_lengths: Array1<i64>,
581 pub doc_offsets: Array1<usize>,
583 pub mmap_codes: crate::mmap::MmapNpyArray1I64,
585 pub mmap_residuals: crate::mmap::MmapNpyArray2U8,
587}
588
589impl MmapIndex {
590 pub fn load(index_path: &str) -> Result<Self> {
598 use ndarray_npy::ReadNpyExt;
599
600 let index_dir = Path::new(index_path);
601
602 let mut metadata = Metadata::load_from_path(index_dir)?;
604
605 if !metadata.next_plaid_compatible {
607 eprintln!("Checking index format compatibility...");
608 let converted = crate::mmap::convert_fastplaid_to_nextplaid(index_dir)?;
609 if converted {
610 eprintln!("Index converted to next-plaid compatible format.");
611 let merged_codes = index_dir.join("merged_codes.npy");
613 let merged_residuals = index_dir.join("merged_residuals.npy");
614 let codes_manifest = index_dir.join("merged_codes.manifest.json");
615 let residuals_manifest = index_dir.join("merged_residuals.manifest.json");
616 for path in [
617 &merged_codes,
618 &merged_residuals,
619 &codes_manifest,
620 &residuals_manifest,
621 ] {
622 if path.exists() {
623 let _ = fs::remove_file(path);
624 }
625 }
626 }
627
628 metadata.next_plaid_compatible = true;
630 let metadata_path = index_dir.join("metadata.json");
631 let file = File::create(&metadata_path)
632 .map_err(|e| Error::IndexLoad(format!("Failed to update metadata: {}", e)))?;
633 serde_json::to_writer_pretty(BufWriter::new(file), &metadata)?;
634 eprintln!("Metadata updated with next_plaid_compatible: true");
635 }
636
637 let codec = ResidualCodec::load_mmap_from_dir(index_dir)?;
640
641 let ivf_path = index_dir.join("ivf.npy");
643 let ivf: Array1<i64> = Array1::read_npy(
644 File::open(&ivf_path)
645 .map_err(|e| Error::IndexLoad(format!("Failed to open ivf.npy: {}", e)))?,
646 )
647 .map_err(|e| Error::IndexLoad(format!("Failed to read ivf.npy: {}", e)))?;
648
649 let ivf_lengths_path = index_dir.join("ivf_lengths.npy");
650 let ivf_lengths: Array1<i32> = Array1::read_npy(
651 File::open(&ivf_lengths_path)
652 .map_err(|e| Error::IndexLoad(format!("Failed to open ivf_lengths.npy: {}", e)))?,
653 )
654 .map_err(|e| Error::IndexLoad(format!("Failed to read ivf_lengths.npy: {}", e)))?;
655
656 let num_centroids = ivf_lengths.len();
658 let mut ivf_offsets = Array1::<i64>::zeros(num_centroids + 1);
659 for i in 0..num_centroids {
660 ivf_offsets[i + 1] = ivf_offsets[i] + ivf_lengths[i] as i64;
661 }
662
663 let mut doc_lengths_vec: Vec<i64> = Vec::with_capacity(metadata.num_documents);
665 for chunk_idx in 0..metadata.num_chunks {
666 let doclens_path = index_dir.join(format!("doclens.{}.json", chunk_idx));
667 let chunk_doclens: Vec<i64> =
668 serde_json::from_reader(BufReader::new(File::open(&doclens_path)?))?;
669 doc_lengths_vec.extend(chunk_doclens);
670 }
671 let doc_lengths = Array1::from_vec(doc_lengths_vec);
672
673 let mut doc_offsets = Array1::<usize>::zeros(doc_lengths.len() + 1);
675 for i in 0..doc_lengths.len() {
676 doc_offsets[i + 1] = doc_offsets[i] + doc_lengths[i] as usize;
677 }
678
679 let max_len = doc_lengths.iter().cloned().max().unwrap_or(0) as usize;
681 let last_len = *doc_lengths.last().unwrap_or(&0) as usize;
682 let padding_needed = max_len.saturating_sub(last_len);
683
684 let merged_codes_path =
686 crate::mmap::merge_codes_chunks(index_dir, metadata.num_chunks, padding_needed)?;
687 let merged_residuals_path =
688 crate::mmap::merge_residuals_chunks(index_dir, metadata.num_chunks, padding_needed)?;
689
690 let mmap_codes = crate::mmap::MmapNpyArray1I64::from_npy_file(&merged_codes_path)?;
692 let mmap_residuals = crate::mmap::MmapNpyArray2U8::from_npy_file(&merged_residuals_path)?;
693
694 Ok(Self {
695 path: index_path.to_string(),
696 metadata,
697 codec,
698 ivf,
699 ivf_lengths,
700 ivf_offsets,
701 doc_lengths,
702 doc_offsets,
703 mmap_codes,
704 mmap_residuals,
705 })
706 }
707
708 pub fn get_candidates(&self, centroid_indices: &[usize]) -> Vec<i64> {
710 let mut candidates: Vec<i64> = Vec::new();
711
712 for &idx in centroid_indices {
713 if idx < self.ivf_lengths.len() {
714 let start = self.ivf_offsets[idx] as usize;
715 let len = self.ivf_lengths[idx] as usize;
716 candidates.extend(self.ivf.slice(s![start..start + len]).iter());
717 }
718 }
719
720 candidates.sort_unstable();
721 candidates.dedup();
722 candidates
723 }
724
725 pub fn get_document_embeddings(&self, doc_id: usize) -> Result<Array2<f32>> {
727 if doc_id >= self.doc_lengths.len() {
728 return Err(Error::Search(format!("Invalid document ID: {}", doc_id)));
729 }
730
731 let start = self.doc_offsets[doc_id];
732 let end = self.doc_offsets[doc_id + 1];
733
734 let codes_slice = self.mmap_codes.slice(start, end);
736 let residuals_view = self.mmap_residuals.slice_rows(start, end);
737
738 let codes: Array1<usize> = Array1::from_iter(codes_slice.iter().map(|&c| c as usize));
740
741 let residuals = residuals_view.to_owned();
743
744 self.codec.decompress(&residuals, &codes.view())
746 }
747
748 pub fn get_document_codes(&self, doc_ids: &[usize]) -> Vec<Vec<i64>> {
750 doc_ids
751 .iter()
752 .map(|&doc_id| {
753 if doc_id >= self.doc_lengths.len() {
754 return vec![];
755 }
756 let start = self.doc_offsets[doc_id];
757 let end = self.doc_offsets[doc_id + 1];
758 self.mmap_codes.slice(start, end).to_vec()
759 })
760 .collect()
761 }
762
763 pub fn decompress_documents(&self, doc_ids: &[usize]) -> Result<(Array2<f32>, Vec<usize>)> {
765 let mut total_tokens = 0usize;
767 let mut lengths = Vec::with_capacity(doc_ids.len());
768 for &doc_id in doc_ids {
769 if doc_id >= self.doc_lengths.len() {
770 lengths.push(0);
771 } else {
772 let len = self.doc_offsets[doc_id + 1] - self.doc_offsets[doc_id];
773 lengths.push(len);
774 total_tokens += len;
775 }
776 }
777
778 if total_tokens == 0 {
779 return Ok((Array2::zeros((0, self.codec.embedding_dim())), lengths));
780 }
781
782 let packed_dim = self.mmap_residuals.ncols();
784 let mut all_codes = Vec::with_capacity(total_tokens);
785 let mut all_residuals = Array2::<u8>::zeros((total_tokens, packed_dim));
786 let mut offset = 0;
787
788 for &doc_id in doc_ids {
789 if doc_id >= self.doc_lengths.len() {
790 continue;
791 }
792 let start = self.doc_offsets[doc_id];
793 let end = self.doc_offsets[doc_id + 1];
794 let len = end - start;
795
796 let codes_slice = self.mmap_codes.slice(start, end);
798 all_codes.extend(codes_slice.iter().map(|&c| c as usize));
799
800 let residuals_view = self.mmap_residuals.slice_rows(start, end);
802 all_residuals
803 .slice_mut(s![offset..offset + len, ..])
804 .assign(&residuals_view);
805 offset += len;
806 }
807
808 let codes_arr = Array1::from_vec(all_codes);
809 let embeddings = self.codec.decompress(&all_residuals, &codes_arr.view())?;
810
811 Ok((embeddings, lengths))
812 }
813
814 pub fn search(
826 &self,
827 query: &Array2<f32>,
828 params: &crate::search::SearchParameters,
829 subset: Option<&[i64]>,
830 ) -> Result<crate::search::SearchResult> {
831 crate::search::search_one_mmap(self, query, params, subset)
832 }
833
834 pub fn search_batch(
847 &self,
848 queries: &[Array2<f32>],
849 params: &crate::search::SearchParameters,
850 parallel: bool,
851 subset: Option<&[i64]>,
852 ) -> Result<Vec<crate::search::SearchResult>> {
853 crate::search::search_many_mmap(self, queries, params, parallel, subset)
854 }
855
856 pub fn num_documents(&self) -> usize {
858 self.doc_lengths.len()
859 }
860
861 pub fn num_embeddings(&self) -> usize {
863 self.metadata.num_embeddings
864 }
865
866 pub fn num_partitions(&self) -> usize {
868 self.metadata.num_partitions
869 }
870
871 pub fn avg_doclen(&self) -> f64 {
873 self.metadata.avg_doclen
874 }
875
876 pub fn embedding_dim(&self) -> usize {
878 self.codec.embedding_dim()
879 }
880
881 pub fn reconstruct(&self, doc_ids: &[i64]) -> Result<Vec<Array2<f32>>> {
907 crate::embeddings::reconstruct_embeddings(self, doc_ids)
908 }
909
910 pub fn reconstruct_single(&self, doc_id: i64) -> Result<Array2<f32>> {
922 crate::embeddings::reconstruct_single(self, doc_id)
923 }
924
925 pub fn create_with_kmeans(
945 embeddings: &[Array2<f32>],
946 index_path: &str,
947 config: &IndexConfig,
948 ) -> Result<Self> {
949 create_index_with_kmeans_files(embeddings, index_path, config)?;
951
952 Self::load(index_path)
954 }
955
956 pub fn update(
984 &mut self,
985 embeddings: &[Array2<f32>],
986 config: &crate::update::UpdateConfig,
987 ) -> Result<Vec<i64>> {
988 use crate::codec::ResidualCodec;
989 use crate::update::{
990 clear_buffer, clear_embeddings_npy, embeddings_npy_exists, load_buffer,
991 load_buffer_info, load_cluster_threshold, load_embeddings_npy, save_buffer,
992 update_centroids, update_index,
993 };
994
995 let path_str = self.path.clone();
996 let index_path = std::path::Path::new(&path_str);
997 let num_new_docs = embeddings.len();
998
999 if self.metadata.num_documents <= config.start_from_scratch {
1003 let existing_embeddings = load_embeddings_npy(index_path)?;
1005
1006 if existing_embeddings.len() == self.metadata.num_documents {
1011 let start_doc_id = existing_embeddings.len() as i64;
1013
1014 let combined_embeddings: Vec<Array2<f32>> = existing_embeddings
1016 .into_iter()
1017 .chain(embeddings.iter().cloned())
1018 .collect();
1019
1020 let index_config = IndexConfig {
1022 nbits: self.metadata.nbits,
1023 batch_size: config.batch_size,
1024 seed: Some(config.seed),
1025 kmeans_niters: config.kmeans_niters,
1026 max_points_per_centroid: config.max_points_per_centroid,
1027 n_samples_kmeans: config.n_samples_kmeans,
1028 start_from_scratch: config.start_from_scratch,
1029 force_cpu: config.force_cpu,
1030 };
1031
1032 *self = Self::create_with_kmeans(&combined_embeddings, &path_str, &index_config)?;
1034
1035 if combined_embeddings.len() > config.start_from_scratch
1037 && embeddings_npy_exists(index_path)
1038 {
1039 clear_embeddings_npy(index_path)?;
1040 }
1041
1042 return Ok((start_doc_id..start_doc_id + num_new_docs as i64).collect());
1044 }
1045 }
1047
1048 let buffer = load_buffer(index_path)?;
1050 let buffer_len = buffer.len();
1051 let total_new = embeddings.len() + buffer_len;
1052
1053 let start_doc_id: i64;
1055
1056 let mut codec = ResidualCodec::load_from_dir(index_path)?;
1058
1059 if total_new >= config.buffer_size {
1061 let num_buffered = load_buffer_info(index_path)?;
1065
1066 if num_buffered > 0 && self.metadata.num_documents >= num_buffered {
1068 let start_del_idx = self.metadata.num_documents - num_buffered;
1069 let docs_to_delete: Vec<i64> = (start_del_idx..self.metadata.num_documents)
1070 .map(|i| i as i64)
1071 .collect();
1072 crate::delete::delete_from_index_keep_buffer(&docs_to_delete, &path_str)?;
1073 self.metadata = Metadata::load_from_path(index_path)?;
1075 }
1076
1077 start_doc_id = (self.metadata.num_documents + buffer_len) as i64;
1079
1080 let combined: Vec<Array2<f32>> = buffer
1082 .into_iter()
1083 .chain(embeddings.iter().cloned())
1084 .collect();
1085
1086 if let Ok(cluster_threshold) = load_cluster_threshold(index_path) {
1088 let new_centroids =
1089 update_centroids(index_path, &combined, cluster_threshold, config)?;
1090 if new_centroids > 0 {
1091 codec = ResidualCodec::load_from_dir(index_path)?;
1093 }
1094 }
1095
1096 clear_buffer(index_path)?;
1098
1099 update_index(
1101 &combined,
1102 &path_str,
1103 &codec,
1104 Some(config.batch_size),
1105 true,
1106 config.force_cpu,
1107 )?;
1108 } else {
1109 start_doc_id = self.metadata.num_documents as i64;
1112
1113 let combined_buffer: Vec<Array2<f32>> = buffer
1115 .into_iter()
1116 .chain(embeddings.iter().cloned())
1117 .collect();
1118 save_buffer(index_path, &combined_buffer)?;
1119
1120 update_index(
1122 embeddings,
1123 &path_str,
1124 &codec,
1125 Some(config.batch_size),
1126 false,
1127 config.force_cpu,
1128 )?;
1129 }
1130
1131 *self = Self::load(&path_str)?;
1133
1134 Ok((start_doc_id..start_doc_id + num_new_docs as i64).collect())
1136 }
1137
1138 pub fn update_with_metadata(
1150 &mut self,
1151 embeddings: &[Array2<f32>],
1152 config: &crate::update::UpdateConfig,
1153 metadata: Option<&[serde_json::Value]>,
1154 ) -> Result<Vec<i64>> {
1155 if let Some(meta) = metadata {
1157 if meta.len() != embeddings.len() {
1158 return Err(Error::Config(format!(
1159 "Metadata length ({}) must match embeddings length ({})",
1160 meta.len(),
1161 embeddings.len()
1162 )));
1163 }
1164 }
1165
1166 let doc_ids = self.update(embeddings, config)?;
1168
1169 if let Some(meta) = metadata {
1171 crate::filtering::update(&self.path, meta, &doc_ids)?;
1172 }
1173
1174 Ok(doc_ids)
1175 }
1176
1177 pub fn update_or_create(
1190 embeddings: &[Array2<f32>],
1191 index_path: &str,
1192 index_config: &IndexConfig,
1193 update_config: &crate::update::UpdateConfig,
1194 ) -> Result<(Self, Vec<i64>)> {
1195 let index_dir = std::path::Path::new(index_path);
1196 let metadata_path = index_dir.join("metadata.json");
1197
1198 if metadata_path.exists() {
1199 let mut index = Self::load(index_path)?;
1201 let doc_ids = index.update(embeddings, update_config)?;
1202 Ok((index, doc_ids))
1203 } else {
1204 let num_docs = embeddings.len();
1206 let index = Self::create_with_kmeans(embeddings, index_path, index_config)?;
1207 let doc_ids: Vec<i64> = (0..num_docs as i64).collect();
1208 Ok((index, doc_ids))
1209 }
1210 }
1211
1212 pub fn reload(&mut self) -> Result<()> {
1217 *self = Self::load(&self.path)?;
1218 Ok(())
1219 }
1220
1221 pub fn delete(&mut self, doc_ids: &[i64]) -> Result<usize> {
1234 self.delete_with_options(doc_ids, true)
1235 }
1236
1237 pub fn delete_with_options(&mut self, doc_ids: &[i64], delete_metadata: bool) -> Result<usize> {
1251 let path = self.path.clone();
1252
1253 let deleted = crate::delete::delete_from_index(doc_ids, &path)?;
1255
1256 if delete_metadata && deleted > 0 {
1258 let index_path = std::path::Path::new(&path);
1259 let db_path = index_path.join("metadata.db");
1260 if db_path.exists() {
1261 crate::filtering::delete(&path, doc_ids)?;
1262 }
1263 }
1264
1265 Ok(deleted)
1266 }
1267}
1268
1269#[cfg(test)]
1270mod tests {
1271 use super::*;
1272
1273 #[test]
1274 fn test_index_config_default() {
1275 let config = IndexConfig::default();
1276 assert_eq!(config.nbits, 4);
1277 assert_eq!(config.batch_size, 50_000);
1278 assert_eq!(config.seed, Some(42));
1279 }
1280
1281 #[test]
1282 fn test_update_or_create_new_index() {
1283 use ndarray::Array2;
1284 use tempfile::tempdir;
1285
1286 let temp_dir = tempdir().unwrap();
1287 let index_path = temp_dir.path().to_str().unwrap();
1288
1289 let mut embeddings: Vec<Array2<f32>> = Vec::new();
1291 for i in 0..5 {
1292 let mut doc = Array2::<f32>::zeros((5, 32));
1293 for j in 0..5 {
1294 for k in 0..32 {
1295 doc[[j, k]] = (i as f32 * 0.1) + (j as f32 * 0.01) + (k as f32 * 0.001);
1296 }
1297 }
1298 for mut row in doc.rows_mut() {
1300 let norm: f32 = row.iter().map(|x| x * x).sum::<f32>().sqrt();
1301 if norm > 0.0 {
1302 row.iter_mut().for_each(|x| *x /= norm);
1303 }
1304 }
1305 embeddings.push(doc);
1306 }
1307
1308 let index_config = IndexConfig {
1309 nbits: 2,
1310 batch_size: 50,
1311 seed: Some(42),
1312 kmeans_niters: 2,
1313 ..Default::default()
1314 };
1315 let update_config = crate::update::UpdateConfig::default();
1316
1317 let (index, doc_ids) =
1319 MmapIndex::update_or_create(&embeddings, index_path, &index_config, &update_config)
1320 .expect("Failed to create index");
1321
1322 assert_eq!(index.metadata.num_documents, 5);
1323 assert_eq!(doc_ids, vec![0, 1, 2, 3, 4]);
1324
1325 assert!(temp_dir.path().join("metadata.json").exists());
1327 assert!(temp_dir.path().join("centroids.npy").exists());
1328 }
1329
1330 #[test]
1331 fn test_update_or_create_existing_index() {
1332 use ndarray::Array2;
1333 use tempfile::tempdir;
1334
1335 let temp_dir = tempdir().unwrap();
1336 let index_path = temp_dir.path().to_str().unwrap();
1337
1338 let create_embeddings = |count: usize, offset: usize| -> Vec<Array2<f32>> {
1340 let mut embeddings = Vec::new();
1341 for i in 0..count {
1342 let mut doc = Array2::<f32>::zeros((5, 32));
1343 for j in 0..5 {
1344 for k in 0..32 {
1345 doc[[j, k]] =
1346 ((i + offset) as f32 * 0.1) + (j as f32 * 0.01) + (k as f32 * 0.001);
1347 }
1348 }
1349 for mut row in doc.rows_mut() {
1350 let norm: f32 = row.iter().map(|x| x * x).sum::<f32>().sqrt();
1351 if norm > 0.0 {
1352 row.iter_mut().for_each(|x| *x /= norm);
1353 }
1354 }
1355 embeddings.push(doc);
1356 }
1357 embeddings
1358 };
1359
1360 let index_config = IndexConfig {
1361 nbits: 2,
1362 batch_size: 50,
1363 seed: Some(42),
1364 kmeans_niters: 2,
1365 ..Default::default()
1366 };
1367 let update_config = crate::update::UpdateConfig::default();
1368
1369 let embeddings1 = create_embeddings(5, 0);
1371 let (index1, doc_ids1) =
1372 MmapIndex::update_or_create(&embeddings1, index_path, &index_config, &update_config)
1373 .expect("Failed to create index");
1374 assert_eq!(index1.metadata.num_documents, 5);
1375 assert_eq!(doc_ids1, vec![0, 1, 2, 3, 4]);
1376
1377 let embeddings2 = create_embeddings(3, 5);
1379 let (index2, doc_ids2) =
1380 MmapIndex::update_or_create(&embeddings2, index_path, &index_config, &update_config)
1381 .expect("Failed to update index");
1382 assert_eq!(index2.metadata.num_documents, 8);
1383 assert_eq!(doc_ids2, vec![5, 6, 7]);
1384 }
1385}