faiss 0.13.0

High-level bindings for Faiss, the vector similarity search engine
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
//! Vector transformation implementation

use crate::error::Result;
use crate::faiss_try;
use faiss_sys::*;
use std::os::raw::c_int;
use std::ptr;

/// Trait for native implementations of a Faiss VectorTransform.
pub trait NativeVectorTransform {
    /// Retrieve a pointer to the native object.
    fn inner_ptr(&self) -> *mut FaissVectorTransform;
}

pub trait VectorTransform {
    /// Getter for is_trained
    fn is_trained(&self) -> bool;

    /// Getter for input dimension
    fn d_in(&self) -> u32;

    /// Getter for output dimension
    fn d_out(&self) -> u32;

    /// Perform training on a representative set of vectors
    fn train(&mut self, n: usize, x: &[f32]) -> Result<()>;

    /// apply transformation and result is pre-allocated
    fn apply_noalloc(&self, x: &[f32]) -> Vec<f32>;

    /// reverse transformation. May not be implemented or may return
    /// approximate result
    fn reverse_transform(&self, xt: &[f32]) -> Vec<f32>;
}

impl<T> VectorTransform for T
where
    T: NativeVectorTransform,
{
    fn is_trained(&self) -> bool {
        unsafe { faiss_VectorTransform_is_trained(self.inner_ptr()) != 0 }
    }

    fn d_in(&self) -> u32 {
        unsafe { faiss_VectorTransform_d_in(self.inner_ptr()) as u32 }
    }

    fn d_out(&self) -> u32 {
        unsafe { faiss_VectorTransform_d_out(self.inner_ptr()) as u32 }
    }

    fn train(&mut self, n: usize, x: &[f32]) -> Result<()> {
        unsafe {
            faiss_try(faiss_VectorTransform_train(
                self.inner_ptr(),
                n as i64,
                x.as_ptr(),
            ))?;
            Ok(())
        }
    }

    fn apply_noalloc(&self, x: &[f32]) -> Vec<f32> {
        unsafe {
            let n = x.len() / self.d_in() as usize;
            let mut xt = Vec::with_capacity(n * self.d_out() as usize);
            faiss_VectorTransform_apply_noalloc(
                self.inner_ptr(),
                n as i64,
                x.as_ptr(),
                xt.as_mut_ptr(),
            );

            xt
        }
    }

    fn reverse_transform(&self, xt: &[f32]) -> Vec<f32> {
        unsafe {
            let n = xt.len() / self.d_out() as usize;
            let mut x = Vec::with_capacity(n * self.d_in() as usize);
            faiss_VectorTransform_reverse_transform(
                self.inner_ptr(),
                n as i64,
                xt.as_ptr(),
                x.as_mut_ptr(),
            );

            x
        }
    }
}

pub trait LinearTransform: VectorTransform {
    /// compute x = A^T * (x - b)
    /// is reverse transform if A has orthonormal lines
    fn transform_transpose(&self, y: &[f32]) -> Vec<f32>;

    /// compute A^T * A to set the is_orthonormal flag
    fn set_is_orthonormal(&mut self);

    /// Getter for have_bias
    fn have_bias(&self) -> bool;

    /// Getter for is_orthonormal
    fn is_orthonormal(&self) -> bool;
}

pub type RandomRotationMatrix = RandomRotationMatrixImpl;

pub struct RandomRotationMatrixImpl {
    inner: *mut FaissRandomRotationMatrix,
}

unsafe impl Send for RandomRotationMatrixImpl {}
unsafe impl Sync for RandomRotationMatrixImpl {}

impl Drop for RandomRotationMatrixImpl {
    fn drop(&mut self) {
        unsafe {
            faiss_RandomRotationMatrix_free(self.inner);
        }
    }
}

impl RandomRotationMatrixImpl {
    pub fn new(d_in: u32, d_out: u32) -> Result<Self> {
        unsafe {
            let mut inner = ptr::null_mut();
            faiss_try(faiss_RandomRotationMatrix_new_with(
                &mut inner,
                d_in as i32,
                d_out as i32,
            ))?;

            Ok(RandomRotationMatrixImpl { inner })
        }
    }
}

impl NativeVectorTransform for RandomRotationMatrixImpl {
    fn inner_ptr(&self) -> *mut FaissVectorTransform {
        self.inner
    }
}

impl_native_linear_transform!(RandomRotationMatrixImpl);

pub type PCAMatrix = PCAMatrixImpl;

pub struct PCAMatrixImpl {
    inner: *mut FaissPCAMatrix,
}

