rinnd 0.3.1__tar.gz → 0.4.1__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 (48) hide show
  1. {rinnd-0.3.1 → rinnd-0.4.1}/Cargo.toml +1 -1
  2. {rinnd-0.3.1 → rinnd-0.4.1}/PKG-INFO +1 -1
  3. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd/Cargo.toml +5 -0
  4. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd/src/lib.rs +4 -0
  5. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/Cargo.toml +10 -1
  6. rinnd-0.4.1/crates/rinnd-core/examples/graph_bench.rs +52 -0
  7. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/src/distance/alternatives.rs +25 -0
  8. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/src/distance/euclidean.rs +5 -0
  9. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/src/distance/mod.rs +2 -0
  10. rinnd-0.4.1/crates/rinnd-core/src/distance/tile.rs +247 -0
  11. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/src/distance/traits.rs +6 -0
  12. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/src/nndescent/candidates.rs +549 -0
  13. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/src/nndescent/mod.rs +77 -4
  14. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/src/search/greedy.rs +25 -0
  15. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/src/tree/breadth_first.rs +8 -8
  16. rinnd-0.4.1/crates/rinnd-core/src/tree/hybrid_forest.rs +508 -0
  17. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/src/tree/mod.rs +7 -1
  18. {rinnd-0.3.1 → rinnd-0.4.1}/pyproject.toml +1 -1
  19. {rinnd-0.3.1 → rinnd-0.4.1}/Cargo.lock +0 -0
  20. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/benches/distance.rs +0 -0
  21. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/benches/heap.rs +0 -0
  22. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/src/distance/angular.rs +0 -0
  23. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/src/distance/binary.rs +0 -0
  24. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/src/distance/cosine.rs +0 -0
  25. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/src/distance/hellinger.rs +0 -0
  26. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/src/distance/inner_product.rs +0 -0
  27. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/src/distance/minkowski.rs +0 -0
  28. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/src/distance/quantized.rs +0 -0
  29. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/src/graph/mod.rs +0 -0
  30. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/src/graph/neighbor_graph.rs +0 -0
  31. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/src/graph/search_graph.rs +0 -0
  32. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/src/heap/candidate_heap.rs +0 -0
  33. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/src/heap/mod.rs +0 -0
  34. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/src/heap/neighbor_heap.rs +0 -0
  35. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/src/index.rs +0 -0
  36. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/src/lib.rs +0 -0
  37. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/src/nndescent/update.rs +0 -0
  38. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/src/rng.rs +0 -0
  39. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/src/search/mod.rs +0 -0
  40. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/src/tree/builder.rs +0 -0
  41. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/src/tree/flat_tree.rs +0 -0
  42. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-core/src/visited.rs +0 -0
  43. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-simd/Cargo.toml +0 -0
  44. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-simd/benches/simd_distance.rs +0 -0
  45. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-simd/src/avx2.rs +0 -0
  46. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-simd/src/avx512.rs +0 -0
  47. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-simd/src/detect.rs +0 -0
  48. {rinnd-0.3.1 → rinnd-0.4.1}/crates/rinnd-simd/src/lib.rs +0 -0
@@ -8,7 +8,7 @@ edition = "2021"
8
8
  authors = ["Leland McInnes <leland.mcinnes@gmail.com>"]
9
9
  license = "BSD-2-Clause"
10
10
  repository = "https://github.com/lmcinnes/rinnd"
11
- rust-version = "1.77"
11
+ rust-version = "1.89"
12
12
 
13
13
  [workspace.dependencies]
14
14
  # Parallelism
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rinnd
3
- Version: 0.3.1
3
+ Version: 0.4.1
4
4
  Classifier: Programming Language :: Rust
5
5
  Classifier: Programming Language :: Python :: Implementation :: CPython
6
6
  Classifier: Programming Language :: Python :: 3
@@ -17,6 +17,11 @@ default = ["rinnd-core/default"]
17
17
  packed-updates = ["rinnd-core/packed-updates"]
18
18
  candidate-membership = ["rinnd-core/candidate-membership"]
19
19
  candidate-workspace = ["rinnd-core/candidate-workspace"]
20
+ active-candidates = ["rinnd-core/active-candidates"]
21
+ blocked-candidates = ["rinnd-core/blocked-candidates"]
22
+ hybrid-forest = ["rinnd-core/hybrid-forest"]
23
+ tiled-leaves = ["rinnd-core/tiled-leaves"]
24
+ generation-prefetch = ["rinnd-core/generation-prefetch"]
20
25
 
