oxirag 0.1.1

A four-layer RAG engine with SMT-based logic verification and knowledge graph support
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
//! SIMD-accelerated similarity computations for vector operations.
//!
//! Provides high-performance similarity metrics using explicit SIMD instructions
//! for ARM NEON and x86 AVX/SSE architectures.

// Allow unsafe code in unsafe functions for Rust 2024 edition SIMD operations
#![allow(unsafe_op_in_unsafe_fn)]
// Allow similar names for mathematical variables (norm_a, norm_b, etc.)
#![allow(clippy::similar_names)]

#[cfg(target_arch = "aarch64")]
#[allow(clippy::wildcard_imports)]
use std::arch::aarch64::*;

#[cfg(target_arch = "x86_64")]
#[allow(clippy::wildcard_imports)]
use std::arch::x86_64::*;

/// SIMD-optimized cosine similarity for f32 vectors.
///
/// Uses NEON on ARM64 or AVX/SSE on `x86_64` for 4-8x speedup over scalar code.
///
/// # Safety
/// This function uses unsafe SIMD intrinsics but is safe to call as it:
/// - Only reads within vector bounds
/// - Handles remainder elements with scalar code
/// - Uses platform-specific intrinsics guarded by `target_arch`
#[inline]
#[must_use]
pub fn cosine_similarity_simd(a: &[f32], b: &[f32]) -> f32 {
    debug_assert_eq!(a.len(), b.len(), "Vectors must have the same length");

    #[cfg(target_arch = "aarch64")]
    {
        unsafe { cosine_similarity_neon(a, b) }
    }

    #[cfg(all(target_arch = "x86_64", target_feature = "avx"))]
    {
        unsafe { cosine_similarity_avx(a, b) }
    }

    #[cfg(all(
        target_arch = "x86_64",
        not(target_feature = "avx"),
        target_feature = "sse2"
    ))]
    {
        unsafe { cosine_similarity_sse(a, b) }
    }

    #[cfg(not(any(
        target_arch = "aarch64",
        all(target_arch = "x86_64", target_feature = "sse2")
    )))]
    {
        // Fallback to scalar implementation
        super::similarity::cosine_similarity(a, b)
    }
}

/// SIMD-optimized dot product for f32 vectors.
#[inline]
#[must_use]
pub fn dot_product_simd(a: &[f32], b: &[f32]) -> f32 {
    debug_assert_eq!(a.len(), b.len(), "Vectors must have the same length");

    #[cfg(target_arch = "aarch64")]
    {
        unsafe { dot_product_neon(a, b) }
    }

    #[cfg(all(target_arch = "x86_64", target_feature = "avx"))]
    {
        unsafe { dot_product_avx(a, b) }
    }

    #[cfg(all(
        target_arch = "x86_64",
        not(target_feature = "avx"),
        target_feature = "sse2"
    ))]
    {
        unsafe { dot_product_sse(a, b) }
    }

    #[cfg(not(any(
        target_arch = "aarch64",
        all(target_arch = "x86_64", target_feature = "sse2")
    )))]
    {
        super::similarity::dot_product(a, b)
    }
}

/// SIMD-optimized vector normalization.
#[inline]
#[must_use]
pub fn normalize_simd(v: &[f32]) -> Vec<f32> {
    let norm_squared = dot_product_simd(v, v);
    let norm = norm_squared.sqrt();

    if norm < 1e-10 {
        return v.to_vec();
    }

    let inv_norm = 1.0 / norm;
    let mut result = vec![0.0f32; v.len()];

    #[cfg(target_arch = "aarch64")]
    {
        unsafe {
            multiply_scalar_neon(v, inv_norm, &mut result);
        }
    }

    #[cfg(all(target_arch = "x86_64", target_feature = "avx"))]
    {
        unsafe {
            multiply_scalar_avx(v, inv_norm, &mut result);
        }
    }

    #[cfg(all(
        target_arch = "x86_64",
        not(target_feature = "avx"),
        target_feature = "sse2"
    ))]
    {
        unsafe {
            multiply_scalar_sse(v, inv_norm, &mut result);
        }
    }

    #[cfg(not(any(
        target_arch = "aarch64",
        all(target_arch = "x86_64", target_feature = "sse2")
    )))]
    {
        for (i, &val) in v.iter().enumerate() {
            result[i] = val * inv_norm;
        }
    }

    result
}

