diskann 0.51.0

DiskANN is a fast approximate nearest neighbor search library for high dimensional data
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
/*
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 */

/// A generalized trait for extracting search results.
///
/// Putting this behind a trait allows multiple different output containers to use common
/// interfaces. This, in turn, can allow search to return IDs and distances as separate
/// buffers (see [`IdDistance`]), or as a contiguous [`crate::neighbor::BackInserter`].
///
/// It also makes it easier to testing search post-processing routines as they should target
/// an output implementing `SearchOutputBuffer`, simplifying how they can be tested.
pub trait SearchOutputBuffer<I, D = f32> {
    /// Return a hint on the remaining size of the buffer.
    ///
    /// `None` may be returned in instances where the output has unknown or unbounded size.
    fn size_hint(&self) -> Option<usize>;

    /// Push an `id` and `distance` pair to the next position in the buffer.
    ///
    /// Returns a [`BufferState`] to indicate whether future insertions will succeed.
    ///
    /// Unlike the iterator interface, implementations should return [`BufferState::Full`]
    /// if **future** insertions will fail to prevent unnecessary work.
    fn push(&mut self, id: I, distance: D) -> BufferState;

    /// Return the number of items pushed into the buffer.
    fn current_len(&self) -> usize;

    /// Set from an iterator, returning the number of positions filled.
    ///
    /// The entire iterator may not be consumed if there is insufficient capacity in `self`.
    fn extend<Itr>(&mut self, itr: Itr) -> usize
    where
        Itr: IntoIterator<Item = (I, D)>;
}

/// Indicate whether future calls to [`SearchOutputBuffer::push`] will succeed or not.
#[derive(Debug, Clone, Copy, PartialEq)]
#[must_use = "This type indicates whether the output buffer is full or not."]
pub enum BufferState {
    /// There is capacity available in the buffer.
    Available,

    /// The buffer is full. Future calls to [`SearchOutputBuffer::push`] or
    /// [`SearchOutputBuffer::extend`] will fail.
    Full,
}

impl BufferState {
    /// Return `true` if `self == Self::Available`. Otherwise return `false`.
    pub fn is_available(self) -> bool {
        self == Self::Available
    }

    /// Return `true` if `self == Self::Full`. Otherwise return `false`.
    pub fn is_full(self) -> bool {
        self == Self::Full
    }
}

/// A [`SearchOutputBuffer`] that maintains two separate slices for IDs and distances.
///
/// # Internal Invariants
///
/// Both `ids` and `distances` must have the same length.
#[derive(Debug)]
pub struct IdDistance<'a, I> {
    ids: &'a mut [I],
    distances: &'a mut [f32],
    position: usize,
}

impl<'a, I> IdDistance<'a, I> {
    /// Construct a new [`IdDistance`] around the two slices.
    ///
    /// # Panics
    ///
    /// Panics if the two slices have different lengths.
    pub fn new(ids: &'a mut [I], distances: &'a mut [f32]) -> Self {
        assert_eq!(
            ids.len(),
            distances.len(),
            "ids and distances should have the same length"
        );
        Self {
            ids,
            distances,
            position: 0,
        }
    }

    /// The length of **both** internal slices.
    pub fn capacity(&self) -> usize {
        self.ids.len()
    }
}

impl<I> SearchOutputBuffer<I> for IdDistance<'_, I> {
    fn size_hint(&self) -> Option<usize> {
        Some(self.capacity() - self.position)
    }

    fn push(&mut self, id: I, distance: f32) -> BufferState {
        if self.position == self.capacity() {
            return BufferState::Full;
        }

        self.ids[self.position] = id;
        self.distances[self.position] = distance;
        self.position += 1;

        // Return `Full` if we added the last item.
        if self.position == self.capacity() {
            BufferState::Full
        } else {
            BufferState::Available
        }
    }

    fn current_len(&self) -> usize {
        self.position
    }

    fn extend<Itr>(&mut self, itr: Itr) -> usize
    where
        Itr: IntoIterator<Item = (I, f32)>,
    {
        let mut i = 0;
        let p = self.position;
        std::iter::zip(
            self.ids.iter_mut().skip(p),
            self.distances.iter_mut().skip(p),
        )
        .zip(itr)
        .for_each(|((i_out, d_out), (i_in, d_in))| {
            i += 1;
            *i_out = i_in;
            *d_out = d_in;
        });
        self.position += i;
        i
    }
}

