scirs2-neural 0.4.2

Neural network building blocks module for SciRS2 (scirs2-neural) - Minimal Version
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
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
//! Mixed Precision Training Support for Neural Networks
//!
//! This module provides comprehensive mixed precision training utilities that enable:
//!
//! - **FP16/FP32 Mixed Precision**: Forward passes in FP16 for speed, master weights in FP32 for accuracy
//! - **Dynamic Loss Scaling**: Automatic gradient scaling with overflow detection
//! - **Master Weight Management**: FP32 master weights with FP16 computation copies
//! - **Automatic Mixed Precision (AMP)**: Easy-to-use wrapper for mixed precision training
//! - **Memory-Efficient Operations**: Reduced memory footprint through half-precision activations
//!
//! # Example Usage
//!
//! ```rust
//! use scirs2_neural::training::mixed_precision::{
//!     MixedPrecisionConfig, GradScaler, AutoMixedPrecision, MixedPrecisionTrainer,
//! };
//!
//! // Configure mixed precision training
//! let config = MixedPrecisionConfig::builder()
//!     .enabled(true)
//!     .initial_loss_scale(65536.0)
//!     .growth_factor(2.0)
//!     .backoff_factor(0.5)
//!     .growth_interval(2000)
//!     .build()
//!     .expect("failed to build config");
//!
//! // Create gradient scaler
//! let mut scaler = GradScaler::new(config.clone()).expect("failed to create scaler");
//!
//! // Create mixed precision trainer
//! let trainer = MixedPrecisionTrainer::<f64>::new(config).expect("failed to create trainer");
//! ```

use crate::error::{NeuralError, Result};
use crate::layers::Layer;
use scirs2_core::ndarray::{Array, ArrayD, IxDyn, ScalarOperand};
use scirs2_core::numeric::{Float, FromPrimitive, NumAssign};
use std::collections::HashMap;
use std::fmt::Debug;
use std::marker::PhantomData;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, RwLock};

// ============================================================================
// Configuration Types
// ============================================================================

/// Loss scaling strategy for mixed precision training
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LossScalingStrategy {
    /// Fixed loss scaling with a constant scale factor
    Fixed,
    /// Dynamic loss scaling that adapts based on gradient overflow detection
    #[default]
    Dynamic,
    /// Automatic selection based on hardware and training conditions
    Automatic,
}

/// Precision mode for different parts of the computation
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PrecisionMode {
    /// Full FP32 precision (standard)
    FP32,
    /// Half precision FP16 for forward/backward, FP32 for master weights
    #[default]
    FP16Mixed,
    /// BFloat16 mixed precision (better for training stability)
    BF16Mixed,
    /// Automatic precision selection based on operation type
    Automatic,
}

/// Operations that should always run in FP32 for numerical stability
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FP32Operation {
    /// Loss computation
    LossComputation,
    /// Softmax and log-softmax
    Softmax,
    /// Layer normalization
    LayerNorm,
    /// Batch normalization running statistics
    BatchNormStats,
    /// Gradient accumulation
    GradientAccumulation,
    /// Optimizer state updates
    OptimizerUpdate,
    /// Embedding operations
    Embedding,
    /// Reduction operations (sum, mean, etc.)
    Reductions,
}

/// Configuration for mixed precision training
#[derive(Debug, Clone)]
pub struct MixedPrecisionConfig {
    /// Whether to enable mixed precision training
    pub enabled: bool,
    /// Precision mode to use
    pub precision_mode: PrecisionMode,
    /// Loss scaling strategy
    pub loss_scaling_strategy: LossScalingStrategy,
    /// Initial loss scale factor for dynamic scaling
    pub initial_loss_scale: f64,
    /// Factor to multiply loss scale when no overflow is detected
    pub growth_factor: f64,
    /// Factor to multiply loss scale when overflow is detected
    pub backoff_factor: f64,
    /// Number of successful steps before increasing loss scale
    pub growth_interval: usize,
    /// Minimum loss scale (to prevent underflow)
    pub min_loss_scale: f64,
    /// Maximum loss scale (to prevent overflow)
    pub max_loss_scale: f64,
    /// Operations that should always use FP32
    pub fp32_operations: Vec<FP32Operation>,
    /// Whether to cast model parameters to FP16 during forward pass
    pub cast_model_type: bool,
    /// Whether to use memory-efficient gradient computation
    pub memory_efficient_gradients: bool,
    /// Whether to enable gradient checkpointing integration
    pub gradient_checkpointing: bool,
    /// Maximum number of consecutive overflows before reducing scale aggressively
    pub max_consecutive_overflows: usize,
    /// Gradient clipping threshold (applied before unscaling)
    pub grad_clip_threshold: Option<f64>,
    /// Whether to log scaling statistics
    pub log_statistics: bool,
}

impl Default for MixedPrecisionConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            precision_mode: PrecisionMode::FP16Mixed,
            loss_scaling_strategy: LossScalingStrategy::Dynamic,
            initial_loss_scale: 65536.0, // 2^16
            growth_factor: 2.0,
            backoff_factor: 0.5,
            growth_interval: 2000,
            min_loss_scale: 1.0,
            max_loss_scale: 2.0_f64.powi(24), // 2^24
            fp32_operations: vec![
                FP32Operation::LossComputation,
                FP32Operation::Softmax,
                FP32Operation::LayerNorm,
                FP32Operation::BatchNormStats,
                FP32Operation::GradientAccumulation,
                FP32Operation::OptimizerUpdate,
            ],
            cast_model_type: true,
            memory_efficient_gradients: true,
            gradient_checkpointing: false,
            max_consecutive_overflows: 5,
            grad_clip_threshold: None,
            log_statistics: false,
        }
    }
}

impl MixedPrecisionConfig {
    /// Create a new builder for MixedPrecisionConfig
    pub fn builder() -> MixedPrecisionConfigBuilder {
        MixedPrecisionConfigBuilder::new()
    }

    /// Check if an operation should use FP32
    pub fn should_use_fp32(&self, operation: FP32Operation) -> bool {
        self.fp32_operations.contains(&operation)
    }

    /// Validate the configuration
    pub fn validate(&self) -> Result<()> {
        if self.initial_loss_scale <= 0.0 {
            return Err(NeuralError::ConfigError(
                "Initial loss scale must be positive".to_string(),
            ));
        }
        if self.growth_factor <= 1.0 {
            return Err(NeuralError::ConfigError(
                "Growth factor must be greater than 1.0".to_string(),
            ));
        }
        if self.backoff_factor <= 0.0 || self.backoff_factor >= 1.0 {
            return Err(NeuralError::ConfigError(
                "Backoff factor must be in (0.0, 1.0)".to_string(),
            ));
        }
        if self.min_loss_scale > self.max_loss_scale {
            return Err(NeuralError::ConfigError(
                "Minimum loss scale cannot exceed maximum loss scale".to_string(),
            ));
        }
        if self.growth_interval == 0 {
            return Err(NeuralError::ConfigError(
                "Growth interval must be at least 1".to_string(),
            ));
        }
        Ok(())
    }
}

/// Builder for MixedPrecisionConfig
#[derive(Debug, Clone)]
pub struct MixedPrecisionConfigBuilder {
    config: MixedPrecisionConfig,
}

impl MixedPrecisionConfigBuilder {
    /// Create a new builder with default values
    pub fn new() -> Self {
        Self {
            config: MixedPrecisionConfig::default(),
        }
    }

    /// Enable or disable mixed precision training
    pub fn enabled(mut self, enabled: bool) -> Self {
        self.config.enabled = enabled;
        self
    }

    /// Set the precision mode
    pub fn precision_mode(mut self, mode: PrecisionMode) -> Self {
        self.config.precision_mode = mode;
        self
    }

