rag-plusplus-core 0.1.0

High-performance retrieval engine with SIMD-accelerated vector search and trajectory memory
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
//! Scalar (Pure Rust) Distance Implementations
//!
//! These are the baseline implementations without SIMD.
//! They serve as:
//! - Fallback when SIMD is not available
//! - Reference implementations for correctness testing
//! - Baseline for benchmark comparisons

/// Compute L2 (Euclidean) distance between two vectors.
///
/// `L2 = sqrt(sum((a[i] - b[i])^2))`
///
/// # Arguments
///
/// * `a` - First vector
/// * `b` - Second vector (must have same length as `a`)
///
/// # Returns
///
/// The Euclidean distance. Lower values indicate more similar vectors.
/// Returns 0.0 for identical vectors.
///
/// # Example
///
/// ```
/// use rag_plusplus_core::distance::l2_distance;
///
/// let a = [1.0, 0.0, 0.0];
/// let b = [0.0, 1.0, 0.0];
/// let dist = l2_distance(&a, &b);
/// assert!((dist - std::f32::consts::SQRT_2).abs() < 1e-6);
/// ```
#[inline]
pub fn l2_distance(a: &[f32], b: &[f32]) -> f32 {
    l2_distance_squared(a, b).sqrt()
}

/// Compute squared L2 distance (avoids sqrt for comparison-only use).
///
/// When only comparing distances (not using the actual value), using
/// squared distance avoids the expensive sqrt operation.
///
/// # Arguments
///
/// * `a` - First vector
/// * `b` - Second vector (must have same length as `a`)
///
/// # Returns
///
/// The squared Euclidean distance.
#[inline]
pub fn l2_distance_squared(a: &[f32], b: &[f32]) -> f32 {
    debug_assert_eq!(a.len(), b.len());

    a.iter()
        .zip(b.iter())
        .map(|(x, y)| {
            let diff = x - y;
            diff * diff
        })
        .sum()
}

/// Compute inner product (dot product) of two vectors.
///
/// `IP = sum(a[i] * b[i])`
///
/// # Arguments
///
/// * `a` - First vector
/// * `b` - Second vector (must have same length as `a`)
///
/// # Returns
///
/// The inner product. Higher values indicate more similar vectors
/// (assuming vectors point in similar directions).
///
/// # Example
///
/// ```
/// use rag_plusplus_core::distance::inner_product;
///
/// let a = [1.0, 2.0, 3.0];
/// let b = [4.0, 5.0, 6.0];
/// let ip = inner_product(&a, &b);
/// assert!((ip - 32.0).abs() < 1e-6); // 1*4 + 2*5 + 3*6 = 32
/// ```
#[inline]
pub fn inner_product(a: &[f32], b: &[f32]) -> f32 {
    debug_assert_eq!(a.len(), b.len());

    a.iter()
        .zip(b.iter())
        .map(|(x, y)| x * y)
        .sum()
}

/// Compute cosine similarity between two vectors.
///
/// `cos(a, b) = dot(a, b) / (||a|| * ||b||)`
///
/// # Arguments
///
/// * `a` - First vector
/// * `b` - Second vector (must have same length as `a`)
///
/// # Returns
///
/// Cosine similarity in range [-1, 1]. Higher values indicate more similar vectors.
/// Returns 1.0 for identical directions, 0.0 for orthogonal, -1.0 for opposite.
/// Returns 0.0 if either vector has zero norm.
///
/// # Performance Note
///
/// For pre-normalized vectors (norm = 1), use `inner_product` instead -
/// it's equivalent but faster (skips norm computation).
///
/// # Example
///
/// ```
/// use rag_plusplus_core::distance::cosine_similarity;
///
/// let a = [1.0, 0.0];
/// let b = [1.0, 0.0];
/// let cos = cosine_similarity(&a, &b);
/// assert!((cos - 1.0).abs() < 1e-6); // Identical = 1.0
/// ```
#[inline]
pub fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
    debug_assert_eq!(a.len(), b.len());

    let dot = inner_product(a, b);
    let norm_a = norm(a);
    let norm_b = norm(b);

    if norm_a == 0.0 || norm_b == 0.0 {
        0.0
    } else {
        dot / (norm_a * norm_b)
    }
}

