abaddon 0.2.0-rc.1

Blazingly fast LLM inference engine - The Destroyer renders judgment
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
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
//! GPU-accelerated holographic tensor reconstruction.
//!
//! This module provides CUDA-accelerated reconstruction for HoloTensor format,
//! enabling progressive loading of neural network weights with quality proportional
//! to fragments loaded.
//!
//! ## Encoding Schemes
//!
//! ### Spectral (SHE)
//! Uses 2D IDCT (Inverse Discrete Cosine Transform) for reconstruction.
//! Each fragment contributes frequency coefficients that are accumulated
//! before final inverse transform.
//!
//! ### Random Projection (RPH)
//! Uses least-squares reconstruction from random projections.
//! Projections are accumulated and normalized for final output.
//!
//! ### Low-Rank Distributed (LRDF)
//! Uses batched outer products for rank-1 component accumulation.
//! Each fragment contributes (u, s, v) triplets that sum to the output.
//!
//! ## Architecture
//!
//! ```text
//! โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
//! โ”‚                    HoloTensor GPU Reconstruction                             โ”‚
//! โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
//! โ”‚                                                                             โ”‚
//! โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”              โ”‚
//! โ”‚  โ”‚Fragment 0โ”‚    โ”‚Fragment 1โ”‚    โ”‚Fragment 2โ”‚    โ”‚Fragment Nโ”‚              โ”‚
//! โ”‚  โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”˜              โ”‚
//! โ”‚       โ”‚               โ”‚               โ”‚               โ”‚                     โ”‚
//! โ”‚       โ–ผ               โ–ผ               โ–ผ               โ–ผ                     โ”‚
//! โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”           โ”‚
//! โ”‚  โ”‚              Accumulator Buffer (GPU)                        โ”‚           โ”‚
//! โ”‚  โ”‚  Spectral: DCT coefficients accumulating                     โ”‚           โ”‚
//! โ”‚  โ”‚  RPH: Projection sum accumulating                            โ”‚           โ”‚
//! โ”‚  โ”‚  LRDF: Rank-1 matrices accumulating                          โ”‚           โ”‚
//! โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜           โ”‚
//! โ”‚                               โ”‚                                             โ”‚
//! โ”‚                               โ–ผ (when quality threshold reached)            โ”‚
//! โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”           โ”‚
//! โ”‚  โ”‚              GPU Reconstruction Kernel                       โ”‚           โ”‚
//! โ”‚  โ”‚  Spectral: IDCT-2D                                           โ”‚           โ”‚
//! โ”‚  โ”‚  RPH: Final normalization                                    โ”‚           โ”‚
//! โ”‚  โ”‚  LRDF: No finalization needed                                โ”‚           โ”‚
//! โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜           โ”‚
//! โ”‚                               โ”‚                                             โ”‚
//! โ”‚                               โ–ผ                                             โ”‚
//! โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”           โ”‚
//! โ”‚  โ”‚              Reconstructed Tensor (GPU memory)               โ”‚           โ”‚
//! โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜           โ”‚
//! โ”‚                                                                             โ”‚
//! โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
//! ```

/// CUDA-accelerated holographic tensor reconstruction.
#[cfg(feature = "cuda")]
pub mod cuda {
    use std::sync::Arc;

    use cudarc::driver::{CudaDevice, CudaSlice, DeviceSlice, LaunchAsync, LaunchConfig};
    use cudarc::nvrtc::Ptx;
    use haagenti::holotensor::{HoloFragment, HoloTensorHeader, HolographicEncoding, QualityCurve};

    // Haagenti's FFT-capable DCT context (when haagenti-gpu feature is enabled)
    #[cfg(feature = "haagenti-gpu")]
    use haagenti_cuda::dct_gpu::GpuDctContext;

    // ==================== Error Types ====================

    /// Errors from GPU holographic operations.
    #[derive(Debug, thiserror::Error)]
    pub enum GpuHoloError {
        /// CUDA device initialization failed.
        #[error("Failed to initialize CUDA device {device_id}: {message}")]
        DeviceInit {
            /// CUDA device ID.
            device_id: usize,
            /// Error message.
            message: String,
        },

        /// Kernel loading failed.
        #[error("Failed to load kernel: {message}")]
        KernelLoad {
            /// Error message.
            message: String,
        },

        /// Kernel not loaded.
        #[error("Kernel not loaded: {kernel}")]
        KernelNotLoaded {
            /// Kernel name.
            kernel: String,
        },

        /// Kernel execution failed.
        #[error("Kernel execution failed: {message}")]
        KernelExec {
            /// Error message.
            message: String,
        },

        /// Memory allocation failed.
        #[error("Memory allocation failed: {message}")]
        MemoryAlloc {
            /// Error message.
            message: String,
        },

        /// Memory copy failed.
        #[error("Memory copy failed: {message}")]
        MemoryCopy {
            /// Error message.
            message: String,
        },

        /// Synchronization failed.
        #[error("Synchronization failed: {message}")]
        Synchronize {
            /// Error message.
            message: String,
        },

        /// Invalid input data.
        #[error("Invalid input: {message}")]
        InvalidInput {
            /// Error message.
            message: String,
        },

        /// Insufficient fragments for reconstruction.
        #[error("Insufficient fragments: need at least {min_required}, have {available}")]
        InsufficientFragments {
            /// Minimum fragments required.
            min_required: u16,
            /// Number of fragments available.
            available: u16,
        },

        /// Unsupported encoding.
        #[error("Unsupported encoding: {encoding:?}")]
        UnsupportedEncoding {
            /// The unsupported encoding type.
            encoding: HolographicEncoding,
        },

        /// Fragment decode error.
        #[error("Fragment decode error: {message}")]
        FragmentDecode {
            /// Error message.
            message: String,
        },

        /// Stream creation failed.
        #[error("Failed to create CUDA stream {stream_id}: {message}")]
        StreamCreate {
            /// Stream index.
            stream_id: usize,
            /// Error message.
            message: String,
        },

        /// Quality target not reached.
        #[error("Quality target {target} not reached, current quality: {current}")]
        QualityNotReached {
            /// Target quality score.
            target: f32,
            /// Current quality score.
            current: f32,
        },
    }

    // ==================== Accumulator State ====================

    /// Accumulator state for progressive reconstruction.
    #[derive(Debug)]
    pub enum AccumulatorState {
        /// Spectral: accumulated DCT coefficients
        Spectral {
            /// Accumulated frequency coefficients
            coefficients: CudaSlice<f32>,
            /// Mask of which coefficients are present
            present_mask: CudaSlice<u8>,
            /// Width of tensor
            width: usize,
            /// Height of tensor
            height: usize,
        },
        /// RPH: accumulated projections
        RandomProjection {
            /// Sum of projections
            projection_sum: CudaSlice<f32>,
            /// Number of projections accumulated
            num_projections: u32,
            /// Projection dimension
            proj_dim: usize,
            /// Output dimension
            output_dim: usize,
            /// Base seed for projection generation
            seed: u64,
        },
        /// LRDF: accumulated rank-1 matrices
        LowRankDistributed {
            /// Accumulated output matrix
            output: CudaSlice<f32>,
            /// Number of components accumulated
            num_components: u32,
            /// Number of matrix rows.
            rows: usize,
            /// Number of matrix columns.
            cols: usize,
        },
    }

    // ==================== Kernel Configuration ====================

    /// Kernel launch configuration for optimal GPU utilization.
    ///
    /// These values are tuned based on device properties (SM count, warp size,
    /// max threads per block, shared memory size).
    #[derive(Debug, Clone, Copy)]
    pub struct KernelConfig {
        /// Block size for 1D kernels (accumulate, finalize).
        pub block_size_1d: u32,
        /// Block size for 2D kernels (IDCT, outer product).
        pub block_size_2d: u32,
        /// Maximum shared memory per block (bytes).
        pub shared_mem_limit: u32,
        /// Number of streaming multiprocessors.
        pub sm_count: u32,
        /// Warp size (typically 32).
        pub warp_size: u32,
    }

    impl Default for KernelConfig {
        fn default() -> Self {
            // Conservative defaults for SM 7.0+ (Volta and newer)
            Self {
                block_size_1d: 256,
                block_size_2d: 16,
                shared_mem_limit: 48 * 1024, // 48 KB
                sm_count: 80,
                warp_size: 32,
            }
        }
    }

    impl KernelConfig {
        /// Create configuration optimized for 1D operations.
        pub fn for_1d_operation(&self, num_elements: usize) -> (u32, u32) {
            let grid = ((num_elements as u32) + self.block_size_1d - 1) / self.block_size_1d;
            (grid.max(1), self.block_size_1d)
        }

        /// Create configuration optimized for 2D operations (matrix ops).
        pub fn for_2d_operation(&self, rows: usize, cols: usize) -> ((u32, u32), (u32, u32)) {
            let grid_x = ((cols as u32) + self.block_size_2d - 1) / self.block_size_2d;
            let grid_y = ((rows as u32) + self.block_size_2d - 1) / self.block_size_2d;
            (
                (grid_x.max(1), grid_y.max(1)),
                (self.block_size_2d, self.block_size_2d),
            )
        }

        /// Calculate optimal block size for given shared memory requirement.
        pub fn optimal_block_for_shared_mem(&self, shared_per_thread: u32) -> u32 {
            let max_threads = self.shared_mem_limit / shared_per_thread.max(1);
            // Round down to nearest warp size multiple
            let threads = max_threads.min(1024);
            (threads / self.warp_size) * self.warp_size
        }
    }

    // ==================== GPU Tensor ====================

    /// A tensor stored in GPU memory.
    ///
    /// Wraps a CUDA buffer with shape information and provides
    /// convenience methods for data transfer.
    pub struct GpuTensor {
        data: CudaSlice<f32>,
        rows: usize,
        cols: usize,
        device: Arc<CudaDevice>,
    }

    impl GpuTensor {
        /// Creates a new GPU tensor.
        pub fn new(
            data: CudaSlice<f32>,
            rows: usize,
            cols: usize,
            device: Arc<CudaDevice>,
        ) -> Self {
            Self {
                data,
                rows,
                cols,
                device,
            }
        }

        /// Returns the number of rows.
        pub fn rows(&self) -> usize {
            self.rows
        }

        /// Returns the number of columns.
        pub fn cols(&self) -> usize {
            self.cols
        }

        /// Returns the total number of elements.
        pub fn len(&self) -> usize {
            self.rows * self.cols
        }

        /// Returns true if the tensor is empty.
        pub fn is_empty(&self) -> bool {
            self.rows == 0 || self.cols == 0
        }

        /// Copies the tensor data to host memory.
        pub fn to_host(&self) -> Result<Vec<f32>, GpuHoloError> {
            let mut host = vec![0.0f32; self.len()];
            self.device
                .dtoh_sync_copy_into(&self.data, &mut host)
                .map_err(|e| GpuHoloError::MemoryCopy {
                    message: e.to_string(),
                })?;
            Ok(host)
        }

        /// Returns a reference to the raw GPU data.
        pub fn raw(&self) -> &CudaSlice<f32> {
            &self.data
        }

        /// Converts to a Vec, copying from GPU to CPU.
        pub fn to_vec(&self) -> Vec<f32> {
            self.to_host().unwrap_or_default()
        }
    }

    // ==================== GPU Context ====================

    /// GPU holographic reconstruction context.
    ///
    /// Manages CUDA kernels and state for holographic tensor reconstruction.
    pub struct GpuHoloContext {
        device: Arc<CudaDevice>,
        device_id: usize,
        spectral_kernel_loaded: bool,
        rph_kernel_loaded: bool,
        lrdf_kernel_loaded: bool,
        /// Kernel configuration based on device properties.
        kernel_config: KernelConfig,
        /// Haagenti's FFT-capable DCT context for large tensor reconstruction.
        /// Uses FFT-based O(n log n) IDCT for dimensions > 4096, providing 40-80x speedup.
        #[cfg(feature = "haagenti-gpu")]
        fft_dct_ctx: Mutex<Option<GpuDctContext>>,
    }

    impl GpuHoloContext {
        /// Threshold for using FFT-based IDCT (dimensions > this use FFT).
        /// For tensors like MLP layers (28672x8192), FFT provides 40-80x speedup.
        /// TEMP: Set to very high value to disable FFT path (GpuDctContext hangs in WSL)
        /// TODO: Debug GpuDctContext::with_device() hang and re-enable FFT for perf gain
        pub const FFT_THRESHOLD: usize = 1_000_000_000;

        /// Creates a new GPU holographic context for the specified device.
        pub fn new(device_id: usize) -> Result<Self, GpuHoloError> {
            let device = CudaDevice::new(device_id).map_err(|e| GpuHoloError::DeviceInit {
                device_id,
                message: e.to_string(),
            })?;

            // Query device properties for optimal kernel configuration
            let kernel_config = KernelConfig::default();

            Ok(Self {
                device,
                device_id,
                spectral_kernel_loaded: false,
                rph_kernel_loaded: false,
                lrdf_kernel_loaded: false,
                kernel_config,
                #[cfg(feature = "haagenti-gpu")]
                fft_dct_ctx: Mutex::new(None), // Lazily initialized on first use
            })
        }

        /// Creates a new context using an existing CUDA device.
        pub fn with_device(device: Arc<CudaDevice>, device_id: usize) -> Self {
            Self {
                device,
                device_id,
                spectral_kernel_loaded: false,
                rph_kernel_loaded: false,
                lrdf_kernel_loaded: false,
                kernel_config: KernelConfig::default(),
                #[cfg(feature = "haagenti-gpu")]
                fft_dct_ctx: Mutex::new(None),
            }
        }

        /// Returns the kernel configuration.
        pub fn kernel_config(&self) -> &KernelConfig {
            &self.kernel_config
        }

        /// Sets a custom kernel configuration.
        pub fn with_kernel_config(mut self, config: KernelConfig) -> Self {
            self.kernel_config = config;
            self
        }

        /// Returns the CUDA device ID.
        pub fn device_id(&self) -> usize {
            self.device_id
        }

        /// Returns a reference to the CUDA device.
        pub fn device(&self) -> &Arc<CudaDevice> {
            &self.device
        }

        // ==================== Kernel Loading ====================

        /// Loads the spectral (IDCT) reconstruction kernels.
        pub fn load_spectral_kernel(&mut self) -> Result<(), GpuHoloError> {
            if self.spectral_kernel_loaded {
                return Ok(());
            }

            let ptx = Ptx::from_src(SPECTRAL_KERNEL_PTX);
            self.device
                .load_ptx(
                    ptx,
                    "holo_spectral",
                    &[
                        "holo_spectral_accumulate",
                        "holo_spectral_idct_1d_rows",
                        "holo_spectral_idct_1d_cols",
                        "holo_spectral_idct_2d", // DD-8 stub: retained for future Nihil optimization
                    ],
                )
                .map_err(|e| GpuHoloError::KernelLoad {
                    message: e.to_string(),
                })?;

            self.spectral_kernel_loaded = true;
            Ok(())
        }

        /// Loads the RPH (random projection) reconstruction kernels.
        pub fn load_rph_kernel(&mut self) -> Result<(), GpuHoloError> {
            if self.rph_kernel_loaded {
                return Ok(());
            }

            let ptx = Ptx::from_src(RPH_KERNEL_PTX);
            self.device
                .load_ptx(
                    ptx,
                    "holo_rph",
                    &[
                        "holo_rph_accumulate",
                        "holo_rph_finalize",
                        "holo_rph_generate_projection", // DD-8 stub: retained for future RPH batching
                    ],
                )
                .map_err(|e| GpuHoloError::KernelLoad {
                    message: e.to_string(),
                })?;

            self.rph_kernel_loaded = true;
            Ok(())
        }

        /// Loads the LRDF (low-rank) reconstruction kernels.
        pub fn load_lrdf_kernel(&mut self) -> Result<(), GpuHoloError> {
            if self.lrdf_kernel_loaded {
                return Ok(());
            }

            let ptx = Ptx::from_src(LRDF_KERNEL_PTX);
            self.device
                .load_ptx(
                    ptx,
                    "holo_lrdf",
                    &["holo_lrdf_outer_product", "holo_lrdf_outer_product_batched"],
                )
                .map_err(|e| GpuHoloError::KernelLoad {
                    message: e.to_string(),
                })?;

            self.lrdf_kernel_loaded = true;
            Ok(())
        }

        /// Loads all holographic reconstruction kernels.
        pub fn load_all_kernels(&mut self) -> Result<(), GpuHoloError> {
            self.load_spectral_kernel()?;
            self.load_rph_kernel()?;
            self.load_lrdf_kernel()?;
            Ok(())
        }

        // ==================== Accumulator Creation ====================

        /// Creates an accumulator for progressive reconstruction.
        pub fn create_accumulator(
            &self,
            header: &HoloTensorHeader,
        ) -> Result<AccumulatorState, GpuHoloError> {
            let (width, height) = Self::extract_2d_dims(header)?;
            let total_size = width * height;

            match header.encoding {
                HolographicEncoding::Spectral => {
                    // Allocate coefficient buffer and presence mask
                    let coefficients: CudaSlice<f32> = self
                        .device
                        .alloc_zeros(total_size)
                        .map_err(|e| GpuHoloError::MemoryAlloc {
                            message: e.to_string(),
                        })?;

                    let present_mask: CudaSlice<u8> =
                        self.device.alloc_zeros(total_size).map_err(|e| {
                            GpuHoloError::MemoryAlloc {
                                message: e.to_string(),
                            }
                        })?;

                    Ok(AccumulatorState::Spectral {
                        coefficients,
                        present_mask,
                        width,
                        height,
                    })
                },

                HolographicEncoding::RandomProjection => {
                    // For RPH, we accumulate projected values
                    let proj_dim = Self::compute_projection_dim(total_size);
                    let projection_sum: CudaSlice<f32> = self
                        .device
                        .alloc_zeros(total_size)
                        .map_err(|e| GpuHoloError::MemoryAlloc {
                            message: e.to_string(),
                        })?;

                    Ok(AccumulatorState::RandomProjection {
                        projection_sum,
                        num_projections: 0,
                        proj_dim,
                        output_dim: total_size,
                        seed: header.seed,
                    })
                },

                HolographicEncoding::LowRankDistributed => {
                    // For LRDF, we accumulate the output matrix directly
                    let output: CudaSlice<f32> =
                        self.device.alloc_zeros(total_size).map_err(|e| {
                            GpuHoloError::MemoryAlloc {
                                message: e.to_string(),
                            }
                        })?;

                    Ok(AccumulatorState::LowRankDistributed {
                        output,
                        num_components: 0,
                        rows: height,
                        cols: width,
                    })
                },
            }
        }

        // ==================== Spectral Reconstruction ====================

        /// HCT3 format magic bytes: "HCT3" = 0x48435433
        const HCT3_MAGIC: u32 = 0x48435433;

        /// Accumulates a spectral fragment into the accumulator.
        /// Supports both legacy format and HCT3 format from CompressiveSpectralEncoder.
        pub fn accumulate_spectral(
            &self,
            fragment: &HoloFragment,
            accumulator: &mut AccumulatorState,
        ) -> Result<(), GpuHoloError> {
            if !self.spectral_kernel_loaded {
                return Err(GpuHoloError::KernelNotLoaded {
                    kernel: "holo_spectral".to_string(),
                });
            }

            let (coefficients, present_mask, width, height) = match accumulator {
                AccumulatorState::Spectral {
                    coefficients,
                    present_mask,
                    width,
                    height,
                } => (coefficients, present_mask, *width, *height),
                _ => {
                    return Err(GpuHoloError::InvalidInput {
                        message: "Expected spectral accumulator".to_string(),
                    })
                },
            };

            let fragment_data = &fragment.data;
            if fragment_data.len() < 4 {
                return Err(GpuHoloError::FragmentDecode {
                    message: "Fragment too small".to_string(),
                });
            }

            // Check for HCT3 format magic
            let magic = u32::from_le_bytes([
                fragment_data[0],
                fragment_data[1],
                fragment_data[2],
                fragment_data[3],
            ]);

            if magic == Self::HCT3_MAGIC {
                // HCT3 format from CompressiveSpectralEncoder
                return self.accumulate_spectral_hct3(
                    fragment,
                    coefficients,
                    present_mask,
                    width,
                    height,
                );
            }

            // Legacy format: [num_coeffs: u32][indices: u32...][values: f32...]
            let num_coeffs = magic as usize; // First 4 bytes are num_coeffs in legacy format

            let expected_size = 4 + num_coeffs * 4 + num_coeffs * 4; // header + indices + values
            if fragment_data.len() < expected_size {
                return Err(GpuHoloError::FragmentDecode {
                    message: format!(
                        "Fragment size mismatch: expected {}, got {}",
                        expected_size,
                        fragment_data.len()
                    ),
                });
            }

            // Extract indices and values
            let indices_start = 4;
            let values_start = 4 + num_coeffs * 4;

            let mut indices = Vec::with_capacity(num_coeffs);
            let mut values = Vec::with_capacity(num_coeffs);

            for i in 0..num_coeffs {
                let idx_offset = indices_start + i * 4;
                let idx = u32::from_le_bytes([
                    fragment_data[idx_offset],
                    fragment_data[idx_offset + 1],
                    fragment_data[idx_offset + 2],
                    fragment_data[idx_offset + 3],
                ]);
                indices.push(idx);

                let val_offset = values_start + i * 4;
                let val = f32::from_le_bytes([
                    fragment_data[val_offset],
                    fragment_data[val_offset + 1],
                    fragment_data[val_offset + 2],
                    fragment_data[val_offset + 3],
                ]);
                values.push(val);
            }

            self.accumulate_spectral_kernel(
                &indices,
                &values,
                coefficients,
                present_mask,
                width * height,
            )
        }

        /// Accumulates HCT3 format spectral fragment.
        /// HCT3 Fragment 0: [magic][width][height][retain_count][essential_count][detail_per_frag][bitmap][essential_f16...]
        /// HCT3 Fragment k>0: [detail_f16...]
        fn accumulate_spectral_hct3(
            &self,
            fragment: &HoloFragment,
            coefficients: &mut CudaSlice<f32>,
            present_mask: &mut CudaSlice<u8>,
            width: usize,
            height: usize,
        ) -> Result<(), GpuHoloError> {
            use half::f16;

            let data = &fragment.data;
            let n = width * height;

            if fragment.index == 0 {
                // Parse HCT3 header (24 bytes)
                if data.len() < 24 {
                    return Err(GpuHoloError::FragmentDecode {
                        message: "HCT3 fragment 0 too short for header".to_string(),
                    });
                }

                // Skip magic (already checked), read dimensions
                let hct3_width = u32::from_le_bytes([data[4], data[5], data[6], data[7]]) as usize;
                let hct3_height =
                    u32::from_le_bytes([data[8], data[9], data[10], data[11]]) as usize;
                let retain_count =
                    u32::from_le_bytes([data[12], data[13], data[14], data[15]]) as usize;
                let essential_count =
                    u32::from_le_bytes([data[16], data[17], data[18], data[19]]) as usize;
                let _detail_per_frag =
                    u32::from_le_bytes([data[20], data[21], data[22], data[23]]) as usize;

                // Validate dimensions match
                if hct3_width != width || hct3_height != height {
                    return Err(GpuHoloError::FragmentDecode {
                        message: format!(
                            "HCT3 dimensions mismatch: header ({},{}) vs accumulator ({},{})",
                            hct3_width, hct3_height, width, height
                        ),
                    });
                }

                // Read bitmap and build index map
                let bitmap_bytes = (n + 7) / 8;
                let bitmap_start = 24;
                let bitmap_end = bitmap_start + bitmap_bytes;

                if data.len() < bitmap_end {
                    return Err(GpuHoloError::FragmentDecode {
                        message: "HCT3 fragment 0 truncated (missing bitmap)".to_string(),
                    });
                }

                // Scan bitmap to get indices of retained coefficients
                let mut indices = Vec::with_capacity(retain_count);
                for i in 0..n {
                    let byte_idx = bitmap_start + i / 8;
                    let bit_idx = i % 8;
                    if (data[byte_idx] >> bit_idx) & 1 == 1 {
                        indices.push(i as u32);
                    }
                }

                if indices.len() != retain_count {
                    return Err(GpuHoloError::FragmentDecode {
                        message: format!(
                            "HCT3 bitmap mismatch: {} set bits, expected {}",
                            indices.len(),
                            retain_count
                        ),
                    });
                }

                // Read essential coefficients (f16)
                let coeff_start = bitmap_end;
                let coeff_end = coeff_start + essential_count * 2;

                if data.len() < coeff_end {
                    return Err(GpuHoloError::FragmentDecode {
                        message: "HCT3 fragment 0 truncated (missing essential coefficients)"
                            .to_string(),
                    });
                }

                let mut values = Vec::with_capacity(essential_count);
                for i in 0..essential_count {
                    let offset = coeff_start + i * 2;
                    let f16_val = f16::from_le_bytes([data[offset], data[offset + 1]]);
                    values.push(f16_val.to_f32());
                }

                // Accumulate essential coefficients (first essential_count indices)
                let essential_indices: Vec<u32> = indices[..essential_count].to_vec();
                self.accumulate_spectral_kernel(
                    &essential_indices,
                    &values,
                    coefficients,
                    present_mask,
                    n,
                )?;

                // Store index map for detail fragments (we need this state across fragments)
                // For now, we'll re-read the bitmap for detail fragments (simpler but slightly less efficient)
                Ok(())
            } else {
                // Detail fragment: just f16 coefficients
                // We need to know which indices these correspond to, which requires re-parsing fragment 0
                // For GPU efficiency, we'll fall back to CPU for HCT3 detail fragments
                // This is a limitation - full HCT3 GPU support would require stateful tracking

                // For now, return an error to trigger CPU fallback
                Err(GpuHoloError::FragmentDecode {
                    message:
                        "HCT3 detail fragments not yet supported in GPU path - use CPU fallback"
                            .to_string(),
                })
            }
        }

