scirs2-linalg 0.4.0

Linear algebra module for SciRS2 (scirs2-linalg)
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
// Implementation of Exponential Moving Average (EMA) calibration methods

use super::calibration::{
    create_params_from_range, determine_data_type, find_min_max, find_min_max_vec,
};
use super::{QuantizationMethod, QuantizationParams};
use crate::error::{LinalgError, LinalgResult};
use scirs2_core::ndarray::{Array2, ArrayView1, ArrayView2};
use std::fmt::Debug;

// Utility function to convert f32 to any Float type
#[allow(dead_code)]
fn to_f<F>(val: f32) -> F
where
    F: scirs2_core::numeric::Float + scirs2_core::numeric::FromPrimitive,
{
    F::from_f32(val).expect("Operation failed")
}

// Helper to convert from generic float to f32
#[allow(dead_code)]
fn to_f32<F>(val: F) -> f32
where
    F: scirs2_core::numeric::Float + scirs2_core::numeric::AsPrimitive<f32>,
{
    val.as_()
}

/// Exponential moving average calibration for matrices
///
/// This method uses iterative refinement with EMA to find optimal quantization parameters
/// where each step calibrates parameters, quantizes/dequantizes, and uses the error to
/// update the min/max values.
///
/// # Arguments
///
/// * `matrix` - Input matrix to calibrate
/// * `bits` - Bit width for quantization
/// * `ema_factor` - Smoothing factor (0-1) where higher values give more weight to recent observations
/// * `max_iterations` - Maximum number of iterations for convergence
/// * `convergence_threshold` - Threshold for early stopping
/// * `symmetric` - Whether to use symmetric quantization
///
/// # Returns
///
/// * Calibrated quantization parameters
#[allow(dead_code)]
pub fn calibrate_matrix_ema<F>(
    matrix: &ArrayView2<F>,
    bits: u8,
    ema_factor: f32,
    max_iterations: usize,
    convergence_threshold: f32,
    symmetric: bool,
) -> LinalgResult<QuantizationParams>
where
    F: scirs2_core::numeric::Float
        + Debug
        + scirs2_core::numeric::AsPrimitive<f32>
        + scirs2_core::numeric::FromPrimitive,
    f32: scirs2_core::numeric::AsPrimitive<F>,
{
    // Validate parameters
    if !(0.0..=1.0).contains(&ema_factor) {
        return Err(LinalgError::ValueError(
            "EMA factor must be between 0.0 and 1.0".to_string(),
        ));
    }

    // Start with min-max calibration
    let (min_val_f32, max_val_f32) = find_min_max(matrix);

    // Convert min/max values back to type F
    let mut min_val = to_f::<F>(min_val_f32);
    let mut max_val = to_f::<F>(max_val_f32);

    // Convert matrix to f32 for calculations
    let matrix_f32 = matrix.mapv(|x| x.as_());

    let mut prev_mse = f32::MAX;

    // Iterative refinement
    for _iter in 0..max_iterations {
        // Create parameters based on current min/max
        let min_val_f32 = to_f32(min_val);
        let max_val_f32 = to_f32(max_val);
        let params = create_params_from_range(bits, min_val_f32, max_val_f32, symmetric)?;

        // Simulate quantization and dequantization for error calculation
        let dequantized = simulate_quantization(&matrix_f32, &params, bits);

        // Calculate MSE
        let mse = (&matrix_f32 - &dequantized).mapv(|x| x * x).sum() / matrix_f32.len() as f32;

        // Check convergence
        if (prev_mse - mse).abs() < convergence_threshold {
            // Converged, return current parameters
            return Ok(params);
        }

        prev_mse = mse;

        // Update min/max values using error feedback
        if symmetric {
            // For symmetric quantization, adjust abs_max
            let abs_max = max_val.abs().max(min_val.abs());

            // Calculate error and update abs_max
            let mean_abs_error = (&matrix_f32 - &dequantized)
                .mapv(|x| x.abs())
                .mean()
                .unwrap_or(0.0);
            let scale_adjustment = if mean_abs_error > 0.01 {
                1.0 + mean_abs_error
            } else {
                1.0
            };

            // Apply EMA to abs_max - converting between F and f32 properly
            let abs_max_f32 = to_f32(abs_max);
            let new_abs_max_f32 = abs_max_f32 * scale_adjustment;
            let updated_abs_max_f32 =
                abs_max_f32 * (1.0 - ema_factor) + new_abs_max_f32 * ema_factor;
            let updated_abs_max = to_f::<F>(updated_abs_max_f32);

            // Update min/max
            min_val = -updated_abs_max;
            max_val = updated_abs_max;
        } else {
            // For asymmetric quantization, adjust min and max separately
            // Calculate per-direction errors
            let negative_errors = matrix_f32
                .iter()
                .zip(dequantized.iter())
                .filter_map(|(&orig, &deq)| {
                    if orig < deq {
                        Some((orig - deq).abs())
                    } else {
                        None
                    }
                })
                .fold(0.0, |sum, error| sum + error);

            let positive_errors = matrix_f32
                .iter()
                .zip(dequantized.iter())
                .filter_map(|(&orig, &deq)| {
                    if orig > deq {
                        Some((orig - deq).abs())
                    } else {
                        None
                    }
                })
                .fold(0.0, |sum, error| sum + error);

            // Calculate adjustment factors
            let neg_count = matrix_f32.iter().filter(|&&x| x < 0.0).count() as f32;
            let pos_count = matrix_f32.iter().filter(|&&x| x > 0.0).count() as f32;

            let neg_adjustment = if neg_count > 0.0 {
                1.0 + (negative_errors / neg_count)
            } else {
                1.0
            };
            let pos_adjustment = if pos_count > 0.0 {
                1.0 + (positive_errors / pos_count)
            } else {
                1.0
            };

            // Apply EMA to min and max - converting properly between types
            let min_val_f32 = to_f32(min_val);
            let max_val_f32 = to_f32(max_val);

            let new_min_f32 = min_val_f32 * neg_adjustment;
            let new_max_f32 = max_val_f32 * pos_adjustment;

            let updated_min_f32 = min_val_f32 * (1.0 - ema_factor) + new_min_f32 * ema_factor;
            let updated_max_f32 = max_val_f32 * (1.0 - ema_factor) + new_max_f32 * ema_factor;

            min_val = to_f::<F>(updated_min_f32);
            max_val = to_f::<F>(updated_max_f32);
        }

        // Debug output for last iteration
        if _iter == max_iterations - 1 {
            println!("EMA calibration reached max iterations with MSE: {mse}");
        }
    }

    // Return parameters from the final iteration
    let min_val_f32 = to_f32(min_val);
    let max_val_f32 = to_f32(max_val);
    create_params_from_range(bits, min_val_f32, max_val_f32, symmetric)
}

