Skip to main content

VectorQuantizer

Struct VectorQuantizer 

Source
pub struct VectorQuantizer {
    pub config: QuantizationConfig,
    pub codebooks: Vec<Codebook>,
    pub trained: bool,
    pub stats: QuantizationStats,
}
Expand description

Product-quantization based vector compressor.

§Example

use ipfrs_semantic::vector_quantizer::{VectorQuantizer, QuantizationConfig};

let config = QuantizationConfig::new(4, 16, 50, 1e-6);
let mut vq = VectorQuantizer::new(config);

// Train on representative data (must have >= codes_per_subspace vectors)
let training_data: Vec<Vec<f64>> = (0..32)
    .map(|i| (0..16).map(|d| (i * 16 + d) as f64 * 0.01).collect())
    .collect();
vq.train(&training_data).unwrap();

let code = vq.encode(&vec![0.5_f64; 16]).unwrap();
let reconstructed = vq.decode(&code).unwrap();
assert_eq!(reconstructed.len(), 16);

Fields§

§config: QuantizationConfig

Quantization parameters.

§codebooks: Vec<Codebook>

One codebook per subspace; populated after train.

§trained: bool

Whether the quantizer has been trained.

§stats: QuantizationStats

Runtime statistics.

Implementations§

Source§

impl VectorQuantizer

Source

pub fn new(config: QuantizationConfig) -> Self

Create a new, untrained quantizer with the given configuration.

Source

pub fn train(&mut self, vectors: &[Vec<f64>]) -> Result<(), VqError>

Train the quantizer by running k-means over vectors for each subspace.

§Errors
Source

pub fn encode(&mut self, vector: &[f64]) -> Result<QuantizerCode, VqError>

Encode a vector into a compact QuantizerCode.

For each subspace the sub-vector is mapped to the index of its nearest centroid.

§Errors
Source

pub fn decode(&mut self, code: &QuantizerCode) -> Result<Vec<f64>, VqError>

Decode a QuantizerCode back into an approximate full-dimensional vector.

Reconstructs the vector by concatenating the centroid vectors from each codebook.

§Errors
Source

pub fn encode_batch( &mut self, vectors: &[Vec<f64>], ) -> Result<Vec<QuantizerCode>, VqError>

Encode a batch of vectors.

All vectors must have the same dimension as the training data.

§Errors

Propagates the first error encountered (see encode).

Source

pub fn asymmetric_distance( &self, query: &[f64], code: &QuantizerCode, ) -> Result<f64, VqError>

Compute the asymmetric squared L2 distance between a raw query vector and a code.

This is more accurate than symmetric_distance because the query is not quantized — only the database vector is approximated.

§Errors
Source

pub fn symmetric_distance( &mut self, a: &QuantizerCode, b: &QuantizerCode, ) -> Result<f64, VqError>

Compute the symmetric squared L2 distance between two quantizer codes.

Both codes are decoded to full vectors before computing the distance. This is less accurate than asymmetric_distance but useful when the query is also stored as a code.

§Errors
Source

pub fn quantization_error(&mut self, vector: &[f64]) -> Result<f64, VqError>

Compute the per-dimension mean squared reconstruction error for a vector.

||vector - decode(encode(vector))||^2 / dim

§Errors

Propagates errors from encode and decode.

Source

pub fn avg_error_on_batch( &mut self, vectors: &[Vec<f64>], ) -> Result<f64, VqError>

Compute the mean quantization error over a batch of vectors.

§Errors

Propagates the first error encountered.

Source

pub fn codebook_stats(&self) -> Vec<(usize, usize)>

Return (subspace_idx, num_centroids) pairs for each codebook.

Trait Implementations§

Source§

impl Debug for VectorQuantizer

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Allocation for T
where T: RefUnwindSafe + Send + Sync,

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more