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
//! Matrix calibration implementations for quantization
//!
//! This module contains all matrix-specific calibration methods including
//! both standard and per-channel calibration strategies.

use super::super::{QuantizationMethod, QuantizationParams};
use super::utils::*;
use crate::error::{LinalgError, LinalgResult};
use scirs2_core::ndarray::ArrayView2;
use std::fmt::Debug;

// -------------------------------------------------------------------------
// Matrix calibration implementations
// -------------------------------------------------------------------------

/// Simple min-max calibration for matrices
#[allow(dead_code)]
pub(super) fn calibrate_matrix_minmax<F>(
    matrix: &ArrayView2<F>,
    bits: u8,
    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>,
{
    // Find min and max values in the matrix
    let mut min_val = f32::MAX;
    let mut max_val = f32::MIN;

    for &val in matrix.iter() {
        let val_f32 = val.as_();
        if val_f32.is_finite() {
            min_val = min_val.min(val_f32);
            max_val = max_val.max(val_f32);
        }
    }

    // Handle edge cases
    if !min_val.is_finite() || !max_val.is_finite() {
        return Err(LinalgError::ValueError(
            "Matrix contains non-finite values".to_string(),
        ));
    }

    if min_val == max_val {
        min_val -= 1.0;
        max_val += 1.0;
    }

    create_params_from_range(bits, min_val, max_val, symmetric)
}

/// Moving average min-max calibration for matrices
#[allow(dead_code)]
pub(super) fn calibrate_matrix_moving_average<F>(
    matrix: &ArrayView2<F>,
    bits: u8,
    windowsize: usize,
    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>,
{
    // Convert matrix to a flattened vector of finite f32 values
    let mut values: Vec<f32> = matrix
        .iter()
        .filter_map(|&x| {
            let val = x.as_();
            if val.is_finite() {
                Some(val)
            } else {
                None
            }
        })
        .collect();

    if values.is_empty() {
        return Err(LinalgError::ValueError(
            "Matrix contains no finite values".to_string(),
        ));
    }

    // Sort values
    values.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));

    // Calculate moving averages to find stable min/max
    if values.len() <= windowsize {
        // Not enough data for moving average, fall back to min-max
        let min_val = *values.first().expect("Operation failed");
        let max_val = *values.last().expect("Operation failed");
        create_params_from_range(bits, min_val, max_val, symmetric)
    } else {
        // Calculate moving averages
        let min_val = values.iter().take(windowsize).sum::<f32>() / windowsize as f32;
        let max_val = values.iter().rev().take(windowsize).sum::<f32>() / windowsize as f32;

        create_params_from_range(bits, min_val, max_val, symmetric)
    }
}

/// Percentile-based calibration for matrices
#[allow(dead_code)]
pub(super) fn calibrate_matrix_percentile<F>(
    matrix: &ArrayView2<F>,
    bits: u8,
    percentile: 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>,
{
    if !(0.0..=1.0).contains(&percentile) {
        return Err(LinalgError::ValueError(
            "Percentile must be between 0.0 and 1.0".to_string(),
        ));
    }

    // Convert matrix to a flattened vector of finite f32 values
    let mut values: Vec<f32> = matrix
        .iter()
        .filter_map(|&x| {
            let val = x.as_();
            if val.is_finite() {
                Some(val)
            } else {
                None
            }
        })
        .collect();

    if values.is_empty() {
        return Err(LinalgError::ValueError(
            "Matrix contains no finite values".to_string(),
        ));
    }

    // Sort values
    values.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));

    // Compute percentile indexes
    let low_idx = ((1.0 - percentile) * (values.len() as f32)).round() as usize;
    let high_idx = ((percentile) * (values.len() as f32)).round() as usize;

    // Get percentile values
    let min_val = values[low_idx.min(values.len() - 1)];
    let max_val = values[high_idx.min(values.len() - 1)];

    create_params_from_range(bits, min_val, max_val, symmetric)
}

