Skip to main content

itzma_core/
search.rs

1//! Flat (brute-force) nearest-neighbor search.
2//!
3//! Every candidate is compared against the query, and a bounded max-heap keeps
4//! the best `k`. That is O(n log k) time and O(k) extra memory for `n`
5//! documents. The indexed path (`query.rs`) reranks its shortlist with the same
6//! [`distance`].
7
8use std::borrow::Borrow;
9use std::cmp::Ordering;
10use std::collections::BinaryHeap;
11
12use crate::document::{Document, Metric};
13use crate::kernels;
14
15/// One search result.
16///
17/// Results come back sorted by ascending `distance`, so the first hit is the
18/// closest.
19#[derive(Debug, Clone, PartialEq)]
20pub struct Hit {
21    /// Id of the matching [`Document`].
22    pub id: String,
23    /// Distance from the query under the namespace's metric. Lower is closer
24    /// for every metric, and the value can be negative (see
25    /// [`Metric::Dot`]). Compare distances within one query only; the scale
26    /// differs between metrics.
27    pub distance: f32,
28    /// The document's attributes, exactly as stored.
29    pub attrs: Option<serde_json::Value>,
30}
31
32/// Distance between `a` and `b` under `metric`. Lower is closer.
33///
34/// | Metric | Value |
35/// |---|---|
36/// | [`Metric::L2`] | `sum((a_i - b_i)^2)`, no square root |
37/// | [`Metric::Dot`] | `-sum(a_i * b_i)` |
38/// | [`Metric::Cosine`] | `1 - dot(a, b) / (norm(a) * norm(b))`, so 0 for the same direction, 1 for orthogonal, 2 for opposite |
39///
40/// The sums run in `f32` with eight independent accumulators, which the
41/// compiler vectorizes. The distance is recomputed with `f64` sums
42/// when that result is not finite, and under cosine also when a squared norm
43/// is not finite or is too small for `f32` to hold its bits (below `1e-30`),
44/// or when the distance is below `1e-4`, where `f32` resolves `1 - cos` only
45/// to about `1e-7`. So a large component does not overflow part way through,
46/// a tiny one does not underflow, and near-duplicates keep their order. The
47/// result is the same bits for the same inputs on every call.
48///
49/// Under cosine, if either vector has zero norm the result is `1.0` (no
50/// relationship) rather than NaN. Writes reject zero vectors, so this only
51/// matters for data that reached storage some other way.
52///
53/// The slices are expected to have equal length. Extra components in the
54/// longer one are ignored, because callers validate against the schema first.
55///
56/// # Examples
57///
58/// ```
59/// use itzma_core::Metric;
60/// use itzma_core::search::distance;
61///
62/// assert_eq!(distance(Metric::L2, &[0.0, 0.0], &[3.0, 4.0]), 25.0);
63/// assert_eq!(distance(Metric::Dot, &[1.0, 2.0], &[3.0, 4.0]), -11.0);
64/// assert!(distance(Metric::Cosine, &[1.0, 0.0], &[2.0, 0.0]).abs() < 1e-6);
65/// ```
66pub 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
90/// [`distance`] with `f64` sums, for the values the `f32` kernels cannot hold.
91fn 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
113/// Inner product in `f64`, for [`reference`].
114fn 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
121/// Heap entry ordered by (distance, id) so the worst candidate sits on top
122/// and ties resolve deterministically by id.
123struct 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
147/// The `k` documents closest to `query`, closest first.
148///
149/// Scans all of `docs` once. A max-heap of at most `k` entries holds the best
150/// candidates so far, with the current worst on top so it can be evicted
151/// cheaply. A document enters the heap only when it beats the current worst,
152/// so most are compared and dropped without being moved.
153///
154/// Ties on distance are broken by id (ascending), so results are
155/// deterministic no matter what order `docs` arrives in. That matters because
156/// the caller feeds this from a `HashMap`, whose iteration order is random.
157///
158/// Returns fewer than `k` hits if there are fewer documents, and an empty
159/// vector if `k == 0`. The vectors in `docs` must already match the query's
160/// length.
161///
162/// # Examples
163///
164/// ```
165/// use itzma_core::search::flat_top_k;
166/// use itzma_core::{Document, Metric};
167///
168/// let doc = |id: &str, x: f32| Document {
169///     id: id.into(),
170///     vector: vec![x],
171///     attrs: None,
172///     sparse: None,
173/// };
174/// let docs = vec![doc("far", 9.0), doc("near", 1.0), doc("mid", 4.0)];
175///
176/// let hits = flat_top_k(Metric::L2, &[0.0], docs, 2);
177/// let ids: Vec<_> = hits.iter().map(|h| h.id.as_str()).collect();
178/// assert_eq!(ids, ["near", "mid"]);
179/// ```
180pub 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
200/// The `k` closest candidates, closest first, ties by id: a max-heap of at
201/// most `k` with the current worst on top, entered only by a candidate that
202/// beats it.
203fn 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    /// The `f64` reference for these tests, spelled out rather than calling
286    /// the private fallback, so a bug there cannot hide.
287    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        // The squared norm, 4e-50, underflows f32 to zero; f64 keeps it.
314        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        // Squared norms of 1e-44 to 1e-46 are subnormal in f32: nonzero, but
323        // with too few bits left for the products to survive.
324        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        // Squared norms of 1e40 overflow f32, the cosine itself does not.
352        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        // Products of +-1e40 overflow to +inf and -inf, which cancel to NaN in
358        // f32 and to 0 in f64.
359        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}