    /// Set the loss scaling strategy
    pub fn loss_scaling_strategy(mut self, strategy: LossScalingStrategy) -> Self {
        self.config.loss_scaling_strategy = strategy;
        self
    }

    /// Set the initial loss scale
    pub fn initial_loss_scale(mut self, scale: f64) -> Self {
        self.config.initial_loss_scale = scale;
        self
    }

    /// Set the growth factor for dynamic scaling
    pub fn growth_factor(mut self, factor: f64) -> Self {
        self.config.growth_factor = factor;
        self
    }

    /// Set the backoff factor for dynamic scaling
    pub fn backoff_factor(mut self, factor: f64) -> Self {
        self.config.backoff_factor = factor;
        self
    }

    /// Set the growth interval
    pub fn growth_interval(mut self, interval: usize) -> Self {
        self.config.growth_interval = interval;
        self
    }

    /// Set the minimum loss scale
    pub fn min_loss_scale(mut self, scale: f64) -> Self {
        self.config.min_loss_scale = scale;
        self
    }

    /// Set the maximum loss scale
    pub fn max_loss_scale(mut self, scale: f64) -> Self {
        self.config.max_loss_scale = scale;
        self
    }

    /// Add an FP32 operation
    pub fn add_fp32_operation(mut self, operation: FP32Operation) -> Self {
        if !self.config.fp32_operations.contains(&operation) {
            self.config.fp32_operations.push(operation);
        }
        self
    }

    /// Set gradient clipping threshold
    pub fn grad_clip_threshold(mut self, threshold: f64) -> Self {
        self.config.grad_clip_threshold = Some(threshold);
        self
    }

    /// Enable memory-efficient gradients
    pub fn memory_efficient_gradients(mut self, enabled: bool) -> Self {
        self.config.memory_efficient_gradients = enabled;
        self
    }

    /// Enable gradient checkpointing integration
    pub fn gradient_checkpointing(mut self, enabled: bool) -> Self {
        self.config.gradient_checkpointing = enabled;
        self
    }

    /// Enable logging of scaling statistics
    pub fn log_statistics(mut self, enabled: bool) -> Self {
        self.config.log_statistics = enabled;
        self
    }

    /// Build the configuration
    pub fn build(self) -> Result<MixedPrecisionConfig> {
        self.config.validate()?;
        Ok(self.config)
    }
}

impl Default for MixedPrecisionConfigBuilder {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Half Precision Tensor Operations
// ============================================================================

/// Half precision (FP16) value representation
///
/// Uses u16 internally to store the IEEE 754 half-precision float
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Half(u16);

impl Half {
    /// Zero value in half precision
    pub const ZERO: Half = Half(0);

    /// One value in half precision
    pub const ONE: Half = Half(0x3c00);

    /// Maximum finite value
    pub const MAX: Half = Half(0x7bff);

    /// Minimum positive normalized value
    pub const MIN_POSITIVE: Half = Half(0x0400);

    /// Infinity
    pub const INFINITY: Half = Half(0x7c00);

    /// Negative infinity
    pub const NEG_INFINITY: Half = Half(0xfc00);

    /// NaN (quiet NaN)
    pub const NAN: Half = Half(0x7e00);

    /// Create a half from raw bits
    pub const fn from_bits(bits: u16) -> Self {
        Half(bits)
    }

    /// Get the raw bits
    pub const fn to_bits(self) -> u16 {
        self.0
    }

    /// Convert from f32 to half precision
    pub fn from_f32(value: f32) -> Self {
        let bits = value.to_bits();
        let sign = (bits >> 31) & 1;
        let exp = ((bits >> 23) & 0xff) as i32;
        let frac = bits & 0x7fffff;

        // Handle special cases
        if exp == 0xff {
            // Infinity or NaN
            if frac == 0 {
                // Infinity
                return Half(((sign << 15) | 0x7c00) as u16);
            } else {
                // NaN
                return Half(((sign << 15) | 0x7e00) as u16);
            }
        }

        // Rebias exponent from f32 (bias 127) to f16 (bias 15)
        let new_exp = exp - 127 + 15;

        if new_exp <= 0 {
            // Denormalized or zero
            if new_exp < -10 {
                // Too small, becomes zero
                return Half((sign << 15) as u16);
            }
            // Denormalized
            let shift = 1 - new_exp;
            let frac_with_hidden = frac | 0x800000;
            let frac16 = (frac_with_hidden >> (shift + 13)) as u16;
            return Half(((sign << 15) | frac16 as u32) as u16);
        }

        if new_exp >= 31 {
            // Overflow to infinity
            return Half(((sign << 15) | 0x7c00) as u16);
        }

        // Normal case
        let frac16 = (frac >> 13) as u16;
        Half(((sign << 15) | ((new_exp as u32) << 10) | frac16 as u32) as u16)
    }

    /// Convert from half precision to f32
    pub fn to_f32(self) -> f32 {
        let bits = self.0 as u32;
        let sign = (bits >> 15) & 1;
        let exp = (bits >> 10) & 0x1f;
        let frac = bits & 0x3ff;

        if exp == 0 {
            if frac == 0 {
                // Zero
                return f32::from_bits(sign << 31);
            }
            // Denormalized
            let mut frac = frac;
            let mut e = -14i32;
            while frac & 0x400 == 0 {
                frac <<= 1;
                e -= 1;
            }
            frac &= 0x3ff;
            let exp32 = (e + 127) as u32;
            let frac32 = frac << 13;
            return f32::from_bits((sign << 31) | (exp32 << 23) | frac32);
        }

        if exp == 0x1f {
            // Infinity or NaN
            if frac == 0 {
                return f32::from_bits((sign << 31) | 0x7f800000);
            }
            return f32::from_bits((sign << 31) | 0x7fc00000);
        }

        // Normal case
        let exp32 = (exp as i32 - 15 + 127) as u32;
        let frac32 = frac << 13;
        f32::from_bits((sign << 31) | (exp32 << 23) | frac32)
    }

    /// Check if the value is NaN
    pub fn is_nan(self) -> bool {
        (self.0 & 0x7c00) == 0x7c00 && (self.0 & 0x03ff) != 0
    }

    /// Check if the value is infinite
    pub fn is_infinite(self) -> bool {
        (self.0 & 0x7fff) == 0x7c00
    }

    /// Check if the value is finite
    pub fn is_finite(self) -> bool {
        (self.0 & 0x7c00) != 0x7c00
    }

    /// Check if the value is zero
    pub fn is_zero(self) -> bool {
        (self.0 & 0x7fff) == 0
    }
}

impl From<f32> for Half {
    fn from(value: f32) -> Self {
        Half::from_f32(value)
    }
}

impl From<Half> for f32 {
    fn from(value: Half) -> Self {
        value.to_f32()
    }
}

impl From<f64> for Half {
    fn from(value: f64) -> Self {
        Half::from_f32(value as f32)
    }
}

impl From<Half> for f64 {
    fn from(value: Half) -> Self {
        value.to_f32() as f64
    }
}

/// Container for mixed precision tensors
#[derive(Debug, Clone)]
pub struct MixedPrecisionTensor<F: Float + Debug + ScalarOperand> {
    /// Original FP32 data
    fp32_data: Option<ArrayD<F>>,
    /// FP16 representation (stored as raw bits for computation)
    fp16_bits: Option<ArrayD<u16>>,
    /// Shape of the tensor
    shape: Vec<usize>,
    /// Current precision state
    precision: PrecisionMode,
}

impl<F: Float + Debug + ScalarOperand + FromPrimitive> MixedPrecisionTensor<F> {
    /// Create a new mixed precision tensor from FP32 data
    pub fn from_fp32(data: ArrayD<F>) -> Self {
        let shape = data.shape().to_vec();
        Self {
            fp32_data: Some(data),
            fp16_bits: None,
            shape,
            precision: PrecisionMode::FP32,
        }
    }

