scirs2-core 0.6.5

Core utilities and common functionality for SciRS2 (scirs2-core)
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
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
// Copyright (c) 2025, `SciRS2` Team
//
// Licensed under the Apache License, Version 2.0
// (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
//

//! Neural network layers and models using the array protocol.
//!
//! This module provides neural network layers and models that work with
//! any array type implementing the ArrayProtocol trait.

use ::ndarray::{Array, Array1, Array4, ArrayD, Axis, Ix1, Ix2, Ix4, IxDyn, Zip};

use rand::{Rng, RngExt, SeedableRng};

use crate::array_protocol::ml_ops::ActivationFunc;
use crate::array_protocol::operations::OperationError;
use crate::array_protocol::{ArrayProtocol, NdarrayWrapper};

/// Gradients produced by a single layer's [`Layer::backward`] pass.
pub struct LayerGrad {
    /// Gradient of the loss with respect to this layer's input, to be
    /// passed as `grad_output` to the previous layer's `backward`.
    pub grad_input: Box<dyn ArrayProtocol>,

    /// Gradients of the loss with respect to each of this layer's
    /// parameters, in the same order as [`Layer::parameters`] /
    /// [`Layer::parameter_names`].
    pub grad_params: Vec<Box<dyn ArrayProtocol>>,
}

/// Trait for neural network layers.
pub trait Layer: Send + Sync {
    /// Forward pass through the layer.
    /// Get the layer type name for serialization.
    fn layer_type(&self) -> &str;

    fn forward(&self, inputs: &dyn ArrayProtocol)
        -> Result<Box<dyn ArrayProtocol>, OperationError>;

    /// Backward pass through the layer: given the layer's original `input`
    /// (as seen by the preceding `forward` call) and `grad_output` (the
    /// gradient of the loss with respect to this layer's output), compute
    /// the gradient with respect to the input and every parameter.
    ///
    /// `forward` does not cache any intermediate state, so implementations
    /// that need it (e.g. a pre-activation value) recompute it from `input`
    /// — cheap relative to the training pipeline's own forward pass, and it
    /// keeps `Layer` object-safe and side-effect-free.
    ///
    /// The default returns [`OperationError::NotImplemented`] so that
    /// existing third-party `Layer` implementations continue to compile;
    /// every layer defined in this module overrides it with a real
    /// implementation (or, where forward itself is already a documented
    /// simplification, an explicit and equally honest error).
    fn backward(
        &self,
        _input: &dyn ArrayProtocol,
        _grad_output: &dyn ArrayProtocol,
    ) -> Result<LayerGrad, OperationError> {
        Err(OperationError::NotImplemented(format!(
            "backward() is not implemented for layer type '{layertype}'",
            layertype = self.layer_type()
        )))
    }

    /// Get the layer's parameters.
    fn parameters(&self) -> Vec<Box<dyn ArrayProtocol>>;

    /// Get mutable references to the layer's parameters.
    fn parameters_mut(&mut self) -> Vec<&mut Box<dyn ArrayProtocol>>;

    /// Update a specific parameter by name
    fn update_parameter(
        &mut self,
        name: &str,
        value: Box<dyn ArrayProtocol>,
    ) -> Result<(), OperationError>;

    /// Get parameter names
    fn parameter_names(&self) -> Vec<String>;

    /// Set the layer to training mode.
    fn train(&mut self);

    /// Set the layer to evaluation mode.
    fn eval(&mut self);

    /// Check if the layer is in training mode.
    fn is_training(&self) -> bool;

    /// Get the layer's name.
    fn name(&self) -> &str;
}

/// Downcasts an `ArrayProtocol` object to an owned `f64` array, regardless
/// of its concrete (static or dynamic) dimensionality. Used internally by
/// `Layer::backward` implementations, which only need to do plain
/// elementwise/linear-algebra math on the underlying data.
fn as_f64_array(a: &dyn ArrayProtocol) -> Result<ArrayD<f64>, OperationError> {
    if let Some(w) = a.as_any().downcast_ref::<NdarrayWrapper<f64, IxDyn>>() {
        return Ok(w.as_array().clone());
    }
    if let Some(w) = a.as_any().downcast_ref::<NdarrayWrapper<f64, Ix1>>() {
        return Ok(w.as_array().clone().into_dyn());
    }
    if let Some(w) = a.as_any().downcast_ref::<NdarrayWrapper<f64, Ix2>>() {
        return Ok(w.as_array().clone().into_dyn());
    }
    if let Some(w) = a.as_any().downcast_ref::<NdarrayWrapper<f64, Ix4>>() {
        return Ok(w.as_array().clone().into_dyn());
    }
    Err(OperationError::TypeMismatch(
        "Layer::backward currently only supports f64 NdarrayWrapper arrays (Ix1/Ix2/Ix4/IxDyn)"
            .to_string(),
    ))
}

/// Wraps `data` to match the concrete dimensionality that `reference`'s own
/// `NdarrayWrapper` uses, so the result stays dispatch-compatible with
/// operations (like `subtract`/`multiply_by_scalar_f64` in a gradient-descent
/// update) that require both operands to share the same concrete `D`.
/// Falls back to `IxDyn` when `reference` isn't one of the recognized
/// concrete dimensionalities.
fn wrap_like(
    reference: &dyn ArrayProtocol,
    data: ArrayD<f64>,
) -> Result<Box<dyn ArrayProtocol>, OperationError> {
    if reference
        .as_any()
        .downcast_ref::<NdarrayWrapper<f64, Ix1>>()
        .is_some()
    {
        let arr = data
            .into_dimensionality::<Ix1>()
            .map_err(|e| OperationError::ShapeMismatch(format!("wrap_like (Ix1): {e}")))?;
        return Ok(Box::new(NdarrayWrapper::new(arr)));
    }
    if reference
        .as_any()
        .downcast_ref::<NdarrayWrapper<f64, Ix2>>()
        .is_some()
    {
        let arr = data
            .into_dimensionality::<Ix2>()
            .map_err(|e| OperationError::ShapeMismatch(format!("wrap_like (Ix2): {e}")))?;
        return Ok(Box::new(NdarrayWrapper::new(arr)));
    }
    if reference
        .as_any()
        .downcast_ref::<NdarrayWrapper<f64, Ix4>>()
        .is_some()
    {
        let arr = data
            .into_dimensionality::<Ix4>()
            .map_err(|e| OperationError::ShapeMismatch(format!("wrap_like (Ix4): {e}")))?;
        return Ok(Box::new(NdarrayWrapper::new(arr)));
    }
    Ok(Box::new(NdarrayWrapper::new(data)))
}

/// Elementwise gradient of `ActivationFunc` (see `ml_ops::apply_activation`
/// for the matching forward computation): given the pre-activation `z` and
/// `grad_y` (`dL/dy` where `y = activation(z)`), returns `dL/dz`.
fn activation_grad(
    z: &ArrayD<f64>,
    act: ActivationFunc,
    grad_y: &ArrayD<f64>,
) -> Result<ArrayD<f64>, OperationError> {
    match act {
        ActivationFunc::ReLU => {
            Ok(Zip::from(z)
                .and(grad_y)
                .map_collect(|&zv, &gy| if zv > 0.0 { gy } else { 0.0 }))
        }
        ActivationFunc::Sigmoid => Ok(Zip::from(z).and(grad_y).map_collect(|&zv, &gy| {
            let s = 1.0 / (1.0 + (-zv).exp());
            gy * s * (1.0 - s)
        })),
        ActivationFunc::Tanh => Ok(Zip::from(z).and(grad_y).map_collect(|&zv, &gy| {
            let t = zv.tanh();
            gy * (1.0 - t * t)
        })),
        ActivationFunc::LeakyReLU(alpha) => Ok(Zip::from(z)
            .and(grad_y)
            .map_collect(|&zv, &gy| if zv > 0.0 { gy } else { gy * alpha })),
        ActivationFunc::Softmax => Err(OperationError::NotImplemented(
            "Softmax backward is not implemented: ml_ops::apply_activation's multi-dimensional \
             Softmax normalizes along the array's last axis regardless of what that axis \
             semantically represents for a given layer, so a generic gradient here would not \
             reliably correspond to forward's behavior. Use an element-wise activation (ReLU, \
             Sigmoid, Tanh, or LeakyReLU) on layers that need to be part of a differentiated model."
                .to_string(),
        )),
    }
}

