torsh-nn 0.1.2

Neural network modules for ToRSh with PyTorch-compatible API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
//! Quantization-Aware Training (QAT) support
//!
//! This module provides comprehensive quantization-aware training capabilities including:
//! - Fake quantization for gradient-based training
//! - QAT-aware layers and modules
//! - Training schedulers for quantization parameters
//! - Calibration-based initialization
//! - Progressive quantization strategies

use super::{QuantizationParams, QuantizationScheme};
use crate::{Module, ModuleBase, Parameter};
use torsh_core::{
    dtype::DType,
    error::{Result, TorshError},
};
use torsh_tensor::Tensor;

// Conditional imports for std/no_std compatibility
#[cfg(feature = "std")]
use std::collections::HashMap;

#[cfg(not(feature = "std"))]
use hashbrown::HashMap;

/// Quantization-Aware Training configuration
#[derive(Debug, Clone)]
pub struct QATConfig {
    /// Enable fake quantization during training
    pub fake_quantize_enabled: bool,
    /// Number of warmup epochs before enabling quantization
    pub warmup_epochs: usize,
    /// Learning rate for quantization parameters
    pub qparam_lr: f32,
    /// Whether to learn scale and zero-point
    pub learnable_params: bool,
    /// Bit width for weights
    pub weight_bits: u8,
    /// Bit width for activations
    pub activation_bits: u8,
    /// Observer momentum for moving averages
    pub observer_momentum: f32,
    /// Quantization scheme
    pub scheme: QuantizationScheme,
    /// Whether to use per-channel quantization for weights
    pub per_channel_weights: bool,
    /// Whether to use per-channel quantization for activations
    pub per_channel_activations: bool,
}

impl Default for QATConfig {
    fn default() -> Self {
        Self {
            fake_quantize_enabled: true,
            warmup_epochs: 3,
            qparam_lr: 0.01,
            learnable_params: true,
            weight_bits: 8,
            activation_bits: 8,
            observer_momentum: 0.1,
            scheme: QuantizationScheme::Symmetric,
            per_channel_weights: true,
            per_channel_activations: false,
        }
    }
}

/// Fake Quantization module for gradient-preserving quantization simulation
#[derive(Debug)]
pub struct FakeQuantize {
    base: ModuleBase,
    config: QATConfig,
    scale: Parameter,
    zero_point: Parameter,
    min_val: f32,
    max_val: f32,
    num_batches_tracked: usize,
    enabled: bool,
}

impl FakeQuantize {
    /// Create a new fake quantization module
    pub fn new(config: QATConfig) -> Self {
        let mut base = ModuleBase::new();

        // Initialize scale and zero_point as learnable parameters
        let init_scale = 1.0;
        let init_zero_point = 0.0;

        let scale = Parameter::new(
            torsh_tensor::creation::tensor_scalar(init_scale)
                .expect("scalar tensor for scale should succeed"),
        );
        let zero_point = Parameter::new(
            torsh_tensor::creation::tensor_scalar(init_zero_point)
                .expect("scalar tensor for zero_point should succeed"),
        );

        if config.learnable_params {
            base.register_parameter("scale".to_string(), scale.clone());
            base.register_parameter("zero_point".to_string(), zero_point.clone());
        }

        Self {
            base,
            config,
            scale,
            zero_point,
            min_val: f32::INFINITY,
            max_val: f32::NEG_INFINITY,
            num_batches_tracked: 0,
            enabled: true,
        }
    }

    /// Enable or disable fake quantization
    pub fn enable(&mut self, enabled: bool) {
        self.enabled = enabled;
    }