// ============================================================================
// ARM NEON implementations (Apple Silicon, ARM servers)
// ============================================================================

#[cfg(target_arch = "aarch64")]
#[inline]
unsafe fn cosine_similarity_neon(a: &[f32], b: &[f32]) -> f32 {
    let len = a.len();
    let mut dot_acc = vdupq_n_f32(0.0);
    let mut norm_a_acc = vdupq_n_f32(0.0);
    let mut norm_b_acc = vdupq_n_f32(0.0);

    let chunks = len / 4;
    let remainder = len % 4;

    // Process 4 elements at a time with NEON
    for i in 0..chunks {
        let idx = i * 4;
        let va = vld1q_f32(a.as_ptr().add(idx));
        let vb = vld1q_f32(b.as_ptr().add(idx));

        // Dot product: a[i] * b[i]
        dot_acc = vfmaq_f32(dot_acc, va, vb);

        // Norm of a: a[i] * a[i]
        norm_a_acc = vfmaq_f32(norm_a_acc, va, va);

        // Norm of b: b[i] * b[i]
        norm_b_acc = vfmaq_f32(norm_b_acc, vb, vb);
    }

    // Horizontal sum
    let mut dot_sum = vaddvq_f32(dot_acc);
    let mut norm_a_sum = vaddvq_f32(norm_a_acc);
    let mut norm_b_sum = vaddvq_f32(norm_b_acc);

    // Handle remainder elements
    let offset = chunks * 4;
    for i in 0..remainder {
        let ai = a[offset + i];
        let bi = b[offset + i];
        dot_sum += ai * bi;
        norm_a_sum += ai * ai;
        norm_b_sum += bi * bi;
    }

    if norm_a_sum == 0.0 || norm_b_sum == 0.0 {
        return 0.0;
    }

    dot_sum / (norm_a_sum.sqrt() * norm_b_sum.sqrt())
}

#[cfg(target_arch = "aarch64")]
#[inline]
unsafe fn dot_product_neon(a: &[f32], b: &[f32]) -> f32 {
    let len = a.len();
    let mut acc = vdupq_n_f32(0.0);

    let chunks = len / 4;
    let remainder = len % 4;

    for i in 0..chunks {
        let idx = i * 4;
        let va = vld1q_f32(a.as_ptr().add(idx));
        let vb = vld1q_f32(b.as_ptr().add(idx));
        acc = vfmaq_f32(acc, va, vb);
    }

    let mut sum = vaddvq_f32(acc);

    // Handle remainder
    let offset = chunks * 4;
    for i in 0..remainder {
        sum += a[offset + i] * b[offset + i];
    }

    sum
}

#[cfg(target_arch = "aarch64")]
#[inline]
unsafe fn multiply_scalar_neon(v: &[f32], scalar: f32, result: &mut [f32]) {
    let len = v.len();
    let scalar_vec = vdupq_n_f32(scalar);

    let chunks = len / 4;
    let remainder = len % 4;

    for i in 0..chunks {
        let idx = i * 4;
        let vv = vld1q_f32(v.as_ptr().add(idx));
        let res = vmulq_f32(vv, scalar_vec);
        vst1q_f32(result.as_mut_ptr().add(idx), res);
    }

    // Handle remainder
    let offset = chunks * 4;
    for i in 0..remainder {
        result[offset + i] = v[offset + i] * scalar;
    }
}

// ============================================================================
// x86_64 AVX implementations
// ============================================================================

