rinnd 0.2.0__tar.gz → 0.4.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 (52) hide show
  1. {rinnd-0.2.0 → rinnd-0.4.0}/Cargo.toml +1 -1
  2. {rinnd-0.2.0 → rinnd-0.4.0}/PKG-INFO +1 -1
  3. rinnd-0.4.0/crates/rinnd/Cargo.toml +32 -0
  4. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd/src/lib.rs +24 -0
  5. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-core/Cargo.toml +15 -1
  6. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-core/benches/distance.rs +39 -1
  7. rinnd-0.4.0/crates/rinnd-core/benches/heap.rs +168 -0
  8. rinnd-0.4.0/crates/rinnd-core/examples/graph_bench.rs +52 -0
  9. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-core/src/distance/alternatives.rs +82 -0
  10. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-core/src/distance/cosine.rs +53 -0
  11. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-core/src/distance/euclidean.rs +71 -0
  12. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-core/src/distance/inner_product.rs +49 -0
  13. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-core/src/distance/mod.rs +27 -0
  14. rinnd-0.4.0/crates/rinnd-core/src/distance/tile.rs +247 -0
  15. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-core/src/distance/traits.rs +12 -0
  16. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-core/src/heap/neighbor_heap.rs +47 -30
  17. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-core/src/index.rs +58 -1
  18. rinnd-0.4.0/crates/rinnd-core/src/nndescent/candidates.rs +1438 -0
  19. rinnd-0.4.0/crates/rinnd-core/src/nndescent/mod.rs +1474 -0
  20. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-core/src/search/greedy.rs +135 -9
  21. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-core/src/tree/breadth_first.rs +8 -8
  22. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-core/src/tree/builder.rs +80 -5
  23. rinnd-0.4.0/crates/rinnd-core/src/tree/hybrid_forest.rs +430 -0
  24. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-core/src/tree/mod.rs +7 -1
  25. {rinnd-0.2.0 → rinnd-0.4.0}/pyproject.toml +1 -1
  26. rinnd-0.2.0/crates/rinnd/Cargo.toml +0 -22
  27. rinnd-0.2.0/crates/rinnd-core/benches/heap.rs +0 -78
  28. rinnd-0.2.0/crates/rinnd-core/src/nndescent/candidates.rs +0 -593
  29. rinnd-0.2.0/crates/rinnd-core/src/nndescent/mod.rs +0 -661
  30. {rinnd-0.2.0 → rinnd-0.4.0}/Cargo.lock +0 -0
  31. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-core/src/distance/angular.rs +0 -0
  32. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-core/src/distance/binary.rs +0 -0
  33. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-core/src/distance/hellinger.rs +0 -0
  34. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-core/src/distance/minkowski.rs +0 -0
  35. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-core/src/distance/quantized.rs +0 -0
  36. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-core/src/graph/mod.rs +0 -0
  37. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-core/src/graph/neighbor_graph.rs +0 -0
  38. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-core/src/graph/search_graph.rs +0 -0
  39. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-core/src/heap/candidate_heap.rs +0 -0
  40. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-core/src/heap/mod.rs +0 -0
  41. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-core/src/lib.rs +0 -0
  42. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-core/src/nndescent/update.rs +0 -0
  43. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-core/src/rng.rs +0 -0
  44. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-core/src/search/mod.rs +0 -0
  45. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-core/src/tree/flat_tree.rs +0 -0
  46. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-core/src/visited.rs +0 -0
  47. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-simd/Cargo.toml +0 -0
  48. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-simd/benches/simd_distance.rs +0 -0
  49. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-simd/src/avx2.rs +0 -0
  50. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-simd/src/avx512.rs +0 -0
  51. {rinnd-0.2.0 → rinnd-0.4.0}/crates/rinnd-simd/src/detect.rs +0 -0
  52. {rinnd-0.2.0 → rinnd-0.4.0}/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.75"
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.2.0
3
+ Version: 0.4.0
4
4
  Classifier: Programming Language :: Rust