/// Entropy-based calibration for matrices
#[allow(dead_code)]
pub(super) fn calibrate_matrix_entropy<F>(
    matrix: &ArrayView2<F>,
    bits: u8,
    num_bins: usize,
    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>,
{
    // First get min-max range to create histogram
    let (min_val, max_val) = find_min_max(matrix);

    // Create histogram of the data
    let histogram = create_histogram(matrix, min_val, max_val, num_bins);

    // Use KL divergence minimization to find optimal thresholds
    let (opt_min, opt_max) =
        optimize_thresholds_kl_divergence(&histogram, min_val, max_val, bits, symmetric);

    create_params_from_range(bits, opt_min, opt_max, symmetric)
}

/// MSE-based calibration for matrices
#[allow(dead_code)]
pub(super) fn calibrate_matrix_mse<F>(
    matrix: &ArrayView2<F>,
    bits: u8,
    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>,
{
    // Start with min-max calibration
    let mut base_params = calibrate_matrix_minmax(matrix, bits, symmetric)?;

    // Define a range of scale factors to try
    let scales = if symmetric {
        optimize_symmetric_scale(matrix, bits, base_params.scale)
    } else {
        let (scale, zero_point) =
            optimize_affine_params(matrix, bits, base_params.scale, base_params.zero_point);
        base_params.scale = scale;
        base_params.zero_point = zero_point;
        base_params.scale
    };

    // Create QuantizationParams with optimized scale
    let mut opt_params = base_params.clone();
    opt_params.scale = scales;

    Ok(opt_params)
}

// -------------------------------------------------------------------------
// Per-channel matrix calibration implementations
// -------------------------------------------------------------------------

/// Per-channel min-max calibration for matrices
#[allow(dead_code)]
pub(super) fn calibrate_matrix_per_channel_minmax<F>(
    matrix: &ArrayView2<F>,
    bits: u8,
    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>,
{
    let (_rows, cols) = matrix.dim();

    // Global min/max for the entire matrix
    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 });

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

        // Find min/max for this channel
        let mut col_min = f32::MAX;
        let mut col_max = f32::MIN;

        for &val in column.iter() {
            let val_f32 = val.as_();
            if val_f32.is_finite() {
                col_min = col_min.min(val_f32);
                col_max = col_max.max(val_f32);
            }
        }

        // Handle edge cases
        if !col_min.is_finite() || !col_max.is_finite() {
            col_min = 0.0;
            col_max = 1.0;
        }

        if col_min == col_max {
            col_min -= 1.0;
            col_max += 1.0;
        }

        // Calculate scale and zero point for this channel
        let (scale, zero_point) = if symmetric {
            let abs_max = col_max.abs().max(col_min.abs());
            let scale = abs_max / ((1 << (bits - 1)) - 1) as f32;
            (scale, 0)
        } else {
            let scale = (col_max - col_min) / ((1 << bits) - 1) as f32;
            let zero_point = (-col_min / scale).round() as i32;
            (scale, 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)
        },
    })
}

/// Per-channel moving average calibration for matrices
#[allow(dead_code)]
pub(super) fn calibrate_matrix_per_channel_moving_average<F>(
    matrix: &ArrayView2<F>,
    bits: u8,
    windowsize: usize,
    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>,
{
    let (_rows, cols) = matrix.dim();

    // Global min/max for the entire matrix
    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 });

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

        // Convert column to a vector of finite f32 values
        let mut values: Vec<f32> = column
            .iter()
            .filter_map(|&x| {
                let val = x.as_();
                if val.is_finite() {
                    Some(val)
                } else {
                    None
                }
            })
            .collect();

        if values.is_empty() {
            // Handle empty or non-finite column
            channel_scales.push(1.0);
            if !symmetric {
                channel_zero_points.push(0);
            }
            continue;
        }

        // Sort values
        values.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));

        // Calculate moving averages to find stable min/max
        let (col_min, col_max) = if values.len() <= windowsize {
            // Not enough data for moving average, fall back to min-max
            (
                *values.first().expect("Operation failed"),
                *values.last().expect("Operation failed"),
            )
        } else {
            // Calculate moving averages
            let min_val = values.iter().take(windowsize).sum::<f32>() / windowsize as f32;
            let max_val = values.iter().rev().take(windowsize).sum::<f32>() / windowsize as f32;
            (min_val, max_val)
        };

        // Calculate scale and zero point for this channel
        let (scale, zero_point) = if symmetric {
            let abs_max = col_max.abs().max(col_min.abs());
            let scale = abs_max / ((1 << (bits - 1)) - 1) as f32;
            (scale, 0)
        } else {
            let scale = (col_max - col_min) / ((1 << bits) - 1) as f32;
            let zero_point = (-col_min / scale).round() as i32;
            (scale, 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)
        },
    })
}

