kannolo 0.1.6

kANNolo is designed for easy prototyping of ANN Search algorithms while ensuring high effectiveness and efficiency over both dense and sparse vectors.
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
use crate::distances::{dense_dot_product_unrolled, dense_euclidean_distance_unrolled};
use crate::plain_quantizer::PlainQuantizer;
use crate::quantizer::{Quantizer, QueryEvaluator};
use crate::topk_selectors::{OnlineTopKSelector, TopkHeap};
use crate::{
    DArray1, Dataset, DenseDArray1, DistanceType, Float, GrowableDataset, PlainDenseDataset,
};
use crate::{DotProduct, EuclideanDistance};

use serde::{Deserialize, Serialize};

#[derive(Default, PartialEq, Debug, Clone, Serialize, Deserialize)]
pub struct DenseDataset<Q, B = Vec<<Q as Quantizer>::OutputItem>>
where
    Q: Quantizer,
{
    data: B,
    n_vecs: usize,
    d: usize,
    quantizer: Q,
}

/// immutable
impl<'a, Q, B> Dataset<'a, Q> for DenseDataset<Q, B>
where
    Q: Quantizer<DatasetType<'a> = Self> + 'a,
    B: AsRef<[Q::OutputItem]> + Default,
{
    type DataType = DenseDArray1<&'a [Q::OutputItem]>;

    #[inline]
    fn new(quantizer: Q, d: usize) -> Self {
        Self {
            data: B::default(),
            n_vecs: 0,
            d,
            quantizer,
        }
    }

    #[inline]
    fn quantizer(&self) -> &Q {
        &self.quantizer
    }

    #[inline]
    fn shape(&self) -> (usize, usize) {
        (self.n_vecs, self.d)
    }

    #[inline]
    fn data(&'a self) -> Self::DataType {
        DenseDArray1::new(self.data.as_ref())
    }

    #[inline]
    fn dim(&self) -> usize {
        self.d
    }

    #[inline]
    fn len(&self) -> usize {
        self.n_vecs
    }

    #[inline]
    fn nnz(&self) -> usize {
        self.n_vecs * self.d
    }

    fn get_space_usage_bytes(&self) -> usize {
        self.len() * self.dim() * std::mem::size_of::<Q::OutputItem>()
            + self.quantizer.get_space_usage_bytes()
    }

    #[inline]
    fn get(&'a self, index: usize) -> Self::DataType {
        assert!(index < self.len(), "Index out of bounds.");

        // m is the dim for plain, and is the number of subspaces for quantizers
        let m = self.quantizer.m();
        let start = index * m;
        let end = start + m;

        DenseDArray1::new(&self.data.as_ref()[start..end])
    }

    fn compute_distance_by_id(&'a self, idx1: usize, idx2: usize) -> f32
    where
        Q::OutputItem: Float,
    {
        let document1 = self.get(idx1);
        let document2 = self.get(idx2);
        match self.quantizer().distance() {
            DistanceType::Euclidean => dense_euclidean_distance_unrolled(&document1, &document2),
            DistanceType::DotProduct => -dense_dot_product_unrolled(&document1, &document2),
        }
    }

    #[inline]
    fn iter(&'a self) -> impl Iterator<Item = Self::DataType> {
        // 1 is the batch size
        DenseDatasetIter::new(self, 1)
    }

    #[inline]
    fn search<H: OnlineTopKSelector>(
        &'a self,
        query: <Q::Evaluator<'a> as QueryEvaluator<'a>>::QueryType,
        heap: &mut H,
    ) -> Vec<(f32, usize)>
    where
        Q::InputItem: Float + EuclideanDistance<Q::InputItem> + DotProduct<Q::InputItem>,
    {
        assert_eq!(
            query.len(),
            self.dim(),
            "Query dimension ({}) does not match the vector dimension ({}).",
            query.len(),
            self.dim()
        );

        if self.data().values_as_slice().is_empty() {
            return Vec::new();
        }

        let evaluator = self.query_evaluator(query);
        let distances = evaluator.compute_distances(0..self.len());
        evaluator.topk_retrieval(distances, heap)
    }
}

impl<'a, Q, B> DenseDataset<Q, B>
where
    Q: Quantizer,
    B: AsRef<[Q::OutputItem]>,
{
    #[inline]
    pub fn values(&self) -> &[Q::OutputItem] {
        self.data.as_ref()
    }
}

impl<'a, Q> DenseDataset<Q, Vec<Q::OutputItem>>
where
    Q: Quantizer,
{
    #[inline]
    pub fn with_capacity(quantizer: Q, d: usize, capacity: usize) -> Self {
        Self {
            data: Vec::with_capacity(capacity * d),
            n_vecs: 0,
            d,
            quantizer,
        }
    }

    #[inline]
    pub fn with_dim(quantizer: Q, d: usize) -> Self {
        Self {
            data: Vec::new(),
            n_vecs: 0,
            d,
            quantizer,
        }
    }

    #[inline]
    pub fn from_vec(data: Vec<Q::OutputItem>, d: usize, quantizer: Q) -> Self {
        let n_components = data.len();
        Self {
            data,
            n_vecs: n_components / d,
            d,
            quantizer,
        }
    }

    #[inline]
    pub fn shrink_to_fit(&mut self) {
        self.data.shrink_to_fit();
    }
}

/// mutable
impl<'a, Q> GrowableDataset<'a, Q> for DenseDataset<Q, Vec<Q::OutputItem>>
where
    Q: Quantizer<DatasetType<'a> = DenseDataset<Q>> + 'a,
    Q::OutputItem: Copy + Default,
{
    type InputDataType = DenseDArray1<&'a [Q::InputItem]>;

    #[inline]
    fn push(&mut self, vec: &Self::InputDataType) {
        assert_eq!(
            vec.len() % self.d,
            0,
            "Input vectors' length is not divisible by the dimensionality."
        );

        let old_size = self.data.len();
        let new_size = self.quantizer.m() + old_size;

        self.data.resize(new_size, Default::default());

        self.quantizer
            .encode(vec.values_as_slice(), &mut self.data[old_size..new_size]);

        self.n_vecs += 1;
    }
}

impl<Q> Extend<Q::OutputItem> for DenseDataset<Q, Vec<Q::OutputItem>>
where
    Q: Quantizer,
{
    fn extend<I: IntoIterator<Item = Q::OutputItem>>(&mut self, iter: I) {
        for item in iter {
            self.data.push(item);
        }
        self.n_vecs = self.data.len() / self.d;
    }
}

impl<Q> From<DenseDataset<Q, Vec<Q::OutputItem>>> for DenseDataset<Q, Box<[Q::OutputItem]>>
where
    Q: Quantizer,
{
    fn from(mutable_dataset: DenseDataset<Q, Vec<Q::OutputItem>>) -> Self {
        DenseDataset {
            data: mutable_dataset.data.into_boxed_slice(),
            n_vecs: mutable_dataset.n_vecs,
            d: mutable_dataset.d,
            quantizer: mutable_dataset.quantizer,
        }
    }
}

impl<'a, Q, B> IntoIterator for &'a DenseDataset<Q, B>
where
    Q: Quantizer<DatasetType<'a> = DenseDataset<Q, B>>,
    B: AsRef<[Q::OutputItem]> + Default,
{
    type Item = DenseDArray1<&'a [Q::OutputItem]>;
    type IntoIter = DenseDatasetIter<'a, Q>;

    fn into_iter(self) -> Self::IntoIter {
        DenseDatasetIter::new(self, 1)
    }
}

impl<Q, T> AsRef<[Q::OutputItem]> for DenseDataset<Q, T>
where
    Q: Quantizer,
    T: AsRef<[Q::OutputItem]>,
{
    fn as_ref(&self) -> &[Q::OutputItem] {
        self.data.as_ref()
    }
}

impl<Q, T> AsMut<[Q::OutputItem]> for DenseDataset<Q, T>
where
    Q: Quantizer,
    T: AsMut<[Q::OutputItem]>,
{
    fn as_mut(&mut self) -> &mut [Q::OutputItem] {
        self.data.as_mut()
    }
}

/// densedataset iterator
pub struct DenseDatasetIter<'a, Q>
where
    Q: Quantizer,
{
    data: &'a [Q::OutputItem],
    d: usize,
    batch_size: usize,
    index: usize,
}

impl<'a, Q> DenseDatasetIter<'a, Q>
where
    Q: Quantizer,
{
    pub fn new<B>(dataset: &'a DenseDataset<Q, B>, batch_size: usize) -> Self
    where
        Q: Quantizer<DatasetType<'a> = DenseDataset<Q, B>>,
        B: AsRef<[Q::OutputItem]> + Default,
    {
        Self {
            data: dataset.values(),
            d: dataset.dim(),
            batch_size,
            index: 0,
        }
    }
}

impl<'a, Q> Iterator for DenseDatasetIter<'a, Q>
where
    Q: Quantizer,
{
    type Item = DenseDArray1<&'a [Q::OutputItem]>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.index >= self.data.len() {
            return None;
        }

        let start = self.index;
        let end = std::cmp::min(start + self.batch_size * self.d, self.data.len());
        self.index = end;

        Some(DenseDArray1::new(&self.data[start..end]))
    }
}

