torsh-nn 0.1.2

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

pub mod parameter_ext;

pub use parameter_ext::{
    ParameterAnalysis, ParameterCollectionExt, ParameterConstraint, ParameterExt, ParameterGroup,
};

use crate::init::Initializer;
use parking_lot::RwLock;
use std::sync::Arc;
use torsh_core::device::DeviceType;
use torsh_core::error::Result;
use torsh_tensor::Tensor;

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

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

/// Parameter wrapper for trainable tensors
#[derive(Clone, Debug)]
pub struct Parameter {
    data: Arc<RwLock<Tensor>>,
    requires_grad: bool,
}

impl Parameter {
    /// Create a new parameter
    pub fn new(tensor: Tensor) -> Self {
        Self {
            data: Arc::new(RwLock::new(tensor)),
            requires_grad: true,
        }
    }

    /// Create a parameter that doesn't require gradients
    pub fn new_no_grad(tensor: Tensor) -> Self {
        Self {
            data: Arc::new(RwLock::new(tensor)),
            requires_grad: false,
        }
    }

    /// Get the underlying tensor
    pub fn tensor(&self) -> Arc<RwLock<Tensor>> {
        self.data.clone()
    }

    /// Create a parameter from an existing tensor Arc
    pub fn from_tensor(tensor: Arc<RwLock<Tensor>>) -> Self {
        Self {
            data: tensor,
            requires_grad: true,
        }
    }

    /// Set whether this parameter requires gradients
    pub fn requires_grad_(mut self, requires_grad: bool) -> Self {
        self.requires_grad = requires_grad;
        // Note: torsh_tensor doesn't support requires_grad yet
        // This will be implemented when autograd is available
        self
    }

    /// Check if parameter requires gradients
    pub fn requires_grad(&self) -> bool {
        self.requires_grad
    }

    /// Get parameter shape
    pub fn shape(&self) -> Result<Vec<usize>> {
        Ok(self.data.read().shape().dims().to_vec())
    }

    /// Get parameter size (number of elements)
    pub fn numel(&self) -> Result<usize> {
        Ok(self.data.read().shape().numel())
    }

    /// Move parameter to device
    pub fn to_device(&mut self, device: DeviceType) -> Result<()> {
        // This would move the tensor to the specified device
        // For now, just update the device field when tensor supports it
        let _ = device; // Suppress warning
        Ok(())
    }

    /// Zero the parameter gradients
    pub fn zero_grad(&mut self) {
        // This would zero gradients when autograd is available
        // For now, this is a placeholder
    }

    /// Clone the parameter data
    pub fn clone_data(&self) -> Tensor {
        self.data.read().clone()
    }
}

/// Enhanced parameter management utilities
impl Parameter {
    /// Create parameter with specific initialization function
    ///
    /// This is the most flexible parameter creation method, allowing custom
    /// initialization logic.
    pub fn with_init<F>(shape: Vec<usize>, _device: DeviceType, init_fn: F) -> Result<Self>
    where
        F: FnOnce(Vec<usize>) -> Result<Tensor>,
    {
        let tensor = init_fn(shape)?;
        Ok(Self::new(tensor))
    }

    /// Create parameter from existing data
    ///
    /// Convenient method to create a parameter from a vector of data.
    pub fn from_data(data: Vec<f32>, shape: Vec<usize>) -> Result<Self> {
        let tensor = torsh_tensor::Tensor::from_vec(data, &shape)?;
        Ok(Self::new(tensor))
    }

    /// Create parameter with automatic shape inference
    ///
    /// Creates a parameter where the shape is inferred from the provided data.
    pub fn from_data_auto_shape(data: Vec<f32>) -> Result<Self> {
        let shape = vec![data.len()];
        Self::from_data(data, shape)
    }

    /// Create parameter with random initialization and automatic fan calculation
    ///
    /// This method automatically chooses the best initialization based on the layer type.
    pub fn auto_init(shape: Vec<usize>, device: DeviceType, layer_type: LayerType) -> Result<Self> {
        use crate::init::InitMethod;

        let init_method = match layer_type {
            LayerType::Linear | LayerType::Dense => InitMethod::KaimingUniform {
                mode: crate::init::FanMode::FanIn,
                nonlinearity: crate::init::Nonlinearity::Linear,
            },
            LayerType::Conv => InitMethod::KaimingUniform {
                mode: crate::init::FanMode::FanOut,
                nonlinearity: crate::init::Nonlinearity::ReLU,
            },
            LayerType::RNN | LayerType::LSTM | LayerType::GRU => {
                InitMethod::XavierUniform { gain: 1.0 }
            }
            LayerType::Attention => InitMethod::XavierNormal { gain: 1.0 },
            LayerType::Embedding => InitMethod::Normal {
                mean: 0.0,
                std: 1.0,
            },
            LayerType::Bias => InitMethod::Constant { value: 0.0 },
            LayerType::BatchNorm => InitMethod::Constant { value: 1.0 },
            LayerType::Custom => InitMethod::KaimingUniform {
                mode: crate::init::FanMode::FanIn,
                nonlinearity: crate::init::Nonlinearity::ReLU,
            },
        };

        Self::with_init_method(shape, device, init_method)
    }

    /// Create parameter filled with zeros
    pub fn zeros(shape: Vec<usize>, _device: DeviceType) -> Result<Self> {
        use torsh_tensor::creation::zeros;
        let tensor = zeros(&shape)?;
        Ok(Self::new(tensor))
    }

    /// Create parameter filled with ones
    pub fn ones(shape: Vec<usize>, _device: DeviceType) -> Result<Self> {
        use torsh_tensor::creation::ones;
        let tensor = ones(&shape)?;
        Ok(Self::new(tensor))
    }

    /// Create parameter using InitMethod enum
    pub fn with_init_method(
        shape: Vec<usize>,
        _device: DeviceType,
        method: crate::init::InitMethod,
    ) -> Result<Self> {
        let tensor = method.initialize(&shape)?;
        Ok(Self::new(tensor))
    }

    /// Create parameter with uniform random initialization
    pub fn uniform(shape: Vec<usize>, device: DeviceType, low: f32, high: f32) -> Result<Self> {
        use crate::init::InitMethod;
        Self::with_init_method(shape, device, InitMethod::Uniform { low, high })
    }

    /// Create parameter with normal random initialization
    pub fn normal(shape: Vec<usize>, device: DeviceType, mean: f32, std: f32) -> Result<Self> {
        use crate::init::InitMethod;
        Self::with_init_method(shape, device, InitMethod::Normal { mean, std })
    }