#[cfg(all(target_arch = "x86_64", target_feature = "avx"))]
#[inline]
unsafe fn cosine_similarity_avx(a: &[f32], b: &[f32]) -> f32 {
    let len = a.len();
    let mut dot_acc = _mm256_setzero_ps();
    let mut norm_a_acc = _mm256_setzero_ps();
    let mut norm_b_acc = _mm256_setzero_ps();

    let chunks = len / 8;
    let remainder = len % 8;

    for i in 0..chunks {
        let idx = i * 8;
        let va = _mm256_loadu_ps(a.as_ptr().add(idx));
        let vb = _mm256_loadu_ps(b.as_ptr().add(idx));

        dot_acc = _mm256_fmadd_ps(va, vb, dot_acc);
        norm_a_acc = _mm256_fmadd_ps(va, va, norm_a_acc);
        norm_b_acc = _mm256_fmadd_ps(vb, vb, norm_b_acc);
    }

    // Horizontal sum for AVX
    let mut dot_sum = horizontal_sum_avx(dot_acc);
    let mut norm_a_sum = horizontal_sum_avx(norm_a_acc);
    let mut norm_b_sum = horizontal_sum_avx(norm_b_acc);

    // Handle remainder
    let offset = chunks * 8;
    for i in 0..remainder {
        let ai = a[offset + i];
        let bi = b[offset + i];
        dot_sum += ai * bi;
        norm_a_sum += ai * ai;
        norm_b_sum += bi * bi;
    }

    if norm_a_sum == 0.0 || norm_b_sum == 0.0 {
        return 0.0;
    }

    dot_sum / (norm_a_sum.sqrt() * norm_b_sum.sqrt())
}

#[cfg(all(target_arch = "x86_64", target_feature = "avx"))]
#[inline]
unsafe fn dot_product_avx(a: &[f32], b: &[f32]) -> f32 {
    let len = a.len();
    let mut acc = _mm256_setzero_ps();

    let chunks = len / 8;
    let remainder = len % 8;

    for i in 0..chunks {
        let idx = i * 8;
        let va = _mm256_loadu_ps(a.as_ptr().add(idx));
        let vb = _mm256_loadu_ps(b.as_ptr().add(idx));
        acc = _mm256_fmadd_ps(va, vb, acc);
    }

    let mut sum = horizontal_sum_avx(acc);

    let offset = chunks * 8;
    for i in 0..remainder {
        sum += a[offset + i] * b[offset + i];
    }

    sum
}

#[cfg(all(target_arch = "x86_64", target_feature = "avx"))]
#[inline]
unsafe fn multiply_scalar_avx(v: &[f32], scalar: f32, result: &mut [f32]) {
    let len = v.len();
    let scalar_vec = _mm256_set1_ps(scalar);

    let chunks = len / 8;
    let remainder = len % 8;

    for i in 0..chunks {
        let idx = i * 8;
        let vv = _mm256_loadu_ps(v.as_ptr().add(idx));
        let res = _mm256_mul_ps(vv, scalar_vec);
        _mm256_storeu_ps(result.as_mut_ptr().add(idx), res);
    }

    let offset = chunks * 8;
    for i in 0..remainder {
        result[offset + i] = v[offset + i] * scalar;
    }
}

#[cfg(all(target_arch = "x86_64", target_feature = "avx"))]
#[inline]
unsafe fn horizontal_sum_avx(v: __m256) -> f32 {
    let hi = _mm256_extractf128_ps(v, 1);
    let lo = _mm256_castps256_ps128(v);
    let sum128 = _mm_add_ps(hi, lo);

    let shuf = _mm_movehdup_ps(sum128);
    let sums = _mm_add_ps(sum128, shuf);
    let shuf2 = _mm_movehl_ps(shuf, sums);
    let result = _mm_add_ss(sums, shuf2);

    _mm_cvtss_f32(result)
}

// ============================================================================
// x86_64 SSE implementations (fallback for older CPUs)
// ============================================================================

#[cfg(all(target_arch = "x86_64", target_feature = "sse2"))]
#[inline]
unsafe fn cosine_similarity_sse(a: &[f32], b: &[f32]) -> f32 {
    let len = a.len();
    let mut dot_acc = _mm_setzero_ps();
    let mut norm_a_acc = _mm_setzero_ps();
    let mut norm_b_acc = _mm_setzero_ps();

    let chunks = len / 4;
    let remainder = len % 4;

    for i in 0..chunks {
        let idx = i * 4;
        let va = _mm_loadu_ps(a.as_ptr().add(idx));
        let vb = _mm_loadu_ps(b.as_ptr().add(idx));

        dot_acc = _mm_add_ps(dot_acc, _mm_mul_ps(va, vb));
        norm_a_acc = _mm_add_ps(norm_a_acc, _mm_mul_ps(va, va));
        norm_b_acc = _mm_add_ps(norm_b_acc, _mm_mul_ps(vb, vb));
    }

    let mut dot_sum = horizontal_sum_sse(dot_acc);
    let mut norm_a_sum = horizontal_sum_sse(norm_a_acc);
    let mut norm_b_sum = horizontal_sum_sse(norm_b_acc);

    let offset = chunks * 4;
    for i in 0..remainder {
        let ai = a[offset + i];
        let bi = b[offset + i];
        dot_sum += ai * bi;
        norm_a_sum += ai * ai;
        norm_b_sum += bi * bi;
    }

    if norm_a_sum == 0.0 || norm_b_sum == 0.0 {
        return 0.0;
    }

    dot_sum / (norm_a_sum.sqrt() * norm_b_sum.sqrt())
}

