vxdb-server 0.5.0__tar.gz → 0.6.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. {vxdb_server-0.5.0 → vxdb_server-0.6.0}/Cargo.lock +3 -3
  2. {vxdb_server-0.5.0 → vxdb_server-0.6.0}/Cargo.toml +1 -1
  3. {vxdb_server-0.5.0 → vxdb_server-0.6.0}/PKG-INFO +1 -1
  4. {vxdb_server-0.5.0 → vxdb_server-0.6.0}/crates/vxdb-core/Cargo.toml +1 -2
  5. {vxdb_server-0.5.0 → vxdb_server-0.6.0}/crates/vxdb-core/src/distance/cosine.rs +62 -8
  6. {vxdb_server-0.5.0 → vxdb_server-0.6.0}/crates/vxdb-core/src/distance/dot.rs +54 -8
  7. {vxdb_server-0.5.0 → vxdb_server-0.6.0}/crates/vxdb-core/src/distance/euclidean.rs +56 -8
  8. vxdb_server-0.6.0/crates/vxdb-core/src/distance/mod.rs +102 -0
  9. vxdb_server-0.6.0/crates/vxdb-core/src/distance/simd.rs +238 -0
  10. {vxdb_server-0.5.0 → vxdb_server-0.6.0}/crates/vxdb-core/src/storage/mmap.rs +4 -2
  11. vxdb_server-0.5.0/crates/vxdb-core/src/distance/mod.rs +0 -49
  12. {vxdb_server-0.5.0 → vxdb_server-0.6.0}/README.md +0 -0
  13. {vxdb_server-0.5.0 → vxdb_server-0.6.0}/crates/vxdb-core/src/collection.rs +0 -0
  14. {vxdb_server-0.5.0 → vxdb_server-0.6.0}/crates/vxdb-core/src/error.rs +0 -0
  15. {vxdb_server-0.5.0 → vxdb_server-0.6.0}/crates/vxdb-core/src/filter.rs +0 -0
  16. {vxdb_server-0.5.0 → vxdb_server-0.6.0}/crates/vxdb-core/src/hybrid.rs +0 -0
  17. {vxdb_server-0.5.0 → vxdb_server-0.6.0}/crates/vxdb-core/src/index/flat.rs +0 -0
  18. {vxdb_server-0.5.0 → vxdb_server-0.6.0}/crates/vxdb-core/src/index/hnsw.rs +0 -0
  19. {vxdb_server-0.5.0 → vxdb_server-0.6.0}/crates/vxdb-core/src/index/mod.rs +0 -0
  20. {vxdb_server-0.5.0 → vxdb_server-0.6.0}/crates/vxdb-core/src/lib.rs +0 -0
  21. {vxdb_server-0.5.0 → vxdb_server-0.6.0}/crates/vxdb-core/src/storage/metadata.rs +0 -0
  22. {vxdb_server-0.5.0 → vxdb_server-0.6.0}/crates/vxdb-core/src/storage/mod.rs +0 -0
  23. {vxdb_server-0.5.0 → vxdb_server-0.6.0}/crates/vxdb-core/src/storage/persistent.rs +0 -0
  24. {vxdb_server-0.5.0 → vxdb_server-0.6.0}/crates/vxdb-core/src/storage/wal.rs +0 -0
  25. {vxdb_server-0.5.0 → vxdb_server-0.6.0}/crates/vxdb-core/src/types.rs +0 -0
  26. {vxdb_server-0.5.0 → vxdb_server-0.6.0}/crates/vxdb-server/Cargo.toml +0 -0
  27. {vxdb_server-0.5.0 → vxdb_server-0.6.0}/crates/vxdb-server/README.md +0 -0
  28. {vxdb_server-0.5.0 → vxdb_server-0.6.0}/crates/vxdb-server/src/config.rs +0 -0
  29. {vxdb_server-0.5.0 → vxdb_server-0.6.0}/crates/vxdb-server/src/main.rs +0 -0
  30. {vxdb_server-0.5.0 → vxdb_server-0.6.0}/crates/vxdb-server/src/routes.rs +0 -0
  31. {vxdb_server-0.5.0 → vxdb_server-0.6.0}/pyproject.toml +0 -0
@@ -1837,7 +1837,7 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
1837
1837
 
1838
1838
  [[package]]
1839
1839
  name = "vxdb-core"