21
26
  [dependencies]
22
27
  rinnd-core = { path = "../rinnd-core", default-features = false, features = ["std", "rayon"] }
@@ -1425,6 +1425,10 @@ impl PyNNDescent {
1425
1425
  candidate_phases.set_item(name, values)?;
1426
1426
  }
1427
1427
  result.set_item("candidate_phases", candidate_phases)?;
1428
+ result.set_item(
1429
+ "candidate_active_vertices",
1430
+ phases.iter().map(|phase| phase.active_vertices).collect::<Vec<_>>(),
1431
+ )?;
1428
1432
  result.set_item(
1429
1433
  "update_generation_seconds",
1430
1434
  stats.nn_descent.update_generation_seconds.clone(),
@@ -9,7 +9,7 @@ repository.workspace = true
9
9
  rust-version.workspace = true
10
10
 
11
11
  [features]
12
- default = ["std", "rayon", "batched-euclidean", "batched-angular", "compact-candidates", "batched-leaves", "candidate-membership", "candidate-workspace"]
12
+ default = ["std", "rayon", "batched-euclidean", "batched-angular", "compact-candidates", "batched-leaves", "candidate-membership", "candidate-workspace", "active-candidates", "hybrid-forest", "tiled-leaves", "generation-prefetch"]
13
13
  std = []
14
14
  rayon = ["dep:rayon"]
15
15
  mmap = ["dep:memmap2"]
@@ -19,8 +19,17 @@ batched-euclidean = []
19
19
  batched-angular = []
20
20
  compact-candidates = []
21
21
  candidate-membership = []
22
+ # Cache-blocked candidate construction (see nndescent/candidates.rs, mod blocked).
23
+ blocked-candidates = []
24
+ # Hybrid breadth-first / cache-local RP forest for graph-only builds (identical leaves).
25
+ hybrid-forest = []
22
26
  candidate-workspace = []
27
+ active-candidates = []
23
28
  batched-leaves = []
29
+ # Register-tiled leaf-initialization kernels (bit-identical distances).
30
+ tiled-leaves = []
31
+ # Prefetch next hub's candidate vectors during update generation (dim <= 256).
32
+ generation-prefetch = []
24
33
  packed-updates = []
25
34
 
26
35
  [dependencies]
@@ -0,0 +1,52 @@
1
+ //! Time a graph-only build (the UMAP-style path) and print one JSON line.
2
+ //!
3
+ //! Usage: graph_bench <data.f32> <n> <dim> <k> <seed> <forest> [out_indices.i32]
4
+ //! forest = depth | bfs<W> (breadth-first, batch width W in 1..=8)
5
+ //! Candidate construction follows the build's features; with `blocked-candidates`,
6
+ //! RINND_BLOCKED_CANDIDATES=0 selects the original algorithm at runtime.
7
+
8
+ use rinnd_core::distance::SquaredEuclidean;
9
+ use rinnd_core::index::NNDescentBuilder;
10
+ use std::time::Instant;
11
+
12
+ fn main() {
13
+ let a: Vec<String> = std::env::args().collect();
14
+ if a.len() < 7 {
15
+ eprintln!("usage: graph_bench <data.f32> <n> <dim> <k> <seed> <forest> [out.i32]");
16
+ std::process::exit(2);
17
+ }
18
+ let n: usize = a[2].parse().unwrap();
19
+ let dim: usize = a[3].parse().unwrap();
20
+ let k: usize = a[4].parse().unwrap();
21
+ let seed: u64 = a[5].parse().unwrap();
22
+ let forest = a[6].as_str();
23
+ let bytes = std::fs::read(&a[1]).unwrap();
24
+ let data: Vec<f32> = bytes.chunks_exact(4).map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect();
25
+ assert_eq!(data.len(), n * dim);
26
+
27
+ let mut builder = NNDescentBuilder::new(&data, n, dim).n_neighbors(k).random_seed(seed);
28
+ builder = match forest {
29
+ "depth" => builder.depth_first_tree_build(),
30
+ f if f.starts_with("bfs") => builder.breadth_first_tree_batch_width(f[3..].parse().unwrap()),
31
+ _ => panic!("forest must be depth or bfs<W>"),
32
+ };
33
+ let started = Instant::now();
34
+ let result = builder.build_graph_with_distance(SquaredEuclidean, None);
35
+ let wall = started.elapsed().as_secs_f64();
36
+ let s = &result.stats.nn_descent;
37
+ if let Some(path) = a.get(7) {
38
+ std::fs::write(path, result.graph.indices.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>()).unwrap();
39
+ }
40
+ let sum = |v: &Vec<f64>| v.iter().sum::<f64>();
41
+ let phase = |f: fn(&rinnd_core::nndescent::CandidateBuildStats) -> f64| s.candidate_phases.iter().map(f).sum::<f64>();
42
+ println!(
43
+ "{{\"forest_mode\":\"{}\",\"cand_mode\":\"{}\",\"n\":{},\"dim\":{},\"k\":{},\"seed\":{},\"wall\":{:.4},\
44
+ \"forest\":{:.4},\"leaf_init\":{:.4},\"candidates\":{:.4},\"cand_init\":{:.4},\"cand_forward\":{:.4},\"cand_reverse\":{:.4},\
45
+ \"cand_mark\":{:.4},\"generation\":{:.4},\"application\":{:.4},\"iters\":{},\"updates\":{:?}}}",
46
+ forest, std::env::var("RINND_BLOCKED_CANDIDATES").unwrap_or_else(|_| "default".into()),
47
+ n, dim, k, seed, wall, s.forest_seconds, s.leaf_initialization_seconds, sum(&s.candidate_seconds),
48
+ phase(|p| p.initialization_seconds), phase(|p| p.forward_seconds), phase(|p| p.reverse_seconds),
49
+ phase(|p| p.mark_seconds), sum(&s.update_generation_seconds), sum(&s.update_application_seconds),
50
+ s.updates.len(), s.updates,
51
+ );
52
+ }
@@ -111,6 +111,12 @@ impl Distance<f32> for AlternativeDot {
111
111
  normalized_dot_four(query, candidates).map(alternative_dot_from_similarity)
112
112
  }
113
113
 
114
+ #[cfg(feature = "tiled-leaves")]
115
+ fn distance_upper(&self, rows: &[&[f32]], out: &mut [f32]) -> bool {
116
+ let computed = super::tile::dot_upper(rows, out);
117
+ map_upper(rows.len(), out, computed, alternative_dot_from_similarity)
118
+ }
119
+
114
120
  #[inline]
115
121
  fn distance(&self, a: &[f32], b: &[f32]) -> f32 {
116
122
  debug_assert_eq!(a.len(), b.len());
@@ -145,6 +151,12 @@ impl Distance<f32> for DirectNormalizedCosine {
145
151
  normalized_dot_four(query, candidates).map(|similarity| 1.0 - similarity.clamp(-1.0, 1.0))
146
152
  }
147
153
 
154
+ #[cfg(feature = "tiled-leaves")]
155
+ fn distance_upper(&self, rows: &[&[f32]], out: &mut [f32]) -> bool {
156
+ let computed = super::tile::dot_upper(rows, out);
157
+ map_upper(rows.len(), out, computed, |similarity| 1.0 - similarity.clamp(-1.0, 1.0))
158
+ }
159
+
148
160
  #[inline]
149
161
  fn distance(&self, a: &[f32], b: &[f32]) -> f32 {
150
162
  debug_assert_eq!(a.len(), b.len());
@@ -167,6 +179,19 @@ impl Distance<f32> for DirectNormalizedCosine {
167
179
  }
168
180
  }
169
181
 
182
+ /// Map tiled similarities in the upper triangle to distances.
183
+ #[cfg(feature = "tiled-leaves")]
184
+ fn map_upper(m: usize, out: &mut [f32], computed: bool, transform: impl Fn(f32) -> f32) -> bool {
185
+ if computed {
186
+ for i in 0..m {
187
+ for value in &mut out[i * m + i + 1..(i + 1) * m] {
188
+ *value = transform(*value);
189
+ }
190
+ }
191
+ }
192
+ computed
193
+ }
194
+
170
195
  #[inline]
171
196
  fn normalized_dot_four(query: &[f32], candidates: [&[f32]; 4]) -> [f32; 4] {
172
197
  for candidate in candidates {
@@ -43,6 +43,11 @@ impl Distance<f32> for SquaredEuclidean {
43
43
  candidates.map(|candidate| scalar_l2_sqr(query, candidate))
44
44
  }
45
45
 
46
+ #[cfg(feature = "tiled-leaves")]
47
+ fn distance_upper(&self, rows: &[&[f32]], out: &mut [f32]) -> bool {
48
+ super::tile::l2_upper(rows, out)
49
+ }
50
+
46
51
  fn name(&self) -> &'static str {
47
52
  "squared_euclidean"
48
53
  }
@@ -41,6 +41,8 @@ mod hellinger;
41
41
  mod inner_product;
42
42
  mod minkowski;
43
43
  pub mod quantized;
44
+ #[cfg(feature = "tiled-leaves")]
45
+ mod tile;
44
46
  mod traits;
45
47
 
46
48
  pub use cosine::Cosine;
@@ -0,0 +1,247 @@
1
+ //! AVX-512VL/AVX2 register-tiled pairwise kernels for dense blocks (leaf initialization).
2
+ //!
3
+ //! Each pair keeps the accumulator layout, reduction order and scalar tail of the
4
+ //! corresponding single-pair kernel, so results are bit-identical to `distance`.
5
+ //! AVX-512VL is used only for its 32 vector registers (6x4 tiles of 256-bit lanes).
6
+
7
+ /// Squared Euclidean for all pairs `i < j`; false if AVX2/FMA is unavailable.
8
+ pub(crate) fn l2_upper(rows: &[&[f32]], out: &mut [f32]) -> bool {
9
+ #[cfg(target_arch = "x86_64")]
10
+ if rows.len() >= 2 && is_x86_feature_detected!("avx2") && is_x86_feature_detected!("fma") {
11
+ if avx512_tiles() {
12
+ unsafe { upper_avx512::<false>(rows, out) };
13
+ } else {
14
+ unsafe { upper_avx2::<false>(rows, out) };
15
+ }
16
+ return true;
17
+ }
18
+ let _ = (rows, out);
19
+ false
20
+ }
21
+
22
+ /// Dot products for all pairs `i < j`; false if unsupported or not profitable.
23
+ pub(crate) fn dot_upper(rows: &[&[f32]], out: &mut [f32]) -> bool {
24
+ // At d = 100 tiles were neutral to slower in leaf init (GloVe), for both tile widths.
25
+ const MIN_DIM: usize = 128;
26
+ #[cfg(target_arch = "x86_64")]
27
+ if rows.len() >= 2
28
+ && rows[0].len() >= MIN_DIM
29
+ && is_x86_feature_detected!("avx2")
30
+ && is_x86_feature_detected!("fma")
31
+ {
32
+ if avx512_tiles() {
33
+ unsafe { upper_avx512::<true>(rows, out) };
34
+ } else {
35
+ unsafe { upper_avx2::<true>(rows, out) };
36
+ }
37
+ return true;
38
+ }
39
+ let _ = (rows, out);
40
+ false
41
+ }
42
+
43
+ #[cfg(target_arch = "x86_64")]
44
+ fn avx512_tiles() -> bool {
45
+ is_x86_feature_detected!("avx512f") && is_x86_feature_detected!("avx512vl")
46
+ }
47
+
48
+ const TQ: usize = 4;
49
+
50
+ #[cfg(target_arch = "x86_64")]
51
+ #[target_feature(enable = "avx2", enable = "fma")]
52
+ unsafe fn upper_avx2<const DOT: bool>(rows: &[&[f32]], out: &mut [f32]) {
53
+ upper::<DOT, 2>(rows, out)
54
+ }
55
+
56
+ #[cfg(target_arch = "x86_64")]
57
+ #[target_feature(enable = "avx2", enable = "fma", enable = "avx512f", enable = "avx512vl")]
58
+ unsafe fn upper_avx512<const DOT: bool>(rows: &[&[f32]], out: &mut [f32]) {
59
+ upper::<DOT, 6>(rows, out)
60
+ }
61
+
62
+ #[cfg(target_arch = "x86_64")]
63
+ #[inline(always)]
64
+ unsafe fn upper<const DOT: bool, const TP: usize>(rows: &[&[f32]], out: &mut [f32]) {
65
+ let m = rows.len();
66
+ debug_assert!(out.len() >= m * m);
67
+ let row = |index: usize| rows[index.min(m - 1)];
68
+ let mut tile = [[0.0f32; TQ]; TP];
69
+ for a0 in (0..m).step_by(TP) {
70
+ let ps: [&[f32]; TP] = std::array::from_fn(|a| row(a0 + a));
71
+ let mut b0 = a0 + 1;
72
+ while b0 < m {
73
+ let qs: [&[f32]; TQ] = std::array::from_fn(|b| row(b0 + b));
74
+ if DOT {
75
+ dot_tile::<TP>(ps, qs, &mut tile);
76
+ } else {
77
+ l2_tile::<TP>(ps, qs, &mut tile);
78
+ }
79
+ for a in 0..TP {
80
+ let i = a0 + a;
81
+ for b in 0..TQ {
82
+ let j = b0 + b;
83
+ if i < m && j < m && j > i {
84
+ out[i * m + j] = tile[a][b];
85
+ }
86
+ }
87
+ }
88
+ b0 += TQ;
89
+ }
90
+ }
91
+ }
92
+
93
+ #[cfg(target_arch = "x86_64")]
94
+ #[inline(always)]
95
+ unsafe fn dot_tile<const TP: usize>(ps: [&[f32]; TP], qs: [&[f32]; TQ], out: &mut [[f32; TQ]; TP]) {
96
+ use std::arch::x86_64::*;
97
+ let dim = ps[0].len();
98
+ let end = dim / 32 * 32;
99
+ let mut lanes = [[[_mm256_setzero_ps(); 4]; TQ]; TP];
100
+ for lane in 0..4 {
101
+ let mut acc = [[_mm256_setzero_ps(); TQ]; TP];
102
+ let mut offset = lane * 8;
103
+ while offset < end {
104
+ let qv: [__m256; TQ] = std::array::from_fn(|b| _mm256_loadu_ps(qs[b].as_ptr().add(offset)));
105
+ for a in 0..TP {
106
+ let pv = _mm256_loadu_ps(ps[a].as_ptr().add(offset));
107
+ for b in 0..TQ {
108
+ acc[a][b] = _mm256_fmadd_ps(pv, qv[b], acc[a][b]);
109
+ }
110
+ }
111
+ offset += 32;
112
+ }
113
+ for a in 0..TP {
114
+ for b in 0..TQ {
115
+ lanes[a][b][lane] = acc[a][b];
116
+ }
117
+ }
118
+ }
119
+ for a in 0..TP {
120
+ for b in 0..TQ {
121
+ let s = lanes[a][b];
122
+ let mut dot = dot_hsum(_mm256_add_ps(_mm256_add_ps(s[0], s[1]), _mm256_add_ps(s[2], s[3])));
123
+ for i in end..dim {
124
+ dot += ps[a][i] * qs[b][i];
125
+ }
126
+ out[a][b] = dot;
127
+ }
128
+ }
129
+ }
130
+
131
+ #[cfg(target_arch = "x86_64")]
132
+ #[inline(always)]
133
+ unsafe fn l2_tile<const TP: usize>(ps: [&[f32]; TP], qs: [&[f32]; TQ], out: &mut [[f32; TQ]; TP]) {
134
+ use std::arch::x86_64::*;
135
+ let dim = ps[0].len();
136
+ let end = dim / 8 * 8;
137
+ let mut acc = [[_mm256_setzero_ps(); TQ]; TP];
138
+ let mut offset = 0;
139
+ while offset < end {
140
+ let qv: [__m256; TQ] = std::array::from_fn(|b| _mm256_loadu_ps(qs[b].as_ptr().add(offset)));
141
+ for a in 0..TP {
142
+ let pv = _mm256_loadu_ps(ps[a].as_ptr().add(offset));
143
+ for b in 0..TQ {
144
+ let difference = _mm256_sub_ps(pv, qv[b]);
145
+ acc[a][b] = _mm256_fmadd_ps(difference, difference, acc[a][b]);
146
+ }
147
+ }
148
+ offset += 8;
149
+ }
150
+ for a in 0..TP {
151
+ for b in 0..TQ {
152
+ let mut sum = l2_hsum(acc[a][b]);
153
+ for i in end..dim {
154
+ let difference = ps[a][i] - qs[b][i];
155
+ sum += difference * difference;
156
+ }
157
+ out[a][b] = sum;
158
+ }
159
+ }
160
+ }
161
+
162
+ /// Same reduction as `alternatives::horizontal_sum_avx`.
163
+ #[cfg(target_arch = "x86_64")]
164
+ #[inline(always)]
165
+ unsafe fn dot_hsum(value: std::arch::x86_64::__m256) -> f32 {
166
+ use std::arch::x86_64::*;
167
+ let sum = _mm_add_ps(_mm256_castps256_ps128(value), _mm256_extractf128_ps(value, 1));
168
+ let pairs = _mm_add_ps(sum, _mm_movehl_ps(sum, sum));
169
+ let odd = _mm_shuffle_ps(pairs, pairs, 0x55);
170
+ _mm_cvtss_f32(_mm_add_ss(pairs, odd))
171
+ }
172
+
173
+ /// Same reduction as `euclidean::hsum256_ps_avx`.
174
+ #[cfg(target_arch = "x86_64")]
175
+ #[inline(always)]
176
+ unsafe fn l2_hsum(value: std::arch::x86_64::__m256) -> f32 {
177
+ use std::arch::x86_64::*;
178
+ let sum = _mm_add_ps(_mm256_extractf128_ps(value, 1), _mm256_castps256_ps128(value));
179
+ let sums = _mm_add_ps(sum, _mm_movehdup_ps(sum));
180
+ _mm_cvtss_f32(_mm_add_ss(sums, _mm_movehl_ps(sums, sums)))
181
+ }
182
+
183
+ #[cfg(test)]
184
+ mod tests {
185
+ use crate::distance::{AlternativeDot, DirectNormalizedCosine, Distance, SquaredEuclidean};
186
+ use crate::rng::FastRng;
187
+
188
+ fn check<D: Distance<f32>>(distance: D) {
189
+ let mut rng = FastRng::new(17);
190
+ for dim in [8, 31, 100, 128, 131, 256, 784] {
191
+ for m in [2, 3, 5, 8, 9, 17, 60, 64] {
192
+ let mut data: Vec<f32> = (0..m * dim).map(|_| rng.next_float() - 0.5).collect();
193
+ for row in data.chunks_mut(dim) {
194
+ let norm = row.iter().map(|x| x * x).sum::<f32>().sqrt();
195
+ row.iter_mut().for_each(|x| *x /= norm);
196
+ }
197
+ let rows: Vec<&[f32]> = data.chunks(dim).collect();
198
+ let mut out = vec![f32::NAN; m * m];
199
+ if !distance.distance_upper(&rows, &mut out) {
200
+ continue;
201
+ }
202
+ for i in 0..m {
203
+ for j in i + 1..m {
204
+ let expected = distance.distance(rows[i], rows[j]);
205
+ assert_eq!(out[i * m + j].to_bits(), expected.to_bits(), "dim={dim} m={m} ({i},{j})");
206
+ }
207
+ }
208
+ }
209
+ }
210
+ }
211
+
212
+ #[test]
213
+ fn tiled_upper_matches_single_pair_distances() {
214
+ check(SquaredEuclidean);
215
+ check(AlternativeDot);
216
+ check(DirectNormalizedCosine);
217
+ }
218
+
219
+ #[cfg(target_arch = "x86_64")]
220
+ #[test]
221
+ fn avx2_and_avx512_tiles_agree() {
222
+ if !(is_x86_feature_detected!("avx2") && is_x86_feature_detected!("fma") && super::avx512_tiles()) {
223
+ return;
224
+ }
225
+ let mut rng = FastRng::new(5);
226
+ for dim in [8, 31, 100, 256, 784] {
227
+ for m in [2, 7, 13, 60] {
228
+ let data: Vec<f32> = (0..m * dim).map(|_| rng.next_float() - 0.5).collect();
229
+ let rows: Vec<&[f32]> = data.chunks(dim).collect();
230
+ let run = |avx512: bool, dot: bool| {
231
+ let mut out = vec![0.0f32; m * m];
232
+ unsafe {
233
+ match (avx512, dot) {
234
+ (true, true) => super::upper_avx512::<true>(&rows, &mut out),
235
+ (true, false) => super::upper_avx512::<false>(&rows, &mut out),
236
+ (false, true) => super::upper_avx2::<true>(&rows, &mut out),
237
+ (false, false) => super::upper_avx2::<false>(&rows, &mut out),
238
+ }
239
+ }
240
+ out.iter().map(|value| value.to_bits()).collect::<Vec<_>>()
241
+ };
242
+ assert_eq!(run(true, true), run(false, true), "dot dim={dim} m={m}");
243
+ assert_eq!(run(true, false), run(false, false), "l2 dim={dim} m={m}");
244
+ }
245
+ }
246
+ }
247
+ }
@@ -21,6 +21,12 @@ pub trait Distance<T>: Send + Sync + Clone {
21
21
  candidates.map(|candidate| self.distance(query, candidate))
22
22
  }
23
23
 
24
+ /// Distances for all pairs `i < j` of `rows`, written to `out[i * rows.len() + j]`,
25
+ /// bit-identical to `distance(rows[i], rows[j])`. Returns false if no block kernel applies.
26
+ fn distance_upper(&self, _rows: &[&[T]], _out: &mut [f32]) -> bool {
27
+ false
28
+ }
29
+
24
30
  /// Compute distances from one query to multiple data points.
25
31
  ///
26
32
  /// Default implementation calls `distance` in a loop.