oxidelm 0.2.0

Bare-metal pure-Rust Transformer engine with reverse-mode autograd, BPE tokenization, and wgpu acceleration
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
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
//! Weight-only quantization schemes for Linear packs.
//!
//! Round-to-nearest (RTN) packing with configurable format, granularity,
//! symmetry, and scale selection. Used by inference packing and the
//! `oxidelm --quantize` product surface.

use serde::{Deserialize, Serialize};

/// Packed weight element format.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum WeightQuantization {
    Int8,
    Int4,
    Int3,
    Int2,
    Nf4,
    #[serde(rename = "fp8_e4m3")]
    Fp8E4M3,
    #[serde(rename = "fp8_e5m2")]
    Fp8E5M2,
}

impl WeightQuantization {
    pub fn bits(self) -> u32 {
        match self {
            Self::Int8 | Self::Fp8E4M3 | Self::Fp8E5M2 => 8,
            Self::Int4 | Self::Nf4 => 4,
            Self::Int3 => 3,
            Self::Int2 => 2,
        }
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Self::Int8 => "int8",
            Self::Int4 => "int4",
            Self::Int3 => "int3",
            Self::Int2 => "int2",
            Self::Nf4 => "nf4",
            Self::Fp8E4M3 => "fp8_e4m3",
            Self::Fp8E5M2 => "fp8_e5m2",
        }
    }

    pub fn parse(value: &str) -> Result<Self, String> {
        match value.trim().to_ascii_lowercase().as_str() {
            "int8" | "i8" | "8" => Ok(Self::Int8),
            "int4" | "i4" | "4" => Ok(Self::Int4),
            "int3" | "i3" | "3" => Ok(Self::Int3),
            "int2" | "i2" | "2" => Ok(Self::Int2),
            "nf4" => Ok(Self::Nf4),
            "fp8" | "fp8_e4m3" | "e4m3" => Ok(Self::Fp8E4M3),
            "fp8_e5m2" | "e5m2" => Ok(Self::Fp8E5M2),
            other => Err(format!(
                "unknown weight quantization '{other}'; expected int8|int4|int3|int2|nf4|fp8_e4m3|fp8_e5m2"
            )),
        }
    }

    /// Values packed per `u32` word.
    pub fn values_per_word(self) -> usize {
        match self {
            Self::Int3 => 10, // 10 × 3 bits = 30; 2 bits unused
            other => 32 / other.bits() as usize,
        }
    }

    /// Signed integer q-domain maximum (symmetric int formats).
    pub fn int_maximum(self) -> Option<f32> {
        match self {
            Self::Int8 => Some(127.0),
            Self::Int4 => Some(7.0),
            Self::Int3 => Some(3.0),
            Self::Int2 => Some(1.0),
            _ => None,
        }
    }

    pub fn is_integer(self) -> bool {
        matches!(self, Self::Int8 | Self::Int4 | Self::Int3 | Self::Int2)
    }

    pub fn supports_asymmetric(self) -> bool {
        self.is_integer()
    }

    /// WGSL / GPU scheme discriminator.
    pub fn gpu_scheme_id(self, symmetric: bool) -> u32 {
        match self {
            Self::Int8 | Self::Int4 | Self::Int3 | Self::Int2 => {
                if symmetric {
                    0
                } else {
                    1
                }
            }
            Self::Nf4 => 2,
            Self::Fp8E4M3 => 3,
            Self::Fp8E5M2 => 4,
        }
    }
}

/// Scale / zero-point granularity along the input feature axis.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum QuantGranularity {
    /// One scale for the entire weight matrix.
    PerTensor,
    /// One scale per output channel (default RTN).
    PerChannel,
    /// Groups of `size` along `in_features` (typically 32 / 64 / 128).
    PerGroup {
        size: usize,
    },
}

impl QuantGranularity {
    pub fn parse(value: &str) -> Result<Self, String> {
        let value = value.trim().to_ascii_lowercase();
        match value.as_str() {
            "tensor" | "per-tensor" | "per_tensor" => Ok(Self::PerTensor),
            "channel" | "per-channel" | "per_channel" | "0" => Ok(Self::PerChannel),
            other => {
                if let Some(rest) = other
                    .strip_prefix("group:")
                    .or_else(|| other.strip_prefix("per-group:"))
                    .or_else(|| other.strip_prefix("per_group:"))
                {
                    let size: usize = rest
                        .parse()
                        .map_err(|_| format!("invalid group size '{rest}'"))?;
                    return Ok(Self::PerGroup { size });
                }
                if let Ok(size) = other.parse::<usize>() {
                    if size == 0 {
                        return Ok(Self::PerChannel);
                    }
                    return Ok(Self::PerGroup { size });
                }
                Err(format!(
                    "unknown granularity '{other}'; expected tensor|channel|32|64|128"
                ))
            }
        }
    }