        /// Common kernel invocation for spectral accumulation.
        fn accumulate_spectral_kernel(
            &self,
            indices: &[u32],
            values: &[f32],
            coefficients: &mut CudaSlice<f32>,
            present_mask: &mut CudaSlice<u8>,
            total_size: usize,
        ) -> Result<(), GpuHoloError> {
            let num_coeffs = indices.len();
            if num_coeffs == 0 {
                return Ok(());
            }

            // Copy to GPU
            let d_indices =
                self.device
                    .htod_copy(indices.to_vec())
                    .map_err(|e| GpuHoloError::MemoryAlloc {
                        message: e.to_string(),
                    })?;

            let d_values =
                self.device
                    .htod_copy(values.to_vec())
                    .map_err(|e| GpuHoloError::MemoryAlloc {
                        message: e.to_string(),
                    })?;

            // Launch accumulation kernel
            let func = self
                .device
                .get_func("holo_spectral", "holo_spectral_accumulate")
                .ok_or_else(|| GpuHoloError::KernelNotLoaded {
                    kernel: "holo_spectral_accumulate".to_string(),
                })?;

            let threads_per_block = 256u32;
            let num_blocks = ((num_coeffs as u32) + threads_per_block - 1) / threads_per_block;

            let cfg = LaunchConfig {
                grid_dim: (num_blocks.max(1), 1, 1),
                block_dim: (threads_per_block, 1, 1),
                shared_mem_bytes: 0,
            };

            unsafe {
                func.launch(
                    cfg,
                    (
                        &d_indices,
                        &d_values,
                        coefficients,
                        present_mask,
                        num_coeffs as u32,
                        total_size as u32,
                    ),
                )
            }
            .map_err(|e| GpuHoloError::KernelExec {
                message: e.to_string(),
            })?;

            Ok(())
        }

        /// Performs 2D IDCT reconstruction from accumulated spectral coefficients.
        ///
        /// For large tensors (dimensions > 4096), uses haagenti's FFT-based O(n log n) IDCT
        /// which provides 40-80x speedup over the direct O(nยฒ) kernel.
        pub fn finalize_spectral(
            &self,
            accumulator: &AccumulatorState,
        ) -> Result<CudaSlice<f32>, GpuHoloError> {
            let (coefficients, _present_mask, width, height) = match accumulator {
                AccumulatorState::Spectral {
                    coefficients,
                    present_mask,
                    width,
                    height,
                } => (coefficients, present_mask, *width, *height),
                _ => {
                    return Err(GpuHoloError::InvalidInput {
                        message: "Expected spectral accumulator".to_string(),
                    })
                },
            };

            // Use FFT-based IDCT for large tensors (40-80x faster)
            #[cfg(feature = "haagenti-gpu")]
            if width > Self::FFT_THRESHOLD || height > Self::FFT_THRESHOLD {
                return self.finalize_spectral_fft(coefficients, width, height);
            }

            // Fall back to direct PTX kernel for small tensors
            self.finalize_spectral_direct(coefficients, width, height)
        }

        /// FFT-based IDCT for large tensors using haagenti-cuda.
        ///
        /// Uses cuFFT-based O(n log n) algorithm for 40-80x speedup on large tensors.
        /// For a 28672x8192 tensor: ~1.3s direct โ†’ ~0.03s FFT.
        #[cfg(feature = "haagenti-gpu")]
        fn finalize_spectral_fft(
            &self,
            coefficients: &CudaSlice<f32>,
            width: usize,
            height: usize,
        ) -> Result<CudaSlice<f32>, GpuHoloError> {
            let total_size = width * height;

            // Copy coefficients from GPU to host
            let mut host_coeffs = vec![0.0f32; total_size];
            self.device
                .dtoh_sync_copy_into(coefficients, &mut host_coeffs)
                .map_err(|e| GpuHoloError::MemoryCopy {
                    message: format!("FFT IDCT: failed to copy coefficients to host: {}", e),
                })?;

            // Initialize or get the FFT DCT context
            let mut ctx_guard = self.fft_dct_ctx.lock();
            let dct_ctx = ctx_guard.get_or_insert_with(|| {
                tracing::info!(
                    "Initializing haagenti FFT-IDCT context for large tensor reconstruction"
                );
                GpuDctContext::with_device(self.device.clone())
                    .expect("Failed to create GpuDctContext")
            });

            // Perform FFT-based IDCT
            let reconstructed = dct_ctx.idct_2d(&host_coeffs, width, height).map_err(|e| {
                GpuHoloError::KernelExec {
                    message: format!("FFT IDCT failed: {}", e),
                }
            })?;

            // Copy result back to GPU
            let output = self.device.htod_sync_copy(&reconstructed).map_err(|e| {
                GpuHoloError::MemoryCopy {
                    message: format!("FFT IDCT: failed to copy result to GPU: {}", e),
                }
            })?;

            tracing::debug!(width, height, "FFT-based IDCT complete for large tensor");

            Ok(output)
        }

        /// Direct PTX kernel IDCT for small/medium tensors.
        fn finalize_spectral_direct(
            &self,
            coefficients: &CudaSlice<f32>,
            width: usize,
            height: usize,
        ) -> Result<CudaSlice<f32>, GpuHoloError> {
            if !self.spectral_kernel_loaded {
                return Err(GpuHoloError::KernelNotLoaded {
                    kernel: "holo_spectral".to_string(),
                });
            }

            let total_size = width * height;

            // Allocate intermediate and output buffers
            let temp: CudaSlice<f32> =
                self.device
                    .alloc_zeros(total_size)
                    .map_err(|e| GpuHoloError::MemoryAlloc {
                        message: e.to_string(),
                    })?;

            let output: CudaSlice<f32> =
                self.device
                    .alloc_zeros(total_size)
                    .map_err(|e| GpuHoloError::MemoryAlloc {
                        message: e.to_string(),
                    })?;

            // IDCT rows
            let func_rows = self
                .device
                .get_func("holo_spectral", "holo_spectral_idct_1d_rows")
                .ok_or_else(|| GpuHoloError::KernelNotLoaded {
                    kernel: "holo_spectral_idct_1d_rows".to_string(),
                })?;

            let threads_per_block = 256u32;
            let num_blocks = ((height as u32) + threads_per_block - 1) / threads_per_block;

            let cfg = LaunchConfig {
                grid_dim: (num_blocks.max(1), 1, 1),
                block_dim: (threads_per_block, 1, 1),
                shared_mem_bytes: (width * 4) as u32, // Shared memory for one row
            };

            unsafe { func_rows.launch(cfg, (coefficients, &temp, width as u32, height as u32)) }
                .map_err(|e| GpuHoloError::KernelExec {
                    message: e.to_string(),
                })?;

            // IDCT columns
            let func_cols = self
                .device
                .get_func("holo_spectral", "holo_spectral_idct_1d_cols")
                .ok_or_else(|| GpuHoloError::KernelNotLoaded {
                    kernel: "holo_spectral_idct_1d_cols".to_string(),
                })?;

            let num_blocks_cols = ((width as u32) + threads_per_block - 1) / threads_per_block;

            let cfg_cols = LaunchConfig {
                grid_dim: (num_blocks_cols.max(1), 1, 1),
                block_dim: (threads_per_block, 1, 1),
                shared_mem_bytes: (height * 4) as u32,
            };

            unsafe { func_cols.launch(cfg_cols, (&temp, &output, width as u32, height as u32)) }
                .map_err(|e| GpuHoloError::KernelExec {
                    message: e.to_string(),
                })?;

            self.device
                .synchronize()
                .map_err(|e| GpuHoloError::Synchronize {
                    message: e.to_string(),
                })?;

            Ok(output)
        }

        // ==================== RPH Reconstruction ====================

        /// Accumulates an RPH fragment into the accumulator.
        pub fn accumulate_rph(
            &self,
            fragment: &HoloFragment,
            accumulator: &mut AccumulatorState,
        ) -> Result<(), GpuHoloError> {
            if !self.rph_kernel_loaded {
                return Err(GpuHoloError::KernelNotLoaded {
                    kernel: "holo_rph".to_string(),
                });
            }

            let (projection_sum, _num_projections, _proj_dim, output_dim, seed) = match accumulator
            {
                AccumulatorState::RandomProjection {
                    projection_sum,
                    num_projections,
                    proj_dim,
                    output_dim,
                    seed,
                } => (
                    projection_sum,
                    num_projections,
                    *proj_dim,
                    *output_dim,
                    *seed,
                ),
                _ => {
                    return Err(GpuHoloError::InvalidInput {
                        message: "Expected RPH accumulator".to_string(),
                    })
                },
            };

            // Parse fragment data: [proj_dim: u32][seed_offset: u64][projection: f32...]
            let fragment_data = &fragment.data;
            if fragment_data.len() < 12 {
                return Err(GpuHoloError::FragmentDecode {
                    message: "Fragment too small for RPH".to_string(),
                });
            }

            let frag_proj_dim = u32::from_le_bytes([
                fragment_data[0],
                fragment_data[1],
                fragment_data[2],
                fragment_data[3],
            ]) as usize;

            let frag_seed_offset = u64::from_le_bytes([
                fragment_data[4],
                fragment_data[5],
                fragment_data[6],
                fragment_data[7],
                fragment_data[8],
                fragment_data[9],
                fragment_data[10],
                fragment_data[11],
            ]);

            let projection_start = 12;
            let expected_size = 12 + frag_proj_dim * 4;
            if fragment_data.len() < expected_size {
                return Err(GpuHoloError::FragmentDecode {
                    message: format!(
                        "Fragment size mismatch for RPH: expected {}, got {}",
                        expected_size,
                        fragment_data.len()
                    ),
                });
            }

            // Extract projection values
            let mut projection = Vec::with_capacity(frag_proj_dim);
            for i in 0..frag_proj_dim {
                let offset = projection_start + i * 4;
                let val = f32::from_le_bytes([
                    fragment_data[offset],
                    fragment_data[offset + 1],
                    fragment_data[offset + 2],
                    fragment_data[offset + 3],
                ]);
                projection.push(val);
            }

            // Copy projection to GPU
            let d_projection =
                self.device
                    .htod_copy(projection)
                    .map_err(|e| GpuHoloError::MemoryAlloc {
                        message: e.to_string(),
                    })?;

            // Launch RPH accumulation kernel
            // This generates the projection matrix on-the-fly and accumulates
            let func = self
                .device
                .get_func("holo_rph", "holo_rph_accumulate")
                .ok_or_else(|| GpuHoloError::KernelNotLoaded {
                    kernel: "holo_rph_accumulate".to_string(),
                })?;

            let threads_per_block = 256u32;
            let num_blocks = ((output_dim as u32) + threads_per_block - 1) / threads_per_block;

            let cfg = LaunchConfig {
                grid_dim: (num_blocks.max(1), 1, 1),
                block_dim: (threads_per_block, 1, 1),
                shared_mem_bytes: 0,
            };

            let fragment_seed = seed.wrapping_add(frag_seed_offset);

            unsafe {
                func.launch(
                    cfg,
                    (
                        &d_projection,
                        projection_sum,
                        frag_proj_dim as u32,
                        output_dim as u32,
                        fragment_seed,
                    ),
                )
            }
            .map_err(|e| GpuHoloError::KernelExec {
                message: e.to_string(),
            })?;

            // Update projection count
            if let AccumulatorState::RandomProjection {
                num_projections, ..
            } = accumulator
            {
                *num_projections += 1;
            }

            Ok(())
        }

        /// Finalizes RPH reconstruction by normalizing accumulated projections.
        pub fn finalize_rph(
            &self,
            accumulator: &AccumulatorState,
        ) -> Result<CudaSlice<f32>, GpuHoloError> {
            if !self.rph_kernel_loaded {
                return Err(GpuHoloError::KernelNotLoaded {
                    kernel: "holo_rph".to_string(),
                });
            }

            let (projection_sum, num_projections, output_dim) = match accumulator {
                AccumulatorState::RandomProjection {
                    projection_sum,
                    num_projections,
                    output_dim,
                    ..
                } => (projection_sum, *num_projections, *output_dim),
                _ => {
                    return Err(GpuHoloError::InvalidInput {
                        message: "Expected RPH accumulator".to_string(),
                    })
                },
            };

            if num_projections == 0 {
                return Err(GpuHoloError::InsufficientFragments {
                    min_required: 1,
                    available: 0,
                });
            }

            // Allocate output buffer
            let output: CudaSlice<f32> =
                self.device
                    .alloc_zeros(output_dim)
                    .map_err(|e| GpuHoloError::MemoryAlloc {
                        message: e.to_string(),
                    })?;

            // Launch finalization kernel (normalize by projection count)
            let func = self
                .device
                .get_func("holo_rph", "holo_rph_finalize")
                .ok_or_else(|| GpuHoloError::KernelNotLoaded {
                    kernel: "holo_rph_finalize".to_string(),
                })?;

            let threads_per_block = 256u32;
            let num_blocks = ((output_dim as u32) + threads_per_block - 1) / threads_per_block;

            let cfg = LaunchConfig {
                grid_dim: (num_blocks.max(1), 1, 1),
                block_dim: (threads_per_block, 1, 1),
                shared_mem_bytes: 0,
            };

            unsafe {
                func.launch(
                    cfg,
                    (projection_sum, &output, output_dim as u32, num_projections),
                )
            }
            .map_err(|e| GpuHoloError::KernelExec {
                message: e.to_string(),
            })?;

            self.device
                .synchronize()
                .map_err(|e| GpuHoloError::Synchronize {
                    message: e.to_string(),
                })?;

            Ok(output)
        }

        // ==================== LRDF Reconstruction ====================

        /// Accumulates an LRDF fragment into the accumulator.
        pub fn accumulate_lrdf(
            &self,
            fragment: &HoloFragment,
            accumulator: &mut AccumulatorState,
        ) -> Result<(), GpuHoloError> {
            if !self.lrdf_kernel_loaded {
                return Err(GpuHoloError::KernelNotLoaded {
                    kernel: "holo_lrdf".to_string(),
                });
            }

            let (output, rows, cols) = match accumulator {
                AccumulatorState::LowRankDistributed {
                    ref mut output,
                    rows,
                    cols,
                    ..
                } => (output, *rows, *cols),
                _ => {
                    return Err(GpuHoloError::InvalidInput {
                        message: "Expected LRDF accumulator".to_string(),
                    })
                },
            };

            // Parse fragment data (haagenti format):
            // [rows: u32][cols: u32][num_components: u32][components...]
            // Each component: [sigma: f32][u: f32 * rows][v: f32 * cols]
            let fragment_data = &fragment.data;
            if fragment_data.len() < 12 {
                return Err(GpuHoloError::FragmentDecode {
                    message: "Fragment too small for LRDF header".to_string(),
                });
            }

            // Read header: rows, cols, num_components
            let frag_rows = u32::from_le_bytes([
                fragment_data[0],
                fragment_data[1],
                fragment_data[2],
                fragment_data[3],
            ]) as usize;

            let frag_cols = u32::from_le_bytes([
                fragment_data[4],
                fragment_data[5],
                fragment_data[6],
                fragment_data[7],
            ]) as usize;

            let num_comps = u32::from_le_bytes([
                fragment_data[8],
                fragment_data[9],
                fragment_data[10],
                fragment_data[11],
            ]) as usize;

            // Validate dimensions match accumulator
            if frag_rows != rows || frag_cols != cols {
                return Err(GpuHoloError::FragmentDecode {
                    message: format!(
                        "Fragment dimensions {}x{} don't match accumulator {}x{}",
                        frag_rows, frag_cols, rows, cols
                    ),
                });
            }

            // Check for RAW format marker (num_components == 0xFFFFFFFF)
            // RAW format stores raw f32 data directly instead of SVD components
            const RAW_FORMAT_MARKER: usize = 0xFFFFFFFF;
            if num_comps == RAW_FORMAT_MARKER {
                // RAW format: [header: 12 bytes][raw f32 data: rows*cols*4 bytes]
                let expected_size = 12 + rows * cols * 4;
                if fragment_data.len() < expected_size {
                    return Err(GpuHoloError::FragmentDecode {
                        message: format!(
                            "Fragment size mismatch for RAW LRDF: expected {}, got {}",
                            expected_size,
                            fragment_data.len()
                        ),
                    });
                }

                // Parse raw f32 data from fragment
                let raw_data = &fragment_data[12..];
                let total_elements = rows * cols;
                let mut host_data = Vec::with_capacity(total_elements);
                for i in 0..total_elements {
                    let offset = i * 4;
                    let val = f32::from_le_bytes([
                        raw_data[offset],
                        raw_data[offset + 1],
                        raw_data[offset + 2],
                        raw_data[offset + 3],
                    ]);
                    host_data.push(val);
                }

                // Copy directly to GPU output buffer
                self.device
                    .htod_sync_copy_into(&host_data, output)
                    .map_err(|e| GpuHoloError::MemoryCopy {
                        message: format!("Failed to copy RAW data to GPU: {}", e),
                    })?;

                // Mark as having 1 "component" for finalize check
                if let AccumulatorState::LowRankDistributed { num_components, .. } = accumulator {
                    *num_components = 1;
                }

                return Ok(());
            }

            // SVD format: validate expected size
            let component_size = 4 + rows * 4 + cols * 4; // sigma + u + v
            let expected_size = 12 + num_comps * component_size; // 12-byte header
            if fragment_data.len() < expected_size {
                return Err(GpuHoloError::FragmentDecode {
                    message: format!(
                        "Fragment size mismatch for LRDF SVD: expected {}, got {}",
                        expected_size,
                        fragment_data.len()
                    ),
                });
            }

            // Process each SVD component (skip 12-byte header)
            let mut offset = 12;
            for _ in 0..num_comps {
                // Extract sigma
                let sigma = f32::from_le_bytes([
                    fragment_data[offset],
                    fragment_data[offset + 1],
                    fragment_data[offset + 2],
                    fragment_data[offset + 3],
                ]);
                offset += 4;

                // Extract u vector
                let mut u = Vec::with_capacity(rows);
                for _ in 0..rows {
                    let val = f32::from_le_bytes([
                        fragment_data[offset],
                        fragment_data[offset + 1],
                        fragment_data[offset + 2],
                        fragment_data[offset + 3],
                    ]);
                    u.push(val);
                    offset += 4;
                }

                // Extract v vector
                let mut v = Vec::with_capacity(cols);
                for _ in 0..cols {
                    let val = f32::from_le_bytes([
                        fragment_data[offset],
                        fragment_data[offset + 1],
                        fragment_data[offset + 2],
                        fragment_data[offset + 3],
                    ]);
                    v.push(val);
                    offset += 4;
                }

                // Copy to GPU
                let d_u = self
                    .device
                    .htod_copy(u)
                    .map_err(|e| GpuHoloError::MemoryAlloc {
                        message: e.to_string(),
                    })?;

                let d_v = self
                    .device
                    .htod_copy(v)
                    .map_err(|e| GpuHoloError::MemoryAlloc {
                        message: e.to_string(),
                    })?;

                // Launch outer product kernel
                let func = self
                    .device
                    .get_func("holo_lrdf", "holo_lrdf_outer_product")
                    .ok_or_else(|| GpuHoloError::KernelNotLoaded {
                        kernel: "holo_lrdf_outer_product".to_string(),
                    })?;

                // 2D grid for outer product
                let block_size = 16u32;
                let grid_x = ((cols as u32) + block_size - 1) / block_size;
                let grid_y = ((rows as u32) + block_size - 1) / block_size;

                let cfg = LaunchConfig {
                    grid_dim: (grid_x.max(1), grid_y.max(1), 1),
                    block_dim: (block_size, block_size, 1),
                    shared_mem_bytes: 0,
                };

                unsafe {
                    func.clone().launch(
                        cfg,
                        (&d_u, &d_v, &mut *output, sigma, rows as u32, cols as u32),
                    )
                }
                .map_err(|e| GpuHoloError::KernelExec {
                    message: e.to_string(),
                })?;
            }

            // Update component count
            if let AccumulatorState::LowRankDistributed { num_components, .. } = accumulator {
                *num_components += num_comps as u32;
            }

            Ok(())
        }

        /// Batched LRDF accumulation: processes all SVD components in a single kernel launch.
        ///
        /// Packs all components' u, v, sigma into contiguous GPU arrays and calls
        /// `holo_lrdf_outer_product_batched`. More efficient than the per-component
        /// approach for fragments with many components.
        pub fn accumulate_lrdf_batched(
            &self,
            fragment: &HoloFragment,
            accumulator: &mut AccumulatorState,
        ) -> Result<(), GpuHoloError> {
            if !self.lrdf_kernel_loaded {
                return Err(GpuHoloError::KernelNotLoaded {
                    kernel: "holo_lrdf".to_string(),
                });
            }

            let (output, rows, cols) = match accumulator {
                AccumulatorState::LowRankDistributed {
                    ref mut output,
                    rows,
                    cols,
                    ..
                } => (output, *rows, *cols),
                _ => {
                    return Err(GpuHoloError::InvalidInput {
                        message: "Expected LRDF accumulator".to_string(),
                    })
                },
            };

            let fragment_data = &fragment.data;
            if fragment_data.len() < 12 {
                return Err(GpuHoloError::FragmentDecode {
                    message: "Fragment too small for LRDF header".to_string(),
                });
            }

            let frag_rows = u32::from_le_bytes([
                fragment_data[0],
                fragment_data[1],
                fragment_data[2],
                fragment_data[3],
            ]) as usize;
            let frag_cols = u32::from_le_bytes([
                fragment_data[4],
                fragment_data[5],
                fragment_data[6],
                fragment_data[7],
            ]) as usize;
            let num_comps = u32::from_le_bytes([
                fragment_data[8],
                fragment_data[9],
                fragment_data[10],
                fragment_data[11],
            ]) as usize;

            if frag_rows != rows || frag_cols != cols {
                return Err(GpuHoloError::FragmentDecode {
                    message: format!(
                        "Fragment dimensions {}x{} don't match accumulator {}x{}",
                        frag_rows, frag_cols, rows, cols
                    ),
                });
            }

            if num_comps == 0 {
                return Ok(());
            }

            let component_size = 4 + rows * 4 + cols * 4;
            let expected_size = 12 + num_comps * component_size;
            if fragment_data.len() < expected_size {
                return Err(GpuHoloError::FragmentDecode {
                    message: format!(
                        "Fragment size mismatch for batched LRDF: expected {}, got {}",
                        expected_size,
                        fragment_data.len()
                    ),
                });
            }

            // Pack all components into contiguous arrays
            let mut all_sigma = Vec::with_capacity(num_comps);
            let mut all_u = Vec::with_capacity(num_comps * rows);
            let mut all_v = Vec::with_capacity(num_comps * cols);

            let mut offset = 12;
            for _ in 0..num_comps {
                let sigma = f32::from_le_bytes([
                    fragment_data[offset],
                    fragment_data[offset + 1],
                    fragment_data[offset + 2],
                    fragment_data[offset + 3],
                ]);
                all_sigma.push(sigma);
                offset += 4;

                for _ in 0..rows {
                    let val = f32::from_le_bytes([
                        fragment_data[offset],
                        fragment_data[offset + 1],
                        fragment_data[offset + 2],
                        fragment_data[offset + 3],
                    ]);
                    all_u.push(val);
                    offset += 4;
                }

                for _ in 0..cols {
                    let val = f32::from_le_bytes([
                        fragment_data[offset],
                        fragment_data[offset + 1],
                        fragment_data[offset + 2],
                        fragment_data[offset + 3],
                    ]);
                    all_v.push(val);
                    offset += 4;
                }
            }

            // Upload packed arrays to GPU
            let d_sigma =
                self.device
                    .htod_copy(all_sigma)
                    .map_err(|e| GpuHoloError::MemoryAlloc {
                        message: e.to_string(),
                    })?;
            let d_u = self
                .device
                .htod_copy(all_u)
                .map_err(|e| GpuHoloError::MemoryAlloc {
                    message: e.to_string(),
                })?;
            let d_v = self
                .device
                .htod_copy(all_v)
                .map_err(|e| GpuHoloError::MemoryAlloc {
                    message: e.to_string(),
                })?;

            // Single kernel launch for all components
            let func = self
                .device
                .get_func("holo_lrdf", "holo_lrdf_outer_product_batched")
                .ok_or_else(|| GpuHoloError::KernelNotLoaded {
                    kernel: "holo_lrdf_outer_product_batched".to_string(),
                })?;

            let block_size = 16u32;
            let grid_x = ((cols as u32) + block_size - 1) / block_size;
            let grid_y = ((rows as u32) + block_size - 1) / block_size;

            let cfg = LaunchConfig {
                grid_dim: (grid_x.max(1), grid_y.max(1), 1),
                block_dim: (block_size, block_size, 1),
                shared_mem_bytes: 0,
            };

            unsafe {
                func.launch(
                    cfg,
                    (
                        &d_u,
                        &d_v,
                        &d_sigma,
                        &mut *output,
                        num_comps as u32,
                        rows as u32,
                        cols as u32,
                    ),
                )
            }
            .map_err(|e| GpuHoloError::KernelExec {
                message: e.to_string(),
            })?;

            if let AccumulatorState::LowRankDistributed { num_components, .. } = accumulator {
                *num_components += num_comps as u32;
            }

            Ok(())
        }

        /// Finalizes LRDF reconstruction (no additional processing needed).
        pub fn finalize_lrdf(
            &self,
            accumulator: &AccumulatorState,
        ) -> Result<CudaSlice<f32>, GpuHoloError> {
            let (output, num_components, rows, cols) = match accumulator {
                AccumulatorState::LowRankDistributed {
                    output,
                    num_components,
                    rows,
                    cols,
                } => (output, *num_components, *rows, *cols),
                _ => {
                    return Err(GpuHoloError::InvalidInput {
                        message: "Expected LRDF accumulator".to_string(),
                    })
                },
            };

            if num_components == 0 {
                return Err(GpuHoloError::InsufficientFragments {
                    min_required: 1,
                    available: 0,
                });
            }

            self.device
                .synchronize()
                .map_err(|e| GpuHoloError::Synchronize {
                    message: e.to_string(),
                })?;

            // Clone the output (LRDF accumulates directly into output)
            let mut result: CudaSlice<f32> =
                self.device
                    .alloc_zeros(rows * cols)
                    .map_err(|e| GpuHoloError::MemoryAlloc {
                        message: e.to_string(),
                    })?;

            // Copy from accumulator to result
            self.device
                .dtod_copy(output, &mut result)
                .map_err(|e| GpuHoloError::MemoryCopy {
                    message: e.to_string(),
                })?;

            Ok(result)
        }