/// Per-channel percentile calibration for matrices
#[allow(dead_code)]
pub(super) fn calibrate_matrix_per_channel_percentile<F>(
    matrix: &ArrayView2<F>,
    bits: u8,
    percentile: 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>,
{
    if !(0.0..=1.0).contains(&percentile) {
        return Err(LinalgError::ValueError(
            "Percentile must be between 0.0 and 1.0".to_string(),
        ));
    }

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

    // Global min/max for the entire matrix
    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 });

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

        // Convert column to a vector of finite f32 values
        let mut values: Vec<f32> = column
            .iter()
            .filter_map(|&x| {
                let val = x.as_();
                if val.is_finite() {
                    Some(val)
                } else {
                    None
                }
            })
            .collect();

        if values.is_empty() {
            // Handle empty or non-finite column
            channel_scales.push(1.0);
            if !symmetric {
                channel_zero_points.push(0);
            }
            continue;
        }

        // Sort values
        values.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));

        // Compute percentile indexes
        let low_idx = ((1.0 - percentile) * (values.len() as f32)) as usize;
        let high_idx = ((percentile) * (values.len() as f32)) as usize;

        // Get percentile values
        let col_min = values[low_idx.min(values.len() - 1)];
        let col_max = values[high_idx.min(values.len() - 1)];

        // Calculate scale and zero point for this channel
        let (scale, zero_point) = if symmetric {
            let abs_max = col_max.abs().max(col_min.abs());
            let scale = abs_max / ((1 << (bits - 1)) - 1) as f32;
            (scale, 0)
        } else {
            let scale = (col_max - col_min) / ((1 << bits) - 1) as f32;
            let zero_point = (-col_min / scale).round() as i32;
            (scale, 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)
        },
    })
}

/// Per-channel entropy calibration for matrices
#[allow(dead_code)]
pub(super) fn calibrate_matrix_per_channel_entropy<F>(
    matrix: &ArrayView2<F>,
    bits: u8,
    num_bins: usize,
    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>,
{
    let (_rows, cols) = matrix.dim();

    // Global min/max for the entire matrix
    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 });

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

        // Find min/max for this channel
        let (col_min, col_max) = find_min_max_vec(&column);

        // Create histogram of the channel data
        let histogram = create_histogram_vec(&column, col_min, col_max, num_bins);

        // Use KL divergence minimization to find optimal thresholds
        let (opt_min, opt_max) =
            optimize_thresholds_kl_divergence(&histogram, col_min, col_max, bits, symmetric);

        // Calculate scale and zero point for this channel
        let (scale, zero_point) = if symmetric {
            let abs_max = opt_max.abs().max(opt_min.abs());
            let scale = abs_max / ((1 << (bits - 1)) - 1) as f32;
            (scale, 0)
        } else {
            let scale = (opt_max - opt_min) / ((1 << bits) - 1) as f32;
            let zero_point = (-opt_min / scale).round() as i32;
            (scale, 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)
        },
    })
}

/// Per-channel MSE calibration for matrices
#[allow(dead_code)]
pub(super) fn calibrate_matrix_per_channel_mse<F>(
    matrix: &ArrayView2<F>,
    bits: u8,
    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>,
{
    let (_rows, cols) = matrix.dim();

    // Global min/max for the entire matrix
    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 });

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

        // Start with min-max calibration for this channel
        let (col_min, col_max) = find_min_max_vec(&column);

        let base_scale = if symmetric {
            let abs_max = col_max.abs().max(col_min.abs());
            abs_max / ((1 << (bits - 1)) - 1) as f32
        } else {
            (col_max - col_min) / ((1 << bits) - 1) as f32
        };

        let base_zero_point = if symmetric {
            0
        } else {
            (-col_min / base_scale).round() as i32
        };

        // Optimize parameters for this channel
        if symmetric {
            let scale = optimize_symmetric_scale_vec(&column, bits, base_scale);
            channel_scales.push(scale);
        } else {
            let (scale, zero_point) =
                optimize_affine_params_vec(&column, bits, base_scale, base_zero_point);
            channel_scales.push(scale);
            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)
        },
    })
}