    pub fn as_str(self) -> String {
        match self {
            Self::PerTensor => "tensor".into(),
            Self::PerChannel => "channel".into(),
            Self::PerGroup { size } => format!("group:{size}"),
        }
    }

    pub fn group_size(self) -> Option<usize> {
        match self {
            Self::PerGroup { size } => Some(size),
            _ => None,
        }
    }
}

/// How scales (and asymmetric ranges) are chosen.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ScaleMethod {
    AbsMax,
    MinMax,
    Percentile,
    Mse,
}

impl ScaleMethod {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::AbsMax => "absmax",
            Self::MinMax => "minmax",
            Self::Percentile => "percentile",
            Self::Mse => "mse",
        }
    }

    pub fn parse(value: &str) -> Result<Self, String> {
        match value.trim().to_ascii_lowercase().as_str() {
            "absmax" | "abs-max" | "max" => Ok(Self::AbsMax),
            "minmax" | "min-max" | "range" => Ok(Self::MinMax),
            "percentile" | "pct" => Ok(Self::Percentile),
            "mse" | "grid" => Ok(Self::Mse),
            other => Err(format!(
                "unknown scale method '{other}'; expected absmax|minmax|percentile|mse"
            )),
        }
    }
}

/// Complete weight-only RTN scheme.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct QuantScheme {
    pub format: WeightQuantization,
    pub granularity: QuantGranularity,
    pub symmetric: bool,
    pub scale_method: ScaleMethod,
    /// Used when `scale_method == Percentile` (e.g. 99.99).
    pub percentile: f32,
}

impl Default for QuantScheme {
    fn default() -> Self {
        Self {
            format: WeightQuantization::Int8,
            granularity: QuantGranularity::PerChannel,
            symmetric: true,
            scale_method: ScaleMethod::AbsMax,
            percentile: 99.99,
        }
    }
}

impl QuantScheme {
    pub fn default_for(format: WeightQuantization) -> Self {
        Self {
            format,
            ..Self::default()
        }
    }

    pub fn validate(self) -> Result<(), String> {
        if !self.symmetric && !self.format.supports_asymmetric() {
            return Err(format!(
                "{} does not support asymmetric quantization",
                self.format.as_str()
            ));
        }
        if let QuantGranularity::PerGroup { size } = self.granularity {
            if ![32, 64, 128].contains(&size) {
                return Err(format!(
                    "unsupported group size {size}; use 32, 64, or 128"
                ));
            }
        }
        if !(0.0..=100.0).contains(&self.percentile) || !self.percentile.is_finite() {
            return Err("percentile must be in [0, 100]".into());
        }
        Ok(())
    }

    pub fn scale_count(self, in_features: usize, out_features: usize) -> usize {
        match self.granularity {
            QuantGranularity::PerTensor => 1,
            QuantGranularity::PerChannel => out_features,
            QuantGranularity::PerGroup { size } => {
                out_features * in_features.div_ceil(size.max(1))
            }
        }
    }

    pub fn groups_per_channel(self, in_features: usize) -> usize {
        match self.granularity {
            QuantGranularity::PerTensor | QuantGranularity::PerChannel => 1,
            QuantGranularity::PerGroup { size } => in_features.div_ceil(size.max(1)),
        }
    }
}

/// bitsandbytes-compatible NormalFloat4 codebook.
pub const NF4_CODEBOOK: [f32; 16] = [
    -1.0,
    -0.696_192_8,
    -0.525_073_05,
    -0.394_917_5,
    -0.284_441_38,
    -0.184_773_43,
    -0.091_050_036,
    0.0,
    0.079_580_3,
    0.160_930_2,
    0.246_112_3,
    0.337_915_24,
    0.440_709_83,
    0.562_617,
    0.722_956_84,
    1.0,
];

#[derive(Clone, Debug)]
pub struct PackedLinearWeight {
    pub scheme: QuantScheme,
    pub packed_values: Vec<u32>,
    pub scales: Vec<f32>,
    pub zero_points: Option<Vec<f32>>,
    pub in_features: usize,
    pub out_features: usize,
}