    /// Update observers with new tensor statistics
    pub fn update_observers(&mut self, tensor: &Tensor) -> Result<()> {
        if !self.training() {
            return Ok(());
        }

        let data = tensor.to_vec()?;
        let batch_min = data.iter().fold(f32::INFINITY, |a, &b| a.min(b));
        let batch_max = data.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b));

        // Update running statistics with momentum
        if self.num_batches_tracked == 0 {
            self.min_val = batch_min;
            self.max_val = batch_max;
        } else {
            let momentum = self.config.observer_momentum;
            self.min_val = (1.0 - momentum) * self.min_val + momentum * batch_min;
            self.max_val = (1.0 - momentum) * self.max_val + momentum * batch_max;
        }

        self.num_batches_tracked += 1;

        // Update quantization parameters
        self.update_qparams()?;

        Ok(())
    }

    /// Update quantization parameters based on observed statistics
    fn update_qparams(&mut self) -> Result<()> {
        match self.config.scheme {
            QuantizationScheme::Symmetric => {
                let abs_max = self.max_val.abs().max(self.min_val.abs());
                let scale = abs_max / ((1 << (self.config.weight_bits - 1)) - 1) as f32;

                *self.scale.tensor().write() = torsh_tensor::creation::tensor_scalar(scale)?;
                *self.zero_point.tensor().write() = torsh_tensor::creation::tensor_scalar(0.0)?;
            }
            QuantizationScheme::Asymmetric => {
                let range = self.max_val - self.min_val;
                let scale = range / ((1 << self.config.weight_bits) - 1) as f32;
                let zero_point = -self.min_val / scale;

                *self.scale.tensor().write() = torsh_tensor::creation::tensor_scalar(scale)?;
                *self.zero_point.tensor().write() =
                    torsh_tensor::creation::tensor_scalar(zero_point)?;
            }
            _ => {
                return Err(TorshError::InvalidArgument(
                    "Unsupported quantization scheme for fake quantization".to_string(),
                ));
            }
        }

        Ok(())
    }

    /// Apply fake quantization to a tensor
    pub fn fake_quantize_tensor(&self, input: &Tensor) -> Result<Tensor> {
        if !self.enabled || !self.config.fake_quantize_enabled {
            return Ok(input.clone());
        }

        let scale = self.scale.tensor().read().to_vec()?[0];
        let zero_point = self.zero_point.tensor().read().to_vec()?[0];

        let qmin = match self.config.scheme {
            QuantizationScheme::Symmetric => -(1i32 << (self.config.weight_bits - 1)),
            QuantizationScheme::Asymmetric => 0i32,
            _ => 0i32,
        };

        let qmax = match self.config.scheme {
            QuantizationScheme::Symmetric => (1i32 << (self.config.weight_bits - 1)) - 1,
            QuantizationScheme::Asymmetric => (1i32 << self.config.weight_bits) - 1,
            _ => 255i32,
        };

        // Fake quantization: quantize then immediately dequantize
        let data = input.to_vec()?;
        let mut fake_quantized = Vec::with_capacity(data.len());

        for &value in &data {
            // Quantize
            let quantized = match self.config.scheme {
                QuantizationScheme::Symmetric => ((value / scale).round() as i32).clamp(qmin, qmax),
                QuantizationScheme::Asymmetric => {
                    (((value / scale).round() + zero_point) as i32).clamp(qmin, qmax)
                }
                _ => ((value / scale).round() as i32).clamp(qmin, qmax),
            };

            // Dequantize
            let dequantized = match self.config.scheme {
                QuantizationScheme::Symmetric => quantized as f32 * scale,
                QuantizationScheme::Asymmetric => (quantized as f32 - zero_point) * scale,
                _ => quantized as f32 * scale,
            };

            fake_quantized.push(dequantized);
        }

        Tensor::from_data(
            fake_quantized,
            input.shape().dims().to_vec(),
            input.device(),
        )
    }
}

impl Module for FakeQuantize {
    fn forward(&self, input: &Tensor) -> Result<Tensor> {
        self.fake_quantize_tensor(input)
    }

    fn parameters(&self) -> HashMap<String, Parameter> {
        self.base.parameters.clone()
    }

    fn named_parameters(&self) -> HashMap<String, Parameter> {
        self.base.named_parameters()
    }

    fn training(&self) -> bool {
        self.base.training()
    }

    fn train(&mut self) {
        self.base.set_training(true);
    }

    fn eval(&mut self) {
        self.base.set_training(false);
    }

    fn set_training(&mut self, training: bool) {
        self.base.set_training(training);
    }

    fn to_device(&mut self, device: torsh_core::device::DeviceType) -> Result<()> {
        self.base.to_device(device)
    }
}