/// Compute cosine distance (1 - cosine_similarity).
///
/// This converts cosine similarity to a distance where lower = more similar,
/// suitable for min-heap based nearest neighbor search.
///
/// # Arguments
///
/// * `a` - First vector
/// * `b` - Second vector
///
/// # Returns
///
/// Cosine distance in range [0, 2]. Lower values indicate more similar vectors.
#[inline]
pub fn cosine_distance(a: &[f32], b: &[f32]) -> f32 {
    1.0 - cosine_similarity(a, b)
}

/// Compute the L2 norm (magnitude) of a vector.
///
/// `||a|| = sqrt(sum(a[i]^2))`
///
/// # Arguments
///
/// * `a` - Input vector
///
/// # Returns
///
/// The L2 norm of the vector. Returns 0.0 for zero vector.
#[inline]
pub fn norm(a: &[f32]) -> f32 {
    a.iter().map(|x| x * x).sum::<f32>().sqrt()
}

/// Compute squared L2 norm (avoids sqrt).
#[inline]
pub fn norm_squared(a: &[f32]) -> f32 {
    a.iter().map(|x| x * x).sum()
}

/// Create a normalized copy of a vector (unit vector).
///
/// # Arguments
///
/// * `a` - Input vector
///
/// # Returns
///
/// A new vector with the same direction but norm = 1.
/// Returns zero vector if input has zero norm.
#[inline]
#[must_use]
pub fn normalize(a: &[f32]) -> Vec<f32> {
    let n = norm(a);
    if n == 0.0 {
        vec![0.0; a.len()]
    } else {
        a.iter().map(|x| x / n).collect()
    }
}

/// Normalize a vector in-place.
///
/// # Arguments
///
/// * `a` - Vector to normalize (modified in-place)
///
/// # Returns
///
/// The original norm of the vector.
#[inline]
pub fn normalize_in_place(a: &mut [f32]) -> f32 {
    let n = norm(a);
    if n > 0.0 {
        for x in a.iter_mut() {
            *x /= n;
        }
    }
    n
}

// =============================================================================
// BATCH OPERATIONS
// =============================================================================

/// Batch L2 normalization of multiple vectors.
///
/// Normalizes each vector in-place. Optimized for processing large batches
/// of embeddings (thousands of vectors).
///
/// # Arguments
///
/// * `vectors` - Mutable slice of vectors, each represented as a mutable slice
///
/// # Returns
///
/// Vector of original norms for each input vector.
///
/// # Example
///
/// ```
/// use rag_plusplus_core::distance::normalize_batch;
///
/// let mut vecs = vec![
///     vec![3.0f32, 4.0],
///     vec![5.0, 12.0],
///     vec![8.0, 15.0],
/// ];
///
/// // Convert to mutable slices
/// let mut slices: Vec<&mut [f32]> = vecs.iter_mut().map(|v| v.as_mut_slice()).collect();
/// let norms = normalize_batch(&mut slices);
///
/// assert!((norms[0] - 5.0).abs() < 1e-6);   // 3-4-5
/// assert!((norms[1] - 13.0).abs() < 1e-6);  // 5-12-13
/// assert!((norms[2] - 17.0).abs() < 1e-6);  // 8-15-17
/// ```
pub fn normalize_batch(vectors: &mut [&mut [f32]]) -> Vec<f32> {
    vectors.iter_mut()
        .map(|v| normalize_in_place(v))
        .collect()
}