impl PackedLinearWeight {
    pub fn storage_bytes(&self) -> usize {
        let zp = self
            .zero_points
            .as_ref()
            .map(|values| values.len() * std::mem::size_of::<f32>())
            .unwrap_or(0);
        self.packed_values.len() * std::mem::size_of::<u32>()
            + self.scales.len() * std::mem::size_of::<f32>()
            + zp
    }

    pub fn scale_index(&self, input: usize, output: usize) -> usize {
        match self.scheme.granularity {
            QuantGranularity::PerTensor => 0,
            QuantGranularity::PerChannel => output,
            QuantGranularity::PerGroup { size } => {
                let groups = self.in_features.div_ceil(size.max(1));
                output * groups + input / size.max(1)
            }
        }
    }

    pub fn dequantized_value(&self, input: usize, output: usize) -> f32 {
        let q = decode_raw(self, input, output);
        let scale_index = self.scale_index(input, output);
        let scale = self.scales[scale_index];
        match self.scheme.format {
            WeightQuantization::Nf4 => NF4_CODEBOOK[q as usize] * scale,
            WeightQuantization::Fp8E4M3 => fp8_e4m3_to_f32(q as u8) * scale,
            WeightQuantization::Fp8E5M2 => fp8_e5m2_to_f32(q as u8) * scale,
            _ => {
                let zp = self
                    .zero_points
                    .as_ref()
                    .map(|values| values[scale_index])
                    .unwrap_or(0.0);
                (q - zp) * scale
            }
        }
    }

    /// Maximum absolute reconstruction error over all elements vs the original
    /// logical weights provided by `logical_value`.
    pub fn max_abs_dequant_error(
        &self,
        mut logical_value: impl FnMut(usize, usize) -> f32,
    ) -> f32 {
        let mut worst = 0.0f32;
        for input in 0..self.in_features {
            for output in 0..self.out_features {
                let error =
                    (logical_value(input, output) - self.dequantized_value(input, output)).abs();
                worst = worst.max(error);
            }
        }
        worst
    }

    /// Tight-ish RTN bound: integer formats should stay within half a quant
    /// step of the local scale. NF4/FP8 use a looser scale-relative bound.
    pub fn dequant_error_bound(&self) -> f32 {
        let max_scale = self
            .scales
            .iter()
            .copied()
            .fold(0.0f32, f32::max)
            .max(1e-12);
        match self.scheme.format {
            WeightQuantization::Int8
            | WeightQuantization::Int4
            | WeightQuantization::Int3
            | WeightQuantization::Int2 => 0.5 * max_scale + 1e-5,
            WeightQuantization::Nf4 => 0.35 * max_scale + 1e-5,
            WeightQuantization::Fp8E4M3 | WeightQuantization::Fp8E5M2 => 0.15 * max_scale + 1e-4,
        }
    }

    pub fn quantized_numeric(&self, input: usize, output: usize) -> f32 {
        let q = decode_raw(self, input, output);
        match self.scheme.format {
            WeightQuantization::Nf4 => NF4_CODEBOOK[q as usize],
            WeightQuantization::Fp8E4M3 => fp8_e4m3_to_f32(q as u8),
            WeightQuantization::Fp8E5M2 => fp8_e5m2_to_f32(q as u8),
            _ => {
                let scale_index = self.scale_index(input, output);
                let zp = self
                    .zero_points
                    .as_ref()
                    .map(|values| values[scale_index])
                    .unwrap_or(0.0);
                q - zp
            }
        }
    }
}