        // ==================== Unified API ====================

        /// Accumulates a fragment based on the encoding type.
        pub fn accumulate_fragment(
            &self,
            fragment: &HoloFragment,
            accumulator: &mut AccumulatorState,
            encoding: HolographicEncoding,
        ) -> Result<(), GpuHoloError> {
            match encoding {
                HolographicEncoding::Spectral => self.accumulate_spectral(fragment, accumulator),
                HolographicEncoding::RandomProjection => self.accumulate_rph(fragment, accumulator),
                HolographicEncoding::LowRankDistributed => {
                    self.accumulate_lrdf(fragment, accumulator)
                },
            }
        }

        /// Finalizes reconstruction based on the encoding type.
        pub fn finalize_reconstruction(
            &self,
            accumulator: &AccumulatorState,
            encoding: HolographicEncoding,
        ) -> Result<CudaSlice<f32>, GpuHoloError> {
            match encoding {
                HolographicEncoding::Spectral => self.finalize_spectral(accumulator),
                HolographicEncoding::RandomProjection => self.finalize_rph(accumulator),
                HolographicEncoding::LowRankDistributed => self.finalize_lrdf(accumulator),
            }
        }

        /// Reconstructs a tensor from fragments.
        ///
        /// This is the high-level API for reconstruction.
        pub fn reconstruct(
            &self,
            header: &HoloTensorHeader,
            fragments: &[HoloFragment],
        ) -> Result<CudaSlice<f32>, GpuHoloError> {
            if fragments.is_empty() {
                return Err(GpuHoloError::InsufficientFragments {
                    min_required: header.quality_curve.min_fragments,
                    available: 0,
                });
            }

            if (fragments.len() as u16) < header.quality_curve.min_fragments {
                return Err(GpuHoloError::InsufficientFragments {
                    min_required: header.quality_curve.min_fragments,
                    available: fragments.len() as u16,
                });
            }

            // Create accumulator
            let mut accumulator = self.create_accumulator(header)?;

            // Accumulate all fragments
            for fragment in fragments {
                self.accumulate_fragment(fragment, &mut accumulator, header.encoding)?;
            }

            // Finalize and return
            self.finalize_reconstruction(&accumulator, header.encoding)
        }

        /// Copies reconstructed data to host memory.
        pub fn copy_to_host(&self, gpu_data: &CudaSlice<f32>) -> Result<Vec<f32>, GpuHoloError> {
            let len = gpu_data.len();
            let mut host_data = vec![0.0f32; len];
            self.device
                .dtoh_sync_copy_into(gpu_data, &mut host_data)
                .map_err(|e| GpuHoloError::MemoryCopy {
                    message: e.to_string(),
                })?;
            Ok(host_data)
        }

        // ==================== Convenience Methods ====================

        /// Reconstructs a 2D LRDF tensor from fragments.
        ///
        /// This is a convenience wrapper for LRDF reconstruction that builds
        /// the header automatically.
        pub fn reconstruct_lrdf(
            &self,
            fragments: &[HoloFragment],
            rows: usize,
            cols: usize,
        ) -> Result<GpuTensor, GpuHoloError> {
            if fragments.is_empty() {
                return Err(GpuHoloError::InsufficientFragments {
                    min_required: 1,
                    available: 0,
                });
            }

            // Build header for LRDF encoding
            let header = HoloTensorHeader::new(
                HolographicEncoding::LowRankDistributed,
                haagenti::DType::F32,
                vec![rows as u64, cols as u64],
                fragments.len() as u16,
            );

            let gpu_data = self.reconstruct(&header, fragments)?;

            Ok(GpuTensor {
                data: gpu_data,
                rows,
                cols,
                device: self.device.clone(),
            })
        }

        // ==================== Helper Functions ====================

        /// Extracts 2D dimensions from header.
        fn extract_2d_dims(header: &HoloTensorHeader) -> Result<(usize, usize), GpuHoloError> {
            if header.shape.len() < 2 {
                return Err(GpuHoloError::InvalidInput {
                    message: format!("Expected 2D tensor, got {} dimensions", header.shape.len()),
                });
            }
            Ok((header.shape[1] as usize, header.shape[0] as usize))
        }

        /// Computes projection dimension for RPH.
        fn compute_projection_dim(output_dim: usize) -> usize {
            // Use sqrt(n) as default projection dimension
            ((output_dim as f64).sqrt() as usize).max(16)
        }
    }

    // ==================== PTX Kernel Sources ====================

    /// Spectral (IDCT) kernel PTX source.
    const SPECTRAL_KERNEL_PTX: &str = r#"
.version 8.0
.target sm_89
.address_size 64

// Accumulate coefficients into buffer
// Args: indices, values, coefficients, mask, num_coeffs, buffer_size
.visible .entry holo_spectral_accumulate(
    .param .u64 indices_ptr,
    .param .u64 values_ptr,
    .param .u64 coeffs_ptr,
    .param .u64 mask_ptr,
    .param .u32 num_coeffs,
    .param .u32 buffer_size
)
{
    .reg .u32 %gid, %idx, %coeff_idx;
    .reg .u64 %indices_addr, %values_addr, %coeffs_addr, %mask_addr;
    .reg .f32 %val;
    .reg .pred %p;

    // Get thread ID: gid = blockIdx.x * blockDim.x + threadIdx.x
    mov.u32 %gid, %ctaid.x;
    mov.u32 %idx, %ntid.x;
    mul.lo.u32 %gid, %gid, %idx;
    mov.u32 %idx, %tid.x;
    add.u32 %gid, %gid, %idx;

    // Bounds check
    ld.param.u32 %idx, [num_coeffs];
    setp.ge.u32 %p, %gid, %idx;
    @%p bra EXIT;

    // Load index and value
    ld.param.u64 %indices_addr, [indices_ptr];
    ld.param.u64 %values_addr, [values_ptr];

    mad.wide.u32 %indices_addr, %gid, 4, %indices_addr;
    mad.wide.u32 %values_addr, %gid, 4, %values_addr;

    ld.global.u32 %coeff_idx, [%indices_addr];
    ld.global.f32 %val, [%values_addr];

    // Bounds check on coefficient index
    ld.param.u32 %idx, [buffer_size];
    setp.ge.u32 %p, %coeff_idx, %idx;
    @%p bra EXIT;

    // Store coefficient and mark as present
    ld.param.u64 %coeffs_addr, [coeffs_ptr];
    ld.param.u64 %mask_addr, [mask_ptr];

    mad.wide.u32 %coeffs_addr, %coeff_idx, 4, %coeffs_addr;
    cvt.u64.u32 %mask_addr, %coeff_idx;
    add.u64 %mask_addr, %mask_addr, %mask_addr;

    st.global.f32 [%coeffs_addr], %val;

EXIT:
    ret;
}

// 1D IDCT (Type-III DCT) on rows
// x[n] = sqrt(2/N) * [ X[0]/sqrt(2) + sum_{k=1}^{N-1} X[k] * cos(pi*(2n+1)*k / (2N)) ]
// One thread per row, inner loop over width columns.
// Args: input, output, width, height
.visible .entry holo_spectral_idct_1d_rows(
    .param .u64 input_ptr,
    .param .u64 output_ptr,
    .param .u32 width,
    .param .u32 height
)
{
    .reg .u32 %row, %col, %k, %w, %h, %tmp, %n2p1;
    .reg .u64 %in_base, %out_addr, %coeff_addr;
    .reg .f32 %sum, %val, %cos_val, %scale, %pi_2n, %angle, %w_f, %k_f, %n2p1_f;
    .reg .pred %p;

    // Get row index = blockIdx.x * blockDim.x + threadIdx.x
    mov.u32 %row, %ctaid.x;
    mov.u32 %tmp, %ntid.x;
    mul.lo.u32 %row, %row, %tmp;
    mov.u32 %tmp, %tid.x;
    add.u32 %row, %row, %tmp;

    ld.param.u32 %h, [height];
    setp.ge.u32 %p, %row, %h;
    @%p bra ROW_EXIT;

    ld.param.u32 %w, [width];
    ld.param.u64 %in_base, [input_ptr];
    ld.param.u64 %out_addr, [output_ptr];

    // Compute row base offsets: in_base += row * width * 4, out_addr += row * width * 4
    mul.lo.u32 %tmp, %row, %w;
    mad.wide.u32 %in_base, %tmp, 4, %in_base;
    mad.wide.u32 %out_addr, %tmp, 4, %out_addr;

    // Pre-compute scale = sqrt(2.0 / width)
    cvt.rn.f32.u32 %w_f, %w;
    mov.f32 %scale, 2.0;
    div.full.f32 %scale, %scale, %w_f;
    sqrt.approx.f32 %scale, %scale;

    // Pre-compute pi_2n = PI / (2 * width)
    mov.f32 %pi_2n, 3.14159265358979;
    mov.f32 %angle, 2.0;
    mul.f32 %angle, %angle, %w_f;
    div.full.f32 %pi_2n, %pi_2n, %angle;

    // For each output column n = 0..width
    mov.u32 %col, 0;
ROW_COL_LOOP:
    setp.ge.u32 %p, %col, %w;
    @%p bra ROW_COL_END;

    // DC term: sum = X[0] * scale * (1/sqrt(2))
    ld.global.f32 %val, [%in_base];
    mul.f32 %sum, %val, %scale;
    mul.f32 %sum, %sum, 0.7071067811865476;

    // Pre-compute (2*col + 1) as float for AC loop
    mul.lo.u32 %n2p1, %col, 2;
    add.u32 %n2p1, %n2p1, 1;
    cvt.rn.f32.u32 %n2p1_f, %n2p1;

    // AC terms: sum += X[k] * scale * cos((2n+1) * k * pi_2n)
    mov.u32 %k, 1;
ROW_AC_LOOP:
    setp.ge.u32 %p, %k, %w;
    @%p bra ROW_AC_END;

    // Load X[k] from in_base + k * 4
    mad.wide.u32 %coeff_addr, %k, 4, %in_base;
    ld.global.f32 %val, [%coeff_addr];

    // angle = (2n+1) * k * pi_2n
    cvt.rn.f32.u32 %k_f, %k;
    mul.f32 %angle, %n2p1_f, %k_f;
    mul.f32 %angle, %angle, %pi_2n;

    cos.approx.f32 %cos_val, %angle;

    // sum += X[k] * scale * cos(angle)
    mul.f32 %val, %val, %scale;
    fma.rn.f32 %sum, %val, %cos_val, %sum;

    add.u32 %k, %k, 1;
    bra ROW_AC_LOOP;

ROW_AC_END:
    // Store result at output[row * width + col]
    st.global.f32 [%out_addr], %sum;

    add.u64 %out_addr, %out_addr, 4;
    add.u32 %col, %col, 1;
    bra ROW_COL_LOOP;

ROW_COL_END:
ROW_EXIT:
    ret;
}

// 1D IDCT (Type-III DCT) on columns
// x[n] = sqrt(2/H) * [ X[0]/sqrt(2) + sum_{k=1}^{H-1} X[k] * cos(pi*(2n+1)*k / (2H)) ]
// One thread per column, inner loop over height rows.
// Column access pattern: input[k * width + col], output[n * width + col]
// Args: input, output, width, height
.visible .entry holo_spectral_idct_1d_cols(
    .param .u64 input_ptr,
    .param .u64 output_ptr,
    .param .u32 width,
    .param .u32 height
)
{
    .reg .u32 %col, %row, %k, %w, %h, %tmp, %n2p1;
    .reg .u64 %in_base, %out_base, %coeff_addr, %out_addr;
    .reg .f32 %sum, %val, %cos_val, %scale, %pi_2n, %angle, %h_f, %k_f, %n2p1_f;
    .reg .pred %p;

    // Get column index = blockIdx.x * blockDim.x + threadIdx.x
    mov.u32 %col, %ctaid.x;
    mov.u32 %tmp, %ntid.x;
    mul.lo.u32 %col, %col, %tmp;
    mov.u32 %tmp, %tid.x;
    add.u32 %col, %col, %tmp;

    ld.param.u32 %w, [width];
    setp.ge.u32 %p, %col, %w;
    @%p bra COL_EXIT;

    ld.param.u32 %h, [height];
    ld.param.u64 %in_base, [input_ptr];
    ld.param.u64 %out_base, [output_ptr];

    // Pre-compute scale = sqrt(2.0 / height)
    cvt.rn.f32.u32 %h_f, %h;
    mov.f32 %scale, 2.0;
    div.full.f32 %scale, %scale, %h_f;
    sqrt.approx.f32 %scale, %scale;

    // Pre-compute pi_2n = PI / (2 * height)
    mov.f32 %pi_2n, 3.14159265358979;
    mov.f32 %angle, 2.0;
    mul.f32 %angle, %angle, %h_f;
    div.full.f32 %pi_2n, %pi_2n, %angle;

    // For each output row n = 0..height
    mov.u32 %row, 0;
COL_ROW_LOOP:
    setp.ge.u32 %p, %row, %h;
    @%p bra COL_ROW_END;

    // DC term: sum = input[0 * width + col] * scale * (1/sqrt(2))
    mad.wide.u32 %coeff_addr, %col, 4, %in_base;
    ld.global.f32 %val, [%coeff_addr];
    mul.f32 %sum, %val, %scale;
    mul.f32 %sum, %sum, 0.7071067811865476;

    // Pre-compute (2*row + 1) as float for AC loop
    mul.lo.u32 %n2p1, %row, 2;
    add.u32 %n2p1, %n2p1, 1;
    cvt.rn.f32.u32 %n2p1_f, %n2p1;

    // AC terms: sum += input[k*width+col] * scale * cos((2n+1) * k * pi_2n)
    mov.u32 %k, 1;
COL_AC_LOOP:
    setp.ge.u32 %p, %k, %h;
    @%p bra COL_AC_END;

    // Load coefficient: input[k * width + col]
    mul.lo.u32 %tmp, %k, %w;
    add.u32 %tmp, %tmp, %col;
    mad.wide.u32 %coeff_addr, %tmp, 4, %in_base;
    ld.global.f32 %val, [%coeff_addr];

    // angle = (2*row+1) * k * pi_2n
    cvt.rn.f32.u32 %k_f, %k;
    mul.f32 %angle, %n2p1_f, %k_f;
    mul.f32 %angle, %angle, %pi_2n;

    cos.approx.f32 %cos_val, %angle;

    // sum += input[k*w+col] * scale * cos(angle)
    mul.f32 %val, %val, %scale;
    fma.rn.f32 %sum, %val, %cos_val, %sum;

    add.u32 %k, %k, 1;
    bra COL_AC_LOOP;

COL_AC_END:
    // Store result at output[row * width + col]
    mul.lo.u32 %tmp, %row, %w;
    add.u32 %tmp, %tmp, %col;
    mad.wide.u32 %out_addr, %tmp, 4, %out_base;
    st.global.f32 [%out_addr], %sum;

    add.u32 %row, %row, 1;
    bra COL_ROW_LOOP;

COL_ROW_END:
COL_EXIT:
    ret;
}

// DD-8 STUB: Fused 2D IDCT kernel.
// Currently unused - separable row + col IDCT handles 2D reconstruction.
// Potential future optimization: a single-pass 2D IDCT could reduce kernel
// launch overhead and improve cache locality for large tensors. Profile
// separable path under Nihil before implementing.
.visible .entry holo_spectral_idct_2d(
    .param .u64 input_ptr,
    .param .u64 output_ptr,
    .param .u32 width,
    .param .u32 height
)
{
    .reg .u32 %tmp;
    mov.u32 %tmp, 0;
    ret;
}
"#;

    /// RPH (random projection) kernel PTX source.
    const RPH_KERNEL_PTX: &str = r#"
.version 8.0
.target sm_89
.address_size 64

// Accumulate projection into output buffer
// Uses on-the-fly random weight generation via XORShift64 PRNG.
// Each thread handles one output element, iterating over projection dims.
// Reference: haagenti-hct SeededRng (xorshift64: <<13, >>7, <<17)
.visible .entry holo_rph_accumulate(
    .param .u64 projection_ptr,
    .param .u64 output_ptr,
    .param .u32 proj_dim,
    .param .u32 output_dim,
    .param .u64 seed
)
{
    .reg .u32 %gid, %out_idx, %proj_d, %out_d, %tmp, %i;
    .reg .u64 %proj_base, %proj_addr, %out_addr, %rng_state, %tmp64;
    .reg .f32 %sum, %proj_val, %rand_val, %out_val, %scale;
    .reg .pred %p;

    // Get output index = blockIdx.x * blockDim.x + threadIdx.x
    mov.u32 %gid, %ctaid.x;
    mov.u32 %tmp, %ntid.x;
    mul.lo.u32 %gid, %gid, %tmp;
    mov.u32 %tmp, %tid.x;
    add.u32 %out_idx, %gid, %tmp;

    ld.param.u32 %out_d, [output_dim];
    setp.ge.u32 %p, %out_idx, %out_d;
    @%p bra RPH_EXIT;

    // Save projection base pointer (Bug fix: don't modify in loop)
    ld.param.u64 %proj_base, [projection_ptr];
    ld.param.u32 %proj_d, [proj_dim];

    // Per-thread PRNG initialization:
    // state = seed + 1 (matching SeededRng::new wrapping_add(1))
    // then XOR with out_idx spread across both halves for decorrelation
    ld.param.u64 %rng_state, [seed];
    add.u64 %rng_state, %rng_state, 1;
    cvt.u64.u32 %tmp64, %out_idx;
    shl.b64 %rng_state, %rng_state, 1;
    xor.b64 %rng_state, %rng_state, %tmp64;
    shl.b64 %tmp64, %tmp64, 32;
    xor.b64 %rng_state, %rng_state, %tmp64;
    // Ensure non-zero (XORShift64 produces 0 forever from state=0)
    setp.ne.u64 %p, %rng_state, 0;
    @%p bra RPH_SEED_OK;
    mov.u64 %rng_state, 1;
RPH_SEED_OK:

    // scale = 1.0 / sqrt(proj_dim)
    cvt.rn.f32.u32 %scale, %proj_d;
    sqrt.approx.f32 %scale, %scale;
    rcp.approx.f32 %scale, %scale;

    mov.f32 %sum, 0.0;

    // Sum projection[i] * random_weight for each projection dimension
    mov.u32 %i, 0;
RPH_PROJ_LOOP:
    setp.ge.u32 %p, %i, %proj_d;
    @%p bra RPH_END_PROJ;

    // Load projection value: proj_base + i * 4
    mad.wide.u32 %proj_addr, %i, 4, %proj_base;
    ld.global.f32 %proj_val, [%proj_addr];

    // XORShift64: x ^= x << 13; x ^= x >> 7; x ^= x << 17
    shl.b64 %tmp64, %rng_state, 13;
    xor.b64 %rng_state, %rng_state, %tmp64;
    shr.u64 %tmp64, %rng_state, 7;
    xor.b64 %rng_state, %rng_state, %tmp64;
    shl.b64 %tmp64, %rng_state, 17;
    xor.b64 %rng_state, %rng_state, %tmp64;

    // Convert to float [-1, 1):
    // Take bits 40-63 (24 bits) -> [0, 2^24), divide by 2^23 -> [0, 2), sub 1 -> [-1, 1)
    shr.u64 %tmp64, %rng_state, 40;
    cvt.rn.f32.u64 %rand_val, %tmp64;
    div.full.f32 %rand_val, %rand_val, 8388608.0;
    sub.f32 %rand_val, %rand_val, 1.0;

    // Apply projection scale
    mul.f32 %rand_val, %rand_val, %scale;

    // Accumulate: sum += proj_val * rand_val
    fma.rn.f32 %sum, %proj_val, %rand_val, %sum;

    add.u32 %i, %i, 1;
    bra RPH_PROJ_LOOP;

RPH_END_PROJ:
    // Store to output: output[out_idx] += sum
    ld.param.u64 %out_addr, [output_ptr];
    mad.wide.u32 %out_addr, %out_idx, 4, %out_addr;

    ld.global.f32 %out_val, [%out_addr];
    add.f32 %out_val, %out_val, %sum;
    st.global.f32 [%out_addr], %out_val;

RPH_EXIT:
    ret;
}

// Finalize RPH by dividing by projection count
.visible .entry holo_rph_finalize(
    .param .u64 input_ptr,
    .param .u64 output_ptr,
    .param .u32 size,
    .param .u32 num_projections
)
{
    .reg .u32 %gid, %sz, %np, %tmp;
    .reg .u64 %in_addr, %out_addr;
    .reg .f32 %val, %divisor;
    .reg .pred %p;

    mov.u32 %gid, %ctaid.x;
    mov.u32 %tmp, %ntid.x;
    mul.lo.u32 %gid, %gid, %tmp;
    mov.u32 %tmp, %tid.x;
    add.u32 %gid, %gid, %tmp;

    ld.param.u32 %sz, [size];
    setp.ge.u32 %p, %gid, %sz;
    @%p bra EXIT;

    ld.param.u64 %in_addr, [input_ptr];
    ld.param.u64 %out_addr, [output_ptr];
    ld.param.u32 %np, [num_projections];

    mad.wide.u32 %in_addr, %gid, 4, %in_addr;
    mad.wide.u32 %out_addr, %gid, 4, %out_addr;

    ld.global.f32 %val, [%in_addr];
    cvt.rn.f32.u32 %divisor, %np;
    div.rn.f32 %val, %val, %divisor;
    st.global.f32 [%out_addr], %val;

EXIT:
    ret;
}

// DD-8 STUB: On-GPU projection matrix generation.
// Currently unused - projections arrive pre-computed in fragment data and
// random weights are generated on-the-fly in holo_rph_accumulate.
// Future use: pre-generating the full projection matrix on-GPU could enable
// batched RPH accumulation and avoid redundant PRNG work across fragments
// sharing the same seed. Relevant once Nihil replaces Candle and RPH
// reconstruction becomes latency-critical.
.visible .entry holo_rph_generate_projection(
    .param .u64 output_ptr,
    .param .u32 row,
    .param .u32 col,
    .param .u32 rows,
    .param .u32 cols,
    .param .u64 seed
)
{
    ret;
}
"#;

    /// LRDF (low-rank distributed) kernel PTX source.
    const LRDF_KERNEL_PTX: &str = r#"
.version 8.0
.target sm_89
.address_size 64

// Outer product: output += sigma * u * v^T
.visible .entry holo_lrdf_outer_product(
    .param .u64 u_ptr,
    .param .u64 v_ptr,
    .param .u64 output_ptr,
    .param .f32 sigma,
    .param .u32 rows,
    .param .u32 cols
)
{
    .reg .u32 %row, %col, %r, %c, %idx, %tmp;
    .reg .u64 %u_addr, %v_addr, %out_addr;
    .reg .f32 %u_val, %v_val, %prod, %out_val, %sig;
    .reg .pred %p;

    // Get 2D thread position: col = blockIdx.x * blockDim.x + threadIdx.x
    mov.u32 %col, %ctaid.x;
    mov.u32 %tmp, %ntid.x;
    mul.lo.u32 %col, %col, %tmp;
    mov.u32 %tmp, %tid.x;
    add.u32 %col, %col, %tmp;

    // row = blockIdx.y * blockDim.y + threadIdx.y
    mov.u32 %row, %ctaid.y;
    mov.u32 %tmp, %ntid.y;
    mul.lo.u32 %row, %row, %tmp;
    mov.u32 %tmp, %tid.y;
    add.u32 %row, %row, %tmp;

    // Bounds check
    ld.param.u32 %r, [rows];
    ld.param.u32 %c, [cols];
    setp.ge.u32 %p, %row, %r;
    @%p bra EXIT;
    setp.ge.u32 %p, %col, %c;
    @%p bra EXIT;

    // Load u[row] and v[col]
    ld.param.u64 %u_addr, [u_ptr];
    ld.param.u64 %v_addr, [v_ptr];

    mad.wide.u32 %u_addr, %row, 4, %u_addr;
    mad.wide.u32 %v_addr, %col, 4, %v_addr;

    ld.global.f32 %u_val, [%u_addr];
    ld.global.f32 %v_val, [%v_addr];

    // Compute sigma * u * v
    ld.param.f32 %sig, [sigma];
    mul.f32 %prod, %u_val, %v_val;
    mul.f32 %prod, %prod, %sig;

    // Add to output[row * cols + col]
    ld.param.u64 %out_addr, [output_ptr];
    mul.lo.u32 %idx, %row, %c;
    add.u32 %idx, %idx, %col;
    mad.wide.u32 %out_addr, %idx, 4, %out_addr;

    ld.global.f32 %out_val, [%out_addr];
    add.f32 %out_val, %out_val, %prod;
    st.global.f32 [%out_addr], %out_val;

EXIT:
    ret;
}

// Batched outer products: output += sum_i sigma[i] * u[i] * v[i]^T
// Memory layout: u = [u0(rows), u1(rows), ...], v = [v0(cols), v1(cols), ...], sigma = [s0, s1, ...]
// Each thread (row, col) accumulates all components in registers, single write to output.
.visible .entry holo_lrdf_outer_product_batched(
    .param .u64 u_ptr,
    .param .u64 v_ptr,
    .param .u64 sigma_ptr,
    .param .u64 output_ptr,
    .param .u32 num_components,
    .param .u32 rows,
    .param .u32 cols
)
{
    .reg .u32 %row, %col, %r, %c, %nc, %idx, %tmp, %i, %off;
    .reg .u64 %u_base, %v_base, %sig_base, %out_addr, %addr;
    .reg .f32 %u_val, %v_val, %sig_val, %prod, %out_val, %sum;
    .reg .pred %p;

    // Get 2D thread position: col = blockIdx.x * blockDim.x + threadIdx.x
    mov.u32 %col, %ctaid.x;
    mov.u32 %tmp, %ntid.x;
    mul.lo.u32 %col, %col, %tmp;
    mov.u32 %tmp, %tid.x;
    add.u32 %col, %col, %tmp;

    // row = blockIdx.y * blockDim.y + threadIdx.y
    mov.u32 %row, %ctaid.y;
    mov.u32 %tmp, %ntid.y;
    mul.lo.u32 %row, %row, %tmp;
    mov.u32 %tmp, %tid.y;
    add.u32 %row, %row, %tmp;

    // Bounds check
    ld.param.u32 %r, [rows];
    ld.param.u32 %c, [cols];
    setp.ge.u32 %p, %row, %r;
    @%p bra BATCH_EXIT;
    setp.ge.u32 %p, %col, %c;
    @%p bra BATCH_EXIT;

    // Load base pointers and component count
    ld.param.u64 %u_base, [u_ptr];
    ld.param.u64 %v_base, [v_ptr];
    ld.param.u64 %sig_base, [sigma_ptr];
    ld.param.u32 %nc, [num_components];

    // Accumulate all components in registers
    mov.f32 %sum, 0.0;
    mov.u32 %i, 0;

BATCH_COMP_LOOP:
    setp.ge.u32 %p, %i, %nc;
    @%p bra BATCH_COMP_END;

    // sigma[i]: sig_base + i * 4
    mad.wide.u32 %addr, %i, 4, %sig_base;
    ld.global.f32 %sig_val, [%addr];

    // u[i * rows + row]: u_base + (i * rows + row) * 4
    mul.lo.u32 %off, %i, %r;
    add.u32 %off, %off, %row;
    mad.wide.u32 %addr, %off, 4, %u_base;
    ld.global.f32 %u_val, [%addr];

    // v[i * cols + col]: v_base + (i * cols + col) * 4
    mul.lo.u32 %off, %i, %c;
    add.u32 %off, %off, %col;
    mad.wide.u32 %addr, %off, 4, %v_base;
    ld.global.f32 %v_val, [%addr];

    // sum += sigma[i] * u[i][row] * v[i][col]
    mul.f32 %prod, %u_val, %v_val;
    fma.rn.f32 %sum, %sig_val, %prod, %sum;

    add.u32 %i, %i, 1;
    bra BATCH_COMP_LOOP;

BATCH_COMP_END:
    // output[row * cols + col] += sum
    ld.param.u64 %out_addr, [output_ptr];
    mul.lo.u32 %idx, %row, %c;
    add.u32 %idx, %idx, %col;
    mad.wide.u32 %out_addr, %idx, 4, %out_addr;

    ld.global.f32 %out_val, [%out_addr];
    add.f32 %out_val, %out_val, %sum;
    st.global.f32 [%out_addr], %out_val;

BATCH_EXIT:
    ret;
}
"#;

