Skip to main content

reddb_server/storage/engine/
ivf.rs

1//! IVF (Inverted File Index) for Vector Search
2//!
3//! Clustering-based approximate nearest neighbor search.
4//! Partitions vectors into clusters (Voronoi cells) and only searches
5//! the most relevant clusters at query time.
6//!
7//! # Design
8//!
9//! - k-means clustering to build centroids
10//! - Each vector assigned to its nearest centroid
11//! - At query time, probe only `nprobe` nearest clusters
12//! - Trade-off: more probes = better recall, slower search
13//!
14//! # Example
15//!
16//! ```ignore
17//! let mut ivf = IvfIndex::new(IvfConfig {
18//!     n_lists: 100,      // Number of clusters
19//!     n_probes: 10,      // Clusters to search
20//!     dimension: 384,
21//! });
22//!
23//! // Train on sample vectors
24//! ivf.train(&training_vectors);
25//!
26//! // Add vectors
27//! ivf.add_batch(&vectors);
28//!
29//! // Search
30//! let results = ivf.search(&query, 10);
31//! ```
32
33use std::collections::HashMap;
34
35use super::distance::{cmp_f32, l2_squared_simd, DistanceResult};
36use super::hnsw::NodeId;
37
38/// IVF configuration
39#[derive(Clone, Debug)]
40pub struct IvfConfig {
41    /// Number of clusters (Voronoi cells)
42    pub n_lists: usize,
43    /// Number of clusters to probe at query time
44    pub n_probes: usize,
45    /// Vector dimension
46    pub dimension: usize,
47    /// Maximum k-means iterations during training
48    pub max_iterations: usize,
49    /// Convergence threshold for k-means
50    pub convergence_threshold: f32,
51}
52
53impl Default for IvfConfig {
54    fn default() -> Self {
55        Self {
56            n_lists: 100,
57            n_probes: 10,
58            dimension: 128,
59            max_iterations: 50,
60            convergence_threshold: 1e-4,
61        }
62    }
63}
64
65impl IvfConfig {
66    pub fn new(dimension: usize, n_lists: usize) -> Self {
67        Self {
68            n_lists,
69            n_probes: (n_lists / 10).max(1),
70            dimension,
71            ..Default::default()
72        }
73    }
74
75    pub fn with_probes(mut self, n_probes: usize) -> Self {
76        self.n_probes = n_probes;
77        self
78    }
79}
80
81/// A cluster containing vectors
82#[derive(Clone)]
83struct IvfList {
84    /// Centroid of this cluster
85    centroid: Vec<f32>,
86    /// Vector IDs in this cluster
87    ids: Vec<NodeId>,
88    /// Vectors in this cluster (stored for search)
89    vectors: Vec<Vec<f32>>,
90}
91
92impl IvfList {
93    fn new(centroid: Vec<f32>) -> Self {
94        Self {
95            centroid,
96            ids: Vec::new(),
97            vectors: Vec::new(),
98        }
99    }
100
101    fn add(&mut self, id: NodeId, vector: Vec<f32>) {
102        self.ids.push(id);
103        self.vectors.push(vector);
104    }
105
106    fn len(&self) -> usize {
107        self.ids.len()
108    }
109
110    fn is_empty(&self) -> bool {
111        self.ids.is_empty()
112    }
113}
114
115/// IVF Index for approximate nearest neighbor search
116pub struct IvfIndex {
117    config: IvfConfig,
118    /// Cluster lists
119    lists: Vec<IvfList>,
120    /// Mapping from vector ID to list index
121    id_to_list: HashMap<NodeId, usize>,
122    /// Whether the index has been trained
123    trained: bool,
124    /// Total vector count
125    count: usize,
126    /// Next auto-generated ID
127    next_id: NodeId,
128}
129
130impl IvfIndex {
131    /// Create a new IVF index (untrained)
132    pub fn new(config: IvfConfig) -> Self {
133        Self {
134            config,
135            lists: Vec::new(),
136            id_to_list: HashMap::new(),
137            trained: false,
138            count: 0,
139            next_id: 0,
140        }
141    }
142
143    /// Create with default config for given dimension
144    pub fn with_dimension(dimension: usize) -> Self {
145        Self::new(IvfConfig::new(dimension, 100))
146    }
147
148    /// Train the index using k-means clustering
149    pub fn train(&mut self, vectors: &[Vec<f32>]) {
150        if vectors.is_empty() {
151            return;
152        }
153
154        let n_lists = self.config.n_lists.min(vectors.len());
155
156        // Initialize centroids using k-means++
157        let centroids = self.kmeans_plusplus_init(vectors, n_lists);
158
159        // Run k-means
160        let final_centroids = self.kmeans(vectors, centroids);
161
162        // Create lists
163        self.lists = final_centroids.into_iter().map(IvfList::new).collect();
164
165        self.trained = true;
166    }
167
168    /// K-means++ initialization for better centroid starting points
169    fn kmeans_plusplus_init(&self, vectors: &[Vec<f32>], k: usize) -> Vec<Vec<f32>> {
170        let mut centroids = Vec::with_capacity(k);
171
172        if vectors.is_empty() || k == 0 {
173            return centroids;
174        }
175
176        // First centroid: random (use middle for determinism)
177        centroids.push(vectors[vectors.len() / 2].clone());
178
179        // Subsequent centroids: weighted by distance to nearest existing centroid
180        for _ in 1..k {
181            let mut distances: Vec<f32> = vectors
182                .iter()
183                .map(|v| {
184                    centroids
185                        .iter()
186                        .map(|c| l2_squared_simd(v, c))
187                        .fold(f32::MAX, f32::min)
188                })
189                .collect();
190
191            // Normalize to probabilities
192            let total: f32 = distances.iter().sum();
193            if total > 0.0 {
194                for d in &mut distances {
195                    *d /= total;
196                }
197            }
198
199            // Select based on cumulative probability (deterministic: use max distance)
200            let max_idx = distances
201                .iter()
202                .enumerate()
203                .max_by(|(la, a), (lb, b)| cmp_f32(**a, **b).then_with(|| la.cmp(lb)))
204                .map(|(i, _)| i)
205                .unwrap_or(0);
206
207            centroids.push(vectors[max_idx].clone());
208        }
209
210        centroids
211    }
212
213    /// Run k-means clustering
214    fn kmeans(&self, vectors: &[Vec<f32>], mut centroids: Vec<Vec<f32>>) -> Vec<Vec<f32>> {
215        let dim = self.config.dimension;
216        let k = centroids.len();
217
218        for _ in 0..self.config.max_iterations {
219            // Assign vectors to nearest centroid
220            let mut assignments: Vec<Vec<usize>> = vec![Vec::new(); k];
221            for (i, vector) in vectors.iter().enumerate() {
222                let nearest = self.find_nearest_centroid(vector, &centroids);
223                assignments[nearest].push(i);
224            }
225
226            // Compute new centroids
227            let mut new_centroids = Vec::with_capacity(k);
228            let mut max_shift: f32 = 0.0;
229
230            for (cluster_idx, indices) in assignments.iter().enumerate() {
231                if indices.is_empty() {
232                    // Keep old centroid if cluster is empty
233                    new_centroids.push(centroids[cluster_idx].clone());
234                    continue;
235                }
236
237                // Average of all vectors in cluster
238                let mut new_centroid = vec![0.0f32; dim];
239                for &idx in indices {
240                    for (j, val) in vectors[idx].iter().enumerate() {
241                        if j < dim {
242                            new_centroid[j] += val;
243                        }
244                    }
245                }
246                for val in &mut new_centroid {
247                    *val /= indices.len() as f32;
248                }
249
250                // Track centroid shift
251                let shift = l2_squared_simd(&new_centroid, &centroids[cluster_idx]).sqrt();
252                max_shift = max_shift.max(shift);
253
254                new_centroids.push(new_centroid);
255            }
256
257            centroids = new_centroids;
258
259            // Check convergence
260            if max_shift < self.config.convergence_threshold {
261                break;
262            }
263        }
264
265        centroids
266    }
267
268    /// Find nearest centroid index
269    fn find_nearest_centroid(&self, vector: &[f32], centroids: &[Vec<f32>]) -> usize {
270        centroids
271            .iter()
272            .enumerate()
273            .map(|(i, c)| (i, l2_squared_simd(vector, c)))
274            .min_by(|(li, la), (ri, rb)| cmp_f32(*la, *rb).then_with(|| li.cmp(ri)))
275            .map(|(i, _)| i)
276            .unwrap_or(0)
277    }
278
279    /// Find k nearest centroids
280    fn find_nearest_centroids(&self, vector: &[f32], k: usize) -> Vec<usize> {
281        let mut distances: Vec<(usize, f32)> = self
282            .lists
283            .iter()
284            .enumerate()
285            .map(|(i, list)| (i, l2_squared_simd(vector, &list.centroid)))
286            .collect();
287
288        distances.sort_by(|(li, la), (ri, lb)| cmp_f32(*la, *lb).then_with(|| li.cmp(ri)));
289        distances.into_iter().take(k).map(|(i, _)| i).collect()
290    }
291
292    /// Add a single vector
293    pub fn add(&mut self, vector: Vec<f32>) -> NodeId {
294        let id = self.next_id;
295        self.next_id += 1;
296        self.add_with_id(id, vector);
297        id
298    }
299
300    /// Add a vector with specific ID
301    pub fn add_with_id(&mut self, id: NodeId, vector: Vec<f32>) {
302        if !self.trained || self.lists.is_empty() {
303            // Auto-train with a single cluster if not trained
304            if self.lists.is_empty() {
305                self.lists.push(IvfList::new(vector.clone()));
306                self.trained = true;
307            }
308        }
309
310        let list_idx = self.find_nearest_centroid(
311            &vector,
312            &self
313                .lists
314                .iter()
315                .map(|l| l.centroid.clone())
316                .collect::<Vec<_>>(),
317        );
318
319        self.lists[list_idx].add(id, vector);
320        self.id_to_list.insert(id, list_idx);
321        self.count += 1;
322    }
323
324    /// Add multiple vectors
325    pub fn add_batch(&mut self, vectors: Vec<Vec<f32>>) -> Vec<NodeId> {
326        vectors.into_iter().map(|v| self.add(v)).collect()
327    }
328
329    /// Add multiple vectors with IDs
330    pub fn add_batch_with_ids(&mut self, items: Vec<(NodeId, Vec<f32>)>) {
331        for (id, vector) in items {
332            self.add_with_id(id, vector);
333        }
334    }
335
336    /// Remove a vector by ID
337    pub fn remove(&mut self, id: NodeId) -> bool {
338        if let Some(list_idx) = self.id_to_list.remove(&id) {
339            let list = &mut self.lists[list_idx];
340            if let Some(pos) = list.ids.iter().position(|&x| x == id) {
341                // IVF lists are unordered bags; swap_remove the same pos in both
342                // parallel vectors keeps ids/vectors aligned in O(1).
343                list.ids.swap_remove(pos);
344                list.vectors.swap_remove(pos);
345                self.count = self.count.saturating_sub(1);
346                return true;
347            }
348        }
349        false
350    }
351
352    /// Search for k nearest neighbors
353    pub fn search(&self, query: &[f32], k: usize) -> Vec<DistanceResult> {
354        self.search_with_probes(query, k, self.config.n_probes)
355    }
356
357    /// Search with custom number of probes
358    pub fn search_with_probes(
359        &self,
360        query: &[f32],
361        k: usize,
362        n_probes: usize,
363    ) -> Vec<DistanceResult> {
364        if self.lists.is_empty() {
365            return Vec::new();
366        }
367
368        let probes = self.find_nearest_centroids(query, n_probes);
369
370        // Collect candidates from probed clusters
371        let mut candidates: Vec<DistanceResult> = Vec::new();
372        for list_idx in probes {
373            let list = &self.lists[list_idx];
374            for (i, vector) in list.vectors.iter().enumerate() {
375                let distance = l2_squared_simd(query, vector).sqrt();
376                candidates.push(DistanceResult::new(list.ids[i], distance));
377            }
378        }
379
380        // Sort and return top k
381        candidates.sort_by(|a, b| cmp_f32(a.distance, b.distance).then_with(|| a.id.cmp(&b.id)));
382        candidates.truncate(k);
383        candidates
384    }
385
386    /// Get a vector by ID
387    pub fn get(&self, id: NodeId) -> Option<&[f32]> {
388        if let Some(&list_idx) = self.id_to_list.get(&id) {
389            let list = &self.lists[list_idx];
390            if let Some(pos) = list.ids.iter().position(|&x| x == id) {
391                return Some(&list.vectors[pos]);
392            }
393        }
394        None
395    }
396
397    /// Check if index contains an ID
398    pub fn contains(&self, id: NodeId) -> bool {
399        self.id_to_list.contains_key(&id)
400    }
401
402    /// Get total vector count
403    pub fn len(&self) -> usize {
404        self.count
405    }
406
407    /// Check if empty
408    pub fn is_empty(&self) -> bool {
409        self.count == 0
410    }
411
412    /// Get number of clusters
413    pub fn n_lists(&self) -> usize {
414        self.lists.len()
415    }
416
417    /// Get cluster statistics
418    pub fn stats(&self) -> IvfStats {
419        let sizes: Vec<usize> = self.lists.iter().map(|l| l.len()).collect();
420        let non_empty = sizes.iter().filter(|&&s| s > 0).count();
421
422        let avg = if non_empty > 0 {
423            sizes.iter().sum::<usize>() as f64 / non_empty as f64
424        } else {
425            0.0
426        };
427
428        let max = sizes.iter().copied().max().unwrap_or(0);
429        let min = sizes.iter().filter(|&&s| s > 0).copied().min().unwrap_or(0);
430
431        IvfStats {
432            total_vectors: self.count,
433            n_lists: self.lists.len(),
434            non_empty_lists: non_empty,
435            avg_list_size: avg,
436            max_list_size: max,
437            min_list_size: min,
438            dimension: self.config.dimension,
439            trained: self.trained,
440        }
441    }
442
443    /// Serialize the index to bytes for storage.
444    ///
445    /// The `IVF1` payload byte layout is owned by `reddb-file` (ADR 0046); this
446    /// only projects the engine state into [`reddb_file::IvfIndexFrame`].
447    pub fn to_bytes(&self) -> Vec<u8> {
448        let lists = self
449            .lists
450            .iter()
451            .map(|list| reddb_file::IvfListFrame {
452                centroid: list.centroid.clone(),
453                ids: list.ids.clone(),
454                vectors: list.vectors.clone(),
455            })
456            .collect();
457        let frame = reddb_file::IvfIndexFrame {
458            n_lists: self.config.n_lists as u32,
459            n_probes: self.config.n_probes as u32,
460            dimension: self.config.dimension as u32,
461            max_iterations: self.config.max_iterations as u32,
462            convergence_threshold: self.config.convergence_threshold,
463            trained: self.trained,
464            count: self.count as u64,
465            next_id: self.next_id,
466            lists,
467        };
468        reddb_file::encode_ivf_index_frame(&frame)
469    }
470
471    /// Deserialize an index from bytes via the `reddb-file` codec.
472    pub fn from_bytes(bytes: &[u8]) -> Result<Self, String> {
473        let frame = reddb_file::decode_ivf_index_frame(bytes).map_err(|e| e.to_string())?;
474
475        let config = IvfConfig {
476            n_lists: frame.n_lists as usize,
477            n_probes: frame.n_probes as usize,
478            dimension: frame.dimension as usize,
479            max_iterations: frame.max_iterations as usize,
480            convergence_threshold: frame.convergence_threshold,
481        };
482
483        let mut lists = Vec::with_capacity(frame.lists.len());
484        let mut id_to_list = HashMap::new();
485        for (list_idx, list) in frame.lists.into_iter().enumerate() {
486            for &id in &list.ids {
487                id_to_list.insert(id, list_idx);
488            }
489            lists.push(IvfList {
490                centroid: list.centroid,
491                ids: list.ids,
492                vectors: list.vectors,
493            });
494        }
495
496        Ok(Self {
497            config,
498            lists,
499            id_to_list,
500            trained: frame.trained,
501            count: frame.count as usize,
502            next_id: frame.next_id,
503        })
504    }
505}
506
507/// IVF index statistics
508#[derive(Debug, Clone)]
509pub struct IvfStats {
510    pub total_vectors: usize,
511    pub n_lists: usize,
512    pub non_empty_lists: usize,
513    pub avg_list_size: f64,
514    pub max_list_size: usize,
515    pub min_list_size: usize,
516    pub dimension: usize,
517    pub trained: bool,
518}
519
520// ============================================================================
521// Tests
522// ============================================================================
523
524#[cfg(test)]
525mod tests {
526    use super::*;
527
528    fn random_vector(dim: usize, seed: u64) -> Vec<f32> {
529        // Simple deterministic "random" for testing
530        (0..dim)
531            .map(|i| ((seed * 1103515245 + i as u64 * 12345) % 1000) as f32 / 1000.0)
532            .collect()
533    }
534
535    #[test]
536    fn test_ivf_basic() {
537        let mut ivf = IvfIndex::new(IvfConfig::new(8, 4));
538
539        // Generate training vectors
540        let training: Vec<Vec<f32>> = (0..100).map(|i| random_vector(8, i)).collect();
541
542        ivf.train(&training);
543        assert!(ivf.trained);
544        assert_eq!(ivf.n_lists(), 4);
545
546        // Add vectors
547        for (i, v) in training.iter().enumerate() {
548            ivf.add_with_id(i as u64, v.clone());
549        }
550
551        assert_eq!(ivf.len(), 100);
552    }
553
554    #[test]
555    fn test_ivf_search() {
556        let dim = 8;
557        let mut ivf = IvfIndex::new(IvfConfig {
558            n_lists: 4,
559            n_probes: 2,
560            dimension: dim,
561            ..Default::default()
562        });
563
564        // Create clustered data
565        let mut vectors = Vec::new();
566        for cluster in 0..4 {
567            let base = cluster as f32 * 10.0;
568            for i in 0..25 {
569                let mut v = vec![base; dim];
570                v[0] += i as f32 * 0.01;
571                vectors.push(v);
572            }
573        }
574
575        ivf.train(&vectors);
576
577        for (i, v) in vectors.iter().enumerate() {
578            ivf.add_with_id(i as u64, v.clone());
579        }
580
581        // Search for vector near cluster 0
582        let query = vec![0.05; dim];
583        let results = ivf.search(&query, 5);
584
585        assert!(!results.is_empty());
586        // Results should be from cluster 0 (IDs 0-24)
587        for r in &results {
588            assert!(r.id < 25);
589        }
590    }
591
592    #[test]
593    fn test_ivf_remove() {
594        let mut ivf = IvfIndex::new(IvfConfig::new(4, 2));
595
596        ivf.add_with_id(1, vec![1.0, 0.0, 0.0, 0.0]);
597        ivf.add_with_id(2, vec![0.0, 1.0, 0.0, 0.0]);
598        ivf.add_with_id(3, vec![0.0, 0.0, 1.0, 0.0]);
599
600        assert_eq!(ivf.len(), 3);
601        assert!(ivf.contains(2));
602
603        assert!(ivf.remove(2));
604        assert_eq!(ivf.len(), 2);
605        assert!(!ivf.contains(2));
606    }
607
608    #[test]
609    fn test_ivf_stats() {
610        let mut ivf = IvfIndex::new(IvfConfig::new(4, 3));
611
612        let training: Vec<Vec<f32>> = vec![
613            vec![0.0, 0.0, 0.0, 0.0],
614            vec![1.0, 0.0, 0.0, 0.0],
615            vec![2.0, 0.0, 0.0, 0.0],
616        ];
617
618        ivf.train(&training);
619
620        for (i, v) in training.iter().enumerate() {
621            ivf.add_with_id(i as u64, v.clone());
622        }
623
624        let stats = ivf.stats();
625        assert_eq!(stats.total_vectors, 3);
626        assert_eq!(stats.n_lists, 3);
627        assert!(stats.trained);
628    }
629}