rabitq-rs 0.9.0

Advanced vector search: RaBitQ quantization with IVF and MSTG (Multi-Scale Tree Graph) index
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
474
475
476
477
//! SIMD-accelerated distance estimation for MSTG posting lists
//!
//! This module provides optimized distance calculations using AVX2/AVX-512 SIMD instructions
//! to accelerate the hot path in MSTG search.

use super::distance::{estimate_distance, QueryContext};
use crate::{Metric, QuantizedVector};

/// SIMD-accelerated distance estimation (auto-detects CPU features)
///
/// This is the main entry point that automatically selects the best implementation
/// based on available CPU features.
///
/// # Performance
/// Expected speedup: 3-5x compared to scalar implementation on AVX2 CPUs
#[inline]
pub fn estimate_distance_fast(
    ctx: &QueryContext,
    centroid: &[f32],
    quantized: &QuantizedVector,
    metric: Metric,
) -> f32 {
    #[cfg(target_arch = "x86_64")]
    {
        // Try AVX-512 first (best performance) - auto-detected at runtime
        // Automatically available when compiled with target-cpu=native on AVX-512 CPUs
        #[cfg(target_feature = "avx512f")]
        {
            if is_x86_feature_detected!("avx512f") {
                return unsafe { estimate_distance_avx512(ctx, centroid, quantized, metric) };
            }
        }

        // Fall back to AVX2 (widely available)
        if is_x86_feature_detected!("avx2") && is_x86_feature_detected!("fma") {
            return unsafe { estimate_distance_avx2(ctx, centroid, quantized, metric) };
        }
    }

    // Fallback to scalar version for non-x86 or old CPUs
    estimate_distance(ctx, centroid, quantized, metric)
}

// ============================================================================
// AVX2 Implementation (256-bit SIMD)
// ============================================================================

#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2", enable = "fma")]
unsafe fn estimate_distance_avx2(
    ctx: &QueryContext,
    centroid: &[f32],
    quantized: &QuantizedVector,
    metric: Metric,
) -> f32 {
    // Step 1: Compute g_add (query-to-centroid distance component)
    let g_add = match metric {
        Metric::L2 => l2_distance_sqr_avx2(ctx.query, centroid),
        Metric::InnerProduct => -dot_avx2(ctx.query, centroid),
    };

    // Step 2: Binary code dot product with SIMD
    let binary_code = quantized.unpack_binary_code();
    let binary_dot = binary_u8_dot_f32_avx2(ctx.query, &binary_code);

    let binary_term = binary_dot + ctx.c1 * ctx.sum_query;
    let distance_1bit = quantized.f_add + g_add + quantized.f_rescale * binary_term;

    // Step 3: Extended code contribution (if present)
    if ctx.ex_bits > 0 {
        let ex_code = quantized.unpack_ex_code();
        // Convert u16 ex_code to u8 for SIMD (most values fit in u8 range for 7-bit encoding)
        let ex_code_u8: Vec<u8> = ex_code.iter().map(|&x| x.min(255) as u8).collect();
        let ex_dot = ex_u8_dot_f32_avx2(ctx.query, &ex_code_u8);

        let total_term = ctx.binary_scale * binary_dot + ex_dot + ctx.cb * ctx.sum_query;
        quantized.f_add_ex + g_add + quantized.f_rescale_ex * total_term
    } else {
        distance_1bit
    }
}

/// Compute dot product between f32 query and u8 binary code (0 or 1) using AVX2
///
/// # Safety
/// Requires AVX2 support. Caller must check CPU features.
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2")]
unsafe fn binary_u8_dot_f32_avx2(query: &[f32], binary_code: &[u8]) -> f32 {
    use std::arch::x86_64::*;

    let len = query.len().min(binary_code.len());
    let mut sum = _mm256_setzero_ps();

    // Process 8 elements at a time
    let chunks = len / 8;
    for i in 0..chunks {
        let offset = i * 8;

        // Load 8 f32 values from query
        let q = _mm256_loadu_ps(query.as_ptr().add(offset));

        // Load 8 u8 values and convert to f32
        // Note: binary_code contains only 0 or 1
        let b_u8 = _mm_loadl_epi64(binary_code.as_ptr().add(offset) as *const __m128i);
        let b_i32 = _mm256_cvtepu8_epi32(b_u8);
        let b = _mm256_cvtepi32_ps(b_i32);

        // Multiply and accumulate using FMA
        sum = _mm256_fmadd_ps(q, b, sum);
    }

    // Horizontal sum using hadd
    let sum = _mm256_hadd_ps(sum, sum);
    let sum = _mm256_hadd_ps(sum, sum);

    // Extract result (sum of all 8 lanes)
    let lo = _mm256_extractf128_ps(sum, 0);
    let hi = _mm256_extractf128_ps(sum, 1);
    let sum128 = _mm_add_ss(lo, hi);
    let mut result = _mm_cvtss_f32(sum128);

    // Handle remaining elements (scalar)
    for i in (chunks * 8)..len {
        result += query[i] * (binary_code[i] as f32);
    }

    result
}