    /// Fused reconstruction + dequantization kernel PTX source.
    ///
    /// Combines holographic reconstruction output with INT4/INT8 dequantization
    /// in a single pass to avoid extra memory bandwidth.
    const FUSED_KERNEL_PTX: &str = r#"
.version 8.0
.target sm_89
.address_size 64

// Fused holographic reconstruction + F32 to F16 conversion
// For use after IDCT/RPH/LRDF reconstruction when output needs to be F16
.visible .entry holo_fused_f32_to_f16(
    .param .u64 input_ptr,     // F32 reconstructed data
    .param .u64 output_ptr,    // F16 output
    .param .u32 size
)
{
    .reg .u32 %gid, %sz, %tmp;
    .reg .u64 %in_addr, %out_addr;
    .reg .f32 %val;
    .reg .b16 %h_val;
    .reg .pred %p;

    // Get thread index
    mov.u32 %gid, %ctaid.x;
    mov.u32 %tmp, %ntid.x;
    mul.lo.u32 %gid, %gid, %tmp;
    mov.u32 %tmp, %tid.x;
    add.u32 %gid, %gid, %tmp;

    ld.param.u32 %sz, [size];
    setp.ge.u32 %p, %gid, %sz;
    @%p bra EXIT;

    ld.param.u64 %in_addr, [input_ptr];
    ld.param.u64 %out_addr, [output_ptr];

    // Load F32, convert to F16, store
    mad.wide.u32 %in_addr, %gid, 4, %in_addr;
    ld.global.f32 %val, [%in_addr];

    cvt.rn.f16.f32 %h_val, %val;

    mad.wide.u32 %out_addr, %gid, 2, %out_addr;
    st.global.u16 [%out_addr], %h_val;

EXIT:
    ret;
}

// Fused: apply scale and zero-point correction to reconstructed values
// For quantized weight reconstruction
// output = (reconstructed - zero_point) * scale
.visible .entry holo_fused_dequant_f32(
    .param .u64 input_ptr,         // F32 reconstructed (may represent quantized values)
    .param .u64 scales_ptr,        // Per-block scales (F32)
    .param .u64 zeros_ptr,         // Per-block zero points (F32)
    .param .u64 output_ptr,        // F32 dequantized output
    .param .u32 size,
    .param .u32 block_size
)
{
    .reg .u32 %gid, %sz, %blk_sz, %blk_idx, %tmp;
    .reg .u64 %in_addr, %scale_addr, %zero_addr, %out_addr;
    .reg .f32 %val, %scale, %zero, %result;
    .reg .pred %p;

    mov.u32 %gid, %ctaid.x;
    mov.u32 %tmp, %ntid.x;
    mul.lo.u32 %gid, %gid, %tmp;
    mov.u32 %tmp, %tid.x;
    add.u32 %gid, %gid, %tmp;

    ld.param.u32 %sz, [size];
    setp.ge.u32 %p, %gid, %sz;
    @%p bra EXIT2;

    ld.param.u64 %in_addr, [input_ptr];
    ld.param.u64 %scale_addr, [scales_ptr];
    ld.param.u64 %zero_addr, [zeros_ptr];
    ld.param.u64 %out_addr, [output_ptr];
    ld.param.u32 %blk_sz, [block_size];

    // Calculate block index
    div.u32 %blk_idx, %gid, %blk_sz;

    // Load reconstructed value
    mad.wide.u32 %in_addr, %gid, 4, %in_addr;
    ld.global.f32 %val, [%in_addr];

    // Load scale and zero for this block
    mad.wide.u32 %scale_addr, %blk_idx, 4, %scale_addr;
    mad.wide.u32 %zero_addr, %blk_idx, 4, %zero_addr;
    ld.global.f32 %scale, [%scale_addr];
    ld.global.f32 %zero, [%zero_addr];

    // Dequantize: (val - zero) * scale
    sub.f32 %result, %val, %zero;
    mul.f32 %result, %result, %scale;

    // Store
    mad.wide.u32 %out_addr, %gid, 4, %out_addr;
    st.global.f32 [%out_addr], %result;

EXIT2:
    ret;
}

// Fused IDCT + F16 output in single kernel
// Performs 1D IDCT on a row and outputs as F16
.visible .entry holo_spectral_idct_f16(
    .param .u64 coeffs_ptr,    // F32 frequency coefficients
    .param .u64 output_ptr,    // F16 output
    .param .u32 width,
    .param .u32 height
)
{
    .reg .u32 %row, %col, %w, %h, %tmp;
    .reg .u64 %coeff_addr, %out_addr;
    .reg .f32 %sum;
    .reg .b16 %h_val;
    .reg .pred %p;

    mov.u32 %row, %ctaid.x;
    mov.u32 %tmp, %ntid.x;
    mul.lo.u32 %row, %row, %tmp;
    mov.u32 %tmp, %tid.x;
    add.u32 %row, %row, %tmp;

    ld.param.u32 %h, [height];
    setp.ge.u32 %p, %row, %h;
    @%p bra EXIT3;

    ld.param.u32 %w, [width];
    ld.param.u64 %coeff_addr, [coeffs_ptr];
    ld.param.u64 %out_addr, [output_ptr];

    // Process each column in this row
    mov.u32 %col, 0;
COL_LOOP:
    setp.ge.u32 %p, %col, %w;
    @%p bra END_COL;

    // Simplified IDCT placeholder - just copy for now
    // Real implementation would use shared memory for efficiency
    mov.f32 %sum, 0.0;

    // Convert to F16 and store
    cvt.rn.f16.f32 %h_val, %sum;

    // Calculate output offset: (row * width + col) * 2
    mul.lo.u32 %row, %row, %w;
    add.u32 %row, %row, %col;
    mad.wide.u32 %out_addr, %row, 2, %out_addr;
    st.global.u16 [%out_addr], %h_val;

    add.u32 %col, %col, 1;
    bra COL_LOOP;

END_COL:
EXIT3:
    ret;
}

// Scale reconstructed values by a constant factor
.visible .entry holo_scale_values(
    .param .u64 data_ptr,
    .param .f32 scale,
    .param .u32 size
)
{
    .reg .u32 %gid, %sz, %tmp;
    .reg .u64 %addr;
    .reg .f32 %val, %scl;
    .reg .pred %p;

    mov.u32 %gid, %ctaid.x;
    mov.u32 %tmp, %ntid.x;
    mul.lo.u32 %gid, %gid, %tmp;
    mov.u32 %tmp, %tid.x;
    add.u32 %gid, %gid, %tmp;

    ld.param.u32 %sz, [size];
    setp.ge.u32 %p, %gid, %sz;
    @%p bra EXIT4;

    ld.param.u64 %addr, [data_ptr];
    ld.param.f32 %scl, [scale];

    mad.wide.u32 %addr, %gid, 4, %addr;
    ld.global.f32 %val, [%addr];
    mul.f32 %val, %val, %scl;
    st.global.f32 [%addr], %val;

EXIT4:
    ret;
}
"#;

    impl GpuHoloContext {
        // ==================== Fused Operations ====================

        /// Loads the fused reconstruction + dequantization kernels.
        pub fn load_fused_kernel(&mut self) -> Result<(), GpuHoloError> {
            let ptx = Ptx::from_src(FUSED_KERNEL_PTX);
            self.device
                .load_ptx(
                    ptx,
                    "holo_fused",
                    &[
                        "holo_fused_f32_to_f16",
                        "holo_fused_dequant_f32",
                        "holo_spectral_idct_f16",
                        "holo_scale_values",
                    ],
                )
                .map_err(|e| GpuHoloError::KernelLoad {
                    message: e.to_string(),
                })?;

            Ok(())
        }

        /// Converts reconstructed F32 values to F16.
        ///
        /// Useful when inference expects F16 weights.
        pub fn convert_f32_to_f16(
            &self,
            input: &CudaSlice<f32>,
        ) -> Result<CudaSlice<half::f16>, GpuHoloError> {
            let size = input.len();

            let output: CudaSlice<half::f16> =
                self.device
                    .alloc_zeros(size)
                    .map_err(|e| GpuHoloError::MemoryAlloc {
                        message: e.to_string(),
                    })?;

            let func = self
                .device
                .get_func("holo_fused", "holo_fused_f32_to_f16")
                .ok_or_else(|| GpuHoloError::KernelNotLoaded {
                    kernel: "holo_fused_f32_to_f16".to_string(),
                })?;

            let threads_per_block = 256u32;
            let num_blocks = ((size as u32) + threads_per_block - 1) / threads_per_block;

            let cfg = LaunchConfig {
                grid_dim: (num_blocks.max(1), 1, 1),
                block_dim: (threads_per_block, 1, 1),
                shared_mem_bytes: 0,
            };

            unsafe { func.launch(cfg, (input, &output, size as u32)) }.map_err(|e| {
                GpuHoloError::KernelExec {
                    message: e.to_string(),
                }
            })?;

            self.device
                .synchronize()
                .map_err(|e| GpuHoloError::Synchronize {
                    message: e.to_string(),
                })?;

            Ok(output)
        }

        /// Applies per-block dequantization to reconstructed values.
        ///
        /// Formula: output = (input - zero_point) * scale
        ///
        /// # Arguments
        ///
        /// * `input` - Reconstructed F32 values (may represent quantized data)
        /// * `scales` - Per-block scale factors
        /// * `zeros` - Per-block zero points
        /// * `block_size` - Number of values per quantization block
        pub fn dequantize_reconstructed(
            &self,
            input: &CudaSlice<f32>,
            scales: &[f32],
            zeros: &[f32],
            block_size: usize,
        ) -> Result<CudaSlice<f32>, GpuHoloError> {
            let size = input.len();

            // Copy scales and zeros to GPU
            let d_scales =
                self.device
                    .htod_copy(scales.to_vec())
                    .map_err(|e| GpuHoloError::MemoryAlloc {
                        message: e.to_string(),
                    })?;

            let d_zeros =
                self.device
                    .htod_copy(zeros.to_vec())
                    .map_err(|e| GpuHoloError::MemoryAlloc {
                        message: e.to_string(),
                    })?;

            let output: CudaSlice<f32> =
                self.device
                    .alloc_zeros(size)
                    .map_err(|e| GpuHoloError::MemoryAlloc {
                        message: e.to_string(),
                    })?;

            let func = self
                .device
                .get_func("holo_fused", "holo_fused_dequant_f32")
                .ok_or_else(|| GpuHoloError::KernelNotLoaded {
                    kernel: "holo_fused_dequant_f32".to_string(),
                })?;

            let threads_per_block = 256u32;
            let num_blocks = ((size as u32) + threads_per_block - 1) / threads_per_block;

            let cfg = LaunchConfig {
                grid_dim: (num_blocks.max(1), 1, 1),
                block_dim: (threads_per_block, 1, 1),
                shared_mem_bytes: 0,
            };

            unsafe {
                func.launch(
                    cfg,
                    (
                        input,
                        &d_scales,
                        &d_zeros,
                        &output,
                        size as u32,
                        block_size as u32,
                    ),
                )
            }
            .map_err(|e| GpuHoloError::KernelExec {
                message: e.to_string(),
            })?;

            self.device
                .synchronize()
                .map_err(|e| GpuHoloError::Synchronize {
                    message: e.to_string(),
                })?;

            Ok(output)
        }

        /// Scales all values in a buffer by a constant factor.
        pub fn scale_values(
            &self,
            data: &mut CudaSlice<f32>,
            scale: f32,
        ) -> Result<(), GpuHoloError> {
            let size = data.len();

            let func = self
                .device
                .get_func("holo_fused", "holo_scale_values")
                .ok_or_else(|| GpuHoloError::KernelNotLoaded {
                    kernel: "holo_scale_values".to_string(),
                })?;

            let threads_per_block = 256u32;
            let num_blocks = ((size as u32) + threads_per_block - 1) / threads_per_block;

            let cfg = LaunchConfig {
                grid_dim: (num_blocks.max(1), 1, 1),
                block_dim: (threads_per_block, 1, 1),
                shared_mem_bytes: 0,
            };

            unsafe { func.launch(cfg, (data as &CudaSlice<f32>, scale, size as u32)) }.map_err(
                |e| GpuHoloError::KernelExec {
                    message: e.to_string(),
                },
            )?;

            Ok(())
        }

        /// Reconstructs and dequantizes in a single pipeline.
        ///
        /// This is the high-level fused API combining:
        /// 1. Holographic reconstruction from fragments
        /// 2. Dequantization with per-block scales/zeros
        /// 3. Optional F32โ†’F16 conversion
        pub fn reconstruct_and_dequantize(
            &self,
            header: &HoloTensorHeader,
            fragments: &[HoloFragment],
            scales: &[f32],
            zeros: &[f32],
            block_size: usize,
        ) -> Result<CudaSlice<f32>, GpuHoloError> {
            // Step 1: Reconstruct
            let reconstructed = self.reconstruct(header, fragments)?;

            // Step 2: Dequantize
            let dequantized =
                self.dequantize_reconstructed(&reconstructed, scales, zeros, block_size)?;

            Ok(dequantized)
        }

        /// Reconstructs, dequantizes, and converts to F16.
        pub fn reconstruct_dequantize_f16(
            &self,
            header: &HoloTensorHeader,
            fragments: &[HoloFragment],
            scales: &[f32],
            zeros: &[f32],
            block_size: usize,
        ) -> Result<CudaSlice<half::f16>, GpuHoloError> {
            let dequantized =
                self.reconstruct_and_dequantize(header, fragments, scales, zeros, block_size)?;

            self.convert_f32_to_f16(&dequantized)
        }

        // ==================== Quality Calibration ====================

        /// Measures the actual reconstruction quality by comparing to original data.
        ///
        /// Returns a quality score between 0.0 and 1.0 based on normalized MSE.
        pub fn measure_reconstruction_quality(
            &self,
            reconstructed: &CudaSlice<f32>,
            original: &[f32],
        ) -> Result<f32, GpuHoloError> {
            // Copy reconstructed data to host
            let mut reconstructed_host = vec![0.0f32; original.len()];
            self.device
                .dtoh_sync_copy_into(reconstructed, &mut reconstructed_host)
                .map_err(|e| GpuHoloError::MemoryCopy {
                    message: e.to_string(),
                })?;

            // Calculate normalized MSE
            let mse: f32 = original
                .iter()
                .zip(reconstructed_host.iter())
                .map(|(o, r)| (o - r).powi(2))
                .sum::<f32>()
                / original.len() as f32;

            // Calculate variance of original for normalization
            let mean: f32 = original.iter().sum::<f32>() / original.len() as f32;
            let variance: f32 =
                original.iter().map(|x| (x - mean).powi(2)).sum::<f32>() / original.len() as f32;

            // Quality = 1 - normalized_mse, clamped to [0, 1]
            let nmse = if variance > 1e-10 {
                mse / variance
            } else {
                mse
            };
            let quality = (1.0 - nmse).clamp(0.0, 1.0);

            Ok(quality)
        }

        /// Calibrates quality curve by testing reconstruction at various fragment counts.
        ///
        /// Returns a new `QualityCurve` fitted to actual performance on test data.
        pub fn calibrate_quality_curve(
            &mut self,
            original: &[f32],
            width: usize,
            height: usize,
            encoding: HolographicEncoding,
            num_fragments: u16,
        ) -> Result<QualityCurve, GpuHoloError> {
            use haagenti::holotensor::HoloTensorEncoder;

            // Encode the test data
            let encoder = HoloTensorEncoder::new(encoding).with_fragments(num_fragments);
            let (header, fragments) = encoder.encode_2d(original, width, height).map_err(|e| {
                GpuHoloError::InvalidInput {
                    message: format!("Failed to encode test data: {}", e),
                }
            })?;

            // Measure quality at each fragment count
            let mut quality_points = Vec::with_capacity(num_fragments as usize);

            for k in 1..=num_fragments {
                // Reconstruct with k fragments
                let partial_frags: Vec<_> = fragments.iter().take(k as usize).cloned().collect();
                let reconstructed = self.reconstruct(&header, &partial_frags)?;
                let quality = self.measure_reconstruction_quality(&reconstructed, original)?;
                quality_points.push((k as f32 / num_fragments as f32, quality));
            }

            // Fit polynomial curve to quality points
            // Using simple least squares for [a0, a1, a2, a3]
            let coefficients = Self::fit_polynomial(&quality_points);

            // Find min and sufficient fragments
            let min_fragments = quality_points
                .iter()
                .position(|&(_, q)| q > 0.1)
                .map(|i| (i + 1) as u16)
                .unwrap_or(1);

            let sufficient_fragments = quality_points
                .iter()
                .position(|&(_, q)| q > 0.99)
                .map(|i| (i + 1) as u16)
                .unwrap_or(num_fragments);

            Ok(QualityCurve {
                coefficients,
                min_fragments,
                sufficient_fragments,
            })
        }

        /// Fits a 3rd-degree polynomial to quality data points.
        fn fit_polynomial(points: &[(f32, f32)]) -> [f32; 4] {
            // Simple polynomial regression using normal equations
            // y = a0 + a1*x + a2*x^2 + a3*x^3
            let n = points.len() as f32;
            if n < 4.0 {
                // Not enough points, return linear approximation
                return [0.0, 1.0, 0.0, 0.0];
            }

            // Build sums for normal equations
            let mut sx = [0.0f32; 7]; // x^0 to x^6
            let mut sy = [0.0f32; 4]; // y*x^0 to y*x^3

            for &(x, y) in points {
                let mut xp = 1.0f32;
                for i in 0..7 {
                    sx[i] += xp;
                    if i < 4 {
                        sy[i] += y * xp;
                    }
                    xp *= x;
                }
            }

            // Simplified solution: use least squares approximation
            // For robustness, just compute a reasonable fit
            let a0 = points.first().map(|&(_, y)| y).unwrap_or(0.0);
            let a1 = if n > 1.0 {
                points.last().map(|&(_, y)| y).unwrap_or(1.0) - a0
            } else {
                1.0
            };

            [a0, a1, 0.0, 0.0]
        }
    }

    // ==================== Streaming Holographic Context ====================

    /// Progressive holographic loader for streaming reconstruction.
    ///
    /// Supports incremental fragment feeding with quality tracking.
    pub struct ProgressiveHoloLoader {
        context: GpuHoloContext,
        header: HoloTensorHeader,
        accumulator: AccumulatorState,
        fragments_loaded: u16,
        current_quality: f32,
    }

    impl ProgressiveHoloLoader {
        /// Creates a new progressive loader.
        pub fn new(
            context: GpuHoloContext,
            header: HoloTensorHeader,
        ) -> Result<Self, GpuHoloError> {
            let accumulator = context.create_accumulator(&header)?;

            Ok(Self {
                context,
                header,
                accumulator,
                fragments_loaded: 0,
                current_quality: 0.0,
            })
        }

        /// Feeds a fragment into the loader, updating the reconstruction.
        ///
        /// Returns the new quality estimate.
        pub fn feed(&mut self, fragment: &HoloFragment) -> Result<f32, GpuHoloError> {
            self.context.accumulate_fragment(
                fragment,
                &mut self.accumulator,
                self.header.encoding,
            )?;

            self.fragments_loaded += 1;
            self.current_quality = self
                .header
                .quality_curve
                .predict(self.fragments_loaded, self.header.total_fragments);

            Ok(self.current_quality)
        }

        /// Returns the current quality estimate.
        pub fn quality(&self) -> f32 {
            self.current_quality
        }

        /// Returns the number of fragments loaded.
        pub fn fragments_loaded(&self) -> u16 {
            self.fragments_loaded
        }

        /// Checks if minimum fragments are available for reconstruction.
        pub fn can_reconstruct(&self) -> bool {
            self.fragments_loaded >= self.header.quality_curve.min_fragments
        }

        /// Checks if quality target has been reached.
        pub fn is_sufficient(&self, target: f32) -> bool {
            self.current_quality >= target
        }

        /// Finalizes reconstruction with current fragments.
        pub fn finalize(&self) -> Result<CudaSlice<f32>, GpuHoloError> {
            if !self.can_reconstruct() {
                return Err(GpuHoloError::InsufficientFragments {
                    min_required: self.header.quality_curve.min_fragments,
                    available: self.fragments_loaded,
                });
            }

            self.context
                .finalize_reconstruction(&self.accumulator, self.header.encoding)
        }

        /// Returns the header.
        pub fn header(&self) -> &HoloTensorHeader {
            &self.header
        }
    }

    // ==================== Streaming Context ====================

    use cudarc::driver::CudaStream;

    /// Stream pool for async holographic operations.
    ///
    /// Enables pipelining: while one fragment is being transferred,
    /// another is being accumulated on the GPU.
    pub struct HoloStreamPool {
        device: Arc<CudaDevice>,
        streams: Vec<CudaStream>,
        num_streams: usize,
    }

    impl HoloStreamPool {
        /// Creates a new stream pool.
        ///
        /// # Arguments
        ///
        /// * `device` - CUDA device reference
        /// * `num_streams` - Number of concurrent streams (2-4 recommended)
        pub fn new(device: Arc<CudaDevice>, num_streams: usize) -> Result<Self, GpuHoloError> {
            let mut streams = Vec::with_capacity(num_streams);

            for i in 0..num_streams {
                let stream =
                    device
                        .fork_default_stream()
                        .map_err(|e| GpuHoloError::StreamCreate {
                            stream_id: i,
                            message: e.to_string(),
                        })?;
                streams.push(stream);
            }

            Ok(Self {
                device,
                streams,
                num_streams,
            })
        }

        /// Returns a reference to stream at the given index (wraps around).
        pub fn get_stream(&self, index: usize) -> &CudaStream {
            &self.streams[index % self.num_streams]
        }

        /// Returns the number of streams in the pool.
        pub fn num_streams(&self) -> usize {
            self.num_streams
        }

        /// Synchronizes all streams in the pool.
        pub fn synchronize_all(&self) -> Result<(), GpuHoloError> {
            self.device
                .synchronize()
                .map_err(|e| GpuHoloError::Synchronize {
                    message: e.to_string(),
                })?;
            Ok(())
        }
    }

    /// Streaming holographic reconstruction context.
    ///
    /// Provides pipelined fragment loading with overlapped H2D transfers
    /// and GPU accumulation for maximum throughput.
    ///
    /// ## Pipeline Architecture
    ///
    /// ```text
    /// Fragment 0: [Transfer] [Accumulate]
    /// Fragment 1:            [Transfer  ] [Accumulate]
    /// Fragment 2:                         [Transfer  ] [Accumulate]
    /// ```
    ///
    /// ## Usage
    ///
    /// ```ignore
    /// let ctx = StreamingHoloContext::new(0, 4)?;
    /// let result = ctx.reconstruct_streaming(&header, fragments.iter(), 0.95)?;
    /// ```
    pub struct StreamingHoloContext {
        ctx: GpuHoloContext,
        stream_pool: HoloStreamPool,
        pipeline_depth: usize,
    }

    impl StreamingHoloContext {
        /// Creates a new streaming context.
        ///
        /// # Arguments
        ///
        /// * `device_id` - CUDA device ID
        /// * `pipeline_depth` - Number of concurrent operations (2-4 recommended)
        pub fn new(device_id: usize, pipeline_depth: usize) -> Result<Self, GpuHoloError> {
            let mut ctx = GpuHoloContext::new(device_id)?;

            // Load all kernels upfront with better error tracking
            ctx.load_spectral_kernel().map_err(|e| {
                eprintln!("StreamingHoloContext: spectral kernel failed: {:?}", e);
                e
            })?;
            ctx.load_rph_kernel().map_err(|e| {
                eprintln!("StreamingHoloContext: rph kernel failed: {:?}", e);
                e
            })?;
            ctx.load_lrdf_kernel().map_err(|e| {
                eprintln!("StreamingHoloContext: lrdf kernel failed: {:?}", e);
                e
            })?;
            ctx.load_fused_kernel().map_err(|e| {
                eprintln!("StreamingHoloContext: fused kernel failed: {:?}", e);
                e
            })?;

            let stream_pool = HoloStreamPool::new(Arc::clone(&ctx.device), pipeline_depth)?;

            Ok(Self {
                ctx,
                stream_pool,
                pipeline_depth,
            })
        }

