1use 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
25pub 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 quantize_q4_0(&data, shape)
59 }
60 QuantType::F16 => quantize_f16(&data, shape),
61 QuantType::F32 => quantize_f32(&data, shape),
62 }
63}
64
65pub 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
86fn 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 let max_abs = block_data
104 .iter()
105 .map(|x| x.abs())
106 .fold(0.0f32, |a, b| a.max(b));
107
108 let scale = if max_abs > 0.0 { max_abs / 127.0 } else { 1.0 };
110
111 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
125fn 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 let max_abs = block_data
143 .iter()
144 .map(|x| x.abs())
145 .fold(0.0f32, |a, b| a.max(b));
146
147 let scale = if max_abs > 0.0 { max_abs / 7.0 } else { 1.0 };
149
150 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 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
167fn 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 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 let scale = if max > min { (max - min) / 15.0 } else { 1.0 };
189
190 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 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
216fn 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
229fn 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
239pub 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
259pub struct QuantizationStats {
261 pub rmse: f32,
263 pub max_error: f32,
265 pub mean_error: f32,
267 pub compression_ratio: f32,
269}
270
271pub 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#[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 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}