/// Per-channel exponential moving average calibration for matrices
///
/// Applies EMA calibration to each channel (column) independently
///
/// # Arguments
///
/// * `matrix` - Input matrix to calibrate
/// * `bits` - Bit width for quantization
/// * `ema_factor` - Smoothing factor (0-1) where higher values give more weight to recent observations
/// * `max_iterations` - Maximum number of iterations for convergence
/// * `convergence_threshold` - Threshold for early stopping
/// * `symmetric` - Whether to use symmetric quantization
///
/// # Returns
///
/// * Calibrated quantization parameters with per-channel scales
#[allow(dead_code)]
pub fn calibrate_matrix_per_channel_ema<F>(
    matrix: &ArrayView2<F>,
    bits: u8,
    ema_factor: f32,
    max_iterations: usize,
    convergence_threshold: f32,
    symmetric: bool,
) -> LinalgResult<QuantizationParams>
where
    F: scirs2_core::numeric::Float
        + Debug
        + scirs2_core::numeric::AsPrimitive<f32>
        + scirs2_core::numeric::FromPrimitive,
    f32: scirs2_core::numeric::AsPrimitive<F>,
{
    // Validate parameters
    if !(0.0..=1.0).contains(&ema_factor) {
        return Err(LinalgError::ValueError(
            "EMA factor must be between 0.0 and 1.0".to_string(),
        ));
    }

    let (_rows, cols) = matrix.dim();

    // Global min/max for the entire matrix (for tracking only)
    let (global_min, global_max) = find_min_max(matrix);

    // Per-channel scales and zero points
    let mut channel_scales = Vec::with_capacity(cols);
    let mut channel_zero_points = Vec::with_capacity(if symmetric { 0 } else { cols });

    // Convert matrix to f32 for calculations
    let matrix_f32 = matrix.mapv(|x| x.as_());

    // For each channel (column)
    for col_idx in 0..cols {
        let column_view = matrix.column(col_idx);
        let column_f32_view = matrix_f32.column(col_idx);

        // Find initial min/max for this channel
        let (col_min_f32, col_max_f32) = find_min_max_vec(&column_view);
        let mut col_min = to_f::<F>(col_min_f32);
        let mut col_max = to_f::<F>(col_max_f32);
        let mut prev_mse = f32::MAX;

        // Iterative refinement for this channel
        for _iter in 0..max_iterations {
            // Create parameters based on current min/max
            let (scale, zero_point) = if symmetric {
                let abs_max = col_max.abs().max(col_min.abs());
                let abs_max_f32 = to_f32(abs_max);
                let scale_f32 = abs_max_f32 / ((1 << (bits - 1)) - 1) as f32;
                (scale_f32, 0)
            } else {
                let min_val_f32 = to_f32(col_min);
                let max_val_f32 = to_f32(col_max);
                let scale_f32 = (max_val_f32 - min_val_f32) / ((1 << bits) - 1) as f32;
                let zero_point = (-min_val_f32 / scale_f32).round() as i32;
                (scale_f32, zero_point)
            };

            // Simulate quantization for this column
            let dequantized_col = simulate_quantization_vector_f32(
                &column_f32_view,
                scale,
                zero_point,
                bits,
                symmetric,
            );

            // Calculate MSE for this column
            let mse = column_f32_view
                .iter()
                .zip(dequantized_col.iter())
                .map(|(&orig, &deq)| (orig - deq).powi(2))
                .sum::<f32>()
                / column_f32_view.len() as f32;

            // Check convergence
            if (prev_mse - mse).abs() < convergence_threshold {
                break;
            }

            prev_mse = mse;

            // Update min/max values using error feedback
            if symmetric {
                // For symmetric quantization, adjust abs_max
                let abs_max = col_max.abs().max(col_min.abs());

                // Calculate error and update abs_max
                let mean_abs_error = column_f32_view
                    .iter()
                    .zip(dequantized_col.iter())
                    .map(|(&orig, &deq)| (orig - deq).abs())
                    .sum::<f32>()
                    / column_f32_view.len() as f32;

                let scale_adjustment = if mean_abs_error > 0.01 {
                    1.0 + mean_abs_error
                } else {
                    1.0
                };

                // Apply EMA to abs_max - converting between F and f32 properly
                let abs_max_f32 = to_f32(abs_max);
                let new_abs_max_f32 = abs_max_f32 * scale_adjustment;
                let updated_abs_max_f32 =
                    abs_max_f32 * (1.0 - ema_factor) + new_abs_max_f32 * ema_factor;
                let updated_abs_max = to_f::<F>(updated_abs_max_f32);

                // Update min/max
                col_min = -updated_abs_max;
                col_max = updated_abs_max;
            } else {
                // For asymmetric quantization, adjust min and max separately
                // Similar to the global method but for this column only
                let negative_errors = column_f32_view
                    .iter()
                    .zip(dequantized_col.iter())
                    .filter_map(|(&orig, &deq)| {
                        if orig < deq {
                            Some((orig - deq).abs())
                        } else {
                            None
                        }
                    })
                    .sum::<f32>();

                let positive_errors = column_f32_view
                    .iter()
                    .zip(dequantized_col.iter())
                    .filter_map(|(&orig, &deq)| {
                        if orig > deq {
                            Some((orig - deq).abs())
                        } else {
                            None
                        }
                    })
                    .sum::<f32>();

                // Calculate adjustment factors
                let neg_count = column_f32_view.iter().filter(|&&x| x < 0.0).count() as f32;
                let pos_count = column_f32_view.iter().filter(|&&x| x > 0.0).count() as f32;

                let neg_adjustment = if neg_count > 0.0 {
                    1.0 + (negative_errors / neg_count)
                } else {
                    1.0
                };
                let pos_adjustment = if pos_count > 0.0 {
                    1.0 + (positive_errors / pos_count)
                } else {
                    1.0
                };

                // Apply EMA to min and max - converting properly between types
                let min_val_f32 = to_f32(col_min);
                let max_val_f32 = to_f32(col_max);

                let new_min_f32 = min_val_f32 * neg_adjustment;
                let new_max_f32 = max_val_f32 * pos_adjustment;

                let updated_min_f32 = min_val_f32 * (1.0 - ema_factor) + new_min_f32 * ema_factor;
                let updated_max_f32 = max_val_f32 * (1.0 - ema_factor) + new_max_f32 * ema_factor;

                col_min = to_f::<F>(updated_min_f32);
                col_max = to_f::<F>(updated_max_f32);
            }
        }

        // After convergence, calculate final scale and zero_point
        let (scale, zero_point) = if symmetric {
            let abs_max = col_max.abs().max(col_min.abs());
            let abs_max_f32 = to_f32(abs_max);
            let scale_f32 = abs_max_f32 / ((1 << (bits - 1)) - 1) as f32;
            (scale_f32, 0)
        } else {
            let min_val_f32 = to_f32(col_min);
            let max_val_f32 = to_f32(col_max);
            let scale_f32 = (max_val_f32 - min_val_f32) / ((1 << bits) - 1) as f32;
            let zero_point = (-min_val_f32 / scale_f32).round() as i32;
            (scale_f32, zero_point)
        };

        channel_scales.push(scale);
        if !symmetric {
            channel_zero_points.push(zero_point);
        }
    }

    // Create quantization params
    let q_method = if symmetric {
        QuantizationMethod::PerChannelSymmetric
    } else {
        QuantizationMethod::PerChannelAffine
    };

    Ok(QuantizationParams {
        bits,
        scale: 0.0,    // Not used for per-channel
        zero_point: 0, // Not used for per-channel symmetric
        min_val: global_min,
        max_val: global_max,
        method: q_method,
        data_type: determine_data_type(bits),
        channel_scales: Some(channel_scales),
        channel_zero_points: if symmetric {
            None
        } else {
            Some(channel_zero_points)
        },
    })
}