/// Compute dot product between f32 query and u8 ex_code (0-127) using AVX2
///
/// # Safety
/// Requires AVX2 support. Caller must check CPU features.
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2")]
unsafe fn ex_u8_dot_f32_avx2(query: &[f32], ex_code: &[u8]) -> f32 {
    use std::arch::x86_64::*;

    let len = query.len().min(ex_code.len());
    let mut sum = _mm256_setzero_ps();

    let chunks = len / 8;
    for i in 0..chunks {
        let offset = i * 8;

        let q = _mm256_loadu_ps(query.as_ptr().add(offset));

        // Load and convert u8 to f32
        let ex_u8 = _mm_loadl_epi64(ex_code.as_ptr().add(offset) as *const __m128i);
        let ex_i32 = _mm256_cvtepu8_epi32(ex_u8);
        let ex = _mm256_cvtepi32_ps(ex_i32);

        sum = _mm256_fmadd_ps(q, ex, sum);
    }

    // Horizontal sum
    let sum = _mm256_hadd_ps(sum, sum);
    let sum = _mm256_hadd_ps(sum, sum);
    let lo = _mm256_extractf128_ps(sum, 0);
    let hi = _mm256_extractf128_ps(sum, 1);
    let sum128 = _mm_add_ss(lo, hi);
    let mut result = _mm_cvtss_f32(sum128);

    for i in (chunks * 8)..len {
        result += query[i] * (ex_code[i] as f32);
    }

    result
}

/// L2 distance squared using AVX2 with FMA
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2", enable = "fma")]
unsafe fn l2_distance_sqr_avx2(a: &[f32], b: &[f32]) -> f32 {
    use std::arch::x86_64::*;

    let len = a.len().min(b.len());
    let mut sum = _mm256_setzero_ps();

    let chunks = len / 8;
    for i in 0..chunks {
        let offset = i * 8;
        let a_vec = _mm256_loadu_ps(a.as_ptr().add(offset));
        let b_vec = _mm256_loadu_ps(b.as_ptr().add(offset));
        let diff = _mm256_sub_ps(a_vec, b_vec);
        sum = _mm256_fmadd_ps(diff, diff, sum);
    }

    // Horizontal sum
    let sum = _mm256_hadd_ps(sum, sum);
    let sum = _mm256_hadd_ps(sum, sum);
    let lo = _mm256_extractf128_ps(sum, 0);
    let hi = _mm256_extractf128_ps(sum, 1);
    let sum128 = _mm_add_ss(lo, hi);
    let mut result = _mm_cvtss_f32(sum128);

    // Remainder
    for i in (chunks * 8)..len {
        let diff = a[i] - b[i];
        result += diff * diff;
    }

    result
}

/// Dot product using AVX2 with FMA
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2", enable = "fma")]
unsafe fn dot_avx2(a: &[f32], b: &[f32]) -> f32 {
    use std::arch::x86_64::*;

    let len = a.len().min(b.len());
    let mut sum = _mm256_setzero_ps();

    let chunks = len / 8;
    for i in 0..chunks {
        let offset = i * 8;
        let a_vec = _mm256_loadu_ps(a.as_ptr().add(offset));
        let b_vec = _mm256_loadu_ps(b.as_ptr().add(offset));
        sum = _mm256_fmadd_ps(a_vec, b_vec, sum);
    }

    // Horizontal sum
    let sum = _mm256_hadd_ps(sum, sum);
    let sum = _mm256_hadd_ps(sum, sum);
    let lo = _mm256_extractf128_ps(sum, 0);
    let hi = _mm256_extractf128_ps(sum, 1);
    let sum128 = _mm_add_ss(lo, hi);
    let mut result = _mm_cvtss_f32(sum128);

    for i in (chunks * 8)..len {
        result += a[i] * b[i];
    }

    result
}