/// Linear (dense/fully-connected) layer.
pub struct Linear {
    /// The layer's name.
    name: String,

    /// Weight matrix.
    weights: Box<dyn ArrayProtocol>,

    /// Bias vector.
    bias: Option<Box<dyn ArrayProtocol>>,

    /// Activation function.
    activation: Option<ActivationFunc>,

    /// Training mode flag.
    training: bool,
}

impl Linear {
    /// Create a new linear layer.
    pub fn new(
        name: &str,
        weights: Box<dyn ArrayProtocol>,
        bias: Option<Box<dyn ArrayProtocol>>,
        activation: Option<ActivationFunc>,
    ) -> Self {
        Self {
            name: name.to_string(),
            weights,
            bias,
            activation,
            training: true,
        }
    }

    /// Create a new linear layer with randomly initialized weights.
    pub fn new_random(
        name: &str,
        in_features: usize,
        out_features: usize,
        withbias: bool,
        activation: Option<ActivationFunc>,
    ) -> Self {
        // Create random weights using Xavier/Glorot initialization
        let scale = (6.0 / (in_features + out_features) as f64).sqrt();
        let mut rng = rand::rng();
        let weights = Array::from_shape_fn((out_features, in_features), |_| {
            (rng.random::<f64>() * 2.0_f64 - 1.0) * scale
        });

        // Create bias if needed
        let bias = if withbias {
            let bias_array: Array<f64, Ix1> = Array::zeros(out_features);
            Some(Box::new(NdarrayWrapper::new(bias_array)) as Box<dyn ArrayProtocol>)
        } else {
            None
        };

        Self {
            name: name.to_string(),
            weights: Box::new(NdarrayWrapper::new(weights)),
            bias,
            activation,
            training: true,
        }
    }
}

impl Layer for Linear {
    fn layer_type(&self) -> &str {
        "Linear"
    }

    fn forward(
        &self,
        inputs: &dyn ArrayProtocol,
    ) -> Result<Box<dyn ArrayProtocol>, OperationError> {
        // Perform matrix multiplication: y = Wx
        let mut result = crate::array_protocol::matmul(self.weights.as_ref(), inputs)?;

        // Add bias if present: y = Wx + b
        if let Some(bias) = &self.bias {
            // Create a temporary for the intermediate result
            let intermediate = crate::array_protocol::add(result.as_ref(), bias.as_ref())?;
            result = intermediate;
        }

        // Apply activation if present
        if let Some(act_fn) = self.activation {
            // Create a temporary for the intermediate result
            let intermediate = crate::array_protocol::ml_ops::activation(result.as_ref(), act_fn)?;
            result = intermediate;
        }

        Ok(result)
    }

    fn backward(
        &self,
        input: &dyn ArrayProtocol,
        grad_output: &dyn ArrayProtocol,
    ) -> Result<LayerGrad, OperationError> {
        let x = as_f64_array(input)?
            .into_dimensionality::<Ix2>()
            .map_err(|e| {
                OperationError::ShapeMismatch(format!(
                    "Linear::backward expects a 2D input (in_features, batch): {e}"
                ))
            })?;
        let w = as_f64_array(self.weights.as_ref())?
            .into_dimensionality::<Ix2>()
            .map_err(|e| {
                OperationError::ShapeMismatch(format!("Linear::backward expects 2D weights: {e}"))
            })?;

        // Recompute the pre-activation z = Wx [+ b], since `forward` doesn't
        // cache it and it's needed to evaluate the activation's derivative.
        let mut z = w.dot(&x);
        if let Some(bias) = &self.bias {
            let b = as_f64_array(bias.as_ref())?
                .into_dimensionality::<Ix1>()
                .map_err(|e| {
                    OperationError::ShapeMismatch(format!(
                        "Linear::backward expects a 1D bias: {e}"
                    ))
                })?;
            for mut col in z.axis_iter_mut(Axis(1)) {
                col += &b;
            }
        }

        let grad_y = as_f64_array(grad_output)?
            .into_dimensionality::<Ix2>()
            .map_err(|e| {
                OperationError::ShapeMismatch(format!(
                    "Linear::backward expects a 2D grad_output: {e}"
                ))
            })?;

        let grad_z = match self.activation {
            Some(act) => activation_grad(&z.into_dyn(), act, &grad_y.into_dyn())?
                .into_dimensionality::<Ix2>()
                .map_err(|e| {
                    OperationError::Other(format!(
                        "internal shape error recovering activation_grad's result: {e}"
                    ))
                })?,
            None => grad_y,
        };

        // dL/dW = dL/dz @ x^T ; dL/dx = W^T @ dL/dz
        let grad_w = grad_z.dot(&x.t());
        let grad_input = w.t().dot(&grad_z);

        let mut grad_params = vec![wrap_like(self.weights.as_ref(), grad_w.into_dyn())?];
        if let Some(bias) = &self.bias {
            // dL/db = sum over the batch axis of dL/dz
            let grad_b = grad_z.sum_axis(Axis(1));
            grad_params.push(wrap_like(bias.as_ref(), grad_b.into_dyn())?);
        }

        Ok(LayerGrad {
            grad_input: wrap_like(input, grad_input.into_dyn())?,
            grad_params,
        })
    }

    fn parameters(&self) -> Vec<Box<dyn ArrayProtocol>> {
        let mut params = vec![self.weights.clone()];
        if let Some(bias) = &self.bias {
            params.push(bias.clone());
        }
        params
    }

    fn parameters_mut(&mut self) -> Vec<&mut Box<dyn ArrayProtocol>> {
        let mut params = vec![&mut self.weights];
        if let Some(bias) = &mut self.bias {
            params.push(bias);
        }
        params
    }

    fn update_parameter(
        &mut self,
        name: &str,
        value: Box<dyn ArrayProtocol>,
    ) -> Result<(), OperationError> {
        match name {
            "weights" => {
                self.weights = value;
                Ok(())
            }
            "bias" => {
                self.bias = Some(value);
                Ok(())
            }
            _ => Err(OperationError::Other(format!("Unknown parameter: {name}"))),
        }
    }

    fn parameter_names(&self) -> Vec<String> {
        let mut names = vec!["weights".to_string()];
        if self.bias.is_some() {
            names.push("bias".to_string());
        }
        names
    }

    fn train(&mut self) {
        self.training = true;
    }

    fn eval(&mut self) {
        self.training = false;
    }

    fn is_training(&self) -> bool {
        self.training
    }

    fn name(&self) -> &str {
        &self.name
    }
}

/// Convolutional layer.
pub struct Conv2D {
    /// The layer's name.
    name: String,

    /// Filters tensor.
    filters: Box<dyn ArrayProtocol>,

    /// Bias vector.
    bias: Option<Box<dyn ArrayProtocol>>,

