diskann_vector/traits.rs
1/*
2 * Copyright (c) Microsoft Corporation.
3 * Licensed under the MIT license.
4 */
5
6/// An overloadable, 2-argument distance function with a parameterized return type.
7///
8/// Pure distance functions depend only on the values of the argument and the type of the
9/// return value.
10pub trait PureDistanceFunction<Left, Right, To = f32> {
11 fn evaluate(x: Left, y: Right) -> To;
12}
13
14/// An overloadable, 2-argument distance function with a parameterized return type.
15///
16/// Unlike `PureDistanceFunction`, this takes a functor as the receiver. This allows
17/// distance functors to contain auxiliary state required to do their job
18/// (for example, access to some shared quantization tables).
19pub trait DistanceFunction<Left, Right, To = f32> {
20 /// Perform a distance computation between the left-hand and right-hand arguments.
21 fn evaluate_similarity(&self, x: Left, y: Right) -> To;
22}
23
24impl<Left, Right, To, T> DistanceFunction<Left, Right, To> for &T
25where
26 T: DistanceFunction<Left, Right, To>,
27{
28 fn evaluate_similarity(&self, x: Left, y: Right) -> To {
29 <T as DistanceFunction<_, _, _>>::evaluate_similarity(self, x, y)
30 }
31}
32
33/// A mutable version of [`DistanceFunction`] that allows mutation of `Self`.
34///
35/// This trait is useful for computing distances where the distance functor holds
36/// mutable state (e.g., a buffer to accumulate per-vector scores).
37pub trait DistanceFunctionMut<Left, Right, To = ()> {
38 /// Compute distances between the left and right arguments.
39 fn evaluate(&mut self, left: Left, right: Right) -> To;
40}
41
42/// A distance function where one argument is static and interned within `Self`.
43///
44/// The method `self.evaluate_similarity` can then be invoked for arbitrarily many values of
45/// `changing`.
46///
47/// The main idea behind this trait is to enable distance functions where some amount of
48/// preprocessing on a query can be used to accelerate distance computations.
49pub trait PreprocessedDistanceFunction<Changing, To = f32> {
50 fn evaluate_similarity(&self, changing: Changing) -> To;
51}
52
53/// Evaluate a norm of the argument `x` and return the result as the requested type.
54///
55/// Note that while this has a similar signature to `PreprocessedDistanceFunction`, the
56/// semantics of this trait are different. Implementations are expected to be light-weight
57/// types that implement some kind of reduction on on `x`.
58pub trait Norm<T, To = f32> {
59 fn evaluate(&self, x: T) -> To;
60}