// ============================================================================
// AVX-512 Implementation (512-bit SIMD) - Auto-detected at runtime
// Note: Automatically compiled when using target-cpu=native on AVX-512 CPUs
// ============================================================================

#[cfg(all(target_arch = "x86_64", target_feature = "avx512f"))]
/// Compute dot product between f32 query and u8 binary code using AVX-512
///
/// # Safety
/// Requires AVX-512F support. Caller must check CPU features.
#[target_feature(enable = "avx512f")]
unsafe fn binary_u8_dot_f32_avx512(query: &[f32], binary_code: &[u8]) -> f32 {
    use std::arch::x86_64::*;

    let len = query.len().min(binary_code.len());
    let mut sum = _mm512_setzero_ps();

    // Process 16 elements at a time (512-bit SIMD)
    let chunks = len / 16;
    for i in 0..chunks {
        let offset = i * 16;

        // Load 16 f32 values from query
        let q = _mm512_loadu_ps(query.as_ptr().add(offset));

        // Load 16 u8 values and convert to f32
        // Load to 128-bit register first
        let b_u8 = _mm_loadu_si128(binary_code.as_ptr().add(offset) as *const __m128i);
        // Convert u8 -> i32 -> f32
        let b_i32 = _mm512_cvtepu8_epi32(b_u8);
        let b = _mm512_cvtepi32_ps(b_i32);

        // Multiply and accumulate using FMA
        sum = _mm512_fmadd_ps(q, b, sum);
    }

    // Horizontal sum using AVX-512 reduce instruction (much simpler than AVX2!)
    let mut result = _mm512_reduce_add_ps(sum);

    // Handle remaining elements (scalar)
    for i in (chunks * 16)..len {
        result += query[i] * (binary_code[i] as f32);
    }

    result
}

#[cfg(all(target_arch = "x86_64", target_feature = "avx512f"))]
/// Compute dot product between f32 query and u8 ex_code using AVX-512
///
/// # Safety
/// Requires AVX-512F support. Caller must check CPU features.
#[target_feature(enable = "avx512f")]
unsafe fn ex_u8_dot_f32_avx512(query: &[f32], ex_code: &[u8]) -> f32 {
    use std::arch::x86_64::*;

    let len = query.len().min(ex_code.len());
    let mut sum = _mm512_setzero_ps();

    let chunks = len / 16;
    for i in 0..chunks {
        let offset = i * 16;

        let q = _mm512_loadu_ps(query.as_ptr().add(offset));

        // Load and convert u8 to f32
        let ex_u8 = _mm_loadu_si128(ex_code.as_ptr().add(offset) as *const __m128i);
        let ex_i32 = _mm512_cvtepu8_epi32(ex_u8);
        let ex = _mm512_cvtepi32_ps(ex_i32);

        sum = _mm512_fmadd_ps(q, ex, sum);
    }

    // Horizontal sum
    let mut result = _mm512_reduce_add_ps(sum);

    for i in (chunks * 16)..len {
        result += query[i] * (ex_code[i] as f32);
    }

    result
}

#[cfg(all(target_arch = "x86_64", target_feature = "avx512f"))]
/// L2 distance squared using AVX-512 with FMA
#[target_feature(enable = "avx512f")]
unsafe fn l2_distance_sqr_avx512(a: &[f32], b: &[f32]) -> f32 {
    use std::arch::x86_64::*;

    let len = a.len().min(b.len());
    let mut sum = _mm512_setzero_ps();

    let chunks = len / 16;
    for i in 0..chunks {
        let offset = i * 16;
        let a_vec = _mm512_loadu_ps(a.as_ptr().add(offset));
        let b_vec = _mm512_loadu_ps(b.as_ptr().add(offset));
        let diff = _mm512_sub_ps(a_vec, b_vec);
        sum = _mm512_fmadd_ps(diff, diff, sum);
    }

    // Horizontal sum
    let mut result = _mm512_reduce_add_ps(sum);

    // Remainder
    for i in (chunks * 16)..len {
        let diff = a[i] - b[i];
        result += diff * diff;
    }

    result
}