unsafe impl Send for PCAMatrixImpl {}
unsafe impl Sync for PCAMatrixImpl {}

impl Drop for PCAMatrixImpl {
    fn drop(&mut self) {
        unsafe {
            faiss_PCAMatrix_free(self.inner);
        }
    }
}

impl PCAMatrixImpl {
    pub fn new(d_in: u32, d_out: u32, eigen_power: f32, random_rotation: bool) -> Result<Self> {
        unsafe {
            let mut inner = ptr::null_mut();
            faiss_try(faiss_PCAMatrix_new_with(
                &mut inner,
                d_in as i32,
                d_out as i32,
                eigen_power,
                c_int::from(random_rotation),
            ))?;

            Ok(PCAMatrixImpl { inner })
        }
    }

    pub fn eigen_power(&self) -> f32 {
        unsafe { faiss_PCAMatrix_eigen_power(self.inner_ptr()) }
    }

    pub fn random_rotation(&self) -> bool {
        unsafe { faiss_PCAMatrix_random_rotation(self.inner_ptr()) != 0 }
    }
}

impl NativeVectorTransform for PCAMatrixImpl {
    fn inner_ptr(&self) -> *mut FaissVectorTransform {
        self.inner
    }
}

impl_native_linear_transform!(PCAMatrixImpl);

pub type ITQMatrix = ITQMatrixImpl;

pub struct ITQMatrixImpl {
    inner: *mut FaissITQMatrix,
}

unsafe impl Send for ITQMatrixImpl {}
unsafe impl Sync for ITQMatrixImpl {}

impl Drop for ITQMatrixImpl {
    fn drop(&mut self) {
        unsafe {
            faiss_ITQMatrix_free(self.inner);
        }
    }
}

impl ITQMatrixImpl {
    pub fn new(d: u32) -> Result<Self> {
        unsafe {
            let mut inner = ptr::null_mut();
            faiss_try(faiss_ITQMatrix_new_with(&mut inner, d as i32))?;

            Ok(ITQMatrixImpl { inner })
        }
    }
}

impl NativeVectorTransform for ITQMatrixImpl {
    fn inner_ptr(&self) -> *mut FaissVectorTransform {
        self.inner
    }
}

impl_native_linear_transform!(ITQMatrixImpl);

pub type ITQTransform = ITQTransformImpl;

pub struct ITQTransformImpl {
    inner: *mut FaissITQTransform,
}

unsafe impl Send for ITQTransformImpl {}
unsafe impl Sync for ITQTransformImpl {}

impl Drop for ITQTransformImpl {
    fn drop(&mut self) {
        unsafe {
            faiss_ITQTransform_free(self.inner);
        }
    }
}

impl ITQTransformImpl {
    pub fn new(d_in: u32, d_out: u32, do_pca: bool) -> Result<Self> {
        unsafe {
            let mut inner = ptr::null_mut();
            faiss_try(faiss_ITQTransform_new_with(
                &mut inner,
                d_in as i32,
                d_out as i32,
                c_int::from(do_pca),
            ))?;

            Ok(ITQTransformImpl { inner })
        }
    }

    pub fn get_do_pca(&self) -> bool {
        unsafe { faiss_ITQTransform_do_pca(self.inner_ptr()) != 0 }
    }
}

impl NativeVectorTransform for ITQTransformImpl {
    fn inner_ptr(&self) -> *mut FaissVectorTransform {
        self.inner
    }
}

pub type OPQMatrix = OPQMatrixImpl;

pub struct OPQMatrixImpl {
    inner: *mut FaissOPQMatrix,
}

unsafe impl Send for OPQMatrixImpl {}
unsafe impl Sync for OPQMatrixImpl {}

impl Drop for OPQMatrixImpl {
    fn drop(&mut self) {
        unsafe {
            faiss_OPQMatrix_free(self.inner);
        }
    }
}

impl OPQMatrixImpl {
    pub fn new(d: u32, m: u32, d2: u32) -> Result<Self> {
        unsafe {
            let mut inner = ptr::null_mut();
            faiss_try(faiss_OPQMatrix_new_with(
                &mut inner, d as i32, m as i32, d2 as i32,
            ))?;

            Ok(OPQMatrixImpl { inner })
        }
    }

    pub fn set_verbose(&mut self, value: bool) {
        unsafe { faiss_OPQMatrix_set_verbose(self.inner_ptr(), c_int::from(value)) }
    }

