1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
//! Distance metrics for vector similarity calculation.
#[cfg(not(target_arch = "wasm32"))]
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use crate::error::{LaurusError, Result};
/// Distance metrics for vector similarity calculation.
#[derive(
Debug,
Clone,
Copy,
PartialEq,
Eq,
Serialize,
Deserialize,
Default,
rkyv::Archive,
rkyv::Serialize,
rkyv::Deserialize,
)]
pub enum DistanceMetric {
/// Cosine distance (1 - cosine similarity)
#[default]
Cosine,
/// Euclidean (L2) distance
Euclidean,
/// Manhattan (L1) distance
Manhattan,
/// Dot product distance.
///
/// Computed as `-(a . b)` (negated dot product) so that smaller values
/// indicate more similar vectors, consistent with the other distance
/// metrics. Raw dot product similarity is higher for more similar vectors,
/// so the negation converts it into a distance. This means the returned
/// distance values are typically **negative** for vectors with positive
/// dot product similarity.
DotProduct,
/// Angular distance
Angular,
}
impl DistanceMetric {
/// Calculate the distance between two vectors using this metric.
///
/// Lower values indicate more similar vectors for all metrics. For
/// [`DotProduct`](Self::DotProduct), the result is `-(a . b)`, which is
/// typically negative when vectors have positive similarity.
///
/// # Arguments
///
/// * `a` - The first vector (as a float slice).
/// * `b` - The second vector (as a float slice). Must have the same length
/// as `a`.
///
/// # Returns
///
/// The distance between the two vectors according to this metric.
///
/// # Errors
///
/// Returns an error if the two vectors have different dimensions.
pub fn distance(&self, a: &[f32], b: &[f32]) -> Result<f32> {
if a.len() != b.len() {
return Err(LaurusError::InvalidOperation(
"Vector dimensions must match for distance calculation".to_string(),
));
}
let result = match self {
DistanceMetric::Cosine => {
let (dot_product, norm_a_sq, norm_b_sq) = self.simd_dot_and_norms(a, b);
let norm_a = norm_a_sq.sqrt();
let norm_b = norm_b_sq.sqrt();
if norm_a == 0.0 || norm_b == 0.0 {
1.0 // Maximum distance for zero vectors
} else {
let cosine = (dot_product / (norm_a * norm_b)).clamp(-1.0, 1.0);
1.0 - cosine
}
}
DistanceMetric::Euclidean => self.simd_euclidean_sq(a, b).sqrt(),
DistanceMetric::Manhattan => self.simd_manhattan(a, b),
DistanceMetric::DotProduct => -self.simd_dot_product(a, b),
DistanceMetric::Angular => {
let (dot_product, norm_a_sq, norm_b_sq) = self.simd_dot_and_norms(a, b);
let norm_a = norm_a_sq.sqrt();
let norm_b = norm_b_sq.sqrt();
if norm_a == 0.0 || norm_b == 0.0 {
std::f32::consts::PI
} else {
let cosine = (dot_product / (norm_a * norm_b)).clamp(-1.0, 1.0);
cosine.acos()
}
}
};
Ok(result)
}
/// Calculate dot product and squared norms in a single pass using SIMD.
fn simd_dot_and_norms(&self, a: &[f32], b: &[f32]) -> (f32, f32, f32) {
use wide::f32x8;
let mut dot_sum = f32x8::ZERO;
let mut norm_a_sum = f32x8::ZERO;
let mut norm_b_sum = f32x8::ZERO;
let chunks_a = a.chunks_exact(8);
let chunks_b = b.chunks_exact(8);
let rem_a = chunks_a.remainder();
let rem_b = chunks_b.remainder();
for (ca, cb) in chunks_a.zip(chunks_b) {
let va = f32x8::from(ca);
let vb = f32x8::from(cb);
dot_sum += va * vb;
norm_a_sum += va * va;
norm_b_sum += vb * vb;
}
let mut dot_product: f32 = dot_sum.reduce_add();
let mut norm_a_sq: f32 = norm_a_sum.reduce_add();
let mut norm_b_sq: f32 = norm_b_sum.reduce_add();
// Tail
for (x, y) in rem_a.iter().zip(rem_b.iter()) {
dot_product += x * y;
norm_a_sq += x * x;
norm_b_sq += y * y;
}
(dot_product, norm_a_sq, norm_b_sq)
}
/// Calculate dot product using SIMD.
fn simd_dot_product(&self, a: &[f32], b: &[f32]) -> f32 {
use wide::f32x8;
let mut sum = f32x8::ZERO;
let chunks_a = a.chunks_exact(8);
let chunks_b = b.chunks_exact(8);
let rem_a = chunks_a.remainder();
let rem_b = chunks_b.remainder();
for (ca, cb) in chunks_a.zip(chunks_b) {
sum += f32x8::from(ca) * f32x8::from(cb);
}
let mut dot_product: f32 = sum.reduce_add();
for (x, y) in rem_a.iter().zip(rem_b.iter()) {
dot_product += x * y;
}
dot_product
}
/// Calculate squared Euclidean distance using SIMD.
fn simd_euclidean_sq(&self, a: &[f32], b: &[f32]) -> f32 {
use wide::f32x8;
let mut sum = f32x8::ZERO;
let chunks_a = a.chunks_exact(8);
let chunks_b = b.chunks_exact(8);
let rem_a = chunks_a.remainder();
let rem_b = chunks_b.remainder();
for (ca, cb) in chunks_a.zip(chunks_b) {
let diff = f32x8::from(ca) - f32x8::from(cb);
sum += diff * diff;
}
let mut dist_sq: f32 = sum.reduce_add();
for (x, y) in rem_a.iter().zip(rem_b.iter()) {
dist_sq += (x - y).powi(2);
}
dist_sq
}
/// Calculate Manhattan distance using SIMD.
fn simd_manhattan(&self, a: &[f32], b: &[f32]) -> f32 {
use wide::f32x8;
let mut sum = f32x8::ZERO;
let chunks_a = a.chunks_exact(8);
let chunks_b = b.chunks_exact(8);
let rem_a = chunks_a.remainder();
let rem_b = chunks_b.remainder();
for (ca, cb) in chunks_a.zip(chunks_b) {
let va = f32x8::from(ca);
let vb = f32x8::from(cb);
sum += (va - vb).abs();
}
let mut dist: f32 = sum.reduce_add();
for (x, y) in rem_a.iter().zip(rem_b.iter()) {
dist += (x - y).abs();
}
dist
}
/// Calculate similarity (0-1, higher is more similar) between two vectors.
pub fn similarity(&self, a: &[f32], b: &[f32]) -> Result<f32> {
let distance = self.distance(a, b)?;
let similarity = match self {
DistanceMetric::Cosine => 1.0 - distance,
DistanceMetric::Euclidean => (-distance).exp(),
DistanceMetric::Manhattan => (-distance).exp(),
DistanceMetric::DotProduct => -distance,
DistanceMetric::Angular => 1.0 - (distance / std::f32::consts::PI),
};
Ok(similarity.clamp(0.0, 1.0))
}
/// Convert a pre-computed distance value to a similarity score without
/// re-reading the original vectors.
///
/// This is the pure-arithmetic inverse of the per-metric transform applied
/// in [`distance()`](Self::distance), so it is **much** cheaper than calling
/// [`similarity()`](Self::similarity) (which reloads both vectors and
/// recomputes dot products / norms).
///
/// # Arguments
///
/// * `distance` - A distance value previously returned by
/// [`distance()`](Self::distance) for the same metric.
///
/// # Returns
///
/// A similarity score in [0, 1] (higher is more similar).
pub fn distance_to_similarity(&self, distance: f32) -> f32 {
let similarity = match self {
DistanceMetric::Cosine => 1.0 - distance,
DistanceMetric::Euclidean => (-distance).exp(),
DistanceMetric::Manhattan => (-distance).exp(),
DistanceMetric::DotProduct => -distance,
DistanceMetric::Angular => 1.0 - (distance / std::f32::consts::PI),
};
similarity.clamp(0.0, 1.0)
}
/// Get the name of this distance metric.
pub fn name(&self) -> &'static str {
match self {
DistanceMetric::Cosine => "cosine",
DistanceMetric::Euclidean => "euclidean",
DistanceMetric::Manhattan => "manhattan",
DistanceMetric::DotProduct => "dot_product",
DistanceMetric::Angular => "angular",
}
}
/// Parse a distance metric from a string.
pub fn parse_str(s: &str) -> Result<Self> {
match s.to_lowercase().as_str() {
"cosine" => Ok(DistanceMetric::Cosine),
"euclidean" | "l2" => Ok(DistanceMetric::Euclidean),
"manhattan" | "l1" => Ok(DistanceMetric::Manhattan),
"dot_product" | "dot" => Ok(DistanceMetric::DotProduct),
"angular" => Ok(DistanceMetric::Angular),
_ => Err(LaurusError::InvalidOperation(format!(
"Unknown distance metric: {s}"
))),
}
}
/// Calculate distance between a query vector and multiple vectors in parallel.
pub fn batch_distance_parallel(&self, query: &[f32], vectors: &[&[f32]]) -> Result<Vec<f32>> {
if vectors.is_empty() {
return Ok(Vec::new());
}
if vectors.len() < 100 {
return vectors
.iter()
.map(|v| self.distance(query, v))
.collect::<Result<Vec<_>>>();
}
#[cfg(not(target_arch = "wasm32"))]
{
vectors
.par_iter()
.map(|v| self.distance(query, v))
.collect::<Result<Vec<_>>>()
}
#[cfg(target_arch = "wasm32")]
{
vectors
.iter()
.map(|v| self.distance(query, v))
.collect::<Result<Vec<_>>>()
}
}
/// Calculate similarities between a query vector and multiple vectors in parallel.
pub fn batch_similarity_parallel(&self, query: &[f32], vectors: &[&[f32]]) -> Result<Vec<f32>> {
if vectors.is_empty() {
return Ok(Vec::new());
}
if vectors.len() < 100 {
return vectors
.iter()
.map(|v| self.similarity(query, v))
.collect::<Result<Vec<_>>>();
}
#[cfg(not(target_arch = "wasm32"))]
{
vectors
.par_iter()
.map(|v| self.similarity(query, v))
.collect::<Result<Vec<_>>>()
}
#[cfg(target_arch = "wasm32")]
{
vectors
.iter()
.map(|v| self.similarity(query, v))
.collect::<Result<Vec<_>>>()
}
}
}