#[derive(Debug)]
pub struct IdDistanceAssociatedData<'a, I, A> {
    ids: &'a mut [I],
    distances: &'a mut [f32],
    associated_data: &'a mut [A],
    position: usize,
}

impl<'a, I, A> IdDistanceAssociatedData<'a, I, A> {
    pub fn new(ids: &'a mut [I], distances: &'a mut [f32], associated_data: &'a mut [A]) -> Self {
        assert_eq!(
            ids.len(),
            distances.len(),
            "ids and distances should have the same length"
        );
        assert_eq!(
            ids.len(),
            associated_data.len(),
            "ids and associated_data should have the same length"
        );
        Self {
            ids,
            distances,
            associated_data,
            position: 0,
        }
    }

    pub fn capacity(&self) -> usize {
        self.ids.len()
    }
}

impl<I: Copy + Send, A: Clone + Send> SearchOutputBuffer<(I, A), f32>
    for IdDistanceAssociatedData<'_, I, A>
{
    fn size_hint(&self) -> Option<usize> {
        Some(self.capacity() - self.position)
    }

    fn push(&mut self, item: (I, A), distance: f32) -> BufferState {
        if self.position == self.capacity() {
            return BufferState::Full;
        }

        let (id, assoc) = item;
        self.ids[self.position] = id;
        self.distances[self.position] = distance;
        self.associated_data[self.position] = assoc;
        self.position += 1;

        // Return `Full` if we added the last item.
        if self.position == self.capacity() {
            BufferState::Full
        } else {
            BufferState::Available
        }
    }

    fn current_len(&self) -> usize {
        self.position
    }

    fn extend<Itr>(&mut self, itr: Itr) -> usize
    where
        Itr: IntoIterator<Item = ((I, A), f32)>,
    {
        let mut i = 0;
        let p = self.position;
        for (((id_out, dist_out), assoc_out), ((id, assoc), dist)) in self
            .ids
            .iter_mut()
            .skip(p)
            .zip(self.distances.iter_mut().skip(p))
            .zip(self.associated_data.iter_mut().skip(p))
            .zip(itr)
        {
            *id_out = id;
            *dist_out = dist;
            *assoc_out = assoc;
            i += 1;
        }
        self.position += i;
        i
    }
}

///////////
// Tests //
///////////

#[cfg(test)]
mod tests {
    use super::*;

    // Test that the constructor panics on unequal lengths.
    #[test]
    #[should_panic(expected = "ids and distances should have the same length")]
    fn test_new_panics() {
        let mut ids = vec![0u32; 10];
        let mut distances = vec![0.0f32; 9];
        IdDistance::new(&mut ids, &mut distances);
    }

