Skip to main content

ruvector_attention/curvature/
component_quantizer.rs

1//! Component Quantization for Mixed-Curvature Attention
2//!
3//! Different precision for each geometric component:
4//! - Euclidean: 7-8 bit (needs precision)
5//! - Hyperbolic tangent: 5 bit (tolerates noise)
6//! - Spherical: 5 bit (only direction matters)
7
8use serde::{Deserialize, Serialize};
9
10/// Quantization configuration
11#[derive(Debug, Clone, Serialize, Deserialize)]
12pub struct QuantizationConfig {
13    /// Bits for Euclidean component
14    pub euclidean_bits: u8,
15    /// Bits for Hyperbolic component
16    pub hyperbolic_bits: u8,
17    /// Bits for Spherical component
18    pub spherical_bits: u8,
19}
20
21impl Default for QuantizationConfig {
22    fn default() -> Self {
23        Self {
24            euclidean_bits: 8,
25            hyperbolic_bits: 5,
26            spherical_bits: 5,
27        }
28    }
29}
30
31/// Quantized vector representation
32#[derive(Debug, Clone)]
33pub struct QuantizedVector {
34    /// Quantized Euclidean component
35    pub euclidean: Vec<i8>,
36    /// Euclidean scale factor
37    pub euclidean_scale: f32,
38    /// Quantized Hyperbolic component
39    pub hyperbolic: Vec<i8>,
40    /// Hyperbolic scale factor
41    pub hyperbolic_scale: f32,
42    /// Quantized Spherical component
43    pub spherical: Vec<i8>,
44    /// Spherical scale factor
45    pub spherical_scale: f32,
46}
47
48/// Component quantizer for efficient storage and compute
49#[derive(Debug, Clone)]
50pub struct ComponentQuantizer {
51    config: QuantizationConfig,
52    euclidean_levels: i32,
53    hyperbolic_levels: i32,
54    spherical_levels: i32,
55}
56
57impl ComponentQuantizer {
58    /// Create new quantizer
59    pub fn new(config: QuantizationConfig) -> Self {
60        Self {
61            euclidean_levels: (1 << (config.euclidean_bits - 1)) - 1,
62            hyperbolic_levels: (1 << (config.hyperbolic_bits - 1)) - 1,
63            spherical_levels: (1 << (config.spherical_bits - 1)) - 1,
64            config,
65        }
66    }
67
68    /// Quantize a component vector
69    fn quantize_component(&self, values: &[f32], levels: i32) -> (Vec<i8>, f32) {
70        if values.is_empty() {
71            return (vec![], 1.0);
72        }
73
74        // Find absmax for scale
75        let absmax = values
76            .iter()
77            .map(|v| v.abs())
78            .fold(0.0f32, f32::max)
79            .max(1e-8);
80
81        let scale = absmax / levels as f32;
82        let inv_scale = levels as f32 / absmax;
83
84        let quantized: Vec<i8> = values
85            .iter()
86            .map(|v| (v * inv_scale).round().clamp(-127.0, 127.0) as i8)
87            .collect();
88
89        (quantized, scale)
90    }
91
92    /// Dequantize a component
93    fn dequantize_component(&self, quantized: &[i8], scale: f32) -> Vec<f32> {
94        quantized.iter().map(|&q| q as f32 * scale).collect()
95    }
96
97    /// Quantize full vector with component ranges
98    pub fn quantize(
99        &self,
100        vector: &[f32],
101        e_range: std::ops::Range<usize>,
102        h_range: std::ops::Range<usize>,
103        s_range: std::ops::Range<usize>,
104    ) -> QuantizedVector {
105        let (euclidean, euclidean_scale) =
106            self.quantize_component(&vector[e_range], self.euclidean_levels);
107
108        let (hyperbolic, hyperbolic_scale) =
109            self.quantize_component(&vector[h_range], self.hyperbolic_levels);
110
111        let (spherical, spherical_scale) =
112            self.quantize_component(&vector[s_range], self.spherical_levels);
113
114        QuantizedVector {
115            euclidean,
116            euclidean_scale,
117            hyperbolic,
118            hyperbolic_scale,
119            spherical,
120            spherical_scale,
121        }
122    }
123
124    /// Compute dot product between quantized vectors (integer arithmetic)
125    #[inline]
126    pub fn quantized_dot_product(
127        &self,
128        a: &QuantizedVector,
129        b: &QuantizedVector,
130        weights: &[f32; 3],
131    ) -> f32 {
132        // Integer dot products
133        let dot_e = Self::int_dot(&a.euclidean, &b.euclidean);
134        let dot_h = Self::int_dot(&a.hyperbolic, &b.hyperbolic);
135        let dot_s = Self::int_dot(&a.spherical, &b.spherical);
136
137        // Scale and weight
138        let sim_e = dot_e as f32 * a.euclidean_scale * b.euclidean_scale;
139        let sim_h = dot_h as f32 * a.hyperbolic_scale * b.hyperbolic_scale;
140        let sim_s = dot_s as f32 * a.spherical_scale * b.spherical_scale;
141
142        weights[0] * sim_e + weights[1] * sim_h + weights[2] * sim_s
143    }
144
145    /// Integer dot product (SIMD-friendly)
146    #[inline(always)]
147    fn int_dot(a: &[i8], b: &[i8]) -> i32 {
148        let len = a.len().min(b.len());
149        let chunks = len / 4;
150        let remainder = len % 4;
151
152        let mut sum0 = 0i32;
153        let mut sum1 = 0i32;
154        let mut sum2 = 0i32;
155        let mut sum3 = 0i32;
156
157        for i in 0..chunks {
158            let base = i * 4;
159            sum0 += a[base] as i32 * b[base] as i32;
160            sum1 += a[base + 1] as i32 * b[base + 1] as i32;
161            sum2 += a[base + 2] as i32 * b[base + 2] as i32;
162            sum3 += a[base + 3] as i32 * b[base + 3] as i32;
163        }
164
165        let base = chunks * 4;
166        for i in 0..remainder {
167            sum0 += a[base + i] as i32 * b[base + i] as i32;
168        }
169
170        sum0 + sum1 + sum2 + sum3
171    }
172
173    /// Dequantize to full vector
174    pub fn dequantize(&self, quant: &QuantizedVector, total_dim: usize) -> Vec<f32> {
175        let mut result = vec![0.0f32; total_dim];
176
177        let e_vec = self.dequantize_component(&quant.euclidean, quant.euclidean_scale);
178        let h_vec = self.dequantize_component(&quant.hyperbolic, quant.hyperbolic_scale);
179        let s_vec = self.dequantize_component(&quant.spherical, quant.spherical_scale);
180
181        let e_end = e_vec.len();
182        let h_end = e_end + h_vec.len();
183
184        result[0..e_end].copy_from_slice(&e_vec);
185        result[e_end..h_end].copy_from_slice(&h_vec);
186        result[h_end..h_end + s_vec.len()].copy_from_slice(&s_vec);
187
188        result
189    }
190
191    /// Get memory savings ratio
192    pub fn compression_ratio(&self, dim: usize, e_dim: usize, h_dim: usize, s_dim: usize) -> f32 {
193        let original_bits = dim as f32 * 32.0;
194        let quantized_bits = e_dim as f32 * self.config.euclidean_bits as f32
195            + h_dim as f32 * self.config.hyperbolic_bits as f32
196            + s_dim as f32 * self.config.spherical_bits as f32
197            + 3.0 * 32.0; // 3 scale factors
198
199        original_bits / quantized_bits
200    }
201}
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206
207    #[test]
208    fn test_quantize_dequantize() {
209        let quantizer = ComponentQuantizer::new(QuantizationConfig::default());
210
211        let vector = vec![0.5f32; 64];
212        let e_range = 0..32;
213        let h_range = 32..48;
214        let s_range = 48..64;
215
216        let quantized =
217            quantizer.quantize(&vector, e_range.clone(), h_range.clone(), s_range.clone());
218
219        assert_eq!(quantized.euclidean.len(), 32);
220        assert_eq!(quantized.hyperbolic.len(), 16);
221        assert_eq!(quantized.spherical.len(), 16);
222
223        // Dequantize and check approximate equality
224        let dequantized = quantizer.dequantize(&quantized, 64);
225        for (&orig, &deq) in vector.iter().zip(dequantized.iter()) {
226            assert!((orig - deq).abs() < 0.1);
227        }
228    }
229
230    #[test]
231    fn test_quantized_dot_product() {
232        let quantizer = ComponentQuantizer::new(QuantizationConfig::default());
233
234        let a = vec![1.0f32; 64];
235        let b = vec![1.0f32; 64];
236        let e_range = 0..32;
237        let h_range = 32..48;
238        let s_range = 48..64;
239
240        let qa = quantizer.quantize(&a, e_range.clone(), h_range.clone(), s_range.clone());
241        let qb = quantizer.quantize(&b, e_range, h_range, s_range);
242
243        let weights = [0.5, 0.3, 0.2];
244        let dot = quantizer.quantized_dot_product(&qa, &qb, &weights);
245
246        // Should be positive for same vectors
247        assert!(dot > 0.0);
248    }
249
250    #[test]
251    fn test_compression_ratio() {
252        let quantizer = ComponentQuantizer::new(QuantizationConfig::default());
253
254        let ratio = quantizer.compression_ratio(512, 256, 192, 64);
255
256        // With 8/5/5 bits vs 32 bits, expect ~4-5x compression
257        assert!(ratio > 3.0);
258        assert!(ratio < 7.0);
259    }
260}