impl<T> PlainDenseDataset<T>
where
    T: Float,
{
    #[inline]
    pub fn with_dim_plain(d: usize) -> Self {
        let quantizer = PlainQuantizer::new(d, DistanceType::Euclidean);
        Self {
            data: Vec::new(),
            n_vecs: 0,
            d,
            quantizer,
        }
    }

    #[inline]
    pub fn from_vec_plain(data: Vec<T>, d: usize) -> Self {
        let n_components = data.len();
        let quantizer = PlainQuantizer::new(d, DistanceType::Euclidean);
        Self {
            data,
            n_vecs: n_components / d,
            d,
            quantizer,
        }
    }

    #[inline]
    pub fn with_capacity_plain(capacity: usize, d: usize) -> Self {
        let quantizer = PlainQuantizer::new(d, DistanceType::Euclidean);
        Self {
            data: Vec::with_capacity(capacity * d),
            n_vecs: 0,
            d,
            quantizer,
        }
    }

    #[inline]
    pub fn from_random_sample(&self, n_vecs: usize) -> Self {
        use rand::seq::index::sample;

        let mut rng = rand::thread_rng();
        let sampled_id = sample(&mut rng, self.len(), n_vecs);
        let mut sample = Self::with_capacity_plain(n_vecs, self.d);

        for id in sampled_id {
            sample.push(&DenseDArray1::new(
                &self.data[id * self.d..(id + 1) * self.d],
            ));
        }

        sample
    }

    pub fn top1(&self, queries: &[T], batch_size: usize) -> Vec<(f32, usize)>
    where
        T: Float + EuclideanDistance<T> + DotProduct<T>,
    {
        assert!(
            queries.len() == batch_size * self.dim(),
            "Query dimension ({}) does not match centroid dimension ({})!",
            queries.len() / batch_size,
            self.dim(),
        );

        let mut results = Vec::with_capacity(batch_size);

        for query in queries.chunks_exact(self.dim()) {
            let query_array = DenseDArray1::new(query);

            let mut heap = TopkHeap::new(1);
            let search_results = self.search(query_array, &mut heap);

            if let Some((dist, idx)) = search_results.into_iter().next() {
                results.push((dist, idx));
            } else {
                results.push((f32::MAX, usize::MAX));
            }
        }

        results
    }
}