/// Batch L2 normalization of flat vector storage.
///
/// More memory-efficient version that operates on a flat array where
/// vectors are stored contiguously. Each vector has the same dimension.
///
/// # Arguments
///
/// * `data` - Flat array of vectors stored contiguously
/// * `dim` - Dimension of each vector
///
/// # Returns
///
/// Vector of original norms for each vector.
///
/// # Panics
///
/// Panics if `data.len() % dim != 0`.
///
/// # Example
///
/// ```
/// use rag_plusplus_core::distance::normalize_batch_flat;
///
/// let mut data = vec![
///     3.0f32, 4.0,    // Vector 0: norm = 5
///     5.0, 12.0,      // Vector 1: norm = 13
/// ];
///
/// let norms = normalize_batch_flat(&mut data, 2);
///
/// assert!((norms[0] - 5.0).abs() < 1e-6);
/// assert!((norms[1] - 13.0).abs() < 1e-6);
/// assert!((data[0] - 0.6).abs() < 1e-6);  // 3/5
/// assert!((data[1] - 0.8).abs() < 1e-6);  // 4/5
/// ```
pub fn normalize_batch_flat(data: &mut [f32], dim: usize) -> Vec<f32> {
    assert!(dim > 0, "Dimension must be > 0");
    assert!(data.len() % dim == 0, "Data length must be multiple of dimension");

    let n_vectors = data.len() / dim;
    let mut norms = Vec::with_capacity(n_vectors);

    for i in 0..n_vectors {
        let start = i * dim;
        let end = start + dim;
        let vector = &mut data[start..end];
        let n = normalize_in_place(vector);
        norms.push(n);
    }

    norms
}

/// Compute norms for a batch of vectors (without normalization).
///
/// Useful for computing statistics or filtering before normalization.
///
/// # Arguments
///
/// * `data` - Flat array of vectors stored contiguously
/// * `dim` - Dimension of each vector
///
/// # Returns
///
/// Vector of L2 norms for each vector.
pub fn compute_norms_batch(data: &[f32], dim: usize) -> Vec<f32> {
    assert!(dim > 0, "Dimension must be > 0");
    assert!(data.len() % dim == 0, "Data length must be multiple of dimension");

    let n_vectors = data.len() / dim;
    let mut norms = Vec::with_capacity(n_vectors);

    for i in 0..n_vectors {
        let start = i * dim;
        let end = start + dim;
        let vector = &data[start..end];
        norms.push(norm(vector));
    }

    norms
}

