trustformers-core 0.1.1

Core traits and utilities for TrustformeRS
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
#![allow(unused_variables)] // Adaptive computation implementation with reserved parameters

use crate::tensor::Tensor;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AdaptiveComputationConfig {
    pub max_layers: usize,
    pub min_layers: usize,
    pub halt_threshold: f32,
    pub time_penalty: f32,
    pub early_exit_threshold: f32,
    pub complexity_estimation_method: ComplexityEstimationMethod,
    pub dynamic_depth_strategy: DynamicDepthStrategy,
}

impl Default for AdaptiveComputationConfig {
    fn default() -> Self {
        Self {
            max_layers: 12,
            min_layers: 2,
            halt_threshold: 0.99,
            time_penalty: 0.01,
            early_exit_threshold: 0.95,
            complexity_estimation_method: ComplexityEstimationMethod::EntropyBased,
            dynamic_depth_strategy: DynamicDepthStrategy::ConfidenceBased,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ComplexityEstimationMethod {
    EntropyBased,
    AttentionBased,
    GradientNorm,
    LearningCurve,
    Hybrid,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DynamicDepthStrategy {
    ConfidenceBased,
    UncertaintyBased,
    ResourceConstrained,
    LatencyOptimized,
    AccuracyOptimized,
}

#[derive(Debug, Clone)]
pub struct ComputationBudget {
    pub max_flops: u64,
    pub max_memory_mb: u32,
    pub max_latency_ms: u32,
    pub remaining_flops: u64,
    pub remaining_memory_mb: u32,
    pub remaining_time_ms: u32,
}

impl ComputationBudget {
    pub fn new(max_flops: u64, max_memory_mb: u32, max_latency_ms: u32) -> Self {
        Self {
            max_flops,
            max_memory_mb,
            max_latency_ms,
            remaining_flops: max_flops,
            remaining_memory_mb: max_memory_mb,
            remaining_time_ms: max_latency_ms,
        }
    }

    pub fn can_afford(&self, flops: u64, memory_mb: u32, time_ms: u32) -> bool {
        self.remaining_flops >= flops
            && self.remaining_memory_mb >= memory_mb
            && self.remaining_time_ms >= time_ms
    }

    pub fn consume(&mut self, flops: u64, memory_mb: u32, time_ms: u32) {
        self.remaining_flops = self.remaining_flops.saturating_sub(flops);
        self.remaining_memory_mb = self.remaining_memory_mb.saturating_sub(memory_mb);
        self.remaining_time_ms = self.remaining_time_ms.saturating_sub(time_ms);
    }
}

#[derive(Debug, Clone)]
pub struct LayerMetrics {
    pub layer_id: usize,
    pub flops_estimate: u64,
    pub memory_usage_mb: u32,
    pub execution_time_ms: u32,
    pub confidence_score: f32,
    pub uncertainty_score: f32,
    pub output_entropy: f32,
}

pub trait AdaptiveComputationStrategy {
    fn should_continue(
        &self,
        layer_id: usize,
        metrics: &LayerMetrics,
        budget: &ComputationBudget,
        config: &AdaptiveComputationConfig,
    ) -> bool;

    fn estimate_remaining_cost(
        &self,
        current_layer: usize,
        total_layers: usize,
        current_metrics: &LayerMetrics,
    ) -> (u64, u32, u32); // (flops, memory_mb, time_ms)

    fn adjust_computation_path(
        &self,
        input_complexity: f32,
        available_budget: &ComputationBudget,
        config: &AdaptiveComputationConfig,
    ) -> ComputationPath;
}

#[derive(Debug, Clone)]
pub struct ComputationPath {
    pub layers_to_execute: Vec<usize>,
    pub skip_patterns: Vec<LayerSkipPattern>,
    pub early_exit_points: Vec<usize>,
    pub resource_allocation: ResourceAllocation,
}

#[derive(Debug, Clone)]
pub enum LayerSkipPattern {
    Skip,
    Approximate,
    Cached,
    Pruned,
}

#[derive(Debug, Clone)]
pub struct ResourceAllocation {
    pub memory_per_layer: HashMap<usize, u32>,
    pub compute_intensity: HashMap<usize, f32>,
    pub parallelism_factor: HashMap<usize, u32>,
}

pub struct ConfidenceBasedStrategy {
    confidence_history: Arc<RwLock<Vec<f32>>>,
    #[allow(dead_code)]
    performance_tracker: Arc<RwLock<PerformanceTracker>>,
}

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

impl ConfidenceBasedStrategy {
    pub fn new() -> Self {
        Self {
            confidence_history: Arc::new(RwLock::new(Vec::new())),
            performance_tracker: Arc::new(RwLock::new(PerformanceTracker::new())),
        }
    }
}

impl AdaptiveComputationStrategy for ConfidenceBasedStrategy {
    fn should_continue(
        &self,
        layer_id: usize,
        metrics: &LayerMetrics,
        budget: &ComputationBudget,
        config: &AdaptiveComputationConfig,
    ) -> bool {
        // Early exit if confidence is high enough
        if metrics.confidence_score >= config.early_exit_threshold {
            return false;
        }

        // Must continue if below minimum layers
        if layer_id < config.min_layers {
            return true;
        }

        // Stop if at maximum layers
        if layer_id >= config.max_layers {
            return false;
        }

        // Check resource constraints
        let (est_flops, est_memory, est_time) =
            self.estimate_remaining_cost(layer_id, config.max_layers, metrics);

        if !budget.can_afford(est_flops, est_memory, est_time) {
            return false;
        }

        // Adaptive halting criterion based on confidence growth rate
        let mut confidence_history = self
            .confidence_history
            .write()
            .expect("confidence_history lock should not be poisoned");
        confidence_history.push(metrics.confidence_score);

        if confidence_history.len() >= 3 {
            let recent_growth = confidence_history[confidence_history.len() - 1]
                - confidence_history[confidence_history.len() - 3];

            if recent_growth < 0.01 && metrics.confidence_score > config.halt_threshold {
                return false;
            }
        }

        true
    }

    fn estimate_remaining_cost(
        &self,
        current_layer: usize,
        total_layers: usize,
        current_metrics: &LayerMetrics,
    ) -> (u64, u32, u32) {
        let remaining_layers = total_layers.saturating_sub(current_layer);

        // Estimate based on current layer metrics
        let avg_flops_per_layer = current_metrics.flops_estimate;
        let avg_memory_per_layer = current_metrics.memory_usage_mb;
        let avg_time_per_layer = current_metrics.execution_time_ms;

        (
            avg_flops_per_layer * remaining_layers as u64,
            avg_memory_per_layer * remaining_layers as u32,
            avg_time_per_layer * remaining_layers as u32,
        )
    }

    fn adjust_computation_path(
        &self,
        input_complexity: f32,
        available_budget: &ComputationBudget,
        config: &AdaptiveComputationConfig,
    ) -> ComputationPath {
        let mut layers_to_execute = Vec::new();
        let mut skip_patterns = HashMap::new();
        let mut resource_allocation = ResourceAllocation {
            memory_per_layer: HashMap::new(),
            compute_intensity: HashMap::new(),
            parallelism_factor: HashMap::new(),
        };

        // Determine layers based on input complexity
        let estimated_layers = if input_complexity < 0.3 {
            config.min_layers
        } else if input_complexity < 0.7 {
            (config.min_layers + config.max_layers) / 2
        } else {
            config.max_layers
        };

        for layer_id in 0..estimated_layers {
            layers_to_execute.push(layer_id);

            // Allocate resources based on layer position and input complexity
            let layer_importance = 1.0 - (layer_id as f32 / estimated_layers as f32);
            let complexity_factor = input_complexity * layer_importance;

            resource_allocation.memory_per_layer.insert(
                layer_id,
                (available_budget.max_memory_mb as f32 / estimated_layers as f32
                    * complexity_factor) as u32,
            );

            resource_allocation.compute_intensity.insert(layer_id, complexity_factor);
            resource_allocation.parallelism_factor.insert(layer_id, 1);

            // Determine skip patterns for less important layers
            if complexity_factor < 0.3 && layer_id > config.min_layers {
                skip_patterns.insert(layer_id, LayerSkipPattern::Approximate);
            }
        }

        ComputationPath {
            layers_to_execute,
            skip_patterns: skip_patterns.into_values().collect(),
            early_exit_points: vec![estimated_layers / 2, estimated_layers * 3 / 4],
            resource_allocation,
        }
    }
}

pub struct UncertaintyBasedStrategy {
    #[allow(dead_code)]
    uncertainty_tracker: Arc<RwLock<Vec<f32>>>,
}

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

impl UncertaintyBasedStrategy {
    pub fn new() -> Self {
        Self {
            uncertainty_tracker: Arc::new(RwLock::new(Vec::new())),
        }
    }
}

impl AdaptiveComputationStrategy for UncertaintyBasedStrategy {
    fn should_continue(
        &self,
        layer_id: usize,
        metrics: &LayerMetrics,
        budget: &ComputationBudget,
        config: &AdaptiveComputationConfig,
    ) -> bool {
        // Continue if uncertainty is still high
        if metrics.uncertainty_score > 0.1 && layer_id < config.max_layers {
            let (est_flops, est_memory, est_time) =
                self.estimate_remaining_cost(layer_id, config.max_layers, metrics);
            return budget.can_afford(est_flops, est_memory, est_time);
        }

        // Must continue if below minimum
        layer_id < config.min_layers
    }

    fn estimate_remaining_cost(
        &self,
        current_layer: usize,
        total_layers: usize,
        current_metrics: &LayerMetrics,
    ) -> (u64, u32, u32) {
        let remaining_layers = total_layers.saturating_sub(current_layer);

        // Uncertainty-based scaling: higher uncertainty means more computation needed
        let uncertainty_factor = current_metrics.uncertainty_score.max(0.1);

        (
            (current_metrics.flops_estimate as f32 * remaining_layers as f32 * uncertainty_factor)
                as u64,
            (current_metrics.memory_usage_mb as f32 * remaining_layers as f32 * uncertainty_factor)
                as u32,
            (current_metrics.execution_time_ms as f32
                * remaining_layers as f32
                * uncertainty_factor) as u32,
        )
    }

    fn adjust_computation_path(
        &self,
        input_complexity: f32,
        available_budget: &ComputationBudget,
        config: &AdaptiveComputationConfig,
    ) -> ComputationPath {
        // Similar to confidence-based but focuses on uncertainty reduction
        let estimated_layers = ((input_complexity * config.max_layers as f32) as usize)
            .max(config.min_layers)
            .min(config.max_layers);

        let layers_to_execute: Vec<usize> = (0..estimated_layers).collect();
        let mut resource_allocation = ResourceAllocation {
            memory_per_layer: HashMap::new(),
            compute_intensity: HashMap::new(),
            parallelism_factor: HashMap::new(),
        };

        // Allocate more resources to layers that typically reduce uncertainty more
        for layer_id in &layers_to_execute {
            let uncertainty_reduction_factor = 1.0 + (*layer_id as f32 / estimated_layers as f32);

            resource_allocation.memory_per_layer.insert(
                *layer_id,
                (available_budget.max_memory_mb as f32 / estimated_layers as f32
                    * uncertainty_reduction_factor) as u32,
            );

            resource_allocation
                .compute_intensity
                .insert(*layer_id, uncertainty_reduction_factor);
            resource_allocation.parallelism_factor.insert(*layer_id, 1);
        }

        ComputationPath {
            layers_to_execute,
            skip_patterns: Vec::new(),
            early_exit_points: vec![estimated_layers / 3, estimated_layers * 2 / 3],
            resource_allocation,
        }
    }
}

#[derive(Debug, Clone)]
pub struct PerformanceTracker {
    layer_execution_times: HashMap<usize, Vec<u32>>,
    accuracy_by_layers: HashMap<usize, Vec<f32>>,
    resource_usage_history: Vec<(u64, u32, u32)>, // (flops, memory, time)
}

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

impl PerformanceTracker {
    pub fn new() -> Self {
        Self {
            layer_execution_times: HashMap::new(),
            accuracy_by_layers: HashMap::new(),
            resource_usage_history: Vec::new(),
        }
    }

    pub fn record_layer_execution(&mut self, layer_id: usize, execution_time_ms: u32) {
        self.layer_execution_times.entry(layer_id).or_default().push(execution_time_ms);
    }

    pub fn record_accuracy(&mut self, layers_used: usize, accuracy: f32) {
        self.accuracy_by_layers.entry(layers_used).or_default().push(accuracy);
    }

    pub fn record_resource_usage(&mut self, flops: u64, memory_mb: u32, time_ms: u32) {
        self.resource_usage_history.push((flops, memory_mb, time_ms));
    }

    pub fn get_average_execution_time(&self, layer_id: usize) -> Option<f32> {
        self.layer_execution_times
            .get(&layer_id)
            .map(|times| times.iter().sum::<u32>() as f32 / times.len() as f32)
    }

    pub fn get_accuracy_trend(&self, layers_used: usize) -> Option<f32> {
        self.accuracy_by_layers.get(&layers_used).and_then(|accuracies| {
            if accuracies.is_empty() {
                None
            } else {
                Some(accuracies.iter().sum::<f32>() / accuracies.len() as f32)
            }
        })
    }
}

pub struct AdaptiveComputationManager {
    config: AdaptiveComputationConfig,
    strategy: Box<dyn AdaptiveComputationStrategy + Send + Sync>,
    performance_tracker: Arc<RwLock<PerformanceTracker>>,
    complexity_estimator: Box<dyn ComplexityEstimator + Send + Sync>,
}

impl AdaptiveComputationManager {
    pub fn new(
        config: AdaptiveComputationConfig,
        strategy: Box<dyn AdaptiveComputationStrategy + Send + Sync>,
        complexity_estimator: Box<dyn ComplexityEstimator + Send + Sync>,
    ) -> Self {
        Self {
            config,
            strategy,
            performance_tracker: Arc::new(RwLock::new(PerformanceTracker::new())),
            complexity_estimator,
        }
    }

    pub fn plan_computation(
        &self,
        input: &Tensor,
        budget: &ComputationBudget,
    ) -> Result<ComputationPath, Box<dyn std::error::Error>> {
        // Estimate input complexity
        let input_complexity = self.complexity_estimator.estimate_complexity(input)?;

        // Generate computation path
        let path = self.strategy.adjust_computation_path(input_complexity, budget, &self.config);

        Ok(path)
    }

    pub fn should_continue_layer(
        &self,
        layer_id: usize,
        layer_output: &Tensor,
        budget: &ComputationBudget,
    ) -> Result<bool, Box<dyn std::error::Error>> {
        // Calculate layer metrics
        let metrics = self.calculate_layer_metrics(layer_id, layer_output)?;

        // Use strategy to decide
        let should_continue =
            self.strategy.should_continue(layer_id, &metrics, budget, &self.config);

        // Update performance tracking
        {
            let mut tracker = self
                .performance_tracker
                .write()
                .expect("performance_tracker lock should not be poisoned");
            tracker.record_layer_execution(layer_id, metrics.execution_time_ms);
        }

        Ok(should_continue)
    }

    fn calculate_layer_metrics(
        &self,
        layer_id: usize,
        layer_output: &Tensor,
    ) -> Result<LayerMetrics, Box<dyn std::error::Error>> {
        // Estimate computational cost
        let flops_estimate = self.estimate_flops(layer_output)?;
        let memory_usage_mb = self.estimate_memory_usage(layer_output)?;

        // Calculate confidence and uncertainty
        let confidence_score = self.calculate_confidence(layer_output)?;
        let uncertainty_score = 1.0 - confidence_score;

        // Calculate output entropy
        let output_entropy = self.calculate_entropy(layer_output)?;

        Ok(LayerMetrics {
            layer_id,
            flops_estimate,
            memory_usage_mb,
            execution_time_ms: 10, // This would be measured in practice
            confidence_score,
            uncertainty_score,
            output_entropy,
        })
    }

    fn estimate_flops(&self, tensor: &Tensor) -> Result<u64, Box<dyn std::error::Error>> {
        // Rough FLOPS estimation based on tensor size
        let size: u64 = tensor.shape().iter().map(|&x| x as u64).product();
        Ok(size * 2) // Assume roughly 2 operations per element
    }

    fn estimate_memory_usage(&self, tensor: &Tensor) -> Result<u32, Box<dyn std::error::Error>> {
        let size: u64 = tensor.shape().iter().map(|&x| x as u64).product();
        Ok((size * 4 / (1024 * 1024)) as u32) // 4 bytes per f32, convert to MB
    }

    fn calculate_confidence(&self, tensor: &Tensor) -> Result<f32, Box<dyn std::error::Error>> {
        // Simple confidence calculation based on output distribution
        let max_value = tensor.max_value()?;
        let mean_value = tensor.mean()?;

        // Extract scalar values from single-element tensors
        let max_scalar = max_value.get_float(0)?;
        let mean_scalar = mean_value.get_float(0)?;

        // Higher ratio of max to mean suggests higher confidence
        let confidence = (max_scalar / (mean_scalar + 1e-8)).min(1.0);
        Ok(confidence)
    }

    fn calculate_entropy(&self, tensor: &Tensor) -> Result<f32, Box<dyn std::error::Error>> {
        // Calculate entropy of output distribution
        let softmax_output = tensor.softmax(-1)?;
        let log_probs = softmax_output.log()?;
        let entropy_tensor = softmax_output
            .mul(&log_probs)?
            .neg()?
            .sum(Some(vec![tensor.shape().len() - 1]), false)?;

        let mean_entropy = entropy_tensor.mean()?;
        Ok(mean_entropy.get_float(0)?)
    }
}

pub trait ComplexityEstimator {
    fn estimate_complexity(&self, input: &Tensor) -> Result<f32, Box<dyn std::error::Error>>;
}

pub struct EntropyBasedComplexityEstimator;

impl ComplexityEstimator for EntropyBasedComplexityEstimator {
    fn estimate_complexity(&self, input: &Tensor) -> Result<f32, Box<dyn std::error::Error>> {
        // Calculate input entropy as complexity measure
        let input_normalized = input.softmax(-1)?;
        let log_input = input_normalized.log()?;
        let entropy_tensor = input_normalized.mul(&log_input)?.neg()?.mean()?;
        let entropy = entropy_tensor.get_float(0)?;

        // Normalize to 0-1 range
        let max_entropy = (*input.shape().last().unwrap_or(&1) as f32).ln();
        Ok((entropy / max_entropy).clamp(0.0, 1.0))
    }
}

// ===== DYNAMIC ARCHITECTURE SUPPORT =====

/// Dynamic architecture configuration supporting runtime topology modification
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DynamicArchitectureConfig {
    pub enable_dynamic_topology: bool,
    pub max_concurrent_paths: usize,
    pub path_selection_strategy: PathSelectionStrategy,
    pub architecture_search_enabled: bool,
    pub runtime_modification_enabled: bool,
    pub voting_mechanism: VotingMechanism,
    pub layer_insertion_threshold: f32,
    pub layer_removal_threshold: f32,
    pub branching_confidence_threshold: f32,
}

impl Default for DynamicArchitectureConfig {
    fn default() -> Self {
        Self {
            enable_dynamic_topology: true,
            max_concurrent_paths: 4,
            path_selection_strategy: PathSelectionStrategy::ConfidenceBased,
            architecture_search_enabled: false,
            runtime_modification_enabled: true,
            voting_mechanism: VotingMechanism::WeightedAverage,
            layer_insertion_threshold: 0.3,
            layer_removal_threshold: 0.8,
            branching_confidence_threshold: 0.5,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PathSelectionStrategy {
    ConfidenceBased,
    UncertaintyBased,
    EnsembleVoting,
    AdaptiveRouting,
    CostEffectiveness,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum VotingMechanism {
    MajorityVote,
    WeightedAverage,
    ConfidenceWeighted,
    UncertaintyWeighted,
    ExpertMixing,
}

/// Dynamic architecture manager supporting runtime topology changes
#[derive(Debug)]
pub struct DynamicArchitectureManager {
    config: DynamicArchitectureConfig,
    #[allow(dead_code)]
    active_paths: Arc<RwLock<HashMap<String, ExecutionPath>>>,
    #[allow(dead_code)]
    architecture_cache: Arc<RwLock<HashMap<String, CachedArchitecture>>>,
    performance_history: Arc<RwLock<Vec<ArchitecturePerformance>>>,
    topology_modifier: TopologyModifier,
    path_router: PathRouter,
}

impl DynamicArchitectureManager {
    pub fn new(config: DynamicArchitectureConfig) -> Self {
        Self {
            config: config.clone(),
            active_paths: Arc::new(RwLock::new(HashMap::new())),
            architecture_cache: Arc::new(RwLock::new(HashMap::new())),
            performance_history: Arc::new(RwLock::new(Vec::new())),
            topology_modifier: TopologyModifier::new(config.clone()),
            path_router: PathRouter::new(config.clone()),
        }
    }

    /// Create dynamic execution plan with multiple paths
    pub fn create_dynamic_execution_plan(
        &self,
        input: &Tensor,
        base_architecture: &ArchitectureBlueprint,
        constraints: &ComputationBudget,
    ) -> Result<DynamicExecutionPlan, Box<dyn std::error::Error>> {
        let input_complexity = self.analyze_input_complexity(input)?;

        // Generate multiple execution paths
        let execution_paths =
            self.generate_execution_paths(input_complexity, base_architecture, constraints)?;

        // Select optimal paths based on strategy
        let selected_paths = self.path_router.select_optimal_paths(
            &execution_paths,
            &self.config.path_selection_strategy,
            self.config.max_concurrent_paths,
        )?;

        Ok(DynamicExecutionPlan {
            paths: selected_paths,
            voting_mechanism: self.config.voting_mechanism.clone(),
            fallback_path: self.create_fallback_path(base_architecture)?,
            modification_points: self.identify_modification_points(base_architecture)?,
        })
    }

    /// Modify architecture topology at runtime
    pub fn modify_architecture_runtime(
        &self,
        current_state: &ExecutionState,
        performance_metrics: &LayerMetrics,
        architecture: &mut ArchitectureBlueprint,
    ) -> Result<Vec<TopologyModification>, Box<dyn std::error::Error>> {
        if !self.config.runtime_modification_enabled {
            return Ok(vec![]);
        }

        let mut modifications = Vec::new();

        // Dynamic layer insertion based on uncertainty
        if performance_metrics.uncertainty_score > self.config.layer_insertion_threshold {
            let insertion_point = self
                .topology_modifier
                .find_optimal_insertion_point(current_state, architecture)?;

            if let Some(point) = insertion_point {
                let new_layer =
                    self.topology_modifier.create_adaptive_layer(point, performance_metrics)?;

                modifications.push(TopologyModification::InsertLayer {
                    position: point,
                    layer_config: new_layer,
                });
            }
        }

        // Dynamic layer removal based on confidence
        if performance_metrics.confidence_score > self.config.layer_removal_threshold {
            let removal_candidates =
                self.topology_modifier.identify_redundant_layers(current_state, architecture)?;

            for candidate in removal_candidates {
                modifications.push(TopologyModification::RemoveLayer {
                    position: candidate,
                });
            }
        }

        // Dynamic branching based on confidence distribution
        if self.should_create_branch(performance_metrics) {
            let branch_config = self
                .topology_modifier
                .create_branch_configuration(current_state, performance_metrics)?;

            modifications.push(TopologyModification::CreateBranch {
                source_position: current_state.current_layer,
                branch_config,
            });
        }

        // Apply modifications to architecture
        for modification in &modifications {
            self.topology_modifier.apply_modification(architecture, modification)?;
        }

        Ok(modifications)
    }

    /// Execute multi-path computation with voting
    pub fn execute_multi_path(
        &self,
        input: &Tensor,
        execution_plan: &DynamicExecutionPlan,
    ) -> Result<MultiPathResult, Box<dyn std::error::Error>> {
        let start_time = Instant::now();
        let mut path_results = Vec::new();
        let mut path_metrics = Vec::new();

        // Execute all paths concurrently (simplified serial execution for now)
        for (path_id, path) in execution_plan.paths.iter().enumerate() {
            let path_start = Instant::now();
            let result = self.execute_single_path(input, path)?;
            let execution_time = path_start.elapsed();

            let metrics = PathExecutionMetrics {
                path_id,
                execution_time,
                confidence: result.confidence,
                accuracy_estimate: result.accuracy_estimate,
                resource_usage: result.resource_usage.clone(),
            };

            path_results.push(result);
            path_metrics.push(metrics);
        }

        // Combine results using voting mechanism
        let final_result = self.combine_path_results(
            &path_results,
            &path_metrics,
            &execution_plan.voting_mechanism,
        )?;

        // Record performance for future optimization
        self.record_multi_path_performance(&path_metrics, &final_result);

        Ok(MultiPathResult {
            result: final_result,
            path_metrics,
            total_execution_time: start_time.elapsed(),
            paths_executed: path_results.len(),
        })
    }

    fn analyze_input_complexity(&self, input: &Tensor) -> Result<f32, Box<dyn std::error::Error>> {
        // Compute input complexity using entropy, variance, and distribution analysis
        let entropy = self.compute_entropy(input)?;
        let variance = self.compute_variance(input)?;
        let sparsity = self.compute_sparsity(input)?;

        // Combine metrics into unified complexity score
        let complexity = (entropy * 0.4 + variance * 0.3 + (1.0 - sparsity) * 0.3).clamp(0.0, 1.0);
        Ok(complexity)
    }

    fn generate_execution_paths(
        &self,
        complexity: f32,
        architecture: &ArchitectureBlueprint,
        constraints: &ComputationBudget,
    ) -> Result<Vec<ExecutionPath>, Box<dyn std::error::Error>> {
        let mut paths = Vec::new();

        // Conservative path (minimal layers, high accuracy)
        let conservative_path = ExecutionPath {
            path_id: "conservative".to_string(),
            layers: self.select_essential_layers(architecture)?,
            skip_patterns: HashMap::new(),
            resource_allocation: self.allocate_resources_conservatively(constraints)?,
            expected_accuracy: 0.9,
            expected_latency: Duration::from_millis(50),
        };
        paths.push(conservative_path);

        // Aggressive path (maximum layers, highest accuracy)
        let aggressive_path = ExecutionPath {
            path_id: "aggressive".to_string(),
            layers: architecture.layers.clone(),
            skip_patterns: HashMap::new(),
            resource_allocation: self.allocate_resources_aggressively(constraints)?,
            expected_accuracy: 0.95,
            expected_latency: Duration::from_millis(200),
        };
        paths.push(aggressive_path);

        // Adaptive path (complexity-based selection)
        let adaptive_layers = self.select_adaptive_layers(architecture, complexity)?;
        let adaptive_path = ExecutionPath {
            path_id: "adaptive".to_string(),
            layers: adaptive_layers,
            skip_patterns: self.generate_skip_patterns(complexity)?,
            resource_allocation: self.allocate_resources_adaptively(constraints, complexity)?,
            expected_accuracy: 0.85 + complexity * 0.1,
            expected_latency: Duration::from_millis((100.0 + complexity * 100.0) as u64),
        };
        paths.push(adaptive_path);

        // Efficient path (optimized for speed)
        let efficient_path = ExecutionPath {
            path_id: "efficient".to_string(),
            layers: self.select_efficient_layers(architecture)?,
            skip_patterns: self.generate_efficiency_skip_patterns()?,
            resource_allocation: self.allocate_resources_efficiently(constraints)?,
            expected_accuracy: 0.8,
            expected_latency: Duration::from_millis(30),
        };
        paths.push(efficient_path);

        Ok(paths)
    }

    fn should_create_branch(&self, metrics: &LayerMetrics) -> bool {
        metrics.uncertainty_score > self.config.branching_confidence_threshold
            && metrics.confidence_score < 0.8 // High uncertainty, moderate confidence
    }

    fn execute_single_path(
        &self,
        input: &Tensor,
        path: &ExecutionPath,
    ) -> Result<PathResult, Box<dyn std::error::Error>> {
        // Simplified path execution - in real implementation this would
        // execute the actual neural network layers according to the path
        Ok(PathResult {
            output: input.clone(), // Placeholder
            confidence: 0.85,
            accuracy_estimate: path.expected_accuracy,
            resource_usage: ResourceUsage {
                memory_mb: 100,
                flops: 1000000,
                time_ms: path.expected_latency.as_millis() as u32,
            },
        })
    }

    fn combine_path_results(
        &self,
        results: &[PathResult],
        metrics: &[PathExecutionMetrics],
        voting_mechanism: &VotingMechanism,
    ) -> Result<CombinedResult, Box<dyn std::error::Error>> {
        match voting_mechanism {
            VotingMechanism::WeightedAverage => {
                // Weight by confidence scores
                let total_confidence: f32 = metrics.iter().map(|m| m.confidence).sum();
                let mut weighted_output = Tensor::zeros_like(&results[0].output)?;

                for (result, metric) in results.iter().zip(metrics.iter()) {
                    let weight = metric.confidence / total_confidence;
                    let scaled_output = result.output.mul_scalar(weight)?;
                    weighted_output = weighted_output.add(&scaled_output)?;
                }

                Ok(CombinedResult {
                    output: weighted_output,
                    confidence: total_confidence / results.len() as f32,
                    consensus_score: self.calculate_consensus_score(metrics),
                })
            },
            VotingMechanism::MajorityVote => {
                // Find the most confident result
                let best_idx = metrics
                    .iter()
                    .enumerate()
                    .max_by(|(_, a), (_, b)| {
                        a.confidence.partial_cmp(&b.confidence).expect("Partial comparison failed")
                    })
                    .map(|(idx, _)| idx)
                    .unwrap_or(0);

                Ok(CombinedResult {
                    output: results[best_idx].output.clone(),
                    confidence: metrics[best_idx].confidence,
                    consensus_score: self.calculate_consensus_score(metrics),
                })
            },
            _ => {
                // Fallback to weighted average
                self.combine_path_results(results, metrics, &VotingMechanism::WeightedAverage)
            },
        }
    }

    fn calculate_consensus_score(&self, metrics: &[PathExecutionMetrics]) -> f32 {
        if metrics.len() < 2 {
            return 1.0;
        }

        let mean_confidence: f32 =
            metrics.iter().map(|m| m.confidence).sum::<f32>() / metrics.len() as f32;
        let variance =
            metrics.iter().map(|m| (m.confidence - mean_confidence).powi(2)).sum::<f32>()
                / metrics.len() as f32;

        // Higher consensus when variance is low
        (1.0 - variance.sqrt()).clamp(0.0, 1.0)
    }

    fn record_multi_path_performance(
        &self,
        path_metrics: &[PathExecutionMetrics],
        result: &CombinedResult,
    ) {
        let performance = ArchitecturePerformance {
            timestamp: Instant::now(),
            path_count: path_metrics.len(),
            average_confidence: path_metrics.iter().map(|m| m.confidence).sum::<f32>()
                / path_metrics.len() as f32,
            consensus_score: result.consensus_score,
            total_resource_usage: path_metrics.iter().map(|m| m.resource_usage.memory_mb).sum(),
        };

        if let Ok(mut history) = self.performance_history.write() {
            history.push(performance);
            // Keep only recent history (last 1000 entries)
            if history.len() > 1000 {
                let drain_count = history.len() - 1000;
                history.drain(0..drain_count);
            }
        }
    }

    // Helper methods for path generation
    fn select_essential_layers(
        &self,
        arch: &ArchitectureBlueprint,
    ) -> Result<Vec<LayerConfig>, Box<dyn std::error::Error>> {
        Ok(arch.layers.iter().take(arch.layers.len() / 2).cloned().collect())
    }

    fn select_adaptive_layers(
        &self,
        arch: &ArchitectureBlueprint,
        complexity: f32,
    ) -> Result<Vec<LayerConfig>, Box<dyn std::error::Error>> {
        let layer_count =
            ((arch.layers.len() as f32 * (0.5 + complexity * 0.5)) as usize).min(arch.layers.len());
        Ok(arch.layers.iter().take(layer_count).cloned().collect())
    }

    fn select_efficient_layers(
        &self,
        arch: &ArchitectureBlueprint,
    ) -> Result<Vec<LayerConfig>, Box<dyn std::error::Error>> {
        Ok(arch.layers.iter().step_by(2).cloned().collect())
    }

    fn generate_skip_patterns(
        &self,
        complexity: f32,
    ) -> Result<HashMap<usize, LayerSkipPattern>, Box<dyn std::error::Error>> {
        let mut patterns = HashMap::new();
        if complexity < 0.3 {
            // Skip every other layer for simple inputs
            for i in (1..10).step_by(2) {
                patterns.insert(i, LayerSkipPattern::Skip);
            }
        }
        Ok(patterns)
    }

    fn generate_efficiency_skip_patterns(
        &self,
    ) -> Result<HashMap<usize, LayerSkipPattern>, Box<dyn std::error::Error>> {
        let mut patterns = HashMap::new();
        // Aggressive skipping for efficiency
        for i in 2..10 {
            if i % 3 == 0 {
                patterns.insert(i, LayerSkipPattern::Approximate);
            }
        }
        Ok(patterns)
    }

    fn allocate_resources_conservatively(
        &self,
        budget: &ComputationBudget,
    ) -> Result<ResourceAllocation, Box<dyn std::error::Error>> {
        Ok(ResourceAllocation {
            memory_per_layer: (0..5).map(|i| (i, budget.max_memory_mb / 10)).collect(),
            compute_intensity: (0..5).map(|i| (i, 0.5)).collect(),
            parallelism_factor: (0..5).map(|i| (i, 1)).collect(),
        })
    }

    fn allocate_resources_aggressively(
        &self,
        budget: &ComputationBudget,
    ) -> Result<ResourceAllocation, Box<dyn std::error::Error>> {
        Ok(ResourceAllocation {
            memory_per_layer: (0..10).map(|i| (i, budget.max_memory_mb / 5)).collect(),
            compute_intensity: (0..10).map(|i| (i, 1.0)).collect(),
            parallelism_factor: (0..10).map(|i| (i, 2)).collect(),
        })
    }

    fn allocate_resources_adaptively(
        &self,
        budget: &ComputationBudget,
        complexity: f32,
    ) -> Result<ResourceAllocation, Box<dyn std::error::Error>> {
        let layer_count = (8.0 * (0.5 + complexity * 0.5)) as usize;
        Ok(ResourceAllocation {
            memory_per_layer: (0..layer_count)
                .map(|i| {
                    (
                        i,
                        (budget.max_memory_mb as f32 * (0.5 + complexity * 0.5)) as u32
                            / layer_count as u32,
                    )
                })
                .collect(),
            compute_intensity: (0..layer_count).map(|i| (i, 0.5 + complexity * 0.5)).collect(),
            parallelism_factor: (0..layer_count)
                .map(|i| (i, 1 + (complexity * 2.0) as u32))
                .collect(),
        })
    }

    fn allocate_resources_efficiently(
        &self,
        budget: &ComputationBudget,
    ) -> Result<ResourceAllocation, Box<dyn std::error::Error>> {
        Ok(ResourceAllocation {
            memory_per_layer: (0..3).map(|i| (i, budget.max_memory_mb / 20)).collect(),
            compute_intensity: (0..3).map(|i| (i, 0.3)).collect(),
            parallelism_factor: (0..3).map(|i| (i, 4)).collect(),
        })
    }

    fn create_fallback_path(
        &self,
        arch: &ArchitectureBlueprint,
    ) -> Result<ExecutionPath, Box<dyn std::error::Error>> {
        Ok(ExecutionPath {
            path_id: "fallback".to_string(),
            layers: vec![arch.layers[0].clone()], // Minimal single layer
            skip_patterns: HashMap::new(),
            resource_allocation: ResourceAllocation {
                memory_per_layer: HashMap::from([(0, 50)]),
                compute_intensity: HashMap::from([(0, 0.1)]),
                parallelism_factor: HashMap::from([(0, 1)]),
            },
            expected_accuracy: 0.6,
            expected_latency: Duration::from_millis(10),
        })
    }

    fn identify_modification_points(
        &self,
        arch: &ArchitectureBlueprint,
    ) -> Result<Vec<ModificationPoint>, Box<dyn std::error::Error>> {
        let mut points = Vec::new();

        // Add modification points between layers
        for i in 0..arch.layers.len() - 1 {
            points.push(ModificationPoint {
                position: i,
                modification_type: ModificationType::LayerInsertion,
                confidence_threshold: 0.3,
            });
        }

        // Add branching points at quarter, half, and three-quarter positions
        for &fraction in &[0.25, 0.5, 0.75] {
            let position = (arch.layers.len() as f32 * fraction) as usize;
            points.push(ModificationPoint {
                position,
                modification_type: ModificationType::BranchingPoint,
                confidence_threshold: 0.5,
            });
        }

        Ok(points)
    }

    // Tensor operation helpers
    fn compute_entropy(&self, tensor: &Tensor) -> Result<f32, Box<dyn std::error::Error>> {
        // Simplified entropy calculation
        Ok(0.5) // Placeholder
    }

    fn compute_variance(&self, tensor: &Tensor) -> Result<f32, Box<dyn std::error::Error>> {
        // Simplified variance calculation
        Ok(0.3) // Placeholder
    }

    fn compute_sparsity(&self, tensor: &Tensor) -> Result<f32, Box<dyn std::error::Error>> {
        // Simplified sparsity calculation
        Ok(0.2) // Placeholder
    }
}

// Supporting data structures for dynamic architectures

#[derive(Debug, Clone)]
pub struct ArchitectureBlueprint {
    pub layers: Vec<LayerConfig>,
    pub connections: Vec<ConnectionConfig>,
    pub metadata: ArchitectureMetadata,
}

#[derive(Debug, Clone)]
pub struct LayerConfig {
    pub layer_id: usize,
    pub layer_type: LayerType,
    pub parameters: HashMap<String, f32>,
    pub optional: bool,
}

#[derive(Debug, Clone)]
pub enum LayerType {
    Attention,
    FeedForward,
    Normalization,
    Embedding,
    Output,
    Custom(String),
}

#[derive(Debug, Clone)]
pub struct ConnectionConfig {
    pub from_layer: usize,
    pub to_layer: usize,
    pub connection_type: ConnectionType,
}

#[derive(Debug, Clone)]
pub enum ConnectionType {
    Sequential,
    Residual,
    Attention,
    Custom(String),
}

#[derive(Debug, Clone)]
pub struct ArchitectureMetadata {
    pub name: String,
    pub version: String,
    pub parameter_count: u64,
    pub memory_footprint_mb: u32,
}

#[derive(Debug, Clone)]
pub struct ExecutionPath {
    pub path_id: String,
    pub layers: Vec<LayerConfig>,
    pub skip_patterns: HashMap<usize, LayerSkipPattern>,
    pub resource_allocation: ResourceAllocation,
    pub expected_accuracy: f32,
    pub expected_latency: Duration,
}

#[derive(Debug)]
pub struct DynamicExecutionPlan {
    pub paths: Vec<ExecutionPath>,
    pub voting_mechanism: VotingMechanism,
    pub fallback_path: ExecutionPath,
    pub modification_points: Vec<ModificationPoint>,
}

#[derive(Debug)]
pub struct ExecutionState {
    pub current_layer: usize,
    pub intermediate_results: HashMap<usize, Tensor>,
    pub execution_metrics: Vec<LayerMetrics>,
    pub resource_usage: ResourceUsage,
}

#[derive(Debug, Clone)]
pub struct ResourceUsage {
    pub memory_mb: u32,
    pub flops: u64,
    pub time_ms: u32,
}

#[derive(Debug)]
pub enum TopologyModification {
    InsertLayer {
        position: usize,
        layer_config: LayerConfig,
    },
    RemoveLayer {
        position: usize,
    },
    CreateBranch {
        source_position: usize,
        branch_config: BranchConfig,
    },
    ModifyConnection {
        connection: ConnectionConfig,
    },
}

#[derive(Debug, Clone)]
pub struct BranchConfig {
    pub branch_layers: Vec<LayerConfig>,
    pub merge_strategy: MergeStrategy,
    pub condition: BranchCondition,
}

#[derive(Debug, Clone)]
pub enum MergeStrategy {
    Concatenation,
    Average,
    WeightedSum,
    Attention,
}

#[derive(Debug, Clone)]
pub enum BranchCondition {
    Always,
    ConfidenceThreshold(f32),
    UncertaintyThreshold(f32),
    Custom(String),
}

#[derive(Debug)]
pub struct ModificationPoint {
    pub position: usize,
    pub modification_type: ModificationType,
    pub confidence_threshold: f32,
}

#[derive(Debug)]
pub enum ModificationType {
    LayerInsertion,
    LayerRemoval,
    BranchingPoint,
    ConnectionModification,
}

#[derive(Debug)]
pub struct TopologyModifier {
    #[allow(dead_code)]
    config: DynamicArchitectureConfig,
}

impl TopologyModifier {
    pub fn new(config: DynamicArchitectureConfig) -> Self {
        Self { config }
    }

    pub fn find_optimal_insertion_point(
        &self,
        state: &ExecutionState,
        architecture: &ArchitectureBlueprint,
    ) -> Result<Option<usize>, Box<dyn std::error::Error>> {
        // Find the best position to insert a new layer based on current execution state
        if state.current_layer > 0 && state.current_layer < architecture.layers.len() {
            Ok(Some(state.current_layer))
        } else {
            Ok(None)
        }
    }

    pub fn create_adaptive_layer(
        &self,
        position: usize,
        metrics: &LayerMetrics,
    ) -> Result<LayerConfig, Box<dyn std::error::Error>> {
        // Create a new layer configuration based on current metrics
        let layer_type = if metrics.uncertainty_score > 0.7 {
            LayerType::Attention // Add attention for high uncertainty
        } else {
            LayerType::FeedForward // Add feedforward for general improvement
        };

        Ok(LayerConfig {
            layer_id: position * 1000, // Unique ID for inserted layers
            layer_type,
            parameters: HashMap::from([
                ("hidden_size".to_string(), 512.0),
                ("dropout".to_string(), 0.1),
            ]),
            optional: true,
        })
    }

    pub fn identify_redundant_layers(
        &self,
        state: &ExecutionState,
        architecture: &ArchitectureBlueprint,
    ) -> Result<Vec<usize>, Box<dyn std::error::Error>> {
        let mut redundant = Vec::new();

        // Identify layers that can be safely removed
        for (i, layer) in architecture.layers.iter().enumerate() {
            if layer.optional
                && state.execution_metrics.get(i).is_some_and(|m| m.confidence_score > 0.9)
            {
                redundant.push(i);
            }
        }

        Ok(redundant)
    }

    pub fn create_branch_configuration(
        &self,
        state: &ExecutionState,
        metrics: &LayerMetrics,
    ) -> Result<BranchConfig, Box<dyn std::error::Error>> {
        let branch_layers = vec![LayerConfig {
            layer_id: 9000, // Branch layer ID
            layer_type: LayerType::Attention,
            parameters: HashMap::from([("heads".to_string(), 8.0)]),
            optional: true,
        }];

        Ok(BranchConfig {
            branch_layers,
            merge_strategy: MergeStrategy::WeightedSum,
            condition: BranchCondition::UncertaintyThreshold(metrics.uncertainty_score),
        })
    }

    pub fn apply_modification(
        &self,
        architecture: &mut ArchitectureBlueprint,
        modification: &TopologyModification,
    ) -> Result<(), Box<dyn std::error::Error>> {
        match modification {
            TopologyModification::InsertLayer {
                position,
                layer_config,
            } => {
                if *position <= architecture.layers.len() {
                    architecture.layers.insert(*position, layer_config.clone());
                }
            },
            TopologyModification::RemoveLayer { position } => {
                if *position < architecture.layers.len() {
                    architecture.layers.remove(*position);
                }
            },
            TopologyModification::CreateBranch {
                source_position,
                branch_config,
            } => {
                // Add branch layers after source position
                for (i, layer) in branch_config.branch_layers.iter().enumerate() {
                    architecture.layers.insert(source_position + i + 1, layer.clone());
                }
            },
            TopologyModification::ModifyConnection { connection } => {
                // Add or modify connections
                architecture.connections.push(connection.clone());
            },
        }
        Ok(())
    }
}

#[derive(Debug)]
pub struct PathRouter {
    #[allow(dead_code)]
    config: DynamicArchitectureConfig,
}

impl PathRouter {
    pub fn new(config: DynamicArchitectureConfig) -> Self {
        Self { config }
    }

    pub fn select_optimal_paths(
        &self,
        paths: &[ExecutionPath],
        strategy: &PathSelectionStrategy,
        max_paths: usize,
    ) -> Result<Vec<ExecutionPath>, Box<dyn std::error::Error>> {
        let mut selected = match strategy {
            PathSelectionStrategy::ConfidenceBased => {
                let mut sorted_paths = paths.to_vec();
                sorted_paths.sort_by(|a, b| {
                    b.expected_accuracy
                        .partial_cmp(&a.expected_accuracy)
                        .expect("Partial comparison failed")
                });
                sorted_paths
            },
            PathSelectionStrategy::CostEffectiveness => {
                let mut sorted_paths = paths.to_vec();
                sorted_paths.sort_by(|a, b| {
                    let cost_a = a.expected_latency.as_millis() as f32 / a.expected_accuracy;
                    let cost_b = b.expected_latency.as_millis() as f32 / b.expected_accuracy;
                    cost_a.partial_cmp(&cost_b).expect("Partial comparison failed")
                });
                sorted_paths
            },
            _ => paths.to_vec(),
        };

        selected.truncate(max_paths);
        Ok(selected)
    }
}

#[derive(Debug)]
pub struct PathResult {
    pub output: Tensor,
    pub confidence: f32,
    pub accuracy_estimate: f32,
    pub resource_usage: ResourceUsage,
}

#[derive(Debug)]
pub struct PathExecutionMetrics {
    pub path_id: usize,
    pub execution_time: Duration,
    pub confidence: f32,
    pub accuracy_estimate: f32,
    pub resource_usage: ResourceUsage,
}

#[derive(Debug)]
pub struct CombinedResult {
    pub output: Tensor,
    pub confidence: f32,
    pub consensus_score: f32,
}

#[derive(Debug)]
pub struct MultiPathResult {
    pub result: CombinedResult,
    pub path_metrics: Vec<PathExecutionMetrics>,
    pub total_execution_time: Duration,
    pub paths_executed: usize,
}

#[derive(Debug)]
pub struct ArchitecturePerformance {
    pub timestamp: Instant,
    pub path_count: usize,
    pub average_confidence: f32,
    pub consensus_score: f32,
    pub total_resource_usage: u32,
}

#[derive(Debug)]
pub struct CachedArchitecture {
    pub blueprint: ArchitectureBlueprint,
    pub performance_history: Vec<ArchitecturePerformance>,
    pub last_used: Instant,
}

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

    // ── ComputationBudget tests ──

    #[test]
    fn test_computation_budget() {
        let mut budget = ComputationBudget::new(1000, 100, 50);

        assert!(budget.can_afford(500, 50, 25));
        budget.consume(500, 50, 25);

        assert_eq!(budget.remaining_flops, 500);
        assert_eq!(budget.remaining_memory_mb, 50);
        assert_eq!(budget.remaining_time_ms, 25);

        assert!(!budget.can_afford(600, 60, 30));
    }

    #[test]
    fn test_budget_saturating_consume() {
        let mut budget = ComputationBudget::new(100, 10, 5);
        budget.consume(200, 20, 10);
        assert_eq!(budget.remaining_flops, 0);
        assert_eq!(budget.remaining_memory_mb, 0);
        assert_eq!(budget.remaining_time_ms, 0);
    }

    #[test]
    fn test_budget_can_afford_exact() {
        let budget = ComputationBudget::new(100, 10, 5);
        assert!(budget.can_afford(100, 10, 5));
    }

    #[test]
    fn test_budget_can_afford_fails_on_flops() {
        let budget = ComputationBudget::new(100, 10, 5);
        assert!(!budget.can_afford(101, 10, 5));
    }

    #[test]
    fn test_budget_can_afford_fails_on_memory() {
        let budget = ComputationBudget::new(100, 10, 5);
        assert!(!budget.can_afford(100, 11, 5));
    }

    #[test]
    fn test_budget_can_afford_fails_on_time() {
        let budget = ComputationBudget::new(100, 10, 5);
        assert!(!budget.can_afford(100, 10, 6));
    }

    #[test]
    fn test_budget_zero_budget() {
        let budget = ComputationBudget::new(0, 0, 0);
        assert!(budget.can_afford(0, 0, 0));
        assert!(!budget.can_afford(1, 0, 0));
    }

    // ── AdaptiveComputationConfig tests ──

    #[test]
    fn test_adaptive_config_default() {
        let config = AdaptiveComputationConfig::default();
        assert_eq!(config.max_layers, 12);
        assert_eq!(config.min_layers, 2);
        assert!((config.halt_threshold - 0.99).abs() < 1e-6);
        assert!((config.time_penalty - 0.01).abs() < 1e-6);
        assert!((config.early_exit_threshold - 0.95).abs() < 1e-6);
    }

    #[test]
    fn test_adaptive_config_clone() {
        let config = AdaptiveComputationConfig::default();
        let cloned = config.clone();
        assert_eq!(config.max_layers, cloned.max_layers);
        assert_eq!(config.min_layers, cloned.min_layers);
    }

    // ── ConfidenceBasedStrategy tests ──

    #[test]
    fn test_confidence_based_strategy() {
        let strategy = ConfidenceBasedStrategy::new();
        let config = AdaptiveComputationConfig::default();
        let budget = ComputationBudget::new(10000, 1000, 100);

        let metrics = LayerMetrics {
            layer_id: 0,
            flops_estimate: 100,
            memory_usage_mb: 10,
            execution_time_ms: 5,
            confidence_score: 0.5,
            uncertainty_score: 0.5,
            output_entropy: 1.0,
        };

        assert!(strategy.should_continue(0, &metrics, &budget, &config));

        let high_confidence_metrics = LayerMetrics {
            confidence_score: 0.98,
            ..metrics
        };

        assert!(!strategy.should_continue(5, &high_confidence_metrics, &budget, &config));
    }

    #[test]
    fn test_confidence_strategy_respects_min_layers() {
        let strategy = ConfidenceBasedStrategy::new();
        let config = AdaptiveComputationConfig {
            min_layers: 5,
            ..AdaptiveComputationConfig::default()
        };
        let budget = ComputationBudget::new(10000, 1000, 100);

        let metrics = LayerMetrics {
            layer_id: 0,
            flops_estimate: 100,
            memory_usage_mb: 10,
            execution_time_ms: 5,
            confidence_score: 0.8,
            uncertainty_score: 0.2,
            output_entropy: 0.5,
        };

        // Below min_layers, must continue
        assert!(strategy.should_continue(2, &metrics, &budget, &config));
    }

    #[test]
    fn test_confidence_strategy_stops_at_max_layers() {
        let strategy = ConfidenceBasedStrategy::new();
        let config = AdaptiveComputationConfig {
            max_layers: 6,
            ..AdaptiveComputationConfig::default()
        };
        let budget = ComputationBudget::new(10000, 1000, 100);

        let metrics = LayerMetrics {
            layer_id: 6,
            flops_estimate: 100,
            memory_usage_mb: 10,
            execution_time_ms: 5,
            confidence_score: 0.5,
            uncertainty_score: 0.5,
            output_entropy: 1.0,
        };

        assert!(!strategy.should_continue(6, &metrics, &budget, &config));
    }

    #[test]
    fn test_confidence_strategy_stops_on_budget_exhaustion() {
        let strategy = ConfidenceBasedStrategy::new();
        let config = AdaptiveComputationConfig::default();
        let budget = ComputationBudget::new(10, 1, 1); // Very tight budget

        let metrics = LayerMetrics {
            layer_id: 5,
            flops_estimate: 100,
            memory_usage_mb: 10,
            execution_time_ms: 5,
            confidence_score: 0.5,
            uncertainty_score: 0.5,
            output_entropy: 1.0,
        };

        assert!(!strategy.should_continue(5, &metrics, &budget, &config));
    }

    #[test]
    fn test_confidence_strategy_estimate_remaining_cost() {
        let strategy = ConfidenceBasedStrategy::new();
        let metrics = LayerMetrics {
            layer_id: 3,
            flops_estimate: 100,
            memory_usage_mb: 10,
            execution_time_ms: 5,
            confidence_score: 0.5,
            uncertainty_score: 0.5,
            output_entropy: 1.0,
        };

        let (flops, mem, time) = strategy.estimate_remaining_cost(3, 10, &metrics);
        assert_eq!(flops, 700); // 7 remaining * 100
        assert_eq!(mem, 70); // 7 * 10
        assert_eq!(time, 35); // 7 * 5
    }

    #[test]
    fn test_confidence_strategy_adjust_computation_path_low_complexity() {
        let strategy = ConfidenceBasedStrategy::new();
        let config = AdaptiveComputationConfig {
            min_layers: 2,
            max_layers: 12,
            ..AdaptiveComputationConfig::default()
        };
        let budget = ComputationBudget::new(100000, 10000, 1000);

        let path = strategy.adjust_computation_path(0.1, &budget, &config);
        // Low complexity => min_layers
        assert_eq!(path.layers_to_execute.len(), config.min_layers);
    }

    #[test]
    fn test_confidence_strategy_adjust_computation_path_high_complexity() {
        let strategy = ConfidenceBasedStrategy::new();
        let config = AdaptiveComputationConfig {
            min_layers: 2,
            max_layers: 12,
            ..AdaptiveComputationConfig::default()
        };
        let budget = ComputationBudget::new(100000, 10000, 1000);

        let path = strategy.adjust_computation_path(0.9, &budget, &config);
        assert_eq!(path.layers_to_execute.len(), config.max_layers);
    }

    // ── UncertaintyBasedStrategy tests ──

    #[test]
    fn test_uncertainty_strategy_continues_on_high_uncertainty() {
        let strategy = UncertaintyBasedStrategy::new();
        let config = AdaptiveComputationConfig::default();
        let budget = ComputationBudget::new(100000, 10000, 1000);

        let metrics = LayerMetrics {
            layer_id: 5,
            flops_estimate: 100,
            memory_usage_mb: 10,
            execution_time_ms: 5,
            confidence_score: 0.3,
            uncertainty_score: 0.7,
            output_entropy: 1.0,
        };

        assert!(strategy.should_continue(5, &metrics, &budget, &config));
    }

    #[test]
    fn test_uncertainty_strategy_stops_on_low_uncertainty() {
        let strategy = UncertaintyBasedStrategy::new();
        let config = AdaptiveComputationConfig {
            min_layers: 2,
            ..AdaptiveComputationConfig::default()
        };
        let budget = ComputationBudget::new(100000, 10000, 1000);

        let metrics = LayerMetrics {
            layer_id: 5,
            flops_estimate: 100,
            memory_usage_mb: 10,
            execution_time_ms: 5,
            confidence_score: 0.95,
            uncertainty_score: 0.05,
            output_entropy: 0.1,
        };

        assert!(!strategy.should_continue(5, &metrics, &budget, &config));
    }

    #[test]
    fn test_uncertainty_strategy_adjust_path() {
        let strategy = UncertaintyBasedStrategy::new();
        let config = AdaptiveComputationConfig {
            min_layers: 2,
            max_layers: 10,
            ..AdaptiveComputationConfig::default()
        };
        let budget = ComputationBudget::new(100000, 10000, 1000);

        let path = strategy.adjust_computation_path(0.5, &budget, &config);
        assert!(path.layers_to_execute.len() >= config.min_layers);
        assert!(path.layers_to_execute.len() <= config.max_layers);
    }

    // ── PerformanceTracker tests ──

    #[test]
    fn test_performance_tracker() {
        let mut tracker = PerformanceTracker::new();

        tracker.record_layer_execution(0, 10);
        tracker.record_layer_execution(0, 20);
        tracker.record_accuracy(5, 0.85);
        tracker.record_accuracy(5, 0.90);

        assert_eq!(tracker.get_average_execution_time(0), Some(15.0));
        assert_eq!(tracker.get_accuracy_trend(5), Some(0.875));
    }

    #[test]
    fn test_performance_tracker_no_data() {
        let tracker = PerformanceTracker::new();
        assert_eq!(tracker.get_average_execution_time(0), None);
        assert_eq!(tracker.get_accuracy_trend(0), None);
    }

    #[test]
    fn test_performance_tracker_record_resource_usage() {
        let mut tracker = PerformanceTracker::new();
        tracker.record_resource_usage(1000, 50, 10);
        tracker.record_resource_usage(2000, 100, 20);
        assert_eq!(tracker.resource_usage_history.len(), 2);
    }

    #[test]
    fn test_performance_tracker_multiple_layers() {
        let mut tracker = PerformanceTracker::new();
        tracker.record_layer_execution(0, 10);
        tracker.record_layer_execution(1, 20);
        tracker.record_layer_execution(2, 30);

        assert_eq!(tracker.get_average_execution_time(0), Some(10.0));
        assert_eq!(tracker.get_average_execution_time(1), Some(20.0));
        assert_eq!(tracker.get_average_execution_time(2), Some(30.0));
    }

    #[test]
    fn test_performance_tracker_default() {
        let tracker = PerformanceTracker::default();
        assert!(tracker.layer_execution_times.is_empty());
        assert!(tracker.accuracy_by_layers.is_empty());
        assert!(tracker.resource_usage_history.is_empty());
    }

    // ── EntropyBasedComplexityEstimator tests ──

    #[test]
    fn test_entropy_complexity_estimator() {
        let estimator = EntropyBasedComplexityEstimator;

        let low_entropy_input = Tensor::from_vec(vec![10.0, 0.0, 0.0, 0.0, 0.0], &[1, 5])
            .expect("Tensor from_vec failed");

        let high_entropy_input = Tensor::ones(&[1, 5]).expect("Failed to create ones tensor");

        let low_complexity = estimator
            .estimate_complexity(&low_entropy_input)
            .expect("operation failed in test");
        let high_complexity = estimator
            .estimate_complexity(&high_entropy_input)
            .expect("operation failed in test");

        assert!(high_complexity > low_complexity);
        assert!((0.0..=1.0).contains(&low_complexity));
        assert!((0.0..=1.0).contains(&high_complexity));
    }

    // ── ComputationPath tests ──

    #[test]
    fn test_computation_path_structure() {
        let path = ComputationPath {
            layers_to_execute: vec![0, 1, 2, 3],
            skip_patterns: vec![LayerSkipPattern::Approximate],
            early_exit_points: vec![2],
            resource_allocation: ResourceAllocation {
                memory_per_layer: HashMap::new(),
                compute_intensity: HashMap::new(),
                parallelism_factor: HashMap::new(),
            },
        };
        assert_eq!(path.layers_to_execute.len(), 4);
        assert_eq!(path.skip_patterns.len(), 1);
        assert_eq!(path.early_exit_points, vec![2]);
    }

    // ── DynamicArchitectureConfig tests ──

    #[test]
    fn test_dynamic_architecture_config_default() {
        let config = DynamicArchitectureConfig::default();
        assert!(config.enable_dynamic_topology);
        assert_eq!(config.max_concurrent_paths, 4);
        assert!((config.layer_insertion_threshold - 0.3).abs() < 1e-6);
        assert!((config.layer_removal_threshold - 0.8).abs() < 1e-6);
        assert!((config.branching_confidence_threshold - 0.5).abs() < 1e-6);
    }

    #[test]
    fn test_dynamic_architecture_config_clone() {
        let config = DynamicArchitectureConfig::default();
        let cloned = config.clone();
        assert_eq!(config.max_concurrent_paths, cloned.max_concurrent_paths);
        assert_eq!(
            config.enable_dynamic_topology,
            cloned.enable_dynamic_topology
        );
    }

    // ── LayerSkipPattern tests ──

    #[test]
    fn test_layer_skip_pattern_variants() {
        let skip = LayerSkipPattern::Skip;
        let approx = LayerSkipPattern::Approximate;
        let cached = LayerSkipPattern::Cached;
        let pruned = LayerSkipPattern::Pruned;

        // Clone and Debug
        let _skip_clone = skip.clone();
        let _debug = format!("{:?}", approx);
        let _debug2 = format!("{:?}", cached);
        let _debug3 = format!("{:?}", pruned);
    }

    // ── LayerMetrics tests ──

    #[test]
    fn test_layer_metrics_clone() {
        let metrics = LayerMetrics {
            layer_id: 0,
            flops_estimate: 1000,
            memory_usage_mb: 50,
            execution_time_ms: 10,
            confidence_score: 0.8,
            uncertainty_score: 0.2,
            output_entropy: 0.5,
        };
        let cloned = metrics.clone();
        assert_eq!(metrics.layer_id, cloned.layer_id);
        assert_eq!(metrics.flops_estimate, cloned.flops_estimate);
        assert!((metrics.confidence_score - cloned.confidence_score).abs() < 1e-6);
    }

    // ── ResourceAllocation tests ──

    #[test]
    fn test_resource_allocation_empty() {
        let alloc = ResourceAllocation {
            memory_per_layer: HashMap::new(),
            compute_intensity: HashMap::new(),
            parallelism_factor: HashMap::new(),
        };
        assert!(alloc.memory_per_layer.is_empty());
        assert!(alloc.compute_intensity.is_empty());
        assert!(alloc.parallelism_factor.is_empty());
    }

    #[test]
    fn test_resource_allocation_with_data() {
        let mut alloc = ResourceAllocation {
            memory_per_layer: HashMap::new(),
            compute_intensity: HashMap::new(),
            parallelism_factor: HashMap::new(),
        };
        alloc.memory_per_layer.insert(0, 100);
        alloc.compute_intensity.insert(0, 0.8);
        alloc.parallelism_factor.insert(0, 4);

        assert_eq!(alloc.memory_per_layer.get(&0), Some(&100));
        assert_eq!(alloc.parallelism_factor.get(&0), Some(&4));
    }

    // ── Complexity estimation method / strategy enums ──

    #[test]
    fn test_complexity_estimation_method_variants() {
        let _a = ComplexityEstimationMethod::EntropyBased;
        let _b = ComplexityEstimationMethod::AttentionBased;
        let _c = ComplexityEstimationMethod::GradientNorm;
        let _d = ComplexityEstimationMethod::LearningCurve;
        let _e = ComplexityEstimationMethod::Hybrid;
    }

    #[test]
    fn test_dynamic_depth_strategy_variants() {
        let _a = DynamicDepthStrategy::ConfidenceBased;
        let _b = DynamicDepthStrategy::UncertaintyBased;
        let _c = DynamicDepthStrategy::ResourceConstrained;
        let _d = DynamicDepthStrategy::LatencyOptimized;
        let _e = DynamicDepthStrategy::AccuracyOptimized;
    }

    #[test]
    fn test_path_selection_strategy_variants() {
        let _a = PathSelectionStrategy::ConfidenceBased;
        let _b = PathSelectionStrategy::UncertaintyBased;
        let _c = PathSelectionStrategy::EnsembleVoting;
        let _d = PathSelectionStrategy::AdaptiveRouting;
        let _e = PathSelectionStrategy::CostEffectiveness;
    }

    #[test]
    fn test_voting_mechanism_variants() {
        let _a = VotingMechanism::MajorityVote;
        let _b = VotingMechanism::WeightedAverage;
        let _c = VotingMechanism::ConfidenceWeighted;
        let _d = VotingMechanism::UncertaintyWeighted;
        let _e = VotingMechanism::ExpertMixing;
    }
}