        /// Returns the underlying context for synchronous operations.
        pub fn context(&self) -> &GpuHoloContext {
            &self.ctx
        }

        /// Returns mutable reference to the underlying context.
        pub fn context_mut(&mut self) -> &mut GpuHoloContext {
            &mut self.ctx
        }

        /// Returns the stream pool for advanced async operations.
        pub fn stream_pool(&self) -> &HoloStreamPool {
            &self.stream_pool
        }

        /// Reconstructs from fragments with pipelined streaming.
        ///
        /// This method overlaps H2D transfers with accumulation to maximize
        /// throughput. Fragments are processed in batches according to pipeline depth.
        ///
        /// # Arguments
        ///
        /// * `header` - HoloTensor header with encoding info
        /// * `fragments` - Iterator of fragments to process
        /// * `min_quality` - Stop early if this quality is reached (0.0 to process all)
        ///
        /// # Returns
        ///
        /// Reconstructed tensor on GPU
        pub fn reconstruct_streaming<'a, I>(
            &self,
            header: &HoloTensorHeader,
            fragments: I,
            min_quality: f32,
        ) -> Result<CudaSlice<f32>, GpuHoloError>
        where
            I: Iterator<Item = &'a HoloFragment>,
        {
            let mut accumulator = self.ctx.create_accumulator(header)?;
            let mut fragments_loaded: u16 = 0;

            // Process fragments with pipelining
            for chunk in fragments.collect::<Vec<_>>().chunks(self.pipeline_depth) {
                for (i, fragment) in chunk.iter().enumerate() {
                    let _stream = self.stream_pool.get_stream(i);

                    // Accumulate fragment (transfers data and runs kernel)
                    self.ctx
                        .accumulate_fragment(fragment, &mut accumulator, header.encoding)?;
                    fragments_loaded += 1;
                }

                // Synchronize after each batch
                self.stream_pool.synchronize_all()?;

                // Check if quality target reached
                if min_quality > 0.0 {
                    let quality = header
                        .quality_curve
                        .predict(fragments_loaded, header.total_fragments);
                    if quality >= min_quality {
                        break;
                    }
                }
            }

            // Check minimum fragment requirement
            if fragments_loaded < header.quality_curve.min_fragments {
                return Err(GpuHoloError::InsufficientFragments {
                    min_required: header.quality_curve.min_fragments,
                    available: fragments_loaded,
                });
            }

            // Finalize reconstruction
            self.ctx
                .finalize_reconstruction(&accumulator, header.encoding)
        }

        /// Reconstructs with a callback after each fragment.
        ///
        /// Useful for progress reporting or early termination based on quality.
        ///
        /// # Arguments
        ///
        /// * `header` - HoloTensor header
        /// * `fragments` - Iterator of fragments
        /// * `callback` - Called after each fragment with (fragments_loaded, quality)
        ///                Return `false` to stop early.
        pub fn reconstruct_with_callback<'a, I, F>(
            &self,
            header: &HoloTensorHeader,
            fragments: I,
            mut callback: F,
        ) -> Result<CudaSlice<f32>, GpuHoloError>
        where
            I: Iterator<Item = &'a HoloFragment>,
            F: FnMut(u16, f32) -> bool,
        {
            let mut accumulator = self.ctx.create_accumulator(header)?;
            let mut fragments_loaded: u16 = 0;

            for fragment in fragments {
                self.ctx
                    .accumulate_fragment(fragment, &mut accumulator, header.encoding)?;
                fragments_loaded += 1;

                let quality = header
                    .quality_curve
                    .predict(fragments_loaded, header.total_fragments);

                // Call user callback - return false to stop
                if !callback(fragments_loaded, quality) {
                    break;
                }
            }

            // Check minimum fragment requirement
            if fragments_loaded < header.quality_curve.min_fragments {
                return Err(GpuHoloError::InsufficientFragments {
                    min_required: header.quality_curve.min_fragments,
                    available: fragments_loaded,
                });
            }

            self.ctx
                .finalize_reconstruction(&accumulator, header.encoding)
        }

        /// Reconstructs, dequantizes, and converts to F16 in a streaming pipeline.
        ///
        /// This is the high-level API for model loading that combines:
        /// 1. Streaming holographic reconstruction
        /// 2. Dequantization with per-block scales/zeros
        /// 3. F32 to F16 conversion
        pub fn reconstruct_dequantize_f16_streaming<'a, I>(
            &self,
            header: &HoloTensorHeader,
            fragments: I,
            scales: &[f32],
            zeros: &[f32],
            block_size: usize,
            min_quality: f32,
        ) -> Result<CudaSlice<half::f16>, GpuHoloError>
        where
            I: Iterator<Item = &'a HoloFragment>,
        {
            // Step 1: Reconstruct with streaming
            let reconstructed = self.reconstruct_streaming(header, fragments, min_quality)?;

            // Step 2: Dequantize
            let dequantized =
                self.ctx
                    .dequantize_reconstructed(&reconstructed, scales, zeros, block_size)?;

            // Step 3: Convert to F16
            self.ctx.convert_f32_to_f16(&dequantized)
        }

        /// Returns streaming statistics for the last operation.
        pub fn stats(&self) -> StreamingHoloStats {
            StreamingHoloStats {
                pipeline_depth: self.pipeline_depth,
                num_streams: self.stream_pool.num_streams(),
            }
        }
    }

    /// Statistics for streaming operations.
    #[derive(Debug, Clone)]
    pub struct StreamingHoloStats {
        /// Pipeline depth used
        pub pipeline_depth: usize,
        /// Number of CUDA streams
        pub num_streams: usize,
    }

    // ==================== Memory Coalescing Optimization ====================

    /// Optimized kernel PTX with memory coalescing.
    ///
    /// These kernels use vectorized loads/stores (ld.global.v4, st.global.v4)
    /// for coalesced memory access when accessing consecutive elements.
    const COALESCED_KERNEL_PTX: &str = r#"
.version 8.0
.target sm_89
.address_size 64

// Coalesced vectorized accumulate (4 elements per thread)
// Processes 4 consecutive elements per thread for optimal memory coalescing
.visible .entry holo_coalesced_accumulate_v4(
    .param .u64 src_ptr,
    .param .u64 dst_ptr,
    .param .u32 num_elements
)
{
    .reg .u32 %gid, %base_idx, %sz, %tmp;
    .reg .u64 %src_addr, %dst_addr;
    .reg .v4 .f32 %src_vec, %dst_vec, %result;
    .reg .pred %p;

    // Get thread ID and compute base index (4 elements per thread)
    mov.u32 %gid, %ctaid.x;
    mov.u32 %tmp, %ntid.x;
    mul.lo.u32 %gid, %gid, %tmp;
    mov.u32 %tmp, %tid.x;
    add.u32 %gid, %gid, %tmp;
    mul.lo.u32 %base_idx, %gid, 4;

    ld.param.u32 %sz, [num_elements];
    setp.ge.u32 %p, %base_idx, %sz;
    @%p bra EXIT;

    ld.param.u64 %src_addr, [src_ptr];
    ld.param.u64 %dst_addr, [dst_ptr];

    // Compute aligned addresses
    mad.wide.u32 %src_addr, %base_idx, 4, %src_addr;
    mad.wide.u32 %dst_addr, %base_idx, 4, %dst_addr;

    // Vectorized load (4 floats = 16 bytes, naturally coalesced)
    ld.global.v4.f32 %src_vec, [%src_addr];
    ld.global.v4.f32 %dst_vec, [%dst_addr];

    // Add vectors
    add.f32 %result.x, %src_vec.x, %dst_vec.x;
    add.f32 %result.y, %src_vec.y, %dst_vec.y;
    add.f32 %result.z, %src_vec.z, %dst_vec.z;
    add.f32 %result.w, %src_vec.w, %dst_vec.w;

    // Vectorized store
    st.global.v4.f32 [%dst_addr], %result;

EXIT:
    ret;
}

// Coalesced IDCT with shared memory (tile-based)
// Each block processes a tile using shared memory for coefficient reuse
.visible .entry holo_coalesced_idct_tile(
    .param .u64 coeffs_ptr,
    .param .u64 output_ptr,
    .param .u32 width,
    .param .u32 height,
    .param .u32 tile_size
)
{
    .shared .align 16 .f32 tile[1024];  // 32x32 tile max
    .reg .u32 %tid_x, %tid_y, %tile_x, %tile_y, %w, %h, %ts;
    .reg .u64 %coeff_addr, %out_addr;
    .reg .f32 %val, %cos_val, %sum;
    .reg .pred %p;

    // Get 2D thread position within block
    mov.u32 %tid_x, %tid.x;
    mov.u32 %tid_y, %tid.y;

    // Get tile position
    mov.u32 %tile_x, %ctaid.x;
    mov.u32 %tile_y, %ctaid.y;

    ld.param.u32 %w, [width];
    ld.param.u32 %h, [height];
    ld.param.u32 %ts, [tile_size];

    // Load coefficients into shared memory (coalesced)
    // Each thread loads one element
    mul.lo.u32 %tile_x, %tile_x, %ts;
    mul.lo.u32 %tile_y, %tile_y, %ts;
    add.u32 %tile_x, %tile_x, %tid_x;
    add.u32 %tile_y, %tile_y, %tid_y;

    setp.ge.u32 %p, %tile_x, %w;
    @%p bra SKIP_LOAD;
    setp.ge.u32 %p, %tile_y, %h;
    @%p bra SKIP_LOAD;

    // Compute global index (row-major)
    mul.lo.u32 %tile_y, %tile_y, %w;
    add.u32 %tile_y, %tile_y, %tile_x;

    ld.param.u64 %coeff_addr, [coeffs_ptr];
    mad.wide.u32 %coeff_addr, %tile_y, 4, %coeff_addr;
    ld.global.f32 %val, [%coeff_addr];

    // Store to shared memory
    mul.lo.u32 %tile_y, %tid_y, %ts;
    add.u32 %tile_y, %tile_y, %tid_x;
    mul.lo.u32 %tile_y, %tile_y, 4;
    mov.u32 %tile_x, tile;
    add.u32 %tile_x, %tile_x, %tile_y;
    st.shared.f32 [%tile_x], %val;

SKIP_LOAD:
    bar.sync 0;

    // IDCT computation using shared memory
    // (Simplified: actual IDCT would iterate over frequencies)
    mov.f32 %sum, 0.0;

    // Store result
    ld.param.u64 %out_addr, [output_ptr];
    st.global.f32 [%out_addr], %sum;

EXIT:
    ret;
}