    /// Create parameter with Xavier/Glorot uniform initialization
    pub fn xavier_uniform(shape: Vec<usize>, device: DeviceType, gain: f32) -> Result<Self> {
        use crate::init::InitMethod;
        Self::with_init_method(shape, device, InitMethod::XavierUniform { gain })
    }

    /// Create parameter with Xavier/Glorot normal initialization
    pub fn xavier_normal(shape: Vec<usize>, device: DeviceType, gain: f32) -> Result<Self> {
        use crate::init::InitMethod;
        Self::with_init_method(shape, device, InitMethod::XavierNormal { gain })
    }

    /// Create parameter with Kaiming/He uniform initialization
    pub fn kaiming_uniform(
        shape: Vec<usize>,
        device: DeviceType,
        nonlinearity: &str,
    ) -> Result<Self> {
        use crate::init::{FanMode, InitMethod, Nonlinearity};
        let nl = match nonlinearity {
            "relu" => Nonlinearity::ReLU,
            "leaky_relu" => Nonlinearity::LeakyReLU {
                negative_slope: 0.01,
            },
            "tanh" => Nonlinearity::Tanh,
            "sigmoid" => Nonlinearity::Sigmoid,
            "selu" => Nonlinearity::SELU,
            "elu" => Nonlinearity::ELU,
            "swish" => Nonlinearity::Swish,
            "linear" => Nonlinearity::Linear,
            _ => Nonlinearity::Linear,
        };
        Self::with_init_method(
            shape,
            device,
            InitMethod::KaimingUniform {
                mode: FanMode::FanIn,
                nonlinearity: nl,
            },
        )
    }

    /// Create parameter with Kaiming/He normal initialization
    pub fn kaiming_normal(
        shape: Vec<usize>,
        device: DeviceType,
        nonlinearity: &str,
    ) -> Result<Self> {
        use crate::init::{FanMode, InitMethod, Nonlinearity};
        let nl = match nonlinearity {
            "relu" => Nonlinearity::ReLU,
            "leaky_relu" => Nonlinearity::LeakyReLU {
                negative_slope: 0.01,
            },
            "tanh" => Nonlinearity::Tanh,
            "sigmoid" => Nonlinearity::Sigmoid,
            "selu" => Nonlinearity::SELU,
            "elu" => Nonlinearity::ELU,
            "swish" => Nonlinearity::Swish,
            "linear" => Nonlinearity::Linear,
            _ => Nonlinearity::Linear,
        };
        Self::with_init_method(
            shape,
            device,
            InitMethod::KaimingNormal {
                mode: FanMode::FanIn,
                nonlinearity: nl,
            },
        )
    }

    /// Create parameter with constant value
    pub fn constant(shape: Vec<usize>, device: DeviceType, value: f32) -> Result<Self> {
        use crate::init::InitMethod;
        Self::with_init_method(shape, device, InitMethod::Constant { value })
    }

    /// Create parameter with orthogonal initialization
    pub fn orthogonal(shape: Vec<usize>, device: DeviceType, gain: f32) -> Result<Self> {
        use crate::init::InitMethod;
        Self::with_init_method(shape, device, InitMethod::Orthogonal { gain })
    }

    /// Create parameter with sparse initialization
    pub fn sparse(shape: Vec<usize>, device: DeviceType, sparsity: f32, std: f32) -> Result<Self> {
        use crate::init::InitMethod;
        Self::with_init_method(shape, device, InitMethod::Sparse { sparsity, std })
    }

    /// Create parameter with Lecun uniform initialization
    pub fn lecun_uniform(shape: Vec<usize>, device: DeviceType) -> Result<Self> {
        use crate::init::InitMethod;
        Self::with_init_method(shape, device, InitMethod::LecunUniform)
    }

    /// Create parameter with Lecun normal initialization
    pub fn lecun_normal(shape: Vec<usize>, device: DeviceType) -> Result<Self> {
        use crate::init::InitMethod;
        Self::with_init_method(shape, device, InitMethod::LecunNormal)
    }

    /// Create parameter with truncated normal initialization
    pub fn truncated_normal(
        shape: Vec<usize>,
        device: DeviceType,
        mean: f32,
        std: f32,
        a: f32,
        b: f32,
    ) -> Result<Self> {
        use crate::init::InitMethod;
        Self::with_init_method(
            shape,
            device,
            InitMethod::TruncatedNormal { mean, std, a, b },
        )
    }

    /// Create parameter with eye/identity initialization
    pub fn eye(shape: Vec<usize>, device: DeviceType) -> Result<Self> {
        use crate::init::InitMethod;
        Self::with_init_method(shape, device, InitMethod::Eye)
    }