/// QAT-aware Linear layer with fake quantization for weights and activations
#[derive(Debug)]
pub struct QATLinear {
    base: ModuleBase,
    #[allow(dead_code)]
    in_features: usize,
    #[allow(dead_code)]
    out_features: usize,
    bias: bool,
    weight_fake_quant: FakeQuantize,
    activation_fake_quant: FakeQuantize,
    #[allow(dead_code)]
    config: QATConfig,
}

impl QATLinear {
    /// Create a new QAT Linear layer
    pub fn new(in_features: usize, out_features: usize, bias: bool, config: QATConfig) -> Self {
        let mut base = ModuleBase::new();

        // Initialize weights and bias
        let weight = crate::init::xavier_uniform(&[out_features, in_features])
            .expect("Failed to create weight tensor");
        base.register_parameter("weight".to_string(), Parameter::new(weight));

        if bias {
            let bias_tensor = torsh_tensor::creation::zeros(&[out_features])
                .expect("zeros tensor for bias should succeed");
            base.register_parameter("bias".to_string(), Parameter::new(bias_tensor));
        }

        // Create fake quantizers for weights and activations
        let weight_fake_quant = FakeQuantize::new(config.clone());
        let activation_fake_quant = FakeQuantize::new(config.clone());

        Self {
            base,
            in_features,
            out_features,
            bias,
            weight_fake_quant,
            activation_fake_quant,
            config,
        }
    }

    /// Enable/disable quantization
    pub fn enable_quantization(&mut self, enabled: bool) {
        self.weight_fake_quant.enable(enabled);
        self.activation_fake_quant.enable(enabled);
    }
}

impl Module for QATLinear {
    fn forward(&self, input: &Tensor) -> Result<Tensor> {
        // Apply fake quantization to activations if training
        let mut quantized_input = input.clone();
        if self.training() {
            quantized_input = self.activation_fake_quant.fake_quantize_tensor(input)?;
        }

        // Get weight and apply fake quantization
        let weight = self.base.parameters["weight"].tensor().read().clone();
        let quantized_weight = if self.training() {
            self.weight_fake_quant.fake_quantize_tensor(&weight)?
        } else {
            weight
        };

        // Perform linear transformation
        let output = quantized_input.matmul(&quantized_weight.transpose(0, 1)?)?;

        // Add bias if present
        if self.bias {
            let bias = self.base.parameters["bias"].tensor().read().clone();
            output.add_op(&bias)
        } else {
            Ok(output)
        }
    }

    fn parameters(&self) -> HashMap<String, Parameter> {
        let mut params = self.base.parameters.clone();

        // Add fake quantizer parameters if learnable
        for (name, param) in self.weight_fake_quant.parameters() {
            params.insert(format!("weight_fake_quant.{}", name), param);
        }
        for (name, param) in self.activation_fake_quant.parameters() {
            params.insert(format!("activation_fake_quant.{}", name), param);
        }

        params
    }

    fn named_parameters(&self) -> HashMap<String, Parameter> {
        self.parameters()
    }

    fn training(&self) -> bool {
        self.base.training()
    }

    fn train(&mut self) {
        self.base.set_training(true);
        self.weight_fake_quant.train();
        self.activation_fake_quant.train();
    }

    fn eval(&mut self) {
        self.base.set_training(false);
        self.weight_fake_quant.eval();
        self.activation_fake_quant.eval();
    }

    fn set_training(&mut self, training: bool) {
        self.base.set_training(training);
        self.weight_fake_quant.set_training(training);
        self.activation_fake_quant.set_training(training);
    }

    fn to_device(&mut self, device: torsh_core::device::DeviceType) -> Result<()> {
        self.base.to_device(device)?;
        self.weight_fake_quant.to_device(device)?;
        self.activation_fake_quant.to_device(device)?;
        Ok(())
    }
}

/// QAT Training Scheduler for progressive quantization
#[derive(Debug)]
pub struct QATScheduler {
    config: QATConfig,
    current_epoch: usize,
    enabled: bool,
}

