|
| 1 | +/* |
| 2 | + * Copyright (c) Microsoft Corporation. |
| 3 | + * Licensed under the MIT license. |
| 4 | + */ |
| 5 | + |
| 6 | +use diskann_quantization::{ |
| 7 | + alloc::{AllocatorError, GlobalAllocator, Poly}, |
| 8 | + spherical::{ |
| 9 | + iface::{self as spherical_iface, Quantizer}, |
| 10 | + SphericalQuantizer, |
| 11 | + }, |
| 12 | +}; |
| 13 | +use diskann_utils::views::MatrixView; |
| 14 | +use rand::SeedableRng; |
| 15 | + |
| 16 | +use crate::{inputs::bftree::QuantConfig, utils::SimilarityMeasure}; |
| 17 | + |
| 18 | +fn new_quantizer<const NBITS: usize>( |
| 19 | + quantizer: SphericalQuantizer, |
| 20 | +) -> Result<Poly<dyn Quantizer>, AllocatorError> |
| 21 | +where |
| 22 | + spherical_iface::Impl<NBITS>: spherical_iface::Constructible + Quantizer, |
| 23 | +{ |
| 24 | + let imp = spherical_iface::Impl::<NBITS>::new(quantizer)?; |
| 25 | + diskann_quantization::poly!(Quantizer, imp, GlobalAllocator) |
| 26 | +} |
| 27 | + |
| 28 | +pub(super) fn build_quantizer( |
| 29 | + quantization: &QuantConfig, |
| 30 | + data: MatrixView<'_, f32>, |
| 31 | + distance: SimilarityMeasure, |
| 32 | +) -> anyhow::Result<Option<Poly<dyn Quantizer>>> { |
| 33 | + match quantization { |
| 34 | + QuantConfig::None => Ok(None), |
| 35 | + QuantConfig::Spherical { |
| 36 | + seed, |
| 37 | + transform_kind, |
| 38 | + num_bits, |
| 39 | + pre_scale, |
| 40 | + .. |
| 41 | + } => { |
| 42 | + let m: diskann_vector::distance::Metric = distance.into(); |
| 43 | + let pre_scale = match pre_scale { |
| 44 | + Some(v) => (*v).try_into()?, |
| 45 | + None => diskann_quantization::spherical::PreScale::None, |
| 46 | + }; |
| 47 | + |
| 48 | + let quantizer = SphericalQuantizer::train( |
| 49 | + data, |
| 50 | + transform_kind.into(), |
| 51 | + m.try_into()?, |
| 52 | + pre_scale, |
| 53 | + &mut rand::rngs::StdRng::seed_from_u64(*seed), |
| 54 | + GlobalAllocator, |
| 55 | + )?; |
| 56 | + |
| 57 | + let poly = match num_bits.get() { |
| 58 | + 1 => new_quantizer::<1>(quantizer)?, |
| 59 | + 2 => new_quantizer::<2>(quantizer)?, |
| 60 | + 4 => new_quantizer::<4>(quantizer)?, |
| 61 | + n => anyhow::bail!("{n} bits not supported for spherical quantization"), |
| 62 | + }; |
| 63 | + |
| 64 | + Ok(Some(poly)) |
| 65 | + } |
| 66 | + } |
| 67 | +} |
0 commit comments