/// Pack FP32 logical weights `[in × out]` with the given scheme.
///
/// `logical_value(input, output)` returns the weight at that position.
pub fn pack_weights(
    in_features: usize,
    out_features: usize,
    scheme: QuantScheme,
    mut logical_value: impl FnMut(usize, usize) -> f32,
) -> Result<PackedLinearWeight, String> {
    scheme.validate()?;
    if in_features == 0 || out_features == 0 {
        return Err("quantized linear dimensions must be non-zero".into());
    }

    let scale_count = scheme.scale_count(in_features, out_features);
    let mut scales = vec![1.0f32; scale_count];
    let mut zero_points = if scheme.symmetric {
        None
    } else {
        Some(vec![0.0f32; scale_count])
    };

    // Collect values per scale group, then choose scales.
    for scale_index in 0..scale_count {
        let values = collect_group_values(
            in_features,
            out_features,
            scheme,
            scale_index,
            &mut logical_value,
        );
        let (scale, zp) = choose_scale_zp(&values, scheme)?;
        scales[scale_index] = scale;
        if let Some(zero_points) = zero_points.as_mut() {
            zero_points[scale_index] = zp;
        }
    }

    let values_per_word = scheme.format.values_per_word();
    let total = in_features * out_features;
    let mut packed_values = vec![0u32; total.div_ceil(values_per_word)];

    for input in 0..in_features {
        for output in 0..out_features {
            let index = input * out_features + output;
            let scale_index = match scheme.granularity {
                QuantGranularity::PerTensor => 0,
                QuantGranularity::PerChannel => output,
                QuantGranularity::PerGroup { size } => {
                    let groups = in_features.div_ceil(size.max(1));
                    output * groups + input / size.max(1)
                }
            };
            let value = logical_value(input, output);
            let encoded = encode_value(
                value,
                scales[scale_index],
                zero_points
                    .as_ref()
                    .map(|values| values[scale_index])
                    .unwrap_or(0.0),
                scheme,
            );
            write_packed(&mut packed_values, index, encoded, scheme.format);
        }
    }

    Ok(PackedLinearWeight {
        scheme,
        packed_values,
        scales,
        zero_points,
        in_features,
        out_features,
    })
}

/// Pack FP32 logical weights using caller-provided scales (and optional zero-points).
///
/// Used when exporting QAT checkpoints that trained learnable (LSQ) scales.
pub fn pack_weights_with_scales(
    in_features: usize,
    out_features: usize,
    scheme: QuantScheme,
    scales: &[f32],
    zero_points: Option<&[f32]>,
    mut logical_value: impl FnMut(usize, usize) -> f32,
) -> Result<PackedLinearWeight, String> {
    scheme.validate()?;
    if in_features == 0 || out_features == 0 {
        return Err("quantized linear dimensions must be non-zero".into());
    }
    let scale_count = scheme.scale_count(in_features, out_features);
    if scales.len() != scale_count {
        return Err(format!(
            "expected {scale_count} scales, got {}",
            scales.len()
        ));
    }
    let zero_points = match zero_points {
        Some(values) => {
            if values.len() != scale_count {
                return Err(format!(
                    "expected {scale_count} zero-points, got {}",
                    values.len()
                ));
            }
            if scheme.symmetric {
                return Err("symmetric schemes do not take zero-points".into());
            }
            Some(values.to_vec())
        }
        None => {
            if !scheme.symmetric {
                return Err("asymmetric packing requires zero-points".into());
            }
            None
        }
    };

    let values_per_word = scheme.format.values_per_word();
    let total = in_features * out_features;
    let mut packed_values = vec![0u32; total.div_ceil(values_per_word)];

    for input in 0..in_features {
        for output in 0..out_features {
            let index = input * out_features + output;
            let scale_index = match scheme.granularity {
                QuantGranularity::PerTensor => 0,
                QuantGranularity::PerChannel => output,
                QuantGranularity::PerGroup { size } => {
                    let groups = in_features.div_ceil(size.max(1));
                    output * groups + input / size.max(1)
                }
            };
            let value = logical_value(input, output);
            let encoded = encode_value(
                value,
                scales[scale_index],
                zero_points
                    .as_ref()
                    .map(|values| values[scale_index])
                    .unwrap_or(0.0),
                scheme,
            );
            write_packed(&mut packed_values, index, encoded, scheme.format);
        }
    }

    Ok(PackedLinearWeight {
        scheme,
        packed_values,
        scales: scales.to_vec(),
        zero_points,
        in_features,
        out_features,
    })
}

fn collect_group_values(
    in_features: usize,
    out_features: usize,
    scheme: QuantScheme,
    scale_index: usize,
    logical_value: &mut impl FnMut(usize, usize) -> f32,
) -> Vec<f32> {
    let mut values = Vec::new();
    match scheme.granularity {
        QuantGranularity::PerTensor => {
            values.reserve(in_features * out_features);
            for input in 0..in_features {
                for output in 0..out_features {
                    values.push(logical_value(input, output));
                }
            }
        }
        QuantGranularity::PerChannel => {
            let output = scale_index;
            values.reserve(in_features);
            for input in 0..in_features {
                values.push(logical_value(input, output));
            }
        }
        QuantGranularity::PerGroup { size } => {
            let groups = in_features.div_ceil(size.max(1));
            let output = scale_index / groups;
            let group = scale_index % groups;
            let start = group * size;
            let end = (start + size).min(in_features);
            values.reserve(end - start);
            for input in start..end {
                values.push(logical_value(input, output));
            }
        }
    }
    values
}