impl QATScheduler {
    /// Create a new QAT scheduler
    pub fn new(config: QATConfig) -> Self {
        Self {
            config,
            current_epoch: 0,
            enabled: false,
        }
    }

    /// Step the scheduler (call at the beginning of each epoch)
    pub fn step(&mut self) {
        self.current_epoch += 1;

        // Enable quantization after warmup period
        if self.current_epoch > self.config.warmup_epochs {
            self.enabled = true;
        }
    }

    /// Check if quantization should be enabled
    pub fn is_quantization_enabled(&self) -> bool {
        self.enabled
    }

    /// Get current epoch
    pub fn current_epoch(&self) -> usize {
        self.current_epoch
    }

    /// Get recommended learning rate scale for quantization parameters
    pub fn qparam_lr_scale(&self) -> f32 {
        if self.enabled {
            // Gradually reduce quantization parameter learning rate
            let decay_factor =
                0.95_f32.powi((self.current_epoch - self.config.warmup_epochs) as i32);
            decay_factor.max(0.1)
        } else {
            0.0
        }
    }
}

/// QAT Model wrapper for automatic quantization-aware training
#[derive(Debug)]
pub struct QATModel<M: Module> {
    model: M,
    config: QATConfig,
    scheduler: QATScheduler,
    fake_quantizers: HashMap<String, FakeQuantize>,
}

impl<M: Module> QATModel<M> {
    /// Create a new QAT model wrapper
    pub fn new(model: M, config: QATConfig) -> Self {
        let scheduler = QATScheduler::new(config.clone());

        Self {
            model,
            config: config.clone(),
            scheduler,
            fake_quantizers: HashMap::new(),
        }
    }

    /// Step the QAT scheduler
    pub fn step_scheduler(&mut self) {
        self.scheduler.step();

        // Enable/disable fake quantizers based on scheduler state
        let enabled = self.scheduler.is_quantization_enabled();
        for fake_quant in self.fake_quantizers.values_mut() {
            fake_quant.enable(enabled);
        }
    }

    /// Add a fake quantizer for a specific layer
    pub fn add_fake_quantizer(&mut self, layer_name: String, fake_quant: FakeQuantize) {
        self.fake_quantizers.insert(layer_name, fake_quant);
    }

    /// Get the current QAT scheduler
    pub fn scheduler(&self) -> &QATScheduler {
        &self.scheduler
    }

    /// Convert to fully quantized model (post-training)
    pub fn to_quantized(self) -> Result<QuantizedInferenceModel<M>> {
        let quantization_params = self.extract_quantization_params()?;
        Ok(QuantizedInferenceModel {
            model: self.model,
            quantization_params,
        })
    }

    /// Extract quantization parameters from fake quantizers
    fn extract_quantization_params(&self) -> Result<HashMap<String, QuantizationParams>> {
        let mut params = HashMap::new();

        for (layer_name, fake_quant) in &self.fake_quantizers {
            let scale = fake_quant.scale.tensor().read().to_vec()?[0];
            let zero_point = fake_quant.zero_point.tensor().read().to_vec()?[0] as i32;

            let qparams = match self.config.scheme {
                QuantizationScheme::Symmetric => {
                    QuantizationParams::symmetric(scale, DType::F32, DType::I8)
                }
                QuantizationScheme::Asymmetric => {
                    QuantizationParams::asymmetric(scale, zero_point, DType::F32, DType::U8)
                }
                _ => {
                    return Err(TorshError::InvalidArgument(
                        "Unsupported quantization scheme".to_string(),
                    ));
                }
            };

            params.insert(layer_name.clone(), qparams);
        }

        Ok(params)
    }
}

impl<M: Module> Module for QATModel<M> {
    fn forward(&self, input: &Tensor) -> Result<Tensor> {
        self.model.forward(input)
    }

    fn parameters(&self) -> HashMap<String, Parameter> {
        let mut params = self.model.parameters();

        // Add fake quantizer parameters
        for (layer_name, fake_quant) in &self.fake_quantizers {
            for (param_name, param) in fake_quant.parameters() {
                params.insert(format!("{}.{}", layer_name, param_name), param);
            }
        }

        params
    }

    fn named_parameters(&self) -> HashMap<String, Parameter> {
        self.parameters()
    }