    pub fn verbose(&self) -> bool {
        unsafe { faiss_OPQMatrix_verbose(self.inner_ptr()) != 0 }
    }

    pub fn set_niter(&mut self, value: u32) {
        unsafe { faiss_OPQMatrix_set_niter(self.inner_ptr(), value as i32) }
    }

    pub fn niter(&self) -> u32 {
        unsafe { faiss_OPQMatrix_niter(self.inner_ptr()) as u32 }
    }

    pub fn set_niter_pq(&mut self, value: u32) {
        unsafe { faiss_OPQMatrix_set_niter_pq(self.inner_ptr(), value as i32) }
    }

    pub fn niter_pq(&self) -> u32 {
        unsafe { faiss_OPQMatrix_niter_pq(self.inner_ptr()) as u32 }
    }
}

impl NativeVectorTransform for OPQMatrixImpl {
    fn inner_ptr(&self) -> *mut FaissVectorTransform {
        self.inner
    }
}

impl_native_linear_transform!(OPQMatrixImpl);

pub type RemapDimensionsTransform = RemapDimensionsTransformImpl;

pub struct RemapDimensionsTransformImpl {
    inner: *mut FaissRemapDimensionsTransform,
}

unsafe impl Send for RemapDimensionsTransformImpl {}
unsafe impl Sync for RemapDimensionsTransformImpl {}

impl Drop for RemapDimensionsTransformImpl {
    fn drop(&mut self) {
        unsafe {
            faiss_RemapDimensionsTransform_free(self.inner);
        }
    }
}

impl RemapDimensionsTransformImpl {
    pub fn new(d_in: u32, d_out: u32, uniform: bool) -> Result<Self> {
        unsafe {
            let mut inner = ptr::null_mut();
            faiss_try(faiss_RemapDimensionsTransform_new_with(
                &mut inner,
                d_in as i32,
                d_out as i32,
                c_int::from(uniform),
            ))?;

            Ok(RemapDimensionsTransformImpl { inner })
        }
    }
}

impl NativeVectorTransform for RemapDimensionsTransformImpl {
    fn inner_ptr(&self) -> *mut FaissVectorTransform {
        self.inner
    }
}

pub type NormalizationTransform = NormalizationTransformImpl;

pub struct NormalizationTransformImpl {
    inner: *mut FaissNormalizationTransform,
}

unsafe impl Send for NormalizationTransformImpl {}
unsafe impl Sync for NormalizationTransformImpl {}

impl Drop for NormalizationTransformImpl {
    fn drop(&mut self) {
        unsafe {
            faiss_NormalizationTransform_free(self.inner);
        }
    }
}

impl NormalizationTransformImpl {
    pub fn new(d: u32, norm: f32) -> Result<Self> {
        unsafe {
            let mut inner = ptr::null_mut();
            faiss_try(faiss_NormalizationTransform_new_with(
                &mut inner, d as i32, norm,
            ))?;

            Ok(NormalizationTransformImpl { inner })
        }
    }

    pub fn norm(&self) -> f32 {
        unsafe { faiss_NormalizationTransform_norm(self.inner_ptr()) }
    }
}

impl NativeVectorTransform for NormalizationTransformImpl {
    fn inner_ptr(&self) -> *mut FaissVectorTransform {
        self.inner
    }
}

pub type CenteringTransform = CenteringTransformImpl;

pub struct CenteringTransformImpl {
    inner: *mut FaissCenteringTransform,
}

unsafe impl Send for CenteringTransformImpl {}
unsafe impl Sync for CenteringTransformImpl {}

impl Drop for CenteringTransformImpl {
    fn drop(&mut self) {
        unsafe {
            faiss_CenteringTransform_free(self.inner);
        }
    }
}

impl CenteringTransformImpl {
    pub fn new(d: u32) -> Result<Self> {
        unsafe {
            let mut inner = ptr::null_mut();
            faiss_try(faiss_CenteringTransform_new_with(&mut inner, d as i32))?;

            Ok(CenteringTransformImpl { inner })
        }
    }
}

impl NativeVectorTransform for CenteringTransformImpl {
    fn inner_ptr(&self) -> *mut FaissVectorTransform {
        self.inner
    }
}

#[cfg(test)]
mod tests {

    use super::*;

    #[test]
    fn random_rotation_matrix_base_checks() {
        let rrt = RandomRotationMatrix::new(512, 256).unwrap();
        // vector transform
        assert_eq!(rrt.d_in(), 512);
        assert_eq!(rrt.d_out(), 256);
        assert_eq!(rrt.is_trained(), false);
    }
}