    /// Convert to FP16 representation
    pub fn to_fp16(&mut self) -> Result<()> {
        if self.fp16_bits.is_some() {
            return Ok(()); // Already in FP16
        }

        let fp32 = self
            .fp32_data
            .as_ref()
            .ok_or_else(|| NeuralError::InvalidState("No FP32 data available".to_string()))?;

        // Convert each element to FP16 bits
        let fp16_data: Vec<u16> = fp32
            .iter()
            .map(|&x| {
                let f32_val = x.to_f64().unwrap_or(0.0) as f32;
                Half::from_f32(f32_val).to_bits()
            })
            .collect();

        self.fp16_bits = Some(
            ArrayD::from_shape_vec(IxDyn(&self.shape), fp16_data).map_err(|e| {
                NeuralError::ShapeMismatch(format!("FP16 conversion failed: {}", e))
            })?,
        );
        self.precision = PrecisionMode::FP16Mixed;
        Ok(())
    }

    /// Convert back to FP32
    pub fn to_fp32(&mut self) -> Result<()> {
        if self.fp32_data.is_some() && self.precision == PrecisionMode::FP32 {
            return Ok(()); // Already in FP32
        }

        let fp16 = self
            .fp16_bits
            .as_ref()
            .ok_or_else(|| NeuralError::InvalidState("No FP16 data available".to_string()))?;

        // Convert each element back to FP32
        let fp32_data: Vec<F> = fp16
            .iter()
            .map(|&bits| {
                let f32_val = Half::from_bits(bits).to_f32();
                F::from(f32_val).unwrap_or_else(F::zero)
            })
            .collect();

        self.fp32_data = Some(
            ArrayD::from_shape_vec(IxDyn(&self.shape), fp32_data).map_err(|e| {
                NeuralError::ShapeMismatch(format!("FP32 conversion failed: {}", e))
            })?,
        );
        self.precision = PrecisionMode::FP32;
        Ok(())
    }

    /// Get FP32 data (converting if necessary)
    pub fn get_fp32(&mut self) -> Result<&ArrayD<F>> {
        self.to_fp32()?;
        self.fp32_data
            .as_ref()
            .ok_or_else(|| NeuralError::InvalidState("FP32 data not available".to_string()))
    }

    /// Get current precision mode
    pub fn precision(&self) -> PrecisionMode {
        self.precision
    }

    /// Get shape
    pub fn shape(&self) -> &[usize] {
        &self.shape
    }

    /// Free FP16 memory to save space
    pub fn free_fp16(&mut self) {
        self.fp16_bits = None;
    }

    /// Free FP32 memory (use with caution - will need to regenerate)
    pub fn free_fp32(&mut self) {
        self.fp32_data = None;
    }

    /// Check if tensor has valid data
    pub fn is_valid(&self) -> bool {
        self.fp32_data.is_some() || self.fp16_bits.is_some()
    }
}

// ============================================================================
// Gradient Scaler
// ============================================================================

/// Statistics for gradient scaling
#[derive(Debug, Clone, Default)]
pub struct GradScalerStats {
    /// Current loss scale
    pub loss_scale: f64,
    /// Total number of steps
    pub total_steps: u64,
    /// Number of steps with overflow
    pub overflow_steps: u64,
    /// Number of successful steps since last scale increase
    pub steps_since_increase: u64,
    /// Number of scale increases
    pub num_scale_increases: u64,
    /// Number of scale decreases
    pub num_scale_decreases: u64,
    /// Consecutive overflow count
    pub consecutive_overflows: u64,
}

/// Gradient scaler for dynamic loss scaling in mixed precision training
///
/// The GradScaler performs the following operations:
/// 1. Scales the loss before backward pass to prevent gradient underflow in FP16
/// 2. Unscales gradients after backward pass
/// 3. Checks for overflow/NaN in gradients
/// 4. Dynamically adjusts the scale factor based on gradient health
#[derive(Debug)]
pub struct GradScaler {
    /// Configuration
    config: MixedPrecisionConfig,
    /// Current loss scale
    scale: Arc<RwLock<f64>>,
    /// Number of successful steps since last scale increase
    growth_tracker: AtomicU64,
    /// Whether an overflow was detected in the current step
    found_inf: AtomicBool,
    /// Consecutive overflow count
    consecutive_overflows: AtomicU64,
    /// Statistics
    stats: Arc<RwLock<GradScalerStats>>,
}

impl GradScaler {
    /// Create a new gradient scaler
    pub fn new(config: MixedPrecisionConfig) -> Result<Self> {
        config.validate()?;
        let initial_scale = config.initial_loss_scale;

        Ok(Self {
            config,
            scale: Arc::new(RwLock::new(initial_scale)),
            growth_tracker: AtomicU64::new(0),
            found_inf: AtomicBool::new(false),
            consecutive_overflows: AtomicU64::new(0),
            stats: Arc::new(RwLock::new(GradScalerStats {
                loss_scale: initial_scale,
                ..Default::default()
            })),
        })
    }

    /// Get the current loss scale
    pub fn get_scale(&self) -> f64 {
        *self.scale.read().unwrap_or_else(|e| e.into_inner())
    }

    /// Scale a loss value for backward pass
    pub fn scale_loss<F: Float + Debug + FromPrimitive>(&self, loss: F) -> Result<F> {
        if !self.config.enabled {
            return Ok(loss);
        }

        let scale = self.get_scale();
        let scale_f = F::from(scale).ok_or_else(|| {
            NeuralError::ComputationError("Failed to convert scale to loss type".to_string())
        })?;

        Ok(loss * scale_f)
    }

    /// Unscale gradients after backward pass
    pub fn unscale_gradients<F: Float + Debug + ScalarOperand + FromPrimitive + NumAssign>(
        &self,
        gradients: &mut [ArrayD<F>],
    ) -> Result<bool> {
        if !self.config.enabled {
            return Ok(false);
        }

        let scale = self.get_scale();
        let inv_scale = F::from(1.0 / scale).ok_or_else(|| {
            NeuralError::ComputationError("Failed to compute inverse scale".to_string())
        })?;

        let mut found_inf = false;

        for grad in gradients.iter_mut() {
            for val in grad.iter_mut() {
                *val *= inv_scale;

                // Check for overflow/NaN
                let f64_val = val.to_f64().unwrap_or(f64::NAN);
                if !f64_val.is_finite() {
                    found_inf = true;
                }
            }
        }

        self.found_inf.store(found_inf, Ordering::SeqCst);
        Ok(found_inf)
    }

    /// Check if gradients contain inf/nan values
    pub fn check_gradients_for_overflow<F: Float + Debug + ScalarOperand>(
        &self,
        gradients: &[ArrayD<F>],
    ) -> bool {
        for grad in gradients {
            for val in grad.iter() {
                let f64_val = val.to_f64().unwrap_or(f64::NAN);
                if !f64_val.is_finite() {
                    return true;
                }
            }
        }
        false
    }