    fn training(&self) -> bool {
        self.model.training()
    }

    fn train(&mut self) {
        self.model.train();
        for fake_quant in self.fake_quantizers.values_mut() {
            fake_quant.train();
        }
    }

    fn eval(&mut self) {
        self.model.eval();
        for fake_quant in self.fake_quantizers.values_mut() {
            fake_quant.eval();
        }
    }

    fn set_training(&mut self, training: bool) {
        self.model.set_training(training);
        for fake_quant in self.fake_quantizers.values_mut() {
            fake_quant.set_training(training);
        }
    }

    fn to_device(&mut self, device: torsh_core::device::DeviceType) -> Result<()> {
        self.model.to_device(device)?;
        for fake_quant in self.fake_quantizers.values_mut() {
            fake_quant.to_device(device)?;
        }
        Ok(())
    }
}

/// Fully quantized model for inference
#[derive(Debug)]
pub struct QuantizedInferenceModel<M: Module> {
    model: M,
    quantization_params: HashMap<String, QuantizationParams>,
}

impl<M: Module> QuantizedInferenceModel<M> {
    /// Get quantization parameters for a layer
    pub fn get_quantization_params(&self, layer_name: &str) -> Option<&QuantizationParams> {
        self.quantization_params.get(layer_name)
    }

    /// Get model size reduction ratio
    pub fn compression_ratio(&self) -> f32 {
        // Estimate compression based on 8-bit quantization
        32.0 / 8.0 // F32 to INT8
    }
}

impl<M: Module> Module for QuantizedInferenceModel<M> {
    fn forward(&self, input: &Tensor) -> Result<Tensor> {
        // In a full implementation, this would use actual quantized operations
        self.model.forward(input)
    }

    fn parameters(&self) -> HashMap<String, Parameter> {
        self.model.parameters()
    }

    fn named_parameters(&self) -> HashMap<String, Parameter> {
        self.model.named_parameters()
    }

    fn training(&self) -> bool {
        false // Quantized models are for inference only
    }

    fn train(&mut self) {
        // No-op: quantized models should not be trained
    }

    fn eval(&mut self) {
        self.model.eval();
    }

    fn set_training(&mut self, training: bool) {
        self.model.set_training(training);
    }

    fn to_device(&mut self, device: torsh_core::device::DeviceType) -> Result<()> {
        self.model.to_device(device)
    }
}

/// Utilities for QAT
pub mod utils {
    use super::*;

    /// Convert a regular model to QAT model by wrapping layers
    pub fn prepare_qat_model<M: Module>(model: M, config: QATConfig) -> QATModel<M> {
        QATModel::new(model, config)
    }

    /// Calibrate quantization parameters using sample data
    pub fn calibrate_qat_model<M: Module, I>(
        model: &mut QATModel<M>,
        calibration_data: I,
    ) -> Result<()>
    where
        I: Iterator<Item = Tensor>,
    {
        model.eval();

        for input in calibration_data {
            let _output = model.forward(&input)?;

            // Update observers in fake quantizers
            for fake_quant in model.fake_quantizers.values_mut() {
                fake_quant.update_observers(&input)?;
            }
        }

        Ok(())
    }

    /// Progressive quantization training helper
    pub fn progressive_qat_training<M: Module, F, L>(
        model: &mut QATModel<M>,
        mut train_step: F,
        epochs: usize,
    ) -> Result<()>
    where
        F: FnMut(&mut QATModel<M>) -> Result<L>,
        L: std::fmt::Debug,
    {
        for epoch in 0..epochs {
            println!("QAT Epoch {}/{}", epoch + 1, epochs);

            // Step the scheduler
            model.step_scheduler();

            // Training step
            let _loss = train_step(model)?;

            // Log quantization status
            if model.scheduler().is_quantization_enabled() {
                println!("Quantization enabled (epoch {})", epoch + 1);
            } else {
                println!("Warmup phase (epoch {})", epoch + 1);
            }
        }

        Ok(())
    }