/// Exponential moving average calibration for vectors
///
/// # Arguments
///
/// * `vector` - Input vector to calibrate
/// * `bits` - Bit width for quantization
/// * `ema_factor` - Smoothing factor (0-1) where higher values give more weight to recent observations
/// * `max_iterations` - Maximum number of iterations for convergence
/// * `convergence_threshold` - Threshold for early stopping
/// * `symmetric` - Whether to use symmetric quantization
///
/// # Returns
///
/// * Calibrated quantization parameters
#[allow(dead_code)]
pub fn calibrate_vector_ema<F>(
    vector: &ArrayView1<F>,
    bits: u8,
    ema_factor: f32,
    max_iterations: usize,
    convergence_threshold: f32,
    symmetric: bool,
) -> LinalgResult<QuantizationParams>
where
    F: scirs2_core::numeric::Float
        + Debug
        + scirs2_core::numeric::AsPrimitive<f32>
        + scirs2_core::numeric::FromPrimitive,
    f32: scirs2_core::numeric::AsPrimitive<F>,
{
    // Validate parameters
    if !(0.0..=1.0).contains(&ema_factor) {
        return Err(LinalgError::ValueError(
            "EMA factor must be between 0.0 and 1.0".to_string(),
        ));
    }

    // Start with min-max calibration
    let (min_val_f32, max_val_f32) = find_min_max_vec(vector);

    // Convert min/max values back to type F
    let mut min_val = to_f::<F>(min_val_f32);
    let mut max_val = to_f::<F>(max_val_f32);

    // Convert vector to f32 for calculations
    let vector_f32 = vector.mapv(|x| x.as_());

    let mut prev_mse = f32::MAX;

    // Iterative refinement
    for _iter in 0..max_iterations {
        // Calculate scale and zero point
        let (scale, zero_point) = if symmetric {
            let abs_max = max_val.abs().max(min_val.abs());
            let abs_max_f32 = to_f32(abs_max);
            let scale_f32 = abs_max_f32 / ((1 << (bits - 1)) - 1) as f32;
            (scale_f32, 0)
        } else {
            let min_val_f32 = to_f32(min_val);
            let max_val_f32 = to_f32(max_val);
            let scale_f32 = (max_val_f32 - min_val_f32) / ((1 << bits) - 1) as f32;
            let zero_point = (-min_val_f32 / scale_f32).round() as i32;
            (scale_f32, zero_point)
        };

        // Simulate quantization
        let dequantized = simulate_quantization_vector_f32(
            &vector_f32.view(),
            scale,
            zero_point,
            bits,
            symmetric,
        );

        // Calculate MSE
        let mse = vector_f32
            .iter()
            .zip(dequantized.iter())
            .map(|(&orig, &deq)| (orig - deq).powi(2))
            .sum::<f32>()
            / vector_f32.len() as f32;

        // Check convergence
        if (prev_mse - mse).abs() < convergence_threshold {
            // Converged, return current parameters
            let min_val_f32 = to_f32(min_val);
            let max_val_f32 = to_f32(max_val);
            return create_params_from_range(bits, min_val_f32, max_val_f32, symmetric);
        }

        prev_mse = mse;

        // Update min/max values using error feedback
        if symmetric {
            // For symmetric quantization, adjust abs_max
            let abs_max = max_val.abs().max(min_val.abs());

            // Calculate error and update abs_max
            let mean_abs_error = vector_f32
                .iter()
                .zip(dequantized.iter())
                .map(|(&orig, &deq)| (orig - deq).abs())
                .sum::<f32>()
                / vector_f32.len() as f32;

            let scale_adjustment = if mean_abs_error > 0.01 {
                1.0 + mean_abs_error
            } else {
                1.0
            };

            // Apply EMA to abs_max - converting between F and f32 properly
            let abs_max_f32 = to_f32(abs_max);
            let new_abs_max_f32 = abs_max_f32 * scale_adjustment;
            let updated_abs_max_f32 =
                abs_max_f32 * (1.0 - ema_factor) + new_abs_max_f32 * ema_factor;
            let updated_abs_max = to_f::<F>(updated_abs_max_f32);

            // Update min/max
            min_val = -updated_abs_max;
            max_val = updated_abs_max;
        } else {
            // For asymmetric quantization, adjust min and max separately
            let negative_errors = vector_f32
                .iter()
                .zip(dequantized.iter())
                .filter_map(|(&orig, &deq)| {
                    if orig < deq {
                        Some((orig - deq).abs())
                    } else {
                        None
                    }
                })
                .sum::<f32>();

            let positive_errors = vector_f32
                .iter()
                .zip(dequantized.iter())
                .filter_map(|(&orig, &deq)| {
                    if orig > deq {
                        Some((orig - deq).abs())
                    } else {
                        None
                    }
                })
                .sum::<f32>();

            // Calculate adjustment factors
            let neg_count = vector_f32.iter().filter(|&&x| x < 0.0).count() as f32;
            let pos_count = vector_f32.iter().filter(|&&x| x > 0.0).count() as f32;

            let neg_adjustment = if neg_count > 0.0 {
                1.0 + (negative_errors / neg_count)
            } else {
                1.0
            };
            let pos_adjustment = if pos_count > 0.0 {
                1.0 + (positive_errors / pos_count)
            } else {
                1.0
            };

            // Apply EMA to min and max - converting properly between types
            let min_val_f32 = to_f32(min_val);
            let max_val_f32 = to_f32(max_val);

            let new_min_f32 = min_val_f32 * neg_adjustment;
            let new_max_f32 = max_val_f32 * pos_adjustment;

            let updated_min_f32 = min_val_f32 * (1.0 - ema_factor) + new_min_f32 * ema_factor;
            let updated_max_f32 = max_val_f32 * (1.0 - ema_factor) + new_max_f32 * ema_factor;

            min_val = to_f::<F>(updated_min_f32);
            max_val = to_f::<F>(updated_max_f32);
        }
    }

    // Return parameters from the final iteration
    let min_val_f32 = to_f32(min_val);
    let max_val_f32 = to_f32(max_val);
    create_params_from_range(bits, min_val_f32, max_val_f32, symmetric)
}