1840
- version = "0.5.0"
1840
+ version = "0.6.0"
1841
1841
  dependencies = [
1842
1842
  "memmap2",
1843
1843
  "parking_lot",
@@ -1851,7 +1851,7 @@ dependencies = [
1851
1851
 
1852
1852
  [[package]]
1853
1853
  name = "vxdb-python"
1854
- version = "0.5.0"
1854
+ version = "0.6.0"
1855
1855
  dependencies = [
1856
1856
  "pyo3",
1857
1857
  "serde_json",
@@ -1860,7 +1860,7 @@ dependencies = [
1860
1860
 
1861
1861
  [[package]]
1862
1862
  name = "vxdb-server"
1863
- version = "0.5.0"
1863
+ version = "0.6.0"
1864
1864
  dependencies = [
1865
1865
  "axum",
1866
1866
  "clap",
@@ -3,6 +3,6 @@ resolver = "2"
3
3
  members = ["crates/vxdb-core", "crates/vxdb-server"]
4
4
 
5
5
  [workspace.package]
6
- version = "0.5.0"
6
+ version = "0.6.0"
7
7
  edition = "2021"
8
8
  license = "Apache-2.0"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: vxdb-server
3
- Version: 0.5.0
3
+ Version: 0.6.0
4
4
  Classifier: Development Status :: 4 - Beta
5
5
  Classifier: Intended Audience :: Developers
6
6
  Classifier: License :: OSI Approved :: Apache Software License
@@ -3,11 +3,10 @@ name = "vxdb-core"
3
3
  version.workspace = true
4
4
  edition.workspace = true
5
5
  license.workspace = true
6
- description = "Core engine for vxdb — a lightweight, high-performance vector store"
6
+ description = "Core engine for vxdb, a lightweight, high-performance vector database"
7
7
 
8
8
  [features]
9
9
  default = []
10
- simd = []
11
10
 
12
11
  [dependencies]
13
12
  serde = { version = "1", features = ["derive"] }
@@ -1,19 +1,37 @@
1
1
  use super::DistanceMetric;
2
2
 
3
3
  /// Cosine distance (1 - cosine similarity). Free function shared by the trait
4
- /// impl and the monomorphized `Metric` enum. Multiple accumulators let LLVM
5
- /// auto-vectorize the three reductions (see `euclidean` for the rationale).
4
+ /// impl and the monomorphized `Metric` enum. Dispatches to a SIMD kernel when
5
+ /// the CPU supports one; `cosine_scalar` is the reference and the fallback.
6
6
  #[inline]
7
7
  pub(crate) fn cosine(a: &[f32], b: &[f32]) -> f32 {
8
+ #[cfg(target_arch = "aarch64")]
9
+ {
10
+ // SAFETY: NEON is baseline on every Rust aarch64 std target.
11
+ return unsafe { super::simd::neon::cosine(a, b) };
12
+ }
13
+ #[cfg(target_arch = "x86_64")]
14
+ {
15
+ if super::simd::avx2_available() {
16
+ // SAFETY: AVX2 and FMA support verified at runtime just above.
17
+ return unsafe { super::simd::avx2::cosine(a, b) };
18
+ }
19
+ }
20
+ #[allow(unreachable_code)]
21
+ cosine_scalar(a, b)
22
+ }
23
+
24
+ /// Scalar reference. Multiple accumulators let LLVM auto-vectorize the three
25
+ /// reductions (see `euclidean` for the rationale).
26
+ #[inline]
27
+ pub(crate) fn cosine_scalar(a: &[f32], b: &[f32]) -> f32 {
8
28
  const LANES: usize = 8;
9
29
  let mut adot = [0.0f32; LANES];
10
30
  let mut anorm_a = [0.0f32; LANES];
11
31
  let mut anorm_b = [0.0f32; LANES];
12
- let mut ca = a.chunks_exact(LANES);
13
- let mut cb = b.chunks_exact(LANES);
14
- for (x, y) in ca.by_ref().zip(cb.by_ref()) {
15
- let x: &[f32; LANES] = x.try_into().unwrap();
16
- let y: &[f32; LANES] = y.try_into().unwrap();
32
+ let (ca, ra) = a.as_chunks::<LANES>();
33
+ let (cb, rb) = b.as_chunks::<LANES>();
34
+ for (x, y) in ca.iter().zip(cb) {
17
35
  for j in 0..LANES {
18
36
  adot[j] += x[j] * y[j];
19
37
  anorm_a[j] += x[j] * x[j];
@@ -23,7 +41,7 @@ pub(crate) fn cosine(a: &[f32], b: &[f32]) -> f32 {
23
41
  let mut dot: f32 = adot.iter().sum();
24
42
  let mut norm_a: f32 = anorm_a.iter().sum();
25
43
  let mut norm_b: f32 = anorm_b.iter().sum();
26
- for (x, y) in ca.remainder().iter().zip(cb.remainder()) {
44
+ for (x, y) in ra.iter().zip(rb) {
27
45
  dot += x * y;
28
46
  norm_a += x * x;
29
47
  norm_b += y * y;
@@ -114,4 +132,40 @@ mod tests {
114
132
  let d2 = d.distance(&[2.0, 4.0], &[6.0, 8.0]);
115
133
  assert!((d1 - d2).abs() < EPS);
116
134
  }
135
+
136
+ #[test]
137
+ fn test_dispatch_matches_scalar_across_dims() {
138
+ use rand::rngs::StdRng;
139
+ use rand::{Rng, SeedableRng};
140
+ let mut rng = StdRng::seed_from_u64(103);
141
+ for dim in [
142
+ 0usize, 1, 3, 4, 7, 8, 15, 16, 17, 31, 32, 33, 100, 384, 768, 769, 1536,
143
+ ] {
144
+ let a: Vec<f32> = (0..dim).map(|_| rng.gen_range(-1.0f32..1.0)).collect();
145
+ let b: Vec<f32> = (0..dim).map(|_| rng.gen_range(-1.0f32..1.0)).collect();
146
+ let got = cosine(&a, &b);
147
+ let scalar = cosine_scalar(&a, &b);
148
+ if dim == 0 {
149
+ assert_eq!(got, 1.0, "empty vectors must hit the zero-denominator path");
150
+ assert_eq!(scalar, 1.0);
151
+ continue;
152
+ }
153
+ let dot: f64 = a
154
+ .iter()
155
+ .zip(&b)
156
+ .map(|(x, y)| (*x as f64) * (*y as f64))
157
+ .sum();
158
+ let na: f64 = a.iter().map(|x| (*x as f64).powi(2)).sum::<f64>().sqrt();
159
+ let nb: f64 = b.iter().map(|x| (*x as f64).powi(2)).sum::<f64>().sqrt();
160
+ let naive = (1.0 - dot / (na * nb)) as f32;
161
+ assert!(
162
+ (got - naive).abs() <= 1e-3,
163
+ "dim={dim}: dispatch {got} vs f64 naive {naive}"
164
+ );
165
+ assert!(
166
+ (scalar - naive).abs() <= 1e-3,
167
+ "dim={dim}: scalar {scalar} vs f64 naive {naive}"
168
+ );
169
+ }
170
+ }
117
171
  }
@@ -1,23 +1,41 @@
1
1
  use super::DistanceMetric;
2
2
 
3
3
  /// Negative dot product (so lower = more similar). Free function shared by the
4
- /// trait impl and the monomorphized `Metric` enum. Multiple accumulators let
5
- /// LLVM auto-vectorize the reduction (see `euclidean` for the rationale).
4
+ /// trait impl and the monomorphized `Metric` enum. Dispatches to a SIMD kernel
5
+ /// when the CPU supports one; `dot_scalar` is the reference and the fallback.
6
6
  #[inline]
7
7
  pub(crate) fn dot(a: &[f32], b: &[f32]) -> f32 {
8
+ #[cfg(target_arch = "aarch64")]
9
+ {
10
+ // SAFETY: NEON is baseline on every Rust aarch64 std target.
11
+ return unsafe { super::simd::neon::dot(a, b) };
12
+ }
13
+ #[cfg(target_arch = "x86_64")]
14
+ {
15
+ if super::simd::avx2_available() {
16
+ // SAFETY: AVX2 and FMA support verified at runtime just above.
17
+ return unsafe { super::simd::avx2::dot(a, b) };
18
+ }
19
+ }
20
+ #[allow(unreachable_code)]
21
+ dot_scalar(a, b)
22
+ }
23
+
24
+ /// Scalar reference. Multiple accumulators let LLVM auto-vectorize the
25
+ /// reduction (see `euclidean` for the rationale).
26
+ #[inline]
27
+ pub(crate) fn dot_scalar(a: &[f32], b: &[f32]) -> f32 {
8
28
  const LANES: usize = 8;
9
29
  let mut acc = [0.0f32; LANES];
10
- let mut ca = a.chunks_exact(LANES);
11
- let mut cb = b.chunks_exact(LANES);
12
- for (x, y) in ca.by_ref().zip(cb.by_ref()) {
13
- let x: &[f32; LANES] = x.try_into().unwrap();
14
- let y: &[f32; LANES] = y.try_into().unwrap();
30
+ let (ca, ra) = a.as_chunks::<LANES>();
31
+ let (cb, rb) = b.as_chunks::<LANES>();
32
+ for (x, y) in ca.iter().zip(cb) {
15
33
  for j in 0..LANES {
16
34
  acc[j] += x[j] * y[j];
17
35
  }
18
36
  }
19
37
  let mut sum: f32 = acc.iter().sum();
20
- for (x, y) in ca.remainder().iter().zip(cb.remainder()) {
38
+ for (x, y) in ra.iter().zip(rb) {
21
39
  sum += x * y;
22
40
  }
23
41
  -sum
@@ -98,4 +116,32 @@ mod tests {
98
116
  let d2 = d.distance(&[4.0, 5.0, 6.0], &[1.0, 2.0, 3.0]);
99
117
  assert!((d1 - d2).abs() < EPS);
100
118
  }
119
+
120
+ #[test]
121
+ fn test_dispatch_matches_scalar_across_dims() {
122
+ use rand::rngs::StdRng;
123
+ use rand::{Rng, SeedableRng};
124
+ let mut rng = StdRng::seed_from_u64(101);
125
+ for dim in [
126
+ 0usize, 1, 3, 4, 7, 8, 15, 16, 17, 31, 32, 33, 100, 384, 768, 769, 1536,
127
+ ] {
128
+ let a: Vec<f32> = (0..dim).map(|_| rng.gen_range(-1.0f32..1.0)).collect();
129
+ let b: Vec<f32> = (0..dim).map(|_| rng.gen_range(-1.0f32..1.0)).collect();
130
+ let got = dot(&a, &b);
131
+ let scalar = dot_scalar(&a, &b);
132
+ let naive = -(a
133
+ .iter()
134
+ .zip(&b)
135
+ .map(|(x, y)| (*x as f64) * (*y as f64))
136
+ .sum::<f64>()) as f32;
137
+ assert!(
138
+ (got - naive).abs() <= 1e-3 * naive.abs().max(1.0),
139
+ "dim={dim}: dispatch {got} vs f64 naive {naive}"
140
+ );
141
+ assert!(
142
+ (scalar - naive).abs() <= 1e-3 * naive.abs().max(1.0),
143
+ "dim={dim}: scalar {scalar} vs f64 naive {naive}"
144
+ );
145
+ }
146
+ }
101
147
  }
@@ -1,7 +1,28 @@
1
1
  use super::DistanceMetric;
2
2
 
3
3
  /// L2 distance. Free function so both the `DistanceMetric` trait impl and the
4
- /// monomorphized `Metric` enum share one `#[inline]` code path.
4
+ /// monomorphized `Metric` enum share one `#[inline]` code path. Dispatches to
5
+ /// a SIMD kernel when the CPU supports one; `euclidean_scalar` is the
6
+ /// reference and the fallback.
7
+ #[inline]
8
+ pub(crate) fn euclidean(a: &[f32], b: &[f32]) -> f32 {
9
+ #[cfg(target_arch = "aarch64")]
10
+ {
11
+ // SAFETY: NEON is baseline on every Rust aarch64 std target.
12
+ return unsafe { super::simd::neon::euclidean(a, b) };
13
+ }
14
+ #[cfg(target_arch = "x86_64")]
15
+ {
16
+ if super::simd::avx2_available() {
17
+ // SAFETY: AVX2 and FMA support verified at runtime just above.
18
+ return unsafe { super::simd::avx2::euclidean(a, b) };
19
+ }
20
+ }
21
+ #[allow(unreachable_code)]
22
+ euclidean_scalar(a, b)
23
+ }
24
+
25
+ /// Scalar reference.
5
26
  ///
6
27
  /// Uses `LANES` independent accumulators so LLVM can auto-vectorize the
7
28
  /// reduction (NEON/SSE are baseline on arm64/x86-64) — a single running sum
@@ -9,21 +30,19 @@ use super::DistanceMetric;
9
30
  /// `unsafe`, no intrinsics. Vectors shorter than `LANES` fall to the scalar
10
31
  /// remainder and match the naive result exactly.
11
32
  #[inline]
12
- pub(crate) fn euclidean(a: &[f32], b: &[f32]) -> f32 {
33
+ pub(crate) fn euclidean_scalar(a: &[f32], b: &[f32]) -> f32 {
13
34
  const LANES: usize = 8;
14
35
  let mut acc = [0.0f32; LANES];
15
- let mut ca = a.chunks_exact(LANES);
16
- let mut cb = b.chunks_exact(LANES);
17
- for (x, y) in ca.by_ref().zip(cb.by_ref()) {
18
- let x: &[f32; LANES] = x.try_into().unwrap();
19
- let y: &[f32; LANES] = y.try_into().unwrap();
36
+ let (ca, ra) = a.as_chunks::<LANES>();
37
+ let (cb, rb) = b.as_chunks::<LANES>();
38
+ for (x, y) in ca.iter().zip(cb) {
20
39
  for j in 0..LANES {
21
40
  let d = x[j] - y[j];
22
41
  acc[j] += d * d;
23
42
  }
24
43
  }
25
44
  let mut sum: f32 = acc.iter().sum();
26
- for (x, y) in ca.remainder().iter().zip(cb.remainder()) {
45
+ for (x, y) in ra.iter().zip(rb) {
27
46
  let d = x - y;
28
47
  sum += d * d;
29
48
  }
@@ -115,4 +134,33 @@ mod tests {
115
134
  let ac = d.distance(a, c);
116
135
  assert!(ac <= ab + bc + EPS);
117
136
  }
137
+
138
+ #[test]
139
+ fn test_dispatch_matches_scalar_across_dims() {
140
+ use rand::rngs::StdRng;
141
+ use rand::{Rng, SeedableRng};
142
+ let mut rng = StdRng::seed_from_u64(102);
143
+ for dim in [
144
+ 0usize, 1, 3, 4, 7, 8, 15, 16, 17, 31, 32, 33, 100, 384, 768, 769, 1536,
145
+ ] {
146
+ let a: Vec<f32> = (0..dim).map(|_| rng.gen_range(-1.0f32..1.0)).collect();
147
+ let b: Vec<f32> = (0..dim).map(|_| rng.gen_range(-1.0f32..1.0)).collect();
148
+ let got = euclidean(&a, &b);
149
+ let scalar = euclidean_scalar(&a, &b);
150
+ let naive = a
151
+ .iter()
152
+ .zip(&b)
153
+ .map(|(x, y)| ((*x as f64) - (*y as f64)).powi(2))
154
+ .sum::<f64>()
155
+ .sqrt() as f32;
156
+ assert!(
157
+ (got - naive).abs() <= 1e-3 * naive.max(1.0),
158
+ "dim={dim}: dispatch {got} vs f64 naive {naive}"
159
+ );
160
+ assert!(
161
+ (scalar - naive).abs() <= 1e-3 * naive.max(1.0),
162
+ "dim={dim}: scalar {scalar} vs f64 naive {naive}"
163
+ );
164
+ }
165
+ }
118
166
  }
@@ -0,0 +1,102 @@
1
+ mod cosine;
2
+ mod dot;
3
+ mod euclidean;
4
+ mod simd;
5
+
6
+ pub use cosine::CosineDistance;
7
+ pub use dot::DotProductDistance;
8
+ pub use euclidean::EuclideanDistance;
9
+
10
+ use crate::types::DistanceMetricKind;
11
+
12
+ /// All distance functions return a *distance* (lower = more similar).
13
+ /// For cosine: distance = 1 - cosine_similarity
14
+ /// For dot product: distance = -dot_product (negate so lower = higher similarity)
15
+ /// For euclidean: distance = L2 distance
16
+ pub trait DistanceMetric: Send + Sync {
17
+ fn distance(&self, a: &[f32], b: &[f32]) -> f32;
18
+ }
19
+
20
+ /// Monomorphized distance dispatch for the hot path.
21
+ ///
22
+ /// Unlike `Box<dyn DistanceMetric>`, this `Copy` enum lets the compiler inline
23
+ /// `distance` into the index inner loops (a vtable call cannot be inlined),
24
+ /// which in turn lets LLVM auto-vectorize the per-dimension reduction. Same
25
+ /// math as the trait impls — both share the `#[inline]` free functions.
26
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
27
+ pub enum Metric {
28
+ Cosine,
29
+ Euclidean,
30
+ DotProduct,
31
+ }
32
+
33
+ impl Metric {
34
+ #[inline]
35
+ pub fn distance(&self, a: &[f32], b: &[f32]) -> f32 {
36
+ match self {
37
+ Metric::Cosine => cosine::cosine(a, b),
38
+ Metric::Euclidean => euclidean::euclidean(a, b),
39
+ Metric::DotProduct => dot::dot(a, b),
40
+ }
41
+ }
42
+ }
43
+
44
+ pub fn metric_for_kind(kind: DistanceMetricKind) -> Metric {
45
+ match kind {
46
+ DistanceMetricKind::Cosine => Metric::Cosine,
47
+ DistanceMetricKind::Euclidean => Metric::Euclidean,
48
+ DistanceMetricKind::DotProduct => Metric::DotProduct,
49
+ }
50
+ }
51
+
52
+ #[cfg(test)]
53
+ mod tests {
54
+ use super::*;
55
+
56
+ /// Not a correctness test. Run manually:
57
+ /// `cargo test -p vxdb-core --release -- --ignored bench_distance --nocapture`
58
+ #[test]
59
+ #[ignore = "micro-benchmark, run explicitly in release mode"]
60
+ fn bench_distance_throughput() {
61
+ use rand::rngs::StdRng;
62
+ use rand::{Rng, SeedableRng};
63
+ use std::time::Instant;
64
+ const DIM: usize = 768;
65
+ const ROWS: usize = 20_000;
66
+ const REPS: usize = 10;
67
+ let mut rng = StdRng::seed_from_u64(42);
68
+ let data: Vec<f32> = (0..DIM * ROWS)
69
+ .map(|_| rng.gen_range(-1.0f32..1.0))
70
+ .collect();
71
+ let q: Vec<f32> = (0..DIM).map(|_| rng.gen_range(-1.0f32..1.0)).collect();
72
+
73
+ let mut acc = 0.0f32;
74
+ let t = Instant::now();
75
+ for _ in 0..REPS {
76
+ for row in data.chunks_exact(DIM) {
77
+ acc += cosine::cosine_scalar(row, &q);
78
+ }
79
+ }
80
+ let scalar = t.elapsed();
81
+
82
+ let mut acc2 = 0.0f32;
83
+ let t = Instant::now();
84
+ for _ in 0..REPS {
85
+ for row in data.chunks_exact(DIM) {
86
+ acc2 += Metric::Cosine.distance(row, &q);
87
+ }
88
+ }
89
+ let dispatch = t.elapsed();
90
+
91
+ let per = |d: std::time::Duration| d.as_nanos() as f64 / (ROWS * REPS) as f64;
92
+ eprintln!(
93
+ "cosine 768d scalar: {:>8.1} ns/vec (acc={acc})",
94
+ per(scalar)
95
+ );
96
+ eprintln!(
97
+ "cosine 768d dispatch: {:>8.1} ns/vec (acc={acc2})",
98
+ per(dispatch)
99
+ );
100
+ eprintln!("speedup: {:.2}x", per(scalar) / per(dispatch));
101
+ }
102
+ }
@@ -0,0 +1,238 @@
1
+ //! Explicit SIMD kernels for the distance hot path.
2
+ //!
3
+ //! All functions are `unsafe` because of `#[target_feature]`. Dispatch rules:
4
+ //! on aarch64, NEON (AdvSIMD) is part of the baseline Armv8-A ISA that every
5
+ //! Rust aarch64 std target assumes, so kernels run unconditionally; on x86_64,
6
+ //! callers must check `avx2_available()` first (the result is cached by std).
7
+ //! Kernels clamp to `min(a.len(), b.len())` so a length mismatch can never
8
+ //! read out of bounds, matching the scalar zip semantics.
9
+
10
+ #[cfg(target_arch = "x86_64")]
11
+ pub(crate) fn avx2_available() -> bool {
12
+ std::arch::is_x86_feature_detected!("avx2") && std::arch::is_x86_feature_detected!("fma")
13
+ }
14
+
15
+ #[cfg(target_arch = "aarch64")]
16
+ pub(crate) mod neon {
17
+ use core::arch::aarch64::*;
18
+
19
+ #[target_feature(enable = "neon")]
20
+ pub(crate) unsafe fn dot(a: &[f32], b: &[f32]) -> f32 {
21
+ let n = a.len().min(b.len());
22
+ let (pa, pb) = (a.as_ptr(), b.as_ptr());
23
+ let mut acc0 = vdupq_n_f32(0.0);
24
+ let mut acc1 = vdupq_n_f32(0.0);
25
+ let mut acc2 = vdupq_n_f32(0.0);
26
+ let mut acc3 = vdupq_n_f32(0.0);
27
+ let mut i = 0;
28
+ while i + 16 <= n {
29
+ acc0 = vfmaq_f32(acc0, vld1q_f32(pa.add(i)), vld1q_f32(pb.add(i)));
30
+ acc1 = vfmaq_f32(acc1, vld1q_f32(pa.add(i + 4)), vld1q_f32(pb.add(i + 4)));
31
+ acc2 = vfmaq_f32(acc2, vld1q_f32(pa.add(i + 8)), vld1q_f32(pb.add(i + 8)));
32
+ acc3 = vfmaq_f32(acc3, vld1q_f32(pa.add(i + 12)), vld1q_f32(pb.add(i + 12)));
33
+ i += 16;
34
+ }
35
+ while i + 4 <= n {
36
+ acc0 = vfmaq_f32(acc0, vld1q_f32(pa.add(i)), vld1q_f32(pb.add(i)));
37
+ i += 4;
38
+ }
39
+ let mut sum = vaddvq_f32(vaddq_f32(vaddq_f32(acc0, acc1), vaddq_f32(acc2, acc3)));
40
+ while i < n {
41
+ sum += *pa.add(i) * *pb.add(i);
42
+ i += 1;
43
+ }
44
+ -sum
45
+ }
46
+
47
+ #[target_feature(enable = "neon")]
48
+ pub(crate) unsafe fn euclidean(a: &[f32], b: &[f32]) -> f32 {
49
+ let n = a.len().min(b.len());
50
+ let (pa, pb) = (a.as_ptr(), b.as_ptr());
51
+ let mut acc0 = vdupq_n_f32(0.0);
52
+ let mut acc1 = vdupq_n_f32(0.0);
53
+ let mut acc2 = vdupq_n_f32(0.0);
54
+ let mut acc3 = vdupq_n_f32(0.0);
55
+ let mut i = 0;
56
+ while i + 16 <= n {
57
+ let d0 = vsubq_f32(vld1q_f32(pa.add(i)), vld1q_f32(pb.add(i)));
58
+ let d1 = vsubq_f32(vld1q_f32(pa.add(i + 4)), vld1q_f32(pb.add(i + 4)));
59
+ let d2 = vsubq_f32(vld1q_f32(pa.add(i + 8)), vld1q_f32(pb.add(i + 8)));
60
+ let d3 = vsubq_f32(vld1q_f32(pa.add(i + 12)), vld1q_f32(pb.add(i + 12)));
61
+ acc0 = vfmaq_f32(acc0, d0, d0);
62
+ acc1 = vfmaq_f32(acc1, d1, d1);
63
+ acc2 = vfmaq_f32(acc2, d2, d2);
64
+ acc3 = vfmaq_f32(acc3, d3, d3);
65
+ i += 16;
66
+ }
67
+ while i + 4 <= n {
68
+ let d = vsubq_f32(vld1q_f32(pa.add(i)), vld1q_f32(pb.add(i)));
69
+ acc0 = vfmaq_f32(acc0, d, d);
70
+ i += 4;
71
+ }
72
+ let mut sum = vaddvq_f32(vaddq_f32(vaddq_f32(acc0, acc1), vaddq_f32(acc2, acc3)));
73
+ while i < n {
74
+ let d = *pa.add(i) - *pb.add(i);
75
+ sum += d * d;
76
+ i += 1;
77
+ }
78
+ sum.sqrt()
79
+ }
80
+
81
+ #[target_feature(enable = "neon")]
82
+ pub(crate) unsafe fn cosine(a: &[f32], b: &[f32]) -> f32 {
83
+ let n = a.len().min(b.len());
84
+ let (pa, pb) = (a.as_ptr(), b.as_ptr());
85
+ let mut dot0 = vdupq_n_f32(0.0);
86
+ let mut dot1 = vdupq_n_f32(0.0);
87
+ let mut na0 = vdupq_n_f32(0.0);
88
+ let mut na1 = vdupq_n_f32(0.0);
89
+ let mut nb0 = vdupq_n_f32(0.0);
90
+ let mut nb1 = vdupq_n_f32(0.0);
91
+ let mut i = 0;
92
+ while i + 8 <= n {
93
+ let x0 = vld1q_f32(pa.add(i));
94
+ let y0 = vld1q_f32(pb.add(i));
95
+ let x1 = vld1q_f32(pa.add(i + 4));
96
+ let y1 = vld1q_f32(pb.add(i + 4));
97
+ dot0 = vfmaq_f32(dot0, x0, y0);
98
+ dot1 = vfmaq_f32(dot1, x1, y1);
99
+ na0 = vfmaq_f32(na0, x0, x0);
100
+ na1 = vfmaq_f32(na1, x1, x1);
101
+ nb0 = vfmaq_f32(nb0, y0, y0);
102
+ nb1 = vfmaq_f32(nb1, y1, y1);
103
+ i += 8;
104
+ }
105
+ while i + 4 <= n {
106
+ let x = vld1q_f32(pa.add(i));
107
+ let y = vld1q_f32(pb.add(i));
108
+ dot0 = vfmaq_f32(dot0, x, y);
109
+ na0 = vfmaq_f32(na0, x, x);
110
+ nb0 = vfmaq_f32(nb0, y, y);
111
+ i += 4;
112
+ }
113
+ let mut dot = vaddvq_f32(vaddq_f32(dot0, dot1));
114
+ let mut norm_a = vaddvq_f32(vaddq_f32(na0, na1));
115
+ let mut norm_b = vaddvq_f32(vaddq_f32(nb0, nb1));
116
+ while i < n {
117
+ let (x, y) = (*pa.add(i), *pb.add(i));
118
+ dot += x * y;
119
+ norm_a += x * x;
120
+ norm_b += y * y;
121
+ i += 1;
122
+ }
123
+ let denom = norm_a.sqrt() * norm_b.sqrt();
124
+ if denom == 0.0 {
125
+ return 1.0;
126
+ }
127
+ 1.0 - (dot / denom)
128
+ }
129
+ }
130
+
131
+ #[cfg(target_arch = "x86_64")]
132
+ pub(crate) mod avx2 {
133
+ use core::arch::x86_64::*;
134
+
135
+ /// Horizontal sum of one 256-bit register.
136
+ #[inline]
137
+ #[target_feature(enable = "avx2", enable = "fma")]
138
+ unsafe fn hsum(v: __m256) -> f32 {
139
+ let lo = _mm256_castps256_ps128(v);
140
+ let hi = _mm256_extractf128_ps(v, 1);
141
+ let s = _mm_add_ps(lo, hi);
142
+ let s = _mm_hadd_ps(s, s);
143
+ let s = _mm_hadd_ps(s, s);
144
+ _mm_cvtss_f32(s)
145
+ }
146
+
147
+ #[target_feature(enable = "avx2", enable = "fma")]
148
+ pub(crate) unsafe fn dot(a: &[f32], b: &[f32]) -> f32 {
149
+ let n = a.len().min(b.len());
150
+ let (pa, pb) = (a.as_ptr(), b.as_ptr());
151
+ let mut acc0 = _mm256_setzero_ps();
152
+ let mut acc1 = _mm256_setzero_ps();
153
+ let mut i = 0;
154
+ while i + 16 <= n {
155
+ acc0 = _mm256_fmadd_ps(_mm256_loadu_ps(pa.add(i)), _mm256_loadu_ps(pb.add(i)), acc0);
156
+ acc1 = _mm256_fmadd_ps(
157
+ _mm256_loadu_ps(pa.add(i + 8)),
158
+ _mm256_loadu_ps(pb.add(i + 8)),
159
+ acc1,
160
+ );
161
+ i += 16;
162
+ }
163
+ while i + 8 <= n {
164
+ acc0 = _mm256_fmadd_ps(_mm256_loadu_ps(pa.add(i)), _mm256_loadu_ps(pb.add(i)), acc0);
165
+ i += 8;
166
+ }
167
+ let mut sum = hsum(_mm256_add_ps(acc0, acc1));
168
+ while i < n {
169
+ sum += *pa.add(i) * *pb.add(i);
170
+ i += 1;
171
+ }
172
+ -sum
173
+ }
174
+
175
+ #[target_feature(enable = "avx2", enable = "fma")]
176
+ pub(crate) unsafe fn euclidean(a: &[f32], b: &[f32]) -> f32 {
177
+ let n = a.len().min(b.len());
178
+ let (pa, pb) = (a.as_ptr(), b.as_ptr());
179
+ let mut acc0 = _mm256_setzero_ps();
180
+ let mut acc1 = _mm256_setzero_ps();
181
+ let mut i = 0;
182
+ while i + 16 <= n {
183
+ let d0 = _mm256_sub_ps(_mm256_loadu_ps(pa.add(i)), _mm256_loadu_ps(pb.add(i)));
184
+ let d1 = _mm256_sub_ps(
185
+ _mm256_loadu_ps(pa.add(i + 8)),
186
+ _mm256_loadu_ps(pb.add(i + 8)),
187
+ );
188
+ acc0 = _mm256_fmadd_ps(d0, d0, acc0);
189
+ acc1 = _mm256_fmadd_ps(d1, d1, acc1);
190
+ i += 16;
191
+ }
192
+ while i + 8 <= n {
193
+ let d = _mm256_sub_ps(_mm256_loadu_ps(pa.add(i)), _mm256_loadu_ps(pb.add(i)));
194
+ acc0 = _mm256_fmadd_ps(d, d, acc0);
195
+ i += 8;
196
+ }
197
+ let mut sum = hsum(_mm256_add_ps(acc0, acc1));
198
+ while i < n {
199
+ let d = *pa.add(i) - *pb.add(i);
200
+ sum += d * d;
201
+ i += 1;
202
+ }
203
+ sum.sqrt()
204
+ }
205
+
206
+ #[target_feature(enable = "avx2", enable = "fma")]
207
+ pub(crate) unsafe fn cosine(a: &[f32], b: &[f32]) -> f32 {
208
+ let n = a.len().min(b.len());
209
+ let (pa, pb) = (a.as_ptr(), b.as_ptr());
210
+ let mut dot_acc = _mm256_setzero_ps();
211
+ let mut na_acc = _mm256_setzero_ps();
212
+ let mut nb_acc = _mm256_setzero_ps();
213
+ let mut i = 0;
214
+ while i + 8 <= n {
215
+ let x = _mm256_loadu_ps(pa.add(i));
216
+ let y = _mm256_loadu_ps(pb.add(i));
217
+ dot_acc = _mm256_fmadd_ps(x, y, dot_acc);
218
+ na_acc = _mm256_fmadd_ps(x, x, na_acc);
219
+ nb_acc = _mm256_fmadd_ps(y, y, nb_acc);
220
+ i += 8;
221
+ }
222
+ let mut dot = hsum(dot_acc);
223
+ let mut norm_a = hsum(na_acc);
224
+ let mut norm_b = hsum(nb_acc);
225
+ while i < n {
226
+ let (x, y) = (*pa.add(i), *pb.add(i));
227
+ dot += x * y;
228
+ norm_a += x * x;
229
+ norm_b += y * y;
230
+ i += 1;
231
+ }
232
+ let denom = norm_a.sqrt() * norm_b.sqrt();
233
+ if denom == 0.0 {
234
+ return 1.0;
235
+ }
236
+ 1.0 - (dot / denom)
237
+ }
238
+ }
@@ -163,8 +163,10 @@ impl MmapVectorStorage {
163
163
  let bytes = &mmap[offset..offset + byte_len];
164
164
 
165
165
  let floats: Vec<f32> = bytes
166
- .chunks_exact(4)
167
- .map(|chunk| f32::from_le_bytes(chunk.try_into().unwrap()))
166
+ .as_chunks::<4>()
167
+ .0
168
+ .iter()
169
+ .map(|chunk| f32::from_le_bytes(*chunk))
168
170
  .collect();
169
171
 
170
172
  Ok(floats)
@@ -1,49 +0,0 @@
1
- mod cosine;
2
- mod dot;
3
- mod euclidean;
4
-
5
- pub use cosine::CosineDistance;
6
- pub use dot::DotProductDistance;
7
- pub use euclidean::EuclideanDistance;
8
-
9
- use crate::types::DistanceMetricKind;
10
-
11
- /// All distance functions return a *distance* (lower = more similar).
12
- /// For cosine: distance = 1 - cosine_similarity
13
- /// For dot product: distance = -dot_product (negate so lower = higher similarity)
14
- /// For euclidean: distance = L2 distance
15
- pub trait DistanceMetric: Send + Sync {
16
- fn distance(&self, a: &[f32], b: &[f32]) -> f32;
17
- }
18
-
19
- /// Monomorphized distance dispatch for the hot path.
20
- ///
21
- /// Unlike `Box<dyn DistanceMetric>`, this `Copy` enum lets the compiler inline
22
- /// `distance` into the index inner loops (a vtable call cannot be inlined),
23
- /// which in turn lets LLVM auto-vectorize the per-dimension reduction. Same
24
- /// math as the trait impls — both share the `#[inline]` free functions.
25
- #[derive(Clone, Copy, Debug, PartialEq, Eq)]
26
- pub enum Metric {
27
- Cosine,
28
- Euclidean,
29
- DotProduct,
30
- }
31
-
32
- impl Metric {
33
- #[inline]
34
- pub fn distance(&self, a: &[f32], b: &[f32]) -> f32 {
35
- match self {
36
- Metric::Cosine => cosine::cosine(a, b),
37
- Metric::Euclidean => euclidean::euclidean(a, b),
38
- Metric::DotProduct => dot::dot(a, b),
39
- }
40
- }
41
- }
42
-
43
- pub fn metric_for_kind(kind: DistanceMetricKind) -> Metric {
44
- match kind {
45
- DistanceMetricKind::Cosine => Metric::Cosine,
46
- DistanceMetricKind::Euclidean => Metric::Euclidean,
47
- DistanceMetricKind::DotProduct => Metric::DotProduct,
48
- }
49
- }
File without changes
File without changes