#[cfg(all(target_arch = "x86_64", target_feature = "sse2"))]
#[inline]
unsafe fn dot_product_sse(a: &[f32], b: &[f32]) -> f32 {
    let len = a.len();
    let mut acc = _mm_setzero_ps();

    let chunks = len / 4;
    let remainder = len % 4;

    for i in 0..chunks {
        let idx = i * 4;
        let va = _mm_loadu_ps(a.as_ptr().add(idx));
        let vb = _mm_loadu_ps(b.as_ptr().add(idx));
        acc = _mm_add_ps(acc, _mm_mul_ps(va, vb));
    }

    let mut sum = horizontal_sum_sse(acc);

    let offset = chunks * 4;
    for i in 0..remainder {
        sum += a[offset + i] * b[offset + i];
    }

    sum
}

#[cfg(all(target_arch = "x86_64", target_feature = "sse2"))]
#[inline]
unsafe fn multiply_scalar_sse(v: &[f32], scalar: f32, result: &mut [f32]) {
    let len = v.len();
    let scalar_vec = _mm_set1_ps(scalar);

    let chunks = len / 4;
    let remainder = len % 4;

    for i in 0..chunks {
        let idx = i * 4;
        let vv = _mm_loadu_ps(v.as_ptr().add(idx));
        let res = _mm_mul_ps(vv, scalar_vec);
        _mm_storeu_ps(result.as_mut_ptr().add(idx), res);
    }

    let offset = chunks * 4;
    for i in 0..remainder {
        result[offset + i] = v[offset + i] * scalar;
    }
}

#[cfg(all(target_arch = "x86_64", target_feature = "sse2"))]
#[inline]
unsafe fn horizontal_sum_sse(v: __m128) -> f32 {
    let shuf = _mm_movehdup_ps(v);
    let sums = _mm_add_ps(v, shuf);
    let shuf2 = _mm_movehl_ps(shuf, sums);
    let result = _mm_add_ss(sums, shuf2);
    _mm_cvtss_f32(result)
}

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

    #[test]
    fn test_simd_cosine_similarity() {
        let a = vec![1.0, 2.0, 3.0, 4.0];
        let b = vec![1.0, 2.0, 3.0, 4.0];

        let sim = cosine_similarity_simd(&a, &b);
        assert!((sim - 1.0).abs() < 1e-6);
    }

    #[test]
    fn test_simd_dot_product() {
        let a = vec![1.0, 2.0, 3.0, 4.0];
        let b = vec![4.0, 3.0, 2.0, 1.0];

        let dot = dot_product_simd(&a, &b);
        assert!((dot - 20.0).abs() < 1e-6);
    }

    #[test]
    fn test_simd_normalize() {
        let v = vec![3.0, 4.0, 0.0, 0.0];
        let normalized = normalize_simd(&v);

        let norm: f32 = normalized.iter().map(|x| x * x).sum::<f32>().sqrt();
        assert!((norm - 1.0).abs() < 1e-5);
    }

    #[test]
    #[allow(clippy::cast_precision_loss)] // Intentional for test data generation
    fn test_simd_matches_scalar() {
        let a: Vec<f32> = (0..128).map(|i| (i as f32 * 0.1).sin()).collect();
        let b: Vec<f32> = (0..128).map(|i| (i as f32 * 0.15).cos()).collect();

        let simd_cos = cosine_similarity_simd(&a, &b);
        let scalar_cos = super::super::similarity::cosine_similarity(&a, &b);

        assert!(
            (simd_cos - scalar_cos).abs() < 1e-5,
            "SIMD: {simd_cos}, Scalar: {scalar_cos}"
        );
    }
}