    #[test]
    fn test_id_distance() {
        const MAX_LENGTH: usize = 5;

        // All `push`.
        {
            let mut ids = [0u32; MAX_LENGTH];
            let mut distances = [0.0f32; MAX_LENGTH];
            let mut buffer = IdDistance::new(&mut ids, &mut distances);

            assert_eq!(buffer.capacity(), MAX_LENGTH);
            assert_eq!(buffer.size_hint(), Some(MAX_LENGTH));
            assert_eq!(buffer.current_len(), 0);

            assert!(buffer.push(1, 1.0).is_available());
            assert_eq!(buffer.current_len(), 1);
            assert_eq!(buffer.size_hint(), Some(MAX_LENGTH - 1));

            assert!(buffer.push(2, 2.0).is_available());
            assert_eq!(buffer.current_len(), 2);
            assert_eq!(buffer.size_hint(), Some(MAX_LENGTH - 2));

            assert!(buffer.push(3, 3.0).is_available());
            assert_eq!(buffer.current_len(), 3);
            assert_eq!(buffer.size_hint(), Some(MAX_LENGTH - 3));

            assert!(buffer.push(4, 4.0).is_available());
            assert_eq!(buffer.current_len(), 4);
            assert_eq!(buffer.size_hint(), Some(MAX_LENGTH - 4));

            // This should error since further attempts will not work.
            assert!(buffer.push(5, 5.0).is_full());
            assert_eq!(buffer.current_len(), 5);
            assert_eq!(buffer.size_hint(), Some(0));

            assert!(buffer.push(6, 6.0).is_full());
            assert_eq!(buffer.current_len(), 5);
            assert_eq!(buffer.size_hint(), Some(0));

            assert_eq!(&ids, &[1, 2, 3, 4, 5]);
            assert_eq!(&distances, &[1.0, 2.0, 3.0, 4.0, 5.0]);
        }

        // All `iterator`.
        {
            let mut ids = [0u32; MAX_LENGTH];
            let mut distances = [0.0f32; MAX_LENGTH];
            let mut buffer = IdDistance::new(&mut ids, &mut distances);

            assert_eq!(buffer.capacity(), MAX_LENGTH);
            assert_eq!(buffer.size_hint(), Some(MAX_LENGTH));
            assert_eq!(buffer.current_len(), 0);

            let set = buffer.extend([(1, 1.0), (2, 2.0), (3, 3.0), (4, 4.0), (5, 5.0), (6, 6.0)]);
            assert_eq!(set, MAX_LENGTH);
            assert_eq!(buffer.current_len(), MAX_LENGTH);
            assert_eq!(buffer.size_hint(), Some(0));

            // Ensure that `pushing` respects the limit.
            assert!(buffer.push(7, 7.0).is_full());

            let set = buffer.extend([(10, 10.0), (20, 20.0)]);
            assert_eq!(set, 0, "no more items can be added");

            assert_eq!(&ids, &[1, 2, 3, 4, 5]);
            assert_eq!(&distances, &[1.0, 2.0, 3.0, 4.0, 5.0]);
        }

        // Mixture
        {
            let mut ids = [0u32; MAX_LENGTH];
            let mut distances = [0.0f32; MAX_LENGTH];
            let mut buffer = IdDistance::new(&mut ids, &mut distances);

            assert!(buffer.push(1, 1.0).is_available());

            let set = buffer.extend([(2, 2.0), (3, 3.0)]);
            assert_eq!(set, 2, "only two items were pushed");

            assert_eq!(buffer.current_len(), 3);
            assert_eq!(buffer.size_hint(), Some(2));

            assert!(buffer.push(4, 4.0).is_available());
            assert_eq!(buffer.current_len(), 4);
            assert_eq!(buffer.size_hint(), Some(1));

            let set = buffer.extend([(5, 5.0), (6, 6.0)]);
            assert_eq!(
                set, 1,
                "there should only be room for one more item in the buffer"
            );
            assert_eq!(buffer.current_len(), 5);
            assert_eq!(buffer.size_hint(), Some(0));

            assert_eq!(&ids, &[1, 2, 3, 4, 5],);
            assert_eq!(&distances, &[1.0, 2.0, 3.0, 4.0, 5.0]);
        }
    }

    #[test]
    #[should_panic(expected = "ids and associated_data should have the same length")]
    fn test_id_distance_associated_data_panics_on_different_id_associated_data_lengths() {
        let mut ids = vec![0u32; 10];
        let mut distances = vec![0.0f32; 10];
        let mut associated_data = vec![0u32; 9];
        IdDistanceAssociatedData::new(&mut ids, &mut distances, &mut associated_data);
    }

