Skip to main content

diskann_quantization/multi_vector/distance/
kernel.rs

1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT license.
3
4//! Object-safe kernel boundary trait plus BYOTE visitor trait.
5
6use crate::multi_vector::{MatRef, MaxSimError, Standard};
7
8/// Object-safe interface for computing per-query MaxSim scores.
9pub trait MaxSimKernel<T: Copy>: Send + Sync + std::fmt::Debug {
10    /// Number of query rows whose scores this kernel produces.
11    fn nrows(&self) -> usize;
12
13    /// Compute per-query MaxSim scores into `scores`. On zero docs, fills
14    /// every slot with `f32::MAX`.
15    ///
16    /// # Errors
17    ///
18    /// [`MaxSimError::InvalidBufferLength`] if `scores.len() != self.nrows()`.
19    fn compute_max_sim(
20        &self,
21        doc: MatRef<'_, Standard<T>>,
22        scores: &mut [f32],
23    ) -> Result<(), MaxSimError>;
24}
25
26/// "Bring your own type erasure" visitor: the factory hands a concrete
27/// kernel to [`Erase::erase`], which decides how to package it (e.g. as
28/// `Box<dyn MaxSimKernel<T>>` via [`BoxErase`], a chamfer-only closure, a
29/// batched evaluator, …).
30pub trait Erase<T: Copy> {
31    type Output;
32    /// `K` is generic so the body sees its concrete type and the compiler
33    /// can inline it.
34    fn erase<K: MaxSimKernel<T> + 'static>(self, kernel: K) -> Self::Output;
35}
36
37/// Default boxing [`Erase`] impl.
38#[derive(Debug, Clone, Copy)]
39pub struct BoxErase;
40
41impl<T: Copy + 'static> Erase<T> for BoxErase {
42    type Output = Box<dyn MaxSimKernel<T>>;
43
44    fn erase<K: MaxSimKernel<T> + 'static>(self, kernel: K) -> Self::Output {
45        Box::new(kernel)
46    }
47}