/// Validate that all vectors are normalized (norm ≈ 1.0).
///
/// # Arguments
///
/// * `data` - Flat array of vectors stored contiguously
/// * `dim` - Dimension of each vector
/// * `tolerance` - Maximum allowed deviation from 1.0
///
/// # Returns
///
/// Vector of indices of vectors that are NOT normalized within tolerance.
/// Empty vector if all are normalized.
pub fn find_unnormalized(data: &[f32], dim: usize, tolerance: f32) -> Vec<usize> {
    assert!(dim > 0, "Dimension must be > 0");
    assert!(data.len() % dim == 0, "Data length must be multiple of dimension");

    let n_vectors = data.len() / dim;
    let mut unnormalized = Vec::new();

    for i in 0..n_vectors {
        let start = i * dim;
        let end = start + dim;
        let vector = &data[start..end];
        let n = norm(vector);
        if (n - 1.0).abs() > tolerance {
            unnormalized.push(i);
        }
    }

    unnormalized
}

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

    const EPSILON: f32 = 1e-6;

    fn assert_approx_eq(a: f32, b: f32) {
        assert!((a - b).abs() < EPSILON, "Expected {} ≈ {}", a, b);
    }

    #[test]
    fn test_l2_distance_identical() {
        let a = [1.0, 2.0, 3.0, 4.0];
        assert_approx_eq(l2_distance(&a, &a), 0.0);
    }

    #[test]
    fn test_l2_distance_orthogonal() {
        let a = [1.0, 0.0, 0.0, 0.0];
        let b = [0.0, 1.0, 0.0, 0.0];
        assert_approx_eq(l2_distance(&a, &b), std::f32::consts::SQRT_2);
    }

    #[test]
    fn test_l2_distance_known_value() {
        let a = [0.0, 0.0, 0.0];
        let b = [3.0, 4.0, 0.0];
        assert_approx_eq(l2_distance(&a, &b), 5.0); // 3-4-5 triangle
    }

    #[test]
    fn test_inner_product_orthogonal() {
        let a = [1.0, 0.0, 0.0];
        let b = [0.0, 1.0, 0.0];
        assert_approx_eq(inner_product(&a, &b), 0.0);
    }

    #[test]
    fn test_inner_product_parallel() {
        let a = [1.0, 2.0, 3.0];
        let b = [2.0, 4.0, 6.0];
        assert_approx_eq(inner_product(&a, &b), 28.0); // 2 + 8 + 18
    }

    #[test]
    fn test_inner_product_known_value() {
        let a = [1.0, 2.0, 3.0, 4.0];
        let b = [4.0, 3.0, 2.0, 1.0];
        assert_approx_eq(inner_product(&a, &b), 20.0); // 4 + 6 + 6 + 4
    }

    #[test]
    fn test_cosine_identical() {
        let a = [1.0, 2.0, 3.0];
        assert_approx_eq(cosine_similarity(&a, &a), 1.0);
    }

    #[test]
    fn test_cosine_orthogonal() {
        let a = [1.0, 0.0];
        let b = [0.0, 1.0];
        assert_approx_eq(cosine_similarity(&a, &b), 0.0);
    }

    #[test]
    fn test_cosine_opposite() {
        let a = [1.0, 0.0];
        let b = [-1.0, 0.0];
        assert_approx_eq(cosine_similarity(&a, &b), -1.0);
    }

    #[test]
    fn test_cosine_zero_vector() {
        let a = [0.0, 0.0, 0.0];
        let b = [1.0, 2.0, 3.0];
        assert_approx_eq(cosine_similarity(&a, &b), 0.0);
    }

    #[test]
    fn test_cosine_distance() {
        let a = [1.0, 0.0];
        let b = [1.0, 0.0];
        assert_approx_eq(cosine_distance(&a, &b), 0.0);

        let c = [1.0, 0.0];
        let d = [-1.0, 0.0];
        assert_approx_eq(cosine_distance(&c, &d), 2.0);
    }

    #[test]
    fn test_norm() {
        let a = [3.0, 4.0];
        assert_approx_eq(norm(&a), 5.0);

        let b = [0.0, 0.0, 0.0];
        assert_approx_eq(norm(&b), 0.0);
    }

    #[test]
    fn test_normalize() {
        let a = [3.0, 4.0];
        let n = normalize(&a);
        assert_approx_eq(n[0], 0.6);
        assert_approx_eq(n[1], 0.8);
        assert_approx_eq(norm(&n), 1.0);
    }

    #[test]
    fn test_normalize_zero_vector() {
        let a = [0.0, 0.0];
        let n = normalize(&a);
        assert_approx_eq(n[0], 0.0);
        assert_approx_eq(n[1], 0.0);
    }

    #[test]
    fn test_normalize_in_place() {
        let mut a = [3.0, 4.0];
        let original_norm = normalize_in_place(&mut a);
        assert_approx_eq(original_norm, 5.0);
        assert_approx_eq(a[0], 0.6);
        assert_approx_eq(a[1], 0.8);
    }

    #[test]
    fn test_symmetry() {
        let a = [1.0, 2.0, 3.0, 4.0];
        let b = [5.0, 6.0, 7.0, 8.0];

        assert_approx_eq(l2_distance(&a, &b), l2_distance(&b, &a));
        assert_approx_eq(inner_product(&a, &b), inner_product(&b, &a));
        assert_approx_eq(cosine_similarity(&a, &b), cosine_similarity(&b, &a));
    }

    #[test]
    fn test_high_dimension() {
        let dim = 512;
        let a: Vec<f32> = (0..dim).map(|i| i as f32 * 0.01).collect();
        let b: Vec<f32> = (0..dim).map(|i| (dim - i) as f32 * 0.01).collect();

        // Just verify no panics and reasonable values
        let l2 = l2_distance(&a, &b);
        let ip = inner_product(&a, &b);
        let cos = cosine_similarity(&a, &b);

        assert!(l2.is_finite());
        assert!(ip.is_finite());
        assert!(cos.is_finite());
        assert!(cos >= -1.0 && cos <= 1.0);
    }
}