torsh_backend/quantization/
mod.rs1#![allow(dead_code)]
56pub mod core;
58pub mod ops;
59pub mod params;
60pub mod tensor;
61pub mod types;
62
63pub mod accelerator;
65pub mod hardware;
66pub mod specialized;
67
68pub mod benchmarks;
70pub mod calibration;
71
72pub use core::{dequantize_from_int8, quantize_to_int8};
74pub use ops::{CpuQuantizationOps, QuantizationOps};
75pub use params::QuantizationParams;
76pub use tensor::QuantizedTensor;
77pub use types::{QuantizationScheme, QuantizedDType};
78
79pub use hardware::{
81 QuantizationHardwareFeatures, QuantizationPerformanceHints, QuantizedMemoryLayout,
82 SimdQuantizationOps,
83};
84
85pub use specialized::{
87 Dp4aQuantizationOps, SpecializedQuantizationOps, TensorCoreFormat, TensorCoreQuantizationOps,
88 VnniQuantizationOps,
89};
90
91pub use accelerator::{
93 AdvancedQuantizationAccelerator, AutoTuningConfig, BenchmarkResults, OptimalQuantizationConfig,
94 PerformanceRequirements, QuantizationOperationType, QuantizationRecommendations,
95 QuantizationWorkload,
96};
97
98pub use calibration::{
100 CalibrationFunction, CalibrationMethod, CalibrationStatistics, PercentileCalibrator,
101 QuantizationCalibrator,
102};
103
104pub use benchmarks::{
106 BenchmarkConfig, BenchmarkResult, BenchmarkSummary, ComparativeBenchmarkResult,
107 MemoryBenchmarkResults, MemoryUsage, QuantizationBenchmarkSuite,
108};
109
110use crate::{BackendResult, Device};
111use std::sync::Arc;
112
113#[cfg(not(feature = "std"))]
114use alloc::{boxed::Box, string::String, sync::Arc, vec::Vec};
115
116pub fn create_quantization_system(device: Device) -> BackendResult<QuantizationSystem> {
139 QuantizationSystem::new(device)
140}
141
142pub fn create_optimal_params(dtype: QuantizedDType, accuracy_priority: bool) -> QuantizationParams {
156 if accuracy_priority {
157 match dtype {
159 QuantizedDType::Int8 => QuantizationParams::int8_symmetric(),
160 QuantizedDType::UInt8 => QuantizationParams::uint8_asymmetric(),
161 QuantizedDType::Int4 => QuantizationParams::int4_symmetric(),
162 _ => {
163 let mut params = QuantizationParams::default();
164 params.dtype = dtype;
165 params
166 }
167 }
168 } else {
169 let mut params = QuantizationParams {
171 dtype: dtype.clone(),
172 scheme: QuantizationScheme::Symmetric, scale: vec![1.0],
174 zero_point: vec![0],
175 block_size: None,
176 min_val: None,
177 max_val: None,
178 };
179
180 if matches!(
182 dtype,
183 QuantizedDType::UInt8 | QuantizedDType::UInt4 | QuantizedDType::UInt16
184 ) {
185 params.scheme = QuantizationScheme::Asymmetric;
186 }
187
188 params
189 }
190}
191
192#[derive(Debug)]
197pub struct QuantizationSystem {
198 device: Device,
200 hw_features: QuantizationHardwareFeatures,
202 base_ops: CpuQuantizationOps,
204 accelerator: Option<AdvancedQuantizationAccelerator>,
206 calibrator: QuantizationCalibrator,
208 benchmark_suite: QuantizationBenchmarkSuite,
210}
211
212impl QuantizationSystem {
213 pub fn new(device: Device) -> BackendResult<Self> {
215 let hw_features = QuantizationHardwareFeatures::detect_for_device(&device);
216 let base_ops = CpuQuantizationOps::new();
217
218 let accelerator = if hw_features.supports_int8_simd || hw_features.supports_tensor_cores {
220 Some(AdvancedQuantizationAccelerator::new(
221 device.clone(),
222 Arc::new(base_ops.clone()),
223 ))
224 } else {
225 None
226 };
227
228 let calibrator = QuantizationCalibrator::new(CalibrationMethod::Adaptive, device.clone());
229 let benchmark_suite =
230 QuantizationBenchmarkSuite::new(device.clone(), BenchmarkConfig::default());
231
232 Ok(Self {
233 device,
234 hw_features,
235 base_ops,
236 accelerator,
237 calibrator,
238 benchmark_suite,
239 })
240 }
241
242 pub fn hardware_features(&self) -> &QuantizationHardwareFeatures {
244 &self.hw_features
245 }
246
247 pub fn device(&self) -> &Device {
249 &self.device
250 }
251
252 pub fn has_acceleration(&self) -> bool {
254 self.accelerator.is_some()
255 }
256
257 pub fn get_recommendations(
259 &self,
260 workload: &QuantizationWorkload,
261 ) -> QuantizationRecommendations {
262 if let Some(ref accelerator) = self.accelerator {
263 accelerator.get_recommendations(workload)
264 } else {
265 QuantizationRecommendations::default()
267 }
268 }
269
270 pub fn calibrate_from_samples(
272 &mut self,
273 samples: Vec<Vec<f32>>,
274 dtype: QuantizedDType,
275 method: CalibrationMethod,
276 ) -> BackendResult<QuantizationParams> {
277 self.calibrator.set_method(method);
278 self.calibrator.clear_samples();
279 self.calibrator.add_samples(samples);
280 self.calibrator.calibrate(dtype)
281 }
282
283 pub fn auto_tune(
285 &mut self,
286 workload: &QuantizationWorkload,
287 ) -> BackendResult<OptimalQuantizationConfig> {
288 if let Some(ref mut accelerator) = self.accelerator {
289 accelerator.auto_tune(workload)
290 } else {
291 Ok(OptimalQuantizationConfig::default())
293 }
294 }
295
296 pub fn benchmark_operations(&mut self) -> BackendResult<BenchmarkSummary> {
298 self.benchmark_suite
299 .benchmark_quantization_ops(&self.base_ops)
300 }
301
302 pub fn quantize_f32(
304 &self,
305 input: &[f32],
306 params: &QuantizationParams,
307 ) -> BackendResult<Vec<u8>> {
308 if self.should_use_acceleration(¶ms.dtype) {
310 if let Some(ref _accelerator) = self.accelerator {
311 return self.base_ops.quantize_f32(input, params);
314 }
315 }
316
317 self.base_ops.quantize_f32(input, params)
318 }
319
320 pub fn dequantize_f32(
322 &self,
323 input: &[u8],
324 params: &QuantizationParams,
325 ) -> BackendResult<Vec<f32>> {
326 if self.should_use_acceleration(¶ms.dtype) {
328 if let Some(ref _accelerator) = self.accelerator {
329 return self.base_ops.dequantize_f32(input, params);
332 }
333 }
334
335 self.base_ops.dequantize_f32(input, params)
336 }
337
338 pub fn qmatmul(
340 &self,
341 a: &QuantizedTensor,
342 b: &QuantizedTensor,
343 ) -> BackendResult<QuantizedTensor> {
344 self.base_ops.qmatmul(a, b)
345 }
346
347 fn should_use_acceleration(&self, dtype: &QuantizedDType) -> bool {
349 self.hw_features.supports_dtype_efficiently(dtype)
350 }
351
352 pub fn create_quantized_tensor(
354 &self,
355 shape: Vec<usize>,
356 params: QuantizationParams,
357 ) -> QuantizedTensor {
358 QuantizedTensor::new(shape, params, self.device.clone())
359 }
360
361 pub fn optimal_block_size(&self) -> usize {
363 self.hw_features.optimal_block_size()
364 }
365
366 pub fn performance_hints(&self) -> QuantizationPerformanceHints {
368 QuantizationPerformanceHints::for_hardware(&self.hw_features)
369 }
370}
371
372pub fn auto_quantize_tensor(
378 data: &[f32],
379 shape: Vec<usize>,
380 device: Device,
381 target_dtype: QuantizedDType,
382) -> BackendResult<QuantizedTensor> {
383 let mut calibrator = QuantizationCalibrator::new(CalibrationMethod::Adaptive, device.clone());
385 calibrator.add_sample(data.to_vec());
386
387 let params = calibrator.calibrate(target_dtype)?;
388
389 let system = QuantizationSystem::new(device)?;
391 let quantized_data = system.quantize_f32(data, ¶ms)?;
392
393 Ok(QuantizedTensor {
394 data: quantized_data,
395 shape,
396 params,
397 device: system.device.clone(),
398 })
399}
400
401pub fn estimate_memory_savings(dtype: &QuantizedDType) -> f64 {
406 let fp32_bits = 32.0;
407 let quantized_bits = dtype.bits() as f64;
408 1.0 - (quantized_bits / fp32_bits)
409}
410
411pub fn estimate_accuracy_impact(dtype: &QuantizedDType, scheme: QuantizationScheme) -> f64 {
416 let base_accuracy: f64 = match dtype {
418 QuantizedDType::Int16 | QuantizedDType::UInt16 => 0.99,
419 QuantizedDType::Int8 | QuantizedDType::UInt8 => 0.95,
420 QuantizedDType::Int4 | QuantizedDType::UInt4 => 0.85,
421 QuantizedDType::Binary => 0.70,
422 QuantizedDType::Mixed(_) => 0.90,
423 };
424
425 let scheme_factor: f64 = match scheme {
427 QuantizationScheme::Symmetric => 1.0,
428 QuantizationScheme::Linear => 0.98,
429 QuantizationScheme::Asymmetric => 0.96,
430 QuantizationScheme::ChannelWise => 1.02, QuantizationScheme::BlockWise => 1.01, QuantizationScheme::Logarithmic => 0.90, };
434
435 (base_accuracy * scheme_factor).min(1.0f64)
436}
437
438#[cfg(test)]
439mod tests {
440 use super::*;
441
442 #[test]
443 fn test_create_quantization_system() {
444 let device = Device::cpu().expect("Device should succeed");
445 let system = create_quantization_system(device);
446 assert!(system.is_ok());
447
448 let system = system.expect("operation should succeed");
449 assert!(!system.device().device_type().to_string().is_empty());
450 }
451
452 #[test]
453 fn test_create_optimal_params() {
454 let params_acc = create_optimal_params(QuantizedDType::Int8, true);
456 assert_eq!(params_acc.dtype, QuantizedDType::Int8);
457 assert_eq!(params_acc.scheme, QuantizationScheme::Symmetric);
458
459 let params_speed = create_optimal_params(QuantizedDType::UInt8, false);
461 assert_eq!(params_speed.dtype, QuantizedDType::UInt8);
462 assert_eq!(params_speed.scheme, QuantizationScheme::Asymmetric);
463 }
464
465 #[test]
466 fn test_quantization_system_creation() {
467 let device = Device::cpu().expect("Device should succeed");
468 let system = QuantizationSystem::new(device);
469 assert!(system.is_ok());
470
471 let system = system.expect("operation should succeed");
472 assert!(system.hardware_features().max_parallel_ops >= 1);
473 }
474
475 #[test]
476 fn test_quantization_system_operations() {
477 let device = Device::cpu().expect("Device should succeed");
478 let system = QuantizationSystem::new(device).expect("Quantization System should succeed");
479
480 let data = vec![1.0, 2.0, 3.0, 4.0];
481 let params = QuantizationParams::int8_symmetric();
482
483 let quantized = system.quantize_f32(&data, ¶ms);
485 assert!(quantized.is_ok());
486
487 let quantized_data = quantized.expect("operation should succeed");
489 let dequantized = system.dequantize_f32(&quantized_data, ¶ms);
490 assert!(dequantized.is_ok());
491
492 let dequantized_data = dequantized.expect("operation should succeed");
493 assert_eq!(dequantized_data.len(), data.len());
494 }
495
496 #[test]
497 fn test_auto_quantize_tensor() {
498 let device = Device::cpu().expect("Device should succeed");
499 let data = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
500 let shape = vec![2, 3];
501
502 let result = auto_quantize_tensor(&data, shape.clone(), device, QuantizedDType::Int8);
503 assert!(result.is_ok());
504
505 let tensor = result.expect("operation should succeed");
506 assert_eq!(tensor.shape, shape);
507 assert_eq!(tensor.params.dtype, QuantizedDType::Int8);
508 }
509
510 #[test]
511 fn test_memory_savings_estimation() {
512 let savings_int8 = estimate_memory_savings(&QuantizedDType::Int8);
514 assert!((savings_int8 - 0.75).abs() < 0.01);
515
516 let savings_int4 = estimate_memory_savings(&QuantizedDType::Int4);
518 assert!((savings_int4 - 0.875).abs() < 0.01);
519
520 let savings_binary = estimate_memory_savings(&QuantizedDType::Binary);
522 assert!((savings_binary - 0.96875).abs() < 0.01);
523 }
524
525 #[test]
526 fn test_accuracy_impact_estimation() {
527 let accuracy_int8 =
529 estimate_accuracy_impact(&QuantizedDType::Int8, QuantizationScheme::Symmetric);
530 assert!(accuracy_int8 >= 0.90);
531
532 let accuracy_int4 =
534 estimate_accuracy_impact(&QuantizedDType::Int4, QuantizationScheme::Symmetric);
535 assert!(accuracy_int4 < accuracy_int8);
536
537 let accuracy_channelwise =
539 estimate_accuracy_impact(&QuantizedDType::Int8, QuantizationScheme::ChannelWise);
540 let accuracy_linear =
541 estimate_accuracy_impact(&QuantizedDType::Int8, QuantizationScheme::Linear);
542 assert!(accuracy_channelwise >= accuracy_linear);
543 }
544
545 #[test]
546 fn test_quantization_system_calibration() {
547 let device = Device::cpu().expect("Device should succeed");
548 let mut system =
549 QuantizationSystem::new(device).expect("Quantization System should succeed");
550
551 let samples = vec![vec![1.0, 2.0, 3.0], vec![4.0, 5.0, 6.0]];
552
553 let result =
554 system.calibrate_from_samples(samples, QuantizedDType::Int8, CalibrationMethod::MinMax);
555
556 assert!(result.is_ok());
557 let params = result.expect("operation should succeed");
558 assert_eq!(params.dtype, QuantizedDType::Int8);
559 }
560
561 #[test]
562 fn test_quantization_system_benchmarking() {
563 let device = Device::cpu().expect("Device should succeed");
564 let mut system =
565 QuantizationSystem::new(device).expect("Quantization System should succeed");
566
567 let result = system.benchmark_operations();
568 assert!(result.is_ok());
569
570 let summary = result.expect("operation should succeed");
571 assert!(!summary.results.is_empty());
572 }
573
574 #[test]
575 fn test_quantization_system_tensor_creation() {
576 let device = Device::cpu().expect("Device should succeed");
577 let system = QuantizationSystem::new(device).expect("Quantization System should succeed");
578
579 let shape = vec![2, 3, 4];
580 let params = QuantizationParams::int8_symmetric();
581
582 let tensor = system.create_quantized_tensor(shape.clone(), params.clone());
583 assert_eq!(tensor.shape, shape);
584 assert_eq!(tensor.params.dtype, params.dtype);
585 }
586
587 #[test]
588 fn test_quantization_system_performance_hints() {
589 let device = Device::cpu().expect("Device should succeed");
590 let system = QuantizationSystem::new(device).expect("Quantization System should succeed");
591
592 let hints = system.performance_hints();
593 assert!(!hints.preferred_dtypes.is_empty());
594 assert!(!hints.preferred_schemes.is_empty());
595 assert!(hints.optimal_batch_size > 0);
596 }
597}