Skip to main content

trustformers_mobile/optimization/
quantization.rs

1//! Mobile Quantization Module
2//!
3//! Provides efficient quantization implementations for mobile deployment including:
4//! - INT4 quantization for ultra-low memory
5//! - INT8 quantization for balanced performance
6//! - FP16 quantization for GPU acceleration
7//! - Dynamic quantization for runtime adaptation
8
9use half::f16;
10use scirs2_core::ndarray::{ArrayD, IxDyn};
11use serde::{Deserialize, Serialize};
12use std::collections::HashMap;
13use std::fs::File;
14use std::io::BufReader;
15use std::path::{Path, PathBuf};
16use trustformers_core::errors::{invalid_config, runtime_error, tensor_op_error, Result};
17use trustformers_core::Tensor;
18
19/// Quantization scheme types
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
21// reason: variants mirror standard ML dtype spellings (e.g. FP16, INT8).
22#[allow(non_camel_case_types)]
23pub enum QuantizationScheme {
24    Int4,
25    Int8,
26    FP16,
27    Dynamic,
28    /// GGUF Q2_K: 2.5625 bits per weight, ultra-low memory
29    GGUF_Q2_K,
30    /// GGUF Q3_K: 3.4375 bits per weight, balanced
31    GGUF_Q3_K,
32    /// GGUF Q4_K: 4.5 bits per weight, high quality
33    GGUF_Q4_K,
34    /// GGUF Q5_0: 5.5 bits per weight, very high quality
35    GGUF_Q5_0,
36    /// GGUF Q6_K: 6.5 bits per weight, near-lossless
37    GGUF_Q6_K,
38}
39
40impl std::fmt::Display for QuantizationScheme {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        match self {
43            QuantizationScheme::Int4 => write!(f, "INT4"),
44            QuantizationScheme::Int8 => write!(f, "INT8"),
45            QuantizationScheme::FP16 => write!(f, "FP16"),
46            QuantizationScheme::Dynamic => write!(f, "Dynamic"),
47            QuantizationScheme::GGUF_Q2_K => write!(f, "GGUF_Q2_K"),
48            QuantizationScheme::GGUF_Q3_K => write!(f, "GGUF_Q3_K"),
49            QuantizationScheme::GGUF_Q4_K => write!(f, "GGUF_Q4_K"),
50            QuantizationScheme::GGUF_Q5_0 => write!(f, "GGUF_Q5_0"),
51            QuantizationScheme::GGUF_Q6_K => write!(f, "GGUF_Q6_K"),
52        }
53    }
54}
55
56/// Calibration method for quantization
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum CalibrationMethod {
59    MinMax,
60    Percentile,
61    MovingAverage,
62    KLDivergence,
63}
64
65/// Quantization context with calibration data
66#[derive(Debug, Clone)]
67pub struct QuantizationContext {
68    pub method: CalibrationMethod,
69    pub num_calibration_samples: usize,
70    pub percentile: f32,    // For percentile method
71    pub smooth_factor: f32, // For moving average
72}
73
74impl Default for QuantizationContext {
75    fn default() -> Self {
76        Self {
77            method: CalibrationMethod::MinMax,
78            num_calibration_samples: 100,
79            percentile: 99.9,
80            smooth_factor: 0.999,
81        }
82    }
83}
84
85/// Quantization calibration data
86#[derive(Debug, Clone, Default)]
87pub struct QuantizationCalibration {
88    pub min_values: HashMap<String, f32>,
89    pub max_values: HashMap<String, f32>,
90    pub scales: HashMap<String, f32>,
91    pub zero_points: HashMap<String, i32>,
92    pub histogram_bins: HashMap<String, Vec<f32>>,
93}
94
95/// External quantization scheme configuration
96#[derive(Debug, Clone, Serialize, Deserialize)]
97pub struct QuantizationSchemeConfig {
98    /// Default quantization scheme
99    pub default_scheme: QuantizationScheme,
100    /// Layer-specific quantization schemes
101    pub layer_schemes: HashMap<String, QuantizationScheme>,
102    /// Tensor-specific quantization schemes (by hash or name)
103    pub tensor_schemes: HashMap<String, QuantizationScheme>,
104    /// Model-specific schemes
105    pub model_schemes: HashMap<String, QuantizationScheme>,
106    /// Performance-based scheme mappings
107    pub performance_schemes: HashMap<String, QuantizationScheme>,
108}
109
110impl Default for QuantizationSchemeConfig {
111    fn default() -> Self {
112        Self {
113            default_scheme: QuantizationScheme::Int8,
114            layer_schemes: HashMap::new(),
115            tensor_schemes: HashMap::new(),
116            model_schemes: HashMap::new(),
117            performance_schemes: HashMap::new(),
118        }
119    }
120}
121
122/// Quantization scheme storage manager
123#[derive(Debug, Clone)]
124pub struct QuantizationSchemeStorage {
125    /// Configuration file path
126    pub config_path: Option<PathBuf>,
127    /// In-memory configuration
128    pub config: QuantizationSchemeConfig,
129    /// Cache for recently determined schemes
130    pub scheme_cache: HashMap<String, QuantizationScheme>,
131}
132
133impl Default for QuantizationSchemeStorage {
134    fn default() -> Self {
135        Self::new()
136    }
137}
138
139impl QuantizationSchemeStorage {
140    /// Create a new storage manager
141    pub fn new() -> Self {
142        Self {
143            config_path: None,
144            config: QuantizationSchemeConfig::default(),
145            scheme_cache: HashMap::new(),
146        }
147    }
148
149    /// Create storage manager with config file
150    pub fn with_config_file<P: AsRef<Path>>(path: P) -> Result<Self> {
151        let config_path = path.as_ref().to_path_buf();
152        let config = Self::load_config(&config_path)?;
153
154        Ok(Self {
155            config_path: Some(config_path),
156            config,
157            scheme_cache: HashMap::new(),
158        })
159    }
160
161    /// Load configuration from file
162    pub fn load_config<P: AsRef<Path>>(path: P) -> Result<QuantizationSchemeConfig> {
163        let file = File::open(path.as_ref())
164            .map_err(|e| runtime_error(format!("Failed to open config file: {}", e)))?;
165        let reader = BufReader::new(file);
166
167        serde_json::from_reader(reader)
168            .map_err(|e| invalid_config("load_config", format!("Failed to parse config: {}", e)))
169    }
170
171    /// Save configuration to file
172    pub fn save_config(&self) -> Result<()> {
173        if let Some(ref path) = self.config_path {
174            let file = File::create(path)
175                .map_err(|e| runtime_error(format!("Failed to create config file: {}", e)))?;
176
177            serde_json::to_writer_pretty(file, &self.config)
178                .map_err(|e| runtime_error(format!("Failed to write config: {}", e)))?;
179        }
180        Ok(())
181    }
182
183    /// Determine quantization scheme for a tensor
184    pub fn determine_scheme(
185        &mut self,
186        tensor_id: &str,
187        layer_name: Option<&str>,
188        model_name: Option<&str>,
189    ) -> QuantizationScheme {
190        // Check cache first
191        if let Some(&scheme) = self.scheme_cache.get(tensor_id) {
192            return scheme;
193        }
194
195        // Check tensor-specific scheme
196        if let Some(&scheme) = self.config.tensor_schemes.get(tensor_id) {
197            self.scheme_cache.insert(tensor_id.to_string(), scheme);
198            return scheme;
199        }
200
201        // Check layer-specific scheme
202        if let Some(layer) = layer_name {
203            if let Some(&scheme) = self.config.layer_schemes.get(layer) {
204                self.scheme_cache.insert(tensor_id.to_string(), scheme);
205                return scheme;
206            }
207        }
208
209        // Check model-specific scheme
210        if let Some(model) = model_name {
211            if let Some(&scheme) = self.config.model_schemes.get(model) {
212                self.scheme_cache.insert(tensor_id.to_string(), scheme);
213                return scheme;
214            }
215        }
216
217        // Use default scheme
218        let default_scheme = self.config.default_scheme;
219        self.scheme_cache.insert(tensor_id.to_string(), default_scheme);
220        default_scheme
221    }
222
223    /// Set scheme for specific tensor
224    pub fn set_tensor_scheme(&mut self, tensor_id: String, scheme: QuantizationScheme) {
225        self.config.tensor_schemes.insert(tensor_id.clone(), scheme);
226        self.scheme_cache.insert(tensor_id, scheme);
227    }
228
229    /// Set scheme for specific layer
230    pub fn set_layer_scheme(&mut self, layer_name: String, scheme: QuantizationScheme) {
231        self.config.layer_schemes.insert(layer_name, scheme);
232    }
233
234    /// Set scheme for specific model
235    pub fn set_model_scheme(&mut self, model_name: String, scheme: QuantizationScheme) {
236        self.config.model_schemes.insert(model_name, scheme);
237    }
238
239    /// Clear cache
240    pub fn clear_cache(&mut self) {
241        self.scheme_cache.clear();
242    }
243
244    /// Generate tensor ID from tensor properties
245    pub fn generate_tensor_id(tensor: &Tensor, layer_name: Option<&str>) -> String {
246        let shape_str = tensor.shape().iter().map(|&s| s.to_string()).collect::<Vec<_>>().join("x");
247
248        let data_hash = {
249            if let Ok(data) = tensor.data() {
250                let sample_size = (data.len() / 100).max(1).min(1000); // Sample for hash
251                let mut hash = 0u64;
252                for i in (0..data.len()).step_by(sample_size) {
253                    hash = hash.wrapping_mul(31).wrapping_add(data[i].to_bits() as u64);
254                }
255                hash
256            } else {
257                0u64 // Default hash if data access fails
258            }
259        };
260
261        match layer_name {
262            Some(layer) => format!("{}:{}:{:x}", layer, shape_str, data_hash),
263            None => format!("tensor:{}:{:x}", shape_str, data_hash),
264        }
265    }
266}
267
268/// Trait for mobile quantizers
269pub trait MobileQuantizer: Send + Sync {
270    /// Get the quantization scheme
271    fn get_scheme(&self) -> QuantizationScheme;
272
273    /// Check if calibration is required
274    fn requires_calibration(&self) -> bool;
275
276    /// Calibrate the quantizer with sample data
277    fn calibrate(&self, data: &[Tensor]) -> Result<()>;
278
279    /// Quantize a tensor
280    fn quantize_tensor(&self, tensor: &Tensor) -> Result<Tensor>;
281
282    /// Dequantize a tensor
283    fn dequantize_tensor(&self, tensor: &Tensor) -> Result<Tensor>;
284}
285
286/// INT4 Quantizer - Ultra-low memory for mobile
287pub struct Int4Quantizer {
288    context: QuantizationContext,
289    calibration: std::sync::RwLock<QuantizationCalibration>,
290}
291
292impl Default for Int4Quantizer {
293    fn default() -> Self {
294        Self::new()
295    }
296}
297
298impl Int4Quantizer {
299    pub fn new() -> Self {
300        Self {
301            context: QuantizationContext::default(),
302            calibration: std::sync::RwLock::new(QuantizationCalibration::default()),
303        }
304    }
305
306    fn compute_scale_zero_point(&self, min_val: f32, max_val: f32) -> (f32, i32) {
307        let qmin = -8.0; // 4-bit signed: -8 to 7
308        let qmax = 7.0;
309
310        let scale = (max_val - min_val) / (qmax - qmin);
311        let zero_point = ((qmin - min_val / scale).round() as i32).clamp(-8, 7);
312
313        (scale, zero_point)
314    }
315
316    fn quantize_value(&self, value: f32, scale: f32, zero_point: i32) -> i8 {
317        let quantized = (value / scale).round() as i32 + zero_point;
318        quantized.clamp(-8, 7) as i8
319    }
320
321    fn dequantize_value(&self, quantized: i8, scale: f32, zero_point: i32) -> f32 {
322        (quantized as i32 - zero_point) as f32 * scale
323    }
324}
325
326impl MobileQuantizer for Int4Quantizer {
327    fn get_scheme(&self) -> QuantizationScheme {
328        QuantizationScheme::Int4
329    }
330
331    fn requires_calibration(&self) -> bool {
332        true
333    }
334
335    fn calibrate(&self, data: &[Tensor]) -> Result<()> {
336        let mut calibration = self.calibration.write().unwrap_or_else(|p| p.into_inner());
337
338        for tensor in data {
339            let tensor_data = tensor.data()?;
340            let min_val = tensor_data.iter().fold(f32::INFINITY, |a, &b| a.min(b));
341            let max_val = tensor_data.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b));
342
343            let (scale, zero_point) = self.compute_scale_zero_point(min_val, max_val);
344
345            // Store as global calibration parameters (simplified for single tensor case)
346            calibration.min_values.insert("global".to_string(), min_val);
347            calibration.max_values.insert("global".to_string(), max_val);
348            calibration.scales.insert("global".to_string(), scale);
349            calibration.zero_points.insert("global".to_string(), zero_point);
350        }
351
352        Ok(())
353    }
354
355    fn quantize_tensor(&self, tensor: &Tensor) -> Result<Tensor> {
356        let calibration = self.calibration.read().unwrap_or_else(|p| p.into_inner());
357        let tensor_data = tensor.data()?;
358
359        // Get or compute scale and zero point
360        let (scale, zero_point) = if let Some(&scale) = calibration.scales.get("global") {
361            (
362                scale,
363                *calibration
364                    .zero_points
365                    .get("global")
366                    .ok_or_else(|| runtime_error("missing global zero point".to_string()))?,
367            )
368        } else {
369            // Compute on the fly if not calibrated
370            let min_val = tensor_data.iter().fold(f32::INFINITY, |a, &b| a.min(b));
371            let max_val = tensor_data.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b));
372            self.compute_scale_zero_point(min_val, max_val)
373        };
374
375        // Quantize to INT4 (stored as individual i8 values for compatibility)
376        let quantized_data: Vec<i8> =
377            tensor_data.iter().map(|&x| self.quantize_value(x, scale, zero_point)).collect();
378
379        // Convert to f32 for tensor storage (maintain same shape)
380        let quantized_f32: Vec<f32> = quantized_data.iter().map(|&x| x as f32).collect();
381
382        // Create quantized tensor with same shape as original
383        let quantized_tensor = Tensor::from_vec(quantized_f32, &tensor.shape())?;
384
385        // Note: Quantization parameters stored separately (tensor doesn't support metadata)
386
387        Ok(quantized_tensor)
388    }
389
390    fn dequantize_tensor(&self, tensor: &Tensor) -> Result<Tensor> {
391        let calibration = self.calibration.read().unwrap_or_else(|p| p.into_inner());
392        let tensor_data = tensor.data()?;
393
394        // Get quantization parameters from calibration data
395        let (scale, zero_point) = if let Some(&scale) = calibration.scales.get("global") {
396            (
397                scale,
398                *calibration
399                    .zero_points
400                    .get("global")
401                    .ok_or_else(|| runtime_error("missing global zero point".to_string()))?,
402            )
403        } else {
404            // Fallback: estimate from quantized data range
405            let min_q = tensor_data.iter().fold(f32::INFINITY, |a, &b| a.min(b)) as i8;
406            let max_q = tensor_data.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b)) as i8;
407            let range = (max_q - min_q) as f32;
408            let scale = if range > 0.0 { 15.0 / range } else { 1.0 }; // 4-bit range is -8 to 7 = 15
409            (scale, 0)
410        };
411
412        // Dequantize i8 values back to f32
413        let dequantized_data: Vec<f32> = tensor_data
414            .iter()
415            .map(|&x| self.dequantize_value(x as i8, scale, zero_point))
416            .collect();
417
418        Tensor::from_vec(dequantized_data, &tensor.shape())
419    }
420}
421
422/// INT8 Quantizer - Balanced performance and accuracy
423pub struct Int8Quantizer {
424    context: QuantizationContext,
425    calibration: std::sync::RwLock<QuantizationCalibration>,
426    symmetric: bool,
427}
428
429impl Default for Int8Quantizer {
430    fn default() -> Self {
431        Self::new()
432    }
433}
434
435impl Int8Quantizer {
436    pub fn new() -> Self {
437        Self {
438            context: QuantizationContext::default(),
439            calibration: std::sync::RwLock::new(QuantizationCalibration::default()),
440            symmetric: true, // Symmetric quantization is often better for mobile
441        }
442    }
443
444    fn compute_scale_zero_point(&self, min_val: f32, max_val: f32) -> (f32, i32) {
445        if self.symmetric {
446            // Symmetric quantization (zero point = 0)
447            let abs_max = min_val.abs().max(max_val.abs());
448            let scale = abs_max / 127.0;
449            (scale, 0)
450        } else {
451            // Asymmetric quantization
452            let qmin = -128.0;
453            let qmax = 127.0;
454            let scale = (max_val - min_val) / (qmax - qmin);
455            let zero_point = ((qmin - min_val / scale).round() as i32).clamp(-128, 127);
456            (scale, zero_point)
457        }
458    }
459}
460
461impl MobileQuantizer for Int8Quantizer {
462    fn get_scheme(&self) -> QuantizationScheme {
463        QuantizationScheme::Int8
464    }
465
466    fn requires_calibration(&self) -> bool {
467        true
468    }
469
470    fn calibrate(&self, data: &[Tensor]) -> Result<()> {
471        let mut calibration = self.calibration.write().unwrap_or_else(|p| p.into_inner());
472
473        for tensor in data {
474            let tensor_data = tensor.data()?;
475
476            let (min_val, max_val) = match self.context.method {
477                CalibrationMethod::MinMax => {
478                    let min = tensor_data.iter().fold(f32::INFINITY, |a, &b| a.min(b));
479                    let max = tensor_data.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b));
480                    (min, max)
481                },
482                CalibrationMethod::Percentile => {
483                    let mut sorted = tensor_data.to_vec();
484                    sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
485                    let percentile_idx =
486                        (sorted.len() as f32 * self.context.percentile / 100.0) as usize;
487                    let min_idx =
488                        (sorted.len() as f32 * (100.0 - self.context.percentile) / 100.0) as usize;
489                    (
490                        sorted[min_idx],
491                        sorted[percentile_idx.min(sorted.len() - 1)],
492                    )
493                },
494                _ => {
495                    // For other methods, fall back to min-max
496                    let min = tensor_data.iter().fold(f32::INFINITY, |a, &b| a.min(b));
497                    let max = tensor_data.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b));
498                    (min, max)
499                },
500            };
501
502            let (scale, zero_point) = self.compute_scale_zero_point(min_val, max_val);
503
504            // Store as global calibration parameters (simplified for single tensor case)
505            calibration.min_values.insert("global".to_string(), min_val);
506            calibration.max_values.insert("global".to_string(), max_val);
507            calibration.scales.insert("global".to_string(), scale);
508            calibration.zero_points.insert("global".to_string(), zero_point);
509        }
510
511        Ok(())
512    }
513
514    fn quantize_tensor(&self, tensor: &Tensor) -> Result<Tensor> {
515        let calibration = self.calibration.read().unwrap_or_else(|p| p.into_inner());
516        let tensor_data = tensor.data()?;
517
518        let (scale, zero_point) = if let Some(&scale) = calibration.scales.get("global") {
519            (
520                scale,
521                *calibration
522                    .zero_points
523                    .get("global")
524                    .ok_or_else(|| runtime_error("missing global zero point".to_string()))?,
525            )
526        } else {
527            let min_val = tensor_data.iter().fold(f32::INFINITY, |a, &b| a.min(b));
528            let max_val = tensor_data.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b));
529            self.compute_scale_zero_point(min_val, max_val)
530        };
531
532        let quantized_data: Vec<i8> = tensor_data
533            .iter()
534            .map(|&x| {
535                let q = (x / scale).round() as i32 + zero_point;
536                q.clamp(-128, 127) as i8
537            })
538            .collect();
539
540        // Convert to f32 for tensor storage (temporary)
541        let quantized_f32: Vec<f32> = quantized_data.iter().map(|&x| x as f32).collect();
542
543        let quantized_tensor = Tensor::from_vec(quantized_f32, &tensor.shape())?;
544        // Note: Quantization parameters stored separately (tensor doesn't support metadata)
545
546        Ok(quantized_tensor)
547    }
548
549    fn dequantize_tensor(&self, tensor: &Tensor) -> Result<Tensor> {
550        let calibration = self.calibration.read().unwrap_or_else(|p| p.into_inner());
551        let tensor_data = tensor.data()?;
552
553        // Get quantization parameters from calibration data
554        let (scale, zero_point) = if let Some(&scale) = calibration.scales.get("global") {
555            (
556                scale,
557                *calibration
558                    .zero_points
559                    .get("global")
560                    .ok_or_else(|| runtime_error("missing global zero point".to_string()))?,
561            )
562        } else {
563            // Fallback: estimate from quantized data range
564            let min_q = tensor_data.iter().fold(f32::INFINITY, |a, &b| a.min(b)) as i32;
565            let max_q = tensor_data.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b)) as i32;
566            let range = (max_q - min_q) as f32;
567            let scale = if range > 0.0 { 255.0 / range } else { 1.0 }; // 8-bit range is 255
568            (scale, 0)
569        };
570
571        let dequantized_data: Vec<f32> =
572            tensor_data.iter().map(|&x| ((x as i32) - zero_point) as f32 * scale).collect();
573
574        Tensor::from_vec(dequantized_data, &tensor.shape())
575    }
576}
577
578/// FP16 Quantizer - Hardware-accelerated on modern mobile GPUs
579pub struct FP16Quantizer;
580
581impl Default for FP16Quantizer {
582    fn default() -> Self {
583        Self::new()
584    }
585}
586
587impl FP16Quantizer {
588    pub fn new() -> Self {
589        Self
590    }
591}
592
593impl MobileQuantizer for FP16Quantizer {
594    fn get_scheme(&self) -> QuantizationScheme {
595        QuantizationScheme::FP16
596    }
597
598    fn requires_calibration(&self) -> bool {
599        false // FP16 doesn't require calibration
600    }
601
602    fn calibrate(&self, _data: &[Tensor]) -> Result<()> {
603        Ok(()) // No calibration needed
604    }
605
606    /// Quantize to a genuinely `Tensor::F16`-backed tensor (2 bytes/element
607    /// in `half::f16`'s own `ArrayD`, via `trustformers_core::Tensor`'s
608    /// real `F16` variant) rather than rounding through `f16` for numerical
609    /// fidelity and then storing the result as `f32` again. The previous
610    /// implementation did exactly that round-trip-then-widen, so the
611    /// "quantized" tensor it returned occupied the same 4 bytes/element as
612    /// the original input -- `QuantizationScheme::FP16` was reported but
613    /// delivered 0% of the ~2x memory reduction FP16 quantization is
614    /// supposed to provide.
615    fn quantize_tensor(&self, tensor: &Tensor) -> Result<Tensor> {
616        let tensor_data = tensor.data()?;
617        let shape = tensor.shape();
618
619        let fp16_data: Vec<f16> = tensor_data.iter().map(|&x| f16::from_f32(x)).collect();
620        let array = ArrayD::from_shape_vec(IxDyn(&shape), fp16_data).map_err(|e| {
621            tensor_op_error(
622                "FP16Quantizer::quantize_tensor",
623                format!("shape {shape:?} incompatible with element count: {e}"),
624            )
625        })?;
626
627        Ok(Tensor::F16(array))
628    }
629
630    /// Convert a real `Tensor::F16` back to `Tensor::F32` for compute.
631    /// `trustformers_core::Tensor::to_f32`/`to_dtype` do not (yet) cover
632    /// `F16` as a source dtype, so the widening is done directly here
633    /// against the `Tensor::F16` variant's own public `ArrayD<half::f16>`
634    /// payload -- still real per-element conversion, just performed in
635    /// this crate rather than delegated to core.
636    fn dequantize_tensor(&self, tensor: &Tensor) -> Result<Tensor> {
637        match tensor {
638            Tensor::F16(array) => Ok(Tensor::F32(array.mapv(f32::from))),
639            Tensor::F32(_) => Ok(tensor.clone()),
640            other => Err(tensor_op_error(
641                "FP16Quantizer::dequantize_tensor",
642                format!(
643                    "expected an F16 (or already-F32) tensor, got {:?}",
644                    other.dtype()
645                ),
646            )),
647        }
648    }
649}
650
651/// Dynamic Quantizer - Adapts quantization based on runtime statistics
652pub struct DynamicQuantizer {
653    int8_quantizer: Int8Quantizer,
654    fp16_quantizer: FP16Quantizer,
655    selection_threshold: f32,
656    scheme_storage: QuantizationSchemeStorage,
657    layer_context: Option<String>,
658    model_context: Option<String>,
659}
660
661impl Default for DynamicQuantizer {
662    fn default() -> Self {
663        Self::new()
664    }
665}
666
667impl DynamicQuantizer {
668    pub fn new() -> Self {
669        Self {
670            int8_quantizer: Int8Quantizer::new(),
671            fp16_quantizer: FP16Quantizer::new(),
672            selection_threshold: 0.1, // 10% error threshold
673            scheme_storage: QuantizationSchemeStorage::new(),
674            layer_context: None,
675            model_context: None,
676        }
677    }
678
679    pub fn with_config_file<P: AsRef<Path>>(path: P) -> Result<Self> {
680        let scheme_storage = QuantizationSchemeStorage::with_config_file(path)?;
681        Ok(Self {
682            int8_quantizer: Int8Quantizer::new(),
683            fp16_quantizer: FP16Quantizer::new(),
684            selection_threshold: 0.1,
685            scheme_storage,
686            layer_context: None,
687            model_context: None,
688        })
689    }
690
691    pub fn set_layer_context(&mut self, layer_name: String) {
692        self.layer_context = Some(layer_name);
693    }
694
695    pub fn set_model_context(&mut self, model_name: String) {
696        self.model_context = Some(model_name);
697    }
698
699    /// Get mutable reference to scheme storage for configuration
700    pub fn scheme_storage_mut(&mut self) -> &mut QuantizationSchemeStorage {
701        &mut self.scheme_storage
702    }
703
704    /// Get reference to scheme storage
705    pub fn scheme_storage(&self) -> &QuantizationSchemeStorage {
706        &self.scheme_storage
707    }
708
709    fn select_quantization_scheme(&self, tensor: &Tensor) -> Result<QuantizationScheme> {
710        let tensor_data = tensor.data()?;
711
712        // Compute dynamic range
713        let min_val = tensor_data.iter().fold(f32::INFINITY, |a, &b| a.min(b));
714        let max_val = tensor_data.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b));
715        let range = max_val - min_val;
716
717        // Compute variance
718        let mean = tensor_data.iter().sum::<f32>() / tensor_data.len() as f32;
719        let variance =
720            tensor_data.iter().map(|&x| (x - mean).powi(2)).sum::<f32>() / tensor_data.len() as f32;
721
722        // Decision logic
723        if range < 1.0 && variance < 0.01 {
724            // Small range and low variance - INT8 is sufficient
725            Ok(QuantizationScheme::Int8)
726        } else {
727            // Large range or high variance - use FP16
728            Ok(QuantizationScheme::FP16)
729        }
730    }
731}
732
733impl MobileQuantizer for DynamicQuantizer {
734    fn get_scheme(&self) -> QuantizationScheme {
735        QuantizationScheme::Dynamic
736    }
737
738    fn requires_calibration(&self) -> bool {
739        true // INT8 path requires calibration
740    }
741
742    fn calibrate(&self, data: &[Tensor]) -> Result<()> {
743        // Calibrate INT8 quantizer
744        self.int8_quantizer.calibrate(data)
745    }
746
747    fn quantize_tensor(&self, tensor: &Tensor) -> Result<Tensor> {
748        // Generate tensor ID for scheme determination
749        let tensor_id =
750            QuantizationSchemeStorage::generate_tensor_id(tensor, self.layer_context.as_deref());
751
752        // First check external storage for quantization scheme
753        let mut storage = self.scheme_storage.clone();
754        let scheme = storage.determine_scheme(
755            &tensor_id,
756            self.layer_context.as_deref(),
757            self.model_context.as_deref(),
758        );
759
760        // If external storage returns Dynamic, fall back to selection logic
761        let final_scheme = if scheme == QuantizationScheme::Dynamic {
762            self.select_quantization_scheme(tensor)?
763        } else {
764            scheme
765        };
766
767        match final_scheme {
768            QuantizationScheme::Int4 => {
769                // For int4, we need to create a quantizer instance
770                let int4_quantizer = Int4Quantizer::new();
771                int4_quantizer.quantize_tensor(tensor)
772            },
773            QuantizationScheme::Int8 => self.int8_quantizer.quantize_tensor(tensor),
774            QuantizationScheme::FP16 => self.fp16_quantizer.quantize_tensor(tensor),
775            // GGUF schemes fall back to INT8 (will be handled by dedicated GGUF quantizer)
776            QuantizationScheme::GGUF_Q2_K
777            | QuantizationScheme::GGUF_Q3_K
778            | QuantizationScheme::GGUF_Q4_K
779            | QuantizationScheme::GGUF_Q5_0
780            | QuantizationScheme::GGUF_Q6_K => {
781                // Note: GGUF quantization should use MobileGGUFQuantizer directly
782                // For now, fall back to INT8
783                self.int8_quantizer.quantize_tensor(tensor)
784            },
785            QuantizationScheme::Dynamic => {
786                // This shouldn't happen after our check above, but handle gracefully
787                let selected_scheme = self.select_quantization_scheme(tensor)?;
788                match selected_scheme {
789                    QuantizationScheme::Int4 => {
790                        let int4_quantizer = Int4Quantizer::new();
791                        int4_quantizer.quantize_tensor(tensor)
792                    },
793                    QuantizationScheme::Int8 => self.int8_quantizer.quantize_tensor(tensor),
794                    QuantizationScheme::FP16 => self.fp16_quantizer.quantize_tensor(tensor),
795                    // GGUF schemes fall back to INT8
796                    QuantizationScheme::GGUF_Q2_K
797                    | QuantizationScheme::GGUF_Q3_K
798                    | QuantizationScheme::GGUF_Q4_K
799                    | QuantizationScheme::GGUF_Q5_0
800                    | QuantizationScheme::GGUF_Q6_K => self.int8_quantizer.quantize_tensor(tensor),
801                    QuantizationScheme::Dynamic => {
802                        // If still Dynamic, default to Int8 as fallback
803                        self.int8_quantizer.quantize_tensor(tensor)
804                    },
805                }
806            },
807        }
808    }
809
810    fn dequantize_tensor(&self, tensor: &Tensor) -> Result<Tensor> {
811        // Generate tensor ID for scheme determination
812        let tensor_id =
813            QuantizationSchemeStorage::generate_tensor_id(tensor, self.layer_context.as_deref());
814
815        // Determine scheme from external storage
816        let mut storage = self.scheme_storage.clone();
817        let scheme = storage.determine_scheme(
818            &tensor_id,
819            self.layer_context.as_deref(),
820            self.model_context.as_deref(),
821        );
822
823        match scheme {
824            QuantizationScheme::Int8 => self.int8_quantizer.dequantize_tensor(tensor),
825            QuantizationScheme::FP16 => self.fp16_quantizer.dequantize_tensor(tensor),
826            QuantizationScheme::Int4 => {
827                // For int4, we need to create a quantizer instance
828                let int4_quantizer = Int4Quantizer::new();
829                int4_quantizer.dequantize_tensor(tensor)
830            },
831            // GGUF schemes fall back to INT8 dequantization
832            QuantizationScheme::GGUF_Q2_K
833            | QuantizationScheme::GGUF_Q3_K
834            | QuantizationScheme::GGUF_Q4_K
835            | QuantizationScheme::GGUF_Q5_0
836            | QuantizationScheme::GGUF_Q6_K => {
837                // Note: GGUF dequantization should use MobileGGUFQuantizer directly
838                // For now, fall back to INT8
839                self.int8_quantizer.dequantize_tensor(tensor)
840            },
841            QuantizationScheme::Dynamic => {
842                // For dynamic schemes, fall back to the selection logic
843                let selected_scheme = self.select_quantization_scheme(tensor)?;
844                match selected_scheme {
845                    QuantizationScheme::Int8 => self.int8_quantizer.dequantize_tensor(tensor),
846                    QuantizationScheme::FP16 => self.fp16_quantizer.dequantize_tensor(tensor),
847                    _ => self.int8_quantizer.dequantize_tensor(tensor), // Default fallback
848                }
849            },
850        }
851    }
852}
853
854/// Quantization utilities
855pub struct QuantizationUtils;
856
857impl QuantizationUtils {
858    /// Compute quantization error
859    pub fn compute_error(original: &Tensor, quantized: &Tensor) -> Result<f32> {
860        let orig_data = original.data()?;
861        let quant_data = quantized.data()?;
862
863        if orig_data.len() != quant_data.len() {
864            return Err(tensor_op_error(
865                "compute_error",
866                "Tensors must have same size for error computation",
867            ));
868        }
869
870        let mse = orig_data
871            .iter()
872            .zip(quant_data.iter())
873            .map(|(&o, &q)| (o - q).powi(2))
874            .sum::<f32>()
875            / orig_data.len() as f32;
876
877        Ok(mse.sqrt())
878    }
879
880    /// Get compression ratio
881    pub fn compression_ratio(scheme: QuantizationScheme) -> f32 {
882        match scheme {
883            QuantizationScheme::Int4 => 8.0,                // 32-bit to 4-bit
884            QuantizationScheme::Int8 => 4.0,                // 32-bit to 8-bit
885            QuantizationScheme::FP16 => 2.0,                // 32-bit to 16-bit
886            QuantizationScheme::Dynamic => 3.0,             // Average
887            QuantizationScheme::GGUF_Q2_K => 32.0 / 2.5625, // 32-bit to 2.5625-bit
888            QuantizationScheme::GGUF_Q3_K => 32.0 / 3.4375, // 32-bit to 3.4375-bit
889            QuantizationScheme::GGUF_Q4_K => 32.0 / 4.5,    // 32-bit to 4.5-bit
890            QuantizationScheme::GGUF_Q5_0 => 32.0 / 5.5,    // 32-bit to 5.5-bit
891            QuantizationScheme::GGUF_Q6_K => 32.0 / 6.5,    // 32-bit to 6.5-bit
892        }
893    }
894
895    /// Estimate memory savings
896    pub fn memory_savings_percent(scheme: QuantizationScheme) -> f32 {
897        let ratio = Self::compression_ratio(scheme);
898        (1.0 - 1.0 / ratio) * 100.0
899    }
900}
901
902#[cfg(test)]
903mod tests {
904    use super::*;
905
906    #[test]
907    fn test_int4_quantization() {
908        let quantizer = Int4Quantizer::new();
909        let tensor = Tensor::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0], &[2, 4])
910            .expect("Failed to create tensor");
911
912        // Calibrate
913        quantizer.calibrate(std::slice::from_ref(&tensor)).expect("Calibration failed");
914
915        // Quantize
916        let quantized = quantizer.quantize_tensor(&tensor).expect("Quantization failed");
917        assert_eq!(quantized.shape(), tensor.shape());
918
919        // Dequantize
920        let dequantized = quantizer.dequantize_tensor(&quantized).expect("Dequantization failed");
921        assert_eq!(dequantized.shape(), tensor.shape());
922
923        // Check error is reasonable
924        let error = QuantizationUtils::compute_error(&tensor, &dequantized)
925            .expect("Error computation failed");
926        assert!(error < 1.0); // Error should be small
927    }
928
929    #[test]
930    fn test_int8_quantization() {
931        let quantizer = Int8Quantizer::new();
932        let tensor = Tensor::from_vec(vec![-10.0, -5.0, 0.0, 5.0, 10.0], &[5])
933            .expect("Failed to create tensor");
934
935        quantizer.calibrate(std::slice::from_ref(&tensor)).expect("Calibration failed");
936
937        let quantized = quantizer.quantize_tensor(&tensor).expect("Quantization failed");
938        let dequantized = quantizer.dequantize_tensor(&quantized).expect("Dequantization failed");
939
940        let error = QuantizationUtils::compute_error(&tensor, &dequantized)
941            .expect("Error computation failed");
942        assert!(error < 0.1); // INT8 should have very low error
943    }
944
945    #[test]
946    fn test_fp16_quantization() {
947        let quantizer = FP16Quantizer::new();
948        let tensor = Tensor::from_vec(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]).expect("Operation failed");
949
950        // FP16 doesn't require calibration
951        assert!(!quantizer.requires_calibration());
952
953        let quantized = quantizer.quantize_tensor(&tensor).expect("Quantization failed");
954        let dequantized = quantizer.dequantize_tensor(&quantized).expect("Dequantization failed");
955
956        // FP16 should have minimal error for normal range values
957        let error = QuantizationUtils::compute_error(&tensor, &dequantized)
958            .expect("Error computation failed");
959        assert!(error < 0.001);
960    }
961
962    /// Regression test for the previous `FP16Quantizer::quantize_tensor`,
963    /// which rounded values through `f16` and then immediately converted
964    /// them back to `f32` for storage -- the returned tensor was always
965    /// `Tensor::F32` (4 bytes/element), identical memory footprint to the
966    /// unquantized input, despite `get_scheme()` reporting
967    /// `QuantizationScheme::FP16`. A real fix must return a genuine
968    /// `Tensor::F16` (2 bytes/element via `half::f16`), and
969    /// `dequantize_tensor` must convert it back to `Tensor::F32` for
970    /// compute.
971    #[test]
972    fn test_fp16_quantize_tensor_stores_real_f16_not_widened_f32() {
973        let quantizer = FP16Quantizer::new();
974        let tensor = Tensor::from_vec(vec![1.5, -2.25, 3.75, 4.0], &[2, 2]).expect("tensor");
975
976        let quantized = quantizer.quantize_tensor(&tensor).expect("quantize failed");
977        assert!(
978            matches!(quantized, Tensor::F16(_)),
979            "quantize_tensor must return a real Tensor::F16, not a widened Tensor::F32"
980        );
981        assert_eq!(quantized.shape(), tensor.shape());
982
983        // Round-tripping back through dequantize must recover values that
984        // are close (fp16 has ~3 decimal digits of precision) to the
985        // originals, and the dequantized tensor must be directly usable as
986        // f32 again (`.data()` must succeed).
987        let dequantized = quantizer.dequantize_tensor(&quantized).expect("dequantize failed");
988        assert!(matches!(dequantized, Tensor::F32(_)));
989        let recovered = dequantized.data().expect("dequantized data");
990        for (original, got) in [1.5, -2.25, 3.75, 4.0].iter().zip(recovered.iter()) {
991            assert!(
992                (original - got).abs() < 0.01,
993                "expected ~{original}, got {got}"
994            );
995        }
996    }
997
998    /// `dequantize_tensor` must not silently pass through non-F16 tensors
999    /// as if they were already-dequantized data; an unexpected dtype should
1000    /// be a structured error, not a fabricated success.
1001    #[test]
1002    fn test_fp16_dequantize_rejects_unexpected_dtype() {
1003        let quantizer = FP16Quantizer::new();
1004        let int_tensor = Tensor::I64(
1005            scirs2_core::ndarray::ArrayD::from_shape_vec(
1006                scirs2_core::ndarray::IxDyn(&[2]),
1007                vec![1i64, 2i64],
1008            )
1009            .expect("array"),
1010        );
1011        assert!(quantizer.dequantize_tensor(&int_tensor).is_err());
1012    }
1013
1014    #[test]
1015    fn test_dynamic_quantization() {
1016        let mut quantizer = DynamicQuantizer::new();
1017
1018        // Small range tensor - should use INT8
1019        let small_range =
1020            Tensor::from_vec(vec![0.1, 0.2, 0.3, 0.4], &[4]).expect("Operation failed");
1021
1022        quantizer
1023            .calibrate(std::slice::from_ref(&small_range))
1024            .expect("Operation failed");
1025        let quantized = quantizer.quantize_tensor(&small_range).expect("Operation failed");
1026
1027        // Test external storage functionality
1028        let tensor_id = QuantizationSchemeStorage::generate_tensor_id(&small_range, None);
1029
1030        // Configure external storage to use FP16 for this tensor
1031        quantizer
1032            .scheme_storage_mut()
1033            .set_tensor_scheme(tensor_id.clone(), QuantizationScheme::FP16);
1034
1035        // Quantize again - should now use FP16 due to external storage
1036        let quantized_fp16 = quantizer.quantize_tensor(&small_range).expect("Operation failed");
1037
1038        // Verify the storage can retrieve the scheme
1039        let stored_scheme = quantizer.scheme_storage_mut().determine_scheme(&tensor_id, None, None);
1040        assert_eq!(stored_scheme, QuantizationScheme::FP16);
1041
1042        // Test default fallback
1043        let unknown_tensor = Tensor::from_vec(vec![1.0, 2.0, 3.0], &[3]).expect("Operation failed");
1044        let unknown_id = QuantizationSchemeStorage::generate_tensor_id(&unknown_tensor, None);
1045        let default_scheme =
1046            quantizer.scheme_storage_mut().determine_scheme(&unknown_id, None, None);
1047        assert_eq!(default_scheme, QuantizationScheme::Int8); // Default scheme
1048    }
1049
1050    #[test]
1051    fn test_compression_ratios() {
1052        assert_eq!(
1053            QuantizationUtils::compression_ratio(QuantizationScheme::Int4),
1054            8.0
1055        );
1056        assert_eq!(
1057            QuantizationUtils::compression_ratio(QuantizationScheme::Int8),
1058            4.0
1059        );
1060        assert_eq!(
1061            QuantizationUtils::compression_ratio(QuantizationScheme::FP16),
1062            2.0
1063        );
1064
1065        assert_eq!(
1066            QuantizationUtils::memory_savings_percent(QuantizationScheme::Int4),
1067            87.5
1068        );
1069        assert_eq!(
1070            QuantizationUtils::memory_savings_percent(QuantizationScheme::Int8),
1071            75.0
1072        );
1073        assert_eq!(
1074            QuantizationUtils::memory_savings_percent(QuantizationScheme::FP16),
1075            50.0
1076        );
1077    }
1078}