    /// Get parameter statistics
    pub fn stats(&self) -> Result<ParameterStats> {
        let tensor = self.data.read();
        let data = tensor.to_vec()?;

        if data.is_empty() {
            return Ok(ParameterStats {
                mean: 0.0,
                std: 0.0,
                variance: 0.0,
                min: 0.0,
                max: 0.0,
                numel: 0,
                median: 0.0,
                q25: 0.0,
                q75: 0.0,
                skewness: 0.0,
                kurtosis: 0.0,
            });
        }

        let mean = data.iter().sum::<f32>() / data.len() as f32;
        let variance = data.iter().map(|x| (x - mean).powi(2)).sum::<f32>() / data.len() as f32;
        let std = variance.sqrt();
        let min = data.iter().copied().fold(f32::INFINITY, f32::min);
        let max = data.iter().copied().fold(f32::NEG_INFINITY, f32::max);

        // Calculate additional statistics
        let mut sorted_data = data.clone();
        sorted_data.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));

        let median = if sorted_data.len() % 2 == 0 {
            (sorted_data[sorted_data.len() / 2 - 1] + sorted_data[sorted_data.len() / 2]) / 2.0
        } else {
            sorted_data[sorted_data.len() / 2]
        };

        let q25_idx = sorted_data.len() / 4;
        let q75_idx = 3 * sorted_data.len() / 4;
        let q25 = sorted_data.get(q25_idx).copied().unwrap_or(min);
        let q75 = sorted_data.get(q75_idx).copied().unwrap_or(max);

        // Basic skewness and kurtosis calculations
        let n = data.len() as f32;
        let skewness = if std > 0.0 {
            data.iter().map(|x| ((x - mean) / std).powi(3)).sum::<f32>() / n
        } else {
            0.0
        };

        let kurtosis = if std > 0.0 {
            data.iter().map(|x| ((x - mean) / std).powi(4)).sum::<f32>() / n - 3.0
        } else {
            0.0
        };

        Ok(ParameterStats {
            mean,
            std,
            variance,
            min,
            max,
            numel: data.len(),
            median,
            q25,
            q75,
            skewness,
            kurtosis,
        })
    }

    /// Check if parameter has finite values (no NaN or infinity)
    pub fn is_finite(&self) -> Result<bool> {
        let tensor = self.data.read();
        let data = tensor.to_vec()?;
        Ok(data.iter().all(|x| x.is_finite()))
    }

    /// Reinitialize parameter with a new method
    pub fn reinitialize(&mut self, method: crate::init::InitMethod) -> Result<()> {
        let current_shape = self.shape()?;
        let new_tensor = method.initialize(&current_shape)?;
        *self.data.write() = new_tensor;
        Ok(())
    }

    /// Get parameter norm (L2 norm)
    pub fn norm(&self) -> Result<f32> {
        let tensor = self.data.read();
        let data = tensor.to_vec()?;
        let norm = data.iter().map(|x| x * x).sum::<f32>().sqrt();
        Ok(norm)
    }

    /// Get parameter L1 norm
    pub fn l1_norm(&self) -> Result<f32> {
        let tensor = self.data.read();
        let data = tensor.to_vec()?;
        let norm = data.iter().map(|x| x.abs()).sum::<f32>();
        Ok(norm)
    }

    /// Get parameter L-infinity norm (max absolute value)
    pub fn linf_norm(&self) -> Result<f32> {
        let tensor = self.data.read();
        let data = tensor.to_vec()?;
        let norm = data.iter().map(|x| x.abs()).fold(0.0f32, f32::max);
        Ok(norm)
    }

    /// Clamp parameter values to a range
    pub fn clamp(&mut self, min: f32, max: f32) -> Result<()> {
        let mut tensor = self.data.write();
        let data = tensor.to_vec()?;
        let clamped_data: Vec<f32> = data.iter().map(|&x| x.clamp(min, max)).collect();
        let shape = tensor.shape().dims().to_vec();
        *tensor = torsh_tensor::Tensor::from_vec(clamped_data, &shape)?;
        Ok(())
    }

    /// Apply a function to all parameter values
    pub fn apply_fn<F>(&mut self, f: F) -> Result<()>
    where
        F: Fn(f32) -> f32,
    {
        let mut tensor = self.data.write();
        let data = tensor.to_vec()?;
        let transformed_data: Vec<f32> = data.iter().map(|&x| f(x)).collect();
        let shape = tensor.shape().dims().to_vec();
        *tensor = torsh_tensor::Tensor::from_vec(transformed_data, &shape)?;
        Ok(())
    }

    /// Scale parameter by a factor
    pub fn scale(&mut self, factor: f32) -> Result<()> {
        self.apply_fn(|x| x * factor)
    }

    /// Add noise to parameter
    pub fn add_noise(&mut self, std: f32) -> Result<()> {
        use scirs2_core::random::thread_rng;
        let mut rng = thread_rng();
        let mut tensor = self.data.write();
        let data = tensor.to_vec()?;
        let noisy_data: Vec<f32> = data
            .iter()
            .map(|&x| x + rng.random::<f32>() * std)
            .collect();
        let shape = tensor.shape().dims().to_vec();
        *tensor = torsh_tensor::Tensor::from_vec(noisy_data, &shape)?;
        Ok(())
    }

    /// Get parameter histogram for analysis
    pub fn histogram(&self, bins: usize) -> Result<Vec<(f32, usize)>> {
        let tensor = self.data.read();
        let data = tensor.to_vec()?;

        if data.is_empty() {
            return Ok(Vec::new());
        }

        let min_val = data.iter().copied().fold(f32::INFINITY, f32::min);
        let max_val = data.iter().copied().fold(f32::NEG_INFINITY, f32::max);

        if min_val == max_val {
            return Ok(vec![(min_val, data.len())]);
        }

        let bin_width = (max_val - min_val) / bins as f32;
        let mut histogram = vec![0; bins];

        for &value in &data {
            let bin_index = ((value - min_val) / bin_width).floor() as usize;
            let bin_index = bin_index.min(bins - 1);
            histogram[bin_index] += 1;
        }

        let result: Vec<(f32, usize)> = histogram
            .into_iter()
            .enumerate()
            .map(|(i, count)| (min_val + (i as f32 + 0.5) * bin_width, count))
            .collect();

        Ok(result)
    }

    /// Check for common parameter issues
    pub fn diagnose(&self) -> Result<ParameterDiagnostics> {
        let stats = self.stats()?;
        let mut issues = Vec::new();
        let mut warnings = Vec::new();

        // Check for NaN or infinite values
        if !self.is_finite()? {
            issues.push("Parameter contains NaN or infinite values".to_string());
        }

        // Check for suspicious statistics
        if stats.std < 1e-6 {
            warnings
                .push("Very low standard deviation - parameters may be too uniform".to_string());
        }

        if stats.std > 10.0 {
            warnings.push("Very high standard deviation - parameters may be unstable".to_string());
        }

        if stats.mean.abs() > 5.0 {
            warnings
                .push("High mean absolute value - parameters may be poorly centered".to_string());
        }

        // Check gradient-related issues
        let norm = self.norm()?;
        if norm < 1e-8 {
            warnings
                .push("Very small parameter norm - may indicate vanishing gradients".to_string());
        } else if norm > 100.0 {
            warnings
                .push("Very large parameter norm - may indicate exploding gradients".to_string());
        }

        Ok(ParameterDiagnostics {
            stats,
            issues,
            warnings,
            norm,
            is_finite: self.is_finite()?,
        })
    }
}

/// Layer type enumeration for automatic parameter initialization
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LayerType {
    Linear,
    Dense,
    Conv,
    RNN,
    LSTM,
    GRU,
    Attention,
    Embedding,
    Bias,
    BatchNorm,
    Custom,
}

/// Parameter statistics for analysis and debugging
#[derive(Debug, Clone)]
pub struct ParameterStats {
    pub mean: f32,
    pub std: f32,
    pub variance: f32,
    pub min: f32,
    pub max: f32,
    pub numel: usize,
    pub median: f32,
    pub q25: f32,
    pub q75: f32,
    pub skewness: f32,
    pub kurtosis: f32,
}