fn choose_scale_zp(values: &[f32], scheme: QuantScheme) -> Result<(f32, f32), String> {
    if values.is_empty() {
        return Ok((1.0, 0.0));
    }
    match scheme.format {
        WeightQuantization::Nf4 => Ok((nf4_scale(values, scheme), 0.0)),
        WeightQuantization::Fp8E4M3 | WeightQuantization::Fp8E5M2 => {
            Ok((fp8_scale(values, scheme), 0.0))
        }
        _ => {
            if scheme.symmetric {
                let max_q = scheme.format.int_maximum().unwrap();
                let absmax = match scheme.scale_method {
                    ScaleMethod::AbsMax | ScaleMethod::MinMax => {
                        values.iter().map(|v| v.abs()).fold(0.0f32, f32::max)
                    }
                    ScaleMethod::Percentile => percentile_abs(values, scheme.percentile),
                    ScaleMethod::Mse => {
                        return Ok((mse_symmetric_scale(values, max_q), 0.0));
                    }
                };
                let scale = if absmax > 0.0 { absmax / max_q } else { 1.0 };
                Ok((scale, 0.0))
            } else {
                asymmetric_scale_zp(values, scheme)
            }
        }
    }
}

fn asymmetric_scale_zp(values: &[f32], scheme: QuantScheme) -> Result<(f32, f32), String> {
    let max_q = scheme.format.int_maximum().unwrap();
    let qmin = -max_q;
    let qmax = max_q;
    let (min_v, max_v) = match scheme.scale_method {
        ScaleMethod::AbsMax => {
            let absmax = values.iter().map(|v| v.abs()).fold(0.0f32, f32::max);
            (-absmax, absmax)
        }
        ScaleMethod::MinMax | ScaleMethod::Mse => {
            let min_v = values.iter().copied().fold(f32::INFINITY, f32::min);
            let max_v = values.iter().copied().fold(f32::NEG_INFINITY, f32::max);
            (min_v, max_v)
        }
        ScaleMethod::Percentile => {
            let lo = percentile_signed(values, 100.0 - scheme.percentile);
            let hi = percentile_signed(values, scheme.percentile);
            (lo, hi)
        }
    };
    if !min_v.is_finite() || !max_v.is_finite() || min_v == max_v {
        return Ok((1.0, 0.0));
    }
    let mut scale = (max_v - min_v) / (qmax - qmin);
    if scale <= 0.0 || !scale.is_finite() {
        scale = 1.0;
    }
    let mut zp = qmin - min_v / scale;
    zp = zp.round().clamp(qmin, qmax);
    if scheme.scale_method == ScaleMethod::Mse {
        return Ok(mse_asymmetric_scale_zp(values, qmin, qmax, scale, zp));
    }
    Ok((scale, zp))
}

fn mse_symmetric_scale(values: &[f32], max_q: f32) -> f32 {
    let absmax = values.iter().map(|v| v.abs()).fold(0.0f32, f32::max);
    if absmax <= 0.0 {
        return 1.0;
    }
    let mut best_scale = absmax / max_q;
    let mut best_mse = f32::INFINITY;
    for step in 0..32 {
        let candidate = absmax / max_q * (1.0 - step as f32 / 64.0);
        if candidate <= 0.0 {
            continue;
        }
        let mse = values
            .iter()
            .map(|value| {
                let q = (value / candidate).round().clamp(-max_q, max_q);
                let recon = q * candidate;
                let err = value - recon;
                err * err
            })
            .sum::<f32>();
        if mse < best_mse {
            best_mse = mse;
            best_scale = candidate;
        }
    }
    best_scale
}

fn mse_asymmetric_scale_zp(
    values: &[f32],
    qmin: f32,
    qmax: f32,
    base_scale: f32,
    base_zp: f32,
) -> (f32, f32) {
    let mut best = (base_scale, base_zp);
    let mut best_mse = f32::INFINITY;
    for step in 0..16 {
        let scale = base_scale * (1.0 - step as f32 / 32.0).max(0.05);
        for zp_delta in -2i32..=2 {
            let zp = (base_zp + zp_delta as f32).clamp(qmin, qmax);
            let mse = values
                .iter()
                .map(|value| {
                    let q = (value / scale + zp).round().clamp(qmin, qmax);
                    let recon = (q - zp) * scale;
                    let err = value - recon;
                    err * err
                })
                .sum::<f32>();
            if mse < best_mse {
                best_mse = mse;
                best = (scale, zp);
            }
        }
    }
    best
}