    /// Apply gradient clipping if configured
    pub fn clip_gradients<F: Float + Debug + ScalarOperand + FromPrimitive + NumAssign>(
        &self,
        gradients: &mut [ArrayD<F>],
    ) -> Result<Option<f64>> {
        let threshold = match self.config.grad_clip_threshold {
            Some(t) => t,
            None => return Ok(None),
        };

        // Compute global norm
        let mut global_norm_sq = 0.0_f64;
        for grad in gradients.iter() {
            for val in grad.iter() {
                let f = val.to_f64().unwrap_or(0.0);
                global_norm_sq += f * f;
            }
        }
        let global_norm = global_norm_sq.sqrt();

        if global_norm > threshold {
            let clip_factor = F::from(threshold / global_norm).ok_or_else(|| {
                NeuralError::ComputationError("Failed to compute clip factor".to_string())
            })?;

            for grad in gradients.iter_mut() {
                for val in grad.iter_mut() {
                    *val *= clip_factor;
                }
            }
        }

        Ok(Some(global_norm))
    }

    /// Update the scale after a training step
    ///
    /// Returns true if the step should be skipped (due to overflow)
    pub fn update(&self) -> Result<bool> {
        if !self.config.enabled {
            return Ok(false);
        }

        let found_inf = self.found_inf.load(Ordering::SeqCst);

        let mut scale = self.scale.write().unwrap_or_else(|e| e.into_inner());
        let mut stats = self.stats.write().unwrap_or_else(|e| e.into_inner());

        stats.total_steps += 1;

        if found_inf {
            // Overflow detected - decrease scale
            *scale *= self.config.backoff_factor;
            *scale = scale.max(self.config.min_loss_scale);

            self.growth_tracker.store(0, Ordering::SeqCst);
            let consec = self.consecutive_overflows.fetch_add(1, Ordering::SeqCst) + 1;

            stats.overflow_steps += 1;
            stats.num_scale_decreases += 1;
            stats.consecutive_overflows = consec;
            stats.steps_since_increase = 0;

            if self.config.log_statistics {
                eprintln!(
                    "[GradScaler] Overflow detected. Scale: {:.2} -> {:.2}, consecutive: {}",
                    *scale / self.config.backoff_factor,
                    *scale,
                    consec
                );
            }

            // Check for too many consecutive overflows
            if consec >= self.config.max_consecutive_overflows as u64 {
                // Apply more aggressive backoff
                *scale *= self.config.backoff_factor;
                *scale = scale.max(self.config.min_loss_scale);

                if self.config.log_statistics {
                    eprintln!(
                        "[GradScaler] Aggressive backoff due to {} consecutive overflows. Scale: {:.2}",
                        consec, *scale
                    );
                }
            }

            stats.loss_scale = *scale;
            self.found_inf.store(false, Ordering::SeqCst);
            return Ok(true); // Skip this step
        }

        // No overflow - potentially increase scale
        self.consecutive_overflows.store(0, Ordering::SeqCst);
        let growth_count = self.growth_tracker.fetch_add(1, Ordering::SeqCst) + 1;
        stats.steps_since_increase = growth_count;

        if growth_count >= self.config.growth_interval as u64 {
            // Increase scale
            let old_scale = *scale;
            *scale *= self.config.growth_factor;
            *scale = scale.min(self.config.max_loss_scale);

            self.growth_tracker.store(0, Ordering::SeqCst);
            stats.num_scale_increases += 1;
            stats.steps_since_increase = 0;

            if self.config.log_statistics && *scale != old_scale {
                eprintln!(
                    "[GradScaler] Scale increased: {:.2} -> {:.2}",
                    old_scale, *scale
                );
            }
        }

        stats.loss_scale = *scale;
        stats.consecutive_overflows = 0;
        self.found_inf.store(false, Ordering::SeqCst);
        Ok(false)
    }

    /// Get statistics
    pub fn get_stats(&self) -> GradScalerStats {
        self.stats.read().unwrap_or_else(|e| e.into_inner()).clone()
    }

    /// Reset the scaler to initial state
    pub fn reset(&self) {
        let mut scale = self.scale.write().unwrap_or_else(|e| e.into_inner());
        *scale = self.config.initial_loss_scale;

        self.growth_tracker.store(0, Ordering::SeqCst);
        self.found_inf.store(false, Ordering::SeqCst);
        self.consecutive_overflows.store(0, Ordering::SeqCst);

        let mut stats = self.stats.write().unwrap_or_else(|e| e.into_inner());
        *stats = GradScalerStats {
            loss_scale: self.config.initial_loss_scale,
            ..Default::default()
        };
    }

    /// Check if currently enabled
    pub fn is_enabled(&self) -> bool {
        self.config.enabled
    }
}

// ============================================================================
// Master Weights Management
// ============================================================================

/// Master weights container for mixed precision training
///
/// Stores FP32 master weights while using FP16 copies for computation.
/// This is essential for training stability as FP16 has limited precision.
#[derive(Debug)]
pub struct MasterWeights<F: Float + Debug + ScalarOperand> {
    /// FP32 master weights (authoritative)
    master_weights: HashMap<String, ArrayD<F>>,
    /// FP16 computation copies (derived from master)
    compute_weights: HashMap<String, ArrayD<u16>>,
    /// Whether to sync on every update
    sync_on_update: bool,
    /// Precision mode
    precision_mode: PrecisionMode,
}

impl<F: Float + Debug + ScalarOperand + FromPrimitive + NumAssign> MasterWeights<F> {
    /// Create a new master weights container
    pub fn new(precision_mode: PrecisionMode) -> Self {
        Self {
            master_weights: HashMap::new(),
            compute_weights: HashMap::new(),
            sync_on_update: true,
            precision_mode,
        }
    }

    /// Register a weight tensor
    pub fn register(&mut self, name: &str, weights: ArrayD<F>) -> Result<()> {
        self.master_weights.insert(name.to_string(), weights);
        self.sync_to_compute(name)?;
        Ok(())
    }

    /// Sync master weights to compute weights (FP32 -> FP16)
    fn sync_to_compute(&mut self, name: &str) -> Result<()> {
        let master = self
            .master_weights
            .get(name)
            .ok_or_else(|| NeuralError::InvalidArgument(format!("Weight '{}' not found", name)))?;

        let fp16_data: Vec<u16> = master
            .iter()
            .map(|&x| {
                let f32_val = x.to_f64().unwrap_or(0.0) as f32;
                Half::from_f32(f32_val).to_bits()
            })
            .collect();

        let compute = ArrayD::from_shape_vec(IxDyn(master.shape()), fp16_data)
            .map_err(|e| NeuralError::ShapeMismatch(format!("Sync failed: {}", e)))?;

        self.compute_weights.insert(name.to_string(), compute);
        Ok(())
    }

    /// Get compute weights (FP16) for a layer
    pub fn get_compute_weights(&self, name: &str) -> Option<&ArrayD<u16>> {
        self.compute_weights.get(name)
    }

    /// Get master weights (FP32) for a layer
    pub fn get_master_weights(&self, name: &str) -> Option<&ArrayD<F>> {
        self.master_weights.get(name)
    }

    /// Update master weights with unscaled gradients
    pub fn update_master_weights(
        &mut self,
        name: &str,
        gradients: &ArrayD<F>,
        learning_rate: F,
    ) -> Result<()> {
        let master = self
            .master_weights
            .get_mut(name)
            .ok_or_else(|| NeuralError::InvalidArgument(format!("Weight '{}' not found", name)))?;

        // Standard SGD update: w = w - lr * grad
        for (w, g) in master.iter_mut().zip(gradients.iter()) {
            *w -= learning_rate * *g;
        }

        // Sync to compute weights if enabled
        if self.sync_on_update {
            self.sync_to_compute(name)?;
        }

        Ok(())
    }

    /// Sync all master weights to compute weights
    pub fn sync_all(&mut self) -> Result<()> {
        let names: Vec<String> = self.master_weights.keys().cloned().collect();
        for name in names {
            self.sync_to_compute(&name)?;
        }
        Ok(())
    }