/// Simulate quantization for a vector (f32 version) using given scale and zero point
///
/// This is an overloaded version that takes f32 directly
#[allow(dead_code)]
fn simulate_quantization_vector_f32(
    vector: &ArrayView1<f32>,
    scale: f32,
    zero_point: i32,
    bits: u8,
    symmetric: bool,
) -> Array2<f32> {
    let mut result = Array2::zeros((vector.len(), 1));

    if symmetric {
        // Symmetric quantization
        let clamp_min = -(1 << (bits - 1)) as f32;
        let clamp_max = ((1 << (bits - 1)) - 1) as f32;

        for (i, &val) in vector.iter().enumerate() {
            let quantized = (val / scale).round().clamp(clamp_min, clamp_max);
            result[[i, 0]] = quantized * scale;
        }
    } else {
        // Affine quantization
        let clamp_max = ((1 << bits) - 1) as f32;
        let zero_point = zero_point as f32;

        for (i, &val) in vector.iter().enumerate() {
            let quantized = ((val / scale) + zero_point).round().clamp(0.0, clamp_max);
            result[[i, 0]] = (quantized - zero_point) * scale;
        }
    }

    result
}

/// Simulate quantization for a matrix using given quantization parameters
///
/// # Arguments
///
/// * `matrix` - Input matrix
/// * `params` - Quantization parameters
/// * `bits` - Bit width for quantization
///
/// # Returns
///
/// * Dequantized matrix after simulated quantization
#[allow(dead_code)]
fn simulate_quantization(
    matrix: &Array2<f32>,
    params: &QuantizationParams,
    bits: u8,
) -> Array2<f32> {
    match params.method {
        QuantizationMethod::Symmetric | QuantizationMethod::Int4 => {
            let scale = params.scale;
            let clamp_min = -(1 << (bits - 1)) as f32;
            let clamp_max = ((1 << (bits - 1)) - 1) as f32;

            matrix.mapv(|x| {
                let quantized = (x / scale).round().clamp(clamp_min, clamp_max);
                quantized * scale
            })
        }
        QuantizationMethod::Affine | QuantizationMethod::UInt4 => {
            let scale = params.scale;
            let zero_point = params.zero_point as f32;
            let clamp_max = ((1 << bits) - 1) as f32;

            matrix.mapv(|x| {
                let quantized = ((x / scale) + zero_point).round().clamp(0.0, clamp_max);
                (quantized - zero_point) * scale
            })
        }
        QuantizationMethod::PerChannelSymmetric | QuantizationMethod::PerChannelAffine => {
            // For per-channel quantization, we need to handle each column separately
            let mut result = Array2::zeros(matrix.dim());
            let (_, cols) = matrix.dim();

            if let Some(channel_scales) = &params.channel_scales {
                for col_idx in 0..cols {
                    let col_view = matrix.column(col_idx);
                    let scale = channel_scales[col_idx];

                    if params.method == QuantizationMethod::PerChannelSymmetric {
                        // Symmetric quantization
                        let clamp_min = -(1 << (bits - 1)) as f32;
                        let clamp_max = ((1 << (bits - 1)) - 1) as f32;

                        for (row_idx, &val) in col_view.iter().enumerate() {
                            let quantized = (val / scale).round().clamp(clamp_min, clamp_max);
                            result[[row_idx, col_idx]] = quantized * scale;
                        }
                    } else {
                        // Affine quantization (with zero point)
                        let clamp_max = ((1 << bits) - 1) as f32;
                        let zero_point = params
                            .channel_zero_points
                            .as_ref()
                            .expect("Operation failed")[col_idx]
                            as f32;

                        for (row_idx, &val) in col_view.iter().enumerate() {
                            let quantized =
                                ((val / scale) + zero_point).round().clamp(0.0, clamp_max);
                            result[[row_idx, col_idx]] = (quantized - zero_point) * scale;
                        }
                    }
                }
            }

            result
        }
        _ => {
            // For other methods (like float16, bfloat16, etc.), just return the original matrix
            // since we don't have simple simulation for these formats
            matrix.clone()
        }
    }
}