1use std::borrow::Borrow;
9use std::cmp::Ordering;
10use std::collections::BinaryHeap;
11
12use crate::document::{Document, Metric};
13use crate::kernels;
14
15#[derive(Debug, Clone, PartialEq)]
20pub struct Hit {
21 pub id: String,
23 pub distance: f32,
28 pub attrs: Option<serde_json::Value>,
30}
31
32pub fn distance(metric: Metric, a: &[f32], b: &[f32]) -> f32 {
67 let fast = match metric {
68 Metric::L2 => kernels::l2(a, b),
69 Metric::Dot => -kernels::dot(a, b),
70 Metric::Cosine => {
71 let (na, nb) = (kernels::norm2(a), kernels::norm2(b));
72 let trusted = |n: f32| n.is_finite() && n >= kernels::NORM_FLOOR;
73 if !(trusted(na) && trusted(nb)) {
74 return reference(metric, a, b);
75 }
76 let cosine = 1.0 - kernels::dot(a, b) / (na.sqrt() * nb.sqrt());
77 if cosine < kernels::COSINE_RECHECK {
78 return reference(metric, a, b);
79 }
80 cosine
81 }
82 };
83 if fast.is_finite() {
84 fast
85 } else {
86 reference(metric, a, b)
87 }
88}
89
90fn reference(metric: Metric, a: &[f32], b: &[f32]) -> f32 {
92 match metric {
93 Metric::L2 => a
94 .iter()
95 .zip(b)
96 .map(|(x, y)| {
97 let d = f64::from(*x) - f64::from(*y);
98 d * d
99 })
100 .sum::<f64>() as f32,
101 Metric::Dot => -dot_f64(a, b) as f32,
102 Metric::Cosine => {
103 let na = dot_f64(a, a);
104 let nb = dot_f64(b, b);
105 if na == 0.0 || nb == 0.0 {
106 return 1.0;
107 }
108 (1.0 - dot_f64(a, b) / (na.sqrt() * nb.sqrt())) as f32
109 }
110 }
111}
112
113fn dot_f64(a: &[f32], b: &[f32]) -> f64 {
115 a.iter()
116 .zip(b)
117 .map(|(x, y)| f64::from(*x) * f64::from(*y))
118 .sum()
119}
120
121struct Candidate<D> {
124 distance: f32,
125 doc: D,
126}
127
128impl<D: Borrow<Document>> PartialEq for Candidate<D> {
129 fn eq(&self, other: &Self) -> bool {
130 self.cmp(other) == Ordering::Equal
131 }
132}
133impl<D: Borrow<Document>> Eq for Candidate<D> {}
134impl<D: Borrow<Document>> PartialOrd for Candidate<D> {
135 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
136 Some(self.cmp(other))
137 }
138}
139impl<D: Borrow<Document>> Ord for Candidate<D> {
140 fn cmp(&self, other: &Self) -> Ordering {
141 self.distance
142 .total_cmp(&other.distance)
143 .then_with(|| self.doc.borrow().id.cmp(&other.doc.borrow().id))
144 }
145}
146
147pub fn flat_top_k(
181 metric: Metric,
182 query: &[f32],
183 docs: impl IntoIterator<Item = Document>,
184 k: usize,
185) -> Vec<Hit> {
186 let candidates = docs.into_iter().map(|doc| Candidate {
187 distance: distance(metric, query, &doc.vector),
188 doc,
189 });
190 select(candidates, k)
191 .into_iter()
192 .map(|c| Hit {
193 id: c.doc.id,
194 distance: c.distance,
195 attrs: c.doc.attrs,
196 })
197 .collect()
198}
199
200fn select<D: Borrow<Document>>(
204 candidates: impl Iterator<Item = Candidate<D>>,
205 k: usize,
206) -> Vec<Candidate<D>> {
207 if k == 0 {
208 return Vec::new();
209 }
210 let mut heap: BinaryHeap<Candidate<D>> = BinaryHeap::with_capacity(k.min(1024) + 1);
211 for candidate in candidates {
212 if heap.len() < k {
213 heap.push(candidate);
214 } else if heap.peek().is_some_and(|worst| candidate < *worst) {
215 heap.pop();
216 heap.push(candidate);
217 }
218 }
219 heap.into_sorted_vec()
220}
221
222#[cfg(test)]
223mod tests {
224 use super::*;
225
226 fn doc(id: &str, v: &[f32]) -> Document {
227 Document {
228 id: id.into(),
229 vector: v.to_vec(),
230 attrs: None,
231 sparse: None,
232 }
233 }
234
235 #[test]
236 fn l2_is_squared_euclidean() {
237 assert_eq!(distance(Metric::L2, &[0.0, 0.0], &[3.0, 4.0]), 25.0);
238 }
239
240 #[test]
241 fn dot_is_negated() {
242 assert_eq!(distance(Metric::Dot, &[1.0, 2.0], &[3.0, 4.0]), -11.0);
243 }
244
245 #[test]
246 fn cosine_identical_is_zero_orthogonal_is_one_opposite_is_two() {
247 assert!(distance(Metric::Cosine, &[1.0, 0.0], &[2.0, 0.0]).abs() < 1e-6);
248 assert!((distance(Metric::Cosine, &[1.0, 0.0], &[0.0, 5.0]) - 1.0).abs() < 1e-6);
249 assert!((distance(Metric::Cosine, &[1.0, 0.0], &[-1.0, 0.0]) - 2.0).abs() < 1e-6);
250 }
251
252 #[test]
253 fn cosine_with_zero_norm_stored_vector_is_one() {
254 assert_eq!(distance(Metric::Cosine, &[1.0, 0.0], &[0.0, 0.0]), 1.0);
255 }
256
257 #[test]
258 fn top_k_returns_closest_ascending() {
259 let docs = vec![
260 doc("far", &[10.0, 0.0]),
261 doc("near", &[1.0, 0.0]),
262 doc("mid", &[4.0, 0.0]),
263 ];
264 let hits = flat_top_k(Metric::L2, &[0.0, 0.0], docs, 2);
265 let ids: Vec<_> = hits.iter().map(|h| h.id.as_str()).collect();
266 assert_eq!(ids, ["near", "mid"]);
267 assert!(hits[0].distance < hits[1].distance);
268 }
269
270 #[test]
271 fn ties_break_by_id() {
272 let docs = vec![doc("b", &[1.0]), doc("a", &[1.0]), doc("c", &[1.0])];
273 let hits = flat_top_k(Metric::L2, &[0.0], docs, 2);
274 let ids: Vec<_> = hits.iter().map(|h| h.id.as_str()).collect();
275 assert_eq!(ids, ["a", "b"]);
276 }
277
278 #[test]
279 fn k_larger_than_corpus_returns_all_and_zero_returns_none() {
280 let docs = vec![doc("a", &[1.0]), doc("b", &[2.0])];
281 assert_eq!(flat_top_k(Metric::L2, &[0.0], docs.clone(), 10).len(), 2);
282 assert!(flat_top_k(Metric::L2, &[0.0], docs, 0).is_empty());
283 }
284
285 fn reference_f64(metric: Metric, a: &[f32], b: &[f32]) -> f64 {
288 let dot = |x: &[f32], y: &[f32]| -> f64 {
289 x.iter()
290 .zip(y)
291 .map(|(p, q)| f64::from(*p) * f64::from(*q))
292 .sum()
293 };
294 match metric {
295 Metric::L2 => a
296 .iter()
297 .zip(b)
298 .map(|(x, y)| (f64::from(*x) - f64::from(*y)).powi(2))
299 .sum(),
300 Metric::Dot => -dot(a, b),
301 Metric::Cosine => {
302 let (na, nb) = (dot(a, a), dot(b, b));
303 if na == 0.0 || nb == 0.0 {
304 return 1.0;
305 }
306 1.0 - dot(a, b) / (na.sqrt() * nb.sqrt())
307 }
308 }
309 }
310
311 #[test]
312 fn tiny_vectors_keep_their_cosine() {
313 let a = [1e-25f32; 4];
315 assert!(distance(Metric::Cosine, &a, &a).abs() < 1e-6);
316 let b = [1e-25f32, -1e-25, 1e-25, -1e-25];
317 assert!((distance(Metric::Cosine, &a, &b) - 1.0).abs() < 1e-6);
318 }
319
320 #[test]
321 fn subnormal_scale_vectors_keep_their_cosine() {
322 for s in [1e-21f32, 1e-22, 3e-23, 1e-23] {
325 let (a, b) = ([3.0 * s, s], [s, 3.0 * s]);
326 let got = distance(Metric::Cosine, &a, &b);
327 assert!((got - 0.4).abs() < 1e-6, "s={s}: {got}");
328 }
329 }
330
331 #[test]
332 fn cosine_near_zero_keeps_its_resolution() {
333 let a: Vec<f32> = (0..128)
334 .map(|i| ((i * 7) % 13) as f32 / 13.0 + 0.1)
335 .collect();
336 let self_distance = distance(Metric::Cosine, &a, &a);
337 assert!(self_distance.abs() < 1e-12, "self distance {self_distance}");
338 let mut b = a.clone();
339 b[0] += 1e-4;
340 let near = distance(Metric::Cosine, &a, &b);
341 let want = reference_f64(Metric::Cosine, &a, &b);
342 assert!(near > 0.0, "a moved vector must be farther than itself");
343 assert!(
344 (f64::from(near) - want).abs() <= 1e-3 * want,
345 "{near} vs {want}"
346 );
347 }
348
349 #[test]
350 fn huge_components_give_the_reference_value() {
351 let (a, b) = ([1e20f32, 0.0], [1e20f32, 1e20]);
353 let want = reference_f64(Metric::Cosine, &a, &b) as f32;
354 assert!((distance(Metric::Cosine, &a, &b) - want).abs() < 1e-6);
355 assert!((want - 0.292_893_2).abs() < 1e-6);
356
357 let (a, b) = ([1e20f32, 1e20], [1e20f32, -1e20]);
360 assert_eq!(distance(Metric::Dot, &a, &b), 0.0);
361 }
362
363 #[test]
364 fn distance_matches_the_f64_reference_at_every_dimension() {
365 let mut seed = 9u64;
366 let mut next = || {
367 seed ^= seed << 13;
368 seed ^= seed >> 7;
369 seed ^= seed << 17;
370 (seed >> 40) as f32 / (1u32 << 23) as f32 - 1.0
371 };
372 for dim in [1, 3, 7, 8, 9, 25, 128, 960] {
373 let a: Vec<f32> = (0..dim).map(|_| next()).collect();
374 let b: Vec<f32> = (0..dim).map(|_| next()).collect();
375 for metric in [Metric::L2, Metric::Dot, Metric::Cosine] {
376 let want = reference_f64(metric, &a, &b);
377 let got = distance(metric, &a, &b);
378 assert!(
379 (f64::from(got) - want).abs() <= 1e-4 * (1.0 + want.abs()),
380 "{metric:?} at {dim}: {got} vs {want}"
381 );
382 }
383 }
384 }
385
386 #[test]
387 fn flat_top_k_agrees_with_a_full_sort() {
388 let docs: Vec<Document> = (0..200)
389 .map(|i| {
390 doc(
391 &format!("d{i:03}"),
392 &[((i * 37) % 101) as f32, (i % 7) as f32],
393 )
394 })
395 .collect();
396 let query = [50.0f32, 3.0];
397 let mut all: Vec<(f32, String)> = docs
398 .iter()
399 .map(|d| (distance(Metric::L2, &query, &d.vector), d.id.clone()))
400 .collect();
401 all.sort_by(|a, b| a.0.total_cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
402 for k in [1, 5, 50, 200, 300] {
403 let want: Vec<&str> = all.iter().take(k).map(|(_, id)| id.as_str()).collect();
404 let flat = flat_top_k(Metric::L2, &query, docs.clone(), k);
405 let flat: Vec<&str> = flat.iter().map(|h| h.id.as_str()).collect();
406 assert_eq!(flat, want, "flat_top_k k={k}");
407 }
408 }
409
410 #[test]
411 fn attrs_are_carried_onto_hits() {
412 let mut d = doc("a", &[1.0]);
413 d.attrs = Some(serde_json::json!({"tag": 1}));
414 let hits = flat_top_k(Metric::L2, &[0.0], vec![d], 1);
415 assert_eq!(hits[0].attrs, Some(serde_json::json!({"tag": 1})));
416 }
417}