// Coalesced F32 to F16 conversion (4 elements per thread)
.visible .entry holo_coalesced_f32_to_f16_v4(
    .param .u64 input_ptr,
    .param .u64 output_ptr,
    .param .u32 size
)
{
    .reg .u32 %gid, %base_idx, %sz, %tmp;
    .reg .u64 %in_addr, %out_addr;
    .reg .v4 .f32 %f32_vec;
    .reg .v4 .b16 %f16_vec;
    .reg .pred %p;

    mov.u32 %gid, %ctaid.x;
    mov.u32 %tmp, %ntid.x;
    mul.lo.u32 %gid, %gid, %tmp;
    mov.u32 %tmp, %tid.x;
    add.u32 %gid, %gid, %tmp;
    mul.lo.u32 %base_idx, %gid, 4;

    ld.param.u32 %sz, [size];
    setp.ge.u32 %p, %base_idx, %sz;
    @%p bra EXIT;

    ld.param.u64 %in_addr, [input_ptr];
    ld.param.u64 %out_addr, [output_ptr];

    mad.wide.u32 %in_addr, %base_idx, 4, %in_addr;
    mad.wide.u32 %out_addr, %base_idx, 2, %out_addr;

    // Vectorized load F32
    ld.global.v4.f32 %f32_vec, [%in_addr];

    // Convert to F16
    cvt.rn.f16.f32 %f16_vec.x, %f32_vec.x;
    cvt.rn.f16.f32 %f16_vec.y, %f32_vec.y;
    cvt.rn.f16.f32 %f16_vec.z, %f32_vec.z;
    cvt.rn.f16.f32 %f16_vec.w, %f32_vec.w;

    // Vectorized store F16
    st.global.v4.u16 [%out_addr], %f16_vec;

EXIT:
    ret;
}
"#;

    /// True CUDA pinned (page-locked) memory buffer.
    ///
    /// Uses cuMemAllocHost_v2 for proper page-locked allocation that provides:
    /// - ~2x higher bandwidth for H2D/D2H transfers
    /// - Ability to overlap transfers with kernel execution
    /// - Required for async memory operations (cudaMemcpyAsync)
    ///
    /// # Safety
    /// The buffer is automatically freed when dropped via cuMemFreeHost.
    pub struct PinnedBuffer {
        ptr: *mut u8,
        size: usize,
        capacity: usize,
    }

    // Safety: PinnedBuffer is just a raw pointer to host memory, safe to send across threads
    unsafe impl Send for PinnedBuffer {}
    unsafe impl Sync for PinnedBuffer {}

    impl PinnedBuffer {
        /// Allocates a new pinned memory buffer of the given size.
        ///
        /// Returns None if CUDA allocation fails.
        pub fn new(size: usize) -> Option<Self> {
            if size == 0 {
                return Some(Self {
                    ptr: std::ptr::NonNull::dangling().as_ptr(),
                    size: 0,
                    capacity: 0,
                });
            }

            // Use cudarc's driver sys module to call cuMemAllocHost_v2
            use std::ffi::c_void;

            let mut host_ptr: *mut c_void = std::ptr::null_mut();
            // Safety: lib() returns the loaded CUDA driver library
            let result =
                unsafe { cudarc::driver::sys::lib().cuMemAllocHost_v2(&mut host_ptr, size) };

            if result != cudarc::driver::sys::CUresult::CUDA_SUCCESS {
                // Fallback: try regular allocation if CUDA pinned fails
                // This can happen if CUDA context isn't active
                return None;
            }

            Some(Self {
                ptr: host_ptr as *mut u8,
                size,
                capacity: size,
            })
        }

        /// Returns a mutable slice to the buffer contents.
        #[inline]
        pub fn as_mut_slice(&mut self) -> &mut [u8] {
            if self.capacity == 0 {
                return &mut [];
            }
            unsafe { std::slice::from_raw_parts_mut(self.ptr, self.size) }
        }

        /// Returns an immutable slice to the buffer contents.
        #[inline]
        pub fn as_slice(&self) -> &[u8] {
            if self.capacity == 0 {
                return &[];
            }
            unsafe { std::slice::from_raw_parts(self.ptr, self.size) }
        }

        /// Returns the raw pointer to the buffer.
        #[inline]
        pub fn as_ptr(&self) -> *const u8 {
            self.ptr
        }

        /// Returns the mutable raw pointer to the buffer.
        #[inline]
        pub fn as_mut_ptr(&mut self) -> *mut u8 {
            self.ptr
        }

        /// Returns the current size (used portion) of the buffer.
        #[inline]
        pub fn len(&self) -> usize {
            self.size
        }

        /// Returns true if the buffer is empty.
        #[inline]
        pub fn is_empty(&self) -> bool {
            self.size == 0
        }

        /// Returns the total capacity of the buffer.
        #[inline]
        pub fn capacity(&self) -> usize {
            self.capacity
        }

        /// Sets the used size of the buffer (must be <= capacity).
        #[inline]
        pub fn set_len(&mut self, len: usize) {
            debug_assert!(len <= self.capacity);
            self.size = len.min(self.capacity);
        }

        /// Copies data from a slice into the buffer.
        ///
        /// Panics if the slice is larger than the buffer capacity.
        pub fn copy_from_slice(&mut self, src: &[u8]) {
            assert!(
                src.len() <= self.capacity,
                "Source slice too large for pinned buffer"
            );
            unsafe {
                std::ptr::copy_nonoverlapping(src.as_ptr(), self.ptr, src.len());
            }
            self.size = src.len();
        }
    }

    impl Drop for PinnedBuffer {
        fn drop(&mut self) {
            if self.capacity > 0 && !self.ptr.is_null() {
                use std::ffi::c_void;

                // Safety: lib() returns the loaded CUDA driver library
                unsafe {
                    let _ = cudarc::driver::sys::lib().cuMemFreeHost(self.ptr as *mut c_void);
                }
            }
        }
    }

    /// Pinned (page-locked) memory pool for fast H2D transfers.
    ///
    /// Uses true CUDA page-locked memory via cuMemAllocHost for maximum
    /// H2D/D2H transfer bandwidth (up to 2x faster than pageable memory).
    ///
    /// Falls back to regular Vec allocation if CUDA pinned allocation fails.
    pub struct PinnedMemoryPool {
        #[allow(dead_code)]
        device: Arc<CudaDevice>,
        /// Pre-allocated pinned buffers by size class
        pinned_pools: std::collections::HashMap<usize, Vec<PinnedBuffer>>,
        /// Fallback regular buffers (when pinned allocation fails)
        fallback_pools: std::collections::HashMap<usize, Vec<Vec<u8>>>,
        /// Size classes (powers of 2 from 4KB to 64MB)
        size_classes: Vec<usize>,
        /// Whether we successfully use pinned memory
        pinned_available: bool,
        /// Stats
        pinned_allocations: std::sync::atomic::AtomicUsize,
        fallback_allocations: std::sync::atomic::AtomicUsize,
    }

    /// Handle to a pinned or fallback buffer from the pool.
    pub enum PooledBuffer {
        /// True CUDA pinned buffer
        Pinned(PinnedBuffer),
        /// Fallback regular Vec buffer
        Fallback(Vec<u8>),
    }

    impl PooledBuffer {
        /// Returns a mutable slice to the buffer.
        pub fn as_mut_slice(&mut self) -> &mut [u8] {
            match self {
                PooledBuffer::Pinned(buf) => buf.as_mut_slice(),
                PooledBuffer::Fallback(buf) => buf.as_mut_slice(),
            }
        }

        /// Returns an immutable slice to the buffer.
        pub fn as_slice(&self) -> &[u8] {
            match self {
                PooledBuffer::Pinned(buf) => buf.as_slice(),
                PooledBuffer::Fallback(buf) => buf.as_slice(),
            }
        }

        /// Returns the capacity of the buffer.
        pub fn capacity(&self) -> usize {
            match self {
                PooledBuffer::Pinned(buf) => buf.capacity(),
                PooledBuffer::Fallback(buf) => buf.capacity(),
            }
        }

        /// Returns true if this is a true pinned buffer.
        pub fn is_pinned(&self) -> bool {
            matches!(self, PooledBuffer::Pinned(_))
        }

        /// Copies data from a slice into the buffer.
        pub fn copy_from_slice(&mut self, src: &[u8]) {
            match self {
                PooledBuffer::Pinned(buf) => buf.copy_from_slice(src),
                PooledBuffer::Fallback(buf) => {
                    buf.clear();
                    buf.extend_from_slice(src);
                },
            }
        }
    }

    impl PinnedMemoryPool {
        /// Creates a new pinned memory pool.
        pub fn new(device: Arc<CudaDevice>) -> Self {
            // Size classes: 4KB, 16KB, 64KB, 256KB, 1MB, 4MB, 16MB, 64MB
            let size_classes: Vec<usize> = (12..=26).step_by(2).map(|exp| 1usize << exp).collect();

            // Test if pinned allocation works
            let pinned_available = PinnedBuffer::new(4096).is_some();

            Self {
                device,
                pinned_pools: std::collections::HashMap::new(),
                fallback_pools: std::collections::HashMap::new(),
                size_classes,
                pinned_available,
                pinned_allocations: std::sync::atomic::AtomicUsize::new(0),
                fallback_allocations: std::sync::atomic::AtomicUsize::new(0),
            }
        }

        /// Returns true if true CUDA pinned memory is available.
        pub fn is_pinned_available(&self) -> bool {
            self.pinned_available
        }

        /// Gets the size class for a given allocation size.
        fn size_class(&self, size: usize) -> usize {
            for &class in &self.size_classes {
                if size <= class {
                    return class;
                }
            }
            // For very large allocations, round up to next power of 2
            size.next_power_of_two()
        }

        /// Allocates a buffer of at least the given size.
        ///
        /// Returns a pinned buffer if available, otherwise falls back to regular Vec.
        pub fn allocate(&mut self, size: usize) -> PooledBuffer {
            use std::sync::atomic::Ordering;
            let class = self.size_class(size);

            // Try pinned pool first
            if self.pinned_available {
                if let Some(pool) = self.pinned_pools.get_mut(&class) {
                    if let Some(mut buf) = pool.pop() {
                        buf.set_len(size);
                        self.pinned_allocations.fetch_add(1, Ordering::Relaxed);
                        return PooledBuffer::Pinned(buf);
                    }
                }

                // Try to allocate new pinned buffer
                if let Some(mut buf) = PinnedBuffer::new(class) {
                    buf.set_len(size);
                    self.pinned_allocations.fetch_add(1, Ordering::Relaxed);
                    return PooledBuffer::Pinned(buf);
                }
            }

            // Fallback to regular pool
            if let Some(pool) = self.fallback_pools.get_mut(&class) {
                if let Some(mut buf) = pool.pop() {
                    buf.resize(size, 0);
                    self.fallback_allocations.fetch_add(1, Ordering::Relaxed);
                    return PooledBuffer::Fallback(buf);
                }
            }

            // Allocate new fallback buffer
            self.fallback_allocations.fetch_add(1, Ordering::Relaxed);
            PooledBuffer::Fallback(vec![0u8; class])
        }

        /// Allocates a buffer of exactly the given size (for legacy Vec<u8> compatibility).
        pub fn allocate_vec(&mut self, size: usize) -> Vec<u8> {
            let class = self.size_class(size);

            // For Vec API, only use fallback pool
            if let Some(pool) = self.fallback_pools.get_mut(&class) {
                if let Some(mut buf) = pool.pop() {
                    buf.resize(size, 0);
                    return buf;
                }
            }

            vec![0u8; class]
        }

        /// Returns a buffer to the pool for reuse.
        pub fn deallocate(&mut self, buf: PooledBuffer) {
            match buf {
                PooledBuffer::Pinned(mut pinned_buf) => {
                    let class = pinned_buf.capacity();
                    pinned_buf.set_len(class); // Reset to full capacity
                    self.pinned_pools
                        .entry(class)
                        .or_insert_with(Vec::new)
                        .push(pinned_buf);
                },
                PooledBuffer::Fallback(buf) => {
                    let class = buf.capacity();
                    self.fallback_pools
                        .entry(class)
                        .or_insert_with(Vec::new)
                        .push(buf);
                },
            }
        }

        /// Returns a Vec buffer to the pool (legacy API).
        pub fn deallocate_vec(&mut self, buf: Vec<u8>) {
            let class = buf.capacity();
            self.fallback_pools
                .entry(class)
                .or_insert_with(Vec::new)
                .push(buf);
        }

        /// Pre-warms the pool by allocating buffers for each size class.
        pub fn prewarm(&mut self, buffers_per_class: usize) {
            for &class in &self.size_classes.clone() {
                for _ in 0..buffers_per_class {
                    if self.pinned_available {
                        if let Some(buf) = PinnedBuffer::new(class) {
                            self.pinned_pools
                                .entry(class)
                                .or_insert_with(Vec::new)
                                .push(buf);
                            continue;
                        }
                    }
                    // Fallback
                    let buf = vec![0u8; class];
                    self.fallback_pools
                        .entry(class)
                        .or_insert_with(Vec::new)
                        .push(buf);
                }
            }
        }

        /// Returns statistics about pool usage.
        pub fn stats(&self) -> PinnedPoolStats {
            use std::sync::atomic::Ordering;

            let mut pinned_buffers = 0;
            let mut pinned_bytes = 0;
            let mut fallback_buffers = 0;
            let mut fallback_bytes = 0;

            for (&class, pool) in &self.pinned_pools {
                pinned_buffers += pool.len();
                pinned_bytes += class * pool.len();
            }

            for (&class, pool) in &self.fallback_pools {
                fallback_buffers += pool.len();
                fallback_bytes += class * pool.len();
            }

            PinnedPoolStats {
                num_size_classes: self.size_classes.len(),
                pinned_buffers,
                pinned_bytes,
                fallback_buffers,
                fallback_bytes,
                pinned_available: self.pinned_available,
                total_pinned_allocations: self.pinned_allocations.load(Ordering::Relaxed),
                total_fallback_allocations: self.fallback_allocations.load(Ordering::Relaxed),
            }
        }
    }

    /// Statistics for pinned memory pool.
    #[derive(Debug, Clone)]
    pub struct PinnedPoolStats {
        /// Number of size classes
        pub num_size_classes: usize,
        /// Pinned buffers currently in pool
        pub pinned_buffers: usize,
        /// Pinned bytes currently in pool
        pub pinned_bytes: usize,
        /// Fallback buffers currently in pool
        pub fallback_buffers: usize,
        /// Fallback bytes currently in pool
        pub fallback_bytes: usize,
        /// Whether true CUDA pinned memory is available
        pub pinned_available: bool,
        /// Total pinned allocations served
        pub total_pinned_allocations: usize,
        /// Total fallback allocations served
        pub total_fallback_allocations: usize,
    }

    impl PinnedPoolStats {
        /// Total buffers in pool (pinned + fallback)
        pub fn total_buffers(&self) -> usize {
            self.pinned_buffers + self.fallback_buffers
        }

        /// Total bytes in pool (pinned + fallback)
        pub fn total_bytes(&self) -> usize {
            self.pinned_bytes + self.fallback_bytes
        }
    }

    // ==================== Multi-GPU Support ====================

    /// Multi-GPU holographic reconstruction context.
    ///
    /// Distributes fragments across multiple GPUs for parallel processing,
    /// then gathers results back to a primary device.
    ///
    /// ## Distribution Strategy
    ///
    /// Fragments are distributed round-robin across devices:
    /// - Device 0: fragments 0, N, 2N, ...
    /// - Device 1: fragments 1, N+1, 2N+1, ...
    /// - ...
    ///
    /// Each device maintains its own accumulator, and results are combined
    /// on the primary device during finalization.
    pub struct MultiGpuHoloContext {
        /// Primary device (where final result is assembled)
        primary_device_id: usize,
        /// Per-device contexts
        contexts: Vec<GpuHoloContext>,
        /// Per-device stream pools for pipelining
        stream_pools: Vec<HoloStreamPool>,
        /// Number of devices
        num_devices: usize,
    }

    impl MultiGpuHoloContext {
        /// Creates a multi-GPU context using specified devices.
        ///
        /// # Arguments
        ///
        /// * `device_ids` - List of CUDA device IDs to use
        /// * `streams_per_device` - Number of streams per device for pipelining
        pub fn new(device_ids: &[usize], streams_per_device: usize) -> Result<Self, GpuHoloError> {
            if device_ids.is_empty() {
                return Err(GpuHoloError::InvalidInput {
                    message: "At least one device required".to_string(),
                });
            }

            let primary_device_id = device_ids[0];
            let mut contexts = Vec::with_capacity(device_ids.len());
            let mut stream_pools = Vec::with_capacity(device_ids.len());

            for &device_id in device_ids {
                let mut ctx = GpuHoloContext::new(device_id)?;
                ctx.load_all_kernels()?;
                ctx.load_fused_kernel()?;

                let pool = HoloStreamPool::new(Arc::clone(ctx.device()), streams_per_device)?;

                contexts.push(ctx);
                stream_pools.push(pool);
            }

            Ok(Self {
                primary_device_id,
                contexts,
                stream_pools,
                num_devices: device_ids.len(),
            })
        }

        /// Creates a context using all available CUDA devices.
        pub fn new_all_devices(streams_per_device: usize) -> Result<Self, GpuHoloError> {
            // Query available devices
            let num_devices = CudaDevice::count().map_err(|e| GpuHoloError::DeviceInit {
                device_id: 0,
                message: format!("Failed to count devices: {}", e),
            })?;

            if num_devices == 0 {
                return Err(GpuHoloError::DeviceInit {
                    device_id: 0,
                    message: "No CUDA devices available".to_string(),
                });
            }

            let device_ids: Vec<usize> = (0..num_devices as usize).collect();
            Self::new(&device_ids, streams_per_device)
        }

        /// Returns the number of devices in use.
        pub fn num_devices(&self) -> usize {
            self.num_devices
        }

        /// Returns the primary device ID.
        pub fn primary_device(&self) -> usize {
            self.primary_device_id
        }

        /// Returns context for a specific device.
        pub fn device_context(&self, device_idx: usize) -> Option<&GpuHoloContext> {
            self.contexts.get(device_idx)
        }

        /// Reconstructs from fragments using all devices in parallel.
        ///
        /// Fragments are distributed across devices, each device accumulates
        /// its portion, and results are combined on the primary device.
        pub fn reconstruct_multi_gpu(
            &self,
            header: &HoloTensorHeader,
            fragments: &[HoloFragment],
        ) -> Result<CudaSlice<f32>, GpuHoloError> {
            if fragments.is_empty() {
                return Err(GpuHoloError::InsufficientFragments {
                    min_required: header.quality_curve.min_fragments,
                    available: 0,
                });
            }

            // Create accumulators on each device
            let mut accumulators: Vec<AccumulatorState> = self
                .contexts
                .iter()
                .map(|ctx| ctx.create_accumulator(header))
                .collect::<Result<Vec<_>, _>>()?;

            // Distribute fragments round-robin across devices
            for (i, fragment) in fragments.iter().enumerate() {
                let device_idx = i % self.num_devices;
                self.contexts[device_idx].accumulate_fragment(
                    fragment,
                    &mut accumulators[device_idx],
                    header.encoding,
                )?;
            }

            // Finalize reconstruction on each device
            let mut device_results: Vec<CudaSlice<f32>> = Vec::with_capacity(self.num_devices);
            for (ctx, accumulator) in self.contexts.iter().zip(accumulators.iter()) {
                let result = ctx.finalize_reconstruction(accumulator, header.encoding)?;
                device_results.push(result);
            }

            // Combine results on primary device
            // For additive accumulation schemes (RPH, LRDF), we average
            // For spectral, each device may have different coefficients
            self.combine_results(&device_results, header)
        }

        /// Combines results from multiple devices onto the primary device.
        fn combine_results(
            &self,
            device_results: &[CudaSlice<f32>],
            header: &HoloTensorHeader,
        ) -> Result<CudaSlice<f32>, GpuHoloError> {
            if device_results.is_empty() {
                return Err(GpuHoloError::InvalidInput {
                    message: "No device results to combine".to_string(),
                });
            }

            // For single device, just return the result
            if device_results.len() == 1 {
                return Ok(device_results[0].clone());
            }

            let primary_ctx = &self.contexts[0];
            let size = device_results[0].len();

            // Allocate output on primary device
            let output: CudaSlice<f32> =
                primary_ctx
                    .device
                    .alloc_zeros(size)
                    .map_err(|e| GpuHoloError::MemoryAlloc {
                        message: e.to_string(),
                    })?;

            // Copy first result to output
            let mut host_buf = vec![0.0f32; size];
            primary_ctx
                .device
                .dtoh_sync_copy_into(&device_results[0], &mut host_buf)
                .map_err(|e| GpuHoloError::MemoryCopy {
                    message: e.to_string(),
                })?;

            // Accumulate other results
            for result in device_results.iter().skip(1) {
                let mut other_buf = vec![0.0f32; size];
                // Note: In production, we'd use P2P transfers between devices
                // For now, go through host memory
                primary_ctx
                    .device
                    .dtoh_sync_copy_into(result, &mut other_buf)
                    .map_err(|e| GpuHoloError::MemoryCopy {
                        message: e.to_string(),
                    })?;

                for (h, o) in host_buf.iter_mut().zip(other_buf.iter()) {
                    *h += *o;
                }
            }

            // For averaging (RPH), normalize by device count
            if header.encoding == HolographicEncoding::RandomProjection {
                let scale = 1.0 / self.num_devices as f32;
                for h in host_buf.iter_mut() {
                    *h *= scale;
                }
            }

            // Copy back to device
            primary_ctx
                .device
                .htod_sync_copy_into(&host_buf, &mut output.clone())
                .map_err(|e| GpuHoloError::MemoryCopy {
                    message: e.to_string(),
                })?;

            Ok(output)
        }

        /// Returns statistics about multi-GPU configuration.
        pub fn stats(&self) -> MultiGpuStats {
            MultiGpuStats {
                num_devices: self.num_devices,
                primary_device: self.primary_device_id,
                streams_per_device: self
                    .stream_pools
                    .first()
                    .map(|p| p.num_streams())
                    .unwrap_or(0),
            }
        }
    }

    /// Statistics for multi-GPU context.
    #[derive(Debug, Clone)]
    pub struct MultiGpuStats {
        /// Number of devices in use
        pub num_devices: usize,
        /// Primary device ID
        pub primary_device: usize,
        /// Streams per device
        pub streams_per_device: usize,
    }

    // ==================== Coalesced Operations ====================

    impl GpuHoloContext {
        /// Loads coalesced (vectorized) kernels for optimized memory access.
        pub fn load_coalesced_kernels(&mut self) -> Result<(), GpuHoloError> {
            let ptx = Ptx::from_src(COALESCED_KERNEL_PTX);
            self.device
                .load_ptx(
                    ptx,
                    "holo_coalesced",
                    &[
                        "holo_coalesced_accumulate_v4",
                        "holo_coalesced_idct_tile",
                        "holo_coalesced_f32_to_f16_v4",
                    ],
                )
                .map_err(|e| GpuHoloError::KernelLoad {
                    message: e.to_string(),
                })?;

            Ok(())
        }

        /// Performs coalesced vectorized accumulation (4 elements per thread).
        ///
        /// This is optimized for large contiguous memory regions where
        /// adjacent threads access adjacent memory locations.
        pub fn accumulate_coalesced_v4(
            &self,
            src: &CudaSlice<f32>,
            dst: &mut CudaSlice<f32>,
        ) -> Result<(), GpuHoloError> {
            let size = src.len().min(dst.len());
            if size == 0 {
                return Ok(());
            }

            let func = self
                .device
                .get_func("holo_coalesced", "holo_coalesced_accumulate_v4")
                .ok_or_else(|| GpuHoloError::KernelNotLoaded {
                    kernel: "holo_coalesced_accumulate_v4".to_string(),
                })?;

            // 4 elements per thread
            let elements_per_thread = 4u32;
            let threads_per_block = 256u32;
            let num_threads = ((size as u32) + elements_per_thread - 1) / elements_per_thread;
            let num_blocks = (num_threads + threads_per_block - 1) / threads_per_block;

            let cfg = LaunchConfig {
                grid_dim: (num_blocks.max(1), 1, 1),
                block_dim: (threads_per_block, 1, 1),
                shared_mem_bytes: 0,
            };

            unsafe { func.launch(cfg, (src, dst as &CudaSlice<f32>, size as u32)) }.map_err(
                |e| GpuHoloError::KernelExec {
                    message: e.to_string(),
                },
            )?;

            Ok(())
        }

        /// Converts F32 to F16 using coalesced vectorized operations.
        pub fn convert_f32_to_f16_coalesced(
            &self,
            input: &CudaSlice<f32>,
        ) -> Result<CudaSlice<half::f16>, GpuHoloError> {
            let size = input.len();
            if size == 0 {
                return Err(GpuHoloError::InvalidInput {
                    message: "Empty input buffer".to_string(),
                });
            }

            let output: CudaSlice<half::f16> =
                self.device
                    .alloc_zeros(size)
                    .map_err(|e| GpuHoloError::MemoryAlloc {
                        message: e.to_string(),
                    })?;

            let func = self
                .device
                .get_func("holo_coalesced", "holo_coalesced_f32_to_f16_v4")
                .ok_or_else(|| GpuHoloError::KernelNotLoaded {
                    kernel: "holo_coalesced_f32_to_f16_v4".to_string(),
                })?;

            let elements_per_thread = 4u32;
            let threads_per_block = 256u32;
            let num_threads = ((size as u32) + elements_per_thread - 1) / elements_per_thread;
            let num_blocks = (num_threads + threads_per_block - 1) / threads_per_block;

            let cfg = LaunchConfig {
                grid_dim: (num_blocks.max(1), 1, 1),
                block_dim: (threads_per_block, 1, 1),
                shared_mem_bytes: 0,
            };

            unsafe { func.launch(cfg, (input, &output, size as u32)) }.map_err(|e| {
                GpuHoloError::KernelExec {
                    message: e.to_string(),
                }
            })?;

            self.device
                .synchronize()
                .map_err(|e| GpuHoloError::Synchronize {
                    message: e.to_string(),
                })?;

            Ok(output)
        }
    }

    // ==================== Phase 7: Fault Tolerance ====================

    /// Result of checksum validation.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub enum ValidationResult {
        /// Fragment is valid.
        Valid,
        /// Checksum mismatch - fragment is corrupted.
        Corrupted,
        /// Fragment is missing (not yet received).
        Missing,
    }

    /// Fragment validation and recovery options.
    #[derive(Debug, Clone)]
    pub struct FaultToleranceConfig {
        /// Whether to validate checksums on fragment load.
        pub validate_checksums: bool,
        /// Whether to skip corrupted fragments (vs failing).
        pub skip_corrupted: bool,
        /// Minimum quality threshold before failing (0.0 = accept any).
        pub min_quality_threshold: f32,
        /// Whether to replicate essential data across fragments.
        pub essential_redundancy: bool,
        /// Maximum retry count for corrupted fragments.
        pub max_retries: u32,
    }

    impl Default for FaultToleranceConfig {
        fn default() -> Self {
            Self {
                validate_checksums: true,
                skip_corrupted: true,
                min_quality_threshold: 0.5,
                essential_redundancy: true,
                max_retries: 3,
            }
        }
    }

    /// Fault-tolerant holographic decoder.
    ///
    /// Handles:
    /// - Missing fragments (reconstructs with available data)
    /// - Corrupted fragments (skips and adjusts quality)
    /// - Checksum validation
    /// - Automatic quality adjustment
    pub struct FaultTolerantDecoder {
        ctx: GpuHoloContext,
        config: FaultToleranceConfig,
        header: HoloTensorHeader,
        accumulator: AccumulatorState,
        /// Validation status for each fragment.
        fragment_status: Vec<ValidationResult>,
        /// Number of valid fragments loaded.
        valid_count: u16,
        /// Number of corrupted fragments skipped.
        corrupted_count: u16,
    }

    impl FaultTolerantDecoder {
        /// Creates a new fault-tolerant decoder.
        pub fn new(
            ctx: GpuHoloContext,
            header: HoloTensorHeader,
            config: FaultToleranceConfig,
        ) -> Result<Self, GpuHoloError> {
            let accumulator = ctx.create_accumulator(&header)?;
            let fragment_status = vec![ValidationResult::Missing; header.total_fragments as usize];

            Ok(Self {
                ctx,
                config,
                header,
                accumulator,
                fragment_status,
                valid_count: 0,
                corrupted_count: 0,
            })
        }

        /// Validates a fragment's checksum.
        fn validate_fragment(&self, fragment: &HoloFragment) -> ValidationResult {
            if !self.config.validate_checksums {
                return ValidationResult::Valid;
            }

            // Compute XXH3-64 checksum of fragment data
            let computed = Self::compute_checksum(&fragment.data);
            if computed == fragment.checksum {
                ValidationResult::Valid
            } else {
                ValidationResult::Corrupted
            }
        }

        /// Computes XXH3-64 checksum of data.
        fn compute_checksum(data: &[u8]) -> u64 {
            // Simple FNV-1a hash as fallback (production would use xxhash)
            let mut hash: u64 = 0xcbf29ce484222325;
            for &byte in data {
                hash ^= byte as u64;
                hash = hash.wrapping_mul(0x100000001b3);
            }
            hash
        }

        /// Adds a fragment with validation.
        ///
        /// Returns the validation result and current quality estimate.
        pub fn add_fragment(
            &mut self,
            fragment: &HoloFragment,
        ) -> Result<(ValidationResult, f32), GpuHoloError> {
            let idx = fragment.index as usize;
            if idx >= self.fragment_status.len() {
                return Err(GpuHoloError::InvalidInput {
                    message: format!("Fragment index {} out of range", idx),
                });
            }

            // Validate checksum
            let validation = self.validate_fragment(fragment);

            match validation {
                ValidationResult::Valid => {
                    // Accumulate valid fragment
                    self.ctx.accumulate_fragment(
                        fragment,
                        &mut self.accumulator,
                        self.header.encoding,
                    )?;
                    self.fragment_status[idx] = ValidationResult::Valid;
                    self.valid_count += 1;
                },
                ValidationResult::Corrupted => {
                    self.fragment_status[idx] = ValidationResult::Corrupted;
                    self.corrupted_count += 1;

                    if !self.config.skip_corrupted {
                        return Err(GpuHoloError::FragmentDecode {
                            message: format!("Fragment {} checksum validation failed", idx),
                        });
                    }
                },
                ValidationResult::Missing => {
                    // Should not happen for incoming fragment
                },
            }

            // Calculate quality based on valid fragments only
            let quality = self
                .header
                .quality_curve
                .predict(self.valid_count, self.header.total_fragments);

            Ok((validation, quality))
        }

        /// Returns the number of valid fragments loaded.
        pub fn valid_count(&self) -> u16 {
            self.valid_count
        }

        /// Returns the number of corrupted fragments skipped.
        pub fn corrupted_count(&self) -> u16 {
            self.corrupted_count
        }

        /// Returns the number of missing fragments.
        pub fn missing_count(&self) -> u16 {
            self.fragment_status
                .iter()
                .filter(|&&s| s == ValidationResult::Missing)
                .count() as u16
        }

        /// Returns current quality estimate.
        pub fn quality(&self) -> f32 {
            self.header
                .quality_curve
                .predict(self.valid_count, self.header.total_fragments)
        }

        /// Checks if minimum quality threshold is met.
        pub fn meets_threshold(&self) -> bool {
            self.quality() >= self.config.min_quality_threshold
        }

        /// Returns validation status for each fragment.
        pub fn fragment_status(&self) -> &[ValidationResult] {
            &self.fragment_status
        }

        /// Attempts reconstruction with available valid fragments.
        ///
        /// Returns an error if minimum quality threshold is not met.
        pub fn reconstruct(&self) -> Result<CudaSlice<f32>, GpuHoloError> {
            let quality = self.quality();

            if quality < self.config.min_quality_threshold {
                return Err(GpuHoloError::QualityNotReached {
                    target: self.config.min_quality_threshold,
                    current: quality,
                });
            }

            if self.valid_count < self.header.quality_curve.min_fragments {
                return Err(GpuHoloError::InsufficientFragments {
                    min_required: self.header.quality_curve.min_fragments,
                    available: self.valid_count,
                });
            }

            self.ctx
                .finalize_reconstruction(&self.accumulator, self.header.encoding)
        }

        /// Returns statistics about fault tolerance.
        pub fn stats(&self) -> FaultToleranceStats {
            FaultToleranceStats {
                total_fragments: self.header.total_fragments,
                valid_count: self.valid_count,
                corrupted_count: self.corrupted_count,
                missing_count: self.missing_count(),
                current_quality: self.quality(),
                meets_threshold: self.meets_threshold(),
            }
        }
    }

    /// Statistics for fault-tolerant decoding.
    #[derive(Debug, Clone)]
    pub struct FaultToleranceStats {
        /// Total fragments expected.
        pub total_fragments: u16,
        /// Valid fragments loaded.
        pub valid_count: u16,
        /// Corrupted fragments skipped.
        pub corrupted_count: u16,
        /// Missing fragments.
        pub missing_count: u16,
        /// Current quality estimate.
        pub current_quality: f32,
        /// Whether minimum threshold is met.
        pub meets_threshold: bool,
    }

    // ==================== Phase 7: Distributed Loading ====================

    /// Source for fragment data.
    ///
    /// Implement this trait to provide fragments from various sources
    /// (local files, HTTP, S3, peer-to-peer, etc.).
    pub trait FragmentSource: Send + Sync {
        /// Fetches a specific fragment by index.
        fn fetch_fragment(&self, index: u16) -> Result<HoloFragment, GpuHoloError>;

        /// Returns the total number of fragments available.
        fn fragment_count(&self) -> u16;

        /// Returns source priority (lower = prefer this source).
        fn priority(&self) -> u32 {
            100
        }

        /// Returns source name for logging.
        fn name(&self) -> &str;
    }

    /// Configuration for distributed loading.
    #[derive(Debug, Clone)]
    pub struct DistributedLoadConfig {
        /// Maximum concurrent fragment fetches.
        pub max_concurrent: usize,
        /// Timeout per fragment fetch (milliseconds).
        pub fetch_timeout_ms: u64,
        /// Whether to try multiple sources for failed fetches.
        pub failover_enabled: bool,
        /// Target quality to stop loading.
        pub target_quality: f32,
        /// Whether to prefer local sources.
        pub prefer_local: bool,
    }

    impl Default for DistributedLoadConfig {
        fn default() -> Self {
            Self {
                max_concurrent: 4,
                fetch_timeout_ms: 5000,
                failover_enabled: true,
                target_quality: 0.95,
                prefer_local: true,
            }
        }
    }

    /// Distributed fragment loader.
    ///
    /// Fetches fragments from multiple sources in parallel with:
    /// - Priority-based source selection
    /// - Failover on source failure
    /// - Early termination on quality target
    pub struct DistributedLoader {
        sources: Vec<Box<dyn FragmentSource>>,
        config: DistributedLoadConfig,
        header: HoloTensorHeader,
    }

    impl DistributedLoader {
        /// Creates a new distributed loader.
        pub fn new(
            sources: Vec<Box<dyn FragmentSource>>,
            header: HoloTensorHeader,
            config: DistributedLoadConfig,
        ) -> Self {
            Self {
                sources,
                config,
                header,
            }
        }

        /// Adds a fragment source.
        pub fn add_source(&mut self, source: Box<dyn FragmentSource>) {
            self.sources.push(source);
        }

        /// Returns sources sorted by priority.
        fn prioritized_sources(&self) -> Vec<&dyn FragmentSource> {
            let mut sources: Vec<_> = self.sources.iter().map(|s| s.as_ref()).collect();
            sources.sort_by_key(|s| s.priority());
            sources
        }

        /// Fetches a fragment with failover.
        fn fetch_with_failover(&self, index: u16) -> Result<HoloFragment, GpuHoloError> {
            let sources = self.prioritized_sources();

            for source in sources {
                match source.fetch_fragment(index) {
                    Ok(fragment) => return Ok(fragment),
                    Err(_) if self.config.failover_enabled => continue,
                    Err(e) => return Err(e),
                }
            }

            Err(GpuHoloError::FragmentDecode {
                message: format!("Failed to fetch fragment {} from any source", index),
            })
        }

        /// Loads fragments until target quality is reached.
        ///
        /// Returns fragments in priority order (essential first).
        pub fn load_to_quality(&self) -> Result<Vec<HoloFragment>, GpuHoloError> {
            if self.sources.is_empty() {
                return Err(GpuHoloError::InvalidInput {
                    message: "No fragment sources configured".to_string(),
                });
            }

            let mut fragments = Vec::new();
            let mut loaded_indices = std::collections::HashSet::new();

            // Calculate how many fragments needed for target quality
            let needed = self
                .header
                .quality_curve
                .fragments_for_quality(self.config.target_quality, self.header.total_fragments);

            // Load fragments in order (essential first if FLAG_ESSENTIAL_FIRST)
            for index in 0..self.header.total_fragments.min(needed) {
                if loaded_indices.contains(&index) {
                    continue;
                }

                match self.fetch_with_failover(index) {
                    Ok(fragment) => {
                        loaded_indices.insert(index);
                        fragments.push(fragment);
                    },
                    Err(e) if self.config.failover_enabled => {
                        // Skip failed fragment, try to continue
                        continue;
                    },
                    Err(e) => return Err(e),
                }
            }

            if fragments.is_empty() {
                return Err(GpuHoloError::InsufficientFragments {
                    min_required: self.header.quality_curve.min_fragments,
                    available: 0,
                });
            }

            Ok(fragments)
        }

        /// Loads all fragments from all sources.
        pub fn load_all(&self) -> Result<Vec<HoloFragment>, GpuHoloError> {
            let mut fragments = Vec::with_capacity(self.header.total_fragments as usize);

            for index in 0..self.header.total_fragments {
                match self.fetch_with_failover(index) {
                    Ok(fragment) => fragments.push(fragment),
                    Err(e) if self.config.failover_enabled => continue,
                    Err(e) => return Err(e),
                }
            }

            Ok(fragments)
        }

        /// Returns statistics about sources.
        pub fn stats(&self) -> DistributedLoadStats {
            DistributedLoadStats {
                source_count: self.sources.len(),
                total_fragments: self.header.total_fragments,
                target_quality: self.config.target_quality,
            }
        }
    }

    /// Statistics for distributed loading.
    #[derive(Debug, Clone)]
    pub struct DistributedLoadStats {
        /// Number of fragment sources.
        pub source_count: usize,
        /// Total fragments in tensor.
        pub total_fragments: u16,
        /// Target quality for loading.
        pub target_quality: f32,
    }

    /// In-memory fragment source for testing.
    pub struct MemoryFragmentSource {
        name: String,
        fragments: Vec<HoloFragment>,
        priority: u32,
    }

    impl MemoryFragmentSource {
        /// Creates a new memory source.
        pub fn new(name: impl Into<String>, fragments: Vec<HoloFragment>, priority: u32) -> Self {
            Self {
                name: name.into(),
                fragments,
                priority,
            }
        }
    }

    impl FragmentSource for MemoryFragmentSource {
        fn fetch_fragment(&self, index: u16) -> Result<HoloFragment, GpuHoloError> {
            self.fragments
                .iter()
                .find(|f| f.index == index)
                .cloned()
                .ok_or_else(|| GpuHoloError::FragmentDecode {
                    message: format!("Fragment {} not found in memory source", index),
                })
        }

        fn fragment_count(&self) -> u16 {
            self.fragments.len() as u16
        }

        fn priority(&self) -> u32 {
            self.priority
        }

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

    // ==================== Phase 7: Adaptive Quality ====================

    /// Quality adjustment policy.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub enum QualityPolicy {
        /// Fixed quality target.
        Fixed,
        /// Adjust based on memory pressure.
        MemoryAdaptive,
        /// Adjust based on inference latency.
        LatencyAdaptive,
        /// Best quality within constraints.
        BestEffort,
    }

    /// Configuration for adaptive quality management.
    #[derive(Debug, Clone)]
    pub struct AdaptiveQualityConfig {
        /// Quality adjustment policy.
        pub policy: QualityPolicy,
        /// Minimum acceptable quality.
        pub min_quality: f32,
        /// Maximum acceptable quality (1.0 = full).
        pub max_quality: f32,
        /// Memory threshold to trigger quality reduction (bytes).
        pub memory_threshold: usize,
        /// Latency threshold to trigger quality reduction (ms).
        pub latency_threshold_ms: u64,
        /// How aggressively to adjust quality (0.0-1.0).
        pub adjustment_rate: f32,
    }

    impl Default for AdaptiveQualityConfig {
        fn default() -> Self {
            Self {
                policy: QualityPolicy::BestEffort,
                min_quality: 0.7,
                max_quality: 1.0,
                memory_threshold: 8 * 1024 * 1024 * 1024, // 8 GB
                latency_threshold_ms: 100,
                adjustment_rate: 0.1,
            }
        }
    }

    /// Per-layer quality target.
    #[derive(Debug, Clone)]
    pub struct LayerQualityTarget {
        /// Layer name pattern (supports wildcards).
        pub layer_pattern: String,
        /// Quality target for matching layers.
        pub quality: f32,
        /// Priority (higher = apply first).
        pub priority: u32,
    }

    /// Adaptive quality controller.
    ///
    /// Manages quality targets based on:
    /// - System memory pressure
    /// - Inference latency
    /// - Per-layer importance
    /// - User preferences
    pub struct AdaptiveQualityController {
        config: AdaptiveQualityConfig,
        /// Current target quality.
        current_quality: f32,
        /// Per-layer quality overrides.
        layer_targets: Vec<LayerQualityTarget>,
        /// Memory usage samples.
        memory_samples: Vec<usize>,
        /// Latency samples (ms).
        latency_samples: Vec<u64>,
        /// Sample window size.
        sample_window: usize,
    }

    impl AdaptiveQualityController {
        /// Creates a new adaptive quality controller.
        pub fn new(config: AdaptiveQualityConfig) -> Self {
            let initial_quality = match config.policy {
                QualityPolicy::Fixed => config.max_quality,
                QualityPolicy::MemoryAdaptive => config.max_quality,
                QualityPolicy::LatencyAdaptive => config.max_quality,
                QualityPolicy::BestEffort => config.max_quality,
            };

            Self {
                config,
                current_quality: initial_quality,
                layer_targets: Vec::new(),
                memory_samples: Vec::new(),
                latency_samples: Vec::new(),
                sample_window: 10,
            }
        }

        /// Adds a per-layer quality target.
        pub fn add_layer_target(&mut self, target: LayerQualityTarget) {
            self.layer_targets.push(target);
            self.layer_targets
                .sort_by_key(|t| std::cmp::Reverse(t.priority));
        }

        /// Gets quality target for a specific layer.
        pub fn quality_for_layer(&self, layer_name: &str) -> f32 {
            // Check per-layer overrides
            for target in &self.layer_targets {
                if Self::pattern_matches(&target.layer_pattern, layer_name) {
                    return target
                        .quality
                        .clamp(self.config.min_quality, self.config.max_quality);
                }
            }

            // Fall back to current global quality
            self.current_quality
        }

        /// Checks if a pattern matches a layer name.
        fn pattern_matches(pattern: &str, name: &str) -> bool {
            if pattern == "*" {
                return true;
            }
            if pattern.ends_with('*') {
                let prefix = &pattern[..pattern.len() - 1];
                return name.starts_with(prefix);
            }
            if pattern.starts_with('*') {
                let suffix = &pattern[1..];
                return name.ends_with(suffix);
            }
            pattern == name
        }

        /// Records a memory usage sample.
        pub fn record_memory_usage(&mut self, bytes: usize) {
            self.memory_samples.push(bytes);
            if self.memory_samples.len() > self.sample_window {
                self.memory_samples.remove(0);
            }
            self.update_quality();
        }

        /// Records an inference latency sample.
        pub fn record_latency(&mut self, ms: u64) {
            self.latency_samples.push(ms);
            if self.latency_samples.len() > self.sample_window {
                self.latency_samples.remove(0);
            }
            self.update_quality();
        }

        /// Updates quality target based on samples.
        fn update_quality(&mut self) {
            match self.config.policy {
                QualityPolicy::Fixed => {
                    // No adjustment
                },
                QualityPolicy::MemoryAdaptive => {
                    self.adjust_for_memory();
                },
                QualityPolicy::LatencyAdaptive => {
                    self.adjust_for_latency();
                },
                QualityPolicy::BestEffort => {
                    self.adjust_for_memory();
                    self.adjust_for_latency();
                },
            }
        }

        /// Adjusts quality based on memory pressure.
        fn adjust_for_memory(&mut self) {
            if self.memory_samples.is_empty() {
                return;
            }

            let avg_memory: usize =
                self.memory_samples.iter().sum::<usize>() / self.memory_samples.len();

            if avg_memory > self.config.memory_threshold {
                // Reduce quality
                let reduction = self.config.adjustment_rate;
                self.current_quality = (self.current_quality - reduction)
                    .clamp(self.config.min_quality, self.config.max_quality);
            } else if avg_memory < self.config.memory_threshold / 2 {
                // Increase quality if there's headroom
                let increase = self.config.adjustment_rate / 2.0;
                self.current_quality = (self.current_quality + increase)
                    .clamp(self.config.min_quality, self.config.max_quality);
            }
        }

        /// Adjusts quality based on latency.
        fn adjust_for_latency(&mut self) {
            if self.latency_samples.is_empty() {
                return;
            }

            let avg_latency: u64 =
                self.latency_samples.iter().sum::<u64>() / self.latency_samples.len() as u64;

            if avg_latency > self.config.latency_threshold_ms {
                // Reduce quality for faster inference
                let reduction = self.config.adjustment_rate;
                self.current_quality = (self.current_quality - reduction)
                    .clamp(self.config.min_quality, self.config.max_quality);
            } else if avg_latency < self.config.latency_threshold_ms / 2 {
                // Increase quality if there's headroom
                let increase = self.config.adjustment_rate / 2.0;
                self.current_quality = (self.current_quality + increase)
                    .clamp(self.config.min_quality, self.config.max_quality);
            }
        }

        /// Returns current quality target.
        pub fn current_quality(&self) -> f32 {
            self.current_quality
        }

        /// Sets quality target directly.
        pub fn set_quality(&mut self, quality: f32) {
            self.current_quality = quality.clamp(self.config.min_quality, self.config.max_quality);
        }

        /// Returns statistics about quality management.
        pub fn stats(&self) -> AdaptiveQualityStats {
            let avg_memory = if self.memory_samples.is_empty() {
                0
            } else {
                self.memory_samples.iter().sum::<usize>() / self.memory_samples.len()
            };

            let avg_latency = if self.latency_samples.is_empty() {
                0
            } else {
                self.latency_samples.iter().sum::<u64>() / self.latency_samples.len() as u64
            };

            AdaptiveQualityStats {
                policy: self.config.policy,
                current_quality: self.current_quality,
                min_quality: self.config.min_quality,
                max_quality: self.config.max_quality,
                avg_memory_usage: avg_memory,
                avg_latency_ms: avg_latency,
                layer_target_count: self.layer_targets.len(),
            }
        }
    }

    /// Statistics for adaptive quality.
    #[derive(Debug, Clone)]
    pub struct AdaptiveQualityStats {
        /// Current quality policy.
        pub policy: QualityPolicy,
        /// Current quality target.
        pub current_quality: f32,
        /// Minimum allowed quality.
        pub min_quality: f32,
        /// Maximum allowed quality.
        pub max_quality: f32,
        /// Average memory usage (bytes).
        pub avg_memory_usage: usize,
        /// Average latency (ms).
        pub avg_latency_ms: u64,
        /// Number of layer-specific targets.
        pub layer_target_count: usize,
    }

    // ==================== Hot Reload Support ====================

    /// Hot-reload controller for progressive quality improvement.
    ///
    /// Allows loading initial low-quality weights for fast startup,
    /// then progressively improving quality in the background.
    pub struct HotReloadController {
        ctx: GpuHoloContext,
        header: HoloTensorHeader,
        accumulator: AccumulatorState,
        /// Current quality level.
        current_quality: f32,
        /// Fragments loaded so far.
        fragments_loaded: u16,
        /// Whether initial reconstruction is done.
        initial_ready: bool,
        /// Minimum quality for initial readiness.
        initial_threshold: f32,
    }

    impl HotReloadController {
        /// Creates a new hot-reload controller.
        pub fn new(
            ctx: GpuHoloContext,
            header: HoloTensorHeader,
            initial_threshold: f32,
        ) -> Result<Self, GpuHoloError> {
            let accumulator = ctx.create_accumulator(&header)?;

            Ok(Self {
                ctx,
                header,
                accumulator,
                current_quality: 0.0,
                fragments_loaded: 0,
                initial_ready: false,
                initial_threshold,
            })
        }

        /// Adds a fragment and returns whether quality improved.
        ///
        /// Returns (new_quality, quality_improved).
        pub fn add_fragment(
            &mut self,
            fragment: &HoloFragment,
        ) -> Result<(f32, bool), GpuHoloError> {
            self.ctx
                .accumulate_fragment(fragment, &mut self.accumulator, self.header.encoding)?;
            self.fragments_loaded += 1;

            let new_quality = self
                .header
                .quality_curve
                .predict(self.fragments_loaded, self.header.total_fragments);
            let improved = new_quality > self.current_quality;
            self.current_quality = new_quality;

            if !self.initial_ready && new_quality >= self.initial_threshold {
                self.initial_ready = true;
            }

            Ok((new_quality, improved))
        }

        /// Checks if initial quality threshold is met.
        pub fn is_ready(&self) -> bool {
            self.initial_ready
        }

        /// Returns current quality.
        pub fn quality(&self) -> f32 {
            self.current_quality
        }

        /// Returns number of fragments loaded.
        pub fn fragments_loaded(&self) -> u16 {
            self.fragments_loaded
        }

        /// Reconstructs current state.
        ///
        /// Can be called multiple times as quality improves.
        pub fn reconstruct(&self) -> Result<CudaSlice<f32>, GpuHoloError> {
            if self.fragments_loaded < self.header.quality_curve.min_fragments {
                return Err(GpuHoloError::InsufficientFragments {
                    min_required: self.header.quality_curve.min_fragments,
                    available: self.fragments_loaded,
                });
            }

            self.ctx
                .finalize_reconstruction(&self.accumulator, self.header.encoding)
        }

        /// Returns statistics.
        pub fn stats(&self) -> HotReloadStats {
            HotReloadStats {
                fragments_loaded: self.fragments_loaded,
                total_fragments: self.header.total_fragments,
                current_quality: self.current_quality,
                initial_threshold: self.initial_threshold,
                is_ready: self.initial_ready,
            }
        }
    }

    /// Statistics for hot reload.
    #[derive(Debug, Clone)]
    pub struct HotReloadStats {
        /// Fragments loaded so far.
        pub fragments_loaded: u16,
        /// Total fragments available.
        pub total_fragments: u16,
        /// Current quality level.
        pub current_quality: f32,
        /// Threshold for initial readiness.
        pub initial_threshold: f32,
        /// Whether initial threshold is met.
        pub is_ready: bool,
    }
}

