rinnd 0.2.0__tar.gz → 0.3.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.
- {rinnd-0.2.0 → rinnd-0.3.1}/Cargo.toml +1 -1
- {rinnd-0.2.0 → rinnd-0.3.1}/PKG-INFO +1 -1
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd/Cargo.toml +7 -1
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd/src/lib.rs +20 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-core/Cargo.toml +8 -1
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-core/benches/distance.rs +39 -1
- rinnd-0.3.1/crates/rinnd-core/benches/heap.rs +168 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-core/src/distance/alternatives.rs +57 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-core/src/distance/cosine.rs +53 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-core/src/distance/euclidean.rs +66 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-core/src/distance/inner_product.rs +49 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-core/src/distance/mod.rs +25 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-core/src/distance/traits.rs +6 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-core/src/heap/neighbor_heap.rs +47 -30
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-core/src/index.rs +58 -1
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-core/src/nndescent/candidates.rs +324 -28
- rinnd-0.3.1/crates/rinnd-core/src/nndescent/mod.rs +1430 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-core/src/search/greedy.rs +135 -9
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-core/src/tree/builder.rs +80 -5
- {rinnd-0.2.0 → rinnd-0.3.1}/pyproject.toml +1 -1
- rinnd-0.2.0/crates/rinnd-core/benches/heap.rs +0 -78
- rinnd-0.2.0/crates/rinnd-core/src/nndescent/mod.rs +0 -661
- {rinnd-0.2.0 → rinnd-0.3.1}/Cargo.lock +0 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-core/src/distance/angular.rs +0 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-core/src/distance/binary.rs +0 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-core/src/distance/hellinger.rs +0 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-core/src/distance/minkowski.rs +0 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-core/src/distance/quantized.rs +0 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-core/src/graph/mod.rs +0 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-core/src/graph/neighbor_graph.rs +0 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-core/src/graph/search_graph.rs +0 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-core/src/heap/candidate_heap.rs +0 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-core/src/heap/mod.rs +0 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-core/src/lib.rs +0 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-core/src/nndescent/update.rs +0 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-core/src/rng.rs +0 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-core/src/search/mod.rs +0 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-core/src/tree/breadth_first.rs +0 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-core/src/tree/flat_tree.rs +0 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-core/src/tree/mod.rs +0 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-core/src/visited.rs +0 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-simd/Cargo.toml +0 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-simd/benches/simd_distance.rs +0 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-simd/src/avx2.rs +0 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-simd/src/avx512.rs +0 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-simd/src/detect.rs +0 -0
- {rinnd-0.2.0 → rinnd-0.3.1}/crates/rinnd-simd/src/lib.rs +0 -0
|
@@ -12,8 +12,14 @@ rust-version.workspace = true
|
|
|
12
12
|
name = "rinnd"
|
|
13
13
|
crate-type = ["cdylib"]
|
|
14
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
|
+
|
|
15
21
|
[dependencies]
|
|
16
|
-
rinnd-core = { path = "../rinnd-core", features = ["rayon"] }
|
|
22
|
+
rinnd-core = { path = "../rinnd-core", default-features = false, features = ["std", "rayon"] }
|
|
17
23
|
rinnd-simd = { path = "../rinnd-simd" }
|
|
18
24
|
pyo3 = { workspace = true }
|
|
19
25
|
numpy = { workspace = true }
|
|
@@ -1413,6 +1413,26 @@ 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
|
+
"update_generation_seconds",
|
|
1430
|
+
stats.nn_descent.update_generation_seconds.clone(),
|
|
1431
|
+
)?;
|
|
1432
|
+
result.set_item(
|
|
1433
|
+
"update_application_seconds",
|
|
1434
|
+
stats.nn_descent.update_application_seconds.clone(),
|
|
1435
|
+
)?;
|
|
1416
1436
|
result.set_item("updates", stats.nn_descent.updates.clone())?;
|
|
1417
1437
|
result.set_item("nn_descent_seconds", stats.nn_descent.total_seconds())?;
|
|
1418
1438
|
result.set_item("sort_seconds", stats.sort_seconds)?;
|
|
@@ -9,12 +9,19 @@ 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"]
|
|
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
|
+
candidate-workspace = []
|
|
23
|
+
batched-leaves = []
|
|
24
|
+
packed-updates = []
|
|
18
25
|
|
|
19
26
|
[dependencies]
|
|
20
27
|
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);
|
|
@@ -104,6 +104,13 @@ 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
|
+
|
|
107
114
|
#[inline]
|
|
108
115
|
fn distance(&self, a: &[f32], b: &[f32]) -> f32 {
|
|
109
116
|
debug_assert_eq!(a.len(), b.len());
|
|
@@ -131,6 +138,13 @@ impl Distance<f32> for AlternativeDot {
|
|
|
131
138
|
pub struct DirectNormalizedCosine;
|
|
132
139
|
|
|
133
140
|
impl Distance<f32> for DirectNormalizedCosine {
|
|
141
|
+
const USE_DISTANCE_FOUR: bool = cfg!(feature = "batched-angular");
|
|
142
|
+
|
|
143
|
+
#[inline]
|
|
144
|
+
fn distance_four(&self, query: &[f32], candidates: [&[f32]; 4]) -> [f32; 4] {
|
|
145
|
+
normalized_dot_four(query, candidates).map(|similarity| 1.0 - similarity.clamp(-1.0, 1.0))
|
|
146
|
+
}
|
|
147
|
+
|
|
134
148
|
#[inline]
|
|
135
149
|
fn distance(&self, a: &[f32], b: &[f32]) -> f32 {
|
|
136
150
|
debug_assert_eq!(a.len(), b.len());
|
|
@@ -153,6 +167,49 @@ impl Distance<f32> for DirectNormalizedCosine {
|
|
|
153
167
|
}
|
|
154
168
|
}
|
|
155
169
|
|
|
170
|
+
#[inline]
|
|
171
|
+
fn normalized_dot_four(query: &[f32], candidates: [&[f32]; 4]) -> [f32; 4] {
|
|
172
|
+
for candidate in candidates {
|
|
173
|
+
assert_eq!(query.len(), candidate.len());
|
|
174
|
+
}
|
|
175
|
+
#[cfg(target_arch = "x86_64")]
|
|
176
|
+
if is_x86_feature_detected!("avx2") && is_x86_feature_detected!("fma") {
|
|
177
|
+
unsafe {
|
|
178
|
+
let first = normalized_dot_two_avx2(query, [candidates[0], candidates[1]]);
|
|
179
|
+
let second = normalized_dot_two_avx2(query, [candidates[2], candidates[3]]);
|
|
180
|
+
return [first[0], first[1], second[0], second[1]];
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
candidates.map(|candidate| normalized_dot_scalar(query, candidate))
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
#[cfg(target_arch = "x86_64")]
|
|
187
|
+
#[target_feature(enable = "avx2", enable = "fma")]
|
|
188
|
+
unsafe fn normalized_dot_two_avx2(query: &[f32], candidates: [&[f32]; 2]) -> [f32; 2] {
|
|
189
|
+
use std::arch::x86_64::*;
|
|
190
|
+
|
|
191
|
+
let mut sums = [[_mm256_setzero_ps(); 4]; 2];
|
|
192
|
+
let vector_end = query.len() / 32 * 32;
|
|
193
|
+
for offset in (0..vector_end).step_by(32) {
|
|
194
|
+
for lane in 0..4 {
|
|
195
|
+
let query_values = _mm256_loadu_ps(query.as_ptr().add(offset + lane * 8));
|
|
196
|
+
for candidate in 0..2 {
|
|
197
|
+
let values = _mm256_loadu_ps(candidates[candidate].as_ptr().add(offset + lane * 8));
|
|
198
|
+
sums[candidate][lane] = _mm256_fmadd_ps(query_values, values, sums[candidate][lane]);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
let mut results = sums.map(|sum| {
|
|
203
|
+
horizontal_sum_avx(_mm256_add_ps(_mm256_add_ps(sum[0], sum[1]), _mm256_add_ps(sum[2], sum[3])))
|
|
204
|
+
});
|
|
205
|
+
for offset in vector_end..query.len() {
|
|
206
|
+
for candidate in 0..2 {
|
|
207
|
+
results[candidate] += query[offset] * candidates[candidate][offset];
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
results
|
|
211
|
+
}
|
|
212
|
+
|
|
156
213
|
/// Alternative inner product distance using reciprocal transform.
|
|
157
214
|
///
|
|
158
215
|
/// 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,50 @@ 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
|
+
|
|
30
46
|
fn name(&self) -> &'static str {
|
|
31
47
|
"squared_euclidean"
|
|
32
48
|
}
|
|
33
49
|
}
|
|
34
50
|
|
|
51
|
+
#[cfg(target_arch = "x86_64")]
|
|
52
|
+
#[target_feature(enable = "avx2", enable = "fma")]
|
|
53
|
+
unsafe fn l2_sqr_four_avx2(query: &[f32], candidates: [&[f32]; 4]) -> [f32; 4] {
|
|
54
|
+
use std::arch::x86_64::*;
|
|
55
|
+
|
|
56
|
+
let mut sums = [_mm256_setzero_ps(); 4];
|
|
57
|
+
let vector_end = query.len() / 8 * 8;
|
|
58
|
+
for offset in (0..vector_end).step_by(8) {
|
|
59
|
+
let query_values = _mm256_loadu_ps(query.as_ptr().add(offset));
|
|
60
|
+
for candidate in 0..4 {
|
|
61
|
+
let values = _mm256_loadu_ps(candidates[candidate].as_ptr().add(offset));
|
|
62
|
+
let difference = _mm256_sub_ps(query_values, values);
|
|
63
|
+
sums[candidate] = _mm256_fmadd_ps(difference, difference, sums[candidate]);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
let mut results = sums.map(|sum| hsum256_ps_avx(sum));
|
|
67
|
+
for offset in vector_end..query.len() {
|
|
68
|
+
for candidate in 0..4 {
|
|
69
|
+
let difference = query[offset] - candidates[candidate][offset];
|
|
70
|
+
results[candidate] += difference * difference;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
results
|
|
74
|
+
}
|
|
75
|
+
|
|
35
76
|
/// Scalar squared Euclidean distance (fallback).
|
|
36
77
|
#[inline]
|
|
37
78
|
fn scalar_l2_sqr(a: &[f32], b: &[f32]) -> f32 {
|
|
@@ -116,6 +157,13 @@ unsafe fn hsum256_ps_avx(v: std::arch::x86_64::__m256) -> f32 {
|
|
|
116
157
|
pub struct Euclidean;
|
|
117
158
|
|
|
118
159
|
impl Distance<f32> for Euclidean {
|
|
160
|
+
const USE_DISTANCE_FOUR: bool = SquaredEuclidean::USE_DISTANCE_FOUR;
|
|
161
|
+
|
|
162
|
+
#[inline]
|
|
163
|
+
fn distance_four(&self, query: &[f32], candidates: [&[f32]; 4]) -> [f32; 4] {
|
|
164
|
+
SquaredEuclidean.distance_four(query, candidates).map(f32::sqrt)
|
|
165
|
+
}
|
|
166
|
+
|
|
119
167
|
#[inline]
|
|
120
168
|
fn distance(&self, a: &[f32], b: &[f32]) -> f32 {
|
|
121
169
|
SquaredEuclidean.distance(a, b).sqrt()
|
|
@@ -184,6 +232,24 @@ pub mod simd {
|
|
|
184
232
|
mod tests {
|
|
185
233
|
use super::*;
|
|
186
234
|
|
|
235
|
+
#[test]
|
|
236
|
+
fn four_distances_match_individual_bits() {
|
|
237
|
+
for dimension in (0..40).chain([100, 256, 784, 785, 1024]) {
|
|
238
|
+
let query: Vec<f32> = (0..dimension)
|
|
239
|
+
.map(|position| (position as f32 * 0.19).sin() * 255.0)
|
|
240
|
+
.collect();
|
|
241
|
+
let candidates: [Vec<f32>; 4] = std::array::from_fn(|candidate| {
|
|
242
|
+
(0..dimension)
|
|
243
|
+
.map(|position| ((position + candidate * 17) as f32 * 0.31).cos() * 255.0)
|
|
244
|
+
.collect()
|
|
245
|
+
});
|
|
246
|
+
let slices: [&[f32]; 4] = std::array::from_fn(|i| candidates[i].as_slice());
|
|
247
|
+
let actual = SquaredEuclidean.distance_four(&query, slices);
|
|
248
|
+
let expected = slices.map(|candidate| SquaredEuclidean.distance(&query, candidate));
|
|
249
|
+
assert_eq!(actual.map(f32::to_bits), expected.map(f32::to_bits), "dimension={dimension}");
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
187
253
|
#[test]
|
|
188
254
|
fn test_squared_euclidean_basic() {
|
|
189
255
|
let a = vec![1.0, 0.0, 0.0];
|
|
@@ -94,6 +94,13 @@ fn dot_product(a: &[f32], b: &[f32]) -> f32 {
|
|
|
94
94
|
}
|
|
95
95
|
|
|
96
96
|
impl Distance<f32> for InnerProduct {
|
|
97
|
+
const USE_DISTANCE_FOUR: bool = cfg!(feature = "batched-angular");
|
|
98
|
+
|
|
99
|
+
#[inline]
|
|
100
|
+
fn distance_four(&self, query: &[f32], candidates: [&[f32]; 4]) -> [f32; 4] {
|
|
101
|
+
dot_product_four(query, candidates).map(|dot| -dot)
|
|
102
|
+
}
|
|
103
|
+
|
|
97
104
|
#[inline]
|
|
98
105
|
fn distance(&self, a: &[f32], b: &[f32]) -> f32 {
|
|
99
106
|
let dot = dot_product(a, b);
|
|
@@ -113,6 +120,13 @@ impl Distance<f32> for InnerProduct {
|
|
|
113
120
|
pub struct Dot;
|
|
114
121
|
|
|
115
122
|
impl Distance<f32> for Dot {
|
|
123
|
+
const USE_DISTANCE_FOUR: bool = cfg!(feature = "batched-angular");
|
|
124
|
+
|
|
125
|
+
#[inline]
|
|
126
|
+
fn distance_four(&self, query: &[f32], candidates: [&[f32]; 4]) -> [f32; 4] {
|
|
127
|
+
dot_product_four(query, candidates).map(|dot| if dot <= 0.0 { 1.0 } else { 1.0 - dot })
|
|
128
|
+
}
|
|
129
|
+
|
|
116
130
|
#[inline]
|
|
117
131
|
fn distance(&self, a: &[f32], b: &[f32]) -> f32 {
|
|
118
132
|
let dot = dot_product(a, b);
|
|
@@ -128,6 +142,41 @@ impl Distance<f32> for Dot {
|
|
|
128
142
|
}
|
|
129
143
|
}
|
|
130
144
|
|
|
145
|
+
#[inline]
|
|
146
|
+
fn dot_product_four(query: &[f32], candidates: [&[f32]; 4]) -> [f32; 4] {
|
|
147
|
+
for candidate in candidates {
|
|
148
|
+
assert_eq!(query.len(), candidate.len());
|
|
149
|
+
}
|
|
150
|
+
#[cfg(target_arch = "x86_64")]
|
|
151
|
+
if is_x86_feature_detected!("avx2") && is_x86_feature_detected!("fma") {
|
|
152
|
+
return unsafe { dot_four_avx2(query, candidates) };
|
|
153
|
+
}
|
|
154
|
+
candidates.map(|candidate| scalar_dot(query, candidate))
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
#[cfg(target_arch = "x86_64")]
|
|
158
|
+
#[target_feature(enable = "avx2", enable = "fma")]
|
|
159
|
+
unsafe fn dot_four_avx2(query: &[f32], candidates: [&[f32]; 4]) -> [f32; 4] {
|
|
160
|
+
use std::arch::x86_64::*;
|
|
161
|
+
|
|
162
|
+
let mut sums = [_mm256_setzero_ps(); 4];
|
|
163
|
+
let vector_end = query.len() / 8 * 8;
|
|
164
|
+
for offset in (0..vector_end).step_by(8) {
|
|
165
|
+
let query_values = _mm256_loadu_ps(query.as_ptr().add(offset));
|
|
166
|
+
for candidate in 0..4 {
|
|
167
|
+
let values = _mm256_loadu_ps(candidates[candidate].as_ptr().add(offset));
|
|
168
|
+
sums[candidate] = _mm256_fmadd_ps(query_values, values, sums[candidate]);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
let mut results = sums.map(|sum| hsum256_ps(sum));
|
|
172
|
+
for offset in vector_end..query.len() {
|
|
173
|
+
for candidate in 0..4 {
|
|
174
|
+
results[candidate] += query[offset] * candidates[candidate][offset];
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
results
|
|
178
|
+
}
|
|
179
|
+
|
|
131
180
|
/// Raw dot product (not negated).
|
|
132
181
|
///
|
|
133
182
|
/// This computes the standard dot product without negation.
|
|
@@ -259,6 +259,31 @@ impl Metric {
|
|
|
259
259
|
mod tests {
|
|
260
260
|
use super::*;
|
|
261
261
|
|
|
262
|
+
fn assert_four_matches_individual<D: Distance<f32>>(distance: D) {
|
|
263
|
+
for dim in (0..40).chain([63, 64, 65, 100, 127, 128, 129, 256, 784, 1024]) {
|
|
264
|
+
let query: Vec<f32> = (0..dim).map(|offset| (offset as f32 * 0.37).sin()).collect();
|
|
265
|
+
let other: Vec<f32> = (0..dim).map(|offset| (offset as f32 * 0.19).cos()).collect();
|
|
266
|
+
let opposite: Vec<f32> = query.iter().map(|value| -value).collect();
|
|
267
|
+
let zero = vec![0.0; dim];
|
|
268
|
+
let candidates = [query.as_slice(), other.as_slice(), opposite.as_slice(), zero.as_slice()];
|
|
269
|
+
for input in [query.as_slice(), zero.as_slice()] {
|
|
270
|
+
let actual = distance.distance_four(input, candidates);
|
|
271
|
+
let expected = candidates.map(|candidate| distance.distance(input, candidate));
|
|
272
|
+
assert_eq!(actual.map(f32::to_bits), expected.map(f32::to_bits), "{} dim={dim}", distance.name());
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
#[test]
|
|
278
|
+
fn batched_metric_bits_match() {
|
|
279
|
+
assert_four_matches_individual(Cosine);
|
|
280
|
+
assert_four_matches_individual(InnerProduct);
|
|
281
|
+
assert_four_matches_individual(Dot);
|
|
282
|
+
assert_four_matches_individual(AlternativeDot);
|
|
283
|
+
assert_four_matches_individual(DirectNormalizedCosine);
|
|
284
|
+
assert_four_matches_individual(Euclidean);
|
|
285
|
+
}
|
|
286
|
+
|
|
262
287
|
#[test]
|
|
263
288
|
fn test_metric_from_str() {
|
|
264
289
|
assert_eq!(Metric::from_str("euclidean"), Some(Metric::Euclidean));
|
|
@@ -5,6 +5,8 @@
|
|
|
5
5
|
/// Implementations should be thread-safe (Send + Sync) to support
|
|
6
6
|
/// parallel computation.
|
|
7
7
|
pub trait Distance<T>: Send + Sync + Clone {
|
|
8
|
+
const USE_DISTANCE_FOUR: bool = false;
|
|
9
|
+
|
|
8
10
|
/// Compute the distance between two vectors.
|
|
9
11
|
///
|
|
10
12
|
/// # Arguments
|
|
@@ -15,6 +17,10 @@ pub trait Distance<T>: Send + Sync + Clone {
|
|
|
15
17
|
/// The distance as a f32. Lower values indicate more similarity.
|
|
16
18
|
fn distance(&self, a: &[T], b: &[T]) -> f32;
|
|
17
19
|
|
|
20
|
+
fn distance_four(&self, query: &[T], candidates: [&[T]; 4]) -> [f32; 4] {
|
|
21
|
+
candidates.map(|candidate| self.distance(query, candidate))
|
|
22
|
+
}
|
|
23
|
+
|
|
18
24
|
/// Compute distances from one query to multiple data points.
|
|
19
25
|
///
|
|
20
26
|
/// Default implementation calls `distance` in a loop.
|