impl ParameterStats {
    /// Create parameter statistics from data
    pub fn from_data(data: &[f32]) -> Self {
        if data.is_empty() {
            return Self::empty();
        }

        let n = data.len() as f32;
        let mean = data.iter().sum::<f32>() / n;
        let variance = data.iter().map(|x| (x - mean).powi(2)).sum::<f32>() / n;
        let std = variance.sqrt();

        let mut sorted_data = data.to_vec();
        sorted_data.sort_by(|a, b| {
            a.partial_cmp(b)
                .expect("data comparison should not involve NaN")
        });

        let min = sorted_data[0];
        let max = sorted_data[sorted_data.len() - 1];
        let median = Self::percentile(&sorted_data, 0.5);
        let q25 = Self::percentile(&sorted_data, 0.25);
        let q75 = Self::percentile(&sorted_data, 0.75);

        // Calculate skewness and kurtosis
        let std_cubed = std.powi(3);
        let std_fourth = std.powi(4);

        let skewness = if std_cubed > 0.0 {
            data.iter().map(|x| ((x - mean) / std).powi(3)).sum::<f32>() / n
        } else {
            0.0
        };

        let kurtosis = if std_fourth > 0.0 {
            data.iter().map(|x| ((x - mean) / std).powi(4)).sum::<f32>() / n - 3.0
        } else {
            0.0
        };

        Self {
            mean,
            std,
            variance,
            min,
            max,
            numel: data.len(),
            median,
            q25,
            q75,
            skewness,
            kurtosis,
        }
    }

    /// Create empty statistics
    pub fn empty() -> Self {
        Self {
            mean: 0.0,
            std: 0.0,
            variance: 0.0,
            min: 0.0,
            max: 0.0,
            numel: 0,
            median: 0.0,
            q25: 0.0,
            q75: 0.0,
            skewness: 0.0,
            kurtosis: 0.0,
        }
    }

    /// Calculate percentile from sorted data
    fn percentile(sorted_data: &[f32], p: f32) -> f32 {
        if sorted_data.is_empty() {
            return 0.0;
        }

        let index = p * (sorted_data.len() - 1) as f32;
        let lower = index.floor() as usize;
        let upper = index.ceil() as usize;

        if lower == upper {
            sorted_data[lower]
        } else {
            let weight = index - lower as f32;
            sorted_data[lower] * (1.0 - weight) + sorted_data[upper] * weight
        }
    }

    /// Get interquartile range
    pub fn iqr(&self) -> f32 {
        self.q75 - self.q25
    }

    /// Check if distribution appears normal
    pub fn is_approximately_normal(&self) -> bool {
        // Simple heuristic: check if skewness and kurtosis are reasonable
        self.skewness.abs() < 1.0 && self.kurtosis.abs() < 3.0
    }
}

impl core::fmt::Display for ParameterStats {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "ParameterStats(mean={:.4}, std={:.4}, min={:.4}, max={:.4}, numel={})",
            self.mean, self.std, self.min, self.max, self.numel
        )
    }
}

/// Parameter diagnostics for debugging and analysis
#[derive(Debug, Clone)]
pub struct ParameterDiagnostics {
    pub stats: ParameterStats,
    pub issues: Vec<String>,
    pub warnings: Vec<String>,
    pub norm: f32,
    pub is_finite: bool,
}

impl core::fmt::Display for ParameterDiagnostics {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        writeln!(f, "Parameter Diagnostics:")?;
        writeln!(f, "  {}", self.stats)?;
        writeln!(f, "  Norm: {:.6}", self.norm)?;
        writeln!(f, "  Finite: {}", self.is_finite)?;

        if !self.issues.is_empty() {
            writeln!(f, "  Issues:")?;
            for issue in &self.issues {
                writeln!(f, "    - {issue}")?;
            }
        }

        if !self.warnings.is_empty() {
            writeln!(f, "  Warnings:")?;
            for warning in &self.warnings {
                writeln!(f, "    - {warning}")?;
            }
        }

        Ok(())
    }
}

/// Parameter collection utility for managing multiple parameters
///
/// This provides convenient methods for working with collections of parameters,
/// such as applying operations to all parameters in a module.
#[derive(Debug, Clone)]
pub struct ParameterCollection {
    parameters: HashMap<String, Parameter>,
}

impl ParameterCollection {
    /// Create a new parameter collection
    pub fn new() -> Self {
        Self {
            parameters: HashMap::new(),
        }
    }

    /// Create from a parameter map
    pub fn from_map(parameters: HashMap<String, Parameter>) -> Self {
        Self { parameters }
    }

    /// Add a parameter to the collection
    pub fn add(&mut self, name: String, parameter: Parameter) {
        self.parameters.insert(name, parameter);
    }

    /// Get a parameter by name
    pub fn get(&self, name: &str) -> Option<&Parameter> {
        self.parameters.get(name)
    }

    /// Get a mutable parameter by name
    pub fn get_mut(&mut self, name: &str) -> Option<&mut Parameter> {
        self.parameters.get_mut(name)
    }

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

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

    /// Check if the collection is empty
    pub fn is_empty(&self) -> bool {
        self.parameters.is_empty()
    }

    /// Apply a function to all parameters
    pub fn apply_to_all<F>(&mut self, mut f: F) -> Result<()>
    where
        F: FnMut(&mut Parameter) -> Result<()>,
    {
        for param in self.parameters.values_mut() {
            f(param)?;
        }
        Ok(())
    }

    /// Get statistics for all parameters
    pub fn stats(&self) -> Result<HashMap<String, ParameterStats>> {
        let mut stats = HashMap::new();
        for (name, param) in &self.parameters {
            stats.insert(name.clone(), param.stats()?);
        }
        Ok(stats)
    }

    /// Get diagnostics for all parameters
    pub fn diagnose(&self) -> Result<HashMap<String, ParameterDiagnostics>> {
        let mut diagnostics = HashMap::new();
        for (name, param) in &self.parameters {
            diagnostics.insert(name.clone(), param.diagnose()?);
        }
        Ok(diagnostics)
    }

    /// Get total parameter count
    pub fn total_parameters(&self) -> usize {
        self.parameters
            .values()
            .map(|p| p.numel().unwrap_or(0))
            .sum()
    }

    /// Get total memory usage
    pub fn total_memory_usage(&self) -> usize {
        self.parameters
            .values()
            .map(|p| p.numel().unwrap_or(0) * 4) // Assume f32
            .sum()
    }

    /// Freeze all parameters
    pub fn freeze_all(&mut self) {
        for param in self.parameters.values_mut() {
            param.requires_grad = false;
        }
    }

    /// Unfreeze all parameters
    pub fn unfreeze_all(&mut self) {
        for param in self.parameters.values_mut() {
            param.requires_grad = true;
        }
    }

    /// Scale all parameters by a factor
    pub fn scale_all(&mut self, factor: f32) -> Result<()> {
        self.apply_to_all(|param| param.scale(factor))
    }