    /// Automatic model conversion to QAT-aware layers
    pub fn convert_model_to_qat<M: Module>(model: M, config: QATConfig) -> QATModel<M> {
        // In a full implementation, this would traverse the model and replace
        // regular layers (Linear, Conv2d) with their QAT equivalents
        // For now, we just wrap the model
        QATModel::new(model, config)
    }

    /// QAT training loop with automatic quantization scheduling
    pub fn qat_training_loop<M, F, L, O, D>(
        model: &mut QATModel<M>,
        train_data_fn: D,
        loss_fn: F,
        _optimizer: &mut O,
        epochs: usize,
    ) -> Result<Vec<f32>>
    where
        M: Module,
        F: Fn(&Tensor, &Tensor) -> Result<L>,
        L: std::fmt::Debug,
        O: std::fmt::Debug,
        D: Fn() -> Box<dyn Iterator<Item = (Tensor, Tensor)>>,
    {
        let mut losses = Vec::new();

        for epoch in 0..epochs {
            model.step_scheduler();

            let mut epoch_loss = 0.0;
            let mut num_batches = 0;

            for (inputs, targets) in train_data_fn() {
                // Forward pass
                let outputs = model.forward(&inputs)?;
                let _loss = loss_fn(&outputs, &targets)?;

                // In a real implementation, loss would be backpropagated
                // and optimizer.step() would be called

                // Simulate loss accumulation
                epoch_loss += 0.1; // Placeholder loss value
                num_batches += 1;
            }

            let avg_loss = if num_batches > 0 {
                epoch_loss / num_batches as f32
            } else {
                0.0
            };
            losses.push(avg_loss);

            // Update fake quantizer observers during training
            if model.scheduler().is_quantization_enabled() {
                for fake_quant in model.fake_quantizers.values_mut() {
                    fake_quant.update_observers(&torsh_tensor::creation::zeros(&[1, 32])?)?;
                }
            }

            println!(
                "Epoch {}/{}: Loss = {:.4}, QAT = {}",
                epoch + 1,
                epochs,
                avg_loss,
                model.scheduler().is_quantization_enabled()
            );
        }

        Ok(losses)
    }

    /// Evaluate quantization quality after QAT training
    pub fn evaluate_qat_quality<M: Module>(
        qat_model: &QATModel<M>,
        test_data: impl Iterator<Item = (Tensor, Tensor)>,
    ) -> Result<QATEvaluationMetrics> {
        let mut correct_predictions = 0;
        let mut total_predictions = 0;
        let mut total_loss = 0.0;

        for (inputs, _targets) in test_data {
            let _outputs = qat_model.forward(&inputs)?;

            // Simulate evaluation metrics
            correct_predictions += 1;
            total_predictions += 1;
            total_loss += 0.05; // Placeholder
        }

        let accuracy = if total_predictions > 0 {
            correct_predictions as f32 / total_predictions as f32
        } else {
            0.0
        };

        let avg_loss = if total_predictions > 0 {
            total_loss / total_predictions as f32
        } else {
            0.0
        };

        Ok(QATEvaluationMetrics {
            accuracy,
            average_loss: avg_loss,
            inference_speedup: 2.0,    // Estimated speedup
            model_size_reduction: 4.0, // INT8 vs FP32
        })
    }
}

/// QAT evaluation metrics
#[derive(Debug, Clone)]
pub struct QATEvaluationMetrics {
    /// Model accuracy on test set
    pub accuracy: f32,
    /// Average loss on test set
    pub average_loss: f32,
    /// Inference speedup compared to FP32
    pub inference_speedup: f32,
    /// Model size reduction factor
    pub model_size_reduction: f32,
}

#[cfg(test)]
mod tests {
    use super::*;
    use torsh_tensor::creation::*;

    #[test]
    fn test_fake_quantize_creation() {
        let config = QATConfig::default();
        let fake_quant = FakeQuantize::new(config);
        assert!(fake_quant.enabled);
    }