    #[test]
    fn test_id_distance_associated() {
        const MAX_LENGTH: usize = 5;

        // All `push`.
        {
            let mut ids = [0u32; MAX_LENGTH];
            let mut distances = [0.0f32; MAX_LENGTH];
            let mut associated = [0u32; MAX_LENGTH];
            let mut buffer =
                IdDistanceAssociatedData::new(&mut ids, &mut distances, &mut associated);

            assert_eq!(buffer.capacity(), MAX_LENGTH);
            assert_eq!(buffer.size_hint(), Some(MAX_LENGTH));
            assert_eq!(buffer.current_len(), 0);

            assert!(buffer.push((1, 10), 1.0).is_available());
            assert_eq!(buffer.current_len(), 1);
            assert_eq!(buffer.size_hint(), Some(MAX_LENGTH - 1));

            assert!(buffer.push((2, 20), 2.0).is_available());
            assert_eq!(buffer.current_len(), 2);
            assert_eq!(buffer.size_hint(), Some(MAX_LENGTH - 2));

            assert!(buffer.push((3, 30), 3.0).is_available());
            assert_eq!(buffer.current_len(), 3);
            assert_eq!(buffer.size_hint(), Some(MAX_LENGTH - 3));

            assert!(buffer.push((4, 40), 4.0).is_available());
            assert_eq!(buffer.current_len(), 4);
            assert_eq!(buffer.size_hint(), Some(MAX_LENGTH - 4));

            // This should error since further attempts will not work.
            assert!(buffer.push((5, 50), 5.0).is_full());
            assert_eq!(buffer.current_len(), 5);
            assert_eq!(buffer.size_hint(), Some(0));

            assert!(buffer.push((6, 60), 6.0).is_full());
            assert_eq!(buffer.current_len(), 5);
            assert_eq!(buffer.size_hint(), Some(0));

            assert_eq!(&ids, &[1, 2, 3, 4, 5]);
            assert_eq!(&distances, &[1.0, 2.0, 3.0, 4.0, 5.0]);
            assert_eq!(&associated, &[10, 20, 30, 40, 50]);
        }

        // All `iterator`.
        {
            let mut ids = [0u32; MAX_LENGTH];
            let mut distances = [0.0f32; MAX_LENGTH];
            let mut associated = [0u32; MAX_LENGTH];
            let mut buffer =
                IdDistanceAssociatedData::new(&mut ids, &mut distances, &mut associated);

            assert_eq!(buffer.capacity(), MAX_LENGTH);
            assert_eq!(buffer.size_hint(), Some(MAX_LENGTH));
            assert_eq!(buffer.current_len(), 0);

            let set = buffer.extend([
                ((1, 10), 1.0),
                ((2, 20), 2.0),
                ((3, 30), 3.0),
                ((4, 40), 4.0),
                ((5, 50), 5.0),
                ((6, 60), 6.0),
            ]);
            assert_eq!(set, MAX_LENGTH);
            assert_eq!(buffer.current_len(), MAX_LENGTH);
            assert_eq!(buffer.size_hint(), Some(0));

            // Ensure that `pushing` respects the limit.
            assert!(buffer.push((7, 70), 7.0).is_full());

            let set = buffer.extend([((10, 100), 10.0), ((20, 200), 20.0)]);
            assert_eq!(set, 0, "no more items can be added");

            assert_eq!(&ids, &[1, 2, 3, 4, 5]);
            assert_eq!(&distances, &[1.0, 2.0, 3.0, 4.0, 5.0]);
            assert_eq!(&associated, &[10, 20, 30, 40, 50]);
        }

        // Mixture
        {
            let mut ids = [0u32; MAX_LENGTH];
            let mut distances = [0.0f32; MAX_LENGTH];
            let mut associated = [0u32; MAX_LENGTH];
            let mut buffer =
                IdDistanceAssociatedData::new(&mut ids, &mut distances, &mut associated);

            assert!(buffer.push((1, 10), 1.0).is_available());

            let set = buffer.extend([((2, 20), 2.0), ((3, 30), 3.0)]);
            assert_eq!(set, 2, "only two items were pushed");

            assert_eq!(buffer.current_len(), 3);
            assert_eq!(buffer.size_hint(), Some(2));

            assert!(buffer.push((4, 40), 4.0).is_available());
            assert_eq!(buffer.current_len(), 4);
            assert_eq!(buffer.size_hint(), Some(1));

            let set = buffer.extend([((5, 50), 5.0), ((6, 60), 6.0)]);
            assert_eq!(
                set, 1,
                "there should only be room for one more item in the buffer"
            );
            assert_eq!(buffer.current_len(), 5);
            assert_eq!(buffer.size_hint(), Some(0));

            assert_eq!(&ids, &[1, 2, 3, 4, 5],);
            assert_eq!(&distances, &[1.0, 2.0, 3.0, 4.0, 5.0]);
            assert_eq!(&associated, &[10, 20, 30, 40, 50],);
        }
    }
}