fn nf4_scale(values: &[f32], scheme: QuantScheme) -> f32 {
    let absmax = match scheme.scale_method {
        ScaleMethod::Percentile => percentile_abs(values, scheme.percentile),
        _ => values.iter().map(|v| v.abs()).fold(0.0f32, f32::max),
    };
    if absmax > 0.0 {
        absmax
    } else {
        1.0
    }
}

fn fp8_scale(values: &[f32], scheme: QuantScheme) -> f32 {
    // Pack FP8 values into the unit cube relative to absmax, then store scale.
    let absmax = match scheme.scale_method {
        ScaleMethod::Percentile => percentile_abs(values, scheme.percentile),
        _ => values.iter().map(|v| v.abs()).fold(0.0f32, f32::max),
    };
    if absmax > 0.0 {
        absmax
    } else {
        1.0
    }
}

fn percentile_abs(values: &[f32], pct: f32) -> f32 {
    let mut abs: Vec<f32> = values.iter().map(|v| v.abs()).collect();
    if abs.is_empty() {
        return 0.0;
    }
    abs.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
    let rank = ((pct / 100.0) * (abs.len() - 1) as f32).round() as usize;
    abs[rank.min(abs.len() - 1)]
}

fn percentile_signed(values: &[f32], pct: f32) -> f32 {
    let mut sorted = values.to_vec();
    if sorted.is_empty() {
        return 0.0;
    }
    sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
    let rank = ((pct / 100.0) * (sorted.len() - 1) as f32).round() as usize;
    sorted[rank.min(sorted.len() - 1)]
}

/// Encode one scalar into the packed raw domain for `format`.
pub fn encode_scalar(
    value: f32,
    scale: f32,
    zero_point: f32,
    format: WeightQuantization,
    symmetric: bool,
) -> u32 {
    encode_value(
        value,
        scale,
        zero_point,
        QuantScheme {
            format,
            granularity: QuantGranularity::PerTensor,
            symmetric,
            scale_method: ScaleMethod::AbsMax,
            percentile: 99.99,
        },
    )
}

/// Decode one packed raw value back to FP32.
pub fn decode_scalar(
    raw: u32,
    scale: f32,
    zero_point: f32,
    format: WeightQuantization,
    symmetric: bool,
) -> f32 {
    let _ = symmetric;
    match format {
        WeightQuantization::Nf4 => NF4_CODEBOOK[raw as usize] * scale,
        WeightQuantization::Fp8E4M3 => fp8_e4m3_to_f32(raw as u8) * scale,
        WeightQuantization::Fp8E5M2 => fp8_e5m2_to_f32(raw as u8) * scale,
        format => {
            let bits = format.bits();
            let sign_bit = 1u32 << (bits - 1);
            let signed = if raw & sign_bit == 0 {
                raw as i32
            } else {
                raw as i32 - (1i32 << bits)
            };
            (signed as f32 - zero_point) * scale
        }
    }
}

/// Pack a flat FP32 buffer with a single shared scale (and optional zero-point).
pub fn pack_flat(
    values: &[f32],
    format: WeightQuantization,
    scale: f32,
    zero_point: f32,
    symmetric: bool,
) -> Vec<u32> {
    let words = values.len().div_ceil(format.values_per_word());
    let mut packed = vec![0u32; words];
    for (index, &value) in values.iter().enumerate() {
        let encoded = encode_scalar(value, scale, zero_point, format, symmetric);
        write_packed(&mut packed, index, encoded, format);
    }
    packed
}

/// Unpack a flat packed buffer produced by [`pack_flat`].
pub fn unpack_flat(
    packed: &[u32],
    length: usize,
    format: WeightQuantization,
    scale: f32,
    zero_point: f32,
    symmetric: bool,
) -> Vec<f32> {
    let mut values = vec![0.0; length];
    for index in 0..length {
        let raw = read_packed(packed, index, format);
        values[index] = decode_scalar(raw, scale, zero_point, format, symmetric);
    }
    values
}

/// Abs-max scale for a symmetric integer / NF4 / FP8 range.
pub fn absmax_scale(values: &[f32], format: WeightQuantization) -> f32 {
    let absmax = values.iter().map(|v| v.abs()).fold(0.0f32, f32::max);
    if absmax <= 0.0 || !absmax.is_finite() {
        return 1.0;
    }
    match format.int_maximum() {
        Some(max_q) => absmax / max_q,
        None => absmax, // NF4 / FP8: scale maps into the unit codebook / float domain
    }
}