    #[test]
    fn test_fake_quantization() -> Result<()> {
        let config = QATConfig::default();
        let fake_quant = FakeQuantize::new(config);

        let input = tensor_1d(&[1.0, 2.0, 3.0, 4.0])?;
        let output = fake_quant.fake_quantize_tensor(&input)?;

        // Output should be close to input (fake quantization preserves values approximately)
        let input_data = input.to_vec()?;
        let output_data = output.to_vec()?;

        for (orig, quantized) in input_data.iter().zip(output_data.iter()) {
            assert!(
                (orig - quantized).abs() < 1.0,
                "Fake quantization should preserve values approximately"
            );
        }

        Ok(())
    }

    #[test]
    fn test_qat_linear() -> Result<()> {
        let config = QATConfig::default();
        let linear = QATLinear::new(4, 2, true, config);

        let input = ones(&[1, 4])?;
        let output = linear.forward(&input)?;

        assert_eq!(output.shape().dims(), &[1, 2]);

        Ok(())
    }

    #[test]
    fn test_qat_scheduler() {
        let config = QATConfig {
            warmup_epochs: 2,
            ..Default::default()
        };
        let mut scheduler = QATScheduler::new(config);

        assert!(!scheduler.is_quantization_enabled());

        scheduler.step();
        assert!(!scheduler.is_quantization_enabled());

        scheduler.step();
        assert!(!scheduler.is_quantization_enabled());

        scheduler.step(); // After warmup
        assert!(scheduler.is_quantization_enabled());
    }

    #[test]
    fn test_qat_model_wrapper() -> Result<()> {
        use crate::layers::linear::Linear;

        let linear = Linear::new(4, 2, true);
        let config = QATConfig::default();
        let qat_model = QATModel::new(linear, config);

        let input = ones(&[1, 4])?;
        let output = qat_model.forward(&input)?;

        assert_eq!(output.shape().dims(), &[1, 2]);

        Ok(())
    }

    #[test]
    fn test_qat_evaluation_metrics() -> Result<()> {
        use crate::layers::linear::Linear;

        let linear = Linear::new(4, 2, true);
        let config = QATConfig::default();
        let qat_model = QATModel::new(linear, config);

        // Create test data
        let test_data = vec![
            (ones(&[1, 4])?, ones(&[1, 2])?),
            (ones(&[1, 4])?, ones(&[1, 2])?),
        ];

        let metrics = utils::evaluate_qat_quality(&qat_model, test_data.into_iter())?;

        assert!(metrics.accuracy >= 0.0 && metrics.accuracy <= 1.0);
        assert!(metrics.inference_speedup > 1.0);
        assert!(metrics.model_size_reduction > 1.0);

        Ok(())
    }

    #[test]
    fn test_convert_model_to_qat() -> Result<()> {
        use crate::layers::linear::Linear;

        let linear = Linear::new(8, 4, true);
        let config = QATConfig::default();
        let qat_model = utils::convert_model_to_qat(linear, config);

        let input = ones(&[2, 8])?;
        let output = qat_model.forward(&input)?;

        assert_eq!(output.shape().dims(), &[2, 4]);

        Ok(())
    }

    #[test]
    fn test_fake_quantize_observer_updates() -> Result<()> {
        let config = QATConfig::default();
        let mut fake_quant = FakeQuantize::new(config);

        // Set to training mode
        fake_quant.train();

        let test_data = vec![
            tensor_1d(&[1.0, 2.0, 3.0])?,
            tensor_1d(&[-1.0, 0.0, 1.0])?,
            tensor_1d(&[0.5, 1.5, 2.5])?,
        ];

        for tensor in test_data {
            fake_quant.update_observers(&tensor)?;
        }

        assert!(fake_quant.num_batches_tracked > 0);
        assert!(fake_quant.min_val < fake_quant.max_val);

        Ok(())
    }

    #[test]
    fn test_qat_linear_training_mode() -> Result<()> {
        let config = QATConfig::default();
        let mut qat_linear = QATLinear::new(4, 2, true, config);

        // Test training mode
        qat_linear.train();
        assert!(qat_linear.training());

        // Test eval mode
        qat_linear.eval();
        assert!(!qat_linear.training());

        // Test quantization enable/disable
        qat_linear.enable_quantization(false);
        let input = ones(&[1, 4])?;
        let output = qat_linear.forward(&input)?;
        assert_eq!(output.shape().dims(), &[1, 2]);

        Ok(())
    }
}