    /// Stride for the convolution.
    stride: (usize, usize),

    /// Padding for the convolution.
    padding: (usize, usize),

    /// Activation function.
    activation: Option<ActivationFunc>,

    /// Training mode flag.
    training: bool,
}

impl Conv2D {
    /// Create a new convolutional layer.
    pub fn new(
        name: &str,
        filters: Box<dyn ArrayProtocol>,
        bias: Option<Box<dyn ArrayProtocol>>,
        stride: (usize, usize),
        padding: (usize, usize),
        activation: Option<ActivationFunc>,
    ) -> Self {
        Self {
            name: name.to_string(),
            filters,
            bias,
            stride,
            padding,
            activation,
            training: true,
        }
    }

    /// Create a new convolutional layer with randomly initialized weights.
    #[allow(clippy::too_many_arguments)]
    pub fn withshape(
        name: &str,
        filter_height: usize,
        filter_width: usize,
        in_channels: usize,
        out_channels: usize,
        stride: (usize, usize),
        padding: (usize, usize),
        withbias: bool,
        activation: Option<ActivationFunc>,
    ) -> Self {
        // Create random filters using Kaiming initialization
        let fan_in = filter_height * filter_width * in_channels;
        let scale = (2.0 / fan_in as f64).sqrt();
        let mut rng = rand::rng();
        let filters = Array::from_shape_fn(
            (filter_height, filter_width, in_channels, out_channels),
            |_| (rng.random::<f64>() * 2.0_f64 - 1.0) * scale,
        );

        // Create bias if needed
        let bias = if withbias {
            let bias_array: Array<f64, Ix1> = Array::zeros(out_channels);
            Some(Box::new(NdarrayWrapper::new(bias_array)) as Box<dyn ArrayProtocol>)
        } else {
            None
        };

        Self {
            name: name.to_string(),
            filters: Box::new(NdarrayWrapper::new(filters)),
            bias,
            stride,
            padding,
            activation,
            training: true,
        }
    }
}

impl Layer for Conv2D {
    fn layer_type(&self) -> &str {
        "Conv2D"
    }

    fn forward(
        &self,
        inputs: &dyn ArrayProtocol,
    ) -> Result<Box<dyn ArrayProtocol>, OperationError> {
        // Perform convolution
        let mut result = crate::array_protocol::ml_ops::conv2d(
            inputs,
            self.filters.as_ref(),
            self.stride,
            self.padding,
        )?;

        // Add bias if present
        if let Some(bias) = &self.bias {
            result = crate::array_protocol::add(result.as_ref(), bias.as_ref())?;
        }

        // Apply activation if present
        if let Some(act_fn) = self.activation {
            result = crate::array_protocol::ml_ops::activation(result.as_ref(), act_fn)?;
        }

        Ok(result)
    }