fn encode_value(value: f32, scale: f32, zp: f32, scheme: QuantScheme) -> u32 {
    match scheme.format {
        WeightQuantization::Nf4 => {
            let normalized = if scale > 0.0 { value / scale } else { 0.0 };
            nearest_nf4_index(normalized)
        }
        WeightQuantization::Fp8E4M3 => {
            let normalized = if scale > 0.0 { value / scale } else { 0.0 };
            u32::from(f32_to_fp8_e4m3(normalized))
        }
        WeightQuantization::Fp8E5M2 => {
            let normalized = if scale > 0.0 { value / scale } else { 0.0 };
            u32::from(f32_to_fp8_e5m2(normalized))
        }
        format => {
            let max_q = format.int_maximum().unwrap();
            let q = if scheme.symmetric {
                (value / scale).round().clamp(-max_q, max_q)
            } else {
                (value / scale + zp).round().clamp(-max_q, max_q)
            } as i32;
            let bits = format.bits();
            (q as u32) & ((1u32 << bits) - 1)
        }
    }
}

fn nearest_nf4_index(value: f32) -> u32 {
    let mut best = 0u32;
    let mut best_dist = f32::INFINITY;
    for (index, &code) in NF4_CODEBOOK.iter().enumerate() {
        let dist = (value - code).abs();
        if dist < best_dist {
            best_dist = dist;
            best = index as u32;
        }
    }
    best
}

/// Write a packed raw code at logical index (public for activation / KV packs).
pub fn write_packed_public(
    packed: &mut [u32],
    index: usize,
    encoded: u32,
    format: WeightQuantization,
) {
    write_packed(packed, index, encoded, format);
}

/// Read a packed raw code at logical index.
pub fn read_packed_public(packed: &[u32], index: usize, format: WeightQuantization) -> u32 {
    read_packed(packed, index, format)
}

fn write_packed(packed: &mut [u32], index: usize, encoded: u32, format: WeightQuantization) {
    let values_per_word = format.values_per_word();
    let bits = format.bits();
    let word = index / values_per_word;
    let slot = index % values_per_word;
    let shift = (slot as u32) * bits;
    let mask = (1u32 << bits) - 1;
    packed[word] |= (encoded & mask) << shift;
}

fn read_packed(packed: &[u32], index: usize, format: WeightQuantization) -> u32 {
    let values_per_word = format.values_per_word();
    let bits = format.bits();
    let word = index / values_per_word;
    let slot = index % values_per_word;
    let shift = (slot as u32) * bits;
    let mask = (1u32 << bits) - 1;
    (packed[word] >> shift) & mask
}

fn decode_raw(weight: &PackedLinearWeight, input: usize, output: usize) -> f32 {
    let index = input * weight.out_features + output;
    let raw = read_packed(&weight.packed_values, index, weight.scheme.format);
    match weight.scheme.format {
        WeightQuantization::Nf4 | WeightQuantization::Fp8E4M3 | WeightQuantization::Fp8E5M2 => {
            raw as f32
        }
        format => {
            let bits = format.bits();
            let sign_bit = 1u32 << (bits - 1);
            let signed = if raw & sign_bit == 0 {
                raw as i32
            } else {
                raw as i32 - (1i32 << bits)
            };
            signed as f32
        }
    }
}

/// Validate packed tensors restored from a checkpoint.
pub fn validate_packed(
    scheme: QuantScheme,
    packed_values: &[u32],
    scales: &[f32],
    zero_points: Option<&[f32]>,
    in_features: usize,
    out_features: usize,
) -> Result<(), String> {
    scheme.validate()?;
    if in_features == 0 || out_features == 0 {
        return Err("quantized linear dimensions must be non-zero".into());
    }
    let expected_scales = scheme.scale_count(in_features, out_features);
    if scales.len() != expected_scales {
        return Err(format!(
            "expected {expected_scales} scales, got {}",
            scales.len()
        ));
    }
    match (scheme.symmetric, zero_points) {
        (true, Some(_)) => {
            return Err("symmetric scheme must not include zero-points".into());
        }
        (false, None) => return Err("asymmetric scheme requires zero-points".into()),
        (false, Some(zp)) if zp.len() != expected_scales => {
            return Err(format!(
                "expected {expected_scales} zero-points, got {}",
                zp.len()
            ));
        }
        _ => {}
    }
    let expected_words =
        (in_features * out_features).div_ceil(scheme.format.values_per_word());
    if packed_values.len() != expected_words {
        return Err(format!(
            "expected {expected_words} packed words, got {}",
            packed_values.len()
        ));
    }
    Ok(())
}