#[cfg(all(target_arch = "x86_64", target_feature = "avx512f"))]
/// Dot product using AVX-512 with FMA
#[target_feature(enable = "avx512f")]
unsafe fn dot_avx512(a: &[f32], b: &[f32]) -> f32 {
    use std::arch::x86_64::*;

    let len = a.len().min(b.len());
    let mut sum = _mm512_setzero_ps();

    let chunks = len / 16;
    for i in 0..chunks {
        let offset = i * 16;
        let a_vec = _mm512_loadu_ps(a.as_ptr().add(offset));
        let b_vec = _mm512_loadu_ps(b.as_ptr().add(offset));
        sum = _mm512_fmadd_ps(a_vec, b_vec, sum);
    }

    // Horizontal sum
    let mut result = _mm512_reduce_add_ps(sum);

    for i in (chunks * 16)..len {
        result += a[i] * b[i];
    }

    result
}

#[cfg(all(target_arch = "x86_64", target_feature = "avx512f"))]
#[target_feature(enable = "avx512f")]
unsafe fn estimate_distance_avx512(
    ctx: &QueryContext,
    centroid: &[f32],
    quantized: &QuantizedVector,
    metric: Metric,
) -> f32 {
    // Step 1: Compute g_add (query-to-centroid distance component)
    let g_add = match metric {
        Metric::L2 => l2_distance_sqr_avx512(ctx.query, centroid),
        Metric::InnerProduct => -dot_avx512(ctx.query, centroid),
    };

    // Step 2: Binary code dot product with SIMD
    let binary_code = quantized.unpack_binary_code();
    let binary_dot = binary_u8_dot_f32_avx512(ctx.query, &binary_code);

    let binary_term = binary_dot + ctx.c1 * ctx.sum_query;
    let distance_1bit = quantized.f_add + g_add + quantized.f_rescale * binary_term;

    // Step 3: Extended code contribution (if present)
    if ctx.ex_bits > 0 {
        let ex_code = quantized.unpack_ex_code();
        // Convert u16 ex_code to u8 for SIMD
        let ex_code_u8: Vec<u8> = ex_code.iter().map(|&x| x.min(255) as u8).collect();
        let ex_dot = ex_u8_dot_f32_avx512(ctx.query, &ex_code_u8);

        let total_term = ctx.binary_scale * binary_dot + ex_dot + ctx.cb * ctx.sum_query;
        quantized.f_add_ex + g_add + quantized.f_rescale_ex * total_term
    } else {
        distance_1bit
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::quantizer::{quantize_with_centroid, RabitqConfig};
    use crate::Metric;
    use rand::prelude::*;

    #[test]
    fn test_simd_vs_scalar() {
        let mut rng = StdRng::seed_from_u64(42);

        // Generate test data
        let dim = 960;
        let query: Vec<f32> = (0..dim).map(|_| rng.gen()).collect();
        let centroid: Vec<f32> = (0..dim).map(|_| rng.gen()).collect();
        let vector: Vec<f32> = (0..dim).map(|_| rng.gen()).collect();

        // Use RaBitQ
        let config = RabitqConfig::faster(dim, 7, 42);
        let quantized = quantize_with_centroid(&vector, &centroid, &config, Metric::L2);

        // Create query context (ex_bits = total_bits - 1 for the sign bit)
        let ex_bits = config.total_bits.saturating_sub(1) as u8;
        let ctx = QueryContext::new(&query, ex_bits);

        // Compare SIMD and scalar versions
        let result_scalar = estimate_distance(&ctx, &centroid, &quantized, Metric::L2);
        let result_simd = estimate_distance_fast(&ctx, &centroid, &quantized, Metric::L2);

        // Results should be very close (may have small floating point differences)
        let diff = (result_scalar - result_simd).abs();
        assert!(
            diff < 0.01,
            "SIMD and scalar results differ: {} vs {} (diff: {})",
            result_scalar,
            result_simd,
            diff
        );
    }

    #[test]
    #[cfg(target_arch = "x86_64")]
    fn test_binary_dot_simd() {
        if !is_x86_feature_detected!("avx2") {
            println!("Skipping AVX2 test on non-AVX2 CPU");
            return;
        }

        let query = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0];
        let binary = vec![1, 0, 1, 0, 1, 0, 1, 0, 1, 0];

        let result_simd = unsafe { binary_u8_dot_f32_avx2(&query, &binary) };

        // Expected: 1*1 + 3*1 + 5*1 + 7*1 + 9*1 = 25
        let expected = 25.0;

        assert!(
            (result_simd - expected).abs() < 0.001,
            "Binary dot SIMD: got {}, expected {}",
            result_simd,
            expected
        );
    }
}