    #[allow(clippy::needless_range_loop)]
    fn backward(
        &self,
        input: &dyn ArrayProtocol,
        grad_output: &dyn ArrayProtocol,
    ) -> Result<LayerGrad, OperationError> {
        let inputarr = as_f64_array(input)?
            .into_dimensionality::<Ix4>()
            .map_err(|e| {
                OperationError::ShapeMismatch(format!("Conv2D::backward expects a 4D input: {e}"))
            })?;
        let filters = as_f64_array(self.filters.as_ref())?
            .into_dimensionality::<Ix4>()
            .map_err(|e| {
                OperationError::ShapeMismatch(format!("Conv2D::backward expects 4D filters: {e}"))
            })?;

        let (stride_h, stride_w) = self.stride;
        let (pad_h, pad_w) = self.padding;
        let batch_size = inputarr.shape()[0];
        let input_height = inputarr.shape()[1];
        let input_width = inputarr.shape()[2];
        let input_channels = inputarr.shape()[3];
        let filter_height = filters.shape()[0];
        let filter_width = filters.shape()[1];
        let filter_out_channels = filters.shape()[3];
        let out_height = (input_height - filter_height + 2 * pad_h) / stride_h + 1;
        let out_width = (input_width - filter_width + 2 * pad_w) / stride_w + 1;

        // Recompute the pre-activation convolution output (forward doesn't
        // cache it), needed to evaluate the activation's derivative.
        let mut conv_out =
            Array4::<f64>::zeros((batch_size, out_height, out_width, filter_out_channels));
        for b in 0..batch_size {
            for oc in 0..filter_out_channels {
                for oh in 0..out_height {
                    for ow in 0..out_width {
                        let mut sum = 0.0;
                        for fh in 0..filter_height {
                            for fw in 0..filter_width {
                                let in_h = (oh * stride_h) as i32 + fh as i32 - pad_h as i32;
                                let in_w = (ow * stride_w) as i32 + fw as i32 - pad_w as i32;
                                if in_h >= 0
                                    && in_h < input_height as i32
                                    && in_w >= 0
                                    && in_w < input_width as i32
                                {
                                    for ic in 0..input_channels {
                                        sum += inputarr[[b, in_h as usize, in_w as usize, ic]]
                                            * filters[[fh, fw, ic, oc]];
                                    }
                                }
                            }
                        }
                        conv_out[[b, oh, ow, oc]] = sum;
                    }
                }
            }
        }
        if let Some(bias) = &self.bias {
            let bias_arr = as_f64_array(bias.as_ref())?;
            for b in 0..batch_size {
                for oh in 0..out_height {
                    for ow in 0..out_width {
                        for oc in 0..filter_out_channels {
                            conv_out[[b, oh, ow, oc]] += bias_arr[[oc]];
                        }
                    }
                }
            }
        }

        let grad_y = as_f64_array(grad_output)?
            .into_dimensionality::<Ix4>()
            .map_err(|e| {
                OperationError::ShapeMismatch(format!(
                    "Conv2D::backward expects a 4D grad_output: {e}"
                ))
            })?;

        let grad_preact = match self.activation {
            Some(act) => activation_grad(&conv_out.into_dyn(), act, &grad_y.into_dyn())?
                .into_dimensionality::<Ix4>()
                .map_err(|e| {
                    OperationError::Other(format!(
                        "internal shape error recovering activation_grad's result: {e}"
                    ))
                })?,
            None => grad_y,
        };

        // Backward via loop transposition of the exact forward computation:
        // every (b, oc, oh, ow, fh, fw, ic) contribution to `conv_out` above
        // contributes symmetrically to `grad_filters` and `grad_input`.
        let mut grad_input =
            Array4::<f64>::zeros((batch_size, input_height, input_width, input_channels));
        let mut grad_filters = Array4::<f64>::zeros((
            filter_height,
            filter_width,
            input_channels,
            filter_out_channels,
        ));

        for b in 0..batch_size {
            for oc in 0..filter_out_channels {
                for oh in 0..out_height {
                    for ow in 0..out_width {
                        let g = grad_preact[[b, oh, ow, oc]];
                        for fh in 0..filter_height {
                            for fw in 0..filter_width {
                                let in_h = (oh * stride_h) as i32 + fh as i32 - pad_h as i32;
                                let in_w = (ow * stride_w) as i32 + fw as i32 - pad_w as i32;
                                if in_h >= 0
                                    && in_h < input_height as i32
                                    && in_w >= 0
                                    && in_w < input_width as i32
                                {
                                    let (in_h, in_w) = (in_h as usize, in_w as usize);
                                    for ic in 0..input_channels {
                                        grad_filters[[fh, fw, ic, oc]] +=
                                            g * inputarr[[b, in_h, in_w, ic]];
                                        grad_input[[b, in_h, in_w, ic]] +=
                                            g * filters[[fh, fw, ic, oc]];
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        let mut grad_params = vec![wrap_like(self.filters.as_ref(), grad_filters.into_dyn())?];
        if let Some(bias) = &self.bias {
            let mut grad_bias = Array1::<f64>::zeros(filter_out_channels);
            for b in 0..batch_size {
                for oh in 0..out_height {
                    for ow in 0..out_width {
                        for oc in 0..filter_out_channels {
                            grad_bias[oc] += grad_preact[[b, oh, ow, oc]];
                        }
                    }
                }
            }
            grad_params.push(wrap_like(bias.as_ref(), grad_bias.into_dyn())?);
        }

        Ok(LayerGrad {
            grad_input: wrap_like(input, grad_input.into_dyn())?,
            grad_params,
        })
    }

    fn parameters(&self) -> Vec<Box<dyn ArrayProtocol>> {
        let mut params = vec![self.filters.clone()];
        if let Some(bias) = &self.bias {
            params.push(bias.clone());
        }
        params
    }

    fn parameters_mut(&mut self) -> Vec<&mut Box<dyn ArrayProtocol>> {
        let mut params = vec![&mut self.filters];
        if let Some(bias) = &mut self.bias {
            params.push(bias);
        }
        params
    }

    fn update_parameter(
        &mut self,
        name: &str,
        value: Box<dyn ArrayProtocol>,
    ) -> Result<(), OperationError> {
        match name {
            "filters" => {
                self.filters = value;
                Ok(())
            }
            "bias" => {
                self.bias = Some(value);
                Ok(())
            }
            _ => Err(OperationError::Other(format!("Unknown parameter: {name}"))),
        }
    }

    fn parameter_names(&self) -> Vec<String> {
        let mut names = vec!["filters".to_string()];
        if self.bias.is_some() {
            names.push("bias".to_string());
        }
        names
    }

    fn train(&mut self) {
        self.training = true;
    }

    fn eval(&mut self) {
        self.training = false;
    }

    fn is_training(&self) -> bool {
        self.training
    }

    fn name(&self) -> &str {
        &self.name
    }
}

/// Builder for creating Conv2D layers
pub struct Conv2DBuilder {
    name: String,
    filter_height: usize,
    filter_width: usize,
    in_channels: usize,
    out_channels: usize,
    stride: (usize, usize),
    padding: (usize, usize),
    withbias: bool,
    activation: Option<ActivationFunc>,
}

impl Conv2DBuilder {
    /// Create a new Conv2D builder
    pub fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
            filter_height: 3,
            filter_width: 3,
            in_channels: 1,
            out_channels: 1,
            stride: (1, 1),
            padding: (0, 0),
            withbias: true,
            activation: None,
        }
    }

    /// Set filter dimensions
    pub const fn filter_size(mut self, height: usize, width: usize) -> Self {
        self.filter_height = height;
        self.filter_width = width;
        self
    }

    /// Set input and output channels
    pub const fn channels(mut self, input: usize, output: usize) -> Self {
        self.in_channels = input;
        self.out_channels = output;
        self
    }

    /// Set stride
    pub fn stride(mut self, stride: (usize, usize)) -> Self {
        self.stride = stride;
        self
    }

    /// Set padding
    pub fn padding(mut self, padding: (usize, usize)) -> Self {
        self.padding = padding;
        self
    }

    /// Set whether to include bias
    pub fn withbias(mut self, withbias: bool) -> Self {
        self.withbias = withbias;
        self
    }

    /// Set activation function
    pub fn activation(mut self, activation: ActivationFunc) -> Self {
        self.activation = Some(activation);
        self
    }

    /// Build the Conv2D layer
    pub fn build(self) -> Conv2D {
        Conv2D::withshape(
            &self.name,
            self.filter_height,
            self.filter_width,
            self.in_channels,
            self.out_channels,
            self.stride,
            self.padding,
            self.withbias,
            self.activation,
        )
    }
}

/// Max pooling layer.
#[allow(dead_code)]
pub struct MaxPool2D {
    /// The layer's name.
    name: String,

    /// Kernel size.
    kernel_size: (usize, usize),

    /// Stride.
    stride: (usize, usize),

    /// Padding.
    padding: (usize, usize),

    /// Training mode flag.
    training: bool,
}

impl MaxPool2D {
    /// Create a new max pooling layer.
    pub fn new(
        name: &str,
        kernel_size: (usize, usize),
        stride: Option<(usize, usize)>,
        padding: (usize, usize),
    ) -> Self {
        let stride = stride.unwrap_or(kernel_size);

        Self {
            name: name.to_string(),
            kernel_size,
            stride,
            padding,
            training: true,
        }
    }
}

impl Layer for MaxPool2D {
    fn layer_type(&self) -> &str {
        "MaxPool2D"
    }

    fn forward(
        &self,
        inputs: &dyn ArrayProtocol,
    ) -> Result<Box<dyn ArrayProtocol>, OperationError> {
        // Use the max_pool2d implementation from ml_ops module
        crate::array_protocol::ml_ops::max_pool2d(
            inputs,
            self.kernel_size,
            self.stride,
            self.padding,
        )
    }

    fn backward(
        &self,
        input: &dyn ArrayProtocol,
        grad_output: &dyn ArrayProtocol,
    ) -> Result<LayerGrad, OperationError> {
        let inputarr = as_f64_array(input)?
            .into_dimensionality::<Ix4>()
            .map_err(|e| {
                OperationError::ShapeMismatch(format!(
                    "MaxPool2D::backward expects a 4D input: {e}"
                ))
            })?;
        let grad_y = as_f64_array(grad_output)?
            .into_dimensionality::<Ix4>()
            .map_err(|e| {
                OperationError::ShapeMismatch(format!(
                    "MaxPool2D::backward expects a 4D grad_output: {e}"
                ))
            })?;

        let (kernel_h, kernel_w) = self.kernel_size;
        let (stride_h, stride_w) = self.stride;
        let (pad_h, pad_w) = self.padding;

        let batch_size = inputarr.shape()[0];
        let input_height = inputarr.shape()[1];
        let input_width = inputarr.shape()[2];
        let channels = inputarr.shape()[3];
        let out_height = grad_y.shape()[1];
        let out_width = grad_y.shape()[2];

        let mut grad_input =
            Array4::<f64>::zeros((batch_size, input_height, input_width, channels));

        // Route each output cell's gradient to whichever input cell was the
        // max in its pooling window (accumulating, since overlapping
        // windows can route to the same input cell more than once).
        for b in 0..batch_size {
            for c in 0..channels {
                for out_h in 0..out_height {
                    for out_w in 0..out_width {
                        let mut max_val = f64::NEG_INFINITY;
                        let mut argmax: Option<(usize, usize)> = None;
                        for k_h in 0..kernel_h {
                            for k_w in 0..kernel_w {
                                let in_h = (out_h * stride_h) as i32 + k_h as i32 - pad_h as i32;
                                let in_w = (out_w * stride_w) as i32 + k_w as i32 - pad_w as i32;
                                if in_h >= 0
                                    && in_h < input_height as i32
                                    && in_w >= 0
                                    && in_w < input_width as i32
                                {
                                    let val = inputarr[[b, in_h as usize, in_w as usize, c]];
                                    if val > max_val {
                                        max_val = val;
                                        argmax = Some((in_h as usize, in_w as usize));
                                    }
                                }
                            }
                        }
                        if let Some((in_h, in_w)) = argmax {
                            grad_input[[b, in_h, in_w, c]] += grad_y[[b, out_h, out_w, c]];
                        }
                    }
                }
            }
        }

        Ok(LayerGrad {
            grad_input: wrap_like(input, grad_input.into_dyn())?,
            grad_params: Vec::new(),
        })
    }

    fn parameters(&self) -> Vec<Box<dyn ArrayProtocol>> {
        // Pooling layers have no parameters
        Vec::new()
    }

    fn parameters_mut(&mut self) -> Vec<&mut Box<dyn ArrayProtocol>> {
        // Pooling layers have no parameters
        Vec::new()
    }

    fn update_parameter(
        &mut self,
        name: &str,
        _value: Box<dyn ArrayProtocol>,
    ) -> Result<(), OperationError> {
        Err(OperationError::Other(format!(
            "MaxPool2D has no parameter: {name}"
        )))
    }

    fn parameter_names(&self) -> Vec<String> {
        // Pooling layers have no parameters
        Vec::new()
    }

    fn train(&mut self) {
        self.training = true;
    }

    fn eval(&mut self) {
        self.training = false;
    }

    fn is_training(&self) -> bool {
        self.training
    }

    fn name(&self) -> &str {
        &self.name
    }
}

/// Batch normalization layer.
pub struct BatchNorm {
    /// The layer's name.
    name: String,

    /// Scale parameter.
    scale: Box<dyn ArrayProtocol>,

    /// Offset parameter.
    offset: Box<dyn ArrayProtocol>,

    /// Running mean (for inference).
    running_mean: Box<dyn ArrayProtocol>,

    /// Running variance (for inference).
    running_var: Box<dyn ArrayProtocol>,

    /// Epsilon for numerical stability.
    epsilon: f64,

    /// Training mode flag.
    training: bool,
}

impl BatchNorm {
    /// Create a new batch normalization layer.
    pub fn new(
        name: &str,
        scale: Box<dyn ArrayProtocol>,
        offset: Box<dyn ArrayProtocol>,
        running_mean: Box<dyn ArrayProtocol>,
        running_var: Box<dyn ArrayProtocol>,
        epsilon: f64,
    ) -> Self {
        Self {
            name: name.to_string(),
            scale,
            offset,
            running_mean,
            running_var,
            epsilon,
            training: true,
        }
    }

    /// Create a new batch normalization layer with initialized parameters.
    pub fn withshape(
        name: &str,
        num_features: usize,
        epsilon: Option<f64>,
        _momentum: Option<f64>,
    ) -> Self {
        // Initialize parameters with explicit types
        let scale: Array<f64, Ix1> = Array::ones(num_features);
        let offset: Array<f64, Ix1> = Array::zeros(num_features);
        let running_mean: Array<f64, Ix1> = Array::zeros(num_features);
        let running_var: Array<f64, Ix1> = Array::ones(num_features);

        Self {
            name: name.to_string(),
            scale: Box::new(NdarrayWrapper::new(scale)),
            offset: Box::new(NdarrayWrapper::new(offset)),
            running_mean: Box::new(NdarrayWrapper::new(running_mean)),
            running_var: Box::new(NdarrayWrapper::new(running_var)),
            epsilon: epsilon.unwrap_or(1e-5),
            training: true,
        }
    }
}

impl Layer for BatchNorm {
    fn layer_type(&self) -> &str {
        "BatchNorm"
    }

    fn forward(
        &self,
        inputs: &dyn ArrayProtocol,
    ) -> Result<Box<dyn ArrayProtocol>, OperationError> {
        crate::array_protocol::ml_ops::batch_norm(
            inputs,
            self.scale.as_ref(),
            self.offset.as_ref(),
            self.running_mean.as_ref(),
            self.running_var.as_ref(),
            self.epsilon,
        )
    }

    fn backward(
        &self,
        input: &dyn ArrayProtocol,
        grad_output: &dyn ArrayProtocol,
    ) -> Result<LayerGrad, OperationError> {
        // `ml_ops::batch_norm`'s forward always normalizes with the given
        // `mean`/`variance` directly (it does not compute batch statistics
        // even in training mode), so — matching that — they're treated here
        // as constants rather than differentiated through: only `scale` and
        // `offset` are learnable parameters (see `parameters()` below).
        let x = as_f64_array(input)?
            .into_dimensionality::<Ix4>()
            .map_err(|e| {
                OperationError::ShapeMismatch(format!(
                    "BatchNorm::backward expects a 4D input: {e}"
                ))
            })?;
        let grad_y = as_f64_array(grad_output)?
            .into_dimensionality::<Ix4>()
            .map_err(|e| {
                OperationError::ShapeMismatch(format!(
                    "BatchNorm::backward expects a 4D grad_output: {e}"
                ))
            })?;
        let scale = as_f64_array(self.scale.as_ref())?;
        let mean = as_f64_array(self.running_mean.as_ref())?;
        let variance = as_f64_array(self.running_var.as_ref())?;

        let (batch_size, height, width, channels) = x.dim();
        let mut grad_input = Array4::<f64>::zeros((batch_size, height, width, channels));
        let mut grad_scale = Array1::<f64>::zeros(channels);
        let mut grad_offset = Array1::<f64>::zeros(channels);

        for c in 0..channels {
            let inv_std = 1.0 / (variance[[c]] + self.epsilon).sqrt();
            let m = mean[[c]];
            let s = scale[[c]];
            let mut grad_scale_c = 0.0;
            let mut grad_offset_c = 0.0;
            for b in 0..batch_size {
                for h in 0..height {
                    for w in 0..width {
                        let gy = grad_y[[b, h, w, c]];
                        let normalized = (x[[b, h, w, c]] - m) * inv_std;
                        grad_scale_c += gy * normalized;
                        grad_offset_c += gy;
                        grad_input[[b, h, w, c]] = gy * s * inv_std;
                    }
                }
            }
            grad_scale[c] = grad_scale_c;
            grad_offset[c] = grad_offset_c;
        }

        Ok(LayerGrad {
            grad_input: wrap_like(input, grad_input.into_dyn())?,
            grad_params: vec![
                wrap_like(self.scale.as_ref(), grad_scale.into_dyn())?,
                wrap_like(self.offset.as_ref(), grad_offset.into_dyn())?,
            ],
        })
    }

    fn parameters(&self) -> Vec<Box<dyn ArrayProtocol>> {
        vec![self.scale.clone(), self.offset.clone()]
    }

    fn parameters_mut(&mut self) -> Vec<&mut Box<dyn ArrayProtocol>> {
        vec![&mut self.scale, &mut self.offset]
    }

    fn update_parameter(
        &mut self,
        name: &str,
        value: Box<dyn ArrayProtocol>,
    ) -> Result<(), OperationError> {
        match name {
            "scale" => {
                self.scale = value;
                Ok(())
            }
            "offset" => {
                self.offset = value;
                Ok(())
            }
            _ => Err(OperationError::Other(format!("Unknown parameter: {name}"))),
        }
    }

    fn parameter_names(&self) -> Vec<String> {
        vec!["scale".to_string(), "offset".to_string()]
    }

    fn train(&mut self) {
        self.training = true;
    }

    fn eval(&mut self) {
        self.training = false;
    }

    fn is_training(&self) -> bool {
        self.training
    }

    fn name(&self) -> &str {
        &self.name
    }
}

/// Dropout layer.
pub struct Dropout {
    /// The layer's name.
    name: String,

    /// Dropout rate.
    rate: f64,

    /// Optional seed for reproducibility.
    seed: Option<u64>,

    /// Training mode flag.
    training: bool,
}

impl Dropout {
    /// Create a new dropout layer.
    pub fn new(name: &str, rate: f64, seed: Option<u64>) -> Self {
        Self {
            name: name.to_string(),
            rate,
            seed,
            training: true,
        }
    }
}

impl Layer for Dropout {
    fn layer_type(&self) -> &str {
        "Dropout"
    }

    fn forward(
        &self,
        inputs: &dyn ArrayProtocol,
    ) -> Result<Box<dyn ArrayProtocol>, OperationError> {
        crate::array_protocol::ml_ops::dropout(inputs, self.rate, self.training, self.seed)
    }

    fn backward(
        &self,
        input: &dyn ArrayProtocol,
        grad_output: &dyn ArrayProtocol,
    ) -> Result<LayerGrad, OperationError> {
        if !self.training {
            // Inference-mode dropout is the identity function.
            return Ok(LayerGrad {
                grad_input: grad_output.box_clone(),
                grad_params: Vec::new(),
            });
        }

        // `ml_ops::dropout`'s forward doesn't cache the mask it drew, so it
        // can only be reproduced deterministically (and thus differentiated
        // through) when the layer was constructed with a fixed seed.
        let seed = self.seed.ok_or_else(|| {
            OperationError::NotImplemented(
                "Dropout::backward requires a fixed `seed` to deterministically reproduce the \
                 forward mask (forward() does not cache it); construct the layer via \
                 `Dropout::new(name, rate, Some(seed))` to backpropagate through training-mode \
                 dropout"
                    .to_string(),
            )
        })?;

        let grad_y = as_f64_array(grad_output)?;
        let inputarr = as_f64_array(input)?;
        if inputarr.shape() != grad_y.shape() {
            return Err(OperationError::ShapeMismatch(format!(
                "Dropout::backward: input shape {inputshape:?} != grad_output shape {gradshape:?}",
                inputshape = inputarr.shape(),
                gradshape = grad_y.shape()
            )));
        }

        // Reproduce the exact mask `forward()` would have drawn for this
        // input shape, using the same seeded RNG sequence.
        let mut rng = rand::rngs::StdRng::seed_from_u64(seed);
        let rate = self.rate;
        let mask = Array::from_shape_fn(inputarr.raw_dim(), |_| {
            if rng.random::<f64>() >= rate {
                1.0
            } else {
                0.0
            }
        });
        let scale = 1.0 / (1.0 - self.rate);
        let grad_input = grad_y * &mask * scale;

        Ok(LayerGrad {
            grad_input: wrap_like(input, grad_input)?,
            grad_params: Vec::new(),
        })
    }

    fn parameters(&self) -> Vec<Box<dyn ArrayProtocol>> {
        // Dropout layers have no parameters
        Vec::new()
    }

    fn parameters_mut(&mut self) -> Vec<&mut Box<dyn ArrayProtocol>> {
        // Dropout layers have no parameters
        Vec::new()
    }

    fn update_parameter(
        &mut self,
        name: &str,
        _value: Box<dyn ArrayProtocol>,
    ) -> Result<(), OperationError> {
        Err(OperationError::Other(format!(
            "Dropout has no parameter: {name}"
        )))
    }

    fn parameter_names(&self) -> Vec<String> {
        // Dropout layers have no parameters
        Vec::new()
    }

    fn train(&mut self) {
        self.training = true;
    }

    fn eval(&mut self) {
        self.training = false;
    }

    fn is_training(&self) -> bool {
        self.training
    }

    fn name(&self) -> &str {
        &self.name
    }
}

/// Multi-head attention layer.
pub struct MultiHeadAttention {
    /// The layer's name.
    name: String,

    /// Query projection.
    wq: Box<dyn ArrayProtocol>,

    /// Key projection.
    wk: Box<dyn ArrayProtocol>,

    /// Value projection.
    wv: Box<dyn ArrayProtocol>,

    /// Output projection.
    wo: Box<dyn ArrayProtocol>,

    /// Number of attention heads.
    num_heads: usize,

    /// Model dimension.
    dmodel: usize,

    /// Training mode flag.
    training: bool,
}

impl MultiHeadAttention {
    /// Create a new multi-head attention layer.
    pub fn new(
        name: &str,
        wq: Box<dyn ArrayProtocol>,
        wk: Box<dyn ArrayProtocol>,
        wv: Box<dyn ArrayProtocol>,
        wo: Box<dyn ArrayProtocol>,
        num_heads: usize,
        dmodel: usize,
    ) -> Self {
        Self {
            name: name.to_string(),
            wq,
            wk,
            wv,
            wo,
            num_heads,
            dmodel,
            training: true,
        }
    }

    /// Create a new multi-head attention layer with randomly initialized weights.
    pub fn with_params(name: &str, num_heads: usize, dmodel: usize) -> Self {
        // Check if dmodel is divisible by num_heads
        assert!(
            dmodel % num_heads == 0,
            "dmodel must be divisible by num_heads"
        );

        // Initialize parameters
        let scale = (1.0_f64 / dmodel as f64).sqrt();
        let mut rng = rand::rng();

        let wq = Array::from_shape_fn((dmodel, dmodel), |_| {
            (rng.random::<f64>() * 2.0_f64 - 1.0) * scale
        });

        let wk = Array::from_shape_fn((dmodel, dmodel), |_| {
            (rng.random::<f64>() * 2.0_f64 - 1.0) * scale
        });

        let wv = Array::from_shape_fn((dmodel, dmodel), |_| {
            (rng.random::<f64>() * 2.0_f64 - 1.0) * scale
        });

        let wo = Array::from_shape_fn((dmodel, dmodel), |_| {
            (rng.random::<f64>() * 2.0_f64 - 1.0) * scale
        });

        Self {
            name: name.to_string(),
            wq: Box::new(NdarrayWrapper::new(wq)),
            wk: Box::new(NdarrayWrapper::new(wk)),
            wv: Box::new(NdarrayWrapper::new(wv)),
            wo: Box::new(NdarrayWrapper::new(wo)),
            num_heads,
            dmodel,
            training: true,
        }
    }
}

impl Layer for MultiHeadAttention {
    fn layer_type(&self) -> &str {
        "MultiHeadAttention"
    }

    fn forward(
        &self,
        inputs: &dyn ArrayProtocol,
    ) -> Result<Box<dyn ArrayProtocol>, OperationError> {
        // For a real implementation, this would:
        // 1. Project inputs to queries, keys, and values
        // 2. Reshape for multi-head attention
        // 3. Compute self-attention
        // 4. Reshape and project back to output space

        // This is a simplified placeholder implementation
        let queries = crate::array_protocol::matmul(self.wq.as_ref(), inputs)?;
        let keys = crate::array_protocol::matmul(self.wk.as_ref(), inputs)?;
        let values = crate::array_protocol::matmul(self.wv.as_ref(), inputs)?;

        // Compute self-attention
        let attention = crate::array_protocol::ml_ops::self_attention(
            queries.as_ref(),
            keys.as_ref(),
            values.as_ref(),
            None,
            Some((self.dmodel / self.num_heads) as f64),
        )?;

        // Project back to output space
        let output = crate::array_protocol::matmul(self.wo.as_ref(), attention.as_ref())?;

        Ok(output)
    }

    fn backward(
        &self,
        _input: &dyn ArrayProtocol,
        _grad_output: &dyn ArrayProtocol,
    ) -> Result<LayerGrad, OperationError> {
        // `forward()` above is already documented as "a simplified
        // placeholder implementation" that doesn't perform real per-head
        // reshape/splitting — differentiating it exactly wouldn't give a
        // gradient for the multi-head attention operation this layer is
        // meant to represent. Fixing `forward()` for real is a prerequisite
        // for a meaningful `backward()` here.
        Err(OperationError::NotImplemented(
            "MultiHeadAttention::backward is not implemented (forward() is itself a documented \
             simplified placeholder, not real multi-head attention)"
                .to_string(),
        ))
    }

    fn parameters(&self) -> Vec<Box<dyn ArrayProtocol>> {
        vec![
            self.wq.clone(),
            self.wk.clone(),
            self.wv.clone(),
            self.wo.clone(),
        ]
    }

    fn parameters_mut(&mut self) -> Vec<&mut Box<dyn ArrayProtocol>> {
        vec![&mut self.wq, &mut self.wk, &mut self.wv, &mut self.wo]
    }

    fn update_parameter(
        &mut self,
        name: &str,
        value: Box<dyn ArrayProtocol>,
    ) -> Result<(), OperationError> {
        match name {
            "wq" => {
                self.wq = value;
                Ok(())
            }
            "wk" => {
                self.wk = value;
                Ok(())
            }
            "wv" => {
                self.wv = value;
                Ok(())
            }
            "wo" => {
                self.wo = value;
                Ok(())
            }
            _ => Err(OperationError::Other(format!("Unknown parameter: {name}"))),
        }
    }

    fn parameter_names(&self) -> Vec<String> {
        vec![
            "wq".to_string(),
            "wk".to_string(),
            "wv".to_string(),
            "wo".to_string(),
        ]
    }

    fn train(&mut self) {
        self.training = true;
    }

    fn eval(&mut self) {
        self.training = false;
    }

    fn is_training(&self) -> bool {
        self.training
    }

    fn name(&self) -> &str {
        &self.name
    }
}

/// Sequential model that chains layers together.
pub struct Sequential {
    /// The model's name.
    name: String,

    /// The layers in the model.
    layers: Vec<Box<dyn Layer>>,

    /// Training mode flag.
    training: bool,
}

impl Sequential {
    /// Create a new sequential model.
    pub fn new(name: &str, layers: Vec<Box<dyn Layer>>) -> Self {
        Self {
            name: name.to_string(),
            layers,
            training: true,
        }
    }

    /// Add a layer to the model.
    pub fn add_layer(&mut self, layer: Box<dyn Layer>) {
        self.layers.push(layer);
    }

    /// Forward pass through the model.
    pub fn forward(
        &self,
        inputs: &dyn ArrayProtocol,
    ) -> Result<Box<dyn ArrayProtocol>, OperationError> {
        // Clone the input to a Box
        let mut x: Box<dyn ArrayProtocol> = inputs.box_clone();

        for layer in &self.layers {
            // Get a reference from the box for the layer
            let x_ref: &dyn ArrayProtocol = x.as_ref();
            // Update x with the layer output
            x = layer.forward(x_ref)?;
        }

        Ok(x)
    }

    /// Get all parameters in the model.
    pub fn parameters(&self) -> Vec<Box<dyn ArrayProtocol>> {
        let mut params = Vec::new();

        for layer in &self.layers {
            params.extend(layer.parameters());
        }

        params
    }

    /// Set the model to training mode.
    pub fn train(&mut self) {
        self.training = true;

        for layer in &mut self.layers {
            layer.train();
        }
    }

    /// Set the model to evaluation mode.
    pub fn eval(&mut self) {
        self.training = false;

        for layer in &mut self.layers {
            layer.eval();
        }
    }

    /// Get the model's name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the layers in the model.
    pub fn layers(&self) -> &[Box<dyn Layer>] {
        &self.layers
    }

    /// Get mutable access to the layers in the model — e.g. so a
    /// deserializer can restore saved parameter values in place.
    pub fn layers_mut(&mut self) -> &mut [Box<dyn Layer>] {
        &mut self.layers
    }

    /// Backward pass through the model: given the original `input` fed to
    /// `forward` and `grad_output` (the gradient of the loss with respect
    /// to the model's final output — e.g. `Loss::backward`'s result),
    /// computes the gradient for every parameter in every layer via
    /// backpropagation. The returned dictionary is keyed
    /// `"{layer_index}.{param_name}"`, matching [`Self::all_parameter_names`]
    /// and [`Self::update_parameter`]'s expected format.
    ///
    /// `Layer::forward` doesn't cache intermediate activations, so this
    /// first recomputes the forward pass (retaining each layer's input) and
    /// then walks the layers in reverse, threading each layer's
    /// `grad_input` to the previous layer as its `grad_output`.
    pub fn backward(
        &self,
        input: &dyn ArrayProtocol,
        grad_output: &dyn ArrayProtocol,
    ) -> Result<crate::array_protocol::grad::GradientDict, crate::error::CoreError> {
        let mut gradients = crate::array_protocol::grad::GradientDict::new();
        if self.layers.is_empty() {
            return Ok(gradients);
        }

        // Recompute the forward pass, caching each layer's input so that
        // `activations[i]` is the input seen by `self.layers[i]`.
        let mut activations: Vec<Box<dyn ArrayProtocol>> =
            Vec::with_capacity(self.layers.len() + 1);
        activations.push(input.box_clone());
        for layer in &self.layers {
            let layer_input: &dyn ArrayProtocol = activations
                .last()
                .ok_or_else(|| {
                    crate::error::CoreError::ComputationError(crate::error::ErrorContext::new(
                        "internal error: activation cache unexpectedly empty".to_string(),
                    ))
                })?
                .as_ref();
            let out = layer.forward(layer_input).map_err(|e| {
                crate::error::CoreError::ComputationError(crate::error::ErrorContext::new(format!(
                    "backward(): forward recompute failed in layer '{name}': {e}",
                    name = layer.name()
                )))
            })?;
            activations.push(out);
        }

        // Walk the layers in reverse, propagating the gradient and
        // collecting each layer's parameter gradients.
        let mut grad_current: Box<dyn ArrayProtocol> = grad_output.box_clone();
        for (layer_idx, layer) in self.layers.iter().enumerate().rev() {
            let layer_input: &dyn ArrayProtocol = activations[layer_idx].as_ref();
            let layer_grad = layer
                .backward(layer_input, grad_current.as_ref())
                .map_err(|e| {
                    crate::error::CoreError::ComputationError(crate::error::ErrorContext::new(
                        format!(
                            "backward() failed in layer '{name}' (index {layer_idx}): {e}",
                            name = layer.name()
                        ),
                    ))
                })?;

            let param_names = layer.parameter_names();
            for (param_idx, grad_param) in layer_grad.grad_params.into_iter().enumerate() {
                let param_name = param_names.get(param_idx).ok_or_else(|| {
                    crate::error::CoreError::ComputationError(crate::error::ErrorContext::new(
                        format!(
                            "layer '{name}' (index {layer_idx}) returned {ngrads} parameter \
                             gradient(s) but parameter_names() only has {nnames}",
                            name = layer.name(),
                            ngrads = param_idx + 1,
                            nnames = param_names.len()
                        ),
                    ))
                })?;
                gradients.insert(format!("{layer_idx}.{param_name}"), grad_param);
            }

            grad_current = layer_grad.grad_input;
        }

        Ok(gradients)
    }

    /// Update a parameter in the model
    pub fn update_parameter(
        &mut self,
        param_name: &str,
        gradient: &dyn ArrayProtocol,
        learningrate: f64,
    ) -> Result<(), crate::error::CoreError> {
        // Parse parameter name: layer_index.parameter_name (e.g., "0.weights", "1.bias")
        let parts: Vec<&str> = param_name.split('.').collect();
        if parts.len() != 2 {
            return Err(crate::error::CoreError::ValueError(
                crate::error::ErrorContext::new(format!(
                    "Invalid parameter name format. Expected 'layer_index.param_name', got: {param_name}"
                )),
            ));
        }

        let layer_index: usize = parts[0].parse().map_err(|_| {
            crate::error::CoreError::ValueError(crate::error::ErrorContext::new(format!(
                "Invalid layer index: {layer_idx}",
                layer_idx = parts[0]
            )))
        })?;

        let param_name = parts[1];

        if layer_index >= self.layers.len() {
            return Err(crate::error::CoreError::ValueError(
                crate::error::ErrorContext::new(format!(
                    "Layer index {layer_index} out of bounds (model has {num_layers} layers)",
                    num_layers = self.layers.len()
                )),
            ));
        }

        // Get the current parameter value
        let layer = &mut self.layers[layer_index];
        let current_params = layer.parameters();
        let param_names = layer.parameter_names();

        // Find the parameter by name
        let param_idx = param_names
            .iter()
            .position(|name| name == param_name)
            .ok_or_else(|| {
                crate::error::CoreError::ValueError(crate::error::ErrorContext::new(format!(
                    "Parameter '{param_name}' not found in layer {layer_index}"
                )))
            })?;

        // Perform gradient descent update: param = param - learningrate * gradient
        let current_param = &current_params[param_idx];

        // Multiply gradient by learning _rate
        let scaled_gradient =
            crate::array_protocol::operations::multiply_by_scalar_f64(gradient, learningrate)
                .map_err(|e| {
                    crate::error::CoreError::ComputationError(crate::error::ErrorContext::new(
                        format!("Failed to scale gradient: {e}"),
                    ))
                })?;

        // Subtract scaled gradient from current parameter
        let updated_param = crate::array_protocol::operations::subtract(
            current_param.as_ref(),
            scaled_gradient.as_ref(),
        )
        .map_err(|e| {
            crate::error::CoreError::ComputationError(crate::error::ErrorContext::new(format!(
                "Failed to update parameter: {e}"
            )))
        })?;

        // Update the parameter in the layer
        layer
            .update_parameter(param_name, updated_param)
            .map_err(|e| {
                crate::error::CoreError::ComputationError(crate::error::ErrorContext::new(format!(
                    "Failed to set parameter in layer: {e}"
                )))
            })?;

        Ok(())
    }

    /// Get all parameter names in the model with layer prefixes
    pub fn all_parameter_names(&self) -> Vec<String> {
        let mut all_names = Vec::new();
        for (layer_idx, layer) in self.layers.iter().enumerate() {
            let layer_param_names = layer.parameter_names();
            for param_name in layer_param_names {
                all_names.push(format!("{layer_idx}.{param_name}"));
            }
        }
        all_names
    }

    /// Get all parameters in the model
    pub fn all_parameters(&self) -> Vec<Box<dyn ArrayProtocol>> {
        let mut all_params = Vec::new();
        for layer in &self.layers {
            all_params.extend(layer.parameters());
        }
        all_params
    }
}

/// Example function to create a simple CNN model.
#[allow(dead_code)]
pub fn create_simple_cnn(inputshape: (usize, usize, usize), num_classes: usize) -> Sequential {
    let (height, width, channels) = inputshape;

    let mut model = Sequential::new("SimpleCNN", Vec::new());

    // First convolutional block
    model.add_layer(Box::new(Conv2D::withshape(
        "conv1",
        3,
        3, // Filter size
        channels,
        32,     // In/out channels
        (1, 1), // Stride
        (1, 1), // Padding
        true,   // With bias
        Some(ActivationFunc::ReLU),
    )));

    model.add_layer(Box::new(MaxPool2D::new(
        "pool1",
        (2, 2), // Kernel size
        None,   // Stride (default to kernel size)
        (0, 0), // Padding
    )));

    // Second convolutional block
    model.add_layer(Box::new(Conv2D::withshape(
        "conv2",
        3,
        3, // Filter size
        32,
        64,     // In/out channels
        (1, 1), // Stride
        (1, 1), // Padding
        true,   // With bias
        Some(ActivationFunc::ReLU),
    )));

    model.add_layer(Box::new(MaxPool2D::new(
        "pool2",
        (2, 2), // Kernel size
        None,   // Stride (default to kernel size)
        (0, 0), // Padding
    )));

    // Flatten layer (implemented as a Linear layer with reshape)

    // Fully connected layers
    model.add_layer(Box::new(Linear::new_random(
        "fc1",
        64 * (height / 4) * (width / 4), // Input features
        128,                             // Output features
        true,                            // With bias
        Some(ActivationFunc::ReLU),
    )));

    model.add_layer(Box::new(Dropout::new(
        "dropout", 0.5,  // Dropout rate
        None, // No fixed seed
    )));

    model.add_layer(Box::new(Linear::new_random(
        "fc2",
        128,         // Input features
        num_classes, // Output features
        true,        // With bias
        None,        // No activation (will be applied in loss function)
    )));

    model
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::array_protocol::{self, NdarrayWrapper};
    use ndarray::{Array1, Array2};

    #[test]
    fn test_linear_layer() {
        // Initialize the array protocol system
        array_protocol::init();

        // Create a linear layer
        let weights = Array2::<f64>::eye(3);
        let bias = Array1::<f64>::ones(3);

        let layer = Linear::new(
            "linear",
            Box::new(NdarrayWrapper::new(weights)),
            Some(Box::new(NdarrayWrapper::new(bias))),
            Some(ActivationFunc::ReLU),
        );

        // Create input - ensure we use a dynamic array
        // (commented out since we're not using it in the test now)
        // let x = array![[-1.0, 2.0, -3.0]].into_dyn();
        // let input = NdarrayWrapper::new(x);

        // We can't actually run the operation without proper implementation
        // Skip the actual forward pass for now
        // let output = layer.forward(&input).expect("Operation failed");

        // For now, just make sure the layer is created correctly
        assert_eq!(layer.name(), "linear");
        assert!(layer.is_training());
    }

    #[test]
    fn test_sequential_model() {
        // Initialize the array protocol system
        array_protocol::init();

        // Create a simple sequential model
        let mut model = Sequential::new("test_model", Vec::new());

        // Add linear layers
        model.add_layer(Box::new(Linear::new_random(
            "fc1",
            3,    // Input features
            2,    // Output features
            true, // With bias
            Some(ActivationFunc::ReLU),
        )));

        model.add_layer(Box::new(Linear::new_random(
            "fc2",
            2,    // Input features
            1,    // Output features
            true, // With bias
            Some(ActivationFunc::Sigmoid),
        )));

        // Just test that the model is constructed correctly
        assert_eq!(model.name(), "test_model");
        assert_eq!(model.layers().len(), 2);
        assert!(model.training);
    }

    #[test]
    fn test_simple_cnn_creation() {
        // Initialize the array protocol system
        array_protocol::init();

        // Create a simple CNN
        let model = create_simple_cnn((28, 28, 1), 10);

        // Check the model structure
        assert_eq!(model.layers().len(), 7);
        assert_eq!(model.name(), "SimpleCNN");

        // Check parameters
        let params = model.parameters();
        assert!(!params.is_empty());
    }
}

// Split out to keep neural.rs under the workspace's 2000-line-per-file limit
// (see grad.rs/grad_tests.rs for the same pattern).
#[cfg(test)]
#[path = "neural_backward_tests.rs"]
mod backward_tests;