    /// Clamp all parameters to a range
    pub fn clamp_all(&mut self, min: f32, max: f32) -> Result<()> {
        self.apply_to_all(|param| param.clamp(min, max))
    }

    /// Add noise to all parameters
    pub fn add_noise_all(&mut self, std: f32) -> Result<()> {
        self.apply_to_all(|param| param.add_noise(std))
    }

    /// Filter parameters by name pattern
    pub fn filter_by_name(&self, pattern: &str) -> ParameterCollection {
        let filtered: HashMap<String, Parameter> = self
            .parameters
            .iter()
            .filter(|(name, _)| name.contains(pattern))
            .map(|(name, param)| (name.clone(), param.clone()))
            .collect();
        ParameterCollection::from_map(filtered)
    }

    /// Filter parameters by predicate
    pub fn filter_by<F>(&self, predicate: F) -> ParameterCollection
    where
        F: Fn(&String, &Parameter) -> bool,
    {
        let filtered: HashMap<String, Parameter> = self
            .parameters
            .iter()
            .filter(|(name, param)| predicate(name, param))
            .map(|(name, param)| (name.clone(), param.clone()))
            .collect();
        ParameterCollection::from_map(filtered)
    }

    /// Create a summary report of all parameters
    pub fn summary_report(&self) -> Result<String> {
        let mut report = String::new();
        report.push_str("Parameter Collection Summary\n");
        report.push_str(&format!("Total parameters: {}\n", self.len()));
        report.push_str(&format!("Total elements: {}\n", self.total_parameters()));
        report.push_str(&format!(
            "Memory usage: {:.2} MB\n",
            self.total_memory_usage() as f64 / (1024.0 * 1024.0)
        ));
        report.push_str("\nParameter Details:\n");

        for (name, param) in &self.parameters {
            let stats = param.stats()?;
            report.push_str(&format!(
                "  {}: {} elements, mean={:.4}, std={:.4}\n",
                name, stats.numel, stats.mean, stats.std
            ));
        }

        Ok(report)
    }
}

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

impl From<HashMap<String, Parameter>> for ParameterCollection {
    fn from(parameters: HashMap<String, Parameter>) -> Self {
        Self::from_map(parameters)
    }
}