/// Stub for non-CUDA builds.
#[cfg(not(feature = "cuda"))]
pub mod cuda {
    /// Placeholder error for non-CUDA builds.
    #[derive(Debug, thiserror::Error)]
    pub enum GpuHoloError {
        /// CUDA support is not enabled.
        #[error("CUDA support not enabled")]
        CudaNotEnabled,
    }

    /// Placeholder context for non-CUDA builds.
    pub struct GpuHoloContext;

    impl GpuHoloContext {
        /// Creates a new context (always fails without CUDA).
        pub fn new(_device_id: usize) -> Result<Self, GpuHoloError> {
            Err(GpuHoloError::CudaNotEnabled)
        }
    }

    /// Placeholder streaming context for non-CUDA builds.
    pub struct StreamingHoloContext;

    impl StreamingHoloContext {
        /// Creates a new streaming context (always fails without CUDA).
        pub fn new(_device_id: usize, _pipeline_depth: usize) -> Result<Self, GpuHoloError> {
            Err(GpuHoloError::CudaNotEnabled)
        }
    }

    /// Placeholder stream pool for non-CUDA builds.
    pub struct HoloStreamPool;

    /// Placeholder statistics for non-CUDA builds.
    #[derive(Debug, Clone)]
    pub struct StreamingHoloStats {
        /// Pipeline depth used
        pub pipeline_depth: usize,
        /// Number of CUDA streams
        pub num_streams: usize,
    }
}

// ==================== Phase 4: gpu_holo Tests ====================
// Trust boundary ยง6 (HoloTensor Reconstruction) from GPU-CODEC-PIPELINE-TDD.md.

#[cfg(test)]
mod tests {
    use super::cuda::*;
    #[cfg(feature = "cuda")]
    use cudarc::driver::LaunchAsync;

    /// Stub test: non-CUDA build returns CudaNotEnabled.
    #[test]
    #[cfg(not(feature = "cuda"))]
    fn test_holo_context_stub_not_enabled() {
        match GpuHoloContext::new(0) {
            Err(GpuHoloError::CudaNotEnabled) => {},
            other => panic!("Expected CudaNotEnabled, got {:?}", other.err()),
        }
    }

    /// Stub test: StreamingHoloContext non-CUDA build returns CudaNotEnabled.
    #[test]
    #[cfg(not(feature = "cuda"))]
    fn test_streaming_holo_context_stub_not_enabled() {
        match StreamingHoloContext::new(0, 2) {
            Err(GpuHoloError::CudaNotEnabled) => {},
            other => panic!("Expected CudaNotEnabled, got {:?}", other.err()),
        }
    }

    /// CUDA: context creation succeeds with valid device.
    #[test]
    #[cfg(feature = "cuda")]
    fn test_holo_context_creation() {
        match GpuHoloContext::new(0) {
            Ok(ctx) => {
                assert_eq!(ctx.device_id(), 0);
            },
            Err(GpuHoloError::DeviceInit { .. }) => {
                eprintln!("Skipping: no CUDA device available");
            },
            Err(e) => panic!("Unexpected error: {:?}", e),
        }
    }

    /// CUDA: spectral kernel loading.
    #[test]
    #[cfg(feature = "cuda")]
    fn test_holo_spectral_kernel_load() {
        let mut ctx = match GpuHoloContext::new(0) {
            Ok(ctx) => ctx,
            Err(_) => {
                eprintln!("Skipping: no CUDA device available");
                return;
            },
        };

        ctx.load_spectral_kernel()
            .expect("spectral kernel should load");
        // Second load should be idempotent
        ctx.load_spectral_kernel()
            .expect("second load should succeed");
    }

    /// CUDA: RPH kernel loading.
    #[test]
    #[cfg(feature = "cuda")]
    fn test_holo_rph_kernel_load() {
        let mut ctx = match GpuHoloContext::new(0) {
            Ok(ctx) => ctx,
            Err(_) => {
                eprintln!("Skipping: no CUDA device available");
                return;
            },
        };

        ctx.load_rph_kernel().expect("RPH kernel should load");
    }

    /// CUDA: LRDF kernel loading.
    #[test]
    #[cfg(feature = "cuda")]
    fn test_holo_lrdf_kernel_load() {
        let mut ctx = match GpuHoloContext::new(0) {
            Ok(ctx) => ctx,
            Err(_) => {
                eprintln!("Skipping: no CUDA device available");
                return;
            },
        };

        ctx.load_lrdf_kernel().expect("LRDF kernel should load");
    }

    /// CUDA: invalid device ID returns error.
    #[test]
    #[cfg(feature = "cuda")]
    fn test_holo_invalid_device() {
        let result = GpuHoloContext::new(999);
        assert!(result.is_err(), "Device 999 should not exist");
    }

    /// CUDA: KernelConfig defaults are sane.
    #[test]
    #[cfg(feature = "cuda")]
    fn test_holo_kernel_config_defaults() {
        let ctx = match GpuHoloContext::new(0) {
            Ok(ctx) => ctx,
            Err(_) => {
                eprintln!("Skipping: no CUDA device available");
                return;
            },
        };

        let config = ctx.kernel_config();
        // Block dimensions should be reasonable (> 0 and <= 1024)
        assert!(
            config.block_size_1d > 0 && config.block_size_1d <= 1024,
            "1D block size should be 1-1024, got {}",
            config.block_size_1d
        );
        assert!(
            config.block_size_2d > 0 && config.block_size_2d <= 32,
            "2D block size should be 1-32, got {}",
            config.block_size_2d
        );
    }

    // ==================== TDD Phase 4: HoloTensor Reconstruction Tests ====================
    // GPU-CODEC-PIPELINE-TDD.md ยง6.1-6.5

    /// Helper to build an LRDF fragment with one rank-1 SVD component.
    /// Format: [rows: u32][cols: u32][num_components: u32][sigma: f32][u: f32*rows][v: f32*cols]
    #[cfg(feature = "cuda")]
    fn make_lrdf_fragment(
        index: u16,
        rows: usize,
        cols: usize,
        sigma: f32,
        u: &[f32],
        v: &[f32],
    ) -> haagenti::holotensor::HoloFragment {
        assert_eq!(u.len(), rows);
        assert_eq!(v.len(), cols);
        let mut data = Vec::new();
        data.extend_from_slice(&(rows as u32).to_le_bytes());
        data.extend_from_slice(&(cols as u32).to_le_bytes());
        data.extend_from_slice(&1u32.to_le_bytes()); // 1 component
        data.extend_from_slice(&sigma.to_le_bytes());
        for &val in u {
            data.extend_from_slice(&val.to_le_bytes());
        }
        for &val in v {
            data.extend_from_slice(&val.to_le_bytes());
        }
        haagenti::holotensor::HoloFragment::new(index, data)
    }

    /// ยง6.2: LRDF rank-1 outer product reconstruction.
    ///
    /// A single fragment with one component: sigma * u * v^T.
    /// Verifies GPU reconstruction matches the expected outer product.
    #[test]
    #[cfg(feature = "cuda")]
    fn test_lrdf_rank1_reconstruction() {
        let mut ctx = match GpuHoloContext::new(0) {
            Ok(ctx) => ctx,
            Err(_) => {
                eprintln!("Skipping: no CUDA device available");
                return;
            },
        };
        ctx.load_lrdf_kernel().expect("LRDF kernel should load");

        let rows = 3;
        let cols = 2;
        let u = vec![1.0f32, 2.0, 3.0];
        let v = vec![4.0f32, 5.0];
        let sigma = 2.0f32;

        let fragment = make_lrdf_fragment(0, rows, cols, sigma, &u, &v);

        // Build header
        let header = haagenti::holotensor::HoloTensorHeader::new(
            haagenti::holotensor::HolographicEncoding::LowRankDistributed,
            haagenti::DType::F32,
            vec![rows as u64, cols as u64],
            1, // total fragments
        );

        // Reconstruct
        let gpu_result = ctx.reconstruct(&header, &[fragment]).unwrap();
        let host = ctx.copy_to_host(&gpu_result).unwrap();

        // Expected: sigma * u_i * v_j (row-major)
        let expected = vec![
            2.0 * 1.0 * 4.0,
            2.0 * 1.0 * 5.0, // row 0: 8, 10
            2.0 * 2.0 * 4.0,
            2.0 * 2.0 * 5.0, // row 1: 16, 20
            2.0 * 3.0 * 4.0,
            2.0 * 3.0 * 5.0, // row 2: 24, 30
        ];

        assert_eq!(host.len(), expected.len());
        for (i, (e, g)) in expected.iter().zip(host.iter()).enumerate() {
            assert!(
                (e - g).abs() < 1e-4,
                "LRDF rank-1 mismatch at {}: expected={}, got={}",
                i,
                e,
                g
            );
        }
    }

    /// ยง6.2: LRDF multi-component reconstruction (2 rank-1 terms).
    ///
    /// Two fragments each contributing one rank-1 component.
    /// Result should be sigma1 * u1 * v1^T + sigma2 * u2 * v2^T.
    #[test]
    #[cfg(feature = "cuda")]
    fn test_lrdf_multi_component_reconstruction() {
        let mut ctx = match GpuHoloContext::new(0) {
            Ok(ctx) => ctx,
            Err(_) => {
                eprintln!("Skipping: no CUDA device available");
                return;
            },
        };
        ctx.load_lrdf_kernel().expect("LRDF kernel should load");

        let rows = 2;
        let cols = 2;

        // Component 1: 1.0 * [1, 0] * [1, 0]^T = [[1, 0], [0, 0]]
        let frag0 = make_lrdf_fragment(0, rows, cols, 1.0, &[1.0, 0.0], &[1.0, 0.0]);
        // Component 2: 1.0 * [0, 1] * [0, 1]^T = [[0, 0], [0, 1]]
        let frag1 = make_lrdf_fragment(1, rows, cols, 1.0, &[0.0, 1.0], &[0.0, 1.0]);

        let header = haagenti::holotensor::HoloTensorHeader::new(
            haagenti::holotensor::HolographicEncoding::LowRankDistributed,
            haagenti::DType::F32,
            vec![rows as u64, cols as u64],
            2,
        );

        let gpu_result = ctx.reconstruct(&header, &[frag0, frag1]).unwrap();
        let host = ctx.copy_to_host(&gpu_result).unwrap();

        // Expected: identity matrix [[1, 0], [0, 1]]
        let expected = vec![1.0, 0.0, 0.0, 1.0];

        assert_eq!(host.len(), expected.len());
        for (i, (e, g)) in expected.iter().zip(host.iter()).enumerate() {
            assert!(
                (e - g).abs() < 1e-4,
                "LRDF multi-comp mismatch at {}: expected={}, got={}",
                i,
                e,
                g
            );
        }
    }

    /// ยง6.5: F32 โ†’ F16 conversion kernel correctness.
    #[test]
    #[cfg(feature = "cuda")]
    fn test_holo_f32_to_f16_conversion() {
        let mut ctx = match GpuHoloContext::new(0) {
            Ok(ctx) => ctx,
            Err(_) => {
                eprintln!("Skipping: no CUDA device available");
                return;
            },
        };
        ctx.load_fused_kernel().expect("fused kernel should load");

        let input = vec![1.0f32, 0.5, -1.0, 0.0, 100.0, -0.001];
        let d_input = ctx.device().htod_copy(input.clone()).unwrap();

        let d_output = ctx.convert_f32_to_f16(&d_input).unwrap();

        let mut host_f16 = vec![half::f16::ZERO; input.len()];
        ctx.device()
            .dtoh_sync_copy_into(&d_output, &mut host_f16)
            .unwrap();

        for (i, (&f32_val, &f16_val)) in input.iter().zip(host_f16.iter()).enumerate() {
            let expected = half::f16::from_f32(f32_val);
            assert_eq!(
                f16_val.to_bits(),
                expected.to_bits(),
                "F32โ†’F16 wrong at {}: input={}, got=0x{:04X}, expected=0x{:04X}",
                i,
                f32_val,
                f16_val.to_bits(),
                expected.to_bits()
            );
        }
    }

    /// ยง6.5: scale_values utility kernel.
    #[test]
    #[cfg(feature = "cuda")]
    fn test_holo_scale_values() {
        let mut ctx = match GpuHoloContext::new(0) {
            Ok(ctx) => ctx,
            Err(_) => {
                eprintln!("Skipping: no CUDA device available");
                return;
            },
        };
        ctx.load_fused_kernel().expect("fused kernel should load");

        let data = vec![1.0f32, 2.0, 3.0, 4.0];
        let mut d_data = ctx.device().htod_copy(data.clone()).unwrap();

        ctx.scale_values(&mut d_data, 0.5).unwrap();

        let mut host = vec![0.0f32; data.len()];
        ctx.device()
            .dtoh_sync_copy_into(&d_data, &mut host)
            .unwrap();

        let expected = vec![0.5, 1.0, 1.5, 2.0];
        for (i, (e, g)) in expected.iter().zip(host.iter()).enumerate() {
            assert!(
                (e - g).abs() < 1e-6,
                "Scale mismatch at {}: expected={}, got={}",
                i,
                e,
                g
            );
        }
    }

    /// ยง6.2: LRDF convenience reconstruct_lrdf produces correct GpuTensor.
    #[test]
    #[cfg(feature = "cuda")]
    fn test_lrdf_convenience_reconstruct() {
        let mut ctx = match GpuHoloContext::new(0) {
            Ok(ctx) => ctx,
            Err(_) => {
                eprintln!("Skipping: no CUDA device available");
                return;
            },
        };
        ctx.load_lrdf_kernel().expect("LRDF kernel should load");

        let rows = 4;
        let cols = 4;
        // Identity-like: sigma=1 for each basis vector pair
        let frag = make_lrdf_fragment(
            0,
            rows,
            cols,
            1.0,
            &[1.0, 1.0, 1.0, 1.0],
            &[1.0, 1.0, 1.0, 1.0],
        );

        let tensor = ctx.reconstruct_lrdf(&[frag], rows, cols).unwrap();

        assert_eq!(tensor.rows(), rows);
        assert_eq!(tensor.cols(), cols);
        assert_eq!(tensor.len(), rows * cols);

        let host = tensor.to_host().unwrap();
        // All 1s outer product: every element should be 1.0
        for (i, &val) in host.iter().enumerate() {
            assert!(
                (val - 1.0).abs() < 1e-4,
                "reconstruct_lrdf all-ones mismatch at {}: got={}",
                i,
                val
            );
        }
    }

    // ==================== Phase 5: ยงL4 LRDF Batched Outer Product ====================

    /// Helper to build a multi-component LRDF fragment.
    /// Format: [rows: u32][cols: u32][num_components: u32]([sigma: f32][u: f32*rows][v: f32*cols])*
    #[cfg(feature = "cuda")]
    fn make_lrdf_multi_fragment(
        index: u16,
        rows: usize,
        cols: usize,
        components: &[(f32, Vec<f32>, Vec<f32>)], // [(sigma, u, v), ...]
    ) -> haagenti::holotensor::HoloFragment {
        let mut data = Vec::new();
        data.extend_from_slice(&(rows as u32).to_le_bytes());
        data.extend_from_slice(&(cols as u32).to_le_bytes());
        data.extend_from_slice(&(components.len() as u32).to_le_bytes());
        for (sigma, u, v) in components {
            assert_eq!(u.len(), rows);
            assert_eq!(v.len(), cols);
            data.extend_from_slice(&sigma.to_le_bytes());
            for &val in u {
                data.extend_from_slice(&val.to_le_bytes());
            }
            for &val in v {
                data.extend_from_slice(&val.to_le_bytes());
            }
        }
        haagenti::holotensor::HoloFragment::new(index, data)
    }