    /// Get all weight names
    pub fn weight_names(&self) -> Vec<&String> {
        self.master_weights.keys().collect()
    }

    /// Check if a weight exists
    pub fn contains(&self, name: &str) -> bool {
        self.master_weights.contains_key(name)
    }

    /// Get the number of registered weights
    pub fn len(&self) -> usize {
        self.master_weights.len()
    }

    /// Check if empty
    pub fn is_empty(&self) -> bool {
        self.master_weights.is_empty()
    }

    /// Get precision mode
    pub fn precision_mode(&self) -> PrecisionMode {
        self.precision_mode
    }
}

// ============================================================================
// Automatic Mixed Precision (AMP) Wrapper
// ============================================================================

/// Context manager state for AMP
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AmpContextState {
    /// Normal operation (outside AMP context)
    Normal,
    /// Inside forward pass context
    Forward,
    /// Inside backward pass context
    Backward,
    /// Inside optimization step context
    Optimization,
}

/// Automatic Mixed Precision (AMP) wrapper
///
/// Provides automatic precision management for neural network operations.
/// Similar to PyTorch's `torch.cuda.amp.autocast` context manager.
#[derive(Debug)]
pub struct AutoMixedPrecision<F: Float + Debug + ScalarOperand> {
    /// Configuration
    config: MixedPrecisionConfig,
    /// Gradient scaler
    scaler: Option<GradScaler>,
    /// Master weights
    master_weights: Option<MasterWeights<F>>,
    /// Current context state
    context_state: Arc<RwLock<AmpContextState>>,
    /// Whether AMP is active
    active: AtomicBool,
    /// Phantom data
    _phantom: PhantomData<F>,
}

impl<F: Float + Debug + ScalarOperand + FromPrimitive + NumAssign + Send + Sync>
    AutoMixedPrecision<F>
{
    /// Create a new AMP wrapper
    pub fn new(config: MixedPrecisionConfig) -> Result<Self> {
        config.validate()?;

        let scaler = if config.enabled {
            Some(GradScaler::new(config.clone())?)
        } else {
            None
        };

        let master_weights = if config.enabled {
            Some(MasterWeights::new(config.precision_mode))
        } else {
            None
        };

        Ok(Self {
            config,
            scaler,
            master_weights,
            context_state: Arc::new(RwLock::new(AmpContextState::Normal)),
            active: AtomicBool::new(false),
            _phantom: PhantomData,
        })
    }

    /// Check if AMP is enabled
    pub fn is_enabled(&self) -> bool {
        self.config.enabled
    }

    /// Enter forward pass context
    pub fn enter_forward(&self) -> Result<()> {
        if !self.config.enabled {
            return Ok(());
        }

        let mut state = self
            .context_state
            .write()
            .unwrap_or_else(|e| e.into_inner());
        *state = AmpContextState::Forward;
        self.active.store(true, Ordering::SeqCst);
        Ok(())
    }

    /// Exit forward pass context
    pub fn exit_forward(&self) -> Result<()> {
        if !self.config.enabled {
            return Ok(());
        }

        let mut state = self
            .context_state
            .write()
            .unwrap_or_else(|e| e.into_inner());
        *state = AmpContextState::Normal;
        Ok(())
    }

    /// Enter backward pass context
    pub fn enter_backward(&self) -> Result<()> {
        if !self.config.enabled {
            return Ok(());
        }

        let mut state = self
            .context_state
            .write()
            .unwrap_or_else(|e| e.into_inner());
        *state = AmpContextState::Backward;
        Ok(())
    }

    /// Exit backward pass context
    pub fn exit_backward(&self) -> Result<()> {
        if !self.config.enabled {
            return Ok(());
        }

        let mut state = self
            .context_state
            .write()
            .unwrap_or_else(|e| e.into_inner());
        *state = AmpContextState::Normal;
        Ok(())
    }

    /// Get current context state
    pub fn context_state(&self) -> AmpContextState {
        *self.context_state.read().unwrap_or_else(|e| e.into_inner())
    }

    /// Scale loss for backward pass
    pub fn scale_loss(&self, loss: F) -> Result<F> {
        match &self.scaler {
            Some(scaler) => scaler.scale_loss(loss),
            None => Ok(loss),
        }
    }

    /// Unscale and check gradients
    pub fn unscale_gradients(&self, gradients: &mut [ArrayD<F>]) -> Result<bool> {
        match &self.scaler {
            Some(scaler) => scaler.unscale_gradients(gradients),
            None => Ok(false),
        }
    }

    /// Update scaler after step
    pub fn update_scaler(&self) -> Result<bool> {
        match &self.scaler {
            Some(scaler) => scaler.update(),
            None => Ok(false),
        }
    }

    /// Get current loss scale
    pub fn get_loss_scale(&self) -> f64 {
        self.scaler.as_ref().map_or(1.0, |s| s.get_scale())
    }

    /// Register model weights for master weight management
    pub fn register_weights(&mut self, name: &str, weights: ArrayD<F>) -> Result<()> {
        if let Some(ref mut mw) = self.master_weights {
            mw.register(name, weights)?;
        }
        Ok(())
    }

    /// Get scaler statistics
    pub fn get_scaler_stats(&self) -> Option<GradScalerStats> {
        self.scaler.as_ref().map(|s| s.get_stats())
    }

    /// Reset the AMP state
    pub fn reset(&mut self) {
        if let Some(ref scaler) = self.scaler {
            scaler.reset();
        }
        if let Some(ref mut mw) = self.master_weights {
            *mw = MasterWeights::new(self.config.precision_mode);
        }
        self.active.store(false, Ordering::SeqCst);
        let mut state = self
            .context_state
            .write()
            .unwrap_or_else(|e| e.into_inner());
        *state = AmpContextState::Normal;
    }

    /// Convert tensor to computation precision (FP16)
    pub fn to_compute_precision(&self, tensor: &ArrayD<F>) -> Result<ArrayD<u16>> {
        let fp16_data: Vec<u16> = tensor
            .iter()
            .map(|&x| {
                let f32_val = x.to_f64().unwrap_or(0.0) as f32;
                Half::from_f32(f32_val).to_bits()
            })
            .collect();

        ArrayD::from_shape_vec(IxDyn(tensor.shape()), fp16_data)
            .map_err(|e| NeuralError::ShapeMismatch(format!("Precision conversion failed: {}", e)))
    }

    /// Convert tensor from computation precision (FP16) to FP32
    pub fn from_compute_precision(&self, tensor: &ArrayD<u16>) -> Result<ArrayD<F>> {
        let fp32_data: Vec<F> = tensor
            .iter()
            .map(|&bits| {
                let f32_val = Half::from_bits(bits).to_f32();
                F::from(f32_val).unwrap_or_else(F::zero)
            })
            .collect();

        ArrayD::from_shape_vec(IxDyn(tensor.shape()), fp32_data)
            .map_err(|e| NeuralError::ShapeMismatch(format!("Precision conversion failed: {}", e)))
    }
}

// ============================================================================
// Mixed Precision Trainer
// ============================================================================

/// Training step result
#[derive(Debug, Clone)]
pub struct MixedPrecisionStepResult<F: Float + Debug + NumAssign> {
    /// Scaled loss (before unscaling)
    pub scaled_loss: F,
    /// Unscaled loss (actual loss value)
    pub unscaled_loss: F,
    /// Whether overflow was detected
    pub overflow_detected: bool,
    /// Whether this step was skipped due to overflow
    pub step_skipped: bool,
    /// Current loss scale
    pub loss_scale: f64,
    /// Gradient norm (after unscaling and clipping)
    pub grad_norm: Option<f64>,
}

/// Mixed precision trainer for complete training loop management
#[derive(Debug)]
pub struct MixedPrecisionTrainer<F: Float + Debug + ScalarOperand + FromPrimitive + NumAssign> {
    /// Configuration
    config: MixedPrecisionConfig,
    /// AMP wrapper
    amp: AutoMixedPrecision<F>,
    /// Total training steps
    total_steps: AtomicU64,
    /// Skipped steps due to overflow
    skipped_steps: AtomicU64,
    /// Whether currently training
    training: AtomicBool,
}

impl<F: Float + Debug + ScalarOperand + FromPrimitive + NumAssign + Send + Sync>
    MixedPrecisionTrainer<F>
{
    /// Create a new mixed precision trainer
    pub fn new(config: MixedPrecisionConfig) -> Result<Self> {
        let amp = AutoMixedPrecision::new(config.clone())?;

        Ok(Self {
            config,
            amp,
            total_steps: AtomicU64::new(0),
            skipped_steps: AtomicU64::new(0),
            training: AtomicBool::new(false),
        })
    }

    /// Check if mixed precision is enabled
    pub fn is_enabled(&self) -> bool {
        self.config.enabled
    }

    /// Start training mode
    pub fn train(&self) {
        self.training.store(true, Ordering::SeqCst);
    }

    /// Stop training mode
    pub fn eval(&self) {
        self.training.store(false, Ordering::SeqCst);
    }

    /// Is in training mode
    pub fn is_training(&self) -> bool {
        self.training.load(Ordering::SeqCst)
    }

    /// Perform a forward pass with mixed precision
    pub fn forward<L: Layer<F>>(&self, model: &L, input: &ArrayD<F>) -> Result<ArrayD<F>> {
        self.amp.enter_forward()?;
        let result = model.forward(input);
        self.amp.exit_forward()?;
        result
    }

    /// Scale loss for backward pass
    pub fn scale_loss(&self, loss: F) -> Result<F> {
        self.amp.scale_loss(loss)
    }

    /// Perform a complete training step
    ///
    /// This method handles:
    /// 1. Loss scaling
    /// 2. Gradient unscaling
    /// 3. Overflow detection
    /// 4. Dynamic scale adjustment
    pub fn training_step<L: Layer<F>>(
        &self,
        model: &mut L,
        input: &ArrayD<F>,
        target: &ArrayD<F>,
        loss_fn: impl Fn(&ArrayD<F>, &ArrayD<F>) -> Result<F>,
        optimizer_step: impl FnOnce(&mut L, F) -> Result<()>,
    ) -> Result<MixedPrecisionStepResult<F>> {
        self.total_steps.fetch_add(1, Ordering::SeqCst);

        // Forward pass
        self.amp.enter_forward()?;
        let output = model.forward(input)?;
        self.amp.exit_forward()?;

        // Compute loss
        let unscaled_loss = loss_fn(&output, target)?;

        // Scale loss if enabled
        let scaled_loss = self.amp.scale_loss(unscaled_loss)?;

        // Backward pass
        self.amp.enter_backward()?;

        // Get gradients from model
        let mut gradients = model.gradients();

        // Unscale gradients
        let overflow_detected = self.amp.unscale_gradients(&mut gradients)?;

        // Apply clipped gradients back to model
        model.set_gradients(&gradients)?;

        self.amp.exit_backward()?;

        // Update scaler and check if step should be skipped
        let step_skipped = self.amp.update_scaler()?;

        if step_skipped {
            self.skipped_steps.fetch_add(1, Ordering::SeqCst);
        } else {
            // Perform optimizer step
            let lr = F::from(0.001).unwrap_or_else(F::zero); // Default LR, should be passed in
            optimizer_step(model, lr)?;
        }

        Ok(MixedPrecisionStepResult {
            scaled_loss,
            unscaled_loss,
            overflow_detected,
            step_skipped,
            loss_scale: self.amp.get_loss_scale(),
            grad_norm: None,
        })
    }

    /// Get training statistics
    pub fn get_stats(&self) -> TrainingStats {
        let scaler_stats = self.amp.get_scaler_stats();
        TrainingStats {
            total_steps: self.total_steps.load(Ordering::SeqCst),
            skipped_steps: self.skipped_steps.load(Ordering::SeqCst),
            current_loss_scale: self.amp.get_loss_scale(),
            scaler_stats,
        }
    }

    /// Reset training statistics
    pub fn reset_stats(&mut self) {
        self.total_steps.store(0, Ordering::SeqCst);
        self.skipped_steps.store(0, Ordering::SeqCst);
        self.amp.reset();
    }

    /// Get the AMP wrapper
    pub fn amp(&self) -> &AutoMixedPrecision<F> {
        &self.amp
    }

    /// Get mutable AMP wrapper
    pub fn amp_mut(&mut self) -> &mut AutoMixedPrecision<F> {
        &mut self.amp
    }

    /// Get configuration
    pub fn config(&self) -> &MixedPrecisionConfig {
        &self.config
    }
}

/// Training statistics
#[derive(Debug, Clone)]
pub struct TrainingStats {
    /// Total number of training steps
    pub total_steps: u64,
    /// Number of skipped steps due to overflow
    pub skipped_steps: u64,
    /// Current loss scale
    pub current_loss_scale: f64,
    /// Detailed scaler statistics
    pub scaler_stats: Option<GradScalerStats>,
}

// ============================================================================
// Mixed Precision Callback
// ============================================================================

use crate::callbacks::{Callback, CallbackContext, CallbackTiming};

/// Callback for mixed precision training integration
#[derive(Debug)]
pub struct MixedPrecisionCallback<
    F: Float + Debug + ScalarOperand + FromPrimitive + NumAssign + Send + Sync,
> {
    /// Configuration
    config: MixedPrecisionConfig,
    /// Gradient scaler
    scaler: GradScaler,
    /// Last recorded loss scale
    last_loss_scale: f64,
    /// Number of overflows in current epoch
    epoch_overflows: usize,
    /// Phantom
    _phantom: PhantomData<F>,
}

impl<F: Float + Debug + ScalarOperand + FromPrimitive + NumAssign + Send + Sync>
    MixedPrecisionCallback<F>
{
    /// Create a new mixed precision callback
    pub fn new(config: MixedPrecisionConfig) -> Result<Self> {
        let scaler = GradScaler::new(config.clone())?;
        let initial_scale = config.initial_loss_scale;

        Ok(Self {
            config,
            scaler,
            last_loss_scale: initial_scale,
            epoch_overflows: 0,
            _phantom: PhantomData,
        })
    }

    /// Get the gradient scaler
    pub fn scaler(&self) -> &GradScaler {
        &self.scaler
    }

    /// Get the current loss scale
    pub fn loss_scale(&self) -> f64 {
        self.scaler.get_scale()
    }

    /// Get statistics
    pub fn get_stats(&self) -> GradScalerStats {
        self.scaler.get_stats()
    }
}

impl<
        F: Float + Debug + ScalarOperand + FromPrimitive + NumAssign + std::fmt::Display + Send + Sync,
    > Callback<F> for MixedPrecisionCallback<F>
{
    fn on_event(&mut self, timing: CallbackTiming, context: &mut CallbackContext<F>) -> Result<()> {
        if !self.config.enabled {
            return Ok(());
        }

        match timing {
            CallbackTiming::BeforeEpoch => {
                self.epoch_overflows = 0;
                self.last_loss_scale = self.scaler.get_scale();
            }
            CallbackTiming::AfterBatch => {
                // Check if model gradients have overflow
                if let Some(model) = context.model.as_mut() {
                    let mut gradients = model.gradients();
                    let overflow = self.scaler.unscale_gradients(&mut gradients)?;

                    if overflow {
                        self.epoch_overflows += 1;
                    }

                    // Update scaler
                    let _skipped = self.scaler.update()?;

                    // Apply clipped gradients back if no overflow
                    if !overflow {
                        model.set_gradients(&gradients)?;
                    }
                }
            }
            CallbackTiming::AfterEpoch if self.config.log_statistics => {
                let stats = self.scaler.get_stats();
                eprintln!(
                    "[MixedPrecision] Epoch {} - Scale: {:.2}, Overflows: {}, Total skipped: {}",
                    context.epoch, stats.loss_scale, self.epoch_overflows, stats.overflow_steps
                );
            }
            _ => {}
        }

        Ok(())
    }
}

// ============================================================================
// Utility Functions
// ============================================================================

/// Check if a tensor contains inf or nan values
pub fn contains_inf_or_nan<F: Float + Debug + NumAssign>(tensor: &ArrayD<F>) -> bool {
    tensor.iter().any(|x| {
        let val = x.to_f64().unwrap_or(f64::NAN);
        !val.is_finite()
    })
}

/// Compute the L2 norm of a tensor
pub fn tensor_norm<F: Float + Debug + NumAssign>(tensor: &ArrayD<F>) -> f64 {
    let sum_sq: f64 = tensor
        .iter()
        .map(|x| {
            let val = x.to_f64().unwrap_or(0.0);
            val * val
        })
        .sum();
    sum_sq.sqrt()
}

/// Compute the global norm across multiple tensors
pub fn global_norm<F: Float + Debug + NumAssign>(tensors: &[ArrayD<F>]) -> f64 {
    let sum_sq: f64 = tensors
        .iter()
        .flat_map(|t| t.iter())
        .map(|x| {
            let val = x.to_f64().unwrap_or(0.0);
            val * val
        })
        .sum();
    sum_sq.sqrt()
}

/// Clip tensor values by maximum absolute value
pub fn clip_by_value<F: Float + Debug + ScalarOperand + FromPrimitive + NumAssign>(
    tensor: &mut ArrayD<F>,
    max_value: f64,
) -> Result<()> {
    let max_f = F::from(max_value)
        .ok_or_else(|| NeuralError::ComputationError("Failed to convert max value".to_string()))?;
    let min_f = F::from(-max_value)
        .ok_or_else(|| NeuralError::ComputationError("Failed to convert min value".to_string()))?;

    for val in tensor.iter_mut() {
        if *val > max_f {
            *val = max_f;
        } else if *val < min_f {
            *val = min_f;
        }
    }

    Ok(())
}

/// Clip tensors by global norm
pub fn clip_by_global_norm<F: Float + Debug + ScalarOperand + FromPrimitive + NumAssign>(
    tensors: &mut [ArrayD<F>],
    max_norm: f64,
) -> Result<f64> {
    let current_norm = global_norm(tensors);

    if current_norm > max_norm {
        let scale = F::from(max_norm / current_norm).ok_or_else(|| {
            NeuralError::ComputationError("Failed to compute clip scale".to_string())
        })?;

        for tensor in tensors.iter_mut() {
            for val in tensor.iter_mut() {
                *val *= scale;
            }
        }
    }

    Ok(current_norm)
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_mixed_precision_config_builder() {
        let config = MixedPrecisionConfig::builder()
            .enabled(true)
            .initial_loss_scale(1024.0)
            .growth_factor(2.0)
            .backoff_factor(0.5)
            .growth_interval(100)
            .build()
            .expect("Config build should succeed");

        assert!(config.enabled);
        assert!((config.initial_loss_scale - 1024.0).abs() < 1e-10);
        assert!((config.growth_factor - 2.0).abs() < 1e-10);
        assert!((config.backoff_factor - 0.5).abs() < 1e-10);
        assert_eq!(config.growth_interval, 100);
    }

    #[test]
    fn test_config_validation() {
        // Invalid initial scale
        let result = MixedPrecisionConfig::builder()
            .initial_loss_scale(-1.0)
            .build();
        assert!(result.is_err());

        // Invalid growth factor
        let result = MixedPrecisionConfig::builder().growth_factor(0.5).build();
        assert!(result.is_err());

        // Invalid backoff factor
        let result = MixedPrecisionConfig::builder().backoff_factor(1.5).build();
        assert!(result.is_err());
    }

    #[test]
    fn test_half_precision_conversion() {
        // Test positive values
        let val = 1.5_f32;
        let half = Half::from_f32(val);
        let back = half.to_f32();
        assert!((val - back).abs() < 0.01);

        // Test negative values
        let val = -std::f32::consts::PI;
        let half = Half::from_f32(val);
        let back = half.to_f32();
        assert!((val - back).abs() < 0.01);

        // Test zero
        let half = Half::from_f32(0.0);
        assert!(half.is_zero());

        // Test infinity
        let half = Half::from_f32(f32::INFINITY);
        assert!(half.is_infinite());

        // Test NaN
        let half = Half::from_f32(f32::NAN);
        assert!(half.is_nan());
    }

    #[test]
    fn test_grad_scaler_creation() {
        let config = MixedPrecisionConfig::builder()
            .enabled(true)
            .initial_loss_scale(65536.0)
            .build()
            .expect("Config should be valid");

        let scaler = GradScaler::new(config).expect("Scaler creation should succeed");
        assert!((scaler.get_scale() - 65536.0).abs() < 1e-10);
    }

    #[test]
    fn test_grad_scaler_scale_loss() {
        let config = MixedPrecisionConfig::builder()
            .enabled(true)
            .initial_loss_scale(1024.0)
            .build()
            .expect("Config should be valid");

        let scaler = GradScaler::new(config).expect("Scaler creation should succeed");

        let loss = 0.5_f64;
        let scaled = scaler.scale_loss(loss).expect("Scale should succeed");
        assert!((scaled - 512.0).abs() < 1e-10);
    }

    #[test]
    fn test_grad_scaler_unscale() {
        let config = MixedPrecisionConfig::builder()
            .enabled(true)
            .initial_loss_scale(1024.0)
            .build()
            .expect("Config should be valid");

        let scaler = GradScaler::new(config).expect("Scaler creation should succeed");

        let mut gradients =
            vec![
                Array::from_shape_vec(vec![2, 2], vec![1024.0_f64, 2048.0, 512.0, 256.0])
                    .expect("Array creation should succeed")
                    .into_dyn(),
            ];

        let overflow = scaler
            .unscale_gradients(&mut gradients)
            .expect("Unscale should succeed");
        assert!(!overflow);

        // Check that gradients are unscaled
        assert!((gradients[0][[0, 0]] - 1.0).abs() < 1e-10);
        assert!((gradients[0][[0, 1]] - 2.0).abs() < 1e-10);
    }

    #[test]
    fn test_grad_scaler_overflow_detection() {
        let config = MixedPrecisionConfig::builder()
            .enabled(true)
            .initial_loss_scale(1024.0)
            .build()
            .expect("Config should be valid");

        let scaler = GradScaler::new(config).expect("Scaler creation should succeed");

        let mut gradients = vec![Array::from_shape_vec(vec![2], vec![f64::INFINITY, 1.0])
            .expect("Array creation should succeed")
            .into_dyn()];

        let overflow = scaler
            .unscale_gradients(&mut gradients)
            .expect("Unscale should succeed");
        assert!(overflow);
    }

    #[test]
    fn test_grad_scaler_update_no_overflow() {
        let config = MixedPrecisionConfig::builder()
            .enabled(true)
            .initial_loss_scale(1024.0)
            .growth_interval(2)
            .growth_factor(2.0)
            .build()
            .expect("Config should be valid");

        let scaler = GradScaler::new(config).expect("Scaler creation should succeed");

        // Two successful steps should trigger scale increase
        let skipped = scaler.update().expect("Update should succeed");
        assert!(!skipped);

        let skipped = scaler.update().expect("Update should succeed");
        assert!(!skipped);

        // Scale should have doubled
        assert!((scaler.get_scale() - 2048.0).abs() < 1e-10);
    }

    #[test]
    fn test_grad_scaler_update_with_overflow() {
        let config = MixedPrecisionConfig::builder()
            .enabled(true)
            .initial_loss_scale(1024.0)
            .backoff_factor(0.5)
            .build()
            .expect("Config should be valid");

        let scaler = GradScaler::new(config).expect("Scaler creation should succeed");

        // Simulate overflow
        let mut gradients = vec![Array::from_shape_vec(vec![1], vec![f64::INFINITY])
            .expect("Array creation should succeed")
            .into_dyn()];
        scaler
            .unscale_gradients(&mut gradients)
            .expect("Unscale should succeed");

        let skipped = scaler.update().expect("Update should succeed");
        assert!(skipped);

        // Scale should have halved
        assert!((scaler.get_scale() - 512.0).abs() < 1e-10);
    }

    #[test]
    fn test_mixed_precision_tensor() {
        let data: ArrayD<f64> = Array::from_shape_vec(vec![2, 2], vec![1.0, 2.0, 3.0, 4.0])
            .expect("Array creation should succeed")
            .into_dyn();

        let mut tensor = MixedPrecisionTensor::from_fp32(data);
        assert_eq!(tensor.precision(), PrecisionMode::FP32);

        tensor.to_fp16().expect("FP16 conversion should succeed");
        assert_eq!(tensor.precision(), PrecisionMode::FP16Mixed);

        tensor.to_fp32().expect("FP32 conversion should succeed");
        assert_eq!(tensor.precision(), PrecisionMode::FP32);

        let fp32 = tensor.get_fp32().expect("Get FP32 should succeed");
        assert!((fp32[[0, 0]] - 1.0).abs() < 0.01);
    }

    #[test]
    fn test_master_weights() {
        let mut weights: MasterWeights<f64> = MasterWeights::new(PrecisionMode::FP16Mixed);

        let w1: ArrayD<f64> = Array::from_shape_vec(vec![3, 2], vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
            .expect("Array creation should succeed")
            .into_dyn();

        weights
            .register("layer1", w1)
            .expect("Register should succeed");
        assert!(weights.contains("layer1"));
        assert_eq!(weights.len(), 1);

        let master = weights.get_master_weights("layer1");
        assert!(master.is_some());

        let compute = weights.get_compute_weights("layer1");
        assert!(compute.is_some());
    }

    #[test]
    fn test_auto_mixed_precision() {
        let config = MixedPrecisionConfig::builder()
            .enabled(true)
            .initial_loss_scale(1024.0)
            .build()
            .expect("Config should be valid");

        let amp: AutoMixedPrecision<f64> =
            AutoMixedPrecision::new(config).expect("AMP creation should succeed");

        assert!(amp.is_enabled());
        assert_eq!(amp.context_state(), AmpContextState::Normal);

        amp.enter_forward().expect("Enter forward should succeed");
        assert_eq!(amp.context_state(), AmpContextState::Forward);

        amp.exit_forward().expect("Exit forward should succeed");
        assert_eq!(amp.context_state(), AmpContextState::Normal);
    }

    #[test]
    fn test_mixed_precision_trainer_creation() {
        let config = MixedPrecisionConfig::builder()
            .enabled(true)
            .build()
            .expect("Config should be valid");

        let trainer: MixedPrecisionTrainer<f64> =
            MixedPrecisionTrainer::new(config).expect("Trainer creation should succeed");

        assert!(trainer.is_enabled());
        assert!(!trainer.is_training());

        trainer.train();
        assert!(trainer.is_training());

        trainer.eval();
        assert!(!trainer.is_training());
    }

    #[test]
    fn test_utility_functions() {
        // Test contains_inf_or_nan
        let normal: ArrayD<f64> = Array::from_shape_vec(vec![2], vec![1.0, 2.0])
            .expect("Array creation should succeed")
            .into_dyn();
        assert!(!contains_inf_or_nan(&normal));

        let with_nan: ArrayD<f64> = Array::from_shape_vec(vec![2], vec![1.0, f64::NAN])
            .expect("Array creation should succeed")
            .into_dyn();
        assert!(contains_inf_or_nan(&with_nan));

        // Test tensor_norm
        let t: ArrayD<f64> = Array::from_shape_vec(vec![2], vec![3.0, 4.0])
            .expect("Array creation should succeed")
            .into_dyn();
        assert!((tensor_norm(&t) - 5.0).abs() < 1e-10);

        // Test global_norm
        let t1: ArrayD<f64> = Array::from_shape_vec(vec![2], vec![1.0, 2.0])
            .expect("Array creation should succeed")
            .into_dyn();
        let t2: ArrayD<f64> = Array::from_shape_vec(vec![2], vec![2.0, 0.0])
            .expect("Array creation should succeed")
            .into_dyn();
        let norm = global_norm(&[t1, t2]);
        assert!((norm - 3.0).abs() < 1e-10);
    }

    #[test]
    fn test_clip_by_value() {
        let mut tensor: ArrayD<f64> = Array::from_shape_vec(vec![4], vec![-5.0, -1.0, 1.0, 5.0])
            .expect("Array creation should succeed")
            .into_dyn();

        clip_by_value(&mut tensor, 2.0).expect("Clip should succeed");

        assert!((tensor[[0]] - (-2.0)).abs() < 1e-10);
        assert!((tensor[[1]] - (-1.0)).abs() < 1e-10);
        assert!((tensor[[2]] - 1.0).abs() < 1e-10);
        assert!((tensor[[3]] - 2.0).abs() < 1e-10);
    }

    #[test]
    fn test_clip_by_global_norm() {
        let mut tensors = vec![Array::from_shape_vec(vec![2], vec![3.0, 4.0])
            .expect("Array creation should succeed")
            .into_dyn()];

        let original_norm = clip_by_global_norm(&mut tensors, 2.5).expect("Clip should succeed");
        assert!((original_norm - 5.0).abs() < 1e-10);

        // Check that norm is now approximately 2.5
        let new_norm = global_norm(&tensors);
        assert!((new_norm - 2.5).abs() < 1e-10);
    }

    #[test]
    fn test_fp32_operation_check() {
        let config = MixedPrecisionConfig::default();

        assert!(config.should_use_fp32(FP32Operation::LossComputation));
        assert!(config.should_use_fp32(FP32Operation::Softmax));
        assert!(config.should_use_fp32(FP32Operation::LayerNorm));
        assert!(!config.should_use_fp32(FP32Operation::Embedding)); // Not in default list
    }

    #[test]
    fn test_grad_scaler_reset() {
        let config = MixedPrecisionConfig::builder()
            .enabled(true)
            .initial_loss_scale(1024.0)
            .backoff_factor(0.5)
            .build()
            .expect("Config should be valid");

        let scaler = GradScaler::new(config).expect("Scaler creation should succeed");

        // Simulate overflow and scale reduction
        let mut gradients = vec![Array::from_shape_vec(vec![1], vec![f64::INFINITY])
            .expect("Array creation should succeed")
            .into_dyn()];
        scaler
            .unscale_gradients(&mut gradients)
            .expect("Unscale should succeed");
        scaler.update().expect("Update should succeed");

        assert!((scaler.get_scale() - 512.0).abs() < 1e-10);

        // Reset
        scaler.reset();
        assert!((scaler.get_scale() - 1024.0).abs() < 1e-10);
    }
}