impl From<ParameterCollection> for HashMap<String, Parameter> {
    fn from(val: ParameterCollection) -> Self {
        val.parameters
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_relative_eq;
    use torsh_core::device::DeviceType;
    use torsh_tensor::creation::zeros;

    // ========================================================================
    // Parameter Creation Tests
    // ========================================================================

    #[test]
    fn test_parameter_new() -> Result<()> {
        let tensor = zeros(&[3, 4])?;
        let param = Parameter::new(tensor);

        assert!(param.requires_grad());
        assert_eq!(param.shape()?, vec![3, 4]);
        assert_eq!(param.numel()?, 12);
        Ok(())
    }

    #[test]
    fn test_parameter_new_no_grad() -> Result<()> {
        let tensor = zeros(&[2, 3])?;
        let param = Parameter::new_no_grad(tensor);

        assert!(!param.requires_grad());
        assert_eq!(param.shape()?, vec![2, 3]);
        Ok(())
    }

    #[test]
    fn test_parameter_from_tensor() -> Result<()> {
        let tensor = zeros(&[5])?;
        let arc_tensor = Arc::new(RwLock::new(tensor));
        let param = Parameter::from_tensor(arc_tensor);

        assert!(param.requires_grad());
        assert_eq!(param.shape()?, vec![5]);
        Ok(())
    }

    #[test]
    fn test_parameter_requires_grad_setter() -> Result<()> {
        let tensor = zeros(&[2, 2])?;
        let param = Parameter::new(tensor).requires_grad_(false);

        assert!(!param.requires_grad());
        Ok(())
    }

    #[test]
    fn test_parameter_from_data() -> Result<()> {
        let data = vec![1.0, 2.0, 3.0, 4.0];
        let param = Parameter::from_data(data.clone(), vec![2, 2])?;

        assert_eq!(param.shape()?, vec![2, 2]);
        assert_eq!(param.numel()?, 4);

        let tensor_data = param.clone_data().to_vec()?;
        assert_eq!(tensor_data, data);
        Ok(())
    }

    #[test]
    fn test_parameter_from_data_auto_shape() -> Result<()> {
        let data = vec![1.0, 2.0, 3.0];
        let param = Parameter::from_data_auto_shape(data.clone())?;

        assert_eq!(param.shape()?, vec![3]);
        assert_eq!(param.numel()?, 3);
        Ok(())
    }

    // ========================================================================
    // Parameter Initialization Tests
    // ========================================================================

    #[test]
    fn test_parameter_zeros() -> Result<()> {
        let param = Parameter::zeros(vec![2, 3], DeviceType::Cpu)?;
        let data = param.clone_data().to_vec()?;

        assert_eq!(param.numel()?, 6);
        assert!(data.iter().all(|&x| x == 0.0));
        Ok(())
    }

    #[test]
    fn test_parameter_ones() -> Result<()> {
        let param = Parameter::ones(vec![3, 2], DeviceType::Cpu)?;
        let data = param.clone_data().to_vec()?;

        assert_eq!(param.numel()?, 6);
        assert!(data.iter().all(|&x| x == 1.0));
        Ok(())
    }

    #[test]
    fn test_parameter_constant() -> Result<()> {
        let param = Parameter::constant(vec![2, 2], DeviceType::Cpu, 5.0)?;
        let data = param.clone_data().to_vec()?;

        assert!(data.iter().all(|&x| (x - 5.0).abs() < 1e-6));
        Ok(())
    }

    #[test]
    fn test_parameter_uniform() -> Result<()> {
        let param = Parameter::uniform(vec![100], DeviceType::Cpu, -1.0, 1.0)?;
        let data = param.clone_data().to_vec()?;

        // Check all values are in range
        assert!(data.iter().all(|&x| x >= -1.0 && x <= 1.0));

        // Check distribution statistics
        let mean = data.iter().sum::<f32>() / data.len() as f32;
        assert!(mean.abs() < 0.2); // Should be close to 0
        Ok(())
    }

    #[test]
    fn test_parameter_normal() -> Result<()> {
        let param = Parameter::normal(vec![1000], DeviceType::Cpu, 0.0, 1.0)?;
        let data = param.clone_data().to_vec()?;

        let mean = data.iter().sum::<f32>() / data.len() as f32;
        let variance = data.iter().map(|x| (x - mean).powi(2)).sum::<f32>() / data.len() as f32;

        // Normal distribution should have mean ≈ 0 and variance ≈ 1
        assert!(mean.abs() < 0.1);
        assert!((variance - 1.0).abs() < 0.2);
        Ok(())
    }

    #[test]
    fn test_parameter_xavier_uniform() -> Result<()> {
        let shape = vec![100, 50];
        let param = Parameter::xavier_uniform(shape.clone(), DeviceType::Cpu, 1.0)?;

        assert_eq!(param.shape()?, shape);
        assert!(param.is_finite()?);
        Ok(())
    }

    #[test]
    fn test_parameter_xavier_normal() -> Result<()> {
        let shape = vec![50, 100];
        let param = Parameter::xavier_normal(shape.clone(), DeviceType::Cpu, 1.0)?;

        assert_eq!(param.shape()?, shape);
        assert!(param.is_finite()?);
        Ok(())
    }

    #[test]
    fn test_parameter_kaiming_uniform() -> Result<()> {
        let shape = vec![64, 32];
        let param = Parameter::kaiming_uniform(shape.clone(), DeviceType::Cpu, "relu")?;

        assert_eq!(param.shape()?, shape);
        assert!(param.is_finite()?);
        Ok(())
    }

    #[test]
    fn test_parameter_kaiming_normal() -> Result<()> {
        let shape = vec![32, 64];
        let param = Parameter::kaiming_normal(shape.clone(), DeviceType::Cpu, "relu")?;

        assert_eq!(param.shape()?, shape);
        assert!(param.is_finite()?);
        Ok(())
    }

    #[test]
    fn test_parameter_lecun_uniform() -> Result<()> {
        let shape = vec![50, 50];
        let param = Parameter::lecun_uniform(shape.clone(), DeviceType::Cpu)?;

        assert_eq!(param.shape()?, shape);
        assert!(param.is_finite()?);
        Ok(())
    }

    #[test]
    fn test_parameter_lecun_normal() -> Result<()> {
        let shape = vec![50, 50];
        let param = Parameter::lecun_normal(shape.clone(), DeviceType::Cpu)?;

        assert_eq!(param.shape()?, shape);
        assert!(param.is_finite()?);
        Ok(())
    }

    #[test]
    fn test_parameter_truncated_normal() -> Result<()> {
        let param = Parameter::truncated_normal(vec![100], DeviceType::Cpu, 0.0, 1.0, -2.0, 2.0)?;

        let data = param.clone_data().to_vec()?;
        // All values should be within truncation bounds
        assert!(data.iter().all(|&x| x >= -2.0 && x <= 2.0));
        Ok(())
    }

    #[test]
    fn test_parameter_eye() -> Result<()> {
        let param = Parameter::eye(vec![3, 3], DeviceType::Cpu)?;
        let data = param.clone_data().to_vec()?;

        // Check diagonal elements are 1
        assert_relative_eq!(data[0], 1.0, epsilon = 1e-6); // [0,0]
        assert_relative_eq!(data[4], 1.0, epsilon = 1e-6); // [1,1]
        assert_relative_eq!(data[8], 1.0, epsilon = 1e-6); // [2,2]

        // Check off-diagonal elements are 0
        assert_relative_eq!(data[1], 0.0, epsilon = 1e-6);
        assert_relative_eq!(data[2], 0.0, epsilon = 1e-6);
        Ok(())
    }

    #[test]
    fn test_parameter_auto_init_linear() -> Result<()> {
        let param = Parameter::auto_init(vec![10, 5], DeviceType::Cpu, LayerType::Linear)?;

        assert_eq!(param.shape()?, vec![10, 5]);
        assert!(param.is_finite()?);
        Ok(())
    }

    #[test]
    fn test_parameter_auto_init_conv() -> Result<()> {
        let param = Parameter::auto_init(vec![3, 3, 32, 64], DeviceType::Cpu, LayerType::Conv)?;

        assert_eq!(param.shape()?, vec![3, 3, 32, 64]);
        assert!(param.is_finite()?);
        Ok(())
    }

    #[test]
    fn test_parameter_auto_init_embedding() -> Result<()> {
        let param = Parameter::auto_init(vec![1000, 128], DeviceType::Cpu, LayerType::Embedding)?;

        assert_eq!(param.shape()?, vec![1000, 128]);
        assert!(param.is_finite()?);
        Ok(())
    }

    // ========================================================================
    // Parameter Statistics Tests
    // ========================================================================

    #[test]
    fn test_parameter_stats() -> Result<()> {
        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let param = Parameter::from_data(data, vec![5])?;
        let stats = param.stats()?;

        assert_relative_eq!(stats.mean, 3.0, epsilon = 1e-5);
        assert_relative_eq!(stats.min, 1.0, epsilon = 1e-5);
        assert_relative_eq!(stats.max, 5.0, epsilon = 1e-5);
        assert_eq!(stats.numel, 5);
        assert_relative_eq!(stats.median, 3.0, epsilon = 1e-5);
        Ok(())
    }

    #[test]
    fn test_parameter_stats_empty() -> Result<()> {
        let param: Parameter = Parameter::from_data(vec![], vec![0])?;
        let stats = param.stats()?;

        assert_eq!(stats.numel, 0);
        assert_eq!(stats.mean, 0.0);
        assert_eq!(stats.std, 0.0);
        Ok(())
    }

    #[test]
    fn test_parameter_norm_l2() -> Result<()> {
        let data = vec![3.0, 4.0]; // 3^2 + 4^2 = 25, sqrt = 5
        let param = Parameter::from_data(data, vec![2])?;
        let norm = param.norm()?;

        assert_relative_eq!(norm, 5.0, epsilon = 1e-5);
        Ok(())
    }

    #[test]
    fn test_parameter_norm_l1() -> Result<()> {
        let data = vec![3.0, -4.0, 5.0]; // |3| + |-4| + |5| = 12
        let param = Parameter::from_data(data, vec![3])?;
        let norm = param.l1_norm()?;

        assert_relative_eq!(norm, 12.0, epsilon = 1e-5);
        Ok(())
    }

    #[test]
    fn test_parameter_norm_linf() -> Result<()> {
        let data = vec![1.0, -5.0, 3.0]; // max(|1|, |-5|, |3|) = 5
        let param = Parameter::from_data(data, vec![3])?;
        let norm = param.linf_norm()?;

        assert_relative_eq!(norm, 5.0, epsilon = 1e-5);
        Ok(())
    }

    // ========================================================================
    // Parameter Operations Tests
    // ========================================================================

    #[test]
    fn test_parameter_clamp() -> Result<()> {
        let data = vec![-5.0, 0.0, 5.0, 10.0];
        let mut param = Parameter::from_data(data, vec![4])?;

        param.clamp(0.0, 5.0)?;

        let clamped = param.clone_data().to_vec()?;
        assert_relative_eq!(clamped[0], 0.0, epsilon = 1e-5); // -5 clamped to 0
        assert_relative_eq!(clamped[1], 0.0, epsilon = 1e-5);
        assert_relative_eq!(clamped[2], 5.0, epsilon = 1e-5);
        assert_relative_eq!(clamped[3], 5.0, epsilon = 1e-5); // 10 clamped to 5
        Ok(())
    }

    #[test]
    fn test_parameter_scale() -> Result<()> {
        let data = vec![1.0, 2.0, 3.0];
        let mut param = Parameter::from_data(data, vec![3])?;

        param.scale(2.0)?;

        let scaled = param.clone_data().to_vec()?;
        assert_relative_eq!(scaled[0], 2.0, epsilon = 1e-5);
        assert_relative_eq!(scaled[1], 4.0, epsilon = 1e-5);
        assert_relative_eq!(scaled[2], 6.0, epsilon = 1e-5);
        Ok(())
    }

    #[test]
    fn test_parameter_apply_fn() -> Result<()> {
        let data = vec![1.0, 2.0, 3.0];
        let mut param = Parameter::from_data(data, vec![3])?;

        param.apply_fn(|x| x * x)?; // Square each element

        let result = param.clone_data().to_vec()?;
        assert_relative_eq!(result[0], 1.0, epsilon = 1e-5);
        assert_relative_eq!(result[1], 4.0, epsilon = 1e-5);
        assert_relative_eq!(result[2], 9.0, epsilon = 1e-5);
        Ok(())
    }

    #[test]
    fn test_parameter_add_noise() -> Result<()> {
        let data = vec![0.0; 100];
        let mut param = Parameter::from_data(data, vec![100])?;

        param.add_noise(0.1)?;

        let noisy = param.clone_data().to_vec()?;
        // After adding noise, values should no longer all be 0
        let all_zero = noisy.iter().all(|&x| x == 0.0);
        assert!(!all_zero);
        Ok(())
    }

    #[test]
    fn test_parameter_is_finite() -> Result<()> {
        let data = vec![1.0, 2.0, 3.0];
        let param = Parameter::from_data(data, vec![3])?;

        assert!(param.is_finite()?);
        Ok(())
    }

    #[test]
    fn test_parameter_reinitialize() -> Result<()> {
        let mut param = Parameter::zeros(vec![5], DeviceType::Cpu)?;

        use crate::init::InitMethod;
        param.reinitialize(InitMethod::Constant { value: 7.0 })?;

        let data = param.clone_data().to_vec()?;
        assert!(data.iter().all(|&x| (x - 7.0).abs() < 1e-6));
        Ok(())
    }

    #[test]
    fn test_parameter_histogram() -> Result<()> {
        let data: Vec<f32> = (0..100).map(|i| i as f32).collect();
        let param = Parameter::from_data(data, vec![100])?;

        let histogram = param.histogram(10)?;

        assert_eq!(histogram.len(), 10);
        // Each bin should have roughly 10 elements
        for (_, count) in histogram {
            assert!(count >= 9 && count <= 11);
        }
        Ok(())
    }

    #[test]
    fn test_parameter_histogram_constant() -> Result<()> {
        let data = vec![5.0; 10];
        let param = Parameter::from_data(data, vec![10])?;

        let histogram = param.histogram(5)?;

        // All values are the same, should return single bin
        assert_eq!(histogram.len(), 1);
        assert_eq!(histogram[0].1, 10);
        Ok(())
    }

    #[test]
    fn test_parameter_diagnose_normal() -> Result<()> {
        let data = vec![1.0, 2.0, 3.0, 4.0];
        let param = Parameter::from_data(data, vec![4])?;

        let diagnostics = param.diagnose()?;

        assert!(diagnostics.is_finite);
        assert!(diagnostics.issues.is_empty());
        assert_eq!(diagnostics.stats.numel, 4);
        Ok(())
    }

    // ========================================================================
    // ParameterStats Tests
    // ========================================================================

    #[test]
    fn test_parameter_stats_from_data() {
        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let stats = ParameterStats::from_data(&data);

        assert_relative_eq!(stats.mean, 3.0, epsilon = 1e-5);
        assert_relative_eq!(stats.median, 3.0, epsilon = 1e-5);
        assert_relative_eq!(stats.min, 1.0, epsilon = 1e-5);
        assert_relative_eq!(stats.max, 5.0, epsilon = 1e-5);
        assert_eq!(stats.numel, 5);
    }

    #[test]
    fn test_parameter_stats_empty_constructor() {
        let stats = ParameterStats::empty();

        assert_eq!(stats.mean, 0.0);
        assert_eq!(stats.std, 0.0);
        assert_eq!(stats.numel, 0);
    }

    #[test]
    fn test_parameter_stats_iqr() {
        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let stats = ParameterStats::from_data(&data);

        let iqr = stats.iqr();
        assert!(iqr > 0.0);
    }

    #[test]
    fn test_parameter_stats_is_approximately_normal() {
        // Create approximately normal data
        let data: Vec<f32> = vec![-1.0, -0.5, 0.0, 0.5, 1.0, -0.3, 0.3, -0.8, 0.8, -0.2, 0.2];
        let stats = ParameterStats::from_data(&data);

        // This is a simple heuristic check
        assert!(stats.skewness.abs() < 2.0); // Not too skewed
    }

    // ========================================================================
    // ParameterCollection Tests
    // ========================================================================

    #[test]
    fn test_parameter_collection_new() {
        let collection = ParameterCollection::new();

        assert_eq!(collection.len(), 0);
        assert!(collection.is_empty());
    }

    #[test]
    fn test_parameter_collection_add_get() -> Result<()> {
        let mut collection = ParameterCollection::new();

        let param = Parameter::zeros(vec![3, 4], DeviceType::Cpu)?;
        collection.add("weight".to_string(), param);

        assert_eq!(collection.len(), 1);
        assert!(collection.get("weight").is_some());
        assert!(collection.get("bias").is_none());
        Ok(())
    }

    #[test]
    fn test_parameter_collection_names() -> Result<()> {
        let mut collection = ParameterCollection::new();

        collection.add(
            "weight".to_string(),
            Parameter::zeros(vec![2, 2], DeviceType::Cpu)?,
        );
        collection.add(
            "bias".to_string(),
            Parameter::zeros(vec![2], DeviceType::Cpu)?,
        );

        let names = collection.names();
        assert_eq!(names.len(), 2);
        assert!(names.contains(&&"weight".to_string()));
        assert!(names.contains(&&"bias".to_string()));
        Ok(())
    }

    #[test]
    fn test_parameter_collection_total_parameters() -> Result<()> {
        let mut collection = ParameterCollection::new();

        collection.add(
            "weight".to_string(),
            Parameter::zeros(vec![2, 3], DeviceType::Cpu)?,
        ); // 6 params
        collection.add(
            "bias".to_string(),
            Parameter::zeros(vec![3], DeviceType::Cpu)?,
        ); // 3 params

        assert_eq!(collection.total_parameters(), 9);
        Ok(())
    }

    #[test]
    fn test_parameter_collection_total_memory_usage() -> Result<()> {
        let mut collection = ParameterCollection::new();

        collection.add(
            "weight".to_string(),
            Parameter::zeros(vec![10], DeviceType::Cpu)?,
        );

        let memory = collection.total_memory_usage();
        assert_eq!(memory, 10 * 4); // 10 f32 elements * 4 bytes
        Ok(())
    }

    #[test]
    fn test_parameter_collection_freeze_unfreeze() -> Result<()> {
        let mut collection = ParameterCollection::new();

        let param = Parameter::zeros(vec![2], DeviceType::Cpu)?;
        collection.add("weight".to_string(), param);

        collection.freeze_all();
        assert!(!collection
            .get("weight")
            .expect("element retrieval should succeed for valid index")
            .requires_grad());

        collection.unfreeze_all();
        assert!(collection
            .get("weight")
            .expect("element retrieval should succeed for valid index")
            .requires_grad());
        Ok(())
    }

    #[test]
    fn test_parameter_collection_scale_all() -> Result<()> {
        let mut collection = ParameterCollection::new();

        let param = Parameter::ones(vec![3], DeviceType::Cpu)?;
        collection.add("weight".to_string(), param);

        collection.scale_all(2.0)?;

        let weight = collection
            .get("weight")
            .expect("element retrieval should succeed for valid index");
        let data = weight.clone_data().to_vec()?;
        assert!(data.iter().all(|&x| (x - 2.0).abs() < 1e-5));
        Ok(())
    }

    #[test]
    fn test_parameter_collection_clamp_all() -> Result<()> {
        let mut collection = ParameterCollection::new();

        let data = vec![-5.0, 0.0, 5.0];
        let param = Parameter::from_data(data, vec![3])?;
        collection.add("weight".to_string(), param);

        collection.clamp_all(-1.0, 1.0)?;

        let weight = collection
            .get("weight")
            .expect("element retrieval should succeed for valid index");
        let clamped = weight.clone_data().to_vec()?;
        assert!(clamped.iter().all(|&x| x >= -1.0 && x <= 1.0));
        Ok(())
    }

    #[test]
    fn test_parameter_collection_filter_by_name() -> Result<()> {
        let mut collection = ParameterCollection::new();

        collection.add(
            "layer1.weight".to_string(),
            Parameter::zeros(vec![2], DeviceType::Cpu)?,
        );
        collection.add(
            "layer1.bias".to_string(),
            Parameter::zeros(vec![2], DeviceType::Cpu)?,
        );
        collection.add(
            "layer2.weight".to_string(),
            Parameter::zeros(vec![2], DeviceType::Cpu)?,
        );

        let filtered = collection.filter_by_name("layer1");
        assert_eq!(filtered.len(), 2);

        let filtered_weight = collection.filter_by_name("weight");
        assert_eq!(filtered_weight.len(), 2);
        Ok(())
    }

    #[test]
    fn test_parameter_collection_filter_by_predicate() -> Result<()> {
        let mut collection = ParameterCollection::new();

        collection.add(
            "weight".to_string(),
            Parameter::zeros(vec![10], DeviceType::Cpu)?,
        );
        collection.add(
            "bias".to_string(),
            Parameter::zeros(vec![5], DeviceType::Cpu)?,
        );

        // Filter parameters with > 5 elements
        let filtered = collection.filter_by(|_, param| param.numel().unwrap_or(0) > 5);
        assert_eq!(filtered.len(), 1);
        assert!(filtered.get("weight").is_some());
        Ok(())
    }

    #[test]
    fn test_parameter_collection_stats() -> Result<()> {
        let mut collection = ParameterCollection::new();

        collection.add(
            "weight".to_string(),
            Parameter::ones(vec![5], DeviceType::Cpu)?,
        );

        let stats = collection.stats()?;
        assert_eq!(stats.len(), 1);

        let weight_stats = stats
            .get("weight")
            .expect("element retrieval should succeed for valid index");
        assert_relative_eq!(weight_stats.mean, 1.0, epsilon = 1e-5);
        Ok(())
    }

    #[test]
    fn test_parameter_collection_diagnose() -> Result<()> {
        let mut collection = ParameterCollection::new();

        collection.add(
            "weight".to_string(),
            Parameter::ones(vec![3], DeviceType::Cpu)?,
        );

        let diagnostics = collection.diagnose()?;
        assert_eq!(diagnostics.len(), 1);

        let weight_diag = diagnostics
            .get("weight")
            .expect("element retrieval should succeed for valid index");
        assert!(weight_diag.is_finite);
        Ok(())
    }

    #[test]
    fn test_parameter_collection_summary_report() -> Result<()> {
        let mut collection = ParameterCollection::new();

        collection.add(
            "weight".to_string(),
            Parameter::ones(vec![10], DeviceType::Cpu)?,
        );
        collection.add(
            "bias".to_string(),
            Parameter::zeros(vec![5], DeviceType::Cpu)?,
        );

        let report = collection.summary_report()?;

        assert!(report.contains("Total parameters: 2"));
        assert!(report.contains("Total elements: 15"));
        assert!(report.contains("weight"));
        assert!(report.contains("bias"));
        Ok(())
    }

    #[test]
    fn test_parameter_collection_from_hashmap() -> Result<()> {
        let mut map = HashMap::new();
        map.insert(
            "weight".to_string(),
            Parameter::zeros(vec![3], DeviceType::Cpu)?,
        );

        let collection = ParameterCollection::from_map(map);
        assert_eq!(collection.len(), 1);
        Ok(())
    }

    #[test]
    fn test_parameter_collection_into_hashmap() -> Result<()> {
        let mut collection = ParameterCollection::new();
        collection.add(
            "weight".to_string(),
            Parameter::zeros(vec![3], DeviceType::Cpu)?,
        );

        let map: HashMap<String, Parameter> = collection.into();
        assert_eq!(map.len(), 1);
        assert!(map.contains_key("weight"));
        Ok(())
    }
}