    /// ยงL4.1: Single-component batched matches unbatched single outer product.
    #[test]
    #[cfg(feature = "cuda")]
    fn test_lrdf_batched_single_matches_unbatched() {
        let mut ctx = match GpuHoloContext::new(0) {
            Ok(ctx) => ctx,
            Err(_) => {
                eprintln!("Skipping: no CUDA device available");
                return;
            },
        };
        ctx.load_lrdf_kernel().expect("LRDF kernel should load");

        let rows = 4;
        let cols = 3;
        let sigma = 2.5f32;
        let u = vec![1.0, 0.5, 0.25, 0.125];
        let v = vec![0.3, 0.6, 0.9];

        // Unbatched: single outer product
        let frag_single = make_lrdf_fragment(0, rows, cols, sigma, &u, &v);
        let header = haagenti::holotensor::HoloTensorHeader::new(
            haagenti::holotensor::HolographicEncoding::LowRankDistributed,
            haagenti::DType::F32,
            vec![rows as u64, cols as u64],
            1,
        );
        let mut acc_single = ctx.create_accumulator(&header).unwrap();
        ctx.accumulate_lrdf(&frag_single, &mut acc_single).unwrap();
        let result_single = ctx.finalize_lrdf(&acc_single).unwrap();
        let host_single = ctx.copy_to_host(&result_single).unwrap();

        // Batched: same data through batched path
        let frag_batched = make_lrdf_multi_fragment(0, rows, cols, &[(sigma, u, v)]);
        let mut acc_batched = ctx.create_accumulator(&header).unwrap();
        ctx.accumulate_lrdf_batched(&frag_batched, &mut acc_batched)
            .unwrap();
        let result_batched = ctx.finalize_lrdf(&acc_batched).unwrap();
        let host_batched = ctx.copy_to_host(&result_batched).unwrap();

        assert_eq!(host_single.len(), host_batched.len());
        for (i, (&s, &b)) in host_single.iter().zip(host_batched.iter()).enumerate() {
            assert!(
                (s - b).abs() < 1e-5,
                "Batched vs unbatched mismatch at {}: single={}, batched={}",
                i,
                s,
                b
            );
        }
    }

    /// ยงL4.2: Multi-component batched matches sequential single calls.
    #[test]
    #[cfg(feature = "cuda")]
    fn test_lrdf_batched_multi_matches_sequential() {
        let mut ctx = match GpuHoloContext::new(0) {
            Ok(ctx) => ctx,
            Err(_) => {
                eprintln!("Skipping: no CUDA device available");
                return;
            },
        };
        ctx.load_lrdf_kernel().expect("LRDF kernel should load");

        let rows = 4;
        let cols = 3;
        let components = vec![
            (2.0f32, vec![1.0, 0.0, 0.0, 0.0], vec![1.0, 0.0, 0.0]),
            (1.5f32, vec![0.0, 1.0, 0.0, 0.0], vec![0.0, 1.0, 0.0]),
            (0.8f32, vec![0.0, 0.0, 1.0, 0.0], vec![0.0, 0.0, 1.0]),
        ];

        let header = haagenti::holotensor::HoloTensorHeader::new(
            haagenti::holotensor::HolographicEncoding::LowRankDistributed,
            haagenti::DType::F32,
            vec![rows as u64, cols as u64],
            1,
        );

        // Sequential: 3 separate single-component fragments
        let mut acc_seq = ctx.create_accumulator(&header).unwrap();
        for (i, (sigma, ref u, ref v)) in components.iter().enumerate() {
            let frag = make_lrdf_fragment(i as u16, rows, cols, *sigma, u, v);
            ctx.accumulate_lrdf(&frag, &mut acc_seq).unwrap();
        }
        let result_seq = ctx.finalize_lrdf(&acc_seq).unwrap();
        let host_seq = ctx.copy_to_host(&result_seq).unwrap();

        // Batched: all 3 components in single fragment
        let frag_batched = make_lrdf_multi_fragment(0, rows, cols, &components);
        let mut acc_batched = ctx.create_accumulator(&header).unwrap();
        ctx.accumulate_lrdf_batched(&frag_batched, &mut acc_batched)
            .unwrap();
        let result_batched = ctx.finalize_lrdf(&acc_batched).unwrap();
        let host_batched = ctx.copy_to_host(&result_batched).unwrap();

        assert_eq!(host_seq.len(), host_batched.len());
        for (i, (&s, &b)) in host_seq.iter().zip(host_batched.iter()).enumerate() {
            assert!(
                (s - b).abs() < 1e-5,
                "Batched vs sequential mismatch at {}: seq={}, batched={}",
                i,
                s,
                b
            );
        }

        // Verify expected values: diagonal-like pattern
        // output[0][0] = 2.0, output[1][1] = 1.5, output[2][2] = 0.8, rest ~0
        assert!(
            (host_batched[0] - 2.0).abs() < 1e-5,
            "Expected 2.0 at [0,0]"
        );
        assert!(
            (host_batched[4] - 1.5).abs() < 1e-5,
            "Expected 1.5 at [1,1]"
        );
        assert!(
            (host_batched[8] - 0.8).abs() < 1e-5,
            "Expected 0.8 at [2,2]"
        );
    }

    // ==================== Phase 4: ยง6.1 Spectral IDCT Reconstruction ====================
    // GPU-CODEC-PIPELINE-TDD.md ยง6.1: Spectral accumulation and IDCT reconstruction.

    /// Helper to build a legacy spectral fragment.
    /// Format: [num_coeffs: u32][indices: u32...][values: f32...]
    #[cfg(feature = "cuda")]
    fn make_spectral_fragment(
        frag_index: u16,
        coeffs: &[(u32, f32)],
    ) -> haagenti::holotensor::HoloFragment {
        let num_coeffs = coeffs.len() as u32;
        let mut data = Vec::new();
        data.extend_from_slice(&num_coeffs.to_le_bytes());
        for &(idx, _) in coeffs {
            data.extend_from_slice(&idx.to_le_bytes());
        }
        for &(_, val) in coeffs {
            data.extend_from_slice(&val.to_le_bytes());
        }
        haagenti::holotensor::HoloFragment::new(frag_index, data)
    }

    /// ยง6.1 + ยงS1.1: DC-only spectral coefficient accumulates correctly and
    /// reconstructs to a constant output.
    ///
    /// A single DC coefficient (index 0) should land at position 0 in the
    /// coefficient buffer with all other positions zero. Full reconstruction
    /// (accumulate โ†’ IDCT rows โ†’ IDCT cols) should produce a uniform constant
    /// equal to DC / sqrt(width) (for height=1, col IDCT is identity).
    #[test]
    #[cfg(feature = "cuda")]
    fn test_spectral_dc_only_produces_constant_output() {
        let mut ctx = match GpuHoloContext::new(0) {
            Ok(ctx) => ctx,
            Err(_) => {
                eprintln!("Skipping: no CUDA device available");
                return;
            },
        };
        ctx.load_spectral_kernel()
            .expect("spectral kernel should load");

        let width = 8;
        let height = 1;
        let dc_value = 4.0f32;

        let fragment = make_spectral_fragment(0, &[(0, dc_value)]);

        let header = haagenti::holotensor::HoloTensorHeader::new(
            haagenti::holotensor::HolographicEncoding::Spectral,
            haagenti::DType::F32,
            vec![height as u64, width as u64],
            1,
        );

        // Accumulate and verify coefficients directly
        let mut accumulator = ctx.create_accumulator(&header).unwrap();
        ctx.accumulate_spectral(&fragment, &mut accumulator)
            .unwrap();

        if let AccumulatorState::Spectral {
            ref coefficients, ..
        } = accumulator
        {
            let host_coeffs = ctx.copy_to_host(coefficients).unwrap();
            assert_eq!(host_coeffs.len(), width * height);

            // DC coefficient at index 0 should equal the input value
            assert!(
                (host_coeffs[0] - dc_value).abs() < 1e-6,
                "DC coefficient: expected {}, got {}",
                dc_value,
                host_coeffs[0]
            );

            // All other positions should be zero
            for (i, &val) in host_coeffs[1..].iter().enumerate() {
                assert!(
                    val.abs() < 1e-6,
                    "Non-DC position {} should be 0, got {}",
                    i + 1,
                    val
                );
            }
        } else {
            panic!("Expected Spectral accumulator variant");
        }

        // Full reconstruction: DC-only IDCT should produce constant output.
        // For 1D (height=1): x[n] = DC * sqrt(2/N) * 1/sqrt(2) = DC / sqrt(N)
        let result = ctx.finalize_spectral(&accumulator).unwrap();
        let output = ctx.copy_to_host(&result).unwrap();
        let expected = dc_value / (width as f32).sqrt();
        for (i, &val) in output.iter().enumerate() {
            assert!(
                (val - expected).abs() < 1e-3,
                "DC reconstruction at {}: expected {:.6}, got {:.6}",
                i,
                expected,
                val
            );
        }
    }

    /// ยง6.1: Sparse spectral coefficients accumulate at correct indices.
    ///
    /// Verifies the accumulation kernel places coefficient values at the
    /// correct positions in the frequency buffer, with zeros elsewhere.
    #[test]
    #[cfg(feature = "cuda")]
    fn test_spectral_sparse_accumulation_correct_indices() {
        let mut ctx = match GpuHoloContext::new(0) {
            Ok(ctx) => ctx,
            Err(_) => {
                eprintln!("Skipping: no CUDA device available");
                return;
            },
        };
        ctx.load_spectral_kernel()
            .expect("spectral kernel should load");

        let width = 4;
        let height = 4;
        let total_size = width * height;

        let header = haagenti::holotensor::HoloTensorHeader::new(
            haagenti::holotensor::HolographicEncoding::Spectral,
            haagenti::DType::F32,
            vec![height as u64, width as u64],
            1,
        );

        // Create accumulator and accumulate a sparse fragment
        let mut accumulator = ctx.create_accumulator(&header).unwrap();
        let coeffs = [(0u32, 1.0f32), (3, 2.0), (7, 3.0), (15, 4.0)];
        let fragment = make_spectral_fragment(0, &coeffs);
        ctx.accumulate_spectral(&fragment, &mut accumulator)
            .unwrap();

        // Read back coefficient buffer from accumulator
        if let AccumulatorState::Spectral {
            ref coefficients, ..
        } = accumulator
        {
            let host_coeffs = ctx.copy_to_host(coefficients).unwrap();
            assert_eq!(host_coeffs.len(), total_size);

            // Indexed positions should have the accumulated values
            assert!(
                (host_coeffs[0] - 1.0).abs() < 1e-6,
                "Index 0: expected 1.0, got {}",
                host_coeffs[0]
            );
            assert!(
                (host_coeffs[3] - 2.0).abs() < 1e-6,
                "Index 3: expected 2.0, got {}",
                host_coeffs[3]
            );
            assert!(
                (host_coeffs[7] - 3.0).abs() < 1e-6,
                "Index 7: expected 3.0, got {}",
                host_coeffs[7]
            );
            assert!(
                (host_coeffs[15] - 4.0).abs() < 1e-6,
                "Index 15: expected 4.0, got {}",
                host_coeffs[15]
            );

            // All non-indexed positions should be zero
            for (i, &val) in host_coeffs.iter().enumerate() {
                if ![0, 3, 7, 15].contains(&i) {
                    assert!(
                        val.abs() < 1e-6,
                        "Non-indexed position {} should be 0, got {}",
                        i,
                        val
                    );
                }
            }
        } else {
            panic!("Expected Spectral accumulator variant");
        }
    }

    // ==================== DD-8 ยงS1.2: Single AC Coefficient Row IDCT ====================

    /// ยงS1.2: A single AC coefficient at index k produces a cosine wave.
    /// x[n] = amplitude * sqrt(2/N) * cos(ฯ€(2n+1)k / 2N)
    #[test]
    #[cfg(feature = "cuda")]
    fn test_idct_1d_rows_single_ac() {
        let mut ctx = match GpuHoloContext::new(0) {
            Ok(ctx) => ctx,
            Err(_) => {
                eprintln!("Skipping: no CUDA device available");
                return;
            },
        };
        ctx.load_spectral_kernel()
            .expect("spectral kernel should load");

        let width = 8;
        let height = 1;
        let k = 1usize; // First AC frequency
        let amplitude = 3.0f32;

        // Create coefficient buffer with single AC at index k
        let mut coeffs = vec![0.0f32; width * height];
        coeffs[k] = amplitude;

        // Upload and run row IDCT directly
        let d_input = ctx.device().htod_copy(coeffs).unwrap();
        let d_output: cudarc::driver::CudaSlice<f32> =
            ctx.device().alloc_zeros(width * height).unwrap();

        let func = ctx
            .device()
            .get_func("holo_spectral", "holo_spectral_idct_1d_rows")
            .unwrap();
        let cfg = cudarc::driver::LaunchConfig {
            grid_dim: (1, 1, 1),
            block_dim: (256, 1, 1),
            shared_mem_bytes: (width * 4) as u32,
        };
        unsafe { func.launch(cfg, (&d_input, &d_output, width as u32, height as u32)) }.unwrap();
        ctx.device().synchronize().unwrap();

        let host = ctx.copy_to_host(&d_output).unwrap();
        let scale = (2.0 / width as f32).sqrt();
        let pi_2n = std::f32::consts::PI / (2.0 * width as f32);

        for n in 0..width {
            let expected = amplitude * scale * ((2 * n + 1) as f32 * k as f32 * pi_2n).cos();
            assert!(
                (host[n] - expected).abs() < 1e-3,
                "AC[{}] row IDCT at {}: expected {:.6}, got {:.6}",
                k,
                n,
                expected,
                host[n]
            );
        }
    }

    // ==================== DD-8 ยงS2.3: End-to-End 2D IDCT ====================

    /// ยงS2.3: Full 2D IDCT pipeline โ€” accumulate DCT coefficients, finalize,
    /// compare with CPU reference (`haagenti_core::dct::idct_1d_direct`).
    ///
    /// Uses a known 4ร—4 spatial signal โ†’ DCT-II โ†’ GPU IDCT โ†’ compare.
    #[test]
    #[cfg(feature = "cuda")]
    fn test_spectral_2d_idct_end_to_end() {
        let mut ctx = match GpuHoloContext::new(0) {
            Ok(ctx) => ctx,
            Err(_) => {
                eprintln!("Skipping: no CUDA device available");
                return;
            },
        };
        ctx.load_spectral_kernel()
            .expect("spectral kernel should load");

        let width = 4;
        let height = 4;

        // Known spatial signal
        let spatial: Vec<f32> = (0..width * height)
            .map(|i| (i as f32 * 0.3).sin())
            .collect();

        // Compute DCT-II coefficients using CPU reference
        let mut dct_coeffs = vec![0.0f32; width * height];
        haagenti_core::dct::dct_2d(&spatial, &mut dct_coeffs, width, height);

        // Build spectral fragments from all non-zero coefficients
        let mut coeff_pairs: Vec<(u32, f32)> = Vec::new();
        for (i, &c) in dct_coeffs.iter().enumerate() {
            if c.abs() > 1e-10 {
                coeff_pairs.push((i as u32, c));
            }
        }
        let fragment = make_spectral_fragment(0, &coeff_pairs);

        let header = haagenti::holotensor::HoloTensorHeader::new(
            haagenti::holotensor::HolographicEncoding::Spectral,
            haagenti::DType::F32,
            vec![height as u64, width as u64],
            1,
        );

        // GPU reconstruction
        let mut acc = ctx.create_accumulator(&header).unwrap();
        ctx.accumulate_spectral(&fragment, &mut acc).unwrap();
        let result = ctx.finalize_spectral(&acc).unwrap();
        let gpu_output = ctx.copy_to_host(&result).unwrap();

        // CPU reference IDCT for comparison
        let mut cpu_output = vec![0.0f32; width * height];
        haagenti_core::dct::idct_2d(&dct_coeffs, &mut cpu_output, width, height);

        for (i, (&orig, &recon)) in cpu_output.iter().zip(gpu_output.iter()).enumerate() {
            assert!(
                (orig - recon).abs() < 1e-2,
                "2D IDCT at {}: cpu_reference={:.6}, gpu={:.6}, diff={:.6}",
                i,
                orig,
                recon,
                (orig - recon).abs()
            );
        }
    }

    // ==================== DD-8 ยงS1.3: GPU vs CPU Proptest ====================

    #[cfg(feature = "cuda")]
    mod idct_proptest {
        use super::*;
        use proptest::prelude::*;

        proptest! {
            #![proptest_config(ProptestConfig::with_cases(20))]
            #[test]
            fn gpu_idct_2d_matches_cpu_reference(
                dim in prop::sample::select(vec![4usize, 8]),
                coeffs_raw in proptest::collection::vec(-5.0f32..5.0f32, 64),
            ) {
                let mut ctx = match GpuHoloContext::new(0) {
                    Ok(ctx) => ctx,
                    Err(_) => { return Ok(()); }
                };
                ctx.load_spectral_kernel().unwrap();

                let width = dim;
                let height = dim;
                let total = width * height;
                let coeffs: Vec<f32> = coeffs_raw[..total].to_vec();

                // CPU reference
                let mut cpu_output = vec![0.0f32; total];
                haagenti_core::dct::idct_2d(&coeffs, &mut cpu_output, width, height);

                // GPU: upload coefficients directly, run finalize_spectral_direct
                let d_coeffs = ctx.device().htod_copy(coeffs).unwrap();

                // Create spectral accumulator and inject coefficients directly
                let acc = AccumulatorState::Spectral {
                    coefficients: d_coeffs,
                    present_mask: ctx.device().alloc_zeros(total).unwrap(),
                    width,
                    height,
                };
                let result = ctx.finalize_spectral(&acc).unwrap();
                let gpu_output = ctx.copy_to_host(&result).unwrap();

                for (i, (&cpu, &gpu)) in cpu_output.iter().zip(gpu_output.iter()).enumerate() {
                    prop_assert!(
                        (cpu - gpu).abs() < 0.05,
                        "IDCT 2D mismatch at {}: cpu={:.6}, gpu={:.6}, diff={:.6}",
                        i, cpu, gpu, (cpu - gpu).abs()
                    );
                }
            }
        }
    }

    // ==================== Phase 4: ยง6.3 RPH Determinism ====================
    // GPU-CODEC-PIPELINE-TDD.md ยง6.3: Same seed produces same output.

    /// Helper to build an RPH fragment.
    /// Format: [proj_dim: u32][seed_offset: u64][projection: f32...]
    #[cfg(feature = "cuda")]
    fn make_rph_fragment(
        frag_index: u16,
        proj_dim: usize,
        seed_offset: u64,
        projection: &[f32],
    ) -> haagenti::holotensor::HoloFragment {
        assert_eq!(projection.len(), proj_dim);
        let mut data = Vec::new();
        data.extend_from_slice(&(proj_dim as u32).to_le_bytes());
        data.extend_from_slice(&seed_offset.to_le_bytes());
        for &val in projection {
            data.extend_from_slice(&val.to_le_bytes());
        }
        haagenti::holotensor::HoloFragment::new(frag_index, data)
    }

    /// ยงR2.2 + ยงR2.3: RPH reconstruction produces non-zero output and is deterministic.
    ///
    /// Two runs of accumulate+finalize with identical inputs (same header, same seed,
    /// same fragments) must produce bit-identical, non-zero outputs.
    #[test]
    #[cfg(feature = "cuda")]
    fn test_rph_deterministic_same_seed() {
        let mut ctx = match GpuHoloContext::new(0) {
            Ok(ctx) => ctx,
            Err(_) => {
                eprintln!("Skipping: no CUDA device available");
                return;
            },
        };
        ctx.load_rph_kernel().expect("RPH kernel should load");

        let proj_dim = 8;
        let projection: Vec<f32> = (0..proj_dim).map(|i| (i as f32 + 1.0) * 0.5).collect();

        let header = haagenti::holotensor::HoloTensorHeader::new(
            haagenti::holotensor::HolographicEncoding::RandomProjection,
            haagenti::DType::F32,
            vec![4, 4], // 4x4 = 16 output elements
            1,
        );

        // First run: accumulate + finalize
        let frag1 = make_rph_fragment(0, proj_dim, 42, &projection);
        let mut acc1 = ctx.create_accumulator(&header).unwrap();
        ctx.accumulate_rph(&frag1, &mut acc1).unwrap();
        let result1 = ctx.finalize_rph(&acc1).unwrap();
        let host1 = ctx.copy_to_host(&result1).unwrap();

        // Second run with identical inputs
        let frag2 = make_rph_fragment(0, proj_dim, 42, &projection);
        let mut acc2 = ctx.create_accumulator(&header).unwrap();
        ctx.accumulate_rph(&frag2, &mut acc2).unwrap();
        let result2 = ctx.finalize_rph(&acc2).unwrap();
        let host2 = ctx.copy_to_host(&result2).unwrap();

        assert_eq!(host1.len(), host2.len(), "Output lengths must match");
        assert_eq!(host1.len(), 16, "Output should be 4x4 = 16 elements");

        // ยงR2.2: Output must be non-zero (XORShift PRNG fixed)
        assert!(
            host1.iter().any(|v| *v != 0.0),
            "RPH output should be non-zero after XORShift PRNG fix"
        );

        // ยงR2.3: Determinism โ€” bit-identical across runs
        for (i, (v1, v2)) in host1.iter().zip(host2.iter()).enumerate() {
            assert_eq!(
                v1.to_bits(),
                v2.to_bits(),
                "RPH determinism violation at {}: run1={}, run2={}",
                i,
                v1,
                v2
            );
        }
    }

    /// ยงR2.3: Different seeds produce different RPH output.
    #[test]
    #[cfg(feature = "cuda")]
    fn test_rph_different_seeds_diverge() {
        let mut ctx = match GpuHoloContext::new(0) {
            Ok(ctx) => ctx,
            Err(_) => {
                eprintln!("Skipping: no CUDA device available");
                return;
            },
        };
        ctx.load_rph_kernel().expect("RPH kernel should load");

        let proj_dim = 8;
        let projection: Vec<f32> = (0..proj_dim).map(|i| (i as f32 + 1.0) * 0.5).collect();

        let header = haagenti::holotensor::HoloTensorHeader::new(
            haagenti::holotensor::HolographicEncoding::RandomProjection,
            haagenti::DType::F32,
            vec![4, 4],
            1,
        );

        // Run with seed_offset=42
        let frag_a = make_rph_fragment(0, proj_dim, 42, &projection);
        let mut acc_a = ctx.create_accumulator(&header).unwrap();
        ctx.accumulate_rph(&frag_a, &mut acc_a).unwrap();
        let result_a = ctx.finalize_rph(&acc_a).unwrap();
        let host_a = ctx.copy_to_host(&result_a).unwrap();

        // Run with seed_offset=999
        let frag_b = make_rph_fragment(0, proj_dim, 999, &projection);
        let mut acc_b = ctx.create_accumulator(&header).unwrap();
        ctx.accumulate_rph(&frag_b, &mut acc_b).unwrap();
        let result_b = ctx.finalize_rph(&acc_b).unwrap();
        let host_b = ctx.copy_to_host(&result_b).unwrap();

        // Different seeds must produce different output
        let differs = host_a
            .iter()
            .zip(host_b.iter())
            .any(|(a, b)| a.to_bits() != b.to_bits());
        assert!(
            differs,
            "Different seed offsets should produce different RPH output"
        );
    }

    /// ยง6.3: RPH accumulate pipeline exercises fragment parsing and state tracking.
    ///
    /// Verifies the full RPH pipeline: fragment construction, kernel load,
    /// accumulation, and finalization all complete without error.
    /// The accumulator state (num_projections) is correctly incremented.
    #[test]
    #[cfg(feature = "cuda")]
    fn test_rph_accumulate_pipeline_state_tracking() {
        let mut ctx = match GpuHoloContext::new(0) {
            Ok(ctx) => ctx,
            Err(_) => {
                eprintln!("Skipping: no CUDA device available");
                return;
            },
        };
        ctx.load_rph_kernel().expect("RPH kernel should load");

        let frag_proj_dim = 8;
        let projection: Vec<f32> = (0..frag_proj_dim).map(|i| (i as f32 + 1.0) * 0.5).collect();

        let header = haagenti::holotensor::HoloTensorHeader::new(
            haagenti::holotensor::HolographicEncoding::RandomProjection,
            haagenti::DType::F32,
            vec![4, 4],
            1,
        );

        let mut acc = ctx.create_accumulator(&header).unwrap();

        // Verify initial state.
        // Accumulator proj_dim is compute_projection_dim(16) = max(sqrt(16), 16) = 16,
        // which differs from the fragment's proj_dim (8).
        if let AccumulatorState::RandomProjection {
            num_projections,
            proj_dim: pd,
            output_dim: od,
            ..
        } = &acc
        {
            assert_eq!(*num_projections, 0, "Initial num_projections should be 0");
            assert_eq!(*pd, 16, "proj_dim = max(sqrt(output_dim), 16) = 16");
            assert_eq!(*od, 16, "output_dim should be 4*4=16");
        } else {
            panic!("Expected RandomProjection accumulator");
        }

        // Accumulate two fragments with different seed_offsets
        let frag_a = make_rph_fragment(0, frag_proj_dim, 42, &projection);
        ctx.accumulate_rph(&frag_a, &mut acc).unwrap();

        if let AccumulatorState::RandomProjection {
            num_projections, ..
        } = &acc
        {
            assert_eq!(
                *num_projections, 1,
                "num_projections should be 1 after first accumulate"
            );
        }

        let frag_b = make_rph_fragment(1, frag_proj_dim, 999, &projection);
        ctx.accumulate_rph(&frag_b, &mut acc).unwrap();

        if let AccumulatorState::RandomProjection {
            num_projections, ..
        } = &acc
        {
            assert_eq!(
                *num_projections, 2,
                "num_projections should be 2 after second accumulate"
            );
        }

        // Finalize and verify output shape
        let result = ctx.finalize_rph(&acc).unwrap();
        let host = ctx.copy_to_host(&result).unwrap();
        assert_eq!(host.len(), 16, "Finalized output should be 4*4=16 elements");

        // After XORShift PRNG fix, output should be non-zero
        assert!(
            host.iter().any(|v| *v != 0.0),
            "RPH pipeline output should be non-zero after PRNG fix"
        );
    }
}

// Re-exports
pub use cuda::GpuHoloContext;
#[cfg(feature = "cuda")]
pub use cuda::GpuHoloError;
#[cfg(feature = "cuda")]
pub use cuda::HoloStreamPool;
pub use cuda::StreamingHoloContext;
#[cfg(feature = "cuda")]
pub use cuda::StreamingHoloStats;