5
5
  Classifier: Programming Language :: Python :: Implementation :: CPython
6
6
  Classifier: Programming Language :: Python :: 3
@@ -0,0 +1,32 @@
1
+ [package]
2
+ name = "rinnd"
3
+ description = "Python bindings for RINND"
4
+ version.workspace = true
5
+ edition.workspace = true
6
+ authors.workspace = true
7
+ license.workspace = true
8
+ repository.workspace = true
9
+ rust-version.workspace = true
10
+
11
+ [lib]
12
+ name = "rinnd"
13
+ crate-type = ["cdylib"]
14
+
15
+ [features]
16
+ default = ["rinnd-core/default"]
17
+ packed-updates = ["rinnd-core/packed-updates"]
18
+ candidate-membership = ["rinnd-core/candidate-membership"]
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
+
25
+ [dependencies]
26
+ rinnd-core = { path = "../rinnd-core", default-features = false, features = ["std", "rayon"] }
27
+ rinnd-simd = { path = "../rinnd-simd" }
28
+ pyo3 = { workspace = true }
29
+ numpy = { workspace = true }
30
+ rayon = { workspace = true }
31
+
32
+ [dev-dependencies]
@@ -1413,6 +1413,30 @@ impl PyNNDescent {
1413
1413
  stats.nn_descent.candidate_seconds.clone(),
1414
1414
  )?;
1415
1415
  result.set_item("update_seconds", stats.nn_descent.update_seconds.clone())?;
1416
+ let phases = &stats.nn_descent.candidate_phases;
1417
+ let candidate_phases = PyDict::new_bound(py);
1418
+ for (name, values) in [
1419
+ ("initialization", phases.iter().map(|phase| phase.initialization_seconds).collect::<Vec<_>>()),
1420
+ ("forward", phases.iter().map(|phase| phase.forward_seconds).collect()),
1421
+ ("reverse", phases.iter().map(|phase| phase.reverse_seconds).collect()),
1422
+ ("mark", phases.iter().map(|phase| phase.mark_seconds).collect()),
1423
+ ("release", phases.iter().map(|phase| phase.release_seconds).collect()),
1424
+ ] {
1425
+ candidate_phases.set_item(name, values)?;
1426
+ }
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
+ )?;
1432
+ result.set_item(
1433
+ "update_generation_seconds",
1434
+ stats.nn_descent.update_generation_seconds.clone(),
1435
+ )?;
1436
+ result.set_item(
1437
+ "update_application_seconds",
1438
+ stats.nn_descent.update_application_seconds.clone(),
1439
+ )?;
1416
1440
  result.set_item("updates", stats.nn_descent.updates.clone())?;
1417
1441
  result.set_item("nn_descent_seconds", stats.nn_descent.total_seconds())?;
1418
1442
  result.set_item("sort_seconds", stats.sort_seconds)?;
@@ -9,12 +9,26 @@ repository.workspace = true
9
9
  rust-version.workspace = true
10
10
 
11
11
  [features]
12
- default = ["std", "rayon"]
12
+ default = ["std", "rayon", "batched-euclidean", "batched-angular", "compact-candidates", "batched-leaves", "candidate-membership", "candidate-workspace", "active-candidates", "hybrid-forest", "tiled-leaves"]
13
13
  std = []
14
14
  rayon = ["dep:rayon"]
15
15
  mmap = ["dep:memmap2"]
16
16
  serde = ["dep:serde", "dep:bincode"]
17
17
  bench-internals = ["dep:memmap2"]
18
+ batched-euclidean = []
19
+ batched-angular = []
20
+ compact-candidates = []
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 = []
26
+ candidate-workspace = []
27
+ active-candidates = []
28
+ batched-leaves = []
29
+ # Register-tiled leaf-initialization kernels (bit-identical distances).
30
+ tiled-leaves = []
31
+ packed-updates = []
18
32
 