// --- FP8 helpers (E4M3 / E5M2, finite-only; no NaN/Inf encoding) ---

fn f32_to_fp8_e4m3(value: f32) -> u8 {
    float_to_fp8(value, 4, 3, 7)
}

fn f32_to_fp8_e5m2(value: f32) -> u8 {
    float_to_fp8(value, 5, 2, 15)
}

fn fp8_e4m3_to_f32(bits: u8) -> f32 {
    fp8_to_float(bits, 4, 3, 7)
}

fn fp8_e5m2_to_f32(bits: u8) -> f32 {
    fp8_to_float(bits, 5, 2, 15)
}

fn float_to_fp8(value: f32, exp_bits: u32, mant_bits: u32, exp_bias: i32) -> u8 {
    if !value.is_finite() || value == 0.0 {
        return if value.is_sign_negative() { 0x80 } else { 0 };
    }
    let sign = if value.is_sign_negative() { 1u8 } else { 0u8 };
    let abs = value.abs();
    let max_exp = (1i32 << exp_bits) - 1;
    let mut exp = (abs.log2().floor() as i32) + exp_bias;
    if exp <= 0 {
        // Subnormals: encode as zero for simplicity (RTN path prioritizes stability).
        return sign << 7;
    }
    if exp >= max_exp {
        exp = max_exp - 1;
    }
    let frac = abs / 2f32.powi(exp - exp_bias) - 1.0;
    let mant_max = (1u32 << mant_bits) - 1;
    let mant = (frac * (mant_max + 1) as f32)
        .round()
        .clamp(0.0, mant_max as f32) as u8;
    (sign << 7) | ((exp as u8) << mant_bits) | mant
}

fn fp8_to_float(bits: u8, exp_bits: u32, mant_bits: u32, exp_bias: i32) -> f32 {
    let sign = if bits & 0x80 != 0 { -1.0f32 } else { 1.0 };
    let exp_mask = (1u8 << exp_bits) - 1;
    let mant_mask = (1u8 << mant_bits) - 1;
    let exp = ((bits >> mant_bits) & exp_mask) as i32;
    let mant = bits & mant_mask;
    if exp == 0 {
        return 0.0 * sign;
    }
    let frac = 1.0 + (mant as f32) / ((mant_mask + 1) as f32);
    sign * frac * 2f32.powi(exp - exp_bias)
}

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

    #[test]
    fn symmetric_int8_per_channel_roundtrips() {
        let in_features = 4;
        let out_features = 2;
        let data = [0.5f32, -1.0, 0.25, 0.75, -0.5, 0.1, 0.9, -0.2];
        let packed = pack_weights(in_features, out_features, QuantScheme::default(), |i, o| {
            data[i * out_features + o]
        })
        .unwrap();
        assert_eq!(packed.scales.len(), out_features);
        assert!(packed.zero_points.is_none());
        for i in 0..in_features {
            for o in 0..out_features {
                let original = data[i * out_features + o];
                let recon = packed.dequantized_value(i, o);
                assert!((original - recon).abs() < 0.02, "{original} vs {recon}");
            }
        }
    }

    #[test]
    fn group_and_asymmetric_int4_pack() {
        let scheme = QuantScheme {
            format: WeightQuantization::Int4,
            granularity: QuantGranularity::PerGroup { size: 32 },
            symmetric: false,
            scale_method: ScaleMethod::MinMax,
            percentile: 99.99,
        };
        let in_features = 32;
        let out_features = 2;
        let packed = pack_weights(in_features, out_features, scheme, |i, o| {
            ((i + o) as f32) * 0.01 - 0.1
        })
        .unwrap();
        assert_eq!(packed.scales.len(), out_features);
        assert!(packed.zero_points.is_some());
    }

    #[test]
    fn nf4_and_fp8_pack() {
        for format in [
            WeightQuantization::Nf4,
            WeightQuantization::Fp8E4M3,
            WeightQuantization::Fp8E5M2,
        ] {
            let packed = pack_weights(8, 2, QuantScheme::default_for(format), |i, o| {
                (i as f32 * 0.1 + o as f32 * 0.05) - 0.3
            })
            .unwrap();
            assert_eq!(packed.scheme.format, format);
            assert!(!packed.scales.is_empty());
        }
    }
}