Skip to main content

axonml_quant/
quantize.rs

1//! Quantization Functions
2//!
3//! # File
4//! `crates/axonml-quant/src/quantize.rs`
5//!
6//! # Author
7//! Andrew Jewell Sr - AutomataNexus
8//!
9//! # Updated
10//! March 8, 2026
11//!
12//! # Disclaimer
13//! Use at own risk. This software is provided "as is", without warranty of any
14//! kind, express or implied. The author and AutomataNexus shall not be held
15//! liable for any damages arising from the use of this software.
16
17use axonml_tensor::Tensor;
18use half::f16;
19use rayon::prelude::*;
20
21use crate::DEFAULT_BLOCK_SIZE;
22use crate::error::QuantResult;
23use crate::types::{Q4_1Block, Q4Block, Q8Block, QuantType, QuantizedBlock, QuantizedTensor};
24
25// =============================================================================
26// Public API
27// =============================================================================
28
29/// Quantizes a tensor to the specified quantization type.
30///
31/// # Arguments
32/// * `tensor` - The input tensor to quantize
33/// * `quant_type` - The target quantization type
34///
35/// # Returns
36/// A quantized tensor
37///
38/// # Example
39/// ```ignore
40/// use axonml_quant::{quantize_tensor, QuantType};
41///
42/// let tensor = Tensor::from_vec(vec![1.0, 2.0, 3.0, 4.0], &[4])?;
43/// let quantized = quantize_tensor(&tensor, QuantType::Q8_0)?;
44/// ```
45pub fn quantize_tensor(
46    tensor: &Tensor<f32>,
47    quant_type: QuantType,
48) -> QuantResult<QuantizedTensor> {
49    let data = tensor.to_vec();
50    let shape = tensor.shape().to_vec();
51
52    match quant_type {
53        QuantType::Q8_0 => quantize_q8_0(&data, shape),
54        QuantType::Q4_0 => quantize_q4_0(&data, shape),
55        QuantType::Q4_1 => quantize_q4_1(&data, shape),
56        QuantType::Q5_0 | QuantType::Q5_1 => {
57            // Fall back to Q4 for now
58            quantize_q4_0(&data, shape)
59        }
60        QuantType::F16 => quantize_f16(&data, shape),
61        QuantType::F32 => quantize_f32(&data, shape),
62    }
63}
64
65/// Quantizes a model (collection of named tensors).
66///
67/// # Arguments
68/// * `tensors` - Named tensors to quantize
69/// * `quant_type` - The target quantization type
70///
71/// # Returns
72/// A map of quantized tensors
73pub fn quantize_model(
74    tensors: &[(&str, &Tensor<f32>)],
75    quant_type: QuantType,
76) -> QuantResult<Vec<(String, QuantizedTensor)>> {
77    tensors
78        .par_iter()
79        .map(|(name, tensor)| {
80            let quantized = quantize_tensor(tensor, quant_type)?;
81            Ok((name.to_string(), quantized))
82        })
83        .collect()
84}
85
86// =============================================================================
87// Q8_0 Quantization
88// =============================================================================
89
90/// Quantizes data to Q8_0 format (8-bit with per-block scale).
91fn quantize_q8_0(data: &[f32], shape: Vec<usize>) -> QuantResult<QuantizedTensor> {
92    let block_size = DEFAULT_BLOCK_SIZE;
93    let n_blocks = data.len().div_ceil(block_size);
94
95    let blocks: Vec<QuantizedBlock> = (0..n_blocks)
96        .into_par_iter()
97        .map(|block_idx| {
98            let start = block_idx * block_size;
99            let end = (start + block_size).min(data.len());
100            let block_data = &data[start..end];
101
102            // Find max absolute value for scale
103            let max_abs = block_data
104                .iter()
105                .map(|x| x.abs())
106                .fold(0.0f32, |a, b| a.max(b));
107
108            // Compute scale (avoid division by zero)
109            let scale = if max_abs > 0.0 { max_abs / 127.0 } else { 1.0 };
110
111            // Quantize to int8
112            let mut quantized = [0i8; 32];
113            for (i, &val) in block_data.iter().enumerate() {
114                let q = (val / scale).round().clamp(-127.0, 127.0) as i8;
115                quantized[i] = q;
116            }
117
118            QuantizedBlock::Q8(Q8Block::new(f16::from_f32(scale), quantized))
119        })
120        .collect();
121
122    Ok(QuantizedTensor::new(shape, QuantType::Q8_0, blocks))
123}
124
125// =============================================================================
126// Q4_0 Quantization
127// =============================================================================
128
129/// Quantizes data to Q4_0 format (4-bit with per-block scale).
130fn quantize_q4_0(data: &[f32], shape: Vec<usize>) -> QuantResult<QuantizedTensor> {
131    let block_size = DEFAULT_BLOCK_SIZE;
132    let n_blocks = data.len().div_ceil(block_size);
133
134    let blocks: Vec<QuantizedBlock> = (0..n_blocks)
135        .into_par_iter()
136        .map(|block_idx| {
137            let start = block_idx * block_size;
138            let end = (start + block_size).min(data.len());
139            let block_data = &data[start..end];
140
141            // Find max absolute value for scale
142            let max_abs = block_data
143                .iter()
144                .map(|x| x.abs())
145                .fold(0.0f32, |a, b| a.max(b));
146
147            // Compute scale (4-bit range is -8 to 7)
148            let scale = if max_abs > 0.0 { max_abs / 7.0 } else { 1.0 };
149
150            // Quantize to 4-bit (stored as i8 in range -8 to 7)
151            let mut quantized = [0i8; 32];
152            for (i, &val) in block_data.iter().enumerate() {
153                let q = (val / scale).round().clamp(-8.0, 7.0) as i8;
154                quantized[i] = q;
155            }
156
157            // Pack into bytes
158            let packed = Q4Block::pack(&quantized);
159
160            QuantizedBlock::Q4(Q4Block::new(f16::from_f32(scale), packed))
161        })
162        .collect();
163
164    Ok(QuantizedTensor::new(shape, QuantType::Q4_0, blocks))
165}
166
167// =============================================================================
168// Q4_1 Quantization
169// =============================================================================
170
171/// Quantizes data to Q4_1 format (4-bit with per-block scale and min).
172fn quantize_q4_1(data: &[f32], shape: Vec<usize>) -> QuantResult<QuantizedTensor> {
173    let block_size = DEFAULT_BLOCK_SIZE;
174    let n_blocks = data.len().div_ceil(block_size);
175
176    let blocks: Vec<QuantizedBlock> = (0..n_blocks)
177        .into_par_iter()
178        .map(|block_idx| {
179            let start = block_idx * block_size;
180            let end = (start + block_size).min(data.len());
181            let block_data = &data[start..end];
182
183            // Find min and max
184            let min = block_data.iter().fold(f32::INFINITY, |a, &b| a.min(b));
185            let max = block_data.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b));
186
187            // Compute scale (4-bit unsigned range is 0 to 15)
188            let scale = if max > min { (max - min) / 15.0 } else { 1.0 };
189
190            // Quantize to 4-bit unsigned
191            let mut quantized = [0u8; 32];
192            for (i, &val) in block_data.iter().enumerate() {
193                let q = ((val - min) / scale).round().clamp(0.0, 15.0) as u8;
194                quantized[i] = q;
195            }
196
197            // Pack into bytes
198            let mut packed = [0u8; 16];
199            for i in 0..16.min(block_data.len() / 2) {
200                let low = quantized[i * 2] & 0x0F;
201                let high = quantized.get(i * 2 + 1).copied().unwrap_or(0) & 0x0F;
202                packed[i] = low | (high << 4);
203            }
204
205            QuantizedBlock::Q4_1(Q4_1Block::new(
206                f16::from_f32(scale),
207                f16::from_f32(min),
208                packed,
209            ))
210        })
211        .collect();
212
213    Ok(QuantizedTensor::new(shape, QuantType::Q4_1, blocks))
214}
215
216// =============================================================================
217// F16 Quantization
218// =============================================================================
219
220/// Quantizes data to F16 format (half precision).
221fn quantize_f16(data: &[f32], shape: Vec<usize>) -> QuantResult<QuantizedTensor> {
222    let f16_data: Vec<f16> = data.par_iter().map(|&x| f16::from_f32(x)).collect();
223
224    let blocks = vec![QuantizedBlock::F16(f16_data)];
225
226    Ok(QuantizedTensor::new(shape, QuantType::F16, blocks))
227}
228
229// =============================================================================
230// F32 (No Quantization)
231// =============================================================================
232
233/// Stores data as F32 (no quantization, for comparison).
234fn quantize_f32(data: &[f32], shape: Vec<usize>) -> QuantResult<QuantizedTensor> {
235    let blocks = vec![QuantizedBlock::F32(data.to_vec())];
236    Ok(QuantizedTensor::new(shape, QuantType::F32, blocks))
237}
238
239// =============================================================================
240// Utility Functions
241// =============================================================================
242
243/// Computes the quantization error (RMSE) between original and quantized.
244pub fn compute_quantization_error(original: &[f32], dequantized: &[f32]) -> f32 {
245    if original.len() != dequantized.len() || original.is_empty() {
246        return f32::INFINITY;
247    }
248
249    let mse: f32 = original
250        .iter()
251        .zip(dequantized.iter())
252        .map(|(a, b)| (a - b).powi(2))
253        .sum::<f32>()
254        / original.len() as f32;
255
256    mse.sqrt()
257}
258
259/// Returns statistics about quantization error.
260pub struct QuantizationStats {
261    /// Root mean square error.
262    pub rmse: f32,
263    /// Maximum absolute error.
264    pub max_error: f32,
265    /// Mean absolute error.
266    pub mean_error: f32,
267    /// Compression ratio.
268    pub compression_ratio: f32,
269}
270
271/// Computes detailed quantization statistics.
272pub fn compute_quantization_stats(
273    original: &[f32],
274    dequantized: &[f32],
275    quant_type: QuantType,
276) -> QuantizationStats {
277    let errors: Vec<f32> = original
278        .iter()
279        .zip(dequantized.iter())
280        .map(|(a, b)| (a - b).abs())
281        .collect();
282
283    let mse: f32 = errors.iter().map(|e| e.powi(2)).sum::<f32>() / errors.len() as f32;
284    let max_error = errors.iter().fold(0.0f32, |a, &b| a.max(b));
285    let mean_error = errors.iter().sum::<f32>() / errors.len() as f32;
286
287    QuantizationStats {
288        rmse: mse.sqrt(),
289        max_error,
290        mean_error,
291        compression_ratio: quant_type.compression_ratio(),
292    }
293}
294
295// =============================================================================
296// Tests
297// =============================================================================
298
299#[cfg(test)]
300mod tests {
301    use super::*;
302
303    #[test]
304    fn test_quantize_q8_0() {
305        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0];
306        let tensor = Tensor::from_vec(data.clone(), &[8]).unwrap();
307        let quantized = quantize_tensor(&tensor, QuantType::Q8_0).unwrap();
308
309        assert_eq!(quantized.quant_type, QuantType::Q8_0);
310        assert_eq!(quantized.shape, vec![8]);
311        assert_eq!(quantized.num_blocks(), 1);
312    }
313
314    #[test]
315    fn test_quantize_q4_0() {
316        let data: Vec<f32> = (0..64).map(|x| x as f32 / 10.0).collect();
317        let tensor = Tensor::from_vec(data.clone(), &[64]).unwrap();
318        let quantized = quantize_tensor(&tensor, QuantType::Q4_0).unwrap();
319
320        assert_eq!(quantized.quant_type, QuantType::Q4_0);
321        assert_eq!(quantized.num_blocks(), 2);
322    }
323
324    #[test]
325    fn test_quantize_f16() {
326        let data = vec![1.0, 2.0, 3.0, 4.0];
327        let tensor = Tensor::from_vec(data.clone(), &[4]).unwrap();
328        let quantized = quantize_tensor(&tensor, QuantType::F16).unwrap();
329
330        assert_eq!(quantized.quant_type, QuantType::F16);
331    }
332
333    #[test]
334    fn test_compression_ratio() {
335        let data: Vec<f32> = (0..256).map(|x| x as f32).collect();
336        let tensor = Tensor::from_vec(data, &[256]).unwrap();
337
338        let q8 = quantize_tensor(&tensor, QuantType::Q8_0).unwrap();
339        let q4 = quantize_tensor(&tensor, QuantType::Q4_0).unwrap();
340
341        // Q8 should be about 4x compression, Q4 about 8x
342        assert!(q8.compression_ratio() > 2.0);
343        assert!(q4.compression_ratio() > q8.compression_ratio());
344    }
345
346    #[test]
347    fn test_quantization_error() {
348        let original = vec![1.0, 2.0, 3.0, 4.0];
349        let dequantized = vec![1.1, 2.0, 2.9, 4.1];
350
351        let rmse = compute_quantization_error(&original, &dequantized);
352        assert!(rmse > 0.0);
353        assert!(rmse < 0.2);
354    }
355}