19
33
  [dependencies]
20
34
  rayon = { workspace = true, optional = true }
@@ -30,17 +30,54 @@ fn bench_euclidean(c: &mut Criterion) {
30
30
  fn bench_squared_euclidean(c: &mut Criterion) {
31
31
  let mut group = c.benchmark_group("squared_euclidean");
32
32
 
33
- for dim in [32, 64, 128, 256, 512, 768, 1024].iter() {
33
+ for dim in [32, 64, 128, 256, 512, 768, 784, 1024].iter() {
34
34
  let (a, b) = generate_vectors(1, *dim);
35
35
 
36
36
  group.bench_with_input(BenchmarkId::new("scalar", dim), dim, |bench, _| {
37
37
  bench.iter(|| black_box(SquaredEuclidean.distance(&a, &b)))
38
38
  });
39
+ let (_, candidate_data) = generate_vectors(4, *dim);
40
+ let candidates: [&[f32]; 4] = std::array::from_fn(|candidate| {
41
+ &candidate_data[candidate * dim..(candidate + 1) * dim]
42
+ });
43
+ group.bench_with_input(BenchmarkId::new("sequential_four", dim), dim, |bench, _| {
44
+ bench.iter(|| {
45
+ black_box(black_box(candidates).map(|candidate| {
46
+ SquaredEuclidean.distance(black_box(&a), candidate)
47
+ }))
48
+ })
49
+ });
50
+ group.bench_with_input(BenchmarkId::new("four", dim), dim, |bench, _| {
51
+ bench.iter(|| black_box(SquaredEuclidean.distance_four(black_box(&a), black_box(candidates))))
52
+ });
39
53
  }
40
54
 
41
55
  group.finish();
42
56
  }
43
57
 
58
+ fn bench_four<D: Distance<f32>>(criterion: &mut Criterion, distance: D) {
59
+ let mut group = criterion.benchmark_group(format!("batched_{}", distance.name()));
60
+ for dim in [100, 256, 784] {
61
+ let (query, candidates) = generate_vectors(4, dim);
62
+ let query = &query[..dim];
63
+ let candidates = std::array::from_fn(|candidate| &candidates[candidate * dim..(candidate + 1) * dim]);
64
+ group.bench_function(BenchmarkId::new("sequential", dim), |bench| {
65
+ bench.iter(|| black_box(black_box(candidates).map(|candidate| distance.distance(black_box(query), candidate))))
66
+ });
67
+ group.bench_function(BenchmarkId::new("four", dim), |bench| {
68
+ bench.iter(|| black_box(distance.distance_four(black_box(query), black_box(candidates))))
69
+ });
70
+ }
71
+ group.finish();
72
+ }
73
+
74
+ fn bench_batched_metrics(criterion: &mut Criterion) {
75
+ bench_four(criterion, Cosine);
76
+ bench_four(criterion, InnerProduct);
77
+ bench_four(criterion, AlternativeDot);
78
+ bench_four(criterion, DirectNormalizedCosine);
79
+ }
80
+
44
81
  fn bench_cosine(c: &mut Criterion) {
45
82
  let mut group = c.benchmark_group("cosine");
46
83
 
@@ -202,6 +239,7 @@ criterion_group!(
202
239
  bench_euclidean,
203
240
  bench_squared_euclidean,
204
241
  bench_cosine,
242
+ bench_batched_metrics,
205
243
  bench_inner_product,
206
244
  bench_alternative_dot,
207
245
  bench_quantized_i8_dot,
@@ -0,0 +1,168 @@
1
+ //! Benchmarks for heap data structures.
2
+
3
+ use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion};
4
+ use rinnd_core::heap::NeighborHeap;
5
+ use rinnd_core::rng::TauRand;
6
+
7
+ fn bench_neighbor_heap_push(c: &mut Criterion) {
8
+ let mut group = c.benchmark_group("neighbor_heap_push");
9
+
10
+ for n_neighbors in [10, 30, 50, 100].iter() {
11
+ let n_points = 1000;
12
+
13
+ group.bench_with_input(
14
+ BenchmarkId::new("random_push", n_neighbors),
15
+ n_neighbors,
16
+ |bench, &k| {
17
+ let mut rng = TauRand::new(42);
18
+ bench.iter(|| {
19
+ let mut heap = NeighborHeap::new(n_points, k);
20
+ // Push random neighbors
21
+ for i in 0..n_points {
22
+ for _ in 0..k * 2 {
23
+ let neighbor = (rng.next_int() as usize) % n_points;
24
+ let dist = (rng.next_int() as f32).abs() / (i32::MAX as f32);
25
+ heap.checked_flagged_push(i, neighbor as i32, dist, true);
26
+ }
27
+ }
28
+ black_box(heap)
29
+ })
30
+ },
31
+ );
32
+ }
33
+
34
+ group.finish();
35
+ }
36
+
37
+ fn bench_neighbor_heap_deheap(c: &mut Criterion) {
38
+ let mut group = c.benchmark_group("neighbor_heap_deheap");
39
+
40
+ for n_neighbors in [10, 30, 50].iter() {
41
+ let n_points = 1000;
42
+
43
+ group.bench_with_input(
44
+ BenchmarkId::new("deheap_sort", n_neighbors),
45
+ n_neighbors,
46
+ |bench, &k| {
47
+ let mut rng = TauRand::new(42);
48
+
49
+ // Pre-build heap
50
+ let mut template_heap = NeighborHeap::new(n_points, k);
51
+ for i in 0..n_points {
52
+ for _ in 0..k * 2 {
53
+ let neighbor = (rng.next_int() as usize) % n_points;
54
+ let dist = (rng.next_int() as f32).abs() / (i32::MAX as f32);
55
+ template_heap.checked_flagged_push(i, neighbor as i32, dist, true);
56
+ }
57
+ }
58
+
59
+ bench.iter(|| {
60
+ let heap = template_heap.clone();
61
+ for point in 0..n_points {
62
+ black_box(heap.deheap_sort(point));
63
+ }
64
+ black_box(heap)
65
+ })
66
+ },
67
+ );
68
+ }
69
+
70
+ group.finish();
71
+ }
72
+
73
+ fn bench_update_replay(criterion: &mut Criterion) {
74
+ #[cfg(feature = "bench-internals")]
75
+ {
76
+ use criterion::BatchSize;
77
+ use rinnd_core::distance::{Distance, SquaredEuclidean};
78
+ use rinnd_core::nndescent::{benchmark, CandidateSets};
79
+ use rinnd_core::rng::FastRng;
80
+
81
+ let mut group = criterion.benchmark_group("update_replay");
82
+ group.sample_size(10);
83
+ for n_points in [256, 4096] {
84
+ let dimension = 100;
85
+ let mut rng = FastRng::new(42);
86
+ let data: Vec<f32> = (0..n_points * dimension).map(|_| rng.next_float()).collect();
87
+ for degree in [15, 30] {
88
+ let mut template = NeighborHeap::new(n_points, degree);
89
+ for point in 0..n_points {
90
+ for _ in 0..degree {
91
+ let neighbor = rng.next_u64() as usize % n_points;
92
+ let distance = SquaredEuclidean.distance(
93
+ &data[point * dimension..(point + 1) * dimension],
94
+ &data[neighbor * dimension..(neighbor + 1) * dimension],
95
+ );
96
+ template.checked_flagged_push(point, neighbor as i32, distance, true);
97
+ }
98
+ }
99
+ for threads in [1, 8] {
100
+ let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).build().unwrap();
101
+ let candidates = pool.install(|| CandidateSets::build_from_graph(
102
+ &mut template.clone(), degree, &mut FastRng::new(42),
103
+ ));
104
+ for packed in [false, true] {
105
+ let layout = if packed { "packed" } else { "wide" };
106
+ let label = format!("{layout}/n{n_points}-k{degree}-t{threads}");
107
+ let stats = pool.install(|| benchmark::buffer_stats(
108
+ &mut template.clone(), &candidates, &data, dimension, &SquaredEuclidean, packed,
109
+ ));
110
+ eprintln!("{label}: {stats:?}");
111
+ group.bench_function(label, |bench| {
112
+ bench.iter_batched(
113
+ || template.clone(),
114
+ |mut graph| pool.install(|| {
115
+ black_box(benchmark::replay(
116
+ &mut graph, &candidates, &data, dimension, &SquaredEuclidean, packed,
117
+ ));
118
+ black_box(graph)
119
+ }),
120
+ BatchSize::LargeInput,
121
+ );
122
+ });
123
+ }
124
+ }
125
+ }
126
+ }
127
+ group.finish();
128
+ }
129
+ #[cfg(not(feature = "bench-internals"))]
130
+ let _ = criterion;
131
+ }
132
+
133
+ fn bench_candidate_membership(criterion: &mut Criterion) {
134
+ #[cfg(feature = "bench-internals")]
135
+ {
136
+ use criterion::BatchSize;
137
+ use rinnd_core::nndescent::CandidateSets;
138
+ use rinnd_core::rng::FastRng;
139
+
140
+ let mut group = criterion.benchmark_group("candidate_membership");
141
+ for width in [15, 30, 60] {
142
+ let mut rng = FastRng::new(89);
143
+ let updates: Vec<(f32, i32)> = (0..width * 4)
144
+ .map(|_| (rng.next_float(), (rng.next_u64() % (width * 3) as u64) as i32)).collect();
145
+ for vector in [false, true] {
146
+ group.bench_function(format!("{}-k{width}", if vector { "reduction" } else { "scalar" }), |bench| {
147
+ bench.iter_batched(|| (vec![f32::INFINITY; width], vec![-1; width]),
148
+ |(mut priorities, mut indices)| {
149
+ CandidateSets::replay_heap_updates(&mut priorities, &mut indices, black_box(&updates), vector);
150
+ black_box((priorities, indices))
151
+ }, BatchSize::SmallInput);
152
+ });
153
+ }
154
+ }
155
+ group.finish();
156
+ }
157
+ #[cfg(not(feature = "bench-internals"))]
158
+ let _ = criterion;
159
+ }
160
+
161
+ criterion_group!(
162
+ benches,
163
+ bench_neighbor_heap_push,
164
+ bench_neighbor_heap_deheap,
165
+ bench_update_replay,
166
+ bench_candidate_membership,
167
+ );
168
+ criterion_main!(benches);
@@ -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
+ }
@@ -104,6 +104,19 @@ unsafe fn horizontal_sum_avx(value: std::arch::x86_64::__m256) -> f32 {
104
104
  }
105
105
 
106
106
  impl Distance<f32> for AlternativeDot {
107
+ const USE_DISTANCE_FOUR: bool = cfg!(feature = "batched-angular");
108
+
109
+ #[inline]
110
+ fn distance_four(&self, query: &[f32], candidates: [&[f32]; 4]) -> [f32; 4] {
111
+ normalized_dot_four(query, candidates).map(alternative_dot_from_similarity)
112
+ }
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
+
107
120
  #[inline]
108
121
  fn distance(&self, a: &[f32], b: &[f32]) -> f32 {
109
122
  debug_assert_eq!(a.len(), b.len());
@@ -131,6 +144,19 @@ impl Distance<f32> for AlternativeDot {
131
144
  pub struct DirectNormalizedCosine;
132
145
 
133
146
  impl Distance<f32> for DirectNormalizedCosine {
147
+ const USE_DISTANCE_FOUR: bool = cfg!(feature = "batched-angular");
148
+
149
+ #[inline]
150
+ fn distance_four(&self, query: &[f32], candidates: [&[f32]; 4]) -> [f32; 4] {
151
+ normalized_dot_four(query, candidates).map(|similarity| 1.0 - similarity.clamp(-1.0, 1.0))
152
+ }
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
+
134
160
  #[inline]
135
161
  fn distance(&self, a: &[f32], b: &[f32]) -> f32 {
136
162
  debug_assert_eq!(a.len(), b.len());
@@ -153,6 +179,62 @@ impl Distance<f32> for DirectNormalizedCosine {
153
179
  }
154
180
  }
155
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
+
195
+ #[inline]
196
+ fn normalized_dot_four(query: &[f32], candidates: [&[f32]; 4]) -> [f32; 4] {
197
+ for candidate in candidates {
198
+ assert_eq!(query.len(), candidate.len());
199
+ }
200
+ #[cfg(target_arch = "x86_64")]
201
+ if is_x86_feature_detected!("avx2") && is_x86_feature_detected!("fma") {
202
+ unsafe {
203
+ let first = normalized_dot_two_avx2(query, [candidates[0], candidates[1]]);
204
+ let second = normalized_dot_two_avx2(query, [candidates[2], candidates[3]]);
205
+ return [first[0], first[1], second[0], second[1]];
206
+ }
207
+ }
208
+ candidates.map(|candidate| normalized_dot_scalar(query, candidate))
209
+ }
210
+
211
+ #[cfg(target_arch = "x86_64")]
212
+ #[target_feature(enable = "avx2", enable = "fma")]
213
+ unsafe fn normalized_dot_two_avx2(query: &[f32], candidates: [&[f32]; 2]) -> [f32; 2] {
214
+ use std::arch::x86_64::*;
215
+
216
+ let mut sums = [[_mm256_setzero_ps(); 4]; 2];
217
+ let vector_end = query.len() / 32 * 32;
218
+ for offset in (0..vector_end).step_by(32) {
219
+ for lane in 0..4 {
220
+ let query_values = _mm256_loadu_ps(query.as_ptr().add(offset + lane * 8));
221
+ for candidate in 0..2 {
222
+ let values = _mm256_loadu_ps(candidates[candidate].as_ptr().add(offset + lane * 8));
223
+ sums[candidate][lane] = _mm256_fmadd_ps(query_values, values, sums[candidate][lane]);
224
+ }
225
+ }
226
+ }
227
+ let mut results = sums.map(|sum| {
228
+ horizontal_sum_avx(_mm256_add_ps(_mm256_add_ps(sum[0], sum[1]), _mm256_add_ps(sum[2], sum[3])))
229
+ });
230
+ for offset in vector_end..query.len() {
231
+ for candidate in 0..2 {
232
+ results[candidate] += query[offset] * candidates[candidate][offset];
233
+ }
234
+ }
235
+ results
236
+ }
237
+
156
238
  /// Alternative inner product distance using reciprocal transform.
157
239
  ///
158
240
  /// d_alt(a, b) = 1 / (a·b) for positive inner products, FLOAT32_MAX otherwise.
@@ -98,6 +98,20 @@ unsafe fn hsum256_ps(v: std::arch::x86_64::__m256) -> f32 {
98
98
  }
99
99
 
100
100
  impl Distance<f32> for Cosine {
101
+ const USE_DISTANCE_FOUR: bool = cfg!(feature = "batched-angular");
102
+
103
+ #[inline]
104
+ fn distance_four(&self, query: &[f32], candidates: [&[f32]; 4]) -> [f32; 4] {
105
+ for candidate in candidates {
106
+ assert_eq!(query.len(), candidate.len());
107
+ }
108
+ #[cfg(target_arch = "x86_64")]
109
+ if is_x86_feature_detected!("avx2") && is_x86_feature_detected!("fma") {
110
+ return unsafe { cosine_four_avx2(query, candidates) };
111
+ }
112
+ candidates.map(|candidate| scalar_cosine(query, candidate))
113
+ }
114
+
101
115
  #[inline]
102
116
  fn distance(&self, a: &[f32], b: &[f32]) -> f32 {
103
117
  debug_assert_eq!(a.len(), b.len());
@@ -117,6 +131,45 @@ impl Distance<f32> for Cosine {
117
131
  }
118
132
  }
119
133
 
134
+ #[cfg(target_arch = "x86_64")]
135
+ #[target_feature(enable = "avx2", enable = "fma")]
136
+ unsafe fn cosine_four_avx2(query: &[f32], candidates: [&[f32]; 4]) -> [f32; 4] {
137
+ use std::arch::x86_64::*;
138
+
139
+ let mut dots = [_mm256_setzero_ps(); 4];
140
+ let mut norms = [_mm256_setzero_ps(); 4];
141
+ let mut query_norm = _mm256_setzero_ps();
142
+ let vector_end = query.len() / 8 * 8;
143
+ for offset in (0..vector_end).step_by(8) {
144
+ let query_values = _mm256_loadu_ps(query.as_ptr().add(offset));
145
+ query_norm = _mm256_fmadd_ps(query_values, query_values, query_norm);
146
+ for candidate in 0..4 {
147
+ let values = _mm256_loadu_ps(candidates[candidate].as_ptr().add(offset));
148
+ dots[candidate] = _mm256_fmadd_ps(query_values, values, dots[candidate]);
149
+ norms[candidate] = _mm256_fmadd_ps(values, values, norms[candidate]);
150
+ }
151
+ }
152
+ let mut dots = dots.map(|sum| hsum256_ps(sum));
153
+ let mut norms = norms.map(|sum| hsum256_ps(sum));
154
+ let mut query_norm = hsum256_ps(query_norm);
155
+ for offset in vector_end..query.len() {
156
+ query_norm += query[offset] * query[offset];
157
+ for candidate in 0..4 {
158
+ let value = candidates[candidate][offset];
159
+ dots[candidate] += query[offset] * value;
160
+ norms[candidate] += value * value;
161
+ }
162
+ }
163
+ std::array::from_fn(|candidate| {
164
+ let denom = (query_norm * norms[candidate]).sqrt();
165
+ if denom < 1e-12 {
166
+ 1.0
167
+ } else {
168
+ 1.0 - (dots[candidate] / denom).clamp(-1.0, 1.0)
169
+ }
170
+ })
171
+ }
172
+
120
173
  /// Normalize a vector to unit length in-place.
121
174
  #[inline]
122
175
  pub fn normalize_inplace(v: &mut [f32]) {
@@ -12,6 +12,8 @@ use super::traits::{Distance, HasSquaredForm};
12
12
  pub struct SquaredEuclidean;
13
13
 
14
14
  impl Distance<f32> for SquaredEuclidean {
15
+ const USE_DISTANCE_FOUR: bool = cfg!(feature = "batched-euclidean");
16
+
15
17
  #[inline]
16
18
  fn distance(&self, a: &[f32], b: &[f32]) -> f32 {
17
19
  debug_assert_eq!(a.len(), b.len());
@@ -27,11 +29,55 @@ impl Distance<f32> for SquaredEuclidean {
27
29
  scalar_l2_sqr(a, b)
28
30
  }
29
31
 
32
+ #[inline]
33
+ fn distance_four(&self, query: &[f32], candidates: [&[f32]; 4]) -> [f32; 4] {
34
+ for candidate in candidates {
35
+ assert_eq!(query.len(), candidate.len());
36
+ }
37
+ #[cfg(target_arch = "x86_64")]
38
+ {
39
+ if is_x86_feature_detected!("avx2") && is_x86_feature_detected!("fma") {
40
+ return unsafe { l2_sqr_four_avx2(query, candidates) };
41
+ }
42
+ }
43
+ candidates.map(|candidate| scalar_l2_sqr(query, candidate))
44
+ }
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
+
30
51
  fn name(&self) -> &'static str {
31
52
  "squared_euclidean"
32
53
  }
33
54
  }
34
55
 
56
+ #[cfg(target_arch = "x86_64")]
57
+ #[target_feature(enable = "avx2", enable = "fma")]
58
+ unsafe fn l2_sqr_four_avx2(query: &[f32], candidates: [&[f32]; 4]) -> [f32; 4] {
59
+ use std::arch::x86_64::*;
60
+
61
+ let mut sums = [_mm256_setzero_ps(); 4];
62
+ let vector_end = query.len() / 8 * 8;
63
+ for offset in (0..vector_end).step_by(8) {
64
+ let query_values = _mm256_loadu_ps(query.as_ptr().add(offset));
65
+ for candidate in 0..4 {
66
+ let values = _mm256_loadu_ps(candidates[candidate].as_ptr().add(offset));
67
+ let difference = _mm256_sub_ps(query_values, values);
68
+ sums[candidate] = _mm256_fmadd_ps(difference, difference, sums[candidate]);
69
+ }
70
+ }
71
+ let mut results = sums.map(|sum| hsum256_ps_avx(sum));
72
+ for offset in vector_end..query.len() {
73
+ for candidate in 0..4 {
74
+ let difference = query[offset] - candidates[candidate][offset];
75
+ results[candidate] += difference * difference;
76
+ }
77
+ }
78
+ results
79
+ }
80
+
35
81
  /// Scalar squared Euclidean distance (fallback).
36
82
  #[inline]
37
83
  fn scalar_l2_sqr(a: &[f32], b: &[f32]) -> f32 {
@@ -116,6 +162,13 @@ unsafe fn hsum256_ps_avx(v: std::arch::x86_64::__m256) -> f32 {
116
162
  pub struct Euclidean;
117
163
 
118
164
  impl Distance<f32> for Euclidean {
165
+ const USE_DISTANCE_FOUR: bool = SquaredEuclidean::USE_DISTANCE_FOUR;
166
+
167
+ #[inline]
168
+ fn distance_four(&self, query: &[f32], candidates: [&[f32]; 4]) -> [f32; 4] {
169
+ SquaredEuclidean.distance_four(query, candidates).map(f32::sqrt)
170
+ }
171
+
119
172
  #[inline]
120
173
  fn distance(&self, a: &[f32], b: &[f32]) -> f32 {
121
174
  SquaredEuclidean.distance(a, b).sqrt()
@@ -184,6 +237,24 @@ pub mod simd {
184
237
  mod tests {
185
238
  use super::*;
186
239
 
240
+ #[test]
241
+ fn four_distances_match_individual_bits() {
242
+ for dimension in (0..40).chain([100, 256, 784, 785, 1024]) {
243
+ let query: Vec<f32> = (0..dimension)
244
+ .map(|position| (position as f32 * 0.19).sin() * 255.0)
245
+ .collect();
246
+ let candidates: [Vec<f32>; 4] = std::array::from_fn(|candidate| {
247
+ (0..dimension)
248
+ .map(|position| ((position + candidate * 17) as f32 * 0.31).cos() * 255.0)
249
+ .collect()
250
+ });
251
+ let slices: [&[f32]; 4] = std::array::from_fn(|i| candidates[i].as_slice());
252
+ let actual = SquaredEuclidean.distance_four(&query, slices);
253
+ let expected = slices.map(|candidate| SquaredEuclidean.distance(&query, candidate));
254
+ assert_eq!(actual.map(f32::to_bits), expected.map(f32::to_bits), "dimension={dimension}");
255
+ }
256
+ }
257
+
187
258
  #[test]
188
259
  fn test_squared_euclidean_basic() {
189
260
  let a = vec![1.0, 0.0, 0.0];